-
Notifications
You must be signed in to change notification settings - Fork 26
/
Winscard.cpp
4517 lines (3897 loc) · 146 KB
/
Winscard.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "stdafx.h"
#include <chrono>
#include <thread>
#include <fstream>
#include <codecvt>
#ifndef INTERFACE_H
#define INTERFACE_H
/*
This is of APDUPlay project for interception and manipulation of PC/SC APDU packets for smart cards.
See https://www.fi.muni.cz/~xsvenda/apduinspect.html for more information
Copyright (C) 2011 Petr Svenda <[email protected]>
LICENSE TERMS
The free distribution and use of this software in both source and binary
form is allowed (with or without changes) provided that:
1. distributions of this source code include the above copyright
notice, this list of conditions and the following disclaimer;
2. distributions in binary form include the above copyright
notice, this list of conditions and the following disclaimer
in the documentation and/or other associated materials;
3. the copyright holder's name is not used to endorse products
built using this software without specific written permission.
ALTERNATIVELY, provided that this notice is retained in full, this product
may be distributed under the terms of the GNU General Public License (GPL),
in which case the provisions of the GPL apply INSTEAD OF those given above.
DISCLAIMER
This software is provided 'as is' with no explicit or implied warranties
in respect of its properties, including, but not limited to, correctness
and/or fitness for purpose.
Please, report any bugs to author <[email protected]>
/**/
// Winscard.cpp : Defines the initialization routines for the DLL.
//
#include "stdafx.h"
#include <stdio.h>
#include <winscard.h>
#include "Winscard.h"
#include "CommonFnc.h"
#include <time.h>
#if defined(_WIN32)
#include "socket.h"
#define SCardConnect SCardConnectA
#define SCardStatus SCardStatusA
#define SCardListReaders SCardListReadersA
#define SCardListReaderGroups SCardListReaderGroupsA
#endif
#ifdef __linux__
#include <dlfcn.h>
#include <pwd.h>
#include "wintypes.h"
#endif
/*
extern SCard (.*?) STDCALL.*?(SCard.*?)\((.*?)\);
static SCard \1 (STDCALL *Original_\2)
\3
);
/**/
#pragma warning(disable:4996)
static string_type LIBRARY_VERSION = _CONV("2019.07.17");
static string_type ENV_APDUPLAY_WINSCARD_RULES_PATH = _CONV("APDUPLAY");
static string_type ENV_APDUPLAY_DEBUG_PATH = _CONV("APDUPLAY_DEBUG");
static string_type ENV_APDUPLAY_REMOTE_TAG = _CONV("APDUPLAY_REMOTE_TAG");
static string_type ENV_APDUPLAY_DISABLE_LOGGING = _CONV("APDUPLAY_DISABLE_LOGGING");
static string_type NO_READER = "*"; // was "empty" before
static string_type APDUPLAY_DEBUG_FILE = _CONV("c:\\Temp\\apduplay_debug.txt");
static string_type RULE_FILE = _CONV("winscard_rules.txt");
static string_type WINSCARD_RULES_LOG = _CONV("winscard_rules_log.txt");
static string_type WINSCARD_LOG = _CONV("winscard_log.txt");
static std::string INSTRUCTION_FILE = "Instructions.txt";
// The one and only CWinscardApp object
CWinscardApp theApp;
#define REMOTE_SOCKET_TIMEOUT 20
#define REMOTE_SOCKET_LONG_TIMEOUT 20
static string_type REMOTE_SOCKET_ENDSEQ = _CONV("@@");
#define VIRTUAL_READERS_SEPARATOR _CONV('|')
#define REMOTE_APDU_RESPONSE_WAIT_TIME 0
#define REMOTE_APDU_RESPONSE_WAIT_TIME_PER_BYTE 20
//#define HANDLE_VIRTUAL_CARD 0xABADBABE
#define HANDLE_VIRTUAL_CARD 0x1
//BYTE START_APDU[] = {0xB0, 0x05, 0x01, 0x00, 0x01};
BYTE START_APDU[] = { 0xB0, 0x01, 0x01, 0x00, 0x0C };
BYTE PIN_COUNTER_APDU[] = { 0xB0, 0x05, 0x01, 0x00, 0x01 };
BYTE GET_APDU1[] = { 0x00, 0xC0, 0x00, 0x00 };
BYTE GET_APDU2[] = { 0xC0, 0xC0, 0x00, 0x00 };
//#define VIRT_READER_NAME "VirtOpenPGP"
//#define VIRT_READER_NAME "Simona /111.222.123.033@07"
//#define VIRTUAL_READERS_LEN strlen(VIRT_READER_NAME)
#define CMD_APDU "APDU"
#define CMD_RESET "RESET"
#define CMD_ENUM "ENUM"
#define CMD_READERS "READERS"
#define CMD_PERSONALIZE "PERSONALIZE"
#define CMD_LINE_SEPARATOR "|"
#define CMD_SEPARATOR ":"
#define CMD_RESPONSE_FAIL "FAIL"
/* ******************************************************************************* */
#ifdef __linux__
static void* hOriginal = NULL;
#else
static HANDLE hOut = 0;
static HMODULE hOriginal = 0;
#endif
int apduCounter = 0;
/* ******************************************************************************* */
/* The following values variables MUST be defined here, but MUST NOT be referenced
in this or any other program module. The DEF file is set to forward their linkage
to the "originalxx.dll". If we need the data that these variables should be pointing
to, we must GetProcAddress on "originalxx.dll" and use the data there.
*/
#if defined(_WIN32)
const SCARD_IO_REQUEST g_rgSCardT0Pci, g_rgSCardT1Pci, g_rgSCardRawPci;
/* Just make sure we don't accidentally use the wrong global variable... */
#define g_rgSCardT0Pci DONT_USE_ME_g_rgSCardT0Pci
#undef SCARD_PCI_T0
#define SCARD_PCI_T0 DONT_USE_ME_SCARD_PCI_T0
#define g_rgSCardT1Pci DONT_USE_ME_g_rgSCardT1Pci
#undef SCARD_PCI_T1
#define SCARD_PCI_T1 DONT_USE_ME_SCARD_PCI_T1
#define g_rgSCardTRawPci DONT_USE_ME_g_rgSCardTRawPci
#undef SCARD_PCI_RAW
#define SCARD_PCI_RAW DONT_USE_ME_SCARD_PCI_RAW
#endif
/* ******************************************************************************* */
void LogDebugString(string_type message, bool bInsertTime = true) {
if (theApp.m_remoteConfig.bDisableLogging == FALSE) {
string_type logLine;
if (bInsertTime) {
string_type date_and_time = getCurrentTimeString();
CCommonFnc::File_AppendString(APDUPLAY_DEBUG_FILE, string_format(_CONV("%s: %s"), date_and_time.c_str(), message.c_str()));
}
else {
CCommonFnc::File_AppendString(APDUPLAY_DEBUG_FILE, message);
}
}
}
void LogWinscardRules(string_type message) {
if (theApp.m_remoteConfig.bDisableLogging == FALSE) {
LogDebugString(message);
CCommonFnc::File_AppendString(WINSCARD_RULES_LOG, message);
}
}
void DumpMemory(LPCBYTE location, DWORD length) {
string_type message;
CCommonFnc::BYTE_ConvertFromArrayToHexString((BYTE*) location, length, &message);
CCommonFnc::File_AppendString(WINSCARD_LOG, message);
CCommonFnc::File_AppendString(WINSCARD_LOG, _CONV("\n"));
}
static SCard LONG(STDCALL *Original_SCardEstablishContext)(
IN DWORD dwScope,
IN LPCVOID pvReserved1,
IN LPCVOID pvReserved2,
OUT LPSCARDCONTEXT phContext
);
SCard LONG STDCALL SCardEstablishContext(
IN DWORD dwScope,
IN LPCVOID pvReserved1,
IN LPCVOID pvReserved2,
OUT LPSCARDCONTEXT phContext
) {
string_type message;
message = string_format(_CONV("SCardEstablishContext() called\n"));
LogWinscardRules(message);
// Release ctxs for remote cards (if any)
theApp.Remote_SCardReleaseContext();
LONG status = (*Original_SCardEstablishContext)(dwScope, pvReserved1, pvReserved2, phContext);
message = string_format(_CONV("-> hContext:0x%x\n"), *phContext);
LogWinscardRules(message);
return status;
}
static SCard LONG(STDCALL *Original_SCardReleaseContext)(
IN SCARDCONTEXT hContext
);
SCard LONG STDCALL SCardReleaseContext(
IN SCARDCONTEXT hContext
) {
string_type message;
message = string_format(_CONV("SCardReleaseContext(hContext:0x%x) called\n"), hContext);
LogWinscardRules(message);
// Release ctxs for remote cards (if any)
theApp.Remote_SCardReleaseContext();
LONG status = (*Original_SCardReleaseContext)(hContext);
return status;
}
static SCard LONG(STDCALL *Original_SCardIsValidContext)(
IN SCARDCONTEXT hContext
);
SCard LONG STDCALL SCardIsValidContext(
IN SCARDCONTEXT hContext
) {
string_type message;
message = string_format(_CONV("SCardIsValidContext(hContext:0x%x) called\n"), hContext);
LogWinscardRules(message);
return (*Original_SCardIsValidContext)(hContext);
}
static SCard LONG(STDCALL *Original_SCardCancel)(
IN SCARDCONTEXT hContext
);
SCard LONG STDCALL SCardCancel(
IN SCARDCONTEXT hContext
) {
LogWinscardRules(_CONV("SCardCancel called\n"));
return (*Original_SCardCancel)(hContext);
}
static SCard LONG(STDCALL *Original_SCardReconnect)(
IN SCARDHANDLE hCard,
IN DWORD dwShareMode,
IN DWORD dwPreferredProtocols,
IN DWORD dwInitialization,
OUT LPDWORD pdwActiveProtocol
);
SCard LONG STDCALL SCardReconnect(
IN SCARDHANDLE hCard,
IN DWORD dwShareMode,
IN DWORD dwPreferredProtocols,
IN DWORD dwInitialization,
OUT LPDWORD pdwActiveProtocol
) {
string_type message;
message = string_format(_CONV("SCardReconnect(hCard:0x%x) called\n"), hCard);
LogWinscardRules(message);
if (theApp.IsRemoteCard(hCard)) {
return SCARD_S_SUCCESS;
*pdwActiveProtocol = SCARD_PROTOCOL_T1;
}
else {
return (*Original_SCardReconnect)(hCard, dwShareMode, dwPreferredProtocols, dwInitialization, pdwActiveProtocol);
}
}
static SCard LONG(STDCALL *Original_SCardBeginTransaction)(
IN SCARDHANDLE hCard
);
SCard LONG STDCALL SCardBeginTransaction(
IN SCARDHANDLE hCard
) {
LogWinscardRules(_CONV("SCardBeginTransaction called\n"));
if (theApp.IsRemoteCard(hCard)) {
return SCARD_S_SUCCESS;
}
else {
return (*Original_SCardBeginTransaction)(hCard);
}
}
static SCard LONG(STDCALL *Original_SCardEndTransaction)(
IN SCARDHANDLE hCard,
IN DWORD dwDisposition
);
SCard LONG STDCALL SCardEndTransaction(
IN SCARDHANDLE hCard,
IN DWORD dwDisposition
) {
LogWinscardRules(_CONV("SCardEndTransaction called\n"));
if (theApp.IsRemoteCard(hCard)) {
return SCARD_S_SUCCESS;
}
else {
return (*Original_SCardEndTransaction)(hCard, dwDisposition);
}
}
static SCard LONG(STDCALL *Original_SCardControl)(
IN SCARDHANDLE hCard,
IN DWORD dwControlCode,
IN LPCVOID lpInBuffer,
IN DWORD nInBufferSize,
OUT LPVOID lpOutBuffer,
IN DWORD nOutBufferSize,
OUT LPDWORD lpBytesReturned
);
SCard LONG STDCALL SCardControl(
IN SCARDHANDLE hCard,
IN DWORD dwControlCode,
IN LPCVOID lpInBuffer,
IN DWORD nInBufferSize,
OUT LPVOID lpOutBuffer,
IN DWORD nOutBufferSize,
OUT LPDWORD lpBytesReturned
) {
LogWinscardRules(_CONV("SCardControl called\n"));
if (theApp.IsRemoteCard(hCard)) {
return SCARD_S_SUCCESS;
}
else {
return (*Original_SCardControl)(hCard, dwControlCode, lpInBuffer, nInBufferSize, lpOutBuffer, nOutBufferSize, lpBytesReturned);
}
}
static SCard LONG(STDCALL *Original_SCardGetAttrib)(
IN SCARDHANDLE hCard,
IN DWORD dwAttrId,
OUT LPBYTE pbAttr,
IN OUT LPDWORD pcbAttrLen
);
SCard LONG STDCALL SCardGetAttrib(
IN SCARDHANDLE hCard,
IN DWORD dwAttrId,
OUT LPBYTE pbAttr,
IN OUT LPDWORD pcbAttrLen
) {
LogWinscardRules(_CONV("SCardGetAttrib called\n"));
if (theApp.IsRemoteCard(hCard)) {
return SCARD_S_SUCCESS;
}
else {
return (*Original_SCardGetAttrib)(hCard, dwAttrId, pbAttr, pcbAttrLen);
}
}
static SCard LONG(STDCALL *Original_SCardSetAttrib)(
IN SCARDHANDLE hCard,
IN DWORD dwAttrId,
IN LPCBYTE pbAttr,
IN DWORD cbAttrLen
);
SCard LONG STDCALL SCardSetAttrib(
IN SCARDHANDLE hCard,
IN DWORD dwAttrId,
IN LPCBYTE pbAttr,
IN DWORD cbAttrLen
) {
LogWinscardRules(_CONV("SCardSetAttrib called\n"));
if (theApp.IsRemoteCard(hCard)) {
return SCARD_S_SUCCESS;
}
else {
return (*Original_SCardSetAttrib)(hCard, dwAttrId, pbAttr, cbAttrLen);
}
}
/* ******************************************************************************* */
CWinscardApp::~CWinscardApp()
{
iniparser_freedict(instructionDict);
#ifdef __linux
dlclose(hOriginal);
#else
FreeLibrary(hOriginal);
#endif
// Reference to WINSCARD_LOG will fail with access to 0xfeefee (global CString WINSCARD_LOG does not exists at the time of dll release (strange))
// if (theApp.m_winscardConfig.bLOG_EXCHANGED_APDU) CCommonFnc::File_AppendString(WINSCARD_LOG, "[end]\n");
#if defined(_WIN32)
if (m_remoteConfig.pSocket != NULL) delete m_remoteConfig.pSocket;
#endif
lptr::iterator iter;
for (iter = m_charAllocatedMemoryList.begin(); iter != m_charAllocatedMemoryList.end(); iter++) {
char* ptr = (char*)*iter;
if (ptr != NULL) delete[] ptr;
}
m_charAllocatedMemoryList.clear();
for (iter = m_wcharAllocatedMemoryList.begin(); iter != m_wcharAllocatedMemoryList.end(); iter++) {
WCHAR* ptr = (WCHAR*)*iter;
if (ptr != NULL) delete[] ptr;
}
m_wcharAllocatedMemoryList.clear();
}
void ConvertOuterParenthessis(std::string& description)
{
int count = 0;
for (unsigned int i = 0; i < description.length(); ++i)
{
if (description[i] == _CONV('('))
{
if (count == 0)
{
description[i] = _CONV('[');
}
++count;
}
else if (description[i] == _CONV(')'))
{
if (count == 1)
{
description[i] = _CONV(']');
}
--count;
}
}
}
void CWinscardApp::WriteDescription(BYTE insByte)
{
char_type sec_and_key[256];
string_type hexNum = string_format(_CONV("%.2x"), insByte);
char_type* section_name = _CONV("instructions:");
const char* description;
string_type prefix = _CONV("instruction info: ");
type_copy(sec_and_key, section_name);
type_cat(sec_and_key, hexNum.c_str());
#ifdef UNICODE
char sec_and_key_char[256];
wcstombs(sec_and_key_char, sec_and_key, type_length(sec_and_key));
description = iniparser_getstring(instructionDict, sec_and_key_char, "");
std::string tmp(description);
if (strlen(description) != 0)
{
ConvertOuterParenthessis(tmp);
CCommonFnc::File_AppendString(WINSCARD_LOG, prefix + std::wstring(tmp.begin(), tmp.end()));
CCommonFnc::File_AppendString(WINSCARD_LOG, _CONV("\n"));
}
#else
description = iniparser_getstring(instructionDict, sec_and_key, "");
std::string tmp(description);
if (strlen(description) != 0)
{
ConvertOuterParenthessis(tmp);
CCommonFnc::File_AppendString(WINSCARD_LOG, prefix + tmp);
CCommonFnc::File_AppendString(WINSCARD_LOG, _CONV("\n"));
}
#endif
}
static SCard LONG(STDCALL *Original_SCardFreeMemory)(
IN SCARDCONTEXT hContext,
IN LPCVOID pvMem
);
SCard LONG STDCALL SCardFreeMemory(
IN SCARDCONTEXT hContext,
IN LPCVOID pvMem)
{
string_type message;
message = string_format(_CONV("SCardFreeMemory(hContext:0x%x) called\n"), hContext);
LogWinscardRules(message);
LONG status = SCARD_S_SUCCESS;
// TRY TO FIND GIVEN MEMORY REFFERENCE IN LOCAL ALLOCATIONS
BOOL bFound = FALSE;
lptr::iterator iter;
for (iter = theApp.m_charAllocatedMemoryList.begin(); iter != theApp.m_charAllocatedMemoryList.end(); iter++) {
char* ptr = (char*)*iter;
if (ptr != NULL && (ptr == pvMem)) {
delete[] ptr;
bFound = TRUE;
theApp.m_charAllocatedMemoryList.erase(iter);
break;
}
}
for (iter = theApp.m_wcharAllocatedMemoryList.begin(); iter != theApp.m_wcharAllocatedMemoryList.end(); iter++) {
WCHAR* ptr = (WCHAR*)*iter;
if (ptr != NULL && (ptr == pvMem)) {
delete[] ptr;
bFound = TRUE;
theApp.m_wcharAllocatedMemoryList.erase(iter);
break;
}
}
// IF NOT FOUND, PASS TO ORIGINAL LIBRARY
if (!bFound) status = (*Original_SCardFreeMemory)(hContext, pvMem);
return status;
}
static SCard LONG(STDCALL *Original_SCardDisconnect)(
SCARDHANDLE hCard,
DWORD dwDisposition
);
SCard LONG STDCALL SCardDisconnect(
SCARDHANDLE hCard,
DWORD dwDisposition)
{
LogWinscardRules(_CONV("SCardDisconnect called\n"));
// DISCONNECT FROM CARD
if (theApp.IsRemoteCard(hCard)) {
return SCARD_S_SUCCESS;
}
else {
return (*Original_SCardDisconnect)(hCard, dwDisposition);
}
}
static SCard LONG(STDCALL *Original_SCardTransmit)(
IN SCARDHANDLE hCard,
IN LPCSCARD_IO_REQUEST pioSendPci,
IN LPCBYTE pbSendBuffer,
IN DWORD cbSendLength,
IN OUT LPSCARD_IO_REQUEST pioRecvPci,
OUT LPBYTE pbRecvBuffer,
IN OUT LPDWORD pcbRecvLength
);
SCard LONG STDCALL SCardTransmit(
IN SCARDHANDLE hCard,
IN LPCSCARD_IO_REQUEST pioSendPci,
IN LPCBYTE pbSendBuffer,
IN DWORD cbSendLength,
IN OUT LPSCARD_IO_REQUEST pioRecvPci,
OUT LPBYTE pbRecvBuffer,
IN OUT LPDWORD pcbRecvLength
) {
LogWinscardRules(_CONV("SCardTransmit called\n"));
LONG result = SCARD_S_SUCCESS;
// DWORD written;
char_type *txMsg = _CONV("transmitted:");
char_type *rxMsg = _CONV("received:");
char_type *crlf = _CONV("\n");
const int bufferLength = 1024;
//char_type buffer[bufferLength];
string_type buffer;
char_type sendBuffer[300];
//clock_t elapsedCard;
//clock_t elapsedLibrary;
typedef std::chrono::high_resolution_clock Clock;
string_type message;
//elapsedLibrary = -clock();
auto lib_timestamp1 = Clock::now();
if (theApp.m_winscardConfig.bLOG_EXCHANGED_APDU) {
//sprintf(buffer, "SCardTransmit (handle 0x%0.8X)#\n", hCard);
buffer = string_format(_CONV("SCardTransmit (handle 0x%0.8X)#\n"), hCard);
CCommonFnc::File_AppendString(WINSCARD_LOG, buffer);
LogWinscardRules(buffer);
//sprintf(buffer, "apduCounter:%d#\n", apduCounter);
buffer = string_format(_CONV("apduCounter:%d#\n"), apduCounter);
CCommonFnc::File_AppendString(WINSCARD_LOG, buffer);
//sprintf(buffer, "totalBytesINCounter:%d#\n", theApp.m_processedApduByteCounter + 1);
buffer = string_format(_CONV("totalBytesINCounter:%d#\n"), theApp.m_processedApduByteCounter + 1);
CCommonFnc::File_AppendString(WINSCARD_LOG, buffer);
if(theApp.m_winscardConfig.bLOG_WRITE_DESCRIPTION)
{
theApp.WriteDescription((BYTE)pbSendBuffer[1]); // Send the INS BYTE to the function
}
CCommonFnc::File_AppendString(WINSCARD_LOG, txMsg);
DumpMemory(pbSendBuffer, cbSendLength);
}
// SAVE INCOMING APDU
APDU_BUFFER apduBuff;
memset(&apduBuff, 0, sizeof(APDU_BUFFER));
memcpy(&apduBuff, pbSendBuffer, cbSendLength);
theApp.apduInList.push_front(apduBuff);
if (theApp.m_winscardConfig.bMODIFY_APDU_BY_RULES) {
message = string_format(_CONV("\nIncoming rules applied for apduCounter %d: \n"), apduCounter);
LogWinscardRules(message);
CCommonFnc::BYTE_ConvertFromArrayToHexString((BYTE*)pbSendBuffer, cbSendLength, &message);
//message.Insert(0, " "); message += "\n";
message.insert(0, _CONV(" ")); message += _CONV("\n");
if (theApp.m_winscardConfig.bLOG_EXCHANGED_APDU) LogWinscardRules(message);
}
// COPY INPUT DATA
memcpy(sendBuffer, pbSendBuffer, cbSendLength);
// APPLY INCOMING RULES
if (theApp.m_winscardConfig.bMODIFY_APDU_BY_RULES) {
theApp.ApplyRules((BYTE*)sendBuffer, &cbSendLength, INPUT_APDU);
CCommonFnc::BYTE_ConvertFromArrayToHexString((BYTE*)sendBuffer, cbSendLength, &message);
//message.Insert(0, " "); message += "\n";
message.insert(0, _CONV(" ")); message += _CONV("\n");
if (theApp.m_winscardConfig.bLOG_EXCHANGED_APDU) LogWinscardRules(message);
}
//elapsedCard = -clock();
auto card_timestamp1 = Clock::now();
// INCREASE COUNTER OF THE BYTES SEND TO CARD - IS USED AS MEASUREMENT TRIGGER LATER
theApp.m_processedApduByteCounter += cbSendLength;
#if defined(_WIN32)
// Check if provided card handle is remote card
if (theApp.IsRemoteCard(hCard)) {
// FORWARD TO REMOTE SOCKET
result = theApp.Remote_SCardTransmit(&(theApp.m_remoteConfig), theApp.GetReaderName(hCard), (SCARD_IO_REQUEST *)pioSendPci, (LPCBYTE)sendBuffer, cbSendLength, pioRecvPci, pbRecvBuffer, pcbRecvLength);
}
else {
#endif
// If required, then ensure that at least one byte will be send to card
if (theApp.m_winscardConfig.bFORCE_APDU_NONZERO_INPUT_DATA) {
if (cbSendLength < 6) {
// ADD ONE ZERO BYTE
sendBuffer[4] = 1;
sendBuffer[5] = 0;
cbSendLength++;
}
}
// SEND DIRECTLY TO LOCAL READER
result = (*Original_SCardTransmit)(hCard, pioSendPci, (LPCBYTE)sendBuffer, cbSendLength, pioRecvPci, pbRecvBuffer, pcbRecvLength);
#if defined(_WIN32)
}
#endif
// HACK - if required, then perform transparently data readout on behalf of reader
// RECEIVE RESPONSE DATA, IF ANY
if ((*pcbRecvLength == 2) && theApp.m_winscardConfig.bAUTO_REQUEST_DATA) {
// READOUT ALL DATA
DWORD recvOffset = 0;
while (((pbRecvBuffer[recvOffset]) == 0x61) || ((pbRecvBuffer[recvOffset]) == 0x6C)) { // 0x61 ... SW_BYTES_REMAINING_00, 0x6C ... SW_CORRECT_LENGTH_00
// GET DATA APDU
sendBuffer[0] = (BYTE)0x00;
//sendBuffer[0] = (BYTE) 0xC0;
//sendBuffer[0] = (BYTE) 0xA0;
sendBuffer[1] = (BYTE)0xC0;
sendBuffer[2] = (BYTE)0x00;
sendBuffer[3] = (BYTE)0x00;
// HACK TO DEAL WITH CARDS THAT CANNOT HANDLE 254B AND MORE APDUS - if 0x61 0x00 (SW_BYTES_REMAINING_00 with zero remaining bytes is detected, then ask for 254 bytes instead
if ((pbRecvBuffer[*pcbRecvLength - 1] & 0xff) == 0) sendBuffer[4] = (BYTE)254;
else sendBuffer[4] = (BYTE)pbRecvBuffer[*pcbRecvLength - 1];
cbSendLength = 5;
int tmp = sendBuffer[4] & 0xff; tmp += 2; *pcbRecvLength = tmp;
#if defined(_WIN32)
// Check if provided card handle is remote card
if (theApp.IsRemoteCard(hCard)) {
// FORWARD TO REMOTE SOCKET
result = theApp.Remote_SCardTransmit(&(theApp.m_remoteConfig), theApp.GetReaderName(hCard), (SCARD_IO_REQUEST *) pioSendPci, (LPCBYTE)sendBuffer, cbSendLength, pioRecvPci, pbRecvBuffer + recvOffset, pcbRecvLength);
}
else {
#endif
result = (*Original_SCardTransmit)(hCard, pioSendPci, (LPCBYTE)sendBuffer, cbSendLength, pioRecvPci, pbRecvBuffer + recvOffset, pcbRecvLength);
#if defined(_WIN32)
}
#endif
recvOffset = *pcbRecvLength - 2;
}
}
// SAVE TIME OF CARD RESPONSE
//elapsedCard += clock();
auto card_timestamp2 = Clock::now();
auto elapsedCard = std::chrono::duration_cast<std::chrono::milliseconds>(card_timestamp2 - card_timestamp1).count();
if (theApp.m_winscardConfig.bLOG_EXCHANGED_APDU) {
//sprintf(buffer, "responseTime:%d#\n", elapsedCard);
buffer = string_format(_CONV("responseTime:%d#\n"), elapsedCard);
CCommonFnc::File_AppendString(WINSCARD_LOG, buffer);
//sprintf(buffer, "SCardTransmit result:0x%x#\n", result);
buffer = string_format(_CONV("SCardTransmit result:0x%x#\n"), result);
CCommonFnc::File_AppendString(WINSCARD_LOG, buffer);
}
if (result != SCARD_S_SUCCESS) {
// CHANGE LENGTH OF RESPONSE TO PREVENT PARSING OF INCORRECT DATA
*pcbRecvLength = 0;
}
if (theApp.m_winscardConfig.bLOG_EXCHANGED_APDU) {
CCommonFnc::File_AppendString(WINSCARD_LOG, rxMsg);
DumpMemory(pbRecvBuffer, *pcbRecvLength);
CCommonFnc::File_AppendString(WINSCARD_LOG, crlf);
}
// SAVE OUTGOING APDU
memset(&apduBuff, 0, sizeof(APDU_BUFFER));
memcpy(&apduBuff, pbRecvBuffer, *pcbRecvLength);
theApp.apduOutList.push_front(apduBuff);
if (theApp.m_winscardConfig.bMODIFY_APDU_BY_RULES) {
message = string_format(_CONV("\nOutgoing rules applied for apduCounter %d: \n"), apduCounter);
LogWinscardRules(message);
CCommonFnc::BYTE_ConvertFromArrayToHexString(pbRecvBuffer, *pcbRecvLength, &message);
//message.Insert(0, " "); message += "\n";
message.insert(0, _CONV(" ")); message += _CONV("\n");
if (theApp.m_winscardConfig.bLOG_EXCHANGED_APDU) LogWinscardRules(message);
// APPLY OUTGOING RULES
if (theApp.m_winscardConfig.bMODIFY_APDU_BY_RULES) theApp.ApplyRules(pbRecvBuffer, pcbRecvLength, OUTPUT_APDU);
CCommonFnc::BYTE_ConvertFromArrayToHexString(pbRecvBuffer, *pcbRecvLength, &message);
//message.Insert(0, " "); message += "\n";
message.insert(0, _CONV(" ")); message += _CONV("\n");
if (theApp.m_winscardConfig.bLOG_EXCHANGED_APDU) LogWinscardRules(message);
}
// increase apdu counter
apduCounter++;
//elapsedLibrary += clock();
auto lib_timestamp2 = Clock::now();
auto elapsedLibrary = std::chrono::duration_cast<std::chrono::milliseconds>(lib_timestamp2 - lib_timestamp1).count();
if (theApp.m_winscardConfig.bLOG_EXCHANGED_APDU) {
message = string_format(_CONV("responseTimeLibrary:%d#\n"), elapsedLibrary);
LogWinscardRules(message);
}
return result;
}
static SCard LONG(STDCALL *Original_SCardConnect)(
IN SCARDCONTEXT hContext,
IN LPCSTR szReader,
IN DWORD dwShareMode,
IN DWORD dwPreferredProtocols,
OUT LPSCARDHANDLE phCard,
OUT LPDWORD pdwActiveProtocol);
SCard LONG STDCALL SCardConnect(
IN SCARDCONTEXT hContext,
IN LPCSTR szReader,
IN DWORD dwShareMode,
IN DWORD dwPreferredProtocols,
OUT LPSCARDHANDLE phCard,
OUT LPDWORD pdwActiveProtocol)
{
LogWinscardRules(_CONV("SCardConnect called\n"));
LONG status = SCARD_S_SUCCESS;
if (theApp.m_winscardConfig.bFORCE_CONNECT_SHARED_MODE) {
// we will always set mode to shared, if required
dwShareMode = SCARD_SHARE_SHARED;
}
// Detect remote cards
#if defined(_WIN32)
string_type readerName = szReader;
if (theApp.IsRemoteReader(readerName)) {
theApp.m_nextRemoteCardID++;
*phCard = theApp.m_nextRemoteCardID;
theApp.remoteReadersMap[*phCard] = szReader;
string_type atr;
status = theApp.Remote_SCardConnect(&(theApp.m_remoteConfig), szReader, &atr);
theApp.remoteCardsATRMap[szReader] = atr;
}
else {
#endif
// Standard physical reader
status = (*Original_SCardConnect)(hContext, szReader, dwShareMode, dwPreferredProtocols, phCard, pdwActiveProtocol);
string_type message;
message = string_format(_CONV("SCardConnect(hContext:0x%x,%s,hCard:0x%x) called\n"), hContext, szReader, *phCard);
LogWinscardRules(message);
#if defined(_WIN32)
}
#endif
// Store mapping between card handle and reader (used in card remoting)
theApp.cardReaderMap[*phCard] = szReader;
return status;
}
static SCard LONG(STDCALL*Original_SCardStatus)(
SCARDHANDLE hCard,
LPSTR szReaderName,
LPDWORD pcchReaderLen,
LPDWORD pdwState,
LPDWORD pdwProtocol,
LPBYTE pbAtr,
LPDWORD pcbAtrLen
);
SCard LONG STDCALL SCardStatus(
SCARDHANDLE hCard,
LPSTR szReaderName,
LPDWORD pcchReaderLen,
LPDWORD pdwState,
LPDWORD pdwProtocol,
LPBYTE pbAtr,
LPDWORD pcbAtrLen)
{
LogWinscardRules(string_format(_CONV("SCardStatus(hCard:0x%x,pcchReaderLen:%d,pcbAtrLen:%d) called\n"), hCard, *pcchReaderLen, *pcbAtrLen));
if (theApp.IsRemoteCard(hCard)) {
// According to https://docs.microsoft.com/en-us/windows/desktop/api/winscard/nf-winscard-scardstatusa
*pdwState = SCARD_SPECIFIC;
*pdwProtocol = SCARD_PROTOCOL_T1;
return SCARD_S_SUCCESS;
}
else {
return (*Original_SCardStatus)(hCard, szReaderName, pcchReaderLen, pdwState, pdwProtocol, pbAtr, pcbAtrLen);
}
}
static SCard LONG(STDCALL *Original_SCardListReaders)(
IN SCARDCONTEXT hContext,
IN LPCSTR mszGroups,
OUT LPSTR mszReaders,
IN OUT LPDWORD pcchReaders
);
SCard LONG STDCALL SCardListReaders(
IN SCARDCONTEXT hContext,
IN LPCSTR mszGroups,
OUT LPSTR mszReaders,
IN OUT LPDWORD pcchReaders)
{
LogWinscardRules(_CONV("SCardListReaders called\n"));
int status = SCARD_S_SUCCESS;
ls readersList;
// Try to read list of remote readers if required
if (theApp.m_remoteConfig.bRedirect) {
string_type readers = "";
list<string_type> remoteReaders;
if (theApp.Remote_ListReaders(&(theApp.m_remoteConfig), &remoteReaders) == SCARD_S_SUCCESS) {
// Put remote readers into list
theApp.m_winscardConfig.listVIRTUAL_READERS = remoteReaders;
theApp.remoteCardsATRMap.clear(); // Clear ATR of remote cards
// Obtain ATR for every remote reader
ls::iterator iter;
for (iter = remoteReaders.begin(); iter != remoteReaders.end(); iter++) {
string_type atr;
status = theApp.Remote_SCardConnect(&(theApp.m_remoteConfig), *iter, &atr);
if (status == SCARD_S_SUCCESS) {
theApp.remoteCardsATRMap[*iter] = atr;
}
}
// readers from cfg file
theApp.m_winscardConfig.listVIRTUAL_READERS.insert(theApp.m_winscardConfig.listVIRTUAL_READERS.begin(),
theApp.m_winscardConfig.listVIRTUAL_READERS_STATIC.begin(), theApp.m_winscardConfig.listVIRTUAL_READERS_STATIC.end());
}
}
if (*pcchReaders == SCARD_AUTOALLOCATE) {
// NO BUFFER IS SUPPLIED
// OBTAIN REQUIRED LENGTH FOR REAL READERS
DWORD realLen = 0;
status = (*Original_SCardListReaders)(hContext, mszGroups, NULL, &realLen);
*pcchReaders = realLen;
// Supress error when virtual readers are set
if (status == SCARD_E_NO_READERS_AVAILABLE && theApp.m_winscardConfig.listVIRTUAL_READERS.size() > 0) {
*pcchReaders = 0;
status = SCARD_S_SUCCESS;
}
if (status == SCARD_S_SUCCESS) {
// ALLOCATE OWN BUFFER FOR REAL AND VIRTUAL READERS
size_t virtReadersLen = 0;
CCommonFnc::String_SerializeAsSeparatedArray(&theApp.m_winscardConfig.listVIRTUAL_READERS, '\0', NULL, &virtReadersLen);
DWORD newLen = (DWORD)(*pcchReaders + virtReadersLen + 2); // +2 for two terminating zeroes
char* readers = new char[newLen];
memset(readers, 0, newLen);
*pcchReaders = newLen;
status = (*Original_SCardListReaders)(hContext, mszGroups, readers, pcchReaders);
if (status == SCARD_E_NO_READERS_AVAILABLE) {
// No real readers are available. Check if virtual readers are supplied
if (theApp.m_winscardConfig.listVIRTUAL_READERS.size() > 0) {
LogDebugString(string_format(_CONV("No real cards available, but virtual readers specified => continuing only with virtual readers.\n")));
// Virtual readers are required => continue as OK (only virtual will be returned)
status = SCARD_S_SUCCESS;
*pcchReaders = 0;
}
else {
// No virtual readers specified => return SCARD_E_NO_READERS_AVAILABLE error
}
}
if (status == SCARD_S_SUCCESS) {
// COPY NAME OF VIRTUAL READERS TO THE END
char* virtReadersPtr = readers;
if (realLen > 0) { // Jump right after real readers
virtReadersPtr += realLen - 1;
}
CCommonFnc::String_SerializeAsSeparatedArray(&theApp.m_winscardConfig.listVIRTUAL_READERS, '\0', virtReadersPtr, &virtReadersLen);
// If no real readers were present, add space additional trailing zero
if (realLen == 0) {
*pcchReaders = (DWORD)(virtReadersLen + 1); // Add additional zero
}
else {
*pcchReaders = (DWORD)(realLen + virtReadersLen); // space for additional zero was already inserted before
}
readers[*pcchReaders - 1] = 0;
//mszReaders[*pcchReaders - 1] = 0;
// CAST mszReaders TO char** IS NECESSARY TO CORRECTLY PROPAGATE ALLOCATED BUFFER
char** temp = (char**)mszReaders;
*temp = readers;
CCommonFnc::String_ParseNullSeparatedArray((BYTE*) readers, *pcchReaders - 1, &readersList);
// ADD ALLOCATED MEMORY TO LIST FOR FUTURE DEALLOCATION
theApp.m_charAllocatedMemoryList.push_back(readers);
}
}
}
else {
// BUFFER SUPPLIED
// OBTAIN REQUIRED LENGTH FOR REAL READERS
DWORD realLen = *pcchReaders;
status = (*Original_SCardListReaders)(hContext, mszGroups, NULL, &realLen);
// Supress error when virtual readers are set
if (status == SCARD_E_NO_READERS_AVAILABLE && theApp.m_winscardConfig.listVIRTUAL_READERS.size() > 0) {
realLen = 0;
status = SCARD_S_SUCCESS;
}
if (status == SCARD_S_SUCCESS) {
size_t virtReadersLen = 0;
CCommonFnc::String_SerializeAsSeparatedArray(&theApp.m_winscardConfig.listVIRTUAL_READERS, '\0', NULL, &virtReadersLen);
if ((realLen + virtReadersLen + 2 > *pcchReaders) || (mszReaders == NULL)) {
// SUPPLIED BUFFER IS NOT LARGE ENOUGHT
*pcchReaders = (DWORD) (realLen + virtReadersLen);
if (mszReaders != NULL) status = SCARD_E_INSUFFICIENT_BUFFER;
}
else {
// SUPPLIED BUFFER IS OK, COPY REAL AND VIRTUAL READERS
memset(mszReaders, 0, *pcchReaders);
realLen = *pcchReaders;
status = (*Original_SCardListReaders)(hContext, mszGroups, mszReaders, &realLen);
if (status == SCARD_E_NO_READERS_AVAILABLE) {
// No real readers are available. Check if virtual readers are supplied
if (theApp.m_winscardConfig.listVIRTUAL_READERS.size() > 0) {
LogDebugString(string_format(_CONV("No real cards available, but virtual readers specified => continuing only with virtual readers.\n")));
// Virtual readers are required => continue as OK (only virtual will be returned)
status = SCARD_S_SUCCESS;