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