yubikey.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. // +build cgo
  2. package yubikey
  3. import (
  4. "context"
  5. "crypto"
  6. "crypto/x509"
  7. "encoding/hex"
  8. "net/url"
  9. "strings"
  10. "github.com/go-piv/piv-go/piv"
  11. "github.com/pkg/errors"
  12. "github.com/smallstep/certificates/kms/apiv1"
  13. "github.com/smallstep/certificates/kms/uri"
  14. )
  15. // Scheme is the scheme used in uris.
  16. const Scheme = "yubikey"
  17. // YubiKey implements the KMS interface on a YubiKey.
  18. type YubiKey struct {
  19. yk *piv.YubiKey
  20. pin string
  21. managementKey [24]byte
  22. }
  23. // New initializes a new YubiKey.
  24. // TODO(mariano): only one card is currently supported.
  25. func New(ctx context.Context, opts apiv1.Options) (*YubiKey, error) {
  26. managementKey := piv.DefaultManagementKey
  27. if opts.URI != "" {
  28. u, err := uri.ParseWithScheme(Scheme, opts.URI)
  29. if err != nil {
  30. return nil, err
  31. }
  32. if v := u.Pin(); v != "" {
  33. opts.Pin = v
  34. }
  35. if v := u.Get("management-key"); v != "" {
  36. opts.ManagementKey = v
  37. }
  38. }
  39. // Deprecated way to set configuration parameters.
  40. if opts.ManagementKey != "" {
  41. b, err := hex.DecodeString(opts.ManagementKey)
  42. if err != nil {
  43. return nil, errors.Wrap(err, "error decoding managementKey")
  44. }
  45. if len(b) != 24 {
  46. return nil, errors.New("invalid managementKey: length is not 24 bytes")
  47. }
  48. copy(managementKey[:], b[:24])
  49. }
  50. cards, err := piv.Cards()
  51. if err != nil {
  52. return nil, err
  53. }
  54. if len(cards) == 0 {
  55. return nil, errors.New("error detecting yubikey: try removing and reconnecting the device")
  56. }
  57. yk, err := piv.Open(cards[0])
  58. if err != nil {
  59. return nil, errors.Wrap(err, "error opening yubikey")
  60. }
  61. return &YubiKey{
  62. yk: yk,
  63. pin: opts.Pin,
  64. managementKey: managementKey,
  65. }, nil
  66. }
  67. func init() {
  68. apiv1.Register(apiv1.YubiKey, func(ctx context.Context, opts apiv1.Options) (apiv1.KeyManager, error) {
  69. return New(ctx, opts)
  70. })
  71. }
  72. // LoadCertificate implements kms.CertificateManager and loads a certificate
  73. // from the YubiKey.
  74. func (k *YubiKey) LoadCertificate(req *apiv1.LoadCertificateRequest) (*x509.Certificate, error) {
  75. slot, err := getSlot(req.Name)
  76. if err != nil {
  77. return nil, err
  78. }
  79. cert, err := k.yk.Certificate(slot)
  80. if err != nil {
  81. return nil, errors.Wrap(err, "error retrieving certificate")
  82. }
  83. return cert, nil
  84. }
  85. // StoreCertificate implements kms.CertificateManager and stores a certificate
  86. // in the YubiKey.
  87. func (k *YubiKey) StoreCertificate(req *apiv1.StoreCertificateRequest) error {
  88. if req.Certificate == nil {
  89. return errors.New("storeCertificateRequest 'Certificate' cannot be nil")
  90. }
  91. slot, err := getSlot(req.Name)
  92. if err != nil {
  93. return err
  94. }
  95. err = k.yk.SetCertificate(k.managementKey, slot, req.Certificate)
  96. if err != nil {
  97. return errors.Wrap(err, "error storing certificate")
  98. }
  99. return nil
  100. }
  101. // GetPublicKey returns the public key present in the YubiKey signature slot.
  102. func (k *YubiKey) GetPublicKey(req *apiv1.GetPublicKeyRequest) (crypto.PublicKey, error) {
  103. slot, err := getSlot(req.Name)
  104. if err != nil {
  105. return nil, err
  106. }
  107. pub, err := k.getPublicKey(slot)
  108. if err != nil {
  109. return nil, err
  110. }
  111. return pub, nil
  112. }
  113. // CreateKey generates a new key in the YubiKey and returns the public key.
  114. func (k *YubiKey) CreateKey(req *apiv1.CreateKeyRequest) (*apiv1.CreateKeyResponse, error) {
  115. alg, err := getSignatureAlgorithm(req.SignatureAlgorithm, req.Bits)
  116. if err != nil {
  117. return nil, err
  118. }
  119. slot, name, err := getSlotAndName(req.Name)
  120. if err != nil {
  121. return nil, err
  122. }
  123. pub, err := k.yk.GenerateKey(k.managementKey, slot, piv.Key{
  124. Algorithm: alg,
  125. PINPolicy: piv.PINPolicyAlways,
  126. TouchPolicy: piv.TouchPolicyNever,
  127. })
  128. if err != nil {
  129. return nil, errors.Wrap(err, "error generating key")
  130. }
  131. return &apiv1.CreateKeyResponse{
  132. Name: name,
  133. PublicKey: pub,
  134. CreateSignerRequest: apiv1.CreateSignerRequest{
  135. SigningKey: name,
  136. },
  137. }, nil
  138. }
  139. // CreateSigner creates a signer using the key present in the YubiKey signature
  140. // slot.
  141. func (k *YubiKey) CreateSigner(req *apiv1.CreateSignerRequest) (crypto.Signer, error) {
  142. slot, err := getSlot(req.SigningKey)
  143. if err != nil {
  144. return nil, err
  145. }
  146. pub, err := k.getPublicKey(slot)
  147. if err != nil {
  148. return nil, err
  149. }
  150. priv, err := k.yk.PrivateKey(slot, pub, piv.KeyAuth{
  151. PIN: k.pin,
  152. PINPolicy: piv.PINPolicyAlways,
  153. })
  154. if err != nil {
  155. return nil, errors.Wrap(err, "error retrieving private key")
  156. }
  157. signer, ok := priv.(crypto.Signer)
  158. if !ok {
  159. return nil, errors.New("private key is not a crypto.Signer")
  160. }
  161. return signer, nil
  162. }
  163. // Close releases the connection to the YubiKey.
  164. func (k *YubiKey) Close() error {
  165. return errors.Wrap(k.yk.Close(), "error closing yubikey")
  166. }
  167. // getPublicKey returns the public key on a slot. First it attempts to do
  168. // attestation to get a certificate with the public key in it, if this succeeds
  169. // means that the key was generated in the device. If not we'll try to get the
  170. // key from a stored certificate in the same slot.
  171. func (k *YubiKey) getPublicKey(slot piv.Slot) (crypto.PublicKey, error) {
  172. cert, err := k.yk.Attest(slot)
  173. if err != nil {
  174. if cert, err = k.yk.Certificate(slot); err != nil {
  175. return nil, errors.Wrap(err, "error retrieving public key")
  176. }
  177. }
  178. return cert.PublicKey, nil
  179. }
  180. // signatureAlgorithmMapping is a mapping between the step signature algorithm,
  181. // and bits for RSA keys, with yubikey ones.
  182. var signatureAlgorithmMapping = map[apiv1.SignatureAlgorithm]interface{}{
  183. apiv1.UnspecifiedSignAlgorithm: piv.AlgorithmEC256,
  184. apiv1.SHA256WithRSA: map[int]piv.Algorithm{
  185. 0: piv.AlgorithmRSA2048,
  186. 1024: piv.AlgorithmRSA1024,
  187. 2048: piv.AlgorithmRSA2048,
  188. },
  189. apiv1.SHA512WithRSA: map[int]piv.Algorithm{
  190. 0: piv.AlgorithmRSA2048,
  191. 1024: piv.AlgorithmRSA1024,
  192. 2048: piv.AlgorithmRSA2048,
  193. },
  194. apiv1.SHA256WithRSAPSS: map[int]piv.Algorithm{
  195. 0: piv.AlgorithmRSA2048,
  196. 1024: piv.AlgorithmRSA1024,
  197. 2048: piv.AlgorithmRSA2048,
  198. },
  199. apiv1.SHA512WithRSAPSS: map[int]piv.Algorithm{
  200. 0: piv.AlgorithmRSA2048,
  201. 1024: piv.AlgorithmRSA1024,
  202. 2048: piv.AlgorithmRSA2048,
  203. },
  204. apiv1.ECDSAWithSHA256: piv.AlgorithmEC256,
  205. apiv1.ECDSAWithSHA384: piv.AlgorithmEC384,
  206. }
  207. func getSignatureAlgorithm(alg apiv1.SignatureAlgorithm, bits int) (piv.Algorithm, error) {
  208. v, ok := signatureAlgorithmMapping[alg]
  209. if !ok {
  210. return 0, errors.Errorf("YubiKey does not support signature algorithm '%s'", alg)
  211. }
  212. switch v := v.(type) {
  213. case piv.Algorithm:
  214. return v, nil
  215. case map[int]piv.Algorithm:
  216. signatureAlgorithm, ok := v[bits]
  217. if !ok {
  218. return 0, errors.Errorf("YubiKey does not support signature algorithm '%s' with '%d' bits", alg, bits)
  219. }
  220. return signatureAlgorithm, nil
  221. default:
  222. return 0, errors.Errorf("unexpected error: this should not happen")
  223. }
  224. }
  225. var slotMapping = map[string]piv.Slot{
  226. "9a": piv.SlotAuthentication,
  227. "9c": piv.SlotSignature,
  228. "9e": piv.SlotCardAuthentication,
  229. "9d": piv.SlotKeyManagement,
  230. "82": {Key: 0x82, Object: 0x5FC10D},
  231. "83": {Key: 0x83, Object: 0x5FC10E},
  232. "84": {Key: 0x84, Object: 0x5FC10F},
  233. "85": {Key: 0x85, Object: 0x5FC110},
  234. "86": {Key: 0x86, Object: 0x5FC111},
  235. "87": {Key: 0x87, Object: 0x5FC112},
  236. "88": {Key: 0x88, Object: 0x5FC113},
  237. "89": {Key: 0x89, Object: 0x5FC114},
  238. "8a": {Key: 0x8a, Object: 0x5FC115},
  239. "8b": {Key: 0x8b, Object: 0x5FC116},
  240. "8c": {Key: 0x8c, Object: 0x5FC117},
  241. "8d": {Key: 0x8d, Object: 0x5FC118},
  242. "8e": {Key: 0x8e, Object: 0x5FC119},
  243. "8f": {Key: 0x8f, Object: 0x5FC11A},
  244. "90": {Key: 0x90, Object: 0x5FC11B},
  245. "91": {Key: 0x91, Object: 0x5FC11C},
  246. "92": {Key: 0x92, Object: 0x5FC11D},
  247. "93": {Key: 0x93, Object: 0x5FC11E},
  248. "94": {Key: 0x94, Object: 0x5FC11F},
  249. "95": {Key: 0x95, Object: 0x5FC120},
  250. }
  251. func getSlot(name string) (piv.Slot, error) {
  252. slot, _, err := getSlotAndName(name)
  253. return slot, err
  254. }
  255. func getSlotAndName(name string) (piv.Slot, string, error) {
  256. if name == "" {
  257. return piv.SlotSignature, "yubikey:slot-id=9c", nil
  258. }
  259. var slotID string
  260. name = strings.ToLower(name)
  261. if strings.HasPrefix(name, "yubikey:") {
  262. u, err := url.Parse(name)
  263. if err != nil {
  264. return piv.Slot{}, "", errors.Wrapf(err, "error parsing '%s'", name)
  265. }
  266. v, err := url.ParseQuery(u.Opaque)
  267. if err != nil {
  268. return piv.Slot{}, "", errors.Wrapf(err, "error parsing '%s'", name)
  269. }
  270. if slotID = v.Get("slot-id"); slotID == "" {
  271. return piv.Slot{}, "", errors.Wrapf(err, "error parsing '%s': slot-id is missing", name)
  272. }
  273. } else {
  274. slotID = name
  275. }
  276. s, ok := slotMapping[slotID]
  277. if !ok {
  278. return piv.Slot{}, "", errors.Errorf("unsupported slot-id '%s'", name)
  279. }
  280. name = "yubikey:slot-id=" + url.QueryEscape(slotID)
  281. return s, name, nil
  282. }