| name | implementing-api-security-posture-management |
| description | 实施API安全态势管理,持续发现、分类并基于风险对API评分,同时在API生命周期中强制执行安全策略。
|
| domain | cybersecurity |
| subdomain | api-security |
| tags | ["api-security","aspm","api-posture-management","api-discovery","risk-scoring","api-governance","continuous-monitoring","api-inventory"] |
| version | 1.0 |
| author | mahipal |
| license | Apache-2.0 |
实施API安全态势管理
概述
API安全态势管理(API Security Posture Management,API-SPM)通过自动发现、分类和风险评分组织内所有API(包括内部、外部、合作伙伴和影子端点),持续监控API攻击面。与点时间测试工具不同,API-SPM持续运行,检测配置漂移(Configuration Drift)、策略违规、缺失安全控制、敏感数据暴露和合规差距。它从DAST、SAST、SCA和运行时监控工具聚合发现结果,提供整个组织API风险态势的统一视图。
前置条件
- 带流量日志的API网关(Kong、AWS API Gateway、Apigee、Envoy)
- 已记录API的OpenAPI规范
- SIEM或日志聚合平台(Splunk、Elastic)
- CI/CD流水线访问权限(安全左移集成)
- 用于基础设施发现的云提供商API
- Python 3.8+(自定义态势评估工具)
核心组件
1. API发现与清单管理
"""API安全态势管理引擎
持续发现、分类和风险评分API,
以维护全面的安全态势清单。
"""
import json
import re
import hashlib
from datetime import datetime, timedelta
from typing import Dict, List, Optional, Set
from dataclasses import dataclass, field
from enum import Enum
class APIClassification(Enum):
EXTERNAL = "external"
INTERNAL = "internal"
PARTNER = "partner"
SHADOW = "shadow"
DEPRECATED = "deprecated"
class RiskLevel(Enum):
CRITICAL = 4
HIGH = 3
MEDIUM = 2
LOW = 1
INFO = 0
@dataclass
class SecurityControl:
name: str
present: bool
required: bool
severity: RiskLevel
details: str =
:
api_id:
method:
path:
service_name:
classification: APIClassification
owner: [] =
version: [] =
first_discovered: =
last_seen: =
documented: =
security_controls: [SecurityControl] = field(default_factory=)
risk_score: =
sensitive_data_types: [] = field(default_factory=)
compliance_tags: [] = field(default_factory=)
traffic_volume_daily: =
:
SENSITIVE_PATTERNS = {
: re.(),
: re.(),
: re.(),
: re.(),
: re.(),
: re.(),
}
():
.inventory: [, APIEndpoint] = {}
.policy_rules: [] = []
() -> :
raw =
hashlib.sha256(raw.encode()).hexdigest()[:]
() -> APIEndpoint:
api_id = .generate_api_id(method, path, service_name)
now = datetime.now().isoformat()
api_id .inventory:
endpoint = .inventory[api_id]
endpoint.last_seen = now
endpoint
endpoint = APIEndpoint(
api_id=api_id,
method=method,
path=path,
service_name=service_name,
classification=classification,
owner=owner,
first_discovered=now,
last_seen=now,
documented=documented
)
.inventory[api_id] = endpoint
endpoint
() -> [SecurityControl]:
controls = []
has_auth = (h traffic_sample.get(, {})
h [, , ])
controls.append(SecurityControl(
name=,
present=has_auth,
required=,
severity=RiskLevel.CRITICAL,
details= has_auth
))
is_https = traffic_sample.get(, ).lower() ==
controls.append(SecurityControl(
name=,
present=is_https,
required=,
severity=RiskLevel.CRITICAL,
details= is_https
))
has_rate_limit = (h.startswith() h ==
h traffic_sample.get(, {}).keys())
controls.append(SecurityControl(
name=,
present=has_rate_limit,
required=,
severity=RiskLevel.HIGH,
details= has_rate_limit
))
cors_origin = traffic_sample.get(, {}).get(, )
has_strict_cors = cors_origin cors_origin !=
controls.append(SecurityControl(
name=,
present=has_strict_cors,
required=endpoint.classification == APIClassification.EXTERNAL,
severity=RiskLevel.HIGH cors_origin == RiskLevel.MEDIUM,
details= cors_origin
))
sec_headers = traffic_sample.get(, {})
required_headers = {
: ,
: ,
: ,
: ,
}
missing = [h h required_headers h sec_headers]
controls.append(SecurityControl(
name=,
present=(missing) == ,
required=,
severity=RiskLevel.MEDIUM,
details= missing
))
has_validation = traffic_sample.get(, )
controls.append(SecurityControl(
name=,
present=has_validation,
required=,
severity=RiskLevel.HIGH,
details= has_validation
))
endpoint.security_controls = controls
controls
() -> :
score =
max_score =
control endpoint.security_controls:
weight = control.severity.value *
max_score += weight
control.present control.required:
score += weight
classification_weights = {
APIClassification.EXTERNAL: ,
APIClassification.PARTNER: ,
APIClassification.SHADOW: ,
APIClassification.DEPRECATED: ,
APIClassification.INTERNAL: ,
}
multiplier = classification_weights.get(endpoint.classification, )
endpoint.documented:
score +=
score += (endpoint.sensitive_data_types) *
max_score > :
normalized = (, (score / max_score) * * multiplier)
:
normalized =
endpoint.risk_score = (normalized, )
endpoint.risk_score
() -> :
total = (.inventory)
total == :
{: }
risk_distribution = {level.name: level RiskLevel}
classification_counts = {c.value: c APIClassification}
undocumented =
missing_auth =
missing_tls =
endpoint .inventory.values():
.calculate_risk_score(endpoint)
endpoint.risk_score >= :
risk_distribution[] +=
endpoint.risk_score >= :
risk_distribution[] +=
endpoint.risk_score >= :
risk_distribution[] +=
:
risk_distribution[] +=
classification_counts[endpoint.classification.value] +=
endpoint.documented:
undocumented +=
control endpoint.security_controls:
control.name == control.present:
missing_auth +=
control.name == control.present:
missing_tls +=
avg_risk = (e.risk_score e .inventory.values()) / total
{
: datetime.now().isoformat(),
: total,
: (avg_risk, ),
: risk_distribution,
: classification_counts,
: undocumented,
: missing_auth,
: missing_tls,
: (
[{: e.api_id, : e.method, : e.path,
: e.service_name, : e.risk_score,
: e.classification.value}
e .inventory.values()],
key= x: x[],
reverse=
)[:]
}
2. 策略执行
在所有API中定义并强制执行安全策略:
policies:
- name: require-authentication
description: 所有外部API必须要求认证
scope:
classification: [external, partner]
rule:
control: authentication
required: true
severity: critical
remediation: "添加OAuth2、API密钥或JWT认证"
- name: enforce-tls
description: 所有API必须使用HTTPS
scope:
classification: [external, internal, partner]
rule:
control: transport_encryption
required: true
severity: critical
remediation: "配置TLS证书并将HTTP重定向到HTTPS"
- name: require-rate-limiting
description: 外部API必须实施速率限制
scope:
classification: [external]
rule:
control: rate_limiting
required: true
severity:
[]
[, ]
[]
持续监控仪表盘指标
| 指标 | 描述 | 目标 |
|---|
| API发现覆盖率 | 有文档的API占比 | > 95% |
| 平均风险分数 | 所有API的平均风险分数 | < 25 |
| 严重发现数 | 严重风险API数量 | 0 |
| 影子API数量 | 未记录/未管理的API | 0 |
| 认证覆盖率 | 有认证控制的API占比 | 100% |
| TLS覆盖率 | 使用HTTPS的API占比 | 100% |
| 策略合规率 | 符合所有策略的API占比 | > 90% |
| 平均修复时间 | 修复发现问题的平均天数 | < 7天 |
参考资料