> ## Documentation Index
> Fetch the complete documentation index at: https://cloudanix.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Audit Logging Enabled

### More Info:

Ensures that default audit logging is enabled on the project. The default audit logs should be configured to log all admin activities and write and read access to data for all services. In addition, no exempted members should be added to the logs to ensure proper delivery of all audit logs.

### Risk Level

High

### Address

Security

### Compliance Standards

### Triage and Remediation

<Tabs>
  <Tab title="Remediation">
    ### Remediation

    <AccordionGroup>
      <Accordion title="Using Console" defaultOpen="true">
        To remediate “Audit Logging not enabled” for GCP IAM using the GCP Console:

        1. **Go to the GCP Console**
           * Open: [https://console.cloud.google.com](https://console.cloud.google.com)
           * Make sure you’ve selected the correct **Project** (or **Folder/Organization**) at the top.

        2. **Open Audit Logs settings**
           * In the left-hand menu, go to:\
             **IAM & Admin → Audit Logs**

        3. **Select the resource scope**
           * At the top of the page, use the drop-down to choose the scope you want to configure:
             * **Organization** (preferred for centralized control), or
             * **Folder**, or
             * **Project**

        4. **Filter to IAM-related services**\
           In the service list, locate and configure at least:

           * `IAM Service`
           * `IAM Service Account`
           * `Cloud Resource Manager` (often also important for IAM-like changes, e.g., project bindings)

           You can use the filter box to search for “IAM”.

        5. **Enable the desired audit log types**\
           For each of the relevant services (e.g., IAM Service):
           * Click the service name (or checkbox, depending on UI version).
           * On the right (or in the panel that appears), enable the log types you need by checking:
             * **Admin Read** – controls/reads IAM policies, roles, etc.
             * **Data Read** – reads of data (less relevant specifically for IAM, but good to have if required by policy).
             * **Data Write** – changes to data/resources (e.g., policy updates, role bindings).
           * For strict security/compliance, enable **all three** for applicable principals:
             * You’ll see columns like **All users**, **Admin**, **Service accounts**, etc. Ensure these are checked according to your org’s policy (many orgs enable for **All principals**).

        6. **Save the configuration**
           * After selecting the log types, click **Save** at the bottom/right of the panel.

        7. **Verify logs are being written**
           * Go to **Logging → Logs Explorer**.
           * In the query builder, filter by:
             * `resource.type="project"` (or org/folder type as appropriate)
             * `logName:"cloudaudit.googleapis.com"`
           * Make a small IAM change (e.g., add/remove a test role) and confirm an **AuditLog** entry appears.

        Once these steps are complete, IAM audit logging is enabled and the “Audit Logging Enabled” misconfiguration for GCP IAM should be remediated for that scope.
      </Accordion>

      <Accordion title="Using CLI">
        In GCP, “Audit Logging enabled” for IAM usually means **Data Access audit logs** are turned on (Admin Activity logs are always on). You enable these by adding `auditConfigs` to the IAM policy using `gcloud`.

        Below is how to do it with GCP CLI at the **project** level (similar for folder/org).

        ***

        ### 1. Set environment variables

        ```bash theme={null}
        PROJECT_ID="my-project-id"
        gcloud config set project "$PROJECT_ID"
        ```

        ***

        ### 2. Export current IAM policy to a file

        ```bash theme={null}
        gcloud projects get-iam-policy "$PROJECT_ID" \
          --format=json > iam-policy.json
        ```

        ***

        ### 3. Edit the IAM policy to add auditConfigs

        Open `iam-policy.json` in an editor and add an `auditConfigs` block at the top level (sibling to `bindings`).\
        Example to enable all Data Access logs for all services and no exemptions:

        ```jsonc theme={null}
        {
          "bindings": [
            ...
          ],
          "auditConfigs": [
            {
              "service": "allServices",
              "auditLogConfigs": [
                {
                  "logType": "DATA_READ"
                },
                {
                  "logType": "DATA_WRITE"
                },
                {
                  "logType": "ADMIN_READ"
                }
              ]
            }
          ],
          "etag": "..."
        }
        ```

        Notes:

        * Keep the existing `etag` unchanged.
        * If `auditConfigs` already exists, merge your desired `auditLogConfigs` instead of overwriting unrelated entries.
        * You can also set for a specific service, e.g. `"service": "iam.googleapis.com"` instead of `"allServices"`.

        ***

        ### 4. Apply the updated IAM policy

        ```bash theme={null}
        gcloud projects set-iam-policy "$PROJECT_ID" iam-policy.json
        ```

        Confirm the updated policy:

        ```bash theme={null}
        gcloud projects get-iam-policy "$PROJECT_ID" --format=json | jq '.auditConfigs'
        ```

        ***

        ### 5. (Optional) Do the same at folder / org level

        For a folder:

        ```bash theme={null}
        FOLDER_ID="123456789012"
        gcloud resource-manager folders get-iam-policy "$FOLDER_ID" --format=json > folder-iam.json
        # edit folder-iam.json to add auditConfigs as above
        gcloud resource-manager folders set-iam-policy "$FOLDER_ID" folder-iam.json
        ```

        For an org:

        ```bash theme={null}
        ORG_ID="123456789012"
        gcloud organizations get-iam-policy "$ORG_ID" --format=json > org-iam.json
        # edit org-iam.json
        gcloud organizations set-iam-policy "$ORG_ID" org-iam.json
        ```

        This enables IAM Data Access audit logging via CLI in GCP.
      </Accordion>

      <Accordion title="Using Python">
        To remediate “Audit Logging not enabled” for GCP IAM using Python, you need to update the project’s IAM policy to include `auditConfigs` for the services you care about (e.g., `allServices`) and log types (ADMIN\_READ, DATA\_READ, DATA\_WRITE).

        Below is a minimal, step‑by‑step example using the `google-api-python-client` library.

        ***

        ### 1. Prerequisites

        1. Enable these APIs on the project:
           * IAM Service: `iam.googleapis.com`
           * Cloud Resource Manager API: `cloudresourcemanager.googleapis.com`
        2. Install libraries:
           ```bash theme={null}
           pip install google-api-python-client google-auth google-auth-httplib2 google-auth-oauthlib
           ```
        3. Authenticate with an identity that has `resourcemanager.projects.setIamPolicy` and `resourcemanager.projects.getIamPolicy` (e.g., Owner or Security Admin):
           ```bash theme={null}
           gcloud auth application-default login
           ```

        ***

        ### 2. Decide what to log

        Common secure baseline for all services:

        * `ADMIN_READ`
        * `DATA_READ`
        * `DATA_WRITE`

        Optionally include `exemptedMembers` if some principals must be excluded from logging.

        ***

        ### 3. Python: Enable Audit Logging on a Project

        ```python theme={null}
        from google.oauth2 import service_account
        from googleapiclient import discovery
        from googleapiclient.errors import HttpError
        import google.auth

        # -------------------------------------------------------------------
        # CONFIG
        # -------------------------------------------------------------------
        PROJECT_ID = "your-project-id"  # <-- change this
        ENABLE_ADMIN_READ = True
        ENABLE_DATA_READ = True
        ENABLE_DATA_WRITE = True

        # If using ADC (gcloud auth application-default login), just call default():
        credentials, _ = google.auth.default(scopes=["https://www.googleapis.com/auth/cloud-platform"])

        # Alternatively, use a service account key:
        # credentials = service_account.Credentials.from_service_account_file(
        #     "path/to/key.json",
        #     scopes=["https://www.googleapis.com/auth/cloud-platform"],
        # )

        service = discovery.build("cloudresourcemanager", "v1", credentials=credentials)


        def build_audit_config():
            log_types = []
            if ENABLE_ADMIN_READ:
                log_types.append("ADMIN_READ")
            if ENABLE_DATA_READ:
                log_types.append("DATA_READ")
            if ENABLE_DATA_WRITE:
                log_types.append("DATA_WRITE")

            if not log_types:
                return []

            # Example: apply to all services
            return [{
                "service": "allServices",
                "auditLogConfigs": [
                    {
                        "logType": log_type,
                        # Optional: exempt some members from logging
                        # "exemptedMembers": ["user:someone@example.com"]
                    }
                    for log_type in log_types
                ],
            }]


        def main():
            project_resource = f"projects/{PROJECT_ID}"

            try:
                # 1. Get current IAM policy
                policy = service.projects().getIamPolicy(
                    resource=project_resource,
                    body={"options": {"requestedPolicyVersion": 3}},
                ).execute()

                current_audit_configs = policy.get("auditConfigs", [])
                new_audit_config = build_audit_config()

                # Replace or merge auditConfigs. Here we simply replace configs for "allServices".
                # If you need to merge per service, add merging logic instead.
                # ---- Simple replace strategy ----
                other_configs = [ac for ac in current_audit_configs if ac.get("service") != "allServices"]
                policy["auditConfigs"] = other_configs + new_audit_config

                # 2. Set updated IAM policy
                set_req = service.projects().setIamPolicy(
                    resource=project_resource,
                    body={"policy": policy},
                )
                updated_policy = set_req.execute()

                print("Updated IAM policy auditConfigs:")
                print(updated_policy.get("auditConfigs", []))

            except HttpError as e:
                print(f"Error updating IAM policy: {e}")


        if __name__ == "__main__":
            main()
        ```

        ***

        ### 4. Verify in Console

        1. Go to: IAM & Admin → Audit Logs → Select project.
        2. Confirm that for “All services” (or specific services), the chosen log types (Admin, Data read/write) are enabled.
        3. Optionally check Cloud Logging → Logs Explorer for `cloudaudit.googleapis.com` logs.
      </Accordion>

      <Accordion title="Using Terraform">
        ```hcl theme={null}
        # Enable Cloud Audit Logs for all services and log types on a project.
        # Substitute YOUR_PROJECT_ID with your GCP project ID.
        resource "google_project_iam_audit_config" "all_services_audit_logging" {
          project = "YOUR_PROJECT_ID"

          service = "allServices"

          audit_log_config {
            log_type = "ADMIN_READ"
          }

          audit_log_config {
            log_type = "DATA_READ"
          }

          audit_log_config {
            log_type = "DATA_WRITE"
          }
        }
        ```

        Replace `YOUR_PROJECT_ID` with your actual project ID.\
        This updates the IAM audit logging configuration in place; it does not recreate the project or other resources.

        For verification, `terraform plan` should show an update to `google_project_iam_audit_config.all_services_audit_logging` adding the three `audit_log_config` blocks (ADMIN\_READ, DATA\_READ, DATA\_WRITE).
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>

### Additional Reading:

* [https://cloud.google.com/logging/docs/audit/](https://cloud.google.com/logging/docs/audit/)
