File: crypto.c

package info (click to toggle)
libnbd 1.22.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 10,636 kB
  • sloc: ansic: 53,855; ml: 12,311; sh: 8,499; python: 4,595; makefile: 2,902; perl: 165; cpp: 24
file content (843 lines) | stat: -rw-r--r-- 21,355 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
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
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
/* NBD client library in userspace
 * Copyright Red Hat
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; 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 <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <assert.h>

#ifdef HAVE_GNUTLS
#include <gnutls/gnutls.h>

/* See comment in configure.ac */
#ifdef HAVE_GNUTLS_SOCKET_H
#include <gnutls/socket.h>
#endif
#endif

#include "internal.h"
#include "nbdkit-string.h"

int
nbd_unlocked_set_tls (struct nbd_handle *h, int tls)
{
#ifdef HAVE_GNUTLS
  h->tls = tls;
  return 0;
#else
  /* Don't allow setting this to any non-zero value, but setting it to
   * 0 (disable TLS) is OK.
   */
  if (tls != 0) {
    set_error (ENOTSUP, "libnbd was compiled without TLS support");
    return -1;
  }
  return 0;
#endif
}

/* NB: may_set_error = false. */
int
nbd_unlocked_get_tls (struct nbd_handle *h)
{
  return h->tls;
}

int
nbd_unlocked_get_tls_negotiated (struct nbd_handle *h)
{
  return h->tls_negotiated;
}

int
nbd_unlocked_set_tls_certificates (struct nbd_handle *h, const char *dir)
{
  char *new_dir;

  new_dir = strdup (dir);
  if (!new_dir) {
    set_error (errno, "strdup");
    return -1;
  }
  free (h->tls_certificates);
  h->tls_certificates = new_dir;
  return 0;
}

/* NB: may_set_error = false. */
int
nbd_unlocked_set_tls_verify_peer (struct nbd_handle *h, bool verify)
{
  h->tls_verify_peer = verify;
  return 0;
}

int
nbd_unlocked_get_tls_verify_peer (struct nbd_handle *h)
{
  return h->tls_verify_peer;
}

int
nbd_unlocked_set_tls_username (struct nbd_handle *h, const char *username)
{
  char *new_user;

  new_user = strdup (username);
  if (!new_user) {
    set_error (errno, "strdup");
    return -1;
  }
  free (h->tls_username);
  h->tls_username = new_user;
  return 0;
}

char *
nbd_unlocked_get_tls_username (struct nbd_handle *h)
{
  char *s, *ret;
  string str = empty_vector;

  if (h->tls_username) {
    ret = strdup (h->tls_username);
    if (ret == NULL) {
      set_error (errno, "strdup");
      return NULL;
    }
    return ret;
  }

  /* Otherwise we return the local login name.  Try $LOGNAME first for
   * two reasons: (1) So the user can override it.  (2) Because
   * getlogin fails with ENXIO if there is no controlling terminal
   * (which is often the case in test and embedded environments).
   */
  s = getenv ("LOGNAME");
  if (s) {
    ret = strdup (s);
    if (ret == NULL) {
      set_error (errno, "strdup");
      return NULL;
    }
    return ret;
  }

  for (;;) {
    /* Increase capacity (str.cap starts at 0) */
    if (string_reserve (&str, 16) == -1) {
      set_error (errno, "realloc");
      free (str.ptr);
      return NULL;
    }

    if (getlogin_r (str.ptr, str.cap) == 0) {
      return str.ptr;
    }

    if (errno != ERANGE) {
      set_error (errno, "getlogin_r");
      free (str.ptr);
      return NULL;
    }
  }
}

int
nbd_unlocked_set_tls_hostname (struct nbd_handle *h, const char *hostname)
{
  char *new_hostname;

  new_hostname = strdup (hostname);
  if (!new_hostname) {
    set_error (errno, "strdup");
    return -1;
  }
  free (h->tls_hostname);
  h->tls_hostname = new_hostname;
  return 0;
}

static const char *
get_tls_hostname (struct nbd_handle *h)
{
  if (h->tls_hostname)
    return h->tls_hostname;
  else if (h->hostname)
    return h->hostname;
  else
    return NULL;
}

char *
nbd_unlocked_get_tls_hostname (struct nbd_handle *h)
{
  const char *hostname = get_tls_hostname (h);
  char *ret;

  if (hostname)
    ret = strdup (hostname);
  else
    /* Otherwise, return "" (not an error). */
    ret = strdup ("");

  if (ret == NULL) {
    set_error (errno, "strdup");
    return NULL;
  }
  return ret;
}

int
nbd_unlocked_set_tls_psk_file (struct nbd_handle *h, const char *filename)
{
  char *new_file;

  new_file = strdup (filename);
  if (!new_file) {
    set_error (errno, "strdup");
    return -1;
  }
  free (h->tls_psk_file);
  h->tls_psk_file = new_file;
  return 0;
}

#ifdef HAVE_GNUTLS

static ssize_t
tls_recv (struct nbd_handle *h, struct socket *sock, void *buf, size_t len)
{
  ssize_t r;

  r = gnutls_record_recv (sock->u.tls.session, buf, len);
  if (r < 0) {
    if (r == GNUTLS_E_INTERRUPTED || r == GNUTLS_E_AGAIN) {
      errno = EAGAIN;
      return -1;
    }
    if (h->tls_shut_writes &&
        (r == GNUTLS_E_PULL_ERROR || r == GNUTLS_E_PREMATURE_TERMINATION)) {
      /* qemu-nbd doesn't call gnutls_bye to cleanly shut down the
       * connection after we send NBD_CMD_DISC, instead it simply
       * closes the connection.  On the client side we see
       * "gnutls_record_recv: The TLS connection was non-properly
       * terminated" or "gnutls_record_recv: Error in the pull
       * function.".
       *
       * If we see these errors after we shut down the write side
       * (h->tls_shut_writes), which happens after we have sent
       * NBD_CMD_DISC on the wire, downgrade them to a debug message.
       */
      debug (h, "gnutls_record_recv: %s", gnutls_strerror (r));
      return 0; /* EOF */
    }
    set_error (0, "gnutls_record_recv: %s", gnutls_strerror (r));
    errno = EIO;
    return -1;
  }
  return r;
}

static ssize_t
tls_send (struct nbd_handle *h,
          struct socket *sock, const void *buf, size_t len, int flags)
{
  ssize_t r;

  r = gnutls_record_send (sock->u.tls.session, buf, len);
  if (r < 0) {
    if (r == GNUTLS_E_INTERRUPTED || r == GNUTLS_E_AGAIN) {
      errno = EAGAIN;
      return -1;
    }
    set_error (0, "gnutls_record_send: %s", gnutls_strerror (r));
    errno = EIO;
    return -1;
  }
  return r;
}

static bool
tls_pending (struct socket *sock)
{
  return gnutls_record_check_pending (sock->u.tls.session) > 0;
}

static int
tls_get_fd (struct socket *sock)
{
  return sock->u.tls.oldsock->ops->get_fd (sock->u.tls.oldsock);
}

static bool
tls_shut_writes (struct nbd_handle *h, struct socket *sock)
{
  int r = gnutls_bye (sock->u.tls.session, GNUTLS_SHUT_WR);

  if (r == GNUTLS_E_AGAIN || r == GNUTLS_E_INTERRUPTED)
    return false;
  if (r != 0)
    debug (h, "ignoring gnutls_bye failure: %s", gnutls_strerror (r));
  h->tls_shut_writes = true;
  return sock->u.tls.oldsock->ops->shut_writes (h, sock->u.tls.oldsock);
}

/* XXX Calling gnutls_bye(GNUTLS_SHUT_RDWR) is possible, but it may send
 * and receive data over the wire which would require further modifications
 * to the state machine.  So instead we abruptly drop the TLS session.
 */
static int
tls_close (struct socket *sock)
{
  int r;

  r = sock->u.tls.oldsock->ops->close (sock->u.tls.oldsock);
  gnutls_deinit (sock->u.tls.session);
  if (sock->u.tls.pskcreds)
    gnutls_psk_free_client_credentials (sock->u.tls.pskcreds);
  if (sock->u.tls.xcreds)
    gnutls_certificate_free_credentials (sock->u.tls.xcreds);
  free (sock);
  return r;
}

static struct socket_ops crypto_ops = {
  .recv = tls_recv,
  .send = tls_send,
  .pending = tls_pending,
  .get_fd = tls_get_fd,
  .shut_writes = tls_shut_writes,
  .close = tls_close,
};

/* Look up the user's key in the PSK file. */
static int
lookup_key (const char *pskfile, const char *username,
            gnutls_datum_t *key)
{
  FILE *fp;
  const size_t ulen = strlen (username);
  size_t len = 0;
  ssize_t r;
  char *line = NULL;

  fp = fopen (pskfile, "re");
  if (fp == NULL) {
    set_error (errno, "open: %s", pskfile);
    goto error;
  }
  while ((r = getline (&line, &len, fp)) != -1) {
    if (r > 0 && line[r-1] == '\n') line[--r] = '\0';
    if (r > 0 && line[r-1] == '\r') line[--r] = '\0';

    if (r > ulen+1 &&
        strncmp (line, username, ulen) == 0 &&
        line[ulen] == ':') {
      key->data = (unsigned char *)strdup (&line[ulen+1]);
      if (key->data == NULL) {
        set_error (errno, "strdup");
        goto error;
      }
      key->size = r - ulen - 1;
      break;
    }
  }
  if (ferror (fp)) {
    set_error (errno, "%s: getline failed", pskfile);
    goto error;
  }

  if (key->data == NULL) {
    set_error (EINVAL, "%s: username %s was not found in PSK file",
               pskfile, username);
    goto error;
  }

  fclose (fp);
  free (line);
  return 0;

 error:
  if (fp)
    fclose (fp);
  free (line);
  return -1;
}

static gnutls_psk_client_credentials_t
set_up_psk_credentials (struct nbd_handle *h, gnutls_session_t session)
{
  int err;
  const char prio[] = TLS_PRIORITY ":" "+ECDHE-PSK:+DHE-PSK:+PSK";
  gnutls_datum_t key = { .data = NULL };
  char *username = NULL;
  gnutls_psk_client_credentials_t ret = NULL;

  err = gnutls_priority_set_direct (session, prio, NULL);
  if (err < 0) {
    set_error (0, "gnutls_priority_set_direct: %s", gnutls_strerror (err));
    goto error;
  }

  username = nbd_unlocked_get_tls_username (h);
  if (username == NULL)
    goto error;

  if (lookup_key (h->tls_psk_file, username, &key) == -1)
    goto error;

  err = gnutls_psk_allocate_client_credentials (&ret);
  if (err < 0) {
    set_error (0, "gnutls_psk_allocate_client_credentials: %s",
               gnutls_strerror (err));
    goto error;
  }
  err = gnutls_psk_set_client_credentials (ret, username,
                                           &key, GNUTLS_PSK_KEY_HEX);
  if (err < 0) {
    set_error (0, "gnutls_psk_set_client_credentials: %s",
               gnutls_strerror (err));
    goto error;
  }

  err = gnutls_credentials_set (session, GNUTLS_CRD_PSK, ret);
  if (err < 0) {
    set_error (0, "gnutls_credentials_set: %s", gnutls_strerror (err));
    goto error;
  }

  free (username);
  free (key.data);
  return ret;

 error:
  free (username);
  free (key.data);
  if (ret)
    gnutls_psk_free_client_credentials (ret);
  return NULL;
}

static int
load_certificates (const char *path, gnutls_certificate_credentials_t *ret)
{
  int err;
  char *cacert = NULL;
  char *clientcert = NULL;
  char *clientkey = NULL;
  char *cacrl = NULL;

  if (asprintf (&cacert, "%s/ca-cert.pem", path) == -1) {
    set_error (errno, "asprintf");
    goto error;
  }
  /* Only ca-cert.pem must be present. */
  if (access (cacert, R_OK) == -1) {
    free (cacert);
    return 0;
  }

  if (asprintf (&clientcert, "%s/client-cert.pem", path) == -1) {
    set_error (errno, "asprintf");
    goto error;
  }
  if (asprintf (&clientkey, "%s/client-key.pem", path) == -1) {
    set_error (errno, "asprintf");
    goto error;
  }
  if (asprintf (&cacrl, "%s/ca-crl.pem", path) == -1) {
    set_error (errno, "asprintf");
    goto error;
  }

  err = gnutls_certificate_allocate_credentials (ret);
  if (err < 0) {
    set_error (0, "gnutls_certificate_allocate_credentials: %s",
               gnutls_strerror (err));
    goto error;
  }

  err = gnutls_certificate_set_x509_trust_file (*ret, cacert,
                                                GNUTLS_X509_FMT_PEM);
  if (err < 0) {
    set_error (0, "gnutls_certificate_set_x509_trust_file: %s: %s",
               cacert, gnutls_strerror (err));
    goto error;
  }

  /* Optional for client certification authentication. */
  if (access (clientcert, R_OK) == 0 && access (clientkey, R_OK) == 0) {
    err = gnutls_certificate_set_x509_key_file (*ret, clientcert, clientkey,
                                                GNUTLS_X509_FMT_PEM);
    if (err < 0) {
      set_error (0, "gnutls_certificate_set_x509_key_file: %s, %s: %s",
                 clientcert, clientkey, gnutls_strerror (err));
      goto error;
    }
  }

  if (access (cacrl, R_OK) == 0) {
    err = gnutls_certificate_set_x509_crl_file (*ret, cacrl,
                                                GNUTLS_X509_FMT_PEM);
    if (err < 0) {
      set_error (0, "gnutls_certificate_set_x509_crl_file: %s: %s",
                 cacrl, gnutls_strerror (err));
      goto error;
    }
  }

  free (cacert);
  free (clientcert);
  free (clientkey);
  free (cacrl);
  return 0;

 error:
  if (*ret)
    gnutls_certificate_free_credentials (*ret);
  *ret = NULL;
  free (cacert);
  free (clientcert);
  free (clientkey);
  free (cacrl);
  return -1;
}

static gnutls_certificate_credentials_t
set_up_certificate_credentials (struct nbd_handle *h,
                                gnutls_session_t session, bool *is_error)
{
  int err;
  gnutls_certificate_credentials_t ret = NULL;
  const char *home = getenv ("HOME");
  char *path = NULL;

  err = gnutls_priority_set_direct (session, TLS_PRIORITY, NULL);
  if (err < 0) {
    set_error (0, "gnutls_priority_set_direct: %s", gnutls_strerror (err));
    goto error;
  }

  /* Try to load the certificates from the directory. */
  if (h->tls_certificates) {
    if (load_certificates (h->tls_certificates, &ret) == -1)
      goto error;
    if (ret)
      goto found_certificates;
  }
  else {
    if (geteuid () != 0 && home != NULL) {
      if (asprintf (&path, "%s/.pki/%s", home, PACKAGE_NAME) == -1) {
        set_error (errno, "asprintf");
        goto error;
      }
      if (load_certificates (path, &ret) == -1)
        goto error;
      if (ret)
        goto found_certificates;
      free (path);
      if (asprintf (&path, "%s/.config/pki/%s", home, PACKAGE_NAME) == -1) {
        set_error (errno, "asprintf");
        goto error;
      }
      if (load_certificates (path, &ret) == -1)
        goto error;
      if (ret)
        goto found_certificates;
    }
    else { /* geteuid () == 0 */
      if (load_certificates (sysconfdir "/pki/" PACKAGE_NAME, &ret) == -1)
        goto error;
      if (ret)
        goto found_certificates;
    }
  }

  /* Not found. */
  free (path);
  return NULL;

 found_certificates:
  err = gnutls_credentials_set (session, GNUTLS_CRD_CERTIFICATE, ret);
  if (err < 0) {
    set_error (0, "gnutls_credentials_set: %s", gnutls_strerror (err));
    goto error;
  }

  free (path);
  return ret;

 error:
  gnutls_certificate_free_credentials (ret);
  free (path);
  *is_error = true;
  return NULL;
}

static gnutls_certificate_credentials_t
set_up_system_CA (struct nbd_handle *h, gnutls_session_t session)
{
  int err;
  gnutls_certificate_credentials_t ret = NULL;

  err = gnutls_priority_set_direct (session, TLS_PRIORITY, NULL);
  if (err < 0) {
    set_error (0, "gnutls_priority_set_direct: %s", gnutls_strerror (err));
    return NULL;
  }

  err = gnutls_certificate_allocate_credentials (&ret);
  if (err < 0) {
    set_error (0, "gnutls_certificate_allocate_credentials: %s",
               gnutls_strerror (err));
    return NULL;
  }

  err = gnutls_certificate_set_x509_system_trust (ret);
  if (err < 0) {
    set_error (0, "gnutls_certificate_set_x509_system_trust: %s",
               gnutls_strerror (err));
    gnutls_certificate_free_credentials (ret);
    return NULL;
  }

  err = gnutls_credentials_set (session, GNUTLS_CRD_CERTIFICATE, ret);
  if (err < 0) {
    set_error (0, "gnutls_credentials_set: %s", gnutls_strerror (err));
    gnutls_certificate_free_credentials (ret);
    return NULL;
  }

  return ret;
}

/* Called from the state machine after receiving an ACK from
 * NBD_OPT_STARTTLS when we want to start upgrading the connection to
 * TLS.  Allocate and initialize the TLS session and set up the socket
 * ops.
 */
struct socket *
nbd_internal_crypto_create_session (struct nbd_handle *h,
                                    struct socket *oldsock)
{
  int err;
  struct socket *sock;
  gnutls_session_t session;
  gnutls_psk_client_credentials_t pskcreds = NULL;
  gnutls_certificate_credentials_t xcreds = NULL;
  unsigned init_flags;

  init_flags = GNUTLS_CLIENT | GNUTLS_NONBLOCK;
#ifdef GNUTLS_NO_SIGNAL
  init_flags |= GNUTLS_NO_SIGNAL;
#endif
  err = gnutls_init (&session, init_flags);
  if (err < 0) {
    set_error (errno, "gnutls_init: %s", gnutls_strerror (err));
    return NULL;
  }

  /* If we have the server name, pass SNI. */
  if (h->hostname) {
    err = gnutls_server_name_set (session, GNUTLS_NAME_DNS,
                                  h->hostname, strlen (h->hostname));
    if (err < 0) {
      set_error (errno, "gnutls_server_name_set: %s", gnutls_strerror (err));
      gnutls_deinit (session);
      return NULL;
    }
  }

  if (h->tls_psk_file) {
    pskcreds = set_up_psk_credentials (h, session);
    if (pskcreds == NULL) {
      gnutls_deinit (session);
      return NULL;
    }
  }
  else {
    bool is_error = false;

    xcreds = set_up_certificate_credentials (h, session, &is_error);
    if (xcreds == NULL) {
      if (!is_error) {
        /* Fallback case: use system CA. */
        xcreds = set_up_system_CA (h, session);
        if (xcreds == NULL)
          is_error = true;
      }
    }

    if (is_error) {
      gnutls_deinit (session);
      return NULL;
    }

    if (h->tls_verify_peer) {
      /* Verify the server certificate using h->tls_hostname, falling
       * back to h->hostname.
       */
      const char *hostname = get_tls_hostname (h);
      gnutls_session_set_verify_cert (session, hostname, 0);
    }
  }

  /* Wrap the underlying socket with GnuTLS. */
  gnutls_transport_set_int (session, oldsock->ops->get_fd (oldsock));

  gnutls_handshake_set_timeout (session,
                                GNUTLS_DEFAULT_HANDSHAKE_TIMEOUT);

  sock = malloc (sizeof *sock);
  if (sock == NULL) {
    set_error (errno, "malloc");
    gnutls_deinit (session);
    if (pskcreds)
      gnutls_psk_free_client_credentials (pskcreds);
    if (xcreds)
      gnutls_certificate_free_credentials (xcreds);
    return NULL;
  }
  sock->u.tls.session = session;
  sock->u.tls.pskcreds = pskcreds;
  sock->u.tls.xcreds = xcreds;
  sock->u.tls.oldsock = oldsock;
  sock->ops = &crypto_ops;
  return sock;
}

/* Return the read/write direction. */
bool
nbd_internal_crypto_is_reading (struct nbd_handle *h)
{
  assert (h->sock->u.tls.session);
  return gnutls_record_get_direction (h->sock->u.tls.session) == 0;
}

/* Continue with the TLS handshake.  Returns 0 if the handshake
 * completed successfully, 1 if the handshake is continuing, and -1 if
 * there was a GnuTLS error.
 */
int
nbd_internal_crypto_handshake (struct nbd_handle *h)
{
  int err;
  gnutls_handshake_description_t in, out;
  const gnutls_session_t session = h->sock->u.tls.session;

  assert (session);
  err = gnutls_handshake (session);
  if (err == 0)
    return 0;
  if (!gnutls_error_is_fatal (err))
    return 1;

  /* Get some additional debug information about where in the
   * handshake protocol it failed.  You have to look up these codes in
   * <gnutls/gnutls.h>.
   */
  in = gnutls_handshake_get_last_in (session);
  out = gnutls_handshake_get_last_out (session);
  set_error (0, "gnutls_handshake: %s (%d/%d)",
             gnutls_strerror (err), (int)in, (int)out);
  return -1;
}

/* The state machine calls this when TLS has definitely been enabled
 * on the connection (after the handshake), and we use it to print
 * useful debugging information.
 */
void
nbd_internal_crypto_debug_tls_enabled (struct nbd_handle *h)
{
  if_debug (h) {
    const gnutls_session_t session = h->sock->u.tls.session;
    const gnutls_cipher_algorithm_t cipher = gnutls_cipher_get (session);
    const gnutls_kx_algorithm_t kx = gnutls_kx_get (session);
    const gnutls_mac_algorithm_t mac = gnutls_mac_get (session);
#ifdef HAVE_GNUTLS_TRANSPORT_IS_KTLS_ENABLED
    const char *ktls_status;
    gnutls_transport_ktls_enable_flags_t ktls_enabled;
#else
    const char *ktls_status = "disabled";
#endif

#ifdef HAVE_GNUTLS_TRANSPORT_IS_KTLS_ENABLED
    ktls_enabled = gnutls_transport_is_ktls_enabled (session);
    switch (ktls_enabled) {
    case GNUTLS_KTLS_RECV: ktls_status = "enabled receive only"; break;
    case GNUTLS_KTLS_SEND: ktls_status = "enabled send only"; break;
    case GNUTLS_KTLS_DUPLEX: ktls_status = "enabled"; break;
    default:
      if ((int)ktls_enabled == 0)
        ktls_status = "disabled";
      else
        ktls_status = "unknown";
    }
#endif

    debug (h,
           "connection is using TLS: "
           "cipher %s (%zu bits) key exchange %s mac %s (%zu bits) kTLS %s",
           gnutls_cipher_get_name (cipher),
           8 * gnutls_cipher_get_key_size (cipher),
           gnutls_kx_get_name (kx),
           gnutls_mac_get_name (mac),
           8 * gnutls_mac_get_key_size (mac),
           ktls_status
           );
  }
}

#else /* !HAVE_GNUTLS */

/* These functions should never be called from the state machine if
 * !HAVE_GNUTLS.
 */
struct socket *
nbd_internal_crypto_create_session (struct nbd_handle *h,
                                    struct socket *oldsock)
{
  abort ();
}

bool
nbd_internal_crypto_is_reading (struct nbd_handle *h)
{
  abort ();
}

int
nbd_internal_crypto_handshake (struct nbd_handle *h)
{
  abort ();
}

void
nbd_internal_crypto_debug_tls_enabled (struct nbd_handle *h)
{
  abort ();
}

#endif /* !HAVE_GNUTLS */