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