Accessing the user keychain using a script

yadmin
New Contributor II

I'm trying to retrieve the expiration date on a certificate that is only on the user's keychain, so that we can notify the user when their certificate is expiring.

After many failed attempts, I've concluded that the best way to do so is to run the security command under the user's PID.

declare -x LoginWindowPID="$(/bin/ps -axww | /usr/bin/grep loginwindo[w] | /usr/bin/awk '/console/{print $1;exit}')"
certificate=$(/bin/launchctl bsexec "${LoginWindowPID:?}" /usr/bin/sudo -u "$consoleuser" security find-certificate -c "CERT NAME")

This seems to work for about half the computers, but the other half returns that the certificate could not be found because the only available keychains are the System's.

Any ideas on how to fix this, or why the script can't access some user's keychains?

5 REPLIES 5

dfarnworth
New Contributor III

Can I ask why the need to run this under the user's PID?

We do some keychain interaction from scripts and generally find that just running

sudo -u "$currentuser" security ...

works fine.

However, what I have found is I do usually need to supply the path to the user's keychain i.e.

sudo -u "$CURRUSER" security add-generic-password -a "$KC_ACC" -s "$KC_SRV" -A -U -w "$USERPW" "$LOGINKC"

yadmin
New Contributor II

I find that running

sudo -u "$currentuser" security find-certificate -c "$cert_name"

only searches the System's keychain for the certificate. Running it from the user's PID tends to give us better results and usually returns the certificate from the user's keychain instead.

It doesn't look like there's a way to supply the user's keychain path for

security find-certificate

RobertHammen
Valued Contributor II

What about a LaunchAgent/script combo that runs when the user logs in and dumps this to a file, then a policy to pull the contents of the file as a result?

yadmin
New Contributor II

Is there a difference between a LaunchAgent and a policy that runs at login? I've tried running this script as a policy at login and the only keychains that are accessible then are the System's

RobertHammen
Valued Contributor II

LaunchAgent = runs as the user. May be able to work around this using sudo and the script variables, but...