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

# Google.login.loginservice.loginfailure

### Event Information

* **What it is**: `google.login.LoginService.LoginFailure` is a Cloud Logging audit/security event indicating a *failed* authentication attempt to a Google account identity (often via the Google login endpoint). In a GCP/org context, it usually precedes/blocks GCPIAM access because the principal never successfully authenticated.

* **Typical causes / fields to check**:
  * Wrong password, 2‑Step Verification failure, disabled/suspended account, blocked by context‑aware access, device/trust policy, or risk‑based login protection.
  * Review `authenticationInfo.principalEmail`, `metadata.reason` / `error`, source IP / geolocation, user agent, and `resource.labels.project_id` to distinguish normal user error from suspicious activity.

* **Practical handling & compliance**:
  * Monitor and alert on spikes or patterns (multiple failures for one account, single IP hitting many accounts, geo‑impossible logins) as indicators of brute‑force or credential‑stuffing; feed into SIEM (e.g., Chronicle, Splunk).
  * Use findings to enforce controls required by standards like ISO 27001, SOC 2, PCI DSS, HIPAA: enable strong MFA, context‑aware access, account lockout/throttling policies, and document incident response steps for repeated `LoginFailure` events.

### Examples

* **Brute-force or credential-stuffing attempts on privileged accounts**
  * Multiple `google.login.LoginService.LoginFailure` events from a small set of user accounts or service accounts, especially with admin/owner/organization-level roles, from the same or rotating IPs.
  * Risk: Possible account takeover attempt violating CIS GCP 1.x and NIST AC-7 (failed login monitoring). Mitigation: Implement IP-based throttling, enforce reCAPTCHA/2FA, and alert on high failure rates.

* **Suspicious geo-velocity / impossible travel with failed logins**
  * `LoginFailure` events for the same principal from distant geographic regions or TOR/VPN exit nodes shortly before/after successful logins from another region.
  * Risk: Indicator of credential compromise impacting SOC 2 CC6, ISO 27001 A.8/A.12. Mitigation: Enforce Context-Aware Access, require strong MFA, and block high-risk locations or anonymizing networks.

* **Service account abuse and lateral movement attempts**
  * Repeated `LoginFailure` events tied to service accounts or workload identities that should only be used by specific workloads, especially if originating from unusual projects, networks, or identities.
  * Risk: Potential lateral movement or privilege escalation violating PCI DSS 8.x and NIST AC-6. Mitigation: Restrict service account key usage, rotate keys, tighten IAM bindings, and create alerts on anomalous login sources for service accounts.

### Remediation

#### Using Console

* **Harden authentication, context, and throttling (covers CIS 1.x, NIST AC-7, SOC2, ISO 27001, PCI DSS 8.x)**
  * In GCP Console → **IAM & Admin → Security → Authentication** (or **Security → Identity-Aware Proxy / Context-Aware Access** depending on your setup):
    * Enforce **MFA** for admins/privileged users via your IdP or **Google Workspace → Security → 2-step verification → Enforcement**; require strong factors (FIDO2/security keys).
    * Enable **Context-Aware Access** (CAA): Admin Console → **Security → Context-Aware Access**; create access levels to block/step-up auth for:
      * High-risk geos or TOR/VPN ASNs.
      * Non-corporate IPs or untrusted device posture.
    * At your IdP or network edge (e.g., Cloud Armor): configure **rate limiting / IP throttling** for Google sign-in endpoints and administrative apps; add **reCAPTCHA** to any custom-facing login frontends.
  * GCP Console → **Security → Security Command Center → Settings**:
    * Ensure **SCC Standard/Premium** enabled; turn on **Event Threat Detection** to detect brute force and anomalous logins.

* **Strengthen IAM & service account controls to prevent lateral movement (covers NIST AC-6, PCI DSS 8.x)**
  * GCP Console → **IAM & Admin → IAM**:
    * Filter by **Role** for `Owner`, `Editor`, `Organization Admin`, `Project IAM Admin`, `Service Account User/Token Creator`; remove or narrow bindings to **principle of least privilege**.
    * For any suspicious principals generating `LoginFailure` events, temporarily **disable account** (if user) or **remove high-privilege roles** until investigation completes.
  * GCP Console → **IAM & Admin → Service Accounts**:
    * For each high-value service account:
      * **Disable key creation** (Service account → **Keys → Disable** / don’t create new keys); delete unused keys and rotate active ones.
      * Under **Permissions**, remove broad roles (`roles/editor`, `roles/owner`, cross-project SA bindings) and replace with minimal, workload-specific roles.
      * Confirm usage: only from expected projects/networks (e.g., GCE, GKE); if `LoginFailure` events come from other sources, **revoke keys**, rotate credentials, and re-deploy workloads with new bindings.

* **Detect, alert, and investigate login anomalies (NIST AC-7, continuous monitoring controls)**
  * GCP Console → **Logging → Logs Explorer**:
    * Query:
      ```text theme={null}
      resource.type="audited_resource"
      logName:"cloudaudit.googleapis.com"
      protoPayload.methodName="google.login.LoginService.LoginFailure"
      ```
      Add filters for `authenticationInfo.principalEmail` and IP/geolocation fields to identify:
      * High failed-login counts from same/rotating IPs.
      * Same principal from distant regions in short time (impossible travel).
      * Service accounts failing logins from unexpected projects/networks.
  * GCP Console → **Monitoring → Alerting → Create Policy**:
    * Use **Logs-based metrics** on `LoginFailure` counts per principal/IP; create alerts when:
      * Failures exceed a threshold in N minutes (per user/IP).
      * Service accounts generate any interactive/abnormal login failures.
    * Route alerts to **email / PagerDuty / SIEM**; run playbooks: lock/disable suspicious accounts, force **password reset**, terminate active sessions, and document actions for SOC 2 / ISO 27001 evidence.

#### Using CLI

* **Detect and alert on brute-force / credential stuffing (CIS GCP 1.x, NIST AC-7)**
  * Create a log-based metric on `LoginFailure` with filters such as:
    ```bash theme={null}
    gcloud logging metrics create login-failures-metric \
      --description="Failed logins for privileged accounts" \
      --log-filter='resource.type="audited_resource"
      protoPayload.methodName="google.login.LoginService.LoginFailure"
      protoPayload.authenticationInfo.principalEmail:("admin@" OR "owner@" OR "org-admin@")'
    ```
  * Set an alert for high failure counts (e.g., >5 in 5 minutes) and notify your SOC:
    ```bash theme={null}
    gcloud alpha monitoring policies create \
      --policy-from-file=login_failure_alert.json
    ```
    Example `login_failure_alert.json` snippet metric reference:
    ```json theme={null}
    {
      "displayName": "Privileged account failed login spike",
      "conditions": [{
        "conditionThreshold": {
          "filter": "metric.type=\"logging.googleapis.com/user/login-failures-metric\"",
          "comparison": "COMPARISON_GT",
          "thresholdValue": 5,
          "duration": "300s",
          "trigger": {"count": 1}
        }
      }],
      "notificationChannels": ["projects/PROJECT_ID/notificationChannels/CHANNEL_ID"]
    }
    ```
  * Reduce attack surface: enforce MFA and reCAPTCHA; for users, require security keys:
    ```bash theme={null}
    gcloud identity settings two-factor update --state=ON
    ```
    For IP throttling / blocking, use Cloud Armor on external apps:
    ```bash theme={null}
    gcloud compute security-policies rules create 1000 \
      --security-policy=web-login-policy \
      --expression="origin.ip in [\"1.2.3.4\", \"5.6.7.0/24\"]" \
      --action=throttle \
      --rate-limit-threshold-count=10 \
      --rate-limit-threshold-interval-sec=60
    ```

* **Mitigate impossible travel / suspicious geo-velocity (SOC 2 CC6, ISO 27001 A.8/A.12)**
  * Use Context-Aware Access to enforce device/location conditions on high-privilege apps:
    ```bash theme={null}
    gcloud access-context-manager perimeters create secure-admin-perimeter \
      --title="Secure Admin Perimeter" \
      --perimeter-type=PERIMETER_TYPE_REGULAR \
      --resources="projects/PROJECT_NUMBER" \
      --restricted-services="iam.googleapis.com"
    ```
  * Restrict access to trusted countries and block TOR/VPN ranges via Cloud Armor for external apps:
    ```bash theme={null}
    gcloud compute security-policies rules create 900 \
      --security-policy=web-login-policy \
      --expression="inIpRange(origin.ip, 'TOR_EXIT_NODE_RANGE')" \
      --action=deny-403
    ```
  * Enforce MFA for all admins and set stronger session controls in Google Workspace / Cloud Identity (mapped to GCP org):
    ```bash theme={null}
    gcloud organizations get-iam-policy ORG_ID > org-policy.yaml
    # Manually add constraints for strong authentication, then:
    gcloud organizations set-iam-policy ORG_ID org-policy.yaml
    ```

* **Constrain service account usage & detect abuse (PCI DSS 8.x, NIST AC-6)**
  * Disable and rotate exposed keys; restrict key creation:
    ```bash theme={null}
    # List keys
    gcloud iam service-accounts keys list \
      --iam-account=SA_NAME@PROJECT_ID.iam.gserviceaccount.com

    # Delete suspicious keys
    gcloud iam service-accounts keys delete KEY_ID \
      --iam-account=SA_NAME@PROJECT_ID.iam.gserviceaccount.com

    # Org policy: disable SA key creation where possible
    gcloud org-policies set-policy org-policy-no-sa-keys.yaml
    ```
    Example `org-policy-no-sa-keys.yaml` snippet:
    ```yaml theme={null}
    policy:
      name: "organizations/ORG_ID/policies/constraints/iam.disableServiceAccountKeyCreation"
      spec:
        rules:
        - enforce: true
    ```
  * Tighten IAM bindings so SAs are only used by intended workloads:
    ```bash theme={null}
    # Remove broad roles and replace with least-privilege
    gcloud projects remove-iam-policy-binding PROJECT_ID \
      --member="serviceAccount:SA_NAME@PROJECT_ID.iam.gserviceaccount.com" \
      --role="roles/editor"

    gcloud projects add-iam-policy-binding PROJECT_ID \
      --member="serviceAccount:SA_NAME@PROJECT_ID.iam.gserviceaccount.com" \
      --role="roles/storage.objectViewer"
    ```
  * Detect anomalous SA login sources with log-based metrics and alerts:
    ```bash theme={null}
    gcloud logging metrics create sa-login-failures-metric \
      --description="Service account login failures from unusual sources" \
      --log-filter='resource.type="audited_resource"
      protoPayload.authenticationInfo.principalEmail:@gserviceaccount.com
      protoPayload.methodName="google.login.LoginService.LoginFailure"'
    ```
    Then create a Monitoring policy (similar to above) to alert on spikes or from unexpected projects/VPCs, and feed these into your SIEM for correlation with lateral movement patterns.

#### Using Python

* **Detection & alerting for brute-force / geo-velocity / service account abuse (Cloud Logging + Cloud Monitoring)**
  * Enable Admin Activity / Access Transparency logs and aggregate `google.login.LoginService.LoginFailure` and `google.login.LoginService.LoginSuccess` into a log-based metric for failures per principal and per IP:
    ```python theme={null}
    from google.cloud import logging_v2, monitoring_v3

    project_id = "YOUR_PROJECT_ID"

    def create_log_metric_failed_logins():
        client = logging_v2.MetricsServiceV2Client()
        parent = f"projects/{project_id}"
        metric = logging_v2.LogMetric(
            name="failed_logins_by_principal",
            description="Count LoginFailure events grouped by principal and IP",
            filter=(
                'resource.type="audited_resource" '
                'AND protoPayload.@type="type.googleapis.com/google.cloud.audit.AuditLog" '
                'AND protoPayload.methodName="google.login.LoginService.LoginFailure"'
            ),
            metric_descriptor=logging_v2.MetricDescriptor(
                metric_kind=logging_v2.MetricDescriptor.MetricKind.DELTA,
                value_type=logging_v2.MetricDescriptor.ValueType.INT64,
                labels=[
                    logging_v2.LabelDescriptor(
                        key="principalEmail", value_type="STRING",
                        description="Principal email from authenticationInfo"
                    ),
                    logging_v2.LabelDescriptor(
                        key="ip", value_type="STRING",
                        description="Caller IP from requestMetadata"
                    ),
                ],
            )
        )
        client.create_log_metric(parent=parent, metric=metric)

    def create_alert_policy_high_failures(threshold=20, window_minutes=5):
        client = monitoring_v3.AlertPolicyServiceClient()
        project_name = f"projects/{project_id}"

        alert_policy = monitoring_v3.AlertPolicy(
            display_name="High failed login rate - potential brute force",
            combiner=monitoring_v3.AlertPolicy.ConditionCombinerType.AND,
            conditions=[
                monitoring_v3.AlertPolicy.Condition(
                    display_name="Failed logins per principal/IP",
                    condition_threshold=monitoring_v3.AlertPolicy.Condition.MetricThreshold(
                        filter=(
                            'metric.type="logging.googleapis.com/user/failed_logins_by_principal"'
                        ),
                        comparison=monitoring_v3.ComparisonType.COMPARISON_GT,
                        threshold_value=threshold,
                        duration={"seconds": window_minutes * 60},
                        aggregations=[
                            monitoring_v3.Aggregation(
                                alignment_period={"seconds": window_minutes * 60},
                                per_series_aligner=(
                                    monitoring_v3.Aggregation.Aligner.ALIGN_DELTA
                                ),
                                cross_series_reducer=(
                                    monitoring_v3.Aggregation.Reducer.REDUCE_SUM
                                ),
                                group_by_fields=["metric.label.principalEmail", "metric.label.ip"],
                            )
                        ],
                    ),
                )
            ],
            notification_channels=[  # pre-create channels
                "projects/YOUR_PROJECT_ID/notificationChannels/YOUR_CHANNEL_ID"
            ],
            user_labels={"control": "nist_ac7_cis_gcp_1x"}
        )
        client.create_alert_policy(name=project_name, alert_policy=alert_policy)

    if __name__ == "__main__":
        create_log_metric_failed_logins()
        create_alert_policy_high_failures()
    ```
  * For geo-velocity: add a second metric that extracts `requestMetadata.callerIp` and enrich via SIEM or custom pipeline (Cloud Functions/Cloud Run) with GeoIP, then alert when same `principalEmail` has failures from distant countries within short intervals; treat TOR/VPN ASN lists as high-risk and feed into block lists / custom alerts.

* **Policy controls: Context-Aware Access, MFA, IP/location restrictions (compliance: SOC 2, ISO 27001, NIST AC-7/AC-6)**
  * Enforce strong MFA and risk-based access for privileged accounts by assigning them to an access level that requires MFA and trusted device / network:
    * In Cloud Console or via Access Context Manager API, create access levels that restrict to corporate IP ranges / device attributes and attach them to IAM Conditions on admin roles (`roles/owner`, `roles/editor`, org-admin roles), satisfying NIST AC‑6 and SOC 2 CC6.
  * Use an Org Policy plus IAM Conditions to deny high-privilege logins from risky countries or anonymizers (integrate external IP reputation feeds into Conditions via `request.time`, `request.attributes.origin.ip`) and ensure shared service accounts used by workloads cannot be used from user IP ranges (only specific subnet tags / VPC connector), supporting PCI DSS 8.x.
  * Where feasible, enforce reCAPTCHA or per-app throttling in front-end apps that rely on Google Identity (to reduce credential stuffing) and configure Login Challenges in Google Workspace / Cloud Identity (MFA, device trust) for all admin groups.

* **Service account hardening & anomaly detection (PCI DSS 8.x, NIST AC-6)**
  * Programmatically audit and restrict service account key usage, rotate keys, and detect anomalous login sources:
    ```python theme={null}
    from google.cloud import iam_credentials_v1, logging_v2

    project_id = "YOUR_PROJECT_ID"

    def list_service_accounts():
        from google.cloud import iam_v1
        client = iam_v1.IAMClient()
        parent = f"projects/{project_id}"
        return list(client.list_service_accounts(name=parent))

    def rotate_keys_for_service_account(sa_email):
        from google.cloud import iam_v1
        client = iam_v1.IAMClient()
        name = f"projects/{project_id}/serviceAccounts/{sa_email}"

        # 1) List and delete existing keys (be careful in production!)
        keys = client.list_service_account_keys(
            name=name,
            key_types=[iam_v1.ListServiceAccountKeysRequest.KeyType.USER_MANAGED],
        )
        for key in keys.keys:
            client.delete_service_account_key(name=key.name)

        # 2) Create a new key
        new_key = client.create_service_account_key(name=name)
        return new_key  # store securely (Secret Manager / HSM)

    def create_metric_sa_failed_logins():
        client = logging_v2.MetricsServiceV2Client()
        parent = f"projects/{project_id}"
        metric = logging_v2.LogMetric(
            name="sa_failed_logins",
            description="LoginFailure events for service accounts",
            filter=(
                'resource.type="audited_resource" '
                'AND protoPayload.methodName="google.login.LoginService.LoginFailure" '
                'AND protoPayload.authenticationInfo.principalEmail:".gserviceaccount.com"'
            ),
        )
        client.create_log_metric(parent=parent, metric=metric)

    if __name__ == "__main__":
        # Example: list SAs and rotate keys for a specific, non-critical SA
        sas = list_service_accounts()
        for sa in sas:
            print(sa.email)
        # rotate_keys_for_service_account("my-sa@YOUR_PROJECT_ID.iam.gserviceaccount.com")
        create_metric_sa_failed_logins()
    ```
  * Bind service accounts only to specific workloads (GCE, GKE, Cloud Run) using least privilege and remove user or external principal impersonation rights (`roles/iam.serviceAccountUser`, `roles/iam.serviceAccountTokenCreator`) except where strictly necessary; monitor for `LoginFailure` from projects / networks where the SA should never be used and auto-open incidents or auto-disable keys via Cloud Functions.
