summaryrefslogtreecommitdiff
path: root/src/common
blob: 6fc5f3318d10dc39f4482ddf6efccea44003d7f5 (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. # need to do it this way (as opposed to "while read...") so that
  260. # variables set in loop will be visible outside of loop
  261. echo "$gpgOut" | cut -d: -f1,2,5,10,12 | \
  262. while IFS=: read -r type validity keyid uidfpr usage ; do
  263. # process based on record type
  264. case $type in
  265. 'pub') # primary keys
  266. # new key, wipe the slate
  267. keyOK=
  268. uidOK=
  269. lastKey=pub
  270. lastKeyOK=
  271. fingerprint=
  272. log " primary key found: $keyid"
  273. # if overall key is not valid, skip
  274. if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
  275. log " - unacceptable primary key validity ($validity)."
  276. continue
  277. fi
  278. # if overall key is disabled, skip
  279. if check_capability "$usage" 'D' ; then
  280. log " - key disabled."
  281. continue
  282. fi
  283. # if overall key capability is not ok, skip
  284. if ! check_capability "$usage" $requiredPubCapability ; then
  285. log " - unacceptable primary key capability ($usage)."
  286. continue
  287. fi
  288. # mark overall key as ok
  289. keyOK=true
  290. # mark primary key as ok if capability is ok
  291. if check_capability "$usage" $requiredCapability ; then
  292. lastKeyOK=true
  293. fi
  294. ;;
  295. 'uid') # user ids
  296. # if an acceptable user ID was already found, skip
  297. if [ "$uidOK" ] ; then
  298. continue
  299. fi
  300. # if the user ID does not match, skip
  301. if [ "$(unescape "$uidfpr")" != "$userID" ] ; then
  302. continue
  303. fi
  304. # if the user ID validity is not ok, skip
  305. if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
  306. continue
  307. fi
  308. # mark user ID acceptable
  309. uidOK=true
  310. # output a line for the primary key
  311. # 0 = ok, 1 = bad
  312. if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
  313. log " * acceptable key found."
  314. echo "0:${fingerprint}"
  315. else
  316. echo "1:${fingerprint}"
  317. fi
  318. ;;
  319. 'sub') # sub keys
  320. # unset acceptability of last key
  321. lastKey=sub
  322. lastKeyOK=
  323. fingerprint=
  324. # if sub key validity is not ok, skip
  325. if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
  326. continue
  327. fi
  328. # if sub key capability is not ok, skip
  329. if ! check_capability "$usage" $requiredCapability ; then
  330. continue
  331. fi
  332. # mark sub key as ok
  333. lastKeyOK=true
  334. ;;
  335. 'fpr') # key fingerprint
  336. fingerprint="$uidfpr"
  337. # if the last key was the pub key, skip
  338. if [ "$lastKey" = pub ] ; then
  339. continue
  340. fi
  341. # output a line for the last subkey
  342. # 0 = ok, 1 = bad
  343. if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
  344. log " * acceptable key found."
  345. echo "0:${fingerprint}"
  346. else
  347. echo "1:${fingerprint}"
  348. fi
  349. ;;
  350. esac
  351. done
  352. }
  353. # process a single host in the known_host file
  354. process_host_known_hosts() {
  355. local host
  356. local userID
  357. local nKeys
  358. local nKeysOK
  359. local ok
  360. local keyid
  361. local tmpfile
  362. host="$1"
  363. log "processing host: $host"
  364. userID="ssh://${host}"
  365. nKeys=0
  366. nKeysOK=0
  367. for line in $(process_user_id "ssh://${host}") ; do
  368. # note that key was found
  369. nKeys=$((nKeys+1))
  370. ok=$(echo "$line" | cut -d: -f1)
  371. keyid=$(echo "$line" | cut -d: -f2)
  372. sshKey=$(gpg2ssh "$keyid")
  373. if [ -z "$sshKey" ] ; then
  374. log " ! key could not be translated."
  375. continue
  376. fi
  377. # remove the old host key line, and note if removed
  378. remove_line "$KNOWN_HOSTS" "$sshKey"
  379. # if key OK, add new host line
  380. if [ "$ok" -eq '0' ] ; then
  381. # note that key was found ok
  382. nKeysOK=$((nKeysOK+1))
  383. # hash if specified
  384. if [ "$HASH_KNOWN_HOSTS" = 'true' ] ; then
  385. # FIXME: this is really hackish cause ssh-keygen won't
  386. # hash from stdin to stdout
  387. tmpfile=$(mktemp)
  388. ssh2known_hosts "$host" "$sshKey" > "$tmpfile"
  389. ssh-keygen -H -f "$tmpfile" 2> /dev/null
  390. cat "$tmpfile" >> "$KNOWN_HOSTS"
  391. rm -f "$tmpfile" "${tmpfile}.old"
  392. else
  393. ssh2known_hosts "$host" "$sshKey" >> "$KNOWN_HOSTS"
  394. fi
  395. fi
  396. done
  397. # if at least one key was found...
  398. if [ "$nKeys" -gt 0 ] ; then
  399. # if ok keys were found, return 0
  400. if [ "$nKeysOK" -gt 0 ] ; then
  401. return 0
  402. # else return 2
  403. else
  404. return 2
  405. fi
  406. # if no keys were found, return 1
  407. else
  408. return 1
  409. fi
  410. }
  411. # update the known_hosts file for a set of hosts listed on command
  412. # line
  413. update_known_hosts() {
  414. local nHosts
  415. local nHostsOK
  416. local nHostsBAD
  417. local host
  418. # the number of hosts specified on command line
  419. nHosts="$#"
  420. nHostsOK=0
  421. nHostsBAD=0
  422. # set the trap to remove any lockfiles on exit
  423. trap "lockfile-remove $KNOWN_HOSTS" EXIT
  424. # create a lockfile on known_hosts
  425. lockfile-create "$KNOWN_HOSTS"
  426. for host ; do
  427. # process the host
  428. process_host_known_hosts "$host"
  429. # note the result
  430. case "$?" in
  431. 0)
  432. nHostsOK=$((nHostsOK+1))
  433. ;;
  434. 2)
  435. nHostsBAD=$((nHostsBAD+1))
  436. ;;
  437. esac
  438. # touch the lockfile, for good measure.
  439. lockfile-touch --oneshot "$KNOWN_HOSTS"
  440. done
  441. # remove the lockfile
  442. lockfile-remove "$KNOWN_HOSTS"
  443. # note if the known_hosts file was updated
  444. if [ "$nHostsOK" -gt 0 -o "$nHostsBAD" -gt 0 ] ; then
  445. log "known_hosts file updated."
  446. fi
  447. # if an acceptable host was found, return 0
  448. if [ "$nHostsOK" -gt 0 ] ; then
  449. return 0
  450. # else if no ok hosts were found...
  451. else
  452. # if no bad host were found then no hosts were found at all,
  453. # and return 1
  454. if [ "$nHostsBAD" -eq 0 ] ; then
  455. return 1
  456. # else if at least one bad host was found, return 2
  457. else
  458. return 2
  459. fi
  460. fi
  461. }
  462. # process hosts from a known_hosts file
  463. process_known_hosts() {
  464. local hosts
  465. log "processing known_hosts file..."
  466. hosts=$(meat "$KNOWN_HOSTS" | cut -d ' ' -f 1 | grep -v '^|.*$' | tr , ' ' | tr '\n' ' ')
  467. # take all the hosts from the known_hosts file (first
  468. # field), grep out all the hashed hosts (lines starting
  469. # with '|')...
  470. update_known_hosts $hosts
  471. }
  472. # process uids for the authorized_keys file
  473. process_uid_authorized_keys() {
  474. local userID
  475. local nKeys
  476. local nKeysOK
  477. local ok
  478. local keyid
  479. userID="$1"
  480. log "processing user ID: $userID"
  481. nKeys=0
  482. nKeysOK=0
  483. for line in $(process_user_id "$userID") ; do
  484. # note that key was found
  485. nKeys=$((nKeys+1))
  486. ok=$(echo "$line" | cut -d: -f1)
  487. keyid=$(echo "$line" | cut -d: -f2)
  488. sshKey=$(gpg2ssh "$keyid")
  489. if [ -z "$sshKey" ] ; then
  490. log " ! key could not be translated."
  491. continue
  492. fi
  493. # remove the old host key line
  494. remove_line "$AUTHORIZED_KEYS" "$sshKey"
  495. # if key OK, add new host line
  496. if [ "$ok" -eq '0' ] ; then
  497. # note that key was found ok
  498. nKeysOK=$((nKeysOK+1))
  499. ssh2authorized_keys "$userID" "$sshKey" >> "$AUTHORIZED_KEYS"
  500. fi
  501. done
  502. # if at least one key was found...
  503. if [ "$nKeys" -gt 0 ] ; then
  504. # if ok keys were found, return 0
  505. if [ "$nKeysOK" -gt 0 ] ; then
  506. return 0
  507. # else return 2
  508. else
  509. return 2
  510. fi
  511. # if no keys were found, return 1
  512. else
  513. return 1
  514. fi
  515. }
  516. # update the authorized_keys files from a list of user IDs on command
  517. # line
  518. update_authorized_keys() {
  519. local userID
  520. local nIDs
  521. local nIDsOK
  522. local nIDsBAD
  523. # the number of ids specified on command line
  524. nIDs="$#"
  525. nIDsOK=0
  526. nIDsBAD=0
  527. # set the trap to remove any lockfiles on exit
  528. trap "lockfile-remove $AUTHORIZED_KEYS" EXIT
  529. # create a lockfile on authorized_keys
  530. lockfile-create "$AUTHORIZED_KEYS"
  531. for userID ; do
  532. # process the user ID, change return code if key not found for
  533. # user ID
  534. process_uid_authorized_keys "$userID"
  535. # note the result
  536. case "$?" in
  537. 0)
  538. nIDsOK=$((nIDsOK+1))
  539. ;;
  540. 2)
  541. nIDsBAD=$((nIDsBAD+1))
  542. ;;
  543. esac
  544. # touch the lockfile, for good measure.
  545. lockfile-touch --oneshot "$AUTHORIZED_KEYS"
  546. done
  547. # remove the lockfile
  548. lockfile-remove "$AUTHORIZED_KEYS"
  549. # note if the authorized_keys file was updated
  550. if [ "$nIDsOK" -gt 0 -o "$nIDsBAD" -gt 0 ] ; then
  551. log "authorized_keys file updated."
  552. fi
  553. # if an acceptable id was found, return 0
  554. if [ "$nIDsOK" -gt 0 ] ; then
  555. return 0
  556. # else if no ok ids were found...
  557. else
  558. # if no bad ids were found then no ids were found at all, and
  559. # return 1
  560. if [ "$nIDsBAD" -eq 0 ] ; then
  561. return 1
  562. # else if at least one bad id was found, return 2
  563. else
  564. return 2
  565. fi
  566. fi
  567. }
  568. # process an authorized_user_ids file for authorized_keys
  569. process_authorized_user_ids() {
  570. local line
  571. local nline
  572. local userIDs
  573. authorizedUserIDs="$1"
  574. log "processing authorized_user_ids file..."
  575. nline=0
  576. # extract user IDs from authorized_user_ids file
  577. IFS=$'\n'
  578. for line in $(meat "$authorizedUserIDs") ; do
  579. userIDs["$nline"]="$line"
  580. nline=$((nline+1))
  581. done
  582. update_authorized_keys "${userIDs[@]}"
  583. }
  584. # EXPERIMENTAL (unused) process userids found in authorized_keys file
  585. # go through line-by-line, extract monkeysphere userids from comment
  586. # fields, and process each userid
  587. # NOT WORKING
  588. process_authorized_keys() {
  589. local authorizedKeys
  590. local userID
  591. local returnCode
  592. # default return code is 0, and is set to 1 if a key for a user
  593. # is not found
  594. returnCode=0
  595. authorizedKeys="$1"
  596. # take all the monkeysphere userids from the authorized_keys file
  597. # comment field (third field) that starts with "MonkeySphere uid:"
  598. # FIXME: needs to handle authorized_keys options (field 0)
  599. meat "$authorizedKeys" | \
  600. while read -r options keytype key comment ; do
  601. # if the comment field is empty, assume the third field was
  602. # the comment
  603. if [ -z "$comment" ] ; then
  604. comment="$key"
  605. fi
  606. if echo "$comment" | egrep -v -q '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}' ; then
  607. continue
  608. fi
  609. userID=$(echo "$comment" | awk "{ print $2 }")
  610. if [ -z "$userID" ] ; then
  611. continue
  612. fi
  613. # process the userid
  614. log "processing userid: '$userID'"
  615. process_user_id "$userID" > /dev/null || returnCode=1
  616. done
  617. return "$returnCode"
  618. }