Coverage Report

Created: 2026-01-09 06:43

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