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