-
Notifications
You must be signed in to change notification settings - Fork 1
/
util_pkcs15.cpp
2334 lines (1863 loc) · 60.6 KB
/
util_pkcs15.cpp
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
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "config.h"
#include <openssl/opensslv.h>
#if OPENSSL_VERSION_NUMBER >= 0x00907000L
#include <openssl/conf.h>
#endif
#include <openssl/evp.h>
#include <openssl/pem.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#include <openssl/rsa.h>
#include <openssl/dsa.h>
#include <openssl/bn.h>
#include <openssl/pkcs12.h>
#include <openssl/x509v3.h>
#if OPENSSL_VERSION_NUMBER >= 0x10000000L
#include <openssl/opensslconf.h> /* for OPENSSL_NO_EC */
#ifndef OPENSSL_NO_EC
#include <openssl/ec.h>
#endif /* OPENSSL_NO_EC */
#endif /* OPENSSL_VERSION_NUMBER >= 0x10000000L */
#ifndef OPENSSL_NO_ENGINE
#include <openssl/engine.h>
#endif
#include "epToken/usbtoken.h"
#include "inc/token.h"
#include "inc/ep_pkcs15.h"
#include "inc/util_pkcs15.h"
#include "libopensc/asn1.h"
#include "engine_pkcs11.h"
#include "inc/ep_thread_ctx.h"
#ifdef REQUEST_EXTENSIONS
/* Add extension using V3 code: we can set the config file as NULL
* because we wont reference any other sections.
*/
static int
add_ext(STACK_OF(X509_EXTENSION) *sk, int nid, char *value)
{
X509_EXTENSION *ex;
ex = X509V3_EXT_conf_nid(NULL, NULL, nid, value);
if (!ex)
return 0;
sk_X509_EXTENSION_push(sk, ex);
return 1;
}
#endif
namespace util {
#ifndef OPENSSL_NO_ENGINE
/* Try to load an engine in a shareable library */
static ENGINE *try_load_engine(const char *sopath)
{
ENGINE *e = ENGINE_by_id("dynamic");
if (e)
{
if (!ENGINE_ctrl_cmd_string(e, "SO_PATH", sopath, 0)
|| !ENGINE_ctrl_cmd_string(e, "LIST_ADD", "1", 0)
|| !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0))
{
ENGINE_free(e);
e = NULL;
}
}
return e;
}
ENGINE *setup_engine(const char *id, const char *sopath, const char *modulepath, const char *pin, const char *args)
{
ENGINE *e;
ENGINE_load_builtin_engines();
if (id)
{
if((e = ENGINE_by_id(id)) == NULL
&& (e = try_load_engine(sopath)) == NULL)
{
fprintf(stderr, "invalid engine \"%s\"\n", id);
//ERR_print_errors(err);
return NULL;
}
if(!ENGINE_ctrl_cmd_string(e, "MODULE_PATH", modulepath, 0)
|| !ENGINE_ctrl_cmd_string(e, "PIN", pin, 0)
|| !ENGINE_ctrl_cmd_string(e, "INIT_ARGS", args, 0)) {
return NULL;
}
if(!ENGINE_init(e)) {
/* the engine couldn't initialise, release 'e' */
ENGINE_free(e);
return NULL;
}
// //ENGINE_ctrl_cmd(e, "SET_USER_INTERFACE", 0, ui_method, 0, 1);
// if(!ENGINE_set_default(e, ENGINE_METHOD_ALL))
// {
// printf("can't use that engine\n");
// //ERR_print_errors(err);
// ENGINE_free(e);
// return NULL;
// }
printf("engine \"%s\" set.\n", ENGINE_get_id(e));
/* Release the functional reference from ENGINE_init() */
ENGINE_finish(e);
/* Free our "structural" reference. */
ENGINE_free(e);
}
return e;
}
#endif
int ep_open_reader_and_card(struct sc_context **ctx, const char *reader, struct sc_card **card) {
int verbose = 1;
sc_context_param_t ctx_param;
memset(&ctx_param, 0, sizeof(ctx_param));
ctx_param.ver = 0;
ctx_param.app_name = E_TOKEN_APPLICATION_NAME;
ctx_param.thread_ctx = &sc_thread_ctx;
if (sc_context_create(ctx, &ctx_param))
return 0;
if (verbose > 1) {
(*ctx)->debug = verbose;
sc_ctx_log_to_file(*ctx, "log.txt");
}
return ::util_connect_card(*ctx, card, reader, 0, verbose) ? 0 : 1;
}
int ep_pkcs15_bind_card(struct sc_card *card, struct sc_pkcs15_card **p15card, struct sc_profile *profile) {
int r;
if (r = sc_pkcs15_bind(card, NULL, p15card))
return r;
/* XXX: should compare card to profile here to make
* sure we're not messing things up */
sc_pkcs15init_set_p15card(profile, *p15card);
return SC_SUCCESS;
}
void ep_refresh_pin_info(struct sc_card *card, struct sc_pkcs15_auth_info *pin) {
struct sc_pin_cmd_data data;
/* Try to update PIN info from card */
memset(&data, 0, sizeof(data));
data.cmd = SC_PIN_CMD_GET_INFO;
data.pin_type = SC_AC_CHV;
data.pin_reference = pin->attrs.pin.reference;
if (sc_pin_cmd(card, &data, NULL) == SC_SUCCESS) {
if (data.pin1.max_tries > 0)
pin->max_tries = data.pin1.max_tries;
/* tries_left must be supported or sc_pin_cmd should not return SC_SUCCESS */
pin->tries_left = data.pin1.tries_left;
}
}
int ep_has_onepin(sc_profile *profile) {
sc_pkcs15_auth_info_t sopin_info;
sc_pkcs15init_get_pin_info(profile, SC_PKCS15INIT_SO_PIN, &sopin_info);
return sopin_info.attrs.pin.flags & SC_PKCS15_PIN_FLAG_SO_PIN ? 0 : 1;
}
sc_pkcs15_object *get_pin_info(struct sc_pkcs15_card *p15card) {
struct sc_pkcs15_object *objs[32];
int ii, r;
r = sc_pkcs15_get_objects(p15card, SC_PKCS15_TYPE_AUTH_PIN, objs, 32);
if (r < 0) {
//util_debug("PIN code enumeration failed: %s\n", sc_strerror(r));
return NULL;
}
if (r == 0) {
//util_debug("No PIN codes found.\n");
return NULL;
}
for (ii = 0; ii < r; ii++) {
struct sc_pkcs15_auth_info *pin_info = (struct sc_pkcs15_auth_info *) objs[ii]->data;
//if (pin_info->auth_type != SC_PKCS15_PIN_AUTH_TYPE_PIN) continue;
//if (pin_info->attrs.pin.flags & SC_PKCS15_PIN_FLAG_SO_PIN) continue; /* #TODO: Is this right? */
//if (pin_info->attrs.pin.flags & SC_PKCS15_PIN_FLAG_UNBLOCKING_PIN) continue;
return objs[ii];
}
return NULL;
}
int ep_authenticate_object(struct sc_pkcs15_card *p15card, sc_pkcs15_object_t *obj, const u8 *pin) {
sc_pkcs15_object_t *pin_obj;
int r;
if (obj->auth_id.len == 0)
return SC_SUCCESS;
r = sc_pkcs15_find_pin_by_auth_id(p15card, &obj->auth_id, &pin_obj);
return r != SC_SUCCESS ? r : sc_pkcs15_verify_pin(p15card, pin_obj, pin, pin? strlen((char *) pin) : 0);
}
/* Verify pin */
int ep_verify_pin(struct sc_pkcs15_card *p15card, const char *pin) {
struct sc_pkcs15_object *pin_obj;
int r;
if ((pin_obj = ::util::get_pin_info(p15card)) == NULL)
return -1;
r = sc_pkcs15_verify_pin(p15card, pin_obj, (const u8 *) pin, pin? strlen(pin) : 0);
return r;
}
EVP_PKEY *ep_load_pubkey(void *data, size_t len, int format)
{
BIO *key=NULL;
EVP_PKEY *pkey=NULL;
key=BIO_new_mem_buf(data, len);
if (key == NULL)
{
//ERR_print_errors(err);
goto end;
}
if (format == FORMAT_ASN1)
{
pkey=d2i_PUBKEY_bio(key, NULL);
}
#ifndef OPENSSL_NO_RSA
else if (format == FORMAT_ASN1RSA)
{
RSA *rsa;
rsa = d2i_RSAPublicKey_bio(key, NULL);
if (rsa)
{
pkey = EVP_PKEY_new();
if (pkey)
EVP_PKEY_set1_RSA(pkey, rsa);
RSA_free(rsa);
}
else
pkey = NULL;
}
else if (format == FORMAT_PEMRSA)
{
RSA *rsa;
rsa = PEM_read_bio_RSAPublicKey(key, NULL,
NULL, NULL);
if (rsa)
{
pkey = EVP_PKEY_new();
if (pkey)
EVP_PKEY_set1_RSA(pkey, rsa);
RSA_free(rsa);
}
else
pkey = NULL;
}
#endif
else if (format == FORMAT_PEM)
{
pkey=PEM_read_bio_PUBKEY(key,NULL,
NULL, NULL);
}
#if !defined(OPENSSL_NO_RC4) && !defined(OPENSSL_NO_RSA)
else if (format == FORMAT_NETSCAPE || format == FORMAT_IISSGC)
pkey = load_netscape_key(key, format);
#endif
#if !defined(OPENSSL_NO_RSA) && !defined(OPENSSL_NO_DSA)
else if (format == FORMAT_MSBLOB)
pkey = b2i_PublicKey_bio(key);
#endif
else
{
//BIO_printf(err,"bad input format specified for key file\n");
goto end;
}
end:
if (key != NULL) BIO_free(key);
//if (pkey == NULL)
//BIO_printf(err,"unable to load %s\n", key_descrip);
return(pkey);
}
#if !defined(OPENSSL_NO_RC4) && !defined(OPENSSL_NO_RSA)
static EVP_PKEY *
load_netscape_key(BIO *key, int format)
{
EVP_PKEY *pkey;
BUF_MEM *buf;
RSA *rsa;
const unsigned char *p;
int size, i;
buf=BUF_MEM_new();
pkey = EVP_PKEY_new();
size = 0;
if (buf == NULL || pkey == NULL)
goto error;
for (;;)
{
if (!BUF_MEM_grow_clean(buf,size+1024*10))
goto error;
i = BIO_read(key, &(buf->data[size]), 1024*10);
size += i;
if (i == 0)
break;
if (i < 0)
{
//BIO_printf(err, "Error reading %s %s",
//key_descrip, file);
goto error;
}
}
p=(unsigned char *)buf->data;
rsa = d2i_RSA_NET(NULL,&p,(long)size,NULL,
(format == FORMAT_IISSGC ? 1 : 0));
if (rsa == NULL)
goto error;
BUF_MEM_free(buf);
EVP_PKEY_set1_RSA(pkey, rsa);
return pkey;
error:
BUF_MEM_free(buf);
EVP_PKEY_free(pkey);
return NULL;
}
#endif /* ndef OPENSSL_NO_RC4 */
static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *subj, int multirdn,
unsigned long chtype)
{
int ret=0,i;
/* setup version number */
if (!X509_REQ_set_version(req,0L)) goto err; /* version 1 */
i = build_subject(req, subj, chtype, multirdn);
if(!i) goto err;
if (!X509_REQ_set_pubkey(req,pkey)) goto err;
ret=1;
err:
return(ret);
}
static int
pkey_ctrl_string(EVP_PKEY_CTX *ctx, char *value)
{
int rv;
char *stmp, *vtmp = NULL;
stmp = BUF_strdup(value);
if (!stmp)
return -1;
vtmp = strchr(stmp, ':');
if (vtmp)
{
*vtmp = 0;
vtmp++;
}
rv = EVP_PKEY_CTX_ctrl_str(ctx, stmp, vtmp);
OPENSSL_free(stmp);
return rv;
}
static int
do_sign_init(EVP_MD_CTX *ctx, EVP_PKEY *pkey,
const EVP_MD *md, STACK_OF(OPENSSL_STRING) *sigopts)
{
EVP_PKEY_CTX *pkctx = NULL;
int i;
EVP_MD_CTX_init(ctx);
if (!EVP_DigestSignInit(ctx, &pkctx, md, NULL, pkey))
return 0;
for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++)
{
char *sigopt = sk_OPENSSL_STRING_value(sigopts, i);
if (pkey_ctrl_string(pkctx, sigopt) <= 0)
{
//BIO_printf(err, "parameter error \"%s\"\n", sigopt);
//ERR_print_errors(bio_err);
return 0;
}
}
return 1;
}
int do_X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const EVP_MD *md,
STACK_OF(OPENSSL_STRING) *sigopts)
{
int rv;
EVP_MD_CTX mctx;
EVP_MD_CTX_init(&mctx);
rv = do_sign_init(&mctx, pkey, md, sigopts);
if (rv > 0)
rv = X509_REQ_sign_ctx(x, &mctx);
EVP_MD_CTX_cleanup(&mctx);
return rv > 0 ? 1 : 0;
}
/*
* subject is expected to be in the format /type0=value0/type1=value1/type2=...
* where characters may be escaped by \
*/
static int build_subject(X509_REQ *req, char *subject, unsigned long chtype, int multirdn)
{
X509_NAME *n;
if (!(n = parse_name(subject, chtype, multirdn)))
return 0;
if (!X509_REQ_set_subject_name(req, n))
{
X509_NAME_free(n);
return 0;
}
X509_NAME_free(n);
return 1;
}
/*
* subject is expected to be in the format /type0=value0/type1=value1/type2=...
* where characters may be escaped by \
*/
static X509_NAME *parse_name(char *subject, long chtype, int multirdn)
{
size_t buflen = strlen(subject)+1; /* to copy the types and values into. due to escaping, the copy can only become shorter */
char *buf = (char *)OPENSSL_malloc(buflen);
size_t max_ne = buflen / 2 + 1; /* maximum number of name elements */
char **ne_types = (char **)OPENSSL_malloc(max_ne * sizeof (char *));
char **ne_values = (char **)OPENSSL_malloc(max_ne * sizeof (char *));
int *mval = (int *)OPENSSL_malloc (max_ne * sizeof (int));
char *sp = subject, *bp = buf;
int i, ne_num = 0;
X509_NAME *n = NULL;
int nid;
if (!buf || !ne_types || !ne_values)
{
//BIO_printf(bio_err, "malloc error\n");
goto error;
}
if (*subject != '/')
{
//BIO_printf(bio_err, "Subject does not start with '/'.\n");
goto error;
}
sp++; /* skip leading / */
/* no multivalued RDN by default */
mval[ne_num] = 0;
while (*sp)
{
/* collect type */
ne_types[ne_num] = bp;
while (*sp)
{
if (*sp == '\\') /* is there anything to escape in the type...? */
{
if (*++sp)
*bp++ = *sp++;
else
{
//BIO_printf(bio_err, "escape character at end of string\n");
goto error;
}
}
else if (*sp == '=')
{
sp++;
*bp++ = '\0';
break;
}
else
*bp++ = *sp++;
}
if (!*sp)
{
//BIO_printf(bio_err, "end of string encountered while processing type of subject name element #%d\n", ne_num);
goto error;
}
ne_values[ne_num] = bp;
while (*sp)
{
if (*sp == '\\')
{
if (*++sp)
*bp++ = *sp++;
else
{
//BIO_printf(bio_err, "escape character at end of string\n");
goto error;
}
}
else if (*sp == '/')
{
sp++;
/* no multivalued RDN by default */
mval[ne_num+1] = 0;
break;
}
else if (*sp == '+' && multirdn)
{
/* a not escaped + signals a mutlivalued RDN */
sp++;
mval[ne_num+1] = -1;
break;
}
else
*bp++ = *sp++;
}
*bp++ = '\0';
ne_num++;
}
if (!(n = X509_NAME_new()))
goto error;
for (i = 0; i < ne_num; i++)
{
if ((nid=OBJ_txt2nid(ne_types[i])) == NID_undef)
{
//BIO_printf(bio_err, "Subject Attribute %s has no known NID, skipped\n", ne_types[i]);
continue;
}
if (!*ne_values[i])
{
//BIO_printf(bio_err, "No value provided for Subject Attribute %s, skipped\n", ne_types[i]);
continue;
}
if (!X509_NAME_add_entry_by_NID(n, nid, chtype, (unsigned char*)ne_values[i], -1,-1,mval[i]))
goto error;
}
OPENSSL_free(ne_values);
OPENSSL_free(ne_types);
OPENSSL_free(buf);
return n;
error:
X509_NAME_free(n);
if (ne_values)
OPENSSL_free(ne_values);
if (ne_types)
OPENSSL_free(ne_types);
if (buf)
OPENSSL_free(buf);
return NULL;
}
std::string Format(char *fmt, ...) {
int size = 100;
std::string str;
va_list ap;
for(;;) {
str.resize(size);
va_start(ap, fmt);
int n = vsnprintf((char *)str.c_str(), size, fmt, ap);
va_end(ap);
if (n > -1 && n < size) {
str.resize(n);
return str;
}
if (n > -1)
size=n+1;
else
size*=2;
}
}
int ep_gen_x509_req(CefRefPtr<epsilon::TokenContext> ctx, CefRefPtr<ClientHandler> handler, const char *id, const unsigned char *cn, const unsigned char *o,
const unsigned char *ou, const unsigned char *city, const unsigned char *region, const unsigned char *country, const unsigned char *emailAddress, const char *authData) {
struct sc_pkcs15_card *p15card;
struct sc_pkcs15_object *obj;
struct sc_pkcs15_pubkey *pubkey = NULL;
struct sc_pkcs15_cert *cert = NULL;
struct sc_pkcs15_id kid;
int r = -1, i;
ENGINE *e = NULL;
X509_REQ *x = NULL;
EVP_PKEY *pk = NULL;
STACK_OF(X509_EXTENSION) *exts = NULL;
FILE *fp = NULL;
std::string path, defaultFileName;
u8 *out;
if((p15card = epsilon::BindP15Card(ctx)) == NULL)
return r;
if(ep_verify_pin(p15card, authData) < 0)
goto out;
memset(&kid, 0, sizeof(kid));
memset(kid.value, 0, sizeof(kid.value));
sc_pkcs15_format_id(id, &kid);
i = sc_pkcs15_find_pubkey_by_id(p15card, &kid, &obj);
if (i >= 0) {
//if (verbose)
//printf("Reading public key with ID '%s'\n", opt_pubkey);
i = ep_authenticate_object(p15card, obj, (const u8 *)authData);
if (i >= 0)
i = sc_pkcs15_read_pubkey(p15card, obj, &pubkey);
} else if (i == SC_ERROR_OBJECT_NOT_FOUND) {
/* No pubkey - try if there's a certificate */
i = sc_pkcs15_find_cert_by_id(p15card, &kid, &obj);
if (i >= 0) {
//if (verbose)
//printf("Reading certificate with ID '%s'\n", opt_pubkey);
i = sc_pkcs15_read_certificate(p15card, (struct sc_pkcs15_cert_info *)obj->data, &cert);
}
if (i >= 0)
pubkey = cert->key;
}
if(i < 0)
goto out;
void *p = pubkey->data.value;
if((pk=ep_load_pubkey(p, pubkey->data.len, FORMAT_ASN1RSA)) == NULL)
goto end;
if ((x=X509_REQ_new()) == NULL)
{
goto end;
}
if (!make_REQ(x, pk, (char *)Format("/CN=%s/O=%s/OU=%s/L=%s/ST=%s/C=%s/emailAddress=%s/", cn, o, ou, city, region, country, emailAddress).c_str()))
{
//BIO_printf(bio_err,"problems making Certificate Request\n");
goto end;
}
#ifdef REQUEST_EXTENSIONS
/* Certificate requests can contain extensions, which can be used
* to indicate the extensions the requestor would like added to
* their certificate. CAs might ignore them however or even choke
* if they are present.
*/
/* For request extensions they are all packed in a single attribute.
* We save them in a STACK and add them all at once later...
*/
exts = sk_X509_EXTENSION_new_null();
/* Standard extenions */
add_ext(exts, NID_key_usage, "critical,digitalSignature,keyEncipherment");
/* This is a typical use for request extensions: requesting a value for
* subject alternative name.
*/
add_ext(exts, NID_subject_alt_name, (char *)Format("email:%s", emailAddress).c_str());
/* Some Netscape specific extensions */
add_ext(exts, NID_netscape_cert_type, "client,email");
//#ifdef CUSTOM_EXT
// /* Maybe even add our own extension based on existing */
// {
// int nid;
// nid = OBJ_create("1.2.3.4", "MyAlias", "My Test Alias Extension");
// X509V3_EXT_add_alias(nid, NID_netscape_comment);
// add_ext(x, nid, "example comment alias");
// }
//#endif
/* Now we've created the extensions we add them to the request */
X509_REQ_add_extensions(x, exts);
sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
#endif
e = setup_engine(
"pkcs11",
".\\engine_pkcs11.dll",
".\\opensc-pkcs11.dll", authData, NULL
);
const char *iid = ENGINE_get_id(e);
printf("%d", iid);
if(sc_pkcs15_find_prkey_by_id(p15card, &kid, &obj) == 0) {
u8 *x509_req = NULL;
int size;
if((size = i2d_X509_REQ(x, &x509_req)) < 0)
goto end;
x509_req[size] = 0;
/* This has to be done on the key */
out = (u8 *)malloc(size);
// if(ep_sign(p15card, obj, x509_req, size, SC_ALGORITHM_RSA_HASH_SHA1|SC_ALGORITHM_RSA_PAD_PKCS1, out) == 0) {
defaultFileName = Format("%s.csr", obj->label);
path = handler->GetDownloadPath(defaultFileName);
if (path.empty()) {
//Save to My Documents
path = defaultFileName;
}
fp = fopen(path.c_str(), "w");
if(!fp)
goto end;
if(!PEM_write_X509_REQ_NEW(fp, x))
goto end;
r = 0;
// }
}
end:
if(e)
e = NULL;
if(out)
free(out);
if(fp)
fclose(fp);
if(x)
X509_REQ_free(x);
if(pk)
EVP_PKEY_free(pk);
out :
if(pubkey)
sc_pkcs15_free_pubkey(pubkey);
epsilon::ReleaseP15Card(p15card);
return e == NULL && r;
}
int ep_export_x509_certificate(CefRefPtr<epsilon::TokenContext> ctx, CefRefPtr<ClientHandler> handler, const char *path, const char *id, const char *authData, unsigned int format) {
struct sc_pkcs15_card *p15card;
struct sc_pkcs15_object *obj;
struct sc_pkcs15_cert *cert = NULL;
struct sc_pkcs15_id kid;
int r = -1;
std::string defaultFileName = Format("%s.%s", path, format == FORMAT_ASN1 ? "der" : "crt"), mypath;
FILE *fp;
X509 *x509;
if((p15card = epsilon::BindP15Card(ctx)) == NULL)
return r;
if((r = ep_verify_pin(p15card, authData)) < 0)
goto out;
memset(&kid, 0, sizeof(kid));
memset(kid.value, 0, sizeof(kid.value));
sc_pkcs15_format_id(id, &kid);
r = sc_pkcs15_find_cert_by_id(p15card, &kid, &obj);
if (r >= 0) {
//if (verbose)
//printf("Reading certificate with ID '%s'\n", opt_pubkey);
r = sc_pkcs15_read_certificate(p15card, (struct sc_pkcs15_cert_info *)obj->data, &cert);
}
if(r >= 0) {
r = -1;
if((x509 = d2i_X509(NULL, (const u8 **)&cert->data, cert->data_len)) == NULL)
goto out;
/* Select a sensible label based on subject's name */
//defaultFileName = Format("%s.%s", obj->label, format == FORMAT_ASN1 ? "der" : "crt");
mypath = handler->GetDownloadPath(defaultFileName);
if (mypath.empty())
mypath = defaultFileName;
fp = fopen(mypath.c_str(), "w");
if(!fp)
goto out;
switch(format) {
case FORMAT_ASN1:
if(!i2d_X509_fp(fp,x509))
goto out;
break;
default:
if(!PEM_write_X509(fp, x509))
goto out;
break;
}
r = 0;
}
out :
if(fp)
fclose(fp);
if(x509)
X509_free(x509);
epsilon::ReleaseP15Card(p15card);
return r;
}
/* Key management functions */
static int
print_pem_object(unsigned char **buf, const u8 *data, size_t data_len) {
size_t buf_len = 1024;
int r;
/* With base64, every 3 bytes yield 4 characters, and with
* 64 chars per line we know almost exactly how large a buffer we
* will need. */
buf_len = (data_len + 2) / 3 * 4;
buf_len += 2 * (buf_len / 64 + 2); /* certain platforms use CRLF */
buf_len += 64; /* slack for checksum etc */
if (!(*buf = (u8 *)malloc(buf_len))) {
perror("print_pem_object");
return 1;
}
r = sc_base64_encode(data, data_len, *buf, buf_len, 64);
if (r < 0) {
fprintf(stderr, "Base64 encoding failed: %s\n", sc_strerror(r));
free(buf);
return r;
}
/*if (opt_outfile != NULL) {
outf = fopen(opt_outfile, "w");
if (outf == NULL) {
fprintf(stderr, "Error opening file '%s': %s\n",
opt_outfile, strerror(errno));
free(buf);
return 2;
}
} else
fprintf(stdout,
"-----BEGIN %s-----\n"
"%s"
"-----END %s-----\n",
kind, buf, kind);
if (outf != stdout)
fclose(outf);
free(buf);*/
return buf_len;
}
int ep_delete_prkey(CefRefPtr<epsilon::TokenContext> ctx, const char *id, const char *authData) {
struct sc_pkcs15_card *p15card;
struct sc_pkcs15_object *obj;
struct sc_pkcs15_id kid;
int r;
if((p15card = epsilon::BindP15Card(ctx)) == NULL)
return 0;
if((r = ep_verify_pin(p15card, authData)) < 0)
goto out;
memset(&kid, 0, sizeof(kid));
memset(kid.value, 0, sizeof(kid.value));
sc_pkcs15_format_id(id, &kid);
if ((r = sc_pkcs15_find_prkey_by_id(p15card, &kid, &obj)) != 0)
goto out;
r = sc_pkcs15init_delete_object(p15card, ctx->GetProfile(), obj);
if(r >= 0 && sc_pkcs15_find_pubkey_by_id(p15card, &kid, &obj) == 0)
r = sc_pkcs15init_delete_object(p15card, ctx->GetProfile(), obj);
out : epsilon::ReleaseP15Card(p15card);
return r;
}
int ep_delete_x509_certificate(CefRefPtr<epsilon::TokenContext> ctx, const char *id, const char *authData) {
struct sc_pkcs15_card *p15card;
struct sc_pkcs15_object *obj;
struct sc_pkcs15_id kid;
int r;
if((p15card = epsilon::BindP15Card(ctx)) == NULL)
return 0;
if((r = ep_verify_pin(p15card, authData)) < 0)
goto out;
memset(&kid, 0, sizeof(kid));
memset(kid.value, 0, sizeof(kid.value));
sc_pkcs15_format_id(id, &kid);
if ((r = sc_pkcs15_find_cert_by_id(p15card, &kid, &obj)) != 0)
goto out;
r = sc_pkcs15init_delete_object(p15card, ctx->GetProfile(), obj);
out : epsilon::ReleaseP15Card(p15card);
return r;
}
/*
* Generate a new private key
*/
int ep_generate_key(CefRefPtr<epsilon::TokenContext> ctx,
const char *spec, const char *pubkey_label, char **id, char *authid, const char *authData, int x509_usage) {
struct sc_pkcs15init_keygen_args keygen_args;
struct sc_pkcs15_card *p15card;
struct sc_pkcs15_object *obj;
unsigned int keybits = 1024;
int r;
if((p15card = epsilon::BindP15Card(ctx)) == NULL)
return 0;
if((r = ep_verify_pin(p15card, authData)) < 0)
goto out;
memset(&keygen_args, 0, sizeof(keygen_args));
keygen_args.pubkey_label = pubkey_label;
if ((r = init_keyargs(&keygen_args.prkey_args, NULL, authid, pubkey_label, x509_usage)) < 0)
goto out;