Skip to content

Instantly share code, notes, and snippets.

@xmanwms95

xmanwms95/ami.json Secret

Last active May 8, 2020
Embed
What would you like to do?
Inspector Quickstart CodeBuild & Lambda Code
{
"variables": {
"inspector_vpc_id": "",
"commit_id": "",
"ami_name": "",
"region": ""
},
"builders": [{
"type": "amazon-ebs",
"region": "{{user `region`}}",
"source_ami_filter": {
"filters": {
"virtualization-type": "hvm",
"name": "amzn2-ami-hvm-2.0.*x86_64-ebs",
"root-device-type": "ebs"
},
"owners": ["amazon"],
"most_recent": true
},
"tags": {
"Name": "{{user `ami_name`}}-{{timestamp}}",
"CommitId": "{{user `commit_id`}}"
},
"snapshot_tags": {
"Name": "{{user `ami_name`}}-{{timestamp}}",
"CommitId": "{{user `commit_id`}}"
},
"instance_type": "t2.micro",
"ssh_username": "ec2-user",
"associate_public_ip_address": true,
"vpc_id": "{{user `inspector_vpc_id`}}",
"subnet_filter": {
"filters": {
"tag:Subnet": "InspectorQuickstart-subnet-1"
},
"random": true
},
"ami_name": "{{user `ami_name`}}-{{timestamp}}",
"ami_description": "Inspector Quickstart"
}],
"provisioners": [
{
"type": "shell",
"inline": [
"sudo yum update -y",
"sudo yum install -y wget",
"wget https://inspector-agent.amazonaws.com/linux/latest/install",
"sudo bash install"
]
}
]
}
AWSTemplateFormatVersion: "2010-09-09"
Description: "AWS-Inspector-Quickstart"
Parameters:
AMI:
Description: AMI ID
Type: AWS::EC2::Image::Id
KeyPair:
Description: Key pair to launch ec2 instance
Type: AWS::EC2::KeyPair::KeyName
SubnetId:
Description: Subnet ID to launch instance for scanning
Type: AWS::EC2::Subnet::Id
ec2tag:
Description: Tag for ec2 instances for scanning
Type: String
ScanLength:
Type: Number
Description: Duration of Inspector Scan in seconds
Default: 180
CommitId:
Type: String
Description: Duration of Inspector Scan in seconds
Mappings:
RegionMap:
us-east-1:
CommonVul: arn:aws:inspector:us-east-1:316112463485:rulespackage/0-gEjTy7T7
CIS: arn:aws:inspector:us-east-1:316112463485:rulespackage/0-rExsr2X8
SecurityBest: arn:aws:inspector:us-east-1:316112463485:rulespackage/0-R01qwB5Q
us-east-2:
CommonVul: arn:aws:inspector:us-east-2:646659390643:rulespackage/0-JnA8Zp85
CIS: arn:aws:inspector:us-east-2:646659390643:rulespackage/0-m8r61nnh
SecurityBest: arn:aws:inspector:us-east-2:646659390643:rulespackage/0-AxKmMHPX
us-west-1:
CommonVul: arn:aws:inspector:us-west-1:166987590008:rulespackage/0-TKgzoVOa
CIS: arn:aws:inspector:us-west-1:166987590008:rulespackage/0-xUY8iRqX
SecurityBest: arn:aws:inspector:us-west-1:166987590008:rulespackage/0-byoQRFYm
us-west-2:
CommonVul: arn:aws:inspector:us-west-2:758058086616:rulespackage/0-9hgA516p
CIS: arn:aws:inspector:us-west-2:758058086616:rulespackage/0-H5hpSawc
SecurityBest: arn:aws:inspector:us-west-2:758058086616:rulespackage/0-JJOtZiqQ
ap-south-1:
CommonVul: arn:aws:inspector:ap-south-1:162588757376:rulespackage/0-LqnJE9dO
CIS: arn:aws:inspector:ap-south-1:162588757376:rulespackage/0-PSUlX14m
SecurityBest: arn:aws:inspector:ap-south-1:162588757376:rulespackage/0-fs0IZZBj
ap-northeast-2:
CommonVul: arn:aws:inspector:ap-northeast-2:526946625049:rulespackage/0-PoGHMznc
CIS: arn:aws:inspector:ap-northeast-2:526946625049:rulespackage/0-T9srhg1z
SecurityBest: arn:aws:inspector:ap-northeast-2:526946625049:rulespackage/0-2WRpmi4n
ap-southeast-2:
CommonVul: arn:aws:inspector:ap-southeast-2:454640832652:rulespackage/0-D5TGAxiR
CIS: arn:aws:inspector:ap-southeast-2:454640832652:rulespackage/0-Vkd2Vxjq
SecurityBest: arn:aws:inspector:ap-southeast-2:454640832652:rulespackage/0-asL6HRgN
ap-northeast-1:
CommonVul: arn:aws:inspector:ap-northeast-1:406045910587:rulespackage/0-gHP9oWNT
CIS: arn:aws:inspector:ap-northeast-1:406045910587:rulespackage/0-7WNjqgGu
SecurityBest: arn:aws:inspector:ap-northeast-1:406045910587:rulespackage/0-bBUQnxMq
eu-central-1:
CommonVul: arn:aws:inspector:eu-central-1:537503971621:rulespackage/0-wNqHa8M9
CIS: arn:aws:inspector:eu-central-1:537503971621:rulespackage/0-nZrAVuv8
SecurityBest: arn:aws:inspector:eu-central-1:537503971621:rulespackage/0-ZujVHEPB
eu-west-1:
CommonVul: arn:aws:inspector:eu-west-1:357557129151:rulespackage/0-ubA5XvBh
CIS: arn:aws:inspector:eu-west-1:357557129151:rulespackage/0-sJBhCr0F
SecurityBest: arn:aws:inspector:eu-west-1:357557129151:rulespackage/0-SnojL3Z6
eu-west-2:
CommonVul: arn:aws:inspector:eu-west-2:146838936955:rulespackage/0-kZGCqcE1
CIS: arn:aws:inspector:eu-west-2:146838936955:rulespackage/0-IeCjwf1W
SecurityBest: arn:aws:inspector:eu-west-2:146838936955:rulespackage/0-XApUiSaP
eu-north-1:
CommonVul: arn:aws:inspector:eu-north-1:453420244670:rulespackage/0-IgdgIewd
CIS: arn:aws:inspector:eu-north-1:453420244670:rulespackage/0-Yn8jlX7f
SecurityBest: arn:aws:inspector:eu-north-1:453420244670:rulespackage/0-HfBQSbSf
us-gov-east-1:
CommonVul: arn:aws-us-gov:inspector:us-gov-east-1:206278770380:rulespackage/0-3IFKFuOb
CIS: arn:aws-us-gov:inspector:us-gov-east-1:206278770380:rulespackage/0-pTLCdIww
SecurityBest: arn:aws-us-gov:inspector:us-gov-east-1:206278770380:rulespackage/0-vlgEGcVD
us-gov-west-1:
CommonVul: arn:aws-us-gov:inspector:us-gov-west-1:850862329162:rulespackage/0-4oQgcI4G
CIS: arn:aws-us-gov:inspector:us-gov-west-1:850862329162:rulespackage/0-Ac4CFOuc
SecurityBest: aarn:aws-us-gov:inspector:us-gov-west-1:850862329162:rulespackage/0-rOTGqe5G
Resources:
InspectorEC2Instance:
Type: AWS::EC2::Instance
Properties:
ImageId: !Ref AMI
InstanceType: t2.micro
KeyName: !Ref KeyPair
SubnetId: !Ref SubnetId
Tags:
- Key: Name
Value: !Ref ec2tag
InspectorResourceGroup:
Type: AWS::Inspector::ResourceGroup
Properties:
ResourceGroupTags:
- Key: Name
Value: !Ref ec2tag
InspectorAssessmentTarget:
Type: AWS::Inspector::AssessmentTarget
Properties:
ResourceGroupArn: !Ref InspectorResourceGroup
InspectorAssessmentTemplate:
Type: AWS::Inspector::AssessmentTemplate
Properties:
AssessmentTargetArn: !Ref InspectorAssessmentTarget
DurationInSeconds: !Ref ScanLength
RulesPackageArns:
- !FindInMap [RegionMap, !Ref "AWS::Region", CommonVul]
- !FindInMap [RegionMap, !Ref "AWS::Region", CIS]
- !FindInMap [RegionMap, !Ref "AWS::Region", SecurityBest]
UserAttributesForFindings:
- Key: Name
Value: !Ref ec2tag
- Key: StackName
Value: !Ref "AWS::StackName"
- Key: CommitId
Value: !Ref CommitId
- Key: AMI_ID
Value: !Ref AMI
Outputs:
ResourceGroup:
Description: Inspector Resource Group
Value: !GetAtt InspectorResourceGroup.Arn
AssessmentTarget:
Description: Inspector Assessment Target
Value: !GetAtt InspectorAssessmentTarget.Arn
AssessmentTemplate:
Description: Inspector Assessment Template
Value: !GetAtt InspectorAssessmentTemplate.Arn
CommitId:
Description: Commit Id
Value: !Ref CommitId
version: 0.2
phases:
install:
runtime-versions:
python: 3.7
commands:
- pip install --upgrade pip
- pip install --upgrade awscli
build:
commands:
- echo "Hello Inspector"
- AMI_ID=$(aws ec2 describe-images --owners ${ACCOUNT_ID} --filters "Name=name,Values=InspectorQuickstart*" "Name=tag:CommitId,Values=${COMMIT_ID}" --query 'sort_by(Images, &CreationDate)'[-1].ImageId | tr -d '"')
- echo $AMI_ID
- aws cloudformation deploy --template-file aws-inspector-cf.yaml --stack-name "${STACK_NAME}-${COMMIT_ID}" --no-fail-on-empty-changeset --parameter-overrides AMI=${AMI_ID} KeyPair=${KEY_PAIR} SubnetId=${SUBNET_ID} ec2tag="InspectorPipeline-${COMMIT_ID}" CommitId=${COMMIT_ID} ScanLength=${SCAN_LENGTH}
{
"type": "shell",
"execute_command": "echo 'packer' | sudo -S env {{ .Vars }} {{ .Path }}",
"inline": [
"sudo echo \"Hello Inspector SSH Banner\" > /etc/ssh/sshd-banner",
"sudo echo \"Banner /etc/ssh/sshd-banner\" > /etc/ssh/sshd_config",
"sudo echo \"Protocol 2\" >> /etc/ssh/sshd_config",
"sudo echo \"LogLevel VERBOSE\" >> /etc/ssh/sshd_config",
"sudo echo \"X11Forwarding no\" >> /etc/ssh/sshd_config",
"sudo echo \"MaxAuthTries 4\" >> /etc/ssh/sshd_config",
"sudo echo \"IgnoreRhosts yes\" >> /etc/ssh/sshd_config",
"sudo echo \"HostbasedAuthentication no\" >> /etc/ssh/sshd_config",
"sudo echo \"PermitRootLogin no\" >> /etc/ssh/sshd_config",
"sudo echo \"PermitEmptyPasswords no\" >> /etc/ssh/sshd_config",
"sudo echo \"PermitUserEnvironment no\" >> /etc/ssh/sshd_config",
"sudo echo \"Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com,aes256-ctr,aes192-ctr,aes128-ctr\" >> /etc/ssh/sshd_config",
"sudo echo \"MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512,hmac-sha2-256\" >> /etc/ssh/sshd_config",
"sudo echo \"KexAlgorithms curve25519-sha256,curve25519-sha256@libssh.org,diffie-hellman-group14-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,ecdh-sha2-nistp521,ecdh-sha2-nistp384,ecdh-sha2-nistp256,diffie-hellman-group-exchange-sha256\" >> /etc/ssh/sshd_config",
"sudo echo \"ClientAliveInterval 300\" >> /etc/ssh/sshd_config",
"sudo echo \"ClientAliveCountMax 0\" >> /etc/ssh/sshd_config",
"sudo echo \"LoginGraceTime 60\" >> /etc/ssh/sshd_config",
"sudo chown root:root /etc/crontab",
"sudo chmod og-rwx /etc/crontab",
"sudo chown root:root /etc/cron.hourly",
"sudo chmod og-rwx /etc/cron.hourly",
"sudo chown root:root /etc/cron.daily",
"sudo chmod og-rwx /etc/cron.daily",
"sudo chown root:root /etc/cron.weekly",
"sudo chmod og-rwx /etc/cron.weekly",
"sudo chown root:root /etc/cron.monthly",
"sudo chmod og-rwx /etc/cron.monthly",
"sudo chown root:root /etc/cron.d",
"sudo chmod og-rwx /etc/cron.d"
]
}
import json, os, logging, boto3, urllib.request, shutil
from datetime import datetime as dt
logger = logging.getLogger('InspectorQuickstart')
logger.setLevel(logging.DEBUG)
inspectorClient = boto3.client('inspector')
cloudformationClient = boto3.client('cloudformation')
s3Client = boto3.client('s3')
snsClient = boto3.client('sns')
reports_bucket = os.environ["REPORTS_BUCKET"]
notification_topic = os.environ["REPORT_COMPLETE_SNS"]
def get_template_user_attributes(assement_template_arn):
user_attributes = {}
response = inspectorClient.describe_assessment_templates(
assessmentTemplateArns=[
assement_template_arn,
]
)
logger.info(response)
if "assessmentTemplates" in response:
for template in response["assessmentTemplates"]:
for user_att in template["userAttributesForFindings"]:
user_attributes[user_att["key"]] = user_att["value"]
return user_attributes
def generate_report(run_arn):
while True:
response = inspectorClient.get_assessment_report(
assessmentRunArn=run_arn,
reportFileFormat="HTML",
reportType="FULL",
)
if "url" in response:
break
url = response["url"]
logger.info(url)
return url
def download_report(url, user_attributes):
report_name = user_attributes["AMI_ID"] + "-inspector-report.html"
temp_file = "/tmp/" + report_name
with urllib.request.urlopen(url=url) as response, open(temp_file, "wb") as out_file:
shutil.copyfileobj(response, out_file)
logger.info(response)
current_date = dt.now().strftime("%m-%d-%Y")
report_to_upload = open(temp_file, "rb")
s3_report_key = current_date + "/" + user_attributes["CommitId"] + "/" + report_name
s3_response = s3Client.put_object(
Bucket=reports_bucket,
Key=s3_report_key,
Body=report_to_upload,
)
logger.info(s3_response)
s3_report_location = "s3://" + reports_bucket + "/" + s3_report_key
logger.info("Report Location: %s", s3_report_location)
return s3_report_location
def notify_scan_completion(ami_id, report_location):
subject = "Inspector Scan Completion for AMI: " + ami_id
message = "Scan Results for " + ami_id + " are located at: " + report_location
response = snsClient.publish(
TopicArn=notification_topic,
Message=message,
Subject=subject,
)
logger.info(response)
return response
def cleanup_scan_resources(stack_name):
response = cloudformationClient.delete_stack(
StackName=stack_name,
)
return response
def handler(event, context):
print("Event: %s" % json.dumps(event))
for record in event["Records"]:
message = json.loads(record["Sns"]["Message"])
if message["event"] == "ENABLE_ASSESSMENT_NOTIFICATIONS":
response = { 'message' : "Scan is not complete" }
elif message["event"] == "ASSESSMENT_RUN_COMPLETED":
user_attributes = get_template_user_attributes(assement_template_arn=message["template"])
report_url = generate_report(run_arn=message["run"])
report_location = download_report(url=report_url, user_attributes=user_attributes)
sns_response = notify_scan_completion(ami_id=user_attributes["AMI_ID"], report_location=report_location)
cleanup_response = cleanup_scan_resources(stack_name=user_attributes["StackName"])
return cleanup_response
return response
INFO:Acceptance Test:Verifying Resources
INFO:Acceptance Test:Printing Resources to terminal
INFO:Acceptance Test: CodePipelineName: test-inspector-stack-codepipeline
INFO:Acceptance Test: NotificationSNS: arn:aws:sns:us-east-1:111111111111:test-inspector-stack-InspectorScanCompleteTopic-FPVM2AYE7MP1
INFO:Acceptance Test: LambdaFunctionName: test-inspector-stack-InspectorLambda-17S0TAT4SNLPE
INFO:Acceptance Test: ReportsBucket: test-inspector-stack-reportsbucket-vxfpqw2wqbkf
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.