TExcelTAD
Home › Cloud & Container Security › Cloud Audit Logs: CloudTrail, Azure Activity Log and GCP Audit Logs

Cloud Audit Logs: CloudTrail, Azure Activity Log and GCP Audit Logs

In a cloud account almost everything an attacker does is an API call, and the control plane writes most API calls to an audit log: who called, from where, with which credentials, what they asked for, and whether it worked. That makes the audit log the single most valuable data source for cloud detection and investigation, and it makes the log itself a target: an attacker who can stop or delete it works in the dark. This lesson reads one event from each major cloud field by field, normalises them into one schema, and then shows how log integrity is protected and how tampering is detected. CloudTrail and AWS Config covered setting the trail up; Log Sources puts cloud logs among the others.

What each cloud records

AWS CloudTrail Azure Activity Log (+ Entra ID logs) Google Cloud Audit Logs
Control-plane changes management events, on by default (90-day event history; a trail is needed to keep them) Activity Log, subscription level, 90 days unless exported with a diagnostic setting Admin Activity, always on, can't be disabled
Data reads and writes data events (S3 objects, DynamoDB items, Lambda invokes…), off by default, per resource resource logs (diagnostic settings per resource) Data Access logs, off by default (except BigQuery)
Sign-ins ConsoleLogin events Entra ID sign-in logs Cloud Identity / Workspace logs
Denied by policy errorCode on the event status: Failed Policy Denied logs
Who userIdentity (type, ARN, access key, session issuer) caller, claims authenticationInfo.principalEmail
What eventSource + eventName operationName serviceName + methodName

Two consequences for an auditor: data access is invisible unless someone turned it on, and retention is short unless someone exported it. Both are findings in most first reviews.

Three events, one schema

The program parses one synthetic event from each cloud (field names as the providers document them, values invented) and maps them to a common shape, which is what a SIEM's normalisation does (Normalisation and Schemas).

python · try it yourself
import json

aws = json.loads("""{
 "eventVersion": "1.10", "eventTime": "2026-04-14T08:31:12Z", "eventSource": "iam.amazonaws.com",
 "eventName": "AttachRolePolicy", "awsRegion": "us-east-1", "sourceIPAddress": "198.51.100.23",
 "userAgent": "aws-cli/2.x", "readOnly": false, "eventType": "AwsApiCall", "recipientAccountId": "123456789012",
 "userIdentity": {"type": "AssumedRole", "arn": "arn:aws:sts::123456789012:assumed-role/ci-deploy/gh-run-4411",
   "accessKeyId": "ASIA2LABEXAMPLE00001", "sessionContext": {"sessionIssuer": {"arn": "arn:aws:iam::123456789012:role/ci-deploy"},
   "attributes": {"mfaAuthenticated": "false"}}},
 "requestParameters": {"roleName": "app-role", "policyArn": "arn:aws:iam::aws:policy/AdministratorAccess"},
 "responseElements": null}""")
azure = json.loads("""{
 "time": "2026-04-14T08:35:40Z", "operationName": {"value": "Microsoft.Authorization/roleAssignments/write"},
 "category": {"value": "Administrative"}, "status": {"value": "Succeeded"}, "caller": "bob@lab.test",
 "callerIpAddress": "203.0.113.66", "correlationId": "4b1c...",
 "resourceId": "/subscriptions/00000000-0000-0000-0000-000000000001/providers/Microsoft.Authorization/roleAssignments/9f2e",
 "properties": {"requestbody": "{\\"properties\\":{\\"roleDefinitionId\\":\\".../8e3af657-a8ff-443c-a75c-2fe8c4bcb635\\",\\"principalId\\":\\"a1b2\\"}}"}}""")
gcp = json.loads("""{
 "logName": "projects/lab-prod/logs/cloudaudit.googleapis.com%2Factivity", "timestamp": "2026-04-14T08:40:02Z",
 "protoPayload": {"@type": "type.googleapis.com/google.cloud.audit.AuditLog", "serviceName": "iam.googleapis.com",
   "methodName": "google.iam.admin.v1.CreateServiceAccountKey", "authenticationInfo": {"principalEmail": "ci@lab-prod.iam.gserviceaccount.com"},
   "requestMetadata": {"callerIp": "192.0.2.44"}, "resourceName": "projects/-/serviceAccounts/backup@lab-prod.iam.gserviceaccount.com",
   "status": {}},
 "severity": "NOTICE"}""")

def from_aws(e):
    ui = e["userIdentity"]
    actor = ui.get("sessionContext", {}).get("sessionIssuer", {}).get("arn", ui.get("arn"))
    return dict(time=e["eventTime"], cloud="aws", actor=actor, ip=e["sourceIPAddress"],
                action=f"{e['eventSource'].split('.')[0]}:{e['eventName']}",
                target=json.dumps(e.get("requestParameters"), separators=(",", ":")),
                outcome=e.get("errorCode", "success"))

def from_azure(e):
    return dict(time=e["time"], cloud="azure", actor=e["caller"], ip=e["callerIpAddress"],
                action=e["operationName"]["value"], target=e["resourceId"].split("/providers/")[1],
                outcome=e["status"]["value"].lower().replace("succeeded", "success"))

def from_gcp(e):
    p = e["protoPayload"]
    return dict(time=e["timestamp"], cloud="gcp", actor=p["authenticationInfo"]["principalEmail"],
                ip=p["requestMetadata"]["callerIp"], action=f"{p['serviceName']}:{p['methodName'].split('.')[-1]}",
                target=p["resourceName"], outcome="success" if not p["status"] else f"error {p['status'].get('code')}")

for row in [from_aws(aws), from_azure(azure), from_gcp(gcp)]:
    print(f"{row['time']} {row['cloud']:5} {row['action']}")
    print(f"{'':20} by {row['actor']} from {row['ip']} -> {row['outcome']}")
    print(f"{'':20} on {row['target']}")
2026-04-14T08:31:12Z aws   iam:AttachRolePolicy
                     by arn:aws:iam::123456789012:role/ci-deploy from 198.51.100.23 -> success
                     on {"roleName":"app-role","policyArn":"arn:aws:iam::aws:policy/AdministratorAccess"}
2026-04-14T08:35:40Z azure Microsoft.Authorization/roleAssignments/write
                     by bob@lab.test from 203.0.113.66 -> success
                     on Microsoft.Authorization/roleAssignments/9f2e
2026-04-14T08:40:02Z gcp   iam.googleapis.com:CreateServiceAccountKey
                     by ci@lab-prod.iam.gserviceaccount.com from 192.0.2.44 -> success
                     on projects/-/serviceAccounts/backup@lab-prod.iam.gserviceaccount.com

All three are the same story in three dialects: a privilege change. In AWS the CI role attached AdministratorAccess to the application role (note how the actor is resolved from the session issuer, the role behind the temporary key, not the session name); in Azure a user created a role assignment whose role definition GUID is the built-in Owner role; in GCP a CI service account created a key for the backup service account. The next lesson turns such patterns into detections.

Protecting the log itself

Attackers who reach administrative rights often try to blind the defenders. The events to watch:

Cloud Tampering events
AWS StopLogging, DeleteTrail, UpdateTrail (e.g. moving it to another bucket), PutEventSelectors (removing data events), changes to the log bucket's policy or lifecycle, DeleteBucket on it
Azure microsoft.insights/diagnosticSettings/delete or write, deleting the Log Analytics workspace
GCP google.logging.v2.ConfigServiceV2.DeleteSink / UpdateSink, changes to Data Access audit config in SetIamPolicy (auditConfigs)

Prevention is structural: an organisation trail (or organisation-level export) that member accounts can't modify, logs delivered to a separate log-archive account with object lock or retention locks, SCPs denying the tampering actions, and alerts on every attempt (the attempt itself is logged even when an SCP denies it).

CloudTrail also offers log file integrity validation: every hour it writes a digest file listing the SHA-256 hash of every log file delivered in that hour, signs the digest with a private key that AWS holds, and includes the previous digest's signature, so the digests form a chain. Anyone with the public key can later prove that no log file was changed or deleted. The model below builds such a chain with Ed25519 (AWS uses RSA with SHA-256; the structure is the point) and then lets an attacker edit one log file and delete another.

python · try it yourself
import hashlib, json
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
from cryptography.exceptions import InvalidSignature

signing_key = Ed25519PrivateKey.from_private_bytes(hashlib.sha256(b"lab-only digest key").digest())  # fixed for the demo
public_key = signing_key.public_key()

bucket = {f"logs/2026-04-14T{h:02d}-part{i}.json": f'{{"hour": {h}, "part": {i}, "events": [...]}}'.encode()
          for h in (8, 9, 10) for i in (1, 2)}
digests, prev_sig = [], ""
for h in (8, 9, 10):
    files = {k: hashlib.sha256(v).hexdigest() for k, v in bucket.items() if f"T{h:02d}-" in k}
    body = json.dumps({"hour": h, "logFiles": files, "previousDigestSignature": prev_sig}, sort_keys=True).encode()
    sig = signing_key.sign(body).hex()
    digests.append((body, sig))
    prev_sig = sig

# the attacker edits one file and deletes another (they can't re-sign the digests)
bucket["logs/2026-04-14T09-part1.json"] = b'{"hour": 9, "part": 1, "events": []}'
del bucket["logs/2026-04-14T10-part2.json"]

def validate():
    prev = ""
    for body, sig in digests:
        d = json.loads(body)
        try:
            public_key.verify(bytes.fromhex(sig), body)
        except InvalidSignature:
            print(f"hour {d['hour']}: digest signature INVALID"); continue
        chain = "chain ok" if d["previousDigestSignature"] == prev else "CHAIN BROKEN"
        prev = sig
        for name, h in d["logFiles"].items():
            if name not in bucket:
                status = "MISSING"
            elif hashlib.sha256(bucket[name]).hexdigest() != h:
                status = "MODIFIED"
            else:
                status = "valid"
            print(f"hour {d['hour']:2} {chain:9} {name:34} {status}")
validate()
hour  8 chain ok  logs/2026-04-14T08-part1.json      valid
hour  8 chain ok  logs/2026-04-14T08-part2.json      valid
hour  9 chain ok  logs/2026-04-14T09-part1.json      MODIFIED
hour  9 chain ok  logs/2026-04-14T09-part2.json      valid
hour 10 chain ok  logs/2026-04-14T10-part1.json      valid
hour 10 chain ok  logs/2026-04-14T10-part2.json      MISSING

Editing a log file changes its hash, deleting it leaves a name in a signed digest without a file, and the attacker can't produce new valid digests without the signing key, which never leaves the provider. Deleting a whole digest would break the chain of the next one. On AWS the check is one command, aws cloudtrail validate-logs --trail-arn … --start-time ….

How gaps in audit logging are detected

  • Configuration review: is there an organisation trail (or org-level diagnostic setting / aggregated sink) covering all regions and accounts? Are data events on for sensitive buckets and tables? Is integrity validation on? Where do logs go, who can delete them, how long are they kept?
  • Health signals: a log source that goes quiet is an alert in itself; compare expected event volume per account and hour.
  • Tampering events above, from any principal other than the logging pipeline.

How it is fixed

  1. Create organisation-wide logging (organisation trail, management-group diagnostic settings, organisation sinks) into a dedicated log-archive account or project.
  2. Turn on data events for sensitive data stores, accepting the cost for those, not for everything.
  3. Lock the archive (S3 Object Lock in compliance mode, immutable blob storage, bucket retention policies) and deny tampering actions with SCPs or organisation policies.
  4. Keep logs as long as investigations need: incidents are often found months later; one year online and longer in archive is a common baseline.

Pitfalls

  • Relying on the 90-day console history: it isn't a trail, it can't be queried at scale and it doesn't include data events.
  • One trail per account that the account's admins can stop: the attacker with admin rights is exactly who you need to log.
  • Forgetting regions: an attacker who works in a region nobody logs is invisible (organisation trails cover all regions by default).

Practice

1. In the AWS event, why is the actor reported as role/ci-deploy and not the session ARN?

The session ARN (assumed-role/ci-deploy/gh-run-4411) changes with every session; the session issuer is the stable identity, which is what detections and baselines should key on. Keep the session name too: it links to the CI run.

2. In the integrity model, change nothing in the bucket but replace the second digest's previousDigestSignature with "". What does validation say?

The digest's own signature becomes invalid (its body changed and the attacker can't re-sign), so the report shows hour 9: digest signature INVALID, and the hour-10 rows say CHAIN BROKEN because the validator never accepted digest 9. Even an attacker who could re-sign digest 9 would break the chain: the third digest names the old signature.

3. List three things a first audit of an account's logging should check.

An organisation-wide, all-region trail (or equivalent) delivering to a separate locked archive; data events for the sensitive data stores; alerts on tampering events and on sources going quiet. Retention and integrity validation are close fourth and fifth.

Test yourself

Which kind of AWS activity is NOT logged by CloudTrail unless enabled?

  1. IAM policy changes
  2. S3 object reads and writes (data events)
  3. Console sign-ins
  4. EC2 instance launches

What makes CloudTrail digest files tamper-evident?

  1. They are encrypted
  2. They hold SHA-256 hashes of each log file, are signed by AWS and chained through the previous digest's signature
  3. They are stored twice
  4. They are compressed

Which GCP audit log type is always on and can't be disabled?

  1. Data Access
  2. Admin Activity
  3. Policy Denied
  4. VPC flow logs

Why should audit logs go to a separate log-archive account?

  1. It is cheaper
  2. So administrators of the monitored account, and attackers who become them, can't delete or alter the logs
  3. To make queries faster
  4. Providers require it