pkcs11.go 10 KB

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