OWASP Top 10 Risks: #1: Injection
Join the DZone community and get the full member experience.Join For Free
we all have probably witnessed (and had a good laugh) when commands have been mixed with data as in the case where the baker literally writes the instructions for the message as the cake message. there isn't much difference in this example and what is one of the core elements in what owasp has identified as the no. 1 application security risk to organizations; the risk of an injection . before getting into what comprises an injection, how it is carried out and what defense measure we can take, let me introduce you to owasp by deferring to their own description:
the open web application security project (owasp) is a 501(c)(3) worldwide not-for-profit charitable organization focused on improving the security of software. our mission is to make software security visible, so that individuals and organizations worldwide can make informed decisions about true software security risks.
owasp’s top 10
for a number of years now, owasp have been publishing a list of the top 10 application security risks for developers to use to be more responsible with their applications. the words “responsible” and “software developer” are not words you hear together to often. but in the day of online banking accounts, personal profiles and online shopping, software developers should be taking a more responsible approach to their craft. one way to demonstrate responsibility is being very well versed in the common security risks that online applications face. a way to achieve that is through the familiarity of the risks that have been identified in owasp’s top 10 list and the information they provide for identifying and recommended countermeasures.
from the previous 2010 top 10 list to the current 2013 , not much has changed with the exception of a few risks reordering based on severity. however, the topic of this post has remained the #1 risk on both editions.
injection you say?
the term injection can encompass a large number of different variations such as sql, xml, ldap, html, css and remote file injections (which is not an exhaustive list). in the end, they all boil down to injecting a command in the guise of data, where the command is then executed with malicious results on the targeted system. this is all a result of what owasp has identified as injection flaws which they have defined as:
injection flaws, such as sql, os, and ldap injection occur when distrusted data is sent to an
interpreter as part of a command or query. the attacker’s hostile data can trick the interpreter
into executing unintended commands or accessing data without proper authorization.
lets look at some examples…
injection in action
no reasonable documentation on injection can be complete without the conventional sql injection examples. sql injections are one of, if not the most prevalent type of injection due to their simplicity and technology prevalence and can easily be demonstrated.
to set the stage, imagine for a moment you have a public api exposed http://mycornyproducts.com/api/products that will provide a consumer of your api to retrieve product information. behind the scenes you take that input (data) which will formulate as the criteria for the query you run against your applications database.
a sql injection example at its core is made up of 2 ingredients; query and data. in our example we have the following query structure:select * from products where name = data
in this case, name is a string data type and data can represent any valid criteria, for example “flash light” and return a record:
here we see data represented as it was intended. but remember, this is user data, distrusted and invalidated user data. recall the earlier statement about commands becoming data? what if the previous submitted user data looked something like this:
where bat; update products set name = ‘all your base are belong to us’ is the provided data by the user. we can see what the query would end up looking like without any validation of the use input:select * from products where name =
‘bat’ ; update products set name = ‘all your base are belong to us’
we can see here that our criteria data has now become a command of updating all product names and when executed against our database table would have the following results:
this is a pretty straight forward example with minimal impact. but this example could be in the form of any number of scenarios such as inserting a user with the keys to the kingdom or forcing the leakage of sensitive data through additional sub queries and the list goes on. now having seen an example of an injection in action, lets look at the root cause for such a vulnerability so we can formulate a plan of defense.
understanding the root problem
before diving into what can be done to stop this type of vulnerability, lets focus on the root problem for a moment. in most cases if not all, the root problem is the allowance of distrusted data into our system. depending on the type of injection, distrusted data can access a system from a number of different sources. an incomplete list of sources where distrusted data can garnish access to your system are:
- request headers
- form fields
- query strings
- isolated storage
- image exif
in all these cases, our system doesn't have immediate and complete control over them to ensure they can be a trusted source. disclaimer: there are probably cases where trusted sources of a system can still be the catalyst for distrusted and malicious data.
the distrusted data we have been mentioning is some form of a command that has come in as a guise of valid data. lets look at how we can protect our system from injection vulnerability.
your maginot line (defense in depth)
if your not familiar with the french maginot line , the french established a defense in depth line of fortifications, turrets, guns and traps (just to name a few) on their border with germany which was successful in withstanding a direct attack. we also are going to take a defense in depth approach to protecting out system by implementing a 3 layer defense approach (each defense being a mitigation). it’s important to point out that the maginot line had a weakness and your maginot defense line can too, but we’ll come back to that shortly.
the 3 mitigation we are going to apply are:
- input validation
- query parameterization
- principle of least privilege
to summarize our approach, we want to impose rules of validation on all distrusted data. in the case that malicious data is incorrectly validated, safe guard our internal queries by encapsulating the input into named statements. finally, regulate our applications database accounts with the least privileges it needs to perform its job.
if you have used a strongly typed language like c# and java you have performed implicit user validation whether you knew or not, compliments of the language’s type safety. when your asp.net web api or mvc controller action requires an id of type integer, you automatically have some level of input validation for free. however, rely on the language’s type safety for input validation is not enough. in many cases type safety won’t even be an option as is the case with dynamic languages or user input in the form of strings; where you truly are left to the creativity of the user as to what input will be submitted to your application. this leaves you with no other option but to perform some explicit validation on the input.
there are generally two validation approaches, validating input against white list (approved patterns) or validating against a blacklist (patterns that have been deemed invalid). there is a big difference between the two and can easily mean the difference of this line of defense being successful.
blacklists retain all the invalid patterns that you want to safe guard against. for example, validating an email address by ensuring it doesn’t match an entry in your blacklist. the problem with the blacklist approach is maintenance. if there is change or a new pattern you need to safe guard against, you’re vulnerable to that pattern until you update your blacklist. contrary to what some people might state about blacklist, they are necessary at times. however, white list take the complete opposite approach and are generally looked at as a best practice approach.
white list maintain a list of patterns you deem valid. therefore, no matter what input is submitted, if it doesn’t adhere to a valid pattern in the white list, validation can’t occur. now, there has to be some case where the previous sentence is wrong, but that is why input validation is not our only means of defense, remember this is defense in-depth approach. therefore, if you’re applications requirements is to only accept 3 valid email formats (patterns), you only need to verify that a submitted email adheres to one of the 3 valid patterns to know it is valid. you don’t care about all the other possibilities. in the end, white list allow easier maintenance, easier to read and comprehend and lend to a more secure validation approach.
depending on the application, multiple tiers of input validation can be setup as in the case of enforcing input validation rules at the client level on all input fields. this is then followed up by server-side validation of all input. if you do leverage a number of existing validation tools such as asp.net web form validators, data annotations and/or their jquery unobtrusive library (just to name a few), make sure you’re aware of how they operate. blindly relying on some 3rd party or framework’s validation tools is like trusting your kids to any o’babysitter with no background check.
however, client validation is not always an available luxury as in the case of a rest api or web service where the client is out of your control. therefore, server-side validation is not an option and should always be performed whether you have control of the client or not. i have said before and will say it again
in some cases, the importance of where you are handling specific security related issues can be as important as whether you are at all.
remember, in most cases of injection and the ones we have been concentrating on, the bottom line is that we are processing some type of statement against our data source based on the submitted distrusted data. in the case of a rdbms it could be a query for a record, carry out a command on a record(s) or a combination of both. the problem enters when we are concatenating our distrusted data with the statement.
as in the examples from the previous injection in action section
select * from products where name = distrusted_data
where distrusted data is its own query and ends up revealing all products public or not
select * from products where name = ‘bat’ or 1=1; - -
or malicious in a different way such as carrying out its own command
select * from products where name = ‘bat’; drop table products; - -
in all these examples, the vulnerability comes from the fact that we have simply concatenated our query with the distrusted data. we can plug this vulnerability by letting our database engine know the difference between the statement (query) we want to run and the criteria (distrusted data) that we provide. this allows the database engine to properly escape the criteria and not allow it to operate outside it’s intended purpose.
forgetting for the moment about orm’s (object relation mapper) such as entity framework lets look at what a parameterized query would look like:
var conn =
"select * from products where name=@criteria"
(var sqlcommand =
, sqldbtype.nvarchar).value = name;
var reader = sqlcommand.executereader();
//removed for brevity
we can see that we clearly defining the query and separately the data. this is done by defining what the query will be and specifying placeholders (@criteria) of where the data is expected. followed up by defining what the data’s type (sqldbtype.nvarchar) is and it’s value (name). in the case of more constrained types (i.e. integers) our sql database engine would throw an error if the supplied data doesn’t conform.
in an example where the submitted input for our name parameter has malicious content such as 1; update products set name = ‘all your base are belong to us ’, the above code will render the following parameterized query:
exec sp_executesql n'select * from products where name=@criteria' , n'@criteria nvarchar(62)' ,@criteria= n'1; update products set name = ‘all your base are belong to us’'
the important part of this final result, is that the distrusted data has been escaped and is operated against as data of type nvarchar and no longer a valid sql statement that will be executed.
depending on your organization's policies or application performance, utilizing stored procedures is yet another way to enforce parameterization. but they provide the same level of security through the same mechanisms of separation of data from query and definition of data type which result in the escaping of the data by the database engine before execution.
dangers to be aware of
one might be thinking “i use an orm, so i already have this covered”. that’s true, most orm’s such as entity framework and nhiberate provide prepared statements as the de facto method of operation. the problem that arises whether you use orm’s or stored procedures comes when you start dynamically creating statements.
based on the complexity of your query, you might find yourself taking a shortcut or because of tool limitations by dynamically constructing a string to execute as a query by the native means of your orm or within the stored procedures themselves. be aware that when you do this, you have formally put yourself back in seat of the original problem. which brings us to our next defense.
principle of least privilege
how many times have we heard or stated ourselves, that developers are lazy? the truth couldn't be more apparent with how we devise the database users accounts that our application operate under. more likely than not, most public facing applications you have worked on have only one account that all their database layer operations connect under. in addition, this single account usually retains at minimum both read and write access.
the above scenario introduces the need for applying the principle of least privilege . which, for us, basically means diversifying the accounts the application uses and enforcing that each account operates under the minimal permissions needed to carry out its objective.
in the examples we have used up until now, where we are simply allowing users to query for products by a certain name, the database account only needs to be able to read from the database.
alternatively, we can be more restrictive and define exactly what objects and the permissions on those objects that the account has. each rdbms is different. for example, below is microsoft sql server restricting this user to select statements on the products table.
what does this do for us? this restriction to the appropriate account with minimal permissions would have stopped our previous examples of input with malicious intent to write to our database. this wouldn’t stop a malicious read query that attempts to leak unintended records or database schema information, but that would be covered under the safe guard of query parameterization.
all this talk about restricting access at the database layer begs the question of managing different database accounts and connections within your application. this obviously introduces additional overhead and complexity but greatly increases the security at the database layer. i do plan on writing a post specifically on known ways to manage multiple accounts, managing connection strings and options available in the very near future. for now, a very simple example would be the separation of administrative and public areas each with their own accounts restricted to the minimal permissions needed.
making sense of it all
we have definitely covered a lot here, but the take away is that defense against injection is not composed of a single action but defense in-depth; multiple layers that each provide a particular overlapping protection. like the french maginot line, your defense can be formidable.
but remember when i said that the maginot line has a weakness? well in wwii on may 10th, 1940, instead of taking on the maginot line head first, the germans avoided the maginot defense by going around and entering france by way of an unprotected area (comparably) north of the maginot line and within 43 days had won the battle of france forcing france to sign an armistice on june 22nd. making it one of the quickest defeats of what was presumed to be one of, if not the best armies at the time. there is two points to take away from this. if you shortcut an area of your defense in-depth or completely opt out of implementing some layer of defense, you leave an area of your application vulnerable. in addition, we have only discussed one type of risk. therefore, not being cognitive and taking deliberate preventative steps to protect from other risks will leave your application vulnerable. stay tuned for up coming posts on additional owasp top 10 risks.
owasp top 10 risks: #1: injection first appeared on
featured image via: pleated-jeans.com
Opinions expressed by DZone contributors are their own.