FreeRDP
Loading...
Searching...
No Matches
credssp_auth.c
1
21
22#include <ctype.h>
23
24#include <freerdp/config.h>
25#include "settings.h"
26#include <freerdp/build-config.h>
27#include <freerdp/peer.h>
28#include <freerdp/utils/helpers.h>
29#include <winpr/config-readers.h>
30
31#include <winpr/crt.h>
32#include <winpr/wtypes.h>
33#include <winpr/assert.h>
34#include <winpr/library.h>
35#if !defined(WITHOUT_FREERDP_3x_DEPRECATED)
36#include <winpr/registry.h>
37#endif
38#include <winpr/sspi.h>
39
40#include <freerdp/log.h>
41
42#include "utils.h"
43#include "credssp_auth.h"
44
45#define TAG FREERDP_TAG("core.auth")
46
47#if !defined(WITHOUT_FREERDP_3x_DEPRECATED)
48#define SERVER_KEY "Software\\%s\\Server"
49#endif
50
51enum AUTH_STATE
52{
53 AUTH_STATE_INITIAL,
54 AUTH_STATE_CREDS,
55 AUTH_STATE_IN_PROGRESS,
56 AUTH_STATE_FINAL
57};
58
59struct rdp_credssp_auth
60{
61 const rdpContext* rdp_ctx;
62 SecurityFunctionTable* table;
63 SecPkgInfo* info;
64 SEC_WINNT_AUTH_IDENTITY identity;
65 SEC_WINPR_NTLM_SETTINGS_V2* ntlmSettingsV2;
66 SEC_WINPR_KERBEROS_SETTINGS_V2* kerberosSettingsV2;
67 CredHandle credentials;
68 BOOL server;
69 SecPkgContext_Bindings* bindings;
70 TCHAR* spn;
71 WCHAR* package_list;
72 CtxtHandle context;
73 SecBuffer input_buffer;
74 SecBuffer output_buffer;
75 ULONG flags;
76 SecPkgContext_Sizes sizes;
77 SECURITY_STATUS sspi_error;
78 enum AUTH_STATE state;
79 char* pkgNameA;
80};
81
82static const char credssp_config_file_name[] = "credssp.json";
83
84static const char* credssp_auth_state_string(const rdpCredsspAuth* auth)
85{
86 WINPR_ASSERT(auth);
87 switch (auth->state)
88 {
89 case AUTH_STATE_INITIAL:
90 return "AUTH_STATE_INITIAL";
91 case AUTH_STATE_CREDS:
92 return "AUTH_STATE_CREDS";
93 case AUTH_STATE_IN_PROGRESS:
94 return "AUTH_STATE_IN_PROGRESS";
95 case AUTH_STATE_FINAL:
96 return "AUTH_STATE_FINAL";
97 default:
98 return "AUTH_STATE_UNKNOWN";
99 }
100}
101static BOOL parseKerberosDeltat(const char* value, INT32* dest, const char* message);
102static BOOL credssp_auth_setup_identity(rdpCredsspAuth* auth);
103static SecurityFunctionTable* auth_resolve_sspi_table(const rdpSettings* settings);
104
105#define log_status(status, level, ...) \
106 log_status_((status), (level), __FILE__, __func__, __LINE__, __VA_ARGS__)
107
108WINPR_ATTR_FORMAT_ARG(6, 7)
109static BOOL log_status_(SECURITY_STATUS status, DWORD level, const char* file, const char* fkt,
110 size_t line, WINPR_FORMAT_ARG const char* what, ...)
111{
112 static wLog* log = nullptr;
113 if (!log)
114 log = WLog_Get(TAG);
115
116 if (WLog_IsLevelActive(log, level))
117 {
118 char fwhat[128] = WINPR_C_ARRAY_INIT;
119 va_list ap = WINPR_C_ARRAY_INIT;
120 va_start(ap, what);
121 (void)vsnprintf(fwhat, sizeof(fwhat) - 1, what, ap);
122 va_end(ap);
123
124 WLog_PrintTextMessage(log, level, line, file, fkt, "%s status %s [0x%08" PRIx32 "]", fwhat,
125 GetSecurityStatusString(status),
126 WINPR_CXX_COMPAT_CAST(uint32_t, status));
127 }
128
129 return FALSE;
130}
131
132static BOOL credssp_auth_update_name_cache(rdpCredsspAuth* auth, TCHAR* name)
133{
134 WINPR_ASSERT(auth);
135
136 free(auth->pkgNameA);
137 auth->pkgNameA = nullptr;
138 if (name)
139#if defined(UNICODE)
140 auth->pkgNameA = ConvertWCharToUtf8Alloc(name, nullptr);
141#else
142 auth->pkgNameA = _strdup(name);
143#endif
144 return TRUE;
145}
146rdpCredsspAuth* credssp_auth_new(const rdpContext* context)
147{
148 WINPR_ASSERT(context);
149 rdpCredsspAuth* auth = calloc(1, sizeof(rdpCredsspAuth));
150 if (!auth)
151 return nullptr;
152
153 auth->ntlmSettingsV2 = sspi_AllocSecNtlmSettings();
154 if (!auth->ntlmSettingsV2)
155 goto fail;
156
157 auth->kerberosSettingsV2 = sspi_AllocSecKerberosSettings();
158 if (!auth->kerberosSettingsV2)
159 goto fail;
160
161 auth->rdp_ctx = context;
162
163 return auth;
164
165fail:
166 credssp_auth_free(auth);
167 return nullptr;
168}
169
170BOOL credssp_auth_init(rdpCredsspAuth* auth, TCHAR* pkg_name, SecPkgContext_Bindings* bindings)
171{
172 WINPR_ASSERT(auth);
173 WINPR_ASSERT(auth->rdp_ctx);
174
175 const rdpSettings* settings = auth->rdp_ctx->settings;
176 WINPR_ASSERT(settings);
177
178 if (!credssp_auth_update_name_cache(auth, pkg_name))
179 return FALSE;
180
181 auth->table = auth_resolve_sspi_table(settings);
182 if (!auth->table)
183 {
184 WLog_ERR(TAG, "Unable to initialize sspi table");
185 return FALSE;
186 }
187
188 /* Package name will be stored in the info structure */
189 WINPR_ASSERT(auth->table->QuerySecurityPackageInfo);
190 const SECURITY_STATUS status = auth->table->QuerySecurityPackageInfo(pkg_name, &auth->info);
191 if (status != SEC_E_OK)
192 return log_status(status, WLOG_ERROR, "QuerySecurityPackageInfo (%s)",
193 credssp_auth_pkg_name(auth));
194
195 if (!credssp_auth_update_name_cache(auth, auth->info->Name))
196 return FALSE;
197
198 WLog_DBG(TAG, "Using package: %s (cbMaxToken: %u bytes)", credssp_auth_pkg_name(auth),
199 auth->info->cbMaxToken);
200
201 /* Setup common identity settings */
202 if (!credssp_auth_setup_identity(auth))
203 return FALSE;
204
205 auth->bindings = bindings;
206
207 return TRUE;
208}
209
210static BOOL credssp_auth_setup_auth_data(rdpCredsspAuth* auth,
211 const SEC_WINNT_AUTH_IDENTITY* identity,
212 SEC_WINNT_AUTH_IDENTITY_WINPR_V2* pAuthData)
213{
214 WINPR_ASSERT(pAuthData);
215 ZeroMemory(pAuthData, sizeof(SEC_WINNT_AUTH_IDENTITY_WINPR_V2));
216
217 SEC_WINNT_AUTH_IDENTITY_EXW* identityEx = &pAuthData->identity;
218 identityEx->Version = SEC_WINNT_AUTH_IDENTITY_VERSION;
219 identityEx->Length = sizeof(SEC_WINNT_AUTH_IDENTITY_EX);
220 identityEx->User = identity->User;
221 identityEx->UserLength = identity->UserLength;
222 identityEx->Domain = identity->Domain;
223 identityEx->DomainLength = identity->DomainLength;
224 identityEx->Password = identity->Password;
225 identityEx->PasswordLength = identity->PasswordLength;
226 identityEx->Flags = identity->Flags;
227 identityEx->Flags |= SEC_WINNT_AUTH_IDENTITY_UNICODE;
228 identityEx->Flags |= SEC_WINNT_AUTH_IDENTITY_EXTENDED_v2;
229
230 if (auth->package_list)
231 {
232 const size_t len = _wcslen(auth->package_list);
233 if (len > UINT32_MAX)
234 return FALSE;
235
236 identityEx->PackageList = (UINT16*)auth->package_list;
237 identityEx->PackageListLength = (UINT32)len;
238 }
239
240 pAuthData->version = SEC_WINNT_AUTH_IDENTITY_WINPR_V2_REVISION_1;
241 pAuthData->ntlmSettingsV2 = auth->ntlmSettingsV2;
242 WINPR_ASSERT(pAuthData->ntlmSettingsV2);
243
244 pAuthData->kerberosSettingsV2 = auth->kerberosSettingsV2;
245 WINPR_ASSERT(pAuthData->kerberosSettingsV2);
246
247 return TRUE;
248}
249
250static BOOL credssp_auth_client_init_cred_attributes(rdpCredsspAuth* auth)
251{
252 WINPR_ASSERT(auth);
253
254 if (!utils_str_is_empty(auth->kerberosSettingsV2->kdcUrl))
255 {
256 SECURITY_STATUS status = ERROR_INTERNAL_ERROR;
257 SSIZE_T str_size = 0;
258
259 str_size = ConvertUtf8ToWChar(auth->kerberosSettingsV2->kdcUrl, nullptr, 0);
260 if ((str_size <= 0) || (str_size >= UINT16_MAX / 2))
261 return FALSE;
262 str_size++;
263
264 const size_t buffer_size =
265 sizeof(SecPkgCredentials_KdcProxySettingsW) + (size_t)str_size * sizeof(WCHAR);
266 if (buffer_size > UINT32_MAX)
267 return FALSE;
268 SecPkgCredentials_KdcProxySettingsW* secAttr = calloc(1, buffer_size);
269 if (!secAttr)
270 return FALSE;
271
272 secAttr->Version = KDC_PROXY_SETTINGS_V1;
273 secAttr->ProxyServerLength = (UINT16)((size_t)str_size * sizeof(WCHAR));
274 secAttr->ProxyServerOffset = sizeof(SecPkgCredentials_KdcProxySettingsW);
275
276 if (ConvertUtf8ToWChar(auth->kerberosSettingsV2->kdcUrl, (WCHAR*)(secAttr + 1),
277 (size_t)str_size) <= 0)
278 {
279 free(secAttr);
280 return FALSE;
281 }
282
283#ifdef UNICODE
284 if (auth->table->SetCredentialsAttributesW)
285 status = auth->table->SetCredentialsAttributesW(&auth->credentials,
286 SECPKG_CRED_ATTR_KDC_PROXY_SETTINGS,
287 (void*)secAttr, (UINT32)buffer_size);
288 else
289 status = SEC_E_UNSUPPORTED_FUNCTION;
290#else
291 if (auth->table->SetCredentialsAttributesA)
292 status = auth->table->SetCredentialsAttributesA(&auth->credentials,
293 SECPKG_CRED_ATTR_KDC_PROXY_SETTINGS,
294 (void*)secAttr, (UINT32)buffer_size);
295 else
296 status = SEC_E_UNSUPPORTED_FUNCTION;
297#endif
298
299 if (status != SEC_E_OK)
300 {
301 WLog_WARN(TAG, "Explicit Kerberos KDC URL (%s) injection is not supported",
302 auth->kerberosSettingsV2->kdcUrl);
303 }
304
305 free(secAttr);
306 }
307
308 return TRUE;
309}
310
311/* With smartcard logon the password of the identity is the PIN of the card. Kerberos needs it
312 * for PKINIT, but it must never be used as NTLM password: NTLM can not authenticate with a
313 * smartcard and a peer could recover the PIN offline from the NTLM response. */
314static BOOL credssp_auth_client_disable_ntlm(rdpCredsspAuth* auth)
315{
316 WINPR_ASSERT(auth);
317 WINPR_ASSERT(auth->rdp_ctx);
318
319 const rdpSettings* settings = auth->rdp_ctx->settings;
320 WINPR_ASSERT(settings);
321
322 const char* pkg = credssp_auth_pkg_name(auth);
323 if (pkg && (_stricmp(pkg, CREDSSP_AUTH_PKG_NTLM) == 0))
324 {
325 WLog_ERR(TAG, "%s authentication is not supported with smartcard logon", pkg);
326 return FALSE;
327 }
328
329 char* list = nullptr;
330 size_t len = 0;
331 const char* cur = settings->AuthenticationPackageList;
332 const BOOL empty = utils_str_is_empty(cur);
333 if (winpr_asprintf(&list, &len, "%s%s!ntlm", empty ? "" : cur, empty ? "" : ",") < 0)
334 return FALSE;
335
336 free(auth->package_list);
337 auth->package_list = ConvertUtf8ToWCharAlloc(list, nullptr);
338 free(list);
339 return auth->package_list != nullptr;
340}
341
342BOOL credssp_auth_setup_client(rdpCredsspAuth* auth, const char* target_service,
343 const char* target_hostname, const SEC_WINNT_AUTH_IDENTITY* identity,
344 const char* pkinit)
345{
346 void* pAuthData = nullptr;
347 SEC_WINNT_AUTH_IDENTITY_WINPR_V2 winprAuthData = WINPR_C_ARRAY_INIT;
348
349 WINPR_ASSERT(auth);
350 WINPR_ASSERT(auth->table);
351 WINPR_ASSERT(auth->info);
352 WINPR_ASSERT(auth->rdp_ctx);
353 WINPR_ASSERT(auth->rdp_ctx->settings);
354
355 WINPR_ASSERT(auth->state == AUTH_STATE_INITIAL);
356
357 /* Checked here and not in credssp_auth_init as the authentication callbacks might have
358 * changed the logon to smartcard in between */
359 if (auth->rdp_ctx->settings->SmartcardLogon && !credssp_auth_client_disable_ntlm(auth))
360 return FALSE;
361
362 /* Construct the service principal name */
363 if (!credssp_auth_set_spn(auth, target_service, target_hostname))
364 return FALSE;
365
366 if (identity)
367 {
368 credssp_auth_setup_auth_data(auth, identity, &winprAuthData);
369
370 if (pkinit)
371 {
372 if (!sspi_CloneSecSettingsString(&auth->kerberosSettingsV2->pkinitX509Identity, pkinit))
373 {
374 WLog_ERR(TAG, "unable to copy pkinitArgs");
375 return FALSE;
376 }
377 }
378
379 pAuthData = (void*)&winprAuthData;
380 }
381
382 WINPR_ASSERT(auth->table->AcquireCredentialsHandle);
383 const SECURITY_STATUS status = auth->table->AcquireCredentialsHandle(
384 nullptr, auth->info->Name, SECPKG_CRED_OUTBOUND, nullptr, pAuthData, nullptr, nullptr,
385 &auth->credentials, nullptr);
386
387 if (status != SEC_E_OK)
388 return log_status(status, WLOG_ERROR, "AcquireCredentialsHandleA");
389
390 if (!credssp_auth_client_init_cred_attributes(auth))
391 {
392 WLog_ERR(TAG, "Fatal error setting credential attributes");
393 return FALSE;
394 }
395
396 auth->state = AUTH_STATE_CREDS;
397 WLog_DBG(TAG, "Acquired client credentials");
398
399 return TRUE;
400}
401
402BOOL credssp_auth_setup_server(rdpCredsspAuth* auth)
403{
404 void* pAuthData = nullptr;
405 SEC_WINNT_AUTH_IDENTITY_WINPR_V2 winprAuthData = WINPR_C_ARRAY_INIT;
406
407 WINPR_ASSERT(auth);
408 WINPR_ASSERT(auth->table);
409
410 WINPR_ASSERT(auth->state == AUTH_STATE_INITIAL);
411
412 if (auth->ntlmSettingsV2->samFile || auth->ntlmSettingsV2->hashCallback ||
413 auth->kerberosSettingsV2->keytab)
414 {
415 credssp_auth_setup_auth_data(auth, &auth->identity, &winprAuthData);
416 pAuthData = &winprAuthData;
417 }
418
419 WINPR_ASSERT(auth->table->AcquireCredentialsHandle);
420 const SECURITY_STATUS status = auth->table->AcquireCredentialsHandle(
421 nullptr, auth->info->Name, SECPKG_CRED_INBOUND, nullptr, pAuthData, nullptr, nullptr,
422 &auth->credentials, nullptr);
423 if (status != SEC_E_OK)
424 return log_status(status, WLOG_ERROR, "AcquireCredentialsHandleA");
425
426 auth->state = AUTH_STATE_CREDS;
427 WLog_DBG(TAG, "Acquired server credentials");
428
429 auth->server = TRUE;
430
431 return TRUE;
432}
433
434void credssp_auth_set_flags(rdpCredsspAuth* auth, ULONG flags)
435{
436 WINPR_ASSERT(auth);
437 auth->flags = flags;
438}
439
477
478#define query_logged(auth, ulAttribute, pBuffer) \
479 query_logged_((auth), (ulAttribute), (pBuffer), __FILE__, __func__, __LINE__)
480static SECURITY_STATUS query_logged_(rdpCredsspAuth* auth, ULONG ulAttribute, void* pBuffer,
481 const char* file, const char* fkt, size_t line)
482{
483 WINPR_ASSERT(auth);
484 WINPR_ASSERT(auth->table);
485 WINPR_ASSERT(auth->table->QueryContextAttributes);
486
487 SECURITY_STATUS status =
488 auth->table->QueryContextAttributes(&auth->context, ulAttribute, pBuffer);
489 (void)log_status_(status, WLOG_DEBUG, file, fkt, line,
490 "QueryContextAttributes(0x%08" PRIx32 ")", ulAttribute);
491 return status;
492}
493
494int credssp_auth_authenticate(rdpCredsspAuth* auth)
495{
496 SECURITY_STATUS status = ERROR_INTERNAL_ERROR;
497 SecBuffer input_buffers[2] = WINPR_C_ARRAY_INIT;
498 SecBufferDesc input_buffer_desc = { SECBUFFER_VERSION, 1, input_buffers };
499 CtxtHandle* context = nullptr;
500
501 WINPR_ASSERT(auth);
502 WINPR_ASSERT(auth->table);
503
504 SecBufferDesc output_buffer_desc = { SECBUFFER_VERSION, 1, &auth->output_buffer };
505
506 switch (auth->state)
507 {
508 case AUTH_STATE_CREDS:
509 case AUTH_STATE_IN_PROGRESS:
510 break;
511 case AUTH_STATE_INITIAL:
512 case AUTH_STATE_FINAL:
513 WLog_ERR(TAG, "context in invalid state!");
514 return -1;
515 default:
516 break;
517 }
518
519 /* input buffer will be null on first call,
520 * context MUST be nullptr on first call */
521 context = &auth->context;
522 if (!auth->context.dwLower && !auth->context.dwUpper)
523 context = nullptr;
524
525 input_buffers[0] = auth->input_buffer;
526
527 if (auth->bindings)
528 {
529 input_buffer_desc.cBuffers = 2;
530
531 input_buffers[1].BufferType = SECBUFFER_CHANNEL_BINDINGS;
532 input_buffers[1].cbBuffer = auth->bindings->BindingsLength;
533 input_buffers[1].pvBuffer = auth->bindings->Bindings;
534 }
535
536 /* Free previous output buffer (presumably no longer needed) */
537 sspi_SecBufferFree(&auth->output_buffer);
538 auth->output_buffer.BufferType = SECBUFFER_TOKEN;
539 if (!sspi_SecBufferAlloc(&auth->output_buffer, auth->info->cbMaxToken))
540 return -1;
541
542 if (auth->server)
543 {
544 WINPR_ASSERT(auth->table->AcceptSecurityContext);
545 status = auth->table->AcceptSecurityContext(
546 &auth->credentials, context, &input_buffer_desc, auth->flags, SECURITY_NATIVE_DREP,
547 &auth->context, &output_buffer_desc, &auth->flags, nullptr);
548 }
549 else
550 {
551 WINPR_ASSERT(auth->table->InitializeSecurityContext);
552 status = auth->table->InitializeSecurityContext(
553 &auth->credentials, context, auth->spn, auth->flags, 0, SECURITY_NATIVE_DREP,
554 &input_buffer_desc, 0, &auth->context, &output_buffer_desc, &auth->flags, nullptr);
555
556#if !defined(_WIN32)
557 const rdpSettings* settings = auth->rdp_ctx->settings;
558 WINPR_ASSERT(settings);
559 const char* name = freerdp_settings_get_string(settings, FreeRDP_SspiClientHostname);
560 if (name)
561 {
562 const size_t len = strlen(name);
563 if (len > ULONG_MAX)
564 status = SEC_E_INVALID_PARAMETER;
565 else
566 {
567 const SECURITY_STATUS sca = auth->table->SetContextAttributesA(
568 &auth->context, SECPKG_ATTR_AUTH_NTLM_HOSTNAME,
569 WINPR_CAST_CONST_PTR_AWAY(name, char*), WINPR_ASSERTING_INT_CAST(ULONG, len));
570 (void)log_status(sca, WLOG_DEBUG, "SetContextAttributesA(0x%08" PRIx32 ")",
571 SECPKG_ATTR_AUTH_NTLM_HOSTNAME);
572 }
573 }
574#endif
575 }
576
577 if (status == SEC_E_OK)
578 {
579 WLog_DBG(TAG, "Authentication complete (output token size: %" PRIu32 " bytes)",
580 auth->output_buffer.cbBuffer);
581 auth->state = AUTH_STATE_FINAL;
582
583 /* Not terrible if this fails, although encryption functions may run into issues down the
584 * line, still, authentication succeeded */
585 (void)query_logged(auth, SECPKG_ATTR_SIZES, &auth->sizes);
586 WLog_DBG(TAG, "Context sizes: cbMaxSignature=%" PRIu32 ", cbSecurityTrailer=%" PRIu32 "",
587 auth->sizes.cbMaxSignature, auth->sizes.cbSecurityTrailer);
588
589 int rc = 1;
590#if !defined(_WIN32)
591 rdpSettings* settings = auth->rdp_ctx->settings;
592 if (!freerdp_settings_set_string(settings, FreeRDP_SspiClientHostname, nullptr))
593 return -1;
594
595 ULONG len = 0;
596 SECURITY_STATUS qstatus = query_logged(auth, SECPKG_ATTR_AUTH_NTLM_HOSTNAME_LEN, &len);
597
598 if ((qstatus == SEC_E_OK) && (len > 0))
599 {
600 void* WorkstationName = calloc(len + 1, sizeof(WCHAR));
601 if (!WorkstationName)
602 return -1;
603
604 qstatus = query_logged(auth, SECPKG_ATTR_AUTH_NTLM_HOSTNAME, WorkstationName);
605 if (qstatus == SEC_E_OK)
606 {
607#if defined(UNICODE)
608 if (!freerdp_settings_set_string_from_utf16N(settings, FreeRDP_SspiClientHostname,
609 WorkstationName, len))
610 rc = -1;
611#else
612 if (!freerdp_settings_set_string_len(settings, FreeRDP_SspiClientHostname,
613 WorkstationName, len))
614 rc = -1;
615#endif
616 }
617 free(WorkstationName);
618 }
619#endif
620 return rc;
621 }
622 else if (status == SEC_I_CONTINUE_NEEDED)
623 {
624 WLog_DBG(TAG, "Authentication in progress... (output token size: %" PRIu32 ")",
625 auth->output_buffer.cbBuffer);
626 auth->state = AUTH_STATE_IN_PROGRESS;
627 return 0;
628 }
629 else
630 {
631 (void)log_status(status, WLOG_ERROR,
632 auth->server ? "AcceptSecurityContext" : "InitializeSecurityContext");
633 auth->sspi_error = status;
634 return -1;
635 }
636}
637
638/* Plaintext is not modified; Output buffer MUST be freed if encryption succeeds */
639BOOL credssp_auth_encrypt(rdpCredsspAuth* auth, const SecBuffer* plaintext, SecBuffer* ciphertext,
640 size_t* signature_length, ULONG sequence)
641{
642 SECURITY_STATUS status = ERROR_INTERNAL_ERROR;
643 SecBuffer buffers[2] = WINPR_C_ARRAY_INIT;
644 SecBufferDesc buffer_desc = { SECBUFFER_VERSION, 2, buffers };
645 BYTE* buf = nullptr;
646
647 WINPR_ASSERT(auth && auth->table);
648 WINPR_ASSERT(plaintext);
649 WINPR_ASSERT(ciphertext);
650
651 switch (auth->state)
652 {
653 case AUTH_STATE_INITIAL:
654 WLog_ERR(TAG, "Invalid state %s", credssp_auth_state_string(auth));
655 return FALSE;
656 default:
657 break;
658 }
659
660 if (plaintext->cbBuffer > SIZE_MAX - auth->sizes.cbSecurityTrailer)
661 return FALSE;
662 const size_t len = 1ull * plaintext->cbBuffer + auth->sizes.cbSecurityTrailer;
663
664 /* Allocate consecutive memory for ciphertext and signature */
665 buf = calloc(1, len);
666 if (!buf)
667 return FALSE;
668
669 buffers[0].BufferType = SECBUFFER_TOKEN;
670 buffers[0].cbBuffer = auth->sizes.cbSecurityTrailer;
671 buffers[0].pvBuffer = buf;
672
673 buffers[1].BufferType = SECBUFFER_DATA;
674 if (plaintext->BufferType & SECBUFFER_READONLY)
675 buffers[1].BufferType |= SECBUFFER_READONLY;
676 buffers[1].pvBuffer = buf + auth->sizes.cbSecurityTrailer;
677 buffers[1].cbBuffer = plaintext->cbBuffer;
678 CopyMemory(buffers[1].pvBuffer, plaintext->pvBuffer, plaintext->cbBuffer);
679
680 WINPR_ASSERT(auth->table->EncryptMessage);
681 status = auth->table->EncryptMessage(&auth->context, 0, &buffer_desc, sequence);
682 if (status != SEC_E_OK)
683 {
684 free(buf);
685 return log_status(status, WLOG_ERROR, "EncryptMessage");
686 }
687
688 if (buffers[0].cbBuffer < auth->sizes.cbSecurityTrailer)
689 {
690 /* The signature is smaller than cbSecurityTrailer, so shrink the excess in between */
691 MoveMemory(((BYTE*)buffers[0].pvBuffer) + buffers[0].cbBuffer, buffers[1].pvBuffer,
692 buffers[1].cbBuffer);
693 // use reported signature size as new cbSecurityTrailer value for DecryptMessage
694 auth->sizes.cbSecurityTrailer = buffers[0].cbBuffer;
695 }
696
697 ciphertext->cbBuffer = buffers[0].cbBuffer + buffers[1].cbBuffer;
698 ciphertext->pvBuffer = buf;
699
700 if (signature_length)
701 *signature_length = buffers[0].cbBuffer;
702
703 return TRUE;
704}
705
706/* Output buffer MUST be freed if decryption succeeds */
707BOOL credssp_auth_decrypt(rdpCredsspAuth* auth, const SecBuffer* ciphertext, SecBuffer* plaintext,
708 ULONG sequence)
709{
710 SecBuffer buffers[2];
711 SecBufferDesc buffer_desc = { SECBUFFER_VERSION, 2, buffers };
712 ULONG fqop = 0;
713
714 WINPR_ASSERT(auth && auth->table);
715 WINPR_ASSERT(ciphertext);
716 WINPR_ASSERT(plaintext);
717
718 switch (auth->state)
719 {
720 case AUTH_STATE_INITIAL:
721 WLog_ERR(TAG, "Invalid state %s", credssp_auth_state_string(auth));
722 return FALSE;
723 default:
724 break;
725 }
726
727 /* Sanity check: ciphertext must at least have a signature */
728 if (ciphertext->cbBuffer < auth->sizes.cbSecurityTrailer)
729 {
730 WLog_ERR(TAG, "Encrypted message buffer too small");
731 return FALSE;
732 }
733
734 /* Split the input into signature and encrypted data; we assume the signature length is equal to
735 * cbSecurityTrailer */
736 buffers[0].BufferType = SECBUFFER_TOKEN;
737 buffers[0].pvBuffer = ciphertext->pvBuffer;
738 buffers[0].cbBuffer = auth->sizes.cbSecurityTrailer;
739
740 buffers[1].BufferType = SECBUFFER_DATA;
741 if (!sspi_SecBufferAlloc(&buffers[1], ciphertext->cbBuffer - auth->sizes.cbSecurityTrailer))
742 return FALSE;
743 CopyMemory(buffers[1].pvBuffer, (BYTE*)ciphertext->pvBuffer + auth->sizes.cbSecurityTrailer,
744 buffers[1].cbBuffer);
745
746 WINPR_ASSERT(auth->table->DecryptMessage);
747 const SECURITY_STATUS status =
748 auth->table->DecryptMessage(&auth->context, &buffer_desc, sequence, &fqop);
749 if (status != SEC_E_OK)
750 {
751 WLog_ERR(TAG, "DecryptMessage failed with %s [0x%08" PRIx32 "]",
752 GetSecurityStatusString(status), WINPR_CXX_COMPAT_CAST(uint32_t, status));
753 sspi_SecBufferFree(&buffers[1]);
754 return FALSE;
755 }
756
757 *plaintext = buffers[1];
758
759 return TRUE;
760}
761
762BOOL credssp_auth_impersonate(rdpCredsspAuth* auth)
763{
764 WINPR_ASSERT(auth && auth->table);
765
766 WINPR_ASSERT(auth->table->ImpersonateSecurityContext);
767 const SECURITY_STATUS status = auth->table->ImpersonateSecurityContext(&auth->context);
768
769 if (status != SEC_E_OK)
770 {
771 WLog_ERR(TAG, "ImpersonateSecurityContext failed with %s [0x%08" PRIx32 "]",
772 GetSecurityStatusString(status), WINPR_CXX_COMPAT_CAST(uint32_t, status));
773 return FALSE;
774 }
775
776 return TRUE;
777}
778
779BOOL credssp_auth_revert_to_self(rdpCredsspAuth* auth)
780{
781 WINPR_ASSERT(auth && auth->table);
782
783 WINPR_ASSERT(auth->table->RevertSecurityContext);
784 const SECURITY_STATUS status = auth->table->RevertSecurityContext(&auth->context);
785
786 if (status != SEC_E_OK)
787 {
788 WLog_ERR(TAG, "RevertSecurityContext failed with %s [0x%08" PRIx32 "]",
789 GetSecurityStatusString(status), WINPR_CXX_COMPAT_CAST(uint32_t, status));
790 return FALSE;
791 }
792
793 return TRUE;
794}
795
796void credssp_auth_take_input_buffer(rdpCredsspAuth* auth, SecBuffer* buffer)
797{
798 WINPR_ASSERT(auth);
799 WINPR_ASSERT(buffer);
800
801 sspi_SecBufferFree(&auth->input_buffer);
802
803 auth->input_buffer = *buffer;
804 auth->input_buffer.BufferType = SECBUFFER_TOKEN;
805
806 /* Invalidate original, rdpCredsspAuth now has ownership of the buffer */
807 SecBuffer empty = WINPR_C_ARRAY_INIT;
808 *buffer = empty;
809}
810
811const SecBuffer* credssp_auth_get_output_buffer(const rdpCredsspAuth* auth)
812{
813 WINPR_ASSERT(auth);
814 return &auth->output_buffer;
815}
816
817BOOL credssp_auth_have_output_token(rdpCredsspAuth* auth)
818{
819 WINPR_ASSERT(auth);
820 return (auth->output_buffer.cbBuffer != 0);
821}
822
823BOOL credssp_auth_is_complete(const rdpCredsspAuth* auth)
824{
825 WINPR_ASSERT(auth);
826 return auth->state == AUTH_STATE_FINAL;
827}
828
829size_t credssp_auth_trailer_size(const rdpCredsspAuth* auth)
830{
831 WINPR_ASSERT(auth);
832 return auth->sizes.cbSecurityTrailer;
833}
834
835const char* credssp_auth_pkg_name(const rdpCredsspAuth* auth)
836{
837 WINPR_ASSERT(auth && auth->info);
838 return auth->pkgNameA;
839}
840
841INT32 credssp_auth_sspi_error(const rdpCredsspAuth* auth)
842{
843 WINPR_ASSERT(auth);
844 return auth->sspi_error;
845}
846
847void credssp_auth_tableAndContext(rdpCredsspAuth* auth, SecurityFunctionTable** ptable,
848 CtxtHandle* pcontext)
849{
850 WINPR_ASSERT(auth);
851 WINPR_ASSERT(ptable);
852 WINPR_ASSERT(pcontext);
853
854 *ptable = auth->table;
855 *pcontext = auth->context;
856}
857
858void credssp_auth_free(rdpCredsspAuth* auth)
859{
860 if (!auth)
861 return;
862
863 if (auth->table)
864 {
865 switch (auth->state)
866 {
867 case AUTH_STATE_IN_PROGRESS:
868 case AUTH_STATE_FINAL:
869 WINPR_ASSERT(auth->table->DeleteSecurityContext);
870 auth->table->DeleteSecurityContext(&auth->context);
871 /* fallthrouth */
872 WINPR_FALLTHROUGH
873 case AUTH_STATE_CREDS:
874 WINPR_ASSERT(auth->table->FreeCredentialsHandle);
875 auth->table->FreeCredentialsHandle(&auth->credentials);
876 break;
877 case AUTH_STATE_INITIAL:
878 default:
879 break;
880 }
881
882 if (auth->info)
883 {
884 WINPR_ASSERT(auth->table->FreeContextBuffer);
885 auth->table->FreeContextBuffer(auth->info);
886 }
887 }
888
889 sspi_FreeAuthIdentity(&auth->identity);
890 sspi_FreeSecKerberosSettings(auth->kerberosSettingsV2);
891 sspi_FreeSecNtlmSettings(auth->ntlmSettingsV2);
892
893 free(auth->package_list);
894 free(auth->spn);
895 sspi_SecBufferFree(&auth->input_buffer);
896 sspi_SecBufferFree(&auth->output_buffer);
897 credssp_auth_update_name_cache(auth, nullptr);
898 free(auth);
899}
900
901static void auth_get_sspi_module_from_config(char** sspi_module)
902{
903 WINPR_ASSERT(sspi_module);
904
905 WINPR_JSON* json = freerdp_GetJSONConfigFile(TRUE, credssp_config_file_name);
906 if (!json)
907 return;
908
909 winpr_config_apply_string(credssp_config_file_name, json, "SspiModule", sspi_module);
910 WINPR_JSON_Delete(json);
911}
912
913#if !defined(WITHOUT_FREERDP_3x_DEPRECATED)
914static void auth_get_sspi_module_from_reg(char** sspi_module)
915{
916 HKEY hKey = nullptr;
917 DWORD dwType = 0;
918 DWORD dwSize = 0;
919
920 WINPR_ASSERT(sspi_module);
921
922 char* key = freerdp_getApplicatonDetailsRegKey(SERVER_KEY);
923 if (!key)
924 return;
925
926 const LONG rc = RegOpenKeyExA(HKEY_LOCAL_MACHINE, key, 0, KEY_READ | KEY_WOW64_64KEY, &hKey);
927 free(key);
928
929 if (rc != ERROR_SUCCESS)
930 return;
931
932 WLog_WARN(TAG, "HKLM.reg is deprecated since 3.33.0. ATTENTION: Use %s instead!",
933 credssp_config_file_name);
934 if (RegQueryValueExA(hKey, "SspiModule", nullptr, &dwType, nullptr, &dwSize) != ERROR_SUCCESS)
935 {
936 RegCloseKey(hKey);
937 return;
938 }
939
940 char* module = (LPSTR)calloc(dwSize + sizeof(CHAR), sizeof(char));
941 if (!module)
942 {
943 RegCloseKey(hKey);
944 return;
945 }
946
947 if (RegQueryValueExA(hKey, "SspiModule", nullptr, &dwType, (BYTE*)module, &dwSize) !=
948 ERROR_SUCCESS)
949 {
950 RegCloseKey(hKey);
951 free(module);
952 return;
953 }
954
955 RegCloseKey(hKey);
956
957 free(*sspi_module);
958 *sspi_module = module;
959}
960#endif
961
962static SecurityFunctionTable* auth_resolve_sspi_table(const rdpSettings* settings)
963{
964 char* sspi_module = nullptr;
965
966 WINPR_ASSERT(settings);
967
968 if (settings->ServerMode)
969 {
970#if !defined(WITHOUT_FREERDP_3x_DEPRECATED)
971 auth_get_sspi_module_from_reg(&sspi_module);
972#endif
973 auth_get_sspi_module_from_config(&sspi_module);
974 }
975
976 if (sspi_module || settings->SspiModule)
977 {
978 const char* module_name = sspi_module ? sspi_module : settings->SspiModule;
979#ifdef UNICODE
980 const char* proc_name = "InitSecurityInterfaceW";
981#else
982 const char* proc_name = "InitSecurityInterfaceA";
983#endif /* UNICODE */
984
985 HMODULE hSSPI = LoadLibraryX(module_name);
986
987 if (!hSSPI)
988 {
989 WLog_ERR(TAG, "Failed to load SSPI module: %s", module_name);
990 free(sspi_module);
991 return nullptr;
992 }
993
994 WLog_INFO(TAG, "Using SSPI Module: %s", module_name);
995
996 INIT_SECURITY_INTERFACE InitSecurityInterface_ptr =
997 GetProcAddressAs(hSSPI, proc_name, INIT_SECURITY_INTERFACE);
998 if (!InitSecurityInterface_ptr)
999 {
1000 WLog_ERR(TAG, "Failed to load SSPI module: %s, no function %s", module_name, proc_name);
1001 free(sspi_module);
1002 return nullptr;
1003 }
1004 free(sspi_module);
1005 return InitSecurityInterface_ptr();
1006 }
1007
1008 return InitSecurityInterfaceEx(0);
1009}
1010
1011static BOOL credssp_auth_setup_identity(rdpCredsspAuth* auth)
1012{
1013 WINPR_ASSERT(auth);
1014 WINPR_ASSERT(auth->rdp_ctx);
1015
1016 freerdp_peer* peer = auth->rdp_ctx->peer;
1017 const rdpSettings* settings = auth->rdp_ctx->settings;
1018 WINPR_ASSERT(settings);
1019
1020 SEC_WINPR_KERBEROS_SETTINGS_V2* krb_settings = auth->kerberosSettingsV2;
1021 WINPR_ASSERT(krb_settings);
1022
1023 SEC_WINPR_NTLM_SETTINGS_V2* ntlm_settings = auth->ntlmSettingsV2;
1024 WINPR_ASSERT(ntlm_settings);
1025
1026 if (settings->KerberosLifeTime)
1027 parseKerberosDeltat(settings->KerberosLifeTime, &krb_settings->lifeTime, "lifetime");
1028 if (settings->KerberosStartTime)
1029 parseKerberosDeltat(settings->KerberosStartTime, &krb_settings->startTime, "starttime");
1030 if (settings->KerberosRenewableLifeTime)
1031 parseKerberosDeltat(settings->KerberosRenewableLifeTime, &krb_settings->renewLifeTime,
1032 "renewLifeTime");
1033
1034 if (settings->KerberosKdcUrl)
1035 {
1036 if (!sspi_CloneSecSettingsString(&krb_settings->kdcUrl, settings->KerberosKdcUrl))
1037 {
1038 WLog_ERR(TAG, "unable to copy kdcUrl");
1039 return FALSE;
1040 }
1041 }
1042
1043 if (settings->KerberosCache)
1044 {
1045 if (!sspi_CloneSecSettingsString(&krb_settings->cache, settings->KerberosCache))
1046 {
1047 WLog_ERR(TAG, "unable to copy cache name");
1048 return FALSE;
1049 }
1050 }
1051
1052 if (settings->KerberosKeytab)
1053 {
1054 if (!sspi_CloneSecSettingsString(&krb_settings->keytab, settings->KerberosKeytab))
1055 if (!krb_settings->keytab)
1056 {
1057 WLog_ERR(TAG, "unable to copy keytab name");
1058 return FALSE;
1059 }
1060 }
1061
1062 if (settings->KerberosArmor)
1063 {
1064 if (!sspi_CloneSecSettingsString(&krb_settings->armorCache, settings->KerberosArmor))
1065 {
1066 WLog_ERR(TAG, "unable to copy armorCache");
1067 return FALSE;
1068 }
1069 }
1070
1071 if (settings->PkinitAnchors)
1072 {
1073 if (!sspi_CloneSecSettingsString(&krb_settings->pkinitX509Anchors, settings->PkinitAnchors))
1074 {
1075 WLog_ERR(TAG, "unable to copy pkinitX509Anchors");
1076 return FALSE;
1077 }
1078 }
1079
1080 if (settings->NtlmSamFile)
1081 {
1082 if (!sspi_CloneSecSettingsString(&ntlm_settings->samFile, settings->NtlmSamFile))
1083 {
1084 WLog_ERR(TAG, "unable to copy samFile");
1085 return FALSE;
1086 }
1087 }
1088
1089 if (peer && peer->SspiNtlmHashCallback)
1090 {
1091 ntlm_settings->hashCallback = peer->SspiNtlmHashCallback;
1092 ntlm_settings->hashCallbackArg = peer;
1093 }
1094
1095 if (settings->AuthenticationPackageList)
1096 {
1097 auth->package_list = ConvertUtf8ToWCharAlloc(settings->AuthenticationPackageList, nullptr);
1098 if (!auth->package_list)
1099 return FALSE;
1100 }
1101
1102 auth->identity.Flags |= SEC_WINNT_AUTH_IDENTITY_UNICODE;
1103 auth->identity.Flags |= SEC_WINNT_AUTH_IDENTITY_EXTENDED_v2;
1104
1105 return TRUE;
1106}
1107
1108BOOL credssp_auth_set_spn(rdpCredsspAuth* auth, const char* service, const char* hostname)
1109{
1110 size_t length = 0;
1111 char* spn = nullptr;
1112
1113 WINPR_ASSERT(auth);
1114
1115 if (!hostname)
1116 return FALSE;
1117
1118 if (!service)
1119 spn = _strdup(hostname);
1120 else
1121 {
1122 length = strlen(service) + strlen(hostname) + 2;
1123 spn = calloc(length + 1, sizeof(char));
1124 if (!spn)
1125 return FALSE;
1126
1127 (void)sprintf_s(spn, length, "%s/%s", service, hostname);
1128 }
1129 if (!spn)
1130 return FALSE;
1131
1132#if defined(UNICODE)
1133 auth->spn = ConvertUtf8ToWCharAlloc(spn, nullptr);
1134 free(spn);
1135#else
1136 auth->spn = spn;
1137#endif
1138
1139 return TRUE;
1140}
1141
1142static const char* parseInt(const char* v, INT32* r)
1143{
1144 *r = 0;
1145
1146 /* check that we have at least a digit */
1147 if (!*v || !((*v >= '0') && (*v <= '9')))
1148 return nullptr;
1149
1150 for (; *v && (*v >= '0') && (*v <= '9'); v++)
1151 {
1152 *r = (*r * 10) + (*v - '0');
1153 }
1154
1155 return v;
1156}
1157
1158static BOOL parseKerberosDeltat(const char* value, INT32* dest, const char* message)
1159{
1160 INT32 v = 0;
1161 const char* ptr = nullptr;
1162
1163 WINPR_ASSERT(value);
1164 WINPR_ASSERT(dest);
1165 WINPR_ASSERT(message);
1166
1167 /* determine the format :
1168 * h:m[:s] (3:00:02) deltat in hours/minutes
1169 * <n>d<n>h<n>m<n>s 1d4h deltat in day/hours/minutes/seconds
1170 * <n> deltat in seconds
1171 */
1172 ptr = strchr(value, ':');
1173 if (ptr)
1174 {
1175 /* format like h:m[:s] */
1176 *dest = 0;
1177 value = parseInt(value, &v);
1178 if (!value || *value != ':')
1179 {
1180 WLog_ERR(TAG, "Invalid value for %s", message);
1181 return FALSE;
1182 }
1183
1184 *dest = v * 3600;
1185
1186 value = parseInt(value + 1, &v);
1187 if (!value || (*value != 0 && *value != ':') || (v > 60))
1188 {
1189 WLog_ERR(TAG, "Invalid value for %s", message);
1190 return FALSE;
1191 }
1192 *dest += v * 60;
1193
1194 if (*value == ':')
1195 {
1196 /* have optional seconds */
1197 value = parseInt(value + 1, &v);
1198 if (!value || (*value != 0) || (v > 60))
1199 {
1200 WLog_ERR(TAG, "Invalid value for %s", message);
1201 return FALSE;
1202 }
1203 *dest += v;
1204 }
1205 return TRUE;
1206 }
1207
1208 /* <n> or <n>d<n>h<n>m<n>s format */
1209 value = parseInt(value, &v);
1210 if (!value)
1211 {
1212 WLog_ERR(TAG, "Invalid value for %s", message);
1213 return FALSE;
1214 }
1215
1216 if (!*value || isspace(*value))
1217 {
1218 /* interpret that as a value in seconds */
1219 *dest = v;
1220 return TRUE;
1221 }
1222
1223 *dest = 0;
1224 do
1225 {
1226 INT32 factor = 0;
1227 INT32 maxValue = 0;
1228
1229 switch (*value)
1230 {
1231 case 'd':
1232 factor = 3600 * 24;
1233 maxValue = 0;
1234 break;
1235 case 'h':
1236 factor = 3600;
1237 maxValue = 0;
1238 break;
1239 case 'm':
1240 factor = 60;
1241 maxValue = 60;
1242 break;
1243 case 's':
1244 factor = 1;
1245 maxValue = 60;
1246 break;
1247 default:
1248 WLog_ERR(TAG, "invalid value for unit %c when parsing %s", *value, message);
1249 return FALSE;
1250 }
1251
1252 if ((maxValue > 0) && (v > maxValue))
1253 {
1254 WLog_ERR(TAG, "invalid value for unit %c when parsing %s", *value, message);
1255 return FALSE;
1256 }
1257
1258 *dest += (v * factor);
1259 value++;
1260 if (!*value)
1261 return TRUE;
1262
1263 value = parseInt(value, &v);
1264 if (!value || !*value)
1265 {
1266 WLog_ERR(TAG, "Invalid value for %s", message);
1267 return FALSE;
1268 }
1269
1270 } while (TRUE);
1271
1272 return TRUE;
1273}
WINPR_API void WINPR_JSON_Delete(WINPR_JSON *item)
Delete a WinPR JSON wrapper object.
Definition c-json.c:103
WINPR_ATTR_NODISCARD FREERDP_API BOOL freerdp_settings_set_string_from_utf16N(rdpSettings *settings, FreeRDP_Settings_Keys_String id, const WCHAR *param, size_t length)
Sets a string settings value. The param is converted to UTF-8 and the copy stored.
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_set_string_len(rdpSettings *settings, FreeRDP_Settings_Keys_String id, const char *val, size_t len)
Sets a string settings value. The val is copied.
WINPR_ATTR_NODISCARD 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.