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