阿里云主机折上折
  • 微信号
Current Site:Index > Common front-end security threats

Common front-end security threats

Author:Chuan Chen 阅读数:30460人阅读 分类: 前端安全

In front-end development, security issues are often overlooked, but once vulnerabilities occur, they can lead to user data leaks, session hijacking, or even system crashes. From XSS to CSRF, clickjacking to dependency library vulnerabilities, attack methods are diverse. Developers need a comprehensive understanding of these threats' mechanisms and defense strategies.

Cross-Site Scripting (XSS)

XSS attacks inject malicious scripts into web pages, which execute when users browse. There are three main types:

  1. Stored XSS: Malicious scripts are permanently stored on the server.
// Attacker-submitted comment content
Malicious payload: <script>stealCookies()</script>
  1. Reflected XSS: Malicious scripts originate from the current HTTP request.
// Malicious URL crafted by the attacker
http://example.com/search?q=<script>alert(1)</script>
  1. DOM-based XSS: Executed entirely on the client side.
// Unsafe DOM operation
document.getElementById('output').innerHTML = userInput;

Defense measures:

  • HTML entity encoding for all dynamic content
  • Use CSP (Content Security Policy) headers
  • Avoid innerHTML; prefer textContent
  • Filter rich text using libraries like DOMPurify

Cross-Site Request Forgery (CSRF)

CSRF tricks users into performing unintended actions in authenticated web applications. Typical attack flow:

  1. User logs into a bank website; session cookie is valid.
  2. Attacker lures the user to a malicious page.
  3. The page automatically submits a transfer form.
<!-- Auto-submitting form in a malicious page -->
<form action="https://bank.com/transfer" method="POST">
  <input type="hidden" name="amount" value="10000">
  <input type="hidden" name="to" value="attacker">
</form>
<script>document.forms[0].submit()</script>

Defense strategies:

  • Use CSRF tokens
  • Set SameSite cookie attributes
  • Check Origin/Referer headers
  • Require secondary authentication for critical operations

Clickjacking

Uses transparent iframes to trick users into clicking hidden elements. Example:

<style>
  iframe {
    opacity: 0.01;
    position: absolute;
    top: 300px;
    left: 400px;
    width: 200px;
    height: 50px;
  }
</style>
<iframe src="https://bank.com/delete-account"></iframe>

Defense methods:

  • Set X-Frame-Options headers
  • Use CSP's frame-ancestors directive
  • Add "framebuster" scripts

Insecure Third-Party Dependencies

Modern front-end projects rely on numerous npm packages, which may introduce vulnerabilities:

# Check for known vulnerabilities
npm audit

Common issues:

  • Outdated jQuery versions with XSS vulnerabilities
  • Tampered dependency packages (supply chain attacks)
  • Malicious code in font/image resources

Solutions:

  • Regularly update dependencies
  • Use npm ci instead of npm install
  • Verify resource integrity signatures
  • Lock dependency versions

Client-Side Data Storage Risks

Insecure local storage usage:

// Unsafe: Storing sensitive data in localStorage
localStorage.setItem('authToken', 'eyJhbGci...');

// Cookies that can be read
document.cookie = "session=123; path=/;";

Best practices:

  • Use HttpOnly and Secure cookies for sensitive data
  • Prefer SessionStorage over localStorage
  • Encrypt stored data when necessary
  • Regularly clean stored data

CORS Misconfiguration

Incorrect CORS settings can lead to data leaks:

// Dangerous server configuration
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true

Correct approach:

  • Explicitly specify allowed origins
  • Avoid using wildcards with credentials
  • Disable CORS for sensitive operations
  • Strictly validate preflight requests

Front-End Input Validation Bypass

Risks of relying solely on front-end validation:

// Client-side validation easily bypassed
if(password.length > 6) {
  submitForm();
}

Complete solution:

  • Server must repeat all validations
  • Use strict regex for input formatting
  • Escape special characters
  • Implement rate limiting to prevent brute force attacks

WebSocket Security Issues

Insecure WebSocket implementations:

const ws = new WebSocket('ws://example.com/chat');

// Unverified message handling
ws.onmessage = (event) => {
  document.getElementById('chat').innerHTML += event.data;
};

Protection measures:

  • Use wss:// protocol
  • Verify message source and format
  • Set message size limits
  • Sensitive operations still require server authentication

Performance API Abuse

Performance APIs may leak sensitive information:

// Measuring execution time of specific operations
const start = performance.now();
checkPassword(input);
const duration = performance.now() - start;

Mitigation methods:

  • Disable high-precision timestamps
  • Use PerformanceObserver for monitoring
  • Add random delays to eliminate timing differences

Browser Caching Issues

Sensitive data may be accidentally cached:

HTTP/1.1 200 OK
Content-Type: application/json
Cache-Control: public

Correct caching strategy:

  • Default to Cache-Control: no-store
  • Add no-cache to API responses
  • Use hash fingerprints for static resources
  • Set Clear-Site-Data for sensitive pages

Front-End Supply Chain Attacks

Build tools can become attack vectors:

  1. Malicious pre-commit hooks
  2. Tampered webpack plugins
  3. Malicious editor extensions

Protection recommendations:

  • Verify build artifact integrity
  • Use lock files (e.g., package-lock.json)
  • Isolate CI/CD environments
  • Audit all build scripts

Insecure Communication Transmission

Risks of unencrypted communication:

<!-- Mixed content warning -->
<img src="http://example.com/logo.png">

Security requirements:

  • Full-site HTTPS deployment
  • Enable HSTS headers
  • Automatically upgrade insecure requests
  • Disable TLS 1.0/1.1

Client-Side Logic Bypass

Front-end validation can be easily bypassed:

// Modify front-end validation logic
document.forms[0].onsubmit = function(){ return true; }

Defensive design:

  • Critical logic must be implemented server-side
  • Obfuscate important client-side code
  • Use WebAssembly for sensitive algorithms
  • Implement runtime integrity checks

Browser Extension Risks

Malicious extensions may:

  • Read all page data
  • Modify DOM content
  • Steal login credentials

Protection advice:

  • Minimize installed extensions
  • Regularly review extension permissions
  • Use enterprise policies to restrict installations
  • Perform sensitive operations in isolated browsers

Automation Tool Abuse

Threats from crawlers and automation scripts:

# Using Selenium to simulate user actions
driver.find_element_by_id('username').send_keys('admin')

Countermeasures:

  • Implement CAPTCHA
  • Detect automation behavior patterns
  • Set operation frequency limits
  • Use anti-automation services like Akamai Bot Manager

Front-End Encryption Implementation Flaws

Incorrect encryption implementations:

// Unsafe custom encryption
function encrypt(text) {
  return text.split('').reverse().join('');
}

Correct approach:

  • Use Web Crypto API
  • Avoid handling sensitive encryption client-side
  • Leave key management to the server
  • Use audited encryption libraries

Server-Side Rendering Security

SSR-specific security issues:

// Unsafe props passing
<script>
  window.__INITIAL_STATE__ = ${JSON.stringify(data)};
</script>

Security practices:

  • Filter JSON serialization
  • Avoid directly injecting user input into templates
  • Implement strict CSP policies
  • Isolate rendering process permissions

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.