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