コード例 #1
0
def dashboard(role=None):
    start = time.time()
    instance_count = 0
    user_count = 0
    sg_count = 0
    elb_count = 0

    aws_accounts = AwsAccounts()
    accounts = aws_accounts.all()

    pool = Pool(10)
    results = pool.map(get_account_stats, accounts)
    pool.close()
    pool.join()
    for x in results:
        instance_count += x['InstanceCount']
        user_count += x['UserCount']
        sg_count += x['SecurityGroupCount']
        elb_count += x['ELBCount']

    end = time.time()
    result = dict(Time=(end - start),
                  Summary=dict(AccountsCount=len(accounts),
                               InstanceCount=instance_count,
                               UserCount=user_count,
                               SecurityGroupCount=sg_count,
                               ELBCount=elb_count))

    return result
コード例 #2
0
ファイル: getpublicips.py プロジェクト: webdog/bovine
def get_public_ips(function_name, account, region='us-east-1'):
    """ Get all public IP addresses from an AWS account
    :param account: AWS account
    :param region: AWS region
    """
    if not region:
        region = 'us-east-1'
    start = time.time()
    aws_accounts = AwsAccounts()
    if not account:
        # running for all accounts, fan out Lambdas to make it faster
        account_list = aws_accounts.all(attr=['accountNum', 'alias'])
        pool = Pool(10)
        account_map = []
        for acc in account_list:
            acc['region'] = region
            acc['function_name'] = function_name
            account_map.append(acc)
        results = pool.map(invoke_get_public_ips, account_map)
        pool.close()
        pool.join()
        address_data = [item for sublist in results for item in sublist]
        end = time.time()
    else:
        # running for a single account
        end = time.time()
        account_data = aws_accounts.with_number(account)
        address_data = query_for_account(account_data, region)
    return address_data, (end - start)
コード例 #3
0
def dashboard():
    """ Main dashboard function. Run stats across all accounts. """
    start = time.time()
    instance_count = 0
    user_count = 0
    sg_count = 0
    elb_count = 0

    aws_accounts = AwsAccounts()
    accounts = aws_accounts.all()

    pool = Pool(10)
    results = pool.map(get_account_stats, accounts)
    pool.close()
    pool.join()
    for acc_result in results:
        instance_count += acc_result['InstanceCount']
        user_count += acc_result['UserCount']
        sg_count += acc_result['SecurityGroupCount']
        elb_count += acc_result['ELBCount']

    end = time.time()
    result = dict(Time=(end - start),
                  Summary=dict(AccountsCount=len(accounts),
                               InstanceCount=instance_count,
                               UserCount=user_count,
                               SecurityGroupCount=sg_count,
                               ELBCount=elb_count))

    return result
コード例 #4
0
ファイル: getredshiftclusters.py プロジェクト: webdog/bovine
def get_redshift_clusters(account, region):
    """ Get all redshift clusters from all accounts. """
    redshift_data = []
    aws_accounts = AwsAccounts()
    accounts = aws_accounts.all()

    if not account:
        session = boto3.session.Session()
        for acc in accounts:
            alias = None
            assume = rolesession.assume_crossact_audit_role(
                session,
                acc['accountNum'],
                region)

            if assume:
                client = assume.client('redshift')
                redshift_list = mp_wrappers.describe_clusters(client)[
                    'Clusters']
                alias = acc.get('alias')

                for cluster in redshift_list:
                    redshift_data.append(
                        dict(Region=region,
                             ClusterId=(cluster['ClusterIdentifier']),
                             Username=(cluster['MasterUsername']),
                             DBName=(cluster['DBName']),
                             Endpoint=(cluster['Endpoint']),
                             PubliclyAccessible=(
                                 cluster['PubliclyAccessible']),
                             Encrypted=(cluster['Encrypted']),
                             AccountNum=acc['accountNum'],
                             AccountAlias=alias))
            else:
                pass
    elif account.isdigit() and len(account) == 12:
        session = boto3.session.Session()
        assume = rolesession.assume_crossact_audit_role(
            session,
            account,
            region)
        alias = None
        if assume:
            client = assume.client('redshift')
            redshift_list = mp_wrappers.describe_clusters(client)['Clusters']
            alias = account.get('alias')
            for cluster in redshift_list:
                redshift_data.append(
                    dict(Region=region,
                         ClusterId=(cluster['ClusterIdentifier']),
                         Username=(cluster['MasterUsername']),
                         DBName=(cluster['DBName']),
                         Endpoint=(cluster['Endpoint']),
                         PubliclyAccessible=(cluster['PubliclyAccessible']),
                         Encrypted=(cluster['Encrypted']),
                         AccountNum=account,
                         AccountAlias=alias))
    else:
        return dict(Error='Account not found'), 404
    return dict(Clusters=redshift_data), 200
コード例 #5
0
ファイル: instancecount.py プロジェクト: webdog/bovine
def ec2_count(function_name, account=None, region='us-east-1'):
    """ EC2 Instance count in an AWS account
    :param account: AWS account
    :param region: AWS region
    """
    start = time.time()
    instance_data = []
    if not account:
        aws_accounts = AwsAccounts()
        # running for all accounts, fan out Lambdas to make it faster
        account_list = aws_accounts.all(attr=['accountNum', 'alias'])
        account_map = []
        for acc in account_list:
            acc['region'] = region
            acc['function_name'] = function_name
            account_map.append(acc)
        pool = Pool(10)
        results = pool.map(invoke_instance_count, account_map)
        pool.close()
        pool.join()
        # Flatten the result
        instance_data = [item for sublist in results for item in sublist]
        end = time.time()
        return instance_data, (end - start)
    else:
        # running for a single account
        end = time.time()
        data = get_instance_count_for_account(account)
        return data, (end - start)
コード例 #6
0
def get_roles(account):
    start = time.time()
    user_data = []
    aws_accounts = AwsAccounts()
    if not account:
        # running for all accounts, fan out Lambdas to make it faster
        account_list = aws_accounts.all(attr=['accountNum', 'alias'])
        client = boto3.client('lambda')
        user_count = 0
        pool = Pool(10)
        account_map = []
        for account in account_list:
            account_map.append(account)
        results = pool.map(invoke_get_roles, account_map)
        pool.close()
        pool.join()
        role_data = [item for sublist in results for item in sublist]
        end = time.time()
        return role_data, (end - start)
    else:
        # running for a single account
        end = time.time()
        account_data = aws_accounts.with_number(account)
        data = get_roles_for_account(account_data)
        return data, (end - start)
コード例 #7
0
def instance_count(account=None, region='us-east-1'):
    start = time.time()
    instance_data = []
    if not account:
        aws_accounts = AwsAccounts()
        # running for all accounts, fan out Lambdas to make it faster
        account_list = aws_accounts.all(attr=['accountNum', 'alias'])
        account_map = []
        for account in account_list:
            account['region'] = region
            account_map.append(account)
        client = boto3.client('lambda')
        instance_count = 0
        pool = Pool(10)
        results = pool.map(invoke_instance_count, account_map)
        pool.close()
        pool.join()
        # Flatten the result
        instance_data = [item for sublist in results for item in sublist]
        end = time.time()
        final = dict(Summary=instance_data, Time=(end - start))
        return instance_data, (end - start)
    else:
        # running for a single account
        end = time.time()
        data = get_instance_count_for_account(account)
        return data, (end - start)
コード例 #8
0
def get_roles(function_name, account):
    """ Get IAM roles for all accounts.
    :param account: AWS account
    """
    start = time.time()
    aws_accounts = AwsAccounts()
    if not account:
        # running for all accounts, fan out Lambdas to make it faster
        account_list = aws_accounts.all(attr=['accountNum', 'alias'])
        pool = Pool(10)
        account_map = []
        for acc in account_list:
            acc['function_name'] = function_name
            account_map.append(acc)
        results = pool.map(invoke_get_roles, account_map)
        pool.close()
        pool.join()
        role_data = [item for sublist in results for item in sublist]
        end = time.time()
    else:
        # running for a single account
        end = time.time()
        account_data = aws_accounts.with_number(account)
        role_data = get_roles_for_account(account_data)
    return role_data, (end - start)
コード例 #9
0
ファイル: accountcount.py プロジェクト: patrickbrandt/bovine
def account_count():
    accounts = AwsAccounts()
    accounts_count = accounts.count()
    cred = dict(AccountsCount=accounts_count)
    final = dict(Summary=cred)
    print final
    return final
コード例 #10
0
def get_s3_buckets(account, region):
    if not region:
        region = 'us-east-1'
    start = time.time()
    s3_data = []
    aws_accounts = AwsAccounts()
    if not account:
        # running for all accounts, fan out Lambdas to make it faster
        account_list = aws_accounts.all(attr=['accountNum', 'alias'])
        client = boto3.client('lambda')
        pool = Pool(10)
        account_map = []
        for account in account_list:
            account['region'] = region
            account_map.append(account)
        results = pool.map(invoke_get_s3_buckets, account_map)
        pool.close()
        pool.join()
        s3_data = [item for sublist in results for item in sublist]
        end = time.time()
        return s3_data, (end - start)
    else:
        # running for a single account
        end = time.time()
        account_data = aws_accounts.with_number(account)
        data = get_s3_buckets_for_account(account_data, region)
        return data, (end - start)
コード例 #11
0
def get_user_count(function_name, account=None):
    """ Get user count for all accounts or a specific account.
    :param account: Account to get user count
    """
    start = time.time()
    user_data = []
    if not account:
        aws_accounts = AwsAccounts()
        # running for all accounts, fan out Lambdas to make it faster
        account_list = aws_accounts.all(attr=['accountNum', 'alias'])
        new_acc_list = []
        for acc in account_list:
            acc['function_name'] = function_name
            new_acc_list.append(acc)
        print new_acc_list
        pool = Pool(10)
        results = pool.map(invoke_user_count, new_acc_list)
        pool.close()
        pool.join()
        user_data = [item for sublist in results for item in sublist]
        end = time.time()
        final_data = dict(Summary=user_data, Time=(end - start))
        return final_data
    # running for a single account
    acc_data = get_usercount_for_account(account)
    return acc_data
コード例 #12
0
def add_account(account_info):
    if account_info['accountNum'].isdigit() and len(
            account_info['accountNum']) == 12:
        aws_accounts = AwsAccounts()
        return {"response": aws_accounts.add(account_info)}, 200
    else:
        return {"response:": "Incorrect account number given"}, 500
コード例 #13
0
def add_account(account_info):
    """ Add an acount to the AWS accounts table
    :param account_info: AWS account metadata - id, alias, owner, etc
    """
    if account_info['accountNum'].isdigit() and len(account_info['accountNum']) == 12:
        aws_accounts = AwsAccounts()
        return {"response": aws_accounts.add(account_info)}, 200
    return {"response:": "Incorrect account number given"}, 500
コード例 #14
0
def get_security_groups(account, region='us-east-1'):
    sg_data = []

    aws_accounts = AwsAccounts()
    accounts = aws_accounts.all()
    session = boto3.session.Session(region_name=region)

    if not account:
        for acc in accounts:
            if acc['accountNum']:
                assume = rolesession.assume_crossact_audit_role(
                    session, acc['accountNum'], region)
                if assume:
                    ec2 = assume.client('ec2')
                    security_groups = ec2.describe_security_groups(
                    )['SecurityGroups']

                    for group in security_groups:
                        sg_name = None
                        try:
                            for tag in group['Tags']:
                                if tag['Key'] == 'Name':
                                    sg_name = tag['Value']
                        except:
                            sg_name = None

                        sg_data.append(
                            dict(Region=region,
                                 GroupName=sg_name,
                                 GroupId=(group['GroupId']),
                                 AccountNum=acc['accountNum'],
                                 AccountAlias=acc['alias']))
    elif account.isdigit() and len(account) == 12:
        assume = rolesession.assume_crossact_audit_role(
            session, account, region)
        alias = aws_accounts.with_number(account)['alias']
        if assume:
            ec2 = assume.client('ec2')
            security_groups = ec2.describe_security_groups()['SecurityGroups']

            for group in security_groups:
                sg_name = None
                for tag in group['Tags']:
                    if tag['Key'] == 'Name':
                        sg_name = tag['Value']
                sg_id = group['GroupId']
                sg_data.append(
                    dict(GroupName=sg_name,
                         GroupId=sg_id,
                         AccountNum=account,
                         AccountAlias=alias))
    else:
        return (dict(Message='Account not found'), 404)
    # print(sg_data)
    return dict(SecurityGroups=sg_data), 200
コード例 #15
0
def get_dynamo_tables(account, region):
    """Provide an event that contains the following keys:
        -account: account to look in or all for all security groups
        -region: region to pull from
    """
    dynamo_data = []

    aws_accounts = AwsAccounts()
    if not account:
        accounts = aws_accounts.all()
        session = boto3.session.Session()
        for account in accounts:
            assume = rolesession.assume_crossact_audit_role(
                session, account['accountNum'], region)
            if assume:
                client = assume.client('dynamodb')
                dynamo_list = client.list_tables()['TableNames']

                for table in dynamo_list:
                    dynamo_data.append(
                        dict(Region=region,
                             TableName=table,
                             AccountNum=account['accountNum'],
                             AccountAlias=account['alias']))
            else:
                pass
    elif account.isdigit() and len(account) == 12:
        account_number = account
        accounts_matching = aws_accounts.with_number(account_number)
        alias = accounts_matching['alias']
        session = boto3.session.Session()
        assume = rolesession.assume_crossact_audit_role(
            session, account_number, region)
        if assume:
            account = aws_accounts.with_number(account_number)
            client = assume.client('dynamodb')
            dynamo_list = client.list_tables()['TableNames']
            for table in dynamo_list:
                dynamo_data.append(
                    dict(Region=region,
                         TableName=table,
                         AccountNum=account['accountNum'],
                         AccountAlias=account['alias']))
        else:
            print("[D] Assume: %s" % assume)
            return {"Error": "Unable to assume role"}, 500
    else:
        return dict(Error='Account not found.'), 404
    return dict(Tables=dynamo_data), 200
コード例 #16
0
ファイル: usercount.py プロジェクト: patrickbrandt/bovine
def get_user_count(account=None):
    start = time.time()
    user_data = []
    if not account:
        aws_accounts = AwsAccounts()
        # running for all accounts, fan out Lambdas to make it faster
        account_list = aws_accounts.all(attr=['accountNum', 'alias'])
        pool = Pool(10)
        results = pool.map(invoke_user_count, account_list)
        pool.close()
        pool.join()
        user_data = [item for sublist in results for item in sublist]
        end = time.time()
        final = dict(Summary=user_data, Time=(end - start))
        return final
    else:
        # running for a single account
        data = get_usercount_for_account(account)
        return data
コード例 #17
0
ファイル: getaccount.py プロジェクト: patrickbrandt/bovine
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)
コード例 #18
0
ファイル: getelbs.py プロジェクト: patrickbrandt/bovine
def get_elbs(account, region):
    global elb_data
    elb_data = []
    global accounts
    aws_accounts = AwsAccounts()

    if not account:
        session = boto3.session.Session(region_name=region)
        for account_rec in aws_accounts.all():
            elb_data.extend(
                query_elbs_for_account(account_rec, region, session))
    elif account.isdigit() and len(account) == 12:
        session = boto3.session.Session()
        aws_account = aws_accounts.with_number(account)
        if aws_account:
            elb_data.append(
                query_elbs_for_account(aws_account, region, session))
        else:
            return dict(Message="Account not found"), 404

    # print(elb_data)
    return dict(LoadBalancers=elb_data), 200
コード例 #19
0
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'), ]
コード例 #20
0
ファイル: getuser.py プロジェクト: webdog/bovine
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'),
        ]
コード例 #21
0
ファイル: getinstance.py プロジェクト: patrickbrandt/bovine
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
コード例 #22
0
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)
コード例 #23
0
def get_security_group(account, group, region):
    if account.isdigit() and len(account) == 12:
        account = account
        mode = 'account'
    else:
        alias = account
        mode = 'alias'

    aws_accounts = AwsAccounts()
    #This should have error handling for cases when the
    #alias/account does not exist.
    if mode == 'alias':
        account = aws_accounts.by_alias(alias)['accountNum']
    elif mode == 'account':
        print("Account mode")

    else:
        print('Error: Invalid option')
        raise Exception('Error: Invalid option')

    if account:
        session = boto3.session.Session(region_name=region)
        assume = rolesession.assume_crossact_audit_role(
            session, account, region)

        ec2 = assume.client('ec2')
        try:
            sg_info = ec2.describe_security_groups(
                GroupIds=[group])['SecurityGroups'][0]
        except Exception as e:
            print("Security group not found")
            return dict(Account=dict(accountNum=account),
                        Instance=dict(message='Security group not found'))

        print(sg_info)
        group_name = sg_info['GroupName']
        group_id = sg_info['GroupId']
        group_desc = sg_info['Description']
        group_tags = sg_info.get('Tags', None)

        group_ingress = format_inbound_rules(sg_info['IpPermissions'])
        group_egress = format_outbound_rules(sg_info['IpPermissionsEgress'])
        group_vpc = sg_info['VpcId']
        instance_data = []
        instance_info = ec2.describe_instances(
            Filters=[dict(Name='instance.group-id', Values=[group_id])])
        instances = instance_info['Reservations']
        for res in instances:
            instance_name = None
            for instance in res['Instances']:
                for tag in instance['Tags']:
                    if tag['Key'] == 'Name':
                        instance_name = tag.get('Value', None)
                        break

            instance_data.append(
                dict(Name=instance_name,
                     InstanceId=instance['InstanceId'],
                     AccountNum=account))

        client = assume.client('elb')
        elb_data = []
        elb_info = client.describe_load_balancers()['LoadBalancerDescriptions']
        for elb in elb_info:
            for sg in elb['SecurityGroups']:
                if sg == group_id:
                    elb_data.append(
                        dict(Name=elb['LoadBalancerName'], AccountNum=account))

        return dict(Account=dict(accountNum=account),
                    SecurityGroup=dict(GroupName=group_name,
                                       GroupId=group_id,
                                       Description=group_desc,
                                       Tags=group_tags,
                                       InboundRules=group_ingress,
                                       OutboundRules=group_egress,
                                       VpcId=group_vpc,
                                       Region=region),
                    Instances=instance_data,
                    ELB=elb_data)
    else:
        print('{"message":"Account not found"}')
        return [
            dict(Message='Account not found'),
        ]