This repository has been archived by the owner on May 16, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
esteidcm.cpp
1785 lines (1674 loc) · 65.4 KB
/
esteidcm.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
/*
* EstEID Minidriver
*
* This software is released under either the GNU Library General Public
* License (see LICENSE.LGPL) or the BSD License (see LICENSE.BSD).
*
* Note that the only valid version of the LGPL license as far as this
* project is concerned is the original GNU Library General Public License
* Version 2.1, February 1999
*
*/
#include "stdafx.h"
#define AUTH_PIN_ID ROLE_USER
#define SIGN_PIN_ID 3
#define PUKK_PIN_ID ROLE_ADMIN
#define AUTH_CONTAINER_INDEX 0
#define SIGN_CONTAINER_INDEX 1
#define RETURN(X) return logreturn(__FUNCTION__, __FILE__, __LINE__, #X, X)
#define SC(API, ...) SCCall(__FILE__, __LINE__, "SCard"#API, SCard##API, __VA_ARGS__)
#define _log(...) log(__FUNCTION__, __FILE__, __LINE__, __VA_ARGS__)
#define DECLARE_UNSUPPORTED(name) DWORD WINAPI name { RETURN(SCARD_E_UNSUPPORTED_FEATURE); }
static const BYTE cardapps[] = { 1, 'm', 's', 'c', 'p', 0, 0, 0, 0 };
static const BYTE cardcf[] = { 0, 0, 0, 0, 0, 0 };
using namespace std;
enum DRIVER_FEATURES {
FEATURE_VERIFY_PIN_START = 0x01,
FEATURE_VERIFY_PIN_FINISH = 0x02,
FEATURE_MODIFY_PIN_START = 0x03,
FEATURE_MODIFY_PIN_FINISH = 0x04,
FEATURE_GET_KEY_PRESSED = 0x05,
FEATURE_VERIFY_PIN_DIRECT = 0x06,
FEATURE_MODIFY_PIN_DIRECT = 0x07,
FEATURE_MCT_READER_DIRECT = 0x08,
FEATURE_MCT_UNIVERSAL = 0x09,
FEATURE_IFD_PIN_PROPERTIES = 0x0A,
FEATURE_ABORT = 0x0B,
FEATURE_SET_SPE_MESSAGE = 0x0C,
FEATURE_VERIFY_PIN_DIRECT_APP_ID = 0x0D,
FEATURE_MODIFY_PIN_DIRECT_APP_ID = 0x0E,
FEATURE_WRITE_DISPLAY = 0x0F,
FEATURE_GET_KEY = 0x10,
FEATURE_IFD_DISPLAY_PROPERTIES = 0x11,
FEATURE_GET_TLV_PROPERTIES = 0x12,
FEATURE_CCID_ESC_COMMAND = 0x13
};
#pragma pack(push, 1)
typedef struct
{
uint8_t bTimerOut;
uint8_t bTimerOut2;
uint8_t bmFormatString;
uint8_t bmPINBlockString;
uint8_t bmPINLengthFormat;
uint16_t wPINMaxExtraDigit;
uint8_t bEntryValidationCondition;
uint8_t bNumberMessage;
uint16_t wLangId;
uint8_t bMsgIndex;
uint8_t bTeoPrologue[3];
uint32_t ulDataLength;
uint8_t abData[1];
} PIN_VERIFY_STRUCTURE;
typedef struct
{
uint8_t bTimerOut;
uint8_t bTimerOut2;
uint8_t bmFormatString;
uint8_t bmPINBlockString;
uint8_t bmPINLengthFormat;
uint8_t bInsertionOffsetOld;
uint8_t bInsertionOffsetNew;
uint16_t wPINMaxExtraDigit;
uint8_t bConfirmPIN;
uint8_t bEntryValidationCondition;
uint8_t bNumberMessage;
uint16_t wLangId;
uint8_t bMsgIndex1;
uint8_t bMsgIndex2;
uint8_t bMsgIndex3;
uint8_t bTeoPrologue[3];
uint32_t ulDataLength;
uint8_t abData[1];
} PIN_MODIFY_STRUCTURE;
#pragma pack(pop)
typedef struct
{
PUBLICKEYSTRUC publickeystruc;
RSAPUBKEY rsapubkey;
} PUBKEYSTRUCT, *PPUBKEYSTRUCT;
typedef struct
{
HWND hwndParentWindow, windowHandle;
PIN_ID pinId;
LANGID langId;
} EXTERNAL_INFO, *PEXTERNAL_INFO;
struct Files
{
bool pinpadEnabled = true;
BYTE cardid[16];
PCCERT_CONTEXT auth = nullptr, sign = nullptr;
HWND cp = nullptr;
map<byte, vector<byte>> dhAgreements;
};
struct Result {
byte SW1, SW2; vector<byte> data;
bool operator !() const { return !(SW1 == 0x90 && SW2 == 0x00); }
};
static int32_t ntohl(int32_t source)
{
return 0
| ((source & 0x000000ff) << 24)
| ((source & 0x0000ff00) << 8)
| ((source & 0x00ff0000) >> 8)
| ((source & 0xff000000) >> 24);
}
static void log(const char *functionName, const char *fileName, int lineNumber, string message, ...)
{
static const wstring path = []{
wstring path(MAX_PATH, 0);
DWORD size = GetTempPathW(DWORD(path.size()), &path[0]);
path.resize(size);
path += L"\\esteidcm.log";
return path;
}();
if (_waccess(path.c_str(), 2) == -1)
return;
FILE *log = _wfsopen(path.c_str(), L"a", _SH_DENYNO);
if (!log)
return;
fprintf(log, "[%s:%i] %s() ", fileName, lineNumber, functionName);
va_list args;
va_start(args, message);
vfprintf(log, message.c_str(), args);
va_end(args);
fprintf(log, "\n");
fclose(log);
}
static DWORD logreturn(const char *functionName, const char *fileName, int lineNumber, const char *resultstr, DWORD result)
{
log(functionName, fileName, lineNumber, "Returning %s", resultstr);
return result;
}
template <typename Func, typename... Args>
LONG SCCall(const char *fileName, int lineNumber, const char *function, Func func, Args... args)
{
LONG err = func(args...);
log(function, fileName, lineNumber, "%X", err);
return err;
}
static string toHex(const vector<byte> &data)
{
stringstream os;
os << hex << setfill('0');
for (const byte &i: data)
os << setw(2) << static_cast<int>(i);
return os.str();
}
static Result transfer(const vector<byte> &apdu, SCARDHANDLE card)
{
vector<byte> data(1024, 0);
DWORD size = DWORD(data.size());
DWORD dwProtocol = 0;
SC(Status, card, nullptr, nullptr, nullptr, &dwProtocol, nullptr, nullptr);
_log("> " + toHex(apdu));
DWORD ret = SC(Transmit, card, dwProtocol == SCARD_PROTOCOL_T0 ? SCARD_PCI_T0 : SCARD_PCI_T1,
apdu.data(), DWORD(apdu.size()), nullptr, data.data(), &size);
if (ret != SCARD_S_SUCCESS)
return{ 0, 0, vector<byte>() };
Result result = { data[size - 2], data[size - 1], data };
result.data.resize(size - 2);
_log("< %02x%02x " + toHex(result.data), result.SW1, result.SW2);
if (result.SW1 == 0x61)
{
Result result2 = transfer({ 0x00, 0xC0, 0x00, 0x00, result.SW2 }, card);
result2.data.insert(result2.data.begin(), result.data.begin(), result.data.end());
return result2;
}
return result;
}
static map<DRIVER_FEATURES, uint32_t> features(SCARDHANDLE card)
{
map<DRIVER_FEATURES, uint32_t> result;
DWORD size = 0;
BYTE feature[256];
LONG rv = SC(Control, card, SCARD_CTL_CODE(3400), nullptr, 0, feature, DWORD(sizeof(feature)), &size);
if (rv == SCARD_W_RESET_CARD)
{
rv = SC(Reconnect, card, SCARD_SHARE_SHARED, SCARD_PROTOCOL_T0|SCARD_PROTOCOL_T1, SCARD_LEAVE_CARD, nullptr);
if (rv != SCARD_S_SUCCESS)
return result;
rv = SC(Control, card, SCARD_CTL_CODE(3400), nullptr, 0, feature, DWORD(sizeof(feature)), &size);
}
if (rv != SCARD_S_SUCCESS)
return result;
for (BYTE *p = feature; DWORD(p - feature) < size;)
{
int tag = *p++, len = *p++, value = 0;
for (int i = 0; i < len; ++i)
value |= *p++ << 8 * i;
result[DRIVER_FEATURES(tag)] = ntohl(value);
}
return result;
}
static Result transferCTL(const vector<byte> &apdu, bool verify, uint32_t lang, short minlen, SCARDHANDLE card)
{
map<DRIVER_FEATURES, uint32_t> f = features(card);
if (f.empty())
return { 0, 0, vector<byte>() };
struct {
uint16_t wLcdLayout;
uint8_t bEntryValidationCondition;
uint8_t bTimeOut2;
} pin_properties = { 0, 0, 0 };
DWORD size = sizeof(pin_properties);
auto ioctl = f.find(FEATURE_IFD_PIN_PROPERTIES);
if (ioctl != f.cend())
SC(Control, card, ioctl->second, nullptr, 0, &pin_properties, size, &size);
#define SET(X) \
X->bTimerOut = 30; \
X->bTimerOut2 = 30; \
X->bmFormatString = 0x02; \
X->bmPINBlockString = 0x00; \
X->bmPINLengthFormat = 0x00; \
X->wPINMaxExtraDigit = (minlen << 8) + 12; \
X->bEntryValidationCondition = 0x02; \
X->wLangId = lang; \
X->bTeoPrologue[0] = 0x00; \
X->bTeoPrologue[1] = 0x00; \
X->bTeoPrologue[2] = 0x00
vector<byte> cmd;
if (verify)
{
cmd.resize(sizeof(PIN_VERIFY_STRUCTURE) - 1);
PIN_VERIFY_STRUCTURE *data = (PIN_VERIFY_STRUCTURE*)cmd.data();
SET(data);
data->bNumberMessage = pin_properties.wLcdLayout > 0 ? 0xFF : 0x00;
data->bMsgIndex = 0x00;
data->ulDataLength = uint32_t(apdu.size());
}
else
{
cmd.resize(sizeof(PIN_MODIFY_STRUCTURE) - 1);
PIN_MODIFY_STRUCTURE *data = (PIN_MODIFY_STRUCTURE*)cmd.data();
SET(data);
data->bNumberMessage = pin_properties.wLcdLayout > 0 ? 0x03 : 0x00;
data->bInsertionOffsetOld = 0x00;
data->bInsertionOffsetNew = 0x00;
data->bConfirmPIN = 0x03;
data->bMsgIndex1 = 0x00;
data->bMsgIndex2 = 0x01;
data->bMsgIndex3 = 0x02;
data->ulDataLength = uint32_t(apdu.size());
}
cmd.insert(cmd.cend(), apdu.cbegin(), apdu.cend());
ioctl = f.find(verify ? FEATURE_VERIFY_PIN_START : FEATURE_MODIFY_PIN_START);
if (ioctl == f.cend())
ioctl = f.find(verify ? FEATURE_VERIFY_PIN_DIRECT : FEATURE_MODIFY_PIN_DIRECT);
_log("> " + toHex(apdu));
_log("CTL> " + toHex(cmd));
vector<byte> data(255 + 3, 0);
size = DWORD(data.size());
DWORD err = SC(Control, card, ioctl->second, cmd.data(), DWORD(cmd.size()), LPVOID(data.data()), DWORD(data.size()), &size);
if (err != SCARD_S_SUCCESS)
return { 0, 0, vector<byte>() };
ioctl = f.find(verify ? FEATURE_VERIFY_PIN_FINISH : FEATURE_MODIFY_PIN_FINISH);
if (ioctl != f.cend())
{
size = DWORD(data.size());
err = SC(Control, card, ioctl->second, nullptr, 0, LPVOID(data.data()), DWORD(data.size()), &size);
if (err != SCARD_S_SUCCESS)
return{ 0, 0, vector<byte>() };
}
Result result = { data[size - 2], data[size - 1], data };
result.data.resize(size - 2);
_log("< %02x%02x " + toHex(result.data), result.SW1, result.SW2);
return result;
}
static PPUBKEYSTRUCT pubKeyRSAStruct(PCARD_DATA pCardData, PCCERT_CONTEXT cer, DWORD &sw, ALG_ID algID)
{
PCRYPT_BIT_BLOB PublicKey = &cer->pCertInfo->SubjectPublicKeyInfo.PublicKey;
CryptDecodeObject(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, RSA_CSP_PUBLICKEYBLOB,
PublicKey->pbData, PublicKey->cbData, 0, nullptr, &sw);
PPUBKEYSTRUCT oh = PPUBKEYSTRUCT(pCardData->pfnCspAlloc(sw));
if (!oh)
return nullptr;
CryptDecodeObject(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, RSA_CSP_PUBLICKEYBLOB,
PublicKey->pbData, PublicKey->cbData, 0, LPVOID(oh), &sw);
oh->publickeystruc.aiKeyAlg = algID;
return oh;
}
static bool isECDSAPubKey(PCCERT_CONTEXT cert)
{
return strcmp(szOID_ECC_PUBLIC_KEY, cert->pCertInfo->SubjectPublicKeyInfo.Algorithm.pszObjId) == 0;
}
static DWORD keySize(PCARD_DATA pCardData, PCCERT_CONTEXT cert)
{
if (isECDSAPubKey(cert))
return (cert->pCertInfo->SubjectPublicKeyInfo.PublicKey.cbData - 1) * 4;
else
{
DWORD size = 2048;
DWORD sw = 0;
PPUBKEYSTRUCT oh = pubKeyRSAStruct(pCardData, cert, sw, 0);
if (!oh)
return size;
size = oh->rsapubkey.bitlen;
pCardData->pfnCspFree(oh);
return size;
}
}
static PBCRYPT_ECCKEY_BLOB pubKeyECStruct(PCARD_DATA pCardData, PCCERT_CONTEXT cert, DWORD &sw, bool ecdsa)
{
PCRYPT_BIT_BLOB PublicKey = &cert->pCertInfo->SubjectPublicKeyInfo.PublicKey;
sw = DWORD(sizeof(BCRYPT_ECCKEY_BLOB) + (PublicKey->cbData - 1));
PBCRYPT_ECCKEY_BLOB oh = PBCRYPT_ECCKEY_BLOB(pCardData->pfnCspAlloc(sw));
if (!oh)
return nullptr;
oh->cbKey = (PublicKey->cbData - 1) / 2;
oh->dwMagic = ecdsa ? BCRYPT_ECDSA_PUBLIC_P384_MAGIC : BCRYPT_ECDH_PUBLIC_P384_MAGIC;
CopyMemory(PBYTE(oh) + sizeof(BCRYPT_ECCKEY_BLOB), PublicKey->pbData + 1, PublicKey->cbData - 1);
return oh;
}
static vector<byte> md5sum(const string &data)
{
vector<byte> result(16, 0);
BCRYPT_ALG_HANDLE hAlgorithm = 0;
BCRYPT_HASH_HANDLE hHash = 0;
if (BCryptOpenAlgorithmProvider(&hAlgorithm, BCRYPT_MD5_ALGORITHM, MS_PRIMITIVE_PROVIDER, 0) ||
BCryptCreateHash(hAlgorithm, &hHash, nullptr, 0, nullptr, 0, 0) ||
BCryptHashData(hHash, PBYTE(data.c_str()), DWORD(data.size()), 0) ||
BCryptFinishHash(hHash, result.data(), ULONG(result.size()), 0))
result.clear();
if (hHash)
BCryptDestroyHash(hHash);
if (hAlgorithm)
BCryptCloseAlgorithmProvider(hAlgorithm, 0);
return result;
}
static void getMD5GUID(const string &data, PWCHAR guid)
{
string result = toHex(md5sum(data));
for (size_t i = 0; i < result.size(); ++i)
guid[i] = result[i];
}
static map<uint8_t, vector<byte>> parseFCI(const vector<byte> &data)
{
map<uint8_t, vector<byte>> result;
for (vector<byte>::const_iterator i = data.cbegin(); i != data.cend(); ++i)
{
uint8_t tag(*i), size(*++i);
result[tag] = size > 0 ? vector<byte>(i + 1, i + 1 + size) : vector<byte>();
switch (tag)
{
case 0x6F:
case 0x62:
case 0x64:
case 0xA1: continue;
default: i += size; break;
}
}
return result;
}
static bool isPinPad(PCARD_DATA pCardData)
{
Files *files = (Files*)pCardData->pvVendorSpecific;
if (!files->pinpadEnabled)
return false;
map<DRIVER_FEATURES, uint32_t> f = features(pCardData->hScard);
return f.find(FEATURE_VERIFY_PIN_DIRECT) != f.cend() || f.find(FEATURE_VERIFY_PIN_START) != f.cend();
}
DWORD WINAPI CreateProgressBar(LPVOID lpParam)
{
PEXTERNAL_INFO externalInfo = PEXTERNAL_INFO(lpParam);
TASKDIALOGCONFIG config = { 0 };
config.cbSize = sizeof(config);
config.hwndParent = externalInfo->hwndParentWindow;
config.hInstance = GetModuleHandle(nullptr);
config.dwCommonButtons = TDCBF_CANCEL_BUTTON;
config.pszMainIcon = TD_INFORMATION_ICON;
config.dwFlags = TDF_EXPAND_FOOTER_AREA | TDF_SHOW_PROGRESS_BAR | TDF_CALLBACK_TIMER;
config.lpCallbackData = LONG_PTR(externalInfo);
config.pfCallback = [](HWND hwnd, UINT uNotification, WPARAM wParam, LPARAM lParam, LONG_PTR dwRefData) {
PEXTERNAL_INFO externalInfo = PEXTERNAL_INFO(dwRefData);
externalInfo->windowHandle = hwnd;
switch (uNotification)
{
case TDN_CREATED:
SendMessage(hwnd, TDM_SET_PROGRESS_BAR_STATE, 0x0003, 0);
SendMessage(hwnd, TDM_SET_PROGRESS_BAR_POS, 100, 0L);
SendMessage(hwnd, TDM_SET_PROGRESS_BAR_STATE, 0x0001, 0);
break;
case TDN_TIMER:
SendMessage(hwnd, TDM_SET_PROGRESS_BAR_POS, (100 - int(wParam) / 300), 0);
break;
case TDN_BUTTON_CLICKED:
SendMessage(hwnd, WM_NCDESTROY, 0, 0);
return S_FALSE;
}
return S_OK;
};
switch (PRIMARYLANGID(externalInfo->langId))
{
case LANG_ESTONIAN:
config.pszMainInstruction = L"PIN Pad kaardilugeja";
config.pszContent = L"Sisestage PIN";
switch (externalInfo->pinId)
{
case AUTH_PIN_ID:
config.pszContent = L"Palun sisestage isikutuvastuse PIN (PIN1)";
config.pszExpandedInformation = L"Valitud tegevuse jaoks on vaja kasutada isikutuvastuse sertifikaati. Sertifikaadi kasutamiseks sisesta PIN1 kaardilugeja sõrmistikult.";
break;
case SIGN_PIN_ID:
config.pszContent = L"Palun sisestage digiallkirjastamise PIN (PIN2)";
config.pszExpandedInformation = L"Valitud tegevuse jaoks on vaja kasutada allkirjastamise sertifikaati. Sertifikaadi kasutamiseks sisesta PIN2 kaardilugeja sõrmistikult.";
break;
default: break;
}
break;
case LANG_RUSSIAN:
config.pszMainInstruction = L"PIN Pad считыватель";
config.pszContent = L"Введите PIN код";
switch (externalInfo->pinId)
{
case AUTH_PIN_ID:
config.pszContent = L"Введите код PIN для идентификации (PIN 1)";
config.pszExpandedInformation = L"Данная операция требует сертификат идентификации. Для использования сертификата идентификации введите PIN1 с клавиатуры считывателя.";
break;
case SIGN_PIN_ID:
config.pszContent = L"Введите код PIN для подписи (PIN 2)";
config.pszExpandedInformation = L"Для данной операцин необходим сертификат подписи. Для использования сертификата подписи введите PIN2 с клавиатуры считывателя.";
break;
default: break;
}
break;
default:
config.pszMainInstruction = L"PIN Pad Reader";
config.pszContent = L"Enter PIN code";
switch (externalInfo->pinId)
{
case AUTH_PIN_ID:
config.pszContent = L"Enter PIN for authentication (PIN 1)";
config.pszExpandedInformation = L"Selected action requires authentication certificate. For using authentication certificate enter PIN1 at the reader.";
break;
case SIGN_PIN_ID:
config.pszContent = L"Enter PIN for digital signature (PIN 2)";
config.pszExpandedInformation = L"Selected action requires digital signature certificate. For using signature certificate enter PIN2 at the reader.";
break;
default: break;
}
break;
}
_log("Create Progress Dialog");
DWORD result = 0;
HMODULE h = LoadLibrary(L"comctl32.dll");
if (!h)
return result;
typedef HRESULT (WINAPI *f_TaskDialogIndirect)(_In_ const TASKDIALOGCONFIG *pTaskConfig,
_Out_opt_ int *pnButton, _Out_opt_ int *pnRadioButton, _Out_opt_ BOOL *pfVerificationFlagChecked);
if (f_TaskDialogIndirect f = f_TaskDialogIndirect(GetProcAddress(h, "TaskDialogIndirect")))
result = f(&config, nullptr, nullptr, nullptr);
FreeLibrary(h);
return result;
}
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
#ifdef _WIN64
_log("Loading esteidcm X64 version %s reason %u", FILE_VERSION_STR, ul_reason_for_call);
#else
_log("Loading esteidcm X86 version %s reason %u", FILE_VERSION_STR, ul_reason_for_call);
#endif
return TRUE;
}
DWORD WINAPI CardAcquireContext(__inout PCARD_DATA pCardData, __in DWORD dwFlags)
{
if (!pCardData)
RETURN(SCARD_E_INVALID_PARAMETER);
_log("dwVersion=%u, name=%S, hScard=0x%08X, hSCardCtx=0x%08X", pCardData->dwVersion, pCardData->pwszCardName,
pCardData->hScard, pCardData->hSCardCtx);
if (pCardData->dwVersion < CARD_DATA_VERSION_SEVEN)
RETURN(ERROR_REVISION_MISMATCH);
if (dwFlags ||
pCardData->cbAtr == 0 ||
pCardData->cbAtr == 0xffffffff ||
!pCardData->pbAtr ||
!pCardData->pwszCardName ||
!pCardData->pfnCspAlloc ||
!pCardData->pfnCspReAlloc ||
!pCardData->pfnCspFree)
RETURN(SCARD_E_INVALID_PARAMETER);
if (!pCardData->hScard)
RETURN(SCARD_E_INVALID_HANDLE);
static vector<vector<byte>> atrs{
{ 0x3B, 0xFE, 0x18, 0x00, 0x00, 0x80, 0x31, 0xFE, 0x45, 0x45, 0x73, 0x74, 0x45, 0x49, 0x44, 0x20, 0x76, 0x65, 0x72, 0x20, 0x31, 0x2E, 0x30, 0xA8 }, /*ESTEID_V3_COLD_DEV1_ATR*/
{ 0x3B, 0xFE, 0x18, 0x00, 0x00, 0x80, 0x31, 0xFE, 0x45, 0x80, 0x31, 0x80, 0x66, 0x40, 0x90, 0xA4, 0x56, 0x1B, 0x16, 0x83, 0x01, 0x90, 0x00, 0x86 }, /*ESTEID_V3_WARM_DEV1_ATR*/
{ 0x3B, 0xFE, 0x18, 0x00, 0x00, 0x80, 0x31, 0xFE, 0x45, 0x80, 0x31, 0x80, 0x66, 0x40, 0x90, 0xA4, 0x16, 0x2A, 0x00, 0x83, 0x01, 0x90, 0x00, 0xE1 }, /*ESTEID_V3_WARM_DEV2_ATR*/
{ 0x3B, 0xFE, 0x18, 0x00, 0x00, 0x80, 0x31, 0xFE, 0x45, 0x80, 0x31, 0x80, 0x66, 0x40, 0x90, 0xA4, 0x16, 0x2A, 0x00, 0x83, 0x0F, 0x90, 0x00, 0xEF }, /*ESTEID_V3_WARM_DEV3_ATR/ESTEID_V35_WARM_ATR*/
{ 0x3B, 0xFA, 0x18, 0x00, 0x00, 0x80, 0x31, 0xFE, 0x45, 0xFE, 0x65, 0x49, 0x44, 0x20, 0x2F, 0x20, 0x50, 0x4B, 0x49, 0x03 }, /*ESTEID_V35_COLD_ATR*/
};
if (!any_of(atrs.cbegin(), atrs.cend(), [&](const vector<byte> &atr){
return atr.size() == pCardData->cbAtr && equal(atr.cbegin(), atr.cend(), pCardData->pbAtr);
}))
RETURN(SCARD_E_UNKNOWN_CARD);
Result data;
if (!transfer({ 0x00, 0xA4, 0x00, 0x0C }, pCardData->hScard) ||
!transfer({ 0x00, 0xA4, 0x01, 0x0C, 0x02, 0xEE, 0xEE }, pCardData->hScard) ||
!transfer({ 0x00, 0xA4, 0x02, 0x0C, 0x02, 0x50, 0x44 }, pCardData->hScard) ||
!(data = transfer({ 0x00, 0xB2, 0x08, 0x04, 0x00 }, pCardData->hScard)))
RETURN(SCARD_E_FILE_NOT_FOUND);
auto readCert = [](const vector<byte> &file, SCARDHANDLE card) {
vector<byte> cert;
Result data;
if (!(data = transfer(file, card)))
return cert;
map<uint8_t, vector<byte>> fci = parseFCI(data.data);
map<uint8_t, vector<byte>>::const_iterator found = fci.find(0x85);
size_t size = found != fci.cend() ? found->second[0] << 8 | found->second[1] : 0x0600;
while (cert.size() < size)
{
Result data = transfer({ 0x00, 0xB0, byte(cert.size() >> 8), byte(cert.size()), 0x00 }, card);
if (!data)
return cert;
cert.insert(cert.end(), data.data.begin(), data.data.end());
}
return cert;
};
string cardid(data.data.cbegin(), data.data.cend());
vector<byte> auth = readCert({ 0x00, 0xA4, 0x02, 0x00, 0x02, 0xAA, 0xCE }, pCardData->hScard);
vector<byte> sign = readCert({ 0x00, 0xA4, 0x02, 0x00, 0x02, 0xDD, 0xCE }, pCardData->hScard);
if (cardid.length() < 8 || cardid.length() > 9 || auth.empty() || sign.empty())
RETURN(SCARD_E_FILE_NOT_FOUND);
_log("cardid: " + cardid);
Files *files = new Files;
pCardData->pvVendorSpecific = files;
if (!pCardData->pvVendorSpecific)
RETURN(ERROR_NOT_ENOUGH_MEMORY);
files->auth = CertCreateCertificateContext(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, auth.data(), DWORD(auth.size()));
files->sign = CertCreateCertificateContext(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, sign.data(), DWORD(sign.size()));
if (!files->auth || !files->sign)
RETURN(ERROR_NOT_ENOUGH_MEMORY);
ZeroMemory(files->cardid, sizeof(files->cardid));
CopyMemory(files->cardid, cardid.c_str(), cardid.size());
HKEY rootKey = nullptr;
DWORD lpData = 0;
DWORD lpSize = sizeof(lpData);
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"SOFTWARE\\RIA\\minidriver", 0, KEY_READ, &rootKey) == ERROR_SUCCESS &&
RegQueryValueEx(rootKey, L"disablepinpad", 0, nullptr, PBYTE(&lpData), &lpSize) == ERROR_SUCCESS &&
lpData > 0)
{
files->pinpadEnabled = false;
_log("Disabling pinpad by registry setting");
}
if (rootKey)
RegCloseKey(rootKey);
pCardData->dwVersion = CARD_DATA_VERSION_SEVEN;
pCardData->pfnCardDeleteContext = CardDeleteContext;
pCardData->pfnCardQueryCapabilities = CardQueryCapabilities;
pCardData->pfnCardDeleteContainer = CardDeleteContainer;
pCardData->pfnCardCreateContainer = CardCreateContainer;
pCardData->pfnCardGetContainerInfo = CardGetContainerInfo;
pCardData->pfnCardAuthenticatePin = CardAuthenticatePin;
pCardData->pfnCardGetChallenge = CardGetChallenge;
pCardData->pfnCardAuthenticateChallenge = CardAuthenticateChallenge;
pCardData->pfnCardUnblockPin = CardUnblockPin;
pCardData->pfnCardChangeAuthenticator = CardChangeAuthenticator;
pCardData->pfnCardDeauthenticate = nullptr;
pCardData->pfnCardCreateDirectory = CardCreateDirectory;
pCardData->pfnCardDeleteDirectory = CardDeleteDirectory;
pCardData->pvUnused3 = nullptr;
pCardData->pvUnused4 = nullptr;
pCardData->pfnCardCreateFile = CardCreateFile;
pCardData->pfnCardReadFile = CardReadFile;
pCardData->pfnCardWriteFile = CardWriteFile;
pCardData->pfnCardDeleteFile = CardDeleteFile;
pCardData->pfnCardEnumFiles = CardEnumFiles;
pCardData->pfnCardGetFileInfo = CardGetFileInfo;
pCardData->pfnCardQueryFreeSpace = CardQueryFreeSpace;
pCardData->pfnCardQueryKeySizes = CardQueryKeySizes;
pCardData->pfnCardSignData = CardSignData;
pCardData->pfnCardRSADecrypt = CardRSADecrypt;
pCardData->pfnCardConstructDHAgreement = isECDSAPubKey(files->auth) ? CardConstructDHAgreement : nullptr;
pCardData->pfnCardDeriveKey = isECDSAPubKey(files->auth) ? CardDeriveKey : nullptr;
pCardData->pfnCardDestroyDHAgreement = isECDSAPubKey(files->auth) ? CardDestroyDHAgreement : nullptr;
pCardData->pfnCspGetDHAgreement = nullptr;
pCardData->pfnCardGetChallengeEx = CardGetChallengeEx;
pCardData->pfnCardAuthenticateEx = CardAuthenticateEx;
pCardData->pfnCardChangeAuthenticatorEx = CardChangeAuthenticatorEx;
pCardData->pfnCardDeauthenticateEx = CardDeauthenticateEx;
pCardData->pfnCardGetContainerProperty = CardGetContainerProperty;
pCardData->pfnCardSetContainerProperty = CardSetContainerProperty;
pCardData->pfnCardGetProperty = CardGetProperty;
pCardData->pfnCardSetProperty = CardSetProperty;
//pCardData->pfnCspUnpadData = CspUnpadData;
pCardData->pfnMDImportSessionKey = MDImportSessionKey;
pCardData->pfnMDEncryptData = MDEncryptData;
pCardData->pfnCardImportSessionKey = CardImportSessionKey;
pCardData->pfnCardGetSharedKeyHandle = CardGetSharedKeyHandle;
pCardData->pfnCardGetAlgorithmProperty = CardGetAlgorithmProperty;
pCardData->pfnCardGetKeyProperty = CardGetKeyProperty;
pCardData->pfnCardSetKeyProperty = CardSetKeyProperty;
pCardData->pfnCardDestroyKey = CardDestroyKey;
pCardData->pfnCardProcessEncryptedData = CardProcessEncryptedData;
pCardData->pfnCardCreateContainerEx = CardCreateContainerEx;
RETURN(NO_ERROR);
}
DWORD WINAPI CardDeleteContext(__inout PCARD_DATA pCardData)
{
if (!pCardData)
RETURN(SCARD_E_INVALID_PARAMETER);
if (Files *files = (Files*)pCardData->pvVendorSpecific)
{
if (files->auth) CertFreeCertificateContext(files->auth);
if (files->sign) CertFreeCertificateContext(files->sign);
delete files;
}
RETURN(NO_ERROR);
}
DWORD WINAPI CardGetContainerProperty(__in PCARD_DATA pCardData, __in BYTE bContainerIndex, __in LPCWSTR wszProperty,
__out_bcount_part_opt(cbData, *pdwDataLen) PBYTE pbData, __in DWORD cbData, __out PDWORD pdwDataLen, __in DWORD dwFlags)
{
if (!pCardData)
RETURN(SCARD_E_INVALID_PARAMETER);
_log("bContainerIndex=%u, wszProperty=%S, cbData=%u, dwFlags=0x%08X", bContainerIndex, wszProperty, cbData, dwFlags);
if (!wszProperty || dwFlags || !pbData || !pdwDataLen)
RETURN(SCARD_E_INVALID_PARAMETER);
if (wcscmp(CCP_CONTAINER_INFO, wszProperty) == 0)
{
PCONTAINER_INFO p = PCONTAINER_INFO(pbData);
if (pdwDataLen)
*pdwDataLen = sizeof(*p);
if (cbData < sizeof(*p))
RETURN(ERROR_INSUFFICIENT_BUFFER);
return CardGetContainerInfo(pCardData, bContainerIndex, 0, p);
}
if (wcscmp(CCP_PIN_IDENTIFIER, wszProperty) == 0)
{
PPIN_ID p = PPIN_ID(pbData);
if (pdwDataLen)
*pdwDataLen = sizeof(*p);
if (cbData < sizeof(*p))
RETURN(ERROR_INSUFFICIENT_BUFFER);
switch (bContainerIndex)
{
case AUTH_CONTAINER_INDEX: *p = AUTH_PIN_ID; break;
case SIGN_CONTAINER_INDEX: *p = SIGN_PIN_ID; break;
default: RETURN(SCARD_E_NO_KEY_CONTAINER);
}
RETURN(NO_ERROR);
}
RETURN(SCARD_E_INVALID_PARAMETER);
}
DWORD WINAPI CardGetProperty(__in PCARD_DATA pCardData, __in LPCWSTR wszProperty,
__out_bcount_part_opt(cbData, *pdwDataLen) PBYTE pbData, __in DWORD cbData, __out PDWORD pdwDataLen, __in DWORD dwFlags)
{
_log("wszProperty=%S, cbData=%u, dwFlags=%u", wszProperty, cbData, dwFlags);
if (!pCardData || !wszProperty || !pbData || !pdwDataLen)
RETURN(SCARD_E_INVALID_PARAMETER);
if (wcscmp(CP_CARD_FREE_SPACE, wszProperty) == 0)
{
PCARD_FREE_SPACE_INFO p = PCARD_FREE_SPACE_INFO(pbData);
if (pdwDataLen)
*pdwDataLen = sizeof(*p);
if (cbData < sizeof(*p) - sizeof(DWORD)) // Ver 0 = 12, 1 = 16
RETURN(SCARD_E_INSUFFICIENT_BUFFER);
return CardQueryFreeSpace(pCardData, dwFlags, p);
}
if (wcscmp(CP_CARD_CAPABILITIES, wszProperty) == 0)
{
PCARD_CAPABILITIES p = PCARD_CAPABILITIES(pbData);
if (pdwDataLen)
*pdwDataLen = sizeof(*p);
if (cbData < sizeof(*p))
RETURN(SCARD_E_INSUFFICIENT_BUFFER);
return CardQueryCapabilities(pCardData, p);
}
if (wcscmp(CP_CARD_KEYSIZES, wszProperty) == 0)
{
PCARD_KEY_SIZES p = PCARD_KEY_SIZES(pbData);
if (pdwDataLen)
*pdwDataLen = sizeof(*p);
if (cbData < sizeof(*p))
RETURN(SCARD_E_INSUFFICIENT_BUFFER);
return CardQueryKeySizes(pCardData, dwFlags, 0, p);
}
if (wcscmp(CP_CARD_READ_ONLY, wszProperty) == 0)
{
if (dwFlags)
RETURN(SCARD_E_INVALID_PARAMETER);
PBOOL p = PBOOL(pbData);
if (pdwDataLen)
*pdwDataLen = sizeof(*p);
if (cbData < sizeof(*p))
RETURN(SCARD_E_INSUFFICIENT_BUFFER);
*p = TRUE;
RETURN(NO_ERROR);
}
if (wcscmp(CP_CARD_CACHE_MODE, wszProperty) == 0)
{
if (dwFlags)
RETURN(SCARD_E_INVALID_PARAMETER);
PDWORD p = PDWORD(pbData);
if (pdwDataLen)
*pdwDataLen = sizeof(*p);
if (cbData < sizeof(*p))
RETURN(SCARD_E_INSUFFICIENT_BUFFER);
*p = CP_CACHE_MODE_SESSION_ONLY;
RETURN(NO_ERROR);
}
if (wcscmp(CP_SUPPORTS_WIN_X509_ENROLLMENT, wszProperty) == 0)
{
if (dwFlags)
RETURN(SCARD_E_INVALID_PARAMETER);
PDWORD p = PDWORD(pbData);
if (pdwDataLen)
*pdwDataLen = sizeof(*p);
if (cbData < sizeof(*p))
RETURN(SCARD_E_INSUFFICIENT_BUFFER);
*p = 0;
RETURN(NO_ERROR);
}
if (wcscmp(CP_CARD_GUID, wszProperty) == 0 ||
wcscmp(CP_CARD_SERIAL_NO, wszProperty) == 0)
{
if (dwFlags)
RETURN(SCARD_E_INVALID_PARAMETER);
Files *files = (Files *)pCardData->pvVendorSpecific;
if (pdwDataLen)
*pdwDataLen = sizeof(files->cardid);
if (cbData < sizeof(files->cardid))
RETURN(SCARD_E_INSUFFICIENT_BUFFER);
CopyMemory(pbData, files->cardid, sizeof(files->cardid));
RETURN(NO_ERROR);
}
if (wcscmp(CP_CARD_PIN_INFO, wszProperty) == 0)
{
PPIN_INFO p = PPIN_INFO(pbData);
if (pdwDataLen)
*pdwDataLen = sizeof(*p);
if (cbData < sizeof(*p))
RETURN(SCARD_E_INSUFFICIENT_BUFFER);
if (p->dwVersion != PIN_INFO_CURRENT_VERSION)
RETURN(ERROR_REVISION_MISMATCH);
p->dwFlags = 0;
p->dwChangePermission = 0;// CREATE_PIN_SET(dwFlags);
p->dwUnblockPermission = 0; // dwFlags == PUKK_PIN_ID ? CREATE_PIN_SET(PUKK_PIN_ID) : 0;
p->PinType = isPinPad(pCardData) ? ExternalPinType : AlphaNumericPinType;
p->PinCachePolicy.dwVersion = PIN_CACHE_POLICY_CURRENT_VERSION;
p->PinCachePolicy.dwPinCachePolicyInfo = 0;
p->PinCachePolicy.PinCachePolicyType = dwFlags == AUTH_PIN_ID ? PinCacheNormal : PinCacheNone;
switch (dwFlags)
{
case AUTH_PIN_ID: p->PinPurpose = AuthenticationPin; break;
case SIGN_PIN_ID: p->PinPurpose = DigitalSignaturePin; break;
//case PUKK_PIN_ID: p->PinPurpose = UnblockOnlyPin; break;
default: RETURN(SCARD_E_INVALID_PARAMETER);
}
RETURN(NO_ERROR);
}
if (wcscmp(CP_CARD_LIST_PINS, wszProperty) == 0)
{
if (dwFlags)
RETURN(SCARD_E_INVALID_PARAMETER);
PPIN_SET p = PPIN_SET(pbData);
if (pdwDataLen)
*pdwDataLen = sizeof(*p);
if (cbData < sizeof(*p))
RETURN(SCARD_E_INSUFFICIENT_BUFFER);
SET_PIN(*p, AUTH_PIN_ID);
SET_PIN(*p, SIGN_PIN_ID);
//SET_PIN(*p, PUKK_PIN_ID);
RETURN(NO_ERROR);
}
if (wcscmp(CP_CARD_PIN_STRENGTH_VERIFY, wszProperty) == 0)
{
if (dwFlags < AUTH_PIN_ID || dwFlags > SIGN_PIN_ID)
RETURN(SCARD_E_INVALID_PARAMETER);
PDWORD p = PDWORD(pbData);
if (pdwDataLen)
*pdwDataLen = sizeof(*p);
if (cbData < sizeof(*p))
RETURN(SCARD_E_INSUFFICIENT_BUFFER);
*p = CARD_PIN_STRENGTH_PLAINTEXT;
RETURN(NO_ERROR);
}
if (wcscmp(CP_KEY_IMPORT_SUPPORT, wszProperty) == 0)
{
PDWORD p = PDWORD(pbData);
if (pdwDataLen)
*pdwDataLen = sizeof(*p);
if (cbData < sizeof(*p))
RETURN(SCARD_E_INSUFFICIENT_BUFFER);
*p = 0;
RETURN(NO_ERROR);
}
if (wcscmp(CP_PADDING_SCHEMES, wszProperty) == 0)
{
PDWORD p = PDWORD(pbData);
if (pdwDataLen)
*pdwDataLen = sizeof(*p);
if (cbData < sizeof(*p))
RETURN(SCARD_E_INSUFFICIENT_BUFFER);
*p = CARD_PADDING_NONE | CARD_PADDING_PKCS1;
RETURN(NO_ERROR);
}
RETURN(SCARD_E_UNSUPPORTED_FEATURE);
}
DWORD WINAPI CardSetProperty(__in PCARD_DATA pCardData, __in LPCWSTR wszProperty, __in_bcount(cbDataLen) PBYTE pbData,
__in DWORD cbDataLen, __in DWORD dwFlags)
{
if (!pCardData || !wszProperty)
RETURN(SCARD_E_INVALID_PARAMETER);
_log("wszProperty=%S, cbDataLen=%u, dwFlags=%u", wszProperty, cbDataLen, dwFlags);
if (wcscmp(CP_PIN_CONTEXT_STRING, wszProperty) == 0)
RETURN(NO_ERROR);
if (!pbData || !cbDataLen)
RETURN(SCARD_E_INVALID_PARAMETER);
if (wcscmp(CP_CARD_CACHE_MODE, wszProperty) == 0 ||
wcscmp(CP_SUPPORTS_WIN_X509_ENROLLMENT, wszProperty) == 0 ||
wcscmp(CP_CARD_GUID, wszProperty) == 0 ||
wcscmp(CP_CARD_SERIAL_NO, wszProperty) == 0 ||
wcscmp(CP_CARD_PIN_STRENGTH_VERIFY, wszProperty) == 0 ||
wcscmp(CP_CARD_PIN_INFO, wszProperty) == 0)
RETURN(SCARD_W_SECURITY_VIOLATION);
if (wcscmp(CP_PARENT_WINDOW, wszProperty) == 0)
{
if (dwFlags)
RETURN(SCARD_E_INVALID_PARAMETER);
if (cbDataLen != sizeof(pCardData))
RETURN(SCARD_E_INVALID_PARAMETER);
HWND cp = *((HWND *) pbData);
if (cp != 0 && !IsWindow(cp))
RETURN(SCARD_E_INVALID_PARAMETER);
Files *files = (Files*)pCardData->pvVendorSpecific;
files->cp = cp;
RETURN(NO_ERROR);
}
RETURN(SCARD_E_INVALID_PARAMETER);
}
DWORD WINAPI CardQueryCapabilities(__in PCARD_DATA pCardData, __inout PCARD_CAPABILITIES pCardCapabilities)
{
if (!pCardData || !pCardCapabilities)
RETURN(SCARD_E_INVALID_PARAMETER);
if (pCardCapabilities->dwVersion != CARD_CAPABILITIES_CURRENT_VERSION && pCardCapabilities->dwVersion != 0)
RETURN(ERROR_REVISION_MISMATCH);
pCardCapabilities->dwVersion = CARD_CAPABILITIES_CURRENT_VERSION;
_log("dwVersion=%u, fKeyGen=%u, fCertificateCompression=%u", pCardCapabilities->dwVersion,
pCardCapabilities->fKeyGen, pCardCapabilities->fCertificateCompression);
pCardCapabilities->fCertificateCompression = TRUE;
pCardCapabilities->fKeyGen = FALSE;
RETURN(NO_ERROR);
}
DWORD WINAPI CardGetContainerInfo(__in PCARD_DATA pCardData, __in BYTE bContainerIndex, __in DWORD dwFlags, __inout PCONTAINER_INFO pContainerInfo)
{
if (!pCardData || !pContainerInfo || dwFlags)
RETURN(SCARD_E_INVALID_PARAMETER);
if (pContainerInfo->dwVersion < 0 || pContainerInfo->dwVersion > CONTAINER_INFO_CURRENT_VERSION)
RETURN(ERROR_REVISION_MISMATCH);
_log("bContainerIndex=%u, dwFlags=0x%08X, dwVersion=%u", bContainerIndex, dwFlags, pContainerInfo->dwVersion);
pContainerInfo->dwVersion = CONTAINER_INFO_CURRENT_VERSION;
pContainerInfo->cbSigPublicKey = 0;
pContainerInfo->pbSigPublicKey = nullptr;
pContainerInfo->cbKeyExPublicKey = 0;
pContainerInfo->pbKeyExPublicKey = nullptr;
Files *files = (Files*)pCardData->pvVendorSpecific;
switch (bContainerIndex)
{
case AUTH_CONTAINER_INDEX:
{
pContainerInfo->pbKeyExPublicKey = isECDSAPubKey(files->auth) ?
PBYTE(pubKeyECStruct(pCardData, files->auth, pContainerInfo->cbKeyExPublicKey, false)) :
PBYTE(pubKeyRSAStruct(pCardData, files->auth, pContainerInfo->cbKeyExPublicKey, CALG_RSA_KEYX));
if (!pContainerInfo->pbKeyExPublicKey)
RETURN(ERROR_NOT_ENOUGH_MEMORY);
break;
}
case SIGN_CONTAINER_INDEX:
{
pContainerInfo->pbSigPublicKey = isECDSAPubKey(files->sign) ?
PBYTE(pubKeyECStruct(pCardData, files->sign, pContainerInfo->cbSigPublicKey, true)) :
PBYTE(pubKeyRSAStruct(pCardData, files->sign, pContainerInfo->cbSigPublicKey, CALG_RSA_SIGN));
if (!pContainerInfo->pbSigPublicKey)
RETURN(ERROR_NOT_ENOUGH_MEMORY);
break;
}
default:
RETURN(SCARD_E_NO_KEY_CONTAINER);
}
RETURN(NO_ERROR);
}
DWORD WINAPI CardAuthenticatePin(__in PCARD_DATA pCardData, __in LPWSTR pwszUserId, __in_bcount(cbPin) PBYTE pbPin, __in DWORD cbPin, __out_opt PDWORD pcAttemptsRemaining)
{
_log("pwszUserId=%S", pwszUserId);
if (!pwszUserId || wcscmp(pwszUserId, wszCARD_USER_USER) != 0 || !pbPin)
RETURN(SCARD_E_INVALID_PARAMETER);
return CardAuthenticateEx(pCardData, AUTH_PIN_ID, CARD_PIN_SILENT_CONTEXT, pbPin, cbPin, nullptr, nullptr, pcAttemptsRemaining);
}
DWORD WINAPI CardAuthenticateEx(__in PCARD_DATA pCardData, __in PIN_ID PinId, __in DWORD dwFlags, __in_bcount(cbPinData) PBYTE pbPinData, __in DWORD cbPinData,
__deref_opt_out_bcount(*pcbSessionPin) PBYTE *ppbSessionPin, __out_opt PDWORD pcbSessionPin, __out_opt PDWORD pcAttemptsRemaining)
{
_log("PinId=%u, dwFlags=0x%08X, cbPinData=%u, Attempts %s", PinId, dwFlags, cbPinData, pcAttemptsRemaining ? "YES" : "NO");
if (!pCardData || (PinId != AUTH_PIN_ID && PinId != SIGN_PIN_ID))
RETURN(SCARD_E_INVALID_PARAMETER);
Result data;
BYTE remaining = (!transfer({ 0x00, 0xA4, 0x00, 0x0C, 0x00 }, pCardData->hScard) ||
!transfer({ 0x00, 0xA4, 0x02, 0x0C, 0x02, 0x00, 0x16 }, pCardData->hScard) ||
!(data = transfer({ 0x00, 0xB2, byte(PinId == AUTH_PIN_ID ? 1 : 2), 0x04, 0x00 }, pCardData->hScard))) ? 3 : data.data[5];
if (!isPinPad(pCardData))
{
_log("Secure connection is not used");
if (dwFlags == CARD_AUTHENTICATE_GENERATE_SESSION_PIN ||
dwFlags == CARD_AUTHENTICATE_SESSION_PIN)
RETURN(SCARD_E_UNSUPPORTED_FEATURE);
if (dwFlags && dwFlags != CARD_PIN_SILENT_CONTEXT)
RETURN(SCARD_E_INVALID_PARAMETER);
if (!pbPinData)
RETURN(SCARD_E_INVALID_PARAMETER);
if ((PinId == AUTH_PIN_ID && cbPinData < 4) ||
(PinId == SIGN_PIN_ID && cbPinData < 5) ||
cbPinData > 12 ||
!std::all_of(pbPinData, pbPinData + cbPinData, std::isdigit))
RETURN(SCARD_W_WRONG_CHV);
if (remaining == 0)
RETURN(SCARD_W_CHV_BLOCKED);
vector<byte> cmd{ 0x00, 0x20, 0x00, byte(PinId == AUTH_PIN_ID ? 0x01 : 0x02), byte(cbPinData) };
cmd.insert(cmd.end(), pbPinData, pbPinData + cbPinData);
Result result = transfer(cmd, pCardData->hScard);
switch ((uint8_t(result.SW1) << 8) + uint8_t(result.SW2))
{
case 0x9000: RETURN(NO_ERROR);
case 0x63C0: //pin retry count 0
if (pcAttemptsRemaining)
*pcAttemptsRemaining = 0;