Top 25 Dangerous Coding Errors from CWE (Common Weakness Enumeration)

Last Updated May 28, 2023 by . First Published in 2009.

2,901 words, estimated reading time 11 minutes.

Top 25 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.

This is a list of 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, just two of the errors led to more than 1.5m website security breaches during 2008.

More than 30 organisations, including the NSA, the Department of Homeland Security, Microsoft, and Symantec published the document, which gives 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 the majority of 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 brand new programmer will be making more basic errors.Patrick Lincoln

Previously, most advice has focused on vulnerabilities that can result from programming errors. This top 25 list examines the actual programming errors themselves.

We need to make sure every programmer knows how to write code that is free of the top 25 errors, and then we need to make sure every programming team has processes in place to find and fix these problems, both in existing code and future code, as well as having the tools needed to verify code is free of errors.

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 that is 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.

decimal price = 20.00;
int quantity = Request.Params["quantity"];
decimal total = price * quantity;

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, but it does not sufficiently encode or escape the data in a way that fails to preserve the intended structure of the message.

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

Here a value read from an HTML form parameter is reflected in the client browser without having been 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.

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(); 

The query that this code intends to execute follows:

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:

name' OR 'a'='a

for itemName, then the query becomes the following:

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

The addition of the:

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:

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 that is used as a web page that is 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.

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 code will be executed by the web browser as it displays the HTTP response. Initially, this might not appear to be much of a vulnerability. After all, why would someone enter a URL that causes malicious code to run on their own computer? The real danger is that an attacker will create the 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 own 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, but 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 can be sniffed by unauthorized actors.

string sensitiveData = "Your username and password are 'fred' and 'letmein'";

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. and can result in data disclosure or unintended code execution.

CWE-362:Race Condition

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

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

CWE-209:Error Message Information Leak

The software generates an error message that includes sensitive information about its environment, users, or 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 potentially 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. In other environments, which are unmanaged, such as C or PHP this is a high-risk issue.

CWE-642:External Control of Critical State Data

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

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, then it may create vulnerability. For example, an application may perform authentication, and then save the state in an "authenticated=true" cookie. An attacker may simply 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 that are used in file system operations. This could allow an attacker to access or modify system files or other files that are 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 give the attacker the ability 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 that is not under the application's direct control.

This might allow attackers to execute their own programs, access unauthorized data files, or modify configurations in unexpected ways. If the application uses a search path to locate critical resources such as programs, then an attacker could modify that search path to point to a malicious program, which the targeted application would then execute. The problem extends to any type of 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 that input is used within the code that 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 as well as 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, but 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.

private void processFile(string fName) 
StreamWriter sw = new
string line;
while ((line = sr.ReadLine()) != null) 

This method never closes the file handle it opens. 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. In fact, there is no guarantee that Finalize() 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 initializing 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 that determines whether a user has been authenticated or not.

private bool initialized = true;
public void someMethod() 
if (!initialized) 
// perform initialization tasks

initialized = true;

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

CWE-682:Incorrect Calculation

The software performs a calculation that generates 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 of the direct results of an incorrect calculation can lead to even larger problems such as failed protection mechanisms or even 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 that they should not be allowed to perform. This can lead to a wide range of problems, including information leaks, denial of service, and arbitrary code execution.

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

The use of a broken or risky cryptographic algorithm is an unnecessary risk that may result in the disclosure of 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 own 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 into disabling 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.

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, it is 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 that is higher than the minimum level required, which creates new weaknesses or amplifies the consequences of other weaknesses.

New weaknesses can be exposed because running with extra privileges, such as root or Administrator, can disable the normal security checks being 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 that is 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.

Was this article helpful to you?

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?

We respect your privacy, and will not make your email public. Hashed email address may be checked against Gravatar service to retrieve avatars. This site uses Akismet to reduce spam. Learn how your comment data is processed.