Web security

In this post I will list out some resources and best practices about web security, what are the most common attacks and how to protect from them.

OWASP

When the topic is web security, an important resource to follow is OWASP (The Open Web Application Security Project) - it provides tons of tools and resources and is the primary source of knowledge to secure the web.

Top Ten

The OWASP Top 10 is a standard awareness document for developers, that represents a broad consensus about the most critical security risks to web applications.

View OWASP Top Ten

Cheat Sheet Series

The OWASP Cheat Sheet Series was created to provide a concise collection of high value information on specific application security topics.

View OWASP Cheatsheet Series

Authentication

Authentication is the process of verifying that an individual, entity or website is whom it claims to be.

User IDs

Make sure your usernames/user IDs are case-insensitive and unique.

Implement Proper Password Strength Controls

A key concern when using passwords for authentication is password strength. A "strong" password policy makes it difficult or even improbable for one to guess the password through either manual or automated means.

  • Password length
    • Minimum length of the passwords should be enforced by the application. Passwords shorter than 8 characters are considered to be weak.
    • Maximum password length should not be set too low, as it will prevent users from creating passphrases. A common maximum length is 64 characters due to limitations in certain hashing algorithms
  • Include password strength meter to help users create a more complex password and block common and previously breached passwords
  • Allow usage of all characters including unicode and whitespace. There should be no password composition rules limiting the type of characters permitted.

For more detailed information check Passwords Evolved: Authentication Guidance for the Modern Era

Implement Secure Password Recovery Mechanism

  • Return a consistent message for both existent and non-existent accounts to prevent the attacker to check which accounts exist and which don't.
  • Use URL tokens for the simplest and fastest implementation.
  • Ensure that generated tokens or codes are:
    • Randomly generated using a cryptographically safe algorithm.
    • Sufficiently long to protect against brute-force attacks.
    • Stored securely.
    • Single use and expire after an appropriate period.
  • Do not make a change to the account until a valid token is presented, such as locking out the account

Resetting password

  • The user should confirm the password they set by writing it twice.
  • Ensure that a secure password policy is in place, and is consistent with the rest of the application.
  • Update and store the password following secure practices.
  • Send the user an email informing them that their password has been reset (do not send the password in the email!).
  • Once they have set their new password, the user should then login through the usual mechanism. Don't automatically log the user in, as this introduces additional complexity to the authentication and session handling code, and increases the likelihood of introducing vulnerabilities.
  • Ask the user if they want to invalidate all of their existing sessions, or invalidate the sessions automatically.

Authentication and Error Messages

Using any of the authentication mechanisms (login, password reset or password recovery), an application must respond with a generic error message regardless of whether:

  • The user ID or password was incorrect.
  • The account does not exist.
  • The account is locked or disabled.

Example of correct login error message:
Login failed; Invalid user ID or password

Example of correct password recovery error message:
If that email address is in our database, we will send you an email to reset your password.

Example of correct account creation error message:
A link to activate your account has been emailed to the address provided.

Multi-Factor Authentication

Multi-factor authentication (MFA) is by far the best defence against the majority of password-related attacks, including brute-force attacks, with analysis by Microsoft suggesting that it would have stopped 99.9% of account compromises.

Read more about Multifactor Authentication

Captcha

The use of an effective CAPTCHA can help to prevent automated login attempts against accounts. However, many CAPTCHA implementations have weaknesses that allow them to be solved using automated techniques or can be outsourced to services which can solve them. As such, the use of CAPTCHA should be viewed as a defence-in-depth control to make brute-force attacks more time consuming and expensive, rather than as a preventative.

OAuth

Open Authorization (OAuth) is a protocol that allows an application to authenticate against a server as a user, without requiring passwords or any third party server that acts as an identity provider. It uses a token generated by the server and provides how the authorization flows most occur, so that a client, such as a web application, can tell the server what user is using the service.

OpenId

OpenId is an HTTP-based protocol that uses identity providers to validate that a user is who they say they are. It is a very simple protocol which allows a service provider initiated way for single sign-on (SSO). This allows the user to re-use a single identity given to a trusted OpenId identity provider and be the same user in multiple websites, without the need to provide any website with the password, except for the OpenId identity provider.

SAML

SAML stands for Security Assertion Markup Language. It is an XML-based open-standard for transferring identity data between two parties: an identity provider (IdP) and a service provider (SP).

  • Identity Provider — Performs authentication and passes the user's identity and authorization level to the service provider.

  • Service Provider — Trusts the identity provider and authorizes the given user to access the requested resource.


Authorization

Authorization is the function of specifying access rights/privileges to resources - in other words it's the process of verifying that a requested action or service is approved for a specific entity.

Enforce Least Privileges

As a security concept, Least Privileges refers to the principle of assigning users only the minimum privileges necessary to complete their job. This concept comes into play mainly in system administration, but has relevance in all applications where there are distinct roles and permissions for different user types.

Failure to enforce least privileges in an application can jeopardize the confidentially of sensitive resources.

Deny by default

One should be able to explicitly justify why a specific permission was granted to a particular user or group rather than assuming access to be the default position.

Enforce Authorization Checks on Static Resources

The importance of securing of static resources is often overlooked or at least overshadowed by other security concerns. Although unprotected static resources is certainly a problem for websites and web applications of all forms, in recent years, poorly secured resources in cloud storage offerings (such as Amazon S3 Buckets) have risen to prominence. When securing static resources, consider the following:

  • Ensure that static resources are incorporated into access control policies. Ensure any cloud based services used to store static resources are secured using the configuration options and tools provided by the vendor. Review the cloud provider's documentation (see guidance from AWS, Google Cloud and Azure for specific implementations details,)
  • When possible, protect static resources using the same access control logic and mechanisms that are used to secure other application resources and functionality.

Subresource Integrity(SRI)

Subresource Integrity (SRI) is a security feature that enables browsers to verify that resources they fetch (for example, from a CDN) are delivered without unexpected manipulation. It works by allowing you to provide a cryptographic hash that a fetched resource must match.

Cross-Origin Resource Sharing (CORS)

Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading of resources. CORS also relies on a mechanism by which browsers make a "preflight" request to the server hosting the cross-origin resource, in order to check that the server will permit the actual request. In that preflight, the browser sends headers that indicate the HTTP method and headers that will be used in the actual request.

Content Security Policy (CSP)

CSP makes it possible to specify the domains that the browser should consider to be valid sources of executable scripts. A CSP compatible browser will then only execute scripts loaded in source files received from those allowed domains, ignoring all other scripts (including inline scripts and event-handling HTML attributes).

  • A primary goal of CSP is to mitigate and report XSS attacks. XSS attacks exploit the browser's trust in the content received from the server. Malicious scripts are executed by the victim's browser because the browser trusts the source of the content, even when it's not coming from where it seems to be coming from.
  • In addition to restricting the domains from which content can be loaded, the server can specify which protocols are allowed to be used
    • f.e enforcing HTTPS for data transfer
    • marking all cookies with the secure attribute and providing automatic redirects from HTTP pages to their HTTPS counterparts

Exit Safely when Authorization Checks Fail

Failed access control checks are a normal occurrence in a secured application; consequently, developers must plan for such failures and handle them securely. Improper handling of such failures can lead to the application being left in an unpredictable state.

  • Ensure all exception and failed access control checks are handled no matter how unlikely they seem
  • Centralize the logic for handling failed access control checks - this can be achieved with API wrapper, that is used for requests throughout the application.

Types of attacks

Automated attacks

Brute Force - Testing multiple passwords from a dictionary or other source against a single account.

Credential Stuffing - Testing username/password pairs obtained from the breach of another site.

Password Spraying - Testing a single weak password against a large number of different accounts.

XSS

Cross-site scripting (XSS) is a security exploit which allows an attacker to inject into a website malicious client-side code.

Stored XSS Attacks

The injected script is stored permanently on the target servers. The victim then retrieves this malicious script from the server when the browser sends a request for data.

  1. An attacker with a malicious script accesses the application.

  2. He fills up a form and inputs malicious script in the form field.

  3. The malicious script reaches back-end systems via a form field data and is saved in the database.

  4. When some legitimate user accesses the application, he is served with the malicious script by the application’s back-end. The browser doesn’t know it is a malicious script and executes it.

Reflected XSS Attacks

When a user is tricked into clicking a malicious link, submitting a specially crafted form, or browsing to a malicious site, the injected code travels to the vulnerable website. The Web server reflects the injected script back to the user's browser, such as in an error message, search result, or any other response that includes data sent to the server as part of the request. The browser executes the code because it assumes the response is from a "trusted" server which the user has already interacted with.

DOM-based XSS Attacks

The payload is executed as a result of modifying the DOM environment (in the victim’s browser) used by the original client-side script. That is, the page itself does not change, but the client side code contained in the page runs in an unexpected manner because of the malicious modifications to the DOM environment.

XSS Prevention Methods

  • HTML Encode Before Inserting Untrusted Data into HTML Element Content - When you need to put untrusted data directly into the HTML body somewhere. This includes inside normal tags like div, p, b, td, etc
<span>UNTRUSTED DATA</span>
  • Attribute Encode Before Inserting Untrusted Data into HTML Common Attributes - When you need to put untrusted data into HTML attribute values like width, name, value, etc.
<input type="text" name="fname" value="UNTRUSTED DATA" />
  • JavaScript Encode Before Inserting Untrusted Data into JavaScript Data Values
    • HTML Encode JSON values in an HTML context and read the data with JSON.parse
  • CSS Encode And Strictly Validate Before Inserting Untrusted Data into HTML Style Property Values
<div style="width:UNTRUSTED DATA">Selection</div>
  • URL Encode Before Inserting Untrusted Data into HTML URL Parameter Values
<a href="/site/search?value=UNTRUSTED DATA">clickme</a>
  • Sanitize HTML Markup with a Library Designed for the Job
  • Avoid JavaScript URLs - Untrusted URLs that include the protocol javascript: will execute JavaScript code when used in URL DOM locations such as anchor tag HREF attributes or iFrame src locations.
<a href="UNTRUSTED URL">clickme</a> <iframe src="UNTRUSTED URL" />
  • Use HTTPOnly cookie flag - OWASP recommends you set the HTTPOnly flag on your session cookie and any custom cookies you have that are not accessed by any JavaScript you wrote.
  • Implement Content Security Policy
  • Properly use modern JS frameworks
    • Modern JavaScript frameworks have pretty good XSS protection built in. Usually framework API allows bypassing that protection in order to render unescaped HTML or include executable code.

View more about XSS prevention

Cross-Site Request Forgery (CSRF)

CSRF (sometimes also called XSRF) is a related class of attack. The attacker causes the user's browser to perform a request to the website's backend without the user's consent or knowledge. An attacker can use an XSS payload to launch a CSRF attack.

For every session of a user, the server should generate a randomized token (CSRF Token) and send it to the client. The client can save the token, from where javascript can read it.

When a web application is making an HTTP request, the application should include that randomized token (CSRF Token) in the header of each request.

View more about CSRF prevention

Man-in-the-middle (MitM)

A Man in the Middle attack, or MITM, is a situation where a malicious entity can read/write data that is being transmitted between two or more systems (in most cases, between you and the website that you are surfing).

Session hijacking

Session hijacking consists of gaining access to and misusing a user's authenticated session. This may happen by stealing a cookie for an existing session, or by fooling the user (or their browser) into setting a cookie with a predetermined session ID.

HSTS

The HTTP Strict-Transport-Security response header (often abbreviated as HSTS) lets a web site tell browsers that it should only be accessed using HTTPS, instead of using HTTP.

If a website accepts a connection through HTTP and redirects to HTTPS, visitors may initially communicate with the non-encrypted version of the site before being redirected, if, for example, the visitor types http://www.foo.com/ or even just foo.com. This creates an opportunity for a man-in-the-middle attack. The redirect could be exploited to direct visitors to a malicious site instead of the secure version of the original site.


Resources used:

  • https://owasp.org
  • https://owasp.org/www-project-top-ten
  • https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html
  • https://cheatsheetseries.owasp.org/cheatsheets/Authorization_Cheat_Sheet.html
  • https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity
  • https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
  • https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP
  • https://auth0.com/blog/how-saml-authentication-works/
  • https://developer.mozilla.org/en-US/docs/Web/Security/Types_of_attacks
  • https://medium.com/@manojsingh047/understanding-frontend-security-ff6585395534
  • https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html
  • https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html
  • https://www.catchpoint.com/blog/https-man-in-the-middle
  • https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security

© kaidohussar.dev

Check out my CMS for web apps

contentstorage.app