### CloudWatch Logs Configuration Example Source: https://github.com/airbnb/streamalert/blob/master/docs/source/config-clusters.rst Example configuration for the cloudwatch_logs_destination module, including cross-account IDs and region settings. This setup requires the Kinesis module to be enabled as well. ```json { "id": "cloudwatch-logs-example", "classifier_config": { "enable_custom_metrics": true, "log_level": "info", "log_retention_days": 14, "memory": 128, "timeout": 60 }, "data_sources": { "kinesis": { "abc_prod_streamalert": [ "cloudwatch" ] } }, "modules": { "cloudwatch_logs_destination": { "cross_account_ids": [ "111111111111" ], "enabled": true, "regions": [ "ap-northeast-1", "ap-northeast-2", "ap-southeast-2" ] }, "kinesis": { "streams": { "retention": 96, "shards": 10 } }, "kinesis_events": { "batch_size": 100, "enabled": true } } } ``` -------------------------------- ### Log Pattern Matching Examples Source: https://github.com/airbnb/streamalert/blob/master/docs/source/config-schemas.rst Examples of logs that do not match and do match the configured log patterns. ```json { "computer_name": "test-server-name", "hostname": "okay_host", "instance_id": "95909", "process_id": "82571", "message": "this is not important info", "timestamp": "1427381694.88", "type": "good.log.type.value" } ``` ```json { "computer_name": "fake-server-name", "hostname": "bad_host", "instance_id": "589891", "process_id": "72491", "message": "this is super important info", "timestamp": "1486943917.12", "type": "bad.log.type.value" } ``` -------------------------------- ### Syslog Format and Example Logs Source: https://github.com/airbnb/streamalert/blob/master/docs/source/config-schemas.rst Displays the expected log format and example log entries for the Syslog parser. ```default timestamp(Month DD HH:MM:SS) host application: message ``` ```default Jan 10 19:35:33 vagrant-ubuntu-trusty-64 sudo: session opened for root Jan 10 19:35:13 vagrant-ubuntu-precise-32 ssh[13941]: login for user ``` -------------------------------- ### Configure Slack output Source: https://github.com/airbnb/streamalert/blob/master/docs/source/outputs.rst Example command to initiate the configuration process for a Slack integration. ```bash python manage.py output slack ``` -------------------------------- ### Run Unit Tests Source: https://github.com/airbnb/streamalert/blob/master/docs/source/getting-started.rst Execute the unit test script to verify the installation. ```bash tests/scripts/unit_tests.sh ``` -------------------------------- ### Install Python Requirements Source: https://github.com/airbnb/streamalert/blob/master/docs/source/getting-started.rst Install the required Python packages using pip. ```bash pip install -r requirements.txt ``` -------------------------------- ### Firehose configuration example in global.json Source: https://github.com/airbnb/streamalert/blob/master/docs/source/config-global.rst Example of the firehose configuration block within the infrastructure section of global.json. It shows how to enable Firehose, set the bucket name, buffer size and interval, and configure enabled_logs with per-log settings such as enable_alarm and evaluation_periods. ```json { "infrastructure": { "firehose": { "enabled": true, "bucket_name": "-streamalert-data", "buffer_size": 64, "buffer_interval": 300, "enabled_logs": { "osquery": { "enable_alarm": true }, "cloudwatch:cloudtrail": {}, "ghe": { "enable_alarm": true, "evaluation_periods": 10, "period_seconds": 3600, "log_min_count_threshold": 100000 } } } } } ``` -------------------------------- ### Example App List Output Source: https://github.com/airbnb/streamalert/blob/master/docs/source/apps.rst Sample output showing the configuration details for an App named duo_prod_collector. ```default Cluster: prod Name: duo_prod_collector log_level: info interval: rate(2 hours) timeout: 80 memory: 128 type: duo_auth ``` -------------------------------- ### CloudWatch Events Configuration Example Source: https://github.com/airbnb/streamalert/blob/master/docs/source/config-clusters.rst A complete configuration example for the cloudwatch_events module, including event patterns, cross-account settings, and required Kinesis module configuration. ```json { "id": "cloudwatch-events-example", "classifier_config": { "enable_custom_metrics": true, "log_level": "info", "log_retention_days": 14, "memory": 128, "timeout": 60 }, "data_sources": { "kinesis": { "abc_prod_streamalert": [ "cloudwatch" ] } }, "modules": { "cloudwatch_events": { "event_pattern": { "account": [ "123456789012" ], "detail-type": [ "EC2 Instance Launch Successful", "EC2 Instance Launch Unsuccessful", "EC2 Instance Terminate Successful", "EC2 Instance Terminate Unsuccessful" ] }, "cross_account": { "accounts": { "123456789012": [ "us-east-1" ] }, "organizations": { "o-aabbccddee": [ "us-east-1" ] } } }, "kinesis": { "streams": { "retention": 96, "shards": 10 } }, "kinesis_events": { "batch_size": 100, "enabled": true } } } ``` -------------------------------- ### Start Vagrant Virtual Machine Source: https://github.com/airbnb/streamalert/blob/master/streamalert_cli/_infrastructure/modules/tf_globals/lambda_layers/README.rst Initialize the virtual machine using the Vagrantfile provided in the repository root. ```bash # It may take few minutes to start the virtual machine for the first time, depending on your network speed $ vagrant up ``` -------------------------------- ### KV Parser Schema and Log Example Source: https://github.com/airbnb/streamalert/blob/master/docs/source/config-schemas.rst Example schema configuration and a corresponding log line for the KV parser. ```json { "example_kv_log_type": { "parser": "kv", "schema": { "time": "integer", "user": "string", "result": "string" } } } ``` ```default "time=1039395819 user=bob result=pass" ``` -------------------------------- ### Kinesis Module Configuration Example Source: https://github.com/airbnb/streamalert/blob/master/docs/source/config-clusters.rst Example configuration for the Kinesis module, including classifier settings, data sources, and stream-specific parameters like shard count and retention. ```json { "id": "kinesis-example", "classifier_config": { "enable_custom_metrics": true, "log_level": "info", "log_retention_days": 14, "memory": 128, "timeout": 60 }, "data_sources": { "kinesis": { "abc_prod_streamalert": [ "cloudwatch" ] } }, "modules": { "kinesis": { "streams": { "create_user": true, "retention": 24, "shard_level_metrics": [ "IncomingBytes", "IncomingRecords", "IteratorAgeMilliseconds", "OutgoingBytes", "OutgoingRecords", "WriteProvisionedThroughputExceeded" ], "shards": 1, "terraform_outputs": [ "user_arn", "access_key_id", "secret_key" ] } }, "kinesis_events": { "batch_size": 100, "enabled": true } } } ``` -------------------------------- ### Install Terraform on MacOS Source: https://github.com/airbnb/streamalert/blob/master/docs/source/getting-started.rst Install Terraform using Homebrew and verify the version is at least 0.13.0. ```bash brew install terraform # MacOS Homebrew terraform --version # Must be >= v0.13.0 ``` -------------------------------- ### Telemetry Data Example Source: https://github.com/airbnb/streamalert/blob/master/docs/source/lookup-tables.rst An example of telemetry data containing a hostname. ```default { "hostname": "securityiscool.airbnb.com", ... } ``` -------------------------------- ### Configure AWS CLI Credentials Source: https://github.com/airbnb/streamalert/blob/master/docs/source/getting-started.rst Install the AWS CLI and run the configuration wizard to set up credentials. ```bash pip install --user awscli aws configure ``` -------------------------------- ### Get help for app configuration Source: https://github.com/airbnb/streamalert/blob/master/docs/source/apps.rst Use this command to view help options for creating a new StreamAlert app. ```bash python manage.py app new --help ``` -------------------------------- ### Inline Whitelist Example Source: https://github.com/airbnb/streamalert/blob/master/docs/source/lookup-tables.rst An example of a hardcoded IP whitelist defined directly in the code. ```python IP_WHITELIST = [ '2.2.2.2', '8.8.8.8', '8.0.8.0', ] ``` -------------------------------- ### Install Python Development Libraries on Linux Source: https://github.com/airbnb/streamalert/blob/master/docs/source/getting-started.rst Install necessary Python development libraries for Debian or CentOS/RHEL systems. ```bash sudo apt install python-dev # Debian sudo yum install python-devel # CentOS/RHEL ``` -------------------------------- ### Configure Athena Partitioner Lambda Source: https://github.com/airbnb/streamalert/blob/master/docs/source/historical-search.rst Example configuration for the Athena Partitioner Lambda function in conf/lambda.json. ```json { "athena_partitioner_config": { "log_level": "info", "memory": 128, "buckets": { "alternative_bucket": "data" }, "file_format": "parquet", "timeout": 60 } } ``` -------------------------------- ### Example prompts for Duo Auth Source: https://github.com/airbnb/streamalert/blob/master/docs/source/apps.rst These are the prompts displayed by the CLI to collect authentication information for Duo Security integration. ```default Please supply the API URL for your duosecurity instance. This should be in a format similar to 'api-abcdef12.duosecurity.com': api-abcdef12.duosecurity.com Please supply the secret key for your duosecurity Admin API. This should be a string of 40 alphanumeric characters: 123424af2ae101d47d9704b783c940dffa825678 Please supply the integration key for your duosecurity Admin API. This should be in a format similar to 'DIABCDEFGHIJKLMN1234': DIABCDEFGHIJKLMN1234 ``` -------------------------------- ### DynamoDB driver configuration example Source: https://github.com/airbnb/streamalert/blob/master/docs/source/lookup-tables.rst Example configuration for the DynamoDB driver. The partition key and sort key must be string types. The table must be in the same AWS region as the StreamAlert deployment. Multiple LookupTables can overlap on a single table using different value_key values. Consistent reads can be enabled for immediate availability at the cost of performance. ```json { "driver": "dynamodb", "table": "some_table_name", "partition_key": "MyPartitionKey", "sort_key": "MySortKey", "value_key": "MyValueKey", "consistent_read": false, "key_delimiter": ":", "cache_refresh_minutes": 2, "cache_maximum_key_count": 10 } ``` -------------------------------- ### Nested CSV Log Example Source: https://github.com/airbnb/streamalert/blob/master/docs/source/config-schemas.rst Example logs and the corresponding schema configuration for parsing CSV logs with nested fields. ```default "1485729127","john_adams","memcache,us-east1" "1485729127","john_adams","mysqldb,us-west1" ``` ```json { "example_csv_with_nesting": { "parser": "csv", "schema": { "time": "integer", "user": "string", "message": { "role": "string", "region": "string" } } } } ``` -------------------------------- ### Box.com Event Log Example Source: https://github.com/airbnb/streamalert/blob/master/docs/source/conf-schemas-examples.rst A sample JSON log entry for a Box.com event. ```json { "source": { "item_type": "file", "item_id": "111111111111", "item_name": "my-file.pdf", "parent": { "type": "folder", "name": "Files", "id": "22222222222" } }, "created_by": { "type": "user", "id": "111111111", "name": "User Name", "login": "user.name@domain.com" }, "created_at": "2017-01-01T00:00:00-07:00", "event_id": "111ccc11-7777-4444-aaaa-dddddddddddddd", "event_type": "EDIT", "ip_address": "127.0.0.1", "type": "event", "session_id": null, "additional_details": { "shared_link_id": "sadfjaksfd981348fkdqwjwelasd9f8", "size": 14212335, "ekm_id": "111ccc11-7777-4444-aaaa-dddddddddd", "version_id": "111111111111", "service_id": "5555", "service_name": "Box Sync for Mac" } } ``` -------------------------------- ### Build Dependencies on EC2 Instance Source: https://github.com/airbnb/streamalert/blob/master/streamalert_cli/_infrastructure/modules/tf_globals/lambda_layers/README.rst Commands to prepare the environment, install dependencies into a 'python' directory, and create a zip archive for Lambda Layers. ```bash # Remove any previous caches $ rm -rf $HOME/.cache/pip/ # Create and source venv $ python3.7 -m venv $HOME/venv $ source $HOME/venv/bin/activate # Upgrade pip and setuptools (they are super old) $ pip install --upgrade pip setuptools # Make a temp build directory and temp pip install directory $ mkdir -p $HOME/build_temp $HOME/pip_temp/python # Install all of the dependencies to this directory $ pip install boxsdk[jwt]==2.6.1 --build $HOME/build_temp/ --target $HOME/pip_temp/python # Replace the `boxsdk[jwt]==2.6.1` below with the desired package & version # For example, the following would update the aliyun dependencies: # pip install aliyun-python-sdk-actiontrail==2.0.0 --build $HOME/build_temp/ --target $HOME/pip_temp # Change into the install directory $ cd $HOME/pip_temp # Cleanup any pyc files $ find . -name '*.pyc' | xargs rm -rf # Zip it all up $ zip -r pip.zip . # Exit the ssh session $ exit ``` -------------------------------- ### Build Dependencies via Vagrant Source: https://github.com/airbnb/streamalert/blob/master/streamalert_cli/_infrastructure/modules/tf_globals/lambda_layers/README.rst Commands to SSH into the Vagrant VM, install dependencies, and package them into a zip file. ```bash $ vagrant ssh # make sure you create virtual environment with python3.7 $ which python3.7 # Create and source venv $ python3.7 -m venv venv && source venv/bin/activate # upgrade pip and setuptools if neccessary $ pip install --upgrade pip setuptools $ mkdir -p $HOME/build_temp $HOME/pip_temp/python $ pip install boxsdk[jwt]==2.9.0 --build $HOME/build_temp/ --target $HOME/pip_temp/python # Replace the `boxsdk[jwt]==2.6.1` below with the desired package & version # For example, the following would update the aliyun dependencies: # pip install aliyun-python-sdk-actiontrail==2.0.0 --build $HOME/build_temp/ --target $HOME/pip_temp $ cd $HOME/pip_temp $ find . -name '*.pyc' | xargs rm -rf # Install zip package $ sudo apt-get install zip $ zip -r pip.zip . ``` -------------------------------- ### Register a publisher for a specific rule output Source: https://github.com/airbnb/streamalert/blob/master/docs/source/publishers.rst This example demonstrates how to apply a publisher to a specific output (PagerDuty) while leaving other outputs (Slack) unaffected. ```python from publishers.pagerduty import simplify_pagerduty_output from streamalert.shared.rule import Rule @rule( logs=['ssh'], outputs=['slack:engineering', 'pagerduty:engineering'], publishers={ 'pagerduty:engineering': simplify_pagerduty_output, } ) def machine_ssh_login(rec): # ... ``` -------------------------------- ### Optional Top Level Keys Log Input Source: https://github.com/airbnb/streamalert/blob/master/docs/source/config-schemas.rst Example log missing optional keys. ```json { "key1": [ 1, 2, 3 ], "key2": "test", "key3": 100, "key4": true } ``` -------------------------------- ### Configure the globals module Source: https://github.com/airbnb/streamalert/blob/master/streamalert_cli/_infrastructure/modules/tf_globals/README.md Example usage of the globals Terraform module with required input parameters. ```hcl module "globals" { source = "../modules/tf_globals" account_id = "112233445566" region = "us-east-1" prefix = "mycompany" } ``` -------------------------------- ### Inspec Log Example Source: https://github.com/airbnb/streamalert/blob/master/docs/source/conf-schemas-examples.rst A sample JSON log entry generated by Inspec. ```json { "version": "1.4.1", "profiles": [ { "supports": [], "controls": [ { "title": null, "desc": null, "impact": 0.5, "refs": [], "tags": {}, "code": "code-snip", "source_location": { "ref": "/lib/inspec/control_eval_context.rb", "line": 87 }, "id": "(generated from osquery.rb:6 de0aa7d2405c27dfaf34a56e2aa67842)", "results": [ { "status": "passed", "code_desc": "File /var/osquery/osquery.conf should be file", "run_time": 0.001332, "start_time": "2017-01-01 00:00:00 -0700" } ] } ], "groups": [ { "title": null, "controls": [ "(generated from osquery.rb:1 813971f93b6f1a66e85f6541d49bbba5)", "(generated from osquery.rb:6 de0aa7d2405c27dfaf34a56e2aa67842)" ], "id": "osquery.rb" } ], "attributes": [] } ], "other_checks": [], "statistics": { "duration": 0.041876 } } ``` -------------------------------- ### Standard JSON Log Example Source: https://github.com/airbnb/streamalert/blob/master/docs/source/config-schemas.rst A standard log format where all fields are at the top level. ```json { "example": 1, "host": "myhostname.domain.com", "time": "10:00 AM" } ``` -------------------------------- ### Nested JSON Regex Parsing Example Source: https://github.com/airbnb/streamalert/blob/master/docs/source/config-schemas.rst Example of log data wrapped with additional context keys requiring regex parsing. ```json { "collector": "my-app-1", "date-collected": "Oct 12, 2017", "@timestamp": "1507845487", "data": "<0> program[pid]: {'actual': 'data is here'}" } ``` -------------------------------- ### Sample Publisher Implementation Source: https://github.com/airbnb/streamalert/blob/master/docs/source/publishers.rst Example of modifying the publication dictionary. Publishers should return a dict containing only simple types. ```python from streamalert.shared.publisher import Register @Register def sample_publisher(alert, publication): publication['new_field'] = 'new_value'] publication.pop('old_field', None) return publication ``` -------------------------------- ### List Terraform targets and build specific modules Source: https://github.com/airbnb/streamalert/blob/master/docs/source/deployment.rst Use 'list-targets' to see available Terraform targets, then use 'build' with '--target' to apply specific changes and speed up Terraform runs. The output shows example targets; the build commands apply to single or multiple modules. ```bash python manage.py list-targets Target Type ---------------------------------------------------------------------------------------------- ... classifier_prod_iam module classifier_prod_lambda module cloudwatch_monitoring_prod module kinesis_events_prod module kinesis_prod module metric_filters_Classifier_FailedParses_PROD module metric_filters_Classifier_FirehoseFailedRecords_PROD module metric_filters_Classifier_FirehoseRecordsSent_PROD module ... ``` ```bash python manage.py build --target cloudwatch_monitoring_prod # apply to single module ``` ```bash python manage.py build --target kinesis_prod classifier_prod_iam # apply to two modules ``` ```bash python manage.py build --target metric_filters_Classifier_*_PROD # apply to three modules ``` -------------------------------- ### Basic Cluster Configuration Source: https://github.com/airbnb/streamalert/blob/master/docs/source/config-clusters.rst A minimal cluster configuration example demonstrating the classifier_config block and a basic Kinesis data source. ```json { "id": "minimal-cluster", "classifier_config": { "enable_custom_metrics": true, "log_level": "info", "log_retention_days": 14, "memory": 128, "timeout": 60 }, "data_sources": { "kinesis": { "abc_corporate_streamalert": [ "cloudwatch" ] } } } ``` -------------------------------- ### Configure Lambda Module and IAM Policy Source: https://github.com/airbnb/streamalert/blob/master/streamalert_cli/_infrastructure/modules/tf_lambda/README.md Example configuration for the alert_processor module and an associated custom IAM role policy. ```hcl module "alert_processor" { function_name = "alert_processor" handler = "streamalert.alert_processor.main.handler" filename = "alert_processor.zip" environment_variables = { LOGGER_LEVEL = "info" } // Commonly used optional variables description = "Function Description" memory_size_mb = 128 timeout_sec = 60 vpc_subnet_ids = ["abc"] vpc_security_group_ids = ["id0"] log_retention_days = 14 alarm_actions = ["SNS_ARN"] errors_alarm_threshold = 1 enable_iterator_age_alarm = true } // Add additional permissions resource "aws_iam_role_policy" "policy" { name = "CustomPolicy" role = "${module.alert_processor.role_id}" policy = "${data.aws_iam_policy_document.policy.json}" } data "aws_iam_policy_document" "policy" { statement { effect = "Allow" actions = ["s3:PutObject"] resources = ["arn:aws:s3:::..."] } } ``` -------------------------------- ### Implement a Custom App Integration Source: https://github.com/airbnb/streamalert/blob/master/docs/source/apps.rst A non-functional example demonstrating how to implement a new App by subclassing AppIntegration for the Box Events API. ```python # streamalert/apps/_apps/box.py from . import AppIntegration, LOGGER, StreamAlertApp @StreamAlertApp class BoxApp(AppIntegration): """Box StreamAlert App""" _BOX_API_V2_EVENTS_ENDPOINT = 'https://api.box.com/2.0/events' _MAX_EVENTS_LIMIT = 500 # Implement this abstractproperty @classmethod def service(cls): return 'box' # Implement this abstractproperty @classmethod def _type(cls): return 'admin_logs' # Implement this abstractmethod def required_auth_info(self): return { 'secret_key': { 'description': ('the secret key for this Box instance...'), 'format': re.compile(r'...') }, 'client_id': { 'description': ('the client_id for this Box instance...'), 'format': re.compile(r'...') }, 'token': { 'description': ('the token for this Box instance...'), 'format': re.compile(r'...') } } # Implement this abstractmethod def _sleep_seconds(self): """Return the number of seconds this polling function should sleep for between requests Box imposes the following API limits: 10 API calls per second per user Box reference: https://developer.box.com/reference#rate-limiting Basically, this function should guarantee we sleep for 1 second every 10 requests Returns: int: Number of seconds that this function should sleep for between requests """ return self._poll_count / 10 * 1 # Implement this abstractmethod def _gather_logs(self): """Gather the Box event logs. This function should set a few things on the superclass: self._last_timestamp # Set to the last timestamp/stream position from the logs self._more_to_poll # Set to True if the max # of logs was polled this time Returns: list or bool: The list of logs fetched from the service, or False if there was an error during log collection. """ headers = {'Authorization': 'Bearer {}'.format(self._get_oauth())} params = {'stream_position': self._last_timestamp, 'limit': self._MAX_EVENTS_LIMIT, 'stream_type': 'admin_logs'} # Make the request to the api, resulting in a bool or dict response = self._make_request(self._BOX_API_V2_EVENTS_ENDPOINT, headers=headers, params=params) if not response: return False logs = response['entries'] # Set the last timestamp to the next stream position to be used in the next poll self._last_timestamp = response['next_stream_position'] # Set self._more_to_poll to indicate there are more logs to collect self._more_to_poll = len(logs) >= self._MAX_EVENTS_LIMIT return logs def _get_oauth(self): """This should return the oauth token for this request""" secret_key = self._config.auth['secret_key'] client_id = self._config.auth['client_id'] token = self._config.auth['token'] # Do something to generate oauth return generated_oauth ``` -------------------------------- ### CloudWatch Monitoring Configuration Example Source: https://github.com/airbnb/streamalert/blob/master/docs/source/config-clusters.rst This JSON configuration enables Kinesis and Lambda alarms and demonstrates how to tune specific alarm thresholds. ```json { "id": "cloudwatch-monitoring-example", "classifier_config": { "enable_custom_metrics": true, "log_level": "info", "log_retention_days": 14, "memory": 128, "timeout": 60 }, "data_sources": { "kinesis": { "abc_prod_streamalert": [ "cloudwatch" ] } }, "modules": { "cloudwatch_monitoring": { "enabled": true, "kinesis_alarms_enabled": true, "lambda_alarms_enabled": true, "settings": { "lambda_invocation_error_threshold": 0, "lambda_throttle_error_threshold": 0, "kinesis_iterator_age_error_threshold": 1000000, "kinesis_write_throughput_exceeded_threshold": 10 } } } } ``` -------------------------------- ### Configure CloudTrail to CloudWatch Module Source: https://github.com/airbnb/streamalert/blob/master/streamalert_cli/_infrastructure/modules/tf_cloudtrail/modules/tf_cloudtrail_cloudwatch/README.md Example usage of the cloudtrail_to_cloudwatch module, including required parameters like region, prefix, and cluster, as well as optional CloudWatch destination configuration. ```hcl module "cloudtrail_to_cloudwatch" { source = "./modules/tf_cloudtrail/modules/tf_cloudtrail_cloudwatch" region = "us-east-1" prefix = "company" cluster = "prod" cloudwatch_destination_arn = "arn:aws:logs:us-east-1:123456789012:destination:company_prod_streamalert_log_destination" // Output from another module retention_in_days = 4 exclude_home_region_events = true } ``` -------------------------------- ### Define a rule with a publisher Source: https://github.com/airbnb/streamalert/blob/master/docs/source/testing.rst Example of a rule definition using the @rule decorator, specifying logs, outputs, and a publisher. ```python @rule( logs=['cloudwatch:events'], outputs=['slack:sample-channel'], publishers={'slack': my_publisher} ) def my_rule(record): # .. something logic return True ``` -------------------------------- ### CloudWatch EC2 Event Log Example Source: https://github.com/airbnb/streamalert/blob/master/docs/source/conf-schemas-examples.rst A sample JSON log entry for an EC2 instance state-change notification. ```json { "version": "0", "id": "6a7e8feb-b491-4cf7-a9f1-bf3703467718", "detail-type": "EC2 Instance State-change Notification", "source": "aws.ec2", "account": "111122223333", "time": "2015-12-22T18:43:48Z", "region": "us-east-1", "resources": [ "arn:aws:ec2:us-east-1:123456789012:instance/i-12345678" ], "detail": { "instance-id": "i-12345678", "state": "terminated" } } ``` -------------------------------- ### Configure cloudwatch_events module Source: https://github.com/airbnb/streamalert/blob/master/streamalert_cli/_infrastructure/modules/tf_cloudwatch_events/README.md Example usage of the cloudwatch_events module, requiring a prefix, cluster name, event pattern, and the Kinesis stream ARN. ```hcl module "cloudwatch_events" { source = "./modules/tf_cloudwatch_events" prefix = "company" cluster = "prod" event_pattern = "{\"accountId\": [\"123456789012\"]}" kinesis_arn = "arn:aws:kinesis:us-east-1:123456789012:stream/company_prod_streamalert" // Output from another module } ``` -------------------------------- ### Main Module Configuration Source: https://github.com/airbnb/streamalert/blob/master/streamalert_cli/_infrastructure/modules/tf_cloudwatch_logs_destination/README.md Example configuration for the main CloudWatch Logs destination module, which creates the IAM role assumable by the logs service. ```hcl module "cwl_destination_role" { source = "./modules/tf_cloudwatch_logs_destination" prefix = "orgname" cluster = "prod" destination_kinesis_stream_arn = "arn:aws:kinesis:region:account-id:stream/stream-name" regions = ["us-east-1", "us-west-1"] } ``` -------------------------------- ### CloudTrail Module Configuration Source: https://github.com/airbnb/streamalert/blob/master/streamalert_cli/_infrastructure/modules/tf_cloudtrail/README.md Example usage of the CloudTrail Terraform module, including required account IDs, region, and logging destinations. ```hcl module "cloudtrail" { source = "./modules/tf_cloudtrail" primary_account_id = "123456789012" region = "us-east-1" prefix = "company" cluster = "prod" s3_cross_account_ids = ["456789012345"] enable_logging = true is_global_trail = true s3_logging_bucket = "logging-bucket-name" s3_bucket_name = "cloudtrail-bucket-name" s3_event_selector_type = "All" cloudwatch_logs_role_arn = "arn:aws:iam::123456789012:role/streamalert/company_prod_cloudwatch_logs_subscription_role" // Output from another module cloudwatch_logs_group_arn = "arn:aws:logs:us-east-1:123456789012:log-group:CloudTrail/DefaultLogGroup" // Output from another module } ``` -------------------------------- ### Define log schemas in conf/schemas Source: https://github.com/airbnb/streamalert/blob/master/docs/source/config-global.rst Example of schema definitions for various log types and subtypes that determine which Firehose resources are created based on the enabled_logs configuration. ```json { "cloudwatch:events": { "parser": "json", "schema": {"key": "type"} }, "cloudwatch:cloudtrail": { "parser": "json", "schema": {"key": "type"} }, "osquery:differential": { "parser": "json", "schema": {"key": "type"} }, "osquery:status": { "parser": "json", "schema": {"key": "type"} } } ``` -------------------------------- ### Configure VPC Flow Logs Source: https://github.com/airbnb/streamalert/blob/master/docs/source/config-clusters.rst Example JSON configuration for enabling VPC Flow Logs, including Kinesis and Kinesis Events modules. Requires one of enis, subnets, or vpcs to be set to function. ```json { "id": "prod", "classifier_config": { "enable_custom_metrics": true, "log_level": "info", "log_retention_days": 14, "memory": 128, "timeout": 60 }, "data_sources": { "kinesis": { "abc_prod_streamalert": [ "cloudwatch:flow_logs" ] } }, "modules": { "flow_logs": { "enis": [], "enabled": true, "subnets": [ "subnet-12345678" ], "vpcs": [ "vpc-ed123456" ] }, "kinesis": { "streams": { "retention": 24, "shards": 10 } }, "kinesis_events": { "batch_size": 2, "enabled": true } } } ``` -------------------------------- ### Configure VPC Flow Logs Module Source: https://github.com/airbnb/streamalert/blob/master/streamalert_cli/_infrastructure/modules/tf_flow_logs/README.md Example configuration for the tf_flow_logs module, specifying the region, prefix, cluster, destination ARN, and target VPC IDs. ```hcl module "flow_logs_prod" { source = "./modules/tf_flow_logs" region = "us-east-1" prefix = "orgname" cluster = "prod" cloudwatch_logs_destination_arn = "${module.cloudwatch_destinations_prod_us-east-1.cloudwatch_logs_destination_arn}" // Output from tf_cloudwatch_logs_destination module vpcs = ["vpc-id-01"] } ``` -------------------------------- ### S3 Event Notification Configuration Source: https://github.com/airbnb/streamalert/blob/master/docs/source/config-clusters.rst Example configuration for the s3_events module, demonstrating how to define bucket names, optional filter prefixes, and suffixes to trigger the classifier function. ```json { "id": "s3-events-example", "classifier_config": { "enable_custom_metrics": true, "log_level": "info", "log_retention_days": 14, "memory": 128, "timeout": 60 }, "data_sources": { "s3": { "bucket_name_01": [ "cloudtrail" ], "bucket_name_02": [ "cloudtrail" ] } }, "modules": { "s3_events": { "bucket_name_01": [ { "filter_prefix": "AWSLogs/1234", "filter_suffix": ".log" }, { "filter_prefix": "AWSLogs/5678" } ], "bucket_name_02": [] } } } ``` -------------------------------- ### Example usage of last_hour helper Source: https://github.com/airbnb/streamalert/blob/master/docs/source/testing.rst A JSON test event configuration demonstrating the use of the last_hour helper to dynamically set a time field. ```json { "records": [ { "data": { "host": "app01.prod.mydomain.net", "time": "" }, "description": "example usage of helpers", "log": "host_time_log", "service": "kinesis", "source": "my_demo_kinesis_stream", "trigger_rules": [ "last_hour_rule_name" ] } ] } ``` -------------------------------- ### Configure Kinesis Terraform Module Source: https://github.com/airbnb/streamalert/blob/master/streamalert_cli/_infrastructure/modules/tf_kinesis_streams/README.md Example configuration for the Kinesis stream module, including required account, region, and cluster identifiers. ```hcl module "kinesis" { source = "../modules/tf_kinesis_streams" account_id = "333333444444" region = "us-east-1" prefix = "company-name" cluster = "cluster-name" stream_name = "name-for-kinesis-stream" shards = 10 retention = 72 } ``` -------------------------------- ### Create and Activate Virtual Environment Source: https://github.com/airbnb/streamalert/blob/master/docs/source/getting-started.rst Navigate to the project directory, create a Python 3.7 virtual environment, and activate it. ```bash cd streamalert python3.7 -m venv venv source venv/bin/activate ``` -------------------------------- ### Configure a new App Source: https://github.com/airbnb/streamalert/blob/master/docs/source/apps.rst Use the CLI to add a new app configuration with specific parameters like type, cluster, name, interval, timeout, and memory. ```bash python manage.py app new \ --type duo_auth \ --cluster prod \ --name duo_prod_collector \ --interval 'rate(2 hours)' \ --timeout 80 \ --memory 128 ``` -------------------------------- ### Destination Submodule Configuration Source: https://github.com/airbnb/streamalert/blob/master/streamalert_cli/_infrastructure/modules/tf_cloudwatch_logs_destination/README.md Example configuration for the destination submodule, which creates CloudWatch Log Destinations and policies in multiple regions using aliased providers. ```hcl module "cwl_destination" { source = "./modules/tf_cloudwatch_logs_destination/modules/destination" prefix = "orgname" cluster = "prod" destination_kinesis_stream_arn = "arn:aws:kinesis:region:account-id:stream/stream-name" account_ids = ["123456789012", "234567890123"] cloudwatch_logs_subscription_role_arn = ${module.cwl_destination_role.cloudwatch_logs_subscription_role_arn providers = ["aws.us-west-2"] // Aliased to provider in terraform/providers.tf } ``` -------------------------------- ### List Configured Apps Source: https://github.com/airbnb/streamalert/blob/master/docs/source/apps.rst Use this CLI command to list all currently configured Apps, grouped by cluster. ```bash python manage.py app list ``` -------------------------------- ### Create Test Log File Source: https://github.com/airbnb/streamalert/blob/master/docs/source/getting-started.rst Create a JSON file representing a sample log entry for testing. ```json { "account": "1234", "detail": { "eventType": "AwsConsoleSignIn", "userIdentity": { "type": "Root" } }, "detail-type": "CloudTrail Test", "id": "1234", "region": "us-east-1", "resources": [], "source": "1.1.1.2", "time": "now", "version": "2018" } ``` -------------------------------- ### Normalization v2 condition block examples Source: https://github.com/airbnb/streamalert/blob/master/docs/source/normalization.rst Examples of the optional condition block used to filter when a normalizer is applied, supporting various comparison operators. ```default "condition": { "path": ["account"], "is": "123456" } "condition": { "path": ["detail", "userIdentity", "userName"], "in": ["root", "test_username"] } ``` -------------------------------- ### Configure kinesis_firehose module Source: https://github.com/airbnb/streamalert/blob/master/streamalert_cli/_infrastructure/modules/tf_kinesis_firehose_setup/README.md Example usage of the kinesis_firehose module within a Terraform configuration. ```hcl module "kinesis_firehose" { source = "../modules/tf_kinesis_firehose_setup" account_id = "111111222222" region = "us-east-1" prefix = "my-company" logs = ["json_data", "csv_data"] s3_bucket_name = "my-data-bucket.id" s3_logging_bucket = "my-logging-bucket.id" } ``` -------------------------------- ### Casting Special Types Log Input Source: https://github.com/airbnb/streamalert/blob/master/docs/source/config-schemas.rst Example log before parsing with nested data. ```json { "field_1": "test-string", "field_2": "100", "field_3": { "data": "misc-data", "time": "1491584265" } } ``` -------------------------------- ### Deploy functions Source: https://github.com/airbnb/streamalert/blob/master/docs/source/apps.rst Deploy the apps and classifier functions to apply the new configuration. ```bash python manage.py deploy --functions classifier apps ``` -------------------------------- ### Deploy Rule Promotion Lambda Source: https://github.com/airbnb/streamalert/blob/master/docs/source/rule-promotion.rst Use the manage.py script to deploy the Rule Promotion infrastructure and function code. ```bash python manage.py deploy --functions rule_promo ``` -------------------------------- ### Initialize StreamAlert Source: https://github.com/airbnb/streamalert/blob/master/docs/source/deployment.rst Run this command to perform the initial build of StreamAlert. It creates S3 buckets and encryption keys, creates AWS Lambda functions, builds declared infrastructure in Terraform files, and deploys initial production AWS Lambda versions. Type 'yes' at each prompt. ```bash python manage.py init ``` -------------------------------- ### Create SNS Topics Source: https://github.com/airbnb/streamalert/blob/master/docs/source/getting-started.rst Create the necessary SNS topics for data ingestion and alert delivery. ```bash aws sns create-topic --name streamalert-test-data aws sns create-topic --name streamalert-test-alerts ``` -------------------------------- ### @disable decorator Source: https://github.com/airbnb/streamalert/blob/master/docs/source/rules.rst Example of using the @disable decorator to temporarily disable a rule while keeping its definition and tests. ```APIDOC ## @disable ### Description Temporarily disables a rule. The rule definition and tests remain in place but the rule will not be evaluated. ### Usage Place @disable above the @rule decorator. ### Example ```python from streamalert.shared.rule import disable, rule @disable # TODO: this rule is too noisy! @rule(logs=['example'], outputs=['slack']) def example_rule(record): return True ``` ``` -------------------------------- ### Register Publishers on a Rule Source: https://github.com/airbnb/streamalert/blob/master/docs/source/publishers.rst Example of registering publishers on a rule using the publisher argument on the @rule decorator. ```APIDOC ## Register Publishers on a Rule ### Description Register publishers on a rule using the `publisher` argument on the `@rule` decorator. ### Code Example ```python from publishers import publisher_1, publisher_2 from streamalert.shared.rule import Rule @rule( logs=['stuff'], outputs=['pagerduty', 'slack'], publishers=[publisher_1, publisher_2] ) def my_rule(rec): # ... ``` ``` -------------------------------- ### Nested JSON Log Example Source: https://github.com/airbnb/streamalert/blob/master/docs/source/config-schemas.rst A log format where fields to be parsed are nested within a 'logs.results' structure. ```json { "logs": { "results": [ { "example": 1, "host": "jumphost-1.domain.com", "time": "11:00 PM" }, { "example": 2, "host": "jumphost-2.domain.com", "time": "12:00 AM" } ] }, "id": 1431948983198, "application": "my-app" } ``` -------------------------------- ### List of publishers configuration Source: https://github.com/airbnb/streamalert/blob/master/docs/source/publishers.rst Applying a list of multiple publishers to all outputs. ```python publishers=[publisher_1, publisher_2, publisher_3] ``` -------------------------------- ### Dynamic output with external API source Source: https://github.com/airbnb/streamalert/blob/master/docs/source/dynamic-outputs.rst Demonstrates querying an external API to determine output destinations. Note that frequent API calls may impact performance. ```python from streamalert.shared.rule import rule import requests def dynamic_output(record): account_id = record.get('recipientaccountid') # invoke an external API to get data back response = requests.get("API/team_map") for team in response.json(): if account_id in team["accounts"]: return team["outputs"] # potentially "aws-lambda:team_a" @rule( logs=['cloudwatch:events'], outputs=["aws-sns:security], dynamic_outputs=[dynamic_output], ) def cloudtrail_root_account_usage(rec): # Rule logic ``` -------------------------------- ### Configure a new output service Source: https://github.com/airbnb/streamalert/blob/master/docs/source/outputs.rst Use the manage.py script to add a new configuration for a supported service. ```bash python manage.py output ``` -------------------------------- ### Configure streamalert_app module Source: https://github.com/airbnb/streamalert/blob/master/streamalert_cli/_infrastructure/modules/tf_app_iam/README.md Example usage of the streamalert_app Terraform module to define IAM permissions for a Lambda function. ```hcl module "streamalert_app" { account_id = "123456789012" region = "us-east-1" function_name = "testprefix_prod_duo_auth_duo_auth_app" function_role_id = "testprefix_prod_duo_auth_duo_auth_app_role_id" destination_function_name = "testprefix_prod_streamalert_classifier source = "../modules/tf_app_iam" } ``` -------------------------------- ### Casting Normal Types Log Input Source: https://github.com/airbnb/streamalert/blob/master/docs/source/config-schemas.rst Example log before parsing, showing string-based numeric and boolean values. ```json { "field_1": "test-string", "field_2": "100", "field_3": "true" } ``` -------------------------------- ### Build Metric Filters Source: https://github.com/airbnb/streamalert/blob/master/docs/source/normalization.rst Apply the custom metrics configuration by building the metric filters. ```bash python manage.py build --target "metric_filters_*" ``` -------------------------------- ### Copy Dependencies from Vagrant Locally Source: https://github.com/airbnb/streamalert/blob/master/streamalert_cli/_infrastructure/modules/tf_globals/lambda_layers/README.rst Move the zip file to the local host and exit the Vagrant session. ```bash $ cp pip.zip /vagrant/streamalert_cli/_infrastructure/modules/tf_globals/lambda_layers/boxsdk[jwt]==2.6.1_dependencies.zip $ exit # exit the session ``` -------------------------------- ### Configure cloudwatch_events_cross_account module Source: https://github.com/airbnb/streamalert/blob/master/streamalert_cli/_infrastructure/modules/tf_cloudwatch_events/cross_account/README.md Example usage of the module to permit events from specific AWS accounts and organizations in a given region. ```hcl module "cloudwatch_events_cross_account" { source = "./modules/tf_cloudwatch_events/cross_account" accounts = ["123456789012"] organizations = ["o-aabbccddee"] region = "us-east-1" } ``` -------------------------------- ### Conditional User Identity Normalization Source: https://github.com/airbnb/streamalert/blob/master/docs/source/normalization.rst Example of normalizing user identity only for specific AWS accounts using a condition block. ```json "cloudwatch:events": { "schema": { "account": "string", "detail": {}, "detail-type": "string", "id": "string", "region": "string", "resources": [], "source": "string", "time": "string", "version": "string" }, "parser": "json", "configuration": { "normalization": { "user_identity": [ { "path": ["detail", "userIdentity", "userName"], "function": "User identity username", "condition": { "path": ["account"], "in": ["11111111", "22222222"] } } ] } } } ```