├── .gitignore ├── CredentialCompromiseDetection-Kinesis-Template.yaml ├── CredentialCompromiseDetection-SQS-Template.yaml ├── LICENSE ├── README.md ├── Samples ├── Instance-Data.json └── sample-cw-event-sqs.json └── lambda ├── README.md ├── detect-SQS.py ├── detect-cwl.py ├── inventory.py └── update.sh /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | *Manifest.yaml 3 | test_event.json 4 | Attic/ 5 | 6 | # Byte-compiled / optimized / DLL files 7 | __pycache__/ 8 | *.py[cod] 9 | *$py.class 10 | 11 | # C extensions 12 | *.so 13 | 14 | # Distribution / packaging 15 | .Python 16 | build/ 17 | develop-eggs/ 18 | dist/ 19 | downloads/ 20 | eggs/ 21 | .eggs/ 22 | lib/ 23 | lib64/ 24 | parts/ 25 | sdist/ 26 | var/ 27 | wheels/ 28 | *.egg-info/ 29 | .installed.cfg 30 | *.egg 31 | MANIFEST 32 | 33 | # PyInstaller 34 | # Usually these files are written by a python script from a template 35 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 36 | *.manifest 37 | *.spec 38 | 39 | # Installer logs 40 | pip-log.txt 41 | pip-delete-this-directory.txt 42 | 43 | # Unit test / coverage reports 44 | htmlcov/ 45 | .tox/ 46 | .coverage 47 | .coverage.* 48 | .cache 49 | nosetests.xml 50 | coverage.xml 51 | *.cover 52 | .hypothesis/ 53 | .pytest_cache/ 54 | 55 | # Translations 56 | *.mo 57 | *.pot 58 | 59 | # Django stuff: 60 | *.log 61 | local_settings.py 62 | db.sqlite3 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # pyenv 81 | .python-version 82 | 83 | # celery beat schedule file 84 | celerybeat-schedule 85 | 86 | # SageMath parsed files 87 | *.sage.py 88 | 89 | # Environments 90 | .env 91 | .venv 92 | env/ 93 | venv/ 94 | ENV/ 95 | env.bak/ 96 | venv.bak/ 97 | 98 | # Spyder project settings 99 | .spyderproject 100 | .spyproject 101 | 102 | # Rope project settings 103 | .ropeproject 104 | 105 | # mkdocs documentation 106 | /site 107 | 108 | # mypy 109 | .mypy_cache/ 110 | 111 | 112 | # Created by https://www.gitignore.io/api/osx 113 | 114 | ### OSX ### 115 | *.DS_Store 116 | .AppleDouble 117 | .LSOverride 118 | 119 | # Icon must end with two \r 120 | Icon 121 | 122 | # Thumbnails 123 | ._* 124 | 125 | # Files that might appear in the root of a volume 126 | .DocumentRevisions-V100 127 | .fseventsd 128 | .Spotlight-V100 129 | .TemporaryItems 130 | .Trashes 131 | .VolumeIcon.icns 132 | .com.apple.timemachine.donotpresent 133 | 134 | # Directories potentially created on remote AFP share 135 | .AppleDB 136 | .AppleDesktop 137 | Network Trash Folder 138 | Temporary Items 139 | .apdisk -------------------------------------------------------------------------------- /CredentialCompromiseDetection-Kinesis-Template.yaml: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: '2010-09-09' 2 | Description: Template to detect credential compromise via CloudWatch Events and expected IPs. What's in Your CloudWatch? 3 | 4 | Parameters: 5 | 6 | pDebug: 7 | Description: Enable Debugging in CloudWatchLogs 8 | Type: String 9 | Default: False 10 | 11 | pObjectKey: 12 | Description: Name of the S3 Object in the bucket with the expected IPs. 13 | Type: String 14 | Default: Instance-Data.json 15 | 16 | pReservedConcurrentExecutions: 17 | Description: Number of concurrent executions for the detect functions 18 | Type: Number 19 | Default: 100 # 10% of default limit of 1000 20 | 21 | pTopicArn: 22 | Description: ARN of the Topic which to send events to 23 | Type: String 24 | 25 | pTopicRegion: 26 | Description: Region where the Topic is. 27 | Type: String 28 | 29 | pCloudTrailLogGroupName: 30 | Description: LogGroup in CloudWatch logs to get the CloudTrail events 31 | Type: String 32 | Default: "CloudTrail/DefaultLogGroup" 33 | 34 | Resources: 35 | 36 | Bucket: 37 | Type: AWS::S3::Bucket 38 | Properties: 39 | AccessControl: Private 40 | BucketEncryption: 41 | ServerSideEncryptionConfiguration: 42 | - ServerSideEncryptionByDefault: 43 | SSEAlgorithm: AES256 44 | PublicAccessBlockConfiguration: 45 | BlockPublicAcls: True 46 | BlockPublicPolicy: True 47 | IgnorePublicAcls: True 48 | RestrictPublicBuckets: True 49 | 50 | LambdaRole: 51 | Type: AWS::IAM::Role 52 | Properties: 53 | AssumeRolePolicyDocument: 54 | Version: '2012-10-17' 55 | Statement: 56 | - Effect: Allow 57 | Principal: 58 | Service: 59 | - lambda.amazonaws.com 60 | Action: 61 | - sts:AssumeRole 62 | Path: / 63 | ManagedPolicyArns: 64 | - arn:aws:iam::aws:policy/AmazonEC2ReadOnlyAccess 65 | Policies: 66 | - PolicyName: S3Access 67 | PolicyDocument: 68 | Version: '2012-10-17' 69 | Statement: 70 | - Action: 71 | - s3:* 72 | Effect: Allow 73 | Resource: 74 | - !Join ['', ['arn:aws:s3:::', !Ref Bucket , /*]] 75 | - !Join ['', ['arn:aws:s3:::', !Ref Bucket ]] 76 | - Action: 77 | - s3:ListAllMyBuckets 78 | - s3:GetBucketLocation 79 | Effect: Allow 80 | Resource: '*' 81 | - PolicyName: LambdaLogging 82 | PolicyDocument: 83 | Version: '2012-10-17' 84 | Statement: 85 | - Resource: '*' 86 | Action: 87 | - logs:* 88 | Effect: Allow 89 | # - PolicyName: GetMessages 90 | # PolicyDocument: 91 | # Version: '2012-10-17' 92 | # Statement: 93 | # - Resource: !GetAtt CloudWatchEventQueue.Arn 94 | # Action: 95 | # - sqs:* 96 | # Effect: Allow 97 | - PolicyName: PublishEvents 98 | PolicyDocument: 99 | Version: '2012-10-17' 100 | Statement: 101 | - Resource: !Ref pTopicArn 102 | Action: 103 | - sns:publish 104 | Effect: Allow 105 | - PolicyName: ReadKineses 106 | PolicyDocument: 107 | Version: '2012-10-17' 108 | Statement: 109 | - Resource: !GetAtt CloudTrailStream.Arn 110 | Effect: Allow 111 | Action: 112 | - kinesis:DescribeStream 113 | - kinesis:DescribeStreamSummary 114 | - kinesis:GetRecords 115 | - kinesis:GetShardIterator 116 | - kinesis:ListShards 117 | - kinesis:ListStreams 118 | - kinesis:SubscribeToShard 119 | - logs:CreateLogGroup 120 | - logs:CreateLogStream 121 | - logs:PutLogEvent 122 | 123 | DetectFunction: 124 | Type: AWS::Lambda::Function 125 | Properties: 126 | FunctionName: !Sub "${AWS::StackName}-detect" 127 | Description: Compare Cloudtrail Event Source IP to expected values 128 | Handler: index.handler 129 | Runtime: python3.6 130 | Timeout: 60 131 | ReservedConcurrentExecutions: !Ref pReservedConcurrentExecutions 132 | Role: !GetAtt LambdaRole.Arn 133 | Code: 134 | ZipFile: !Sub | 135 | import boto3 136 | import re 137 | import json 138 | import os 139 | import base64 140 | import gzip 141 | 142 | import logging 143 | logger = logging.getLogger() 144 | logger.setLevel(logging.INFO) 145 | logging.getLogger('botocore').setLevel(logging.WARNING) 146 | logging.getLogger('boto3').setLevel(logging.WARNING) 147 | 148 | 149 | def handler(event, context): 150 | re_principal = re.compile(r'AR[^\:]+\:i\-[0-9a-z]+') 151 | instance_data = [] 152 | logger.debug(f"Event: {event}") 153 | 154 | try: 155 | logger.info(f"Received {len(event['Records'])} kinesis events") 156 | for record in event['Records']: 157 | cwl_str = gzip.decompress(base64.b64decode(record["kinesis"]["data"])) 158 | logger.debug(f"Log String: {cwl_str}") 159 | cwl_records = json.loads(cwl_str) 160 | if cwl_records['messageType'] != "DATA_MESSAGE": 161 | continue 162 | 163 | logger.info(f"Received {len(cwl_records['logEvents'])} CW Log events") 164 | for log_event in cwl_records['logEvents']: 165 | cwevent = json.loads(log_event['message']) 166 | 167 | if cwevent['eventType'] != "AwsApiCall": 168 | logger.debug(f"Got Event type that should have been filtered: {cwevent}") 169 | continue 170 | 171 | # Filter out stuff 172 | if "amazonaws.com" in cwevent['sourceIPAddress']: 173 | continue 174 | 175 | logger.debug("cwevent: {}".format(json.dumps(cwevent, sort_keys=True))) 176 | 177 | principal = cwevent['userIdentity']['principalId'] 178 | if not re_principal.match(principal): 179 | logger.debug(f"Principal {principal} is not an instance profile role. Skipping") 180 | continue 181 | 182 | if instance_data is not None: # Wait to get instance data till we need it 183 | instance_data = get_instance_data(os.environ['BUCKET'], os.environ['OBJECT']) 184 | 185 | # Extract the instance Id 186 | (role_id, instance_id) = principal.split(":") 187 | source_ip = cwevent['sourceIPAddress'] 188 | region = cwevent['awsRegion'] 189 | 190 | if instance_id not in instance_data['instances']: 191 | logger.info(f"Instance {instance_id} is not in my database of instances") 192 | send_event("InstanceMissing", cwevent, f"Instance {instance_id} is not in my database of instances", instance_id, source_ip, []) 193 | continue 194 | 195 | if source_ip in instance_data['instances'][instance_id]: 196 | logger.debug(f"Event is from expected IP: {cwevent}") 197 | continue 198 | 199 | if source_ip in instance_data['all_ips']: 200 | logger.info(f"Event is not from expected ip, but from an account IP: {cwevent}") 201 | continue 202 | 203 | logger.error(f"Event from IP {source_ip} for instance {instance_id} is not from expected addresses: {cwevent}") 204 | send_event("BadSource", cwevent, f"Event from IP {source_ip} for instance {instance_id} is not from expected addresses", instance_id, source_ip, instance_data['instances'][instance_id]) 205 | return(200) 206 | except Exception as e: 207 | logger.critical(f"Exception {e} processing") 208 | raise 209 | 210 | def send_event(eventtype, cwevent, message, instance_id, source_ip, expected_ips): 211 | try: 212 | client = boto3.client('sns', region_name=os.environ['TOPIC_REGION']) 213 | snsmessage = { 214 | 'type': eventtype, 215 | 'CloudTrailEvent': cwevent, 216 | 'message': message, 217 | 'expected_ips': expected_ips, 218 | 'instance_id': instance_id, 219 | 'uniq_id': f"{instance_id}-{source_ip}" # We can dedup events on this later 220 | } 221 | response = client.publish( 222 | TopicArn=os.environ['TOPICARN'], 223 | Message=json.dumps(snsmessage), 224 | Subject=f'Potential Credential Compromise for {instance_id}', 225 | ) 226 | except Exception as e: 227 | logger.critical(f"Unable to send message to SNS: {e} \n{snsmessage}") 228 | raise 229 | 230 | def get_instance_data(bucket, obj_key): 231 | '''get the object to index from S3 and return the parsed json''' 232 | s3 = boto3.client('s3') 233 | response = s3.get_object( 234 | Bucket=bucket, 235 | Key=obj_key 236 | ) 237 | return(json.loads(response['Body'].read())) 238 | ### END OF CODE ### 239 | 240 | Environment: 241 | Variables: 242 | BUCKET: !Ref Bucket 243 | OBJECT: !Ref pObjectKey 244 | DEBUG: !Ref pDebug 245 | TOPICARN: !Ref pTopicArn 246 | TOPIC_REGION: !Ref pTopicRegion 247 | # Tags inherited from Stack 248 | 249 | InventoryFunction: 250 | Type: AWS::Lambda::Function 251 | Properties: 252 | FunctionName: !Sub "${AWS::StackName}-inventory" 253 | Description: Collect Instance IPs and NatGateway Addresses 254 | Handler: index.handler 255 | Runtime: python3.6 256 | Timeout: 150 257 | MemorySize: 768 258 | Role: !GetAtt LambdaRole.Arn 259 | Code: 260 | ZipFile: !Sub | 261 | import boto3 262 | from botocore.exceptions import ClientError 263 | import json 264 | import os 265 | import datetime 266 | 267 | import logging 268 | logger = logging.getLogger() 269 | logger.setLevel(logging.INFO) 270 | logging.getLogger('botocore').setLevel(logging.WARNING) 271 | logging.getLogger('boto3').setLevel(logging.WARNING) 272 | 273 | 274 | def handler(event, context): 275 | 276 | output_json = {} 277 | output_json['instances'] = {} 278 | output_json['all_ips'] = [] 279 | output_json['nat_gateways'] = {} 280 | 281 | try: 282 | ec2_client = boto3.client('ec2') 283 | 284 | interfaces = get_all_interfaces(ec2_client) 285 | for eni in interfaces: 286 | if eni['InterfaceType'] != 'nat_gateway': 287 | continue 288 | if 'PublicIp' not in eni['Association']: 289 | continue 290 | 291 | if eni['VpcId'] not in output_json['nat_gateways']: # make it an array 292 | output_json['nat_gateways'][eni['VpcId']] = [] 293 | 294 | output_json['nat_gateways'][eni['VpcId']].append(eni['Association']['PublicIp']) 295 | output_json['all_ips'].append(eni['Association']['PublicIp']) 296 | 297 | for reservation in get_all_instances(ec2_client): 298 | for instance in reservation['Instances']: 299 | instance_id = instance['InstanceId'] 300 | vpc_id = instance['VpcId'] 301 | output_json['instances'][instance_id] = [] 302 | 303 | if 'PublicIpAddress' in instance: 304 | public_ip = instance['PublicIpAddress'] 305 | output_json['instances'][instance_id].append(public_ip) 306 | output_json['all_ips'].append(public_ip) 307 | 308 | if vpc_id in output_json['nat_gateways']: 309 | output_json['instances'][instance_id] += output_json['nat_gateways'][vpc_id] 310 | 311 | output_json['data_collected'] = str(datetime.datetime.now()) 312 | 313 | except ClientError as e: 314 | logger.critical("AWS Error getting info: {}".format(e)) 315 | raise 316 | except Exception as e: 317 | logger.critical("{}".format(e)) 318 | raise 319 | 320 | s3client = boto3.client('s3') 321 | try: 322 | s3client.put_object( 323 | Body=json.dumps(output_json, sort_keys=True, default=str, indent=2), 324 | Bucket=os.environ['BUCKET'], 325 | ContentType='application/json', 326 | Key=os.environ['OBJECT'], 327 | ) 328 | return(event) 329 | except ClientError as e: 330 | logger.error("Unable to save object {}: {}".format(os.environ['OBJECT'], e)) 331 | raise 332 | 333 | def get_all_instances(ec2_client): 334 | output = [] 335 | filters = [{'Name': 'instance-state-name', 'Values': ['running']}] 336 | response = ec2_client.describe_instances(Filters=filters) 337 | while 'NextToken' in response: 338 | output += response['Reservations'] 339 | response = ec2_client.describe_instances(Filters=filters, NextToken=response['NextToken']) 340 | output += response['Reservations'] 341 | return(output) 342 | 343 | 344 | def get_all_interfaces(ec2_client): 345 | interfaces = [] 346 | response = ec2_client.describe_network_interfaces() 347 | while 'NextToken' in response: # Gotta Catch 'em all! 348 | interfaces += response['NetworkInterfaces'] 349 | response = ec2_client.describe_network_interfaces(NextToken=response['NextToken']) 350 | interfaces += response['NetworkInterfaces'] 351 | return(interfaces) 352 | ### END OF CODE ### 353 | Environment: 354 | Variables: 355 | BUCKET: !Ref Bucket 356 | OBJECT: !Ref pObjectKey 357 | DEBUG: !Ref pDebug 358 | # Tags inherited from Stack 359 | 360 | CloudTrailStream: 361 | Type: AWS::Kinesis::Stream 362 | Properties: 363 | RetentionPeriodHours: 24 364 | ShardCount: 1 365 | StreamEncryption: 366 | EncryptionType: KMS 367 | KeyId: alias/aws/kinesis 368 | 369 | CloudTrailSubscriptionFilter: 370 | Type: AWS::Logs::SubscriptionFilter 371 | Properties: 372 | DestinationArn: !GetAtt CloudTrailStream.Arn 373 | FilterPattern: "{($.userIdentity.type = AssumedRole) && ($.eventType = AwsApiCall) && ($.sourceIPAddress != *.amazonaws.com)}" 374 | LogGroupName: !Ref pCloudTrailLogGroupName 375 | RoleArn: !GetAtt LogsInvokeKinesisRole.Arn 376 | 377 | LogsInvokeKinesisRole: 378 | Type: AWS::IAM::Role 379 | Properties: 380 | AssumeRolePolicyDocument: 381 | Version: '2012-10-17' 382 | Statement: 383 | - Effect: Allow 384 | Principal: 385 | Service: 386 | - events.amazonaws.com 387 | - !Sub logs.${AWS::Region}.amazonaws.com 388 | Action: 389 | - sts:AssumeRole 390 | Path: / 391 | Policies: 392 | - PolicyName: KinesisPut 393 | PolicyDocument: 394 | Version: '2012-10-17' 395 | Statement: 396 | - Action: 397 | - kinesis:PutRecord 398 | - kinesis:PutRecords 399 | Effect: Allow 400 | Resource: 401 | - !GetAtt CloudTrailStream.Arn 402 | 403 | DetectFunctionMapping: 404 | Type: AWS::Lambda::EventSourceMapping 405 | Properties: 406 | BatchSize: 20 407 | Enabled: True # FIXME !Ref pState 408 | EventSourceArn: !GetAtt CloudTrailStream.Arn 409 | FunctionName: !GetAtt DetectFunction.Arn 410 | StartingPosition: LATEST 411 | 412 | TriggerInventoryRule: 413 | Type: "AWS::Events::Rule" 414 | Properties: 415 | Description: !Sub "${AWS::StackName} Trigger gathering of IP Addresses" 416 | ScheduleExpression: rate(10 minutes) 417 | Targets: 418 | - Arn: !GetAtt InventoryFunction.Arn 419 | Id: TargetFunctionV1 420 | 421 | InventoryLambdaPermission: 422 | Type: AWS::Lambda::Permission 423 | Properties: 424 | FunctionName: !GetAtt InventoryFunction.Arn 425 | Principal: events.amazonaws.com 426 | SourceArn: !GetAtt TriggerInventoryRule.Arn 427 | Action: lambda:invokeFunction 428 | 429 | Outputs: 430 | StackName: 431 | Description: Name of this Stack 432 | Value: !Ref AWS::StackName 433 | 434 | TemplateVersion: 435 | Description: Version of this CFT 436 | Value: 0.0.1 -------------------------------------------------------------------------------- /CredentialCompromiseDetection-SQS-Template.yaml: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: '2010-09-09' 2 | Description: Template to detect credential compromise via CloudWatch Events and expected IPs. What's in Your CloudWatch? 3 | 4 | Parameters: 5 | 6 | pDebug: 7 | Description: Enable Debugging in CloudWatchLogs 8 | Type: String 9 | Default: False 10 | 11 | pObjectKey: 12 | Description: Name of the S3 Object in the bucket with the expected IPs. 13 | Type: String 14 | Default: Instance-Data.json 15 | 16 | pReservedConcurrentExecutions: 17 | Description: Number of concurrent executions for the detect functions 18 | Type: Number 19 | Default: 100 # 10% of default limit of 1000 20 | 21 | pState: 22 | Description: Enable the CloudWatch Event 23 | Type: String 24 | Default: DISABLED 25 | AllowedValues: 26 | - DISABLED 27 | - ENABLED 28 | 29 | pTopicArn: 30 | Description: ARN of the Topic which to send events to 31 | Type: String 32 | 33 | pTopicRegion: 34 | Description: Region where the Topic is. 35 | Type: String 36 | 37 | Resources: 38 | 39 | Bucket: 40 | Type: AWS::S3::Bucket 41 | Properties: 42 | AccessControl: Private 43 | BucketEncryption: 44 | ServerSideEncryptionConfiguration: 45 | - ServerSideEncryptionByDefault: 46 | SSEAlgorithm: AES256 47 | PublicAccessBlockConfiguration: 48 | BlockPublicAcls: True 49 | BlockPublicPolicy: True 50 | IgnorePublicAcls: True 51 | RestrictPublicBuckets: True 52 | 53 | LambdaRole: 54 | Type: AWS::IAM::Role 55 | Properties: 56 | AssumeRolePolicyDocument: 57 | Version: '2012-10-17' 58 | Statement: 59 | - Effect: Allow 60 | Principal: 61 | Service: 62 | - lambda.amazonaws.com 63 | Action: 64 | - sts:AssumeRole 65 | Path: / 66 | ManagedPolicyArns: 67 | - arn:aws:iam::aws:policy/AmazonEC2ReadOnlyAccess 68 | Policies: 69 | - PolicyName: S3Access 70 | PolicyDocument: 71 | Version: '2012-10-17' 72 | Statement: 73 | - Action: 74 | - s3:* 75 | Effect: Allow 76 | Resource: 77 | - !Join ['', ['arn:aws:s3:::', !Ref Bucket , /*]] 78 | - !Join ['', ['arn:aws:s3:::', !Ref Bucket ]] 79 | - Action: 80 | - s3:ListAllMyBuckets 81 | - s3:GetBucketLocation 82 | Effect: Allow 83 | Resource: '*' 84 | - PolicyName: LambdaLogging 85 | PolicyDocument: 86 | Version: '2012-10-17' 87 | Statement: 88 | - Resource: '*' 89 | Action: 90 | - logs:* 91 | Effect: Allow 92 | - PolicyName: GetMessages 93 | PolicyDocument: 94 | Version: '2012-10-17' 95 | Statement: 96 | - Resource: !GetAtt CloudWatchEventQueue.Arn 97 | Action: 98 | - sqs:* 99 | Effect: Allow 100 | - PolicyName: PublishEvents 101 | PolicyDocument: 102 | Version: '2012-10-17' 103 | Statement: 104 | - Resource: !Ref pTopicArn 105 | Action: 106 | - sns:publish 107 | Effect: Allow 108 | 109 | DetectFunction: 110 | Type: AWS::Lambda::Function 111 | Properties: 112 | FunctionName: !Sub "${AWS::StackName}-detect" 113 | Description: Compare Cloudtrail Event Source IP to expected values 114 | Handler: index.handler 115 | Runtime: python3.6 116 | Timeout: 60 117 | ReservedConcurrentExecutions: !Ref pReservedConcurrentExecutions 118 | Role: !GetAtt LambdaRole.Arn 119 | Code: 120 | ZipFile: !Sub | 121 | import boto3 122 | import re 123 | import json 124 | import os 125 | 126 | import logging 127 | logger = logging.getLogger() 128 | logger.setLevel(logging.INFO) 129 | logging.getLogger('botocore').setLevel(logging.WARNING) 130 | logging.getLogger('boto3').setLevel(logging.WARNING) 131 | 132 | 133 | def handler(event, context): 134 | if 'DEBUG' in os.environ and os.environ['DEBUG'] == "True": 135 | logger.setLevel(logging.DEBUG) 136 | re_principal = re.compile(r'AR[^\:]+\:i\-[0-9a-z]+') 137 | instance_data = [] 138 | 139 | try: 140 | for record in event['Records']: 141 | cwevent = json.loads(record['body']) 142 | 143 | # Filter out stuff 144 | if (cwevent['detail']['userIdentity']['accessKeyId'] == os.environ['AWS_ACCESS_KEY_ID'] or 145 | cwevent['detail']['userIdentity']['type'] == "AWSService" or 146 | "amazonaws.com" in cwevent['detail']['sourceIPAddress']): 147 | if len(event['Records']) == 1: 148 | return(200) 149 | else: 150 | continue 151 | 152 | logger.debug("cwevent: {}".format(json.dumps(cwevent, sort_keys=True))) 153 | 154 | principal = cwevent['detail']['userIdentity']['principalId'] 155 | if not re_principal.match(principal): 156 | logger.debug(f"Principal {principal} is not an instance profile role. Skipping") 157 | continue 158 | 159 | if instance_data is not None: # Wait to get instance data till we need it 160 | instance_data = get_instance_data(os.environ['BUCKET'], os.environ['OBJECT']) 161 | 162 | # Extract the instance Id 163 | (role_id, instance_id) = principal.split(":") 164 | source_ip = cwevent['detail']['sourceIPAddress'] 165 | region = cwevent['detail']['awsRegion'] 166 | 167 | if instance_id not in instance_data['instances']: 168 | logger.info(f"Instance {instance_id} is not in my database of instances") 169 | send_event("InstanceMissing", cwevent, f"Instance {instance_id} is not in my database of instances", instance_id, source_ip, []) 170 | continue 171 | 172 | if source_ip in instance_data['instances'][instance_id]: 173 | logger.debug(f"Event is from expected IP: {cwevent}") 174 | continue 175 | 176 | if source_ip in instance_data['all_ips']: 177 | logger.info(f"Event is not from expected ip, but from an account IP: {cwevent}") 178 | continue 179 | 180 | logger.error(f"Event from IP {source_ip} for instance {instance_id} is not from expected addresses: {cwevent}") 181 | send_event("BadSource", cwevent, f"Event from IP {source_ip} for instance {instance_id} is not from expected addresses", instance_id, source_ip, instance_data['instances'][instance_id]) 182 | 183 | logger.debug(f"Received {len(event['Records'])} events") 184 | return(200) 185 | except Exception as e: 186 | logger.critical(f"Exception {e} processing cwevent {cwevent}") 187 | return(200) # Return for a good status so we purge the bad event 188 | 189 | 190 | def send_event(eventtype, cwevent, message, instance_id, source_ip, expected_ips): 191 | try: 192 | client = boto3.client('sns', region_name=os.environ['TOPIC_REGION']) 193 | snsmessage = { 194 | 'type': eventtype, 195 | 'CloudTrailEvent': cwevent, 196 | 'message': message, 197 | 'expected_ips': expected_ips, 198 | 'instance_id': instance_id, 199 | 'uniq_id': f"{instance_id}-{source_ip}" # We can dedup events on this later 200 | } 201 | response = client.publish( 202 | TopicArn=os.environ['TOPICARN'], 203 | Message=json.dumps(snsmessage), 204 | Subject=f'Potential Credential Compromise for {instance_id}', 205 | ) 206 | except Exception as e: 207 | logger.critical(f"Unable to send message to SNS: {e} \n{snsmessage}") 208 | raise 209 | 210 | def get_instance_data(bucket, obj_key): 211 | '''get the object to index from S3 and return the parsed json''' 212 | s3 = boto3.client('s3') 213 | response = s3.get_object( 214 | Bucket=bucket, 215 | Key=obj_key 216 | ) 217 | return(json.loads(response['Body'].read())) 218 | ### END OF CODE ### 219 | Environment: 220 | Variables: 221 | BUCKET: !Ref Bucket 222 | OBJECT: !Ref pObjectKey 223 | DEBUG: !Ref pDebug 224 | SQS_QUEUE_URL: !Ref CloudWatchEventQueue 225 | TOPICARN: !Ref pTopicArn 226 | TOPIC_REGION: !Ref pTopicRegion 227 | # Tags inherited from Stack 228 | 229 | InventoryFunction: 230 | Type: AWS::Lambda::Function 231 | Properties: 232 | FunctionName: !Sub "${AWS::StackName}-inventory" 233 | Description: Collect Instance IPs and NatGateway Addresses 234 | Handler: index.handler 235 | Runtime: python3.6 236 | Timeout: 150 237 | MemorySize: 768 238 | Role: !GetAtt LambdaRole.Arn 239 | Code: 240 | ZipFile: !Sub | 241 | import boto3 242 | from botocore.exceptions import ClientError 243 | import json 244 | import os 245 | import time 246 | import datetime 247 | from dateutil import tz 248 | 249 | import logging 250 | logger = logging.getLogger() 251 | logger.setLevel(logging.INFO) 252 | logging.getLogger('botocore').setLevel(logging.WARNING) 253 | logging.getLogger('boto3').setLevel(logging.WARNING) 254 | 255 | 256 | def handler(event, context): 257 | 258 | output_json = {} 259 | output_json['instances'] = {} 260 | output_json['all_ips'] = [] 261 | output_json['nat_gateways'] = {} 262 | 263 | try: 264 | regions = get_regions() 265 | for r in regions: 266 | ec2_client = boto3.client('ec2', region_name = r) 267 | 268 | interfaces = get_all_interfaces(ec2_client) 269 | for eni in interfaces: 270 | if eni['InterfaceType'] != 'nat_gateway': 271 | continue 272 | if 'PublicIp' not in eni['Association']: 273 | continue 274 | 275 | if eni['VpcId'] not in output_json['nat_gateways']: # make it an array 276 | output_json['nat_gateways'][eni['VpcId']] = [] 277 | 278 | output_json['nat_gateways'][eni['VpcId']].append(eni['Association']['PublicIp']) 279 | output_json['all_ips'].append(eni['Association']['PublicIp']) 280 | 281 | for reservation in get_all_instances(ec2_client): 282 | for instance in reservation['Instances']: 283 | instance_id = instance['InstanceId'] 284 | vpc_id = instance['VpcId'] 285 | output_json['instances'][instance_id] = [] 286 | 287 | if 'PublicIpAddress' in instance: 288 | public_ip = instance['PublicIpAddress'] 289 | output_json['instances'][instance_id].append(public_ip) 290 | output_json['all_ips'].append(public_ip) 291 | 292 | if vpc_id in output_json['nat_gateways']: 293 | output_json['instances'][instance_id] += output_json['nat_gateways'][vpc_id] 294 | 295 | 296 | output_json['data_collected'] = str(datetime.datetime.now()) 297 | 298 | except ClientError as e: 299 | logger.critical("AWS Error getting info: {}".format(e)) 300 | raise 301 | except Exception as e: 302 | logger.critical("{}".format(e)) 303 | raise 304 | 305 | s3client = boto3.client('s3') 306 | try: 307 | s3client.put_object( 308 | Body=json.dumps(output_json, sort_keys=True, default=str, indent=2), 309 | Bucket=os.environ['BUCKET'], 310 | ContentType='application/json', 311 | Key=os.environ['OBJECT'], 312 | ) 313 | return(event) 314 | except ClientError as e: 315 | logger.error("Unable to save object {}: {}".format(os.environ['OBJECT'], e)) 316 | raise 317 | 318 | 319 | def get_regions(): 320 | """Return an array of the regions this account is active in. Ordered with us-east-1 in the front.""" 321 | ec2 = boto3.client('ec2') 322 | response = ec2.describe_regions() 323 | output = ['us-east-1'] 324 | for r in response['Regions']: 325 | if r['RegionName'] == "us-east-1": 326 | continue 327 | output.append(r['RegionName']) 328 | return(output) 329 | 330 | 331 | def get_all_instances(ec2_client): 332 | output = [] 333 | filters = [{'Name': 'instance-state-name', 'Values': ['running']}] 334 | response = ec2_client.describe_instances(Filters=filters) 335 | while 'NextToken' in response: 336 | output += response['Reservations'] 337 | response = ec2_client.describe_instances(Filters=filters, NextToken=response['NextToken']) 338 | output += response['Reservations'] 339 | return(output) 340 | 341 | 342 | def get_all_interfaces(ec2_client): 343 | interfaces = [] 344 | response = ec2_client.describe_network_interfaces() 345 | while 'NextToken' in response: # Gotta Catch 'em all! 346 | interfaces += response['NetworkInterfaces'] 347 | response = ec2_client.describe_network_interfaces(NextToken=response['NextToken']) 348 | interfaces += response['NetworkInterfaces'] 349 | return(interfaces) 350 | ### END OF CODE ### 351 | Environment: 352 | Variables: 353 | BUCKET: !Ref Bucket 354 | OBJECT: !Ref pObjectKey 355 | DEBUG: !Ref pDebug 356 | SQS_QUEUE_URL: !Ref CloudWatchEventQueue 357 | # Tags inherited from Stack 358 | 359 | CloudWatchEventQueue: 360 | Type: AWS::SQS::Queue 361 | Properties: 362 | MessageRetentionPeriod: 3600 # Any messages older than an hour are probably out-of-date 363 | ReceiveMessageWaitTimeSeconds: 10 364 | # RedrivePolicy: 365 | # FIXME 366 | VisibilityTimeout: 300 367 | 368 | APIEventRule: 369 | Type: AWS::Events::Rule 370 | Properties: 371 | Description: !Sub "${AWS::StackName} Detect Credential Compromise" 372 | EventPattern: # this event pattern returns everything! 373 | detail: 374 | userIdentity: 375 | type: 376 | - "AssumedRole" 377 | account: 378 | - !Ref AWS::AccountId 379 | # RoleArn: String 380 | State: !Ref pState 381 | Targets: 382 | - Id: SendToSQS 383 | Arn: !GetAtt CloudWatchEventQueue.Arn 384 | # RoleArn: String 385 | 386 | CloudWatchEventQueuePolicy: 387 | Type: AWS::SQS::QueuePolicy 388 | Properties: 389 | Queues: 390 | - !Ref CloudWatchEventQueue 391 | PolicyDocument: 392 | Version: '2012-10-17' 393 | Id: AllowS3 394 | Statement: 395 | - Effect: Allow 396 | Principal: 397 | AWS: '*' 398 | Action: 399 | - SQS:SendMessage 400 | Resource: !GetAtt CloudWatchEventQueue.Arn 401 | Condition: 402 | ArnLike: 403 | aws:SourceArn: !GetAtt APIEventRule.Arn 404 | 405 | DetectFunctionMapping: 406 | Type: AWS::Lambda::EventSourceMapping 407 | Properties: 408 | BatchSize: 10 # 10 is Max 409 | Enabled: True 410 | EventSourceArn: !GetAtt CloudWatchEventQueue.Arn 411 | FunctionName: !GetAtt DetectFunction.Arn 412 | 413 | CloudWatchEventQueueAlarm: 414 | Type: AWS::CloudWatch::Alarm 415 | Properties: 416 | ActionsEnabled: True 417 | # AlarmActions: 418 | # - String 419 | AlarmDescription: "Alert when Queue doesn't properly drain" 420 | AlarmName: !Sub "${AWS::StackName}-EventQueueFull" 421 | ComparisonOperator: GreaterThanOrEqualToThreshold 422 | Dimensions: 423 | - Name: QueueName 424 | Value: !GetAtt CloudWatchEventQueue.QueueName 425 | EvaluationPeriods: 1 426 | MetricName: ApproximateNumberOfMessagesVisible 427 | Namespace: AWS/SQS 428 | # OKActions: 429 | # - String 430 | Period: 300 431 | Statistic: Average 432 | Threshold: 80000 433 | TreatMissingData: missing 434 | 435 | TriggerInventoryRule: 436 | Type: "AWS::Events::Rule" 437 | Properties: 438 | Description: !Sub "${AWS::StackName} Trigger gathering of IP Addresses" 439 | ScheduleExpression: rate(10 minutes) 440 | Targets: 441 | - Arn: !GetAtt InventoryFunction.Arn 442 | Id: TargetFunctionV1 443 | 444 | InventoryLambdaPermission: 445 | Type: AWS::Lambda::Permission 446 | Properties: 447 | FunctionName: !GetAtt InventoryFunction.Arn 448 | Principal: events.amazonaws.com 449 | SourceArn: !GetAtt TriggerInventoryRule.Arn 450 | Action: lambda:invokeFunction 451 | 452 | Outputs: 453 | StackName: 454 | Description: Name of this Stack 455 | Value: !Ref AWS::StackName 456 | 457 | CloudWatchEventQueueArn: 458 | Description: Arn of the SQS Queue S3 should send new events notifications to 459 | Value: !GetAtt CloudWatchEventQueue.Arn 460 | 461 | CloudWatchEventQueueUrl: 462 | Description: Arn of the SQS Queue S3 should send new events notifications to 463 | Value: !Ref CloudWatchEventQueue 464 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Detecting Credential Compromise 2 | CloudFormation Template and Lambda to detect if Instance Profile credentials are being used outside your AWS Account. 3 | 4 | What's in your CloudTrail? 5 | 6 | 7 | ## Motivation 8 | The running theory on the Capital One hack was the attacker exposed a SSRF in a Capital One instance, captured legitimate credentials from the EC2 MetaData service, and then used those credentials in another AWS account to exfiltrate 100m credit card applications from S3. 9 | 10 | While AWS GuardDuty has a detection for when Instance Profile credentials are used outside of AWS, it does not detect if the credentials are used outside of _your_ AWS account. 11 | 12 | ## What is this? 13 | 14 | This repo contains two CloudFormation Templates that will help to detect the usage of AWS IAM Instance profiles outside of the AWS Account to which they are assigned. 15 | 16 | The first template leverages SQS and CloudWatch Events and is designed for a small install with minimal activity and cost. This solution is regional and CloudWatch Events doesn't monitor Get* List* and Describe* events (which is what the Capital One hacker used to exfil data). 17 | 18 | The second template leverages Kinesis Streams and the CloudWatch Logs group that CloudTrail sends all events to. This template provides much greater coverage in that it covers all regions and read-only events (assuming CloudTrail is properly configured). The cost of the Kinesis stream starts at about $78/mo. 19 | 20 | ## How does it work 21 | 22 | An Inventory Lambda runs every 10 minutes and gathers up all the EC2 Instance PublicIps and all the VPC NatGateways in the account. This is saved to S3 and becomes the list of known IPs we'd expect an Instance Profile's API calls to originate from. 23 | 24 | The Kinesis Stream or SQS Queue invokes a Detection lambda that looks at the `sourceIPAddress` in the event and compares it to the list of expected IP addresses for the instance and in the AWS account. 25 | 26 | When the Lambda flags an issue, it will publish the message to an SNS Topic you specify as a parameter of the CF Template. This allows for the centralized gathering of these detected events and provides an easy way to push them to Slack, Splunk or just email. 27 | 28 | Events are filtered based on `userIdentity.type` being `AssumedRole`. Any `sourceIPAddress` that contains `*.amazonaws.com` are also excluded, as these are calls made by AWS on your behalf. 29 | 30 | 31 | ## Deployment 32 | 33 | 34 | 35 | ## Alerts 36 | This is the json we send to the SNS Topic 37 | ```json 38 | { 39 | "type": "BadSource", 40 | "message": "Event from IP 99.161.198.92 for instance i-088eFNORDBLAH is not from expected addresses", 41 | "expected_ips": [ 42 | "52.204.226.45" 43 | ], 44 | "instance_id": "i-088eFNORDBLAH", 45 | "uniq_id": "i-088eFNORDBLAH-99.161.198.92", 46 | "CloudTrailEvent": { 47 | "eventVersion": "1.05", 48 | "userIdentity": { 49 | "type": "AssumedRole", 50 | "principalId": "AROAIFNORD:i-088eFNORDBLAH", 51 | "arn": "arn:aws:sts::123456789012:assumed-role/pacu-instance-InstanceIamInstanceRole-1RSL9E7QA5QCI/i-088eFNORDBLAH", 52 | "accountId": "123456789012", 53 | "accessKeyId": "ASIAQ2AHBLAH", 54 | "sessionContext": { 55 | "attributes": { 56 | "mfaAuthenticated": "false", 57 | "creationDate": "2019-08-10T20:39:26Z" 58 | }, 59 | "sessionIssuer": { 60 | "type": "Role", 61 | "principalId": "AROAIFNORD", 62 | "arn": "arn:aws:iam::123456789012:role/pacu-instance-InstanceIamInstanceRole-1RSL9E7QA5QCI", 63 | "accountId": "123456789012", 64 | "userName": "pacu-instance-InstanceIamInstanceRole-1RSL9E7QA5QCI" 65 | } 66 | } 67 | }, 68 | "eventTime": "2019-08-11T01:25:22Z", 69 | "eventSource": "sts.amazonaws.com", 70 | "eventName": "GetCallerIdentity", 71 | "awsRegion": "us-east-1", 72 | "sourceIPAddress": "99.161.198.92", 73 | "userAgent": "aws-cli/1.16.190 Python/3.7.3 Darwin/16.7.0 botocore/1.12.180", 74 | "requestParameters": null, 75 | "responseElements": { 76 | }, 77 | "requestID": "e329713b-BLAH", 78 | "eventID": "5081622b-BLAH", 79 | "eventType": "AwsApiCall", 80 | "recipientAccountId": "123456789012" 81 | } 82 | } 83 | ``` 84 | 85 | The `uniq_id` is created to allow you to de-duplicate messages in your downstream processing engine. 86 | 87 | `type` can be: 88 | * `BadSource` - `SourceIPAddress` is not from the known list 89 | * `InstanceMissing` - The instance id in the request is not found in the inventory file 90 | 91 | ### False Positives 92 | 93 | - Perhaps EKS is doing something with these instance profiles from an AWS owned IP Space. I see a lot of `GetCallerIdentity` calls being flagged in EKS. 94 | 95 | 96 | ## Challenges 97 | 98 | There are a few challenges with this approach. This stack itself generates events and those events trigger this function. 99 | 100 | The Kinesis solution requires that CloudTrail is delivering to a CloudWatch Logs group, and each CloudWatch Logs group can have only one subscription filter and Kinesis stream. So if you're already doing something with your CloudTrail Events in CloudWatch logs, this solution won't work out of the box. 101 | 102 | When using CloudWatch Events, the pattern matching is not complex. I cannot use a regex to detect only Instance Profile credentials. As a result, there is less logging than would be desired, and the lambda will compare the event `accessKeyId` to it's own access key (via the AWS_ACCESS_KEY_ID environment variable), and stop processing the event without logging anything (because writing a log generates another cloudwatch API event). 103 | 104 | The Cloud Watch Event Pattern is: 105 | ```json 106 | { 107 | "account": [ 108 | "123456789012" 109 | ], 110 | "detail": { 111 | "userIdentity": { 112 | "type": [ 113 | "AssumedRole" 114 | ] 115 | } 116 | } 117 | } 118 | ``` 119 | Any advice on how to scope this down further to only capture Instance Profile triggered events would be desired (and would lower the invocation counts on Lambda) 120 | 121 | The CloudWatch Logs Filter is better: 122 | ``` 123 | {($.userIdentity.type = AssumedRole) && ($.eventType = AwsApiCall) && ($.sourceIPAddress != *.amazonaws.com)} 124 | ``` 125 | 126 | For both solutions a default reserve concurrency limit of 100 to prevent this function from throttling other functions in the region. 127 | 128 | 129 | 130 | ## Credit 131 | 132 | The initial idea for this tool was [Will Bengston](https://twitter.com/__muscles)'s 2018 post on [Detecting Credential Compromise in AWS](https://medium.com/netflix-techblog/netflix-cloud-security-detecting-credential-compromise-in-aws-9493d6fd373a) 133 | 134 | This tool is non-intrusive and doesn't require any enterprise tooling. My initial attempt to address the Capital One breach was to leverage a bunch of centralized enterprise tools. Once I took a step back to figure out how I'd protect my own AWS accounts, I realized I was trying to protect _everything_ rather than protecting _anything_. 135 | 136 | ## This solutions sucks, how do I really detect SSRF based Credential Compromise? 137 | 138 | Yup, this solution isn't ideal. However AWS provides minimal protections for the http://169.254.169.254/ metadata service. There are not required headers and there is no logging. 139 | 140 | Additionally, GuardDuty is limited to telling you if the credentials are used outside of AWS. The Capital One attacked bypassed GuardDuty by compromising someone else's account and using the credentials there. 141 | 142 | I'd recommend reaching out to your account team and asking AWS to improve both of these services. 143 | 144 | Will Bengston did publish another concept [Dynamically Locking AWS Credentials to Your Environment](https://medium.com/@williambengtson/active-defense-dynamically-locking-aws-credentials-to-your-environment-47a9c920e704) which injects Deny statements if they API calls are not coming from the known locations. Additionally, he proposes a Metadata service proxy that sits between the on-instance SDKs and the hypervisor based Metadata service. 145 | 146 | Both of these options require a significant re-engineering effort and regression testing before they can be pushed to production. 147 | -------------------------------------------------------------------------------- /Samples/Instance-Data.json: -------------------------------------------------------------------------------- 1 | { 2 | "all_ips": [ 3 | "nn.nn.nn.nn", 4 | "mm.mm.mm.mm", 5 | "aa.aa.aa.aa", 6 | "bb.bb.bb.bb" 7 | ], 8 | "data_collected": "2019-08-10 12:19:59.336394", 9 | "instances": { 10 | "i-00blah": [ 11 | "aa.aa.aa.aa" 12 | ], 13 | "i-00d1blah": [ 14 | "bb.bb.bb.bb", 15 | "nn.nn.nn.nn", 16 | "mm.mm.mm.mm" 17 | ] 18 | }, 19 | "nat_gateways": { 20 | "vpc-043fnord": [ 21 | "nn.nn.nn.nn", 22 | "mm.mm.mm.mm" 23 | ] 24 | } 25 | } -------------------------------------------------------------------------------- /Samples/sample-cw-event-sqs.json: -------------------------------------------------------------------------------- 1 | { 2 | "account": "123456789012", 3 | "detail": { 4 | "awsRegion": "us-east-1", 5 | "eventID": "24d7a595-4c20-46c1-8143-10b64055bf9f", 6 | "eventName": "ListObjects", 7 | "eventSource": "s3.amazonaws.com", 8 | "eventTime": "2019-08-10T13:04:25Z", 9 | "eventType": "AwsApiCall", 10 | "eventVersion": "1.05", 11 | "readOnly": true, 12 | "recipientAccountId": "123456789012", 13 | "requestID": "920733F68B653FDF", 14 | "requestParameters": { 15 | }, 16 | "resources": [ 17 | ], 18 | "responseElements": null, 19 | "sourceIPAddress": "54.52.68.192", 20 | "userAgent": "[Boto3/1.9.111 Python/3.7.4 Linux/4.14.77-70.59.amzn1.x86_64 Botocore/1.12.168 Resource]", 21 | "userIdentity": { 22 | "accessKeyId": "ASIAFNORD", 23 | "accountId": "123456789012", 24 | "arn": "arn:aws:sts::123456789012:assumed-role/ROLENAME/i-INSTANCEIDBLAH", 25 | "principalId": "AROAFNORD:i-INSTANCEIDBLAH", 26 | "sessionContext": { 27 | "attributes": { 28 | "creationDate": "2019-08-10T09:45:23Z", 29 | "mfaAuthenticated": "false" 30 | }, 31 | "sessionIssuer": { 32 | "accountId": "123456789012", 33 | "arn": "arn:aws:iam::123456789012:role/ROLENAME", 34 | "principalId": "AROAFNORD", 35 | "type": "Role", 36 | "userName": "ROLENAME" 37 | } 38 | }, 39 | "type": "AssumedRole" 40 | } 41 | }, 42 | "detail-type": "AWS API Call via CloudTrail", 43 | "id": "a6781eb2-f432-837e-1bd3-58540ad390f4", 44 | "region": "us-east-1", 45 | "resources": [], 46 | "source": "aws.s3", 47 | "time": "2019-08-10T13:04:25Z", 48 | "version": "0" 49 | } -------------------------------------------------------------------------------- /lambda/README.md: -------------------------------------------------------------------------------- 1 | # Lambda Directory 2 | 3 | For easy of install, the Lambda are embedded into the CloudFormation Templates. 4 | 5 | This directory contains the lambda code that can be edited and updated outside of Cloudformation and is for troubleshooting and development purposes -------------------------------------------------------------------------------- /lambda/detect-SQS.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | import re 3 | import json 4 | import os 5 | 6 | import logging 7 | logger = logging.getLogger() 8 | logger.setLevel(logging.INFO) 9 | logging.getLogger('botocore').setLevel(logging.WARNING) 10 | logging.getLogger('boto3').setLevel(logging.WARNING) 11 | 12 | 13 | def handler(event, context): 14 | if 'DEBUG' in os.environ and os.environ['DEBUG'] == "True": 15 | logger.setLevel(logging.DEBUG) 16 | re_principal = re.compile(r'AR[^\:]+\:i\-[0-9a-z]+') 17 | instance_data = [] 18 | 19 | try: 20 | for record in event['Records']: 21 | cwevent = json.loads(record['body']) 22 | 23 | # Filter out stuff 24 | if (cwevent['detail']['userIdentity']['accessKeyId'] == os.environ['AWS_ACCESS_KEY_ID'] or 25 | cwevent['detail']['userIdentity']['type'] == "AWSService" or 26 | "amazonaws.com" in cwevent['detail']['sourceIPAddress']): 27 | if len(event['Records']) == 1: 28 | return(200) 29 | else: 30 | continue 31 | 32 | logger.debug("cwevent: {}".format(json.dumps(cwevent, sort_keys=True))) 33 | 34 | principal = cwevent['detail']['userIdentity']['principalId'] 35 | if not re_principal.match(principal): 36 | logger.debug(f"Principal {principal} is not an instance profile role. Skipping") 37 | continue 38 | 39 | if instance_data is not None: # Wait to get instance data till we need it 40 | instance_data = get_instance_data(os.environ['BUCKET'], os.environ['OBJECT']) 41 | 42 | # Extract the instance Id 43 | (role_id, instance_id) = principal.split(":") 44 | source_ip = cwevent['detail']['sourceIPAddress'] 45 | region = cwevent['detail']['awsRegion'] 46 | 47 | if instance_id not in instance_data['instances']: 48 | logger.info(f"Instance {instance_id} is not in my database of instances") 49 | send_event("InstanceMissing", cwevent, f"Instance {instance_id} is not in my database of instances", instance_id, source_ip, []) 50 | continue 51 | 52 | if source_ip in instance_data['instances'][instance_id]: 53 | logger.debug(f"Event is from expected IP: {cwevent}") 54 | continue 55 | 56 | if source_ip in instance_data['all_ips']: 57 | logger.info(f"Event is not from expected ip, but from an account IP: {cwevent}") 58 | continue 59 | 60 | logger.error(f"Event from IP {source_ip} for instance {instance_id} is not from expected addresses: {cwevent}") 61 | send_event("BadSource", cwevent, f"Event from IP {source_ip} for instance {instance_id} is not from expected addresses", instance_id, source_ip, instance_data['instances'][instance_id]) 62 | 63 | logger.debug(f"Received {len(event['Records'])} events") 64 | return(200) 65 | except Exception as e: 66 | logger.critical(f"Exception {e} processing cwevent {cwevent}") 67 | return(200) # Return for a good status so we purge the bad event 68 | 69 | 70 | def send_event(eventtype, cwevent, message, instance_id, source_ip, expected_ips): 71 | try: 72 | client = boto3.client('sns', region_name=os.environ['TOPIC_REGION']) 73 | snsmessage = { 74 | 'type': eventtype, 75 | 'CloudTrailEvent': cwevent, 76 | 'message': message, 77 | 'expected_ips': expected_ips, 78 | 'instance_id': instance_id, 79 | 'uniq_id': f"{instance_id}-{source_ip}" # We can dedup events on this later 80 | } 81 | response = client.publish( 82 | TopicArn=os.environ['TOPICARN'], 83 | Message=json.dumps(snsmessage), 84 | Subject=f'Potential Credential Compromise for {instance_id}', 85 | ) 86 | except Exception as e: 87 | logger.critical(f"Unable to send message to SNS: {e} \n{snsmessage}") 88 | raise 89 | 90 | def get_instance_data(bucket, obj_key): 91 | '''get the object to index from S3 and return the parsed json''' 92 | s3 = boto3.client('s3') 93 | response = s3.get_object( 94 | Bucket=bucket, 95 | Key=obj_key 96 | ) 97 | return(json.loads(response['Body'].read())) 98 | ### END OF CODE ### 99 | 100 | 101 | ####################################################################################################################### 102 | # This exists for local testing 103 | if __name__ == '__main__': 104 | 105 | # Process Arguments 106 | import argparse 107 | parser = argparse.ArgumentParser() 108 | parser.add_argument("--debug", help="print debugging info", action='store_true') 109 | parser.add_argument("--error", help="print error info only", action='store_true') 110 | parser.add_argument("--bucket", help="Bucket with Instance Details", required=True) 111 | parser.add_argument("--object-key", help="Object Key with Instance Details", required=True) 112 | parser.add_argument("--event-file", help="Test Event File", required=True) 113 | 114 | args = parser.parse_args() 115 | 116 | # Logging idea stolen from: https://docs.python.org/3/howto/logging.html#configuring-logging 117 | # create console handler and set level to debug 118 | ch = logging.StreamHandler() 119 | if args.debug: 120 | ch.setLevel(logging.DEBUG) 121 | elif args.error: 122 | ch.setLevel(logging.ERROR) 123 | else: 124 | ch.setLevel(logging.INFO) 125 | # create formatter 126 | # formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') 127 | formatter = logging.Formatter('%(name)s - %(levelname)s - %(message)s') 128 | # add formatter to ch 129 | ch.setFormatter(formatter) 130 | # add ch to logger 131 | logger.addHandler(ch) 132 | 133 | f = open(args.event_file, "r") 134 | contents = f.read() 135 | 136 | event = json.loads(contents) 137 | 138 | os.environ['DEBUG'] = str(args.debug) 139 | os.environ['BUCKET'] = args.bucket 140 | os.environ['OBJECT'] = args.object_key 141 | 142 | # Wrap in a handler for Ctrl-C 143 | try: 144 | rc = handler(event, None) 145 | print("Lambda returned {}".format(rc)) 146 | except KeyboardInterrupt: 147 | exit(1) 148 | -------------------------------------------------------------------------------- /lambda/detect-cwl.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | import re 3 | import json 4 | import os 5 | import base64 6 | import gzip 7 | 8 | import logging 9 | logger = logging.getLogger() 10 | logger.setLevel(logging.INFO) 11 | logging.getLogger('botocore').setLevel(logging.WARNING) 12 | logging.getLogger('boto3').setLevel(logging.WARNING) 13 | 14 | 15 | def handler(event, context): 16 | re_principal = re.compile(r'AR[^\:]+\:i\-[0-9a-z]+') 17 | instance_data = [] 18 | logger.debug(f"Event: {event}") 19 | 20 | try: 21 | logger.info(f"Received {len(event['Records'])} kinesis events") 22 | for record in event['Records']: 23 | cwl_str = gzip.decompress(base64.b64decode(record["kinesis"]["data"])) 24 | logger.debug(f"Log String: {cwl_str}") 25 | cwl_records = json.loads(cwl_str) 26 | if cwl_records['messageType'] != "DATA_MESSAGE": 27 | continue 28 | 29 | logger.info(f"Received {len(cwl_records['logEvents'])} CW Log events") 30 | for log_event in cwl_records['logEvents']: 31 | cwevent = json.loads(log_event['message']) 32 | 33 | if cwevent['eventType'] != "AwsApiCall": 34 | logger.debug(f"Got Event type that should have been filtered: {cwevent}") 35 | continue 36 | 37 | # Filter out stuff 38 | if "amazonaws.com" in cwevent['sourceIPAddress']: 39 | continue 40 | 41 | logger.debug("cwevent: {}".format(json.dumps(cwevent, sort_keys=True))) 42 | 43 | principal = cwevent['userIdentity']['principalId'] 44 | if not re_principal.match(principal): 45 | logger.debug(f"Principal {principal} is not an instance profile role. Skipping") 46 | continue 47 | 48 | if instance_data is not None: # Wait to get instance data till we need it 49 | instance_data = get_instance_data(os.environ['BUCKET'], os.environ['OBJECT']) 50 | 51 | # Extract the instance Id 52 | (role_id, instance_id) = principal.split(":") 53 | source_ip = cwevent['sourceIPAddress'] 54 | region = cwevent['awsRegion'] 55 | 56 | if instance_id not in instance_data['instances']: 57 | logger.info(f"Instance {instance_id} is not in my database of instances") 58 | send_event("InstanceMissing", cwevent, f"Instance {instance_id} is not in my database of instances", instance_id, source_ip, []) 59 | continue 60 | 61 | if source_ip in instance_data['instances'][instance_id]: 62 | logger.debug(f"Event is from expected IP: {cwevent}") 63 | continue 64 | 65 | if source_ip in instance_data['all_ips']: 66 | logger.info(f"Event is not from expected ip, but from an account IP: {cwevent}") 67 | continue 68 | 69 | logger.error(f"Event from IP {source_ip} for instance {instance_id} is not from expected addresses: {cwevent}") 70 | send_event("BadSource", cwevent, f"Event from IP {source_ip} for instance {instance_id} is not from expected addresses", instance_id, source_ip, instance_data['instances'][instance_id]) 71 | return(200) 72 | except Exception as e: 73 | logger.critical(f"Exception {e} processing") 74 | raise 75 | 76 | def send_event(eventtype, cwevent, message, instance_id, source_ip, expected_ips): 77 | try: 78 | client = boto3.client('sns', region_name=os.environ['TOPIC_REGION']) 79 | snsmessage = { 80 | 'type': eventtype, 81 | 'CloudTrailEvent': cwevent, 82 | 'message': message, 83 | 'expected_ips': expected_ips, 84 | 'instance_id': instance_id, 85 | 'uniq_id': f"{instance_id}-{source_ip}" # We can dedup events on this later 86 | } 87 | response = client.publish( 88 | TopicArn=os.environ['TOPICARN'], 89 | Message=json.dumps(snsmessage), 90 | Subject=f'Potential Credential Compromise for {instance_id}', 91 | ) 92 | except Exception as e: 93 | logger.critical(f"Unable to send message to SNS: {e} \n{snsmessage}") 94 | raise 95 | 96 | def get_instance_data(bucket, obj_key): 97 | '''get the object to index from S3 and return the parsed json''' 98 | s3 = boto3.client('s3') 99 | response = s3.get_object( 100 | Bucket=bucket, 101 | Key=obj_key 102 | ) 103 | return(json.loads(response['Body'].read())) 104 | ### END OF CODE ### 105 | -------------------------------------------------------------------------------- /lambda/inventory.py: -------------------------------------------------------------------------------- 1 | import boto3 2 | from botocore.exceptions import ClientError 3 | import json 4 | import os 5 | import datetime 6 | 7 | import logging 8 | logger = logging.getLogger() 9 | logger.setLevel(logging.INFO) 10 | logging.getLogger('botocore').setLevel(logging.WARNING) 11 | logging.getLogger('boto3').setLevel(logging.WARNING) 12 | 13 | 14 | def handler(event, context): 15 | 16 | output_json = {} 17 | output_json['instances'] = {} 18 | output_json['all_ips'] = [] 19 | output_json['nat_gateways'] = {} 20 | 21 | try: 22 | ec2_client = boto3.client('ec2') 23 | 24 | interfaces = get_all_interfaces(ec2_client) 25 | for eni in interfaces: 26 | if eni['InterfaceType'] != 'nat_gateway': 27 | continue 28 | if 'PublicIp' not in eni['Association']: 29 | continue 30 | 31 | if eni['VpcId'] not in output_json['nat_gateways']: # make it an array 32 | output_json['nat_gateways'][eni['VpcId']] = [] 33 | 34 | output_json['nat_gateways'][eni['VpcId']].append(eni['Association']['PublicIp']) 35 | output_json['all_ips'].append(eni['Association']['PublicIp']) 36 | 37 | for reservation in get_all_instances(ec2_client): 38 | for instance in reservation['Instances']: 39 | instance_id = instance['InstanceId'] 40 | vpc_id = instance['VpcId'] 41 | output_json['instances'][instance_id] = [] 42 | 43 | if 'PublicIpAddress' in instance: 44 | public_ip = instance['PublicIpAddress'] 45 | output_json['instances'][instance_id].append(public_ip) 46 | output_json['all_ips'].append(public_ip) 47 | 48 | if vpc_id in output_json['nat_gateways']: 49 | output_json['instances'][instance_id] += output_json['nat_gateways'][vpc_id] 50 | 51 | output_json['data_collected'] = str(datetime.datetime.now()) 52 | 53 | except ClientError as e: 54 | logger.critical("AWS Error getting info: {}".format(e)) 55 | raise 56 | except Exception as e: 57 | logger.critical("{}".format(e)) 58 | raise 59 | 60 | s3client = boto3.client('s3') 61 | try: 62 | s3client.put_object( 63 | Body=json.dumps(output_json, sort_keys=True, default=str, indent=2), 64 | Bucket=os.environ['BUCKET'], 65 | ContentType='application/json', 66 | Key=os.environ['OBJECT'], 67 | ) 68 | return(event) 69 | except ClientError as e: 70 | logger.error("Unable to save object {}: {}".format(os.environ['OBJECT'], e)) 71 | raise 72 | 73 | def get_all_instances(ec2_client): 74 | output = [] 75 | filters = [{'Name': 'instance-state-name', 'Values': ['running']}] 76 | response = ec2_client.describe_instances(Filters=filters) 77 | while 'NextToken' in response: 78 | output += response['Reservations'] 79 | response = ec2_client.describe_instances(Filters=filters, NextToken=response['NextToken']) 80 | output += response['Reservations'] 81 | return(output) 82 | 83 | 84 | def get_all_interfaces(ec2_client): 85 | interfaces = [] 86 | response = ec2_client.describe_network_interfaces() 87 | while 'NextToken' in response: # Gotta Catch 'em all! 88 | interfaces += response['NetworkInterfaces'] 89 | response = ec2_client.describe_network_interfaces(NextToken=response['NextToken']) 90 | interfaces += response['NetworkInterfaces'] 91 | return(interfaces) 92 | ### END OF CODE ### 93 | 94 | 95 | ####################################################################################################################### 96 | # This exists for local testing 97 | if __name__ == '__main__': 98 | 99 | # Process Arguments 100 | import argparse 101 | parser = argparse.ArgumentParser() 102 | parser.add_argument("--debug", help="print debugging info", action='store_true') 103 | parser.add_argument("--error", help="print error info only", action='store_true') 104 | parser.add_argument("--bucket", help="Bucket with Instance Details", required=True) 105 | parser.add_argument("--object-key", help="Object Key with Instance Details", required=True) 106 | 107 | 108 | args = parser.parse_args() 109 | 110 | # Logging idea stolen from: https://docs.python.org/3/howto/logging.html#configuring-logging 111 | # create console handler and set level to debug 112 | ch = logging.StreamHandler() 113 | if args.debug: 114 | ch.setLevel(logging.DEBUG) 115 | elif args.error: 116 | ch.setLevel(logging.ERROR) 117 | else: 118 | ch.setLevel(logging.INFO) 119 | # create formatter 120 | # formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') 121 | formatter = logging.Formatter('%(name)s - %(levelname)s - %(message)s') 122 | # add formatter to ch 123 | ch.setFormatter(formatter) 124 | # add ch to logger 125 | logger.addHandler(ch) 126 | 127 | event = {} 128 | 129 | if args.debug: 130 | os.environ['DEBUG'] = str(args.debug) 131 | os.environ['BUCKET'] = args.bucket 132 | os.environ['OBJECT'] = args.object_key 133 | 134 | # Wrap in a handler for Ctrl-C 135 | try: 136 | rc = handler(event, None) 137 | print("Lambda returned {}".format(rc)) 138 | except KeyboardInterrupt: 139 | exit(1) -------------------------------------------------------------------------------- /lambda/update.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | STACK=$1 4 | FUNC=$2 5 | 6 | if [ -z $FUNC ] ; then 7 | echo "Usage: $0 " 8 | echo "Where function can be 'inventory' or 'sqs' or 'cwl'" 9 | exit 1 10 | fi 11 | 12 | if [ $FUNC == "sqs" ] ; then 13 | cp detect-SQS.py index.py 14 | zip -r upload.zip index.py 15 | aws lambda update-function-code --function-name ${STACK}-detect --zip-file fileb://upload.zip 16 | rm index.py upload.zip 17 | fi 18 | 19 | if [ $FUNC == "inventory" ] ; then 20 | cp inventory.py index.py 21 | zip -r upload.zip index.py 22 | aws lambda update-function-code --function-name ${STACK}-inventory --zip-file fileb://upload.zip 23 | rm index.py upload.zip 24 | fi 25 | 26 | # if [ $FUNC == "kinesis" ] ; then 27 | # cp detect-kinesis.py index.py 28 | # zip -r upload.zip index.py 29 | # aws lambda update-function-code --function-name ${STACK}-detect --zip-file fileb://upload.zip 30 | # rm index.py upload.zip 31 | # fi 32 | 33 | 34 | if [ $FUNC == "cwl" ] ; then 35 | cp detect-cwl.py index.py 36 | zip -r upload.zip index.py 37 | aws lambda update-function-code --function-name ${STACK}-detect --zip-file fileb://upload.zip 38 | rm index.py upload.zip 39 | fi --------------------------------------------------------------------------------