Lab 5: Building an Automated Detection

Lab 5: Building an Automated Detection

Aug 30, 2023·

6 min read

Play this article

Lab Objective

  • View the Lambda function that will handle the event

  • Create an AWS EventBridge rule to capture CloudTrail data events involving your password-backup honey file and trigger a Lambda function called HoneyFileDetection

  • Perform T1530 (Data from Cloud Storage) once more to trigger this automation

  • Review Security Hub to find your automated detection

Challenge 1: View Honey File Detection Lambda Function

Go to the Lambda service and view the code for the HoneyFileDetection function. What is this function doing when it receives information from another service?

  • Navigate directly to the HoneyFileDetection function by going here.
import boto3
import re

def lambda_handler(event, context):
    # Get IP version
    if bool("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}", event['detail']['sourceIPAddress'])):
        ipver = "SourceIpV4"
        ipver = "SourceIpV6" 

    # Get Account ID
    client = boto3.client('sts')
    response = client.get_caller_identity()
    acctId = response['Account']

    # Check if assumed role and set userName
    if event['detail']['userIdentity']['type'] == "AssumedRole":
        userName = event['detail']['userIdentity']['sessionContext']['sessionIssuer']['userName']
    elif 'userName' in event['detail']['userIdentity'].keys():
        userName = event['detail']['userIdentity']['userName']
        userName = event['detail']['userIdentity']['arn']

    # Write finding
    client = boto3.client('securityhub')
        Findings = [{
        "AwsAccountId": acctId,
        "CreatedAt": event['detail']['eventTime'],
        "Description": "Honey file used",
        "GeneratorId": "custom",
        "Id": "honeyfile-" + event['detail']['sourceIPAddress'],
        "ProductArn": "arn:aws:securityhub:us-east-1:" + acctId + ":product/" + acctId + "/default",
        "Resources": [
                    "Id": "arn:aws:s3:::" + event['detail']['requestParameters']['bucketName'] + "/" + event['detail']['requestParameters']['key'],
                    "Partition": "aws",
                    "Region": "us-east-1",
                    "Type" : "AwsS3Bucket"
        "Network": {
                "Direction": "IN",
                ipver: event['detail']['sourceIPAddress']
        "SchemaVersion": "2018-10-08",
        "Title": "Honey file used",
        "UpdatedAt": event['detail']['eventTime'],
        "UserDefinedFields": {
            "userName": userName,
            "eventName": event['detail']['eventName']
        "Types": [
                "Effects/Data Exfiltration",
                "Unusual Behaviors/User"
        "Severity": {
            "Label": "CRITICAL",
            "Original": "CRITICAL"

    return {
        'statusCode': 200,
        'body': "Success!"

  • Review the Python function to understand what the code does. Code breakdown;
Line numbersDescription
1 - 2Import the AWS Software Development Kit (SDK) for Python (boto3) and regular expression (re) modules necessary for this automation to function properly.
4Begin handler function. This is the Python function is triggered when the Lambda function is executed.
5 - 9Since the Security Hub finding that this will generate (more on this in a moment) will have a field name depending on the version of the Internet Protocol (IP) that was identified, set the proper field name by analyzing the detail.sourceIPAddress portion of the event that is passed into the Lambda function.
11 - 15Acquire the account number for the account in which this function is running so that the generated finding contains the proper information.
17 - 23As the userName entry can be found two different ways depending on if you are using IAM roles, this code extracts the userName value properly. Otherwise, the function will error (thanks Shaun McCullough :))
25 - 64Based on the information passed to the Lambda function, generate a Security Hub finding with the proper context (e.g., where the password-backup.txt file request came from, the name of the API call, the location of the accessed file, the type of finding, and much more).
66 - 69Just a basic return that will inform the caller of any manual invocations that the run was successful.

Challenge 2: Create EventBridge Rule

Having grasped the intended function of the call, proceed to establish an AWS EventBridge rule. This rule should be configured with the specified logic to activate the function whenever there is an access attempt to the "password-backup.txt" honey file.

  • Captures any S3 API call

  • The S3 object key acted upon has a value of password-backup.txt (the honey file)

  • The target of the rule is the HoneyFileDetection Lambda function

  • Navigate to the EventBridge service.

  • On the Amazon EventBridge page, Get started by selecting the EventBridge Rule radio button and clicking on the Create rule.

  • On the Rules detail page, give the rule a name (here, honeyfile) and select a Rule type by checking the Rule with an event pattern radio button. Then click Next.

  • On the Build event pattern page, retain the default event source “AWS events or EventBridge partner events,” which triggers when certain AWS API calls are made.

  • Scroll down the page to the Event Pattern section, under Event source, select AWS services from the dropdown, and select Simple Storage Service (S3) under the AWS service dropdown menu. Next, under the Event type dropdown, select Object-Level API Call via CloudTrail (This will let you know when the S3 object (the honey file) is accessed.)

  • Review the JSON file generated after the selection. This JSON document defines what EventBridge will be looking for, and if there is a match, it will pass this event to a target.
  "source": ["aws.s3"],
  "detail-type": ["AWS API Call via CloudTrail"],
  "detail": {
    "eventSource": [""],
    "eventName": ["ListObjects", "ListObjectVersions", "PutObject", "GetObject", "HeadObject", "CopyObject", "GetObjectAcl", "PutObjectAcl", "CreateMultipartUpload", "ListParts", "UploadPart", "CompleteMultipartUpload", "AbortMultipartUpload", "UploadPartCopy", "RestoreObject", "DeleteObject", "DeleteObjects", "GetObjectTorrent", "SelectObjectContent", "PutObjectLockRetention", "PutObjectLockLegalHold", "GetObjectLockRetention", "GetObjectLockLegalHold"]
  • Edit the JSON file to specify that the requested key is equal to,password-backup.txt so that only those interactions are passed to the target.

    Click on the Edit Pattern button and replace the Code below with the generated JSON file. Then Click Next once you're done.

    "source": ["aws.s3"],
    "detail-type": ["AWS API Call via CloudTrail"],
    "detail": {
        "eventSource": [""],
        "eventName": ["ListObjects", "ListObjectVersions", "PutObject", "GetObject", "HeadObject", "CopyObject", "GetObjectAcl", "PutObjectAcl", "CreateMultipartUpload", "ListParts", "UploadPart", "CompleteMultipartUpload", "AbortMultipartUpload", "UploadPartCopy", "RestoreObject", "DeleteObject", "DeleteObjects", "GetObjectTorrent", "SelectObjectContent", "PutObjectLockRetention", "PutObjectLockLegalHold", "GetObjectLockRetention", "GetObjectLockLegalHold"],
        "requestParameters": {
            "key": ["password-backup.txt"]

  • On the Select target(s) page, select the target type as AWS service Since we are sending this to another AWS service component, the HoneyFileDetection Lambda function. Then, click the Select a Target from the dropdown and choose the lambda function. Next, under the Function dropdown, choose your HoneyFileDetection function then Click Next.

  • On Configure tags, Since it is optional click Next. Then on the Review and Create page, evaluate the configuration and click on the Create rule at the bottom of the page.

Challenge 3: Emulate Stolen File Access

To test the EventBridge rule's activation, trigger the execution of the Lambda function. This will generate a fresh Security Hub finding linked to the honey file access. Repeat the attack by downloading the "password-backup.txt" file from S3.

  • List the bucket content for databackup-
BUCKET=$(aws s3api list-buckets | jq -r \
  '.Buckets[] | select(.Name | startswith("databackup-")) | .Name')
aws s3 ls s3://$BUCKET/

  • Download the content (object) of the file using aws s3 cp command.
aws s3 cp s3://$BUCKET/password-backup.txt /home/cloudshell-user/password-backup.txt

The AWS CLI's execution of the s3:GetObject API call should be sufficient to activate the EventBridge rule.

Challenge 4: Review Security Hub Detection

The moment of truth has arrived: check whether this automated detection has produced a finding in AWS Security Hub. Go to the Security Hub service to locate your findings.

NB: It may take a few minutes for the finding to appear,

  • On the Findings page, you will see at the top of the list of findings, one called Honey file use . Click on that finding to reveal more details (all of which were generated by the HoneyFileDetection Lambda function).

  • The pane pops out on the right with the finding details. expand each section to review the content populated by the Lambda function based on the event information passed in from EventBridge.

Congratulations! You have effectively constructed a detection mechanism to identify an adversary attempting to access a honey file. Even more significant, you've gone through the steps of creating an effective detection.

Did you find this article valuable?

Support Goodycyb by becoming a sponsor. Any amount is appreciated!