pkcs11.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. //go:build cgo
  2. // +build cgo
  3. package pkcs11
  4. import (
  5. "context"
  6. "crypto"
  7. "crypto/elliptic"
  8. "crypto/rsa"
  9. "crypto/x509"
  10. "encoding/hex"
  11. "fmt"
  12. "math/big"
  13. "strconv"
  14. "sync"
  15. "github.com/ThalesIgnite/crypto11"
  16. "github.com/pkg/errors"
  17. "github.com/smallstep/certificates/kms/apiv1"
  18. "github.com/smallstep/certificates/kms/uri"
  19. )
  20. // Scheme is the scheme used in uris.
  21. const Scheme = "pkcs11"
  22. // DefaultRSASize is the number of bits of a new RSA key if no size has been
  23. // specified.
  24. const DefaultRSASize = 3072
  25. // P11 defines the methods on crypto11.Context that this package will use. This
  26. // interface will be used for unit testing.
  27. type P11 interface {
  28. FindKeyPair(id, label []byte) (crypto11.Signer, error)
  29. FindCertificate(id, label []byte, serial *big.Int) (*x509.Certificate, error)
  30. ImportCertificateWithAttributes(template crypto11.AttributeSet, certificate *x509.Certificate) error
  31. DeleteCertificate(id, label []byte, serial *big.Int) error
  32. GenerateRSAKeyPairWithAttributes(public, private crypto11.AttributeSet, bits int) (crypto11.SignerDecrypter, error)
  33. GenerateECDSAKeyPairWithAttributes(public, private crypto11.AttributeSet, curve elliptic.Curve) (crypto11.Signer, error)
  34. Close() error
  35. }
  36. var p11Configure = func(config *crypto11.Config) (P11, error) {
  37. return crypto11.Configure(config)
  38. }
  39. // PKCS11 is the implementation of a KMS using the PKCS #11 standard.
  40. type PKCS11 struct {
  41. p11 P11
  42. closed sync.Once
  43. }
  44. // New returns a new PKCS11 KMS.
  45. func New(ctx context.Context, opts apiv1.Options) (*PKCS11, error) {
  46. var config crypto11.Config
  47. if opts.URI != "" {
  48. u, err := uri.ParseWithScheme(Scheme, opts.URI)
  49. if err != nil {
  50. return nil, err
  51. }
  52. config.Pin = u.Pin()
  53. config.Path = u.Get("module-path")
  54. config.TokenLabel = u.Get("token")
  55. config.TokenSerial = u.Get("serial")
  56. if v := u.Get("slot-id"); v != "" {
  57. n, err := strconv.Atoi(v)
  58. if err != nil {
  59. return nil, errors.Wrap(err, "kms uri 'slot-id' is not valid")
  60. }
  61. config.SlotNumber = &n
  62. }
  63. }
  64. if config.Pin == "" && opts.Pin != "" {
  65. config.Pin = opts.Pin
  66. }
  67. switch {
  68. case config.Path == "":
  69. return nil, errors.New("kms uri 'module-path' are required")
  70. case config.TokenLabel == "" && config.TokenSerial == "" && config.SlotNumber == nil:
  71. return nil, errors.New("kms uri 'token', 'serial' or 'slot-id' are required")
  72. case config.Pin == "":
  73. return nil, errors.New("kms 'pin' cannot be empty")
  74. case config.TokenLabel != "" && config.TokenSerial != "":
  75. return nil, errors.New("kms uri 'token' and 'serial' are mutually exclusive")
  76. case config.TokenLabel != "" && config.SlotNumber != nil:
  77. return nil, errors.New("kms uri 'token' and 'slot-id' are mutually exclusive")
  78. case config.TokenSerial != "" && config.SlotNumber != nil:
  79. return nil, errors.New("kms uri 'serial' and 'slot-id' are mutually exclusive")
  80. }
  81. p11, err := p11Configure(&config)
  82. if err != nil {
  83. return nil, errors.Wrap(err, "error initializing PKCS#11")
  84. }
  85. return &PKCS11{
  86. p11: p11,
  87. }, nil
  88. }
  89. func init() {
  90. apiv1.Register(apiv1.PKCS11, func(ctx context.Context, opts apiv1.Options) (apiv1.KeyManager, error) {
  91. return New(ctx, opts)
  92. })
  93. }
  94. // GetPublicKey returns the public key ....
  95. func (k *PKCS11) GetPublicKey(req *apiv1.GetPublicKeyRequest) (crypto.PublicKey, error) {
  96. if req.Name == "" {
  97. return nil, errors.New("getPublicKeyRequest 'name' cannot be empty")
  98. }
  99. signer, err := findSigner(k.p11, req.Name)
  100. if err != nil {
  101. return nil, errors.Wrap(err, "getPublicKey failed")
  102. }
  103. return signer.Public(), nil
  104. }
  105. // CreateKey generates a new key in the PKCS#11 module and returns the public key.
  106. func (k *PKCS11) CreateKey(req *apiv1.CreateKeyRequest) (*apiv1.CreateKeyResponse, error) {
  107. switch {
  108. case req.Name == "":
  109. return nil, errors.New("createKeyRequest 'name' cannot be empty")
  110. case req.Bits < 0:
  111. return nil, errors.New("createKeyRequest 'bits' cannot be negative")
  112. }
  113. signer, err := generateKey(k.p11, req)
  114. if err != nil {
  115. return nil, errors.Wrap(err, "createKey failed")
  116. }
  117. return &apiv1.CreateKeyResponse{
  118. Name: req.Name,
  119. PublicKey: signer.Public(),
  120. CreateSignerRequest: apiv1.CreateSignerRequest{
  121. SigningKey: req.Name,
  122. },
  123. }, nil
  124. }
  125. // CreateSigner creates a signer using a key present in the PKCS#11 module.
  126. func (k *PKCS11) CreateSigner(req *apiv1.CreateSignerRequest) (crypto.Signer, error) {
  127. if req.SigningKey == "" {
  128. return nil, errors.New("createSignerRequest 'signingKey' cannot be empty")
  129. }
  130. signer, err := findSigner(k.p11, req.SigningKey)
  131. if err != nil {
  132. return nil, errors.Wrap(err, "createSigner failed")
  133. }
  134. return signer, nil
  135. }
  136. // CreateDecrypter creates a decrypter using a key present in the PKCS#11
  137. // module.
  138. func (k *PKCS11) CreateDecrypter(req *apiv1.CreateDecrypterRequest) (crypto.Decrypter, error) {
  139. if req.DecryptionKey == "" {
  140. return nil, errors.New("createDecrypterRequest 'decryptionKey' cannot be empty")
  141. }
  142. signer, err := findSigner(k.p11, req.DecryptionKey)
  143. if err != nil {
  144. return nil, errors.Wrap(err, "createDecrypterRequest failed")
  145. }
  146. // Only RSA keys will implement the Decrypter interface.
  147. if _, ok := signer.Public().(*rsa.PublicKey); ok {
  148. if dec, ok := signer.(crypto.Decrypter); ok {
  149. return dec, nil
  150. }
  151. }
  152. return nil, errors.New("createDecrypterRequest failed: signer does not implement crypto.Decrypter")
  153. }
  154. // LoadCertificate implements kms.CertificateManager and loads a certificate
  155. // from the YubiKey.
  156. func (k *PKCS11) LoadCertificate(req *apiv1.LoadCertificateRequest) (*x509.Certificate, error) {
  157. if req.Name == "" {
  158. return nil, errors.New("loadCertificateRequest 'name' cannot be nil")
  159. }
  160. cert, err := findCertificate(k.p11, req.Name)
  161. if err != nil {
  162. return nil, errors.Wrap(err, "loadCertificate failed")
  163. }
  164. return cert, nil
  165. }
  166. // StoreCertificate implements kms.CertificateManager and stores a certificate
  167. // in the YubiKey.
  168. func (k *PKCS11) StoreCertificate(req *apiv1.StoreCertificateRequest) error {
  169. switch {
  170. case req.Name == "":
  171. return errors.New("storeCertificateRequest 'name' cannot be empty")
  172. case req.Certificate == nil:
  173. return errors.New("storeCertificateRequest 'Certificate' cannot be nil")
  174. }
  175. id, object, err := parseObject(req.Name)
  176. if err != nil {
  177. return errors.Wrap(err, "storeCertificate failed")
  178. }
  179. // Enforce the use of both id and labels. This is not strictly necessary in
  180. // PKCS #11, but it's a good practice.
  181. if len(id) == 0 || len(object) == 0 {
  182. return errors.Errorf("key with uri %s is not valid, id and object are required", req.Name)
  183. }
  184. cert, err := k.p11.FindCertificate(id, object, nil)
  185. if err != nil {
  186. return errors.Wrap(err, "storeCertificate failed")
  187. }
  188. if cert != nil {
  189. return errors.Wrap(apiv1.ErrAlreadyExists{
  190. Message: req.Name + " already exists",
  191. }, "storeCertificate failed")
  192. }
  193. // Import certificate with the necessary attributes.
  194. template, err := crypto11.NewAttributeSetWithIDAndLabel(id, object)
  195. if err != nil {
  196. return errors.Wrap(err, "storeCertificate failed")
  197. }
  198. if req.Extractable {
  199. template.Set(crypto11.CkaExtractable, true)
  200. }
  201. if err := k.p11.ImportCertificateWithAttributes(template, req.Certificate); err != nil {
  202. return errors.Wrap(err, "storeCertificate failed")
  203. }
  204. return nil
  205. }
  206. // DeleteKey is a utility function to delete a key given an uri.
  207. func (k *PKCS11) DeleteKey(u string) error {
  208. id, object, err := parseObject(u)
  209. if err != nil {
  210. return errors.Wrap(err, "deleteKey failed")
  211. }
  212. signer, err := k.p11.FindKeyPair(id, object)
  213. if err != nil {
  214. return errors.Wrap(err, "deleteKey failed")
  215. }
  216. if signer == nil {
  217. return nil
  218. }
  219. if err := signer.Delete(); err != nil {
  220. return errors.Wrap(err, "deleteKey failed")
  221. }
  222. return nil
  223. }
  224. // DeleteCertificate is a utility function to delete a certificate given an uri.
  225. func (k *PKCS11) DeleteCertificate(u string) error {
  226. id, object, err := parseObject(u)
  227. if err != nil {
  228. return errors.Wrap(err, "deleteCertificate failed")
  229. }
  230. if err := k.p11.DeleteCertificate(id, object, nil); err != nil {
  231. return errors.Wrap(err, "deleteCertificate failed")
  232. }
  233. return nil
  234. }
  235. // Close releases the connection to the PKCS#11 module.
  236. func (k *PKCS11) Close() (err error) {
  237. k.closed.Do(func() {
  238. err = errors.Wrap(k.p11.Close(), "error closing pkcs#11 context")
  239. })
  240. return
  241. }
  242. func toByte(s string) []byte {
  243. if s == "" {
  244. return nil
  245. }
  246. return []byte(s)
  247. }
  248. func parseObject(rawuri string) ([]byte, []byte, error) {
  249. u, err := uri.ParseWithScheme(Scheme, rawuri)
  250. if err != nil {
  251. return nil, nil, err
  252. }
  253. id := u.GetEncoded("id")
  254. object := u.Get("object")
  255. if len(id) == 0 && object == "" {
  256. return nil, nil, errors.Errorf("key with uri %s is not valid, id or object are required", rawuri)
  257. }
  258. return id, toByte(object), nil
  259. }
  260. func generateKey(ctx P11, req *apiv1.CreateKeyRequest) (crypto11.Signer, error) {
  261. id, object, err := parseObject(req.Name)
  262. if err != nil {
  263. return nil, err
  264. }
  265. signer, err := ctx.FindKeyPair(id, object)
  266. if err != nil {
  267. return nil, err
  268. }
  269. if signer != nil {
  270. return nil, apiv1.ErrAlreadyExists{
  271. Message: req.Name + " already exists",
  272. }
  273. }
  274. // Enforce the use of both id and labels. This is not strictly necessary in
  275. // PKCS #11, but it's a good practice.
  276. if len(id) == 0 || len(object) == 0 {
  277. return nil, errors.Errorf("key with uri %s is not valid, id and object are required", req.Name)
  278. }
  279. // Create template for public and private keys
  280. public, err := crypto11.NewAttributeSetWithIDAndLabel(id, object)
  281. if err != nil {
  282. return nil, err
  283. }
  284. private := public.Copy()
  285. if req.Extractable {
  286. private.Set(crypto11.CkaExtractable, true)
  287. }
  288. bits := req.Bits
  289. if bits == 0 {
  290. bits = DefaultRSASize
  291. }
  292. switch req.SignatureAlgorithm {
  293. case apiv1.UnspecifiedSignAlgorithm:
  294. return ctx.GenerateECDSAKeyPairWithAttributes(public, private, elliptic.P256())
  295. case apiv1.SHA256WithRSA, apiv1.SHA384WithRSA, apiv1.SHA512WithRSA:
  296. return ctx.GenerateRSAKeyPairWithAttributes(public, private, bits)
  297. case apiv1.SHA256WithRSAPSS, apiv1.SHA384WithRSAPSS, apiv1.SHA512WithRSAPSS:
  298. return ctx.GenerateRSAKeyPairWithAttributes(public, private, bits)
  299. case apiv1.ECDSAWithSHA256:
  300. return ctx.GenerateECDSAKeyPairWithAttributes(public, private, elliptic.P256())
  301. case apiv1.ECDSAWithSHA384:
  302. return ctx.GenerateECDSAKeyPairWithAttributes(public, private, elliptic.P384())
  303. case apiv1.ECDSAWithSHA512:
  304. return ctx.GenerateECDSAKeyPairWithAttributes(public, private, elliptic.P521())
  305. case apiv1.PureEd25519:
  306. return nil, fmt.Errorf("signature algorithm %s is not supported", req.SignatureAlgorithm)
  307. default:
  308. return nil, fmt.Errorf("signature algorithm %s is not supported", req.SignatureAlgorithm)
  309. }
  310. }
  311. func findSigner(ctx P11, rawuri string) (crypto11.Signer, error) {
  312. id, object, err := parseObject(rawuri)
  313. if err != nil {
  314. return nil, err
  315. }
  316. signer, err := ctx.FindKeyPair(id, object)
  317. if err != nil {
  318. return nil, errors.Wrapf(err, "error finding key with uri %s", rawuri)
  319. }
  320. if signer == nil {
  321. return nil, errors.Errorf("key with uri %s not found", rawuri)
  322. }
  323. return signer, nil
  324. }
  325. func findCertificate(ctx P11, rawuri string) (*x509.Certificate, error) {
  326. u, err := uri.ParseWithScheme(Scheme, rawuri)
  327. if err != nil {
  328. return nil, err
  329. }
  330. id, object, serial := u.GetEncoded("id"), u.Get("object"), u.Get("serial")
  331. if len(id) == 0 && object == "" && serial == "" {
  332. return nil, errors.Errorf("key with uri %s is not valid, id, object or serial are required", rawuri)
  333. }
  334. var serialNumber *big.Int
  335. if serial != "" {
  336. b, err := hex.DecodeString(serial)
  337. if err != nil {
  338. return nil, errors.Errorf("key with uri %s is not valid, failed to decode serial", rawuri)
  339. }
  340. serialNumber = new(big.Int).SetBytes(b)
  341. }
  342. cert, err := ctx.FindCertificate(id, toByte(object), serialNumber)
  343. if err != nil {
  344. return nil, errors.Wrapf(err, "error finding certificate with uri %s", rawuri)
  345. }
  346. if cert == nil {
  347. return nil, errors.Errorf("certificate with uri %s not found", rawuri)
  348. }
  349. return cert, nil
  350. }