-
Notifications
You must be signed in to change notification settings - Fork 718
/
pkcs15-init.c
3223 lines (2826 loc) · 82.1 KB
/
pkcs15-init.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
/*
* Initialize Cards according to PKCS#15.
*
* This is a fill in the blanks sort of exercise. You need a
* profile that describes characteristics of your card, and the
* application specific layout on the card. This program will
* set up the card according to this specification (including
* PIN initialization etc) and create the corresponding PKCS15
* structure.
*
* There are a very few tasks that are too card specific to have
* a generic implementation; that is how PINs and keys are stored
* on the card. These should be implemented in pkcs15-<cardname>.c
*
* Copyright (C) 2002, Olaf Kirch <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "config.h"
#include <stdio.h>
#include <ctype.h>
#include <stdarg.h>
#include <assert.h>
#ifdef HAVE_STRING_H
#include <string.h>
#endif
#include <openssl/opensslv.h>
#include "libopensc/sc-ossl-compat.h"
#include <openssl/conf.h>
#include <openssl/evp.h>
#include <openssl/pem.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#include <openssl/rsa.h>
#include <openssl/bn.h>
#include <openssl/pkcs12.h>
#include <openssl/x509v3.h>
#include <openssl/crypto.h>
#include <openssl/opensslconf.h> /* for OPENSSL_NO_EC */
#if OPENSSL_VERSION_NUMBER >= 0x30000000L
# include <openssl/core_names.h>
# include <openssl/param_build.h>
#endif
#ifndef OPENSSL_NO_EC
#include <openssl/ec.h>
#endif /* OPENSSL_NO_EC */
#include "common/compat_strlcpy.h"
#include "libopensc/internal.h"
#include "libopensc/cardctl.h"
#include "libopensc/pkcs15.h"
#include "libopensc/log.h"
#include "libopensc/cards.h"
#include "libopensc/asn1.h"
#include "pkcs15init/pkcs15-init.h"
#include "pkcs15init/profile.h"
#include "util.h"
#undef GET_KEY_ECHO_OFF
static const char *app_name = "pkcs15-init";
/* Handle encoding of PKCS15 on the card */
typedef int (*pkcs15_encoder)(sc_context_t *,
struct sc_pkcs15_card *, u8 **, size_t *);
/* Local functions */
static int open_reader_and_card(char *);
static int do_assert_pristine(sc_card_t *);
static int do_erase(sc_card_t *, struct sc_profile *);
static int do_erase_application(sc_card_t *, struct sc_profile *);
static int do_delete_objects(struct sc_profile *, unsigned int myopt_delete_flags);
static int do_change_attributes(struct sc_profile *, unsigned int myopt_type);
static int do_init_app(struct sc_profile *);
static int do_store_pin(struct sc_profile *);
static int do_generate_key(struct sc_profile *, const char *);
static int do_generate_skey(struct sc_profile *, const char *);
static int do_store_private_key(struct sc_profile *);
static int do_store_public_key(struct sc_profile *, EVP_PKEY *);
static int do_store_secret_key(struct sc_profile *);
static int do_store_certificate(struct sc_profile *);
static int do_update_certificate(struct sc_profile *);
static int do_convert_cert(sc_pkcs15_der_t *, X509 *);
static int is_cacert_already_present(struct sc_pkcs15init_certargs *);
static int do_finalize_card(sc_card_t *, struct sc_profile *);
static int do_read_data_object(const char *name, u8 **out, size_t *outlen, size_t expected);
static int do_store_data_object(struct sc_profile *profile);
static int do_sanity_check(struct sc_profile *profile);
static int init_prkeyargs(struct sc_pkcs15init_prkeyargs *);
static int init_skeyargs(struct sc_pkcs15init_skeyargs *);
static void init_gost_params(struct sc_pkcs15init_keyarg_gost_params *, EVP_PKEY *);
static int get_pin_callback(struct sc_profile *profile,
int id, const struct sc_pkcs15_auth_info *info,
const char *label,
u8 *pinbuf, size_t *pinsize);
static int get_key_callback(struct sc_profile *,
int method, int reference,
const u8 *, size_t, u8 *, size_t *);
static int do_read_private_key(const char *, const char *, EVP_PKEY **, X509 **, unsigned int);
static int do_read_public_key(const char *, const char *, EVP_PKEY **);
static int do_read_certificate(const char *, const char *, X509 **);
static char * cert_common_name(X509 *x509);
static void parse_commandline(int argc, char **argv);
static int verify_pin(struct sc_pkcs15_card *, char *);
enum {
OPT_PASSPHRASE = 0x100,
OPT_PUBKEY,
OPT_SECRKEY,
OPT_EXTRACTABLE,
OPT_INSECURE,
OPT_AUTHORITY,
OPT_ASSERT_PRISTINE,
OPT_SECRET,
OPT_SECRKEY_ALGO,
OPT_PUBKEY_LABEL,
OPT_CERT_LABEL,
OPT_APPLICATION_NAME,
OPT_APPLICATION_ID,
OPT_PUK_ID,
OPT_PUK_LABEL,
OPT_VERIFY_PIN,
OPT_SANITY_CHECK,
OPT_BIND_TO_AID,
OPT_UPDATE_LAST_UPDATE,
OPT_ERASE_APPLICATION,
OPT_IGNORE_CA_CERTIFICATES,
OPT_UPDATE_EXISTING,
OPT_MD_CONTAINER_GUID,
OPT_VERSION,
OPT_USER_CONSENT,
OPT_PIN1 = 0x10000, /* don't touch these values */
OPT_PUK1 = 0x10001,
OPT_PIN2 = 0x10002,
OPT_PUK2 = 0x10003,
OPT_SERIAL = 0x10004,
OPT_NO_SOPIN = 0x10005,
OPT_USE_PINPAD= 0x10006,
OPT_USE_PINPAD_DEPRECATED
};
const struct option options[] = {
{ "version", 0, NULL, OPT_VERSION },
{ "erase-card", no_argument, NULL, 'E' },
{ "create-pkcs15", no_argument, NULL, 'C' },
{ "store-pin", no_argument, NULL, 'P' },
{ "generate-key", required_argument, NULL, 'G' },
{ "store-private-key", required_argument, NULL, 'S' },
{ "store-public-key", required_argument, NULL, OPT_PUBKEY },
{ "store-secret-key", required_argument, NULL, OPT_SECRKEY },
{ "store-certificate", required_argument, NULL, 'X' },
{ "update-certificate", required_argument, NULL, 'U' },
{ "store-data", required_argument, NULL, 'W' },
{ "delete-objects", required_argument, NULL, 'D' },
{ "change-attributes", required_argument, NULL, 'A' },
{ "sanity-check", no_argument, NULL, OPT_SANITY_CHECK},
{ "erase-application", required_argument, NULL, OPT_ERASE_APPLICATION},
{ "reader", required_argument, NULL, 'r' },
{ "pin", required_argument, NULL, OPT_PIN1 },
{ "puk", required_argument, NULL, OPT_PUK1 },
{ "so-pin", required_argument, NULL, OPT_PIN2 },
{ "so-puk", required_argument, NULL, OPT_PUK2 },
{ "no-so-pin", no_argument, NULL, OPT_NO_SOPIN },
{ "serial", required_argument, NULL, OPT_SERIAL },
{ "auth-id", required_argument, NULL, 'a' },
{ "puk-id", required_argument, NULL, OPT_PUK_ID },
{ "verify-pin", no_argument, NULL, OPT_VERIFY_PIN },
{ "id", required_argument, NULL, 'i' },
{ "label", required_argument, NULL, 'l' },
{ "puk-label", required_argument, NULL, OPT_PUK_LABEL },
{ "secret-key-algorithm", required_argument, NULL, OPT_SECRKEY_ALGO },
{ "public-key-label", required_argument, NULL, OPT_PUBKEY_LABEL },
{ "cert-label", required_argument, NULL, OPT_CERT_LABEL },
{ "application-name", required_argument, NULL, OPT_APPLICATION_NAME },
{ "application-id", required_argument, NULL, OPT_APPLICATION_ID },
{ "aid", required_argument, NULL, OPT_BIND_TO_AID },
{ "output-file", required_argument, NULL, 'o' },
{ "format", required_argument, NULL, 'f' },
{ "passphrase", required_argument, NULL, OPT_PASSPHRASE },
{ "authority", no_argument, NULL, OPT_AUTHORITY },
{ "key-usage", required_argument, NULL, 'u' },
{ "finalize", no_argument, NULL, 'F' },
{ "update-last-update", no_argument, NULL, OPT_UPDATE_LAST_UPDATE},
{ "ignore-ca-certificates",no_argument, NULL, OPT_IGNORE_CA_CERTIFICATES},
{ "update-existing", no_argument, NULL, OPT_UPDATE_EXISTING},
{ "extractable", no_argument, NULL, OPT_EXTRACTABLE },
{ "user-consent", required_argument, NULL, OPT_USER_CONSENT},
{ "insecure", no_argument, NULL, OPT_INSECURE },
{ "use-default-transport-keys",
no_argument, NULL, 'T' },
{ "use-pinpad", no_argument, NULL, OPT_USE_PINPAD },
{ "no-prompt", no_argument, NULL, OPT_USE_PINPAD_DEPRECATED },
{ "profile", required_argument, NULL, 'p' },
{ "card-profile", required_argument, NULL, 'c' },
{ "md-container-guid", required_argument, NULL, OPT_MD_CONTAINER_GUID},
{ "wait", no_argument, NULL, 'w' },
{ "help", no_argument, NULL, 'h' },
{ "verbose", no_argument, NULL, 'v' },
/* Hidden options for testing */
{ "assert-pristine", no_argument, NULL, OPT_ASSERT_PRISTINE },
{ "secret", required_argument, NULL, OPT_SECRET },
{ NULL, 0, NULL, 0 }
};
static const char * option_help[] = {
"Print OpenSC package version",
"Erase the smart card",
"Creates a new PKCS #15 structure",
"Store a new PIN/PUK on the card",
"Generate a new key and store it on the card",
"Store private key",
"Store public key",
"Store secret key",
"Store an X.509 certificate",
"Update an X.509 certificate (careful with mail decryption certs!!)",
"Store a data object",
"Delete object(s) (use \"help\" for more information)",
"Change attribute(s) (use \"help\" for more information)",
"Card specific sanity check and possibly update procedure",
"Erase application with AID <arg>",
"Specify which reader to use",
"Specify PIN",
"Specify unblock PIN",
"Specify security officer (SO) PIN",
"Specify unblock PIN for SO PIN",
"Do not install a SO PIN, and do not prompt for it",
"Specify the serial number of the card",
"Specify ID of PIN to use/create",
"Specify ID of PUK to use/create",
"Verify PIN after card binding (use with --auth-id)",
"Specify ID of key/certificate",
"Specify label of PIN/key",
"Specify label of PUK",
"Specify secret key algorithm (use with --store-secret-key)",
"Specify public key label (use with --generate-key)",
"Specify user cert label (use with --store-private-key)",
"Specify application name of data object (use with --store-data-object)",
"Specify application id of data object (use with --store-data-object)",
"Specify AID of the on-card PKCS#15 application to be binded to (in hexadecimal form)",
"Output public portion of generated key to file",
"Specify key/cert file format: PEM (=default), DER or PKCS12",
"Specify passphrase for unlocking secret key",
"Mark certificate as a CA certificate",
"Specify X.509 key usage (use \"--key-usage help\" for more information)",
"Finish initialization phase of the smart card",
"Update 'lastUpdate' attribute of tokenInfo",
"When storing PKCS#12 ignore CA certificates",
"Store or update existing certificate",
"Private key stored as an extractable key",
"Set userConsent. Default = 0",
"Insecure mode: do not require a PIN for private key",
"Do not ask for transport keys if the driver thinks it knows the key",
"Do not prompt the user; if no PINs supplied, pinpad will be used",
NULL,
"Specify the general profile to use",
"Specify the card profile to use",
"For a new key specify GUID for a MD container",
"Wait for card insertion",
"Display this message",
"Verbose operation, may be used several times",
NULL,
NULL,
};
enum {
ACTION_NONE = 0,
ACTION_ASSERT_PRISTINE,
ACTION_ERASE,
ACTION_INIT,
ACTION_DELETE_OBJECTS,
ACTION_STORE_PIN,
ACTION_GENERATE_KEY,
ACTION_STORE_PRIVKEY,
ACTION_STORE_PUBKEY,
ACTION_STORE_SECRKEY,
ACTION_STORE_CERT,
ACTION_UPDATE_CERT,
ACTION_STORE_DATA,
ACTION_FINALIZE_CARD,
ACTION_CHANGE_ATTRIBUTES,
ACTION_SANITY_CHECK,
ACTION_UPDATE_LAST_UPDATE,
ACTION_ERASE_APPLICATION,
ACTION_PRINT_VERSION,
ACTION_MAX
};
static const char *action_names[] = {
"do nothing",
"verify that card is pristine",
"erase card",
"create PKCS #15 meta structure",
"delete object(s)",
"store PIN",
"generate key",
"store private key",
"store public key",
"store secret key",
"store certificate",
"update certificate",
"store data object",
"finalizing card",
"change attribute(s)",
"check card's sanity",
"update 'last-update'",
"erase application"
};
#define MAX_CERTS 4
#define MAX_SECRETS 16
struct secret {
int type;
int reference;
sc_pkcs15_id_t id;
unsigned char key[64];
size_t len;
};
/* Flags for do_delete_crypto_objects() and do_change_attributes() */
#define SC_PKCS15INIT_TYPE_PRKEY 1
#define SC_PKCS15INIT_TYPE_PUBKEY 2
#define SC_PKCS15INIT_TYPE_CERT 4
#define SC_PKCS15INIT_TYPE_CHAIN (8 | 4)
#define SC_PKCS15INIT_TYPE_DATA 16
#define SC_PKCS15INIT_TYPE_SKEY 32
static sc_context_t * g_ctx = NULL;
static sc_card_t * g_card = NULL;
static struct sc_pkcs15_card * g_p15card = NULL;
static char * opt_reader = NULL;
static unsigned int opt_actions;
static int opt_extractable = 0,
opt_insecure = 0,
opt_authority = 0,
opt_use_pinpad = 0,
opt_no_sopin = 0,
opt_use_defkeys = 0,
opt_wait = 0,
opt_verify_pin = 0;
static const char * opt_profile = "pkcs15";
static char * opt_card_profile = NULL;
static char * opt_infile = NULL;
static char * opt_format = NULL;
static char * opt_authid = NULL;
static char * opt_objectid = NULL;
static char * opt_label = NULL;
static char * opt_puk_label = NULL;
static char * opt_pubkey_label = NULL;
static char * opt_secrkey_algo = NULL;
static char * opt_cert_label = NULL;
static const char * opt_pins[4];
static char * pins[4];
static char * opt_serial = NULL;
static const char * opt_passphrase = NULL;
static char * opt_newkey = NULL;
static char * opt_outkey = NULL;
static char * opt_application_id = NULL;
static char * opt_application_name = NULL;
static char * opt_bind_to_aid = NULL;
static char * opt_puk_authid = NULL;
static char * opt_md_container_guid = NULL;
static unsigned int opt_x509_usage = 0;
static unsigned int opt_delete_flags = 0;
static unsigned int opt_type = 0;
static int ignore_cmdline_pins = 0;
static struct secret opt_secrets[MAX_SECRETS];
static unsigned int opt_secret_count;
static int opt_ignore_ca_certs = 0;
static int opt_update_existing = 0;
static int verbose = 0;
static int opt_user_consent = 0;
static struct sc_pkcs15init_callbacks callbacks = {
get_pin_callback, /* get_pin() */
get_key_callback, /* get_key() */
};
/*
* Dialog types for get_pin
*/
#define SC_UI_USAGE_OTHER 0x0000
#define SC_UI_USAGE_NEW_PIN 0x0001
#define SC_UI_USAGE_UNBLOCK_PIN 0x0002
#define SC_UI_USAGE_CHANGE_PIN 0x0003
/*
* Dialog flags
*/
#define SC_UI_PIN_RETYPE 0x0001 /* new pin, retype */
#define SC_UI_PIN_OPTIONAL 0x0002 /* new pin optional */
#define SC_UI_PIN_CHECK_LENGTH 0x0004 /* check pin length */
#define SC_UI_PIN_MISMATCH_RETRY 0x0008 /* retry if new pin mismatch? */
/* Hints passed to get_pin
* M marks mandatory fields,
* O marks optional fields
*/
typedef struct sc_ui_hints {
const char * prompt; /* M: cmdline prompt */
const char * dialog_name; /* M: dialog name */
unsigned int usage; /* M: usage hint */
unsigned int flags; /* M: flags */
sc_card_t * card; /* M: card handle */
struct sc_pkcs15_card * p15card; /* O: pkcs15 handle */
/* We may not have a pkcs15 object yet when we get
* here, but we may have an idea of what it's going to
* look like. */
const char * obj_label; /* O: object (PIN) label */
union {
struct sc_pkcs15_auth_info *pin;
} info;
} sc_ui_hints_t;
/*
* ask user for a pin
*/
extern int get_pin(sc_ui_hints_t *hints, char **out);
static int get_new_pin(sc_ui_hints_t *, const char *, const char *,
char **);
int
main(int argc, char **argv)
{
struct sc_profile *profile = NULL;
unsigned int n;
int r = 0;
struct sc_pkcs15_card *tmp_p15_data = NULL;
#ifdef RANDOM_POOL
if (!RAND_load_file(RANDOM_POOL, 32))
util_fatal("Unable to seed random number pool for key generation");
#endif
parse_commandline(argc, argv);
if (optind != argc)
util_print_usage_and_die(app_name, options, option_help, NULL);
if (opt_actions == 0) {
fprintf(stderr, "No action specified.\n");
util_print_usage_and_die(app_name, options, option_help, NULL);
}
if (!opt_profile) {
fprintf(stderr, "No profile specified.\n");
util_print_usage_and_die(app_name, options, option_help, NULL);
}
/* Connect to the card */
if (!open_reader_and_card(opt_reader))
return 1;
sc_pkcs15init_set_callbacks(&callbacks);
/* Bind the card-specific operations and load the profile */
r = sc_pkcs15init_bind(g_card, opt_profile, opt_card_profile, NULL, &profile);
if (r < 0) {
printf("Couldn't bind to the card: %s\n", sc_strerror(r));
return 1;
}
for (n = 0; n < sizeof(pins)/sizeof(pins[0]); n++) {
pins[n] = NULL;
}
for (n = 0; n < ACTION_MAX; n++) {
unsigned int action = n;
if (!(opt_actions & (1 << action)))
continue;
if (action != ACTION_ERASE
&& action != ACTION_INIT
&& action != ACTION_ASSERT_PRISTINE
&& g_p15card == NULL) {
/* Read the PKCS15 structure from the card */
if (opt_bind_to_aid) {
struct sc_aid aid;
aid.len = sizeof(aid.value);
if (sc_hex_to_bin(opt_bind_to_aid, aid.value, &aid.len)) {
fprintf(stderr, "Invalid AID value: '%s'\n", opt_bind_to_aid);
return 1;
}
r = sc_pkcs15init_finalize_profile(g_card, profile, &aid);
if (r < 0) {
fprintf(stderr, "Finalize profile error %s\n", sc_strerror(r));
break;
}
r = sc_pkcs15_bind(g_card, &aid, &g_p15card);
}
else {
r = sc_pkcs15_bind(g_card, NULL, &g_p15card);
}
if (r) {
fprintf(stderr, "PKCS#15 binding failed: %s\n", sc_strerror(r));
break;
}
/* XXX: should compare card to profile here to make
* sure we're not messing things up */
if (verbose)
printf("Found %s\n", g_p15card->tokeninfo->label);
sc_pkcs15init_set_p15card(profile, g_p15card);
if (opt_verify_pin) {
r = verify_pin(g_p15card, opt_authid);
if (r) {
fprintf(stderr, "Failed to verify User PIN : %s\n",
sc_strerror(r));
break;
}
}
}
if (verbose && action != ACTION_ASSERT_PRISTINE)
printf("About to %s.\n", action_names[action]);
switch (action) {
case ACTION_PRINT_VERSION:
printf("%s\n", OPENSC_SCM_REVISION);
break;
case ACTION_ASSERT_PRISTINE:
/* skip printing error message */
if ((r = do_assert_pristine(g_card)) < 0)
goto out;
continue;
case ACTION_ERASE:
r = do_erase(g_card, profile);
break;
case ACTION_INIT:
r = do_init_app(profile);
break;
case ACTION_STORE_PIN:
r = do_store_pin(profile);
break;
case ACTION_STORE_PRIVKEY:
r = do_store_private_key(profile);
break;
case ACTION_STORE_PUBKEY:
r = do_store_public_key(profile, NULL);
break;
case ACTION_STORE_SECRKEY:
r = do_store_secret_key(profile);
break;
case ACTION_STORE_CERT:
r = do_store_certificate(profile);
break;
case ACTION_UPDATE_CERT:
r = do_update_certificate(profile);
break;
case ACTION_STORE_DATA:
r = do_store_data_object(profile);
break;
case ACTION_DELETE_OBJECTS:
r = do_delete_objects(profile, opt_delete_flags);
break;
case ACTION_CHANGE_ATTRIBUTES:
r = do_change_attributes(profile, opt_type);
break;
case ACTION_GENERATE_KEY:
r = do_generate_key(profile, opt_newkey);
if (r == SC_ERROR_INVALID_ARGUMENTS)
r = do_generate_skey(profile, opt_newkey);
break;
case ACTION_FINALIZE_CARD:
r = do_finalize_card(g_card, profile);
break;
case ACTION_SANITY_CHECK:
r = do_sanity_check(profile);
break;
case ACTION_UPDATE_LAST_UPDATE:
profile->dirty = 1;
break;
case ACTION_ERASE_APPLICATION:
r = do_erase_application(g_card, profile);
break;
default:
util_fatal("Action not yet implemented\n");
}
if (r < 0) {
fprintf(stderr, "Failed to %s: %s\n",
action_names[action], sc_strerror(r));
break;
}
}
for (n = 0; n < sizeof(pins)/sizeof(pins[0]); n++) {
free(pins[n]);
}
out:
/* After erasing card profile->p15_data might change */
if (profile) {
tmp_p15_data = profile->p15_data;
sc_pkcs15init_unbind(profile);
if (tmp_p15_data != g_p15card) {
sc_pkcs15_unbind(tmp_p15_data);
}
}
if (g_p15card) {
sc_pkcs15_unbind(g_p15card);
}
if (g_card) {
sc_disconnect_card(g_card);
}
sc_release_context(g_ctx);
return r < 0? 1 : 0;
}
static int
open_reader_and_card(char *reader)
{
int r;
sc_context_param_t ctx_param;
memset(&ctx_param, 0, sizeof(ctx_param));
ctx_param.ver = 0;
ctx_param.app_name = app_name;
ctx_param.debug = verbose;
if (verbose)
ctx_param.debug_file = stderr;
r = sc_context_create(&g_ctx, &ctx_param);
if (r) {
util_error("Failed to establish context: %s\n", sc_strerror(r));
return 0;
}
if (util_connect_card_ex(g_ctx, &g_card, reader, opt_wait, 0))
return 0;
return 1;
}
/*
* Make sure there's no pkcs15 structure on the card
*/
static int
do_assert_pristine(sc_card_t *in_card)
{
sc_path_t path;
int r, ok = 1;
r = sc_lock(in_card);
if (r < 0)
goto end;
sc_format_path("3F00", &path);
r = sc_select_file(in_card, &path, NULL);
if (r)
goto end;
sc_format_path("2F00", &path);
r = sc_select_file(in_card, &path, NULL);
if (r)
goto end;
/* For a while only the presence of OpenSC on-card pkcs#15 is checked.
TODO: Parse DIR(2F00) to get know if there is some PKCS#15 applications.*/
sc_format_path("5015", &path);
r = sc_select_file(in_card, &path, NULL);
if (r)
goto end;
ok = 0;
end:
sc_unlock(in_card);
if (!ok) {
fprintf(stderr,
"Card not pristine; detected (possibly incomplete) "
"PKCS#15 structure\n");
} else if (verbose) {
printf("Pristine card.\n");
}
return ok ? 0 : -1;
}
/* algorithm spec parsing */
struct alg_spec {
const char *spec;
int algorithm;
unsigned int keybits;
};
static const struct alg_spec alg_types_sym[] = {
{ "des", SC_ALGORITHM_DES, 64 },
{ "3des", SC_ALGORITHM_3DES, 192 },
{ "aes", SC_ALGORITHM_AES, 128 },
{ NULL, -1, 0 }
};
/* RSA can have a number , default is 2048 */
/* EC require a curve name */
/* EDDSA and XEDDSA without a size require a size or curve name or OID */
/* other EDDSA and XEDDSA can be used alone */
static const struct alg_spec alg_types_asym[] = {
{ "rsa", SC_ALGORITHM_RSA, 2048 }, /* new default */
{ "gost2001", SC_ALGORITHM_GOSTR3410, SC_PKCS15_GOSTR3410_KEYSIZE },
{ "ec", SC_ALGORITHM_EC, 0 },
{ "EdDSA", SC_ALGORITHM_EDDSA, 0 }, /* RFC 8410 section 8 */
{ "xeddsa", SC_ALGORITHM_XEDDSA, 0 },
{ "ECDH", SC_ALGORITHM_XEDDSA, 0 }, /* RFC 8410 section 8 */
/* RFC 8410 */
{ "Ed25519", SC_ALGORITHM_EDDSA, 255 }, /* RFC 8410 and gunpg */
{ "Ed448", SC_ALGORITHM_EDDSA, 448 },
{ "X25519", SC_ALGORITHM_XEDDSA, 255 },
{ "X448", SC_ALGORITHM_XEDDSA, 448 },
/* used by Yubikey and GNUK */
{ "edwards25519", SC_ALGORITHM_EDDSA, 255 },
{ "curve25519", SC_ALGORITHM_XEDDSA, 255 },
/* gnupg */
{ "cv25519", SC_ALGORITHM_XEDDSA, 255 },
{ NULL, -1, 0 }
};
static int
parse_alg_spec(const struct alg_spec *types, const char *spec, unsigned int *keybits, struct sc_pkcs15_prkey *prkey)
{
int i, types_idx = -1, algorithm = -1;
char *end;
for (i = 0; types[i].spec; i++) {
if (!strncasecmp(spec, types[i].spec, strlen(types[i].spec))) {
types_idx = i; /* save index of types array */
algorithm = types[i].algorithm;
*keybits = types[i].keybits;
spec += strlen(types[i].spec);
break;
}
}
if (algorithm < 0) {
util_error("Unknown algorithm \"%s\"", spec);
return SC_ERROR_INVALID_ARGUMENTS;
}
if (*spec == '/' || *spec == '-' || *spec == ':')
spec++;
/* if we have everything for EDDSA or XEDDSA */
if (*spec == 0x00 && *keybits && (algorithm == SC_ALGORITHM_EDDSA || algorithm == SC_ALGORITHM_XEDDSA) && prkey) {
prkey->u.ec.params.named_curve = strdup(types[types_idx].spec); /* correct case */
*keybits = types[types_idx].keybits;
return algorithm;
}
if (*spec) {
if (isalpha((unsigned char)*spec)
&& algorithm == SC_ALGORITHM_EC && prkey)
prkey->u.ec.params.named_curve = strdup(spec);
else
if (isalpha((unsigned char)*spec)
&& (algorithm == SC_ALGORITHM_EDDSA || algorithm == SC_ALGORITHM_XEDDSA)
&& prkey) {
prkey->u.ec.params.named_curve = strdup(types[types_idx].spec); /* copy correct case */
} else {
*keybits = (unsigned)strtoul(spec, &end, 10);
if (*end) {
util_error("Invalid number of key bits \"%s\"", spec);
return SC_ERROR_INVALID_ARGUMENTS;
}
}
}
return algorithm;
}
/*
* Erase card
*/
static int
do_erase(sc_card_t *in_card, struct sc_profile *profile)
{
int r;
struct sc_pkcs15_card *p15card;
struct sc_aid aid;
struct sc_aid *paid = NULL;
p15card = sc_pkcs15_card_new();
p15card->card = in_card;
ignore_cmdline_pins++;
if (opt_bind_to_aid) {
aid.len = sizeof(aid.value);
r = sc_hex_to_bin(opt_bind_to_aid, aid.value, &aid.len);
if (r < 0) {
fprintf(stderr, "Invalid AID value: '%s'\n", opt_bind_to_aid);
goto err;
}
paid = &aid;
}
r = sc_lock(p15card->card);
if (r < 0)
goto err;
r = sc_pkcs15init_erase_card(p15card, profile, paid);
sc_unlock(p15card->card);
ignore_cmdline_pins--;
err:
sc_pkcs15_card_free(p15card);
return r;
}
static int
do_erase_application(sc_card_t *in_card, struct sc_profile *profile)
{
int r;
ignore_cmdline_pins--;
r = do_erase(in_card, profile);
ignore_cmdline_pins++;
return r;
}
static int do_finalize_card(sc_card_t *in_card, struct sc_profile *profile)
{
int r;
r = sc_lock(in_card);
if (r < 0)
return r;
r = sc_pkcs15init_finalize_card(in_card, profile);
sc_unlock(in_card);
return r;
}
/*
* Initialize pkcs15 application
*/
static int
do_init_app(struct sc_profile *profile)
{
struct sc_pkcs15init_initargs args;
sc_pkcs15_auth_info_t info;
sc_ui_hints_t hints;
const char *role = "so";
int r, so_puk_disabled = 0;
memset(&hints, 0, sizeof(hints));
memset(&info, 0, sizeof(info));
hints.usage = SC_UI_USAGE_NEW_PIN;
hints.flags = SC_UI_PIN_RETYPE
| SC_UI_PIN_CHECK_LENGTH
| SC_UI_PIN_MISMATCH_RETRY;
hints.card = g_card;
hints.p15card = NULL;
hints.info.pin = &info;
/* If it's the onepin option, we need the user PIN iso the SO PIN */
if (opt_profile && strstr(opt_profile, "+onepin")) {
if (opt_pins[0])
opt_pins[2] = opt_pins[0];
if (opt_pins[1])
opt_pins[3] = opt_pins[1];
}
memset(&args, 0, sizeof(args));
sc_pkcs15init_get_pin_info(profile, SC_PKCS15INIT_SO_PIN, &info);
if (!(info.attrs.pin.flags & SC_PKCS15_PIN_FLAG_SO_PIN))
role = "user";
else
hints.flags |= SC_UI_PIN_OPTIONAL; /* SO PIN is always optional */
if ((info.attrs.pin.flags & SC_PKCS15_PIN_FLAG_UNBLOCK_DISABLED)
&& (info.attrs.pin.flags & SC_PKCS15_PIN_FLAG_SO_PIN))
so_puk_disabled = 1;
if (!opt_pins[2] && !opt_use_pinpad && !opt_no_sopin) {
r = get_new_pin(&hints, role, "pin", &pins[2]);
if (r < 0)
goto failed;
opt_pins[2] = pins[2];
}
if (!so_puk_disabled && opt_pins[2] && !opt_pins[3] && !opt_use_pinpad) {
sc_pkcs15init_get_pin_info(profile, SC_PKCS15INIT_SO_PUK, &info);
if (!(info.attrs.pin.flags & SC_PKCS15_PIN_FLAG_SO_PIN))
role = "user";
hints.flags |= SC_UI_PIN_OPTIONAL;
r = get_new_pin(&hints, role, "puk", &pins[3]);
if (r < 0)
goto failed;
opt_pins[3] = pins[3];
}
args.so_pin = (const u8 *) opt_pins[2];
if (args.so_pin)
args.so_pin_len = strlen((const char *) args.so_pin);
if (!so_puk_disabled) {
args.so_puk = (const u8 *) opt_pins[3];
if (args.so_puk)
args.so_puk_len = strlen((const char *) args.so_puk);
}
args.serial = (const char *) opt_serial;
args.label = opt_label;
r = sc_lock(g_card);
if (r < 0)
return r;
r = sc_pkcs15init_add_app(g_card, profile, &args);
sc_unlock(g_card);
return r;
failed: fprintf(stderr, "Failed to read PIN: %s\n", sc_strerror(r));
return SC_ERROR_PKCS15INIT;
}
/*
* Store a PIN/PUK pair
*/
static int
do_store_pin(struct sc_profile *profile)
{
struct sc_pkcs15init_pinargs args;
sc_pkcs15_auth_info_t info;
sc_ui_hints_t hints;
int r;
const char *pin_id;
memset(&hints, 0, sizeof(hints));
hints.usage = SC_UI_USAGE_NEW_PIN;
hints.flags = SC_UI_PIN_RETYPE
| SC_UI_PIN_CHECK_LENGTH
| SC_UI_PIN_MISMATCH_RETRY;
hints.card = g_card;
hints.p15card = g_p15card;
hints.info.pin = &info;
pin_id = opt_objectid ? opt_objectid : opt_authid;
if (!pin_id) {
util_error("No pin id specified\n");
return SC_ERROR_INVALID_ARGUMENTS;
}
sc_pkcs15init_get_pin_info(profile, SC_PKCS15INIT_USER_PIN, &info);
if (opt_pins[0] == NULL) {
if ((r = get_new_pin(&hints, "user", "pin", &pins[0])) < 0)
goto failed;
opt_pins[0] = pins[0];
}
if (*opt_pins[0] == '\0') {
util_error("You must specify a PIN\n");
return SC_ERROR_INVALID_ARGUMENTS;
}
memset(&args, 0, sizeof(args));
sc_pkcs15_format_id(pin_id, &args.auth_id);
args.pin = (u8 *) opt_pins[0];
args.pin_len = strlen(opt_pins[0]);
args.label = opt_label;
if (!(info.attrs.pin.flags & SC_PKCS15_PIN_FLAG_UNBLOCK_DISABLED)
&& opt_pins[1] == NULL) {
sc_pkcs15init_get_pin_info(profile, SC_PKCS15INIT_USER_PUK, &info);
hints.flags |= SC_UI_PIN_OPTIONAL;
if ((r = get_new_pin(&hints, "user", "puk", &pins[1])) < 0)