3 # Shared sh functions for the monkeysphere
6 # Jameson Rollins <jrollins@fifthhorseman.net>
8 # Copyright 2008, released under the GPL, version 3 or later
10 # all-caps variables are meant to be user supplied (ie. from config
11 # file) and are considered global
13 ########################################################################
17 ETC="/etc/monkeysphere"
20 ########################################################################
23 # failure function. exits with code 255, unless specified otherwise.
29 # write output to stderr based on specified LOG_LEVEL the first
30 # parameter is the priority of the output, and everything else is what
37 # translate lowers to uppers in global log level
38 LOG_LEVEL=$(echo "$LOG_LEVEL" | tr "[:lower:]" "[:upper:]")
40 # just go ahead and return if the log level is silent
41 if [ "$LOG_LEVEL" = 'SILENT' ] ; then
45 # get priority from first parameter, translating all lower to
47 priority=$(echo "$1" | tr "[:lower:]" "[:upper:]")
50 # scan over available levels
51 # list in decreasing verbosity (all caps)
52 for level in DEBUG INFO ERROR ; do
53 # output if the log level matches, set output to true
54 # this will output for all subsequenty loops as well.
55 if [ "$LOG_LEVEL" = "$level" ] ; then
58 if [ "$priority" = "$level" -a "$output" = 'true' ] ; then
65 # cut out all comments(#) and blank lines from standard input
67 grep -v -e "^[[:space:]]*#" -e '^$' "$1"
70 # cut a specified line from standard input
72 head --line="$1" "$2" | tail -1
75 # check that characters are in a string (in an AND fashion).
76 # used for checking key capability
77 # check_capability capability a [b...]
86 if echo "$usage" | grep -q -v "$capcheck" ; then
95 md5sum "$1" 2> /dev/null
98 # convert escaped characters in pipeline from gpg output back into
100 # FIXME: undo all escape character translation in with-colons gpg
106 # convert nasty chars into gpg-friendly form in pipeline
107 # FIXME: escape everything, not just colons!
112 # prompt for GPG-formatted expiration, and emit result on stdout
113 get_gpg_expiration() {
118 if [ -z "$keyExpire" ]; then
120 Please specify how long the key should be valid.
121 0 = key does not expire
122 <n> = key expires in n days
123 <n>w = key expires in n weeks
124 <n>m = key expires in n months
125 <n>y = key expires in n years
127 while [ -z "$keyExpire" ] ; do
128 read -p "Key is valid for? (0) " keyExpire
129 if ! test_gpg_expire ${keyExpire:=0} ; then
130 echo "invalid value" >&2
134 elif ! test_gpg_expire "$keyExpire" ; then
135 failure "invalid key expiration value '$keyExpire'."
141 passphrase_prompt() {
146 if [ "$DISPLAY" ] && which "${SSH_ASKPASS:-ssh-askpass}" >/dev/null; then
147 "${SSH_ASKPASS:-ssh-askpass}" "$prompt" > "$fifo"
149 read -s -p "$prompt" PASS
150 # Uses the builtin echo, so should not put the passphrase into
151 # the process table. I think. --dkg
152 echo "$PASS" > "$fifo"
156 test_gnu_dummy_s2k_extension() {
158 # this block contains a demonstration private key that has had the
159 # primary key stripped out using the GNU S2K extension known as
160 # "gnu-dummy" (see /usr/share/doc/gnupg/DETAILS.gz). The subkey is
161 # present in cleartext, however.
163 # openpgp2ssh will be able to deal with this based on whether the
164 # local copy of GnuTLS contains read_s2k support that can handle it.
166 # read up on that here:
168 # http://lists.gnu.org/archive/html/gnutls-devel/2008-08/msg00005.html
171 -----BEGIN PGP PRIVATE KEY BLOCK-----
172 Version: GnuPG v1.4.9 (GNU/Linux)
174 lQCVBEO3YdABBACRqqEnucag4+vyZny2M67Pai5+5suIRRvY+Ly8Ms5MvgCi3EVV
175 xT05O/+0ShiRaf+QicCOFrhbU9PZzzU+seEvkeW2UCu4dQfILkmj+HBEIltGnHr3
176 G0yegHj5pnqrcezERURf2e17gGFWX91cXB9Cm721FPXczuKraphKwCA9PwARAQAB
177 /gNlAkdOVQG0OURlbW9uc3RyYXRpb24gS2V5IGZvciBTMksgR05VIGV4dGVuc2lv
178 biAxMDAxIC0tIGdudS1kdW1teYi8BBMBAgAmBQJDt2HQAhsDBQkB4TOABgsJCAcD
179 AgQVAggDBBYCAwECHgECF4AACgkQQZUwSa4UDezTOQP/TMQXUVrWzHYZGopoPZ2+
180 ZS3qddiznBHsgb7MGYg1KlTiVJSroDUBCHIUJvdQKZV9zrzrFl47D07x6hGyUPHV
181 aZXvuITW8t1o5MMHkCy3pmJ2KgfDvdUxrBvLfgPMICA4c6zA0mWquee43syEW9NY
182 g3q61iPlQwD1J1kX1wlimLCdAdgEQ7dh0AEEANAwa63zlQbuy1Meliy8otwiOa+a
183 mH6pxxUgUNggjyjO5qx+rl25mMjvGIRX4/L1QwIBXJBVi3SgvJW1COZxZqBYqj9U
184 8HVT07mWKFEDf0rZLeUE2jTm16cF9fcW4DQhW+sfYm+hi2sY3HeMuwlUBK9KHfW2
185 +bGeDzVZ4pqfUEudABEBAAEAA/0bemib+wxub9IyVFUp7nPobjQC83qxLSNzrGI/
186 RHzgu/5CQi4tfLOnwbcQsLELfker2hYnjsLrT9PURqK4F7udrWEoZ1I1LymOtLG/
187 4tNZ7Mnul3wRC2tCn7FKx8sGJwGh/3li8vZ6ALVJAyOia5TZ/buX0+QZzt6+hPKk
188 7MU1WQIA4bUBjtrsqDwro94DvPj3/jBnMZbXr6WZIItLNeVDUcM8oHL807Am97K1
189 ueO/f6v1sGAHG6lVPTmtekqPSTWBfwIA7CGFvEyvSALfB8NUa6jtk27NCiw0csql
190 kuhCmwXGMVOiryKEfegkIahf2bAd/gnWHPrpWp7bUE20v8YoW22I4wIAhnm5Wr5Q
191 Sy7EHDUxmJm5TzadFp9gq08qNzHBpXSYXXJ3JuWcL1/awUqp3tE1I6zZ0hZ38Ia6
192 SdBMN88idnhDPqPoiKUEGAECAA8FAkO3YdACGyAFCQHhM4AACgkQQZUwSa4UDezm
193 vQP/ZhK+2ly9oI2z7ZcNC/BJRch0/ybQ3haahII8pXXmOThpZohr/LUgoWgCZdXg
194 vP6yiszNk2tIs8KphCAw7Lw/qzDC2hEORjWO4f46qk73RAgSqG/GyzI4ltWiDhqn
195 vnQCFl3+QFSe4zinqykHnLwGPMXv428d/ZjkIc2ju8dRsn4=
197 -----END PGP PRIVATE KEY BLOCK-----
198 " | openpgp2ssh 4129E89D17C1D591 >/dev/null 2>/dev/null
202 # remove all lines with specified string from specified file
210 if [ -z "$file" -o -z "$string" ] ; then
214 if [ ! -e "$file" ] ; then
218 # if the string is in the file...
219 if grep -q -F "$string" "$file" 2> /dev/null ; then
220 # remove the line with the string, and return 0
221 grep -v -F "$string" "$file" | sponge "$file"
229 # remove all lines with MonkeySphere strings in file
230 remove_monkeysphere_lines() {
235 if [ -z "$file" ] ; then
239 if [ ! -e "$file" ] ; then
243 egrep -v '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$' \
244 "$file" | sponge "$file"
247 # translate ssh-style path variables %h and %u
248 translate_ssh_variables() {
255 # get the user's home directory
256 userHome=$(getent passwd "$uname" | cut -d: -f6)
258 # translate '%u' to user name
259 path=${path/\%u/"$uname"}
260 # translate '%h' to user home directory
261 path=${path/\%h/"$userHome"}
266 # test that a string to conforms to GPG's expiration format
268 echo "$1" | egrep -q "^[0-9]+[mwy]?$"
271 # check that a file is properly owned, and that all it's parent
272 # directories are not group/other writable
273 check_key_file_permissions() {
280 # function to check that an octal corresponds to writability
282 [ "$1" -eq 2 -o "$1" -eq 3 -o "$1" -eq 6 -o "$1" -eq 7 ]
288 # return 0 is path does not exist
289 [ -e "$path" ] || return 0
291 owner=$(stat --format '%U' "$path")
292 access=$(stat --format '%a' "$path")
293 gAccess=$(echo "$access" | cut -c2)
294 oAccess=$(echo "$access" | cut -c3)
297 if [ "$owner" != "$user" -a "$owner" != 'root' ] ; then
301 # check group/other writability
302 if is_write "$gAccess" || is_write "$oAccess" ; then
306 if [ "$path" = '/' ] ; then
309 check_key_file_permissions $(dirname "$path")
313 ### CONVERSION UTILITIES
315 # output the ssh key for a given key ID
321 gpg --export "$keyID" | openpgp2ssh "$keyID" 2> /dev/null
324 # output known_hosts line from ssh key
333 echo -n "$key" | tr -d '\n'
334 echo " MonkeySphere${DATE}"
337 # output authorized_keys line from ssh key
338 ssh2authorized_keys() {
345 echo -n "$key" | tr -d '\n'
346 echo " MonkeySphere${DATE} ${userID}"
349 # convert key from gpg to ssh known_hosts format
357 # NOTE: it seems that ssh-keygen -R removes all comment fields from
358 # all lines in the known_hosts file. why?
359 # NOTE: just in case, the COMMENT can be matched with the
361 # '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$'
363 gpg2ssh "$keyID" | tr -d '\n'
364 echo " MonkeySphere${DATE}"
367 # convert key from gpg to ssh authorized_keys format
368 gpg2authorized_keys() {
375 # NOTE: just in case, the COMMENT can be matched with the
377 # '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$'
378 gpg2ssh "$keyID" | tr -d '\n'
379 echo " MonkeySphere${DATE} ${userID}"
384 # retrieve all keys with given user id from keyserver
385 # FIXME: need to figure out how to retrieve all matching keys
386 # (not just first N (5 in this case))
391 if [ "$CHECK_KEYSERVER" != 'true' ] ; then
397 log info " checking keyserver $KEYSERVER... "
399 gpg --quiet --batch --with-colons \
400 --command-fd 0 --keyserver "$KEYSERVER" \
401 --search ="$userID" > /dev/null 2>&1
404 # if the user is the monkeysphere user, then update the
405 # monkeysphere user's trustdb
406 if [ $(id -un) = "$MONKEYSPHERE_USER" ] ; then
407 gpg_authentication "--check-trustdb" > /dev/null 2>&1
413 ########################################################################
414 ### PROCESSING FUNCTIONS
416 # userid and key policy checking
417 # the following checks policy on the returned keys
418 # - checks that full key has appropriate valididy (u|f)
419 # - checks key has specified capability (REQUIRED_*_KEY_CAPABILITY)
420 # - checks that requested user ID has appropriate validity
421 # (see /usr/share/doc/gnupg/DETAILS.gz)
422 # output is one line for every found key, in the following format:
426 # "flag" is an acceptability flag, 0 = ok, 1 = bad
427 # "sshKey" is the translated gpg key
429 # all log output must go to stderr, as stdout is used to pass the
430 # flag:sshKey to the calling function.
432 # expects global variable: "MODE"
435 local requiredCapability
436 local requiredPubCapability
451 # set the required key capability based on the mode
452 if [ "$MODE" = 'known_hosts' ] ; then
453 requiredCapability="$REQUIRED_HOST_KEY_CAPABILITY"
454 elif [ "$MODE" = 'authorized_keys' ] ; then
455 requiredCapability="$REQUIRED_USER_KEY_CAPABILITY"
457 requiredPubCapability=$(echo "$requiredCapability" | tr "[:lower:]" "[:upper:]")
459 # fetch the user ID if necessary/requested
460 gpg_fetch_userid "$userID"
462 # output gpg info for (exact) userid and store
463 gpgOut=$(gpg --list-key --fixed-list-mode --with-colon \
464 --with-fingerprint --with-fingerprint \
465 ="$userID" 2>/dev/null)
467 # if the gpg query return code is not 0, return 1
468 if [ "$?" -ne 0 ] ; then
469 log error " no primary keys found."
473 # loop over all lines in the gpg output and process.
474 echo "$gpgOut" | cut -d: -f1,2,5,10,12 | \
475 while IFS=: read -r type validity keyid uidfpr usage ; do
476 # process based on record type
478 'pub') # primary keys
479 # new key, wipe the slate
486 log error " primary key found: $keyid"
488 # if overall key is not valid, skip
489 if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
490 log error " - unacceptable primary key validity ($validity)."
493 # if overall key is disabled, skip
494 if check_capability "$usage" 'D' ; then
495 log error " - key disabled."
498 # if overall key capability is not ok, skip
499 if ! check_capability "$usage" $requiredPubCapability ; then
500 log error " - unacceptable primary key capability ($usage)."
504 # mark overall key as ok
507 # mark primary key as ok if capability is ok
508 if check_capability "$usage" $requiredCapability ; then
513 if [ "$lastKey" != pub ] ; then
514 log error " - got a user ID after a sub key?! user IDs should only follow primary keys!"
517 # if an acceptable user ID was already found, skip
518 if [ "$uidOK" = 'true' ] ; then
521 # if the user ID does matches...
522 if [ "$(echo "$uidfpr" | gpg_unescape)" = "$userID" ] ; then
523 # and the user ID validity is ok
524 if [ "$validity" = 'u' -o "$validity" = 'f' ] ; then
525 # mark user ID acceptable
532 # output a line for the primary key
534 if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
535 log error " * acceptable primary key."
536 if [ -z "$sshKey" ] ; then
537 log error " ! primary key could not be translated (not RSA or DSA?)."
542 log error " - unacceptable primary key."
543 if [ -z "$sshKey" ] ; then
544 log error " ! primary key could not be translated (not RSA or DSA?)."
551 # unset acceptability of last key
556 # don't bother with sub keys if the primary key is not valid
557 if [ "$keyOK" != true ] ; then
561 # don't bother with sub keys if no user ID is acceptable:
562 if [ "$uidOK" != true ] ; then
566 # if sub key validity is not ok, skip
567 if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
570 # if sub key capability is not ok, skip
571 if ! check_capability "$usage" $requiredCapability ; then
578 'fpr') # key fingerprint
579 fingerprint="$uidfpr"
581 sshKey=$(gpg2ssh "$fingerprint")
583 # if the last key was the pub key, skip
584 if [ "$lastKey" = pub ] ; then
588 # output a line for the sub key
590 if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
591 log error " * acceptable sub key."
592 if [ -z "$sshKey" ] ; then
593 log error " ! sub key could not be translated (not RSA or DSA?)."
598 log error " - unacceptable sub key."
599 if [ -z "$sshKey" ] ; then
600 log error " ! sub key could not be translated (not RSA or DSA?)."
607 done | sort -t: -k1 -n -r
608 # NOTE: this last sort is important so that the "good" keys (key
609 # flag '0') come last. This is so that they take precedence when
610 # being processed in the key files over "bad" keys (key flag '1')
613 # process a single host in the known_host file
614 process_host_known_hosts() {
624 userID="ssh://${host}"
626 log info "processing: $host"
632 for line in $(process_user_id "${userID}") ; do
633 # note that key was found
636 ok=$(echo "$line" | cut -d: -f1)
637 sshKey=$(echo "$line" | cut -d: -f2)
639 if [ -z "$sshKey" ] ; then
643 # remove the old host key line, and note if removed
644 remove_line "$KNOWN_HOSTS" "$sshKey"
646 # if key OK, add new host line
647 if [ "$ok" -eq '0' ] ; then
648 # note that key was found ok
649 nKeysOK=$((nKeysOK+1))
652 if [ "$HASH_KNOWN_HOSTS" = 'true' ] ; then
653 # FIXME: this is really hackish cause ssh-keygen won't
654 # hash from stdin to stdout
656 ssh2known_hosts "$host" "$sshKey" > "$tmpfile"
657 ssh-keygen -H -f "$tmpfile" 2> /dev/null
658 cat "$tmpfile" >> "$KNOWN_HOSTS"
659 rm -f "$tmpfile" "${tmpfile}.old"
661 ssh2known_hosts "$host" "$sshKey" >> "$KNOWN_HOSTS"
666 # if at least one key was found...
667 if [ "$nKeys" -gt 0 ] ; then
668 # if ok keys were found, return 0
669 if [ "$nKeysOK" -gt 0 ] ; then
675 # if no keys were found, return 1
681 # update the known_hosts file for a set of hosts listed on command
683 update_known_hosts() {
690 # the number of hosts specified on command line
696 # set the trap to remove any lockfiles on exit
697 trap "lockfile-remove $KNOWN_HOSTS" EXIT
699 # create a lockfile on known_hosts
700 lockfile-create "$KNOWN_HOSTS"
702 # note pre update file checksum
703 fileCheck="$(file_hash "$KNOWN_HOSTS")"
707 process_host_known_hosts "$host"
711 nHostsOK=$((nHostsOK+1))
714 nHostsBAD=$((nHostsBAD+1))
718 # touch the lockfile, for good measure.
719 lockfile-touch --oneshot "$KNOWN_HOSTS"
722 # remove the lockfile
723 lockfile-remove "$KNOWN_HOSTS"
725 # note if the known_hosts file was updated
726 if [ "$(file_hash "$KNOWN_HOSTS")" != "$fileCheck" ] ; then
727 log info "known_hosts file updated."
730 # if an acceptable host was found, return 0
731 if [ "$nHostsOK" -gt 0 ] ; then
733 # else if no ok hosts were found...
735 # if no bad host were found then no hosts were found at all,
737 if [ "$nHostsBAD" -eq 0 ] ; then
739 # else if at least one bad host was found, return 2
746 # process hosts from a known_hosts file
747 process_known_hosts() {
750 log info "processing known_hosts file..."
752 hosts=$(meat "$KNOWN_HOSTS" | cut -d ' ' -f 1 | grep -v '^|.*$' | tr , ' ' | tr '\n' ' ')
754 if [ -z "$hosts" ] ; then
755 log error "no hosts to process."
759 # take all the hosts from the known_hosts file (first
760 # field), grep out all the hashed hosts (lines starting
762 update_known_hosts $hosts
765 # process uids for the authorized_keys file
766 process_uid_authorized_keys() {
775 log info "processing: $userID"
781 for line in $(process_user_id "$userID") ; do
782 # note that key was found
785 ok=$(echo "$line" | cut -d: -f1)
786 sshKey=$(echo "$line" | cut -d: -f2)
788 if [ -z "$sshKey" ] ; then
792 # remove the old host key line
793 remove_line "$AUTHORIZED_KEYS" "$sshKey"
795 # if key OK, add new host line
796 if [ "$ok" -eq '0' ] ; then
797 # note that key was found ok
798 nKeysOK=$((nKeysOK+1))
800 ssh2authorized_keys "$userID" "$sshKey" >> "$AUTHORIZED_KEYS"
804 # if at least one key was found...
805 if [ "$nKeys" -gt 0 ] ; then
806 # if ok keys were found, return 0
807 if [ "$nKeysOK" -gt 0 ] ; then
813 # if no keys were found, return 1
819 # update the authorized_keys files from a list of user IDs on command
821 update_authorized_keys() {
828 # the number of ids specified on command line
834 # set the trap to remove any lockfiles on exit
835 trap "lockfile-remove $AUTHORIZED_KEYS" EXIT
837 # create a lockfile on authorized_keys
838 lockfile-create "$AUTHORIZED_KEYS"
840 # note pre update file checksum
841 fileCheck="$(file_hash "$AUTHORIZED_KEYS")"
843 # remove any monkeysphere lines from authorized_keys file
844 remove_monkeysphere_lines "$AUTHORIZED_KEYS"
847 # process the user ID, change return code if key not found for
849 process_uid_authorized_keys "$userID"
857 nIDsBAD=$((nIDsBAD+1))
861 # touch the lockfile, for good measure.
862 lockfile-touch --oneshot "$AUTHORIZED_KEYS"
865 # remove the lockfile
866 lockfile-remove "$AUTHORIZED_KEYS"
868 # note if the authorized_keys file was updated
869 if [ "$(file_hash "$AUTHORIZED_KEYS")" != "$fileCheck" ] ; then
870 log info "authorized_keys file updated."
873 # if an acceptable id was found, return 0
874 if [ "$nIDsOK" -gt 0 ] ; then
876 # else if no ok ids were found...
878 # if no bad ids were found then no ids were found at all, and
880 if [ "$nIDsBAD" -eq 0 ] ; then
882 # else if at least one bad id was found, return 2
889 # process an authorized_user_ids file for authorized_keys
890 process_authorized_user_ids() {
895 authorizedUserIDs="$1"
897 log info "processing authorized_user_ids file..."
899 if ! meat "$authorizedUserIDs" > /dev/null ; then
900 log error "no user IDs to process."
906 # extract user IDs from authorized_user_ids file
908 for line in $(meat "$authorizedUserIDs") ; do
909 userIDs["$nline"]="$line"
913 update_authorized_keys "${userIDs[@]}"