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

### Event Information

* **Event meaning & context**
  * `google.login.LoginService.loginSuccess` is an audit log event generated when a user (or service account using a browser flow) successfully authenticates to Google (identity platform) and receives valid credentials.
  * In GCP/GCPIAM context, it indicates a successful sign‑in to an account that *may then* be used to access GCP resources, but this event itself is about identity authentication, not specific resource access.

* **Security & compliance relevance**
  * Treat this as a key indicator in authentication monitoring: correlate it with IAM audit events (e.g., `google.iam.admin.*`, `cloudaudit.googleapis.com/activity`) to see what the authenticated principal actually did.
  * For standards like ISO 27001, SOC 2, PCI DSS, HIPAA, and CIS GCP Benchmark, use this event to support log‑based controls over user authentication, account monitoring, and anomaly detection (e.g., logins from unusual geos, frequencies, or devices).

* **Practical usage in GCP**
  * In Cloud Logging, filter on `protoPayload.methodName="google.login.LoginService.loginSuccess"` and then group by `authenticationInfo.principalEmail`, IP, and user-agent to build baselines and detect suspicious patterns.
  * Forward these logs to SIEM / Cloud Logging sinks; create alerts for high‑risk cases (e.g., loginSuccess for privileged accounts from new countries, Tor/VPN ranges, or shortly before/after sensitive IAM changes).

### Examples

* **Compromised user account gaining console access**
  * `google.login.LoginService.loginSuccess` for a user with unusual IP/ASN, geo-velocity, or outside corporate ranges.
  * Impact: Attacker can use GCPIAM permissions tied to that identity (e.g., view/modify IAM policies, exfiltrate data from Storage/BigQuery).
  * Action: Immediately revoke sessions, rotate credentials, enforce MFA, review recent `setIamPolicy` and data-access logs.

* **Privilege escalation via dormant or service account**
  * Successful login on an account that is rarely used or meant to be non-interactive (e.g., service account with console login misconfigured).
  * Impact: Violation of least privilege (ISO 27001, SOC 2), potential to modify IAM roles, create new keys, or grant admin privileges.
  * Action: Disable console login for service/dedicated accounts, remove excessive roles, review for abnormal `roles/*.admin` assignments post-login.

* **Bypass of corporate SSO / MFA policy**
  * `loginSuccess` appears for a local Google account where policy mandates SSO-only or MFA-enforced access for the project/org.
  * Impact: Breaks identity governance and access control requirements (e.g., PCI DSS 8, NIST AC-2/AC-7), reduces traceability and centralized control.
  * Action: Enforce Organization Policy for allowed domains and 2SV/MFA, audit all `loginSuccess` events for non-federated accounts, and remove their IAM bindings.

### Remediation

#### Using Console

* **Compromised user account gaining console access**
  * **Immediately contain the account**
    * In Google Cloud Console → “IAM & Admin” → “IAM”: locate the user → edit → temporarily remove all roles, or replace with a minimal read-only role while investigating.
    * In Google Admin Console (if Workspace-managed): Users → select user → “Security” → “Sign-in & security” → click “Sign out of all sessions” and “Reset sign-in cookies”; force password reset and require MFA.
  * **Rotate credentials and harden authentication**
    * In Google Admin Console: enforce 2-Step Verification and strong password policies for the OU/project group; ensure security keys or other phishing-resistant MFA where feasible.
    * In Cloud Console → “IAM & Admin” → “Service Accounts” and “Credentials” (APIs & Services): rotate any keys/tokens the user had access to (e.g., service account keys, OAuth client secrets).
  * **Review and remediate IAM and data access**
    * Cloud Console → “Logging” → “Logs Explorer”:
      * Query `protoPayload.methodName="SetIamPolicy"` and `protoPayload.authenticationInfo.principalEmail="<compromised-user>"` for suspicious IAM changes.
      * Query Storage, BigQuery, and other data-access logs (e.g., `storage.objects.get`, `bigquery.jobs.query`) filtered by the user and timeframe.
    * Roll back any suspicious IAM changes (IAM → “IAM” and “Roles” → remove newly granted roles, especially high-privilege ones), and restrict access to critical datasets.

***

* **Privilege escalation via dormant or service account**
  * **Block console/interactive use of the account**
    * For Google Workspace-managed identities: in Google Admin Console → Users → locate dormant/service user → “Security” → set “Access” to “Blocked” or disable sign-in; for true service accounts, ensure they’re not person-type users and are used via keys/tokens only.
    * In Cloud Console → “IAM & Admin” → “IAM”: confirm that service accounts do not have “Console” login paths (no OAuth consent screen for human use, no passwords/usernames).
  * **Reduce roles to least privilege**
    * Cloud Console → “IAM & Admin” → “IAM”: filter “Type” = “Service account” or specific dormant user → edit and remove broad roles like `roles/owner`, `roles/editor`, `roles/*Admin`; keep only the minimal roles required by workloads.
    * For each affected service account: “IAM & Admin” → “Service Accounts” → select account → “Permissions”: remove members granted to this service account unnecessarily (avoid service-account-as-admin patterns).
  * **Investigate and remediate potential escalation**
    * Logs Explorer:
      * Query `protoPayload.authenticationInfo.principalEmail="<acct>"` around the login time.
      * Specifically check `protoPayload.methodName="SetIamPolicy"` and `protoPayload.serviceData.policyDelta.bindingDeltas.role:"roles/*admin"` for post-login privilege grants.
    * If suspicious changes are found, revert them in “IAM” and “Roles”, revoke any newly created service account keys (“Service Accounts” → account → “Keys” → delete keys), and document changes to align with ISO 27001/SOC 2 access review requirements.

***

* **Bypass of corporate SSO / MFA policy**
  * **Identify and remove non-compliant local Google identities**
    * Cloud Console → “IAM & Admin” → “IAM”: sort/filter “Principal” by non-corporate domains (e.g., `@gmail.com`).
    * Remove these bindings by editing each member and deleting roles; ensure they’re replaced with federated/SSO identities from the allowed corporate domain(s).
  * **Enforce org policies for identity domain and MFA**
    * Cloud Console → “IAM & Admin” → “Organization policies”:
      * Set and enforce `constraints/iam.allowedPolicyMemberDomains` to only your corporate domain(s).
      * In Google Admin Console: Security → “2-step verification” → enforce MFA for all users accessing GCP projects under the org; align with PCI DSS 8 and NIST AC controls.
  * **Audit `loginSuccess` for non-federated accounts and validate compliance**
    * Logs Explorer:
      * Query `protoPayload.methodName="google.login.LoginService.loginSuccess"` and filter `protoPayload.authenticationInfo.principalEmail` not ending in your corporate domain.
      * Export these logs to BigQuery or Security Command Center for periodic review; formally track and close any findings where non-federated or non-MFA accounts had access.

#### Using CLI

* **Compromised user account gaining console access**
  * Immediately revoke sessions and rotate credentials:
    * Force sign-out (if using Google Workspace / Cloud Identity):
      * Admin Console → Security → Manage user → `End all sessions` and reset password.
    * Revoke refresh tokens and 2SV tokens (per user):
      ```bash theme={null}
      gcloud auth login   # as admin
      # List IAM policy bindings for user to identify access
      gcloud projects get-iam-policy PROJECT_ID \
        --filter="bindings.members:user:USER_EMAIL" \
        --format="yaml(bindings.role,bindings.members)"

      # Temporarily remove critical roles
      gcloud projects remove-iam-policy-binding PROJECT_ID \
        --member="user:USER_EMAIL" \
        --role="roles/owner"
      ```
  * Enforce MFA and harden account:
    * Require 2SV/MFA in org policy (Admin Console → Security → Authentication → 2-step verification).
    * Optionally add an Access Context Manager policy to restrict logins by IP:
      ```bash theme={null}
      gcloud access-context-manager perimeters update PERIMETER_NAME \
        --policy=POLICY_ID \
        --set-restricted-services=all \
        --add-resources=projects/PROJECT_NUMBER \
        --add-access-levels=accessPolicies/POLICY_ID/accessLevels/ALLOWED_IP_RANGE
      ```
  * Investigate IAM and data access:
    ```bash theme={null}
    # Review IAM changes
    gcloud logging read \
      'resource.type="project"
       protoPayload.methodName="SetIamPolicy"
       protoPayload.authenticationInfo.principalEmail="USER_EMAIL"
       timestamp>="2024-01-01T00:00:00Z"' \
      --project=PROJECT_ID \
      --format="json"

    # Review data access to Storage
    gcloud logging read \
      'resource.type="gcs_bucket"
       protoPayload.authenticationInfo.principalEmail="USER_EMAIL"
       severity>=INFO
       timestamp>="2024-01-01T00:00:00Z"' \
      --project=PROJECT_ID \
      --format="json"
    ```

* **Privilege escalation via dormant or service account**
  * Disable / restrict console and interactive use:
    * For service accounts, ensure no console login: they should only be used as `serviceAccount:...` principals, not user accounts. Remove interactive-style roles:
      ```bash theme={null}
      # List roles on service account
      gcloud projects get-iam-policy PROJECT_ID \
        --filter="bindings.members:serviceAccount:SVC_EMAIL" \
        --format="yaml(bindings.role,bindings.members)"

      # Remove over-privileged roles (example: owner / admin)
      gcloud projects remove-iam-policy-binding PROJECT_ID \
        --member="serviceAccount:SVC_EMAIL" \
        --role="roles/owner"
      gcloud projects remove-iam-policy-binding PROJECT_ID \
        --member="serviceAccount:SVC_EMAIL" \
        --role="roles/editor"
      ```
  * Lock down keys and usage to least privilege (ISO 27001 / SOC 2):
    ```bash theme={null}
    # List service account keys
    gcloud iam service-accounts keys list \
      --iam-account=SVC_EMAIL

    # Delete unused or suspicious keys
    gcloud iam service-accounts keys delete KEY_ID \
      --iam-account=SVC_EMAIL
    ```
  * Investigate recent escalations via `roles/*.admin`:
    ```bash theme={null}
    gcloud logging read \
      'resource.type="project"
       protoPayload.methodName="SetIamPolicy"
       protoPayload.authenticationInfo.principalEmail="SVC_EMAIL"
       protoPayload.serviceData.policyDelta.bindingDeltas.role:"roles/"
       timestamp>="2024-01-01T00:00:00Z"' \
      --project=PROJECT_ID \
      --format="json"
    ```

* **Bypass of corporate SSO / MFA policy**
  * Enforce org policy for allowed identity domains and MFA (PCI DSS 8, NIST AC-2/AC-7):
    ```bash theme={null}
    # Restrict identities to specific domains
    gcloud org-policies set-policy allowed_domains.yaml \
      --organization=ORG_ID

    # Example allowed_domains.yaml
    # policy:
    #   constraint: constraints/iam.allowedPolicyMemberDomains
    #   listPolicy:
    #     allowedValues:
    #     - "CLOUD_IDENTITY_CUSTOMER_ID"  # or workspace domain
    ```
    * Enable required 2SV in Admin Console and/or use BeyondCorp / Access Context Manager for additional controls.
  * Detect and audit non-federated logins:
    ```bash theme={null}
    gcloud logging read \
      'resource.type="project"
       protoPayload.methodName="google.login.LoginService.loginSuccess"
       NOT protoPayload.authenticationInfo.principalEmail:YOUR_CORP_DOMAIN
       timestamp>="2024-01-01T00:00:00Z"' \
      --project=PROJECT_ID \
      --format="json"
    ```
  * Remove IAM bindings for local/non-federated accounts:
    ```bash theme={null}
    # Inspect current bindings
    gcloud projects get-iam-policy PROJECT_ID \
      --format="yaml"

    # Remove a non-federated user
    gcloud projects remove-iam-policy-binding PROJECT_ID \
      --member="user:NONFED_GOOGLE_ACCOUNT" \
      --role="roles/viewer"
    ```

#### Using Python

* **Contain compromised account & sessions (GCPIAM / Cloud Identity / Audit review)**
  * Revoke active sessions and reset password / revoke 2SV: use Cloud Identity / Admin SDK Directory API to force sign-out and rotate credentials; immediately enforce MFA on the user if not already enabled.
  * Review IAM & data access since compromise: query Cloud Logging (`google.login.LoginService.loginSuccess`, `setIamPolicy`, `storage.objects.*`, `bigquery.jobs.*`) for the actor and timeframe; snapshot current IAM bindings for later comparison.
  * Python example (list recent loginSuccess + setIamPolicy for a user):
    ```python theme={null}
    from google.cloud import logging_v2
    from datetime import datetime, timedelta
    import json

    project_id = "YOUR_PROJECT_ID"
    user_email = "compromised.user@yourcorp.com"
    client = logging_v2.Client(project=project_id)

    now = datetime.utcnow()
    window = now - timedelta(hours=6)

    filter_ = f'''
      protoPayload.authenticationInfo.principalEmail="{user_email}"
      AND (
        protoPayload.methodName="google.login.LoginService.loginSuccess" OR
        protoPayload.methodName="SetIamPolicy" OR
        protoPayload.serviceName="storage.googleapis.com" OR
        protoPayload.serviceName="bigquery.googleapis.com"
      )
      AND timestamp>="{window.isoformat()}Z"
    '''

    for entry in client.list_entries(filter_=filter_, order_by=logging_v2.DESCENDING):
        print(entry.timestamp, entry.payload if isinstance(entry.payload, dict) else entry.payload)
    ```

* **Harden IAM for dormant / service accounts (remove console login, least privilege)**
  * Ensure service/dedicated accounts are non-interactive: remove any login-capable identities from your IdP for those accounts; for any user-account acting as “service”, strip roles that allow console use (e.g., `roles/browser`, `roles/viewer`) unless strictly required and accessed via service credentials only.
  * Detect dormant/service account misuse: search for `google.login.LoginService.loginSuccess` on principals that should never log in; then audit their IAM bindings for elevated roles (`roles/owner`, `roles/*Admin`).
  * Python example (find logins for a list of “service-like” accounts and dump current IAM roles):
    ```python theme={null}
    from google.cloud import logging_v2, resourcemanager_v3

    project_id = "YOUR_PROJECT_ID"
    service_like_accounts = [
        "svc-account-1@yourproj.iam.gserviceaccount.com",
        "svc-account-2@yourproj.iam.gserviceaccount.com",
    ]

    # 1) Find loginSuccess events (misconfig: service accounts should not have console logins)
    log_client = logging_v2.Client(project=project_id)
    filter_accounts = " OR ".join(
        [f'protoPayload.authenticationInfo.principalEmail="{a}"' for a in service_like_accounts]
    )
    log_filter = f'''
      protoPayload.methodName="google.login.LoginService.loginSuccess"
      AND ({filter_accounts})
      AND timestamp>="{datetime.utcnow().date().isoformat()}T00:00:00Z"
    '''

    for entry in log_client.list_entries(filter_=log_filter):
        print("Unexpected login:", entry.timestamp, entry.payload.get("authenticationInfo", {}))

    # 2) Dump IAM policy for manual review and role reduction
    rm_client = resourcemanager_v3.ProjectsClient()
    name = f"projects/{project_id}"
    policy = rm_client.get_iam_policy(request={"resource": name})
    for b in policy.bindings:
        if any(m in service_like_accounts for m in b.members):
            print("Binding using service-like account:", b.role, b.members)
    ```

* **Enforce SSO/MFA & eliminate local Google accounts (Org Policy + IAM cleanup)**
  * Enforce allowed domains and 2SV/MFA: configure Organization Policies such as `constraints/iam.allowedPolicyMemberDomains` and use Cloud Identity / Admin console to mandate MFA, satisfying PCI DSS 8 and NIST AC-2/AC-7.
  * Detect non-federated / local Google accounts with access: list all IAM principals on org/folder/project and look for accounts outside your corporate domain or IdP; for each, remove bindings and track any `loginSuccess` usage in logs.
  * Python example (enumerate and optionally remove non-corporate principals from a project IAM policy):
    ```python theme={null}
    from google.cloud import resourcemanager_v3

    project_id = "YOUR_PROJECT_ID"
    allowed_domain = "@yourcorp.com"  # corporate / SSO domain

    client = resourcemanager_v3.ProjectsClient()
    resource = f"projects/{project_id}"

    policy = client.get_iam_policy(request={"resource": resource})
    updated_bindings = []

    for b in policy.bindings:
        kept_members = []
        removed_members = []
        for m in b.members:
            if m.startswith("user:") or m.startswith("serviceAccount:"):
                principal = m.split(":", 1)[1]
                if allowed_domain not in principal:
                    removed_members.append(m)
                    continue
            kept_members.append(m)
        if kept_members:
            b.members[:] = kept_members
            updated_bindings.append(b)
        if removed_members:
            print(f"Removing from role {b.role}: {removed_members}")

    policy.bindings[:] = updated_bindings
    client.set_iam_policy(request={"resource": resource, "policy": policy})
    ```
