Most Dangerous Coding Errors from CWE (Common Weakness Enumeration)

The US National Security Agency (NSA) has helped put together a list of the most dangerous coding errors called Common Weakness Enumeration.

By Tim TrottSoftware Engineering • January 28, 2009
2,750 words, estimated reading time 11 minutes.
Most Dangerous Coding Errors from CWE (Common Weakness Enumeration)

This list lists the top 25 most dangerous coding errors that can lead to security holes or vulnerable areas targeted by cybercriminals. Experts say many of these errors are not well understood by programmers. According to the SANS Institute in Maryland, two errors led to over 1.5 million website security breaches during 2008.

Over 30 organisations, including the NSA, the Department of Homeland Security, Microsoft, and Symantec, published the document, giving developers a minimum set of coding errors that must be eradicated before customers use the software.

There appears to be broad agreement on the programming errors; now it is time to fix them.SANS director, Mason Brown

Patrick Lincoln, director of the Computer Science Laboratory at SRI International, told the BBC that if programmers prevented these errors from appearing in their code, it would deter most hackers.

This list is primarily for people who have the first responsibility for designing a system. Veteran programmers have probably learnt the hard way, whereas a new programmer will make more basic errors.Patrick Lincoln

Previously, most advice focused on vulnerabilities resulting from programming errors. This top 25 list examines the actual programming errors themselves.

We need to ensure every programmer knows how to write code free of the top 25 errors. Then, we need to ensure every programming team has processes to find and fix these problems, both in existing and future code and have the tools to verify that the code is error-free.

The US Office of the Director of National Intelligence, the principal adviser to the President, the National Security Council and the Homeland Security Council also lent their support to the list.

The Top 25 Dangerous Coding Errors

CWE-20:Improper Input Validation

When software fails to validate input properly, an attacker can craft the input in a form not expected by the rest of the application. This will lead to parts of the system receiving unintended input, which may result in altered control flow, arbitrary control of a resource, or arbitrary code execution.

C#
decimal price = 20.00;
int quantity = Request.Params["quantity"];
decimal total = price * quantity;
chargeUser(total);

The user has no control over the price variable. However, the code does not prevent a negative value from being specified for quantity. If an attacker were to provide a negative value, then the user would have their account credited instead of debited.

CWE-116:Improper Encoding or Escaping of Output

The software prepares a structured message for communication with another component. Still, it does not sufficiently encode or escape the data in a way that fails to preserve the intended structure of the message.

xml
<% string email = Request.Params["email"]; %>
...
Email Address: <%= email %>

Here, a value read from an HTML form parameter is reflected in the client browser without being encoded before output.

CWE-89:Failure to Preserve SQL Query Structure

The application dynamically generates an SQL query based on user input, but it does not sufficiently prevent that input from modifying the intended structure of the query.

C#
string userName = ctx.getAuthenticatedUserName();
string query = "SELECT * FROM items WHERE owner = '" + userName + "' AND itemname = '" + ItemName.Text + "'"; 
sda = new SqlDataAdapter(query, conn); 
DataTable dt = new DataTable(); 
sda.Fill(dt);

The query that this code intends to execute follows:

sql
SELECT * FROM items WHERE owner = <userName> AND itemname = <itemName>;

However, because the query is constructed dynamically by concatenating a constant base query string and a user input string, the query only behaves correctly if itemName does not contain a single-quote character. If an attacker with the username "wiley" enters the string:

sql
name' OR 'a'='a

for itemName, then the query becomes the following:

sql
SELECT * FROM items WHERE owner = 'wiley' AND itemname = 'name' OR 'a'='a';

The addition of OR 'a'='a' to the condition causes the WHERE clause to always evaluate to true, so the query becomes logically equivalent to the much simpler query:

sql
SELECT * FROM items;

This simplification of the query allows the attacker to bypass the requirement that the query only returns items owned by the authenticated user; the query now returns all entries stored in the items table, regardless of their specified owner.

CWE-79:Failure to Preserve Web Page Structure

The software does not sufficiently validate, filter, escape, and encode user-controllable input before it is placed in output used as a web page served to other users.

Cross-site scripting (XSS) vulnerabilities occur when:
Untrusted data enters a web application, typically from a web request.
The web application dynamically generates a web page that contains this untrusted data.

C#
...
protected System.Web.UI.WebControls.TextBox Login;
protected System.Web.UI.WebControls.Label EmployeeID;
...
EmployeeID.Text = Login.Text;
... (HTML follows) ...
<asp:label id="EmployeeID" runat="server" />


...

The code in this example operates correctly if the Employee ID variable contains only standard alphanumeric text. If it has a value that includes meta-characters or source code, then the web browser will execute the code as it displays the HTTP response. Initially, this is not much of a vulnerability. After all, why would someone enter a URL that causes malicious code to run on their computer? The real danger is that an attacker will create a malicious URL and then use e-mail or social engineering tricks to lure victims into visiting a link to the URL. When victims click the link, they unwittingly reflect the malicious content through the vulnerable web application back to their computers. This mechanism of exploiting vulnerable web applications is known as Reflected XSS.

CWE-78:Failure to Preserve OS Command Structure

The software uses externally-supplied input to dynamically construct all or part of a command, which is then passed to the operating system for execution. Still, the software does not sufficiently enforce which commands and arguments are specified.

CWE-319:Cleartext Transmission of Sensitive Information

The software transmits sensitive or security-critical data in cleartext in a communication channel that unauthorised actors can sniff.

C#
string sensitiveData = "Your username and password are 'fred' and 'letmein'";
Response.Write(sensitiveData);

Anyone can read the contents of the message if they have access to any channel being used for communication.

CWE-352:Cross-Site Request Forgery

The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.

When a web server is designed to receive a request from a client without any mechanism for verifying that it was intentionally sent, then it might be possible for an attacker to trick a client into making an unintentional request to the web server, which will be treated as an authentic request. This can be done via a URL, image load, XMLHttpRequest, etc., resulting in data disclosure or unintended code execution.

CWE-362:Race Condition

The code requires that certain states not be modified between two operations, but a timing window exists in which an unexpected actor or process can modify the state.

This can have security implications when the expected synchronisation is in security-critical code, such as recording whether a user is authenticated or modifying important state information that an outsider should not influence.

CWE-209:Error Message Information Leak

The software generates an error message containing sensitive information about its environment, users, and associated data.

This typically occurs when ASP.Net applications are set to customErrors="Off" and debug="true" on a production server. PHP, by default, will output the executing script filename when it crashes out.

CWE-119:Failure to Constrain Operations within the Bounds of a Memory Buffer

The software may allow operations, such as reading or writing, to be performed at addresses not intended by the developer.

When software permits read or write operations on memory located outside of an allocated range, an attacker may be able to access/modify sensitive information, cause the system to crash, alter the intended control flow, or execute arbitrary code.

This should not be an issue with managed .Net code unless you are dealing with legacy COM applications or are using the unsafe keyword to perform pointer operations. This is a high-risk issue in other unmanaged environments, such as C or PHP.

CWE-642:External Control of Critical State Data

If an attacker can modify the state information without detection, it could be used to perform unauthorised actions or access unexpected resources since the application programmer does not expect the state to change.

State information can be stored in various locations, such as a cookie, in a hidden web form field, input parameter or argument, an environment variable, a database record, within a settings file, etc. All of these locations have the potential to be modified by an attacker. When this state information is used to control security or determine resource usage, it may create vulnerability. For example, an application may authenticate and save the state in an "authenticated=true" cookie. An attacker may create this cookie to bypass the authentication.

CWE-73:External Control of File Name or Path

The software allows user input to control or influence paths used in file system operations. This could allow attackers to access or modify system files or other files critical to the application.

Path manipulation errors occur when the following two conditions are met.

  1. An attacker can specify a path used in an operation on the filesystem.
  2. By specifying the resource, the attacker gains a capability that would not otherwise be permitted.

For example, the program may allow the attacker to overwrite the specified file or run with a configuration controlled by the attacker.

CWE-426:Untrusted Search Path

The application searches for critical resources using an externally supplied search path that can point to resources not under the application's direct control.

This might allow attackers to execute their programs, access unauthorised data files, or modify configurations unexpectedly. If the application uses a search path to locate critical resources such as programs, an attacker could modify that path to point to a malicious program, which the targeted application would execute. The problem extends to any critical resource that the application trusts.

CWE-94:Failure to Control Generation of Code

The product does not sufficiently filter code (control-plane) syntax from user-controlled input (data plane) when used within the code the product generates.

When software allows a user's input to contain code syntax, it might be possible for an attacker to craft the code in such a way that it will alter the intended control flow of the software. Such an alteration could lead to arbitrary code execution.

CWE-494:Download of Code Without Integrity Check

The product downloads source code or an executable from a remote location and executes the code without sufficiently verifying the origin and integrity of the code. This allows attackers to execute malicious code by compromising the host server, performing DNS spoofing, or modifying the code in transit.

CWE-404:Improper Resource Shutdown or Release

When a resource is created or allocated, the developer is responsible for properly releasing the resource and accounting for all potential paths of expiration or invalidation, such as a set period or revocation.

Most unreleased resource issues result in general software reliability problems. Still, if an attacker can intentionally trigger a resource leak, the attacker might be able to launch a denial of service attack by depleting the resource pool.

C#
private void processFile(string fName) 
{
StreamWriter sw = new
StreamWriter(fName);
string line;
while ((line = sr.ReadLine()) != null) 
processLine(line);
}

This method never closes the file handle but leaves it open. The Finalize() method for StreamReader eventually calls Close(), but there is no guarantee as to how long it will take before the Finalize() method is invoked. There is no guarantee that Finalise () will ever be invoked. In a busy environment, this can result in the VM using up all of its available file handles.

CWE-665:Improper Initialization

The software does not follow the proper procedures for initialising a resource, which might leave the resource in an improper state when it is accessed or used. This can have security implications when the associated resource is expected to have certain properties or values, such as a variable determining whether a user has been authenticated.

C#
private bool initialized = true;
public void someMethod() 
{
if (!initialized) 
{
// perform initialisation tasks
...

initialized = true;
}
}

Here, a boolean initialised field is consulted to ensure that initialisation tasks are only completed once. However, the field is mistakenly set to true during static initialisation, so the initialisation code is never reached.

CWE-682:Incorrect Calculation

The software calculates incorrect or unintended results that are later used in security-critical decisions or resource management.

When software performs a security-critical calculation incorrectly, it might lead to incorrect resource allocations, incorrect privilege assignments, or failed comparisons, among other things. Many direct results of an incorrect calculation can lead to even larger problems, such as failed protection mechanisms or arbitrary code execution.

CWE-285:Improper Access Control

The software does not consistently perform access control checks across all potential execution paths.

When access control checks are not applied consistently - or not at all - users can access data or perform actions they should not be allowed to perform. This can lead to many problems, including information leaks, denial of service, and arbitrary code execution.

CWE-327:Use of a Broken or Risky Cryptographic Algorithm

Using a broken or risky cryptographic algorithm is an unnecessary risk that may result in disclosing sensitive information.

The use of a non-standard algorithm is dangerous because a determined attacker may be able to break the algorithm and compromise whatever data has been protected. Well-known techniques may exist to break the algorithm.

CWE-259:Hard-Coded Password

The software contains a hard-coded password, which it uses for its inbound authentication or outbound communication to external components.

A hard-coded password typically leads to a significant authentication failure that can be difficult for the system administrator to detect. Once detected, it can be difficult to fix, so the administrator may be forced to turn off the product entirely.

CWE-732:Insecure Permission Assignment for Critical Resource

The software specifies permissions for a security-critical resource in a way that allows that resource to be read or modified by unintended actors.

When a resource is given a permissions setting that provides access to a wider range of actors than required, it could lead to the disclosure of sensitive information or the modification of that resource by unintended parties. This is especially dangerous when the resource is related to program configuration, execution or sensitive user data.

CWE-330:Use of Insufficiently Random Values

The software may use insufficiently random numbers or values in a security context that depends on unpredictable numbers.

When software receives predictable values in a context requiring unpredictability, it may be possible for an attacker to guess those predictable values and use this guess to impersonate another user or access sensitive information.

C#
string GenerateReceiptURL(string baseUrl) 
{
Random ranGen = new Random((new Date()).getTime()); 
return(baseUrl + ranGen.Next(400000000) + ".html")); 
}

This code uses the Random.Next() function to generate "unique" identifiers for the receipt pages it generates because of Random.Next() is a statistical PRNG, which makes it easy for an attacker to guess the strings it generates. Although the underlying design of the receipt system is also faulty, it would be more secure if it used a random number generator that did not produce predictable receipt identifiers, such as a cryptographic PRNG.

CWE-250:Execution with Unnecessary Privileges

The software operates at a privilege level higher than the minimum level required, creating new weaknesses or amplifying the consequences of other weaknesses.

New weaknesses can be exposed because running with extra privileges, such as root or Administrator, can turn off the normal security checks performed by the operating system or surrounding environment. Other pre-existing weaknesses can turn into security vulnerabilities if they occur while operating at raised privileges.

CWE-602:Client-Side Enforcement of Server-Side Security

The software has a server that relies on the client to implement a mechanism intended to protect the server.

When the server relies on protection mechanisms placed on the client side, an attacker can modify the client-side behaviour to bypass the protection mechanisms, resulting in potentially unexpected interactions between the client and server. The consequences will vary, depending on what the mechanisms are trying to protect.

About the Author

Tim Trott is a senior software engineer with over 20 years of experience in designing, building, and maintaining software systems across a range of industries. Passionate about clean code, scalable architecture, and continuous learning, he specialises in creating robust solutions that solve real-world problems. He is currently based in Edinburgh, where he develops innovative software and collaborates with teams around the globe.

Related ArticlesThese articles may also be of interest to you

CommentsShare your thoughts in the comments below

My website and its content are free to use without the clutter of adverts, popups, marketing messages or anything else like that. If you enjoyed reading this article, or it helped you in some way, all I ask in return is you leave a comment below or share this page with your friends. Thank you.

There are no comments yet. Why not get the discussion started?

New comments for this post are currently closed.