Front End Security: Threats And Countermeasures
Published: 2023-11-10 19:29:26

 by [Esther Abraham](https://blog.openreplay.com/authors/esther-abraham)

<blockquote><em>
The front end is the first thing a user gets to experience once they use your website or web app. If the front end of your web app is breached, it can affect the whole layout and create terrible user experiences that might be hard to recover from. It is becoming increasingly important to integrate front-end security, and this article will guide you through the preventive countermeasures you can apply to guard your web apps.
</em></blockquote>

<div style="background-color:#efefef; border-radius:8px; padding:10px; display:block;">
<hr/>
<h3><em>Session Replay for Developers</em></h3> 
<p><em>Uncover frustrations, understand bugs and fix slowdowns like never before with <strong><a href="https://github.com/openreplay/openreplay" target="_blank">OpenReplay</a></strong> — an open-source session replay suite for developers. It can be <strong>self-hosted</strong> in minutes, giving you complete control over your customer data.</em></p>
<img alt="OpenReplay" style="margin-top:5px; margin-bottom:5px;" width="768" height="400" src="https://raw.githubusercontent.com/openreplay/openreplay/main/static/openreplay-git-hero.svg" class="astro-UXNKDZ4E" loading="lazy" decoding="async">
<p><em>Happy debugging! <a href="https://openreplay.com" target="_blank">Try using OpenReplay today.</a></em><p>
<hr/>
</div>

Front-end security refers to the techniques or practices used to protect the client side of your web apps/websites from threats and vulnerabilities. It is important to prevent unauthorized access, data breaches, and malicious activities that can affect the overall integrity of your web app. Your front end can be vulnerable to several attacks like [Cross-Site Scripting (XSS)](https://owasp.org/www-community/attacks/xss/), which injects malicious scripts into your web app to target its users. There are other front-end threats like [Cross-Site Request Forgery](https://www.cloudflare.com/en-gb/learning/security/threats/cross-site-request-forgery/), [Clickjacking](https://portswigger.net/web-security/clickjacking), and so on. Without the proper measures, your web app will be vulnerable to most of these threats.
Let’s dive in!
 
## Why is Front End Security Important?
There are several reasons why front-end security is important, and it is usually the first line of defense against cyber threats. When you implement rigorous security measures for the front end of your web apps, you mitigate several vulnerabilities that an attacker could exploit. Here are a few reasons why front-end application security is important:
1. **Protection of Data Usage and Privacy:** One of the most important aspects of front-end security is that it safeguards data usage and privacy. The front end of several web apps usually asks users to input sensitive information like personal or financial data. This sensitive information can easily be stolen if your front-end security is weak and vulnerable. If you implement good security measures, it will prevent unauthorized access to user data and help maintain confidentiality.

2. **Handling User Authentication and Vulnerabilities:** It is critical to ensure user logins and authentication. When you perform proper front-end security, you stop/mitigate unauthorized access to user accounts. This authentication prevents a user’s account and actions on your web app from being exploited.

3. **Secure Communication and Content Security:** Implementing front-end security also helps to encrypt the data exchange between users and the server to prevent unauthorized eavesdropping or interception. This secure communication ensures that every sensitive information sent during transmission is kept confidential.
 
So, front-end security gives you an upper hand in protecting user data, establishing trust in your web apps, and ensuring secure communications. When you focus on protecting users' data and putting several security measures in place, you introduce users to an environment where they can confidently engage in your web apps, knowing their data and privacy are safe.
 

<CTA_Middle_Security />
 
## Common Front-End Security Threats and Their Preventive Measures
Attackers are usually interested in the vulnerabilities of your front-end architecture as it makes it easy for them to break down your web apps. But with the right measures in place, you can easily fend off and mitigate any threat. There are tons of threats that your web application can be vulnerable to. [OWASP's top ten](https://owasp.org/www-project-top-ten/) gives us an insight into a few security threats we should be aware of. Some of these include Cross-Site Scripting (XSS), Injections, Server-side request forgery, and many more.
In this section, we will explain a few threats listed by OWASP's top ten that can affect the security of your web app's front end. We will also look at the preventive measures you can use to safeguard your front end against these threats and vulnerabilities. Let's have a look at the common threats and their preventive measures.

### 1. Cross-Site Scripting (XSS):
Cross-site scripting (XSS) is one of the most common threats to the front end of web apps. It occurs when an attacker injects a malicious script into several web pages that will be delivered to the users of your web app. These malicious scripts are set to gain access to a user's data, browser history, cookies, etc. So, a serious consequence of XSS attacks is the theft of user information and even the manipulation of user sessions.

To prevent XSS attacks, you can implement a [Content Security Policy (CSP)](https://content-security-policy.com/) or carry out [input sanitizations](https://www.google.com/amp/s/www.webopedia.com/definitions/input-sanitization/amp/). Let's take a look at each of them:
- **Content Security Policy (CSP):**
The role of CSP is to help specify which content sources are safe to load. This helps to reduce the risk of XSS attacks by avoiding the execution of malicious scripts from an attacker. CSP directives are also known to restrict the loading of scripts to reduce the security risk. To implement CSP:
1. Add a CSP header to your web page's HTTP response. You can carry this out using a `<meta>` tag in the HTML code, as follows:
```HTML
<meta http-equiv="Content-Security-Policy" content="...">
```

2. In the `content` attribute above, define the sources that will be allowed for several types of content like scripts, styles, images, etc. You can use directives like `img-src`, `script-src`, etc., to define all allowed domains. For example:
```HTML
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' https://trusted-cdn.com;">
```

3. To reduce the risk of inline code injection attacks, use nonces or hashes to specify inline content to be executed. Example:
```HTML
<script nnonce="randomly_generated_nonce">...</script>
```
4. You must implement a reporting mechanism using either the `report-uri` or `report-to` directive. This implementation helps you to understand and debug violations of your CSP policy by sending violation reports to a designated endpoint. Here's how:
```HTML
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; report-to /csp-report-endpoint;">
```
The usage of `report-to` requires a [JSON](https://www.json.org/json-en.html) configuration specifying the reporting endpoints and group. Example:
```HTML
<script>
 window.reportingEndpoint = "https://your-reporting-endpoint.com";
 window.reportingGroup = "your-reporting-group";
</script>
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; report-to your-reporting-group;">
```
It is also advised that you test thoroughly to ensure that your CSP policy does not block essential resources or cause issues on your website.
 

- **Input Sanitization:**
This helps to validate and sanitize a user's input before rendering it on a web page. Here, we make use of validation libraries or frameworks that reject inputs that contain harmful characters. When you sanitize user inputs, you prevent attackers from injecting malicious scripts in the first place. Here are a few things to implement for input sanitization:
1. Use front-end libraries or frameworks that automatically escape user input. [React](https://react.dev/) and [Angular](https://angular.io/) are perfect examples that sanitize input data by default.
2. Make use of escape functions to encode special characters. Common escape functions include `textContent` for text nodes, `setAttribute` for setting attributes, and `encodeURIComponent` for URL parameters.
3. You should minimize the use of `innerHTML` for injecting any user-generated content into the DOM. It is safer to set the text content directly. Here's how:
```javascript
element.textContent = sanitizedUserInput; 
```
4. You can validate user inputs to ensure they align with expected formats. Reject all inputs that contain HTML or script tags. Here's how:
```javascript
if (isValidInput(userInput)) {
// Process input
}
```
It is recommended that you go for a combination of the above. Combining the above methods should give you solid layers of defense against XSS attacks.
 
### 2. Cross-Site Request Forgery (CSRF):
In Cross-Site Request Forgery (CSRF), an attacker lures a user into taking a harmful action on a website without their knowledge. CSRF attacks are usually executed with download forms.
It is a common thing for some users to save their login credentials on your web app. But this can prove to be a problem. An attacker can send a download link to your web app's user. If the user downloads the file, they automatically give up their saved credentials. When an attacker has access to a user's credentials, it can be used for fraudulent purposes.

You can prevent CSRF attacks by implementing a common preventive measure known as [CSRF tokens](https://brightsec.com/blog/csrf-token/). When implemented, a unique code is generated for every user session and embedded in forms. The server now verifies the token with every request to make sure that the action originated from the same user to avoid actions from malicious requests. Here's a step-by-step process on how to implement CSRF tokens:
1. You will need to generate the CSRF tokens. When a user logs into your web app or starts a session, generate a unique CSRF token on the server side and associate it with the user's session. 
2. Include the CSRF tokens as a hidden field in forms or the headers of your AJAX requests. Here's how to include CSRF tokens in forms:
```html
<form action="/process" method="POST">
     <input type="hidden" name="csrf_token" value="unique_token_here">
     <!-- other form fields go here }
     <button type="submit">Tap to submit </button>
</form>
```
Here's how to include CSRF tokens in the headers of your AJAX requests:
```javascript
const csrfToken = "unique_token_goes_here";
fetch('/api/data', {
  method: 'POST', 
  headers: {
      'Content-Type': 'application/json', 
      'X-CSRF-Token': csrfToken
  },
  body: JSON.stringify(data)
});
```
3. When you receive a form submission or AJAX request, you need to verify that the provided CSRF tokens match the one linked with the user's session. You can reject the requests if the tokens do not match. Here's an example using a server-side language like Express.js (Node.js):
```javascript
app.post('/process', (req, res) => {
  const clientToken = req.body.csrf_token; // Token from the client
  const serverToken = req.session.csrf_token; // Token associated with the user's session
  
  if (clientToken === serverToken) {
    // CSRF token is valid, process the request
    // ...
  } else {
    // CSRF token is invalid, reject the request
    res.status(403).send('CSRF token mismatch');
  }
});
```

With the above, you should get an idea of how to handle tokens and how they work to help prevent CSRF attacks.

### 3. Clickjacking:
This is carried out by replacing genuine parts of a website (like layout) with similar elements that are dangerous. It is meant to trick users into clicking on something different from what they thought was legit. For example, a button can be replaced with a malicious one that can redirect a user to fake pages or dangerous sites.
Clickjacking deceives users into carrying out actions they never intended. This can lead to the disclosure of sensitive data, exposure to malware, and even financial losses (attackers can use users' financial data to make fraudulent purchases).
It is quite easy to prevent clickjacking on your web apps; you can either implement Javascript [frame-busting](https://docs.oracle.com/en/applications/jd-edwards/administration/9.2.x/eotsc/framebusting.html) scripts or [`X-Frame-Options`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options). Let's have a look at each of them:
- **Javascript Frame-Busting Script:**
To prevent content from being uploaded within iframes or iframes, it is important to implement Frame-busting techniques like the Javascript frame-busting script. This code prevents your web pages from being loaded within iframes. Here's how to implement a Javascript frame-busting script:
```javascript
if (window !=top) {
  top.location.href = window.location.href;
}
```
The code above checks if the current window is the top-level window. If it isn't, the top-level window will be redirected to the same URL, thereby breaking out of any iframe embedding.
- **X-Frame-Options:**
When you set the `X-Frame-Options` header in the HTTPS response, you can specify if your site should be displayed on an iframe on another domain. There are three options which are: 
1. **`DENY`:** Doesn't allow any domain to display a particular page within an iframe. 
2. **`SAMEORIGIN`:** Allows a page to be displayed in a frame on another page but only within the same domain.
3. **`ALLOW-FROM uri`:** Allows a page to be displayed in a frame only in a specific URL.

Here's an example code using one of the options above:
```HTML
X-Frame-Options: DENY
```
It is recommended that you combine both the Javascript frame-busting script with `X-Frame-Options` for better security against clickjacking.

### 4. UI Redressing (CSS injections):
UI redressing or [CSS injections](https://owasp.org/www-project-web-security-testing-guide/v41/4-Web_Application_Security_Testing/11-Client_Side_Testing/05-Testing_for_CSS_Injection) is when an attacker injects malicious CSS codes into your web app. The purpose of a CSS injection is to alter the original layout of your web app.
CSS injections change the appearance of your web app, making it look legitimate while it misleads users. An attacker can alter several things on your web app, like buttons, links, or forms, using CSS injections. These altered buttons or links can redirect a user to malicious pages.
To prevent CSS injections, you need to ensure proper input validation. Ensuring proper input validation is important to validate all user-generated input that can be targeted and used in CSS injection points. Make sure that only the intended styles are allowed to be injected into your web app spreadsheet. Here's what you need to do:
1. Only accept user-generated content from sources that are reliable and trusted. Avoid users from inputting raw CSS codes directly.
2. Limit user inputs to specific characters or formats. For example, if you expect a color code, verify that the input matches a valid color pattern. Here's how:
```javascript
if (!isValidColorCode(userInput)) {
  // Reject input that doesn't match the expected format
}
```
3. Next, you can create your list of allowed CSS properties concerning user-generated content. Example:
```javascript
const allowedProperties = ['color', 'font-size', 'background-color'];
if (!allowedProperties.includes(userProperty)) {
  // Reject input with disallowed property
}
```
4. Use a library that sanitizes user inputs to remove or escape harmful characters. [DOMpurify](https://github.com/cure53/DOMPurify) is a Javascript library for this. First, you have to include the DOMpurify library into your HTML code via a [Content Delivery Network (CDN)](https://www.cloudflare.com/en-gb/learning/cdn/what-is-a-cdn/):
```HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/dompurify/2.3.1/purify.min.js"></script>
```
Next, you can use DOMpurify in your Javascript code to sanitize user inputs:
```javascript
const userInput = '<script>alert("XSS attack!");</script>';
const sanitizedInput = DOMPurify.sanitize(userInput);
console.log(sanitizedInput);
```

With all the rules you have set from the above steps, it should be difficult for an attacker to inject your web apps with malicious CSS codes.
 
### 5. Man-in-the-Middle Attacks (MitM):
[MitM attacks](https://www.imperva.com/learn/application-security/man-in-the-middle-attack-mitm/) are a type of threat that occurs when an attacker interrupts the communication between two parties. This interruption in communication is done without either party's consent or knowledge.
In MitM attacks, the information exchanged between communicating parties is stolen. Attackers can steal information like credit card insurance, passwords, or other personal information. In the worst cases, an attacker can use this stolen information for purposes that may harm the victim.
You can avoid a MitM attack by implementing HTTPS with Valid [SSL/TLS certificates](https://aws.amazon.com/what-is/ssl-certificate/). HTTPS helps to encrypt the data that is transmitted between users and websites. Data encryption makes it difficult for an attacker to interrupt and modify information. Valid SSL/TLS certificates help ensure the connection is secure and authenticated. Here are general steps you can follow to do this:
1. You will need to acquire an SSL/TLS certificate from a trusted Certificate Authority (CA) like [Let’s Encrypt](https://letsencrypt.org/).
2. Follow the easy instructions provided by your web server software like [Apache](https://httpd.apache.org/) or [Nginx](https://www.nginx.com/) to install the SSL/TLS certificate.
3. Configure your web server to listen on the HTTPS port. You must redirect all HTTP traffic to HTTPS to ensure the connections are encrypted. Here's an example using Nginx:
```nginx
server {
  listen 80;
  server_name yourdomainname.com www.yourdomainname.com;
  return 301 https://$host$request_uri;
}
```

4. Make use of the [HTTP Strict Transport Security (HSTS)](https://developers.cloudflare.com/ssl/edge-certificates/additional-options/http-strict-transport-security/) header to your server responses to help instruct browsers to always use HTTPS for future connections.
Implementing the above is an important security measure for all web-based applications to ensure data confidentiality and integrity.

## Conclusion
In web development, it is not a consideration to implement front-end security, and it is a necessity to do so. Protecting user data and enhancing trust among the users of your web app should be a priority. It also helps to foster the integrity of your web apps.
In this article, we have talked about a few threats that are common to front-end security based on insights from OWASP's top ten. Some of these threats include Cross-site Scripting (XSS), Cross-site Request Forgery (CSRF), Clickjacking, and the rest. Every one of these threats has the potential to disrupt your web apps if you don't implement the proper preventive measures discussed above. Don't forget to uphold the security of your front-end software development; it is usually one of the key areas where trust and foundation are built.