security-practices

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Security Practices Skill

安全实践技能

Level 1: Quick Start (5 minutes)

一级:快速入门(5分钟)

What You'll Learn

你将学到什么

Implement essential security practices to protect applications from common vulnerabilities and attacks.
实施基础安全实践,保护应用程序免受常见漏洞和攻击。

Core Principles

核心原则

  • Zero Trust: Never trust, always verify
  • Defense in Depth: Multiple layers of security controls
  • Shift Left: Integrate security early in development
  • Least Privilege: Grant minimum necessary permissions
  • 零信任(Zero Trust):永不信任,始终验证
  • 纵深防御:多层安全控制
  • 左移安全(Shift Left):在开发早期集成安全
  • 最小权限:授予必要的最小权限

Quick Security Checklist

快速安全检查清单

  • Enable MFA for all user accounts
  • Use HTTPS/TLS 1.3 for all connections
  • Validate and sanitize all inputs
  • Never commit secrets to version control
  • Run dependency vulnerability scans
  • Implement proper error handling (no sensitive info in errors)
  • 为所有用户账户启用MFA
  • 为所有连接使用HTTPS/TLS 1.3
  • 验证并清理所有输入
  • 切勿将敏感信息提交到版本控制系统
  • 运行依赖项漏洞扫描
  • 实施适当的错误处理(错误信息中不包含敏感内容)

Common Vulnerabilities to Avoid

需要避免的常见漏洞

typescript
// ❌ NEVER: Hardcoded secrets
const API_KEY = "sk_live_abc123";

// ✅ ALWAYS: Use environment variables
const API_KEY = process.env.API_KEY;

// ❌ NEVER: SQL injection vulnerability
const query = `SELECT * FROM users WHERE id = ${userId}`;

// ✅ ALWAYS: Parameterized queries
const query = "SELECT * FROM users WHERE id = ?";
db.query(query, [userId]);

// ❌ NEVER: Weak password validation
if (password.length >= 6) { /* valid */ }

// ✅ ALWAYS: Strong password requirements
if (
  password.length >= 12 &&
  /[A-Z]/.test(password) &&
  /[a-z]/.test(password) &&
  /[0-9]/.test(password) &&
  /[^A-Za-z0-9]/.test(password)
) { /* valid */ }
typescript
// ❌ 禁止:硬编码敏感信息
const API_KEY = "sk_live_abc123";

// ✅ 推荐:使用环境变量
const API_KEY = process.env.API_KEY;

// ❌ 禁止:存在SQL注入漏洞
const query = `SELECT * FROM users WHERE id = ${userId}`;

// ✅ 推荐:使用参数化查询
const query = "SELECT * FROM users WHERE id = ?";
db.query(query, [userId]);

// ❌ 禁止:弱密码验证
if (password.length >= 6) { /* 验证通过 */ }

// ✅ 推荐:强密码要求
if (
  password.length >= 12 &&
  /[A-Z]/.test(password) &&
  /[a-z]/.test(password) &&
  /[0-9]/.test(password) &&
  /[^A-Za-z0-9]/.test(password)
) { /* 验证通过 */ }

Critical Security Tools

关键安全工具

  • Secrets Management: HashiCorp Vault, AWS Secrets Manager
  • Dependency Scanning: Snyk, Dependabot, npm audit
  • SAST: SonarQube, Semgrep, CodeQL
  • DAST: OWASP ZAP, Burp Suite

  • 敏感信息管理:HashiCorp Vault, AWS Secrets Manager
  • 依赖项扫描:Snyk, Dependabot, npm audit
  • 静态应用安全测试(SAST):SonarQube, Semgrep, CodeQL
  • 动态应用安全测试(DAST):OWASP ZAP, Burp Suite

Level 2: Implementation (30 minutes)

二级:实践实施(30分钟)

Deep Dive Topics

深入主题

1. Zero Trust Architecture

1. 零信任架构(Zero Trust Architecture)

Core Components:
typescript
// Identity verification with MFA
interface AuthenticationService {
  // Primary authentication
  verifyCredentials(username: string, password: string): Promise<Session>;

  // Multi-factor authentication
  verifyMfaToken(sessionId: string, token: string): Promise<boolean>;

  // Continuous authentication
  verifySessionValidity(sessionId: string): Promise<boolean>;
}

// Policy engine for access decisions
class PolicyEngine {
  async evaluateAccess(
    user: User,
    resource: Resource,
    context: Context
  ): Promise<AccessDecision> {
    const riskScore = await this.calculateRiskScore(user, context);
    const policy = await this.getApplicablePolicy(user, resource);

    return {
      allowed: this.checkPermissions(user, resource, policy),
      requiresStepUp: riskScore > RISK_THRESHOLD,
      auditRequired: true,
    };
  }

  private async calculateRiskScore(
    user: User,
    context: Context
  ): Promise<number> {
    let risk = 0;
    if (context.location !== user.knownLocations) risk += 30;
    if (context.device !== user.knownDevices) risk += 20;
    if (context.timeOfDay < 6 || context.timeOfDay > 22) risk += 10;
    return risk;
  }
}
NIST Mapping:
  • @nist-controls: [ac-2, ac-3, ac-6, ia-2, ia-5, au-2, sc-8]
核心组件:
typescript
// 带MFA的身份验证
interface AuthenticationService {
  // 主身份验证
  verifyCredentials(username: string, password: string): Promise<Session>;

  // 多因素验证
  verifyMfaToken(sessionId: string, token: string): Promise<boolean>;

  // 持续身份验证
  verifySessionValidity(sessionId: string): Promise<boolean>;
}

// 用于访问决策的策略引擎
class PolicyEngine {
  async evaluateAccess(
    user: User,
    resource: Resource,
    context: Context
  ): Promise<AccessDecision> {
    const riskScore = await this.calculateRiskScore(user, context);
    const policy = await this.getApplicablePolicy(user, resource);

    return {
      allowed: this.checkPermissions(user, resource, policy),
      requiresStepUp: riskScore > RISK_THRESHOLD,
      auditRequired: true,
    };
  }

  private async calculateRiskScore(
    user: User,
    context: Context
  ): Promise<number> {
    let risk = 0;
    if (context.location !== user.knownLocations) risk += 30;
    if (context.device !== user.knownDevices) risk += 20;
    if (context.timeOfDay < 6 || context.timeOfDay > 22) risk += 10;
    return risk;
  }
}
NIST映射:
  • @nist-controls: [ac-2, ac-3, ac-6, ia-2, ia-5, au-2, sc-8]

2. Supply Chain Security

2. 供应链安全

yaml
undefined
yaml
undefined

.github/workflows/supply-chain-security.yml

.github/workflows/supply-chain-security.yml

name: Supply Chain Security
on: [push, pull_request]
jobs: dependency-scan: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3
  # Dependency vulnerability scanning
  - name: Run Snyk
    uses: snyk/actions/node@master
    env:
      SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}
    with:
      args: --severity-threshold=high

  # SBOM generation
  - name: Generate SBOM
    run: |
      npm install -g @cyclonedx/cyclonedx-npm
      cyclonedx-npm --output-file sbom.json

  # License compliance
  - name: Check Licenses
    run: |
      npm install -g license-checker
      license-checker --production --failOn "GPL;AGPL"

**SBOM Implementation:**

```typescript
// Generate Software Bill of Materials
interface SBOMEntry {
  name: string;
  version: string;
  license: string;
  supplier: string;
  checksum: string;
  vulnerabilities: Vulnerability[];
}

async function generateSBOM(): Promise<SBOM> {
  const dependencies = await analyzeDependencies();
  const vulnerabilities = await scanVulnerabilities(dependencies);

  return {
    components: dependencies.map((dep) => ({
      name: dep.name,
      version: dep.version,
      license: dep.license,
      checksum: calculateChecksum(dep),
      vulnerabilities: vulnerabilities.filter((v) => v.package === dep.name),
    })),
    metadata: {
      timestamp: new Date().toISOString(),
      toolVersion: "1.0.0",
    },
  };
}
NIST Mapping:
  • @nist-controls: [sa-10, sr-3, sr-4, sr-6, sr-11]
name: Supply Chain Security
on: [push, pull_request]
jobs: dependency-scan: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3
  # 依赖项漏洞扫描
  - name: Run Snyk
    uses: snyk/actions/node@master
    env:
      SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}
    with:
      args: --severity-threshold=high

  # SBOM生成
  - name: Generate SBOM
    run: |
      npm install -g @cyclonedx/cyclonedx-npm
      cyclonedx-npm --output-file sbom.json

  # 许可证合规性检查
  - name: Check Licenses
    run: |
      npm install -g license-checker
      license-checker --production --failOn "GPL;AGPL"

**SBOM实施:**

```typescript
// 生成软件物料清单(SBOM)
interface SBOMEntry {
  name: string;
  version: string;
  license: string;
  supplier: string;
  checksum: string;
  vulnerabilities: Vulnerability[];
}

async function generateSBOM(): Promise<SBOM> {
  const dependencies = await analyzeDependencies();
  const vulnerabilities = await scanVulnerabilities(dependencies);

  return {
    components: dependencies.map((dep) => ({
      name: dep.name,
      version: dep.version,
      license: dep.license,
      checksum: calculateChecksum(dep),
      vulnerabilities: vulnerabilities.filter((v) => v.package === dep.name),
    })),
    metadata: {
      timestamp: new Date().toISOString(),
      toolVersion: "1.0.0",
    },
  };
}
NIST映射:
  • @nist-controls: [sa-10, sr-3, sr-4, sr-6, sr-11]

3. Container Security

3. 容器安全

dockerfile
undefined
dockerfile
undefined

Secure Dockerfile example

安全Dockerfile示例

FROM node:20-alpine AS base
FROM node:20-alpine AS base

Security: Run as non-root user

安全:以非root用户运行

RUN addgroup -g 1001 -S nodejs &&
adduser -S nodejs -u 1001
RUN addgroup -g 1001 -S nodejs &&
adduser -S nodejs -u 1001

Security: Minimal base image, scan for vulnerabilities

安全:使用最小基础镜像,扫描漏洞

FROM base AS dependencies WORKDIR /app COPY package*.json ./ RUN npm ci --only=production &&
npm cache clean --force
FROM base AS builder WORKDIR /app COPY . . RUN npm ci && npm run build
FROM base AS runner WORKDIR /app
FROM base AS dependencies WORKDIR /app COPY package*.json ./ RUN npm ci --only=production &&
npm cache clean --force
FROM base AS builder WORKDIR /app COPY . . RUN npm ci && npm run build
FROM base AS runner WORKDIR /app

Security: Copy only necessary files

安全:仅复制必要文件

COPY --from=dependencies --chown=nodejs:nodejs /app/node_modules ./node_modules COPY --from=builder --chown=nodejs:nodejs /app/dist ./dist
COPY --from=dependencies --chown=nodejs:nodejs /app/node_modules ./node_modules COPY --from=builder --chown=nodejs:nodejs /app/dist ./dist

Security: Switch to non-root user

安全:切换到非root用户

USER nodejs
USER nodejs

Security: Expose only necessary port

安全:仅暴露必要端口

EXPOSE 3000
EXPOSE 3000

Security: Use exec form for better signal handling

安全:使用exec格式以获得更好的信号处理

CMD ["node", "dist/index.js"]

**Kubernetes Security:**

```yaml
CMD ["node", "dist/index.js"]

**Kubernetes安全:**

```yaml

pod-security-policy.yaml

pod-security-policy.yaml

apiVersion: policy/v1beta1 kind: PodSecurityPolicy metadata: name: restricted spec: privileged: false # Prevent privileged containers allowPrivilegeEscalation: false requiredDropCapabilities: - ALL volumes: - "configMap" - "secret" - "persistentVolumeClaim" hostNetwork: false hostIPC: false hostPID: false runAsUser: rule: "MustRunAsNonRoot" seLinux: rule: "RunAsAny" supplementalGroups: rule: "RunAsAny" fsGroup: rule: "RunAsAny" readOnlyRootFilesystem: true

**NIST Mapping:**

- @nist-controls: [cm-2, cm-3, cm-7, si-7]
apiVersion: policy/v1beta1 kind: PodSecurityPolicy metadata: name: restricted spec: privileged: false # 禁止特权容器 allowPrivilegeEscalation: false requiredDropCapabilities: - ALL volumes: - "configMap" - "secret" - "persistentVolumeClaim" hostNetwork: false hostIPC: false hostPID: false runAsUser: rule: "MustRunAsNonRoot" seLinux: rule: "RunAsAny" supplementalGroups: rule: "RunAsAny" fsGroup: rule: "RunAsAny" readOnlyRootFilesystem: true

**NIST映射:**

- @nist-controls: [cm-2, cm-3, cm-7, si-7]

4. API Security

4. API安全

typescript
// Rate limiting
import rateLimit from "express-rate-limit";

const apiLimiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 100, // Limit each IP to 100 requests per windowMs
  message: "Too many requests from this IP",
  standardHeaders: true,
  legacyHeaders: false,
});

// Input validation with sanitization
import { z } from "zod";
import sanitizeHtml from "sanitize-html";

const CreateUserSchema = z.object({
  email: z.string().email().max(255),
  password: z.string().min(12).max(128),
  name: z
    .string()
    .min(1)
    .max(100)
    .transform((val) => sanitizeHtml(val, { allowedTags: [] })),
});

// Authentication middleware
async function authenticate(
  req: Request,
  res: Response,
  next: NextFunction
) {
  try {
    const token = req.headers.authorization?.split(" ")[1];
    if (!token) {
      throw new UnauthorizedError("No token provided");
    }

    const decoded = await verifyJWT(token);
    const session = await validateSession(decoded.sessionId);

    if (!session.valid) {
      throw new UnauthorizedError("Invalid session");
    }

    req.user = decoded;
    next();
  } catch (error) {
    // @nist au-2 "Audit authentication failures"
    await auditLog.record("auth.failure", {
      ip: req.ip,
      path: req.path,
      error: error.message,
    });
    res.status(401).json({ error: "Unauthorized" });
  }
}

// CORS configuration
const corsOptions = {
  origin: (origin: string, callback: Function) => {
    const allowedOrigins = process.env.ALLOWED_ORIGINS?.split(",") || [];
    if (!origin || allowedOrigins.includes(origin)) {
      callback(null, true);
    } else {
      callback(new Error("Not allowed by CORS"));
    }
  },
  credentials: true,
  maxAge: 86400,
};
NIST Mapping:
  • @nist-controls: [ac-2, ac-3, ia-2, sc-8, si-10]
typescript
// 速率限制
import rateLimit from "express-rate-limit";

const apiLimiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15分钟
  max: 100, // 限制每个IP在窗口时间内最多100次请求
  message: "来自该IP的请求过多",
  standardHeaders: true,
  legacyHeaders: false,
});

// 带清理的输入验证
import { z } from "zod";
import sanitizeHtml from "sanitize-html";

const CreateUserSchema = z.object({
  email: z.string().email().max(255),
  password: z.string().min(12).max(128),
  name: z
    .string()
    .min(1)
    .max(100)
    .transform((val) => sanitizeHtml(val, { allowedTags: [] })),
});

// 身份验证中间件
async function authenticate(
  req: Request,
  res: Response,
  next: NextFunction
) {
  try {
    const token = req.headers.authorization?.split(" ")[1];
    if (!token) {
      throw new UnauthorizedError("未提供令牌");
    }

    const decoded = await verifyJWT(token);
    const session = await validateSession(decoded.sessionId);

    if (!session.valid) {
      throw new UnauthorizedError("无效会话");
    }

    req.user = decoded;
    next();
  } catch (error) {
    // @nist au-2 "审计身份验证失败"
    await auditLog.record("auth.failure", {
      ip: req.ip,
      path: req.path,
      error: error.message,
    });
    res.status(401).json({ error: "未授权" });
  }
}

// CORS配置
const corsOptions = {
  origin: (origin: string, callback: Function) => {
    const allowedOrigins = process.env.ALLOWED_ORIGINS?.split(",") || [];
    if (!origin || allowedOrigins.includes(origin)) {
      callback(null, true);
    } else {
      callback(new Error("CORS不允许"));
    }
  },
  credentials: true,
  maxAge: 86400,
};
NIST映射:
  • @nist-controls: [ac-2, ac-3, ia-2, sc-8, si-10]

5. DevSecOps Integration

5. DevSecOps集成

yaml
undefined
yaml
undefined

.github/workflows/security-pipeline.yml

.github/workflows/security-pipeline.yml

name: Security Pipeline
on: push: branches: [main, develop] pull_request: branches: [main]
jobs: security-scan: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3
  # Secret scanning
  - name: TruffleHog Secret Scan
    uses: trufflesecurity/trufflehog@main
    with:
      path: ./
      base: ${{ github.event.repository.default_branch }}
      head: HEAD

  # Static Application Security Testing (SAST)
  - name: Run Semgrep
    uses: returntocorp/semgrep-action@v1
    with:
      config: >-
        p/security-audit
        p/owasp-top-ten
        p/cwe-top-25

  # Dependency scanning
  - name: Run Snyk
    uses: snyk/actions/node@master
    env:
      SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}

  # Container scanning
  - name: Trivy Container Scan
    uses: aquasecurity/trivy-action@master
    with:
      image-ref: "myapp:${{ github.sha }}"
      format: "sarif"
      output: "trivy-results.sarif"

  # Upload results to GitHub Security
  - name: Upload SARIF
    uses: github/codeql-action/upload-sarif@v2
    with:
      sarif_file: trivy-results.sarif

Security gate: block on high/critical vulnerabilities

security-gate: needs: security-scan runs-on: ubuntu-latest steps: - name: Check Security Results run: | if [ "${{ needs.security-scan.result }}" != "success" ]; then echo "Security scan failed - blocking deployment" exit 1 fi
undefined
name: Security Pipeline
on: push: branches: [main, develop] pull_request: branches: [main]
jobs: security-scan: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3
  # 敏感信息扫描
  - name: TruffleHog Secret Scan
    uses: trufflesecurity/trufflehog@main
    with:
      path: ./
      base: ${{ github.event.repository.default_branch }}
      head: HEAD

  # 静态应用安全测试(SAST)
  - name: Run Semgrep
    uses: returntocorp/semgrep-action@v1
    with:
      config: >-
        p/security-audit
        p/owasp-top-ten
        p/cwe-top-25

  # 依赖项扫描
  - name: Run Snyk
    uses: snyk/actions/node@master
    env:
      SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}

  # 容器扫描
  - name: Trivy Container Scan
    uses: aquasecurity/trivy-action@master
    with:
      image-ref: "myapp:${{ github.sha }}"
      format: "sarif"
      output: "trivy-results.sarif"

  # 将结果上传到GitHub Security
  - name: Upload SARIF
    uses: github/codeql-action/upload-sarif@v2
    with:
      sarif_file: trivy-results.sarif

安全网关:阻止高/严重级漏洞

security-gate: needs: security-scan runs-on: ubuntu-latest steps: - name: Check Security Results run: | if [ "${{ needs.security-scan.result }}" != "success" ]; then echo "安全扫描失败 - 阻止部署" exit 1 fi
undefined

Integration Points

集成点

  • Links to Coding Standards for secure code patterns
  • Links to Testing Standards for security testing
  • Links to NIST Compliance for control implementation

  • 链接到编码标准以获取安全代码模式
  • 链接到测试标准以获取安全测试内容
  • 链接到NIST合规性以获取控制实施指南

Level 3: Mastery (Extended Learning)

三级:精通(进阶学习)

Advanced Topics

高级主题

1. Incident Response Automation

1. 事件响应自动化

typescript
// Automated incident response workflow
class IncidentResponseOrchestrator {
  async handleSecurityIncident(incident: SecurityIncident): Promise<void> {
    // 1. Immediate containment
    await this.containThreat(incident);

    // 2. Evidence collection
    const evidence = await this.collectEvidence(incident);

    // 3. Analysis and root cause
    const analysis = await this.analyzeIncident(incident, evidence);

    // 4. Remediation
    await this.remediateVulnerability(analysis);

    // 5. Notification
    await this.notifyStakeholders(incident, analysis);

    // 6. Post-incident review
    await this.schedulePostMortem(incident);
  }

  private async containThreat(incident: SecurityIncident): Promise<void> {
    switch (incident.type) {
      case "compromised-credentials":
        await this.revokeAllSessions(incident.userId);
        await this.resetPassword(incident.userId);
        break;
      case "malicious-traffic":
        await this.blockIPAddress(incident.sourceIP);
        break;
      case "data-exfiltration":
        await this.isolateAffectedSystems(incident.systemIds);
        await this.disableExternalConnections();
        break;
    }
  }
}
typescript
// 自动化事件响应工作流
class IncidentResponseOrchestrator {
  async handleSecurityIncident(incident: SecurityIncident): Promise<void> {
    // 1. 立即遏制
    await this.containThreat(incident);

    // 2. 证据收集
    const evidence = await this.collectEvidence(incident);

    // 3. 分析与根本原因
    const analysis = await this.analyzeIncident(incident, evidence);

    // 4. 修复
    await this.remediateVulnerability(analysis);

    // 5. 通知
    await this.notifyStakeholders(incident, analysis);

    // 6. 事后审查
    await this.schedulePostMortem(incident);
  }

  private async containThreat(incident: SecurityIncident): Promise<void> {
    switch (incident.type) {
      case "compromised-credentials":
        await this.revokeAllSessions(incident.userId);
        await this.resetPassword(incident.userId);
        break;
      case "malicious-traffic":
        await this.blockIPAddress(incident.sourceIP);
        break;
      case "data-exfiltration":
        await this.isolateAffectedSystems(incident.systemIds);
        await this.disableExternalConnections();
        break;
    }
  }
}

2. Cryptographic Implementations

2. 加密实现

typescript
// Secure password hashing with Argon2
import argon2 from "argon2";

async function hashPassword(password: string): Promise<string> {
  return argon2.hash(password, {
    type: argon2.argon2id,
    memoryCost: 65536, // 64 MB
    timeCost: 3,
    parallelism: 4,
  });
}

// Secure token generation
import crypto from "crypto";

function generateSecureToken(length: number = 32): string {
  return crypto.randomBytes(length).toString("base64url");
}

// Encryption at rest
import { createCipheriv, createDecipheriv, randomBytes } from "crypto";

class DataEncryption {
  private algorithm = "aes-256-gcm";
  private key: Buffer;

  constructor(secretKey: string) {
    this.key = crypto.scryptSync(secretKey, "salt", 32);
  }

  encrypt(data: string): { encrypted: string; iv: string; tag: string } {
    const iv = randomBytes(16);
    const cipher = createCipheriv(this.algorithm, this.key, iv);

    let encrypted = cipher.update(data, "utf8", "hex");
    encrypted += cipher.final("hex");

    return {
      encrypted,
      iv: iv.toString("hex"),
      tag: cipher.getAuthTag().toString("hex"),
    };
  }

  decrypt(encrypted: string, iv: string, tag: string): string {
    const decipher = createDecipheriv(
      this.algorithm,
      this.key,
      Buffer.from(iv, "hex")
    );
    decipher.setAuthTag(Buffer.from(tag, "hex"));

    let decrypted = decipher.update(encrypted, "hex", "utf8");
    decrypted += decipher.final("utf8");

    return decrypted;
  }
}
typescript
// 使用Argon2进行安全密码哈希
import argon2 from "argon2";

async function hashPassword(password: string): Promise<string> {
  return argon2.hash(password, {
    type: argon2.argon2id,
    memoryCost: 65536, // 64 MB
    timeCost: 3,
    parallelism: 4,
  });
}

// 安全令牌生成
import crypto from "crypto";

function generateSecureToken(length: number = 32): string {
  return crypto.randomBytes(length).toString("base64url");
}

// 静态数据加密
import { createCipheriv, createDecipheriv, randomBytes } from "crypto";

class DataEncryption {
  private algorithm = "aes-256-gcm";
  private key: Buffer;

  constructor(secretKey: string) {
    this.key = crypto.scryptSync(secretKey, "salt", 32);
  }

  encrypt(data: string): { encrypted: string; iv: string; tag: string } {
    const iv = randomBytes(16);
    const cipher = createCipheriv(this.algorithm, this.key, iv);

    let encrypted = cipher.update(data, "utf8", "hex");
    encrypted += cipher.final("hex");

    return {
      encrypted,
      iv: iv.toString("hex"),
      tag: cipher.getAuthTag().toString("hex"),
    };
  }

  decrypt(encrypted: string, iv: string, tag: string): string {
    const decipher = createDecipheriv(
      this.algorithm,
      this.key,
      Buffer.from(iv, "hex")
    );
    decipher.setAuthTag(Buffer.from(tag, "hex"));

    let decrypted = decipher.update(encrypted, "hex", "utf8");
    decrypted += decipher.final("utf8");

    return decrypted;
  }
}

3. Security Monitoring and Alerting

3. 安全监控与告警

typescript
// Real-time security monitoring
class SecurityMonitor {
  private metrics: MetricsCollector;
  private alerting: AlertingService;

  async monitorAuthenticationPatterns(): Promise<void> {
    const recentAttempts = await this.getRecentAuthAttempts();

    // Detect brute force attacks
    const bruteForceAttempts = recentAttempts.filter(
      (attempt) => attempt.failures > 5 && attempt.timeWindow < 60000
    );

    if (bruteForceAttempts.length > 0) {
      await this.alerting.send({
        severity: "high",
        type: "brute-force-detected",
        details: bruteForceAttempts,
      });
    }

    // Detect credential stuffing
    const stuffingIndicators = await this.detectCredentialStuffing(
      recentAttempts
    );
    if (stuffingIndicators.length > 0) {
      await this.alerting.send({
        severity: "critical",
        type: "credential-stuffing",
        details: stuffingIndicators,
      });
    }
  }
}
typescript
// 实时安全监控
class SecurityMonitor {
  private metrics: MetricsCollector;
  private alerting: AlertingService;

  async monitorAuthenticationPatterns(): Promise<void> {
    const recentAttempts = await this.getRecentAuthAttempts();

    // 检测暴力破解攻击
    const bruteForceAttempts = recentAttempts.filter(
      (attempt) => attempt.failures > 5 && attempt.timeWindow < 60000
    );

    if (bruteForceAttempts.length > 0) {
      await this.alerting.send({
        severity: "high",
        type: "brute-force-detected",
        details: bruteForceAttempts,
      });
    }

    // 检测凭证填充攻击
    const stuffingIndicators = await this.detectCredentialStuffing(
      recentAttempts
    );
    if (stuffingIndicators.length > 0) {
      await this.alerting.send({
        severity: "critical",
        type: "credential-stuffing",
        details: stuffingIndicators,
      });
    }
  }
}

Resources

资源

Essential Reading

必读资料

Security Tools

安全工具

  • SAST: Semgrep, CodeQL, SonarQube
  • DAST: OWASP ZAP, Burp Suite
  • Secrets Detection: TruffleHog, GitLeaks, detect-secrets
  • Container Security: Trivy, Clair, Anchore
  • Dependency Scanning: Snyk, Dependabot, WhiteSource
  • SAST:Semgrep, CodeQL, SonarQube
  • DAST:OWASP ZAP, Burp Suite
  • 敏感信息检测:TruffleHog, GitLeaks, detect-secrets
  • 容器安全:Trivy, Clair, Anchore
  • 依赖项扫描:Snyk, Dependabot, WhiteSource

Compliance Frameworks

合规框架

  • NIST 800-53r5
  • ISO 27001
  • SOC 2
  • PCI DSS
  • GDPR
  • NIST 800-53r5
  • ISO 27001
  • SOC 2
  • PCI DSS
  • GDPR

Templates

模板

Security Review Checklist

安全审查清单

markdown
undefined
markdown
undefined

Security Review Checklist

安全审查清单

Authentication & Authorization

身份验证与授权

  • MFA implemented for all user accounts
  • Password requirements meet complexity standards
  • Session management secure (timeout, rotation)
  • RBAC properly implemented
  • 为所有用户账户实施MFA
  • 密码要求符合复杂度标准
  • 会话管理安全(超时、轮换)
  • 正确实施RBAC

Data Protection

数据保护

  • Sensitive data encrypted at rest
  • TLS 1.3 enforced for data in transit
  • PII properly identified and protected
  • Backups encrypted
  • 静态敏感数据已加密
  • 传输数据强制使用TLS 1.3
  • PII已正确识别并保护
  • 备份已加密

Input Validation

输入验证

  • All inputs validated and sanitized
  • SQL injection prevented
  • XSS prevention implemented
  • CSRF tokens in use
  • 所有输入已验证并清理
  • 已防止SQL注入
  • 已实施XSS防护
  • 已使用CSRF令牌

Infrastructure

基础设施

  • Containers run as non-root
  • Network segmentation implemented
  • Security groups properly configured
  • Logging and monitoring enabled
undefined
  • 容器以非root用户运行
  • 已实施网络分段
  • 安全组已正确配置
  • 已启用日志记录与监控
undefined

Scripts

脚本

See
./scripts/
for:
  • Vulnerability scanning automation
  • Secret detection pre-commit hooks
  • SBOM generation scripts
  • Security audit reporters
请查看
./scripts/
获取:
  • 漏洞扫描自动化脚本
  • 敏感信息检测提交前钩子
  • SBOM生成脚本
  • 安全审计报告工具

Examples

示例

Basic Usage

基础用法

python
// TODO: Add basic example for security-practices
// This example demonstrates core functionality
python
// TODO: 添加安全实践的基础示例
// 本示例展示核心功能

Advanced Usage

高级用法

python
// TODO: Add advanced example for security-practices
// This example shows production-ready patterns
python
// TODO: 添加安全实践的高级示例
// 本示例展示生产就绪模式

Integration Example

集成示例

python
// TODO: Add integration example showing how security-practices
// works with other systems and services
See
examples/security-practices/
for complete working examples.
python
// TODO: 添加集成示例,展示安全实践
// 如何与其他系统和服务协作
请查看
examples/security-practices/
获取完整的可运行示例。

Integration Points

集成点

This skill integrates with:
本技能可与以下内容集成:

Upstream Dependencies

上游依赖

  • Tools: Common development tools and frameworks
  • Prerequisites: Basic understanding of general concepts
  • 工具:常见开发工具与框架
  • 前置条件:对通用概念的基本理解

Downstream Consumers

下游使用者

  • Applications: Production systems requiring security-practices functionality
  • CI/CD Pipelines: Automated testing and deployment workflows
  • Monitoring Systems: Observability and logging platforms
  • 应用程序:需要安全实践功能的生产系统
  • CI/CD流水线:自动化测试与部署工作流
  • 监控系统:可观测性与日志平台

Related Skills

相关技能

  • See other skills in this category
  • 查看本分类下的其他技能

Common Integration Patterns

常见集成模式

  1. Development Workflow: How this skill fits into daily development
  2. Production Deployment: Integration with production systems
  3. Monitoring & Alerting: Observability integration points
  1. 开发工作流:本技能如何融入日常开发
  2. 生产部署:与生产系统的集成
  3. 监控与告警:可观测性集成点

Common Pitfalls

常见陷阱

Pitfall 1: Insufficient Testing

陷阱1:测试不足

Problem: Not testing edge cases and error conditions leads to production bugs
Solution: Implement comprehensive test coverage including:
  • Happy path scenarios
  • Error handling and edge cases
  • Integration points with external systems
Prevention: Enforce minimum code coverage (80%+) in CI/CD pipeline
问题:未测试边缘情况和错误条件会导致生产环境漏洞
解决方案:实现全面的测试覆盖,包括:
  • 常规路径场景
  • 错误处理与边缘情况
  • 与外部系统的集成点
预防措施:在CI/CD流水线中强制执行最低代码覆盖率(80%+)

Pitfall 2: Hardcoded Configuration

陷阱2:硬编码配置

Problem: Hardcoding values makes applications inflexible and environment-dependent
Solution: Use environment variables and configuration management:
  • Separate config from code
  • Use environment-specific configuration files
  • Never commit secrets to version control
Prevention: Use tools like dotenv, config validators, and secret scanners
问题:硬编码值会导致应用程序灵活性不足,且依赖环境
解决方案:使用环境变量和配置管理:
  • 将配置与代码分离
  • 使用环境特定的配置文件
  • 切勿将敏感信息提交到版本控制系统
预防措施:使用dotenv、配置验证器和敏感信息扫描工具

Pitfall 3: Ignoring Security Best Practices

陷阱3:忽略安全最佳实践

Problem: Security vulnerabilities from not following established security patterns
Solution: Follow security guidelines:
  • Input validation and sanitization
  • Proper authentication and authorization
  • Encrypted data transmission (TLS/SSL)
  • Regular security audits and updates
Prevention: Use security linters, SAST tools, and regular dependency updates
Best Practices:
  • Follow established patterns and conventions for security-practices
  • Keep dependencies up to date and scan for vulnerabilities
  • Write comprehensive documentation and inline comments
  • Use linting and formatting tools consistently
  • Implement proper error handling and logging
  • Regular code reviews and pair programming
  • Monitor production metrics and set up alerts

问题:不遵循已建立的安全模式会导致安全漏洞
解决方案:遵循安全指南:
  • 输入验证与清理
  • 适当的身份验证与授权
  • 加密数据传输(TLS/SSL)
  • 定期安全审计与更新
预防措施:使用安全检查器、SAST工具和定期依赖项更新
最佳实践
  • 遵循已建立的安全实践模式与规范
  • 保持依赖项最新并扫描漏洞
  • 编写全面的文档和内联注释
  • 持续使用代码检查与格式化工具
  • 实施适当的错误处理与日志记录
  • 定期代码审查与结对编程
  • 监控生产指标并设置告警

Bundled Resources

捆绑资源

  • Full MODERN_SECURITY_STANDARDS.md
  • NIST Implementation Guide
  • Security policy templates in
    ./templates/
  • Automated security scanning scripts in
    ./scripts/
  • Example secure configurations in
    ./resources/
  • 完整的MODERN_SECURITY_STANDARDS.md
  • NIST实施指南
  • ./templates/
    中的安全策略模板
  • ./scripts/
    中的自动化安全扫描脚本
  • ./resources/
    中的示例安全配置