summaryrefslogtreecommitdiff
path: root/src/common
blob: 48739d92d8639056c59295cf6fba0585df162eec (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. ETC="/etc/monkeysphere"
  16. export ETC
  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 an octal corresponds to writability
  340. is_write() {
  341. [ "$1" -eq 2 -o "$1" -eq 3 -o "$1" -eq 6 -o "$1" -eq 7 ]
  342. }
  343. user="$1"
  344. path="$2"
  345. # return 0 is path does not exist
  346. [ -e "$path" ] || return 0
  347. owner=$(stat --format '%U' "$path")
  348. access=$(stat --format '%a' "$path")
  349. gAccess=$(echo "$access" | cut -c2)
  350. oAccess=$(echo "$access" | cut -c3)
  351. # check owner
  352. if [ "$owner" != "$user" -a "$owner" != 'root' ] ; then
  353. return 1
  354. fi
  355. # check group/other writability
  356. if is_write "$gAccess" || is_write "$oAccess" ; then
  357. return 2
  358. fi
  359. if [ "$path" = '/' ] ; then
  360. return 0
  361. else
  362. check_key_file_permissions $(dirname "$path")
  363. fi
  364. }
  365. ### CONVERSION UTILITIES
  366. # output the ssh key for a given key ID
  367. gpg2ssh() {
  368. local keyID
  369. keyID="$1"
  370. gpg --export "$keyID" | openpgp2ssh "$keyID" 2> /dev/null
  371. }
  372. # output known_hosts line from ssh key
  373. ssh2known_hosts() {
  374. local host
  375. local key
  376. host="$1"
  377. key="$2"
  378. echo -n "$host "
  379. echo -n "$key" | tr -d '\n'
  380. echo " MonkeySphere${DATE}"
  381. }
  382. # output authorized_keys line from ssh key
  383. ssh2authorized_keys() {
  384. local userID
  385. local key
  386. userID="$1"
  387. key="$2"
  388. echo -n "$key" | tr -d '\n'
  389. echo " MonkeySphere${DATE} ${userID}"
  390. }
  391. # convert key from gpg to ssh known_hosts format
  392. gpg2known_hosts() {
  393. local host
  394. local keyID
  395. host="$1"
  396. keyID="$2"
  397. # NOTE: it seems that ssh-keygen -R removes all comment fields from
  398. # all lines in the known_hosts file. why?
  399. # NOTE: just in case, the COMMENT can be matched with the
  400. # following regexp:
  401. # '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$'
  402. echo -n "$host "
  403. gpg2ssh "$keyID" | tr -d '\n'
  404. echo " MonkeySphere${DATE}"
  405. }
  406. # convert key from gpg to ssh authorized_keys format
  407. gpg2authorized_keys() {
  408. local userID
  409. local keyID
  410. userID="$1"
  411. keyID="$2"
  412. # NOTE: just in case, the COMMENT can be matched with the
  413. # following regexp:
  414. # '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$'
  415. gpg2ssh "$keyID" | tr -d '\n'
  416. echo " MonkeySphere${DATE} ${userID}"
  417. }
  418. ### GPG UTILITIES
  419. # retrieve all keys with given user id from keyserver
  420. # FIXME: need to figure out how to retrieve all matching keys
  421. # (not just first N (5 in this case))
  422. gpg_fetch_userid() {
  423. local userID
  424. local returnCode
  425. if [ "$CHECK_KEYSERVER" != 'true' ] ; then
  426. return 0
  427. fi
  428. userID="$1"
  429. log info " checking keyserver $KEYSERVER... "
  430. echo 1,2,3,4,5 | \
  431. gpg --quiet --batch --with-colons \
  432. --command-fd 0 --keyserver "$KEYSERVER" \
  433. --search ="$userID" > /dev/null 2>&1
  434. returnCode="$?"
  435. # if the user is the monkeysphere user, then update the
  436. # monkeysphere user's trustdb
  437. if [ $(id -un) = "$MONKEYSPHERE_USER" ] ; then
  438. gpg_authentication "--check-trustdb" > /dev/null 2>&1
  439. fi
  440. return "$returnCode"
  441. }
  442. ########################################################################
  443. ### PROCESSING FUNCTIONS
  444. # userid and key policy checking
  445. # the following checks policy on the returned keys
  446. # - checks that full key has appropriate valididy (u|f)
  447. # - checks key has specified capability (REQUIRED_*_KEY_CAPABILITY)
  448. # - checks that requested user ID has appropriate validity
  449. # (see /usr/share/doc/gnupg/DETAILS.gz)
  450. # output is one line for every found key, in the following format:
  451. #
  452. # flag:sshKey
  453. #
  454. # "flag" is an acceptability flag, 0 = ok, 1 = bad
  455. # "sshKey" is the translated gpg key
  456. #
  457. # all log output must go to stderr, as stdout is used to pass the
  458. # flag:sshKey to the calling function.
  459. #
  460. # expects global variable: "MODE"
  461. process_user_id() {
  462. local userID
  463. local requiredCapability
  464. local requiredPubCapability
  465. local gpgOut
  466. local type
  467. local validity
  468. local keyid
  469. local uidfpr
  470. local usage
  471. local keyOK
  472. local uidOK
  473. local lastKey
  474. local lastKeyOK
  475. local fingerprint
  476. userID="$1"
  477. # set the required key capability based on the mode
  478. if [ "$MODE" = 'known_hosts' ] ; then
  479. requiredCapability="$REQUIRED_HOST_KEY_CAPABILITY"
  480. elif [ "$MODE" = 'authorized_keys' ] ; then
  481. requiredCapability="$REQUIRED_USER_KEY_CAPABILITY"
  482. fi
  483. requiredPubCapability=$(echo "$requiredCapability" | tr "[:lower:]" "[:upper:]")
  484. # fetch the user ID if necessary/requested
  485. gpg_fetch_userid "$userID"
  486. # output gpg info for (exact) userid and store
  487. gpgOut=$(gpg --list-key --fixed-list-mode --with-colon \
  488. --with-fingerprint --with-fingerprint \
  489. ="$userID" 2>/dev/null)
  490. # if the gpg query return code is not 0, return 1
  491. if [ "$?" -ne 0 ] ; then
  492. log verbose " no primary keys found."
  493. return 1
  494. fi
  495. # loop over all lines in the gpg output and process.
  496. echo "$gpgOut" | cut -d: -f1,2,5,10,12 | \
  497. while IFS=: read -r type validity keyid uidfpr usage ; do
  498. # process based on record type
  499. case $type in
  500. 'pub') # primary keys
  501. # new key, wipe the slate
  502. keyOK=
  503. uidOK=
  504. lastKey=pub
  505. lastKeyOK=
  506. fingerprint=
  507. log verbose " primary key found: $keyid"
  508. # if overall key is not valid, skip
  509. if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
  510. log error " - unacceptable primary key validity ($validity)."
  511. continue
  512. fi
  513. # if overall key is disabled, skip
  514. if check_capability "$usage" 'D' ; then
  515. log error " - key disabled."
  516. continue
  517. fi
  518. # if overall key capability is not ok, skip
  519. if ! check_capability "$usage" $requiredPubCapability ; then
  520. log error " - unacceptable primary key capability ($usage)."
  521. continue
  522. fi
  523. # mark overall key as ok
  524. keyOK=true
  525. # mark primary key as ok if capability is ok
  526. if check_capability "$usage" $requiredCapability ; then
  527. lastKeyOK=true
  528. fi
  529. ;;
  530. 'uid') # user ids
  531. if [ "$lastKey" != pub ] ; then
  532. log error " - got a user ID after a sub key?! user IDs should only follow primary keys!"
  533. continue
  534. fi
  535. # if an acceptable user ID was already found, skip
  536. if [ "$uidOK" = 'true' ] ; then
  537. continue
  538. fi
  539. # if the user ID does matches...
  540. if [ "$(echo "$uidfpr" | gpg_unescape)" = "$userID" ] ; then
  541. # and the user ID validity is ok
  542. if [ "$validity" = 'u' -o "$validity" = 'f' ] ; then
  543. # mark user ID acceptable
  544. uidOK=true
  545. fi
  546. else
  547. continue
  548. fi
  549. # output a line for the primary key
  550. # 0 = ok, 1 = bad
  551. if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
  552. log verbose " * acceptable primary key."
  553. if [ -z "$sshKey" ] ; then
  554. log error " ! primary key could not be translated (not RSA or DSA?)."
  555. else
  556. echo "0:${sshKey}"
  557. fi
  558. else
  559. log error " - unacceptable primary key."
  560. if [ -z "$sshKey" ] ; then
  561. log error " ! primary key could not be translated (not RSA or DSA?)."
  562. else
  563. echo "1:${sshKey}"
  564. fi
  565. fi
  566. ;;
  567. 'sub') # sub keys
  568. # unset acceptability of last key
  569. lastKey=sub
  570. lastKeyOK=
  571. fingerprint=
  572. # don't bother with sub keys if the primary key is not valid
  573. if [ "$keyOK" != true ] ; then
  574. continue
  575. fi
  576. # don't bother with sub keys if no user ID is acceptable:
  577. if [ "$uidOK" != true ] ; then
  578. continue
  579. fi
  580. # if sub key validity is not ok, skip
  581. if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
  582. continue
  583. fi
  584. # if sub key capability is not ok, skip
  585. if ! check_capability "$usage" $requiredCapability ; then
  586. continue
  587. fi
  588. # mark sub key as ok
  589. lastKeyOK=true
  590. ;;
  591. 'fpr') # key fingerprint
  592. fingerprint="$uidfpr"
  593. sshKey=$(gpg2ssh "$fingerprint")
  594. # if the last key was the pub key, skip
  595. if [ "$lastKey" = pub ] ; then
  596. continue
  597. fi
  598. # output a line for the sub key
  599. # 0 = ok, 1 = bad
  600. if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
  601. log verbose " * acceptable sub key."
  602. if [ -z "$sshKey" ] ; then
  603. log error " ! sub key could not be translated (not RSA or DSA?)."
  604. else
  605. echo "0:${sshKey}"
  606. fi
  607. else
  608. log error " - unacceptable sub key."
  609. if [ -z "$sshKey" ] ; then
  610. log error " ! sub key could not be translated (not RSA or DSA?)."
  611. else
  612. echo "1:${sshKey}"
  613. fi
  614. fi
  615. ;;
  616. esac
  617. done | sort -t: -k1 -n -r
  618. # NOTE: this last sort is important so that the "good" keys (key
  619. # flag '0') come last. This is so that they take precedence when
  620. # being processed in the key files over "bad" keys (key flag '1')
  621. }
  622. # process a single host in the known_host file
  623. process_host_known_hosts() {
  624. local host
  625. local userID
  626. local nKeys
  627. local nKeysOK
  628. local ok
  629. local sshKey
  630. local tmpfile
  631. host="$1"
  632. userID="ssh://${host}"
  633. log verbose "processing: $host"
  634. nKeys=0
  635. nKeysOK=0
  636. IFS=$'\n'
  637. for line in $(process_user_id "${userID}") ; do
  638. # note that key was found
  639. nKeys=$((nKeys+1))
  640. ok=$(echo "$line" | cut -d: -f1)
  641. sshKey=$(echo "$line" | cut -d: -f2)
  642. if [ -z "$sshKey" ] ; then
  643. continue
  644. fi
  645. # remove the old host key line, and note if removed
  646. remove_line "$KNOWN_HOSTS" "$sshKey"
  647. # if key OK, add new host line
  648. if [ "$ok" -eq '0' ] ; then
  649. # note that key was found ok
  650. nKeysOK=$((nKeysOK+1))
  651. # hash if specified
  652. if [ "$HASH_KNOWN_HOSTS" = 'true' ] ; then
  653. # FIXME: this is really hackish cause ssh-keygen won't
  654. # hash from stdin to stdout
  655. tmpfile=$(mktemp ${TMPDIR:-/tmp}/tmp.XXXXXXXXXX)
  656. ssh2known_hosts "$host" "$sshKey" > "$tmpfile"
  657. ssh-keygen -H -f "$tmpfile" 2> /dev/null
  658. cat "$tmpfile" >> "$KNOWN_HOSTS"
  659. rm -f "$tmpfile" "${tmpfile}.old"
  660. else
  661. ssh2known_hosts "$host" "$sshKey" >> "$KNOWN_HOSTS"
  662. fi
  663. fi
  664. done
  665. # if at least one key was found...
  666. if [ "$nKeys" -gt 0 ] ; then
  667. # if ok keys were found, return 0
  668. if [ "$nKeysOK" -gt 0 ] ; then
  669. return 0
  670. # else return 2
  671. else
  672. return 2
  673. fi
  674. # if no keys were found, return 1
  675. else
  676. return 1
  677. fi
  678. }
  679. # update the known_hosts file for a set of hosts listed on command
  680. # line
  681. update_known_hosts() {
  682. local nHosts
  683. local nHostsOK
  684. local nHostsBAD
  685. local fileCheck
  686. local host
  687. # the number of hosts specified on command line
  688. nHosts="$#"
  689. nHostsOK=0
  690. nHostsBAD=0
  691. # create a lockfile on known_hosts:
  692. lock create "$KNOWN_HOSTS"
  693. # FIXME: we're discarding any pre-existing EXIT trap; is this bad?
  694. trap "lock remove $KNOWN_HOSTS" EXIT
  695. # note pre update file checksum
  696. fileCheck="$(file_hash "$KNOWN_HOSTS")"
  697. for host ; do
  698. # process the host
  699. process_host_known_hosts "$host"
  700. # note the result
  701. case "$?" in
  702. 0)
  703. nHostsOK=$((nHostsOK+1))
  704. ;;
  705. 2)
  706. nHostsBAD=$((nHostsBAD+1))
  707. ;;
  708. esac
  709. # touch the lockfile, for good measure.
  710. lock touch "$KNOWN_HOSTS"
  711. done
  712. # remove the lockfile and the trap
  713. lock remove "$KNOWN_HOSTS"
  714. trap - EXIT
  715. # note if the known_hosts file was updated
  716. if [ "$(file_hash "$KNOWN_HOSTS")" != "$fileCheck" ] ; then
  717. log verbose "known_hosts file updated."
  718. fi
  719. # if an acceptable host was found, return 0
  720. if [ "$nHostsOK" -gt 0 ] ; then
  721. return 0
  722. # else if no ok hosts were found...
  723. else
  724. # if no bad host were found then no hosts were found at all,
  725. # and return 1
  726. if [ "$nHostsBAD" -eq 0 ] ; then
  727. return 1
  728. # else if at least one bad host was found, return 2
  729. else
  730. return 2
  731. fi
  732. fi
  733. }
  734. # process hosts from a known_hosts file
  735. process_known_hosts() {
  736. local hosts
  737. log verbose "processing known_hosts file..."
  738. hosts=$(meat "$KNOWN_HOSTS" | cut -d ' ' -f 1 | grep -v '^|.*$' | tr , ' ' | tr '\n' ' ')
  739. if [ -z "$hosts" ] ; then
  740. log error "no hosts to process."
  741. return
  742. fi
  743. # take all the hosts from the known_hosts file (first
  744. # field), grep out all the hashed hosts (lines starting
  745. # with '|')...
  746. update_known_hosts $hosts
  747. }
  748. # process uids for the authorized_keys file
  749. process_uid_authorized_keys() {
  750. local userID
  751. local nKeys
  752. local nKeysOK
  753. local ok
  754. local sshKey
  755. userID="$1"
  756. log verbose "processing: $userID"
  757. nKeys=0
  758. nKeysOK=0
  759. IFS=$'\n'
  760. for line in $(process_user_id "$userID") ; do
  761. # note that key was found
  762. nKeys=$((nKeys+1))
  763. ok=$(echo "$line" | cut -d: -f1)
  764. sshKey=$(echo "$line" | cut -d: -f2)
  765. if [ -z "$sshKey" ] ; then
  766. continue
  767. fi
  768. # remove the old host key line
  769. remove_line "$AUTHORIZED_KEYS" "$sshKey"
  770. # if key OK, add new host line
  771. if [ "$ok" -eq '0' ] ; then
  772. # note that key was found ok
  773. nKeysOK=$((nKeysOK+1))
  774. ssh2authorized_keys "$userID" "$sshKey" >> "$AUTHORIZED_KEYS"
  775. fi
  776. done
  777. # if at least one key was found...
  778. if [ "$nKeys" -gt 0 ] ; then
  779. # if ok keys were found, return 0
  780. if [ "$nKeysOK" -gt 0 ] ; then
  781. return 0
  782. # else return 2
  783. else
  784. return 2
  785. fi
  786. # if no keys were found, return 1
  787. else
  788. return 1
  789. fi
  790. }
  791. # update the authorized_keys files from a list of user IDs on command
  792. # line
  793. update_authorized_keys() {
  794. local userID
  795. local nIDs
  796. local nIDsOK
  797. local nIDsBAD
  798. local fileCheck
  799. # the number of ids specified on command line
  800. nIDs="$#"
  801. nIDsOK=0
  802. nIDsBAD=0
  803. # create a lockfile on authorized_keys
  804. lock create "$AUTHORIZED_KEYS"
  805. # FIXME: we're discarding any pre-existing EXIT trap; is this bad?
  806. trap "lock remove $AUTHORIZED_KEYS" EXIT
  807. # note pre update file checksum
  808. fileCheck="$(file_hash "$AUTHORIZED_KEYS")"
  809. # remove any monkeysphere lines from authorized_keys file
  810. remove_monkeysphere_lines "$AUTHORIZED_KEYS"
  811. for userID ; do
  812. # process the user ID, change return code if key not found for
  813. # user ID
  814. process_uid_authorized_keys "$userID"
  815. # note the result
  816. case "$?" in
  817. 0)
  818. nIDsOK=$((nIDsOK+1))
  819. ;;
  820. 2)
  821. nIDsBAD=$((nIDsBAD+1))
  822. ;;
  823. esac
  824. # touch the lockfile, for good measure.
  825. lock touch "$AUTHORIZED_KEYS"
  826. done
  827. # remove the lockfile and the trap
  828. lock remove "$AUTHORIZED_KEYS"
  829. trap - EXIT
  830. # note if the authorized_keys file was updated
  831. if [ "$(file_hash "$AUTHORIZED_KEYS")" != "$fileCheck" ] ; then
  832. log verbose "authorized_keys file updated."
  833. fi
  834. # if an acceptable id was found, return 0
  835. if [ "$nIDsOK" -gt 0 ] ; then
  836. return 0
  837. # else if no ok ids were found...
  838. else
  839. # if no bad ids were found then no ids were found at all, and
  840. # return 1
  841. if [ "$nIDsBAD" -eq 0 ] ; then
  842. return 1
  843. # else if at least one bad id was found, return 2
  844. else
  845. return 2
  846. fi
  847. fi
  848. }
  849. # process an authorized_user_ids file for authorized_keys
  850. process_authorized_user_ids() {
  851. local line
  852. local nline
  853. local userIDs
  854. authorizedUserIDs="$1"
  855. log verbose "processing authorized_user_ids file..."
  856. if ! meat "$authorizedUserIDs" > /dev/null ; then
  857. log error "no user IDs to process."
  858. return
  859. fi
  860. nline=0
  861. # extract user IDs from authorized_user_ids file
  862. IFS=$'\n'
  863. for line in $(meat "$authorizedUserIDs") ; do
  864. userIDs["$nline"]="$line"
  865. nline=$((nline+1))
  866. done
  867. update_authorized_keys "${userIDs[@]}"
  868. }