summaryrefslogtreecommitdiff
path: root/src/common
blob: 396670582b289376423a2f70f490358d978b8b48 (plain)
  1. # -*-shell-script-*-
  2. # Shared sh functions for the monkeysphere
  3. #
  4. # Written by
  5. # Jameson Rollins <jrollins@fifthhorseman.net>
  6. #
  7. # Copyright 2008, released under the GPL, version 3 or later
  8. # all-caps variables are meant to be user supplied (ie. from config
  9. # file) and are considered global
  10. ########################################################################
  11. ### COMMON VARIABLES
  12. # managed directories
  13. ETC="/etc/monkeysphere"
  14. export ETC
  15. ########################################################################
  16. ### UTILITY FUNCTIONS
  17. # failure function. exits with code 255, unless specified otherwise.
  18. failure() {
  19. echo "$1" >&2
  20. exit ${2:-'255'}
  21. }
  22. # write output to stderr
  23. log() {
  24. echo -n "ms: " >&2
  25. echo "$@" >&2
  26. }
  27. loge() {
  28. echo "$@" >&2
  29. }
  30. # cut out all comments(#) and blank lines from standard input
  31. meat() {
  32. grep -v -e "^[[:space:]]*#" -e '^$' "$1"
  33. }
  34. # cut a specified line from standard input
  35. cutline() {
  36. head --line="$1" "$2" | tail -1
  37. }
  38. # check that characters are in a string (in an AND fashion).
  39. # used for checking key capability
  40. # check_capability capability a [b...]
  41. check_capability() {
  42. local usage
  43. local capcheck
  44. usage="$1"
  45. shift 1
  46. for capcheck ; do
  47. if echo "$usage" | grep -q -v "$capcheck" ; then
  48. return 1
  49. fi
  50. done
  51. return 0
  52. }
  53. # convert escaped characters from gpg output back into original
  54. # character
  55. # FIXME: undo all escape character translation in with-colons gpg output
  56. unescape() {
  57. echo "$1" | sed 's/\\x3a/:/'
  58. }
  59. # remove all lines with specified string from specified file
  60. remove_line() {
  61. local file
  62. local string
  63. file="$1"
  64. string="$2"
  65. if [ -z "$file" -o -z "$string" ] ; then
  66. return 1
  67. fi
  68. if [ ! -e "$file" ] ; then
  69. return 1
  70. fi
  71. # if the string is in the file...
  72. if grep -q -F "$string" "$file" 2> /dev/null ; then
  73. # remove the line with the string, and return 0
  74. grep -v -F "$string" "$file" | sponge "$file"
  75. return 0
  76. # otherwise return 1
  77. else
  78. return 1
  79. fi
  80. }
  81. # remove all lines with MonkeySphere strings in file
  82. remove_monkeysphere_lines() {
  83. local file
  84. file="$1"
  85. if [ -z "$file" ] ; then
  86. return 1
  87. fi
  88. if [ ! -e "$file" ] ; then
  89. return 1
  90. fi
  91. egrep -v '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$' \
  92. "$file" | sponge "$file"
  93. }
  94. # translate ssh-style path variables %h and %u
  95. translate_ssh_variables() {
  96. local uname
  97. local home
  98. uname="$1"
  99. path="$2"
  100. # get the user's home directory
  101. userHome=$(getent passwd "$uname" | cut -d: -f6)
  102. # translate '%u' to user name
  103. path=${path/\%u/"$uname"}
  104. # translate '%h' to user home directory
  105. path=${path/\%h/"$userHome"}
  106. echo "$path"
  107. }
  108. # test that a string to conforms to GPG's expiration format
  109. test_gpg_expire() {
  110. echo "$1" | egrep -q "^[0-9]+[mwy]?$"
  111. }
  112. # check that a file is properly owned, and that all it's parent
  113. # directories are not group/other writable
  114. check_key_file_permissions() {
  115. local user
  116. local path
  117. local access
  118. local gAccess
  119. local oAccess
  120. # function to check that an octal corresponds to writability
  121. is_write() {
  122. [ "$1" -eq 2 -o "$1" -eq 3 -o "$1" -eq 6 -o "$1" -eq 7 ]
  123. }
  124. user="$1"
  125. path="$2"
  126. # return 0 is path does not exist
  127. [ -e "$path" ] || return 0
  128. owner=$(stat --format '%U' "$path")
  129. access=$(stat --format '%a' "$path")
  130. gAccess=$(echo "$access" | cut -c2)
  131. oAccess=$(echo "$access" | cut -c3)
  132. # check owner
  133. if [ "$owner" != "$user" -a "$owner" != 'root' ] ; then
  134. return 1
  135. fi
  136. # check group/other writability
  137. if is_write "$gAccess" || is_write "$oAccess" ; then
  138. return 2
  139. fi
  140. if [ "$path" = '/' ] ; then
  141. return 0
  142. else
  143. check_key_file_permissions $(dirname "$path")
  144. fi
  145. }
  146. ### CONVERSION UTILITIES
  147. # output the ssh key for a given key ID
  148. gpg2ssh() {
  149. local keyID
  150. keyID="$1"
  151. gpg --export "$keyID" | openpgp2ssh "$keyID" 2> /dev/null
  152. }
  153. # output known_hosts line from ssh key
  154. ssh2known_hosts() {
  155. local host
  156. local key
  157. host="$1"
  158. key="$2"
  159. echo -n "$host "
  160. echo -n "$key" | tr -d '\n'
  161. echo " MonkeySphere${DATE}"
  162. }
  163. # output authorized_keys line from ssh key
  164. ssh2authorized_keys() {
  165. local userID
  166. local key
  167. userID="$1"
  168. key="$2"
  169. echo -n "$key" | tr -d '\n'
  170. echo " MonkeySphere${DATE} ${userID}"
  171. }
  172. # convert key from gpg to ssh known_hosts format
  173. gpg2known_hosts() {
  174. local host
  175. local keyID
  176. host="$1"
  177. keyID="$2"
  178. # NOTE: it seems that ssh-keygen -R removes all comment fields from
  179. # all lines in the known_hosts file. why?
  180. # NOTE: just in case, the COMMENT can be matched with the
  181. # following regexp:
  182. # '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$'
  183. echo -n "$host "
  184. gpg2ssh "$keyID" | tr -d '\n'
  185. echo " MonkeySphere${DATE}"
  186. }
  187. # convert key from gpg to ssh authorized_keys format
  188. gpg2authorized_keys() {
  189. local userID
  190. local keyID
  191. userID="$1"
  192. keyID="$2"
  193. # NOTE: just in case, the COMMENT can be matched with the
  194. # following regexp:
  195. # '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$'
  196. gpg2ssh "$keyID" | tr -d '\n'
  197. echo " MonkeySphere${DATE} ${userID}"
  198. }
  199. ### GPG UTILITIES
  200. # retrieve all keys with given user id from keyserver
  201. # FIXME: need to figure out how to retrieve all matching keys
  202. # (not just first N (5 in this case))
  203. gpg_fetch_userid() {
  204. local userID
  205. local returnCode
  206. if [ "$CHECK_KEYSERVER" != 'true' ] ; then
  207. return 0
  208. fi
  209. userID="$1"
  210. log -n " checking keyserver $KEYSERVER... "
  211. echo 1,2,3,4,5 | \
  212. gpg --quiet --batch --with-colons \
  213. --command-fd 0 --keyserver "$KEYSERVER" \
  214. --search ="$userID" > /dev/null 2>&1
  215. returnCode="$?"
  216. loge "done."
  217. # if the user is the monkeysphere user, then update the
  218. # monkeysphere user's trustdb
  219. if [ $(id -un) = "$MONKEYSPHERE_USER" ] ; then
  220. gpg_authentication "--check-trustdb" > /dev/null 2>&1
  221. fi
  222. return "$returnCode"
  223. }
  224. ########################################################################
  225. ### PROCESSING FUNCTIONS
  226. # userid and key policy checking
  227. # the following checks policy on the returned keys
  228. # - checks that full key has appropriate valididy (u|f)
  229. # - checks key has specified capability (REQUIRED_*_KEY_CAPABILITY)
  230. # - checks that requested user ID has appropriate validity
  231. # (see /usr/share/doc/gnupg/DETAILS.gz)
  232. # output is one line for every found key, in the following format:
  233. #
  234. # flag fingerprint
  235. #
  236. # "flag" is an acceptability flag, 0 = ok, 1 = bad
  237. # "fingerprint" is the fingerprint of the key
  238. #
  239. # expects global variable: "MODE"
  240. process_user_id() {
  241. local userID
  242. local requiredCapability
  243. local requiredPubCapability
  244. local gpgOut
  245. local type
  246. local validity
  247. local keyid
  248. local uidfpr
  249. local usage
  250. local keyOK
  251. local uidOK
  252. local lastKey
  253. local lastKeyOK
  254. local fingerprint
  255. userID="$1"
  256. # set the required key capability based on the mode
  257. if [ "$MODE" = 'known_hosts' ] ; then
  258. requiredCapability="$REQUIRED_HOST_KEY_CAPABILITY"
  259. elif [ "$MODE" = 'authorized_keys' ] ; then
  260. requiredCapability="$REQUIRED_USER_KEY_CAPABILITY"
  261. fi
  262. requiredPubCapability=$(echo "$requiredCapability" | tr "[:lower:]" "[:upper:]")
  263. # fetch the user ID if necessary/requested
  264. gpg_fetch_userid "$userID"
  265. # output gpg info for (exact) userid and store
  266. gpgOut=$(gpg --list-key --fixed-list-mode --with-colon \
  267. --with-fingerprint --with-fingerprint \
  268. ="$userID" 2>/dev/null)
  269. # if the gpg query return code is not 0, return 1
  270. if [ "$?" -ne 0 ] ; then
  271. log " no primary keys found."
  272. return 1
  273. fi
  274. # loop over all lines in the gpg output and process.
  275. echo "$gpgOut" | cut -d: -f1,2,5,10,12 | \
  276. while IFS=: read -r type validity keyid uidfpr usage ; do
  277. # process based on record type
  278. case $type in
  279. 'pub') # primary keys
  280. # new key, wipe the slate
  281. keyOK=
  282. uidOK=
  283. lastKey=pub
  284. lastKeyOK=
  285. fingerprint=
  286. log " primary key found: $keyid"
  287. # if overall key is not valid, skip
  288. if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
  289. log " - unacceptable primary key validity ($validity)."
  290. continue
  291. fi
  292. # if overall key is disabled, skip
  293. if check_capability "$usage" 'D' ; then
  294. log " - key disabled."
  295. continue
  296. fi
  297. # if overall key capability is not ok, skip
  298. if ! check_capability "$usage" $requiredPubCapability ; then
  299. log " - unacceptable primary key capability ($usage)."
  300. continue
  301. fi
  302. # mark overall key as ok
  303. keyOK=true
  304. # mark primary key as ok if capability is ok
  305. if check_capability "$usage" $requiredCapability ; then
  306. lastKeyOK=true
  307. fi
  308. ;;
  309. 'uid') # user ids
  310. # if an acceptable user ID was already found, skip
  311. if [ "$uidOK" ] ; then
  312. continue
  313. fi
  314. # if the user ID does not match, skip
  315. if [ "$(unescape "$uidfpr")" != "$userID" ] ; then
  316. continue
  317. fi
  318. # if the user ID validity is not ok, skip
  319. if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
  320. continue
  321. fi
  322. # mark user ID acceptable
  323. uidOK=true
  324. # output a line for the primary key
  325. # 0 = ok, 1 = bad
  326. if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
  327. log " * acceptable primary key."
  328. if [ -z "$sshKey" ] ; then
  329. log " ! primary key could not be translated."
  330. else
  331. echo "0:${sshKey}"
  332. fi
  333. else
  334. log " - unacceptable primary key."
  335. if [ -z "$sshKey" ] ; then
  336. log " ! primary key could not be translated."
  337. else
  338. echo "1:${sshKey}"
  339. fi
  340. fi
  341. ;;
  342. 'sub') # sub keys
  343. # unset acceptability of last key
  344. lastKey=sub
  345. lastKeyOK=
  346. fingerprint=
  347. # if sub key validity is not ok, skip
  348. if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
  349. continue
  350. fi
  351. # if sub key capability is not ok, skip
  352. if ! check_capability "$usage" $requiredCapability ; then
  353. continue
  354. fi
  355. # mark sub key as ok
  356. lastKeyOK=true
  357. ;;
  358. 'fpr') # key fingerprint
  359. fingerprint="$uidfpr"
  360. sshKey=$(gpg2ssh "$fingerprint")
  361. # if the last key was the pub key, skip
  362. if [ "$lastKey" = pub ] ; then
  363. continue
  364. fi
  365. # output a line for the primary key
  366. # 0 = ok, 1 = bad
  367. if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
  368. log " * acceptable sub key."
  369. if [ -z "$sshKey" ] ; then
  370. log " ! sub key could not be translated."
  371. else
  372. echo "0:${sshKey}"
  373. fi
  374. else
  375. log " - unacceptable sub key."
  376. if [ -z "$sshKey" ] ; then
  377. log " ! sub key could not be translated."
  378. else
  379. echo "1:${sshKey}"
  380. fi
  381. fi
  382. ;;
  383. esac
  384. done
  385. }
  386. # process a single host in the known_host file
  387. process_host_known_hosts() {
  388. local host
  389. local userID
  390. local nKeys
  391. local nKeysOK
  392. local ok
  393. local sshKey
  394. local tmpfile
  395. host="$1"
  396. log "processing: $host"
  397. userID="ssh://${host}"
  398. nKeys=0
  399. nKeysOK=0
  400. IFS=$'\n'
  401. for line in $(process_user_id "ssh://${host}") ; do
  402. # note that key was found
  403. nKeys=$((nKeys+1))
  404. ok=$(echo "$line" | cut -d: -f1)
  405. sshKey=$(echo "$line" | cut -d: -f2)
  406. if [ -z "$sshKey" ] ; then
  407. continue
  408. fi
  409. # remove the old host key line, and note if removed
  410. remove_line "$KNOWN_HOSTS" "$sshKey"
  411. # if key OK, add new host line
  412. if [ "$ok" -eq '0' ] ; then
  413. # note that key was found ok
  414. nKeysOK=$((nKeysOK+1))
  415. # hash if specified
  416. if [ "$HASH_KNOWN_HOSTS" = 'true' ] ; then
  417. # FIXME: this is really hackish cause ssh-keygen won't
  418. # hash from stdin to stdout
  419. tmpfile=$(mktemp)
  420. ssh2known_hosts "$host" "$sshKey" > "$tmpfile"
  421. ssh-keygen -H -f "$tmpfile" 2> /dev/null
  422. cat "$tmpfile" >> "$KNOWN_HOSTS"
  423. rm -f "$tmpfile" "${tmpfile}.old"
  424. else
  425. ssh2known_hosts "$host" "$sshKey" >> "$KNOWN_HOSTS"
  426. fi
  427. fi
  428. done
  429. # if at least one key was found...
  430. if [ "$nKeys" -gt 0 ] ; then
  431. # if ok keys were found, return 0
  432. if [ "$nKeysOK" -gt 0 ] ; then
  433. return 0
  434. # else return 2
  435. else
  436. return 2
  437. fi
  438. # if no keys were found, return 1
  439. else
  440. return 1
  441. fi
  442. }
  443. # update the known_hosts file for a set of hosts listed on command
  444. # line
  445. update_known_hosts() {
  446. local nHosts
  447. local nHostsOK
  448. local nHostsBAD
  449. local fileCheck
  450. local host
  451. # the number of hosts specified on command line
  452. nHosts="$#"
  453. nHostsOK=0
  454. nHostsBAD=0
  455. # set the trap to remove any lockfiles on exit
  456. trap "lockfile-remove $KNOWN_HOSTS" EXIT
  457. # create a lockfile on known_hosts
  458. lockfile-create "$KNOWN_HOSTS"
  459. # note pre update file checksum
  460. fileCheck="$(cat "$KNOWN_HOSTS" | md5sum)"
  461. for host ; do
  462. # process the host
  463. process_host_known_hosts "$host"
  464. # note the result
  465. case "$?" in
  466. 0)
  467. nHostsOK=$((nHostsOK+1))
  468. ;;
  469. 2)
  470. nHostsBAD=$((nHostsBAD+1))
  471. ;;
  472. esac
  473. # touch the lockfile, for good measure.
  474. lockfile-touch --oneshot "$KNOWN_HOSTS"
  475. done
  476. # remove the lockfile
  477. lockfile-remove "$KNOWN_HOSTS"
  478. # note if the known_hosts file was updated
  479. if [ "$(cat "$KNOWN_HOSTS" | md5sum)" != "$fileCheck" ] ; then
  480. log "known_hosts file updated."
  481. fi
  482. # if an acceptable host was found, return 0
  483. if [ "$nHostsOK" -gt 0 ] ; then
  484. return 0
  485. # else if no ok hosts were found...
  486. else
  487. # if no bad host were found then no hosts were found at all,
  488. # and return 1
  489. if [ "$nHostsBAD" -eq 0 ] ; then
  490. return 1
  491. # else if at least one bad host was found, return 2
  492. else
  493. return 2
  494. fi
  495. fi
  496. }
  497. # process hosts from a known_hosts file
  498. process_known_hosts() {
  499. local hosts
  500. log "processing known_hosts file..."
  501. hosts=$(meat "$KNOWN_HOSTS" | cut -d ' ' -f 1 | grep -v '^|.*$' | tr , ' ' | tr '\n' ' ')
  502. if [ -z "$hosts" ] ; then
  503. log "no hosts to process."
  504. return
  505. fi
  506. # take all the hosts from the known_hosts file (first
  507. # field), grep out all the hashed hosts (lines starting
  508. # with '|')...
  509. update_known_hosts $hosts
  510. }
  511. # process uids for the authorized_keys file
  512. process_uid_authorized_keys() {
  513. local userID
  514. local nKeys
  515. local nKeysOK
  516. local ok
  517. local sshKey
  518. userID="$1"
  519. log "processing: $userID"
  520. nKeys=0
  521. nKeysOK=0
  522. IFS=$'\n'
  523. for line in $(process_user_id "$userID") ; do
  524. # note that key was found
  525. nKeys=$((nKeys+1))
  526. ok=$(echo "$line" | cut -d: -f1)
  527. sshKey=$(echo "$line" | cut -d: -f2)
  528. if [ -z "$sshKey" ] ; then
  529. continue
  530. fi
  531. # remove the old host key line
  532. remove_line "$AUTHORIZED_KEYS" "$sshKey"
  533. # if key OK, add new host line
  534. if [ "$ok" -eq '0' ] ; then
  535. # note that key was found ok
  536. nKeysOK=$((nKeysOK+1))
  537. ssh2authorized_keys "$userID" "$sshKey" >> "$AUTHORIZED_KEYS"
  538. fi
  539. done
  540. # if at least one key was found...
  541. if [ "$nKeys" -gt 0 ] ; then
  542. # if ok keys were found, return 0
  543. if [ "$nKeysOK" -gt 0 ] ; then
  544. return 0
  545. # else return 2
  546. else
  547. return 2
  548. fi
  549. # if no keys were found, return 1
  550. else
  551. return 1
  552. fi
  553. }
  554. # update the authorized_keys files from a list of user IDs on command
  555. # line
  556. update_authorized_keys() {
  557. local userID
  558. local nIDs
  559. local nIDsOK
  560. local nIDsBAD
  561. local fileCheck
  562. # the number of ids specified on command line
  563. nIDs="$#"
  564. nIDsOK=0
  565. nIDsBAD=0
  566. # set the trap to remove any lockfiles on exit
  567. trap "lockfile-remove $AUTHORIZED_KEYS" EXIT
  568. # create a lockfile on authorized_keys
  569. lockfile-create "$AUTHORIZED_KEYS"
  570. # note pre update file checksum
  571. fileCheck="$(cat "$AUTHORIZED_KEYS" | md5sum)"
  572. # remove any monkeysphere lines from authorized_keys file
  573. remove_monkeysphere_lines "$AUTHORIZED_KEYS"
  574. for userID ; do
  575. # process the user ID, change return code if key not found for
  576. # user ID
  577. process_uid_authorized_keys "$userID"
  578. # note the result
  579. case "$?" in
  580. 0)
  581. nIDsOK=$((nIDsOK+1))
  582. ;;
  583. 2)
  584. nIDsBAD=$((nIDsBAD+1))
  585. ;;
  586. esac
  587. # touch the lockfile, for good measure.
  588. lockfile-touch --oneshot "$AUTHORIZED_KEYS"
  589. done
  590. # remove the lockfile
  591. lockfile-remove "$AUTHORIZED_KEYS"
  592. # note if the authorized_keys file was updated
  593. if [ "$(cat "$AUTHORIZED_KEYS" | md5sum)" != "$fileCheck" ] ; then
  594. log "authorized_keys file updated."
  595. fi
  596. # if an acceptable id was found, return 0
  597. if [ "$nIDsOK" -gt 0 ] ; then
  598. return 0
  599. # else if no ok ids were found...
  600. else
  601. # if no bad ids were found then no ids were found at all, and
  602. # return 1
  603. if [ "$nIDsBAD" -eq 0 ] ; then
  604. return 1
  605. # else if at least one bad id was found, return 2
  606. else
  607. return 2
  608. fi
  609. fi
  610. }
  611. # process an authorized_user_ids file for authorized_keys
  612. process_authorized_user_ids() {
  613. local line
  614. local nline
  615. local userIDs
  616. authorizedUserIDs="$1"
  617. log "processing authorized_user_ids file..."
  618. if ! meat "$authorizedUserIDs" > /dev/null ; then
  619. log "no user IDs to process."
  620. return
  621. fi
  622. nline=0
  623. # extract user IDs from authorized_user_ids file
  624. IFS=$'\n'
  625. for line in $(meat "$authorizedUserIDs") ; do
  626. userIDs["$nline"]="$line"
  627. nline=$((nline+1))
  628. done
  629. update_authorized_keys "${userIDs[@]}"
  630. }