-
Notifications
You must be signed in to change notification settings - Fork 33
/
crypto.c
544 lines (471 loc) · 14.5 KB
/
crypto.c
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
/* nbdkit
* Copyright (C) 2017 Red Hat Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Red Hat nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY RED HAT AND CONTRIBUTORS ''AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL RED HAT OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdbool.h>
#include <inttypes.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <limits.h>
#include <errno.h>
#include <sys/types.h>
#include <assert.h>
#include "internal.h"
#ifdef HAVE_GNUTLS
#include <gnutls/gnutls.h>
static int crypto_auth;
#define CRYPTO_AUTH_CERTIFICATES 1
#define CRYPTO_AUTH_PSK 2
static gnutls_certificate_credentials_t x509_creds;
static gnutls_psk_server_credentials_t psk_creds;
static void print_gnutls_error (int err, const char *fs, ...)
__attribute__((format (printf, 2, 3)));
static void
print_gnutls_error (int err, const char *fs, ...)
{
va_list args;
fprintf (stderr, "%s: GnuTLS error: ", program_name);
va_start (args, fs);
vfprintf (stderr, fs, args);
va_end (args);
fprintf (stderr, ": %s\n", gnutls_strerror (err));
}
/* Try to load certificates from 'path'. Returns true if successful.
* If it's not a certicate directory it returns false. Exits on
* other errors.
*/
static int
load_certificates (const char *path)
{
CLEANUP_FREE char *ca_cert_filename = NULL;
CLEANUP_FREE char *server_cert_filename = NULL;
CLEANUP_FREE char *server_key_filename = NULL;
CLEANUP_FREE char *ca_crl_filename = NULL;
int err;
if (asprintf (&ca_cert_filename, "%s/ca-cert.pem", path) == -1) {
perror ("asprintf");
exit (EXIT_FAILURE);
}
if (asprintf (&server_cert_filename, "%s/server-cert.pem", path) == -1) {
perror ("asprintf");
exit (EXIT_FAILURE);
}
if (asprintf (&server_key_filename, "%s/server-key.pem", path) == -1) {
perror ("asprintf");
exit (EXIT_FAILURE);
}
if (asprintf (&ca_crl_filename, "%s/ca-crl.pem", path) == -1) {
perror ("asprintf");
exit (EXIT_FAILURE);
}
/* Our test for a certificate directory is that ca-cert.pem,
* server-cert.pem and server-key.pem must all exist in the path.
*/
if (access (ca_cert_filename, R_OK) == -1)
return 0;
if (access (server_cert_filename, R_OK) == -1)
return 0;
if (access (server_key_filename, R_OK) == -1)
return 0;
/* Any problem past here is a hard error. */
err = gnutls_certificate_allocate_credentials (&x509_creds);
if (err < 0) {
print_gnutls_error (err, "allocating credentials");
exit (EXIT_FAILURE);
}
err = gnutls_certificate_set_x509_trust_file (x509_creds, ca_cert_filename,
GNUTLS_X509_FMT_PEM);
if (err < 0) {
print_gnutls_error (err, "loading %s", ca_cert_filename);
exit (EXIT_FAILURE);
}
if (access (ca_crl_filename, R_OK) == 0) {
err = gnutls_certificate_set_x509_crl_file (x509_creds, ca_crl_filename,
GNUTLS_X509_FMT_PEM);
if (err < 0) {
print_gnutls_error (err, "loading %s", ca_crl_filename);
exit (EXIT_FAILURE);
}
}
err = gnutls_certificate_set_x509_key_file (x509_creds,
server_cert_filename,
server_key_filename,
GNUTLS_X509_FMT_PEM);
if (err < 0) {
print_gnutls_error (err, "loading server certificate and key (%s, %s)",
server_cert_filename, server_key_filename);
exit (EXIT_FAILURE);
}
debug ("successfully loaded TLS certificates from %s", path);
return 1;
}
static int
start_certificates (void)
{
/* Try to locate the certificates directory and load them. */
if (tls_certificates_dir == NULL) {
const char *home;
CLEANUP_FREE char *path = NULL;
if (geteuid () != 0) {
home = getenv ("HOME");
if (home) {
if (asprintf (&path, "%s/.pki/%s", home, PACKAGE_NAME) == -1) {
perror ("asprintf");
exit (EXIT_FAILURE);
}
if (load_certificates (path))
goto found_certificates;
free (path);
if (asprintf (&path, "%s/.config/pki/%s", home, PACKAGE_NAME) == -1) {
perror ("asprintf");
exit (EXIT_FAILURE);
}
if (load_certificates (path))
goto found_certificates;
}
}
else { /* geteuid () == 0 */
if (load_certificates (root_tls_certificates_dir))
goto found_certificates;
}
}
else {
if (load_certificates (tls_certificates_dir))
goto found_certificates;
}
return -1;
found_certificates:
#ifdef HAVE_GNUTLS_CERTIFICATE_SET_KNOWN_DH_PARAMS
gnutls_certificate_set_known_dh_params (x509_creds, GNUTLS_SEC_PARAM_MEDIUM);
#endif
return 0;
}
static int
start_psk (void)
{
int err;
CLEANUP_FREE char *abs_psk_file = NULL;
/* Make sure the path to the PSK file is absolute. */
abs_psk_file = realpath (tls_psk, NULL);
if (abs_psk_file == NULL) {
perror (tls_psk);
exit (EXIT_FAILURE);
}
err = gnutls_psk_allocate_server_credentials (&psk_creds);
if (err < 0) {
print_gnutls_error (err, "allocating PSK credentials");
exit (EXIT_FAILURE);
}
/* Note that this function makes a copy of the string.
* CLEANUP_FREE macro above will free abs_psk_file when
* we return, but this is safe.
*/
gnutls_psk_set_server_credentials_file (psk_creds, abs_psk_file);
return 0;
}
/* Initialize crypto. This also handles the command line parameters
* and loading the server certificate.
*/
void
crypto_init (int tls_set_on_cli)
{
int err, r;
const char *what;
err = gnutls_global_init ();
if (err < 0) {
print_gnutls_error (err, "initializing GnuTLS");
exit (EXIT_FAILURE);
}
if (tls == 0) /* --tls=off */
return;
/* --tls-psk overrides certificates. */
if (tls_psk != NULL) {
what = "Pre-Shared Keys (PSK)";
r = start_psk ();
if (r == 0)
crypto_auth = CRYPTO_AUTH_PSK;
}
else {
what = "X.509 certificates";
r = start_certificates ();
if (r == 0)
crypto_auth = CRYPTO_AUTH_CERTIFICATES;
}
if (r == 0) {
debug ("TLS enabled using: %s", what);
return;
}
/* If we get here, we didn't manage to load the PSK file /
* certificates. If --tls=require was given on the command line
* then that's a problem.
*/
if (tls == 2) { /* --tls=require */
fprintf (stderr,
"%s: --tls=require but could not load TLS certificates.\n"
"Try setting ‘--tls-certificates=/path/to/certificates’ or read\n"
"the \"TLS\" section in nbdkit(1).\n",
program_name);
exit (EXIT_FAILURE);
}
/* If --tls=on was given on the command line, warn before we turn
* TLS off.
*/
if (tls == 1 && tls_set_on_cli) { /* explicit --tls=on */
fprintf (stderr,
"%s: warning: --tls=on but could not load TLS certificates.\n"
"TLS will be disabled and TLS connections will be rejected.\n"
"Try setting ‘--tls-certificates=/path/to/certificates’ or read\n"
"the \"TLS\" section in nbdkit(1).\n",
program_name);
}
tls = 0;
debug ("TLS disabled: could not load TLS certificates");
}
void
crypto_free (void)
{
if (tls > 0) {
switch (crypto_auth) {
case CRYPTO_AUTH_CERTIFICATES:
gnutls_certificate_free_credentials (x509_creds);
break;
case CRYPTO_AUTH_PSK:
gnutls_psk_free_server_credentials (psk_creds);
break;
}
}
gnutls_global_deinit ();
}
/* Read buffer from GnuTLS and either succeed completely
* (returns > 0), read an EOF (returns 0), or fail (returns -1).
*/
static int
crypto_recv (struct connection *conn, void *vbuf, size_t len)
{
gnutls_session_t *session = connection_get_crypto_session (conn);
char *buf = vbuf;
ssize_t r;
bool first_read = true;
assert (session != NULL);
while (len > 0) {
r = gnutls_record_recv (*session, buf, len);
if (r < 0) {
if (r == GNUTLS_E_INTERRUPTED || r == GNUTLS_E_AGAIN)
continue;
nbdkit_error ("gnutls_record_recv: %s", gnutls_strerror (r));
errno = EIO;
return -1;
}
if (r == 0) {
if (first_read)
return 0;
/* Partial record read. This is an error. */
errno = EBADMSG;
return -1;
}
first_read = false;
buf += r;
len -= r;
}
return 1;
}
/* Write buffer to GnuTLS and either succeed completely
* (returns 0) or fail (returns -1).
*/
static int
crypto_send (struct connection *conn, const void *vbuf, size_t len)
{
gnutls_session_t *session = connection_get_crypto_session (conn);
const char *buf = vbuf;
ssize_t r;
assert (session != NULL);
while (len > 0) {
r = gnutls_record_send (*session, buf, len);
if (r < 0) {
if (r == GNUTLS_E_INTERRUPTED || r == GNUTLS_E_AGAIN)
continue;
return -1;
}
buf += r;
len -= r;
}
return 0;
}
/* There's no place in the NBD protocol to send back errors from
* close, so this function ignores errors.
*/
static void
crypto_close (struct connection *conn)
{
gnutls_session_t *session = connection_get_crypto_session (conn);
int sockin, sockout;
assert (session != NULL);
gnutls_transport_get_int2 (*session, &sockin, &sockout);
gnutls_bye (*session, GNUTLS_SHUT_RDWR);
if (sockin >= 0)
close (sockin);
if (sockout >= 0 && sockin != sockout)
close (sockout);
}
/* Upgrade an existing connection to TLS. Also this should do access
* control if enabled. The protocol code ensures this function can
* only be called once per connection.
*/
int
crypto_negotiate_tls (struct connection *conn, int sockin, int sockout)
{
gnutls_session_t *session;
CLEANUP_FREE char *priority = NULL;
int err;
/* Create the GnuTLS session. */
session = malloc (sizeof *session);
if (session == NULL) {
nbdkit_error ("malloc: %m");
return -1;
}
err = gnutls_init (session, GNUTLS_SERVER);
if (err < 0) {
nbdkit_error ("gnutls_init: %s", gnutls_strerror (err));
free (session);
return -1;
}
switch (crypto_auth) {
case CRYPTO_AUTH_CERTIFICATES:
/* Associate the session with the server credentials (key, cert). */
err = gnutls_credentials_set (*session, GNUTLS_CRD_CERTIFICATE,
x509_creds);
if (err < 0) {
nbdkit_error ("gnutls_credentials_set: %s", gnutls_strerror (err));
goto error;
}
/* If verify peer is enabled, tell GnuTLS to request the client
* certificates. (Note the default is to not request or verify
* certificates).
*/
if (tls_verify_peer) {
#ifdef HAVE_GNUTLS_SESSION_SET_VERIFY_CERT
gnutls_certificate_server_set_request (*session, GNUTLS_CERT_REQUEST);
gnutls_session_set_verify_cert (*session, NULL, 0);
#else
nbdkit_error ("--tls-verify-peer: GnuTLS >= 3.4.6 is required for this feature");
goto error;
#endif
}
priority = strdup (TLS_PRIORITY);
if (priority == NULL) {
nbdkit_error ("strdup: %m");
goto error;
}
break;
case CRYPTO_AUTH_PSK:
/* Associate the session with the server PSK credentials. */
err = gnutls_credentials_set (*session, GNUTLS_CRD_PSK, psk_creds);
if (err < 0) {
nbdkit_error ("gnutls_credentials_set: %s", gnutls_strerror (err));
goto error;
}
if (asprintf (&priority,
"%s:+ECDHE-PSK:+DHE-PSK:+PSK", TLS_PRIORITY) == -1) {
nbdkit_error ("asprintf: %m");
goto error;
}
break;
default:
abort ();
}
assert (priority != NULL);
err = gnutls_priority_set_direct (*session, priority, NULL);
if (err < 0) {
nbdkit_error ("failed to set TLS session priority to %s: %s",
priority, gnutls_strerror (err));
goto error;
}
/* Set up GnuTLS so it reads and writes on the raw sockets, and set
* up the connection recv/send/close functions so they call GnuTLS
* wrappers instead.
*/
gnutls_transport_set_int2 (*session, sockin, sockout);
connection_set_crypto_session (conn, session);
connection_set_recv (conn, crypto_recv);
connection_set_send (conn, crypto_send);
connection_set_close (conn, crypto_close);
/* Perform the handshake. */
debug ("starting TLS handshake");
gnutls_handshake_set_timeout (*session,
GNUTLS_DEFAULT_HANDSHAKE_TIMEOUT);
do {
err = gnutls_handshake (*session);
} while (err < 0 && gnutls_error_is_fatal (err) == 0);
if (err < 0) {
nbdkit_error ("gnutls_handshake: %s", gnutls_strerror (err));
goto error;
}
debug ("TLS handshake completed");
return 0;
error:
gnutls_deinit (*session);
free (session);
return -1;
}
#else /* !HAVE_GNUTLS */
/* GnuTLS was not available at compile time. These are stub versions
* of the above functions which either do nothing or report errors as
* appropriate.
*/
void
crypto_init (int tls_set_on_cli)
{
if (tls > 0) {
fprintf (stderr, "%s: TLS cannot be enabled because this binary was compiled without GnuTLS.\n",
program_name);
exit (EXIT_FAILURE);
}
tls = 0;
debug ("TLS disabled: nbdkit was not compiled with GnuTLS support");
}
void
crypto_free (void)
{
/* nothing */
}
int
crypto_negotiate_tls (struct connection *conn, int sockin, int sockout)
{
/* Should never be called because tls == 0. */
abort ();
}
#endif /* !HAVE_GNUTLS */