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