Coverage Report

Created: 2025-08-26 06:37

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