pkcs11.go 11 KB

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