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