aboutsummaryrefslogtreecommitdiff
path: root/nxcomp/Auth.cpp
blob: c52392a511d93da8d9470e85d18b53a0f0e9e96a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
/**************************************************************************/
/*                                                                        */
/* Copyright (c) 2001, 2010 NoMachine, http://www.nomachine.com/.         */
/*                                                                        */
/* NXCOMP, NX protocol compression and NX extensions to this software     */
/* are copyright of NoMachine. Redistribution and use of the present      */
/* software is allowed according to terms specified in the file LICENSE   */
/* which comes in the source distribution.                                */
/*                                                                        */
/* Check http://www.nomachine.com/licensing.html for applicability.       */
/*                                                                        */
/* NX and NoMachine are trademarks of Medialogic S.p.A.                   */
/*                                                                        */
/* All rights reserved.                                                   */
/*                                                                        */
/**************************************************************************/

#include "Auth.h"

#include "Misc.h"
#include "Control.h"
#include "Timestamp.h"
#include "Pipe.h"

#define DEFAULT_STRING_LIMIT  512

//
// Set the verbosity level.
//

#define PANIC
#define WARNING
#undef  TEST
#undef  DEBUG

//
// Store the provided cookie as our 'fake' cookie, then
// read the 'real' cookie from the current X authority
// file. 
//

Auth::Auth(char *display, char *cookie)
{
  display_ = NULL;

  file_ = NULL;

  last_ = nullTimestamp();

  fakeCookie_ = NULL;
  realCookie_ = NULL;

  fakeData_ = NULL;
  realData_ = NULL;

  dataSize_ = 0;

  generatedCookie_ = 0;

  if (display == NULL || *display == '\0' || cookie == NULL ||
          *cookie == '\0' || strlen(cookie) != 32)
  {
    #ifdef PANIC
    *logofs << "Auth: PANIC! Can't create the X authorization data "
            << "with cookie '" << cookie << "' and display '"
            << display << "'.\n" << logofs_flush;
    #endif

    cerr << "Error" << ": Can't create the X authorization data "
         << "with cookie '" << cookie << "' and display '"
         << display << "'.\n";

    return;
  }

  #ifdef TEST
  *logofs << "Auth: Creating X authorization data with cookie '"
          << cookie << "' and display '" << display << "'.\n"
          << logofs_flush;
  #endif

  //
  // Get a local copy of all parameters.
  //

  display_ = new char[strlen(display) + 1];
  file_    = new char[DEFAULT_STRING_LIMIT];

  fakeCookie_ = new char[strlen(cookie) + 1];
  realCookie_ = new char[DEFAULT_STRING_LIMIT];

  if (display_ == NULL || file_ == NULL ||
          fakeCookie_ == NULL || realCookie_ == NULL)
  {
    #ifdef PANIC
    *logofs << "Auth: PANIC! Cannot allocate memory for the X "
            << "authorization data.\n" << logofs_flush;
    #endif

    cerr << "Error" << ": Cannot allocate memory for the X "
         << "authorization data.\n";

    return;
  }

  strcpy(display_, display);

  *file_ = '\0';

  strcpy(fakeCookie_, cookie);

  *realCookie_ = '\0';

  //
  // Get the real cookie from the authorization file.
  //

  updateCookie();
}

Auth::~Auth()
{
  delete [] display_;
  delete [] file_;

  delete [] fakeCookie_;
  delete [] realCookie_;

  delete [] fakeData_;
  delete [] realData_;
}

//
// At the present moment the cookie is read only once,
// at the time the instance is initialized. If the auth
// file changes along the life of the session, the old
// cookie will be used. This works with X servers beca-
// use of an undocumented "feature". See nx-X11.
//

int Auth::updateCookie()
{
  if (isTimestamp(last_) == 0)
  {
    #ifdef TEST
    *logofs << "Auth: Reading the X authorization file "
            << "with last update at " << strMsTimestamp(last_)
            << ".\n" << logofs_flush;
    #endif

    if (getCookie() == 1 && validateCookie() == 1)
    {
      //
      // It should rather be the modification time
      // the auth file, so we can read it again if
      // the file is changed.
      //

      #ifdef TEST
      *logofs << "Auth: Setting last X authorization file "
              << "update at " << strMsTimestamp() << ".\n"
              << logofs_flush;
      #endif

      last_ = getTimestamp();

      return 1;
    }

    #ifdef PANIC
    *logofs << "Auth: PANIC! Cannot read the cookie from the X "
            << "authorization file.\n" << logofs_flush;
    #endif

    cerr << "Error" << ": Cannot read the cookie from the X "
         << "authorization file.\n";

    return -1;
  }

  #ifdef TEST
  *logofs << "Auth: WARNING! Skipping check on the X "
          << "authorization file.\n" << logofs_flush;
  #endif

  return 0;
}

int Auth::getCookie()
{
  //
  // Check the name of the auth file that we are going to use.
  // It can be either the value of the XAUTHORITY environment
  // or the default .Xauthority file in the user's home.
  //

  char *environment;

  environment = getenv("XAUTHORITY");

  if (environment != NULL && *environment != '\0')
  {
    strncpy(file_, environment, DEFAULT_STRING_LIMIT - 1);
  }
  else
  {
    snprintf(file_, DEFAULT_STRING_LIMIT - 1, "%s/.Xauthority",
                 control -> HomePath);
  }

  *(file_ + DEFAULT_STRING_LIMIT - 1) = '\0';

  #ifdef TEST
  *logofs << "Auth: Using X authorization file '" << file_
          << "'.\n" << logofs_flush;
  #endif

  //
  // Use the nxauth command on Windows and the Mac, xauth
  // on all the other platforms. On Windows we assume that
  // the nxauth command is located under bin in the client
  // installation directory. On Mac OS X we assume that the
  // command is located directly in the client installation
  // directory, to make bundle shipping easier. On all the
  // other platforms we use the default xauth command that
  // is in our path.
  //

  char command[DEFAULT_STRING_LIMIT];

  #if defined(__CYGWIN32__)

  snprintf(command, DEFAULT_STRING_LIMIT - 1,
               "%s/bin/nxauth", control -> SystemPath);

  *(command + DEFAULT_STRING_LIMIT - 1) = '\0';

  #elif defined(__APPLE__)

  snprintf(command, DEFAULT_STRING_LIMIT - 1,
               "%s/nxauth", control -> SystemPath);

  *(command + DEFAULT_STRING_LIMIT - 1) = '\0';

  #else

  strcpy(command, "xauth");

  #endif

  #ifdef TEST
  *logofs << "Auth: Using X auth command '" << command
          << "'.\n" << logofs_flush;
  #endif

  //
  // The SSH code forces using the unix:n port when passing localhost:n.
  // This is probably because localhost:n can fail to return a valid
  // entry on machines where the hostname for localhost doesn't match
  // exactly the 'localhost' string. For example, on a freshly installed
  // Fedora Core 3 I get a 'localhost.localdomain/unix:0' entry. Query-
  // ing 'xauth list localhost:0' results in an empty result, while the
  // query 'xauth list unix:0' works as expected. Note anyway that if
  // the cookie for the TCP connection on 'localhost' is set to a dif-
  // ferent cookie than the one for the Unix connections, both SSH and
  // NX will match the wrong cookie and session will fail.
  //
  
  char line[DEFAULT_STRING_LIMIT];

  if (strncmp(display_, "localhost:", 10) == 0)
  {
    snprintf(line, DEFAULT_STRING_LIMIT, "unix:%s", display_ + 10);
  }
  else
  {
    snprintf(line, DEFAULT_STRING_LIMIT, "%.200s", display_);
  }

  const char *parameters[256];

  parameters[0] = command;
  parameters[1] = command;
  parameters[2] = "-f";
  parameters[3] = file_;
  parameters[4] = "list";
  parameters[5] = line;
  parameters[6] = NULL;

  #ifdef TEST
  *logofs << "Auth: Executing command ";

  for (int i = 0; i < 256 && parameters[i] != NULL; i++)
  {
    *logofs << "[" << parameters[i] << "]";
  }

  *logofs << ".\n" << logofs_flush;
  #endif

  //
  // Use the popen() function to read the result
  // of the command. We would better use our own
  // implementation.
  //

  FILE *data = Popen((char *const *) parameters, "r");

  int result = -1;

  if (data == NULL)
  {
    #ifdef PANIC
    *logofs << "Auth: PANIC! Failed to execute the X auth command.\n"
            << logofs_flush;
    #endif

    cerr << "Error" << ": Failed to execute the X auth command.\n";

    goto AuthGetCookieResult;
  }

  if (fgets(line, DEFAULT_STRING_LIMIT, data) == NULL)
  {
    #ifdef WARNING
    *logofs << "Auth: WARNING! Failed to read data from the X "
            << "auth command.\n" << logofs_flush;
    #endif

    #ifdef TEST
    cerr << "Warning" << ": Failed to read data from the X "
         << "auth command.\n";
    #endif

    #ifdef PANIC
    *logofs << "Auth: WARNING! Generating a fake cookie for "
            << "X authentication.\n" << logofs_flush;
    #endif

    #ifdef TEST
    cerr << "Warning" << ": Generating a fake cookie for "
         << "X authentication.\n";
    #endif

    generateCookie(realCookie_);
  }
  else
  {
    #ifdef TEST
    *logofs << "Auth: Checking cookie in string '" << line
            << "'.\n" << logofs_flush;
    #endif

    // 
    // Skip the hostname in the authority entry
    // just in case it includes some white spaces.
    //

    char *cookie = NULL;

    cookie = index(line, ':');

    if (cookie == NULL)
    {
      cookie = line;
    }

    if (sscanf(cookie, "%*s %*s %511s", realCookie_) != 1)
    {
      #ifdef PANIC
      *logofs << "Auth: PANIC! Failed to identify the cookie "
              << "in string '" << line << "'.\n"
              << logofs_flush;
      #endif

      cerr << "Error" << ": Failed to identify the cookie "
           << "in string '" << line << "'.\n";

      goto AuthGetCookieResult;
    }

    #ifdef TEST
    *logofs << "Auth: Got cookie '" << realCookie_
            << "' from file '" << file_ << "'.\n"
            << logofs_flush;
    #endif
  }

  result = 1;

AuthGetCookieResult:

  if (data != NULL)
  {
    Pclose(data);
  }

  return result;
}

int Auth::validateCookie()
{
  unsigned int length = strlen(realCookie_);

  if (length > DEFAULT_STRING_LIMIT / 2 - 1 ||
          strlen(fakeCookie_) != length)
  {
    #ifdef PANIC
    *logofs << "Auth: PANIC! Size mismatch between cookies '"
            << realCookie_ << "' and '" << fakeCookie_ << "'.\n"
            << logofs_flush;
    #endif

    cerr << "Error" << ": Size mismatch between cookies '"
         << realCookie_ << "' and '" << fakeCookie_ << "'.\n";

    goto AuthValidateCookieError;
  }

  //
  // The length of the resulting data will be
  // half the size of the Hex cookie.
  //

  length = length / 2;

  fakeData_ = new char[length];
  realData_ = new char[length];

  if (fakeData_ == NULL || realData_ == NULL)
  {
    #ifdef PANIC
    *logofs << "Auth: PANIC! Cannot allocate memory for the binary X "
            << "authorization data.\n" << logofs_flush;
    #endif

    cerr << "Error" << ": Cannot allocate memory for the binary X "
         << "authorization data.\n";

    goto AuthValidateCookieError;
  }

  //
  // Translate the real cookie from Hex data
  // to its binary representation.
  //

  unsigned int value;

  for (unsigned int i = 0; i < length; i++)
  {
    if (sscanf(realCookie_ + 2 * i, "%2x", &value) != 1)
    {
      #ifdef PANIC
      *logofs << "Auth: PANIC! Bad X authorization data in real "
              << "cookie '" << realCookie_ << "'.\n" << logofs_flush;
      #endif

      cerr << "Error" << ": Bad X authorization data in real cookie '"
           << realCookie_ << "'.\n";

      goto AuthValidateCookieError;
    }

    realData_[i] = value;

    if (sscanf(fakeCookie_ + 2 * i, "%2x", &value) != 1)
    {
      #ifdef PANIC
      *logofs << "Auth: PANIC! Bad X authorization data in fake "
              << "cookie '" << fakeCookie_ << "'.\n" << logofs_flush;
      #endif

      cerr << "Error" << ": Bad X authorization data in fake cookie '"
           << fakeCookie_ << "'.\n";

      goto AuthValidateCookieError;
    }

    fakeData_[i] = value;
  }

  dataSize_ = length;

  #ifdef TEST
  *logofs << "Auth: Validated real cookie '"
          << realCookie_ << "' and fake cookie '" << fakeCookie_
          << "' with data with size " << dataSize_ << ".\n"
          << logofs_flush;

  *logofs << "Auth: Ready to accept incoming connections.\n"
          << logofs_flush;
  #endif

  return 1;

AuthValidateCookieError:

  delete [] fakeData_;
  delete [] realData_;

  fakeData_ = NULL;
  realData_ = NULL;

  dataSize_ = 0;

  return -1;
}

int Auth::checkCookie(unsigned char *buffer)
{
  if (isValid() != 1)
  {
    #ifdef PANIC
    *logofs << "Auth: PANIC! Attempt to check the X cookie with "
            << "invalid authorization data.\n" << logofs_flush;
    #endif

    cerr << "Error" << ": Attempt to check the X cookie with "
         << "invalid authorization data.\n";

    return -1;
  }

  const char *protoName = "MIT-MAGIC-COOKIE-1";
  int protoSize = strlen(protoName);

  int matchedProtoSize;
  int matchedDataSize;

  if (buffer[0] == 0x42)
  {
    //
    // Byte order is MSB first.
    //

    matchedProtoSize = 256 * buffer[6] + buffer[7];
    matchedDataSize  = 256 * buffer[8] + buffer[9];
  }
  else if (buffer[0] == 0x6c)
  {
    //
    // Byte order is LSB first.
    //

    matchedProtoSize = buffer[6] + 256 * buffer[7];
    matchedDataSize  = buffer[8] + 256 * buffer[9];
  }
  else
  {
    #ifdef WARNING
    *logofs << "Auth: WARNING! Bad X connection data in the buffer.\n"
            << logofs_flush;
    #endif

    cerr << "Warning" << ": Bad X connection data in the buffer.\n";

    return -1;
  }

  //
  // Check if both the authentication protocol
  // and the fake cookie match our data.
  //

  int protoOffset = 12;

  #ifdef TEST
  *logofs << "Auth: Received a protocol size of "
          << matchedProtoSize << " bytes.\n"
          << logofs_flush;
  #endif

  if (matchedProtoSize != protoSize ||
          memcmp(buffer + protoOffset, protoName, protoSize) != 0)
  {
    #ifdef WARNING
    *logofs << "Auth: WARNING! Protocol mismatch or no X "
            << "authentication data.\n" << logofs_flush;
    #endif

    cerr << "Warning" << ": Protocol mismatch or no X "
         << "authentication data.\n";

    return -1;
  }

  int dataOffset = protoOffset + ((matchedProtoSize + 3) & ~3);

  #ifdef TEST
  *logofs << "Auth: Received a data size of "
          << matchedDataSize << " bytes.\n"
          << logofs_flush;
  #endif

  if (matchedDataSize != dataSize_ ||
           memcmp(buffer + dataOffset, fakeData_, dataSize_) != 0)
  {
    #ifdef WARNING
    *logofs << "Auth: WARNING! Cookie mismatch in the X "
            << "authentication data.\n" << logofs_flush;
    #endif

    cerr << "Warning" << ": Cookie mismatch in the X "
         << "authentication data.\n";

    return -1;
  }

  //
  // Everything is OK. Replace the fake data.
  //

  #ifdef TEST
  *logofs << "Auth: Replacing fake X authentication data "
          << "with the real data.\n" << logofs_flush;
  #endif

  memcpy(buffer + dataOffset, realData_, dataSize_);

  return 1;
}

void Auth::generateCookie(char *cookie)
{
  //
  // Code is from the SSH implementation, except that
  // we use a much weaker random number generator.
  // This is not critical, anyway, as this is just a
  // fake cookie. The X server doesn't have a cookie
  // for the display, so it will ignore the value we
  // feed to it.
  //

  T_timestamp timer = getTimestamp();

  srand((unsigned int) timer.tv_usec);

  unsigned int data = rand();

  for (int i = 0; i < 16; i++)
  {
    if (i % 4 == 0)
    {
      data = rand();
    }

    snprintf(cookie + 2 * i, 3, "%02x", data & 0xff);

    data >>= 8;
  }

  generatedCookie_ = 1;

  #ifdef TEST
  *logofs << "Auth: Generated X cookie string '"
          << cookie << "'.\n" << logofs_flush;
  #endif
}