def check_security_groups()

in MWAA/verify_env/verify_env.py [0:0]


def check_security_groups(input_env, ec2_client):
    '''
    check MWAA environment's security groups for:
        - have at least 1 rule
        - checks ingress to see if sg allows itself
        - egress is checked by SSM document for 443 and 5432
    '''
    print("")
    security_groups = input_env['NetworkConfiguration']['SecurityGroupIds']
    groups = ec2_client.describe_security_groups(
        GroupIds=security_groups
    )['SecurityGroups']
    # have a sanity check on ingress and egress to make sure it allows something
    print('### Trying to verifying ingress on security groups...')
    valid = True
    for security_group in groups:
        ingress = security_group['IpPermissions']
        egress = security_group['IpPermissionsEgress']
        if not ingress and not egress:
            print('ingress and egress for security group: ', security_group['GroupId'], ' requires at least one rule',
                  "🚫")
            valid = False
            break
        elif not ingress:
            print('ingress for security group: ', security_group['GroupId'], ' requires at least one rule', "🚫")
            valid = False
            break
        elif not egress:
            print('egress for security group: ', security_group['GroupId'], ' requires at least one rule', "🚫")
            break
        # check security groups to ensure port at least the same security group or everything is allowed ingress
        for rule in ingress:
            if rule['IpProtocol'] == "-1":
                if rule['UserIdGroupPairs'] and not (
                    any(x['GroupId'] == security_group['GroupId'] for x in rule['UserIdGroupPairs'])
                ):
                    valid = False
                    break
    if valid:
        print("ingress for security groups have at least 1 rule to allow itself", "✅", "\n")
    else:
        print("ingress for security groups do not have at least 1 rule to allow itself", "🚫", "\n")