Coverage Report

Created: 2026-02-26 06:50

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