-
Notifications
You must be signed in to change notification settings - Fork 98
/
ykpiv.c
2304 lines (2017 loc) · 68.3 KB
/
ykpiv.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) 2014-2020 Yubico AB
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS
* "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 COPYRIGHT
* OWNER OR CONTRIBUTORS 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.
*
*/
/** @file */
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdint.h>
#include <ctype.h>
#include "internal.h"
#include "ykpiv.h"
/**
* DISABLE_PIN_CACHE - disable in-RAM cache of PIN
*
* By default, the PIN is cached in RAM when provided to \p ykpiv_verify() or
* changed with \p ykpiv_change_pin(). If the USB connection is lost between
* calls, the device will be re-authenticated on the next call using the cached
* PIN. The PIN is cleared with a call to \p ykpiv_done().
*
* The PIN cache prevents problems with long-running applications losing their
* authentication in some cases, such as when a laptop sleeps.
*
* The cache can be disabled by setting this define to 1 if it is not desired
* to store the PIN in RAM.
*
*/
#ifndef DISABLE_PIN_CACHE
#define DISABLE_PIN_CACHE 0
#endif
/**
* DISABLE_MGM_KEY_CACHE - disable in-RAM cache of MGM_KEY (SO PIN)
*
* By default, the MGM_KEY is cached in RAM when provided to \p ykpiv_authenticate() or
* changed with \p ykpiv_set_mgmkey(). If the USB connection is lost between
* calls, the device will be re-authenticated on the next call using the cached
* MGM_KEY. The MGM_KEY is cleared with a call to \p ykpiv_done().
*
* The MGM_KEY cache prevents problems with long-running applications losing their
* authentication in some cases, such as when a laptop sleeps.
*
* The cache can be disabled by setting this define to 1 if it is not desired
* to store the MGM_KEY in RAM.
*
*/
#ifndef DISABLE_MGM_KEY_CACHE
#define DISABLE_MGM_KEY_CACHE 0
#endif
/**
* ENABLE_APPLICATION_RESELECT - re-select application for all public API calls
*
* If this is enabled, every public call (prefixed with \r ykpiv_) will check
* that the PIV application is currently selected, or re-select it if it is
* not.
*
* Auto re-selection allows a long-running PIV application to cooperate on
* a system that may simultaneously use the non-PIV applications of connected
* devices.
*
* This is \b DANGEROUS - with this enabled, slots with the policy
* \p YKPIV_PINPOLICY_ALWAYS will not be accessible.
*
*/
#ifndef ENABLE_APPLICATION_RESELECTION
#define ENABLE_APPLICATION_RESELECTION 0
#endif
/**
* ENABLE_IMPLICIT_TRANSACTIONS - call SCardBeginTransaction for all public API calls
*
* If this is enabled, every public call (prefixed with \r ykpiv_) will call
* SCardBeginTransaction on entry and SCardEndTransaction on exit.
*
* For applications that do not do their own transaction management, like the piv tool
* itself, retaining the default setting of enabled can allow other applications and
* threads to make calls to CCID that can interfere with multi-block data sent to the
* card via SCardTransmitData.
*/
#ifndef ENABLE_IMPLICIT_TRANSACTIONS
#define ENABLE_IMPLICIT_TRANSACTIONS 1
#endif
/**
* Platform specific definitions
*/
#ifdef _MSC_VER
#define strncasecmp _strnicmp
#endif
#define YKPIV_MGM_DEFAULT "\x01\x02\x03\x04\x05\x06\x07\x08\x01\x02\x03\x04\x05\x06\x07\x08\x01\x02\x03\x04\x05\x06\x07\x08"
static ykpiv_rc _cache_pin(ykpiv_state *state, const char *pin, size_t len);
static ykpiv_rc _cache_mgm_key(ykpiv_state *state, unsigned const char *key, size_t len);
static ykpiv_rc _ykpiv_get_serial(ykpiv_state *state);
static ykpiv_rc _ykpiv_get_version(ykpiv_state *state);
static ykpiv_rc _ykpiv_verify(ykpiv_state *state, const char *pin, const size_t pin_len);
static ykpiv_rc _ykpiv_authenticate2(ykpiv_state *state, unsigned const char *key, size_t len);
static ykpiv_rc _ykpiv_auth_deauthenticate(ykpiv_state *state);
static unsigned const char piv_aid[] = {
0xa0, 0x00, 0x00, 0x03, 0x08
};
static unsigned const char yk_aid[] = {
0xa0, 0x00, 0x00, 0x05, 0x27, 0x20, 0x01, 0x01
};
static unsigned const char mgmt_aid[] = {
0xa0, 0x00, 0x00, 0x05, 0x27, 0x47, 0x11, 0x17
};
static void* _default_alloc(void *data, size_t cb) {
(void)data;
return calloc(cb, 1);
}
static void * _default_realloc(void *data, void *p, size_t cb) {
(void)data;
return realloc(p, cb);
}
static void _default_free(void *data, void *p) {
(void)data;
free(p);
}
ykpiv_allocator _default_allocator = {
.pfn_alloc = _default_alloc,
.pfn_realloc = _default_realloc,
.pfn_free = _default_free,
.alloc_data = 0
};
/* Memory helper functions */
void* _ykpiv_alloc(ykpiv_state *state, size_t size) {
if (!state || !(state->allocator.pfn_alloc)) return NULL;
return state->allocator.pfn_alloc(state->allocator.alloc_data, size);
}
void* _ykpiv_realloc(ykpiv_state *state, void *address, size_t size) {
if (!state || !(state->allocator.pfn_realloc)) return NULL;
return state->allocator.pfn_realloc(state->allocator.alloc_data, address, size);
}
void _ykpiv_free(ykpiv_state *state, void *data) {
if (!data || !state || !(state->allocator.pfn_free)) return;
state->allocator.pfn_free(state->allocator.alloc_data, data);
}
static void dump_hex(const unsigned char *buf, size_t len) {
for (size_t i = 0; i < len; i++) {
fprintf(stderr, "%02x ", buf[i]);
}
}
size_t _ykpiv_get_length_size(size_t length) {
if(length < 0x80) {
return 1;
} else if(length < 0x100) {
return 2;
} else {
return 3;
}
}
size_t _ykpiv_set_length(unsigned char *buffer, size_t length) {
if(length < 0x80) {
*buffer++ = (unsigned char)length;
return 1;
} else if(length < 0x100) {
*buffer++ = 0x81;
*buffer++ = (unsigned char)length;
return 2;
} else {
*buffer++ = 0x82;
*buffer++ = (length >> 8) & 0xff;
*buffer++ = length & 0xff;
return 3;
}
}
size_t _ykpiv_get_length(const unsigned char *buffer, const unsigned char* end, size_t *len) {
if(buffer + 1 <= end && buffer[0] < 0x80) {
*len = buffer[0];
return buffer + 1 + *len <= end ? 1 : 0;
} else if(buffer + 2 <= end && buffer[0] == 0x81) {
*len = buffer[1];
return buffer + 2 + *len <= end ? 2 : 0;
} else if(buffer + 3 <= end && buffer[0] == 0x82) {
size_t tmp = buffer[1];
*len = (tmp << 8) + buffer[2];
return buffer + 3 + *len <= end ? 3 : 0;
}
*len = 0;
return 0;
}
static unsigned char *set_object(int object_id, unsigned char *buffer) {
*buffer++ = 0x5c;
if(object_id == YKPIV_OBJ_DISCOVERY) {
*buffer++ = 1;
*buffer++ = YKPIV_OBJ_DISCOVERY;
} else if(object_id > 0xffff && object_id <= 0xffffff) {
*buffer++ = 3;
*buffer++ = (object_id >> 16) & 0xff;
*buffer++ = (object_id >> 8) & 0xff;
*buffer++ = object_id & 0xff;
} else {
return NULL;
}
return buffer;
}
ykpiv_rc ykpiv_init_with_allocator(ykpiv_state **state, int verbose, const ykpiv_allocator *allocator) {
ykpiv_state *s;
if (NULL == state) {
return YKPIV_GENERIC_ERROR;
}
if (NULL == allocator || !allocator->pfn_alloc || !allocator->pfn_realloc || !allocator->pfn_free) {
return YKPIV_MEMORY_ERROR;
}
s = allocator->pfn_alloc(allocator->alloc_data, sizeof(ykpiv_state));
if (NULL == s) {
return YKPIV_MEMORY_ERROR;
}
memset(s, 0, sizeof(ykpiv_state));
s->allocator = *allocator;
s->verbose = verbose;
s->context = (SCARDCONTEXT)-1;
*state = s;
return YKPIV_OK;
}
ykpiv_rc ykpiv_init(ykpiv_state **state, int verbose) {
return ykpiv_init_with_allocator(state, verbose, &_default_allocator);
}
static ykpiv_rc _ykpiv_done(ykpiv_state *state, bool disconnect) {
if (disconnect)
ykpiv_disconnect(state);
_cache_pin(state, NULL, 0);
_cache_mgm_key(state, NULL, 0);
_ykpiv_free(state, state);
return YKPIV_OK;
}
ykpiv_rc ykpiv_done_with_external_card(ykpiv_state *state) {
return _ykpiv_done(state, false);
}
ykpiv_rc ykpiv_done(ykpiv_state *state) {
return _ykpiv_done(state, true);
}
ykpiv_rc ykpiv_disconnect(ykpiv_state *state) {
if(state->card) {
if(state->verbose) {
fprintf(stderr, "Disconnect card #%u.\n", state->serial);
}
SCardDisconnect(state->card, SCARD_RESET_CARD);
state->card = 0;
}
if(SCardIsValidContext(state->context) == SCARD_S_SUCCESS) {
SCardReleaseContext(state->context);
state->context = (SCARDCONTEXT)-1;
}
state->serial = 0;
state->ver.major = 0;
state->ver.minor = 0;
state->ver.patch = 0;
return YKPIV_OK;
}
ykpiv_rc _ykpiv_select_application(ykpiv_state *state) {
unsigned char templ[] = {0x00, YKPIV_INS_SELECT_APPLICATION, 0x04, 0x00};
unsigned char data[261] = {0};
unsigned long recv_len = sizeof(data);
int sw = 0;
ykpiv_rc res = YKPIV_OK;
if((res = _ykpiv_transfer_data(state, templ, piv_aid, sizeof(piv_aid), data, &recv_len, &sw)) != YKPIV_OK) {
if(state->verbose) {
fprintf(stderr, "Failed communicating with card: '%s'\n", ykpiv_strerror(res));
}
return res;
}
else if(sw != SW_SUCCESS) {
if(state->verbose) {
fprintf(stderr, "Failed selecting application: %04x\n", sw);
}
return YKPIV_GENERIC_ERROR;
}
/* now that the PIV application is selected, retrieve the version
* and serial number. Previously the NEO/YK4 required switching
* to the yk applet to retrieve the serial, YK5 implements this
* as a PIV applet command. Unfortunately, this change requires
* that we retrieve the version number first, so that get_serial
* can determine how to get the serial number, which for the NEO/Yk4
* will result in another selection of the PIV applet. */
// This stores the number of PIN retries left in state
_ykpiv_verify(state, NULL, 0);
// WRONG_PIN or PIN_LOCKED is expected on successful query.
res = _ykpiv_get_version(state);
if (res != YKPIV_OK) {
if (state->verbose) {
fprintf(stderr, "Failed to retrieve version: '%s'\n", ykpiv_strerror(res));
}
return res;
}
res = _ykpiv_get_serial(state);
if (res != YKPIV_OK) {
if (state->verbose) {
fprintf(stderr, "Failed to retrieve serial number: '%s'\n", ykpiv_strerror(res));
}
res = YKPIV_OK;
}
return res;
}
ykpiv_rc _ykpiv_ensure_application_selected(ykpiv_state *state) {
ykpiv_rc res = YKPIV_OK;
#if ENABLE_APPLICATION_RESELECTION
if (NULL == state) {
return YKPIV_GENERIC_ERROR;
}
res = _ykpiv_verify(state, NULL, 0);
if ((YKPIV_OK != res) && (YKPIV_WRONG_PIN != res) && (YKPIV_PIN_LOCKED != res)) {
res = _ykpiv_select_application(state);
}
else {
res = YKPIV_OK;
}
return res;
#else
(void)state;
return res;
#endif
}
static ykpiv_rc _ykpiv_connect(ykpiv_state *state, uintptr_t context, uintptr_t card) {
ykpiv_rc res = YKPIV_OK;
if (NULL == state) {
return YKPIV_GENERIC_ERROR;
}
// if the context has changed, and the new context is not valid, return an error
if ((context != state->context) && (SCARD_S_SUCCESS != SCardIsValidContext(context))) {
return YKPIV_PCSC_ERROR;
}
// if card handle has changed, determine if handle is valid (less efficient, but complete)
if ((card != state->card)) {
char reader[CB_BUF_MAX] = {0};
pcsc_word reader_len = sizeof(reader);
uint8_t atr[CB_ATR_MAX] = {0};
pcsc_word atr_len = sizeof(atr);
// Cannot set the reader len to NULL. Confirmed in OSX 10.10, so we have to retrieve it even though we don't need it.
if (SCARD_S_SUCCESS != SCardStatus(card, reader, &reader_len, NULL, NULL, atr, &atr_len)) {
return YKPIV_PCSC_ERROR;
}
if(atr_len + 1 == sizeof(YKPIV_ATR_NEO_R3) && !memcmp(atr, YKPIV_ATR_NEO_R3, atr_len))
state->model = DEVTYPE_NEOr3;
else if(atr_len + 1 == sizeof(YKPIV_ATR_NEO_R3_NFC) && !memcmp(atr, YKPIV_ATR_NEO_R3_NFC, atr_len))
state->model = DEVTYPE_NEOr3;
else if(atr_len + 1 == sizeof(YKPIV_ATR_YK4) && !memcmp(atr, YKPIV_ATR_YK4, atr_len))
state->model = DEVTYPE_YK4;
else if(atr_len + 1 == sizeof(YKPIV_ATR_YK5_P1) && !memcmp(atr, YKPIV_ATR_YK5_P1, atr_len))
state->model = DEVTYPE_YK5;
else if(atr_len + 1 == sizeof(YKPIV_ATR_YK5) && !memcmp(atr, YKPIV_ATR_YK5, atr_len))
state->model = DEVTYPE_YK5;
else if(atr_len + 1 == sizeof(YKPIV_ATR_YK5_NFC) && !memcmp(atr, YKPIV_ATR_YK5_NFC, atr_len))
state->model = DEVTYPE_YK5;
else
state->model = DEVTYPE_UNKNOWN;
}
state->context = context;
state->card = card;
/*
** Do not select the applet here, as we need to accommodate commands that are
** sensitive to re-select (custom apdu/auth). All commands that can handle explicit
** selection already check the applet state and select accordingly anyway.
** ykpiv_verify_select is supplied for those who want to select explicitly.
**
** The applet _is_ selected by ykpiv_connect(), but is not selected when bypassing
** it with ykpiv_connect_with_external_card().
*/
return res;
}
ykpiv_rc ykpiv_connect_with_external_card(ykpiv_state *state, uintptr_t context, uintptr_t card) {
return _ykpiv_connect(state, context, card);
}
ykpiv_rc ykpiv_validate(ykpiv_state *state, const char *wanted) {
if(state->card) {
if(state->verbose) {
fprintf(stderr, "Validate reader '%s'.\n", wanted);
}
char reader[CB_BUF_MAX] = {0};
pcsc_word reader_len = sizeof(reader);
uint8_t atr[CB_ATR_MAX] = {0};
pcsc_word atr_len = sizeof(atr);
pcsc_long rc = SCardStatus(state->card, reader, &reader_len, NULL, NULL, atr, &atr_len);
if(rc != SCARD_S_SUCCESS) {
if(state->verbose) {
fprintf (stderr, "SCardStatus failed on reader '%s', rc=%lx\n", wanted, (long)rc);
}
rc = SCardDisconnect(state->card, SCARD_RESET_CARD);
if(rc != SCARD_S_SUCCESS) {
if(state->verbose) {
fprintf (stderr, "SCardDisconnect failed on reader '%s', rc=%lx\n", wanted, (long)rc);
}
}
state->card = 0;
state->serial = 0;
state->ver.major = 0;
state->ver.minor = 0;
state->ver.patch = 0;
_cache_pin(state, NULL, 0);
_cache_mgm_key(state, NULL, 0);
return YKPIV_PCSC_ERROR;
}
if (strcmp(wanted, reader)) {
if(state->verbose) {
fprintf (stderr, "Disconnecting incorrect reader '%s' (wanted '%s'), rc=%lx\n", reader, wanted, (long)rc);
}
rc = SCardDisconnect(state->card, SCARD_RESET_CARD);
if(rc != SCARD_S_SUCCESS) {
if(state->verbose) {
fprintf (stderr, "SCardDisconnect failed on reader '%s' (wanted '%s'), rc=%lx\n", reader, wanted, (long)rc);
}
}
state->card = 0;
state->serial = 0;
state->ver.major = 0;
state->ver.minor = 0;
state->ver.patch = 0;
_cache_pin(state, NULL, 0);
_cache_mgm_key(state, NULL, 0);
return YKPIV_GENERIC_ERROR;
}
return YKPIV_OK;
}
return YKPIV_GENERIC_ERROR;
}
ykpiv_rc ykpiv_connect(ykpiv_state *state, const char *wanted) {
char reader_buf[2048] = {0};
size_t num_readers = sizeof(reader_buf);
pcsc_long rc;
char *reader_ptr;
ykpiv_rc ret;
SCARDHANDLE card = (SCARDHANDLE)-1;
if(wanted && *wanted == '@') {
wanted++; // Skip the '@'
if(state->verbose) {
fprintf(stderr, "Connect reader '%s'.\n", wanted);
}
if(SCardIsValidContext(state->context) != SCARD_S_SUCCESS) {
rc = SCardEstablishContext(SCARD_SCOPE_SYSTEM, NULL, NULL, &state->context);
if (rc != SCARD_S_SUCCESS) {
if(state->verbose) {
fprintf (stderr, "SCardEstablishContext failed, rc=%lx\n", (long)rc);
}
return YKPIV_PCSC_ERROR;
}
}
rc = SCardConnect(state->context, wanted, SCARD_SHARE_SHARED,
SCARD_PROTOCOL_T0|SCARD_PROTOCOL_T1, &card, &state->protocol);
if(rc != SCARD_S_SUCCESS)
{
if(state->verbose) {
fprintf(stderr, "SCardConnect failed for '%s', rc=%lx\n", wanted, (long)rc);
}
SCardReleaseContext(state->context);
state->context = (SCARDCONTEXT)-1;
return YKPIV_PCSC_ERROR;
} else {
if(state->verbose > 2) {
fprintf(stderr, "SCardConnect succeeded for '%s', protocol=%lx\n", wanted, (unsigned long)state->protocol);
}
}
strncpy(state->reader, wanted, sizeof(state->reader));
state->reader[sizeof(state->reader) - 1] = 0;
} else
{
ret = ykpiv_list_readers(state, reader_buf, &num_readers);
if(ret != YKPIV_OK) {
return ret;
}
for(reader_ptr = reader_buf; *reader_ptr != '\0'; reader_ptr += strlen(reader_ptr) + 1) {
if(wanted) {
char *ptr = reader_ptr;
bool found = false;
do {
if(strlen(ptr) < strlen(wanted)) {
break;
}
if(strncasecmp(ptr, wanted, strlen(wanted)) == 0) {
found = true;
break;
}
} while(*ptr++);
if(found == false) {
if(state->verbose) {
fprintf(stderr, "Skipping reader '%s' since it doesn't match '%s'.\n", reader_ptr, wanted);
}
continue;
}
}
if(state->verbose) {
fprintf(stderr, "Connect reader '%s' matching '%s'.\n", reader_ptr, wanted);
}
rc = SCardConnect(state->context, reader_ptr, SCARD_SHARE_SHARED,
SCARD_PROTOCOL_T0|SCARD_PROTOCOL_T1, &card, &state->protocol);
if(rc == SCARD_S_SUCCESS) {
strncpy(state->reader, reader_ptr, sizeof(state->reader));
state->reader[sizeof(state->reader) - 1] = 0;
if(state->verbose > 2) {
fprintf(stderr, "SCardConnect succeeded for '%s', protocol=%lx\n", reader_ptr, (unsigned long)state->protocol);
}
break;
}
if(state->verbose) {
fprintf(stderr, "SCardConnect failed for '%s', rc=%lx\n", reader_ptr, (long)rc);
}
}
if(*reader_ptr == '\0') {
if(state->verbose) {
fprintf(stderr, "No usable reader found matching '%s'.\n", wanted);
}
SCardReleaseContext(state->context);
state->context = (SCARDCONTEXT)-1;
return YKPIV_PCSC_ERROR;
}
}
// at this point, card should not equal state->card, to allow _ykpiv_connect() to determine device type
if (YKPIV_OK == _ykpiv_connect(state, state->context, card)) {
/*
* Select applet. This is done here instead of in _ykpiv_connect() because
* you may not want to select the applet when connecting to a card handle that
* was supplied by an external library.
*/
if (YKPIV_OK != (ret = _ykpiv_begin_transaction(state))) return ret;
#if ENABLE_APPLICATION_RESELECTION
ret = _ykpiv_ensure_application_selected(state);
#else
ret = _ykpiv_select_application(state);
#endif
_ykpiv_end_transaction(state);
return ret;
}
return YKPIV_GENERIC_ERROR;
}
ykpiv_rc ykpiv_list_readers(ykpiv_state *state, char *readers, size_t *len) {
pcsc_word num_readers = 0;
pcsc_long rc;
if(SCardIsValidContext(state->context) != SCARD_S_SUCCESS) {
rc = SCardEstablishContext(SCARD_SCOPE_SYSTEM, NULL, NULL, &state->context);
if (rc != SCARD_S_SUCCESS) {
if(state->verbose) {
fprintf (stderr, "SCardEstablishContext failed, rc=%lx\n", (long)rc);
}
return YKPIV_PCSC_ERROR;
}
}
rc = SCardListReaders(state->context, NULL, NULL, &num_readers);
if (rc != SCARD_S_SUCCESS) {
if(state->verbose) {
fprintf (stderr, "SCardListReaders failed, rc=%lx\n", (long)rc);
}
if(rc == SCARD_E_NO_READERS_AVAILABLE) {
*readers = 0;
*len = 1;
return YKPIV_OK;
}
SCardReleaseContext(state->context);
state->context = (SCARDCONTEXT)-1;
return YKPIV_PCSC_ERROR;
}
if (num_readers > *len) {
num_readers = (pcsc_word)*len;
} else if (num_readers < *len) {
*len = (size_t)num_readers;
}
rc = SCardListReaders(state->context, NULL, readers, &num_readers);
if (rc != SCARD_S_SUCCESS)
{
if(state->verbose) {
fprintf (stderr, "SCardListReaders failed, rc=%lx\n", (long)rc);
}
SCardReleaseContext(state->context);
state->context = (SCARDCONTEXT)-1;
return YKPIV_PCSC_ERROR;
}
*len = num_readers;
return YKPIV_OK;
}
ykpiv_rc _ykpiv_begin_transaction(ykpiv_state *state) {
#if ENABLE_IMPLICIT_TRANSACTIONS
int retries = 0;
pcsc_long rc = SCardBeginTransaction(state->card);
if (rc != SCARD_S_SUCCESS) {
retries++;
if(state->verbose) {
fprintf(stderr, "SCardBeginTransaction on card #%u failed, rc=%lx\n", state->serial, (long)rc);
}
if (SCardIsValidContext(state->context) != SCARD_S_SUCCESS || (rc != SCARD_W_RESET_CARD && rc != SCARD_W_REMOVED_CARD)) {
pcsc_long rc2 = SCardDisconnect(state->card, SCARD_RESET_CARD);
if(state->verbose) {
fprintf(stderr, "SCardDisconnect on card #%u rc=%lx\n", state->serial, (long)rc2);
}
state->card = 0;
}
if (SCardIsValidContext(state->context) != SCARD_S_SUCCESS || rc == SCARD_E_NO_SERVICE) {
rc = SCardReleaseContext(state->context);
if(state->verbose) {
fprintf(stderr, "SCardReleaseContext on card #%u rc=%lx\n", state->serial, (long)rc);
}
state->context = 0;
rc = SCardEstablishContext(SCARD_SCOPE_SYSTEM, NULL, NULL, &state->context);
if(state->verbose) {
fprintf(stderr, "SCardEstablishContext on card #%u rc=%lx\n", state->serial, (long)rc);
}
if(rc != SCARD_S_SUCCESS) {
return YKPIV_PCSC_ERROR;
}
}
if(state->card) {
rc = SCardReconnect(state->card, SCARD_SHARE_SHARED,
SCARD_PROTOCOL_T0|SCARD_PROTOCOL_T1, SCARD_RESET_CARD, &state->protocol);
if(state->verbose) {
fprintf(stderr, "SCardReconnect on card #%u rc=%lx\n", state->serial, (long)rc);
}
if(rc != SCARD_S_SUCCESS) {
return YKPIV_PCSC_ERROR;
}
} else {
rc = SCardConnect(state->context, state->reader, SCARD_SHARE_SHARED,
SCARD_PROTOCOL_T0|SCARD_PROTOCOL_T1, &state->card, &state->protocol);
if(state->verbose) {
fprintf(stderr, "SCardConnect on reader %s card #%u rc=%lx\n", state->reader, state->serial, (long)rc);
}
if(rc != SCARD_S_SUCCESS) {
return YKPIV_PCSC_ERROR;
}
}
rc = SCardBeginTransaction(state->card);
if (rc != SCARD_S_SUCCESS) {
if(state->verbose) {
fprintf(stderr, "SCardBeginTransaction on card #%u failed, rc=%lx\n", state->serial, (long)rc);
}
return YKPIV_PCSC_ERROR;
}
}
if(retries) {
uint32_t serial = state->serial;
state->serial = 0;
state->ver.major = 0;
state->ver.minor = 0;
state->ver.patch = 0;
ykpiv_rc res;
if ((res = _ykpiv_select_application(state)) != YKPIV_OK)
return res;
if(state->serial != serial) {
if(state->verbose) {
fprintf(stderr, "Card #%u detected, was expecting card #%u\n", state->serial, serial);
}
return YKPIV_GENERIC_ERROR;
}
if(state->mgm_key) {
if((res = _ykpiv_authenticate2(state, state->mgm_key, state->mgm_len)) != YKPIV_OK)
return res;
}
if (state->pin) {
if((res = _ykpiv_verify(state, state->pin, strlen(state->pin))) != YKPIV_OK)
return res;
// De-authenticate always-authenticate keys by running an arbitrary command
unsigned char data[80] = {0};
unsigned long recv_len = sizeof(data);
if((res = _ykpiv_fetch_object(state, YKPIV_OBJ_DISCOVERY, data, &recv_len)) != YKPIV_OK)
return res;
}
}
#endif /* ENABLE_IMPLICIT_TRANSACTIONS */
return YKPIV_OK;
}
ykpiv_rc _ykpiv_end_transaction(ykpiv_state *state) {
#if ENABLE_IMPLICIT_TRANSACTIONS
pcsc_long rc = SCardEndTransaction(state->card, SCARD_LEAVE_CARD);
if(rc != SCARD_S_SUCCESS && state->verbose) {
fprintf(stderr, "SCardEndTransaction on card #%u failed, rc=%lx\n", state->serial, (long)rc);
// Ending the transaction can only fail because it's already ended - it's ended now either way so we don't fail here
}
#endif /* ENABLE_IMPLICIT_TRANSACTIONS */
return YKPIV_OK;
}
static const SCARD_IO_REQUEST* _pci(pcsc_word protocol) {
switch (protocol) {
case SCARD_PROTOCOL_T0:
return SCARD_PCI_T0;
case SCARD_PROTOCOL_T1:
return SCARD_PCI_T1;
case SCARD_PROTOCOL_RAW:
return SCARD_PCI_RAW;
default:
return NULL;
}
}
static ykpiv_rc _send_tpdu(ykpiv_state *state, const unsigned char *send_data, pcsc_word send_len,
unsigned char *recv_data, pcsc_word *recv_len, int *sw) {
if(state->verbose > 1) {
fprintf(stderr, "> ");
dump_hex(send_data, send_len);
fprintf(stderr, " (%zu)\n", (size_t)send_len);
}
pcsc_long rc = SCardTransmit(state->card, _pci(state->protocol), send_data, send_len, NULL, recv_data, recv_len);
if(rc != SCARD_S_SUCCESS) {
if(state->verbose) {
fprintf (stderr, "SCardTransmit on card #%u failed, rc=%lx\n", state->serial, (long)rc);
}
return YKPIV_PCSC_ERROR;
}
if(state->verbose > 1) {
fprintf(stderr, "< ");
dump_hex(recv_data, *recv_len);
fprintf(stderr, " (%zu)\n", (size_t)*recv_len);
}
if(*recv_len >= 2) {
*sw = (recv_data[*recv_len - 2] << 8) | recv_data[*recv_len - 1];
*recv_len -= 2;
} else {
*sw = 0;
}
return YKPIV_OK;
}
ykpiv_rc _ykpiv_transfer_data(ykpiv_state *state,
const unsigned char *templ,
const unsigned char *in_data,
unsigned long in_len,
unsigned char *out_data,
unsigned long *out_len,
int *sw) {
const unsigned char *in_ptr = in_data;
unsigned long max_out = *out_len;
ykpiv_rc res = YKPIV_OK;
*out_len = 0;
do {
APDU apdu = {templ[0], templ[1], templ[2], templ[3], 0xff};
unsigned char data[261] = {0};
if(in_ptr + apdu.st.lc < in_data + in_len) {
apdu.st.cla |= 0x10;
} else {
apdu.st.lc = (uint8_t)((in_data + in_len) - in_ptr);
}
if(apdu.st.lc) {
memcpy(apdu.st.data, in_ptr, apdu.st.lc);
in_ptr += apdu.st.lc;
}
unsigned char send_len = apdu.st.lc;
Retry:
if(state->verbose > 2) {
fprintf(stderr, "Going to send %u bytes in this go.\n", send_len);
}
pcsc_word recv_len = sizeof(data);
res = _send_tpdu(state, apdu.raw, send_len + 5, data, &recv_len, sw);
if(res != YKPIV_OK) {
goto Cleanup;
}
// Case 2S.3 — Process aborted; Ne not accepted, Na indicated
if(*sw >> 8 == 0x6c) {
apdu.st.lc = *sw & 0xff;
goto Retry;
}
if(*sw != SW_SUCCESS && *sw >> 8 != 0x61) {
goto Cleanup;
}
if(*out_len + recv_len > max_out) {
if(state->verbose) {
fprintf(stderr, "Output buffer to small, wanted to write %lu, max was %lu.\n", *out_len + recv_len, max_out);
}
res = YKPIV_SIZE_ERROR;
goto Cleanup;
}
if(out_data) {
memcpy(out_data, data, recv_len);
out_data += recv_len;
*out_len += recv_len;
}
} while(in_ptr < in_data + in_len);
while(*sw >> 8 == 0x61) {
unsigned char tpdu[] = {0, YKPIV_INS_GET_RESPONSE_APDU, 0, 0, *sw & 0xff};
unsigned char data[261] = {0};
if(state->verbose > 2) {
fprintf(stderr, "The card indicates there is %u bytes more data for us.\n", tpdu[4] ? tpdu[4] : 0x100);
}
pcsc_word recv_len = sizeof(data);
res = _send_tpdu(state, tpdu, sizeof(tpdu), data, &recv_len, sw);
if(res != YKPIV_OK) {
goto Cleanup;
} else if(*sw != SW_SUCCESS && *sw >> 8 != 0x61) {
goto Cleanup;
}
if(*out_len + recv_len > max_out) {
if(state->verbose) {
fprintf(stderr, "Output buffer to small, wanted to write %lu, max was %lu.", *out_len + recv_len, max_out);
}
res = YKPIV_SIZE_ERROR;
goto Cleanup;
}
if(out_data) {
memcpy(out_data, data, recv_len);
out_data += recv_len;
*out_len += recv_len;
}
}
Cleanup:
return res;
}
ykpiv_rc ykpiv_transfer_data(ykpiv_state *state, const unsigned char *templ,
const unsigned char *in_data, long in_len,
unsigned char *out_data, unsigned long *out_len, int *sw) {
ykpiv_rc res;
if ((res = _ykpiv_begin_transaction(state)) != YKPIV_OK) {
*out_len = 0;
return res;
}
res = _ykpiv_transfer_data(state, templ, in_data, in_len, out_data, out_len, sw);
_ykpiv_end_transaction(state);
return res;
}
ykpiv_rc _ykpiv_send_apdu(ykpiv_state *state, APDU *apdu,
unsigned char *data, unsigned long *recv_len, int *sw) {
return _ykpiv_transfer_data(state, apdu->raw, apdu->st.data, apdu->st.lc, data, recv_len, sw);
}
static ykpiv_rc _ykpiv_get_metadata(ykpiv_state *state, const unsigned char key, unsigned char *data, unsigned long *data_len) {
ykpiv_rc res;
unsigned char templ[] = {0, YKPIV_INS_GET_METADATA, 0, key};
int sw = 0;
if (state == NULL || data == NULL || data_len == NULL) {
return YKPIV_ARGUMENT_ERROR;
}
if ((res = _ykpiv_transfer_data(state, templ, NULL, 0, data, data_len, &sw)) != YKPIV_OK) {
goto Cleanup;
}
if (SW_SUCCESS != sw) {
res = YKPIV_GENERIC_ERROR;
if (SW_ERR_NOT_SUPPORTED == sw) {
res = YKPIV_NOT_SUPPORTED;
}
if (SW_ERR_REFERENCE_NOT_FOUND == sw) {
res = YKPIV_KEY_ERROR;
}
if (SW_ERR_INCORRECT_PARAM == sw) {
res = YKPIV_ARGUMENT_ERROR;
}
}
Cleanup:
return res;
}
ykpiv_rc ykpiv_authenticate(ykpiv_state *state, unsigned const char *key) {
return ykpiv_authenticate2(state, key, DES_LEN_3DES);
}
ykpiv_rc ykpiv_authenticate2(ykpiv_state *state, unsigned const char *key, size_t len) {
ykpiv_rc res;
if (NULL == state) return YKPIV_GENERIC_ERROR;
if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return res;
if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup;
res = _ykpiv_authenticate2(state, key, len);
Cleanup:
_ykpiv_end_transaction(state);
return res;
}
static ykpiv_rc _ykpiv_authenticate2(ykpiv_state *state, unsigned const char *key, size_t len) {
if (NULL == state)
return YKPIV_GENERIC_ERROR;
if (NULL == key) {
key = (unsigned const char*)YKPIV_MGM_DEFAULT;
len = DES_LEN_3DES;
}
ykpiv_metadata metadata = {YKPIV_ALGO_3DES};
unsigned char data[261] = {0};
unsigned long recv_len = sizeof(data);
ykpiv_rc res = _ykpiv_get_metadata(state, YKPIV_KEY_CARDMGM, data, &recv_len);
if (res == YKPIV_OK) {
res = ykpiv_util_parse_metadata(data, recv_len, &metadata);
if (res != YKPIV_OK) {
return res;
}
}
/* set up our key */
cipher_key mgm_key = NULL;
cipher_rc drc = cipher_import_key(metadata.algorithm, key, (uint32_t)len, &mgm_key);
if (drc != CIPHER_OK) {
if(state->verbose) {
fprintf(stderr, "%s: cipher_import_key: %d\n", ykpiv_strerror(YKPIV_ALGORITHM_ERROR), drc);
}
res = YKPIV_ALGORITHM_ERROR;
goto Cleanup;
}
/* get a challenge from the card */
{
int sw = 0;
APDU apdu = {0};
recv_len = sizeof(data);
apdu.st.ins = YKPIV_INS_AUTHENTICATE;
apdu.st.p1 = metadata.algorithm;
apdu.st.p2 = YKPIV_KEY_CARDMGM; /* management key */