OWASP

What is OWASP?

  • The Open Web Application Security Project (OWASP) is a non-profit organization dedicated to providing unbiased, practical information about application security.

Some definitions to know

  • Risks: “Risk” of you being get involved in the accident on road.
  • Threats: “Threats” are the one who makes you to involve in the accident.
  • Vulnerabilities: You are the one “vulnerable” to get involved in the accident.

How to avoid these?

  1. Tools and processes
    • This enable developers to find and fix vulnerabilities while they are coding.
  2. Software composition analysis (SCA) 
    • SCA is the process of automating the visibility into open source software (OSS) use for the purpose of risk management, security and license compliance.
    • Because the majority of software creation includes OS, manual tracking is difficult, requiring the need to use automation to scan source code, binaries and dependencies.
  3. Dynamic analysis 
    • Dynamic analysis is the testing and evaluation of a program by executing data in real-time.
    • The objective is to find errors in a program while it is running, rather than by repeatedly examining the code offline. A daily build and smoke test is one type of dynamic analysis.
    • Testing is called as Dynamic Application Security Testing (DAST).
  4. Static analysis
    • Static analysis is a method of computer program debugging that is done by examining the code without executing the program.
    • Testing is called as Static Application Security Testing (SAST).

What is OWASP Top 10?

  • The OWASP Top 10 Web Application Security Risks (updated every year) will provide guidance to developers and security professionals on the most critical vulnerabilities that are commonly found in web applications, which are also easy to exploit.
  • These 10 application risks are dangerous because they may allow attackers to plant malware, steal data, or completely take over your computers or web servers.

The following identifies each of the OWASP Top 10 Web Application Security Risks.

1. Injection

Injection flaws, such as SQL injection, LDAP injection, and CRLF injection, occur when an attacker sends untrusted data to an interpreter that is executed as a command without proper authorization.

  • Example: SQL injection
    • Java Code:
      • String userId = request.getParameter(“UserId”);
      • String query = “SELECT * FROM Users WHERE UserId = ” + userId;
      • Statement st = Connection.createStatement();
      • ResultSet res = st.executeQuery(query);
    • Input:
      • UserId = 105 OR 1 = 1
    • SQL to-be executed:
      • ” SELECT * FROM Users WHERE UserId = 105 OR 1 = 1 “;
    • Output:
      • The above SQL is valid and will return ALL rows from the “Users” table, since “OR 1 = 1” is always TRUE.
  • Prevention
    • Use parameterized SQL queries (i.e., PreparedStatement) instead of direct SQL statements. Modify the “query” to have a question mark (?) instead of concatenating the “userId” directly. Finally set the value of the variable to the supplied userId.
    • Java Code:
      • String query= “SELECT * FROM Users WHERE UserId = ?”;
      • PreparedStatement st = conn.prepareStatement(query);
      • st.setString(1, userId);
      • ResultSet res = st.executeQuery();
    • Input:
      • UserId = 105 OR 1 = 1
    • SQL to-be executed:
      • ” SELECT * FROM Users WHERE UserId = “105 OR 1 = 1” “;
    • Output:
      • Hacking attempts such as “105 OR 1 = 1” now return no results, since there is no record for UserId = “105 OR 1 = 1”.

2. Broken Authentication

Attackers have access to hundreds of millions of valid username and password combinations for credential stuffing, default administrative account lists, automated brute force, and dictionary attack tools. Session management attacks are well understood, particularly in relation to unexpired session tokens.

  • Example
    • 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 shall allow the attacker with hacked credentials.
  • Prevention
    • Multi-factor authentication, such as FIDO or dedicated apps, reduces the risk of compromised accounts.
    • Enable strong password policy and enforce change user-password often.
    • Change default administrative accounts.
    • Enforce session time-out, idle time-out properly.
    • Develop session management of accounts login to your web-server.

3. Sensitive Data Exposure

Applications and APIs that don’t properly protect sensitive data such as financial data, usernames and passwords, or health information, could enable attackers to access such information to commit fraud or steal identities.

  • Example
    • An application encrypts credit card numbers in a database using automatic database encryption. However, this data is automatically decrypted when retrieved, allowing an SQL injection flaw to retrieve credit card numbers in clear text.
    • No salting of password and store password as it is in the backend.
  • Prevention
    • Encryption of data at rest and in transit.
    • Employ strong encryption/ hashing in your crypto-system.
    • Classify the data and apply controls.

4. XML External Entity (XXE)

Attacker can exploit vulnerable XML processors if they can upload XML or include hostile content in an XML document, exploiting vulnerable code, dependencies or integration. Poorly configured XML processors evaluate external entity references within XML documents. Attackers can use external entities for attacks including remote code execution, and to disclose internal files and SMB file shares.

  • Example
    • Disclosing /etc/passwd or other targeted files.
 <?xml version="1.0" encoding="ISO-8859-1"?>
 <!DOCTYPE foo [  
   <!ELEMENT foo ANY >
   <!ENTITY xxe SYSTEM "file:///etc/passwd" >]><foo>&xxe;</foo>

 <?xml version="1.0" encoding="ISO-8859-1"?>
 <!DOCTYPE foo [  
   <!ELEMENT foo ANY >
   <!ENTITY xxe SYSTEM "file:///c:/boot.ini" >]><foo>&xxe;</foo>
  • Prevention
    • Disable XML external entity and DTD processing in all XML parser.
    • Sanitize the XML input.
    • Use less complex data formats such as JSON and avoid serialization of sensitive data.

5. Broken Access/ Authorization Control

Improperly configured or missing restrictions on authenticated users allow them to access unauthorized functionality or data, such as accessing other users’ accounts, viewing sensitive documents, and modifying data and access rights.

  • Example
    • Accessing some data which are not supposed to access
    • https://bank/balance?acc=123
      • Changing value from 123 to 345, will that allow access to see other’s account (345).
  • Prevention
    • Everyone deny by default and grant specific user-role to grant access for each function needed. It is recommended to log failed attempts to access features to make sure everything is configured correctly.

6. Security Misconfiguration

This risk refers to improper implementation of controls intended to keep application data safe, such as misconfiguration of security headers, error messages containing sensitive information (information leakage), and not patching or upgrading systems, frameworks, and components.

  • Example
    • The application server comes with sample applications that are not removed from the production server where attacker can play around with default credentials.
    • The application server’s configuration allows detailed error messages, e.g. stack traces, to be returned to users. This potentially exposes sensitive information.
  • Prevention
    • Lock down all defaults and unused features.
    • Patch the environments as required.

7. Cross-Site Scripting

Cross-site scripting (XSS) flaws give attackers the capability to inject client-side scripts into the application, for example, to redirect users to malicious websites. XSS enables attackers to inject client-side scripts into web pages viewed by other users. They are 3 types:

  1. Persistent/ Stored XSS, where the malicious input originates from the website’s database.
  2. Reflected XSS, where the malicious input originates from the victim’s request.
  3. DOM-based XSS, where the vulnerability is in the client-side code rather than the server-side code.
  • Example
    • Persistent/ Stored XSS
      • The attacker injects a payload in the website’s database by submitting a vulnerable form with some malicious JavaScript.
      • The victim requests the web page from the website
      • The website serves the victim’s browser the page with the attacker’s payload as part of the HTML body.
      • The victim’s browser will execute the malicious script inside the HTML body. In this case it would send the victim’s cookie to the attacker’s server. The attacker now simply needs to extract the victim’s cookie when the HTTP request arrives to the server, after which the attacker can use the victim’s stolen cookie for impersonation.

Diagram of a persistent XSS attack

  • Type 2: Reflected XSS
    • In a reflected XSS attack, the malicious string is part of the victim’s request to the website. The website then includes this malicious string in the response sent back to the user.
    • The attacker crafts a URL containing a malicious string and sends it to the victim.
    • The victim is tricked by the attacker into requesting the URL from the website.
    • The website includes the malicious string from the URL in the response.
    • The victim’s browser executes the malicious script inside the response, sending the victim’s cookies to the attacker’s server.

Diagram of a persistent XSS attack

  • Type 3: DOM-based XSS
    • DOM-based XSS is a variant of both persistent and reflected XSS. In a DOM-based XSS attack, the malicious string is not actually parsed by the victim’s browser until the website’s legitimate JavaScript is executed.
    • The attacker crafts a URL containing a malicious string and sends it to the victim.
    • The victim is tricked by the attacker into requesting the URL from the website.
    • The website receives the request, but does not include the malicious string in the response.
    • The victim’s browser executes the legitimate script inside the response, causing the malicious script to be inserted into the page.
    • The victim’s browser executes the malicious script inserted into the page, sending the victim’s cookies to the attacker’s server.

Diagram of a DOM-based XSS attack

  • Prevention
    • Encoding, which escapes the user input so that the browser interprets it only as data, not as code. Encoding is the act of escaping user input so that the browser interprets it only as data, not as code. The most recognizable type of encoding in web development is HTML escaping, which converts characters like < and > into &lt; and &gt;, respectively.
    • Validation, which filters the user input so that the browser interprets it as code without malicious commands.

8. Insecure deserialization

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

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.

Example

  • 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:”b6a8b3bea90s0e0e05022f8f3c88bc895“;}

Prevention

  • Have a safe architecture which doesn’t accept serialized objects from untrusted source.
  • If not, implement integrity checks (signature) for all objects from untrusted source.

9. Using Components With Known Vulnerabilities

Developers frequently don’t know which open source and third-party components are in their applications, making it difficult to update components when new vulnerabilities are discovered. Attackers can exploit an insecure component to take over the server or steal sensitive data.

  • Example
    • Library typically run with the same privileges as the application itself, so flaws in any library can result in serious impact. a Struts 2 library exposes remote code execution vulnerability that enables execution of arbitrary code on the app-server.
  • Prevention
    • Software composition analysis conducted at the same time as static analysis can identify insecure versions of components.
    • Remove unused dependencies, unnecessary features, components, files, and documentation.

10. Insufficient Logging and Monitoring

The time to detect a breach is frequently measured in weeks or months. Insufficient logging and ineffective integration with security incident response systems allow attackers to pivot to other systems and maintain persistent threats.

  • Example
    • A major US retailer reportedly had an internal malware analysis sandbox analyzing attachments. The sandbox software had detected potentially unwanted software, but no one responded to this detection. The sandbox had been producing warnings for some time before the breach was detected due to fraudulent card transactions by an external bank.
  • Prevention
    • 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.
    • Monitor and audit the logs often.
    • Think like an attacker and use pen testing to find out if you have sufficient monitoring; examine your logs after pen testing.

Other must to know attacks

  1. CSRF/ XSRF

Anti-CSRF Tokens

The most popular method to prevent Cross-site Request Forgery is to use a challenge token that is associated with a particular user and that is sent as a hidden value in every state-changing form in the web app. This token, called an anti-CSRF token or a synchronizer token, works as follows:

  • The web server generates a token and stores it
  • The token is statically set as a hidden field of the form
  • The form is submitted by the user
  • The token is included in the POST request data
  • The application compares the token generated and stored by the application with the token sent in the request
  • If these tokens match, the request is valid
  • If these tokens do not match, the request is invalid and is rejected

This CSRF protection method is called the synchronizer token pattern. It protects the form against Cross-site Request Forgery attacks because an attacker would also need to guess the token to successfully trick a victim into sending a valid request. The token should also be invalidated after some time and after the user logs out. Anti-CSRF tokens are often exposed via AJAX: sent as headers or request parameters with AJAX requests.

For an anti-CSRF mechanism to be effective, it needs to be cryptographically secure. The token cannot be easily guessed, so it cannot be generated based on a predictable pattern. We also recommend to use anti-CSRF options in popular frameworks such as AngularJS and refrain from creating own mechanisms, if possible. This lets you avoid errors and makes the implementation quicker and easier.

Same-Site Cookies

CSRF attacks are only possible because cookies are always sent with any requests that are sent to a particular origin related to that cookie (see the definition of the same-origin policy). You can set a flag for a cookie that turns it into a same-site cookie. A same-site cookie is a cookie that can only be sent if the request is being made from the origin related to the cookie (not cross-domain). The cookie and the request source are considered to have the same origin if the protocol, port (if applicable) and host (but not the IP address) are the same for both.

A current limitation of same-site cookies is that unlike for example Chrome or Firefox, not all current browsers support them and older browsers do not work with web apps that use same-site cookies (click here for a list of supported browsers). At the moment, same-site cookies are better suited as an additional defense layer due to this limitation. Therefore, you should only use them along with other CSRF protection mechanisms.

  1. Session hijacking attack
  2. Content Spoofing
  3. Buffer overflow attack
  4. Cache Poisoning
  5. Repudiation Attack

 

Cross-Origin Resource Sharing (CORS)

CORS is not wrt cookies, it’s a resource sharing from one domain (1st) context access other resource in other domain (2nd) context (cross-domain) and whether the 2nd domain allows the 1st domain to access the resource or not is determined by the CORS policy configured at 2nd domain.


                    Process flow for CORS requests

Leave a comment