Debian Codegraph @

pkcs11/pkcs11.go

raw ◀ ▶
Source reconstructed at patch state 0 of 2 — not the installed (fully patched) source.
2 Debian patches touch this file
1 // Copyright 2021 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 // Package pkcs11 implements logic for using PKCS #11 shared libraries.
16 package pkcs11
17
18 /*
19 #include <dlfcn.h>
20 #include <stdlib.h>
21
22 #define CK_PTR *
23 #define CK_DECLARE_FUNCTION(returnType, name) \
24 returnType name
25 #define CK_DECLARE_FUNCTION_POINTER(returnType, name) \
26 returnType (* name)
27 #define CK_CALLBACK_FUNCTION(returnType, name) \
28 returnType (* name)
29 #ifndef NULL_PTR
30 #define NULL_PTR 0
31 #endif
32
33 #include "../third_party/pkcs11/pkcs11.h"
34
35 // Go can't call a C function pointer directly, so these are wrappers that
36 // perform the dereference in C.
37
38 CK_RV get_function_list(CK_C_GetFunctionList fn, CK_FUNCTION_LIST_PTR_PTR p) {
39 return (*fn)(p);
40 }
41
42 CK_RV ck_initialize(CK_FUNCTION_LIST_PTR fl, CK_C_INITIALIZE_ARGS_PTR args) {
43 return (*fl->C_Initialize)((CK_VOID_PTR)(args));
44 }
45
46 CK_RV ck_finalize(CK_FUNCTION_LIST_PTR fl) {
47 return (*fl->C_Finalize)(NULL_PTR);
48 }
49
50 CK_RV ck_init_token(
51 CK_FUNCTION_LIST_PTR fl,
52 CK_SLOT_ID slotID,
53 CK_UTF8CHAR_PTR pPin,
54 CK_ULONG ulPinLen,
55 CK_UTF8CHAR_PTR pLabel
56 ) {
57 if (ulPinLen == 0) {
58 // TODO(ericchiang): This isn't tested since softhsm requires a PIN.
59 pPin = NULL_PTR;
60 }
61 return (*fl->C_InitToken)(slotID, pPin, ulPinLen, pLabel);
62 }
63
64 CK_RV ck_get_slot_list(
65 CK_FUNCTION_LIST_PTR fl,
66 CK_SLOT_ID_PTR pSlotList,
67 CK_ULONG_PTR pulCount
68 ) {
69 return (*fl->C_GetSlotList)(CK_FALSE, pSlotList, pulCount);
70 }
71
72 CK_RV ck_get_info(
73 CK_FUNCTION_LIST_PTR fl,
74 CK_INFO_PTR pInfo
75 ) {
76 return (*fl->C_GetInfo)(pInfo);
77 }
78
79 CK_RV ck_get_slot_info(
80 CK_FUNCTION_LIST_PTR fl,
81 CK_SLOT_ID slotID,
82 CK_SLOT_INFO_PTR pInfo
83 ) {
84 return (*fl->C_GetSlotInfo)(slotID, pInfo);
85 }
86
87 CK_RV ck_get_token_info(
88 CK_FUNCTION_LIST_PTR fl,
89 CK_SLOT_ID slotID,
90 CK_TOKEN_INFO_PTR pInfo
91 ) {
92 return (*fl->C_GetTokenInfo)(slotID, pInfo);
93 }
94
95 CK_RV ck_open_session(
96 CK_FUNCTION_LIST_PTR fl,
97 CK_SLOT_ID slotID,
98 CK_FLAGS flags,
99 CK_SESSION_HANDLE_PTR phSession
100 ) {
101 return (*fl->C_OpenSession)(slotID, flags, NULL_PTR, NULL_PTR, phSession);
102 }
103
104 CK_RV ck_close_session(
105 CK_FUNCTION_LIST_PTR fl,
106 CK_SESSION_HANDLE hSession
107 ) {
108 return (*fl->C_CloseSession)(hSession);
109 }
110
111 CK_RV ck_login(
112 CK_FUNCTION_LIST_PTR fl,
113 CK_SESSION_HANDLE hSession,
114 CK_USER_TYPE userType,
115 CK_UTF8CHAR_PTR pPin,
116 CK_ULONG ulPinLen
117 ) {
118 return (*fl->C_Login)(hSession, userType, pPin, ulPinLen);
119 }
120
121 CK_RV ck_logout(
122 CK_FUNCTION_LIST_PTR fl,
123 CK_SESSION_HANDLE hSession
124 ) {
125 return (*fl->C_Logout)(hSession);
126 }
127
128 CK_RV ck_init_pin(
129 CK_FUNCTION_LIST_PTR fl,
130 CK_SESSION_HANDLE hSession,
131 CK_UTF8CHAR_PTR pPin,
132 CK_ULONG ulPinLen
133 ) {
134 return (*fl->C_InitPIN)(hSession, pPin, ulPinLen);
135 }
136
137 CK_RV ck_generate_key_pair(
138 CK_FUNCTION_LIST_PTR fl,
139 CK_SESSION_HANDLE hSession,
140 CK_MECHANISM_PTR pMechanism,
141 CK_ATTRIBUTE_PTR pPublicKeyTemplate,
142 CK_ULONG ulPublicKeyAttributeCount,
143 CK_ATTRIBUTE_PTR pPrivateKeyTemplate,
144 CK_ULONG ulPrivateKeyAttributeCount,
145 CK_OBJECT_HANDLE_PTR phPublicKey,
146 CK_OBJECT_HANDLE_PTR phPrivateKey
147 ) {
148 return (*fl->C_GenerateKeyPair)(
149 hSession,
150 pMechanism,
151 pPublicKeyTemplate,
152 ulPublicKeyAttributeCount,
153 pPrivateKeyTemplate,
154 ulPrivateKeyAttributeCount,
155 phPublicKey,
156 phPrivateKey
157 );
158 }
159
160 CK_RV ck_find_objects_init(
161 CK_FUNCTION_LIST_PTR fl,
162 CK_SESSION_HANDLE hSession,
163 CK_ATTRIBUTE_PTR pTemplate,
164 CK_ULONG ulCount
165 ) {
166 return (*fl->C_FindObjectsInit)(hSession, pTemplate, ulCount);
167 }
168
169 CK_RV ck_find_objects(
170 CK_FUNCTION_LIST_PTR fl,
171 CK_SESSION_HANDLE hSession,
172 CK_OBJECT_HANDLE_PTR phObject,
173 CK_ULONG ulMaxObjectCount,
174 CK_ULONG_PTR pulObjectCount
175 ) {
176 return (*fl->C_FindObjects)(hSession, phObject, ulMaxObjectCount, pulObjectCount);
177 }
178
179 CK_RV ck_find_objects_final(
180 CK_FUNCTION_LIST_PTR fl,
181 CK_SESSION_HANDLE hSession
182 ) {
183 return (*fl->C_FindObjectsFinal)(hSession);
184 }
185
186 CK_RV ck_create_object(
187 CK_FUNCTION_LIST_PTR fl,
188 CK_SESSION_HANDLE hSession,
189 CK_ATTRIBUTE_PTR pTemplate,
190 CK_ULONG ulCount,
191 CK_OBJECT_HANDLE_PTR phObject
192 ) {
193 return (*fl->C_CreateObject)(hSession, pTemplate, ulCount, phObject);
194 }
195
196 CK_RV ck_get_attribute_value(
197 CK_FUNCTION_LIST_PTR fl,
198 CK_SESSION_HANDLE hSession,
199 CK_OBJECT_HANDLE hObject,
200 CK_ATTRIBUTE_PTR pTemplate,
201 CK_ULONG ulCount
202 ) {
203 return (*fl->C_GetAttributeValue)(hSession, hObject, pTemplate, ulCount);
204 }
205
206 CK_RV ck_set_attribute_value(
207 CK_FUNCTION_LIST_PTR fl,
208 CK_SESSION_HANDLE hSession,
209 CK_OBJECT_HANDLE hObject,
210 CK_ATTRIBUTE_PTR pTemplate,
211 CK_ULONG ulCount
212 ) {
213 return (*fl->C_SetAttributeValue)(hSession, hObject, pTemplate, ulCount);
214 }
215
216 CK_RV ck_sign_init(
217 CK_FUNCTION_LIST_PTR fl,
218 CK_SESSION_HANDLE hSession,
219 CK_MECHANISM_PTR pMechanism,
220 CK_OBJECT_HANDLE hKey
221 ) {
222 return (*fl->C_SignInit)(hSession, pMechanism, hKey);
223 }
224
225 CK_RV ck_sign(
226 CK_FUNCTION_LIST_PTR fl,
227 CK_SESSION_HANDLE hSession,
228 CK_BYTE_PTR pData,
229 CK_ULONG ulDataLen,
230 CK_BYTE_PTR pSignature,
231 CK_ULONG_PTR pulSignatureLen
232 ) {
233 return (*fl->C_Sign)(hSession, pData, ulDataLen, pSignature, pulSignatureLen);
234 }
235
236 CK_RV ck_decrypt_init(
237 CK_FUNCTION_LIST_PTR fl,
238 CK_SESSION_HANDLE hSession,
239 CK_MECHANISM_PTR pMechanism,
240 CK_OBJECT_HANDLE hKey
241 ) {
242 return (*fl->C_DecryptInit)(hSession, pMechanism, hKey);
243 }
244
245 CK_RV ck_decrypt(
246 CK_FUNCTION_LIST_PTR fl,
247 CK_SESSION_HANDLE hSession,
248 CK_BYTE_PTR pEncryptedData,
249 CK_ULONG ulEncryptedDataLen,
250 CK_BYTE_PTR pData,
251 CK_ULONG_PTR pulDataLen
252 ) {
253 return (*fl->C_Decrypt)(hSession, pEncryptedData, ulEncryptedDataLen, pData, pulDataLen);
254 }
255 */
256 // #cgo linux LDFLAGS: -ldl
257 import "C"
258 import (
259 "bytes"
260 "crypto"
261 "crypto/ecdsa"
262 "crypto/elliptic"
263 "crypto/rsa"
264 "crypto/x509"
265 "encoding/asn1"
266 "fmt"
267 "io"
268 "math/big"
269 "strings"
270 "unsafe"
271 )
272
273 // ckStringPadded copies a string into b, padded with ' '. If the string is larger
274 // than the provided buffer, this function returns false.
275 func ckStringPadded(b []C.CK_UTF8CHAR, s string) bool {
276 if len(s) > len(b) {
277 return false
278 }
279 for i := range b {
280 if i < len(s) {
281 b[i] = C.CK_UTF8CHAR(s[i])
282 } else {
283 b[i] = C.CK_UTF8CHAR(' ')
284 }
285 }
286 return true
287 }
288
289 // ckString converts a Go string to a cryptokit string. The string is still held
290 // by Go memory and doesn't need to be freed.
291 func ckString(s string) []C.CK_UTF8CHAR {
292 b := make([]C.CK_UTF8CHAR, len(s))
293 for i, c := range []byte(s) {
294 b[i] = C.CK_UTF8CHAR(c)
295 }
296 return b
297 }
298
299 // ckCString converts a Go string to a cryptokit string held by C. This is required,
300 // for example, when building a CK_ATTRIBUTE, which needs to hold a pointer to a
301 // cryptokit string.
302 //
303 // This method also returns a function to free the allocated C memory.
304 func ckCString(s string) (cstring *C.CK_UTF8CHAR, free func()) {
305 b := (*C.CK_UTF8CHAR)(C.malloc(C.sizeof_CK_UTF8CHAR * C.ulong(len(s))))
306 bs := unsafe.Slice(b, len(s))
307 for i, c := range []byte(s) {
308 bs[i] = C.CK_UTF8CHAR(c)
309 }
310 return b, func() { C.free(unsafe.Pointer(b)) }
311 }
312
313 func ckGoString(s *C.CK_UTF8CHAR, n C.CK_ULONG) string {
314 var sb strings.Builder
315 sli := unsafe.Slice(s, n)
316 for _, b := range sli {
317 sb.WriteByte(byte(b))
318 }
319 return sb.String()
320 }
321
322 // Error is returned for cryptokit specific API codes.
323 type Error struct {
324 fnName string
325 code C.CK_RV
326 }
327
328 func (e *Error) Error() string {
329 code, ok := ckRVString[e.code]
330 if !ok {
331 code = fmt.Sprintf("0x%x", e.code)
332 }
333 return fmt.Sprintf("pkcs11: %s() %s", e.fnName, code)
334 }
335
336 var ckRVString = map[C.CK_RV]string{
337 C.CKR_CANCEL: "CKR_CANCEL",
338 C.CKR_HOST_MEMORY: "CKR_HOST_MEMORY",
339 C.CKR_SLOT_ID_INVALID: "CKR_SLOT_ID_INVALID",
340 C.CKR_GENERAL_ERROR: "CKR_GENERAL_ERROR",
341 C.CKR_FUNCTION_FAILED: "CKR_FUNCTION_FAILED",
342 C.CKR_ARGUMENTS_BAD: "CKR_ARGUMENTS_BAD",
343 C.CKR_NO_EVENT: "CKR_NO_EVENT",
344 C.CKR_NEED_TO_CREATE_THREADS: "CKR_NEED_TO_CREATE_THREADS",
345 C.CKR_CANT_LOCK: "CKR_CANT_LOCK",
346 C.CKR_ATTRIBUTE_READ_ONLY: "CKR_ATTRIBUTE_READ_ONLY",
347 C.CKR_ATTRIBUTE_SENSITIVE: "CKR_ATTRIBUTE_SENSITIVE",
348 C.CKR_ATTRIBUTE_TYPE_INVALID: "CKR_ATTRIBUTE_TYPE_INVALID",
349 C.CKR_ATTRIBUTE_VALUE_INVALID: "CKR_ATTRIBUTE_VALUE_INVALID",
350 C.CKR_ACTION_PROHIBITED: "CKR_ACTION_PROHIBITED",
351 C.CKR_DATA_INVALID: "CKR_DATA_INVALID",
352 C.CKR_DATA_LEN_RANGE: "CKR_DATA_LEN_RANGE",
353 C.CKR_DEVICE_ERROR: "CKR_DEVICE_ERROR",
354 C.CKR_DEVICE_MEMORY: "CKR_DEVICE_MEMORY",
355 C.CKR_DEVICE_REMOVED: "CKR_DEVICE_REMOVED",
356 C.CKR_ENCRYPTED_DATA_INVALID: "CKR_ENCRYPTED_DATA_INVALID",
357 C.CKR_ENCRYPTED_DATA_LEN_RANGE: "CKR_ENCRYPTED_DATA_LEN_RANGE",
358 C.CKR_FUNCTION_CANCELED: "CKR_FUNCTION_CANCELED",
359 C.CKR_FUNCTION_NOT_PARALLEL: "CKR_FUNCTION_NOT_PARALLEL",
360 C.CKR_FUNCTION_NOT_SUPPORTED: "CKR_FUNCTION_NOT_SUPPORTED",
361 C.CKR_KEY_HANDLE_INVALID: "CKR_KEY_HANDLE_INVALID",
362 C.CKR_KEY_SIZE_RANGE: "CKR_KEY_SIZE_RANGE",
363 C.CKR_KEY_TYPE_INCONSISTENT: "CKR_KEY_TYPE_INCONSISTENT",
364 C.CKR_KEY_NOT_NEEDED: "CKR_KEY_NOT_NEEDED",
365 C.CKR_KEY_CHANGED: "CKR_KEY_CHANGED",
366 C.CKR_KEY_NEEDED: "CKR_KEY_NEEDED",
367 C.CKR_KEY_INDIGESTIBLE: "CKR_KEY_INDIGESTIBLE",
368 C.CKR_KEY_FUNCTION_NOT_PERMITTED: "CKR_KEY_FUNCTION_NOT_PERMITTED",
369 C.CKR_KEY_NOT_WRAPPABLE: "CKR_KEY_NOT_WRAPPABLE",
370 C.CKR_KEY_UNEXTRACTABLE: "CKR_KEY_UNEXTRACTABLE",
371 C.CKR_MECHANISM_INVALID: "CKR_MECHANISM_INVALID",
372 C.CKR_MECHANISM_PARAM_INVALID: "CKR_MECHANISM_PARAM_INVALID",
373 C.CKR_OBJECT_HANDLE_INVALID: "CKR_OBJECT_HANDLE_INVALID",
374 C.CKR_OPERATION_ACTIVE: "CKR_OPERATION_ACTIVE",
375 C.CKR_OPERATION_NOT_INITIALIZED: "CKR_OPERATION_NOT_INITIALIZED",
376 C.CKR_PIN_INCORRECT: "CKR_PIN_INCORRECT",
377 C.CKR_PIN_INVALID: "CKR_PIN_INVALID",
378 C.CKR_PIN_LEN_RANGE: "CKR_PIN_LEN_RANGE",
379 C.CKR_PIN_EXPIRED: "CKR_PIN_EXPIRED",
380 C.CKR_PIN_LOCKED: "CKR_PIN_LOCKED",
381 C.CKR_SESSION_CLOSED: "CKR_SESSION_CLOSED",
382 C.CKR_SESSION_COUNT: "CKR_SESSION_COUNT",
383 C.CKR_SESSION_HANDLE_INVALID: "CKR_SESSION_HANDLE_INVALID",
384 C.CKR_SESSION_PARALLEL_NOT_SUPPORTED: "CKR_SESSION_PARALLEL_NOT_SUPPORTED",
385 C.CKR_SESSION_READ_ONLY: "CKR_SESSION_READ_ONLY",
386 C.CKR_SESSION_EXISTS: "CKR_SESSION_EXISTS",
387 C.CKR_SESSION_READ_ONLY_EXISTS: "CKR_SESSION_READ_ONLY_EXISTS",
388 C.CKR_SESSION_READ_WRITE_SO_EXISTS: "CKR_SESSION_READ_WRITE_SO_EXISTS",
389 C.CKR_SIGNATURE_INVALID: "CKR_SIGNATURE_INVALID",
390 C.CKR_SIGNATURE_LEN_RANGE: "CKR_SIGNATURE_LEN_RANGE",
391 C.CKR_TEMPLATE_INCOMPLETE: "CKR_TEMPLATE_INCOMPLETE",
392 C.CKR_TEMPLATE_INCONSISTENT: "CKR_TEMPLATE_INCONSISTENT",
393 C.CKR_TOKEN_NOT_PRESENT: "CKR_TOKEN_NOT_PRESENT",
394 C.CKR_TOKEN_NOT_RECOGNIZED: "CKR_TOKEN_NOT_RECOGNIZED",
395 C.CKR_TOKEN_WRITE_PROTECTED: "CKR_TOKEN_WRITE_PROTECTED",
396 C.CKR_UNWRAPPING_KEY_HANDLE_INVALID: "CKR_UNWRAPPING_KEY_HANDLE_INVALID",
397 C.CKR_UNWRAPPING_KEY_SIZE_RANGE: "CKR_UNWRAPPING_KEY_SIZE_RANGE",
398 C.CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT: "CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT",
399 C.CKR_USER_ALREADY_LOGGED_IN: "CKR_USER_ALREADY_LOGGED_IN",
400 C.CKR_USER_NOT_LOGGED_IN: "CKR_USER_NOT_LOGGED_IN",
401 C.CKR_USER_PIN_NOT_INITIALIZED: "CKR_USER_PIN_NOT_INITIALIZED",
402 C.CKR_USER_TYPE_INVALID: "CKR_USER_TYPE_INVALID",
403 C.CKR_USER_ANOTHER_ALREADY_LOGGED_IN: "CKR_USER_ANOTHER_ALREADY_LOGGED_IN",
404 C.CKR_USER_TOO_MANY_TYPES: "CKR_USER_TOO_MANY_TYPES",
405 C.CKR_WRAPPED_KEY_INVALID: "CKR_WRAPPED_KEY_INVALID",
406 C.CKR_WRAPPED_KEY_LEN_RANGE: "CKR_WRAPPED_KEY_LEN_RANGE",
407 C.CKR_WRAPPING_KEY_HANDLE_INVALID: "CKR_WRAPPING_KEY_HANDLE_INVALID",
408 C.CKR_WRAPPING_KEY_SIZE_RANGE: "CKR_WRAPPING_KEY_SIZE_RANGE",
409 C.CKR_WRAPPING_KEY_TYPE_INCONSISTENT: "CKR_WRAPPING_KEY_TYPE_INCONSISTENT",
410 C.CKR_RANDOM_SEED_NOT_SUPPORTED: "CKR_RANDOM_SEED_NOT_SUPPORTED",
411 C.CKR_RANDOM_NO_RNG: "CKR_RANDOM_NO_RNG",
412 C.CKR_DOMAIN_PARAMS_INVALID: "CKR_DOMAIN_PARAMS_INVALID",
413 C.CKR_CURVE_NOT_SUPPORTED: "CKR_CURVE_NOT_SUPPORTED",
414 C.CKR_BUFFER_TOO_SMALL: "CKR_BUFFER_TOO_SMALL",
415 C.CKR_SAVED_STATE_INVALID: "CKR_SAVED_STATE_INVALID",
416 C.CKR_INFORMATION_SENSITIVE: "CKR_INFORMATION_SENSITIVE",
417 C.CKR_STATE_UNSAVEABLE: "CKR_STATE_UNSAVEABLE",
418 C.CKR_CRYPTOKI_NOT_INITIALIZED: "CKR_CRYPTOKI_NOT_INITIALIZED",
419 C.CKR_CRYPTOKI_ALREADY_INITIALIZED: "CKR_CRYPTOKI_ALREADY_INITIALIZED",
420 C.CKR_MUTEX_BAD: "CKR_MUTEX_BAD",
421 C.CKR_MUTEX_NOT_LOCKED: "CKR_MUTEX_NOT_LOCKED",
422 C.CKR_FUNCTION_REJECTED: "CKR_FUNCTION_REJECTED",
423 C.CKR_VENDOR_DEFINED: "CKR_VENDOR_DEFINED",
424 }
425
426 func isOk(fnName string, rv C.CK_RV) error {
427 if rv == C.CKR_OK {
428 return nil
429 }
430 return &Error{fnName, rv}
431 }
432
433 // Module represents an opened shared library. By default, this package
434 // requests locking support from the module, but concurrent safety may
435 // depend on the underlying library.
436 type Module struct {
437 // mod is a pointer to the dlopen handle. Kept around to dlfree
438 // when the Module is closed.
439 mod unsafe.Pointer
440 // List of C functions provided by the module.
441 fl C.CK_FUNCTION_LIST_PTR
442 // Version of the module, used for compatibility.
443 version C.CK_VERSION
444
445 info Info
446 }
447
448 // Open dlopens a shared library by path, initializing the module.
449 func Open(path string) (*Module, error) {
450 cPath := C.CString(path)
451 defer C.free(unsafe.Pointer(cPath))
452
453 mod := C.dlopen(cPath, C.RTLD_NOW)
454 if mod == nil {
455 return nil, fmt.Errorf("pkcs11: dlopen error: %s", C.GoString(C.dlerror()))
456 }
457
458 cSym := C.CString("C_GetFunctionList")
459 defer C.free(unsafe.Pointer(cSym))
460
461 getFuncListFn := (C.CK_C_GetFunctionList)(C.dlsym(mod, cSym))
462 if getFuncListFn == nil {
463 err := fmt.Errorf("pkcs11: lookup function list symbol: %s", C.GoString(C.dlerror()))
464 C.dlclose(mod)
465 return nil, err
466 }
467
468 var p C.CK_FUNCTION_LIST_PTR
469 rv := C.get_function_list(getFuncListFn, &p)
470 if err := isOk("C_GetFunctionList", rv); err != nil {
471 C.dlclose(mod)
472 return nil, err
473 }
474
475 args := C.CK_C_INITIALIZE_ARGS{
476 flags: C.CKF_OS_LOCKING_OK,
477 }
478 if err := isOk("C_Initialize", C.ck_initialize(p, &args)); err != nil {
479 C.dlclose(mod)
480 return nil, err
481 }
482
483 var info C.CK_INFO
484 if err := isOk("C_GetInfo", C.ck_get_info(p, &info)); err != nil {
485 C.dlclose(mod)
486 return nil, err
487 }
488
489 return &Module{
490 mod: mod,
491 fl: p,
492 version: info.cryptokiVersion,
493 info: Info{
494 Manufacturer: toString(info.manufacturerID[:]),
495 Version: Version{
496 Major: uint8(info.libraryVersion.major),
497 Minor: uint8(info.libraryVersion.minor),
498 },
499 },
500 }, nil
501 }
502
503 // Close finalizes the module and releases any resources associated with the
504 // shared library.
505 func (m *Module) Close() error {
506 if err := isOk("C_Finalize", C.ck_finalize(m.fl)); err != nil {
507 return err
508 }
509 if C.dlclose(m.mod) != 0 {
510 return fmt.Errorf("pkcs11: dlclose error: %s", C.GoString(C.dlerror()))
511 }
512 return nil
513 }
514
515 // createSlot configures a slot object. Internally this calls C_InitToken and
516 // C_InitPIN to set the admin and user PIN on the slot.
517 func (m *Module) createSlot(id uint32, opts slotOptions) error {
518 if opts.Label == "" {
519 return fmt.Errorf("no label provided")
520 }
521 if opts.PIN == "" {
522 return fmt.Errorf("no user pin provided")
523 }
524 if opts.AdminPIN == "" {
525 return fmt.Errorf("no admin pin provided")
526 }
527
528 var cLabel [32]C.CK_UTF8CHAR
529 if !ckStringPadded(cLabel[:], opts.Label) {
530 return fmt.Errorf("pkcs11: label too long")
531 }
532
533 cPIN := ckString(opts.AdminPIN)
534 cPINLen := C.CK_ULONG(len(cPIN))
535
536 rv := C.ck_init_token(
537 m.fl,
538 C.CK_SLOT_ID(id),
539 &cPIN[0],
540 cPINLen,
541 &cLabel[0],
542 )
543 if err := isOk("C_InitToken", rv); err != nil {
544 return err
545 }
546
547 so := Options{
548 AdminPIN: opts.AdminPIN,
549 ReadWrite: true,
550 }
551 s, err := m.Slot(id, so)
552 if err != nil {
553 return fmt.Errorf("getting slot: %w", err)
554 }
555 defer s.Close()
556 if err := s.initPIN(opts.PIN); err != nil {
557 return fmt.Errorf("configuring user pin: %w", err)
558 }
559 if err := s.logout(); err != nil {
560 return fmt.Errorf("logout: %v", err)
561 }
562 return nil
563 }
564
565 // SlotIDs returns the IDs of all slots associated with this module, including
566 // ones that haven't been initialized.
567 func (m *Module) SlotIDs() ([]uint32, error) {
568 var n C.CK_ULONG
569 rv := C.ck_get_slot_list(m.fl, nil, &n)
570 if err := isOk("C_GetSlotList", rv); err != nil {
571 return nil, err
572 }
573
574 l := make([]C.CK_SLOT_ID, int(n))
575 rv = C.ck_get_slot_list(m.fl, &l[0], &n)
576 if err := isOk("C_GetSlotList", rv); err != nil {
577 return nil, err
578 }
579 if int(n) > len(l) {
580 return nil, fmt.Errorf("pkcs11: C_GetSlotList returned too many elements, got %d, want %d", int(n), len(l))
581 }
582 l = l[:int(n)]
583
584 ids := make([]uint32, len(l))
585 for i, id := range l {
586 ids[i] = uint32(id)
587 }
588 return ids, nil
589 }
590
591 // Version holds a major and minor version.
592 type Version struct {
593 Major uint8
594 Minor uint8
595 }
596
597 // Info holds global information about the module.
598 type Info struct {
599 // Manufacturer of the implementation. When multiple PKCS #11 devices are
600 // present this is used to differentiate devices.
601 Manufacturer string
602 // Version of the module.
603 Version Version
604 // Human readable description of the module.
605 Description string
606 }
607
608 // SlotInfo holds information about the slot and underlying token.
609 type SlotInfo struct {
610 Label string
611 Model string
612 Serial string
613
614 Description string
615 }
616
617 func toString(b []C.uchar) string {
618 lastIndex := len(b)
619 for i := len(b); i > 0; i-- {
620 if b[i-1] != C.uchar(' ') {
621 break
622 }
623 lastIndex = i - 1
624 }
625
626 var sb strings.Builder
627 for _, c := range b[:lastIndex] {
628 sb.WriteByte(byte(c))
629 }
630 return sb.String()
631 }
632
633 // Info returns additional information about the module.
634 func (m *Module) Info() Info {
635 return m.info
636 }
637
638 // SlotInfo queries for information about the slot, such as the label.
639 func (m *Module) SlotInfo(id uint32) (*SlotInfo, error) {
640 var (
641 cSlotInfo C.CK_SLOT_INFO
642 cTokenInfo C.CK_TOKEN_INFO
643 slotID = C.CK_SLOT_ID(id)
644 )
645 rv := C.ck_get_slot_info(m.fl, slotID, &cSlotInfo)
646 if err := isOk("C_GetSlotInfo", rv); err != nil {
647 return nil, err
648 }
649 info := SlotInfo{
650 Description: toString(cSlotInfo.slotDescription[:]),
651 }
652 if (cSlotInfo.flags & C.CKF_TOKEN_PRESENT) == 0 {
653 return &info, nil
654 }
655
656 rv = C.ck_get_token_info(m.fl, slotID, &cTokenInfo)
657 if err := isOk("C_GetTokenInfo", rv); err != nil {
658 return nil, err
659 }
660 info.Label = toString(cTokenInfo.label[:])
661 info.Model = toString(cTokenInfo.model[:])
662 info.Serial = toString(cTokenInfo.serialNumber[:])
663 return &info, nil
664 }
665
666 // Slot represents a session to a slot.
667 //
668 // A slot holds a listable set of objects, such as certificates and
669 // cryptographic keys.
670 type Slot struct {
671 fl C.CK_FUNCTION_LIST_PTR
672 h C.CK_SESSION_HANDLE
673 }
674
675 type slotOptions struct {
676 AdminPIN string
677 PIN string
678 Label string
679 }
680
681 // Options holds configuration options for the slot session.
682 type Options struct {
683 PIN string
684 AdminPIN string
685 // ReadWrite indicates that the slot should be opened with write capabilities,
686 // such as generating keys or importing certificates.
687 //
688 // By default, sessions can access objects and perform signing requests.
689 ReadWrite bool
690 }
691
692 // Slot creates a session with the given slot, by default read-only. Users
693 // must call Close to release the session.
694 //
695 // The returned Slot's behavior is undefined once the Module is closed.
696 func (m *Module) Slot(id uint32, opts Options) (*Slot, error) {
697 if opts.AdminPIN != "" && opts.PIN != "" {
698 return nil, fmt.Errorf("can't specify pin and admin pin")
699 }
700
701 var (
702 h C.CK_SESSION_HANDLE
703 slotID = C.CK_SLOT_ID(id)
704 // "For legacy reasons, the CKF_SERIAL_SESSION bit MUST always be set".
705 //
706 // http://docs.oasis-open.org/pkcs11/pkcs11-base/v2.40/os/pkcs11-base-v2.40-os.html#_Toc416959742
707 flags C.CK_FLAGS = C.CKF_SERIAL_SESSION
708 )
709
710 if opts.ReadWrite {
711 flags = flags | C.CKF_RW_SESSION
712 }
713
714 rv := C.ck_open_session(m.fl, slotID, flags, &h)
715 if err := isOk("C_OpenSession", rv); err != nil {
716 return nil, err
717 }
718
719 s := &Slot{fl: m.fl, h: h}
720
721 if opts.PIN != "" {
722 if err := s.login(opts.PIN); err != nil {
723 s.Close()
724 return nil, err
725 }
726 }
727 if opts.AdminPIN != "" {
728 if err := s.loginAdmin(opts.AdminPIN); err != nil {
729 s.Close()
730 return nil, err
731 }
732 }
733
734 return s, nil
735 }
736
737 // Close releases the slot session.
738 func (s *Slot) Close() error {
739 return isOk("C_CloseSession", C.ck_close_session(s.fl, s.h))
740 }
741
742 // TODO(ericchiang): merge with SlotInitialize.
743 func (s *Slot) initPIN(pin string) error {
744 if pin == "" {
745 return fmt.Errorf("invalid pin")
746 }
747 cPIN := ckString(pin)
748 cPINLen := C.CK_ULONG(len(cPIN))
749 return isOk("C_InitPIN", C.ck_init_pin(s.fl, s.h, &cPIN[0], cPINLen))
750 }
751
752 func (s *Slot) logout() error {
753 return isOk("C_Logout", C.ck_logout(s.fl, s.h))
754 }
755
756 func (s *Slot) login(pin string) error {
757 // TODO(ericchiang): check for CKR_USER_ALREADY_LOGGED_IN and auto logout.
758 if pin == "" {
759 return fmt.Errorf("invalid pin")
760 }
761 cPIN := ckString(pin)
762 cPINLen := C.CK_ULONG(len(cPIN))
763 return isOk("C_Login", C.ck_login(s.fl, s.h, C.CKU_USER, &cPIN[0], cPINLen))
764 }
765
766 func (s *Slot) loginAdmin(adminPIN string) error {
767 // TODO(ericchiang): maybe run commands, detect CKR_USER_NOT_LOGGED_IN, then
768 // automatically login?
769 if adminPIN == "" {
770 return fmt.Errorf("invalid admin pin")
771 }
772 cPIN := ckString(adminPIN)
773 cPINLen := C.CK_ULONG(len(cPIN))
774 return isOk("C_Login", C.ck_login(s.fl, s.h, C.CKU_SO, &cPIN[0], cPINLen))
775 }
776
777 // Class is the primary object type. Such as a certificate, public key, or
778 // private key.
779 type Class int
780
781 // Set of classes supported by this package.
782 const (
783 ClassData Class = 0x00000000
784 ClassCertificate Class = 0x00000001
785 ClassPublicKey Class = 0x00000002
786 ClassPrivateKey Class = 0x00000003
787 ClassSecretKey Class = 0x00000004
788 ClassDomainParameters Class = 0x00000006
789 )
790
791 var classString = map[Class]string{
792 ClassData: "CKO_DATA",
793 ClassCertificate: "CKO_CERTIFICATE",
794 ClassPublicKey: "CKO_PUBLIC_KEY",
795 ClassPrivateKey: "CKO_PRIVATE_KEY",
796 ClassSecretKey: "CKO_SECRET_KEY",
797 ClassDomainParameters: "CKO_DOMAIN_PARAMETERS",
798 }
799
800 // String returns a human readable version of the object class.
801 func (c Class) String() string {
802 if s, ok := classString[c]; ok {
803 return s
804 }
805 return fmt.Sprintf("Class(0x%08x)", int(c))
806 }
807
808 func (c Class) ckType() (C.CK_OBJECT_CLASS, bool) {
809 switch c {
810 case ClassData:
811 return C.CKO_DATA, true
812 case ClassCertificate:
813 return C.CKO_CERTIFICATE, true
814 case ClassPublicKey:
815 return C.CKO_PUBLIC_KEY, true
816 case ClassPrivateKey:
817 return C.CKO_PRIVATE_KEY, true
818 case ClassSecretKey:
819 return C.CKO_SECRET_KEY, true
820 case ClassDomainParameters:
821 return C.CKO_DOMAIN_PARAMETERS, true
822 }
823 return 0, false
824 }
825
826 func (s *Slot) newObject(o C.CK_OBJECT_HANDLE) (Object, error) {
827 objClass := C.CK_OBJECT_CLASS_PTR(C.malloc(C.sizeof_CK_OBJECT_CLASS))
828 defer C.free(unsafe.Pointer(objClass))
829
830 a := []C.CK_ATTRIBUTE{
831 {C.CKA_CLASS, C.CK_VOID_PTR(objClass), C.CK_ULONG(C.sizeof_CK_OBJECT_CLASS)},
832 }
833 rv := C.ck_get_attribute_value(s.fl, s.h, o, &a[0], C.CK_ULONG(len(a)))
834 if err := isOk("C_GetAttributeValue", rv); err != nil {
835 return Object{}, err
836 }
837 return Object{s.fl, s.h, o, *objClass}, nil
838 }
839
840 type createOptions struct {
841 Label string
842
843 X509Certificate *x509.Certificate
844 }
845
846 func (s *Slot) create(opts createOptions) (*Object, error) {
847 if opts.X509Certificate != nil {
848 return s.createX509Certificate(opts)
849 }
850 return nil, fmt.Errorf("no objects provided to import")
851 }
852
853 // http://docs.oasis-open.org/pkcs11/pkcs11-base/v2.40/os/pkcs11-base-v2.40-os.html#_Toc416959709
854 func (s *Slot) createX509Certificate(opts createOptions) (*Object, error) {
855 if opts.X509Certificate == nil {
856 return nil, fmt.Errorf("no certificate provided")
857 }
858 objClass := (*C.CK_OBJECT_CLASS)(C.malloc(C.sizeof_CK_OBJECT_CLASS))
859 defer C.free(unsafe.Pointer(objClass))
860 *objClass = C.CKO_CERTIFICATE
861
862 ct := (*C.CK_CERTIFICATE_TYPE)(C.malloc(C.sizeof_CK_CERTIFICATE_TYPE))
863 defer C.free(unsafe.Pointer(ct))
864 *ct = C.CKC_X_509
865
866 cSubj := C.CBytes(opts.X509Certificate.RawSubject)
867 defer C.free(cSubj)
868
869 cValue := C.CBytes(opts.X509Certificate.Raw)
870 defer C.free(cValue)
871
872 attrs := []C.CK_ATTRIBUTE{
873 {C.CKA_CLASS, C.CK_VOID_PTR(objClass), C.CK_ULONG(C.sizeof_CK_OBJECT_CLASS)},
874 {C.CKA_CERTIFICATE_TYPE, C.CK_VOID_PTR(ct), C.CK_ULONG(C.sizeof_CK_CERTIFICATE_TYPE)},
875 {C.CKA_SUBJECT, C.CK_VOID_PTR(cSubj), C.CK_ULONG(len(opts.X509Certificate.RawSubject))},
876 {C.CKA_VALUE, C.CK_VOID_PTR(cValue), C.CK_ULONG(len(opts.X509Certificate.Raw))},
877 }
878
879 if opts.Label != "" {
880 cs, free := ckCString(opts.Label)
881 defer free()
882
883 attrs = append(attrs, C.CK_ATTRIBUTE{
884 C.CKA_LABEL,
885 C.CK_VOID_PTR(cs),
886 C.CK_ULONG(len(opts.Label)),
887 })
888 }
889
890 var h C.CK_OBJECT_HANDLE
891 rv := C.ck_create_object(s.fl, s.h, &attrs[0], C.CK_ULONG(len(attrs)), &h)
892 if err := isOk("C_CreateObject", rv); err != nil {
893 return nil, err
894 }
895 obj, err := s.newObject(h)
896 if err != nil {
897 return nil, err
898 }
899 return &obj, nil
900 }
901
902 // Filter hold options for returning a subset of objects from a slot.
903 //
904 // The returned object will match all provided parameters. For example, if
905 // Class=ClassPrivateKey and Label="foo", the returned object must be a
906 // private key with label "foo".
907 type Filter struct {
908 Class Class
909 Label string
910 }
911
912 // Objects searches a slot for objects that match the given options, or all
913 // objects if no options are provided.
914 //
915 // The returned objects behavior is undefined once the Slot object is closed.
916 func (s *Slot) Objects(opts Filter) (objs []Object, err error) {
917 var attrs []C.CK_ATTRIBUTE
918 if opts.Label != "" {
919 cs, free := ckCString(opts.Label)
920 defer free()
921
922 attrs = append(attrs, C.CK_ATTRIBUTE{
923 C.CKA_LABEL,
924 C.CK_VOID_PTR(cs),
925 C.CK_ULONG(len(opts.Label)),
926 })
927 }
928
929 if opts.Class != 0 {
930 c, ok := Class(opts.Class).ckType()
931 if ok {
932 objClass := C.CK_OBJECT_CLASS_PTR(C.malloc(C.sizeof_CK_OBJECT_CLASS))
933 defer C.free(unsafe.Pointer(objClass))
934
935 *objClass = c
936 attrs = append(attrs, C.CK_ATTRIBUTE{
937 C.CKA_CLASS,
938 C.CK_VOID_PTR(objClass),
939 C.CK_ULONG(C.sizeof_CK_OBJECT_CLASS),
940 })
941 }
942 }
943
944 var rv C.CK_RV
945 if len(attrs) > 0 {
946 rv = C.ck_find_objects_init(s.fl, s.h, &attrs[0], C.CK_ULONG(len(attrs)))
947 } else {
948 rv = C.ck_find_objects_init(s.fl, s.h, nil, 0)
949 }
950 if err := isOk("C_FindObjectsInit", rv); err != nil {
951 return nil, err
952 }
953 defer func() {
954 rv := C.ck_find_objects_final(s.fl, s.h)
955 if ferr := isOk("C_FindObjectsFinal", rv); ferr != nil && err == nil {
956 err = ferr
957 }
958 }()
959
960 var handles []C.CK_OBJECT_HANDLE
961 const objectsAtATime = 16
962 for {
963 cObjHandles := make([]C.CK_OBJECT_HANDLE, objectsAtATime)
964 cObjMax := C.CK_ULONG(objectsAtATime)
965 var n C.CK_ULONG
966
967 rv := C.ck_find_objects(s.fl, s.h, &cObjHandles[0], cObjMax, &n)
968 if err := isOk("C_FindObjects", rv); err != nil {
969 return nil, err
970 }
971 if n == 0 {
972 break
973 }
974
975 handles = append(handles, cObjHandles[:int(n)]...)
976 }
977
978 for _, h := range handles {
979 o, err := s.newObject(h)
980 if err != nil {
981 return nil, err
982 }
983 objs = append(objs, o)
984 }
985 return objs, nil
986 }
987
988 // Object represents a single object stored within a slot. For example a key or
989 // certificate.
990 type Object struct {
991 fl C.CK_FUNCTION_LIST_PTR
992 h C.CK_SESSION_HANDLE
993 o C.CK_OBJECT_HANDLE
994 c C.CK_OBJECT_CLASS
995 }
996
997 // Class returns the type of the object stored. For example, certificate, public
998 // key, or private key.
999 func (o Object) Class() Class {
1000 return Class(int(o.c))
1001 }
1002
1003 func (o Object) getAttribute(attrs []C.CK_ATTRIBUTE) error {
1004 return isOk("C_GetAttributeValue",
1005 C.ck_get_attribute_value(o.fl, o.h, o.o, &attrs[0], C.CK_ULONG(len(attrs))),
1006 )
1007 }
1008
1009 func (o Object) setAttribute(attrs []C.CK_ATTRIBUTE) error {
1010 return isOk("C_SetAttributeValue",
1011 C.ck_set_attribute_value(o.fl, o.h, o.o, &attrs[0], C.CK_ULONG(len(attrs))),
1012 )
1013 }
1014
1015 // Label returns a string value attached to an object, which can be used to
1016 // identify or group sets of keys and certificates.
1017 func (o Object) Label() (string, error) {
1018 attrs := []C.CK_ATTRIBUTE{{C.CKA_LABEL, nil, 0}}
1019 if err := o.getAttribute(attrs); err != nil {
1020 return "", err
1021 }
1022 n := attrs[0].ulValueLen
1023
1024 cLabel := (*C.CK_UTF8CHAR)(C.malloc(C.ulong(n)))
1025 defer C.free(unsafe.Pointer(cLabel))
1026 attrs[0].pValue = C.CK_VOID_PTR(cLabel)
1027
1028 if err := o.getAttribute(attrs); err != nil {
1029 return "", err
1030 }
1031 return ckGoString(cLabel, n), nil
1032 }
1033
1034 // setLabel sets the label of the object overwriting any previous value.
1035 func (o Object) setLabel(s string) error {
1036 cs, free := ckCString(s)
1037 defer free()
1038
1039 attrs := []C.CK_ATTRIBUTE{{C.CKA_LABEL, C.CK_VOID_PTR(cs), C.CK_ULONG(len(s))}}
1040 return o.setAttribute(attrs)
1041 }
1042
1043 // Certificate parses the underlying object as a certificate. If the object
1044 // isn't a certificate, this method fails.
1045 func (o Object) Certificate() (*Certificate, error) {
1046 if o.Class() != ClassCertificate {
1047 return nil, fmt.Errorf("object has class: %s", o.Class())
1048 }
1049 ct := (*C.CK_CERTIFICATE_TYPE)(C.malloc(C.sizeof_CK_CERTIFICATE_TYPE))
1050 defer C.free(unsafe.Pointer(ct))
1051
1052 attrs := []C.CK_ATTRIBUTE{
1053 {C.CKA_CERTIFICATE_TYPE, C.CK_VOID_PTR(ct), C.CK_ULONG(C.sizeof_CK_CERTIFICATE_TYPE)},
1054 }
1055 if err := o.getAttribute(attrs); err != nil {
1056 return nil, fmt.Errorf("getting certificate type: %w", err)
1057 }
1058 return &Certificate{o, *ct}, nil
1059 }
1060
1061 // PublicKey parses the underlying object as a public key. Both RSA and ECDSA
1062 // keys are supported.
1063 //
1064 // If the object isn't a public key, this method fails.
1065 func (o Object) PublicKey() (crypto.PublicKey, error) {
1066 if o.Class() != ClassPublicKey {
1067 return nil, fmt.Errorf("object has class: %s", o.Class())
1068 }
1069
1070 kt := (*C.CK_KEY_TYPE)(C.malloc(C.sizeof_CK_KEY_TYPE))
1071 defer C.free(unsafe.Pointer(kt))
1072
1073 attrs := []C.CK_ATTRIBUTE{
1074 {C.CKA_KEY_TYPE, C.CK_VOID_PTR(kt), C.CK_ULONG(C.sizeof_CK_KEY_TYPE)},
1075 }
1076 if err := o.getAttribute(attrs); err != nil {
1077 return nil, fmt.Errorf("getting certificate type: %w", err)
1078 }
1079 switch *kt {
1080 case C.CKK_EC:
1081 return o.ecdsaPublicKey()
1082 case C.CKK_RSA:
1083 return o.rsaPublicKey()
1084 default:
1085 return nil, fmt.Errorf("unsupported key type: 0x%x", *kt)
1086 }
1087 }
1088
1089 func (o Object) rsaPublicKey() (crypto.PublicKey, error) {
1090 // http://docs.oasis-open.org/pkcs11/pkcs11-curr/v2.40/cs01/pkcs11-curr-v2.40-cs01.html#_Toc399398838
1091 attrs := []C.CK_ATTRIBUTE{
1092 {C.CKA_MODULUS, nil, 0},
1093 {C.CKA_PUBLIC_EXPONENT, nil, 0},
1094 }
1095 if err := o.getAttribute(attrs); err != nil {
1096 return nil, fmt.Errorf("getting attributes: %w", err)
1097 }
1098 if attrs[0].ulValueLen == 0 {
1099 return nil, fmt.Errorf("no modulus attribute returned")
1100 }
1101 if attrs[1].ulValueLen == 0 {
1102 return nil, fmt.Errorf("no public exponent returned")
1103 }
1104
1105 cN := (C.CK_VOID_PTR)(C.malloc(attrs[0].ulValueLen * C.sizeof_CK_BYTE))
1106 defer C.free(unsafe.Pointer(cN))
1107 attrs[0].pValue = cN
1108
1109 cE := (C.CK_VOID_PTR)(C.malloc(attrs[1].ulValueLen))
1110 defer C.free(unsafe.Pointer(cE))
1111 attrs[1].pValue = cE
1112
1113 if err := o.getAttribute(attrs); err != nil {
1114 return nil, fmt.Errorf("getting attribute values: %w", err)
1115 }
1116
1117 nBytes := C.GoBytes(unsafe.Pointer(cN), C.int(attrs[0].ulValueLen))
1118 eBytes := C.GoBytes(unsafe.Pointer(cE), C.int(attrs[1].ulValueLen))
1119
1120 var n, e big.Int
1121 n.SetBytes(nBytes)
1122 e.SetBytes(eBytes)
1123 return &rsa.PublicKey{N: &n, E: int(e.Int64())}, nil
1124 }
1125
1126 func (o Object) ecdsaPublicKey() (crypto.PublicKey, error) {
1127 // http://docs.oasis-open.org/pkcs11/pkcs11-curr/v2.40/cs01/pkcs11-curr-v2.40-cs01.html#_Toc399398881
1128 attrs := []C.CK_ATTRIBUTE{
1129 {C.CKA_EC_PARAMS, nil, 0},
1130 {C.CKA_EC_POINT, nil, 0},
1131 }
1132 if err := o.getAttribute(attrs); err != nil {
1133 return nil, fmt.Errorf("getting attributes: %w", err)
1134 }
1135 if attrs[0].ulValueLen == 0 {
1136 return nil, fmt.Errorf("no ec parameters available")
1137 }
1138 if attrs[1].ulValueLen == 0 {
1139 return nil, fmt.Errorf("no ec point available")
1140 }
1141
1142 cParam := (C.CK_VOID_PTR)(C.malloc(attrs[0].ulValueLen))
1143 defer C.free(unsafe.Pointer(cParam))
1144 attrs[0].pValue = cParam
1145
1146 cPoint := (C.CK_VOID_PTR)(C.malloc(attrs[1].ulValueLen))
1147 defer C.free(unsafe.Pointer(cPoint))
1148 attrs[1].pValue = cPoint
1149
1150 if err := o.getAttribute(attrs); err != nil {
1151 return nil, fmt.Errorf("getting attribute values: %w", err)
1152 }
1153
1154 paramBytes := C.GoBytes(unsafe.Pointer(cParam), C.int(attrs[0].ulValueLen))
1155 pointBytes := C.GoBytes(unsafe.Pointer(cPoint), C.int(attrs[1].ulValueLen))
1156
1157 var curve elliptic.Curve
1158 if bytes.Equal(paramBytes, p256OIDRaw) {
1159 curve = elliptic.P256()
1160 } else if bytes.Equal(paramBytes, p384OIDRaw) {
1161 curve = elliptic.P384()
1162 } else if bytes.Equal(paramBytes, p521OIDRaw) {
1163 curve = elliptic.P521()
1164 } else {
1165 return nil, fmt.Errorf("unsupported curve")
1166 }
1167
1168 var rawPoint asn1.RawValue
1169 if _, err := asn1.Unmarshal(pointBytes, &rawPoint); err != nil {
1170 return nil, fmt.Errorf("decoding ec point: %v", err)
1171 }
1172 x, y := elliptic.Unmarshal(curve, rawPoint.Bytes)
1173 if x == nil {
1174 return nil, fmt.Errorf("invalid point format")
1175 }
1176 return &ecdsa.PublicKey{
1177 Curve: curve,
1178 X: x,
1179 Y: y,
1180 }, nil
1181 }
1182
1183 // PrivateKey parses the underlying object as a private key. Both RSA and ECDSA
1184 // keys are supported.
1185 //
1186 // The returned PrivateKey implements crypto.Signer and optionally crypto.Decrypter
1187 // depending on the supported mechanisms.
1188 //
1189 // If the object isn't a public key, this method fails.
1190 func (o Object) PrivateKey(pub crypto.PublicKey) (crypto.PrivateKey, error) {
1191 if o.Class() != ClassPrivateKey {
1192 return nil, fmt.Errorf("object has class: %s", o.Class())
1193 }
1194
1195 kt := (*C.CK_KEY_TYPE)(C.malloc(C.sizeof_CK_KEY_TYPE))
1196 defer C.free(unsafe.Pointer(kt))
1197
1198 attrs := []C.CK_ATTRIBUTE{
1199 {C.CKA_KEY_TYPE, C.CK_VOID_PTR(kt), C.CK_ULONG(C.sizeof_CK_KEY_TYPE)},
1200 }
1201 if err := o.getAttribute(attrs); err != nil {
1202 return nil, fmt.Errorf("getting certificate type: %w", err)
1203 }
1204 switch *kt {
1205 case C.CKK_EC:
1206 p, ok := pub.(*ecdsa.PublicKey)
1207 if !ok {
1208 return nil, fmt.Errorf("expected ecdsa public key, got: %T", pub)
1209 }
1210 return &ecdsaPrivateKey{o, p}, nil
1211 case C.CKK_RSA:
1212 p, ok := pub.(*rsa.PublicKey)
1213 if !ok {
1214 return nil, fmt.Errorf("expected rsa public key, got: %T", pub)
1215 }
1216 return &rsaPrivateKey{o, p}, nil
1217 default:
1218 return nil, fmt.Errorf("unsupported key type: 0x%x", *kt)
1219 }
1220 }
1221
1222 // Precomputed ASN1 signature prefixes.
1223 //
1224 // Borrowed from crypto/rsa.
1225 var hashPrefixes = map[crypto.Hash][]byte{
1226 crypto.SHA224: {0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05, 0x00, 0x04, 0x1c},
1227 crypto.SHA256: {0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20},
1228 crypto.SHA384: {0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00, 0x04, 0x30},
1229 crypto.SHA512: {0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05, 0x00, 0x04, 0x40},
1230 }
1231
1232 type rsaPrivateKey struct {
1233 o Object
1234 pub *rsa.PublicKey
1235 }
1236
1237 func (r *rsaPrivateKey) Public() crypto.PublicKey {
1238 return r.pub
1239 }
1240
1241 func (r *rsaPrivateKey) Sign(_ io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error) {
1242 if o, ok := opts.(*rsa.PSSOptions); ok {
1243 return r.signPSS(digest, o)
1244 }
1245
1246 // http://docs.oasis-open.org/pkcs11/pkcs11-curr/v2.40/cs01/pkcs11-curr-v2.40-cs01.html#_Toc399398842
1247 size := opts.HashFunc().Size()
1248 if size != len(digest) {
1249 return nil, fmt.Errorf("input must be hashed")
1250 }
1251 prefix, ok := hashPrefixes[opts.HashFunc()]
1252 if !ok {
1253 return nil, fmt.Errorf("unsupported hash function: %s", opts.HashFunc())
1254 }
1255
1256 preAndDigest := append(prefix, digest...)
1257 cBytes := toCBytes(preAndDigest)
1258
1259 cSig := make([]C.CK_BYTE, r.pub.Size())
1260 cSigLen := C.CK_ULONG(len(cSig))
1261
1262 m := C.CK_MECHANISM{C.CKM_RSA_PKCS, nil, 0}
1263 rv := C.ck_sign_init(r.o.fl, r.o.h, &m, r.o.o)
1264 if err := isOk("C_SignInit", rv); err != nil {
1265 return nil, err
1266 }
1267 rv = C.ck_sign(r.o.fl, r.o.h, &cBytes[0], C.CK_ULONG(len(cBytes)), &cSig[0], &cSigLen)
1268 if err := isOk("C_Sign", rv); err != nil {
1269 return nil, err
1270 }
1271
1272 if int(cSigLen) != len(cSig) {
1273 return nil, fmt.Errorf("expected signature of length %d, got %d", len(cSig), cSigLen)
1274 }
1275 sig := toBytes(cSig)
1276 return sig, nil
1277 }
1278
1279 func (r *rsaPrivateKey) signPSS(digest []byte, opts *rsa.PSSOptions) ([]byte, error) {
1280 // http://docs.oasis-open.org/pkcs11/pkcs11-curr/v2.40/cs01/pkcs11-curr-v2.40-cs01.html#_Toc399398846
1281 // http://docs.oasis-open.org/pkcs11/pkcs11-curr/v2.40/cs01/pkcs11-curr-v2.40-cs01.html#_Toc399398845
1282 cParam := (C.CK_RSA_PKCS_PSS_PARAMS_PTR)(C.malloc(C.sizeof_CK_RSA_PKCS_PSS_PARAMS))
1283 defer C.free(unsafe.Pointer(cParam))
1284
1285 switch opts.Hash {
1286 case crypto.SHA256:
1287 cParam.hashAlg = C.CKM_SHA256
1288 cParam.mgf = C.CKG_MGF1_SHA256
1289 case crypto.SHA384:
1290 cParam.hashAlg = C.CKM_SHA384
1291 cParam.mgf = C.CKG_MGF1_SHA384
1292 case crypto.SHA512:
1293 cParam.hashAlg = C.CKM_SHA512
1294 cParam.mgf = C.CKG_MGF1_SHA512
1295 default:
1296 return nil, fmt.Errorf("unsupported hash algorithm: %s", opts.Hash)
1297 }
1298
1299 switch opts.SaltLength {
1300 case rsa.PSSSaltLengthAuto:
1301 // Same logic as crypto/rsa.
1302 l := (r.pub.N.BitLen()-1+7)/8 - 2 - opts.Hash.Size()
1303 cParam.sLen = C.CK_ULONG(l)
1304 case rsa.PSSSaltLengthEqualsHash:
1305 cParam.sLen = C.CK_ULONG(opts.Hash.Size())
1306 default:
1307 cParam.sLen = C.CK_ULONG(opts.SaltLength)
1308 }
1309
1310 cBytes := toCBytes(digest)
1311
1312 cSig := make([]C.CK_BYTE, r.pub.Size())
1313 cSigLen := C.CK_ULONG(len(cSig))
1314
1315 m := C.CK_MECHANISM{
1316 mechanism: C.CKM_RSA_PKCS_PSS,
1317 pParameter: C.CK_VOID_PTR(cParam),
1318 ulParameterLen: C.CK_ULONG(C.sizeof_CK_RSA_PKCS_PSS_PARAMS),
1319 }
1320
1321 rv := C.ck_sign_init(r.o.fl, r.o.h, &m, r.o.o)
1322 if err := isOk("C_SignInit", rv); err != nil {
1323 return nil, err
1324 }
1325 rv = C.ck_sign(r.o.fl, r.o.h, &cBytes[0], C.CK_ULONG(len(cBytes)), &cSig[0], &cSigLen)
1326 if err := isOk("C_Sign", rv); err != nil {
1327 return nil, err
1328 }
1329
1330 if int(cSigLen) != len(cSig) {
1331 return nil, fmt.Errorf("expected signature of length %d, got %d", len(cSig), cSigLen)
1332 }
1333 sig := toBytes(cSig)
1334 return sig, nil
1335 }
1336
1337 type ecdsaPrivateKey struct {
1338 o Object
1339 pub *ecdsa.PublicKey
1340 }
1341
1342 func (e *ecdsaPrivateKey) Public() crypto.PublicKey {
1343 return e.pub
1344 }
1345
1346 type ecdsaSignature struct {
1347 R, S *big.Int
1348 }
1349
1350 func (e *ecdsaPrivateKey) Sign(_ io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error) {
1351 // http://docs.oasis-open.org/pkcs11/pkcs11-curr/v2.40/cs01/pkcs11-curr-v2.40-cs01.html#_Toc399398884
1352 m := C.CK_MECHANISM{C.CKM_ECDSA, nil, 0}
1353 rv := C.ck_sign_init(e.o.fl, e.o.h, &m, e.o.o)
1354 if err := isOk("C_SignInit", rv); err != nil {
1355 return nil, err
1356 }
1357
1358 byteLen := (e.pub.Curve.Params().BitSize + 7) / 8
1359 cSig := make([]C.CK_BYTE, byteLen*2)
1360 cSigLen := C.CK_ULONG(len(cSig))
1361
1362 cBytes := toCBytes(digest)
1363
1364 rv = C.ck_sign(e.o.fl, e.o.h, &cBytes[0], C.CK_ULONG(len(digest)), &cSig[0], &cSigLen)
1365 if err := isOk("C_Sign", rv); err != nil {
1366 return nil, err
1367 }
1368
1369 if int(cSigLen) != len(cSig) {
1370 return nil, fmt.Errorf("expected signature of length %d, got %d", len(cSig), cSigLen)
1371 }
1372 sig := toBytes(cSig)
1373
1374 var (
1375 r = big.NewInt(0)
1376 s = big.NewInt(0)
1377 )
1378 r.SetBytes(sig[:len(sig)/2])
1379 s.SetBytes(sig[len(sig)/2:])
1380
1381 return asn1.Marshal(ecdsaSignature{r, s})
1382 }
1383
1384 // CertificateType determines the kind of certificate a certificate object holds.
1385 // This can be X.509, WTLS, GPG, etc.
1386 //
1387 // http://docs.oasis-open.org/pkcs11/pkcs11-base/v2.40/os/pkcs11-base-v2.40-os.html#_Toc416959709
1388 type CertificateType int
1389
1390 // Certificate types supported by this package.
1391 const (
1392 CertificateX509 CertificateType = iota + 1
1393 CertificateUnknown
1394 )
1395
1396 // Certificate holds a certificate object. Because certificates object can hold
1397 // various kinds of certificates, callers should check the type before calling
1398 // methods that parse the certificate.
1399 //
1400 // cert, err := obj.Certificate()
1401 // if err != nil {
1402 // // ...
1403 // }
1404 // if cert.Type() != pkcs11.CertificateX509 {
1405 // // unexpected kind of certificate ...
1406 // }
1407 // x509Cert, err := cert.X509()
1408 type Certificate struct {
1409 o Object
1410 t C.CK_CERTIFICATE_TYPE
1411 }
1412
1413 // Type returns the format of the underlying certificate.
1414 func (c *Certificate) Type() CertificateType {
1415 switch c.t {
1416 case C.CKC_X_509:
1417 return CertificateX509
1418 default:
1419 return CertificateUnknown
1420 }
1421 }
1422
1423 // X509 parses the underlying certificate as an X.509 certificate.
1424 //
1425 // If the certificate holds a different type of certificate, this method
1426 // returns an error.
1427 func (c *Certificate) X509() (*x509.Certificate, error) {
1428 // http://docs.oasis-open.org/pkcs11/pkcs11-base/v2.40/os/pkcs11-base-v2.40-os.html#_Toc416959712
1429 if c.t != C.CKC_X_509 {
1430 return nil, fmt.Errorf("invalid certificate type")
1431 }
1432
1433 // TODO(ericchiang): Do we want to support CKA_URL?
1434 var n C.CK_ULONG
1435 attrs := []C.CK_ATTRIBUTE{
1436 {C.CKA_VALUE, nil, n},
1437 }
1438 if err := c.o.getAttribute(attrs); err != nil {
1439 return nil, fmt.Errorf("getting certificate type: %w", err)
1440 }
1441 n = attrs[0].ulValueLen
1442 if n == 0 {
1443 return nil, fmt.Errorf("certificate value not present")
1444 }
1445 cRaw := (C.CK_VOID_PTR)(C.malloc(C.ulong(n)))
1446 defer C.free(unsafe.Pointer(cRaw))
1447
1448 attrs[0].pValue = cRaw
1449 if err := c.o.getAttribute(attrs); err != nil {
1450 return nil, fmt.Errorf("getting certificate type: %w", err)
1451 }
1452
1453 raw := C.GoBytes(unsafe.Pointer(cRaw), C.int(n))
1454 cert, err := x509.ParseCertificate(raw)
1455 if err != nil {
1456 return nil, fmt.Errorf("parsing certificate: %v", err)
1457 }
1458 return cert, nil
1459 }
1460
1461 // keyOptions holds parameters used for generating a private key.
1462 type keyOptions struct {
1463 // RSABits indicates that the generated key should be a RSA key and also
1464 // provides the number of bits.
1465 RSABits int
1466 // ECDSACurve indicates that the generated key should be an ECDSA key and
1467 // identifies the curve used to generate the key.
1468 ECDSACurve elliptic.Curve
1469
1470 // Label for the final object.
1471 LabelPublic string
1472 LabelPrivate string
1473 }
1474
1475 // https://datatracker.ietf.org/doc/html/rfc5480#section-2.1.1.1
1476
1477 // Generate a private key on the slot, creating associated private and public
1478 // key objects.
1479 func (s *Slot) generate(opts keyOptions) (crypto.PrivateKey, error) {
1480 if opts.ECDSACurve != nil && opts.RSABits != 0 {
1481 return nil, fmt.Errorf("conflicting key parameters provided")
1482 }
1483 if opts.ECDSACurve != nil {
1484 return s.generateECDSA(opts)
1485 }
1486 if opts.RSABits != 0 {
1487 return s.generateRSA(opts)
1488 }
1489 return nil, fmt.Errorf("no key parameters provided")
1490 }
1491
1492 // http://docs.oasis-open.org/pkcs11/pkcs11-base/v2.40/os/pkcs11-base-v2.40-os.html#_Toc416959719
1493 // http://docs.oasis-open.org/pkcs11/pkcs11-curr/v2.40/os/pkcs11-curr-v2.40-os.html#_Toc416959971
1494 func (s *Slot) generateRSA(o keyOptions) (crypto.PrivateKey, error) {
1495 var (
1496 mechanism = C.CK_MECHANISM{
1497 mechanism: C.CKM_RSA_PKCS_KEY_PAIR_GEN,
1498 }
1499 pubH C.CK_OBJECT_HANDLE
1500 privH C.CK_OBJECT_HANDLE
1501 )
1502
1503 cTrue := (C.CK_VOID_PTR)(C.malloc(C.sizeof_CK_BBOOL))
1504 cFalse := (C.CK_VOID_PTR)(C.malloc(C.sizeof_CK_BBOOL))
1505 defer C.free(unsafe.Pointer(cTrue))
1506 defer C.free(unsafe.Pointer(cFalse))
1507 *((*C.CK_BBOOL)(cTrue)) = C.CK_TRUE
1508 *((*C.CK_BBOOL)(cFalse)) = C.CK_FALSE
1509
1510 cModBits := (C.CK_VOID_PTR)(C.malloc(C.sizeof_CK_ULONG))
1511 defer C.free(unsafe.Pointer(cModBits))
1512
1513 *((*C.CK_ULONG)(cModBits)) = C.CK_ULONG(o.RSABits)
1514
1515 privTmpl := []C.CK_ATTRIBUTE{
1516 {C.CKA_PRIVATE, cTrue, C.CK_ULONG(C.sizeof_CK_BBOOL)},
1517 {C.CKA_SENSITIVE, cTrue, C.CK_ULONG(C.sizeof_CK_BBOOL)},
1518 {C.CKA_SIGN, cTrue, C.CK_ULONG(C.sizeof_CK_BBOOL)},
1519 }
1520
1521 if o.LabelPrivate != "" {
1522 cs, free := ckCString(o.LabelPrivate)
1523 defer free()
1524
1525 privTmpl = append(privTmpl, C.CK_ATTRIBUTE{
1526 C.CKA_LABEL,
1527 C.CK_VOID_PTR(cs),
1528 C.CK_ULONG(len(o.LabelPrivate)),
1529 })
1530 }
1531
1532 pubTmpl := []C.CK_ATTRIBUTE{
1533 {C.CKA_MODULUS_BITS, cModBits, C.CK_ULONG(C.sizeof_CK_ULONG)},
1534 {C.CKA_VERIFY, cTrue, C.CK_ULONG(C.sizeof_CK_BBOOL)},
1535 }
1536
1537 if o.LabelPublic != "" {
1538 cs, free := ckCString(o.LabelPublic)
1539 defer free()
1540
1541 pubTmpl = append(pubTmpl, C.CK_ATTRIBUTE{
1542 C.CKA_LABEL,
1543 C.CK_VOID_PTR(cs),
1544 C.CK_ULONG(len(o.LabelPublic)),
1545 })
1546 }
1547
1548 rv := C.ck_generate_key_pair(
1549 s.fl, s.h, &mechanism,
1550 &pubTmpl[0], C.CK_ULONG(len(pubTmpl)),
1551 &privTmpl[0], C.CK_ULONG(len(privTmpl)),
1552 &pubH, &privH,
1553 )
1554
1555 if err := isOk("C_GenerateKeyPair", rv); err != nil {
1556 return nil, err
1557 }
1558
1559 pubObj, err := s.newObject(pubH)
1560 if err != nil {
1561 return nil, fmt.Errorf("public key object: %w", err)
1562 }
1563 privObj, err := s.newObject(privH)
1564 if err != nil {
1565 return nil, fmt.Errorf("private key object: %w", err)
1566 }
1567 pub, err := pubObj.PublicKey()
1568 if err != nil {
1569 return nil, fmt.Errorf("parsing public key: %w", err)
1570 }
1571 priv, err := privObj.PrivateKey(pub)
1572 if err != nil {
1573 return nil, fmt.Errorf("parsing private key: %w", err)
1574 }
1575 return priv, nil
1576 }
1577
1578 // https://datatracker.ietf.org/doc/html/rfc5480#section-2.1.1.1
1579 //
1580 // Generated with https://play.golang.org/p/tkqXov5Xpwp
1581 var (
1582 p256OIDRaw = []byte{0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07}
1583 p384OIDRaw = []byte{0x06, 0x05, 0x2b, 0x81, 0x04, 0x00, 0x22}
1584 p521OIDRaw = []byte{0x06, 0x05, 0x2b, 0x81, 0x04, 0x00, 0x23}
1585 )
1586
1587 // generateECDSA implements the CKM_ECDSA_KEY_PAIR_GEN mechanism.
1588 //
1589 // http://docs.oasis-open.org/pkcs11/pkcs11-base/v2.40/os/pkcs11-base-v2.40-os.html#_Toc416959719
1590 // https://datatracker.ietf.org/doc/html/rfc5480#section-2.1.1.1
1591 // http://docs.oasis-open.org/pkcs11/pkcs11-curr/v2.40/os/pkcs11-curr-v2.40-os.html#_Toc416960014
1592 func (s *Slot) generateECDSA(o keyOptions) (crypto.PrivateKey, error) {
1593 var (
1594 mechanism = C.CK_MECHANISM{
1595 mechanism: C.CKM_EC_KEY_PAIR_GEN,
1596 }
1597 pubH C.CK_OBJECT_HANDLE
1598 privH C.CK_OBJECT_HANDLE
1599 )
1600
1601 if o.ECDSACurve == nil {
1602 return nil, fmt.Errorf("no curve provided")
1603 }
1604
1605 var oid []byte
1606 switch o.ECDSACurve.Params().Name {
1607 case "P-256":
1608 oid = p256OIDRaw
1609 case "P-384":
1610 oid = p384OIDRaw
1611 case "P-521":
1612 oid = p521OIDRaw
1613 default:
1614 return nil, fmt.Errorf("unsupported ECDSA curve")
1615 }
1616
1617 // When passing a struct or array to C, that value can't refer to Go
1618 // memory. Allocate all attribute values in C rather than in Go.
1619 cOID := (C.CK_VOID_PTR)(C.CBytes(oid))
1620 defer C.free(unsafe.Pointer(cOID))
1621
1622 cTrue := (C.CK_VOID_PTR)(C.malloc(C.sizeof_CK_BBOOL))
1623 cFalse := (C.CK_VOID_PTR)(C.malloc(C.sizeof_CK_BBOOL))
1624 defer C.free(unsafe.Pointer(cTrue))
1625 defer C.free(unsafe.Pointer(cFalse))
1626 *((*C.CK_BBOOL)(cTrue)) = C.CK_TRUE
1627 *((*C.CK_BBOOL)(cFalse)) = C.CK_FALSE
1628
1629 privTmpl := []C.CK_ATTRIBUTE{
1630 {C.CKA_PRIVATE, cTrue, C.CK_ULONG(C.sizeof_CK_BBOOL)},
1631 {C.CKA_SENSITIVE, cTrue, C.CK_ULONG(C.sizeof_CK_BBOOL)},
1632 {C.CKA_SIGN, cTrue, C.CK_ULONG(C.sizeof_CK_BBOOL)},
1633 }
1634
1635 if o.LabelPrivate != "" {
1636 cs, free := ckCString(o.LabelPrivate)
1637 defer free()
1638
1639 privTmpl = append(privTmpl, C.CK_ATTRIBUTE{
1640 C.CKA_LABEL,
1641 C.CK_VOID_PTR(cs),
1642 C.CK_ULONG(len(o.LabelPrivate)),
1643 })
1644 }
1645
1646 pubTmpl := []C.CK_ATTRIBUTE{
1647 {C.CKA_EC_PARAMS, cOID, C.CK_ULONG(len(oid))},
1648 {C.CKA_VERIFY, cTrue, C.CK_ULONG(C.sizeof_CK_BBOOL)},
1649 }
1650 if o.LabelPublic != "" {
1651 cs, free := ckCString(o.LabelPublic)
1652 defer free()
1653
1654 pubTmpl = append(pubTmpl, C.CK_ATTRIBUTE{
1655 C.CKA_LABEL,
1656 C.CK_VOID_PTR(cs),
1657 C.CK_ULONG(len(o.LabelPublic)),
1658 })
1659 }
1660
1661 rv := C.ck_generate_key_pair(
1662 s.fl, s.h, &mechanism,
1663 &pubTmpl[0], C.CK_ULONG(len(pubTmpl)),
1664 &privTmpl[0], C.CK_ULONG(len(privTmpl)),
1665 &pubH, &privH,
1666 )
1667
1668 if err := isOk("C_GenerateKeyPair", rv); err != nil {
1669 return nil, err
1670 }
1671
1672 pubObj, err := s.newObject(pubH)
1673 if err != nil {
1674 return nil, fmt.Errorf("public key object: %w", err)
1675 }
1676 privObj, err := s.newObject(privH)
1677 if err != nil {
1678 return nil, fmt.Errorf("private key object: %w", err)
1679 }
1680 pub, err := pubObj.PublicKey()
1681 if err != nil {
1682 return nil, fmt.Errorf("parsing public key: %w", err)
1683 }
1684 priv, err := privObj.PrivateKey(pub)
1685 if err != nil {
1686 return nil, fmt.Errorf("parsing private key: %w", err)
1687 }
1688 return priv, nil
1689 }
1690
1691 func (r *rsaPrivateKey) Decrypt(_ io.Reader, encryptedData []byte, opts crypto.DecrypterOpts) ([]byte, error) {
1692 var m C.CK_MECHANISM
1693
1694 if o, ok := opts.(*rsa.OAEPOptions); ok {
1695 cParam := (C.CK_RSA_PKCS_OAEP_PARAMS_PTR)(C.malloc(C.sizeof_CK_RSA_PKCS_OAEP_PARAMS))
1696 defer C.free(unsafe.Pointer(cParam))
1697
1698 switch o.Hash {
1699 case crypto.SHA256:
1700 cParam.hashAlg = C.CKM_SHA256
1701 cParam.mgf = C.CKG_MGF1_SHA256
1702 case crypto.SHA384:
1703 cParam.hashAlg = C.CKM_SHA384
1704 cParam.mgf = C.CKG_MGF1_SHA384
1705 case crypto.SHA512:
1706 cParam.hashAlg = C.CKM_SHA512
1707 cParam.mgf = C.CKG_MGF1_SHA512
1708 case crypto.SHA1:
1709 cParam.hashAlg = C.CKM_SHA_1
1710 cParam.mgf = C.CKG_MGF1_SHA1
1711 default:
1712 return nil, fmt.Errorf("decryptOAEP error, unsupported hash algorithm: %s", o.Hash)
1713 }
1714
1715 cParam.source = C.CKZ_DATA_SPECIFIED
1716 cParam.pSourceData = nil
1717 cParam.ulSourceDataLen = 0
1718
1719 m = C.CK_MECHANISM{
1720 mechanism: C.CKM_RSA_PKCS_OAEP,
1721 pParameter: C.CK_VOID_PTR(cParam),
1722 ulParameterLen: C.CK_ULONG(C.sizeof_CK_RSA_PKCS_OAEP_PARAMS),
1723 }
1724 } else {
1725 m = C.CK_MECHANISM{C.CKM_RSA_PKCS, nil, 0}
1726 }
1727
1728 cEncDataBytes := toCBytes(encryptedData)
1729
1730 rv := C.ck_decrypt_init(r.o.fl, r.o.h, &m, r.o.o)
1731 if err := isOk("C_DecryptInit", rv); err != nil {
1732 return nil, err
1733 }
1734
1735 var cDecryptedLen C.CK_ULONG
1736
1737 // First call is used to determine length necessary to hold decrypted data (PKCS #11 5.2)
1738 rv = C.ck_decrypt(r.o.fl, r.o.h, &cEncDataBytes[0], C.CK_ULONG(len(cEncDataBytes)), nil, &cDecryptedLen)
1739 if err := isOk("C_Decrypt", rv); err != nil {
1740 return nil, err
1741 }
1742
1743 cDecrypted := make([]C.CK_BYTE, cDecryptedLen)
1744
1745 rv = C.ck_decrypt(r.o.fl, r.o.h, &cEncDataBytes[0], C.CK_ULONG(len(cEncDataBytes)), &cDecrypted[0], &cDecryptedLen)
1746 if err := isOk("C_Decrypt", rv); err != nil {
1747 return nil, err
1748 }
1749
1750 decrypted := toBytes(cDecrypted)
1751
1752 // Removes null padding (PKCS#11 5.2): http://docs.oasis-open.org/pkcs11/pkcs11-base/v2.40/os/pkcs11-base-v2.40-os.html#_Toc416959738
1753 decrypted = bytes.Trim(decrypted, "\x00")
1754
1755 return decrypted, nil
1756 }
1757
1758 func toBytes(data []C.CK_BYTE) []byte {
1759 goBytes := make([]byte, len(data))
1760 for i, b := range data {
1761 goBytes[i] = byte(b)
1762 }
1763 return goBytes
1764 }
1765
1766 func toCBytes(data []byte) []C.CK_BYTE {
1767 cBytes := make([]C.CK_BYTE, len(data))
1768 for i, b := range data {
1769 cBytes[i] = C.CK_BYTE(b)
1770 }
1771 return cBytes
1772 }