Injection

One of the biggest threats to website security is “injection”. Injection happens when an attacker injects malicious code into your website, through a flaw in your application. And one of the most common ways this happens is through APIs (Application Programming Interfaces).
APIs allow different software systems to talk to each other. But if they’re not properly secured they can provide a backdoor for attackers to inject malicious code into your website.

So, in simple terms, injection in API security is when an attacker injects malicious code into your website through a vulnerability in your API. And trust us, you don’t want that to happen. That’s why we’re here to help explain what it is, how it works and how you can prevent it.

Real-World Scenario

A scenario of how injection could occur in a real-world situation:

  • Imagine; you have a website, that allows users to search for products using a search bar. The website uses APIs to connect to a database & retrieve product information.
  • Let’s say; the API takes user input from the search-bar & inserts it into a SQL query to search the database. Here’s an example of what the code might look like:
$userInput = $_GET['searchTerm'];
$sql = "SELECT * FROM products WHERE name LIKE '%$userInput%'";
$result = mysqli_query($conn, $sql);
  • Because this code does not properly sanitize the user input it is vulnerable to injection. An attacker could exploit this vulnerability by injecting malicious SQL codes into the ‘$userInput‘ variable. For example; an attacker could enter the following as the search term;
' OR 1=1; --
  • The final SQL query would look like this:
SELECT * FROM products WHERE name LIKE '%' OR 1=1; -- %'
  • This query would return all the records from the ‘products‘ table, bypassing the original search criteria. The ‘‘ at the end of the query would comment out the rest of the query, effectively neutralizing it.
  • This is just one illustration of how an attacker could exploit an API vulnerability to inject malicious code into a website. To prevent injection attacks, it’s important to always sanitize & validate user input and to use prepared statements or parameterized queries. Here’s an example of how the code could be fixed to prevent injection:
$userInput = mysqli_real_escape_string($conn, $_GET['searchTerm']);
$sql = "SELECT * FROM products WHERE name LIKE ?";
$stmt = mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, "s", "%$userInput%");
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);

By using a prepared statement & binding the user input as a parameter. The input is properly sanitized & the risk of injection is brought down.

Some Vulnerabilities of Injection

SQL Injection

SQL injection occurs when user-supplied data is inserted into an SQL query in an unsafe manner. This can allow an attacker to manipulate the SQL query and potentially access sensitive information, modify data or even execute administrative commands on the database.
Here’s an illustration of vulnerable PHP code that could lead to a SQL injection attack:

$userInput = $_GET['searchTerm'];
$sql = "SELECT * FROM products WHERE name LIKE '%$userInput%'";
$result = mysqli_query($conn, $sql);

In this illustration; the user input is directly concatenated into the SQL query without being properly sanitized. An attacker could supply a malicious value for the ‘searchTerm‘ parameter that would modify the SQL query and allow them to inject malicious code.

LDAP Injection

LDAP (Lightweight Directory Access Protocol) injection occurs when user supplied data is inserted into an LDAP query in an unsafe manner. This can allow an attacker to manipulate the LDAP query and potentially access sensitive information, modify data, or even execute administrative commands on the directory server.

Here’s an example of vulnerable PHP code that could lead to an LDAP injection attack:

$userInput = $_GET['searchTerm'];
$ldap = ldap_connect("ldap://example.com");
ldap_bind($ldap, "cn=admin,dc=example,dc=com", "secret");
$search = ldap_search($ldap, "dc=example,dc=com", "(cn=$userInput)");
$entries = ldap_get_entries($ldap, $search);

In this example; the user input is directly included in the LDAP query without being properly sanitized. An attacker could supply a malicious value for the ‘searchTerm‘ parameter that would modify the LDAP query and allow them to inject malicious code.

Command Injection

Command injection occurs when user-supplied data is used as part of a shell command in an unsafe manner. This can allow an attacker to execute arbitrary commands on the server, potentially leading to data theft, system compromise or other malicious activity.
Here’s an illustration of vulnerable PHP code that could lead to a command injection attack:

$userInput = $_GET['fileName'];
$output = shell_exec("cat $userInput");
echo $output;

In this example; the user input is directly used as part of shell commands without being properly sanitized. An attacker could supply a malicious value for the ‘fileName‘ parameter that would enable them to insert malicious code.

XPath Injection

XPath (XML Path Language) injection occurs when user supplied data is inserted into an XPath query in an unsafe manner. This can allow an attacker to manipulate the XPath query & potentially access sensitive information, modify data or even execute arbitrary code.
Here’s an example of vulnerable PHP code that could lead to an XPath injection attack;

$userInput = $_GET['searchTerm'];
$xml = simplexml_load_file("data.xml");
$result = $xml->xpath("//item[contains(name,'$userInput')]");
foreach ($result as $item) {
    echo $item->name . "<br>";
}

In this example, the user input is directly included in the XPath query without being properly sanitized. An attacker could supply a malicious value for the ‘searchTerm‘ parameter that would modify the XPath query & allow them to inject malicious code.

Cross-Site Scripting (XSS)

XSS occurs when user-supplied data is included in a web page in an insecure manner. This can allow an attacker to inject malicious JavaScript code into the page potentially stealing sensitive information, executing arbitrary code or compromising the user’s session.
Here’s an example of vulnerable PHP code that could lead to an XSS attack:

$userInput = $_GET['message'];
echo "<p>$userInput</p>";

In this example; the user input is directly included in the HTML without being properly sanitized. An attacker could supply a malicious value for the ‘message‘ parameter that would permit them to insert malicious javascript code.

These are just a few examples of the types of injection-vulnerabilities that can occur in PHP code. To prevent these types of attacks it’s important to always validate & sanitize user input & to properly escape any data being included in dynamic SQL, shell commands, or HTML.

How to Fix Injection Flaws

Preventing and mitigating injection attacks in PHP requires a multi-layered approach that includes proper input validation and sanitization, using prepared statements and parameterized queries and implementing secure coding practices. Here are some specific techniques you can use to prevent and mitigate injection attacks in PHP:

Limiting Query Length

Limiting user input in your queries is another technique to stop injection attacks. You can reduce the probability of successful injection attacks by limiting the amount of data that can be entered into a query. You can also assist avoid other sorts of attacks, such as buffer overflow attacks, by doing so. In PHP you can use the ‘substr()‘ function to limit the length of user input.
Here’s an example of limiting query length in PHP:

$userInput = $_GET['searchTerm'];
$safeInput = substr($userInput, 0, 100);

In this example, the ‘substr()‘ function is used to limit the user input to 100 characters & bring down the risk of successful injection attacks.

Input Validation and Sanitization

One of the most important steps in preventing injection attacks is to validate and sanitize all user input. This involves checking the data type, length & format of the input to ensure that it meets the expected criteria and removing any potentially malicious characters or code from the input before using it in a query. In PHP you can use functions such as ‘filter_var()‘, ‘preg_match()‘ and ‘htmlentities()‘ to validate and sanitize input.
Here’s an illustration of input validation and sanitization in PHP;

$userInput = $_GET['searchTerm'];
$safeInput = filter_var($userInput, FILTER_SANITIZE_STRING);
$safeInput = preg_replace("/[^a-zA-Z0-9]+/", "", $safeInput);

In this example; the ‘filter_var()‘ function is used to remove any potentially malicious characters from the user input & the ‘preg_match()‘ function is used to remove any characters that don’t match a specific-pattern.

Escaping User Input

A straightforward but efficient method of preventing injection attempts is escaping user input. By escaping any potentially dangerous characters or code from user input you can ensure that the input is treated as plain text rather than as part of a query or command. In PHP, you can use the ‘addslashes()‘ function to escape user input.
Here’s an example of escaping user input in PHP;

$userInput = $_GET['searchTerm'];
$safeInput = addslashes($userInput);

In this example; the ‘addslashes()‘ function is used to escape any dangerous characters in the user input. So that they are treated as plain text rather than as part of a query or command.

Secure Coding Practices

In addition to input validation and sanitization & using prepared statements and parameterized queries it’s also important to follow secure coding practices in order to prevent injection attacks. This includes avoiding the use of dynamic queries, limiting user privileges and keeping your software up to date with the latest security patches.

Using Enumerated Data Types

The use of enumerated data types is another method of preventing injection attacks. Input attack risk is decreased by using enumerated data types, which let you limit the possible values that can be typed into a field. For the purpose of defining an enumerated data type in PHP utilize the ‘enum‘ type.
Using an enumerated data type in PHP is demonstrated here:

$userInput = $_GET['searchTerm'];
$safeInput = in_array($userInput, array("admin", "user", "guest")) ? $userInput : "guest";

In this example; the ‘in_array()‘ function is used to check the user input against a list of valid values. If the input is not a valid value, the ‘$safeInput‘ variable is set to “guest“. By restricting the possible values that can be entered into the field, employing an enumerated data type in this way can help prevent injection attacks.

Prepared Statements and Parameterized Queries

Utilizing prepared statements and parameterized queries is a further effective defense against injection attempts. These allow you to separate the query from the data so that the data is not treated as part of the query itself. In PHP you can use the ‘mysqli‘ or ‘PDO‘ extension to perform prepared statements and parameterized queries.
Here’s an example of a prepared statement in PHP using the ‘mysqli‘ extension:

$userInput = $_GET['searchTerm'];
$mysqli = new mysqli("localhost", "user", "password", "database");
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $userInput);
$stmt->execute();
$result = $stmt->get_result();

In this example, the ‘bind_param()‘ method is used to bind the user input to the prepared statement, so that it is treated as a separate entity from the query itself.

By following these techniques, you can significantly reduce the risk of injection attacks in your PHP code and ensure that your applications are secure against this type of threat.

Summary

Injection attacks are a common security vulnerability in web applications, where malicious code is injected into a query or command. To prevent these attacks, techniques such as escaping user input, using enumerated data types, prepared statements, input validation and using API keys can be employed. Using these techniques, risk of unauthorized access to sensitive information or the execution of arbitrary code can be reduced. Ensuring the safety of the web application and its users.

References

OWASP API Security Project
OWASP API TOP 10