Advertisement
Guest User

Untitled

a guest
Apr 27th, 2017
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.06 KB | None | 0 0
  1. #!/bin/bash
  2. set -eu
  3.  
  4. # This script prints the first PIV certificate found from a smart card in SSH
  5. # format in the same way that putty-cac does on windows. (yeah.)
  6.  
  7. # LICENSE
  8. #
  9. # As a work of the United States Government, this project is in the public
  10. # domain within the United States.
  11. #
  12. # Additionally, we waive copyright and related rights in the work worldwide
  13. # through the CC0 1.0 Universal public domain dedication.
  14.  
  15. run() {
  16. echo >&2 "+ $*"
  17. "$@"
  18. }
  19.  
  20. get_piv_pubkey_mac() {
  21. lastfirst_str="$(id -F)"
  22. lastfirst_arr=( ${lastfirst_str//,/} )
  23.  
  24. fullname="${lastfirst_arr[*]:1} ${lastfirst_arr[0]}"
  25. fullname_upper="$(echo "$fullname" | tr '[:lower:]' '[:upper:]')"
  26.  
  27. # Contractor format
  28. fullname_upper_affiliate="$fullname_upper (affiliate)"
  29.  
  30. cert="$(run security find-certificate -p "PIV-$fullname_upper")" || true
  31. if [ -z "$cert" ]; then
  32. cert="$(run security find-certificate -p "PIV-$fullname_upper_affiliate")"
  33. fi
  34.  
  35. print_pubkey_from_cert "$cert"
  36. }
  37.  
  38. print_pubkey_from_cert() {
  39. if [ $# -lt 1 ]; then
  40. echo >&2 "usage: print_pubkey_from_cert X509_CERT_CONTENT"
  41. return 1
  42. fi
  43. cert="$1"
  44.  
  45. pubkey="$(ssh-keygen -i -m pkcs8 -f <(
  46. openssl x509 -noout -pubkey <<< "$cert"))"
  47.  
  48. sha1="$(openssl x509 -noout -fingerprint <<< "$cert" \
  49. | cut -d'=' -f2 | tr -d ':')"
  50.  
  51. echo "$pubkey CAPI:User\\MY\\$sha1"
  52. }
  53.  
  54.  
  55. get_piv_pubkey_opensc() {
  56. # we could use `--read-ssh-key 1` instead, but putty uses the SHA1
  57. # fingerprint of the full X.509 certificate, not just the RSA public key
  58.  
  59. # use the first certificate found
  60. cert="$(run pkcs15-tool --read-certificate 1)"
  61.  
  62. print_pubkey_from_cert "$cert"
  63. }
  64.  
  65. trap 'echo ERROR' EXIT
  66.  
  67. # use opensc if it is installed
  68. if which pkcs15-tool >/dev/null 2>&1; then
  69. get_piv_pubkey_opensc
  70. trap - EXIT
  71. exit
  72. fi
  73.  
  74. case "$OSTYPE" in
  75. darwin*)
  76. get_piv_pubkey_mac
  77. ;;
  78. linux*)
  79. get_piv_pubkey_opensc
  80. ;;
  81. *)
  82. trap - EXIT
  83. echo >&2 "Not yet implemented for $OSTYPE. Sorry!"
  84. exit 1
  85. ;;
  86. esac
  87.  
  88. trap - EXIT
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement