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