pkcs11_test.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836
  1. //go:build cgo
  2. // +build cgo
  3. package pkcs11
  4. import (
  5. "bytes"
  6. "context"
  7. "crypto"
  8. "crypto/ecdsa"
  9. "crypto/ed25519"
  10. "crypto/rand"
  11. "crypto/rsa"
  12. "crypto/x509"
  13. "math/big"
  14. "reflect"
  15. "strings"
  16. "testing"
  17. "github.com/ThalesIgnite/crypto11"
  18. "github.com/pkg/errors"
  19. "github.com/smallstep/certificates/kms/apiv1"
  20. "golang.org/x/crypto/cryptobyte"
  21. "golang.org/x/crypto/cryptobyte/asn1"
  22. )
  23. func TestNew(t *testing.T) {
  24. tmp := p11Configure
  25. t.Cleanup(func() {
  26. p11Configure = tmp
  27. })
  28. k := mustPKCS11(t)
  29. t.Cleanup(func() {
  30. k.Close()
  31. })
  32. p11Configure = func(config *crypto11.Config) (P11, error) {
  33. if strings.Contains(config.Path, "fail") {
  34. return nil, errors.New("an error")
  35. }
  36. return k.p11, nil
  37. }
  38. type args struct {
  39. ctx context.Context
  40. opts apiv1.Options
  41. }
  42. tests := []struct {
  43. name string
  44. args args
  45. want *PKCS11
  46. wantErr bool
  47. }{
  48. {"ok", args{context.Background(), apiv1.Options{
  49. Type: "pkcs11",
  50. URI: "pkcs11:module-path=/usr/local/lib/softhsm/libsofthsm2.so;token=pkcs11-test?pin-value=password",
  51. }}, k, false},
  52. {"ok with serial", args{context.Background(), apiv1.Options{
  53. Type: "pkcs11",
  54. URI: "pkcs11:module-path=/usr/local/lib/softhsm/libsofthsm2.so;serial=0123456789?pin-value=password",
  55. }}, k, false},
  56. {"ok with slot-id", args{context.Background(), apiv1.Options{
  57. Type: "pkcs11",
  58. URI: "pkcs11:module-path=/usr/local/lib/softhsm/libsofthsm2.so;slot-id=0?pin-value=password",
  59. }}, k, false},
  60. {"ok with pin", args{context.Background(), apiv1.Options{
  61. Type: "pkcs11",
  62. URI: "pkcs11:module-path=/usr/local/lib/softhsm/libsofthsm2.so;token=pkcs11-test",
  63. Pin: "passowrd",
  64. }}, k, false},
  65. {"fail missing module", args{context.Background(), apiv1.Options{
  66. Type: "pkcs11",
  67. URI: "pkcs11:token=pkcs11-test",
  68. Pin: "passowrd",
  69. }}, nil, true},
  70. {"fail missing pin", args{context.Background(), apiv1.Options{
  71. Type: "pkcs11",
  72. URI: "pkcs11:module-path=/usr/local/lib/softhsm/libsofthsm2.so;token=pkcs11-test",
  73. }}, nil, true},
  74. {"fail missing token/serial/slot-id", args{context.Background(), apiv1.Options{
  75. Type: "pkcs11",
  76. URI: "pkcs11:module-path=/usr/local/lib/softhsm/libsofthsm2.so",
  77. Pin: "passowrd",
  78. }}, nil, true},
  79. {"fail token+serial+slot-id", args{context.Background(), apiv1.Options{
  80. Type: "pkcs11",
  81. URI: "pkcs11:module-path=/usr/local/lib/softhsm/libsofthsm2.so;token=pkcs11-test;serial=0123456789;slot-id=0",
  82. Pin: "passowrd",
  83. }}, nil, true},
  84. {"fail token+serial", args{context.Background(), apiv1.Options{
  85. Type: "pkcs11",
  86. URI: "pkcs11:module-path=/usr/local/lib/softhsm/libsofthsm2.so;token=pkcs11-test;serial=0123456789",
  87. Pin: "passowrd",
  88. }}, nil, true},
  89. {"fail token+slot-id", args{context.Background(), apiv1.Options{
  90. Type: "pkcs11",
  91. URI: "pkcs11:module-path=/usr/local/lib/softhsm/libsofthsm2.so;token=pkcs11-test;slot-id=0",
  92. Pin: "passowrd",
  93. }}, nil, true},
  94. {"fail serial+slot-id", args{context.Background(), apiv1.Options{
  95. Type: "pkcs11",
  96. URI: "pkcs11:module-path=/usr/local/lib/softhsm/libsofthsm2.so;serial=0123456789;slot-id=0",
  97. Pin: "passowrd",
  98. }}, nil, true},
  99. {"fail slot-id", args{context.Background(), apiv1.Options{
  100. Type: "pkcs11",
  101. URI: "pkcs11:module-path=/usr/local/lib/softhsm/libsofthsm2.so;slot-id=x?pin-value=password",
  102. }}, nil, true},
  103. {"fail scheme", args{context.Background(), apiv1.Options{
  104. Type: "pkcs11",
  105. URI: "foo:module-path=/usr/local/lib/softhsm/libsofthsm2.so;token=pkcs11-test?pin-value=password",
  106. }}, nil, true},
  107. {"fail configure", args{context.Background(), apiv1.Options{
  108. Type: "pkcs11",
  109. URI: "pkcs11:module-path=/usr/local/lib/fail.so;token=pkcs11-test?pin-value=password",
  110. }}, nil, true},
  111. }
  112. for _, tt := range tests {
  113. t.Run(tt.name, func(t *testing.T) {
  114. got, err := New(tt.args.ctx, tt.args.opts)
  115. if (err != nil) != tt.wantErr {
  116. t.Errorf("New() error = %v, wantErr %v", err, tt.wantErr)
  117. return
  118. }
  119. if !reflect.DeepEqual(got, tt.want) {
  120. t.Errorf("New() = %v, want %v", got, tt.want)
  121. }
  122. })
  123. }
  124. }
  125. func TestPKCS11_GetPublicKey(t *testing.T) {
  126. k := setupPKCS11(t)
  127. type args struct {
  128. req *apiv1.GetPublicKeyRequest
  129. }
  130. tests := []struct {
  131. name string
  132. args args
  133. want crypto.PublicKey
  134. wantErr bool
  135. }{
  136. {"RSA", args{&apiv1.GetPublicKeyRequest{
  137. Name: "pkcs11:id=7371;object=rsa-key",
  138. }}, &rsa.PublicKey{}, false},
  139. {"RSA by id", args{&apiv1.GetPublicKeyRequest{
  140. Name: "pkcs11:id=7371",
  141. }}, &rsa.PublicKey{}, false},
  142. {"RSA by label", args{&apiv1.GetPublicKeyRequest{
  143. Name: "pkcs11:object=rsa-key",
  144. }}, &rsa.PublicKey{}, false},
  145. {"ECDSA", args{&apiv1.GetPublicKeyRequest{
  146. Name: "pkcs11:id=7373;object=ecdsa-p256-key",
  147. }}, &ecdsa.PublicKey{}, false},
  148. {"ECDSA by id", args{&apiv1.GetPublicKeyRequest{
  149. Name: "pkcs11:id=7373",
  150. }}, &ecdsa.PublicKey{}, false},
  151. {"ECDSA by label", args{&apiv1.GetPublicKeyRequest{
  152. Name: "pkcs11:object=ecdsa-p256-key",
  153. }}, &ecdsa.PublicKey{}, false},
  154. {"fail name", args{&apiv1.GetPublicKeyRequest{
  155. Name: "",
  156. }}, nil, true},
  157. {"fail uri", args{&apiv1.GetPublicKeyRequest{
  158. Name: "https:id=9999;object=https",
  159. }}, nil, true},
  160. {"fail missing", args{&apiv1.GetPublicKeyRequest{
  161. Name: "pkcs11:id=9999;object=rsa-key",
  162. }}, nil, true},
  163. {"fail FindKeyPair", args{&apiv1.GetPublicKeyRequest{
  164. Name: "pkcs11:foo=bar",
  165. }}, nil, true},
  166. }
  167. for _, tt := range tests {
  168. t.Run(tt.name, func(t *testing.T) {
  169. got, err := k.GetPublicKey(tt.args.req)
  170. if (err != nil) != tt.wantErr {
  171. t.Errorf("PKCS11.GetPublicKey() error = %v, wantErr %v", err, tt.wantErr)
  172. return
  173. }
  174. if reflect.TypeOf(got) != reflect.TypeOf(tt.want) {
  175. t.Errorf("PKCS11.GetPublicKey() = %T, want %T", got, tt.want)
  176. }
  177. })
  178. }
  179. }
  180. func TestPKCS11_CreateKey(t *testing.T) {
  181. k := setupPKCS11(t)
  182. // Make sure to delete the created key
  183. k.DeleteKey(testObject)
  184. type args struct {
  185. req *apiv1.CreateKeyRequest
  186. }
  187. tests := []struct {
  188. name string
  189. args args
  190. want *apiv1.CreateKeyResponse
  191. wantErr bool
  192. }{
  193. {"default", args{&apiv1.CreateKeyRequest{
  194. Name: testObject,
  195. }}, &apiv1.CreateKeyResponse{
  196. Name: testObject,
  197. PublicKey: &ecdsa.PublicKey{},
  198. CreateSignerRequest: apiv1.CreateSignerRequest{
  199. SigningKey: testObject,
  200. },
  201. }, false},
  202. {"default extractable", args{&apiv1.CreateKeyRequest{
  203. Name: testObject,
  204. Extractable: true,
  205. }}, &apiv1.CreateKeyResponse{
  206. Name: testObject,
  207. PublicKey: &ecdsa.PublicKey{},
  208. CreateSignerRequest: apiv1.CreateSignerRequest{
  209. SigningKey: testObject,
  210. },
  211. }, false},
  212. {"RSA SHA256WithRSA", args{&apiv1.CreateKeyRequest{
  213. Name: testObject,
  214. SignatureAlgorithm: apiv1.SHA256WithRSA,
  215. }}, &apiv1.CreateKeyResponse{
  216. Name: testObject,
  217. PublicKey: &rsa.PublicKey{},
  218. CreateSignerRequest: apiv1.CreateSignerRequest{
  219. SigningKey: testObject,
  220. },
  221. }, false},
  222. {"RSA SHA384WithRSA", args{&apiv1.CreateKeyRequest{
  223. Name: testObject,
  224. SignatureAlgorithm: apiv1.SHA384WithRSA,
  225. }}, &apiv1.CreateKeyResponse{
  226. Name: testObject,
  227. PublicKey: &rsa.PublicKey{},
  228. CreateSignerRequest: apiv1.CreateSignerRequest{
  229. SigningKey: testObject,
  230. },
  231. }, false},
  232. {"RSA SHA512WithRSA", args{&apiv1.CreateKeyRequest{
  233. Name: testObject,
  234. SignatureAlgorithm: apiv1.SHA512WithRSA,
  235. }}, &apiv1.CreateKeyResponse{
  236. Name: testObject,
  237. PublicKey: &rsa.PublicKey{},
  238. CreateSignerRequest: apiv1.CreateSignerRequest{
  239. SigningKey: testObject,
  240. },
  241. }, false},
  242. {"RSA SHA256WithRSAPSS", args{&apiv1.CreateKeyRequest{
  243. Name: testObject,
  244. SignatureAlgorithm: apiv1.SHA256WithRSAPSS,
  245. }}, &apiv1.CreateKeyResponse{
  246. Name: testObject,
  247. PublicKey: &rsa.PublicKey{},
  248. CreateSignerRequest: apiv1.CreateSignerRequest{
  249. SigningKey: testObject,
  250. },
  251. }, false},
  252. {"RSA SHA384WithRSAPSS", args{&apiv1.CreateKeyRequest{
  253. Name: testObject,
  254. SignatureAlgorithm: apiv1.SHA384WithRSAPSS,
  255. }}, &apiv1.CreateKeyResponse{
  256. Name: testObject,
  257. PublicKey: &rsa.PublicKey{},
  258. CreateSignerRequest: apiv1.CreateSignerRequest{
  259. SigningKey: testObject,
  260. },
  261. }, false},
  262. {"RSA SHA512WithRSAPSS", args{&apiv1.CreateKeyRequest{
  263. Name: testObject,
  264. SignatureAlgorithm: apiv1.SHA512WithRSAPSS,
  265. }}, &apiv1.CreateKeyResponse{
  266. Name: testObject,
  267. PublicKey: &rsa.PublicKey{},
  268. CreateSignerRequest: apiv1.CreateSignerRequest{
  269. SigningKey: testObject,
  270. },
  271. }, false},
  272. {"RSA 2048", args{&apiv1.CreateKeyRequest{
  273. Name: testObject,
  274. SignatureAlgorithm: apiv1.SHA256WithRSA,
  275. Bits: 2048,
  276. }}, &apiv1.CreateKeyResponse{
  277. Name: testObject,
  278. PublicKey: &rsa.PublicKey{},
  279. CreateSignerRequest: apiv1.CreateSignerRequest{
  280. SigningKey: testObject,
  281. },
  282. }, false},
  283. {"RSA 4096", args{&apiv1.CreateKeyRequest{
  284. Name: testObject,
  285. SignatureAlgorithm: apiv1.SHA256WithRSA,
  286. Bits: 4096,
  287. }}, &apiv1.CreateKeyResponse{
  288. Name: testObject,
  289. PublicKey: &rsa.PublicKey{},
  290. CreateSignerRequest: apiv1.CreateSignerRequest{
  291. SigningKey: testObject,
  292. },
  293. }, false},
  294. {"ECDSA P256", args{&apiv1.CreateKeyRequest{
  295. Name: testObject,
  296. SignatureAlgorithm: apiv1.ECDSAWithSHA256,
  297. }}, &apiv1.CreateKeyResponse{
  298. Name: testObject,
  299. PublicKey: &ecdsa.PublicKey{},
  300. CreateSignerRequest: apiv1.CreateSignerRequest{
  301. SigningKey: testObject,
  302. },
  303. }, false},
  304. {"ECDSA P384", args{&apiv1.CreateKeyRequest{
  305. Name: testObject,
  306. SignatureAlgorithm: apiv1.ECDSAWithSHA384,
  307. }}, &apiv1.CreateKeyResponse{
  308. Name: testObject,
  309. PublicKey: &ecdsa.PublicKey{},
  310. CreateSignerRequest: apiv1.CreateSignerRequest{
  311. SigningKey: testObject,
  312. },
  313. }, false},
  314. {"ECDSA P521", args{&apiv1.CreateKeyRequest{
  315. Name: testObject,
  316. SignatureAlgorithm: apiv1.ECDSAWithSHA512,
  317. }}, &apiv1.CreateKeyResponse{
  318. Name: testObject,
  319. PublicKey: &ecdsa.PublicKey{},
  320. CreateSignerRequest: apiv1.CreateSignerRequest{
  321. SigningKey: testObject,
  322. },
  323. }, false},
  324. {"fail name", args{&apiv1.CreateKeyRequest{
  325. Name: "",
  326. }}, nil, true},
  327. {"fail no id", args{&apiv1.CreateKeyRequest{
  328. Name: "pkcs11:object=create-key",
  329. }}, nil, true},
  330. {"fail no object", args{&apiv1.CreateKeyRequest{
  331. Name: "pkcs11:id=9999",
  332. }}, nil, true},
  333. {"fail schema", args{&apiv1.CreateKeyRequest{
  334. Name: "pkcs12:id=9999;object=create-key",
  335. }}, nil, true},
  336. {"fail bits", args{&apiv1.CreateKeyRequest{
  337. Name: "pkcs11:id=9999;object=create-key",
  338. Bits: -1,
  339. SignatureAlgorithm: apiv1.SHA256WithRSAPSS,
  340. }}, nil, true},
  341. {"fail ed25519", args{&apiv1.CreateKeyRequest{
  342. Name: "pkcs11:id=9999;object=create-key",
  343. SignatureAlgorithm: apiv1.PureEd25519,
  344. }}, nil, true},
  345. {"fail unknown", args{&apiv1.CreateKeyRequest{
  346. Name: "pkcs11:id=9999;object=create-key",
  347. SignatureAlgorithm: apiv1.SignatureAlgorithm(100),
  348. }}, nil, true},
  349. {"fail FindKeyPair", args{&apiv1.CreateKeyRequest{
  350. Name: "pkcs11:foo=bar",
  351. SignatureAlgorithm: apiv1.SHA256WithRSAPSS,
  352. }}, nil, true},
  353. {"fail already exists", args{&apiv1.CreateKeyRequest{
  354. Name: "pkcs11:id=7373;object=ecdsa-p256-key",
  355. SignatureAlgorithm: apiv1.ECDSAWithSHA256,
  356. }}, nil, true},
  357. }
  358. for _, tt := range tests {
  359. t.Run(tt.name, func(t *testing.T) {
  360. got, err := k.CreateKey(tt.args.req)
  361. if (err != nil) != tt.wantErr {
  362. t.Errorf("PKCS11.CreateKey() error = %v, wantErr %v", err, tt.wantErr)
  363. return
  364. }
  365. if got != nil {
  366. got.PublicKey = tt.want.PublicKey
  367. }
  368. if !reflect.DeepEqual(got, tt.want) {
  369. t.Errorf("PKCS11.CreateKey() = %v, want %v", got, tt.want)
  370. }
  371. if got != nil {
  372. if err := k.DeleteKey(got.Name); err != nil {
  373. t.Errorf("PKCS11.DeleteKey() error = %v", err)
  374. }
  375. }
  376. })
  377. }
  378. }
  379. func TestPKCS11_CreateSigner(t *testing.T) {
  380. k := setupPKCS11(t)
  381. data := []byte("buggy-coheir-RUBRIC-rabbet-liberal-eaglet-khartoum-stagger")
  382. // VerifyASN1 verifies the ASN.1 encoded signature, sig, of hash using the
  383. // public key, pub. Its return value records whether the signature is valid.
  384. verifyASN1 := func(pub *ecdsa.PublicKey, hash, sig []byte) bool {
  385. var (
  386. r, s = &big.Int{}, &big.Int{}
  387. inner cryptobyte.String
  388. )
  389. input := cryptobyte.String(sig)
  390. if !input.ReadASN1(&inner, asn1.SEQUENCE) ||
  391. !input.Empty() ||
  392. !inner.ReadASN1Integer(r) ||
  393. !inner.ReadASN1Integer(s) ||
  394. !inner.Empty() {
  395. return false
  396. }
  397. return ecdsa.Verify(pub, hash, r, s)
  398. }
  399. type args struct {
  400. req *apiv1.CreateSignerRequest
  401. }
  402. tests := []struct {
  403. name string
  404. args args
  405. algorithm apiv1.SignatureAlgorithm
  406. signerOpts crypto.SignerOpts
  407. wantErr bool
  408. }{
  409. // SoftHSM2
  410. {"RSA", args{&apiv1.CreateSignerRequest{
  411. SigningKey: "pkcs11:id=7371;object=rsa-key",
  412. }}, apiv1.SHA256WithRSA, crypto.SHA256, false},
  413. {"RSA PSS", args{&apiv1.CreateSignerRequest{
  414. SigningKey: "pkcs11:id=7372;object=rsa-pss-key",
  415. }}, apiv1.SHA256WithRSAPSS, &rsa.PSSOptions{
  416. SaltLength: rsa.PSSSaltLengthEqualsHash,
  417. Hash: crypto.SHA256,
  418. }, false},
  419. {"ECDSA P256", args{&apiv1.CreateSignerRequest{
  420. SigningKey: "pkcs11:id=7373;object=ecdsa-p256-key",
  421. }}, apiv1.ECDSAWithSHA256, crypto.SHA256, false},
  422. {"ECDSA P384", args{&apiv1.CreateSignerRequest{
  423. SigningKey: "pkcs11:id=7374;object=ecdsa-p384-key",
  424. }}, apiv1.ECDSAWithSHA384, crypto.SHA384, false},
  425. {"ECDSA P521", args{&apiv1.CreateSignerRequest{
  426. SigningKey: "pkcs11:id=7375;object=ecdsa-p521-key",
  427. }}, apiv1.ECDSAWithSHA512, crypto.SHA512, false},
  428. {"fail SigningKey", args{&apiv1.CreateSignerRequest{
  429. SigningKey: "",
  430. }}, 0, nil, true},
  431. {"fail uri", args{&apiv1.CreateSignerRequest{
  432. SigningKey: "https:id=7375;object=ecdsa-p521-key",
  433. }}, 0, nil, true},
  434. {"fail FindKeyPair", args{&apiv1.CreateSignerRequest{
  435. SigningKey: "pkcs11:foo=bar",
  436. }}, 0, nil, true},
  437. }
  438. for _, tt := range tests {
  439. t.Run(tt.name, func(t *testing.T) {
  440. got, err := k.CreateSigner(tt.args.req)
  441. if (err != nil) != tt.wantErr {
  442. t.Errorf("PKCS11.CreateSigner() error = %v, wantErr %v", err, tt.wantErr)
  443. return
  444. }
  445. if got != nil {
  446. hash := tt.signerOpts.HashFunc()
  447. h := hash.New()
  448. h.Write(data)
  449. digest := h.Sum(nil)
  450. sig, err := got.Sign(rand.Reader, digest, tt.signerOpts)
  451. if err != nil {
  452. t.Errorf("cyrpto.Signer.Sign() error = %v", err)
  453. }
  454. switch tt.algorithm {
  455. case apiv1.SHA256WithRSA, apiv1.SHA384WithRSA, apiv1.SHA512WithRSA:
  456. pub := got.Public().(*rsa.PublicKey)
  457. if err := rsa.VerifyPKCS1v15(pub, hash, digest, sig); err != nil {
  458. t.Errorf("rsa.VerifyPKCS1v15() error = %v", err)
  459. }
  460. case apiv1.UnspecifiedSignAlgorithm, apiv1.SHA256WithRSAPSS, apiv1.SHA384WithRSAPSS, apiv1.SHA512WithRSAPSS:
  461. pub := got.Public().(*rsa.PublicKey)
  462. if err := rsa.VerifyPSS(pub, hash, digest, sig, tt.signerOpts.(*rsa.PSSOptions)); err != nil {
  463. t.Errorf("rsa.VerifyPSS() error = %v", err)
  464. }
  465. case apiv1.ECDSAWithSHA256, apiv1.ECDSAWithSHA384, apiv1.ECDSAWithSHA512:
  466. pub := got.Public().(*ecdsa.PublicKey)
  467. if !verifyASN1(pub, digest, sig) {
  468. t.Error("ecdsa.VerifyASN1() failed")
  469. }
  470. default:
  471. t.Errorf("signature algorithm %s is not supported", tt.algorithm)
  472. }
  473. }
  474. })
  475. }
  476. }
  477. func TestPKCS11_CreateDecrypter(t *testing.T) {
  478. k := setupPKCS11(t)
  479. data := []byte("buggy-coheir-RUBRIC-rabbet-liberal-eaglet-khartoum-stagger")
  480. type args struct {
  481. req *apiv1.CreateDecrypterRequest
  482. }
  483. tests := []struct {
  484. name string
  485. args args
  486. wantErr bool
  487. }{
  488. {"RSA", args{&apiv1.CreateDecrypterRequest{
  489. DecryptionKey: "pkcs11:id=7371;object=rsa-key",
  490. }}, false},
  491. {"RSA PSS", args{&apiv1.CreateDecrypterRequest{
  492. DecryptionKey: "pkcs11:id=7372;object=rsa-pss-key",
  493. }}, false},
  494. {"ECDSA P256", args{&apiv1.CreateDecrypterRequest{
  495. DecryptionKey: "pkcs11:id=7373;object=ecdsa-p256-key",
  496. }}, true},
  497. {"ECDSA P384", args{&apiv1.CreateDecrypterRequest{
  498. DecryptionKey: "pkcs11:id=7374;object=ecdsa-p384-key",
  499. }}, true},
  500. {"ECDSA P521", args{&apiv1.CreateDecrypterRequest{
  501. DecryptionKey: "pkcs11:id=7375;object=ecdsa-p521-key",
  502. }}, true},
  503. {"fail DecryptionKey", args{&apiv1.CreateDecrypterRequest{
  504. DecryptionKey: "",
  505. }}, true},
  506. {"fail uri", args{&apiv1.CreateDecrypterRequest{
  507. DecryptionKey: "https:id=7375;object=ecdsa-p521-key",
  508. }}, true},
  509. {"fail FindKeyPair", args{&apiv1.CreateDecrypterRequest{
  510. DecryptionKey: "pkcs11:foo=bar",
  511. }}, true},
  512. }
  513. for _, tt := range tests {
  514. t.Run(tt.name, func(t *testing.T) {
  515. got, err := k.CreateDecrypter(tt.args.req)
  516. if (err != nil) != tt.wantErr {
  517. t.Errorf("PKCS11.CreateDecrypter() error = %v, wantErr %v", err, tt.wantErr)
  518. return
  519. }
  520. if got != nil {
  521. pub := got.Public().(*rsa.PublicKey)
  522. // PKCS#1 v1.5
  523. enc, err := rsa.EncryptPKCS1v15(rand.Reader, pub, data)
  524. if err != nil {
  525. t.Errorf("rsa.EncryptPKCS1v15() error = %v", err)
  526. return
  527. }
  528. dec, err := got.Decrypt(rand.Reader, enc, nil)
  529. if err != nil {
  530. t.Errorf("PKCS1v15.Decrypt() error = %v", err)
  531. } else if !bytes.Equal(dec, data) {
  532. t.Errorf("PKCS1v15.Decrypt() failed got = %s, want = %s", dec, data)
  533. }
  534. // RSA-OAEP
  535. enc, err = rsa.EncryptOAEP(crypto.SHA256.New(), rand.Reader, pub, data, []byte("label"))
  536. if err != nil {
  537. t.Errorf("rsa.EncryptOAEP() error = %v", err)
  538. return
  539. }
  540. dec, err = got.Decrypt(rand.Reader, enc, &rsa.OAEPOptions{
  541. Hash: crypto.SHA256,
  542. Label: []byte("label"),
  543. })
  544. if err != nil {
  545. t.Errorf("RSA-OAEP.Decrypt() error = %v", err)
  546. } else if !bytes.Equal(dec, data) {
  547. t.Errorf("RSA-OAEP.Decrypt() RSA-OAEP failed got = %s, want = %s", dec, data)
  548. }
  549. }
  550. })
  551. }
  552. }
  553. func TestPKCS11_LoadCertificate(t *testing.T) {
  554. k := setupPKCS11(t)
  555. getCertFn := func(i, j int) func() *x509.Certificate {
  556. return func() *x509.Certificate {
  557. return testCerts[i].Certificates[j]
  558. }
  559. }
  560. type args struct {
  561. req *apiv1.LoadCertificateRequest
  562. }
  563. tests := []struct {
  564. name string
  565. args args
  566. wantFn func() *x509.Certificate
  567. wantErr bool
  568. }{
  569. {"load", args{&apiv1.LoadCertificateRequest{
  570. Name: "pkcs11:id=7376;object=test-root",
  571. }}, getCertFn(0, 0), false},
  572. {"load by id", args{&apiv1.LoadCertificateRequest{
  573. Name: "pkcs11:id=7376",
  574. }}, getCertFn(0, 0), false},
  575. {"load by label", args{&apiv1.LoadCertificateRequest{
  576. Name: "pkcs11:object=test-root",
  577. }}, getCertFn(0, 0), false},
  578. {"load by serial", args{&apiv1.LoadCertificateRequest{
  579. Name: "pkcs11:serial=64",
  580. }}, getCertFn(0, 0), false},
  581. {"fail missing", args{&apiv1.LoadCertificateRequest{
  582. Name: "pkcs11:id=9999;object=test-root",
  583. }}, nil, true},
  584. {"fail name", args{&apiv1.LoadCertificateRequest{
  585. Name: "",
  586. }}, nil, true},
  587. {"fail scheme", args{&apiv1.LoadCertificateRequest{
  588. Name: "foo:id=7376;object=test-root",
  589. }}, nil, true},
  590. {"fail serial", args{&apiv1.LoadCertificateRequest{
  591. Name: "pkcs11:serial=foo",
  592. }}, nil, true},
  593. {"fail FindCertificate", args{&apiv1.LoadCertificateRequest{
  594. Name: "pkcs11:foo=bar",
  595. }}, nil, true},
  596. }
  597. for _, tt := range tests {
  598. t.Run(tt.name, func(t *testing.T) {
  599. got, err := k.LoadCertificate(tt.args.req)
  600. if (err != nil) != tt.wantErr {
  601. t.Errorf("PKCS11.LoadCertificate() error = %v, wantErr %v", err, tt.wantErr)
  602. return
  603. }
  604. var want *x509.Certificate
  605. if tt.wantFn != nil {
  606. want = tt.wantFn()
  607. got.Raw, got.RawIssuer, got.RawSubject, got.RawTBSCertificate, got.RawSubjectPublicKeyInfo = nil, nil, nil, nil, nil
  608. want.Raw, want.RawIssuer, want.RawSubject, want.RawTBSCertificate, want.RawSubjectPublicKeyInfo = nil, nil, nil, nil, nil
  609. }
  610. if !reflect.DeepEqual(got, want) {
  611. t.Errorf("PKCS11.LoadCertificate() = %v, want %v", got, want)
  612. }
  613. })
  614. }
  615. }
  616. func TestPKCS11_StoreCertificate(t *testing.T) {
  617. k := setupPKCS11(t)
  618. pub, priv, err := ed25519.GenerateKey(rand.Reader)
  619. if err != nil {
  620. t.Fatalf("ed25519.GenerateKey() error = %v", err)
  621. }
  622. cert, err := generateCertificate(pub, priv)
  623. if err != nil {
  624. t.Fatalf("x509.CreateCertificate() error = %v", err)
  625. }
  626. // Make sure to delete the created certificate
  627. t.Cleanup(func() {
  628. k.DeleteCertificate(testObject)
  629. k.DeleteCertificate(testObjectAlt)
  630. })
  631. type args struct {
  632. req *apiv1.StoreCertificateRequest
  633. }
  634. tests := []struct {
  635. name string
  636. args args
  637. wantErr bool
  638. }{
  639. {"ok", args{&apiv1.StoreCertificateRequest{
  640. Name: testObject,
  641. Certificate: cert,
  642. }}, false},
  643. {"ok extractable", args{&apiv1.StoreCertificateRequest{
  644. Name: testObjectAlt,
  645. Certificate: cert,
  646. Extractable: true,
  647. }}, false},
  648. {"fail already exists", args{&apiv1.StoreCertificateRequest{
  649. Name: testObject,
  650. Certificate: cert,
  651. }}, true},
  652. {"fail name", args{&apiv1.StoreCertificateRequest{
  653. Name: "",
  654. Certificate: cert,
  655. }}, true},
  656. {"fail certificate", args{&apiv1.StoreCertificateRequest{
  657. Name: testObject,
  658. Certificate: nil,
  659. }}, true},
  660. {"fail uri", args{&apiv1.StoreCertificateRequest{
  661. Name: "http:id=7770;object=create-cert",
  662. Certificate: cert,
  663. }}, true},
  664. {"fail missing id", args{&apiv1.StoreCertificateRequest{
  665. Name: "pkcs11:object=create-cert",
  666. Certificate: cert,
  667. }}, true},
  668. {"fail missing object", args{&apiv1.StoreCertificateRequest{
  669. Name: "pkcs11:id=7770;object=",
  670. Certificate: cert,
  671. }}, true},
  672. }
  673. for _, tt := range tests {
  674. t.Run(tt.name, func(t *testing.T) {
  675. if tt.args.req.Extractable {
  676. if testModule == "SoftHSM2" {
  677. t.Skip("Extractable certificates are not supported on SoftHSM2")
  678. }
  679. }
  680. if err := k.StoreCertificate(tt.args.req); (err != nil) != tt.wantErr {
  681. t.Errorf("PKCS11.StoreCertificate() error = %v, wantErr %v", err, tt.wantErr)
  682. }
  683. if !tt.wantErr {
  684. got, err := k.LoadCertificate(&apiv1.LoadCertificateRequest{
  685. Name: tt.args.req.Name,
  686. })
  687. if err != nil {
  688. t.Errorf("PKCS11.LoadCertificate() error = %v", err)
  689. }
  690. if !reflect.DeepEqual(got, cert) {
  691. t.Errorf("PKCS11.LoadCertificate() = %v, want %v", got, cert)
  692. }
  693. }
  694. })
  695. }
  696. }
  697. func TestPKCS11_DeleteKey(t *testing.T) {
  698. k := setupPKCS11(t)
  699. type args struct {
  700. uri string
  701. }
  702. tests := []struct {
  703. name string
  704. args args
  705. wantErr bool
  706. }{
  707. {"delete", args{testObject}, false},
  708. {"delete by id", args{testObjectByID}, false},
  709. {"delete by label", args{testObjectByLabel}, false},
  710. {"delete missing", args{"pkcs11:id=9999;object=missing-key"}, false},
  711. {"fail name", args{""}, true},
  712. {"fail FindKeyPair", args{"pkcs11:foo=bar"}, true},
  713. }
  714. for _, tt := range tests {
  715. t.Run(tt.name, func(t *testing.T) {
  716. if _, err := k.CreateKey(&apiv1.CreateKeyRequest{
  717. Name: testObject,
  718. }); err != nil {
  719. t.Fatalf("PKCS1.CreateKey() error = %v", err)
  720. }
  721. if err := k.DeleteKey(tt.args.uri); (err != nil) != tt.wantErr {
  722. t.Errorf("PKCS11.DeleteKey() error = %v, wantErr %v", err, tt.wantErr)
  723. }
  724. if _, err := k.GetPublicKey(&apiv1.GetPublicKeyRequest{
  725. Name: tt.args.uri,
  726. }); err == nil {
  727. t.Error("PKCS11.GetPublicKey() public key found and not expected")
  728. }
  729. // Make sure to delete the created one.
  730. if err := k.DeleteKey(testObject); err != nil {
  731. t.Errorf("PKCS11.DeleteKey() error = %v", err)
  732. }
  733. })
  734. }
  735. }
  736. func TestPKCS11_DeleteCertificate(t *testing.T) {
  737. k := setupPKCS11(t)
  738. pub, priv, err := ed25519.GenerateKey(rand.Reader)
  739. if err != nil {
  740. t.Fatalf("ed25519.GenerateKey() error = %v", err)
  741. }
  742. cert, err := generateCertificate(pub, priv)
  743. if err != nil {
  744. t.Fatalf("x509.CreateCertificate() error = %v", err)
  745. }
  746. type args struct {
  747. uri string
  748. }
  749. tests := []struct {
  750. name string
  751. args args
  752. wantErr bool
  753. }{
  754. {"delete", args{testObject}, false},
  755. {"delete by id", args{testObjectByID}, false},
  756. {"delete by label", args{testObjectByLabel}, false},
  757. {"delete missing", args{"pkcs11:id=9999;object=missing-key"}, false},
  758. {"fail name", args{""}, true},
  759. {"fail DeleteCertificate", args{"pkcs11:foo=bar"}, true},
  760. }
  761. for _, tt := range tests {
  762. t.Run(tt.name, func(t *testing.T) {
  763. if err := k.StoreCertificate(&apiv1.StoreCertificateRequest{
  764. Name: testObject,
  765. Certificate: cert,
  766. }); err != nil {
  767. t.Fatalf("PKCS11.StoreCertificate() error = %v", err)
  768. }
  769. if err := k.DeleteCertificate(tt.args.uri); (err != nil) != tt.wantErr {
  770. t.Errorf("PKCS11.DeleteCertificate() error = %v, wantErr %v", err, tt.wantErr)
  771. }
  772. if _, err := k.LoadCertificate(&apiv1.LoadCertificateRequest{
  773. Name: tt.args.uri,
  774. }); err == nil {
  775. t.Error("PKCS11.LoadCertificate() certificate found and not expected")
  776. }
  777. // Make sure to delete the created one.
  778. if err := k.DeleteCertificate(testObject); err != nil {
  779. t.Errorf("PKCS11.DeleteCertificate() error = %v", err)
  780. }
  781. })
  782. }
  783. }
  784. func TestPKCS11_Close(t *testing.T) {
  785. k := mustPKCS11(t)
  786. tests := []struct {
  787. name string
  788. wantErr bool
  789. }{
  790. {"ok", false},
  791. {"second", false},
  792. }
  793. for _, tt := range tests {
  794. t.Run(tt.name, func(t *testing.T) {
  795. if err := k.Close(); (err != nil) != tt.wantErr {
  796. t.Errorf("PKCS11.Close() error = %v, wantErr %v", err, tt.wantErr)
  797. }
  798. })
  799. }
  800. }