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