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