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

# OCI IAM Auth Tokens Should Be Rotated Every 90 Days

### More Info:

Auth tokens should be rotated every 90 days. Stale tokens increase the risk of unauthorized access if credentials are compromised or leaked

### Risk Level

High

### Address

Compliance, Security

### Compliance Standards

* APRA CPS 234 (Australia)
* BSI C5 (Germany)
* Brazil LGPD
* CCPA / CPRA (California)
* CIS AWS
* CIS Critical Security Controls v8
* CMMC 2.0
* CSA Cloud Controls Matrix v4
* Cloudanix Best Practice
* DPDPA
* Digital Operational Resilience Act (EU)
* Essential 8
* GDPR
* HIPAA
* HITRUST CSF
* ISO/IEC 27017
* ISO/IEC 27018
* ISO/IEC 27701
* KSA PDPL
* MAS Technology Risk Management (Singapore)
* MITRE ATT\&CK (Cloud)
* NIS2 Directive
* NIST
* NIST SP 800-171
* NYDFS 23 NYCRR 500
* Reserve Bank of India (RBI) Master Direction – Information Technology Framework
* SWIFT Customer Security Controls Framework
* Sarbanes-Oxley IT General Controls
* UK NCSC Cyber Assessment Framework

### Triage and Remediation

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

    <AccordionGroup>
      <Accordion title="Using Console" defaultOpen="true">
        Below are two things you need to do **using only the OCI Console**:

        1. **Rotate any existing auth tokens older than 90 days**
        2. **Configure monitoring (via Cloud Guard) to detect tokens older than 90 days going forward**

        ***

        ## 1. Manually rotate IAM auth tokens older than 90 days

        You must do this per user.

        1. Sign in to the **OCI Console** with a user that has IAM admin privileges.
        2. Open the navigation menu → **Identity & Security** → **Domains** (or **Identity → Users** if you are on the older model).
        3. Choose the domain (if applicable), then go to **Users**.
        4. Click the target **User**.
        5. Go to the **Auth Tokens** tab.
           * Here you see each token with its **Created** date.
        6. Identify tokens **older than 90 days**.
        7. For each such token:
           1. Click **Generate Token**.
           2. Enter a **Description**, click **Generate Token**.
           3. **Copy the token value once** (you’ll need this for the application that uses it).
           4. Update the corresponding application / script / tool to use the **new token**.
           5. After confirming the application works with the new token, go back to the **Auth Tokens** tab and click **Revoke** (trash icon) for the old token.

        Repeat for all users who have auth tokens.

        ***

        ## 2. Set up monitoring for “auth tokens not rotated in 90 days” using Cloud Guard

        Cloud Guard has built-in IAM detectors that can flag this, and you can get notified or auto-remediate.

        ### 2.1 Enable Cloud Guard and set a target

        1. In the OCI Console, go to **Identity & Security** → **Cloud Guard**.
        2. If Cloud Guard is **not enabled**, click **Enable Cloud Guard**.
        3. Create a **Target**:
           * Click **Targets** → **Create target**.
           * Give it a name.
           * Select the **compartment** (often the root compartment to cover the tenancy).
           * Choose **Target type**: typically **Compartment** (or Tenancy if available in your region/tenant).
           * Save.

        ### 2.2 Enable and tune the IAM Auth Token detector

        1. In Cloud Guard, go to **Detector Recipes**.
        2. Find the **IAM** detector recipe (for example: `OCI Configuration Detector Recipe` or similar; names can vary slightly but look for IAM-related).
        3. Click the recipe in use by your target (it will show **Attached** to your target).
        4. Click **Actions** → **View detector rules** (or “Customize” if needed).
        5. Look for a rule named similar to:
           * **“IAM Auth Token not rotated in last 90 days”**\
             or
           * **“IAM Auth Token older than specified days”**
        6. For that rule:
           * Ensure it is **Enabled**.
           * If there’s a **parameter for days**, set it to **90** days.
           * Set the **Risk Level / Severity** as desired (e.g., High).
           * Save changes (update the recipe if prompted).

        Cloud Guard will now continuously evaluate auth tokens and create **Problems** when it detects tokens older than 90 days.

        ***

        ## 3. Configure notifications for detected problems

        To know when Cloud Guard finds old tokens, connect it to OCI Notifications via Events.

        ### 3.1 Create a Notifications topic and subscription

        1. Go to **Developer Services** → **Notifications**.
        2. Click **Create Topic**, name it (e.g., `cloudguard-iam-alerts`), choose a compartment, and create.
        3. Click the new **Topic**, then **Create Subscription**:
           * Protocol: **Email** (or HTTPS/Slack via webhook as needed).
           * Enter your email and create.
        4. Confirm the subscription from your email inbox (click the confirmation link).

        ### 3.2 Create an Events rule for Cloud Guard problems

        1. Go to **Observability & Management** → **Events Service** → **Rules**.
        2. Click **Create rule**:
           * Name: `cloudguard-iam-auth-token-old-alert`.
           * Compartment: your root or security compartment (same as Cloud Guard target, usually).
        3. **Rule Condition**:
           * Set **Service Name**: `Cloud Guard`.
           * Set **Event Type**: something like **“Problem Detected”** (exact name may vary but it’s the one for new problems).
           * Optionally, add a filter on `data.problemType`, `data.detectorRuleId` or `data.riskLevel` to restrict only to the IAM auth-token detector, if you want to narrow it.
        4. **Actions**:
           * Choose **Notifications**.
           * Select the topic you created (`cloudguard-iam-alerts`).
        5. Create the rule.

        Now, whenever Cloud Guard detects an auth token that hasn’t been rotated in 90 days, it will:

        * Create a **Problem** in Cloud Guard.
        * Emit an **Event**, which triggers the **Notification** rule.
        * Send you an **email (or chosen channel)**.

        ***

        ## Ongoing process

        * **Weekly or monthly**, check **Cloud Guard → Problems** filtered by IAM / auth token rules to see if any tokens are out of compliance.
        * For each problem:
          * Identify the **user** and **auth token**.
          * Go back to **Identity & Security → Users → Auth Tokens**, rotate the token as in section 1.
          * The problem will be automatically resolved on the next evaluation cycle once the old token is revoked.

        This setup enforces the “auth tokens must be rotated every 90 days” policy using the OCI Console with Cloud Guard-based monitoring.
      </Accordion>

      <Accordion title="Using CLI">
        Below is a concise, CLI‑only way to:

        1. Detect IAM auth tokens older than 90 days
        2. Rotate them (delete old, create new)
        3. Optionally make this scriptable for ongoing monitoring

        Assumptions:

        * You already have `oci` configured (`oci setup config` done)
        * You know the user OCID(s) whose auth tokens you want to monitor/rotate

        ***

        ## 1. List IAM Auth Tokens for a User

        ```bash theme={null}
        USER_OCID="<user_ocid>"

        oci iam auth-token list \
          --user-id "$USER_OCID" \
          --all \
          --output table
        ```

        This shows each token’s `id`, `description`, and `time-created`.

        If you want JSON:

        ```bash theme={null}
        oci iam auth-token list \
          --user-id "$USER_OCID" \
          --all \
          --output json
        ```

        ***

        ## 2. Identify Tokens Older Than 90 Days (Monitoring Check)

        Example (Linux/macOS) to list only tokens older than 90 days:

        ```bash theme={null}
        USER_OCID="<user_ocid>"
        CUTOFF_DATE=$(date -u -d '90 days ago' +"%Y-%m-%dT%H:%M:%S")

        oci iam auth-token list \
          --user-id "$USER_OCID" \
          --all \
          --output json \
        | jq --arg cutoff "$CUTOFF_DATE" '
          .data[]
          | select(.["time-created"] < $cutoff)
          | {id: .id, description: .description, time_created: .["time-created"]}
        '
        ```

        On macOS with BSD `date`, use:

        ```bash theme={null}
        CUTOFF_DATE=$(date -u -v-90d +"%Y-%m-%dT%H:%M:%S")
        ```

        This gives you the list of **non‑compliant tokens** (older than 90 days) per user → use this in your monitoring/cron.

        ***

        ## 3. Delete Old (Non‑Compliant) Auth Tokens

        Once you identify IDs of old tokens, delete them:

        ```bash theme={null}
        OLD_TOKEN_ID="<old_auth_token_ocid>"

        oci iam auth-token delete \
          --user-id "$USER_OCID" \
          --auth-token-id "$OLD_TOKEN_ID" \
          --force
        ```

        Repeat for each old token.

        **Scripted delete of all tokens older than 90 days:**

        ```bash theme={null}
        USER_OCID="<user_ocid>"
        CUTOFF_DATE=$(date -u -d '90 days ago' +"%Y-%m-%dT%H:%M:%S")

        oci iam auth-token list \
          --user-id "$USER_OCID" \
          --all \
          --output json \
        | jq -r --arg cutoff "$CUTOFF_DATE" '
          .data[]
          | select(.["time-created"] < $cutoff)
          | .id
        ' \
        | while read TOKEN_ID; do
            echo "Deleting old token: $TOKEN_ID"
            oci iam auth-token delete \
              --user-id "$USER_OCID" \
              --auth-token-id "$TOKEN_ID" \
              --force
          done
        ```

        ***

        ## 4. Create New Replacement Auth Tokens (Rotation)

        Create a new token for the user:

        ```bash theme={null}
        USER_OCID="<user_ocid>"
        DESCRIPTION="Rotated-Token-$(date -u +%Y%m%d)"

        oci iam auth-token create \
          --user-id "$USER_OCID" \
          --description "$DESCRIPTION" \
          --output json
        ```

        The response includes the **plain‑text token** only once. Save it securely and update any system that uses the old token.

        Optional: if you enforce “max N tokens per user”, you can delete the oldest after you confirm all clients use the new token.

        ***

        ## 5. Automate Monitoring + Rotation (Cron / Scheduled Task)

        You can combine the above into a script, e.g. `rotate_oci_auth_tokens.sh`:

        ```bash theme={null}
        #!/usr/bin/env bash
        set -euo pipefail

        USER_OCID="<user_ocid>"
        CUTOFF_DATE=$(date -u -d '90 days ago' +"%Y-%m-%dT%H:%M:%S")

        echo "Checking tokens for user: $USER_OCID (cutoff: $CUTOFF_DATE)"

        # List old tokens
        OLD_TOKENS=$(oci iam auth-token list \
          --user-id "$USER_OCID" \
          --all \
          --output json \
        | jq -r --arg cutoff "$CUTOFF_DATE" '
          .data[]
          | select(.["time-created"] < $cutoff)
          | .id
        ')

        if [ -z "$OLD_TOKENS" ]; then
          echo "No tokens older than 90 days."
          exit 0
        fi

        # Create new token
        DESC="Rotated-Token-$(date -u +%Y%m%d)"
        NEW_TOKEN_JSON=$(oci iam auth-token create \
          --user-id "$USER_OCID" \
          --description "$DESC" \
          --output json)

        echo "New token created; store this value securely and update clients:"
        echo "$NEW_TOKEN_JSON" | jq -r '.data.token'

        # Delete old tokens
        for TOKEN_ID in $OLD_TOKENS; do
          echo "Deleting old token: $TOKEN_ID"
          oci iam auth-token delete \
            --user-id "$USER_OCID" \
            --auth-token-id "$TOKEN_ID" \
            --force
        done
        ```

        Run via cron or your scheduler and integrate with your monitoring/alerting (e.g., log to a file and have your monitoring stack parse it).

        ***

        If you share your OS (Linux/macOS/Windows) and how you prefer to schedule jobs, I can adapt the commands into a ready‑to‑use monitor/rotation script for that environment.
      </Accordion>

      <Accordion title="Using Python">
        You remediate this by **automating detection and rotation** of IAM Auth Tokens older than 90 days using the OCI Python SDK, then scheduling that script (cron/OCI Functions/DevOps).

        Below is a concise step‑by‑step approach and example code.

        ***

        ## 1. Prerequisites

        1. Install the SDK:
           ```bash theme={null}
           pip install oci
           ```

        2. Configure OCI credentials (for the user or instance principal that will manage tokens):

           * Either `~/.oci/config`:
             ```ini theme={null}
             [DEFAULT]
             user=ocid1.user.oc1..
             fingerprint=xx:xx:...
             key_file=/path/to/oci_api_key.pem
             tenancy=ocid1.tenancy.oc1..
             region=us-phoenix-1
             ```
           * Or use Instance/Resource Principals if running in OCI.

        3. The principal must have IAM permissions to manage auth tokens:
           ```text theme={null}
           Allow group <group-name> to manage auth-tokens in tenancy
           ```

        ***

        ## 2. Logic You Need

        For each IAM user:

        1. List all auth tokens.
        2. For each token:
           * Compute age from `time_created`.
           * If age > 90 days, **rotate**:
             1. Create a new token.
             2. Update the downstream system that uses the token (Git, Docker, etc.).
             3. Delete the old token.

        Note: you can’t “edit” an existing auth token; you must create a new one and then delete the old one.

        ***

        ## 3. Python Example – Detect & Rotate Tokens Older Than 90 Days

        This example assumes you’re rotating tokens for a specific user (e.g., a CI user). Adjust as needed.

        ```python theme={null}
        import oci
        from datetime import datetime, timezone, timedelta

        # --- CONFIG ---
        PROFILE_NAME = "DEFAULT"   # profile name in ~/.oci/config
        USER_OCID = "ocid1.user.oc1..xxxx"  # target IAM user whose tokens you want to rotate
        MAX_AGE_DAYS = 90

        # Helper: get OCI config / signer
        def get_identity_client():
            config = oci.config.from_file("~/.oci/config", PROFILE_NAME)
            return oci.identity.IdentityClient(config)

        def list_auth_tokens(identity_client, user_ocid):
            response = identity_client.list_auth_tokens(user_ocid)
            return response.data  # list of AuthToken objects

        def is_token_older_than(token, max_age_days):
            created = token.time_created.replace(tzinfo=timezone.utc)
            age = datetime.now(timezone.utc) - created
            return age > timedelta(days=max_age_days)

        def create_new_auth_token(identity_client, user_ocid, description="Rotated by script"):
            create_details = oci.identity.models.CreateAuthTokenDetails(
                description=description
            )
            response = identity_client.create_auth_token(
                user_id=user_ocid,
                create_auth_token_details=create_details
            )
            return response.data  # contains token and properties

        def delete_auth_token(identity_client, user_ocid, token_id):
            identity_client.delete_auth_token(user_ocid, token_id)

        def main():
            identity_client = get_identity_client()

            tokens = list_auth_tokens(identity_client, USER_OCID)

            for t in tokens:
                if is_token_older_than(t, MAX_AGE_DAYS):
                    print(f"Token {t.id} (desc='{t.description}') is older than {MAX_AGE_DAYS} days; rotating...")

                    # 1) Create a new token
                    new_token = create_new_auth_token(identity_client, USER_OCID,
                                                      description=f"Rotated replacement for {t.id}")
                    print(f"New token created: {new_token.id}")
                    print(f"*** Store this token securely now: {new_token.token} ***")
                    # NOTE: You only see the token value at creation time. Save it securely (Vault, secret manager, etc.).

                    # 2) >>> IMPORTANT <<<
                    # Update the system(s) using the old token (CI pipeline, git credential, docker login, etc.)
                    # This part is environment-specific and must be implemented by you.
                    #
                    # e.g. write the token to a secret store or config file used by your pipeline

                    # 3) After you confirm the new token is in use, delete the old token:
                    delete_auth_token(identity_client, USER_OCID, t.id)
                    print(f"Old token {t.id} deleted.")

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

        ***

        ## 4. Monitoring / Alerting Only (Optional)

        If you only want **monitoring** (no automatic rotation), modify `main()`:

        * Instead of creating/deleting tokens, just print/log tokens older than 90 days (or send to email/Slack, or push to OCI Monitoring/Logging).

        Example snippet:

        ```python theme={null}
        old_tokens = []
        for t in tokens:
            if is_token_older_than(t, MAX_AGE_DAYS):
                old_tokens.append(t)

        if old_tokens:
            for t in old_tokens:
                print(f"[ALERT] Token {t.id} for user {USER_OCID} is older than {MAX_AGE_DAYS} days (created {t.time_created})")
            # Integrate here with your alerting (OCI Notifications, email, Slack, etc.)
        ```

        ***

        ## 5. Run on a Schedule

        * On‑prem/VM: cron job running every day.
        * In OCI:
          * OCI Functions + OCI Events/cron‑like scheduling (via Service Connector or external scheduler).
          * OCI DevOps pipeline stage run on schedule.

        If you tell me your environment (VM, OCI Functions, DevOps, etc.), I can give a minimal scheduling example for that platform.
      </Accordion>

      <Accordion title="Using Terraform">
        Terraform cannot enforce “rotate every 90 days” for OCI IAM auth tokens; rotation is a time‑based operational process, not a configurable property on the `oci_identity_auth_token` resource or any IAM monitoring resource.

        There is no Terraform argument to set a max age, expiry, or rotation policy for auth tokens, and Terraform has no built‑in scheduler to recreate the token every 90 days. To remediate this finding you must rotate tokens outside Terraform, e.g.:

        * Using the OCI Console: for each user, go to **Identity & Security → Users → User Details → Auth Tokens**, delete stale tokens and create new ones.
        * Or via OCI CLI/SDK scheduled by an external system (cron, CI/CD, etc.) to delete and recreate tokens on a 90‑day cadence.

        Because there is no Terraform setting for token age/rotation, `terraform plan` will show no changes related to this control.
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>
