Experiments in Cryptography and System Security

Experiment 1: Implement the product cipher using Substitution and Transposition ciphers

#include <iostream>
#include <algorithm>

void substitution(std::string& text, int key) {
    for (char& c : text) {
        if (isalpha(c)) {
            char base = islower(c) ? 'a' : 'A';
            c = (c - base + key) % 26 + base;
        }
    }
}

void transposition(std::string& text, const std::string& key) {
    int col = key.length();
    int row = (text.length() + col - 1) / col;
    char matrix[row][col];

    int index = 0;
    for (int i = 0; i < row; ++i)
        for (int j = 0; j < col; ++j)
            matrix[i][j] = text[index++];

    for (int i = 0; i < col; ++i)
        for (int j = 0; j < row; ++j)
            text += matrix[j][i];

    text = text.substr(index);
}

int main() {
    std::string plaintext, key;
    
    // Input
    std::cout << "Enter plain text: ";
    std::getline(std::cin, plaintext);
    
    // Substitution
    int substitutionKey;
    std::cout << "Enter substitution key: ";
    std::cin >> substitutionKey;
    substitution(plaintext, substitutionKey);

    // Transposition
    std::cin.ignore();  // Clear newline from the input buffer
    std::cout << "Enter transposition key: ";
    std::getline(std::cin, key);
    transposition(plaintext, key);

    // Output
    std::cout << "Cipher text: " << plaintext << std::endl;

    return 0;
}

Experiment 2: Study the use of network reconnaissance tools/commands

#include <iostream>
#include <algorithm>

void substitution(std::string& text, int key) {
    for (char& c : text) {
        if (isalpha(c)) {
            char base = islower(c) ? 'a' : 'A';
            c = (c - base + key) % 26 + base;
        }
    }
}

void transposition(std::string& text, const std::string& key) {
    int col = key.length();
    int row = (text.length() + col - 1) / col;
    char matrix[row][col];

    int index = 0;
    for (int i = 0; i < row; ++i)
        for (int j = 0; j < col; ++j)
            matrix[i][j] = text[index++];

    for (int i = 0; i < col; ++i)
        for (int j = 0; j < row; ++j)
            text += matrix[j][i];

    text = text.substr(index);
}

int main() {
    std::string plaintext, key;
    
    // Input
    std::cout << "Enter plain text: ";
    std::getline(std::cin, plaintext);
    
    // Substitution
    int substitutionKey;
    std::cout << "Enter substitution key: ";
    std::cin >> substitutionKey;
    substitution(plaintext, substitutionKey);

    // Transposition
    std::cin.ignore();  // Clear newline from the input buffer
    std::cout << "Enter transposition key: ";
    std::getline(std::cin, key);
    transposition(plaintext, key);

    // Output
    std::cout << "Cipher text: " << plaintext << std::endl;

    return 0;
}

Experiment 3: Develop your own hashing algorithm

#include <bits/stdc++.h>
using namespace std;
unsigned int customHash(const string& input) {
 const unsigned int prime = 31;
 const unsigned int mod = 1000000007; 
 unsigned int hash = 0;
 unsigned int power = 1;
 for (char c : input) {
 hash = (hash + (c - 'a' + 1) * power) % mod; 
 power = (power * prime) % mod; 
 }
 return hash;
}
int main() {
 string message;
 cout<<"Enter the message : ";
 getline(cin,message);
 unsigned int hashValue = customHash(message);
 cout << "Hash value of '" << message << "': " << hashValue << endl;
 return 0;
}

Experiment 4: Security Testing using Burp Suite

We successfully implemented a Brute Force attack on the website
http://testphp.vulnweb.com/login.php using Burp Suite.
```html

Experiment 8: Study of packet sniffer tools: Wireshark

Aim: Study of packet sniffer tools: Wireshark

  1. Download and install Wireshark and capture ICMP, TCP, and HTTP packets in promiscuous mode.
  2. Explore how the packets can be traced based on different filters

Hardware / Software Required: Unix/Linux/Windows, Wireshark

Theory:

Wireshark, a network analysis tool formerly known as Ethereal, captures packets in real time and displays them in a human-readable format. Wireshark includes filters, color-coding, and other features that let you dig deep into network traffic and inspect individual packets.

Features of Wireshark:

  • Available for UNIX and Windows.
  • Capture live packet data from a network interface.
  • Open files containing packet data captured with tcpdump/WinDump, Wireshark, and a number of other packet capture programs.
  • Import packets from text files containing hex dumps of packet data.
  • Display packets with very detailed protocol information.
  • Export some or all packets in a number of capture file formats.
  • Filter packets on many criteria.
  • Search for packets on many criteria.
  • Colorize packet display based on filters.
  • Create various statistics.

Capturing Packets:

After downloading and installing Wireshark, you can launch it and click the name of an interface under Interface List to start capturing packets on that interface. For example, if you want to capture traffic on the wireless network, click your wireless interface. You can configure advanced features by clicking Capture Options.

As soon as you click the interface‘s name, you‘ll see the packets start to appear in real time. Wireshark captures each packet sent to or from your system. If you‘re capturing on a wireless interface and have promiscuous mode enabled in your capture options, you‘ll also see the other packets on the network.

Wireshark uses colors to help you identify the types of traffic at a glance. By default, green is TCP traffic, dark blue is DNS traffic, light blue is UDP traffic, and black identifies TCP packets with problems — for example, they could have been delivered out-of-order.

Filtering Packets:

If you‘re trying to inspect something specific, such as the traffic a program sends when phoning home, it helps to close down all other applications using the network so you can narrow down the traffic. Still, you‘ll likely have a large amount of packets to sift through. That‘s where Wireshark‘s filters come in.

The most basic way to apply a filter is by typing it into the filter box at the top of the window and clicking Apply (pressing Enter). For example, type "dns" and you‘ll see only DNS packets. When you start typing, Wireshark will help you autocomplete your filter.

Learning Outcomes: The learner will be able to

  • Sniff network packets and study insights of packets to get detailed network information.
  • Understand the need for traffic analysis.
  • Understand how packet sniffing is done using Wireshark.
  • Trace and understand various packets from dynamic traffic.

Result and Discussion:

Wireshark installation and network traffic analysis using packet sniffing is done. Detailed information about packets is explored by applying filters.

Conclusion:

Experiment 9: Perform and analyze at least two injection attacks

Aim: Perform and analyze at least two injection attacks

Theory:

SQL Injection: Attackers can use SQL injection on an application if it has dynamic database queries that use string concatenation and user supplied input. To avoid SQL injection flaws, developers need to: Stop writing dynamic queries with string concatenation or; Prevent malicious SQL input from being included in executed queries.

HTML Injection: HTML injection is a type of attack where malicious HTML code is inserted into a website. This can lead to a variety of issues, from minor website defacement to serious data breaches. Unlike other web vulnerabilities, HTML injection targets the markup language that forms the backbone of most websites.

Output:

SQL Injection (Technique 1)

Payload 1:

Payload 2

Payload 3

Final Output

SQL Injection (Technique 2 – sqlmap)

HTML Injection

Payload 1: (<h1>hello</h1>)

Payload 2 (<iframe src="https://www.tcetmumbai.in" title="test"></iframe>)

Payload 3 (<button type="button">Click Me!</button>)

Conclusion:

Experiment 10: Cross Site Scripting(XSS)

Aim: To execute Cross Site Scripting attack

Theory:

Cross-Site Scripting (XSS) is a security vulnerability often found in web applications. It occurs when an attacker injects malicious scripts into web pages viewed by other users. These scripts execute in the context of the victim's browser, allowing the attacker to steal sensitive information, manipulate content, or perform unauthorized actions.

Types of XSS:

  1. Stored XSS: Also known as persistent XSS, occurs when the injected script is permanently stored on the target server, such as in a database. Whenever a user accesses the affected page, the script executes.
  2. Reflected XSS: Also known as non-persistent XSS, happens when the injected script is reflected off the web server. This typically occurs via input fields or URLs, and the script executes in the victim's browser when they interact with the vulnerable page.

How XSS Attacks Work:

  1. Injection Points: Attackers identify areas in the web application where user-supplied data is not properly validated or sanitized before being displayed to other users.
  2. Injection Techniques: Attackers inject malicious scripts, often written in JavaScript, into these vulnerable areas. This can be done through input fields, URL parameters, or even HTTP headers.
  3. Script Execution: When unsuspecting users access the compromised page, their browsers execute the injected script within the context of the vulnerable web application.
  4. Impact: XSS attacks can lead to various consequences, including stealing cookies, session hijacking, phishing attacks, defacement of websites, and even malware distribution.

Common Attack Scenarios:

  1. Stealing Cookies: Attackers can use XSS to steal session cookies, enabling them to impersonate the victim and gain unauthorized access to their accounts.
  2. Phishing Attacks: Malicious scripts can prompt users to enter their credentials into fake login forms, allowing attackers to capture sensitive information.
  3. Keylogging: Scripts can capture keystrokes entered by users, allowing attackers to steal passwords and other confidential data.

Preventing XSS Attacks:

  1. Input Validation: Validate and sanitize all user-supplied data before processing or displaying it.
  2. Output Encoding: Encode output data to prevent browsers from interpreting it as executable code. Techniques like HTML entity encoding, JavaScript escaping, and URL encoding can be used.
  3. Content Security Policy (CSP): Implement CSP headers to restrict the sources from which certain types of content can be loaded, thereby mitigating XSS attacks.
  4. XSS Protection Headers: Use HTTP headers like X-XSS-Protection to enable XSS filtering in modern browsers, providing an additional layer of defense against XSS attacks.

Demonstrating XSS:

  1. Setup: Create a vulnerable web application with input fields or other user-controlled areas that do not properly validate or sanitize input.
  2. Injection: Inject a simple JavaScript payload into these vulnerable areas, such as <script>alert('XSS')</script>.
  3. Observation: Notice how the injected script executes when the page is loaded or the input is reflected, demonstrating the XSS vulnerability.
  4. Mitigation: Apply proper input validation, output encoding, and other security measures to prevent XSS vulnerabilities in the web application.

Advantages of XSS:

  • Ability to Exploit User Trust: XSS attacks can exploit the trust users have in a legitimate website by injecting malicious scripts that appear to originate from the trusted site.
  • Versatility: XSS vulnerabilities can be exploited in various ways, allowing attackers to steal sensitive information, hijack sessions, deface websites, distribute malware, and more.

Disadvantages of XSS:

  • Security Risks: XSS vulnerabilities pose significant security risks to web applications and their users. Attackers can exploit these vulnerabilities to perform unauthorized actions, compromise user data, and undermine the integrity of the application.
  • Reputation Damage: Successful XSS attacks can damage the reputation of a website or organization, leading to loss of trust among users and potential legal consequences.

Attack script:

Learning Outcome:

  • LO 1: Understanding of XSS vulnerabilities, their types, and potential impacts on web applications.
  • LO 2: Learn effective strategies for preventing XSS attacks.
  • LO 3: Develop a heightened awareness of client-side security.

Conclusion:

In short, Cross-Site Scripting (XSS) is a serious web security vulnerability where attackers inject malicious scripts into web pages, leading to various risks such as data theft and malware distribution. It comes in two main types: Stored XSS and Reflected XSS. While XSS offers attackers the ability to exploit user trust and versatility, it poses significant disadvantages, including security risks and reputation damage.

Experiment 7: Perform DOS attack

Aim: To perform DoS attack

Tool: Kali Linux, Wireshark

Theory:

DOS Attack: A Denial-of-Service (DoS) attack is an attack meant to shut down a machine or network, making it inaccessible to its intended users. DoS attacks accomplish this by flooding the target with traffic, or sending it information that triggers a crash. In both instances, the DoS attack deprives legitimate users (i.e. employees, members, or account holders) of the service or resource they expected.

A denial-of-service (DoS) attack is a type of cyber attack in which a malicious actor aims to render a computer or other device unavailable to its intended users by interrupting the device's normal functioning.

ICMP flood: Leverages misconfigured network devices by sending spoofed packets that ping every computer on the targeted network, instead of just one specific machine. The network is then triggered to amplify the traffic. This attack is also known as the smurf attack or ping of death.

DOS attack using hping3 command:

hping3 is a network tool able to send custom TCP/IP packets and to display target replies like ping programs do with ICMP replies. hping3 handles fragmentation, arbitrary packet body and size and can be used in order to transfer files encapsulated under supported protocols. It is also known as packet crafting technique.

Features of hping3:

  • Available for UNIX and Windows.
  • Capture live packet data from a network interface.
  • Open Files Containing Packet Data Capture With Tcpdump/WinDump, Wireshark, and a Number of Other Packet Capture Programs.

hping3 Syntax:

  • c – Packet count that we want to send to the victim.
  • d – Data size that we want to send to the victim.
  • p – Victim's port that we want to attack.
  • --flood – This will flood the packets repeatedly.
  • -S – It will set the SYN packet flag with the IP.
  • -a – This will spoof the IP of the attacker.

Results:

Learning Outcomes: The student should have performed a DoS attack

  • LO1: To describe & understand different commands of hping3
  • LO2: To perform DoS attack using hping3 command

Course Outcomes: Upon completion of the course students will be able to understand DoS attack.

Conclusion:

```

Experiment 3: DH ALGO - Diffie Hellman

def power(x,y):
    prod=1
    for i in range(0,y):
        prod=prod*x
    return prod
def r_calc(secret,g,p):
    prod=power(g,secret)
    return prod%p
def key(g,x,y,p):
    prod=power(g,(x*y))
    return (g**(x*y))%p
def DH(p,g,x,y):
    print("R1 value: ")
    R1=r_calc(x,g,p)
    print(R1)
    print("R2 value: ")
    R2=r_calc(y,g,p)
    print(R2)
    print("K1 value: ",r_calc(x,R2,p))
    print("K2 value: ",r_calc(y,R1,p))
    print("k3 value: ",key(g,x,y,p))
print("********** DH Algorithm ************")
p=int(input("Enter the Modulus Value: "))
g=int(input("Enter the primitive root Value: "))
x=int(input("Enter the SecretKey of A: "))
y=int(input("Enter the SecretKey of B: "))
DH(p,g,x,y)

Experiment 4: RSA

def k_calc(nn,e):
    for i in range(0,100):
        if (1+i*nn)%e==0:
            d=(1+i*nn)//e
            return d,i
            break
def cipher(pt,e,N):
    cip=((pt)**e)%N
    return cip
p=int(input("Enter the P: "))
q=int(input("Enter the Q: "))
e=int(input("Enter the SecretKey: "))
pt=int(input("Enter the Plain Text: "))
N=p*q
nn=(p-1)*(q-1)
d,k=k_calc(nn,e)
print("Value of D is: ",d,"for K =",k)
ct=cipher(pt,e,N)
print("Cipher: ",ct)
print("Decipher: ",cipher(ct,d,N))