summaryrefslogtreecommitdiff
path: root/tests/random.c
blob: 8aa730b215578d6bf3d95bb54cbcc9fc2f8668e1 (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
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
/* random.c - part of the Libgcrypt test suite.
   Copyright (C) 2005 Free Software Foundation, Inc.

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public License as
   published by the Free Software Foundation; either version 2 of the
   License, or (at your option) any later version.

   This program is distributed in the hope that it will be useful, but
   WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
   USA.  */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#ifndef HAVE_W32_SYSTEM
# include <signal.h>
# include <unistd.h>
# include <sys/wait.h>
#endif

#include "../src/gcrypt-int.h"

#define PGM "random"

#ifndef DIM
# define DIM(v)		     (sizeof(v)/sizeof((v)[0]))
#endif


static int verbose;
static int debug;
static int with_progress;

static void
die (const char *format, ...)
{
  va_list arg_ptr;

  va_start (arg_ptr, format);
  fputs ( PGM ": ", stderr);
  vfprintf (stderr, format, arg_ptr);
  va_end (arg_ptr);
  exit (1);
}


static void
inf (const char *format, ...)
{
  va_list arg_ptr;

  va_start (arg_ptr, format);
  fputs ( PGM ": ", stderr);
  vfprintf (stderr, format, arg_ptr);
  va_end (arg_ptr);
}


static void
print_hex (const char *text, const void *buf, size_t n)
{
  const unsigned char *p = buf;

  inf ("%s", text);
  for (; n; n--, p++)
    fprintf (stderr, "%02X", *p);
  putc ('\n', stderr);
}


static void
progress_cb (void *cb_data, const char *what, int printchar,
             int current, int total)
{
  (void)cb_data;

  inf ("progress (%s %c %d %d)\n", what, printchar, current, total);
  fflush (stderr);
}


#ifndef HAVE_W32_SYSTEM
static int
writen (int fd, const void *buf, size_t nbytes)
{
  size_t nleft = nbytes;
  int nwritten;

  while (nleft > 0)
    {
      nwritten = write (fd, buf, nleft);
      if (nwritten < 0)
        {
          if (errno == EINTR)
            nwritten = 0;
          else
            return -1;
        }
      nleft -= nwritten;
      buf = (const char*)buf + nwritten;
    }

  return 0;
}
#endif /*!HAVE_W32_SYSTEM*/


#ifndef HAVE_W32_SYSTEM
static int
readn (int fd, void *buf, size_t buflen, size_t *ret_nread)
{
  size_t nleft = buflen;
  int nread;

  while ( nleft > 0 )
    {
      nread = read ( fd, buf, nleft );
      if (nread < 0)
        {
          if (nread == EINTR)
            nread = 0;
          else
            return -1;
        }
      else if (!nread)
        break; /* EOF */
      nleft -= nread;
      buf = (char*)buf + nread;
    }
  if (ret_nread)
    *ret_nread = buflen - nleft;
  return 0;
}
#endif /*!HAVE_W32_SYSTEM*/


/* Check that forking won't return the same random. */
static void
check_forking (void)
{
#ifdef HAVE_W32_SYSTEM
  if (verbose)
    inf ("check_forking skipped: not applicable on Windows\n");
#else /*!HAVE_W32_SYSTEM*/
  pid_t pid;
  int rp[2];
  int i, status;
  size_t nread;
  char tmp1[16], tmp1c[16], tmp1p[16];

  if (verbose)
    inf ("checking that a fork won't cause the same random output\n");

  /* We better make sure that the RNG has been initialzied. */
  gcry_randomize (tmp1, sizeof tmp1, GCRY_STRONG_RANDOM);
  if (verbose)
    print_hex ("initial random: ", tmp1, sizeof tmp1);

  if (pipe (rp) == -1)
    die ("pipe failed: %s\n", strerror (errno));

  pid = fork ();
  if (pid == (pid_t)(-1))
    die ("fork failed: %s\n", strerror (errno));
  if (!pid)
    {
      gcry_randomize (tmp1c, sizeof tmp1c, GCRY_STRONG_RANDOM);
      if (writen (rp[1], tmp1c, sizeof tmp1c))
        die ("write failed: %s\n", strerror (errno));
      if (verbose)
        {
          print_hex ("  child random: ", tmp1c, sizeof tmp1c);
          fflush (stdout);
        }
      _exit (0);
    }
  gcry_randomize (tmp1p, sizeof tmp1p, GCRY_STRONG_RANDOM);
  if (verbose)
    print_hex (" parent random: ", tmp1p, sizeof tmp1p);

  close (rp[1]);
  if (readn (rp[0], tmp1c, sizeof tmp1c, &nread))
    die ("read failed: %s\n", strerror (errno));
  if (nread != sizeof tmp1c)
    die ("read too short\n");

  while ( (i=waitpid (pid, &status, 0)) == -1 && errno == EINTR)
    ;
  if (i != (pid_t)(-1)
      && WIFEXITED (status) && !WEXITSTATUS (status))
    ;
  else
    die ("child failed\n");

  if (!memcmp (tmp1p, tmp1c, sizeof tmp1c))
    die ("parent and child got the same random number\n");
#endif  /*!HAVE_W32_SYSTEM*/
}



/* Check that forking won't return the same nonce. */
static void
check_nonce_forking (void)
{
#ifdef HAVE_W32_SYSTEM
  if (verbose)
    inf ("check_nonce_forking skipped: not applicable on Windows\n");
#else /*!HAVE_W32_SYSTEM*/
  pid_t pid;
  int rp[2];
  int i, status;
  size_t nread;
  char nonce1[10], nonce1c[10], nonce1p[10];

  if (verbose)
    inf ("checking that a fork won't cause the same nonce output\n");

  /* We won't get the same nonce back if we never initialized the
     nonce subsystem, thus we get one nonce here and forget about
     it. */
  gcry_create_nonce (nonce1, sizeof nonce1);
  if (verbose)
    print_hex ("initial nonce: ", nonce1, sizeof nonce1);

  if (pipe (rp) == -1)
    die ("pipe failed: %s\n", strerror (errno));

  pid = fork ();
  if (pid == (pid_t)(-1))
    die ("fork failed: %s\n", strerror (errno));
  if (!pid)
    {
      gcry_create_nonce (nonce1c, sizeof nonce1c);
      if (writen (rp[1], nonce1c, sizeof nonce1c))
        die ("write failed: %s\n", strerror (errno));
      if (verbose)
        {
          print_hex ("  child nonce: ", nonce1c, sizeof nonce1c);
          fflush (stdout);
        }
      _exit (0);
    }
  gcry_create_nonce (nonce1p, sizeof nonce1p);
  if (verbose)
    print_hex (" parent nonce: ", nonce1p, sizeof nonce1p);

  close (rp[1]);
  if (readn (rp[0], nonce1c, sizeof nonce1c, &nread))
    die ("read failed: %s\n", strerror (errno));
  if (nread != sizeof nonce1c)
    die ("read too short\n");

  while ( (i=waitpid (pid, &status, 0)) == -1 && errno == EINTR)
    ;
  if (i != (pid_t)(-1)
      && WIFEXITED (status) && !WEXITSTATUS (status))
    ;
  else
    die ("child failed\n");

  if (!memcmp (nonce1p, nonce1c, sizeof nonce1c))
    die ("parent and child got the same nonce\n");
#endif  /*!HAVE_W32_SYSTEM*/
}


/* Check that a closed random device os re-opened if needed. */
static void
check_close_random_device (void)
{
#ifdef HAVE_W32_SYSTEM
  if (verbose)
    inf ("check_close_random_device skipped: not applicable on Windows\n");
#else /*!HAVE_W32_SYSTEM*/
  pid_t pid;
  int i, status;
  char buf[4];

  if (verbose)
    inf ("checking that close_random_device works\n");

  gcry_randomize (buf, sizeof buf, GCRY_STRONG_RANDOM);
  if (verbose)
    print_hex ("parent random: ", buf, sizeof buf);

  pid = fork ();
  if (pid == (pid_t)(-1))
    die ("fork failed: %s\n", strerror (errno));
  if (!pid)
    {
      gcry_control (GCRYCTL_CLOSE_RANDOM_DEVICE, 0);

      /* The next call will re-open the device.  */
      gcry_randomize (buf, sizeof buf, GCRY_STRONG_RANDOM);
      if (verbose)
        {
          print_hex ("child random : ", buf, sizeof buf);
          fflush (stdout);
        }
      _exit (0);
    }

  while ( (i=waitpid (pid, &status, 0)) == -1 && errno == EINTR)
    ;
  if (i != (pid_t)(-1)
      && WIFEXITED (status) && !WEXITSTATUS (status))
    ;
  else
    die ("child failed\n");

#endif  /*!HAVE_W32_SYSTEM*/
}


static int
rng_type (void)
{
  int rngtype;
  if (gcry_control (GCRYCTL_GET_CURRENT_RNG_TYPE, &rngtype))
    die ("retrieving RNG type failed\n");
  return rngtype;
}


static void
check_rng_type_switching (void)
{
  int rngtype, initial;
  char tmp1[4];

  if (verbose)
    inf ("checking whether RNG type switching works\n");

  rngtype = rng_type ();
  if (debug)
    inf ("rng type: %d\n", rngtype);
  initial = rngtype;
  gcry_randomize (tmp1, sizeof tmp1, GCRY_STRONG_RANDOM);
  if (debug)
    print_hex ("  sample: ", tmp1, sizeof tmp1);
  if (rngtype != rng_type ())
    die ("RNG type unexpectedly changed\n");

  gcry_control (GCRYCTL_SET_PREFERRED_RNG_TYPE, GCRY_RNG_TYPE_SYSTEM);

  rngtype = rng_type ();
  if (debug)
    inf ("rng type: %d\n", rngtype);
  if (rngtype != initial)
    die ("switching to System RNG unexpectedly succeeded\n");
  gcry_randomize (tmp1, sizeof tmp1, GCRY_STRONG_RANDOM);
  if (debug)
    print_hex ("  sample: ", tmp1, sizeof tmp1);
  if (rngtype != rng_type ())
    die ("RNG type unexpectedly changed\n");

  gcry_control (GCRYCTL_SET_PREFERRED_RNG_TYPE, GCRY_RNG_TYPE_FIPS);

  rngtype = rng_type ();
  if (debug)
    inf ("rng type: %d\n", rngtype);
  if (rngtype != initial)
    die ("switching to FIPS RNG unexpectedly succeeded\n");
  gcry_randomize (tmp1, sizeof tmp1, GCRY_STRONG_RANDOM);
  if (debug)
    print_hex ("  sample: ", tmp1, sizeof tmp1);
  if (rngtype != rng_type ())
    die ("RNG type unexpectedly changed\n");

  gcry_control (GCRYCTL_SET_PREFERRED_RNG_TYPE, GCRY_RNG_TYPE_STANDARD);

  rngtype = rng_type ();
  if (debug)
    inf ("rng type: %d\n", rngtype);
  if (rngtype != GCRY_RNG_TYPE_STANDARD)
    die ("switching to standard RNG failed\n");
  gcry_randomize (tmp1, sizeof tmp1, GCRY_STRONG_RANDOM);
  if (debug)
    print_hex ("  sample: ", tmp1, sizeof tmp1);
  if (rngtype != rng_type ())
    die ("RNG type unexpectedly changed\n");
}


static void
check_early_rng_type_switching (void)
{
  int rngtype, initial;

  if (verbose)
    inf ("checking whether RNG type switching works in the early stage\n");

  rngtype = rng_type ();
  if (debug)
    inf ("rng type: %d\n", rngtype);
  initial = rngtype;

  gcry_control (GCRYCTL_SET_PREFERRED_RNG_TYPE, GCRY_RNG_TYPE_SYSTEM);

  rngtype = rng_type ();
  if (debug)
    inf ("rng type: %d\n", rngtype);
  if (initial >= GCRY_RNG_TYPE_SYSTEM && rngtype != GCRY_RNG_TYPE_SYSTEM)
    die ("switching to System RNG failed\n");

  gcry_control (GCRYCTL_SET_PREFERRED_RNG_TYPE, GCRY_RNG_TYPE_FIPS);

  rngtype = rng_type ();
  if (debug)
    inf ("rng type: %d\n", rngtype);
  if (initial >= GCRY_RNG_TYPE_FIPS && rngtype != GCRY_RNG_TYPE_FIPS)
    die ("switching to FIPS RNG failed\n");

  gcry_control (GCRYCTL_SET_PREFERRED_RNG_TYPE, GCRY_RNG_TYPE_STANDARD);

  rngtype = rng_type ();
  if (debug)
    inf ("rng type: %d\n", rngtype);
  if (rngtype != GCRY_RNG_TYPE_STANDARD)
    die ("switching to standard RNG failed\n");
}


static void
check_drbg_reinit (void)
{
  static struct { const char *flags; } tv[] = {
    { NULL },
    { "" },
    { "sha1" },
    { "sha1 pr" },
    { "sha256" },
    { "sha256 pr" },
    { "sha512" },
    { "sha512 pr" },
    { "hmac sha1" },
    { "hmac sha1 pr" },
    { "hmac sha256" },
    { "hmac sha256 pr" },
    { "hmac sha512" },
    { "hmac sha512 pr" },
    { "aes sym128" },
    { "aes sym128 pr" },
    { "aes sym192" },
    { "aes sym192 pr" },
    { "aes sym256" },
    { "aes sym256 pr" }
  };
  int tidx;
  gpg_error_t err;
  char pers_string[] = "I'm a doctor, not an engineer.";
  gcry_buffer_t pers[1];

  if (verbose)
    inf ("checking DRBG_REINIT\n");

  memset (pers, 0, sizeof pers);
  pers[0].data = pers_string;
  pers[0].len = strlen (pers_string);

  err = gcry_control (GCRYCTL_DRBG_REINIT, "", NULL, 0, &err);
  if (gpg_err_code (err) != GPG_ERR_INV_ARG)
    die ("gcry_control(DRBG_REINIT) guard value did not work\n");

  err = gcry_control (GCRYCTL_DRBG_REINIT, "", NULL, -1, NULL);
  if (gpg_err_code (err) != GPG_ERR_INV_ARG)
    die ("gcry_control(DRBG_REINIT) npers negative detection failed\n");

  if (rng_type () != GCRY_RNG_TYPE_FIPS)
    {
      err = gcry_control (GCRYCTL_DRBG_REINIT, "", NULL, 0, NULL);
      if (gpg_err_code (err) != GPG_ERR_NOT_SUPPORTED)
        die ("DRBG_REINIT worked despite that DRBG is not active\n");
      return;
    }

  err = gcry_control (GCRYCTL_DRBG_REINIT, "", NULL, 1, NULL);
  if (gpg_err_code (err) != GPG_ERR_INV_ARG)
    die ("_gcry_rngdrbg_reinit failed to detact: (!pers && npers)\n");
  err = gcry_control (GCRYCTL_DRBG_REINIT, "", pers, 2, NULL);
  if (gpg_err_code (err) != GPG_ERR_INV_ARG)
    die ("_gcry_rngdrbg_reinit failed to detect: (pers && npers != 1)\n");

  err = gcry_control (GCRYCTL_DRBG_REINIT, "aes sym128 bad pr ", pers, 1, NULL);
  if (gpg_err_code (err) != GPG_ERR_INV_FLAG)
    die ("_gcry_rngdrbg_reinit failed to detect a bad flag\n");

  for (tidx=0; tidx < DIM(tv); tidx++)
    {
      err = gcry_control (GCRYCTL_DRBG_REINIT, tv[tidx].flags, NULL, 0, NULL);
      if (err)
        die ("_gcry_rngdrbg_reinit failed for \"%s\" w/o pers: %s\n",

             tv[tidx].flags, gpg_strerror (err));
      err = gcry_control (GCRYCTL_DRBG_REINIT, tv[tidx].flags, pers, 1, NULL);
      if (err)
        die ("_gcry_rngdrbg_reinit failed for \"%s\" with pers: %s\n",
             tv[tidx].flags, gpg_strerror (err));
      /* fixme: We should extract some random after each test.  */
    }
}


/* Because we want to check initialization behaviour, we need to
   fork/exec this program with several command line arguments.  We use
   system, so that these tests work also on Windows.  */
static void
run_all_rng_tests (const char *program)
{
  static const char *options[] = {
    "--early-rng-check",
    "--early-rng-check --prefer-standard-rng",
    "--early-rng-check --prefer-fips-rng",
    "--early-rng-check --prefer-system-rng",
    "--prefer-standard-rng",
    "--prefer-fips-rng",
    "--prefer-system-rng",
    NULL
  };
  int idx;
  size_t len, maxlen;
  char *cmdline;

  maxlen = 0;
  for (idx=0; options[idx]; idx++)
    {
      len = strlen (options[idx]);
      if (len > maxlen)
        maxlen = len;
    }
  maxlen += strlen (program);
  maxlen += strlen (" --in-recursion --verbose --debug --progress");
  maxlen++;
  cmdline = malloc (maxlen + 1);
  if (!cmdline)
    die ("out of core\n");

  for (idx=0; options[idx]; idx++)
    {
      if (verbose)
        inf ("now running with options '%s'\n", options[idx]);
      strcpy (cmdline, program);
      strcat (cmdline, " --in-recursion");
      if (verbose)
        strcat (cmdline, " --verbose");
      if (debug)
        strcat (cmdline, " --debug");
      if (with_progress)
        strcat (cmdline, " --progress");
      strcat (cmdline, " ");
      strcat (cmdline, options[idx]);
      if (system (cmdline))
        die ("running '%s' failed\n", cmdline);
    }

  free (cmdline);
}

int
main (int argc, char **argv)
{
  int last_argc = -1;
  int early_rng = 0;
  int in_recursion = 0;
  const char *program = NULL;

  if (argc)
    {
      program = *argv;
      argc--; argv++;
    }
  else
    die ("argv[0] missing\n");

  while (argc && last_argc != argc )
    {
      last_argc = argc;
      if (!strcmp (*argv, "--"))
        {
          argc--; argv++;
          break;
        }
      else if (!strcmp (*argv, "--help"))
        {
          fputs ("usage: random [options]\n", stdout);
          exit (0);
        }
      else if (!strcmp (*argv, "--verbose"))
        {
          verbose = 1;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--debug"))
        {
          debug = verbose = 1;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--progress"))
        {
          argc--; argv++;
          with_progress = 1;
        }
      else if (!strcmp (*argv, "--in-recursion"))
        {
          in_recursion = 1;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--early-rng-check"))
        {
          early_rng = 1;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--prefer-standard-rng"))
        {
          /* This is anyway the default, but we may want to use it for
             debugging. */
          gcry_control (GCRYCTL_SET_PREFERRED_RNG_TYPE, GCRY_RNG_TYPE_STANDARD);
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--prefer-fips-rng"))
        {
          gcry_control (GCRYCTL_SET_PREFERRED_RNG_TYPE, GCRY_RNG_TYPE_FIPS);
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--prefer-system-rng"))
        {
          gcry_control (GCRYCTL_SET_PREFERRED_RNG_TYPE, GCRY_RNG_TYPE_SYSTEM);
          argc--; argv++;
        }
    }

#ifndef HAVE_W32_SYSTEM
  signal (SIGPIPE, SIG_IGN);
#endif

  if (early_rng)
    check_early_rng_type_switching ();

  gcry_control (GCRYCTL_DISABLE_SECMEM, 0);
  if (!gcry_check_version (GCRYPT_VERSION))
    die ("version mismatch\n");

  if (with_progress)
    gcry_set_progress_handler (progress_cb, NULL);

  gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
  if (debug)
    gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1u, 0);

  if (!in_recursion)
    {
      check_forking ();
      check_nonce_forking ();
      check_close_random_device ();
    }
  check_drbg_reinit ();
  check_rng_type_switching ();

  if (!in_recursion)
    run_all_rng_tests (program);

  return 0;
}