-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathscard_windows.go
4323 lines (3858 loc) · 126 KB
/
scard_windows.go
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
//go:build windows
// +build windows
// Copyright (c) 2023-2024, El Mostafa IDRASSI.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package goscard
import (
"bytes"
"encoding/binary"
"encoding/hex"
"fmt"
"path/filepath"
"syscall"
"unsafe"
"golang.org/x/sys/windows"
)
type hnd uintptr
type dword uint32
//////////////////////////////////////////////////////////////////////////////////////
// Misc.
//////////////////////////////////////////////////////////////////////////////////////
func hexStringToByteArray(s string) ([]byte, error) {
return hex.DecodeString(s)
}
func byteArrayToHexString(data []byte) string {
return hex.EncodeToString(data)
}
// utf16BytesToString transforms a []byte which contains a wide char string in LE
// into its []uint16 corresponding representation,
// then returns the UTF-8 encoding of the UTF-16 sequence,
// with a terminating NUL removed. If after converting the []byte into
// a []uint16, there is a NUL uint16, the conversion to string stops
// at that NUL uint16.
func utf16BytesToString(buf []byte) (string, error) {
if len(buf)%2 != 0 {
return "", fmt.Errorf("input is not a valid byte representation of a wide char string in LE")
}
b := make([]uint16, len(buf)/2)
// LPCSTR (Windows' representation of utf16) is always little endian.
if err := binary.Read(bytes.NewReader(buf), binary.LittleEndian, b); err != nil {
return "", err
}
return windows.UTF16ToString(b), nil
}
// utf16ToString transforms a []utf16 which contains a wide char string in LE
// into its UTF-8 encoding representation, with a terminating NUL removed.
// The conversion stops at the first encountered NUL uint16.
func utf16ToString(buf []uint16) (string, error) {
return windows.UTF16ToString(buf), nil
}
// utf16PtrToString transforms a *utf16 which contains a wide char string in LE
// into its UTF-8 encoding representation, with a terminating NUL removed.
// The conversion stops at the first encountered NUL uint16.
func utf16PtrToString(buf *uint16) string {
return windows.UTF16PtrToString(buf)
}
// stringToUtf16Ptr returns the UTF-16 encoding of the UTF-8 string
// str, with a terminating NUL added. If str contains a NUL byte at any
// location, it returns (nil, EINVAL).
func stringToUtf16(str string) ([]uint16, error) {
if str == "" {
return nil, nil
}
return windows.UTF16FromString(str)
}
// stringToUtf16Ptr returns the UTF-16 encoding of the UTF-8 string
// str, with a terminating NUL added. If str contains a NUL byte at any
// location, it returns (nil, EINVAL).
func stringToUtf16Ptr(str string) (*uint16, error) {
if str == "" {
return nil, nil
}
return windows.UTF16PtrFromString(str)
}
// bytesToUtf16Ptr returns the UTF-16 encoding of the UTF-8 string
// contained in buf as a byte array, with a terminating NUL added.
// If str contains a NUL byte at any location, it returns (nil, EINVAL).
func bytesToUtf16Ptr(buf []byte) (*uint16, error) {
str := string(buf)
return stringToUtf16Ptr(str)
}
// bytesToUtf16 returns the UTF-16 encoding of the UTF-8 string
// contained in buf as a byte array, with a terminating NUL added.
// If str contains a NUL byte at any location, it returns (nil, EINVAL).
func bytesToUtf16(buf []byte) ([]uint16, error) {
str := string(buf)
return stringToUtf16(str)
}
// stringToUtf16Bytes returns the UTF-16 encoding of the UTF-8 string
// str, as a byte array with a terminating NUL added. If str contains a NUL byte at any
// location, it returns (nil, EINVAL).
func stringToUtf16Bytes(str string) ([]byte, error) {
if str == "" {
return nil, nil
}
utf16Str, err := windows.UTF16FromString(str)
if err != nil {
return nil, err
}
bytesStr := make([]byte, len(utf16Str)*2)
j := 0
for _, utf16 := range utf16Str {
b := make([]byte, 2)
// LPCSTR (Windows' representation of utf16) is always little endian.
binary.LittleEndian.PutUint16(b, utf16)
bytesStr[j] = b[0]
bytesStr[j+1] = b[1]
j += 2
}
return bytesStr, nil
}
// stringToUtf16String returns the UTF-16 encoding of the UTF-8 string
// str, with a terminating NUL added. If str contains a NUL byte at any
// location, it returns (nil, EINVAL).
func stringToUtf16String(str string) ([]uint16, error) {
if str == "" {
return nil, nil
}
utf16Str, err := windows.UTF16FromString(str)
if err != nil {
return nil, err
}
return utf16Str, nil
}
// multiUtf16StringToStrings splits a []utf16, which contains one or
// more wide char strings in LE separated with \0 (multi-string),
// into separate UTF-8 strings and returns them in as a string
// array.
func multiUtf16StringToStrings(multiUtf16String []uint16) ([]string, error) {
var strings []string
for len(multiUtf16String) > 0 && multiUtf16String[0] != 0 {
i := 0
for i = range multiUtf16String {
if multiUtf16String[i] == 0 {
break
}
}
str, err := utf16ToString(multiUtf16String[:i+1]) // need to include the \0, therefore i+1
if err != nil {
return nil, err
}
strings = append(strings, str)
multiUtf16String = multiUtf16String[i+1:]
}
return strings, nil
}
// stringsToMultiUtf16String creates a wide char multi-string
// from the passed string array. The wide char strings are
// separated with \0, and the whole multi-string is terminated
// with a double \0.
func stringsToMultiUtf16String(strings []string) ([]uint16, error) {
var multiUtf16String []uint16
for _, str := range strings {
utf16String, err := stringToUtf16(str)
if err != nil {
return nil, err
}
multiUtf16String = append(multiUtf16String, utf16String...)
}
multiUtf16String = append(multiUtf16String, 0x00) // Add terminating \0 to get a double trailing zero.
return multiUtf16String, nil
}
// ======================================================================================
// Windows error codes.
// From C:\Program Files (x86)\Windows Kits\10\Include\10.0.19041.0\shared\winerror.h.
// ======================================================================================
var (
// Smart Card Error Codes.
scardErrNums = map[uint64]string{
0x80100001: "SCARD_F_INTERNAL_ERROR",
0x80100002: "SCARD_E_CANCELLED",
0x80100003: "SCARD_E_INVALID_HANDLE",
0x80100004: "SCARD_E_INVALID_PARAMETER",
0x80100005: "SCARD_E_INVALID_TARGET",
0x80100006: "SCARD_E_NO_MEMORY",
0x80100007: "SCARD_F_WAITED_TOO_LONG",
0x80100008: "SCARD_E_INSUFFICIENT_BUFFER",
0x80100009: "SCARD_E_UNKNOWN_READER",
0x8010000A: "SCARD_E_TIMEOUT",
0x8010000B: "SCARD_E_SHARING_VIOLATION",
0x8010000C: "SCARD_E_NO_SMARTCARD",
0x8010000D: "SCARD_E_UNKNOWN_CARD",
0x8010000E: "SCARD_E_CANT_DISPOSE",
0x8010000F: "SCARD_E_PROTO_MISMATCH",
0x80100010: "SCARD_E_NOT_READY",
0x80100011: "SCARD_E_INVALID_VALUE",
0x80100012: "SCARD_E_SYSTEM_CANCELLED",
0x80100013: "SCARD_F_COMM_ERROR",
0x80100014: "SCARD_F_UNKNOWN_ERROR",
0x80100015: "SCARD_E_INVALID_ATR",
0x80100016: "SCARD_E_NOT_TRANSACTED",
0x80100017: "SCARD_E_READER_UNAVAILABLE",
0x80100018: "SCARD_P_SHUTDOWN",
0x80100019: "SCARD_E_PCI_TOO_SMALL",
0x8010001A: "SCARD_E_READER_UNSUPPORTED",
0x8010001B: "SCARD_E_DUPLICATE_READER",
0x8010001C: "SCARD_E_CARD_UNSUPPORTED",
0x8010001D: "SCARD_E_NO_SERVICE",
0x8010001E: "SCARD_E_SERVICE_STOPPED",
0x8010001F: "SCARD_E_UNEXPECTED",
0x80100020: "SCARD_E_ICC_INSTALLATION",
0x80100021: "SCARD_E_ICC_CREATEORDER",
0x80100022: "SCARD_E_UNSUPPORTED_FEATURE",
0x80100023: "SCARD_E_DIR_NOT_FOUND",
0x80100024: "SCARD_E_FILE_NOT_FOUND",
0x80100025: "SCARD_E_NO_DIR",
0x80100026: "SCARD_E_NO_FILE",
0x80100027: "SCARD_E_NO_ACCESS",
0x80100028: "SCARD_E_WRITE_TOO_MANY",
0x80100029: "SCARD_E_BAD_SEEK",
0x8010002A: "SCARD_E_INVALID_CHV",
0x8010002B: "SCARD_E_UNKNOWN_RES_MNG",
0x8010002C: "SCARD_E_NO_SUCH_CERTIFICATE",
0x8010002D: "SCARD_E_CERTIFICATE_UNAVAILABLE",
0x8010002E: "SCARD_E_NO_READERS_AVAILABLE",
0x8010002F: "SCARD_E_COMM_DATA_LOST",
0x80100030: "SCARD_E_NO_KEY_CONTAINER",
0x80100031: "SCARD_E_SERVER_TOO_BUSY",
0x80100032: "SCARD_E_PIN_CACHE_EXPIRED",
0x80100033: "SCARD_E_NO_PIN_CACHE",
0x80100034: "SCARD_E_READ_ONLY_CARD",
0x80100065: "SCARD_W_UNSUPPORTED_CARD",
0x80100066: "SCARD_W_UNRESPONSIVE_CARD",
0x80100067: "SCARD_W_UNPOWERED_CARD",
0x80100068: "SCARD_W_RESET_CARD",
0x80100069: "SCARD_W_REMOVED_CARD",
0x8010006A: "SCARD_W_SECURITY_VIOLATION",
0x8010006B: "SCARD_W_WRONG_CHV",
0x8010006C: "SCARD_W_CHV_BLOCKED",
0x8010006D: "SCARD_W_EOF",
0x8010006E: "SCARD_W_CANCELLED_BY_USER",
0x8010006F: "SCARD_W_CARD_NOT_AUTHENTICATED",
0x80100070: "SCARD_W_CACHE_ITEM_NOT_FOUND",
0x80100071: "SCARD_W_CACHE_ITEM_STALE",
0x80100072: "SCARD_W_CACHE_ITEM_TOO_BIG",
}
)
func maybePcscErr(errNo uintptr) error {
if code, known := scardErrNums[uint64(errNo)]; known {
return fmt.Errorf("scard failure: 0x%.8X (%s) (%s)", errNo, code, syscall.Errno(errNo).Error())
} else {
return fmt.Errorf("errno code: 0x%.8X (%s)", errNo, syscall.Errno(errNo).Error())
}
}
//////////////////////////////////////////////////////////////////////////////////////
// WinSMCRD header content.
// From C:\Program Files (x86)\Windows Kits\10\Include\10.0.19041.0\shared\winsmcrd.h
//////////////////////////////////////////////////////////////////////////////////////
const (
methodBuffered dword = 0 // From C:\Program Files (x86)\Windows Kits\10\Include\10.0.19041.0\um\winioctl.h
fileAnyAccess dword = 0 // From C:\Program Files (x86)\Windows Kits\10\Include\10.0.19041.0\um\winioctl.h
fileDeviceSmartCard dword = 0x00000031
scardAtrLength dword = 33 // ISO 7816-3 spec.
infiniteTimeout dword = 0xFFFFFFFF
maxBufferSize dword = 258 // Maximum Tx/Rx Buffer for short APDU
maxBufferSizeExtended dword = 65538 // Maximum Tx/Rx Buffer for extended APDU
)
//
///////////////////////////////////////////////////////////////////////////////
//
// Protocol Flag definitions
//
type SCardProtocol dword
const (
SCardProtocolUndefined SCardProtocol = 0x00000000 // There is no active protocol.
SCardProtocolT0 SCardProtocol = 0x00000001 // T=0 is the active protocol.
SCardProtocolT1 SCardProtocol = 0x00000002 // T=1 is the active protocol.
SCardProtocolRaw SCardProtocol = 0x00010000 // Raw is the active protocol.
//
// This is the mask of ISO defined transmission protocols
//
SCardProtocolTx SCardProtocol = SCardProtocolT0 | SCardProtocolT1
SCardProtocolAny SCardProtocol = SCardProtocolTx
//
// Use the default transmission parameters / card clock freq.
//
SCardProtocolDefault SCardProtocol = 0x80000000
//
// Use optimal transmission parameters / card clock freq.
// Since using the optimal parameters is the default case no bit is defined to be 1
//
SCardProtocolOptimal SCardProtocol = 0x00000000
//
// T=15 protocol.
//
SCardProtocolT15 SCardProtocol = 0x00000008
)
func (p SCardProtocol) String() string {
output := ""
if p == SCardProtocolUndefined {
output += "Undefined"
} else {
if p&SCardProtocolT0 == SCardProtocolT0 {
output += "T0;"
}
if p&SCardProtocolT1 == SCardProtocolT1 {
output += "T1;"
}
if p&SCardProtocolT15 == SCardProtocolT15 {
output += "T15;"
}
if p&SCardProtocolRaw == SCardProtocolRaw {
output += "Raw;"
}
if p&SCardProtocolDefault == SCardProtocolDefault {
output += "Default;"
}
if len(output) > 0 {
output = output[:len(output)-1] // Remove last ';'
}
}
return output
}
// Ioctl parameters 1 for IOCTL_SMARTCARD_POWER
type SCardPowerOperation dword
const (
SCardPowerDown SCardPowerOperation = 0 // Power down the card.
SCardColdReset SCardPowerOperation = 1 // Cycle power and reset the card.
SCardWarmReset SCardPowerOperation = 2 // Force a reset on the card.
)
func (p *SCardPowerOperation) String() string {
switch *p {
case SCardPowerDown:
return "PowerDown"
case SCardColdReset:
return "ColdReset"
case SCardWarmReset:
return "WarmReset"
default:
return "N/A"
}
}
//
///////////////////////////////////////////////////////////////////////////////
//
// Reader Action IOCTLs
//
type SCardCtlCode dword
// From C:\Program Files (x86)\Windows Kits\10\Include\10.0.19041.0\um\winioctl.h
func ctlCode(DeviceType, Function, Method, Access dword) dword {
return ((DeviceType << 16) | (Access << 14) | (Function << 2) | Method)
}
func scardCtlCodeFunc(code dword) SCardCtlCode {
return SCardCtlCode(ctlCode(fileDeviceSmartCard, code, methodBuffered, fileAnyAccess))
}
var (
IoctlSmartCardPower = scardCtlCodeFunc(1)
IoctlSmartCardGetAttribute = scardCtlCodeFunc(2)
IoctlSmartCardSetAttribute = scardCtlCodeFunc(3)
IoctlSmartCardConfiscate = scardCtlCodeFunc(4)
IoctlSmartCardTransmit = scardCtlCodeFunc(5)
IoctlSmartCardEject = scardCtlCodeFunc(6)
IoctlSmartCardSwallow = scardCtlCodeFunc(7)
IoctlSmartCardIsPresent = scardCtlCodeFunc(10)
IoctlSmartCardIsAbsent = scardCtlCodeFunc(11)
IoctlSmartCardSetProtocol = scardCtlCodeFunc(12)
IoctlSmartCardGetState = scardCtlCodeFunc(14)
IoctlSmartCardGetLastError = scardCtlCodeFunc(15)
IoctlSmartCardGetPerfCntr = scardCtlCodeFunc(16)
IoctlSmartCardGetFeatureRequest = scardCtlCodeFunc(3400)
// IoctlSmartCardRead = scardCtlCodeFunc(8) obsolete
// IoctlSmartCardWrite = scardCtlCodeFunc(9) obsolete
)
//
///////////////////////////////////////////////////////////////////////////////
//
// Tags for requesting card and reader attributes
//
const (
maximumAttrStringLength = 32 // Nothing bigger than this from getAttr
maximumSmartcardReaders = 10 // Limit the readers on the system
)
type SCardAttr dword
type SCardClass dword
func scardAttrValue(class SCardClass, tag dword) SCardAttr {
return SCardAttr((dword(class) << 16) | tag)
}
const (
SCardClassVendorInfo SCardClass = 1 // Vendor information definitions
SCardClassCommunications SCardClass = 2 // Communication definitions
SCardClassProtocol SCardClass = 3 // Protocol definitions
SCardClassPowerMgmt SCardClass = 4 // Power Management definitions
SCardClassSecurity SCardClass = 5 // Security Assurance definitions
SCardClassMechanical SCardClass = 6 // Mechanical characteristic definitions
SCardClassVendorDefined SCardClass = 7 // Vendor specific definitions
SCardClassIFDProtocol SCardClass = 8 // Interface Device Protocol options
SCardClassICCState SCardClass = 9 // ICC State specific definitions
SCardClassPerf SCardClass = 0x7ffe // Performance counters
SCardClassSystem SCardClass = 0x7fff // System-specific definitions
)
func (c *SCardClass) String() string {
switch *c {
case SCardClassVendorInfo:
return "VendorInfo"
case SCardClassCommunications:
return "Communications"
case SCardClassProtocol:
return "Protocol"
case SCardClassPowerMgmt:
return "PowerMgmt"
case SCardClassSecurity:
return "Security"
case SCardClassMechanical:
return "Mechanical"
case SCardClassVendorDefined:
return "VendorDefined"
case SCardClassIFDProtocol:
return "IFDProtocol"
case SCardClassICCState:
return "ICCState"
case SCardClassPerf:
return "Perf"
case SCardClassSystem:
return "System"
default:
return "N/A"
}
}
var (
SCardAttrVendorName SCardAttr = scardAttrValue(SCardClassVendorInfo, 0x0100)
SCardAttrVendorIFDType SCardAttr = scardAttrValue(SCardClassVendorInfo, 0x0101)
SCardAttrVendorIFDVersion SCardAttr = scardAttrValue(SCardClassVendorInfo, 0x0102)
SCardAttrVendorIFDSerialNo SCardAttr = scardAttrValue(SCardClassVendorInfo, 0x0103)
SCardAttrChannelID SCardAttr = scardAttrValue(SCardClassCommunications, 0x0110)
//SCardAttrAsyncProtocolTypes SCardAttr = scardAttrValue(SCardClassProtocol, 0x0120)
SCardAttrDefaultClk SCardAttr = scardAttrValue(SCardClassProtocol, 0x0121)
SCardAttrMaxClk SCardAttr = scardAttrValue(SCardClassProtocol, 0x0122)
SCardAttrDefaultDataRate SCardAttr = scardAttrValue(SCardClassProtocol, 0x0123)
SCardAttrMaxDataRate SCardAttr = scardAttrValue(SCardClassProtocol, 0x0124)
SCardAttrMaxIFSD SCardAttr = scardAttrValue(SCardClassProtocol, 0x0125)
//SCardAttrSyncProtocolTypes SCardAttr = scardAttrValue(SCardClassProtocol, 0x0126)
SCardAttrPowerMgmtSupport SCardAttr = scardAttrValue(SCardClassPowerMgmt, 0x0131)
SCardAttrUserToCardAuthDevice SCardAttr = scardAttrValue(SCardClassSecurity, 0x0140)
SCardAttrUserAuthInputDevice SCardAttr = scardAttrValue(SCardClassSecurity, 0x0142)
SCardAttrCharacteristics SCardAttr = scardAttrValue(SCardClassMechanical, 0x0150)
SCardAttrCurrentProtocolType SCardAttr = scardAttrValue(SCardClassIFDProtocol, 0x0201)
SCardAttrCurrentClk SCardAttr = scardAttrValue(SCardClassIFDProtocol, 0x0202)
SCardAttrCurrentF SCardAttr = scardAttrValue(SCardClassIFDProtocol, 0x0203)
SCardAttrCurrentD SCardAttr = scardAttrValue(SCardClassIFDProtocol, 0x0204)
SCardAttrCurrentN SCardAttr = scardAttrValue(SCardClassIFDProtocol, 0x0205)
SCardAttrCurrentW SCardAttr = scardAttrValue(SCardClassIFDProtocol, 0x0206)
SCardAttrCurrentIFSC SCardAttr = scardAttrValue(SCardClassIFDProtocol, 0x0207)
SCardAttrCurrentIFSD SCardAttr = scardAttrValue(SCardClassIFDProtocol, 0x0208)
SCardAttrCurrentBWT SCardAttr = scardAttrValue(SCardClassIFDProtocol, 0x0209)
SCardAttrCurrentCWT SCardAttr = scardAttrValue(SCardClassIFDProtocol, 0x020a)
SCardAttrCurrentEBCEncoding SCardAttr = scardAttrValue(SCardClassIFDProtocol, 0x020b)
SCardAttrExtendedBWT SCardAttr = scardAttrValue(SCardClassIFDProtocol, 0x020c)
SCardAttrICCPresence SCardAttr = scardAttrValue(SCardClassICCState, 0x0300)
SCardAttrICCInterfaceStatus SCardAttr = scardAttrValue(SCardClassICCState, 0x0301)
SCardAttrCurrentIOState SCardAttr = scardAttrValue(SCardClassICCState, 0x0302)
SCardAttrATRString SCardAttr = scardAttrValue(SCardClassICCState, 0x0303)
SCardAttrICCTYPEPerATR SCardAttr = scardAttrValue(SCardClassICCState, 0x0304)
SCardAttrESCReset SCardAttr = scardAttrValue(SCardClassVendorDefined, 0xA000)
SCardAttrESCCancel SCardAttr = scardAttrValue(SCardClassVendorDefined, 0xA003)
SCardAttrESCAuthRequest SCardAttr = scardAttrValue(SCardClassVendorDefined, 0xA005)
SCardAttrMaxInput SCardAttr = scardAttrValue(SCardClassVendorDefined, 0xA007)
SCardAttrVendorSpecificInfo SCardAttr = scardAttrValue(SCardClassVendorDefined, 0xA008)
SCardAttrDeviceUnit SCardAttr = scardAttrValue(SCardClassSystem, 0x0001)
SCardAttrDeviceInUse SCardAttr = scardAttrValue(SCardClassSystem, 0x0002)
SCardAttrDeviceFriendlyNameA SCardAttr = scardAttrValue(SCardClassSystem, 0x0003)
SCardAttrDeviceSystemNameA SCardAttr = scardAttrValue(SCardClassSystem, 0x0004)
SCardAttrDeviceFriendlyNameW SCardAttr = scardAttrValue(SCardClassSystem, 0x0005)
SCardAttrDeviceSystemNameW SCardAttr = scardAttrValue(SCardClassSystem, 0x0006)
SCardAttrSuppressT1IFSRequest SCardAttr = scardAttrValue(SCardClassSystem, 0x0007)
SCarddAttrPerfNumTransmissions SCardAttr = scardAttrValue(SCardClassPerf, 0x0001)
SCarddAttrPerfBytesTransmitted SCardAttr = scardAttrValue(SCardClassPerf, 0x0002)
SCarddAttrPerfTransmissionTime SCardAttr = scardAttrValue(SCardClassPerf, 0x0003)
SCardAttrDeviceFriendlyName SCardAttr = SCardAttrDeviceFriendlyNameW
SCardAttrDeviceSystemName SCardAttr = SCardAttrDeviceSystemNameW
)
func (a *SCardAttr) String() string {
switch *a {
case SCardAttrVendorName:
return "VendorName"
case SCardAttrVendorIFDType:
return "VendorIFDType"
case SCardAttrVendorIFDVersion:
return "VendorIFDVersion"
case SCardAttrVendorIFDSerialNo:
return "VendorIFDSerialNo"
case SCardAttrChannelID:
return "ChannelID"
case SCardAttrDefaultClk:
return "DefaultClk"
case SCardAttrMaxClk:
return "MaxClk"
case SCardAttrDefaultDataRate:
return "DefaultDataRate"
case SCardAttrMaxDataRate:
return "MaxDataRate"
case SCardAttrMaxIFSD:
return "MaxIFSD"
case SCardAttrPowerMgmtSupport:
return "PowerMgmtSupport"
case SCardAttrUserToCardAuthDevice:
return "UserToCardAuthDevice"
case SCardAttrUserAuthInputDevice:
return "UserAuthInputDevice"
case SCardAttrCharacteristics:
return "Characteristics"
case SCardAttrCurrentProtocolType:
return "CurrentProtocolType"
case SCardAttrCurrentClk:
return "CurrentClk"
case SCardAttrCurrentF:
return "CurrentF"
case SCardAttrCurrentD:
return "CurrentD"
case SCardAttrCurrentN:
return "CurrentN"
case SCardAttrCurrentW:
return "CurrentW"
case SCardAttrCurrentIFSC:
return "CurrentIFSC"
case SCardAttrCurrentIFSD:
return "CurrentIFSD"
case SCardAttrCurrentBWT:
return "CurrentBWT"
case SCardAttrCurrentCWT:
return "CurrentCWT"
case SCardAttrCurrentEBCEncoding:
return "CurrentEBCEncoding"
case SCardAttrExtendedBWT:
return "ExtendedBWT"
case SCardAttrICCPresence:
return "ICCPresence"
case SCardAttrICCInterfaceStatus:
return "ICCInterfaceStatus"
case SCardAttrCurrentIOState:
return "CurrentIOState"
case SCardAttrATRString:
return "ATRString"
case SCardAttrICCTYPEPerATR:
return "ICCTYPEPerATR"
case SCardAttrESCReset:
return "ESCReset"
case SCardAttrESCCancel:
return "ESCCancel"
case SCardAttrESCAuthRequest:
return "ESCAuthRequest"
case SCardAttrMaxInput:
return "MaxInput"
case SCardAttrVendorSpecificInfo:
return "VendorSpecificInfo"
case SCardAttrDeviceUnit:
return "DeviceUnit"
case SCardAttrDeviceInUse:
return "DeviceInUse"
case SCardAttrDeviceFriendlyNameA:
return "DeviceFriendlyNameA"
case SCardAttrDeviceSystemNameA:
return "DeviceSystemNameA"
case SCardAttrDeviceFriendlyNameW:
case SCardAttrDeviceFriendlyName:
return "DeviceFriendlyNameW"
case SCardAttrDeviceSystemNameW:
case SCardAttrDeviceSystemName:
return "DeviceSystemNameW"
case SCardAttrSuppressT1IFSRequest:
return "SuppressT1IFSRequest"
case SCarddAttrPerfNumTransmissions:
return "PerfNumTransmissions"
case SCarddAttrPerfBytesTransmitted:
return "PerfBytesTransmitted"
case SCarddAttrPerfTransmissionTime:
return "PerfTransmissionTime"
}
return "N/A"
}
// T=0 Protocol Defines
const (
scardT0HeaderLength = 7
scardT0CmdLength = 5
)
// T=1 Protocol Defines
const (
scardT1PrologueLength = 3
scardT1EpilogueLength = 2 // CRC
scardT1EpilogueLengthLRC = 1
scardT1MaxIFs = 254
)
//
///////////////////////////////////////////////////////////////////////////////
//
// Reader states
//
type ReaderState dword
const (
SCardUnknown ReaderState = 0 // This value implies the driver is unaware of the current state of the reader.
SCardAbsent ReaderState = 1 // This value implies there is no card in the reader.
SCardPresent ReaderState = 2 // This value implies there is a card is present in the reader, but that it has not been moved into position for use.
SCardSwallowed ReaderState = 3 // This value implies there is a card in the reader in position for use. The card is not powered.
SCardPowered ReaderState = 4 // This value implies there is power is being provided to the card, but the Reader Driver is unaware of the mode of the card.
SCardNegotiable ReaderState = 5 // This value implies the card has been reset and is awaiting PTS negotiation.
SCardSpecific ReaderState = 6 // This value implies the card has been reset and specific communication protocols have been established.
)
func (s *ReaderState) String() string {
switch *s {
case SCardUnknown:
return "Unknown"
case SCardAbsent:
return "Absent"
case SCardPresent:
return "Present"
case SCardSwallowed:
return "Swallowed"
case SCardPowered:
return "Powered"
case SCardNegotiable:
return "Negotiable"
case SCardSpecific:
return "Specific"
default:
return "N/A"
}
}
////////////////////////////////////////////////////////////////////////////////
//
// I/O Services
//
// The following services provide access to the I/O capabilities of the
// reader drivers. Services of the Smart Card are requested by placing the
// following structure into the protocol buffer:
//
type SCardIORequest struct {
Protocol dword // Protocol identifier
PciLength dword // Protocol Control Information Length
}
//
////////////////////////////////////////////////////////////////////////////////
//
// Driver attribute flags
//
type DriverAttribute dword
const (
SCardReaderSwallows DriverAttribute = 0x00000001 // Reader has a card swallowing mechanism.
SCardReaderEjects DriverAttribute = 0x00000002 // Reader has a card ejection mechanism.
SCardReaderConfiscates DriverAttribute = 0x00000004 // Reader has a card capture mechanism.
SCardReaderContactless DriverAttribute = 0x00000008 // Reader supports contactless.
)
func (a *DriverAttribute) String() string {
switch *a {
case SCardReaderSwallows:
return "Swallows"
case SCardReaderEjects:
return "Ejects"
case SCardReaderConfiscates:
return "Confiscates"
case SCardReaderContactless:
return "Contactless"
default:
return "N/A"
}
}
// /////////////////////////////////////////////////////////////////////////////
//
// Type of reader
type SCardReaderType dword
const (
SCardReaderTypeSerial SCardReaderType = 0x01
SCardReaderTypeParallel SCardReaderType = 0x02
SCardReaderTypeKeyboard SCardReaderType = 0x04
SCardReaderTypeSCSI SCardReaderType = 0x08
SCardReaderTypeIDE SCardReaderType = 0x10
SCardReaderTypeUSB SCardReaderType = 0x20
SCardReaderTypePCMCIA SCardReaderType = 0x40
SCardReaderTypeTPM SCardReaderType = 0x80
SCardReaderTypeNFC SCardReaderType = 0x100
SCardReaderTypeUICC SCardReaderType = 0x200
SCardReaderTypeNGC SCardReaderType = 0x400
SCardReaderTypeEmbeddedSE SCardReaderType = 0x800
SCardReaderTypeVendor SCardReaderType = 0xF0
)
func (t *SCardReaderType) String() string {
switch *t {
case SCardReaderTypeSerial:
return "Serial"
case SCardReaderTypeParallel:
return "Parallel"
case SCardReaderTypeKeyboard:
return "Keyboard"
case SCardReaderTypeSCSI:
return "SCSI"
case SCardReaderTypeIDE:
return "IDE"
case SCardReaderTypeUSB:
return "USB"
case SCardReaderTypePCMCIA:
return "PCMCIA"
case SCardReaderTypeTPM:
return "TPM"
case SCardReaderTypeNFC:
return "NFC"
case SCardReaderTypeUICC:
return "UICC"
case SCardReaderTypeNGC:
return "NGC"
case SCardReaderTypeEmbeddedSE:
return "EmbeddedSE"
case SCardReaderTypeVendor:
return "Vendor"
default:
return "N/A"
}
}
//////////////////////////////////////////////////////////////////////////////////////
// WinSCard header content.
// From C:\Program Files (x86)\Windows Kits\10\Include\10.0.19041.0\um\winscard.h
//////////////////////////////////////////////////////////////////////////////////////
//
////////////////////////////////////////////////////////////////////////////////
//
// Service Manager Access Services
//
// The following services are used to manage user and terminal contexts for
// Smart Cards.
//
type SCardContext hnd
type SCardHandle hnd
const invalidHandleValue = ^hnd(0)
const scardAutoAllocate = ^dword(0)
type SCardScope dword
const (
// The context is a user context, and any
// database operations are performed within the
// domain of the user.
SCardScopeUser SCardScope = 0
// The context is that of the current terminal,
// and any database operations are performed
// within the domain of that terminal. (The
// calling application must have appropriate
// access permissions for any database actions.)
// This flag is currently unused; it is here for
// compatibility with [PCSC5] section 3.1.3.
// Using this flag with SCardEstablishContext
// returns SCARD_E_INVALID_VALUE.
SCardScopeTerminal SCardScope = 1
// The context is the system context, and any
// database operations are performed within the
// domain of the system. (The calling
// application must have appropriate access
// permissions for any database actions.)
SCardScopeSystem SCardScope = 2
)
func (s *SCardScope) String() string {
switch *s {
case SCardScopeUser:
return "User"
case SCardScopeTerminal:
return "Terminal"
case SCardScopeSystem:
return "System"
default:
return "N/A"
}
}
//
////////////////////////////////////////////////////////////////////////////////
//
// Smart Card Database Management Services
//
// The following services provide for managing the Smart Card Database.
//
const (
SCardAllReaders = "SCard$AllReaders"
SCardDefaultReaders = "SCard$DefaultReaders"
SCardLocalReaders = "SCard$LocalReaders"
SCardSystemReaders = "SCard$SystemReaders"
)
type SCardProviderType dword
const (
SCardProviderPrimary SCardProviderType = 1 // Primary Provider Id
SCardProviderCSP SCardProviderType = 2 // Crypto Service Provider Id
SCardProviderKSP SCardProviderType = 3 // Key Storage Provider Id
SCardProviderCardModule SCardProviderType = 0x80000001 // Name of the card module
)
func (t *SCardProviderType) String() string {
switch *t {
case SCardProviderPrimary:
return "Primary"
case SCardProviderCSP:
return "CSP"
case SCardProviderKSP:
return "KSP"
case SCardProviderCardModule:
return "CardModule"
default:
return "N/A"
}
}
//
////////////////////////////////////////////////////////////////////////////////
//
// Reader Services
//
// The following services supply means for tracking cards within readers.
//
// This is the actual golang equivalent of Windows SCardReaderState.
type scardReaderState struct {
Reader *uint16 // reader name
UserData unsafe.Pointer // user defined data
CurrentState SCardState // current state of reader at time of call
EventState SCardState // state of reader after state change
AtrLen dword // Number of bytes in the returned ATR
Atr [36]byte // Atr of inserted card (extra alignment bytes)
}
type SCardReaderState struct {
Reader string // reader name
UserData unsafe.Pointer // user defined data
CurrentState SCardState // current state of reader at time of call
EventState SCardState // state of reader after state change
Atr string // Atr of inserted card
}
func (s *SCardReaderState) fromInternal(internalReaderState scardReaderState) {
s.Reader = utf16PtrToString(internalReaderState.Reader)
s.UserData = internalReaderState.UserData
s.CurrentState = internalReaderState.CurrentState
s.EventState = internalReaderState.EventState
if internalReaderState.AtrLen > 0 {
s.Atr = byteArrayToHexString(internalReaderState.Atr[:internalReaderState.AtrLen])
}
}
func (s *SCardReaderState) toInternal() (scardReaderState, error) {
var atrBytes []byte
var atr [36]byte
var atrLen dword
readerNameUtf16Ptr, err := stringToUtf16Ptr(s.Reader)
if err != nil {
return scardReaderState{}, fmt.Errorf("failed to parse reader name \"%s\" (%w)", s.Reader, err)
}
if len(s.Atr) > 0 {
atrBytes, err = hexStringToByteArray(s.Atr)
if err != nil {
return scardReaderState{}, fmt.Errorf("failed to parse atr \"%s\" (%w)", s.Atr, err)
}
copy(atr[:], atrBytes)
atrLen = dword(len(atrBytes))
if len(atrBytes) > 36 {
atrLen = 36
}
}
return scardReaderState{
Reader: readerNameUtf16Ptr,
UserData: s.UserData,
CurrentState: s.CurrentState,
EventState: s.EventState,
AtrLen: atrLen,
Atr: atr,
}, nil
}
type SCardState dword
const (
// The application is unaware of the
// current state, and would like to
// know. The use of this value
// results in an immediate return
// from state transition monitoring
// services. This is represented by
// all bits set to zero.
SCardStateUnaware SCardState = 0x00000000
// The application requested that
// this reader be ignored. No other
// bits will be set.
SCardStateIgnore SCardState = 0x00000001
// This implies that there is a
// difference between the state
// believed by the application, and
// the state known by the Service
// Manager. When this bit is set,
// the application may assume a
// significant state change has
// occurred on this reader.
SCardStateChanged SCardState = 0x00000002
// This implies that the given
// reader name is not recognized by
// the Service Manager. If this bit
// is set, then SCARD_STATE_CHANGED
// and SCARD_STATE_IGNORE will also
// be set.
SCardStateUnknown SCardState = 0x00000004
// This implies that the actual
// state of this reader is not
// available. If this bit is set,
// then all the following bits are
// clear.
SCardStateUnavailable SCardState = 0x00000008
// This implies that there is not
// card in the reader. If this bit
// is set, all the following bits
// will be clear.
SCardStateEmpty SCardState = 0x00000010
// This implies that there is a card
// in the reader.
SCardStatePresent SCardState = 0x00000020