home *** CD-ROM | disk | FTP | other *** search
/ Clickx 115 / Clickx 115.iso / software / tools / windows / tails-i386-0.16.iso / live / filesystem.squashfs / usr / share / monkeysphere / common < prev    next >
Encoding:
Text File  |  2011-03-24  |  25.8 KB  |  975 lines

  1. # -*-shell-script-*-
  2. # This should be sourced by bash (though we welcome changes to make it POSIX sh compliant)
  3.  
  4. # Shared sh functions for the monkeysphere
  5. #
  6. # Written by
  7. # Jameson Rollins <jrollins@finestructure.net>
  8. # Jamie McClelland <jm@mayfirst.org>
  9. # Daniel Kahn Gillmor <dkg@fifthhorseman.net>
  10. #
  11. # Copyright 2008-2009, released under the GPL, version 3 or later
  12.  
  13. # all-caps variables are meant to be user supplied (ie. from config
  14. # file) and are considered global
  15.  
  16. ########################################################################
  17. ### UTILITY FUNCTIONS
  18.  
  19. # output version info
  20. version() {
  21.     cat "${SYSSHAREDIR}/VERSION"
  22. }
  23.  
  24. # failure function.  exits with code 255, unless specified otherwise.
  25. failure() {
  26.     [ "$1" ] && echo "$1" >&2
  27.     exit ${2:-'255'}
  28. }
  29.  
  30. # write output to stderr based on specified LOG_LEVEL the first
  31. # parameter is the priority of the output, and everything else is what
  32. # is echoed to stderr.  If there is nothing else, then output comes
  33. # from stdin, and is not prefaced by log prefix.
  34. log() {
  35.     local priority
  36.     local level
  37.     local output
  38.     local alllevels
  39.     local found=
  40.  
  41.     # don't include SILENT in alllevels: it's handled separately
  42.     # list in decreasing verbosity (all caps).
  43.     # separate with $IFS explicitly, since we do some fancy footwork
  44.     # elsewhere.
  45.     alllevels="DEBUG${IFS}VERBOSE${IFS}INFO${IFS}ERROR"
  46.  
  47.     # translate lowers to uppers in global log level
  48.     LOG_LEVEL=$(echo "$LOG_LEVEL" | tr "[:lower:]" "[:upper:]")
  49.  
  50.     # just go ahead and return if the log level is silent
  51.     if [ "$LOG_LEVEL" = 'SILENT' ] ; then
  52.     return
  53.     fi
  54.  
  55.     for level in $alllevels ; do 
  56.     if [ "$LOG_LEVEL" = "$level" ] ; then
  57.         found=true
  58.     fi
  59.     done
  60.     if [ -z "$found" ] ; then
  61.     # default to INFO:
  62.     LOG_LEVEL=INFO
  63.     fi
  64.  
  65.     # get priority from first parameter, translating all lower to
  66.     # uppers
  67.     priority=$(echo "$1" | tr "[:lower:]" "[:upper:]")
  68.     shift
  69.  
  70.     # scan over available levels
  71.     for level in $alllevels ; do
  72.     # output if the log level matches, set output to true
  73.     # this will output for all subsequent loops as well.
  74.     if [ "$LOG_LEVEL" = "$level" ] ; then
  75.         output=true
  76.     fi
  77.     if [ "$priority" = "$level" -a "$output" = 'true' ] ; then
  78.         if [ "$1" ] ; then
  79.         echo "$@"
  80.         else
  81.         cat
  82.         fi | sed 's/^/'"${LOG_PREFIX}"'/' >&2
  83.     fi
  84.     done
  85. }
  86.  
  87. # run command as monkeysphere user
  88. su_monkeysphere_user() {
  89.     # our main goal here is to run the given command as the the
  90.     # monkeysphere user, but without prompting for any sort of
  91.     # authentication.  If this is not possible, we should just fail.
  92.  
  93.     # FIXME: our current implementation is overly restrictive, because
  94.     # there may be some su PAM configurations that would allow su
  95.     # "$MONKEYSPHERE_USER" -c "$@" to Just Work without prompting,
  96.     # allowing specific users to invoke commands which make use of
  97.     # this user.
  98.  
  99.     # chpst (from runit) would be nice to use, but we don't want to
  100.     # introduce an extra dependency just for this.  This may be a
  101.     # candidate for re-factoring if we switch implementation languages.
  102.  
  103.     case $(id -un) in
  104.     # if monkeysphere user, run the command under bash
  105.     "$MONKEYSPHERE_USER")
  106.         bash -c "$*"
  107.         ;;
  108.  
  109.          # if root, su command as monkeysphere user
  110.     'root')
  111.         su "$MONKEYSPHERE_USER" -c "$*"
  112.         ;;
  113.  
  114.     # otherwise, fail
  115.     *)
  116.         log error "non-privileged user."
  117.         ;;
  118.     esac
  119. }
  120.  
  121. # cut out all comments(#) and blank lines from standard input
  122. meat() {
  123.     grep -v -e "^[[:space:]]*#" -e '^$' "$1"
  124. }
  125.  
  126. # cut a specified line from standard input
  127. cutline() {
  128.     head --line="$1" "$2" | tail -1
  129. }
  130.  
  131. # make a temporary directory
  132. msmktempdir() {
  133.     mktemp -d ${TMPDIR:-/tmp}/monkeysphere.XXXXXXXXXX
  134. }
  135.  
  136. # make a temporary file
  137. msmktempfile() {
  138.     mktemp ${TMPDIR:-/tmp}/monkeysphere.XXXXXXXXXX
  139. }
  140.  
  141. # this is a wrapper for doing lock functions.
  142. #
  143. # it lets us depend on either lockfile-progs (preferred) or procmail's
  144. # lockfile, and should
  145. lock() {
  146.     local use_lockfileprogs=true
  147.     local action="$1"
  148.     local file="$2"
  149.  
  150.     if ! ( type lockfile-create &>/dev/null ) ; then
  151.     if ! ( type lockfile &>/dev/null ); then
  152.         failure "Neither lockfile-create nor lockfile are in the path!"
  153.     fi
  154.     use_lockfileprogs=
  155.     fi
  156.     
  157.     case "$action" in
  158.     create)
  159.         if [ -n "$use_lockfileprogs" ] ; then
  160.         lockfile-create "$file" || failure "unable to lock '$file'"
  161.         else
  162.         lockfile -r 20 "${file}.lock" || failure "unable to lock '$file'"
  163.         fi
  164.         log debug "lock created on '$file'."
  165.         ;;
  166.     touch)    
  167.         if [ -n "$use_lockfileprogs" ] ; then
  168.         lockfile-touch --oneshot "$file"
  169.         else
  170.         : Nothing to do here
  171.         fi
  172.         log debug "lock touched on '$file'."
  173.         ;;
  174.     remove)
  175.         if [ -n "$use_lockfileprogs" ] ; then
  176.         lockfile-remove "$file"
  177.         else
  178.         rm -f "${file}.lock"
  179.         fi
  180.         log debug "lock removed on '$file'."
  181.         ;;
  182.     *)
  183.         failure "bad argument for lock subfunction '$action'"
  184.     esac
  185. }
  186.  
  187.  
  188. # for portability, between gnu date and BSD date.
  189. # arguments should be:  number longunits format
  190.  
  191. # e.g. advance_date 20 seconds +%F
  192. advance_date() {
  193.     local gnutry
  194.     local number="$1"
  195.     local longunits="$2"
  196.     local format="$3"
  197.     local shortunits
  198.  
  199.     # try things the GNU way first 
  200.     if date -d "$number $longunits" "$format" &>/dev/null; then
  201.     date -d "$number $longunits" "$format"
  202.     else
  203.     # otherwise, convert to (a limited version of) BSD date syntax:
  204.     case "$longunits" in
  205.         years)
  206.         shortunits=y
  207.         ;;
  208.         months)
  209.         shortunits=m
  210.         ;;
  211.         weeks)
  212.         shortunits=w
  213.         ;;
  214.         days)
  215.         shortunits=d
  216.         ;;
  217.         hours)
  218.         shortunits=H
  219.         ;;
  220.         minutes)
  221.         shortunits=M
  222.         ;;
  223.         seconds)
  224.         shortunits=S
  225.         ;;
  226.         *)
  227.         # this is a longshot, and will likely fail; oh well.
  228.         shortunits="$longunits"
  229.     esac
  230.     date "-v+${number}${shortunits}" "$format"
  231.     fi
  232. }
  233.  
  234.  
  235. # check that characters are in a string (in an AND fashion).
  236. # used for checking key capability
  237. # check_capability capability a [b...]
  238. check_capability() {
  239.     local usage
  240.     local capcheck
  241.  
  242.     usage="$1"
  243.     shift 1
  244.  
  245.     for capcheck ; do
  246.     if echo "$usage" | grep -q -v "$capcheck" ; then
  247.         return 1
  248.     fi
  249.     done
  250.     return 0
  251. }
  252.  
  253. # hash of a file
  254. file_hash() {
  255.     if type md5sum &>/dev/null ; then
  256.     md5sum "$1"
  257.     elif type md5 &>/dev/null ; then
  258.     md5 "$1"
  259.     else
  260.     failure "Neither md5sum nor md5 are in the path!"
  261.     fi
  262. }
  263.  
  264. # convert escaped characters in pipeline from gpg output back into
  265. # original character
  266. # FIXME: undo all escape character translation in with-colons gpg
  267. # output
  268. gpg_unescape() {
  269.     sed 's/\\x3a/:/g'
  270. }
  271.  
  272. # convert nasty chars into gpg-friendly form in pipeline
  273. # FIXME: escape everything, not just colons!
  274. gpg_escape() {
  275.     sed 's/:/\\x3a/g'
  276. }
  277.  
  278. # prompt for GPG-formatted expiration, and emit result on stdout
  279. get_gpg_expiration() {
  280.     local keyExpire
  281.  
  282.     keyExpire="$1"
  283.  
  284.     if [ -z "$keyExpire" -a "$PROMPT" != 'false' ]; then
  285.     cat >&2 <<EOF
  286. Please specify how long the key should be valid.
  287.          0 = key does not expire
  288.       <n>  = key expires in n days
  289.       <n>w = key expires in n weeks
  290.       <n>m = key expires in n months
  291.       <n>y = key expires in n years
  292. EOF
  293.     while [ -z "$keyExpire" ] ; do
  294.         printf "Key is valid for? (0) " >&2
  295.         read keyExpire
  296.         if ! test_gpg_expire ${keyExpire:=0} ; then
  297.         echo "invalid value" >&2
  298.         unset keyExpire
  299.         fi
  300.     done
  301.     elif ! test_gpg_expire "$keyExpire" ; then
  302.     failure "invalid key expiration value '$keyExpire'."
  303.     fi
  304.     
  305.     echo "$keyExpire"
  306. }
  307.  
  308. passphrase_prompt() {
  309.     local prompt="$1"
  310.     local fifo="$2"
  311.     local PASS
  312.  
  313.     if [ "$DISPLAY" ] && type "${SSH_ASKPASS:-ssh-askpass}" >/dev/null 2>/dev/null; then
  314.     printf 'Launching "%s"\n' "${SSH_ASKPASS:-ssh-askpass}" | log info
  315.     printf '(with prompt "%s")\n' "$prompt" | log debug
  316.     "${SSH_ASKPASS:-ssh-askpass}" "$prompt" > "$fifo"
  317.     else
  318.     read -s -p "$prompt" PASS
  319.     # Uses the builtin echo, so should not put the passphrase into
  320.     # the process table.  I think. --dkg
  321.     echo "$PASS" > "$fifo"
  322.     fi
  323. }
  324.  
  325. # remove all lines with specified string from specified file
  326. remove_line() {
  327.     local file
  328.     local lines
  329.     local tempfile
  330.  
  331.     file="$1"
  332.     shift
  333.  
  334.     if [ ! -e "$file" ] ; then
  335.     return 1
  336.     fi
  337.  
  338.     if (($# == 1)) ; then
  339.     lines=$(grep -F "$1" "$file") || true
  340.     else
  341.     lines=$(grep -F "$1" "$file" | grep -F "$2") || true
  342.     fi
  343.  
  344.     # if the string was found, remove it
  345.     if [ "$lines" ] ; then
  346.     log debug "removing matching key lines..."
  347.     tempfile=$(mktemp "${file}.XXXXXXX") || \
  348.         failure "Unable to make temp file '${file}.XXXXXXX'"
  349.     grep -v -x -F "$lines" "$file" >"$tempfile" || :
  350.     mv -f "$tempfile" "$file"
  351.     fi
  352. }
  353.  
  354. # remove all lines with MonkeySphere strings from stdin
  355. remove_monkeysphere_lines() {
  356.     egrep -v ' MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2} '
  357. }
  358.  
  359. # translate ssh-style path variables %h and %u
  360. translate_ssh_variables() {
  361.     local uname
  362.     local home
  363.  
  364.     uname="$1"
  365.     path="$2"
  366.  
  367.     # get the user's home directory
  368.     userHome=$(get_homedir "$uname")
  369.  
  370.     # translate '%u' to user name
  371.     path=${path/\%u/"$uname"}
  372.     # translate '%h' to user home directory
  373.     path=${path/\%h/"$userHome"}
  374.  
  375.     echo "$path"
  376. }
  377.  
  378. # test that a string to conforms to GPG's expiration format
  379. test_gpg_expire() {
  380.     echo "$1" | egrep -q "^[0-9]+[mwy]?$"
  381. }
  382.  
  383. # touch a key file if it doesn't exist, including creating needed
  384. # directories with correct permissions
  385. touch_key_file_or_fail() {
  386.     local keyFile="$1"
  387.     local newUmask
  388.  
  389.     if [ ! -f "$keyFile" ]; then
  390.     # make sure to create files and directories with the
  391.     # appropriate write bits turned off:
  392.     newUmask=$(printf "%04o" $(( 0$(umask) | 0022 )) )
  393.     [ -d $(dirname "$keyFile") ] \
  394.         || (umask "$newUmask" && mkdir -p -m 0700 $(dirname "$keyFile") ) \
  395.         || failure "Could not create path to $keyFile"
  396.     # make sure to create this file with the appropriate bits turned off:
  397.     (umask "$newUmask" && touch "$keyFile") \
  398.         || failure "Unable to create $keyFile"
  399.     fi
  400. }
  401.  
  402. # check that a file is properly owned, and that all it's parent
  403. # directories are not group/other writable
  404. check_key_file_permissions() {
  405.     local uname
  406.     local path
  407.  
  408.     uname="$1"
  409.     path="$2"
  410.  
  411.     if [ "$STRICT_MODES" = 'false' ] ; then
  412.     log debug "skipping path permission check for '$path' because STRICT_MODES is false..."
  413.     return 0
  414.     fi
  415.     log debug "checking path permission '$path'..."
  416.     "${SYSSHAREDIR}/checkperms" "$uname" "$path"
  417. }
  418.  
  419. # return a list of all users on the system
  420. list_users() {
  421.     if type getent &>/dev/null ; then
  422.     # for linux and FreeBSD systems
  423.     getent passwd | cut -d: -f1
  424.     elif type dscl &>/dev/null ; then
  425.     # for Darwin systems
  426.     dscl localhost -list /Search/Users
  427.     else
  428.     failure "Neither getent or dscl is in the path!  Could not determine list of users."
  429.     fi
  430. }
  431.  
  432. # take one argument, a service name.  in response, print a series of
  433. # lines, each with a unique numeric port number that might be
  434. # associated with that service name.  (e.g. in: "https", out: "443")
  435. # if nothing is found, print nothing, and return 0.
  436. # return 1 if there was an error in the search somehow
  437. get_port_for_service() {
  438.  
  439.     [[ "$1" =~ ^[a-z0-9]([a-z0-9-]*[a-z0-9])?$ ]] || \
  440.         failure $(printf "This is not a valid service name: '%s'" "$1")
  441.     if type getent &>/dev/null ; then
  442.         # for linux and FreeBSD systems (getent returns 2 if not found, 0 on success, 1 or 3 on various failures)
  443.         (getent services "$service" || if [ "$?" -eq 2 ] ; then true ; else false; fi) | awk '{ print $2 }' | cut -f1 -d/ | sort -u
  444.     elif [ -r /etc/services ] ; then
  445.         # fall back to /etc/services for systems that don't have getent (MacOS?)
  446.         # FIXME: doesn't handle aliases like "null" (or "http"?), which don't show up at the beginning of the line.
  447.         awk $(printf '/^%s[[:space:]]/{ print $2 }' "$1") /etc/services | cut -f1 -d/ | sort -u
  448.     else
  449.         return 1
  450.     fi
  451. }
  452.  
  453. # return the path to the home directory of a user
  454. get_homedir() {
  455.     local uname=${1:-`whoami`}
  456.     eval "echo ~${uname}"
  457. }
  458.  
  459. # return the primary group of a user
  460. get_primary_group() {
  461.     local uname=${1:-`whoami`}
  462.     groups "$uname" | sed 's/^..* : //' | awk '{ print $1 }'
  463. }
  464.  
  465. ### CONVERSION UTILITIES
  466.  
  467. # output the ssh key for a given key ID
  468. gpg2ssh() {
  469.     local keyID
  470.     
  471.     keyID="$1"
  472.  
  473.     gpg --export --no-armor "$keyID" | openpgp2ssh "$keyID" 2>/dev/null
  474. }
  475.  
  476. # output known_hosts line from ssh key
  477. ssh2known_hosts() {
  478.     local host
  479.     local port
  480.     local key
  481.  
  482.     # FIXME this does not properly deal with IPv6 hosts using the
  483.     # standard port (because it's unclear whether their final
  484.     # colon-delimited address section is a port number or an address
  485.     # string)
  486.     host=${1%:*}
  487.     port=${1##*:}
  488.     key="$2"
  489.  
  490.     # specify the host and port properly for new ssh known_hosts
  491.     # format
  492.     if [ "$port" != "$host" ] ; then
  493.     host="[${host}]:${port}"
  494.     fi
  495.  
  496.     # hash if specified
  497.     if [ "$HASH_KNOWN_HOSTS" = 'true' ] ; then
  498.     if (type ssh-keygen >/dev/null) ; then
  499.         log verbose "hashing known_hosts line"
  500.         # FIXME: this is really hackish cause
  501.         # ssh-keygen won't hash from stdin to
  502.         # stdout
  503.         tmpfile=$(mktemp ${TMPDIR:-/tmp}/tmp.XXXXXXXXXX)
  504.         printf "%s %s MonkeySphere%s\n" "$host" "$key" "$DATE" \
  505.         > "$tmpfile"
  506.         ssh-keygen -H -f "$tmpfile" 2>/dev/null
  507.         if [[ "$keyFile" == '-' ]] ; then
  508.         cat "$tmpfile"
  509.         else
  510.         cat "$tmpfile" >> "$keyFile"
  511.         fi
  512.         rm -f "$tmpfile" "${tmpfile}.old"
  513.         # FIXME: we could do this without needing ssh-keygen.
  514.         # hashed known_hosts looks like: |1|X|Y where 1 means SHA1
  515.         # (nothing else is defined in openssh sources), X is the
  516.         # salt (same length as the digest output), base64-encoded,
  517.         # and Y is the digested hostname (also base64-encoded).
  518.         # see hostfile.{c,h} in openssh sources.
  519.     else
  520.         log error "Cannot hash known_hosts line as requested."
  521.     fi
  522.     else
  523.     printf "%s %s MonkeySphere%s\n" "$host" "$key" "$DATE"
  524.     fi
  525. }
  526.  
  527. # output authorized_keys line from ssh key
  528. ssh2authorized_keys() {
  529.     local userID="$1"
  530.     local key="$2"
  531.  
  532.     if [[ "$AUTHORIZED_KEYS_OPTIONS" ]]; then
  533.         printf "%s %s MonkeySphere%s %s\n" "$AUTHORIZED_KEYS_OPTIONS" "$key" "$DATE" "$userID"
  534.     else
  535.     printf "%s MonkeySphere%s %s\n" "$key" "$DATE" "$userID"
  536.     fi
  537. }
  538.  
  539. # convert key from gpg to ssh known_hosts format
  540. gpg2known_hosts() {
  541.     local host
  542.     local keyID
  543.     local key
  544.  
  545.     host="$1"
  546.     keyID="$2"
  547.  
  548.     key=$(gpg2ssh "$keyID")
  549.  
  550.     # NOTE: it seems that ssh-keygen -R removes all comment fields from
  551.     # all lines in the known_hosts file.  why?
  552.     # NOTE: just in case, the COMMENT can be matched with the
  553.     # following regexp:
  554.     # '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$'
  555.     printf "%s %s MonkeySphere%s\n" "$host" "$key" "$DATE"
  556. }
  557.  
  558. # convert key from gpg to ssh authorized_keys format
  559. gpg2authorized_keys() {
  560.     local userID
  561.     local keyID
  562.     local key
  563.  
  564.     userID="$1"
  565.     keyID="$2"
  566.  
  567.     key=$(gpg2ssh "$keyID")
  568.  
  569.     # NOTE: just in case, the COMMENT can be matched with the
  570.     # following regexp:
  571.     # '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$'
  572.     printf "%s MonkeySphere%s %s\n" "$key" "$DATE" "$userID"
  573. }
  574.  
  575. ### GPG UTILITIES
  576.  
  577. # script to determine if gpg version is equal to or greater than specified version
  578. is_gpg_version_greater_equal() {
  579.     local gpgVersion=$(gpg --version | head -1 | awk '{ print $3 }')
  580.     local latest=$(printf '%s\n%s\n' "$1" "$gpgVersion" \
  581.     | tr '.' ' ' | sort -g -k1 -k2 -k3 \
  582.     | tail -1 | tr ' ' '.')
  583.     [[ "$gpgVersion" == "$latest" ]]
  584. }
  585.  
  586. # retrieve all keys with given user id from keyserver
  587. # FIXME: need to figure out how to retrieve all matching keys
  588. # (not just first N (5 in this case))
  589. gpg_fetch_userid() {
  590.     local returnCode=0
  591.     local userID
  592.  
  593.     if [ "$CHECK_KEYSERVER" != 'true' ] ; then
  594.     return 0
  595.     fi
  596.  
  597.     userID="$1"
  598.  
  599.     log verbose " checking keyserver $KEYSERVER... "
  600.     echo 1,2,3,4,5 | \
  601.     gpg --quiet --batch --with-colons \
  602.     --command-fd 0 --keyserver "$KEYSERVER" \
  603.     --search ="$userID" &>/dev/null
  604.     returnCode="$?"
  605.  
  606.     if [ "$returnCode" != 0 ] ; then
  607.         log error "Failure ($returnCode) searching keyserver $KEYSERVER for user id '$userID'"
  608.     fi
  609.  
  610.     return "$returnCode"
  611. }
  612.  
  613. ########################################################################
  614. ### PROCESSING FUNCTIONS
  615.  
  616. # userid and key policy checking
  617. # the following checks policy on the returned keys
  618. # - checks that full key has appropriate valididy (u|f)
  619. # - checks key has specified capability (REQUIRED_KEY_CAPABILITY)
  620. # - checks that requested user ID has appropriate validity
  621. # (see /usr/share/doc/gnupg/DETAILS.gz)
  622. # output is one line for every found key, in the following format:
  623. #
  624. # flag:sshKey
  625. #
  626. # "flag" is an acceptability flag, 0 = ok, 1 = bad
  627. # "sshKey" is the relevant OpenPGP key, in the form accepted by OpenSSH
  628. #
  629. # all log output must go to stderr, as stdout is used to pass the
  630. # flag:sshKey to the calling function.
  631. process_user_id() {
  632.     local returnCode=0
  633.     local userID="$1"
  634.     local requiredCapability
  635.     local requiredPubCapability
  636.     local gpgOut
  637.     local type
  638.     local validity
  639.     local keyid
  640.     local uidfpr
  641.     local usage
  642.     local keyOK
  643.     local uidOK
  644.     local lastKey
  645.     local lastKeyOK
  646.     local fingerprint
  647.  
  648.     # set the required key capability based on the mode
  649.     requiredCapability=${REQUIRED_KEY_CAPABILITY:="a"}
  650.     requiredPubCapability=$(echo "$requiredCapability" | tr "[:lower:]" "[:upper:]")
  651.  
  652.     # fetch the user ID if necessary/requested
  653.     gpg_fetch_userid "$userID"
  654.  
  655.     # output gpg info for (exact) userid and store
  656.     gpgOut=$(gpg --list-key --fixed-list-mode --with-colons \
  657.     --with-fingerprint --with-fingerprint \
  658.     ="$userID" 2>/dev/null) || returnCode="$?"
  659.  
  660.     # if the gpg query return code is not 0, return 1
  661.     if [ "$returnCode" -ne 0 ] ; then
  662.         log verbose " no primary keys found."
  663.         return 1
  664.     fi
  665.  
  666.     # loop over all lines in the gpg output and process.
  667.     echo "$gpgOut" | cut -d: -f1,2,5,10,12 | \
  668.     while IFS=: read -r type validity keyid uidfpr usage ; do
  669.     # process based on record type
  670.     case $type in
  671.         'pub') # primary keys
  672.         # new key, wipe the slate
  673.         keyOK=
  674.         uidOK=
  675.         lastKey=pub
  676.         lastKeyOK=
  677.         fingerprint=
  678.  
  679.         log verbose " primary key found: $keyid"
  680.  
  681.         # if overall key is not valid, skip
  682.         if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
  683.             log debug "  - unacceptable primary key validity ($validity)."
  684.             continue
  685.         fi
  686.         # if overall key is disabled, skip
  687.         if check_capability "$usage" 'D' ; then
  688.             log debug "  - key disabled."
  689.             continue
  690.         fi
  691.         # if overall key capability is not ok, skip
  692.         if ! check_capability "$usage" $requiredPubCapability ; then
  693.             log debug "  - unacceptable primary key capability ($usage)."
  694.             continue
  695.         fi
  696.  
  697.         # mark overall key as ok
  698.         keyOK=true
  699.  
  700.         # mark primary key as ok if capability is ok
  701.         if check_capability "$usage" $requiredCapability ; then
  702.             lastKeyOK=true
  703.         fi
  704.         ;;
  705.         'uid') # user ids
  706.         if [ "$lastKey" != pub ] ; then
  707.             log verbose " ! got a user ID after a sub key?!  user IDs should only follow primary keys!"
  708.             continue
  709.         fi
  710.         # if an acceptable user ID was already found, skip
  711.         if [ "$uidOK" = 'true' ] ; then
  712.             continue
  713.         fi
  714.         # if the user ID does matches...
  715.         if [ "$(echo "$uidfpr" | gpg_unescape)" = "$userID" ] ; then
  716.             # and the user ID validity is ok
  717.             if [ "$validity" = 'u' -o "$validity" = 'f' ] ; then
  718.             # mark user ID acceptable
  719.             uidOK=true
  720.             else
  721.             log debug "  - unacceptable user ID validity ($validity)."
  722.             fi
  723.         else
  724.             continue
  725.         fi
  726.  
  727.         # output a line for the primary key
  728.         # 0 = ok, 1 = bad
  729.         if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
  730.             log verbose "  * acceptable primary key."
  731.             if [ -z "$sshKey" ] ; then
  732.             log verbose "    ! primary key could not be translated (not RSA?)."
  733.             else
  734.             echo "0:${sshKey}"
  735.             fi
  736.         else
  737.             log debug "  - unacceptable primary key."
  738.             if [ -z "$sshKey" ] ; then
  739.             log debug "    ! primary key could not be translated (not RSA?)."
  740.             else
  741.             echo "1:${sshKey}"
  742.             fi
  743.         fi
  744.         ;;
  745.         'sub') # sub keys
  746.         # unset acceptability of last key
  747.         lastKey=sub
  748.         lastKeyOK=
  749.         fingerprint=
  750.         
  751.         # don't bother with sub keys if the primary key is not valid
  752.         if [ "$keyOK" != true ] ; then
  753.             continue
  754.         fi
  755.  
  756.         # don't bother with sub keys if no user ID is acceptable:
  757.         if [ "$uidOK" != true ] ; then
  758.             continue
  759.         fi
  760.         
  761.         # if sub key validity is not ok, skip
  762.         if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
  763.             log debug "  - unacceptable sub key validity ($validity)."
  764.             continue
  765.         fi
  766.         # if sub key capability is not ok, skip
  767.         if ! check_capability "$usage" $requiredCapability ; then
  768.             log debug "  - unacceptable sub key capability ($usage)."
  769.             continue
  770.         fi
  771.  
  772.         # mark sub key as ok
  773.         lastKeyOK=true
  774.         ;;
  775.         'fpr') # key fingerprint
  776.         fingerprint="$uidfpr"
  777.  
  778.         sshKey=$(gpg2ssh "$fingerprint")
  779.  
  780.         # if the last key was the pub key, skip
  781.         if [ "$lastKey" = pub ] ; then
  782.             continue
  783.         fi
  784.  
  785.         # output a line for the sub key
  786.         # 0 = ok, 1 = bad
  787.         if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
  788.             log verbose "  * acceptable sub key."
  789.             if [ -z "$sshKey" ] ; then
  790.             log error "    ! sub key could not be translated (not RSA?)."
  791.             else
  792.             echo "0:${sshKey}"
  793.             fi
  794.         else
  795.             log debug "  - unacceptable sub key."
  796.             if [ -z "$sshKey" ] ; then
  797.             log debug "    ! sub key could not be translated (not RSA?)."
  798.             else
  799.             echo "1:${sshKey}"
  800.             fi
  801.         fi
  802.         ;;
  803.     esac
  804.     done | sort -t: -k1 -n -r
  805.     # NOTE: this last sort is important so that the "good" keys (key
  806.     # flag '0') come last.  This is so that they take precedence when
  807.     # being processed in the key files over "bad" keys (key flag '1')
  808. }
  809.  
  810. process_keys_for_file() {
  811.     local keyFile="$1"
  812.     local userID="$2"
  813.     local host
  814.     local ok
  815.     local sshKey
  816.     local keyLine
  817.  
  818.     log verbose "processing: $userID"
  819.     log debug "key file: $keyFile"
  820.  
  821.     IFS=$'\n'
  822.     for line in $(process_user_id "$userID") ; do
  823.     ok=${line%%:*}
  824.     sshKey=${line#*:}
  825.  
  826.         if [ -z "$sshKey" ] ; then
  827.             continue
  828.         fi
  829.  
  830.     # remove the old key line
  831.     if [[ "$keyFile" != '-' ]] ; then
  832.         case "$FILE_TYPE" in
  833.         ('authorized_keys')
  834.             remove_line "$keyFile" "$sshKey"
  835.             ;;
  836.         ('known_hosts')
  837.             host=${userID#ssh://}
  838.             remove_line "$keyFile" "$host" "$sshKey"
  839.             ;;
  840.         esac
  841.     fi
  842.  
  843.     ((++KEYS_PROCESSED))
  844.  
  845.     # if key OK, add new key line
  846.     if [ "$ok" -eq '0' ] ; then
  847.         case "$FILE_TYPE" in
  848.         ('raw')
  849.             keyLine="$sshKey"
  850.             ;;
  851.         ('authorized_keys')
  852.             keyLine=$(ssh2authorized_keys "$userID" "$sshKey")
  853.             ;;
  854.         ('known_hosts')
  855.             host=${userID#ssh://}
  856.             keyLine=$(ssh2known_hosts "$host" "$sshKey")
  857.             ;;
  858.         esac
  859.  
  860.         echo "key line: $keyLine" | log debug
  861.         if [[ "$keyFile" == '-' ]] ; then
  862.         echo "$keyLine"
  863.         else
  864.         log debug "adding key line to file..."
  865.         echo "$keyLine" >>"$keyFile"
  866.         fi
  867.  
  868.         ((++KEYS_VALID))
  869.     fi
  870.     done
  871.  
  872.     log debug "KEYS_PROCESSED=$KEYS_PROCESSED"
  873.     log debug "KEYS_VALID=$KEYS_VALID"
  874. }
  875.  
  876. # process an authorized_user_ids file on stdin for authorized_keys
  877. process_authorized_user_ids() {
  878.     local authorizedKeys="$1"
  879.     declare -i nline=0
  880.     local line
  881.     declare -a userIDs
  882.     declare -a koptions
  883.  
  884.     # extract user IDs from authorized_user_ids file
  885.     IFS=$'\n'
  886.     while read line ; do
  887.     case "$line" in
  888.         ("#"*)
  889.         continue
  890.         ;;
  891.         (" "*|$'\t'*)
  892.         if [[ -z ${koptions[${nline}]} ]]; then
  893.                 koptions[${nline}]=$(echo $line | sed 's/^[     ]*//;s/[     ]$//;')
  894.         else
  895.                 koptions[${nline}]="${koptions[${nline}]},$(echo $line | sed 's/^[     ]*//;s/[     ]$//;')"
  896.         fi
  897.         ;;
  898.             (*)
  899.         ((++nline))
  900.         userIDs[${nline}]="$line"
  901.         unset koptions[${nline}] || true
  902.         ;;
  903.     esac
  904.     done
  905.  
  906.     for i in $(seq 1 $nline); do
  907.     AUTHORIZED_KEYS_OPTIONS="${koptions[$i]}" FILE_TYPE='authorized_keys' process_keys_for_file "$authorizedKeys" "${userIDs[$i]}" || returnCode="$?"
  908.     done
  909. }
  910.  
  911. # takes a gpg key or keys on stdin, and outputs a list of
  912. # fingerprints, one per line:
  913. list_primary_fingerprints() {
  914.     local fake=$(msmktempdir)
  915.     trap "rm -rf $fake" EXIT
  916.     GNUPGHOME="$fake" gpg --no-tty --quiet --import --ignore-time-conflict 2>/dev/null
  917.     GNUPGHOME="$fake" gpg --with-colons --fingerprint --list-keys | \
  918.     awk -F: '/^fpr:/{ print $10 }'
  919.     trap - EXIT
  920.     rm -rf "$fake"
  921. }
  922.  
  923. # takes an OpenPGP key or set of keys on stdin, a fingerprint or other
  924. # key identifier as $1, and outputs the gpg-formatted information for
  925. # the requested keys from the material on stdin
  926. get_cert_info() {
  927.     local fake=$(msmktempdir)
  928.     trap "rm -rf $fake" EXIT
  929.     GNUPGHOME="$fake" gpg --no-tty --quiet --import --ignore-time-conflict 2>/dev/null
  930.     GNUPGHOME="$fake" gpg --with-colons --fingerprint --fixed-list-mode --list-keys "$1"
  931.     trap - EXIT
  932.     rm -rf "$fake"
  933. }
  934.  
  935.  
  936. check_cruft_file() {
  937.     local loc="$1"
  938.     local version="$2"
  939.     
  940.     if [ -e "$loc" ] ; then
  941.     printf "! The file '%s' is no longer used by\n  monkeysphere (as of version %s), and can be removed.\n\n" "$loc" "$version" | log info
  942.     fi
  943. }
  944.  
  945. check_upgrade_dir() {
  946.     local loc="$1"
  947.     local version="$2"
  948.  
  949.     if [ -d "$loc" ] ; then
  950.     printf "The presence of directory '%s' indicates that you have\nnot yet completed a monkeysphere upgrade.\nYou should probably run the following script:\n  %s/transitions/%s\n\n" "$loc" "$SYSSHAREDIR" "$version" | log info
  951.     fi
  952. }
  953.  
  954. ## look for cruft from old versions of the monkeysphere, and notice if
  955. ## upgrades have not been run:
  956. report_cruft() {
  957.     check_upgrade_dir "${SYSCONFIGDIR}/gnupg-host" 0.23
  958.     check_upgrade_dir "${SYSCONFIGDIR}/gnupg-authentication" 0.23
  959.  
  960.     check_cruft_file "${SYSCONFIGDIR}/gnupg-authentication.conf" 0.23
  961.     check_cruft_file "${SYSCONFIGDIR}/gnupg-host.conf" 0.23
  962.  
  963.     local found=
  964.     for foo in "${SYSDATADIR}/backup-from-"*"-transition"  ; do
  965.     if [ -d "$foo" ] ; then
  966.         printf "! %s\n" "$foo" | log info
  967.         found=true
  968.     fi
  969.     done
  970.     if [ "$found" ] ; then
  971.     printf "The directories above are backups left over from a monkeysphere transition.\nThey may contain copies of sensitive data (host keys, certifier lists), but\nthey are no longer needed by monkeysphere.\nYou may remove them at any time.\n\n" | log info
  972.     fi
  973. }
  974.