File: crypto-gnutls.c

package info (click to toggle)
nbd 1:3.20-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 5,960 kB
  • sloc: ansic: 7,494; sh: 6,496; makefile: 147
file content (627 lines) | stat: -rw-r--r-- 14,720 bytes parent folder | download | duplicates (2)
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
/*

The MIT License (MIT)

Copyright (c) 2016 Wrymouth Innovation Ltd

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

*/

#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <string.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>

#include <gnutls/gnutls.h>
#include <gnutls/crypto.h>
#include <gnutls/x509.h>
#include <gnutls/abstract.h>

#include "crypto-gnutls.h"
#include "buffer.h"

#define MAX_CERTS 10

#define FALSE 0
#define TRUE 1

#define PRIORITY "NORMAL:-VERS-TLS-ALL:+VERS-TLS1.2"

struct tlssession
{
  gnutls_certificate_credentials_t creds;
  gnutls_session_t session;
  char *hostname;
  int (*quitfn) (void *opaque);
  int (*erroutfn) (void *opaque, const char *format, va_list ap);
  int debug;
  void *opaque;
};

#define BUF_SIZE 65536
#define BUF_HWM ((BUF_SIZE*3)/4)

static int
falsequit (void *opaque)
{
  return FALSE;
}

static int
quit (tlssession_t * s)
{
  return s->quitfn (s->opaque);
}


static int
stderrout (void *opaque, const char *format, va_list ap)
{
  return vfprintf (stderr, format, ap);
}

static int
errout (tlssession_t * s, const char *format, ...)
{
  va_list ap;
  int ret;
  va_start (ap, format);
  ret = s->erroutfn (s->opaque, format, ap);
  va_end (ap);
  return ret;
}

static int
debugout (tlssession_t * s, const char *format, ...)
{
  va_list ap;
  int ret = 0;
  va_start (ap, format);
  if (s->debug)
    ret = s->erroutfn (s->opaque, format, ap);
  va_end (ap);
  return ret;
}

static int
socksetnonblock (int fd, int nb)
{
  int sf = fcntl (fd, F_GETFL, 0);
  if (sf == -1)
    return -1;
  return fcntl (fd, F_SETFL, nb ? (sf | O_NONBLOCK) : (sf & ~O_NONBLOCK));
}

/* From (public domain) example file in GNUTLS
 *
 * This function will try to verify the peer's certificate, and
 * also check if the hostname matches, and the activation, expiration dates.
 */
static int
verify_certificate_callback (gnutls_session_t session)
{
  unsigned int status;
  const gnutls_datum_t *cert_list;
  unsigned int cert_list_size;
  int ret;
  gnutls_x509_crt_t cert;
  tlssession_t *s;

  /* read session pointer */
  s = (tlssession_t *) gnutls_session_get_ptr (session);

  /* This verification function uses the trusted CAs in the credentials
   * structure. So you must have installed one or more CA certificates.
   */
  ret = gnutls_certificate_verify_peers2 (session, &status);
  if (ret < 0)
    {
      debugout (s, "Could not verfify peer certificate due to an error\n");
      return GNUTLS_E_CERTIFICATE_ERROR;
    }

  if (status & GNUTLS_CERT_INVALID)
    debugout (s, "The certificate is not trusted.\n");

  if (status & GNUTLS_CERT_SIGNER_NOT_FOUND)
    debugout (s, "The certificate hasn't got a known issuer.\n");

  if (status & GNUTLS_CERT_REVOKED)
    debugout (s, "The certificate has been revoked.\n");

  if (status & GNUTLS_CERT_EXPIRED)
    debugout (s, "The certificate has expired\n");

  if (status & GNUTLS_CERT_NOT_ACTIVATED)
    debugout (s, "The certificate is not yet activated\n");

  if (status)
    return GNUTLS_E_CERTIFICATE_ERROR;

  if (gnutls_certificate_type_get (session) != GNUTLS_CRT_X509)
    return GNUTLS_E_CERTIFICATE_ERROR;

  if (gnutls_x509_crt_init (&cert) < 0)
    {
      debugout (s, "error in initialization\n");
      return GNUTLS_E_CERTIFICATE_ERROR;
    }

  cert_list = gnutls_certificate_get_peers (session, &cert_list_size);
  if (cert_list == NULL)
    {
      debugout (s, "No certificate was found!\n");
      return GNUTLS_E_CERTIFICATE_ERROR;
    }

  /* check only the first certificate - seems to be what curl does */
  if (gnutls_x509_crt_import (cert, &cert_list[0], GNUTLS_X509_FMT_DER) < 0)
    {
      debugout (s, "error parsing certificate\n");
      return GNUTLS_E_CERTIFICATE_ERROR;
    }

  if (s->hostname && *s->hostname)
    {
      if (!gnutls_x509_crt_check_hostname (cert, s->hostname))
	{
	  debugout (s,
		    "The certificate's owner does not match hostname '%s'\n",
		    s->hostname);
	  return GNUTLS_E_CERTIFICATE_ERROR;
	}
    }

  gnutls_x509_crt_deinit (cert);

  debugout (s, "Peer passed certificate verification\n");

  /* notify gnutls to continue handshake normally */
  return 0;
}

tlssession_t *
tlssession_new (int isserver,
		char *keyfile, char *certfile, char *cacertfile,
		char *hostname, int insecure, int debug,
		int (*quitfn) (void *opaque),
		int (*erroutfn) (void *opaque, const char *format,
				 va_list ap), void *opaque)
{
  int ret;
  tlssession_t *s = calloc (1, sizeof (tlssession_t));

  if (quitfn)
    s->quitfn = quitfn;
  else
    s->quitfn = falsequit;

  if (erroutfn)
    s->erroutfn = erroutfn;
  else
    s->erroutfn = stderrout;

  if (hostname)
    s->hostname = strdup (hostname);

  s->debug = debug;

  if (gnutls_certificate_allocate_credentials (&s->creds) < 0)
    {
      errout (s, "Certificate allocation memory error\n");
      goto error;
    }

  if (cacertfile != NULL)
    {
      ret =
	gnutls_certificate_set_x509_trust_file (s->creds, cacertfile,
						GNUTLS_X509_FMT_PEM);
      if (ret < 0)
	{
	  errout (s, "Error setting the x509 trust file: %s\n",
		  gnutls_strerror (ret));
	  goto error;
	}

      if (!insecure)
	{
	  gnutls_certificate_set_verify_function (s->creds,
						  verify_certificate_callback);
	  gnutls_certificate_set_verify_flags (s->creds,
					       GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT);
	}
    }

  if (keyfile && !certfile)
    certfile = keyfile;

  if (certfile != NULL && keyfile != NULL)
    {
      ret =
	gnutls_certificate_set_x509_key_file (s->creds, certfile, keyfile,
					      GNUTLS_X509_FMT_PEM);

      if (ret < 0)
	{
	  errout (s,
		  "Error loading certificate or key file (%s, %s): %s\n",
		  certfile, keyfile, gnutls_strerror (ret));
	  goto error;
	}
    }

  if (isserver)
    {
      ret = gnutls_init (&s->session, GNUTLS_SERVER);
    }
  else
    {
      ret = gnutls_init (&s->session, GNUTLS_CLIENT);
    }
  if (ret < 0)
    {
      errout (s, "Cannot initialize GNUTLS session: %s\n",
	      gnutls_strerror (ret));
      goto error;
    }

  gnutls_session_set_ptr (s->session, (void *) s);

  ret = gnutls_set_default_priority (s->session);
  if (ret < 0)
    {
      errout (s, "Cannot set default GNUTLS session priority: %s\n",
	      gnutls_strerror (ret));
      goto error;
    }

  const char *errpos = NULL;
  ret = gnutls_priority_set_direct (s->session, PRIORITY, &errpos);
  if (ret < 0)
    {
      errout (s, "Cannot set GNUTLS session priority: %s\n",
	      gnutls_strerror (ret));
      goto error;
    }

  gnutls_session_set_ptr (s->session, (void *) s);

  ret = gnutls_credentials_set (s->session, GNUTLS_CRD_CERTIFICATE, s->creds);
  if (ret < 0)
    {
      errout (s, "Cannot set session GNUTL credentials: %s\n",
	      gnutls_strerror (ret));
      goto error;
    }

  if (isserver)
    {
      /* requests but does not check a client certificate */
      gnutls_certificate_server_set_request (s->session, GNUTLS_CERT_REQUEST);
    }


  return s;

error:
  if (s->session)
    gnutls_deinit (s->session);
  free (s);
  return NULL;
}

void
tlssession_close (tlssession_t * s)
{
  if (s->session)
    gnutls_deinit (s->session);
  free (s->hostname);
  free (s);
}

int
tlssession_init ()
{
  return gnutls_global_init ();
}


int
tlssession_mainloop (int cryptfd, int plainfd, tlssession_t * s)
{
  fd_set readfds;
  fd_set writefds;
  int maxfd;
  int tls_wr_interrupted = 0;
  int plainEOF = FALSE;
  int cryptEOF = FALSE;
  int ret;

  buffer_t *plainToCrypt = bufNew (BUF_SIZE, BUF_HWM);
  buffer_t *cryptToPlain = bufNew (BUF_SIZE, BUF_HWM);

  if (socksetnonblock (cryptfd, 0) < 0)
    {
      errout (s, "Could not turn on blocking: %m");
      goto error;
    }

  /* set it up to work with our FD */
  gnutls_transport_set_ptr (s->session,
			    (gnutls_transport_ptr_t) (intptr_t) cryptfd);


  /* Now do the handshake */
  ret = gnutls_handshake (s->session);
  if (ret < 0)
    {
      errout (s, "TLS handshake failed: %s\n", gnutls_strerror (ret));
      goto error;
    }

  if (socksetnonblock (cryptfd, 1) < 0)
    {
      errout (s, "Could not turn on non-blocking on crypt FD: %m");
      goto error;
    }

  if (socksetnonblock (plainfd, 1) < 0)
    {
      errout (s, "Could not turn on non-blocking on plain FD: %m");
      goto error;
    }

  maxfd = (plainfd > cryptfd) ? plainfd + 1 : cryptfd + 1;

  while ((!plainEOF || !cryptEOF) && !quit (s))
    {
      struct timeval timeout;
      int result;
      int selecterrno;
      int wait = TRUE;

      FD_ZERO (&readfds);
      FD_ZERO (&writefds);

      size_t buffered = gnutls_record_check_pending (s->session);
      if (buffered)
	wait = FALSE;		/* do not wait for select to return if we have buffered data */

      if (plainEOF)
	{
	  /* plain text end has closed, but me may still have
	   * data yet to write to the crypt end */
	  if (bufIsEmpty (plainToCrypt) && !tls_wr_interrupted)
	    {
	      cryptEOF = TRUE;
	      break;
	    }
	}
      else
	{
	  if (!bufIsEmpty (cryptToPlain))
	    FD_SET (plainfd, &writefds);
	  if (!bufIsOverHWM (plainToCrypt))
	    FD_SET (plainfd, &readfds);
	}

      if (cryptEOF)
	{
	  /* crypt end has closed, but me way still have data to
	   * write from the crypt buffer */
	  if (bufIsEmpty (cryptToPlain) && !buffered)
	    {
	      plainEOF = TRUE;
	      break;
	    }
	}
      else
	{
	  if (!bufIsEmpty (plainToCrypt) || tls_wr_interrupted)
	    FD_SET (cryptfd, &writefds);
	  if (!bufIsOverHWM (cryptToPlain))
	    FD_SET (cryptfd, &readfds);
	}

      /* Repeat select whilst EINTR happens */
      do
	{
	  timeout.tv_sec = wait ? 1 : 0;
	  timeout.tv_usec = 0;
	  result = select (maxfd, &readfds, &writefds, NULL, &timeout);

	  selecterrno = errno;
	}
      while ((result == -1) && (selecterrno == EINTR) && !quit (s));
      if (quit (s))
	break;

      if (FD_ISSET (plainfd, &readfds))
	{
	  /* we can read at least one byte */
	  void *addr = NULL;
	  /* get a span of characters to write to the
	   * buffer. As the empty portion may wrap the end of the
	   * circular buffer this might not be all we could read.
	   */
	  ssize_t len = bufGetWriteSpan (plainToCrypt, &addr);
	  if (len > 0)
	    {
	      ssize_t ret;
	      do
		{
		  ret = read (plainfd, addr, (size_t) len);
		}
	      while ((ret < 0) && (errno == EINTR) && !quit (s));
	      if (quit (s))
		break;
	      if (ret < 0)
		{
		  errout (s, "Error on read from plain socket: %m\n");
		  goto error;
		}
	      if (ret == 0)
		{
		  plainEOF = TRUE;
		}
	      else
		{
		  bufDoneWrite (plainToCrypt, ret);	/* mark ret bytes as written to the buffer */
		}
	    }
	}

      if (FD_ISSET (plainfd, &writefds))
	{
	  /* we can write at least one byte */
	  void *addr = NULL;
	  /* get a span of characters to read from the buffer
	   * as the full portion may wrap the end of the circular buffer
	   * this might not be all we have to write.
	   */
	  ssize_t len = bufGetReadSpan (cryptToPlain, &addr);
	  if (len > 0)
	    {
	      ssize_t ret;
	      do
		{
		  ret = write (plainfd, addr, (size_t) len);
		}
	      while ((ret < 0) && (errno == EINTR) && !quit (s));
	      if (quit (s))
		break;
	      if (ret < 0)
		{
		  errout (s, "Error on write to plain socket: %m\n");
		  goto error;
		}
	      bufDoneRead (cryptToPlain, ret);	/* mark ret bytes as read from the buffer */
	    }
	}

      if (FD_ISSET (cryptfd, &readfds) || buffered)
	{
	  /* we can read at least one byte */
	  void *addr = NULL;
	  /* get a span of characters to write to the
	   * buffer. As the empty portion may wrap the end of the
	   * circular buffer this might not be all we could read.
	   */
	  ssize_t len = bufGetWriteSpan (cryptToPlain, &addr);
	  if (len > 0)
	    {
	      ssize_t ret;
	      do
		{
		  ret = gnutls_record_recv (s->session, addr, (size_t) len);
		}
	      while (ret == GNUTLS_E_INTERRUPTED && !quit (s));
	      /* do not loop on GNUTLS_E_AGAIN - this means we'd block so we'd loop for
	       * ever
	       */
	      if (quit (s))
		break;
	      if (ret < 0 && ret != GNUTLS_E_AGAIN)
		{
		  errout (s, "Error on read from crypt socket: %s\n",
			  gnutls_strerror (ret));
		  goto error;
		}
	      if (ret == 0)
		{
		  cryptEOF = TRUE;
		}
	      else
		{
		  bufDoneWrite (cryptToPlain, ret);	/* mark ret bytes as written to the buffer */
		}
	    }
	}

      if (FD_ISSET (cryptfd, &writefds))
	{
	  /* we can write at least one byte */
	  void *addr = NULL;
	  /* get a span of characters to read from the buffer
	   * as the full portion may wrap the end of the circular buffer
	   * this might not be all we have to write.
	   */
	  ssize_t len = bufGetReadSpan (plainToCrypt, &addr);
	  if (len > 0)
	    {
	      ssize_t ret;
	      do
		{
		  if (tls_wr_interrupted)
		    {
		      ret = gnutls_record_send (s->session, NULL, 0);
		    }
		  else
		    {
		      ret = gnutls_record_send (s->session, addr, len);
		    }
		}
	      while (ret == GNUTLS_E_INTERRUPTED && !quit (s));
	      if (quit (s))
		break;
	      if (ret == GNUTLS_E_AGAIN)
		{
		  /* we need to call this again with NULL parameters
		   * as it blocked
		   */
		  tls_wr_interrupted = TRUE;
		}
	      else if (ret < 0)
		{
		  errout (s, "Error on write to crypto socket: %s\n",
			  gnutls_strerror (ret));
		  goto error;
		}
	      else
		{
		  bufDoneRead (plainToCrypt, ret);	/* mark ret bytes as read from the buffer */
		}
	    }
	}
    }

  ret = 0;
  goto freereturn;

error:
  ret = -1;

freereturn:
  gnutls_bye (s->session, GNUTLS_SHUT_RDWR);
  shutdown (plainfd, SHUT_RDWR);
  bufFree (plainToCrypt);
  bufFree (cryptToPlain);
  return ret;
}