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