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/Negotiate/negotiate.c
Line
Count
Source
1
/**
2
 * WinPR: Windows Portable Runtime
3
 * Negotiate Security Package
4
 *
5
 * Copyright 2011-2014 Marc-Andre Moreau <marcandre.moreau@gmail.com>
6
 * Copyright 2017 Dorian Ducournau <dorian.ducournau@gmail.com>
7
 *
8
 * Licensed under the Apache License, Version 2.0 (the "License");
9
 * you may not use this file except in compliance with the License.
10
 * You may obtain a copy of the License at
11
 *
12
 *     http://www.apache.org/licenses/LICENSE-2.0
13
 *
14
 * Unless required by applicable law or agreed to in writing, software
15
 * distributed under the License is distributed on an "AS IS" BASIS,
16
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
 * See the License for the specific language governing permissions and
18
 * limitations under the License.
19
 */
20
21
#include <winpr/config.h>
22
23
#include <winpr/crt.h>
24
#include <winpr/wtypes.h>
25
#include <winpr/assert.h>
26
#include <winpr/sspi.h>
27
#include <winpr/tchar.h>
28
#if !defined(WITHOUT_WINPR_3x_DEPRECATED)
29
#include <winpr/registry.h>
30
#endif
31
#include <winpr/build-config.h>
32
#include <winpr/asn1.h>
33
#include <winpr/path.h>
34
#include <winpr/config-readers.h>
35
36
#include "negotiate.h"
37
38
#include "../NTLM/ntlm.h"
39
#include "../NTLM/ntlm_export.h"
40
#include "../Kerberos/kerberos.h"
41
#include "../sspi.h"
42
#include "../../utils.h"
43
#include "../../log.h"
44
#define TAG WINPR_TAG("negotiate")
45
46
#if !defined(WITHOUT_WINPR_3x_DEPRECATED)
47
0
#define NEGO_REG_KEY "Software\\%s\\SSPI\\Negotiate"
48
#endif
49
50
static const char PACKAGE_NAME_DISABLE_ALL[] = "none";
51
static const char PACKAGE_NAME_NTLM[] = "ntlm";
52
static const char PACKAGE_NAME_KERBEROS[] = "kerberos";
53
static const char PACKAGE_NAME_KERBEROS_U2U[] = "u2u";
54
55
typedef struct
56
{
57
  const TCHAR* name;
58
  const SecurityFunctionTableA* table;
59
  const SecurityFunctionTableW* table_w;
60
} SecPkg;
61
62
struct Mech_st
63
{
64
  const WinPrAsn1_OID* oid;
65
  const SecPkg* pkg;
66
  const UINT flags;
67
  const BOOL preferred;
68
};
69
70
typedef struct
71
{
72
  const Mech* mech;
73
  CredHandle cred;
74
  BOOL valid;
75
} MechCred;
76
77
const SecPkgInfoA NEGOTIATE_SecPkgInfoA = {
78
  0x00083BB3,                    /* fCapabilities */
79
  1,                             /* wVersion */
80
  0x0009,                        /* wRPCID */
81
  0x00002FE0,                    /* cbMaxToken */
82
  "Negotiate",                   /* Name */
83
  "Microsoft Package Negotiator" /* Comment */
84
};
85
86
static WCHAR NEGOTIATE_SecPkgInfoW_NameBuffer[32] = WINPR_C_ARRAY_INIT;
87
static WCHAR NEGOTIATE_SecPkgInfoW_CommentBuffer[32] = WINPR_C_ARRAY_INIT;
88
89
const SecPkgInfoW NEGOTIATE_SecPkgInfoW = {
90
  0x00083BB3,                         /* fCapabilities */
91
  1,                                  /* wVersion */
92
  0x0009,                             /* wRPCID */
93
  0x00002FE0,                         /* cbMaxToken */
94
  NEGOTIATE_SecPkgInfoW_NameBuffer,   /* Name */
95
  NEGOTIATE_SecPkgInfoW_CommentBuffer /* Comment */
96
};
97
98
static const WinPrAsn1_OID spnego_OID = { 6, (BYTE*)"\x2b\x06\x01\x05\x05\x02" };
99
static const WinPrAsn1_OID kerberos_u2u_OID = { 10,
100
                                              (BYTE*)"\x2a\x86\x48\x86\xf7\x12\x01\x02\x02\x03" };
101
static const WinPrAsn1_OID kerberos_OID = { 9, (BYTE*)"\x2a\x86\x48\x86\xf7\x12\x01\x02\x02" };
102
static const WinPrAsn1_OID kerberos_wrong_OID = { 9,
103
                                                (BYTE*)"\x2a\x86\x48\x82\xf7\x12\x01\x02\x02" };
104
static const WinPrAsn1_OID ntlm_OID = { 10, (BYTE*)"\x2b\x06\x01\x04\x01\x82\x37\x02\x02\x0a" };
105
106
static const WinPrAsn1_OID negoex_OID = { 10, (BYTE*)"\x2b\x06\x01\x04\x01\x82\x37\x02\x02\x1e" };
107
108
#ifdef WITH_KRB5
109
static const SecPkg SecPkgTable[] = {
110
  { KERBEROS_SSP_NAME, &KERBEROS_SecurityFunctionTableA, &KERBEROS_SecurityFunctionTableW },
111
  { KERBEROS_SSP_NAME, &KERBEROS_SecurityFunctionTableA, &KERBEROS_SecurityFunctionTableW },
112
  { NTLM_SSP_NAME, &NTLM_SecurityFunctionTableA, &NTLM_SecurityFunctionTableW }
113
};
114
115
static const Mech MechTable[] = {
116
  { &kerberos_u2u_OID, &SecPkgTable[0], ISC_REQ_INTEGRITY | ISC_REQ_USE_SESSION_KEY, TRUE },
117
  { &kerberos_OID, &SecPkgTable[1], ISC_REQ_INTEGRITY, TRUE },
118
  { &ntlm_OID, &SecPkgTable[2], 0, FALSE },
119
};
120
#else
121
static const SecPkg SecPkgTable[] = { { NTLM_SSP_NAME, &NTLM_SecurityFunctionTableA,
122
                                      &NTLM_SecurityFunctionTableW } };
123
124
static const Mech MechTable[] = {
125
  { &ntlm_OID, &SecPkgTable[0], 0, FALSE },
126
};
127
#endif
128
129
static const size_t MECH_COUNT = ARRAYSIZE(MechTable);
130
131
enum NegState
132
{
133
  NOSTATE = -1,
134
  ACCEPT_COMPLETED,
135
  ACCEPT_INCOMPLETE,
136
  REJECT,
137
  REQUEST_MIC
138
};
139
140
typedef struct
141
{
142
  enum NegState negState;
143
  BOOL init;
144
  WinPrAsn1_OID supportedMech;
145
  SecBuffer mechTypes;
146
  SecBuffer mechToken;
147
  SecBuffer mic;
148
} NegToken;
149
150
static const NegToken empty_neg_token = { NOSTATE,           FALSE,
151
                                        { 0, nullptr },    { 0, 0, nullptr },
152
                                        { 0, 0, nullptr }, { 0, 0, nullptr } };
153
154
static NEGOTIATE_CONTEXT* negotiate_ContextNew(NEGOTIATE_CONTEXT* init_context)
155
0
{
156
0
  NEGOTIATE_CONTEXT* context = nullptr;
157
158
0
  WINPR_ASSERT(init_context);
159
160
0
  context = calloc(1, sizeof(NEGOTIATE_CONTEXT));
161
0
  if (!context)
162
0
    return nullptr;
163
164
0
  if (init_context->spnego)
165
0
  {
166
0
    init_context->mechTypes.pvBuffer = malloc(init_context->mechTypes.cbBuffer);
167
0
    if (!init_context->mechTypes.pvBuffer)
168
0
    {
169
0
      free(context);
170
0
      return nullptr;
171
0
    }
172
0
  }
173
174
0
  *context = *init_context;
175
176
0
  return context;
177
0
}
178
179
static void negotiate_ContextFree(NEGOTIATE_CONTEXT* context)
180
0
{
181
0
  WINPR_ASSERT(context);
182
183
0
  if (context->mechTypes.pvBuffer)
184
0
    free(context->mechTypes.pvBuffer);
185
0
  free(context);
186
0
}
187
188
static const char* negotiate_mech_name(const WinPrAsn1_OID* oid)
189
0
{
190
0
  if (sspi_gss_oid_compare(oid, &spnego_OID))
191
0
    return "SPNEGO (1.3.6.1.5.5.2)";
192
0
  else if (sspi_gss_oid_compare(oid, &kerberos_u2u_OID))
193
0
    return "Kerberos user to user (1.2.840.113554.1.2.2.3)";
194
0
  else if (sspi_gss_oid_compare(oid, &kerberos_OID))
195
0
    return "Kerberos (1.2.840.113554.1.2.2)";
196
0
  else if (sspi_gss_oid_compare(oid, &kerberos_wrong_OID))
197
0
    return "Kerberos [wrong OID] (1.2.840.48018.1.2.2)";
198
0
  else if (sspi_gss_oid_compare(oid, &ntlm_OID))
199
0
    return "NTLM (1.3.6.1.4.1.311.2.2.10)";
200
0
  else if (sspi_gss_oid_compare(oid, &negoex_OID))
201
0
    return "NegoEx (1.3.6.1.4.1.311.2.2.30)";
202
0
  else
203
0
    return "Unknown mechanism";
204
0
}
205
206
static const Mech* negotiate_GetMechByOID(const WinPrAsn1_OID* oid)
207
0
{
208
0
  WINPR_ASSERT(oid);
209
210
0
  WinPrAsn1_OID testOid = *oid;
211
212
0
  if (sspi_gss_oid_compare(&testOid, &kerberos_wrong_OID))
213
0
  {
214
0
    testOid.len = kerberos_OID.len;
215
0
    testOid.data = kerberos_OID.data;
216
0
  }
217
218
0
  for (size_t i = 0; i < MECH_COUNT; i++)
219
0
  {
220
0
    if (sspi_gss_oid_compare(&testOid, MechTable[i].oid))
221
0
      return &MechTable[i];
222
0
  }
223
0
  return nullptr;
224
0
}
225
226
static PSecHandle negotiate_FindCredential(MechCred* creds, const Mech* mech)
227
0
{
228
0
  WINPR_ASSERT(creds);
229
230
0
  if (!mech)
231
0
    return nullptr;
232
233
0
  for (size_t i = 0; i < MECH_COUNT; i++)
234
0
  {
235
0
    MechCred* cred = &creds[i];
236
237
0
    if (cred->mech == mech)
238
0
    {
239
0
      if (cred->valid)
240
0
        return &cred->cred;
241
0
      return nullptr;
242
0
    }
243
0
  }
244
245
0
  return nullptr;
246
0
}
247
248
#if !defined(WITHOUT_WINPR_3x_DEPRECATED)
249
static BOOL negotiate_get_dword(HKEY hKey, const char* subkey, DWORD* pdwValue)
250
0
{
251
0
  DWORD dwValue = 0;
252
0
  DWORD dwType = 0;
253
0
  DWORD dwSize = sizeof(dwValue);
254
0
  LONG rc = RegQueryValueExA(hKey, subkey, nullptr, &dwType, (BYTE*)&dwValue, &dwSize);
255
256
0
  if (rc != ERROR_SUCCESS)
257
0
    return FALSE;
258
0
  if (dwType != REG_DWORD)
259
0
    return FALSE;
260
261
0
  *pdwValue = dwValue;
262
0
  return TRUE;
263
0
}
264
#endif
265
266
static BOOL negotiate_get_config_from_auth_package_list(void* pAuthData, BOOL* kerberos, BOOL* ntlm,
267
                                                        BOOL* u2u)
268
0
{
269
0
  BOOL rc = FALSE;
270
0
  char* tok_ctx = nullptr;
271
0
  char* PackageList = nullptr;
272
273
0
  if (!sspi_CopyAuthPackageListA((const SEC_WINNT_AUTH_IDENTITY_INFO*)pAuthData, &PackageList))
274
0
    return FALSE;
275
276
0
  char* tok_ptr = strtok_s(PackageList, ",", &tok_ctx);
277
278
0
  while (tok_ptr)
279
0
  {
280
0
    const char* PackageName = tok_ptr;
281
0
    BOOL PackageInclude = TRUE;
282
283
0
    if (PackageName[0] == '!')
284
0
    {
285
0
      PackageName = &PackageName[1];
286
0
      PackageInclude = FALSE;
287
0
    }
288
289
0
    if (_stricmp(PackageName, PACKAGE_NAME_NTLM) == 0)
290
0
    {
291
0
      *ntlm = PackageInclude;
292
0
    }
293
0
    else if (_stricmp(PackageName, PACKAGE_NAME_KERBEROS) == 0)
294
0
    {
295
0
      *kerberos = PackageInclude;
296
0
    }
297
0
    else if (_stricmp(PackageName, PACKAGE_NAME_KERBEROS_U2U) == 0)
298
0
    {
299
0
      *u2u = PackageInclude;
300
0
    }
301
0
    else if (_stricmp(PackageName, PACKAGE_NAME_DISABLE_ALL) == 0)
302
0
    {
303
0
      *kerberos = FALSE;
304
0
      *ntlm = FALSE;
305
0
      *u2u = FALSE;
306
307
0
      if (PackageName != PackageList)
308
0
      {
309
0
        WLog_WARN(TAG, "Special keyword '%s' not first in list, aborting", PackageName);
310
0
        goto fail;
311
0
      }
312
0
    }
313
0
    else
314
0
    {
315
0
      WLog_WARN(TAG, "Unknown authentication package name: %s, ignoring", PackageName);
316
0
    }
317
318
0
    tok_ptr = strtok_s(nullptr, ",", &tok_ctx);
319
0
  }
320
321
0
  rc = TRUE;
322
0
fail:
323
0
  free(PackageList);
324
0
  return rc;
325
0
}
326
327
static BOOL negotiate_get_config(void* pAuthData, BOOL* kerberos, BOOL* ntlm, BOOL* u2u)
328
0
{
329
0
  WINPR_ASSERT(kerberos);
330
0
  WINPR_ASSERT(ntlm);
331
0
  WINPR_ASSERT(u2u);
332
333
0
#if !defined(WITH_KRB5_NO_NTLM_FALLBACK)
334
0
  *ntlm = TRUE;
335
#else
336
  *ntlm = FALSE;
337
#endif
338
0
#if defined(WITH_KRB5)
339
0
  *kerberos = TRUE;
340
0
  *u2u = TRUE;
341
#else
342
  *kerberos = FALSE;
343
  *u2u = FALSE;
344
#endif
345
346
0
  if (negotiate_get_config_from_auth_package_list(pAuthData, kerberos, ntlm, u2u))
347
0
  {
348
0
    return TRUE; // use explicit authentication package list
349
0
  }
350
351
0
  const char config[] = "negotiate.json";
352
353
0
#if !defined(WITHOUT_WINPR_3x_DEPRECATED)
354
0
  {
355
0
    char* key = winpr_getApplicatonDetailsRegKey(NEGO_REG_KEY);
356
0
    if (key)
357
0
    {
358
0
      HKEY hKey = nullptr;
359
0
      const LONG rc =
360
0
          RegOpenKeyExA(HKEY_LOCAL_MACHINE, key, 0, KEY_READ | KEY_WOW64_64KEY, &hKey);
361
0
      free(key);
362
0
      if (rc == ERROR_SUCCESS)
363
0
      {
364
0
        WLog_WARN(TAG, "HKLM.reg is deprecated since 3.33.0. ATTENTION: Use %s instead!",
365
0
                  config);
366
367
0
        DWORD dwValue = 0;
368
369
0
        if (negotiate_get_dword(hKey, PACKAGE_NAME_KERBEROS, &dwValue))
370
0
          *kerberos = (dwValue != 0);
371
372
0
        if (negotiate_get_dword(hKey, PACKAGE_NAME_KERBEROS_U2U, &dwValue))
373
0
          *u2u = (dwValue != 0);
374
375
0
#if !defined(WITH_KRB5_NO_NTLM_FALLBACK)
376
0
        if (negotiate_get_dword(hKey, PACKAGE_NAME_NTLM, &dwValue))
377
0
          *ntlm = (dwValue != 0);
378
0
#endif
379
380
0
        RegCloseKey(hKey);
381
0
      }
382
0
    }
383
0
  }
384
0
#endif
385
386
0
  WINPR_JSON* json = winpr_GetJSONConfigFile(TRUE, config);
387
0
  if (json)
388
0
  {
389
0
    winpr_config_apply_bool(config, json, PACKAGE_NAME_KERBEROS, kerberos);
390
0
    winpr_config_apply_bool(config, json, PACKAGE_NAME_KERBEROS_U2U, u2u);
391
0
#if !defined(WITH_KRB5_NO_NTLM_FALLBACK)
392
0
    winpr_config_apply_bool(config, json, PACKAGE_NAME_NTLM, ntlm);
393
0
#endif
394
0
    WINPR_JSON_Delete(json);
395
0
  }
396
397
0
  return TRUE;
398
0
}
399
400
static BOOL negotiate_write_neg_token(PSecBuffer output_buffer, NegToken* token)
401
0
{
402
0
  WINPR_ASSERT(output_buffer);
403
0
  WINPR_ASSERT(token);
404
405
0
  BOOL ret = FALSE;
406
0
  WinPrAsn1Encoder* enc = nullptr;
407
0
  WinPrAsn1_MemoryChunk mechTypes = { token->mechTypes.cbBuffer, token->mechTypes.pvBuffer };
408
0
  WinPrAsn1_OctetString mechToken = { token->mechToken.cbBuffer, token->mechToken.pvBuffer };
409
0
  WinPrAsn1_OctetString mechListMic = { token->mic.cbBuffer, token->mic.pvBuffer };
410
0
  wStream s;
411
0
  size_t len = 0;
412
413
0
  enc = WinPrAsn1Encoder_New(WINPR_ASN1_DER);
414
0
  if (!enc)
415
0
    return FALSE;
416
417
  /* For NegTokenInit wrap in an initialContextToken */
418
0
  if (token->init)
419
0
  {
420
    /* InitialContextToken [APPLICATION 0] IMPLICIT SEQUENCE */
421
0
    if (!WinPrAsn1EncAppContainer(enc, 0))
422
0
      goto cleanup;
423
424
    /* thisMech MechType OID */
425
0
    if (!WinPrAsn1EncOID(enc, &spnego_OID))
426
0
      goto cleanup;
427
0
  }
428
429
  /* innerContextToken [0] NegTokenInit or [1] NegTokenResp */
430
0
  if (!WinPrAsn1EncContextualSeqContainer(enc, token->init ? 0 : 1))
431
0
    goto cleanup;
432
433
0
  WLog_DBG(TAG, token->init ? "Writing negTokenInit..." : "Writing negTokenResp...");
434
435
  /* mechTypes [0] MechTypeList (mechTypes already contains the SEQUENCE tag) */
436
0
  if (token->init)
437
0
  {
438
0
    if (!WinPrAsn1EncContextualRawContent(enc, 0, &mechTypes))
439
0
      goto cleanup;
440
0
    WLog_DBG(TAG, "\tmechTypes [0] (%" PRIu32 " bytes)", token->mechTypes.cbBuffer);
441
0
  }
442
  /* negState [0] ENUMERATED */
443
0
  else if (token->negState != NOSTATE)
444
0
  {
445
0
    if (!WinPrAsn1EncContextualEnumerated(enc, 0, token->negState))
446
0
      goto cleanup;
447
0
    WLog_DBG(TAG, "\tnegState [0] (%d)", token->negState);
448
0
  }
449
450
  /* supportedMech [1] OID */
451
0
  if (token->supportedMech.len)
452
0
  {
453
0
    if (!WinPrAsn1EncContextualOID(enc, 1, &token->supportedMech))
454
0
      goto cleanup;
455
0
    WLog_DBG(TAG, "\tsupportedMech [1] (%s)", negotiate_mech_name(&token->supportedMech));
456
0
  }
457
458
  /* mechToken [2] OCTET STRING */
459
0
  if (token->mechToken.cbBuffer)
460
0
  {
461
0
    if (WinPrAsn1EncContextualOctetString(enc, 2, &mechToken) == 0)
462
0
      goto cleanup;
463
0
    WLog_DBG(TAG, "\tmechToken [2] (%" PRIu32 " bytes)", token->mechToken.cbBuffer);
464
0
  }
465
466
  /* mechListMIC [3] OCTET STRING */
467
0
  if (token->mic.cbBuffer)
468
0
  {
469
0
    if (WinPrAsn1EncContextualOctetString(enc, 3, &mechListMic) == 0)
470
0
      goto cleanup;
471
0
    WLog_DBG(TAG, "\tmechListMIC [3] (%" PRIu32 " bytes)", token->mic.cbBuffer);
472
0
  }
473
474
  /* NegTokenInit or NegTokenResp */
475
0
  if (!WinPrAsn1EncEndContainer(enc))
476
0
    goto cleanup;
477
478
0
  if (token->init)
479
0
  {
480
    /* initialContextToken */
481
0
    if (!WinPrAsn1EncEndContainer(enc))
482
0
      goto cleanup;
483
0
  }
484
485
0
  if (!WinPrAsn1EncStreamSize(enc, &len) || len > output_buffer->cbBuffer)
486
0
    goto cleanup;
487
488
0
  if (len > UINT32_MAX)
489
0
    goto cleanup;
490
491
0
  Stream_StaticInit(&s, output_buffer->pvBuffer, len);
492
493
0
  if (WinPrAsn1EncToStream(enc, &s))
494
0
  {
495
0
    output_buffer->cbBuffer = (UINT32)len;
496
0
    ret = TRUE;
497
0
  }
498
499
0
cleanup:
500
0
  WinPrAsn1Encoder_Free(&enc);
501
0
  return ret;
502
0
}
503
504
static BOOL negotiate_read_neg_token(PSecBuffer input, NegToken* token)
505
0
{
506
0
  WinPrAsn1Decoder dec = WinPrAsn1Decoder_init();
507
0
  WinPrAsn1Decoder dec2 = WinPrAsn1Decoder_init();
508
0
  WinPrAsn1_OID oid = WINPR_C_ARRAY_INIT;
509
0
  WinPrAsn1_tagId contextual = 0;
510
0
  WinPrAsn1_tag tag = 0;
511
0
  size_t len = 0;
512
0
  WinPrAsn1_OctetString octet_string = WINPR_C_ARRAY_INIT;
513
0
  BOOL err = 0;
514
515
0
  WINPR_ASSERT(input);
516
0
  WINPR_ASSERT(token);
517
518
  /* The peer might not have sent a token at all */
519
0
  if (!input->pvBuffer || (input->cbBuffer == 0))
520
0
    return FALSE;
521
522
0
  WinPrAsn1Decoder_InitMem(&dec, WINPR_ASN1_DER, input->pvBuffer, input->cbBuffer);
523
524
0
  if (!WinPrAsn1DecPeekTag(&dec, &tag))
525
0
    return FALSE;
526
527
0
  if (tag == 0x60)
528
0
  {
529
    /* initialContextToken [APPLICATION 0] */
530
0
    if (!WinPrAsn1DecReadApp(&dec, &tag, &dec2) || tag != 0)
531
0
      return FALSE;
532
0
    dec = dec2;
533
534
    /* thisMech OID */
535
0
    if (!WinPrAsn1DecReadOID(&dec, &oid, FALSE))
536
0
      return FALSE;
537
538
0
    if (!sspi_gss_oid_compare(&spnego_OID, &oid))
539
0
      return FALSE;
540
541
    /* [0] NegTokenInit */
542
0
    if (!WinPrAsn1DecReadContextualSequence(&dec, 0, &err, &dec2))
543
0
      return FALSE;
544
545
0
    token->init = TRUE;
546
0
  }
547
  /* [1] NegTokenResp */
548
0
  else if (!WinPrAsn1DecReadContextualSequence(&dec, 1, &err, &dec2))
549
0
    return FALSE;
550
0
  dec = dec2;
551
552
0
  WLog_DBG(TAG, token->init ? "Reading negTokenInit..." : "Reading negTokenResp...");
553
554
  /* Read NegTokenResp sequence members */
555
0
  do
556
0
  {
557
0
    if (!WinPrAsn1DecReadContextualTag(&dec, &contextual, &dec2))
558
0
      return FALSE;
559
560
0
    switch (contextual)
561
0
    {
562
0
      case 0:
563
0
        if (token->init)
564
0
        {
565
          /* mechTypes [0] MechTypeList */
566
0
          wStream s = WinPrAsn1DecGetStream(&dec2);
567
0
          token->mechTypes.BufferType = SECBUFFER_TOKEN;
568
0
          const size_t mlen = Stream_Length(&s);
569
0
          if (mlen > UINT32_MAX)
570
0
            return FALSE;
571
0
          token->mechTypes.cbBuffer = (UINT32)mlen;
572
0
          token->mechTypes.pvBuffer = Stream_Buffer(&s);
573
0
          WLog_DBG(TAG, "\tmechTypes [0] (%" PRIu32 " bytes)", token->mechTypes.cbBuffer);
574
0
        }
575
0
        else
576
0
        {
577
          /* negState [0] ENUMERATED */
578
0
          WinPrAsn1_ENUMERATED rd = 0;
579
0
          if (!WinPrAsn1DecReadEnumerated(&dec2, &rd))
580
0
            return FALSE;
581
0
          switch (rd)
582
0
          {
583
0
            case NOSTATE:
584
0
            case ACCEPT_COMPLETED:
585
0
            case ACCEPT_INCOMPLETE:
586
0
            case REJECT:
587
0
            case REQUEST_MIC:
588
0
              break;
589
0
            default:
590
0
              WLog_ERR(TAG, "Invalid negState enumeration value %d", rd);
591
0
              return FALSE;
592
0
          }
593
594
0
          token->negState = WINPR_ASSERTING_INT_CAST(enum NegState, rd);
595
0
          WLog_DBG(TAG, "\tnegState [0] (%d)", rd);
596
0
        }
597
0
        break;
598
0
      case 1:
599
0
        if (token->init)
600
0
        {
601
          /* reqFlags [1] ContextFlags BIT STRING (ignored) */
602
0
          if (!WinPrAsn1DecPeekTagAndLen(&dec2, &tag, &len) || (tag != ER_TAG_BIT_STRING))
603
0
            return FALSE;
604
0
          WLog_DBG(TAG, "\treqFlags [1] (%" PRIuz " bytes)", len);
605
0
        }
606
0
        else
607
0
        {
608
          /* supportedMech [1] MechType */
609
0
          if (!WinPrAsn1DecReadOID(&dec2, &token->supportedMech, FALSE))
610
0
            return FALSE;
611
0
          WLog_DBG(TAG, "\tsupportedMech [1] (%s)",
612
0
                   negotiate_mech_name(&token->supportedMech));
613
0
        }
614
0
        break;
615
0
      case 2:
616
        /* mechToken [2] OCTET STRING */
617
0
        if (!WinPrAsn1DecReadOctetString(&dec2, &octet_string, FALSE))
618
0
          return FALSE;
619
0
        if (octet_string.len > UINT32_MAX)
620
0
          return FALSE;
621
0
        token->mechToken.cbBuffer = (UINT32)octet_string.len;
622
0
        token->mechToken.pvBuffer = octet_string.data;
623
0
        token->mechToken.BufferType = SECBUFFER_TOKEN;
624
0
        WLog_DBG(TAG, "\tmechToken [2] (%" PRIuz " bytes)", octet_string.len);
625
0
        break;
626
0
      case 3:
627
        /* mechListMic [3] OCTET STRING */
628
0
        if (!WinPrAsn1DecReadOctetString(&dec2, &octet_string, FALSE))
629
0
          return FALSE;
630
0
        if (octet_string.len > UINT32_MAX)
631
0
          return FALSE;
632
0
        token->mic.cbBuffer = (UINT32)octet_string.len;
633
0
        token->mic.pvBuffer = octet_string.data;
634
0
        token->mic.BufferType = SECBUFFER_TOKEN;
635
0
        WLog_DBG(TAG, "\tmechListMIC [3] (%" PRIuz " bytes)", octet_string.len);
636
0
        break;
637
0
      default:
638
0
        WLog_ERR(TAG, "unknown contextual item %d", contextual);
639
0
        return FALSE;
640
0
    }
641
0
  } while (WinPrAsn1DecPeekTag(&dec, &tag));
642
643
0
  return TRUE;
644
0
}
645
646
static SECURITY_STATUS negotiate_mic_exchange(NEGOTIATE_CONTEXT* context, NegToken* input_token,
647
                                              NegToken* output_token, PSecBuffer output_buffer)
648
0
{
649
0
  SecBuffer mic_buffers[2] = WINPR_C_ARRAY_INIT;
650
0
  SecBufferDesc mic_buffer_desc = { SECBUFFER_VERSION, 2, mic_buffers };
651
0
  SECURITY_STATUS status = 0;
652
653
0
  WINPR_ASSERT(context);
654
0
  WINPR_ASSERT(input_token);
655
0
  WINPR_ASSERT(output_token);
656
0
  WINPR_ASSERT(context->mech);
657
0
  WINPR_ASSERT(context->mech->pkg);
658
659
0
  const SecurityFunctionTableA* table = context->mech->pkg->table;
660
0
  WINPR_ASSERT(table);
661
662
0
  mic_buffers[0] = context->mechTypes;
663
664
  /* Verify MIC if we received one */
665
0
  if (input_token->mic.cbBuffer > 0)
666
0
  {
667
0
    mic_buffers[1] = input_token->mic;
668
669
0
    status = table->VerifySignature(&context->sub_context, &mic_buffer_desc, 0, nullptr);
670
0
    if (status != SEC_E_OK)
671
0
      return status;
672
673
0
    output_token->negState = ACCEPT_COMPLETED;
674
0
  }
675
676
  /* If peer expects a MIC then generate it */
677
0
  if (input_token->negState != ACCEPT_COMPLETED)
678
0
  {
679
    /* Store the mic token after the mech token in the output buffer */
680
0
    output_token->mic.BufferType = SECBUFFER_TOKEN;
681
0
    if (output_buffer)
682
0
    {
683
0
      output_token->mic.cbBuffer = output_buffer->cbBuffer - output_token->mechToken.cbBuffer;
684
0
      output_token->mic.pvBuffer =
685
0
          (BYTE*)output_buffer->pvBuffer + output_token->mechToken.cbBuffer;
686
0
    }
687
0
    mic_buffers[1] = output_token->mic;
688
689
0
    status = table->MakeSignature(&context->sub_context, 0, &mic_buffer_desc, 0);
690
0
    if (status != SEC_E_OK)
691
0
      return status;
692
693
0
    output_token->mic = mic_buffers[1];
694
0
  }
695
696
  /* When using NTLM cipher states need to be reset after mic exchange */
697
0
  const SSPI_PACKAGE_ID sub_id = sspi_SecureHandleGetPackageId(&context->sub_context);
698
0
  if (!sub_id)
699
0
    return SEC_E_INTERNAL_ERROR;
700
701
0
  if (sub_id == SSPI_PACKAGE_NTLM)
702
0
  {
703
0
    if (!ntlm_reset_cipher_state(&context->sub_context))
704
0
      return SEC_E_INTERNAL_ERROR;
705
0
  }
706
707
0
  return SEC_E_OK;
708
0
}
709
710
static SECURITY_STATUS SEC_ENTRY negotiate_InitializeSecurityContextW(
711
    PCredHandle phCredential, PCtxtHandle phContext, SEC_WCHAR* pszTargetName, ULONG fContextReq,
712
    ULONG Reserved1, ULONG TargetDataRep, PSecBufferDesc pInput, ULONG Reserved2,
713
    PCtxtHandle phNewContext, PSecBufferDesc pOutput, PULONG pfContextAttr, PTimeStamp ptsExpiry)
714
0
{
715
0
  NEGOTIATE_CONTEXT* context = nullptr;
716
0
  NEGOTIATE_CONTEXT init_context = NEGOTIATE_CONTEXT_init();
717
0
  MechCred* creds = nullptr;
718
0
  PCtxtHandle sub_context = nullptr;
719
0
  PCredHandle sub_cred = nullptr;
720
0
  NegToken input_token = empty_neg_token;
721
0
  NegToken output_token = empty_neg_token;
722
0
  PSecBuffer input_buffer = nullptr;
723
0
  PSecBuffer output_buffer = nullptr;
724
0
  PSecBuffer bindings_buffer = nullptr;
725
0
  SecBuffer mech_input_buffers[2] = WINPR_C_ARRAY_INIT;
726
0
  SecBufferDesc mech_input = { SECBUFFER_VERSION, 2, mech_input_buffers };
727
0
  SecBufferDesc mech_output = { SECBUFFER_VERSION, 1, &output_token.mechToken };
728
0
  SECURITY_STATUS status = SEC_E_INTERNAL_ERROR;
729
0
  SECURITY_STATUS sub_status = SEC_E_INTERNAL_ERROR;
730
0
  WinPrAsn1Encoder* enc = nullptr;
731
0
  wStream s;
732
0
  const Mech* mech = nullptr;
733
734
0
  if (!phCredential || !SecIsValidHandle(phCredential))
735
0
    return SEC_E_NO_CREDENTIALS;
736
737
0
  creds = sspi_SecureHandleGetLowerPointer(phCredential);
738
739
  /* behave like windows SSPIs that don't want empty context */
740
0
  if (phContext && !phContext->dwLower && !phContext->dwUpper)
741
0
    return SEC_E_INVALID_HANDLE;
742
743
0
  context = sspi_SecureHandleGetLowerPointer(phContext);
744
745
0
  if (pInput)
746
0
  {
747
0
    input_buffer = sspi_FindSecBuffer(pInput, SECBUFFER_TOKEN);
748
0
    bindings_buffer = sspi_FindSecBuffer(pInput, SECBUFFER_CHANNEL_BINDINGS);
749
0
  }
750
0
  if (pOutput)
751
0
    output_buffer = sspi_FindSecBuffer(pOutput, SECBUFFER_TOKEN);
752
753
0
  if (!context)
754
0
  {
755
0
    enc = WinPrAsn1Encoder_New(WINPR_ASN1_DER);
756
0
    if (!enc)
757
0
      return SEC_E_INSUFFICIENT_MEMORY;
758
759
0
    if (!WinPrAsn1EncSeqContainer(enc))
760
0
      goto cleanup;
761
762
0
    for (size_t i = 0; i < MECH_COUNT; i++)
763
0
    {
764
0
      MechCred* cred = &creds[i];
765
0
      const SecPkg* pkg = MechTable[i].pkg;
766
0
      WINPR_ASSERT(pkg);
767
0
      WINPR_ASSERT(pkg->table_w);
768
769
0
      if (!cred->valid)
770
0
      {
771
0
        WLog_DBG(TAG, "Unavailable mechanism: %s", negotiate_mech_name(cred->mech->oid));
772
0
        continue;
773
0
      }
774
775
      /* Send an optimistic token for the first valid mechanism */
776
0
      if (!init_context.mech)
777
0
      {
778
        /* Use the output buffer to store the optimistic token */
779
0
        if (!output_buffer)
780
0
          goto cleanup;
781
782
0
        CopyMemory(&output_token.mechToken, output_buffer, sizeof(SecBuffer));
783
784
0
        if (bindings_buffer)
785
0
          mech_input_buffers[0] = *bindings_buffer;
786
787
0
        WINPR_ASSERT(pkg->table_w->InitializeSecurityContextW);
788
0
        sub_status = pkg->table_w->InitializeSecurityContextW(
789
0
            &cred->cred, nullptr, pszTargetName, fContextReq | cred->mech->flags, Reserved1,
790
0
            TargetDataRep, &mech_input, Reserved2, &init_context.sub_context, &mech_output,
791
0
            pfContextAttr, ptsExpiry);
792
793
        /* If the mechanism failed we can't use it; skip */
794
0
        if (IsSecurityStatusError(sub_status))
795
0
        {
796
0
          if (SecIsValidHandle(&init_context.sub_context))
797
0
          {
798
0
            WINPR_ASSERT(pkg->table_w->DeleteSecurityContext);
799
0
            pkg->table_w->DeleteSecurityContext(&init_context.sub_context);
800
0
          }
801
0
          cred->valid = FALSE;
802
0
          continue;
803
0
        }
804
805
0
        init_context.mech = cred->mech;
806
0
      }
807
808
0
      if (!WinPrAsn1EncOID(enc, cred->mech->oid))
809
0
        goto cleanup;
810
0
      WLog_DBG(TAG, "Available mechanism: %s", negotiate_mech_name(cred->mech->oid));
811
0
    }
812
813
    /* No usable mechanisms were found */
814
0
    if (!init_context.mech)
815
0
      goto cleanup;
816
817
    /* If the only available mech is NTLM use it directly otherwise use spnego */
818
0
    if (init_context.mech->oid == &ntlm_OID)
819
0
    {
820
0
      init_context.spnego = FALSE;
821
0
      output_buffer->cbBuffer = output_token.mechToken.cbBuffer;
822
0
      WLog_DBG(TAG, "Using direct NTLM");
823
0
    }
824
0
    else
825
0
    {
826
0
      init_context.spnego = TRUE;
827
0
      init_context.mechTypes.BufferType = SECBUFFER_DATA;
828
0
      const size_t cb = WinPrAsn1EncEndContainer(enc);
829
0
      WINPR_ASSERT(cb <= UINT32_MAX);
830
0
      init_context.mechTypes.cbBuffer = (UINT32)cb;
831
0
    }
832
833
    /* Allocate memory for the new context */
834
0
    context = negotiate_ContextNew(&init_context);
835
0
    if (!context)
836
0
    {
837
0
      init_context.mech->pkg->table->DeleteSecurityContext(&init_context.sub_context);
838
0
      WinPrAsn1Encoder_Free(&enc);
839
0
      return SEC_E_INSUFFICIENT_MEMORY;
840
0
    }
841
842
0
    sspi_SecureHandleSetPackageId(phNewContext, SSPI_PACKAGE_NEGOTIATE);
843
0
    sspi_SecureHandleSetLowerPointer(phNewContext, context);
844
845
0
    if (!context->spnego)
846
0
    {
847
0
      status = sub_status;
848
0
      goto cleanup;
849
0
    }
850
851
    /* Write mechTypesList */
852
0
    Stream_StaticInit(&s, context->mechTypes.pvBuffer, context->mechTypes.cbBuffer);
853
0
    if (!WinPrAsn1EncToStream(enc, &s))
854
0
      goto cleanup;
855
856
0
    output_token.mechTypes.cbBuffer = context->mechTypes.cbBuffer;
857
0
    output_token.mechTypes.pvBuffer = context->mechTypes.pvBuffer;
858
0
    output_token.init = TRUE;
859
860
0
    if (sub_status == SEC_E_OK)
861
0
      context->state = NEGOTIATE_STATE_FINAL_OPTIMISTIC;
862
0
  }
863
0
  else
864
0
  {
865
0
    if (!input_buffer)
866
0
      return SEC_E_INVALID_TOKEN;
867
868
0
    sub_context = &context->sub_context;
869
0
    sub_cred = negotiate_FindCredential(creds, context->mech);
870
871
0
    if (!context->spnego)
872
0
    {
873
0
      return context->mech->pkg->table_w->InitializeSecurityContextW(
874
0
          sub_cred, sub_context, pszTargetName, fContextReq | context->mech->flags, Reserved1,
875
0
          TargetDataRep, pInput, Reserved2, sub_context, pOutput, pfContextAttr, ptsExpiry);
876
0
    }
877
878
0
    if (!negotiate_read_neg_token(input_buffer, &input_token))
879
0
      return SEC_E_INVALID_TOKEN;
880
881
    /* On first response check if the server doesn't like out preferred mech */
882
0
    if (context->state < NEGOTIATE_STATE_NEGORESP && input_token.supportedMech.len &&
883
0
        !sspi_gss_oid_compare(&input_token.supportedMech, context->mech->oid))
884
0
    {
885
0
      mech = negotiate_GetMechByOID(&input_token.supportedMech);
886
0
      if (!mech)
887
0
        return SEC_E_INVALID_TOKEN;
888
889
      /* Make sure the specified mech is supported and get the appropriate credential */
890
0
      sub_cred = negotiate_FindCredential(creds, mech);
891
0
      if (!sub_cred)
892
0
        return SEC_E_INVALID_TOKEN;
893
894
      /* Clean up the optimistic mech */
895
0
      context->mech->pkg->table_w->DeleteSecurityContext(&context->sub_context);
896
0
      sub_context = nullptr;
897
898
0
      context->mech = mech;
899
0
      context->mic = TRUE;
900
0
    }
901
902
    /* Check neg_state (required on first response) */
903
0
    if (context->state < NEGOTIATE_STATE_NEGORESP)
904
0
    {
905
0
      switch (input_token.negState)
906
0
      {
907
0
        case NOSTATE:
908
0
          return SEC_E_INVALID_TOKEN;
909
0
        case REJECT:
910
0
          return SEC_E_LOGON_DENIED;
911
0
        case REQUEST_MIC:
912
0
          context->mic = TRUE;
913
          /* fallthrough */
914
0
          WINPR_FALLTHROUGH
915
0
        case ACCEPT_INCOMPLETE:
916
0
          context->state = NEGOTIATE_STATE_NEGORESP;
917
0
          break;
918
0
        case ACCEPT_COMPLETED:
919
0
          if (context->state == NEGOTIATE_STATE_INITIAL)
920
0
            context->state = NEGOTIATE_STATE_NEGORESP;
921
0
          else
922
0
            context->state = NEGOTIATE_STATE_FINAL;
923
0
          break;
924
0
        default:
925
0
          break;
926
0
      }
927
928
0
      WLog_DBG(TAG, "Negotiated mechanism: %s", negotiate_mech_name(context->mech->oid));
929
0
    }
930
931
0
    if (context->state == NEGOTIATE_STATE_NEGORESP)
932
0
    {
933
      /* Store the mech token in the output buffer */
934
0
      if (!output_buffer)
935
0
        goto cleanup;
936
0
      CopyMemory(&output_token.mechToken, output_buffer, sizeof(SecBuffer));
937
938
0
      mech_input_buffers[0] = input_token.mechToken;
939
0
      if (bindings_buffer)
940
0
        mech_input_buffers[1] = *bindings_buffer;
941
942
0
      status = context->mech->pkg->table_w->InitializeSecurityContextW(
943
0
          sub_cred, sub_context, pszTargetName, fContextReq | context->mech->flags, Reserved1,
944
0
          TargetDataRep, input_token.mechToken.cbBuffer ? &mech_input : nullptr, Reserved2,
945
0
          &context->sub_context, &mech_output, pfContextAttr, ptsExpiry);
946
947
0
      if (IsSecurityStatusError(status))
948
0
        return status;
949
0
    }
950
951
0
    if (status == SEC_E_OK)
952
0
    {
953
0
      if (output_token.mechToken.cbBuffer > 0)
954
0
        context->state = NEGOTIATE_STATE_MIC;
955
0
      else
956
0
        context->state = NEGOTIATE_STATE_FINAL;
957
0
    }
958
959
    /* Check if the acceptor sent its final token without a mic */
960
0
    if (context->state == NEGOTIATE_STATE_FINAL && input_token.mic.cbBuffer == 0)
961
0
    {
962
0
      if (context->mic || input_token.negState != ACCEPT_COMPLETED)
963
0
        return SEC_E_INVALID_TOKEN;
964
965
0
      if (output_buffer)
966
0
        output_buffer->cbBuffer = 0;
967
0
      return SEC_E_OK;
968
0
    }
969
970
0
    if ((context->state == NEGOTIATE_STATE_MIC && context->mic) ||
971
0
        context->state == NEGOTIATE_STATE_FINAL)
972
0
    {
973
0
      status = negotiate_mic_exchange(context, &input_token, &output_token, output_buffer);
974
0
      if (status != SEC_E_OK)
975
0
        return status;
976
0
    }
977
0
  }
978
979
0
  if (input_token.negState == ACCEPT_COMPLETED)
980
0
  {
981
0
    if (output_buffer)
982
0
      output_buffer->cbBuffer = 0;
983
0
    return SEC_E_OK;
984
0
  }
985
986
0
  if (output_token.negState == ACCEPT_COMPLETED)
987
0
    status = SEC_E_OK;
988
0
  else
989
0
    status = SEC_I_CONTINUE_NEEDED;
990
991
0
  if (!negotiate_write_neg_token(output_buffer, &output_token))
992
0
    status = SEC_E_INTERNAL_ERROR;
993
994
0
cleanup:
995
0
  WinPrAsn1Encoder_Free(&enc);
996
0
  return status;
997
0
}
998
999
static SECURITY_STATUS SEC_ENTRY negotiate_InitializeSecurityContextA(
1000
    PCredHandle phCredential, PCtxtHandle phContext, SEC_CHAR* pszTargetName, ULONG fContextReq,
1001
    ULONG Reserved1, ULONG TargetDataRep, PSecBufferDesc pInput, ULONG Reserved2,
1002
    PCtxtHandle phNewContext, PSecBufferDesc pOutput, PULONG pfContextAttr, PTimeStamp ptsExpiry)
1003
0
{
1004
0
  SECURITY_STATUS status = 0;
1005
0
  SEC_WCHAR* pszTargetNameW = nullptr;
1006
1007
0
  if (pszTargetName)
1008
0
  {
1009
0
    pszTargetNameW = ConvertUtf8ToWCharAlloc(pszTargetName, nullptr);
1010
0
    if (!pszTargetNameW)
1011
0
      return SEC_E_INTERNAL_ERROR;
1012
0
  }
1013
1014
0
  status = negotiate_InitializeSecurityContextW(
1015
0
      phCredential, phContext, pszTargetNameW, fContextReq, Reserved1, TargetDataRep, pInput,
1016
0
      Reserved2, phNewContext, pOutput, pfContextAttr, ptsExpiry);
1017
0
  free(pszTargetNameW);
1018
0
  return status;
1019
0
}
1020
1021
WINPR_ATTR_NODISCARD
1022
static const Mech* guessMech(PSecBuffer input_buffer, BOOL* spNego, WinPrAsn1_OID* oid)
1023
0
{
1024
0
  WinPrAsn1Decoder decoder = WinPrAsn1Decoder_init();
1025
0
  WinPrAsn1Decoder appDecoder = WinPrAsn1Decoder_init();
1026
0
  WinPrAsn1_tagId tag = 0;
1027
0
  const char ssp[] = "NTLMSSP";
1028
1029
0
  if (!input_buffer || !input_buffer->pvBuffer || (input_buffer->cbBuffer == 0))
1030
0
    return nullptr;
1031
1032
0
  *spNego = FALSE;
1033
1034
  /* Check for NTLM token */
1035
0
  if (input_buffer->cbBuffer >= 8 && strncmp(input_buffer->pvBuffer, ssp, sizeof(ssp)) == 0)
1036
0
  {
1037
0
    *oid = ntlm_OID;
1038
0
    return negotiate_GetMechByOID(&ntlm_OID);
1039
0
  }
1040
1041
  /* Read initialContextToken or raw Kerberos token */
1042
0
  WinPrAsn1Decoder_InitMem(&decoder, WINPR_ASN1_DER, input_buffer->pvBuffer,
1043
0
                           input_buffer->cbBuffer);
1044
1045
0
  if (!WinPrAsn1DecReadApp(&decoder, &tag, &appDecoder) || tag != 0)
1046
0
    return nullptr;
1047
1048
0
  if (!WinPrAsn1DecReadOID(&appDecoder, oid, FALSE))
1049
0
    return nullptr;
1050
1051
0
  if (sspi_gss_oid_compare(oid, &spnego_OID))
1052
0
  {
1053
0
    *spNego = TRUE;
1054
0
    return nullptr;
1055
0
  }
1056
1057
0
  return negotiate_GetMechByOID(oid);
1058
0
}
1059
1060
static SECURITY_STATUS SEC_ENTRY negotiate_AcceptSecurityContext(
1061
    PCredHandle phCredential, PCtxtHandle phContext, PSecBufferDesc pInput, ULONG fContextReq,
1062
    ULONG TargetDataRep, PCtxtHandle phNewContext, PSecBufferDesc pOutput, PULONG pfContextAttr,
1063
    PTimeStamp ptsTimeStamp)
1064
0
{
1065
0
  NEGOTIATE_CONTEXT* context = nullptr;
1066
0
  NEGOTIATE_CONTEXT init_context = NEGOTIATE_CONTEXT_init();
1067
0
  MechCred* creds = nullptr;
1068
0
  PCredHandle sub_cred = nullptr;
1069
0
  NegToken input_token = empty_neg_token;
1070
0
  NegToken output_token = empty_neg_token;
1071
0
  PSecBuffer input_buffer = nullptr;
1072
0
  PSecBuffer output_buffer = nullptr;
1073
0
  SecBufferDesc mech_input = { SECBUFFER_VERSION, 1, &input_token.mechToken };
1074
0
  SecBufferDesc mech_output = { SECBUFFER_VERSION, 1, &output_token.mechToken };
1075
0
  SECURITY_STATUS status = SEC_E_INTERNAL_ERROR;
1076
0
  WinPrAsn1Decoder dec = WinPrAsn1Decoder_init();
1077
0
  WinPrAsn1Decoder dec2 = WinPrAsn1Decoder_init();
1078
0
  WinPrAsn1_tagId tag = 0;
1079
0
  WinPrAsn1_OID oid = WINPR_C_ARRAY_INIT;
1080
0
  const Mech* first_mech = nullptr;
1081
1082
0
  if (!phCredential || !SecIsValidHandle(phCredential))
1083
0
    return SEC_E_NO_CREDENTIALS;
1084
1085
0
  creds = sspi_SecureHandleGetLowerPointer(phCredential);
1086
1087
0
  if (!pInput)
1088
0
    return SEC_E_INVALID_TOKEN;
1089
1090
  /* behave like windows SSPIs that don't want empty context */
1091
0
  if (phContext && !phContext->dwLower && !phContext->dwUpper)
1092
0
    return SEC_E_INVALID_HANDLE;
1093
1094
0
  context = sspi_SecureHandleGetLowerPointer(phContext);
1095
1096
0
  input_buffer = sspi_FindSecBuffer(pInput, SECBUFFER_TOKEN);
1097
0
  if (pOutput)
1098
0
    output_buffer = sspi_FindSecBuffer(pOutput, SECBUFFER_TOKEN);
1099
1100
0
  if (!context)
1101
0
  {
1102
0
    init_context.mech = guessMech(input_buffer, &init_context.spnego, &oid);
1103
0
    if (!init_context.mech && !init_context.spnego)
1104
0
      return SEC_E_INVALID_TOKEN;
1105
1106
0
    WLog_DBG(TAG, "Mechanism: %s", negotiate_mech_name(&oid));
1107
1108
0
    if (init_context.spnego)
1109
0
    {
1110
      /* Process spnego token */
1111
0
      if (!negotiate_read_neg_token(input_buffer, &input_token))
1112
0
        return SEC_E_INVALID_TOKEN;
1113
1114
      /* First token must be negoTokenInit and must contain a mechList */
1115
0
      if (!input_token.init || input_token.mechTypes.cbBuffer == 0)
1116
0
        return SEC_E_INVALID_TOKEN;
1117
1118
0
      init_context.mechTypes.BufferType = SECBUFFER_DATA;
1119
0
      init_context.mechTypes.cbBuffer = input_token.mechTypes.cbBuffer;
1120
1121
      /* Prepare to read mechList */
1122
0
      WinPrAsn1Decoder_InitMem(&dec, WINPR_ASN1_DER, input_token.mechTypes.pvBuffer,
1123
0
                               input_token.mechTypes.cbBuffer);
1124
1125
0
      if (!WinPrAsn1DecReadSequence(&dec, &dec2))
1126
0
        return SEC_E_INVALID_TOKEN;
1127
0
      dec = dec2;
1128
1129
      /* If an optimistic token was provided pass it into the first mech */
1130
0
      if (input_token.mechToken.cbBuffer)
1131
0
      {
1132
0
        if (!WinPrAsn1DecReadOID(&dec, &oid, FALSE))
1133
0
          return SEC_E_INVALID_TOKEN;
1134
1135
0
        init_context.mech = negotiate_GetMechByOID(&oid);
1136
1137
0
        if (init_context.mech)
1138
0
        {
1139
0
          if (output_buffer)
1140
0
            output_token.mechToken = *output_buffer;
1141
0
          WLog_DBG(TAG, "Requested mechanism: %s",
1142
0
                   negotiate_mech_name(init_context.mech->oid));
1143
0
        }
1144
0
      }
1145
0
    }
1146
1147
0
    if (init_context.mech)
1148
0
    {
1149
0
      sub_cred = negotiate_FindCredential(creds, init_context.mech);
1150
1151
0
      if (sub_cred)
1152
0
      {
1153
0
        status = init_context.mech->pkg->table->AcceptSecurityContext(
1154
0
            sub_cred, nullptr, init_context.spnego ? &mech_input : pInput, fContextReq,
1155
0
            TargetDataRep, &init_context.sub_context,
1156
0
            init_context.spnego ? &mech_output : pOutput, pfContextAttr, ptsTimeStamp);
1157
0
      }
1158
0
    }
1159
1160
0
    if (IsSecurityStatusError(status))
1161
0
    {
1162
0
      if (!init_context.spnego)
1163
0
        return status;
1164
1165
      /* Clean up any partially created sub context before falling back to
1166
       * another mechanism (mirrors the mech change handling in
1167
       * negotiate_InitializeSecurityContextW) */
1168
0
      if (init_context.mech)
1169
0
        init_context.mech->pkg->table->DeleteSecurityContext(&init_context.sub_context);
1170
1171
0
      init_context.mic = TRUE;
1172
0
      first_mech = init_context.mech;
1173
0
      init_context.mech = nullptr;
1174
0
      output_token.mechToken.cbBuffer = 0;
1175
0
    }
1176
1177
0
    while (!init_context.mech && WinPrAsn1DecPeekTag(&dec, &tag))
1178
0
    {
1179
      /* Read each mechanism */
1180
0
      if (!WinPrAsn1DecReadOID(&dec, &oid, FALSE))
1181
0
        return SEC_E_INVALID_TOKEN;
1182
1183
0
      init_context.mech = negotiate_GetMechByOID(&oid);
1184
0
      WLog_DBG(TAG, "Requested mechanism: %s", negotiate_mech_name(&oid));
1185
1186
      /* Microsoft may send two versions of the kerberos OID */
1187
0
      if (init_context.mech == first_mech)
1188
0
        init_context.mech = nullptr;
1189
1190
0
      if (init_context.mech && !negotiate_FindCredential(creds, init_context.mech))
1191
0
        init_context.mech = nullptr;
1192
0
    }
1193
1194
0
    if (!init_context.mech)
1195
0
      return SEC_E_INTERNAL_ERROR;
1196
1197
0
    context = negotiate_ContextNew(&init_context);
1198
0
    if (!context)
1199
0
    {
1200
0
      if (!IsSecurityStatusError(status))
1201
0
        init_context.mech->pkg->table->DeleteSecurityContext(&init_context.sub_context);
1202
0
      return SEC_E_INSUFFICIENT_MEMORY;
1203
0
    }
1204
1205
0
    sspi_SecureHandleSetPackageId(phNewContext, SSPI_PACKAGE_NEGOTIATE);
1206
0
    sspi_SecureHandleSetLowerPointer(phNewContext, context);
1207
1208
0
    if (!init_context.spnego)
1209
0
      return status;
1210
1211
0
    CopyMemory(init_context.mechTypes.pvBuffer, input_token.mechTypes.pvBuffer,
1212
0
               input_token.mechTypes.cbBuffer);
1213
1214
0
    if (!context->mech->preferred)
1215
0
    {
1216
0
      output_token.negState = REQUEST_MIC;
1217
0
      context->mic = TRUE;
1218
0
    }
1219
0
    else
1220
0
    {
1221
0
      output_token.negState = ACCEPT_INCOMPLETE;
1222
0
    }
1223
1224
0
    if (status == SEC_E_OK)
1225
0
      context->state = NEGOTIATE_STATE_FINAL;
1226
0
    else
1227
0
      context->state = NEGOTIATE_STATE_NEGORESP;
1228
1229
0
    output_token.supportedMech = oid;
1230
0
    WLog_DBG(TAG, "Accepted mechanism: %s", negotiate_mech_name(&output_token.supportedMech));
1231
0
  }
1232
0
  else
1233
0
  {
1234
0
    sub_cred = negotiate_FindCredential(creds, context->mech);
1235
0
    if (!sub_cred)
1236
0
      return SEC_E_NO_CREDENTIALS;
1237
1238
0
    if (!context->spnego)
1239
0
    {
1240
0
      return context->mech->pkg->table->AcceptSecurityContext(
1241
0
          sub_cred, &context->sub_context, pInput, fContextReq, TargetDataRep,
1242
0
          &context->sub_context, pOutput, pfContextAttr, ptsTimeStamp);
1243
0
    }
1244
1245
0
    if (!negotiate_read_neg_token(input_buffer, &input_token))
1246
0
      return SEC_E_INVALID_TOKEN;
1247
1248
    /* Process the mechanism token */
1249
0
    if (input_token.mechToken.cbBuffer > 0)
1250
0
    {
1251
0
      if (context->state != NEGOTIATE_STATE_NEGORESP)
1252
0
        return SEC_E_INVALID_TOKEN;
1253
1254
      /* Use the output buffer to store the optimistic token */
1255
0
      if (output_buffer)
1256
0
        CopyMemory(&output_token.mechToken, output_buffer, sizeof(SecBuffer));
1257
1258
      /* If the client's optimistic mechanism was not accepted the sub
1259
       * context was never created (or was cleaned up); pass NULL so the
1260
       * selected mechanism creates a fresh context instead of rejecting
1261
       * the empty handle with SEC_E_INVALID_HANDLE */
1262
0
      PCtxtHandle sub_context = sspi_SecureHandleGetLowerPointer(&context->sub_context)
1263
0
                                    ? &context->sub_context
1264
0
                                    : nullptr;
1265
0
      status = context->mech->pkg->table->AcceptSecurityContext(
1266
0
          sub_cred, sub_context, &mech_input, fContextReq | context->mech->flags,
1267
0
          TargetDataRep, &context->sub_context, &mech_output, pfContextAttr, ptsTimeStamp);
1268
1269
0
      if (IsSecurityStatusError(status))
1270
0
        return status;
1271
1272
0
      if (status == SEC_E_OK)
1273
0
        context->state = NEGOTIATE_STATE_FINAL;
1274
0
    }
1275
0
    else if (context->state == NEGOTIATE_STATE_NEGORESP)
1276
0
      return SEC_E_INVALID_TOKEN;
1277
0
  }
1278
1279
0
  if (context->state == NEGOTIATE_STATE_FINAL)
1280
0
  {
1281
    /* Check if initiator sent the last mech token without a mic and a mic was required */
1282
0
    if (context->mic && output_token.mechToken.cbBuffer == 0 && input_token.mic.cbBuffer == 0)
1283
0
      return SEC_E_INVALID_TOKEN;
1284
1285
0
    if (context->mic || input_token.mic.cbBuffer > 0)
1286
0
    {
1287
0
      status = negotiate_mic_exchange(context, &input_token, &output_token, output_buffer);
1288
0
      if (status != SEC_E_OK)
1289
0
        return status;
1290
0
    }
1291
0
    else
1292
0
      output_token.negState = ACCEPT_COMPLETED;
1293
0
  }
1294
1295
0
  if (input_token.negState == ACCEPT_COMPLETED)
1296
0
  {
1297
0
    if (output_buffer)
1298
0
      output_buffer->cbBuffer = 0;
1299
0
    return SEC_E_OK;
1300
0
  }
1301
1302
0
  if (output_token.negState == ACCEPT_COMPLETED)
1303
0
    status = SEC_E_OK;
1304
0
  else
1305
0
    status = SEC_I_CONTINUE_NEEDED;
1306
1307
0
  if (!negotiate_write_neg_token(output_buffer, &output_token))
1308
0
    return SEC_E_INTERNAL_ERROR;
1309
1310
0
  return status;
1311
0
}
1312
1313
static SECURITY_STATUS SEC_ENTRY negotiate_CompleteAuthToken(PCtxtHandle phContext,
1314
                                                             PSecBufferDesc pToken)
1315
0
{
1316
0
  NEGOTIATE_CONTEXT* context = nullptr;
1317
0
  SECURITY_STATUS status = SEC_E_OK;
1318
0
  context = (NEGOTIATE_CONTEXT*)sspi_SecureHandleGetLowerPointer(phContext);
1319
1320
0
  if (!context)
1321
0
    return SEC_E_INVALID_HANDLE;
1322
1323
0
  WINPR_ASSERT(context->mech);
1324
0
  WINPR_ASSERT(context->mech->pkg);
1325
0
  WINPR_ASSERT(context->mech->pkg->table);
1326
0
  if (context->mech->pkg->table->CompleteAuthToken)
1327
0
    status = context->mech->pkg->table->CompleteAuthToken(&context->sub_context, pToken);
1328
1329
0
  return status;
1330
0
}
1331
1332
static SECURITY_STATUS SEC_ENTRY negotiate_DeleteSecurityContext(PCtxtHandle phContext)
1333
0
{
1334
0
  SECURITY_STATUS status = SEC_E_OK;
1335
0
  NEGOTIATE_CONTEXT* context = (NEGOTIATE_CONTEXT*)sspi_SecureHandleGetLowerPointer(phContext);
1336
0
  sspi_SecureHandleInvalidate(phContext);
1337
0
  const SecPkg* pkg = nullptr;
1338
1339
0
  if (!context)
1340
0
    return SEC_E_INVALID_HANDLE;
1341
1342
0
  WINPR_ASSERT(context->mech);
1343
0
  WINPR_ASSERT(context->mech->pkg);
1344
0
  WINPR_ASSERT(context->mech->pkg->table);
1345
0
  pkg = context->mech->pkg;
1346
1347
0
  if (pkg->table->DeleteSecurityContext)
1348
0
    status = pkg->table->DeleteSecurityContext(&context->sub_context);
1349
1350
0
  negotiate_ContextFree(context);
1351
0
  return status;
1352
0
}
1353
1354
static SECURITY_STATUS SEC_ENTRY
1355
negotiate_ImpersonateSecurityContext(WINPR_ATTR_UNUSED PCtxtHandle phContext)
1356
0
{
1357
0
  return SEC_E_OK;
1358
0
}
1359
1360
static SECURITY_STATUS SEC_ENTRY
1361
negotiate_RevertSecurityContext(WINPR_ATTR_UNUSED PCtxtHandle phContext)
1362
0
{
1363
0
  return SEC_E_OK;
1364
0
}
1365
1366
static SECURITY_STATUS SEC_ENTRY negotiate_QueryContextAttributesW(PCtxtHandle phContext,
1367
                                                                   ULONG ulAttribute, void* pBuffer)
1368
0
{
1369
0
  NEGOTIATE_CONTEXT* context = (NEGOTIATE_CONTEXT*)sspi_SecureHandleGetLowerPointer(phContext);
1370
1371
0
  if (!context)
1372
0
    return SEC_E_INVALID_HANDLE;
1373
1374
0
  WINPR_ASSERT(context->mech);
1375
0
  WINPR_ASSERT(context->mech->pkg);
1376
0
  WINPR_ASSERT(context->mech->pkg->table_w);
1377
0
  if (context->mech->pkg->table_w->QueryContextAttributesW)
1378
0
    return context->mech->pkg->table_w->QueryContextAttributesW(&context->sub_context,
1379
0
                                                                ulAttribute, pBuffer);
1380
1381
0
  return SEC_E_UNSUPPORTED_FUNCTION;
1382
0
}
1383
1384
static SECURITY_STATUS SEC_ENTRY negotiate_QueryContextAttributesA(PCtxtHandle phContext,
1385
                                                                   ULONG ulAttribute, void* pBuffer)
1386
0
{
1387
0
  NEGOTIATE_CONTEXT* context = (NEGOTIATE_CONTEXT*)sspi_SecureHandleGetLowerPointer(phContext);
1388
1389
0
  if (!context)
1390
0
    return SEC_E_INVALID_HANDLE;
1391
1392
0
  WINPR_ASSERT(context->mech);
1393
0
  WINPR_ASSERT(context->mech->pkg);
1394
0
  WINPR_ASSERT(context->mech->pkg->table);
1395
0
  if (context->mech->pkg->table->QueryContextAttributesA)
1396
0
    return context->mech->pkg->table->QueryContextAttributesA(&context->sub_context,
1397
0
                                                              ulAttribute, pBuffer);
1398
1399
0
  return SEC_E_UNSUPPORTED_FUNCTION;
1400
0
}
1401
1402
static SECURITY_STATUS SEC_ENTRY negotiate_SetContextAttributesW(PCtxtHandle phContext,
1403
                                                                 ULONG ulAttribute, void* pBuffer,
1404
                                                                 ULONG cbBuffer)
1405
0
{
1406
0
  NEGOTIATE_CONTEXT* context = (NEGOTIATE_CONTEXT*)sspi_SecureHandleGetLowerPointer(phContext);
1407
1408
0
  if (!context)
1409
0
    return SEC_E_INVALID_HANDLE;
1410
1411
0
  WINPR_ASSERT(context->mech);
1412
0
  WINPR_ASSERT(context->mech->pkg);
1413
0
  WINPR_ASSERT(context->mech->pkg->table_w);
1414
0
  if (context->mech->pkg->table_w->SetContextAttributesW)
1415
0
    return context->mech->pkg->table_w->SetContextAttributesW(&context->sub_context,
1416
0
                                                              ulAttribute, pBuffer, cbBuffer);
1417
1418
0
  return SEC_E_UNSUPPORTED_FUNCTION;
1419
0
}
1420
1421
static SECURITY_STATUS SEC_ENTRY negotiate_SetContextAttributesA(PCtxtHandle phContext,
1422
                                                                 ULONG ulAttribute, void* pBuffer,
1423
                                                                 ULONG cbBuffer)
1424
0
{
1425
0
  NEGOTIATE_CONTEXT* context = (NEGOTIATE_CONTEXT*)sspi_SecureHandleGetLowerPointer(phContext);
1426
1427
0
  if (!context)
1428
0
    return SEC_E_INVALID_HANDLE;
1429
1430
0
  WINPR_ASSERT(context->mech);
1431
0
  WINPR_ASSERT(context->mech->pkg);
1432
0
  WINPR_ASSERT(context->mech->pkg->table);
1433
0
  if (context->mech->pkg->table->SetContextAttributesA)
1434
0
    return context->mech->pkg->table->SetContextAttributesA(&context->sub_context, ulAttribute,
1435
0
                                                            pBuffer, cbBuffer);
1436
1437
0
  return SEC_E_UNSUPPORTED_FUNCTION;
1438
0
}
1439
1440
static SECURITY_STATUS SEC_ENTRY negotiate_SetCredentialsAttributesW(PCredHandle phCredential,
1441
                                                                     ULONG ulAttribute,
1442
                                                                     void* pBuffer, ULONG cbBuffer)
1443
0
{
1444
0
  BOOL success = FALSE;
1445
0
  MechCred* creds = sspi_SecureHandleGetLowerPointer(phCredential);
1446
1447
0
  if (!creds)
1448
0
    return SEC_E_INVALID_HANDLE;
1449
1450
0
  for (size_t i = 0; i < MECH_COUNT; i++)
1451
0
  {
1452
0
    MechCred* cred = &creds[i];
1453
1454
0
    WINPR_ASSERT(cred->mech);
1455
0
    WINPR_ASSERT(cred->mech->pkg);
1456
0
    WINPR_ASSERT(cred->mech->pkg->table);
1457
0
    WINPR_ASSERT(cred->mech->pkg->table_w->SetCredentialsAttributesW);
1458
0
    const SECURITY_STATUS secStatus = cred->mech->pkg->table_w->SetCredentialsAttributesW(
1459
0
        &cred->cred, ulAttribute, pBuffer, cbBuffer);
1460
1461
0
    if (secStatus == SEC_E_OK)
1462
0
      success = TRUE;
1463
0
    else
1464
0
      WLog_WARN(TAG, "SetCredentialsAttributesW returned %s",
1465
0
                GetSecurityStatusString(secStatus));
1466
0
  }
1467
1468
  // return success if at least one submodule accepts the credential attribute
1469
0
  return (success ? SEC_E_OK : SEC_E_UNSUPPORTED_FUNCTION);
1470
0
}
1471
1472
static SECURITY_STATUS SEC_ENTRY negotiate_SetCredentialsAttributesA(PCredHandle phCredential,
1473
                                                                     ULONG ulAttribute,
1474
                                                                     void* pBuffer, ULONG cbBuffer)
1475
0
{
1476
0
  BOOL success = FALSE;
1477
1478
0
  MechCred* creds = sspi_SecureHandleGetLowerPointer(phCredential);
1479
1480
0
  if (!creds)
1481
0
    return SEC_E_INVALID_HANDLE;
1482
1483
0
  for (size_t i = 0; i < MECH_COUNT; i++)
1484
0
  {
1485
0
    MechCred* cred = &creds[i];
1486
1487
0
    if (!cred->valid)
1488
0
      continue;
1489
1490
0
    WINPR_ASSERT(cred->mech);
1491
0
    WINPR_ASSERT(cred->mech->pkg);
1492
0
    WINPR_ASSERT(cred->mech->pkg->table);
1493
0
    WINPR_ASSERT(cred->mech->pkg->table->SetCredentialsAttributesA);
1494
0
    const SECURITY_STATUS secStatus = cred->mech->pkg->table->SetCredentialsAttributesA(
1495
0
        &cred->cred, ulAttribute, pBuffer, cbBuffer);
1496
1497
0
    if (secStatus == SEC_E_OK)
1498
0
    {
1499
0
      success = TRUE;
1500
0
    }
1501
0
    else
1502
0
      WLog_WARN(TAG, "SetCredentialsAttributesA returned %s",
1503
0
                GetSecurityStatusString(secStatus));
1504
0
  }
1505
1506
  // return success if at least one submodule accepts the credential attribute
1507
0
  return (success ? SEC_E_OK : SEC_E_UNSUPPORTED_FUNCTION);
1508
0
}
1509
1510
WINPR_ATTR_NODISCARD
1511
static BOOL checkMechCredValid(void* pAuthData, MechCred* cred)
1512
0
{
1513
0
  WINPR_ASSERT(cred);
1514
0
  WINPR_ASSERT(cred->mech);
1515
0
  WINPR_ASSERT(cred->mech->pkg);
1516
1517
0
  BOOL kerberos = FALSE;
1518
0
  BOOL ntlm = FALSE;
1519
0
  BOOL u2u = FALSE;
1520
0
  if (!negotiate_get_config(pAuthData, &kerberos, &ntlm, &u2u))
1521
0
  {
1522
0
    WLog_DBG(TAG, "Failed to get negotiate configuration");
1523
0
    return FALSE;
1524
0
  }
1525
1526
0
  if (!kerberos && sspi_gss_oid_compare(cred->mech->oid, &kerberos_OID))
1527
0
  {
1528
0
    WLog_DBG(TAG, "Kerberos disabled, skipping");
1529
0
    return FALSE;
1530
0
  }
1531
1532
0
  if (!u2u && sspi_gss_oid_compare(cred->mech->oid, &kerberos_u2u_OID))
1533
0
  {
1534
0
    WLog_DBG(TAG, "Kerberos U2U disabled, skipping");
1535
0
    return FALSE;
1536
0
  }
1537
1538
0
  if (!ntlm && _tcsncmp(cred->mech->pkg->name, NTLM_SSP_NAME, ARRAYSIZE(NTLM_SSP_NAME)) == 0)
1539
0
  {
1540
0
    WLog_DBG(TAG, "NTLM disabled, skipping");
1541
0
    return FALSE;
1542
0
  }
1543
0
  return TRUE;
1544
0
}
1545
1546
static SECURITY_STATUS SEC_ENTRY negotiate_AcquireCredentialsHandleW(
1547
    SEC_WCHAR* pszPrincipal, SEC_WCHAR* pszPackage, ULONG fCredentialUse, void* pvLogonID,
1548
    void* pAuthData, SEC_GET_KEY_FN pGetKeyFn, void* pvGetKeyArgument, PCredHandle phCredential,
1549
    PTimeStamp ptsExpiry)
1550
0
{
1551
0
  MechCred* creds = calloc(MECH_COUNT, sizeof(MechCred));
1552
1553
0
  if (!creds)
1554
0
    return SEC_E_INTERNAL_ERROR;
1555
1556
0
  for (size_t i = 0; i < MECH_COUNT; i++)
1557
0
  {
1558
0
    MechCred* cred = &creds[i];
1559
0
    const SecPkg* pkg = MechTable[i].pkg;
1560
0
    cred->mech = &MechTable[i];
1561
1562
0
    if (!checkMechCredValid(pAuthData, cred))
1563
0
      continue;
1564
1565
0
    WINPR_ASSERT(pkg->table_w);
1566
0
    WINPR_ASSERT(pkg->table_w->AcquireCredentialsHandleW);
1567
0
    const SECURITY_STATUS rc = pkg->table_w->AcquireCredentialsHandleW(
1568
0
        pszPrincipal, pszPackage, fCredentialUse, pvLogonID, pAuthData, pGetKeyFn,
1569
0
        pvGetKeyArgument, &cred->cred, ptsExpiry);
1570
0
    if (rc != SEC_E_OK)
1571
0
    {
1572
0
      WLog_DBG(TAG, "AcquireCredentialsHandleW returned %s", GetSecurityStatusString(rc));
1573
0
      continue;
1574
0
    }
1575
1576
0
    cred->valid = TRUE;
1577
0
  }
1578
1579
0
  sspi_SecureHandleSetLowerPointer(phCredential, (void*)creds);
1580
0
  sspi_SecureHandleSetPackageId(phCredential, SSPI_PACKAGE_NEGOTIATE);
1581
0
  return SEC_E_OK;
1582
0
}
1583
1584
static SECURITY_STATUS SEC_ENTRY negotiate_AcquireCredentialsHandleA(
1585
    SEC_CHAR* pszPrincipal, SEC_CHAR* pszPackage, ULONG fCredentialUse, void* pvLogonID,
1586
    void* pAuthData, SEC_GET_KEY_FN pGetKeyFn, void* pvGetKeyArgument, PCredHandle phCredential,
1587
    PTimeStamp ptsExpiry)
1588
0
{
1589
0
  MechCred* creds = calloc(MECH_COUNT, sizeof(MechCred));
1590
1591
0
  if (!creds)
1592
0
    return SEC_E_INTERNAL_ERROR;
1593
1594
0
  for (size_t i = 0; i < MECH_COUNT; i++)
1595
0
  {
1596
0
    const SecPkg* pkg = MechTable[i].pkg;
1597
0
    MechCred* cred = &creds[i];
1598
1599
0
    cred->mech = &MechTable[i];
1600
1601
0
    if (!checkMechCredValid(pAuthData, cred))
1602
0
      continue;
1603
1604
0
    WINPR_ASSERT(pkg->table);
1605
0
    WINPR_ASSERT(pkg->table->AcquireCredentialsHandleA);
1606
0
    const SECURITY_STATUS rc = pkg->table->AcquireCredentialsHandleA(
1607
0
        pszPrincipal, pszPackage, fCredentialUse, pvLogonID, pAuthData, pGetKeyFn,
1608
0
        pvGetKeyArgument, &cred->cred, ptsExpiry);
1609
0
    if (rc != SEC_E_OK)
1610
0
    {
1611
0
      WLog_DBG(TAG, "AcquireCredentialsHandleA returned %s", GetSecurityStatusString(rc));
1612
0
      continue;
1613
0
    }
1614
1615
0
    cred->valid = TRUE;
1616
0
  }
1617
1618
0
  sspi_SecureHandleSetLowerPointer(phCredential, (void*)creds);
1619
0
  sspi_SecureHandleSetPackageId(phCredential, SSPI_PACKAGE_NEGOTIATE);
1620
0
  return SEC_E_OK;
1621
0
}
1622
1623
static SECURITY_STATUS SEC_ENTRY negotiate_QueryCredentialsAttributesW(
1624
    WINPR_ATTR_UNUSED PCredHandle phCredential, WINPR_ATTR_UNUSED ULONG ulAttribute,
1625
    WINPR_ATTR_UNUSED void* pBuffer)
1626
0
{
1627
0
  WLog_ERR(TAG, "TODO: Implement");
1628
0
  return SEC_E_UNSUPPORTED_FUNCTION;
1629
0
}
1630
1631
static SECURITY_STATUS SEC_ENTRY negotiate_QueryCredentialsAttributesA(
1632
    WINPR_ATTR_UNUSED PCredHandle phCredential, WINPR_ATTR_UNUSED ULONG ulAttribute,
1633
    WINPR_ATTR_UNUSED void* pBuffer)
1634
0
{
1635
0
  WLog_ERR(TAG, "TODO: Implement");
1636
0
  return SEC_E_UNSUPPORTED_FUNCTION;
1637
0
}
1638
1639
static SECURITY_STATUS SEC_ENTRY negotiate_FreeCredentialsHandle(PCredHandle phCredential)
1640
0
{
1641
0
  MechCred* creds = sspi_SecureHandleGetLowerPointer(phCredential);
1642
0
  sspi_SecureHandleInvalidate(phCredential);
1643
0
  if (!creds)
1644
0
    return SEC_E_INVALID_HANDLE;
1645
1646
0
  for (size_t i = 0; i < MECH_COUNT; i++)
1647
0
  {
1648
0
    MechCred* cred = &creds[i];
1649
1650
0
    WINPR_ASSERT(cred->mech);
1651
0
    WINPR_ASSERT(cred->mech->pkg);
1652
0
    WINPR_ASSERT(cred->mech->pkg->table);
1653
0
    WINPR_ASSERT(cred->mech->pkg->table->FreeCredentialsHandle);
1654
0
    const SECURITY_STATUS rc = cred->mech->pkg->table->FreeCredentialsHandle(&cred->cred);
1655
0
    if (rc != SEC_E_OK)
1656
0
      WLog_DBG(TAG, "FreeCredentialsHandle returned %s", GetSecurityStatusString(rc));
1657
0
  }
1658
0
  free(creds);
1659
1660
0
  return SEC_E_OK;
1661
0
}
1662
1663
static SECURITY_STATUS SEC_ENTRY negotiate_EncryptMessage(PCtxtHandle phContext, ULONG fQOP,
1664
                                                          PSecBufferDesc pMessage,
1665
                                                          ULONG MessageSeqNo)
1666
0
{
1667
0
  NEGOTIATE_CONTEXT* context = (NEGOTIATE_CONTEXT*)sspi_SecureHandleGetLowerPointer(phContext);
1668
1669
0
  if (!context)
1670
0
    return SEC_E_INVALID_HANDLE;
1671
1672
0
  if (context->mic)
1673
0
    MessageSeqNo++;
1674
1675
0
  WINPR_ASSERT(context->mech);
1676
0
  WINPR_ASSERT(context->mech->pkg);
1677
0
  WINPR_ASSERT(context->mech->pkg->table);
1678
0
  if (context->mech->pkg->table->EncryptMessage)
1679
0
    return context->mech->pkg->table->EncryptMessage(&context->sub_context, fQOP, pMessage,
1680
0
                                                     MessageSeqNo);
1681
1682
0
  return SEC_E_UNSUPPORTED_FUNCTION;
1683
0
}
1684
1685
static SECURITY_STATUS SEC_ENTRY negotiate_DecryptMessage(PCtxtHandle phContext,
1686
                                                          PSecBufferDesc pMessage,
1687
                                                          ULONG MessageSeqNo, ULONG* pfQOP)
1688
0
{
1689
0
  NEGOTIATE_CONTEXT* context = (NEGOTIATE_CONTEXT*)sspi_SecureHandleGetLowerPointer(phContext);
1690
1691
0
  if (!context)
1692
0
    return SEC_E_INVALID_HANDLE;
1693
1694
0
  if (context->mic)
1695
0
    MessageSeqNo++;
1696
1697
0
  WINPR_ASSERT(context->mech);
1698
0
  WINPR_ASSERT(context->mech->pkg);
1699
0
  WINPR_ASSERT(context->mech->pkg->table);
1700
0
  if (context->mech->pkg->table->DecryptMessage)
1701
0
    return context->mech->pkg->table->DecryptMessage(&context->sub_context, pMessage,
1702
0
                                                     MessageSeqNo, pfQOP);
1703
1704
0
  return SEC_E_UNSUPPORTED_FUNCTION;
1705
0
}
1706
1707
static SECURITY_STATUS SEC_ENTRY negotiate_MakeSignature(PCtxtHandle phContext, ULONG fQOP,
1708
                                                         PSecBufferDesc pMessage,
1709
                                                         ULONG MessageSeqNo)
1710
0
{
1711
0
  NEGOTIATE_CONTEXT* context = (NEGOTIATE_CONTEXT*)sspi_SecureHandleGetLowerPointer(phContext);
1712
1713
0
  if (!context)
1714
0
    return SEC_E_INVALID_HANDLE;
1715
1716
0
  if (context->mic)
1717
0
    MessageSeqNo++;
1718
1719
0
  WINPR_ASSERT(context->mech);
1720
0
  WINPR_ASSERT(context->mech->pkg);
1721
0
  WINPR_ASSERT(context->mech->pkg->table);
1722
0
  if (context->mech->pkg->table->MakeSignature)
1723
0
    return context->mech->pkg->table->MakeSignature(&context->sub_context, fQOP, pMessage,
1724
0
                                                    MessageSeqNo);
1725
1726
0
  return SEC_E_UNSUPPORTED_FUNCTION;
1727
0
}
1728
1729
static SECURITY_STATUS SEC_ENTRY negotiate_VerifySignature(PCtxtHandle phContext,
1730
                                                           PSecBufferDesc pMessage,
1731
                                                           ULONG MessageSeqNo, ULONG* pfQOP)
1732
0
{
1733
0
  NEGOTIATE_CONTEXT* context = (NEGOTIATE_CONTEXT*)sspi_SecureHandleGetLowerPointer(phContext);
1734
1735
0
  if (!context)
1736
0
    return SEC_E_INVALID_HANDLE;
1737
1738
0
  if (context->mic)
1739
0
    MessageSeqNo++;
1740
1741
0
  WINPR_ASSERT(context->mech);
1742
0
  WINPR_ASSERT(context->mech->pkg);
1743
0
  WINPR_ASSERT(context->mech->pkg->table);
1744
0
  if (context->mech->pkg->table->VerifySignature)
1745
0
    return context->mech->pkg->table->VerifySignature(&context->sub_context, pMessage,
1746
0
                                                      MessageSeqNo, pfQOP);
1747
1748
0
  return SEC_E_UNSUPPORTED_FUNCTION;
1749
0
}
1750
1751
const SecurityFunctionTableA NEGOTIATE_SecurityFunctionTableA = {
1752
  3,                                     /* dwVersion */
1753
  nullptr,                               /* EnumerateSecurityPackages */
1754
  negotiate_QueryCredentialsAttributesA, /* QueryCredentialsAttributes */
1755
  negotiate_AcquireCredentialsHandleA,   /* AcquireCredentialsHandle */
1756
  negotiate_FreeCredentialsHandle,       /* FreeCredentialsHandle */
1757
  nullptr,                               /* Reserved2 */
1758
  negotiate_InitializeSecurityContextA,  /* InitializeSecurityContext */
1759
  negotiate_AcceptSecurityContext,       /* AcceptSecurityContext */
1760
  negotiate_CompleteAuthToken,           /* CompleteAuthToken */
1761
  negotiate_DeleteSecurityContext,       /* DeleteSecurityContext */
1762
  nullptr,                               /* ApplyControlToken */
1763
  negotiate_QueryContextAttributesA,     /* QueryContextAttributes */
1764
  negotiate_ImpersonateSecurityContext,  /* ImpersonateSecurityContext */
1765
  negotiate_RevertSecurityContext,       /* RevertSecurityContext */
1766
  negotiate_MakeSignature,               /* MakeSignature */
1767
  negotiate_VerifySignature,             /* VerifySignature */
1768
  nullptr,                               /* FreeContextBuffer */
1769
  nullptr,                               /* QuerySecurityPackageInfo */
1770
  nullptr,                               /* Reserved3 */
1771
  nullptr,                               /* Reserved4 */
1772
  nullptr,                               /* ExportSecurityContext */
1773
  nullptr,                               /* ImportSecurityContext */
1774
  nullptr,                               /* AddCredentials */
1775
  nullptr,                               /* Reserved8 */
1776
  nullptr,                               /* QuerySecurityContextToken */
1777
  negotiate_EncryptMessage,              /* EncryptMessage */
1778
  negotiate_DecryptMessage,              /* DecryptMessage */
1779
  negotiate_SetContextAttributesA,       /* SetContextAttributes */
1780
  negotiate_SetCredentialsAttributesA,   /* SetCredentialsAttributes */
1781
};
1782
1783
const SecurityFunctionTableW NEGOTIATE_SecurityFunctionTableW = {
1784
  3,                                     /* dwVersion */
1785
  nullptr,                               /* EnumerateSecurityPackages */
1786
  negotiate_QueryCredentialsAttributesW, /* QueryCredentialsAttributes */
1787
  negotiate_AcquireCredentialsHandleW,   /* AcquireCredentialsHandle */
1788
  negotiate_FreeCredentialsHandle,       /* FreeCredentialsHandle */
1789
  nullptr,                               /* Reserved2 */
1790
  negotiate_InitializeSecurityContextW,  /* InitializeSecurityContext */
1791
  negotiate_AcceptSecurityContext,       /* AcceptSecurityContext */
1792
  negotiate_CompleteAuthToken,           /* CompleteAuthToken */
1793
  negotiate_DeleteSecurityContext,       /* DeleteSecurityContext */
1794
  nullptr,                               /* ApplyControlToken */
1795
  negotiate_QueryContextAttributesW,     /* QueryContextAttributes */
1796
  negotiate_ImpersonateSecurityContext,  /* ImpersonateSecurityContext */
1797
  negotiate_RevertSecurityContext,       /* RevertSecurityContext */
1798
  negotiate_MakeSignature,               /* MakeSignature */
1799
  negotiate_VerifySignature,             /* VerifySignature */
1800
  nullptr,                               /* FreeContextBuffer */
1801
  nullptr,                               /* QuerySecurityPackageInfo */
1802
  nullptr,                               /* Reserved3 */
1803
  nullptr,                               /* Reserved4 */
1804
  nullptr,                               /* ExportSecurityContext */
1805
  nullptr,                               /* ImportSecurityContext */
1806
  nullptr,                               /* AddCredentials */
1807
  nullptr,                               /* Reserved8 */
1808
  nullptr,                               /* QuerySecurityContextToken */
1809
  negotiate_EncryptMessage,              /* EncryptMessage */
1810
  negotiate_DecryptMessage,              /* DecryptMessage */
1811
  negotiate_SetContextAttributesW,       /* SetContextAttributes */
1812
  negotiate_SetCredentialsAttributesW,   /* SetCredentialsAttributes */
1813
};
1814
1815
BOOL NEGOTIATE_init(void)
1816
1
{
1817
1
  InitializeConstWCharFromUtf8(NEGOTIATE_SecPkgInfoA.Name, NEGOTIATE_SecPkgInfoW_NameBuffer,
1818
1
                               ARRAYSIZE(NEGOTIATE_SecPkgInfoW_NameBuffer));
1819
1
  InitializeConstWCharFromUtf8(NEGOTIATE_SecPkgInfoA.Comment, NEGOTIATE_SecPkgInfoW_CommentBuffer,
1820
1
                               ARRAYSIZE(NEGOTIATE_SecPkgInfoW_CommentBuffer));
1821
1822
1
  return TRUE;
1823
1
}