6 Ways to Apply CompTIA Security+ Material with Python
I came up with the idea for this article as a follow-up to my previous article. For those who are having trouble finding practice labs to study for the Security+ exam, these scripts are a good way to learn about these particular topics in a hands-on way. In addition, these scripts can be used as a Github portfolio for those who want to purport Python programming as a viable skill to put on your resume.
Prerequisites:
Windows OS
Python 3+
Clam AV
Snort
Wireshark
Scapy (Python library)
- Run an anti-virus scanner.
Clam AV is an open-source antivirus scanner that is available on Windows, Linux and Mac.
antivirus_scan.py
import subprocessdef main():
# Create an empty list.
filename_array = []filename = input(“Enter the filepath of the file/folder to scan: ”) # Insert the filepath into the list.
filename_array.insert(0, filename) # Scan the file/folder.
subprocess.Popen([“powershell”, “cd ‘C:\\Program Files\\clamav’; \
.\\clamscan — recursive “] + filename_array, shell=True)if __name__ == “__main__”:
main()
2. Run a network scanner.
Snort is an open-source network intrusion detection system (IDS) that is also available on Windows, Linux and Mac. The Python script below uses the Scapy library to read the IP packets that are traveling through a network, collect the packets and store them in what is called a .pcap file (short for “packet capture”.) Snort uses the .pcap file to detect threats within the network traffic.
I tried to enter a try…catch statement in the script to catch user input that doesn’t include a backslash at the end of the file path in one of the input statements below, but received an error from the Scapy libary. So, remember to end the file path with a backslash.
snort_packet_sniff_www.py
from scapy.all import sniff
from scapy.all import wrpcap
from scapy.arch.windows import get_windows_if_list
from subprocess import check_calldef main():
# Enter a file path and name for the packet file.
snort_filepath = input(“Enter the file path for the .pcap file: “)
snort_filename = input(“Enter a name for the .pcap file: “)
snort_file = snort_filepath + snort_filename + “.pcap” # Sniff for HTTP/HTTPS packets from Network Interface #1 for 60 seconds.
packets = sniff(filter=”(tcp port 80) or (tcp port 443)”, \
timeout = 60, \
iface = get_windows_if_list()[1][“name”]) # Store the packets in the packet file.
wrpcap(snort_file, packets) # Open the packet file in Snort.
check_call([“C:\\Snort\\bin\\snort.exe”, “-r”, snort_file])if __name__ == “__main__”:
main()
3. Run a network analysis tool. (Wireshark)
Wireshark is a tool that reads IP packets that travel on a network and allows for analysis on an OSI-layer perspective. Wireshark is another tool that uses the Scapy library and .pcap files for network analysis.
Wireshark is open-source and available on Windows, Linux and Mac.
packet_sniff_dns.py
from scapy.all import sniff
from scapy.all import wrpcap
from scapy.arch.windows import get_windows_if_list
from subprocess import check_calldef main():
# Enter a file path and name for the packet file.
shark_filepath = input(“Enter the file path of the .pcap file: “)
shark_filename = input(“Enter a name of the .pcap file: “)
shark_file = shark_filepath + shark_filename + “.pcap” # Sniff for DNS packets on Network Interface# 1 for 60 seconds.
packets = sniff(filter=”port 53", \
timeout = 60, \
iface = get_windows_if_list()[1][“name”]) # Store the packets in the packet file.
wrpcap(shark_file, packets) # Open the packet file in Wireshark.
subprocess.Popen(“%s %s” %(“C:\\Program Files\\Wireshark\\Wireshark.exe”, shark_file))if __name__ == “__main__”:
main()
4. Generate an RSA key pair.
A certificate can be used to gain access to a device. A .pem file is a commonly used type of certificate. Pem files are used to gain remote access to Amazon AWS EC2 instances.
This type of certificate uses asymmetric encryption; it creates two keys, a public key and private key.
Unfortunately, I received errors when I entered the file path for the .pem file through the input() function. So, the file path needs to be manually entered in the script below for each instance of the file path.
public_key_gen.py
from Crypto.PublicKey import RSA
import subprocess, sysdef main():
# Generate a 4096-bit RSA key for the private and public .pem files.
key = RSA.generate(4096) # Initialize the key for the private file in .pem format.
private_key = key.exportKey(‘PEM’) # Create the private .pem file.
# The subprocess command below cannot read file paths that have spaces in them, even with quotation marks around them.
new_private_file = open(“C:\\[ENTER FILE PATH HERE]\\private_key.pem”, “wb”) # Insert the key into the private .pem file.
new_private_file.write(private_key) # View the contents of the private .pem file.
subprocess.Popen([“powershell.exe”, “Get-Content -Path {0}”\
.format(“C:\\[ENTER FILE PATH HERE]\\private_key.pem”)],
stdout=sys.stdout) # Initialize the key for the public file in .pem format.
public_key = key.publickey().exportKey(‘PEM’) # Create the public .pem file.
new_public_file = open(“C:\\[ENTER FILE PATH HERE]\\public_key.pem”, “wb”) # Insert the key into the public .pem file.
new_public_file.write(public_key) # View the contents of the public .pem file.
subprocess.Popen([“powershell.exe”, “Get-Content -Path {0}”\
.format(“C:\\[ENTER FILE PATH HERE]\\public_key.pem”)],
stdout=sys.stdout)if __name__ == “__main__”:
main()
5. Run a strong password generator.
I thought this was a good script to create, for those who are running password-protected systems and need a source to create a strong password. It’s not perfect but I believe it’s usable.
password_gen.py
import randomdef main():
# Create a string that contains all alphanumeric and special characters.
gen_string = “0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*(),./-=;’][}{|<>?:” # Create an empty list.
gen_pass = [] # For an 8-character-long password, loop from 0 to 8 (without an iterator.)
for _ in range(8):
# In the loop, select a random character from the string and add it to the list.
gen_pass.append(gen_string[random.randint(0, len(gen_string))]) # Convert the list into a string.
print(“”.join(gen_pass))if __name__ == “__main__”:
main()
6. Run a checksum on a file.
A checksum is a number that verifies the data integrity of a file/folder. This means that, if a file/folder has been tampered with, the checksum will be a different number compared to the checksum that was generated from the original file/folder.
A checksum is generated from a hashing algorithm, such as MD5 (Message Digest 5), SHA-256 (Secure Hash Algorithm), HMAC (Hash-based Message Authentication Code) and RIPEMD (RACE Integrity Primitives Evaluation Message Digest). MD5 and SHA-256 are the most commonly used hashing algorithms.
checksum_gen.py
import hashlibdef main():
file_name = input(“Enter the file path of the file or folder you want to hash: ”)
hash_name = input(“Do you want to run the checksum with MD5 or SHA-256? ”)
# Verify that the user input is a valid hashing algorithm.
while True:
try:
hash_name == “md5” or hash_name == “MD5” or \
hash_name == “sha256” or hash_name == “SHA256” or \
hash_name == “sha-256” or hash_name == “SHA-256”
break
except ValueError:
print(“Enter either ‘md5/MD5’ or ‘sha256/SHA256/sha-256/SHA-256’.”)
# Run the hash.
if hash_name == “md5” or hash_name == “MD5”:
hasher = hashlib.md5()
else:
hasher = hashlib.sha256() # View the hash.
with open(file_name, ‘rb’) as afile:
hasher.update(afile.read())
print(hasher.hexdigest())if __name__ == “__main__”:
main()