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