阿里云主机折上折
  • 微信号
Current Site:Index > Dynamic security scanning tools (such as OWASP ZAP)

Dynamic security scanning tools (such as OWASP ZAP)

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

Basic Concepts of Dynamic Security Scanning Tools

Dynamic Application Security Testing (DAST) tools identify potential vulnerabilities by simulating attacks against running web applications. Unlike static analysis, dynamic scanning does not require access to source code. Instead, it detects security issues by sending HTTP requests and analyzing responses. These tools are particularly effective for identifying runtime vulnerabilities such as injection attacks and authentication flaws.

OWASP ZAP (Zed Attack Proxy) is a typical open-source dynamic scanning tool that offers active scanning, passive scanning, and API testing. Its workflow can be summarized as follows:

  1. Intercepting HTTP/HTTPS traffic in proxy mode
  2. Discovering application endpoints using automated crawlers
  3. Sending malicious payloads to test input points
  4. Determining the existence of vulnerabilities based on responses
// Example: A typical XSS test request intercepted by ZAP
GET /search?q=<script>alert(1)</script> HTTP/1.1
Host: vulnerable.site
User-Agent: OWASP-ZAP/v2.11

Detection of Common Frontend Vulnerabilities

XSS Vulnerability Scanning

ZAP detects reflected/stored XSS by injecting various test vectors, including:

  • Basic payload: <script>alert(1)</script>
  • Event handlers: " onmouseover="alert(1)
  • SVG vectors: <svg onload=alert(1)>
  • Unicode obfuscation: \u003cscript\u003ealert(1)
<!-- Example of detected DOM-based XSS -->
<script>
  // Writing URL parameter values directly to the DOM
  document.write(decodeURIComponent(location.search.slice(3)));
  // Triggered when accessing example.com/?=<script>alert(1)</script>
</script>

CSRF Vulnerability Detection

The tool identifies CSRF risks by checking for:

  1. Sensitive operations using GET methods
  2. Presence of CSRF tokens
  3. CORS/Origin header configurations
  4. SameSite Cookie attributes
// Example of frontend CSRF protection code
const csrfToken = document.querySelector('meta[name="csrf-token"]').content;
fetch('/transfer', {
  method: 'POST',
  headers: {
    'X-CSRF-Token': csrfToken,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ amount: 1000 })
});

Insecure Configuration Detection

ZAP flags the following frontend security issues:

  • Missing security headers (e.g., CSP, X-Frame-Options)
  • Sensitive information leakage (API keys, internal IPs)
  • Enabled insecure HTTP methods (PUT/DELETE)
  • Improper CORS configurations (Access-Control-Allow-Origin: *)

Scanning Strategies and Configuration

Scan Scope Control

Define test boundaries using Contexts:

# ZAP API configuration example (Python)
import zapv2
zap = zapv2.ZAPv2()
context_id = zap.context.new_context('frontend_app')
zap.context.include_in_context('frontend_app', 'https://app.com/.*')
zap.context.exclude_from_context('frontend_app', 'https://app.com/logout')

Policy Customization

  1. Strength:

    • Low: Basic test set (quick scan)
    • Medium: Includes boundary value testing
    • High: Incorporates fuzz testing and encoding bypass attempts
  2. Threshold:

    • Off: Ignores potential issues
    • Low: Lenient reporting
    • High: Strict mode (reduces false positives)

CI/CD Integration

Automated Scanning Workflow

  1. Start ZAP daemon:

    docker run -u zap -p 8080:8080 owasp/zap2docker-stable zap.sh \
      -daemon -host 0.0.0.0 -port 8080 -config api.key=12345
    
  2. Execute scan and generate reports:

    // Node.js integration example
    const zap = require('zapv2')();
    (async () => {
      await zap.spider.scan('https://app.com');
      await zap.ascan.scan('https://app.com');
      const report = await zap.core.htmlreport();
      fs.writeFileSync('report.html', report);
    })();
    

Result Analysis

Typical scan reports include:

  • Risk level distribution (High/Medium/Low/Informational)
  • Vulnerability details (request/response samples)
  • Remediation guidance (code examples and configuration instructions)
  • False-positive marking functionality

Advanced Techniques and Custom Rules

Custom Script Extensions

ZAP supports various script types:

// Authentication script example (Groovy)
def authenticate(helper, paramsValues, credentials) {
  def loginUrl = 'https://app.com/login'
  def postData = "user=${credentials.getParam('username')}&pass=${credentials.getParam('password')}"
  helper.sendAndReceive(loginUrl, postData, 'POST')
}

// Passive scan rule example
def appliesToHistoryType(historyType) {
  return historyType == HistoryReference.TYPE_PROXIED
}

def scan(history, helper) {
  if (history.getResponseBody().toString().contains('password')) {
    helper.newAlert()
      .setName('Sensitive Information Leakage')
      .setDescription('Response contains password field')
      .raise()
  }
}

API Security Testing

Methods for testing modern frontend frameworks' APIs:

  1. Import OpenAPI/Swagger definitions
  2. Automate parameter analysis
  3. Test JWT/OAuth2 implementations
  4. Batch detect IDOR (Insecure Direct Object Reference)
# Example API request testing for unauthorized access
GET /api/user/123/profile HTTP/1.1
Authorization: Bearer stolen_token

Collaboration with Other Tools

Combining Static Analysis

Forming a comprehensive security chain:

  1. ZAP detects runtime vulnerabilities
  2. ESLint identifies code pattern issues
  3. Snyk analyzes dependency risks
// package.json security configuration example
{
  "scripts": {
    "security": "zap-baseline.py -t https://app.com && eslint --plugin security ."
  },
  "dependencies": {
    "helmet": "^7.0.0" // Security middleware
  }
}

Real User Monitoring (RUM) Integration

Collecting production environment anomalies via proxy:

// Frontend error collection
window.addEventListener('error', (e) => {
  fetch('/security-log', {
    method: 'POST',
    body: JSON.stringify({
      type: 'ClientSideError',
      message: e.message,
      stack: e.error.stack,
      timestamp: Date.now()
    })
  });
});

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

如果侵犯了你的权益请来信告知我们删除。邮箱: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 ☕.