OWASP TOP 10 2017

SQL Injection

OWASP Top 10 2017 – A1 (Injection)


A SQL injection attack consists of insertion or “injection” of a SQL query via the input data from the client to the application.

A successful SQL injection exploit can read sensitive data from the database, modify database data (Insert/Update/Delete), execute administration operations on the database (such as shutdown the DBMS), recover the content of a given file present on the DBMS file system and in some cases issue commands to the operating system. SQL injection attacks are a type of injection attack, in which SQL commands are injected into data-plane input in order to effect the execution of predefined SQL commands.


Here is a basic HTML login form with two inputs: username and password.

      <form method="post" action="/login">
      <input name="username" type="text" id="username">
      <input name="password" type="password" id="password">

The common way for the /login to work is by building a database query. If the variables $request.username and $request.password are requested directly from the user’s input, this can be compromised.

      SELECT id
      FROM Users
      WHERE username = '$request.username'
      AND password = '$request.password'

For example, if a user inserts admin' or 1=1 -- as the username, he/she will bypass the login form without providing a valid username/password combination.

      SELECT id
      FROM Users
      WHERE username = 'admin' or 1=1--
      AND password = 'request.password'

The issue is that the ' in the username closes out the usernamefield, then the -- starts a SQL comment causing the database server to ignore the rest of the string. As the inputs of the web application are not sanitized, the query has been modified in a malicious way.


The source of the problem of SQL Injection (the most important injection risk) is based on SQL queries that use untrusted data without the use of parametrized queries (without PreparedStatement in Java environments).

First of all Hdiv minimizes the existence of untrusted data thanks to the web information flow control system that avoids the manipulation of the data generated on the server side. This architecture minimizes the risk to just the new data generated legally from editable form elements. It’s important to note that even using PreparedStatement if the query is based on untrusted data generated previously at server side (for instance the identification id of an item within a list) it’s possible to exist a SQL Injection risk.

Although PreparedStatement solves the most of the cases, there are some SQL keywords that can not be used with PreparedStatement, such as ORDER BY. In these cases, you have to concatenate the column name and the order to the SQL query but only after verifying that the column name and order are valid in this context and sanitising them to counter any attempt of SQL Injection attack.


Use parametrized queries

Variables passed as arguments to prepared statements will automatically be escaped by the JDBC driver.

      conn = pool.getConnection( );

      PreparedStatement stmt = conn.prepareStatement(
        "SELECT id FROM Account WHERE username=? AND password=?");

      stmt.setString(1, username);
      stmt.setString(2, password);

      rs = stmt.executeQuery(sql);
      if (rs.next()) {
        loggedIn = true;
        out.println("Successfully logged in");
      } else {
        out.println("Username and/or password not recognized");

Input validation

Custom validation

Validate all input data to the application using whitelist (what is allowed) for type, format, length, range, reject if invalid. For example, validate an email address and a phone number:

      private Pattern regexPattern;
      private Matcher regMatcher;

      public String validateEmailAddress(String emailAddress) {
          regexPattern = Pattern.compile("^[(a-zA-Z-0-9-\\_\\+\\.)]+@[(a-z-A-z)]+\\.[(a-zA-z)]{2,3}$");
          regMatcher   = regexPattern.matcher(emailAddress);
          if (regMatcher.matches()) {
              return "Valid Email Address";
          } else {
              return "Invalid Email Address";

      public String validateMobileNumber(String mobileNumber) {
          regexPattern = Pattern.compile("^\\+[0-9]{2,3}+-[0-9]{10}$");
          regMatcher   = regexPattern.matcher(mobileNumber);
          if (regMatcher.matches()) {
              return "Valid Mobile Number";
          } else {
              return "Invalid Mobile Number";




Broken Authentication

OWASP Top 10 – A2

Broken Authentication



These types of weaknesses can allow an attacker to either capture or bypass the authentication methods that are used by a web application.

  • Permits automated attacks such as credential stuffing, where the attacker has a list of valid usernames and passwords.
  • Permits brute force or other automated attacks.
  • Permits default, weak, or well-known passwords, such as “Password1” or “admin/admin“.
  • Uses weak or ineffective credential recovery and forgot-password processes, such as “knowledge-based answers”, which cannot be made safe.
  • Uses plain text, encrypted, or weakly hashed passwords (see A3:2017-Sensitive Data Exposure).
  • Has missing or ineffective multi-factor authentication.
  • Exposes Session IDs in the URL (e.g., URL rewriting).
  • Does not rotate Session IDs after successful login.
  • Does not properly invalidate Session IDs. User sessions or authentication tokens (particularly single sign-on (SSO) tokens) aren’t properly invalidated during logout or a period of inactivity.

The goal of an attack is to take over one or more accounts and for the attacker to get the same privileges as the attacked user.


Example #1: Credential stuffing

The use of lists of known passwords, is a common attack. If an application does not implement automated threat or credential stuffing protections, the application can be used as a password oracle to determine if the credentials are valid.

Example #2: Application session timeouts aren’t set properly.

A user uses a public computer to access an application. Instead of selecting “logout” the user simply closes the browser tab and walks away. An attacker uses the same browser an hour later, and the user is still authenticated.

Example #3: Passwords are not properly hashed and salted

An insider or external attacker gains access to the system’s password database. User passwords are not properly hashed and salted, exposing every user’s password.


  • Stored username and password values should be salted and hashed, in addition to being encrypted.




  • Where possible, implement multi-factor authentication to prevent automated, credential stuffing, brute force, and stolen credential re-use attacks.
  • Do not ship or deploy with any default credentials, particularly for admin users.
  • Implement weak-password checks, such as testing new or changed passwords against a list of the top 10000 worst passwords.
  • Align password length, complexity and rotation policies with NIST 800-63 B’s guidelines in section 5.1.1 for Memorized Secrets or other modern, evidence based password policies.
  • Ensure registration, credential recovery, and API pathways are hardened against account enumeration attacks by using the same messages for all outcomes.
  • Limit or increasingly delay failed login attempts. Log all failures and alert administrators when credential stuffing, brute force, or other attacks are detected.
  • Use a server-side, secure, built-in session manager that generates a new random session ID with high entropy after login. Session IDs should not be in the URL, be securely stored and invalidated after logout, idle, and absolute timeouts.



Sensitive Data Exposure

OWASP Top 10 – A3

Sensitive Data Exposure



The first thing you have to determine is which data is sensitive enough to require extra protection. For example:

  • Banking information: account numbers, credit card numbers.
  • Health information.
  • Personal information: SSN/SIN, date of birth, etc.
  • User account/passwords.


  • Financial loss.
  • Identity hijacking.
  • Decreased brand trust.


Example #1: Credit card encryption

An application encrypts credit card numbers in a database using automatic database encryption. However, this means it also decrypts this data automatically when retrieved, allowing a SQL injection flaw to retrieve credit card numbers in clear text.


  • The system should have encrypted the credit card numbers using a public key, and only allowed back- end applications to decrypt them with the private key.

Example #2: SSL is not used for all authenticated pages


  • Attacker simply monitors network traffic (like an open wireless network), and steals the user’s session cookie. Attacker then replays this cookie and hijacks the user’s session, accessing the user’s private data.

Example #3: The password database uses unsalted hashes to store everyone’s passwords


  • A file upload flaw allows an attacker to retrieve the password file. All of the unsalted hashes can be exposed with a rainbow table of precalculated hashes.



  • Encrypt data during transport and at rest.
  • Minimize data surface area.
  • Use the latest encrytion algorithms.
  • Disable autocomplete on forms that collect data.
  • Disable caching on forms that collect data.









XML External Entities (XXE)

OWASP Top 10 – A4



According to OWASP, “An XML External Entity attack is a type of attack against an application that parses XML input. This attack occurs when XML input containing a reference to an external entity is processed by a weakly configured XML parser. This attack may lead to the disclosure of confidential data, denial of service, server side request forgery, port scanning from the perspective of the machine where the parser is located, and other system impacts.”

Applications and in particular XML-based web services or downstream integrations might be vulnerable to attack if:

  • The application accepts XML directly or XML uploads, especially from untrusted sources, or inserts untrusted data into XML documents, which is then parsed by an XML processor.
  • Any of the XML processors in the application or SOAP based web services has document type definitions (DTDs) enabled. As the exact mechanism for disabling DTD processing varies by processor, it is good practice to consult a reference such as the OWASP Cheat Sheet ‘XXE Prevention’.
  • If your application uses SAML for identity processing within federated security or single sign on (SSO) purposes. SAML uses XML for identity assertions, and may be vulnerable.
  • If the application uses SOAP prior to version 1.2, it is likely susceptible to XXE attacks if XML entities are being passed to the SOAP framework.
  • Being vulnerable to XXE attacks likely means that the application is vulnerable to denial of service attacks including the Billion Laughs attack.


Numerous public XXE issues have been discovered, including attacking embedded devices. XXE occurs in a lot of unexpected places, including deeply nested dependencies. The easiest way is to upload a malicious XML file, if accepted:

Example #1: The attacker attempts to extract data from the server

          <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE foo [
          <!ELEMENT foo ANY >
          <!ENTITY xxe SYSTEM "file:///etc/passwd" >]> <foo>&xxe;</foo>

Example #2: An attacker probes the server’s private network by changing the above ENTITY line to

          <!ENTITY xxe SYSTEM "" >]>

Example #3: An attacker attempts a denial-of-service attack by including a potentially endless file

          <!ENTITY xxe SYSTEM "file:///dev/random" >]>



Developer training is essential to identify and mitigate XXE. Besides that, preventing XXE requires:

  • Whenever possible, use less complex data formats such as JSON, and avoiding serialization of sensitive data.
  • Patch or upgrade all XML processors and libraries in use by the application or on the underlying operating system. Use dependency checkers. Update SOAP to SOAP 1.2 or higher.
  • Disable XML external entity and DTD processing in all XML parsers in the application, as per the OWASP Cheat Sheet ‘XXE Prevention’.
  • Implement positive (“whitelisting”) server-side input validation, filtering, or sanitization to prevent hostile data within XML documents, headers, or nodes.
  • Verify that XML or XSL file upload functionality validates incoming XML using XSD validation or similar.
  • SAST tools can help detect XXE in source code, although manual code review is the best alternative in large, complex applications with many integrations.

If these controls are not possible, consider using virtual patching, API security gateways, Web Application Firewalls (WAF), or Interactive Application Security Testing (IAST) tools to detect, monitor, and block XXE attacks.





A5-Broken Access Control


Access control enforces policy such that users cannot act outside of their intended permissions. Failures typically lead to unauthorized information disclosure, modification or destruction of all data, or performing a business function outside of the limits of the user. Common access control vulnerabilities include:

  • Bypassing access control checks by modifying the URL, internal application state, or the HTML page, or simply using a custom API attack tool
  • Allowing the primary key to be changed to another’s users record, permitting viewing or editing someone else’s account.
  • Elevation of privilege. Acting as a user without being logged in, or acting as an admin when logged in as a user.
  • Metadata manipulation, such as replaying or tampering with a JSON Web Token (JWT) access control token or a cookie or hidden field manipulated to elevate privileges, or abusing JWT invalidation
  • CORS misconfiguration allows unauthorized API access.
  • Force browsing to authenticated pages as an unauthenticated user or to privileged pages as a standard user. Accessing API with missing access controls for POST, PUT and DELETE.


Example #1: The application uses unverified data

The application uses unverified data in a SQL call that is accessing account information:

        pstmt.setString(1, request.getParameter("acct"));
        ResultSet results = pstmt.executeQuery();

An attacker simply modifies the acctparameter in the browser to send whatever account number they want. If not properly verified, the attacker can access any user’s account.


Example #2: An attacker simply force browses to target URLs

Admin rights are required for access to the admin page.


If an unauthenticated user can access either page, it’s a flaw. If a non-admin can access the admin page, this is a flaw.



Access control is only effective if enforced in trusted server-side code or server-less API, where the attacker cannot modify the access control check or metadata.

  • Deny access to functionality by default.
  • Use Access control lists and role-based authentication mechanisms.
  • Do not just hide functions.







Security Misconfiguration

OWASP Top 10 – A6



Improper server or web application configuration leading to various flaws:

  • Debugging enabled.
  • Incorrect folder permissions.
  • Using default accounts or passwords.
  • Setup/Configuration pages enabled.

All of your data could be stolen or modified slowly over time.

Current application security architectures do not follow security by default. On the contrary, programmers must apply security measures to avoid access to private or confidential resources.


Example #1: The app server admin console is automatically installed and not removed

Default accounts are not changed.


  • Attacker discovers the standard admin pages are on your server, logs in with default passwords, and takes over.

Example #2: Directory listing is not disabled on your server


  • Attacker discovers they can simply list directories to find any file. Attacker finds and downloads all your compiled Java classes, which they decompile and reverse engineer to get all your custom code. They then find a serious access control flaw in your application.

Example #3: App server configuration allows stack traces to be returned to users, potentially exposing underlying flaws


  • Attackers love the extra information error messages provide.

Example #4: App server comes with sample applications that are not removed from your production server


  • These sample applications have well-known security flaws attackers can use to compromise your server.



The principle of least privilege: Everything off by default.

  • Disable administration interfaces.
  • Disable debugging.
  • Disable use of default accounts/passwords.
  • Configure server to prevent unauthorized access, directory listing, etc.
  • Consider running scans and doing audits periodically to help detect future misconfigurations or missing patches.





Cross-site Scripting (XSS)

OWASP Top 10 – A7



Cross-Site Scripting (XSS) attacks are a type of injection, in which malicious scripts are injected into otherwise benign and trusted web sites. XSS attacks occur when an attacker uses a web application to send malicious code, generally in the form of a browser side script, to a different end user. Flaws that allow these attacks to succeed are quite widespread and occur anywhere a web application uses input from a user within the output it generates without validating or encoding it.

An attacker can use XSS to send a malicious script to an unsuspecting user. The end user’s browser has no way to know that the script should not be trusted, and will execute the script. Because it thinks the script came from a trusted source, the malicious script can access any cookies, session tokens, or other sensitive information retained by the browser and used with that site. These scripts can even rewrite the content of the HTML page.


The most common example of XSS is a basic coded search engine for a website. The site search script is in this format:


Once something has been searched for, the script displays on the webpage something along the lines of:

"Results for Hdiv XSS here"

Simply displaying the search string straight onto the webpage without performing any validation checks. An attacker could insert a script and if no sanitation checks are being performed, this will just be displayed straight onto the webpage. This could be used to display anything the attacker wants.

http://www.vulnerablewebsite.com/search/query?q=alert("Hdiv XSS");



The source of the problem of XSS risk is based on writes that use untrusted data without using escaped functions.


HTML Escape

XSS can be prevented sanitizing any user input before it is processed and/or rendered back to the browser. For example, in JSP by using JSTL <c:out> tag or fn:escapeXml() EL function when (re)displaying user-controlled input. This includes request headers, cookies, URL, body, parameters, etc, the whole request. Also the user-controlled input which is stored in a database needs to be escaped during redisplaying.


JSTL Tag: <c:out value="${bean.userControlledValue}"/>
Spring Form Tags: <form:hidden path="${bean.userControlledValue}" htmlEscape="true" />
Spring Eval: <spring:eval expression="bean.userControlledValue" htmlEscape="true"/>
Struts 1: <bean:write name="bean" property="userControlledValue" filter="true"/>
Struts 2: <s:property value="#request.bean.userControlledValue" escapeHtml='true'/>

Input validation

Custom validation

Validate all input data to the application using whitelist (what is allowed) for type, format, length, range, reject if invalid.



Insecure Deserialization

OWASP Top 10 – A8



According to OWASP, applications and APIs will be vulnerable if they deserialize hostile or tampered objects supplied by an attacker. This can result in two primary types of attacks:

  • Object and data structure related attacks where the attacker modifies application logic or achieves arbitrary remote code execution if there are classes available to the application that can change behavior during or after deserialization.
  • Typical data tampering attacks, such as access-control-related attacks, where existing data structures are used but the content is changed.

Serialization may be used in applications for:

  • Remote- and inter-process communication (RPC/IPC)
  • Wire protocols, web services, message brokers
  • Caching/Persistence
  • Databases, cache servers, file systems
  • HTTP cookies, HTML form parameters, API authentication tokens


Example #1

A React application calls a set of Spring Boot microservices. Being functional programmers, they tried to ensure that their code is immutable. The solution they came up with is serializing user state and passing it back and forth with each request. An attacker notices the “R00” Java object signature, and uses the Java Serial Killer tool to gain remote code execution on the application server.

Example #2

A PHP forum uses PHP object serialization to save a “super” cookie, containing the user’s user ID, role, password hash, and other state:

          a:4:{i:0;i:132;i:1;s:7:"Mallory";i:2;s:4:"user"; i:3;s:32:"b6a8b3bea87fe0e05022f8f3c88bc960";}

An attacker changes the serialized object to give themselves admin privileges:

          a:4:{i:0;i:1;i:1;s:5:"Alice";i:2;s:5:"admin"; i:3;s:32:"b6a8b3bea87fe0e05022f8f3c88bc960";} 



The only safe architectural pattern is not to accept serialized objects from untrusted sources or to use serialization mediums that only permit primitive data types. If that is not possible, consider one of more of the following:

  • Implementing integrity checks such as digital signatures on any serialized objects to prevent hostile object creation or data tampering.
  • Enforcing strict type constraints during deserialization before object creation as the code typically expects a definable set of classes. Bypasses to this technique have been demonstrated, so reliance solely on this is not advisable.
  • Isolating and running code that deserializes in low privilege environments when possible.
  • Logging deserialization exceptions and failures, such as where the incoming type is not the expected type, or the deserialization throws exceptions.
  • Restricting or monitoring incoming and outgoing network connectivity from containers or servers that deserialize.
  • Monitoring deserialization, alerting if a user deserializes constantly.




Components With Known Vulnerabilities

OWASP Top 10 – A9




Some vulnerable components (e.g., framework libraries) can be identified and exploited with automated tools, expanding the threat agent pool beyond targeted attackers to include chaotic actors.

Virtually every application has these issues because most development teams don’t focus on ensuring their components/libraries are up to date. In many cases, the developers don’t even know all the components they are using, never mind their versions. Component dependencies make things even worse.



Manual updates

One option is not to use components that you did not write. But that is not very realistic. Most component projects do not create vulnerability patches for old versions. Instead, most simply fix the problem in the next version. So upgrading to these new versions is critical.






Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.