A Comprehensive Guide to Secure Code Review

Krunal Kawa
7 min readAug 11, 2023

--

Introduction

Secure Code Review should be regular development practice for organizations. Also, it is a process to identify potential security vulnerabilities in software's. A secure SDLC process can be used to detect common coding flaws such as SQL injection, Sensitive Data Exposure, and cross-site scripting. Secure Code Review protects the application from data and intellectual property loss, which can harm a company’s revenue and reputation.

Before initiating the secure code review process, it is important to gain access to the source code, check the Line of Code (LOC), and perform a walkthrough of the critical modules of the application. This ensures a comprehensive understanding of the codebase.

This is a short article to guide you through the basics of secure code review. The OWASP Top 10 and MITRE Top 25, are widely recognized lists of common vulnerabilities that can be used as references during the secure code review process. Additionally, secure code review is included in the Payment Card Industry Data Security Standard (PCI DSS), indicating its relevance in the context of secure payment processing.

Secure Code Review vs Source Code Review

Secure code review involves a comprehensive assessment of an application’s source code, encompassing both manual and automated processes. The primary objective is to detect and address potential security flaws and vulnerabilities.

Methodologies

Numerous methodologies exist for conducting secure code reviews. Here are a few examples:

· String matching/Grep for bugs. (<>grep to find calls)

Techniques such as using grep are employed to conduct searches for patterns or keywords within the source code. These patterns or keywords can serve as indicators of potential vulnerabilities, such as passwords, initialization vectors (IVs), keys, API keys, database passwords, and even sensitive information stored in comments.

· User Controlled Inputs (Data coming from the database (for stored XSS and second-order injections for example)

This approach centres on the analysis of how the code manages user-controlled data. It entails scrutinizing the processing, validation, and sanitization of input provided by users, which may include data from forms, databases, or external sources.

· Functionality (Authentication, Authorization, Password Reset, Upload Functionality)

This approach entails a detailed examination of specific functionalities or features in the application’s codebase. It involves scrutinizing how the code manages crucial operations like authentication, authorization, password reset, and file uploads. Through this review, security flaws related to access control, session management, input validation, and possible file upload vulnerabilities can be identified.

These techniques act as a foundational step in conducting secure code reviews and play a vital role in identifying prevalent security issues. Nevertheless, it is crucial to acknowledge that secure code review is a multifaceted task, and further methods and tools might be utilized based on the specific requirements and technologies in use.

OSINT Software's

· Yasca — https://scovetta.github.io/yasca/

· OWASP Orizon — https://orizon.sourceforge.net/

· SonarQube- https://hub.docker.com/_/sonarqube

· Visual Code Grepper — https://github.com/nccgroup/VCG

· Mobile-Security-Framework-MobSF — https://github.com/MobSF/Mobile-Security-Framework-MobSF

Commercial Software's

· SonarQube Enterprise — https://www.sonarsource.com/

· Veracode — https://www.veracode.com/security/code-analysis

· AppScan — https://www.hcltechsw.com/appscan/offerings/source

· Checkmarx — https://checkmarx.com/cxsast-source-code-scanning

· Fortify Enterprise— https://www.microfocus.com/en-us/cyberres/application-security/static-code-analyzer

Enhancing with SAST

In SAST automated assessments, a significant portion of reported vulnerabilities often turns out to be false positives. Consequently, a manual code review assessment becomes essential to ensure accuracy and reliability.

During this process, several high-level or evergreen vulnerabilities can be identified. Here are some examples as follows:

SQL Injection: The vulnerabilities arise when untrusted and malicious SQL data is included as part of a command or query sent to an interpreter.

To address this issue, the remediation of the prepared statement is used with placeholders represented by “?” in the SQL query for parameters. The user input is then bound to these parameters using appropriate methods like bindParam() in PHP and setString() in Java. This way, the SQL injection attack is mitigated, as the input is not directly concatenated into the SQL query.

<?php
// Assume we have a database connection established
// User input (to be used as a parameter)
$id = $_GET['id'];
// Prepare the SQL statement
$stmt = $conn->prepare("SELECT * FROM table_name WHERE id = ?");
// Bind the parameter value
$stmt->bind_param("i", $id);
// Execute the prepared statement
$stmt->execute();
// Close the statement and release resources
$stmt->close();
// Close the database connection
$conn->close();
?>

Cross-Site Scripting (XSS): Cross-Site Scripting (XSS) is one of the most common and critical web application security vulnerabilities.

To address the issue, the remediation process involves implementing htmlentities() or htmlspecialchars() to reduce the risk of in the code. This entails preventing Cross-Site Scripting (XSS) attacks in applications such as <, >, &, , and , are converted to their respective HTML entities.

Here’s an example to handle the user input and output in a PHP application:

// Validating and sanitizing user input
$user_input = $_POST['input_field'];
$clean_input = filter_var($user_input, FILTER_SANITIZE_STRING);

// Encoding user output before rendering
$user_output = "<script>alert('XSS attack');</script>";
$encoded_output = htmlspecialchars($user_output, ENT_QUOTES, 'UTF-8');

// Rendering the encoded output
echo "<p>$encoded_output</p>";

Cross-Site Request Forgery (CSRF): Cross-Site Request Forgery (CSRF) is another common vulnerability that occurs when an attacker tricks a user into performing unwanted actions on a website without their consent.

To address this issue, the remediation process involves implementing CSRF tokens on the server side. i.e., anti-CSRF headers such as X-CSRF-Token or X-Requested-With in your AJAX requests. This entails generating unique tokens for each user session, including a token as a hidden input field in each form and then validating these tokens on the server side to effectively prevent CSRF attacks. Also, check the HTTP Referer header to ensure requests originate from the same domain.

Here’s an example to handle and might implement CSRF protection in a PHP application:

// Generating and verifying CSRF tokens

// Generating a CSRF token and storing it in the session
session_start();
if (!isset($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32)); // Generate a random 32-byte token
}

// Including the CSRF token in a form
$csrf_token = $_SESSION['csrf_token'];
echo '<form method="post">';
echo '<input type="hidden" name="csrf_token" value="' . $csrf_token . '">';
echo '<button type="submit">Submit</button>';
echo '</form>';

// Verifying the CSRF token on the server side
if (isset($_POST['csrf_token']) && $_POST['csrf_token'] === $_SESSION['csrf_token']) {
// Process the request
} else {
// Handle CSRF attack attempt
}

Security Misconfigurations: Security Misconfigurations represent a persistent and critical set of vulnerabilities that can expose web applications and systems to various security risks. These misconfigurations can lead to severe consequences such as data breaches, unauthorized access, and other security incidents.

Some common security misconfigurations include unencrypted Web configuration Files, Passwords in configuration Files, Debug Enabled, Directory Indexing Enabled, Missing Default cases in switch statements and Improper Exceptions Handling, Unrestricted File Upload, Weak Session Management, Improper CORS Configuration and Insecure Header Configurations.

<?php
// Example of secure coding practices

1. Storing sensitive configuration outside web root
BAD: include 'config.php'; // if 'config.php' contains sensitive data
GOOD: require_once '../config/config.php';

2. Storing passwords securely
BAD: $dbPassword = 'mysecretpassword';
GOOD: $hashedPassword = password_hash('mysecretpassword', PASSWORD_BCRYPT);

3. Disabling debug mode
BAD: define('DEBUG', true);
GOOD: define('DEBUG', false);

4. Disabling directory indexing
BAD: Options +Indexes
GOOD: Options -Indexes

5. Handling default cases in switch statements
BAD:
switch ($userRole) {
case 'admin':
...}

GOOD:
switch ($userRole) {
case 'admin':
...
break;
default:
// Handle unexpected role
}

6. Proper exception handling

try {
// Code that may throw exceptions
} catch (Exception $e) {
// Log the error
error_log('Exception: ' . $e->getMessage());
// Display user-friendly error message
echo 'An error occurred. Please try again later.';
}

7. Unrestricted File Upload

$allowedExtensions = ['jpg', 'png', 'gif'];
$allowedMimeTypes = ['image/jpeg', 'image/png', 'image/gif'];
$maxFileSize = 1000000; // 1 MB
$uploadedFile = $_FILES['userfile'];
$filename = $uploadedFile['name'];
$extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
$mime = mime_content_type($uploadedFile['tmp_name']); // Get the MIME type

if (
in_array($extension, $allowedExtensions) &&
in_array($mime, $allowedMimeTypes) &&
$uploadedFile['size'] <= $maxFileSize
) {
// Process the upload

// Move the uploaded file to a secure location outside the web root
$targetDirectory = '/path/to/secure/directory/';
$uniqueFilename = uniqid() . '.' . $extension;
$targetPath = $targetDirectory . $uniqueFilename;

move_uploaded_file($uploadedFile['tmp_name'], $targetPath);
} else {
// Reject the upload
}

8. Weak Session Management
session_start();
$currentTime = time();
$maxInactiveTime = 1800; // 30 minutes

if (isset($_SESSION['last_activity']) && $currentTime - $_SESSION['last_activity'] > $maxInactiveTime) {
// Regenerate the session ID to prevent fixation
session_regenerate_id(true);

// Destroy the old session and create a new one
session_unset();
session_destroy();

// Optionally, create a new session
session_start();
} else {
$_SESSION['last_activity'] = $currentTime;
}

9. CORS Configuration (HTTP response header)
header('Access-Control-Allow-Origin: https://trusted-domain.com');
header('Access-Control-Allow-Methods: GET, POST');
header('Access-Control-Allow-Headers: Content-Type');
header('Access-Control-Allow-Credentials: true');

10. Insecure Header Configuration
header('Content-Security-Policy: default-src \'self\'');
header('Strict-Transport-Security: max-age=31536000; includeSubDomains');
header('X-Frame-Options: DENY');
header('X-XSS-Protection: 1; mode=block');
header('X-Content-Type-Options: nosniff');
?>

The examples provided above represent only a fraction of the high-level vulnerabilities that can be discovered through a code review. To ensure a robust security posture, it is crucial to perform a comprehensive review customized for the application and technology stack. This approach will effectively uncover and remediate all potential security weaknesses.

Here is the training platform where you can evaluate and enhance your secure code review skills:

· https://owasp.org/SecureCodingDojo/codereview101/

Conclusion

I hope this article provides you with enough information and the methodology to get started performing Secure Code Review. Initially, make a habit of regularly reviewing the smaller codes. Regularly reviewing smaller sections of code and emphasizes the importance of proper planning, execution, and a thorough understanding of the code being reviewed.

References

· OWASP Code Review Guide

· Source Code Analysis Tools

· https://pentesterlab.com/exercises/codereview/course

· https://github.com/mgreiler/code-review-checklist

· https://book.hacktricks.xyz/network-services-pentesting/pentesting-web/code-review-tools

--

--

Krunal Kawa

Cyber Security expert who has a thorough understanding of Cybersecurity tools and techniques.