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