Module 2

Object-Oriented Programming

Master classes, inheritance, and polymorphism for scalable security applications

Learning Objectives

Understand classes and object instantiation

Master inheritance and method overriding

Implement polymorphism and encapsulation

Design security-focused class hierarchies

Apply SOLID principles to code design

Build real-world security tools with OOP

Core OOP Concepts

Classes and Objects
Blueprint for creating objects with attributes and methods

A class is a template that defines the structure and behavior of objects. Objects are instances of classes that contain data (attributes) and functions (methods).

python
class User:
    def __init__(self, username, email):
        self.username = username
        self.email = email
        self.is_active = True
    
    def display_info(self):
        return f"User: {self.username}, Email: {self.email}"
    
    def deactivate(self):
        self.is_active = False

user1 = User("alice", "[email protected]")
print(user1.display_info())
print(f"Active: {user1.is_active}")

user1.deactivate()
print(f"Active: {user1.is_active}")

Security-Focused OOP Patterns

User Authentication System
Build a secure authentication framework
python
import hashlib

class Authenticator:
    def __init__(self):
        self.users = {}
    
    def hash_password(self, password):
        return hashlib.sha256(password.encode()).hexdigest()
    
    def register(self, username, password):
        if username in self.users:
            return "User already exists"
        self.users[username] = self.hash_password(password)
        return "Registration successful"
    
    def login(self, username, password):
        if username not in self.users:
            return "User not found"
        if self.users[username] == self.hash_password(password):
            return "Login successful"
        return "Invalid password"

auth = Authenticator()
print(auth.register("alice", "secure_pass123"))
print(auth.login("alice", "secure_pass123"))
print(auth.login("alice", "wrong_pass"))

SOLID Principles

Single Responsibility Principle

Each class should have only one reason to change. Separate concerns into different classes.

python
class UserRepository:
    def save_user(self, user):
        pass

class UserValidator:
    def validate_email(self, email):
        return "@" in email

class UserService:
    def __init__(self, repository, validator):
        self.repository = repository
        self.validator = validator
    
    def create_user(self, username, email):
        if self.validator.validate_email(email):
            self.repository.save_user({"username": username, "email": email})
            return "User created"
        return "Invalid email"
Open/Closed Principle

Classes should be open for extension but closed for modification.

python
class PaymentProcessor:
    def process(self, amount):
        pass

class CreditCardProcessor(PaymentProcessor):
    def process(self, amount):
        return f"Processing credit card payment: {amount}"

class PayPalProcessor(PaymentProcessor):
    def process(self, amount):
        return f"Processing PayPal payment: {amount}"

def checkout(processor, amount):
    return processor.process(amount)

cc = CreditCardProcessor()
paypal = PayPalProcessor()
print(checkout(cc, 100.0))
print(checkout(paypal, 50.0))

Hands-On Project

Build a Port Scanner Class
Create a reusable security tool using OOP principles

Design a PortScanner class that encapsulates port scanning functionality with proper error handling and logging.

python
class PortScanner:
    def __init__(self, target_host, timeout=2):
        self.target_host = target_host
        self.timeout = timeout
        self.open_ports = []
        self.scan_results = []
    
    def scan_port(self, port):
        try:
            import socket
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.settimeout(self.timeout)
            result = sock.connect_ex((self.target_host, port))
            sock.close()
            return result == 0
        except Exception as e:
            return False
    
    def scan_range(self, start_port, end_port):
        for port in range(start_port, end_port + 1):
            if self.scan_port(port):
                self.open_ports.append(port)
                self.scan_results.append({"port": port, "status": "OPEN"})
    
    def get_results(self):
        return {"target": self.target_host, "open_ports": self.open_ports}

scanner = PortScanner("127.0.0.1")
scanner.scan_range(20, 100)
print(scanner.get_results())