forked from OpenSC/libp11
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheng_back.c
1102 lines (1001 loc) · 31.2 KB
/
eng_back.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2001 Markus Friedl
* Copyright (c) 2002 Juha Yrjölä
* Copyright (c) 2002 Olaf Kirch
* Copyright (c) 2003 Kevin Stefanik
* Copyright (c) 2016-2018 Michał Trojnara <[email protected]>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "engine.h"
#include <stdio.h>
#include <string.h>
#if defined(_WIN32) || defined(_WIN64)
#define strncasecmp _strnicmp
#endif
/* The maximum length of an internally-allocated PIN */
#define MAX_PIN_LENGTH 32
#define MAX_VALUE_LEN 200
struct st_engine_ctx {
/* Engine configuration */
/*
* The PIN used for login. Cache for the ctx_get_pin function.
* The memory for this PIN is always owned internally,
* and may be freed as necessary. Before freeing, the PIN
* must be whitened, to prevent security holes.
*/
char *pin;
size_t pin_length;
int verbose;
char *module;
char *init_args;
UI_METHOD *ui_method;
void *callback_data;
int force_login;
/* Engine initialization mutex */
#if OPENSSL_VERSION_NUMBER >= 0x10100004L && !defined(LIBRESSL_VERSION_NUMBER)
CRYPTO_RWLOCK *rwlock;
#else
int rwlock;
#endif
/* Current operations */
PKCS11_CTX *pkcs11_ctx;
PKCS11_SLOT *slot_list;
unsigned int slot_count;
};
/******************************************************************************/
/* Utility functions */
/******************************************************************************/
void ctx_log(ENGINE_CTX *ctx, int level, const char *format, ...)
{
va_list ap;
if (level > ctx->verbose)
return;
va_start(ap, format);
vfprintf(stderr, format, ap);
va_end(ap);
}
static void dump_hex(ENGINE_CTX *ctx, int level,
const unsigned char *val, const size_t len)
{
size_t n;
for (n = 0; n < len; n++)
ctx_log(ctx, level, "%02x", val[n]);
}
/******************************************************************************/
/* PIN handling */
/******************************************************************************/
/* Free PIN storage in secure way. */
static void ctx_destroy_pin(ENGINE_CTX *ctx)
{
if (ctx->pin) {
OPENSSL_cleanse(ctx->pin, ctx->pin_length);
OPENSSL_free(ctx->pin);
ctx->pin = NULL;
ctx->pin_length = 0;
}
}
/* Get the PIN via asking user interface. The supplied call-back data are
* passed to the user interface implemented by an application. Only the
* application knows how to interpret the call-back data.
* A (strdup'ed) copy of the PIN code will be stored in the pin variable. */
static int ctx_get_pin(ENGINE_CTX *ctx, const char* token_label, UI_METHOD *ui_method, void *callback_data)
{
UI *ui;
char* prompt;
/* call ui to ask for a pin */
ui = UI_new_method(ui_method);
if (!ui) {
ctx_log(ctx, 0, "UI_new failed\n");
return 0;
}
if (callback_data)
UI_add_user_data(ui, callback_data);
ctx_destroy_pin(ctx);
ctx->pin = OPENSSL_malloc(MAX_PIN_LENGTH+1);
if (!ctx->pin)
return 0;
memset(ctx->pin, 0, MAX_PIN_LENGTH+1);
ctx->pin_length = MAX_PIN_LENGTH;
prompt = UI_construct_prompt(ui, "PKCS#11 token PIN", token_label);
if (!prompt) {
return 0;
}
if (!UI_dup_input_string(ui, prompt,
UI_INPUT_FLAG_DEFAULT_PWD, ctx->pin, 4, MAX_PIN_LENGTH)) {
ctx_log(ctx, 0, "UI_dup_input_string failed\n");
UI_free(ui);
OPENSSL_free(prompt);
return 0;
}
OPENSSL_free(prompt);
if (UI_process(ui)) {
ctx_log(ctx, 0, "UI_process failed\n");
UI_free(ui);
return 0;
}
UI_free(ui);
return 1;
}
/* Return 1 if the user has already logged in */
static int slot_logged_in(ENGINE_CTX *ctx, PKCS11_SLOT *slot) {
int logged_in = 0;
/* Check if already logged in to avoid resetting state */
if (PKCS11_is_logged_in(slot, 0, &logged_in) != 0) {
ctx_log(ctx, 0, "Unable to check if already logged in\n");
return 0;
}
return logged_in;
}
/*
* Log-into the token if necessary.
*
* @slot is PKCS11 slot to log in
* @tok is PKCS11 token to log in (??? could be derived as @slot->token)
* @ui_method is OpenSSL user interface which is used to ask for a password
* @callback_data are application data to the user interface
* @return 1 on success, 0 on error.
*/
static int ctx_login(ENGINE_CTX *ctx, PKCS11_SLOT *slot, PKCS11_TOKEN *tok,
UI_METHOD *ui_method, void *callback_data)
{
if (!(ctx->force_login || tok->loginRequired) || slot_logged_in(ctx, slot))
return 1;
/* If the token has a secure login (i.e., an external keypad),
* then use a NULL PIN. Otherwise, obtain a new PIN if needed. */
if (tok->secureLogin) {
/* Free the PIN if it has already been
* assigned (i.e, cached by ctx_get_pin) */
ctx_destroy_pin(ctx);
} else if (!ctx->pin) {
ctx->pin = OPENSSL_malloc(MAX_PIN_LENGTH+1);
ctx->pin_length = MAX_PIN_LENGTH;
if (ctx->pin == NULL) {
ctx_log(ctx, 0, "Could not allocate memory for PIN\n");
return 0;
}
memset(ctx->pin, 0, MAX_PIN_LENGTH+1);
if (!ctx_get_pin(ctx, tok->label, ui_method, callback_data)) {
ctx_destroy_pin(ctx);
ctx_log(ctx, 0, "No PIN code was entered\n");
return 0;
}
}
/* Now login in with the (possibly NULL) PIN */
if (PKCS11_login(slot, 0, ctx->pin)) {
/* Login failed, so free the PIN if present */
ctx_destroy_pin(ctx);
ctx_log(ctx, 0, "Login failed\n");
return 0;
}
return 1;
}
/******************************************************************************/
/* Initialization and cleanup */
/******************************************************************************/
ENGINE_CTX *ctx_new()
{
ENGINE_CTX *ctx;
char *mod;
ctx = OPENSSL_malloc(sizeof(ENGINE_CTX));
if (!ctx)
return NULL;
memset(ctx, 0, sizeof(ENGINE_CTX));
mod = getenv("PKCS11_MODULE_PATH");
if (mod) {
ctx->module = OPENSSL_strdup(mod);
} else {
#ifdef DEFAULT_PKCS11_MODULE
ctx->module = OPENSSL_strdup(DEFAULT_PKCS11_MODULE);
#else
ctx->module = NULL;
#endif
}
#if OPENSSL_VERSION_NUMBER >= 0x10100004L && !defined(LIBRESSL_VERSION_NUMBER)
ctx->rwlock = CRYPTO_THREAD_lock_new();
#else
ctx->rwlock = CRYPTO_get_dynlock_create_callback() ?
CRYPTO_get_new_dynlockid() : 0;
#endif
return ctx;
}
/* Destroy the context allocated with ctx_new() */
int ctx_destroy(ENGINE_CTX *ctx)
{
if (ctx) {
ctx_destroy_pin(ctx);
OPENSSL_free(ctx->module);
OPENSSL_free(ctx->init_args);
#if OPENSSL_VERSION_NUMBER >= 0x10100004L && !defined(LIBRESSL_VERSION_NUMBER)
CRYPTO_THREAD_lock_free(ctx->rwlock);
#else
if (ctx->rwlock)
CRYPTO_destroy_dynlockid(ctx->rwlock);
#endif
OPENSSL_free(ctx);
}
return 1;
}
/* Initialize libp11 data: ctx->pkcs11_ctx and ctx->slot_list */
static void ctx_init_libp11_unlocked(ENGINE_CTX *ctx)
{
PKCS11_CTX *pkcs11_ctx;
PKCS11_SLOT *slot_list = NULL;
unsigned int slot_count = 0;
ctx_log(ctx, 1, "PKCS#11: Initializing the engine\n");
pkcs11_ctx = PKCS11_CTX_new();
PKCS11_CTX_init_args(pkcs11_ctx, ctx->init_args);
PKCS11_set_ui_method(pkcs11_ctx, ctx->ui_method, ctx->callback_data);
/* PKCS11_CTX_load() uses C_GetSlotList() via p11-kit */
if (PKCS11_CTX_load(pkcs11_ctx, ctx->module) < 0) {
ctx_log(ctx, 0, "Unable to load module %s\n", ctx->module);
PKCS11_CTX_free(pkcs11_ctx);
return;
}
/* PKCS11_enumerate_slots() uses C_GetSlotList() via libp11 */
if (PKCS11_enumerate_slots(pkcs11_ctx, &slot_list, &slot_count) < 0) {
ctx_log(ctx, 0, "Failed to enumerate slots\n");
PKCS11_CTX_unload(pkcs11_ctx);
PKCS11_CTX_free(pkcs11_ctx);
return;
}
ctx_log(ctx, 1, "Found %u slot%s\n", slot_count,
slot_count <= 1 ? "" : "s");
ctx->pkcs11_ctx = pkcs11_ctx;
ctx->slot_list = slot_list;
ctx->slot_count = slot_count;
}
static int ctx_init_libp11(ENGINE_CTX *ctx)
{
#if OPENSSL_VERSION_NUMBER >= 0x10100004L && !defined(LIBRESSL_VERSION_NUMBER)
CRYPTO_THREAD_write_lock(ctx->rwlock);
#else
if (ctx->rwlock)
CRYPTO_w_lock(ctx->rwlock);
#endif
if (!ctx->pkcs11_ctx|| !ctx->slot_list)
ctx_init_libp11_unlocked(ctx);
#if OPENSSL_VERSION_NUMBER >= 0x10100004L && !defined(LIBRESSL_VERSION_NUMBER)
CRYPTO_THREAD_unlock(ctx->rwlock);
#else
if (ctx->rwlock)
CRYPTO_w_unlock(ctx->rwlock);
#endif
return ctx->pkcs11_ctx && ctx->slot_list ? 0 : -1;
}
/* Function called from ENGINE_init() */
int ctx_init(ENGINE_CTX *ctx)
{
/* OpenSC implicitly locks CRYPTO_LOCK_ENGINE during C_GetSlotList().
* OpenSSL also locks CRYPTO_LOCK_ENGINE in ENGINE_init().
* Double-locking a non-recursive rwlock causes the application to
* crash or hang, depending on the locking library implementation. */
/* Only attempt initialization when dynamic locks are unavailable.
* This likely also indicates a single-threaded application,
* so temporarily unlocking CRYPTO_LOCK_ENGINE should be safe. */
#if OPENSSL_VERSION_NUMBER < 0x10100004L && !defined(LIBRESSL_VERSION_NUMBER)
if (CRYPTO_get_dynlock_create_callback() == NULL ||
CRYPTO_get_dynlock_lock_callback() == NULL ||
CRYPTO_get_dynlock_destroy_callback() == NULL) {
CRYPTO_w_unlock(CRYPTO_LOCK_ENGINE);
ctx_init_libp11_unlocked(ctx);
CRYPTO_w_lock(CRYPTO_LOCK_ENGINE);
return ctx->pkcs11_ctx && ctx->slot_list ? 1 : 0;
}
#else
(void)ctx; /* squash the unused parameter warning */
#endif
return 1;
}
/* Finish engine operations initialized with ctx_init() */
int ctx_finish(ENGINE_CTX *ctx)
{
if (ctx) {
if (ctx->slot_list) {
PKCS11_release_all_slots(ctx->pkcs11_ctx,
ctx->slot_list, ctx->slot_count);
ctx->slot_list = NULL;
ctx->slot_count = 0;
}
if (ctx->pkcs11_ctx) {
PKCS11_CTX_unload(ctx->pkcs11_ctx);
PKCS11_CTX_free(ctx->pkcs11_ctx);
ctx->pkcs11_ctx = NULL;
}
}
return 1;
}
/******************************************************************************/
/* Certificate handling */
/******************************************************************************/
/* prototype for OpenSSL ENGINE_load_cert */
/* used by load_cert_ctrl via ENGINE_ctrl for now */
static X509 *ctx_load_cert(ENGINE_CTX *ctx, const char *s_slot_cert_id,
const int login)
{
PKCS11_SLOT *slot;
PKCS11_SLOT *found_slot = NULL, **matched_slots = NULL;
PKCS11_TOKEN *tok, *match_tok = NULL;
PKCS11_CERT *certs, *selected_cert = NULL;
X509 *x509 = NULL;
unsigned int cert_count, n, m;
unsigned char cert_id[MAX_VALUE_LEN / 2];
size_t cert_id_len = sizeof(cert_id);
char *cert_label = NULL;
char tmp_pin[MAX_PIN_LENGTH+1];
size_t tmp_pin_len = MAX_PIN_LENGTH;
int slot_nr = -1;
char flags[64];
size_t matched_count = 0;
if (ctx_init_libp11(ctx)) /* Delayed libp11 initialization */
return NULL;
if (s_slot_cert_id && *s_slot_cert_id) {
if (!strncasecmp(s_slot_cert_id, "pkcs11:", 7)) {
n = parse_pkcs11_uri(ctx, s_slot_cert_id, &match_tok,
cert_id, &cert_id_len,
tmp_pin, &tmp_pin_len, &cert_label);
if (!n) {
ctx_log(ctx, 0,
"The certificate ID is not a valid PKCS#11 URI\n"
"The PKCS#11 URI format is defined by RFC7512\n");
ENGerr(ENG_F_CTX_LOAD_CERT, ENG_R_INVALID_ID);
goto error;
}
if (tmp_pin_len > 0 && tmp_pin[0] != 0) {
ctx_destroy_pin(ctx);
ctx->pin = OPENSSL_malloc(MAX_PIN_LENGTH+1);
if (ctx->pin) {
memset(ctx->pin, 0, MAX_PIN_LENGTH+1);
memcpy(ctx->pin, tmp_pin, tmp_pin_len);
ctx->pin_length = tmp_pin_len;
}
}
} else {
n = parse_slot_id_string(ctx, s_slot_cert_id, &slot_nr,
cert_id, &cert_id_len, &cert_label);
if (!n) {
ctx_log(ctx, 0,
"The certificate ID is not a valid PKCS#11 URI\n"
"The PKCS#11 URI format is defined by RFC7512\n"
"The legacy ENGINE_pkcs11 ID format is also "
"still accepted for now\n");
ENGerr(ENG_F_CTX_LOAD_CERT, ENG_R_INVALID_ID);
goto error;
}
}
ctx_log(ctx, 1, "Looking in slot %d for certificate: ",
slot_nr);
if (cert_id_len != 0) {
ctx_log(ctx, 1, "id=");
dump_hex(ctx, 1, cert_id, cert_id_len);
}
if (cert_id_len != 0 && cert_label)
ctx_log(ctx, 1, " ");
if (cert_label)
ctx_log(ctx, 1, "label=%s", cert_label);
ctx_log(ctx, 1, "\n");
}
matched_slots = (PKCS11_SLOT **)calloc(ctx->slot_count,
sizeof(PKCS11_SLOT *));
if (!matched_slots) {
ctx_log(ctx, 0, "Could not allocate memory for matched slots\n");
goto error;
}
for (n = 0; n < ctx->slot_count; n++) {
slot = ctx->slot_list + n;
flags[0] = '\0';
if (slot->token) {
if (!slot->token->initialized)
strcat(flags, "uninitialized, ");
else if (!slot->token->userPinSet)
strcat(flags, "no pin, ");
if (slot->token->loginRequired)
strcat(flags, "login, ");
if (slot->token->readOnly)
strcat(flags, "ro, ");
} else {
strcpy(flags, "no token");
}
if ((m = strlen(flags)) != 0) {
flags[m - 2] = '\0';
}
if (slot_nr != -1 &&
slot_nr == (int)PKCS11_get_slotid_from_slot(slot)) {
found_slot = slot;
}
if (match_tok && slot->token &&
(!match_tok->label ||
!strcmp(match_tok->label, slot->token->label)) &&
(!match_tok->manufacturer ||
!strcmp(match_tok->manufacturer, slot->token->manufacturer)) &&
(!match_tok->serialnr ||
!strcmp(match_tok->serialnr, slot->token->serialnr)) &&
(!match_tok->model ||
!strcmp(match_tok->model, slot->token->model))) {
found_slot = slot;
}
ctx_log(ctx, 1, "[%lu] %-25.25s %-16s",
PKCS11_get_slotid_from_slot(slot),
slot->description, flags);
if (slot->token) {
ctx_log(ctx, 1, " (%s)",
slot->token->label[0] ?
slot->token->label : "no label");
}
ctx_log(ctx, 1, "\n");
if (found_slot && found_slot->token && !found_slot->token->initialized)
ctx_log(ctx, 0, "Found uninitialized token\n");
/* Ignore slots without tokens or with uninitialized token */
if (found_slot && found_slot->token && found_slot->token->initialized) {
matched_slots[matched_count] = found_slot;
matched_count++;
}
found_slot = NULL;
}
if (matched_count == 0) {
if (match_tok) {
ctx_log(ctx, 0, "Specified object not found\n");
goto error;
}
/* If the legacy slot ID format was used */
if (slot_nr != -1) {
ctx_log(ctx, 0, "Invalid slot number: %d\n", slot_nr);
goto error;
} else {
found_slot = PKCS11_find_token(ctx->pkcs11_ctx,
ctx->slot_list, ctx->slot_count);
/* Ignore if the the token is not initialized */
if (found_slot && found_slot->token &&
found_slot->token->initialized) {
matched_slots[matched_count] = found_slot;
matched_count++;
} else {
ctx_log(ctx, 0, "No tokens found\n");
goto error;
}
}
}
for (n = 0; n < matched_count; n++) {
slot = matched_slots[n];
tok = slot->token;
if (!tok) {
ctx_log(ctx, 0, "Empty token found\n");
break;
}
ctx_log(ctx, 1, "Found slot: %s\n", slot->description);
ctx_log(ctx, 1, "Found token: %s\n", slot->token->label);
/* In several tokens certificates are marked as private */
if (login) {
/* Only try to login if login is required */
if (tok->loginRequired) {
/* Only try to login if a single slot matched to avoiding trying
* the PIN against all matching slots */
if (matched_count == 1) {
if (!ctx_login(ctx, slot, tok,
ctx->ui_method, ctx->callback_data)) {
ctx_log(ctx, 0, "Login to token failed, returning NULL...\n");
goto error;
}
} else {
ctx_log(ctx, 0, "Multiple matching slots (%lu); will not try to"
" login\n", matched_count);
for (m = 0; m < matched_count; m++){
slot = matched_slots[m];
ctx_log(ctx, 0, "[%u] %s: %s\n", m + 1,
slot->description? slot->description:
"(no description)",
(slot->token && slot->token->label)?
slot->token->label: "no label");
}
goto error;
}
}
}
if (PKCS11_enumerate_certs(tok, &certs, &cert_count)) {
ctx_log(ctx, 0, "Unable to enumerate certificates\n");
continue;
}
ctx_log(ctx, 1, "Found %u cert%s:\n", cert_count,
(cert_count <= 1) ? "" : "s");
if ((s_slot_cert_id && *s_slot_cert_id) &&
(cert_id_len != 0 || cert_label)) {
for (m = 0; m < cert_count; m++) {
PKCS11_CERT *k = certs + m;
if (cert_label && k->label && strcmp(k->label, cert_label) == 0)
selected_cert = k;
if (cert_id_len != 0 && k->id_len == cert_id_len &&
memcmp(k->id, cert_id, cert_id_len) == 0)
selected_cert = k;
}
} else {
for (m = 0; m < cert_count; m++) {
PKCS11_CERT *k = certs + m;
if (k->id && *(k->id)) {
selected_cert = k; /* Use the first certificate with nonempty id */
break;
}
}
if (!selected_cert)
selected_cert = certs; /* Use the first certificate */
}
if (selected_cert) {
break;
}
}
if (selected_cert) {
x509 = X509_dup(selected_cert->x509);
} else {
if (login) /* Only print the error on the second attempt */
ctx_log(ctx, 0, "Certificate not found.\n");
x509 = NULL;
}
error:
/* Free the searched token data */
if (match_tok) {
OPENSSL_free(match_tok->model);
OPENSSL_free(match_tok->manufacturer);
OPENSSL_free(match_tok->serialnr);
OPENSSL_free(match_tok->label);
OPENSSL_free(match_tok);
}
if (cert_label)
OPENSSL_free(cert_label);
if (matched_slots)
free(matched_slots);
return x509;
}
static int ctx_ctrl_load_cert(ENGINE_CTX *ctx, void *p)
{
struct {
const char *s_slot_cert_id;
X509 *cert;
} *parms = p;
if (!parms) {
ENGerr(ENG_F_CTX_CTRL_LOAD_CERT, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
if (parms->cert) {
ENGerr(ENG_F_CTX_CTRL_LOAD_CERT, ENG_R_INVALID_PARAMETER);
return 0;
}
ERR_clear_error();
if (!ctx->force_login)
parms->cert = ctx_load_cert(ctx, parms->s_slot_cert_id, 0);
if (!parms->cert) { /* Try again with login */
ERR_clear_error();
parms->cert = ctx_load_cert(ctx, parms->s_slot_cert_id, 1);
}
if (!parms->cert) {
if (!ERR_peek_last_error())
ENGerr(ENG_F_CTX_CTRL_LOAD_CERT, ENG_R_OBJECT_NOT_FOUND);
return 0;
}
return 1;
}
/******************************************************************************/
/* Private and public key handling */
/******************************************************************************/
static EVP_PKEY *ctx_load_key(ENGINE_CTX *ctx, const char *s_slot_key_id,
UI_METHOD *ui_method, void *callback_data,
const int isPrivate, const int login)
{
PKCS11_SLOT *slot;
PKCS11_SLOT *found_slot = NULL, **matched_slots = NULL;
PKCS11_TOKEN *tok, *match_tok = NULL;
PKCS11_KEY *keys, *selected_key = NULL;
EVP_PKEY *pk = NULL;
unsigned int key_count, n, m;
unsigned char key_id[MAX_VALUE_LEN / 2];
size_t key_id_len = sizeof(key_id);
char *key_label = NULL;
int slot_nr = -1;
char tmp_pin[MAX_PIN_LENGTH+1];
size_t tmp_pin_len = MAX_PIN_LENGTH;
char flags[64];
size_t matched_count = 0;
if (ctx_init_libp11(ctx)) /* Delayed libp11 initialization */
goto error;
ctx_log(ctx, 1, "Loading %s key \"%s\"\n",
(char *)(isPrivate ? "private" : "public"),
s_slot_key_id);
if (s_slot_key_id && *s_slot_key_id) {
if (!strncasecmp(s_slot_key_id, "pkcs11:", 7)) {
n = parse_pkcs11_uri(ctx, s_slot_key_id, &match_tok,
key_id, &key_id_len,
tmp_pin, &tmp_pin_len, &key_label);
if (!n) {
ctx_log(ctx, 0,
"The key ID is not a valid PKCS#11 URI\n"
"The PKCS#11 URI format is defined by RFC7512\n");
ENGerr(ENG_F_CTX_LOAD_KEY, ENG_R_INVALID_ID);
goto error;
}
if (tmp_pin_len > 0 && tmp_pin[0] != 0) {
/* If the searched key is public, try without login once even
* when the PIN is provided */
if (!login && isPrivate)
goto error; /* Process on second attempt */
ctx_destroy_pin(ctx);
ctx->pin = OPENSSL_malloc(MAX_PIN_LENGTH+1);
if (ctx->pin) {
memset(ctx->pin, 0, MAX_PIN_LENGTH+1);
memcpy(ctx->pin, tmp_pin, tmp_pin_len);
ctx->pin_length = tmp_pin_len;
}
}
} else {
n = parse_slot_id_string(ctx, s_slot_key_id, &slot_nr,
key_id, &key_id_len, &key_label);
if (!n) {
ctx_log(ctx, 0,
"The key ID is not a valid PKCS#11 URI\n"
"The PKCS#11 URI format is defined by RFC7512\n"
"The legacy ENGINE_pkcs11 ID format is also "
"still accepted for now\n");
ENGerr(ENG_F_CTX_LOAD_KEY, ENG_R_INVALID_ID);
goto error;
}
}
ctx_log(ctx, 1, "Looking in slot %d for key: ",
slot_nr);
if (key_id_len != 0) {
ctx_log(ctx, 1, "id=");
dump_hex(ctx, 1, key_id, key_id_len);
}
if (key_id_len != 0 && key_label)
ctx_log(ctx, 1, " ");
if (key_label)
ctx_log(ctx, 1, "label=%s", key_label);
ctx_log(ctx, 1, "\n");
}
matched_slots = (PKCS11_SLOT **)calloc(ctx->slot_count,
sizeof(PKCS11_SLOT *));
if (!matched_slots) {
ctx_log(ctx, 0, "Could not allocate memory for matched slots\n");
goto error;
}
for (n = 0; n < ctx->slot_count; n++) {
slot = ctx->slot_list + n;
flags[0] = '\0';
if (slot->token) {
if (!slot->token->initialized)
strcat(flags, "uninitialized, ");
else if (!slot->token->userPinSet)
strcat(flags, "no pin, ");
if (slot->token->loginRequired)
strcat(flags, "login, ");
if (slot->token->readOnly)
strcat(flags, "ro, ");
} else {
strcpy(flags, "no token");
}
if ((m = strlen(flags)) != 0) {
flags[m - 2] = '\0';
}
if (slot_nr != -1 &&
slot_nr == (int)PKCS11_get_slotid_from_slot(slot)) {
found_slot = slot;
}
if (match_tok && slot->token &&
(!match_tok->label ||
!strcmp(match_tok->label, slot->token->label)) &&
(!match_tok->manufacturer ||
!strcmp(match_tok->manufacturer, slot->token->manufacturer)) &&
(!match_tok->serialnr ||
!strcmp(match_tok->serialnr, slot->token->serialnr)) &&
(!match_tok->model ||
!strcmp(match_tok->model, slot->token->model))) {
found_slot = slot;
}
ctx_log(ctx, 1, "[%lu] %-25.25s %-16s",
PKCS11_get_slotid_from_slot(slot),
slot->description, flags);
if (slot->token) {
ctx_log(ctx, 1, " (%s)",
slot->token->label[0] ?
slot->token->label : "no label");
}
ctx_log(ctx, 1, "\n");
if (found_slot && found_slot->token && !found_slot->token->initialized)
ctx_log(ctx, 0, "Found uninitialized token\n");
/* Ignore slots without tokens or with uninitialized token */
if (found_slot && found_slot->token && found_slot->token->initialized) {
matched_slots[matched_count] = found_slot;
matched_count++;
}
found_slot = NULL;
}
if (matched_count == 0) {
if (match_tok) {
ctx_log(ctx, 0, "Specified object not found\n");
goto error;
}
/* If the legacy slot ID format was used */
if (slot_nr != -1) {
ctx_log(ctx, 0, "Invalid slot number: %d\n", slot_nr);
goto error;
} else {
found_slot = PKCS11_find_token(ctx->pkcs11_ctx,
ctx->slot_list, ctx->slot_count);
/* Ignore if the the token is not initialized */
if (found_slot && found_slot->token &&
found_slot->token->initialized) {
matched_slots[matched_count] = found_slot;
matched_count++;
} else {
ctx_log(ctx, 0, "No tokens found\n");
goto error;
}
}
}
for (n = 0; n < matched_count; n++) {
slot = matched_slots[n];
tok = slot->token;
if (!tok) {
ctx_log(ctx, 0, "Found empty token\n");
break;
}
ctx_log(ctx, 1, "Found slot: %s\n", slot->description);
ctx_log(ctx, 1, "Found token: %s\n", slot->token->label);
/* Both private and public keys can have the CKA_PRIVATE attribute
* set and thus require login (even to retrieve attributes!) */
if (login) {
/* Try to login only if login is required */
if (tok->loginRequired) {
/* Try to login only if a single slot matched to avoiding trying
* the PIN against all matching slots */
if (matched_count == 1) {
if (!ctx_login(ctx, slot, tok, ui_method, callback_data)) {
ctx_log(ctx, 0, "Login to token failed, returning NULL...\n");
goto error;
}
} else {
ctx_log(ctx, 0, "Multiple matching slots (%lu); will not try to"
" login\n", matched_count);
for (m = 0; m < matched_count; m++){
slot = matched_slots[m];
ctx_log(ctx, 1, "[%u] %s: %s\n", m + 1,
slot->description? slot->description:
"(no description)",
(slot->token && slot->token->label)?
slot->token->label: "no label");
}
goto error;
}
}
}
if (isPrivate) {
/* Make sure there is at least one private key on the token */
if (PKCS11_enumerate_keys(tok, &keys, &key_count)) {
ctx_log(ctx, 0, "Unable to enumerate private keys\n");
continue;
}
} else {
/* Make sure there is at least one public key on the token */
if (PKCS11_enumerate_public_keys(tok, &keys, &key_count)) {
ctx_log(ctx, 0, "Unable to enumerate public keys\n");
continue;
}
}
if (key_count == 0) {
if (login) /* Only print the error on the second attempt */
ctx_log(ctx, 0, "No %s keys found.\n",
(char *)(isPrivate ? "private" : "public"));
continue;
}
ctx_log(ctx, 1, "Found %u %s key%s:\n", key_count,
(char *)(isPrivate ? "private" : "public"),
(key_count == 1) ? "" : "s");
if (s_slot_key_id && *s_slot_key_id && (key_id_len != 0 || key_label)) {
for (m = 0; m < key_count; m++) {
PKCS11_KEY *k = keys + m;
ctx_log(ctx, 1, " %2u %c%c id=", m + 1,
k->isPrivate ? 'P' : ' ',
k->needLogin ? 'L' : ' ');
dump_hex(ctx, 1, k->id, k->id_len);
ctx_log(ctx, 1, " label=%s\n", k->label ? k->label : "(null)");
if (key_label && k->label && strcmp(k->label, key_label) == 0)
selected_key = k;
if (key_id_len != 0 && k->id_len == key_id_len
&& memcmp(k->id, key_id, key_id_len) == 0)
selected_key = k;
}
} else {
selected_key = keys; /* Use the first key */
}
if (selected_key) {
break;
}
}
if (selected_key) {
pk = isPrivate ?
PKCS11_get_private_key(selected_key) :
PKCS11_get_public_key(selected_key);
} else {
if (login) /* Only print the error on the second attempt */
ctx_log(ctx, 0, "Key not found.\n");
pk = NULL;
}
error:
/* Free the searched token data */
if (match_tok) {
OPENSSL_free(match_tok->model);
OPENSSL_free(match_tok->manufacturer);
OPENSSL_free(match_tok->serialnr);
OPENSSL_free(match_tok->label);
OPENSSL_free(match_tok);
}
if (key_label)
OPENSSL_free(key_label);
if (matched_slots)
free(matched_slots);
return pk;
}
EVP_PKEY *ctx_load_pubkey(ENGINE_CTX *ctx, const char *s_key_id,
UI_METHOD *ui_method, void *callback_data)
{
EVP_PKEY *pk = NULL;
ERR_clear_error();
if (!ctx->force_login)
pk = ctx_load_key(ctx, s_key_id, ui_method, callback_data, 0, 0);
if (!pk) { /* Try again with login */
ERR_clear_error();
pk = ctx_load_key(ctx, s_key_id, ui_method, callback_data, 0, 1);
}
if (!pk) {
ctx_log(ctx, 0, "PKCS11_load_public_key returned NULL\n");
if (!ERR_peek_last_error())
ENGerr(ENG_F_CTX_LOAD_PUBKEY, ENG_R_OBJECT_NOT_FOUND);
return NULL;
}
return pk;
}
EVP_PKEY *ctx_load_privkey(ENGINE_CTX *ctx, const char *s_key_id,
UI_METHOD *ui_method, void *callback_data)
{
EVP_PKEY *pk = NULL;
ERR_clear_error();
if (!ctx->force_login)
pk = ctx_load_key(ctx, s_key_id, ui_method, callback_data, 1, 0);
if (!pk) { /* Try again with login */
ERR_clear_error();
pk = ctx_load_key(ctx, s_key_id, ui_method, callback_data, 1, 1);
}
if (!pk) {
ctx_log(ctx, 0, "PKCS11_get_private_key returned NULL\n");
if (!ERR_peek_last_error())
ENGerr(ENG_F_CTX_LOAD_PRIVKEY, ENG_R_OBJECT_NOT_FOUND);
return NULL;
}
return pk;
}
/******************************************************************************/
/* Engine ctrl request handling */
/******************************************************************************/
static int ctx_ctrl_set_module(ENGINE_CTX *ctx, const char *modulename)
{
OPENSSL_free(ctx->module);
ctx->module = modulename ? OPENSSL_strdup(modulename) : NULL;
return 1;
}
/**
* Set the PIN used for login. A copy of the PIN shall be made.
*
* If the PIN cannot be assigned, the value 0 shall be returned
* and errno shall be set as follows:
*
* EINVAL - a NULL PIN was supplied
* ENOMEM - insufficient memory to copy the PIN
*
* @param pin the pin to use for login. Must not be NULL.