FreeRDP
Loading...
Searching...
No Matches
smartcardlogon.c
1
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
40struct SmartcardKeyInfo_st
41{
42 char* certPath;
43 char* keyPath;
44};
45
46static void delete_file(char* path)
47{
48 if (!path)
49 return;
50
51 /* Overwrite data in files before deletion */
52 {
53 FILE* fp = winpr_fopen(path, "r+");
54 if (fp)
55 {
56 const char buffer[8192] = WINPR_C_ARRAY_INIT;
57 INT64 size = 0;
58 int rs = _fseeki64(fp, 0, SEEK_END);
59 if (rs == 0)
60 size = _ftelli64(fp);
61 if (_fseeki64(fp, 0, SEEK_SET) == 0)
62 {
63 for (INT64 x = 0; x < size; x += sizeof(buffer))
64 {
65 const size_t dnmemb = (size_t)(size - x);
66 const size_t nmemb = MIN(sizeof(buffer), dnmemb);
67 const size_t count = fwrite(buffer, nmemb, 1, fp);
68 if (count != 1)
69 break;
70 }
71 }
72
73 (void)fclose(fp);
74 }
75 }
76
77 winpr_DeleteFile(path);
78 free(path);
79}
80
81static void smartcardKeyInfo_Free(SmartcardKeyInfo* key_info)
82{
83 if (!key_info)
84 return;
85
86 delete_file(key_info->certPath);
87 delete_file(key_info->keyPath);
88
89 free(key_info);
90}
91
92void smartcardCertInfo_Free(SmartcardCertInfo* scCert)
93{
94 if (!scCert)
95 return;
96
97 free(scCert->csp);
98 free(scCert->reader);
99 freerdp_certificate_free(scCert->certificate);
100 free(scCert->pkinitArgs);
101 free(scCert->keyName);
102 free(scCert->containerName);
103 free(scCert->upn);
104 free(scCert->userHint);
105 free(scCert->domainHint);
106 free(scCert->subject);
107 free(scCert->issuer);
108 smartcardKeyInfo_Free(scCert->key_info);
109
110 free(scCert);
111}
112
113void smartcardCertList_Free(SmartcardCertInfo** pscCert, size_t count)
114{
115 if (!pscCert)
116 return;
117
118 for (size_t i = 0; i < count; i++)
119 {
120 SmartcardCertInfo* cert = pscCert[i];
121 smartcardCertInfo_Free(cert);
122 }
123
124 free((void*)pscCert);
125}
126
127static BOOL add_cert_to_list(SmartcardCertInfo*** certInfoList, size_t* count,
128 SmartcardCertInfo* certInfo)
129{
130 size_t curCount = *count;
131 SmartcardCertInfo** curInfoList = *certInfoList;
132
133 /* Check if the certificate is already in the list */
134 for (size_t i = 0; i < curCount; ++i)
135 {
136 if (_wcscmp(curInfoList[i]->containerName, certInfo->containerName) == 0)
137 {
138 smartcardCertInfo_Free(certInfo);
139 return TRUE;
140 }
141 }
142
143 {
144 SmartcardCertInfo** tmpInfoList = (SmartcardCertInfo**)realloc(
145 (void*)curInfoList, sizeof(SmartcardCertInfo*) * (curCount + 1));
146 if (!tmpInfoList)
147 {
148 WLog_ERR(TAG, "unable to reallocate certs");
149 return FALSE;
150 }
151 curInfoList = tmpInfoList;
152 }
153
154 curInfoList[curCount++] = certInfo;
155 *certInfoList = curInfoList;
156 *count = curCount;
157 return TRUE;
158}
159
160static BOOL treat_sc_cert(SmartcardCertInfo* scCert)
161{
162 WINPR_ASSERT(scCert);
163
164 scCert->upn = freerdp_certificate_get_upn(scCert->certificate);
165 if (!scCert->upn)
166 {
167 WLog_DBG(TAG, "%s has no UPN, trying emailAddress", scCert->keyName);
168 scCert->upn = freerdp_certificate_get_email(scCert->certificate);
169 }
170
171 if (scCert->upn)
172 {
173 size_t userLen = 0;
174 const char* atPos = strchr(scCert->upn, '@');
175
176 if (!atPos)
177 {
178 WLog_ERR(TAG, "invalid UPN, for key %s (no @)", scCert->keyName);
179 return FALSE;
180 }
181
182 userLen = (size_t)(atPos - scCert->upn);
183 scCert->userHint = malloc(userLen + 1);
184 scCert->domainHint = _strdup(atPos + 1);
185
186 if (!scCert->userHint || !scCert->domainHint)
187 {
188 WLog_ERR(TAG, "error allocating userHint or domainHint, for key %s", scCert->keyName);
189 return FALSE;
190 }
191
192 memcpy(scCert->userHint, scCert->upn, userLen);
193 scCert->userHint[userLen] = 0;
194 }
195
196 scCert->subject = freerdp_certificate_get_subject(scCert->certificate);
197 scCert->issuer = freerdp_certificate_get_issuer(scCert->certificate);
198 return TRUE;
199}
200
201static BOOL set_info_certificate(SmartcardCertInfo* cert, BYTE* certBytes, DWORD cbCertBytes,
202 const char* userFilter, const char* domainFilter)
203{
204 if (!winpr_Digest(WINPR_MD_SHA1, certBytes, cbCertBytes, cert->sha1Hash,
205 sizeof(cert->sha1Hash)))
206 {
207 WLog_ERR(TAG, "unable to compute certificate sha1 for key %s", cert->keyName);
208 return FALSE;
209 }
210
211 cert->certificate = freerdp_certificate_new_from_der(certBytes, cbCertBytes);
212 if (!cert->certificate)
213 {
214 WLog_ERR(TAG, "unable to parse X509 certificate for key %s", cert->keyName);
215 return FALSE;
216 }
217
218 if (!freerdp_certificate_check_eku(cert->certificate, NID_ms_smartcard_login))
219 {
220 WLog_DBG(TAG, "discarding certificate without Smartcard Login EKU for key %s",
221 cert->keyName);
222 return FALSE;
223 }
224
225 if (!treat_sc_cert(cert))
226 {
227 WLog_DBG(TAG, "error treating cert");
228 return FALSE;
229 }
230
231 if (userFilter && (!cert->upn || (strcmp(cert->upn, userFilter) != 0)))
232 {
233 if (cert->userHint && strcmp(cert->userHint, userFilter) != 0)
234 {
235 WLog_DBG(TAG, "discarding non matching cert by user %s@%s", cert->userHint,
236 cert->domainHint);
237 return FALSE;
238 }
239 }
240
241 if (domainFilter && cert->domainHint && strcmp(cert->domainHint, domainFilter) != 0)
242 {
243 WLog_DBG(TAG, "discarding non matching cert by domain(%s) %s@%s", domainFilter,
244 cert->userHint, cert->domainHint);
245 return FALSE;
246 }
247
248 return TRUE;
249}
250
251#ifndef _WIN32
252static BOOL build_pkinit_args(NCRYPT_PROV_HANDLE provider, SmartcardCertInfo* scCert)
253{
254 /* pkinit args only under windows
255 * PKCS11:module_name=opensc-pkcs11.so
256 */
257 const char* pkModule = winpr_NCryptGetModulePath(provider);
258 size_t size = 0;
259
260 return (winpr_asprintf(&scCert->pkinitArgs, &size, "PKCS11:module_name=%s:slotid=%" PRIu16,
261 pkModule, (UINT16)scCert->slotId) > 0);
262}
263#endif /* _WIN32 */
264
265#ifdef _WIN32
266static 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
371out:
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
384static 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{
389 BOOL ret = FALSE;
390 NCryptKeyName* keyName = nullptr;
391 PVOID enumState = nullptr;
392 SmartcardCertInfo** cert_list = *pcerts;
393 size_t count = *pcount;
394
395 while (NCryptEnumKeys(provider, scope, &keyName, &enumState, NCRYPT_SILENT_FLAG) ==
396 ERROR_SUCCESS)
397 {
398 NCRYPT_KEY_HANDLE phKey = 0;
399 PBYTE certBytes = nullptr;
400 DWORD dwFlags = NCRYPT_SILENT_FLAG;
401 DWORD cbOutput = 0;
402 SmartcardCertInfo* cert = nullptr;
403 BOOL haveError = TRUE;
404 SECURITY_STATUS status = 0;
405
406 cert = calloc(1, sizeof(SmartcardCertInfo));
407 if (!cert)
408 goto out;
409
410 cert->keyName = ConvertWCharToUtf8Alloc(keyName->pszName, nullptr);
411 if (!cert->keyName)
412 goto endofloop;
413
414 WLog_DBG(TAG, "opening key %s", cert->keyName);
415
416 status =
417 NCryptOpenKey(provider, &phKey, keyName->pszName, keyName->dwLegacyKeySpec, dwFlags);
418 if (status != ERROR_SUCCESS)
419 {
420 WLog_DBG(TAG,
421 "unable to NCryptOpenKey(dwLegacyKeySpec=0x%08" PRIx32 " dwFlags=0x%08" PRIx32
422 "), status=%s, skipping",
423 keyName->dwLegacyKeySpec, keyName->dwFlags,
424 winpr_NCryptSecurityStatusError(status));
425 goto endofloop;
426 }
427
428 cert->csp = _wcsdup(csp);
429 if (!cert->csp)
430 goto endofloop;
431
432#ifndef _WIN32
433 status = NCryptGetProperty(phKey, NCRYPT_WINPR_SLOTID, (PBYTE)&cert->slotId, 4, &cbOutput,
434 dwFlags);
435 if (status != ERROR_SUCCESS)
436 {
437 WLog_ERR(TAG, "unable to retrieve slotId for key %s, status=%s", cert->keyName,
438 winpr_NCryptSecurityStatusError(status));
439 goto endofloop;
440 }
441#endif /* _WIN32 */
442
443 /* ====== retrieve key's reader ====== */
444 cbOutput = 0;
445 status = NCryptGetProperty(phKey, NCRYPT_READER_PROPERTY, nullptr, 0, &cbOutput, dwFlags);
446 if (status != ERROR_SUCCESS)
447 {
448 WLog_DBG(TAG, "unable to retrieve reader's name length for key %s", cert->keyName);
449 goto endofloop;
450 }
451
452 cert->reader = calloc(1, cbOutput + 2);
453 if (!cert->reader)
454 {
455 WLog_ERR(TAG, "unable to allocate reader's name for key %s", cert->keyName);
456 goto endofloop;
457 }
458
459 status = NCryptGetProperty(phKey, NCRYPT_READER_PROPERTY, (PBYTE)cert->reader, cbOutput + 2,
460 &cbOutput, dwFlags);
461 if (status != ERROR_SUCCESS)
462 {
463 WLog_ERR(TAG, "unable to retrieve reader's name for key %s", cert->keyName);
464 goto endofloop;
465 }
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 cbOutput = 0;
470 status = NCryptGetProperty(phKey, NCRYPT_NAME_PROPERTY, nullptr, 0, &cbOutput, dwFlags);
471 if (status == ERROR_SUCCESS)
472 {
473 cert->containerName = calloc(1, cbOutput + sizeof(WCHAR));
474 if (!cert->containerName)
475 {
476 WLog_ERR(TAG, "unable to allocate key container name for key %s", cert->keyName);
477 goto endofloop;
478 }
479
480 status = NCryptGetProperty(phKey, NCRYPT_NAME_PROPERTY, (BYTE*)cert->containerName,
481 cbOutput, &cbOutput, dwFlags);
482 }
483
484 if (status != ERROR_SUCCESS)
485 {
486 WLog_ERR(TAG, "unable to retrieve key container name for key %s", cert->keyName);
487 goto endofloop;
488 }
489
490 /* ========= retrieve the certificate ===============*/
491 cbOutput = 0;
492 status =
493 NCryptGetProperty(phKey, NCRYPT_CERTIFICATE_PROPERTY, nullptr, 0, &cbOutput, dwFlags);
494 if (status != ERROR_SUCCESS)
495 {
496 /* can happen that key don't have certificates */
497 WLog_DBG(TAG, "unable to retrieve certificate property len, status=%s, skipping",
498 winpr_NCryptSecurityStatusError(status));
499 goto endofloop;
500 }
501
502 certBytes = calloc(1, cbOutput);
503 if (!certBytes)
504 {
505 WLog_ERR(TAG, "unable to allocate %" PRIu32 " certBytes for key %s", cbOutput,
506 cert->keyName);
507 goto endofloop;
508 }
509
510 status = NCryptGetProperty(phKey, NCRYPT_CERTIFICATE_PROPERTY, certBytes, cbOutput,
511 &cbOutput, dwFlags);
512 if (status != ERROR_SUCCESS)
513 {
514 WLog_ERR(TAG, "unable to retrieve certificate for key %s", cert->keyName);
515 goto endofloop;
516 }
517
518 if (!set_info_certificate(cert, certBytes, cbOutput, userFilter, domainFilter))
519 goto endofloop;
520
521#ifndef _WIN32
522 if (!build_pkinit_args(provider, cert))
523 {
524 WLog_ERR(TAG, "error build pkinit args");
525 goto endofloop;
526 }
527#endif
528 haveError = FALSE;
529
530 endofloop:
531 free(certBytes);
532 NCryptFreeBuffer(keyName);
533 if (phKey)
534 NCryptFreeObject((NCRYPT_HANDLE)phKey);
535
536 if (haveError)
537 smartcardCertInfo_Free(cert);
538 else
539 {
540 if (!add_cert_to_list(&cert_list, &count, cert))
541 goto out;
542 }
543 }
544
545 ret = TRUE;
546out:
547 if (count == 0)
548 {
549 char cspa[128] = WINPR_C_ARRAY_INIT;
550
551 (void)ConvertWCharToUtf8(csp, cspa, sizeof(cspa));
552 char scopea[128] = WINPR_C_ARRAY_INIT;
553 (void)ConvertWCharToUtf8(scope, scopea, sizeof(scopea));
554 WLog_WARN(TAG, "%s [%s] no certificates found", cspa, scopea);
555 }
556 *pcount = count;
557 *pcerts = cert_list;
558 NCryptFreeBuffer(enumState);
559 return ret;
560}
561
562static 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{
567 BOOL ret = FALSE;
568 LPWSTR scope = nullptr;
569 NCRYPT_PROV_HANDLE provider = 0;
570 SECURITY_STATUS status = 0;
571 size_t count = 0;
572 SmartcardCertInfo** cert_list = nullptr;
573 const char* Pkcs11Module = freerdp_settings_get_string(settings, FreeRDP_Pkcs11Module);
574
575 WINPR_ASSERT(scCerts);
576 WINPR_ASSERT(retCount);
577
578 if (reader)
579 {
580 size_t readerSz = strlen(reader);
581 char* scopeStr = malloc(4 + readerSz + 1 + 1);
582 if (!scopeStr)
583 goto out;
584
585 (void)_snprintf(scopeStr, readerSz + 6, "\\\\.\\%s\\", reader);
586 scope = ConvertUtf8NToWCharAlloc(scopeStr, readerSz + 6, nullptr);
587 free(scopeStr);
588
589 if (!scope)
590 goto out;
591 }
592
593 if (Pkcs11Module)
594 {
595 /* load a unique CSP by pkcs11 module path */
596 LPCSTR paths[] = { Pkcs11Module, nullptr };
597
598 if (!csp)
599 csp = MS_SCARD_PROV;
600
601 status = winpr_NCryptOpenStorageProviderEx(&provider, csp, 0, paths);
602 if (status != ERROR_SUCCESS)
603 {
604 WLog_ERR(TAG, "unable to open provider given by pkcs11 module");
605 goto out;
606 }
607
608 status = list_provider_keys(settings, provider, csp, scope, userFilter, domainFilter,
609 &cert_list, &count);
610 NCryptFreeObject((NCRYPT_HANDLE)provider);
611 if (!status)
612 {
613 WLog_ERR(TAG, "error listing keys from CSP loaded from %s", Pkcs11Module);
614 goto out;
615 }
616 }
617 else
618 {
619 NCryptProviderName* names = nullptr;
620 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 status = NCryptEnumStorageProviders(&nproviders, &names, NCRYPT_SILENT_FLAG);
659 if (status != ERROR_SUCCESS)
660 {
661 WLog_ERR(TAG, "error listing providers");
662 goto out;
663 }
664
665 for (DWORD i = 0; i < nproviders; i++)
666 {
667 char providerNameStr[256] = WINPR_C_ARRAY_INIT;
668 const NCryptProviderName* name = &names[i];
669
670 if (ConvertWCharToUtf8(name->pszName, providerNameStr, ARRAYSIZE(providerNameStr)) < 0)
671 {
672 (void)_snprintf(providerNameStr, sizeof(providerNameStr), "<unknown>");
673 WLog_ERR(TAG, "unable to convert provider name to char*, will show it as '%s'",
674 providerNameStr);
675 }
676
677 WLog_DBG(TAG, "exploring CSP '%s'", providerNameStr);
678 if (csp && _wcscmp(name->pszName, csp) != 0)
679 {
680 WLog_DBG(TAG, "CSP '%s' filtered out", providerNameStr);
681 continue;
682 }
683
684 status = NCryptOpenStorageProvider(&provider, name->pszName, 0);
685 if (status != ERROR_SUCCESS)
686 continue;
687
688 if (!list_provider_keys(settings, provider, name->pszName, scope, userFilter,
689 domainFilter, &cert_list, &count))
690 WLog_INFO(TAG, "error when retrieving keys in CSP '%s'", providerNameStr);
691
692 NCryptFreeObject((NCRYPT_HANDLE)provider);
693 }
694
695 NCryptFreeBuffer(names);
696 }
697
698 *scCerts = cert_list;
699 *retCount = count;
700 ret = TRUE;
701
702out:
703 if (!ret)
704 smartcardCertList_Free(cert_list, count);
705 free(scope);
706 return ret;
707}
708
709static char* create_temporary_file(void)
710{
711 BYTE buffer[32] = WINPR_C_ARRAY_INIT;
712 char* path = nullptr;
713
714 if (winpr_RAND(buffer, sizeof(buffer)) < 0)
715 return nullptr;
716
717 char* hex = winpr_BinToHexString(buffer, sizeof(buffer), FALSE);
718 if (hex)
719 path = GetKnownSubPath(KNOWN_PATH_TEMP, hex);
720 free(hex);
721 return path;
722}
723
724static SmartcardCertInfo* smartcardCertInfo_New(const char* privKeyPEM, const char* certPEM)
725{
726 size_t size = 0;
727
728 WINPR_ASSERT(privKeyPEM);
729 WINPR_ASSERT(certPEM);
730
731 SmartcardCertInfo* cert = calloc(1, sizeof(SmartcardCertInfo));
732 if (!cert)
733 goto fail;
734
735 {
736 SmartcardKeyInfo* info = cert->key_info = calloc(1, sizeof(SmartcardKeyInfo));
737 if (!info)
738 goto fail;
739
740 cert->certificate = freerdp_certificate_new_from_pem(certPEM);
741 if (!cert->certificate)
742 {
743 WLog_ERR(TAG, "unable to read smartcard certificate");
744 goto fail;
745 }
746
747 if (!treat_sc_cert(cert))
748 {
749 WLog_ERR(TAG, "unable to treat smartcard certificate");
750 goto fail;
751 }
752
753 {
754 char* str = nullptr;
755 size_t len = 0;
756 (void)winpr_asprintf(&str, &len, "%s Emulator", freerdp_getApplicationDetailsString());
757 if (str)
758 cert->reader = ConvertUtf8NToWCharAlloc(str, len, nullptr);
759 free(str);
760 }
761 if (!cert->reader)
762 goto fail;
763
764 cert->containerName = ConvertUtf8ToWCharAlloc("Private Key 00", nullptr);
765 if (!cert->containerName)
766 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 info->keyPath = create_temporary_file();
774 WLog_DBG(TAG, "writing PKINIT key to %s", info->keyPath);
775 if (!crypto_write_pem(info->keyPath, privKeyPEM, strlen(privKeyPEM)))
776 goto fail;
777
778 info->certPath = create_temporary_file();
779 WLog_DBG(TAG, "writing PKINIT cert to %s", info->certPath);
780 if (!crypto_write_pem(info->certPath, certPEM, strlen(certPEM)))
781 goto fail;
782
783 {
784 const int res = winpr_asprintf(&cert->pkinitArgs, &size, "FILE:%s,%s", info->certPath,
785 info->keyPath);
786 if (res <= 0)
787 goto fail;
788 }
789 }
790
791 return cert;
792fail:
793 smartcardCertInfo_Free(cert);
794 return nullptr;
795}
796
797static BOOL smartcard_sw_enumerateCerts(const rdpSettings* settings, SmartcardCertInfo*** scCerts,
798 size_t* retCount)
799{
800 BOOL rc = FALSE;
801 SmartcardCertInfo** cert_list = nullptr;
802
803 WINPR_ASSERT(settings);
804 WINPR_ASSERT(scCerts);
805 WINPR_ASSERT(retCount);
806
807 const char* privKeyPEM = freerdp_settings_get_string(settings, FreeRDP_SmartcardPrivateKey);
808 const char* certPEM = freerdp_settings_get_string(settings, FreeRDP_SmartcardCertificate);
809 if (!privKeyPEM)
810 {
811 WLog_ERR(TAG, "Invalid smartcard private key PEM, aborting");
812 goto out_error;
813 }
814 if (!certPEM)
815 {
816 WLog_ERR(TAG, "Invalid smartcard certificate PEM, aborting");
817 goto out_error;
818 }
819
820 cert_list = (SmartcardCertInfo**)calloc(1, sizeof(SmartcardCertInfo*));
821 if (!cert_list)
822 goto out_error;
823
824 {
825 SmartcardCertInfo* cert = smartcardCertInfo_New(privKeyPEM, certPEM);
826 if (!cert)
827 goto out_error;
828 cert_list[0] = cert;
829 }
830
831 rc = TRUE;
832 *scCerts = cert_list;
833 *retCount = 1;
834
835out_error:
836 if (!rc)
837 smartcardCertList_Free(cert_list, 1);
838 return rc;
839}
840
841BOOL smartcard_enumerateCerts(const rdpSettings* settings, SmartcardCertInfo*** scCerts,
842 size_t* retCount, BOOL gateway)
843{
844 BOOL ret = 0;
845 LPWSTR csp = nullptr;
846 const char* ReaderName = freerdp_settings_get_string(settings, FreeRDP_ReaderName);
847 const char* CspName = freerdp_settings_get_string(settings, FreeRDP_CspName);
848 const char* Username = nullptr;
849 const char* Domain = nullptr;
850
851 if (gateway)
852 {
853 Username = freerdp_settings_get_string(settings, FreeRDP_GatewayUsername);
854 Domain = freerdp_settings_get_string(settings, FreeRDP_GatewayDomain);
855 }
856 else
857 {
858 Username = freerdp_settings_get_string(settings, FreeRDP_Username);
859 Domain = freerdp_settings_get_string(settings, FreeRDP_Domain);
860 }
861
862 WINPR_ASSERT(settings);
863 WINPR_ASSERT(scCerts);
864 WINPR_ASSERT(retCount);
865
866 if (Domain && !strlen(Domain))
867 Domain = nullptr;
868
869 if (freerdp_settings_get_bool(settings, FreeRDP_SmartcardEmulation))
870 return smartcard_sw_enumerateCerts(settings, scCerts, retCount);
871
872 if (CspName && (!(csp = ConvertUtf8ToWCharAlloc(CspName, nullptr))))
873 {
874 WLog_ERR(TAG, "error while converting CSP to WCHAR");
875 return FALSE;
876 }
877
878 ret =
879 smartcard_hw_enumerateCerts(settings, csp, ReaderName, Username, Domain, scCerts, retCount);
880 free(csp);
881 return ret;
882}
883
884static BOOL set_settings_from_smartcard(rdpSettings* settings, FreeRDP_Settings_Keys_String id,
885 const char* value)
886{
887 WINPR_ASSERT(settings);
888
889 if (!freerdp_settings_get_string(settings, id) && value)
890 if (!freerdp_settings_set_string(settings, id, value))
891 return FALSE;
892
893 return TRUE;
894}
895
896BOOL smartcard_getCert(const rdpContext* context, SmartcardCertInfo** cert, BOOL gateway)
897{
898 WINPR_ASSERT(context);
899
900 const freerdp* instance = context->instance;
901 rdpSettings* settings = context->settings;
902 SmartcardCertInfo** cert_list = nullptr;
903 size_t count = 0;
904
905 WINPR_ASSERT(instance);
906 WINPR_ASSERT(settings);
907
908 if (!smartcard_enumerateCerts(settings, &cert_list, &count, gateway))
909 return FALSE;
910
911 if (count < 1)
912 {
913 WLog_ERR(TAG, "no suitable smartcard certificates were found");
914 return FALSE;
915 }
916
917 if (count > UINT32_MAX)
918 {
919 WLog_ERR(TAG, "smartcard certificate count %" PRIuz " exceeds UINT32_MAX", count);
920 return FALSE;
921 }
922
923 if (count > 1)
924 {
925 DWORD index = 0;
926
927 if (!instance->ChooseSmartcard ||
928 !instance->ChooseSmartcard(context->instance, cert_list, (UINT32)count, &index,
929 gateway))
930 {
931 WLog_ERR(TAG, "more than one suitable smartcard certificate was found");
932 smartcardCertList_Free(cert_list, count);
933 return FALSE;
934 }
935 *cert = cert_list[index];
936
937 for (DWORD i = 0; i < index; i++)
938 smartcardCertInfo_Free(cert_list[i]);
939 for (DWORD i = index + 1; i < count; i++)
940 smartcardCertInfo_Free(cert_list[i]);
941 }
942 else
943 *cert = cert_list[0];
944
945 FreeRDP_Settings_Keys_String username_setting =
946 gateway ? FreeRDP_GatewayUsername : FreeRDP_Username;
947 FreeRDP_Settings_Keys_String domain_setting = gateway ? FreeRDP_GatewayDomain : FreeRDP_Domain;
948
949 free((void*)cert_list);
950
951 if (!set_settings_from_smartcard(settings, username_setting, (*cert)->userHint) ||
952 !set_settings_from_smartcard(settings, domain_setting, (*cert)->domainHint))
953 {
954 WLog_ERR(TAG, "unable to set settings from smartcard!");
955 smartcardCertInfo_Free(*cert);
956 return FALSE;
957 }
958
959 return TRUE;
960}
WINPR_ATTR_NODISCARD FREERDP_API const char * freerdp_settings_get_string(const rdpSettings *settings, FreeRDP_Settings_Keys_String id)
Returns a immutable string settings value.
WINPR_ATTR_NODISCARD FREERDP_API BOOL freerdp_settings_get_bool(const rdpSettings *settings, FreeRDP_Settings_Keys_Bool id)
Returns a boolean settings value.
FREERDP_API BOOL freerdp_settings_set_string(rdpSettings *settings, FreeRDP_Settings_Keys_String id, const char *val)
Sets a string settings value. The param is copied.
a key name descriptor
a provider name descriptor