summaryrefslogtreecommitdiff
path: root/src/common
blob: ef931ca4bc7a20282be621bfa533830c9cfef8bb (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. # if the user is the monkeysphere user, then update the
  445. # monkeysphere user's trustdb
  446. if [ $(id -un) = "$MONKEYSPHERE_USER" ] ; then
  447. gpg_authentication "--check-trustdb" > /dev/null 2>&1
  448. fi
  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. }