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