Secure Coding Guidelines

Our secure code guidelines are designed to help you quickly understand the ins and outs of software vulnerabilities such as the OWASP Top 10, what they look like, and how to avoid them.

let ip = request.params.ipAddress;

system("ping " + ip);

Command Injection

Let’s look at Command Injection by itself. We’re mostly going to focus on a few different examples so it’s easier to see what it looks like in action. So, as a quick refresher, Command Injection vulnerabilities occur when user input uses part of an operating system command. Read the guideline for more information.

View The Guideline   

import mysql.connector
db = mysql.connector.connect
#Bad Practice. Avoid this! This is just for learning.
(host="localhost", user="newuser", passwd="pass", db="sample")
cur = db.cursor()
name = raw_input('Enter Name: ')
cur.execute("SELECT * FROM sample_data WHERE Name = '%s';" % name) for row in cur.fetchall(): print(row)
db.close()

SQL Injection

SQL injection (SQLi) injects code into SQL statements to attack and gather important information from an application. It is a web security vulnerability. It is the most common technique of hacking that manipulates the database and extracts crucial information from it.

View The Guideline   

Some of the most common injection types include:

SQL Injection
Cross-Site Scripting (HTML/Javascript injection)
Path Traversal (Path/Url injection)
Command Injection
Code Injection

Injection 101

One of the most well-known classes of vulnerabilities tends to be injection vulnerabilities, especially, and surprising no one, the undisputed poster-child: SQL Injection. It’s hard to avoid hearing about SQL injection in the tech world, so we’re just going to talk about it. Read on to get a short introduction to injection flaws.

View The Guideline   

public string UploadProfilePicture(FormFile uploadedFile)
{
    // Generate path to save the uploaded file at
    var path = $"./uploads/avatars/{request.User.Id}/{uploadedFile.FileName}";

    // Save the file
    var localFile = File.OpenWrite(path);
    localFile.Write(uploadedFile.ReadToEnd());
    localFile.Flush();
    localFile.Close();

    // Update the profile picture 
    UserProfile.UpdateUserProfilePicture(request.User, path)

    return path;
}

File Upload

It’s very common that applications will, at some point or another, need to allow users to upload a file (either for use or just for storage) somewhere within the application. While it seems simple enough, how this function is implemented can be pretty critical due to the potential risks associated with how file uploads are handled. Read the guideline for more information.

View The Guideline   

cs

// Ensure the default behaviour is to authenticate requests, and check if they are admin
[Authenticate]
[Authorize("Admin")]
public class SecureController : Controller
{

}

public class MyController : SecureController
{

    // Overrides the Authorize attribute inherited to allow any user to access the page

Authentication and Authorization

View The Guideline   
Feature Cryptographic hash Password hash Speed Very fast Intentionally slow Work factor can be adjusted No Yes

Password Storage

If your application authenticates users, chances are, it’s also going to deal with passwords. Handling user passwords is a really big deal and handling them appropriately is an even bigger one. It's hard to imagine a scenario worse than an application being attacked and user passwords being leaked across the internet for all to see. How can passwords be stored safely and according to best practices? Let’s take a look at a few ways. 

View The Guideline   

html
<form method="POST">
     <input name="Id" type="hidden" value="666">
     <input name="Name" type="text" value="Bad guy">
     <input name="EmailAddress" type="text" value="hacker@attacker.com">
     <input name="IsAdmin" type="hidden" value="true">
     <input type="submit">
</form>  

Mass Assignment

Mass Assignment is a vulnerability where API endpoints don’t restrict which properties of their associated object can be modified by a user. This vulnerability can occur when making use of a library/framework that allows for the automatic binding of HTTP parameters onto a model that then goes on to be used without any validation. The use of the automatic binding from a request onto an object can be extremely helpful at times, but it can also lead to security issues if the model has properties that aren’t meant to be accessible to the user. Read the guideline for more details.

View The Guideline   

ts
let url = request.params.url;

let response = http.get(url);
let render = response.render();

return render.export();

Server-Side Request Forgery

Server-Side Request Forgery vulnerabilities occur when a user is able to cause an application to make HTTP requests to an attacker-determined domain. If an application has access to private/internal networks, an attacker could also cause the application to make requests to internal servers. We’ll take a closer look at this with some examples to better understand what it looks like in action in this guideline.

View The Guideline   

Many frameworks also have a set of endpoints that can be enabled which allows for monitoring of the application, whether that's in a production or test/dev environment. These can include:

Metrics (Prometheus)
Logs
Environment information
Path/Url Mappings

Security Misconfiguration

Security Misconfiguration is somewhat of an umbrella term that covers common vulnerabilities that come into play because of an application’s configuration settings, rather than bad code. It’s a wide-ranging subject and it’s heavily dependent on factors like your technology stack. Often times addressing these issues is something that seems simple, like changing a configuration file or even a single line of code, but the impact and consequences of these vulnerabilities can be severe. Read our guideline to learn more about this vulnerability and how to mitigate it.

View The Guideline   

xml
<?xml version="1.0" ?>
<!DOCTYPE outerElement [
   <!ENTITY externalEntity SYSTEM  "file:///etc/passwd" > ]>
<outerElement>&externalEntity;</outerElement>

Security misconfiguration - XXE detailed

The “XML eXternal Entities” (XXE) vulnerability class is a Security Misconfiguration involving XML parsers. The XML standard includes ways of referencing “entities”, such as files and URLs. It’s often the default for parsers to fully resolve external entities which means that XML documents can lead to the disclosure of files and other sensitive information to potential attackers. Read the full guideline for more information.

View The Guideline   

Best practices:

Audit logging for sensitive functions
Error logging
Storing logs in a centralized location
Retain logs for a defined amount of time
Regularly audit logs for PII

Insufficient Logging and Monitoring

Logging and monitoring are often an afterthought when something has already gone wrong, but really, failure to ensure there is proper logging and monitoring can be very costly. On one extreme, when an incident occurs (be it security-related or not), having few or no logs at all makes it impossible to figure out what’s actually happened. On the other extreme, logging too much data can lead to privacy issues which can then lead to issues with regulators. Read our guideline for best practices to avoid insufficient logging and monitoring.

View The Guideline   

{
 "dependencies": {
   "foo": "1.0.0 - 2.9999.9999",
   "bar": ">=1.0.2 <2.1.2"
 }
}

Using Components with Known Vulnerabilities

Most applications make use of large amounts of third-party components. These components provide everything from logging, templating, database access, and more. This makes developing software much easier and saves a lot of time. But they're also made by people, which means some will inevitably contain vulnerabilities. Read the guideline to find out more.

View The Guideline   
pseudo
let baseFolder = "/var/www/api/documents/"; 
let path = baseFolder + request.params.filename;

return file.read(path);

Injection - Path Traversal

Path Traversal is another pretty common type of injection vulnerability. They tend to happen when the construction of a URI (be it for a URL, file path, or otherwise) doesn’t properly ensure that the fully resolved path isn’t pointing outside the root of the intended path. The impact of a path traversal vulnerability heavily depends on the context of where the traversal occurs, and the overall hardening that’s been done. Read the guideline to learn more.

View The Guideline   
```html
<!--- UNSAFE: The htmlSnippet will get interpreted without any escaping --->
@Html.Raw(htmlSnippet)
```

Injection - XSS

Cross-Site Scripting, also known as XSS, is another type of injection vulnerability that leads to the evaluation of an attacker-controlled script in another user's browser. XSS can also be considered an HTML/JavaScript injection vulnerability. Let’s look at the types of XSS you can encounter.

View The Guideline   

public string UploadProfilePicture(FormFile uploadedFile)
{
    // Generate path to save the uploaded file at
    var path = $"./uploads/avatars/{request.User.Id}/{uploadedFile.FileName}";

    // Save the file
    var localFile = File.OpenWrite(path);
    localFile.Write(uploadedFile.ReadToEnd());
    localFile.Flush();
    localFile.Close();

    // Update the profile picture 
    UserProfile.UpdateUserProfilePicture(request.User, path)

    return path;
}

File Upload

It’s very common that applications will, at some point or another, need to allow users to upload a file (either for use or just for storage) somewhere within the application. While it seems simple enough, how this function is implemented can be pretty critical due to the potential risks associated with how file uploads are handled. Read the guideline for more information.

View The Guideline   
```html
<!--- UNSAFE: The htmlSnippet will get interpreted without any escaping --->
@Html.Raw(htmlSnippet)
```

Injection - XSS

Cross-Site Scripting, also known as XSS, is another type of injection vulnerability that leads to the evaluation of an attacker-controlled script in another user's browser. XSS can also be considered an HTML/JavaScript injection vulnerability. Let’s look at the types of XSS you can encounter.

View The Guideline   
pseudo
let baseFolder = "/var/www/api/documents/"; 
let path = baseFolder + request.params.filename;

return file.read(path);

Injection - Path Traversal

Path Traversal is another pretty common type of injection vulnerability. They tend to happen when the construction of a URI (be it for a URL, file path, or otherwise) doesn’t properly ensure that the fully resolved path isn’t pointing outside the root of the intended path. The impact of a path traversal vulnerability heavily depends on the context of where the traversal occurs, and the overall hardening that’s been done. Read the guideline to learn more.

View The Guideline   

Some of the most common injection types include:

SQL Injection
Cross-Site Scripting (HTML/Javascript injection)
Path Traversal (Path/Url injection)
Command Injection
Code Injection

Injection 101

One of the most well-known classes of vulnerabilities tends to be injection vulnerabilities, especially, and surprising no one, the undisputed poster-child: SQL Injection. It’s hard to avoid hearing about SQL injection in the tech world, so we’re just going to talk about it. Read on to get a short introduction to injection flaws.

View The Guideline   

import mysql.connector
db = mysql.connector.connect
#Bad Practice. Avoid this! This is just for learning.
(host="localhost", user="newuser", passwd="pass", db="sample")
cur = db.cursor()
name = raw_input('Enter Name: ')
cur.execute("SELECT * FROM sample_data WHERE Name = '%s';" % name) for row in cur.fetchall(): print(row)
db.close()

SQL Injection

SQL injection (SQLi) injects code into SQL statements to attack and gather important information from an application. It is a web security vulnerability. It is the most common technique of hacking that manipulates the database and extracts crucial information from it.

View The Guideline   

let ip = request.params.ipAddress;

system("ping " + ip);

Command Injection

Let’s look at Command Injection by itself. We’re mostly going to focus on a few different examples so it’s easier to see what it looks like in action. So, as a quick refresher, Command Injection vulnerabilities occur when user input uses part of an operating system command. Read the guideline for more information.

View The Guideline   

html
<form method="POST">
     <input name="Id" type="hidden" value="666">
     <input name="Name" type="text" value="Bad guy">
     <input name="EmailAddress" type="text" value="hacker@attacker.com">
     <input name="IsAdmin" type="hidden" value="true">
     <input type="submit">
</form>  

Mass Assignment

Mass Assignment is a vulnerability where API endpoints don’t restrict which properties of their associated object can be modified by a user. This vulnerability can occur when making use of a library/framework that allows for the automatic binding of HTTP parameters onto a model that then goes on to be used without any validation. The use of the automatic binding from a request onto an object can be extremely helpful at times, but it can also lead to security issues if the model has properties that aren’t meant to be accessible to the user. Read the guideline for more details.

View The Guideline   
No items found.

xml
<?xml version="1.0" ?>
<!DOCTYPE outerElement [
   <!ENTITY externalEntity SYSTEM  "file:///etc/passwd" > ]>
<outerElement>&externalEntity;</outerElement>

Security misconfiguration - XXE detailed

The “XML eXternal Entities” (XXE) vulnerability class is a Security Misconfiguration involving XML parsers. The XML standard includes ways of referencing “entities”, such as files and URLs. It’s often the default for parsers to fully resolve external entities which means that XML documents can lead to the disclosure of files and other sensitive information to potential attackers. Read the full guideline for more information.

View The Guideline   

Many frameworks also have a set of endpoints that can be enabled which allows for monitoring of the application, whether that's in a production or test/dev environment. These can include:

Metrics (Prometheus)
Logs
Environment information
Path/Url Mappings

Security Misconfiguration

Security Misconfiguration is somewhat of an umbrella term that covers common vulnerabilities that come into play because of an application’s configuration settings, rather than bad code. It’s a wide-ranging subject and it’s heavily dependent on factors like your technology stack. Often times addressing these issues is something that seems simple, like changing a configuration file or even a single line of code, but the impact and consequences of these vulnerabilities can be severe. Read our guideline to learn more about this vulnerability and how to mitigate it.

View The Guideline   
Feature Cryptographic hash Password hash Speed Very fast Intentionally slow Work factor can be adjusted No Yes

Password Storage

If your application authenticates users, chances are, it’s also going to deal with passwords. Handling user passwords is a really big deal and handling them appropriately is an even bigger one. It's hard to imagine a scenario worse than an application being attacked and user passwords being leaked across the internet for all to see. How can passwords be stored safely and according to best practices? Let’s take a look at a few ways. 

View The Guideline   

Best practices:

Audit logging for sensitive functions
Error logging
Storing logs in a centralized location
Retain logs for a defined amount of time
Regularly audit logs for PII

Insufficient Logging and Monitoring

Logging and monitoring are often an afterthought when something has already gone wrong, but really, failure to ensure there is proper logging and monitoring can be very costly. On one extreme, when an incident occurs (be it security-related or not), having few or no logs at all makes it impossible to figure out what’s actually happened. On the other extreme, logging too much data can lead to privacy issues which can then lead to issues with regulators. Read our guideline for best practices to avoid insufficient logging and monitoring.

View The Guideline   

{
 "dependencies": {
   "foo": "1.0.0 - 2.9999.9999",
   "bar": ">=1.0.2 <2.1.2"
 }
}

Using Components with Known Vulnerabilities

Most applications make use of large amounts of third-party components. These components provide everything from logging, templating, database access, and more. This makes developing software much easier and saves a lot of time. But they're also made by people, which means some will inevitably contain vulnerabilities. Read the guideline to find out more.

View The Guideline   

cs

// Ensure the default behaviour is to authenticate requests, and check if they are admin
[Authenticate]
[Authorize("Admin")]
public class SecureController : Controller
{

}

public class MyController : SecureController
{

    // Overrides the Authorize attribute inherited to allow any user to access the page

Authentication and Authorization

View The Guideline   
Secure Code Warrior Learning Platform

Discover the Secure Code Warrior Learning Platform

We secure software through developer-driven security at the start of the software development lifecycle.

Visit Secure Code Warrior