Coverage Report

Created: 2026-06-22 06:39

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openvswitch/lib/stream-ssl.c
Line
Count
Source
1
/*
2
 * Copyright (c) 2008-2016, 2019 Nicira, Inc.
3
 *
4
 * Licensed under the Apache License, Version 2.0 (the "License");
5
 * you may not use this file except in compliance with the License.
6
 * You may obtain a copy of the License at:
7
 *
8
 *     http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 * Unless required by applicable law or agreed to in writing, software
11
 * distributed under the License is distributed on an "AS IS" BASIS,
12
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 * See the License for the specific language governing permissions and
14
 * limitations under the License.
15
 */
16
17
#include <config.h>
18
#include "stream-ssl.h"
19
#include "dhparams.h"
20
#include <ctype.h>
21
#include <errno.h>
22
#include <inttypes.h>
23
#include <string.h>
24
#include <sys/types.h>
25
#include <sys/socket.h>
26
#include <netinet/tcp.h>
27
#include <openssl/err.h>
28
#include <openssl/rand.h>
29
#include <openssl/ssl.h>
30
#include <openssl/x509v3.h>
31
#include <poll.h>
32
#include <fcntl.h>
33
#include <sys/stat.h>
34
#include <unistd.h>
35
#include "bitmap.h"
36
#include "coverage.h"
37
#include "openvswitch/dynamic-string.h"
38
#include "entropy.h"
39
#include "openvswitch/ofpbuf.h"
40
#include "openflow/openflow.h"
41
#include "packets.h"
42
#include "openvswitch/poll-loop.h"
43
#include "openvswitch/shash.h"
44
#include "socket-util.h"
45
#include "util.h"
46
#include "sset.h"
47
#include "stream-provider.h"
48
#include "stream.h"
49
#include "timeval.h"
50
#include "openvswitch/vlog.h"
51
52
VLOG_DEFINE_THIS_MODULE(stream_ssl);
53
54
/* Active SSL/TLS. */
55
56
enum ssl_state {
57
    STATE_TCP_CONNECTING,
58
    STATE_SSL_CONNECTING
59
};
60
61
enum session_type {
62
    CLIENT,
63
    SERVER
64
};
65
66
struct ssl_stream
67
{
68
    struct stream stream;
69
    enum ssl_state state;
70
    enum session_type type;
71
    int fd;
72
    SSL *ssl;
73
    struct ofpbuf *txbuf;
74
    unsigned int session_nr;
75
76
    /* rx_want and tx_want record the result of the last call to SSL_read()
77
     * and SSL_write(), respectively:
78
     *
79
     *    - If the call reported that data needed to be read from the file
80
     *      descriptor, the corresponding member is set to SSL_READING.
81
     *
82
     *    - If the call reported that data needed to be written to the file
83
     *      descriptor, the corresponding member is set to SSL_WRITING.
84
     *
85
     *    - Otherwise, the member is set to SSL_NOTHING, indicating that the
86
     *      call completed successfully (or with an error) and that there is no
87
     *      need to block.
88
     *
89
     * These are needed because there is no way to ask OpenSSL what a data read
90
     * or write would require without giving it a buffer to receive into or
91
     * data to send, respectively.  (Note that the SSL_want() status is
92
     * overwritten by each SSL_read() or SSL_write() call, so we can't rely on
93
     * its value.)
94
     *
95
     * A single call to SSL_read() or SSL_write() can perform both reading
96
     * and writing and thus invalidate not one of these values but actually
97
     * both.  Consider this situation, for example:
98
     *
99
     *    - SSL_write() blocks on a read, so tx_want gets SSL_READING.
100
     *
101
     *    - SSL_read() laters succeeds reading from 'fd' and clears out the
102
     *      whole receive buffer, so rx_want gets SSL_READING.
103
     *
104
     *    - Client calls stream_wait(STREAM_RECV) and stream_wait(STREAM_SEND)
105
     *      and blocks.
106
     *
107
     *    - Now we're stuck blocking until the peer sends us data, even though
108
     *      SSL_write() could now succeed, which could easily be a deadlock
109
     *      condition.
110
     *
111
     * On the other hand, we can't reset both tx_want and rx_want on every call
112
     * to SSL_read() or SSL_write(), because that would produce livelock,
113
     * e.g. in this situation:
114
     *
115
     *    - SSL_write() blocks, so tx_want gets SSL_READING or SSL_WRITING.
116
     *
117
     *    - SSL_read() blocks, so rx_want gets SSL_READING or SSL_WRITING,
118
     *      but tx_want gets reset to SSL_NOTHING.
119
     *
120
     *    - Client calls stream_wait(STREAM_RECV) and stream_wait(STREAM_SEND)
121
     *      and blocks.
122
     *
123
     *    - Client wakes up immediately since SSL_NOTHING in tx_want indicates
124
     *      that no blocking is necessary.
125
     *
126
     * The solution we adopt here is to set tx_want to SSL_NOTHING after
127
     * calling SSL_read() only if the SSL state of the connection changed,
128
     * which indicates that an SSL-level renegotiation made some progress, and
129
     * similarly for rx_want and SSL_write().  This prevents both the
130
     * deadlock and livelock situations above.
131
     */
132
    int rx_want, tx_want;
133
134
    /* A few bytes of header data in case SSL negotiation fails. */
135
    uint8_t head[2];
136
    short int n_head;
137
};
138
139
/* SSL context created by ssl_init(). */
140
static SSL_CTX *ctx;
141
142
struct ssl_config_file {
143
    bool read;                  /* Whether the file was successfully read. */
144
    char *file_name;            /* Configured file name, if any. */
145
    struct timespec mtime;      /* File mtime as of last time we read it. */
146
};
147
148
/* SSL configuration files. */
149
static struct ssl_config_file private_key;
150
static struct ssl_config_file certificate;
151
static struct ssl_config_file ca_cert;
152
static char *ssl_protocols = "TLSv1.2+";
153
static char *ssl_ciphers = "DEFAULT:@SECLEVEL=2";
154
static char *ssl_ciphersuites = ""; /* Using default ones, unless specified. */
155
156
/* Server name override for SNI (Server Name Indication).
157
 * If set, this name will be used for SNI instead of the hostname
158
 * extracted from the connection string. */
159
static char *ssl_server_name_override;
160
161
/* Ordinarily, the SSL client and server verify each other's certificates using
162
 * a CA certificate.  Setting this to false disables this behavior.  (This is a
163
 * security risk.) */
164
static bool verify_peer_cert = true;
165
166
/* Ordinarily, we require a CA certificate for the peer to be locally
167
 * available.  We can, however, bootstrap the CA certificate from the peer at
168
 * the beginning of our first connection then use that certificate on all
169
 * subsequent connections, saving it to a file for use in future runs also.  In
170
 * this case, 'bootstrap_ca_cert' is true. */
171
static bool bootstrap_ca_cert;
172
173
/* Session number.  Used in debug logging messages to uniquely identify a
174
 * session. */
175
static unsigned int next_session_nr;
176
177
/* Who knows what can trigger various SSL errors, so let's throttle them down
178
 * quite a bit. */
179
static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(10, 25);
180
181
static int ssl_init(void);
182
static int do_ssl_init(void);
183
static bool ssl_wants_io(int ssl_error);
184
static void ssl_close(struct stream *);
185
static void ssl_clear_txbuf(struct ssl_stream *);
186
static void interpret_queued_ssl_error(const char *function);
187
static int interpret_ssl_error(const char *function, int ret, int error,
188
                               int *want);
189
#if OPENSSL_VERSION_NUMBER < 0x3000000fL
190
static DH *tmp_dh_callback(SSL *ssl, int is_export OVS_UNUSED, int keylength);
191
#endif
192
static void log_ca_cert(const char *file_name, X509 *cert);
193
static void stream_ssl_set_ca_cert_file__(const char *file_name,
194
                                          bool bootstrap, bool force);
195
static void ssl_protocol_cb(int write_p, int version, int content_type,
196
                            const void *, size_t, SSL *, void *sslv_);
197
static bool update_ssl_config(struct ssl_config_file *, const char *file_name);
198
static int sock_errno(void);
199
200
static short int
201
want_to_poll_events(int want)
202
0
{
203
0
    switch (want) {
204
0
    case SSL_NOTHING:
205
0
        OVS_NOT_REACHED();
206
207
0
    case SSL_READING:
208
0
        return POLLIN;
209
210
0
    case SSL_WRITING:
211
0
        return POLLOUT;
212
213
0
    default:
214
0
        OVS_NOT_REACHED();
215
0
    }
216
0
}
217
218
/* Creates a new SSL connection based on socket 'fd', as either a client or a
219
 * server according to 'type', initially in 'state'.  On success, returns 0 and
220
 * stores the new stream in '*streamp', otherwise returns an errno value and
221
 * doesn't bother with '*streamp'.
222
 *
223
 * Takes ownership of 'name', which should be the name of the connection in the
224
 * format that would be used to connect to it, e.g. "ssl:1.2.3.4:5".
225
 *
226
 * For client connections, 'server_name' should be the host name of the server
227
 * being connected to, for use with SSL SNI (server name indication).  Takes
228
 * ownership of 'server_name'. */
229
static int
230
new_ssl_stream(char *name, char *server_name, int fd, enum session_type type,
231
               enum ssl_state state, struct stream **streamp)
232
0
{
233
0
    struct ssl_stream *sslv;
234
0
    SSL *ssl = NULL;
235
0
    int retval;
236
237
    /* Check for all the needful configuration. */
238
0
    retval = 0;
239
0
    if (!private_key.read) {
240
0
        VLOG_ERR("Private key must be configured to use SSL");
241
0
        retval = ENOPROTOOPT;
242
0
    }
243
0
    if (!certificate.read) {
244
0
        VLOG_ERR("Certificate must be configured to use SSL");
245
0
        retval = ENOPROTOOPT;
246
0
    }
247
0
    if (!ca_cert.read && verify_peer_cert && !bootstrap_ca_cert) {
248
0
        VLOG_ERR("CA certificate must be configured to use SSL");
249
0
        retval = ENOPROTOOPT;
250
0
    }
251
0
    if (!retval && !SSL_CTX_check_private_key(ctx)) {
252
0
        VLOG_ERR("Private key does not match certificate public key: %s",
253
0
                 ERR_error_string(ERR_get_error(), NULL));
254
0
        retval = ENOPROTOOPT;
255
0
    }
256
0
    if (retval) {
257
0
        goto error;
258
0
    }
259
260
    /* Disable Nagle. */
261
0
    setsockopt_tcp_nodelay(fd);
262
263
    /* Create and configure OpenSSL stream. */
264
0
    ssl = SSL_new(ctx);
265
0
    if (ssl == NULL) {
266
0
        VLOG_ERR("SSL_new: %s", ERR_error_string(ERR_get_error(), NULL));
267
0
        retval = ENOPROTOOPT;
268
0
        goto error;
269
0
    }
270
0
    if (SSL_set_fd(ssl, fd) == 0) {
271
0
        VLOG_ERR("SSL_set_fd: %s", ERR_error_string(ERR_get_error(), NULL));
272
0
        retval = ENOPROTOOPT;
273
0
        goto error;
274
0
    }
275
0
    if (!verify_peer_cert || (bootstrap_ca_cert && type == CLIENT)) {
276
0
        SSL_set_verify(ssl, SSL_VERIFY_NONE, NULL);
277
0
    }
278
0
    if (server_name && !SSL_set_tlsext_host_name(ssl, server_name)) {
279
0
        VLOG_ERR("%s: failed to set server name indication (%s)",
280
0
                 server_name, ERR_error_string(ERR_get_error(), NULL));
281
0
        retval = ENOPROTOOPT;
282
0
        goto error;
283
0
    }
284
285
    /* Create and return the ssl_stream. */
286
0
    sslv = xmalloc(sizeof *sslv);
287
0
    stream_init(&sslv->stream, &ssl_stream_class, EAGAIN, name);
288
0
    sslv->state = state;
289
0
    sslv->type = type;
290
0
    sslv->fd = fd;
291
0
    sslv->ssl = ssl;
292
0
    sslv->txbuf = NULL;
293
0
    sslv->rx_want = sslv->tx_want = SSL_NOTHING;
294
0
    sslv->session_nr = next_session_nr++;
295
0
    sslv->n_head = 0;
296
297
0
    if (VLOG_IS_DBG_ENABLED()) {
298
0
        SSL_set_msg_callback(ssl, ssl_protocol_cb);
299
0
        SSL_set_msg_callback_arg(ssl, sslv);
300
0
    }
301
302
0
    *streamp = &sslv->stream;
303
0
    free(server_name);
304
0
    return 0;
305
306
0
error:
307
0
    if (ssl) {
308
0
        SSL_free(ssl);
309
0
    }
310
0
    closesocket(fd);
311
0
    free(name);
312
0
    free(server_name);
313
0
    return retval;
314
0
}
315
316
static struct ssl_stream *
317
ssl_stream_cast(struct stream *stream)
318
0
{
319
0
    stream_assert_class(stream, &ssl_stream_class);
320
0
    return CONTAINER_OF(stream, struct ssl_stream, stream);
321
0
}
322
323
/* Extracts and returns the server name from 'suffix'.  The caller must
324
 * eventually free it.
325
 *
326
 * Returns NULL if there is no server name, and particularly if it is an IP
327
 * address rather than a host name, since RFC 3546 is explicit that IP
328
 * addresses are unsuitable as server name indication (SNI). */
329
static char *
330
get_server_name(const char *suffix_)
331
0
{
332
0
    char *suffix = xstrdup(suffix_);
333
334
0
    char *host, *port;
335
0
    inet_parse_host_port_tokens(suffix, &host, &port);
336
337
0
    ovs_be32 ipv4;
338
0
    struct in6_addr ipv6;
339
0
    char *server_name = (ip_parse(host, &ipv4) || ipv6_parse(host, &ipv6)
340
0
                         ? NULL : xstrdup(host));
341
342
0
    free(suffix);
343
344
0
    return server_name;
345
0
}
346
347
static int
348
ssl_open(const char *name, char *suffix, struct stream **streamp, uint8_t dscp)
349
0
{
350
0
    int error, fd;
351
352
0
    error = ssl_init();
353
0
    if (error) {
354
0
        return error;
355
0
    }
356
357
0
    error = inet_open_active(SOCK_STREAM, suffix, OFP_PORT, NULL, &fd,
358
0
                             dscp);
359
0
    if (fd >= 0) {
360
0
        int state = error ? STATE_TCP_CONNECTING : STATE_SSL_CONNECTING;
361
0
        char *server_name = ssl_server_name_override
362
0
                            ? xstrdup(ssl_server_name_override)
363
0
                            : get_server_name(suffix);
364
365
0
        return new_ssl_stream(xstrdup(name), server_name,
366
0
                              fd, CLIENT, state, streamp);
367
0
    } else {
368
0
        VLOG_ERR("%s: connect: %s", name, ovs_strerror(error));
369
0
        return error;
370
0
    }
371
0
}
372
373
static int
374
do_ca_cert_bootstrap(struct stream *stream)
375
0
{
376
0
    struct ssl_stream *sslv = ssl_stream_cast(stream);
377
0
    STACK_OF(X509) *chain;
378
0
    X509 *cert;
379
0
    FILE *file;
380
0
    int error;
381
0
    int fd;
382
383
0
    chain = SSL_get_peer_cert_chain(sslv->ssl);
384
0
    if (!chain || !sk_X509_num(chain)) {
385
0
        VLOG_ERR("could not bootstrap CA cert: no certificate presented by "
386
0
                 "peer");
387
0
        return EPROTO;
388
0
    }
389
0
    cert = sk_X509_value(chain, sk_X509_num(chain) - 1);
390
391
    /* Check that 'cert' is self-signed.  Otherwise it is not a CA
392
     * certificate and we should not attempt to use it as one. */
393
0
    error = X509_check_issued(cert, cert);
394
0
    if (error) {
395
0
        VLOG_ERR("could not bootstrap CA cert: obtained certificate is "
396
0
                 "not self-signed (%s)",
397
0
                 X509_verify_cert_error_string(error));
398
0
        if (sk_X509_num(chain) < 2) {
399
0
            VLOG_ERR("only one certificate was received, so probably the peer "
400
0
                     "is not configured to send its CA certificate");
401
0
        }
402
0
        return EPROTO;
403
0
    }
404
405
0
    fd = open(ca_cert.file_name, O_CREAT | O_EXCL | O_WRONLY, 0444);
406
0
    if (fd < 0) {
407
0
        if (errno == EEXIST) {
408
0
            VLOG_INFO_RL(&rl, "reading CA cert %s created by another process",
409
0
                         ca_cert.file_name);
410
0
            stream_ssl_set_ca_cert_file__(ca_cert.file_name, true, true);
411
0
            return EPROTO;
412
0
        } else {
413
0
            VLOG_ERR("could not bootstrap CA cert: creating %s failed: %s",
414
0
                     ca_cert.file_name, ovs_strerror(errno));
415
0
            return errno;
416
0
        }
417
0
    }
418
419
0
    file = fdopen(fd, "w");
420
0
    if (!file) {
421
0
        error = errno;
422
0
        VLOG_ERR("could not bootstrap CA cert: fdopen failed: %s",
423
0
                 ovs_strerror(error));
424
0
        unlink(ca_cert.file_name);
425
0
        return error;
426
0
    }
427
428
0
    if (!PEM_write_X509(file, cert)) {
429
0
        VLOG_ERR("could not bootstrap CA cert: PEM_write_X509 to %s failed: "
430
0
                 "%s", ca_cert.file_name,
431
0
                 ERR_error_string(ERR_get_error(), NULL));
432
0
        fclose(file);
433
0
        unlink(ca_cert.file_name);
434
0
        return EIO;
435
0
    }
436
437
0
    if (fclose(file)) {
438
0
        error = errno;
439
0
        VLOG_ERR("could not bootstrap CA cert: writing %s failed: %s",
440
0
                 ca_cert.file_name, ovs_strerror(error));
441
0
        unlink(ca_cert.file_name);
442
0
        return error;
443
0
    }
444
445
0
    VLOG_INFO("successfully bootstrapped CA cert to %s", ca_cert.file_name);
446
0
    log_ca_cert(ca_cert.file_name, cert);
447
0
    bootstrap_ca_cert = false;
448
0
    ca_cert.read = true;
449
450
    /* SSL_CTX_add_client_CA makes a copy of cert's relevant data. */
451
0
    SSL_CTX_add_client_CA(ctx, cert);
452
453
0
    SSL_CTX_set_cert_store(ctx, X509_STORE_new());
454
0
    if (SSL_CTX_load_verify_locations(ctx, ca_cert.file_name, NULL) != 1) {
455
0
        VLOG_ERR("SSL_CTX_load_verify_locations: %s",
456
0
                 ERR_error_string(ERR_get_error(), NULL));
457
0
        return EPROTO;
458
0
    }
459
0
    VLOG_INFO("killing successful connection to retry using CA cert");
460
0
    return EPROTO;
461
0
}
462
463
static char *
464
get_peer_common_name(const struct ssl_stream *sslv)
465
0
{
466
0
    char *peer_name = NULL;
467
0
#if OPENSSL_VERSION_NUMBER < 0x3000000fL
468
0
    X509 *peer_cert = SSL_get_peer_certificate(sslv->ssl);
469
#else
470
    X509 *peer_cert = SSL_get1_peer_certificate(sslv->ssl);
471
#endif
472
0
    if (!peer_cert) {
473
0
        return NULL;
474
0
    }
475
476
0
    int cn_index = X509_NAME_get_index_by_NID(X509_get_subject_name(peer_cert),
477
0
                                              NID_commonName, -1);
478
0
    if (cn_index < 0) {
479
0
        goto error;
480
0
    }
481
482
0
    X509_NAME_ENTRY *cn_entry = X509_NAME_get_entry(
483
0
        X509_get_subject_name(peer_cert), cn_index);
484
0
    if (!cn_entry) {
485
0
        goto error;
486
0
    }
487
488
0
    ASN1_STRING *cn_data = X509_NAME_ENTRY_get_data(cn_entry);
489
0
    if (!cn_data) {
490
0
        goto error;
491
0
    }
492
493
0
    peer_name = xstrdup((const char *) ASN1_STRING_get0_data(cn_data));
494
495
0
error:
496
0
    X509_free(peer_cert);
497
0
    return peer_name;
498
0
}
499
500
static int
501
ssl_connect(struct stream *stream)
502
0
{
503
0
    struct ssl_stream *sslv = ssl_stream_cast(stream);
504
0
    int retval;
505
506
0
    switch (sslv->state) {
507
0
    case STATE_TCP_CONNECTING:
508
0
        retval = check_connection_completion(sslv->fd);
509
0
        if (retval) {
510
0
            return retval;
511
0
        }
512
0
        sslv->state = STATE_SSL_CONNECTING;
513
0
        setsockopt_tcp_nodelay(sslv->fd);
514
        /* Fall through. */
515
516
0
    case STATE_SSL_CONNECTING:
517
        /* Capture the first few bytes of received data so that we can guess
518
         * what kind of funny data we've been sent if SSL negotiation fails. */
519
0
        if (sslv->n_head <= 0) {
520
0
            sslv->n_head = recv(sslv->fd, sslv->head, sizeof sslv->head,
521
0
                                MSG_PEEK);
522
0
        }
523
524
0
        retval = (sslv->type == CLIENT
525
0
                   ? SSL_connect(sslv->ssl) : SSL_accept(sslv->ssl));
526
0
        if (retval != 1) {
527
0
            int error = SSL_get_error(sslv->ssl, retval);
528
0
            if (retval < 0 && ssl_wants_io(error)) {
529
0
                return EAGAIN;
530
0
            } else {
531
0
                int unused;
532
533
0
                interpret_ssl_error((sslv->type == CLIENT ? "SSL_connect"
534
0
                                     : "SSL_accept"), retval, error, &unused);
535
0
                shutdown(sslv->fd, SHUT_RDWR);
536
0
                stream_report_content(sslv->head, sslv->n_head, STREAM_SSL,
537
0
                                      &this_module, stream_get_name(stream));
538
0
                return EPROTO;
539
0
            }
540
0
        } else if (bootstrap_ca_cert) {
541
0
            return do_ca_cert_bootstrap(stream);
542
0
        } else if (verify_peer_cert
543
0
                   && ((SSL_get_verify_mode(sslv->ssl)
544
0
                       & (SSL_VERIFY_NONE | SSL_VERIFY_PEER))
545
0
                       != SSL_VERIFY_PEER)) {
546
            /* Two or more SSL connections completed at the same time while we
547
             * were in bootstrap mode.  Only one of these can finish the
548
             * bootstrap successfully.  The other one(s) must be rejected
549
             * because they were not verified against the bootstrapped CA
550
             * certificate.  (Alternatively we could verify them against the CA
551
             * certificate, but that's more trouble than it's worth.  These
552
             * connections will succeed the next time they retry, assuming that
553
             * they have a certificate against the correct CA.) */
554
0
            VLOG_INFO(
555
0
                "rejecting SSL/TLS connection during bootstrap race window");
556
0
            return EPROTO;
557
0
        } else {
558
0
            const char *servername = SSL_get_servername(
559
0
                sslv->ssl, TLSEXT_NAMETYPE_host_name);
560
0
            if (servername) {
561
0
                VLOG_DBG("connection indicated server name %s", servername);
562
0
            }
563
564
0
            char *cn = get_peer_common_name(sslv);
565
566
0
            if (cn) {
567
0
                stream_set_peer_id(stream, cn);
568
0
                free(cn);
569
0
            }
570
0
            return 0;
571
0
        }
572
0
    }
573
574
0
    OVS_NOT_REACHED();
575
0
}
576
577
static void
578
ssl_close(struct stream *stream)
579
0
{
580
0
    struct ssl_stream *sslv = ssl_stream_cast(stream);
581
0
    ssl_clear_txbuf(sslv);
582
583
    /* Attempt clean shutdown of the SSL connection.  This will work most of
584
     * the time, as long as the kernel send buffer has some free space and the
585
     * SSL connection isn't renegotiating, etc.  That has to be good enough,
586
     * since we don't have any way to continue the close operation in the
587
     * background. */
588
0
    SSL_shutdown(sslv->ssl);
589
590
    /* SSL_shutdown() might have signaled an error, in which case we need to
591
     * flush it out of the OpenSSL error queue or the next OpenSSL operation
592
     * will falsely signal an error. */
593
0
    ERR_clear_error();
594
595
0
    SSL_free(sslv->ssl);
596
0
    closesocket(sslv->fd);
597
0
    free(sslv);
598
0
}
599
600
static void
601
interpret_queued_ssl_error(const char *function)
602
0
{
603
0
    int queued_error = ERR_get_error();
604
0
    if (queued_error != 0) {
605
0
        VLOG_WARN_RL(&rl, "%s: %s",
606
0
                     function, ERR_error_string(queued_error, NULL));
607
0
    } else {
608
0
        VLOG_ERR_RL(&rl, "%s: SSL_ERROR_SSL without queued error", function);
609
0
    }
610
0
}
611
612
static int
613
interpret_ssl_error(const char *function, int ret, int error,
614
                    int *want)
615
0
{
616
0
    *want = SSL_NOTHING;
617
618
0
    switch (error) {
619
0
    case SSL_ERROR_NONE:
620
0
        VLOG_ERR_RL(&rl, "%s: unexpected SSL_ERROR_NONE", function);
621
0
        break;
622
623
0
    case SSL_ERROR_ZERO_RETURN:
624
0
        VLOG_ERR_RL(&rl, "%s: unexpected SSL_ERROR_ZERO_RETURN", function);
625
0
        break;
626
627
0
    case SSL_ERROR_WANT_READ:
628
0
        *want = SSL_READING;
629
0
        return EAGAIN;
630
631
0
    case SSL_ERROR_WANT_WRITE:
632
0
        *want = SSL_WRITING;
633
0
        return EAGAIN;
634
635
0
    case SSL_ERROR_WANT_CONNECT:
636
0
        VLOG_ERR_RL(&rl, "%s: unexpected SSL_ERROR_WANT_CONNECT", function);
637
0
        break;
638
639
0
    case SSL_ERROR_WANT_ACCEPT:
640
0
        VLOG_ERR_RL(&rl, "%s: unexpected SSL_ERROR_WANT_ACCEPT", function);
641
0
        break;
642
643
0
    case SSL_ERROR_WANT_X509_LOOKUP:
644
0
        VLOG_ERR_RL(&rl, "%s: unexpected SSL_ERROR_WANT_X509_LOOKUP",
645
0
                    function);
646
0
        break;
647
648
0
    case SSL_ERROR_SYSCALL: {
649
0
        int queued_error = ERR_get_error();
650
0
        if (queued_error == 0) {
651
0
            if (ret < 0) {
652
0
                int status = errno;
653
0
                VLOG_WARN_RL(&rl, "%s: system error (%s)",
654
0
                             function, ovs_strerror(status));
655
0
                return status;
656
0
            } else {
657
0
                VLOG_WARN_RL(&rl, "%s: unexpected SSL/TLS connection close",
658
0
                             function);
659
0
                return EPROTO;
660
0
            }
661
0
        } else {
662
0
            VLOG_WARN_RL(&rl, "%s: %s",
663
0
                         function, ERR_error_string(queued_error, NULL));
664
0
            break;
665
0
        }
666
0
    }
667
668
0
    case SSL_ERROR_SSL:
669
0
        interpret_queued_ssl_error(function);
670
0
        break;
671
672
0
    default:
673
0
        VLOG_ERR_RL(&rl, "%s: bad SSL error code %d", function, error);
674
0
        break;
675
0
    }
676
0
    return EIO;
677
0
}
678
679
static ssize_t
680
ssl_recv(struct stream *stream, void *buffer, size_t n)
681
0
{
682
0
    struct ssl_stream *sslv = ssl_stream_cast(stream);
683
0
    int old_state;
684
0
    ssize_t ret;
685
686
    /* Behavior of zero-byte SSL_read is poorly defined. */
687
0
    ovs_assert(n > 0);
688
689
0
    old_state = SSL_get_state(sslv->ssl);
690
0
    ret = SSL_read(sslv->ssl, buffer, n);
691
0
    if (old_state != SSL_get_state(sslv->ssl)) {
692
0
        sslv->tx_want = SSL_NOTHING;
693
0
    }
694
0
    sslv->rx_want = SSL_NOTHING;
695
696
0
    if (ret > 0) {
697
0
        return ret;
698
0
    } else {
699
0
        int error = SSL_get_error(sslv->ssl, ret);
700
0
        if (error == SSL_ERROR_ZERO_RETURN) {
701
0
            return 0;
702
0
        } else {
703
0
            return -interpret_ssl_error("SSL_read", ret, error,
704
0
                                        &sslv->rx_want);
705
0
        }
706
0
    }
707
0
}
708
709
static void
710
ssl_clear_txbuf(struct ssl_stream *sslv)
711
0
{
712
0
    ofpbuf_delete(sslv->txbuf);
713
0
    sslv->txbuf = NULL;
714
0
}
715
716
static int
717
ssl_do_tx(struct stream *stream)
718
0
{
719
0
    struct ssl_stream *sslv = ssl_stream_cast(stream);
720
721
0
    for (;;) {
722
0
        int old_state = SSL_get_state(sslv->ssl);
723
0
        int ret = SSL_write(sslv->ssl, sslv->txbuf->data, sslv->txbuf->size);
724
0
        if (old_state != SSL_get_state(sslv->ssl)) {
725
0
            sslv->rx_want = SSL_NOTHING;
726
0
        }
727
0
        sslv->tx_want = SSL_NOTHING;
728
0
        if (ret > 0) {
729
0
            ofpbuf_pull(sslv->txbuf, ret);
730
0
            if (sslv->txbuf->size == 0) {
731
0
                return 0;
732
0
            }
733
0
        } else {
734
0
            int ssl_error = SSL_get_error(sslv->ssl, ret);
735
0
            if (ssl_error == SSL_ERROR_ZERO_RETURN) {
736
0
                VLOG_WARN_RL(&rl, "SSL_write: connection closed");
737
0
                return EPIPE;
738
0
            } else {
739
0
                return interpret_ssl_error("SSL_write", ret, ssl_error,
740
0
                                           &sslv->tx_want);
741
0
            }
742
0
        }
743
0
    }
744
0
}
745
746
static ssize_t
747
ssl_send(struct stream *stream, const void *buffer, size_t n)
748
0
{
749
0
    struct ssl_stream *sslv = ssl_stream_cast(stream);
750
751
0
    if (sslv->txbuf) {
752
0
        return -EAGAIN;
753
0
    } else {
754
0
        struct ofpbuf buf;
755
0
        int error;
756
757
0
        ofpbuf_use_const(&buf, buffer, n);
758
0
        sslv->txbuf = &buf;
759
0
        error = ssl_do_tx(stream);
760
0
        switch (error) {
761
0
        case 0:
762
0
            sslv->txbuf = NULL;
763
0
            return n;
764
0
        case EAGAIN:
765
            /* Copy remaining data. */
766
0
            sslv->txbuf = ofpbuf_clone_data(buf.data, buf.size);
767
0
            return n;
768
0
        default:
769
0
            sslv->txbuf = NULL;
770
0
            return -error;
771
0
        }
772
0
    }
773
0
}
774
775
static void
776
ssl_run(struct stream *stream)
777
0
{
778
0
    struct ssl_stream *sslv = ssl_stream_cast(stream);
779
780
0
    if (sslv->txbuf && ssl_do_tx(stream) != EAGAIN) {
781
0
        ssl_clear_txbuf(sslv);
782
0
    }
783
0
}
784
785
static void
786
ssl_run_wait(struct stream *stream)
787
0
{
788
0
    struct ssl_stream *sslv = ssl_stream_cast(stream);
789
790
0
    if (sslv->tx_want != SSL_NOTHING) {
791
0
        poll_fd_wait(sslv->fd, want_to_poll_events(sslv->tx_want));
792
0
    }
793
0
}
794
795
static void
796
ssl_wait(struct stream *stream, enum stream_wait_type wait)
797
0
{
798
0
    struct ssl_stream *sslv = ssl_stream_cast(stream);
799
800
0
    switch (wait) {
801
0
    case STREAM_CONNECT:
802
0
        if (stream_connect(stream) != EAGAIN) {
803
0
            poll_immediate_wake();
804
0
        } else {
805
0
            switch (sslv->state) {
806
0
            case STATE_TCP_CONNECTING:
807
0
                poll_fd_wait(sslv->fd, POLLOUT);
808
0
                break;
809
810
0
            case STATE_SSL_CONNECTING:
811
                /* ssl_connect() called SSL_accept() or SSL_connect(), which
812
                 * set up the status that we test here. */
813
0
                poll_fd_wait(sslv->fd,
814
0
                               want_to_poll_events(SSL_want(sslv->ssl)));
815
0
                break;
816
817
0
            default:
818
0
                OVS_NOT_REACHED();
819
0
            }
820
0
        }
821
0
        break;
822
823
0
    case STREAM_RECV:
824
0
        if (sslv->rx_want != SSL_NOTHING) {
825
0
            poll_fd_wait(sslv->fd, want_to_poll_events(sslv->rx_want));
826
0
        } else {
827
0
            poll_immediate_wake();
828
0
        }
829
0
        break;
830
831
0
    case STREAM_SEND:
832
0
        if (!sslv->txbuf) {
833
            /* We have room in our tx queue. */
834
0
            poll_immediate_wake();
835
0
        } else {
836
            /* stream_run_wait() will do the right thing; don't bother with
837
             * redundancy. */
838
0
        }
839
0
        break;
840
841
0
    default:
842
0
        OVS_NOT_REACHED();
843
0
    }
844
0
}
845
846
const struct stream_class ssl_stream_class = {
847
    "ssl",                      /* name */
848
    true,                       /* needs_probes */
849
    ssl_open,                   /* open */
850
    ssl_close,                  /* close */
851
    ssl_connect,                /* connect */
852
    ssl_recv,                   /* recv */
853
    ssl_send,                   /* send */
854
    ssl_run,                    /* run */
855
    ssl_run_wait,               /* run_wait */
856
    ssl_wait,                   /* wait */
857
};
858

859
/* Passive SSL/TLS. */
860
861
struct pssl_pstream
862
{
863
    struct pstream pstream;
864
    int fd;
865
};
866
867
const struct pstream_class pssl_pstream_class;
868
869
static struct pssl_pstream *
870
pssl_pstream_cast(struct pstream *pstream)
871
0
{
872
0
    pstream_assert_class(pstream, &pssl_pstream_class);
873
0
    return CONTAINER_OF(pstream, struct pssl_pstream, pstream);
874
0
}
875
876
static int
877
pssl_open(const char *name OVS_UNUSED, char *suffix, struct pstream **pstreamp,
878
          uint8_t dscp)
879
0
{
880
0
    struct sockaddr_storage ss;
881
0
    struct pssl_pstream *pssl;
882
0
    uint16_t port;
883
0
    int retval;
884
0
    int fd;
885
886
0
    retval = ssl_init();
887
0
    if (retval) {
888
0
        return retval;
889
0
    }
890
891
0
    fd = inet_open_passive(SOCK_STREAM, suffix, OFP_PORT, &ss, dscp, true);
892
0
    if (fd < 0) {
893
0
        return -fd;
894
0
    }
895
896
0
    port = ss_get_port(&ss);
897
898
0
    struct ds bound_name = DS_EMPTY_INITIALIZER;
899
0
    ds_put_format(&bound_name, "pssl:%"PRIu16":", port);
900
0
    ss_format_address(&ss, &bound_name);
901
902
0
    pssl = xmalloc(sizeof *pssl);
903
0
    pstream_init(&pssl->pstream, &pssl_pstream_class,
904
0
                 ds_steal_cstr(&bound_name));
905
0
    pstream_set_bound_port(&pssl->pstream, htons(port));
906
0
    pssl->fd = fd;
907
0
    *pstreamp = &pssl->pstream;
908
909
0
    return 0;
910
0
}
911
912
static void
913
pssl_close(struct pstream *pstream)
914
0
{
915
0
    struct pssl_pstream *pssl = pssl_pstream_cast(pstream);
916
0
    closesocket(pssl->fd);
917
0
    free(pssl);
918
0
}
919
920
static int
921
pssl_accept(struct pstream *pstream, struct stream **new_streamp)
922
0
{
923
0
    struct pssl_pstream *pssl = pssl_pstream_cast(pstream);
924
0
    struct sockaddr_storage ss;
925
0
    socklen_t ss_len = sizeof ss;
926
0
    int new_fd;
927
0
    int error;
928
929
0
    new_fd = accept(pssl->fd, (struct sockaddr *) &ss, &ss_len);
930
0
    if (new_fd < 0) {
931
0
        error = sock_errno();
932
0
        if (error != EAGAIN) {
933
0
            VLOG_DBG_RL(&rl, "accept: %s", sock_strerror(error));
934
0
        }
935
0
        return error;
936
0
    }
937
938
0
    error = set_nonblocking(new_fd);
939
0
    if (error) {
940
0
        closesocket(new_fd);
941
0
        return error;
942
0
    }
943
944
0
    struct ds name = DS_EMPTY_INITIALIZER;
945
0
    ds_put_cstr(&name, "ssl:");
946
0
    ss_format_address(&ss, &name);
947
0
    ds_put_format(&name, ":%"PRIu16, ss_get_port(&ss));
948
0
    return new_ssl_stream(ds_steal_cstr(&name), NULL, new_fd, SERVER,
949
0
                          STATE_SSL_CONNECTING, new_streamp);
950
0
}
951
952
static void
953
pssl_wait(struct pstream *pstream)
954
0
{
955
0
    struct pssl_pstream *pssl = pssl_pstream_cast(pstream);
956
0
    poll_fd_wait(pssl->fd, POLLIN);
957
0
}
958
959
const struct pstream_class pssl_pstream_class = {
960
    "pssl",
961
    true,
962
    pssl_open,
963
    pssl_close,
964
    pssl_accept,
965
    pssl_wait,
966
};
967

968
/*
969
 * Returns true if OpenSSL error is WANT_READ or WANT_WRITE, indicating that
970
 * OpenSSL is requesting that we call it back when the socket is ready for read
971
 * or writing, respectively.
972
 */
973
static bool
974
ssl_wants_io(int ssl_error)
975
0
{
976
0
    return (ssl_error == SSL_ERROR_WANT_WRITE
977
0
            || ssl_error == SSL_ERROR_WANT_READ);
978
0
}
979
980
static int
981
ssl_init(void)
982
0
{
983
0
    static int init_status = -1;
984
0
    if (init_status < 0) {
985
0
        init_status = do_ssl_init();
986
0
        ovs_assert(init_status >= 0);
987
0
    }
988
0
    return init_status;
989
0
}
990
991
static int
992
do_ssl_init(void)
993
0
{
994
0
    if (!RAND_status()) {
995
        /* We occasionally see OpenSSL fail to seed its random number generator
996
         * in heavily loaded hypervisors.  I suspect the following scenario:
997
         *
998
         * 1. OpenSSL calls read() to get 32 bytes from /dev/urandom.
999
         * 2. The kernel generates 10 bytes of randomness and copies it out.
1000
         * 3. A signal arrives (perhaps SIGALRM).
1001
         * 4. The kernel interrupts the system call to service the signal.
1002
         * 5. Userspace gets 10 bytes of entropy.
1003
         * 6. OpenSSL doesn't read again to get the final 22 bytes.  Therefore
1004
         *    OpenSSL doesn't have enough entropy to consider itself
1005
         *    initialized.
1006
         *
1007
         * The only part I'm not entirely sure about is #6, because the OpenSSL
1008
         * code is so hard to read. */
1009
0
        uint8_t seed[32];
1010
0
        int retval;
1011
1012
0
        VLOG_WARN("OpenSSL random seeding failed, reseeding ourselves");
1013
1014
0
        retval = get_entropy(seed, sizeof seed);
1015
0
        if (retval) {
1016
0
            VLOG_ERR("failed to obtain entropy (%s)",
1017
0
                     ovs_retval_to_string(retval));
1018
0
            return retval > 0 ? retval : ENOPROTOOPT;
1019
0
        }
1020
1021
0
        RAND_seed(seed, sizeof seed);
1022
0
    }
1023
1024
    /* Using version-flexible "connection method".  Allowed versions will
1025
     * be restricted below.
1026
     *
1027
     * The context can be used for both client and server connections, so
1028
     * not using specific TLS_server_method() or TLS_client_method() here. */
1029
0
    const SSL_METHOD *method = TLS_method();
1030
0
    if (method == NULL) {
1031
0
        VLOG_ERR("TLS_method: %s", ERR_error_string(ERR_get_error(), NULL));
1032
0
        return ENOPROTOOPT;
1033
0
    }
1034
1035
0
    ctx = SSL_CTX_new(method);
1036
0
    if (ctx == NULL) {
1037
0
        VLOG_ERR("SSL_CTX_new: %s", ERR_error_string(ERR_get_error(), NULL));
1038
0
        return ENOPROTOOPT;
1039
0
    }
1040
1041
#ifdef SSL_OP_IGNORE_UNEXPECTED_EOF
1042
    SSL_CTX_set_options(ctx, SSL_OP_IGNORE_UNEXPECTED_EOF);
1043
#endif
1044
1045
    /* Only allow TLSv1.2 or later. */
1046
0
    SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
1047
0
    SSL_CTX_set_max_proto_version(ctx, 0);
1048
1049
0
#if OPENSSL_VERSION_NUMBER < 0x3000000fL
1050
0
    SSL_CTX_set_tmp_dh_callback(ctx, tmp_dh_callback);
1051
#else
1052
    SSL_CTX_set_dh_auto(ctx, 1);
1053
#endif
1054
0
    SSL_CTX_set_mode(ctx, SSL_MODE_ENABLE_PARTIAL_WRITE);
1055
0
    SSL_CTX_set_mode(ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
1056
0
    SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
1057
0
                       NULL);
1058
0
    SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
1059
0
    SSL_CTX_set_options(ctx, SSL_OP_NO_TICKET);
1060
0
    SSL_CTX_set_cipher_list(ctx, "DEFAULT:@SECLEVEL=2");
1061
1062
0
    return 0;
1063
0
}
1064
1065
#if OPENSSL_VERSION_NUMBER < 0x3000000fL
1066
static DH *
1067
tmp_dh_callback(SSL *ssl OVS_UNUSED, int is_export OVS_UNUSED, int keylength)
1068
0
{
1069
0
    struct dh {
1070
0
        int keylength;
1071
0
        DH *dh;
1072
0
        DH *(*constructor)(void);
1073
0
    };
1074
1075
0
    static struct dh dh_table[] = {
1076
0
        {2048, NULL, get_dh2048},
1077
0
        {4096, NULL, get_dh4096},
1078
0
    };
1079
1080
0
    struct dh *dh;
1081
1082
0
    for (dh = dh_table; dh < &dh_table[ARRAY_SIZE(dh_table)]; dh++) {
1083
0
        if (dh->keylength >= keylength) {
1084
0
            if (!dh->dh) {
1085
0
                dh->dh = dh->constructor();
1086
0
                if (!dh->dh) {
1087
0
                    out_of_memory();
1088
0
                }
1089
0
            }
1090
0
            return dh->dh;
1091
0
        }
1092
0
    }
1093
0
    VLOG_ERR_RL(&rl, "no Diffie-Hellman parameters for key length %d",
1094
0
                keylength);
1095
0
    return NULL;
1096
0
}
1097
#endif
1098
1099
/* Returns true if SSL/TLS is at least partially configured. */
1100
bool
1101
stream_ssl_is_configured(void)
1102
0
{
1103
0
    return private_key.file_name || certificate.file_name || ca_cert.file_name;
1104
0
}
1105
1106
static bool
1107
update_ssl_config(struct ssl_config_file *config, const char *file_name)
1108
0
{
1109
0
    struct timespec mtime;
1110
0
    int error;
1111
1112
0
    if (ssl_init() || !file_name) {
1113
0
        return false;
1114
0
    }
1115
1116
    /* If the file name hasn't changed and neither has the file contents, stop
1117
     * here. */
1118
0
    error = get_mtime(file_name, &mtime);
1119
0
    if (error && error != ENOENT) {
1120
0
        VLOG_ERR_RL(&rl, "%s: stat failed (%s)",
1121
0
                    file_name, ovs_strerror(error));
1122
0
    }
1123
0
    if (config->file_name
1124
0
        && !strcmp(config->file_name, file_name)
1125
0
        && mtime.tv_sec == config->mtime.tv_sec
1126
0
        && mtime.tv_nsec == config->mtime.tv_nsec) {
1127
0
        return false;
1128
0
    }
1129
1130
    /* Update 'config'. */
1131
0
    config->mtime = mtime;
1132
0
    if (file_name != config->file_name) {
1133
0
        free(config->file_name);
1134
0
        config->file_name = xstrdup(file_name);
1135
0
    }
1136
0
    return true;
1137
0
}
1138
1139
static void
1140
stream_ssl_set_private_key_file__(const char *file_name)
1141
0
{
1142
0
    if (SSL_CTX_use_PrivateKey_file(ctx, file_name, SSL_FILETYPE_PEM) == 1) {
1143
0
        private_key.read = true;
1144
0
    } else {
1145
0
        VLOG_ERR("SSL_use_PrivateKey_file: %s",
1146
0
                 ERR_error_string(ERR_get_error(), NULL));
1147
0
    }
1148
0
}
1149
1150
void
1151
stream_ssl_set_private_key_file(const char *file_name)
1152
0
{
1153
0
    if (update_ssl_config(&private_key, file_name)) {
1154
0
        stream_ssl_set_private_key_file__(file_name);
1155
0
    }
1156
0
}
1157
1158
static void
1159
stream_ssl_set_certificate_file__(const char *file_name)
1160
0
{
1161
0
    if (SSL_CTX_use_certificate_file(ctx, file_name, SSL_FILETYPE_PEM) == 1) {
1162
0
        certificate.read = true;
1163
0
    } else {
1164
0
        VLOG_ERR("SSL_use_certificate_file: %s",
1165
0
                 ERR_error_string(ERR_get_error(), NULL));
1166
0
    }
1167
0
}
1168
1169
void
1170
stream_ssl_set_certificate_file(const char *file_name)
1171
0
{
1172
0
    if (update_ssl_config(&certificate, file_name)) {
1173
0
        stream_ssl_set_certificate_file__(file_name);
1174
0
    }
1175
0
}
1176
1177
/* Sets the private key and certificate files in one operation.  Use this
1178
 * interface, instead of calling stream_ssl_set_private_key_file() and
1179
 * stream_ssl_set_certificate_file() individually, in the main loop of a
1180
 * long-running program whose key and certificate might change at runtime.
1181
 *
1182
 * This is important because of OpenSSL's behavior.  If an OpenSSL context
1183
 * already has a certificate, and stream_ssl_set_private_key_file() is called
1184
 * to install a new private key, OpenSSL will report an error because the new
1185
 * private key does not match the old certificate.  The other order, of setting
1186
 * a new certificate, then setting a new private key, does work.
1187
 *
1188
 * If this were the only problem, calling stream_ssl_set_certificate_file()
1189
 * before stream_ssl_set_private_key_file() would fix it.  But, if the private
1190
 * key is changed before the certificate (e.g. someone "scp"s or "mv"s the new
1191
 * private key in place before the certificate), then OpenSSL would reject that
1192
 * change, and then the change of certificate would succeed, but there would be
1193
 * no associated private key (because it had only changed once and therefore
1194
 * there was no point in re-reading it).
1195
 *
1196
 * This function avoids both problems by, whenever either the certificate or
1197
 * the private key file changes, re-reading both of them, in the correct order.
1198
 */
1199
void
1200
stream_ssl_set_key_and_cert(const char *private_key_file,
1201
                            const char *certificate_file)
1202
0
{
1203
0
    if (update_ssl_config(&private_key, private_key_file)
1204
0
        && update_ssl_config(&certificate, certificate_file)) {
1205
0
        stream_ssl_set_certificate_file__(certificate_file);
1206
0
        stream_ssl_set_private_key_file__(private_key_file);
1207
0
    }
1208
0
}
1209
1210
/* Sets SSL/TLS ciphers for TLSv1.2 based on string input.
1211
 * Aborts with an error message if 'arg' is not valid. */
1212
void
1213
stream_ssl_set_ciphers(const char *arg)
1214
0
{
1215
0
    if (ssl_init() || !arg || !strcmp(ssl_ciphers, arg)) {
1216
0
        return;
1217
0
    }
1218
0
    if (SSL_CTX_set_cipher_list(ctx,arg) == 0) {
1219
0
        VLOG_ERR("SSL_CTX_set_cipher_list: %s",
1220
0
                 ERR_error_string(ERR_get_error(), NULL));
1221
0
    }
1222
0
    ssl_ciphers = xstrdup(arg);
1223
0
}
1224
1225
/* Sets TLS ciphersuites for TLSv1.3 and later based on string input.
1226
 * Aborts with an error message if 'arg' is not valid. */
1227
void
1228
stream_ssl_set_ciphersuites(const char *arg)
1229
0
{
1230
0
    if (ssl_init() || !arg || !strcmp(ssl_ciphersuites, arg)) {
1231
0
        return;
1232
0
    }
1233
0
    if (SSL_CTX_set_ciphersuites(ctx, arg) == 0) {
1234
0
        VLOG_ERR("SSL_CTX_set_ciphersuites: %s",
1235
0
                 ERR_error_string(ERR_get_error(), NULL));
1236
0
    }
1237
0
    ssl_ciphersuites = xstrdup(arg);
1238
0
}
1239
1240
/* Sets the server name override for SNI (Server Name Indication).
1241
 * If 'server_name' is NULL, clears any existing override and SNI will
1242
 * use the hostname from the connection string. */
1243
void
1244
stream_ssl_set_server_name(const char *server_name)
1245
0
{
1246
0
    free(ssl_server_name_override);
1247
0
    ssl_server_name_override = nullable_xstrdup(server_name);
1248
0
}
1249
1250
/* Set SSL/TLS protocols based on the string input. Aborts with an error
1251
 * message if 'arg' is invalid. */
1252
void
1253
stream_ssl_set_protocols(const char *arg)
1254
0
{
1255
0
    if (ssl_init() || !arg || !strcmp(arg, ssl_protocols)) {
1256
0
        return;
1257
0
    }
1258
1259
0
    struct sset set = SSET_INITIALIZER(&set);
1260
0
    struct {
1261
0
        const char *name;
1262
0
        int version;
1263
0
        bool deprecated;
1264
0
    } protocols[] = {
1265
0
        {"later",   0 /* any version */, false},
1266
0
        {"TLSv1.2", TLS1_2_VERSION,      false},
1267
0
        {"TLSv1.3", TLS1_3_VERSION,      false},
1268
0
    };
1269
0
    const char *dash = strchr(arg, '-');
1270
0
    bool or_later = false;
1271
0
    int len = strlen(arg);
1272
1273
0
    if (len && arg[len - 1] == '+') {
1274
        /* We only support full ranges, so more than one version or later "X+"
1275
         * doesn't make a lot of sense. */
1276
0
        sset_add_and_free(&set, xmemdup0(arg, len - 1));
1277
0
        or_later = true;
1278
0
    } else if (dash) {
1279
        /* Again, do not attempt to parse multiple ranges.  The range should
1280
         * always be a single "X-Y". */
1281
0
        sset_add_and_free(&set, xmemdup0(arg, dash - arg));
1282
0
        sset_add_and_free(&set, xstrdup(dash + 1));
1283
0
    } else {
1284
        /* Otherwise, it's a list that should not include ranges. */
1285
0
        sset_from_delimited_string(&set, arg, " ,\t");
1286
0
    }
1287
1288
0
    if (sset_is_empty(&set)) {
1289
0
        VLOG_ERR("SSL/TLS protocol settings invalid");
1290
0
        goto exit;
1291
0
    }
1292
1293
0
    size_t min_version = ARRAY_SIZE(protocols) + 1;
1294
0
    size_t max_version = 0;
1295
0
    unsigned long map = 0;
1296
1297
0
    for (size_t i = 1; i < ARRAY_SIZE(protocols); i++) {
1298
0
        if (sset_contains(&set, protocols[i].name)) {
1299
0
            min_version = MIN(min_version, i);
1300
0
            max_version = MAX(max_version, i);
1301
0
            if (protocols[i].deprecated) {
1302
0
                VLOG_WARN("%s protocol is deprecated", protocols[i].name);
1303
0
            }
1304
0
            bitmap_set1(&map, i);
1305
0
            sset_find_and_delete(&set, protocols[i].name);
1306
0
        }
1307
0
    }
1308
1309
0
    if (!sset_is_empty(&set)) {
1310
0
        const char *word;
1311
1312
0
        SSET_FOR_EACH (word, &set) {
1313
0
            VLOG_ERR("%s: SSL/TLS protocol not recognized", word);
1314
0
        }
1315
0
        goto exit;
1316
0
    }
1317
1318
    /* At this point we must have parsed at least one protocol. */
1319
0
    ovs_assert(min_version && min_version < ARRAY_SIZE(protocols));
1320
0
    ovs_assert(max_version && max_version < ARRAY_SIZE(protocols));
1321
0
    if (!or_later && !dash) {
1322
0
        for (size_t i = min_version + 1; i < max_version; i++) {
1323
0
            if (!bitmap_is_set(&map, i)) {
1324
0
                VLOG_WARN("SSL/TLS protocol %s"
1325
0
                          " is not configured, but will be enabled anyway.",
1326
0
                          protocols[i].name);
1327
0
            }
1328
0
        }
1329
0
    }
1330
1331
0
    if (or_later) {
1332
0
        ovs_assert(min_version == max_version);
1333
0
        max_version = 0;
1334
0
    }
1335
1336
    /* Set the actual versions. */
1337
0
    SSL_CTX_set_min_proto_version(ctx, protocols[min_version].version);
1338
0
    SSL_CTX_set_max_proto_version(ctx, protocols[max_version].version);
1339
0
    VLOG_DBG("Enabled protocol range: %s%s%s", protocols[min_version].name,
1340
0
                                               max_version ? " - " : " or ",
1341
0
                                               protocols[max_version].name);
1342
0
    ssl_protocols = xstrdup(arg);
1343
1344
0
exit:
1345
0
    sset_destroy(&set);
1346
0
}
1347
1348
/* Reads the X509 certificate or certificates in file 'file_name'.  On success,
1349
 * stores the address of the first element in an array of pointers to
1350
 * certificates in '*certs' and the number of certificates in the array in
1351
 * '*n_certs', and returns 0.  On failure, stores a null pointer in '*certs', 0
1352
 * in '*n_certs', and returns a positive errno value.
1353
 *
1354
 * The caller is responsible for freeing '*certs'. */
1355
static int
1356
read_cert_file(const char *file_name, X509 ***certs, size_t *n_certs)
1357
0
{
1358
0
    FILE *file;
1359
0
    size_t allocated_certs = 0;
1360
1361
0
    *certs = NULL;
1362
0
    *n_certs = 0;
1363
1364
0
    file = fopen(file_name, "r");
1365
0
    if (!file) {
1366
0
        VLOG_ERR("failed to open %s for reading: %s",
1367
0
                 file_name, ovs_strerror(errno));
1368
0
        return errno;
1369
0
    }
1370
1371
0
    for (;;) {
1372
0
        X509 *cert;
1373
0
        int c;
1374
1375
        /* Read certificate from file. */
1376
0
        cert = PEM_read_X509(file, NULL, NULL, NULL);
1377
0
        if (!cert) {
1378
0
            size_t i;
1379
1380
0
            VLOG_ERR("PEM_read_X509 failed reading %s: %s",
1381
0
                     file_name, ERR_error_string(ERR_get_error(), NULL));
1382
0
            for (i = 0; i < *n_certs; i++) {
1383
0
                X509_free((*certs)[i]);
1384
0
            }
1385
0
            free(*certs);
1386
0
            *certs = NULL;
1387
0
            *n_certs = 0;
1388
0
            fclose(file);
1389
0
            return EIO;
1390
0
        }
1391
1392
        /* Add certificate to array. */
1393
0
        if (*n_certs >= allocated_certs) {
1394
0
            *certs = x2nrealloc(*certs, &allocated_certs, sizeof **certs);
1395
0
        }
1396
0
        (*certs)[(*n_certs)++] = cert;
1397
1398
        /* Are there additional certificates in the file? */
1399
0
        do {
1400
0
            c = getc(file);
1401
0
        } while (c != EOF && isspace(c));
1402
0
        if (c == EOF) {
1403
0
            break;
1404
0
        }
1405
0
        ungetc(c, file);
1406
0
    }
1407
0
    fclose(file);
1408
0
    return 0;
1409
0
}
1410
1411
1412
/* Sets 'file_name' as the name of a file containing one or more X509
1413
 * certificates to send to the peer.  Typical use in OpenFlow is to send the CA
1414
 * certificate to the peer, which enables a switch to pick up the controller's
1415
 * CA certificate on its first connection. */
1416
void
1417
stream_ssl_set_peer_ca_cert_file(const char *file_name)
1418
0
{
1419
0
    X509 **certs;
1420
0
    size_t n_certs;
1421
0
    size_t i;
1422
1423
0
    if (ssl_init()) {
1424
0
        return;
1425
0
    }
1426
1427
0
    if (!read_cert_file(file_name, &certs, &n_certs)) {
1428
0
        for (i = 0; i < n_certs; i++) {
1429
0
            if (SSL_CTX_add_extra_chain_cert(ctx, certs[i]) != 1) {
1430
0
                VLOG_ERR("SSL_CTX_add_extra_chain_cert: %s",
1431
0
                         ERR_error_string(ERR_get_error(), NULL));
1432
0
            }
1433
0
        }
1434
0
        free(certs);
1435
0
    }
1436
0
}
1437
1438
/* Logs fingerprint of CA certificate 'cert' obtained from 'file_name'. */
1439
static void
1440
log_ca_cert(const char *file_name, X509 *cert)
1441
0
{
1442
0
    unsigned char digest[EVP_MAX_MD_SIZE];
1443
0
    unsigned int n_bytes;
1444
0
    struct ds fp;
1445
0
    char *subject;
1446
1447
0
    ds_init(&fp);
1448
0
    if (!X509_digest(cert, EVP_sha1(), digest, &n_bytes)) {
1449
0
        ds_put_cstr(&fp, "<out of memory>");
1450
0
    } else {
1451
0
        unsigned int i;
1452
0
        for (i = 0; i < n_bytes; i++) {
1453
0
            if (i) {
1454
0
                ds_put_char(&fp, ':');
1455
0
            }
1456
0
            ds_put_format(&fp, "%02x", digest[i]);
1457
0
        }
1458
0
    }
1459
0
    subject = X509_NAME_oneline(X509_get_subject_name(cert), NULL, 0);
1460
0
    VLOG_INFO("Trusting CA cert from %s (%s) (fingerprint %s)", file_name,
1461
0
              subject ? subject : "<out of memory>", ds_cstr(&fp));
1462
0
    OPENSSL_free(subject);
1463
0
    ds_destroy(&fp);
1464
0
}
1465
1466
static void
1467
stream_ssl_set_ca_cert_file__(const char *file_name,
1468
                              bool bootstrap, bool force)
1469
0
{
1470
0
    struct stat s;
1471
1472
0
    if (!update_ssl_config(&ca_cert, file_name) && !force) {
1473
0
        return;
1474
0
    }
1475
1476
0
    if (!strcmp(file_name, "none")) {
1477
0
        verify_peer_cert = false;
1478
0
        VLOG_WARN("Peer certificate validation disabled "
1479
0
                  "(this is a security risk)");
1480
0
    } else if (bootstrap && stat(file_name, &s) && errno == ENOENT) {
1481
0
        bootstrap_ca_cert = true;
1482
0
    } else {
1483
0
        STACK_OF(X509_NAME) *cert_names = SSL_load_client_CA_file(file_name);
1484
0
        if (cert_names) {
1485
            /* Set up list of CAs that the server will accept from the
1486
             * client. */
1487
0
            SSL_CTX_set_client_CA_list(ctx, cert_names);
1488
1489
            /* Set up CAs for OpenSSL to trust in verifying the peer's
1490
             * certificate. */
1491
0
            SSL_CTX_set_cert_store(ctx, X509_STORE_new());
1492
0
            if (SSL_CTX_load_verify_locations(ctx, file_name, NULL) != 1) {
1493
0
                VLOG_ERR("SSL_CTX_load_verify_locations: %s",
1494
0
                         ERR_error_string(ERR_get_error(), NULL));
1495
0
                return;
1496
0
            }
1497
0
            bootstrap_ca_cert = false;
1498
0
        } else {
1499
0
            VLOG_ERR("failed to load client certificates from %s: %s",
1500
0
                     file_name, ERR_error_string(ERR_get_error(), NULL));
1501
0
        }
1502
0
    }
1503
0
    ca_cert.read = true;
1504
0
}
1505
1506
/* Sets 'file_name' as the name of the file from which to read the CA
1507
 * certificate used to verify the peer within SSL/TLS connections.  If
1508
 * 'bootstrap' is false, the file must exist.  If 'bootstrap' is false, then
1509
 * the file is read if it is exists; if it does not, then it will be created
1510
 * from the CA certificate received from the peer on the first SSL/TLS
1511
 * connection. */
1512
void
1513
stream_ssl_set_ca_cert_file(const char *file_name, bool bootstrap)
1514
0
{
1515
0
    stream_ssl_set_ca_cert_file__(file_name, bootstrap, false);
1516
0
}
1517

1518
/* SSL/TLS protocol logging. */
1519
1520
static const char *
1521
ssl_alert_level_to_string(uint8_t type)
1522
0
{
1523
0
    switch (type) {
1524
0
    case 1: return "warning";
1525
0
    case 2: return "fatal";
1526
0
    default: return "<unknown>";
1527
0
    }
1528
0
}
1529
1530
static const char *
1531
ssl_alert_description_to_string(uint8_t type)
1532
0
{
1533
0
    switch (type) {
1534
0
    case 0: return "close_notify";
1535
0
    case 10: return "unexpected_message";
1536
0
    case 20: return "bad_record_mac";
1537
0
    case 21: return "decryption_failed";
1538
0
    case 22: return "record_overflow";
1539
0
    case 30: return "decompression_failure";
1540
0
    case 40: return "handshake_failure";
1541
0
    case 42: return "bad_certificate";
1542
0
    case 43: return "unsupported_certificate";
1543
0
    case 44: return "certificate_revoked";
1544
0
    case 45: return "certificate_expired";
1545
0
    case 46: return "certificate_unknown";
1546
0
    case 47: return "illegal_parameter";
1547
0
    case 48: return "unknown_ca";
1548
0
    case 49: return "access_denied";
1549
0
    case 50: return "decode_error";
1550
0
    case 51: return "decrypt_error";
1551
0
    case 60: return "export_restriction";
1552
0
    case 70: return "protocol_version";
1553
0
    case 71: return "insufficient_security";
1554
0
    case 80: return "internal_error";
1555
0
    case 90: return "user_canceled";
1556
0
    case 100: return "no_renegotiation";
1557
0
    default: return "<unknown>";
1558
0
    }
1559
0
}
1560
1561
static const char *
1562
ssl_handshake_type_to_string(uint8_t type)
1563
0
{
1564
0
    switch (type) {
1565
0
    case 0: return "hello_request";
1566
0
    case 1: return "client_hello";
1567
0
    case 2: return "server_hello";
1568
0
    case 11: return "certificate";
1569
0
    case 12: return "server_key_exchange";
1570
0
    case 13: return "certificate_request";
1571
0
    case 14: return "server_hello_done";
1572
0
    case 15: return "certificate_verify";
1573
0
    case 16: return "client_key_exchange";
1574
0
    case 20: return "finished";
1575
0
    default: return "<unknown>";
1576
0
    }
1577
0
}
1578
1579
static void
1580
ssl_protocol_cb(int write_p, int version OVS_UNUSED, int content_type,
1581
                const void *buf_, size_t len, SSL *ssl OVS_UNUSED, void *sslv_)
1582
0
{
1583
0
    const struct ssl_stream *sslv = sslv_;
1584
0
    const uint8_t *buf = buf_;
1585
0
    struct ds details;
1586
1587
0
    if (!VLOG_IS_DBG_ENABLED()) {
1588
0
        return;
1589
0
    }
1590
1591
0
    ds_init(&details);
1592
0
    if (content_type == 20) {
1593
0
        ds_put_cstr(&details, "change_cipher_spec");
1594
0
    } else if (content_type == 21) {
1595
0
        ds_put_format(&details, "alert: %s, %s",
1596
0
                      ssl_alert_level_to_string(buf[0]),
1597
0
                      ssl_alert_description_to_string(buf[1]));
1598
0
    } else if (content_type == 22) {
1599
0
        ds_put_format(&details, "handshake: %s",
1600
0
                      ssl_handshake_type_to_string(buf[0]));
1601
0
    } else {
1602
0
        ds_put_format(&details, "type %d", content_type);
1603
0
    }
1604
1605
0
    VLOG_DBG("%s%u%s%s %s (%"PRIuSIZE" bytes)",
1606
0
             sslv->type == CLIENT ? "client" : "server",
1607
0
             sslv->session_nr, write_p ? "-->" : "<--",
1608
0
             stream_get_name(&sslv->stream), ds_cstr(&details), len);
1609
1610
0
    ds_destroy(&details);
1611
0
}