summaryrefslogtreecommitdiff
path: root/src/getrandom.c
blob: f9bb5c0c5fc6f76f2d662020ded5af5dddd3ff4d (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
/* getrandom.c - Libgcrypt Random Number client
 * Copyright (C) 2006 Free Software Foundation, Inc.
 *
 * Getrandom 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.
 *
 * Getrandom 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., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */

#include <config.h>
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdarg.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <errno.h>

#define PGM "getrandom"
#define MYVERSION_LINE PGM " (Libgcrypt) " VERSION
#define BUGREPORT_LINE "\nReport bugs to <bug-libgcrypt@gnupg.org>.\n"


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

  va_start (arg_ptr, format) ;
  fputs (PGM ": ", stderr);
  vfprintf (stderr, format, arg_ptr);
  putc ('\n', stderr);
  va_end (arg_ptr);
}


/* Send LENGTH bytes of BUFFER to file descriptor FD.  Returns 0 on
   success or another value on write error. */
static int
writen (int fd, const void *buffer, size_t length)
{
  while (length)
    {
      ssize_t n;

      do
        n = write (fd, buffer, length);
      while (n < 0 && errno == EINTR);
      if (n < 0)
         {
           logit ("write error: %s", strerror (errno));
           return -1; /* write error */
         }
      length -= n;
      buffer = (const char *)buffer + n;
    }
  return 0;  /* Okay */
}




static void
print_version (int with_help)
{
  fputs (MYVERSION_LINE "\n"
         "Copyright (C) 2006 Free Software Foundation, Inc.\n"
         "License GPLv2+: GNU GPL version 2 or later "
         "<http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>\n"
         "This is free software: you are free to change and redistribute it.\n"
         "There is NO WARRANTY, to the extent permitted by law.\n",
         stdout);

  if (with_help)
    fputs ("\n"
           "Usage: " PGM " [OPTIONS] NBYTES\n"
           "Connect to libgcrypt's random number daemon and "
           "return random numbers"
           "\n"
           "  --nonce       Return weak random suitable for a nonce\n"
           "  --very-strong Return very strong random\n"
           "  --ping        Send a ping\n"
           "  --socket NAME Name of sockket to connect to\n"
           "  --hex         Return result as a hex dump\n"
           "  --verbose     Show what we are doing\n"
           "  --version     Print version of the program and exit\n"
           "  --help        Display this help and exit\n"
           BUGREPORT_LINE, stdout );

  exit (0);
}

static int
print_usage (void)
{
  fputs ("usage: " PGM " [OPTIONS] NBYTES\n", stderr);
  fputs ("       (use --help to display options)\n", stderr);
  exit (1);
}


int
main (int argc, char **argv)
{
  struct sockaddr_un *srvr_addr;
  socklen_t addrlen;
  int fd;
  int rc;
  unsigned char buffer[300];
  int nleft, nread;
  const char *socketname = "/var/run/libgcrypt/S.gcryptrnd";
  int do_ping = 0;
  int get_nonce = 0;
  int get_very_strong = 0;
  int req_nbytes, nbytes, n;
  int verbose = 0;
  int fail = 0;
  int do_hex = 0;

  if (argc)
    {
      argc--; argv++;
    }
  while (argc && **argv == '-' && (*argv)[1] == '-')
    {
      if (!(*argv)[2])
        {
          argc--; argv++;
          break;
        }
      else if (!strcmp (*argv, "--version"))
        print_version (0);
      else if (!strcmp (*argv, "--help"))
        print_version (1);
      else if (!strcmp (*argv, "--socket") && argc > 1 )
        {
          argc--; argv++;
          socketname = *argv;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--nonce"))
        {
          argc--; argv++;
          get_nonce = 1;
        }
      else if (!strcmp (*argv, "--very-strong"))
        {
          argc--; argv++;
          get_very_strong = 1;
        }
      else if (!strcmp (*argv, "--ping"))
        {
          argc--; argv++;
          do_ping = 1;
        }
      else if (!strcmp (*argv, "--hex"))
        {
          argc--; argv++;
          do_hex = 1;
        }
      else if (!strcmp (*argv, "--verbose"))
        {
          argc--; argv++;
          verbose = 1;
        }
      else
        print_usage ();
    }


  if (!argc && do_ping)
    ; /* This is allowed. */
  else if (argc != 1)
    print_usage ();
  req_nbytes = argc? atoi (*argv) : 0;

  if (req_nbytes < 0)
    print_usage ();

  /* Create a socket. */
  fd = socket (AF_UNIX, SOCK_STREAM, 0);
  if (fd == -1)
    {
      logit ("can't create socket: %s", strerror (errno));
      exit (1);
    }
  srvr_addr = malloc (sizeof *srvr_addr);
  if (!srvr_addr)
    {
      logit ("malloc failed: %s", strerror (errno));
      exit (1);
    }
  memset (srvr_addr, 0, sizeof *srvr_addr);
  srvr_addr->sun_family = AF_UNIX;
  if (strlen (socketname) + 1 >= sizeof (srvr_addr->sun_path))
    {
      logit ("socket name `%s' too long", socketname);
      exit (1);
    }
  strcpy (srvr_addr->sun_path, socketname);
  addrlen = (offsetof (struct sockaddr_un, sun_path)
             + strlen (srvr_addr->sun_path) + 1);
  rc = connect (fd, (struct sockaddr*) srvr_addr, addrlen);
  if (rc == -1)
    {
      logit ("error connecting socket `%s': %s",
             srvr_addr->sun_path, strerror (errno));
      close (fd);
      exit (1);
    }

  do
    {
      nbytes = req_nbytes > 255? 255 : req_nbytes;
      req_nbytes -= nbytes;

      buffer[0] = 3;
      if (do_ping)
        buffer[1] = 0;
      else if (get_nonce)
        buffer[1] = 10;
      else if (get_very_strong)
        buffer[1] = 12;
      else
        buffer[1] = 11;
      buffer[2] = nbytes;
      if (writen (fd, buffer, 3))
        fail = 1;
      else
        {
          for (nleft=2, nread=0; nleft > 0; )
            {
              do
                n = read (fd, buffer+nread, nleft);
              while (n < 0 && errno == EINTR);
              if (n < 0)
                {
                  logit ("read error: %s", strerror (errno));
                  exit (1);
                }
              nleft -= n;
              nread += n;
              if (nread && buffer[0])
                {
                  logit ("server returned error code %d", buffer[0]);
                  exit (1);
                }
            }
          if (verbose)
            logit ("received response with %d bytes of data", buffer[1]);
          if (buffer[1] < nbytes)
            {
              logit ("warning: server returned less bytes than requested");
              fail = 1;
            }
          else if (buffer[1] > nbytes && !do_ping)
            {
              logit ("warning: server returned more bytes than requested");
              fail = 1;
            }
          nbytes = buffer[1];
          if (nbytes > sizeof buffer)
            {
              logit ("buffer too short to receive data");
              exit (1);
            }

          for (nleft=nbytes, nread=0; nleft > 0; )
            {
              do
                n = read (fd, buffer+nread, nleft);
              while (n < 0 && errno == EINTR);
              if (n < 0)
                {
                  logit ("read error: %s", strerror (errno));
                  exit (1);
                }
              nleft -= n;
              nread += n;
            }

          if (do_hex)
            {
              for (n=0; n < nbytes; n++)
                {
                  if (!n)
                    ;
                  else if (!(n % 16))
                    putchar ('\n');
                  else
                    putchar (' ');
                  printf ("%02X", buffer[n]);
                }
              if (nbytes)
                putchar ('\n');
            }
          else
            {
              if (fwrite (buffer, nbytes, 1, stdout) != 1)
                {
                  logit ("error writing to stdout: %s", strerror (errno));
                  fail = 1;
                }
            }
        }
    }
  while (!fail && req_nbytes);

  close (fd);
  free (srvr_addr);
  return fail? 1 : 0;
}