Boost Your Cybersecurity: Top Python Libraries You Need

Python is one of the most popular languages in cybersecurity. With wide popularity and large community support, python offers a plethora of libraries that can be used for various tasks. Here are some of the top Python libraries commonly used in cybersecurity. Here is a quick cheat sheet.

Scrapy

Scrapy is a powerful web crawling and web scraping framework that comes with packet manipulation modules. It can be used for network packet sniffing, generation, analysis, and decoding.

'''packet analysis using scapy'''
from scapy.all import *

# Load packets from a pcap file
packets = rdpcap('network_traffic.pcap')

# Display summary of each packet
for packet in packets:
    print(packet.summary())
    if packet.haslayer(IP):
        print(f"Source IP: {packet[IP].src}, Destination IP: {packet[IP].dst}")


Requests

Requests is a user-friendly library designed for straightforward interaction with web services, such as retrieving web pages and submitting forms. It offers a simple and secure way to send requests and reliably handles responses.

import requests

# Define the URL of the server that requires a client certificate
url = "https://example.com/secure-endpoint"

# Define the paths to the certificate and key files
cert_file = "path/to/cert.pem"
key_file = "path/to/key.pem"

# Make a GET request with the client certificate
try:
    response = requests.get(url, cert=(cert_file, key_file))

    # Check the status code of the response
    if response.status_code == 200:
        print("Request was successful")
        print("Response content:")
        print(response.text)
    else:
        print(f"Request failed with status code: {response.status_code}")

except requests.exceptions.RequestException as e:
    print(f"An error occurred: {e}")


Impacket

While Impacket is frequently used by a variety of adversaries, it is an extremely useful collection of Python classes for working with network protocols. It is most commonly used for low-level networking (IP, UDP, and TCP) and tasks related to Windows high-level protocols like SMB in penetration testing and vulnerability assessments. You can find the most available within your Kali Linux environment. Alternatively, here is a list of some script examples and reposotory.

Cryptography

The cryptography package provides reliable cryptographic algorithms and protocols for secure communication. It includes both high-level recipes and low-level interfaces to common cryptographic algorithms. It can be used for encryption and decryption, secure password storage, cryptographic key generation and management, and implementation of secure communication protocols. Cryptography provides two levels of cryptographic operations: cryptographic recipes, which are easy to use with minimal configuration, and low-level cryptographic primitives in the cryptography.hazmat package, which require deep cryptographic knowledge.

from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
import os

# Generate a random 256-bit (32 bytes) key
key = os.urandom(32)

# Generate a random 128-bit (16 bytes) initialization vector
iv = os.urandom(16)

# Data to be encrypted
secret_data = "Super duper secret message!!!"

# Create an AES Cipher object with the key and IV in CBC mode
cipher = Cipher(algorithms.AES(key), modes.CBC(iv))

# Encrypt the data
encryptor = cipher.encryptor()
encrypted_data = encryptor.update(secret_data.ljust(16)) + encryptor.finalize()

print(f"Encrypted super duper secret message: {encrypted_data}")

# Decrypt the data
decryptor = cipher.decryptor()
decrypted_data = decryptor.update(encrypted_data) + decryptor.finalize()

print(f"Decrypted/plaintext: {decrypted_data.strip()}")


python-nmap

Python-nmap library helps in easy access to modules with Nmap port scanner functionality. Explore example.py script to see how the python-nmap package can be used to automate network scanning and retrieval of device information during network discovery and security auditing. Note this is not the only way to automate network scanning. RollerScanner is an excellent example of a fast network scanner without python-nmap.

pwntools

Pwntools is your to go to library for CTF (capture the flag) and exploit development automation. “It provides utilities to simplify interractionwith binaries, network services, and management of shellcode. It provides easy access to tolls for crafting and sending payloads, handling binary data, debugging. pwntool-tutorial is a great place to start. Here is a great cheatsheet by Anvbis to get you started.

Volatility

Volatility is a memory forensics framework for “the extraction of digital artifacts from volatile memory (RAM) samples” in the analysis of volatile memory during digital forensics investigations. A quick guide on using Volatility is a great way to get started. Great example from Varonis on identifying malicious network connections, injected code, and malicious processes. Follow these steps on your Linux machine to install Volatility. Take a look at the BlackHat presentation “Investigating Malware Using Memory Forensics” and Volatility Cheat Sheet from SANS.

git clone https://github.com/volatilityfoundation/volatility3.git
cd volatility3
pip3 install -r requirements.txt

# Volatility help menu
python3 vol.py -h

yara-python

The yara-python library allows you to include all of YARA’s functionality in Python scripts. It is mainly used for malware research. Yara-python provides a simple way to scan files and process them for known malware signatures in malware detection and analysis, as well as identify and classify malware samples. It allows you to create complex rules to match binary patterns. Here is an example of a Python script that creates YARA rules.

dnspython

A DNS toolkit for Python, useful for performing DNS queries, MX records queries, and for such can be used in network reconnaissance. It comes with few example sripts.

import dns.resolver

# Qyery A records
def automated_recon(domain, subdomains):
    recon_data = {
        'A Records': query_a_records(domain),
        'MX Records': query_mx_records(domain),
        'NS Records': query_ns_records(domain),
        'Subdomains': find_subdomains(domain, subdomains)
    }
    print('Reconnaissance Data:', recon_data)

automated_recon('example.com', ['www', 'mail', 'ftp', 'blog'])


socket

The socket library in python is a low-level networking tool for incorporating networking functionality within Python scripts. It can be used for network scanning, packet crafting, honeypot creation, and penetration testing. You can find number of examples use scripts from Pysheets and few more in Black Had Python by Justin Seitz.

OpenCV

OpenCV-Python is a library of Python bindings designed to solve computer vision problems.” While primarily used for computer vision, OpenCV can be used for cybersecurity to detect anomalies and identify hidden data within images (steganography). Here is an example:

import cv2
import numpy as np

def detect_steganography(image_path):
    image = cv2.imread(image_path)
    image_hist = cv2.calcHist([image], [0], None, [256], [0, 256])
    if len(np.where(image_hist == 0)[0]) > 10:
        print("Steganography detected in image.")
    else:
        print("Steganography not detected in image.")

detect_steganography('image.jpg')


hashlib

Hashlib is a standard Python library used for secure hash and message digest algorithms, which are useful for integrity checks and cryptographic operations like digital signature generation. It supports SHA-2 (SHA224, sha256, sha384, and sha512) and SHA-3 algorithms.

import hashlib

def hash_text(text):
    if not isinstance(text, str):
        raise ValueError("Input must be a string.")
    hash_object = hashlib.sha256(text.encode('utf-8'))
    return hash_object.hexdigest()


Pillow (PIL)

Pillow - Python Imaging Library (PIL) is yet another library that can be used for steganography and image forensics for image processing tasks. Here is a bit more on how that can be done in “Image Steganography with Python”.

from PIL import Image

def encode_image(image_path, secret_message, output_path):
    image = Image.open(image_path)
    secret_message += "secret script goes here"  # End marker
    encoded = image.copy()
    width, height = image.size
    idx = 0

    for x in range(width):
        for y in range(height):
            if idx < len(secret_message):
                r, g, b = image.getpixel((x, y))
                encoded.putpixel((x, y), (r, g, ord(secret_message[idx])))
                idx += 1
    encoded.save(output_path)





    Enjoyed this read?

    Here are some more articles you might like to read next:

  • Crafting Your Incident Runbook
  • Return of SSH Race Condition: Regression Testing Chronicles
  • Hello World!