summaryrefslogtreecommitdiffstats
path: root/libnetdata/socket/security.c
blob: 3a3a171e529678e30a78259a14a5fcd9c6a9a0a2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
#include "../libnetdata.h"

#ifdef ENABLE_HTTPS

SSL_CTX *netdata_ssl_exporting_ctx =NULL;
SSL_CTX *netdata_ssl_streaming_sender_ctx =NULL;
SSL_CTX *netdata_ssl_web_server_ctx =NULL;
const char *netdata_ssl_security_key =NULL;
const char *netdata_ssl_security_cert =NULL;
const char *tls_version=NULL;
const char *tls_ciphers=NULL;
bool netdata_ssl_validate_certificate =  true;
bool netdata_ssl_validate_certificate_sender =  true;

static SOCKET_PEERS netdata_ssl_peers(NETDATA_SSL *ssl) {
    int sock_fd;

    if(unlikely(!ssl->conn))
        sock_fd = -1;
    else
        sock_fd = SSL_get_rfd(ssl->conn);

    return socket_peers(sock_fd);
}

static void netdata_ssl_log_error_queue(const char *call, NETDATA_SSL *ssl, unsigned long err) {
    error_limit_static_thread_var(erl, 1, 0);

    if(err == SSL_ERROR_NONE)
        err = ERR_get_error();

    if(err == SSL_ERROR_NONE)
        return;

    do {
        char *code;

        switch (err) {
            case SSL_ERROR_SSL:
                code = "SSL_ERROR_SSL";
                ssl->state = NETDATA_SSL_STATE_FAILED;
                break;

            case SSL_ERROR_WANT_READ:
                code = "SSL_ERROR_WANT_READ";
                break;

            case SSL_ERROR_WANT_WRITE:
                code = "SSL_ERROR_WANT_WRITE";
                break;

            case SSL_ERROR_WANT_X509_LOOKUP:
                code = "SSL_ERROR_WANT_X509_LOOKUP";
                break;

            case SSL_ERROR_SYSCALL:
                code = "SSL_ERROR_SYSCALL";
                ssl->state = NETDATA_SSL_STATE_FAILED;
                break;

            case SSL_ERROR_ZERO_RETURN:
                code = "SSL_ERROR_ZERO_RETURN";
                break;

            case SSL_ERROR_WANT_CONNECT:
                code = "SSL_ERROR_WANT_CONNECT";
                break;

            case SSL_ERROR_WANT_ACCEPT:
                code = "SSL_ERROR_WANT_ACCEPT";
                break;

#ifdef SSL_ERROR_WANT_ASYNC
            case SSL_ERROR_WANT_ASYNC:
                code = "SSL_ERROR_WANT_ASYNC";
                break;
#endif

#ifdef SSL_ERROR_WANT_ASYNC_JOB
            case SSL_ERROR_WANT_ASYNC_JOB:
                code = "SSL_ERROR_WANT_ASYNC_JOB";
                break;
#endif

#ifdef SSL_ERROR_WANT_CLIENT_HELLO_CB
            case SSL_ERROR_WANT_CLIENT_HELLO_CB:
                code = "SSL_ERROR_WANT_CLIENT_HELLO_CB";
                break;
#endif

#ifdef SSL_ERROR_WANT_RETRY_VERIFY
            case SSL_ERROR_WANT_RETRY_VERIFY:
                code = "SSL_ERROR_WANT_RETRY_VERIFY";
                break;
#endif

            default:
                code = "SSL_ERROR_UNKNOWN";
                break;
        }

        char str[1024 + 1];
        ERR_error_string_n(err, str, 1024);
        str[1024] = '\0';
        SOCKET_PEERS peers = netdata_ssl_peers(ssl);
        error_limit(&erl, "SSL: %s() on socket local [[%s]:%d] <-> remote [[%s]:%d], returned error %lu (%s): %s",
                    call, peers.local.ip, peers.local.port, peers.peer.ip, peers.peer.port, err, code, str);

    } while((err = ERR_get_error()));
}

bool netdata_ssl_open(NETDATA_SSL *ssl, SSL_CTX *ctx, int fd) {
    errno = 0;
    ssl->ssl_errno = 0;

    if(ssl->conn) {
        if(!ctx || SSL_get_SSL_CTX(ssl->conn) != ctx) {
            SSL_free(ssl->conn);
            ssl->conn = NULL;
        }
        else if (SSL_clear(ssl->conn) == 0) {
            netdata_ssl_log_error_queue("SSL_clear", ssl, SSL_ERROR_NONE);
            SSL_free(ssl->conn);
            ssl->conn = NULL;
        }
    }

    if(!ssl->conn) {
        if(!ctx) {
            internal_error(true, "SSL: not CTX given");
            ssl->state = NETDATA_SSL_STATE_FAILED;
            return false;
        }

        ssl->conn = SSL_new(ctx);
        if (!ssl->conn) {
            netdata_ssl_log_error_queue("SSL_new", ssl, SSL_ERROR_NONE);
            ssl->state = NETDATA_SSL_STATE_FAILED;
            return false;
        }
    }

    if(SSL_set_fd(ssl->conn, fd) != 1) {
        netdata_ssl_log_error_queue("SSL_set_fd", ssl, SSL_ERROR_NONE);
        ssl->state = NETDATA_SSL_STATE_FAILED;
        return false;
    }

    ssl->state = NETDATA_SSL_STATE_INIT;

    ERR_clear_error();

    return true;
}

void netdata_ssl_close(NETDATA_SSL *ssl) {
    errno = 0;
    ssl->ssl_errno = 0;

    if(ssl->conn) {
        if(SSL_connection(ssl)) {
            int ret = SSL_shutdown(ssl->conn);
            if(ret == 0)
                SSL_shutdown(ssl->conn);
        }

        SSL_free(ssl->conn);

        ERR_clear_error();
    }

    *ssl = NETDATA_SSL_UNSET_CONNECTION;
}

static inline bool is_handshake_complete(NETDATA_SSL *ssl, const char *op) {
    error_limit_static_thread_var(erl, 1, 0);

    if(unlikely(!ssl->conn)) {
        internal_error(true, "SSL: trying to %s on a NULL connection", op);
        return false;
    }

    switch(ssl->state) {
        case NETDATA_SSL_STATE_NOT_SSL: {
            SOCKET_PEERS peers = netdata_ssl_peers(ssl);
            error_limit(&erl, "SSL: on socket local [[%s]:%d] <-> remote [[%s]:%d], attempt to %s on non-SSL connection",
                        peers.local.ip, peers.local.port, peers.peer.ip, peers.peer.port, op);
            return false;
        }

        case NETDATA_SSL_STATE_INIT: {
            SOCKET_PEERS peers = netdata_ssl_peers(ssl);
            error_limit(&erl, "SSL: on socket local [[%s]:%d] <-> remote [[%s]:%d], attempt to %s on an incomplete connection",
                        peers.local.ip, peers.local.port, peers.peer.ip, peers.peer.port, op);
            return false;
        }

        case NETDATA_SSL_STATE_FAILED: {
            SOCKET_PEERS peers = netdata_ssl_peers(ssl);
            error_limit(&erl, "SSL: on socket local [[%s]:%d] <-> remote [[%s]:%d], attempt to %s on a failed connection",
                        peers.local.ip, peers.local.port, peers.peer.ip, peers.peer.port, op);
            return false;
        }

        case NETDATA_SSL_STATE_COMPLETE: {
            return true;
        }
    }

    return false;
}

/*
 * netdata_ssl_read() should return the same as read():
 *
 * Positive value: The read() function succeeded and read some bytes. The exact number of bytes read is returned.
 *
 * Zero: For files and sockets, a return value of zero signifies end-of-file (EOF), meaning no more data is available
 *       for reading. For sockets, this usually means the other side has closed the connection.
 *
 * -1: An error occurred. The specific error can be found by examining the errno variable.
 *     EAGAIN or EWOULDBLOCK: The file descriptor is in non-blocking mode, and the read operation would block.
 *     (These are often the same value, but can be different on some systems.)
 */

ssize_t netdata_ssl_read(NETDATA_SSL *ssl, void *buf, size_t num) {
    errno = 0;
    ssl->ssl_errno = 0;

    if(unlikely(!is_handshake_complete(ssl, "read")))
        return -1;

    int bytes = SSL_read(ssl->conn, buf, (int)num);

    if(unlikely(bytes <= 0)) {
        int err = SSL_get_error(ssl->conn, bytes);
        if (err == SSL_ERROR_ZERO_RETURN) {
            ssl->ssl_errno = err;
            return 0;
        }

        if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) {
            ssl->ssl_errno = err;
            errno = EWOULDBLOCK;
        }
        else
            netdata_ssl_log_error_queue("SSL_read", ssl, err);

        bytes = -1;  // according to read() or recv()
    }

    return bytes;
}

/*
 * netdata_ssl_write() should return the same as write():
 *
 * Positive value: The write() function succeeded and wrote some bytes. The exact number of bytes written is returned.
 *
 * Zero: It's technically possible for write() to return zero, indicating that zero bytes were written. However, for a
 * socket, this generally does not happen unless the size of the data to be written is zero.
 *
 * -1: An error occurred. The specific error can be found by examining the errno variable.
 *     EAGAIN or EWOULDBLOCK: The file descriptor is in non-blocking mode, and the write operation would block.
 *     (These are often the same value, but can be different on some systems.)
 */

ssize_t netdata_ssl_write(NETDATA_SSL *ssl, const void *buf, size_t num) {
    errno = 0;
    ssl->ssl_errno = 0;

    if(unlikely(!is_handshake_complete(ssl, "write")))
        return -1;

    int bytes = SSL_write(ssl->conn, (uint8_t *)buf, (int)num);

    if(unlikely(bytes <= 0)) {
        int err = SSL_get_error(ssl->conn, bytes);
        if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) {
            ssl->ssl_errno = err;
            errno = EWOULDBLOCK;
        }
        else
            netdata_ssl_log_error_queue("SSL_write", ssl, err);

        bytes = -1; // according to write() or send()
    }

    return bytes;
}

static inline bool is_handshake_initialized(NETDATA_SSL *ssl, const char *op) {
    error_limit_static_thread_var(erl, 1, 0);

    if(unlikely(!ssl->conn)) {
        internal_error(true, "SSL: trying to %s on a NULL connection", op);
        return false;
    }

    switch(ssl->state) {
        case NETDATA_SSL_STATE_NOT_SSL: {
            SOCKET_PEERS peers = netdata_ssl_peers(ssl);
            error_limit(&erl, "SSL: on socket local [[%s]:%d] <-> remote [[%s]:%d], attempt to %s on non-SSL connection",
                        peers.local.ip, peers.local.port, peers.peer.ip, peers.peer.port, op);
            return false;
        }

        case NETDATA_SSL_STATE_INIT: {
            return true;
        }

        case NETDATA_SSL_STATE_FAILED: {
            SOCKET_PEERS peers = netdata_ssl_peers(ssl);
            error_limit(&erl, "SSL: on socket local [[%s]:%d] <-> remote [[%s]:%d], attempt to %s on a failed connection",
                        peers.local.ip, peers.local.port, peers.peer.ip, peers.peer.port, op);
            return false;
        }

        case NETDATA_SSL_STATE_COMPLETE: {
            SOCKET_PEERS peers = netdata_ssl_peers(ssl);
            error_limit(&erl, "SSL: on socket local [[%s]:%d] <-> remote [[%s]:%d], attempt to %s on an complete connection",
                        peers.local.ip, peers.local.port, peers.peer.ip, peers.peer.port, op);
            return false;
        }
    }

    return false;
}

#define WANT_READ_WRITE_TIMEOUT_MS 10

static inline bool want_read_write_should_retry(NETDATA_SSL *ssl, int err) {
    int ssl_errno = SSL_get_error(ssl->conn, err);
    if(ssl_errno == SSL_ERROR_WANT_READ || ssl_errno == SSL_ERROR_WANT_WRITE) {
        struct pollfd pfds[1] = { [0] = {
                .fd = SSL_get_rfd(ssl->conn),
                .events = (short)(((ssl_errno == SSL_ERROR_WANT_READ ) ? POLLIN  : 0) |
                                  ((ssl_errno == SSL_ERROR_WANT_WRITE) ? POLLOUT : 0)),
        }};

        if(poll(pfds, 1, WANT_READ_WRITE_TIMEOUT_MS) <= 0)
            return false; // timeout (0) or error (<0)

        return true; // we have activity, so we should retry
    }

    return false; // an unknown error
}

bool netdata_ssl_connect(NETDATA_SSL *ssl) {
    errno = 0;
    ssl->ssl_errno = 0;

    if(unlikely(!is_handshake_initialized(ssl, "connect")))
        return false;

    SSL_set_connect_state(ssl->conn);

    int err;
    while ((err = SSL_connect(ssl->conn)) != 1) {
        if(!want_read_write_should_retry(ssl, err))
            break;
    }

    if (err != 1) {
        err = SSL_get_error(ssl->conn, err);
        netdata_ssl_log_error_queue("SSL_connect", ssl, err);
        ssl->state = NETDATA_SSL_STATE_FAILED;
        return false;
    }

    ssl->state = NETDATA_SSL_STATE_COMPLETE;
    return true;
}

bool netdata_ssl_accept(NETDATA_SSL *ssl) {
    errno = 0;
    ssl->ssl_errno = 0;

    if(unlikely(!is_handshake_initialized(ssl, "accept")))
        return false;

    SSL_set_accept_state(ssl->conn);

    int err;
    while ((err = SSL_accept(ssl->conn)) != 1) {
        if(!want_read_write_should_retry(ssl, err))
            break;
    }

    if (err != 1) {
        err = SSL_get_error(ssl->conn, err);
        netdata_ssl_log_error_queue("SSL_accept", ssl, err);
        ssl->state = NETDATA_SSL_STATE_FAILED;
        return false;
    }

    ssl->state = NETDATA_SSL_STATE_COMPLETE;
    return true;
}

/**
 * Info Callback
 *
 * Function used as callback for the OpenSSL Library
 *
 * @param ssl a pointer to the SSL structure of the client
 * @param where the variable with the flags set.
 * @param ret the return of the caller
 */
static void netdata_ssl_info_callback(const SSL *ssl, int where, int ret __maybe_unused) {
    (void)ssl;
    if (where & SSL_CB_ALERT) {
        netdata_log_debug(D_WEB_CLIENT,"SSL INFO CALLBACK %s %s", SSL_alert_type_string(ret), SSL_alert_desc_string_long(ret));
    }
}

/**
 * OpenSSL Library
 *
 * Starts the openssl library for the Netdata.
 */
void netdata_ssl_initialize_openssl() {

#if OPENSSL_VERSION_NUMBER < OPENSSL_VERSION_110
# if (SSLEAY_VERSION_NUMBER >= OPENSSL_VERSION_097)
    OPENSSL_config(NULL);
# endif

    SSL_load_error_strings();

    SSL_library_init();

#else

    if (OPENSSL_init_ssl(OPENSSL_INIT_LOAD_CONFIG, NULL) != 1) {
        netdata_log_error("SSL library cannot be initialized.");
    }

#endif
}

#if OPENSSL_VERSION_NUMBER >= OPENSSL_VERSION_110
/**
 * TLS version
 *
 * Returns the TLS version depending of the user input.
 *
 * @param lversion is the user input.
 *
 * @return it returns the version number.
 */
static int netdata_ssl_select_tls_version(const char *lversion) {
    if (!strcmp(lversion, "1") || !strcmp(lversion, "1.0"))
        return TLS1_VERSION;
    else if (!strcmp(lversion, "1.1"))
        return TLS1_1_VERSION;
    else if (!strcmp(lversion, "1.2"))
        return TLS1_2_VERSION;
#if defined(TLS1_3_VERSION)
    else if (!strcmp(lversion, "1.3"))
        return TLS1_3_VERSION;
#endif

#if defined(TLS_MAX_VERSION)
    return TLS_MAX_VERSION;
#else
    return TLS1_2_VERSION;
#endif
}
#endif

/**
 * Initialize Openssl Client
 *
 * Starts the client context with TLS 1.2.
 *
 * @return It returns the context on success or NULL otherwise
 */
SSL_CTX * netdata_ssl_create_client_ctx(unsigned long mode) {
    SSL_CTX *ctx;
#if OPENSSL_VERSION_NUMBER < OPENSSL_VERSION_110
    ctx = SSL_CTX_new(SSLv23_client_method());
#else
    ctx = SSL_CTX_new(TLS_client_method());
#endif
    if(ctx) {
#if OPENSSL_VERSION_NUMBER < OPENSSL_VERSION_110
        SSL_CTX_set_options (ctx,SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3|SSL_OP_NO_COMPRESSION);
#else
        SSL_CTX_set_min_proto_version(ctx, TLS1_VERSION);
# if defined(TLS_MAX_VERSION)
        SSL_CTX_set_max_proto_version(ctx, TLS_MAX_VERSION);
# elif defined(TLS1_3_VERSION)
        SSL_CTX_set_max_proto_version(ctx, TLS1_3_VERSION);
# elif defined(TLS1_2_VERSION)
        SSL_CTX_set_max_proto_version(ctx, TLS1_2_VERSION);
# endif
#endif
    }

    if(mode)
        SSL_CTX_set_mode(ctx, mode);

    return ctx;
}

/**
 * Initialize OpenSSL server
 *
 * Starts the server context with TLS 1.2 and load the certificate.
 *
 * @return It returns the context on success or NULL otherwise
 */
static SSL_CTX * netdata_ssl_create_server_ctx(unsigned long mode) {
    SSL_CTX *ctx;
    char lerror[512];
	static int netdata_id_context = 1;

    //TO DO: Confirm the necessity to check return for other OPENSSL function
#if OPENSSL_VERSION_NUMBER < OPENSSL_VERSION_110
	ctx = SSL_CTX_new(SSLv23_server_method());
    if (!ctx) {
		netdata_log_error("Cannot create a new SSL context, netdata won't encrypt communication");
        return NULL;
    }

    SSL_CTX_use_certificate_file(ctx, netdata_ssl_security_cert, SSL_FILETYPE_PEM);
#else
    ctx = SSL_CTX_new(TLS_server_method());
    if (!ctx) {
        netdata_log_error("Cannot create a new SSL context, netdata won't encrypt communication");
        return NULL;
    }

    SSL_CTX_use_certificate_chain_file(ctx, netdata_ssl_security_cert);
#endif

#if OPENSSL_VERSION_NUMBER < OPENSSL_VERSION_110
    SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3|SSL_OP_NO_COMPRESSION);
#else
    SSL_CTX_set_min_proto_version(ctx, TLS1_VERSION);
    SSL_CTX_set_max_proto_version(ctx, netdata_ssl_select_tls_version(tls_version));

    if(tls_ciphers  && strcmp(tls_ciphers, "none") != 0) {
        if (!SSL_CTX_set_cipher_list(ctx, tls_ciphers)) {
            netdata_log_error("SSL error. cannot set the cipher list");
        }
    }
#endif

    SSL_CTX_use_PrivateKey_file(ctx, netdata_ssl_security_key,SSL_FILETYPE_PEM);

    if (!SSL_CTX_check_private_key(ctx)) {
        ERR_error_string_n(ERR_get_error(),lerror,sizeof(lerror));
        netdata_log_error("SSL cannot check the private key: %s",lerror);
        SSL_CTX_free(ctx);
        return NULL;
    }

	SSL_CTX_set_session_id_context(ctx,(void*)&netdata_id_context,(unsigned int)sizeof(netdata_id_context));
    SSL_CTX_set_info_callback(ctx, netdata_ssl_info_callback);

#if (OPENSSL_VERSION_NUMBER < OPENSSL_VERSION_095)
	SSL_CTX_set_verify_depth(ctx,1);
#endif
    netdata_log_debug(D_WEB_CLIENT,"SSL GLOBAL CONTEXT STARTED\n");

    SSL_CTX_set_mode(ctx, mode);

    return ctx;
}

/**
 * Start SSL
 *
 * Call the correct function to start the SSL context.
 *
 * @param selector informs the context that must be initialized, the following list has the valid values:
 *      NETDATA_SSL_CONTEXT_SERVER - the server context
 *      NETDATA_SSL_CONTEXT_STREAMING - Starts the streaming context.
 *      NETDATA_SSL_CONTEXT_EXPORTING - Starts the OpenTSDB context
 */
void netdata_ssl_initialize_ctx(int selector) {
    static SPINLOCK sp = NETDATA_SPINLOCK_INITIALIZER;
    spinlock_lock(&sp);

    switch (selector) {
        case NETDATA_SSL_WEB_SERVER_CTX: {
            if(!netdata_ssl_web_server_ctx) {
                struct stat statbuf;
                if (stat(netdata_ssl_security_key, &statbuf) || stat(netdata_ssl_security_cert, &statbuf))
                    netdata_log_info("To use encryption it is necessary to set \"ssl certificate\" and \"ssl key\" in [web] !\n");
                else {
                    netdata_ssl_web_server_ctx = netdata_ssl_create_server_ctx(
                            SSL_MODE_ENABLE_PARTIAL_WRITE |
                            SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
                            // SSL_MODE_AUTO_RETRY |
                            0);

                    if(netdata_ssl_web_server_ctx && !netdata_ssl_validate_certificate)
                        SSL_CTX_set_verify(netdata_ssl_web_server_ctx, SSL_VERIFY_NONE, NULL);
                }
            }
            break;
        }

        case NETDATA_SSL_STREAMING_SENDER_CTX: {
            if(!netdata_ssl_streaming_sender_ctx) {
                //This is necessary for the stream, because it is working sometimes with nonblock socket.
                //It returns the bitmask after to change, there is not any description of errors in the documentation
                netdata_ssl_streaming_sender_ctx = netdata_ssl_create_client_ctx(
                        SSL_MODE_ENABLE_PARTIAL_WRITE |
                        SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
                        // SSL_MODE_AUTO_RETRY |
                        0
                );

                if(netdata_ssl_streaming_sender_ctx && !netdata_ssl_validate_certificate_sender)
                    SSL_CTX_set_verify(netdata_ssl_streaming_sender_ctx, SSL_VERIFY_NONE, NULL);
            }
            break;
        }

        case NETDATA_SSL_EXPORTING_CTX: {
            if(!netdata_ssl_exporting_ctx) {
                netdata_ssl_exporting_ctx = netdata_ssl_create_client_ctx(0);

                if(netdata_ssl_exporting_ctx && !netdata_ssl_validate_certificate)
                    SSL_CTX_set_verify(netdata_ssl_exporting_ctx, SSL_VERIFY_NONE, NULL);
            }
            break;
        }
    }

    spinlock_unlock(&sp);
}

/**
 * Clean Open SSL
 *
 * Clean all the allocated contexts from netdata.
 */
void netdata_ssl_cleanup()
{
    if (netdata_ssl_web_server_ctx) {
        SSL_CTX_free(netdata_ssl_web_server_ctx);
        netdata_ssl_web_server_ctx = NULL;
    }

    if (netdata_ssl_streaming_sender_ctx) {
        SSL_CTX_free(netdata_ssl_streaming_sender_ctx);
        netdata_ssl_streaming_sender_ctx = NULL;
    }

    if (netdata_ssl_exporting_ctx) {
        SSL_CTX_free(netdata_ssl_exporting_ctx);
        netdata_ssl_exporting_ctx = NULL;
    }

#if OPENSSL_VERSION_NUMBER < OPENSSL_VERSION_110
    ERR_free_strings();
#endif
}

/**
 * Test Certificate
 *
 * Check the certificate of Netdata parent
 *
 * @param ssl is the connection structure
 *
 * @return It returns 0 on success and -1 otherwise
 */
int security_test_certificate(SSL *ssl) {
    X509* cert = SSL_get_peer_certificate(ssl);
    int ret;
    long status;
    if (!cert) {
        return -1;
    }

    status = SSL_get_verify_result(ssl);
    if((X509_V_OK != status))
    {
        char error[512];
        ERR_error_string_n(ERR_get_error(), error, sizeof(error));
        netdata_log_error("SSL RFC4158 check:  We have a invalid certificate, the tests result with %ld and message %s", status, error);
        ret = -1;
    } else {
        ret = 0;
    }

    return ret;
}

/**
 * Location for context
 *
 * Case the user give us a directory with the certificates available and
 * the Netdata parent certificate, we use this function to validate the certificate.
 *
 * @param ctx the context where the path will be set.
 * @param file the file with Netdata parent certificate.
 * @param path the directory where the certificates are stored.
 *
 * @return It returns 0 on success and -1 otherwise.
 */
int ssl_security_location_for_context(SSL_CTX *ctx, char *file, char *path) {
    int load_custom = 1, load_default = 1;
    if (file || path) {
        if(!SSL_CTX_load_verify_locations(ctx, file, path)) {
            netdata_log_info("Netdata can not verify custom CAfile or CApath for parent's SSL certificate, so it will use the default OpenSSL configuration to validate certificates!");
            load_custom = 0;
        }
    }

    if(!SSL_CTX_set_default_verify_paths(ctx)) {
        netdata_log_info("Can not verify default OpenSSL configuration to validate certificates!");
        load_default = 0;
    }

    if (load_custom  == 0 && load_default == 0)
        return -1;

    return 0;
}
#endif