Debian Codegraph @

winscard.go

raw symbols SCIP
1 // BSD 3-Clause License
2 //
3 // Copyright (c) 2019, Guillaume Ballet
4 // All rights reserved.
5 //
6 // Redistribution and use in source and binary forms, with or without
7 // modification, are permitted provided that the following conditions are met:
8 //
9 // * Redistributions of source code must retain the above copyright notice, this
10 // list of conditions and the following disclaimer.
11 //
12 // * Redistributions in binary form must reproduce the above copyright notice,
13 // this list of conditions and the following disclaimer in the documentation
14 // and/or other materials provided with the distribution.
15 //
16 // * Neither the name of the copyright holder nor the names of its
17 // contributors may be used to endorse or promote products derived from
18 // this software without specific prior written permission.
19 //
20 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21 // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
23 // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
24 // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
26 // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
27 // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
28 // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
31 package pcsc
32
33 import (
34 "encoding/binary"
35 "fmt"
36 "net"
37 "sync"
38 "unsafe"
39 )
40
41 // Client contains all the information needed to establish
42 // and maintain a connection to the deamon/card.
43 type Client struct {
44 conn net.Conn
45
46 minor uint32
47 major uint32
48
49 ctx uint32
50
51 mutex sync.Mutex
52
53 readerStateDescriptors [MaxReaderStateDescriptors]ReaderState
54 }
55
56 // EstablishContext asks the PCSC daemon to create a context
57 // handle for further communication with connected cards and
58 // readers.
59 func EstablishContext(path string, scope uint32) (*Client, error) {
60 client := &Client{}
61
62 conn, err := clientSetupSession(path)
63 if err != nil {
64 return nil, err
65 }
66 client.conn = conn
67
68 payload := make([]byte, 12)
69 response := make([]byte, 12)
70
71 var code uint32
72 var minor uint32
73 for minor = ProtocolVersionMinor; minor <= ProtocolVersionMinor+1; minor++ {
74 /* Exchange version information */
75 binary.LittleEndian.PutUint32(payload, ProtocolVersionMajor)
76 binary.LittleEndian.PutUint32(payload[4:], minor)
77 binary.LittleEndian.PutUint32(payload[8:], SCardSuccess.Code())
78 err = messageSendWithHeader(CommandVersion, conn, payload)
79 if err != nil {
80 return nil, err
81 }
82 n, err := conn.Read(response)
83 if err != nil {
84 return nil, err
85 }
86 if n != len(response) {
87 return nil, fmt.Errorf("invalid response length: expected %d, got %d", len(response), n)
88 }
89 code = binary.LittleEndian.Uint32(response[8:])
90 if code != SCardSuccess.Code() {
91 continue
92 }
93 client.major = binary.LittleEndian.Uint32(response)
94 client.minor = binary.LittleEndian.Uint32(response[4:])
95 if client.major != ProtocolVersionMajor || client.minor != minor {
96 continue
97 }
98 break
99 }
100
101 if code != SCardSuccess.Code() {
102 return nil, fmt.Errorf("invalid response code: expected %d, got %d (%v)", SCardSuccess, code, ErrorCode(code).Error())
103 }
104 if client.major != ProtocolVersionMajor || (client.minor != minor && client.minor+1 != minor) {
105 return nil, fmt.Errorf("invalid version found: expected %d.%d, got %d.%d", ProtocolVersionMajor, ProtocolVersionMinor, client.major, client.minor)
106 }
107
108 /* Establish the context proper */
109 binary.LittleEndian.PutUint32(payload, scope)
110 binary.LittleEndian.PutUint32(payload[4:], 0)
111 binary.LittleEndian.PutUint32(payload[8:], SCardSuccess.Code())
112 err = messageSendWithHeader(SCardEstablishContext, conn, payload)
113 if err != nil {
114 return nil, err
115 }
116 response = make([]byte, 12)
117 n, err := conn.Read(response)
118 if err != nil {
119 return nil, err
120 }
121 if n != len(response) {
122 return nil, fmt.Errorf("invalid response length: expected %d, got %d", len(response), n)
123 }
124 code = binary.LittleEndian.Uint32(response[8:])
125 if code != SCardSuccess.Code() {
126 return nil, fmt.Errorf("invalid response code: expected %d, got %d (%v)", SCardSuccess, code, ErrorCode(code).Error())
127 }
128 client.ctx = binary.LittleEndian.Uint32(response[4:])
129
130 return client, nil
131 }
132
133 // ReleaseContext tells the daemon that the client will no longer
134 // need the context.
135 func (client *Client) ReleaseContext() error {
136 client.mutex.Lock()
137 defer client.mutex.Unlock()
138
139 data := [8]byte{}
140 binary.LittleEndian.PutUint32(data[:], client.ctx)
141 binary.LittleEndian.PutUint32(data[4:], SCardSuccess.Code())
142 err := messageSendWithHeader(SCardReleaseContext, client.conn, data[:])
143 if err != nil {
144 return err
145 }
146 total := 0
147 for total < len(data) {
148 n, err := client.conn.Read(data[total:])
149 if err != nil {
150 return err
151 }
152 total += n
153 }
154 code := binary.LittleEndian.Uint32(data[4:])
155 if code != SCardSuccess.Code() {
156 return fmt.Errorf("invalid return code: %x, %v", code, ErrorCode(code).Error())
157 }
158
159 return nil
160 }
161
162 // Constants related to the reader state structure
163 const (
164 ReaderStateNameLength = 128
165 ReaderStateMaxAtrSizeLength = 33
166 // NOTE: ATR is 32-byte aligned in the C version, which means it's
167 // actually 36 byte long and not 33.
168 ReaderStateDescriptorLength = ReaderStateNameLength + ReaderStateMaxAtrSizeLength + 5*4 + 3
169
170 MaxReaderStateDescriptors = 16
171 )
172
173 // ReaderState represent the state of a single reader, as reported
174 // by the PCSC daemon.
175 type ReaderState struct {
176 Name string /* reader name */
177 eventCounter uint32 /* number of card events */
178 readerState uint32 /* SCARD_* bit field */
179 readerSharing uint32 /* PCSCLITE_SHARING_* sharing status */
180
181 cardAtr [ReaderStateMaxAtrSizeLength]byte /* ATR */
182 cardAtrLength uint32 /* ATR length */
183 cardProtocol uint32 /* SCARD_PROTOCOL_* value */
184 }
185
186 func getReaderState(data []byte) (ReaderState, error) {
187 ret := ReaderState{}
188 if len(data) < ReaderStateDescriptorLength {
189 return ret, fmt.Errorf("could not unmarshall data of length %d < %d", len(data), ReaderStateDescriptorLength)
190 }
191
192 ret.Name = string(data[:ReaderStateNameLength])
193 ret.eventCounter = binary.LittleEndian.Uint32(data[unsafe.Offsetof(ret.eventCounter):])
194 ret.readerState = binary.LittleEndian.Uint32(data[unsafe.Offsetof(ret.readerState):])
195 ret.readerSharing = binary.LittleEndian.Uint32(data[unsafe.Offsetof(ret.readerSharing):])
196 copy(ret.cardAtr[:], data[unsafe.Offsetof(ret.cardAtr):unsafe.Offsetof(ret.cardAtr)+ReaderStateMaxAtrSizeLength])
197 ret.cardAtrLength = binary.LittleEndian.Uint32(data[unsafe.Offsetof(ret.cardAtrLength):])
198 ret.cardProtocol = binary.LittleEndian.Uint32(data[unsafe.Offsetof(ret.cardProtocol):])
199
200 return ret, nil
201 }
202
203 // ListReaders gets the list of readers from the daemon
204 func (client *Client) ListReaders() ([]string, error) {
205 client.mutex.Lock()
206 defer client.mutex.Unlock()
207
208 err := messageSendWithHeader(CommandGetReaderState, client.conn, []byte{})
209 if err != nil {
210 return nil, err
211 }
212 response := make([]byte, ReaderStateDescriptorLength*MaxReaderStateDescriptors)
213 total := 0
214 for total < len(response) {
215 n, err := client.conn.Read(response[total:])
216 if err != nil {
217 return nil, err
218 }
219 total += n
220 }
221
222 var names []string
223 for i := range client.readerStateDescriptors {
224 desc, err := getReaderState(response[i*ReaderStateDescriptorLength:])
225 if err != nil {
226 return nil, err
227 }
228 client.readerStateDescriptors[i] = desc
229 if desc.Name[0] == 0 {
230 break
231 }
232 names = append(names, desc.Name)
233 }
234
235 return names, nil
236 }
237
238 // Offsets into the Connect request/response packet
239 const (
240 SCardConnectReaderNameOffset = 4
241 SCardConnectShareModeOffset = SCardConnectReaderNameOffset + ReaderStateNameLength
242 SCardConnectPreferredProtocolOffset = SCardConnectShareModeOffset + 4
243 SCardConnectReturnValueOffset = SCardConnectPreferredProtocolOffset + 12
244 )
245
246 // Card represents the connection to a card
247 type Card struct {
248 handle uint32
249 activeProto uint32
250 client *Client
251 }
252
253 // Connect asks the daemon to connect to the card
254 func (client *Client) Connect(name string, shareMode uint32, preferredProtocol uint32) (*Card, error) {
255 client.mutex.Lock()
256 defer client.mutex.Unlock()
257
258 request := make([]byte, ReaderStateNameLength+4*6)
259 binary.LittleEndian.PutUint32(request, client.ctx)
260 copy(request[SCardConnectReaderNameOffset:], []byte(name))
261 binary.LittleEndian.PutUint32(request[SCardConnectShareModeOffset:], shareMode)
262 binary.LittleEndian.PutUint32(request[SCardConnectPreferredProtocolOffset:], preferredProtocol)
263 binary.LittleEndian.PutUint32(request[SCardConnectReturnValueOffset:], SCardSuccess.Code())
264
265 err := messageSendWithHeader(SCardConnect, client.conn, request)
266 if err != nil {
267 return nil, err
268 }
269 response := make([]byte, ReaderStateNameLength+4*6)
270 total := 0
271 for total < len(response) {
272 n, err := client.conn.Read(response[total:])
273 if err != nil {
274 return nil, err
275 }
276 // fmt.Println("total, n", total, n, response)
277 total += n
278 }
279 code := binary.LittleEndian.Uint32(response[148:])
280 if code != SCardSuccess.Code() {
281 return nil, fmt.Errorf("invalid return code: %x (%v)", code, ErrorCode(code).Error())
282 }
283 handle := binary.LittleEndian.Uint32(response[140:])
284 active := binary.LittleEndian.Uint32(response[SCardConnectPreferredProtocolOffset:])
285
286 return &Card{handle: handle, activeProto: active, client: client}, nil
287 }
288
289 /**
290 * @brief contained in \ref SCARD_TRANSMIT Messages.
291 *
292 * These data are passed throw the field \c sharedSegmentMsg.data.
293 */
294 type transmit struct {
295 hCard uint32
296 ioSendPciProtocol uint32
297 ioSendPciLength uint32
298 cbSendLength uint32
299 ioRecvPciProtocol uint32
300 ioRecvPciLength uint32
301 pcbRecvLength uint32
302 rv uint32
303 }
304
305 // SCardIoRequest contains the info needed for performing an IO request
306 type SCardIoRequest struct {
307 proto uint32
308 length uint32
309 }
310
311 const (
312 TransmitRequestLength = 32
313 )
314
315 // Transmit sends request data to a card and returns the response
316 func (card *Card) Transmit(adpu []byte) ([]byte, *SCardIoRequest, error) {
317 card.client.mutex.Lock()
318 defer card.client.mutex.Unlock()
319
320 request := [TransmitRequestLength]byte{}
321 binary.LittleEndian.PutUint32(request[:], card.handle)
322 binary.LittleEndian.PutUint32(request[4:] /*card.activeProto*/, 2)
323 binary.LittleEndian.PutUint32(request[8:], 8)
324 binary.LittleEndian.PutUint32(request[12:], uint32(len(adpu)))
325 binary.LittleEndian.PutUint32(request[16:], 0)
326 binary.LittleEndian.PutUint32(request[20:], 0)
327 binary.LittleEndian.PutUint32(request[24:], 0x10000)
328 binary.LittleEndian.PutUint32(request[28:], SCardSuccess.Code())
329 err := messageSendWithHeader(SCardTransmit, card.client.conn, request[:])
330 if err != nil {
331 return nil, nil, err
332 }
333 // Add the ADPU payload after the transmit descriptor
334 n, err := card.client.conn.Write(adpu)
335 if err != nil {
336 return nil, nil, err
337 }
338 if n != len(adpu) {
339 return nil, nil, fmt.Errorf("Invalid number of bytes written: expected %d, got %d", len(adpu), n)
340 }
341 response := [TransmitRequestLength]byte{}
342 total := 0
343 for total < len(response) {
344 n, err = card.client.conn.Read(response[total:])
345 if err != nil {
346 return nil, nil, err
347 }
348 total += n
349 }
350
351 code := binary.LittleEndian.Uint32(response[28:])
352 if code != SCardSuccess.Code() {
353 return nil, nil, fmt.Errorf("invalid return code: %x (%v)", code, ErrorCode(code).Error())
354 }
355
356 // Recover the response data
357 recvProto := binary.LittleEndian.Uint32(response[16:])
358 recvLength := binary.LittleEndian.Uint32(response[20:])
359 recv := &SCardIoRequest{proto: recvProto, length: recvLength}
360 recvLength = binary.LittleEndian.Uint32(response[24:])
361 recvData := make([]byte, recvLength)
362 total = 0
363 for uint32(total) < recvLength {
364 n, err := card.client.conn.Read(recvData[total:])
365 if err != nil {
366 return nil, nil, err
367 }
368 total += n
369 }
370
371 return recvData, recv, nil
372 }
373
374 // Disconnect tells the PCSC daemon that the client is no longer
375 // interested in communicating with the card.
376 func (card *Card) Disconnect(disposition uint32) error {
377 card.client.mutex.Lock()
378 defer card.client.mutex.Unlock()
379
380 data := [12]byte{}
381 binary.LittleEndian.PutUint32(data[:], card.handle)
382 binary.LittleEndian.PutUint32(data[4:], disposition)
383 binary.LittleEndian.PutUint32(data[8:], SCardSuccess.Code())
384 err := messageSendWithHeader(SCardDisConnect, card.client.conn, data[:])
385 if err != nil {
386 return err
387 }
388 total := 0
389 for total < len(data) {
390 n, err := card.client.conn.Read(data[total:])
391 if err != nil {
392 return err
393 }
394 total += n
395 }
396 code := binary.LittleEndian.Uint32(data[8:])
397 if code != SCardSuccess.Code() {
398 return fmt.Errorf("invalid return code: %x (%v)", code, ErrorCode(code).Error())
399 }
400
401 return nil
402 }