summaryrefslogtreecommitdiff
path: root/src/common
blob: 7768335082be95af78567a26983897e38a6229f1 (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. file="$1"
  190. string="$2"
  191. if [ -z "$file" -o -z "$string" ] ; then
  192. return 1
  193. fi
  194. if [ ! -e "$file" ] ; then
  195. return 1
  196. fi
  197. # if the string is in the file...
  198. if grep -q -F "$string" "$file" 2> /dev/null ; then
  199. # remove the line with the string, and return 0
  200. grep -v -F "$string" "$file" | sponge "$file"
  201. return 0
  202. # otherwise return 1
  203. else
  204. return 1
  205. fi
  206. }
  207. # remove all lines with MonkeySphere strings in file
  208. remove_monkeysphere_lines() {
  209. local file
  210. file="$1"
  211. if [ -z "$file" ] ; then
  212. return 1
  213. fi
  214. if [ ! -e "$file" ] ; then
  215. return 1
  216. fi
  217. egrep -v '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$' \
  218. "$file" | sponge "$file"
  219. }
  220. # translate ssh-style path variables %h and %u
  221. translate_ssh_variables() {
  222. local uname
  223. local home
  224. uname="$1"
  225. path="$2"
  226. # get the user's home directory
  227. userHome=$(getent passwd "$uname" | cut -d: -f6)
  228. # translate '%u' to user name
  229. path=${path/\%u/"$uname"}
  230. # translate '%h' to user home directory
  231. path=${path/\%h/"$userHome"}
  232. echo "$path"
  233. }
  234. # test that a string to conforms to GPG's expiration format
  235. test_gpg_expire() {
  236. echo "$1" | egrep -q "^[0-9]+[mwy]?$"
  237. }
  238. # check that a file is properly owned, and that all it's parent
  239. # directories are not group/other writable
  240. check_key_file_permissions() {
  241. local user
  242. local path
  243. local access
  244. local gAccess
  245. local oAccess
  246. # function to check that an octal corresponds to writability
  247. is_write() {
  248. [ "$1" -eq 2 -o "$1" -eq 3 -o "$1" -eq 6 -o "$1" -eq 7 ]
  249. }
  250. user="$1"
  251. path="$2"
  252. # return 0 is path does not exist
  253. [ -e "$path" ] || return 0
  254. owner=$(stat --format '%U' "$path")
  255. access=$(stat --format '%a' "$path")
  256. gAccess=$(echo "$access" | cut -c2)
  257. oAccess=$(echo "$access" | cut -c3)
  258. # check owner
  259. if [ "$owner" != "$user" -a "$owner" != 'root' ] ; then
  260. return 1
  261. fi
  262. # check group/other writability
  263. if is_write "$gAccess" || is_write "$oAccess" ; then
  264. return 2
  265. fi
  266. if [ "$path" = '/' ] ; then
  267. return 0
  268. else
  269. check_key_file_permissions $(dirname "$path")
  270. fi
  271. }
  272. ### CONVERSION UTILITIES
  273. # output the ssh key for a given key ID
  274. gpg2ssh() {
  275. local keyID
  276. keyID="$1"
  277. gpg --export "$keyID" | openpgp2ssh "$keyID" 2> /dev/null
  278. }
  279. # output known_hosts line from ssh key
  280. ssh2known_hosts() {
  281. local host
  282. local key
  283. host="$1"
  284. key="$2"
  285. echo -n "$host "
  286. echo -n "$key" | tr -d '\n'
  287. echo " MonkeySphere${DATE}"
  288. }
  289. # output authorized_keys line from ssh key
  290. ssh2authorized_keys() {
  291. local userID
  292. local key
  293. userID="$1"
  294. key="$2"
  295. echo -n "$key" | tr -d '\n'
  296. echo " MonkeySphere${DATE} ${userID}"
  297. }
  298. # convert key from gpg to ssh known_hosts format
  299. gpg2known_hosts() {
  300. local host
  301. local keyID
  302. host="$1"
  303. keyID="$2"
  304. # NOTE: it seems that ssh-keygen -R removes all comment fields from
  305. # all lines in the known_hosts file. why?
  306. # NOTE: just in case, the COMMENT can be matched with the
  307. # following regexp:
  308. # '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$'
  309. echo -n "$host "
  310. gpg2ssh "$keyID" | tr -d '\n'
  311. echo " MonkeySphere${DATE}"
  312. }
  313. # convert key from gpg to ssh authorized_keys format
  314. gpg2authorized_keys() {
  315. local userID
  316. local keyID
  317. userID="$1"
  318. keyID="$2"
  319. # NOTE: just in case, the COMMENT can be matched with the
  320. # following regexp:
  321. # '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$'
  322. gpg2ssh "$keyID" | tr -d '\n'
  323. echo " MonkeySphere${DATE} ${userID}"
  324. }
  325. ### GPG UTILITIES
  326. # retrieve all keys with given user id from keyserver
  327. # FIXME: need to figure out how to retrieve all matching keys
  328. # (not just first N (5 in this case))
  329. gpg_fetch_userid() {
  330. local userID
  331. local returnCode
  332. if [ "$CHECK_KEYSERVER" != 'true' ] ; then
  333. return 0
  334. fi
  335. userID="$1"
  336. log info " checking keyserver $KEYSERVER... "
  337. echo 1,2,3,4,5 | \
  338. gpg --quiet --batch --with-colons \
  339. --command-fd 0 --keyserver "$KEYSERVER" \
  340. --search ="$userID" > /dev/null 2>&1
  341. returnCode="$?"
  342. # if the user is the monkeysphere user, then update the
  343. # monkeysphere user's trustdb
  344. if [ $(id -un) = "$MONKEYSPHERE_USER" ] ; then
  345. gpg_authentication "--check-trustdb" > /dev/null 2>&1
  346. fi
  347. return "$returnCode"
  348. }
  349. ########################################################################
  350. ### PROCESSING FUNCTIONS
  351. # userid and key policy checking
  352. # the following checks policy on the returned keys
  353. # - checks that full key has appropriate valididy (u|f)
  354. # - checks key has specified capability (REQUIRED_*_KEY_CAPABILITY)
  355. # - checks that requested user ID has appropriate validity
  356. # (see /usr/share/doc/gnupg/DETAILS.gz)
  357. # output is one line for every found key, in the following format:
  358. #
  359. # flag:sshKey
  360. #
  361. # "flag" is an acceptability flag, 0 = ok, 1 = bad
  362. # "sshKey" is the translated gpg key
  363. #
  364. # all log output must go to stderr, as stdout is used to pass the
  365. # flag:sshKey to the calling function.
  366. #
  367. # expects global variable: "MODE"
  368. process_user_id() {
  369. local userID
  370. local requiredCapability
  371. local requiredPubCapability
  372. local gpgOut
  373. local type
  374. local validity
  375. local keyid
  376. local uidfpr
  377. local usage
  378. local keyOK
  379. local uidOK
  380. local lastKey
  381. local lastKeyOK
  382. local fingerprint
  383. userID="$1"
  384. # set the required key capability based on the mode
  385. if [ "$MODE" = 'known_hosts' ] ; then
  386. requiredCapability="$REQUIRED_HOST_KEY_CAPABILITY"
  387. elif [ "$MODE" = 'authorized_keys' ] ; then
  388. requiredCapability="$REQUIRED_USER_KEY_CAPABILITY"
  389. fi
  390. requiredPubCapability=$(echo "$requiredCapability" | tr "[:lower:]" "[:upper:]")
  391. # fetch the user ID if necessary/requested
  392. gpg_fetch_userid "$userID"
  393. # output gpg info for (exact) userid and store
  394. gpgOut=$(gpg --list-key --fixed-list-mode --with-colon \
  395. --with-fingerprint --with-fingerprint \
  396. ="$userID" 2>/dev/null)
  397. # if the gpg query return code is not 0, return 1
  398. if [ "$?" -ne 0 ] ; then
  399. log verbose " no primary keys found."
  400. return 1
  401. fi
  402. # loop over all lines in the gpg output and process.
  403. echo "$gpgOut" | cut -d: -f1,2,5,10,12 | \
  404. while IFS=: read -r type validity keyid uidfpr usage ; do
  405. # process based on record type
  406. case $type in
  407. 'pub') # primary keys
  408. # new key, wipe the slate
  409. keyOK=
  410. uidOK=
  411. lastKey=pub
  412. lastKeyOK=
  413. fingerprint=
  414. log verbose " primary key found: $keyid"
  415. # if overall key is not valid, skip
  416. if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
  417. log error " - unacceptable primary key validity ($validity)."
  418. continue
  419. fi
  420. # if overall key is disabled, skip
  421. if check_capability "$usage" 'D' ; then
  422. log error " - key disabled."
  423. continue
  424. fi
  425. # if overall key capability is not ok, skip
  426. if ! check_capability "$usage" $requiredPubCapability ; then
  427. log error " - unacceptable primary key capability ($usage)."
  428. continue
  429. fi
  430. # mark overall key as ok
  431. keyOK=true
  432. # mark primary key as ok if capability is ok
  433. if check_capability "$usage" $requiredCapability ; then
  434. lastKeyOK=true
  435. fi
  436. ;;
  437. 'uid') # user ids
  438. if [ "$lastKey" != pub ] ; then
  439. log error " - got a user ID after a sub key?! user IDs should only follow primary keys!"
  440. continue
  441. fi
  442. # if an acceptable user ID was already found, skip
  443. if [ "$uidOK" = 'true' ] ; then
  444. continue
  445. fi
  446. # if the user ID does matches...
  447. if [ "$(echo "$uidfpr" | gpg_unescape)" = "$userID" ] ; then
  448. # and the user ID validity is ok
  449. if [ "$validity" = 'u' -o "$validity" = 'f' ] ; then
  450. # mark user ID acceptable
  451. uidOK=true
  452. fi
  453. else
  454. continue
  455. fi
  456. # output a line for the primary key
  457. # 0 = ok, 1 = bad
  458. if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
  459. log verbose " * acceptable primary key."
  460. if [ -z "$sshKey" ] ; then
  461. log error " ! primary key could not be translated (not RSA or DSA?)."
  462. else
  463. echo "0:${sshKey}"
  464. fi
  465. else
  466. log error " - unacceptable primary key."
  467. if [ -z "$sshKey" ] ; then
  468. log error " ! primary key could not be translated (not RSA or DSA?)."
  469. else
  470. echo "1:${sshKey}"
  471. fi
  472. fi
  473. ;;
  474. 'sub') # sub keys
  475. # unset acceptability of last key
  476. lastKey=sub
  477. lastKeyOK=
  478. fingerprint=
  479. # don't bother with sub keys if the primary key is not valid
  480. if [ "$keyOK" != true ] ; then
  481. continue
  482. fi
  483. # don't bother with sub keys if no user ID is acceptable:
  484. if [ "$uidOK" != true ] ; then
  485. continue
  486. fi
  487. # if sub key validity is not ok, skip
  488. if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
  489. continue
  490. fi
  491. # if sub key capability is not ok, skip
  492. if ! check_capability "$usage" $requiredCapability ; then
  493. continue
  494. fi
  495. # mark sub key as ok
  496. lastKeyOK=true
  497. ;;
  498. 'fpr') # key fingerprint
  499. fingerprint="$uidfpr"
  500. sshKey=$(gpg2ssh "$fingerprint")
  501. # if the last key was the pub key, skip
  502. if [ "$lastKey" = pub ] ; then
  503. continue
  504. fi
  505. # output a line for the sub key
  506. # 0 = ok, 1 = bad
  507. if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
  508. log verbose " * acceptable sub key."
  509. if [ -z "$sshKey" ] ; then
  510. log error " ! sub key could not be translated (not RSA or DSA?)."
  511. else
  512. echo "0:${sshKey}"
  513. fi
  514. else
  515. log error " - unacceptable sub key."
  516. if [ -z "$sshKey" ] ; then
  517. log error " ! sub key could not be translated (not RSA or DSA?)."
  518. else
  519. echo "1:${sshKey}"
  520. fi
  521. fi
  522. ;;
  523. esac
  524. done | sort -t: -k1 -n -r
  525. # NOTE: this last sort is important so that the "good" keys (key
  526. # flag '0') come last. This is so that they take precedence when
  527. # being processed in the key files over "bad" keys (key flag '1')
  528. }
  529. # process a single host in the known_host file
  530. process_host_known_hosts() {
  531. local host
  532. local userID
  533. local nKeys
  534. local nKeysOK
  535. local ok
  536. local sshKey
  537. local tmpfile
  538. host="$1"
  539. userID="ssh://${host}"
  540. log verbose "processing: $host"
  541. nKeys=0
  542. nKeysOK=0
  543. IFS=$'\n'
  544. for line in $(process_user_id "${userID}") ; do
  545. # note that key was found
  546. nKeys=$((nKeys+1))
  547. ok=$(echo "$line" | cut -d: -f1)
  548. sshKey=$(echo "$line" | cut -d: -f2)
  549. if [ -z "$sshKey" ] ; then
  550. continue
  551. fi
  552. # remove the old host key line, and note if removed
  553. remove_line "$KNOWN_HOSTS" "$sshKey"
  554. # if key OK, add new host line
  555. if [ "$ok" -eq '0' ] ; then
  556. # note that key was found ok
  557. nKeysOK=$((nKeysOK+1))
  558. # hash if specified
  559. if [ "$HASH_KNOWN_HOSTS" = 'true' ] ; then
  560. # FIXME: this is really hackish cause ssh-keygen won't
  561. # hash from stdin to stdout
  562. tmpfile=$(mktemp)
  563. ssh2known_hosts "$host" "$sshKey" > "$tmpfile"
  564. ssh-keygen -H -f "$tmpfile" 2> /dev/null
  565. cat "$tmpfile" >> "$KNOWN_HOSTS"
  566. rm -f "$tmpfile" "${tmpfile}.old"
  567. else
  568. ssh2known_hosts "$host" "$sshKey" >> "$KNOWN_HOSTS"
  569. fi
  570. fi
  571. done
  572. # if at least one key was found...
  573. if [ "$nKeys" -gt 0 ] ; then
  574. # if ok keys were found, return 0
  575. if [ "$nKeysOK" -gt 0 ] ; then
  576. return 0
  577. # else return 2
  578. else
  579. return 2
  580. fi
  581. # if no keys were found, return 1
  582. else
  583. return 1
  584. fi
  585. }
  586. # update the known_hosts file for a set of hosts listed on command
  587. # line
  588. update_known_hosts() {
  589. local nHosts
  590. local nHostsOK
  591. local nHostsBAD
  592. local fileCheck
  593. local host
  594. # the number of hosts specified on command line
  595. nHosts="$#"
  596. nHostsOK=0
  597. nHostsBAD=0
  598. # set the trap to remove any lockfiles on exit
  599. trap "lockfile-remove $KNOWN_HOSTS" EXIT
  600. # create a lockfile on known_hosts
  601. lockfile-create "$KNOWN_HOSTS"
  602. # note pre update file checksum
  603. fileCheck="$(file_hash "$KNOWN_HOSTS")"
  604. for host ; do
  605. # process the host
  606. process_host_known_hosts "$host"
  607. # note the result
  608. case "$?" in
  609. 0)
  610. nHostsOK=$((nHostsOK+1))
  611. ;;
  612. 2)
  613. nHostsBAD=$((nHostsBAD+1))
  614. ;;
  615. esac
  616. # touch the lockfile, for good measure.
  617. lockfile-touch --oneshot "$KNOWN_HOSTS"
  618. done
  619. # remove the lockfile
  620. lockfile-remove "$KNOWN_HOSTS"
  621. # note if the known_hosts file was updated
  622. if [ "$(file_hash "$KNOWN_HOSTS")" != "$fileCheck" ] ; then
  623. log verbose "known_hosts file updated."
  624. fi
  625. # if an acceptable host was found, return 0
  626. if [ "$nHostsOK" -gt 0 ] ; then
  627. return 0
  628. # else if no ok hosts were found...
  629. else
  630. # if no bad host were found then no hosts were found at all,
  631. # and return 1
  632. if [ "$nHostsBAD" -eq 0 ] ; then
  633. return 1
  634. # else if at least one bad host was found, return 2
  635. else
  636. return 2
  637. fi
  638. fi
  639. }
  640. # process hosts from a known_hosts file
  641. process_known_hosts() {
  642. local hosts
  643. log verbose "processing known_hosts file..."
  644. hosts=$(meat "$KNOWN_HOSTS" | cut -d ' ' -f 1 | grep -v '^|.*$' | tr , ' ' | tr '\n' ' ')
  645. if [ -z "$hosts" ] ; then
  646. log error "no hosts to process."
  647. return
  648. fi
  649. # take all the hosts from the known_hosts file (first
  650. # field), grep out all the hashed hosts (lines starting
  651. # with '|')...
  652. update_known_hosts $hosts
  653. }
  654. # process uids for the authorized_keys file
  655. process_uid_authorized_keys() {
  656. local userID
  657. local nKeys
  658. local nKeysOK
  659. local ok
  660. local sshKey
  661. userID="$1"
  662. log verbose "processing: $userID"
  663. nKeys=0
  664. nKeysOK=0
  665. IFS=$'\n'
  666. for line in $(process_user_id "$userID") ; do
  667. # note that key was found
  668. nKeys=$((nKeys+1))
  669. ok=$(echo "$line" | cut -d: -f1)
  670. sshKey=$(echo "$line" | cut -d: -f2)
  671. if [ -z "$sshKey" ] ; then
  672. continue
  673. fi
  674. # remove the old host key line
  675. remove_line "$AUTHORIZED_KEYS" "$sshKey"
  676. # if key OK, add new host line
  677. if [ "$ok" -eq '0' ] ; then
  678. # note that key was found ok
  679. nKeysOK=$((nKeysOK+1))
  680. ssh2authorized_keys "$userID" "$sshKey" >> "$AUTHORIZED_KEYS"
  681. fi
  682. done
  683. # if at least one key was found...
  684. if [ "$nKeys" -gt 0 ] ; then
  685. # if ok keys were found, return 0
  686. if [ "$nKeysOK" -gt 0 ] ; then
  687. return 0
  688. # else return 2
  689. else
  690. return 2
  691. fi
  692. # if no keys were found, return 1
  693. else
  694. return 1
  695. fi
  696. }
  697. # update the authorized_keys files from a list of user IDs on command
  698. # line
  699. update_authorized_keys() {
  700. local userID
  701. local nIDs
  702. local nIDsOK
  703. local nIDsBAD
  704. local fileCheck
  705. # the number of ids specified on command line
  706. nIDs="$#"
  707. nIDsOK=0
  708. nIDsBAD=0
  709. # set the trap to remove any lockfiles on exit
  710. trap "lockfile-remove $AUTHORIZED_KEYS" EXIT
  711. # create a lockfile on authorized_keys
  712. lockfile-create "$AUTHORIZED_KEYS"
  713. # note pre update file checksum
  714. fileCheck="$(file_hash "$AUTHORIZED_KEYS")"
  715. # remove any monkeysphere lines from authorized_keys file
  716. remove_monkeysphere_lines "$AUTHORIZED_KEYS"
  717. for userID ; do
  718. # process the user ID, change return code if key not found for
  719. # user ID
  720. process_uid_authorized_keys "$userID"
  721. # note the result
  722. case "$?" in
  723. 0)
  724. nIDsOK=$((nIDsOK+1))
  725. ;;
  726. 2)
  727. nIDsBAD=$((nIDsBAD+1))
  728. ;;
  729. esac
  730. # touch the lockfile, for good measure.
  731. lockfile-touch --oneshot "$AUTHORIZED_KEYS"
  732. done
  733. # remove the lockfile
  734. lockfile-remove "$AUTHORIZED_KEYS"
  735. # note if the authorized_keys file was updated
  736. if [ "$(file_hash "$AUTHORIZED_KEYS")" != "$fileCheck" ] ; then
  737. log verbose "authorized_keys file updated."
  738. fi
  739. # if an acceptable id was found, return 0
  740. if [ "$nIDsOK" -gt 0 ] ; then
  741. return 0
  742. # else if no ok ids were found...
  743. else
  744. # if no bad ids were found then no ids were found at all, and
  745. # return 1
  746. if [ "$nIDsBAD" -eq 0 ] ; then
  747. return 1
  748. # else if at least one bad id was found, return 2
  749. else
  750. return 2
  751. fi
  752. fi
  753. }
  754. # process an authorized_user_ids file for authorized_keys
  755. process_authorized_user_ids() {
  756. local line
  757. local nline
  758. local userIDs
  759. authorizedUserIDs="$1"
  760. log verbose "processing authorized_user_ids file..."
  761. if ! meat "$authorizedUserIDs" > /dev/null ; then
  762. log error "no user IDs to process."
  763. return
  764. fi
  765. nline=0
  766. # extract user IDs from authorized_user_ids file
  767. IFS=$'\n'
  768. for line in $(meat "$authorizedUserIDs") ; do
  769. userIDs["$nline"]="$line"
  770. nline=$((nline+1))
  771. done
  772. update_authorized_keys "${userIDs[@]}"
  773. }