Static Code Analysis: An important process for finding vulnerabilities

SSRF-vulnerability
Double-check Inputs to Avoid SSRF Vulnerability
October 13, 2021
windows-active-directory
How do you set up an Active Directory in Windows
October 28, 2021

October 19, 2021

Static code analysis analyses source code and identifies the bugs before the program is run. Vulnerabilities are identified in the source code through Static source code analysis (SSCA); Developers use SSCA to ensure that codes are error-free.

Developers are some of the most creative individuals, but sometimes, while developing functionality, logic or creating any new technology all over, they can unintentionally introduce vulnerabilities, and this is where the static source code analysis jumps in.

Static Source Code Analysis (SSCA) debugs a set of codes before they are executed or pushed as the main application. SSCA is done by scrutinizing the code against programming standards/policies and analyzing important functionalities of the application to find either logic flaws, use of outdated packages, code vulnerabilities, dangerous functions or a lot more.

Benefits of learning source code review

  • Gives you a deeper understanding of how a developer thinks and how functionality can be exploited.
  • If you are a Pentester, you’d understand why a bug exists in the first place.
  • Helps you find more bugs. Now that you know how a developer thinks and implements a piece of code, you can try to find a work-around for the same functionality and exploit it.
  • Helps you find sensitive information related to your target, sensitive instances like AWS keys, auth token, API keys, hardcoded credentials, exposed files and a lot more.
  • Source: Source is that part of the code that allows a vulnerability to exist
  • Sink: Sink as part of the code allows any tainted user control input to pass through it. It can be a function.

Factors to consider while going through a Static Source Code Analysis

 1. Programming Language

Programs written in safe languages like C# or Java are less susceptible to security bugs like buffer overflows than other languages like C and C++. While working on a SAST, the programming language you are working with determines the bug types in the application.

 2. Risk

Performing SAST can be a good starting point for strengthening the security, but even an impeccably executed SAST cannot help reduce 100% of the risk. That’s why code reviewers need prioritization; they need to prioritize functionalities or bugs for testing. Start with finding critical severity bugs and gradually move into the low-level bugs. Lines of code too can determine the number of bugs that can be present in a source code: the more the number of lines in the source code, the more chances of finding security bugs.

 3. Resources, Time allocation and the deadline

Assigning resources can be a bit tricky; a complicated application will require someone with a deep understanding of the programming concept, logic, along with the ability to swiftly analyze the code. Further, the assigning must be time-bound; Time plays a vital role in source code review; any complicated program requires more time and resources; if the same project is allotted less time, prioritizing the bugs and functionalities should become the first task.

Why a Manual approach to Static Source Code Analysis?

Though, there exists a decent number of good Source Code Analysis tools that can help a reviewer by finding many code vulnerabilities in a source code with only a few false positives. But ideally, these tools don’t touch the unexplored territories of Business Logic Vulnerabilities; they come with a very limited understanding of bugs and their logic. Design flaws are something these tools can barely evaluate. And Lastly, many times, issues reported by these tools are a false positive and not a security vulnerability.

Nevertheless, SASTs can many times be helpful and save a lot of time for a reviewer. Choosing a proper SAST is an essential task too. Few tips to follow while looking for a proper SAST:

  1. Use the tool that supports or is built specifically to analyze the programming language used in the application.
  2. Does the tool report a lot of false positives?
  3. Commercial tools do have lots of advantages and features over a free SAST. Identifying the preference between commercial and free tools can help a reviewer with a good approach to finding a proper SAST.

Secure Coding Practices:

Static Source Code review, used only for, identifies “Insecure Code”, and an application developed without proper secure coding standards will be prone to various vulnerabilities. Secure Coding or Defensive Coding loosely translates to following best coding practices while keeping the security of the application in mind. Applications developed via these practices are less susceptible to vulnerabilities and promise the best application security.

Below are some Secure Coding Standards a Developer must follow:

  • Input Validation: A developer must recognize all the untrusted data sources and data inputs and validate them. A properly implemented input validation makes the application secure against the majority of Injection vulnerabilities.
  • Compiler Warnings: Compilation of code must be done via the highest possible warning, and then these warnings must be eliminated by altering the code.
  • Parameterized Queries: Prevents injection-based attacks when input validation cannot be implemented.
  • Sanitization of data being sent to other systems: Sanitization of data being exchanged or transferred to a 3rd party system. Any data that is being sent to a command shell, relational DB, or any COTs component must be sanitized; if not, an attacker can call any functions that are not being used via any malicious SQL statement or any injection payload.
  • Follow the principle of least privilege: Every instance/process running into the application must run with the least privilege to complete the task.

Security Issues that may beset a reviewer using Static Source Code Analysis

Injection:

Injection attacks allow any malicious user to add or inject arbitrary commands or content into an application that can eventually cause the application to behave in an unintended way.

Injection vulnerabilities can lead to various security issues such as:

  1. Sensitive Information Disclosure
  2. Data’s integrity can be compromised. Any SQLi attack can tamper with the stored data in the DB by modifying, deleting or inserting new records.
  3. Privilege Escalation.
  4. Access to the back-end network.

 Let us discuss one of the most common injection vulnerabilities:

 SQL Injection:

Considering that SQLi is the most common injection vulnerability that exists, These can be easy to exploit. The issue with handling SQL queries in the legacy applications is that previously developers gave close to zero thoughts about secure coding practices and many times ended up using string concatenation of user input with a predefined SQL statement, which an attacker could use to leverage the vulnerability.

When the SQL parser is unable to differentiate between actual code and user input, an attacker can craft a malicious SQL payload and compromise the application’s data.

Taking the example of an insecure Java code dealing with an SQL Query            

</Non-Compliant Code

String query = “SELECT * FROM users WHERE forename = ‘ “+ firstname +” ‘ AND surname= ‘ ” + lastname+ ” ‘ “;

Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery(query);

Here the value of the variables “forename” & “surname” is directly being concatenated to the SQL query string without any encoding, malicious character escaping or any kind of input sanitization. When an attacker provides malicious input to either of the variables, the SQL Parser, not able to differentiate between the actual line of code and user-input, will eventually add the malicious input as a valid code into the SQL query, thus eventually executing a successful SQL injection attack.

SQLi demonstration for the non-compliant code:

String query = “SELECT * FROM users WHERE forename = ‘ “+ firstname +” ‘ AND surname= ‘ ” + lastname+ ” ‘ OR ‘1’=’1’ “;

Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery(query);

</Compliant Code via Parameterized SQL Queries>

String query = “SELECT id, firstname, lastname FROM authors WHERE forename =

? and surname = ?”;

PreparedStatement pstmt = connection.prepareStatement( query ); pstmt.setString( 1, firstname );

pstmt.setString( 2, lastname );

In the above Code Snippet, SQL Query is crafted in a manner that does not rely on client-side input and then the “PreparedStatement -> pstmt” is generated from it. The “setString” function is used to replace the 1st question mark with the string value of “firstname” and the 2nd question mark with the string value of “lastname”. The “setString” function, when called, makes sure that no SQL syntax is present in the string value.

Few checks to perform to prevent SQL injection:

  1. Validate user input based on length, type, format & range.
  2. Never build SQL statements directly from user input.
  3. Use parameterized queries rather than string concatenation.
  4. Perform multiple input validation and sanitization.
  5. Use stored procedures to validate user input; When not using stored procedures, use SQL API provided by the platform. i.e. Parameterized Statements.
  6. Review all the code snippet that performs any SQL execution.
Session management and Authentication

Authentication:

Web applications and web services both use authentication as the mean of access control via valid credentials. Access control to any web application or service is essential as it protects the CIA triad of the application.

Authentication is the first step towards the protection of any application. An authenticated user has the privilege of authorization, wherein they can interact with the application with a certain privilege, whereas an unauthenticated user is denied from using the same application.

  • While reviewing the code for Authentication, do look out for few common issues such as:
  • Ensuring that the Login page URL is accessible only over a TLS connection
  • Make sure that any invalid credential error message does not leak any kind of sensitive information
  • Implement the use of a long and complex password policy
  • Implement Account Lockout functionality once invalid credentials are entered for the user more than allowed time
  • Make sure that the application employs the usage of a strong encryption method to store passwords 
  • While reviewing any MVC .NET application, it is important that all the pages use SSL and not just the login page.

Session Management:

A web session is a sequence of HTTP requests and response cycles linked to the user. The session enables establishing access rights, interacting with the application and a lot more.

Any code reviewer must be able to determine the technique employed for session management of the user so that they can spot vulnerabilities related to that technique.

The implementation of a secure session must meet the following requirements:

  • Session ID names shouldn’t be descriptive
  • Remember to change the default Session ID name
  • Session ID length must be at least 128 bits

While reviewing the code for Session management, do look out for few common issues, such as, code reviewer needs to understand what information is being stored into an application cookie. They need to make sure that no sensitive information is leaking in the cookie content:

  • Compliant .NET ASPX web.config using SSL for cookies:

<authentication mode=”Forms”>

<forms loginUrl=”member_login.aspx” cookieless=”UseCookies”

requireSSL=”true” path=”/MyApplication” />

</authentication>

  • Java web.xml

<session-config>

<cookie-config>

<secure>true</secure>

</cookie-config>

</session-config>

  • PHP.INI

void session_set_cookie_params ( int $lifetime [, string $path [, string

$domain [, bool $secure = true [, bool $httponly = true ]]]] )

Few other security misconfigurations to look for in web.config file:
● Missing Custom Error Handling

 A developer must always remember to enable custom error pages so that any attackers can not mine any sensitive information.

Misconfigured Code:

 <customErrors mode=”Off” />

Secure Code:

 <customErrors mode=”RemoteOnly” />

 <customErrors mode=”On” defaultRedirect=”YourErrorPage.htm” />

● Password in the configuration file

Hardcoded credentials must always be removed from the configuration file. If left out, you are providing attackers direct access to the application.

Misconfigured Code:

<authentication mode=”Forms”>

<forms>

<credentials>

<user name=”John” password=”John@991″/>

</credentials>

</forms>

</authentication>

Secure Code:

<authentication mode=”Forms”>

<forms             timeout=”129600″       name=”myWebApp”    protection=”All” slidingExpiration=”false”                                               loginUrl=”~/Account/login.aspx” cookieless=”UseCookies”/>

</authentication>

 ● Debugging Enabled

Debugging mode enabled can help an attacker learn sensitive information about the application and may formulate an attack plan.

Misconfigured Code:

<configuration>

<system.web>

<compilation debug=”true” targetFramework=”4.5″>

….

</compilation>

</system.web>

</configuration>

Secure Code:

<configuration>

<system.web>

<compilation debug=”false ” targetFramework=”4.5″>

….

</compilation>

</system.web>

</configuration>

● Cookieless Session State Enabled

Asp.net web application allows storing the session token in the page URLs rather than a cookie.

Misconfigured Code:

<configuration>

 <system.Web>

 <sessionState cookieless=”UseUri”/>

 </system.Web>

 </configuration>

Secure Code:

 <configuration>

 <system.Web>

 <sessionState cookieless=”UseCookies”/>

 </system.Web>

 </configuration>

 ● Tracing Enabled

Tracing features can help a developer to debug an application, but for an attacker, Tracing features are like a goldmine as an attacker can utilize this feature to attack the application.

Misconfigured Code:

<configuration>

<system.Web>

<trace enabled=”true” localOnly=”false”/>

</system.Web>

</configuration>

Secure Code:

<configuration>

<system.Web>

<trace enabled=”false” localOnly=”true”/>

</system.Web>

</configuration>

Conclusion

Static source code analysis helps to analyze the code without executing it. This allows the developer to identify vulnerabilities hiding in the remote and unattended section of the code. Static code analysis can spot bugs in the early stages of the development cycle, thereby; leading to a sharp decrease in bug fixing costs. Static source code analysis must be integrated into any organization’s software developing process.

References:

  1. OWASP CODE REVIEW GUIDE 2.0
  2. https://securecode.wiki/docs
  3. https://www.codechef4u.com/post/2015/07/12/Security-Vulnerabilities-in-Webconfig

Discover more from SecureLayer7 - Offensive Security, API Scanner & Attack Surface Management

Subscribe now to keep reading and get access to the full archive.

Continue reading

Enable Notifications OK No thanks