summaryrefslogtreecommitdiff
path: root/src/share/common
blob: b2dcd35d98628ed56ba6472b78f7b7444ab8e396 (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. ### COMMON VARIABLES
  15. # managed directories
  16. SYSCONFIGDIR=${MONKEYSPHERE_SYSCONFIGDIR:-"/etc/monkeysphere"}
  17. export SYSCONFIGDIR
  18. # default log level
  19. LOG_LEVEL="INFO"
  20. # default keyserver
  21. KEYSERVER="pool.sks-keyservers.net"
  22. # whether or not to check keyservers by defaul
  23. CHECK_KEYSERVER="true"
  24. # default monkeysphere user
  25. MONKEYSPHERE_USER="monkeysphere"
  26. # default about whether or not to prompt
  27. PROMPT="true"
  28. ########################################################################
  29. ### UTILITY FUNCTIONS
  30. # output version info
  31. version() {
  32. cat "${SYSSHAREDIR}/VERSION"
  33. }
  34. # failure function. exits with code 255, unless specified otherwise.
  35. failure() {
  36. [ "$1" ] && echo "$1" >&2
  37. exit ${2:-'255'}
  38. }
  39. # write output to stderr based on specified LOG_LEVEL the first
  40. # parameter is the priority of the output, and everything else is what
  41. # is echoed to stderr. If there is nothing else, then output comes
  42. # from stdin, and is not prefaced by log prefix.
  43. log() {
  44. local priority
  45. local level
  46. local output
  47. local alllevels
  48. local found=
  49. # don't include SILENT in alllevels: it's handled separately
  50. # list in decreasing verbosity (all caps).
  51. # separate with $IFS explicitly, since we do some fancy footwork
  52. # elsewhere.
  53. alllevels="DEBUG${IFS}VERBOSE${IFS}INFO${IFS}ERROR"
  54. # translate lowers to uppers in global log level
  55. LOG_LEVEL=$(echo "$LOG_LEVEL" | tr "[:lower:]" "[:upper:]")
  56. # just go ahead and return if the log level is silent
  57. if [ "$LOG_LEVEL" = 'SILENT' ] ; then
  58. return
  59. fi
  60. for level in $alllevels ; do
  61. if [ "$LOG_LEVEL" = "$level" ] ; then
  62. found=true
  63. fi
  64. done
  65. if [ -z "$found" ] ; then
  66. # default to INFO:
  67. LOG_LEVEL=INFO
  68. fi
  69. # get priority from first parameter, translating all lower to
  70. # uppers
  71. priority=$(echo "$1" | tr "[:lower:]" "[:upper:]")
  72. shift
  73. # scan over available levels
  74. for level in $alllevels ; do
  75. # output if the log level matches, set output to true
  76. # this will output for all subsequent loops as well.
  77. if [ "$LOG_LEVEL" = "$level" ] ; then
  78. output=true
  79. fi
  80. if [ "$priority" = "$level" -a "$output" = 'true' ] ; then
  81. if [ "$1" ] ; then
  82. echo -n "ms: " >&2
  83. echo "$@" >&2
  84. else
  85. cat >&2
  86. fi
  87. fi
  88. done
  89. }
  90. # run command as monkeysphere user
  91. su_monkeysphere_user() {
  92. # our main goal here is to run the given command as the the
  93. # monkeysphere user, but without prompting for any sort of
  94. # authentication. If this is not possible, we should just fail.
  95. # FIXME: our current implementation is overly restrictive, because
  96. # there may be some su PAM configurations that would allow su
  97. # "$MONKEYSPHERE_USER" -c "$@" to Just Work without prompting,
  98. # allowing specific users to invoke commands which make use of
  99. # this user.
  100. # chpst (from runit) would be nice to use, but we don't want to
  101. # introduce an extra dependency just for this. This may be a
  102. # candidate for re-factoring if we switch implementation languages.
  103. case $(id -un) in
  104. # if monkeysphere user, run the command under bash
  105. "$MONKEYSPHERE_USER")
  106. bash -c "$@"
  107. ;;
  108. # if root, su command as monkeysphere user
  109. 'root')
  110. su "$MONKEYSPHERE_USER" -c "$@"
  111. ;;
  112. # otherwise, fail
  113. *)
  114. log error "non-privileged user."
  115. ;;
  116. esac
  117. }
  118. # cut out all comments(#) and blank lines from standard input
  119. meat() {
  120. grep -v -e "^[[:space:]]*#" -e '^$' "$1"
  121. }
  122. # cut a specified line from standard input
  123. cutline() {
  124. head --line="$1" "$2" | tail -1
  125. }
  126. # make a temporary directory
  127. msmktempdir() {
  128. mktemp -d ${TMPDIR:-/tmp}/monkeysphere.XXXXXXXXXX
  129. }
  130. # make a temporary file
  131. msmktempfile() {
  132. mktemp ${TMPDIR:-/tmp}/monkeysphere.XXXXXXXXXX
  133. }
  134. # this is a wrapper for doing lock functions.
  135. #
  136. # it lets us depend on either lockfile-progs (preferred) or procmail's
  137. # lockfile, and should
  138. lock() {
  139. local use_lockfileprogs=true
  140. local action="$1"
  141. local file="$2"
  142. if ! ( which lockfile-create >/dev/null 2>/dev/null ) ; then
  143. if ! ( which lockfile >/dev/null ); then
  144. failure "Neither lockfile-create nor lockfile are in the path!"
  145. fi
  146. use_lockfileprogs=
  147. fi
  148. case "$action" in
  149. create)
  150. if [ -n "$use_lockfileprogs" ] ; then
  151. lockfile-create "$file" || failure "unable to lock '$file'"
  152. else
  153. lockfile -r 20 "${file}.lock" || failure "unable to lock '$file'"
  154. fi
  155. log debug "lock created on '$file'."
  156. ;;
  157. touch)
  158. if [ -n "$use_lockfileprogs" ] ; then
  159. lockfile-touch --oneshot "$file"
  160. else
  161. : Nothing to do here
  162. fi
  163. log debug "lock touched on '$file'."
  164. ;;
  165. remove)
  166. if [ -n "$use_lockfileprogs" ] ; then
  167. lockfile-remove "$file"
  168. else
  169. rm -f "${file}.lock"
  170. fi
  171. log debug "lock removed on '$file'."
  172. ;;
  173. *)
  174. failure "bad argument for lock subfunction '$action'"
  175. esac
  176. }
  177. # for portability, between gnu date and BSD date.
  178. # arguments should be: number longunits format
  179. # e.g. advance_date 20 seconds +%F
  180. advance_date() {
  181. local gnutry
  182. local number="$1"
  183. local longunits="$2"
  184. local format="$3"
  185. local shortunits
  186. # try things the GNU way first
  187. if date -d "$number $longunits" "$format" >/dev/null 2>&1; then
  188. date -d "$number $longunits" "$format"
  189. else
  190. # otherwise, convert to (a limited version of) BSD date syntax:
  191. case "$longunits" in
  192. years)
  193. shortunits=y
  194. ;;
  195. months)
  196. shortunits=m
  197. ;;
  198. weeks)
  199. shortunits=w
  200. ;;
  201. days)
  202. shortunits=d
  203. ;;
  204. hours)
  205. shortunits=H
  206. ;;
  207. minutes)
  208. shortunits=M
  209. ;;
  210. seconds)
  211. shortunits=S
  212. ;;
  213. *)
  214. # this is a longshot, and will likely fail; oh well.
  215. shortunits="$longunits"
  216. esac
  217. date "-v+${number}${shortunits}" "$format"
  218. fi
  219. }
  220. # check that characters are in a string (in an AND fashion).
  221. # used for checking key capability
  222. # check_capability capability a [b...]
  223. check_capability() {
  224. local usage
  225. local capcheck
  226. usage="$1"
  227. shift 1
  228. for capcheck ; do
  229. if echo "$usage" | grep -q -v "$capcheck" ; then
  230. return 1
  231. fi
  232. done
  233. return 0
  234. }
  235. # hash of a file
  236. file_hash() {
  237. md5sum "$1" 2> /dev/null
  238. }
  239. # convert escaped characters in pipeline from gpg output back into
  240. # original character
  241. # FIXME: undo all escape character translation in with-colons gpg
  242. # output
  243. gpg_unescape() {
  244. sed 's/\\x3a/:/g'
  245. }
  246. # convert nasty chars into gpg-friendly form in pipeline
  247. # FIXME: escape everything, not just colons!
  248. gpg_escape() {
  249. sed 's/:/\\x3a/g'
  250. }
  251. # prompt for GPG-formatted expiration, and emit result on stdout
  252. get_gpg_expiration() {
  253. local keyExpire
  254. keyExpire="$1"
  255. if [ -z "$keyExpire" -a "$PROMPT" = 'true' ]; then
  256. cat >&2 <<EOF
  257. Please specify how long the key should be valid.
  258. 0 = key does not expire
  259. <n> = key expires in n days
  260. <n>w = key expires in n weeks
  261. <n>m = key expires in n months
  262. <n>y = key expires in n years
  263. EOF
  264. while [ -z "$keyExpire" ] ; do
  265. read -p "Key is valid for? (0) " keyExpire
  266. if ! test_gpg_expire ${keyExpire:=0} ; then
  267. echo "invalid value" >&2
  268. unset keyExpire
  269. fi
  270. done
  271. elif ! test_gpg_expire "$keyExpire" ; then
  272. failure "invalid key expiration value '$keyExpire'."
  273. fi
  274. echo "$keyExpire"
  275. }
  276. passphrase_prompt() {
  277. local prompt="$1"
  278. local fifo="$2"
  279. local PASS
  280. if [ "$DISPLAY" ] && which "${SSH_ASKPASS:-ssh-askpass}" >/dev/null; then
  281. "${SSH_ASKPASS:-ssh-askpass}" "$prompt" > "$fifo"
  282. else
  283. read -s -p "$prompt" PASS
  284. # Uses the builtin echo, so should not put the passphrase into
  285. # the process table. I think. --dkg
  286. echo "$PASS" > "$fifo"
  287. fi
  288. }
  289. test_gnu_dummy_s2k_extension() {
  290. # this block contains a demonstration private key that has had the
  291. # primary key stripped out using the GNU S2K extension known as
  292. # "gnu-dummy" (see /usr/share/doc/gnupg/DETAILS.gz). The subkey is
  293. # present in cleartext, however.
  294. # openpgp2ssh will be able to deal with this based on whether the
  295. # local copy of GnuTLS contains read_s2k support that can handle it.
  296. # read up on that here:
  297. # http://lists.gnu.org/archive/html/gnutls-devel/2008-08/msg00005.html
  298. echo "
  299. -----BEGIN PGP PRIVATE KEY BLOCK-----
  300. Version: GnuPG v1.4.9 (GNU/Linux)
  301. lQCVBEO3YdABBACRqqEnucag4+vyZny2M67Pai5+5suIRRvY+Ly8Ms5MvgCi3EVV
  302. xT05O/+0ShiRaf+QicCOFrhbU9PZzzU+seEvkeW2UCu4dQfILkmj+HBEIltGnHr3
  303. G0yegHj5pnqrcezERURf2e17gGFWX91cXB9Cm721FPXczuKraphKwCA9PwARAQAB
  304. /gNlAkdOVQG0OURlbW9uc3RyYXRpb24gS2V5IGZvciBTMksgR05VIGV4dGVuc2lv
  305. biAxMDAxIC0tIGdudS1kdW1teYi8BBMBAgAmBQJDt2HQAhsDBQkB4TOABgsJCAcD
  306. AgQVAggDBBYCAwECHgECF4AACgkQQZUwSa4UDezTOQP/TMQXUVrWzHYZGopoPZ2+
  307. ZS3qddiznBHsgb7MGYg1KlTiVJSroDUBCHIUJvdQKZV9zrzrFl47D07x6hGyUPHV
  308. aZXvuITW8t1o5MMHkCy3pmJ2KgfDvdUxrBvLfgPMICA4c6zA0mWquee43syEW9NY
  309. g3q61iPlQwD1J1kX1wlimLCdAdgEQ7dh0AEEANAwa63zlQbuy1Meliy8otwiOa+a
  310. mH6pxxUgUNggjyjO5qx+rl25mMjvGIRX4/L1QwIBXJBVi3SgvJW1COZxZqBYqj9U
  311. 8HVT07mWKFEDf0rZLeUE2jTm16cF9fcW4DQhW+sfYm+hi2sY3HeMuwlUBK9KHfW2
  312. +bGeDzVZ4pqfUEudABEBAAEAA/0bemib+wxub9IyVFUp7nPobjQC83qxLSNzrGI/
  313. RHzgu/5CQi4tfLOnwbcQsLELfker2hYnjsLrT9PURqK4F7udrWEoZ1I1LymOtLG/
  314. 4tNZ7Mnul3wRC2tCn7FKx8sGJwGh/3li8vZ6ALVJAyOia5TZ/buX0+QZzt6+hPKk
  315. 7MU1WQIA4bUBjtrsqDwro94DvPj3/jBnMZbXr6WZIItLNeVDUcM8oHL807Am97K1
  316. ueO/f6v1sGAHG6lVPTmtekqPSTWBfwIA7CGFvEyvSALfB8NUa6jtk27NCiw0csql
  317. kuhCmwXGMVOiryKEfegkIahf2bAd/gnWHPrpWp7bUE20v8YoW22I4wIAhnm5Wr5Q
  318. Sy7EHDUxmJm5TzadFp9gq08qNzHBpXSYXXJ3JuWcL1/awUqp3tE1I6zZ0hZ38Ia6
  319. SdBMN88idnhDPqPoiKUEGAECAA8FAkO3YdACGyAFCQHhM4AACgkQQZUwSa4UDezm
  320. vQP/ZhK+2ly9oI2z7ZcNC/BJRch0/ybQ3haahII8pXXmOThpZohr/LUgoWgCZdXg
  321. vP6yiszNk2tIs8KphCAw7Lw/qzDC2hEORjWO4f46qk73RAgSqG/GyzI4ltWiDhqn
  322. vnQCFl3+QFSe4zinqykHnLwGPMXv428d/ZjkIc2ju8dRsn4=
  323. =CR5w
  324. -----END PGP PRIVATE KEY BLOCK-----
  325. " | openpgp2ssh 4129E89D17C1D591 >/dev/null 2>/dev/null
  326. }
  327. # remove all lines with specified string from specified file
  328. remove_line() {
  329. local file
  330. local string
  331. local tempfile
  332. file="$1"
  333. string="$2"
  334. if [ -z "$file" -o -z "$string" ] ; then
  335. return 1
  336. fi
  337. if [ ! -e "$file" ] ; then
  338. return 1
  339. fi
  340. # if the string is in the file...
  341. if grep -q -F "$string" "$file" 2> /dev/null ; then
  342. tempfile=$(mktemp "${file}.XXXXXXX") || \
  343. failure "Unable to make temp file '${file}.XXXXXXX'"
  344. # remove the line with the string, and return 0
  345. grep -v -F "$string" "$file" >"$tempfile"
  346. cat "$tempfile" > "$file"
  347. rm "$tempfile"
  348. return 0
  349. # otherwise return 1
  350. else
  351. return 1
  352. fi
  353. }
  354. # remove all lines with MonkeySphere strings in file
  355. remove_monkeysphere_lines() {
  356. local file
  357. local tempfile
  358. file="$1"
  359. if [ -z "$file" ] ; then
  360. return 1
  361. fi
  362. if [ ! -e "$file" ] ; then
  363. return 1
  364. fi
  365. tempfile=$(mktemp "${file}.XXXXXXX") || \
  366. failure "Could not make temporary file '${file}.XXXXXXX'."
  367. egrep -v '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$' \
  368. "$file" >"$tempfile"
  369. cat "$tempfile" > "$file"
  370. rm "$tempfile"
  371. }
  372. # translate ssh-style path variables %h and %u
  373. translate_ssh_variables() {
  374. local uname
  375. local home
  376. uname="$1"
  377. path="$2"
  378. # get the user's home directory
  379. userHome=$(getent passwd "$uname" | cut -d: -f6)
  380. # translate '%u' to user name
  381. path=${path/\%u/"$uname"}
  382. # translate '%h' to user home directory
  383. path=${path/\%h/"$userHome"}
  384. echo "$path"
  385. }
  386. # test that a string to conforms to GPG's expiration format
  387. test_gpg_expire() {
  388. echo "$1" | egrep -q "^[0-9]+[mwy]?$"
  389. }
  390. # check that a file is properly owned, and that all it's parent
  391. # directories are not group/other writable
  392. check_key_file_permissions() {
  393. local uname
  394. local path
  395. local stat
  396. local access
  397. local gAccess
  398. local oAccess
  399. # function to check that the given permission corresponds to writability
  400. is_write() {
  401. [ "$1" = "w" ]
  402. }
  403. uname="$1"
  404. path="$2"
  405. log debug "checking path permission '$path'..."
  406. # return 255 if cannot stat file
  407. if ! stat=$(ls -ld "$path" 2>/dev/null) ; then
  408. log error "could not stat path '$path'."
  409. return 255
  410. fi
  411. owner=$(echo "$stat" | awk '{ print $3 }')
  412. gAccess=$(echo "$stat" | cut -c6)
  413. oAccess=$(echo "$stat" | cut -c9)
  414. # return 1 if path has invalid owner
  415. if [ "$owner" != "$uname" -a "$owner" != 'root' ] ; then
  416. log error "improper ownership on path '$path'."
  417. return 1
  418. fi
  419. # return 2 if path has group or other writability
  420. if is_write "$gAccess" || is_write "$oAccess" ; then
  421. log error "improper group or other writability on path '$path'."
  422. return 2
  423. fi
  424. # return zero if all clear, or go to next path
  425. if [ "$path" = '/' ] ; then
  426. return 0
  427. else
  428. check_key_file_permissions "$uname" $(dirname "$path")
  429. fi
  430. }
  431. ### CONVERSION UTILITIES
  432. # output the ssh key for a given key ID
  433. gpg2ssh() {
  434. local keyID
  435. keyID="$1"
  436. gpg --export "$keyID" | openpgp2ssh "$keyID" 2> /dev/null
  437. }
  438. # output known_hosts line from ssh key
  439. ssh2known_hosts() {
  440. local host
  441. local key
  442. host="$1"
  443. key="$2"
  444. echo -n "$host "
  445. echo -n "$key" | tr -d '\n'
  446. echo " MonkeySphere${DATE}"
  447. }
  448. # output authorized_keys line from ssh key
  449. ssh2authorized_keys() {
  450. local userID
  451. local key
  452. userID="$1"
  453. key="$2"
  454. echo -n "$key" | tr -d '\n'
  455. echo " MonkeySphere${DATE} ${userID}"
  456. }
  457. # convert key from gpg to ssh known_hosts format
  458. gpg2known_hosts() {
  459. local host
  460. local keyID
  461. host="$1"
  462. keyID="$2"
  463. # NOTE: it seems that ssh-keygen -R removes all comment fields from
  464. # all lines in the known_hosts file. why?
  465. # NOTE: just in case, the COMMENT can be matched with the
  466. # following regexp:
  467. # '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$'
  468. echo -n "$host "
  469. gpg2ssh "$keyID" | tr -d '\n'
  470. echo " MonkeySphere${DATE}"
  471. }
  472. # convert key from gpg to ssh authorized_keys format
  473. gpg2authorized_keys() {
  474. local userID
  475. local keyID
  476. userID="$1"
  477. keyID="$2"
  478. # NOTE: just in case, the COMMENT can be matched with the
  479. # following regexp:
  480. # '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$'
  481. gpg2ssh "$keyID" | tr -d '\n'
  482. echo " MonkeySphere${DATE} ${userID}"
  483. }
  484. ### GPG UTILITIES
  485. # retrieve all keys with given user id from keyserver
  486. # FIXME: need to figure out how to retrieve all matching keys
  487. # (not just first N (5 in this case))
  488. gpg_fetch_userid() {
  489. local returnCode=0
  490. local userID
  491. if [ "$CHECK_KEYSERVER" != 'true' ] ; then
  492. return 0
  493. fi
  494. userID="$1"
  495. log verbose " checking keyserver $KEYSERVER... "
  496. echo 1,2,3,4,5 | \
  497. gpg --quiet --batch --with-colons \
  498. --command-fd 0 --keyserver "$KEYSERVER" \
  499. --search ="$userID" > /dev/null 2>&1
  500. returnCode="$?"
  501. return "$returnCode"
  502. }
  503. ########################################################################
  504. ### PROCESSING FUNCTIONS
  505. # userid and key policy checking
  506. # the following checks policy on the returned keys
  507. # - checks that full key has appropriate valididy (u|f)
  508. # - checks key has specified capability (REQUIRED_*_KEY_CAPABILITY)
  509. # - checks that requested user ID has appropriate validity
  510. # (see /usr/share/doc/gnupg/DETAILS.gz)
  511. # output is one line for every found key, in the following format:
  512. #
  513. # flag:sshKey
  514. #
  515. # "flag" is an acceptability flag, 0 = ok, 1 = bad
  516. # "sshKey" is the translated gpg key
  517. #
  518. # all log output must go to stderr, as stdout is used to pass the
  519. # flag:sshKey to the calling function.
  520. #
  521. # expects global variable: "MODE"
  522. process_user_id() {
  523. local returnCode=0
  524. local userID
  525. local requiredCapability
  526. local requiredPubCapability
  527. local gpgOut
  528. local type
  529. local validity
  530. local keyid
  531. local uidfpr
  532. local usage
  533. local keyOK
  534. local uidOK
  535. local lastKey
  536. local lastKeyOK
  537. local fingerprint
  538. userID="$1"
  539. # set the required key capability based on the mode
  540. if [ "$MODE" = 'known_hosts' ] ; then
  541. requiredCapability="$REQUIRED_HOST_KEY_CAPABILITY"
  542. elif [ "$MODE" = 'authorized_keys' ] ; then
  543. requiredCapability="$REQUIRED_USER_KEY_CAPABILITY"
  544. fi
  545. requiredPubCapability=$(echo "$requiredCapability" | tr "[:lower:]" "[:upper:]")
  546. # fetch the user ID if necessary/requested
  547. gpg_fetch_userid "$userID"
  548. # output gpg info for (exact) userid and store
  549. gpgOut=$(gpg --list-key --fixed-list-mode --with-colon \
  550. --with-fingerprint --with-fingerprint \
  551. ="$userID" 2>/dev/null) || returnCode="$?"
  552. # if the gpg query return code is not 0, return 1
  553. if [ "$returnCode" -ne 0 ] ; then
  554. log verbose " no primary keys found."
  555. return 1
  556. fi
  557. # loop over all lines in the gpg output and process.
  558. echo "$gpgOut" | cut -d: -f1,2,5,10,12 | \
  559. while IFS=: read -r type validity keyid uidfpr usage ; do
  560. # process based on record type
  561. case $type in
  562. 'pub') # primary keys
  563. # new key, wipe the slate
  564. keyOK=
  565. uidOK=
  566. lastKey=pub
  567. lastKeyOK=
  568. fingerprint=
  569. log verbose " primary key found: $keyid"
  570. # if overall key is not valid, skip
  571. if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
  572. log debug " - unacceptable primary key validity ($validity)."
  573. continue
  574. fi
  575. # if overall key is disabled, skip
  576. if check_capability "$usage" 'D' ; then
  577. log debug " - key disabled."
  578. continue
  579. fi
  580. # if overall key capability is not ok, skip
  581. if ! check_capability "$usage" $requiredPubCapability ; then
  582. log debug " - unacceptable primary key capability ($usage)."
  583. continue
  584. fi
  585. # mark overall key as ok
  586. keyOK=true
  587. # mark primary key as ok if capability is ok
  588. if check_capability "$usage" $requiredCapability ; then
  589. lastKeyOK=true
  590. fi
  591. ;;
  592. 'uid') # user ids
  593. if [ "$lastKey" != pub ] ; then
  594. log verbose " ! got a user ID after a sub key?! user IDs should only follow primary keys!"
  595. continue
  596. fi
  597. # if an acceptable user ID was already found, skip
  598. if [ "$uidOK" = 'true' ] ; then
  599. continue
  600. fi
  601. # if the user ID does matches...
  602. if [ "$(echo "$uidfpr" | gpg_unescape)" = "$userID" ] ; then
  603. # and the user ID validity is ok
  604. if [ "$validity" = 'u' -o "$validity" = 'f' ] ; then
  605. # mark user ID acceptable
  606. uidOK=true
  607. else
  608. log debug " - unacceptable user ID validity ($validity)."
  609. fi
  610. else
  611. continue
  612. fi
  613. # output a line for the primary key
  614. # 0 = ok, 1 = bad
  615. if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
  616. log verbose " * acceptable primary key."
  617. if [ -z "$sshKey" ] ; then
  618. log error " ! primary key could not be translated (not RSA or DSA?)."
  619. else
  620. echo "0:${sshKey}"
  621. fi
  622. else
  623. log debug " - unacceptable primary key."
  624. if [ -z "$sshKey" ] ; then
  625. log debug " ! primary key could not be translated (not RSA or DSA?)."
  626. else
  627. echo "1:${sshKey}"
  628. fi
  629. fi
  630. ;;
  631. 'sub') # sub keys
  632. # unset acceptability of last key
  633. lastKey=sub
  634. lastKeyOK=
  635. fingerprint=
  636. # don't bother with sub keys if the primary key is not valid
  637. if [ "$keyOK" != true ] ; then
  638. continue
  639. fi
  640. # don't bother with sub keys if no user ID is acceptable:
  641. if [ "$uidOK" != true ] ; then
  642. continue
  643. fi
  644. # if sub key validity is not ok, skip
  645. if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
  646. log debug " - unacceptable sub key validity ($validity)."
  647. continue
  648. fi
  649. # if sub key capability is not ok, skip
  650. if ! check_capability "$usage" $requiredCapability ; then
  651. log debug " - unacceptable sub key capability ($usage)."
  652. continue
  653. fi
  654. # mark sub key as ok
  655. lastKeyOK=true
  656. ;;
  657. 'fpr') # key fingerprint
  658. fingerprint="$uidfpr"
  659. sshKey=$(gpg2ssh "$fingerprint")
  660. # if the last key was the pub key, skip
  661. if [ "$lastKey" = pub ] ; then
  662. continue
  663. fi
  664. # output a line for the sub key
  665. # 0 = ok, 1 = bad
  666. if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
  667. log verbose " * acceptable sub key."
  668. if [ -z "$sshKey" ] ; then
  669. log error " ! sub key could not be translated (not RSA or DSA?)."
  670. else
  671. echo "0:${sshKey}"
  672. fi
  673. else
  674. log debug " - unacceptable sub key."
  675. if [ -z "$sshKey" ] ; then
  676. log debug " ! sub key could not be translated (not RSA or DSA?)."
  677. else
  678. echo "1:${sshKey}"
  679. fi
  680. fi
  681. ;;
  682. esac
  683. done | sort -t: -k1 -n -r
  684. # NOTE: this last sort is important so that the "good" keys (key
  685. # flag '0') come last. This is so that they take precedence when
  686. # being processed in the key files over "bad" keys (key flag '1')
  687. }
  688. # process a single host in the known_host file
  689. process_host_known_hosts() {
  690. local host
  691. local userID
  692. local noKey=
  693. local nKeys
  694. local nKeysOK
  695. local ok
  696. local sshKey
  697. local tmpfile
  698. # set the key processing mode
  699. export MODE='known_hosts'
  700. host="$1"
  701. userID="ssh://${host}"
  702. log verbose "processing: $host"
  703. nKeys=0
  704. nKeysOK=0
  705. IFS=$'\n'
  706. for line in $(process_user_id "${userID}") ; do
  707. # note that key was found
  708. nKeys=$((nKeys+1))
  709. ok=$(echo "$line" | cut -d: -f1)
  710. sshKey=$(echo "$line" | cut -d: -f2)
  711. if [ -z "$sshKey" ] ; then
  712. continue
  713. fi
  714. # remove any old host key line, and note if removed nothing is
  715. # removed
  716. remove_line "$KNOWN_HOSTS" "$sshKey" || noKey=true
  717. # if key OK, add new host line
  718. if [ "$ok" -eq '0' ] ; then
  719. # note that key was found ok
  720. nKeysOK=$((nKeysOK+1))
  721. # hash if specified
  722. if [ "$HASH_KNOWN_HOSTS" = 'true' ] ; then
  723. # FIXME: this is really hackish cause ssh-keygen won't
  724. # hash from stdin to stdout
  725. tmpfile=$(mktemp ${TMPDIR:-/tmp}/tmp.XXXXXXXXXX)
  726. ssh2known_hosts "$host" "$sshKey" > "$tmpfile"
  727. ssh-keygen -H -f "$tmpfile" 2> /dev/null
  728. cat "$tmpfile" >> "$KNOWN_HOSTS"
  729. rm -f "$tmpfile" "${tmpfile}.old"
  730. else
  731. ssh2known_hosts "$host" "$sshKey" >> "$KNOWN_HOSTS"
  732. fi
  733. # log if this is a new key to the known_hosts file
  734. if [ "$noKey" ] ; then
  735. log info "* new key for $host added to known_hosts file."
  736. fi
  737. fi
  738. done
  739. # if at least one key was found...
  740. if [ "$nKeys" -gt 0 ] ; then
  741. # if ok keys were found, return 0
  742. if [ "$nKeysOK" -gt 0 ] ; then
  743. return 0
  744. # else return 2
  745. else
  746. return 2
  747. fi
  748. # if no keys were found, return 1
  749. else
  750. return 1
  751. fi
  752. }
  753. # update the known_hosts file for a set of hosts listed on command
  754. # line
  755. update_known_hosts() {
  756. local returnCode=0
  757. local nHosts
  758. local nHostsOK
  759. local nHostsBAD
  760. local fileCheck
  761. local host
  762. # the number of hosts specified on command line
  763. nHosts="$#"
  764. nHostsOK=0
  765. nHostsBAD=0
  766. # touch the known_hosts file so that the file permission check
  767. # below won't fail upon not finding the file
  768. (umask 0022 && touch "$KNOWN_HOSTS")
  769. # check permissions on the known_hosts file path
  770. check_key_file_permissions "$USER" "$KNOWN_HOSTS" || failure
  771. # create a lockfile on known_hosts:
  772. lock create "$KNOWN_HOSTS"
  773. # FIXME: we're discarding any pre-existing EXIT trap; is this bad?
  774. trap "lock remove $KNOWN_HOSTS" EXIT
  775. # note pre update file checksum
  776. fileCheck="$(file_hash "$KNOWN_HOSTS")"
  777. for host ; do
  778. # process the host
  779. process_host_known_hosts "$host" || returnCode="$?"
  780. # note the result
  781. case "$returnCode" in
  782. 0)
  783. nHostsOK=$((nHostsOK+1))
  784. ;;
  785. 2)
  786. nHostsBAD=$((nHostsBAD+1))
  787. ;;
  788. esac
  789. # touch the lockfile, for good measure.
  790. lock touch "$KNOWN_HOSTS"
  791. done
  792. # remove the lockfile and the trap
  793. lock remove "$KNOWN_HOSTS"
  794. trap - EXIT
  795. # note if the known_hosts file was updated
  796. if [ "$(file_hash "$KNOWN_HOSTS")" != "$fileCheck" ] ; then
  797. log debug "known_hosts file updated."
  798. fi
  799. # if an acceptable host was found, return 0
  800. if [ "$nHostsOK" -gt 0 ] ; then
  801. return 0
  802. # else if no ok hosts were found...
  803. else
  804. # if no bad host were found then no hosts were found at all,
  805. # and return 1
  806. if [ "$nHostsBAD" -eq 0 ] ; then
  807. return 1
  808. # else if at least one bad host was found, return 2
  809. else
  810. return 2
  811. fi
  812. fi
  813. }
  814. # process hosts from a known_hosts file
  815. process_known_hosts() {
  816. local hosts
  817. # exit if the known_hosts file does not exist
  818. if [ ! -e "$KNOWN_HOSTS" ] ; then
  819. failure "known_hosts file '$KNOWN_HOSTS' does not exist."
  820. fi
  821. log debug "processing known_hosts file..."
  822. hosts=$(meat "$KNOWN_HOSTS" | cut -d ' ' -f 1 | grep -v '^|.*$' | tr , ' ' | tr '\n' ' ')
  823. if [ -z "$hosts" ] ; then
  824. log debug "no hosts to process."
  825. return
  826. fi
  827. # take all the hosts from the known_hosts file (first
  828. # field), grep out all the hashed hosts (lines starting
  829. # with '|')...
  830. update_known_hosts $hosts
  831. }
  832. # process uids for the authorized_keys file
  833. process_uid_authorized_keys() {
  834. local userID
  835. local nKeys
  836. local nKeysOK
  837. local ok
  838. local sshKey
  839. # set the key processing mode
  840. export MODE='authorized_keys'
  841. userID="$1"
  842. log verbose "processing: $userID"
  843. nKeys=0
  844. nKeysOK=0
  845. IFS=$'\n'
  846. for line in $(process_user_id "$userID") ; do
  847. # note that key was found
  848. nKeys=$((nKeys+1))
  849. ok=$(echo "$line" | cut -d: -f1)
  850. sshKey=$(echo "$line" | cut -d: -f2)
  851. if [ -z "$sshKey" ] ; then
  852. continue
  853. fi
  854. # remove the old host key line
  855. remove_line "$AUTHORIZED_KEYS" "$sshKey"
  856. # if key OK, add new host line
  857. if [ "$ok" -eq '0' ] ; then
  858. # note that key was found ok
  859. nKeysOK=$((nKeysOK+1))
  860. ssh2authorized_keys "$userID" "$sshKey" >> "$AUTHORIZED_KEYS"
  861. fi
  862. done
  863. # if at least one key was found...
  864. if [ "$nKeys" -gt 0 ] ; then
  865. # if ok keys were found, return 0
  866. if [ "$nKeysOK" -gt 0 ] ; then
  867. return 0
  868. # else return 2
  869. else
  870. return 2
  871. fi
  872. # if no keys were found, return 1
  873. else
  874. return 1
  875. fi
  876. }
  877. # update the authorized_keys files from a list of user IDs on command
  878. # line
  879. update_authorized_keys() {
  880. local returnCode=0
  881. local userID
  882. local nIDs
  883. local nIDsOK
  884. local nIDsBAD
  885. local fileCheck
  886. # the number of ids specified on command line
  887. nIDs="$#"
  888. nIDsOK=0
  889. nIDsBAD=0
  890. # check permissions on the authorized_keys file path
  891. check_key_file_permissions "$USER" "$AUTHORIZED_KEYS" || failure
  892. # create a lockfile on authorized_keys
  893. lock create "$AUTHORIZED_KEYS"
  894. # FIXME: we're discarding any pre-existing EXIT trap; is this bad?
  895. trap "lock remove $AUTHORIZED_KEYS" EXIT
  896. # note pre update file checksum
  897. fileCheck="$(file_hash "$AUTHORIZED_KEYS")"
  898. # remove any monkeysphere lines from authorized_keys file
  899. remove_monkeysphere_lines "$AUTHORIZED_KEYS"
  900. for userID ; do
  901. # process the user ID, change return code if key not found for
  902. # user ID
  903. process_uid_authorized_keys "$userID" || returnCode="$?"
  904. # note the result
  905. case "$returnCode" in
  906. 0)
  907. nIDsOK=$((nIDsOK+1))
  908. ;;
  909. 2)
  910. nIDsBAD=$((nIDsBAD+1))
  911. ;;
  912. esac
  913. # touch the lockfile, for good measure.
  914. lock touch "$AUTHORIZED_KEYS"
  915. done
  916. # remove the lockfile and the trap
  917. lock remove "$AUTHORIZED_KEYS"
  918. # remove the trap
  919. trap - EXIT
  920. # note if the authorized_keys file was updated
  921. if [ "$(file_hash "$AUTHORIZED_KEYS")" != "$fileCheck" ] ; then
  922. log debug "authorized_keys file updated."
  923. fi
  924. # if an acceptable id was found, return 0
  925. if [ "$nIDsOK" -gt 0 ] ; then
  926. return 0
  927. # else if no ok ids were found...
  928. else
  929. # if no bad ids were found then no ids were found at all, and
  930. # return 1
  931. if [ "$nIDsBAD" -eq 0 ] ; then
  932. return 1
  933. # else if at least one bad id was found, return 2
  934. else
  935. return 2
  936. fi
  937. fi
  938. }
  939. # process an authorized_user_ids file for authorized_keys
  940. process_authorized_user_ids() {
  941. local line
  942. local nline
  943. local userIDs
  944. authorizedUserIDs="$1"
  945. # exit if the authorized_user_ids file is empty
  946. if [ ! -e "$authorizedUserIDs" ] ; then
  947. failure "authorized_user_ids file '$authorizedUserIDs' does not exist."
  948. fi
  949. # check permissions on the authorized_user_ids file path
  950. check_key_file_permissions "$USER" "$authorizedUserIDs" || failure
  951. log debug "processing authorized_user_ids file..."
  952. if ! meat "$authorizedUserIDs" > /dev/null ; then
  953. log debug " no user IDs to process."
  954. return
  955. fi
  956. nline=0
  957. # extract user IDs from authorized_user_ids file
  958. IFS=$'\n'
  959. for line in $(meat "$authorizedUserIDs") ; do
  960. userIDs["$nline"]="$line"
  961. nline=$((nline+1))
  962. done
  963. update_authorized_keys "${userIDs[@]}"
  964. }
  965. # takes a gpg key or keys on stdin, and outputs a list of
  966. # fingerprints, one per line:
  967. list_primary_fingerprints() {
  968. local fake=$(msmktempdir)
  969. GNUPGHOME="$fake" gpg --no-tty --quiet --import
  970. GNUPGHOME="$fake" gpg --with-colons --fingerprint --list-keys | \
  971. awk -F: '/^fpr:/{ print $10 }'
  972. rm -rf "$fake"
  973. }
  974. check_cruft_file() {
  975. local loc="$1"
  976. local version="$2"
  977. if [ -e "$loc" ] ; then
  978. 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
  979. fi
  980. }
  981. check_upgrade_dir() {
  982. local loc="$1"
  983. local version="$2"
  984. if [ -d "$loc" ] ; then
  985. 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
  986. fi
  987. }
  988. ## look for cruft from old versions of the monkeysphere, and notice if
  989. ## upgrades have not been run:
  990. report_cruft() {
  991. check_upgrade_dir "${SYSCONFIGDIR}/gnupg-host" 0.23
  992. check_upgrade_dir "${SYSCONFIGDIR}/gnupg-authentication" 0.23
  993. check_cruft_file "${SYSCONFIGDIR}/gnupg-authentication.conf" 0.23
  994. check_cruft_file "${SYSCONFIGDIR}/gnupg-host.conf" 0.23
  995. local found=
  996. for foo in "${SYSDATADIR}/backup-from-"*"-transition" ; do
  997. if [ -d "$foo" ] ; then
  998. printf "! %s\n" "$foo" | log info
  999. found=true
  1000. fi
  1001. done
  1002. if [ "$found" ] ; then
  1003. 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
  1004. fi
  1005. }