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