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