-
Notifications
You must be signed in to change notification settings - Fork 0
/
CardNative.cs
666 lines (581 loc) · 21.4 KB
/
CardNative.cs
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
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
namespace CardReaderGui
{
/// <summary>
/// CARD_STATE enumeration, used by the PC/SC function SCardGetStatusChanged
/// </summary>
enum CARD_STATE
{
UNAWARE = 0x00000000,
IGNORE = 0x00000001,
CHANGED = 0x00000002,
UNKNOWN = 0x00000004,
UNAVAILABLE = 0x00000008,
EMPTY = 0x00000010,
PRESENT = 0x00000020,
ATRMATCH = 0x00000040,
EXCLUSIVE = 0x00000080,
INUSE = 0x00000100,
MUTE = 0x00000200,
UNPOWERED = 0x00000400
}
/// <summary>
/// Wraps the SCARD_IO_STRUCTURE
///
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct SCard_IO_Request
{
public UInt32 m_dwProtocol;
public UInt32 m_cbPciLength;
}
/// <summary>
/// Wraps theSCARD_READERSTATE structure of PC/SC
/// </summary>
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct SCard_ReaderState
{
public string m_szReader;
public IntPtr m_pvUserData;
public UInt32 m_dwCurrentState;
public UInt32 m_dwEventState;
public UInt32 m_cbAtr;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=32)]
public byte[] m_rgbAtr;
}
/// <summary>
/// Implementation of ICard using native (P/Invoke) interoperability for PC/SC
/// </summary>
public class CardNative : CardBase
{
private IntPtr m_hContext = IntPtr.Zero;
private IntPtr m_hCard = IntPtr.Zero;
private UInt32 m_nProtocol = (uint) PROTOCOL.T0;
private int m_nLastError = 0;
public uint LastError { get { return (uint)m_nLastError; } }
#region PCSC_FUNCTIONS
/// <summary>
/// Native SCardGetStatusChanged from winscard.dll
/// </summary>
/// <param name="hContext"></param>
/// <param name="dwTimeout"></param>
/// <param name="rgReaderStates"></param>
/// <param name="cReaders"></param>
/// <returns></returns>
[DllImport("winscard.dll", SetLastError = true)]
internal static extern int SCardGetStatusChange(IntPtr hContext,
UInt32 dwTimeout,
[In,Out] SCard_ReaderState[] rgReaderStates,
UInt32 cReaders);
/// <summary>
/// Native SCardListReaders function from winscard.dll
/// </summary>
/// <param name="hContext"></param>
/// <param name="mszGroups"></param>
/// <param name="mszReaders"></param>
/// <param name="pcchReaders"></param>
/// <returns></returns>
[DllImport("winscard.dll", SetLastError=true)]
internal static extern int SCardListReaders(IntPtr hContext,
[MarshalAs(UnmanagedType.LPTStr)] string mszGroups,
IntPtr mszReaders,
out UInt32 pcchReaders);
/// <summary>
/// Native SCardEstablishContext function from winscard.dll
/// </summary>
/// <param name="dwScope"></param>
/// <param name="pvReserved1"></param>
/// <param name="pvReserved2"></param>
/// <param name="phContext"></param>
/// <returns></returns>
[DllImport("winscard.dll", SetLastError=true)]
internal static extern int SCardEstablishContext(UInt32 dwScope,
IntPtr pvReserved1,
IntPtr pvReserved2,
IntPtr phContext);
/// <summary>
/// Native SCardReleaseContext function from winscard.dll
/// </summary>
/// <param name="hContext"></param>
/// <returns></returns>
[DllImport("winscard.dll", SetLastError=true)]
internal static extern int SCardReleaseContext(IntPtr hContext);
/// <summary>
/// Native SCardConnect function from winscard.dll
/// </summary>
/// <param name="hContext"></param>
/// <param name="szReader"></param>
/// <param name="dwShareMode"></param>
/// <param name="dwPreferredProtocols"></param>
/// <param name="phCard"></param>
/// <param name="pdwActiveProtocol"></param>
/// <returns></returns>
[DllImport("winscard.dll", SetLastError=true, CharSet=CharSet.Auto)]
internal static extern int SCardConnect(IntPtr hContext,
[MarshalAs(UnmanagedType.LPTStr)] string szReader,
UInt32 dwShareMode,
UInt32 dwPreferredProtocols,
IntPtr phCard,
IntPtr pdwActiveProtocol);
/// <summary>
/// Native SCardDisconnect function from winscard.dll
/// </summary>
/// <param name="hCard"></param>
/// <param name="dwDisposition"></param>
/// <returns></returns>
[DllImport("winscard.dll", SetLastError=true)]
internal static extern int SCardDisconnect(IntPtr hCard,
UInt32 dwDisposition);
/// <summary>
/// Native SCardTransmit function from winscard.dll
/// </summary>
/// <param name="hCard"></param>
/// <param name="pioSendPci"></param>
/// <param name="pbSendBuffer"></param>
/// <param name="cbSendLength"></param>
/// <param name="pioRecvPci"></param>
/// <param name="pbRecvBuffer"></param>
/// <param name="pcbRecvLength"></param>
/// <returns></returns>
[DllImport("winscard.dll", SetLastError=true)]
internal static extern int SCardTransmit(IntPtr hCard,
[In] ref SCard_IO_Request pioSendPci,
byte[] pbSendBuffer,
UInt32 cbSendLength,
ref SCard_IO_Request pioRecvPci,
[Out] byte[] pbRecvBuffer,
ref UInt32 pcbRecvLength
);
/// <summary>
/// Native SCardBeginTransaction function of winscard.dll
/// </summary>
/// <param name="hContext"></param>
/// <returns></returns>
[DllImport("winscard.dll", SetLastError = true)]
internal static extern int SCardBeginTransaction(IntPtr hContext);
/// <summary>
/// Native SCardEndTransaction function of winscard.dll
/// </summary>
/// <param name="hContext"></param>
/// <returns></returns>
[DllImport("winscard.dll", SetLastError = true)]
internal static extern int SCardEndTransaction(IntPtr hContext, UInt32 dwDisposition);
[DllImport("winscard.dll", SetLastError = true)]
internal static extern int SCardGetAttrib(IntPtr hCard,
UInt32 dwAttribId,
[Out] byte[] pbAttr,
out UInt32 pcbAttrLen);
#endregion WINSCARD_FUNCTIONS
/// <summary>
/// Default constructor
/// </summary>
public CardNative()
{
}
/// <summary>
/// Object destruction
/// </summary>
~CardNative()
{
Disconnect(DISCONNECT.Unpower);
ReleaseContext();
}
#region ICard Members
/// <summary>
/// Wraps the PCSC function
/// LONG SCardListReaders(SCARDCONTEXT hContext,
/// LPCTSTR mszGroups,
/// LPTSTR mszReaders,
/// LPDWORD pcchReaders
/// );
/// </summary>
/// <returns>A string array of the readers</returns>
public override string[] ListReaders()
{
EstablishContext(SCOPE.User);
string[] sListReaders = new string[0];
UInt32 pchReaders = 0;
IntPtr szListReaders = IntPtr.Zero;
m_nLastError = SCardListReaders(m_hContext, null, szListReaders, out pchReaders);
if (m_nLastError == 0)
{
szListReaders = Marshal.AllocHGlobal((int) pchReaders);
m_nLastError = SCardListReaders(m_hContext, null, szListReaders, out pchReaders);
if (m_nLastError == 0)
{
char[] caReadersData = new char[pchReaders];
int nbReaders = 0;
for (int nI = 0; nI < pchReaders; nI++)
{
caReadersData[nI] = (char) Marshal.ReadByte(szListReaders, nI);
if (caReadersData[nI] == 0)
nbReaders++;
}
// Remove last 0
--nbReaders;
if (nbReaders != 0)
{
sListReaders = new string[nbReaders];
char[] caReader = new char[pchReaders];
int nIdx = 0;
int nIdy = 0;
int nIdz = 0;
// Get the nJ string from the multi-string
while(nIdx < pchReaders - 1)
{
caReader[nIdy] = caReadersData[nIdx];
if (caReader[nIdy] == 0)
{
sListReaders[nIdz] = new string(caReader, 0, nIdy);
++nIdz;
nIdy = 0;
caReader = new char[pchReaders];
}
else
++nIdy;
++nIdx;
}
}
}
Marshal.FreeHGlobal(szListReaders);
}
ReleaseContext();
return sListReaders;
}
/// <summary>
/// Wraps the PCSC function
/// LONG SCardEstablishContext(
/// IN DWORD dwScope,
/// IN LPCVOID pvReserved1,
/// IN LPCVOID pvReserved2,
/// OUT LPSCARDCONTEXT phContext
/// );
/// </summary>
/// <param name="Scope"></param>
public void EstablishContext(SCOPE Scope)
{
IntPtr hContext = Marshal.AllocHGlobal(Marshal.SizeOf(m_hContext));
m_nLastError = SCardEstablishContext((uint) Scope, IntPtr.Zero, IntPtr.Zero, hContext);
if (m_nLastError != 0)
{
string msg = "SCardEstablishContext error: " + m_nLastError;
Marshal.FreeHGlobal(hContext);
throw new Exception(msg);
}
m_hContext = Marshal.ReadIntPtr(hContext);
Marshal.FreeHGlobal(hContext);
}
/// <summary>
/// Wraps the PCSC function
/// LONG SCardReleaseContext(
/// IN SCARDCONTEXT hContext
/// );
/// </summary>
public void ReleaseContext()
{
if (m_hContext != IntPtr.Zero)
{
m_nLastError = SCardReleaseContext(m_hContext);
if (m_nLastError != 0)
{
string msg = "SCardReleaseContext error: " + m_nLastError;
throw new Exception(msg);
}
m_hContext = IntPtr.Zero;
}
}
/// <summary>
/// Wraps the PCSC function
/// LONG SCardConnect(
/// IN SCARDCONTEXT hContext,
/// IN LPCTSTR szReader,
/// IN DWORD dwShareMode,
/// IN DWORD dwPreferredProtocols,
/// OUT LPSCARDHANDLE phCard,
/// OUT LPDWORD pdwActiveProtocol
/// );
/// </summary>
/// <param name="Reader"></param>
/// <param name="ShareMode"></param>
/// <param name="PreferredProtocols"></param>
public override void Connect(string Reader, SHARE ShareMode, PROTOCOL PreferredProtocols)
{
EstablishContext(SCOPE.User);
IntPtr hCard = Marshal.AllocHGlobal(Marshal.SizeOf(m_hCard));
IntPtr pProtocol = Marshal.AllocHGlobal(Marshal.SizeOf(m_nProtocol));
m_nLastError = SCardConnect(m_hContext,
Reader,
(uint) ShareMode,
(uint) PreferredProtocols,
hCard,
pProtocol);
if (m_nLastError != 0)
{
string msg = "SCardConnect error: " + m_nLastError;
Marshal.FreeHGlobal(hCard);
Marshal.FreeHGlobal(pProtocol);
throw new Exception(msg);
}
m_hCard = Marshal.ReadIntPtr(hCard);
m_nProtocol = (uint) Marshal.ReadInt32(pProtocol);
Marshal.FreeHGlobal(hCard);
Marshal.FreeHGlobal(pProtocol);
}
/// <summary>
/// Wraps the PCSC function
/// LONG SCardDisconnect(
/// IN SCARDHANDLE hCard,
/// IN DWORD dwDisposition
/// );
/// </summary>
/// <param name="Disposition"></param>
public override void Disconnect(DISCONNECT Disposition)
{
if (m_hCard != IntPtr.Zero)
{
m_nLastError = SCardDisconnect(m_hCard, (uint) Disposition);
m_hCard = IntPtr.Zero;
if (m_nLastError != 0)
{
string msg = "SCardDisconnect error: " + m_nLastError;
throw new Exception(msg);
}
ReleaseContext();
}
}
/// <summary>
/// Wraps the PCSC function
/// LONG SCardTransmit(
/// SCARDHANDLE hCard,
/// LPCSCARD_I0_REQUEST pioSendPci,
/// LPCBYTE pbSendBuffer,
/// DWORD cbSendLength,
/// LPSCARD_IO_REQUEST pioRecvPci,
/// LPBYTE pbRecvBuffer,
/// LPDWORD pcbRecvLength
/// );
/// </summary>
/// <param name="ApduCmd">APDUCommand object with the APDU to send to the card</param>
/// <returns>An APDUResponse object with the response from the card</returns>
public override APDUResponse Transmit(APDUCommand ApduCmd)
{
uint RecvLength = (uint) (ApduCmd.Le + APDUResponse.SW_LENGTH);
byte[] ApduBuffer = null;
byte[] ApduResponse = new byte[RecvLength];
SCard_IO_Request ioRequest = new SCard_IO_Request();
ioRequest.m_dwProtocol = m_nProtocol;
ioRequest.m_cbPciLength = 8;
SCard_IO_Request ioResponse = new SCard_IO_Request();
ioResponse.m_dwProtocol = m_nProtocol;
ioResponse.m_cbPciLength = 8;
// Build the command APDU
if (ApduCmd.Data == null)
{
ApduBuffer = new byte[APDUCommand.APDU_MIN_LENGTH + ((ApduCmd.Le != 0) ? 1 : 0)];
if (ApduCmd.Le != 0)
ApduBuffer[4] = (byte) ApduCmd.Le;
}
else
{
ApduBuffer = new byte[APDUCommand.APDU_MIN_LENGTH + 1 + ApduCmd.Data.Length + ((ApduCmd.Le != 0) ? 1 : 0)];
for (int nI = 0; nI < ApduCmd.Data.Length; nI++)
ApduBuffer[APDUCommand.APDU_MIN_LENGTH + 1 + nI] = ApduCmd.Data[nI];
ApduBuffer[APDUCommand.APDU_MIN_LENGTH] = (byte) ApduCmd.Data.Length;
if (ApduCmd.Le != 0)
ApduBuffer[ApduBuffer.Length - 1] = (byte)ApduCmd.Le;
}
ApduBuffer[0] = ApduCmd.Class;
ApduBuffer[1] = ApduCmd.Ins;
ApduBuffer[2] = ApduCmd.P1;
ApduBuffer[3] = ApduCmd.P2;
m_nLastError = SCardTransmit(m_hCard, ref ioRequest, ApduBuffer, (uint) ApduBuffer.Length, ref ioResponse, ApduResponse, ref RecvLength);
if (m_nLastError != 0)
{
string msg = "SCardTransmit error: " + m_nLastError;
throw new Exception(msg);
}
int sw1 = ApduResponse[ApduResponse.Length - 2] & 0xff;
int sw2 = ApduResponse[ApduResponse.Length - 1] & 0xff;
if (sw1 == 0x6c) //wrong length, read again with correct len
{
ApduBuffer = new byte[] { ApduCmd.Class, ApduCmd.Ins, ApduCmd.P1, ApduCmd.P2, (byte)sw2 };
ApduResponse = new byte[sw2 + APDUResponse.SW_LENGTH];
RecvLength = (uint)ApduResponse.Length;
m_nLastError = SCardTransmit(m_hCard, ref ioRequest, ApduBuffer, (uint)ApduBuffer.Length, ref ioResponse, ApduResponse, ref RecvLength);
if (m_nLastError != 0)
{
string msg = "SCardTransmit error: " + m_nLastError;
throw new Exception(msg);
}
sw1 = ApduResponse[ApduResponse.Length - 2] & 0xff;
sw2 = ApduResponse[ApduResponse.Length - 1] & 0xff;
}
MemoryStream ms = new MemoryStream();
ms.Write(ApduResponse, 0, ApduResponse.Length - APDUResponse.SW_LENGTH);
//while has remaining bytes to be read
while (sw1 == 0x61)
{
ApduBuffer = new byte[] { 0, 0xc0, 0, 0, (byte)sw2 }; //read sw2 number of bytes
ApduResponse = new byte[sw2 + APDUResponse.SW_LENGTH];
RecvLength = (uint)ApduResponse.Length;
m_nLastError = SCardTransmit(m_hCard, ref ioRequest, ApduBuffer, (uint)ApduBuffer.Length, ref ioResponse, ApduResponse, ref RecvLength);
if (m_nLastError != 0)
{
string msg = "SCardTransmit error: " + m_nLastError;
throw new Exception(msg);
}
sw1 = ApduResponse[ApduResponse.Length - 2] & 0xff;
sw2 = ApduResponse[ApduResponse.Length - 1] & 0xff;
if (ApduResponse.Length > APDUResponse.SW_LENGTH)
{
ms.Write(ApduResponse, 0, ApduResponse.Length - APDUResponse.SW_LENGTH);
}
}
ms.WriteByte((byte)sw1);
ms.WriteByte((byte)sw2);
return new APDUResponse(ms.ToArray());
}
/// <summary>
/// Wraps the PSCS function
/// LONG SCardBeginTransaction(
/// SCARDHANDLE hCard
// );
/// </summary>
public override void BeginTransaction()
{
if (m_hCard != IntPtr.Zero)
{
m_nLastError = SCardBeginTransaction(m_hCard);
if (m_nLastError != 0)
{
string msg = "SCardBeginTransaction error: " + m_nLastError;
throw new Exception(msg);
}
}
}
/// <summary>
/// Wraps the PCSC function
/// LONG SCardEndTransaction(
/// SCARDHANDLE hCard,
/// DWORD dwDisposition
/// );
/// </summary>
/// <param name="Disposition">A value from DISCONNECT enum</param>
public override void EndTransaction(DISCONNECT Disposition)
{
if (m_hCard != IntPtr.Zero)
{
m_nLastError = SCardEndTransaction(m_hCard, (UInt32)Disposition);
if (m_nLastError != 0)
{
string msg = "SCardEndTransaction error: " + m_nLastError;
throw new Exception(msg);
}
}
}
/// <summary>
/// Gets the attributes of the card
/// </summary>
/// <param name="AttribId">Identifier for the Attribute to get</param>
/// <returns>Attribute content</returns>
public override byte[] GetAttribute(UInt32 AttribId)
{
byte[] attr = null;
UInt32 attrLen = 0;
m_nLastError = SCardGetAttrib(m_hCard, AttribId, attr, out attrLen);
if (m_nLastError == 0)
{
if (attrLen != 0)
{
attr = new byte[attrLen];
m_nLastError = SCardGetAttrib(m_hCard, AttribId, attr, out attrLen);
if (m_nLastError != 0)
{
string msg = "SCardGetAttr error: " + m_nLastError;
throw new Exception(msg);
}
}
}
else
{
string msg = "SCardGetAttr error: " + m_nLastError;
throw new Exception(msg);
}
return attr;
}
#endregion
/// <summary>
/// This function must implement a card detection mechanism.
///
/// When card insertion is detected, it must call the method CardInserted()
/// When card removal is detected, it must call the method CardRemoved()
///
/// </summary>
protected override void RunCardDetection(object Reader)
{
bool bFirstLoop = true;
IntPtr hContext = IntPtr.Zero; // Local context
IntPtr phContext;
phContext = Marshal.AllocHGlobal(Marshal.SizeOf(hContext));
if (SCardEstablishContext((uint) SCOPE.User, IntPtr.Zero, IntPtr.Zero, phContext) == 0)
{
hContext = Marshal.ReadIntPtr(phContext);
Marshal.FreeHGlobal(phContext);
UInt32 nbReaders = 1;
SCard_ReaderState[] readerState = new SCard_ReaderState[nbReaders];
readerState[0].m_dwCurrentState = (UInt32) CARD_STATE.UNAWARE;
readerState[0].m_szReader = (string)Reader;
UInt32 eventState;
UInt32 currentState = readerState[0].m_dwCurrentState;
// Card detection loop
do
{
if (SCardGetStatusChange(hContext, WAIT_TIME
, readerState, nbReaders) == 0)
{
eventState = readerState[0].m_dwEventState;
currentState = readerState[0].m_dwCurrentState;
// Check state
if (((eventState & (uint) CARD_STATE.CHANGED) == (uint) CARD_STATE.CHANGED) && !bFirstLoop)
{
// State has changed
if ((eventState & (uint) CARD_STATE.EMPTY) == (uint) CARD_STATE.EMPTY)
{
// There is no card, card has been removed -> Fire CardRemoved event
CardRemoved();
}
if (((eventState & (uint)CARD_STATE.PRESENT) == (uint)CARD_STATE.PRESENT) &&
((eventState & (uint) CARD_STATE.PRESENT) != (currentState & (uint) CARD_STATE.PRESENT)))
{
// There is a card in the reader -> Fire CardInserted event
CardInserted();
}
if ((eventState & (uint) CARD_STATE.ATRMATCH) == (uint) CARD_STATE.ATRMATCH)
{
// There is a card in the reader and it matches the ATR we were expecting-> Fire CardInserted event
CardInserted();
}
}
// The current stateis now the event state
readerState[0].m_dwCurrentState = eventState;
bFirstLoop = false;
}
Thread.Sleep(100);
if (m_bRunCardDetection == false)
break;
}
while (true); // Exit on request
}
else
{
Marshal.FreeHGlobal(phContext);
throw new Exception("PC/SC error");
}
SCardReleaseContext(hContext);
}
}
}