Debian Codegraph @

c/src/ssl/openssl.c

raw ◀ ▶
Source reconstructed at patch state 0 of 2 — not the installed (fully patched) source.
2 Debian patches touch this file
1 /*
2 *
3 * Licensed to the Apache Software Foundation (ASF) under one
4 * or more contributor license agreements. See the NOTICE file
5 * distributed with this work for additional information
6 * regarding copyright ownership. The ASF licenses this file
7 * to you under the Apache License, Version 2.0 (the
8 * "License"); you may not use this file except in compliance
9 * with the License. You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing,
14 * software distributed under the License is distributed on an
15 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16 * KIND, either express or implied. See the License for the
17 * specific language governing permissions and limitations
18 * under the License.
19 *
20 */
21
22 #include "platform/platform.h"
23 #include "platform/platform_fmt.h"
24 #include "core/engine-internal.h"
25 #include "core/logger_private.h"
26 #include "core/util.h"
27
28 #include <proton/ssl.h>
29 #include <proton/engine.h>
30
31 // openssl on windows expects the user to have already included
32 // winsock.h
33
34 #ifdef _MSC_VER
35 #ifndef _WIN32_WINNT
36 #define _WIN32_WINNT 0x0501
37 #endif
38 #if _WIN32_WINNT < 0x0501
39 #error "Proton requires Windows API support for XP or later."
40 #endif
41 #include <winsock2.h>
42 #include <mswsock.h>
43 #include <Ws2tcpip.h>
44 #endif
45
46
47 #include <openssl/ssl.h>
48 #include <openssl/dh.h>
49 #include <openssl/err.h>
50 #include <openssl/x509v3.h>
51 #include <sys/types.h>
52 #include <sys/stat.h>
53 #include <fcntl.h>
54 #include <assert.h>
55 #include <stdio.h>
56
57 /** @file
58 * SSL/TLS support API.
59 *
60 * This file contains an OpenSSL-based implemention of the SSL/TLS API.
61 */
62
63 typedef struct pn_ssl_session_t pn_ssl_session_t;
64
65 static int ssl_ex_data_index;
66
67 struct pn_ssl_domain_t {
68
69 SSL_CTX *ctx;
70
71 char *keyfile_pw;
72
73 // settings used for all connections
74 char *trusted_CAs;
75
76 char *ciphers;
77
78 int ref_count;
79 #ifdef SSL_SECOP_PEER
80 int default_seclevel;
81 #endif
82 pn_ssl_mode_t mode;
83 pn_ssl_verify_mode_t verify_mode;
84
85 bool has_certificate; // true when certificate configured
86 bool allow_unsecured;
87 };
88
89
90 struct pni_ssl_t {
91 pn_ssl_mode_t mode;
92 pn_ssl_verify_mode_t verify_mode;
93 const char *session_id;
94 const char *peer_hostname;
95 SSL *ssl;
96
97 BIO *bio_ssl; // i/o from/to SSL socket layer
98 BIO *bio_ssl_io; // SSL "half" of network-facing BIO
99 BIO *bio_net_io; // socket-side "half" of network-facing BIO
100 // buffers for holding I/O from "applications" above SSL
101 #define APP_BUF_SIZE (4*1024)
102 char *outbuf;
103 char *inbuf;
104
105 ssize_t app_input_closed; // error code returned by upper layer process input
106 ssize_t app_output_closed; // error code returned by upper layer process output
107
108 size_t out_size;
109 size_t out_count;
110 size_t in_size;
111 size_t in_count;
112
113 bool ssl_shutdown; // BIO_ssl_shutdown() called on socket.
114 bool ssl_closed; // shutdown complete, or SSL error
115 bool read_blocked; // SSL blocked until more network data is read
116 bool write_blocked; // SSL blocked until data is written to network
117
118 char *subject;
119 X509 *peer_certificate;
120 };
121
122 static inline pn_transport_t *get_transport_internal(pn_ssl_t *ssl)
123 {
124 // The external pn_sasl_t is really a pointer to the internal pni_transport_t
125 return ((pn_transport_t *)ssl);
126 }
127
128 static inline pni_ssl_t *get_ssl_internal(pn_ssl_t *ssl)
129 {
130 // The external pn_sasl_t is really a pointer to the internal pni_transport_t
131 return ssl ? ((pn_transport_t *)ssl)->ssl : NULL;
132 }
133
134 // define two sets of allowable ciphers: those that require authentication, and those
135 // that do not require authentication (anonymous). See ciphers(1).
136 #define CIPHERS_AUTHENTICATE "ALL:!aNULL:!eNULL:@STRENGTH"
137 #define CIPHERS_ANONYMOUS "ALL:aNULL:!eNULL:@STRENGTH"
138
139 /* */
140 static int keyfile_pw_cb(char *buf, int size, int rwflag, void *userdata);
141 static void handle_error_ssl( pn_transport_t *transport, unsigned int layer);
142 static ssize_t process_input_ssl( pn_transport_t *transport, unsigned int layer, const char *input_data, size_t len);
143 static ssize_t process_output_ssl( pn_transport_t *transport, unsigned int layer, char *input_data, size_t len);
144 static ssize_t process_input_done(pn_transport_t *transport, unsigned int layer, const char *input_data, size_t len);
145 static ssize_t process_output_done(pn_transport_t *transport, unsigned int layer, char *input_data, size_t len);
146 static int init_ssl_socket(pn_transport_t *, pni_ssl_t *, pn_ssl_domain_t *);
147 static void release_ssl_socket( pni_ssl_t * );
148 static size_t buffered_output( pn_transport_t *transport );
149 static X509 *get_peer_certificate(pni_ssl_t *ssl);
150
151 static void ssl_vlog(pn_transport_t *transport, pn_log_level_t sev, const char *fmt, va_list ap)
152 {
153 pn_logger_t *logger = transport ? &transport->logger : pn_default_logger();
154 if (PN_SHOULD_LOG(logger, PN_SUBSYSTEM_SSL, sev)) {
155 pni_logger_vlogf(logger, PN_SUBSYSTEM_SSL, sev, fmt, ap);
156 }
157 }
158
159 static void ssl_log(pn_transport_t *transport, pn_log_level_t sev, const char *fmt, ...)
160 {
161 va_list ap;
162 va_start(ap, fmt);
163 ssl_vlog(transport, sev, fmt, ap);
164 va_end(ap);
165 }
166
167 static void ssl_log_flush(pn_transport_t* transport, pn_log_level_t sev)
168 {
169 char buf[128]; // see "man ERR_error_string_n()"
170 unsigned long err = ERR_get_error();
171 while (err) {
172 ERR_error_string_n(err, buf, sizeof(buf));
173 ssl_log(transport, sev, "%s", buf);
174 err = ERR_get_error();
175 }
176 }
177
178 // log an error and dump the SSL error stack
179 static void ssl_log_error(const char *fmt, ...)
180 {
181 if (fmt) {
182 va_list ap;
183 va_start(ap, fmt);
184 ssl_vlog(NULL, PN_LEVEL_ERROR, fmt, ap);
185 va_end(ap);
186 }
187 ssl_log_flush(NULL, PN_LEVEL_ERROR);
188 }
189
190 static void ssl_log_clear_data(pn_transport_t *transport, const char *data, size_t len)
191 {
192 PN_LOG_DATA(&transport->logger, PN_SUBSYSTEM_SSL, PN_LEVEL_RAW, "decrypted data", data, len );
193 }
194
195 // unrecoverable SSL failure occurred, notify transport and generate error code.
196 static int ssl_failed(pn_transport_t *transport)
197 {
198 pni_ssl_t *ssl = transport->ssl;
199 SSL_set_shutdown(ssl->ssl, SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN);
200 ssl->ssl_closed = true;
201 ssl->app_input_closed = ssl->app_output_closed = PN_EOS;
202 // fake a shutdown so the i/o processing code will close properly
203 SSL_set_shutdown(ssl->ssl, SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN);
204 // try to grab the first SSL error to add to the failure log
205 char buf[256] = "Unknown error";
206 unsigned long ssl_err = ERR_get_error();
207 if (ssl_err) {
208 ERR_error_string_n( ssl_err, buf, sizeof(buf) );
209 }
210 ssl_log_flush(transport, PN_LEVEL_ERROR); // spit out any remaining errors to the log file
211 pn_do_error(transport, "amqp:connection:framing-error", "SSL Failure: %s", buf);
212 return PN_EOS;
213 }
214
215 /* match the DNS name pattern from the peer certificate against our configured peer
216 hostname */
217 static bool match_dns_pattern( const char *hostname,
218 const char *pattern, int plen )
219 {
220 int slen = (int) strlen(hostname);
221 if (memchr( pattern, '*', plen ) == NULL)
222 return (plen == slen &&
223 pn_strncasecmp( pattern, hostname, plen ) == 0);
224
225 /* dns wildcarded pattern - RFC2818 */
226 char plabel[64]; /* max label length < 63 - RFC1034 */
227 char slabel[64];
228
229 while (plen > 0 && slen > 0) {
230 const char *cptr;
231 int len;
232
233 cptr = (const char *) memchr( pattern, '.', plen );
234 len = (cptr) ? cptr - pattern : plen;
235 if (len > (int) sizeof(plabel) - 1) return false;
236 memcpy( plabel, pattern, len );
237 plabel[len] = 0;
238 if (cptr) ++len; // skip matching '.'
239 pattern += len;
240 plen -= len;
241
242 cptr = (const char *) memchr( hostname, '.', slen );
243 len = (cptr) ? cptr - hostname : slen;
244 if (len > (int) sizeof(slabel) - 1) return false;
245 memcpy( slabel, hostname, len );
246 slabel[len] = 0;
247 if (cptr) ++len; // skip matching '.'
248 hostname += len;
249 slen -= len;
250
251 char *star = strchr( plabel, '*' );
252 if (!star) {
253 if (pn_strcasecmp( plabel, slabel )) return false;
254 } else {
255 *star = '\0';
256 char *prefix = plabel;
257 int prefix_len = strlen(prefix);
258 char *suffix = star + 1;
259 int suffix_len = strlen(suffix);
260 if (prefix_len && pn_strncasecmp( prefix, slabel, prefix_len )) return false;
261 if (suffix_len && pn_strncasecmp( suffix,
262 slabel + (strlen(slabel) - suffix_len),
263 suffix_len )) return false;
264 }
265 }
266
267 return plen == slen;
268 }
269
270 // Certificate chain verification callback: return 1 if verified,
271 // 0 if remote cannot be verified (fail handshake).
272 //
273 static int verify_callback(int preverify_ok, X509_STORE_CTX *ctx)
274 {
275 if (!preverify_ok || X509_STORE_CTX_get_error_depth(ctx) != 0)
276 // already failed, or not at peer cert in chain
277 return preverify_ok;
278
279 X509 *cert = X509_STORE_CTX_get_current_cert(ctx);
280 SSL *ssn = (SSL *) X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
281 if (!ssn) {
282 ssl_log(NULL, PN_LEVEL_ERROR, "Error: unexpected error - SSL session info not available for peer verify!");
283 return 0; // fail connection
284 }
285
286 pn_transport_t *transport = (pn_transport_t *)SSL_get_ex_data(ssn, ssl_ex_data_index);
287 if (!transport) {
288 ssl_log(transport, PN_LEVEL_ERROR, "Error: unexpected error - SSL context info not available for peer verify!");
289 return 0; // fail connection
290 }
291
292 pni_ssl_t *ssl = transport->ssl;
293 if (ssl->verify_mode != PN_SSL_VERIFY_PEER_NAME) return preverify_ok;
294 if (!ssl->peer_hostname) {
295 ssl_log(transport, PN_LEVEL_ERROR, "Error: configuration error: PN_SSL_VERIFY_PEER_NAME configured, but no peer hostname set!");
296 return 0; // fail connection
297 }
298
299 ssl_log(transport, PN_LEVEL_TRACE, "Checking identifying name in peer cert against '%s'", ssl->peer_hostname);
300
301 bool matched = false;
302
303 /* first check any SubjectAltName entries, as per RFC2818 */
304 GENERAL_NAMES *sans = (GENERAL_NAMES *) X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
305 if (sans) {
306 int name_ct = sk_GENERAL_NAME_num( sans );
307 int i;
308 for (i = 0; !matched && i < name_ct; ++i) {
309 GENERAL_NAME *name = sk_GENERAL_NAME_value( sans, i );
310 if (name->type == GEN_DNS) {
311 ASN1_STRING *asn1 = name->d.dNSName;
312 if (asn1 && asn1->data && asn1->length) {
313 unsigned char *str;
314 int len = ASN1_STRING_to_UTF8( &str, asn1 );
315 if (len >= 0) {
316 ssl_log(transport, PN_LEVEL_TRACE, "SubjectAltName (dns) from peer cert = '%.*s'", len, str );
317 matched = match_dns_pattern( ssl->peer_hostname, (const char *)str, len );
318 OPENSSL_free( str );
319 }
320 }
321 }
322 }
323 GENERAL_NAMES_free( sans );
324 }
325
326 /* if no general names match, try the CommonName from the subject */
327 X509_NAME *name = X509_get_subject_name(cert);
328 int i = -1;
329 while (!matched && (i = X509_NAME_get_index_by_NID(name, NID_commonName, i)) >= 0) {
330 X509_NAME_ENTRY *ne = X509_NAME_get_entry(name, i);
331 ASN1_STRING *name_asn1 = X509_NAME_ENTRY_get_data(ne);
332 if (name_asn1) {
333 unsigned char *str;
334 int len = ASN1_STRING_to_UTF8( &str, name_asn1);
335 if (len >= 0) {
336 ssl_log(transport, PN_LEVEL_TRACE, "commonName from peer cert = '%.*s'", len, str);
337 matched = match_dns_pattern( ssl->peer_hostname, (const char *)str, len );
338 OPENSSL_free(str);
339 }
340 }
341 }
342
343 if (!matched) {
344 ssl_log(transport, PN_LEVEL_ERROR, "Error: no name matching %s found in peer cert - rejecting handshake.",
345 ssl->peer_hostname);
346 preverify_ok = 0;
347 #ifdef X509_V_ERR_APPLICATION_VERIFICATION
348 X509_STORE_CTX_set_error( ctx, X509_V_ERR_APPLICATION_VERIFICATION );
349 #endif
350 } else {
351 ssl_log(transport, PN_LEVEL_TRACE, "Name from peer cert matched - peer is valid.");
352 }
353 return preverify_ok;
354 }
355
356 // This was introduced in v1.1
357 #if OPENSSL_VERSION_NUMBER < 0x10100000
358 int DH_set0_pqg(DH *dh, BIGNUM *p, BIGNUM *q, BIGNUM *g)
359 {
360 dh->p = p;
361 dh->q = q;
362 dh->g = g;
363 return 1;
364 }
365 #endif
366
367 // this code was generated using the command:
368 // "openssl dhparam -C -2 2048"
369 static DH *get_dh2048(void)
370 {
371 static const unsigned char dhp_2048[]={
372 0xAE,0xF7,0xE9,0x66,0x26,0x7A,0xAC,0x0A,0x6F,0x1E,0xCD,0x81,
373 0xBD,0x0A,0x10,0x7E,0xFA,0x2C,0xF5,0x2D,0x98,0xD4,0xE7,0xD9,
374 0xE4,0x04,0x8B,0x06,0x85,0xF2,0x0B,0xA3,0x90,0x15,0x56,0x0C,
375 0x8B,0xBE,0xF8,0x48,0xBB,0x29,0x63,0x75,0x12,0x48,0x9D,0x7E,
376 0x7C,0x24,0xB4,0x3A,0x38,0x7E,0x97,0x3C,0x77,0x95,0xB0,0xA2,
377 0x72,0xB6,0xE9,0xD8,0xB8,0xFA,0x09,0x1B,0xDC,0xB3,0x80,0x6E,
378 0x32,0x0A,0xDA,0xBB,0xE8,0x43,0x88,0x5B,0xAB,0xC3,0xB2,0x44,
379 0xE1,0x95,0x85,0x0A,0x0D,0x13,0xE2,0x02,0x1E,0x96,0x44,0xCF,
380 0xA0,0xD8,0x46,0x32,0x68,0x63,0x7F,0x68,0xB3,0x37,0x52,0xCE,
381 0x3A,0x4E,0x48,0x08,0x7F,0xD5,0x53,0x00,0x59,0xA8,0x2C,0xCB,
382 0x51,0x64,0x3D,0x5F,0xEF,0x0E,0x5F,0xE6,0xAF,0xD9,0x1E,0xA2,
383 0x35,0x64,0x37,0xD7,0x4C,0xC9,0x24,0xFD,0x2F,0x75,0xBB,0x3A,
384 0x15,0x82,0x76,0x4D,0xC2,0x8B,0x1E,0xB9,0x4B,0xA1,0x33,0xCF,
385 0xAA,0x3B,0x7C,0xC2,0x50,0x60,0x6F,0x45,0x69,0xD3,0x6B,0x88,
386 0x34,0x9B,0xE4,0xF8,0xC6,0xC7,0x5F,0x10,0xA1,0xBA,0x01,0x8C,
387 0xDA,0xD1,0xA3,0x59,0x9C,0x97,0xEA,0xC3,0xF6,0x02,0x55,0x5C,
388 0x92,0x1A,0x39,0x67,0x17,0xE2,0x9B,0x27,0x8D,0xE8,0x5C,0xE9,
389 0xA5,0x94,0xBB,0x7E,0x16,0x6F,0x53,0x5A,0x6D,0xD8,0x03,0xC2,
390 0xAC,0x7A,0xCD,0x22,0x98,0x8E,0x33,0x2A,0xDE,0xAB,0x12,0xC0,
391 0x0B,0x7C,0x0C,0x20,0x70,0xD9,0x0B,0xAE,0x0B,0x2F,0x20,0x9B,
392 0xA4,0xED,0xFD,0x49,0x0B,0xE3,0x4A,0xF6,0x28,0xB3,0x98,0xB0,
393 0x23,0x1C,0x09,0x33,
394 };
395 static const unsigned char dhg_2048[]={
396 0x02,
397 };
398 DH *dh = DH_new();
399 BIGNUM *dhp_bn, *dhg_bn;
400
401 if (dh == NULL)
402 return NULL;
403 dhp_bn = BN_bin2bn(dhp_2048, sizeof (dhp_2048), NULL);
404 dhg_bn = BN_bin2bn(dhg_2048, sizeof (dhg_2048), NULL);
405 if (dhp_bn == NULL || dhg_bn == NULL
406 || !DH_set0_pqg(dh, dhp_bn, NULL, dhg_bn)) {
407 DH_free(dh);
408 BN_free(dhp_bn);
409 BN_free(dhg_bn);
410 return NULL;
411 }
412 return dh;
413 }
414
415 typedef struct {
416 char *id;
417 SSL_SESSION *session;
418 } ssl_cache_data;
419
420 #define SSL_CACHE_SIZE 4
421 static int ssl_cache_ptr = 0;
422 static ssl_cache_data ssl_cache[SSL_CACHE_SIZE];
423
424 static void ssn_init(void) {
425 ssl_cache_data s = {NULL, NULL};
426 for (int i=0; i<SSL_CACHE_SIZE; i++) {
427 ssl_cache[i] = s;
428 }
429 }
430
431 static void ssn_restore(pn_transport_t *transport, pni_ssl_t *ssl) {
432 if (!ssl->session_id) return;
433 for (int i = ssl_cache_ptr;;) {
434 i = (i==0) ? SSL_CACHE_SIZE-1 : i-1;
435 if (ssl_cache[i].id == NULL) return;
436 if (strcmp(ssl_cache[i].id, ssl->session_id) == 0) {
437 ssl_log( transport, PN_LEVEL_TRACE, "Restoring previous session id=%s", ssl->session_id );
438 int rc = SSL_set_session( ssl->ssl, ssl_cache[i].session );
439 if (rc != 1) {
440 ssl_log( transport, PN_LEVEL_WARNING, "Session restore failed, id=%s", ssl->session_id );
441 }
442 return;
443 }
444 if (i == ssl_cache_ptr) return;
445 }
446 }
447
448 static void ssn_save(pn_transport_t *transport, pni_ssl_t *ssl) {
449 if (ssl->session_id) {
450 // Attach the session id to the session before we close the connection
451 // So that if we find it in the cache later we can figure out the session id
452 SSL_SESSION *session = SSL_get1_session( ssl->ssl );
453 if (session) {
454 ssl_log(transport, PN_LEVEL_TRACE, "Saving SSL session as %s", ssl->session_id );
455 // If we're overwriting a value, need to free it
456 free(ssl_cache[ssl_cache_ptr].id);
457 if (ssl_cache[ssl_cache_ptr].session) SSL_SESSION_free(ssl_cache[ssl_cache_ptr].session);
458
459 char *id = pn_strdup( ssl->session_id );
460 ssl_cache_data s = {id, session};
461 ssl_cache[ssl_cache_ptr++] = s;
462 if (ssl_cache_ptr==SSL_CACHE_SIZE) ssl_cache_ptr = 0;
463 }
464 }
465 }
466
467 /** Public API - visible to application code */
468
469 bool pn_ssl_present(void)
470 {
471 return true;
472 }
473
474 static bool ensure_initialized(void);
475
476 static bool pni_init_ssl_domain( pn_ssl_domain_t * domain, pn_ssl_mode_t mode )
477 {
478 if (!ensure_initialized()) {
479 ssl_log_error("Unable to initialize OpenSSL library");
480 return false;
481 }
482
483 domain->ref_count = 1;
484 domain->mode = mode;
485
486 // enable all supported protocol versions, then explicitly disable the
487 // known vulnerable ones. This should allow us to use the latest version
488 // of the TLS standard that the installed library supports.
489 switch(mode) {
490 case PN_SSL_MODE_CLIENT:
491 domain->ctx = SSL_CTX_new(SSLv23_client_method()); // and TLSv1+
492 if (!domain->ctx) {
493 ssl_log_error("Unable to initialize OpenSSL context.");
494 return false;
495 }
496 SSL_CTX_set_session_cache_mode(domain->ctx, SSL_SESS_CACHE_CLIENT);
497
498 // By default, require peer name verification - this is a safe default
499 if (pn_ssl_domain_set_peer_authentication( domain, PN_SSL_VERIFY_PEER_NAME, NULL )) {
500 SSL_CTX_free(domain->ctx);
501 return false;
502 }
503 break;
504
505 case PN_SSL_MODE_SERVER:
506 domain->ctx = SSL_CTX_new(SSLv23_server_method()); // and TLSv1+
507 if (!domain->ctx) {
508 ssl_log_error("Unable to initialize OpenSSL context.");
509 return false;
510 }
511 // By default, allow anonymous ciphers and do no authentication so certificates are
512 // not required 'out of the box'; authenticating the client can be done by SASL.
513 if (pn_ssl_domain_set_peer_authentication( domain, PN_SSL_ANONYMOUS_PEER, NULL )) {
514 SSL_CTX_free(domain->ctx);
515 return false;
516 }
517 break;
518
519 default:
520 ssl_log(NULL, PN_LEVEL_ERROR, "Invalid value for pn_ssl_mode_t: %d", mode);
521 return false;
522 }
523
524 // By default set up system default certificates
525 if (!SSL_CTX_set_default_verify_paths(domain->ctx)){
526 ssl_log_error("Failed to set default certificate paths");
527 SSL_CTX_free(domain->ctx);
528 return false;
529 };
530
531 const long reject_insecure =
532 SSL_OP_NO_SSLv2
533 | SSL_OP_NO_SSLv3
534 // Mitigate the CRIME vulnerability
535 # ifdef SSL_OP_NO_COMPRESSION
536 | SSL_OP_NO_COMPRESSION
537 # endif
538 ;
539 SSL_CTX_set_options(domain->ctx, reject_insecure);
540
541 # ifdef SSL_SECOP_PEER
542 domain->default_seclevel = SSL_CTX_get_security_level(domain->ctx);
543 # endif
544
545 DH *dh = get_dh2048();
546 if (dh) {
547 SSL_CTX_set_tmp_dh(domain->ctx, dh);
548 DH_free(dh);
549 SSL_CTX_set_options(domain->ctx, SSL_OP_SINGLE_DH_USE);
550 }
551
552 return true;
553 }
554
555 pn_ssl_domain_t *pn_ssl_domain( pn_ssl_mode_t mode )
556 {
557 pn_ssl_domain_t *domain = (pn_ssl_domain_t *) calloc(1, sizeof(pn_ssl_domain_t));
558 if (!domain) return NULL;
559
560 if (!pni_init_ssl_domain(domain, mode)) {
561 free(domain);
562 return NULL;
563 }
564
565 return domain;
566 }
567
568 void pn_ssl_domain_free( pn_ssl_domain_t *domain )
569 {
570 if (--domain->ref_count == 0) {
571
572 SSL_CTX_free(domain->ctx);
573 free(domain->keyfile_pw);
574 free(domain->trusted_CAs);
575 free(domain->ciphers);
576 free(domain);
577 }
578 }
579
580
581 int pn_ssl_domain_set_credentials( pn_ssl_domain_t *domain,
582 const char *certificate_file,
583 const char *private_key_file,
584 const char *password)
585 {
586 if (!domain || !domain->ctx) return -1;
587
588 if (SSL_CTX_use_certificate_chain_file(domain->ctx, certificate_file) != 1) {
589 ssl_log_error("SSL_CTX_use_certificate_chain_file( %s ) failed", certificate_file);
590 return -3;
591 }
592
593 if (password) {
594 domain->keyfile_pw = pn_strdup(password); // @todo: obfuscate me!!!
595 SSL_CTX_set_default_passwd_cb(domain->ctx, keyfile_pw_cb);
596 SSL_CTX_set_default_passwd_cb_userdata(domain->ctx, domain->keyfile_pw);
597 }
598
599 if (SSL_CTX_use_PrivateKey_file(domain->ctx, private_key_file, SSL_FILETYPE_PEM) != 1) {
600 ssl_log_error("SSL_CTX_use_PrivateKey_file( %s ) failed", private_key_file);
601 return -4;
602 }
603
604 if (SSL_CTX_check_private_key(domain->ctx) != 1) {
605 ssl_log_error("The key file %s is not consistent with the certificate %s",
606 private_key_file, certificate_file);
607 return -5;
608 }
609
610 domain->has_certificate = true;
611
612 // bug in older versions of OpenSSL: servers may request client cert even if anonymous
613 // cipher was negotiated. TLSv1 will reject such a request. Hack: once a cert is
614 // configured, allow only authenticated ciphers.
615 if (!domain->ciphers && !SSL_CTX_set_cipher_list( domain->ctx, CIPHERS_AUTHENTICATE )) {
616 ssl_log_error("Failed to set cipher list to %s", CIPHERS_AUTHENTICATE);
617 return -6;
618 }
619
620 return 0;
621 }
622
623 int pn_ssl_domain_set_ciphers(pn_ssl_domain_t *domain, const char *ciphers)
624 {
625 if (!SSL_CTX_set_cipher_list(domain->ctx, ciphers)) {
626 ssl_log_error("Failed to set cipher list to %s", ciphers);
627 return -6;
628 }
629 if (domain->ciphers) free(domain->ciphers);
630 domain->ciphers = pn_strdup(ciphers);
631 return 0;
632 }
633
634 int pn_ssl_domain_set_protocols(pn_ssl_domain_t *domain, const char *protocols)
635 {
636 static const struct {
637 const char *name;
638 const long option;
639 } protocol_options[] =
640 {
641 {"TLSv1", SSL_OP_NO_TLSv1},
642 {"TLSv1.1", SSL_OP_NO_TLSv1_1},
643 {"TLSv1.2", SSL_OP_NO_TLSv1_2},
644 #ifdef SSL_OP_NO_TLSv1_3
645 {"TLSv1.3", SSL_OP_NO_TLSv1_3},
646 #endif
647 };
648 static const char seps[] = " ,;";
649 static const long all_prots =
650 SSL_OP_NO_TLSv1
651 | SSL_OP_NO_TLSv1_1
652 | SSL_OP_NO_TLSv1_2
653 #ifdef SSL_OP_NO_TLSv1_3
654 | SSL_OP_NO_TLSv1_3
655 #endif
656 ;
657
658 // Start with all protocols turned off
659 long options = all_prots;
660
661 // For each separate token in protocols
662 const char *token = protocols;
663 while (*token!=0) {
664 // Find next separator
665 size_t tsize = strcspn(token, seps);
666 while (tsize==0 && *token!=0) {
667 ++token;
668 tsize = strcspn(token, seps);
669 }
670 if (tsize==0) break; // No more tokens
671
672 // Linear search the possibilities for the option to set
673 for (size_t i = 0; i<sizeof(protocol_options)/sizeof(*protocol_options); ++i) {
674 if (strncmp(token, protocol_options[i].name, tsize)==0) {
675 options &= ~protocol_options[i].option;
676 goto found;
677 }
678 }
679 // Didn't find any match - error
680 return PN_ARG_ERR;
681
682 found:
683 token += tsize;
684 }
685
686 // Check if we found anything
687 if (options==all_prots) return PN_ARG_ERR;
688
689 SSL_CTX_clear_options(domain->ctx, all_prots);
690 SSL_CTX_set_options(domain->ctx, options);
691 return 0;
692 }
693
694 int pn_ssl_domain_set_trusted_ca_db(pn_ssl_domain_t *domain,
695 const char *certificate_db)
696 {
697 if (!domain) return -1;
698
699 // certificates can be either a file or a directory, which determines how it is passed
700 // to SSL_CTX_load_verify_locations()
701 struct stat sbuf;
702 if (stat( certificate_db, &sbuf ) != 0) {
703 ssl_log(NULL, PN_LEVEL_ERROR, "stat(%s) failed: %s", certificate_db, strerror(errno));
704 return -1;
705 }
706
707 const char *file;
708 const char *dir;
709 if (S_ISDIR(sbuf.st_mode)) {
710 dir = certificate_db;
711 file = NULL;
712 } else {
713 dir = NULL;
714 file = certificate_db;
715 }
716
717 if (SSL_CTX_load_verify_locations( domain->ctx, file, dir ) != 1) {
718 ssl_log_error("SSL_CTX_load_verify_locations( %s ) failed", certificate_db);
719 return -1;
720 }
721
722 return 0;
723 }
724
725
726 int pn_ssl_domain_set_peer_authentication(pn_ssl_domain_t *domain,
727 const pn_ssl_verify_mode_t mode,
728 const char *trusted_CAs)
729 {
730 if (!domain) return -1;
731
732 switch (mode) {
733 case PN_SSL_VERIFY_PEER:
734 case PN_SSL_VERIFY_PEER_NAME:
735
736 #ifdef SSL_SECOP_PEER
737 SSL_CTX_set_security_level(domain->ctx, domain->default_seclevel);
738 #endif
739
740 if (domain->mode == PN_SSL_MODE_SERVER) {
741 // openssl requires that server connections supply a list of trusted CAs which is
742 // sent to the client
743 if (!trusted_CAs) {
744 ssl_log(NULL, PN_LEVEL_ERROR, "Error: a list of trusted CAs must be provided.");
745 return -1;
746 }
747 if (!domain->has_certificate) {
748 ssl_log(NULL, PN_LEVEL_ERROR, "Error: Server cannot verify peer without configuring a certificate, use pn_ssl_domain_set_credentials()");
749 return -1;
750 }
751
752 if (domain->trusted_CAs) free(domain->trusted_CAs);
753 domain->trusted_CAs = pn_strdup( trusted_CAs );
754 STACK_OF(X509_NAME) *cert_names;
755 cert_names = SSL_load_client_CA_file( domain->trusted_CAs );
756 if (cert_names != NULL)
757 SSL_CTX_set_client_CA_list(domain->ctx, cert_names);
758 else {
759 ssl_log(NULL, PN_LEVEL_ERROR, "Error: Unable to process file of trusted CAs: %s", trusted_CAs);
760 return -1;
761 }
762 }
763
764 SSL_CTX_set_verify( domain->ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
765 verify_callback);
766 #if (OPENSSL_VERSION_NUMBER < 0x00905100L)
767 SSL_CTX_set_verify_depth(domain->ctx, 1);
768 #endif
769
770 // A bit of a hack - If we asked for peer verification then disallow anonymous ciphers
771 // A much more robust thing would be to ensure that we actually have a peer certificate
772 // when we've finished the SSL handshake
773 if (!domain->ciphers && !SSL_CTX_set_cipher_list( domain->ctx, CIPHERS_AUTHENTICATE )) {
774 ssl_log_error("Failed to set cipher list to %s", CIPHERS_AUTHENTICATE);
775 return -1;
776 }
777 break;
778
779 case PN_SSL_ANONYMOUS_PEER: // hippie free love mode... :)
780 #ifdef SSL_SECOP_PEER
781 // Must use lowest OpenSSL security level to enable anonymous ciphers.
782 SSL_CTX_set_security_level(domain->ctx, 0);
783 #endif
784 SSL_CTX_set_verify( domain->ctx, SSL_VERIFY_NONE, NULL );
785 // Only allow anonymous ciphers if we allow anonymous peers
786 if (!domain->ciphers && !SSL_CTX_set_cipher_list( domain->ctx, CIPHERS_ANONYMOUS )) {
787 ssl_log_error("Failed to set cipher list to %s", CIPHERS_ANONYMOUS);
788 return -1;
789 }
790 break;
791
792 default:
793 ssl_log(NULL, PN_LEVEL_ERROR, "Invalid peer authentication mode given." );
794 return -1;
795 }
796
797 domain->verify_mode = mode;
798 return 0;
799 }
800
801 const pn_io_layer_t ssl_layer = {
802 process_input_ssl,
803 process_output_ssl,
804 handle_error_ssl,
805 NULL,
806 buffered_output
807 };
808
809 const pn_io_layer_t ssl_input_closed_layer = {
810 process_input_done,
811 process_output_ssl,
812 handle_error_ssl,
813 NULL,
814 buffered_output
815 };
816
817 const pn_io_layer_t ssl_output_closed_layer = {
818 process_input_ssl,
819 process_output_done,
820 handle_error_ssl,
821 NULL,
822 buffered_output
823 };
824
825 const pn_io_layer_t ssl_closed_layer = {
826 process_input_done,
827 process_output_done,
828 handle_error_ssl,
829 NULL,
830 buffered_output
831 };
832
833 static pn_ssl_domain_t default_client_domain = {0};
834 static pn_ssl_domain_t default_server_domain = {0};
835
836 int pn_ssl_init(pn_ssl_t *ssl0, pn_ssl_domain_t *domain, const char *session_id)
837 {
838 pn_transport_t *transport = get_transport_internal(ssl0);
839 pni_ssl_t *ssl = transport->ssl;
840 if (!ssl) return -1;
841
842 if (!domain) {
843 if (transport->server) {
844 domain = &default_server_domain;
845 if (domain->ref_count==0) {
846 pni_init_ssl_domain(domain, PN_SSL_MODE_SERVER);
847 }
848 } else {
849 domain = &default_client_domain;
850 if (domain->ref_count==0) {
851 pni_init_ssl_domain(domain, PN_SSL_MODE_CLIENT);
852 }
853 }
854 }
855
856 ssl->mode = domain->mode;
857 ssl->verify_mode = domain->verify_mode;
858
859 if (session_id && domain->mode == PN_SSL_MODE_CLIENT)
860 ssl->session_id = pn_strdup(session_id);
861
862 // If SSL doesn't specifically allow skipping encryption, require SSL
863 // TODO: This is a probably a stop-gap until allow_unsecured is removed
864 if (!domain->allow_unsecured) transport->encryption_required = true;
865
866 return init_ssl_socket(transport, ssl, domain);
867 }
868
869
870 int pn_ssl_domain_allow_unsecured_client(pn_ssl_domain_t *domain)
871 {
872 if (!domain) return -1;
873 if (domain->mode != PN_SSL_MODE_SERVER) {
874 ssl_log(NULL, PN_LEVEL_ERROR, "Cannot permit unsecured clients - not a server.");
875 return -1;
876 }
877 domain->allow_unsecured = true;
878 return 0;
879 }
880
881 int pn_ssl_get_ssf(pn_ssl_t *ssl0)
882 {
883 const SSL_CIPHER *c;
884
885 pni_ssl_t *ssl = get_ssl_internal(ssl0);
886 if (ssl && ssl->ssl && (c = SSL_get_current_cipher( ssl->ssl ))) {
887 return SSL_CIPHER_get_bits(c, NULL);
888 }
889 return 0;
890 }
891
892 bool pn_ssl_get_cipher_name(pn_ssl_t *ssl0, char *buffer, size_t size )
893 {
894 const SSL_CIPHER *c;
895
896 pni_ssl_t *ssl = get_ssl_internal(ssl0);
897 if (buffer && size) *buffer = '\0';
898 if (ssl->ssl && (c = SSL_get_current_cipher( ssl->ssl ))) {
899 const char *v = SSL_CIPHER_get_name(c);
900 if (buffer && v) {
901 snprintf( buffer, size, "%s", v );
902 return true;
903 }
904 }
905 return false;
906 }
907
908 bool pn_ssl_get_protocol_name(pn_ssl_t *ssl0, char *buffer, size_t size )
909 {
910 const SSL_CIPHER *c;
911
912 pni_ssl_t *ssl = get_ssl_internal(ssl0);
913 if (buffer && size) *buffer = '\0';
914 if (ssl->ssl && (c = SSL_get_current_cipher( ssl->ssl ))) {
915 const char *v = SSL_CIPHER_get_version(c);
916 if (buffer && v) {
917 snprintf( buffer, size, "%s", v );
918 return true;
919 }
920 }
921 return false;
922 }
923
924
925 void pn_ssl_free(pn_transport_t *transport)
926 {
927 pni_ssl_t *ssl = transport->ssl;
928 if (!ssl) return;
929 ssl_log(transport, PN_LEVEL_TRACE, "SSL socket freed." );
930 release_ssl_socket( ssl );
931 if (ssl->session_id) free((void *)ssl->session_id);
932 if (ssl->peer_hostname) free((void *)ssl->peer_hostname);
933 if (ssl->inbuf) free((void *)ssl->inbuf);
934 if (ssl->outbuf) free((void *)ssl->outbuf);
935 if (ssl->subject) free(ssl->subject);
936 if (ssl->peer_certificate) X509_free(ssl->peer_certificate);
937 free(ssl);
938 }
939
940 pn_ssl_t *pn_ssl(pn_transport_t *transport)
941 {
942 if (!transport) return NULL;
943 if (transport->ssl) return (pn_ssl_t *) transport;
944
945 pni_ssl_t *ssl = (pni_ssl_t *) calloc(1, sizeof(pni_ssl_t));
946 if (!ssl) return NULL;
947 ssl->out_size = APP_BUF_SIZE;
948 uint32_t max_frame = pn_transport_get_max_frame(transport);
949 ssl->in_size = max_frame ? max_frame : APP_BUF_SIZE;
950 ssl->outbuf = (char *)malloc(ssl->out_size);
951 if (!ssl->outbuf) {
952 free(ssl);
953 return NULL;
954 }
955 ssl->inbuf = (char *)malloc(ssl->in_size);
956 if (!ssl->inbuf) {
957 free(ssl->outbuf);
958 free(ssl);
959 return NULL;
960 }
961
962 transport->ssl = ssl;
963
964 // Set up hostname from any bound connection
965 if (transport->connection) {
966 if (pn_string_size(transport->connection->hostname)) {
967 pn_ssl_set_peer_hostname((pn_ssl_t *) transport, pn_string_get(transport->connection->hostname));
968 }
969 }
970
971 return (pn_ssl_t *) transport;
972 }
973
974
975 /** Private: */
976
977 static int keyfile_pw_cb(char *buf, int size, int rwflag, void *userdata)
978 {
979 strncpy(buf, (char *)userdata, size); // @todo: un-obfuscate me!!!
980 buf[size - 1] = '\0';
981 return(strlen(buf));
982 }
983
984
985 static int start_ssl_shutdown(pn_transport_t *transport)
986 {
987 pni_ssl_t *ssl = transport->ssl;
988 if (!ssl->ssl_shutdown) {
989 ssl_log(transport, PN_LEVEL_TRACE, "Shutting down SSL connection...");
990 ssn_save(transport, ssl);
991 ssl->ssl_shutdown = true;
992 BIO_ssl_shutdown( ssl->bio_ssl );
993 }
994 return 0;
995 }
996
997
998 //////// SSL Connections
999
1000
1001 // take data from the network, and pass it into SSL. Attempt to read decrypted data from
1002 // SSL socket and pass it to the application.
1003 static ssize_t process_input_ssl( pn_transport_t *transport, unsigned int layer, const char *input_data, size_t available)
1004 {
1005 pni_ssl_t *ssl = transport->ssl;
1006 if (ssl->ssl == NULL) {
1007 if (init_ssl_socket(transport, ssl, NULL)) return PN_EOS;
1008 transport->present_layers |= LAYER_SSL;
1009 }
1010
1011 ssl_log( transport, PN_LEVEL_TRACE, "process_input_ssl( data size=%d )",available );
1012
1013 ssize_t consumed = 0;
1014 bool work_pending;
1015 bool shutdown_input = (available == 0); // caller is closed
1016
1017 do {
1018 work_pending = false;
1019 ERR_clear_error();
1020
1021 // Write to network bio as much as possible, consuming bytes/available
1022
1023 if (available > 0) {
1024 int written = BIO_write( ssl->bio_net_io, input_data, available );
1025 if (written > 0) {
1026 input_data += written;
1027 available -= written;
1028 consumed += written;
1029 ssl->read_blocked = false;
1030 work_pending = (available > 0);
1031 ssl_log( transport, PN_LEVEL_TRACE, "Wrote %d bytes to BIO Layer, %" PN_ZU " left over", written, available );
1032 }
1033 } else if (shutdown_input) {
1034 // lower layer (caller) has closed. Close the WRITE side of the BIO. This will cause
1035 // an EOF to be passed to SSL once all pending inbound data has been consumed.
1036 ssl_log( transport, PN_LEVEL_TRACE, "Lower layer closed - shutting down BIO write side");
1037 (void)BIO_shutdown_wr( ssl->bio_net_io );
1038 shutdown_input = false;
1039 }
1040
1041 // Read all available data from the SSL socket
1042
1043 if (!ssl->ssl_closed && ssl->in_count < ssl->in_size) {
1044 int read = BIO_read( ssl->bio_ssl, &ssl->inbuf[ssl->in_count], ssl->in_size - ssl->in_count );
1045 if (read > 0) {
1046 ssl_log( transport, PN_LEVEL_TRACE, "Read %d bytes from SSL socket for app", read );
1047 ssl_log_clear_data(transport, &ssl->inbuf[ssl->in_count], read );
1048 ssl->in_count += read;
1049 work_pending = true;
1050 } else {
1051 if (!BIO_should_retry(ssl->bio_ssl)) {
1052 int reason = SSL_get_error( ssl->ssl, read );
1053 switch (reason) {
1054 case SSL_ERROR_ZERO_RETURN:
1055 // SSL closed cleanly
1056 ssl_log(transport, PN_LEVEL_TRACE, "SSL connection has closed");
1057 start_ssl_shutdown(transport); // KAG: not sure - this may not be necessary
1058 ssl->ssl_closed = true;
1059 break;
1060 default:
1061 // unexpected error
1062 return (ssize_t)ssl_failed(transport);
1063 }
1064 } else {
1065 if (BIO_should_write( ssl->bio_ssl )) {
1066 ssl->write_blocked = true;
1067 ssl_log(transport, PN_LEVEL_TRACE, "Detected write-blocked");
1068 }
1069 if (BIO_should_read( ssl->bio_ssl )) {
1070 ssl->read_blocked = true;
1071 ssl_log(transport, PN_LEVEL_TRACE, "Detected read-blocked");
1072 }
1073 }
1074 }
1075 }
1076
1077 // write incoming data to app layer
1078
1079 if (!ssl->app_input_closed) {
1080 if (ssl->in_count > 0 || ssl->ssl_closed) { /* if ssl_closed, send 0 count */
1081 ssize_t consumed = transport->io_layers[layer+1]->process_input(transport, layer+1, ssl->inbuf, ssl->in_count);
1082 if (consumed > 0) {
1083 ssl->in_count -= consumed;
1084 if (ssl->in_count)
1085 memmove( ssl->inbuf, ssl->inbuf + consumed, ssl->in_count );
1086 work_pending = true;
1087 ssl_log( transport, PN_LEVEL_TRACE, "Application consumed %d bytes from peer", (int) consumed );
1088 } else if (consumed < 0) {
1089 ssl_log(transport, PN_LEVEL_TRACE, "Application layer closed its input, error=%d (discarding %d bytes)",
1090 (int) consumed, (int)ssl->in_count);
1091 ssl->in_count = 0; // discard any pending input
1092 ssl->app_input_closed = consumed;
1093 if (ssl->app_output_closed && ssl->out_count == 0) {
1094 // both sides of app closed, and no more app output pending:
1095 start_ssl_shutdown(transport);
1096 }
1097 } else {
1098 // app did not consume any bytes, must be waiting for a full frame
1099 if (ssl->in_count == ssl->in_size) {
1100 // but the buffer is full, not enough room for a full frame.
1101 // can we grow the buffer?
1102 uint32_t max_frame = pn_transport_get_max_frame(transport);
1103 if (!max_frame) max_frame = ssl->in_size * 2; // no limit
1104 if (ssl->in_size < max_frame) {
1105 // no max frame limit - grow it.
1106 size_t newsize = pn_min(max_frame, ssl->in_size * 2);
1107 char *newbuf = (char *)realloc( ssl->inbuf, newsize );
1108 if (newbuf) {
1109 ssl->in_size = newsize;
1110 ssl->inbuf = newbuf;
1111 work_pending = true; // can we get more input?
1112 }
1113 } else {
1114 // can't gather any more input, but app needs more?
1115 // This is a bug - since SSL can buffer up to max-frame,
1116 // the application _must_ have enough data to process. If
1117 // this is an oversized frame, the app _must_ handle it
1118 // by returning an error code to SSL.
1119 ssl_log(transport, PN_LEVEL_ERROR, "Error: application unable to consume input.");
1120 }
1121 }
1122 }
1123 }
1124 }
1125
1126 } while (work_pending);
1127
1128 //_log(ssl, "ssl_closed=%d in_count=%d app_input_closed=%d app_output_closed=%d",
1129 // ssl->ssl_closed, ssl->in_count, ssl->app_input_closed, ssl->app_output_closed );
1130
1131 // PROTON-82: Instead, close the input side as soon as we've completed enough of the SSL
1132 // shutdown handshake to send the close_notify. We're not requiring the response, as
1133 // some implementations never reply.
1134 // ---
1135 // tell transport our input side is closed if the SSL socket cannot be read from any
1136 // longer, AND any pending input has been written up to the application (or the
1137 // application is closed)
1138 //if (ssl->ssl_closed && ssl->app_input_closed) {
1139 // consumed = ssl->app_input_closed;
1140 //}
1141 if (ssl->app_input_closed && (SSL_get_shutdown(ssl->ssl) & SSL_SENT_SHUTDOWN) ) {
1142 consumed = ssl->app_input_closed;
1143 if (transport->io_layers[layer]==&ssl_output_closed_layer) {
1144 transport->io_layers[layer] = &ssl_closed_layer;
1145 } else {
1146 transport->io_layers[layer] = &ssl_input_closed_layer;
1147 }
1148 }
1149 ssl_log(transport, PN_LEVEL_TRACE, "process_input_ssl() returning %d", (int) consumed);
1150 return consumed;
1151 }
1152
1153 static void handle_error_ssl(pn_transport_t *transport, unsigned int layer)
1154 {
1155 transport->io_layers[layer] = &ssl_closed_layer;
1156 }
1157
1158 static ssize_t process_output_ssl( pn_transport_t *transport, unsigned int layer, char *buffer, size_t max_len)
1159 {
1160 pni_ssl_t *ssl = transport->ssl;
1161 if (!ssl) return PN_EOS;
1162 if (ssl->ssl == NULL && init_ssl_socket(transport, ssl, NULL)) return PN_EOS;
1163
1164 ssize_t written = 0;
1165 bool work_pending;
1166
1167 do {
1168 work_pending = false;
1169 ERR_clear_error();
1170
1171 // first, get any pending application output, if possible
1172
1173 if (!ssl->app_output_closed && ssl->out_count < ssl->out_size) {
1174 ssize_t app_bytes = transport->io_layers[layer+1]->process_output(transport, layer+1, &ssl->outbuf[ssl->out_count], ssl->out_size - ssl->out_count);
1175 if (app_bytes > 0) {
1176 ssl->out_count += app_bytes;
1177 work_pending = true;
1178 ssl_log(transport, PN_LEVEL_TRACE, "Gathered %" PN_ZI " bytes from app to send to peer", app_bytes);
1179 } else {
1180 if (app_bytes < 0) {
1181 ssl_log(transport, PN_LEVEL_TRACE, "Application layer closed its output, error=%d (%d bytes pending send)",
1182 (int) app_bytes, (int) ssl->out_count);
1183 ssl->app_output_closed = app_bytes;
1184 }
1185 }
1186 }
1187
1188 // now push any pending app data into the socket
1189
1190 if (!ssl->ssl_closed) {
1191 char *data = ssl->outbuf;
1192 if (ssl->out_count > 0) {
1193 int wrote = BIO_write( ssl->bio_ssl, data, ssl->out_count );
1194 if (wrote > 0) {
1195 data += wrote;
1196 ssl->out_count -= wrote;
1197 work_pending = true;
1198 ssl_log( transport, PN_LEVEL_TRACE, "Wrote %d bytes from app to socket", wrote );
1199 } else {
1200 if (!BIO_should_retry(ssl->bio_ssl)) {
1201 int reason = SSL_get_error( ssl->ssl, wrote );
1202 switch (reason) {
1203 case SSL_ERROR_ZERO_RETURN:
1204 // SSL closed cleanly
1205 ssl_log(transport, PN_LEVEL_TRACE, "SSL connection has closed");
1206 start_ssl_shutdown(transport); // KAG: not sure - this may not be necessary
1207 ssl->out_count = 0; // can no longer write to socket, so erase app output data
1208 ssl->ssl_closed = true;
1209 break;
1210 default:
1211 // unexpected error
1212 return (ssize_t)ssl_failed(transport);
1213 }
1214 } else {
1215 if (BIO_should_read( ssl->bio_ssl )) {
1216 ssl->read_blocked = true;
1217 ssl_log(transport, PN_LEVEL_TRACE, "Detected read-blocked");
1218 }
1219 if (BIO_should_write( ssl->bio_ssl )) {
1220 ssl->write_blocked = true;
1221 ssl_log(transport, PN_LEVEL_TRACE, "Detected write-blocked");
1222 }
1223 }
1224 }
1225 }
1226
1227 if (ssl->out_count == 0) {
1228 if (ssl->app_input_closed && ssl->app_output_closed) {
1229 // application is done sending/receiving data, and all buffered output data has
1230 // been written to the SSL socket
1231 start_ssl_shutdown(transport);
1232 }
1233 } else if (data != ssl->outbuf) {
1234 memmove( ssl->outbuf, data, ssl->out_count );
1235 }
1236 }
1237
1238 // read from the network bio as much as possible, filling the buffer
1239 if (max_len) {
1240 int available = BIO_read( ssl->bio_net_io, buffer, max_len );
1241 if (available > 0) {
1242 max_len -= available;
1243 buffer += available;
1244 written += available;
1245 ssl->write_blocked = false;
1246 work_pending = work_pending || max_len > 0;
1247 ssl_log(transport, PN_LEVEL_TRACE, "Read %d bytes from BIO Layer", available );
1248 }
1249 }
1250
1251 } while (work_pending);
1252
1253 //_log(ssl, "written=%d ssl_closed=%d in_count=%d app_input_closed=%d app_output_closed=%d bio_pend=%d",
1254 // written, ssl->ssl_closed, ssl->in_count, ssl->app_input_closed, ssl->app_output_closed, BIO_pending(ssl->bio_net_io) );
1255
1256 // PROTON-82: close the output side as soon as we've sent the SSL close_notify.
1257 // We're not requiring the response, as some implementations never reply.
1258 // ----
1259 // Once no more data is available "below" the SSL socket, tell the transport we are
1260 // done.
1261 //if (written == 0 && ssl->ssl_closed && BIO_pending(ssl->bio_net_io) == 0) {
1262 // written = ssl->app_output_closed ? ssl->app_output_closed : PN_EOS;
1263 //}
1264 if (written == 0 && (SSL_get_shutdown(ssl->ssl) & SSL_SENT_SHUTDOWN) && BIO_pending(ssl->bio_net_io) == 0) {
1265 written = ssl->app_output_closed ? ssl->app_output_closed : PN_EOS;
1266 if (transport->io_layers[layer]==&ssl_input_closed_layer) {
1267 transport->io_layers[layer] = &ssl_closed_layer;
1268 } else {
1269 transport->io_layers[layer] = &ssl_output_closed_layer;
1270 }
1271 }
1272 ssl_log(transport, PN_LEVEL_TRACE, "process_output_ssl() returning %d", (int) written);
1273 return written;
1274 }
1275
1276 static int init_ssl_socket(pn_transport_t* transport, pni_ssl_t *ssl, pn_ssl_domain_t *domain)
1277 {
1278 if (ssl->ssl) return 0;
1279 if (!domain) return -1;
1280
1281 ssl->ssl = SSL_new(domain->ctx);
1282 if (!ssl->ssl) {
1283 ssl_log(transport, PN_LEVEL_ERROR, "SSL socket setup failure." );
1284 ssl_log_flush(transport, PN_LEVEL_ERROR);
1285 return -1;
1286 }
1287
1288 // store backpointer to pn_transport_t in SSL object:
1289 SSL_set_ex_data(ssl->ssl, ssl_ex_data_index, transport);
1290
1291 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
1292 if (ssl->peer_hostname && ssl->mode == PN_SSL_MODE_CLIENT) {
1293 SSL_set_tlsext_host_name(ssl->ssl, ssl->peer_hostname);
1294 }
1295 #endif
1296
1297 // restore session, if available
1298 ssn_restore(transport, ssl);
1299
1300 // now layer a BIO over the SSL socket
1301 ssl->bio_ssl = BIO_new(BIO_f_ssl());
1302 if (!ssl->bio_ssl) {
1303 ssl_log(transport, PN_LEVEL_ERROR, "BIO setup failure." );
1304 return -1;
1305 }
1306 (void)BIO_set_ssl(ssl->bio_ssl, ssl->ssl, BIO_NOCLOSE);
1307
1308 // create the "lower" BIO "pipe", and attach it below the SSL layer
1309 if (!BIO_new_bio_pair(&ssl->bio_ssl_io, 0, &ssl->bio_net_io, 0)) {
1310 ssl_log(transport, PN_LEVEL_ERROR, "BIO setup failure." );
1311 return -1;
1312 }
1313 SSL_set_bio(ssl->ssl, ssl->bio_ssl_io, ssl->bio_ssl_io);
1314
1315 if (ssl->mode == PN_SSL_MODE_SERVER) {
1316 SSL_set_accept_state(ssl->ssl);
1317 BIO_set_ssl_mode(ssl->bio_ssl, 0); // server mode
1318 ssl_log( transport, PN_LEVEL_TRACE, "Server SSL socket created." );
1319 } else { // client mode
1320 SSL_set_connect_state(ssl->ssl);
1321 BIO_set_ssl_mode(ssl->bio_ssl, 1); // client mode
1322 ssl_log( transport, PN_LEVEL_TRACE, "Client SSL socket created." );
1323 }
1324 ssl->subject = NULL;
1325 ssl->peer_certificate = NULL;
1326 return 0;
1327 }
1328
1329 static void release_ssl_socket(pni_ssl_t *ssl)
1330 {
1331 if (ssl->bio_ssl) BIO_free(ssl->bio_ssl);
1332 if (ssl->ssl) {
1333 SSL_free(ssl->ssl); // will free bio_ssl_io
1334 } else {
1335 if (ssl->bio_ssl_io) BIO_free(ssl->bio_ssl_io);
1336 }
1337 if (ssl->bio_net_io) BIO_free(ssl->bio_net_io);
1338 ssl->bio_ssl = NULL;
1339 ssl->bio_ssl_io = NULL;
1340 ssl->bio_net_io = NULL;
1341 ssl->ssl = NULL;
1342 }
1343
1344
1345
1346 pn_ssl_resume_status_t pn_ssl_resume_status(pn_ssl_t *ssl0)
1347 {
1348 pni_ssl_t *ssl = get_ssl_internal(ssl0);
1349 if (!ssl || !ssl->ssl) return PN_SSL_RESUME_UNKNOWN;
1350 switch (SSL_session_reused( ssl->ssl )) {
1351 case 0: return PN_SSL_RESUME_NEW;
1352 case 1: return PN_SSL_RESUME_REUSED;
1353 default: break;
1354 }
1355 return PN_SSL_RESUME_UNKNOWN;
1356 }
1357
1358
1359 int pn_ssl_set_peer_hostname(pn_ssl_t *ssl0, const char *hostname)
1360 {
1361 pni_ssl_t *ssl = get_ssl_internal(ssl0);
1362 if (!ssl) return -1;
1363
1364 if (ssl->peer_hostname) free((void *)ssl->peer_hostname);
1365 ssl->peer_hostname = NULL;
1366 if (hostname) {
1367 ssl->peer_hostname = pn_strdup(hostname);
1368 if (!ssl->peer_hostname) return -2;
1369 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
1370 if (ssl->ssl && ssl->mode == PN_SSL_MODE_CLIENT) {
1371 SSL_set_tlsext_host_name(ssl->ssl, ssl->peer_hostname);
1372 }
1373 #endif
1374 }
1375 return 0;
1376 }
1377
1378 int pn_ssl_get_peer_hostname(pn_ssl_t *ssl0, char *hostname, size_t *bufsize)
1379 {
1380 pni_ssl_t *ssl = get_ssl_internal(ssl0);
1381 if (!ssl) return -1;
1382 if (!ssl->peer_hostname) {
1383 *bufsize = 0;
1384 if (hostname) *hostname = '\0';
1385 return 0;
1386 }
1387 unsigned len = strlen(ssl->peer_hostname);
1388 if (hostname) {
1389 if (len >= *bufsize) return -1;
1390 strcpy( hostname, ssl->peer_hostname );
1391 }
1392 *bufsize = len;
1393 return 0;
1394 }
1395
1396 static X509 *get_peer_certificate(pni_ssl_t *ssl)
1397 {
1398 // Cache for multiple use and final X509_free
1399 if (!ssl->peer_certificate && ssl->ssl) {
1400 ssl->peer_certificate = SSL_get_peer_certificate(ssl->ssl);
1401 // May still be NULL depending on timing or type of SSL connection
1402 }
1403 return ssl->peer_certificate;
1404 }
1405
1406 const char* pn_ssl_get_remote_subject(pn_ssl_t *ssl0)
1407 {
1408 pni_ssl_t *ssl = get_ssl_internal(ssl0);
1409 if (!ssl || !ssl->ssl) return NULL;
1410 if (!ssl->subject) {
1411 X509 *cert = get_peer_certificate(ssl);
1412 if (!cert) return NULL;
1413 X509_NAME *subject = X509_get_subject_name(cert);
1414 if (!subject) return NULL;
1415
1416 BIO *out = BIO_new(BIO_s_mem());
1417 X509_NAME_print_ex(out, subject, 0, XN_FLAG_RFC2253);
1418 int len = BIO_number_written(out);
1419 ssl->subject = (char*) malloc(len+1);
1420 ssl->subject[len] = 0;
1421 BIO_read(out, ssl->subject, len);
1422 BIO_free(out);
1423 }
1424 return ssl->subject;
1425 }
1426
1427 int pn_ssl_get_cert_fingerprint(pn_ssl_t *ssl0, char *fingerprint, size_t fingerprint_length, pn_ssl_hash_alg hash_alg)
1428 {
1429 const char *digest_name = NULL;
1430 size_t min_required_length;
1431
1432 // old versions of python expect fingerprint to contain a valid string on
1433 // return from this function
1434 fingerprint[0] = 0;
1435
1436 // Assign the correct digest_name value based on the enum values.
1437 switch (hash_alg) {
1438 case PN_SSL_SHA1 :
1439 min_required_length = 41; // 40 hex characters + 1 '\0' character
1440 digest_name = "sha1";
1441 break;
1442 case PN_SSL_SHA256 :
1443 min_required_length = 65; // 64 hex characters + 1 '\0' character
1444 digest_name = "sha256";
1445 break;
1446 case PN_SSL_SHA512 :
1447 min_required_length = 129; // 128 hex characters + 1 '\0' character
1448 digest_name = "sha512";
1449 break;
1450 case PN_SSL_MD5 :
1451 min_required_length = 33; // 32 hex characters + 1 '\0' character
1452 digest_name = "md5";
1453 break;
1454 default:
1455 ssl_log_error("Unknown or unhandled hash algorithm %i ", hash_alg);
1456 return PN_ERR;
1457
1458 }
1459
1460 if(fingerprint_length < min_required_length) {
1461 ssl_log_error("Insufficient fingerprint_length %" PN_ZU ". fingerprint_length must be %" PN_ZU " or above for %s digest",
1462 fingerprint_length, min_required_length, digest_name);
1463 return PN_ERR;
1464 }
1465
1466 const EVP_MD *digest = EVP_get_digestbyname(digest_name);
1467
1468 pni_ssl_t *ssl = get_ssl_internal(ssl0);
1469 X509 *cert = get_peer_certificate(ssl);
1470
1471 if(cert) {
1472 unsigned int len;
1473
1474 unsigned char bytes[64]; // sha512 uses 64 octets, we will use that as the maximum.
1475
1476 if (X509_digest(cert, digest, bytes, &len) != 1) {
1477 ssl_log_error("Failed to extract X509 digest");
1478 return PN_ERR;
1479 }
1480
1481 char *cursor = fingerprint;
1482
1483 for (size_t i=0; i<len ; i++) {
1484 cursor += snprintf((char *)cursor, fingerprint_length, "%02x", bytes[i]);
1485 fingerprint_length = fingerprint_length - 2;
1486 }
1487
1488 return PN_OK;
1489 }
1490 else {
1491 ssl_log_error("No certificate is available yet ");
1492 return PN_ERR;
1493 }
1494
1495 return 0;
1496 }
1497
1498
1499 const char* pn_ssl_get_remote_subject_subfield(pn_ssl_t *ssl0, pn_ssl_cert_subject_subfield field)
1500 {
1501 int openssl_field = 0;
1502
1503 // Assign openssl internal representations of field values to openssl_field
1504 switch (field) {
1505 case PN_SSL_CERT_SUBJECT_COUNTRY_NAME :
1506 openssl_field = NID_countryName;
1507 break;
1508 case PN_SSL_CERT_SUBJECT_STATE_OR_PROVINCE :
1509 openssl_field = NID_stateOrProvinceName;
1510 break;
1511 case PN_SSL_CERT_SUBJECT_CITY_OR_LOCALITY :
1512 openssl_field = NID_localityName;
1513 break;
1514 case PN_SSL_CERT_SUBJECT_ORGANIZATION_NAME :
1515 openssl_field = NID_organizationName;
1516 break;
1517 case PN_SSL_CERT_SUBJECT_ORGANIZATION_UNIT :
1518 openssl_field = NID_organizationalUnitName;
1519 break;
1520 case PN_SSL_CERT_SUBJECT_COMMON_NAME :
1521 openssl_field = NID_commonName;
1522 break;
1523 default:
1524 ssl_log_error("Unknown or unhandled certificate subject subfield %i", field);
1525 return NULL;
1526 }
1527
1528 pni_ssl_t *ssl = get_ssl_internal(ssl0);
1529 X509 *cert = get_peer_certificate(ssl);
1530 if (!cert) return NULL;
1531
1532 X509_NAME *subject_name = X509_get_subject_name(cert);
1533
1534 // TODO (gmurthy) - A server side cert subject field can have more than one common name like this - Subject: CN=www.domain1.com, CN=www.domain2.com, see https://bugzilla.mozilla.org/show_bug.cgi?id=380656
1535 // For now, we will only return the first common name if there is more than one common name in the cert
1536 int index = X509_NAME_get_index_by_NID(subject_name, openssl_field, -1);
1537
1538 if (index > -1) {
1539 X509_NAME_ENTRY *ne = X509_NAME_get_entry(subject_name, index);
1540 if(ne) {
1541 ASN1_STRING *name_asn1 = X509_NAME_ENTRY_get_data(ne);
1542 return (char *) name_asn1->data;
1543 }
1544 }
1545
1546 return NULL;
1547 }
1548
1549 static ssize_t process_input_done(pn_transport_t *transport, unsigned int layer, const char *input_data, size_t len)
1550 {
1551 return PN_EOS;
1552 }
1553 static ssize_t process_output_done(pn_transport_t *transport, unsigned int layer, char *input_data, size_t len)
1554 {
1555 return PN_EOS;
1556 }
1557
1558 // return # output bytes sitting in this layer
1559 static size_t buffered_output(pn_transport_t *transport)
1560 {
1561 size_t count = 0;
1562 pni_ssl_t *ssl = transport->ssl;
1563 if (ssl) {
1564 count += ssl->out_count;
1565 if (ssl->bio_net_io) { // pick up any bytes waiting for network io
1566 count += BIO_ctrl_pending(ssl->bio_net_io);
1567 }
1568 }
1569 return count;
1570 }
1571
1572
1573 /* Thread-safe locking and initialization for POSIX and Windows */
1574
1575 static bool init_ok = false;
1576
1577 #ifdef _WIN32
1578
1579 typedef CRITICAL_SECTION pni_mutex_t;
1580 static inline void pni_mutex_init(pni_mutex_t *m) { InitializeCriticalSection(m); }
1581 static inline void pni_mutex_lock(pni_mutex_t *m) { EnterCriticalSection(m); }
1582 static inline void pni_mutex_unlock(pni_mutex_t *m) { LeaveCriticalSection(m); }
1583 static inline unsigned long id_callback(void) { return (unsigned long)GetCurrentThreadId(); }
1584 INIT_ONCE initialize_once = INIT_ONCE_STATIC_INIT;
1585 static inline bool ensure_initialized(void) {
1586 void* dummy;
1587 InitOnceExecuteOnce(&initialize_once, &initialize, NULL, &dummy);
1588 return init_ok;
1589 }
1590
1591 #else /* POSIX */
1592
1593 #include <pthread.h>
1594
1595 static void initialize(void);
1596
1597 typedef pthread_mutex_t pni_mutex_t;
1598 static inline int pni_mutex_init(pni_mutex_t *m) { return pthread_mutex_init(m, NULL); }
1599 static inline int pni_mutex_lock(pni_mutex_t *m) { return pthread_mutex_lock(m); }
1600 static inline int pni_mutex_unlock(pni_mutex_t *m) { return pthread_mutex_unlock(m); }
1601 static inline unsigned long id_callback(void) { return (unsigned long)pthread_self(); }
1602 static pthread_once_t initialize_once = PTHREAD_ONCE_INIT;
1603 static inline bool ensure_initialized(void) {
1604 pthread_once(&initialize_once, &initialize);
1605 return init_ok;
1606 }
1607
1608 #endif
1609
1610 static pni_mutex_t *locks = NULL; /* Lock array for openssl */
1611
1612 /* Callback function for openssl locking */
1613 static void locking_callback(int mode, int n, const char *file, int line) {
1614 if(mode & CRYPTO_LOCK)
1615 pni_mutex_lock(&locks[n]);
1616 else
1617 pni_mutex_unlock(&locks[n]);
1618 }
1619
1620 static void initialize(void) {
1621 int i;
1622 SSL_library_init();
1623 SSL_load_error_strings();
1624 OpenSSL_add_all_algorithms();
1625 ssl_ex_data_index = SSL_get_ex_new_index( 0, (void *) "org.apache.qpid.proton.ssl",
1626 NULL, NULL, NULL);
1627 ssn_init();
1628 locks = (pni_mutex_t*)malloc(CRYPTO_num_locks() * sizeof(pni_mutex_t));
1629 if (!locks) return;
1630 for(i = 0; i < CRYPTO_num_locks(); i++)
1631 pni_mutex_init(&locks[i]);
1632 CRYPTO_set_id_callback(&id_callback);
1633 CRYPTO_set_locking_callback(&locking_callback);
1634 /* In recent versions of openssl, the set_callback functions are no-op macros,
1635 so we need to take steps to stop the compiler complaining about unused functions. */
1636 (void)&id_callback;
1637 (void)&locking_callback;
1638 init_ok = true;
1639 }
1640
1641 /* TODO aconway 2017-10-16: There is no opportunity to clean up the locks as proton has no
1642 final shut-down call. If it did, we should call this: */
1643 /*
1644 static void shutdown(void) {
1645 CRYPTO_set_id_callback(NULL);
1646 CRYPTO_set_locking_callback(NULL);
1647 if(locks) {
1648 int i;
1649 for(i = 0; i < CRYPTO_num_locks(); i++)
1650 pni_mutex_destroy(&locks[i]);
1651 free(locks);
1652 locks = NULL;
1653 }
1654 }
1655 */