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