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