class: center, middle, inverse, title-slide .title[ # ISA 419: Data-Driven Security ] .subtitle[ ## 02: Python Programming Basics ] .author[ ###
Fadel M. Megahed, PhD
Professor
Farmer School of Business
Miami University
@FadelMegahed
fmegahed
fmegahed@miamioh.edu
Automated Scheduler for Office Hours
] .date[ ### Fall 2025 ] --- ## Quick Refresher of Last Class ✅ Define **information security (Infosec)**, its **main goals**, and how it fits within a firm’s overall security protocols ✅ Describe the **three main steps** in information security: prevention, detection, and response. ✅ Explain why **prevention as a sole security measure is deemed to fail**. ✅ Describe **course structure**, **goals**, and **overview**. --- ## Learning Objectives for Today's Class - Use pseudocode to map out a problem. - Python syntax, data types, and data structures - Convert data types using type casting - Manipulate lists and use methods on lists --- class: inverse, center, middle # Use Pseudocode to Map out a Cybersecurity Problem --- ## Background: Why is BUS 104 is a Pre-Req? ### From the MU Bulletin > .bold[BUS 104. Introduction to Computational Thinking for Business. (2)] > As part of the Farmer School of Business first-year integrated core curriculum, this course introduces students to the fundamentals of computational thinking as an aid to data-driven business problem-solving. Topics include: computational thinking as **problem solving**, **representing data through abstractions**, and **thinking in terms of algorithms** (loops, conditions, reusable code, functions and events) to **automate finding solutions**. The course lays the foundations for students identifying, analyzing, and implementing solutions for data-driven business problems and the communication of results. .footnote[ <html> <hr> </html> **Source:** [Business Analysis (BUS) | Miami University Bulletin](https://bulletin.miamioh.edu/courses-instruction/bus/). ] --- ## Background: (Distributed) Denial of Service Attacks <center> <iframe width="810" height="472.5" src="https://www.youtube-nocookie.com/embed/bDAY-oUP0DQ?si=9RiVqrFSJdStTIeS" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe> </center> .footnote[ <html> <hr> </html> **Credits:** Jeff Crume. (2023) [IBM Technology: Denial of Service Attacks Explained](https://www.youtube.com/watch?v=bDAY-oUP0DQ). ] --- ## Simplifying our Task Ahead: SYN Flood Attacks - We will focus on the simple **SYN flood attack**. - Attackers send a succession of SYN requests to a target's system. <img src="data:image/png;base64,#../../figures/ibm_ddos_frame_grab.png" alt="A screen grab from the IBM video, demonstrating the SYN flood attack" width="75%" style="display: block; margin: auto;" /> .footnote[ <html> <hr> </html> **Image Source:** Captured from the Jeff Crume. (2023) [IBM Technology: Denial of Service Attacks Explained](https://www.youtube.com/watch?v=bDAY-oUP0DQ) video (~ the frame corresponding to 3:47). Then, the image was adjusted by: (a) removing the presenter's picture, and (b) adding a circle around the SYN attack. ] --- ## Class Activity: Detecting SYN Flood Attacks
−
+
10
:
00
.panelset[ .panel[.panel-name[Task] - Toward creating an algorithm for monitoring network traffic and detecting SYN flood attacks, in pairs, please think and answer the following questions. - Write down your answers in each tab, after each question. ] .panel[.panel-name[Q1] 1. What kind of **information** or **data points** do you think would be important to collect and analyze? .can-edit.key-activity3a[ - **Data Points to Collect:** + Edit me. + Edit me. + Edit me. ] ] .panel[.panel-name[Q2] 1. In a DDoS attack, what aspects of network traffic might change when there's an attack happening? How could you measure or quantify these changes? .can-edit.key-activity3b[ - **Changes in Network Traffic during an Attack:** + Edit me. + Edit me. + Edit me. ] ] .panel[.panel-name[Q3] 1. Think about monitoring network traffic over a period of time. What time-related factors should you consider when designing a detection system? .can-edit.key-activity3c[ - **Changes in Network Traffic during an Attack:** Edit me. ] ] .panel[.panel-name[Q4] 1. If you were trying to identify multiple requests coming from the same IP address, how would you keep track of these requests? What kind of **data structure** could you use to achieve this? .can-edit.key-activity3d[ - **Tracking Requests from the Same IP:** Edit me. ] ] .panel[.panel-name[Q5] 1. What could be some potential signs that a specific IP address is involved in a DDoS attack? 1. How would you set a threshold to determine when an IP address should be flagged as a potential source of an attack? .can-edit.key-activity3e[ - **Setting a Threshold:** Edit me. ] ] ] ??? 1. **Data Points to Collect:** Important data points to collect might include IP addresses of incoming requests, the time of each request, and the number of requests from each IP address. 1. **Changes in Network Traffic during an Attack:** During a DDoS attack, there may be a sudden increase in the number of incoming requests from various IP addresses. To quantify these changes, you could monitor request frequency, request rate, and the total number of unique IP addresses making requests. 1. **Time-Related Factors:** When monitoring network traffic over time, you should consider the duration of the monitoring period (time window) to observe patterns and changes. You might also consider the timestamps of incoming requests to track the rate at which requests are arriving. 1. **Tracking Requests from the Same IP:** To keep track of requests from the same IP address, we could use a data structure like a dictionary or hash table. Each IP address could be a key, and the associated value would be the count of requests made from that IP address. 1. **Setting a Threshold:** To flag an IP address as a potential source of a DDoS attack, you would need a threshold value representing an unusual level of traffic. If the number of requests from an IP address exceeds this threshold within the specified time window, you would flag it as a potential source of the attack. --- ## Computational Thinking: From Problem to Code/Solution <img src="data:image/png;base64,#../../figures/ct_diagram.png" alt="A diagram showing the four steps of computational thinking: decomposition, pattern recognition, abstraction, and algorithm design" width="69%" style="display: block; margin: auto;" /> .footnote[ <html> <hr> <html> **Image Source:** Harimurti, R., & Asto, B. I. (2019, May). The concept of computational thinking toward information and communication technology learning. In IOP Conference Series: Materials Science and Engineering (Vol. 535, No. 1, p. 012004). IOP Publishing. [Figure 02](https://www.researchgate.net/figure/The-elements-of-computational-thinking_fig1_333826796). ] ??? - **Decomposition:** Breaking down a complex problem into smaller, more manageable parts. This process involves dissecting a large, complex problem into smaller, more understandable and solvable components. - **Pattern Recognition:** Looking for similarities among and within problems. This involves identifying patterns, trends, or common characteristics in a set of data or problems to simplify and solve them more effectively. - **Abstraction:** Focusing on the important information only, ignoring irrelevant detail. It involves extracting the essential details about an issue or a problem, ignoring the background noise or unnecessary information. - **Algorithm Design:** Developing a step-by-step solution to the problem, or the rules to follow to solve the problem. This is about creating a clear set of instructions or a plan that can be followed to solve a problem or perform a task. --- ## Pseudocode for Detecting SYN Flood Attacks ``` python BEGIN DDoS_Detection `SET` threshold_limit `to` a significant number representing unusual traffic `SET` time_window `to` the period of monitoring traffic (e.g., per minute) `SET` ip_request_count `to` an empty data structure (e.g., dictionary) for each request in network_traffic `GET` ip_address from request `GET` request_time from request if ip_address is not in ip_request_count `SET` ip_request_count[ip_address] to 1 else `INCREMENT` ip_request_count[ip_address] by 1 if ip_request_count[ip_address] exceeds threshold_limit within time_window `FLAG` ip_address as potential DDoS source `TAKE` necessary action (e.g., block IP, alert admin) if time elapsed > time_window `RESET` ip_request_count for each ip_address `END` FOR loop END DDoS_Detection ``` --- ## App: Detecting Simulated Attacks based on Pseudocode <iframe src="https://muddos.streamlit.app/?embedded=true" style="height: 450px; width: 100%; max-width: 100%; border: none;" allowfullscreen> </iframe> .footnote[ <html> <hr> </html> **Notes:** Students are encouraged to "play" with the app's simulation configurations to better understand the pseudo_code. The app can be opened in your browser by navigating to: <https://muddos.streamlit.app/>. ] --- class: inverse, center, middle # Python Syntax, Data Types & Data Structures --- ## Why are we Discussing Syntax? > .font120[Good coding style is like **correct punctuation**: you can manage without it, **butitsuremakesthingseasiertoread**.] <br> -- [The tidyverse style guide](https://style.tidyverse.org) <br> > .font120[Code is **read much more often than it is written**. The guidelines provided here are intended to improve the readability of code ...] -- [PEP 8 - Style Guide for Python Code](https://peps.python.org/pep-0008/) --- ## Python Syntax: Key PEP 8 Guidelines .pull-left[ **Indentation** - Use .bold[4 spaces per indentation level]. - Do **not mix tabs and spaces for indentation**. - Example: ``` python def my_function(): for i in range(10): print(i) ``` ] .pull-right[ **Naming Conventions** - .bold[Functions and variables:] `lower_case_with_underscores` - .bold[Classes:] `CapWords` (or CamelCase) - .bold[Constants:] `UPPER_CASE_WITH_UNDERSCORES` - Example: ``` python class MyClass: CONSTANT_VALUE = 123 def my_method(self): my_variable = 10 ``` ] .footnote[ <html> <hr> </html> **Tip:** Consistency with these guidelines improves code readability and maintainability. See [PEP 8 - Style Guide](https://peps.python.org/pep-0008/) for more details. ] --- ## Python Syntax: Key PEP 8 Guidelines .pull-left[ **Comments** - Write .bold[clear comments (full sentences)] for tricky parts of the code. - .bold[Inline comments] should be used .bold[sparingly]. - Example: ``` python # Calculate the square of x (yes) square = x ** 2 # Square value (No) ``` ] .pull-right[ **Importing Modules** - Imports should be on separate lines. - **Order:** standard library (e.g., `os`) `\(\longrightarrow\)` related third-party (e.g., `pandas`) `\(\longrightarrow\)` local application/library specific imports (e.g. from other `.py` files). - Example: ``` python import os import sys import numpy as np import pandas as pd from my_local_module import my_function ``` ] .footnote[ <html> <hr> </html> **Tip:** Consistency with these guidelines improves code readability and maintainability. See [PEP 8 - Style Guide](https://peps.python.org/pep-0008/) for more details. ] --- ## Python's Data Model: "Everything is an Object in Python" <iframe src="https://docs.python.org/3/reference/datamodel.html" style="height: 475px; width: 100%; max-width: 100%; border: none;" allowfullscreen> </iframe> .footnote[ <html> <hr> </html> **Source:** The embedded page is from [3. Data model - Python 3.12.1 documentation](https://docs.python.org/3/reference/datamodel.html). ] --- ## Data Types <img src="data:image/png;base64,#../../figures/python_data_types.png" alt="A hierarchical flowchart representing Python data types and examples. The top-level includes Python Data Types/Classes, which are categorized into None, Numbers, Sequences, Set types, and Mappings. Each category is further divided into specific data types, and example values are provided for each data type, such as integers, floats, complex numbers, strings, tuples, lists, sets, frozensets, and dictionaries." width="100%" style="display: block; margin: auto;" /> .center[An overview of the most common data types in Python. Note that I excluded the `None` type as well as `modules` and `callables` from this flowchart (for the sake of conciseness).] .footnote[ <html> <hr> </html> **Image Credits:** Created by the author (Fadel M. Megahed) for our ISA 419 course, based on the information provided in the [Python's Data model documentation](https://docs.python.org/3/reference/datamodel.html). ] --- ## Python Variables are Pointers, Not Buckets .pull-left[ - Variables in Python are not buckets containing things; they're **pointers** (they point to objects). - A **pointer** just represents the **connection between a variable and an objects**. - Imagine **variables** living in *variable land* and **objects** living in *object land*. A pointer is a little arrow that connects each variable to the object it **points to**. - Assignment statements point a variable to an object. ] .pull-right[ ``` python numbers = [2, 1, 3, 4, 7] numbers2 = [11, 18, 29] name = "Trey" ``` <img src="data:image/png;base64,#../../figures/variables_are_pointers1.png" width="100%" style="display: block; margin: auto;" /> ] .footnote[ <html> <hr> </html> **Source:** The content and the figure in this slide are from Trey Hunter (2022). [Variables and objects in Python](https://www.pythonmorsels.com/pointers/) ] --- ## Assignment Points a Variable to an Object .pull-left[ - Variables in Python are not buckets containing things; they're **pointers** (they point to objects). - A **pointer** just represents the **connection between a variable and an objects**. - Imagine **variables** living in *variable land* and **objects** living in *object land*. A pointer is a little arrow that connects each variable to the object it **points to**. - Assignment statements point a variable to an object. ] .pull-right[ ``` python numbers = [2, 1, 3, 4, 7] numbers2 = numbers name = "Trey" ``` <img src="data:image/png;base64,#../../figures/variables_are_pointers2.png" width="100%" style="display: block; margin: auto;" /> ] .footnote[ <html> <hr> </html> **Source:** The content and the figure in this slide are from Trey Hunter (2022). [Variables and objects in Python](https://www.pythonmorsels.com/pointers/) ] --- ## Implications: Equality Compares Objects Python's `==` operator checks that two objects **represent the same data** (a.k.a. **equality**): .pull-left[ The variables `my_numbers` and `your_numbers` point to **objects representing the same data**, but the objects they **point to are not the same**. ``` python my_numbers = [2, 1, 3, 4, 7] your_numbers = [2, 1, 3, 4, 7] my_numbers == your_numbers ``` ``` ## True ``` ``` python my_numbers is your_numbers ``` ``` ## False ``` ] .pull-right[ So changing one variable/object **does not** change the other: ``` python my_numbers[0] = 7 my_numbers == your_numbers ``` ``` ## False ``` ] --- ## Changing the Object will Change Both Variables If two variables **point to the same object:** ``` python my_numbers_again = my_numbers my_numbers is my_numbers_again ``` ``` ## True ``` Changing the object one variable points to **also changes** the object the other variable points to: ``` python *my_numbers_again.append(419) print('my_numbers_again =', my_numbers_again, 'and my_numbers also =', my_numbers, '.') ``` ``` ## my_numbers_again = [7, 1, 3, 4, 7, 419] and my_numbers also = [7, 1, 3, 4, 7, 419] . ``` On a positive note, this does not apply to strings and numbers (both are **immutable**). .footnote[ <html> <hr> </html> **Source:** The content in this slide is adapted from Trey Hunter (2022). [Variables and objects in Python](https://www.pythonmorsels.com/pointers/) ] --- class: inverse, center, middle # Convert Basic Data Types --- ## Type Conversions in Python <img src="data:image/png;base64,#../../figures/type_conversion.png" alt="A flowchart depicting the process of Type Conversion in Python, including Implicit and Explicit Type Conversion, with examples and various data types such as integers, floats, strings, lists, sets, dictionaries, and more" width="100%" style="display: block; margin: auto;" /> .center[An overview of type conversions in Python.] .footnote[ <html> <hr> </html> **Image Credits:** Created by the author (Fadel M. Megahed) for our ISA 419 course. ] --- ## Class Activity: Type Conversion
−
+
03
:
00
.panelset[ .panel[.panel-name[Task] - Based on the previous chart, use [Google Colab](https://colab.research.google.com/) (or your preferred Python environment) to run the following two code examples. - Write down your observations in the next tab. .pull-left[ ``` python course_a = 'isa419' course_list_a = list(course_a) print(course_list_a) print(type(course_list_a)) ``` ] .pull-right[ ``` python course_b = 419 course_list_b = list(course_b) print(course_list_b) print(type(course_list_b)) ``` ] ] .panel[.panel-name[Observations] .can-edit.key-activity4[ - **My observations from these simple examples are:** + Edit me. + Edit me. + Edit me. ] ] ] --- class: center, inverse, middle # Manipulate Lists and Use Methods on Lists --- ## Lists in Python - A **list** is a **mutable** sequence of elements, i.e., it can be changed after it is created. - Lists are created by placing elements inside square brackets `[]`, separated by commas. - Lists can contain elements of different types, including other lists. - Lists are **ordered** and **indexed** (i.e., you can access elements by their position). --- ## Lists: Indexing and Slicing .font80[ .pull-left[ - **Indexing:** Accessing individual elements in a list. - Starts from 0 (for the first element) and goes up to `n-1` (for the last element). - To reference the last element, you can use `-1`, and so on. - You can call a particular item out of a list by using its index. For example, `my_list[0]` will return the first item in the list. ] .pull-right[ - **Slicing:** Accessing a subset of elements in a list, using the `:` operator, where: `my_list[start:stop:step]`. - If `start` not provided, it defaults to 0 - If `stop` is not provided, it defaults to the length of the list. - If `step` is not provided, it defaults to 1. * `my_list[:3]` returns the first three elements. * `my_list[3:]` returns all elements from the fourth to the last. *`my_list[::2]` returns every other element, and * `my_list[::-1]` returns the list in reverse order. ] ] --- ## Python List Functions | List Function | Description | Example | |------------------------|-------------------------------------------------------|-----------------------------------------| | `len()` | Returns the length of the list. | `my_list = [1,2,3]` <br/> `length = len(my_list)`<br/>`# length is 3` | | `max()` | Returns the maximum value in the list. | `my_list = [1,2,3]` <br/> `maximum = max(my_list)`<br/>`# maximum is 3` | | `min()` | Returns the minimum value in the list. | `my_list = [1,2,3]` <br/> `minimum = min(my_list)`<br/>`# minimum is 1` | | `sum()` | Returns the sum of all elements in the list. | `my_list = [1,2,3]` <br/> `total = sum(my_list)`<br/>`# total is 6` | | `sort()` | Sorts the list in ascending order. | `my_list = [3,2,1]` <br/> `my_list.sort()`<br/>`# my_list is now [1, 2, 3]` | --- ## Python List Functions (Cont.) | List Function | Description | Example | |------------------------|-------------------------------------------------------|-----------------------------------------| | `index(item)` | Returns the index of the first occurrence of `item`. | `my_list = [1,2,3]` <br/> `my_list.index(2)`<br/>`# index is 1` | | `append(item)` | Adds `item` to the end of the list. | `my_list = [1,2,3]` <br/> `my_list.append(4)`<br/>`# my_list is now [1, 2, 3, 4]` | | `pop(index)` | Removes and returns the element at `index`. | `my_list = [1,2,3]` <br/> `popped = my_list.pop(1)`<br/>`# popped is 2,` <br/> `# my_list is [1, 3]` | | `remove(item)` | Removes the first occurrence of `item` from the list.| `my_list = [1,2,3]` <br/> `my_list.remove(2)`<br/>`# my_list is [1, 3]` | --- ## Class Activity: List Manipulation
−
+
10
:
00
.panelset[ .panel[.panel-name[Task] In pairs, build on the code below to: ``` python # your path will be different with open("../../data/simulated_logs.txt", "r") as file: lines = file.readlines() # Strip newline characters from each line log_entries = [line.strip() for line in lines] type(log_entries) ``` 1. Show how to get the **total number of log entries**. 1. Show how to slice the **first 5 log entries**. 1. **Filter out all** log entries that contain the word **ERROR**. 1. **Count** the number of **ERROR** entries. ] .panel[.panel-name[Solution] In [Google Colab](https://colab.research.google.com/) (or your favorite Python environment), write code to address the questions in the previous tab. ] ] --- class: inverse, center, middle # Recap --- ## Summary of Main Points By now, you should be able to do the following: - Use pseudocode to map out a problem. - Python Syntax, Data Types, and Data Structures - Convert data types using type casting - Manipulate lists and use methods on lists --- ## 📝 Review and Clarification 📝 1. **Class Notes**: Take some time to revisit your class notes for key insights and concepts. 2. **Zoom Recording**: The recording of today's class will be made available on Canvas approximately 3-4 hours after the end of class. 3. **Questions**: Please don't hesitate to ask for clarification on any topics discussed in class. It's crucial not to let questions accumulate. --- ## 🎯 Assignment 🎯 Please work on and submit [Assignment 02](https://miamioh.instructure.com/courses/229048/quizzes/702078) prior to our next class.