summaryrefslogtreecommitdiff
path: root/src/share/common
blob: d6e494953d078e1178c1dda7addc3cf985196f1e (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 ! ( which lockfile-create >/dev/null 2>/dev/null ) ; then
  127. if ! ( which 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 2>&1; 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. # check that characters are in a string (in an AND fashion).
  205. # used for checking key capability
  206. # check_capability capability a [b...]
  207. check_capability() {
  208. local usage
  209. local capcheck
  210. usage="$1"
  211. shift 1
  212. for capcheck ; do
  213. if echo "$usage" | grep -q -v "$capcheck" ; then
  214. return 1
  215. fi
  216. done
  217. return 0
  218. }
  219. # hash of a file
  220. file_hash() {
  221. md5sum "$1" 2> /dev/null
  222. }
  223. # convert escaped characters in pipeline from gpg output back into
  224. # original character
  225. # FIXME: undo all escape character translation in with-colons gpg
  226. # output
  227. gpg_unescape() {
  228. sed 's/\\x3a/:/g'
  229. }
  230. # convert nasty chars into gpg-friendly form in pipeline
  231. # FIXME: escape everything, not just colons!
  232. gpg_escape() {
  233. sed 's/:/\\x3a/g'
  234. }
  235. # prompt for GPG-formatted expiration, and emit result on stdout
  236. get_gpg_expiration() {
  237. local keyExpire
  238. keyExpire="$1"
  239. if [ -z "$keyExpire" -a "$PROMPT" = 'true' ]; then
  240. cat >&2 <<EOF
  241. Please specify how long the key should be valid.
  242. 0 = key does not expire
  243. <n> = key expires in n days
  244. <n>w = key expires in n weeks
  245. <n>m = key expires in n months
  246. <n>y = key expires in n years
  247. EOF
  248. while [ -z "$keyExpire" ] ; do
  249. read -p "Key is valid for? (0) " keyExpire
  250. if ! test_gpg_expire ${keyExpire:=0} ; then
  251. echo "invalid value" >&2
  252. unset keyExpire
  253. fi
  254. done
  255. elif ! test_gpg_expire "$keyExpire" ; then
  256. failure "invalid key expiration value '$keyExpire'."
  257. fi
  258. echo "$keyExpire"
  259. }
  260. passphrase_prompt() {
  261. local prompt="$1"
  262. local fifo="$2"
  263. local PASS
  264. if [ "$DISPLAY" ] && which "${SSH_ASKPASS:-ssh-askpass}" >/dev/null; then
  265. "${SSH_ASKPASS:-ssh-askpass}" "$prompt" > "$fifo"
  266. else
  267. read -s -p "$prompt" PASS
  268. # Uses the builtin echo, so should not put the passphrase into
  269. # the process table. I think. --dkg
  270. echo "$PASS" > "$fifo"
  271. fi
  272. }
  273. # remove all lines with specified string from specified file
  274. remove_line() {
  275. local file
  276. local string
  277. local tempfile
  278. file="$1"
  279. string="$2"
  280. if [ -z "$file" -o -z "$string" ] ; then
  281. return 1
  282. fi
  283. if [ ! -e "$file" ] ; then
  284. return 1
  285. fi
  286. # if the string is in the file...
  287. if grep -q -F "$string" "$file" 2> /dev/null ; then
  288. tempfile=$(mktemp "${file}.XXXXXXX") || \
  289. failure "Unable to make temp file '${file}.XXXXXXX'"
  290. # remove the line with the string, and return 0
  291. grep -v -F "$string" "$file" >"$tempfile"
  292. cat "$tempfile" > "$file"
  293. rm "$tempfile"
  294. return 0
  295. # otherwise return 1
  296. else
  297. return 1
  298. fi
  299. }
  300. # remove all lines with MonkeySphere strings in file
  301. remove_monkeysphere_lines() {
  302. local file
  303. local tempfile
  304. file="$1"
  305. # return error if file does not exist
  306. if [ ! -e "$file" ] ; then
  307. return 1
  308. fi
  309. # just return ok if the file is empty, since there aren't any
  310. # lines to remove
  311. if [ ! -s "$file" ] ; then
  312. return 0
  313. fi
  314. tempfile=$(mktemp "${file}.XXXXXXX") || \
  315. failure "Could not make temporary file '${file}.XXXXXXX'."
  316. egrep -v '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$' \
  317. "$file" >"$tempfile"
  318. cat "$tempfile" > "$file"
  319. rm "$tempfile"
  320. }
  321. # translate ssh-style path variables %h and %u
  322. translate_ssh_variables() {
  323. local uname
  324. local home
  325. uname="$1"
  326. path="$2"
  327. # get the user's home directory
  328. userHome=$(getent passwd "$uname" | cut -d: -f6)
  329. # translate '%u' to user name
  330. path=${path/\%u/"$uname"}
  331. # translate '%h' to user home directory
  332. path=${path/\%h/"$userHome"}
  333. echo "$path"
  334. }
  335. # test that a string to conforms to GPG's expiration format
  336. test_gpg_expire() {
  337. echo "$1" | egrep -q "^[0-9]+[mwy]?$"
  338. }
  339. # check that a file is properly owned, and that all it's parent
  340. # directories are not group/other writable
  341. check_key_file_permissions() {
  342. local uname
  343. local path
  344. local stat
  345. local access
  346. local gAccess
  347. local oAccess
  348. # function to check that the given permission corresponds to writability
  349. is_write() {
  350. [ "$1" = "w" ]
  351. }
  352. uname="$1"
  353. path="$2"
  354. log debug "checking path permission '$path'..."
  355. # return 255 if cannot stat file
  356. if ! stat=$(ls -ld "$path" 2>/dev/null) ; then
  357. log error "could not stat path '$path'."
  358. return 255
  359. fi
  360. owner=$(echo "$stat" | awk '{ print $3 }')
  361. gAccess=$(echo "$stat" | cut -c6)
  362. oAccess=$(echo "$stat" | cut -c9)
  363. # return 1 if path has invalid owner
  364. if [ "$owner" != "$uname" -a "$owner" != 'root' ] ; then
  365. log error "improper ownership on path '$path':"
  366. log error " $owner != ($uname|root)"
  367. return 1
  368. fi
  369. # return 2 if path has group or other writability
  370. if is_write "$gAccess" || is_write "$oAccess" ; then
  371. log error "improper group or other writability on path '$path':"
  372. log error " group: $gAccess, other: $oAcess"
  373. return 2
  374. fi
  375. # return zero if all clear, or go to next path
  376. if [ "$path" = '/' ] ; then
  377. log debug "path ok."
  378. return 0
  379. else
  380. check_key_file_permissions "$uname" $(dirname "$path")
  381. fi
  382. }
  383. ### CONVERSION UTILITIES
  384. # output the ssh key for a given key ID
  385. gpg2ssh() {
  386. local keyID
  387. keyID="$1"
  388. gpg --export "$keyID" | openpgp2ssh "$keyID" 2> /dev/null
  389. }
  390. # output known_hosts line from ssh key
  391. ssh2known_hosts() {
  392. local host
  393. local port
  394. local key
  395. # FIXME this does not properly deal with IPv6 hosts using the
  396. # standard port (because it's unclear whether their final
  397. # colon-delimited address section is a port number or an address
  398. # string)
  399. host=${1%:*}
  400. port=${1##*:}
  401. key="$2"
  402. # specify the host and port properly for new ssh known_hosts
  403. # format
  404. if [ "$port" != "$host" ] ; then
  405. host="[${host}]:${port}"
  406. fi
  407. printf "%s %s MonkeySphere%s\n" "$host" "$key" "$DATE"
  408. }
  409. # output authorized_keys line from ssh key
  410. ssh2authorized_keys() {
  411. local userID
  412. local key
  413. userID="$1"
  414. key="$2"
  415. printf "%s MonkeySphere%s %s\n" "$key" "$DATE" "$userID"
  416. }
  417. # convert key from gpg to ssh known_hosts format
  418. gpg2known_hosts() {
  419. local host
  420. local keyID
  421. local key
  422. host="$1"
  423. keyID="$2"
  424. key=$(gpg2ssh "$keyID")
  425. # NOTE: it seems that ssh-keygen -R removes all comment fields from
  426. # all lines in the known_hosts file. why?
  427. # NOTE: just in case, the COMMENT can be matched with the
  428. # following regexp:
  429. # '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$'
  430. printf "%s %s MonkeySphere%s\n" "$host" "$key" "$DATE"
  431. }
  432. # convert key from gpg to ssh authorized_keys format
  433. gpg2authorized_keys() {
  434. local userID
  435. local keyID
  436. local key
  437. userID="$1"
  438. keyID="$2"
  439. key=$(gpg2ssh "$keyID")
  440. # NOTE: just in case, the COMMENT can be matched with the
  441. # following regexp:
  442. # '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$'
  443. printf "%s MonkeySphere%s %s\n" "$key" "$DATE" "$userID"
  444. }
  445. ### GPG UTILITIES
  446. # retrieve all keys with given user id from keyserver
  447. # FIXME: need to figure out how to retrieve all matching keys
  448. # (not just first N (5 in this case))
  449. gpg_fetch_userid() {
  450. local returnCode=0
  451. local userID
  452. if [ "$CHECK_KEYSERVER" != 'true' ] ; then
  453. return 0
  454. fi
  455. userID="$1"
  456. log verbose " checking keyserver $KEYSERVER... "
  457. echo 1,2,3,4,5 | \
  458. gpg --quiet --batch --with-colons \
  459. --command-fd 0 --keyserver "$KEYSERVER" \
  460. --search ="$userID" > /dev/null 2>&1
  461. returnCode="$?"
  462. return "$returnCode"
  463. }
  464. ########################################################################
  465. ### PROCESSING FUNCTIONS
  466. # userid and key policy checking
  467. # the following checks policy on the returned keys
  468. # - checks that full key has appropriate valididy (u|f)
  469. # - checks key has specified capability (REQUIRED_*_KEY_CAPABILITY)
  470. # - checks that requested user ID has appropriate validity
  471. # (see /usr/share/doc/gnupg/DETAILS.gz)
  472. # output is one line for every found key, in the following format:
  473. #
  474. # flag:sshKey
  475. #
  476. # "flag" is an acceptability flag, 0 = ok, 1 = bad
  477. # "sshKey" is the translated gpg key
  478. #
  479. # all log output must go to stderr, as stdout is used to pass the
  480. # flag:sshKey to the calling function.
  481. #
  482. # expects global variable: "MODE"
  483. process_user_id() {
  484. local returnCode=0
  485. local userID
  486. local requiredCapability
  487. local requiredPubCapability
  488. local gpgOut
  489. local type
  490. local validity
  491. local keyid
  492. local uidfpr
  493. local usage
  494. local keyOK
  495. local uidOK
  496. local lastKey
  497. local lastKeyOK
  498. local fingerprint
  499. userID="$1"
  500. # set the required key capability based on the mode
  501. if [ "$MODE" = 'known_hosts' ] ; then
  502. requiredCapability="$REQUIRED_HOST_KEY_CAPABILITY"
  503. elif [ "$MODE" = 'authorized_keys' ] ; then
  504. requiredCapability="$REQUIRED_USER_KEY_CAPABILITY"
  505. fi
  506. requiredPubCapability=$(echo "$requiredCapability" | tr "[:lower:]" "[:upper:]")
  507. # fetch the user ID if necessary/requested
  508. gpg_fetch_userid "$userID"
  509. # output gpg info for (exact) userid and store
  510. gpgOut=$(gpg --list-key --fixed-list-mode --with-colon \
  511. --with-fingerprint --with-fingerprint \
  512. ="$userID" 2>/dev/null) || returnCode="$?"
  513. # if the gpg query return code is not 0, return 1
  514. if [ "$returnCode" -ne 0 ] ; then
  515. log verbose " no primary keys found."
  516. return 1
  517. fi
  518. # loop over all lines in the gpg output and process.
  519. echo "$gpgOut" | cut -d: -f1,2,5,10,12 | \
  520. while IFS=: read -r type validity keyid uidfpr usage ; do
  521. # process based on record type
  522. case $type in
  523. 'pub') # primary keys
  524. # new key, wipe the slate
  525. keyOK=
  526. uidOK=
  527. lastKey=pub
  528. lastKeyOK=
  529. fingerprint=
  530. log verbose " primary key found: $keyid"
  531. # if overall key is not valid, skip
  532. if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
  533. log debug " - unacceptable primary key validity ($validity)."
  534. continue
  535. fi
  536. # if overall key is disabled, skip
  537. if check_capability "$usage" 'D' ; then
  538. log debug " - key disabled."
  539. continue
  540. fi
  541. # if overall key capability is not ok, skip
  542. if ! check_capability "$usage" $requiredPubCapability ; then
  543. log debug " - unacceptable primary key capability ($usage)."
  544. continue
  545. fi
  546. # mark overall key as ok
  547. keyOK=true
  548. # mark primary key as ok if capability is ok
  549. if check_capability "$usage" $requiredCapability ; then
  550. lastKeyOK=true
  551. fi
  552. ;;
  553. 'uid') # user ids
  554. if [ "$lastKey" != pub ] ; then
  555. log verbose " ! got a user ID after a sub key?! user IDs should only follow primary keys!"
  556. continue
  557. fi
  558. # if an acceptable user ID was already found, skip
  559. if [ "$uidOK" = 'true' ] ; then
  560. continue
  561. fi
  562. # if the user ID does matches...
  563. if [ "$(echo "$uidfpr" | gpg_unescape)" = "$userID" ] ; then
  564. # and the user ID validity is ok
  565. if [ "$validity" = 'u' -o "$validity" = 'f' ] ; then
  566. # mark user ID acceptable
  567. uidOK=true
  568. else
  569. log debug " - unacceptable user ID validity ($validity)."
  570. fi
  571. else
  572. continue
  573. fi
  574. # output a line for the primary key
  575. # 0 = ok, 1 = bad
  576. if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
  577. log verbose " * acceptable primary key."
  578. if [ -z "$sshKey" ] ; then
  579. log error " ! primary key could not be translated (not RSA?)."
  580. else
  581. echo "0:${sshKey}"
  582. fi
  583. else
  584. log debug " - unacceptable primary key."
  585. if [ -z "$sshKey" ] ; then
  586. log debug " ! primary key could not be translated (not RSA?)."
  587. else
  588. echo "1:${sshKey}"
  589. fi
  590. fi
  591. ;;
  592. 'sub') # sub keys
  593. # unset acceptability of last key
  594. lastKey=sub
  595. lastKeyOK=
  596. fingerprint=
  597. # don't bother with sub keys if the primary key is not valid
  598. if [ "$keyOK" != true ] ; then
  599. continue
  600. fi
  601. # don't bother with sub keys if no user ID is acceptable:
  602. if [ "$uidOK" != true ] ; then
  603. continue
  604. fi
  605. # if sub key validity is not ok, skip
  606. if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
  607. log debug " - unacceptable sub key validity ($validity)."
  608. continue
  609. fi
  610. # if sub key capability is not ok, skip
  611. if ! check_capability "$usage" $requiredCapability ; then
  612. log debug " - unacceptable sub key capability ($usage)."
  613. continue
  614. fi
  615. # mark sub key as ok
  616. lastKeyOK=true
  617. ;;
  618. 'fpr') # key fingerprint
  619. fingerprint="$uidfpr"
  620. sshKey=$(gpg2ssh "$fingerprint")
  621. # if the last key was the pub key, skip
  622. if [ "$lastKey" = pub ] ; then
  623. continue
  624. fi
  625. # output a line for the sub key
  626. # 0 = ok, 1 = bad
  627. if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
  628. log verbose " * acceptable sub key."
  629. if [ -z "$sshKey" ] ; then
  630. log error " ! sub key could not be translated (not RSA?)."
  631. else
  632. echo "0:${sshKey}"
  633. fi
  634. else
  635. log debug " - unacceptable sub key."
  636. if [ -z "$sshKey" ] ; then
  637. log debug " ! sub key could not be translated (not RSA?)."
  638. else
  639. echo "1:${sshKey}"
  640. fi
  641. fi
  642. ;;
  643. esac
  644. done | sort -t: -k1 -n -r
  645. # NOTE: this last sort is important so that the "good" keys (key
  646. # flag '0') come last. This is so that they take precedence when
  647. # being processed in the key files over "bad" keys (key flag '1')
  648. }
  649. # process a single host in the known_host file
  650. process_host_known_hosts() {
  651. local host
  652. local userID
  653. local noKey=
  654. local nKeys
  655. local nKeysOK
  656. local ok
  657. local sshKey
  658. local tmpfile
  659. # set the key processing mode
  660. export MODE='known_hosts'
  661. host="$1"
  662. userID="ssh://${host}"
  663. log verbose "processing: $host"
  664. nKeys=0
  665. nKeysOK=0
  666. IFS=$'\n'
  667. for line in $(process_user_id "${userID}") ; do
  668. # note that key was found
  669. nKeys=$((nKeys+1))
  670. ok=$(echo "$line" | cut -d: -f1)
  671. sshKey=$(echo "$line" | cut -d: -f2)
  672. if [ -z "$sshKey" ] ; then
  673. continue
  674. fi
  675. # remove any old host key line, and note if removed nothing is
  676. # removed
  677. remove_line "$KNOWN_HOSTS" "$sshKey" || noKey=true
  678. # if key OK, add new host line
  679. if [ "$ok" -eq '0' ] ; then
  680. # note that key was found ok
  681. nKeysOK=$((nKeysOK+1))
  682. # hash if specified
  683. if [ "$HASH_KNOWN_HOSTS" = 'true' ] ; then
  684. # FIXME: this is really hackish cause ssh-keygen won't
  685. # hash from stdin to stdout
  686. tmpfile=$(mktemp ${TMPDIR:-/tmp}/tmp.XXXXXXXXXX)
  687. ssh2known_hosts "$host" "$sshKey" > "$tmpfile"
  688. ssh-keygen -H -f "$tmpfile" 2> /dev/null
  689. cat "$tmpfile" >> "$KNOWN_HOSTS"
  690. rm -f "$tmpfile" "${tmpfile}.old"
  691. else
  692. ssh2known_hosts "$host" "$sshKey" >> "$KNOWN_HOSTS"
  693. fi
  694. # log if this is a new key to the known_hosts file
  695. if [ "$noKey" ] ; then
  696. log info "* new key for $host added to known_hosts file."
  697. fi
  698. fi
  699. done
  700. # if at least one key was found...
  701. if [ "$nKeys" -gt 0 ] ; then
  702. # if ok keys were found, return 0
  703. if [ "$nKeysOK" -gt 0 ] ; then
  704. return 0
  705. # else return 2
  706. else
  707. return 2
  708. fi
  709. # if no keys were found, return 1
  710. else
  711. return 1
  712. fi
  713. }
  714. # update the known_hosts file for a set of hosts listed on command
  715. # line
  716. update_known_hosts() {
  717. local returnCode=0
  718. local nHosts
  719. local nHostsOK
  720. local nHostsBAD
  721. local fileCheck
  722. local host
  723. # the number of hosts specified on command line
  724. nHosts="$#"
  725. nHostsOK=0
  726. nHostsBAD=0
  727. # touch the known_hosts file so that the file permission check
  728. # below won't fail upon not finding the file
  729. (umask 0022 && touch "$KNOWN_HOSTS")
  730. # check permissions on the known_hosts file path
  731. check_key_file_permissions $(whoami) "$KNOWN_HOSTS" || failure
  732. # create a lockfile on known_hosts:
  733. lock create "$KNOWN_HOSTS"
  734. # FIXME: we're discarding any pre-existing EXIT trap; is this bad?
  735. trap "lock remove $KNOWN_HOSTS" EXIT
  736. # note pre update file checksum
  737. fileCheck="$(file_hash "$KNOWN_HOSTS")"
  738. for host ; do
  739. # process the host
  740. process_host_known_hosts "$host" || returnCode="$?"
  741. # note the result
  742. case "$returnCode" in
  743. 0)
  744. nHostsOK=$((nHostsOK+1))
  745. ;;
  746. 2)
  747. nHostsBAD=$((nHostsBAD+1))
  748. ;;
  749. esac
  750. # touch the lockfile, for good measure.
  751. lock touch "$KNOWN_HOSTS"
  752. done
  753. # remove the lockfile and the trap
  754. lock remove "$KNOWN_HOSTS"
  755. trap - EXIT
  756. # note if the known_hosts file was updated
  757. if [ "$(file_hash "$KNOWN_HOSTS")" != "$fileCheck" ] ; then
  758. log debug "known_hosts file updated."
  759. fi
  760. # if an acceptable host was found, return 0
  761. if [ "$nHostsOK" -gt 0 ] ; then
  762. return 0
  763. # else if no ok hosts were found...
  764. else
  765. # if no bad host were found then no hosts were found at all,
  766. # and return 1
  767. if [ "$nHostsBAD" -eq 0 ] ; then
  768. return 1
  769. # else if at least one bad host was found, return 2
  770. else
  771. return 2
  772. fi
  773. fi
  774. }
  775. # process hosts from a known_hosts file
  776. process_known_hosts() {
  777. local hosts
  778. # exit if the known_hosts file does not exist
  779. if [ ! -e "$KNOWN_HOSTS" ] ; then
  780. failure "known_hosts file '$KNOWN_HOSTS' does not exist."
  781. fi
  782. log debug "processing known_hosts file:"
  783. log debug " $KNOWN_HOSTS"
  784. hosts=$(meat "$KNOWN_HOSTS" | cut -d ' ' -f 1 | grep -v '^|.*$' | tr , ' ' | tr '\n' ' ')
  785. if [ -z "$hosts" ] ; then
  786. log debug "no hosts to process."
  787. return
  788. fi
  789. # take all the hosts from the known_hosts file (first
  790. # field), grep out all the hashed hosts (lines starting
  791. # with '|')...
  792. update_known_hosts $hosts
  793. }
  794. # process uids for the authorized_keys file
  795. process_uid_authorized_keys() {
  796. local userID
  797. local nKeys
  798. local nKeysOK
  799. local ok
  800. local sshKey
  801. # set the key processing mode
  802. export MODE='authorized_keys'
  803. userID="$1"
  804. log verbose "processing: $userID"
  805. nKeys=0
  806. nKeysOK=0
  807. IFS=$'\n'
  808. for line in $(process_user_id "$userID") ; do
  809. # note that key was found
  810. nKeys=$((nKeys+1))
  811. ok=$(echo "$line" | cut -d: -f1)
  812. sshKey=$(echo "$line" | cut -d: -f2)
  813. if [ -z "$sshKey" ] ; then
  814. continue
  815. fi
  816. # remove the old host key line
  817. remove_line "$AUTHORIZED_KEYS" "$sshKey"
  818. # if key OK, add new host line
  819. if [ "$ok" -eq '0' ] ; then
  820. # note that key was found ok
  821. nKeysOK=$((nKeysOK+1))
  822. ssh2authorized_keys "$userID" "$sshKey" >> "$AUTHORIZED_KEYS"
  823. fi
  824. done
  825. # if at least one key was found...
  826. if [ "$nKeys" -gt 0 ] ; then
  827. # if ok keys were found, return 0
  828. if [ "$nKeysOK" -gt 0 ] ; then
  829. return 0
  830. # else return 2
  831. else
  832. return 2
  833. fi
  834. # if no keys were found, return 1
  835. else
  836. return 1
  837. fi
  838. }
  839. # update the authorized_keys files from a list of user IDs on command
  840. # line
  841. update_authorized_keys() {
  842. local returnCode=0
  843. local userID
  844. local nIDs
  845. local nIDsOK
  846. local nIDsBAD
  847. local fileCheck
  848. # the number of ids specified on command line
  849. nIDs="$#"
  850. nIDsOK=0
  851. nIDsBAD=0
  852. log debug "updating authorized_keys file:"
  853. log debug " $AUTHORIZED_KEYS"
  854. # check permissions on the authorized_keys file path
  855. check_key_file_permissions $(whoami) "$AUTHORIZED_KEYS" || failure
  856. # create a lockfile on authorized_keys
  857. lock create "$AUTHORIZED_KEYS"
  858. # FIXME: we're discarding any pre-existing EXIT trap; is this bad?
  859. trap "lock remove $AUTHORIZED_KEYS" EXIT
  860. # note pre update file checksum
  861. fileCheck="$(file_hash "$AUTHORIZED_KEYS")"
  862. # remove any monkeysphere lines from authorized_keys file
  863. remove_monkeysphere_lines "$AUTHORIZED_KEYS"
  864. for userID ; do
  865. # process the user ID, change return code if key not found for
  866. # user ID
  867. process_uid_authorized_keys "$userID" || returnCode="$?"
  868. # note the result
  869. case "$returnCode" in
  870. 0)
  871. nIDsOK=$((nIDsOK+1))
  872. ;;
  873. 2)
  874. nIDsBAD=$((nIDsBAD+1))
  875. ;;
  876. esac
  877. # touch the lockfile, for good measure.
  878. lock touch "$AUTHORIZED_KEYS"
  879. done
  880. # remove the lockfile and the trap
  881. lock remove "$AUTHORIZED_KEYS"
  882. # remove the trap
  883. trap - EXIT
  884. # note if the authorized_keys file was updated
  885. if [ "$(file_hash "$AUTHORIZED_KEYS")" != "$fileCheck" ] ; then
  886. log debug "authorized_keys file updated."
  887. fi
  888. # if an acceptable id was found, return 0
  889. if [ "$nIDsOK" -gt 0 ] ; then
  890. return 0
  891. # else if no ok ids were found...
  892. else
  893. # if no bad ids were found then no ids were found at all, and
  894. # return 1
  895. if [ "$nIDsBAD" -eq 0 ] ; then
  896. return 1
  897. # else if at least one bad id was found, return 2
  898. else
  899. return 2
  900. fi
  901. fi
  902. }
  903. # process an authorized_user_ids file for authorized_keys
  904. process_authorized_user_ids() {
  905. local line
  906. local nline
  907. local userIDs
  908. authorizedUserIDs="$1"
  909. # exit if the authorized_user_ids file is empty
  910. if [ ! -e "$authorizedUserIDs" ] ; then
  911. failure "authorized_user_ids file '$authorizedUserIDs' does not exist."
  912. fi
  913. log debug "processing authorized_user_ids file:"
  914. log debug " $authorizedUserIDs"
  915. # check permissions on the authorized_user_ids file path
  916. check_key_file_permissions $(whoami) "$authorizedUserIDs" || failure
  917. if ! meat "$authorizedUserIDs" > /dev/null ; then
  918. log debug " no user IDs to process."
  919. return
  920. fi
  921. nline=0
  922. # extract user IDs from authorized_user_ids file
  923. IFS=$'\n'
  924. for line in $(meat "$authorizedUserIDs") ; do
  925. userIDs["$nline"]="$line"
  926. nline=$((nline+1))
  927. done
  928. update_authorized_keys "${userIDs[@]}"
  929. }
  930. # takes a gpg key or keys on stdin, and outputs a list of
  931. # fingerprints, one per line:
  932. list_primary_fingerprints() {
  933. local fake=$(msmktempdir)
  934. GNUPGHOME="$fake" gpg --no-tty --quiet --import
  935. GNUPGHOME="$fake" gpg --with-colons --fingerprint --list-keys | \
  936. awk -F: '/^fpr:/{ print $10 }'
  937. rm -rf "$fake"
  938. }
  939. check_cruft_file() {
  940. local loc="$1"
  941. local version="$2"
  942. if [ -e "$loc" ] ; then
  943. 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
  944. fi
  945. }
  946. check_upgrade_dir() {
  947. local loc="$1"
  948. local version="$2"
  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. ## look for cruft from old versions of the monkeysphere, and notice if
  954. ## upgrades have not been run:
  955. report_cruft() {
  956. check_upgrade_dir "${SYSCONFIGDIR}/gnupg-host" 0.23
  957. check_upgrade_dir "${SYSCONFIGDIR}/gnupg-authentication" 0.23
  958. check_cruft_file "${SYSCONFIGDIR}/gnupg-authentication.conf" 0.23
  959. check_cruft_file "${SYSCONFIGDIR}/gnupg-host.conf" 0.23
  960. local found=
  961. for foo in "${SYSDATADIR}/backup-from-"*"-transition" ; do
  962. if [ -d "$foo" ] ; then
  963. printf "! %s\n" "$foo" | log info
  964. found=true
  965. fi
  966. done
  967. if [ "$found" ] ; then
  968. 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
  969. fi
  970. }