FreeRDP
Loading...
Searching...
No Matches
smartcard_virtual_gids.c
1
21
22#include <freerdp/config.h>
23
24#include <winpr/wlog.h>
25#include <winpr/stream.h>
26#include <winpr/collections.h>
27
28#include <freerdp/crypto/crypto.h>
29
30#include <zlib.h>
31
32#include "../../crypto/certificate.h"
33#include "../../crypto/privatekey.h"
34#include "smartcard_virtual_gids.h"
35
36#define TAG CHANNELS_TAG("smartcard.vgids")
37
38#define VGIDS_EFID_MASTER 0xA000
39#define VGIDS_EFID_COMMON 0xA010
40// #define VGIDS_EFID_CARDCF VGIDS_EFID_COMMON
41// #define VGIDS_EFID_CARDAPPS VGIDS_EFID_COMMON
42// #define VGIDS_EFID_CMAPFILE VGIDS_EFID_COMMON
43#define VGIDS_EFID_CARDID 0xA012
44// #define VGIDS_EFID_KXC00 VGIDS_EFID_COMMON
45#define VGIDS_EFID_CURRENTDF 0x3FFF
46
47#define VGIDS_DO_FILESYSTEMTABLE 0xDF1F
48#define VGIDS_DO_KEYMAP 0xDF20
49#define VGIDS_DO_CARDID 0xDF20
50#define VGIDS_DO_CARDAPPS 0xDF21
51#define VGIDS_DO_CARDCF 0xDF22
52#define VGIDS_DO_CMAPFILE 0xDF23
53#define VGIDS_DO_KXC00 0xDF24
54
55#define VGIDS_CARDID_SIZE 16
56#define VGIDS_MAX_PIN_SIZE 127
57
58#define VGIDS_KEY_TYPE_KEYEXCHANGE 0x9A
59// #define VGIDS_KEY_TYPE_SIGNATURE 0x9C
60
61#define VGIDS_ALGID_RSA_1024 0x06
62#define VGIDS_ALGID_RSA_2048 0x07
63#define VGIDS_ALGID_RSA_3072 0x08
64#define VGIDS_ALGID_RSA_4096 0x09
65
66// #define VGIDS_SE_CRT_AUTH 0xA4
67#define VGIDS_SE_CRT_SIGN 0xB6
68#define VGIDS_SE_CRT_CONF 0xB8
69
70#define VGIDS_SE_ALGOID_CT_PAD_PKCS1 0x40
71#define VGIDS_SE_ALGOID_CT_PAD_OAEP 0x80
72// #define VGIDS_SE_ALGOID_CT_RSA_1024 0x06
73// #define VGIDS_SE_ALGOID_CT_RSA_2048 0x07
74// #define VGIDS_SE_ALGOID_CT_RSA_3072 0x08
75// #define VGIDS_SE_ALGOID_CT_RSA_4096 0x09
76
77#define VGIDS_SE_ALGOID_DST_PAD_PKCS1 0x40
78// #define VGIDS_SE_ALGOID_DST_RSA_1024 0x06
79// #define VGIDS_SE_ALGOID_DST_RSA_2048 0x07
80// #define VGIDS_SE_ALGOID_DST_RSA_3072 0x08
81// #define VGIDS_SE_ALGOID_DST_RSA_4096 0x09
82// #define VGIDS_SE_ALGOID_DST_ECDSA_P192 0x0A
83// #define VGIDS_SE_ALGOID_DST_ECDSA_P224 0x0B
84// #define VGIDS_SE_ALGOID_DST_ECDSA_P256 0x0C
85// #define VGIDS_SE_ALGOID_DST_ECDSA_P384 0x0D
86// #define VGIDS_SE_ALGOID_DST_ECDSA_P512 0x0E
87
88#define VGIDS_DEFAULT_KEY_REF 0x81
89
90#define ISO_INS_SELECT 0xA4
91#define ISO_INS_GETDATA 0xCB
92#define ISO_INS_GETRESPONSE 0xC0
93#define ISO_INS_MSE 0x22
94#define ISO_INS_PSO 0x2A
95#define ISO_INS_VERIFY 0x20
96
97#define ISO_STATUS_MORE_DATA 0x6100
98#define ISO_STATUS_VERIFYFAILED 0x6300
99#define ISO_STATUS_WRONGLC 0x6700
100#define ISO_STATUS_COMMANDNOTALLOWED 0x6900
101#define ISO_STATUS_SECURITYSTATUSNOTSATISFIED 0x6982
102#define ISO_STATUS_AUTHMETHODBLOCKED 0x6983
103#define ISO_STATUS_INVALIDCOMMANDDATA 0x6A80
104#define ISO_STATUS_FILENOTFOUND 0x6A82
105#define ISO_STATUS_INVALIDP1P2 0x6A86
106#define ISO_STATUS_INVALIDLC 0x6A87
107#define ISO_STATUS_REFERENCEDATANOTFOUND 0x6A88
108#define ISO_STATUS_SUCCESS 0x9000
109
110#define ISO_AID_MAX_SIZE 16
111
112#define ISO_FID_MF 0x3F00
113
114struct vgids_ef
115{
116 UINT16 id;
117 UINT16 dirID;
118 wStream* data;
119};
120typedef struct vgids_ef vgidsEF;
121
122struct vgids_se
123{
124 BYTE crt; /* control reference template tag */
125 BYTE algoId; /* Algorithm ID */
126 BYTE keyRef; /* Key reference */
127};
128typedef struct vgids_se vgidsSE;
129
130struct vgids_context
131{
132 UINT16 currentDF;
133 char* name;
134 wStream* commandData;
135 wStream* responseData;
136 BOOL pinVerified;
137 vgidsSE currentSE;
138
139 rdpCertificate* certificate;
140 rdpPrivateKey* privateKey;
141
142 wArrayList* files;
143 SmartcardEmulationContext* emuContext; // Reference, lifecycle managed outside
144};
145
146/* PKCS 1.5 DER encoded digest information */
147#define VGIDS_MAX_DIGEST_INFO 7
148
149static const BYTE g_PKCS1_SHA1[] = { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e,
150 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14 };
151static const BYTE g_PKCS1_SHA224[] = { 0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01,
152 0x65, 0x03, 0x04, 0x02, 0x04, 0x05, 0x00, 0x04, 0x1c };
153static const BYTE g_PKCS1_SHA256[] = { 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01,
154 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20 };
155static const BYTE g_PKCS1_SHA384[] = { 0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01,
156 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00, 0x04, 0x30 };
157static const BYTE g_PKCS1_SHA512[] = { 0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01,
158 0x65, 0x03, 0x04, 0x02, 0x03, 0x05, 0x00, 0x04, 0x40 };
159static const BYTE g_PKCS1_SHA512_224[] = { 0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60,
160 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02,
161 0x05, 0x05, 0x00, 0x04, 0x1c };
162static const BYTE g_PKCS1_SHA512_256[] = { 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60,
163 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02,
164 0x06, 0x05, 0x00, 0x04, 0x20 };
165
166/* Helper struct to map PKCS1.5 digest info to OpenSSL EVP_MD */
167struct vgids_digest_info_map
168{
169 const BYTE* info;
170 size_t infoSize;
171 const EVP_MD* digest;
172};
173typedef struct vgids_digest_info_map vgidsDigestInfoMap;
174
175/* MS GIDS AID */
176/* xx: Used by the Windows smart card framework for the GIDS version number. This byte must be set
177 * to the GIDS specification revision number which is either 0x01 or 0x02.
178 * yy: Reserved for use by the card application (set to 01)
179 */
180static const BYTE g_MsGidsAID[] = {
181 0xA0, 0x00, 0x00, 0x03, 0x97, 0x42, 0x54, 0x46, 0x59, 0x02, 0x01
182};
183
184/* GIDS APP File Control Parameter:
185 FD-Byte (82): 38 (not shareable-DF)
186 Sec Attr (8C): 03 30 30 Create/Delete File(03) Ext/User-Auth (30)
187*/
188static const BYTE g_GidsAppFCP[] = { 0x62, 0x08, 0x82, 0x01, 0x38, 0x8C, 0x03, 0x03, 0x30, 0x30 };
189/* GIDS APP File Control Information:
190 AppID (4F, Len 0B): A0 00 00 03 97 42 54 46 59 02 01
191 Discretionary DOs (73, Len 03): 40 01 C0
192 Supported Auth Protocols (40, Len 01): C0 Mutual/External-Auth
193 */
194static const BYTE g_GidsAppFCI[] = { 0x61, 0x12, 0x4F, 0x0B, 0xA0, 0x00, 0x00, 0x03, 0x97, 0x42,
195 0x54, 0x46, 0x59, 0x02, 0x01, 0x73, 0x03, 0x40, 0x01, 0xC0 };
196
197/*
198typedef struct
199{
200 BYTE bVersion; // Cache version
201 BYTE bPinsFreshness; // Card PIN
202 WORD wContainersFreshness;
203 WORD wFilesFreshness;
204} CARD_CACHE_FILE_FORMAT, *PCARD_CACHE_FILE_FORMAT; */
205static const BYTE g_CardCFContents[] = { 0x00, 0x00, 0x01, 0x00, 0x04, 0x00 };
206
207/* {‘mscp’,0,0,0,0} */
208static const BYTE g_CardAppsContents[] = { 0x6d, 0x73, 0x63, 0x70, 0x00, 0x00, 0x00, 0x00 };
209
210#pragma pack(push, 1)
211
212/* Type: CONTAINER_MAP_RECORD (taken from Windows Smart Card Minidriver Specification)
213
214 This structure describes the format of the Base CSP's
215 container map file, stored on the card. This is wellknown
216 logical file wszCONTAINER_MAP_FILE. The file consists of
217 zero or more of these records. */
218#define MAX_CONTAINER_NAME_LEN 39
219
220/* This flag is set in the CONTAINER_MAP_RECORD bFlags
221 member if the corresponding container is valid and currently
222 exists on the card. // If the container is deleted, its
223 bFlags field must be cleared. */
224#define CONTAINER_MAP_VALID_CONTAINER 1
225
226/* This flag is set in the CONTAINER_MAP_RECORD bFlags
227 member if the corresponding container is the default
228 container on the card. */
229#define CONTAINER_MAP_DEFAULT_CONTAINER 2
230
231struct vgids_container_map_entry
232{
233 WCHAR wszGuid[MAX_CONTAINER_NAME_LEN + 1];
234 BYTE bFlags;
235 BYTE bReserved;
236 WORD wSigKeySizeBits;
237 WORD wKeyExchangeKeySizeBits;
238};
239typedef struct vgids_container_map_entry vgidsContainerMapEntry;
240
241struct vgids_filesys_table_entry
242{
243 char directory[9];
244 char filename[9];
245 UINT16 pad0;
246 UINT16 dataObjectIdentifier;
247 UINT16 pad1;
248 UINT16 fileIdentifier;
249 UINT16 unknown;
250};
251typedef struct vgids_filesys_table_entry vgidsFilesysTableEntry;
252
253struct vgids_keymap_record
254{
255 UINT32 state;
256 BYTE algid;
257 BYTE keytype;
258 UINT16 keyref;
259 UINT16 unknownWithFFFF;
260 UINT16 unknownWith0000;
261};
262typedef struct vgids_keymap_record vgidsKeymapRecord;
263
264#pragma pack(pop)
265
266static void vgids_ef_free(void* ptr);
267
268WINPR_ATTR_MALLOC(vgids_ef_free, 1)
269static vgidsEF* vgids_ef_new(vgidsContext* ctx, USHORT id)
270{
271 vgidsEF* ef = calloc(1, sizeof(vgidsEF));
272
273 ef->id = id;
274 ef->data = Stream_New(nullptr, 1024);
275 if (!ef->data)
276 {
277 WLog_ERR(TAG, "Failed to create file data stream");
278 goto create_failed;
279 }
280 if (!Stream_SetLength(ef->data, 0))
281 goto create_failed;
282
283 if (!ArrayList_Append(ctx->files, ef))
284 {
285 WLog_ERR(TAG, "Failed to add new ef to file list");
286 goto create_failed;
287 }
288
289 return ef;
290
291create_failed:
292 vgids_ef_free(ef);
293 return nullptr;
294}
295
296WINPR_ATTR_NODISCARD
297static BOOL vgids_write_tlv(wStream* s, UINT16 tag, const void* data, size_t dataSize)
298{
299 WINPR_ASSERT(dataSize <= UINT16_MAX);
300
301 /* A maximum of 5 additional bytes is needed */
302 if (!Stream_EnsureRemainingCapacity(s, dataSize + 5ull))
303 {
304 WLog_ERR(TAG, "Failed to ensure capacity of DO stream");
305 return FALSE;
306 }
307
308 /* BER encoding: If the most-significant bit is set (0x80) the length is encoded in the
309 * remaining bits. So lengths < 128 bytes can be set directly, all others are encoded */
310 if (tag > 0xFF)
311 Stream_Write_UINT16_BE(s, tag);
312 else
313 Stream_Write_UINT8(s, (BYTE)tag);
314 if (dataSize < 128)
315 {
316 Stream_Write_UINT8(s, (BYTE)dataSize);
317 }
318 else if (dataSize < 256)
319 {
320 Stream_Write_UINT8(s, 0x81);
321 Stream_Write_UINT8(s, (BYTE)dataSize);
322 }
323 else
324 {
325 Stream_Write_UINT8(s, 0x82);
326 Stream_Write_UINT16_BE(s, (UINT16)dataSize);
327 }
328 Stream_Write(s, data, dataSize);
329 Stream_SealLength(s);
330 return TRUE;
331}
332
333WINPR_ATTR_NODISCARD
334static BOOL vgids_ef_write_do(vgidsEF* ef, UINT16 doID, const void* data, DWORD dataSize)
335{
336 /* Write DO to end of file: 2-Byte ID, 1-Byte Len, Data */
337 return vgids_write_tlv(ef->data, doID, data, dataSize);
338}
339
340WINPR_ATTR_NODISCARD
341static BOOL vgids_ef_read_do(vgidsEF* ef, UINT16 doID, BYTE** data, DWORD* dataSize)
342{
343 /* Read the given DO from the file: 2-Byte ID, 1-Byte Len, Data */
344 Stream_ResetPosition(ef->data);
345
346 /* Look for the requested DO */
347 while (Stream_GetRemainingLength(ef->data) > 3)
348 {
349 BYTE len = 0;
350 size_t curPos = 0;
351 UINT16 doSize = 0;
352 UINT16 nextDOID = 0;
353
354 curPos = Stream_GetPosition(ef->data);
355 Stream_Read_UINT16_BE(ef->data, nextDOID);
356 Stream_Read_UINT8(ef->data, len);
357 if ((len & 0x80))
358 {
359 BYTE lenSize = len & 0x7F;
360 if (!Stream_CheckAndLogRequiredLength(TAG, ef->data, lenSize))
361 return FALSE;
362
363 switch (lenSize)
364 {
365 case 1:
366 Stream_Read_UINT8(ef->data, doSize);
367 break;
368 case 2:
369 Stream_Read_UINT16_BE(ef->data, doSize);
370 break;
371 default:
372 WLog_ERR(TAG, "Unexpected tag length %" PRIu8, lenSize);
373 return FALSE;
374 }
375 }
376 else
377 doSize = len;
378
379 if (!Stream_CheckAndLogRequiredLength(TAG, ef->data, doSize))
380 return FALSE;
381
382 if (nextDOID == doID)
383 {
384 BYTE* outData = nullptr;
385
386 /* Include Tag and length in result */
387 doSize += (UINT16)(Stream_GetPosition(ef->data) - curPos);
388 if (!Stream_SetPosition(ef->data, curPos))
389 return FALSE;
390
391 outData = malloc(doSize);
392 if (!outData)
393 {
394 WLog_ERR(TAG, "Failed to allocate output buffer");
395 return FALSE;
396 }
397
398 Stream_Read(ef->data, outData, doSize);
399 *data = outData;
400 *dataSize = doSize;
401 return TRUE;
402 }
403 else
404 {
405 /* Skip DO */
406 if (!Stream_SafeSeek(ef->data, doSize))
407 return FALSE;
408 }
409 }
410
411 return FALSE;
412}
413
414void vgids_ef_free(void* ptr)
415{
416 vgidsEF* ef = ptr;
417 if (ef)
418 {
419 Stream_Free(ef->data, TRUE);
420 free(ef);
421 }
422}
423
424WINPR_ATTR_NODISCARD
425static BOOL vgids_prepare_fstable(const vgidsFilesysTableEntry* fstable, DWORD numEntries,
426 BYTE** outData, DWORD* outDataSize)
427{
428 /* Filesystem table:
429 BYTE unknown: 0x01
430 Array of vgidsFilesysTableEntry
431 */
432 BYTE* data = malloc(sizeof(vgidsFilesysTableEntry) * numEntries + 1);
433 if (!data)
434 {
435 WLog_ERR(TAG, "Failed to allocate filesystem table data blob");
436 return FALSE;
437 }
438
439 *data = 0x01;
440 for (UINT32 i = 0; i < numEntries; ++i)
441 memcpy(data + 1 + (sizeof(vgidsFilesysTableEntry) * i), &fstable[i],
442 sizeof(vgidsFilesysTableEntry));
443
444 *outData = data;
445 *outDataSize = sizeof(vgidsFilesysTableEntry) * numEntries + 1;
446
447 return TRUE;
448}
449
450WINPR_ATTR_NODISCARD
451static BOOL vgids_prepare_certificate(const rdpCertificate* cert, BYTE** kxc, DWORD* kxcSize)
452{
453 /* Key exchange container:
454 UINT16 compression version: 0001
455 UINT16 source size
456 ZLIB compressed cert
457 */
458 uLongf destSize = 0;
459 wStream* s = nullptr;
460 BYTE* comprData = nullptr;
461
462 WINPR_ASSERT(cert);
463
464 size_t certSize = 0;
465 BYTE* certData = freerdp_certificate_get_der(cert, &certSize);
466 if (!certData || (certSize == 0) || (certSize > UINT16_MAX))
467 {
468 WLog_ERR(TAG, "Failed to get certificate size");
469 goto handle_error;
470 }
471
472 comprData = malloc(certSize);
473 if (!comprData)
474 {
475 WLog_ERR(TAG, "Failed to allocate certificate buffer");
476 goto handle_error;
477 }
478
479 /* compress certificate data */
480 destSize = WINPR_ASSERTING_INT_CAST(uint16_t, certSize);
481 if (compress(comprData, &destSize, certData, WINPR_ASSERTING_INT_CAST(uint16_t, certSize)) !=
482 Z_OK)
483 {
484 WLog_ERR(TAG, "Failed to compress certificate data");
485 goto handle_error;
486 }
487
488 /* Write container data */
489 s = Stream_New(nullptr, destSize + 4);
490 Stream_Write_UINT16(s, 0x0001);
491 Stream_Write_UINT16(s, WINPR_ASSERTING_INT_CAST(uint16_t, certSize));
492 Stream_Write(s, comprData, destSize);
493 Stream_SealLength(s);
494
495 *kxc = Stream_Buffer(s);
496 *kxcSize = (DWORD)Stream_Length(s);
497
498 Stream_Free(s, FALSE);
499 free(certData);
500 free(comprData);
501 return TRUE;
502
503handle_error:
504 Stream_Free(s, TRUE);
505 free(certData);
506 free(comprData);
507 return FALSE;
508}
509
510WINPR_ATTR_NODISCARD
511static size_t get_rsa_key_size(const rdpPrivateKey* privateKey)
512{
513 WINPR_ASSERT(privateKey);
514
515 return freerdp_key_get_bits(privateKey) / 8;
516}
517
518WINPR_ATTR_NODISCARD
519static BYTE vgids_get_algid(vgidsContext* p_Ctx)
520{
521 WINPR_ASSERT(p_Ctx);
522
523 switch (get_rsa_key_size(p_Ctx->privateKey))
524 {
525 case (1024 / 8):
526 return VGIDS_ALGID_RSA_1024;
527 case (2048 / 8):
528 return VGIDS_ALGID_RSA_2048;
529 case (3072 / 8):
530 return VGIDS_ALGID_RSA_3072;
531 case (4096 / 8):
532 return VGIDS_ALGID_RSA_4096;
533 default:
534 WLog_ERR(TAG, "Failed to determine algid for private key");
535 break;
536 }
537
538 return 0;
539}
540
541WINPR_ATTR_NODISCARD
542static BOOL vgids_prepare_keymap(vgidsContext* context, BYTE** outData, DWORD* outDataSize)
543{
544 /* Key map record table:
545 BYTE unknown (count?): 0x01
546 Array of vgidsKeymapRecord
547 */
548 BYTE* data = nullptr;
549 vgidsKeymapRecord record = {
550 1, /* state */
551 0, /* algo */
552 VGIDS_KEY_TYPE_KEYEXCHANGE, /* keytpe */
553 (0xB000 | VGIDS_DEFAULT_KEY_REF), /* keyref */
554 0xFFFF, /* unknown FFFF */
555 0x0000 /* unknown 0000 */
556 };
557
558 /* Determine algo */
559 BYTE algid = vgids_get_algid(context);
560 if (algid == 0)
561 return FALSE;
562
563 data = malloc(sizeof(record) + 1);
564 if (!data)
565 {
566 WLog_ERR(TAG, "Failed to allocate filesystem table data blob");
567 return FALSE;
568 }
569
570 *data = 0x01;
571 record.algid = algid;
572 memcpy(data + 1, &record, sizeof(record));
573
574 *outData = data;
575 *outDataSize = sizeof(record) + 1;
576
577 return TRUE;
578}
579
580WINPR_ATTR_NODISCARD
581static BOOL vgids_parse_apdu_header(wStream* s, BYTE* cla, BYTE* ins, BYTE* p1, BYTE* p2, BYTE* lc,
582 BYTE* le)
583{
584 if (!Stream_CheckAndLogRequiredLength(TAG, s, 4))
585 return FALSE;
586
587 /* Read and verify APDU data */
588 if (cla)
589 Stream_Read_UINT8(s, *cla);
590 else
591 Stream_Seek(s, 1);
592 if (ins)
593 Stream_Read_UINT8(s, *ins);
594 else
595 Stream_Seek(s, 1);
596 if (p1)
597 Stream_Read_UINT8(s, *p1);
598 else
599 Stream_Seek(s, 1);
600 if (p2)
601 Stream_Read_UINT8(s, *p2);
602 else
603 Stream_Seek(s, 1);
604
605 /* If LC is requested - check remaining length and read as well */
606 if (lc)
607 {
608 if (!Stream_CheckAndLogRequiredLength(TAG, s, 1))
609 return FALSE;
610
611 Stream_Read_UINT8(s, *lc);
612 if (!Stream_CheckAndLogRequiredLength(TAG, s, *lc))
613 return FALSE;
614 }
615
616 /* read LE */
617 if (le)
618 {
619 if (!Stream_CheckAndLogRequiredLength(TAG, s, 1))
620 return FALSE;
621 Stream_Read_UINT8(s, *le);
622 }
623
624 return TRUE;
625}
626
627WINPR_ATTR_NODISCARD
628static BOOL vgids_create_response(UINT16 status, const BYTE* answer, DWORD answerSize,
629 BYTE** outData, DWORD* outDataSize)
630{
631 BYTE* out = malloc(answerSize + 2);
632 if (!out)
633 {
634 WLog_ERR(TAG, "Failed to allocate memory for response data");
635 return FALSE;
636 }
637
638 *outData = out;
639 if (answer)
640 {
641 memcpy(out, answer, answerSize);
642 out += answerSize;
643 }
644
645 *out = (BYTE)((status >> 8) & 0xFF);
646 *(out + 1) = (BYTE)(status & 0xFF);
647 *outDataSize = answerSize + 2;
648 return TRUE;
649}
650
651WINPR_ATTR_NODISCARD
652static BOOL vgids_read_do_fkt(void* data, size_t index, va_list ap)
653{
654 BYTE* response = nullptr;
655 DWORD responseSize = 0;
656 vgidsEF* file = (vgidsEF*)data;
657 vgidsContext* context = va_arg(ap, vgidsContext*);
658 UINT16 efID = (UINT16)va_arg(ap, unsigned);
659 UINT16 doID = (UINT16)va_arg(ap, unsigned);
660 WINPR_UNUSED(index);
661
662 if (efID == 0x3FFF || efID == file->id)
663 {
664 /* If the DO was successfully read - abort file enum */
665 if (vgids_ef_read_do(file, doID, &response, &responseSize))
666 {
667 context->responseData = Stream_New(response, (size_t)responseSize);
668 if (!context->responseData)
669 free(response);
670 return FALSE;
671 }
672 }
673
674 return TRUE;
675}
676
677WINPR_ATTR_NODISCARD
678static BOOL vgids_read_do(vgidsContext* context, UINT16 efID, UINT16 doID)
679{
680 return ArrayList_ForEach(context->files, vgids_read_do_fkt, context, efID, doID);
681}
682
683static void vgids_reset_context_response(vgidsContext* context)
684{
685 Stream_Free(context->responseData, TRUE);
686 context->responseData = nullptr;
687}
688
689static void vgids_reset_context_command_data(vgidsContext* context)
690{
691 Stream_Free(context->commandData, TRUE);
692 context->commandData = nullptr;
693}
694
695WINPR_ATTR_NODISCARD
696static BOOL vgids_ins_select(vgidsContext* context, wStream* s, BYTE** response,
697 DWORD* responseSize)
698{
699 BYTE p1 = 0;
700 BYTE p2 = 0;
701 BYTE lc = 0;
702 DWORD resultDataSize = 0;
703 const BYTE* resultData = nullptr;
704 UINT16 status = ISO_STATUS_SUCCESS;
705
706 /* The only select operations performed are either select by AID or select 3FFF (return
707 * information about the currently selected DF) */
708 if (!vgids_parse_apdu_header(s, nullptr, nullptr, &p1, &p2, &lc, nullptr))
709 return FALSE;
710
711 /* Check P1 for selection mode */
712 switch (p1)
713 {
714 /* Select by AID */
715 case 0x04:
716 {
717 /* read AID from APDU */
718 BYTE aid[ISO_AID_MAX_SIZE] = WINPR_C_ARRAY_INIT;
719 if (lc > ISO_AID_MAX_SIZE)
720 {
721 WLog_ERR(TAG, "The LC byte is greater than the maximum AID length");
722 status = ISO_STATUS_INVALIDLC;
723 break;
724 }
725
726 /* Check if we select MS GIDS App (only one we know) */
727 Stream_Read(s, aid, lc);
728 if ((lc > sizeof(g_MsGidsAID)) || (memcmp(aid, g_MsGidsAID, lc) != 0))
729 {
730 status = ISO_STATUS_FILENOTFOUND;
731 break;
732 }
733
734 /* Return FCI or FCP for MsGids App */
735 switch (p2)
736 {
737 /* Return FCI information */
738 case 0x00:
739 {
740 resultData = g_GidsAppFCI;
741 resultDataSize = sizeof(g_GidsAppFCI);
742 break;
743 }
744 /* Return FCP information */
745 case 0x04:
746 {
747 resultData = g_GidsAppFCP;
748 resultDataSize = sizeof(g_GidsAppFCP);
749 break;
750 }
751 default:
752 status = ISO_STATUS_INVALIDP1P2;
753 break;
754 }
755
756 if (resultData)
757 context->currentDF = ISO_FID_MF;
758 break;
759 }
760 /* Select by FID */
761 case 0x00:
762 {
763 /* read FID from APDU */
764 UINT16 fid = 0;
765 if (lc != 2)
766 {
767 WLog_ERR(TAG, "The LC byte for the file ID must be 2");
768 status = ISO_STATUS_INVALIDLC;
769 break;
770 }
771
772 Stream_Read_UINT16_BE(s, fid);
773 if (fid != VGIDS_EFID_CURRENTDF || context->currentDF == 0)
774 {
775 status = ISO_STATUS_FILENOTFOUND;
776 break;
777 }
778 break;
779 }
780 default:
781 {
782 /* P1 P2 combination not supported */
783 status = ISO_STATUS_INVALIDP1P2;
784 break;
785 }
786 }
787
788 return vgids_create_response(status, resultData, resultDataSize, response, responseSize);
789}
790
791WINPR_ATTR_NODISCARD
792static UINT16 vgids_handle_chained_response(vgidsContext* context, const BYTE** response,
793 DWORD* responseSize)
794{
795 /* Cap to a maximum of 256 bytes and set status to more data */
796 UINT16 status = ISO_STATUS_SUCCESS;
797 DWORD remainingBytes = (DWORD)Stream_Length(context->responseData);
798 if (remainingBytes > 256)
799 {
800 status = ISO_STATUS_MORE_DATA;
801 remainingBytes = 256;
802 }
803
804 *response = Stream_Buffer(context->responseData);
805 *responseSize = remainingBytes;
806 Stream_Seek(context->responseData, remainingBytes);
807
808 /* Check if there are more than 256 bytes left or if we can already provide the remaining length
809 * in the status word */
810 remainingBytes = (DWORD)(Stream_Length(context->responseData) - remainingBytes);
811 if (remainingBytes < 256 && remainingBytes != 0)
812 status |= (remainingBytes & 0xFF);
813 return status;
814}
815
816WINPR_ATTR_NODISCARD
817static BOOL vgids_get_public_key(vgidsContext* context, UINT16 doTag)
818{
819 BOOL rc = FALSE;
820 wStream* pubKey = nullptr;
821 wStream* response = nullptr;
822
823 WINPR_ASSERT(context);
824
825 /* Get key components */
826 size_t nSize = 0;
827 size_t eSize = 0;
828
829 char* n = freerdp_certificate_get_param(context->certificate, FREERDP_CERT_RSA_N, &nSize);
830 char* e = freerdp_certificate_get_param(context->certificate, FREERDP_CERT_RSA_E, &eSize);
831
832 if (!n || !e)
833 goto handle_error;
834
835 pubKey = Stream_New(nullptr, nSize + eSize + 0x10);
836 if (!pubKey)
837 {
838 WLog_ERR(TAG, "Failed to allocate public key stream");
839 goto handle_error;
840 }
841
842 response = Stream_New(nullptr, Stream_Capacity(pubKey) + 0x10);
843 if (!response)
844 {
845 WLog_ERR(TAG, "Failed to allocate response stream");
846 goto handle_error;
847 }
848
849 /* write modulus and exponent DOs */
850 if (!vgids_write_tlv(pubKey, 0x81, n, nSize))
851 goto handle_error;
852
853 if (!vgids_write_tlv(pubKey, 0x82, e, eSize))
854 goto handle_error;
855
856 /* write ISO public key template */
857 if (!vgids_write_tlv(response, doTag, Stream_Buffer(pubKey), (DWORD)Stream_Length(pubKey)))
858 goto handle_error;
859
860 /* set response data */
861 Stream_ResetPosition(response);
862 context->responseData = response;
863 response = nullptr;
864
865 rc = TRUE;
866handle_error:
867 free(n);
868 free(e);
869 Stream_Free(pubKey, TRUE);
870 Stream_Free(response, TRUE);
871 return rc;
872}
873
874WINPR_ATTR_NODISCARD
875static BOOL vgids_ins_getdata(vgidsContext* context, wStream* s, BYTE** response,
876 DWORD* responseSize)
877{
878 UINT16 doId = 0;
879 UINT16 fileId = 0;
880 BYTE p1 = 0;
881 BYTE p2 = 0;
882 BYTE lc = 0;
883 DWORD resultDataSize = 0;
884 const BYTE* resultData = nullptr;
885 UINT16 status = ISO_STATUS_SUCCESS;
886
887 /* GetData is called a lot!
888 - To retrieve DOs from files
889 - To retrieve public key information
890 */
891 if (!vgids_parse_apdu_header(s, nullptr, nullptr, &p1, &p2, &lc, nullptr))
892 return FALSE;
893
894 /* free any previous queried data */
895 vgids_reset_context_response(context);
896
897 /* build up file identifier */
898 fileId = (UINT16)(((UINT16)p1 << 8) | p2);
899
900 /* Do we have a DO reference? */
901 switch (lc)
902 {
903 case 4:
904 {
905 BYTE tag = 0;
906 BYTE length = 0;
907 Stream_Read_UINT8(s, tag);
908 Stream_Read_UINT8(s, length);
909 if (tag != 0x5C && length != 0x02)
910 {
911 status = ISO_STATUS_INVALIDCOMMANDDATA;
912 break;
913 }
914
915 Stream_Read_UINT16_BE(s, doId);
916
917 /* the function only returns if the ID was found in the list and iteration aborted early
918 * or not. we can ignore this here. */
919 if (!vgids_read_do(context, fileId, doId))
920 WLog_WARN(TAG, "vgids_read_do failed");
921 break;
922 }
923 case 0xA:
924 {
925 UINT16 pubKeyDO = 0;
926 BYTE tag = 0;
927 BYTE length = 0;
928 BYTE keyRef = 0;
929
930 /* We want to retrieve the public key? */
931 if (p1 != 0x3F && p2 != 0xFF)
932 {
933 status = ISO_STATUS_INVALIDP1P2;
934 break;
935 }
936
937 /* read parent tag/length */
938 Stream_Read_UINT8(s, tag);
939 Stream_Read_UINT8(s, length);
940 if (tag != 0x70 || length != 0x08)
941 {
942 status = ISO_STATUS_INVALIDCOMMANDDATA;
943 break;
944 }
945
946 /* read key reference TLV */
947 Stream_Read_UINT8(s, tag);
948 Stream_Read_UINT8(s, length);
949 Stream_Read_UINT8(s, keyRef);
950 if (tag != 0x84 || length != 0x01 || keyRef != VGIDS_DEFAULT_KEY_REF)
951 {
952 status = ISO_STATUS_INVALIDCOMMANDDATA;
953 break;
954 }
955
956 /* read key value template TLV */
957 Stream_Read_UINT8(s, tag);
958 Stream_Read_UINT8(s, length);
959 if (tag != 0xA5 || length != 0x03)
960 {
961 status = ISO_STATUS_INVALIDCOMMANDDATA;
962 break;
963 }
964
965 Stream_Read_UINT16_BE(s, pubKeyDO);
966 Stream_Read_UINT8(s, length);
967 if (pubKeyDO != 0x7F49 || length != 0x80)
968 {
969 status = ISO_STATUS_INVALIDCOMMANDDATA;
970 break;
971 }
972
973 if (!Stream_CheckAndLogRequiredLength(TAG, s, 1))
974 {
975 status = ISO_STATUS_INVALIDLC;
976 break;
977 }
978
979 /* Return public key value */
980 if (!vgids_get_public_key(context, pubKeyDO))
981 return FALSE;
982 break;
983 }
984 default:
985 status = ISO_STATUS_INVALIDCOMMANDDATA;
986 break;
987 }
988
989 /* If we have response data, make it ready for return */
990 if (context->responseData)
991 status = vgids_handle_chained_response(context, &resultData, &resultDataSize);
992 else if (status == ISO_STATUS_SUCCESS)
993 status = ISO_STATUS_REFERENCEDATANOTFOUND;
994
995 return vgids_create_response(status, resultData, resultDataSize, response, responseSize);
996}
997
998WINPR_ATTR_NODISCARD
999static BOOL vgids_ins_manage_security_environment(vgidsContext* context, wStream* s,
1000 BYTE** response, DWORD* responseSize)
1001{
1002 BYTE tag = 0;
1003 BYTE length = 0;
1004 BYTE p1 = 0;
1005 BYTE p2 = 0;
1006 BYTE lc = 0;
1007 DWORD resultDataSize = 0;
1008 const BYTE* resultData = nullptr;
1009 UINT16 status = ISO_STATUS_SUCCESS;
1010
1011 vgids_reset_context_command_data(context);
1012 vgids_reset_context_response(context);
1013
1014 /* Manage security environment prepares the card for performing crypto operations. */
1015 if (!vgids_parse_apdu_header(s, nullptr, nullptr, &p1, &p2, &lc, nullptr))
1016 return FALSE;
1017
1018 /* Check APDU params */
1019 /* P1: Set Computation, decipherment, Internal Auth */
1020 /* P2: Digital Signature (B6), Confidentiality (B8) */
1021 if (p1 != 0x41 && p2 != 0xB6 && p2 != 0xB8)
1022 {
1023 status = ISO_STATUS_INVALIDP1P2;
1024 goto create_response;
1025 }
1026
1027 if (lc != 6)
1028 {
1029 status = ISO_STATUS_WRONGLC;
1030 goto create_response;
1031 }
1032
1033 context->currentSE.crt = p2;
1034
1035 /* parse command buffer */
1036 /* Read algo ID */
1037 Stream_Read_UINT8(s, tag);
1038 Stream_Read_UINT8(s, length);
1039 if (tag != 0x80 || length != 0x01)
1040 {
1041 status = ISO_STATUS_INVALIDCOMMANDDATA;
1042 goto create_response;
1043 }
1044 Stream_Read_UINT8(s, context->currentSE.algoId);
1045
1046 /* Read private key reference */
1047 Stream_Read_UINT8(s, tag);
1048 Stream_Read_UINT8(s, length);
1049 if (tag != 0x84 || length != 0x01)
1050 {
1051 status = ISO_STATUS_INVALIDCOMMANDDATA;
1052 goto create_response;
1053 }
1054 Stream_Read_UINT8(s, context->currentSE.keyRef);
1055
1056create_response:
1057 /* If an error occurred reset SE */
1058 if (status != ISO_STATUS_SUCCESS)
1059 memset(&context->currentSE, 0, sizeof(context->currentSE));
1060 return vgids_create_response(status, resultData, resultDataSize, response, responseSize);
1061}
1062
1063WINPR_ATTR_NODISCARD
1064static BOOL vgids_perform_digital_signature(vgidsContext* context)
1065{
1066 size_t sigSize = 0;
1067 size_t msgSize = 0;
1068 EVP_PKEY_CTX* ctx = nullptr;
1069 EVP_PKEY* pk = freerdp_key_get_evp_pkey(context->privateKey);
1070 const vgidsDigestInfoMap gidsDigestInfo[VGIDS_MAX_DIGEST_INFO] = {
1071 { g_PKCS1_SHA1, sizeof(g_PKCS1_SHA1), EVP_sha1() },
1072 { g_PKCS1_SHA224, sizeof(g_PKCS1_SHA224), EVP_sha224() },
1073 { g_PKCS1_SHA256, sizeof(g_PKCS1_SHA256), EVP_sha256() },
1074 { g_PKCS1_SHA384, sizeof(g_PKCS1_SHA384), EVP_sha384() },
1075 { g_PKCS1_SHA512, sizeof(g_PKCS1_SHA512), EVP_sha512() },
1076#if OPENSSL_VERSION_NUMBER >= 0x10101000L
1077 { g_PKCS1_SHA512_224, sizeof(g_PKCS1_SHA512_224), EVP_sha512_224() },
1078 { g_PKCS1_SHA512_256, sizeof(g_PKCS1_SHA512_256), EVP_sha512_256() }
1079#endif
1080 };
1081
1082 if (!pk)
1083 {
1084 WLog_ERR(TAG, "Failed to create PKEY");
1085 return FALSE;
1086 }
1087
1088 vgids_reset_context_response(context);
1089
1090 /* for each digest info */
1091 Stream_ResetPosition(context->commandData);
1092 for (int i = 0; i < VGIDS_MAX_DIGEST_INFO; ++i)
1093 {
1094 /* have we found our digest? */
1095 const vgidsDigestInfoMap* digest = &gidsDigestInfo[i];
1096 if (Stream_Length(context->commandData) >= digest->infoSize &&
1097 memcmp(Stream_Buffer(context->commandData), digest->info, digest->infoSize) == 0)
1098 {
1099 /* skip digest info and calculate message size */
1100 Stream_Seek(context->commandData, digest->infoSize);
1101 if (!Stream_CheckAndLogRequiredLength(TAG, context->commandData, 2))
1102 goto sign_failed;
1103 msgSize = Stream_GetRemainingLength(context->commandData);
1104
1105 /* setup signing context */
1106 ctx = EVP_PKEY_CTX_new(pk, nullptr);
1107 if (!ctx)
1108 {
1109 WLog_ERR(TAG, "Failed to create signing context");
1110 goto sign_failed;
1111 }
1112
1113 if (EVP_PKEY_sign_init(ctx) <= 0)
1114 {
1115 WLog_ERR(TAG, "Failed to init signing context");
1116 goto sign_failed;
1117 }
1118
1119 /* set padding and signature algo */
1120 if (context->currentSE.algoId & VGIDS_SE_ALGOID_DST_PAD_PKCS1)
1121 {
1122 if (EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_PADDING) <= 0)
1123 {
1124 WLog_ERR(TAG, "Failed to set padding mode");
1125 goto sign_failed;
1126 }
1127 }
1128
1129 if (EVP_PKEY_CTX_set_signature_md(ctx, digest->digest) <= 0)
1130 {
1131 WLog_ERR(TAG, "Failed to set signing mode");
1132 goto sign_failed;
1133 }
1134
1135 /* Determine buffer length */
1136 if (EVP_PKEY_sign(ctx, nullptr, &sigSize, Stream_Pointer(context->commandData),
1137 msgSize) <= 0)
1138 {
1139 WLog_ERR(TAG, "Failed to determine signature size");
1140 goto sign_failed;
1141 }
1142
1143 context->responseData = Stream_New(nullptr, sigSize);
1144 if (!context->responseData)
1145 {
1146 WLog_ERR(TAG, "Failed to allocate signing buffer");
1147 goto sign_failed;
1148 }
1149
1150 /* sign */
1151 if (EVP_PKEY_sign(ctx, Stream_Buffer(context->responseData), &sigSize,
1152 Stream_Pointer(context->commandData), msgSize) <= 0)
1153 {
1154 WLog_ERR(TAG, "Failed to create signature");
1155 goto sign_failed;
1156 }
1157
1158 if (!Stream_SetLength(context->responseData, sigSize))
1159 goto sign_failed;
1160
1161 EVP_PKEY_CTX_free(ctx);
1162 break;
1163 }
1164 }
1165
1166 EVP_PKEY_free(pk);
1167 vgids_reset_context_command_data(context);
1168 return TRUE;
1169
1170sign_failed:
1171 vgids_reset_context_command_data(context);
1172 vgids_reset_context_response(context);
1173 EVP_PKEY_CTX_free(ctx);
1174 EVP_PKEY_free(pk);
1175 return FALSE;
1176}
1177
1178WINPR_ATTR_NODISCARD
1179static BOOL vgids_perform_decrypt(vgidsContext* context)
1180{
1181 EVP_PKEY_CTX* ctx = nullptr;
1182 BOOL rc = FALSE;
1183 int res = 0;
1184 int padding = RSA_NO_PADDING;
1185
1186 vgids_reset_context_response(context);
1187
1188 /* determine padding */
1189 if (context->currentSE.algoId & VGIDS_SE_ALGOID_CT_PAD_PKCS1)
1190 padding = RSA_PKCS1_PADDING;
1191 else if (context->currentSE.algoId & VGIDS_SE_ALGOID_CT_PAD_OAEP)
1192 padding = RSA_PKCS1_OAEP_PADDING;
1193
1194 /* init response buffer */
1195 EVP_PKEY* pkey = freerdp_key_get_evp_pkey(context->privateKey);
1196 if (!pkey)
1197 goto decrypt_failed;
1198 ctx = EVP_PKEY_CTX_new(pkey, nullptr);
1199 if (!ctx)
1200 goto decrypt_failed;
1201 if (EVP_PKEY_decrypt_init(ctx) <= 0)
1202 goto decrypt_failed;
1203 if (EVP_PKEY_CTX_set_rsa_padding(ctx, padding) <= 0)
1204 goto decrypt_failed;
1205
1206 /* Determine buffer length */
1207 {
1208 const size_t inlen = Stream_Length(context->commandData);
1209 size_t outlen = 0;
1210 res = EVP_PKEY_decrypt(ctx, nullptr, &outlen, Stream_Buffer(context->commandData), inlen);
1211 if (res <= 0)
1212 {
1213 WLog_ERR(TAG, "Failed to decrypt data");
1214 goto decrypt_failed;
1215 }
1216
1217 /* Prepare output buffer */
1218 context->responseData = Stream_New(nullptr, outlen);
1219
1220 if (!context->responseData)
1221 {
1222 WLog_ERR(TAG, "Failed to create decryption buffer");
1223 goto decrypt_failed;
1224 }
1225
1226 /* Decrypt */
1227 res = EVP_PKEY_decrypt(ctx, Stream_Buffer(context->responseData), &outlen,
1228 Stream_Buffer(context->commandData), inlen);
1229
1230 if (res <= 0)
1231 {
1232 WLog_ERR(TAG, "Failed to decrypt data");
1233 goto decrypt_failed;
1234 }
1235
1236 rc = Stream_SetLength(context->responseData, outlen);
1237 }
1238
1239decrypt_failed:
1240 EVP_PKEY_CTX_free(ctx);
1241 EVP_PKEY_free(pkey);
1242 vgids_reset_context_command_data(context);
1243 if (!rc)
1244 vgids_reset_context_response(context);
1245 return rc;
1246}
1247
1248WINPR_ATTR_NODISCARD
1249static BOOL vgids_ins_perform_security_operation(vgidsContext* context, wStream* s, BYTE** response,
1250 DWORD* responseSize)
1251{
1252 BYTE cla = 0;
1253 BYTE p1 = 0;
1254 BYTE p2 = 0;
1255 BYTE lc = 0;
1256 DWORD resultDataSize = 0;
1257 const BYTE* resultData = nullptr;
1258 UINT16 status = ISO_STATUS_SUCCESS;
1259
1260 /* Perform security operation */
1261 if (!vgids_parse_apdu_header(s, &cla, nullptr, &p1, &p2, &lc, nullptr))
1262 return FALSE;
1263
1264 if (lc == 0)
1265 {
1266 status = ISO_STATUS_WRONGLC;
1267 goto create_response;
1268 }
1269
1270 /* Is our default key referenced? */
1271 if (context->currentSE.keyRef != VGIDS_DEFAULT_KEY_REF)
1272 {
1273 status = ISO_STATUS_SECURITYSTATUSNOTSATISFIED;
1274 goto create_response;
1275 }
1276
1277 /* is the pin protecting the key verified? */
1278 if (!context->pinVerified)
1279 {
1280 status = ISO_STATUS_SECURITYSTATUSNOTSATISFIED;
1281 goto create_response;
1282 }
1283
1284 /* Append the data to the context command buffer (PSO might chain command data) */
1285 if (!context->commandData)
1286 {
1287 context->commandData = Stream_New(nullptr, lc);
1288 if (!context->commandData)
1289 return FALSE;
1290 }
1291 else if (!Stream_EnsureRemainingCapacity(context->commandData, lc))
1292 return FALSE;
1293
1294 Stream_Write(context->commandData, Stream_Pointer(s), lc);
1295 Stream_SealLength(context->commandData);
1296
1297 /* Check if the correct operation is requested for our current SE */
1298 switch (context->currentSE.crt)
1299 {
1300 case VGIDS_SE_CRT_SIGN:
1301 {
1302 if (p1 != 0x9E || p2 != 0x9A)
1303 {
1304 status = ISO_STATUS_INVALIDP1P2;
1305 break;
1306 }
1307
1308 /* If chaining is over perform op */
1309 if (!(cla & 0x10))
1310 {
1311 if (!vgids_perform_digital_signature(context))
1312 return FALSE;
1313 }
1314 break;
1315 }
1316 case VGIDS_SE_CRT_CONF:
1317 {
1318 if ((p1 != 0x86 || p2 != 0x80) && (p1 != 0x80 || p2 != 0x86))
1319 {
1320 status = ISO_STATUS_INVALIDP1P2;
1321 break;
1322 }
1323
1324 /* If chaining is over perform op */
1325 if (!(cla & 0x10))
1326 {
1327 if (!vgids_perform_decrypt(context))
1328 return FALSE;
1329 }
1330 break;
1331 }
1332 default:
1333 status = ISO_STATUS_INVALIDP1P2;
1334 break;
1335 }
1336
1337 /* Do chaining of response data if necessary */
1338 if (status == ISO_STATUS_SUCCESS && context->responseData)
1339 status = vgids_handle_chained_response(context, &resultData, &resultDataSize);
1340
1341 /* Check APDU params */
1342create_response:
1343 return vgids_create_response(status, resultData, resultDataSize, response, responseSize);
1344}
1345
1346WINPR_ATTR_NODISCARD
1347static BOOL vgids_ins_getresponse(vgidsContext* context, wStream* s, BYTE** response,
1348 DWORD* responseSize)
1349{
1350 BYTE p1 = 0;
1351 BYTE p2 = 0;
1352 BYTE le = 0;
1353 DWORD resultDataSize = 0;
1354 const BYTE* resultData = nullptr;
1355 DWORD expectedLen = 0;
1356 DWORD remainingSize = 0;
1357 UINT16 status = ISO_STATUS_SUCCESS;
1358
1359 /* Get response continues data transfer after a previous get data command */
1360 /* Check if there is any data to transfer left */
1361 if (!context->responseData || !Stream_CheckAndLogRequiredLength(TAG, context->responseData, 1))
1362 {
1363 status = ISO_STATUS_COMMANDNOTALLOWED;
1364 goto create_response;
1365 }
1366
1367 if (!vgids_parse_apdu_header(s, nullptr, nullptr, &p1, &p2, nullptr, &le))
1368 return FALSE;
1369
1370 /* Check APDU params */
1371 if (p1 != 00 || p2 != 0x00)
1372 {
1373 status = ISO_STATUS_INVALIDP1P2;
1374 goto create_response;
1375 }
1376
1377 /* LE = 0 means 256 bytes expected */
1378 expectedLen = le;
1379 if (expectedLen == 0)
1380 expectedLen = 256;
1381
1382 /* prepare response size and update offset */
1383 remainingSize = (DWORD)Stream_GetRemainingLength(context->responseData);
1384 if (remainingSize < expectedLen)
1385 expectedLen = remainingSize;
1386
1387 resultData = Stream_Pointer(context->responseData);
1388 resultDataSize = expectedLen;
1389 Stream_Seek(context->responseData, expectedLen);
1390
1391 /* If more data is left return 61XX - otherwise 9000 */
1392 remainingSize = (DWORD)Stream_GetRemainingLength(context->responseData);
1393 if (remainingSize > 0)
1394 {
1395 status = ISO_STATUS_MORE_DATA;
1396 if (remainingSize < 256)
1397 status |= (remainingSize & 0xFF);
1398 }
1399
1400create_response:
1401 return vgids_create_response(status, resultData, resultDataSize, response, responseSize);
1402}
1403
1404WINPR_ATTR_NODISCARD
1405static BOOL vgids_ins_verify(vgidsContext* context, wStream* s, BYTE** response,
1406 DWORD* responseSize)
1407{
1408 BYTE ins = 0;
1409 BYTE p1 = 0;
1410 BYTE p2 = 0;
1411 BYTE lc = 0;
1412 UINT16 status = ISO_STATUS_SUCCESS;
1413 char pin[VGIDS_MAX_PIN_SIZE + 1] = WINPR_C_ARRAY_INIT;
1414
1415 /* Verify is always called for the application password (PIN) P2=0x80 */
1416 if (!vgids_parse_apdu_header(s, nullptr, &ins, &p1, &p2, nullptr, nullptr))
1417 return FALSE;
1418
1419 /* Check APDU params */
1420 if (p1 != 00 && p2 != 0x80 && p2 != 0x82)
1421 {
1422 status = ISO_STATUS_INVALIDP1P2;
1423 goto create_response;
1424 }
1425
1426 /* shall we reset the security state? */
1427 if (p2 == 0x82)
1428 {
1429 context->pinVerified = FALSE;
1430 goto create_response;
1431 }
1432
1433 /* Check if pin is not already blocked */
1434 if (Emulate_IsPinBlocked(context->emuContext, context->name))
1435 {
1436 status = ISO_STATUS_AUTHMETHODBLOCKED;
1437 goto create_response;
1438 }
1439
1440 /* Read and verify LC */
1441 if (!Stream_CheckAndLogRequiredLength(TAG, s, 1))
1442 {
1443 status = ISO_STATUS_INVALIDLC;
1444 goto create_response;
1445 }
1446
1447 Stream_Read_UINT8(s, lc);
1448 if (!Stream_CheckAndLogRequiredLength(TAG, s, lc) || (lc > VGIDS_MAX_PIN_SIZE))
1449 {
1450 status = ISO_STATUS_INVALIDLC;
1451 goto create_response;
1452 }
1453
1454 /* read and verify pin */
1455 Stream_Read(s, pin, lc);
1456
1457 UINT16 remaining = 0;
1458 if (!Emulate_IsPinValid(context->emuContext, context->name, pin, lc, &remaining))
1459 {
1460 /* retries are encoded in the lowest 4-bit of the status code */
1461 context->pinVerified = FALSE;
1462 status = (ISO_STATUS_VERIFYFAILED | (remaining & 0xFF));
1463 }
1464 else
1465 {
1466 /* reset retry counter and mark pin as verified */
1467 context->pinVerified = TRUE;
1468 }
1469
1470create_response:
1471 return vgids_create_response(status, nullptr, 0, response, responseSize);
1472}
1473
1474vgidsContext* vgids_new(SmartcardEmulationContext* context)
1475{
1476 if (!context)
1477 return nullptr;
1478
1479 vgidsContext* ctx = calloc(1, sizeof(vgidsContext));
1480 if (!ctx)
1481 return nullptr;
1482 ctx->emuContext = context;
1483
1484 ctx->files = ArrayList_New(FALSE);
1485 if (!ctx->files)
1486 {
1487 WLog_ERR(TAG, "Failed to create files array list");
1488 goto create_failed;
1489 }
1490
1491 wObject* obj = ArrayList_Object(ctx->files);
1492 obj->fnObjectFree = vgids_ef_free;
1493
1494 return ctx;
1495
1496create_failed:
1497 vgids_free(ctx);
1498 return nullptr;
1499}
1500
1501BOOL vgids_init(vgidsContext* ctx, const char* cert, const char* privateKey, const char* pin)
1502{
1503 DWORD kxcSize = 0;
1504 DWORD keymapSize = 0;
1505 DWORD fsTableSize = 0;
1506 BOOL rc = FALSE;
1507 BYTE* kxc = nullptr;
1508 BYTE* keymap = nullptr;
1509 BYTE* fsTable = nullptr;
1510 vgidsEF* masterEF = nullptr;
1511 vgidsEF* cardidEF = nullptr;
1512 vgidsEF* commonEF = nullptr;
1513 BYTE cardid[VGIDS_CARDID_SIZE] = WINPR_C_ARRAY_INIT;
1514 vgidsContainerMapEntry cmrec = { { 'P', 'r', 'i', 'v', 'a', 't', 'e', ' ', 'K', 'e', 'y', ' ',
1515 '0', '0' },
1516 CONTAINER_MAP_VALID_CONTAINER |
1517 CONTAINER_MAP_DEFAULT_CONTAINER,
1518 0,
1519 0,
1520 0x00 /* key-size in bits - filled out later */ };
1521 vgidsFilesysTableEntry filesys[] = {
1522 { "mscp", "", 0, 0, 0, 0xA000, 0 },
1523 { "", "cardid", 0, 0xDF20, 0, 0xA012, 0 },
1524 { "", "cardapps", 0, 0xDF21, 0, 0xA010, 0 },
1525 { "", "cardcf", 0, 0xDF22, 0, 0xA010, 0 },
1526 { "mscp", "cmapfile", 0, 0xDF23, 0, 0xA010, 0 },
1527 { "mscp", "kxc00", 0, 0xDF24, 0, 0xA010, 0 },
1528 };
1529
1530 /* Check params */
1531 if (!cert || !privateKey || !pin)
1532 {
1533 WLog_DBG(TAG, "Passed invalid nullptr argument: cert=%p, privateKey=%p, pin=%p",
1534 WINPR_CXX_COMPAT_CAST(const void*, cert),
1535 WINPR_CXX_COMPAT_CAST(const void*, privateKey),
1536 WINPR_CXX_COMPAT_CAST(const void*, pin));
1537 goto init_failed;
1538 }
1539
1540 /* Convert PEM input to DER certificate/public key/private key */
1541 ctx->certificate = freerdp_certificate_new_from_pem(cert);
1542 if (!ctx->certificate)
1543 goto init_failed;
1544
1545 ctx->privateKey = freerdp_key_new_from_pem_enc(privateKey, nullptr);
1546 if (!ctx->privateKey)
1547 goto init_failed;
1548
1549 ctx->name = freerdp_certificate_get_fingerprint(ctx->certificate);
1550 if (!ctx->name)
1551 goto init_failed;
1552
1553 /* create masterfile */
1554 // NOLINTNEXTLINE(clang-analyzer-unix.Malloc)
1555 masterEF = vgids_ef_new(ctx, VGIDS_EFID_MASTER);
1556 if (!masterEF)
1557 goto init_failed;
1558
1559 /* create cardid file with cardid DO */
1560 // NOLINTNEXTLINE(clang-analyzer-unix.Malloc)
1561 cardidEF = vgids_ef_new(ctx, VGIDS_EFID_CARDID);
1562 if (!cardidEF)
1563 goto init_failed;
1564 if (winpr_RAND(cardid, sizeof(cardid)) < 0)
1565 goto init_failed;
1566 if (!vgids_ef_write_do(cardidEF, VGIDS_DO_CARDID, cardid, sizeof(cardid)))
1567 goto init_failed;
1568
1569 /* create user common file */
1570 // NOLINTNEXTLINE(clang-analyzer-unix.Malloc)
1571 commonEF = vgids_ef_new(ctx, VGIDS_EFID_COMMON);
1572 if (!commonEF)
1573 goto init_failed;
1574
1575 /* write card cache DO */
1576 if (!vgids_ef_write_do(commonEF, VGIDS_DO_CARDCF, g_CardCFContents, sizeof(g_CardCFContents)))
1577 goto init_failed;
1578
1579 /* write container map DO */
1580 {
1581 const size_t size = get_rsa_key_size(ctx->privateKey);
1582 if ((size == 0) || (size > UINT16_MAX / 8))
1583 goto init_failed;
1584
1585 cmrec.wKeyExchangeKeySizeBits = (WORD)size * 8;
1586 }
1587 if (!vgids_ef_write_do(commonEF, VGIDS_DO_CMAPFILE, &cmrec, sizeof(cmrec)))
1588 goto init_failed;
1589
1590 /* write cardapps DO */
1591 if (!vgids_ef_write_do(commonEF, VGIDS_DO_CARDAPPS, g_CardAppsContents,
1592 sizeof(g_CardAppsContents)))
1593 goto init_failed;
1594
1595 /* convert and write certificate to key exchange container */
1596 if (!vgids_prepare_certificate(ctx->certificate, &kxc, &kxcSize))
1597 goto init_failed;
1598 if (!vgids_ef_write_do(commonEF, VGIDS_DO_KXC00, kxc, kxcSize))
1599 goto init_failed;
1600
1601 /* prepare and write file system table */
1602 if (!vgids_prepare_fstable(filesys, ARRAYSIZE(filesys), &fsTable, &fsTableSize))
1603 goto init_failed;
1604 if (!vgids_ef_write_do(masterEF, VGIDS_DO_FILESYSTEMTABLE, fsTable, fsTableSize))
1605 goto init_failed;
1606
1607 /* vgids_prepare_keymap and write to masterEF */
1608 if (!vgids_prepare_keymap(ctx, &keymap, &keymapSize))
1609 goto init_failed;
1610 if (!vgids_ef_write_do(masterEF, VGIDS_DO_KEYMAP, keymap, keymapSize))
1611 goto init_failed;
1612
1613 /* store user pin */
1614 if (!Emulate_SetupPin(ctx->emuContext, ctx->name, pin))
1615 goto init_failed;
1616
1617 rc = TRUE;
1618
1619init_failed:
1620 // ArrayList_Append in vgids_ef_new takes ownership
1621 // of cardidEF, commonEF, masterEF
1622 // NOLINTNEXTLINE(clang-analyzer-unix.Malloc)
1623 free(kxc);
1624 free(keymap);
1625 free(fsTable);
1626 return rc;
1627}
1628
1629BOOL vgids_process_apdu(vgidsContext* context, const BYTE* data, DWORD dataSize, BYTE** response,
1630 DWORD* responseSize)
1631{
1632 wStream s;
1633 static int x = 1;
1634
1635 /* Check params */
1636 if (!context || !data || !response || !responseSize)
1637 {
1638 WLog_ERR(TAG, "Invalid nullptr pointer passed");
1639 return FALSE;
1640 }
1641
1642 if (dataSize < 4)
1643 {
1644 WLog_ERR(TAG, "APDU buffer is less than 4 bytes: %" PRIu32, dataSize);
1645 return FALSE;
1646 }
1647
1648 /* Examine INS byte */
1649 Stream_StaticConstInit(&s, data, dataSize);
1650 if (x++ == 0xe)
1651 x = 0xe + 1;
1652 switch (data[1])
1653 {
1654 case ISO_INS_SELECT:
1655 return vgids_ins_select(context, &s, response, responseSize);
1656 case ISO_INS_GETDATA:
1657 return vgids_ins_getdata(context, &s, response, responseSize);
1658 case ISO_INS_GETRESPONSE:
1659 return vgids_ins_getresponse(context, &s, response, responseSize);
1660 case ISO_INS_MSE:
1661 return vgids_ins_manage_security_environment(context, &s, response, responseSize);
1662 case ISO_INS_PSO:
1663 return vgids_ins_perform_security_operation(context, &s, response, responseSize);
1664 case ISO_INS_VERIFY:
1665 return vgids_ins_verify(context, &s, response, responseSize);
1666 default:
1667 break;
1668 }
1669
1670 /* return command not allowed */
1671 return vgids_create_response(ISO_STATUS_COMMANDNOTALLOWED, nullptr, 0, response, responseSize);
1672}
1673
1674void vgids_free(vgidsContext* context)
1675{
1676 if (context)
1677 {
1678 freerdp_key_free(context->privateKey);
1679 freerdp_certificate_free(context->certificate);
1680 Stream_Free(context->commandData, TRUE);
1681 Stream_Free(context->responseData, TRUE);
1682 winpr_zfree(context->name);
1683 ArrayList_Free(context->files);
1684 free(context);
1685 }
1686}
This struct contains function pointer to initialize/free objects.
Definition collections.h:52