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