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