from datetime import datetime
import json
import requests
import os
import sys
import logging
from bs4 import BeautifulSoup
LOG_LEVEL = logging.INFO
URLS = [
"https://docs.aws.amazon.com/securityhub/latest/userguide/account-controls.html",
"https://docs.aws.amazon.com/securityhub/latest/userguide/acm-controls.html",
"https://docs.aws.amazon.com/securityhub/latest/userguide/apigateway-controls.html",
"https://docs.aws.amazon.com/securityhub/latest/userguide/appsync-controls.html",
"https://docs.aws.amazon.com/securityhub/latest/userguide/athena-controls.html",
"https://docs.aws.amazon.com/securityhub/latest/userguide/backup-controls.html",
"https://docs.aws.amazon.com/securityhub/latest/userguide/cloudformation-controls.html",
"https://docs.aws.amazon.com/securityhub/latest/userguide/cloudfront-controls.html",
"https://docs.aws.amazon.com/securityhub/latest/userguide/cloudtrail-controls.html",
"https://docs.aws.amazon.com/securityhub/latest/userguide/cloudwatch-controls.html",
"https://docs.aws.amazon.com/securityhub/latest/userguide/codebuild-controls.html",
"https://docs.aws.amazon.com/securityhub/latest/userguide/config-controls.html",
"https://docs.aws.amazon.com/securityhub/latest/userguide/dms-controls.html",
"https://docs.aws.amazon.com/securityhub/latest/userguide/documentdb-controls.html",
"https://docs.aws.amazon.com/securityhub/latest/userguide/dynamodb-controls.html",
"https://docs.aws.amazon.com/securityhub/latest/userguide/ecr-controls.html",
"https://docs.aws.amazon.com/securityhub/latest/userguide/ecs-controls.html",
"https://docs.aws.amazon.com/securityhub/latest/userguide/ec2-controls.html",
"https://docs.aws.amazon.com/securityhub/latest/userguide/autoscaling-controls.html",
"https://docs.aws.amazon.com/securityhub/latest/userguide/ssm-controls.html",
"https://docs.aws.amazon.com/securityhub/latest/userguide/efs-controls.html",
"https://docs.aws.amazon.com/securityhub/latest/userguide/eks-controls.html",
"https://docs.aws.amazon.com/securityhub/latest/userguide/elasticache-controls.html",
"https://docs.aws.amazon.com/securityhub/latest/userguide/elasticbeanstalk-controls.html",
"https://docs.aws.amazon.com/securityhub/latest/userguide/elb-controls.html",
"https://docs.aws.amazon.com/securityhub/latest/userguide/emr-controls.html",
"https://docs.aws.amazon.com/securityhub/latest/userguide/es-controls.html",
"https://docs.aws.amazon.com/securityhub/latest/userguide/eventbridge-controls.html",
"https://docs.aws.amazon.com/securityhub/latest/userguide/fsx-controls.html",
"https://docs.aws.amazon.com/securityhub/latest/userguide/guardduty-controls.html",
"https://docs.aws.amazon.com/securityhub/latest/userguide/iam-controls.html",
"https://docs.aws.amazon.com/securityhub/latest/userguide/kinesis-controls.html",
"https://docs.aws.amazon.com/securityhub/latest/userguide/kms-controls.html",
"https://docs.aws.amazon.com/securityhub/latest/userguide/lambda-controls.html",
"https://docs.aws.amazon.com/securityhub/latest/userguide/macie-controls.html",
"https://docs.aws.amazon.com/securityhub/latest/userguide/msk-controls.html",
"https://docs.aws.amazon.com/securityhub/latest/userguide/mq-controls.html",
"https://docs.aws.amazon.com/securityhub/latest/userguide/neptune-controls.html",
"https://docs.aws.amazon.com/securityhub/latest/userguide/networkfirewall-controls.html",
"https://docs.aws.amazon.com/securityhub/latest/userguide/opensearch-controls.html",
"https://docs.aws.amazon.com/securityhub/latest/userguide/pca-controls.html",
"https://docs.aws.amazon.com/securityhub/latest/userguide/rds-controls.html",
"https://docs.aws.amazon.com/securityhub/latest/userguide/redshift-controls.html",
"https://docs.aws.amazon.com/securityhub/latest/userguide/route53-controls.html",
"https://docs.aws.amazon.com/securityhub/latest/userguide/s3-controls.html",
"https://docs.aws.amazon.com/securityhub/latest/userguide/sagemaker-controls.html",
"https://docs.aws.amazon.com/securityhub/latest/userguide/secretsmanager-controls.html",
"https://docs.aws.amazon.com/securityhub/latest/userguide/sns-controls.html",
"https://docs.aws.amazon.com/securityhub/latest/userguide/sqs-controls.html",
"https://docs.aws.amazon.com/securityhub/latest/userguide/stepfunctions-controls.html",
"https://docs.aws.amazon.com/securityhub/latest/userguide/waf-controls.html"
]
SEARCH_STRINGS = {
"AWS Config rule": "code",
"Resource type": "code",
"Schedule type": "text",
"Severity": "text"
}
FIND_ELEMENT_NAME = "h2"
FIND_NEXT_SIBLINGS = "p"
class TimeFormatter(logging.Formatter):
converter = datetime.fromtimestamp
def formatTime(self, record, datefmt=None):
dt = self.converter(record.created)
if datefmt:
s = dt.strftime(datefmt)
else:
t = dt.strftime(self.default_time_format)
s = self.default_msec_format % (t, record.msecs)
return s
def init_logger():
logger = logging.getLogger(__name__)
log_format_string = json.dumps({
'logLevel': '%(levelname)s',
'time': '%(asctime)s',
'line': "%(filename)s: %(lineno)d",
'message': '%(message)s',
}, indent=None)
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter((TimeFormatter(log_format_string)))
logger.addHandler(handler)
logger.propagate = False
logger.setLevel(LOG_LEVEL)
return logger
def main():
logger = init_logger()
result = []
for url in URLS:
response = requests.get(url)
response.encoding = response.apparent_encoding
soup = BeautifulSoup(response.text, 'html.parser')
find_elements = soup.find_all(FIND_ELEMENT_NAME)
for find_element in find_elements:
next_siblings = find_element.find_next_siblings(FIND_NEXT_SIBLINGS)
entry = {"find_element.text": find_element.text}
logger.debug(f"find_element: {find_element}")
for search_string, method in SEARCH_STRINGS.items():
for sibling in next_siblings:
if search_string in sibling.text:
if method == "text":
value = sibling.b.next_sibling.strip()
entry[search_string] = value
logger.debug(f"search_string: {search_string}, value: {value}")
break
else:
value_element = sibling.find(method, {'class': 'code'})
if value_element:
entry[search_string] = value_element.text
logger.debug(f"search_string: {search_string}, value: {value_element.text}")
break
if search_string not in entry:
entry[search_string] = "Not Found"
logger.debug(f"search_string: {search_string}, value: None")
result.append(entry)
if not os.path.exists('.output'):
os.makedirs('.output')
now = datetime.now().strftime('%Y%m%d%H%M%S')
with open(f'.output/result_{now}.json', 'w', encoding='utf-8') as f:
json.dump(result, f, ensure_ascii=False)
logger.info(f"Successfully saved the result to .output/result_{now}.json")
if __name__ == "__main__":
main()
AWS Security Hub 控制參考 JSON
[
{
"find_element.text": "[Account.1] Security contact information should be provided for an AWS account",
"AWS Config rule": "security-account-information-provided",
"Resource type": "AWS::::Account",
"Schedule type": "Periodic",
"Severity": "Medium"
},
{
"find_element.text": "[Account.2] AWS accounts should be part of an AWS Organizations organization",
"AWS Config rule": "account-part-of-organizations",
"Resource type": "AWS::::Account",
"Schedule type": "Periodic",
"Severity": "High"
},
{
"find_element.text": "[ACM.1] Imported and ACM-issued certificates should be renewed after a specified time period",
"AWS Config rule": "acm-certificate-expiration-check",
"Resource type": "AWS::ACM::Certificate",
"Schedule type": "Change triggered and periodic",
"Severity": "Medium"
},
{
"find_element.text": "[APIGateway.1] API Gateway REST and WebSocket API execution logging should be enabled",
"AWS Config rule": "api-gw-execution-logging-enabled",
"Resource type": "AWS::ApiGateway::Stage",
"Schedule type": "Change triggered",
"Severity": "Medium"
},
{
"find_element.text": "[EC2.1] Amazon EBS snapshots should not be publicly restorable",
"AWS Config rule": "ebs-snapshot-public-restorable-check",
"Resource type": "AWS::EC2::Snapshot",
"Schedule type": "Change triggered",
"Severity": "Critical"
},
{
"find_element.text": "[S3.1] S3 general purpose buckets should have block public access settings enabled",
"AWS Config rule": "s3-bucket-level-public-access-prohibited",
"Resource type": "AWS::S3::Bucket",
"Schedule type": "Change triggered",
"Severity": "Critical"
},
{
"find_element.text": "[WAF.12] AWS WAF rules should have CloudWatch metrics enabled",
"AWS Config rule": "wafv2-rulegroup-logging-enabled",
"Resource type": "AWS::WAFv2::RuleGroup",
"Schedule type": "Change triggered",
"Severity": "Medium"
}
]
Note
執行上述擷取指令碼會將全部 300 多項 AWS Security Hub 控制定義輸出至
.output/result_<時間戳記>.json
(上方展示核心控制項的代表性摘錄)。
% cat result_20240204153052.json| jq '.[] | select(.Severity == "Critical") | {title: ."find_element.text" ,config_rule: ."AWS Config rule"}'
{
"title": "[CloudTrail.6] Ensure the S3 bucket used to store CloudTrail logs is not publicly accessible",
"config_rule": "Not Found"
}
{
"title": "[CodeBuild.1] CodeBuild Bitbucket source repository URLs should not contain sensitive credentials",
"config_rule": "codebuild-project-source-repo-url-check"
}
{
"title": "[CodeBuild.2] CodeBuild project environment variables should not contain clear text credentials",
"config_rule": "codebuild-project-envvar-awscred-check"
}
{
"title": "[DMS.1] Database Migration Service replication instances should not be public",
"config_rule": "dms-replication-not-public"
}
{
"title": "[DocumentDB.3] Amazon DocumentDB manual cluster snapshots should not be public",
"config_rule": "docdb-cluster-snapshot-public-prohibited"
}
{
"title": "[EC2.1] Amazon EBS snapshots should not be publicly restorable",
"config_rule": "ebs-snapshot-public-restorable-check"
}
{
"title": "[EC2.19] Security groups should not allow unrestricted\n access to ports with high risk",
"config_rule": "vpc-sg-restricted-common-ports"
}
{
"title": "[SSM.4] SSM documents should not be public",
"config_rule": "ssm-document-not-public"
}
{
"title": "[EMR.2] Amazon EMR block public access setting should be enabled",
"config_rule": "emr-block-public-access"
}
{
"title": "[ES.2] Elasticsearch domains should not be publicly accessible",
"config_rule": "elasticsearch-in-vpc-only"
}
{
"title": "[IAM.4] IAM root user access key should not exist",
"config_rule": "iam-root-access-key-check"
}
{
"title": "[IAM.6] Hardware MFA should be enabled for the root user",
"config_rule": "root-account-hardware-mfa-enabled"
}
{
"title": "[IAM.9] MFA should be enabled for the root user",
"config_rule": "root-account-mfa-enabled"
}
{
"title": "[KMS.3] AWS KMS keys should not be deleted unintentionally",
"config_rule": "kms-cmk-not-scheduled-for-deletion-2"
}
{
"title": "[Lambda.1] Lambda function policies should prohibit public access",
"config_rule": "lambda-function-public-access-prohibited"
}
{
"title": "[Neptune.3] Neptune DB cluster snapshots should not be\n public",
"config_rule": "neptune-cluster-snapshot-public-prohibited"
}
{
"title": "[Opensearch.2] OpenSearch domains should not be publicly accessible",
"config_rule": "opensearch-in-vpc-only"
}
{
"title": "[RDS.1] RDS snapshot should be private",
"config_rule": "rds-snapshots-public-prohibited"
}
{
"title": "[RDS.2] RDS DB Instances should prohibit public access, as determined by the PubliclyAccessible AWS Configuration",
"config_rule": "rds-instance-public-access-check"
}
{
"title": "[Redshift.1] Amazon Redshift clusters should prohibit public access",
"config_rule": "redshift-cluster-public-access-check"
}
{
"title": "[S3.2] S3 buckets should prohibit public read access",
"config_rule": "s3-bucket-public-read-prohibited"
}
{
"title": "[S3.3] S3 buckets should prohibit public write access",
"config_rule": "s3-bucket-public-write-prohibited"
}
{
"title": "[S3.19] S3 access points should have block public access settings enabled",
"config_rule": "s3-access-point-public-access-blocks"
}
% cat result_20240204153052.json| jq '.[] | select(.Severity == "High") | {title: ."find_element.text" ,config_rule: ."AWS Config rule"}'
{
"title": "[Account.2] AWS accounts should be part of an AWS Organizations organization",
"config_rule": "account-part-of-organizations"
}
{
"title": "[ACM.2] RSA certificates managed by ACM should use a key length of at least 2,048 bits",
"config_rule": "acm-certificate-rsa-check"
}
{
"title": "[AppSync.5] AWS AppSync GraphQL APIs should not be authenticated with API keys",
"config_rule": "appsync-authorization-check"
}
{
"title": "[CloudFront.1] CloudFront distributions should have a default root object configured",
"config_rule": "cloudfront-default-root-object-configured"
}
{
"title": "[CloudFront.12] CloudFront distributions should not point to non-existent S3 origins",
"config_rule": "cloudfront-s3-origin-non-existent-bucket"
}
{
"title": "[CloudTrail.1] CloudTrail should be enabled and configured with at least one multi-Region trail that includes read and write management events",
"config_rule": "multi-region-cloudtrail-enabled"
}
{
"title": "[CloudTrail.3] CloudTrail should be enabled",
"config_rule": "cloudtrail-enabled"
}
{
"title": "[CloudWatch.15] CloudWatch alarms should have specified actions configured",
"config_rule": "cloudwatch-alarm-action-check"
}
{
"title": "[CloudWatch.17] CloudWatch alarm actions should be activated",
"config_rule": "cloudwatch-alarm-action-enabled-check"
}
{
"title": "[CodeBuild.5] CodeBuild project environments should not have privileged mode enabled",
"config_rule": "codebuild-project-environment-privileged-check"
}
{
"title": "[ECR.1] ECR private repositories should have image scanning configured",
"config_rule": "ecr-private-image-scanning-enabled"
}
{
"title": "[ECS.1] Amazon ECS task definitions should have secure networking modes and user definitions.",
"config_rule": "ecs-task-definition-user-for-host-mode-check"
}
{
"title": "[ECS.2] ECS services should not have public IP addresses assigned to them automatically",
"config_rule": "Not Found"
}
{
"title": "[ECS.3] ECS task definitions should not share the host's process namespace",
"config_rule": "Not Found"
}
{
"title": "[ECS.4] ECS containers should run as non-privileged",
"config_rule": "Not Found"
}
{
"title": "[ECS.5] ECS containers should be limited to read-only access to root filesystems",
"config_rule": "Not Found"
}
{
"title": "[ECS.8] Secrets should not be passed as container environment variables",
"config_rule": "Not Found"
}
{
"title": "[ECS.9] ECS task definitions should have a logging configuration",
"config_rule": "Not Found"
}
{
"title": "[EC2.2] VPC default security groups should not allow inbound or outbound traffic",
"config_rule": "vpc-default-security-group-closed"
}
{
"title": "[EC2.8] EC2 instances should use Instance Metadata Service Version 2 (IMDSv2)",
"config_rule": "ec2-imdsv2-check"
}
{
"title": "[EC2.9] Amazon EC2 instances should not have a public IPv4 address",
"config_rule": "ec2-instance-no-public-ip"
}
{
"title": "[EC2.13] Security groups should not allow ingress from\n 0.0.0.0/0 or ::/0 to port 22",
"config_rule": "restricted-ssh"
}
{
"title": "[EC2.14] Security groups should not allow ingress from 0.0.0.0/0 or ::/0 to port 3389",
"config_rule": "restricted-common-ports"
}
{
"title": "[EC2.18] Security groups should only allow unrestricted\n incoming traffic for authorized ports",
"config_rule": "vpc-sg-open-only-to-authorized-ports"
}
{
"title": "[EC2.23] Amazon EC2 Transit Gateways should not automatically\n accept VPC attachment requests",
"config_rule": "ec2-transit-gateway-auto-vpc-attach-disabled"
}
{
"title": "[EC2.25] Amazon EC2 launch templates should not assign public\n IPs to network interfaces",
"config_rule": "ec2-launch-template-public-ip-disabled"
}
{
"title": "[AutoScaling.3] Auto Scaling group launch configurations should configure EC2 instances to require Instance Metadata Service Version 2 (IMDSv2)",
"config_rule": "autoscaling-launchconfig-requires-imdsv2"
}
{
"title": "[AutoScaling.4] Auto Scaling group launch configuration should not have a metadata response hop limit greater than 1",
"config_rule": "autoscaling-launch-config-hop-limit"
}
{
"title": "[Autoscaling.5] Amazon EC2 instances launched using Auto Scaling group launch configurations should not have Public IP addresses",
"config_rule": "autoscaling-launch-config-public-ip-disabled"
}
{
"title": "[SSM.2] Amazon EC2 instances managed by Systems Manager should have a patch compliance status of COMPLIANT after a patch installation",
"config_rule": "ec2-managedinstance-patch-compliance-status-check"
}
{
"title": "[EKS.1] EKS cluster endpoints should not be publicly accessible",
"config_rule": "eks-endpoint-no-public-access"
}
{
"title": "[EKS.2] EKS clusters should run on a supported Kubernetes version",
"config_rule": "eks-cluster-supported-version"
}
{
"title": "[ElastiCache.1] ElastiCache Redis clusters should have automatic backup enabled",
"config_rule": "elasticache-redis-cluster-automatic-backup-check"
}
{
"title": "[ElastiCache.2] ElastiCache for Redis cache clusters should have auto minor version upgrade enabled",
"config_rule": "elasticache-auto-minor-version-upgrade-check"
}
{
"title": "[ElastiCache.7] ElastiCache clusters should not use the default subnet group",
"config_rule": "elasticache-subnet-group-check"
}
{
"title": "[ElasticBeanstalk.2] Elastic Beanstalk managed platform updates should be enabled",
"config_rule": "elastic-beanstalk-managed-updates-enabled"
}
{
"title": "[ElasticBeanstalk.3] Elastic Beanstalk should stream logs to CloudWatch",
"config_rule": "elastic-beanstalk-logs-to-cloudwatch"
}
{
"title": "[EMR.1] Amazon EMR cluster primary nodes should not have public IP addresses",
"config_rule": "emr-master-no-public-ip"
}
{
"title": "[GuardDuty.1] GuardDuty should be enabled",
"config_rule": "guardduty-enabled-centralized"
}
{
"title": "[IAM.1] IAM policies should not allow full \"*\" administrative privileges",
"config_rule": "iam-policy-no-statements-with-admin-access"
}
{
"title": "[Opensearch.7] OpenSearch domains should have fine-grained access control enabled",
"config_rule": "opensearch-access-control-enabled"
}
{
"title": "[RDS.13] RDS automatic minor version upgrades should be enabled",
"config_rule": "rds-automatic-minor-version-upgrade-enabled"
}
{
"title": "[RDS.18] RDS instances should be deployed in a VPC",
"config_rule": "rds-deployed-in-vpc"
}
{
"title": "[S3.6] S3 permissions granted to other AWS accounts in bucket policies should be restricted",
"config_rule": "s3-bucket-blacklisted-actions-prohibited"
}
{
"title": "[S3.8] S3 Block Public Access setting should be enabled at the bucket-level",
"config_rule": "s3-bucket-level-public-access-prohibited"
}
{
"title": "[SageMaker.1] Amazon SageMaker notebook instances should not have direct internet access",
"config_rule": "sagemaker-notebook-no-direct-internet-access"
}
{
"title": "[SageMaker.2] SageMaker notebook instances should be launched in a custom VPC",
"config_rule": "sagemaker-notebook-instance-inside-vpc"
}
{
"title": "[SageMaker.3] Users should not have root access to SageMaker notebook instances",
"config_rule": "sagemaker-notebook-instance-root-access-check"
}