summaryrefslogtreecommitdiff
path: root/src/share/common
blob: 9e8a193a37b9a254be017e1591138fdb324deb97 (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" -s "$(which bash)" -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. print_date_from_seconds_since_the_epoch() {
  205. local seconds="$1"
  206. local gnutry
  207. if ! date '+%F %T' -d @"${seconds}" 2>/dev/null ; then
  208. # try it the BSD date way:
  209. date -r "${seconds}" '+%F %T'
  210. fi
  211. }
  212. # check that characters are in a string (in an AND fashion).
  213. # used for checking key capability
  214. # check_capability capability a [b...]
  215. check_capability() {
  216. local usage
  217. local capcheck
  218. usage="$1"
  219. shift 1
  220. for capcheck ; do
  221. if echo "$usage" | grep -q -v "$capcheck" ; then
  222. return 1
  223. fi
  224. done
  225. return 0
  226. }
  227. # hash of a file
  228. file_hash() {
  229. if type md5sum &>/dev/null ; then
  230. md5sum "$1"
  231. elif type md5 &>/dev/null ; then
  232. md5 "$1"
  233. else
  234. failure "Neither md5sum nor md5 are in the path!"
  235. fi
  236. }
  237. # convert escaped characters in pipeline from gpg output back into
  238. # original character
  239. # FIXME: undo all escape character translation in with-colons gpg
  240. # output
  241. gpg_unescape() {
  242. sed 's/\\x3a/:/g'
  243. }
  244. # convert nasty chars into gpg-friendly form in pipeline
  245. # FIXME: escape everything, not just colons!
  246. gpg_escape() {
  247. sed 's/:/\\x3a/g'
  248. }
  249. # prompt for GPG-formatted expiration, and emit result on stdout
  250. get_gpg_expiration() {
  251. local keyExpire
  252. keyExpire="$1"
  253. if [ -z "$keyExpire" -a "$PROMPT" != 'false' ]; then
  254. cat >&2 <<EOF
  255. Please specify how long the key should be valid.
  256. 0 = key does not expire
  257. <n> = key expires in n days
  258. <n>w = key expires in n weeks
  259. <n>m = key expires in n months
  260. <n>y = key expires in n years
  261. EOF
  262. while [ -z "$keyExpire" ] ; do
  263. printf "Key is valid for? (0) " >&2
  264. read keyExpire
  265. if ! test_gpg_expire ${keyExpire:=0} ; then
  266. echo "invalid value" >&2
  267. unset keyExpire
  268. fi
  269. done
  270. elif ! test_gpg_expire "$keyExpire" ; then
  271. failure "invalid key expiration value '$keyExpire'."
  272. fi
  273. echo "$keyExpire"
  274. }
  275. passphrase_prompt() {
  276. local prompt="$1"
  277. local fifo="$2"
  278. local PASS
  279. if [ "$DISPLAY" ] && type "${SSH_ASKPASS:-ssh-askpass}" >/dev/null 2>/dev/null; then
  280. printf 'Launching "%s"\n' "${SSH_ASKPASS:-ssh-askpass}" | log info
  281. printf '(with prompt "%s")\n' "$prompt" | log debug
  282. "${SSH_ASKPASS:-ssh-askpass}" "$prompt" > "$fifo"
  283. else
  284. read -s -p "$prompt" PASS
  285. # Uses the builtin echo, so should not put the passphrase into
  286. # the process table. I think. --dkg
  287. echo "$PASS" > "$fifo"
  288. fi
  289. }
  290. # remove all lines with specified string from specified file
  291. remove_line() {
  292. local file
  293. local lines
  294. local tempfile
  295. file="$1"
  296. shift
  297. if [ ! -e "$file" ] ; then
  298. return 1
  299. fi
  300. if (($# == 1)) ; then
  301. lines=$(grep -F "$1" "$file") || true
  302. else
  303. lines=$(grep -F "$1" "$file" | grep -F "$2") || true
  304. fi
  305. # if the string was found, remove it
  306. if [ "$lines" ] ; then
  307. log debug "removing matching key lines..."
  308. tempfile=$(mktemp "${file}.XXXXXXX") || \
  309. failure "Unable to make temp file '${file}.XXXXXXX'"
  310. grep -v -x -F "$lines" "$file" >"$tempfile" || :
  311. mv -f "$tempfile" "$file"
  312. fi
  313. }
  314. # remove all lines with MonkeySphere strings from stdin
  315. remove_monkeysphere_lines() {
  316. egrep -v ' MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2} '
  317. }
  318. # translate ssh-style path variables %h and %u
  319. translate_ssh_variables() {
  320. local uname
  321. local home
  322. uname="$1"
  323. path="$2"
  324. # get the user's home directory
  325. userHome=$(get_homedir "$uname")
  326. # translate '%u' to user name
  327. path=${path/\%u/"$uname"}
  328. # translate '%h' to user home directory
  329. path=${path/\%h/"$userHome"}
  330. echo "$path"
  331. }
  332. # test that a string to conforms to GPG's expiration format
  333. test_gpg_expire() {
  334. echo "$1" | egrep -q "^[0-9]+[mwy]?$"
  335. }
  336. # touch a key file if it doesn't exist, including creating needed
  337. # directories with correct permissions
  338. touch_key_file_or_fail() {
  339. local keyFile="$1"
  340. local newUmask
  341. if [ ! -f "$keyFile" ]; then
  342. # make sure to create files and directories with the
  343. # appropriate write bits turned off:
  344. newUmask=$(printf "%04o" $(( 0$(umask) | 0022 )) )
  345. [ -d $(dirname "$keyFile") ] \
  346. || (umask "$newUmask" && mkdir -p -m 0700 $(dirname "$keyFile") ) \
  347. || failure "Could not create path to $keyFile"
  348. # make sure to create this file with the appropriate bits turned off:
  349. (umask "$newUmask" && touch "$keyFile") \
  350. || failure "Unable to create $keyFile"
  351. fi
  352. }
  353. # check that a file is properly owned, and that all it's parent
  354. # directories are not group/other writable
  355. check_key_file_permissions() {
  356. local uname
  357. local path
  358. uname="$1"
  359. path="$2"
  360. if [ "$STRICT_MODES" = 'false' ] ; then
  361. log debug "skipping path permission check for '$path' because STRICT_MODES is false..."
  362. return 0
  363. fi
  364. log debug "checking path permission '$path'..."
  365. "${SYSSHAREDIR}/checkperms" "$uname" "$path"
  366. }
  367. # return a list of all users on the system
  368. list_users() {
  369. if type getent &>/dev/null ; then
  370. # for linux and FreeBSD systems
  371. getent passwd | cut -d: -f1
  372. elif type dscl &>/dev/null ; then
  373. # for Darwin systems
  374. dscl localhost -list /Search/Users
  375. else
  376. failure "Neither getent or dscl is in the path! Could not determine list of users."
  377. fi
  378. }
  379. # take one argument, a service name. in response, print a series of
  380. # lines, each with a unique numeric port number that might be
  381. # associated with that service name. (e.g. in: "https", out: "443")
  382. # if nothing is found, print nothing, and return 0.
  383. #
  384. # return 1 if there was an error in the search somehow
  385. get_port_for_service() {
  386. [[ "$1" =~ ^[a-z0-9]([a-z0-9-]*[a-z0-9])?$ ]] || \
  387. failure $(printf "This is not a valid service name: '%s'" "$1")
  388. if type getent &>/dev/null ; then
  389. # for linux and FreeBSD systems (getent returns 2 if not found, 0 on success, 1 or 3 on various failures)
  390. (getent services "$service" || if [ "$?" -eq 2 ] ; then true ; else false; fi) | awk '{ print $2 }' | cut -f1 -d/ | sort -u
  391. elif [ -r /etc/services ] ; then
  392. # fall back to /etc/services for systems that don't have getent (MacOS?)
  393. # FIXME: doesn't handle aliases like "null" (or "http"?), which don't show up at the beginning of the line.
  394. awk $(printf '/^%s[[:space:]]/{ print $2 }' "$1") /etc/services | cut -f1 -d/ | sort -u
  395. else
  396. return 1
  397. fi
  398. }
  399. # return the path to the home directory of a user
  400. get_homedir() {
  401. local uname=${1:-`whoami`}
  402. eval "echo ~${uname}"
  403. }
  404. # return the primary group of a user
  405. get_primary_group() {
  406. local uname=${1:-`whoami`}
  407. groups "$uname" | sed 's/^..* : //' | awk '{ print $1 }'
  408. }
  409. ### CONVERSION UTILITIES
  410. # output the ssh key for a given key ID
  411. gpg2ssh() {
  412. local keyID
  413. keyID="$1"
  414. gpg --export --no-armor "$keyID" | openpgp2ssh "$keyID" 2>/dev/null
  415. }
  416. # output known_hosts line from ssh key
  417. ssh2known_hosts() {
  418. local host
  419. local port
  420. local key
  421. # FIXME this does not properly deal with IPv6 hosts using the
  422. # standard port (because it's unclear whether their final
  423. # colon-delimited address section is a port number or an address
  424. # string)
  425. host=${1%:*}
  426. port=${1##*:}
  427. key="$2"
  428. # specify the host and port properly for new ssh known_hosts
  429. # format
  430. if [ "$port" != "$host" ] ; then
  431. host="[${host}]:${port}"
  432. fi
  433. # hash if specified
  434. if [ "$HASH_KNOWN_HOSTS" = 'true' ] ; then
  435. if (type ssh-keygen >/dev/null) ; then
  436. log verbose "hashing known_hosts line"
  437. # FIXME: this is really hackish cause
  438. # ssh-keygen won't hash from stdin to
  439. # stdout
  440. tmpfile=$(mktemp ${TMPDIR:-/tmp}/tmp.XXXXXXXXXX)
  441. printf "%s %s MonkeySphere%s\n" "$host" "$key" "$DATE" \
  442. > "$tmpfile"
  443. ssh-keygen -H -f "$tmpfile" 2>/dev/null
  444. if [[ "$keyFile" == '-' ]] ; then
  445. cat "$tmpfile"
  446. else
  447. cat "$tmpfile" >> "$keyFile"
  448. fi
  449. rm -f "$tmpfile" "${tmpfile}.old"
  450. # FIXME: we could do this without needing ssh-keygen.
  451. # hashed known_hosts looks like: |1|X|Y where 1 means SHA1
  452. # (nothing else is defined in openssh sources), X is the
  453. # salt (same length as the digest output), base64-encoded,
  454. # and Y is the digested hostname (also base64-encoded).
  455. # see hostfile.{c,h} in openssh sources.
  456. else
  457. log error "Cannot hash known_hosts line as requested."
  458. fi
  459. else
  460. printf "%s %s MonkeySphere%s\n" "$host" "$key" "$DATE"
  461. fi
  462. }
  463. # output authorized_keys line from ssh key
  464. ssh2authorized_keys() {
  465. local userID="$1"
  466. local key="$2"
  467. if [[ "$AUTHORIZED_KEYS_OPTIONS" ]]; then
  468. printf "%s %s MonkeySphere%s %s\n" "$AUTHORIZED_KEYS_OPTIONS" "$key" "$DATE" "$userID"
  469. else
  470. printf "%s MonkeySphere%s %s\n" "$key" "$DATE" "$userID"
  471. fi
  472. }
  473. # convert key from gpg to ssh known_hosts format
  474. gpg2known_hosts() {
  475. local host
  476. local keyID
  477. local key
  478. host="$1"
  479. keyID="$2"
  480. key=$(gpg2ssh "$keyID")
  481. # NOTE: it seems that ssh-keygen -R removes all comment fields from
  482. # all lines in the known_hosts file. why?
  483. # NOTE: just in case, the COMMENT can be matched with the
  484. # following regexp:
  485. # '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$'
  486. printf "%s %s MonkeySphere%s\n" "$host" "$key" "$DATE"
  487. }
  488. # convert key from gpg to ssh authorized_keys format
  489. gpg2authorized_keys() {
  490. local userID
  491. local keyID
  492. local key
  493. userID="$1"
  494. keyID="$2"
  495. key=$(gpg2ssh "$keyID")
  496. # NOTE: just in case, the COMMENT can be matched with the
  497. # following regexp:
  498. # '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$'
  499. printf "%s MonkeySphere%s %s\n" "$key" "$DATE" "$userID"
  500. }
  501. ### GPG UTILITIES
  502. # script to determine if gpg version is equal to or greater than specified version
  503. is_gpg_version_greater_equal() {
  504. local gpgVersion=$(gpg --version | head -1 | awk '{ print $3 }')
  505. local latest=$(printf '%s\n%s\n' "$1" "$gpgVersion" \
  506. | tr '.' ' ' | sort -g -k1 -k2 -k3 \
  507. | tail -1 | tr ' ' '.')
  508. [[ "$gpgVersion" == "$latest" ]]
  509. }
  510. # retrieve all keys with given user id from keyserver
  511. gpg_fetch_userid() {
  512. local returnCode=0
  513. local userID
  514. local foundkeyids
  515. if [ "$CHECK_KEYSERVER" != 'true' ] ; then
  516. return 0
  517. fi
  518. userID="$1"
  519. log verbose " checking keyserver $KEYSERVER... "
  520. foundkeyids="$(echo | \
  521. gpg --quiet --batch --with-colons \
  522. --command-fd 0 --keyserver "$KEYSERVER" \
  523. --search ="$userID" 2>/dev/null)"
  524. returnCode="$?"
  525. if [ "$returnCode" != 0 ] ; then
  526. log error "Failure ($returnCode) searching keyserver $KEYSERVER for user id '$userID'"
  527. else
  528. log debug " keyserver raw output:
  529. -----
  530. $foundkeyids
  531. -----"
  532. foundkeyids="$(printf "%s" "$foundkeyids" | grep '^pub:' | cut -f2 -d: | sed 's/^/0x/')"
  533. log verbose " Found keyids on keyserver: $(printf "%s" "$foundkeyids" | tr '\n' ' ')"
  534. if [ -n "$foundkeyids" ]; then
  535. echo | gpg --quiet --batch --with-colons \
  536. --command-fd 0 --keyserver "$KEYSERVER" \
  537. --recv-keys $foundkeyids &>/dev/null
  538. returnCode="$?"
  539. if [ "$returnCode" != 0 ] ; then
  540. log error "Failure ($returnCode) receiving keyids ($foundkeyids) from keyserver $KEYSERVER"
  541. fi
  542. fi
  543. fi
  544. return "$returnCode"
  545. }
  546. ########################################################################
  547. ### PROCESSING FUNCTIONS
  548. # userid and key policy checking
  549. # the following checks policy on the returned keys
  550. # - checks that full key has appropriate valididy (u|f)
  551. # - checks key has specified capability (REQUIRED_KEY_CAPABILITY)
  552. # - checks that requested user ID has appropriate validity
  553. # (see /usr/share/doc/gnupg/DETAILS.gz)
  554. # output is one line for every found key, in the following format:
  555. #
  556. # flag:sshKey
  557. #
  558. # "flag" is an acceptability flag, 0 = ok, 1 = bad
  559. # "sshKey" is the relevant OpenPGP key, in the form accepted by OpenSSH
  560. #
  561. # all log output must go to stderr, as stdout is used to pass the
  562. # flag:sshKey to the calling function.
  563. process_user_id() {
  564. local returnCode=0
  565. local userID="$1"
  566. local requiredCapability
  567. local requiredPubCapability
  568. local gpgOut
  569. local type
  570. local validity
  571. local keyid
  572. local uidfpr
  573. local usage
  574. local keyOK
  575. local uidOK
  576. local lastKey
  577. local lastKeyOK
  578. local fingerprint
  579. # set the required key capability based on the mode
  580. requiredCapability=${REQUIRED_KEY_CAPABILITY:="a"}
  581. requiredPubCapability=$(echo "$requiredCapability" | tr "[:lower:]" "[:upper:]")
  582. # fetch the user ID if necessary/requested
  583. gpg_fetch_userid "$userID"
  584. # output gpg info for (exact) userid and store
  585. gpgOut=$(gpg --list-key --fixed-list-mode --with-colons \
  586. --with-fingerprint --with-fingerprint \
  587. ="$userID" 2>/dev/null) || returnCode="$?"
  588. # if the gpg query return code is not 0, return 1
  589. if [ "$returnCode" -ne 0 ] ; then
  590. log verbose " no primary keys found."
  591. return 1
  592. fi
  593. # loop over all lines in the gpg output and process.
  594. echo "$gpgOut" | cut -d: -f1,2,5,10,12 | \
  595. while IFS=: read -r type validity keyid uidfpr usage ; do
  596. # process based on record type
  597. case $type in
  598. 'pub') # primary keys
  599. # new key, wipe the slate
  600. keyOK=
  601. uidOK=
  602. lastKey=pub
  603. lastKeyOK=
  604. fingerprint=
  605. log verbose " primary key found: $keyid"
  606. # if overall key is not valid, skip
  607. if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
  608. log debug " - unacceptable primary key validity ($validity)."
  609. continue
  610. fi
  611. # if overall key is disabled, skip
  612. if check_capability "$usage" 'D' ; then
  613. log debug " - key disabled."
  614. continue
  615. fi
  616. # if overall key capability is not ok, skip
  617. if ! check_capability "$usage" $requiredPubCapability ; then
  618. log debug " - unacceptable primary key capability ($usage)."
  619. continue
  620. fi
  621. # mark overall key as ok
  622. keyOK=true
  623. # mark primary key as ok if capability is ok
  624. if check_capability "$usage" $requiredCapability ; then
  625. lastKeyOK=true
  626. fi
  627. ;;
  628. 'uid') # user ids
  629. if [ "$lastKey" != pub ] ; then
  630. log verbose " ! got a user ID after a sub key?! user IDs should only follow primary keys!"
  631. continue
  632. fi
  633. # if an acceptable user ID was already found, skip
  634. if [ "$uidOK" = 'true' ] ; then
  635. continue
  636. fi
  637. # if the user ID does matches...
  638. if [ "$(echo "$uidfpr" | gpg_unescape)" = "$userID" ] ; then
  639. # and the user ID validity is ok
  640. if [ "$validity" = 'u' -o "$validity" = 'f' ] ; then
  641. # mark user ID acceptable
  642. uidOK=true
  643. else
  644. log debug " - unacceptable user ID validity ($validity)."
  645. fi
  646. else
  647. continue
  648. fi
  649. # output a line for the primary key
  650. # 0 = ok, 1 = bad
  651. if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
  652. log verbose " * acceptable primary key."
  653. if [ -z "$sshKey" ] ; then
  654. log verbose " ! primary key could not be translated (not RSA?)."
  655. else
  656. echo "0:${sshKey}"
  657. fi
  658. else
  659. log debug " - unacceptable primary key."
  660. if [ -z "$sshKey" ] ; then
  661. log debug " ! primary key could not be translated (not RSA?)."
  662. else
  663. echo "1:${sshKey}"
  664. fi
  665. fi
  666. ;;
  667. 'sub') # sub keys
  668. # unset acceptability of last key
  669. lastKey=sub
  670. lastKeyOK=
  671. fingerprint=
  672. # don't bother with sub keys if the primary key is not valid
  673. if [ "$keyOK" != true ] ; then
  674. continue
  675. fi
  676. # don't bother with sub keys if no user ID is acceptable:
  677. if [ "$uidOK" != true ] ; then
  678. continue
  679. fi
  680. # if sub key validity is not ok, skip
  681. if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
  682. log debug " - unacceptable sub key validity ($validity)."
  683. continue
  684. fi
  685. # if sub key capability is not ok, skip
  686. if ! check_capability "$usage" $requiredCapability ; then
  687. log debug " - unacceptable sub key capability ($usage)."
  688. continue
  689. fi
  690. # mark sub key as ok
  691. lastKeyOK=true
  692. ;;
  693. 'fpr') # key fingerprint
  694. fingerprint="$uidfpr"
  695. sshKey=$(gpg2ssh "$fingerprint")
  696. # if the last key was the pub key, skip
  697. if [ "$lastKey" = pub ] ; then
  698. continue
  699. fi
  700. # output a line for the sub key
  701. # 0 = ok, 1 = bad
  702. if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
  703. log verbose " * acceptable sub key."
  704. if [ -z "$sshKey" ] ; then
  705. log error " ! sub key could not be translated (not RSA?)."
  706. else
  707. echo "0:${sshKey}"
  708. fi
  709. else
  710. log debug " - unacceptable sub key."
  711. if [ -z "$sshKey" ] ; then
  712. log debug " ! sub key could not be translated (not RSA?)."
  713. else
  714. echo "1:${sshKey}"
  715. fi
  716. fi
  717. ;;
  718. esac
  719. done | sort -t: -k1 -n -r
  720. # NOTE: this last sort is important so that the "good" keys (key
  721. # flag '0') come last. This is so that they take precedence when
  722. # being processed in the key files over "bad" keys (key flag '1')
  723. }
  724. process_keys_for_file() {
  725. local keyFile="$1"
  726. local userID="$2"
  727. local host
  728. local ok
  729. local sshKey
  730. local keyLine
  731. log verbose "processing: $userID"
  732. log debug "key file: $keyFile"
  733. IFS=$'\n'
  734. for line in $(process_user_id "$userID") ; do
  735. ok=${line%%:*}
  736. sshKey=${line#*:}
  737. if [ -z "$sshKey" ] ; then
  738. continue
  739. fi
  740. # remove the old key line
  741. if [[ "$keyFile" != '-' ]] ; then
  742. case "$FILE_TYPE" in
  743. ('authorized_keys')
  744. remove_line "$keyFile" "$sshKey"
  745. ;;
  746. ('known_hosts')
  747. host=${userID#ssh://}
  748. remove_line "$keyFile" "$host" "$sshKey"
  749. ;;
  750. esac
  751. fi
  752. ((++KEYS_PROCESSED))
  753. # if key OK, add new key line
  754. if [ "$ok" -eq '0' ] ; then
  755. case "$FILE_TYPE" in
  756. ('raw')
  757. keyLine="$sshKey"
  758. ;;
  759. ('authorized_keys')
  760. keyLine=$(ssh2authorized_keys "$userID" "$sshKey")
  761. ;;
  762. ('known_hosts')
  763. host=${userID#ssh://}
  764. keyLine=$(ssh2known_hosts "$host" "$sshKey")
  765. ;;
  766. esac
  767. echo "key line: $keyLine" | log debug
  768. if [[ "$keyFile" == '-' ]] ; then
  769. echo "$keyLine"
  770. else
  771. log debug "adding key line to file..."
  772. echo "$keyLine" >>"$keyFile"
  773. fi
  774. ((++KEYS_VALID))
  775. fi
  776. done
  777. log debug "KEYS_PROCESSED=$KEYS_PROCESSED"
  778. log debug "KEYS_VALID=$KEYS_VALID"
  779. }
  780. # process an authorized_user_ids file on stdin for authorized_keys
  781. process_authorized_user_ids() {
  782. local authorizedKeys="$1"
  783. declare -i nline=0
  784. local line
  785. declare -a userIDs
  786. declare -a koptions
  787. # extract user IDs from authorized_user_ids file
  788. IFS=$'\n'
  789. while read line ; do
  790. case "$line" in
  791. ("#"*)
  792. continue
  793. ;;
  794. (" "*|$'\t'*)
  795. if [[ -z ${koptions[${nline}]} ]]; then
  796. koptions[${nline}]=$(echo $line | sed 's/^[ ]*//;s/[ ]$//;')
  797. else
  798. koptions[${nline}]="${koptions[${nline}]},$(echo $line | sed 's/^[ ]*//;s/[ ]$//;')"
  799. fi
  800. ;;
  801. (*)
  802. ((++nline))
  803. userIDs[${nline}]="$line"
  804. unset koptions[${nline}] || true
  805. ;;
  806. esac
  807. done
  808. for i in $(seq 1 $nline); do
  809. AUTHORIZED_KEYS_OPTIONS="${koptions[$i]}" FILE_TYPE='authorized_keys' process_keys_for_file "$authorizedKeys" "${userIDs[$i]}" || returnCode="$?"
  810. done
  811. }
  812. # takes a gpg key or keys on stdin, and outputs a list of
  813. # fingerprints, one per line:
  814. list_primary_fingerprints() {
  815. local fake=$(msmktempdir)
  816. trap "rm -rf $fake" EXIT
  817. GNUPGHOME="$fake" gpg --no-tty --quiet --import --ignore-time-conflict 2>/dev/null
  818. GNUPGHOME="$fake" gpg --with-colons --fingerprint --list-keys | \
  819. awk -F: '/^fpr:/{ print $10 }'
  820. trap - EXIT
  821. rm -rf "$fake"
  822. }
  823. # takes an OpenPGP key or set of keys on stdin, a fingerprint or other
  824. # key identifier as $1, and outputs the gpg-formatted information for
  825. # the requested keys from the material on stdin
  826. get_cert_info() {
  827. local fake=$(msmktempdir)
  828. trap "rm -rf $fake" EXIT
  829. GNUPGHOME="$fake" gpg --no-tty --quiet --import --ignore-time-conflict 2>/dev/null
  830. GNUPGHOME="$fake" gpg --with-colons --fingerprint --fixed-list-mode --list-keys "$1"
  831. trap - EXIT
  832. rm -rf "$fake"
  833. }
  834. check_cruft_file() {
  835. local loc="$1"
  836. local version="$2"
  837. if [ -e "$loc" ] ; then
  838. 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
  839. fi
  840. }
  841. check_upgrade_dir() {
  842. local loc="$1"
  843. local version="$2"
  844. if [ -d "$loc" ] ; then
  845. 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
  846. fi
  847. }
  848. ## look for cruft from old versions of the monkeysphere, and notice if
  849. ## upgrades have not been run:
  850. report_cruft() {
  851. check_upgrade_dir "${SYSCONFIGDIR}/gnupg-host" 0.23
  852. check_upgrade_dir "${SYSCONFIGDIR}/gnupg-authentication" 0.23
  853. check_cruft_file "${SYSCONFIGDIR}/gnupg-authentication.conf" 0.23
  854. check_cruft_file "${SYSCONFIGDIR}/gnupg-host.conf" 0.23
  855. local found=
  856. for foo in "${SYSDATADIR}/backup-from-"*"-transition" ; do
  857. if [ -d "$foo" ] ; then
  858. printf "! %s\n" "$foo" | log info
  859. found=true
  860. fi
  861. done
  862. if [ "$found" ] ; then
  863. 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
  864. fi
  865. }