summaryrefslogtreecommitdiff
path: root/src/common
blob: ba7df7320f69275f81e1d80cae4892649f95fcf2 (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 fileCheck
  416. local host
  417. # the number of hosts specified on command line
  418. nHosts="$#"
  419. nHostsOK=0
  420. nHostsBAD=0
  421. # set the trap to remove any lockfiles on exit
  422. trap "lockfile-remove $KNOWN_HOSTS" EXIT
  423. # create a lockfile on known_hosts
  424. lockfile-create "$KNOWN_HOSTS"
  425. # note pre update file checksum
  426. fileCheck=$(md5sum "$KNOWN_HOSTS")
  427. for host ; do
  428. # process the host
  429. process_host_known_hosts "$host"
  430. # note the result
  431. case "$?" in
  432. 0)
  433. nHostsOK=$((nHostsOK+1))
  434. ;;
  435. 2)
  436. nHostsBAD=$((nHostsBAD+1))
  437. ;;
  438. esac
  439. # touch the lockfile, for good measure.
  440. lockfile-touch --oneshot "$KNOWN_HOSTS"
  441. done
  442. # remove the lockfile
  443. lockfile-remove "$KNOWN_HOSTS"
  444. # note if the known_hosts file was updated
  445. if [ "$(md5sum "$KNOWN_HOSTS")" != "$fileCheck" ] ; then
  446. log "known_hosts file updated."
  447. fi
  448. # if an acceptable host was found, return 0
  449. if [ "$nHostsOK" -gt 0 ] ; then
  450. return 0
  451. # else if no ok hosts were found...
  452. else
  453. # if no bad host were found then no hosts were found at all,
  454. # and return 1
  455. if [ "$nHostsBAD" -eq 0 ] ; then
  456. return 1
  457. # else if at least one bad host was found, return 2
  458. else
  459. return 2
  460. fi
  461. fi
  462. }
  463. # process hosts from a known_hosts file
  464. process_known_hosts() {
  465. local hosts
  466. log "processing known_hosts file..."
  467. hosts=$(meat "$KNOWN_HOSTS" | cut -d ' ' -f 1 | grep -v '^|.*$' | tr , ' ' | tr '\n' ' ')
  468. if [ -z "$hosts" ] ; then
  469. log "no hosts to process."
  470. return
  471. fi
  472. # take all the hosts from the known_hosts file (first
  473. # field), grep out all the hashed hosts (lines starting
  474. # with '|')...
  475. update_known_hosts $hosts
  476. }
  477. # process uids for the authorized_keys file
  478. process_uid_authorized_keys() {
  479. local userID
  480. local nKeys
  481. local nKeysOK
  482. local ok
  483. local keyid
  484. userID="$1"
  485. log "processing user ID: $userID"
  486. nKeys=0
  487. nKeysOK=0
  488. for line in $(process_user_id "$userID") ; do
  489. # note that key was found
  490. nKeys=$((nKeys+1))
  491. ok=$(echo "$line" | cut -d: -f1)
  492. keyid=$(echo "$line" | cut -d: -f2)
  493. sshKey=$(gpg2ssh "$keyid")
  494. if [ -z "$sshKey" ] ; then
  495. log " ! key could not be translated."
  496. continue
  497. fi
  498. # remove the old host key line
  499. remove_line "$AUTHORIZED_KEYS" "$sshKey"
  500. # if key OK, add new host line
  501. if [ "$ok" -eq '0' ] ; then
  502. # note that key was found ok
  503. nKeysOK=$((nKeysOK+1))
  504. ssh2authorized_keys "$userID" "$sshKey" >> "$AUTHORIZED_KEYS"
  505. fi
  506. done
  507. # if at least one key was found...
  508. if [ "$nKeys" -gt 0 ] ; then
  509. # if ok keys were found, return 0
  510. if [ "$nKeysOK" -gt 0 ] ; then
  511. return 0
  512. # else return 2
  513. else
  514. return 2
  515. fi
  516. # if no keys were found, return 1
  517. else
  518. return 1
  519. fi
  520. }
  521. # update the authorized_keys files from a list of user IDs on command
  522. # line
  523. update_authorized_keys() {
  524. local userID
  525. local nIDs
  526. local nIDsOK
  527. local nIDsBAD
  528. local fileCheck
  529. # the number of ids specified on command line
  530. nIDs="$#"
  531. nIDsOK=0
  532. nIDsBAD=0
  533. # set the trap to remove any lockfiles on exit
  534. trap "lockfile-remove $AUTHORIZED_KEYS" EXIT
  535. # create a lockfile on authorized_keys
  536. lockfile-create "$AUTHORIZED_KEYS"
  537. # note pre update file checksum
  538. fileCheck=$(md5sum "$AUTHORIZED_KEYS")
  539. for userID ; do
  540. # process the user ID, change return code if key not found for
  541. # user ID
  542. process_uid_authorized_keys "$userID"
  543. # note the result
  544. case "$?" in
  545. 0)
  546. nIDsOK=$((nIDsOK+1))
  547. ;;
  548. 2)
  549. nIDsBAD=$((nIDsBAD+1))
  550. ;;
  551. esac
  552. # touch the lockfile, for good measure.
  553. lockfile-touch --oneshot "$AUTHORIZED_KEYS"
  554. done
  555. # remove the lockfile
  556. lockfile-remove "$AUTHORIZED_KEYS"
  557. # note if the authorized_keys file was updated
  558. if [ "$(md5sum "$AUTHORIZED_KEYS")" != "$fileCheck" ] ; then
  559. log "authorized_keys file updated."
  560. fi
  561. # if an acceptable id was found, return 0
  562. if [ "$nIDsOK" -gt 0 ] ; then
  563. return 0
  564. # else if no ok ids were found...
  565. else
  566. # if no bad ids were found then no ids were found at all, and
  567. # return 1
  568. if [ "$nIDsBAD" -eq 0 ] ; then
  569. return 1
  570. # else if at least one bad id was found, return 2
  571. else
  572. return 2
  573. fi
  574. fi
  575. }
  576. # process an authorized_user_ids file for authorized_keys
  577. process_authorized_user_ids() {
  578. local line
  579. local nline
  580. local userIDs
  581. authorizedUserIDs="$1"
  582. log "processing authorized_user_ids file..."
  583. if ! meat "$authorizedUserIDs" > /dev/null ; then
  584. log "no user IDs to process."
  585. return
  586. fi
  587. nline=0
  588. # extract user IDs from authorized_user_ids file
  589. IFS=$'\n'
  590. for line in $(meat "$authorizedUserIDs") ; do
  591. userIDs["$nline"]="$line"
  592. nline=$((nline+1))
  593. done
  594. update_authorized_keys "${userIDs[@]}"
  595. }
  596. # EXPERIMENTAL (unused) process userids found in authorized_keys file
  597. # go through line-by-line, extract monkeysphere userids from comment
  598. # fields, and process each userid
  599. # NOT WORKING
  600. process_authorized_keys() {
  601. local authorizedKeys
  602. local userID
  603. local returnCode
  604. # default return code is 0, and is set to 1 if a key for a user
  605. # is not found
  606. returnCode=0
  607. authorizedKeys="$1"
  608. # take all the monkeysphere userids from the authorized_keys file
  609. # comment field (third field) that starts with "MonkeySphere uid:"
  610. # FIXME: needs to handle authorized_keys options (field 0)
  611. meat "$authorizedKeys" | \
  612. while read -r options keytype key comment ; do
  613. # if the comment field is empty, assume the third field was
  614. # the comment
  615. if [ -z "$comment" ] ; then
  616. comment="$key"
  617. fi
  618. if echo "$comment" | egrep -v -q '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}' ; then
  619. continue
  620. fi
  621. userID=$(echo "$comment" | awk "{ print $2 }")
  622. if [ -z "$userID" ] ; then
  623. continue
  624. fi
  625. # process the userid
  626. log "processing userid: '$userID'"
  627. process_user_id "$userID" > /dev/null || returnCode=1
  628. done
  629. return "$returnCode"
  630. }