Coverage Report

Created: 2026-10-28 06:53

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