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