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