Streaming Logs from AWS CloudTrail and CloudWatch (Legacy)
This method is legacy. AWS Log Ingestion through Kinesis Firehose replaces it. It needs no Lambda in your account, and it also covers VPC Flow Logs and Route 53 Resolver query logs. If you are setting this up for the first time, use that guide instead. This page stays for existing customers on the forwarder Lambda, until they move over.
This guide is for customers who want to send AWS CloudTrail events and CloudWatch Logs (for example, application or API logs) to SenseOn. Both use the same mechanism: a small forwarder Lambda in your own AWS account. The Lambda has a subscription to each CloudWatch Log Group that you want to ingest. When you enable the CloudWatch Logs delivery of CloudTrail, CloudTrail uses this same path. It does not use a separate route through S3.
How it works
Your log producers (CloudTrail, applications)
-> CloudWatch Log Group (your account)
-> Subscription filter
-> Forwarder Lambda (your account)
-> HTTPS POST -> SenseOn ingestion endpoint
You do these tasks:
- Deploy the Lambda. Set it to send to the ingestion endpoint that SenseOn gives for your environment.
- Attach a subscription filter to each log group that you want to forward.
- Give CloudWatch Logs permission to invoke the Lambda.
All components run in your own account, and SenseOn pulls nothing from your account. For this path, a cross-account IAM role or access into your account is not necessary. Step 3 covers two methods: a manual method (AWS Console/CLI) and a method that uses Terraform.
Prerequisites
- Permissions in your AWS account to create a Lambda function and its IAM role/permission, and CloudWatch Logs subscription filters.
- If you want to include CloudTrail: an existing CloudTrail trail (or create a new one).
- The ingestion endpoint URL for your environment. Your SenseOn contact gives you this URL.
Step 1: Enable CloudWatch Logs delivery on your CloudTrail trail
If you want to ingest CloudTrail events, open your trail. Enable CloudWatch Logs delivery to a dedicated log group.
This change adds to your setup and does not replace a part of it. Your trail continues to write to its existing S3 destination exactly as before. The change only adds a second, parallel delivery target. It is not necessary to change your current CloudTrail setup.
If you send only CloudWatch application logs and not CloudTrail, skip this step.
Step 2: Identify your CloudWatch log groups
Write down the name of each CloudWatch Log Group that you want SenseOn to receive. Include your application/API logs and, if applicable, the log group for CloudTrail from Step 1.
Step 3: Deploy the forwarder and subscribe your log groups
Select the method that suits how you manage infrastructure. Both methods give the same result: a forwarder Lambda in your account, with a subscription filter on each log group that sends to the Lambda.
Create a new Lambda function:
- Name:
SenseOn-Forwarder - Runtime: Python 3.12
- Timeout: Under Basic settings, increase the execution timeout to 1 minute. The default of 3 seconds is shorter than the 10 second HTTP timeout in the code. Thus the HTTP timeout can never take effect. Usual network latency alone can make Lambda stop the function. Then CloudWatch Logs does retries that are not necessary.
Paste the code that follows directly into the default code editor of the console. The code already matches the default filename and handler of AWS (lambda_function.py / lambda_handler). Thus it is not necessary to change the filename or to configure the Handler:
import base64
import gzip
import json
import os
import urllib.request
from datetime import datetime, timezone
INGESTION_ENDPOINT_URL = os.environ["INGESTION_ENDPOINT_URL"]
DEBUG_LOG_ENVELOPES = os.environ.get("DEBUG_LOG_ENVELOPES", "") == "true"
def _to_iso8601(epoch_ms):
return datetime.fromtimestamp(epoch_ms / 1000, tz=timezone.utc).strftime(
"%Y-%m-%dT%H:%M:%S.%f"
)[:-3] + "Z"
def _envelope(log_group, log_stream, event):
return {
"metadata": {
"original_log_group": log_group,
"resource_id": log_stream,
},
"log_event": {
"eventId": event["id"],
"logStreamName": log_stream,
"timestamp_utc": _to_iso8601(event["timestamp"]),
"message": event["message"],
},
}
def lambda_handler(event, _context):
payload = json.loads(gzip.decompress(base64.b64decode(event["awslogs"]["data"])))
log_group = payload["logGroup"]
log_stream = payload["logStream"]
envelopes = [_envelope(log_group, log_stream, e) for e in payload["logEvents"]]
body = json.dumps(envelopes).encode("utf-8")
if DEBUG_LOG_ENVELOPES:
print(json.dumps(envelopes[:1]))
headers = {"Content-Type": "application/json"}
request = urllib.request.Request(
INGESTION_ENDPOINT_URL, data=body, headers=headers, method="POST"
)
with urllib.request.urlopen(request, timeout=10) as response:
response.read()
return {"forwarded": len(envelopes)}
Environment variables
| Variable | Required | Purpose |
|---|---|---|
INGESTION_ENDPOINT_URL |
Yes | The SenseOn ingestion endpoint provided for your environment. |
DEBUG_LOG_ENVELOPES |
No | To make the function print the payload that it sends, set it to exactly true for a short time. You can see the payload in the CloudWatch Logs group of the function. In all other conditions, do not set it. |
Grant CloudWatch Logs permission to invoke the Lambda
CloudWatch Logs must have explicit permission to call this Lambda for a given log group. This permission is not automatic.
Console: You can use the CloudWatch console to create the subscription filter and select this Lambda as the destination. If you do, the console adds the necessary permission automatically. No other action is necessary.
AWS CLI: If you use aws logs put-subscription-filter directly, add the permission first. If you do not, the command stops with an access error:
aws lambda add-permission \
--function-name SenseOn-Forwarder \
--statement-id AllowCloudWatchLogsInvoke-<log-group-short-name> \
--action lambda:InvokeFunction \
--principal logs.<region>.amazonaws.com \
--source-arn arn:aws:logs:<region>:<account-id>:log-group:<log-group-name>:* \
--source-account <account-id>
If you forward more than one log group, give the permission of each log group a unique --statement-id. For example, the CloudTrail log group and an application log group must each have their own.
Create the subscription filter
Create one subscription filter for each log group that you want to ingest. Use the name SenseOn-Forwarder-SF. The name must be unique only in its own log group. Thus you can use the same name on each log group that you subscribe.
Set the Lambda that you created as the destination. A blank filter pattern forwards each event from that log group.
Think before you exclude events by type. If you send CloudTrail to monitor security, do not filter out read-only calls (
Describe*/List*/Get*). These calls are exactly how AWS account enumeration and reconnaissance activity shows. If you filter them out to decrease the volume, detection cannot see the activity that it must find. If you must decrease the volume, filter by identity type, not by verb. This method is safer. For example, exclude the calls that AWS service principals make.
Troubleshooting
[ERROR] Runtime.HandlerNotFound: Handler 'lambda_handler' missing on module 'lambda_function'
Usually, this error does not occur, because the code in this tab already matches the default filename and handler of AWS. But the source can have a different name, or you can paste it into a file with a different name. In this case, go to the Runtime settings panel of the Code tab. Make sure that Handler shows lambda_function.lambda_handler. Make sure that the name of the source file is lambda_function.py.
Task timed out after 3.00 seconds
You did not increase the execution timeout of the function. Go to Basic settings. Make sure that Timeout is 1 minute or more, not the AWS default of 3 seconds.
This stack only reads the log groups that you list (a data source, never a resource). Thus it cannot create, modify or delete them. Its teardown is also safe at any time, because the teardown removes only what the stack created.
Download the Terraform module (zip) to get all the files that follow. Then you do not have to create each file manually. Unzip the file. Compare the contents with the code on this page. Then go directly to terraform init.
Additional prerequisites: Terraform >= 1.5, the aws CLI and jq. The guardrail script in this tab calls the last two.
The files follow, for reference. They are identical to the files in the zip:
versions.tf:
terraform {
required_version = ">= 1.5"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
archive = {
source = "hashicorp/archive"
version = "~> 2.4"
}
external = {
source = "hashicorp/external"
version = "~> 2.3"
}
}
}
provider "aws" {
region = var.aws_region
profile = var.aws_profile
}
variables.tf:
variable "aws_region" {
description = "Region the log groups being subscribed to (and this stack's own resources) live in."
type = string
default = "eu-west-1"
}
variable "aws_profile" {
description = "Named AWS CLI profile to authenticate with (leave null to use the default credential chain)."
type = string
default = null
}
variable "name_prefix" {
description = "Prefix applied to every resource this stack creates, so it's identifiable in the account and can be torn down cleanly on its own."
type = string
default = "senseon-forwarder"
}
variable "log_group_names" {
description = <<-EOT
CloudWatch Log Group names to forward to SenseOn. Every name must
already exist (CloudTrail delivery, an application log group, etc.) --
this stack only reads each one via a data source and subscribes to it,
it never creates, modifies, or deletes the log group itself. Add or
remove a name here and re-apply to subscribe/unsubscribe that one
source; nothing else is affected.
EOT
type = list(string)
validation {
condition = length(var.log_group_names) > 0
error_message = "log_group_names must list at least one existing CloudWatch Log Group name."
}
validation {
condition = alltrue([for n in var.log_group_names : trimspace(n) == n && n != ""])
error_message = "log_group_names entries must be non-empty and have no leading/trailing whitespace."
}
validation {
condition = length(var.log_group_names) == length(distinct(var.log_group_names))
error_message = "log_group_names must not contain duplicate entries."
}
}
variable "filter_pattern" {
description = <<-EOT
CloudWatch Logs subscription filter pattern applied to every log group
listed above. Defaults to "" (no filtering): for CloudTrail sources in
particular, Describe*/List*/Get* calls are how AWS enumeration/discovery
(MITRE ATT&CK TA0007) actually shows up, so excluding them by verb would
blind detection rather than cut noise.
EOT
type = string
default = ""
}
variable "ingestion_endpoint_url" {
description = "SenseOn's HTTP log ingestion endpoint the forwarder Lambda POSTs to. No authentication scheme exists for this endpoint yet -- TLS is the only protection in transit."
type = string
}
variable "reserved_concurrent_executions" {
description = "Caps how many forwarder invocations can run at once, so a burst from a noisy log group can't consume the account's shared Lambda concurrency pool and starve other functions. -1 removes the cap."
type = number
default = 10
}
variable "debug_log_envelopes" {
description = "Print the exact envelope sent to SenseOn into the forwarder's own logs. A troubleshooting/sample-gathering aid, not for routine use -- puts real log content into CloudWatch. Turn back off afterwards."
type = bool
default = false
}
variable "log_retention_days" {
description = "Retention for the forwarder Lambda's own execution log group. Never applied to your own log groups -- those are untouched by this stack."
type = number
default = 14
}
variable "permissions_boundary_arn" {
description = "Optional IAM permissions boundary ARN to attach to the forwarder's role. Leave null (default) unless your account requires one -- some organisations' SCPs reject any CreateRole call that omits it."
type = string
default = null
}
variable "tags" {
description = "Additional tags applied to every resource this stack creates."
type = map(string)
default = {}
}
forwarder.tf:
locals {
tags = merge(
{ ManagedBy = "senseon-log-forwarder-terraform" },
var.tags,
)
# AWS hard limit, not adjustable via Service Quotas.
subscription_filter_limit = 5
filter_name = "${var.name_prefix}-to-forwarder"
}
data "aws_caller_identity" "current" {}
# Data source, never a resource: your log group must not be something
# this stack's state can create, modify, or delete.
data "aws_cloudwatch_log_group" "source" {
for_each = toset(var.log_group_names)
name = each.value
}
# No `aws` provider data source lists a log group's existing subscription
# filters, so the only way to check before adding ours is a real API call.
data "external" "existing_filters" {
for_each = data.aws_cloudwatch_log_group.source
program = ["bash", "${path.module}/scripts/check_subscription_filters.sh"]
query = {
log_group_name = each.value.name
aws_region = var.aws_region
aws_profile = coalesce(var.aws_profile, "")
}
}
locals {
existing_filter_names = {
for k, v in data.external.existing_filters : k => jsondecode(v.result.names)
}
existing_filter_counts = {
for k, v in data.external.existing_filters : k => tonumber(v.result.count)
}
}
data "archive_file" "forwarder" {
type = "zip"
source_dir = "${path.module}/lambda_src"
output_path = "${path.module}/.build/forwarder.zip"
}
data "aws_iam_policy_document" "lambda_trust" {
statement {
effect = "Allow"
actions = ["sts:AssumeRole"]
principals {
type = "Service"
identifiers = ["lambda.amazonaws.com"]
}
}
}
resource "aws_iam_role" "forwarder" {
name = "${var.name_prefix}-forwarder"
assume_role_policy = data.aws_iam_policy_document.lambda_trust.json
permissions_boundary = var.permissions_boundary_arn
tags = local.tags
}
resource "aws_cloudwatch_log_group" "forwarder" {
name = "/aws/lambda/${var.name_prefix}-forwarder"
retention_in_days = var.log_retention_days
tags = local.tags
}
# Scoped to this Lambda's own log group only, not the account-wide logs:*
# granted by AWSLambdaBasicExecutionRole -- least privilege for a stack
# landing in your account.
data "aws_iam_policy_document" "forwarder_logging" {
statement {
effect = "Allow"
actions = [
"logs:CreateLogStream",
"logs:PutLogEvents",
]
resources = ["${aws_cloudwatch_log_group.forwarder.arn}:*"]
}
}
resource "aws_iam_role_policy" "forwarder_logging" {
name = "${var.name_prefix}-forwarder-logging"
role = aws_iam_role.forwarder.id
policy = data.aws_iam_policy_document.forwarder_logging.json
}
resource "aws_lambda_function" "forwarder" {
function_name = "${var.name_prefix}-forwarder"
role = aws_iam_role.forwarder.arn
handler = "forwarder.handler"
runtime = "python3.12"
timeout = 60
reserved_concurrent_executions = var.reserved_concurrent_executions
filename = data.archive_file.forwarder.output_path
source_code_hash = data.archive_file.forwarder.output_base64sha256
environment {
variables = {
INGESTION_ENDPOINT_URL = var.ingestion_endpoint_url
DEBUG_LOG_ENVELOPES = var.debug_log_envelopes ? "true" : "false"
}
}
depends_on = [aws_iam_role_policy.forwarder_logging]
tags = local.tags
}
# Keyed by log group name so edits to log_group_names map to exactly one
# filter+permission pair, leaving every other source untouched.
resource "aws_lambda_permission" "invoke" {
for_each = data.aws_cloudwatch_log_group.source
statement_id = "AllowInvoke-${substr(md5(each.key), 0, 16)}"
action = "lambda:InvokeFunction"
function_name = aws_lambda_function.forwarder.function_name
principal = "logs.${var.aws_region}.amazonaws.com"
source_arn = "${each.value.arn}:*"
source_account = data.aws_caller_identity.current.account_id
}
resource "aws_cloudwatch_log_subscription_filter" "to_forwarder" {
for_each = data.aws_cloudwatch_log_group.source
name = local.filter_name
log_group_name = each.value.name
filter_pattern = var.filter_pattern
destination_arn = aws_lambda_function.forwarder.arn
lifecycle {
precondition {
condition = (
contains(local.existing_filter_names[each.key], local.filter_name) ||
local.existing_filter_counts[each.key] < local.subscription_filter_limit
)
error_message = "Log group ${each.key} already has ${local.existing_filter_counts[each.key]} subscription filter(s); AWS allows at most ${local.subscription_filter_limit} per log group, a hard limit that can't be raised. Remove or consolidate an existing filter on this log group before adding SenseOn's, or drop it from log_group_names."
}
}
depends_on = [aws_lambda_permission.invoke]
}
outputs.tf:
output "forwarder_function_name" {
value = aws_lambda_function.forwarder.function_name
}
output "forwarder_log_group_name" {
value = aws_cloudwatch_log_group.forwarder.name
}
output "subscribed_log_groups" {
description = "Every log group currently being forwarded, and the subscription filter name attached to it."
value = {
for name, filter in aws_cloudwatch_log_subscription_filter.to_forwarder :
name => filter.name
}
}
lambda_src/forwarder.py:
import base64
import gzip
import json
import os
import urllib.request
from datetime import datetime, timezone
INGESTION_ENDPOINT_URL = os.environ["INGESTION_ENDPOINT_URL"]
DEBUG_LOG_ENVELOPES = os.environ.get("DEBUG_LOG_ENVELOPES", "") == "true"
def _to_iso8601(epoch_ms):
return datetime.fromtimestamp(epoch_ms / 1000, tz=timezone.utc).strftime(
"%Y-%m-%dT%H:%M:%S.%f"
)[:-3] + "Z"
def _envelope(log_group, log_stream, event):
return {
"metadata": {
"original_log_group": log_group,
"resource_id": log_stream,
},
"log_event": {
"eventId": event["id"],
"logStreamName": log_stream,
"timestamp_utc": _to_iso8601(event["timestamp"]),
"message": event["message"],
},
}
def handler(event, _context):
payload = json.loads(gzip.decompress(base64.b64decode(event["awslogs"]["data"])))
log_group = payload["logGroup"]
log_stream = payload["logStream"]
envelopes = [_envelope(log_group, log_stream, e) for e in payload["logEvents"]]
body = json.dumps(envelopes).encode("utf-8")
if DEBUG_LOG_ENVELOPES:
print(json.dumps(envelopes[:1]))
request = urllib.request.Request(
INGESTION_ENDPOINT_URL,
data=body,
headers={"Content-Type": "application/json"},
method="POST",
)
with urllib.request.urlopen(request, timeout=10) as response:
response.read()
return {"forwarded": len(envelopes)}
scripts/check_subscription_filters.sh. Before forwarder.tf adds a filter, it uses this script to do a check of the AWS limit for subscription filters. Make the script executable with chmod +x:
#!/usr/bin/env bash
set -euo pipefail
query="$(cat)"
log_group_name="$(jq -r '.log_group_name' <<<"${query}")"
aws_region="$(jq -r '.aws_region' <<<"${query}")"
aws_profile="$(jq -r '.aws_profile' <<<"${query}")"
profile_args=()
if [[ -n "${aws_profile}" && "${aws_profile}" != "null" ]]; then
profile_args=(--profile "${aws_profile}")
fi
names_json="$(aws logs describe-subscription-filters \
"${profile_args[@]}" --region "${aws_region}" \
--log-group-name "${log_group_name}" \
--query 'subscriptionFilters[].filterName' --output json)"
jq -n --argjson names "${names_json}" \
'{count: ($names | length | tostring), names: ($names | tostring)}'
The zip contains example.tfvars, with the same placeholders as the example that follows. Copy the file, and enter your own values. Keep the real terraform.tfvars out of version control, because it is specific to your account:
aws_region = "eu-west-1"
aws_profile = "your-aws-cli-profile" # named AWS CLI profile for your account
name_prefix = "senseon-forwarder"
# Every name here must already exist -- this stack only reads and
# subscribes to them, it never creates or modifies the log group itself.
log_group_names = [
"/aws/cloudtrail/your-cloudtrail-log-group",
# "/ecs/your-app",
]
ingestion_endpoint_url = "https://your-ingestion-endpoint.senseon.io"
cp example.tfvars terraform.tfvars
# edit terraform.tfvars with your own values
Then apply the configuration:
terraform init
terraform plan -var-file=terraform.tfvars
terraform apply -var-file=terraform.tfvars
Guardrails built into this stack
- Subscription filter limit. AWS sets a maximum of 5 subscription filters on each log group. You cannot increase this hard limit. Before the stack adds the SenseOn filter, the
preconditionuses the guardrail script to get the real count. If the new filter makes the count more than the limit,plan/applystops with an error at the start. The error gives the log group name and its current count. Without this check, you get a rawLimitExceededExceptionduring the apply. - Least-privilege IAM. The role of the forwarder can write only to its own log group. Both
source_arnandsource_accountscope itsaws_lambda_permission. This is the standard protection against a resource in a different account, with the same ARN pattern, that invokes this function. - Concurrency cap. With
reserved_concurrent_executions(default 10), a burst from a noisy log group cannot use all of the shared Lambda concurrency pool in your account.
These guardrails cannot give protection against one problem. A log group that you list can already have an unrelated subscription filter with the exact filter name of this stack (${name_prefix}-to-forwarder). If so, the apply silently takes over that filter. CloudWatch subscription filters do not have an ownership tag. Thus the name alone cannot show the difference between "ours" and "someone else's". Select a name_prefix that is not likely to be the same as a name already in your account.
If apply fails
executable file not found in $PATH: aws or jq is not installed on the computer that runs Terraform. The guardrail script must have both.
Resource precondition failed with a reference to the subscription filter limit: The named log group already has the maximum of 5 filters that AWS allows. Before you add the SenseOn filter, remove or consolidate an existing filter on the log group. As an alternative, remove the log group from log_group_names.
Adding or removing a source
Edit log_group_names. Then apply the configuration again. For each log group that you change, terraform plan shows exactly one filter and one permission that it adds or removes. The change has no effect on all other sources.
Decommissioning
terraform destroy -var-file=terraform.tfvars
This command removes the forwarder Lambda, its role, its own log group, and each subscription filter and permission that this stack created. The command has no effect on the log groups that the stack forwards, or on data that SenseOn already received.
Step 4: Verify it's working
Cause an event in the source log group. Any AWS API call makes a CloudTrail event. For application log groups, a test log line works. Then examine the CloudWatch Logs group of the forwarder Lambda:
- For the Console path, the group is
/aws/lambda/SenseOn-Forwarder. - For the Terraform path, use
terraform output forwarder_log_group_nameto get the group name.
A clean run with no exceptions means that the Lambda got to the ingestion endpoint successfully.
Good practice
- Additive, not disruptive: When you enable CloudWatch Logs delivery on an existing CloudTrail trail, this never changes or replaces its existing S3 delivery.
- No cross-account access required: This path is a push model from your account. For this path, SenseOn never has to have a role or credentials into your AWS account.
- Filter deliberately, not by default: Refer to the warning in the Console tab of Step 3. For a source that you use for detection, it is safer to start with no filter.
- Turn off
DEBUG_LOG_ENVELOPESwhen done: This setting is a diagnostic aid. Do not leave it on, because it prints real log content into CloudWatch. - The stack only ever removes what it created: The stack in the Terraform tab of Step 3 only reads your log groups. It never owns them. Thus, you can apply the stack and later remove it at any time. This is safe for a real log group.