2 # our .zprofile can be expensive, so we keep track of what has been run
3 # already, and only set up what is necessary. this also allows us to re-source
4 # the file to reinitialize specific parts when desired.
6 # in order to ensure future interactive environments are set up as early as
7 # possible, we source this file from .zshenv for non-login shells, under some
8 # specific conditions outlined there.
10 # this file respects non-interactive sessions and will not intentionally emit
13 ### fix path after system profile scripts have possibly mangled it
14 if [[ ! -v _sev_setup_path || -o login ]] {
16 export _sev_setup_path=
20 if [[ ! -v DBUS_SESSION_BUS_ADDRESS && -v commands[dbus-launch] ]] {
22 export DBUS_SESSION_BUS_ADDRESS DBUS_SESSION_BUS_PID
25 ### gpg agent + forwarding
26 # NOTE: while ssh manages its auth sock in-protocol when ForwardSsh is enabled,
27 # GPG must be forwarded manually over Unix socket. to support this, we
28 # forward the restricted gpg-agent extra socket to the remote host with a
29 # RemoteForward rule in ~/.ssh/config that uses the _GNUPG_SOCK_* vars.
31 # to avoid conflicts with other ssh sessions where the same user is
32 # connecting to the same host from different machines, gpg should utilize
33 # its own forwarded socket for each session. previously, you could
34 # provide a path to the agent socket in GPG_AGENT_INFO, but that was
35 # deprecated in GPG v2.1; instead, we must replace the socket in gpg's
38 # gnupg commits fb88f37–aab8a0b moved sockets from GNUPGHOME by default
39 # to directories under /run. aab8a0b in particular solidifies the
40 # functionality shift to utilize systemd-logind's user runtime
41 # directories. if the dir isn't found, gpg will fall back to the homedir.
42 # since previous functionality allowed multiple homedirs with multiple
43 # sockets, a provision was added where changing GNUPGHOME will also
44 # change the socket dir to a hashed dir under the usual runtime dir.
46 # utilizing this information, we can conclude:
47 # - on systems with user runtime dirs, changing GNUPGHOME will also
48 # give us a unique socket dir under the user runtime dir;
49 # - on other systems, the socket dir follows GNUPGHOME.
50 # therefore, the safest way to ensure unique sockets while not having to
51 # write specific logic for both scenarios is to simply change GNUPGHOME.
52 # the easiest way to do this is to create a new dir and link the contents
53 # of GNUPGHOME to the new home. we can then replace all of the agent
54 # sockets wherever they now are with the forwarded one. in either case we
55 # will be overwriting the session-specific sockets.
57 # NOTE: since Unix sockets are not supported under Windows, this will not work
58 # under msys, cygwin, mingw, etc., but may work under wsl2.
60 # HACK: without SendEnv, which is disabled by default in most sshd configs,
61 # there is no foolproof way to prevent race conditions via socket
62 # filename collisions or to pass the desired forward path to the remote
63 # host environment. we just have to guess the path we choose is good on
64 # the desination, and assume the newest matching socket is the correct
65 # one after connecting. in theory, we could occlude the ssh binary on
66 # PATH with an alias or script that would allow us to communicate with
67 # the remote host before opening a shell, so that we can have the host
68 # communicate back to the client where it wants a socket created or ask
69 # the host if the path the client wants to use is writable. however, this
70 # would open up too many edge cases where it wouldn't work or be too
71 # clunky (e.g. asking for password twice) to make it worth it.
72 function _gpg_socketpath {
73 # dirs are percent-encoded: https://stackoverflow.com/a/64312099
74 echo -E - ${1//(#b)%([[:xdigit:]](#c2))/${(#):-0x$match[1]}}
76 if [[ ! -v _sev_setup_gpg_forward && -v commands[gpg] ]] {
77 # XXX: assuming /tmp exists and is writable on destination
78 export _GNUPG_SOCK_DEST_BASE=/tmp/.gpg-agent-forward
79 export _GNUPG_SOCK_DEST_EXT=$(date +%s).$RANDOM
80 export _GNUPG_SOCK_DEST=$_GNUPG_SOCK_DEST_BASE.$_GNUPG_SOCK_DEST_EXT
81 export _sev_gpg_forward_dir=$XDG_RUNTIME_DIR/gnupg/.ssh_forward
82 _sev_zcleanup gpg-forward
84 # check for a forwarded socket
85 if [[ -v SSH_CLIENT ]] {
86 # find newest socket owned by us
88 s=($_GNUPG_SOCK_DEST_BASE*(N=u[$LOGNAME]oc[1]))
90 # create new forward dir
91 export _sev_setup_gpg_forward=
92 h=$_sev_gpg_forward_dir/$$
94 for x (gpg{,-agent}.conf sshcontrol random_seed
95 pubring.kbx{,~} trustdb.gpg private-keys-v1.d crls.d) {
96 ln -s ${GNUPGHOME:-~/.gnupg}/$x $h
100 for x ($(gpgconf --list-dirs | grep 'agent-.*-\?socket:')) {
101 x=$(_gpg_socketpath ${x/#agent-*socket:})
102 if [[ ! -v primary ]] {
103 # move forwarded socket to first valid agent socket path
104 # XXX: if tmp is on different filesystem this may not work
108 # make links to forwarded socket for any others
117 # what we will forward if we start a new ssh connection
118 # NOTE: do this after setting up GNUPGHOME to pick up new socket path;
119 # if already connected over SSH, extra should be the remote one
120 export _GNUPG_SOCK_SRC=$(_gpg_socketpath \
121 $(gpgconf --list-dirs agent-extra-socket))
122 } elif [[ ! -v _sev_setup_gpg_forward ]] {
123 # required for RemoteForward to not error out if the vars are unset
124 [[ ! -v _GNUPG_SOCK_SRC ]] && export _GNUPG_SOCK_SRC=/nonexistent
125 [[ ! -v _GNUPG_SOCK_DEST ]] && export _GNUPG_SOCK_DEST=/nonexistent
129 if [[ -v commands[gpg-connect-agent] &&
130 ( ! -v _sev_setup_gpgagent || -v _sev_refresh_gpgagent ) ]] {
131 # avoid printing if we have already set up tty before
132 [[ ! -v _sev_setup_gpgagent && -o interactive ]] && p=true || p=false
134 print -nP '%F{blue}>>>%f GPG: '
135 if [[ -v _sev_setup_gpg_forward ]] {
136 print -nP '%F{yellow}Forwarded agent '
138 print -nP '%F{green}Agent '
141 gpg-connect-agent /bye >/dev/null 2>&1
143 $p && print -P '%F{red}communication error'
145 if [[ ! -v _sev_setup_gpg_forward ]] {
146 if [[ ${+GPG_TTY} -eq 0 && -o interactive ]]
147 export GPG_TTY=$(tty)
148 if [[ ( -v DISPLAY || -v WAYLAND_DISPLAY ) &&
149 ${PINENTRY_USER_DATA/USE_TTY=0} == $PINENTRY_USER_DATA ]]
150 export PINENTRY_USER_DATA=${${:-${PINENTRY_USER_DATA//USE_TTY=[01] #/} USE_TTY=0}/# ##/}
151 sed -Ei 's
\1f^([[:space:]]*pinentry-program[[:space:]]).*/\.local/bin/pinentry$
\1f\1'$HOME'/.local/bin/pinentry
\1f' \
152 ${GNUPGHOME:-~/.gnupg}/gpg-agent.conf 2>/dev/null
153 gpg-connect-agent RELOADAGENT UPDATESTARTUPTTY /bye >/dev/null 2>&1
155 gpg-connect-agent /subst /serverpid \
156 "/echo pid \${get serverpid} on ${WAYLAND_DISPLAY:-${DISPLAY:-$GPG_TTY}}" /bye 2>/dev/null
162 export _sev_setup_gpgagent=
164 unset p _sev_refresh_gpgagent
168 if [[ ! -v _sev_setup_ssh ]] {
169 # NOTE: preferred order of agents to check: okcagent, gnupg, openssh
170 # first block takes care of okcagent and openssh, second gnupg
171 # XXX: doesn't actually check if ssh is enabled in gpg
172 [[ -o interactive ]] && print -nP '%F{blue}>>>%f SSH: %F{green}'
173 if [[ ! -v SSH_AUTH_SOCK && ( -v commands[okc-ssh-agent] ||
174 ( -v commands[ssh-agent] && ! -v commands[gpg] ) ) ]] {
175 okc=${commands[okc-ssh-agent]:+okc-}
176 e=$_sev_tmp/${okc}ssh-agent-exports
180 IFS=$'\0' read -r sock pid <$e
182 if ([[ -S $sock && $pid > 0 ]] && kill -0 $pid >/dev/null 2>&1) {
183 [[ -o interactive ]] && print -P "Reusing agent PID $pid%f"
184 export SSH_AUTH_SOCK=$sock
185 export SSH_AGENT_PID=$pid
187 # remove stale socket and dir
189 [[ -e $sock ]] && rm $sock 2>/dev/null
190 [[ -d ${sock:h} ]] && rmdir ${sock:h} 2>/dev/null
192 # TODO: ensure ssh-agent path looks legit to avoid unsafe eval?
193 # XXX: doesn't appear to be any other way to handle redirection.
194 # because eval needs to write to current environment,
195 # subshells can't be used to capture output and print.
196 c='TMPDIR=$_sev_tmp ${okc}ssh-agent'
197 if [[ -o interactive ]] {
198 [[ -n $okc ]] && echo -n 'OKC-'
202 eval $(eval $=c) >/dev/null 2>&1
204 echo -En - $SSH_AUTH_SOCK$'\0'$SSH_AGENT_PID >!$e
208 } elif [[ ! -v SSH_AUTH_SOCK && -v commands[gpg] ]] {
209 # since gpg should have been started above, just export and notify
210 if [[ -o interactive ]] {
211 if [[ -v _sev_setup_gpg_forward ]] {
212 echo 'Forwarded GPG agent'
214 gpg-connect-agent /subst /serverpid \
215 '/echo GPG agent pid ${get serverpid}' /bye
219 export SSH_AUTH_SOCK=$(_gpg_socketpath \
220 $(gpgconf --list-dirs agent-ssh-socket))
221 } elif [[ -v SSH_AUTH_SOCK ]] {
222 [[ -o interactive ]] && print -P 'Preconfigured agent%f'
224 [[ -o interactive ]] && print -P '%F{red}No agent available%f'
227 export _sev_setup_ssh=
229 unfunction _gpg_socketpath
232 load-plugins zprofile
234 ### load site-specific
235 load-site-dotfile zprofile