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