Coverage Report

Created: 2026-03-04 06:17

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/FreeRDP/libfreerdp/core/smartcardlogon.c
Line
Count
Source
1
/**
2
 * FreeRDP: A Remote Desktop Protocol Implementation
3
 * Logging in with smartcards
4
 *
5
 * Copyright 2022 David Fort <contact@hardening-consulting.com>
6
 *
7
 * Licensed under the Apache License, Version 2.0 (the "License");
8
 * you may not use this file except in compliance with the License.
9
 * You may obtain a copy of the License at
10
 *
11
 *     http://www.apache.org/licenses/LICENSE-2.0
12
 *
13
 * Unless required by applicable law or agreed to in writing, software
14
 * distributed under the License is distributed on an "AS IS" BASIS,
15
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
 * See the License for the specific language governing permissions and
17
 * limitations under the License.
18
 */
19
#include <string.h>
20
21
#include <winpr/error.h>
22
#include <winpr/ncrypt.h>
23
#include <winpr/string.h>
24
#include <winpr/wlog.h>
25
#include <winpr/crypto.h>
26
#include <winpr/path.h>
27
28
#include <freerdp/log.h>
29
#include <freerdp/freerdp.h>
30
#include <winpr/print.h>
31
32
#include <freerdp/utils/smartcardlogon.h>
33
#include <freerdp/crypto/crypto.h>
34
#include <freerdp/utils/helpers.h>
35
36
#include <openssl/obj_mac.h>
37
38
#define TAG FREERDP_TAG("smartcardlogon")
39
40
struct SmartcardKeyInfo_st
41
{
42
  char* certPath;
43
  char* keyPath;
44
};
45
46
static void delete_file(char* path)
47
0
{
48
0
  if (!path)
49
0
    return;
50
51
  /* Overwrite data in files before deletion */
52
0
  {
53
0
    FILE* fp = winpr_fopen(path, "r+");
54
0
    if (fp)
55
0
    {
56
0
      const char buffer[8192] = WINPR_C_ARRAY_INIT;
57
0
      INT64 size = 0;
58
0
      int rs = _fseeki64(fp, 0, SEEK_END);
59
0
      if (rs == 0)
60
0
        size = _ftelli64(fp);
61
0
      if (_fseeki64(fp, 0, SEEK_SET) == 0)
62
0
      {
63
0
        for (INT64 x = 0; x < size; x += sizeof(buffer))
64
0
        {
65
0
          const size_t dnmemb = (size_t)(size - x);
66
0
          const size_t nmemb = MIN(sizeof(buffer), dnmemb);
67
0
          const size_t count = fwrite(buffer, nmemb, 1, fp);
68
0
          if (count != 1)
69
0
            break;
70
0
        }
71
0
      }
72
73
0
      (void)fclose(fp);
74
0
    }
75
0
  }
76
77
0
  winpr_DeleteFile(path);
78
0
  free(path);
79
0
}
80
81
static void smartcardKeyInfo_Free(SmartcardKeyInfo* key_info)
82
0
{
83
0
  if (!key_info)
84
0
    return;
85
86
0
  delete_file(key_info->certPath);
87
0
  delete_file(key_info->keyPath);
88
89
0
  free(key_info);
90
0
}
91
92
void smartcardCertInfo_Free(SmartcardCertInfo* scCert)
93
15.4k
{
94
15.4k
  if (!scCert)
95
15.4k
    return;
96
97
0
  free(scCert->csp);
98
0
  free(scCert->reader);
99
0
  freerdp_certificate_free(scCert->certificate);
100
0
  free(scCert->pkinitArgs);
101
0
  free(scCert->keyName);
102
0
  free(scCert->containerName);
103
0
  free(scCert->upn);
104
0
  free(scCert->userHint);
105
0
  free(scCert->domainHint);
106
0
  free(scCert->subject);
107
0
  free(scCert->issuer);
108
0
  smartcardKeyInfo_Free(scCert->key_info);
109
110
0
  free(scCert);
111
0
}
112
113
void smartcardCertList_Free(SmartcardCertInfo** pscCert, size_t count)
114
0
{
115
0
  if (!pscCert)
116
0
    return;
117
118
0
  for (size_t i = 0; i < count; i++)
119
0
  {
120
0
    SmartcardCertInfo* cert = pscCert[i];
121
0
    smartcardCertInfo_Free(cert);
122
0
  }
123
124
0
  free((void*)pscCert);
125
0
}
126
127
static BOOL add_cert_to_list(SmartcardCertInfo*** certInfoList, size_t* count,
128
                             SmartcardCertInfo* certInfo)
129
0
{
130
0
  size_t curCount = *count;
131
0
  SmartcardCertInfo** curInfoList = *certInfoList;
132
133
  /* Check if the certificate is already in the list */
134
0
  for (size_t i = 0; i < curCount; ++i)
135
0
  {
136
0
    if (_wcscmp(curInfoList[i]->containerName, certInfo->containerName) == 0)
137
0
    {
138
0
      smartcardCertInfo_Free(certInfo);
139
0
      return TRUE;
140
0
    }
141
0
  }
142
143
0
  {
144
0
    SmartcardCertInfo** tmpInfoList = (SmartcardCertInfo**)realloc(
145
0
        (void*)curInfoList, sizeof(SmartcardCertInfo*) * (curCount + 1));
146
0
    if (!tmpInfoList)
147
0
    {
148
0
      WLog_ERR(TAG, "unable to reallocate certs");
149
0
      return FALSE;
150
0
    }
151
0
    curInfoList = tmpInfoList;
152
0
  }
153
154
0
  curInfoList[curCount++] = certInfo;
155
0
  *certInfoList = curInfoList;
156
0
  *count = curCount;
157
0
  return TRUE;
158
0
}
159
160
static BOOL treat_sc_cert(SmartcardCertInfo* scCert)
161
0
{
162
0
  WINPR_ASSERT(scCert);
163
164
0
  scCert->upn = freerdp_certificate_get_upn(scCert->certificate);
165
0
  if (!scCert->upn)
166
0
  {
167
0
    WLog_DBG(TAG, "%s has no UPN, trying emailAddress", scCert->keyName);
168
0
    scCert->upn = freerdp_certificate_get_email(scCert->certificate);
169
0
  }
170
171
0
  if (scCert->upn)
172
0
  {
173
0
    size_t userLen = 0;
174
0
    const char* atPos = strchr(scCert->upn, '@');
175
176
0
    if (!atPos)
177
0
    {
178
0
      WLog_ERR(TAG, "invalid UPN, for key %s (no @)", scCert->keyName);
179
0
      return FALSE;
180
0
    }
181
182
0
    userLen = (size_t)(atPos - scCert->upn);
183
0
    scCert->userHint = malloc(userLen + 1);
184
0
    scCert->domainHint = _strdup(atPos + 1);
185
186
0
    if (!scCert->userHint || !scCert->domainHint)
187
0
    {
188
0
      WLog_ERR(TAG, "error allocating userHint or domainHint, for key %s", scCert->keyName);
189
0
      return FALSE;
190
0
    }
191
192
0
    memcpy(scCert->userHint, scCert->upn, userLen);
193
0
    scCert->userHint[userLen] = 0;
194
0
  }
195
196
0
  scCert->subject = freerdp_certificate_get_subject(scCert->certificate);
197
0
  scCert->issuer = freerdp_certificate_get_issuer(scCert->certificate);
198
0
  return TRUE;
199
0
}
200
201
static BOOL set_info_certificate(SmartcardCertInfo* cert, BYTE* certBytes, DWORD cbCertBytes,
202
                                 const char* userFilter, const char* domainFilter)
203
0
{
204
0
  if (!winpr_Digest(WINPR_MD_SHA1, certBytes, cbCertBytes, cert->sha1Hash,
205
0
                    sizeof(cert->sha1Hash)))
206
0
  {
207
0
    WLog_ERR(TAG, "unable to compute certificate sha1 for key %s", cert->keyName);
208
0
    return FALSE;
209
0
  }
210
211
0
  cert->certificate = freerdp_certificate_new_from_der(certBytes, cbCertBytes);
212
0
  if (!cert->certificate)
213
0
  {
214
0
    WLog_ERR(TAG, "unable to parse X509 certificate for key %s", cert->keyName);
215
0
    return FALSE;
216
0
  }
217
218
0
  if (!freerdp_certificate_check_eku(cert->certificate, NID_ms_smartcard_login))
219
0
  {
220
0
    WLog_DBG(TAG, "discarding certificate without Smartcard Login EKU for key %s",
221
0
             cert->keyName);
222
0
    return FALSE;
223
0
  }
224
225
0
  if (!treat_sc_cert(cert))
226
0
  {
227
0
    WLog_DBG(TAG, "error treating cert");
228
0
    return FALSE;
229
0
  }
230
231
0
  if (userFilter && (!cert->upn || (strcmp(cert->upn, userFilter) != 0)))
232
0
  {
233
0
    if (cert->userHint && strcmp(cert->userHint, userFilter) != 0)
234
0
    {
235
0
      WLog_DBG(TAG, "discarding non matching cert by user %s@%s", cert->userHint,
236
0
               cert->domainHint);
237
0
      return FALSE;
238
0
    }
239
0
  }
240
241
0
  if (domainFilter && cert->domainHint && strcmp(cert->domainHint, domainFilter) != 0)
242
0
  {
243
0
    WLog_DBG(TAG, "discarding non matching cert by domain(%s) %s@%s", domainFilter,
244
0
             cert->userHint, cert->domainHint);
245
0
    return FALSE;
246
0
  }
247
248
0
  return TRUE;
249
0
}
250
251
#ifndef _WIN32
252
static BOOL build_pkinit_args(NCRYPT_PROV_HANDLE provider, SmartcardCertInfo* scCert)
253
0
{
254
  /* pkinit args only under windows
255
   *    PKCS11:module_name=opensc-pkcs11.so
256
   */
257
0
  const char* pkModule = winpr_NCryptGetModulePath(provider);
258
0
  size_t size = 0;
259
260
0
  return (winpr_asprintf(&scCert->pkinitArgs, &size, "PKCS11:module_name=%s:slotid=%" PRIu16,
261
0
                         pkModule, (UINT16)scCert->slotId) > 0);
262
0
}
263
#endif /* _WIN32 */
264
265
#ifdef _WIN32
266
static BOOL list_capi_provider_keys(const rdpSettings* settings, LPCWSTR csp, LPCWSTR scope,
267
                                    const char* userFilter, const char* domainFilter,
268
                                    SmartcardCertInfo*** pcerts, size_t* pcount)
269
{
270
  BOOL ret = FALSE;
271
  HCRYPTKEY hKey = 0;
272
  HCRYPTPROV hProvider = 0;
273
  SmartcardCertInfo* cert = nullptr;
274
  BYTE* certBytes = nullptr;
275
  CHAR* readerName = nullptr;
276
277
  if (!CryptAcquireContextW(&hProvider, scope, csp, PROV_RSA_FULL, CRYPT_SILENT))
278
  {
279
    WLog_DBG(TAG, "Unable to acquire context: %d", GetLastError());
280
    goto out;
281
  }
282
283
  cert = calloc(1, sizeof(SmartcardCertInfo));
284
  if (!cert)
285
    goto out;
286
287
  cert->csp = _wcsdup(csp);
288
  if (!cert->csp)
289
    goto out;
290
291
  /* ====== retrieve key's reader ====== */
292
  DWORD dwDataLen = 0;
293
  if (!CryptGetProvParam(hProvider, PP_SMARTCARD_READER, nullptr, &dwDataLen, 0))
294
  {
295
    WLog_DBG(TAG, "Unable to get provider param: %d", GetLastError());
296
    goto out;
297
  }
298
299
  readerName = malloc(dwDataLen);
300
  if (!readerName)
301
    goto out;
302
303
  if (!CryptGetProvParam(hProvider, PP_SMARTCARD_READER, readerName, &dwDataLen, 0))
304
  {
305
    WLog_DBG(TAG, "Unable to get reader name: %d", GetLastError());
306
    goto out;
307
  }
308
309
  cert->reader = ConvertUtf8ToWCharAlloc(readerName, nullptr);
310
  if (!cert->reader)
311
    goto out;
312
313
  /* ====== retrieve key container name ====== */
314
  dwDataLen = 0;
315
  if (!CryptGetProvParam(hProvider, PP_CONTAINER, nullptr, &dwDataLen, 0))
316
  {
317
    WLog_DBG(TAG, "Unable to get provider param: %d", GetLastError());
318
    goto out;
319
  }
320
321
  cert->keyName = malloc(dwDataLen);
322
  if (!cert->keyName)
323
    goto out;
324
325
  if (!CryptGetProvParam(hProvider, PP_CONTAINER, cert->keyName, &dwDataLen, 0))
326
  {
327
    WLog_DBG(TAG, "Unable to get container name: %d", GetLastError());
328
    goto out;
329
  }
330
331
  cert->containerName = ConvertUtf8ToWCharAlloc(cert->keyName, nullptr);
332
  if (!cert->containerName)
333
    goto out;
334
335
  /* ========= retrieve the certificate ===============*/
336
  if (!CryptGetUserKey(hProvider, AT_KEYEXCHANGE, &hKey))
337
  {
338
    WLog_DBG(TAG, "Unable to get user key for %s: %d", cert->keyName, GetLastError());
339
    goto out;
340
  }
341
342
  dwDataLen = 0;
343
  if (!CryptGetKeyParam(hKey, KP_CERTIFICATE, nullptr, &dwDataLen, 0))
344
  {
345
    WLog_DBG(TAG, "Unable to get key param for key %s: %d", cert->keyName, GetLastError());
346
    goto out;
347
  }
348
349
  certBytes = malloc(dwDataLen);
350
  if (!certBytes)
351
  {
352
    WLog_ERR(TAG, "unable to allocate %" PRIu32 " certBytes for key %s", dwDataLen,
353
             cert->keyName);
354
    goto out;
355
  }
356
357
  if (!CryptGetKeyParam(hKey, KP_CERTIFICATE, certBytes, &dwDataLen, 0))
358
  {
359
    WLog_ERR(TAG, "unable to retrieve certificate for key %s", cert->keyName);
360
    goto out;
361
  }
362
363
  if (!set_info_certificate(cert, certBytes, dwDataLen, userFilter, domainFilter))
364
    goto out;
365
366
  if (!add_cert_to_list(pcerts, pcount, cert))
367
    goto out;
368
369
  ret = TRUE;
370
371
out:
372
  free(readerName);
373
  free(certBytes);
374
  if (hKey)
375
    CryptDestroyKey(hKey);
376
  if (hProvider)
377
    CryptReleaseContext(hProvider, 0);
378
  if (!ret)
379
    smartcardCertInfo_Free(cert);
380
  return ret;
381
}
382
#endif /* _WIN32 */
383
384
static BOOL list_provider_keys(WINPR_ATTR_UNUSED const rdpSettings* settings,
385
                               NCRYPT_PROV_HANDLE provider, LPCWSTR csp, LPCWSTR scope,
386
                               const char* userFilter, const char* domainFilter,
387
                               SmartcardCertInfo*** pcerts, size_t* pcount)
388
0
{
389
0
  BOOL ret = FALSE;
390
0
  NCryptKeyName* keyName = nullptr;
391
0
  PVOID enumState = nullptr;
392
0
  SmartcardCertInfo** cert_list = *pcerts;
393
0
  size_t count = *pcount;
394
395
0
  while (NCryptEnumKeys(provider, scope, &keyName, &enumState, NCRYPT_SILENT_FLAG) ==
396
0
         ERROR_SUCCESS)
397
0
  {
398
0
    NCRYPT_KEY_HANDLE phKey = 0;
399
0
    PBYTE certBytes = nullptr;
400
0
    DWORD dwFlags = NCRYPT_SILENT_FLAG;
401
0
    DWORD cbOutput = 0;
402
0
    SmartcardCertInfo* cert = nullptr;
403
0
    BOOL haveError = TRUE;
404
0
    SECURITY_STATUS status = 0;
405
406
0
    cert = calloc(1, sizeof(SmartcardCertInfo));
407
0
    if (!cert)
408
0
      goto out;
409
410
0
    cert->keyName = ConvertWCharToUtf8Alloc(keyName->pszName, nullptr);
411
0
    if (!cert->keyName)
412
0
      goto endofloop;
413
414
0
    WLog_DBG(TAG, "opening key %s", cert->keyName);
415
416
0
    status =
417
0
        NCryptOpenKey(provider, &phKey, keyName->pszName, keyName->dwLegacyKeySpec, dwFlags);
418
0
    if (status != ERROR_SUCCESS)
419
0
    {
420
0
      WLog_DBG(TAG,
421
0
               "unable to NCryptOpenKey(dwLegacyKeySpec=0x%08" PRIx32 " dwFlags=0x%08" PRIx32
422
0
               "), status=%s, skipping",
423
0
               keyName->dwLegacyKeySpec, keyName->dwFlags,
424
0
               winpr_NCryptSecurityStatusError(status));
425
0
      goto endofloop;
426
0
    }
427
428
0
    cert->csp = _wcsdup(csp);
429
0
    if (!cert->csp)
430
0
      goto endofloop;
431
432
0
#ifndef _WIN32
433
0
    status = NCryptGetProperty(phKey, NCRYPT_WINPR_SLOTID, (PBYTE)&cert->slotId, 4, &cbOutput,
434
0
                               dwFlags);
435
0
    if (status != ERROR_SUCCESS)
436
0
    {
437
0
      WLog_ERR(TAG, "unable to retrieve slotId for key %s, status=%s", cert->keyName,
438
0
               winpr_NCryptSecurityStatusError(status));
439
0
      goto endofloop;
440
0
    }
441
0
#endif /* _WIN32 */
442
443
    /* ====== retrieve key's reader ====== */
444
0
    cbOutput = 0;
445
0
    status = NCryptGetProperty(phKey, NCRYPT_READER_PROPERTY, nullptr, 0, &cbOutput, dwFlags);
446
0
    if (status != ERROR_SUCCESS)
447
0
    {
448
0
      WLog_DBG(TAG, "unable to retrieve reader's name length for key %s", cert->keyName);
449
0
      goto endofloop;
450
0
    }
451
452
0
    cert->reader = calloc(1, cbOutput + 2);
453
0
    if (!cert->reader)
454
0
    {
455
0
      WLog_ERR(TAG, "unable to allocate reader's name for key %s", cert->keyName);
456
0
      goto endofloop;
457
0
    }
458
459
0
    status = NCryptGetProperty(phKey, NCRYPT_READER_PROPERTY, (PBYTE)cert->reader, cbOutput + 2,
460
0
                               &cbOutput, dwFlags);
461
0
    if (status != ERROR_SUCCESS)
462
0
    {
463
0
      WLog_ERR(TAG, "unable to retrieve reader's name for key %s", cert->keyName);
464
0
      goto endofloop;
465
0
    }
466
467
    /* ====== retrieve key container name ====== */
468
    /* When using PKCS11, this will try to return what Windows would use for the key's name */
469
0
    cbOutput = 0;
470
0
    status = NCryptGetProperty(phKey, NCRYPT_NAME_PROPERTY, nullptr, 0, &cbOutput, dwFlags);
471
0
    if (status == ERROR_SUCCESS)
472
0
    {
473
0
      cert->containerName = calloc(1, cbOutput + sizeof(WCHAR));
474
0
      if (!cert->containerName)
475
0
      {
476
0
        WLog_ERR(TAG, "unable to allocate key container name for key %s", cert->keyName);
477
0
        goto endofloop;
478
0
      }
479
480
0
      status = NCryptGetProperty(phKey, NCRYPT_NAME_PROPERTY, (BYTE*)cert->containerName,
481
0
                                 cbOutput, &cbOutput, dwFlags);
482
0
    }
483
484
0
    if (status != ERROR_SUCCESS)
485
0
    {
486
0
      WLog_ERR(TAG, "unable to retrieve key container name for key %s", cert->keyName);
487
0
      goto endofloop;
488
0
    }
489
490
    /* ========= retrieve the certificate ===============*/
491
0
    cbOutput = 0;
492
0
    status =
493
0
        NCryptGetProperty(phKey, NCRYPT_CERTIFICATE_PROPERTY, nullptr, 0, &cbOutput, dwFlags);
494
0
    if (status != ERROR_SUCCESS)
495
0
    {
496
      /* can happen that key don't have certificates */
497
0
      WLog_DBG(TAG, "unable to retrieve certificate property len, status=%s, skipping",
498
0
               winpr_NCryptSecurityStatusError(status));
499
0
      goto endofloop;
500
0
    }
501
502
0
    certBytes = calloc(1, cbOutput);
503
0
    if (!certBytes)
504
0
    {
505
0
      WLog_ERR(TAG, "unable to allocate %" PRIu32 " certBytes for key %s", cbOutput,
506
0
               cert->keyName);
507
0
      goto endofloop;
508
0
    }
509
510
0
    status = NCryptGetProperty(phKey, NCRYPT_CERTIFICATE_PROPERTY, certBytes, cbOutput,
511
0
                               &cbOutput, dwFlags);
512
0
    if (status != ERROR_SUCCESS)
513
0
    {
514
0
      WLog_ERR(TAG, "unable to retrieve certificate for key %s", cert->keyName);
515
0
      goto endofloop;
516
0
    }
517
518
0
    if (!set_info_certificate(cert, certBytes, cbOutput, userFilter, domainFilter))
519
0
      goto endofloop;
520
521
0
#ifndef _WIN32
522
0
    if (!build_pkinit_args(provider, cert))
523
0
    {
524
0
      WLog_ERR(TAG, "error build pkinit args");
525
0
      goto endofloop;
526
0
    }
527
0
#endif
528
0
    haveError = FALSE;
529
530
0
  endofloop:
531
0
    free(certBytes);
532
0
    NCryptFreeBuffer(keyName);
533
0
    if (phKey)
534
0
      NCryptFreeObject((NCRYPT_HANDLE)phKey);
535
536
0
    if (haveError)
537
0
      smartcardCertInfo_Free(cert);
538
0
    else
539
0
    {
540
0
      if (!add_cert_to_list(&cert_list, &count, cert))
541
0
        goto out;
542
0
    }
543
0
  }
544
545
0
  ret = TRUE;
546
0
out:
547
0
  if (count == 0)
548
0
  {
549
0
    char cspa[128] = WINPR_C_ARRAY_INIT;
550
551
0
    (void)ConvertWCharToUtf8(csp, cspa, sizeof(cspa));
552
0
    char scopea[128] = WINPR_C_ARRAY_INIT;
553
0
    (void)ConvertWCharToUtf8(scope, scopea, sizeof(scopea));
554
0
    WLog_WARN(TAG, "%s [%s] no certificates found", cspa, scopea);
555
0
  }
556
0
  *pcount = count;
557
0
  *pcerts = cert_list;
558
0
  NCryptFreeBuffer(enumState);
559
0
  return ret;
560
0
}
561
562
static BOOL smartcard_hw_enumerateCerts(const rdpSettings* settings, LPCWSTR csp,
563
                                        const char* reader, const char* userFilter,
564
                                        const char* domainFilter, SmartcardCertInfo*** scCerts,
565
                                        size_t* retCount)
566
0
{
567
0
  BOOL ret = FALSE;
568
0
  LPWSTR scope = nullptr;
569
0
  NCRYPT_PROV_HANDLE provider = 0;
570
0
  SECURITY_STATUS status = 0;
571
0
  size_t count = 0;
572
0
  SmartcardCertInfo** cert_list = nullptr;
573
0
  const char* Pkcs11Module = freerdp_settings_get_string(settings, FreeRDP_Pkcs11Module);
574
575
0
  WINPR_ASSERT(scCerts);
576
0
  WINPR_ASSERT(retCount);
577
578
0
  if (reader)
579
0
  {
580
0
    size_t readerSz = strlen(reader);
581
0
    char* scopeStr = malloc(4 + readerSz + 1 + 1);
582
0
    if (!scopeStr)
583
0
      goto out;
584
585
0
    (void)_snprintf(scopeStr, readerSz + 6, "\\\\.\\%s\\", reader);
586
0
    scope = ConvertUtf8NToWCharAlloc(scopeStr, readerSz + 6, nullptr);
587
0
    free(scopeStr);
588
589
0
    if (!scope)
590
0
      goto out;
591
0
  }
592
593
0
  if (Pkcs11Module)
594
0
  {
595
    /* load a unique CSP by pkcs11 module path */
596
0
    LPCSTR paths[] = { Pkcs11Module, nullptr };
597
598
0
    if (!csp)
599
0
      csp = MS_SCARD_PROV;
600
601
0
    status = winpr_NCryptOpenStorageProviderEx(&provider, csp, 0, paths);
602
0
    if (status != ERROR_SUCCESS)
603
0
    {
604
0
      WLog_ERR(TAG, "unable to open provider given by pkcs11 module");
605
0
      goto out;
606
0
    }
607
608
0
    status = list_provider_keys(settings, provider, csp, scope, userFilter, domainFilter,
609
0
                                &cert_list, &count);
610
0
    NCryptFreeObject((NCRYPT_HANDLE)provider);
611
0
    if (!status)
612
0
    {
613
0
      WLog_ERR(TAG, "error listing keys from CSP loaded from %s", Pkcs11Module);
614
0
      goto out;
615
0
    }
616
0
  }
617
0
  else
618
0
  {
619
0
    NCryptProviderName* names = nullptr;
620
0
    DWORD nproviders = 0;
621
622
#ifdef _WIN32
623
    /* On Windows, mstsc first enumerates the legacy CAPI providers for usable certificates. */
624
    DWORD provType, cbProvName = 0;
625
    for (DWORD i = 0; CryptEnumProvidersW(i, nullptr, 0, &provType, nullptr, &cbProvName); ++i)
626
    {
627
      char providerNameStr[256] = WINPR_C_ARRAY_INIT;
628
      LPWSTR szProvName = malloc(cbProvName * sizeof(WCHAR));
629
      if (!CryptEnumProvidersW(i, nullptr, 0, &provType, szProvName, &cbProvName))
630
      {
631
        free(szProvName);
632
        break;
633
      }
634
635
      if (ConvertWCharToUtf8(szProvName, providerNameStr, ARRAYSIZE(providerNameStr)) < 0)
636
      {
637
        _snprintf(providerNameStr, sizeof(providerNameStr), "<unknown>");
638
        WLog_ERR(TAG, "unable to convert provider name to char*, will show it as '%s'",
639
                 providerNameStr);
640
      }
641
642
      WLog_DBG(TAG, "exploring CSP '%s'", providerNameStr);
643
      if (provType != PROV_RSA_FULL || (csp && _wcscmp(szProvName, csp) != 0))
644
      {
645
        WLog_DBG(TAG, "CSP '%s' filtered out", providerNameStr);
646
        goto end_of_loop;
647
      }
648
649
      if (!list_capi_provider_keys(settings, szProvName, scope, userFilter, domainFilter,
650
                                   &cert_list, &count))
651
        WLog_INFO(TAG, "error when retrieving keys in CSP '%s'", providerNameStr);
652
653
    end_of_loop:
654
      free(szProvName);
655
    }
656
#endif
657
658
0
    status = NCryptEnumStorageProviders(&nproviders, &names, NCRYPT_SILENT_FLAG);
659
0
    if (status != ERROR_SUCCESS)
660
0
    {
661
0
      WLog_ERR(TAG, "error listing providers");
662
0
      goto out;
663
0
    }
664
665
0
    for (DWORD i = 0; i < nproviders; i++)
666
0
    {
667
0
      char providerNameStr[256] = WINPR_C_ARRAY_INIT;
668
0
      const NCryptProviderName* name = &names[i];
669
670
0
      if (ConvertWCharToUtf8(name->pszName, providerNameStr, ARRAYSIZE(providerNameStr)) < 0)
671
0
      {
672
0
        (void)_snprintf(providerNameStr, sizeof(providerNameStr), "<unknown>");
673
0
        WLog_ERR(TAG, "unable to convert provider name to char*, will show it as '%s'",
674
0
                 providerNameStr);
675
0
      }
676
677
0
      WLog_DBG(TAG, "exploring CSP '%s'", providerNameStr);
678
0
      if (csp && _wcscmp(name->pszName, csp) != 0)
679
0
      {
680
0
        WLog_DBG(TAG, "CSP '%s' filtered out", providerNameStr);
681
0
        continue;
682
0
      }
683
684
0
      status = NCryptOpenStorageProvider(&provider, name->pszName, 0);
685
0
      if (status != ERROR_SUCCESS)
686
0
        continue;
687
688
0
      if (!list_provider_keys(settings, provider, name->pszName, scope, userFilter,
689
0
                              domainFilter, &cert_list, &count))
690
0
        WLog_INFO(TAG, "error when retrieving keys in CSP '%s'", providerNameStr);
691
692
0
      NCryptFreeObject((NCRYPT_HANDLE)provider);
693
0
    }
694
695
0
    NCryptFreeBuffer(names);
696
0
  }
697
698
0
  *scCerts = cert_list;
699
0
  *retCount = count;
700
0
  ret = TRUE;
701
702
0
out:
703
0
  if (!ret)
704
0
    smartcardCertList_Free(cert_list, count);
705
0
  free(scope);
706
0
  return ret;
707
0
}
708
709
static char* create_temporary_file(void)
710
0
{
711
0
  BYTE buffer[32] = WINPR_C_ARRAY_INIT;
712
0
  char* path = nullptr;
713
714
0
  if (winpr_RAND(buffer, sizeof(buffer)) < 0)
715
0
    return nullptr;
716
717
0
  char* hex = winpr_BinToHexString(buffer, sizeof(buffer), FALSE);
718
0
  if (hex)
719
0
    path = GetKnownSubPath(KNOWN_PATH_TEMP, hex);
720
0
  free(hex);
721
0
  return path;
722
0
}
723
724
static SmartcardCertInfo* smartcardCertInfo_New(const char* privKeyPEM, const char* certPEM)
725
0
{
726
0
  size_t size = 0;
727
728
0
  WINPR_ASSERT(privKeyPEM);
729
0
  WINPR_ASSERT(certPEM);
730
731
0
  SmartcardCertInfo* cert = calloc(1, sizeof(SmartcardCertInfo));
732
0
  if (!cert)
733
0
    goto fail;
734
735
0
  {
736
0
    SmartcardKeyInfo* info = cert->key_info = calloc(1, sizeof(SmartcardKeyInfo));
737
0
    if (!info)
738
0
      goto fail;
739
740
0
    cert->certificate = freerdp_certificate_new_from_pem(certPEM);
741
0
    if (!cert->certificate)
742
0
    {
743
0
      WLog_ERR(TAG, "unable to read smartcard certificate");
744
0
      goto fail;
745
0
    }
746
747
0
    if (!treat_sc_cert(cert))
748
0
    {
749
0
      WLog_ERR(TAG, "unable to treat smartcard certificate");
750
0
      goto fail;
751
0
    }
752
753
0
    {
754
0
      char* str = nullptr;
755
0
      size_t len = 0;
756
0
      (void)winpr_asprintf(&str, &len, "%s Emulator", freerdp_getApplicationDetailsString());
757
0
      if (str)
758
0
        cert->reader = ConvertUtf8NToWCharAlloc(str, len, nullptr);
759
0
      free(str);
760
0
    }
761
0
    if (!cert->reader)
762
0
      goto fail;
763
764
0
    cert->containerName = ConvertUtf8ToWCharAlloc("Private Key 00", nullptr);
765
0
    if (!cert->containerName)
766
0
      goto fail;
767
768
    /* compute PKINIT args FILE:<cert file>,<key file>
769
     *
770
     * We need files for PKINIT to read, so write the certificate to some
771
     * temporary location and use that.
772
     */
773
0
    info->keyPath = create_temporary_file();
774
0
    WLog_DBG(TAG, "writing PKINIT key to %s", info->keyPath);
775
0
    if (!crypto_write_pem(info->keyPath, privKeyPEM, strlen(privKeyPEM)))
776
0
      goto fail;
777
778
0
    info->certPath = create_temporary_file();
779
0
    WLog_DBG(TAG, "writing PKINIT cert to %s", info->certPath);
780
0
    if (!crypto_write_pem(info->certPath, certPEM, strlen(certPEM)))
781
0
      goto fail;
782
783
0
    {
784
0
      const int res = winpr_asprintf(&cert->pkinitArgs, &size, "FILE:%s,%s", info->certPath,
785
0
                                     info->keyPath);
786
0
      if (res <= 0)
787
0
        goto fail;
788
0
    }
789
0
  }
790
791
0
  return cert;
792
0
fail:
793
0
  smartcardCertInfo_Free(cert);
794
0
  return nullptr;
795
0
}
796
797
static BOOL smartcard_sw_enumerateCerts(const rdpSettings* settings, SmartcardCertInfo*** scCerts,
798
                                        size_t* retCount)
799
0
{
800
0
  BOOL rc = FALSE;
801
0
  SmartcardCertInfo** cert_list = nullptr;
802
803
0
  WINPR_ASSERT(settings);
804
0
  WINPR_ASSERT(scCerts);
805
0
  WINPR_ASSERT(retCount);
806
807
0
  const char* privKeyPEM = freerdp_settings_get_string(settings, FreeRDP_SmartcardPrivateKey);
808
0
  const char* certPEM = freerdp_settings_get_string(settings, FreeRDP_SmartcardCertificate);
809
0
  if (!privKeyPEM)
810
0
  {
811
0
    WLog_ERR(TAG, "Invalid smartcard private key PEM, aborting");
812
0
    goto out_error;
813
0
  }
814
0
  if (!certPEM)
815
0
  {
816
0
    WLog_ERR(TAG, "Invalid smartcard certificate PEM, aborting");
817
0
    goto out_error;
818
0
  }
819
820
0
  cert_list = (SmartcardCertInfo**)calloc(1, sizeof(SmartcardCertInfo*));
821
0
  if (!cert_list)
822
0
    goto out_error;
823
824
0
  {
825
0
    SmartcardCertInfo* cert = smartcardCertInfo_New(privKeyPEM, certPEM);
826
0
    if (!cert)
827
0
      goto out_error;
828
0
    cert_list[0] = cert;
829
0
  }
830
831
0
  rc = TRUE;
832
0
  *scCerts = cert_list;
833
0
  *retCount = 1;
834
835
0
out_error:
836
0
  if (!rc)
837
0
    smartcardCertList_Free(cert_list, 1);
838
0
  return rc;
839
0
}
840
841
BOOL smartcard_enumerateCerts(const rdpSettings* settings, SmartcardCertInfo*** scCerts,
842
                              size_t* retCount, BOOL gateway)
843
0
{
844
0
  BOOL ret = 0;
845
0
  LPWSTR csp = nullptr;
846
0
  const char* ReaderName = freerdp_settings_get_string(settings, FreeRDP_ReaderName);
847
0
  const char* CspName = freerdp_settings_get_string(settings, FreeRDP_CspName);
848
0
  const char* Username = nullptr;
849
0
  const char* Domain = nullptr;
850
851
0
  if (gateway)
852
0
  {
853
0
    Username = freerdp_settings_get_string(settings, FreeRDP_GatewayUsername);
854
0
    Domain = freerdp_settings_get_string(settings, FreeRDP_GatewayDomain);
855
0
  }
856
0
  else
857
0
  {
858
0
    Username = freerdp_settings_get_string(settings, FreeRDP_Username);
859
0
    Domain = freerdp_settings_get_string(settings, FreeRDP_Domain);
860
0
  }
861
862
0
  WINPR_ASSERT(settings);
863
0
  WINPR_ASSERT(scCerts);
864
0
  WINPR_ASSERT(retCount);
865
866
0
  if (Domain && !strlen(Domain))
867
0
    Domain = nullptr;
868
869
0
  if (freerdp_settings_get_bool(settings, FreeRDP_SmartcardEmulation))
870
0
    return smartcard_sw_enumerateCerts(settings, scCerts, retCount);
871
872
0
  if (CspName && (!(csp = ConvertUtf8ToWCharAlloc(CspName, nullptr))))
873
0
  {
874
0
    WLog_ERR(TAG, "error while converting CSP to WCHAR");
875
0
    return FALSE;
876
0
  }
877
878
0
  ret =
879
0
      smartcard_hw_enumerateCerts(settings, csp, ReaderName, Username, Domain, scCerts, retCount);
880
0
  free(csp);
881
0
  return ret;
882
0
}
883
884
static BOOL set_settings_from_smartcard(rdpSettings* settings, FreeRDP_Settings_Keys_String id,
885
                                        const char* value)
886
0
{
887
0
  WINPR_ASSERT(settings);
888
889
0
  if (!freerdp_settings_get_string(settings, id) && value)
890
0
    if (!freerdp_settings_set_string(settings, id, value))
891
0
      return FALSE;
892
893
0
  return TRUE;
894
0
}
895
896
BOOL smartcard_getCert(const rdpContext* context, SmartcardCertInfo** cert, BOOL gateway)
897
0
{
898
0
  WINPR_ASSERT(context);
899
900
0
  const freerdp* instance = context->instance;
901
0
  rdpSettings* settings = context->settings;
902
0
  SmartcardCertInfo** cert_list = nullptr;
903
0
  size_t count = 0;
904
905
0
  WINPR_ASSERT(instance);
906
0
  WINPR_ASSERT(settings);
907
908
0
  if (!smartcard_enumerateCerts(settings, &cert_list, &count, gateway))
909
0
    return FALSE;
910
911
0
  if (count < 1)
912
0
  {
913
0
    WLog_ERR(TAG, "no suitable smartcard certificates were found");
914
0
    return FALSE;
915
0
  }
916
917
0
  if (count > UINT32_MAX)
918
0
  {
919
0
    WLog_ERR(TAG, "smartcard certificate count %" PRIuz " exceeds UINT32_MAX", count);
920
0
    return FALSE;
921
0
  }
922
923
0
  if (count > 1)
924
0
  {
925
0
    DWORD index = 0;
926
927
0
    if (!instance->ChooseSmartcard ||
928
0
        !instance->ChooseSmartcard(context->instance, cert_list, (UINT32)count, &index,
929
0
                                   gateway))
930
0
    {
931
0
      WLog_ERR(TAG, "more than one suitable smartcard certificate was found");
932
0
      smartcardCertList_Free(cert_list, count);
933
0
      return FALSE;
934
0
    }
935
0
    *cert = cert_list[index];
936
937
0
    for (DWORD i = 0; i < index; i++)
938
0
      smartcardCertInfo_Free(cert_list[i]);
939
0
    for (DWORD i = index + 1; i < count; i++)
940
0
      smartcardCertInfo_Free(cert_list[i]);
941
0
  }
942
0
  else
943
0
    *cert = cert_list[0];
944
945
0
  FreeRDP_Settings_Keys_String username_setting =
946
0
      gateway ? FreeRDP_GatewayUsername : FreeRDP_Username;
947
0
  FreeRDP_Settings_Keys_String domain_setting = gateway ? FreeRDP_GatewayDomain : FreeRDP_Domain;
948
949
0
  free((void*)cert_list);
950
951
0
  if (!set_settings_from_smartcard(settings, username_setting, (*cert)->userHint) ||
952
0
      !set_settings_from_smartcard(settings, domain_setting, (*cert)->domainHint))
953
0
  {
954
0
    WLog_ERR(TAG, "unable to set settings from smartcard!");
955
0
    smartcardCertInfo_Free(*cert);
956
0
    return FALSE;
957
0
  }
958
959
0
  return TRUE;
960
0
}