Field Notes: Analyze Cross-Account AWS KMS Call Usage with AWS CloudTrail and Amazon Athena
AWS Architecture BlogField Notes: Analyze Cross-Account AWS KMS Call Usage with AWS CloudTrail and Amazon Athenaby Abhijit Rajeshirke and Abhijit Vaidya | on01 NOV 2021| inAmazon Athena,Architecture,AWS CloudTrail,AWS Key Management Service,Technical How-to|Permalink|ShareBusinesses are expanding their footprint on Amazon Web Services (AWS) and are adopting a multi-account strategy to help isolate and manage business applications and data. In the multi-account strategy, it is common to have business applications deployed in one account accessing anAmazon Simple Storage Service(Amazon S3) encrypted bucket from another AWS account.When an application in an AWS account uses aAWS Key Management Service(AWS KMS) key owned by a different account, it’s known as a cross-account call. For cross-account requests, AWS KMS throttles the account that makes the requests, not the account that owns the AWS KMS key. These requests count toward the request quota of the caller account. Sometimes it’s essential to identify or track cross-account AWS KMS API usage. In this blog, you will learn about use cases to track these requests and steps to identify cross-account AWS KMS calls.To understand the problem better, consider a scenario where you have multiple AWS accounts set up in a hub and spoke configuration as shown in the following diagram.  Each account is administered by a different administrator. Amazon S3 data lake is located in the centralized hub account. The data lake bucket is encrypted using server-side encryption with AWS KMS (SSE-KMS) with customer-managed keys. Multiple spoke accounts access datasets from this data lake bucket. When a spoke account uploads or downloads objects from the data lake, Amazon S3 makes aGenerateDataKey(for uploads) orDecrypt(for downloads) API request to AWS KMS on behalf of the spoke account. These API requests get applied toward AWS KMS quota of the spoke account.In the following diagram (figure 1), spoke accounts B, C, and D are uploading/downloading files from the encrypted data lake located in hub account A. Related AWS KMS API quotas will get applied to spoke accounts even though encryption/decryption is happening at the data lake S3 bucket. For example, the centralized Amazon S3 data lake is located in hub account A with an account ID 111111111111. Amazon S3 data lake bucket is encrypted using AWS KMS key ARN ending in 3aa3c82a2174.Spokeaccount Bwith account ID 222222222222 is downloading 1,811 files and uploading 749 files from the centralized data lake. A total of 2,560 AWS KMS API calls will be counted against the request quota for account B.Spokeaccount Cwith account ID 33333333333 is downloading 997 files and uploading 271 files from centralized data lake. A total of 1,268 AWS KMS API calls will be counted against the request quota for account C.Spokeaccount Dwith account ID 444444444444 is downloading 638 files and uploading 306 files from centralized data lake from centralized data lake. The total 944 AWS KMS API quotas will get applied to account D.Spoke and hub accounts are owned by separate business units and owned by different account administrators.Note:when you configure your bucket to use anS3 Bucket Keyfor SSE-KMS, you may not see separateDecryptorGenerateDataKeyfor each file upload or download.Figure 1: Architecture outlining the hub and spoke accountsThis architecture design works for the following three use cases.Use case #1:A spoke account administrator wants to track the individual AWS KMS key-wise encryption/decryption costs usingAWS Cost Explorerand cost allocation tags. Tracking costs this way works well for the AWS KMS API calls made within the same spoke account and related costs will be displayed under appropriate cost allocation tags. However, for the cross account AWS KMS API calls, cost allocation tags will not be visible outside of the hub account and will be displayed under cost allocation tag “None.” Analyzing cross-account AWS KMS API calls will help administrator determine approximate percentage usage by each cross account KMS key.Use case # 2:The spoke account has multiple applications, and each application has a uniqueAWS Identity and Access Management(IAM) principal. The spoke account administrator would like to track encryption/decryption usage. Identifying IAM principal-wise cross account calls will help the administrator determine approximate percent usage by each IAM principal /each application.Use case # 3:The spoke account administrator wants to understand how much AWS KMS quota is used for the cross-account specific KMS keys.Solution OverviewLet’s discuss how we can track cross-account AWS KMS calls usingAWS CloudTrailandAmazon Athena. For this solution, we will reuse your existing CloudTrail or create new CloudTrail in a Region where the hub account Amazon S3 data lake is located. As shown in the following diagram, we will use Athena to query the CloudTrail data to identify cross account AWS KMS calls used for S3 encryption/decryption.Figure 2: Architecture outlining the CloudTrail and Athena SolutionPrerequisitesFor this walkthrough, you should have the following prerequisites:AWS accounts (one for hub and at least one for spoke)AWS KMS (SSE-KMS) with customer managed keys encrypted S3 bucketWalkthroughStep 1: Activate AWS CloudTrail for the hub accountCloudTrail is a service that enables governance, compliance, operational auditing, and risk auditing of your AWS account. With CloudTrail, you can log, continuously monitor, and retain account activity across your AWS accounts. If you have already activated CloudTrail, you can reuse the same. If you haven’t, you can activate it using the steps in thistutorial. For the proposed solution, you must enable CloudTrail for management events only. You don’t require CloudTrail for data events or insight events. Also, be aware that you need only single CloudTrail and creating duplicate cloud trails can increase the service cost.Note:  you can analyze the data in Athena only when the CloudTrail data is available. Any access requests made prior to enabling CloudTrail cannot be analyzed. It takes up to 15 minutes for events to get to CloudTrail, and up to 5 minutes for CloudTrail to write to S3.Step 2: Create Amazon Athena table to query the CloudTrail dataAmazon Athenais an interactive query service that analyzes data in Amazon S3 using standard SQL. Athena is serverless, so there is no infrastructure to manage, and you pay only for the queries that you run. Create an Athena table in any database or default database in a Region where your hub account S3 data lake bucket resides.If you are using Athena for the first time, follow these steps tocreate a database. Once the database is created you need to create Athena table. Follow these steps to create a table:Open the Athena built-in query editor,copy the following query,modify as suggested,run the query.In the LOCATION andstorage.location.templateclauses, replace the bucket withCloudTrail bucket.ReplaceaccountId with hub account’sID and replaceawsRegion with region where data lake S3 bucket is located. Forprojection.timestamp.range, replace 2020/01/01 with the start date you want to use.After successful initiation of the query, you will see the CloudTrail_logs table created in Athena.CREATE EXTERNAL TABLE cloudtrail_logs_region(eventVersion STRING,userIdentity STRUCT<type: STRING,principalId: STRING,arn: STRING,accountId: STRING,invokedBy: STRING,accessKeyId: STRING,userName: STRING,sessionContext: STRUCT<attributes: STRUCT<mfaAuthenticated: STRING,creationDate: STRING>,sessionIssuer: STRUCT<type: STRING,principalId: STRING,arn: STRING,accountId: STRING,userName: STRING>>>,eventTime STRING,eventSource STRING,eventName STRING,awsRegion STRING,sourceIpAddress STRING,userAgent STRING,errorCode STRING,errorMessage STRING,requestParameters STRING,responseElements STRING,additionalEventData STRING,requestId STRING,eventId STRING,readOnly STRING,resources ARRAY<STRUCT<arn: STRING,accountId: STRING,type: STRING>>,eventType STRING,apiVersion STRING,recipientAccountId STRING,serviceEventDetails STRING,sharedEventID STRING,vpcEndpointId STRING)PARTITIONED BY (`timestamp` string)ROW FORMAT SERDE 'com.amazon.emr.hive.serde.CloudTrailSerde'STORED AS INPUTFORMAT 'com.amazon.emr.cloudtrail.CloudTrailInputFormat'OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'LOCATION's3://bucket/AWSLogs/account-id/CloudTrail/aws-region'TBLPROPERTIES ('projection.enabled'='true','projection.timestamp.format'='yyyy/MM/dd','projection.timestamp.interval'='1','projection.timestamp.interval.unit'='DAYS','projection.timestamp.range'='2020/01/01,NOW','projection.timestamp.type'='date','storage.location.template'='s3://bucket/AWSLogs/account-id/CloudTrail/aws-region/${timestamp}')Step 3: Identify cross account Amazon S3 encryption/decryption callsOnce the Athena table is created, you can run the following query to find out cross-account AWS KMS calls made for S3 encryption /decryption.Query:SELECT useridentity.accountid as requestor_account_id,resources[1].accountid as owner_account_id,resources[1].arn as key_arn,count(resources) as countFROM CloudTrail_logs_us_east_2WHERE eventsource='kms.amazonaws.com'AND timestamp between '2021/04/01' and '2021/08/30'AND eventname in ('Decrypt','Encrypt','GenerateDataKey')AND useridentity.accountid!= resources[1].accountidAND json_extract(json_extract(requestparameters , '$.encryptionContext'),'$.aws:s3:arn') is not nullGROUP BY  useridentity.accountid,resources[1].accountid,resources[1].arnORDER BY  key_arn,count descResult:Result displays the cross account AWS KMS calls made for S3 encryption /decryption i.e. where caller account is not the key owner account for time period between April 1, 2021 and August 30, 2021.The preceding example shows cross-account AWS KMS API calls generated by downloading /uploading files from centralized Amazon S3 data lake located in account A (111111111111) from spoke accounts B (222222222222), C (333333333333), and D (444444444444).These AWS KMS quotas will get applied to caller (spoke) accounts even though key owner is hub account.For example:2,560 AWS KMS API call quotas will be applied to account B.1,644 AWS KMS API call quotas will be applied to account C.944 AWS KMS API call quotas will be applied to account D.Step 4: Identify IAM principal-wise cross account Amazon S3 encryption/decryption calls.To identify IAM principal-wise cross account Amazon S3 encryption /decryption calls, you can run following query.Query:SELECT useridentity.accountid as requestor_account_id,useridentity.principalid as requestor_principal,resources[1].accountid as owner_account_id,resources[1].arn as key_arn,count(resources) as countFROM CloudTrail_logs_us_east_2WHERE eventsource='kms.amazonaws.com'AND timestamp between '2021/04/01' and '2021/08/30'AND eventname in ('Decrypt','Encrypt','GenerateDataKey')AND useridentity.accountid!= resources[1].accountidAND json_extract(json_extract(requestparameters , '$.encryptionContext'),'$.aws:s3:arn') is not nullGROUP BY useridentity.accountid,useridentity.principalid,resources[1].accountid,resources[1].arnORDER BY requestor_account_id,count descResult:The preceding result shows  AWS Identity and Access Management (IAM) principal-wise cross-account AWS KMS API calls made between hub and spoke accounts. For example, Account B (22222222222) has two applications configured with IAM principals ids ending with 4C5VIMGI2, 4YFPRTQMP are accessing the centralized S3 bucket located in hub account A (111111111111).For the time period between ‘2021/04/01’ and ‘2021/08/30’, the application configured with IAM principal ending in 4C5VIMGI2 made 1622 cross-account AWS KMS API calls. During this same time period, the application configured with IAM principal 4YFPRTQMP made 936 cross-account AWS KMS API calls.We can further filter the results to see only KMS key ARN ending with 3aa3c82a2174 to get application- wise % of AWS KMS API calls made to the Amazon S3 centralized data lake from all the spoke accounts.Note:  we assume that each application is configured with a unique IAM principal.Step 5: Identify cross account Amazon S3 encryption/decryption calls by events.Query:SELECT useridentity.accountid as requestor_account_id,resources[1].accountid as owner_account_id,resources[1].arn as key_arn,eventname as eventname,count(resources) as countFROM CloudTrail_logs_us_east_2WHERE eventsource='kms.amazonaws.com'AND timestamp between '2021/04/01' and '2021/08/30'AND useridentity.accountid!= resources[1].accountidAND json_extract(json_extract(requestparameters , '$.encryptionContext'),'$.aws:s3:arn') is not nullGROUP BY useridentity.accountid, resources [1].accountid,resources[1].arn,eventnameORDER BY requestor_account_id,count descResult:Amazon S3 makes decrypt API requests when you download the files and GenerateDataKey API request when you upload the file to encrypted S3 bucket. The result shows that:Spoke account B (22222222222) made 1811 decrypt API requests to download 1811 files and 749 GenerateDataKey API requests to uploaded 749 files.Spoke account C (33333333333) made 1373 decrypt API requests to download 1373 files and 271 GenerateDataKey API requests to uploaded 271 files.Spoke account D (444444444444) made 638 decrypt API requests to download 638 files and 306 GenerateDataKey API requests to uploaded 306 files.Note: When you configure your bucket to use anS3BucketKeyfor SSE-KMS, you may not have a separate Decrypt orGenerateDataKeyfor each file upload or download.Step 6: Identify all the AWS KMS Calls.To analyze the hub account for all the AWS KMS API calls made, run following query.Query:SELECT useridentity.accountid as requestor_account_id,resources[1].accountid as owner_account_id,resources[1].arn as key_arn,count(resources) as countFROM CloudTrail_logs_us_east_2WHERE eventsource='kms.amazonaws.com'AND timestamp between '2021/04/01' and '2021/08/30'GROUP BY useridentity.accountid, resources [1].accountid,resources[1].arnORDER BY requestor_account_id,count descResult:Results show all the AWS KMS API calls made in the hub account both within the account and across accounts. From this result, we can analyze that for centralized S3 data lake (KMS key ARN ending with 3aa3c82a2174), the majority of the calls are cross account AWS KMS API call and only 303 calls are made within account. You can do further analysis by refining the Amazon Athena queries based on your needs.Cleaning upTo avoid incurring future charges, delete the resources that are no longer required.Step 1: Delete the CloudTrail created in hub accountIf you have created CloudTrail specifically for this solution, you can delete the CloudTrail by following the instructions in thisuser guide.Step 2: Drop the Amazon Athena tableLog in to the Amazon Athena console and run the following drop table query:Drop table < CloudTrail_logs_aws_region_1>ConclusionTracking use of the cross-account AWS KMS APIs can be challenging in a multi-account scenario. In this blog, we learned how to use AWS CloudTrail and Amazon Athena to analyze AWS KMS API usage. In a hub and spoke account model, cross-account AWS KMS API quotas are applied to the spoke account when the spoke account accesses SSE-KMS encrypted S3 bucket in the hub account. You learned to analyze cross-account AWS KMS API quotas using AWS CloudTrail and Amazon Athena.  Finally, we learned how we can identify all the AWS KMS API call within account for period of time and analyze AWS KMS API traffic within account and across account. You can repeat the process and aggregate the data across Regions.Additional Reading:Manage your AWS KMS API request rates using Service Quotas and Amazon CloudWatchWhy did my CloudTrail cost and usage increase unexpectedly?Field Notes provides hands-on technical guidance from AWS Solutions Architects, consultants, and technical account managers, based on their experiences in the field solving real-world business problems for customers.TAGS:Field NotesAbhijit RajeshirkeAbhijit Rajeshirke is a Solutions Architect for the Enterprise customers at AWS. His core focus areas are Data Analytics, Big Data, and Serverless technologies. Outside of work, he enjoys taking long mindful walks on any available track or trails.Abhijit VaidyaAbhijit Vaidya is a partner solutions architect working with global systems integrators. He works with AWS partners and customers to provide them with architectural guidance for building scalable architecture in AWS environments. He enjoys reading, watching history/discovery channel programs.
Businesses are expanding their footprint on Amazon Web Services (AWS) and are adopting a multi-account strategy to help isolate and manage business applications and data. In the multi-account strategy, it is common to have business applications deployed in one account accessing an Amazon Simple Storage Service (Amazon S3) encrypted bucket from another AWS account. When […]
Abhijit Rajeshirke
Amazon Athena Architecture AWS CloudTrail AWS Key Management Service Technical How-to