Skip to main content

Functions

In this tutorial, we'll explore the power of Python functions and how they can be applied in the realm of Cyber Security.

Functions are reusable blocks of code that perform a specific task.

Understanding Functions

A function in Python is defined using the def keyword, followed by the function name, parentheses (), and a colon :. The code inside the function is indented.

greet.py
def greet():
print("Hello, CyberSec!")

greet()

The above code defines a function named greet() that prints Hello, CyberSec! when called. The function is called at the end of the code.

Parameters and Return Values

Functions can take inputs, known as parameters, and can also return values.

Let's create a function that checks if a given port is a common web port:

is_web_port.py
def is_web_port(port):
web_ports = [80, 443, 8080]
return port in web_ports

print(is_web_port(80)) # Output: True
print(is_web_port(22)) # Output: False

Hashing

Hashing is a fundamental concept in cyber security. Let's create a function to generate an MD5 hash of a given string:

generate_md5.py
import hashlib

def generate_md5(data):
return hashlib.md5(data.encode()).hexdigest()

print(generate_md5("password")) # Output: 1a2b3c4d5e6f7g8h9i0j

Base64 Encoding and Decoding

Base64 is commonly used in a variety of applications including in some forms of authentication:

base64.py
import base64

def encode_base64(data):
return base64.b64encode(data.encode()).decode()

def decode_base64(data):
return base64.b64decode(data.encode()).decode()

encoded = encode_base64("secret")
print(encoded) # Outputs: c2VjcmV0

decoded = decode_base64(encoded)
print(decoded) # Outputs: secret

IP Validation

Let's create a function to validate IPv4 addresses:

validate_ipv4.py
import ipaddress

def validate_ipv4(ip):
try:
ipaddress.IPv4Address(ip)
return True
except ipaddress.AddressValueError:
return False

print(validate_ipv4("192.168.1.1")) # Outputs: True
print(validate_ipv4("256.256.256.256")) # Outputs: False

Automating Nmap Scans

Nmap is a popular network scanning tool. Using the python-nmap library, we can automate scans:

nmap_scan.py
import nmap

def run_nmap_scan(target):
nm = nmap.PortScanner()
nm.scan(target, '22-443')
return nm.all_hosts()

print(run_nmap_scan('192.168.1.1'))

Analyzing Malicious URLs with VirusTotal

VirusTotal provides a public API to check URLs, IPs, and files for malicious content. Here's a function to check the reputation of a URL:

virustotal.py
import requests

def check_url_virustotal(url, api_key):
base_url = "https://www.virustotal.com/vtapi/v2/url/report"
params = {"resource": url, "apikey": api_key}
response = requests.get(base_url, params=params)
data = response.json()
return data['positives'], data['total']

api_key = "YOUR_VIRUSTOTAL_API_KEY"
positives, total = check_url_virustotal("http://example.com", api_key)
print(f"Detected {positives} out of {total} as malicious.")

Note: You need to sign up on VirusTotal to get an API key.

Extracting Metadata from Files

Files, especially images and documents, can contain metadata that might reveal interesting information:

extract_metadata.py
from PIL import Image
from PIL.ExifTags import TAGS

def extract_metadata(image_path):
image = Image.open(image_path)
metadata = {}
for tag, value in image._getexif().items():
tag_name = TAGS.get(tag, tag)
metadata[tag_name] = value
return metadata

metadata = extract_metadata("/path/to/image.jpg")
print(metadata)