yubikey.go 8.4 KB

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