SuperAPI AI Directory

secure-code-review

Testing & quality

View repository

Updated 10-15 19:53

About this skill

Secure Code Review

Overview

Secure code review is an important method for identifying security vulnerabilities in code. This skill provides methods, tools, and best practices for secure code review.

Review Scope

1. Input Validation

Check items:

  • User input validation
  • Parameter validation
  • Data filtering
  • Boundary checking

2. Output Encoding

Check items:

  • XSS protection
  • Output encoding
  • Content Security Policy
  • Response header settings

3. Authentication and Authorization

Check items:

  • Authentication mechanisms
  • Session management
  • Access control
  • Password handling

4. Encryption and Keys

Check items:

  • Data encryption
  • Key management
  • Hash algorithms
  • Random number generation

Review Methods

1. Static Analysis

Use SAST tools:

# SonarQube
sonar-scanner

# Checkmarx
# 使用Web界面

# Fortify
sourceanalyzer -b project build.sh
sourceanalyzer -b project -scan

# Semgrep
semgrep --config=auto .

2. Manual Review

Review checklist:

  • Input validation
  • Output encoding
  • SQL injection
  • XSS vulnerabilities
  • Authentication and authorization
  • Encryption usage
  • Error handling
  • Logging

3. Code Pattern Recognition

Dangerous functions:

# Python危险函数
eval()
exec()
pickle.loads()
os.system()
subprocess.call()
// Java危险函数
Runtime.exec()
ProcessBuilder()
Class.forName()
// PHP危险函数
eval()
exec()
system()
passthru()

Common Vulnerability Patterns

SQL Injection

Dangerous code:

String query = "SELECT * FROM users WHERE id = " + userId;
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query);

Secure code:

String query = "SELECT * FROM users WHERE id = ?";
PreparedStatement stmt = connection.prepareStatement(query);
stmt.setInt(1, userId);
ResultSet rs = stmt.executeQuery();

XSS Vulnerabilities

Dangerous code:

document.innerHTML = userInput;
element.innerHTML = "<div>" + userInput + "</div>";

Secure code:

element.textContent = userInput;
element.setAttribute("data-value", userInput);
// 或使用编码库
element.innerHTML = escapeHtml(userInput);

Command Injection

Dangerous code:

import os
os.system("ping " + user_input)

Secure code:

import subprocess
subprocess.run(["ping", "-c", "1", validated_input])

Path Traversal

Dangerous code:

String filePath = "/uploads/" + fileName;
File file = new File(filePath);

Secure code:

String basePath = "/uploads/";
String fileName = Paths.get(fileName).getFileName().toString();
String filePath = basePath + fileName;
File file = new File(filePath);
if (!file.getCanonicalPath().startsWith(basePath)) {
    throw new SecurityException("Invalid path");
}

Hardcoded Keys

Dangerous code:

String apiKey = "1234567890abcdef";
String password = "admin123";

Secure code:

String apiKey = System.getenv("API_KEY");
String password = keyStore.getPassword("db_password");

Tool Usage

SonarQube

# 启动SonarQube
docker run -d -p 9000:9000 sonarqube

# 运行扫描
sonar-scanner \
  -Dsonar.projectKey=myproject \
  -Dsonar.sources=. \
  -Dsonar.host.url=http://localhost:9000

Semgrep

# 安装
pip install semgrep

# 运行扫描
semgrep --config=auto .

# 使用规则
semgrep --config=p/security-audit .

CodeQL

# 创建数据库
codeql database create database --language=java --source-root=.

# 运行查询
codeql database analyze database security-and-quality.qls --format=sarif-latest

Review Checklist

Input Validation

  • All user input is validated
  • Use whitelist validation
  • Validate data types and ranges
  • Handle special characters

Output Encoding

  • HTML output encoding
  • URL encoding
  • JavaScript encoding
  • SQL parameterization

Authentication and Authorization

  • Strong password policy
  • Secure session management
  • Permission verification
  • Multi-factor authentication

Encryption

  • Use strong encryption algorithms
  • Secure key storage
  • Transport encryption
  • Storage encryption

Error Handling

  • Do not leak sensitive information
  • Unified error responses
  • Log errors
  • Exception handling

Best Practices

1. Secure Coding Standards

  • Follow OWASP Top 10
  • Use secure coding guidelines
  • Code review process
  • Security training

2. Automation Tools

  • Integrate SAST tools
  • CI/CD security checks
  • Automated scanning
  • Result analysis

3. Code review process

  • Peer review
  • Security expert review
  • Regular review
  • Record issues

Considerations

  • Combine tools and manual review
  • Focus on business logic vulnerabilities
  • Regularly update tool rules
  • Build a secure coding culture