summaryrefslogtreecommitdiff
path: root/src/share/common
blob: 5a118172d72774b7ae341269b9ef6bd17f864774 (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. host=${1%%:*}
  396. port=${1##*:}
  397. key="$2"
  398. # specify the host and port properly for new ssh known_hosts
  399. # format
  400. if [ "$port" != "$host" ] ; then
  401. host="[${host}]:${port}"
  402. fi
  403. printf "%s %s MonkeySphere%s\n" "$host" "$key" "$DATE"
  404. }
  405. # output authorized_keys line from ssh key
  406. ssh2authorized_keys() {
  407. local userID
  408. local key
  409. userID="$1"
  410. key="$2"
  411. printf "%s MonkeySphere%s %s\n" "$key" "$DATE" "$userID"
  412. }
  413. # convert key from gpg to ssh known_hosts format
  414. gpg2known_hosts() {
  415. local host
  416. local keyID
  417. local key
  418. host="$1"
  419. keyID="$2"
  420. key=$(gpg2ssh "$keyID")
  421. # NOTE: it seems that ssh-keygen -R removes all comment fields from
  422. # all lines in the known_hosts file. why?
  423. # NOTE: just in case, the COMMENT can be matched with the
  424. # following regexp:
  425. # '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$'
  426. printf "%s %s MonkeySphere%s\n" "$host" "$key" "$DATE"
  427. }
  428. # convert key from gpg to ssh authorized_keys format
  429. gpg2authorized_keys() {
  430. local userID
  431. local keyID
  432. local key
  433. userID="$1"
  434. keyID="$2"
  435. key=$(gpg2ssh "$keyID")
  436. # NOTE: just in case, the COMMENT can be matched with the
  437. # following regexp:
  438. # '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$'
  439. printf "%s MonkeySphere%s %s\n" "$key" "$DATE" "$userID"
  440. }
  441. ### GPG UTILITIES
  442. # retrieve all keys with given user id from keyserver
  443. # FIXME: need to figure out how to retrieve all matching keys
  444. # (not just first N (5 in this case))
  445. gpg_fetch_userid() {
  446. local returnCode=0
  447. local userID
  448. if [ "$CHECK_KEYSERVER" != 'true' ] ; then
  449. return 0
  450. fi
  451. userID="$1"
  452. log verbose " checking keyserver $KEYSERVER... "
  453. echo 1,2,3,4,5 | \
  454. gpg --quiet --batch --with-colons \
  455. --command-fd 0 --keyserver "$KEYSERVER" \
  456. --search ="$userID" > /dev/null 2>&1
  457. returnCode="$?"
  458. return "$returnCode"
  459. }
  460. ########################################################################
  461. ### PROCESSING FUNCTIONS
  462. # userid and key policy checking
  463. # the following checks policy on the returned keys
  464. # - checks that full key has appropriate valididy (u|f)
  465. # - checks key has specified capability (REQUIRED_*_KEY_CAPABILITY)
  466. # - checks that requested user ID has appropriate validity
  467. # (see /usr/share/doc/gnupg/DETAILS.gz)
  468. # output is one line for every found key, in the following format:
  469. #
  470. # flag:sshKey
  471. #
  472. # "flag" is an acceptability flag, 0 = ok, 1 = bad
  473. # "sshKey" is the translated gpg key
  474. #
  475. # all log output must go to stderr, as stdout is used to pass the
  476. # flag:sshKey to the calling function.
  477. #
  478. # expects global variable: "MODE"
  479. process_user_id() {
  480. local returnCode=0
  481. local userID
  482. local requiredCapability
  483. local requiredPubCapability
  484. local gpgOut
  485. local type
  486. local validity
  487. local keyid
  488. local uidfpr
  489. local usage
  490. local keyOK
  491. local uidOK
  492. local lastKey
  493. local lastKeyOK
  494. local fingerprint
  495. userID="$1"
  496. # set the required key capability based on the mode
  497. if [ "$MODE" = 'known_hosts' ] ; then
  498. requiredCapability="$REQUIRED_HOST_KEY_CAPABILITY"
  499. elif [ "$MODE" = 'authorized_keys' ] ; then
  500. requiredCapability="$REQUIRED_USER_KEY_CAPABILITY"
  501. fi
  502. requiredPubCapability=$(echo "$requiredCapability" | tr "[:lower:]" "[:upper:]")
  503. # fetch the user ID if necessary/requested
  504. gpg_fetch_userid "$userID"
  505. # output gpg info for (exact) userid and store
  506. gpgOut=$(gpg --list-key --fixed-list-mode --with-colon \
  507. --with-fingerprint --with-fingerprint \
  508. ="$userID" 2>/dev/null) || returnCode="$?"
  509. # if the gpg query return code is not 0, return 1
  510. if [ "$returnCode" -ne 0 ] ; then
  511. log verbose " no primary keys found."
  512. return 1
  513. fi
  514. # loop over all lines in the gpg output and process.
  515. echo "$gpgOut" | cut -d: -f1,2,5,10,12 | \
  516. while IFS=: read -r type validity keyid uidfpr usage ; do
  517. # process based on record type
  518. case $type in
  519. 'pub') # primary keys
  520. # new key, wipe the slate
  521. keyOK=
  522. uidOK=
  523. lastKey=pub
  524. lastKeyOK=
  525. fingerprint=
  526. log verbose " primary key found: $keyid"
  527. # if overall key is not valid, skip
  528. if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
  529. log debug " - unacceptable primary key validity ($validity)."
  530. continue
  531. fi
  532. # if overall key is disabled, skip
  533. if check_capability "$usage" 'D' ; then
  534. log debug " - key disabled."
  535. continue
  536. fi
  537. # if overall key capability is not ok, skip
  538. if ! check_capability "$usage" $requiredPubCapability ; then
  539. log debug " - unacceptable primary key capability ($usage)."
  540. continue
  541. fi
  542. # mark overall key as ok
  543. keyOK=true
  544. # mark primary key as ok if capability is ok
  545. if check_capability "$usage" $requiredCapability ; then
  546. lastKeyOK=true
  547. fi
  548. ;;
  549. 'uid') # user ids
  550. if [ "$lastKey" != pub ] ; then
  551. log verbose " ! got a user ID after a sub key?! user IDs should only follow primary keys!"
  552. continue
  553. fi
  554. # if an acceptable user ID was already found, skip
  555. if [ "$uidOK" = 'true' ] ; then
  556. continue
  557. fi
  558. # if the user ID does matches...
  559. if [ "$(echo "$uidfpr" | gpg_unescape)" = "$userID" ] ; then
  560. # and the user ID validity is ok
  561. if [ "$validity" = 'u' -o "$validity" = 'f' ] ; then
  562. # mark user ID acceptable
  563. uidOK=true
  564. else
  565. log debug " - unacceptable user ID validity ($validity)."
  566. fi
  567. else
  568. continue
  569. fi
  570. # output a line for the primary key
  571. # 0 = ok, 1 = bad
  572. if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
  573. log verbose " * acceptable primary key."
  574. if [ -z "$sshKey" ] ; then
  575. log error " ! primary key could not be translated (not RSA?)."
  576. else
  577. echo "0:${sshKey}"
  578. fi
  579. else
  580. log debug " - unacceptable primary key."
  581. if [ -z "$sshKey" ] ; then
  582. log debug " ! primary key could not be translated (not RSA?)."
  583. else
  584. echo "1:${sshKey}"
  585. fi
  586. fi
  587. ;;
  588. 'sub') # sub keys
  589. # unset acceptability of last key
  590. lastKey=sub
  591. lastKeyOK=
  592. fingerprint=
  593. # don't bother with sub keys if the primary key is not valid
  594. if [ "$keyOK" != true ] ; then
  595. continue
  596. fi
  597. # don't bother with sub keys if no user ID is acceptable:
  598. if [ "$uidOK" != true ] ; then
  599. continue
  600. fi
  601. # if sub key validity is not ok, skip
  602. if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
  603. log debug " - unacceptable sub key validity ($validity)."
  604. continue
  605. fi
  606. # if sub key capability is not ok, skip
  607. if ! check_capability "$usage" $requiredCapability ; then
  608. log debug " - unacceptable sub key capability ($usage)."
  609. continue
  610. fi
  611. # mark sub key as ok
  612. lastKeyOK=true
  613. ;;
  614. 'fpr') # key fingerprint
  615. fingerprint="$uidfpr"
  616. sshKey=$(gpg2ssh "$fingerprint")
  617. # if the last key was the pub key, skip
  618. if [ "$lastKey" = pub ] ; then
  619. continue
  620. fi
  621. # output a line for the sub key
  622. # 0 = ok, 1 = bad
  623. if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
  624. log verbose " * acceptable sub key."
  625. if [ -z "$sshKey" ] ; then
  626. log error " ! sub key could not be translated (not RSA?)."
  627. else
  628. echo "0:${sshKey}"
  629. fi
  630. else
  631. log debug " - unacceptable sub key."
  632. if [ -z "$sshKey" ] ; then
  633. log debug " ! sub key could not be translated (not RSA?)."
  634. else
  635. echo "1:${sshKey}"
  636. fi
  637. fi
  638. ;;
  639. esac
  640. done | sort -t: -k1 -n -r
  641. # NOTE: this last sort is important so that the "good" keys (key
  642. # flag '0') come last. This is so that they take precedence when
  643. # being processed in the key files over "bad" keys (key flag '1')
  644. }
  645. # process a single host in the known_host file
  646. process_host_known_hosts() {
  647. local host
  648. local userID
  649. local noKey=
  650. local nKeys
  651. local nKeysOK
  652. local ok
  653. local sshKey
  654. local tmpfile
  655. # set the key processing mode
  656. export MODE='known_hosts'
  657. host="$1"
  658. userID="ssh://${host}"
  659. log verbose "processing: $host"
  660. nKeys=0
  661. nKeysOK=0
  662. IFS=$'\n'
  663. for line in $(process_user_id "${userID}") ; do
  664. # note that key was found
  665. nKeys=$((nKeys+1))
  666. ok=$(echo "$line" | cut -d: -f1)
  667. sshKey=$(echo "$line" | cut -d: -f2)
  668. if [ -z "$sshKey" ] ; then
  669. continue
  670. fi
  671. # remove any old host key line, and note if removed nothing is
  672. # removed
  673. remove_line "$KNOWN_HOSTS" "$sshKey" || noKey=true
  674. # if key OK, add new host line
  675. if [ "$ok" -eq '0' ] ; then
  676. # note that key was found ok
  677. nKeysOK=$((nKeysOK+1))
  678. # hash if specified
  679. if [ "$HASH_KNOWN_HOSTS" = 'true' ] ; then
  680. # FIXME: this is really hackish cause ssh-keygen won't
  681. # hash from stdin to stdout
  682. tmpfile=$(mktemp ${TMPDIR:-/tmp}/tmp.XXXXXXXXXX)
  683. ssh2known_hosts "$host" "$sshKey" > "$tmpfile"
  684. ssh-keygen -H -f "$tmpfile" 2> /dev/null
  685. cat "$tmpfile" >> "$KNOWN_HOSTS"
  686. rm -f "$tmpfile" "${tmpfile}.old"
  687. else
  688. ssh2known_hosts "$host" "$sshKey" >> "$KNOWN_HOSTS"
  689. fi
  690. # log if this is a new key to the known_hosts file
  691. if [ "$noKey" ] ; then
  692. log info "* new key for $host added to known_hosts file."
  693. fi
  694. fi
  695. done
  696. # if at least one key was found...
  697. if [ "$nKeys" -gt 0 ] ; then
  698. # if ok keys were found, return 0
  699. if [ "$nKeysOK" -gt 0 ] ; then
  700. return 0
  701. # else return 2
  702. else
  703. return 2
  704. fi
  705. # if no keys were found, return 1
  706. else
  707. return 1
  708. fi
  709. }
  710. # update the known_hosts file for a set of hosts listed on command
  711. # line
  712. update_known_hosts() {
  713. local returnCode=0
  714. local nHosts
  715. local nHostsOK
  716. local nHostsBAD
  717. local fileCheck
  718. local host
  719. # the number of hosts specified on command line
  720. nHosts="$#"
  721. nHostsOK=0
  722. nHostsBAD=0
  723. # touch the known_hosts file so that the file permission check
  724. # below won't fail upon not finding the file
  725. (umask 0022 && touch "$KNOWN_HOSTS")
  726. # check permissions on the known_hosts file path
  727. check_key_file_permissions $(whoami) "$KNOWN_HOSTS" || failure
  728. # create a lockfile on known_hosts:
  729. lock create "$KNOWN_HOSTS"
  730. # FIXME: we're discarding any pre-existing EXIT trap; is this bad?
  731. trap "lock remove $KNOWN_HOSTS" EXIT
  732. # note pre update file checksum
  733. fileCheck="$(file_hash "$KNOWN_HOSTS")"
  734. for host ; do
  735. # process the host
  736. process_host_known_hosts "$host" || returnCode="$?"
  737. # note the result
  738. case "$returnCode" in
  739. 0)
  740. nHostsOK=$((nHostsOK+1))
  741. ;;
  742. 2)
  743. nHostsBAD=$((nHostsBAD+1))
  744. ;;
  745. esac
  746. # touch the lockfile, for good measure.
  747. lock touch "$KNOWN_HOSTS"
  748. done
  749. # remove the lockfile and the trap
  750. lock remove "$KNOWN_HOSTS"
  751. trap - EXIT
  752. # note if the known_hosts file was updated
  753. if [ "$(file_hash "$KNOWN_HOSTS")" != "$fileCheck" ] ; then
  754. log debug "known_hosts file updated."
  755. fi
  756. # if an acceptable host was found, return 0
  757. if [ "$nHostsOK" -gt 0 ] ; then
  758. return 0
  759. # else if no ok hosts were found...
  760. else
  761. # if no bad host were found then no hosts were found at all,
  762. # and return 1
  763. if [ "$nHostsBAD" -eq 0 ] ; then
  764. return 1
  765. # else if at least one bad host was found, return 2
  766. else
  767. return 2
  768. fi
  769. fi
  770. }
  771. # process hosts from a known_hosts file
  772. process_known_hosts() {
  773. local hosts
  774. # exit if the known_hosts file does not exist
  775. if [ ! -e "$KNOWN_HOSTS" ] ; then
  776. failure "known_hosts file '$KNOWN_HOSTS' does not exist."
  777. fi
  778. log debug "processing known_hosts file:"
  779. log debug " $KNOWN_HOSTS"
  780. hosts=$(meat "$KNOWN_HOSTS" | cut -d ' ' -f 1 | grep -v '^|.*$' | tr , ' ' | tr '\n' ' ')
  781. if [ -z "$hosts" ] ; then
  782. log debug "no hosts to process."
  783. return
  784. fi
  785. # take all the hosts from the known_hosts file (first
  786. # field), grep out all the hashed hosts (lines starting
  787. # with '|')...
  788. update_known_hosts $hosts
  789. }
  790. # process uids for the authorized_keys file
  791. process_uid_authorized_keys() {
  792. local userID
  793. local nKeys
  794. local nKeysOK
  795. local ok
  796. local sshKey
  797. # set the key processing mode
  798. export MODE='authorized_keys'
  799. userID="$1"
  800. log verbose "processing: $userID"
  801. nKeys=0
  802. nKeysOK=0
  803. IFS=$'\n'
  804. for line in $(process_user_id "$userID") ; do
  805. # note that key was found
  806. nKeys=$((nKeys+1))
  807. ok=$(echo "$line" | cut -d: -f1)
  808. sshKey=$(echo "$line" | cut -d: -f2)
  809. if [ -z "$sshKey" ] ; then
  810. continue
  811. fi
  812. # remove the old host key line
  813. remove_line "$AUTHORIZED_KEYS" "$sshKey"
  814. # if key OK, add new host line
  815. if [ "$ok" -eq '0' ] ; then
  816. # note that key was found ok
  817. nKeysOK=$((nKeysOK+1))
  818. ssh2authorized_keys "$userID" "$sshKey" >> "$AUTHORIZED_KEYS"
  819. fi
  820. done
  821. # if at least one key was found...
  822. if [ "$nKeys" -gt 0 ] ; then
  823. # if ok keys were found, return 0
  824. if [ "$nKeysOK" -gt 0 ] ; then
  825. return 0
  826. # else return 2
  827. else
  828. return 2
  829. fi
  830. # if no keys were found, return 1
  831. else
  832. return 1
  833. fi
  834. }
  835. # update the authorized_keys files from a list of user IDs on command
  836. # line
  837. update_authorized_keys() {
  838. local returnCode=0
  839. local userID
  840. local nIDs
  841. local nIDsOK
  842. local nIDsBAD
  843. local fileCheck
  844. # the number of ids specified on command line
  845. nIDs="$#"
  846. nIDsOK=0
  847. nIDsBAD=0
  848. log debug "updating authorized_keys file:"
  849. log debug " $AUTHORIZED_KEYS"
  850. # check permissions on the authorized_keys file path
  851. check_key_file_permissions $(whoami) "$AUTHORIZED_KEYS" || failure
  852. # create a lockfile on authorized_keys
  853. lock create "$AUTHORIZED_KEYS"
  854. # FIXME: we're discarding any pre-existing EXIT trap; is this bad?
  855. trap "lock remove $AUTHORIZED_KEYS" EXIT
  856. # note pre update file checksum
  857. fileCheck="$(file_hash "$AUTHORIZED_KEYS")"
  858. # remove any monkeysphere lines from authorized_keys file
  859. remove_monkeysphere_lines "$AUTHORIZED_KEYS"
  860. for userID ; do
  861. # process the user ID, change return code if key not found for
  862. # user ID
  863. process_uid_authorized_keys "$userID" || returnCode="$?"
  864. # note the result
  865. case "$returnCode" in
  866. 0)
  867. nIDsOK=$((nIDsOK+1))
  868. ;;
  869. 2)
  870. nIDsBAD=$((nIDsBAD+1))
  871. ;;
  872. esac
  873. # touch the lockfile, for good measure.
  874. lock touch "$AUTHORIZED_KEYS"
  875. done
  876. # remove the lockfile and the trap
  877. lock remove "$AUTHORIZED_KEYS"
  878. # remove the trap
  879. trap - EXIT
  880. # note if the authorized_keys file was updated
  881. if [ "$(file_hash "$AUTHORIZED_KEYS")" != "$fileCheck" ] ; then
  882. log debug "authorized_keys file updated."
  883. fi
  884. # if an acceptable id was found, return 0
  885. if [ "$nIDsOK" -gt 0 ] ; then
  886. return 0
  887. # else if no ok ids were found...
  888. else
  889. # if no bad ids were found then no ids were found at all, and
  890. # return 1
  891. if [ "$nIDsBAD" -eq 0 ] ; then
  892. return 1
  893. # else if at least one bad id was found, return 2
  894. else
  895. return 2
  896. fi
  897. fi
  898. }
  899. # process an authorized_user_ids file for authorized_keys
  900. process_authorized_user_ids() {
  901. local line
  902. local nline
  903. local userIDs
  904. authorizedUserIDs="$1"
  905. # exit if the authorized_user_ids file is empty
  906. if [ ! -e "$authorizedUserIDs" ] ; then
  907. failure "authorized_user_ids file '$authorizedUserIDs' does not exist."
  908. fi
  909. log debug "processing authorized_user_ids file:"
  910. log debug " $authorizedUserIDs"
  911. # check permissions on the authorized_user_ids file path
  912. check_key_file_permissions $(whoami) "$authorizedUserIDs" || failure
  913. if ! meat "$authorizedUserIDs" > /dev/null ; then
  914. log debug " no user IDs to process."
  915. return
  916. fi
  917. nline=0
  918. # extract user IDs from authorized_user_ids file
  919. IFS=$'\n'
  920. for line in $(meat "$authorizedUserIDs") ; do
  921. userIDs["$nline"]="$line"
  922. nline=$((nline+1))
  923. done
  924. update_authorized_keys "${userIDs[@]}"
  925. }
  926. # takes a gpg key or keys on stdin, and outputs a list of
  927. # fingerprints, one per line:
  928. list_primary_fingerprints() {
  929. local fake=$(msmktempdir)
  930. GNUPGHOME="$fake" gpg --no-tty --quiet --import
  931. GNUPGHOME="$fake" gpg --with-colons --fingerprint --list-keys | \
  932. awk -F: '/^fpr:/{ print $10 }'
  933. rm -rf "$fake"
  934. }
  935. check_cruft_file() {
  936. local loc="$1"
  937. local version="$2"
  938. if [ -e "$loc" ] ; then
  939. 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
  940. fi
  941. }
  942. check_upgrade_dir() {
  943. local loc="$1"
  944. local version="$2"
  945. if [ -d "$loc" ] ; then
  946. 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
  947. fi
  948. }
  949. ## look for cruft from old versions of the monkeysphere, and notice if
  950. ## upgrades have not been run:
  951. report_cruft() {
  952. check_upgrade_dir "${SYSCONFIGDIR}/gnupg-host" 0.23
  953. check_upgrade_dir "${SYSCONFIGDIR}/gnupg-authentication" 0.23
  954. check_cruft_file "${SYSCONFIGDIR}/gnupg-authentication.conf" 0.23
  955. check_cruft_file "${SYSCONFIGDIR}/gnupg-host.conf" 0.23
  956. local found=
  957. for foo in "${SYSDATADIR}/backup-from-"*"-transition" ; do
  958. if [ -d "$foo" ] ; then
  959. printf "! %s\n" "$foo" | log info
  960. found=true
  961. fi
  962. done
  963. if [ "$found" ] ; then
  964. 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
  965. fi
  966. }