|
| 1 | +/** |
| 2 | + * Deploys the CloudMapper audit app. |
| 3 | + * Usage: cdk deploy -c s3_bucket=MYCOMPANY-cloudmapper -c sns_topic=email |
| 4 | + */ |
| 5 | + |
| 6 | +const cdk = require('@aws-cdk/core'); |
| 7 | +const ecs = require('@aws-cdk/aws-ecs'); |
| 8 | +const ecsPatterns = require('@aws-cdk/aws-ecs-patterns'); |
| 9 | +const ec2 = require('@aws-cdk/aws-ec2'); |
| 10 | +const logs = require('@aws-cdk/aws-logs'); |
| 11 | +const iam = require('@aws-cdk/aws-iam'); |
| 12 | +const events = require('@aws-cdk/aws-events'); |
| 13 | +const targets = require('@aws-cdk/aws-events-targets'); |
| 14 | +const cloudwatch = require('@aws-cdk/aws-cloudwatch'); |
| 15 | +const cloudwatch_actions = require('@aws-cdk/aws-cloudwatch-actions'); |
| 16 | +const sns = require('@aws-cdk/aws-sns'); |
| 17 | +const sns_subscription = require('@aws-cdk/aws-sns-subscriptions'); |
| 18 | +const lambda = require('@aws-cdk/aws-lambda'); |
| 19 | + |
| 20 | +// Import libraries to read a config file |
| 21 | +const yaml = require('js-yaml'); |
| 22 | +const fs = require('fs'); |
| 23 | + |
| 24 | +class CloudmapperauditorStack extends cdk.Stack { |
| 25 | + /** |
| 26 | + * |
| 27 | + * @param {cdk.Construct} scope |
| 28 | + * @param {string} id |
| 29 | + * @param {cdk.StackProps=} props |
| 30 | + */ |
| 31 | + constructor(scope, id, props) { |
| 32 | + super(scope, id, props); |
| 33 | + |
| 34 | + // Load config file |
| 35 | + var config = yaml.safeLoad(fs.readFileSync('./s3_bucket_files/cdk_app.yaml', 'utf8')); |
| 36 | + |
| 37 | + if (config['s3_bucket'] == 'MYCOMPANY-cloudmapper') { |
| 38 | + console.log("You must configure the CDK app by editing ./s3_bucket_files/cdk_app.yaml"); |
| 39 | + process.exit(1); |
| 40 | + } |
| 41 | + |
| 42 | + // Create VPC to run everything in, but without a NAT gateway. |
| 43 | + // We want to run in a public subnet, but the CDK creates a private subnet |
| 44 | + // by default, which results in the use of a NAT gateway, which costs $30/mo. |
| 45 | + // To avoid that unnecessary charge, we have to create the VPC in a complicated |
| 46 | + // way. |
| 47 | + // This trick was figured out by jeshan in https://github.com/aws/aws-cdk/issues/1305#issuecomment-525474540 |
| 48 | + // Normally, the CDK does not allow this because the private subnets have to have |
| 49 | + // a route out, and you can't get rid of the private subnets. |
| 50 | + // So the trick is to remove the routes out. |
| 51 | + // The private subnets remain, but are not usable and have no costs. |
| 52 | + const vpc = new ec2.Vpc(this, 'CloudMapperVpc', { |
| 53 | + maxAzs: 2, |
| 54 | + natGateways: 0 |
| 55 | + }); |
| 56 | + |
| 57 | + // Create a condition that will always fail. |
| 58 | + // We will use this in a moment to remove the routes. |
| 59 | + var exclude_condition = new cdk.CfnCondition(this, |
| 60 | + 'exclude-default-route-subnet', |
| 61 | + { |
| 62 | + // Checks if true == false, so this always fails |
| 63 | + expression: cdk.Fn.conditionEquals(true, false) |
| 64 | + } |
| 65 | + ); |
| 66 | + |
| 67 | + // For the private subnets, add a CloudFormation condition to the routes |
| 68 | + // to cause them to not be created. |
| 69 | + for (var subnet of vpc.privateSubnets) { |
| 70 | + for (var child of subnet.node.children) { |
| 71 | + if (child.constructor.name==="CfnRoute") { |
| 72 | + child.cfnOptions.condition = exclude_condition |
| 73 | + } |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + // Define the ECS task |
| 78 | + const cluster = new ecs.Cluster(this, 'Cluster', { vpc }); |
| 79 | + |
| 80 | + const taskDefinition = new ecs.FargateTaskDefinition(this, 'taskDefinition', {}); |
| 81 | + |
| 82 | + taskDefinition.addContainer('cloudmapper-container', { |
| 83 | + image: ecs.ContainerImage.fromAsset('./resources'), |
| 84 | + memoryLimitMiB: 512, |
| 85 | + cpu: 256, |
| 86 | + environment: { |
| 87 | + S3_BUCKET: config['s3_bucket'] |
| 88 | + }, |
| 89 | + logging: new ecs.AwsLogDriver({ |
| 90 | + streamPrefix: 'cloudmapper', |
| 91 | + logRetention: logs.RetentionDays.TWO_WEEKS |
| 92 | + }) |
| 93 | + }); |
| 94 | + |
| 95 | + // Grant the ability to assume the IAM role in any account |
| 96 | + taskDefinition.addToTaskRolePolicy(new iam.PolicyStatement({ |
| 97 | + resources: ["arn:aws:iam::*:role/"+config['iam_role']], |
| 98 | + actions: ['sts:AssumeRole'] |
| 99 | + })); |
| 100 | + |
| 101 | + // Grant the ability to read and write the files from the S3 bucket |
| 102 | + taskDefinition.addToTaskRolePolicy(new iam.PolicyStatement({ |
| 103 | + resources: ["arn:aws:s3:::"+config['s3_bucket']], |
| 104 | + actions: ['s3:ListBucket'] |
| 105 | + })); |
| 106 | + taskDefinition.addToTaskRolePolicy(new iam.PolicyStatement({ |
| 107 | + resources: ["arn:aws:s3:::"+config['s3_bucket']+"/*"], |
| 108 | + actions: ['s3:GetObject','s3:PutObject', 's3:DeleteObject'] |
| 109 | + })); |
| 110 | + |
| 111 | + // Grant the ability to record the stdout to CloudWatch Logs |
| 112 | + taskDefinition.addToTaskRolePolicy(new iam.PolicyStatement({ |
| 113 | + resources: ["*"], |
| 114 | + actions: ['logs:*'] |
| 115 | + })); |
| 116 | + |
| 117 | + // Grant the ability to record error and success metrics |
| 118 | + taskDefinition.addToTaskRolePolicy(new iam.PolicyStatement({ |
| 119 | + // This IAM privilege has no paths or conditions |
| 120 | + resources: ["*"], |
| 121 | + actions: ['cloudwatch:PutMetricData'] |
| 122 | + })); |
| 123 | + |
| 124 | + // Grant the ability to read from Secrets Manager |
| 125 | + taskDefinition.addToTaskRolePolicy(new iam.PolicyStatement({ |
| 126 | + // This IAM privilege has no paths or conditions |
| 127 | + resources: ["*"], |
| 128 | + actions: ['secretsmanager:GetSecretValue'], |
| 129 | + conditions: {'ForAnyValue:StringLike':{'secretsmanager:SecretId': '*cloudmapper-slack-webhook*'}} |
| 130 | + })); |
| 131 | + |
| 132 | + // Create rule to trigger this be run every 24 hours |
| 133 | + new events.Rule(this, "scheduled_run", { |
| 134 | + ruleName: "cloudmapper_scheduler", |
| 135 | + // Run at 2am EST (6am UTC) every night |
| 136 | + schedule: events.Schedule.expression("cron(0 6 * * ? *)"), |
| 137 | + description: "Starts the CloudMapper auditing task every night", |
| 138 | + targets: [new targets.EcsTask({ |
| 139 | + cluster: cluster, |
| 140 | + taskDefinition: taskDefinition, |
| 141 | + subnetSelection: {subnetType: ec2.SubnetType.PUBLIC} |
| 142 | + })] |
| 143 | + }); |
| 144 | + |
| 145 | + // Create rule to trigger this manually |
| 146 | + new events.Rule(this, "manual_run", { |
| 147 | + ruleName: "cloudmapper_manual_run", |
| 148 | + eventPattern: {source: ['cloudmapper']}, |
| 149 | + description: "Allows CloudMapper auditing to be manually started", |
| 150 | + targets: [new targets.EcsTask({ |
| 151 | + cluster: cluster, |
| 152 | + taskDefinition: taskDefinition, |
| 153 | + subnetSelection: {subnetType: ec2.SubnetType.PUBLIC} |
| 154 | + })] |
| 155 | + }); |
| 156 | + |
| 157 | + // Create alarm for any errors |
| 158 | + const error_alarm = new cloudwatch.Alarm(this, "error_alarm", { |
| 159 | + metric: new cloudwatch.Metric({ |
| 160 | + namespace: 'cloudmapper', |
| 161 | + metricName: "errors", |
| 162 | + statistic: "Sum" |
| 163 | + }), |
| 164 | + threshold: 0, |
| 165 | + evaluationPeriods: 1, |
| 166 | + datapointsToAlarm: 1, |
| 167 | + treatMissingData: cloudwatch.TreatMissingData.NOT_BREACHING, |
| 168 | + alarmDescription: "Detect errors", |
| 169 | + alarmName: "cloudmapper_errors" |
| 170 | + }); |
| 171 | + |
| 172 | + // Create SNS for alarms to be sent to |
| 173 | + const sns_topic = new sns.Topic(this, 'cloudmapper_alarm', { |
| 174 | + displayName: 'cloudmapper_alarm' |
| 175 | + }); |
| 176 | + |
| 177 | + // Connect the alarm to the SNS |
| 178 | + error_alarm.addAlarmAction(new cloudwatch_actions.SnsAction(sns_topic)); |
| 179 | + |
| 180 | + // Create Lambda to forward alarms |
| 181 | + const alarm_forwarder = new lambda.Function(this, "alarm_forwarder", { |
| 182 | + runtime: lambda.Runtime.PYTHON_3_7, |
| 183 | + code: lambda.Code.asset("resources/alarm_forwarder"), |
| 184 | + handler: "main.handler", |
| 185 | + description: "Forwards alarms from the local SNS to another", |
| 186 | + logRetention: logs.RetentionDays.TWO_WEEKS, |
| 187 | + timeout: cdk.Duration.seconds(30), |
| 188 | + memorySize: 128, |
| 189 | + environment: { |
| 190 | + "ALARM_SNS": config['alarm_sns_arn'] |
| 191 | + }, |
| 192 | + }); |
| 193 | + |
| 194 | + // Add priv to publish the events so the alarms can be forwarded |
| 195 | + alarm_forwarder.addToRolePolicy(new iam.PolicyStatement({ |
| 196 | + resources: [config['alarm_sns_arn']], |
| 197 | + actions: ['sns:Publish'] |
| 198 | + })); |
| 199 | + |
| 200 | + // Connect the SNS to the Lambda |
| 201 | + sns_topic.addSubscription(new sns_subscription.LambdaSubscription(alarm_forwarder)); |
| 202 | + } |
| 203 | +} |
| 204 | + |
| 205 | +module.exports = { CloudmapperauditorStack } |
0 commit comments