Skip to main content
KBY Technologies Logo

Stopping Login Keychain Prompt Loops Before They Escalate

Automate detection and self-service repair of macOS login keychain sync failures so technicians stop closing the same credential prompt ticket weekly.

KBY Technologies15 min readTier L135 min
Stopping Login Keychain Prompt Loops Before They Escalate

Underlined words are defined in the KBY Lexicon. Tap or click one to see what it means.

Password changes on managed Macs can leave the login keychain out of step with the account, and users then face repeated prompts until someone steps in. The traditional fix deletes the keychain and takes saved credentials with it. The mismatch can be spotted early and repaired without a technician or lost data.

#The Old Way vs the New Way

The old way looks like this: a user changes their network account password through the identity provider, and by lunchtime they are opening three, four, sometimes ten dialog boxes a day asking them to allow Mail, Safari, or Slack to use the login keychain.

The L1 fix has historically been a remote session where the technician walks the user through System Settings, deletes the login keychain, and lets rebuild it – usually losing saved Wi-Fi passwords, certificates, and app tokens in the process. It is slow, it is destructive, and it repeats itself every password rotation cycle for the same population of users.

The new way treats keychain drift as a telemetry signal, not a helpdesk conversation. We detect the unlock failure before the user files a ticket, and we remediate it with a scoped, non-destructive script that the user can run themselves from Self Service, or that fires automatically off an identity provider event. No technician touches the machine. No saved credentials are lost.

#The Everyday Problem: Login Keychain Drift

On macOS, the login keychain (~/Library/Keychains/login.keychain-db) is unlocked automatically at login because its keychain password is set to match the account’s login password.

When a password changes anywhere other than the standard local login screen – through without full sync, a forced Okta or Entra ID reset, a password sync agent lag, or a local account password reset performed by IT – the login keychain password falls out of sync with the account password. macOS keeps trying to unlock it automatically using the new password, fails silently, and then prompts the user interactively every time an app touches a keychain item.

This generates a very specific, very recognisable ticket pattern: “keeps asking me for my keychain password and nothing works.”

This is distinct from a corrupted keychain database (rare) and from an expired certificate prompt (a different signature entirely). Drift is a sync problem, not a corruption problem, and it has a clean, scriptable fix that does not require deleting anything.

macOS login keychain sync automation

#Prerequisites and Permissions

  • MDM platform with custom Extension Attribute and Self Service (or equivalent) support – examples below use syntax but the logic ports to any MDM with a scripting and policy layer.
  • Jamf Pro runs policy scripts with superuser privileges, so the scripts below switch to the logged-in user for the keychain commands, because security keychain operations must run in the user’s security context.
  • No storage of plaintext passwords anywhere – scripts must pass credentials directly to the security binary and never write them to disk, logs, or MDM inventory fields. Known exposure: the remediation passes both passwords to security as command-line arguments, so while that command runs any process on the Mac that lists processes can read them. Accept this risk explicitly for the pilot, or use the manual Keychain Access route described in Step 4.
  • A retention rule for keychain backups: keep each copy until the user confirms the repair, then remove it with the reviewed, logged cleanup in the Rollback section.
  • A backup of each pilot user’s login keychain file, taken by the remediation script.
  • Read-only API scope on the identity provider (Okta System Log or Entra ID Audit Log) if you are wiring up the proactive webhook trigger in Step 5.
  • Jamf Pro API role with read access to computers and update access to static computer groups only – the webhook listener adds computers to one static group, so do not grant full API admin to its service account.
  • Test scope: a single Smart Group of 10–20 pilot machines before fleet-wide deployment. Blast radius if the detection logic misfires is a false-positive notification, not data loss, because the remediation script never deletes keychain data and copies the keychain file before changing its password.

#Implementation Steps

  1. Step 1 – Deploy a lightweight drift detector as a LaunchAgent. Action: push a script and LaunchAgent plist that checks whether the login keychain is unlocked without a password challenge at login. Expected result: a flag file is written when the keychain query fails with one of the expected lock or authentication errors; a successful query clears the flag, and any other result leaves it unchanged. This is an unvalidated heuristic, so treat the flag as a suspected-drift signal that offers the user a fix, never as a trigger for automatic changes. Evidence to capture: presence and timestamp of /Users/Shared/.kc_drift_flag on affected machines.
    1#!/bin/bash
    2# /usr/local/kby/keychain-drift-check.sh
    3# Runs as the logged-in user via LaunchAgent.
    4
    5FLAG="/Users/Shared/.kc_drift_flag"
    6LOGIN_KC="$HOME/Library/Keychains/login.keychain-db"
    7
    8# Query the login keychain's settings; this needs no particular item to exist.
    9# Heuristic, not documented by Apple for drift: exit 0 means the keychain answered
    10# normally. A drifted (still locked) keychain is expected to fail with -25308
    11# (errSecInteractionNotAllowed, "User interaction is not allowed") or -25293
    12# (errSecAuthFailed). Confirm on a deliberately drifted pilot Mac what it prints,
    13# and that it raises no unlock dialog, before scoping anything to the flag.
    14OUTPUT=$(/usr/bin/security show-keychain-info "$LOGIN_KC" 2>&1)
    15STATUS=$?
    16
    17if [ $STATUS -eq 0 ]; then
    18  /bin/rm -f "$FLAG"
    19elif echo "$OUTPUT" | /usr/bin/grep -Eq "25308|25293|User interaction is not allowed"; then
    20  /usr/bin/touch "$FLAG"
    21  echo "$(date -u +%Y-%m-%dT%H:%M:%SZ) drift-detected" >> "$FLAG"
    22else
    23  # Unrecognised result: no evidence either way, so leave any existing flag alone.
    24  /usr/bin/logger -t kc-drift "inconclusive (status $STATUS): $OUTPUT"
    25fi
  2. Step 2 – Register the LaunchAgent so the check runs every login and every four hours. Action: deploy the plist via MDM configuration profile or a package postinstall script. Expected result: launchctl list shows the agent loaded for the console user. Evidence to capture: launchctl print gui/$(id -u)/com.kby.keychaindriftcheck output showing state running or last exit code 0.
    1<?xml version="1.0" encoding="UTF-8"?>
    2<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    3<plist version="1.0">
    4<dict>
    5  <key>Label</key>
    6  <string>com.kby.keychaindriftcheck</string>
    7  <key>ProgramArguments</key>
    8  <array>
    9    <string>/usr/local/kby/keychain-drift-check.sh</string>
    10  </array>
    11  <key>RunAtLoad</key>
    12  <true/>
    13  <key>StartInterval</key>
    14  <integer>14400</integer>
    15</dict>
    16</plist>
  3. Step 3 – Surface the flag as a Jamf Pro Extension Attribute and Smart Group. Action: create an EA script read at inventory update that reports true or false based on flag presence. Expected result: computers with drift populate a Smart Group named Keychain-Drift-Suspected within one inventory cycle. Evidence to capture: Smart Group membership count and the EA value shown against the device record.
    1#!/bin/bash
    2FLAG="/Users/Shared/.kc_drift_flag"
    3if [ -f "$FLAG" ]; then
    4  echo "<result>true</result>"
    5else
    6  echo "<result>false</result>"
    7fi
  4. Step 4 – Build the non-destructive remediation Self Service policy. Action: publish a Self Service item scoped to Keychain-Drift-Suspected that backs up the login keychain file, prompts the user for their previous and current account passwords, changes the keychain password from the old one to the new one in place, then discards both values immediately. The keychain is still protected by the old password, so that old password is needed to change it to the current one. Because both values briefly appear in the process list, offer users the manual alternative too: in Keychain Access, choose Edit > Change Password for Keychain “login” and enter the old and new passwords there. Expected result: subsequent app launches no longer trigger keychain dialogs. Evidence to capture: exit code 0 in the policy log and the drift flag cleared on next detector run.
    1#!/bin/bash
    2# Jamf Pro runs policy scripts with superuser privileges, so user-facing steps run as the console user.
    3CONSOLE_USER=$(/usr/bin/stat -f %Su /dev/console)
    4CONSOLE_UID=$(/usr/bin/id -u "$CONSOLE_USER")
    5USER_HOME=$(/usr/bin/dscl . -read "/Users/$CONSOLE_USER" NFSHomeDirectory | /usr/bin/awk '{print $2}')
    6LOGIN_KC="$USER_HOME/Library/Keychains/login.keychain-db"
    7as_user() { /bin/launchctl asuser "$CONSOLE_UID" /usr/bin/sudo -u "$CONSOLE_USER" "$@"; }
    8ask() {
    9  as_user /usr/bin/osascript -e 'on run argv' \
    10    -e 'text returned of (display dialog (item 1 of argv) default answer "" with hidden answer)' \
    11    -e 'end run' "$1" 2>/dev/null
    12}
    13
    14# Back up the keychain file before changing anything; keep it until the user confirms the repair (see Rollback).
    15/bin/cp -p "$LOGIN_KC" "$LOGIN_KC.bak-$(date +%Y%m%d%H%M%S)" || exit 1
    16
    17OLD_PW=$(ask "Enter your PREVIOUS account password (the one your keychain still uses):")
    18NEW_PW=$(ask "Enter your CURRENT account password:")
    19
    20if [ -z "$OLD_PW" ] || [ -z "$NEW_PW" ]; then
    21  echo "User cancelled remediation."
    22  exit 1
    23fi
    24
    25# Change the keychain password from the old account password to the current one.
    26# -o = old password, -p = new password. Never written to disk, but passed as
    27# arguments, so they are briefly visible in the process list.
    28as_user /usr/bin/security set-keychain-password -o "$OLD_PW" -p "$NEW_PW" "$LOGIN_KC"
    29RESULT=$?
    30
    31unset OLD_PW NEW_PW
    32
    33if [ $RESULT -eq 0 ]; then
    34  /bin/rm -f "/Users/Shared/.kc_drift_flag"
    35  as_user /usr/bin/osascript -e 'display notification "Keychain sync repaired. No restart needed." with title "IT Self Service"'
    36  exit 0
    37else
    38  as_user /usr/bin/osascript -e 'display notification "Password did not match. Contact IT if prompts continue." with title "IT Self Service"'
    39  exit 1
    40fi

    Apple does not document this flow for drift repair, so validate it on pilot Macs (with the backup above in place) before wider release.

    Expected output in the Jamf policy log: Script exit code: 0 and a cleared drift flag confirmed by the next scheduled inventory submission.

  5. Step 5 – Wire the proactive trigger from the identity provider. Action: subscribe to the password-change event in your IdP’s system log and fire a lightweight webhook when a rotation happens. The listener adds the user’s Mac to a static group, Keychain-Resync-Reminder, which scopes a policy that shows a reminder to run the Self Service item. The listener adds a Mac only when exactly one inventory record’s user email equals the address, starts in dry-run mode (it logs what it would add), caps additions per day, and answers 503 while a pause file exists. Expected result: the reminder appears at the Mac’s next check-in after the password change, so delivery time depends on your check-in frequency. Evidence to capture: webhook delivery log, the group membership change, and the reminder policy log entry.
    1{
    2  "eventType": "user.account.update_password",
    3  "actor": {
    4    "id": "00u1a2b3c4d5e6f7g8h9",
    5    "type": "User",
    6    "alternateId": "jane.doe@kby.example"
    7  },
    8  "published": "2024-11-02T09:14:32.101Z",
    9  "outcome": {
    10    "result": "SUCCESS"
    11  },
    12  "target": [
    13    {
    14      "id": "00u1a2b3c4d5e6f7g8h9",
    15      "type": "User",
    16      "alternateId": "jane.doe@kby.example"
    17    }
    18  ]
    19}
    1from flask import Flask, request, abort
    2import hmac, hashlib, os, requests
    3from datetime import datetime, timezone
    4
    5app = Flask(__name__)
    6HOOK_SECRET = os.environ["OKTA_HOOK_AUTH_VALUE"]  # static value set in the Okta event hook
    7JAMF_BASE = os.environ["JAMF_BASE_URL"]
    8JAMF_TOKEN = os.environ["JAMF_API_TOKEN"]
    9PILOT_CAP = 20  # most users notified per delivery
    10REMINDER_GROUP_ID = int(os.environ["REMINDER_GROUP_ID"])  # static group ID
    11DAILY_CAP = 50  # most Macs added per UTC day, across all deliveries
    12DRY_RUN = os.environ.get("DRY_RUN", "true") != "false"  # default: log only
    13PAUSE_FILE = "/var/lib/kby-hook/paused"  # kill switch: create this file to stop changes
    14
    15def within_daily_cap():
    16    # Counts additions per UTC day in a file, so the cap survives restarts.
    17    path = f"/var/lib/kby-hook/added-{datetime.now(timezone.utc):%Y-%m-%d}"
    18    used = int(open(path).read()) if os.path.exists(path) else 0
    19    if used >= DAILY_CAP:
    20        return False
    21    with open(path, "w") as f:
    22        f.write(str(used + 1))
    23    return True
    24
    25@app.route("/okta/password-change", methods=["GET"])
    26def verify_hook():
    27    # Okta's one-time verification request: echo the challenge back.
    28    return {"verification": request.headers.get("X-Okta-Verification-Challenge", "")}
    29
    30@app.route("/okta/password-change", methods=["POST"])
    31def handle_event():
    32    # Okta sends the authorisation value configured on the hook, not an HMAC signature.
    33    auth = request.headers.get("Authorization", "")
    34    if not hmac.compare_digest(auth, HOOK_SECRET):
    35        app.logger.warning("auth failure from %s", request.remote_addr)
    36        abort(401)
    37    if os.path.exists(PAUSE_FILE):
    38        return "", 503  # paused: Okta sees a failure and nothing is changed
    39
    40    # Okta wraps System Log events in data.events; the user whose password changed is the target.
    41    events = request.get_json().get("data", {}).get("events", [])
    42    users = [e["target"][0]["alternateId"] for e in events
    43             if e.get("eventType") == "user.account.update_password" and e.get("target")][:PILOT_CAP]
    44    if not users:
    45        return "", 204
    46
    47    # Exact lookup with the Jamf Pro API: only a Mac whose recorded user email equals
    48    # the address counts, and a user with no match or several matches is skipped for
    49    # manual review. No password data is handled here.
    50    hdrs = {"Authorization": "Bearer " + JAMF_TOKEN, "Accept": "application/json"}
    51    for email in users:
    52        r = requests.get(f"{JAMF_BASE}/api/v1/computers-inventory",
    53                         params={"section": "USER_AND_LOCATION",
    54                                 "filter": f'userAndLocation.email=="{email}"'},
    55                         headers=hdrs, timeout=10)
    56        r.raise_for_status()
    57        macs = [m for m in r.json().get("results", [])
    58                if (m.get("userAndLocation") or {}).get("email", "").lower() == email.lower()]
    59        if len(macs) != 1:
    60            app.logger.warning("skipped %s: %d exact matches", email, len(macs))
    61            continue
    62        mac_id = int(macs[0]["id"])
    63        if DRY_RUN or not within_daily_cap():
    64            app.logger.info("not added (dry run or daily cap): %s -> %d", email, mac_id)
    65            continue
    66        xml = ("<computer_group><computer_additions><computer><id>%d</id>"
    67               "</computer></computer_additions></computer_group>" % mac_id)
    68        resp = requests.put(f"{JAMF_BASE}/JSSResource/computergroups/id/{REMINDER_GROUP_ID}",
    69                            headers={**hdrs, "Content-Type": "application/xml"},
    70                            data=xml, timeout=10)
    71        app.logger.info("added %d for %s: HTTP %s", mac_id, email, resp.status_code)
    72    return "", 200

Following along? Tap a step’s number to tick it off.

#Verification and Expected Evidence

Confirm success across three layers. First, the detector: run /usr/local/kby/keychain-drift-check.sh manually and confirm no flag file is created on a healthy machine. Second, the Smart Group: after remediation, the device drops out of Keychain-Drift-Suspected within one inventory cycle – capture a before-and-after screenshot of group membership count.

Third, the user experience: ask the pilot user to open Mail or Safari and confirm zero keychain prompts across a full working day. Log this as a closed-loop verification note on the change record, not a ticket.

#Rollback

The remediation script is non-destructive by design – it resynchronises the existing keychain password rather than deleting the keychain, so there is no data loss to roll back.

If a run goes wrong, restore the backup with the user logged out: from an MDM script or remote shell, copy the newest login.keychain-db.bak-* file in the user’s ~/Library/Keychains folder over login.keychain-db with cp -p, confirm the user still owns it, and ask the user to log in; the keychain then uses the old password again.

Backups hold data protected by the old password, so remove them once the user has confirmed the repair, not on a blind schedule across every home folder.

Scope the cleanup to one confirmed user and list before you delete: find "/Users/$CONFIRMED_USER/Library/Keychains" -name 'login.keychain-db.bak-*' -print shows what would go; after reviewing that list, run the same command with -print -delete in place of -print from an approved policy, so every removed path is written to the policy log.

If the script fails validation during pilot (exit code 1, or the drift flag persists after a successful-looking run), disable the Self Service policy scope back to the pilot Smart Group, unload the LaunchAgent via a removal script pushed through MDM, and revert affected users to the manual System Settings walkthrough until the script logic is fixed.

Keep the webhook listener paused (return 503 to the IdP) rather than deleting the endpoint, so the IdP does not silently drop the subscription.

Stopping Login Keychain Prompt Loops Before They Escalate architecture diagram 2

#Failure and Escalation Conditions

Escalate to a human technician when any of the following occur: the remediation script returns exit code 1 after the user has confirmed the password entered was correct, which indicates the underlying keychain file may be corrupted rather than merely desynchronised, and needs the destructive rebuild path with proper data-loss consent.

Escalate when a single device triggers the drift flag more than three times in 24 hours, since repeated drift after a successful resync usually points to a Platform SSO configuration fault or a password sync agent looping.

Escalate when the webhook listener logs authorisation failures (401 responses), which may indicate a compromised or misconfigured IdP integration and should be treated as a security event, not a helpdesk item.

The monitoring signal to watch on the automation side is the ratio of Self Service remediation runs to Smart Group entries per day; a sustained spike suggests an upstream password policy change is causing mass drift and warrants a broader fix rather than per-device remediation.

#Measuring Ticket Deflection

Baseline the current volume by pulling the last 90 days of tickets tagged with keywords like “keychain”, “always asking for password”, and “wants to use login keychain” from your ticketing system. After deployment, track three numbers monthly: Smart Group entries into Keychain-Drift-Suspected, Self Service remediation runs with exit code 0, and residual tickets on the same keyword filter.

A successful rollout typically shows Smart Group entries holding steady or rising slightly (better detection) while ticket volume on the same keyword set drops close to zero within one full password rotation cycle, since that is when the old-way tickets used to spike.

Report deflected tickets as detections resolved by Self Service divided by total detections, and keep the time from IdP event to reminder delivery as a secondary KPI to prove the proactive path is catching drift before users notice it.

#References

See Apple’s command reference for keychain password operations in the security command-line tool documentation and Apple’s official guidance on Keychain Access behaviour on macOS. For the identity provider side of the proactive trigger, consult Okta’s System Log API reference for event subscription and payload schema details, and the Jamf Pro API developer documentation for custom trigger and Extension Attribute implementation specifics used throughout this workflow.

Evidence trail

Sources and verification

Primary documentation and external technical references used in this article.

  1. 01security command-line tool documentationss64.com
  2. 02Keychain Access behaviour on macOSsupport.apple.com
  3. 03Okta's System Log API referencedeveloper.okta.com
  4. 04Jamf Pro API developer documentationdeveloper.jamf.com

About this page

Credited to

Dates

Published

Corrections

  • : Corrected during a review of published articles. Details
  • : Corrected during a review of published articles. Details

Found this useful? Follow KBY for more like it.

Reader Interaction

Comments

Add a thoughtful note on Stopping Login Keychain Prompt Loops Before They Escalate. Comments are checked for spam and held for moderation before appearing.

Loading comments...

Operate smarter, with fewer recurring tickets.

Receive new operational playbooks, incident-prevention guidance, automation scripts and recovery runbooks.