CRYPTO_file

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 25

Lab Manual

Cryptography and Cyber Security

COMPUTER SCIENCE & ENGINEERING(R1UC505C)

COMPUTER SCIENCE & ENGINEERING

Fall 2024-2025
SUBJECT Cryptography and Cyber PROGRAMME B. Tech CSE and
Security Specializations

SUBJECT CODE R1UC505C SEMESTER 5

DURATION OF
CREDITS 1 13 Weeks
SEMESTER
PREREQUISITE SESSION
Python/Java 2 Hrs. per Week
SUBJECTS DURATION

Vision

"To be recognized globally as a premier School of Computer Science and Engineering for imparting
quality and value-based education within a multi-disciplinary and collaborative research-based
environment."

Mission
The mission of the school is to:

M1: Develop a strong foundation in fundamentals of computing science and engineering with
responsiveness towards emerging technologies.

M2: Establish state-of-the-art facilities and adopt education 4.0 practices to analyze, develop, test
and deploy sustainable ethical IT solutions by involving multiple stakeholders.

M3: Foster multidisciplinary collaborative research in association with academia and industry
through focused research groups, Centre of Excellence, and Industry Oriented R&D Labs.
PROGRAM EDUCATIONAL OBJECTIVES
The Graduates of Computer Science and Engineering shall:

PEO1: be engaged with leading Global Software Services and Product development
companies handling projects in cutting edge technologies.

PEO2: serve in technical or managerial roles at Government firms, Corporates and contributing to the
society as successful entrepreneurs through startup.

PEO3: undertake higher education, research or academia at institutions of transnational reputation.

PROGRAMME SPECIFIC OUTCOME (PSO):


The students of Computer Science and Engineering shall:

PSO1: Have the ability to work with emerging technologies in computing requisite to Industry 4.0.

PSO2: Demonstrate Engineering Practice learned through industry internship and research project to
solve live problems in various domains.
PROGRAMME OUTCOME (PO):
PO1 Computing Science knowledge: Apply the knowledge of mathematics, statistics, computing
science and information science fundamentals to the solution of complex computer application
problems.

PO2 Problem analysis: Identify, formulate, review research literature, and analyze complex
computing science problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and computer sciences.

PO3 Design/development of solutions: Design solutions for complex computing problems and design
system components or processes that meet the specified needs with appropriate consideration for the
public health and safety, and the cultural, societal, and environmental considerations.

PO4 Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.
PO5 Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
computing science and IT tools including prediction and modeling to complex computing activities
with an understanding of the limitations.

PO6 IT specialist and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
professional computing science and information science practice.

PO7 Environment and sustainability: Understand the impact of the professional computing
science solutions in societal and environmental contexts, and demonstrate the knowledge of, and
need for sustainable development.

PO8 Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the computing science practice.

PO9 Individual and team work: Function effectively as an individual, and as a member or leader
in diverse teams, and in multidisciplinary settings.
PO10 Communication: Communicate effectively on complex engineering activities with the IT
analyst community and with society at large, such as, being able to comprehend and write effective
reports and design documentation, make effective presentations, and give and receive clear
instructions.

PO11 Project management and finance: Demonstrate knowledge and understanding of the
computing science and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.

PO12 Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
List of Programs

Programs
1. To develop a program to implement encryption and decryption using rail fence
transportation technique.
To develop a program to implement Data Encryption Standard for encryption and
decryption.

To develop a program to implement Advanced Encryption Standard for encryption


and decryption.

Develop a program to implement RSA algorithm for encryption and decryption.

Develop a program to implement Diffie Hellman Exchange Algorithm for


encryption and decryption.

Develop a program to implement Secure Hash Algorithm.

To write a program to implement the digital signature scheme in C++/Python


To Deploy an IDS to monitor network traffic and detect potential intrusion
attempts.

To Configure a firewall to protect a network and test its effectiveness against


various types of attacks.

10 To Identify and exploit vulnerabilities in a web application to understand common


web security issues.
11 To demonstrate intrusion detection system(ids) using the tool snort.

12 To explore automated and penetration tools on network (KF Sensor).

13 To write a detail step to configure snort tools.

14 Use Wireshark to capture and analyze the network traffic to observe how WPA2
encrypts data and protects against unauthorized access.

Value Added Programs:

1. Implementation of Advanced Encryption Standard (AES):


2. Implementation of RSA Algorithm:
3. Implementation of Diffie-Hellman Key Exchange:

Course Outcomes

Upon successful completion of this course, students will be able to


Description: Build a program to facilitate secure key exchange between two parties using the Diffie-Hellman
CO1 Understand the Classical Encryption Techniques like Substitution and Transposition
and apply them for Encryption and Decryption of Messages.

CO2 Understand and apply DES, AES, RSA Encryption and Decryption Techniques for
Network Security.
CO3 Implement Hash Algorithms viz., MAC, and HMAC. Determine the appropriate
changes that can improve network security by selection of appropriate services.
CO4 Analyze the Cyber security requirements and able to design better services by selecting
better encryption algorithms. Students should also be able to compare different ciphers
and suggest improvements.
CO-PO-PSO MAPPING:

Continuous Assessment Pattern

Practical ETE Total


IA

100 0 100

Rubrics for Practical IA

S. No. Rubrics – Parts Marks

1 Performance 2

2 Result 3

3 File 2
4 Viva 3

Total 10
Experiment-1

# AIM: Implement encryption and decryption using Rail Fence Cipher technique.
# The Rail Fence Cipher is a form of transposition cipher that rearranges the characters of a plaintext
message
# into a zigzag pattern across a specified number of "rails" or rows and then reads them off row by row.

def rail_fence_encrypt(text: str, key: int) -> str:


"""Encrypts the text using Rail Fence Cipher with the given key."""
rail = ['' for _ in range(key)]
dir_down = None
row = 0
for char in text:
rail[row] += char
if row == 0 or row == key - 1:
dir_down = not dir_down
row += 1 if dir_down else -1
return ''.join(rail)
def rail_fence_decrypt(cipher_text: str, key: int) -> str:
"""Decrypts the cipher text using Rail Fence Cipher with the given key."""
rail = [['' for _ in range(len(cipher_text))] for _ in range(key)]
dir_down = None
row = 0
# Mark the pattern in the rail
for i in range(len(cipher_text)):
rail[row][i] = '*'
if row == 0 or row == key - 1:
dir_down = not dir_down
row += 1 if dir_down else -1
# Fill the rail with the cipher text
index = 0
for r in range(key):
for c in range(len(cipher_text)):
if rail[r][c] == '*' and index < len(cipher_text):
rail[r][c] = cipher_text[index]
index += 1

# Read the message in zigzag pattern


result = []
row = 0
dir_down = None

for i in range(len(cipher_text)):
result.append(rail[row][i])
if row == 0 or row == key - 1:
dir_down = not dir_down
row += 1 if dir_down else -1
return ''.join(result)
def main():
"""Main function to test Rail Fence Cipher encryption and decryption."""
text = input("Enter the text to encrypt: ")
key = int(input("Enter the key (number of rails): "))
encrypted_text = rail_fence_encrypt(text, key)
print("Encrypted Text:", encrypted_text)
decrypted_text = rail_fence_decrypt(encrypted_text, key)
print("Decrypted Text:", decrypted_text)\
if __name__ == "__main__":
main()
Experiment-2

AIM:Data Encryption Standard (DES) Implementation: The Data Encryption Standard (DES)
is a symmetric-key block cipher that encrypts data in 64-bit blocks using a 56-bit key. DES
employs a series of permutations and substitutions based on the key to transform plaintext into
ciphertext and vice versa. The algorithm operates in multiple rounds of processing, each involving
expansion, substitution, permutation, and mixing of the key and data. DES is used for secure data
transmission and storage, and while it has been largely superseded by more secure algorithms like
AES, it remains a fundamental concept in cryptography.

Python Code for DES Encryption and Decryption:

from Crypto.Cipher import DES


from Crypto.Util.Padding import pad, unpad
import binascii

def des_encrypt(plain_text: str, key: bytes) -> str:


"""Encrypts the plain_text using DES with the given key."""
cipher = DES.new(key, DES.MODE_ECB)
padded_text = pad(plain_text.encode(), DES.block_size)
encrypted_text = cipher.encrypt(padded_text)
return binascii.hexlify(encrypted_text).decode()

def des_decrypt(encrypted_text: str, key: bytes) -> str:


"""Decrypts the encrypted_text using DES with the given key."""
cipher = DES.new(key, DES.MODE_ECB)
encrypted_text_bytes = binascii.unhexlify(encrypted_text)
padded_text = cipher.decrypt(encrypted_text_bytes)
plain_text = unpad(padded_text, DES.block_size).decode()
return plain_text

def main():
"""Main function to test DES encryption and decryption."""
plain_text = input("Enter the text to encrypt: ")
key = input("Enter the 8-byte key (hex format): ").encode()

# Ensure the key is exactly 8 bytes long


if len(key) != 8:
print("Key must be 8 bytes long.")
return

encrypted_text = des_encrypt(plain_text, key)


print("Encrypted Text (hex):", encrypted_text)

decrypted_text = des_decrypt(encrypted_text, key)


print("Decrypted Text:", decrypted_text)

if __name__ == "__main__":
main()
EXPERIMENT-3

AIM: Advanced Encryption Standard (AES) Implementation:


The Advanced Encryption Standard (AES) is a symmetric-key block cipher used for encrypting
and decrypting data. AES operates on 128-bit blocks using key sizes of 128, 192, or 256 bits. It is
known for its robustness and efficiency, making it the preferred choice for secure data encryption
in modern applications. AES consists of a series of transformations including substitution,
permutation, and mixing of the data and key, organized into multiple rounds. The algorithm
provides a high level of security and is widely adopted for protecting sensitive information.
from Crypto.Cipher import AES

from Crypto.Util.Padding import pad, unpad

import binascii

def aes_encrypt(plain_text: str, key: bytes) -> str:

"""Encrypts the plain_text using AES with the given key."""

cipher = AES.new(key, AES.MODE_CBC) # CBC (Cipher Block Chaining) mode

padded_text = pad(plain_text.encode(), AES.block_size)

encrypted_text = cipher.encrypt(padded_text)

return binascii.hexlify(cipher.iv + encrypted_text).decode() # Include IV with ciphertext

def aes_decrypt(encrypted_text: str, key: bytes) -> str:

"""Decrypts the encrypted_text using AES with the given key."""

encrypted_text_bytes = binascii.unhexlify(encrypted_text)

iv = encrypted_text_bytes[:AES.block_size] # Extract IV from the beginning

encrypted_text_bytes = encrypted_text_bytes[AES.block_size:]

cipher = AES.new(key, AES.MODE_CBC, iv) # Use the same IV for decryption

padded_text = cipher.decrypt(encrypted_text_bytes)

plain_text = unpad(padded_text, AES.block_size).decode()

return plain_text
def main():

"""Main function to test AES encryption and decryption."""

plain_text = input("Enter the text to encrypt: ")

key = input("Enter the key (16, 24, or 32 bytes in hex format): ").encode()

# Ensure the key is 16, 24, or 32 bytes long

if len(key) not in [16, 24, 32]:

print("Key must be 16, 24, or 32 bytes long.")

return

encrypted_text = aes_encrypt(plain_text, key)

print("Encrypted Text (hex):", encrypted_text)

decrypted_text = aes_decrypt(encrypted_text, key)

print("Decrypted Text:", decrypted_text)

if __name__ == "__main__":

main()
EXPERIMENT-4

AIM: RSA Algorithm Implementation: The RSA (Rivest-Shamir-Adleman) algorithm is a


widely used asymmetric encryption technique that relies on the mathematical properties of prime
numbers. It enables secure data encryption and decryption using a pair of keys: a public key for
encryption and a private key for decryption. RSA is based on the difficulty of factoring large
composite numbers, which provides its security. The algorithm involves key generation,
encryption, and decryption processes that are fundamental to modern cryptographic systems.
Python Code for RSA Encryption and Decryption:

Below is a Python implementation of the RSA algorithm using the pycryptodome library.

This library provides cryptographic functions including RSA key generation, encryption, and
decryption

from Crypto.PublicKey import RSA


from Crypto.Cipher import PKCS1_OAEP
import binascii

def generate_rsa_keys():
"""Generates a pair of RSA keys (public and private)."""
key = RSA.generate(2048) # Generate a 2048-bit RSA key
private_key = key.export_key()
public_key = key.publickey().export_key()
return private_key, public_key

def rsa_encrypt(plain_text: str, public_key: bytes) -> str:


"""Encrypts the plain_text using RSA with the given public key."""
public_key = RSA.import_key(public_key)
cipher = PKCS1_OAEP.new(public_key)
encrypted_text = cipher.encrypt(plain_text.encode())
return binascii.hexlify(encrypted_text).decode()

def rsa_decrypt(encrypted_text: str, private_key: bytes) -> str:


"""Decrypts the encrypted_text using RSA with the given private key."""
private_key = RSA.import_key(private_key)
cipher = PKCS1_OAEP.new(private_key)
encrypted_text_bytes = binascii.unhexlify(encrypted_text)
decrypted_text = cipher.decrypt(encrypted_text_bytes)
return decrypted_text.decode()
def main():
"""Main function to test RSA encryption and decryption."""
# Generate RSA keys
private_key, public_key = generate_rsa_keys()

print("RSA Keys Generated:")


print("Private Key:")
print(private_key.decode())
print("Public Key:")
print(public_key.decode())

# Encrypt and decrypt a message


plain_text = input("Enter the text to encrypt: ")

encrypted_text = rsa_encrypt(plain_text, public_key)


print("Encrypted Text (hex):", encrypted_text)

decrypted_text = rsa_decrypt(encrypted_text, private_key)


print("Decrypted Text:", decrypted_text)

if __name__ == "__main__":
main()
EXPERIMENT-5

AIM: Diffie-Hellman Key Exchange Implementation: The Diffie-Hellman Key


Exchange algorithm is a cryptographic method used to securely share encryption keys over
an insecure communication channel. It allows two parties to each generate a shared secret
key without directly transmitting it. This key can then be used for symmetric encryption.
The security of Diffie-Hellman relies on the difficulty of solving the discrete logarithm
problem. The algorithm involves the use of large prime numbers and their generators to
facilitate the key exchange.
.
import random

def generate_prime_and_generator():
"""Generates a prime number and a generator for the Diffie-Hellman key exchange."""
# For simplicity, using a small prime and generator
# In practice, use large primes for security
p = 23 # A small prime number
g = 5 # A small generator (primitive root) modulo p
return p, g

def generate_private_key():
"""Generates a private key."""
return random.randint(1, 100)

def generate_public_key(private_key, p, g):


"""Generates the public key based on private key, prime, and generator."""
return pow(g, private_key, p)

def compute_shared_secret(public_key, private_key, p):


"""Computes the shared secret using the public key, private key, and prime."""
return pow(public_key, private_key, p)

def main():
"""Main function to demonstrate Diffie-Hellman Key Exchange."""
# Generate prime and generator
p, g = generate_prime_and_generator()
print(f"Prime (p): {p}")
print(f"Generator (g): {g}")

# Generate private keys for Alice and Bob


private_key_alice = generate_private_key()
private_key_bob = generate_private_key()
print(f"Alice's Private Key: {private_key_alice}")
print(f"Bob's Private Key: {private_key_bob}")
# Generate public keys for Alice and Bob
public_key_alice = generate_public_key(private_key_alice, p, g)
public_key_bob = generate_public_key(private_key_bob, p, g)
print(f"Alice's Public Key: {public_key_alice}")
print(f"Bob's Public Key: {public_key_bob}")

# Compute shared secrets


shared_secret_alice = compute_shared_secret(public_key_bob, private_key_alice, p)
shared_secret_bob = compute_shared_secret(public_key_alice, private_key_bob, p)

print(f"Alice's Computed Shared Secret: {shared_secret_alice}")


print(f"Bob's Computed Shared Secret: {shared_secret_bob}")

# Check if both shared secrets match


if shared_secret_alice == shared_secret_bob:
print("Key exchange successful. Both parties have the same shared secret.")
else:
print("Key exchange failed. Shared secrets do not match.")

if __name__ == "__main__":
main()
EXPERIMENT-6

AIM: Secure Hash Algorithm (SHA) Implementation: The Secure Hash Algorithm
(SHA) is a family of cryptographic hash functions designed to produce a fixed-size hash
value from input data of arbitrary size. These functions are widely used in data integrity
checks, digital signatures, and password storage. SHA functions generate hash values that
are unique to each unique input, providing a mechanism for data verification and ensuring
that even a small change in input results in a drastically different hash. The most common
SHA variants are SHA-1, SHA-256, and SHA-3, each providing different levels of
security.

import hashlib

def sha256_hash(input_data: str) -> str:

"""Generates SHA-256 hash of the input data."""

sha256 = hashlib.sha256()

sha256.update(input_data.encode())

return sha256.hexdigest()

def main():

"""Main function to demonstrate SHA-256 hashing."""

input_data = input("Enter the data to hash: ")

hash_value = sha256_hash(input_data)

print("SHA-256 Hash:", hash_value)

if __name__ == "__main__":

main()
EXPERIMENT-7

AIM: Digital Signature Scheme Implementation: A digital signature scheme is a


cryptographic technique used to verify the authenticity and integrity of a digital message
or document. It ensures that a message has not been altered and confirms the identity of
the sender. Digital signatures are based on asymmetric encryption, where a pair of keys—
private and public—is used. The private key is used to create the signature, and the public
key is used to verify it. This mechanism provides authentication, data integrity, and non-
repudiation in digital communications.
from Crypto.PublicKey import RSA
from Crypto.Signature import pkcs1_15
from Crypto.Hash import SHA256
import binascii

def generate_keys():
"""Generates RSA public and private keys."""
key = RSA.generate(2048) # Generate a 2048-bit RSA key
private_key = key.export_key()
public_key = key.publickey().export_key()
return private_key, public_key

def sign_message(message: str, private_key: bytes) -> str:


"""Signs the message using the RSA private key."""
private_key = RSA.import_key(private_key)
h = SHA256.new(message.encode()) # Hash the message
signature = pkcs1_15.new(private_key).sign(h) # Sign the hash
return binascii.hexlify(signature).decode() # Encode signature in hexadecimal

def verify_signature(message: str, signature: str, public_key: bytes) -> bool:


"""Verifies the signature using the RSA public key."""
public_key = RSA.import_key(public_key)
h = SHA256.new(message.encode()) # Hash the message
signature = binascii.unhexlify(signature) # Decode signature from hexadecimal
try:
pkcs1_15.new(public_key).verify(h, signature) # Verify the signature
return True # Signature is valid
except (ValueError, TypeError):
return False # Signature is invalid

def main():
"""Main function to demonstrate digital signature scheme."""
# Generate RSA keys
private_key, public_key = generate_keys()

print("RSA Keys Generated:")


print("Private Key:")
print(private_key.decode())
print("Public Key:")
print(public_key.decode())

# Sign a message
message = input("Enter the message to sign: ")
signature = sign_message(message, private_key)
print("Signature (hex):", signature)

# Verify the signature


verification_result = verify_signature(message, signature, public_key)
if verification_result:
print("Signature is valid.")
else:
print("Signature is invalid.")

if __name__ == "__main__":
main()

EXPERIMENT-8
AIM: Intrusion Detection System (IDS) Deployment: An Intrusion Detection System
(IDS) is a network security tool designed to monitor network traffic for suspicious
activities and potential intrusion attempts. The IDS analyzes network packets and logs to
detect patterns indicative of malicious activities. There are two primary types of IDS:
Network-Based IDS (NIDS) and Host-Based IDS (HIDS). NIDS monitors network traffic
across an entire network segment, while HIDS focuses on individual host systems. The
IDS can alert administrators to potential security breaches, helping to protect sensitive
data and network

from scapy.all import *


import re
# Define a list of suspicious IP addresses and ports
suspicious_ips = ['192.168.1.10', '10.0.0.5']
suspicious_ports = [22, 23]

def packet_callback(packet):
"""Callback function to process each packet."""
if packet.haslayer(IP):
ip_src = packet[IP].src
ip_dst = packet[IP].dst
src_port = packet.sport if packet.haslayer(TCP) else None
dst_port = packet.dport if packet.haslayer(TCP) else None

# Check for suspicious IP addresses


if ip_src in suspicious_ips or ip_dst in suspicious_ips:
print(f"[ALERT] Suspicious IP detected: {ip_src} -> {ip_dst}")

# Check for suspicious ports


if src_port in suspicious_ports or dst_port in suspicious_ports:
print(f"[ALERT] Suspicious port detected: {src_port} -> {dst_port}")

# Example: Detecting HTTP traffic to unusual domain


if packet.haslayer(DNS) and packet[DNS].qr == 0: # DNS Query
domain = packet[DNS].qd.qname.decode()
if re.search(r'\bexample\.com\b', domain):
print(f"[ALERT] Suspicious domain accessed: {domain}")

def main():
"""Main function to start the packet sniffing."""
print("Starting IDS. Monitoring network traffic...")
sniff(prn=packet_callback, store=0, filter="ip")
if __name__ == "__main__":
main()
EXPERIMENT-9

AIM:-Firewall Configuration and Effectiveness Testing: A firewall is a network


security system that monitors and controls incoming and outgoing network traffic based on
predetermined security rules. Its primary role is to establish a barrier between a trusted
internal network and untrusted external networks, such as the Internet. Configuring a
firewall properly helps protect the network from unauthorized access, attacks, and other
security threats. Testing the firewall's effectiveness involves simulating various types of
attacks to ensure that the firewall rules are properly enforced and that the network remains
secure.

sudo apt-get update


sudo apt-get install iptables
#!/bin/bash

# Flush existing rules


iptables -F
iptables -t nat -F
iptables -t mangle -F
iptables -X

# Default policies
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT
# Allow loopback traffic
iptables -A INPUT -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT
# Allow established and related connections
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
# Allow SSH (port 22) and HTTP (port 80)
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
# Log dropped packets
iptables -A INPUT -j LOG --log-prefix "Dropped Packet: "
# Save rulesiptables-save > /etc/iptables/rules.v4
EXPERIMENT-10

AIM:- Identify and Exploit Vulnerabilities in a Web Application: Understanding and exploiting
vulnerabilities in a web application helps in identifying common web security issues and improving the
application's security posture. By performing ethical hacking and vulnerability assessment, security
professionals can uncover weaknesses that could be exploited by malicious actors. This process involves
scanning for vulnerabilities, exploiting them in a controlled manner, and recommending fixes to enhance
security.

Steps to Identify and Exploit Web Application Vulnerabilities:

1. Reconnaissance and Information Gathering:

Before testing for vulnerabilities, gather information about the web application, such as its structure,
technologies used, and entry points.

Tools and Techniques:

 Web Browsers: Use tools like Chrome Developer Tools to inspect web application behavior.
 Nmap: Scan the web server to gather information about open ports and services.

nmap -p 80,443 <target_ip>

Whois Lookup: Get information about the domain registration and ownership.

whois <target_domain>

Web Technologies Fingerprinting: Use tools like Wappalyzer or BuiltWith to identify technologies used by
the web application.

Scanning for Vulnerabilities:

Perform automated and manual scans to detect common web vulnerabilities.

Automated Scanning Tools:

 OWASP ZAP: An open-source security tool for finding vulnerabilities in web applications.
 Burp Suite: A comprehensive security testing tool with features for scanning and analyzing web
applications.
access. For different purposes, health records must be kept safe and confidential. Blockchain helps for the
decentralized protection of data in healthcare and avoids specific threats.

Nikto: A web server scanner that detects various vulnerabilities.

nikto -h <target_url>

Manual Testing Techniques:

 Input Validation: Test form fields, URL parameters, and other input fields for improper
validation and sanitization.
 Directory Traversal: Attempt to access restricted directories using patterns like ../.

http://<target_url>/../../etc/passwd

SQL Injection: Test for SQL injection vulnerabilities by injecting malicious SQL queries into input fields.

' OR '1'='1

Exploiting Vulnerabilities:

Once vulnerabilities are identified, they can be exploited to understand their impact.

Common Exploits:

 Cross-Site Scripting (XSS): Inject malicious scripts into web pages.

<script>alert('XSS')</script>

SQL Injection: Extract data or perform unauthorized actions in the database

' UNION SELECT null, username, password FROM users--

Cross-Site Request Forgery (CSRF): Trick users into performing actions on behalf of an attacker.

<img src="http://<target_url>/change_email?email=attacker@example.com" />

File Upload Vulnerabilities: Upload and execute malicious files.

<?php system($_GET['cmd']); ?>


Reporting and Mitigation:

Document the findings, including details about each vulnerability, its impact, and recommended fixes.

Reporting:

 Vulnerability Description: Explain the nature of each vulnerability.


 Proof of Concept (PoC): Provide examples of how the vulnerability can be exploited.
 Impact Assessment: Describe the potential impact if the vulnerability were exploited.
 Recommendations: Suggest remediation steps and best practices to fix the vulnerabilities.

Mitigation Techniques:

 Input Validation: Implement server-side validation and sanitization of user inputs.


 Prepared Statements: Use prepared statements to prevent SQL injection.
 Content Security Policy (CSP): Implement CSP headers to mitigate XSS attacks.
 Secure File Upload: Validate and restrict file uploads to prevent malicious file execution.

Example Python Code for Simple Vulnerability Testing:

Here’s an example of a Python script to test for SQL Injection vulnerability using the requests library:

import requests

def test_sql_injection(url, param):

"""Test for SQL Injection vulnerability."""

payloads = ["' OR '1'='1", '" OR "1"="1', "' OR 1=1--", '" OR 1=1--']

for payload in payloads:

test_url = f"{url}?{param}={payload}"

response = requests.get(test_url)

if "error" not in response.text.lower() and "database" in response.text.lower():

print(f"Possible SQL Injection vulnerability found with payload: {payload}")

else:

print(f"No SQL Injection vulnerability detected with payload: {payload}")

if __name__ == "__main__":

target_url = "http://example.com/vulnerable_page"

parameter = "id"

test_sql_injection(target_url, parameter)
Conclusion:

1. Reconnaissance: Gather information about the target web application to understand its structure and
technologies.
2. Scanning: Use automated tools and manual techniques to identify vulnerabilities.
3. Exploitation: Safely exploit identified vulnerabilities to assess their impact.
4. Reporting and Mitigation: Document findings and provide recommendations for fixing vulnerabilities.
Value Added List of Experiments

1. To Deploy an IDS to monitor network traffic and detect potential intrusion


attempts
2. Simulation To Identify vulnerabilities in a given network and assess their
potential impact.
3. To Set up a secure wireless network and understand various security
protocols.

Dr. Abhishek Srivastava


Name of the Course Coordinator: Signature

You might also like