Learn Python - Ethical Hacking From Stratch (StationX Notes)
Learn Python - Ethical Hacking From Stratch (StationX Notes)
You can
find the StationX courses here.
Learn Python & Ethical Hacking From Scratch
What is Hacking?
3 Types of hacking
1. Black-hat Hackers
a. Don’t have permission to hack
2. White-hat Hackers
a. Have permission
3. Gray-hat Hackers
a. Do not have full permission, but will identify and report to white-hat
Why Hacking?
- An existing industry
- Lots of job opportunities
- Be able to secure systems from hackers
- Large demand for ethical hackers
What is a program?
- A set of instructions to do certain tasks or solve a problem
Why Python?
- Simple but powerful
- Free & Open Source
- Object Oriented
- Lots of great libraries for hackers
Why Programming?
- Great skill to learn
- Lots of job opportunities
- Allows you to implement your own solutions
Kali Linux
- Kali Linux is a Linux distribution based on Debian, Kali is especially made for
pentesters, it contains most of the tools that we need, installed, and configured
correctly
- You can download Kali on their official website: https://www.kali.org/downloads/
Configuring Settings
- 1024 MB for 1 GB
- 2048 MB for 2 GB (if you have 16GB of RAM)
Terminator → A program that allows you to split screens and have multiple command
prompts open at the same time
Python 2 vs Python 3
- You should always include the ShaBang in your scripts to let the computer know
what kind of script it is
- #!/usr/bin/env python or #!/usr/bin/env python3
The Terminal
- Think of the terminal as a means of knowing two different languages and can
commute between both as a translator
- In the terminal, ensure you are in the right directory with the file
- python file_name.py
SubProcess Module
Variables: A variable is a location in memory that contains a certain value. It’s a name
that is used to store information.
Insecure Method: When using a variable without any validation, you are allowed to
enter as many commands or other commands in the input rather than what’s supposed
to be possible - you need input validation.
- When using the subprocess.call()
- When using the suprocess.call[] → You fix this issue because python knows to
only take one argument
Class: Anything that has a capital letter is typically a class. A class is a blueprint which
allows you to execute a certain commands with a declared option.
Functions
- Set of instructions to carry out a task
- Can take input, and return result
- Make the code clearer, reusable, and more abstract
- input() function prompts the user to enter a value
Decision Making
- Execute code ONLY if a condition is true. → Use of If statements
Mac_Changer: Simple Algorithm
Steps:
1. Execute and read ifconfig
2. Read the MAC address from output
3. Check if MAC in ifconfig is what the user requested
4. Print appropriate message
Regular Expressions:
To convert to a str
- Use the str() method
- Treating something or an object as another type is known as casting in
programming
IP Address Range: To find an IP Address within the current range use 10.0.1.1/24 to
find all addresses between 10.0.1.1 - 10.0.1.254
Netscan: Use netscanner -r 10.1.1.1/24 to scan all devices with subnet mask
Communication within a network is carried out by the Mac address, not the IP address.
Resolves or maps the IP address of a client with the associated MAC address
- Requesting client/workstation knows the IP address, but not the MAC address
- ARP request packet (with IP address of target client) is sent to all
clients/workstations within the network
- The client with the associated correct IP address communicates back with
its MAC address
Scapy Module: A python module which allows for sending ARP requests
Steps
1. Create arp request directed to broadcast MAC asking for IP
2. Send packet and receive response
3. Parse the response
4. Print result
Step 1:
- Use ARP to ask who has target IP
- Set destination MAC to broadcast MAC
Scapy ARP:
Scape Ether:
- broadcast = scapy.Ether(dst=”ff:ff:ff:ff:ff:ff”) → Set destination MAC address to
Broadcast MAC
- broadcast.show() → Will show summary of executed scapy commands
Lists
-
Iterating over Lists and Analyzing the Packets:
- \t → New tab
- \n → New line
- print(“hello there\t\t\t”)
Dictionaries
- Attacker is in the middle of the client & router, intercepting both points.
- The victim thinks the attacker is the router and the router thinks the
attacker is the victim
Creating a Counter:
- Set variable to zero before loop, then increment by number
- counter = 0
- while True:
- counter = counter + 1
Handling Exceptions
- try/except can be used to handle errors
- Write default code in try block
- Write code to run if error occurs in except block
To delete IPTables:
- Command: iptables --flush
To Modify the IPTables
- Use: Netfilterqueue python module
- To initialize a new netfilterqueue:
- queue = netfilterqueue.NetfilertOpen()
To bind the packet to the queue created by IPTables:
- queue.bind(0, packet_process_function())
To run the queue:
- queue.run()
- To create a local web server on your Kali Machine, type in terminal: service
apache2 start
- Run ifconfig to see the IP address of eth0 (your local web server)
- Use an if statement
- Example: if “.exe” in scapy_packet[scapy.Raw].load
We can append fields ack & seq to a list in order to see if the request and response
correspond with each other
- Edit requests/responses
- Replace download requests
- Inject code (html/Javascript)
- Will be learning how to intercept and modify any part in the raw layers of any web
page
When running this program, the HTML is encoded with gzip, a type of encoder which
translates HTML down to gzip formatting.
To retranslate from gzip to HTML, we first need to edit the Accept-Encoding field with a
regex expression.
Default:
After we have the encoding we will create a new packet under the .dport field.
After we have set our encoding to accept HTML, we want to set up a command to
replace the packet
- To do this, we use the .replace method to append or replace the </body> with
some test JavaScript code
Modified_load = scapy_packet[scapy.Raw].load.replace(“</body>”,
“<script>alert(‘test’):</script></body>”)
new_packet = set_load(scapy_packet, modified_load)
packet.set_payload(str(new_packet))
Content Length of page is requested before injecting the sample JavaScript code
- E.x.: Content-Length: 31245
- When injecting the test JavaScript code, the length increases, terminating
the browser from loading again
First, we must single out the Content-Length portion of the load field.
- Content_length_search = re.search(“(?:Content-Length:\s)(\d*)”, load)
The (?:.....) section looks for that portion of the string, but doesn’t include it. We only
want the digits (length of website content), not the “Content-Length” portion.
If content_length_search:
content_length = content_length_search.group(1)
print(conent_length)
After this we create a new_content_length variable which calculates the length of the
page with the injection code.
BeEF Framework
Once BeEF Framework has launched, you can use various exploits once a website is
hooked.
To hook a website in BeEF, ensure you copy the hook javascript (circled in red)
Change the IP address to the target IP within the hook field.
- Copy and paste this JavaScript code into code_injector program
After injecting the JavaScript code into our Python program, you can use any type of
command within BeEF (ex social engineering, screenshots, alert boxes, website
redirection)
Bypassing HTTPS
- To bypass HTTPS, the attacker must be in the middle of the victim / internet
- When the internet resource (ex website) sends an initial request off to the victim
for HTTPS, the victim will respond with a response to be communicating over
HTTPS
- The attacker will downgrade HTTPS while being in between this process using a
program called SSLstrip
HTTP Strict Transport Security (HSTS): A whitelist created which will only allow a
browser to be run on HTTPS - cannot bypass HSTS as of right now.
Using SSLStrip:
Change the dport and sport fields to port 10000 (for SSLStrip).
Writing a ARP Spoofer Detector
Windows
- Python programs needs an interpreter to run
- Most Linux distributions come with a built-in python interpreter
- Python can be manually installed on Windows
- Allows Windows to run Python Programs
Writing Malware
Writing Malware
- Writing Evil programs which create backdoors
We will learn
- Download a file
- Execute Code
- Send Report
- Download & Execute
- Execute & Report
- Download, Execute, & Report
Execute System Command Payload
- Execute system command on target
- If programs is executed on Windows → Execute Windows commands
- If program is executed on Mac OS X → Execute Unix commands
After packaging:
- Execute any system command
Settings:
- Set email server through smptlib.SMTP(“smtp.gmail.com”, 587)
- Must set
- .starttls()
- .login(email, password)
- .sendmail(your_email, send_email_to_this_address, your_message)
- .quit()
Filtering Command Output Using Regex
For filtering network names with command ‘netsh wlan show profile’
- To create a loop which will continually append new names in a string, create a
empty string outside of a loop then perform the operations, then make the same
variable name equal to the same variable name + the edited functions inside the
loop.
Downloading Files From Programs
- Import os module
- Use remove method: os.remove(“testfile.exe”)
Keylogger
Common Features:
Code screenshot:
- To use a variable outside the function, you must use a global variable
- Global variables are not the best solution, however.
Example:
Code:
Threading:
Recursion:
Constructor Method:
Backdoors:
- Interactive program gives access to system its executed on.
- Command execution
- Access file system
- Upload/download files
- Run keylogger
- After we have established an open port via netcat, we will create a program on
the victim machine which will send packets to kali machine
Code:
To allow more than one command to be executed by the Kali Terminal to the Windows
Machine, implement this code: While True statement allows for more than one
command to be executed.
Creating a Listener (Server on Attacker Side)
To create a listener on the attacker side (target), import and utilize the socket module:
Make both the listener program & the reverse_backdoor program Object Oriented.
Listener:
Reverse_backdoor:
Serialization Theory
- TCP Stream Problem: There is not enough storage capacity for the client
(server) to receive, meaning there is still more data to be transferred over to the
server
- Solution: Seralization
Serialization:
- Client converts object to a stream of well-defined bytes
- Server converts well-defined stream of bytes back into an object
Serialization Implementation:
- Json and Pickle are common solutions for Python
- Json (Javascript Object Notation) is implemented in many programming
languages
- Represents objects as text
- Widely used when transferring data between clients and servers
Create two new functions, json_send & json_recieve:
Reliable_send: Takes the data, converts to json format, and the sends over the TCP
stream.
Reliable_recieve: Creates a new string variable, receives data from TCP stream,
converts back into regular format, and continues to iterate through (1024 bytes) until the
data has been fully unpackaged
Make sure to add the reliable_send and receive to the execute_remotely method
To add an exit command, which will close the backdoor, add an if statement to the
execute_remotely method which will close the socket connection, then exit the python
program. In addition, add a split() method to the run in the listener to split the string into
a list.
Add this code to the run statement in the reverse_backdoor.py program
- How this works: We created a method which changes the working directory from
the os module. After this, we create an “elif” statement which checks to see if
argument 0 is the string, ‘cd’, and we also check to see if the command length is
greater than one. For example, typing in >>> cd is one in length, whereas, >>>
cd .. is two in length. After we check to see if the command is one or greater, we
call the working directory function which imports the .. into the os.chdir(path) and
changes one directory back.
-
- Create the functionality in the backdoor by adding a new “elif” statement which
checks for the word download
-
On listener.py (attacker machine)
- Create function which opens a file and writes the the file. “wb” stands for write
binary.
-
- Create the functionality in the backdoor by adding a new “elif” statement which
checks for the word “download” if and when the victim types in “download”
Adding base64:
Problem:
- We can read and write plain text, but if the attacker wants to download an image,
base64 will have to be used.
Solution:
- Import base64 module in both the reversebackdoor.py & listener.py program
- In reversebackdoor.py add the base64.b64encode function when reading the file
-
- In listener.py add the base64.b64encode function to the write function
Upload Functionality:
Problem:
- We can download files from the victim machine via the attacker’s machine, but
we can’t upload new files
Solution:
- Copy and paste the read_file() function into the listener.py and the write_file()
function to the reversebackdoor.py
- In reversebackdoor.py:
- Add an upload functionality which checks for the word ‘upload’ and then
writes the filename to the victim mahine
-
- In listener.py
- Add a upload functionality which reads the file and appends the file
content
Quick Note: It’s better to package a trojan from the same machine as what the victim
will be using
-
- For Python 2, you must add a devnull variable
- And then you can delete the subprocess in front of the DEVNulls
Note: In order for a program to run successfully, you must install all third party python
libraries with the executable.
Persistence
In Windows:
- Use regedit program
- Locate HKEY_CURRENTUSER → Software → Microsoft → Windows →
CurrentVersion → Run
- We can use the command prompt to add a new entry
Creating a Trojan
Methods:
To add the front file with the executable, add a --add-date parameter.
Bypassing Anti-Virus Programs
To bypass signatures
- Use your own code - make it unique (obfuscation, useless operations, encode,
pack)
To bypass behaviors
- Run file in a sandbox and analyze it
- Run trusted operations before evil code
- Delay execution of evil code
To add the icon, add the --icon parameter when compiling the file with a normal file:
Spoofing File Extensions
- Spoofing file extensions can be hard and will require the exploitation of
vulnerabilities
- Unless the Windows File Extensions are unset by the default “turn off file
extensions”, you will have to respell the file from right to left
- To do this, search “Characters” in Kali Program List and type “right-to-left
Override”
-
- Then, put cursor before the fdp and paste the override
- The file should be renamed & then you can change the filename for the evil file
- It’s a good idea to compile your trojans from the same OS as you are intending
them to be executed on
- Mac: Must download pyinstaller.
- To compile the evil script to a normal file with an icon of a pdf
What is a website?
Information Gathering
- IP address
- Domain name info
- Technologies used
- Other websites on the same server
- DNS records
- Files, sub-domains, directories
Crawling Subdomains
Crawling Directories
Ex:
- target.com/directory
- plus.google.com/discover
To guess login information, we will first have to look into the HTML code. We need to
specifically look for the <form> tag with an action attribute containing the login link.
After we have gathered this information, we can create a short python script which
opens a file with predetermined and define list of common passwords.
Vulnerability Scanner
Vulnerability_Scanner:
Three Types:
1. Persistent/Stored XSS → Code will continue to return and run with stored XSS
2. Reflected XSS → Code will only be executed when URL is run
3. DOM Based → Ran on the client side without having communication on the web
server
Discovering XSS
- Try to inject javascript code into the pages
- Test text boxes and url parameters on the form
- http://target.com/page.php?something=something
Reflected XSS
- None persistent, not stored
- Only work if the target visits a specially crafted URL
- Ex: http://target.com/page.php?something=<script>alert(“XSS”)<script>
Stored XSS
- Persistent, stored on the page or DB
- The injected code is executed every time the page is loaded
- Login
- Change Directory: cd /var/www/dvwa/dvwa/includes/
- Run Command: sudo nano dvva.Page.inc.php
- Look for setcookie(‘security’, ‘high’);
- Set to medium
- Then click x and y