'alert when a KMS master key contains a policy giving permissions
to a foreign account'

def check_for_kms_policy_with_foreign_account(self, kms_item):

    tag = '{0}    contains    policies    with    foreign    account    permissions.'.format(self.i_am_singular)
    key_account_id = kms_item.config.get('AWSAccountId')
    key_policies = kms_item.config.get('Policies')
    for policy in key_policies:
        for statement in policy.get('Statement'):
            condition_accounts = []
            if ('Condition' in statement):
                condition = statement.get('Condition')
                if condition:
                    condition_accounts = extract_condition_account_numbers(condition)
                cross_accounts = [account for account in condition_accounts if (account != key_account_id)]
                if cross_accounts:
                    notes = 'Condition    -    kms:CallerAccount:    {}'.format(json.dumps(cross_accounts))
                    self.add_issue(5, tag, kms_item, notes=notes)
            if (statement and statement.get('Principal')):
                aws_principal = statement.get('Principal')
                if isinstance(aws_principal, dict):
                    if ('AWS' in aws_principal):
                        aws_principal = aws_principal.get('AWS')
                    elif ('Service' in aws_principal):
                        aws_principal = aws_principal.get('Service')
                if isinstance(aws_principal, basestring):
                    aws_principal = [aws_principal]
                principal_account_ids = set()
                for arn in aws_principal:
                    if ((arn == '*') and (not condition_accounts) and ('allow' == statement.get('Effect').lower())):
                        notes = "An    KMS    policy    where    {    'Principal':    {    'AWS':    '*'    }    }    must    also    have"
                        notes += "    a    {'Condition':    {'StringEquals':    {    'kms:CallerAccount':    '<AccountNumber>'    }    }    }"
                        notes += '    or    it    is    open    to    the    world.'
                        self.add_issue(5, tag, kms_item, notes=notes)
                        continue
                    if (':' not in arn):
                        continue
                    statement_account_id = arn.split(':')[4]
                    if (statement_account_id != key_account_id):
                        principal_account_ids.add(statement_account_id)
                if principal_account_ids:
                    notes = 'Principal    -    {}'.format(json.dumps(sorted(list(principal_account_ids))))
                    self.add_issue(5, tag, kms_item, notes=notes)
