Query Details

25 A03 Python Startup To Aws Secrets

Query

// REVIEW ONLY workbook query: 8.3 A03 Preview — AWS cross-cloud - Python startup artifacts and metadata access precede secrets use
let Start = {TimeRange:start};
let End = {TimeRange:end};
let AccountFilter = trim(" ", base64_decode_tostring("{AwsAccount:base64}"));
let UseAllAccounts = AccountFilter in ("", "*");
let TargetXdrTenant = tolower(trim(" ", base64_decode_tostring("{XdrTenantId:base64}")));
let SafeCloudTrail = union isfuzzy=true
  (datatable(TimeGenerated:datetime, AwsEventId:string, EventSource:string, EventName:string, AWSRegion:string,
    RecipientAccountId:string, UserIdentityAccountId:string, UserIdentityType:string, UserIdentityArn:string,
    UserIdentityAccessKeyId:string, SourceIpAddress:string, UserAgent:string,
    ErrorCode:string, ErrorMessage:string, RequestParameters:string, ResponseElements:string, Resources:string,
    ManagementEvent:bool, ReadOnly:bool, SessionMfaAuthenticated:string)[]),
  (AWSCloudTrail
   | where TimeGenerated between (Start .. End)
   | project TimeGenerated, AwsEventId, EventSource, EventName, AWSRegion, RecipientAccountId,
       UserIdentityAccountId, UserIdentityType, UserIdentityArn,
       UserIdentityAccessKeyId, SourceIpAddress, UserAgent, ErrorCode, ErrorMessage,
       RequestParameters, ResponseElements, Resources, ManagementEvent, ReadOnly, SessionMfaAuthenticated);
let IdentityMap = union isfuzzy=true
  (datatable(SearchKey:string)[]),
  (_GetWatchlist('AWS_EntraIdentityMap'))
| where isnotempty(tostring(column_ifexists("SearchKey", "")))
| extend VerifiedVal = tolower(tostring(column_ifexists("Verified", ""))),
    MappingEvidenceVal = tostring(column_ifexists("MappingEvidence", ""))
| where VerifiedVal == "true" and isnotempty(MappingEvidenceVal)
| project AwsAccessKeyId=tostring(column_ifexists("AwsAccessKeyId", "")),
    AwsPrincipalArn=tostring(column_ifexists("AwsPrincipalArn", "")),
    AWSAccountId=tostring(column_ifexists("AWSAccountId", "")),
    EntraTenantId=tolower(tostring(column_ifexists("EntraTenantId", ""))),
    EntraObjectId=tolower(tostring(column_ifexists("EntraObjectId", ""))),
    IdentityType=tostring(column_ifexists("IdentityType", "")),
    AppClientId=tolower(tostring(column_ifexists("AppClientId", ""))),
    ValidFrom=todatetime(column_ifexists("ValidFromUtc", "")),
    ValidTo=todatetime(column_ifexists("ValidToUtc", ""))
| summarize MappingRows=count(), take_any(*) by AwsAccessKeyId, AwsPrincipalArn, AWSAccountId
| where MappingRows == 1 and isnotempty(EntraTenantId) and isnotempty(EntraObjectId);
let AssetMap = union isfuzzy=true
  (datatable(SearchKey:string)[]),
  (_GetWatchlist('AWS_AssetIdentityMap'))
| where isnotempty(tostring(column_ifexists("SearchKey", "")))
| extend VerifiedVal = tolower(tostring(column_ifexists("Verified", ""))),
    MappingEvidenceVal = tostring(column_ifexists("MappingEvidence", ""))
| where VerifiedVal == "true" and isnotempty(MappingEvidenceVal)
| project AWSAccountId=tostring(column_ifexists("AWSAccountId", "")),
    AwsPrincipalArn=tostring(column_ifexists("AwsPrincipalArn", "")),
    AwsAccessKeyId=tostring(column_ifexists("AwsAccessKeyId", "")),
    DeviceId=tostring(column_ifexists("DeviceId", "")),
    XdrTenantId=tolower(tostring(column_ifexists("XdrTenantId", ""))),
    AwsInstanceId=tostring(column_ifexists("AwsInstanceId", "")),
    ValidFrom=todatetime(column_ifexists("ValidFromUtc", "")),
    ValidTo=todatetime(column_ifexists("ValidToUtc", ""))
| summarize MappingRows=count(), take_any(*) by AWSAccountId, AwsPrincipalArn, AwsAccessKeyId
| where MappingRows == 1 and isnotempty(DeviceId) and isnotempty(AwsInstanceId) and isnotempty(AwsAccessKeyId);
let ScopedAssets = AssetMap | where isempty(TargetXdrTenant) or XdrTenantId == TargetXdrTenant;
let HookFiles = union isfuzzy=true
  (datatable(FileTime:datetime, DeviceId:string, DeviceName:string, FolderPath:string, FileName:string, SHA256:string)[]),
  (DeviceFileEvents
   | where Timestamp between ((Start - 4h) .. End)
   | where ActionType in ("FileCreated", "FileModified", "FileRenamed")
   | where FileName endswith ".pth" or FileName in~ ("sitecustomize.py", "usercustomize.py")
   | project FileTime=Timestamp, DeviceId, DeviceName, FolderPath, FileName, SHA256);
let PyExec = union isfuzzy=true
  (datatable(PyTime:datetime, DeviceId:string, PyFile:string, ProcessCommandLine:string)[]),
  (DeviceProcessEvents
   | where Timestamp between (Start .. End)
   | where FileName in~ ("python", "python3", "python.exe", "python3.exe")
   | project PyTime=Timestamp, DeviceId, PyFile=FileName, ProcessCommandLine);
SafeCloudTrail
| where EventSource == "secretsmanager.amazonaws.com" and EventName == "GetSecretValue"
| where isempty(ErrorCode) and isempty(ErrorMessage)
| where UseAllAccounts or UserIdentityAccountId == AccountFilter or RecipientAccountId == AccountFilter
| project TimeGenerated, AwsEventId, AWSAccountId=UserIdentityAccountId, RecipientAccountId, AWSRegion,
    AwsAccessKeyId=UserIdentityAccessKeyId, AwsPrincipalArn=UserIdentityArn, SourceIpAddress
| join kind=inner ScopedAssets on AWSAccountId, AwsPrincipalArn, AwsAccessKeyId
| where TimeGenerated between (ValidFrom .. ValidTo)
| join kind=inner HookFiles on DeviceId
| where FileTime between ((TimeGenerated - 4h) .. TimeGenerated)
| join kind=inner PyExec on DeviceId
| where PyTime between (FileTime .. TimeGenerated)
| summarize HookFileTime=min(FileTime), HookFiles=make_set(FileName, 10), PythonTime=max(PyTime), take_any(DeviceName, AwsInstanceId)
    by TimeGenerated, AwsEventId, AWSAccountId, RecipientAccountId, AWSRegion, AwsPrincipalArn, AwsAccessKeyId, SourceIpAddress, DeviceId
| order by TimeGenerated desc
| take 5000

Explanation

This query is designed to analyze AWS CloudTrail logs to identify potential security risks related to the use of secrets in Python environments across AWS accounts. Here's a simplified breakdown of what the query does:

  1. Time Range and Account Filtering: It sets a time range and filters for specific AWS accounts based on provided parameters.

  2. Data Collection:

    • CloudTrail Logs: It gathers AWS CloudTrail logs related to the use of the AWS Secrets Manager, specifically focusing on the GetSecretValue event.
    • Identity and Asset Mapping: It retrieves identity and asset mappings from watchlists to verify and map AWS accounts, access keys, and devices.
    • File and Process Events: It collects file events related to Python startup files and process events where Python executables are run.
  3. Data Joining and Filtering:

    • It joins the CloudTrail logs with the asset and identity mappings to ensure that the events are associated with verified and mapped AWS accounts and devices.
    • It further joins with file and process events to identify when Python startup files were accessed or modified before the secrets were used.
  4. Result Summarization:

    • The query summarizes the results by listing the earliest time a Python startup file was accessed (HookFileTime) and the latest time a Python process was executed (PythonTime) for each secret access event.
    • It includes details such as the AWS account, region, principal ARN, access key ID, source IP address, and device information.
  5. Output:

    • The results are ordered by the time the secret was accessed and limited to the most recent 5000 entries.

In essence, this query helps detect potential security incidents where Python scripts might be accessing AWS secrets, possibly indicating unauthorized or suspicious activity.