Source Code Analysis Project - Hs07192_ri07157_za06539_za07168 - Final

You might also like

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

Source Code Analysis Project

Software Security – CS 371


Hammad Aziz Shaikh – hs07192
Syed Rayan Irfan – ri07157
Zia Ali Ahmad – za06539
Zain Ali Ahmad – za07168

In today’s digital age, software security is essential, where cybersecurity threats


and data theft is common. Protecting software applications is increasingly vital,
making the role of source code analysis more crucial. Source code analysis
involves scrutinizing the source code of a software application to pinpoint and
resolve potential security vulnerabilities. By identifying these issues early in the
development phase, it's possible to minimize the likelihood of security incidents
and boost the application's overall security.
The objective of this project report is to conduct a thorough source code analysis
on an application, focusing on software security. The report will detail the tools
used for the analysis, the outcomes, and a detailed examination of detected
vulnerabilities and bugs. It will also discuss the potential consequences, attack
scenarios, and recommended mitigations for the identified issues. This report
aims to offer a complete perspective on source code analysis and its critical role in
fortifying software security. It will serve as a valuable resource for software
developers, security experts, and anyone engaged in the software development
lifecycle.
For this project, we have chosen a Project "Dastaan", which has been developed
by students at Habib University only. By analysing this project, we as students will
also be able to get a better idea of the common mistakes made during such
projects and how to avoid/correct them. Hopefully, we can incorporate our
learning into our work as well.
Source Code Repository:
GitHub URL: https://github.com/gulzar-hussain/Dastaan/tree/main
Application Name: Dastaan
Application Version: 2.0
Description: “Dastaan is a web-based archives museum for Karachi. Users can
view and add stories of Karachi's heritage in the form of text and images.”

SonarQube Installation:
SonarQube installation was done on MacOS using docker. Docker was installed
and a new container was created for SonarQube.
Once the application was set up on Docker, we opened it on localhost port 55000
and logged in using the admin credentials. Then, we created a new project for our
source code analysis and ran the generated command to start the analysis.
Once the analysis was complete, SonarQube generated a report containing the
details of its findings regarding the security aspects of the code. These findings
can be seen below:
Generated Report:
The analysis completed by the tool reported 93 vulnerabilities, 48 bugs, and 3700
code smells, after going through 3952 files in the repository. Here are brief
overviews of all 3 aspects of the report:
Detailed Analysis:
Vulnerability 1: Make sure this Google API Key is either secured or revoked,
changed, and removed from the code. (High Severity Security Risk)
Vulnerable Code:
Description:
The presence of an unsecured Google API Key in the code creates multiple
problems. Firstly, unauthorized access is very risky; if the API Key is exposed and it
is not protected by other security layers, any person who has basic access to it can
use it to access different Google services and data. This leads to the possibility of
data getting breached where wrongdoers, upon acquiring the API Key, could
cause breaches and steal personal data from Google’s servers, potentially using
this data for malicious activities such as blackmail or other criminal activities. In
addition, the hacker can perform malicious and wrong actions on the exposed
criteria, he can further manipulate it, delete it, or carry out other attacks and
disrupt services by sending fake input or requests. Another severe implication
involves compliance breaches; accessing data via the unprotected API Key could
lead the organization to non-compliance with industry-specified regulations and
organizational security policies. The potential security incidents that are triggered
by the exposure could adversely impact the organization’s reputation, causing
significant damage and loss of trust by the consumer. Also, such incidents can
lead to legal problems, including financial sanctions from the court or other
institutions as well, and compensations to the affected people. As long as the API
Key remains unprotected in the code, it continues to pose a threat that may later
be discovered by other hackers.
Relevant CWE and OWASP Articles:
CWE-798: Use of Hard-coded Credentials - This weakness covers scenarios where
credentials (such as API keys) are hard-coded into an application, making them
easily discoverable through code analysis.
CWE-200: Information Exposure - When an API Key is exposed, it can lead to
unauthorized access to sensitive data, fitting under this category of exposing
information unintentionally.
CWE-284: Improper Access Control - This covers failures in ensuring that users
have appropriate access rights, which is relevant if the API Key allows more access
than intended without sufficient restrictions.
OWASP API Security Top 10
API1:2019 - Broken Object Level Authorization - Not directly related to API keys,
but relevant for understanding access controls that may fail if an API key is
compromised.
API2:2019 - Broken User Authentication - This could be relevant if the API Key
bypasses normal authentication processes.
API3:2019 - Excessive Data Exposure - Discusses the risks of exposing too much
data through APIs, which could be a concern if the API Key allows access to more
data than it should.
A2:2021 - Cryptographic Failures - This might be relevant as poor handling and
exposure of API keys could be considered a form of cryptographic failure since API
keys are often used as part of security measures for authentication and data
protection.

Attack Scenarios:
According to OWASP:
1. A typical e-commerce platform that hosts individual shops choreographs
their revenue charts on a listing page. This is achieved by querying and
processing the revenue data for each shop accessed from the
path/shops/{shopName}/revenue_data.json. However, r an attacker
discovers an unsecured Google API Key integrated into the platform for
various attack services apart the data retrieval. Considering the API Key
gives the bearer all the rights to data retrieval without the need for normal
authentication, the attacker scripts requests through randomly iterating
shop names obtained from another compromised attack endpoint to fetch
revenue data for thousands of shops.
2. Any xyz system uses an unsecured Google API Key in the user verification
process, one of the approaches being password recovery by SMS token
verification. Ideally, a user gets a 6-digit SMS token for password retrieval
and keys them into the attack system. However, the attacker notices that
the Google API Key can help them in getting around rate limiting policies or
server validations of the maximum Token attempts made by a single end-
user. Thus, they brute force the password recovery prompt in all potential
token combinations, courtesy of the unsecured API Key, which acts as a
pass-by for the authentication process.
3. This scenario involves an IOT-supported surveillance system that trusts an
unsecured Google API Key during the authentication of API calls including
those that fetch data about camera installations within a given site. While
the user interface restricts guarding officers to the allowed cameras per
building, the unsecured Google API Key allows attackers to fetch full
camera details regardless of user permissions because the API does not
validate the level of access.
4. An application protects the encryption of credit card numbers saved in its
database but decrypts and exposes them automatically at data pull. The
backend of the application uses an unsecured Google API key to ensure the
database to avail individuals of the selected data is decrypted. However, an
attacker uses the SQL injection which the API key does not protect against.
Since the API Key gives unrestricted access to database operations, the
attacker is able to inject malicious queries to retrieve decrypted credit card
numbers, leveraging the unsecured API Key to bypass normal security
checks.

Mitigation Plan:
According to NVD Guidelines:
Architecture and Design
- Implement Environment-specific Keys: Utilize separate API keys for
development, testing, and production environments to ensure that keys
used in less secure environments do not have access to production data.
- Adopt the Principle of Least Privilege: Each API key should be configured to
have only the necessary permissions that are required for its specific
function to limit the potential damage in the event of a compromise.
OWASP Cheat Sheets and Secure Design Principles:
- Secure Storage of Secrets: Store API keys securely using secrets
management tools or services that provide encryption, access control, and
audit capabilities.
- Input Validation: Follow OWASP guidelines to validate all inputs to the API
to prevent injection and other related attacks.
- Regular Security Assessments: Conduct periodic security assessments and
code reviews to identify and mitigate security vulnerabilities related to API
usage.
Virtual Patching:
- Deploy Web Application Firewalls (WAFs): Configure WAFs to detect and
block suspicious activities that could indicate attempts to misuse API keys.
- Use API Gateways: Implement API gateways to manage, monitor, and
secure API traffic, including authentication, rate limiting, and access
control.
Code Fixing:
- Remove Hard-coded API Keys: Refactor the application to eliminate hard-
coded API keys. Use environment variables or configuration files to manage
keys outside of the application code.
- Enhanced Error Handling: Design the application to handle errors without
disclosing sensitive information, which could be used to facilitate further
attacks.
- Access Control Enhancements: Strengthen access control checks within the
application to ensure that users can only access data and actions that are
appropriate for their permission level.
Secure Storage and Access:
- Key Rotation Policies: Implement key rotation policies to regularly change
API keys and credentials, minimizing the risk exposure time in case of a key
compromise.
- Audit Logs and Monitoring: Set up detailed logging and monitoring for all
API key usage to quickly detect and respond to unauthorized access
attempts.

Vulnerability 2: Change this code to use a stronger protocol. (High Severity


Security Risk)
Vulnerable Code:
Description:
This specific security threat could be found most commonly in our software’s scan
in many of the different components. It occurs when a weak SSL protocol is used
in an application. When a product encrypts sensitive data, it needs a robust
encryption method to match the required security level. However, some systems
use encryption that, while theoretically correct, isn't strong enough to ward off
modern threats. This weakness can leave the door open to brute force attacks,
where attackers have a feasible chance of cracking the code with current
technologies. Encryption algorithms are essential for scrambling data to block
unauthorized access or alterations. But, the rapid advancements in cryptography
mean that an algorithm can quickly become outdated. As new vulnerabilities are
discovered or as computational power grows, previously secure encryption
methods can become insufficient, exposing sensitive data, altering information, or
allowing for identity spoofing and other security breaches.

Relevant CWE and OWASP Articles:


CWE-327 - Inadequate Encryption Strength: This weakness occurs when an
application uses an encryption algorithm that does not provide a sufficient level
of security, leading to the potential for the encrypted data to be broken or
decrypted by attackers. This could be due to using outdated algorithms,
insufficient key sizes, or flawed implementation of encryption methods.
CWE-326 - Use of a Broken and Risky Cryptographic Algorithm: This article refers
to the implementation of cryptographic algorithms that are either fundamentally
broken or have been found to be vulnerable to attack. Using such algorithms can
compromise the security of the system because these algorithms can be
predictably cracked using various techniques, including brute force attacks.
OWASP Top 10 2017 - Category A3 - Sensitive Data Exposure: This involves the
protection of data that must be kept confidential, such as personal data, credit
card numbers, health information, etc. This category addresses failures in data
protection strategies that lead to unauthorized access to or disclosure of this
data. Common issues include weak encryption, improper handling of data, and
lack of essential security controls.
OWASP Top 10 2017 - Category A6 - Sensitive Misconfiguration: This occurs when
security settings are defined, implemented, and maintained improperly. This can
happen at any level of an application stack, including network services, platforms,
web servers, application servers, databases, and custom code. Misconfigurations
can give attackers unauthorized access to system data or functionality, often
leading to a full system compromise.

Attack Scenarios:
1 - An app uses its database's built-in encryption to protect stored credit card
details. Yet, these details are decrypted automatically when accessed, making
them vulnerable. This flaw allows an attacker to use SQL injection to access and
retrieve the credit card numbers in their original, unencrypted form.
2 - A website fails to consistently implement or enforce TLS across all its pages, or
it supports weak encryption protocols. This vulnerability can be exploited on
insecure networks, such as public WiFi, where an attacker can force connections
from secure HTTPS to insecure HTTP, intercept these communications, and steal
session cookies. This stolen cookie enables the attacker to take over the user's
session, potentially accessing or altering the user's sensitive information, like
redirecting funds during a transaction.
3 - A system stores passwords using simple or unsalted hashes. If an attacker
exploits a file upload vulnerability to gain access to the password database, they
can easily breach these hashes using pre-calculated tables, known as rainbow
tables. Even if the hashes are salted, weak or fast hashing algorithms may be
cracked using powerful GPUs, compromising user passwords.
As a consequence of this vulnerability being exploited in the attack scenarios
given above, three aspects of the software’s security can be compromised:
confidentiality, integrity and accountability. The attacker can use brute force
attacks to bypass the weak encryption and access confidential data. This data can
also be modified and thus sensitive data can be compromised, meaning the
integrity of the data is damaged. Moreover, activities that use the weak
cryptographic algorithm to ensure identity protection of sensitive data, the
accountability of such activities can be compromised too.

Mitigation Plan:
According to NVD Guidelines:
Architecture and Design:
- Use an encryption scheme that is currently considered to be strong by
experts in the field.
- Make sure to encrypt all sensitive data at rest.
- Ensure up-to-date and strong standard algorithms, protocols, and keys are
in place; use proper key management.
- Encrypt all data in transit with secure protocols such as TLS with perfect
forward secrecy (PFS) ciphers, cipher prioritization by the server, and
secure parameters.
- Enforce encryption using directives like HTTP Strict Transport Security
(HSTS).
According to OWASP Cheat Sheets and Secure Design Principles:
- Implement recommendations from the OWASP TLS Security Cheat Sheet,
such as disabling TLS compression and renegotiation, which can be abused
in certain attacks.
- Use tools like Mozilla’s SSL Configuration Generator to create a secure
server configuration, ensuring compatibility with the majority of clients
while providing strong security.
Virtual Patching:
- Deploy a Web Application Firewall to configured to mitigate vulnerabilities
that can exploit weak SSL/TLS implementations, providing an additional
layer of security while permanent fixes are applied.
Code Fixing:
- Ensure that the application’s codebase uses well-supported libraries for
SSL/TLS functionalities. Libraries like OpenSSL (ensure it's the latest version)
or Java’s TLS implementation should be configured correctly.
- Securely manage sessions by using strong session identifiers, secure cookies
(Secure, HttpOnly flags), and ensuring that session expiration is properly
handled.
Vulnerability 3: ‘tempfile.mktemp’ is insecure. Use ‘tempfile.TemporaryFile’
instead. (High Severity Security Risk)

Vulnerable Code:

Description:
When an application like Dastaan uses the 'tempfile.mktemp' function, it's
essentially creating temporary files in an insecure manner. These temporary files
are often used for storing data temporarily during the execution of the program.
However, the way 'mktemp' creates these files can leave both the application and
the system vulnerable to attacks.
One of the primary concerns with using 'mktemp' is its susceptibility to race
conditions. A race condition occurs when multiple processes or threads attempt
to access and manipulate the same resource concurrently. In the case of
'mktemp', an attacker could potentially exploit this vulnerability by manipulating
the creation of temporary files between the time the file is created and when it's
used by the application. This could lead to the injection of malicious code or the
unauthorized access, modification, or deletion of sensitive data.
Furthermore, 'mktemp' does not provide any built-in mechanism for securely
managing temporary files. Once created, these files may remain on the system
indefinitely, posing a security risk if they contain sensitive information.
Additionally, if the application crashes or is terminated abruptly, these temporary
files may not be properly cleaned up, leaving behind potentially sensitive data for
an attacker to exploit.
Relevant CWE and OWASP Articles:
CWE-377: Insecure Temporary File - CWE-377 addresses vulnerabilities related to
the creation and usage of insecure temporary files within software applications.
When temporary files are created without proper security measures, it can
expose both application and system data to various forms of attacks.
CWE-378: Creation of Temporary File With Insecure Permissions - CWE-378
focuses specifically on vulnerabilities related to the creation of temporary files
with insecure permissions. When temporary files are opened without appropriate
measures or controls, it can leave the file, its contents, and any function that it
impacts vulnerable to attack.
OWASP Top 10:
A3:2017 - Sensitive Data Exposure: This OWASP Top 10 category focuses on
vulnerabilities that result in the exposure of sensitive data, such as user
credentials, personal information, or financial data. Vulnerabilities related to
insecure temporary files (CWE-377) can lead to sensitive data exposure if the
temporary files contain confidential information.
A01:2021 – Broken Access Control: Broken access control vulnerabilities involve
inadequate enforcement of access controls, allowing unauthorized users to access
restricted resources or perform privileged actions. Insecure temporary files with
incorrect permissions (CWE-378) can result in unauthorized access to sensitive
data, making this category relevant.
A03:2021 – Injection: Injection vulnerabilities involve the insertion of malicious
code or commands into applications, typically through unsanitized input. While
not directly related to temporary files, injection attacks can exploit vulnerabilities
in applications that arise from insecure file handling, such as insecure temporary
file creation (CWE-377).
A05:2021 – Security Misconfiguration: Security misconfiguration vulnerabilities
arise from improper configuration of security controls, leading to exploitable
weaknesses. Insecure temporary file management, such as improper file
permissions (CWE-378), can be considered a form of security misconfiguration
that exposes applications to attacks.

Attack Scenarios:
a) Sensitive Data Exposure:
Scenario #1: An application encrypts credit card numbers in a database using
automatic database encryption. However, this data is automatically decrypted
when retrieved, allowing a SQL injection flaw to retrieve credit card numbers in
clear text.
Scenario #2: The password database uses unsalted or simple hashes to store
everyone’s passwords. A file upload flaw allows an attacker to retrieve the
password database. All the unsalted hashes can be exposed with a rainbow table
of pre-calculated hashes. Hashes generated by simple or fast hash functions may
be cracked by GPUs, even if they were salted.
b) Broken Access Control:
Scenario #1: The application uses unverified data in a SQL call that is accessing
account information:

An attacker simply modifies the browser's 'acct' parameter to send whatever


account number they want. If not correctly verified, the attacker can access any
user's account.
Scenario #2: An attacker simply forces browses to target URLs. Admin rights are
required for access to the admin page.

If an unauthenticated user can access either page, it's a flaw. If a non-admin can
access the admin page, this is a flaw.
c) Injection:
Scenario #1: An application uses untrusted data in the construction of the
following vulnerable SQL call:
String query = "SELECT \* FROM accounts WHERE custID='" +
request.getParameter("id") + "'";
Scenario #2: Similarly, an application’s blind trust in frameworks may result in
queries that are still vulnerable, (e.g., Hibernate Query Language (HQL)):
Query HQLQuery = session.createQuery("FROM accounts WHERE custID='" +
request.getParameter("id") + "'");
In both cases, the attacker modifies the ‘id’ parameter value in their browser to
send: ' UNION SLEEP(10);--. For example:

This changes the meaning of both queries to return all the records from the
accounts table. More dangerous attacks could modify or delete data or even
invoke stored procedures.
d) Security Misconfiguration:
Scenario #1: The application server comes with sample applications not removed
from the production server. These sample applications have known security flaws
attackers use to compromise the server. Suppose one of these applications is the
admin console, and default accounts weren't changed. In that case, the attacker
logs in with default passwords and takes over.
Scenario #2: Directory listing is not disabled on the server. An attacker discovers
they can simply list directories. The attacker finds and downloads the compiled
Java classes, which they decompile and reverse engineer to view the code. The
attacker then finds a severe access control flaw in the application.

Mitigation Plan:
According to NVD Guidelines, OWASP Cheat Sheets, and Secure Design Principles,
the following techniques can be adopted to address each of the vulnerabilities:
a) Sensitive Data Exposure:
- Encrypt Data Properly: Ensure that sensitive data, such as credit card numbers
and passwords, are encrypted using strong encryption algorithms and properly
managed encryption keys.
- Implement Proper Access Controls: Enforce strict access controls to prevent
unauthorized access to sensitive data. This includes implementing role-based
access control (RBAC) and least privilege principles.
- Use Secure Password Storage: Store passwords securely using salted hashes with
strong cryptographic hashing algorithms, such as bcrypt or Argon2. Avoid using
unsalted or weak hashes that are susceptible to rainbow table attacks.
b) Broken Access Control:
- Parameterize SQL Queries: Use parameterized queries or prepared statements
to prevent SQL injection attacks. This ensures that user input is properly sanitized
and treated as data rather than executable code.
- Implement Proper Authentication and Authorization: Implement strong
authentication mechanisms, such as multi-factor authentication (MFA), and
enforce proper authorization checks to ensure that users can only access
resources they are authorized to access.
c) Injection:
- Use ORM or Query Builders: Utilize Object-Relational Mapping (ORM)
frameworks or query builders that automatically sanitize user input and prevent
SQL injection vulnerabilities.
- Input Validation and Sanitization: Validate and sanitize all user-supplied input to
ensure that it does not contain malicious content. Use input validation libraries or
frameworks to enforce strict validation rules.
d) Security Misconfiguration:
- Remove Unused Sample Applications: Remove any unused or unnecessary
sample applications and default configurations from production servers to reduce
the attack surface.
- Disable Directory Listing: Disable directory listing and ensure that sensitive
directories and files are not accessible to unauthorized users. Configure web
servers to prevent directory listing by default.
- Regular Security Audits: Conduct regular security audits and vulnerability
assessments to identify and remediate any misconfigurations or security
weaknesses in the application infrastructure.

Conclusion and Feedback:


Overall, this project was a great learning opportunity for all of us. We were able
to employ all of the skills and knoweldge we gained over the semester and put it
all to use. Setting up the software SonarQube itself was very interesting as well,
and the challenges we faced, along with the solutions we found for them, were all
opportunities for us to learn more and also have a similar experience to what we
may have to face in our professional careers. Also, the source code we used was
from the final project of our seniors at Habib University as well, and this was
intentionally done by us as well so that we may be able to use this project as a
chance for us to get to know the type of errors and mistakes which students like
us may be prone to making when working on such projects, and hopefully avoid
them and make secure, efficient softwares in the future.

You might also like