Coverage Report

Created: 2026-10-15 06:31

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