DEV Community

Gilad David Maayan
Gilad David Maayan

Posted on

Secure Coding Best Practices for 2022

https://www.vecteezy.com/free-photos

What Is Secure Coding?

Secure coding is the process of developing code in a way that ensures security and eliminates vulnerabilities. It requires knowledge of exploitable issues in specific programming languages, as well as vulnerabilities associated with the hosting environment.

While developers cannot control all variables that can lead to environment or integration vulnerabilities, they can control the source code. The fewer vulnerabilities they include when building software, the safer the application and its users will be.

As teams adopt a DevSecOps approach (converging development, security, and operations teams), secure coding skills are becoming a requirement for many developers. From an organization’s perspective, it is less expensive and much less complex to eliminate code vulnerabilities during development than to patch problems in production.

Examples of Software Vulnerabilities

Code Injection
Attackers use code injection vulnerabilities to inject malicious code into an application and trick the application into interpreting and executing it.

Typically, malicious injection involves attackers constructing partial code snippets and providing them via user input forms which do not have sufficient input validation. Attackers identify flaws in user input validation, such as data format, acceptable characters, and expected amount of data, and use them as the basis for developing malicious code.

Code injection can be used to disrupt business operations, gain unauthorized access to sensitive data, and in some cases completely compromise an application and its hosting environment.

XML External Entity Injection (XXE)
XXE is a web security vulnerability that allows an attacker to interfere with the way an application processes XML data. When successful, attackers can view files on the application server's file system and interact with backends or external systems that the application has access to.

XXE is relevant to applications that use the XML format to send data between the browser and the server. Applications that do this almost always use standard libraries or platform APIs to process XML data from the server. The XXE vulnerability occurs because the XML specification contains a number of potentially dangerous features, which are supported by standard parsers, yet are not normally used by applications.

Remote Code Execution (RCE)
RCE attacks allow an attacker to execute malicious code remotely on a computer. The impact of RCE vulnerabilities can range from executing malware to an attacker taking complete control of an infected system.

An attacker can achieve RCE in several ways, including:

  • Injection attacks (described above)
  • Deserialization attacks—deserialization transforms a bitstream into an object that can be used by a software program. Within serialized data, specially formatted user input can be interpreted as executable code by the deserializer, leading to RCE.
  • Out-of-bounds writes—the application periodically allocates a fixed-size block of memory to store data, including user-supplied data. If this memory is misallocated, an attacker could manipulate input written outside the allocated buffer. Executable code is also stored in memory, so any user-supplied data written to the correct location could be executed by the application.

Server-Side Request Forgery (SSRF)
SSRF attacks involve attackers exploiting server capabilities to access or modify resources. Attackers target applications that fetch data from URLs or allow users to read data from URLs. The attacker can then manipulate those URLs by replacing them with new URLs or forging a URL path traversal.

Typically, an attacker provides a URL (or modifies an existing URL), and code running on the server reads the data or sends data to the URL. An attacker could use the URL to access sensitive, internal data and services, such as HTTP-enabled databases or server configuration data.

Cross-Site Scripting (XSS)
XSS attacks involve attackers injecting malicious code into web apps or websites. While similar to SQL injection, XXS differs because the malicious script only runs when a user goes to a compromised application or site. The attackers may execute an XSS attack by inserting a script into input fields—the compromised page runs the script when a visitor views it.

XSS attacks often expose sensitive data without arousing suspicion of the compromise, damaging a business’s long-term reputation. Attackers may steal any data the user sends to the infected site or application without the user realizing it.

Local File Inclusion (LFI)
LFI attacks exploit a web application’s dynamic local file inclusion mechanism. For example, a web app that accepts remote user input may be vulnerable to LFI if it passes the input (e.g., a URL or parameter value) to a file inclusion command. Attackers may exploit this mechanism, tricking the application into including a file with malicious code.

Many web applications use file inclusion because it allows the app to package shared code into separate files for future reference by the primary modules. A web application may implicitly or explicitly execute malicious code when referencing files for inclusion—for example, to call a given procedure. Applications are usually vulnerable to LFI if they have a module-to-load option based on HTTP requests.

Security Configuration Errors
Misconfigured security controls are an especially dangerous vulnerability in web apps because they offer opportunities for an attacker to infiltrate the app. Any library, application, framework, or operating system may contain an exploitable security misconfiguration.

Attackers can exploit various security configuration errors such as unmodified default settings, incomplete or ad hoc configurations, cloud data, HTTP header misconfiguration, and plaintext messages disclosing sensitive information.

Secure Coding Standards

OWASP Top 10
The Open Web Application Security Project (OWASP) is a global nonprofit organization that teaches software developers to securely design, build, and maintain applications. It produces an annual report, OWASP Top 10, listing the most critical API and web application security risks for the year.

CWE Top 25
The Common Weakness Enumeration (CWE) Top 25 lists common security vulnerabilities in hardware and software, including programming languages like Java, C, and C++. The CWE community compiles and maintains this list based on feedback about the most critical and widespread vulnerabilities that may result in serious breaches.

CVE
Common Vulnerabilities and Exposures (CVE) lists computer vulnerabilities and exposures in specific software products. It aggregates information from multiple vulnerability databases, allowing users to compare security services and tools.

CERT Coding Standards
The Community Emergency Response Team (CERT) publishes standards that support popular programming languages like Java, C, and C++. A risk assessment accompanies every guideline in the coding security standards, helping development teams understand the consequences of violating the specific recommendation or rule.

NVD
The National Vulnerability Database is a US government database providing information about vulnerability management data. It is standards-based and linked to the CVE list, providing additional information on severity and impact scores and how to address vulnerabilities.

Users must refer to the Common Vulnerability Scoring System (CVSS) to calculate vulnerability severity scores. This system is an industry standard for evaluating the severity of cybersecurity vulnerabilities in software, assigning a score to each vulnerability.

DISA STIGS
The Defense Information Systems Agency (DISA) offers communication support to help individuals and organizations working with the US Department of Defense. It supervises the technical aspects of collecting, arranging, and managing data for defense purposes. DISA provides Security Technical Implementation Guides (STIGs) to help organizations operate security systems.

6 Secure Coding Best Practices

1. Shift Security Left
A DevSecOps approach, adopted by many development organizations, focuses on the principle of shifting security left. This means adding security practices early in the SDLC, to reduce the chance that bugs will go unnoticed and reach testing and production environments. Catching security bugs early makes it possible to fix them easily and inexpensively.

When security becomes an integral part of the development process, developers are responsible for testing open source dependencies and proprietary code for risks, before they commit them to a source code repository. Even after code is committed, security tests are run at all stages of the development pipeline to identify security flaws as soon as possible.

Resources like the OWASP Top 10 list, and automated tools such as static application security testing (SAST) and dynamic application security testing (DAST) can help developers quickly identify security defects and understand how to fix them.

2. Validation of Inputs and Encoding of Outputs
All user input must be validated against syntactic and semantic standards, and queries must be parameterized or otherwise clearly marked as user input, and separated from code for execution. Whitelisting is the preferred method for validation and can be achieved through regular expression comparisons.

Application outputs must be encoded through entities such as JavaScript hex or HTML, to remove potentially harmful characters and invalidate script commands. Combining these techniques helps prevent cross-site scripting, code injection, and related attacks.

3. Authentication and Session Management
Authentication is a critical part of application security. Server-side session management and identity management controls can minimize the risk of session hijacking or credential compromise. Multi-factor authentication provides better security, and many organizations are transitioning to passwordless authentication.

Implementing conservative timeouts during periods of inactivity can help keep user data safe, while reducing the risk of user session abuse. Limiting the number of concurrent sessions from the same user account ensures that only legitimate users are able to access your application or site.

4. Proper Encryption Techniques
Using cryptographic tools developed by recognized experts, such as Google KeyCzar and Bouncy Castle, is safer and easier than developing your own solution. Regardless of the encryption protocol used, it is important to use appropriate design methods such as layering and strict trust policies. Incorrect key management can break the strongest encryption, so ensure you store keys separately from encrypted data.

5. Automation
Automation makes incorporating security practices into the coding processes easier, reducing the risk of human error. Automation ensures that the development pipeline includes important steps while eliminating dangerous variables.

Automation also helps save time. For example, development teams often build servers on demand to run software in the cloud, which can be time-consuming and increases the risk of mistakes. Automated server creation ensures the servers are the same every time, ensuring the team consistently follows secure coding practices.

Security automation is crucial for scaling, allowing teams to introduce security frequently and early in the SDLC while enabling rapid feedback.

6. Threat Modeling the Software
Threat modeling involves testing the software’s design to identify weaknesses that attackers might exploit. Developers use threat modeling to understand better how an attacker might compromise an application, allowing them to build adequate defenses.

The most important step toward writing secure code is investigating attackers’ methods to compromise software. Before learning a new coding technique or syntax, developers must walk through attack scenarios to determine how flawed code can lead to a data breach.

Threat modeling requires the following basic steps:

  • Understanding the app—the team should document how the software functions, focusing on how data flows through the app.
  • Identifying threats—the team traces the data flow to identify weak points.
  • Determining remediation strategies—the team rates the threats and identifies appropriate mitigation methods.
  • Validation—the team checks the model to ensure it covers everything.

Threat modeling is a continuous effort. The DevSecOps team must repeatedly use threat modeling when developers change the application to ensure they don’t introduce new vulnerabilities.

When properly implemented, threat modeling ensures code security, helping teams build security into the software rather than addressing it at the end of the pipeline.

Top comments (0)