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