Lab Manual
Lab Manual
Lab Manual
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.
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
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 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
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.
• 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
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
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
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
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)
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)
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)
class Role:
def __init__(self, name):
self.name = name
self.permissions = set()
class User:
def __init__(self, name, role=None):
self.name = name
self.role = role
# Example users
admin_user = User("admin_user", admin_role)
user = User("normal_user", user_role)
# Test permissions
13
permission_to_check = "write"
• Review the rbac.py module and understand the classes Role and User.
• Identify how roles and permissions are defined and assigned to users.
• Run the main.py script and observe the initial roles and permissions for admin_user and 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.
• 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.
• Test the system with edge cases such as checking permissions for a user with no role assigned.
14
• 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
Explore how these techniques contribute to building reliable and secure applications.
20
openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365
app = Flask(__name__)
if __name__ == '__main__':
app.run(ssl_context=('cert.pem', 'key.pem'), debug=True)
app = Flask(__name__)
22
• 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)
• 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
import mysql.connector
cursor = connection.cursor()
4. Access Controls:
• Set up proper access controls for the MySQL database, ensuring that only authorized users have access
to sensitive data.
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.
29
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")
if __name__ == "__main__":
app.run(debug=True)
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"
if __name__ == "__main__":
app.run(debug=True)
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 identity(payload):
user_id = payload['identity']
# Implement user identity retrieval logic
return {'user_id': user_id}
@app.route('/protected')
@jwt_required()
def protected():
return f'Hello, {current_identity["user_id"]}!'
31
32