Coverage Report

Created: 2026-11-10 06:39

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