Coverage Report

Created: 2025-07-01 06:46

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