Coverage Report

Created: 2025-07-01 06:46

/src/FreeRDP/libfreerdp/core/nla.c
Line
Count
Source (jump to first uncovered line)
1
/**
2
 * FreeRDP: A Remote Desktop Protocol Implementation
3
 * Network Level Authentication (NLA)
4
 *
5
 * Copyright 2010-2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
6
 * Copyright 2015 Thincast Technologies GmbH
7
 * Copyright 2015 DI (FH) Martin Haimberger <martin.haimberger@thincast.com>
8
 * Copyright 2016 Martin Fleisz <martin.fleisz@thincast.com>
9
 * Copyright 2017 Dorian Ducournau <dorian.ducournau@gmail.com>
10
 * Copyright 2022 David Fort <contact@hardening-consulting.com>
11
 *
12
 * Licensed under the Apache License, Version 2.0 (the "License");
13
 * you may not use this file except in compliance with the License.
14
 * You may obtain a copy of the License at
15
 *
16
 *     http://www.apache.org/licenses/LICENSE-2.0
17
 *
18
 * Unless required by applicable law or agreed to in writing, software
19
 * distributed under the License is distributed on an "AS IS" BASIS,
20
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21
 * See the License for the specific language governing permissions and
22
 * limitations under the License.
23
 */
24
25
#include <freerdp/config.h>
26
27
#include "settings.h"
28
29
#include <time.h>
30
#include <ctype.h>
31
32
#include <freerdp/log.h>
33
#include <freerdp/build-config.h>
34
35
#include <winpr/crt.h>
36
#include <winpr/assert.h>
37
#include <winpr/sam.h>
38
#include <winpr/sspi.h>
39
#include <winpr/print.h>
40
#include <winpr/tchar.h>
41
#include <winpr/ncrypt.h>
42
#include <winpr/cred.h>
43
#include <winpr/debug.h>
44
#include <winpr/asn1.h>
45
#include <winpr/secapi.h>
46
47
#include "../crypto/tls.h"
48
#include "nego.h"
49
#include "rdp.h"
50
#include "nla.h"
51
#include "utils.h"
52
#include "credssp_auth.h"
53
#include <freerdp/utils/smartcardlogon.h>
54
55
#define TAG FREERDP_TAG("core.nla")
56
57
// #define SERVER_KEY "Software\\" FREERDP_VENDOR_STRING "\\" FREERDP_PRODUCT_STRING "\\Server"
58
59
0
#define NLA_AUTH_PKG NEGO_SSP_NAME
60
61
typedef enum
62
{
63
  AUTHZ_SUCCESS = 0x00000000,
64
  AUTHZ_ACCESS_DENIED = 0x00000005,
65
} AUTHZ_RESULT;
66
67
/**
68
 * TSRequest ::= SEQUENCE {
69
 *  version    [0] INTEGER,
70
 *  negoTokens [1] NegoData OPTIONAL,
71
 *  authInfo   [2] OCTET STRING OPTIONAL,
72
 *  pubKeyAuth [3] OCTET STRING OPTIONAL,
73
 *  errorCode  [4] INTEGER OPTIONAL
74
 * }
75
 *
76
 * NegoData ::= SEQUENCE OF NegoDataItem
77
 *
78
 * NegoDataItem ::= SEQUENCE {
79
 *  negoToken [0] OCTET STRING
80
 * }
81
 *
82
 * TSCredentials ::= SEQUENCE {
83
 *  credType    [0] INTEGER,
84
 *  credentials [1] OCTET STRING
85
 * }
86
 *
87
 * TSPasswordCreds ::= SEQUENCE {
88
 *  domainName  [0] OCTET STRING,
89
 *  userName    [1] OCTET STRING,
90
 *  password    [2] OCTET STRING
91
 * }
92
 *
93
 * TSSmartCardCreds ::= SEQUENCE {
94
 *  pin        [0] OCTET STRING,
95
 *  cspData    [1] TSCspDataDetail,
96
 *  userHint   [2] OCTET STRING OPTIONAL,
97
 *  domainHint [3] OCTET STRING OPTIONAL
98
 * }
99
 *
100
 * TSCspDataDetail ::= SEQUENCE {
101
 *  keySpec       [0] INTEGER,
102
 *  cardName      [1] OCTET STRING OPTIONAL,
103
 *  readerName    [2] OCTET STRING OPTIONAL,
104
 *  containerName [3] OCTET STRING OPTIONAL,
105
 *  cspName       [4] OCTET STRING OPTIONAL
106
 * }
107
 *
108
 */
109
110
struct rdp_nla
111
{
112
  BOOL server;
113
  NLA_STATE state;
114
  ULONG sendSeqNum;
115
  ULONG recvSeqNum;
116
  rdpContext* rdpcontext;
117
  rdpTransport* transport;
118
  UINT32 version;
119
  UINT32 peerVersion;
120
  INT32 errorCode;
121
122
  /* Lifetime of buffer nla_new -> nla_free */
123
  SecBuffer ClientNonce; /* Depending on protocol version a random nonce or a value read from the
124
                            server. */
125
126
  SecBuffer negoToken;
127
  SecBuffer pubKeyAuth;
128
  SecBuffer authInfo;
129
  SecBuffer PublicKey;
130
  SecBuffer tsCredentials;
131
132
  SEC_WINNT_AUTH_IDENTITY* identity;
133
134
  rdpCredsspAuth* auth;
135
  char* pkinitArgs;
136
  SmartcardCertInfo* smartcardCert;
137
  BYTE certSha1[20];
138
  BOOL earlyUserAuth;
139
};
140
141
static BOOL nla_send(rdpNla* nla);
142
static int nla_server_recv(rdpNla* nla);
143
static BOOL nla_encrypt_public_key_echo(rdpNla* nla);
144
static BOOL nla_encrypt_public_key_hash(rdpNla* nla);
145
static BOOL nla_decrypt_public_key_echo(rdpNla* nla);
146
static BOOL nla_decrypt_public_key_hash(rdpNla* nla);
147
static BOOL nla_encrypt_ts_credentials(rdpNla* nla);
148
static BOOL nla_decrypt_ts_credentials(rdpNla* nla);
149
150
void nla_set_early_user_auth(rdpNla* nla, BOOL earlyUserAuth)
151
0
{
152
0
  WINPR_ASSERT(nla);
153
0
  WLog_DBG(TAG, "Early User Auth active: %s", earlyUserAuth ? "true" : "false");
154
0
  nla->earlyUserAuth = earlyUserAuth;
155
0
}
156
157
static void nla_buffer_free(rdpNla* nla)
158
0
{
159
0
  WINPR_ASSERT(nla);
160
0
  sspi_SecBufferFree(&nla->pubKeyAuth);
161
0
  sspi_SecBufferFree(&nla->authInfo);
162
0
  sspi_SecBufferFree(&nla->negoToken);
163
0
  sspi_SecBufferFree(&nla->ClientNonce);
164
0
  sspi_SecBufferFree(&nla->PublicKey);
165
0
}
166
167
static BOOL nla_Digest_Update_From_SecBuffer(WINPR_DIGEST_CTX* ctx, const SecBuffer* buffer)
168
0
{
169
0
  if (!buffer)
170
0
    return FALSE;
171
0
  return winpr_Digest_Update(ctx, buffer->pvBuffer, buffer->cbBuffer);
172
0
}
173
174
static BOOL nla_sec_buffer_alloc(SecBuffer* buffer, size_t size)
175
0
{
176
0
  WINPR_ASSERT(buffer);
177
0
  sspi_SecBufferFree(buffer);
178
0
  if (size > UINT32_MAX)
179
0
    return FALSE;
180
0
  if (!sspi_SecBufferAlloc(buffer, (ULONG)size))
181
0
    return FALSE;
182
183
0
  WINPR_ASSERT(buffer);
184
0
  buffer->BufferType = SECBUFFER_TOKEN;
185
0
  return TRUE;
186
0
}
187
188
static BOOL nla_sec_buffer_alloc_from_data(SecBuffer* buffer, const BYTE* data, size_t offset,
189
                                           size_t size)
190
0
{
191
0
  if (!nla_sec_buffer_alloc(buffer, offset + size))
192
0
    return FALSE;
193
194
0
  WINPR_ASSERT(buffer);
195
0
  BYTE* pb = buffer->pvBuffer;
196
0
  memcpy(&pb[offset], data, size);
197
0
  return TRUE;
198
0
}
199
200
/* CredSSP Client-To-Server Binding Hash\0 */
201
static const BYTE ClientServerHashMagic[] = { 0x43, 0x72, 0x65, 0x64, 0x53, 0x53, 0x50, 0x20,
202
                                            0x43, 0x6C, 0x69, 0x65, 0x6E, 0x74, 0x2D, 0x54,
203
                                            0x6F, 0x2D, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72,
204
                                            0x20, 0x42, 0x69, 0x6E, 0x64, 0x69, 0x6E, 0x67,
205
                                            0x20, 0x48, 0x61, 0x73, 0x68, 0x00 };
206
207
/* CredSSP Server-To-Client Binding Hash\0 */
208
static const BYTE ServerClientHashMagic[] = { 0x43, 0x72, 0x65, 0x64, 0x53, 0x53, 0x50, 0x20,
209
                                            0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x2D, 0x54,
210
                                            0x6F, 0x2D, 0x43, 0x6C, 0x69, 0x65, 0x6E, 0x74,
211
                                            0x20, 0x42, 0x69, 0x6E, 0x64, 0x69, 0x6E, 0x67,
212
                                            0x20, 0x48, 0x61, 0x73, 0x68, 0x00 };
213
214
static const UINT32 NonceLength = 32;
215
216
static BOOL nla_adjust_settings_from_smartcard(rdpNla* nla)
217
0
{
218
0
  BOOL ret = FALSE;
219
220
0
  WINPR_ASSERT(nla);
221
0
  WINPR_ASSERT(nla->rdpcontext);
222
223
0
  rdpSettings* settings = nla->rdpcontext->settings;
224
0
  WINPR_ASSERT(settings);
225
226
0
  if (!settings->SmartcardLogon)
227
0
    return TRUE;
228
229
0
  smartcardCertInfo_Free(nla->smartcardCert);
230
231
0
  if (!smartcard_getCert(nla->rdpcontext, &nla->smartcardCert, FALSE))
232
0
  {
233
0
    WLog_ERR(TAG, "unable to get smartcard certificate for logon");
234
0
    return FALSE;
235
0
  }
236
237
0
  if (!settings->CspName)
238
0
  {
239
0
    if (nla->smartcardCert->csp && !freerdp_settings_set_string_from_utf16(
240
0
                                       settings, FreeRDP_CspName, nla->smartcardCert->csp))
241
0
    {
242
0
      WLog_ERR(TAG, "unable to set CSP name");
243
0
      goto out;
244
0
    }
245
0
    if (!settings->CspName &&
246
0
        !freerdp_settings_set_string(settings, FreeRDP_CspName, MS_SCARD_PROV_A))
247
0
    {
248
0
      WLog_ERR(TAG, "unable to set CSP name");
249
0
      goto out;
250
0
    }
251
0
  }
252
253
0
  if (!settings->ReaderName && nla->smartcardCert->reader)
254
0
  {
255
0
    if (!freerdp_settings_set_string_from_utf16(settings, FreeRDP_ReaderName,
256
0
                                                nla->smartcardCert->reader))
257
0
    {
258
0
      WLog_ERR(TAG, "unable to copy reader name");
259
0
      goto out;
260
0
    }
261
0
  }
262
263
0
  if (!settings->ContainerName && nla->smartcardCert->containerName)
264
0
  {
265
0
    if (!freerdp_settings_set_string_from_utf16(settings, FreeRDP_ContainerName,
266
0
                                                nla->smartcardCert->containerName))
267
0
    {
268
0
      WLog_ERR(TAG, "unable to copy container name");
269
0
      goto out;
270
0
    }
271
0
  }
272
273
0
  memcpy(nla->certSha1, nla->smartcardCert->sha1Hash, sizeof(nla->certSha1));
274
275
0
  if (nla->smartcardCert->pkinitArgs)
276
0
  {
277
0
    nla->pkinitArgs = _strdup(nla->smartcardCert->pkinitArgs);
278
0
    if (!nla->pkinitArgs)
279
0
    {
280
0
      WLog_ERR(TAG, "unable to copy pkinitArgs");
281
0
      goto out;
282
0
    }
283
0
  }
284
285
0
  ret = TRUE;
286
0
out:
287
0
  return ret;
288
0
}
289
290
static BOOL nla_client_setup_identity(rdpNla* nla)
291
0
{
292
0
  BOOL PromptPassword = FALSE;
293
294
0
  WINPR_ASSERT(nla);
295
0
  WINPR_ASSERT(nla->rdpcontext);
296
297
0
  rdpSettings* settings = nla->rdpcontext->settings;
298
0
  WINPR_ASSERT(settings);
299
300
0
  freerdp* instance = nla->rdpcontext->instance;
301
0
  WINPR_ASSERT(instance);
302
303
  /* */
304
0
  if ((utils_str_is_empty(settings->Username) ||
305
0
       (utils_str_is_empty(settings->Password) &&
306
0
        utils_str_is_empty((const char*)settings->RedirectionPassword))))
307
0
  {
308
0
    PromptPassword = TRUE;
309
0
  }
310
311
0
  if (PromptPassword && !utils_str_is_empty(settings->Username))
312
0
  {
313
0
    WINPR_SAM* sam = SamOpen(NULL, TRUE);
314
0
    if (sam)
315
0
    {
316
0
      const UINT32 userLength = (UINT32)strnlen(settings->Username, INT32_MAX);
317
0
      WINPR_SAM_ENTRY* entry = SamLookupUserA(
318
0
          sam, settings->Username, userLength + 1 /* ensure '\0' is checked too */, NULL, 0);
319
0
      if (entry)
320
0
      {
321
        /**
322
         * The user could be found in SAM database.
323
         * Use entry in SAM database later instead of prompt
324
         */
325
0
        PromptPassword = FALSE;
326
0
        SamFreeEntry(sam, entry);
327
0
      }
328
329
0
      SamClose(sam);
330
0
    }
331
0
  }
332
333
0
  if (PromptPassword)
334
0
  {
335
0
    if (settings->RestrictedAdminModeRequired)
336
0
    {
337
0
      if ((settings->PasswordHash) && (strlen(settings->PasswordHash) > 0))
338
0
        PromptPassword = FALSE;
339
0
    }
340
341
0
    if (settings->RemoteCredentialGuard)
342
0
      PromptPassword = FALSE;
343
0
  }
344
345
0
  BOOL smartCardLogonWasDisabled = !settings->SmartcardLogon;
346
0
  if (PromptPassword)
347
0
  {
348
0
    switch (utils_authenticate(instance, AUTH_NLA, TRUE))
349
0
    {
350
0
      case AUTH_SKIP:
351
0
      case AUTH_SUCCESS:
352
0
        break;
353
0
      case AUTH_CANCELLED:
354
0
        freerdp_set_last_error_log(instance->context, FREERDP_ERROR_CONNECT_CANCELLED);
355
0
        return FALSE;
356
0
      case AUTH_NO_CREDENTIALS:
357
0
        WLog_INFO(TAG, "No credentials provided - using NULL identity");
358
0
        break;
359
0
      default:
360
0
        return FALSE;
361
0
    }
362
0
  }
363
364
0
  if (!settings->Username)
365
0
  {
366
0
    sspi_FreeAuthIdentity(nla->identity);
367
0
    free(nla->identity);
368
0
    nla->identity = NULL;
369
0
  }
370
0
  else if (settings->SmartcardLogon)
371
0
  {
372
0
    if (smartCardLogonWasDisabled)
373
0
    {
374
0
      if (!nla_adjust_settings_from_smartcard(nla))
375
0
        return FALSE;
376
0
    }
377
378
0
    if (!identity_set_from_smartcard_hash(nla->identity, settings, FreeRDP_Username,
379
0
                                          FreeRDP_Domain, FreeRDP_Password, nla->certSha1,
380
0
                                          sizeof(nla->certSha1)))
381
0
      return FALSE;
382
0
  }
383
0
  else
384
0
  {
385
0
    BOOL usePassword = TRUE;
386
387
0
    if (settings->RedirectionPassword && (settings->RedirectionPasswordLength > 0))
388
0
    {
389
0
      const WCHAR* wstr = (const WCHAR*)settings->RedirectionPassword;
390
0
      const size_t len = _wcsnlen(wstr, settings->RedirectionPasswordLength / sizeof(WCHAR));
391
392
0
      if (!identity_set_from_settings_with_pwd(nla->identity, settings, FreeRDP_Username,
393
0
                                               FreeRDP_Domain, wstr, len))
394
0
        return FALSE;
395
396
0
      usePassword = FALSE;
397
0
    }
398
399
0
    if (settings->RestrictedAdminModeRequired)
400
0
    {
401
0
      if (settings->PasswordHash && strlen(settings->PasswordHash) == 32)
402
0
      {
403
0
        if (!identity_set_from_settings(nla->identity, settings, FreeRDP_Username,
404
0
                                        FreeRDP_Domain, FreeRDP_PasswordHash))
405
0
          return FALSE;
406
407
        /**
408
         * Increase password hash length by LB_PASSWORD_MAX_LENGTH to obtain a
409
         * length exceeding the maximum (LB_PASSWORD_MAX_LENGTH) and use it this for
410
         * hash identification in WinPR.
411
         */
412
0
        nla->identity->PasswordLength += LB_PASSWORD_MAX_LENGTH;
413
0
        usePassword = FALSE;
414
0
      }
415
0
    }
416
417
0
    if (usePassword)
418
0
    {
419
0
      if (!identity_set_from_settings(nla->identity, settings, FreeRDP_Username,
420
0
                                      FreeRDP_Domain, FreeRDP_Password))
421
0
        return FALSE;
422
0
    }
423
0
  }
424
425
0
  return TRUE;
426
0
}
427
428
static int nla_client_init(rdpNla* nla)
429
0
{
430
0
  WINPR_ASSERT(nla);
431
0
  WINPR_ASSERT(nla->rdpcontext);
432
433
0
  rdpSettings* settings = nla->rdpcontext->settings;
434
0
  WINPR_ASSERT(settings);
435
436
0
  nla_set_state(nla, NLA_STATE_INITIAL);
437
438
0
  if (!nla_adjust_settings_from_smartcard(nla))
439
0
    return -1;
440
441
0
  if (!credssp_auth_init(nla->auth, NLA_AUTH_PKG, NULL))
442
0
    return -1;
443
444
0
  if (!nla_client_setup_identity(nla))
445
0
    return -1;
446
447
0
  const char* hostname = freerdp_settings_get_server_name(settings);
448
449
0
  if (!credssp_auth_setup_client(nla->auth, "TERMSRV", hostname, nla->identity, nla->pkinitArgs))
450
0
    return -1;
451
452
0
  const BYTE* data = NULL;
453
0
  DWORD length = 0;
454
0
  if (!transport_get_public_key(nla->transport, &data, &length))
455
0
  {
456
0
    WLog_ERR(TAG, "Failed to get public key");
457
0
    return -1;
458
0
  }
459
460
0
  if (!nla_sec_buffer_alloc_from_data(&nla->PublicKey, data, 0, length))
461
0
  {
462
0
    WLog_ERR(TAG, "Failed to allocate sspi secBuffer");
463
0
    return -1;
464
0
  }
465
466
0
  return 1;
467
0
}
468
469
int nla_client_begin(rdpNla* nla)
470
0
{
471
0
  WINPR_ASSERT(nla);
472
473
0
  if (nla_client_init(nla) < 1)
474
0
    return -1;
475
476
0
  if (nla_get_state(nla) != NLA_STATE_INITIAL)
477
0
    return -1;
478
479
  /*
480
   * from tspkg.dll: 0x00000132
481
   * ISC_REQ_MUTUAL_AUTH
482
   * ISC_REQ_CONFIDENTIALITY
483
   * ISC_REQ_USE_SESSION_KEY
484
   * ISC_REQ_ALLOCATE_MEMORY
485
   */
486
0
  credssp_auth_set_flags(nla->auth, ISC_REQ_MUTUAL_AUTH | ISC_REQ_CONFIDENTIALITY);
487
488
0
  const int rc = credssp_auth_authenticate(nla->auth);
489
490
0
  switch (rc)
491
0
  {
492
0
    case 0:
493
0
      if (!nla_send(nla))
494
0
        return -1;
495
0
      nla_set_state(nla, NLA_STATE_NEGO_TOKEN);
496
0
      break;
497
0
    case 1:
498
0
      if (credssp_auth_have_output_token(nla->auth))
499
0
      {
500
0
        if (!nla_send(nla))
501
0
          return -1;
502
0
      }
503
0
      nla_set_state(nla, NLA_STATE_FINAL);
504
0
      break;
505
0
    default:
506
0
      switch (credssp_auth_sspi_error(nla->auth))
507
0
      {
508
0
        case SEC_E_LOGON_DENIED:
509
0
        case SEC_E_NO_CREDENTIALS:
510
0
          freerdp_set_last_error_log(nla->rdpcontext,
511
0
                                     FREERDP_ERROR_CONNECT_LOGON_FAILURE);
512
0
          break;
513
0
        default:
514
0
          break;
515
0
      }
516
0
      return -1;
517
0
  }
518
519
0
  return 1;
520
0
}
521
522
static int nla_client_recv_nego_token(rdpNla* nla)
523
0
{
524
0
  credssp_auth_take_input_buffer(nla->auth, &nla->negoToken);
525
0
  const int rc = credssp_auth_authenticate(nla->auth);
526
527
0
  switch (rc)
528
0
  {
529
0
    case 0:
530
0
      if (!nla_send(nla))
531
0
        return -1;
532
0
      break;
533
0
    case 1: /* completed */
534
0
    {
535
0
      int res = -1;
536
0
      if (nla->peerVersion < 5)
537
0
        res = nla_encrypt_public_key_echo(nla);
538
0
      else
539
0
        res = nla_encrypt_public_key_hash(nla);
540
541
0
      if (!res)
542
0
        return -1;
543
544
0
      if (!nla_send(nla))
545
0
        return -1;
546
547
0
      nla_set_state(nla, NLA_STATE_PUB_KEY_AUTH);
548
0
    }
549
0
    break;
550
551
0
    default:
552
0
      return -1;
553
0
  }
554
555
0
  return 1;
556
0
}
557
558
static int nla_client_recv_pub_key_auth(rdpNla* nla)
559
0
{
560
0
  BOOL rc = FALSE;
561
562
0
  WINPR_ASSERT(nla);
563
564
  /* Verify Server Public Key Echo */
565
0
  if (nla->peerVersion < 5)
566
0
    rc = nla_decrypt_public_key_echo(nla);
567
0
  else
568
0
    rc = nla_decrypt_public_key_hash(nla);
569
570
0
  sspi_SecBufferFree(&nla->pubKeyAuth);
571
572
0
  if (!rc)
573
0
    return -1;
574
575
  /* Send encrypted credentials */
576
0
  rc = nla_encrypt_ts_credentials(nla);
577
0
  if (!rc)
578
0
    return -1;
579
580
0
  if (!nla_send(nla))
581
0
    return -1;
582
583
0
  if (nla->earlyUserAuth)
584
0
  {
585
0
    transport_set_early_user_auth_mode(nla->transport, TRUE);
586
0
    nla_set_state(nla, NLA_STATE_EARLY_USER_AUTH);
587
0
  }
588
0
  else
589
0
    nla_set_state(nla, NLA_STATE_AUTH_INFO);
590
0
  return 1;
591
0
}
592
593
static int nla_client_recv_early_user_auth(rdpNla* nla)
594
0
{
595
0
  WINPR_ASSERT(nla);
596
597
0
  transport_set_early_user_auth_mode(nla->transport, FALSE);
598
0
  nla_set_state(nla, NLA_STATE_AUTH_INFO);
599
0
  return 1;
600
0
}
601
602
static int nla_client_recv(rdpNla* nla)
603
0
{
604
0
  WINPR_ASSERT(nla);
605
606
0
  switch (nla_get_state(nla))
607
0
  {
608
0
    case NLA_STATE_NEGO_TOKEN:
609
0
      return nla_client_recv_nego_token(nla);
610
611
0
    case NLA_STATE_PUB_KEY_AUTH:
612
0
      return nla_client_recv_pub_key_auth(nla);
613
614
0
    case NLA_STATE_EARLY_USER_AUTH:
615
0
      return nla_client_recv_early_user_auth(nla);
616
617
0
    case NLA_STATE_FINAL:
618
0
    default:
619
0
      WLog_ERR(TAG, "NLA in invalid client receive state %s",
620
0
               nla_get_state_str(nla_get_state(nla)));
621
0
      return -1;
622
0
  }
623
0
}
624
625
static int nla_client_authenticate(rdpNla* nla)
626
0
{
627
0
  int rc = -1;
628
629
0
  WINPR_ASSERT(nla);
630
631
0
  wStream* s = Stream_New(NULL, 4096);
632
633
0
  if (!s)
634
0
  {
635
0
    WLog_ERR(TAG, "Stream_New failed!");
636
0
    return -1;
637
0
  }
638
639
0
  if (nla_client_begin(nla) < 1)
640
0
    goto fail;
641
642
0
  while (nla_get_state(nla) < NLA_STATE_AUTH_INFO)
643
0
  {
644
0
    Stream_SetPosition(s, 0);
645
0
    const int status = transport_read_pdu(nla->transport, s);
646
647
0
    if (status < 0)
648
0
    {
649
0
      WLog_ERR(TAG, "nla_client_authenticate failure");
650
0
      goto fail;
651
0
    }
652
653
0
    const int status2 = nla_recv_pdu(nla, s);
654
655
0
    if (status2 < 0)
656
0
      goto fail;
657
0
  }
658
659
0
  rc = 1;
660
0
fail:
661
0
  Stream_Free(s, TRUE);
662
0
  return rc;
663
0
}
664
665
/**
666
 * Initialize NTLMSSP authentication module (server).
667
 */
668
669
static int nla_server_init(rdpNla* nla)
670
0
{
671
0
  WINPR_ASSERT(nla);
672
673
0
  const BYTE* data = NULL;
674
0
  DWORD length = 0;
675
0
  if (!transport_get_public_key(nla->transport, &data, &length))
676
0
  {
677
0
    WLog_ERR(TAG, "Failed to get public key");
678
0
    return -1;
679
0
  }
680
681
0
  if (!nla_sec_buffer_alloc_from_data(&nla->PublicKey, data, 0, length))
682
0
  {
683
0
    WLog_ERR(TAG, "Failed to allocate SecBuffer for public key");
684
0
    return -1;
685
0
  }
686
687
0
  if (!credssp_auth_init(nla->auth, NLA_AUTH_PKG, NULL))
688
0
    return -1;
689
690
0
  if (!credssp_auth_setup_server(nla->auth))
691
0
    return -1;
692
693
0
  nla_set_state(nla, NLA_STATE_INITIAL);
694
0
  return 1;
695
0
}
696
697
static wStream* nla_server_recv_stream(rdpNla* nla)
698
0
{
699
0
  wStream* s = NULL;
700
0
  int status = -1;
701
702
0
  WINPR_ASSERT(nla);
703
704
0
  s = Stream_New(NULL, 4096);
705
706
0
  if (!s)
707
0
    goto fail;
708
709
0
  status = transport_read_pdu(nla->transport, s);
710
711
0
fail:
712
0
  if (status < 0)
713
0
  {
714
0
    WLog_ERR(TAG, "nla_recv() error: %d", status);
715
0
    Stream_Free(s, TRUE);
716
0
    return NULL;
717
0
  }
718
719
0
  return s;
720
0
}
721
722
static BOOL nla_server_recv_credentials(rdpNla* nla)
723
0
{
724
0
  WINPR_ASSERT(nla);
725
726
0
  if (nla_server_recv(nla) < 0)
727
0
    return FALSE;
728
729
0
  if (!nla_decrypt_ts_credentials(nla))
730
0
    return FALSE;
731
732
0
  if (!nla_impersonate(nla))
733
0
    return FALSE;
734
735
0
  if (!nla_revert_to_self(nla))
736
0
    return FALSE;
737
738
0
  return TRUE;
739
0
}
740
741
/**
742
 * Authenticate with client using CredSSP (server).
743
 * @param nla The NLA instance to use
744
 *
745
 * @return 1 if authentication is successful
746
 */
747
748
static int nla_server_authenticate(rdpNla* nla)
749
0
{
750
0
  int ret = -1;
751
752
0
  WINPR_ASSERT(nla);
753
754
0
  if (nla_server_init(nla) < 1)
755
0
    goto fail;
756
757
  /*
758
   * from tspkg.dll: 0x00000112
759
   * ASC_REQ_MUTUAL_AUTH
760
   * ASC_REQ_CONFIDENTIALITY
761
   * ASC_REQ_ALLOCATE_MEMORY
762
   */
763
0
  credssp_auth_set_flags(nla->auth, ASC_REQ_MUTUAL_AUTH | ASC_REQ_CONFIDENTIALITY |
764
0
                                        ASC_REQ_CONNECTION | ASC_REQ_USE_SESSION_KEY |
765
0
                                        ASC_REQ_SEQUENCE_DETECT | ASC_REQ_EXTENDED_ERROR);
766
767
  /* Client is starting, here es the state machine:
768
   *
769
   *  -- NLA_STATE_INITIAL  --> NLA_STATE_INITIAL
770
   * ----->> sending...
771
   *    ----->> protocol version 6
772
   *    ----->> nego token
773
   *    ----->> client nonce
774
   * <<----- receiving...
775
   *    <<----- protocol version 6
776
   *    <<----- nego token
777
   * ----->> sending...
778
   *    ----->> protocol version 6
779
   *    ----->> nego token
780
   *    ----->> public key auth
781
   *    ----->> client nonce
782
   * -- NLA_STATE_NEGO_TOKEN  --> NLA_STATE_PUB_KEY_AUTH
783
   * <<----- receiving...
784
   *    <<----- protocol version 6
785
   *    <<----- public key info
786
   * ----->> sending...
787
   *    ----->> protocol version 6
788
   *    ----->> auth info
789
   *    ----->> client nonce
790
   * -- NLA_STATE_PUB_KEY_AUTH  --> NLA_STATE
791
   */
792
793
0
  while (TRUE)
794
0
  {
795
0
    int res = -1;
796
797
0
    if (nla_server_recv(nla) < 0)
798
0
      goto fail;
799
800
0
    WLog_DBG(TAG, "Receiving Authentication Token");
801
0
    credssp_auth_take_input_buffer(nla->auth, &nla->negoToken);
802
803
0
    res = credssp_auth_authenticate(nla->auth);
804
805
0
    if (res == -1)
806
0
    {
807
      /* Special handling of these specific error codes as NTSTATUS_FROM_WIN32
808
         unfortunately does not map directly to the corresponding NTSTATUS values
809
       */
810
0
      switch (GetLastError())
811
0
      {
812
0
        case ERROR_PASSWORD_MUST_CHANGE:
813
0
          nla->errorCode = STATUS_PASSWORD_MUST_CHANGE;
814
0
          break;
815
816
0
        case ERROR_PASSWORD_EXPIRED:
817
0
          nla->errorCode = STATUS_PASSWORD_EXPIRED;
818
0
          break;
819
820
0
        case ERROR_ACCOUNT_DISABLED:
821
0
          nla->errorCode = STATUS_ACCOUNT_DISABLED;
822
0
          break;
823
824
0
        default:
825
0
          nla->errorCode = NTSTATUS_FROM_WIN32(GetLastError());
826
0
          break;
827
0
      }
828
829
0
      (void)nla_send(nla);
830
      /* Access Denied */
831
0
      goto fail;
832
0
    }
833
834
0
    if (res == 1)
835
0
    {
836
      /* Process final part of the nego token exchange */
837
0
      if (credssp_auth_have_output_token(nla->auth))
838
0
      {
839
0
        if (!nla_send(nla))
840
0
          goto fail;
841
842
0
        if (nla_server_recv(nla) < 0)
843
0
          goto fail;
844
845
0
        WLog_DBG(TAG, "Receiving pubkey Token");
846
0
      }
847
848
0
      if (nla->peerVersion < 5)
849
0
        res = nla_decrypt_public_key_echo(nla);
850
0
      else
851
0
        res = nla_decrypt_public_key_hash(nla);
852
853
0
      if (!res)
854
0
        goto fail;
855
856
      /* Clear nego token buffer or we will send it again to the client */
857
0
      sspi_SecBufferFree(&nla->negoToken);
858
859
0
      if (nla->peerVersion < 5)
860
0
        res = nla_encrypt_public_key_echo(nla);
861
0
      else
862
0
        res = nla_encrypt_public_key_hash(nla);
863
864
0
      if (!res)
865
0
        goto fail;
866
0
    }
867
868
    /* send authentication token */
869
0
    WLog_DBG(TAG, "Sending Authentication Token");
870
871
0
    if (!nla_send(nla))
872
0
      goto fail;
873
874
0
    if (res == 1)
875
0
    {
876
0
      ret = 1;
877
0
      break;
878
0
    }
879
0
  }
880
881
  /* Receive encrypted credentials */
882
0
  if (!nla_server_recv_credentials(nla))
883
0
    ret = -1;
884
885
0
fail:
886
0
  nla_buffer_free(nla);
887
0
  return ret;
888
0
}
889
890
/**
891
 * Authenticate using CredSSP.
892
 * @param nla The NLA instance to use
893
 *
894
 * @return 1 if authentication is successful
895
 */
896
897
int nla_authenticate(rdpNla* nla)
898
0
{
899
0
  WINPR_ASSERT(nla);
900
901
0
  if (nla->server)
902
0
    return nla_server_authenticate(nla);
903
0
  else
904
0
    return nla_client_authenticate(nla);
905
0
}
906
907
static void ap_integer_increment_le(BYTE* number, size_t size)
908
0
{
909
0
  WINPR_ASSERT(number || (size == 0));
910
911
0
  for (size_t index = 0; index < size; index++)
912
0
  {
913
0
    if (number[index] < 0xFF)
914
0
    {
915
0
      number[index]++;
916
0
      break;
917
0
    }
918
0
    else
919
0
    {
920
0
      number[index] = 0;
921
0
      continue;
922
0
    }
923
0
  }
924
0
}
925
926
static void ap_integer_decrement_le(BYTE* number, size_t size)
927
0
{
928
0
  WINPR_ASSERT(number || (size == 0));
929
930
0
  for (size_t index = 0; index < size; index++)
931
0
  {
932
0
    if (number[index] > 0)
933
0
    {
934
0
      number[index]--;
935
0
      break;
936
0
    }
937
0
    else
938
0
    {
939
0
      number[index] = 0xFF;
940
0
      continue;
941
0
    }
942
0
  }
943
0
}
944
945
BOOL nla_encrypt_public_key_echo(rdpNla* nla)
946
0
{
947
0
  BOOL status = FALSE;
948
949
0
  WINPR_ASSERT(nla);
950
951
0
  sspi_SecBufferFree(&nla->pubKeyAuth);
952
0
  if (nla->server)
953
0
  {
954
0
    SecBuffer buf = { 0 };
955
0
    if (!sspi_SecBufferAlloc(&buf, nla->PublicKey.cbBuffer))
956
0
      return FALSE;
957
0
    ap_integer_increment_le(buf.pvBuffer, buf.cbBuffer);
958
0
    status = credssp_auth_encrypt(nla->auth, &buf, &nla->pubKeyAuth, NULL, nla->sendSeqNum++);
959
0
    sspi_SecBufferFree(&buf);
960
0
  }
961
0
  else
962
0
  {
963
0
    status = credssp_auth_encrypt(nla->auth, &nla->PublicKey, &nla->pubKeyAuth, NULL,
964
0
                                  nla->sendSeqNum++);
965
0
  }
966
967
0
  return status;
968
0
}
969
970
BOOL nla_encrypt_public_key_hash(rdpNla* nla)
971
0
{
972
0
  BOOL status = FALSE;
973
0
  WINPR_DIGEST_CTX* sha256 = NULL;
974
0
  SecBuffer buf = { 0 };
975
976
0
  WINPR_ASSERT(nla);
977
978
0
  const BYTE* hashMagic = nla->server ? ServerClientHashMagic : ClientServerHashMagic;
979
0
  const size_t hashSize =
980
0
      nla->server ? sizeof(ServerClientHashMagic) : sizeof(ClientServerHashMagic);
981
982
0
  if (!sspi_SecBufferAlloc(&buf, WINPR_SHA256_DIGEST_LENGTH))
983
0
    return FALSE;
984
985
  /* generate SHA256 of following data: ClientServerHashMagic, Nonce, SubjectPublicKey */
986
0
  if (!(sha256 = winpr_Digest_New()))
987
0
    goto out;
988
989
0
  if (!winpr_Digest_Init(sha256, WINPR_MD_SHA256))
990
0
    goto out;
991
992
  /* include trailing \0 from hashMagic */
993
0
  if (!winpr_Digest_Update(sha256, hashMagic, hashSize))
994
0
    goto out;
995
996
0
  if (!nla_Digest_Update_From_SecBuffer(sha256, &nla->ClientNonce))
997
0
    goto out;
998
999
  /* SubjectPublicKey */
1000
0
  if (!nla_Digest_Update_From_SecBuffer(sha256, &nla->PublicKey))
1001
0
    goto out;
1002
1003
0
  if (!winpr_Digest_Final(sha256, buf.pvBuffer, WINPR_SHA256_DIGEST_LENGTH))
1004
0
    goto out;
1005
1006
0
  sspi_SecBufferFree(&nla->pubKeyAuth);
1007
0
  if (!credssp_auth_encrypt(nla->auth, &buf, &nla->pubKeyAuth, NULL, nla->sendSeqNum++))
1008
0
    goto out;
1009
1010
0
  status = TRUE;
1011
1012
0
out:
1013
0
  winpr_Digest_Free(sha256);
1014
0
  sspi_SecBufferFree(&buf);
1015
0
  return status;
1016
0
}
1017
1018
BOOL nla_decrypt_public_key_echo(rdpNla* nla)
1019
0
{
1020
0
  BOOL status = FALSE;
1021
0
  SecBuffer public_key = { 0 };
1022
1023
0
  if (!nla)
1024
0
    goto fail;
1025
1026
0
  if (!credssp_auth_decrypt(nla->auth, &nla->pubKeyAuth, &public_key, nla->recvSeqNum++))
1027
0
    return FALSE;
1028
1029
0
  if (!nla->server)
1030
0
  {
1031
    /* server echos the public key +1 */
1032
0
    ap_integer_decrement_le(public_key.pvBuffer, public_key.cbBuffer);
1033
0
  }
1034
1035
0
  if (public_key.cbBuffer != nla->PublicKey.cbBuffer ||
1036
0
      memcmp(public_key.pvBuffer, nla->PublicKey.pvBuffer, public_key.cbBuffer) != 0)
1037
0
  {
1038
0
    WLog_ERR(TAG, "Could not verify server's public key echo");
1039
#if defined(WITH_DEBUG_NLA)
1040
    WLog_ERR(TAG, "Expected (length = %" PRIu32 "):", nla->PublicKey.cbBuffer);
1041
    winpr_HexDump(TAG, WLOG_ERROR, nla->PublicKey.pvBuffer, nla->PublicKey.cbBuffer);
1042
    WLog_ERR(TAG, "Actual (length = %" PRIu32 "):", public_key.cbBuffer);
1043
    winpr_HexDump(TAG, WLOG_ERROR, public_key.pvBuffer, public_key.cbBuffer);
1044
#endif
1045
    /* DO NOT SEND CREDENTIALS! */
1046
0
    goto fail;
1047
0
  }
1048
1049
0
  status = TRUE;
1050
0
fail:
1051
0
  sspi_SecBufferFree(&public_key);
1052
0
  return status;
1053
0
}
1054
1055
BOOL nla_decrypt_public_key_hash(rdpNla* nla)
1056
0
{
1057
0
  WINPR_DIGEST_CTX* sha256 = NULL;
1058
0
  BYTE serverClientHash[WINPR_SHA256_DIGEST_LENGTH] = { 0 };
1059
0
  BOOL status = FALSE;
1060
1061
0
  WINPR_ASSERT(nla);
1062
1063
0
  const BYTE* hashMagic = nla->server ? ClientServerHashMagic : ServerClientHashMagic;
1064
0
  const size_t hashSize =
1065
0
      nla->server ? sizeof(ClientServerHashMagic) : sizeof(ServerClientHashMagic);
1066
0
  SecBuffer hash = { 0 };
1067
1068
0
  if (!credssp_auth_decrypt(nla->auth, &nla->pubKeyAuth, &hash, nla->recvSeqNum++))
1069
0
    return FALSE;
1070
1071
  /* generate SHA256 of following data: ServerClientHashMagic, Nonce, SubjectPublicKey */
1072
0
  if (!(sha256 = winpr_Digest_New()))
1073
0
    goto fail;
1074
1075
0
  if (!winpr_Digest_Init(sha256, WINPR_MD_SHA256))
1076
0
    goto fail;
1077
1078
  /* include trailing \0 from hashMagic */
1079
0
  if (!winpr_Digest_Update(sha256, hashMagic, hashSize))
1080
0
    goto fail;
1081
1082
0
  if (!nla_Digest_Update_From_SecBuffer(sha256, &nla->ClientNonce))
1083
0
    goto fail;
1084
1085
  /* SubjectPublicKey */
1086
0
  if (!nla_Digest_Update_From_SecBuffer(sha256, &nla->PublicKey))
1087
0
    goto fail;
1088
1089
0
  if (!winpr_Digest_Final(sha256, serverClientHash, sizeof(serverClientHash)))
1090
0
    goto fail;
1091
1092
  /* verify hash */
1093
0
  if (hash.cbBuffer != WINPR_SHA256_DIGEST_LENGTH ||
1094
0
      memcmp(serverClientHash, hash.pvBuffer, WINPR_SHA256_DIGEST_LENGTH) != 0)
1095
0
  {
1096
0
    WLog_ERR(TAG, "Could not verify server's hash");
1097
    /* DO NOT SEND CREDENTIALS! */
1098
0
    goto fail;
1099
0
  }
1100
1101
0
  status = TRUE;
1102
0
fail:
1103
0
  winpr_Digest_Free(sha256);
1104
0
  sspi_SecBufferFree(&hash);
1105
0
  return status;
1106
0
}
1107
1108
static BOOL set_creds_octetstring_to_settings(WinPrAsn1Decoder* dec, WinPrAsn1_tagId tagId,
1109
                                              BOOL optional, FreeRDP_Settings_Keys_String settingId,
1110
                                              rdpSettings* settings)
1111
0
{
1112
0
  if (optional)
1113
0
  {
1114
0
    WinPrAsn1_tagId itemTag = 0;
1115
0
    if (!WinPrAsn1DecPeekTag(dec, &itemTag) || (itemTag != tagId))
1116
0
      return TRUE;
1117
0
  }
1118
1119
0
  BOOL error = FALSE;
1120
0
  WinPrAsn1_OctetString value;
1121
  /* note: not checking "error" value, as the not present optional item case is handled above
1122
   *       if the function fails it's because of a real error not because the item is not present
1123
   */
1124
0
  if (!WinPrAsn1DecReadContextualOctetString(dec, tagId, &error, &value, FALSE))
1125
0
    return FALSE;
1126
1127
0
  return freerdp_settings_set_string_from_utf16N(settings, settingId, (const WCHAR*)value.data,
1128
0
                                                 value.len / sizeof(WCHAR));
1129
0
}
1130
1131
static BOOL nla_read_TSCspDataDetail(WinPrAsn1Decoder* dec, rdpSettings* settings)
1132
0
{
1133
0
  BOOL error = FALSE;
1134
1135
  /* keySpec [0] INTEGER */
1136
0
  WinPrAsn1_INTEGER keyspec = 0;
1137
0
  if (!WinPrAsn1DecReadContextualInteger(dec, 0, &error, &keyspec))
1138
0
    return FALSE;
1139
0
  settings->KeySpec = (UINT32)keyspec;
1140
1141
  /* cardName [1] OCTET STRING OPTIONAL */
1142
0
  if (!set_creds_octetstring_to_settings(dec, 1, TRUE, FreeRDP_CardName, settings))
1143
0
    return FALSE;
1144
1145
  /* readerName [2] OCTET STRING OPTIONAL */
1146
0
  if (!set_creds_octetstring_to_settings(dec, 2, TRUE, FreeRDP_ReaderName, settings))
1147
0
    return FALSE;
1148
1149
  /* containerName [3] OCTET STRING OPTIONAL */
1150
0
  if (!set_creds_octetstring_to_settings(dec, 3, TRUE, FreeRDP_ContainerName, settings))
1151
0
    return FALSE;
1152
1153
  /* cspName [4] OCTET STRING OPTIONAL */
1154
0
  return set_creds_octetstring_to_settings(dec, 4, TRUE, FreeRDP_CspName, settings);
1155
0
}
1156
1157
static BOOL nla_read_KERB_TICKET_LOGON(WINPR_ATTR_UNUSED rdpNla* nla, wStream* s,
1158
                                       KERB_TICKET_LOGON* ticket)
1159
0
{
1160
0
  WINPR_ASSERT(nla);
1161
1162
0
  if (!ticket)
1163
0
    return FALSE;
1164
1165
  /* mysterious extra 16 bytes before TGS/TGT content */
1166
0
  if (!Stream_CheckAndLogRequiredLength(TAG, s, 16 + 16))
1167
0
    return FALSE;
1168
1169
0
  Stream_Read_UINT32(s, ticket->MessageType);
1170
0
  Stream_Read_UINT32(s, ticket->Flags);
1171
0
  Stream_Read_UINT32(s, ticket->ServiceTicketLength);
1172
0
  Stream_Read_UINT32(s, ticket->TicketGrantingTicketLength);
1173
1174
0
  if (ticket->MessageType != KerbTicketLogon)
1175
0
  {
1176
0
    WLog_ERR(TAG, "Not a KerbTicketLogon");
1177
0
    return FALSE;
1178
0
  }
1179
1180
0
  if (!Stream_CheckAndLogRequiredLength(
1181
0
          TAG, s, 16ull + ticket->ServiceTicketLength + ticket->TicketGrantingTicketLength))
1182
0
    return FALSE;
1183
1184
  /* mysterious 16 bytes in the way, maybe they would need to be interpreted... */
1185
0
  Stream_Seek(s, 16);
1186
1187
  /*WLog_INFO(TAG, "TGS");
1188
  winpr_HexDump(TAG, WLOG_DEBUG, Stream_PointerAs(s, const BYTE), ticket->ServiceTicketLength);*/
1189
0
  ticket->ServiceTicket = Stream_PointerAs(s, UCHAR);
1190
0
  Stream_Seek(s, ticket->ServiceTicketLength);
1191
1192
  /*WLog_INFO(TAG, "TGT");
1193
  winpr_HexDump(TAG, WLOG_DEBUG, Stream_PointerAs(s, const BYTE),
1194
                ticket->TicketGrantingTicketLength);*/
1195
0
  ticket->TicketGrantingTicket = Stream_PointerAs(s, UCHAR);
1196
0
  return TRUE;
1197
0
}
1198
1199
/** @brief kind of RCG credentials */
1200
typedef enum
1201
{
1202
  RCG_TYPE_NONE,
1203
  RCG_TYPE_KERB,
1204
  RCG_TYPE_NTLM
1205
} RemoteGuardPackageCredType;
1206
1207
static BOOL nla_read_TSRemoteGuardPackageCred(WINPR_ATTR_UNUSED rdpNla* nla, WinPrAsn1Decoder* dec,
1208
                                              RemoteGuardPackageCredType* credsType,
1209
                                              wStream* payload)
1210
0
{
1211
0
  WinPrAsn1_OctetString packageName = { 0 };
1212
0
  WinPrAsn1_OctetString credBuffer = { 0 };
1213
0
  BOOL error = FALSE;
1214
0
  char packageNameStr[100] = { 0 };
1215
1216
0
  WINPR_ASSERT(nla);
1217
0
  WINPR_ASSERT(dec);
1218
0
  WINPR_ASSERT(credsType);
1219
0
  WINPR_ASSERT(payload);
1220
1221
0
  *credsType = RCG_TYPE_NONE;
1222
1223
  /* packageName [0] OCTET STRING */
1224
0
  if (!WinPrAsn1DecReadContextualOctetString(dec, 0, &error, &packageName, FALSE) || error)
1225
0
    return FALSE;
1226
1227
0
  ConvertMszWCharNToUtf8((WCHAR*)packageName.data, packageName.len / sizeof(WCHAR),
1228
0
                         packageNameStr, sizeof(packageNameStr));
1229
0
  WLog_DBG(TAG, "TSRemoteGuardPackageCred(%s)", packageNameStr);
1230
1231
  /* credBuffer [1] OCTET STRING, */
1232
0
  if (!WinPrAsn1DecReadContextualOctetString(dec, 1, &error, &credBuffer, FALSE) || error)
1233
0
    return FALSE;
1234
1235
0
  if (_stricmp(packageNameStr, "Kerberos") == 0)
1236
0
  {
1237
0
    *credsType = RCG_TYPE_KERB;
1238
0
  }
1239
0
  else if (_stricmp(packageNameStr, "NTLM") == 0)
1240
0
  {
1241
0
    *credsType = RCG_TYPE_NTLM;
1242
0
  }
1243
0
  else
1244
0
  {
1245
0
    WLog_INFO(TAG, "TSRemoteGuardPackageCred package %s not handled", packageNameStr);
1246
0
    return FALSE;
1247
0
  }
1248
1249
0
  Stream_StaticInit(payload, credBuffer.data, credBuffer.len);
1250
0
  return TRUE;
1251
0
}
1252
1253
/** @brief kind of TSCreds */
1254
typedef enum
1255
{
1256
  TSCREDS_INVALID = 0,
1257
  TSCREDS_USER_PASSWD = 1,
1258
  TSCREDS_SMARTCARD = 2,
1259
  TSCREDS_REMOTEGUARD = 6
1260
} TsCredentialsType;
1261
1262
static BOOL nla_read_ts_credentials(rdpNla* nla, SecBuffer* data)
1263
0
{
1264
0
  WinPrAsn1Decoder dec = { 0 };
1265
0
  WinPrAsn1Decoder dec2 = { 0 };
1266
0
  WinPrAsn1_OctetString credentials = { 0 };
1267
0
  BOOL error = FALSE;
1268
0
  WinPrAsn1_INTEGER credType = -1;
1269
0
  BOOL ret = TRUE;
1270
1271
0
  WINPR_ASSERT(nla);
1272
0
  WINPR_ASSERT(data);
1273
1274
0
  WinPrAsn1Decoder_InitMem(&dec, WINPR_ASN1_DER, (BYTE*)data->pvBuffer, data->cbBuffer);
1275
1276
  /* TSCredentials */
1277
0
  if (!WinPrAsn1DecReadSequence(&dec, &dec2))
1278
0
    return FALSE;
1279
0
  dec = dec2;
1280
1281
  /* credType [0] INTEGER */
1282
0
  if (!WinPrAsn1DecReadContextualInteger(&dec, 0, &error, &credType))
1283
0
    return FALSE;
1284
1285
  /* credentials [1] OCTET STRING */
1286
0
  if (!WinPrAsn1DecReadContextualOctetString(&dec, 1, &error, &credentials, FALSE))
1287
0
    return FALSE;
1288
1289
0
  WinPrAsn1Decoder_InitMem(&dec, WINPR_ASN1_DER, credentials.data, credentials.len);
1290
1291
0
  rdpSettings* settings = nla->rdpcontext->settings;
1292
0
  if (nego_get_remoteCredentialGuard(nla->rdpcontext->rdp->nego) &&
1293
0
      credType != TSCREDS_REMOTEGUARD)
1294
0
  {
1295
0
    WLog_ERR(TAG, "connecting with RCG but it's not TSRemoteGuard credentials");
1296
0
    return FALSE;
1297
0
  }
1298
1299
0
  switch (credType)
1300
0
  {
1301
0
    case TSCREDS_USER_PASSWD:
1302
0
    {
1303
      /* TSPasswordCreds */
1304
0
      if (!WinPrAsn1DecReadSequence(&dec, &dec2))
1305
0
        return FALSE;
1306
0
      dec = dec2;
1307
1308
      /* domainName [0] OCTET STRING */
1309
0
      if (!set_creds_octetstring_to_settings(&dec, 0, FALSE, FreeRDP_Domain, settings))
1310
0
        return FALSE;
1311
1312
      /* userName [1] OCTET STRING */
1313
0
      if (!set_creds_octetstring_to_settings(&dec, 1, FALSE, FreeRDP_Username, settings))
1314
0
        return FALSE;
1315
1316
      /* password [2] OCTET STRING */
1317
0
      return set_creds_octetstring_to_settings(&dec, 2, FALSE, FreeRDP_Password, settings);
1318
0
    }
1319
0
    case TSCREDS_SMARTCARD:
1320
0
    {
1321
      /* TSSmartCardCreds */
1322
0
      if (!WinPrAsn1DecReadSequence(&dec, &dec2))
1323
0
        return FALSE;
1324
0
      dec = dec2;
1325
1326
      /* pin [0] OCTET STRING, */
1327
0
      if (!set_creds_octetstring_to_settings(&dec, 0, FALSE, FreeRDP_Password, settings))
1328
0
        return FALSE;
1329
0
      settings->PasswordIsSmartcardPin = TRUE;
1330
1331
      /* cspData [1] TSCspDataDetail */
1332
0
      WinPrAsn1Decoder cspDetails = { 0 };
1333
0
      if (!WinPrAsn1DecReadContextualSequence(&dec, 1, &error, &cspDetails) && error)
1334
0
        return FALSE;
1335
0
      if (!nla_read_TSCspDataDetail(&cspDetails, settings))
1336
0
        return FALSE;
1337
1338
      /* userHint [2] OCTET STRING OPTIONAL */
1339
0
      if (!set_creds_octetstring_to_settings(&dec, 2, TRUE, FreeRDP_Username, settings))
1340
0
        return FALSE;
1341
1342
      /* domainHint [3] OCTET STRING OPTIONAL */
1343
0
      return set_creds_octetstring_to_settings(&dec, 3, TRUE, FreeRDP_Domain, settings);
1344
0
    }
1345
0
    case TSCREDS_REMOTEGUARD:
1346
0
    {
1347
      /* TSRemoteGuardCreds */
1348
0
      if (!WinPrAsn1DecReadSequence(&dec, &dec2))
1349
0
        return FALSE;
1350
1351
      /* logonCred[0] TSRemoteGuardPackageCred */
1352
0
      KERB_TICKET_LOGON kerbLogon = { 0 };
1353
0
      WinPrAsn1Decoder logonCredsSeq = { 0 };
1354
0
      if (!WinPrAsn1DecReadContextualSequence(&dec2, 0, &error, &logonCredsSeq) || error)
1355
0
        return FALSE;
1356
1357
0
      RemoteGuardPackageCredType logonCredsType = RCG_TYPE_NONE;
1358
0
      wStream logonPayload = { 0 };
1359
0
      if (!nla_read_TSRemoteGuardPackageCred(nla, &logonCredsSeq, &logonCredsType,
1360
0
                                             &logonPayload))
1361
0
        return FALSE;
1362
0
      if (logonCredsType != RCG_TYPE_KERB)
1363
0
      {
1364
0
        WLog_ERR(TAG, "logonCred must be some Kerberos creds");
1365
0
        return FALSE;
1366
0
      }
1367
1368
0
      if (!nla_read_KERB_TICKET_LOGON(nla, &logonPayload, &kerbLogon))
1369
0
      {
1370
0
        WLog_ERR(TAG, "invalid KERB_TICKET_LOGON");
1371
0
        return FALSE;
1372
0
      }
1373
1374
      /* supplementalCreds [1] SEQUENCE OF TSRemoteGuardPackageCred OPTIONAL, */
1375
0
      MSV1_0_SUPPLEMENTAL_CREDENTIAL* suppCreds = NULL;
1376
0
      WinPrAsn1Decoder suppCredsSeq = { 0 };
1377
1378
0
      if (WinPrAsn1DecReadContextualSequence(&dec2, 1, &error, &suppCredsSeq))
1379
0
      {
1380
0
        WinPrAsn1Decoder ntlmCredsSeq = { 0 };
1381
0
        if (!WinPrAsn1DecReadSequence(&suppCredsSeq, &ntlmCredsSeq))
1382
0
          return FALSE;
1383
1384
0
        RemoteGuardPackageCredType suppCredsType = { 0 };
1385
0
        wStream ntlmPayload = { 0 };
1386
0
        if (!nla_read_TSRemoteGuardPackageCred(nla, &ntlmCredsSeq, &suppCredsType,
1387
0
                                               &ntlmPayload))
1388
0
          return FALSE;
1389
1390
0
        if (suppCredsType != RCG_TYPE_NTLM)
1391
0
        {
1392
0
          WLog_ERR(TAG, "supplementalCreds must be some NTLM creds");
1393
0
          return FALSE;
1394
0
        }
1395
1396
        /* TODO: suppCreds = &ntlmCreds; and parse NTLM creds */
1397
0
      }
1398
0
      else if (error)
1399
0
      {
1400
0
        WLog_ERR(TAG, "invalid supplementalCreds");
1401
0
        return FALSE;
1402
0
      }
1403
1404
0
      freerdp_peer* peer = nla->rdpcontext->peer;
1405
0
      ret = IFCALLRESULT(TRUE, peer->RemoteCredentials, peer, &kerbLogon, suppCreds);
1406
0
      break;
1407
0
    }
1408
0
    default:
1409
0
      WLog_DBG(TAG, "TSCredentials type " PRIu32 " not supported for now", credType);
1410
0
      ret = FALSE;
1411
0
      break;
1412
0
  }
1413
1414
0
  return ret;
1415
0
}
1416
1417
static BOOL nla_write_KERB_TICKET_LOGON(wStream* s, const KERB_TICKET_LOGON* ticket)
1418
0
{
1419
0
  WINPR_ASSERT(ticket);
1420
1421
0
  if (!Stream_EnsureRemainingCapacity(s, (4ULL * 4) + 16ULL + ticket->ServiceTicketLength +
1422
0
                                             ticket->TicketGrantingTicketLength))
1423
0
    return FALSE;
1424
1425
0
  Stream_Write_UINT32(s, KerbTicketLogon);
1426
0
  Stream_Write_UINT32(s, ticket->Flags);
1427
0
  Stream_Write_UINT32(s, ticket->ServiceTicketLength);
1428
0
  Stream_Write_UINT32(s, ticket->TicketGrantingTicketLength);
1429
1430
0
  Stream_Write_UINT64(s, 0x20);                               /* offset of TGS in the packet */
1431
0
  Stream_Write_UINT64(s, 0x20 + ticket->ServiceTicketLength); /* offset of TGT in packet */
1432
1433
0
  Stream_Write(s, ticket->ServiceTicket, ticket->ServiceTicketLength);
1434
0
  Stream_Write(s, ticket->TicketGrantingTicket, ticket->TicketGrantingTicketLength);
1435
0
  return TRUE;
1436
0
}
1437
1438
static BOOL nla_get_KERB_TICKET_LOGON(rdpNla* nla, KERB_TICKET_LOGON* logonTicket)
1439
0
{
1440
0
  WINPR_ASSERT(nla);
1441
0
  WINPR_ASSERT(logonTicket);
1442
1443
0
  SecurityFunctionTable* table = NULL;
1444
0
  CtxtHandle context = { 0 };
1445
0
  credssp_auth_tableAndContext(nla->auth, &table, &context);
1446
0
  return table->QueryContextAttributes(&context, SECPKG_CRED_ATTR_TICKET_LOGON, logonTicket) ==
1447
0
         SEC_E_OK;
1448
0
}
1449
1450
static BOOL nla_write_TSRemoteGuardKerbCred(rdpNla* nla, WinPrAsn1Encoder* enc)
1451
0
{
1452
0
  BOOL ret = FALSE;
1453
0
  wStream* s = NULL;
1454
0
  char kerberos[] = { 'K', '\0', 'e', '\0', 'r', '\0', 'b', '\0',
1455
0
                    'e', '\0', 'r', '\0', 'o', '\0', 's', '\0' };
1456
0
  WinPrAsn1_OctetString packageName = { sizeof(kerberos), (BYTE*)kerberos };
1457
0
  WinPrAsn1_OctetString credBuffer;
1458
0
  KERB_TICKET_LOGON logonTicket;
1459
1460
0
  logonTicket.ServiceTicket = NULL;
1461
0
  logonTicket.TicketGrantingTicket = NULL;
1462
1463
  /* packageName [0] OCTET STRING */
1464
0
  if (!WinPrAsn1EncContextualOctetString(enc, 0, &packageName))
1465
0
    goto out;
1466
1467
  /* credBuffer [1] OCTET STRING */
1468
0
  if (!nla_get_KERB_TICKET_LOGON(nla, &logonTicket))
1469
0
    goto out;
1470
1471
0
  s = Stream_New(NULL, 2000);
1472
0
  if (!s)
1473
0
    goto out;
1474
1475
0
  if (!nla_write_KERB_TICKET_LOGON(s, &logonTicket))
1476
0
    goto out;
1477
1478
0
  credBuffer.len = Stream_GetPosition(s);
1479
0
  credBuffer.data = Stream_Buffer(s);
1480
0
  ret = WinPrAsn1EncContextualOctetString(enc, 1, &credBuffer) != 0;
1481
1482
0
out:
1483
0
  free(logonTicket.ServiceTicket);
1484
0
  free(logonTicket.TicketGrantingTicket);
1485
0
  Stream_Free(s, TRUE);
1486
0
  return ret;
1487
0
}
1488
1489
/**
1490
 * Encode TSCredentials structure.
1491
 * @param nla A pointer to the NLA to use
1492
 *
1493
 * @return \b TRUE for success, \b FALSE otherwise
1494
 */
1495
1496
static BOOL nla_encode_ts_credentials(rdpNla* nla)
1497
0
{
1498
0
  BOOL ret = FALSE;
1499
0
  WinPrAsn1Encoder* enc = NULL;
1500
0
  size_t length = 0;
1501
0
  wStream s = { 0 };
1502
0
  TsCredentialsType credType = TSCREDS_INVALID;
1503
1504
0
  WINPR_ASSERT(nla);
1505
0
  WINPR_ASSERT(nla->rdpcontext);
1506
1507
0
  rdpSettings* settings = nla->rdpcontext->settings;
1508
0
  WINPR_ASSERT(settings);
1509
1510
0
  if (settings->RemoteCredentialGuard)
1511
0
    credType = TSCREDS_REMOTEGUARD;
1512
0
  else if (settings->SmartcardLogon)
1513
0
    credType = TSCREDS_SMARTCARD;
1514
0
  else
1515
0
    credType = TSCREDS_USER_PASSWD;
1516
1517
0
  enc = WinPrAsn1Encoder_New(WINPR_ASN1_DER);
1518
0
  if (!enc)
1519
0
    return FALSE;
1520
1521
  /* TSCredentials */
1522
0
  if (!WinPrAsn1EncSeqContainer(enc))
1523
0
    goto out;
1524
1525
  /* credType [0] INTEGER */
1526
0
  if (!WinPrAsn1EncContextualInteger(enc, 0, (WinPrAsn1_INTEGER)credType))
1527
0
    goto out;
1528
1529
  /* credentials [1] OCTET STRING */
1530
0
  if (!WinPrAsn1EncContextualOctetStringContainer(enc, 1))
1531
0
    goto out;
1532
1533
0
  switch (credType)
1534
0
  {
1535
0
    case TSCREDS_SMARTCARD:
1536
0
    {
1537
0
      struct
1538
0
      {
1539
0
        WinPrAsn1_tagId tag;
1540
0
        FreeRDP_Settings_Keys_String setting_id;
1541
0
      } cspData_fields[] = { { 1, FreeRDP_CardName },
1542
0
                           { 2, FreeRDP_ReaderName },
1543
0
                           { 3, FreeRDP_ContainerName },
1544
0
                           { 4, FreeRDP_CspName } };
1545
0
      WinPrAsn1_OctetString octet_string = { 0 };
1546
1547
      /* TSSmartCardCreds */
1548
0
      if (!WinPrAsn1EncSeqContainer(enc))
1549
0
        goto out;
1550
1551
      /* pin [0] OCTET STRING */
1552
0
      size_t ss = 0;
1553
0
      octet_string.data =
1554
0
          (BYTE*)freerdp_settings_get_string_as_utf16(settings, FreeRDP_Password, &ss);
1555
0
      octet_string.len = ss * sizeof(WCHAR);
1556
0
      BOOL res = WinPrAsn1EncContextualOctetString(enc, 0, &octet_string) > 0;
1557
0
      free(octet_string.data);
1558
0
      if (!res)
1559
0
        goto out;
1560
1561
      /* cspData [1] SEQUENCE */
1562
0
      if (!WinPrAsn1EncContextualSeqContainer(enc, 1))
1563
0
        goto out;
1564
1565
      /* keySpec [0] INTEGER */
1566
0
      if (!WinPrAsn1EncContextualInteger(
1567
0
              enc, 0,
1568
0
              WINPR_ASSERTING_INT_CAST(
1569
0
                  WinPrAsn1_INTEGER, freerdp_settings_get_uint32(settings, FreeRDP_KeySpec))))
1570
0
        goto out;
1571
1572
0
      for (size_t i = 0; i < ARRAYSIZE(cspData_fields); i++)
1573
0
      {
1574
0
        size_t len = 0;
1575
1576
0
        octet_string.data = (BYTE*)freerdp_settings_get_string_as_utf16(
1577
0
            settings, cspData_fields[i].setting_id, &len);
1578
0
        octet_string.len = len * sizeof(WCHAR);
1579
0
        if (octet_string.len)
1580
0
        {
1581
0
          const BOOL res2 = WinPrAsn1EncContextualOctetString(enc, cspData_fields[i].tag,
1582
0
                                                              &octet_string) > 0;
1583
0
          free(octet_string.data);
1584
0
          if (!res2)
1585
0
            goto out;
1586
0
        }
1587
0
      }
1588
1589
      /* End cspData */
1590
0
      if (!WinPrAsn1EncEndContainer(enc))
1591
0
        goto out;
1592
1593
      /* userHint [2] OCTET STRING OPTIONAL, */
1594
0
      if (freerdp_settings_get_string(settings, FreeRDP_Username))
1595
0
      {
1596
0
        octet_string.data =
1597
0
            (BYTE*)freerdp_settings_get_string_as_utf16(settings, FreeRDP_Username, &ss);
1598
0
        octet_string.len = ss * sizeof(WCHAR);
1599
0
        res = WinPrAsn1EncContextualOctetString(enc, 2, &octet_string) > 0;
1600
0
        free(octet_string.data);
1601
0
        if (!res)
1602
0
          goto out;
1603
0
      }
1604
1605
      /* domainHint [3] OCTET STRING OPTIONAL */
1606
0
      if (freerdp_settings_get_string(settings, FreeRDP_Domain))
1607
0
      {
1608
0
        octet_string.data =
1609
0
            (BYTE*)freerdp_settings_get_string_as_utf16(settings, FreeRDP_Domain, &ss);
1610
0
        octet_string.len = ss * sizeof(WCHAR);
1611
0
        res = WinPrAsn1EncContextualOctetString(enc, 3, &octet_string) > 0;
1612
0
        free(octet_string.data);
1613
0
        if (!res)
1614
0
          goto out;
1615
0
      }
1616
1617
      /* End TSSmartCardCreds */
1618
0
      if (!WinPrAsn1EncEndContainer(enc))
1619
0
        goto out;
1620
0
      break;
1621
0
    }
1622
0
    case TSCREDS_USER_PASSWD:
1623
0
    {
1624
0
      WinPrAsn1_OctetString username = { 0 };
1625
0
      WinPrAsn1_OctetString domain = { 0 };
1626
0
      WinPrAsn1_OctetString password = { 0 };
1627
1628
      /* TSPasswordCreds */
1629
0
      if (!WinPrAsn1EncSeqContainer(enc))
1630
0
        goto out;
1631
1632
0
      if (!settings->DisableCredentialsDelegation && nla->identity)
1633
0
      {
1634
0
        username.len = nla->identity->UserLength * sizeof(WCHAR);
1635
0
        username.data = (BYTE*)nla->identity->User;
1636
1637
0
        domain.len = nla->identity->DomainLength * sizeof(WCHAR);
1638
0
        domain.data = (BYTE*)nla->identity->Domain;
1639
1640
0
        password.len = nla->identity->PasswordLength * sizeof(WCHAR);
1641
0
        password.data = (BYTE*)nla->identity->Password;
1642
0
      }
1643
1644
0
      if (WinPrAsn1EncContextualOctetString(enc, 0, &domain) == 0)
1645
0
        goto out;
1646
0
      if (WinPrAsn1EncContextualOctetString(enc, 1, &username) == 0)
1647
0
        goto out;
1648
0
      if (WinPrAsn1EncContextualOctetString(enc, 2, &password) == 0)
1649
0
        goto out;
1650
1651
      /* End TSPasswordCreds */
1652
0
      if (!WinPrAsn1EncEndContainer(enc))
1653
0
        goto out;
1654
0
      break;
1655
0
    }
1656
0
    case TSCREDS_REMOTEGUARD:
1657
      /* TSRemoteGuardCreds */
1658
0
      if (!WinPrAsn1EncSeqContainer(enc))
1659
0
        goto out;
1660
1661
      /* logonCred [0] TSRemoteGuardPackageCred, */
1662
0
      if (!WinPrAsn1EncContextualSeqContainer(enc, 0))
1663
0
        goto out;
1664
1665
0
      if (!nla_write_TSRemoteGuardKerbCred(nla, enc) || !WinPrAsn1EncEndContainer(enc))
1666
0
        goto out;
1667
1668
      /* supplementalCreds [1] SEQUENCE OF TSRemoteGuardPackageCred OPTIONAL,
1669
       *
1670
       * no NTLM supplemental creds for now
1671
       *
1672
       */
1673
0
      if (!WinPrAsn1EncContextualSeqContainer(enc, 1) || !WinPrAsn1EncEndContainer(enc))
1674
0
        goto out;
1675
1676
      /* End TSRemoteGuardCreds */
1677
0
      if (!WinPrAsn1EncEndContainer(enc))
1678
0
        goto out;
1679
0
      break;
1680
0
    default:
1681
0
      goto out;
1682
0
  }
1683
1684
  /* End credentials | End TSCredentials */
1685
0
  if (!WinPrAsn1EncEndContainer(enc) || !WinPrAsn1EncEndContainer(enc))
1686
0
    goto out;
1687
1688
0
  if (!WinPrAsn1EncStreamSize(enc, &length))
1689
0
    goto out;
1690
1691
0
  if (!nla_sec_buffer_alloc(&nla->tsCredentials, length))
1692
0
  {
1693
0
    WLog_ERR(TAG, "sspi_SecBufferAlloc failed!");
1694
0
    goto out;
1695
0
  }
1696
1697
0
  Stream_StaticInit(&s, (BYTE*)nla->tsCredentials.pvBuffer, length);
1698
1699
0
  ret = WinPrAsn1EncToStream(enc, &s);
1700
1701
0
out:
1702
0
  WinPrAsn1Encoder_Free(&enc);
1703
0
  return ret;
1704
0
}
1705
1706
static BOOL nla_encrypt_ts_credentials(rdpNla* nla)
1707
0
{
1708
0
  WINPR_ASSERT(nla);
1709
1710
0
  if (!nla_encode_ts_credentials(nla))
1711
0
    return FALSE;
1712
1713
0
  sspi_SecBufferFree(&nla->authInfo);
1714
0
  if (!credssp_auth_encrypt(nla->auth, &nla->tsCredentials, &nla->authInfo, NULL,
1715
0
                            nla->sendSeqNum++))
1716
0
    return FALSE;
1717
1718
0
  return TRUE;
1719
0
}
1720
1721
static BOOL nla_decrypt_ts_credentials(rdpNla* nla)
1722
0
{
1723
0
  WINPR_ASSERT(nla);
1724
1725
0
  if (nla->authInfo.cbBuffer < 1)
1726
0
  {
1727
0
    WLog_ERR(TAG, "nla_decrypt_ts_credentials missing authInfo buffer");
1728
0
    return FALSE;
1729
0
  }
1730
1731
0
  sspi_SecBufferFree(&nla->tsCredentials);
1732
0
  if (!credssp_auth_decrypt(nla->auth, &nla->authInfo, &nla->tsCredentials, nla->recvSeqNum++))
1733
0
    return FALSE;
1734
1735
0
  if (!nla_read_ts_credentials(nla, &nla->tsCredentials))
1736
0
    return FALSE;
1737
1738
0
  return TRUE;
1739
0
}
1740
1741
static BOOL nla_write_octet_string(WinPrAsn1Encoder* enc, const SecBuffer* buffer,
1742
                                   WinPrAsn1_tagId tagId, const char* msg)
1743
0
{
1744
0
  BOOL res = FALSE;
1745
1746
0
  WINPR_ASSERT(enc);
1747
0
  WINPR_ASSERT(buffer);
1748
0
  WINPR_ASSERT(msg);
1749
1750
0
  if (buffer->cbBuffer > 0)
1751
0
  {
1752
0
    size_t rc = 0;
1753
0
    WinPrAsn1_OctetString octet_string = { 0 };
1754
1755
0
    WLog_DBG(TAG, "   ----->> %s", msg);
1756
0
    octet_string.data = buffer->pvBuffer;
1757
0
    octet_string.len = buffer->cbBuffer;
1758
0
    rc = WinPrAsn1EncContextualOctetString(enc, tagId, &octet_string);
1759
0
    if (rc != 0)
1760
0
      res = TRUE;
1761
0
  }
1762
1763
0
  return res;
1764
0
}
1765
1766
static BOOL nla_write_octet_string_free(WinPrAsn1Encoder* enc, SecBuffer* buffer,
1767
                                        WinPrAsn1_tagId tagId, const char* msg)
1768
0
{
1769
0
  const BOOL rc = nla_write_octet_string(enc, buffer, tagId, msg);
1770
0
  sspi_SecBufferFree(buffer);
1771
0
  return rc;
1772
0
}
1773
1774
/**
1775
 * Send CredSSP message.
1776
 *
1777
 * @param nla A pointer to the NLA to use
1778
 *
1779
 * @return \b TRUE for success, \b FALSE otherwise
1780
 */
1781
1782
BOOL nla_send(rdpNla* nla)
1783
0
{
1784
0
  BOOL rc = FALSE;
1785
0
  wStream* s = NULL;
1786
0
  size_t length = 0;
1787
0
  WinPrAsn1Encoder* enc = NULL;
1788
1789
0
  WINPR_ASSERT(nla);
1790
1791
0
  enc = WinPrAsn1Encoder_New(WINPR_ASN1_DER);
1792
0
  if (!enc)
1793
0
    return FALSE;
1794
1795
  /* TSRequest */
1796
0
  WLog_DBG(TAG, "----->> sending...");
1797
0
  if (!WinPrAsn1EncSeqContainer(enc))
1798
0
    goto fail;
1799
1800
  /* version [0] INTEGER */
1801
0
  WLog_DBG(TAG, "   ----->> protocol version %" PRIu32, nla->version);
1802
0
  if (!WinPrAsn1EncContextualInteger(enc, 0,
1803
0
                                     WINPR_ASSERTING_INT_CAST(WinPrAsn1_INTEGER, nla->version)))
1804
0
    goto fail;
1805
1806
  /* negoTokens [1] SEQUENCE OF SEQUENCE */
1807
0
  if (nla_get_state(nla) <= NLA_STATE_NEGO_TOKEN && credssp_auth_have_output_token(nla->auth))
1808
0
  {
1809
0
    const SecBuffer* buffer = credssp_auth_get_output_buffer(nla->auth);
1810
1811
0
    if (!WinPrAsn1EncContextualSeqContainer(enc, 1) || !WinPrAsn1EncSeqContainer(enc))
1812
0
      goto fail;
1813
1814
    /* negoToken [0] OCTET STRING */
1815
0
    if (!nla_write_octet_string(enc, buffer, 0, "negoToken"))
1816
0
      goto fail;
1817
1818
    /* End negoTokens (SEQUENCE OF SEQUENCE) */
1819
0
    if (!WinPrAsn1EncEndContainer(enc) || !WinPrAsn1EncEndContainer(enc))
1820
0
      goto fail;
1821
0
  }
1822
1823
  /* authInfo [2] OCTET STRING */
1824
0
  if (nla->authInfo.cbBuffer > 0)
1825
0
  {
1826
0
    if (!nla_write_octet_string_free(enc, &nla->authInfo, 2, "auth info"))
1827
0
      goto fail;
1828
0
  }
1829
1830
  /* pubKeyAuth [3] OCTET STRING */
1831
0
  if (nla->pubKeyAuth.cbBuffer > 0)
1832
0
  {
1833
0
    if (!nla_write_octet_string_free(enc, &nla->pubKeyAuth, 3, "public key auth"))
1834
0
      goto fail;
1835
0
  }
1836
1837
  /* errorCode [4] INTEGER */
1838
0
  if (nla->errorCode && nla->peerVersion >= 3 && nla->peerVersion != 5)
1839
0
  {
1840
0
    WLog_DBG(TAG, "   ----->> error code %s 0x%08" PRIx32, NtStatus2Tag(nla->errorCode),
1841
0
             nla->errorCode);
1842
0
    if (!WinPrAsn1EncContextualInteger(
1843
0
            enc, 4, WINPR_ASSERTING_INT_CAST(WinPrAsn1_INTEGER, nla->errorCode)))
1844
0
      goto fail;
1845
0
  }
1846
1847
  /* clientNonce [5] OCTET STRING */
1848
0
  if (!nla->server && nla->ClientNonce.cbBuffer > 0)
1849
0
  {
1850
0
    if (!nla_write_octet_string(enc, &nla->ClientNonce, 5, "client nonce"))
1851
0
      goto fail;
1852
0
  }
1853
1854
  /* End TSRequest */
1855
0
  if (!WinPrAsn1EncEndContainer(enc))
1856
0
    goto fail;
1857
1858
0
  if (!WinPrAsn1EncStreamSize(enc, &length))
1859
0
    goto fail;
1860
1861
0
  s = Stream_New(NULL, length);
1862
0
  if (!s)
1863
0
    goto fail;
1864
1865
0
  if (!WinPrAsn1EncToStream(enc, s))
1866
0
    goto fail;
1867
1868
0
  WLog_DBG(TAG, "[%" PRIuz " bytes]", length);
1869
0
  if (transport_write(nla->transport, s) < 0)
1870
0
    goto fail;
1871
0
  rc = TRUE;
1872
1873
0
fail:
1874
0
  Stream_Free(s, TRUE);
1875
0
  WinPrAsn1Encoder_Free(&enc);
1876
0
  return rc;
1877
0
}
1878
1879
static int nla_decode_ts_request(rdpNla* nla, wStream* s)
1880
0
{
1881
0
  WinPrAsn1Decoder dec = { 0 };
1882
0
  WinPrAsn1Decoder dec2 = { 0 };
1883
0
  BOOL error = FALSE;
1884
0
  WinPrAsn1_tagId tag = { 0 };
1885
0
  WinPrAsn1_INTEGER val = { 0 };
1886
0
  UINT32 version = 0;
1887
1888
0
  WINPR_ASSERT(nla);
1889
0
  WINPR_ASSERT(s);
1890
1891
0
  WinPrAsn1Decoder_Init(&dec, WINPR_ASN1_DER, s);
1892
1893
0
  WLog_DBG(TAG, "<<----- receiving...");
1894
1895
  /* TSRequest */
1896
0
  const size_t offset = WinPrAsn1DecReadSequence(&dec, &dec2);
1897
0
  if (offset == 0)
1898
0
    return -1;
1899
0
  dec = dec2;
1900
1901
  /* version [0] INTEGER */
1902
0
  if (WinPrAsn1DecReadContextualInteger(&dec, 0, &error, &val) == 0)
1903
0
    return -1;
1904
1905
0
  if (!Stream_SafeSeek(s, offset))
1906
0
    return -1;
1907
1908
0
  version = (UINT)val;
1909
0
  WLog_DBG(TAG, "   <<----- protocol version %" PRIu32, version);
1910
1911
0
  if (nla->peerVersion == 0)
1912
0
    nla->peerVersion = version;
1913
1914
  /* if the peer suddenly changed its version - kick it */
1915
0
  if (nla->peerVersion != version)
1916
0
  {
1917
0
    WLog_ERR(TAG, "CredSSP peer changed protocol version from %" PRIu32 " to %" PRIu32,
1918
0
             nla->peerVersion, version);
1919
0
    return -1;
1920
0
  }
1921
1922
0
  while (WinPrAsn1DecReadContextualTag(&dec, &tag, &dec2) != 0)
1923
0
  {
1924
0
    WinPrAsn1Decoder dec3 = { 0 };
1925
0
    WinPrAsn1_OctetString octet_string = { 0 };
1926
1927
0
    switch (tag)
1928
0
    {
1929
0
      case 1:
1930
0
        WLog_DBG(TAG, "   <<----- nego token");
1931
        /* negoTokens [1] SEQUENCE OF SEQUENCE */
1932
0
        if ((WinPrAsn1DecReadSequence(&dec2, &dec3) == 0) ||
1933
0
            (WinPrAsn1DecReadSequence(&dec3, &dec2) == 0))
1934
0
          return -1;
1935
        /* negoToken [0] OCTET STRING */
1936
0
        if ((WinPrAsn1DecReadContextualOctetString(&dec2, 0, &error, &octet_string,
1937
0
                                                   FALSE) == 0) &&
1938
0
            error)
1939
0
          return -1;
1940
0
        if (!nla_sec_buffer_alloc_from_data(&nla->negoToken, octet_string.data, 0,
1941
0
                                            octet_string.len))
1942
0
          return -1;
1943
0
        break;
1944
0
      case 2:
1945
0
        WLog_DBG(TAG, "   <<----- auth info");
1946
        /* authInfo [2] OCTET STRING */
1947
0
        if (WinPrAsn1DecReadOctetString(&dec2, &octet_string, FALSE) == 0)
1948
0
          return -1;
1949
0
        if (!nla_sec_buffer_alloc_from_data(&nla->authInfo, octet_string.data, 0,
1950
0
                                            octet_string.len))
1951
0
          return -1;
1952
0
        break;
1953
0
      case 3:
1954
0
        WLog_DBG(TAG, "   <<----- public key auth");
1955
        /* pubKeyAuth [3] OCTET STRING */
1956
0
        if (WinPrAsn1DecReadOctetString(&dec2, &octet_string, FALSE) == 0)
1957
0
          return -1;
1958
0
        if (!nla_sec_buffer_alloc_from_data(&nla->pubKeyAuth, octet_string.data, 0,
1959
0
                                            octet_string.len))
1960
0
          return -1;
1961
0
        break;
1962
0
      case 4:
1963
        /* errorCode [4] INTEGER */
1964
0
        if (WinPrAsn1DecReadInteger(&dec2, &val) == 0)
1965
0
          return -1;
1966
0
        nla->errorCode = val;
1967
0
        WLog_DBG(TAG, "   <<----- error code %s 0x%08" PRIx32, NtStatus2Tag(nla->errorCode),
1968
0
                 nla->errorCode);
1969
0
        break;
1970
0
      case 5:
1971
0
        WLog_DBG(TAG, "   <<----- client nonce");
1972
        /* clientNonce [5] OCTET STRING */
1973
0
        if (WinPrAsn1DecReadOctetString(&dec2, &octet_string, FALSE) == 0)
1974
0
          return -1;
1975
0
        if (!nla_sec_buffer_alloc_from_data(&nla->ClientNonce, octet_string.data, 0,
1976
0
                                            octet_string.len))
1977
0
          return -1;
1978
0
        break;
1979
0
      default:
1980
0
        return -1;
1981
0
    }
1982
0
  }
1983
1984
0
  return 1;
1985
0
}
1986
1987
int nla_recv_pdu(rdpNla* nla, wStream* s)
1988
0
{
1989
0
  WINPR_ASSERT(nla);
1990
0
  WINPR_ASSERT(s);
1991
1992
0
  if (nla_get_state(nla) == NLA_STATE_EARLY_USER_AUTH)
1993
0
  {
1994
0
    UINT32 code = 0;
1995
0
    Stream_Read_UINT32(s, code);
1996
0
    if (code != AUTHZ_SUCCESS)
1997
0
    {
1998
0
      WLog_DBG(TAG, "Early User Auth active: FAILURE code 0x%08" PRIX32 "", code);
1999
0
      code = FREERDP_ERROR_AUTHENTICATION_FAILED;
2000
0
      freerdp_set_last_error_log(nla->rdpcontext, code);
2001
0
      return -1;
2002
0
    }
2003
0
    else
2004
0
      WLog_DBG(TAG, "Early User Auth active: SUCCESS");
2005
0
  }
2006
0
  else
2007
0
  {
2008
0
    if (nla_decode_ts_request(nla, s) < 1)
2009
0
      return -1;
2010
2011
0
    if (nla->errorCode)
2012
0
    {
2013
0
      UINT32 code = 0;
2014
2015
0
      switch (nla->errorCode)
2016
0
      {
2017
0
        case STATUS_PASSWORD_MUST_CHANGE:
2018
0
          code = FREERDP_ERROR_CONNECT_PASSWORD_MUST_CHANGE;
2019
0
          break;
2020
2021
0
        case STATUS_PASSWORD_EXPIRED:
2022
0
          code = FREERDP_ERROR_CONNECT_PASSWORD_EXPIRED;
2023
0
          break;
2024
2025
0
        case STATUS_ACCOUNT_DISABLED:
2026
0
          code = FREERDP_ERROR_CONNECT_ACCOUNT_DISABLED;
2027
0
          break;
2028
2029
0
        case STATUS_LOGON_FAILURE:
2030
0
          code = FREERDP_ERROR_CONNECT_LOGON_FAILURE;
2031
0
          break;
2032
2033
0
        case STATUS_WRONG_PASSWORD:
2034
0
          code = FREERDP_ERROR_CONNECT_WRONG_PASSWORD;
2035
0
          break;
2036
2037
0
        case STATUS_ACCESS_DENIED:
2038
0
          code = FREERDP_ERROR_CONNECT_ACCESS_DENIED;
2039
0
          break;
2040
2041
0
        case STATUS_ACCOUNT_RESTRICTION:
2042
0
          code = FREERDP_ERROR_CONNECT_ACCOUNT_RESTRICTION;
2043
0
          break;
2044
2045
0
        case STATUS_ACCOUNT_LOCKED_OUT:
2046
0
          code = FREERDP_ERROR_CONNECT_ACCOUNT_LOCKED_OUT;
2047
0
          break;
2048
2049
0
        case STATUS_ACCOUNT_EXPIRED:
2050
0
          code = FREERDP_ERROR_CONNECT_ACCOUNT_EXPIRED;
2051
0
          break;
2052
2053
0
        case STATUS_LOGON_TYPE_NOT_GRANTED:
2054
0
          code = FREERDP_ERROR_CONNECT_LOGON_TYPE_NOT_GRANTED;
2055
0
          break;
2056
2057
0
        default:
2058
0
          WLog_ERR(TAG, "SPNEGO failed with NTSTATUS: %s [0x%08" PRIX32 "]",
2059
0
                   NtStatus2Tag(nla->errorCode), nla->errorCode);
2060
0
          code = FREERDP_ERROR_AUTHENTICATION_FAILED;
2061
0
          break;
2062
0
      }
2063
2064
0
      freerdp_set_last_error_log(nla->rdpcontext, code);
2065
0
      return -1;
2066
0
    }
2067
0
  }
2068
2069
0
  return nla_client_recv(nla);
2070
0
}
2071
2072
int nla_server_recv(rdpNla* nla)
2073
0
{
2074
0
  int status = -1;
2075
2076
0
  WINPR_ASSERT(nla);
2077
2078
0
  wStream* s = nla_server_recv_stream(nla);
2079
0
  if (!s)
2080
0
    goto fail;
2081
0
  status = nla_decode_ts_request(nla, s);
2082
2083
0
fail:
2084
0
  Stream_Free(s, TRUE);
2085
0
  return status;
2086
0
}
2087
2088
/**
2089
 * Create new CredSSP state machine.
2090
 *
2091
 * @param context A pointer to the rdp context to use
2092
 * @param transport A pointer to the transport to use
2093
 *
2094
 * @return new CredSSP state machine.
2095
 */
2096
2097
rdpNla* nla_new(rdpContext* context, rdpTransport* transport)
2098
0
{
2099
0
  WINPR_ASSERT(transport);
2100
0
  WINPR_ASSERT(context);
2101
2102
0
  rdpSettings* settings = context->settings;
2103
0
  WINPR_ASSERT(settings);
2104
2105
0
  rdpNla* nla = (rdpNla*)calloc(1, sizeof(rdpNla));
2106
2107
0
  if (!nla)
2108
0
    return NULL;
2109
2110
0
  nla->rdpcontext = context;
2111
0
  nla->server = settings->ServerMode;
2112
0
  nla->transport = transport;
2113
0
  nla->sendSeqNum = 0;
2114
0
  nla->recvSeqNum = 0;
2115
0
  nla->version = 6;
2116
0
  nla->earlyUserAuth = FALSE;
2117
2118
0
  nla->identity = calloc(1, sizeof(SEC_WINNT_AUTH_IDENTITY));
2119
0
  if (!nla->identity)
2120
0
    goto cleanup;
2121
2122
0
  nla->auth = credssp_auth_new(context);
2123
0
  if (!nla->auth)
2124
0
    goto cleanup;
2125
2126
  /* init to 0 or we end up freeing a bad pointer if the alloc fails */
2127
0
  if (!nla_sec_buffer_alloc(&nla->ClientNonce, NonceLength))
2128
0
    goto cleanup;
2129
2130
  /* generate random 32-byte nonce */
2131
0
  if (winpr_RAND(nla->ClientNonce.pvBuffer, NonceLength) < 0)
2132
0
    goto cleanup;
2133
2134
0
  return nla;
2135
0
cleanup:
2136
0
  WINPR_PRAGMA_DIAG_PUSH
2137
0
  WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC
2138
0
  nla_free(nla);
2139
0
  WINPR_PRAGMA_DIAG_POP
2140
0
  return NULL;
2141
0
}
2142
2143
/**
2144
 * Free CredSSP state machine.
2145
 * @param nla The NLA instance to free
2146
 */
2147
2148
void nla_free(rdpNla* nla)
2149
0
{
2150
0
  if (!nla)
2151
0
    return;
2152
2153
0
  smartcardCertInfo_Free(nla->smartcardCert);
2154
0
  nla_buffer_free(nla);
2155
0
  sspi_SecBufferFree(&nla->tsCredentials);
2156
0
  credssp_auth_free(nla->auth);
2157
2158
0
  sspi_FreeAuthIdentity(nla->identity);
2159
0
  free(nla->pkinitArgs);
2160
0
  free(nla->identity);
2161
0
  free(nla);
2162
0
}
2163
2164
SEC_WINNT_AUTH_IDENTITY* nla_get_identity(rdpNla* nla)
2165
0
{
2166
0
  if (!nla)
2167
0
    return NULL;
2168
2169
0
  return nla->identity;
2170
0
}
2171
2172
NLA_STATE nla_get_state(rdpNla* nla)
2173
0
{
2174
0
  if (!nla)
2175
0
    return NLA_STATE_FINAL;
2176
2177
0
  return nla->state;
2178
0
}
2179
2180
BOOL nla_set_state(rdpNla* nla, NLA_STATE state)
2181
0
{
2182
0
  if (!nla)
2183
0
    return FALSE;
2184
2185
0
  WLog_DBG(TAG, "-- %s\t--> %s", nla_get_state_str(nla->state), nla_get_state_str(state));
2186
0
  nla->state = state;
2187
0
  return TRUE;
2188
0
}
2189
2190
BOOL nla_set_service_principal(rdpNla* nla, const char* service, const char* hostname)
2191
0
{
2192
0
  if (!credssp_auth_set_spn(nla->auth, service, hostname))
2193
0
    return FALSE;
2194
0
  return TRUE;
2195
0
}
2196
2197
BOOL nla_impersonate(rdpNla* nla)
2198
0
{
2199
0
  return credssp_auth_impersonate(nla->auth);
2200
0
}
2201
2202
BOOL nla_revert_to_self(rdpNla* nla)
2203
0
{
2204
0
  return credssp_auth_revert_to_self(nla->auth);
2205
0
}
2206
2207
const char* nla_get_state_str(NLA_STATE state)
2208
0
{
2209
0
  switch (state)
2210
0
  {
2211
0
    case NLA_STATE_INITIAL:
2212
0
      return "NLA_STATE_INITIAL";
2213
0
    case NLA_STATE_NEGO_TOKEN:
2214
0
      return "NLA_STATE_NEGO_TOKEN";
2215
0
    case NLA_STATE_PUB_KEY_AUTH:
2216
0
      return "NLA_STATE_PUB_KEY_AUTH";
2217
0
    case NLA_STATE_AUTH_INFO:
2218
0
      return "NLA_STATE_AUTH_INFO";
2219
0
    case NLA_STATE_POST_NEGO:
2220
0
      return "NLA_STATE_POST_NEGO";
2221
0
    case NLA_STATE_EARLY_USER_AUTH:
2222
0
      return "NLA_STATE_EARLY_USER_AUTH";
2223
0
    case NLA_STATE_FINAL:
2224
0
      return "NLA_STATE_FINAL";
2225
0
    default:
2226
0
      return "UNKNOWN";
2227
0
  }
2228
0
}
2229
2230
DWORD nla_get_error(rdpNla* nla)
2231
0
{
2232
0
  if (!nla)
2233
0
    return ERROR_INTERNAL_ERROR;
2234
0
  return (UINT32)nla->errorCode;
2235
0
}
2236
2237
INT32 nla_get_sspi_error(rdpNla* nla)
2238
0
{
2239
0
  WINPR_ASSERT(nla);
2240
0
  return credssp_auth_sspi_error(nla->auth);
2241
0
}
2242
2243
BOOL nla_encrypt(rdpNla* nla, const SecBuffer* inBuffer, SecBuffer* outBuffer)
2244
0
{
2245
0
  WINPR_ASSERT(nla);
2246
0
  WINPR_ASSERT(inBuffer);
2247
0
  WINPR_ASSERT(outBuffer);
2248
0
  return credssp_auth_encrypt(nla->auth, inBuffer, outBuffer, NULL, nla->sendSeqNum++);
2249
0
}
2250
2251
BOOL nla_decrypt(rdpNla* nla, const SecBuffer* inBuffer, SecBuffer* outBuffer)
2252
0
{
2253
0
  WINPR_ASSERT(nla);
2254
0
  WINPR_ASSERT(inBuffer);
2255
0
  WINPR_ASSERT(outBuffer);
2256
0
  return credssp_auth_decrypt(nla->auth, inBuffer, outBuffer, nla->recvSeqNum++);
2257
0
}
2258
2259
SECURITY_STATUS nla_QueryContextAttributes(rdpNla* nla, DWORD ulAttr, PVOID pBuffer)
2260
0
{
2261
0
  WINPR_ASSERT(nla);
2262
2263
0
  SecurityFunctionTable* table = NULL;
2264
0
  CtxtHandle context = { 0 };
2265
0
  credssp_auth_tableAndContext(nla->auth, &table, &context);
2266
2267
0
  return table->QueryContextAttributes(&context, ulAttr, pBuffer);
2268
0
}