205
SQL injection. For MySQL, the mysql_real_escape_string() API function is available in both C
and PHP.
Phase: Implementation
Strategy = Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use
a list of acceptable inputs that strictly conform to specifications. Reject any input that does not
strictly conform to specifications, or transform it into something that does. When performing
input validation, consider all potentially relevant properties, including length, type of input, the
full range of acceptable values, missing or extra inputs, syntax, consistency across related
fields, and conformance to business rules. As an example of business rule logic, "boat" may be
syntactically valid because it only contains alphanumeric characters, but it is not valid if the input
is only expected to contain colors such as "red" or "blue." Do not rely exclusively on looking for
malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if
the code's environment changes. This can give attackers enough room to bypass the intended
validation. However, denylists can be useful for detecting potential attacks or determining which
inputs are so malformed that they should be rejected outright. When constructing SQL query
strings, use stringent allowlists that limit the character set based on the expected value of the
parameter in the request. This will indirectly limit the scope of an attack, but this technique is
less important than proper output encoding and escaping. Note that proper output encoding,
escaping, and quoting is the most effective solution for preventing SQL injection, although input
validation may provide some defense-in-depth. This is because it effectively limits what will
appear in output. Input validation will not always prevent SQL injection, especially if you are
required to support free-form text fields that could contain arbitrary characters. For example,
the name "O'Reilly" would likely pass the validation step, since it is a common last name in the
English language. However, it cannot be directly inserted into the database because it contains
the "'" apostrophe character, which would need to be escaped or otherwise handled. In this
case, stripping the apostrophe might reduce the risk of SQL injection, but it would produce
incorrect behavior because the wrong name would be recorded. When feasible, it may be safest
to disallow meta-characters entirely, instead of escaping them. This will provide some defense in
depth. After the data is entered into the database, later processes may neglect to escape metacharacters
before use, and you may not have control over those processes.
Phase: Architecture and Design
Strategy = Enforcement by Conversion
When the set of acceptable objects, such as filenames or URLs, is limited or known, create a
mapping from a set of fixed input values (such as numeric IDs) to the actual filenames or URLs,
and reject all other inputs.
Phase: Implementation
Ensure that error messages only contain minimal details that are useful to the intended audience
and no one else. The messages need to strike the balance between being too cryptic (which
can confuse users) or being too detailed (which may reveal more than intended). The messages
should not reveal the methods that were used to determine the error. Attackers can use detailed
information to refine or optimize their original attack, thereby increasing their chances of success.
If errors must be captured in some detail, record them in log messages, but consider what
could occur if the log messages can be viewed by attackers. Highly sensitive information such
as passwords should never be saved to log files. Avoid inconsistent messaging that might
accidentally tip off an attacker about internal state, such as whether a user account exists or not.
In the context of SQL Injection, error messages revealing the structure of a SQL query can help
attackers tailor successful attack strings.
Phase: Operation
Strategy = Firewall
CWE Version 4.14
CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')
CWE-89: Improper Neutralization of Special
Elements used in an SQL Command ('SQL Injection') 206
Use an application firewall that can detect attacks against this weakness. It can be beneficial
in cases in which the code cannot be fixed (because it is controlled by a third party), as an
emergency prevention measure while more comprehensive software assurance measures are
applied, or to provide defense in depth.
Effectiveness = Moderate
An application firewall might not cover all possible input vectors. In addition, attack techniques
might be available to bypass the protection mechanism, such as using malformed inputs that can
still be processed by the component that receives those inputs. Depending on functionality, an
application firewall might inadvertently reject or modify legitimate requests. Finally, some manual
effort may be required for customization.
Phase: Operation
Phase: Implementation
Strategy = Environment Hardening
When using PHP, configure the application so that it does not use register_globals. During
implementation, develop the application so that it does not rely on this feature, but be wary of
implementing a register_globals emulation that is subject to weaknesses such as CWE-95,
CWE-621, and similar issues.
Demonstrative Examples
Example 1:
In 2008, a large number of web servers were compromised using the same SQL injection attack
string. This single string worked against many different programs. The SQL injection was then used
to modify the web sites to serve malicious code.
Example 2:
The following code dynamically constructs and executes a SQL query that searches for items
matching a specified name. The query restricts the items displayed to those where owner matches
the user name of the currently-authenticated user.
Example Language: C# (Bad)
...
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:
Example Language: (Informative)
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 user name wiley enters the string:
Example Language: (Attack)
name' OR 'a'='a
for itemName, then the query becomes the following:
CWE Version 4.14
CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')
CWE-89: Improper Neutralization of Special
Elements used in an SQL Command ('SQL Injection')