def get_account(account): if account.isdigit() and len(account) == 12: mode = 'account' else: mode = 'alias' aws_accounts = AwsAccounts() if mode == 'account': response = aws_accounts.with_number(account) print("[D] alias/account: %s" % str(account)) if response is None: return "", 404 else: return extract_data_from_item(response) else: alias = account response = aws_accounts.with_alias(alias) if response is None: return "", 404 else: return extract_data_from_item(response)
def get_instance(account, instance, region='us-east-1'): mode = 'account' if not (account.isdigit() and len(account) == 12): alias = account mode = 'alias' aws_accounts = AwsAccounts() if mode == 'alias': account_item = aws_accounts.with_alias(alias) elif mode == 'account': print("Account mode") account_item = aws_accounts.with_number(account) else: print("Error: Invalid option") raise Exception("Error: Invalid option") if account_item: session = boto3.session.Session(region_name=region) assume = rolesession.assume_crossact_audit_role( session, account_item['accountNum'], region) ec2 = assume.client('ec2') try: instance_description = ec2.describe_instances( InstanceIds=[instance]) instance_info = \ instance_description['Reservations'][0]['Instances'][0] except: print("Instance not found") return dict( Account=dict(accountNum=account_item['accountNum']), Instance=dict(message='Instance not found')), 404 public_ip = instance_info.get('PublicIpAddress') subnet_id = instance_info.get('SubnetId') route_tags = None try: # todo: The following line bombs if their are no # explicit route tables.. Seems like a bug describe_route_table_filter = [] if subnet_id: describe_route_table_filter.append( dict(Name='association.subnet-id', Values=[subnet_id])) ec2_describe_route_tables = ec2.describe_route_tables( Filters=describe_route_table_filter) route_info = ec2_describe_route_tables['RouteTables'][0] route_tags = route_info['Tags'] routes = route_info['Routes'] gateway_id = get_geteway_id(routes) except Exception as e: print("[X] No explicit route table found: %s" % e) gateway_id = None data_vpcid = instance_info.get('VpcId') route_filter = [dict(Name='association.main', Values=['true'])] if (data_vpcid): route_filter.append(dict(Name='vpc-id', Values=[data_vpcid])) route_table_description = ec2.describe_route_tables( Filters=route_filter) if len(route_table_description['RouteTables']) > 0: route_info = route_table_description['RouteTables'][0] route_tags = route_info['Tags'] routes = route_info['Routes'] try: gateway_id = get_geteway_id(routes) except: gateway_id = "" if gateway_id.startswith("igw-"): internet_facing = True else: internet_facing = False elb = assume.client('elb') load_balancers = elb.describe_load_balancers()[ 'LoadBalancerDescriptions'] instance_elb = [] for balancer in load_balancers: for elb_instance in balancer['Instances']: if elb_instance['InstanceId'] == instance: instance_elb.append(balancer['LoadBalancerName']) try: image_name = ec2.describe_images( ImageIds=[instance_info['ImageId']])['Images'][0]['Name'] except: image_name = None try: net_acl = ec2.describe_network_acls(Filters=[ dict(Name='association.subnet-id', Values=[subnet_id])])['NetworkAcls'][0]['NetworkAclId'] except: net_acl = None return dict( Account=dict(accountNum=account_item['accountNum']), Instance=dict( InstanceId=instance, ImageId=instance_info.get('ImageId'), ImageName=image_name, PublicDnsName=instance_info.get('PublicDnsName'), PublicIpAddress=public_ip, InternetFacing=internet_facing, ElasticLoadBalancer=instance_elb, PrivateIpAddress=instance_info.get('PrivateIpAddress'), InstanceType=instance_info['InstanceType'], SubnetId=subnet_id, SecurityGroups=instance_info.get('SecurityGroups'), Tags=(instance_info.get('Tags')), NetworkACL=net_acl, CreateDate=json.dumps(instance_info['LaunchTime'], cls=MyEncoder), Region=region), Routes=dict( GatewayId=gateway_id, Tags=route_tags)) else: print('{"message":"Account not found"}') return dict(Message='Account not found'), 404
def get_elb(account, elb, region): aws_accounts = AwsAccounts() if account.isdigit() and len(account) == 12: account = account else: alias = account account = aws_accounts.with_alias(alias)['accountNum'] if not (account.isdigit() and len(account) == 12): return dict(Error='Account not found'), 404 session = boto3.session.Session(region_name=region) assume = rolesession.assume_crossact_audit_role(session, account, region) client = assume.client('elb') try: elb_info = client.describe_load_balancers( LoadBalancerNames=[elb])['LoadBalancerDescriptions'][0] except: return dict(Account=dict(accountNum=account), LoadBalancer=dict(message='ELB not found')), 404 elb_dns = elb_info['DNSName'] # elb_listeners = elb_info['ListenerDescriptions'] elb_subnets = elb_info['Subnets'] elb_vpc = elb_info['VPCId'] elb_instances = elb_info['Instances'] elb_sg = elb_info['SecurityGroups'] ec2 = assume.client('ec2') try: route_info = ec2.describe_route_tables( Filters=[dict(Name='association.subnet-id', Values=elb_subnets) ])['RouteTables'] gatewayid = None nat_gatewayid = None print(route_info) for route_table in route_info: routes = route_table['Routes'] for route in routes: try: if route['DestinationCidrBlock'] == '0.0.0.0/0': try: gatewayid = route['GatewayId'] except: nat_gatewayid = route['NatGatewayId'] except Exception: pass except Exception as e: print(e) gatewayid = None nat_gatewayid = None route_info = ec2.describe_route_tables()['RouteTables'][0] # todo: This follow code is definitely wrong - check route_table for route_table in route_info: routes = route_info['Routes'] for route in routes: try: if route['DestinationCidrBlock'] == '0.0.0.0/0': try: gatewayid = route['GatewayId'] except: nat_gatewayid = route['NatGatewayId'] except Exception as e: pass if gatewayid: if gatewayid.startswith("igw-"): internet_facing = True else: internet_facing = False else: gatewayid = nat_gatewayid internet_facing = False return dict(Account=dict(AccountNum=account), LoadBalancer=dict(ELBName=elb, DNSName=elb_dns, Subnets=elb_subnets, VpcId=elb_vpc, InternetFacing=internet_facing, SecurityGroups=elb_sg, Region=region), Routes=dict(GatewayId=gatewayid), Instances=elb_instances)
def get_user(account, user): """ Grab metadata about a particular AWS user in an AWS account. :param account: AWS account :param user: AWS user to get """ aws_accounts = AwsAccounts() if not (account.isdigit() and len(account) == 12): account = aws_accounts.with_alias(account) if account: print "Account " + str(account) policies = [] # Create an assumed session and IAM client in single call session = boto3.session.Session() iam = rolesession.assume_crossact_audit_role(session, account, 'us-east-1').client('iam') try: if not user_exists(iam, user): final_data = dict(Account=dict(accountNum=account), User=dict(Username=user), Message='User not found') return final_data user_info = mp_wrappers.list_attached_user_policies( iam, user)['AttachedPolicies'] for pol_name in user_info: policies.append({"ManagedPolicy": pol_name['PolicyName']}) access_keys = [] access_key_info = iam.list_access_keys( UserName=user)['AccessKeyMetadata'] for access_key in access_key_info: last_used = iam.get_access_key_last_used( AccessKeyId=access_key['AccessKeyId'])['AccessKeyLastUsed'] try: last_used_date = last_used['LastUsedDate'].isoformat() except AttributeError: last_used_date = None access_keys.append( dict(KeyId=access_key['AccessKeyId'], Status=access_key['Status'], CreateDate=access_key['CreateDate'].isoformat(), LastUsed=last_used_date, LastService=last_used['ServiceName'], LastRegion=last_used['Region'])) except AttributeError as err: print "Exception: %s" % err final_data = dict(Account=dict(accountNum=account), Exception=dict(message=str(err))) return final_data final_data = dict( Account=dict(accountNum=account), User=dict(Username=user, CreateDate=user_create_date(iam, user), PasswordSet=bool( mp_wrappers.get_user( iam, user)['User'].get('PasswordLastUsed')), Policies=policies), AccessKeys=access_keys) return final_data else: # print('{"message":"Account not found"}') return [ dict(Message='Account not found'), ]
def get_user(account, user): aws_accounts = AwsAccounts() if not(account.isdigit() and len(account) == 12): alias = account account = aws_accounts.with_alias(alias) if account: print("Account "+str(account)) policies = [] session = boto3.session.Session() assume = rolesession.assume_crossact_audit_role( session, account, 'us-east-1') iam = assume.client('iam') try: try: #user_info = iam.list_user_policies(UserName=user)[ # 'PolicyNames'] user_info = mp_wrappers.list_user_policies(iam, user)['PolicyNames'] except Exception as e: print(e) final = dict(Account=dict(accountNum=account), User=dict(Username=user), Message='User not found'), 404 return final for pol_name in user_info: policy = iam.get_user_policy(UserName=user, PolicyName=pol_name) policies.append(policy['PolicyDocument']) print(policies) #user_info = iam.list_attached_user_policies(UserName=user)[ # 'AttachedPolicies'] user_info = mp_wrappers.list_attached_user_policies(iam, user)['AttachedPolicies'] for pol_name in user_info: policies.append({"ManagedPolicy": pol_name['PolicyName']}) #create_date = iam.get_user(UserName=user)['User'][ # 'CreateDate'].isoformat() create_date = mp_wrappers.get_user(iam, user)['User']['CreateDate'].isoformat() try: if user['PasswordLastUsed']: password_set = True else: password_set = False except: password_set = False access_keys = [] access_key_info = iam.list_access_keys(UserName=user)[ 'AccessKeyMetadata'] for access_key in access_key_info: last_used = iam.get_access_key_last_used( AccessKeyId=access_key['AccessKeyId'])[ 'AccessKeyLastUsed'] try: last_used_date = last_used['LastUsedDate'].isoformat() except: last_used_date = None last_used_service = last_used['ServiceName'] last_used_region = last_used['Region'] access_keys.append(dict( KeyId=access_key['AccessKeyId'], Status=access_key['Status'], CreateDate=access_key['CreateDate'].isoformat(), LastUsed=last_used_date, LastService=last_used_service, LastRegion=last_used_region)) except Exception as e: print("Exception: %s" % e) final = dict(Account=dict(accountNum=account), Exception=dict(message=e)) return final final = dict(Account=dict(accountNum=account), User=dict( Username=user, CreateDate=create_date, PasswordSet=password_set, Policies=policies), AccessKeys=access_keys) return final else: # print('{"message":"Account not found"}') return [dict(Message='Account not found'), ]