
Auditing Cloud With Cis Benchmarks
- 213 installs
- 27.3k repo stars
- Updated August 2, 2026
- mukul975/anthropic-cybersecurity-skills
Audit and validate their cloud infrastructure against industry-standard security and compliance controls.
About
CIS Benchmarks provide standardized, consensus-driven security guidelines for configuring cloud infrastructure and systems. Solo builders use this skill to audit their cloud environments, validate security configurations, and ensure compliance with industry best practices. This matters because it helps prevent security breaches, ensures regulatory compliance, and reduces the risk of infrastructure misconfigurations that could expose sensitive data or systems.
- Validates cloud security posture against CIS standards
- Identifies compliance gaps and misconfigurations
- Automates security auditing for major cloud providers
Auditing Cloud With Cis Benchmarks by the numbers
- 213 all-time installs (skills.sh)
- +9 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #748 of 2,203 Security skills by installs in the Skillselion catalog
- Security screen: LOW risk (skills.sh audit)
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/mukul975/anthropic-cybersecurity-skills --skill auditing-cloud-with-cis-benchmarksAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 213 |
|---|---|
| repo stars | ★ 27.3k |
| Security audit | 3 / 3 scanners passed |
| Last updated | August 2, 2026 |
| Repository | mukul975/anthropic-cybersecurity-skills ↗ |
What it does
Audit and validate their cloud infrastructure against industry-standard security and compliance controls.
Files
Auditing Cloud with CIS Benchmarks
When to Use
- When performing initial security audits of cloud environments against industry-standard benchmarks
- When preparing for SOC 2, ISO 27001, or regulatory audits that reference CIS controls
- When establishing a measurable security baseline for new cloud accounts or subscriptions
- When tracking compliance improvement over time with periodic reassessment
- When evaluating the security posture of acquired or inherited cloud environments
Do not use for runtime threat detection (see detecting-cloud-threats-with-guardduty), for application-level security testing (see conducting-cloud-penetration-testing), or for compliance frameworks not based on CIS (refer to specific regulatory skill files).
Prerequisites
- Read-only access to target cloud accounts (AWS SecurityAudit policy, Azure Reader role, GCP Viewer role)
- Prowler, ScoutSuite, or cloud-native CSPM tools installed and configured
- Understanding of CIS benchmark structure: sections, controls, profiles (Level 1 and Level 2)
- Remediation access for implementing fixes (separate from audit credentials)
Workflow
Step 1: Select Appropriate CIS Benchmark Version
Choose the correct benchmark version for each cloud provider. Current versions as of 2025 include CIS AWS Foundations Benchmark v5.0, CIS Azure Foundations Benchmark v4.0, and CIS GCP Foundations Benchmark v4.0.
CIS Benchmark Coverage Areas:
+-------------------+-------------------------+------------------------+
| Section | AWS v5.0 | Azure v4.0 |
+-------------------+-------------------------+------------------------+
| Identity & Access | IAM policies, MFA, root | Azure AD, RBAC, PIM |
| Logging | CloudTrail, Config | Activity Log, Diag |
| Monitoring | CloudWatch alarms | Defender, Sentinel |
| Networking | VPC, SG, NACLs | NSG, ASG, Firewall |
| Storage | S3 encryption, access | Storage encryption |
| Database | RDS encryption | SQL TDE, auditing |
+-------------------+-------------------------+------------------------+
CIS Profile Levels:
Level 1: Practical security settings that can be implemented without significant
performance impact or reduced functionality
Level 2: Defense-in-depth settings that may reduce functionality or require
additional planning for implementationStep 2: Run Automated Assessment with Prowler
Execute comprehensive CIS benchmark scans using Prowler for automated control evaluation across AWS, Azure, and GCP.
# AWS CIS v5.0 assessment
prowler aws \
--compliance cis_5.0_aws \
--profile audit-account \
--output-formats json-ocsf,html,csv \
--output-directory ./cis-audit-$(date +%Y%m%d)
# Azure CIS v4.0 assessment
prowler azure \
--compliance cis_4.0_azure \
--subscription-ids "sub-id-1,sub-id-2" \
--output-formats json-ocsf,html,csv \
--output-directory ./cis-audit-azure-$(date +%Y%m%d)
# GCP CIS v4.0 assessment
prowler gcp \
--compliance cis_4.0_gcp \
--project-ids "project-1,project-2" \
--output-formats json-ocsf,html,csv \
--output-directory ./cis-audit-gcp-$(date +%Y%m%d)
# Multi-account AWS scan using ScoutSuite
scout suite aws \
--profile audit-account \
--report-dir ./scout-report \
--ruleset cis-5.0 \
--forceStep 3: Interpret Results and Prioritize Remediation
Analyze audit results by section and severity. Prioritize Level 1 controls first as they represent fundamental security hygiene, then address Level 2 controls for defense in depth.
# Parse Prowler results for failed controls
cat ./cis-audit-*/prowler-output-*.json | \
jq '[.[] | select(.StatusExtended == "FAIL")] | group_by(.CheckID) |
map({control: .[0].CheckID, description: .[0].CheckTitle,
failed_resources: length, severity: .[0].Severity}) |
sort_by(-.failed_resources)'
# Generate compliance score by section
cat ./cis-audit-*/prowler-output-*.json | \
jq 'group_by(.Section) | map({
section: .[0].Section,
total: length,
passed: [.[] | select(.StatusExtended == "PASS")] | length,
failed: [.[] | select(.StatusExtended == "FAIL")] | length,
score: (([.[] | select(.StatusExtended == "PASS")] | length) / length * 100 | round)
})'Step 4: Remediate Critical and High Controls
Address failed controls starting with the highest impact items. Use AWS Config remediation, Azure Policy, or Terraform to apply fixes systematically.
# CIS 1.4: Ensure no root account access key exists
aws iam list-access-keys --user-name root
# If keys exist, delete them
aws iam delete-access-key --user-name root --access-key-id AKIAEXAMPLE
# CIS 2.1.1: Ensure S3 bucket default encryption is enabled
for bucket in $(aws s3api list-buckets --query 'Buckets[*].Name' --output text); do
aws s3api put-bucket-encryption --bucket "$bucket" \
--server-side-encryption-configuration '{
"Rules": [{"ApplyServerSideEncryptionByDefault": {"SSEAlgorithm": "AES256"}}]
}' 2>/dev/null && echo "Encrypted: $bucket" || echo "FAILED: $bucket"
done
# CIS 3.1: Ensure CloudTrail is enabled in all regions
aws cloudtrail create-trail \
--name organization-trail \
--s3-bucket-name cloudtrail-logs-bucket \
--is-multi-region-trail \
--enable-log-file-validation \
--kms-key-id arn:aws:kms:us-east-1:123456789012:key/key-id
aws cloudtrail start-logging --name organization-trail
# CIS 4.x: Configure CloudWatch metric filters and alarms
aws logs put-metric-filter \
--log-group-name CloudTrail/DefaultLogGroup \
--filter-name UnauthorizedAPICalls \
--filter-pattern '{ ($.errorCode = "*UnauthorizedAccess*") || ($.errorCode = "AccessDenied*") }' \
--metric-transformations metricName=UnauthorizedAPICalls,metricNamespace=CISBenchmark,metricValue=1Step 5: Establish Continuous Compliance Monitoring
Deploy automated compliance monitoring to detect configuration drift between periodic audits. Use AWS Security Hub, Azure Policy, or GCP Security Command Center.
# AWS: Enable CIS v5.0 in Security Hub
aws securityhub batch-enable-standards \
--standards-subscription-requests '[
{"StandardsArn": "arn:aws:securityhub:::ruleset/cis-aws-foundations-benchmark/v/5.0.0"}
]'
# Azure: Assign CIS benchmark policy initiative
az policy assignment create \
--name cis-azure-benchmark \
--scope "/subscriptions/<sub-id>" \
--policy-set-definition "1a5bb27d-173f-493e-9568-eb56638dbd0e" \
--params '{"effect": {"value": "AuditIfNotExists"}}'
# Schedule periodic Prowler assessments
# Run weekly via cron or CI/CD pipeline
0 2 * * 1 prowler aws --compliance cis_5.0_aws --output-formats csv --output-directory /opt/audits/weekly-$(date +\%Y\%m\%d)Key Concepts
| Term | Definition |
|---|---|
| CIS Benchmark | Prescriptive security configuration guidelines developed by the Center for Internet Security through community consensus |
| Level 1 Profile | Practical security controls implementable without significant performance or functionality impact, representing security hygiene |
| Level 2 Profile | Defense-in-depth controls that may restrict functionality and require careful planning before implementation |
| Foundations Benchmark | CIS benchmark specifically for cloud providers covering IAM, logging, monitoring, networking, and storage security |
| Control ID | Unique numerical identifier for each CIS recommendation (e.g., 1.4 for root access key checks, 2.1.1 for S3 encryption) |
| Compliance Score | Percentage of CIS controls in a passing state, tracked over time to measure security posture improvement |
| Automated Assessment | Tool-driven evaluation of CIS controls using cloud provider APIs to check resource configurations against benchmark requirements |
| Remediation Runbook | Documented step-by-step procedure for fixing a specific failed CIS control, including pre-checks and validation |
Tools & Systems
- Prowler: Open-source cloud security tool performing 300+ checks including CIS benchmark assessments for AWS, Azure, and GCP
- ScoutSuite: Multi-cloud security auditing tool with CIS benchmark rule sets generating HTML reports
- AWS Security Hub: Native AWS service supporting CIS AWS Foundations Benchmark as a security standard
- Azure Policy: Governance service with built-in CIS benchmark policy initiatives for automated compliance monitoring
- GCP Security Command Center: Native GCP service evaluating configurations against CIS GCP Foundations Benchmark
Common Scenarios
Scenario: Pre-Audit CIS Assessment for SOC 2 Certification
Context: A SaaS company pursuing SOC 2 Type II certification needs to demonstrate cloud security controls aligned to CIS benchmarks. The auditor requires evidence of continuous compliance monitoring across 45 AWS accounts.
Approach: 1. Run Prowler CIS v5.0 assessment across all 45 accounts to establish the baseline compliance score 2. Export results to CSV and categorize failures by section (IAM, Logging, Monitoring, Networking) 3. Map each CIS control to the relevant SOC 2 Trust Services Criteria (CC6.1, CC6.6, CC7.1, etc.) 4. Remediate all Level 1 control failures within 30 days and Level 2 within 60 days 5. Enable CIS v5.0 in AWS Security Hub for continuous monitoring and automated drift detection 6. Generate weekly compliance reports showing improvement trajectory for the auditor 7. Document exceptions for controls intentionally not implemented with risk acceptance justification
Pitfalls: Remediating controls without testing in a staging environment first can break production workloads. Ignoring Level 2 controls entirely weakens the audit narrative even if they are not strictly required.
Output Format
CIS Benchmark Audit Report
============================
Cloud Provider: AWS
Benchmark Version: CIS AWS Foundations Benchmark v5.0
Accounts Assessed: 45
Assessment Date: 2025-02-23
Tool: Prowler v4.3.0
OVERALL COMPLIANCE SCORE: 74%
COMPLIANCE BY SECTION:
1. Identity and Access Management: 68% (41/60 controls passed)
2. Storage: 82% (28/34 controls passed)
3. Logging: 91% (20/22 controls passed)
4. Monitoring: 55% (18/33 controls passed)
5. Networking: 78% (32/41 controls passed)
TOP FAILED CONTROLS (by affected accounts):
[1.4] Root account has active access keys - 3/45 accounts
[1.5] MFA not enabled for root account - 2/45 accounts
[2.1.1] S3 default encryption not enabled - 12/45 accounts
[3.1] CloudTrail not multi-region - 8/45 accounts
[4.3] No alarm for root account usage - 28/45 accounts
[5.1] VPC flow logs not enabled - 15/45 accounts
[5.4] Security groups allow 0.0.0.0/0 ingress - 22/45 accounts
REMEDIATION PRIORITY:
Critical (Fix within 7 days): Root access keys, missing root MFA
High (Fix within 30 days): S3 encryption, CloudTrail, VPC flow logs
Medium (Fix within 60 days): CloudWatch alarms, security group restrictions
Low (Fix within 90 days): Level 2 controls, informational items
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to the Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by the Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding any notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. Please do not remove or change
the license header comment from a contributed file except when
necessary.
Copyright 2026 mukul975
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
API Reference: Auditing Cloud with CIS Benchmarks
boto3 - AWS CIS Checks
IAM Account Summary (Root Keys, MFA)
import boto3
iam = boto3.client("iam")
summary = iam.get_account_summary()["SummaryMap"]
print("Root access keys:", summary["AccountAccessKeysPresent"])
print("Root MFA:", summary["AccountMFAEnabled"])Password Policy
policy = iam.get_account_password_policy()["PasswordPolicy"]
print("Min length:", policy["MinimumPasswordLength"])
print("Require symbols:", policy["RequireSymbols"])CloudTrail Multi-Region
ct = boto3.client("cloudtrail")
trails = ct.describe_trails()["trailList"]
for t in trails:
print(t["Name"], "Multi-region:", t["IsMultiRegionTrail"])VPC Flow Logs
ec2 = boto3.client("ec2")
vpcs = ec2.describe_vpcs()["Vpcs"]
flow_logs = ec2.describe_flow_logs()["FlowLogs"]
logged = {fl["ResourceId"] for fl in flow_logs}
for vpc in vpcs:
print(vpc["VpcId"], "Logged:" if vpc["VpcId"] in logged else "MISSING")CIS Controls Quick Reference
| CIS Control | boto3 Method | Check |
|---|---|---|
| 1.4 Root keys | iam.get_account_summary() | AccountAccessKeysPresent == 0 |
| 1.5 Root MFA | iam.get_account_summary() | AccountMFAEnabled == 1 |
| 2.1.1 S3 encryption | s3.get_bucket_encryption() | No ClientError |
| 3.1 CloudTrail | ct.describe_trails() | IsMultiRegionTrail |
| 5.1 VPC flow logs | ec2.describe_flow_logs() | All VPCs covered |
| 5.4 Default SG | ec2.describe_security_groups() | No 0.0.0.0/0 rules |
Prowler CLI
prowler aws --compliance cis_5.0_aws --output-formats json,csv
prowler azure --compliance cis_4.0_azure
prowler gcp --compliance cis_4.0_gcpReferences
- boto3: https://boto3.amazonaws.com/v1/documentation/api/latest/
- CIS Benchmarks: https://www.cisecurity.org/benchmark/amazon_web_services
- Prowler: https://github.com/prowler-cloud/prowler
#!/usr/bin/env python3
"""Agent for auditing cloud infrastructure against CIS Benchmarks using boto3."""
import os
import json
import argparse
from datetime import datetime
import boto3
from botocore.exceptions import ClientError
def check_root_access_keys(session):
"""CIS 1.4 - Ensure no root account access key exists."""
iam = session.client("iam")
summary = iam.get_account_summary()["SummaryMap"]
root_keys = summary.get("AccountAccessKeysPresent", 0)
return {"control": "1.4", "description": "Root access keys", "status": "FAIL" if root_keys > 0 else "PASS", "detail": f"{root_keys} keys"}
def check_root_mfa(session):
"""CIS 1.5 - Ensure MFA is enabled for the root account."""
iam = session.client("iam")
summary = iam.get_account_summary()["SummaryMap"]
mfa = summary.get("AccountMFAEnabled", 0)
return {"control": "1.5", "description": "Root MFA", "status": "PASS" if mfa else "FAIL"}
def check_password_policy(session):
"""CIS 1.8-1.11 - Ensure IAM password policy is strong."""
iam = session.client("iam")
try:
policy = iam.get_account_password_policy()["PasswordPolicy"]
issues = []
if policy.get("MinimumPasswordLength", 0) < 14:
issues.append("MinLength < 14")
if not policy.get("RequireUppercaseCharacters"):
issues.append("No uppercase required")
if not policy.get("RequireLowercaseCharacters"):
issues.append("No lowercase required")
if not policy.get("RequireNumbers"):
issues.append("No numbers required")
if not policy.get("RequireSymbols"):
issues.append("No symbols required")
return {"control": "1.8-1.11", "description": "Password policy", "status": "FAIL" if issues else "PASS", "detail": issues}
except ClientError:
return {"control": "1.8", "description": "Password policy", "status": "FAIL", "detail": "No policy set"}
def check_cloudtrail_multiregion(session):
"""CIS 3.1 - Ensure CloudTrail is enabled in all regions."""
ct = session.client("cloudtrail")
trails = ct.describe_trails()["trailList"]
multiregion = [t for t in trails if t.get("IsMultiRegionTrail")]
return {"control": "3.1", "description": "CloudTrail multi-region", "status": "PASS" if multiregion else "FAIL", "detail": f"{len(multiregion)} multi-region trails"}
def check_cloudtrail_log_validation(session):
"""CIS 3.2 - Ensure CloudTrail log file validation is enabled."""
ct = session.client("cloudtrail")
trails = ct.describe_trails()["trailList"]
no_validation = [t["Name"] for t in trails if not t.get("LogFileValidationEnabled")]
return {"control": "3.2", "description": "Log file validation", "status": "FAIL" if no_validation else "PASS", "detail": no_validation}
def check_s3_encryption(session):
"""CIS 2.1.1 - Ensure S3 default encryption is enabled."""
s3 = session.client("s3")
buckets = s3.list_buckets()["Buckets"]
unencrypted = []
for b in buckets:
try:
s3.get_bucket_encryption(Bucket=b["Name"])
except ClientError:
unencrypted.append(b["Name"])
return {"control": "2.1.1", "description": "S3 default encryption", "status": "FAIL" if unencrypted else "PASS", "detail": unencrypted}
def check_vpc_flow_logs(session):
"""CIS 5.1 - Ensure VPC flow logging is enabled."""
ec2 = session.client("ec2")
vpcs = ec2.describe_vpcs()["Vpcs"]
flow_logs = ec2.describe_flow_logs()["FlowLogs"]
logged_vpcs = {fl["ResourceId"] for fl in flow_logs}
missing = [v["VpcId"] for v in vpcs if v["VpcId"] not in logged_vpcs]
return {"control": "5.1", "description": "VPC flow logs", "status": "FAIL" if missing else "PASS", "detail": missing}
def check_default_sg_restrictions(session):
"""CIS 5.4 - Ensure default security group restricts all traffic."""
ec2 = session.client("ec2")
sgs = ec2.describe_security_groups(Filters=[{"Name": "group-name", "Values": ["default"]}])["SecurityGroups"]
open_default = []
for sg in sgs:
if sg.get("IpPermissions") or sg.get("IpPermissionsEgress"):
for rule in sg.get("IpPermissions", []):
for ip_range in rule.get("IpRanges", []):
if ip_range.get("CidrIp") == "0.0.0.0/0":
open_default.append(sg["GroupId"])
return {"control": "5.4", "description": "Default SG restrictions", "status": "FAIL" if open_default else "PASS", "detail": open_default}
def run_full_audit(session):
"""Execute all CIS benchmark checks."""
checks = [
check_root_access_keys, check_root_mfa, check_password_policy,
check_cloudtrail_multiregion, check_cloudtrail_log_validation,
check_s3_encryption, check_vpc_flow_logs, check_default_sg_restrictions,
]
results = []
for check_fn in checks:
result = check_fn(session)
results.append(result)
status_icon = "PASS" if result["status"] == "PASS" else "FAIL"
print(f" [{status_icon}] {result['control']}: {result['description']}")
return results
def main():
parser = argparse.ArgumentParser(description="CIS Benchmark Cloud Audit Agent")
parser.add_argument("--profile", default=os.getenv("AWS_PROFILE"))
parser.add_argument("--region", default=os.getenv("AWS_DEFAULT_REGION", "us-east-1"))
parser.add_argument("--output", default="cis_audit_report.json")
args = parser.parse_args()
session = boto3.Session(profile_name=args.profile, region_name=args.region)
account = session.client("sts").get_caller_identity()["Account"]
print(f"[+] CIS Benchmark Audit for account {account}")
results = run_full_audit(session)
passed = sum(1 for r in results if r["status"] == "PASS")
total = len(results)
score = int(passed / total * 100) if total else 0
report = {
"account": account,
"benchmark": "CIS AWS Foundations v5.0",
"audit_date": datetime.utcnow().isoformat(),
"compliance_score": f"{score}%",
"passed": passed,
"failed": total - passed,
"checks": results,
}
with open(args.output, "w") as f:
json.dump(report, f, indent=2, default=str)
print(f"\n[+] Score: {score}% ({passed}/{total} passed)")
print(f"[+] Report saved to {args.output}")
if __name__ == "__main__":
main()
Related skills
FAQ
Is Auditing Cloud With Cis Benchmarks safe to install?
skills.sh reports 3 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.