> ## 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.

# Cloud Monitoring Should Monitor IAM Key Authentication Events Count

### More Info:

Ensure Cloud Monitoring monitors IAM key authentication events count

### Risk Level

Medium

### Address

Security

### Compliance Standards

* Cloudanix Best Practice

### Triage and Remediation

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

    <AccordionGroup>
      <Accordion title="Using Console" defaultOpen="true">
        To remediate the misconfiguration of not monitoring IAM Key Authentication Events Count in GCP, you can follow the below steps using the GCP console:

        1. Open the GCP console and navigate to the Security Command Center.

        2. Click on the "Security Health Analytics" tab on the left-hand side of the screen.

        3. Under the "Security Health Analytics" tab, click on the "Security Health Analytics Findings" option.

        4. In the "Findings" section, search for the finding "IAM Key Authentication Events Count Not Monitored".

        5. Click on the finding to view the details.

        6. In the details section, click on the "Remediation Steps" tab.

        7. Follow the recommended remediation steps to enable monitoring of IAM Key Authentication Events Count.

        8. The recommended remediation steps include creating a new custom dashboard in the GCP console, adding a widget to the dashboard to monitor IAM Key Authentication Events Count, and configuring the widget to display the count of authentication events.

        9. Once the remediation steps are completed, the finding for "IAM Key Authentication Events Count Not Monitored" should be resolved in the Security Health Analytics section.

        By following these steps, you can remediate the misconfiguration of not monitoring IAM Key Authentication Events Count in GCP using the GCP console.

        #
      </Accordion>

      <Accordion title="Using CLI">
        To remediate the misconfiguration of not monitoring IAM key authentication events count in GCP using GCP CLI, follow these steps:

        1. Open the Google Cloud Console and select the project for which you want to remediate the misconfiguration.

        2. Open the Cloud Shell by clicking on the icon in the top right corner of the console.

        3. In the Cloud Shell, enter the following command to enable the Cloud Audit Logs API:

        ```
        gcloud services enable cloudaudit.googleapis.com
        ```

        4. Once the API is enabled, you can create a sink to export the audit logs to a destination of your choice. For example, to export the logs to Cloud Storage, use the following command:

        ```
        gcloud logging sinks create [SINK_NAME] storage.googleapis.com/[BUCKET_NAME] --log-filter='protoPayload.methodName="google.iam.credentials.v1.IAMCredentials.GenerateAccessToken"'
        ```

        Replace `[SINK_NAME]` with a name for the sink and `[BUCKET_NAME]` with the name of the Cloud Storage bucket you want to export the logs to.

        5. After creating the sink, grant the necessary permissions to the Cloud Storage bucket by running the following command:

        ```
        gsutil iam ch serviceAccount:[PROJECT_NUMBER]-compute@developer.gserviceaccount.com:objectCreator,objectViewer gs://[BUCKET_NAME]
        ```

        Replace `[PROJECT_NUMBER]` with the project number and `[BUCKET_NAME]` with the name of the Cloud Storage bucket.

        6. Finally, test the sink by generating an access token using an IAM key and checking if the event count is logged in the Cloud Audit Logs. You can do this by running the following command:

        ```
        gcloud iam service-accounts keys create [KEY_FILE_NAME].json --iam-account [IAM_ACCOUNT_EMAIL]
        ```

        Replace `[KEY_FILE_NAME]` with a name for the key file and `[IAM_ACCOUNT_EMAIL]` with the email address of the IAM key.

        7. After generating the access token, check the Cloud Audit Logs to confirm that the event count has been logged. You can do this by navigating to the Cloud Logging section of the Google Cloud Console and selecting the sink you created in step 4.

        By following these steps, you can remediate the misconfiguration of not monitoring IAM key authentication events count in GCP using GCP CLI.
      </Accordion>

      <Accordion title="Using Python">
        To remediate the misconfiguration in GCP where cloud monitoring should monitor IAM key authentication events count using Python, follow the below steps:

        1. First, you need to enable the required APIs for the project. You can do this by navigating to the APIs & Services section in the GCP console and searching for the required APIs, which in this case are the Cloud Monitoring API and the Cloud IAM API.

        2. Next, you need to create a service account with the required permissions to access the Cloud Monitoring API and the Cloud IAM API. You can do this by navigating to the Service Accounts section in the GCP console and creating a new service account with the required permissions.

        3. Once the service account is created, you need to download the service account key in JSON format. This key will be used to authenticate the Python script to access the Cloud Monitoring API and the Cloud IAM API.

        4. Now, you can use the Python client libraries for the Cloud Monitoring API and the Cloud IAM API to write a script that will retrieve the IAM key authentication events count.

        5. Here is a sample Python script that retrieves the IAM key authentication events count:

        ```python theme={null}
        from google.oauth2 import service_account
        from googleapiclient.discovery import build

        # Replace with the path to your service account key file
        KEY_FILE_LOCATION = '/path/to/key.json'

        # Replace with your project ID
        PROJECT_ID = 'your-project-id'

        # Replace with the name of the metric you want to retrieve
        METRIC_NAME = 'iam.googleapis.com/iam/authorized_keys_count'

        # Replace with the time interval you want to retrieve data for
        TIME_INTERVAL = '1h'

        # Authenticate with the service account key file
        credentials = service_account.Credentials.from_service_account_file(
            KEY_FILE_LOCATION)

        # Build the Cloud Monitoring API client
        monitoring_client = build('monitoring', 'v3', credentials=credentials)

        # Build the Cloud IAM API client
        iam_client = build('iam', 'v1', credentials=credentials)

        # Retrieve the list of service accounts in the project
        service_accounts = iam_client.projects().serviceAccounts().list(
            name='projects/{}'.format(PROJECT_ID)).execute().get('accounts')

        # Loop through each service account and retrieve the IAM key authentication events count
        for service_account in service_accounts:
            resource = 'projects/{}/serviceAccounts/{}'.format(
                PROJECT_ID, service_account['email'])
            response = monitoring_client.projects().timeSeries().list(
                name='projects/{}'.format(PROJECT_ID),
                filter='metric.type="{}" resource.type="service_account" resource.labels.email="{}"'.format(
                    METRIC_NAME, service_account['email']),
                interval_startTime='{}s'.format(int((time.time() - 3600) * 1000000000)),
                interval_endTime='{}s'.format(int(time.time() * 1000000000)),
                aggregation_alignmentPeriod=TIME_INTERVAL,
                aggregation_perSeriesAligner='ALIGN_SUM'
            ).execute()

            # Print the IAM key authentication events count for the service account
            print('Service Account: {}'.format(resource))
            if 'timeSeries' in response:
                for time_series in response['timeSeries']:
                    print('  Metric: {}'.format(time_series['metric']['type']))
                    for point in time_series['points']:
                        print('    Value: {}'.format(point['value']['int64Value']))
            else:
                print('  No data available')
        ```

        6. Replace the `KEY_FILE_LOCATION`, `PROJECT_ID`, `METRIC_NAME`, and `TIME_INTERVAL` variables with the appropriate values for your environment.

        7. Run the Python script to retrieve the IAM key authentication events count for your GCP project.

        By following these steps, you can remediate the misconfiguration in GCP where cloud monitoring should monitor IAM key authentication events count using Python.
      </Accordion>

      <Accordion title="Using Terraform">
        ```hcl theme={null}
        resource "google_monitoring_alert_policy" "iam_key_authn_events_count" {
          project      = "PROJECT_ID"                        # replace with your GCP project ID
          display_name = "IAM Key Authentication Events Count Alert"
          combiner     = "OR"

          conditions {
            display_name = "IAM key authentication events count exceeds threshold"

            condition_threshold {
              # Monitors IAM key authentication events count metric
              # Docs: https://cloud.google.com/monitoring/api/metrics_gcp#iam_keys
              filter = "metric.type=\"iam.googleapis.com/keys/authn_events_count\" resource.type=\"service_account\""

              # Adjust aggregation and threshold to your policy
              aggregations {
                alignment_period   = "300s"
                per_series_aligner = "ALIGN_RATE"
                cross_series_reducer = "REDUCE_SUM"
                group_by_fields      = []
              }

              comparison      = "COMPARISON_GT"
              threshold_value = THRESHOLD_VALUE              # replace with numeric threshold, e.g. 0 or 10
              duration        = "0s"                         # require breach on a single evaluation

              trigger {
                count = 1
              }
            }
          }

          notification_channels = [
            "NOTIFICATION_CHANNEL_RESOURCE_NAME_1",          # e.g. projects/PROJECT_ID/notificationChannels/CHANNEL_ID
            # "NOTIFICATION_CHANNEL_RESOURCE_NAME_2",
          ]

          documentation {
            content  = "IAM key authentication events count has exceeded the configured threshold."
            mime_type = "text/markdown"
          }

          user_labels = {
            environment = "ENVIRONMENT"                      # e.g. prod, staging
          }
        }
        ```

        This change does not replace existing monitored resources; it only adds a new alerting policy in Cloud Monitoring.

        To verify, `terraform plan` should show creation of one new `google_monitoring_alert_policy.iam_key_authn_events_count` resource with the metric filter `iam.googleapis.com/keys/authn_events_count`.
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>

### Additional Reading:

* [https://cloud.google.com/monitoring/api/metrics\_gcp](https://cloud.google.com/monitoring/api/metrics_gcp)
