Download as pdf or txt
Download as pdf or txt
You are on page 1of 33

SECURE SOFTWARE DESIGN

Lab Manual

Student Name: _________________________________________


Roll No: _________________________________________
Session: _________________________________________

BS Cyber Security and Digital Forensics


The Islamia University of Bahawalpur, Pakistan
Introduction
In the rapidly evolving landscape of software development, the importance of security cannot be
overstated. As engineers and developers, our responsibility extends beyond creating functional and efficient
software; it encompasses safeguarding the digital world against an ever-increasing array of threats. Welcome
to the "Secure Software Design" course, a comprehensive journey into the art and science of crafting software
systems with security at their core.
This lab manual serves as your roadmap through this course, designed to equip engineering students with the
knowledge and practical skills needed to create robust and secure software. Over the course of this manual,
you will delve into the fundamentals of secure software design, explore threat modeling, master secure coding
practices, and gain hands-on experience with cryptographic techniques, data storage security, and much more.
Our mission is to empower you with the expertise to not only build innovative and feature-rich software
applications but also to fortify them against the ever-present cybersecurity challenges of our digital age. Let
us embark on this exciting journey together, as we venture into the realm of secure software design and
development.

Learning Objectives
The learning objectives for the "Secure Software Design" lab manual encompass a comprehensive
understanding of secure software development practices. Throughout the course, students will grasp the
significance of integrating security into the software design process and learn to identify and prioritize
potential security threats. They will acquire hands-on experience in implementing secure coding practices,
including authentication, authorization, cryptography, and secure data management. Additionally, students
will develop the ability to recognize and mitigate common security vulnerabilities such as XSS and CSRF,
perform security testing and code reviews, and secure the deployment and configuration of software
applications. By the end of the course, students will have a firm grasp of secure software design principles
and be equipped to create robust, secure software systems.

Code of Conduct and Academic Integrity


Guidelines on Academic Honesty and Integrity
▪ Plagiarism: Always attribute the source when using someone else's work, ideas, or words. Properly
cite and reference all sources, including text, images, and data, following the appropriate citation style
guidelines.
▪ Original Work: Submit only your own original work for assignments, projects, and exams. Collaborate
with others as allowed by the instructor but ensure that your contributions are clear and properly
acknowledged.
1

CSDF 0228: Secure Software Design Lab Manual


▪ Honesty in Assessments: Do not engage in any form of cheating during exams or assessments,
including copying from others, using unauthorized materials or devices, or communicating with others
without permission.
▪ Proper Collaboration: When collaboration is permitted, follow the rules set by the instructor. If unsure,
seek clarification on what constitutes acceptable collaboration and what must be your independent
work.
▪ Respect for Others: Show respect for your fellow students, instructors, and academic staff. Do not
engage in activities that facilitate academic dishonesty or mislead others.
▪ Timely Submission: Submit assignments, projects, and exams within the stipulated deadlines. Late
submissions may not only affect your own learning but also create unfair advantages for others.

Consequences of Academic Misconduct:


▪ Academic Penalties: Academic misconduct may result in various penalties, including receiving a
failing grade for the assignment or exam, failing the course, or being expelled from the institution. The
severity of the consequences may depend on the nature and extent of the misconduct.
▪ Academic Record: Incidents of academic misconduct may be documented on your academic record,
which can have long-term consequences, including difficulties in transferring credits or gaining
admission to other institutions.
▪ Educational Consequences: Academic misconduct hinders your own educational development by
preventing you from mastering essential skills and knowledge. It also erodes trust in your abilities and
integrity.
▪ Professional Implications: Academic dishonesty can have professional repercussions, as it reflects
negatively on your character and ethics. Many employers and graduate programs place a high value
on academic integrity.
▪ Legal Action: In severe cases, academic misconduct may lead to legal action, especially if it involves
fraud or theft of intellectual property. Legal consequences may include fines, lawsuits, or criminal
charges.
▪ Damaged Reputation: Engaging in academic misconduct can damage your reputation within the
academic community and beyond. It may affect recommendations, references, and future
opportunities.
2

CSDF 0228: Secure Software Design Lab Manual


Table of Contents
Introduction ....................................................................................................................................................................... 1
Learning Objectives .......................................................................................................................................................... 1
Code of Conduct and Academic Integrity ......................................................................................................................... 1
Lab 01 Introduction to Secure Software Design ............................................................................................................... 5
Objectives: .................................................................................................................................................................... 5
Security Breach Simulation: ......................................................................................................................................... 5
Activities: ...................................................................................................................................................................... 5
Web Application: Insecure Login System ................................................................................................................. 5
Solution and Mitigation: ........................................................................................................................................... 6
Discussion: .................................................................................................................................................................... 6
Lab 02 Threat Modeling ................................................................................................................................................... 7
Objectives: .................................................................................................................................................................... 7
Threat Modeling Scenario:............................................................................................................................................ 7
Activities & Discussions: .............................................................................................................................................. 8
Lab 03 Secure Coding Practices ....................................................................................................................................... 9
Objectives: .................................................................................................................................................................... 9
Activities: ...................................................................................................................................................................... 9
Lab 04 Authentication and Authorization ....................................................................................................................... 11
Objectives: .............................................................................................................................................................. 11
Activities: ................................................................................................................................................................ 11
Lab 05 Role Based Access Control (RBAC) .................................................................................................................. 13
Objectives: .............................................................................................................................................................. 13
Activities: ................................................................................................................................................................ 13
Tasks for Students: .................................................................................................................................................. 14
Discussion: .............................................................................................................................................................. 15
Lab 06 Data Validation Techniques ................................................................................................................................ 16
Objectives: .............................................................................................................................................................. 16
Activities: ................................................................................................................................................................ 16
Discussion: .............................................................................................................................................................. 17
Lab 07 SQL Injection and Cross Site Scripting (XSS) ................................................................................................... 18
Objectives: .............................................................................................................................................................. 18
SQL Injection: ......................................................................................................................................................... 18
Discussion: .............................................................................................................................................................. 19
Cross Site Scripting (XSS) ...................................................................................................................................... 19
Discussion: .............................................................................................................................................................. 20
Lab 08 Secure Communication Protocols ....................................................................................................................... 21
Objectives: .............................................................................................................................................................. 21
Activities: ................................................................................................................................................................ 21
3

Discussion: .............................................................................................................................................................. 22
CSDF 0228: Secure Software Design Lab Manual
Lab 09 Security Testing Tools ......................................................................................................................................... 23
Objectives: .............................................................................................................................................................. 23
Activities: ................................................................................................................................................................ 23
Discussion: .............................................................................................................................................................. 24
Lab 10 Static and Dynamic Analysis .............................................................................................................................. 25
Objectives: .............................................................................................................................................................. 25
Activities: ................................................................................................................................................................ 25
Discussion: .............................................................................................................................................................. 26
Lab 11 Secure Data Storage ............................................................................................................................................ 27
Objectives: .............................................................................................................................................................. 27
Activities: ................................................................................................................................................................ 27
Discussion: .............................................................................................................................................................. 29
Lab 12 Securing APIs ..................................................................................................................................................... 30
Objectives: .............................................................................................................................................................. 30
Activities: ................................................................................................................................................................ 30
Discussion: .............................................................................................................................................................. 32

CSDF 0228: Secure Software Design Lab Manual


Lab 01
Introduction to Secure Software Design
Objectives:
▪ Understand the significance of secure software design in the development lifecycle.
▪ Identify common security threats and their potential impact on software applications.
▪ Recognize the importance of integrating security from the initial stages of software design.

Security Breach Simulation:


▪ Create a simple web application with known vulnerabilities.
▪ Students need to attempt to exploit these vulnerabilities to simulate a security breach.

Activities:
Web Application: Insecure Login System
1. Lack of Input Validation:

Description: The application does not validate user input, making it susceptible to SQL injection attacks.
Vulnerability: An attacker can manipulate the login form inputs to inject malicious SQL code, potentially
gaining unauthorized access to the application or the database.
Solution: Implement input validation and use prepared statements to prevent SQL injection. For example, use
parameterized queries when interacting with the database.
2. Weak Password Policy:

Description: The application allows weak passwords without complexity requirements.


Vulnerability: Weak passwords are easy to guess or crack, making it easier for attackers to gain unauthorized
access.
Solution: Implement a strong password policy that requires a combination of uppercase and lowercase letters,
numbers, and special characters. Enforce a minimum password length.
3. Lack of Account Lockout:

Description: The application does not lock user accounts after a certain number of failed login attempts.
Vulnerability: Without account lockout, attackers can use brute force attacks to guess passwords without any
restrictions.
Solution: Implement account lockout mechanisms that temporarily suspend user accounts after a specified
number of failed login attempts. This prevents automated password guessing attacks.
5

CSDF 0228: Secure Software Design Lab Manual


4. Absence of Session Management:

Description: The application lacks proper session management, allowing session fixation and session
hijacking vulnerabilities.
Vulnerability: Attackers can hijack active sessions or fixate session IDs, gaining unauthorized access to user
accounts.
Solution: Implement secure session management practices. Generate new session IDs upon login, use secure
cookies, and set session timeouts.

Solution and Mitigation:


1. Input Validation and SQL Injection Prevention:

• Implement input validation to ensure that user inputs are sanitized and adhere to expected formats.
• Use parameterized queries or prepared statements to interact with the database. This prevents attackers
from injecting malicious SQL code.
2. Strong Password Policy:

• Enforce a strong password policy that requires a combination of uppercase and lowercase letters,
numbers, and special characters.
• Set a minimum password length requirement (e.g., at least 8 characters).
3. Account Lockout:

• Implement account lockout mechanisms that temporarily suspend user accounts after a specified
number of failed login attempts.
• Include a timeout period during which the account remains locked.
4. Session Management:

• Generate new session IDs upon successful login to prevent session fixation attacks.
• Use secure cookies to transmit session identifiers.
• Set session timeouts to automatically log users out after a period of inactivity.

Discussion:
Discuss the findings and potential consequences of the security breach simulation.
6

CSDF 0228: Secure Software Design Lab Manual


Lab 02
Threat Modeling
Objectives:
▪ Learn how to perform threat modeling to identify potential security vulnerabilities.
▪ Analyze and evaluate various threat scenarios in software applications.
▪ Develop the skills to prioritize security risks and plan mitigation strategies.

Threat Modeling Scenario:


Without a doubt, one of the most serious potential consequences of an attack is theft of funds from
banks. In 2018, this threat was present at 54% of online banks. The threat of unauthorized access to clients'
data and sensitive bank information was found at every tested bank. In some cases, vulnerabilities allowed
escalating the attack up to penetration of the corporate infrastructure.
Off-the-shelf online banking solutions tend to have better security than in-house applications, but their
developers make more frequent mistakes in protection mechanisms in the rush to get product functionality out
the door. Changes to code slip by without new testing being performed, ultimately making production systems
just as vulnerable as testbed systems. This goes to show that security processes need to be established at every
stage of the online bank lifecycle. Implementing a Secure Software Development Lifecycle (SSDLC) prevents
a wide range of errors, but still does not eliminate the need for regular assessment of web application security.
White-box analysis, because it includes testing of source code, is more effective than gray- and blackbox
methods. As a preventive measure, we also urge use of a web application firewall (WAF) to prevent
exploitation of vulnerabilities caused by code changes.

Figure 1: Core Banking System


7

CSDF 0228: Secure Software Design Lab Manual


In Core Banking System, software applications record transactions, maintain customer information, calculate
interest on loans and deposits etc. The data, instead of huge ledgers, are stored in backend databases in digital
form. Now, the same software can be installed in various branches of a bank and can be interconnected through
the internet or telephone lines to form a core banking network of the bank. The advantage, a customer can
operate on his account from any branch of the bank and if the bank owns Internet Banking or ATM facilities,
then the customer can operate on his account from virtually anywhere.

Activities & Discussions:


Students are expected to:
a. Identifies potential threats and vulnerabilities in the core banking system. You should consider threats at
different stages, including data input, data processing, storage, and output.
b. Discuss the impact and likelihood of each threat.
c. Prioritize threats based on their severity.
d. You should be encouraged to think about technical, procedural, and policy-based solutions.
e. Each of you develop a mitigation plan for the top-priority threats.
f. Create a threat model using Microsoft Threat Modeling Tool as discussed in the class.

CSDF 0228: Secure Software Design Lab Manual


Lab 03
Secure Coding Practices
Objectives:
▪ Acquire practical knowledge of secure coding practices.
▪ Identify common coding vulnerabilities and best practices for prevention.
▪ Demonstrate the ability to refactor code to adhere to secure coding standards.
Activities:
1. Following code snippets are supposed to be in-secure with respect to the practices taught in the class.
Student are expected to remediate codebase containing security vulnerabilities with explanation and
injecting the secure coding.
a.
if (IsValidUsername($username) == 1) {
if (IsValidPassword($username, $password) == 1) {
print “Login Successful”;
}
else {
print “Login Failed - incorrect password”;
}
else {
print “Login Failed - unknown username”;
}
}

b.
Public String getCreditCardNumber(String username) {
if (isAuthorizedUser(username)) {
query = “SELECT ccn, expiryDate FROM userCreditCardDetails WHERE username = ?”

Logger.getLogger(CrediCardManager.class.getName())
.log(Level.INFO, “username: “ + username + “, CCN: “ + ccn + “, Expiration Date: “
+ expiryDate);
}
return ccn;
}

c. Take the following code for a SQL call to retrieve a user’s account balance:
String accountBalancequery = “SELECT accountNumber, balance FROM accounts
WHERE account_owner_id = ’” + request.getParameter(“user_id”) + “’”;

2. Write code for secure code for authentication and access control from the following python code:
a.
def validate_password(password):
if len(password) < 8:
return False
return True

password = input("Enter your password: ")


9

if validate_password(password):
CSDF 0228: Secure Software Design Lab Manual
print("Password is valid.")
else:
print("Password is weak. Please choose a stronger password.")

b.
class User:
def __init__(self, id, name, age, is_admin):
self.id = id
self.name = name
self.age = age
self.is_admin = is_admin

def __str__(self):
return f"User(id={self.id}, name={self.name}, age={self.age},
is_admin={self.is_admin})"

def view_profile(user_id):
# Fetch the user's profile information from the database
profile = fetch_profile_from_database(user_id)

if profile:
return profile
else:
return "Profile not found."

def fetch_profile_from_database(user_id):
return User(user_id, 'John', 45, False)

print(view_profile(12))

3. A Microsoft tool named DevSkim is a set of IDE plugins that provide inline analysis in the development
environment as the developer writes code. How can we use it to give developers notification when they
introduce a vulnerability. Students can study it from https://github.com/Microsoft/DevSkim.

10

CSDF 0228: Secure Software Design Lab Manual


Lab 04
Authentication and Authorization
Objectives:
▪ Comprehend the concepts of user authentication and authorization.
▪ Implement secure authentication mechanisms in software applications.
▪ Apply authorization controls to restrict access to sensitive resources.
Activities:
Students are required to work on the following as required.
a.
import hashlib

def create_user(username, password):


hashed_password = hashlib.md5(password.encode()).hexdigest()

# Store the username and hashed password in the database


store_user_credentials(username, hashed_password)

return "User created successfully."

1. Create store_user_credentials(username, hashed_password) function to print the username


and password in the screen.
2. Create main function which uses the create_user(username, password) function and print the
result.
3. How can implement the bcrypt library in the above code. Please mention each step with code listing.
b.
import stat
import os

def has_secure_permissions(file_path):
try:
file_permissions = stat.S_IMODE(os.lstat(file_path).st_mode)
if file_permissions & stat.S_IRWXG or file_permissions & stat.S_iRWXO:
return False
else:
return True
except OSError:
return False

def read_sensitive_file(file_path):
# Read the contents of a sensitive file
if has_secure_permissions(file_path):
with open(file_path, 'r') as file:
contents = file.read()
return contents
else:
return "Unauthorized Access."

print(read_sensitive_file('/path/to/file/secure-authentication.py'))
11

CSDF 0228: Secure Software Design Lab Manual


1. Create a text file (data.txt) with random text in it. Get its path and set it in the above code.
2. Variate the conditions at line if file_permissions & stat.S_IRWXG or file_permissions &
stat.S_iRWXO and observe the behavior of the code.

c.
import requests

def fetch_data(url):
response = requests.get(url)

if response.status_code == 200:
return response.text
else:
return "Error: Failed to fetch data."

url = 'www.google.com'
contents = fetch_data(url)
print(contents)

Explain the purpose and working of code line-by-line.


d.
import datetime

def write_log(log_message):
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
log_entry = f"[{timestamp}] {log_message}"
print(log_entry)

def transfer_funds(sender, recipient, amount):


# Perform the funds transfer
# ...

log_message = {
"action" : "transfer",
"sender": sender,
"recipient": recipient,
"amount": amount
}
write_log(log_message)

# Usage:
sender = "user123"
recipient = "user456"
amount = 100.0
transfer_funds(sender, recipient, amount)

1. Explain the working of the given code.


2. Modify the code of write_log(log_message) function as it writes the messages on log.txt file.
12

CSDF 0228: Secure Software Design Lab Manual


Lab 05
Role Based Access Control (RBAC)
Objectives:
▪ Implementing role-based access control (RBAC) involves defining roles, assigning permissions to
those roles.
▪ Checking whether a user with a specific role has the necessary permissions to perform a certain action.
Activities:
Step 1: Define Roles and Permissions
Create a Python module (rbac.py) to define roles and their corresponding permissions.

class Role:
def __init__(self, name):
self.name = name
self.permissions = set()

def add_permission(self, permission):


self.permissions.add(permission)

class User:
def __init__(self, name, role=None):
self.name = name
self.role = role

def assign_role(self, role):


self.role = role

def has_permission(self, permission):


return permission in self.role.permissions if self.role else False

# Example roles and permissions


admin_role = Role("admin")
admin_role.add_permission("read")
admin_role.add_permission("write")
user_role = Role("user")
user_role.add_permission("read")

# Example users
admin_user = User("admin_user", admin_role)
user = User("normal_user", user_role)

Step 2: Test the Role-Based Access Control System


Create a script (main.py) to test the role-based access control system.

from rbac import admin_user, user

# Display initial user roles and permissions


print(f"{admin_user.name}'s role: {admin_user.role.name}")
print(f"{user.name}'s role: {user.role.name}")

# Test permissions
13

permission_to_check = "write"

CSDF 0228: Secure Software Design Lab Manual


print(f"\nChecking permission '{permission_to_check}' for {admin_user.name}:
{admin_user.has_permission(permission_to_check)}")
print(f"Checking permission '{permission_to_check}' for {user.name}:
{user.has_permission(permission_to_check)}")

# Assign a new role to a user


user.assign_role(admin_role)
print(f"\n{user.name}'s new role: {user.role.name}")

# Test permissions after role change


print(f"Checking permission '{permission_to_check}' for {user.name}:
{user.has_permission(permission_to_check)}")

Step 3: Run the Script


Run the main.py script to test the role-based access control system.

Tasks for Students:


1. Understand the Code:

• Review the rbac.py module and understand the classes Role and User.
• Identify how roles and permissions are defined and assigned to users.

2. Run the Initial Script:

• Run the main.py script and observe the initial roles and permissions for admin_user and user.

3. Add a New Role:

• Add a new role, e.g., manager, in the rbac.py module.


• Assign appropriate permissions to the new role.

4. Create a New User:

• Create a new user, e.g., manager_user, and assign the manager role to them.
• Display the user's role and permissions.

5. Check Permissions:

• Modify the main.py script to check for additional permissions, and test the access for both admin_user and
manager_user.

6. Change User Role:

• Implement a functionality to change a user's role dynamically.


• Change the role of user from user_role to admin_role in the script and check for updated permissions.

7. Handling Unassigned Roles:

• Modify the User class to handle cases where a user does not have a role assigned.
• Ensure that the has_permission method gracefully handles cases where the user has no role.

8. Edge Case Testing:

• Test the system with edge cases such as checking permissions for a user with no role assigned.
14

CSDF 0228: Secure Software Design Lab Manual


9. Extend Permissions:

• Add new permissions (e.g., delete, update) to existing roles and test the updated permissions.

10. Documentation:

• Write comments in the code to explain the purpose of each class and method.
• Document any modifications made during the tasks.

Discussion:
• Discuss potential real-world scenarios where a role-based access control system could be useful.
• Consider how this system might be expanded or adapted for a more complex application.

In order to expand upon this foundation by adding more roles, permissions, and refining the access control
logic, student are advice to go through video demonstrations and provided Django code.

15

CSDF 0228: Secure Software Design Lab Manual


Lab 06
Data Validation Techniques
Objectives:
• Implement a Python program that demonstrates various data validation techniques for a hypothetical
business scenario.
Activities:
Requirements:
• Python (version 3.x recommended)
• Libraries: json, xml.etree.ElementTree, datetime, re
1. Business Logic Validation:
• Create a Python class representing a business entity (e.g., Order).
• Implement business logic validation methods related to the entity (e.g., check if the order amount is
valid).
2. Custom Validation Rules:
• Extend the class with custom validation rules (e.g., a custom rule that checks if the order date is within
the last 30 days).
3. Schema Validation (JSON and XML):
• Create sample JSON and XML data representing the business entity.
• Implement functions to validate the data against predefined JSON and XML schemas.
4. Cross-Field Validation:
• Add attributes to the class that depend on each other.
• Implement validation methods that ensure consistency between these attributes (e.g., start date should
be before end date).
5. Database Constraints:
• Simulate a database environment by creating a simple SQLite database.
• Implement database constraints (e.g., unique constraints on order IDs).
6. Data Range Validation:
• Implement validation to ensure that numerical values are within a specified range (e.g., order quantity
should be between 1 and 100).
7. Referential Integrity Validation:
• Create a related entity (e.g., Customer) and establish a relationship with the original entity.
• Implement referential integrity checks (e.g., an order should be associated with an existing customer).
8. Content Validation:
16

CSDF 0228: Secure Software Design Lab Manual


• Implement validation to check if textual data follows specific content rules (e.g., a product name should
not contain special characters).
9. Character Encoding Validation:
• Introduce non-ASCII characters in the data and implement validation to ensure proper character
encoding.
10. Security Headers:
• Implement a function to check if HTTP responses include necessary security headers (e.g., Content
Security Policy, Strict Transport Security).
11. Data Transformation Validation:
• Create a function to transform data (e.g., convert a date to a different format) and validate the
transformation.
12. Timestamp Validation:
• Implement validation to ensure that timestamps are in the correct format and timezone.
13. Locale and Language Validation:
• Implement validation to check if the provided locale and language codes are valid.
14. Geospatial Validation:
• If applicable, implement validation for geospatial data (e.g., latitude and longitude are within valid
ranges).
15. Data Accuracy Verification:
• Implement a function to verify the accuracy of data by comparing it with an external source (e.g., an
external API).
16. Data Cleanliness Checks:
• Implement checks to ensure data cleanliness (e.g., no leading or trailing spaces in text fields).
17. XML or JSON Validation:
• Implement additional validation for XML or JSON data, such as checking for well-formedness.
18. Documentation:
• Document each validation technique implemented and explain its purpose.
• Provide comments in the code to enhance readability.
19. Testing:
• Create test cases for each validation method to ensure their correctness.
• Include both valid and invalid data to thoroughly test the implemented validations.
Discussion:
• Discuss the importance of each validation technique in the context of data integrity and application
security.

17

Explore how these techniques contribute to building reliable and secure applications.

CSDF 0228: Secure Software Design Lab Manual


Lab 07
SQL Injection and Cross Site Scripting (XSS)
Objectives:
▪ Demonstrate and understand the concept of SQL injection and its potential risks.
▪ Demonstrate and understand the concept of Cross-Site Scripting (XSS) and its potential risks.
SQL Injection:
Requirements:
• Python (version 3.x recommended)
• MySQL database
1. Setup Database:
• Create a MySQL database with a table named users.
• Include fields such as id, username, and password.
2. Python and MySQL Connection:
• Write a Python script to connect to the MySQL database.
• Create a sample record in the users table.
3. Basic SQL Query:
• Write a Python script that fetches data from the users table using a basic SQL query (e.g., SELECT *
FROM users WHERE username='admin';).
4. Vulnerable SQL Query:
• Create a vulnerable Python script that takes user input to construct a SQL query without proper
validation.
5. Perform a Simple SQL Injection:
• Modify the vulnerable script to accept user input and demonstrate a simple SQL injection attack by
manipulating the query.
6. UNION-based SQL Injection:
• Modify the vulnerable script to demonstrate UNION-based SQL injection.
• Fetch data from another table (e.g., information_schema.tables) using UNION.
7. Time-Based Blind SQL Injection:
• Modify the vulnerable script to demonstrate time-based blind SQL injection.
• Use a sleep function to delay the response if a condition is true.
8. Error-Based SQL Injection:
• Modify the vulnerable script to demonstrate error-based SQL injection.
• Inject code that intentionally produces an error and reveals information about the database.
18

CSDF 0228: Secure Software Design Lab Manual


9. Prevention Techniques:
• Discuss and implement techniques to prevent SQL injection in Python, such as parameterized queries
or using an ORM (Object-Relational Mapping) library.
10. Ethical Considerations:
• Emphasize the ethical use of knowledge gained from lab exercise.
• Discuss the importance of secure coding practices and the potential real-world impact of SQL injection
vulnerabilities.
11. Documentation:
• Document the vulnerable and fixed code.
• Explain the steps taken to perform and prevent SQL injection attacks.
Discussion:
• Engage in a discussion about the importance of secure coding practices.
• Discuss real-world examples of SQL injection attacks and their consequences.
• Encourage students to share their observations and insights from the lab exercise.
Note: It's crucial to perform these exercises in a controlled environment and not on production systems.
Reinforce the ethical use of these techniques for educational purposes only.

Cross Site Scripting (XSS)


Requirements:
• Python (version 3.x recommended)
• Flask or another web framework
• Web browser
1. Setup a Simple Web Application:
• Create a basic web application using Flask or any other Python web framework.
• Include a webpage with a form that accepts user input (e.g., a comment form).
2. Display User Input:
• Write a Python script to display the user input on the web page without proper validation.
3. Simple XSS Attack:
• Modify the script to demonstrate a simple XSS attack by injecting a script into the user input.
4. Reflected XSS Attack:
• Extend the web application to simulate a reflected XSS attack.
• Display the injected script in the response and discuss the impact.
5. Stored XSS Attack:
• Modify the application to simulate a stored XSS attack.
• Save the injected script in the database and retrieve it to demonstrate the impact.
19

6. DOM-based XSS Attack:


CSDF 0228: Secure Software Design Lab Manual
• Discuss and implement a DOM-based XSS attack in the web application.
7. Prevention Techniques:
• Discuss and implement techniques to prevent XSS attacks in Python, such as input validation and
output encoding.
• Introduce the use of Content Security Policy (CSP) headers.
8. Ethical Considerations:
• Emphasize the ethical use of knowledge gained from lab exercise.
• Discuss responsible disclosure of security vulnerabilities.
9. Documentation:
• Document the vulnerable and fixed code.
• Explain the steps taken to perform and prevent XSS attacks.
10. Testing and Validation:
• Encourage students to test the web application for various XSS attack scenarios.
• Validate the effectiveness of the prevention techniques implemented.
Discussion:
Engage in a discussion about the importance of securing web applications against XSS attacks.
Discuss real-world examples of XSS attacks and their consequences.
Encourage students to share their observations and insights from the lab exercise.
Note: It's crucial to perform these exercises in a controlled environment and not on production systems.
Reinforce the ethical use of these techniques for educational purposes only.

20

CSDF 0228: Secure Software Design Lab Manual


Lab 08
Secure Communication Protocols
Objectives:
• Implement HTTPS, SSL, and TLS in a Python web application to secure communication.
Activities:
Requirements:
• Python (version 3.x recommended)
• Flask or another web framework
• OpenSSL (for generating SSL/TLS certificates)
1. Setup a Simple Web Application:
• Create a basic web application using Flask or any other Python web framework.
• Include a homepage with some content.
2. Run the Application Over HTTP:
• Start the web application and run it over HTTP.
• Access the application using a web browser.
3. Generate SSL/TLS Certificates:
• Use OpenSSL to generate self-signed SSL/TLS certificates for the web application.
• Create both a private key and a public key (certificate).

openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365

4. Enable HTTPS in Flask:


• Modify the Flask application to serve content over HTTPS using the generated certificates.

from flask import Flask

app = Flask(__name__)

if __name__ == '__main__':
app.run(ssl_context=('cert.pem', 'key.pem'), debug=True)

5. Access the Application Over HTTPS:


• Access the web application using the HTTPS protocol (e.g., https://localhost:5000).
• Observe the browser's security indicators.
6. Task: Implement SSL/TLS Version Configuration:
• Modify the SSL/TLS configuration to specify a particular version (e.g., TLSv1.2).
from flask import Flask
21

app = Flask(__name__)

CSDF 0228: Secure Software Design Lab Manual


if __name__ == '__main__':
app.run(ssl_context=('cert.pem', 'key.pem', 'TLSv1_2'), debug=True)

7. Task: Redirect HTTP to HTTPS:


• Implement a mechanism to redirect HTTP requests to HTTPS for enhanced security.
8. Task: Certificate Pinning:
• Discuss and implement certificate pinning to enhance security by validating the server's certificate.
9. Task: Perfect Forward Secrecy (PFS):
Explore and implement Perfect Forward Secrecy for stronger encryption.
10. Task: HSTS (HTTP Strict Transport Security):
• Discuss and implement HSTS headers to instruct browsers to always use HTTPS.
11. Ethical Considerations:
• Emphasize the ethical use of secure communication practices.
• Discuss the importance of securing communication for user privacy.
12. Documentation:
• Document the steps taken to enable secure communication.
• Provide explanations for each security enhancement implemented.
13. Testing:
• Test the web application for secure communication and ensure that all implemented security features
are functioning correctly.
Discussion:
• Engage in a discussion about the significance of HTTPS and secure communication in modern web
applications.
• Discuss the role of SSL and TLS in securing data during transmission.

22

CSDF 0228: Secure Software Design Lab Manual


Lab 09
Security Testing Tools
Objectives:
• Integrate OWASP ZAP with a Python script to automate security testing of a web application.
Activities:
Requirements:
• Python (version 3.x recommended)
• OWASP ZAP (installed and running, download from OWASP ZAP Download Page)
• python-owasp-zap-v2.4 library (install using pip install python-owasp-zap-v2.4)
1. Setup Web Application:
• Create a simple vulnerable web application or use an existing one for security testing.
2. Install and Run OWASP ZAP:
• Download and install OWASP ZAP.
• Start the OWASP ZAP proxy.
3. Python Script to Interact with ZAP:
• Write a Python script that interacts with OWASP ZAP using the python-owasp-zap-v2.4 library.
• Connect the script to the running ZAP proxy.

from zapv2 import ZAPv2

zap = ZAPv2(apikey='your_api_key', proxies={'http': 'http://127.0.0.1:8090', 'https':


'http://127.0.0.1:8090'})

• Replace 'your_api_key' with the actual API key or configure ZAP without an API key.
4. Spider the Web Application:
• Use the Python script to initiate the ZAP spider on the target web application.
target_url = 'http://your_target_url'
zap.spider.scan(target_url)

5. Wait for Spider to Finish:


• Implement logic in the Python script to wait for the ZAP spider to finish scanning the web application.
while int(zap.spider.status()) < 100:
print('Spider progress %: ' + zap.spider.status())
time.sleep(1)
print('Spider completed')

6. Display Spider Results:


• Retrieve and display the URLs discovered by the ZAP spider.
for url in zap.spider.full_results():
23

print('Found URL: ' + url)

CSDF 0228: Secure Software Design Lab Manual


7. Active Scan:
• Initiate an active scan on the discovered URLs using the Python script.
for url in zap.core.urls():
zap.ascan.scan(url)

8. Wait for Active Scan to Finish:


• Implement logic in the Python script to wait for the ZAP active scan to complete.
while int(zap.ascan.status()) < 100:
print('Active Scan progress %: ' + zap.ascan.status())
time.sleep(1)
print('Active Scan completed')

9. Display Scan Results:


• Retrieve and display the vulnerabilities found by the ZAP active scan.
for alert in zap.core.alerts():
print('Alert: ' + alert['name'] + ' at URL: ' + alert['url'])

10. Automation and Reporting:


• Enhance the Python script to automate the entire process of spidering, scanning, and displaying results.
• Save the results to a file or report for further analysis.
11. Ethical Considerations:
• Emphasize the ethical use of security testing tools.
• Discuss the importance of responsible disclosure of vulnerabilities.
12. Documentation:
• Document the Python script and its functionality.
• Provide explanations for each step and how ZAP is being used.
Discussion:
• Engage in a discussion about the importance of security testing in web applications.
• Discuss how automated tools like OWASP ZAP can assist in identifying vulnerabilities.
24

CSDF 0228: Secure Software Design Lab Manual


Lab 10
Static and Dynamic Analysis
Objectives:
• Implement static and dynamic analysis techniques in Python for security testing of a sample
application.
Activities:
Requirements:
• Python (version 3.x recommended)
• Static analysis tool (e.g., Bandit for Python)
• Dynamic analysis tool (e.g., OWASP ZAP)
• A sample Python application (can be simple or complex)
1. Setup Sample Python Application:
• Create a simple Python application with potential security vulnerabilities or use an existing one.
2. Static Analysis:
• Use a static analysis tool like Bandit to analyze the source code of the Python application for security
issues.
bandit -r your_python_app_directory

• Interpret the results and identify potential security risks.


3. Task: Fix Static Analysis Findings:
• Address and fix the security issues identified by the static analysis tool.
• Document the fixes made to resolve the identified vulnerabilities.
4. Dynamic Analysis Setup:
• Set up OWASP ZAP or another dynamic analysis tool to perform security testing on the running Python
application.
5. Python Script for Dynamic Analysis:
• Write a Python script that interacts with the dynamic analysis tool (e.g., ZAP) using its API.
from zapv2 import ZAPv2

zap = ZAPv2(apikey='your_api_key', proxies={'http': 'http://127.0.0.1:8090', 'https':


'http://127.0.0.1:8090'})

• Replace 'your_api_key' with the actual API key or configure ZAP without an API key.
6. Dynamic Analysis:
• Use the Python script to initiate a dynamic analysis (e.g., spidering and active scanning) on the running
Python application.
25

target_url = 'http://your_target_url'
CSDF 0228: Secure Software Design Lab Manual
zap.spider.scan(target_url)

• Wait for the dynamic analysis to finish and display the results.
7. Task: Fix Dynamic Analysis Findings:
• Address and fix the security issues identified by the dynamic analysis tool.
• Document the fixes made to resolve the identified vulnerabilities.
8. Automation and Reporting:
• Enhance the Python script to automate the entire process of static and dynamic analysis.
• Save the results to a file or report for further analysis.
9. Ethical Considerations:
• Emphasize the ethical use of security testing tools.
• Discuss the importance of responsible disclosure of vulnerabilities.
10. Documentation:
• Document the Python script and its functionality.
• Provide explanations for each step and how static and dynamic analysis tools are being used.
Discussion:
• Engage in a discussion about the importance of static and dynamic analysis in identifying and
addressing security vulnerabilities.
• Discuss how automated tools assist in enhancing the security posture of applications.

26

CSDF 0228: Secure Software Design Lab Manual


Lab 11
Secure Data Storage
Objectives:
• Implement secure data storage in a MySQL database using Python, including encryption of sensitive
information and proper access controls.
Activities:
Requirements:
• Python (version 3.x recommended)
• MySQL database server
• MySQL Connector/Python (mysql-connector-python library)
1. Setup MySQL Database:
• Set up a MySQL database server.
• Create a new database (e.g., secure_storage_db) and a table (e.g., user_data) with fields for sensitive
information.

CREATE DATABASE secure_storage_db;


USE secure_storage_db;
CREATE TABLE user_data (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(255),
password VARCHAR(255),
email VARCHAR(255)
);

2. Python Script for Data Encryption:


• Write a Python script that uses cryptography libraries to encrypt sensitive information before storing
it in the database.

from cryptography.fernet import Fernet

# Generate a key for encryption


key = Fernet.generate_key()
cipher_suite = Fernet(key)

# Encrypt sensitive data


def encrypt_data(data):
encrypted_data = cipher_suite.encrypt(data.encode())
return encrypted_data

# Decrypt sensitive data


def decrypt_data(encrypted_data):
decrypted_data = cipher_suite.decrypt(encrypted_data).decode()
return decrypted_data
27

CSDF 0228: Secure Software Design Lab Manual


3. Task: Implement Secure Data Storage:
• Modify the Python script to use the encryption functions before storing sensitive data in the MySQL
database.

import mysql.connector

# Connect to the MySQL database


connection = mysql.connector.connect(
host="your_database_host",
user="your_database_user",
password="your_database_password",
database="secure_storage_db"
)

cursor = connection.cursor()

# Store encrypted data in the database


def store_data(username, password, email):
encrypted_password = encrypt_data(password)
query = "INSERT INTO user_data (username, password, email) VALUES (%s, %s, %s)"
cursor.execute(query, (username, encrypted_password, email))
connection.commit()

4. Access Controls:
• Set up proper access controls for the MySQL database, ensuring that only authorized users have access
to sensitive data.

GRANT SELECT, INSERT, UPDATE, DELETE ON secure_storage_db.user_data TO


'your_database_user'@'your_application_host';

5. Task: Implement Secure Data Retrieval:


• Modify the Python script to decrypt sensitive data when retrieving it from the MySQL database.

# Retrieve decrypted data from the database


def retrieve_data():
query = "SELECT * FROM user_data"
cursor.execute(query)
result = cursor.fetchall()

decrypted_data = []
for row in result:
decrypted_password = decrypt_data(row[2])
decrypted_data.append((row[0], row[1], decrypted_password, row[3]))

return decrypted_data

6. Ethical Considerations:
• Emphasize the ethical use of sensitive data.
• Discuss the importance of proper access controls to protect sensitive information.
7. Documentation:
• Document the Python script and its functionality.
28

• Provide explanations for each step and how encryption and access controls are being implemented.

CSDF 0228: Secure Software Design Lab Manual


Discussion:
• Engage in a discussion about the importance of securing sensitive data in databases.
Discuss common security risks related to data storage and how encryption and access controls mitigate these
risks.

29

CSDF 0228: Secure Software Design Lab Manual


Lab 12
Securing APIs
Objectives:
• Implement security measures to secure APIs in a Python-based application.
Activities:
Requirements:
• Python (version 3.x recommended)
• Flask or another web framework
• Flask-RESTful or Flask-RestPlus for API development
• Authlib (pip install Authlib) for OAuth2 and JWT support.
1. Setup a Simple API:
• Create a simple API using Flask or any other Python web framework.
• Include endpoints for basic CRUD operations.
2. Task: Implement API Key Authentication:
Enhance the API by implementing API key authentication.
Modify the Flask application to validate API key in the request headers.

from flask import Flask, request, abort

app = Flask(__name__)
API_KEY = "your_api_key"

@app.before_request
def check_api_key():
if request.headers.get("API-Key") != API_KEY:
abort(401, "Unauthorized")

# Add your API routes here

if __name__ == "__main__":
app.run(debug=True)

3. Implement OAuth2 Authentication:


• Integrate OAuth2 authentication using Authlib.
• Implement authentication and token generation using the OAuth2 authorization code flow.

from authlib.integrations.flask_client import OAuth

app = Flask(__name__)
app.secret_key = "your_secret_key"
oauth = OAuth(app)

oauth.register(
name='your_oauth_provider',
30

client_id='your_client_id',
client_secret='your_client_secret',
CSDF 0228: Secure Software Design Lab Manual
authorize_url='provider_authorize_url',
authorize_params=None,
authorize_params=None,
authorize_params=None,
)

@app.route('/login')
def login():
redirect_uri = url_for('authorize', _external=True)
return oauth.your_oauth_provider.authorize_redirect(redirect_uri)

@app.route('/authorize')
def authorize():
token = oauth.your_oauth_provider.authorize_access_token()
user_info = oauth.your_oauth_provider.parse_id_token(token)
# Process user_info as needed
return "Authorized"

# Add your API routes here

if __name__ == "__main__":
app.run(debug=True)

4. Implement JWT Authentication:


• Implement JSON Web Token (JWT) authentication.
• Use Authlib to generate and verify JWT tokens.

from authlib.integrations.flask_client import OAuth


from flask_jwt import JWT, jwt_required, current_identity

app = Flask(__name__)
app.config['SECRET_KEY'] = 'your_secret_key'
oauth = OAuth(app)

oauth.register(
name='your_oauth_provider',
client_id='your_client_id',
client_secret='your_client_secret',
authorize_url='provider_authorize_url',
authorize_params=None,
authorize_params=None,
authorize_params=None,
)

def authenticate(username, password):


# Implement user authentication logic
pass

def identity(payload):
user_id = payload['identity']
# Implement user identity retrieval logic
return {'user_id': user_id}

jwt = JWT(app, authenticate, identity)

@app.route('/protected')
@jwt_required()
def protected():
return f'Hello, {current_identity["user_id"]}!'
31

# Add your API routes here

CSDF 0228: Secure Software Design Lab Manual


if __name__ == "__main__":
app.run(debug=True)

5. Task: Implement Rate Limiting:


• Implement rate limiting to prevent abuse.
• Use Flask-Limiter or similar libraries to control the number of requests per minute.
6. API Documentation with Swagger:
• Enhance the API by adding Swagger documentation using Flask-RESTPlus or similar libraries.
7. Secure Data Transmission with HTTPS:
• Enforce secure data transmission using HTTPS.
• Generate or obtain SSL/TLS certificates for your server.
8. Ethical Considerations:
• Emphasize the ethical use of API security measures.
• Discuss responsible API usage and the consequences of unauthorized access.
9. Documentation:
• Document the API security measures implemented in the Python code.
• Provide explanations for each step and how different authentication methods and security features are
being used.
Discussion:
• Engage in a discussion about the importance of securing APIs.
• Discuss common security risks related to APIs and how the implemented measures address these risks.

32

CSDF 0228: Secure Software Design Lab Manual

You might also like