Coverage Report

Created: 2024-09-08 06:16

/src/FreeRDP/winpr/libwinpr/sspi/Kerberos/kerberos.c
Line
Count
Source (jump to first uncovered line)
1
/**
2
 * FreeRDP: A Remote Desktop Protocol Client
3
 * Kerberos Auth Protocol
4
 *
5
 * Copyright 2015 ANSSI, Author Thomas Calderon
6
 * Copyright 2017 Dorian Ducournau <dorian.ducournau@gmail.com>
7
 * Copyright 2022 David Fort <contact@hardening-consulting.com>
8
 * Copyright 2022 Isaac Klein <fifthdegree@protonmail.com>
9
 *
10
 * Licensed under the Apache License, Version 2.0 (the "License");
11
 * you may not use this file except in compliance with the License.
12
 * You may obtain a copy of the License at
13
 *
14
 * http://www.apache.org/licenses/LICENSE-2.0
15
 *
16
 * Unless required by applicable law or agreed to in writing, software
17
 * distributed under the License is distributed on an "AS IS" BASIS,
18
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
 * See the License for the specific language governing permissions and
20
 * limitations under the License.
21
 */
22
#include <winpr/config.h>
23
24
#include <stdio.h>
25
#include <stdlib.h>
26
#include <string.h>
27
#include <errno.h>
28
#include <fcntl.h>
29
#include <ctype.h>
30
31
#include <winpr/assert.h>
32
#include <winpr/crt.h>
33
#include <winpr/sspi.h>
34
#include <winpr/print.h>
35
#include <winpr/tchar.h>
36
#include <winpr/sysinfo.h>
37
#include <winpr/registry.h>
38
#include <winpr/endian.h>
39
#include <winpr/crypto.h>
40
#include <winpr/path.h>
41
#include <winpr/wtypes.h>
42
#include <winpr/winsock.h>
43
44
#include "kerberos.h"
45
46
#ifdef WITH_KRB5_MIT
47
#include "krb5glue.h"
48
#include <profile.h>
49
#endif
50
51
#ifdef WITH_KRB5_HEIMDAL
52
#include "krb5glue.h"
53
#include <krb5-protos.h>
54
#endif
55
56
#include "../sspi.h"
57
#include "../../log.h"
58
0
#define TAG WINPR_TAG("sspi.Kerberos")
59
60
0
#define KRB_TGT_REQ 16
61
0
#define KRB_TGT_REP 17
62
63
const SecPkgInfoA KERBEROS_SecPkgInfoA = {
64
  0x000F3BBF,                 /* fCapabilities */
65
  1,                          /* wVersion */
66
  0x0010,                     /* wRPCID */
67
  0x0000BB80,                 /* cbMaxToken : 48k bytes maximum for Windows Server 2012 */
68
  "Kerberos",                 /* Name */
69
  "Kerberos Security Package" /* Comment */
70
};
71
72
static WCHAR KERBEROS_SecPkgInfoW_NameBuffer[32] = { 0 };
73
static WCHAR KERBEROS_SecPkgInfoW_CommentBuffer[32] = { 0 };
74
75
const SecPkgInfoW KERBEROS_SecPkgInfoW = {
76
  0x000F3BBF,                        /* fCapabilities */
77
  1,                                 /* wVersion */
78
  0x0010,                            /* wRPCID */
79
  0x0000BB80,                        /* cbMaxToken : 48k bytes maximum for Windows Server 2012 */
80
  KERBEROS_SecPkgInfoW_NameBuffer,   /* Name */
81
  KERBEROS_SecPkgInfoW_CommentBuffer /* Comment */
82
};
83
84
#ifdef WITH_KRB5
85
86
enum KERBEROS_STATE
87
{
88
  KERBEROS_STATE_INITIAL,
89
  KERBEROS_STATE_TGT_REQ,
90
  KERBEROS_STATE_TGT_REP,
91
  KERBEROS_STATE_AP_REQ,
92
  KERBEROS_STATE_AP_REP,
93
  KERBEROS_STATE_FINAL
94
};
95
96
struct s_KRB_CONTEXT
97
{
98
  enum KERBEROS_STATE state;
99
  krb5_context ctx;
100
  krb5_auth_context auth_ctx;
101
  BOOL acceptor;
102
  uint32_t flags;
103
  uint64_t local_seq;
104
  uint64_t remote_seq;
105
  struct krb5glue_keyset keyset;
106
  BOOL u2u;
107
};
108
109
typedef struct KRB_CREDENTIALS_st
110
{
111
  char* kdc_url;
112
  krb5_ccache ccache;
113
  krb5_keytab keytab;
114
  krb5_keytab client_keytab;
115
  BOOL own_ccache; /**< Whether we created ccache, and must destroy it after use.  */
116
} KRB_CREDENTIALS;
117
118
static const WinPrAsn1_OID kerberos_OID = { 9, (void*)"\x2a\x86\x48\x86\xf7\x12\x01\x02\x02" };
119
static const WinPrAsn1_OID kerberos_u2u_OID = { 10,
120
                                              (void*)"\x2a\x86\x48\x86\xf7\x12\x01\x02\x02\x03" };
121
122
#define krb_log_exec(fkt, ctx, ...) \
123
0
  kerberos_log_msg(ctx, fkt(ctx, ##__VA_ARGS__), #fkt, __FILE__, __func__, __LINE__)
124
#define krb_log_exec_ptr(fkt, ctx, ...) \
125
0
  kerberos_log_msg(*ctx, fkt(ctx, ##__VA_ARGS__), #fkt, __FILE__, __func__, __LINE__)
126
static krb5_error_code kerberos_log_msg(krb5_context ctx, krb5_error_code code, const char* what,
127
                                        const char* file, const char* fkt, size_t line)
128
0
{
129
0
  switch (code)
130
0
  {
131
0
    case 0:
132
0
    case KRB5_KT_END:
133
0
      break;
134
0
    default:
135
0
    {
136
0
      const DWORD level = WLOG_ERROR;
137
138
0
      wLog* log = WLog_Get(TAG);
139
0
      if (WLog_IsLevelActive(log, level))
140
0
      {
141
0
        const char* msg = krb5_get_error_message(ctx, code);
142
0
        WLog_PrintMessage(log, WLOG_MESSAGE_TEXT, level, line, file, fkt, "%s (%s [%d])",
143
0
                          what, msg, code);
144
0
        krb5_free_error_message(ctx, msg);
145
0
      }
146
0
    }
147
0
    break;
148
0
  }
149
0
  return code;
150
0
}
151
152
static void kerberos_ContextFree(KRB_CONTEXT* ctx, BOOL allocated)
153
0
{
154
0
  if (ctx && ctx->ctx)
155
0
  {
156
0
    krb5glue_keys_free(ctx->ctx, &ctx->keyset);
157
158
0
    if (ctx->auth_ctx)
159
0
      krb5_auth_con_free(ctx->ctx, ctx->auth_ctx);
160
161
0
    krb5_free_context(ctx->ctx);
162
0
  }
163
0
  if (allocated)
164
0
    free(ctx);
165
0
}
166
167
static KRB_CONTEXT* kerberos_ContextNew(void)
168
0
{
169
0
  KRB_CONTEXT* context = NULL;
170
171
0
  context = (KRB_CONTEXT*)calloc(1, sizeof(KRB_CONTEXT));
172
0
  if (!context)
173
0
    return NULL;
174
175
0
  return context;
176
0
}
177
178
static krb5_error_code krb5_prompter(krb5_context context, void* data, const char* name,
179
                                     const char* banner, int num_prompts, krb5_prompt prompts[])
180
0
{
181
0
  for (int i = 0; i < num_prompts; i++)
182
0
  {
183
0
    krb5_prompt_type type = krb5glue_get_prompt_type(context, prompts, i);
184
0
    if (type && (type == KRB5_PROMPT_TYPE_PREAUTH || type == KRB5_PROMPT_TYPE_PASSWORD) && data)
185
0
    {
186
0
      prompts[i].reply->data = _strdup((const char*)data);
187
0
      prompts[i].reply->length = strlen((const char*)data);
188
0
    }
189
0
  }
190
0
  return 0;
191
0
}
192
193
static INLINE krb5glue_key get_key(struct krb5glue_keyset* keyset)
194
0
{
195
0
  return keyset->acceptor_key    ? keyset->acceptor_key
196
0
         : keyset->initiator_key ? keyset->initiator_key
197
0
                                 : keyset->session_key;
198
0
}
199
200
static BOOL isValidIPv4(const char* ipAddress)
201
0
{
202
0
  struct sockaddr_in sa = { 0 };
203
0
  int result = inet_pton(AF_INET, ipAddress, &(sa.sin_addr));
204
0
  return result != 0;
205
0
}
206
207
static BOOL isValidIPv6(const char* ipAddress)
208
0
{
209
0
  struct sockaddr_in6 sa = { 0 };
210
0
  int result = inet_pton(AF_INET6, ipAddress, &(sa.sin6_addr));
211
0
  return result != 0;
212
0
}
213
214
static BOOL isValidIP(const char* ipAddress)
215
0
{
216
0
  return isValidIPv4(ipAddress) || isValidIPv6(ipAddress);
217
0
}
218
219
#endif /* WITH_KRB5 */
220
221
static SECURITY_STATUS SEC_ENTRY kerberos_AcquireCredentialsHandleA(
222
    SEC_CHAR* pszPrincipal, SEC_CHAR* pszPackage, ULONG fCredentialUse, void* pvLogonID,
223
    void* pAuthData, SEC_GET_KEY_FN pGetKeyFn, void* pvGetKeyArgument, PCredHandle phCredential,
224
    PTimeStamp ptsExpiry)
225
0
{
226
0
#ifdef WITH_KRB5
227
0
  SEC_WINPR_KERBEROS_SETTINGS* krb_settings = NULL;
228
0
  KRB_CREDENTIALS* credentials = NULL;
229
0
  krb5_context ctx = NULL;
230
0
  krb5_ccache ccache = NULL;
231
0
  krb5_keytab keytab = NULL;
232
0
  krb5_principal principal = NULL;
233
0
  char* domain = NULL;
234
0
  char* username = NULL;
235
0
  char* password = NULL;
236
0
  BOOL own_ccache = FALSE;
237
0
  const char* const default_ccache_type = "MEMORY";
238
239
0
  if (pAuthData)
240
0
  {
241
0
    UINT32 identityFlags = sspi_GetAuthIdentityFlags(pAuthData);
242
243
0
    if (identityFlags & SEC_WINNT_AUTH_IDENTITY_EXTENDED)
244
0
      krb_settings = (((SEC_WINNT_AUTH_IDENTITY_WINPR*)pAuthData)->kerberosSettings);
245
246
0
    if (!sspi_CopyAuthIdentityFieldsA((const SEC_WINNT_AUTH_IDENTITY_INFO*)pAuthData, &username,
247
0
                                      &domain, &password))
248
0
    {
249
0
      WLog_ERR(TAG, "Failed to copy auth identity fields");
250
0
      goto cleanup;
251
0
    }
252
253
0
    if (!pszPrincipal)
254
0
      pszPrincipal = username;
255
0
  }
256
257
0
  if (krb_log_exec_ptr(krb5_init_context, &ctx))
258
0
    goto cleanup;
259
260
0
  if (domain)
261
0
  {
262
0
    char* udomain = _strdup(domain);
263
0
    if (!udomain)
264
0
      goto cleanup;
265
266
0
    CharUpperA(udomain);
267
    /* Will use domain if realm is not specified in username */
268
0
    krb5_error_code rv = krb_log_exec(krb5_set_default_realm, ctx, udomain);
269
0
    free(udomain);
270
271
0
    if (rv)
272
0
      goto cleanup;
273
0
  }
274
275
0
  if (pszPrincipal)
276
0
  {
277
0
    char* cpszPrincipal = _strdup(pszPrincipal);
278
0
    if (!cpszPrincipal)
279
0
      goto cleanup;
280
281
    /* Find realm component if included and convert to uppercase */
282
0
    char* p = strchr(cpszPrincipal, '@');
283
0
    if (p)
284
0
      CharUpperA(p);
285
286
0
    krb5_error_code rv = krb_log_exec(krb5_parse_name, ctx, cpszPrincipal, &principal);
287
0
    free(cpszPrincipal);
288
289
0
    if (rv)
290
0
      goto cleanup;
291
0
  }
292
293
0
  if (krb_settings && krb_settings->cache)
294
0
  {
295
0
    if ((krb_log_exec(krb5_cc_set_default_name, ctx, krb_settings->cache)))
296
0
      goto cleanup;
297
0
  }
298
0
  else
299
0
    own_ccache = TRUE;
300
301
0
  if (principal)
302
0
  {
303
    /* Use the default cache if it's initialized with the right principal */
304
0
    if (krb5_cc_cache_match(ctx, principal, &ccache) == KRB5_CC_NOTFOUND)
305
0
    {
306
0
      if (own_ccache)
307
0
      {
308
0
        if (krb_log_exec(krb5_cc_new_unique, ctx, default_ccache_type, 0, &ccache))
309
0
          goto cleanup;
310
0
      }
311
0
      else
312
0
      {
313
0
        if (krb_log_exec(krb5_cc_resolve, ctx, krb_settings->cache, &ccache))
314
0
          goto cleanup;
315
0
      }
316
317
0
      if (krb_log_exec(krb5_cc_initialize, ctx, ccache, principal))
318
0
        goto cleanup;
319
0
    }
320
0
    else
321
0
      own_ccache = FALSE;
322
0
  }
323
0
  else if (fCredentialUse & SECPKG_CRED_OUTBOUND)
324
0
  {
325
    /* Use the default cache with it's default principal */
326
0
    if (krb_log_exec(krb5_cc_default, ctx, &ccache))
327
0
      goto cleanup;
328
0
    if (krb_log_exec(krb5_cc_get_principal, ctx, ccache, &principal))
329
0
      goto cleanup;
330
0
    own_ccache = FALSE;
331
0
  }
332
0
  else
333
0
  {
334
0
    if (own_ccache)
335
0
    {
336
0
      if (krb_log_exec(krb5_cc_new_unique, ctx, default_ccache_type, 0, &ccache))
337
0
        goto cleanup;
338
0
    }
339
0
    else
340
0
    {
341
0
      if (krb_log_exec(krb5_cc_resolve, ctx, krb_settings->cache, &ccache))
342
0
        goto cleanup;
343
0
    }
344
0
  }
345
346
0
  if (krb_settings && krb_settings->keytab)
347
0
  {
348
0
    if (krb_log_exec(krb5_kt_resolve, ctx, krb_settings->keytab, &keytab))
349
0
      goto cleanup;
350
0
  }
351
0
  else
352
0
  {
353
0
    if (fCredentialUse & SECPKG_CRED_INBOUND)
354
0
      if (krb_log_exec(krb5_kt_default, ctx, &keytab))
355
0
        goto cleanup;
356
0
  }
357
358
  /* Get initial credentials if required */
359
0
  if (fCredentialUse & SECPKG_CRED_OUTBOUND)
360
0
  {
361
0
    if (krb_log_exec(krb5glue_get_init_creds, ctx, principal, ccache, krb5_prompter, password,
362
0
                     krb_settings))
363
0
      goto cleanup;
364
0
  }
365
366
0
  credentials = calloc(1, sizeof(KRB_CREDENTIALS));
367
0
  if (!credentials)
368
0
    goto cleanup;
369
0
  credentials->ccache = ccache;
370
0
  credentials->keytab = keytab;
371
0
  credentials->own_ccache = own_ccache;
372
373
0
cleanup:
374
375
0
  free(domain);
376
0
  free(username);
377
0
  free(password);
378
379
0
  if (principal)
380
0
    krb5_free_principal(ctx, principal);
381
0
  if (ctx)
382
0
  {
383
0
    if (!credentials)
384
0
    {
385
0
      if (ccache)
386
0
      {
387
0
        if (own_ccache)
388
0
          krb5_cc_destroy(ctx, ccache);
389
0
        else
390
0
          krb5_cc_close(ctx, ccache);
391
0
      }
392
0
      if (keytab)
393
0
        krb5_kt_close(ctx, keytab);
394
0
    }
395
0
    krb5_free_context(ctx);
396
0
  }
397
398
  /* If we managed to get credentials set the output */
399
0
  if (credentials)
400
0
  {
401
0
    sspi_SecureHandleSetLowerPointer(phCredential, (void*)credentials);
402
0
    sspi_SecureHandleSetUpperPointer(phCredential, (void*)KERBEROS_SSP_NAME);
403
0
    return SEC_E_OK;
404
0
  }
405
406
0
  return SEC_E_NO_CREDENTIALS;
407
#else
408
  return SEC_E_UNSUPPORTED_FUNCTION;
409
#endif
410
0
}
411
412
static SECURITY_STATUS SEC_ENTRY kerberos_AcquireCredentialsHandleW(
413
    SEC_WCHAR* pszPrincipal, SEC_WCHAR* pszPackage, ULONG fCredentialUse, void* pvLogonID,
414
    void* pAuthData, SEC_GET_KEY_FN pGetKeyFn, void* pvGetKeyArgument, PCredHandle phCredential,
415
    PTimeStamp ptsExpiry)
416
0
{
417
0
  SECURITY_STATUS status = SEC_E_INSUFFICIENT_MEMORY;
418
0
  char* principal = NULL;
419
0
  char* package = NULL;
420
421
0
  if (pszPrincipal)
422
0
  {
423
0
    principal = ConvertWCharToUtf8Alloc(pszPrincipal, NULL);
424
0
    if (!principal)
425
0
      goto fail;
426
0
  }
427
0
  if (pszPackage)
428
0
  {
429
0
    package = ConvertWCharToUtf8Alloc(pszPackage, NULL);
430
0
    if (!package)
431
0
      goto fail;
432
0
  }
433
434
0
  status =
435
0
      kerberos_AcquireCredentialsHandleA(principal, package, fCredentialUse, pvLogonID, pAuthData,
436
0
                                         pGetKeyFn, pvGetKeyArgument, phCredential, ptsExpiry);
437
438
0
fail:
439
0
  free(principal);
440
0
  free(package);
441
442
0
  return status;
443
0
}
444
445
static SECURITY_STATUS SEC_ENTRY kerberos_FreeCredentialsHandle(PCredHandle phCredential)
446
0
{
447
0
#ifdef WITH_KRB5
448
0
  KRB_CREDENTIALS* credentials = NULL;
449
0
  krb5_context ctx = NULL;
450
451
0
  credentials = sspi_SecureHandleGetLowerPointer(phCredential);
452
0
  if (!credentials)
453
0
    return SEC_E_INVALID_HANDLE;
454
455
0
  if (krb5_init_context(&ctx))
456
0
    return SEC_E_INTERNAL_ERROR;
457
458
0
  free(credentials->kdc_url);
459
460
0
  if (credentials->ccache)
461
0
  {
462
0
    if (credentials->own_ccache)
463
0
      krb5_cc_destroy(ctx, credentials->ccache);
464
0
    else
465
0
      krb5_cc_close(ctx, credentials->ccache);
466
0
  }
467
0
  if (credentials->keytab)
468
0
    krb5_kt_close(ctx, credentials->keytab);
469
470
0
  krb5_free_context(ctx);
471
472
0
  free(credentials);
473
474
0
  sspi_SecureHandleInvalidate(phCredential);
475
0
  return SEC_E_OK;
476
#else
477
  return SEC_E_UNSUPPORTED_FUNCTION;
478
#endif
479
0
}
480
481
static SECURITY_STATUS SEC_ENTRY kerberos_QueryCredentialsAttributesW(PCredHandle phCredential,
482
                                                                      ULONG ulAttribute,
483
                                                                      void* pBuffer)
484
0
{
485
0
#ifdef WITH_KRB5
486
0
  if (ulAttribute == SECPKG_CRED_ATTR_NAMES)
487
0
  {
488
0
    return SEC_E_OK;
489
0
  }
490
491
0
  WLog_ERR(TAG, "TODO: Implement ulAttribute=%08" PRIx32, ulAttribute);
492
0
  return SEC_E_UNSUPPORTED_FUNCTION;
493
#else
494
  return SEC_E_UNSUPPORTED_FUNCTION;
495
#endif
496
0
}
497
498
static SECURITY_STATUS SEC_ENTRY kerberos_QueryCredentialsAttributesA(PCredHandle phCredential,
499
                                                                      ULONG ulAttribute,
500
                                                                      void* pBuffer)
501
0
{
502
0
  return kerberos_QueryCredentialsAttributesW(phCredential, ulAttribute, pBuffer);
503
0
}
504
505
#ifdef WITH_KRB5
506
507
static BOOL kerberos_mk_tgt_token(SecBuffer* buf, int msg_type, char* sname, char* host,
508
                                  const krb5_data* ticket)
509
0
{
510
0
  WinPrAsn1Encoder* enc = NULL;
511
0
  WinPrAsn1_MemoryChunk data;
512
0
  wStream s;
513
0
  size_t len = 0;
514
0
  sspi_gss_data token;
515
0
  BOOL ret = FALSE;
516
517
0
  WINPR_ASSERT(buf);
518
519
0
  if (msg_type != KRB_TGT_REQ && msg_type != KRB_TGT_REP)
520
0
    return FALSE;
521
0
  if (msg_type == KRB_TGT_REP && !ticket)
522
0
    return FALSE;
523
524
0
  enc = WinPrAsn1Encoder_New(WINPR_ASN1_DER);
525
0
  if (!enc)
526
0
    return FALSE;
527
528
  /* KERB-TGT-REQUEST (SEQUENCE) */
529
0
  if (!WinPrAsn1EncSeqContainer(enc))
530
0
    goto cleanup;
531
532
  /* pvno [0] INTEGER */
533
0
  if (!WinPrAsn1EncContextualInteger(enc, 0, 5))
534
0
    goto cleanup;
535
536
  /* msg-type [1] INTEGER */
537
0
  if (!WinPrAsn1EncContextualInteger(enc, 1, msg_type))
538
0
    goto cleanup;
539
540
0
  if (msg_type == KRB_TGT_REQ && sname)
541
0
  {
542
    /* server-name [2] PrincipalName (SEQUENCE) */
543
0
    if (!WinPrAsn1EncContextualSeqContainer(enc, 2))
544
0
      goto cleanup;
545
546
    /* name-type [0] INTEGER */
547
0
    if (!WinPrAsn1EncContextualInteger(enc, 0, KRB5_NT_SRV_HST))
548
0
      goto cleanup;
549
550
    /* name-string [1] SEQUENCE OF GeneralString */
551
0
    if (!WinPrAsn1EncContextualSeqContainer(enc, 1))
552
0
      goto cleanup;
553
554
0
    if (!WinPrAsn1EncGeneralString(enc, sname))
555
0
      goto cleanup;
556
557
0
    if (host && !WinPrAsn1EncGeneralString(enc, host))
558
0
      goto cleanup;
559
560
0
    if (!WinPrAsn1EncEndContainer(enc) || !WinPrAsn1EncEndContainer(enc))
561
0
      goto cleanup;
562
0
  }
563
0
  else if (msg_type == KRB_TGT_REP)
564
0
  {
565
    /* ticket [2] Ticket */
566
0
    data.data = (BYTE*)ticket->data;
567
0
    data.len = ticket->length;
568
0
    if (!WinPrAsn1EncContextualRawContent(enc, 2, &data))
569
0
      goto cleanup;
570
0
  }
571
572
0
  if (!WinPrAsn1EncEndContainer(enc))
573
0
    goto cleanup;
574
575
0
  if (!WinPrAsn1EncStreamSize(enc, &len) || len > buf->cbBuffer)
576
0
    goto cleanup;
577
578
0
  Stream_StaticInit(&s, buf->pvBuffer, len);
579
0
  if (!WinPrAsn1EncToStream(enc, &s))
580
0
    goto cleanup;
581
582
0
  token.data = buf->pvBuffer;
583
0
  token.length = (UINT)len;
584
0
  if (sspi_gss_wrap_token(buf, &kerberos_u2u_OID,
585
0
                          msg_type == KRB_TGT_REQ ? TOK_ID_TGT_REQ : TOK_ID_TGT_REP, &token))
586
0
    ret = TRUE;
587
588
0
cleanup:
589
0
  WinPrAsn1Encoder_Free(&enc);
590
0
  return ret;
591
0
}
592
593
static BOOL kerberos_rd_tgt_token(const sspi_gss_data* token, char** target, krb5_data* ticket)
594
0
{
595
0
  WinPrAsn1Decoder dec;
596
0
  WinPrAsn1Decoder dec2;
597
0
  BOOL error = 0;
598
0
  WinPrAsn1_tagId tag = 0;
599
0
  WinPrAsn1_INTEGER val = 0;
600
0
  size_t len = 0;
601
0
  wStream s;
602
0
  char* buf = NULL;
603
0
  char* str = NULL;
604
605
0
  WINPR_ASSERT(token);
606
607
0
  WinPrAsn1Decoder_InitMem(&dec, WINPR_ASN1_DER, (BYTE*)token->data, token->length);
608
609
  /* KERB-TGT-REQUEST (SEQUENCE) */
610
0
  if (!WinPrAsn1DecReadSequence(&dec, &dec2))
611
0
    return FALSE;
612
0
  dec = dec2;
613
614
  /* pvno [0] INTEGER */
615
0
  if (!WinPrAsn1DecReadContextualInteger(&dec, 0, &error, &val) || val != 5)
616
0
    return FALSE;
617
618
  /* msg-type [1] INTEGER */
619
0
  if (!WinPrAsn1DecReadContextualInteger(&dec, 1, &error, &val))
620
0
    return FALSE;
621
622
0
  if (val == KRB_TGT_REQ)
623
0
  {
624
0
    if (!target)
625
0
      return FALSE;
626
0
    *target = NULL;
627
628
0
    s = WinPrAsn1DecGetStream(&dec);
629
0
    len = Stream_Length(&s);
630
0
    if (len == 0)
631
0
      return TRUE;
632
633
0
    buf = malloc(len);
634
0
    if (!buf)
635
0
      return FALSE;
636
637
0
    *buf = 0;
638
0
    *target = buf;
639
640
0
    if (!WinPrAsn1DecReadContextualTag(&dec, &tag, &dec2))
641
0
      goto fail;
642
643
0
    if (tag == 2)
644
0
    {
645
0
      WinPrAsn1Decoder seq;
646
      /* server-name [2] PrincipalName (SEQUENCE) */
647
0
      if (!WinPrAsn1DecReadSequence(&dec2, &seq))
648
0
        goto fail;
649
650
      /* name-type [0] INTEGER */
651
0
      if (!WinPrAsn1DecReadContextualInteger(&seq, 0, &error, &val))
652
0
        goto fail;
653
654
      /* name-string [1] SEQUENCE OF GeneralString */
655
0
      if (!WinPrAsn1DecReadContextualSequence(&seq, 1, &error, &dec2))
656
0
        goto fail;
657
658
0
      while (WinPrAsn1DecPeekTag(&dec2, &tag))
659
0
      {
660
0
        if (!WinPrAsn1DecReadGeneralString(&dec2, &str))
661
0
          goto fail;
662
663
0
        if (buf != *target)
664
0
          *buf++ = '/';
665
0
        buf = stpcpy(buf, str);
666
0
        free(str);
667
0
      }
668
669
0
      if (!WinPrAsn1DecReadContextualTag(&dec, &tag, &dec2))
670
0
        return TRUE;
671
0
    }
672
673
    /* realm [3] Realm */
674
0
    if (tag != 3 || !WinPrAsn1DecReadGeneralString(&dec2, &str))
675
0
      goto fail;
676
677
0
    *buf++ = '@';
678
0
    strcpy(buf, str);
679
0
    free(str);
680
0
    return TRUE;
681
0
  }
682
0
  else if (val == KRB_TGT_REP)
683
0
  {
684
0
    if (!ticket)
685
0
      return FALSE;
686
687
    /* ticket [2] Ticket */
688
0
    if (!WinPrAsn1DecReadContextualTag(&dec, &tag, &dec2) || tag != 2)
689
0
      return FALSE;
690
691
0
    s = WinPrAsn1DecGetStream(&dec2);
692
0
    ticket->data = (char*)Stream_Buffer(&s);
693
0
    ticket->length = Stream_Length(&s);
694
0
    return TRUE;
695
0
  }
696
0
  else
697
0
    return FALSE;
698
699
0
fail:
700
0
  free(buf);
701
0
  if (target)
702
0
    *target = NULL;
703
0
  return FALSE;
704
0
}
705
706
#endif /* WITH_KRB5 */
707
708
static BOOL kerberos_hash_channel_bindings(WINPR_DIGEST_CTX* md5, SEC_CHANNEL_BINDINGS* bindings)
709
0
{
710
0
  BYTE buf[4];
711
712
0
  Data_Write_UINT32(buf, bindings->dwInitiatorAddrType);
713
0
  if (!winpr_Digest_Update(md5, buf, 4))
714
0
    return FALSE;
715
716
0
  Data_Write_UINT32(buf, bindings->cbInitiatorLength);
717
0
  if (!winpr_Digest_Update(md5, buf, 4))
718
0
    return FALSE;
719
720
0
  if (bindings->cbInitiatorLength &&
721
0
      !winpr_Digest_Update(md5, (BYTE*)bindings + bindings->dwInitiatorOffset,
722
0
                           bindings->cbInitiatorLength))
723
0
    return FALSE;
724
725
0
  Data_Write_UINT32(buf, bindings->dwAcceptorAddrType);
726
0
  if (!winpr_Digest_Update(md5, buf, 4))
727
0
    return FALSE;
728
729
0
  Data_Write_UINT32(buf, bindings->cbAcceptorLength);
730
0
  if (!winpr_Digest_Update(md5, buf, 4))
731
0
    return FALSE;
732
733
0
  if (bindings->cbAcceptorLength &&
734
0
      !winpr_Digest_Update(md5, (BYTE*)bindings + bindings->dwAcceptorOffset,
735
0
                           bindings->cbAcceptorLength))
736
0
    return FALSE;
737
738
0
  Data_Write_UINT32(buf, bindings->cbApplicationDataLength);
739
0
  if (!winpr_Digest_Update(md5, buf, 4))
740
0
    return FALSE;
741
742
0
  if (bindings->cbApplicationDataLength &&
743
0
      !winpr_Digest_Update(md5, (BYTE*)bindings + bindings->dwApplicationDataOffset,
744
0
                           bindings->cbApplicationDataLength))
745
0
    return FALSE;
746
747
0
  return TRUE;
748
0
}
749
750
static SECURITY_STATUS SEC_ENTRY kerberos_InitializeSecurityContextA(
751
    PCredHandle phCredential, PCtxtHandle phContext, SEC_CHAR* pszTargetName, ULONG fContextReq,
752
    ULONG Reserved1, ULONG TargetDataRep, PSecBufferDesc pInput, ULONG Reserved2,
753
    PCtxtHandle phNewContext, PSecBufferDesc pOutput, ULONG* pfContextAttr, PTimeStamp ptsExpiry)
754
0
{
755
0
#ifdef WITH_KRB5
756
0
  KRB_CREDENTIALS* credentials = NULL;
757
0
  KRB_CONTEXT* context = NULL;
758
0
  KRB_CONTEXT new_context = { 0 };
759
0
  PSecBuffer input_buffer = NULL;
760
0
  PSecBuffer output_buffer = NULL;
761
0
  PSecBuffer bindings_buffer = NULL;
762
0
  WINPR_DIGEST_CTX* md5 = NULL;
763
0
  char* target = NULL;
764
0
  char* sname = NULL;
765
0
  char* host = NULL;
766
0
  krb5_data input_token = { 0 };
767
0
  krb5_data output_token = { 0 };
768
0
  SECURITY_STATUS status = SEC_E_INTERNAL_ERROR;
769
0
  WinPrAsn1_OID oid = { 0 };
770
0
  uint16_t tok_id = 0;
771
0
  krb5_ap_rep_enc_part* reply = NULL;
772
0
  krb5_flags ap_flags = AP_OPTS_USE_SUBKEY;
773
0
  char cksum_contents[24] = { 0 };
774
0
  krb5_data cksum = { 0 };
775
0
  krb5_creds in_creds = { 0 };
776
0
  krb5_creds* creds = NULL;
777
778
0
  credentials = sspi_SecureHandleGetLowerPointer(phCredential);
779
780
  /* behave like windows SSPIs that don't want empty context */
781
0
  if (phContext && !phContext->dwLower && !phContext->dwUpper)
782
0
    return SEC_E_INVALID_HANDLE;
783
784
0
  context = sspi_SecureHandleGetLowerPointer(phContext);
785
786
0
  if (!credentials)
787
0
    return SEC_E_NO_CREDENTIALS;
788
789
0
  if (pInput)
790
0
  {
791
0
    input_buffer = sspi_FindSecBuffer(pInput, SECBUFFER_TOKEN);
792
0
    bindings_buffer = sspi_FindSecBuffer(pInput, SECBUFFER_CHANNEL_BINDINGS);
793
0
  }
794
0
  if (pOutput)
795
0
    output_buffer = sspi_FindSecBuffer(pOutput, SECBUFFER_TOKEN);
796
797
0
  if (fContextReq & ISC_REQ_MUTUAL_AUTH)
798
0
    ap_flags |= AP_OPTS_MUTUAL_REQUIRED;
799
800
0
  if (fContextReq & ISC_REQ_USE_SESSION_KEY)
801
0
    ap_flags |= AP_OPTS_USE_SESSION_KEY;
802
803
0
  if (!context)
804
0
  {
805
0
    context = &new_context;
806
807
0
    if (krb_log_exec_ptr(krb5_init_context, &context->ctx))
808
0
      return SEC_E_INTERNAL_ERROR;
809
810
0
    if (fContextReq & ISC_REQ_USE_SESSION_KEY)
811
0
    {
812
0
      context->state = KERBEROS_STATE_TGT_REQ;
813
0
      context->u2u = TRUE;
814
0
    }
815
0
    else
816
0
      context->state = KERBEROS_STATE_AP_REQ;
817
0
  }
818
0
  else
819
0
  {
820
0
    if (!input_buffer || !sspi_gss_unwrap_token(input_buffer, &oid, &tok_id, &input_token))
821
0
      goto bad_token;
822
0
    if ((context->u2u && !sspi_gss_oid_compare(&oid, &kerberos_u2u_OID)) ||
823
0
        (!context->u2u && !sspi_gss_oid_compare(&oid, &kerberos_OID)))
824
0
      goto bad_token;
825
0
  }
826
827
  /* Split target name into service/hostname components */
828
0
  if (pszTargetName)
829
0
  {
830
0
    target = _strdup(pszTargetName);
831
0
    if (!target)
832
0
    {
833
0
      status = SEC_E_INSUFFICIENT_MEMORY;
834
0
      goto cleanup;
835
0
    }
836
0
    host = strchr(target, '/');
837
0
    if (host)
838
0
    {
839
0
      *host++ = 0;
840
0
      sname = target;
841
0
    }
842
0
    else
843
0
      host = target;
844
0
    if (isValidIP(host))
845
0
    {
846
0
      status = SEC_E_NO_CREDENTIALS;
847
0
      goto cleanup;
848
0
    }
849
0
  }
850
851
  /* SSPI flags are compatible with GSS flags except INTEG_FLAG */
852
0
  context->flags |= (fContextReq & 0x1F);
853
0
  if (fContextReq & ISC_REQ_INTEGRITY && !(fContextReq & ISC_REQ_NO_INTEGRITY))
854
0
    context->flags |= SSPI_GSS_C_INTEG_FLAG;
855
856
0
  switch (context->state)
857
0
  {
858
0
    case KERBEROS_STATE_TGT_REQ:
859
860
0
      if (!kerberos_mk_tgt_token(output_buffer, KRB_TGT_REQ, sname, host, NULL))
861
0
        goto cleanup;
862
863
0
      context->state = KERBEROS_STATE_TGT_REP;
864
865
0
      status = SEC_I_CONTINUE_NEEDED;
866
867
0
      break;
868
869
0
    case KERBEROS_STATE_TGT_REP:
870
871
0
      if (tok_id != TOK_ID_TGT_REP)
872
0
        goto bad_token;
873
874
0
      if (!kerberos_rd_tgt_token(&input_token, NULL, &in_creds.second_ticket))
875
0
        goto bad_token;
876
877
      /* Continue to AP-REQ */
878
      /* fallthrough */
879
0
      WINPR_FALLTHROUGH
880
881
0
    case KERBEROS_STATE_AP_REQ:
882
883
      /* Set auth_context options */
884
0
      if (krb_log_exec(krb5_auth_con_init, context->ctx, &context->auth_ctx))
885
0
        goto cleanup;
886
0
      if (krb_log_exec(krb5_auth_con_setflags, context->ctx, context->auth_ctx,
887
0
                       KRB5_AUTH_CONTEXT_DO_SEQUENCE | KRB5_AUTH_CONTEXT_USE_SUBKEY))
888
0
        goto cleanup;
889
0
      if (krb_log_exec(krb5glue_auth_con_set_cksumtype, context->ctx, context->auth_ctx,
890
0
                       GSS_CHECKSUM_TYPE))
891
0
        goto cleanup;
892
893
      /* Get a service ticket */
894
0
      if (krb_log_exec(krb5_sname_to_principal, context->ctx, host, sname, KRB5_NT_SRV_HST,
895
0
                       &in_creds.server))
896
0
        goto cleanup;
897
898
0
      if (krb_log_exec(krb5_cc_get_principal, context->ctx, credentials->ccache,
899
0
                       &in_creds.client))
900
0
        goto cleanup;
901
902
0
      if (krb_log_exec(krb5_get_credentials, context->ctx,
903
0
                       context->u2u ? KRB5_GC_USER_USER : 0, credentials->ccache, &in_creds,
904
0
                       &creds))
905
0
        goto cleanup;
906
907
      /* Write the checksum (delegation not implemented) */
908
0
      cksum.data = cksum_contents;
909
0
      cksum.length = sizeof(cksum_contents);
910
0
      Data_Write_UINT32(cksum_contents, 16);
911
0
      Data_Write_UINT32((cksum_contents + 20), context->flags);
912
913
0
      if (bindings_buffer)
914
0
      {
915
0
        SEC_CHANNEL_BINDINGS* bindings = bindings_buffer->pvBuffer;
916
917
        /* Sanity checks */
918
0
        if (bindings_buffer->cbBuffer < sizeof(SEC_CHANNEL_BINDINGS) ||
919
0
            (bindings->cbInitiatorLength + bindings->dwInitiatorOffset) >
920
0
                bindings_buffer->cbBuffer ||
921
0
            (bindings->cbAcceptorLength + bindings->dwAcceptorOffset) >
922
0
                bindings_buffer->cbBuffer ||
923
0
            (bindings->cbApplicationDataLength + bindings->dwApplicationDataOffset) >
924
0
                bindings_buffer->cbBuffer)
925
0
        {
926
0
          status = SEC_E_BAD_BINDINGS;
927
0
          goto cleanup;
928
0
        }
929
930
0
        md5 = winpr_Digest_New();
931
0
        if (!md5)
932
0
          goto cleanup;
933
934
0
        if (!winpr_Digest_Init(md5, WINPR_MD_MD5))
935
0
          goto cleanup;
936
937
0
        if (!kerberos_hash_channel_bindings(md5, bindings))
938
0
          goto cleanup;
939
940
0
        if (!winpr_Digest_Final(md5, (BYTE*)cksum_contents + 4, 16))
941
0
          goto cleanup;
942
0
      }
943
944
      /* Make the AP_REQ message */
945
0
      if (krb_log_exec(krb5_mk_req_extended, context->ctx, &context->auth_ctx, ap_flags,
946
0
                       &cksum, creds, &output_token))
947
0
        goto cleanup;
948
949
0
      if (!sspi_gss_wrap_token(output_buffer,
950
0
                               context->u2u ? &kerberos_u2u_OID : &kerberos_OID,
951
0
                               TOK_ID_AP_REQ, &output_token))
952
0
        goto cleanup;
953
954
0
      if (context->flags & SSPI_GSS_C_SEQUENCE_FLAG)
955
0
      {
956
0
        if (krb_log_exec(krb5_auth_con_getlocalseqnumber, context->ctx, context->auth_ctx,
957
0
                         (INT32*)&context->local_seq))
958
0
          goto cleanup;
959
0
        context->remote_seq ^= context->local_seq;
960
0
      }
961
962
0
      if (krb_log_exec(krb5glue_update_keyset, context->ctx, context->auth_ctx, FALSE,
963
0
                       &context->keyset))
964
0
        goto cleanup;
965
966
0
      context->state = KERBEROS_STATE_AP_REP;
967
968
0
      if (context->flags & SSPI_GSS_C_MUTUAL_FLAG)
969
0
        status = SEC_I_CONTINUE_NEEDED;
970
0
      else
971
0
        status = SEC_E_OK;
972
973
0
      break;
974
975
0
    case KERBEROS_STATE_AP_REP:
976
977
0
      if (tok_id == TOK_ID_AP_REP)
978
0
      {
979
0
        if (krb_log_exec(krb5_rd_rep, context->ctx, context->auth_ctx, &input_token,
980
0
                         &reply))
981
0
          goto cleanup;
982
0
        krb5_free_ap_rep_enc_part(context->ctx, reply);
983
0
      }
984
0
      else if (tok_id == TOK_ID_ERROR)
985
0
      {
986
0
        krb5glue_log_error(context->ctx, &input_token, TAG);
987
0
        goto cleanup;
988
0
      }
989
0
      else
990
0
        goto bad_token;
991
992
0
      if (context->flags & SSPI_GSS_C_SEQUENCE_FLAG)
993
0
      {
994
0
        if (krb_log_exec(krb5_auth_con_getremoteseqnumber, context->ctx, context->auth_ctx,
995
0
                         (INT32*)&context->remote_seq))
996
0
          goto cleanup;
997
0
      }
998
999
0
      if (krb_log_exec(krb5glue_update_keyset, context->ctx, context->auth_ctx, FALSE,
1000
0
                       &context->keyset))
1001
0
        goto cleanup;
1002
1003
0
      context->state = KERBEROS_STATE_FINAL;
1004
1005
0
      if (output_buffer)
1006
0
        output_buffer->cbBuffer = 0;
1007
0
      status = SEC_E_OK;
1008
1009
0
      break;
1010
1011
0
    case KERBEROS_STATE_FINAL:
1012
0
    default:
1013
0
      WLog_ERR(TAG, "Kerberos in invalid state!");
1014
0
      goto cleanup;
1015
0
  }
1016
1017
  /* On first call allocate a new context */
1018
0
  if (new_context.ctx)
1019
0
  {
1020
0
    const KRB_CONTEXT empty = { 0 };
1021
1022
0
    context = kerberos_ContextNew();
1023
0
    if (!context)
1024
0
    {
1025
0
      status = SEC_E_INSUFFICIENT_MEMORY;
1026
0
      goto cleanup;
1027
0
    }
1028
0
    *context = new_context;
1029
0
    new_context = empty;
1030
1031
0
    sspi_SecureHandleSetLowerPointer(phNewContext, context);
1032
0
    sspi_SecureHandleSetUpperPointer(phNewContext, KERBEROS_SSP_NAME);
1033
0
  }
1034
1035
0
cleanup:
1036
1037
0
{
1038
  /* second_ticket is not allocated */
1039
0
  krb5_data edata = { 0 };
1040
0
  in_creds.second_ticket = edata;
1041
0
  krb5_free_cred_contents(context->ctx, &in_creds);
1042
0
}
1043
1044
0
  krb5_free_creds(context->ctx, creds);
1045
0
  if (output_token.data)
1046
0
    krb5glue_free_data_contents(context->ctx, &output_token);
1047
1048
0
  winpr_Digest_Free(md5);
1049
1050
0
  free(target);
1051
0
  kerberos_ContextFree(&new_context, FALSE);
1052
1053
0
  return status;
1054
1055
0
bad_token:
1056
0
  status = SEC_E_INVALID_TOKEN;
1057
0
  goto cleanup;
1058
#else
1059
  return SEC_E_UNSUPPORTED_FUNCTION;
1060
#endif /* WITH_KRB5 */
1061
0
}
1062
1063
static SECURITY_STATUS SEC_ENTRY kerberos_InitializeSecurityContextW(
1064
    PCredHandle phCredential, PCtxtHandle phContext, SEC_WCHAR* pszTargetName, ULONG fContextReq,
1065
    ULONG Reserved1, ULONG TargetDataRep, PSecBufferDesc pInput, ULONG Reserved2,
1066
    PCtxtHandle phNewContext, PSecBufferDesc pOutput, ULONG* pfContextAttr, PTimeStamp ptsExpiry)
1067
0
{
1068
0
  SECURITY_STATUS status = 0;
1069
0
  char* target_name = NULL;
1070
1071
0
  if (pszTargetName)
1072
0
  {
1073
0
    target_name = ConvertWCharToUtf8Alloc(pszTargetName, NULL);
1074
0
    if (!target_name)
1075
0
      return SEC_E_INSUFFICIENT_MEMORY;
1076
0
  }
1077
1078
0
  status = kerberos_InitializeSecurityContextA(phCredential, phContext, target_name, fContextReq,
1079
0
                                               Reserved1, TargetDataRep, pInput, Reserved2,
1080
0
                                               phNewContext, pOutput, pfContextAttr, ptsExpiry);
1081
1082
0
  if (target_name)
1083
0
    free(target_name);
1084
1085
0
  return status;
1086
0
}
1087
1088
static SECURITY_STATUS SEC_ENTRY kerberos_AcceptSecurityContext(
1089
    PCredHandle phCredential, PCtxtHandle phContext, PSecBufferDesc pInput, ULONG fContextReq,
1090
    ULONG TargetDataRep, PCtxtHandle phNewContext, PSecBufferDesc pOutput, ULONG* pfContextAttr,
1091
    PTimeStamp ptsExpity)
1092
0
{
1093
0
#ifdef WITH_KRB5
1094
0
  KRB_CREDENTIALS* credentials = NULL;
1095
0
  KRB_CONTEXT* context = NULL;
1096
0
  KRB_CONTEXT new_context = { 0 };
1097
0
  PSecBuffer input_buffer = NULL;
1098
0
  PSecBuffer output_buffer = NULL;
1099
0
  WinPrAsn1_OID oid = { 0 };
1100
0
  uint16_t tok_id = 0;
1101
0
  krb5_data input_token = { 0 };
1102
0
  krb5_data output_token = { 0 };
1103
0
  SECURITY_STATUS status = SEC_E_INTERNAL_ERROR;
1104
0
  krb5_flags ap_flags = 0;
1105
0
  krb5glue_authenticator authenticator = NULL;
1106
0
  char* target = NULL;
1107
0
  char* sname = NULL;
1108
0
  char* realm = NULL;
1109
0
  krb5_kt_cursor cur = { 0 };
1110
0
  krb5_keytab_entry entry = { 0 };
1111
0
  krb5_principal principal = NULL;
1112
0
  krb5_creds creds = { 0 };
1113
1114
  /* behave like windows SSPIs that don't want empty context */
1115
0
  if (phContext && !phContext->dwLower && !phContext->dwUpper)
1116
0
    return SEC_E_INVALID_HANDLE;
1117
1118
0
  context = sspi_SecureHandleGetLowerPointer(phContext);
1119
0
  credentials = sspi_SecureHandleGetLowerPointer(phCredential);
1120
1121
0
  if (pInput)
1122
0
    input_buffer = sspi_FindSecBuffer(pInput, SECBUFFER_TOKEN);
1123
0
  if (pOutput)
1124
0
    output_buffer = sspi_FindSecBuffer(pOutput, SECBUFFER_TOKEN);
1125
1126
0
  if (!input_buffer)
1127
0
    return SEC_E_INVALID_TOKEN;
1128
1129
0
  if (!sspi_gss_unwrap_token(input_buffer, &oid, &tok_id, &input_token))
1130
0
    return SEC_E_INVALID_TOKEN;
1131
1132
0
  if (!context)
1133
0
  {
1134
0
    context = &new_context;
1135
1136
0
    if (krb_log_exec_ptr(krb5_init_context, &context->ctx))
1137
0
      return SEC_E_INTERNAL_ERROR;
1138
1139
0
    if (sspi_gss_oid_compare(&oid, &kerberos_u2u_OID))
1140
0
    {
1141
0
      context->u2u = TRUE;
1142
0
      context->state = KERBEROS_STATE_TGT_REQ;
1143
0
    }
1144
0
    else if (sspi_gss_oid_compare(&oid, &kerberos_OID))
1145
0
      context->state = KERBEROS_STATE_AP_REQ;
1146
0
    else
1147
0
      goto bad_token;
1148
0
  }
1149
0
  else
1150
0
  {
1151
0
    if ((context->u2u && !sspi_gss_oid_compare(&oid, &kerberos_u2u_OID)) ||
1152
0
        (!context->u2u && !sspi_gss_oid_compare(&oid, &kerberos_OID)))
1153
0
      goto bad_token;
1154
0
  }
1155
1156
0
  if (context->state == KERBEROS_STATE_TGT_REQ && tok_id == TOK_ID_TGT_REQ)
1157
0
  {
1158
0
    if (!kerberos_rd_tgt_token(&input_token, &target, NULL))
1159
0
      goto bad_token;
1160
1161
0
    if (target)
1162
0
    {
1163
0
      if (*target != 0 && *target != '@')
1164
0
        sname = target;
1165
0
      realm = strchr(target, '@');
1166
0
      if (realm)
1167
0
        realm++;
1168
0
    }
1169
1170
0
    if (krb_log_exec(krb5_parse_name_flags, context->ctx, sname ? sname : "",
1171
0
                     KRB5_PRINCIPAL_PARSE_NO_REALM, &principal))
1172
0
      goto cleanup;
1173
1174
0
    if (realm)
1175
0
    {
1176
0
      if (krb_log_exec(krb5glue_set_principal_realm, context->ctx, principal, realm))
1177
0
        goto cleanup;
1178
0
    }
1179
1180
0
    if (krb_log_exec(krb5_kt_start_seq_get, context->ctx, credentials->keytab, &cur))
1181
0
      goto cleanup;
1182
1183
0
    do
1184
0
    {
1185
0
      krb5_error_code rv =
1186
0
          krb_log_exec(krb5_kt_next_entry, context->ctx, credentials->keytab, &entry, &cur);
1187
0
      if (rv == KRB5_KT_END)
1188
0
        break;
1189
0
      if (rv != 0)
1190
0
        goto cleanup;
1191
1192
0
      if ((!sname || krb_log_exec(krb5_principal_compare_any_realm, context->ctx, principal,
1193
0
                                  entry.principal)) &&
1194
0
          (!realm ||
1195
0
           krb_log_exec(krb5_realm_compare, context->ctx, principal, entry.principal)))
1196
0
        break;
1197
0
      if (krb_log_exec(krb5glue_free_keytab_entry_contents, context->ctx, &entry))
1198
0
        goto cleanup;
1199
0
    } while (1);
1200
1201
0
    if (krb_log_exec(krb5_kt_end_seq_get, context->ctx, credentials->keytab, &cur))
1202
0
      goto cleanup;
1203
1204
0
    if (!entry.principal)
1205
0
      goto cleanup;
1206
1207
    /* Get the TGT */
1208
0
    if (krb_log_exec(krb5_get_init_creds_keytab, context->ctx, &creds, entry.principal,
1209
0
                     credentials->keytab, 0, NULL, NULL))
1210
0
      goto cleanup;
1211
1212
0
    if (!kerberos_mk_tgt_token(output_buffer, KRB_TGT_REP, NULL, NULL, &creds.ticket))
1213
0
      goto cleanup;
1214
1215
0
    if (krb_log_exec(krb5_auth_con_init, context->ctx, &context->auth_ctx))
1216
0
      goto cleanup;
1217
1218
0
    if (krb_log_exec(krb5glue_auth_con_setuseruserkey, context->ctx, context->auth_ctx,
1219
0
                     &krb5glue_creds_getkey(creds)))
1220
0
      goto cleanup;
1221
1222
0
    context->state = KERBEROS_STATE_AP_REQ;
1223
0
  }
1224
0
  else if (context->state == KERBEROS_STATE_AP_REQ && tok_id == TOK_ID_AP_REQ)
1225
0
  {
1226
0
    if (krb_log_exec(krb5_rd_req, context->ctx, &context->auth_ctx, &input_token, NULL,
1227
0
                     credentials->keytab, &ap_flags, NULL))
1228
0
      goto cleanup;
1229
1230
0
    if (krb_log_exec(krb5_auth_con_setflags, context->ctx, context->auth_ctx,
1231
0
                     KRB5_AUTH_CONTEXT_DO_SEQUENCE | KRB5_AUTH_CONTEXT_USE_SUBKEY))
1232
0
      goto cleanup;
1233
1234
    /* Retrieve and validate the checksum */
1235
0
    if (krb_log_exec(krb5_auth_con_getauthenticator, context->ctx, context->auth_ctx,
1236
0
                     &authenticator))
1237
0
      goto cleanup;
1238
0
    if (!krb5glue_authenticator_validate_chksum(authenticator, GSS_CHECKSUM_TYPE,
1239
0
                                                &context->flags))
1240
0
      goto bad_token;
1241
1242
0
    if (ap_flags & AP_OPTS_MUTUAL_REQUIRED && context->flags & SSPI_GSS_C_MUTUAL_FLAG)
1243
0
    {
1244
0
      if (!output_buffer)
1245
0
        goto bad_token;
1246
0
      if (krb_log_exec(krb5_mk_rep, context->ctx, context->auth_ctx, &output_token))
1247
0
        goto cleanup;
1248
0
      if (!sspi_gss_wrap_token(output_buffer,
1249
0
                               context->u2u ? &kerberos_u2u_OID : &kerberos_OID,
1250
0
                               TOK_ID_AP_REP, &output_token))
1251
0
        goto cleanup;
1252
0
    }
1253
0
    else
1254
0
    {
1255
0
      if (output_buffer)
1256
0
        output_buffer->cbBuffer = 0;
1257
0
    }
1258
1259
0
    *pfContextAttr = context->flags & 0x1F;
1260
0
    if (context->flags & SSPI_GSS_C_INTEG_FLAG)
1261
0
      *pfContextAttr |= ASC_RET_INTEGRITY;
1262
1263
0
    if (context->flags & SSPI_GSS_C_SEQUENCE_FLAG)
1264
0
    {
1265
0
      if (krb_log_exec(krb5_auth_con_getlocalseqnumber, context->ctx, context->auth_ctx,
1266
0
                       (INT32*)&context->local_seq))
1267
0
        goto cleanup;
1268
0
      if (krb_log_exec(krb5_auth_con_getremoteseqnumber, context->ctx, context->auth_ctx,
1269
0
                       (INT32*)&context->remote_seq))
1270
0
        goto cleanup;
1271
0
    }
1272
1273
0
    if (krb_log_exec(krb5glue_update_keyset, context->ctx, context->auth_ctx, TRUE,
1274
0
                     &context->keyset))
1275
0
      goto cleanup;
1276
1277
0
    context->state = KERBEROS_STATE_FINAL;
1278
0
  }
1279
0
  else
1280
0
    goto bad_token;
1281
1282
  /* On first call allocate new context */
1283
0
  if (new_context.ctx)
1284
0
  {
1285
0
    const KRB_CONTEXT empty = { 0 };
1286
1287
0
    context = kerberos_ContextNew();
1288
0
    if (!context)
1289
0
    {
1290
0
      status = SEC_E_INSUFFICIENT_MEMORY;
1291
0
      goto cleanup;
1292
0
    }
1293
0
    *context = new_context;
1294
0
    new_context = empty;
1295
0
    context->acceptor = TRUE;
1296
1297
0
    sspi_SecureHandleSetLowerPointer(phNewContext, context);
1298
0
    sspi_SecureHandleSetUpperPointer(phNewContext, KERBEROS_SSP_NAME);
1299
0
  }
1300
1301
0
  if (context->state == KERBEROS_STATE_FINAL)
1302
0
    status = SEC_E_OK;
1303
0
  else
1304
0
    status = SEC_I_CONTINUE_NEEDED;
1305
1306
0
cleanup:
1307
1308
0
  free(target);
1309
0
  if (output_token.data)
1310
0
    krb5glue_free_data_contents(context->ctx, &output_token);
1311
0
  if (entry.principal)
1312
0
    krb5glue_free_keytab_entry_contents(context->ctx, &entry);
1313
1314
0
  kerberos_ContextFree(&new_context, FALSE);
1315
0
  return status;
1316
1317
0
bad_token:
1318
0
  status = SEC_E_INVALID_TOKEN;
1319
0
  goto cleanup;
1320
#else
1321
  return SEC_E_UNSUPPORTED_FUNCTION;
1322
#endif /* WITH_KRB5 */
1323
0
}
1324
1325
static KRB_CONTEXT* get_context(PCtxtHandle phContext)
1326
0
{
1327
0
  if (!phContext)
1328
0
    return NULL;
1329
1330
0
  TCHAR* name = sspi_SecureHandleGetUpperPointer(phContext);
1331
0
  if (!name)
1332
0
    return NULL;
1333
1334
0
  if (_tcscmp(KERBEROS_SSP_NAME, name) != 0)
1335
0
    return NULL;
1336
0
  return sspi_SecureHandleGetLowerPointer(phContext);
1337
0
}
1338
1339
static SECURITY_STATUS SEC_ENTRY kerberos_DeleteSecurityContext(PCtxtHandle phContext)
1340
0
{
1341
0
#ifdef WITH_KRB5
1342
0
  KRB_CONTEXT* context = get_context(phContext);
1343
0
  if (!context)
1344
0
    return SEC_E_INVALID_HANDLE;
1345
1346
0
  kerberos_ContextFree(context, TRUE);
1347
1348
0
  return SEC_E_OK;
1349
#else
1350
  return SEC_E_UNSUPPORTED_FUNCTION;
1351
#endif
1352
0
}
1353
1354
static SECURITY_STATUS SEC_ENTRY kerberos_QueryContextAttributesA(PCtxtHandle phContext,
1355
                                                                  ULONG ulAttribute, void* pBuffer)
1356
0
{
1357
0
#ifdef WITH_KRB5
1358
0
  if (!phContext)
1359
0
    return SEC_E_INVALID_HANDLE;
1360
1361
0
  if (!pBuffer)
1362
0
    return SEC_E_INSUFFICIENT_MEMORY;
1363
1364
0
  if (ulAttribute == SECPKG_ATTR_SIZES)
1365
0
  {
1366
0
    UINT header = 0;
1367
0
    UINT pad = 0;
1368
0
    UINT trailer = 0;
1369
0
    krb5glue_key key = NULL;
1370
0
    KRB_CONTEXT* context = get_context(phContext);
1371
0
    SecPkgContext_Sizes* ContextSizes = (SecPkgContext_Sizes*)pBuffer;
1372
1373
0
    WINPR_ASSERT(context);
1374
0
    WINPR_ASSERT(context->ctx);
1375
0
    WINPR_ASSERT(context->auth_ctx);
1376
1377
    /* The MaxTokenSize by default is 12,000 bytes. This has been the default value
1378
     * since Windows 2000 SP2 and still remains in Windows 7 and Windows 2008 R2.
1379
     *  For Windows Server 2012, the default value of the MaxTokenSize registry
1380
     *  entry is 48,000 bytes.*/
1381
0
    ContextSizes->cbMaxToken = KERBEROS_SecPkgInfoA.cbMaxToken;
1382
0
    ContextSizes->cbMaxSignature = 0;
1383
0
    ContextSizes->cbBlockSize = 1;
1384
0
    ContextSizes->cbSecurityTrailer = 0;
1385
1386
0
    key = get_key(&context->keyset);
1387
1388
0
    if (context->flags & SSPI_GSS_C_CONF_FLAG)
1389
0
    {
1390
0
      krb5_error_code rv = krb_log_exec(krb5glue_crypto_length, context->ctx, key,
1391
0
                                        KRB5_CRYPTO_TYPE_HEADER, &header);
1392
0
      if (rv)
1393
0
        return rv;
1394
0
      rv = krb_log_exec(krb5glue_crypto_length, context->ctx, key, KRB5_CRYPTO_TYPE_PADDING,
1395
0
                        &pad);
1396
0
      if (rv)
1397
0
        return rv;
1398
0
      rv = krb_log_exec(krb5glue_crypto_length, context->ctx, key, KRB5_CRYPTO_TYPE_TRAILER,
1399
0
                        &trailer);
1400
0
      if (rv)
1401
0
        return rv;
1402
      /* GSS header (= 16 bytes) + encrypted header = 32 bytes */
1403
0
      ContextSizes->cbSecurityTrailer = header + pad + trailer + 32;
1404
0
    }
1405
0
    if (context->flags & SSPI_GSS_C_INTEG_FLAG)
1406
0
    {
1407
0
      krb5_error_code rv =
1408
0
          krb_log_exec(krb5glue_crypto_length, context->ctx, key, KRB5_CRYPTO_TYPE_CHECKSUM,
1409
0
                       &ContextSizes->cbMaxSignature);
1410
0
      if (rv)
1411
0
        return rv;
1412
0
      ContextSizes->cbMaxSignature += 16;
1413
0
    }
1414
1415
0
    return SEC_E_OK;
1416
0
  }
1417
1418
0
  WLog_ERR(TAG, "TODO: Implement ulAttribute=%08" PRIx32, ulAttribute);
1419
0
  return SEC_E_UNSUPPORTED_FUNCTION;
1420
#else
1421
  return SEC_E_UNSUPPORTED_FUNCTION;
1422
#endif
1423
0
}
1424
1425
static SECURITY_STATUS SEC_ENTRY kerberos_QueryContextAttributesW(PCtxtHandle phContext,
1426
                                                                  ULONG ulAttribute, void* pBuffer)
1427
0
{
1428
0
  return kerberos_QueryContextAttributesA(phContext, ulAttribute, pBuffer);
1429
0
}
1430
1431
static SECURITY_STATUS SEC_ENTRY kerberos_SetContextAttributesW(PCtxtHandle phContext,
1432
                                                                ULONG ulAttribute, void* pBuffer,
1433
                                                                ULONG cbBuffer)
1434
0
{
1435
0
  return SEC_E_UNSUPPORTED_FUNCTION;
1436
0
}
1437
1438
static SECURITY_STATUS SEC_ENTRY kerberos_SetContextAttributesA(PCtxtHandle phContext,
1439
                                                                ULONG ulAttribute, void* pBuffer,
1440
                                                                ULONG cbBuffer)
1441
0
{
1442
0
  return SEC_E_UNSUPPORTED_FUNCTION;
1443
0
}
1444
1445
static SECURITY_STATUS SEC_ENTRY kerberos_SetCredentialsAttributesX(PCredHandle phCredential,
1446
                                                                    ULONG ulAttribute,
1447
                                                                    void* pBuffer, ULONG cbBuffer,
1448
                                                                    BOOL unicode)
1449
0
{
1450
0
#ifdef WITH_KRB5
1451
0
  KRB_CREDENTIALS* credentials = NULL;
1452
1453
0
  if (!phCredential)
1454
0
    return SEC_E_INVALID_HANDLE;
1455
1456
0
  credentials = sspi_SecureHandleGetLowerPointer(phCredential);
1457
1458
0
  if (!credentials)
1459
0
    return SEC_E_INVALID_HANDLE;
1460
1461
0
  if (!pBuffer)
1462
0
    return SEC_E_INSUFFICIENT_MEMORY;
1463
1464
0
  if (ulAttribute == SECPKG_CRED_ATTR_KDC_PROXY_SETTINGS)
1465
0
  {
1466
0
    SecPkgCredentials_KdcProxySettingsW* kdc_settings = pBuffer;
1467
1468
    /* Sanity checks */
1469
0
    if (cbBuffer < sizeof(SecPkgCredentials_KdcProxySettingsW) ||
1470
0
        kdc_settings->Version != KDC_PROXY_SETTINGS_V1 ||
1471
0
        kdc_settings->ProxyServerOffset < sizeof(SecPkgCredentials_KdcProxySettingsW) ||
1472
0
        cbBuffer < sizeof(SecPkgCredentials_KdcProxySettingsW) +
1473
0
                       kdc_settings->ProxyServerOffset + kdc_settings->ProxyServerLength)
1474
0
      return SEC_E_INVALID_TOKEN;
1475
1476
0
    if (credentials->kdc_url)
1477
0
    {
1478
0
      free(credentials->kdc_url);
1479
0
      credentials->kdc_url = NULL;
1480
0
    }
1481
1482
0
    if (kdc_settings->ProxyServerLength > 0)
1483
0
    {
1484
0
      WCHAR* proxy = (WCHAR*)((BYTE*)pBuffer + kdc_settings->ProxyServerOffset);
1485
1486
0
      credentials->kdc_url = ConvertWCharNToUtf8Alloc(
1487
0
          proxy, kdc_settings->ProxyServerLength / sizeof(WCHAR), NULL);
1488
0
      if (!credentials->kdc_url)
1489
0
        return SEC_E_INSUFFICIENT_MEMORY;
1490
0
    }
1491
1492
0
    return SEC_E_OK;
1493
0
  }
1494
1495
0
  return SEC_E_UNSUPPORTED_FUNCTION;
1496
#else
1497
  return SEC_E_UNSUPPORTED_FUNCTION;
1498
#endif
1499
0
}
1500
1501
static SECURITY_STATUS SEC_ENTRY kerberos_SetCredentialsAttributesW(PCredHandle phCredential,
1502
                                                                    ULONG ulAttribute,
1503
                                                                    void* pBuffer, ULONG cbBuffer)
1504
0
{
1505
0
  return kerberos_SetCredentialsAttributesX(phCredential, ulAttribute, pBuffer, cbBuffer, TRUE);
1506
0
}
1507
1508
static SECURITY_STATUS SEC_ENTRY kerberos_SetCredentialsAttributesA(PCredHandle phCredential,
1509
                                                                    ULONG ulAttribute,
1510
                                                                    void* pBuffer, ULONG cbBuffer)
1511
0
{
1512
0
  return kerberos_SetCredentialsAttributesX(phCredential, ulAttribute, pBuffer, cbBuffer, FALSE);
1513
0
}
1514
1515
static SECURITY_STATUS SEC_ENTRY kerberos_EncryptMessage(PCtxtHandle phContext, ULONG fQOP,
1516
                                                         PSecBufferDesc pMessage,
1517
                                                         ULONG MessageSeqNo)
1518
0
{
1519
0
#ifdef WITH_KRB5
1520
0
  KRB_CONTEXT* context = get_context(phContext);
1521
0
  PSecBuffer sig_buffer = NULL;
1522
0
  PSecBuffer data_buffer = NULL;
1523
0
  char* header = NULL;
1524
0
  BYTE flags = 0;
1525
0
  krb5glue_key key = NULL;
1526
0
  krb5_keyusage usage = 0;
1527
0
  krb5_crypto_iov encrypt_iov[] = { { KRB5_CRYPTO_TYPE_HEADER, { 0 } },
1528
0
                                  { KRB5_CRYPTO_TYPE_DATA, { 0 } },
1529
0
                                  { KRB5_CRYPTO_TYPE_DATA, { 0 } },
1530
0
                                  { KRB5_CRYPTO_TYPE_PADDING, { 0 } },
1531
0
                                  { KRB5_CRYPTO_TYPE_TRAILER, { 0 } } };
1532
1533
0
  if (!context)
1534
0
    return SEC_E_INVALID_HANDLE;
1535
1536
0
  if (!(context->flags & SSPI_GSS_C_CONF_FLAG))
1537
0
    return SEC_E_UNSUPPORTED_FUNCTION;
1538
1539
0
  sig_buffer = sspi_FindSecBuffer(pMessage, SECBUFFER_TOKEN);
1540
0
  data_buffer = sspi_FindSecBuffer(pMessage, SECBUFFER_DATA);
1541
1542
0
  if (!sig_buffer || !data_buffer)
1543
0
    return SEC_E_INVALID_TOKEN;
1544
1545
0
  if (fQOP)
1546
0
    return SEC_E_QOP_NOT_SUPPORTED;
1547
1548
0
  flags |= context->acceptor ? FLAG_SENDER_IS_ACCEPTOR : 0;
1549
0
  flags |= FLAG_WRAP_CONFIDENTIAL;
1550
1551
0
  key = get_key(&context->keyset);
1552
0
  if (!key)
1553
0
    return SEC_E_INTERNAL_ERROR;
1554
1555
0
  flags |= context->keyset.acceptor_key == key ? FLAG_ACCEPTOR_SUBKEY : 0;
1556
1557
0
  usage = context->acceptor ? KG_USAGE_ACCEPTOR_SEAL : KG_USAGE_INITIATOR_SEAL;
1558
1559
  /* Set the lengths of the data (plaintext + header) */
1560
0
  encrypt_iov[1].data.length = data_buffer->cbBuffer;
1561
0
  encrypt_iov[2].data.length = 16;
1562
1563
  /* Get the lengths of the header, trailer, and padding and ensure sig_buffer is large enough */
1564
0
  if (krb_log_exec(krb5glue_crypto_length_iov, context->ctx, key, encrypt_iov,
1565
0
                   ARRAYSIZE(encrypt_iov)))
1566
0
    return SEC_E_INTERNAL_ERROR;
1567
0
  if (sig_buffer->cbBuffer <
1568
0
      encrypt_iov[0].data.length + encrypt_iov[3].data.length + encrypt_iov[4].data.length + 32)
1569
0
    return SEC_E_INSUFFICIENT_MEMORY;
1570
1571
  /* Set up the iov array in sig_buffer */
1572
0
  header = sig_buffer->pvBuffer;
1573
0
  encrypt_iov[2].data.data = header + 16;
1574
0
  encrypt_iov[3].data.data = encrypt_iov[2].data.data + encrypt_iov[2].data.length;
1575
0
  encrypt_iov[4].data.data = encrypt_iov[3].data.data + encrypt_iov[3].data.length;
1576
0
  encrypt_iov[0].data.data = encrypt_iov[4].data.data + encrypt_iov[4].data.length;
1577
0
  encrypt_iov[1].data.data = data_buffer->pvBuffer;
1578
1579
  /* Write the GSS header with 0 in RRC */
1580
0
  Data_Write_UINT16_BE(header, TOK_ID_WRAP);
1581
0
  header[2] = flags;
1582
0
  header[3] = (char)0xFF;
1583
0
  Data_Write_UINT32(header + 4, 0);
1584
0
  Data_Write_UINT64_BE(header + 8, (context->local_seq + MessageSeqNo));
1585
1586
  /* Copy header to be encrypted */
1587
0
  CopyMemory(encrypt_iov[2].data.data, header, 16);
1588
1589
  /* Set the correct RRC */
1590
0
  Data_Write_UINT16_BE(header + 6, 16 + encrypt_iov[3].data.length + encrypt_iov[4].data.length);
1591
1592
0
  if (krb_log_exec(krb5glue_encrypt_iov, context->ctx, key, usage, encrypt_iov,
1593
0
                   ARRAYSIZE(encrypt_iov)))
1594
0
    return SEC_E_INTERNAL_ERROR;
1595
1596
0
  return SEC_E_OK;
1597
#else
1598
  return SEC_E_UNSUPPORTED_FUNCTION;
1599
#endif
1600
0
}
1601
1602
static SECURITY_STATUS SEC_ENTRY kerberos_DecryptMessage(PCtxtHandle phContext,
1603
                                                         PSecBufferDesc pMessage,
1604
                                                         ULONG MessageSeqNo, ULONG* pfQOP)
1605
0
{
1606
0
#ifdef WITH_KRB5
1607
0
  KRB_CONTEXT* context = get_context(phContext);
1608
0
  PSecBuffer sig_buffer = NULL;
1609
0
  PSecBuffer data_buffer = NULL;
1610
0
  krb5glue_key key = NULL;
1611
0
  krb5_keyusage usage = 0;
1612
0
  char* header = NULL;
1613
0
  uint16_t tok_id = 0;
1614
0
  BYTE flags = 0;
1615
0
  uint16_t ec = 0;
1616
0
  uint16_t rrc = 0;
1617
0
  uint64_t seq_no = 0;
1618
0
  krb5_crypto_iov iov[] = { { KRB5_CRYPTO_TYPE_HEADER, { 0 } },
1619
0
                          { KRB5_CRYPTO_TYPE_DATA, { 0 } },
1620
0
                          { KRB5_CRYPTO_TYPE_DATA, { 0 } },
1621
0
                          { KRB5_CRYPTO_TYPE_PADDING, { 0 } },
1622
0
                          { KRB5_CRYPTO_TYPE_TRAILER, { 0 } } };
1623
1624
0
  if (!context)
1625
0
    return SEC_E_INVALID_HANDLE;
1626
1627
0
  if (!(context->flags & SSPI_GSS_C_CONF_FLAG))
1628
0
    return SEC_E_UNSUPPORTED_FUNCTION;
1629
1630
0
  sig_buffer = sspi_FindSecBuffer(pMessage, SECBUFFER_TOKEN);
1631
0
  data_buffer = sspi_FindSecBuffer(pMessage, SECBUFFER_DATA);
1632
1633
0
  if (!sig_buffer || !data_buffer || sig_buffer->cbBuffer < 16)
1634
0
    return SEC_E_INVALID_TOKEN;
1635
1636
  /* Read in header information */
1637
0
  header = sig_buffer->pvBuffer;
1638
0
  Data_Read_UINT16_BE(header, tok_id);
1639
0
  flags = header[2];
1640
0
  Data_Read_UINT16_BE((header + 4), ec);
1641
0
  Data_Read_UINT16_BE((header + 6), rrc);
1642
0
  Data_Read_UINT64_BE((header + 8), seq_no);
1643
1644
  /* Check that the header is valid */
1645
0
  if (tok_id != TOK_ID_WRAP || (BYTE)header[3] != 0xFF)
1646
0
    return SEC_E_INVALID_TOKEN;
1647
1648
0
  if ((flags & FLAG_SENDER_IS_ACCEPTOR) == context->acceptor)
1649
0
    return SEC_E_INVALID_TOKEN;
1650
1651
0
  if (context->flags & ISC_REQ_SEQUENCE_DETECT && seq_no != context->remote_seq + MessageSeqNo)
1652
0
    return SEC_E_OUT_OF_SEQUENCE;
1653
1654
0
  if (!(flags & FLAG_WRAP_CONFIDENTIAL))
1655
0
    return SEC_E_INVALID_TOKEN;
1656
1657
  /* We don't expect a trailer buffer; the encrypted header must be rotated */
1658
0
  if (rrc < 16)
1659
0
    return SEC_E_INVALID_TOKEN;
1660
1661
  /* Find the proper key and key usage */
1662
0
  key = get_key(&context->keyset);
1663
0
  if (!key || (flags & FLAG_ACCEPTOR_SUBKEY && context->keyset.acceptor_key != key))
1664
0
    return SEC_E_INTERNAL_ERROR;
1665
0
  usage = context->acceptor ? KG_USAGE_INITIATOR_SEAL : KG_USAGE_ACCEPTOR_SEAL;
1666
1667
  /* Fill in the lengths of the iov array */
1668
0
  iov[1].data.length = data_buffer->cbBuffer;
1669
0
  iov[2].data.length = 16;
1670
0
  if (krb_log_exec(krb5glue_crypto_length_iov, context->ctx, key, iov, ARRAYSIZE(iov)))
1671
0
    return SEC_E_INTERNAL_ERROR;
1672
1673
  /* We don't expect a trailer buffer; everything must be in sig_buffer */
1674
0
  if (rrc != 16 + iov[3].data.length + iov[4].data.length)
1675
0
    return SEC_E_INVALID_TOKEN;
1676
0
  if (sig_buffer->cbBuffer != 16 + rrc + iov[0].data.length)
1677
0
    return SEC_E_INVALID_TOKEN;
1678
1679
  /* Locate the parts of the message */
1680
0
  iov[0].data.data = header + 16 + rrc + ec;
1681
0
  iov[1].data.data = data_buffer->pvBuffer;
1682
0
  iov[2].data.data = header + 16 + ec;
1683
0
  iov[3].data.data = iov[2].data.data + iov[2].data.length;
1684
0
  iov[4].data.data = iov[3].data.data + iov[3].data.length;
1685
1686
0
  if (krb_log_exec(krb5glue_decrypt_iov, context->ctx, key, usage, iov, ARRAYSIZE(iov)))
1687
0
    return SEC_E_INTERNAL_ERROR;
1688
1689
  /* Validate the encrypted header */
1690
0
  Data_Write_UINT16_BE(iov[2].data.data + 4, ec);
1691
0
  Data_Write_UINT16_BE(iov[2].data.data + 6, rrc);
1692
0
  if (memcmp(iov[2].data.data, header, 16) != 0)
1693
0
    return SEC_E_MESSAGE_ALTERED;
1694
1695
0
  *pfQOP = 0;
1696
1697
0
  return SEC_E_OK;
1698
#else
1699
  return SEC_E_UNSUPPORTED_FUNCTION;
1700
#endif
1701
0
}
1702
1703
static SECURITY_STATUS SEC_ENTRY kerberos_MakeSignature(PCtxtHandle phContext, ULONG fQOP,
1704
                                                        PSecBufferDesc pMessage, ULONG MessageSeqNo)
1705
0
{
1706
0
#ifdef WITH_KRB5
1707
0
  KRB_CONTEXT* context = get_context(phContext);
1708
0
  PSecBuffer sig_buffer = NULL;
1709
0
  PSecBuffer data_buffer = NULL;
1710
0
  krb5glue_key key = NULL;
1711
0
  krb5_keyusage usage = 0;
1712
0
  char* header = NULL;
1713
0
  BYTE flags = 0;
1714
0
  krb5_crypto_iov iov[] = { { KRB5_CRYPTO_TYPE_DATA, { 0 } },
1715
0
                          { KRB5_CRYPTO_TYPE_DATA, { 0 } },
1716
0
                          { KRB5_CRYPTO_TYPE_CHECKSUM, { 0 } } };
1717
1718
0
  if (!context)
1719
0
    return SEC_E_INVALID_HANDLE;
1720
1721
0
  if (!(context->flags & SSPI_GSS_C_INTEG_FLAG))
1722
0
    return SEC_E_UNSUPPORTED_FUNCTION;
1723
1724
0
  sig_buffer = sspi_FindSecBuffer(pMessage, SECBUFFER_TOKEN);
1725
0
  data_buffer = sspi_FindSecBuffer(pMessage, SECBUFFER_DATA);
1726
1727
0
  if (!sig_buffer || !data_buffer)
1728
0
    return SEC_E_INVALID_TOKEN;
1729
1730
0
  flags |= context->acceptor ? FLAG_SENDER_IS_ACCEPTOR : 0;
1731
1732
0
  key = get_key(&context->keyset);
1733
0
  if (!key)
1734
0
    return SEC_E_INTERNAL_ERROR;
1735
0
  usage = context->acceptor ? KG_USAGE_ACCEPTOR_SIGN : KG_USAGE_INITIATOR_SIGN;
1736
1737
0
  flags |= context->keyset.acceptor_key == key ? FLAG_ACCEPTOR_SUBKEY : 0;
1738
1739
  /* Fill in the lengths of the iov array */
1740
0
  iov[0].data.length = data_buffer->cbBuffer;
1741
0
  iov[1].data.length = 16;
1742
0
  if (krb_log_exec(krb5glue_crypto_length_iov, context->ctx, key, iov, ARRAYSIZE(iov)))
1743
0
    return SEC_E_INTERNAL_ERROR;
1744
1745
  /* Ensure the buffer is big enough */
1746
0
  if (sig_buffer->cbBuffer < iov[2].data.length + 16)
1747
0
    return SEC_E_INSUFFICIENT_MEMORY;
1748
1749
  /* Write the header */
1750
0
  header = sig_buffer->pvBuffer;
1751
0
  Data_Write_UINT16_BE(header, TOK_ID_MIC);
1752
0
  header[2] = flags;
1753
0
  memset(header + 3, 0xFF, 5);
1754
0
  Data_Write_UINT64_BE(header + 8, (context->local_seq + MessageSeqNo));
1755
1756
  /* Set up the iov array */
1757
0
  iov[0].data.data = data_buffer->pvBuffer;
1758
0
  iov[1].data.data = header;
1759
0
  iov[2].data.data = header + 16;
1760
1761
0
  if (krb_log_exec(krb5glue_make_checksum_iov, context->ctx, key, usage, iov, ARRAYSIZE(iov)))
1762
0
    return SEC_E_INTERNAL_ERROR;
1763
1764
0
  sig_buffer->cbBuffer = iov[2].data.length + 16;
1765
1766
0
  return SEC_E_OK;
1767
#else
1768
  return SEC_E_UNSUPPORTED_FUNCTION;
1769
#endif
1770
0
}
1771
1772
static SECURITY_STATUS SEC_ENTRY kerberos_VerifySignature(PCtxtHandle phContext,
1773
                                                          PSecBufferDesc pMessage,
1774
                                                          ULONG MessageSeqNo, ULONG* pfQOP)
1775
0
{
1776
0
#ifdef WITH_KRB5
1777
0
  PSecBuffer sig_buffer = NULL;
1778
0
  PSecBuffer data_buffer = NULL;
1779
0
  krb5glue_key key = NULL;
1780
0
  krb5_keyusage usage = 0;
1781
0
  char* header = NULL;
1782
0
  BYTE flags = 0;
1783
0
  uint16_t tok_id = 0;
1784
0
  uint64_t seq_no = 0;
1785
0
  krb5_boolean is_valid = 0;
1786
0
  krb5_crypto_iov iov[] = { { KRB5_CRYPTO_TYPE_DATA, { 0 } },
1787
0
                          { KRB5_CRYPTO_TYPE_DATA, { 0 } },
1788
0
                          { KRB5_CRYPTO_TYPE_CHECKSUM, { 0 } } };
1789
0
  BYTE cmp_filler[] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
1790
1791
0
  KRB_CONTEXT* context = get_context(phContext);
1792
0
  if (!context)
1793
0
    return SEC_E_INVALID_HANDLE;
1794
1795
0
  if (!(context->flags & SSPI_GSS_C_INTEG_FLAG))
1796
0
    return SEC_E_UNSUPPORTED_FUNCTION;
1797
1798
0
  sig_buffer = sspi_FindSecBuffer(pMessage, SECBUFFER_TOKEN);
1799
0
  data_buffer = sspi_FindSecBuffer(pMessage, SECBUFFER_DATA);
1800
1801
0
  if (!sig_buffer || !data_buffer || sig_buffer->cbBuffer < 16)
1802
0
    return SEC_E_INVALID_TOKEN;
1803
1804
  /* Read in header info */
1805
0
  header = sig_buffer->pvBuffer;
1806
0
  Data_Read_UINT16_BE(header, tok_id);
1807
0
  flags = header[2];
1808
0
  Data_Read_UINT64_BE((header + 8), seq_no);
1809
1810
  /* Validate header */
1811
0
  if (tok_id != TOK_ID_MIC)
1812
0
    return SEC_E_INVALID_TOKEN;
1813
1814
0
  if ((flags & FLAG_SENDER_IS_ACCEPTOR) == context->acceptor || flags & FLAG_WRAP_CONFIDENTIAL)
1815
0
    return SEC_E_INVALID_TOKEN;
1816
1817
0
  if (memcmp(header + 3, cmp_filler, sizeof(cmp_filler)) != 0)
1818
0
    return SEC_E_INVALID_TOKEN;
1819
1820
0
  if (context->flags & ISC_REQ_SEQUENCE_DETECT && seq_no != context->remote_seq + MessageSeqNo)
1821
0
    return SEC_E_OUT_OF_SEQUENCE;
1822
1823
  /* Find the proper key and usage */
1824
0
  key = get_key(&context->keyset);
1825
0
  if (!key || (flags & FLAG_ACCEPTOR_SUBKEY && context->keyset.acceptor_key != key))
1826
0
    return SEC_E_INTERNAL_ERROR;
1827
0
  usage = context->acceptor ? KG_USAGE_INITIATOR_SIGN : KG_USAGE_ACCEPTOR_SIGN;
1828
1829
  /* Fill in the iov array lengths */
1830
0
  iov[0].data.length = data_buffer->cbBuffer;
1831
0
  iov[1].data.length = 16;
1832
0
  if (krb_log_exec(krb5glue_crypto_length_iov, context->ctx, key, iov, ARRAYSIZE(iov)))
1833
0
    return SEC_E_INTERNAL_ERROR;
1834
1835
0
  if (sig_buffer->cbBuffer != iov[2].data.length + 16)
1836
0
    return SEC_E_INTERNAL_ERROR;
1837
1838
  /* Set up the iov array */
1839
0
  iov[0].data.data = data_buffer->pvBuffer;
1840
0
  iov[1].data.data = header;
1841
0
  iov[2].data.data = header + 16;
1842
1843
0
  if (krb_log_exec(krb5glue_verify_checksum_iov, context->ctx, key, usage, iov, ARRAYSIZE(iov),
1844
0
                   &is_valid))
1845
0
    return SEC_E_INTERNAL_ERROR;
1846
1847
0
  if (!is_valid)
1848
0
    return SEC_E_MESSAGE_ALTERED;
1849
1850
0
  return SEC_E_OK;
1851
#else
1852
  return SEC_E_UNSUPPORTED_FUNCTION;
1853
#endif
1854
0
}
1855
1856
const SecurityFunctionTableA KERBEROS_SecurityFunctionTableA = {
1857
  3,                                    /* dwVersion */
1858
  NULL,                                 /* EnumerateSecurityPackages */
1859
  kerberos_QueryCredentialsAttributesA, /* QueryCredentialsAttributes */
1860
  kerberos_AcquireCredentialsHandleA,   /* AcquireCredentialsHandle */
1861
  kerberos_FreeCredentialsHandle,       /* FreeCredentialsHandle */
1862
  NULL,                                 /* Reserved2 */
1863
  kerberos_InitializeSecurityContextA,  /* InitializeSecurityContext */
1864
  kerberos_AcceptSecurityContext,       /* AcceptSecurityContext */
1865
  NULL,                                 /* CompleteAuthToken */
1866
  kerberos_DeleteSecurityContext,       /* DeleteSecurityContext */
1867
  NULL,                                 /* ApplyControlToken */
1868
  kerberos_QueryContextAttributesA,     /* QueryContextAttributes */
1869
  NULL,                                 /* ImpersonateSecurityContext */
1870
  NULL,                                 /* RevertSecurityContext */
1871
  kerberos_MakeSignature,               /* MakeSignature */
1872
  kerberos_VerifySignature,             /* VerifySignature */
1873
  NULL,                                 /* FreeContextBuffer */
1874
  NULL,                                 /* QuerySecurityPackageInfo */
1875
  NULL,                                 /* Reserved3 */
1876
  NULL,                                 /* Reserved4 */
1877
  NULL,                                 /* ExportSecurityContext */
1878
  NULL,                                 /* ImportSecurityContext */
1879
  NULL,                                 /* AddCredentials */
1880
  NULL,                                 /* Reserved8 */
1881
  NULL,                                 /* QuerySecurityContextToken */
1882
  kerberos_EncryptMessage,              /* EncryptMessage */
1883
  kerberos_DecryptMessage,              /* DecryptMessage */
1884
  kerberos_SetContextAttributesA,       /* SetContextAttributes */
1885
  kerberos_SetCredentialsAttributesA,   /* SetCredentialsAttributes */
1886
};
1887
1888
const SecurityFunctionTableW KERBEROS_SecurityFunctionTableW = {
1889
  3,                                    /* dwVersion */
1890
  NULL,                                 /* EnumerateSecurityPackages */
1891
  kerberos_QueryCredentialsAttributesW, /* QueryCredentialsAttributes */
1892
  kerberos_AcquireCredentialsHandleW,   /* AcquireCredentialsHandle */
1893
  kerberos_FreeCredentialsHandle,       /* FreeCredentialsHandle */
1894
  NULL,                                 /* Reserved2 */
1895
  kerberos_InitializeSecurityContextW,  /* InitializeSecurityContext */
1896
  kerberos_AcceptSecurityContext,       /* AcceptSecurityContext */
1897
  NULL,                                 /* CompleteAuthToken */
1898
  kerberos_DeleteSecurityContext,       /* DeleteSecurityContext */
1899
  NULL,                                 /* ApplyControlToken */
1900
  kerberos_QueryContextAttributesW,     /* QueryContextAttributes */
1901
  NULL,                                 /* ImpersonateSecurityContext */
1902
  NULL,                                 /* RevertSecurityContext */
1903
  kerberos_MakeSignature,               /* MakeSignature */
1904
  kerberos_VerifySignature,             /* VerifySignature */
1905
  NULL,                                 /* FreeContextBuffer */
1906
  NULL,                                 /* QuerySecurityPackageInfo */
1907
  NULL,                                 /* Reserved3 */
1908
  NULL,                                 /* Reserved4 */
1909
  NULL,                                 /* ExportSecurityContext */
1910
  NULL,                                 /* ImportSecurityContext */
1911
  NULL,                                 /* AddCredentials */
1912
  NULL,                                 /* Reserved8 */
1913
  NULL,                                 /* QuerySecurityContextToken */
1914
  kerberos_EncryptMessage,              /* EncryptMessage */
1915
  kerberos_DecryptMessage,              /* DecryptMessage */
1916
  kerberos_SetContextAttributesW,       /* SetContextAttributes */
1917
  kerberos_SetCredentialsAttributesW,   /* SetCredentialsAttributes */
1918
};
1919
1920
BOOL KERBEROS_init(void)
1921
0
{
1922
0
  InitializeConstWCharFromUtf8(KERBEROS_SecPkgInfoA.Name, KERBEROS_SecPkgInfoW_NameBuffer,
1923
0
                               ARRAYSIZE(KERBEROS_SecPkgInfoW_NameBuffer));
1924
0
  InitializeConstWCharFromUtf8(KERBEROS_SecPkgInfoA.Comment, KERBEROS_SecPkgInfoW_CommentBuffer,
1925
0
                               ARRAYSIZE(KERBEROS_SecPkgInfoW_CommentBuffer));
1926
0
  return TRUE;
1927
0
}