0% found this document useful (0 votes)
26 views28 pages

Index

The document outlines various cryptographic techniques and their implementations, including substitution and transposition ciphers, RSA encryption, message authentication codes, digital signatures, Diffie-Hellman key exchange, IPsec configuration, and SSL/TLS for web security. Each section provides practical coding examples in Python for implementing these algorithms and protocols. The document serves as a comprehensive guide for understanding and applying fundamental cryptographic methods for secure communication.

Uploaded by

azizchauhanv3us
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)
26 views28 pages

Index

The document outlines various cryptographic techniques and their implementations, including substitution and transposition ciphers, RSA encryption, message authentication codes, digital signatures, Diffie-Hellman key exchange, IPsec configuration, and SSL/TLS for web security. Each section provides practical coding examples in Python for implementing these algorithms and protocols. The document serves as a comprehensive guide for understanding and applying fundamental cryptographic methods for secure communication.

Uploaded by

azizchauhanv3us
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/ 28

INDEX

1 .Implementing Substitution and Transposition Ciphers: Design and


implement algorithms to encrypt and decrypt messages using classical
substitution and transposition techniques
2. RSA Encryption and Decryption:Implement the RSA algorithm for
public-key encryption and decryption, and explore its properties and security
considerations.
3. Message Authentication Codes:Implement algorithms to generate and
verify message authentication codes (MACs) for ensuring data integrity and
authenticity
4. Digital Signatures: Implement digital signature algorithms such as
RSA-based signatures, and verify the integrity and authenticity of digitally
signed messages.
5. Key Exchange using Diffie-Hellman Implement the Diffie-Hellman key
exchange algorithm to securely exchange keys between two entities over an
insecure network.
6. IP Security (IPsec) Configuration:Configure IPsec on network devices to
provide secure communication and protect against unauthorized access and
attacks
7. Web Security with SSL/TLS:Configure and implement secure web
communication using SSL/TLS protocols, including certificate management
and secure session establishment.
8. Intrusion Detection System:Set up and configure an intrusion detection
system (IDS) to monitor network traffic and detect potential security breaches
or malicious activities.
PRACTICAL 1
Implementing Substitution and Transposition Ciphers: Design and implement algorithms
to encrypt and decrypt messages using classical substitution and transposition techniques.
SOLUTION:
SUBSTITUTION CIPHER
ENCRYPTION CODE:
def caesar_encrypt(plaintext, shift):
encrypted = ""
for char in plaintext:
if char.isalpha():
shift_base = ord('a') if char.islower() else ord('A')
encrypted += chr((ord(char) - shift_base + shift) % 26 + shift_base)
else:
encrypted += char
return encrypted

plaintext = "Hello, World!"


shift = 3
encrypted_text = caesar_encrypt(plaintext, shift)
print(f"Encrypted: {encrypted_text}")

DECRYPTION CODE:
def caesar_decrypt(ciphertext, shift):
return caesar_encrypt(ciphertext, -shift)
decrypted_text = caesar_decrypt(encrypted_text, shift)
print(f"Decrypted: {decrypted_text}")
TRANSPOSITION CIPHER
ENCRYPTION CODE:
def columnar_encrypt(plaintext, key):
# Ensure the plaintext length is a multiple of the key by padding with spaces if necessary
padding_length = (key - len(plaintext) % key) % key
plaintext_padded = plaintext + ' ' * padding_length

# Create an empty list of strings for each column


grid = [''] * key

# Distribute characters of plaintext into the grid columns


for i, char in enumerate(plaintext_padded):
grid[i % key] += char

# Concatenate columns to get the ciphertext


ciphertext = ''.join(grid)
return ciphertext

plaintext = "Hello, World!"


key = 5
encrypted_text = columnar_encrypt(plaintext, key)
print(f"Encrypted: {encrypted_text}")

DECRYPTION CODE:
def columnar_decrypt(ciphertext, key):
n = len(ciphertext) // key
grid = [''] * key
index = 0
for i in range(key):
grid[i] = ciphertext[index:index + n]
index += n
decrypted = ''.join([''.join(col) for col in zip(*grid)])
return decrypted

decrypted_text = columnar_decrypt(encrypted_text, key)


print(f"Decrypted: {decrypted_tex
PRACTICAL 2

Implement the RSA algorithm for public-key encryption and


decryption, and explore its properties and security considerations.
SOLUTION CODE:
import random
import math
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
def mod_inverse(e, phi):
d=0
x1, x2, y1, y2 = 0, 1, 1, 0
temp_phi = phi
while e > 0:
temp1 = temp_phi // e
temp2 = temp_phi - temp1 * e
temp_phi = e
e = temp2
x = x2 - temp1 * x1
y = y2 - temp1 * y1
x2 = x1
x1 = x
y2 = y1
y1 = y
if temp_phi == 1:
return y2 + phi
return 0
def generate_keypair(bitlength):
p = random.getrandbits(bitlength)

q = random.getrandbits(bitlength)
n=p*q
phi = (p - 1) * (q - 1)

e = random.randrange(1, phi)
g = gcd(e, phi)
while g != 1:
e = random.randrange(1, phi)
g = gcd(e, phi)
d = mod_inverse(e, phi)
return ((e, n), (d, n))
def encrypt(public_key, plaintext):
e, n = public_key
cipher = [pow(ord(char), e, n) for char in plaintext]
return cipher
def decrypt(private_key, ciphertext):
d, n = private_key
plain = [chr(pow(char, d, n)) for char in ciphertext]
return ''.join(plain)
# Example usage:
bitlength = 8
public_key, private_key = generate_keypair(bitlength)
message = "Hello, RSA!"
encrypted_message = encrypt(public_key, message)
print (message)
print("Encrypted:", encrypted_message)
decrypted_message = decrypt(private_key, encrypted_message)
PRACTICAL 3

Message Authentication Codes: Implement algorithms to generate and verify message


authentication codes (MACs) for ensuring data integrity and authenticity.

To implement Message Authentication Codes (MACs) for ensuring data integrity and authenticity,
you can follow these two steps:
1. Generating a MAC: A MAC is a tag or signature appended to the message, which is generated
using a secret key. It ensures the message’s authenticity and integrity.
2. Verifying a MAC: When the message is received, the recipient regenerates the MAC using the
same key and compares it with the one received to verify integrity.
Below are the steps to implement MAC generation and verification using Python’s hmac library:

Step 1: Generate a MAC

import hmac
import hashlib
def generate_mac(key, message):
# Create a new HMAC object using the provided key and SHA-256 as the hashing algorithm
hmac_obj = hmac.new(key, message, hashlib.sha256)
# Return the generated MAC (in hexadecimal form for better readability)
return hmac_obj.hexdigest()
# Example usage:
key = b'secret_key'
message = b'This is a secure message'
mac = generate_mac(key, message)
print("Generated MAC:", mac)

Step 2: Verify the MAC


def verify_mac(key, message, received_mac):
# Generate the MAC for the provided message
mac = generate_mac(key, message)
# Compare the received MAC with the generated one
if hmac.compare_digest(mac, received_mac):
return True
else:
return False

# Example usage:
received_mac = mac # From Step 1
is_valid = verify_mac(key, message, received_mac)
print("Is the MAC valid?", is_valid)
Explanation:
hmac.new(key, message, hashlib.sha256): This creates a new HMAC object using the provided key
and message with SHA-256 as the hashing algorithm.
hmac.compare_digest(a, b): This method securely compares two MACs to avoid timing attacks.
Conclusion:
The MAC generation and verification ensures that any change in the message will lead to a
mismatch during verification, thus detecting unauthorized modifications.
PRACTICAL 4

Digital Signatures: Implement digital signature algorithms such as RSA-based signatures, and
verify the integrity and authenticity of digitally signed messages.

Digital signatures use cryptographic algorithms to ensure the integrity and authenticity of a
message. One popular algorithm for digital signatures is RSA. The process involves signing a
message with a private key and verifying it with the corresponding public key. Below is a simple
implementation of RSA-based digital signatures in Python using the cryptography library.

Step 1: Install the cryptography library


If you don't have the library installed, you can install it using:
pip install cryptography

Step 2: Implement RSA Digital Signatures


1. Generate RSA Keys
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization
def generate_keys():
# Generate a private key using RSA
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048
# Generate corresponding public key
public_key = private_key.public_key()

# Return both keys


return private_key, public_key
# Example usage
private_key, public_key = generate_keys()
2. Sign a Message
To sign a message, we use the private key. This ensures that only the holder of the private key can
generate the signature.
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding

def sign_message(private_key, message):


# Sign the message using the private key
signature = private_key.sign(
message,
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA256()
return signature

# Example usage
message = b"Secure message"
signature = sign_message(private_key, message)
print("Signature:", signature.hex())

3. Verify the Signature

To verify a digital signature, we use the public key. This ensures that the message was signed by the
corresponding private key.

def verify_signature(public_key, message, signature):


try:
# Verify the message signature using the public key
public_key.verify(
signature,
message,
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA256()
)
return True
except:
return False

# Example usage
is_valid = verify_signature(public_key, message, signature)
print("Is the signature valid?", is_valid)

Key Serialization (Optional)


For saving and loading keys, you might want to serialize them to and from PEM
(Privacy-Enhanced Mail) format.
Serialize Private Key

def save_private_key(private_key, filename):


pem = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption() # Use encryption for extra security
)
with open(filename, 'wb') as pem_out:
pem_out.write(pem)
# Example usage
save_private_key(private_key, "private_key.pem")

Serialize Public Key


def save_public_key(public_key, filename):
pem = public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
with open(filename, 'wb') as pem_out:
pem_out.write(pem)
# Example usage
save_public_key(public_key, "public_key.pem")

Explanation:
Private Key: Used to sign messages. Only the signer should possess this key.
Public Key: Used to verify the signature. It is shared with anyone who needs to verify the message.
PSS (Probabilistic Signature Scheme): A padding scheme for RSA signatures, providing security
against attack.
PRACTICAL 5

Key Exchange using Diffie-Hellman: Implement the Diffie-Hellman key exchange algorithm to
securely exchange keys between two entities over an insecure network.
The Diffie-Hellman key exchange algorithm allows two entities to securely exchange cryptographic
keys over an insecure network. Each party generates a public and private key, exchanges the public
key, and derives a shared secret key that can be used for encryption or other cryptographic
purposes.

Below is a Python implementation of the Diffie-Hellman key exchange using the cryptography
library.
Step 1: Install the cryptography library
If you don't have the library installed, you can install it using:
pip install cryptography

Step 2: Implement Diffie-Hellman Key Exchange

1. Generate Private and Public Keys


Each party generates a private key and a corresponding public key.
from cryptography.hazmat.primitives.asymmetric import dh
from cryptography.hazmat.backends import default_backend

def generate_dh_keys():
# Generate Diffie-Hellman parameters (this can be shared between parties)
parameters = dh.generate_parameters(generator=2, key_size=2048, backend=default_backend())
# Generate a private key for a party
private_key = parameters.generate_private_key()
# Obtain the public key corresponding to the private key
public_key = private_key.public_key()
return private_key, public_key, parameters
# Example usage (for party A):
private_key_A, public_key_A, parameters = generate_dh_keys()

2. Exchange Public Keys


Each party would send their public key to the other party. For example, Party A sends
public_key_A to Party B, and Party B sends public_key_B to Party A. In this example, assume the
public key exchange has happened.

3. Generate Shared Secret


Once both parties have exchanged public keys, each party can generate the shared secret using
their private key and the other party's public key.
def generate_shared_secret(private_key, peer_public_key):
# Perform the key exchange to get the shared secret
shared_key = private_key.exchange(peer_public_key)
return shared_key
# Example usage:
# Assume Party A has Party B's public key and vice versa
# Party B's public key (received from Party B)
peer_public_key_B = public_key_A # In practice, you would receive this from Party B
# Generate the shared secret for Party A
shared_secret_A = generate_shared_secret(private_key_A, peer_public_key_B)
print("Shared Secret (Party A):", shared_secret_A.hex())

4. Deriving a Key for Symmetric Encryption


The raw shared secret can be used as-is, or you may derive a key from it using a key derivation
function (KDF). This is often done to generate a key of a specific length suitable for encryption.
Here is an example of how to derive a key using the HKDF (HMAC-based Key Derivation
Function):
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
from cryptography.hazmat.primitives import hashes
def derive_key(shared_secret):
# Derive a key using HKDF (you can use any hash function, like SHA-256)
derived_key = HKDF(
algorithm=hashes.SHA256(),
length=32, # Length of the key to be derived (32 bytes for AES-256)
salt=None, # Optionally add a salt for extra security
info=b'handshake data', # Context-specific information
).derive(shared_secret)

return derived_key

# Example usage:
derived_key_A = derive_key(shared_secret_A)
print("Derived Key (Party A):", derived_key_A.hex())

How It Works:

1. Key Generation: Both parties (A and B) generate a private key and a corresponding public key.
2. Public Key Exchange: Each party sends their public key to the other.
3. Shared Secret Calculation: Each party uses their own private key and the other party's public
key to compute a shared secret
4. Key Derivation: The shared secret can be used directly or passed through a key derivation
function to produce a key for encryption.
Conclusion:
The Diffie-Hellman key exchange ensures that even if a third party intercepts the public keys, they
cannot compute the shared secret without access to the private keys. This allows secure key
exchange over an insecure channel.
Let me know if you need further clarification or enhancements!
PRACTICAL 6

IPsec (Internet Protocol Security) is a protocol suite that provides secure communication over IP
networks. It ensures confidentiality, integrity, and authenticity of data transmitted between
network devices. IPsec can be configured in two main modes: Transport Mode and Tunnel Mode.
Here, we’ll outline how to configure IPsec on network devices like routers or firewalls for secure
communication using basic concepts, and we'll focus on configuring IPsec in Tunnel Mode, which is
often used for site-to-site VPNs.

Steps to Configure IPsec on Network Devices

1. Understand IPsec Components


Authentication Header (AH): Provides integrity and authentication for packets, but not encryption.
Encapsulating Security Payload (ESP): Provides encryption, integrity, and authentication.
Security Associations (SA): Defines how data will be secured (encryption algorithms, keys, etc.)
IKE (Internet Key Exchange): Handles key management and negotiation of security policies.
Example: Configuring IPsec on Cisco Routers (for Site-to-Site VPN)
Here, we’ll use two Cisco routers to create a secure VPN tunnel using IPsec. The basic steps
include:
Configuring ISAKMP/IKE Phase 1 for key exchange.
Defining IPsec (Phase 2) policies for encryption and integrity.
Applying these policies to traffic between two remote sites
Router 1 (Site A) Configuration:

1. Configure ISAKMP (IKE Phase 1)


ISAKMP establishes the first phase of the connection and manages the encryption and key
exchange settings.
Router(config)# crypto isakmp policy 10
Router(config-isakmp)# encryption aes 256 # Choose encryption (AES-256)
Router(config-isakmp)# hash sha256 # Hashing algorithm (SHA-256)
Router(config-isakmp)# authentication pre-share # Use pre-shared keys
Router(config-isakmp)# group 14 # DH Group (Group 14 recommended)
Router(config-isakmp)# lifetime 86400 # Lifetime of the key (in seconds)

2. Set the Pre-shared Key for IKE


Router(config)# crypto isakmp key mysecretkey address 192.168.2.1 # IP address of Router 2

3. Define IPsec (Phase 2) Policy


Define the transform set, which dictates how the data will be encrypted and authenticated.
Router(config)# crypto ipsec transform-set myset esp-aes 256 esp-sha-hmac

4. Create a Crypto Map


The crypto map ties everything together and specifies which traffic will be protected by IPsec.
Router(config)# crypto map mymap 10 ipsec-isakmp
Router(config-crypto-map)# set peer 192.168.2.1 # Remote peer (Router 2 IP)
Router(config-crypto-map)# set transform-set myset # Use transform set
Router(config-crypto-map)# match address 100 # Match interesting traffiv

5. Define Interesting Traffic (Access Control List)


Specify which traffic should go through the IPsec tunnel.
Router(config)# access-list 100 permit ip 10.1.1.0 0.0.0.255 10.2.2.0 0.0.0.255

6. Apply the Crypto Map to the Interface


Finally, apply the crypto map to the outbound interface.
Router(config)# interface gigabitEthernet 0/0
Router(config-if)# crypto map mymap
Router 2 (Site B) Configuration:

The configuration for Router 2 is very similar to Router 1, except with reversed IP addresses for the
peer and interesting traffic.
1. Configure ISAKMP (IKE Phase 1)
Router(config)# crypto isakmp policy 10
Router(config-isakmp)# encryption aes 256
Router(config-isakmp)# hash sha256
Router(config-isakmp)# authentication pre-share
Router(config-isakmp)# group 14
Router(config-isakmp)# lifetime 86400

2. Set the Pre-shared Key for IKE


Router(config)# crypto isakmp key mysecretkey address 192.168.1.1 # IP address of Router 1

3. Define IPsec (Phase 2) Policy


Router(config)# crypto ipsec transform-set myset esp-aes 256 esp-sha-hmac

4. Create a Crypto Map


Router(config)# crypto map mymap 10 ipsec-isakmp
Router(config-crypto-map)# set peer 192.168.1.1 # Remote peer (Router 1 IP)
Router(config-crypto-map)# set transform-set myset # Use transform set
Router(config-crypto-map)# match address 100 # Match interesting traffic

5. Define Interesting Traffic (Access Control List)


Router(config)# access-list 100 permit ip 10.2.2.0 0.0.0.255 10.1.1.0 0.0.0.255

6. Apply the Crypto Map to the Interface


Router(config)# interface gigabitEthernet 0/0
Router(config-if)# crypto map mymap
Verifying the IPsec Tunnel
To verify the status of the IPsec tunnel on each router, use the following commands:
Router# show crypto isakmp sa
Router# show crypto ipsec sa
Router# show crypto map
ISAKMP SAs (Security Associations) will show the state of the IKE Phase 1 connection.
IPsec SAs will show statistics and status of IPsec tunnels (Phase 2).
Conclusion:
With IPsec configured on network devices, you can ensure secure communication between two sites,
protecting data from unauthorized access or interception. IPsec is widely used for VPNs, secure
remote access, and encrypting traffic over public networks.
PRACTICAL 7

Web Security with SSL/TLS:Configure and implement secure web communication using SSL/TLS
protocols, including certificate management and secure session establishment.

SSL (Secure Sockets Layer) and TLS (Transport Layer Security) are cryptographic protocols
designed to secure communication over a network, typically for web traffic. TLS is the successor to
SSL and is considered more secure. Configuring and implementing SSL/TLS for secure web
communication requires enabling these protocols on web servers and managing certificates to
authenticate the server to the client.

Key Steps for Secure Web Communication using SSL/TLS:

1. Obtain and manage SSL/TLS certificates.


2. Configure your web server (e.g., Apache, Nginx) to use SSL/TLS.
3. Test the configuration to ensure it works properly.

Step 1: Obtain SSL/TLS Certificates


Certificates can be obtained from a trusted Certificate Authority (CA) like Let’s Encrypt, DigiCert,
or GlobalSign. These certificates prove that a website is legitimate and ensures that traffic is
encrypted.
Self-signed certificate: Used for testing purposes but not trusted by browsers.
CA-signed certificate: Trusted certificates from Certificate Authorities for production
environments.
Using Let's Encrypt (Free SSL/TLS Certificates):
Let’s Encrypt offers free SSL certificates that are widely trusted. You can use the Certbot tool to
easily obtain and install a certificate.
Install Certbot (Ubuntu/Debian):

sudo apt update


sudo apt install certbot python3-certbot-nginx # For Nginx; use `certbot-apache` for Apache

Obtain and Install a Certificate:

sudo certbot --nginx # For Nginx


# OR
sudo certbot --apache # For Apache

# Certbot will ask for domain name and email address for certificate.

Step 2: Configuring SSL/TLS on Web Servers


Here’s how to configure SSL/TLS on popular web servers: Nginx and Apache.
A. Nginx Configuration for SSL/TLS
1. Install Nginx (if it’s not installed):
sudo apt install nginx

2. Edit Nginx Configuration for SSL/TLS: Open the configuration file for your site, typically found
in /etc/nginx/sites-available/your_domain:sudo nano /etc/nginx/sites-available/your_domain

3. Add the SSL Configuration:


Example configuration:
server {
listen 80;
server_name your_domain.com www.your_domain.com;

# Redirect all HTTP traffic to HTTPS


return 301 https://$host$request_uri;
}

server {
listen 443 ssl;
server_name your_domain.com www.your_domain.com;

ssl_certificate /etc/letsencrypt/live/your_domain/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/your_domain/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;

# Root and index


root /var/www/your_domain;
index index.html;

# Additional security headers


add_header Strict-Transport-Security "max-age=31536000" always;
}
4. Restart Nginx to apply the changes:
sudo systemctl restart nginx

B. Apache Configuration for SSL/TLS


1. Install Apache (if it’s not installed):
sudo apt install apache2

2. Enable SSL Module in Apache:


sudo a2enmod ssl
sudo systemctl restart apache2

3. Edit Apache Configuration for SSL/TLS: Open the virtual host configuration file for your
domain:
sudo nano /etc/apache2/sites-available/your_domain.conf
4. Add SSL Configuration:
Example configuration:

<VirtualHost *:80>
ServerName your_domain.com
Redirect permanent / https://your_domain.com/
</VirtualHost>

<VirtualHost *:443>
ServerName your_domain.com
DocumentRoot /var/www/your_domain

SSLEngine on
SSLCertificateFile /etc/letsencrypt/live/your_domain/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/your_domain/privkey.pem
SSLProtocol all -SSLv3 -TLSv1 -TLSv1.1
SSLCipherSuite HIGH:!aNULL:!MD5

# Additional security headers


Header always set Strict-Transport-Security "max-age=31536000"
</VirtualHost>

5. Restart Apache to apply the changes:


sudo systemctl restart apache2

Step 3: Testing SSL/TLS Configuration


1. SSL Labs Test: Use SSL Labs (https://www.ssllabs.com/ssltest/) to check the SSL/TLS
configuration of your site. It will give you a grade and highlight potential issues.

2. Browser Testing: After configuring SSL/TLS, visit your website using https://your_domain.com.
Check that:
The browser shows the lock icon, indicating a secure connection.
There are no security warnings or certificate errors.
Best Practices for SSL/TLS Configuration:

1. Use Strong Encryption (TLSv1.2 or TLSv1.3): Disable older protocols like SSLv3, TLSv1.0, and
TLSv1.1, as they are vulnerable to attacks.
In Nginx:
ssl_protocols TLSv1.2 TLSv1.3;
In Apache:
SSLProtocol all -SSLv3 -TLSv1 -TLSv1.1

2. HTTP Strict Transport Security (HSTS): This forces browsers to use HTTPS, preventing
HTTP-based attacks.
In Nginx:
add_header Strict-Transport-Security "max-age=31536000" always;
In Apache:
Header always set Strict-Transport-Security "max-age=31536000

3. Enable OCSP Stapling (Optional): OCSP stapling enhances performance by providing faster
certificate validation.
In Nginx:
ssl_stapling on;
ssl_stapling_verify on;

Conclusion:
By configuring SSL/TLS on your web server, you ensure that communication between clients and
your server is encrypted, protecting it from eavesdropping and attacks. With proper certificate
management, secure protocols, and best practices like HSTS, your site will be more secure for users.
PRACTICAL 8

To set up and configure an Intrusion Detection System (IDS) programmatically, you can use Python
combined with a packet sniffing library like Scapy to monitor and analyze network traffic. Below is
a Python-based IDS example that captures network packets and detects potential anomalies such as
port scans and ICMP (ping) floods.

Code for a Basic IDS with Python and Scapy


# Import necessary libraries
from scapy.all import *
from collections import defaultdict
import time

# Dictionary to store the packet count for each IP


packet_count = defaultdict(int)
# Time interval to reset the count (e.g., every 60 seconds)
TIME_WINDOW = 60
# Maximum packet count threshold within the time window
MAX_PACKETS = 100

# Function to detect potential intrusion activity


def detect_intrusion(pkt):
# Check if the packet is an IP packet
if IP in pkt:
src_ip = pkt[IP].src

# Increment the packet count for this source IP


packet_count[src_ip] += 1

# Detect ICMP flood (many ping requests from the same source)
if pkt.haslayer(ICMP):
print(f"[ALERT] ICMP packet detected from {src_ip}")

# Detect potential port scan by checking if the source IP is sending packets to multiple different
ports
if TCP in pkt:
dst_port = pkt[TCP].dport
print(f"[INFO] TCP packet from {src_ip} to port {dst_port}")

# Print if the packet count exceeds the threshold within the time window
if packet_count[src_ip] > MAX_PACKETS:
print(f"[ALERT] Possible port scan or DoS attack from {src_ip}. Detected
{packet_count[src_ip]} packets in {TIME_WINDOW} seconds.")

# Function to reset packet counts every TIME_WINDOW seconds


def reset_packet_count():
while True:
time.sleep(TIME_WINDOW)
packet_count.clear()
print("[INFO] Resetting packet counts.")

# Function to start sniffing network packets


def start_sniffing():
# Start sniffing packets on the network
print("[INFO] Starting packet capture...")
sniff(prn=detect_intrusion, store=0)

# Main function
if __name__ == "__main__":
# Start the reset counter in a separate thread
from threading import Thread
reset_thread = Thread(target=reset_packet_count)
reset_thread.daemon = True
reset_thread.start()

# Start sniffing packets


start_sniffing()

Explanation:

1. Packet Sniffing: The sniff() function from the Scapy library captures live network traffic. The
prn=detect_intrusion parameter tells Scapy to pass each captured packet to the detect_intrusion()
function.
2. Detecting Anomalies:
ICMP Detection: If an ICMP packet is detected, the program logs that a ping request has been sent,
which might indicate a ping flood attack.
Port Scanning: If the same source IP is sending TCP packets to multiple different destination ports
in a short period, it could indicate a port scan.
Threshold-Based Alert: If more than MAX_PACKETS are detected from the same source IP in a
given time window (e.g., 60 seconds), it could indicate a denial-of-service (DoS) or port scan attack.
3. Resetting Packet Counts: A separate thread periodically clears the packet count every 60 seconds
(or any time interval you choose). This ensures the IDS is not permanently triggered by a burst of
traffic
Running the Program
1. Run the Script with Root Privileges: Since sniffing network packets usually requires root access,
you'll need to run the script with elevated privileges. On Linux or macOS: sudo python3
simple_ids.py
2. Monitor the Alerts: As packets are sniffed, the program will print information about ICMP
packets, TCP connections, and alert you when a potential intrusion is detected.
Enhancing the IDS:
You can further extend the functionality of this simple IDS:
1. Add more rules for detecting various types of attacks like SYN floods, DNS attacks, or SQL
injection attempts.
2. Log intrusion attempts to a file instead of just printing to the console.
3. Send alerts via email or integrate with security monitoring tools for better incident response.
4. Use machine learning algorithms to analyze packet patterns for anomalies, improving detection
accuracy.

Conclusion:
This Python-based IDS is a basic demonstration of how you can use Scapy to sniff network traffic
and detect potential security issues like ICMP floods and port scans. For a production environment,
you would likely use more sophisticated tools like Snort, Suricata, or OSSEC, but this gives you an
understanding of the core concepts behind an IDS.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy