summaryrefslogtreecommitdiff
path: root/src/share/common
blob: 0c26a91133c1cec3a4a15fb8162e294bdb58f5ba (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.1
  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 returnCode=0
  488. local userID
  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 returnCode=0
  522. local userID
  523. local requiredCapability
  524. local requiredPubCapability
  525. local gpgOut
  526. local type
  527. local validity
  528. local keyid
  529. local uidfpr
  530. local usage
  531. local keyOK
  532. local uidOK
  533. local lastKey
  534. local lastKeyOK
  535. local fingerprint
  536. userID="$1"
  537. # set the required key capability based on the mode
  538. if [ "$MODE" = 'known_hosts' ] ; then
  539. requiredCapability="$REQUIRED_HOST_KEY_CAPABILITY"
  540. elif [ "$MODE" = 'authorized_keys' ] ; then
  541. requiredCapability="$REQUIRED_USER_KEY_CAPABILITY"
  542. fi
  543. requiredPubCapability=$(echo "$requiredCapability" | tr "[:lower:]" "[:upper:]")
  544. # fetch the user ID if necessary/requested
  545. gpg_fetch_userid "$userID"
  546. # output gpg info for (exact) userid and store
  547. gpgOut=$(gpg --list-key --fixed-list-mode --with-colon \
  548. --with-fingerprint --with-fingerprint \
  549. ="$userID" 2>/dev/null) || returnCode="$?"
  550. # if the gpg query return code is not 0, return 1
  551. if [ "$returnCode" -ne 0 ] ; then
  552. log verbose " no primary keys found."
  553. return 1
  554. fi
  555. # loop over all lines in the gpg output and process.
  556. echo "$gpgOut" | cut -d: -f1,2,5,10,12 | \
  557. while IFS=: read -r type validity keyid uidfpr usage ; do
  558. # process based on record type
  559. case $type in
  560. 'pub') # primary keys
  561. # new key, wipe the slate
  562. keyOK=
  563. uidOK=
  564. lastKey=pub
  565. lastKeyOK=
  566. fingerprint=
  567. log verbose " primary key found: $keyid"
  568. # if overall key is not valid, skip
  569. if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
  570. log debug " - unacceptable primary key validity ($validity)."
  571. continue
  572. fi
  573. # if overall key is disabled, skip
  574. if check_capability "$usage" 'D' ; then
  575. log debug " - key disabled."
  576. continue
  577. fi
  578. # if overall key capability is not ok, skip
  579. if ! check_capability "$usage" $requiredPubCapability ; then
  580. log debug " - unacceptable primary key capability ($usage)."
  581. continue
  582. fi
  583. # mark overall key as ok
  584. keyOK=true
  585. # mark primary key as ok if capability is ok
  586. if check_capability "$usage" $requiredCapability ; then
  587. lastKeyOK=true
  588. fi
  589. ;;
  590. 'uid') # user ids
  591. if [ "$lastKey" != pub ] ; then
  592. log verbose " ! got a user ID after a sub key?! user IDs should only follow primary keys!"
  593. continue
  594. fi
  595. # if an acceptable user ID was already found, skip
  596. if [ "$uidOK" = 'true' ] ; then
  597. continue
  598. fi
  599. # if the user ID does matches...
  600. if [ "$(echo "$uidfpr" | gpg_unescape)" = "$userID" ] ; then
  601. # and the user ID validity is ok
  602. if [ "$validity" = 'u' -o "$validity" = 'f' ] ; then
  603. # mark user ID acceptable
  604. uidOK=true
  605. else
  606. log debug " - unacceptable user ID validity ($validity)."
  607. fi
  608. else
  609. continue
  610. fi
  611. # output a line for the primary key
  612. # 0 = ok, 1 = bad
  613. if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
  614. log verbose " * acceptable primary key."
  615. if [ -z "$sshKey" ] ; then
  616. log error " ! primary key could not be translated (not RSA or DSA?)."
  617. else
  618. echo "0:${sshKey}"
  619. fi
  620. else
  621. log debug " - unacceptable primary key."
  622. if [ -z "$sshKey" ] ; then
  623. log debug " ! primary key could not be translated (not RSA or DSA?)."
  624. else
  625. echo "1:${sshKey}"
  626. fi
  627. fi
  628. ;;
  629. 'sub') # sub keys
  630. # unset acceptability of last key
  631. lastKey=sub
  632. lastKeyOK=
  633. fingerprint=
  634. # don't bother with sub keys if the primary key is not valid
  635. if [ "$keyOK" != true ] ; then
  636. continue
  637. fi
  638. # don't bother with sub keys if no user ID is acceptable:
  639. if [ "$uidOK" != true ] ; then
  640. continue
  641. fi
  642. # if sub key validity is not ok, skip
  643. if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
  644. log debug " - unacceptable sub key validity ($validity)."
  645. continue
  646. fi
  647. # if sub key capability is not ok, skip
  648. if ! check_capability "$usage" $requiredCapability ; then
  649. log debug " - unacceptable sub key capability ($usage)."
  650. continue
  651. fi
  652. # mark sub key as ok
  653. lastKeyOK=true
  654. ;;
  655. 'fpr') # key fingerprint
  656. fingerprint="$uidfpr"
  657. sshKey=$(gpg2ssh "$fingerprint")
  658. # if the last key was the pub key, skip
  659. if [ "$lastKey" = pub ] ; then
  660. continue
  661. fi
  662. # output a line for the sub key
  663. # 0 = ok, 1 = bad
  664. if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
  665. log verbose " * acceptable sub key."
  666. if [ -z "$sshKey" ] ; then
  667. log error " ! sub key could not be translated (not RSA or DSA?)."
  668. else
  669. echo "0:${sshKey}"
  670. fi
  671. else
  672. log debug " - unacceptable sub key."
  673. if [ -z "$sshKey" ] ; then
  674. log debug " ! sub key could not be translated (not RSA or DSA?)."
  675. else
  676. echo "1:${sshKey}"
  677. fi
  678. fi
  679. ;;
  680. esac
  681. done | sort -t: -k1 -n -r
  682. # NOTE: this last sort is important so that the "good" keys (key
  683. # flag '0') come last. This is so that they take precedence when
  684. # being processed in the key files over "bad" keys (key flag '1')
  685. }
  686. # process a single host in the known_host file
  687. process_host_known_hosts() {
  688. local host
  689. local userID
  690. local noKey=
  691. local nKeys
  692. local nKeysOK
  693. local ok
  694. local sshKey
  695. local tmpfile
  696. # set the key processing mode
  697. export MODE='known_hosts'
  698. host="$1"
  699. userID="ssh://${host}"
  700. log verbose "processing: $host"
  701. nKeys=0
  702. nKeysOK=0
  703. IFS=$'\n'
  704. for line in $(process_user_id "${userID}") ; do
  705. # note that key was found
  706. nKeys=$((nKeys+1))
  707. ok=$(echo "$line" | cut -d: -f1)
  708. sshKey=$(echo "$line" | cut -d: -f2)
  709. if [ -z "$sshKey" ] ; then
  710. continue
  711. fi
  712. # remove any old host key line, and note if removed nothing is
  713. # removed
  714. remove_line "$KNOWN_HOSTS" "$sshKey" || noKey=true
  715. # if key OK, add new host line
  716. if [ "$ok" -eq '0' ] ; then
  717. # note that key was found ok
  718. nKeysOK=$((nKeysOK+1))
  719. # hash if specified
  720. if [ "$HASH_KNOWN_HOSTS" = 'true' ] ; then
  721. # FIXME: this is really hackish cause ssh-keygen won't
  722. # hash from stdin to stdout
  723. tmpfile=$(mktemp ${TMPDIR:-/tmp}/tmp.XXXXXXXXXX)
  724. ssh2known_hosts "$host" "$sshKey" > "$tmpfile"
  725. ssh-keygen -H -f "$tmpfile" 2> /dev/null
  726. cat "$tmpfile" >> "$KNOWN_HOSTS"
  727. rm -f "$tmpfile" "${tmpfile}.old"
  728. else
  729. ssh2known_hosts "$host" "$sshKey" >> "$KNOWN_HOSTS"
  730. fi
  731. # log if this is a new key to the known_hosts file
  732. if [ "$noKey" ] ; then
  733. log info "* new key for $host added to known_hosts file."
  734. fi
  735. fi
  736. done
  737. # if at least one key was found...
  738. if [ "$nKeys" -gt 0 ] ; then
  739. # if ok keys were found, return 0
  740. if [ "$nKeysOK" -gt 0 ] ; then
  741. return 0
  742. # else return 2
  743. else
  744. return 2
  745. fi
  746. # if no keys were found, return 1
  747. else
  748. return 1
  749. fi
  750. }
  751. # update the known_hosts file for a set of hosts listed on command
  752. # line
  753. update_known_hosts() {
  754. local returnCode=0
  755. local nHosts
  756. local nHostsOK
  757. local nHostsBAD
  758. local fileCheck
  759. local host
  760. # the number of hosts specified on command line
  761. nHosts="$#"
  762. nHostsOK=0
  763. nHostsBAD=0
  764. # touch the known_hosts file so that the file permission check
  765. # below won't fail upon not finding the file
  766. (umask 0022 && touch "$KNOWN_HOSTS")
  767. # check permissions on the known_hosts file path
  768. check_key_file_permissions "$USER" "$KNOWN_HOSTS" || failure
  769. # create a lockfile on known_hosts:
  770. lock create "$KNOWN_HOSTS"
  771. # FIXME: we're discarding any pre-existing EXIT trap; is this bad?
  772. trap "lock remove $KNOWN_HOSTS" EXIT
  773. # note pre update file checksum
  774. fileCheck="$(file_hash "$KNOWN_HOSTS")"
  775. for host ; do
  776. # process the host
  777. process_host_known_hosts "$host" || returnCode="$?"
  778. # note the result
  779. case "$returnCode" in
  780. 0)
  781. nHostsOK=$((nHostsOK+1))
  782. ;;
  783. 2)
  784. nHostsBAD=$((nHostsBAD+1))
  785. ;;
  786. esac
  787. # touch the lockfile, for good measure.
  788. lock touch "$KNOWN_HOSTS"
  789. done
  790. # remove the lockfile and the trap
  791. lock remove "$KNOWN_HOSTS"
  792. trap - EXIT
  793. # note if the known_hosts file was updated
  794. if [ "$(file_hash "$KNOWN_HOSTS")" != "$fileCheck" ] ; then
  795. log debug "known_hosts file updated."
  796. fi
  797. # if an acceptable host was found, return 0
  798. if [ "$nHostsOK" -gt 0 ] ; then
  799. return 0
  800. # else if no ok hosts were found...
  801. else
  802. # if no bad host were found then no hosts were found at all,
  803. # and return 1
  804. if [ "$nHostsBAD" -eq 0 ] ; then
  805. return 1
  806. # else if at least one bad host was found, return 2
  807. else
  808. return 2
  809. fi
  810. fi
  811. }
  812. # process hosts from a known_hosts file
  813. process_known_hosts() {
  814. local hosts
  815. # exit if the known_hosts file does not exist
  816. if [ ! -e "$KNOWN_HOSTS" ] ; then
  817. failure "known_hosts file '$KNOWN_HOSTS' does not exist."
  818. fi
  819. log debug "processing known_hosts file..."
  820. hosts=$(meat "$KNOWN_HOSTS" | cut -d ' ' -f 1 | grep -v '^|.*$' | tr , ' ' | tr '\n' ' ')
  821. if [ -z "$hosts" ] ; then
  822. log debug "no hosts to process."
  823. return
  824. fi
  825. # take all the hosts from the known_hosts file (first
  826. # field), grep out all the hashed hosts (lines starting
  827. # with '|')...
  828. update_known_hosts $hosts
  829. }
  830. # process uids for the authorized_keys file
  831. process_uid_authorized_keys() {
  832. local userID
  833. local nKeys
  834. local nKeysOK
  835. local ok
  836. local sshKey
  837. # set the key processing mode
  838. export MODE='authorized_keys'
  839. userID="$1"
  840. log verbose "processing: $userID"
  841. nKeys=0
  842. nKeysOK=0
  843. IFS=$'\n'
  844. for line in $(process_user_id "$userID") ; do
  845. # note that key was found
  846. nKeys=$((nKeys+1))
  847. ok=$(echo "$line" | cut -d: -f1)
  848. sshKey=$(echo "$line" | cut -d: -f2)
  849. if [ -z "$sshKey" ] ; then
  850. continue
  851. fi
  852. # remove the old host key line
  853. remove_line "$AUTHORIZED_KEYS" "$sshKey"
  854. # if key OK, add new host line
  855. if [ "$ok" -eq '0' ] ; then
  856. # note that key was found ok
  857. nKeysOK=$((nKeysOK+1))
  858. ssh2authorized_keys "$userID" "$sshKey" >> "$AUTHORIZED_KEYS"
  859. fi
  860. done
  861. # if at least one key was found...
  862. if [ "$nKeys" -gt 0 ] ; then
  863. # if ok keys were found, return 0
  864. if [ "$nKeysOK" -gt 0 ] ; then
  865. return 0
  866. # else return 2
  867. else
  868. return 2
  869. fi
  870. # if no keys were found, return 1
  871. else
  872. return 1
  873. fi
  874. }
  875. # update the authorized_keys files from a list of user IDs on command
  876. # line
  877. update_authorized_keys() {
  878. local returnCode=0
  879. local userID
  880. local nIDs
  881. local nIDsOK
  882. local nIDsBAD
  883. local fileCheck
  884. # the number of ids specified on command line
  885. nIDs="$#"
  886. nIDsOK=0
  887. nIDsBAD=0
  888. # check permissions on the authorized_keys file path
  889. check_key_file_permissions "$USER" "$AUTHORIZED_KEYS" || failure
  890. # create a lockfile on authorized_keys
  891. lock create "$AUTHORIZED_KEYS"
  892. # FIXME: we're discarding any pre-existing EXIT trap; is this bad?
  893. trap "lock remove $AUTHORIZED_KEYS" EXIT
  894. # note pre update file checksum
  895. fileCheck="$(file_hash "$AUTHORIZED_KEYS")"
  896. # remove any monkeysphere lines from authorized_keys file
  897. remove_monkeysphere_lines "$AUTHORIZED_KEYS"
  898. for userID ; do
  899. # process the user ID, change return code if key not found for
  900. # user ID
  901. process_uid_authorized_keys "$userID" || returnCode="$?"
  902. # note the result
  903. case "$returnCode" in
  904. 0)
  905. nIDsOK=$((nIDsOK+1))
  906. ;;
  907. 2)
  908. nIDsBAD=$((nIDsBAD+1))
  909. ;;
  910. esac
  911. # touch the lockfile, for good measure.
  912. lock touch "$AUTHORIZED_KEYS"
  913. done
  914. # remove the lockfile and the trap
  915. lock remove "$AUTHORIZED_KEYS"
  916. # remove the trap
  917. trap - EXIT
  918. # note if the authorized_keys file was updated
  919. if [ "$(file_hash "$AUTHORIZED_KEYS")" != "$fileCheck" ] ; then
  920. log debug "authorized_keys file updated."
  921. fi
  922. # if an acceptable id was found, return 0
  923. if [ "$nIDsOK" -gt 0 ] ; then
  924. return 0
  925. # else if no ok ids were found...
  926. else
  927. # if no bad ids were found then no ids were found at all, and
  928. # return 1
  929. if [ "$nIDsBAD" -eq 0 ] ; then
  930. return 1
  931. # else if at least one bad id was found, return 2
  932. else
  933. return 2
  934. fi
  935. fi
  936. }
  937. # process an authorized_user_ids file for authorized_keys
  938. process_authorized_user_ids() {
  939. local line
  940. local nline
  941. local userIDs
  942. authorizedUserIDs="$1"
  943. # exit if the authorized_user_ids file is empty
  944. if [ ! -e "$authorizedUserIDs" ] ; then
  945. failure "authorized_user_ids file '$authorizedUserIDs' does not exist."
  946. fi
  947. # check permissions on the authorized_user_ids file path
  948. check_key_file_permissions "$USER" "$authorizedUserIDs" || failure
  949. log debug "processing authorized_user_ids file..."
  950. if ! meat "$authorizedUserIDs" > /dev/null ; then
  951. log debug " no user IDs to process."
  952. return
  953. fi
  954. nline=0
  955. # extract user IDs from authorized_user_ids file
  956. IFS=$'\n'
  957. for line in $(meat "$authorizedUserIDs") ; do
  958. userIDs["$nline"]="$line"
  959. nline=$((nline+1))
  960. done
  961. update_authorized_keys "${userIDs[@]}"
  962. }
  963. # takes a gpg key or keys on stdin, and outputs a list of
  964. # fingerprints, one per line:
  965. list_primary_fingerprints() {
  966. local fake=$(msmktempdir)
  967. GNUPGHOME="$fake" gpg --no-tty --quiet --import
  968. GNUPGHOME="$fake" gpg --with-colons --fingerprint --list-keys | \
  969. awk -F: '/^fpr:/{ print $10 }'
  970. rm -rf "$fake"
  971. }
  972. check_cruft_file() {
  973. local loc="$1"
  974. local version="$2"
  975. if [ -e "$loc" ] ; then
  976. 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
  977. fi
  978. }
  979. check_upgrade_dir() {
  980. local loc="$1"
  981. local version="$2"
  982. if [ -d "$loc" ] ; then
  983. 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
  984. fi
  985. }
  986. ## look for cruft from old versions of the monkeysphere, and notice if
  987. ## upgrades have not been run:
  988. report_cruft() {
  989. check_upgrade_dir "${SYSCONFIGDIR}/gnupg-host" 0.23
  990. check_upgrade_dir "${SYSCONFIGDIR}/gnupg-authentication" 0.23
  991. check_cruft_file "${SYSCONFIGDIR}/gnupg-authentication.conf" 0.23
  992. check_cruft_file "${SYSCONFIGDIR}/gnupg-host.conf" 0.23
  993. local found=
  994. for foo in "${SYSDATADIR}/backup-from-"*"-transition" ; do
  995. if [ -d "$foo" ] ; then
  996. printf "! %s\n" "$foo" | log info
  997. found=true
  998. fi
  999. done
  1000. if [ "$found" ] ; then
  1001. 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
  1002. fi
  1003. }