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