A Cloud Architect Company
aws guarduty
Amazon Web Services

Enable AWS GuardDuty to detect suspicious activity within your AWS account Using Terraform

Introduction

AWS GuardDuty is a threat detection service offered by Amazon Web Services (AWS) that continuously monitors and analyzes AWS account activity and network traffic to identify potential security threats. GuardDuty uses machine learning, anomaly detection, and threat intelligence to analyze data from AWS CloudTrail, VPC Flow Logs, and DNS logs, and then generates security alerts for potential threats, such as unauthorized access, data exfiltration, or malware infections.

GuardDuty provides a centralized dashboard for security operations teams to view and investigate security findings, as well as integrations with other AWS services, such as AWS CloudWatch, AWS Lambda, and AWS Security Hub, for automated response and remediation. By using GuardDuty, AWS customers can improve their security posture and quickly identify and respond to potential security incidents, helping to protect their sensitive data and applications running on AWS.

In this blog, we will explore the key features and benefits of GuardDuty, how to set up and configure the service using terraform script, and best practices for using GuardDuty to improve your AWS security posture. We will also discuss the use cases of GuardDuty.

Prerequisites

An IAM user is attached with the following permissions.

Procedure

Now it’s time to create GuardDuty and some other related services like CloudTrail using Terraform Script. Why need to create CloudTrail? Enabling GuardDuty on CloudTrail logs is essential because it allows customers to gain additional security insights and detect potential security threats in their AWS environment. It is a key step in improving the security posture of an AWS account and protecting valuable data and resources.

And also we are going to create AWS CloudWatch Event Rule and SNS Topic for sending email notifications from GuardDuty logs.

Also read: What is terraform?

Write Terraform Script for create CloudTrail

Create a folder like guard-duty and open VS Code editor in this folder.

Create a file called provider.tf and add the following code into the file.

provider "aws" {
  region     = "region_name"
  access_key = var.access_key
  secret_key = var.secret_key
}

Replace the region_name with the region name where you want to create CloudTrail.

Next, create another file called variables.tf and add the below code.

variable "access_key" {
  type        = string
  description = "AWS IAM Access key"
  default     = ""
}

variable "secret_key" {
  type        = string
  description = "AWS IAM Secret key"
  default     = ""
}

variable "name" {
  type    = string
  default = ""
}

All the variables’ default values need to be given inside the double quotes.

Finally, create a file named main.tf and enter the below code.

data "aws_caller_identity" "this" {}

locals {
  account_id = data.aws_caller_identity.this.account_id
}

resource "aws_cloudtrail" "this" {
  name                          = var.name
  s3_bucket_name                = aws_s3_bucket.this.id
  s3_key_prefix                 = "cloudtrail"
  enable_log_file_validation    = true
  include_global_service_events = true
  is_multi_region_trail         = true
  event_selector {
    read_write_type           = "All"
    include_management_events = true
    data_resource {
      type   = "AWS::S3::Object"
      values = ["arn:aws:s3:::"]
    }
  }
  event_selector {
    read_write_type           = "All"
    include_management_events = true
    data_resource {
      type   = "AWS::DynamoDB::Table"
      values = ["arn:aws:dynamodb"]
    }
    data_resource {
      type   = "AWS::Lambda::Function"
      values = ["arn:aws:lambda"]
    }
  }
  insight_selector {
    insight_type = "ApiCallRateInsight"
  }
}

resource "aws_s3_bucket" "this" {
  bucket        = "${lower(var.name)}-cloudtrail-${local.account_id}"
  force_destroy = true
}

data "aws_iam_policy_document" "bucket_policy" {
  statement {
    sid    = "AWSCloudTrailAclCheck"
    effect = "Allow"
    principals {
      type        = "Service"
      identifiers = ["cloudtrail.amazonaws.com"]
    }
    actions   = ["s3:GetBucketAcl"]
    resources = [aws_s3_bucket.this.arn]
  }
  statement {
    sid    = "AWSCloudTrailWrite"
    effect = "Allow"
    principals {
      type        = "Service"
      identifiers = ["cloudtrail.amazonaws.com"]
    }
    actions   = ["s3:PutObject"]
    resources = ["${aws_s3_bucket.this.arn}/cloudtrail/AWSLogs/${local.account_id}/*"]
    condition {
      test     = "StringEquals"
      variable = "s3:x-amz-acl"
      values   = ["bucket-owner-full-control"]
    }
  }
}

resource "aws_s3_bucket_policy" "this" {
  bucket = aws_s3_bucket.this.id
  policy = data.aws_iam_policy_document.bucket_policy.json
}

The above terraform code will create a CloudTrail with multi-region enabled. And also it creates an AWS S3 Bucket for CloudTrail log storage.

Run Terraform Script for CloudTrail

Now we have to run this script to create CloudTrail and S3 bucket.

Open the terminal in VS code editor and run the “terraform init” command. This init command should be run on every new terraform script.

Know more about terraform Init command

Enable GuardDuty Create CloudTrail using Terraform init

Now run the “terraform apply” command to deploy this script into your AWS account.

It will prompt you to Enter a value and enter yes to create CloudTrail.

It will create 3 resources like the picture below.

Enable GuardDuty Create CloudTrail using Terraform apply

Open your AWS account and navigate to CloudTrail. On the left side, panel choose Dashboard and you can see the CloudTrail could be created.

Enable GuardDuty Create CloudTrail using Terraform Cloudtrail Created

Add Terraform script for Create GuardDuty

Once you successfully created Cloudtrail, now need to enable GuardDuty.

So copy the below code and add it to the main.tf file under the existing code.

resource "aws_guardduty_detector" "this" {
  enable = true
  datasources {
    s3_logs {
      enable = true
    }
    kubernetes {
      audit_logs {
        enable = false
      }
    }
    malware_protection {
      scan_ec2_instance_with_findings {
        ebs_volumes {
          enable = true
        }
      }
    }
  }
}

resource "aws_cloudwatch_event_rule" "this" {
  name        = var.name
  description = "Event rule for trigger sns topic from AWS Guard duty"
  event_pattern = jsonencode(
    {
      "source" : ["aws.guardduty"],
      "detail-type" : ["GuardDuty Finding"]
    }
  )
}

resource "aws_cloudwatch_event_target" "this" {
  rule      = aws_cloudwatch_event_rule.this.name
  target_id = "SendToSNS"
  arn       = aws_sns_topic.this.arn
  input_transformer {
    input_paths = {
      severity            = "$.detail.severity",
      Finding_ID          = "$.detail.id",
      Finding_Type        = "$.detail.type",
      region              = "$.region",
      Finding_description = "$.detail.description"
    }
    input_template = "\"You have a severity <severity> GuardDuty finding type <Finding_Type> in the <region> region.\"\n \"Finding Description:\" \"<Finding_description>. \"\n \"For more details open the GuardDuty console at https://console.aws.amazon.com/guardduty/home?region=<region>#/findings?search=id%3D<Finding_ID>\""
  }
}

resource "aws_sns_topic" "this" {
  name = var.name
}

resource "aws_sns_topic_policy" "this" {
  arn    = aws_sns_topic.this.arn
  policy = data.aws_iam_policy_document.this.json
}

data "aws_iam_policy_document" "this" {
  statement {
    effect  = "Allow"
    actions = ["SNS:Publish"]
    principals {
      type        = "Service"
      identifiers = ["events.amazonaws.com"]
    }
    resources = [aws_sns_topic.this.arn]
  }
}

The above code will enable AWS GuardDuty and also create SNS Topic and Event Rule.

Run the “terraform apply” command to create these resources.

Enable GuardDuty Create CloudTrail using Terraform apply

Once it runs successfully like in the above picture, navigate to the AWS GuardDuty console to see the changes.

Enable GuardDuty Create CloudTrail using Terraform GuardDuty Enabled

Now it is enabled. But there are no logs to show. Now the next step we are going to generate logs to see how it works.

Generate Sample Findings

Now we are going to generate some sample findings.

On the left side navigation panel click Settings. On the right side, scroll down a little and click Generate sample findings.

Enable GuardDuty Create CloudTrail using Terraform Generate Sample Findings

Now again go to the findings page and you can see some of the sample logs are shown.

On the top right side, you can see three colours with indicated numbers.

These colours represent various severity stages of the reports.

  • Blue → Low

  • Orange → Medium

  • Red → High

Enable GuardDuty Create CloudTrail using Terraform Generated Sample Findings

Click one of the sample findings and it will show the full details about the Behavior activity.

Enable GuardDuty Create CloudTrail using Terraform Explore Sample Findings

AWS GuardDuty uses machine learning and mathematical algorithms. So it can find What action occurs and where it happens and Who did it with their location details like the below picture.

Enable GuardDuty Create CloudTrail using Terraform Explore Sample Findings

Create SNS Email Subscription

Open the SNS topic Console and on the left navigation panel click Topics. Then select the topic which is created by Terraform.

Under the Subscriptions section click Create subscription.

Enable GuardDuty Create CloudTrail using Terraform SNS Subscription

Select the protocol to Email and for Endpoint, enter your email address.

Finally, click Create Subscription.

Enable GuardDuty Create CloudTrail using Terraform Create SNS Subscription

You should receive a subscription confirmation email like in the picture below.

Open the mail and click the confirm subscription link.

Enable GuardDuty Create CloudTrail using Terraform Confirm SNS Subscription

If you prompt to another page like the below picture, your email subscription is confirmed.

Enable GuardDuty Create CloudTrail using Terraform SNS Subscription Confirmed

Get Alerts via Email

All setups are completed. But now we just trying to generate reports and get alerts via email notifications.

So first create an S3 bucket for this testing purpose. So Leave all settings as default and create.

If you don’t know how to create an S3 bucket Pls check the below links.

Create S3 bucket from AWS console
Create S3 bucket using Terraform

Now select the newly created S3 bucket and navigate to the Permissions section.

Under the Block public access settings, you can be able to see Block all public access could be On.

Click the Edit button. We are going to off this setting.

Enable GuardDuty Create CloudTrail using Terraform S3 Public Access

Disable the Block all public access and click Save changes like the below screenshot.

Enable GuardDuty Create CloudTrail using Terraform S3 Block public Access Disable

It asks a confirmation. So enter confirm and click Confirm button.

vEnable GuardDuty Create CloudTrail using Terraform S3 Block public Access Disable confirmation

Now go to the GuardDuty page.  After a couple of minutes, there will be a report showing under the Findings section.

Click the report and it will show all the details about the report. It will show a detailed report like what action happens and where it happens and who did this.

vEnable GuardDuty Create CloudTrail using Terraform GuardDuty Findings Report

And also you got an email like the below picture.

vEnable GuardDuty Create CloudTrail using Terraform GuardDuty Alerts via Email

Use Cases of AWS GuardDuty

Here are some of the use cases of AWS GuardDuty:

  1. Continuous Monitoring: GuardDuty continuously monitors the AWS environment for potential security threats, such as unauthorized access, data exfiltration, and malicious activity.
  2. Detecting Compromised Credentials: GuardDuty can monitor your AWS account for unauthorized access attempts and compromised credentials by analyzing AWS CloudTrail logs, VPC Flow Logs, and DNS logs.
  3. Threat Detection: GuardDuty uses machine learning algorithms and threat intelligence to detect known and unknown threats in the AWS environment.
  4. Compliance Monitoring: GuardDuty can help in maintaining compliance with various industry standards, by identifying potential security issues and providing actionable insights to remediate them.
  5. Incident Response: GuardDuty can help in investigating security incidents by providing detailed logs and alerts, which can be used to identify the root cause of the incident and take appropriate remediation measures.
  6. Integration with Other AWS Services: GuardDuty integrates with other AWS services such as AWS CloudTrail, Amazon S3, and AWS Lambda, to provide comprehensive security monitoring and threat detection capabilities.

Conclusion

In conclusion, creating AWS GuardDuty using Terraform is a straightforward process that can significantly enhance the security posture of your AWS environment. With the ability to detect and respond to potential threats in real time, GuardDuty offers a valuable layer of security that can help protect your business from cyber-attacks. By leveraging the power of Infrastructure as Code (IaC) with Terraform, you can automate the process of setting up GuardDuty, enabling you to quickly and easily configure the service and scale it to meet the needs of your organization.

With AWS GuardDuty and Terraform, you can rest assured that your AWS environment is secure and protected and that you are well-equipped to respond to any potential security threats that may arise. So why not give it a try and see the benefits for yourself?

 

Article written by:

Jerin is working as Cloud Automation Engineer at EasyDeploy Technologies Pvt. Ltd. He is writing terraform scripts that create multiple infrastructures on AWS, Azure cloud providers. He can understand network technologies as they relate to AWS and Azure.

Leave a Reply

Your email address will not be published. Required fields are marked *

back to top

Contact Us to save your AWS bill by 40%

X