3 # Shared sh functions for the monkeysphere
6 # Jameson Rollins <jrollins@fifthhorseman.net>
7 # Jamie McClelland <jm@mayfirst.org>
8 # Daniel Kahn Gillmor <dkg@fifthhorseman.net>
10 # Copyright 2008, released under the GPL, version 3 or later
12 # all-caps variables are meant to be user supplied (ie. from config
13 # file) and are considered global
15 ########################################################################
19 ETC="/etc/monkeysphere"
22 ########################################################################
25 # failure function. exits with code 255, unless specified otherwise.
31 # write output to stderr based on specified LOG_LEVEL the first
32 # parameter is the priority of the output, and everything else is what
38 # don't include SILENT in alllevels: it's handled separately
39 # list in decreasing verbosity (all caps)
40 local alllevels="DEBUG INFO ERROR"
43 # translate lowers to uppers in global log level
44 LOG_LEVEL=$(echo "$LOG_LEVEL" | tr "[:lower:]" "[:upper:]")
46 # just go ahead and return if the log level is silent
47 if [ "$LOG_LEVEL" = 'SILENT' ] ; then
51 for level in $alllevels; do
52 if [ "$LOG_LEVEL" = "$level" ] ; then
56 if [ -z "$found" ] ; then
61 # get priority from first parameter, translating all lower to
63 priority=$(echo "$1" | tr "[:lower:]" "[:upper:]")
66 # scan over available levels
67 for level in $alllevels ; do
68 # output if the log level matches, set output to true
69 # this will output for all subsequent loops as well.
70 if [ "$LOG_LEVEL" = "$level" ] ; then
73 if [ "$priority" = "$level" -a "$output" = 'true' ] ; then
80 # cut out all comments(#) and blank lines from standard input
82 grep -v -e "^[[:space:]]*#" -e '^$' "$1"
85 # cut a specified line from standard input
87 head --line="$1" "$2" | tail -1
90 # check that characters are in a string (in an AND fashion).
91 # used for checking key capability
92 # check_capability capability a [b...]
101 if echo "$usage" | grep -q -v "$capcheck" ; then
110 md5sum "$1" 2> /dev/null
113 # convert escaped characters in pipeline from gpg output back into
115 # FIXME: undo all escape character translation in with-colons gpg
121 # convert nasty chars into gpg-friendly form in pipeline
122 # FIXME: escape everything, not just colons!
127 # prompt for GPG-formatted expiration, and emit result on stdout
128 get_gpg_expiration() {
133 if [ -z "$keyExpire" ]; then
135 Please specify how long the key should be valid.
136 0 = key does not expire
137 <n> = key expires in n days
138 <n>w = key expires in n weeks
139 <n>m = key expires in n months
140 <n>y = key expires in n years
142 while [ -z "$keyExpire" ] ; do
143 read -p "Key is valid for? (0) " keyExpire
144 if ! test_gpg_expire ${keyExpire:=0} ; then
145 echo "invalid value" >&2
149 elif ! test_gpg_expire "$keyExpire" ; then
150 failure "invalid key expiration value '$keyExpire'."
156 passphrase_prompt() {
161 if [ "$DISPLAY" ] && which "${SSH_ASKPASS:-ssh-askpass}" >/dev/null; then
162 "${SSH_ASKPASS:-ssh-askpass}" "$prompt" > "$fifo"
164 read -s -p "$prompt" PASS
165 # Uses the builtin echo, so should not put the passphrase into
166 # the process table. I think. --dkg
167 echo "$PASS" > "$fifo"
171 test_gnu_dummy_s2k_extension() {
173 # this block contains a demonstration private key that has had the
174 # primary key stripped out using the GNU S2K extension known as
175 # "gnu-dummy" (see /usr/share/doc/gnupg/DETAILS.gz). The subkey is
176 # present in cleartext, however.
178 # openpgp2ssh will be able to deal with this based on whether the
179 # local copy of GnuTLS contains read_s2k support that can handle it.
181 # read up on that here:
183 # http://lists.gnu.org/archive/html/gnutls-devel/2008-08/msg00005.html
186 -----BEGIN PGP PRIVATE KEY BLOCK-----
187 Version: GnuPG v1.4.9 (GNU/Linux)
189 lQCVBEO3YdABBACRqqEnucag4+vyZny2M67Pai5+5suIRRvY+Ly8Ms5MvgCi3EVV
190 xT05O/+0ShiRaf+QicCOFrhbU9PZzzU+seEvkeW2UCu4dQfILkmj+HBEIltGnHr3
191 G0yegHj5pnqrcezERURf2e17gGFWX91cXB9Cm721FPXczuKraphKwCA9PwARAQAB
192 /gNlAkdOVQG0OURlbW9uc3RyYXRpb24gS2V5IGZvciBTMksgR05VIGV4dGVuc2lv
193 biAxMDAxIC0tIGdudS1kdW1teYi8BBMBAgAmBQJDt2HQAhsDBQkB4TOABgsJCAcD
194 AgQVAggDBBYCAwECHgECF4AACgkQQZUwSa4UDezTOQP/TMQXUVrWzHYZGopoPZ2+
195 ZS3qddiznBHsgb7MGYg1KlTiVJSroDUBCHIUJvdQKZV9zrzrFl47D07x6hGyUPHV
196 aZXvuITW8t1o5MMHkCy3pmJ2KgfDvdUxrBvLfgPMICA4c6zA0mWquee43syEW9NY
197 g3q61iPlQwD1J1kX1wlimLCdAdgEQ7dh0AEEANAwa63zlQbuy1Meliy8otwiOa+a
198 mH6pxxUgUNggjyjO5qx+rl25mMjvGIRX4/L1QwIBXJBVi3SgvJW1COZxZqBYqj9U
199 8HVT07mWKFEDf0rZLeUE2jTm16cF9fcW4DQhW+sfYm+hi2sY3HeMuwlUBK9KHfW2
200 +bGeDzVZ4pqfUEudABEBAAEAA/0bemib+wxub9IyVFUp7nPobjQC83qxLSNzrGI/
201 RHzgu/5CQi4tfLOnwbcQsLELfker2hYnjsLrT9PURqK4F7udrWEoZ1I1LymOtLG/
202 4tNZ7Mnul3wRC2tCn7FKx8sGJwGh/3li8vZ6ALVJAyOia5TZ/buX0+QZzt6+hPKk
203 7MU1WQIA4bUBjtrsqDwro94DvPj3/jBnMZbXr6WZIItLNeVDUcM8oHL807Am97K1
204 ueO/f6v1sGAHG6lVPTmtekqPSTWBfwIA7CGFvEyvSALfB8NUa6jtk27NCiw0csql
205 kuhCmwXGMVOiryKEfegkIahf2bAd/gnWHPrpWp7bUE20v8YoW22I4wIAhnm5Wr5Q
206 Sy7EHDUxmJm5TzadFp9gq08qNzHBpXSYXXJ3JuWcL1/awUqp3tE1I6zZ0hZ38Ia6
207 SdBMN88idnhDPqPoiKUEGAECAA8FAkO3YdACGyAFCQHhM4AACgkQQZUwSa4UDezm
208 vQP/ZhK+2ly9oI2z7ZcNC/BJRch0/ybQ3haahII8pXXmOThpZohr/LUgoWgCZdXg
209 vP6yiszNk2tIs8KphCAw7Lw/qzDC2hEORjWO4f46qk73RAgSqG/GyzI4ltWiDhqn
210 vnQCFl3+QFSe4zinqykHnLwGPMXv428d/ZjkIc2ju8dRsn4=
212 -----END PGP PRIVATE KEY BLOCK-----
213 " | openpgp2ssh 4129E89D17C1D591 >/dev/null 2>/dev/null
217 # remove all lines with specified string from specified file
225 if [ -z "$file" -o -z "$string" ] ; then
229 if [ ! -e "$file" ] ; then
233 # if the string is in the file...
234 if grep -q -F "$string" "$file" 2> /dev/null ; then
235 # remove the line with the string, and return 0
236 grep -v -F "$string" "$file" | sponge "$file"
244 # remove all lines with MonkeySphere strings in file
245 remove_monkeysphere_lines() {
250 if [ -z "$file" ] ; then
254 if [ ! -e "$file" ] ; then
258 egrep -v '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$' \
259 "$file" | sponge "$file"
262 # translate ssh-style path variables %h and %u
263 translate_ssh_variables() {
270 # get the user's home directory
271 userHome=$(getent passwd "$uname" | cut -d: -f6)
273 # translate '%u' to user name
274 path=${path/\%u/"$uname"}
275 # translate '%h' to user home directory
276 path=${path/\%h/"$userHome"}
281 # test that a string to conforms to GPG's expiration format
283 echo "$1" | egrep -q "^[0-9]+[mwy]?$"
286 # check that a file is properly owned, and that all it's parent
287 # directories are not group/other writable
288 check_key_file_permissions() {
295 # function to check that an octal corresponds to writability
297 [ "$1" -eq 2 -o "$1" -eq 3 -o "$1" -eq 6 -o "$1" -eq 7 ]
303 # return 0 is path does not exist
304 [ -e "$path" ] || return 0
306 owner=$(stat --format '%U' "$path")
307 access=$(stat --format '%a' "$path")
308 gAccess=$(echo "$access" | cut -c2)
309 oAccess=$(echo "$access" | cut -c3)
312 if [ "$owner" != "$user" -a "$owner" != 'root' ] ; then
316 # check group/other writability
317 if is_write "$gAccess" || is_write "$oAccess" ; then
321 if [ "$path" = '/' ] ; then
324 check_key_file_permissions $(dirname "$path")
328 ### CONVERSION UTILITIES
330 # output the ssh key for a given key ID
336 gpg --export "$keyID" | openpgp2ssh "$keyID" 2> /dev/null
339 # output known_hosts line from ssh key
348 echo -n "$key" | tr -d '\n'
349 echo " MonkeySphere${DATE}"
352 # output authorized_keys line from ssh key
353 ssh2authorized_keys() {
360 echo -n "$key" | tr -d '\n'
361 echo " MonkeySphere${DATE} ${userID}"
364 # convert key from gpg to ssh known_hosts format
372 # NOTE: it seems that ssh-keygen -R removes all comment fields from
373 # all lines in the known_hosts file. why?
374 # NOTE: just in case, the COMMENT can be matched with the
376 # '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$'
378 gpg2ssh "$keyID" | tr -d '\n'
379 echo " MonkeySphere${DATE}"
382 # convert key from gpg to ssh authorized_keys format
383 gpg2authorized_keys() {
390 # NOTE: just in case, the COMMENT can be matched with the
392 # '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$'
393 gpg2ssh "$keyID" | tr -d '\n'
394 echo " MonkeySphere${DATE} ${userID}"
399 # retrieve all keys with given user id from keyserver
400 # FIXME: need to figure out how to retrieve all matching keys
401 # (not just first N (5 in this case))
406 if [ "$CHECK_KEYSERVER" != 'true' ] ; then
412 log info " checking keyserver $KEYSERVER... "
414 gpg --quiet --batch --with-colons \
415 --command-fd 0 --keyserver "$KEYSERVER" \
416 --search ="$userID" > /dev/null 2>&1
419 # if the user is the monkeysphere user, then update the
420 # monkeysphere user's trustdb
421 if [ $(id -un) = "$MONKEYSPHERE_USER" ] ; then
422 gpg_authentication "--check-trustdb" > /dev/null 2>&1
428 ########################################################################
429 ### PROCESSING FUNCTIONS
431 # userid and key policy checking
432 # the following checks policy on the returned keys
433 # - checks that full key has appropriate valididy (u|f)
434 # - checks key has specified capability (REQUIRED_*_KEY_CAPABILITY)
435 # - checks that requested user ID has appropriate validity
436 # (see /usr/share/doc/gnupg/DETAILS.gz)
437 # output is one line for every found key, in the following format:
441 # "flag" is an acceptability flag, 0 = ok, 1 = bad
442 # "sshKey" is the translated gpg key
444 # all log output must go to stderr, as stdout is used to pass the
445 # flag:sshKey to the calling function.
447 # expects global variable: "MODE"
450 local requiredCapability
451 local requiredPubCapability
466 # set the required key capability based on the mode
467 if [ "$MODE" = 'known_hosts' ] ; then
468 requiredCapability="$REQUIRED_HOST_KEY_CAPABILITY"
469 elif [ "$MODE" = 'authorized_keys' ] ; then
470 requiredCapability="$REQUIRED_USER_KEY_CAPABILITY"
472 requiredPubCapability=$(echo "$requiredCapability" | tr "[:lower:]" "[:upper:]")
474 # fetch the user ID if necessary/requested
475 gpg_fetch_userid "$userID"
477 # output gpg info for (exact) userid and store
478 gpgOut=$(gpg --list-key --fixed-list-mode --with-colon \
479 --with-fingerprint --with-fingerprint \
480 ="$userID" 2>/dev/null)
482 # if the gpg query return code is not 0, return 1
483 if [ "$?" -ne 0 ] ; then
484 log error " no primary keys found."
488 # loop over all lines in the gpg output and process.
489 echo "$gpgOut" | cut -d: -f1,2,5,10,12 | \
490 while IFS=: read -r type validity keyid uidfpr usage ; do
491 # process based on record type
493 'pub') # primary keys
494 # new key, wipe the slate
501 log error " primary key found: $keyid"
503 # if overall key is not valid, skip
504 if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
505 log error " - unacceptable primary key validity ($validity)."
508 # if overall key is disabled, skip
509 if check_capability "$usage" 'D' ; then
510 log error " - key disabled."
513 # if overall key capability is not ok, skip
514 if ! check_capability "$usage" $requiredPubCapability ; then
515 log error " - unacceptable primary key capability ($usage)."
519 # mark overall key as ok
522 # mark primary key as ok if capability is ok
523 if check_capability "$usage" $requiredCapability ; then
528 if [ "$lastKey" != pub ] ; then
529 log error " - got a user ID after a sub key?! user IDs should only follow primary keys!"
532 # if an acceptable user ID was already found, skip
533 if [ "$uidOK" = 'true' ] ; then
536 # if the user ID does matches...
537 if [ "$(echo "$uidfpr" | gpg_unescape)" = "$userID" ] ; then
538 # and the user ID validity is ok
539 if [ "$validity" = 'u' -o "$validity" = 'f' ] ; then
540 # mark user ID acceptable
547 # output a line for the primary key
549 if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
550 log error " * acceptable primary key."
551 if [ -z "$sshKey" ] ; then
552 log error " ! primary key could not be translated (not RSA or DSA?)."
557 log error " - unacceptable primary key."
558 if [ -z "$sshKey" ] ; then
559 log error " ! primary key could not be translated (not RSA or DSA?)."
566 # unset acceptability of last key
571 # don't bother with sub keys if the primary key is not valid
572 if [ "$keyOK" != true ] ; then
576 # don't bother with sub keys if no user ID is acceptable:
577 if [ "$uidOK" != true ] ; then
581 # if sub key validity is not ok, skip
582 if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
585 # if sub key capability is not ok, skip
586 if ! check_capability "$usage" $requiredCapability ; then
593 'fpr') # key fingerprint
594 fingerprint="$uidfpr"
596 sshKey=$(gpg2ssh "$fingerprint")
598 # if the last key was the pub key, skip
599 if [ "$lastKey" = pub ] ; then
603 # output a line for the sub key
605 if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
606 log error " * acceptable sub key."
607 if [ -z "$sshKey" ] ; then
608 log error " ! sub key could not be translated (not RSA or DSA?)."
613 log error " - unacceptable sub key."
614 if [ -z "$sshKey" ] ; then
615 log error " ! sub key could not be translated (not RSA or DSA?)."
622 done | sort -t: -k1 -n -r
623 # NOTE: this last sort is important so that the "good" keys (key
624 # flag '0') come last. This is so that they take precedence when
625 # being processed in the key files over "bad" keys (key flag '1')
628 # process a single host in the known_host file
629 process_host_known_hosts() {
639 userID="ssh://${host}"
641 log info "processing: $host"
647 for line in $(process_user_id "${userID}") ; do
648 # note that key was found
651 ok=$(echo "$line" | cut -d: -f1)
652 sshKey=$(echo "$line" | cut -d: -f2)
654 if [ -z "$sshKey" ] ; then
658 # remove the old host key line, and note if removed
659 remove_line "$KNOWN_HOSTS" "$sshKey"
661 # if key OK, add new host line
662 if [ "$ok" -eq '0' ] ; then
663 # note that key was found ok
664 nKeysOK=$((nKeysOK+1))
667 if [ "$HASH_KNOWN_HOSTS" = 'true' ] ; then
668 # FIXME: this is really hackish cause ssh-keygen won't
669 # hash from stdin to stdout
671 ssh2known_hosts "$host" "$sshKey" > "$tmpfile"
672 ssh-keygen -H -f "$tmpfile" 2> /dev/null
673 cat "$tmpfile" >> "$KNOWN_HOSTS"
674 rm -f "$tmpfile" "${tmpfile}.old"
676 ssh2known_hosts "$host" "$sshKey" >> "$KNOWN_HOSTS"
681 # if at least one key was found...
682 if [ "$nKeys" -gt 0 ] ; then
683 # if ok keys were found, return 0
684 if [ "$nKeysOK" -gt 0 ] ; then
690 # if no keys were found, return 1
696 # update the known_hosts file for a set of hosts listed on command
698 update_known_hosts() {
705 # the number of hosts specified on command line
711 # set the trap to remove any lockfiles on exit
712 trap "lockfile-remove $KNOWN_HOSTS" EXIT
714 # create a lockfile on known_hosts
715 lockfile-create "$KNOWN_HOSTS"
717 # note pre update file checksum
718 fileCheck="$(file_hash "$KNOWN_HOSTS")"
722 process_host_known_hosts "$host"
726 nHostsOK=$((nHostsOK+1))
729 nHostsBAD=$((nHostsBAD+1))
733 # touch the lockfile, for good measure.
734 lockfile-touch --oneshot "$KNOWN_HOSTS"
737 # remove the lockfile
738 lockfile-remove "$KNOWN_HOSTS"
740 # note if the known_hosts file was updated
741 if [ "$(file_hash "$KNOWN_HOSTS")" != "$fileCheck" ] ; then
742 log info "known_hosts file updated."
745 # if an acceptable host was found, return 0
746 if [ "$nHostsOK" -gt 0 ] ; then
748 # else if no ok hosts were found...
750 # if no bad host were found then no hosts were found at all,
752 if [ "$nHostsBAD" -eq 0 ] ; then
754 # else if at least one bad host was found, return 2
761 # process hosts from a known_hosts file
762 process_known_hosts() {
765 log info "processing known_hosts file..."
767 hosts=$(meat "$KNOWN_HOSTS" | cut -d ' ' -f 1 | grep -v '^|.*$' | tr , ' ' | tr '\n' ' ')
769 if [ -z "$hosts" ] ; then
770 log error "no hosts to process."
774 # take all the hosts from the known_hosts file (first
775 # field), grep out all the hashed hosts (lines starting
777 update_known_hosts $hosts
780 # process uids for the authorized_keys file
781 process_uid_authorized_keys() {
790 log info "processing: $userID"
796 for line in $(process_user_id "$userID") ; do
797 # note that key was found
800 ok=$(echo "$line" | cut -d: -f1)
801 sshKey=$(echo "$line" | cut -d: -f2)
803 if [ -z "$sshKey" ] ; then
807 # remove the old host key line
808 remove_line "$AUTHORIZED_KEYS" "$sshKey"
810 # if key OK, add new host line
811 if [ "$ok" -eq '0' ] ; then
812 # note that key was found ok
813 nKeysOK=$((nKeysOK+1))
815 ssh2authorized_keys "$userID" "$sshKey" >> "$AUTHORIZED_KEYS"
819 # if at least one key was found...
820 if [ "$nKeys" -gt 0 ] ; then
821 # if ok keys were found, return 0
822 if [ "$nKeysOK" -gt 0 ] ; then
828 # if no keys were found, return 1
834 # update the authorized_keys files from a list of user IDs on command
836 update_authorized_keys() {
843 # the number of ids specified on command line
849 # set the trap to remove any lockfiles on exit
850 trap "lockfile-remove $AUTHORIZED_KEYS" EXIT
852 # create a lockfile on authorized_keys
853 lockfile-create "$AUTHORIZED_KEYS"
855 # note pre update file checksum
856 fileCheck="$(file_hash "$AUTHORIZED_KEYS")"
858 # remove any monkeysphere lines from authorized_keys file
859 remove_monkeysphere_lines "$AUTHORIZED_KEYS"
862 # process the user ID, change return code if key not found for
864 process_uid_authorized_keys "$userID"
872 nIDsBAD=$((nIDsBAD+1))
876 # touch the lockfile, for good measure.
877 lockfile-touch --oneshot "$AUTHORIZED_KEYS"
880 # remove the lockfile
881 lockfile-remove "$AUTHORIZED_KEYS"
883 # note if the authorized_keys file was updated
884 if [ "$(file_hash "$AUTHORIZED_KEYS")" != "$fileCheck" ] ; then
885 log info "authorized_keys file updated."
888 # if an acceptable id was found, return 0
889 if [ "$nIDsOK" -gt 0 ] ; then
891 # else if no ok ids were found...
893 # if no bad ids were found then no ids were found at all, and
895 if [ "$nIDsBAD" -eq 0 ] ; then
897 # else if at least one bad id was found, return 2
904 # process an authorized_user_ids file for authorized_keys
905 process_authorized_user_ids() {
910 authorizedUserIDs="$1"
912 log info "processing authorized_user_ids file..."
914 if ! meat "$authorizedUserIDs" > /dev/null ; then
915 log error "no user IDs to process."
921 # extract user IDs from authorized_user_ids file
923 for line in $(meat "$authorizedUserIDs") ; do
924 userIDs["$nline"]="$line"
928 update_authorized_keys "${userIDs[@]}"