Code

Automatically prefix all log messages with the plugin name (if available).
[sysdb.git] / src / utils / ssl.c
1 /*
2  * SysDB - src/utils/ssl.c
3  * Copyright (C) 2015 Sebastian 'tokkee' Harl <sh@tokkee.org>
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
17  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR
19  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
28 #if HAVE_CONFIG_H
29 #       include "config.h"
30 #endif
32 #include "utils/ssl.h"
33 #include "utils/error.h"
35 #include <errno.h>
37 #include <stdlib.h>
38 #include <string.h>
40 #include <pthread.h>
42 #include <openssl/ssl.h>
43 #include <openssl/bio.h>
44 #include <openssl/crypto.h>
45 #include <openssl/x509.h>
46 #include <openssl/err.h>
48 /*
49  * data types
50  */
52 struct sdb_ssl_client {
53         SSL_CTX *ctx;
54         sdb_ssl_options_t opts;
55 };
57 struct sdb_ssl_server {
58         SSL_CTX *ctx;
59         sdb_ssl_options_t opts;
60 };
62 struct sdb_ssl_session {
63         SSL *ssl;
64 };
66 /*
67  * OpenSSL helper functions
68  */
70 static pthread_mutex_t *mutexes = NULL;
71 static int mutexes_num = 0;
73 static void
74 locking_callback(int mode, int n, const char *file, int line)
75 {
76         if (! mutexes) {
77                 sdb_log(SDB_LOG_EMERG, "ssl: CRYPTO_lock called from %s:%d "
78                                 "before initializing SSL", file, line);
79                 return;
80         }
81         if (n >= mutexes_num) {
82                 sdb_log(SDB_LOG_EMERG, "ssl: CRYPTO_lock called from %s:%d "
83                                 "for mutex %d but only %d are available",
84                                 file, line, n, mutexes_num);
85                 return;
86         }
88         if (mode & CRYPTO_LOCK)
89                 pthread_mutex_lock(&mutexes[n]);
90         else
91                 pthread_mutex_unlock(&mutexes[n]);
92 } /* locking_callback */
94 static void
95 threadid_callback(CRYPTO_THREADID *id)
96 {
97         CRYPTO_THREADID_set_numeric(id, (unsigned long)pthread_self());
98 } /* threadid_callback */
100 /*
101  * private helper functions
102  */
104 /* log all pending SSL errors */
105 static void
106 ssl_log(int prio, const char *prefix, ...)
108         char msg[1024];
109         va_list ap;
111         va_start(ap, prefix);
112         vsnprintf(msg, sizeof(msg), prefix, ap);
113         msg[sizeof(msg) - 1] = '\0';
114         va_end(ap);
116         while (42) {
117                 unsigned long e = ERR_get_error();
118                 if (! e)
119                         break;
120                 sdb_log(prio, "%s: %s", msg, ERR_reason_error_string(e));
121         }
122 } /* ssl_log */
124 static void
125 ssl_log_err(int prio, SSL *ssl, int status, const char *prefix, ...)
127         int err = SSL_get_error(ssl, status);
128         char msg[1024];
129         va_list ap;
131         va_start(ap, prefix);
132         vsnprintf(msg, sizeof(msg), prefix, ap);
133         msg[sizeof(msg) - 1] = '\0';
134         va_end(ap);
136         errno = 0;
137         switch (err) {
138                 case SSL_ERROR_NONE:
139                         sdb_log(prio, "%s: success", msg);
140                         break;
141                 case SSL_ERROR_ZERO_RETURN:
142                         errno = ECONNRESET;
143                         break;
144                 case SSL_ERROR_WANT_READ:
145                 case SSL_ERROR_WANT_WRITE:
146                         errno = EWOULDBLOCK;
147                         break;
148                 case SSL_ERROR_WANT_CONNECT:
149                 case SSL_ERROR_WANT_ACCEPT:
150                         sdb_log(prio, "%s: connection not set up", msg);
151                         break;
152                 case SSL_ERROR_WANT_X509_LOOKUP:
153                         sdb_log(prio, "%s: application error", msg);
154                         break;
155                 case SSL_ERROR_SYSCALL:
156                         if (ERR_peek_error())
157                                 return ssl_log(prio, msg);
158                         if (! status)
159                                 sdb_log(prio, "%s: unexpected end-of-file", msg);
160                         else if (! errno)
161                                 errno = EIO;
162                 case SSL_ERROR_SSL:
163                         return ssl_log(prio, msg);
164                 default:
165                         sdb_log(prio, "%s: unkown SSL error %d", msg, err);
166                         break;
167         }
169         if (errno) {
170                 char errbuf[1024];
171                 sdb_log(prio, "%s: %s", msg, sdb_strerror(errno, errbuf, sizeof(errbuf)));
172         }
173 } /* ssl_log_err */
175 static int
176 copy_options(sdb_ssl_options_t *dst, const sdb_ssl_options_t *src)
178         sdb_ssl_options_t tmp;
179         sdb_ssl_options_t def = SDB_SSL_DEFAULT_OPTIONS;
181         if (src)
182                 tmp = *src;
183         else
184                 tmp = def;
186         if (! tmp.ca_file)
187                 tmp.ca_file = def.ca_file;
188         if (! tmp.key_file)
189                 tmp.key_file = def.key_file;
190         if (! tmp.cert_file)
191                 tmp.cert_file = def.cert_file;
193         dst->ca_file = strdup(tmp.ca_file);
194         dst->key_file = strdup(tmp.key_file);
195         dst->cert_file = strdup(tmp.cert_file);
196         if ((! dst->ca_file) || (! dst->key_file) || (! dst->cert_file))
197                 return -1;
198         if (tmp.crl_file) {
199                 dst->crl_file = strdup(tmp.crl_file);
200                 if (! dst->crl_file)
201                         return -1;
202         }
203         return 0;
204 } /* copy_options */
206 /*
207  * public API
208  */
210 int
211 sdb_ssl_init(void)
213         int i;
215         SSL_load_error_strings();
216         OpenSSL_add_ssl_algorithms();
218         mutexes = calloc(CRYPTO_num_locks(), sizeof(*mutexes));
219         if (! mutexes) {
220                 char errbuf[1024];
221                 sdb_log(SDB_LOG_ERR, "ssl: Failed to allocate mutexes: %s",
222                                 sdb_strerror(errno, errbuf, sizeof(errbuf)));
223                 return -1;
224         }
225         for (i = 0; i < CRYPTO_num_locks(); ++i) {
226                 errno = pthread_mutex_init(&mutexes[i], /* attr = */ NULL);
227                 if (errno) {
228                         char errbuf[1024];
229                         sdb_log(SDB_LOG_ERR, "ssl: Failed to initialize mutex: %s",
230                                         sdb_strerror(errno, errbuf, sizeof(errbuf)));
231                         return -1;
232                 }
233                 mutexes_num = i + 1;
234         }
236         CRYPTO_set_locking_callback(locking_callback);
237         CRYPTO_THREADID_set_callback(threadid_callback);
238         return 0;
239 } /* sdb_ssl_init */
241 void
242 sdb_ssl_shutdown(void)
244         int i;
246         ERR_free_strings();
248         for (i = 0; i < mutexes_num; ++i)
249                 pthread_mutex_destroy(&mutexes[i]);
250         if (mutexes)
251                 free(mutexes);
252         mutexes = NULL;
253         mutexes_num = 0;
254 } /* sdb_ssl_shutdown */
256 sdb_ssl_client_t *
257 sdb_ssl_client_create(const sdb_ssl_options_t *opts)
259         sdb_ssl_client_t *client;
261         client = calloc(1, sizeof(*client));
262         if (! client)
263                 return NULL;
265         if (copy_options(&client->opts, opts)) {
266                 sdb_ssl_client_destroy(client);
267                 return NULL;
268         }
270         client->ctx = SSL_CTX_new(SSLv23_client_method());
271         if (! client->ctx) {
272                 ssl_log(SDB_LOG_ERR, "ssl: Failed to create SSL context");
273                 sdb_ssl_client_destroy(client);
274                 return NULL;
275         }
277         if (! SSL_CTX_load_verify_locations(client->ctx,
278                                 client->opts.ca_file, NULL)) {
279                 ssl_log(SDB_LOG_ERR, "ssl: Failed to load CA file '%s'",
280                                 client->opts.ca_file);
281                 sdb_ssl_client_destroy(client);
282                 return NULL;
283         }
284         if (! SSL_CTX_use_certificate_file(client->ctx,
285                                 client->opts.cert_file, SSL_FILETYPE_PEM)) {
286                 ssl_log(SDB_LOG_ERR, "ssl: Failed to load cert file '%s'",
287                                 client->opts.cert_file);
288                 sdb_ssl_client_destroy(client);
289                 return NULL;
290         }
291         if (! SSL_CTX_use_PrivateKey_file(client->ctx,
292                                 client->opts.key_file, SSL_FILETYPE_PEM)) {
293                 ssl_log(SDB_LOG_ERR, "ssl: Failed to load key file '%s'",
294                                 client->opts.key_file);
295                 sdb_ssl_client_destroy(client);
296                 return NULL;
297         }
298         if (! SSL_CTX_check_private_key(client->ctx)) {
299                 ssl_log(SDB_LOG_ERR, "ssl: Failed to verify key (%s)",
300                                 client->opts.key_file);
301                 sdb_ssl_client_destroy(client);
302                 return NULL;
303         }
305         SSL_CTX_set_mode(client->ctx, SSL_MODE_AUTO_RETRY);
306         SSL_CTX_set_verify(client->ctx, SSL_VERIFY_PEER, NULL);
307         SSL_CTX_set_verify_depth(client->ctx, 1);
308         return client;
309 } /* sdb_ssl_client_create */
311 void
312 sdb_ssl_client_destroy(sdb_ssl_client_t *client)
314         if (! client)
315                 return;
317         if (client->ctx)
318                 SSL_CTX_free(client->ctx);
319         sdb_ssl_free_options(&client->opts);
320         free(client);
321 } /* sdb_ssl_client_destroy */
323 sdb_ssl_session_t *
324 sdb_ssl_client_connect(sdb_ssl_client_t *client, int fd)
326         sdb_ssl_session_t *session;
327         int status;
328         BIO *bio;
330         if ((! client) || (fd < 0))
331                 return NULL;
333         session = calloc(1, sizeof(*session));
334         if (! session)
335                 return NULL;
337         bio = BIO_new_socket(fd, BIO_NOCLOSE);
338         if (! bio) {
339                 ssl_log(SDB_LOG_ERR, "ssl: Failed to create SSL socket");
340                 sdb_ssl_session_destroy(session);
341                 return NULL;
342         }
343         session->ssl = SSL_new(client->ctx);
344         if (! session->ssl) {
345                 ssl_log(SDB_LOG_ERR, "ssl: Failed to create SSL object");
346                 sdb_ssl_session_destroy(session);
347                 return NULL;
348         }
349         SSL_set_bio(session->ssl, bio, bio);
351         if ((status = SSL_connect(session->ssl)) <= 0) {
352                 ssl_log_err(SDB_LOG_ERR, session->ssl, status,
353                                 "ssl: Failed to initialize SSL session");
354                 sdb_ssl_session_destroy(session);
355                 return NULL;
356         }
357         if (SSL_get_verify_result(session->ssl) != X509_V_OK) {
358                 sdb_log(SDB_LOG_ERR, "Failed to verify SSL connection");
359                 sdb_ssl_session_destroy(session);
360                 return NULL;
361         }
362         return session;
363 } /* sdb_ssl_client_connect */
365 sdb_ssl_server_t *
366 sdb_ssl_server_create(const sdb_ssl_options_t *opts)
368         sdb_ssl_server_t *server;
370         server = calloc(1, sizeof(*server));
371         if (! server)
372                 return NULL;
374         if (copy_options(&server->opts, opts)) {
375                 sdb_ssl_server_destroy(server);
376                 return NULL;
377         }
379         server->ctx = SSL_CTX_new(SSLv23_server_method());
380         if (! server->ctx) {
381                 ssl_log(SDB_LOG_ERR, "ssl: Failed to create SSL context");
382                 sdb_ssl_server_destroy(server);
383                 return NULL;
384         }
386         /* Recommendation documented at
387          * https://hynek.me/articles/hardening-your-web-servers-ssl-ciphers/ */
388         if (! SSL_CTX_set_cipher_list(server->ctx,
389                                 "ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:"
390                                 "DH+AES:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+3DES:"
391                                 "!aNULL:!MD5:!DSS")) {
392                 sdb_log(SDB_LOG_ERR, "ssl: Invalid cipher list");
393                 sdb_ssl_server_destroy(server);
394                 return NULL;
395         }
397         if (! SSL_CTX_load_verify_locations(server->ctx,
398                                 server->opts.ca_file, NULL)) {
399                 ssl_log(SDB_LOG_ERR, "Failed to load CA file %s",
400                                 server->opts.ca_file);
401                 sdb_ssl_server_destroy(server);
402                 return NULL;
403         }
404         SSL_CTX_set_client_CA_list(server->ctx,
405                         SSL_load_client_CA_file(server->opts.ca_file));
407         if (! SSL_CTX_use_certificate_file(server->ctx,
408                                 server->opts.cert_file, SSL_FILETYPE_PEM)) {
409                 ssl_log(SDB_LOG_ERR, "Failed to load SSL cert file %s",
410                                 server->opts.cert_file);
411                 sdb_ssl_server_destroy(server);
412                 return NULL;
413         }
414         if (! SSL_CTX_use_PrivateKey_file(server->ctx,
415                                 server->opts.key_file, SSL_FILETYPE_PEM)) {
416                 ssl_log(SDB_LOG_ERR, "Failed to load SSL key file %s",
417                                 server->opts.key_file);
418                 sdb_ssl_server_destroy(server);
419                 return NULL;
420         }
421         if (! SSL_CTX_check_private_key(server->ctx)) {
422                 ssl_log(SDB_LOG_ERR, "Failed to verify SSL private key");
423                 sdb_ssl_server_destroy(server);
424                 return NULL;
425         }
427         SSL_CTX_set_mode(server->ctx, SSL_MODE_AUTO_RETRY);
428         SSL_CTX_set_verify(server->ctx,
429                         SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, NULL);
430         SSL_CTX_set_verify_depth(server->ctx, 1);
432         /* TODO: handle server->opts.crl_file */
433         return server;
434 } /* sdb_ssl_server_create */
436 void
437 sdb_ssl_server_destroy(sdb_ssl_server_t *server)
439         if (! server)
440                 return;
442         if (server->ctx)
443                 SSL_CTX_free(server->ctx);
444         sdb_ssl_free_options(&server->opts);
445         free(server);
446 } /* sdb_ssl_server_destroy */
448 sdb_ssl_session_t *
449 sdb_ssl_server_accept(sdb_ssl_server_t *server, int fd)
451         sdb_ssl_session_t *session;
452         int status;
453         BIO *bio;
455         if ((! server) || (fd < 0))
456                 return NULL;
458         session = calloc(1, sizeof(*session));
459         if (! session)
460                 return NULL;
462         bio = BIO_new_socket(fd, BIO_NOCLOSE);
463         if (! bio) {
464                 ssl_log(SDB_LOG_ERR, "ssl: Failed to create SSL socket");
465                 sdb_ssl_session_destroy(session);
466                 return NULL;
467         }
468         session->ssl = SSL_new(server->ctx);
469         if (! session->ssl) {
470                 ssl_log(SDB_LOG_ERR, "ssl: Failed to create SSL object");
471                 sdb_ssl_session_destroy(session);
472                 return NULL;
473         }
474         SSL_set_bio(session->ssl, bio, bio);
476         while (42) {
477                 if ((status = SSL_accept(session->ssl)) <= 0) {
478                         if (SSL_get_error(session->ssl, status) == SSL_ERROR_WANT_READ)
479                                 continue;
481                         ssl_log_err(SDB_LOG_ERR, session->ssl, status,
482                                         "ssl: Failed to initialize SSL session");
483                         sdb_ssl_session_destroy(session);
484                         return NULL;
485                 }
486                 break;
487         }
488         if (SSL_get_verify_result(session->ssl) != X509_V_OK) {
489                 sdb_log(SDB_LOG_ERR, "Failed to verify SSL connection");
490                 sdb_ssl_session_destroy(session);
491                 return NULL;
492         }
493         return session;
494 } /* sdb_ssl_server_accept */
496 void
497 sdb_ssl_session_destroy(sdb_ssl_session_t *session)
499         if (! session)
500                 return;
502         if (session->ssl) {
503                 SSL_shutdown(session->ssl);
504                 SSL_clear(session->ssl);
505                 SSL_free(session->ssl);
506         }
507         free(session);
508 } /* sdb_ssl_session_destroy */
510 char *
511 sdb_ssl_session_peer(sdb_ssl_session_t *session)
513         X509 *x509;
514         X509_NAME *name;
516         char *peer = NULL;
517         char p[1024];
519         if (! session)
520                 return NULL;
522         x509 = SSL_get_peer_certificate(session->ssl);
523         if (! x509)
524                 return NULL;
525         name = X509_get_subject_name(x509);
526         if (! name) {
527                 X509_free(x509);
528                 return NULL;
529         }
531         if (X509_NAME_get_text_by_NID(name, NID_commonName, p, sizeof(p)) > 0)
532                 peer = strdup(p);
534         X509_free(x509);
535         return peer;
536 } /* sdb_ssl_session_peer */
538 ssize_t
539 sdb_ssl_session_write(sdb_ssl_session_t *session, const void *buf, size_t n)
541         int status;
543         if (! session)
544                 return -1;
546         status = SSL_write(session->ssl, buf, (int)n);
547         if (status) {
548                 if ((status < 0) && (errno != EAGAIN))
549                         ssl_log_err(SDB_LOG_ERR, session->ssl, status, "ssl: Write error");
550                 return (ssize_t)status;
551         }
553         status = SSL_get_error(session->ssl, status);
554         if (status == SSL_ERROR_ZERO_RETURN)
555                 return 0;
557         if ((status == SSL_ERROR_WANT_READ) || (status == SSL_ERROR_WANT_WRITE)) {
558                 errno = EWOULDBLOCK;
559                 return -1;
560         }
561         errno = ECONNRESET;
562         return -1;
563 } /* sdb_ssl_session_write */
565 ssize_t
566 sdb_ssl_session_read(sdb_ssl_session_t *session, void *buf, size_t n)
568         int status;
570         if (! session)
571                 return -1;
573         status = SSL_read(session->ssl, buf, (int)n);
574         if (status) {
575                 if ((status < 0) && (errno != EAGAIN))
576                         ssl_log_err(SDB_LOG_ERR, session->ssl, status, "ssl: Read error");
577                 return (ssize_t)status;
578         }
580         status = SSL_get_error(session->ssl, status);
581         if (status == SSL_ERROR_ZERO_RETURN)
582                 return 0;
584         if ((status == SSL_ERROR_WANT_READ) || (status == SSL_ERROR_WANT_WRITE)) {
585                 errno = EWOULDBLOCK;
586                 return -1;
587         }
588         errno = ECONNRESET;
589         return -1;
590 } /* sdb_ssl_session_read */
592 void
593 sdb_ssl_free_options(sdb_ssl_options_t *opts)
595         if (! opts)
596                 return;
598         if (opts->ca_file)
599                 free(opts->ca_file);
600         if (opts->key_file)
601                 free(opts->key_file);
602         if (opts->cert_file)
603                 free(opts->cert_file);
604         if (opts->crl_file)
605                 free(opts->crl_file);
607         opts->ca_file = opts->key_file = opts->cert_file = opts->crl_file = NULL;
608 } /* sdb_ssl_free_options */
610 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */