def lambda_handler(event, context):

    SecurityTagKey = os.environ['SecurityTagKey']
    TargetAccountSecurityRoleName = os.environ['TargetAccountSecurityRoleName']
    BlockPolicyArn = os.environ['BlockPolicyArn']

    if event['detail-type'] == "GuardDuty Finding":
        finding = event["detail"]
    elif event['detail-type'] == "Security Hub Findings - Custom Action":
        finding = security_hub.getFinding(event)

    else:
        raise Exception("Neither GuardDuty nor SecurityHub event")

    event_id = finding['id']
    targetAccount = finding["accountId"]
    principle_id = finding["resource"]["accessKeyDetails"]["userName"]
    principle_type = finding["resource"]["accessKeyDetails"]["userType"]

    session = account_session.get_session(
        targetAccount, os.environ['TargetAccountSecurityRoleName'])

    logger.info(
        f"GuardDuty Duty event {event_id} triggers checking principle {principle_type} of type {principle_type} in account {targetAccount}"
    )
    client = session.client('iam')

    if principle_type == "AssumedRole":
        response = client.get_role(RoleName=principle_id)

        if 'Tags' in response['Role']:
            for t in response['Role']['Tags']:
                if t['Key'] == SecurityTagKey:
                    logger.info(
                        f"Security exception defined with tag {SecurityTagKey}. Skipping blocking {principle_id} of type {principle_type} in account {targetAccount}"
                    )
                    return

        client.attach_role_policy(RoleName=principle_id,
                                  PolicyArn=BlockPolicyArn)
    else:
        response = client.get_user(UserName=principle_id)

        if 'Tags' in response['User']:
            for t in response['User']['Tags']:
                if t['Key'] == SecurityTagKey:
                    logger.info(
                        f"Security exception defined with tag {SecurityTagKey}. Skipping blocking {principle_id} of type {principle_type} in account {targetAccount}"
                    )
                    return
        client.attach_user_policy(UserName=principle_id,
                                  PolicyArn=BlockPolicyArn)

    guard_duty.archiveGuardDutyFinding(finding["arn"])

    notify.sendNotification(
        f"Attached deny policy to principle {principle_id} of type {principle_type} in account {targetAccount}. Guard Duty finding id {event_id} archived."
    )
Пример #2
0
def send_Email():
    print("in send email")
    receiver_email = request.form['receiver_email']
    receiver_name = request.form['receiver_name']
    student_email = request.form['student_email']
    student_name = request.form['student_name']
    class_name = request.form['class_name']
    print(request.form)
    sendNotification(receiver_email, student_email, student_name,
                     receiver_name, class_name)
    return app.response_class(status=200)
Пример #3
0
def lambda_handler(event, context):

    logger.info(f"recieved event: {json.dumps(event)}")

    SecurityTagKey = os.environ['SecurityTagKey']
    region = os.environ['AWS_REGION']
    targetAccount = event["account"]

    session = account_session.get_session(
        targetAccount, os.environ['TargetAccountSecurityRoleName'])

    # check for security exeption
    client = session.client('resourcegroupstaggingapi')
    paginator = client.get_paginator('get_resources')
    pages = paginator.paginate(TagFilters=[{
        'Key': SecurityTagKey,
    }],
                               ResourceTypeFilters=[event["resourseType"]])

    for page in pages:
        for res in page['ResourceTagMappingList']:
            if event["resourceId"] in res['ResourceARN']:
                logger.info(
                    f"Security exception defined with tag {SecurityTagKey}. Skipping {event['resourceId']} of type {event['resourseType']}"
                )
                return

    # execute automation
    if "AutomationDocumentName" in event:
        client = boto3.client('ssm')
        response = client.start_automation_execution(
            DocumentName=event['AutomationDocumentName'],
            Parameters=event['AutomationParameters'],
            TargetLocations=[{
                "Accounts": [targetAccount],
                "Regions": [region]
            }])

        notify.sendNotification(
            f"Triggered incident response in account {event['account']}, SSM document {event['AutomationDocumentName']} with id {response['AutomationExecutionId']} and input parameters "
            + json.dumps(event['AutomationParameters']))
def lambda_handler(event, context):
    
    AllowedNetworkRangeIPv4=os.environ['AllowedNetworkRangeIPv4']
    AllowedNetworkRangeIPv6=os.environ['AllowedNetworkRangeIPv6']
    SecurityTagKey=os.environ['SecurityTagKey']

    if event['source'] == "aws.config":
             sg_id=event["detail"]["resourceId"]
             targetAccount=event["account"]
    else: 
        raise Exception('Unknown event source. Supported only aws.config')
    
    session=account_session.get_session(targetAccount, os.environ['TargetAccountSecurityRoleName']) 
    
    logger.info(f"Checking security group {sg_id} in account {targetAccount}")
    client = session.client('ec2')
    response = client.describe_security_groups(GroupIds=[ sg_id ])
    
    if "Tags" in response['SecurityGroups'][0]:    
         for t in response['SecurityGroups'][0]['Tags']:
             if t['Key'] == SecurityTagKey:
                 logger.info(f"Security exception defined with tag {SecurityTagKey}. Skipping security group {sg_id} to confine") 
                 return
    
    for p in response['SecurityGroups'][0]['IpPermissions']:
        for r in p['IpRanges']:
            if r["CidrIp"] == "0.0.0.0/0":
                client.revoke_security_group_ingress(IpPermissions=[p], GroupId=sg_id)
                r["CidrIp"]=AllowedNetworkRangeIPv4
                client.authorize_security_group_ingress(IpPermissions=[p], GroupId=sg_id)
        for r in p['Ipv6Ranges']:
            if r["CidrIpv6"] == "::/0":
                client.revoke_security_group_ingress(IpPermissions=[p], GroupId=sg_id)
                r["CidrIpv6"]=AllowedNetworkRangeIPv6
                client.authorize_security_group_ingress(IpPermissions=[p], GroupId=sg_id)
    
    notify.sendNotification(f"Confined security group {sg_id} in account id {targetAccount} to safe CIDR")
def lambda_handler(event, context):

    SecurityTagKey = os.environ['SecurityTagKey']
    TargetAccountSecurityRoleName = os.environ['TargetAccountSecurityRoleName']

    if event['detail-type'] == "GuardDuty Finding":
        finding = event["detail"]
    elif event['detail-type'] == "Security Hub Findings - Custom Action":
        finding = security_hub.getFinding(event)

    else:
        raise Exception("Neither GuardDuty nor SecurityHub event")

    i_id = finding["resource"]["instanceDetails"]["instanceId"]
    targetAccount = finding["accountId"]
    event_id = finding['id']

    logger.info(
        f"GuardDuty Duty event {event_id} triggers checking instance {i_id} in account {targetAccount}"
    )

    session = account_session.get_session(
        targetAccount, os.environ['TargetAccountSecurityRoleName'])

    client = session.client('ec2')
    ec2 = client.describe_instances(InstanceIds=[i_id])
    if "Tags" in ec2['Reservations'][0]['Instances'][0]:
        for t in ec2['Reservations'][0]['Instances'][0]["Tags"]:
            if t['Key'] == SecurityTagKey:
                logger.info(
                    f"Security exception defined with tag {SecurityTagKey}. Skipping Isolation of instance {i_id} in account {targetAccount}"
                )
                return

    secGrName = f"secIsolation-{event_id}"
    vpcID = ec2['Reservations'][0]['Instances'][0]["VpcId"]
    # Check if isolation security group already exists
    try:
        r = client.describe_security_groups(Filters=[{
            'Name': 'group-name',
            'Values': [secGrName]
        }, {
            'Name': 'vpc-id',
            'Values': [vpcID]
        }])
        secGrId = r['SecurityGroups'][0]['GroupId']
        logger.info(f'Found existing isolation Sec Group {secGrId}')
    except:
        r = client.create_security_group(Description='security isolation',
                                         GroupName=secGrName,
                                         VpcId=vpcID)
        secGrId = r['GroupId']
        client.revoke_security_group_egress(IpPermissions=[{
            "IpProtocol":
            "-1",
            "IpRanges": [{
                "CidrIp": "0.0.0.0/0"
            }],
            "Ipv6Ranges": [],
            "PrefixListIds": [],
            "UserIdGroupPairs": []
        }],
                                            GroupId=secGrId)
        logger.info(f'Created new isolation Sec Group {secGrId}')

    for eni in ec2['Reservations'][0]['Instances'][0]['NetworkInterfaces']:
        client.modify_network_interface_attribute(
            NetworkInterfaceId=eni["NetworkInterfaceId"], Groups=[secGrId])

    guard_duty.archiveGuardDutyFinding(finding["arn"])

    notify.sendNotification(
        f"Isolation security group {secGrId} created and attached to instance {i_id} in account {targetAccount}. Guard Duty finding id {event_id} archived"
    )