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