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