Debian Codegraph @

pkcs11/pkcs11.go

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