1 /*! \file    dtls.c
2  * \author   Lorenzo Miniero <lorenzo@meetecho.com>
3  * \copyright GNU General Public License v3
4  * \brief    DTLS/SRTP processing
5  * \details  Implementation (based on OpenSSL and libsrtp) of the DTLS/SRTP
6  * transport. The code takes care of the DTLS handshake between peers and
7  * the server, and sets the proper SRTP and SRTCP context up accordingly.
8  * A DTLS alert from a peer is notified to the plugin handling him/her
9  * by means of the hangup_media callback.
10  *
11  * \ingroup protocols
12  * \ref protocols
13  */
14 
15 #include "janus.h"
16 #include "debug.h"
17 #include "dtls.h"
18 #include "rtcp.h"
19 #include "events.h"
20 
21 #include <openssl/err.h>
22 #include <openssl/bn.h>
23 #include <openssl/evp.h>
24 #include <openssl/rsa.h>
25 #include <openssl/asn1.h>
26 
27 
janus_get_dtls_srtp_state(janus_dtls_state state)28 const gchar *janus_get_dtls_srtp_state(janus_dtls_state state) {
29 	switch(state) {
30 		case JANUS_DTLS_STATE_CREATED:
31 			return "created";
32 		case JANUS_DTLS_STATE_TRYING:
33 			return "trying";
34 		case JANUS_DTLS_STATE_CONNECTED:
35 			return "connected";
36 		case JANUS_DTLS_STATE_FAILED:
37 			return "failed";
38 		default:
39 			return NULL;
40 	}
41 	return NULL;
42 }
43 
janus_get_dtls_srtp_role(janus_dtls_role role)44 const gchar *janus_get_dtls_srtp_role(janus_dtls_role role) {
45 	switch(role) {
46 		case JANUS_DTLS_ROLE_ACTPASS:
47 			return "actpass";
48 		case JANUS_DTLS_ROLE_SERVER:
49 			return "passive";
50 		case JANUS_DTLS_ROLE_CLIENT:
51 			return "active";
52 		default:
53 			return NULL;
54 	}
55 	return NULL;
56 }
57 
janus_get_dtls_srtp_profile(int profile)58 const gchar *janus_get_dtls_srtp_profile(int profile) {
59 	switch(profile) {
60 		case SRTP_AES128_CM_SHA1_80:
61 			return "SRTP_AES128_CM_SHA1_80";
62 		case SRTP_AES128_CM_SHA1_32:
63 			return "SRTP_AES128_CM_SHA1_32";
64 #ifdef HAVE_SRTP_AESGCM
65 		case SRTP_AEAD_AES_256_GCM:
66 			return "SRTP_AEAD_AES_256_GCM";
67 		case SRTP_AEAD_AES_128_GCM:
68 			return "SRTP_AEAD_AES_128_GCM";
69 #endif
70 		default:
71 			return NULL;
72 	}
73 	return NULL;
74 }
75 
76 /* Helper to notify DTLS state changes to the event handlers */
janus_dtls_notify_state_change(janus_dtls_srtp * dtls)77 static void janus_dtls_notify_state_change(janus_dtls_srtp *dtls) {
78 	if(!janus_events_is_enabled())
79 		return;
80 	if(dtls == NULL)
81 		return;
82 	janus_ice_component *component = (janus_ice_component *)dtls->component;
83 	if(component == NULL)
84 		return;
85 	janus_ice_stream *stream = component->stream;
86 	if(stream == NULL)
87 		return;
88 	janus_ice_handle *handle = stream->handle;
89 	if(handle == NULL)
90 		return;
91 	janus_session *session = (janus_session *)handle->session;
92 	if(session == NULL)
93 		return;
94 	json_t *info = json_object();
95 	json_object_set_new(info, "dtls", json_string(janus_get_dtls_srtp_state(dtls->dtls_state)));
96 	json_object_set_new(info, "stream_id", json_integer(stream->stream_id));
97 	json_object_set_new(info, "component_id", json_integer(component->component_id));
98 	json_object_set_new(info, "retransmissions", json_integer(dtls->retransmissions));
99 	janus_events_notify_handlers(JANUS_EVENT_TYPE_WEBRTC, JANUS_EVENT_SUBTYPE_WEBRTC_DTLS,
100 		session->session_id, handle->handle_id, handle->opaque_id, info);
101 }
102 
janus_is_dtls(char * buf)103 gboolean janus_is_dtls(char *buf) {
104 	return ((*buf >= 20) && (*buf <= 64));
105 }
106 
107 /* DTLS stuff */
108 #define DTLS_DEFAULT_CIPHERS	"DEFAULT:!NULL:!aNULL:!SHA256:!SHA384:!aECDH:!AESGCM+AES256:!aPSK"
109 static const char *dtls_ciphers = DTLS_DEFAULT_CIPHERS;
110 /* Duration for the self-generated certs: 1 year */
111 #define DTLS_AUTOCERT_DURATION	60*60*24*365
112 /* NIST P-256 elliptic curve used for private key generation */
113 #define DTLS_ELLIPTIC_CURVE NID_X9_62_prime256v1
114 
115 /* By default we always accept self-signed certificates (that's what almost
116  * all of the existing WebRTC implementations do today), but if told so we
117  * can be configured to reject them, and validate them instead */
118 static gboolean dtls_selfsigned_certs_ok = TRUE;
janus_dtls_are_selfsigned_certs_ok(void)119 gboolean janus_dtls_are_selfsigned_certs_ok(void) {
120 	return dtls_selfsigned_certs_ok;
121 }
122 
123 /* DTLS timeout base to enforce: notice that this can currently only be
124  * modified if you're using BoringSSL, as OpenSSL uses 1s (1000ms) and
125  * that value cannot be modified (it will in OpenSSL v1.1.1) */
126 static guint16 dtls_timeout_base = 1000;
127 
128 static SSL_CTX *ssl_ctx = NULL;
129 static X509 *ssl_cert = NULL;
130 static EVP_PKEY *ssl_key = NULL;
131 
132 static gchar local_fingerprint[160];
janus_dtls_get_local_fingerprint(void)133 gchar *janus_dtls_get_local_fingerprint(void) {
134 	return (gchar *)local_fingerprint;
135 }
136 
137 
138 #if JANUS_USE_OPENSSL_PRE_1_1_API && !defined(HAVE_BORINGSSL)
139 /*
140  * DTLS locking stuff to make OpenSSL thread safe (not needed for 1.1.0)
141  *
142  * Note: this is an attempt to fix the infamous issue #316:
143  * 		https://github.com/meetecho/janus-gateway/issues/316
144  * that is the "tlsv1 alert decrypt error" randomly happening when
145  * doing handshakes that force Janus to be restarted (issue affecting
146  * OpenSSL but NOT BoringSSL, apparently). The cause might be related
147  * to race conditions, and in fact OpenSSL docs state that:
148  *
149  * 		"OpenSSL can safely be used in multi-threaded applications
150  * 		provided that at least two callback functions are set,
151  * 		locking_function and threadid_func."
152  *
153  * See here for the whole docs:
154  * 		https://www.openssl.org/docs/manmaster/crypto/threads.html
155  *
156  * The fix proposed here is heavily derived from a discussion related to
157  * RTPEngine:
158  * 		http://lists.sip-router.org/pipermail/sr-dev/2015-January/026860.html
159  * where it was mentioned the issue was fixed in this commit:
160  * 		https://github.com/sipwise/rtpengine/commit/935487b66363c9932684d8085f47450d65a8c37e
161  * which does indeed implement the callbacks the OpenSSL docs suggest.
162  *
163  */
164 static pthread_mutex_t *janus_dtls_locks;
165 
janus_dtls_cb_openssl_threadid(CRYPTO_THREADID * tid)166 static void janus_dtls_cb_openssl_threadid(CRYPTO_THREADID *tid) {
167 	/* FIXME Assuming pthread, which is fine as GLib wraps pthread and
168 	 * so that's what we use anyway? */
169 	pthread_t me = pthread_self();
170 
171 	if(sizeof(me) == sizeof(void *)) {
172 		CRYPTO_THREADID_set_pointer(tid, (void *) me);
173 	} else {
174 		CRYPTO_THREADID_set_numeric(tid, (unsigned long) me);
175 	}
176 }
177 
janus_dtls_cb_openssl_lock(int mode,int type,const char * file,int line)178 static void janus_dtls_cb_openssl_lock(int mode, int type, const char *file, int line) {
179 	if((mode & CRYPTO_LOCK)) {
180 		pthread_mutex_lock(&janus_dtls_locks[type]);
181 	} else {
182 		pthread_mutex_unlock(&janus_dtls_locks[type]);
183 	}
184 }
185 #endif
186 
187 
janus_dtls_generate_keys(X509 ** certificate,EVP_PKEY ** private_key,gboolean rsa_private_key)188 static int janus_dtls_generate_keys(X509 **certificate, EVP_PKEY **private_key, gboolean rsa_private_key) {
189 	static const int num_bits = 2048;
190 	BIGNUM *bne = NULL;
191 	RSA *rsa_key = NULL;
192 	X509_NAME *cert_name = NULL;
193 	EC_KEY *ecc_key = NULL;
194 
195 	JANUS_LOG(LOG_VERB, "Generating DTLS key / cert\n");
196 
197 	/* Create a private key object (needed to hold the RSA key). */
198 	*private_key = EVP_PKEY_new();
199 	if(!*private_key) {
200 		JANUS_LOG(LOG_FATAL, "EVP_PKEY_new() failed\n");
201 		goto error;
202 	}
203 
204 
205 	if(rsa_private_key) {
206 		/* Create a big number object. */
207 		bne = BN_new();
208 		if(!bne) {
209 			JANUS_LOG(LOG_FATAL, "BN_new() failed\n");
210 			goto error;
211 		}
212 
213 		if(!BN_set_word(bne, RSA_F4)) {  /* RSA_F4 == 65537 */
214 			JANUS_LOG(LOG_FATAL, "BN_set_word() failed\n");
215 			goto error;
216 		}
217 
218 		/* Generate a RSA key. */
219 		rsa_key = RSA_new();
220 		if(!rsa_key) {
221 			JANUS_LOG(LOG_FATAL, "RSA_new() failed\n");
222 			goto error;
223 		}
224 
225 		/* This takes some time. */
226 		if(!RSA_generate_key_ex(rsa_key, num_bits, bne, NULL)) {
227 			JANUS_LOG(LOG_FATAL, "RSA_generate_key_ex() failed\n");
228 			goto error;
229 		}
230 
231 		if(!EVP_PKEY_assign_RSA(*private_key, rsa_key)) {
232 			JANUS_LOG(LOG_FATAL, "EVP_PKEY_assign_RSA() failed\n");
233 			goto error;
234 		}
235 
236 		/* The RSA key now belongs to the private key, so don't clean it up separately. */
237 		rsa_key = NULL;
238 	} else {
239 		/* Create key with curve dictated by DTLS_ELLIPTIC_CURVE */
240 		if((ecc_key = EC_KEY_new_by_curve_name(DTLS_ELLIPTIC_CURVE)) == NULL) {
241 			JANUS_LOG(LOG_FATAL, "EC_KEY_new_by_curve_name() failed\n");
242 			goto error;
243 		}
244 
245 		EC_KEY_set_asn1_flag(ecc_key, OPENSSL_EC_NAMED_CURVE);
246 
247 		/* This takes some time. */
248 		if(EC_KEY_generate_key(ecc_key) == 0) {
249 			JANUS_LOG(LOG_FATAL, "EC_KEY_generate_key() failed\n");
250 			goto error;
251 		}
252 
253 		if(EVP_PKEY_assign_EC_KEY(*private_key, ecc_key) == 0) {
254 			JANUS_LOG(LOG_FATAL, "EVP_PKEY_assign_EC_KEY() failed\n");
255 			goto error;
256 		}
257 
258 		/* The EC key now belongs to the private key, so don't clean it up separately. */
259 		ecc_key = NULL;
260 	}
261 
262 	/* Create the X509 certificate. */
263 	*certificate = X509_new();
264 	if(!*certificate) {
265 		JANUS_LOG(LOG_FATAL, "X509_new() failed\n");
266 		goto error;
267 	}
268 
269 	/* Set version 3 (note that 0 means version 1). */
270 	X509_set_version(*certificate, 2);
271 
272 	/* Set serial number. */
273 	ASN1_INTEGER_set(X509_get_serialNumber(*certificate), (long)g_random_int());
274 
275 	/* Set valid period. */
276 	X509_gmtime_adj(X509_get_notBefore(*certificate), -1 * DTLS_AUTOCERT_DURATION);  /* -1 year */
277 	X509_gmtime_adj(X509_get_notAfter(*certificate), DTLS_AUTOCERT_DURATION);  /* 1 year */
278 
279 	/* Set the public key for the certificate using the key. */
280 	if(!X509_set_pubkey(*certificate, *private_key)) {
281 		JANUS_LOG(LOG_FATAL, "X509_set_pubkey() failed\n");
282 		goto error;
283 	}
284 
285 	/* Set certificate fields. */
286 	cert_name = X509_get_subject_name(*certificate);
287 	if(!cert_name) {
288 		JANUS_LOG(LOG_FATAL, "X509_get_subject_name() failed\n");
289 		goto error;
290 	}
291 	X509_NAME_add_entry_by_txt(cert_name, "O", MBSTRING_ASC, (const unsigned char*)"Janus", -1, -1, 0);
292 	X509_NAME_add_entry_by_txt(cert_name, "CN", MBSTRING_ASC, (const unsigned char*)"Janus", -1, -1, 0);
293 
294 	/* It is self-signed so set the issuer name to be the same as the subject. */
295 	if(!X509_set_issuer_name(*certificate, cert_name)) {
296 		JANUS_LOG(LOG_FATAL, "X509_set_issuer_name() failed\n");
297 		goto error;
298 	}
299 
300 	/* Sign the certificate with the private key. */
301 	if(!X509_sign(*certificate, *private_key, EVP_sha1())) {
302 		JANUS_LOG(LOG_FATAL, "X509_sign() failed\n");
303 		goto error;
304 	}
305 
306 	/* Free stuff and resurn. */
307 	BN_free(bne);
308 	return 0;
309 
310 error:
311 	if(bne)
312 		BN_free(bne);
313 	if(rsa_key && !*private_key)
314 		RSA_free(rsa_key);
315 	if(ecc_key && !*private_key)
316 		EC_KEY_free(ecc_key);
317 	if(*private_key)
318 		EVP_PKEY_free(*private_key);  /* This also frees the RSA key. */
319 	if(*certificate)
320 		X509_free(*certificate);
321 	return -1;
322 }
323 
324 
janus_dtls_load_keys(const char * server_pem,const char * server_key,const char * password,X509 ** certificate,EVP_PKEY ** private_key)325 static int janus_dtls_load_keys(const char *server_pem, const char *server_key, const char *password,
326 		X509 **certificate, EVP_PKEY **private_key) {
327 	FILE *f = NULL;
328 
329 	f = fopen(server_pem, "r");
330 	if(!f) {
331 		JANUS_LOG(LOG_FATAL, "Error opening certificate file\n");
332 		goto error;
333 	}
334 	*certificate = PEM_read_X509(f, NULL, NULL, NULL);
335 	if(!*certificate) {
336 		JANUS_LOG(LOG_FATAL, "PEM_read_X509 failed\n");
337 		goto error;
338 	}
339 	fclose(f);
340 
341 	f = fopen(server_key, "r");
342 	if(!f) {
343 		JANUS_LOG(LOG_FATAL, "Error opening key file\n");
344 		goto error;
345 	}
346 	*private_key = PEM_read_PrivateKey(f, NULL, NULL, (void *)password);
347 	if(!*private_key) {
348 		JANUS_LOG(LOG_FATAL, "PEM_read_PrivateKey failed\n");
349 		goto error;
350 	}
351 	fclose(f);
352 
353 	return 0;
354 
355 error:
356 	if(*certificate) {
357 		X509_free(*certificate);
358 		*certificate = NULL;
359 	}
360 	if(*private_key) {
361 		EVP_PKEY_free(*private_key);
362 		*private_key = NULL;
363 	}
364 	return -1;
365 }
366 
367 /* Versioning info ( */
janus_get_ssl_version(void)368 const char *janus_get_ssl_version(void) {
369 	return OPENSSL_VERSION_TEXT;
370 }
371 
372 /* DTLS-SRTP initialization */
janus_dtls_srtp_init(const char * server_pem,const char * server_key,const char * password,const char * ciphers,guint16 timeout,gboolean rsa_private_key,gboolean accept_selfsigned)373 gint janus_dtls_srtp_init(const char *server_pem, const char *server_key, const char *password,
374 		const char *ciphers, guint16 timeout, gboolean rsa_private_key, gboolean accept_selfsigned) {
375 	const char *crypto_lib = NULL;
376 #if JANUS_USE_OPENSSL_PRE_1_1_API && !defined(HAVE_BORINGSSL)
377 #if defined(LIBRESSL_VERSION_NUMBER)
378 	crypto_lib = "LibreSSL";
379 #else
380 	crypto_lib = "OpenSSL pre-1.1.0";
381 #endif
382 	/* First of all make OpenSSL thread safe (see note above on issue #316) */
383 	janus_dtls_locks = g_malloc0(sizeof(*janus_dtls_locks) * CRYPTO_num_locks());
384 	int l=0;
385 	for(l = 0; l < CRYPTO_num_locks(); l++) {
386 		pthread_mutex_init(&janus_dtls_locks[l], NULL);
387 	}
388 	CRYPTO_THREADID_set_callback(janus_dtls_cb_openssl_threadid);
389 	CRYPTO_set_locking_callback(janus_dtls_cb_openssl_lock);
390 #else
391 	crypto_lib = "OpenSSL >= 1.1.0";
392 #endif
393 #ifdef HAVE_BORINGSSL
394 	crypto_lib = "BoringSSL";
395 #endif
396 	JANUS_LOG(LOG_INFO, "Crypto: %s\n", crypto_lib);
397 #ifndef HAVE_SRTP_AESGCM
398 	JANUS_LOG(LOG_WARN, "The libsrtp installation does not support AES-GCM profiles\n");
399 #endif
400 
401 	/* Go on and create the DTLS context */
402 #if JANUS_USE_OPENSSL_PRE_1_1_API && !defined(HAVE_BORINGSSL)
403 #if defined(LIBRESSL_VERSION_NUMBER)
404 	ssl_ctx = SSL_CTX_new(DTLSv1_method());
405 #else
406 	ssl_ctx = SSL_CTX_new(DTLSv1_2_method());
407 #endif
408 #else
409 	ssl_ctx = SSL_CTX_new(DTLS_method());
410 #endif
411 	if(!ssl_ctx) {
412 		JANUS_LOG(LOG_FATAL, "Ops, error creating DTLS context?\n");
413 		return -1;
414 	}
415 	SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, janus_dtls_verify_callback);
416 	SSL_CTX_set_tlsext_use_srtp(ssl_ctx,
417 #ifdef HAVE_SRTP_AESGCM
418 		"SRTP_AEAD_AES_256_GCM:SRTP_AEAD_AES_128_GCM:SRTP_AES128_CM_SHA1_80:SRTP_AES128_CM_SHA1_32");
419 #else
420 		"SRTP_AES128_CM_SHA1_80:SRTP_AES128_CM_SHA1_32");
421 #endif
422 
423 	if(!server_pem && !server_key) {
424 		JANUS_LOG(LOG_INFO, "No cert/key specified, autogenerating some...\n");
425 		if(janus_dtls_generate_keys(&ssl_cert, &ssl_key, rsa_private_key) != 0) {
426 			JANUS_LOG(LOG_FATAL, "Error generating DTLS key/certificate\n");
427 			return -2;
428 		}
429 	} else if(!server_pem || !server_key) {
430 		JANUS_LOG(LOG_FATAL, "DTLS certificate and key must be specified\n");
431 		return -2;
432 	} else if(janus_dtls_load_keys(server_pem, server_key, password, &ssl_cert, &ssl_key) != 0) {
433 		return -3;
434 	}
435 
436 	if(!SSL_CTX_use_certificate(ssl_ctx, ssl_cert)) {
437 		JANUS_LOG(LOG_FATAL, "Certificate error (%s)\n", ERR_reason_error_string(ERR_get_error()));
438 		return -4;
439 	}
440 	if(!SSL_CTX_use_PrivateKey(ssl_ctx, ssl_key)) {
441 		JANUS_LOG(LOG_FATAL, "Certificate key error (%s)\n", ERR_reason_error_string(ERR_get_error()));
442 		return -5;
443 	}
444 	if(!SSL_CTX_check_private_key(ssl_ctx)) {
445 		JANUS_LOG(LOG_FATAL, "Certificate check error (%s)\n", ERR_reason_error_string(ERR_get_error()));
446 		return -6;
447 	}
448 	SSL_CTX_set_read_ahead(ssl_ctx,1);
449 
450 	unsigned int size;
451 	unsigned char fingerprint[EVP_MAX_MD_SIZE];
452 	if(X509_digest(ssl_cert, EVP_sha256(), (unsigned char *)fingerprint, &size) == 0) {
453 		JANUS_LOG(LOG_FATAL, "Error converting X509 structure (%s)\n", ERR_reason_error_string(ERR_get_error()));
454 		return -7;
455 	}
456 	char *lfp = (char *)&local_fingerprint;
457 	unsigned int i = 0;
458 	for(i = 0; i < size; i++) {
459 		g_snprintf(lfp, 4, "%.2X:", fingerprint[i]);
460 		lfp += 3;
461 	}
462 	*(lfp-1) = 0;
463 	JANUS_LOG(LOG_INFO, "Fingerprint of our certificate: %s\n", local_fingerprint);
464 	if(ciphers)
465 		dtls_ciphers = ciphers;
466 	if(SSL_CTX_set_cipher_list(ssl_ctx, dtls_ciphers) == 0) {
467 		JANUS_LOG(LOG_FATAL, "Error setting cipher list (%s)\n", ERR_reason_error_string(ERR_get_error()));
468 		return -8;
469 	}
470 
471 	if(janus_dtls_bio_agent_init() < 0) {
472 		JANUS_LOG(LOG_FATAL, "Error initializing BIO agent\n");
473 		return -9;
474 	}
475 
476 	dtls_timeout_base = timeout;
477 #ifndef HAVE_BORINGSSL
478 	if(dtls_timeout_base != 1000) {
479 		JANUS_LOG(LOG_WARN, "DTLS timeout set to %u ms, but not using BoringSSL: ignoring\n", timeout);
480 	}
481 #endif
482 
483 	/* Initialize libsrtp */
484 	if(srtp_init() != srtp_err_status_ok) {
485 		JANUS_LOG(LOG_FATAL, "Ops, error setting up libsrtp?\n");
486 		return -10;
487 	}
488 
489 	/* Finally, let's set our policy with respect to DTLS self signed certificates */
490 	dtls_selfsigned_certs_ok = accept_selfsigned;
491 	if(!dtls_selfsigned_certs_ok) {
492 		JANUS_LOG(LOG_WARN, "WebRTC PeerConnections with self-signed certificates will NOT be accepted\n");
493 	}
494 
495 	return 0;
496 }
497 
janus_dtls_srtp_free(const janus_refcount * dtls_ref)498 static void janus_dtls_srtp_free(const janus_refcount *dtls_ref) {
499 	janus_dtls_srtp *dtls = janus_refcount_containerof(dtls_ref, janus_dtls_srtp, ref);
500 	/* This stack can be destroyed, free all the resources */
501 	dtls->component = NULL;
502 	if(dtls->ssl != NULL) {
503 		SSL_free(dtls->ssl);
504 		dtls->ssl = NULL;
505 	}
506 	/* BIOs are destroyed by SSL_free */
507 	dtls->read_bio = NULL;
508 	dtls->write_bio = NULL;
509 	if(dtls->srtp_valid) {
510 		if(dtls->srtp_in) {
511 			srtp_dealloc(dtls->srtp_in);
512 			dtls->srtp_in = NULL;
513 		}
514 		if(dtls->srtp_out) {
515 			srtp_dealloc(dtls->srtp_out);
516 			dtls->srtp_out = NULL;
517 		}
518 		/* FIXME What about dtls->remote_policy and dtls->local_policy? */
519 	}
520 	g_free(dtls);
521 	dtls = NULL;
522 }
523 
janus_dtls_srtp_cleanup(void)524 void janus_dtls_srtp_cleanup(void) {
525 	if(ssl_cert != NULL) {
526 		X509_free(ssl_cert);
527 		ssl_cert = NULL;
528 	}
529 	if(ssl_key != NULL) {
530 		EVP_PKEY_free(ssl_key);
531 		ssl_key = NULL;
532 	}
533 	if(ssl_ctx != NULL) {
534 		SSL_CTX_free(ssl_ctx);
535 		ssl_ctx = NULL;
536 	}
537 #if JANUS_USE_OPENSSL_PRE_1_1_API && !defined(HAVE_BORINGSSL)
538 	g_free(janus_dtls_locks);
539 #endif
540 }
541 
542 
janus_dtls_srtp_create(void * ice_component,janus_dtls_role role)543 janus_dtls_srtp *janus_dtls_srtp_create(void *ice_component, janus_dtls_role role) {
544 	janus_ice_component *component = (janus_ice_component *)ice_component;
545 	if(component == NULL) {
546 		JANUS_LOG(LOG_ERR, "No component, no DTLS...\n");
547 		return NULL;
548 	}
549 	janus_ice_stream *stream = component->stream;
550 	if(!stream) {
551 		JANUS_LOG(LOG_ERR, "No stream, no DTLS...\n");
552 		return NULL;
553 	}
554 	janus_ice_handle *handle = stream->handle;
555 	if(!handle || !handle->agent) {
556 		JANUS_LOG(LOG_ERR, "No handle/agent, no DTLS...\n");
557 		return NULL;
558 	}
559 	janus_dtls_srtp *dtls = g_malloc0(sizeof(janus_dtls_srtp));
560 	g_atomic_int_set(&dtls->destroyed, 0);
561 	janus_refcount_init(&dtls->ref, janus_dtls_srtp_free);
562 	/* Create SSL context, at last */
563 	dtls->srtp_valid = 0;
564 	dtls->ssl = SSL_new(ssl_ctx);
565 	if(!dtls->ssl) {
566 		JANUS_LOG(LOG_ERR, "[%"SCNu64"]     Error creating DTLS session! (%s)\n",
567 			handle->handle_id, ERR_reason_error_string(ERR_get_error()));
568 		janus_refcount_decrease(&dtls->ref);
569 		return NULL;
570 	}
571 	SSL_set_ex_data(dtls->ssl, 0, dtls);
572 	SSL_set_info_callback(dtls->ssl, janus_dtls_callback);
573 	dtls->read_bio = BIO_new(BIO_s_mem());
574 	if(!dtls->read_bio) {
575 		JANUS_LOG(LOG_ERR, "[%"SCNu64"]   Error creating read BIO! (%s)\n",
576 			handle->handle_id, ERR_reason_error_string(ERR_get_error()));
577 		janus_refcount_decrease(&dtls->ref);
578 		return NULL;
579 	}
580 	BIO_set_mem_eof_return(dtls->read_bio, -1);
581 	dtls->write_bio = BIO_janus_dtls_agent_new(dtls);
582 	if(!dtls->write_bio) {
583 		JANUS_LOG(LOG_ERR, "[%"SCNu64"]   Error creating write BIO! (%s)\n",
584 			handle->handle_id, ERR_reason_error_string(ERR_get_error()));
585 		janus_refcount_decrease(&dtls->ref);
586 		return NULL;
587 	}
588 	SSL_set_bio(dtls->ssl, dtls->read_bio, dtls->write_bio);
589 	/* The role may change later, depending on the negotiation */
590 	dtls->dtls_role = role;
591 	/* https://code.google.com/p/chromium/issues/detail?id=406458
592 	 * Specify an ECDH group for ECDHE ciphers, otherwise they cannot be
593 	 * negotiated when acting as the server. Use NIST's P-256 which is
594 	 * commonly supported.
595 	 */
596 	EC_KEY *ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
597 	if(ecdh == NULL) {
598 		JANUS_LOG(LOG_ERR, "[%"SCNu64"]   Error creating ECDH group! (%s)\n",
599 			handle->handle_id, ERR_reason_error_string(ERR_get_error()));
600 		janus_refcount_decrease(&dtls->ref);
601 		return NULL;
602 	}
603 	const long flags = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_COMPRESSION | SSL_OP_SINGLE_ECDH_USE;
604 	SSL_set_options(dtls->ssl, flags);
605 	SSL_set_tmp_ecdh(dtls->ssl, ecdh);
606 	EC_KEY_free(ecdh);
607 #ifdef HAVE_DTLS_SETTIMEOUT
608 	JANUS_LOG(LOG_VERB, "[%"SCNu64"]   Setting DTLS initial timeout: %"SCNu16"ms\n", handle->handle_id, dtls_timeout_base);
609 	DTLSv1_set_initial_timeout_duration(dtls->ssl, dtls_timeout_base);
610 #endif
611 	dtls->ready = 0;
612 	dtls->retransmissions = 0;
613 #ifdef HAVE_SCTP
614 	dtls->sctp = NULL;
615 #endif
616 	/* Done */
617 	dtls->dtls_connected = 0;
618 	dtls->component = component;
619 	return dtls;
620 }
621 
janus_dtls_srtp_handshake(janus_dtls_srtp * dtls)622 void janus_dtls_srtp_handshake(janus_dtls_srtp *dtls) {
623 	if(dtls == NULL || dtls->ssl == NULL)
624 		return;
625 	if(dtls->dtls_state == JANUS_DTLS_STATE_CREATED) {
626 		/* Starting the handshake now: enforce the role */
627 		dtls->dtls_started = janus_get_monotonic_time();
628 		if(dtls->dtls_role == JANUS_DTLS_ROLE_CLIENT) {
629 			SSL_set_connect_state(dtls->ssl);
630 		} else {
631 			SSL_set_accept_state(dtls->ssl);
632 		}
633 		dtls->dtls_state = JANUS_DTLS_STATE_TRYING;
634 	}
635 	SSL_do_handshake(dtls->ssl);
636 
637 	/* Notify event handlers */
638 	janus_dtls_notify_state_change(dtls);
639 }
640 
janus_dtls_srtp_create_sctp(janus_dtls_srtp * dtls)641 int janus_dtls_srtp_create_sctp(janus_dtls_srtp *dtls) {
642 #ifdef HAVE_SCTP
643 	if(dtls == NULL)
644 		return -1;
645 	janus_ice_component *component = (janus_ice_component *)dtls->component;
646 	if(component == NULL)
647 		return -2;
648 	janus_ice_stream *stream = component->stream;
649 	if(!stream)
650 		return -3;
651 	janus_ice_handle *handle = stream->handle;
652 	if(!handle || !handle->agent)
653 		return -4;
654 	if(janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_ALERT))
655 		return -5;
656 	dtls->sctp = janus_sctp_association_create(dtls, handle, 5000);
657 	if(dtls->sctp == NULL) {
658 		JANUS_LOG(LOG_ERR, "[%"SCNu64"] Error creating SCTP association...\n", handle->handle_id);
659 		return -6;
660 	}
661 	return 0;
662 #else
663 	/* Support for datachannels hasn't been built in */
664 	return -1;
665 #endif
666 }
667 
janus_dtls_srtp_incoming_msg(janus_dtls_srtp * dtls,char * buf,uint16_t len)668 void janus_dtls_srtp_incoming_msg(janus_dtls_srtp *dtls, char *buf, uint16_t len) {
669 	if(dtls == NULL) {
670 		JANUS_LOG(LOG_ERR, "No DTLS-SRTP stack, no incoming message...\n");
671 		return;
672 	}
673 	janus_ice_component *component = (janus_ice_component *)dtls->component;
674 	if(component == NULL) {
675 		JANUS_LOG(LOG_ERR, "No component, no DTLS...\n");
676 		return;
677 	}
678 	janus_ice_stream *stream = component->stream;
679 	if(!stream) {
680 		JANUS_LOG(LOG_ERR, "No stream, no DTLS...\n");
681 		return;
682 	}
683 	janus_ice_handle *handle = stream->handle;
684 	if(!handle || !handle->agent) {
685 		JANUS_LOG(LOG_ERR, "No handle/agent, no DTLS...\n");
686 		return;
687 	}
688 	if(janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_ALERT)) {
689 		JANUS_LOG(LOG_WARN, "[%"SCNu64"] Alert already triggered, clearing up...\n", handle->handle_id);
690 		return;
691 	}
692 	if(!dtls->ssl || !dtls->read_bio) {
693 		JANUS_LOG(LOG_ERR, "[%"SCNu64"] No DTLS stuff for component %d in stream %d??\n", handle->handle_id, component->component_id, stream->stream_id);
694 		return;
695 	}
696 	if(dtls->dtls_started == 0) {
697 		/* Handshake not started yet: maybe we're still waiting for the answer and the DTLS role? */
698 		return;
699 	}
700 	int written = BIO_write(dtls->read_bio, buf, len);
701 	if(written != len) {
702 		JANUS_LOG(LOG_WARN, "[%"SCNu64"]     Only written %d/%d of those bytes on the read BIO...\n", handle->handle_id, written, len);
703 	} else {
704 		JANUS_LOG(LOG_HUGE, "[%"SCNu64"]     Written %d bytes on the read BIO...\n", handle->handle_id, written);
705 	}
706 	/* Try to read data */
707 	char data[1500];	/* FIXME */
708 	memset(&data, 0, 1500);
709 	int read = SSL_read(dtls->ssl, &data, 1500);
710 	JANUS_LOG(LOG_HUGE, "[%"SCNu64"]     ... and read %d of them from SSL...\n", handle->handle_id, read);
711 	if(read < 0) {
712 		unsigned long err = SSL_get_error(dtls->ssl, read);
713 		if(err == SSL_ERROR_SSL) {
714 			/* Ops, something went wrong with the DTLS handshake */
715 			char error[200];
716 			ERR_error_string_n(ERR_get_error(), error, 200);
717 			JANUS_LOG(LOG_ERR, "[%"SCNu64"] Handshake error: %s\n", handle->handle_id, error);
718 			return;
719 		}
720 	}
721 	if(janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_STOP) || janus_is_stopping()) {
722 		/* DTLS alert triggered, we should end it here */
723 		JANUS_LOG(LOG_VERB, "[%"SCNu64"] Forced to stop it here...\n", handle->handle_id);
724 		return;
725 	}
726 	if(!SSL_is_init_finished(dtls->ssl)) {
727 		/* Nothing else to do for now */
728 		JANUS_LOG(LOG_HUGE, "[%"SCNu64"] Initialization not finished yet...\n", handle->handle_id);
729 		return;
730 	}
731 	if(dtls->ready) {
732 		/* There's data to be read? */
733 		JANUS_LOG(LOG_HUGE, "[%"SCNu64"] Any data available?\n", handle->handle_id);
734 #ifdef HAVE_SCTP
735 		if(dtls->sctp != NULL && read > 0) {
736 			JANUS_LOG(LOG_HUGE, "[%"SCNu64"] Sending data (%d bytes) to the SCTP stack...\n", handle->handle_id, read);
737 			janus_sctp_data_from_dtls(dtls->sctp, data, read);
738 		}
739 #else
740 		if(read > 0) {
741 			JANUS_LOG(LOG_WARN, "[%"SCNu64"] Data available but Data Channels support disabled...\n", handle->handle_id);
742 		}
743 #endif
744 	} else {
745 		JANUS_LOG(LOG_VERB, "[%"SCNu64"] DTLS established, yay!\n", handle->handle_id);
746 		/* Check the remote fingerprint */
747 		X509 *rcert = SSL_get_peer_certificate(dtls->ssl);
748 		if(!rcert) {
749 			JANUS_LOG(LOG_ERR, "[%"SCNu64"] No remote certificate?? (%s)\n",
750 				handle->handle_id, ERR_reason_error_string(ERR_get_error()));
751 		} else {
752 			unsigned int rsize;
753 			unsigned char rfingerprint[EVP_MAX_MD_SIZE];
754 			char remote_fingerprint[160];
755 			char *rfp = (char *)&remote_fingerprint;
756 			if(stream->remote_hashing && !strcasecmp(stream->remote_hashing, "sha-1")) {
757 				JANUS_LOG(LOG_VERB, "[%"SCNu64"] Computing sha-1 fingerprint of remote certificate...\n", handle->handle_id);
758 				X509_digest(rcert, EVP_sha1(), (unsigned char *)rfingerprint, &rsize);
759 			} else {
760 				JANUS_LOG(LOG_VERB, "[%"SCNu64"] Computing sha-256 fingerprint of remote certificate...\n", handle->handle_id);
761 				X509_digest(rcert, EVP_sha256(), (unsigned char *)rfingerprint, &rsize);
762 			}
763 			X509_free(rcert);
764 			rcert = NULL;
765 			unsigned int i = 0;
766 			for(i = 0; i < rsize; i++) {
767 				g_snprintf(rfp, 4, "%.2X:", rfingerprint[i]);
768 				rfp += 3;
769 			}
770 			*(rfp-1) = 0;
771 			JANUS_LOG(LOG_VERB, "[%"SCNu64"] Remote fingerprint (%s) of the client is %s\n",
772 				handle->handle_id, stream->remote_hashing ? stream->remote_hashing : "sha-256", remote_fingerprint);
773 			if(!strcasecmp(remote_fingerprint, stream->remote_fingerprint ? stream->remote_fingerprint : "(none)")) {
774 				JANUS_LOG(LOG_VERB, "[%"SCNu64"]  Fingerprint is a match!\n", handle->handle_id);
775 				dtls->dtls_state = JANUS_DTLS_STATE_CONNECTED;
776 				dtls->dtls_connected = janus_get_monotonic_time();
777 				/* Notify event handlers */
778 				janus_dtls_notify_state_change(dtls);
779 			} else {
780 				/* FIXME NOT a match! MITM? */
781 				JANUS_LOG(LOG_ERR, "[%"SCNu64"]  Fingerprint is NOT a match! got %s, expected %s\n", handle->handle_id, remote_fingerprint, stream->remote_fingerprint);
782 				dtls->dtls_state = JANUS_DTLS_STATE_FAILED;
783 				/* Notify event handlers */
784 				janus_dtls_notify_state_change(dtls);
785 				goto done;
786 			}
787 			if(dtls->dtls_state == JANUS_DTLS_STATE_CONNECTED) {
788 				/* Which SRTP profile is being negotiated? */
789 				const SRTP_PROTECTION_PROFILE *srtp_profile = SSL_get_selected_srtp_profile(dtls->ssl);
790 				if(srtp_profile == NULL) {
791 					/* Should never happen, but just in case... */
792 					JANUS_LOG(LOG_ERR, "[%"SCNu64"] No SRTP profile selected...\n", handle->handle_id);
793 					dtls->dtls_state = JANUS_DTLS_STATE_FAILED;
794 					/* Notify event handlers */
795 					janus_dtls_notify_state_change(dtls);
796 					goto done;
797 				}
798 				JANUS_LOG(LOG_VERB, "[%"SCNu64"] %s\n", handle->handle_id, srtp_profile->name);
799 				int key_length = 0, salt_length = 0, master_length = 0;
800 				switch(srtp_profile->id) {
801 					case SRTP_AES128_CM_SHA1_80:
802 					case SRTP_AES128_CM_SHA1_32:
803 						key_length = SRTP_MASTER_KEY_LENGTH;
804 						salt_length = SRTP_MASTER_SALT_LENGTH;
805 						master_length = SRTP_MASTER_LENGTH;
806 						break;
807 #ifdef HAVE_SRTP_AESGCM
808 					case SRTP_AEAD_AES_256_GCM:
809 						key_length = SRTP_AESGCM256_MASTER_KEY_LENGTH;
810 						salt_length = SRTP_AESGCM256_MASTER_SALT_LENGTH;
811 						master_length = SRTP_AESGCM256_MASTER_LENGTH;
812 						break;
813 					case SRTP_AEAD_AES_128_GCM:
814 						key_length = SRTP_AESGCM128_MASTER_KEY_LENGTH;
815 						salt_length = SRTP_AESGCM128_MASTER_SALT_LENGTH;
816 						master_length = SRTP_AESGCM128_MASTER_LENGTH;
817 						break;
818 #endif
819 					default:
820 						/* Will never happen? */
821 						JANUS_LOG(LOG_WARN, "[%"SCNu64"] Unsupported SRTP profile %lu\n", handle->handle_id, srtp_profile->id);
822 						break;
823 				}
824 				JANUS_LOG(LOG_VERB, "[%"SCNu64"] Key/Salt/Master: %d/%d/%d\n",
825 					handle->handle_id, master_length, key_length, salt_length);
826 				/* Complete with SRTP setup */
827 				unsigned char material[master_length*2];
828 				unsigned char *local_key, *local_salt, *remote_key, *remote_salt;
829 				/* Export keying material for SRTP */
830 				if(!SSL_export_keying_material(dtls->ssl, material, master_length*2, "EXTRACTOR-dtls_srtp", 19, NULL, 0, 0)) {
831 					/* Oops... */
832 					JANUS_LOG(LOG_ERR, "[%"SCNu64"] Oops, couldn't extract SRTP keying material for component %d in stream %d?? (%s)\n",
833 						handle->handle_id, component->component_id, stream->stream_id, ERR_reason_error_string(ERR_get_error()));
834 					goto done;
835 				}
836 				/* Key derivation (http://tools.ietf.org/html/rfc5764#section-4.2) */
837 				if(dtls->dtls_role == JANUS_DTLS_ROLE_CLIENT) {
838 					local_key = material;
839 					remote_key = local_key + key_length;
840 					local_salt = remote_key + key_length;
841 					remote_salt = local_salt + salt_length;
842 				} else {
843 					remote_key = material;
844 					local_key = remote_key + key_length;
845 					remote_salt = local_key + key_length;
846 					local_salt = remote_salt + salt_length;
847 				}
848 				/* Build master keys and set SRTP policies */
849 					/* Remote (inbound) */
850 				switch(srtp_profile->id) {
851 					case SRTP_AES128_CM_SHA1_80:
852 						srtp_crypto_policy_set_aes_cm_128_hmac_sha1_80(&(dtls->remote_policy.rtp));
853 						srtp_crypto_policy_set_aes_cm_128_hmac_sha1_80(&(dtls->remote_policy.rtcp));
854 						break;
855 					case SRTP_AES128_CM_SHA1_32:
856 						srtp_crypto_policy_set_aes_cm_128_hmac_sha1_32(&(dtls->remote_policy.rtp));
857 						srtp_crypto_policy_set_aes_cm_128_hmac_sha1_80(&(dtls->remote_policy.rtcp));
858 						break;
859 #ifdef HAVE_SRTP_AESGCM
860 					case SRTP_AEAD_AES_256_GCM:
861 						srtp_crypto_policy_set_aes_gcm_256_16_auth(&(dtls->remote_policy.rtp));
862 						srtp_crypto_policy_set_aes_gcm_256_16_auth(&(dtls->remote_policy.rtcp));
863 						break;
864 					case SRTP_AEAD_AES_128_GCM:
865 						srtp_crypto_policy_set_aes_gcm_128_16_auth(&(dtls->remote_policy.rtp));
866 						srtp_crypto_policy_set_aes_gcm_128_16_auth(&(dtls->remote_policy.rtcp));
867 						break;
868 #endif
869 					default:
870 						/* Will never happen? */
871 						JANUS_LOG(LOG_WARN, "[%"SCNu64"] Unsupported SRTP profile %s\n", handle->handle_id, srtp_profile->name);
872 						break;
873 				}
874 				dtls->remote_policy.ssrc.type = ssrc_any_inbound;
875 				unsigned char remote_policy_key[master_length];
876 				dtls->remote_policy.key = (unsigned char *)&remote_policy_key;
877 				memcpy(dtls->remote_policy.key, remote_key, key_length);
878 				memcpy(dtls->remote_policy.key + key_length, remote_salt, salt_length);
879 #if HAS_DTLS_WINDOW_SIZE
880 				dtls->remote_policy.window_size = 128;
881 				dtls->remote_policy.allow_repeat_tx = 0;
882 #endif
883 				dtls->remote_policy.next = NULL;
884 					/* Local (outbound) */
885 				switch(srtp_profile->id) {
886 					case SRTP_AES128_CM_SHA1_80:
887 						srtp_crypto_policy_set_aes_cm_128_hmac_sha1_80(&(dtls->local_policy.rtp));
888 						srtp_crypto_policy_set_aes_cm_128_hmac_sha1_80(&(dtls->local_policy.rtcp));
889 						break;
890 					case SRTP_AES128_CM_SHA1_32:
891 						srtp_crypto_policy_set_aes_cm_128_hmac_sha1_32(&(dtls->local_policy.rtp));
892 						srtp_crypto_policy_set_aes_cm_128_hmac_sha1_80(&(dtls->local_policy.rtcp));
893 						break;
894 #ifdef HAVE_SRTP_AESGCM
895 					case SRTP_AEAD_AES_256_GCM:
896 						srtp_crypto_policy_set_aes_gcm_256_16_auth(&(dtls->local_policy.rtp));
897 						srtp_crypto_policy_set_aes_gcm_256_16_auth(&(dtls->local_policy.rtcp));
898 						break;
899 					case SRTP_AEAD_AES_128_GCM:
900 						srtp_crypto_policy_set_aes_gcm_128_16_auth(&(dtls->local_policy.rtp));
901 						srtp_crypto_policy_set_aes_gcm_128_16_auth(&(dtls->local_policy.rtcp));
902 						break;
903 #endif
904 					default:
905 						/* Will never happen? */
906 						JANUS_LOG(LOG_WARN, "[%"SCNu64"] Unsupported SRTP profile %s\n", handle->handle_id, srtp_profile->name);
907 						break;
908 				}
909 				dtls->local_policy.ssrc.type = ssrc_any_outbound;
910 				unsigned char local_policy_key[master_length];
911 				dtls->local_policy.key = (unsigned char *)&local_policy_key;
912 				memcpy(dtls->local_policy.key, local_key, key_length);
913 				memcpy(dtls->local_policy.key + key_length, local_salt, salt_length);
914 #if HAS_DTLS_WINDOW_SIZE
915 				dtls->local_policy.window_size = 128;
916 				dtls->local_policy.allow_repeat_tx = 0;
917 #endif
918 				dtls->local_policy.next = NULL;
919 				/* Create SRTP sessions */
920 				srtp_err_status_t res = srtp_create(&(dtls->srtp_in), &(dtls->remote_policy));
921 				if(res != srtp_err_status_ok) {
922 					/* Something went wrong... */
923 					JANUS_LOG(LOG_ERR, "[%"SCNu64"] Oops, error creating inbound SRTP session for component %d in stream %d??\n", handle->handle_id, component->component_id, stream->stream_id);
924 					JANUS_LOG(LOG_ERR, "[%"SCNu64"]  -- %d (%s)\n", handle->handle_id, res, janus_srtp_error_str(res));
925 					goto done;
926 				}
927 				JANUS_LOG(LOG_VERB, "[%"SCNu64"] Created inbound SRTP session for component %d in stream %d\n", handle->handle_id, component->component_id, stream->stream_id);
928 				res = srtp_create(&(dtls->srtp_out), &(dtls->local_policy));
929 				if(res != srtp_err_status_ok) {
930 					/* Something went wrong... */
931 					JANUS_LOG(LOG_ERR, "[%"SCNu64"] Oops, error creating outbound SRTP session for component %d in stream %d??\n", handle->handle_id, component->component_id, stream->stream_id);
932 					JANUS_LOG(LOG_ERR, "[%"SCNu64"]  -- %d (%s)\n", handle->handle_id, res, janus_srtp_error_str(res));
933 					goto done;
934 				}
935 				dtls->srtp_profile = srtp_profile->id;
936 				dtls->srtp_valid = 1;
937 				JANUS_LOG(LOG_VERB, "[%"SCNu64"] Created outbound SRTP session for component %d in stream %d\n", handle->handle_id, component->component_id, stream->stream_id);
938 #ifdef HAVE_SCTP
939 				if(janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_DATA_CHANNELS)) {
940 					/* Create SCTP association as well */
941 					janus_dtls_srtp_create_sctp(dtls);
942 				}
943 #endif
944 				dtls->ready = 1;
945 			}
946 done:
947 			if(!janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_ALERT) && dtls->srtp_valid) {
948 				/* Handshake successfully completed */
949 				janus_ice_dtls_handshake_done(handle, component);
950 			} else {
951 				/* Something went wrong in either DTLS or SRTP... tell the plugin about it */
952 				janus_dtls_callback(dtls->ssl, SSL_CB_ALERT, 0);
953 				janus_flags_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_CLEANING);
954 			}
955 		}
956 	}
957 }
958 
janus_dtls_srtp_send_alert(janus_dtls_srtp * dtls)959 void janus_dtls_srtp_send_alert(janus_dtls_srtp *dtls) {
960 	if(!dtls)
961 		return;
962 	/* Send alert */
963 	janus_refcount_increase(&dtls->ref);
964 	if(dtls != NULL && dtls->ssl != NULL) {
965 		SSL_shutdown(dtls->ssl);
966 	}
967 	janus_refcount_decrease(&dtls->ref);
968 }
969 
janus_dtls_srtp_destroy(janus_dtls_srtp * dtls)970 void janus_dtls_srtp_destroy(janus_dtls_srtp *dtls) {
971 	if(!dtls || !g_atomic_int_compare_and_exchange(&dtls->destroyed, 0, 1))
972 		return;
973 	dtls->ready = 0;
974 	dtls->retransmissions = 0;
975 #ifdef HAVE_SCTP
976 	/* Destroy the SCTP association if this is a DataChannel */
977 	if(dtls->sctp != NULL) {
978 		janus_sctp_association_destroy(dtls->sctp);
979 		dtls->sctp = NULL;
980 	}
981 #endif
982 	janus_refcount_decrease(&dtls->ref);
983 }
984 
985 /* DTLS alert callback */
janus_dtls_callback(const SSL * ssl,int where,int ret)986 void janus_dtls_callback(const SSL *ssl, int where, int ret) {
987 	/* We only care about alerts */
988 	if(!(where & SSL_CB_ALERT)) {
989 		return;
990 	}
991 	janus_dtls_srtp *dtls = SSL_get_ex_data(ssl, 0);
992 	if(!dtls) {
993 		JANUS_LOG(LOG_ERR, "No DTLS session related to this alert...\n");
994 		return;
995 	}
996 	janus_ice_component *component = dtls->component;
997 	if(component == NULL) {
998 		JANUS_LOG(LOG_ERR, "No ICE component related to this alert...\n");
999 		return;
1000 	}
1001 	janus_ice_stream *stream = component->stream;
1002 	if(!stream) {
1003 		JANUS_LOG(LOG_ERR, "No ICE stream related to this alert...\n");
1004 		return;
1005 	}
1006 	janus_ice_handle *handle = stream->handle;
1007 	if(!handle) {
1008 		JANUS_LOG(LOG_ERR, "No ICE handle related to this alert...\n");
1009 		return;
1010 	}
1011 	JANUS_LOG(LOG_VERB, "[%"SCNu64"] DTLS alert triggered on stream %u (component %u), closing...\n", handle->handle_id, stream->stream_id, component->component_id);
1012 	janus_ice_webrtc_hangup(handle, "DTLS alert");
1013 }
1014 
1015 /* DTLS certificate verification callback */
janus_dtls_verify_callback(int preverify_ok,X509_STORE_CTX * ctx)1016 int janus_dtls_verify_callback(int preverify_ok, X509_STORE_CTX *ctx) {
1017 	/* We just use the verify_callback to request a certificate from the client */
1018 	int err = X509_STORE_CTX_get_error(ctx);
1019 	if(err == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT || err == X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN) {
1020 		/* Self signed certificate: by default we always accept it */
1021 		if(!dtls_selfsigned_certs_ok) {
1022 			/* ... unless we're enforcing validation */
1023 			return 0;
1024 		}
1025 	}
1026 	/* We always reject expired certificates, even when self-signed */
1027 	if(err == X509_V_ERR_CERT_HAS_EXPIRED)
1028 		return 0;
1029 	/* Return a success if we're ok with self-signed, the result of the validation otherwise */
1030 	return dtls_selfsigned_certs_ok ? 1 : (err == X509_V_OK);
1031 }
1032 
1033 #ifdef HAVE_SCTP
janus_dtls_sctp_data_ready(janus_dtls_srtp * dtls)1034 void janus_dtls_sctp_data_ready(janus_dtls_srtp *dtls) {
1035 	if(dtls == NULL)
1036 		return;
1037 	janus_ice_component *component = (janus_ice_component *)dtls->component;
1038 	if(component == NULL) {
1039 		JANUS_LOG(LOG_ERR, "No component...\n");
1040 		return;
1041 	}
1042 	janus_ice_stream *stream = component->stream;
1043 	if(!stream) {
1044 		JANUS_LOG(LOG_ERR, "No stream...\n");
1045 		return;
1046 	}
1047 	janus_ice_handle *handle = stream->handle;
1048 	if(!handle || !handle->agent || !dtls->write_bio) {
1049 		JANUS_LOG(LOG_ERR, "No handle...\n");
1050 		return;
1051 	}
1052 	janus_ice_notify_data_ready(handle);
1053 }
1054 
janus_dtls_wrap_sctp_data(janus_dtls_srtp * dtls,char * label,char * protocol,gboolean textdata,char * buf,int len)1055 void janus_dtls_wrap_sctp_data(janus_dtls_srtp *dtls, char *label, char *protocol, gboolean textdata, char *buf, int len) {
1056 	if(dtls == NULL || !dtls->ready || dtls->sctp == NULL || buf == NULL || len < 1)
1057 		return;
1058 	janus_refcount_increase(&dtls->sctp->ref);
1059 	janus_sctp_send_data(dtls->sctp, label, protocol, textdata, buf, len);
1060 	janus_refcount_decrease(&dtls->sctp->ref);
1061 }
1062 
janus_dtls_send_sctp_data(janus_dtls_srtp * dtls,char * buf,int len)1063 int janus_dtls_send_sctp_data(janus_dtls_srtp *dtls, char *buf, int len) {
1064 	if(dtls == NULL || !dtls->ready || buf == NULL || len < 1)
1065 		return -1;
1066 	int res = SSL_write(dtls->ssl, buf, len);
1067 	if(res <= 0) {
1068 		unsigned long err = SSL_get_error(dtls->ssl, res);
1069 		JANUS_LOG(LOG_ERR, "Error sending data: %s\n", ERR_reason_error_string(err));
1070 	}
1071 	return res;
1072 }
1073 
janus_dtls_notify_sctp_data(janus_dtls_srtp * dtls,char * label,char * protocol,gboolean textdata,char * buf,int len)1074 void janus_dtls_notify_sctp_data(janus_dtls_srtp *dtls, char *label, char *protocol, gboolean textdata, char *buf, int len) {
1075 	if(dtls == NULL || buf == NULL || len < 1)
1076 		return;
1077 	janus_ice_component *component = (janus_ice_component *)dtls->component;
1078 	if(component == NULL) {
1079 		JANUS_LOG(LOG_ERR, "No component...\n");
1080 		return;
1081 	}
1082 	janus_ice_stream *stream = component->stream;
1083 	if(!stream) {
1084 		JANUS_LOG(LOG_ERR, "No stream...\n");
1085 		return;
1086 	}
1087 	janus_ice_handle *handle = stream->handle;
1088 	if(!handle || !handle->agent || !dtls->write_bio) {
1089 		JANUS_LOG(LOG_ERR, "No handle...\n");
1090 		return;
1091 	}
1092 	janus_ice_incoming_data(handle, label, protocol, textdata, buf, len);
1093 }
1094 #endif
1095 
janus_dtls_retry(gpointer stack)1096 gboolean janus_dtls_retry(gpointer stack) {
1097 	janus_dtls_srtp *dtls = (janus_dtls_srtp *)stack;
1098 	if(dtls == NULL)
1099 		return FALSE;
1100 	janus_ice_component *component = (janus_ice_component *)dtls->component;
1101 	if(component == NULL)
1102 		return FALSE;
1103 	janus_ice_stream *stream = component->stream;
1104 	if(!stream)
1105 		goto stoptimer;
1106 	janus_ice_handle *handle = stream->handle;
1107 	if(!handle)
1108 		goto stoptimer;
1109 	if(janus_flags_is_set(&handle->webrtc_flags, JANUS_ICE_HANDLE_WEBRTC_STOP))
1110 		goto stoptimer;
1111 	if(dtls->dtls_state == JANUS_DTLS_STATE_CONNECTED) {
1112 		JANUS_LOG(LOG_VERB, "[%"SCNu64"] DTLS already set up, disabling retransmission timer!\n", handle->handle_id);
1113 		goto stoptimer;
1114 	}
1115 	if(janus_get_monotonic_time() - dtls->dtls_started >= 20*G_USEC_PER_SEC) {
1116 		/* FIXME Should we really give up after 20 seconds waiting for DTLS? */
1117 		JANUS_LOG(LOG_ERR, "[%"SCNu64"] DTLS taking too much time for component %d in stream %d...\n",
1118 			handle->handle_id, component->component_id, stream->stream_id);
1119 		janus_ice_webrtc_hangup(handle, "DTLS timeout");
1120 		goto stoptimer;
1121 	}
1122 	struct timeval timeout = {0};
1123 	if(DTLSv1_get_timeout(dtls->ssl, &timeout) == 0) {
1124 		/* failed to get timeout. try again on next iter */
1125 		return TRUE;
1126 	}
1127 	guint64 timeout_value = timeout.tv_sec*1000 + timeout.tv_usec/1000;
1128 	JANUS_LOG(LOG_HUGE, "[%"SCNu64"] DTLSv1_get_timeout: %"SCNu64"\n", handle->handle_id, timeout_value);
1129 	if(timeout_value == 0) {
1130 		dtls->retransmissions++;
1131 		JANUS_LOG(LOG_VERB, "[%"SCNu64"] DTLS timeout on component %d of stream %d, retransmitting\n", handle->handle_id, component->component_id, stream->stream_id);
1132 		/* Notify event handlers */
1133 		janus_dtls_notify_state_change(dtls);
1134 		/* Retransmit the packet */
1135 		DTLSv1_handle_timeout(dtls->ssl);
1136 	}
1137 	return TRUE;
1138 
1139 stoptimer:
1140 	if(component->dtlsrt_source != NULL) {
1141 		g_source_destroy(component->dtlsrt_source);
1142 		g_source_unref(component->dtlsrt_source);
1143 		component->dtlsrt_source = NULL;
1144 	}
1145 	return FALSE;
1146 }
1147