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