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