FreeRDP
Loading...
Searching...
No Matches
kerberos.c
1
22#include <winpr/config.h>
23
24#include <stdio.h>
25#include <stdlib.h>
26#include <string.h>
27#include <errno.h>
28#include <fcntl.h>
29#include <ctype.h>
30
31#include <winpr/assert.h>
32#include <winpr/cast.h>
33#include <winpr/asn1.h>
34#include <winpr/crt.h>
35#include <winpr/interlocked.h>
36#include <winpr/sspi.h>
37#include <winpr/print.h>
38#include <winpr/tchar.h>
39#include <winpr/sysinfo.h>
40#include <winpr/registry.h>
41#include <winpr/endian.h>
42#include <winpr/crypto.h>
43#include <winpr/path.h>
44#include <winpr/wtypes.h>
45#include <winpr/winsock.h>
46#include <winpr/schannel.h>
47#include <winpr/secapi.h>
48
49#include "kerberos.h"
50
51#ifdef WITH_KRB5_MIT
52#include "krb5glue.h"
53#include <profile.h>
54#endif
55
56#ifdef WITH_KRB5_HEIMDAL
57#include "krb5glue.h"
58#include <krb5-protos.h>
59#endif
60
61#include "../sspi.h"
62#include "../../log.h"
63#define TAG WINPR_TAG("sspi.Kerberos")
64
65#define KRB_TGT_REQ 16
66#define KRB_TGT_REP 17
67
68const SecPkgInfoA KERBEROS_SecPkgInfoA = {
69 0x000F3BBF, /* fCapabilities */
70 1, /* wVersion */
71 0x0010, /* wRPCID */
72 0x0000BB80, /* cbMaxToken : 48k bytes maximum for Windows Server 2012 */
73 "Kerberos", /* Name */
74 "Kerberos Security Package" /* Comment */
75};
76
77static WCHAR KERBEROS_SecPkgInfoW_NameBuffer[32] = { 0 };
78static WCHAR KERBEROS_SecPkgInfoW_CommentBuffer[32] = { 0 };
79
80const SecPkgInfoW KERBEROS_SecPkgInfoW = {
81 0x000F3BBF, /* fCapabilities */
82 1, /* wVersion */
83 0x0010, /* wRPCID */
84 0x0000BB80, /* cbMaxToken : 48k bytes maximum for Windows Server 2012 */
85 KERBEROS_SecPkgInfoW_NameBuffer, /* Name */
86 KERBEROS_SecPkgInfoW_CommentBuffer /* Comment */
87};
88
89#ifdef WITH_KRB5
90
91enum KERBEROS_STATE
92{
93 KERBEROS_STATE_INITIAL,
94 KERBEROS_STATE_TGT_REQ,
95 KERBEROS_STATE_TGT_REP,
96 KERBEROS_STATE_AP_REQ,
97 KERBEROS_STATE_AP_REP,
98 KERBEROS_STATE_FINAL
99};
100
101typedef struct KRB_CREDENTIALS_st
102{
103 volatile LONG refCount;
104 krb5_context ctx;
105 char* kdc_url;
106 krb5_ccache ccache;
107 krb5_keytab keytab;
108 krb5_keytab client_keytab;
109 BOOL own_ccache;
110} KRB_CREDENTIALS;
111
112struct s_KRB_CONTEXT
113{
114 enum KERBEROS_STATE state;
115 KRB_CREDENTIALS* credentials;
116 krb5_auth_context auth_ctx;
117 BOOL acceptor;
118 uint32_t flags;
119 uint64_t local_seq;
120 uint64_t remote_seq;
121 struct krb5glue_keyset keyset;
122 BOOL u2u;
123 char* targetHost;
124};
125
126static const WinPrAsn1_OID kerberos_OID = { 9, (void*)"\x2a\x86\x48\x86\xf7\x12\x01\x02\x02" };
127static const WinPrAsn1_OID kerberos_u2u_OID = { 10,
128 (void*)"\x2a\x86\x48\x86\xf7\x12\x01\x02\x02\x03" };
129
130#define krb_log_exec(fkt, ctx, ...) \
131 kerberos_log_msg(ctx, fkt(ctx, ##__VA_ARGS__), #fkt, __FILE__, __func__, __LINE__)
132#define krb_log_exec_ptr(fkt, ctx, ...) \
133 kerberos_log_msg(*ctx, fkt(ctx, ##__VA_ARGS__), #fkt, __FILE__, __func__, __LINE__)
134static krb5_error_code kerberos_log_msg(krb5_context ctx, krb5_error_code code, const char* what,
135 const char* file, const char* fkt, size_t line)
136{
137 switch (code)
138 {
139 case 0:
140 case KRB5_KT_END:
141 break;
142 default:
143 {
144 const DWORD level = WLOG_ERROR;
145
146 wLog* log = WLog_Get(TAG);
147 if (WLog_IsLevelActive(log, level))
148 {
149 const char* msg = krb5_get_error_message(ctx, code);
150 WLog_PrintTextMessage(log, level, line, file, fkt, "%s (%s [%d])", what, msg, code);
151 krb5_free_error_message(ctx, msg);
152 }
153 }
154 break;
155 }
156 return code;
157}
158
159static void credentials_unref(KRB_CREDENTIALS* credentials);
160
161static void kerberos_ContextFree(KRB_CONTEXT* ctx, BOOL allocated)
162{
163 if (!ctx)
164 return;
165
166 free(ctx->targetHost);
167 ctx->targetHost = NULL;
168
169 if (ctx->credentials)
170 {
171 krb5_context krbctx = ctx->credentials->ctx;
172 if (krbctx)
173 {
174 if (ctx->auth_ctx)
175 krb5_auth_con_free(krbctx, ctx->auth_ctx);
176
177 krb5glue_keys_free(krbctx, &ctx->keyset);
178 }
179
180 credentials_unref(ctx->credentials);
181 }
182
183 if (allocated)
184 free(ctx);
185}
186
187static KRB_CONTEXT* kerberos_ContextNew(KRB_CREDENTIALS* credentials)
188{
189 KRB_CONTEXT* context = NULL;
190
191 context = (KRB_CONTEXT*)calloc(1, sizeof(KRB_CONTEXT));
192 if (!context)
193 return NULL;
194
195 context->credentials = credentials;
196 InterlockedIncrement(&credentials->refCount);
197 return context;
198}
199
200static krb5_error_code krb5_prompter(krb5_context context, void* data,
201 WINPR_ATTR_UNUSED const char* name,
202 WINPR_ATTR_UNUSED const char* banner, int num_prompts,
203 krb5_prompt prompts[])
204{
205 for (int i = 0; i < num_prompts; i++)
206 {
207 krb5_prompt_type type = krb5glue_get_prompt_type(context, prompts, i);
208 if (type && (type == KRB5_PROMPT_TYPE_PREAUTH || type == KRB5_PROMPT_TYPE_PASSWORD) && data)
209 {
210 prompts[i].reply->data = _strdup((const char*)data);
211
212 const size_t len = strlen((const char*)data);
213 if (len > UINT32_MAX)
214 return KRB5KRB_ERR_GENERIC;
215 prompts[i].reply->length = (UINT32)len;
216 }
217 }
218 return 0;
219}
220
221static INLINE krb5glue_key get_key(struct krb5glue_keyset* keyset)
222{
223 return keyset->acceptor_key ? keyset->acceptor_key
224 : keyset->initiator_key ? keyset->initiator_key
225 : keyset->session_key;
226}
227
228static BOOL isValidIPv4(const char* ipAddress)
229{
230 struct sockaddr_in sa = { 0 };
231 int result = inet_pton(AF_INET, ipAddress, &(sa.sin_addr));
232 return result != 0;
233}
234
235static BOOL isValidIPv6(const char* ipAddress)
236{
237 struct sockaddr_in6 sa = { 0 };
238 int result = inet_pton(AF_INET6, ipAddress, &(sa.sin6_addr));
239 return result != 0;
240}
241
242static BOOL isValidIP(const char* ipAddress)
243{
244 return isValidIPv4(ipAddress) || isValidIPv6(ipAddress);
245}
246
247#if defined(WITH_KRB5_MIT)
248WINPR_ATTR_MALLOC(free, 1)
249static char* get_realm_name(krb5_data realm, size_t* plen)
250{
251 WINPR_ASSERT(plen);
252 *plen = 0;
253 if ((realm.length <= 0) || (!realm.data))
254 return NULL;
255
256 char* name = NULL;
257 (void)winpr_asprintf(&name, plen, "krbtgt/%*s@%*s", realm.length, realm.data, realm.length,
258 realm.data);
259 return name;
260}
261#elif defined(WITH_KRB5_HEIMDAL)
262WINPR_ATTR_MALLOC(free, 1)
263static char* get_realm_name(Realm realm, size_t* plen)
264{
265 WINPR_ASSERT(plen);
266 *plen = 0;
267 if (!realm)
268 return NULL;
269
270 char* name = NULL;
271 (void)winpr_asprintf(&name, plen, "krbtgt/%s@%s", realm, realm);
272 return name;
273}
274#endif
275
276static int build_krbtgt(krb5_context ctx, krb5_principal principal, krb5_principal* ptarget)
277{
278 /* "krbtgt/" + realm + "@" + realm */
279 size_t len = 0;
280 krb5_error_code rv = KRB5_CC_NOMEM;
281
282 char* name = get_realm_name(principal->realm, &len);
283 if (!name || (len == 0))
284 goto fail;
285
286 krb5_principal target = { 0 };
287 rv = krb5_parse_name(ctx, name, &target);
288 *ptarget = target;
289fail:
290 free(name);
291 return rv;
292}
293
294#endif /* WITH_KRB5 */
295
296static SECURITY_STATUS SEC_ENTRY kerberos_AcquireCredentialsHandleA(
297 SEC_CHAR* pszPrincipal, WINPR_ATTR_UNUSED SEC_CHAR* pszPackage, ULONG fCredentialUse,
298 WINPR_ATTR_UNUSED void* pvLogonID, void* pAuthData, WINPR_ATTR_UNUSED SEC_GET_KEY_FN pGetKeyFn,
299 WINPR_ATTR_UNUSED void* pvGetKeyArgument, PCredHandle phCredential,
300 WINPR_ATTR_UNUSED PTimeStamp ptsExpiry)
301{
302#ifdef WITH_KRB5
303 SEC_WINPR_KERBEROS_SETTINGS* krb_settings = NULL;
304 KRB_CREDENTIALS* credentials = NULL;
305 krb5_context ctx = NULL;
306 krb5_ccache ccache = NULL;
307 krb5_keytab keytab = NULL;
308 krb5_principal principal = NULL;
309 char* domain = NULL;
310 char* username = NULL;
311 char* password = NULL;
312 BOOL own_ccache = FALSE;
313 const char* const default_ccache_type = "MEMORY";
314
315 if (pAuthData)
316 {
317 UINT32 identityFlags = sspi_GetAuthIdentityFlags(pAuthData);
318
319 if (identityFlags & SEC_WINNT_AUTH_IDENTITY_EXTENDED)
320 krb_settings = (((SEC_WINNT_AUTH_IDENTITY_WINPR*)pAuthData)->kerberosSettings);
321
322 if (!sspi_CopyAuthIdentityFieldsA((const SEC_WINNT_AUTH_IDENTITY_INFO*)pAuthData, &username,
323 &domain, &password))
324 {
325 WLog_ERR(TAG, "Failed to copy auth identity fields");
326 goto cleanup;
327 }
328
329 if (!pszPrincipal)
330 pszPrincipal = username;
331 }
332
333 if (krb_log_exec_ptr(krb5_init_context, &ctx))
334 goto cleanup;
335
336 if (domain)
337 {
338 char* udomain = _strdup(domain);
339 if (!udomain)
340 goto cleanup;
341
342 CharUpperA(udomain);
343 /* Will use domain if realm is not specified in username */
344 krb5_error_code rv = krb_log_exec(krb5_set_default_realm, ctx, udomain);
345 free(udomain);
346
347 if (rv)
348 goto cleanup;
349 }
350
351 if (pszPrincipal)
352 {
353 char* cpszPrincipal = _strdup(pszPrincipal);
354 if (!cpszPrincipal)
355 goto cleanup;
356
357 /* Find realm component if included and convert to uppercase */
358 char* p = strchr(cpszPrincipal, '@');
359 if (p)
360 CharUpperA(p);
361
362 krb5_error_code rv = krb_log_exec(krb5_parse_name, ctx, cpszPrincipal, &principal);
363 free(cpszPrincipal);
364
365 if (rv)
366 goto cleanup;
367 WINPR_ASSERT(principal);
368 }
369
370 if (krb_settings && krb_settings->cache)
371 {
372 if ((krb_log_exec(krb5_cc_set_default_name, ctx, krb_settings->cache)))
373 goto cleanup;
374 }
375 else
376 own_ccache = TRUE;
377
378 if (principal)
379 {
380 /* Use the default cache if it's initialized with the right principal */
381 if (krb5_cc_cache_match(ctx, principal, &ccache) == KRB5_CC_NOTFOUND)
382 {
383 if (own_ccache)
384 {
385 if (krb_log_exec(krb5_cc_new_unique, ctx, default_ccache_type, 0, &ccache))
386 goto cleanup;
387 }
388 else
389 {
390 if (krb_log_exec(krb5_cc_resolve, ctx, krb_settings->cache, &ccache))
391 goto cleanup;
392 }
393
394 if (krb_log_exec(krb5_cc_initialize, ctx, ccache, principal))
395 goto cleanup;
396 }
397 else
398 own_ccache = FALSE;
399 }
400 else if (fCredentialUse & SECPKG_CRED_OUTBOUND)
401 {
402 /* Use the default cache with it's default principal */
403 if (krb_log_exec(krb5_cc_default, ctx, &ccache))
404 goto cleanup;
405 if (krb_log_exec(krb5_cc_get_principal, ctx, ccache, &principal))
406 goto cleanup;
407 own_ccache = FALSE;
408 }
409 else
410 {
411 if (own_ccache)
412 {
413 if (krb_log_exec(krb5_cc_new_unique, ctx, default_ccache_type, 0, &ccache))
414 goto cleanup;
415 }
416 else
417 {
418 if (krb_log_exec(krb5_cc_resolve, ctx, krb_settings->cache, &ccache))
419 goto cleanup;
420 }
421 }
422
423 if (krb_settings && krb_settings->keytab)
424 {
425 if (krb_log_exec(krb5_kt_resolve, ctx, krb_settings->keytab, &keytab))
426 goto cleanup;
427 }
428 else
429 {
430 if (fCredentialUse & SECPKG_CRED_INBOUND)
431 if (krb_log_exec(krb5_kt_default, ctx, &keytab))
432 goto cleanup;
433 }
434
435 /* Get initial credentials if required */
436 if (fCredentialUse & SECPKG_CRED_OUTBOUND)
437 {
438 krb5_creds creds = { 0 };
439 krb5_creds matchCreds = { 0 };
440 krb5_flags matchFlags = KRB5_TC_MATCH_TIMES;
441
442 krb5_timeofday(ctx, &matchCreds.times.endtime);
443 matchCreds.times.endtime += 60;
444 matchCreds.client = principal;
445
446 WINPR_ASSERT(principal);
447 if (krb_log_exec(build_krbtgt, ctx, principal, &matchCreds.server))
448 goto cleanup;
449
450 int rv = krb5_cc_retrieve_cred(ctx, ccache, matchFlags, &matchCreds, &creds);
451 krb5_free_principal(ctx, matchCreds.server);
452 krb5_free_cred_contents(ctx, &creds);
453 if (rv)
454 {
455 if (krb_log_exec(krb5glue_get_init_creds, ctx, principal, ccache, krb5_prompter,
456 password, krb_settings))
457 goto cleanup;
458 }
459 }
460
461 credentials = calloc(1, sizeof(KRB_CREDENTIALS));
462 if (!credentials)
463 goto cleanup;
464 credentials->refCount = 1;
465 credentials->ctx = ctx;
466 credentials->ccache = ccache;
467 credentials->keytab = keytab;
468 credentials->own_ccache = own_ccache;
469
470cleanup:
471
472 free(domain);
473 free(username);
474 free(password);
475
476 if (principal)
477 krb5_free_principal(ctx, principal);
478 if (ctx)
479 {
480 if (!credentials)
481 {
482 if (ccache)
483 {
484 if (own_ccache)
485 krb5_cc_destroy(ctx, ccache);
486 else
487 krb5_cc_close(ctx, ccache);
488 }
489 if (keytab)
490 krb5_kt_close(ctx, keytab);
491
492 krb5_free_context(ctx);
493 }
494 }
495
496 /* If we managed to get credentials set the output */
497 if (credentials)
498 {
499 sspi_SecureHandleSetLowerPointer(phCredential, (void*)credentials);
500 sspi_SecureHandleSetUpperPointer(phCredential, (void*)KERBEROS_SSP_NAME);
501 return SEC_E_OK;
502 }
503
504 return SEC_E_NO_CREDENTIALS;
505#else
506 return SEC_E_UNSUPPORTED_FUNCTION;
507#endif
508}
509
510static SECURITY_STATUS SEC_ENTRY kerberos_AcquireCredentialsHandleW(
511 SEC_WCHAR* pszPrincipal, SEC_WCHAR* pszPackage, ULONG fCredentialUse, void* pvLogonID,
512 void* pAuthData, SEC_GET_KEY_FN pGetKeyFn, void* pvGetKeyArgument, PCredHandle phCredential,
513 PTimeStamp ptsExpiry)
514{
515 SECURITY_STATUS status = SEC_E_INSUFFICIENT_MEMORY;
516 char* principal = NULL;
517 char* package = NULL;
518
519 if (pszPrincipal)
520 {
521 principal = ConvertWCharToUtf8Alloc(pszPrincipal, NULL);
522 if (!principal)
523 goto fail;
524 }
525 if (pszPackage)
526 {
527 package = ConvertWCharToUtf8Alloc(pszPackage, NULL);
528 if (!package)
529 goto fail;
530 }
531
532 status =
533 kerberos_AcquireCredentialsHandleA(principal, package, fCredentialUse, pvLogonID, pAuthData,
534 pGetKeyFn, pvGetKeyArgument, phCredential, ptsExpiry);
535
536fail:
537 free(principal);
538 free(package);
539
540 return status;
541}
542
543#ifdef WITH_KRB5
544static void credentials_unref(KRB_CREDENTIALS* credentials)
545{
546 WINPR_ASSERT(credentials);
547
548 if (InterlockedDecrement(&credentials->refCount))
549 return;
550
551 free(credentials->kdc_url);
552
553 if (credentials->ccache)
554 {
555 if (credentials->own_ccache)
556 krb5_cc_destroy(credentials->ctx, credentials->ccache);
557 else
558 krb5_cc_close(credentials->ctx, credentials->ccache);
559 }
560 if (credentials->keytab)
561 krb5_kt_close(credentials->ctx, credentials->keytab);
562
563 krb5_free_context(credentials->ctx);
564 free(credentials);
565}
566#endif
567
568static SECURITY_STATUS SEC_ENTRY kerberos_FreeCredentialsHandle(PCredHandle phCredential)
569{
570#ifdef WITH_KRB5
571 KRB_CREDENTIALS* credentials = sspi_SecureHandleGetLowerPointer(phCredential);
572 if (!credentials)
573 return SEC_E_INVALID_HANDLE;
574
575 credentials_unref(credentials);
576
577 sspi_SecureHandleInvalidate(phCredential);
578 return SEC_E_OK;
579#else
580 return SEC_E_UNSUPPORTED_FUNCTION;
581#endif
582}
583
584static SECURITY_STATUS SEC_ENTRY kerberos_QueryCredentialsAttributesW(
585 WINPR_ATTR_UNUSED PCredHandle phCredential, ULONG ulAttribute, WINPR_ATTR_UNUSED void* pBuffer)
586{
587#ifdef WITH_KRB5
588 switch (ulAttribute)
589 {
590 case SECPKG_CRED_ATTR_NAMES:
591 return SEC_E_OK;
592 default:
593 WLog_ERR(TAG, "TODO: QueryCredentialsAttributesW, implement ulAttribute=%08" PRIx32,
594 ulAttribute);
595 return SEC_E_UNSUPPORTED_FUNCTION;
596 }
597
598#else
599 return SEC_E_UNSUPPORTED_FUNCTION;
600#endif
601}
602
603static SECURITY_STATUS SEC_ENTRY kerberos_QueryCredentialsAttributesA(PCredHandle phCredential,
604 ULONG ulAttribute,
605 void* pBuffer)
606{
607 return kerberos_QueryCredentialsAttributesW(phCredential, ulAttribute, pBuffer);
608}
609
610#ifdef WITH_KRB5
611
612static BOOL kerberos_mk_tgt_token(SecBuffer* buf, int msg_type, char* sname, char* host,
613 const krb5_data* ticket)
614{
615 WinPrAsn1Encoder* enc = NULL;
617 wStream s;
618 size_t len = 0;
619 sspi_gss_data token;
620 BOOL ret = FALSE;
621
622 WINPR_ASSERT(buf);
623
624 if (msg_type != KRB_TGT_REQ && msg_type != KRB_TGT_REP)
625 return FALSE;
626 if (msg_type == KRB_TGT_REP && !ticket)
627 return FALSE;
628
629 enc = WinPrAsn1Encoder_New(WINPR_ASN1_DER);
630 if (!enc)
631 return FALSE;
632
633 /* KERB-TGT-REQUEST (SEQUENCE) */
634 if (!WinPrAsn1EncSeqContainer(enc))
635 goto cleanup;
636
637 /* pvno [0] INTEGER */
638 if (!WinPrAsn1EncContextualInteger(enc, 0, 5))
639 goto cleanup;
640
641 /* msg-type [1] INTEGER */
642 if (!WinPrAsn1EncContextualInteger(enc, 1, msg_type))
643 goto cleanup;
644
645 if (msg_type == KRB_TGT_REQ && sname)
646 {
647 /* server-name [2] PrincipalName (SEQUENCE) */
648 if (!WinPrAsn1EncContextualSeqContainer(enc, 2))
649 goto cleanup;
650
651 /* name-type [0] INTEGER */
652 if (!WinPrAsn1EncContextualInteger(enc, 0, KRB5_NT_SRV_HST))
653 goto cleanup;
654
655 /* name-string [1] SEQUENCE OF GeneralString */
656 if (!WinPrAsn1EncContextualSeqContainer(enc, 1))
657 goto cleanup;
658
659 if (!WinPrAsn1EncGeneralString(enc, sname))
660 goto cleanup;
661
662 if (host && !WinPrAsn1EncGeneralString(enc, host))
663 goto cleanup;
664
665 if (!WinPrAsn1EncEndContainer(enc) || !WinPrAsn1EncEndContainer(enc))
666 goto cleanup;
667 }
668 else if (msg_type == KRB_TGT_REP)
669 {
670 /* ticket [2] Ticket */
671 data.data = (BYTE*)ticket->data;
672 data.len = ticket->length;
673 if (!WinPrAsn1EncContextualRawContent(enc, 2, &data))
674 goto cleanup;
675 }
676
677 if (!WinPrAsn1EncEndContainer(enc))
678 goto cleanup;
679
680 if (!WinPrAsn1EncStreamSize(enc, &len) || len > buf->cbBuffer)
681 goto cleanup;
682
683 Stream_StaticInit(&s, buf->pvBuffer, len);
684 if (!WinPrAsn1EncToStream(enc, &s))
685 goto cleanup;
686
687 token.data = buf->pvBuffer;
688 token.length = (UINT)len;
689 if (sspi_gss_wrap_token(buf, &kerberos_u2u_OID,
690 msg_type == KRB_TGT_REQ ? TOK_ID_TGT_REQ : TOK_ID_TGT_REP, &token))
691 ret = TRUE;
692
693cleanup:
694 WinPrAsn1Encoder_Free(&enc);
695 return ret;
696}
697
698static BOOL append(char* dst, size_t dstSize, const char* src)
699{
700 const size_t dlen = strnlen(dst, dstSize);
701 const size_t slen = strlen(src);
702 if (dlen + slen >= dstSize)
703 return FALSE;
704 if (!strncat(dst, src, dstSize - dlen))
705 return FALSE;
706 return TRUE;
707}
708
709static BOOL kerberos_rd_tgt_req_tag2(WinPrAsn1Decoder* dec, char* buf, size_t len)
710{
711 BOOL rc = FALSE;
712 WinPrAsn1Decoder seq = { 0 };
713
714 /* server-name [2] PrincipalName (SEQUENCE) */
715 if (!WinPrAsn1DecReadSequence(dec, &seq))
716 goto end;
717
718 /* name-type [0] INTEGER */
719 BOOL error = FALSE;
720 WinPrAsn1_INTEGER val = 0;
721 if (!WinPrAsn1DecReadContextualInteger(&seq, 0, &error, &val))
722 goto end;
723
724 /* name-string [1] SEQUENCE OF GeneralString */
725 if (!WinPrAsn1DecReadContextualSequence(&seq, 1, &error, dec))
726 goto end;
727
728 WinPrAsn1_tag tag = 0;
729 BOOL first = TRUE;
730 while (WinPrAsn1DecPeekTag(dec, &tag))
731 {
732 BOOL success = FALSE;
733 char* lstr = NULL;
734 if (!WinPrAsn1DecReadGeneralString(dec, &lstr))
735 goto fail;
736
737 if (!first)
738 {
739 if (!append(buf, len, "/"))
740 goto fail;
741 }
742 first = FALSE;
743
744 if (!append(buf, len, lstr))
745 goto fail;
746
747 success = TRUE;
748 fail:
749 free(lstr);
750 if (!success)
751 goto end;
752 }
753
754 rc = TRUE;
755end:
756 return rc;
757}
758
759static BOOL kerberos_rd_tgt_req_tag3(WinPrAsn1Decoder* dec, char* buf, size_t len)
760{
761 /* realm [3] Realm */
762 BOOL rc = FALSE;
763 WinPrAsn1_STRING str = NULL;
764 if (!WinPrAsn1DecReadGeneralString(dec, &str))
765 goto end;
766
767 if (!append(buf, len, "@"))
768 goto end;
769 if (!append(buf, len, str))
770 goto end;
771
772 rc = TRUE;
773end:
774 free(str);
775 return rc;
776}
777
778static BOOL kerberos_rd_tgt_req(WinPrAsn1Decoder* dec, char** target)
779{
780 BOOL rc = FALSE;
781
782 if (!target)
783 return FALSE;
784 *target = NULL;
785
786 wStream s = WinPrAsn1DecGetStream(dec);
787 const size_t len = Stream_Length(&s);
788 if (len == 0)
789 return TRUE;
790
791 WinPrAsn1Decoder dec2 = { 0 };
792 WinPrAsn1_tagId tag = 0;
793 if (WinPrAsn1DecReadContextualTag(dec, &tag, &dec2) == 0)
794 return FALSE;
795
796 char* buf = calloc(len + 1, sizeof(char));
797 if (!buf)
798 return FALSE;
799
800 /* We expect ASN1 context tag values 2 or 3.
801 *
802 * In case we got value 2 an (optional) context tag value 3 might follow.
803 */
804 BOOL checkForTag3 = TRUE;
805 if (tag == 2)
806 {
807 rc = kerberos_rd_tgt_req_tag2(&dec2, buf, len);
808 if (rc)
809 {
810 const size_t res = WinPrAsn1DecReadContextualTag(dec, &tag, dec);
811 if (res == 0)
812 checkForTag3 = FALSE;
813 }
814 }
815
816 if (checkForTag3)
817 {
818 if (tag == 3)
819 rc = kerberos_rd_tgt_req_tag3(&dec2, buf, len);
820 else
821 rc = FALSE;
822 }
823
824 if (rc)
825 *target = buf;
826 else
827 free(buf);
828 return rc;
829}
830
831static BOOL kerberos_rd_tgt_rep(WinPrAsn1Decoder* dec, krb5_data* ticket)
832{
833 if (!ticket)
834 return FALSE;
835
836 /* ticket [2] Ticket */
837 WinPrAsn1Decoder asnTicket = { 0 };
838 WinPrAsn1_tagId tag = 0;
839 if (WinPrAsn1DecReadContextualTag(dec, &tag, &asnTicket) == 0)
840 return FALSE;
841
842 if (tag != 2)
843 return FALSE;
844
845 wStream s = WinPrAsn1DecGetStream(&asnTicket);
846 ticket->data = Stream_BufferAs(&s, char);
847
848 const size_t len = Stream_Length(&s);
849 if (len > UINT32_MAX)
850 return FALSE;
851 ticket->length = (UINT32)len;
852 return TRUE;
853}
854
855static BOOL kerberos_rd_tgt_token(const sspi_gss_data* token, char** target, krb5_data* ticket)
856{
857 BOOL error = 0;
858 WinPrAsn1_INTEGER val = 0;
859
860 WINPR_ASSERT(token);
861
862 if (target)
863 *target = NULL;
864
865 WinPrAsn1Decoder der = { 0 };
866 WinPrAsn1Decoder_InitMem(&der, WINPR_ASN1_DER, (BYTE*)token->data, token->length);
867
868 /* KERB-TGT-REQUEST (SEQUENCE) */
869 WinPrAsn1Decoder seq = { 0 };
870 if (!WinPrAsn1DecReadSequence(&der, &seq))
871 return FALSE;
872
873 /* pvno [0] INTEGER */
874 if (!WinPrAsn1DecReadContextualInteger(&seq, 0, &error, &val) || val != 5)
875 return FALSE;
876
877 /* msg-type [1] INTEGER */
878 if (!WinPrAsn1DecReadContextualInteger(&seq, 1, &error, &val))
879 return FALSE;
880
881 switch (val)
882 {
883 case KRB_TGT_REQ:
884 return kerberos_rd_tgt_req(&seq, target);
885 case KRB_TGT_REP:
886 return kerberos_rd_tgt_rep(&seq, ticket);
887 default:
888 break;
889 }
890 return FALSE;
891}
892
893#endif /* WITH_KRB5 */
894
895static BOOL kerberos_hash_channel_bindings(WINPR_DIGEST_CTX* md5, SEC_CHANNEL_BINDINGS* bindings)
896{
897 BYTE buf[4];
898
899 winpr_Data_Write_UINT32(buf, bindings->dwInitiatorAddrType);
900 if (!winpr_Digest_Update(md5, buf, 4))
901 return FALSE;
902
903 winpr_Data_Write_UINT32(buf, bindings->cbInitiatorLength);
904 if (!winpr_Digest_Update(md5, buf, 4))
905 return FALSE;
906
907 if (bindings->cbInitiatorLength &&
908 !winpr_Digest_Update(md5, (BYTE*)bindings + bindings->dwInitiatorOffset,
909 bindings->cbInitiatorLength))
910 return FALSE;
911
912 winpr_Data_Write_UINT32(buf, bindings->dwAcceptorAddrType);
913 if (!winpr_Digest_Update(md5, buf, 4))
914 return FALSE;
915
916 winpr_Data_Write_UINT32(buf, bindings->cbAcceptorLength);
917 if (!winpr_Digest_Update(md5, buf, 4))
918 return FALSE;
919
920 if (bindings->cbAcceptorLength &&
921 !winpr_Digest_Update(md5, (BYTE*)bindings + bindings->dwAcceptorOffset,
922 bindings->cbAcceptorLength))
923 return FALSE;
924
925 winpr_Data_Write_UINT32(buf, bindings->cbApplicationDataLength);
926 if (!winpr_Digest_Update(md5, buf, 4))
927 return FALSE;
928
929 if (bindings->cbApplicationDataLength &&
930 !winpr_Digest_Update(md5, (BYTE*)bindings + bindings->dwApplicationDataOffset,
931 bindings->cbApplicationDataLength))
932 return FALSE;
933
934 return TRUE;
935}
936
937static SECURITY_STATUS SEC_ENTRY kerberos_InitializeSecurityContextA(
938 PCredHandle phCredential, PCtxtHandle phContext, SEC_CHAR* pszTargetName, ULONG fContextReq,
939 WINPR_ATTR_UNUSED ULONG Reserved1, WINPR_ATTR_UNUSED ULONG TargetDataRep, PSecBufferDesc pInput,
940 WINPR_ATTR_UNUSED ULONG Reserved2, PCtxtHandle phNewContext, PSecBufferDesc pOutput,
941 WINPR_ATTR_UNUSED ULONG* pfContextAttr, WINPR_ATTR_UNUSED PTimeStamp ptsExpiry)
942{
943#ifdef WITH_KRB5
944 PSecBuffer input_buffer = NULL;
945 PSecBuffer output_buffer = NULL;
946 PSecBuffer bindings_buffer = NULL;
947 WINPR_DIGEST_CTX* md5 = NULL;
948 char* target = NULL;
949 char* sname = NULL;
950 char* host = NULL;
951 krb5_data input_token = { 0 };
952 krb5_data output_token = { 0 };
953 SECURITY_STATUS status = SEC_E_INTERNAL_ERROR;
954 WinPrAsn1_OID oid = { 0 };
955 uint16_t tok_id = 0;
956 krb5_ap_rep_enc_part* reply = NULL;
957 krb5_flags ap_flags = AP_OPTS_USE_SUBKEY;
958 char cksum_contents[24] = { 0 };
959 krb5_data cksum = { 0 };
960 krb5_creds in_creds = { 0 };
961 krb5_creds* creds = NULL;
962 BOOL isNewContext = FALSE;
963 KRB_CONTEXT* context = NULL;
964 KRB_CREDENTIALS* credentials = sspi_SecureHandleGetLowerPointer(phCredential);
965
966 /* behave like windows SSPIs that don't want empty context */
967 if (phContext && !phContext->dwLower && !phContext->dwUpper)
968 return SEC_E_INVALID_HANDLE;
969
970 context = sspi_SecureHandleGetLowerPointer(phContext);
971
972 if (!credentials)
973 return SEC_E_NO_CREDENTIALS;
974
975 if (pInput)
976 {
977 input_buffer = sspi_FindSecBuffer(pInput, SECBUFFER_TOKEN);
978 bindings_buffer = sspi_FindSecBuffer(pInput, SECBUFFER_CHANNEL_BINDINGS);
979 }
980 if (pOutput)
981 output_buffer = sspi_FindSecBuffer(pOutput, SECBUFFER_TOKEN);
982
983 if (fContextReq & ISC_REQ_MUTUAL_AUTH)
984 ap_flags |= AP_OPTS_MUTUAL_REQUIRED;
985
986 if (fContextReq & ISC_REQ_USE_SESSION_KEY)
987 ap_flags |= AP_OPTS_USE_SESSION_KEY;
988
989 /* Split target name into service/hostname components */
990 if (pszTargetName)
991 {
992 target = _strdup(pszTargetName);
993 if (!target)
994 {
995 status = SEC_E_INSUFFICIENT_MEMORY;
996 goto cleanup;
997 }
998 host = strchr(target, '/');
999 if (host)
1000 {
1001 *host++ = 0;
1002 sname = target;
1003 }
1004 else
1005 host = target;
1006 if (isValidIP(host))
1007 {
1008 status = SEC_E_NO_CREDENTIALS;
1009 goto cleanup;
1010 }
1011 }
1012
1013 if (!context)
1014 {
1015 context = kerberos_ContextNew(credentials);
1016 if (!context)
1017 {
1018 status = SEC_E_INSUFFICIENT_MEMORY;
1019 goto cleanup;
1020 }
1021
1022 isNewContext = TRUE;
1023
1024 if (host)
1025 context->targetHost = _strdup(host);
1026 if (!context->targetHost)
1027 {
1028 status = SEC_E_INSUFFICIENT_MEMORY;
1029 goto cleanup;
1030 }
1031
1032 if (fContextReq & ISC_REQ_USE_SESSION_KEY)
1033 {
1034 context->state = KERBEROS_STATE_TGT_REQ;
1035 context->u2u = TRUE;
1036 }
1037 else
1038 context->state = KERBEROS_STATE_AP_REQ;
1039 }
1040 else
1041 {
1042 if (!input_buffer || !sspi_gss_unwrap_token(input_buffer, &oid, &tok_id, &input_token))
1043 goto bad_token;
1044 if ((context->u2u && !sspi_gss_oid_compare(&oid, &kerberos_u2u_OID)) ||
1045 (!context->u2u && !sspi_gss_oid_compare(&oid, &kerberos_OID)))
1046 goto bad_token;
1047 }
1048
1049 /* SSPI flags are compatible with GSS flags except INTEG_FLAG */
1050 context->flags |= (fContextReq & 0x1F);
1051 if ((fContextReq & ISC_REQ_INTEGRITY) && !(fContextReq & ISC_REQ_NO_INTEGRITY))
1052 context->flags |= SSPI_GSS_C_INTEG_FLAG;
1053
1054 switch (context->state)
1055 {
1056 case KERBEROS_STATE_TGT_REQ:
1057
1058 if (!kerberos_mk_tgt_token(output_buffer, KRB_TGT_REQ, sname, host, NULL))
1059 goto cleanup;
1060
1061 context->state = KERBEROS_STATE_TGT_REP;
1062 status = SEC_I_CONTINUE_NEEDED;
1063 break;
1064
1065 case KERBEROS_STATE_TGT_REP:
1066
1067 if (tok_id != TOK_ID_TGT_REP)
1068 goto bad_token;
1069
1070 if (!kerberos_rd_tgt_token(&input_token, NULL, &in_creds.second_ticket))
1071 goto bad_token;
1072
1073 /* Continue to AP-REQ */
1074 /* fallthrough */
1075 WINPR_FALLTHROUGH
1076
1077 case KERBEROS_STATE_AP_REQ:
1078
1079 /* Set auth_context options */
1080 if (krb_log_exec(krb5_auth_con_init, credentials->ctx, &context->auth_ctx))
1081 goto cleanup;
1082 if (krb_log_exec(krb5_auth_con_setflags, credentials->ctx, context->auth_ctx,
1083 KRB5_AUTH_CONTEXT_DO_SEQUENCE | KRB5_AUTH_CONTEXT_USE_SUBKEY))
1084 goto cleanup;
1085 if (krb_log_exec(krb5glue_auth_con_set_cksumtype, credentials->ctx, context->auth_ctx,
1086 GSS_CHECKSUM_TYPE))
1087 goto cleanup;
1088
1089 /* Get a service ticket */
1090 if (krb_log_exec(krb5_sname_to_principal, credentials->ctx, host, sname,
1091 KRB5_NT_SRV_HST, &in_creds.server))
1092 goto cleanup;
1093
1094 if (krb_log_exec(krb5_cc_get_principal, credentials->ctx, credentials->ccache,
1095 &in_creds.client))
1096 {
1097 status = SEC_E_WRONG_PRINCIPAL;
1098 goto cleanup;
1099 }
1100
1101 if (krb_log_exec(krb5_get_credentials, credentials->ctx,
1102 context->u2u ? KRB5_GC_USER_USER : 0, credentials->ccache, &in_creds,
1103 &creds))
1104 {
1105 status = SEC_E_NO_CREDENTIALS;
1106 goto cleanup;
1107 }
1108
1109 /* Write the checksum (delegation not implemented) */
1110 cksum.data = cksum_contents;
1111 cksum.length = sizeof(cksum_contents);
1112 winpr_Data_Write_UINT32(cksum_contents, 16);
1113 winpr_Data_Write_UINT32((cksum_contents + 20), context->flags);
1114
1115 if (bindings_buffer)
1116 {
1117 SEC_CHANNEL_BINDINGS* bindings = bindings_buffer->pvBuffer;
1118
1119 /* Sanity checks */
1120 if (bindings_buffer->cbBuffer < sizeof(SEC_CHANNEL_BINDINGS) ||
1121 (bindings->cbInitiatorLength + bindings->dwInitiatorOffset) >
1122 bindings_buffer->cbBuffer ||
1123 (bindings->cbAcceptorLength + bindings->dwAcceptorOffset) >
1124 bindings_buffer->cbBuffer ||
1125 (bindings->cbApplicationDataLength + bindings->dwApplicationDataOffset) >
1126 bindings_buffer->cbBuffer)
1127 {
1128 status = SEC_E_BAD_BINDINGS;
1129 goto cleanup;
1130 }
1131
1132 md5 = winpr_Digest_New();
1133 if (!md5)
1134 goto cleanup;
1135
1136 if (!winpr_Digest_Init(md5, WINPR_MD_MD5))
1137 goto cleanup;
1138
1139 if (!kerberos_hash_channel_bindings(md5, bindings))
1140 goto cleanup;
1141
1142 if (!winpr_Digest_Final(md5, (BYTE*)cksum_contents + 4, 16))
1143 goto cleanup;
1144 }
1145
1146 /* Make the AP_REQ message */
1147 if (krb_log_exec(krb5_mk_req_extended, credentials->ctx, &context->auth_ctx, ap_flags,
1148 &cksum, creds, &output_token))
1149 goto cleanup;
1150
1151 if (!sspi_gss_wrap_token(output_buffer,
1152 context->u2u ? &kerberos_u2u_OID : &kerberos_OID,
1153 TOK_ID_AP_REQ, &output_token))
1154 goto cleanup;
1155
1156 if (context->flags & SSPI_GSS_C_SEQUENCE_FLAG)
1157 {
1158 if (krb_log_exec(krb5_auth_con_getlocalseqnumber, credentials->ctx,
1159 context->auth_ctx, (INT32*)&context->local_seq))
1160 goto cleanup;
1161 context->remote_seq ^= context->local_seq;
1162 }
1163
1164 if (krb_log_exec(krb5glue_update_keyset, credentials->ctx, context->auth_ctx, FALSE,
1165 &context->keyset))
1166 goto cleanup;
1167
1168 context->state = KERBEROS_STATE_AP_REP;
1169
1170 if (context->flags & SSPI_GSS_C_MUTUAL_FLAG)
1171 status = SEC_I_CONTINUE_NEEDED;
1172 else
1173 status = SEC_E_OK;
1174 break;
1175
1176 case KERBEROS_STATE_AP_REP:
1177
1178 if (tok_id == TOK_ID_AP_REP)
1179 {
1180 if (krb_log_exec(krb5_rd_rep, credentials->ctx, context->auth_ctx, &input_token,
1181 &reply))
1182 goto cleanup;
1183 krb5_free_ap_rep_enc_part(credentials->ctx, reply);
1184 }
1185 else if (tok_id == TOK_ID_ERROR)
1186 {
1187 krb5glue_log_error(credentials->ctx, &input_token, TAG);
1188 goto cleanup;
1189 }
1190 else
1191 goto bad_token;
1192
1193 if (context->flags & SSPI_GSS_C_SEQUENCE_FLAG)
1194 {
1195 if (krb_log_exec(krb5_auth_con_getremoteseqnumber, credentials->ctx,
1196 context->auth_ctx, (INT32*)&context->remote_seq))
1197 goto cleanup;
1198 }
1199
1200 if (krb_log_exec(krb5glue_update_keyset, credentials->ctx, context->auth_ctx, FALSE,
1201 &context->keyset))
1202 goto cleanup;
1203
1204 context->state = KERBEROS_STATE_FINAL;
1205
1206 if (output_buffer)
1207 output_buffer->cbBuffer = 0;
1208 status = SEC_E_OK;
1209 break;
1210
1211 case KERBEROS_STATE_FINAL:
1212 default:
1213 WLog_ERR(TAG, "Kerberos in invalid state!");
1214 goto cleanup;
1215 }
1216
1217cleanup:
1218{
1219 /* second_ticket is not allocated */
1220 krb5_data edata = { 0 };
1221 in_creds.second_ticket = edata;
1222 krb5_free_cred_contents(credentials->ctx, &in_creds);
1223}
1224
1225 krb5_free_creds(credentials->ctx, creds);
1226 if (output_token.data)
1227 krb5glue_free_data_contents(credentials->ctx, &output_token);
1228
1229 winpr_Digest_Free(md5);
1230
1231 free(target);
1232
1233 if (isNewContext)
1234 {
1235 switch (status)
1236 {
1237 case SEC_E_OK:
1238 case SEC_I_CONTINUE_NEEDED:
1239 sspi_SecureHandleSetLowerPointer(phNewContext, context);
1240 sspi_SecureHandleSetUpperPointer(phNewContext, KERBEROS_SSP_NAME);
1241 break;
1242 default:
1243 kerberos_ContextFree(context, TRUE);
1244 break;
1245 }
1246 }
1247
1248 return status;
1249
1250bad_token:
1251 status = SEC_E_INVALID_TOKEN;
1252 goto cleanup;
1253#else
1254 return SEC_E_UNSUPPORTED_FUNCTION;
1255#endif /* WITH_KRB5 */
1256}
1257
1258static SECURITY_STATUS SEC_ENTRY kerberos_InitializeSecurityContextW(
1259 PCredHandle phCredential, PCtxtHandle phContext, SEC_WCHAR* pszTargetName, ULONG fContextReq,
1260 ULONG Reserved1, ULONG TargetDataRep, PSecBufferDesc pInput, ULONG Reserved2,
1261 PCtxtHandle phNewContext, PSecBufferDesc pOutput, ULONG* pfContextAttr, PTimeStamp ptsExpiry)
1262{
1263 SECURITY_STATUS status = 0;
1264 char* target_name = NULL;
1265
1266 if (pszTargetName)
1267 {
1268 target_name = ConvertWCharToUtf8Alloc(pszTargetName, NULL);
1269 if (!target_name)
1270 return SEC_E_INSUFFICIENT_MEMORY;
1271 }
1272
1273 status = kerberos_InitializeSecurityContextA(phCredential, phContext, target_name, fContextReq,
1274 Reserved1, TargetDataRep, pInput, Reserved2,
1275 phNewContext, pOutput, pfContextAttr, ptsExpiry);
1276
1277 if (target_name)
1278 free(target_name);
1279
1280 return status;
1281}
1282
1283#ifdef WITH_KRB5
1284static BOOL retrieveTgtForPrincipal(KRB_CREDENTIALS* credentials, krb5_principal principal,
1285 krb5_creds* creds)
1286{
1287 BOOL ret = FALSE;
1288 krb5_kt_cursor cur = { 0 };
1289 krb5_keytab_entry entry = { 0 };
1290 if (krb_log_exec(krb5_kt_start_seq_get, credentials->ctx, credentials->keytab, &cur))
1291 goto cleanup;
1292
1293 do
1294 {
1295 krb5_error_code rv =
1296 krb_log_exec(krb5_kt_next_entry, credentials->ctx, credentials->keytab, &entry, &cur);
1297 if (rv == KRB5_KT_END)
1298 break;
1299 if (rv != 0)
1300 goto cleanup;
1301
1302 if (krb5_principal_compare(credentials->ctx, principal, entry.principal))
1303 break;
1304 rv = krb_log_exec(krb5glue_free_keytab_entry_contents, credentials->ctx, &entry);
1305 memset(&entry, 0, sizeof(entry));
1306 if (rv)
1307 goto cleanup;
1308 } while (1);
1309
1310 if (krb_log_exec(krb5_kt_end_seq_get, credentials->ctx, credentials->keytab, &cur))
1311 goto cleanup;
1312
1313 if (!entry.principal)
1314 goto cleanup;
1315
1316 /* Get the TGT */
1317 if (krb_log_exec(krb5_get_init_creds_keytab, credentials->ctx, creds, entry.principal,
1318 credentials->keytab, 0, NULL, NULL))
1319 goto cleanup;
1320
1321 ret = TRUE;
1322
1323cleanup:
1324 return ret;
1325}
1326
1327static BOOL retrieveSomeTgt(KRB_CREDENTIALS* credentials, const char* target, krb5_creds* creds)
1328{
1329 BOOL ret = TRUE;
1330 krb5_principal target_princ = { 0 };
1331 char* default_realm = NULL;
1332
1333 krb5_error_code rv =
1334 krb_log_exec(krb5_parse_name_flags, credentials->ctx, target, 0, &target_princ);
1335 if (rv)
1336 return FALSE;
1337
1338#if defined(WITH_KRB5_HEIMDAL)
1339 if (!target_princ->realm)
1340 {
1341 rv = krb_log_exec(krb5_get_default_realm, credentials->ctx, &default_realm);
1342 if (rv)
1343 goto out;
1344
1345 target_princ->realm = default_realm;
1346 }
1347#else
1348 if (!target_princ->realm.length)
1349 {
1350 rv = krb_log_exec(krb5_get_default_realm, credentials->ctx, &default_realm);
1351 if (rv)
1352 goto out;
1353
1354 target_princ->realm.data = default_realm;
1355 target_princ->realm.length = (unsigned int)strlen(default_realm);
1356 }
1357#endif
1358
1359 /*
1360 * First try with the account service. We were requested with something like
1361 * TERMSRV/<host>@<realm>, let's see if we have that in our keytab and if we're able
1362 * to retrieve a TGT with that entry
1363 *
1364 */
1365 if (retrieveTgtForPrincipal(credentials, target_princ, creds))
1366 goto out;
1367
1368 ret = FALSE;
1369
1370#if defined(WITH_KRB5_MIT)
1371 /*
1372 * if it's not working let's try with <host>$@<REALM> (note the dollar)
1373 */
1374 char hostDollar[300] = { 0 };
1375 if (target_princ->length < 2)
1376 goto out;
1377
1378 (void)snprintf(hostDollar, sizeof(hostDollar) - 1, "%s$@%s", target_princ->data[1].data,
1379 target_princ->realm.data);
1380 krb5_free_principal(credentials->ctx, target_princ);
1381
1382 rv = krb_log_exec(krb5_parse_name_flags, credentials->ctx, hostDollar, 0, &target_princ);
1383 if (rv)
1384 return FALSE;
1385
1386 ret = retrieveTgtForPrincipal(credentials, target_princ, creds);
1387#endif
1388
1389out:
1390 if (default_realm)
1391 krb5_free_default_realm(credentials->ctx, default_realm);
1392
1393 krb5_free_principal(credentials->ctx, target_princ);
1394 return ret;
1395}
1396#endif
1397
1398static SECURITY_STATUS SEC_ENTRY kerberos_AcceptSecurityContext(
1399 PCredHandle phCredential, PCtxtHandle phContext, PSecBufferDesc pInput,
1400 WINPR_ATTR_UNUSED ULONG fContextReq, WINPR_ATTR_UNUSED ULONG TargetDataRep,
1401 PCtxtHandle phNewContext, PSecBufferDesc pOutput, ULONG* pfContextAttr,
1402 WINPR_ATTR_UNUSED PTimeStamp ptsExpity)
1403{
1404#ifdef WITH_KRB5
1405 BOOL isNewContext = FALSE;
1406 PSecBuffer input_buffer = NULL;
1407 PSecBuffer output_buffer = NULL;
1408 WinPrAsn1_OID oid = { 0 };
1409 uint16_t tok_id = 0;
1410 krb5_data input_token = { 0 };
1411 krb5_data output_token = { 0 };
1412 SECURITY_STATUS status = SEC_E_INTERNAL_ERROR;
1413 krb5_flags ap_flags = 0;
1414 krb5glue_authenticator authenticator = NULL;
1415 char* target = NULL;
1416 krb5_keytab_entry entry = { 0 };
1417 krb5_creds creds = { 0 };
1418
1419 /* behave like windows SSPIs that don't want empty context */
1420 if (phContext && !phContext->dwLower && !phContext->dwUpper)
1421 return SEC_E_INVALID_HANDLE;
1422
1423 KRB_CONTEXT* context = sspi_SecureHandleGetLowerPointer(phContext);
1424 KRB_CREDENTIALS* credentials = sspi_SecureHandleGetLowerPointer(phCredential);
1425
1426 if (pInput)
1427 input_buffer = sspi_FindSecBuffer(pInput, SECBUFFER_TOKEN);
1428 if (pOutput)
1429 output_buffer = sspi_FindSecBuffer(pOutput, SECBUFFER_TOKEN);
1430
1431 if (!input_buffer)
1432 return SEC_E_INVALID_TOKEN;
1433
1434 if (!sspi_gss_unwrap_token(input_buffer, &oid, &tok_id, &input_token))
1435 return SEC_E_INVALID_TOKEN;
1436
1437 if (!context)
1438 {
1439 isNewContext = TRUE;
1440 context = kerberos_ContextNew(credentials);
1441 context->acceptor = TRUE;
1442
1443 if (sspi_gss_oid_compare(&oid, &kerberos_u2u_OID))
1444 {
1445 context->u2u = TRUE;
1446 context->state = KERBEROS_STATE_TGT_REQ;
1447 }
1448 else if (sspi_gss_oid_compare(&oid, &kerberos_OID))
1449 context->state = KERBEROS_STATE_AP_REQ;
1450 else
1451 goto bad_token;
1452 }
1453 else
1454 {
1455 if ((context->u2u && !sspi_gss_oid_compare(&oid, &kerberos_u2u_OID)) ||
1456 (!context->u2u && !sspi_gss_oid_compare(&oid, &kerberos_OID)))
1457 goto bad_token;
1458 }
1459
1460 if (context->state == KERBEROS_STATE_TGT_REQ && tok_id == TOK_ID_TGT_REQ)
1461 {
1462 if (!kerberos_rd_tgt_token(&input_token, &target, NULL))
1463 goto bad_token;
1464
1465 if (!retrieveSomeTgt(credentials, target, &creds))
1466 goto cleanup;
1467
1468 if (!kerberos_mk_tgt_token(output_buffer, KRB_TGT_REP, NULL, NULL, &creds.ticket))
1469 goto cleanup;
1470
1471 if (krb_log_exec(krb5_auth_con_init, credentials->ctx, &context->auth_ctx))
1472 goto cleanup;
1473
1474 if (krb_log_exec(krb5glue_auth_con_setuseruserkey, credentials->ctx, context->auth_ctx,
1475 &krb5glue_creds_getkey(creds)))
1476 goto cleanup;
1477
1478 context->state = KERBEROS_STATE_AP_REQ;
1479 }
1480 else if (context->state == KERBEROS_STATE_AP_REQ && tok_id == TOK_ID_AP_REQ)
1481 {
1482 if (krb_log_exec(krb5_rd_req, credentials->ctx, &context->auth_ctx, &input_token, NULL,
1483 credentials->keytab, &ap_flags, NULL))
1484 goto cleanup;
1485
1486 if (krb_log_exec(krb5_auth_con_setflags, credentials->ctx, context->auth_ctx,
1487 KRB5_AUTH_CONTEXT_DO_SEQUENCE | KRB5_AUTH_CONTEXT_USE_SUBKEY))
1488 goto cleanup;
1489
1490 /* Retrieve and validate the checksum */
1491 if (krb_log_exec(krb5_auth_con_getauthenticator, credentials->ctx, context->auth_ctx,
1492 &authenticator))
1493 goto cleanup;
1494 if (!krb5glue_authenticator_validate_chksum(authenticator, GSS_CHECKSUM_TYPE,
1495 &context->flags))
1496 goto bad_token;
1497
1498 if ((ap_flags & AP_OPTS_MUTUAL_REQUIRED) && (context->flags & SSPI_GSS_C_MUTUAL_FLAG))
1499 {
1500 if (!output_buffer)
1501 goto bad_token;
1502 if (krb_log_exec(krb5_mk_rep, credentials->ctx, context->auth_ctx, &output_token))
1503 goto cleanup;
1504 if (!sspi_gss_wrap_token(output_buffer,
1505 context->u2u ? &kerberos_u2u_OID : &kerberos_OID,
1506 TOK_ID_AP_REP, &output_token))
1507 goto cleanup;
1508 }
1509 else
1510 {
1511 if (output_buffer)
1512 output_buffer->cbBuffer = 0;
1513 }
1514
1515 *pfContextAttr = (context->flags & 0x1F);
1516 if (context->flags & SSPI_GSS_C_INTEG_FLAG)
1517 *pfContextAttr |= ASC_RET_INTEGRITY;
1518
1519 if (context->flags & SSPI_GSS_C_SEQUENCE_FLAG)
1520 {
1521 if (krb_log_exec(krb5_auth_con_getlocalseqnumber, credentials->ctx, context->auth_ctx,
1522 (INT32*)&context->local_seq))
1523 goto cleanup;
1524 if (krb_log_exec(krb5_auth_con_getremoteseqnumber, credentials->ctx, context->auth_ctx,
1525 (INT32*)&context->remote_seq))
1526 goto cleanup;
1527 }
1528
1529 if (krb_log_exec(krb5glue_update_keyset, credentials->ctx, context->auth_ctx, TRUE,
1530 &context->keyset))
1531 goto cleanup;
1532
1533 context->state = KERBEROS_STATE_FINAL;
1534 }
1535 else
1536 goto bad_token;
1537
1538 /* On first call allocate new context */
1539 if (context->state == KERBEROS_STATE_FINAL)
1540 status = SEC_E_OK;
1541 else
1542 status = SEC_I_CONTINUE_NEEDED;
1543
1544cleanup:
1545 free(target);
1546 if (output_token.data)
1547 krb5glue_free_data_contents(credentials->ctx, &output_token);
1548 if (entry.principal)
1549 krb5glue_free_keytab_entry_contents(credentials->ctx, &entry);
1550
1551 if (isNewContext)
1552 {
1553 switch (status)
1554 {
1555 case SEC_E_OK:
1556 case SEC_I_CONTINUE_NEEDED:
1557 sspi_SecureHandleSetLowerPointer(phNewContext, context);
1558 sspi_SecureHandleSetUpperPointer(phNewContext, KERBEROS_SSP_NAME);
1559 break;
1560 default:
1561 kerberos_ContextFree(context, TRUE);
1562 break;
1563 }
1564 }
1565
1566 return status;
1567
1568bad_token:
1569 status = SEC_E_INVALID_TOKEN;
1570 goto cleanup;
1571#else
1572 return SEC_E_UNSUPPORTED_FUNCTION;
1573#endif /* WITH_KRB5 */
1574}
1575
1576#ifdef WITH_KRB5
1577static KRB_CONTEXT* get_context(PCtxtHandle phContext)
1578{
1579 if (!phContext)
1580 return NULL;
1581
1582 TCHAR* name = sspi_SecureHandleGetUpperPointer(phContext);
1583 if (!name)
1584 return NULL;
1585
1586 if (_tcsncmp(KERBEROS_SSP_NAME, name, ARRAYSIZE(KERBEROS_SSP_NAME)) != 0)
1587 return NULL;
1588 return sspi_SecureHandleGetLowerPointer(phContext);
1589}
1590
1591static BOOL copy_krb5_data(krb5_data* data, PUCHAR* ptr, ULONG* psize)
1592{
1593 WINPR_ASSERT(data);
1594 WINPR_ASSERT(ptr);
1595 WINPR_ASSERT(psize);
1596
1597 *ptr = (PUCHAR)malloc(data->length);
1598 if (!*ptr)
1599 return FALSE;
1600
1601 *psize = data->length;
1602 memcpy(*ptr, data->data, data->length);
1603 return TRUE;
1604}
1605#endif
1606
1607static SECURITY_STATUS SEC_ENTRY kerberos_DeleteSecurityContext(PCtxtHandle phContext)
1608{
1609#ifdef WITH_KRB5
1610 KRB_CONTEXT* context = get_context(phContext);
1611 if (!context)
1612 return SEC_E_INVALID_HANDLE;
1613
1614 kerberos_ContextFree(context, TRUE);
1615
1616 return SEC_E_OK;
1617#else
1618 return SEC_E_UNSUPPORTED_FUNCTION;
1619#endif
1620}
1621
1622#ifdef WITH_KRB5
1623
1624static SECURITY_STATUS krb5_error_to_SECURITY_STATUS(krb5_error_code code)
1625{
1626 switch (code)
1627 {
1628 case 0:
1629 return SEC_E_OK;
1630 default:
1631 return SEC_E_INTERNAL_ERROR;
1632 }
1633}
1634
1635static SECURITY_STATUS kerberos_ATTR_SIZES(KRB_CONTEXT* context, KRB_CREDENTIALS* credentials,
1636 SecPkgContext_Sizes* ContextSizes)
1637{
1638 UINT header = 0;
1639 UINT pad = 0;
1640 UINT trailer = 0;
1641 krb5glue_key key = NULL;
1642
1643 WINPR_ASSERT(context);
1644 WINPR_ASSERT(context->auth_ctx);
1645
1646 /* The MaxTokenSize by default is 12,000 bytes. This has been the default value
1647 * since Windows 2000 SP2 and still remains in Windows 7 and Windows 2008 R2.
1648 * For Windows Server 2012, the default value of the MaxTokenSize registry
1649 * entry is 48,000 bytes.*/
1650 ContextSizes->cbMaxToken = KERBEROS_SecPkgInfoA.cbMaxToken;
1651 ContextSizes->cbMaxSignature = 0;
1652 ContextSizes->cbBlockSize = 1;
1653 ContextSizes->cbSecurityTrailer = 0;
1654
1655 key = get_key(&context->keyset);
1656
1657 if (context->flags & SSPI_GSS_C_CONF_FLAG)
1658 {
1659 krb5_error_code rv = krb_log_exec(krb5glue_crypto_length, credentials->ctx, key,
1660 KRB5_CRYPTO_TYPE_HEADER, &header);
1661 if (rv)
1662 return krb5_error_to_SECURITY_STATUS(rv);
1663
1664 rv = krb_log_exec(krb5glue_crypto_length, credentials->ctx, key, KRB5_CRYPTO_TYPE_PADDING,
1665 &pad);
1666 if (rv)
1667 return krb5_error_to_SECURITY_STATUS(rv);
1668
1669 rv = krb_log_exec(krb5glue_crypto_length, credentials->ctx, key, KRB5_CRYPTO_TYPE_TRAILER,
1670 &trailer);
1671 if (rv)
1672 return krb5_error_to_SECURITY_STATUS(rv);
1673
1674 /* GSS header (= 16 bytes) + encrypted header = 32 bytes */
1675 ContextSizes->cbSecurityTrailer = header + pad + trailer + 32;
1676 }
1677
1678 if (context->flags & SSPI_GSS_C_INTEG_FLAG)
1679 {
1680 krb5_error_code rv = krb_log_exec(krb5glue_crypto_length, credentials->ctx, key,
1681 KRB5_CRYPTO_TYPE_CHECKSUM, &ContextSizes->cbMaxSignature);
1682 if (rv)
1683 return krb5_error_to_SECURITY_STATUS(rv);
1684
1685 ContextSizes->cbMaxSignature += 16;
1686 }
1687
1688 return SEC_E_OK;
1689}
1690
1691static SECURITY_STATUS kerberos_ATTR_TICKET_LOGON(KRB_CONTEXT* context,
1692 KRB_CREDENTIALS* credentials,
1693 KERB_TICKET_LOGON* ticketLogon)
1694{
1695 krb5_creds matchCred = { 0 };
1696 krb5_auth_context authContext = NULL;
1697 krb5_flags getCredsFlags = KRB5_GC_CACHED;
1698 BOOL firstRun = TRUE;
1699 krb5_creds* hostCred = NULL;
1700 SECURITY_STATUS ret = SEC_E_INSUFFICIENT_MEMORY;
1701 int rv = krb_log_exec(krb5_sname_to_principal, credentials->ctx, context->targetHost, "HOST",
1702 KRB5_NT_SRV_HST, &matchCred.server);
1703 if (rv)
1704 goto out;
1705
1706 rv = krb_log_exec(krb5_cc_get_principal, credentials->ctx, credentials->ccache,
1707 &matchCred.client);
1708 if (rv)
1709 goto out;
1710
1711 /* try from the cache first, and then do a new request */
1712again:
1713 rv = krb_log_exec(krb5_get_credentials, credentials->ctx, getCredsFlags, credentials->ccache,
1714 &matchCred, &hostCred);
1715 switch (rv)
1716 {
1717 case 0:
1718 break;
1719 case KRB5_CC_NOTFOUND:
1720 getCredsFlags = 0;
1721 if (firstRun)
1722 {
1723 firstRun = FALSE;
1724 goto again;
1725 }
1726 WINPR_FALLTHROUGH
1727 default:
1728 WLog_ERR(TAG, "krb5_get_credentials(hostCreds), rv=%d", rv);
1729 goto out;
1730 }
1731
1732 if (krb_log_exec(krb5_auth_con_init, credentials->ctx, &authContext))
1733 goto out;
1734
1735 krb5_data derOut = { 0 };
1736 if (krb_log_exec(krb5_fwd_tgt_creds, credentials->ctx, authContext, context->targetHost,
1737 matchCred.client, matchCred.server, credentials->ccache, 1, &derOut))
1738 {
1739 ret = SEC_E_LOGON_DENIED;
1740 goto out;
1741 }
1742
1743 ticketLogon->MessageType = KerbTicketLogon;
1744 ticketLogon->Flags = KERB_LOGON_FLAG_REDIRECTED;
1745
1746 if (!copy_krb5_data(&hostCred->ticket, &ticketLogon->ServiceTicket,
1747 &ticketLogon->ServiceTicketLength))
1748 {
1749 krb5_free_data(credentials->ctx, &derOut);
1750 goto out;
1751 }
1752
1753 ticketLogon->TicketGrantingTicketLength = derOut.length;
1754 ticketLogon->TicketGrantingTicket = (PUCHAR)derOut.data;
1755
1756 ret = SEC_E_OK;
1757out:
1758 krb5_auth_con_free(credentials->ctx, authContext);
1759 krb5_free_creds(credentials->ctx, hostCred);
1760 krb5_free_cred_contents(credentials->ctx, &matchCred);
1761 return ret;
1762}
1763
1764#endif /* WITH_KRB5 */
1765
1766static SECURITY_STATUS SEC_ENTRY kerberos_QueryContextAttributesA(PCtxtHandle phContext,
1767 ULONG ulAttribute, void* pBuffer)
1768{
1769 if (!phContext)
1770 return SEC_E_INVALID_HANDLE;
1771
1772 if (!pBuffer)
1773 return SEC_E_INVALID_PARAMETER;
1774
1775#ifdef WITH_KRB5
1776 KRB_CONTEXT* context = get_context(phContext);
1777 if (!context)
1778 return SEC_E_INVALID_PARAMETER;
1779
1780 KRB_CREDENTIALS* credentials = context->credentials;
1781
1782 switch (ulAttribute)
1783 {
1784 case SECPKG_ATTR_SIZES:
1785 return kerberos_ATTR_SIZES(context, credentials, (SecPkgContext_Sizes*)pBuffer);
1786
1787 case SECPKG_CRED_ATTR_TICKET_LOGON:
1788 return kerberos_ATTR_TICKET_LOGON(context, credentials, (KERB_TICKET_LOGON*)pBuffer);
1789
1790 default:
1791 WLog_ERR(TAG, "TODO: QueryContextAttributes implement ulAttribute=0x%08" PRIx32,
1792 ulAttribute);
1793 return SEC_E_UNSUPPORTED_FUNCTION;
1794 }
1795#else
1796 return SEC_E_UNSUPPORTED_FUNCTION;
1797#endif
1798}
1799
1800static SECURITY_STATUS SEC_ENTRY kerberos_QueryContextAttributesW(PCtxtHandle phContext,
1801 ULONG ulAttribute, void* pBuffer)
1802{
1803 return kerberos_QueryContextAttributesA(phContext, ulAttribute, pBuffer);
1804}
1805
1806static SECURITY_STATUS SEC_ENTRY kerberos_SetContextAttributesW(
1807 WINPR_ATTR_UNUSED PCtxtHandle phContext, WINPR_ATTR_UNUSED ULONG ulAttribute,
1808 WINPR_ATTR_UNUSED void* pBuffer, WINPR_ATTR_UNUSED ULONG cbBuffer)
1809{
1810 return SEC_E_UNSUPPORTED_FUNCTION;
1811}
1812
1813static SECURITY_STATUS SEC_ENTRY kerberos_SetContextAttributesA(
1814 WINPR_ATTR_UNUSED PCtxtHandle phContext, WINPR_ATTR_UNUSED ULONG ulAttribute,
1815 WINPR_ATTR_UNUSED void* pBuffer, WINPR_ATTR_UNUSED ULONG cbBuffer)
1816{
1817 return SEC_E_UNSUPPORTED_FUNCTION;
1818}
1819
1820static SECURITY_STATUS SEC_ENTRY kerberos_SetCredentialsAttributesX(PCredHandle phCredential,
1821 ULONG ulAttribute,
1822 void* pBuffer, ULONG cbBuffer,
1823 WINPR_ATTR_UNUSED BOOL unicode)
1824{
1825#ifdef WITH_KRB5
1826 KRB_CREDENTIALS* credentials = NULL;
1827
1828 if (!phCredential)
1829 return SEC_E_INVALID_HANDLE;
1830
1831 credentials = sspi_SecureHandleGetLowerPointer(phCredential);
1832
1833 if (!credentials)
1834 return SEC_E_INVALID_HANDLE;
1835
1836 if (!pBuffer)
1837 return SEC_E_INSUFFICIENT_MEMORY;
1838
1839 switch (ulAttribute)
1840 {
1841 case SECPKG_CRED_ATTR_KDC_PROXY_SETTINGS:
1842 {
1843 SecPkgCredentials_KdcProxySettingsW* kdc_settings = pBuffer;
1844
1845 /* Sanity checks */
1846 if (cbBuffer < sizeof(SecPkgCredentials_KdcProxySettingsW) ||
1847 kdc_settings->Version != KDC_PROXY_SETTINGS_V1 ||
1848 kdc_settings->ProxyServerOffset < sizeof(SecPkgCredentials_KdcProxySettingsW) ||
1849 cbBuffer < sizeof(SecPkgCredentials_KdcProxySettingsW) +
1850 kdc_settings->ProxyServerOffset + kdc_settings->ProxyServerLength)
1851 return SEC_E_INVALID_TOKEN;
1852
1853 if (credentials->kdc_url)
1854 {
1855 free(credentials->kdc_url);
1856 credentials->kdc_url = NULL;
1857 }
1858
1859 if (kdc_settings->ProxyServerLength > 0)
1860 {
1861 WCHAR* proxy = (WCHAR*)((BYTE*)pBuffer + kdc_settings->ProxyServerOffset);
1862
1863 credentials->kdc_url = ConvertWCharNToUtf8Alloc(
1864 proxy, kdc_settings->ProxyServerLength / sizeof(WCHAR), NULL);
1865 if (!credentials->kdc_url)
1866 return SEC_E_INSUFFICIENT_MEMORY;
1867 }
1868
1869 return SEC_E_OK;
1870 }
1871 case SECPKG_CRED_ATTR_NAMES:
1872 case SECPKG_ATTR_SUPPORTED_ALGS:
1873 default:
1874 WLog_ERR(TAG, "TODO: SetCredentialsAttributesX implement ulAttribute=0x%08" PRIx32,
1875 ulAttribute);
1876 return SEC_E_UNSUPPORTED_FUNCTION;
1877 }
1878
1879#else
1880 return SEC_E_UNSUPPORTED_FUNCTION;
1881#endif
1882}
1883
1884static SECURITY_STATUS SEC_ENTRY kerberos_SetCredentialsAttributesW(PCredHandle phCredential,
1885 ULONG ulAttribute,
1886 void* pBuffer, ULONG cbBuffer)
1887{
1888 return kerberos_SetCredentialsAttributesX(phCredential, ulAttribute, pBuffer, cbBuffer, TRUE);
1889}
1890
1891static SECURITY_STATUS SEC_ENTRY kerberos_SetCredentialsAttributesA(PCredHandle phCredential,
1892 ULONG ulAttribute,
1893 void* pBuffer, ULONG cbBuffer)
1894{
1895 return kerberos_SetCredentialsAttributesX(phCredential, ulAttribute, pBuffer, cbBuffer, FALSE);
1896}
1897
1898static SECURITY_STATUS SEC_ENTRY kerberos_EncryptMessage(PCtxtHandle phContext, ULONG fQOP,
1899 PSecBufferDesc pMessage,
1900 ULONG MessageSeqNo)
1901{
1902#ifdef WITH_KRB5
1903 KRB_CONTEXT* context = get_context(phContext);
1904 PSecBuffer sig_buffer = NULL;
1905 PSecBuffer data_buffer = NULL;
1906 char* header = NULL;
1907 BYTE flags = 0;
1908 krb5glue_key key = NULL;
1909 krb5_keyusage usage = 0;
1910 krb5_crypto_iov encrypt_iov[] = { { KRB5_CRYPTO_TYPE_HEADER, { 0 } },
1911 { KRB5_CRYPTO_TYPE_DATA, { 0 } },
1912 { KRB5_CRYPTO_TYPE_DATA, { 0 } },
1913 { KRB5_CRYPTO_TYPE_PADDING, { 0 } },
1914 { KRB5_CRYPTO_TYPE_TRAILER, { 0 } } };
1915
1916 if (!context)
1917 return SEC_E_INVALID_HANDLE;
1918
1919 if (!(context->flags & SSPI_GSS_C_CONF_FLAG))
1920 return SEC_E_UNSUPPORTED_FUNCTION;
1921
1922 KRB_CREDENTIALS* creds = context->credentials;
1923
1924 sig_buffer = sspi_FindSecBuffer(pMessage, SECBUFFER_TOKEN);
1925 data_buffer = sspi_FindSecBuffer(pMessage, SECBUFFER_DATA);
1926
1927 if (!sig_buffer || !data_buffer)
1928 return SEC_E_INVALID_TOKEN;
1929
1930 if (fQOP)
1931 return SEC_E_QOP_NOT_SUPPORTED;
1932
1933 flags |= context->acceptor ? FLAG_SENDER_IS_ACCEPTOR : 0;
1934 flags |= FLAG_WRAP_CONFIDENTIAL;
1935
1936 key = get_key(&context->keyset);
1937 if (!key)
1938 return SEC_E_INTERNAL_ERROR;
1939
1940 flags |= context->keyset.acceptor_key == key ? FLAG_ACCEPTOR_SUBKEY : 0;
1941
1942 usage = context->acceptor ? KG_USAGE_ACCEPTOR_SEAL : KG_USAGE_INITIATOR_SEAL;
1943
1944 /* Set the lengths of the data (plaintext + header) */
1945 encrypt_iov[1].data.length = data_buffer->cbBuffer;
1946 encrypt_iov[2].data.length = 16;
1947
1948 /* Get the lengths of the header, trailer, and padding and ensure sig_buffer is large enough */
1949 if (krb_log_exec(krb5glue_crypto_length_iov, creds->ctx, key, encrypt_iov,
1950 ARRAYSIZE(encrypt_iov)))
1951 return SEC_E_INTERNAL_ERROR;
1952 if (sig_buffer->cbBuffer <
1953 encrypt_iov[0].data.length + encrypt_iov[3].data.length + encrypt_iov[4].data.length + 32)
1954 return SEC_E_INSUFFICIENT_MEMORY;
1955
1956 /* Set up the iov array in sig_buffer */
1957 header = sig_buffer->pvBuffer;
1958 encrypt_iov[2].data.data = header + 16;
1959 encrypt_iov[3].data.data = encrypt_iov[2].data.data + encrypt_iov[2].data.length;
1960 encrypt_iov[4].data.data = encrypt_iov[3].data.data + encrypt_iov[3].data.length;
1961 encrypt_iov[0].data.data = encrypt_iov[4].data.data + encrypt_iov[4].data.length;
1962 encrypt_iov[1].data.data = data_buffer->pvBuffer;
1963
1964 /* Write the GSS header with 0 in RRC */
1965 winpr_Data_Write_UINT16_BE(header, TOK_ID_WRAP);
1966 header[2] = WINPR_ASSERTING_INT_CAST(char, flags);
1967 header[3] = (char)0xFF;
1968 winpr_Data_Write_UINT32(header + 4, 0);
1969 winpr_Data_Write_UINT64_BE(header + 8, (context->local_seq + MessageSeqNo));
1970
1971 /* Copy header to be encrypted */
1972 CopyMemory(encrypt_iov[2].data.data, header, 16);
1973
1974 /* Set the correct RRC */
1975 const size_t len = 16 + encrypt_iov[3].data.length + encrypt_iov[4].data.length;
1976 winpr_Data_Write_UINT16_BE(header + 6, WINPR_ASSERTING_INT_CAST(UINT16, len));
1977
1978 if (krb_log_exec(krb5glue_encrypt_iov, creds->ctx, key, usage, encrypt_iov,
1979 ARRAYSIZE(encrypt_iov)))
1980 return SEC_E_INTERNAL_ERROR;
1981
1982 return SEC_E_OK;
1983#else
1984 return SEC_E_UNSUPPORTED_FUNCTION;
1985#endif
1986}
1987
1988static SECURITY_STATUS SEC_ENTRY kerberos_DecryptMessage(PCtxtHandle phContext,
1989 PSecBufferDesc pMessage,
1990 ULONG MessageSeqNo, ULONG* pfQOP)
1991{
1992#ifdef WITH_KRB5
1993 KRB_CONTEXT* context = get_context(phContext);
1994 PSecBuffer sig_buffer = NULL;
1995 PSecBuffer data_buffer = NULL;
1996 krb5glue_key key = NULL;
1997 krb5_keyusage usage = 0;
1998 uint16_t tok_id = 0;
1999 BYTE flags = 0;
2000 uint16_t ec = 0;
2001 uint16_t rrc = 0;
2002 uint64_t seq_no = 0;
2003 krb5_crypto_iov iov[] = { { KRB5_CRYPTO_TYPE_HEADER, { 0 } },
2004 { KRB5_CRYPTO_TYPE_DATA, { 0 } },
2005 { KRB5_CRYPTO_TYPE_DATA, { 0 } },
2006 { KRB5_CRYPTO_TYPE_PADDING, { 0 } },
2007 { KRB5_CRYPTO_TYPE_TRAILER, { 0 } } };
2008
2009 if (!context)
2010 return SEC_E_INVALID_HANDLE;
2011
2012 if (!(context->flags & SSPI_GSS_C_CONF_FLAG))
2013 return SEC_E_UNSUPPORTED_FUNCTION;
2014
2015 KRB_CREDENTIALS* creds = context->credentials;
2016
2017 sig_buffer = sspi_FindSecBuffer(pMessage, SECBUFFER_TOKEN);
2018 data_buffer = sspi_FindSecBuffer(pMessage, SECBUFFER_DATA);
2019
2020 if (!sig_buffer || !data_buffer || sig_buffer->cbBuffer < 16)
2021 return SEC_E_INVALID_TOKEN;
2022
2023 /* Read in header information */
2024 BYTE* header = sig_buffer->pvBuffer;
2025 tok_id = winpr_Data_Get_UINT16_BE(header);
2026 flags = header[2];
2027 ec = winpr_Data_Get_UINT16_BE(&header[4]);
2028 rrc = winpr_Data_Get_UINT16_BE(&header[6]);
2029 seq_no = winpr_Data_Get_UINT64_BE(&header[8]);
2030
2031 /* Check that the header is valid */
2032 if ((tok_id != TOK_ID_WRAP) || (header[3] != 0xFF))
2033 return SEC_E_INVALID_TOKEN;
2034
2035 if ((flags & FLAG_SENDER_IS_ACCEPTOR) == context->acceptor)
2036 return SEC_E_INVALID_TOKEN;
2037
2038 if ((context->flags & ISC_REQ_SEQUENCE_DETECT) &&
2039 (seq_no != context->remote_seq + MessageSeqNo))
2040 return SEC_E_OUT_OF_SEQUENCE;
2041
2042 if (!(flags & FLAG_WRAP_CONFIDENTIAL))
2043 return SEC_E_INVALID_TOKEN;
2044
2045 /* We don't expect a trailer buffer; the encrypted header must be rotated */
2046 if (rrc < 16)
2047 return SEC_E_INVALID_TOKEN;
2048
2049 /* Find the proper key and key usage */
2050 key = get_key(&context->keyset);
2051 if (!key || ((flags & FLAG_ACCEPTOR_SUBKEY) && (context->keyset.acceptor_key != key)))
2052 return SEC_E_INTERNAL_ERROR;
2053 usage = context->acceptor ? KG_USAGE_INITIATOR_SEAL : KG_USAGE_ACCEPTOR_SEAL;
2054
2055 /* Fill in the lengths of the iov array */
2056 iov[1].data.length = data_buffer->cbBuffer;
2057 iov[2].data.length = 16;
2058 if (krb_log_exec(krb5glue_crypto_length_iov, creds->ctx, key, iov, ARRAYSIZE(iov)))
2059 return SEC_E_INTERNAL_ERROR;
2060
2061 /* We don't expect a trailer buffer; everything must be in sig_buffer */
2062 if (rrc != 16 + iov[3].data.length + iov[4].data.length)
2063 return SEC_E_INVALID_TOKEN;
2064 if (sig_buffer->cbBuffer != 16 + rrc + iov[0].data.length)
2065 return SEC_E_INVALID_TOKEN;
2066
2067 /* Locate the parts of the message */
2068 iov[0].data.data = (char*)&header[16 + rrc + ec];
2069 iov[1].data.data = data_buffer->pvBuffer;
2070 iov[2].data.data = (char*)&header[16 + ec];
2071 char* data2 = iov[2].data.data;
2072 iov[3].data.data = &data2[iov[2].data.length];
2073
2074 char* data3 = iov[3].data.data;
2075 iov[4].data.data = &data3[iov[3].data.length];
2076
2077 if (krb_log_exec(krb5glue_decrypt_iov, creds->ctx, key, usage, iov, ARRAYSIZE(iov)))
2078 return SEC_E_INTERNAL_ERROR;
2079
2080 /* Validate the encrypted header */
2081 winpr_Data_Write_UINT16_BE(iov[2].data.data + 4, ec);
2082 winpr_Data_Write_UINT16_BE(iov[2].data.data + 6, rrc);
2083 if (memcmp(iov[2].data.data, header, 16) != 0)
2084 return SEC_E_MESSAGE_ALTERED;
2085
2086 *pfQOP = 0;
2087
2088 return SEC_E_OK;
2089#else
2090 return SEC_E_UNSUPPORTED_FUNCTION;
2091#endif
2092}
2093
2094static SECURITY_STATUS SEC_ENTRY kerberos_MakeSignature(PCtxtHandle phContext,
2095 WINPR_ATTR_UNUSED ULONG fQOP,
2096 PSecBufferDesc pMessage, ULONG MessageSeqNo)
2097{
2098#ifdef WITH_KRB5
2099 KRB_CONTEXT* context = get_context(phContext);
2100 PSecBuffer sig_buffer = NULL;
2101 PSecBuffer data_buffer = NULL;
2102 krb5glue_key key = NULL;
2103 krb5_keyusage usage = 0;
2104 BYTE flags = 0;
2105 krb5_crypto_iov iov[] = { { KRB5_CRYPTO_TYPE_DATA, { 0 } },
2106 { KRB5_CRYPTO_TYPE_DATA, { 0 } },
2107 { KRB5_CRYPTO_TYPE_CHECKSUM, { 0 } } };
2108
2109 if (!context)
2110 return SEC_E_INVALID_HANDLE;
2111
2112 if (!(context->flags & SSPI_GSS_C_INTEG_FLAG))
2113 return SEC_E_UNSUPPORTED_FUNCTION;
2114
2115 KRB_CREDENTIALS* creds = context->credentials;
2116
2117 sig_buffer = sspi_FindSecBuffer(pMessage, SECBUFFER_TOKEN);
2118 data_buffer = sspi_FindSecBuffer(pMessage, SECBUFFER_DATA);
2119
2120 if (!sig_buffer || !data_buffer)
2121 return SEC_E_INVALID_TOKEN;
2122
2123 flags |= context->acceptor ? FLAG_SENDER_IS_ACCEPTOR : 0;
2124
2125 key = get_key(&context->keyset);
2126 if (!key)
2127 return SEC_E_INTERNAL_ERROR;
2128 usage = context->acceptor ? KG_USAGE_ACCEPTOR_SIGN : KG_USAGE_INITIATOR_SIGN;
2129
2130 flags |= context->keyset.acceptor_key == key ? FLAG_ACCEPTOR_SUBKEY : 0;
2131
2132 /* Fill in the lengths of the iov array */
2133 iov[0].data.length = data_buffer->cbBuffer;
2134 iov[1].data.length = 16;
2135 if (krb_log_exec(krb5glue_crypto_length_iov, creds->ctx, key, iov, ARRAYSIZE(iov)))
2136 return SEC_E_INTERNAL_ERROR;
2137
2138 /* Ensure the buffer is big enough */
2139 if (sig_buffer->cbBuffer < iov[2].data.length + 16)
2140 return SEC_E_INSUFFICIENT_MEMORY;
2141
2142 /* Write the header */
2143 char* header = sig_buffer->pvBuffer;
2144 winpr_Data_Write_UINT16_BE(header, TOK_ID_MIC);
2145 header[2] = WINPR_ASSERTING_INT_CAST(char, flags);
2146 memset(header + 3, 0xFF, 5);
2147 winpr_Data_Write_UINT64_BE(header + 8, (context->local_seq + MessageSeqNo));
2148
2149 /* Set up the iov array */
2150 iov[0].data.data = data_buffer->pvBuffer;
2151 iov[1].data.data = header;
2152 iov[2].data.data = header + 16;
2153
2154 if (krb_log_exec(krb5glue_make_checksum_iov, creds->ctx, key, usage, iov, ARRAYSIZE(iov)))
2155 return SEC_E_INTERNAL_ERROR;
2156
2157 sig_buffer->cbBuffer = iov[2].data.length + 16;
2158
2159 return SEC_E_OK;
2160#else
2161 return SEC_E_UNSUPPORTED_FUNCTION;
2162#endif
2163}
2164
2165static SECURITY_STATUS SEC_ENTRY kerberos_VerifySignature(PCtxtHandle phContext,
2166 PSecBufferDesc pMessage,
2167 ULONG MessageSeqNo,
2168 WINPR_ATTR_UNUSED ULONG* pfQOP)
2169{
2170#ifdef WITH_KRB5
2171 PSecBuffer sig_buffer = NULL;
2172 PSecBuffer data_buffer = NULL;
2173 krb5glue_key key = NULL;
2174 krb5_keyusage usage = 0;
2175 BYTE flags = 0;
2176 uint16_t tok_id = 0;
2177 uint64_t seq_no = 0;
2178 krb5_boolean is_valid = 0;
2179 krb5_crypto_iov iov[] = { { KRB5_CRYPTO_TYPE_DATA, { 0 } },
2180 { KRB5_CRYPTO_TYPE_DATA, { 0 } },
2181 { KRB5_CRYPTO_TYPE_CHECKSUM, { 0 } } };
2182 BYTE cmp_filler[] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
2183
2184 KRB_CONTEXT* context = get_context(phContext);
2185 if (!context)
2186 return SEC_E_INVALID_HANDLE;
2187
2188 if (!(context->flags & SSPI_GSS_C_INTEG_FLAG))
2189 return SEC_E_UNSUPPORTED_FUNCTION;
2190
2191 sig_buffer = sspi_FindSecBuffer(pMessage, SECBUFFER_TOKEN);
2192 data_buffer = sspi_FindSecBuffer(pMessage, SECBUFFER_DATA);
2193
2194 if (!sig_buffer || !data_buffer || sig_buffer->cbBuffer < 16)
2195 return SEC_E_INVALID_TOKEN;
2196
2197 /* Read in header info */
2198 BYTE* header = sig_buffer->pvBuffer;
2199 tok_id = winpr_Data_Get_UINT16_BE(header);
2200 flags = header[2];
2201 seq_no = winpr_Data_Get_UINT64_BE((header + 8));
2202
2203 /* Validate header */
2204 if (tok_id != TOK_ID_MIC)
2205 return SEC_E_INVALID_TOKEN;
2206
2207 if ((flags & FLAG_SENDER_IS_ACCEPTOR) == context->acceptor || flags & FLAG_WRAP_CONFIDENTIAL)
2208 return SEC_E_INVALID_TOKEN;
2209
2210 if (memcmp(header + 3, cmp_filler, sizeof(cmp_filler)) != 0)
2211 return SEC_E_INVALID_TOKEN;
2212
2213 if (context->flags & ISC_REQ_SEQUENCE_DETECT && seq_no != context->remote_seq + MessageSeqNo)
2214 return SEC_E_OUT_OF_SEQUENCE;
2215
2216 /* Find the proper key and usage */
2217 key = get_key(&context->keyset);
2218 if (!key || (flags & FLAG_ACCEPTOR_SUBKEY && context->keyset.acceptor_key != key))
2219 return SEC_E_INTERNAL_ERROR;
2220 usage = context->acceptor ? KG_USAGE_INITIATOR_SIGN : KG_USAGE_ACCEPTOR_SIGN;
2221
2222 /* Fill in the iov array lengths */
2223 KRB_CREDENTIALS* creds = context->credentials;
2224 iov[0].data.length = data_buffer->cbBuffer;
2225 iov[1].data.length = 16;
2226 if (krb_log_exec(krb5glue_crypto_length_iov, creds->ctx, key, iov, ARRAYSIZE(iov)))
2227 return SEC_E_INTERNAL_ERROR;
2228
2229 if (sig_buffer->cbBuffer != iov[2].data.length + 16)
2230 return SEC_E_INTERNAL_ERROR;
2231
2232 /* Set up the iov array */
2233 iov[0].data.data = data_buffer->pvBuffer;
2234 iov[1].data.data = (char*)header;
2235 iov[2].data.data = (char*)&header[16];
2236
2237 if (krb_log_exec(krb5glue_verify_checksum_iov, creds->ctx, key, usage, iov, ARRAYSIZE(iov),
2238 &is_valid))
2239 return SEC_E_INTERNAL_ERROR;
2240
2241 if (!is_valid)
2242 return SEC_E_MESSAGE_ALTERED;
2243
2244 return SEC_E_OK;
2245#else
2246 return SEC_E_UNSUPPORTED_FUNCTION;
2247#endif
2248}
2249
2250const SecurityFunctionTableA KERBEROS_SecurityFunctionTableA = {
2251 3, /* dwVersion */
2252 NULL, /* EnumerateSecurityPackages */
2253 kerberos_QueryCredentialsAttributesA, /* QueryCredentialsAttributes */
2254 kerberos_AcquireCredentialsHandleA, /* AcquireCredentialsHandle */
2255 kerberos_FreeCredentialsHandle, /* FreeCredentialsHandle */
2256 NULL, /* Reserved2 */
2257 kerberos_InitializeSecurityContextA, /* InitializeSecurityContext */
2258 kerberos_AcceptSecurityContext, /* AcceptSecurityContext */
2259 NULL, /* CompleteAuthToken */
2260 kerberos_DeleteSecurityContext, /* DeleteSecurityContext */
2261 NULL, /* ApplyControlToken */
2262 kerberos_QueryContextAttributesA, /* QueryContextAttributes */
2263 NULL, /* ImpersonateSecurityContext */
2264 NULL, /* RevertSecurityContext */
2265 kerberos_MakeSignature, /* MakeSignature */
2266 kerberos_VerifySignature, /* VerifySignature */
2267 NULL, /* FreeContextBuffer */
2268 NULL, /* QuerySecurityPackageInfo */
2269 NULL, /* Reserved3 */
2270 NULL, /* Reserved4 */
2271 NULL, /* ExportSecurityContext */
2272 NULL, /* ImportSecurityContext */
2273 NULL, /* AddCredentials */
2274 NULL, /* Reserved8 */
2275 NULL, /* QuerySecurityContextToken */
2276 kerberos_EncryptMessage, /* EncryptMessage */
2277 kerberos_DecryptMessage, /* DecryptMessage */
2278 kerberos_SetContextAttributesA, /* SetContextAttributes */
2279 kerberos_SetCredentialsAttributesA, /* SetCredentialsAttributes */
2280};
2281
2282const SecurityFunctionTableW KERBEROS_SecurityFunctionTableW = {
2283 3, /* dwVersion */
2284 NULL, /* EnumerateSecurityPackages */
2285 kerberos_QueryCredentialsAttributesW, /* QueryCredentialsAttributes */
2286 kerberos_AcquireCredentialsHandleW, /* AcquireCredentialsHandle */
2287 kerberos_FreeCredentialsHandle, /* FreeCredentialsHandle */
2288 NULL, /* Reserved2 */
2289 kerberos_InitializeSecurityContextW, /* InitializeSecurityContext */
2290 kerberos_AcceptSecurityContext, /* AcceptSecurityContext */
2291 NULL, /* CompleteAuthToken */
2292 kerberos_DeleteSecurityContext, /* DeleteSecurityContext */
2293 NULL, /* ApplyControlToken */
2294 kerberos_QueryContextAttributesW, /* QueryContextAttributes */
2295 NULL, /* ImpersonateSecurityContext */
2296 NULL, /* RevertSecurityContext */
2297 kerberos_MakeSignature, /* MakeSignature */
2298 kerberos_VerifySignature, /* VerifySignature */
2299 NULL, /* FreeContextBuffer */
2300 NULL, /* QuerySecurityPackageInfo */
2301 NULL, /* Reserved3 */
2302 NULL, /* Reserved4 */
2303 NULL, /* ExportSecurityContext */
2304 NULL, /* ImportSecurityContext */
2305 NULL, /* AddCredentials */
2306 NULL, /* Reserved8 */
2307 NULL, /* QuerySecurityContextToken */
2308 kerberos_EncryptMessage, /* EncryptMessage */
2309 kerberos_DecryptMessage, /* DecryptMessage */
2310 kerberos_SetContextAttributesW, /* SetContextAttributes */
2311 kerberos_SetCredentialsAttributesW, /* SetCredentialsAttributes */
2312};
2313
2314BOOL KERBEROS_init(void)
2315{
2316 InitializeConstWCharFromUtf8(KERBEROS_SecPkgInfoA.Name, KERBEROS_SecPkgInfoW_NameBuffer,
2317 ARRAYSIZE(KERBEROS_SecPkgInfoW_NameBuffer));
2318 InitializeConstWCharFromUtf8(KERBEROS_SecPkgInfoA.Comment, KERBEROS_SecPkgInfoW_CommentBuffer,
2319 ARRAYSIZE(KERBEROS_SecPkgInfoW_CommentBuffer));
2320 return TRUE;
2321}