ARTICLE DETAIL

资讯详情

深耕网站建设、视觉设计与SEO优化的一线实战洞察。

Checkov OpenAPI 安全策略索引与实现解析:22 条内置规则从源码到实战

Checkov OpenAPI 安全策略索引与实现解析:22 条内置规则从源码到实战 Checkov OpenAPI 安全策略索引与实现解析22 条内置规则从源码到实战【免费下载链接】checkovPrevent cloud misconfigurations and find vulnerabilities during build-time in infrastructure as code, container images and open source packages with Checkov by Bridgecrew.项目地址: https://gitcode.com/GitHub_Trending/ch/checkov本文以 OpenAPI 策略索引openapi.md为核心系统讲解 Checkov 内置的 22 条 OpenAPISwagger规范安全扫描规则CKV_OPENAPI_1 ~ CKV_OPENAPI_21。你将了解到这些规则按 OpenAPI 2.0 / 3.x / 通用generic三类的划分方式、每一条规则检查的具体字段与风险、Checkov 的 OpenAPI Runner 从文件识别到规则执行的完整调用链以及基于仓库测试用例的可复现实战场景。读完本文你可以直接对任意 OpenAPI / Swagger 定义文件执行安全扫描并看懂每一条命中结果的底层判定逻辑。一、OpenAPI 扫描在 Checkov 中的定位Checkov 支持数十种 IaC 与配置文件框架OpenAPISwagger扫描是其 API 安全能力的重要组成部分。在 checkov/openapi/runner.py 中Runner 声明了自身的框架类型与支持的文件扩展名class Runner(YamlRunner, JsonRunner): check_type CheckType.OPENAPI def __init__(self) - None: super().__init__() self.file_extensions [.json, .yml, .yaml]这意味着.json、.yml、.yaml三种格式的 OpenAPI 定义文件都会被纳入扫描且该 Runner 同时复用了 YAML 与 JSON 两套解析能力多重继承自YamlRunner与JsonRunner。在命令行中使用--framework openapi即可单独启用这一框架这一点在 tests/openapi/runner/test_runner.py 中通过RunnerFilter(framework[openapi])得到了验证。二、22 条内置策略完整索引下表完整继承自 openapi.md自动生成并将原来的外部链接转换为仓库内源码路径。其中 Type 统一为resourceIaC 统一为OpenAPIEntity 列表示规则挂载的顶层字段securityDefinitions、security、components、paths、schemesPolicy 列是该规则的一句话判定描述IdTypeEntityPolicyIaCResource LinkCKV_OPENAPI_1resourcesecurityDefinitionsEnsure that securityDefinitions is defined and not empty - version 2.0 filesOpenAPISecurityDefinitions.pyCKV_OPENAPI_2resourcesecurityEnsure that if the security scheme is not of type oauth2, the array value must be empty - version 2.0 filesOpenAPIOauth2SecurityRequirement.pyCKV_OPENAPI_3resourcecomponentsEnsure that security schemes dont allow cleartext credentials over unencrypted channel - version 3.x.y filesOpenAPICleartextOverUnencryptedChannel.pyCKV_OPENAPI_4resourcesecurityEnsure that the global security field has rules definedOpenAPIGlobalSecurityFieldIsEmpty.pyCKV_OPENAPI_5resourcesecurityEnsure that security operations is not empty.OpenAPISecurityOperations.pyCKV_OPENAPI_6resourcesecurityEnsure that security requirement defined in securityDefinitions - version 2.0 filesOpenAPISecurityRequirement.pyCKV_OPENAPI_7resourcesecurityEnsure that the path scheme does not support unencrypted HTTP connection where all transmissions are open to interception- version 2.0 filesOpenAPIPathSchemeDefineHTTP.pyCKV_OPENAPI_8resourcesecurityEnsure that security is not using password flow in OAuth2 authentication - version 2.0 filesOpenAPIOauth2SecurityPasswordFlow.pyCKV_OPENAPI_9resourcepathsEnsure that security scopes of operations are defined in securityDefinitions - version 2.0 filesOpenAPIOperationObjectSecurityScopeUndefined.pyCKV_OPENAPI_10resourcepathsEnsure that operation object does not use password flow in OAuth2 authentication - version 2.0 filesOpenAPIOauth2OperationObjectPasswordFlow.pyCKV_OPENAPI_11resourcesecurityDefinitionsEnsure that operation object does not use password flow in OAuth2 authentication - version 2.0 filesOpenAPIOauth2SecurityDefinitionPasswordFlow.pyCKV_OPENAPI_12resourcesecurityDefinitionsEnsure no security definition is using implicit flow on OAuth2, which is deprecated - version 2.0 filesOpenAPIOauth2SecurityDefinitionImplicitFlow.pyCKV_OPENAPI_13resourcesecurityDefinitionsEnsure security definitions do not use basic auth - version 2.0 filesOpenAPISecurityDefinitionBasicAuth.pyCKV_OPENAPI_14resourcepathsEnsure that operation objects do not use implicit flow, which is deprecated - version 2.0 filesOpenAPIOperationObjectImplicitFlow.pyCKV_OPENAPI_15resourcepathsEnsure that operation objects do not use basic auth - version 2.0 filesOpenAPIOperationObjectBasicAuth.pyCKV_OPENAPI_16resourcepathsEnsure that operation objects have produces field defined for GET operations - version 2.0 filesOpenAPIOperationObjectProducesUndefined.pyCKV_OPENAPI_17resourcepathsEnsure that operation objects have consumes field defined for PUT, POST and PATCH operations - version 2.0 filesOpenAPIOperationObjectConsumesUndefined.pyCKV_OPENAPI_18resourceschemesEnsure that global schemes use https protocol instead of http- version 2.0 filesOpenAPIGlobalSchemeDefineHTTP.pyCKV_OPENAPI_19resourcesecurityEnsure that global security scope is defined in securityDefinitions - version 2.0 filesOpenAPIGlobalSecurityScopeUndefined.pyCKV_OPENAPI_20resourcepathsEnsure that API keys are not sent over cleartextOpenAPIClearTextAPIKey.pyCKV_OPENAPI_21resourcepathsEnsure that arrays have a maximum number of itemsOpenAPINoMaximumNumberItems.py三、规则的三层体系v2、v3 与 generic从源码目录结构看规则被组织为三类对应三个目录resource/v2、resource/v3与resource/generic。这种划分直接决定了规则适用的 OpenAPI 版本3.1 v2 规则Swagger 2.0v2 规则继承自 BaseOpenapiCheckV2其scan_entity_conf实现如下def scan_entity_conf(self, conf, entity_type): if swagger in conf: swagger conf.get(swagger) if isinstance(swagger, str) and swagger 2.0: return self.scan_openapi_conf(conf, entity_type) return CheckResult.UNKNOWN, conf即只有当文档根级存在swagger: 2.0字段时才执行检查否则返回UNKNOWN不产生通过/失败结论。索引中 CKV_OPENAPI_1、2、6、7、8、9、10、11、12、13、14、15、16、17、18、19 共 16 条规则属于此类覆盖了securityDefinitions、全局/操作级security、paths、schemes等 Swagger 2.0 的核心字段。3.2 v3 规则OpenAPI 3.xv3 规则继承自 BaseOpenapiCheckV3判定条件为文档根级存在openapi字段且其值以3.开头if openapi in conf: openapi conf.get(openapi) if isinstance(openapi, str) and openapi.startswith(3.): return self.scan_openapi_conf(conf, entity_type)由于 OpenAPI 3.x 将安全方案移入components.securitySchemesv3 规则主要围绕components展开。索引中 CKV_OPENAPI_3 属于此类。3.3 generic 规则跨版本通用generic 规则直接继承 BaseOpenapiCheck不校验版本字段对 v2 与 v3 文档一视同仁。CKV_OPENAPI_4、5、20、21 属于此类分别检查全局安全规则缺失、安全操作为空、API Key 明文传输、数组缺少maxItems上限。四、Runner 运行机制从文件识别到规则执行要理解这 22 条规则如何被触发需要看清 checkov/openapi/runner.py 的完整调用链主要有三个关键环节1. 预过滤pre_validate_file在真正解析前先做一次轻量字符串匹配命中swagger或openapi关键字才继续staticmethod def pre_validate_file(file_content: str) - bool: openapi_keywords [swagger, openapi] match any(keyword in file_content for keyword in openapi_keywords) return matchtests/openapi/runner/test_runner.py 中test_pre_validate_non_openapi_file与test_pre_validate_openapi_yaml_file分别验证了非 OpenAPI 文件被过滤和含openapi: 3.0.0的 YAML 通过预检两种情形。2. 结构校验is_valid按规范要求v2.0 必须含swagger字段、v3 必须含openapi字段且两者都必须有info对象staticmethod def is_valid(conf) - bool: try: return bool( conf and isinstance(conf, dict) and (swagger in conf or openapi in conf) and isinstance(conf[info], dict) ) except Exception: return False3. 按扩展名分流解析_parse_file依据文件扩展名选择解析器.json走JsonRunner._parse_file.yml/.yaml走YamlRunner._parse_file其他扩展名直接跳过。规则本身通过BaseOpenapiCheck.__init__在构造时即自动注册到 openapi_registry注册表的get_key以文件路径.实体名.检查ID三元组作为去重键见 base_registry.py。所有规则均以BlockType.DOCUMENT粒度挂载即每条规则面对的是整个文档对象再在各自scan_*_conf中自行遍历目标字段。五、代表性规则源码级解析以下选取索引中五条最具代表性的规则结合源码与测试样例拆解判定逻辑。5.1 CKV_OPENAPI_1securityDefinitions 必须定义且非空v2SecurityDefinitions.py 的判定逻辑def scan_openapi_conf(self, conf, entity_type): self.evaluated_keys [securityDefinitions] if securityDefinitions not in conf: return CheckResult.FAILED, conf security_definitions conf[securityDefinitions] if not security_definitions or (not isinstance(security_definitions, DictNode) and len(security_definitions) 2): return CheckResult.FAILED, security_definitions return CheckResult.PASSED, security_definitions要点securityDefinitions字段缺失即失败存在但为空、或长度不超过 2考虑到__startline__/__endline__两个行号辅助键后的实际业务键为空同样失败。这是 Swagger 2.0 认证体系的地基——没有它所有security引用都将悬空。5.2 CKV_OPENAPI_3禁止明文凭据走非加密通道v3CleartextOverUnencryptedChannel.py 从两个维度判定在components.securitySchemes中若存在type: http且scheme: basic的方案直接失败Basic Auth 凭据为明文编码遍历paths下所有操作只要任意操作声明了security即失败——在作者视角下声明了安全需求却仍依赖明文通道是自相矛盾的。对应的失败样例可见 fail.yaml通过样例 pass.yaml 则使用type: oauth2的加密方案。5.3 CKV_OPENAPI_18全局 schemes 必须使用 HTTPSv2GlobalSchemeDefineHTTP.py 逻辑非常清晰schemes conf.get(schemes, []) if not schemes: # 若未声明 schemes默认采用访问该 Swagger 定义自身所用的协议此时规则不适用 return CheckResult.UNKNOWN, conf if http in schemes: return CheckResult.FAILED, conf return CheckResult.PASSED, conf值得注意的边界处理当顶层schemes完全缺失时返回UNKNOWN而非FAILED因为 Swagger 规范规定此时默认协议是访问文档本身所用的协议无法静态判定。只有显式列出http才判定为失败。5.4 CKV_OPENAPI_20API Key 不得明文传输genericClearTextAPIKey.py 的判定链路较长按顺序执行检查顶层schemes列表若不含http与ws通过检查顶层servers列表若没有任何 URL 以http://或ws://开头通过从components.securitySchemesv3或securityDefinitionsv2中过滤出type: apiKey的方案遍历paths各操作若其security引用了上述任一 apiKey 方案失败——因为 apiKey 通常以 header / cookie / query 形式携带一旦通道为明文即可被截获。测试样例 fail.json 展示了三个apiKey方案分别位于 header、cookie、query被/pets的post操作引用的失败场景。5.5 CKV_OPENAPI_21数组参数必须声明 maxItemsgenericNoMaximumNumberItems.py 采用递归遍历从根配置出发对每一层 dict 检查type array且缺少maxItems的情况一旦发现即失败。这能防御请求参数数组无上限导致的资源耗尽类攻击同时该规则不区分 v2/v3属于典型的通用健壮性检查。5.6 认证方式约束族v2v2 下有多条针对认证方式的约束规则机制高度一致可归为一族理解CKV_OPENAPI_2Oauth2SecurityRequirement.py先从securityDefinitions收集所有非oauth2类型的方案名再检查security中引用这些方案时携带的 scope 数组必须为空CKV_OPENAPI_13 / 15SecurityDefinitionBasicAuth.py、OperationObjectBasicAuth.py分别在securityDefinitions与操作级security层面禁止type: basicCKV_OPENAPI_12 / 14禁止在 securityDefinitions 与 operation 中使用已废弃的 OAuth2implicitflowCKV_OPENAPI_8 / 10 / 11从全局 security、operation 对象、securityDefinitions 三个角度禁止 OAuth2passwordflow密码流程会向客户端暴露明文口令。它们共同构成对 Swagger 2.0 认证设计的完整约束面建议在涉及 v2 存量接口时整体启用。六、使用与验证6.1 命令行扫描对单个 OpenAPI 文件扫描并仅启用 openapi 框架checkov -f openapi.yaml --framework openapi对目录递归扫描自动识别目录下的.json/.yml/.yamlOpenAPI 文件checkov -d ./api_specs --framework openapi完整的 CLI 参数说明可参考 CLI Command Reference。注意预过滤依赖文件内容中出现swagger或openapi关键字因此文件命名不包含这两个词并不影响扫描。6.2 运行结果一致性tests/openapi/runner/test_runner.py 给出了可复现的验证基准对resources目录仅启用CKV_OPENAPI_1、CKV_OPENAPI_4、CKV_OPENAPI_3三条规则期望结果为 12 条失败、6 条通过、0 解析错误、0 跳过同时该测试用 SARIF 报告与预生成结果文件比对保证输出格式的稳定性。每条规则目录下均有独立的pass/fail样例与 pytest 测试如 test_ClearTextAPIKey.py、test_CleartextCredsOverUnencryptedChannel.py可直接作为自定义规则的编写范本。6.3 规则与版本匹配提示运行前请先确认被扫描文件的版本根级声明swagger: 2.0时16 条 v2 规则 4 条 generic 规则会参与评估根级声明openapi: 3.x.y时CKV_OPENAPI_3 4 条 generic 规则参与评估若版本字段缺失文件会被is_valid判定为非法文档而整体跳过不会报解析错误而是不产出检查结果。七、总结Checkov 的 OpenAPI 扫描能力由 22 条内置规则构成按 Swagger 2.016 条、OpenAPI 3.x1 条、跨版本通用4 条三层体系组织并通过 openapi.md 这份自动生成索引对外呈现完整清单。从 runner.py 的关键字预过滤、结构校验到 BaseOpenapiCheckV2 / BaseOpenapiCheckV3 的版本分派再到各策略对securityDefinitions、security、paths、schemes、components的细粒度判定整条链路清晰可循。索引中任何一条规则都能在 checkov/openapi/checks 下找到对应实现并配齐正反测试样例——这正是将策略索引转化为可维护、可审计安全基线的关键路径。【免费下载链接】checkovPrevent cloud misconfigurations and find vulnerabilities during build-time in infrastructure as code, container images and open source packages with Checkov by Bridgecrew.项目地址: https://gitcode.com/GitHub_Trending/ch/checkov创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表