1 /* $Id$ */
2 /*
3  * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
4  * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19  */
20 
21 #include <pjmedia/transport_srtp.h>
22 #include <pjmedia/endpoint.h>
23 #include <pjmedia/rtp.h>
24 #include <pjlib-util/base64.h>
25 #include <pj/array.h>
26 #include <pj/assert.h>
27 #include <pj/ctype.h>
28 #include <pj/lock.h>
29 #include <pj/log.h>
30 #include <pj/os.h>
31 #include <pj/pool.h>
32 
33 #if defined(PJMEDIA_HAS_SRTP) && (PJMEDIA_HAS_SRTP != 0)
34 
35 #if defined(PJ_HAS_SSL_SOCK) && PJ_HAS_SSL_SOCK != 0 && \
36     (PJ_SSL_SOCK_IMP == PJ_SSL_SOCK_IMP_OPENSSL)
37 #  include <openssl/rand.h>
38 #  include <openssl/opensslv.h>
39 
40 /* Suppress compile warning of OpenSSL deprecation (OpenSSL is deprecated
41  * since MacOSX 10.7).
42  */
43 #if defined(PJ_DARWINOS) && PJ_DARWINOS==1
44 #  pragma GCC diagnostic ignored "-Wdeprecated-declarations"
45 #endif
46 
47 #endif
48 
49 #if defined(PJMEDIA_EXTERNAL_SRTP)
50 
51 #if (PJMEDIA_EXTERNAL_SRTP == 1) 	/* External SRTP 1.x */
52 #  include <srtp/srtp.h>
53 #  include <srtp/crypto_kernel.h>
54 #define srtp_crypto_policy_t 		crypto_policy_t
55 #define srtp_cipher_type_id_t 		cipher_type_id_t
56 #define srtp_cipher_type_t		cipher_type_t
57 #define srtp_auth_type_id_t 		auth_type_id_t
58 #define srtp_sec_serv_t			sec_serv_t
59 #define srtp_err_status_t		err_status_t
60 #define srtp_err_status_ok		err_status_ok
61 #define srtp_err_status_replay_old	err_status_replay_old
62 #define srtp_err_status_replay_fail	err_status_replay_fail
63 #define srtp_crypto_policy_set_aes_cm_256_hmac_sha1_32 \
64 	     crypto_policy_set_aes_cm_256_hmac_sha1_32
65 #define srtp_crypto_policy_set_aes_cm_256_hmac_sha1_80 \
66 	     crypto_policy_set_aes_cm_256_hmac_sha1_80
67 #define SRTP_NULL_CIPHER		NULL_CIPHER
68 #define SRTP_NULL_AUTH			NULL_AUTH
69 #define SRTP_AES_ICM_128		AES_ICM
70 #define SRTP_AES_ICM_192		AES_ICM
71 #define SRTP_AES_ICM_256		AES_ICM
72 #define SRTP_AES_GCM_128		AES_128_GCM
73 #define SRTP_AES_GCM_256		AES_256_GCM
74 #define SRTP_HMAC_SHA1			HMAC_SHA1
75 #define srtp_aes_gcm_256_openssl        aes_gcm_256_openssl
76 #define srtp_aes_gcm_128_openssl        aes_gcm_128_openssl
77 
78 #else				 	/* External SRTP 2.x */
79 #  include <srtp2/srtp.h>
80 #  include <srtp2/cipher.h>
81 
82 /* In libsrtp 2.0.0, the macro SRTP_AES_ICM_128 is not available.
83  * Instead it was named with ICM at the end: SRTP_AES_128_ICM.
84  */
85 #  ifdef SRTP_AES_128_ICM
86 #    define SRTP_AES_ICM_128		SRTP_AES_128_ICM
87 #    define SRTP_AES_ICM_192		SRTP_AES_192_ICM
88 #    define SRTP_AES_ICM_256		SRTP_AES_256_ICM
89 #    define SRTP_AES_GCM_128		SRTP_AES_128_GCM
90 #    define SRTP_AES_GCM_256		SRTP_AES_256_GCM
91 #  endif
92 
93 #endif
94 
95 #else					/* Bundled SRTP */
96 #  include <srtp.h>
97 #  include <crypto_kernel.h>
98 #endif
99 
100 #define THIS_FILE   "transport_srtp.c"
101 
102 /* Maximum size of outgoing packet */
103 #define MAX_RTP_BUFFER_LEN	    PJMEDIA_MAX_MTU
104 #define MAX_RTCP_BUFFER_LEN	    PJMEDIA_MAX_MTU
105 
106 /* Maximum SRTP crypto key length */
107 #define MAX_KEY_LEN		    128
108 
109 /* Initial value of probation counter. When probation counter > 0,
110  * it means SRTP is in probation state, and it may restart when
111  * srtp_unprotect() returns err_status_replay_*
112  */
113 #define PROBATION_CNT_INIT	    100
114 
115 #define DEACTIVATE_MEDIA(pool, m)   pjmedia_sdp_media_deactivate(pool, m)
116 
117 #ifdef SRTP_MAX_TRAILER_LEN
118 #   define MAX_TRAILER_LEN SRTP_MAX_TRAILER_LEN
119 #else
120 #   define MAX_TRAILER_LEN 10
121 #endif
122 
123 /* Maximum number of SRTP keying method */
124 #define MAX_KEYING		    2
125 
126 static const pj_str_t ID_RTP_AVP  = { "RTP/AVP", 7 };
127 static const pj_str_t ID_RTP_SAVP = { "RTP/SAVP", 8 };
128 // static const pj_str_t ID_INACTIVE = { "inactive", 8 };
129 static const pj_str_t ID_CRYPTO   = { "crypto", 6 };
130 
131 typedef void (*crypto_method_t)(srtp_crypto_policy_t *policy);
132 
133 typedef struct crypto_suite
134 {
135     char		*name;
136     srtp_cipher_type_id_t cipher_type;
137     unsigned		 cipher_key_len;    /* key + salt length    */
138     unsigned		 cipher_salt_len;   /* salt only length	    */
139     srtp_auth_type_id_t	 auth_type;
140     unsigned		 auth_key_len;
141     unsigned		 srtp_auth_tag_len;
142     unsigned		 srtcp_auth_tag_len;
143     srtp_sec_serv_t	 service;
144     /* This is an attempt to validate crypto support by libsrtp, i.e: it should
145      * raise linking error if the libsrtp does not support the crypto.
146      */
147     srtp_cipher_type_t  *ext_cipher_type;
148     crypto_method_t      ext_crypto_method;
149 } crypto_suite;
150 
151 extern srtp_cipher_type_t srtp_aes_gcm_256_openssl;
152 extern srtp_cipher_type_t srtp_aes_gcm_128_openssl;
153 extern srtp_cipher_type_t srtp_aes_icm_192;
154 
155 /* https://www.iana.org/assignments/sdp-security-descriptions/sdp-security-descriptions.xhtml */
156 static crypto_suite crypto_suites[] = {
157     /* plain RTP/RTCP (no cipher & no auth) */
158     {"NULL", SRTP_NULL_CIPHER, 0, SRTP_NULL_AUTH, 0, 0, 0, sec_serv_none},
159 
160 #if defined(PJMEDIA_SRTP_HAS_AES_GCM_256)&&(PJMEDIA_SRTP_HAS_AES_GCM_256!=0)
161 
162     /* cipher AES_GCM, NULL auth, auth tag len = 16 octets */
163     {"AEAD_AES_256_GCM", SRTP_AES_GCM_256, 44, 12,
164 	SRTP_NULL_AUTH, 0, 16, 16, sec_serv_conf_and_auth,
165 	&srtp_aes_gcm_256_openssl},
166 
167     /* cipher AES_GCM, NULL auth, auth tag len = 8 octets */
168     {"AEAD_AES_256_GCM_8", SRTP_AES_GCM_256, 44, 12,
169 	SRTP_NULL_AUTH, 0, 8, 8, sec_serv_conf_and_auth,
170 	&srtp_aes_gcm_256_openssl},
171 #endif
172 #if defined(PJMEDIA_SRTP_HAS_AES_CM_256)&&(PJMEDIA_SRTP_HAS_AES_CM_256!=0)
173 
174     /* cipher AES_CM_256, auth SRTP_HMAC_SHA1, auth tag len = 10 octets */
175     {"AES_256_CM_HMAC_SHA1_80", SRTP_AES_ICM_256, 46, 14,
176 	SRTP_HMAC_SHA1, 20, 10, 10, sec_serv_conf_and_auth,
177 	NULL, &srtp_crypto_policy_set_aes_cm_256_hmac_sha1_80},
178 
179     /* cipher AES_CM_256, auth SRTP_HMAC_SHA1, auth tag len = 10 octets */
180     {"AES_256_CM_HMAC_SHA1_32", SRTP_AES_ICM_256, 46, 14,
181 	SRTP_HMAC_SHA1, 20, 4, 10, sec_serv_conf_and_auth,
182 	NULL, &srtp_crypto_policy_set_aes_cm_256_hmac_sha1_32},
183 #endif
184 #if defined(PJMEDIA_SRTP_HAS_AES_CM_192)&&(PJMEDIA_SRTP_HAS_AES_CM_192!=0)
185 
186     /* cipher AES_CM_192, auth SRTP_HMAC_SHA1, auth tag len = 10 octets */
187     {"AES_192_CM_HMAC_SHA1_80", SRTP_AES_ICM_192, 38, 14,
188 	SRTP_HMAC_SHA1, 20, 10, 10, sec_serv_conf_and_auth,
189 	&srtp_aes_icm_192},
190 
191     /* cipher AES_CM_192, auth SRTP_HMAC_SHA1, auth tag len = 4 octets */
192     {"AES_192_CM_HMAC_SHA1_32", SRTP_AES_ICM_192, 38, 14,
193 	SRTP_HMAC_SHA1, 20, 4, 10, sec_serv_conf_and_auth,
194 	&srtp_aes_icm_192},
195 #endif
196 #if defined(PJMEDIA_SRTP_HAS_AES_GCM_128)&&(PJMEDIA_SRTP_HAS_AES_GCM_128!=0)
197 
198     /* cipher AES_GCM, NULL auth, auth tag len = 16 octets */
199     {"AEAD_AES_128_GCM", SRTP_AES_GCM_128, 28, 12,
200 	SRTP_NULL_AUTH, 0, 16, 16, sec_serv_conf_and_auth,
201 	&srtp_aes_gcm_128_openssl},
202 
203     /* cipher AES_GCM, NULL auth, auth tag len = 8 octets */
204     {"AEAD_AES_128_GCM_8", SRTP_AES_GCM_128, 28, 12,
205 	SRTP_NULL_AUTH, 0, 8, 8, sec_serv_conf_and_auth,
206 	&srtp_aes_gcm_128_openssl},
207 #endif
208 #if defined(PJMEDIA_SRTP_HAS_AES_CM_128)&&(PJMEDIA_SRTP_HAS_AES_CM_128!=0)
209 
210     /* cipher AES_CM_128, auth SRTP_HMAC_SHA1, auth tag len = 10 octets */
211     {"AES_CM_128_HMAC_SHA1_80", SRTP_AES_ICM_128, 30, 14,
212 	SRTP_HMAC_SHA1, 20, 10, 10, sec_serv_conf_and_auth},
213 
214     /* cipher AES_CM_128, auth SRTP_HMAC_SHA1, auth tag len = 4 octets */
215     {"AES_CM_128_HMAC_SHA1_32", SRTP_AES_ICM_128, 30, 14,
216 	SRTP_HMAC_SHA1, 20, 4, 10, sec_serv_conf_and_auth},
217 #endif
218 
219     /*
220      * F8_128_HMAC_SHA1_8 not supported by libsrtp?
221      * {"F8_128_HMAC_SHA1_8", NULL_CIPHER, 0, 0, NULL_AUTH, 0, 0, 0,
222      *	sec_serv_none}
223      */
224 };
225 
226 
227 /* SRTP transport */
228 typedef struct transport_srtp
229 {
230     pjmedia_transport	 base;		    /**< Base transport interface.  */
231     pj_pool_t		*pool;		    /**< Pool for transport SRTP.   */
232     pj_lock_t		*mutex;		    /**< Mutex for libsrtp contexts.*/
233     char		 rtp_tx_buffer[MAX_RTP_BUFFER_LEN];
234     char		 rtcp_tx_buffer[MAX_RTCP_BUFFER_LEN];
235     pjmedia_srtp_setting setting;
236     unsigned		 media_option;
237     pj_bool_t		 use_rtcp_mux;	    /**< Use RTP& RTCP multiplexing?*/
238 
239     /* SRTP policy */
240     pj_bool_t		 session_inited;
241     pj_bool_t		 offerer_side;
242     pj_bool_t		 bypass_srtp;
243     char		 tx_key[MAX_KEY_LEN];
244     char		 rx_key[MAX_KEY_LEN];
245     pjmedia_srtp_crypto  tx_policy;
246     pjmedia_srtp_crypto  rx_policy;
247 
248     /* Temporary policy for negotiation */
249     pjmedia_srtp_crypto  tx_policy_neg;
250     pjmedia_srtp_crypto  rx_policy_neg;
251 
252     /* libSRTP contexts */
253     srtp_t		 srtp_tx_ctx;
254     srtp_t		 srtp_rx_ctx;
255 
256     /* Stream information */
257     void		*user_data;
258     void		(*rtp_cb)( void *user_data,
259 				   void *pkt,
260 				   pj_ssize_t size);
261     void  		(*rtp_cb2)(pjmedia_tp_cb_param*);
262     void		(*rtcp_cb)(void *user_data,
263 				   void *pkt,
264 				   pj_ssize_t size);
265 
266     /* Transport information */
267     pjmedia_transport	*member_tp; /**< Underlying transport.       */
268     pj_bool_t		 member_tp_attached;
269     pj_bool_t		 started;
270 
271     /* SRTP usage policy of peer. This field is updated when media is starting.
272      * This is useful when SRTP is in optional mode and peer is using mandatory
273      * mode, so when local is about to reinvite/update, it should offer
274      * RTP/SAVP instead of offering RTP/AVP.
275      */
276     pjmedia_srtp_use	 peer_use;
277 
278     /* When probation counter > 0, it means SRTP is in probation state,
279      * and it may restart when srtp_unprotect() returns err_status_replay_*
280      */
281     unsigned		 probation_cnt;
282 
283     /* SRTP keying methods. The keying is implemented using media transport
284      * abstraction, so it will also be invoked when the SRTP media transport
285      * operation is invoked.
286      *
287      * As there can be multiple keying methods enabled (currently only SDES &
288      * DTLS-SRTP), each keying method will be given the chance to respond to
289      * remote SDP. If any keying operation returns non-success, it will be
290      * removed from the session. And once SRTP key is obtained via a keying
291      * method, any other keying methods will be stopped and destroyed.
292      */
293     unsigned		 all_keying_cnt;
294     pjmedia_transport	*all_keying[MAX_KEYING];
295 
296     /* Current active SRTP keying methods. */
297     unsigned		 keying_cnt;
298     pjmedia_transport	*keying[MAX_KEYING];
299 
300     /* If not zero, keying nego is ongoing (async-ly, e.g: by DTLS-SRTP).
301      * This field may be updated by keying method.
302      */
303     unsigned		 keying_pending_cnt;
304 
305     /* RTP SSRC in receiving direction, used in getting and setting SRTP
306      * roll over counter (ROC) on SRTP restart.
307      */
308     pj_uint32_t		 rx_ssrc;
309 
310 } transport_srtp;
311 
312 
313 /*
314  * This callback is called by transport when incoming rtp is received
315  */
316 static void srtp_rtp_cb(pjmedia_tp_cb_param *param);
317 
318 /*
319  * This callback is called by transport when incoming rtcp is received
320  */
321 static void srtp_rtcp_cb( void *user_data, void *pkt, pj_ssize_t size);
322 
323 
324 /*
325  * These are media transport operations.
326  */
327 static pj_status_t transport_get_info (pjmedia_transport *tp,
328 				       pjmedia_transport_info *info);
329 //static pj_status_t transport_attach   (pjmedia_transport *tp,
330 //				       void *user_data,
331 //				       const pj_sockaddr_t *rem_addr,
332 //				       const pj_sockaddr_t *rem_rtcp,
333 //				       unsigned addr_len,
334 //				       void (*rtp_cb)(void*,
335 //						      void*,
336 //						      pj_ssize_t),
337 //				       void (*rtcp_cb)(void*,
338 //						       void*,
339 //						       pj_ssize_t));
340 static void	   transport_detach   (pjmedia_transport *tp,
341 				       void *strm);
342 static pj_status_t transport_send_rtp( pjmedia_transport *tp,
343 				       const void *pkt,
344 				       pj_size_t size);
345 static pj_status_t transport_send_rtcp(pjmedia_transport *tp,
346 				       const void *pkt,
347 				       pj_size_t size);
348 static pj_status_t transport_send_rtcp2(pjmedia_transport *tp,
349 				       const pj_sockaddr_t *addr,
350 				       unsigned addr_len,
351 				       const void *pkt,
352 				       pj_size_t size);
353 static pj_status_t transport_media_create(pjmedia_transport *tp,
354 				       pj_pool_t *sdp_pool,
355 				       unsigned options,
356 				       const pjmedia_sdp_session *sdp_remote,
357 				       unsigned media_index);
358 static pj_status_t transport_encode_sdp(pjmedia_transport *tp,
359 				       pj_pool_t *sdp_pool,
360 				       pjmedia_sdp_session *sdp_local,
361 				       const pjmedia_sdp_session *sdp_remote,
362 				       unsigned media_index);
363 static pj_status_t transport_media_start (pjmedia_transport *tp,
364 				       pj_pool_t *pool,
365 				       const pjmedia_sdp_session *sdp_local,
366 				       const pjmedia_sdp_session *sdp_remote,
367 				       unsigned media_index);
368 static pj_status_t transport_media_stop(pjmedia_transport *tp);
369 static pj_status_t transport_simulate_lost(pjmedia_transport *tp,
370 				       pjmedia_dir dir,
371 				       unsigned pct_lost);
372 static pj_status_t transport_destroy  (pjmedia_transport *tp);
373 static pj_status_t transport_attach2  (pjmedia_transport *tp,
374 				       pjmedia_transport_attach_param *param);
375 
376 
377 
378 static pjmedia_transport_op transport_srtp_op =
379 {
380     &transport_get_info,
381     NULL, //&transport_attach,
382     &transport_detach,
383     &transport_send_rtp,
384     &transport_send_rtcp,
385     &transport_send_rtcp2,
386     &transport_media_create,
387     &transport_encode_sdp,
388     &transport_media_start,
389     &transport_media_stop,
390     &transport_simulate_lost,
391     &transport_destroy,
392     &transport_attach2
393 };
394 
395 /* Get crypto index from crypto name */
396 static int get_crypto_idx(const pj_str_t* crypto_name);
397 
398 /* Is crypto empty (i.e: no name or key)? */
399 static pj_bool_t srtp_crypto_empty(const pjmedia_srtp_crypto* c);
400 
401 /* Compare crypto, return zero if same */
402 static int srtp_crypto_cmp(const pjmedia_srtp_crypto* c1,
403 			   const pjmedia_srtp_crypto* c2);
404 
405 /* Start SRTP */
406 static pj_status_t start_srtp(transport_srtp *srtp);
407 
408 
409 /* This function may also be used by other module, e.g: pjmedia/errno.c,
410  * it should have C compatible declaration.
411  */
412 PJ_BEGIN_DECL
413     const char* get_libsrtp_errstr(int err);
414 PJ_END_DECL
415 
get_libsrtp_errstr(int err)416 const char* get_libsrtp_errstr(int err)
417 {
418 #if defined(PJ_HAS_ERROR_STRING) && (PJ_HAS_ERROR_STRING != 0)
419     static char *liberr[] = {
420 	"ok",				    /* srtp_err_status_ok       = 0  */
421 	"unspecified failure",		    /* err_status_fail          = 1  */
422 	"unsupported parameter",	    /* err_status_bad_param     = 2  */
423 	"couldn't allocate memory",	    /* err_status_alloc_fail    = 3  */
424 	"couldn't deallocate properly",	    /* err_status_dealloc_fail  = 4  */
425 	"couldn't initialize",		    /* err_status_init_fail     = 5  */
426 	"can't process as much data as requested",
427 					    /* err_status_terminus      = 6  */
428 	"authentication failure",	    /* err_status_auth_fail     = 7  */
429 	"cipher failure",		    /* err_status_cipher_fail   = 8  */
430 	"replay check failed (bad index)",  /* err_status_replay_fail   = 9  */
431 	"replay check failed (index too old)",
432 					    /* err_status_replay_old    = 10 */
433 	"algorithm failed test routine",    /* err_status_algo_fail     = 11 */
434 	"unsupported operation",	    /* err_status_no_such_op    = 12 */
435 	"no appropriate context found",	    /* err_status_no_ctx        = 13 */
436 	"unable to perform desired validation",
437 					    /* err_status_cant_check    = 14 */
438 	"can't use key any more",	    /* err_status_key_expired   = 15 */
439 	"error in use of socket",	    /* err_status_socket_err    = 16 */
440 	"error in use POSIX signals",	    /* err_status_signal_err    = 17 */
441 	"nonce check failed",		    /* err_status_nonce_bad     = 18 */
442 	"couldn't read data",		    /* err_status_read_fail     = 19 */
443 	"couldn't write data",		    /* err_status_write_fail    = 20 */
444 	"error pasring data",		    /* err_status_parse_err     = 21 */
445 	"error encoding data",		    /* err_status_encode_err    = 22 */
446 	"error while using semaphores",	    /* err_status_semaphore_err = 23 */
447 	"error while using pfkey"	    /* err_status_pfkey_err     = 24 */
448     };
449     if (err >= 0 && err < (int)PJ_ARRAY_SIZE(liberr)) {
450 	return liberr[err];
451     } else {
452 	static char msg[32];
453 	pj_ansi_snprintf(msg, sizeof(msg), "Unknown libsrtp error %d", err);
454 	return msg;
455     }
456 #else
457     static char msg[32];
458     pj_ansi_snprintf(msg, sizeof(msg), "libsrtp error %d", err);
459     return msg;
460 #endif
461 }
462 
463 /* SRTP keying method: Session Description */
464 #if defined(PJMEDIA_SRTP_HAS_SDES) && (PJMEDIA_SRTP_HAS_SDES != 0)
465 #  include "transport_srtp_sdes.c"
466 #endif
467 
468 /* SRTP keying method: DTLS */
469 #if defined(PJMEDIA_SRTP_HAS_DTLS) && (PJMEDIA_SRTP_HAS_DTLS != 0)
470 #  include "transport_srtp_dtls.c"
471 #else
pjmedia_transport_srtp_dtls_start_nego(pjmedia_transport * srtp,const pjmedia_srtp_dtls_nego_param * param)472 PJ_DEF(pj_status_t) pjmedia_transport_srtp_dtls_start_nego(
473 				pjmedia_transport *srtp,
474 				const pjmedia_srtp_dtls_nego_param *param)
475 {
476     PJ_UNUSED_ARG(srtp);
477     PJ_UNUSED_ARG(param);
478     return PJ_ENOTSUP;
479 }
pjmedia_transport_srtp_dtls_get_fingerprint(pjmedia_transport * srtp,const char * hash,char * buf,pj_size_t * len)480 PJ_DEF(pj_status_t) pjmedia_transport_srtp_dtls_get_fingerprint(
481 				pjmedia_transport *srtp,
482 				const char *hash,
483 				char *buf, pj_size_t *len)
484 {
485     PJ_UNUSED_ARG(srtp);
486     PJ_UNUSED_ARG(hash);
487     PJ_UNUSED_ARG(buf);
488     PJ_UNUSED_ARG(len);
489     return PJ_ENOTSUP;
490 }
491 #endif
492 
493 
494 static pj_bool_t libsrtp_initialized;
495 static void pjmedia_srtp_deinit_lib(pjmedia_endpt *endpt);
496 
pjmedia_srtp_init_lib(pjmedia_endpt * endpt)497 PJ_DEF(pj_status_t) pjmedia_srtp_init_lib(pjmedia_endpt *endpt)
498 {
499     pj_status_t status = PJ_SUCCESS;
500 
501     if (libsrtp_initialized)
502 	return PJ_SUCCESS;
503 
504 #if PJMEDIA_LIBSRTP_AUTO_INIT_DEINIT
505     /* Init libsrtp */
506     {
507 	srtp_err_status_t err;
508 
509 	err = srtp_init();
510 	if (err != srtp_err_status_ok) {
511 	    PJ_LOG(4, (THIS_FILE, "Failed to initialize libsrtp: %s",
512 		       get_libsrtp_errstr(err)));
513 	    return PJMEDIA_ERRNO_FROM_LIBSRTP(err);
514 	}
515     }
516 #endif
517 
518 #if defined(PJMEDIA_SRTP_HAS_DTLS) && (PJMEDIA_SRTP_HAS_DTLS != 0)
519     dtls_init();
520 #endif
521 
522     status = pjmedia_endpt_atexit(endpt, pjmedia_srtp_deinit_lib);
523     if (status != PJ_SUCCESS) {
524 	/* There will be memory leak when it fails to schedule libsrtp
525 	 * deinitialization, however the memory leak could be harmless,
526 	 * since in modern OS's memory used by an application is released
527 	 * when the application terminates.
528 	 */
529 	PJ_PERROR(4, (THIS_FILE, status,
530 		      "Failed to register libsrtp deinit."));
531 
532 	/* Ignore this error */
533 	status = PJ_SUCCESS;
534     }
535 
536     libsrtp_initialized = PJ_TRUE;
537 
538     return status;
539 }
540 
pjmedia_srtp_deinit_lib(pjmedia_endpt * endpt)541 static void pjmedia_srtp_deinit_lib(pjmedia_endpt *endpt)
542 {
543     srtp_err_status_t err;
544 
545     /* Note that currently this SRTP init/deinit is not equipped with
546      * reference counter, it should be safe as normally there is only
547      * one single instance of media endpoint and even if it isn't, the
548      * pjmedia_transport_srtp_create() will invoke SRTP init (the only
549      * drawback should be the delay described by #788).
550      */
551 
552     PJ_UNUSED_ARG(endpt);
553 
554 #if !defined(PJMEDIA_SRTP_HAS_DEINIT) && !defined(PJMEDIA_SRTP_HAS_SHUTDOWN)
555 # define PJMEDIA_SRTP_HAS_SHUTDOWN 1
556 #endif
557 
558 #if PJMEDIA_LIBSRTP_AUTO_INIT_DEINIT
559 
560 # if defined(PJMEDIA_SRTP_HAS_DEINIT) && PJMEDIA_SRTP_HAS_DEINIT!=0
561     err = srtp_deinit();
562 # elif defined(PJMEDIA_SRTP_HAS_SHUTDOWN) && PJMEDIA_SRTP_HAS_SHUTDOWN!=0
563     err = srtp_shutdown();
564 # else
565     err = srtp_err_status_ok;
566 # endif
567     if (err != srtp_err_status_ok) {
568 	PJ_LOG(4, (THIS_FILE, "Failed to deinitialize libsrtp: %s",
569 		   get_libsrtp_errstr(err)));
570     }
571 #endif // PJMEDIA_LIBSRTP_AUTO_INIT_DEINIT
572 
573 #if defined(PJMEDIA_SRTP_HAS_DTLS) && (PJMEDIA_SRTP_HAS_DTLS != 0)
574     dtls_deinit();
575 #endif
576 
577     libsrtp_initialized = PJ_FALSE;
578 }
579 
580 
get_crypto_idx(const pj_str_t * crypto_name)581 static int get_crypto_idx(const pj_str_t* crypto_name)
582 {
583     int i;
584     int cs_cnt = sizeof(crypto_suites)/sizeof(crypto_suites[0]);
585 
586     /* treat unspecified crypto_name as crypto 'NULL' */
587     if (crypto_name->slen == 0)
588 	return 0;
589 
590     for (i=0; i<cs_cnt; ++i) {
591 	if (!pj_stricmp2(crypto_name, crypto_suites[i].name))
592 	    return i;
593     }
594 
595     return -1;
596 }
597 
598 
srtp_crypto_cmp(const pjmedia_srtp_crypto * c1,const pjmedia_srtp_crypto * c2)599 static int srtp_crypto_cmp(const pjmedia_srtp_crypto* c1,
600 			   const pjmedia_srtp_crypto* c2)
601 {
602     int r;
603 
604     r = pj_strcmp(&c1->key, &c2->key);
605     if (r != 0)
606 	return r;
607 
608     r = pj_stricmp(&c1->name, &c2->name);
609     if (r != 0)
610 	return r;
611 
612     return (c1->flags != c2->flags);
613 }
614 
615 
srtp_crypto_empty(const pjmedia_srtp_crypto * c)616 static pj_bool_t srtp_crypto_empty(const pjmedia_srtp_crypto* c)
617 {
618     return (c->name.slen==0 || c->key.slen==0);
619 }
620 
621 
pjmedia_srtp_setting_default(pjmedia_srtp_setting * opt)622 PJ_DEF(void) pjmedia_srtp_setting_default(pjmedia_srtp_setting *opt)
623 {
624     pj_assert(opt);
625 
626     pj_bzero(opt, sizeof(pjmedia_srtp_setting));
627     opt->close_member_tp = PJ_TRUE;
628     opt->use = PJMEDIA_SRTP_OPTIONAL;
629 }
630 
631 /*
632  * Enumerate all SRTP cryptos, except "NULL".
633  */
pjmedia_srtp_enum_crypto(unsigned * count,pjmedia_srtp_crypto crypto[])634 PJ_DEF(pj_status_t) pjmedia_srtp_enum_crypto(unsigned *count,
635 					     pjmedia_srtp_crypto crypto[])
636 {
637     unsigned i, max;
638 
639     PJ_ASSERT_RETURN(count && crypto, PJ_EINVAL);
640 
641     max = sizeof(crypto_suites) / sizeof(crypto_suites[0]) - 1;
642     if (*count > max)
643 	*count = max;
644 
645     for (i=0; i<*count; ++i) {
646 	pj_bzero(&crypto[i], sizeof(crypto[0]));
647 	crypto[i].name = pj_str(crypto_suites[i+1].name);
648     }
649 
650     return PJ_SUCCESS;
651 }
652 
653 
654 /*
655  * Enumerate available SRTP keying methods.
656  */
pjmedia_srtp_enum_keying(unsigned * count,pjmedia_srtp_keying_method keying[])657 PJ_DEF(pj_status_t) pjmedia_srtp_enum_keying(unsigned *count,
658 				      pjmedia_srtp_keying_method keying[])
659 {
660     unsigned max;
661 
662     PJ_ASSERT_RETURN(count && keying, PJ_EINVAL);
663 
664     max = *count;
665     *count = 0;
666 
667 #if defined(PJMEDIA_SRTP_HAS_SDES) && (PJMEDIA_SRTP_HAS_SDES != 0)
668     if (*count < max)
669 	keying[(*count)++] = PJMEDIA_SRTP_KEYING_SDES;
670 #endif
671 #if defined(PJMEDIA_SRTP_HAS_DTLS) && (PJMEDIA_SRTP_HAS_DTLS != 0)
672     if (*count < max)
673 	keying[(*count)++] = PJMEDIA_SRTP_KEYING_DTLS_SRTP;
674 #endif
675 
676     return PJ_SUCCESS;
677 }
678 
679 
680 /*
681  * Create an SRTP media transport.
682  */
pjmedia_transport_srtp_create(pjmedia_endpt * endpt,pjmedia_transport * tp,const pjmedia_srtp_setting * opt,pjmedia_transport ** p_tp)683 PJ_DEF(pj_status_t) pjmedia_transport_srtp_create(
684 				       pjmedia_endpt *endpt,
685 				       pjmedia_transport *tp,
686 				       const pjmedia_srtp_setting *opt,
687 				       pjmedia_transport **p_tp)
688 {
689     pj_pool_t *pool;
690     transport_srtp *srtp;
691     pj_status_t status;
692     unsigned i;
693 
694     PJ_ASSERT_RETURN(endpt && tp && p_tp, PJ_EINVAL);
695 
696     /* Check crypto */
697     if (opt && opt->use != PJMEDIA_SRTP_DISABLED) {
698 	for (i=0; i < opt->crypto_count; ++i) {
699 	    int cs_idx = get_crypto_idx(&opt->crypto[i].name);
700 
701 	    /* check crypto name */
702 	    if (cs_idx == -1)
703 		return PJMEDIA_SRTP_ENOTSUPCRYPTO;
704 
705 	    /* check key length */
706 	    if (opt->crypto[i].key.slen &&
707 		opt->crypto[i].key.slen <
708 		(pj_ssize_t)crypto_suites[cs_idx].cipher_key_len)
709 		return PJMEDIA_SRTP_EINKEYLEN;
710 	}
711     }
712 
713     /* Init libsrtp. */
714     status = pjmedia_srtp_init_lib(endpt);
715     if (status != PJ_SUCCESS)
716 	return status;
717 
718     pool = pjmedia_endpt_create_pool(endpt, "srtp%p", 1000, 1000);
719     srtp = PJ_POOL_ZALLOC_T(pool, transport_srtp);
720 
721     srtp->pool = pool;
722     srtp->session_inited = PJ_FALSE;
723     srtp->bypass_srtp = PJ_FALSE;
724     srtp->probation_cnt = PROBATION_CNT_INIT;
725 
726     if (opt) {
727 	srtp->setting = *opt;
728 	if (opt->use == PJMEDIA_SRTP_DISABLED)
729 	    srtp->setting.crypto_count = 0;
730 
731 	for (i=0; i < srtp->setting.crypto_count; ++i) {
732 	    int cs_idx = get_crypto_idx(&opt->crypto[i].name);
733 	    pj_str_t tmp_key = opt->crypto[i].key;
734 
735 	    /* re-set crypto */
736 	    srtp->setting.crypto[i].name = pj_str(crypto_suites[cs_idx].name);
737 	    /* cut key length */
738 	    if (tmp_key.slen)
739 		tmp_key.slen = crypto_suites[cs_idx].cipher_key_len;
740 	    pj_strdup(pool, &srtp->setting.crypto[i].key, &tmp_key);
741 	}
742     } else {
743 	pjmedia_srtp_setting_default(&srtp->setting);
744     }
745 
746     /* If crypto count is set to zero, setup default crypto-suites,
747      * i.e: all available crypto but 'NULL'.
748      */
749     if (srtp->setting.crypto_count == 0 &&
750 	srtp->setting.use != PJMEDIA_SRTP_DISABLED)
751     {
752 	srtp->setting.crypto_count = PJMEDIA_SRTP_MAX_CRYPTOS;
753 	pjmedia_srtp_enum_crypto(&srtp->setting.crypto_count,
754 				 srtp->setting.crypto);
755     }
756 
757     status = pj_lock_create_recursive_mutex(pool, pool->obj_name,
758 					    &srtp->mutex);
759     if (status != PJ_SUCCESS) {
760 	pj_pool_release(pool);
761 	return status;
762     }
763 
764     /* Initialize base pjmedia_transport */
765     pj_memcpy(srtp->base.name, pool->obj_name, PJ_MAX_OBJ_NAME);
766     if (tp)
767 	srtp->base.type = tp->type;
768     else
769 	srtp->base.type = PJMEDIA_TRANSPORT_TYPE_UDP;
770     srtp->base.op = &transport_srtp_op;
771     srtp->base.user_data = srtp->setting.user_data;
772 
773     /* Set underlying transport */
774     srtp->member_tp = tp;
775 
776     /* Initialize peer's SRTP usage mode. */
777     srtp->peer_use = srtp->setting.use;
778 
779     /* If keying count set to zero, setup default keying count & priorities */
780     if (srtp->setting.keying_count == 0) {
781 	srtp->setting.keying_count = PJMEDIA_SRTP_KEYINGS_COUNT;
782 	pjmedia_srtp_enum_keying(&srtp->setting.keying_count,
783 				 srtp->setting.keying);
784     }
785 
786     /* Initialize SRTP keying method. */
787     for (i = 0; i < srtp->setting.keying_count && i < MAX_KEYING; ++i) {
788 	switch(srtp->setting.keying[i]) {
789 
790 	case PJMEDIA_SRTP_KEYING_SDES:
791 #if defined(PJMEDIA_SRTP_HAS_SDES) && (PJMEDIA_SRTP_HAS_SDES != 0)
792 	    sdes_create(srtp, &srtp->all_keying[srtp->all_keying_cnt++]);
793 #endif
794 	    break;
795 
796 	case PJMEDIA_SRTP_KEYING_DTLS_SRTP:
797 #if defined(PJMEDIA_SRTP_HAS_DTLS) && (PJMEDIA_SRTP_HAS_DTLS != 0)
798 	    dtls_create(srtp, &srtp->all_keying[srtp->all_keying_cnt++]);
799 #endif
800 	    break;
801 
802 	default:
803 	    break;
804 	}
805     }
806 
807     /* Done */
808     *p_tp = &srtp->base;
809 
810     return PJ_SUCCESS;
811 }
812 
813 
814 /*
815  * Initialize and start SRTP session with the given parameters.
816  */
pjmedia_transport_srtp_start(pjmedia_transport * tp,const pjmedia_srtp_crypto * tx,const pjmedia_srtp_crypto * rx)817 PJ_DEF(pj_status_t) pjmedia_transport_srtp_start(
818 			   pjmedia_transport *tp,
819 			   const pjmedia_srtp_crypto *tx,
820 			   const pjmedia_srtp_crypto *rx)
821 {
822     transport_srtp  *srtp = (transport_srtp*) tp;
823     srtp_policy_t    tx_;
824     srtp_policy_t    rx_;
825     uint32_t	     rx_roc = 0;
826     srtp_err_status_t err;
827     int		     cr_tx_idx = 0;
828     int		     au_tx_idx = 0;
829     int		     cr_rx_idx = 0;
830     int		     au_rx_idx = 0;
831     pj_status_t	     status = PJ_SUCCESS;
832 
833     PJ_ASSERT_RETURN(tp && tx && rx, PJ_EINVAL);
834 
835     pj_lock_acquire(srtp->mutex);
836 
837     if (srtp->session_inited) {
838 	srtp_get_stream_roc(srtp->srtp_rx_ctx, srtp->rx_ssrc, &rx_roc);
839 	pjmedia_transport_srtp_stop(tp);
840     }
841 
842     /* Get encryption and authentication method */
843     cr_tx_idx = au_tx_idx = get_crypto_idx(&tx->name);
844     if (tx->flags & PJMEDIA_SRTP_NO_ENCRYPTION)
845 	cr_tx_idx = 0;
846     if (tx->flags & PJMEDIA_SRTP_NO_AUTHENTICATION)
847 	au_tx_idx = 0;
848 
849     cr_rx_idx = au_rx_idx = get_crypto_idx(&rx->name);
850     if (rx->flags & PJMEDIA_SRTP_NO_ENCRYPTION)
851 	cr_rx_idx = 0;
852     if (rx->flags & PJMEDIA_SRTP_NO_AUTHENTICATION)
853 	au_rx_idx = 0;
854 
855     /* Check whether the crypto-suite requested is supported */
856     if (cr_tx_idx == -1 || cr_rx_idx == -1 || au_tx_idx == -1 ||
857 	au_rx_idx == -1)
858     {
859 	status = PJMEDIA_SRTP_ENOTSUPCRYPTO;
860 	goto on_return;
861     }
862 
863     /* If all options points to 'NULL' method, just bypass SRTP */
864     if (cr_tx_idx == 0 && cr_rx_idx == 0 && au_tx_idx == 0 && au_rx_idx == 0) {
865 	srtp->bypass_srtp = PJ_TRUE;
866 	goto on_return;
867     }
868 
869     /* Check key length */
870     if (tx->key.slen != (pj_ssize_t)crypto_suites[cr_tx_idx].cipher_key_len ||
871         rx->key.slen != (pj_ssize_t)crypto_suites[cr_rx_idx].cipher_key_len)
872     {
873 	status = PJMEDIA_SRTP_EINKEYLEN;
874 	goto on_return;
875     }
876 
877     /* Init transmit direction */
878     pj_bzero(&tx_, sizeof(srtp_policy_t));
879     pj_memmove(srtp->tx_key, tx->key.ptr, tx->key.slen);
880     if (cr_tx_idx && au_tx_idx)
881 	tx_.rtp.sec_serv    = sec_serv_conf_and_auth;
882     else if (cr_tx_idx)
883 	tx_.rtp.sec_serv    = sec_serv_conf;
884     else if (au_tx_idx)
885 	tx_.rtp.sec_serv    = sec_serv_auth;
886     else
887 	tx_.rtp.sec_serv    = sec_serv_none;
888     tx_.key		    = (uint8_t*)srtp->tx_key;
889     tx_.ssrc.type	    = ssrc_any_outbound;
890     tx_.ssrc.value	    = 0;
891     tx_.rtp.cipher_type	    = crypto_suites[cr_tx_idx].cipher_type;
892     tx_.rtp.cipher_key_len  = crypto_suites[cr_tx_idx].cipher_key_len;
893     tx_.rtp.auth_type	    = crypto_suites[au_tx_idx].auth_type;
894     tx_.rtp.auth_key_len    = crypto_suites[au_tx_idx].auth_key_len;
895     tx_.rtp.auth_tag_len    = crypto_suites[au_tx_idx].srtp_auth_tag_len;
896     tx_.rtcp		    = tx_.rtp;
897     tx_.rtcp.auth_tag_len   = crypto_suites[au_tx_idx].srtcp_auth_tag_len;
898     tx_.next		    = NULL;
899     err = srtp_create(&srtp->srtp_tx_ctx, &tx_);
900     if (err != srtp_err_status_ok) {
901 	status = PJMEDIA_ERRNO_FROM_LIBSRTP(err);
902 	goto on_return;
903     }
904     srtp->tx_policy = *tx;
905     pj_strset(&srtp->tx_policy.key,  srtp->tx_key, tx->key.slen);
906     srtp->tx_policy.name=pj_str(crypto_suites[get_crypto_idx(&tx->name)].name);
907 
908 
909     /* Init receive direction */
910     pj_bzero(&rx_, sizeof(srtp_policy_t));
911     pj_memmove(srtp->rx_key, rx->key.ptr, rx->key.slen);
912     if (cr_rx_idx && au_rx_idx)
913 	rx_.rtp.sec_serv    = sec_serv_conf_and_auth;
914     else if (cr_rx_idx)
915 	rx_.rtp.sec_serv    = sec_serv_conf;
916     else if (au_rx_idx)
917 	rx_.rtp.sec_serv    = sec_serv_auth;
918     else
919 	rx_.rtp.sec_serv    = sec_serv_none;
920     rx_.key		    = (uint8_t*)srtp->rx_key;
921     if (rx_roc != 0 && srtp->rx_ssrc != 0) {
922 	rx_.ssrc.type	    = ssrc_specific;
923 	rx_.ssrc.value	    = srtp->rx_ssrc;
924     } else {
925 	rx_.ssrc.type	    = ssrc_any_inbound;
926 	rx_.ssrc.value	    = 0;
927     }
928     rx_.rtp.sec_serv	    = crypto_suites[cr_rx_idx].service;
929     rx_.rtp.cipher_type	    = crypto_suites[cr_rx_idx].cipher_type;
930     rx_.rtp.cipher_key_len  = crypto_suites[cr_rx_idx].cipher_key_len;
931     rx_.rtp.auth_type	    = crypto_suites[au_rx_idx].auth_type;
932     rx_.rtp.auth_key_len    = crypto_suites[au_rx_idx].auth_key_len;
933     rx_.rtp.auth_tag_len    = crypto_suites[au_rx_idx].srtp_auth_tag_len;
934     rx_.rtcp		    = rx_.rtp;
935     rx_.rtcp.auth_tag_len   = crypto_suites[au_rx_idx].srtcp_auth_tag_len;
936     rx_.next		    = NULL;
937     err = srtp_create(&srtp->srtp_rx_ctx, &rx_);
938     if (err != srtp_err_status_ok) {
939 	srtp_dealloc(srtp->srtp_tx_ctx);
940 	status = PJMEDIA_ERRNO_FROM_LIBSRTP(err);
941 	goto on_return;
942     }
943     if (rx_roc != 0 && srtp->rx_ssrc != 0) {
944 	srtp_set_stream_roc(srtp->srtp_rx_ctx, srtp->rx_ssrc, rx_roc);
945     }
946     srtp->rx_policy = *rx;
947     pj_strset(&srtp->rx_policy.key,  srtp->rx_key, rx->key.slen);
948     srtp->rx_policy.name=pj_str(crypto_suites[get_crypto_idx(&rx->name)].name);
949 
950     /* Declare SRTP session initialized */
951     srtp->session_inited = PJ_TRUE;
952 
953     /* Logging stuffs */
954 #if PJ_LOG_MAX_LEVEL >= 5
955     {
956 	char b64[PJ_BASE256_TO_BASE64_LEN(MAX_KEY_LEN)];
957 	int b64_len;
958 
959 	/* TX crypto and key */
960 	b64_len = sizeof(b64);
961 	status = pj_base64_encode((pj_uint8_t*)tx->key.ptr, (int)tx->key.slen,
962 				  b64, &b64_len);
963 	if (status != PJ_SUCCESS)
964 	    b64_len = pj_ansi_sprintf(b64, "--key too long--");
965 	else
966 	    b64[b64_len] = '\0';
967 
968 	PJ_LOG(5, (srtp->pool->obj_name, "TX: %s key=%s",
969 		   srtp->tx_policy.name.ptr, b64));
970 	if (srtp->tx_policy.flags) {
971 	    PJ_LOG(5,(srtp->pool->obj_name, "TX: disable%s%s",
972 		      (cr_tx_idx?"":" enc"),
973 		      (au_tx_idx?"":" auth")));
974 	}
975 
976 	/* RX crypto and key */
977 	b64_len = sizeof(b64);
978 	status = pj_base64_encode((pj_uint8_t*)rx->key.ptr, (int)rx->key.slen,
979 				  b64, &b64_len);
980 	if (status != PJ_SUCCESS)
981 	    b64_len = pj_ansi_sprintf(b64, "--key too long--");
982 	else
983 	    b64[b64_len] = '\0';
984 
985 	PJ_LOG(5, (srtp->pool->obj_name, "RX: %s key=%s",
986 		   srtp->rx_policy.name.ptr, b64));
987 	if (srtp->rx_policy.flags) {
988 	    PJ_LOG(5,(srtp->pool->obj_name,"RX: disable%s%s",
989 		      (cr_rx_idx?"":" enc"),
990 		      (au_rx_idx?"":" auth")));
991 	}
992     }
993 #endif
994 
995 on_return:
996     pj_lock_release(srtp->mutex);
997     return status;
998 }
999 
1000 /*
1001  * Stop SRTP session.
1002  */
pjmedia_transport_srtp_stop(pjmedia_transport * srtp)1003 PJ_DEF(pj_status_t) pjmedia_transport_srtp_stop(pjmedia_transport *srtp)
1004 {
1005     transport_srtp *p_srtp = (transport_srtp*) srtp;
1006     srtp_err_status_t err;
1007 
1008     PJ_ASSERT_RETURN(srtp, PJ_EINVAL);
1009 
1010     pj_lock_acquire(p_srtp->mutex);
1011 
1012     if (!p_srtp->session_inited) {
1013 	pj_lock_release(p_srtp->mutex);
1014 	return PJ_SUCCESS;
1015     }
1016 
1017     err = srtp_dealloc(p_srtp->srtp_rx_ctx);
1018     if (err != srtp_err_status_ok) {
1019 	PJ_LOG(4, (p_srtp->pool->obj_name,
1020 		   "Failed to dealloc RX SRTP context: %s",
1021 		   get_libsrtp_errstr(err)));
1022     }
1023     err = srtp_dealloc(p_srtp->srtp_tx_ctx);
1024     if (err != srtp_err_status_ok) {
1025 	PJ_LOG(4, (p_srtp->pool->obj_name,
1026 		   "Failed to dealloc TX SRTP context: %s",
1027 		   get_libsrtp_errstr(err)));
1028     }
1029 
1030     p_srtp->session_inited = PJ_FALSE;
1031     pj_bzero(&p_srtp->rx_policy, sizeof(p_srtp->rx_policy));
1032     pj_bzero(&p_srtp->tx_policy, sizeof(p_srtp->tx_policy));
1033 
1034     pj_lock_release(p_srtp->mutex);
1035 
1036     return PJ_SUCCESS;
1037 }
1038 
1039 
start_srtp(transport_srtp * srtp)1040 static pj_status_t start_srtp(transport_srtp *srtp)
1041 {
1042     /* Make sure we have the SRTP policies */
1043     if (srtp_crypto_empty(&srtp->tx_policy_neg) ||
1044 	srtp_crypto_empty(&srtp->rx_policy_neg))
1045     {
1046 	srtp->bypass_srtp = PJ_TRUE;
1047 	srtp->peer_use = PJMEDIA_SRTP_DISABLED;
1048 	if (srtp->session_inited) {
1049 	    pjmedia_transport_srtp_stop(&srtp->base);
1050 	}
1051 
1052 	PJ_LOG(4, (srtp->pool->obj_name, "SRTP not active"));
1053 	return PJ_SUCCESS;
1054     }
1055 
1056     /* Got policy_local & policy_remote, let's initalize the SRTP */
1057 
1058     /* Ticket #1075: media_start() is called whenever media description
1059      * gets updated, e.g: call hold, however we should restart SRTP only
1060      * when the SRTP policy settings are updated.
1061      */
1062     if (srtp_crypto_cmp(&srtp->tx_policy_neg, &srtp->tx_policy) ||
1063 	srtp_crypto_cmp(&srtp->rx_policy_neg, &srtp->rx_policy))
1064     {
1065 	pj_status_t status;
1066 	status = pjmedia_transport_srtp_start(&srtp->base,
1067 					      &srtp->tx_policy_neg,
1068 					      &srtp->rx_policy_neg);
1069 	if (status != PJ_SUCCESS)
1070 	    return status;
1071 
1072 	/* Reset probation counts */
1073 	srtp->probation_cnt = PROBATION_CNT_INIT;
1074 
1075 	PJ_LOG(4, (srtp->pool->obj_name,
1076 		   "SRTP started, keying=%s, crypto=%s",
1077 		   ((int)srtp->keying[0]->type==PJMEDIA_SRTP_KEYING_SDES?
1078 		    "SDES":"DTLS-SRTP"),
1079 		   srtp->tx_policy.name.ptr));
1080     }
1081 
1082     srtp->bypass_srtp = PJ_FALSE;
1083 
1084     return PJ_SUCCESS;
1085 }
1086 
1087 
pjmedia_transport_srtp_get_member(pjmedia_transport * tp)1088 PJ_DEF(pjmedia_transport *) pjmedia_transport_srtp_get_member(
1089 						pjmedia_transport *tp)
1090 {
1091     transport_srtp *srtp = (transport_srtp*) tp;
1092 
1093     PJ_ASSERT_RETURN(tp, NULL);
1094 
1095     return srtp->member_tp;
1096 }
1097 
1098 
transport_get_info(pjmedia_transport * tp,pjmedia_transport_info * info)1099 static pj_status_t transport_get_info(pjmedia_transport *tp,
1100 				      pjmedia_transport_info *info)
1101 {
1102     transport_srtp *srtp = (transport_srtp*) tp;
1103     pjmedia_srtp_info srtp_info;
1104     int spc_info_idx;
1105     unsigned i;
1106 
1107     PJ_ASSERT_RETURN(tp && info, PJ_EINVAL);
1108     PJ_ASSERT_RETURN(info->specific_info_cnt <
1109 		     PJMEDIA_TRANSPORT_SPECIFIC_INFO_MAXCNT, PJ_ETOOMANY);
1110     PJ_ASSERT_RETURN(sizeof(pjmedia_srtp_info) <=
1111 		     PJMEDIA_TRANSPORT_SPECIFIC_INFO_MAXSIZE, PJ_ENOMEM);
1112 
1113     srtp_info.active = srtp->session_inited;
1114     srtp_info.rx_policy = srtp->rx_policy;
1115     srtp_info.tx_policy = srtp->tx_policy;
1116     srtp_info.use = srtp->setting.use;
1117     srtp_info.peer_use = srtp->peer_use;
1118 
1119     spc_info_idx = info->specific_info_cnt++;
1120     info->spc_info[spc_info_idx].type = PJMEDIA_TRANSPORT_TYPE_SRTP;
1121     info->spc_info[spc_info_idx].cbsize = sizeof(srtp_info);
1122     pj_memcpy(&info->spc_info[spc_info_idx].buffer, &srtp_info,
1123 	      sizeof(srtp_info));
1124 
1125     /* Invoke get_info() from any active keying method */
1126     for (i=0; i < srtp->keying_cnt; i++)
1127 	pjmedia_transport_get_info(srtp->keying[i], info);
1128 
1129     return pjmedia_transport_get_info(srtp->member_tp, info);
1130 }
1131 
transport_attach2(pjmedia_transport * tp,pjmedia_transport_attach_param * param)1132 static pj_status_t transport_attach2(pjmedia_transport *tp,
1133 				     pjmedia_transport_attach_param *param)
1134 {
1135     transport_srtp *srtp = (transport_srtp*) tp;
1136     pjmedia_transport_attach_param member_param;
1137     pj_status_t status;
1138 
1139     PJ_ASSERT_RETURN(tp && param, PJ_EINVAL);
1140 
1141     /* Save the callbacks */
1142     pj_lock_acquire(srtp->mutex);
1143     if (param->rtp_cb || param->rtp_cb2) {
1144 	/* Do not update rtp_cb if not set, as attach() is called by
1145 	 * keying method.
1146 	 */
1147 	srtp->rtp_cb = param->rtp_cb;
1148 	srtp->rtp_cb2 = param->rtp_cb2;
1149 	srtp->rtcp_cb = param->rtcp_cb;
1150 	srtp->user_data = param->user_data;
1151     }
1152     pj_lock_release(srtp->mutex);
1153 
1154     /* Attach self to member transport */
1155     member_param = *param;
1156     member_param.user_data = srtp;
1157     member_param.rtp_cb = NULL;
1158     member_param.rtp_cb2 = &srtp_rtp_cb;
1159     member_param.rtcp_cb = &srtp_rtcp_cb;
1160     status = pjmedia_transport_attach2(srtp->member_tp, &member_param);
1161     if (status != PJ_SUCCESS) {
1162 	pj_lock_acquire(srtp->mutex);
1163 	srtp->rtp_cb = NULL;
1164 	srtp->rtcp_cb = NULL;
1165 	srtp->user_data = NULL;
1166 	pj_lock_release(srtp->mutex);
1167 	return status;
1168     }
1169 
1170     /* Check if we are multiplexing RTP & RTCP. */
1171     srtp->use_rtcp_mux = (pj_sockaddr_has_addr(&param->rem_addr) &&
1172     			  pj_sockaddr_cmp(&param->rem_addr,
1173     					  &param->rem_rtcp) == 0);
1174     srtp->member_tp_attached = PJ_TRUE;
1175     return PJ_SUCCESS;
1176 }
1177 
transport_detach(pjmedia_transport * tp,void * strm)1178 static void transport_detach(pjmedia_transport *tp, void *strm)
1179 {
1180     transport_srtp *srtp = (transport_srtp*) tp;
1181 
1182     PJ_UNUSED_ARG(strm);
1183     PJ_ASSERT_ON_FAIL(tp, return);
1184 
1185     if (srtp->member_tp) {
1186 	pjmedia_transport_detach(srtp->member_tp, srtp);
1187     }
1188 
1189     /* Clear up application infos from transport */
1190     pj_lock_acquire(srtp->mutex);
1191     srtp->rtp_cb = NULL;
1192     srtp->rtp_cb2 = NULL;
1193     srtp->rtcp_cb = NULL;
1194     srtp->user_data = NULL;
1195     pj_lock_release(srtp->mutex);
1196     srtp->member_tp_attached = PJ_FALSE;
1197 }
1198 
transport_send_rtp(pjmedia_transport * tp,const void * pkt,pj_size_t size)1199 static pj_status_t transport_send_rtp( pjmedia_transport *tp,
1200 				       const void *pkt,
1201 				       pj_size_t size)
1202 {
1203     pj_status_t status;
1204     transport_srtp *srtp = (transport_srtp*) tp;
1205     int len = (int)size;
1206     srtp_err_status_t err;
1207 
1208     if (srtp->bypass_srtp)
1209 	return pjmedia_transport_send_rtp(srtp->member_tp, pkt, size);
1210 
1211     if (size > sizeof(srtp->rtp_tx_buffer) - MAX_TRAILER_LEN)
1212 	return PJ_ETOOBIG;
1213 
1214     pj_memcpy(srtp->rtp_tx_buffer, pkt, size);
1215 
1216     pj_lock_acquire(srtp->mutex);
1217     if (!srtp->session_inited) {
1218 	pj_lock_release(srtp->mutex);
1219 	return PJMEDIA_SRTP_EKEYNOTREADY;
1220     }
1221     err = srtp_protect(srtp->srtp_tx_ctx, srtp->rtp_tx_buffer, &len);
1222     pj_lock_release(srtp->mutex);
1223 
1224     if (err == srtp_err_status_ok) {
1225 	status = pjmedia_transport_send_rtp(srtp->member_tp,
1226 					    srtp->rtp_tx_buffer, len);
1227     } else {
1228 	status = PJMEDIA_ERRNO_FROM_LIBSRTP(err);
1229     }
1230 
1231     return status;
1232 }
1233 
transport_send_rtcp(pjmedia_transport * tp,const void * pkt,pj_size_t size)1234 static pj_status_t transport_send_rtcp(pjmedia_transport *tp,
1235 				       const void *pkt,
1236 				       pj_size_t size)
1237 {
1238     return transport_send_rtcp2(tp, NULL, 0, pkt, size);
1239 }
1240 
transport_send_rtcp2(pjmedia_transport * tp,const pj_sockaddr_t * addr,unsigned addr_len,const void * pkt,pj_size_t size)1241 static pj_status_t transport_send_rtcp2(pjmedia_transport *tp,
1242 				        const pj_sockaddr_t *addr,
1243 				        unsigned addr_len,
1244 				        const void *pkt,
1245 				        pj_size_t size)
1246 {
1247     pj_status_t status;
1248     transport_srtp *srtp = (transport_srtp*) tp;
1249     int len = (int)size;
1250     srtp_err_status_t err;
1251 
1252     if (srtp->bypass_srtp) {
1253 	return pjmedia_transport_send_rtcp2(srtp->member_tp, addr, addr_len,
1254 	                                    pkt, size);
1255     }
1256 
1257     if (size > sizeof(srtp->rtcp_tx_buffer) - (MAX_TRAILER_LEN+4))
1258 	return PJ_ETOOBIG;
1259 
1260     pj_memcpy(srtp->rtcp_tx_buffer, pkt, size);
1261 
1262     pj_lock_acquire(srtp->mutex);
1263     if (!srtp->session_inited) {
1264 	pj_lock_release(srtp->mutex);
1265 	return PJMEDIA_SRTP_EKEYNOTREADY;
1266     }
1267     err = srtp_protect_rtcp(srtp->srtp_tx_ctx, srtp->rtcp_tx_buffer, &len);
1268     pj_lock_release(srtp->mutex);
1269 
1270     if (err == srtp_err_status_ok) {
1271 	status = pjmedia_transport_send_rtcp2(srtp->member_tp, addr, addr_len,
1272 					      srtp->rtcp_tx_buffer, len);
1273     } else {
1274 	status = PJMEDIA_ERRNO_FROM_LIBSRTP(err);
1275     }
1276 
1277     return status;
1278 }
1279 
1280 
transport_simulate_lost(pjmedia_transport * tp,pjmedia_dir dir,unsigned pct_lost)1281 static pj_status_t transport_simulate_lost(pjmedia_transport *tp,
1282 					   pjmedia_dir dir,
1283 					   unsigned pct_lost)
1284 {
1285     transport_srtp *srtp = (transport_srtp *) tp;
1286 
1287     PJ_ASSERT_RETURN(tp, PJ_EINVAL);
1288 
1289     return pjmedia_transport_simulate_lost(srtp->member_tp, dir, pct_lost);
1290 }
1291 
transport_destroy(pjmedia_transport * tp)1292 static pj_status_t transport_destroy  (pjmedia_transport *tp)
1293 {
1294     transport_srtp *srtp = (transport_srtp *) tp;
1295     pj_status_t status;
1296     unsigned i;
1297 
1298     PJ_ASSERT_RETURN(tp, PJ_EINVAL);
1299 
1300     /* Close all keying. Note that any keying should not be destroyed before
1301      * SRTP transport is destroyed as re-INVITE may initiate new keying method
1302      * without destroying SRTP transport.
1303      */
1304     for (i=0; i < srtp->all_keying_cnt; i++)
1305 	pjmedia_transport_close(srtp->all_keying[i]);
1306 
1307     /* Close member if configured */
1308     if (srtp->setting.close_member_tp && srtp->member_tp) {
1309 	pjmedia_transport_close(srtp->member_tp);
1310     }
1311 
1312     status = pjmedia_transport_srtp_stop(tp);
1313 
1314     /* In case mutex is being acquired by other thread */
1315     pj_lock_acquire(srtp->mutex);
1316     pj_lock_release(srtp->mutex);
1317 
1318     pj_lock_destroy(srtp->mutex);
1319     pj_pool_release(srtp->pool);
1320 
1321     return status;
1322 }
1323 
1324 /*
1325  * This callback is called by transport when incoming rtp is received
1326  */
srtp_rtp_cb(pjmedia_tp_cb_param * param)1327 static void srtp_rtp_cb(pjmedia_tp_cb_param *param)
1328 {
1329     transport_srtp *srtp = (transport_srtp *) param->user_data;
1330     void *pkt = param->pkt;
1331     pj_ssize_t size = param->size;
1332     int len = (int)size;
1333     srtp_err_status_t err;
1334     void (*cb)(void*, void*, pj_ssize_t) = NULL;
1335     void (*cb2)(pjmedia_tp_cb_param*) = NULL;
1336     void *cb_data = NULL;
1337 
1338     if (srtp->bypass_srtp) {
1339         if (srtp->rtp_cb2) {
1340             pjmedia_tp_cb_param param2 = *param;
1341             param2.user_data = srtp->user_data;
1342             srtp->rtp_cb2(&param2);
1343             param->rem_switch = param2.rem_switch;
1344         } else if (srtp->rtp_cb) {
1345 	    srtp->rtp_cb(srtp->user_data, pkt, size);
1346 	}
1347 	return;
1348     }
1349 
1350     if (size < 0) {
1351 	return;
1352     }
1353 
1354     /* Give the packet to keying first by invoking its send_rtp() op.
1355      * Yes, the usage of send_rtp() is rather hacky, but it is convenient
1356      * as the signature suits the purpose and it is ready to use
1357      * (no futher registration/setting needed), and it may never be used
1358      * by any keying method in the future.
1359      */
1360     {
1361 	unsigned i;
1362 	pj_status_t status;
1363 	for (i=0; i < srtp->keying_cnt; i++) {
1364 	    if (!srtp->keying[i]->op->send_rtp)
1365 		continue;
1366 	    status = pjmedia_transport_send_rtp(srtp->keying[i], pkt, size);
1367 	    if (status != PJ_EIGNORED) {
1368 		/* Packet is already consumed by the keying method */
1369 		return;
1370 	    }
1371 	}
1372     }
1373 
1374     /* Make sure buffer is 32bit aligned */
1375     PJ_ASSERT_ON_FAIL( (((pj_ssize_t)pkt) & 0x03)==0, return );
1376 
1377     if (srtp->probation_cnt > 0)
1378 	--srtp->probation_cnt;
1379 
1380     pj_lock_acquire(srtp->mutex);
1381 
1382     if (!srtp->session_inited) {
1383 	pj_lock_release(srtp->mutex);
1384 	return;
1385     }
1386 
1387     /* Check if multiplexing is allowed and the payload indicates RTCP. */
1388     if (srtp->use_rtcp_mux) {
1389     	pjmedia_rtp_hdr *hdr = (pjmedia_rtp_hdr *)pkt;
1390 
1391 	if (hdr->pt >= 64 && hdr->pt <= 95) {
1392 	    pj_lock_release(srtp->mutex);
1393 	    srtp_rtcp_cb(srtp, pkt, size);
1394     	    return;
1395     	}
1396     }
1397 
1398     err = srtp_unprotect(srtp->srtp_rx_ctx, (pj_uint8_t*)pkt, &len);
1399 
1400     if (srtp->probation_cnt > 0 &&
1401 	(err == srtp_err_status_replay_old ||
1402 	 err == srtp_err_status_replay_fail))
1403     {
1404 	/* Handle such condition that stream is updated (RTP seq is reinited
1405 	 * & SRTP is restarted), but some old packets are still coming
1406 	 * so SRTP is learning wrong RTP seq. While the newly inited RTP seq
1407 	 * comes, SRTP thinks the RTP seq is replayed, so srtp_unprotect()
1408 	 * will return err_status_replay_*. Restarting SRTP can resolve this.
1409 	 */
1410 	pjmedia_srtp_crypto tx, rx;
1411 	pj_status_t status;
1412 
1413 	/* Stop SRTP first, otherwise srtp_start() will maintain current
1414 	 * roll-over counter.
1415 	 */
1416 	pjmedia_transport_srtp_stop((pjmedia_transport*)srtp);
1417 
1418 	tx = srtp->tx_policy;
1419 	rx = srtp->rx_policy;
1420 	status = pjmedia_transport_srtp_start((pjmedia_transport*)srtp,
1421 					      &tx, &rx);
1422 	if (status != PJ_SUCCESS) {
1423 	    PJ_LOG(5,(srtp->pool->obj_name, "Failed to restart SRTP, err=%s",
1424 		      get_libsrtp_errstr(err)));
1425 	} else if (!srtp->bypass_srtp) {
1426 	    err = srtp_unprotect(srtp->srtp_rx_ctx, (pj_uint8_t*)pkt, &len);
1427 	}
1428     }
1429 
1430     if (err != srtp_err_status_ok) {
1431 	PJ_LOG(5,(srtp->pool->obj_name,
1432 		  "Failed to unprotect SRTP, pkt size=%d, err=%s",
1433 		  size, get_libsrtp_errstr(err)));
1434     } else {
1435 	cb = srtp->rtp_cb;
1436 	cb2 = srtp->rtp_cb2;
1437 	cb_data = srtp->user_data;
1438 
1439 	/* Save SSRC after successful SRTP unprotect */
1440 	srtp->rx_ssrc = ntohl(((pjmedia_rtp_hdr*)pkt)->ssrc);
1441     }
1442 
1443     pj_lock_release(srtp->mutex);
1444 
1445     if (cb2) {
1446         pjmedia_tp_cb_param param2 = *param;
1447         param2.user_data = cb_data;
1448         param2.pkt = pkt;
1449         param2.size = len;
1450         (*cb2)(&param2);
1451         param->rem_switch = param2.rem_switch;
1452     } else if (cb) {
1453 	(*cb)(cb_data, pkt, len);
1454     }
1455 }
1456 
1457 /*
1458  * This callback is called by transport when incoming rtcp is received
1459  */
srtp_rtcp_cb(void * user_data,void * pkt,pj_ssize_t size)1460 static void srtp_rtcp_cb( void *user_data, void *pkt, pj_ssize_t size)
1461 {
1462     transport_srtp *srtp = (transport_srtp *) user_data;
1463     int len = (int)size;
1464     srtp_err_status_t err;
1465     void (*cb)(void*, void*, pj_ssize_t) = NULL;
1466     void *cb_data = NULL;
1467 
1468     if (srtp->bypass_srtp) {
1469 	srtp->rtcp_cb(srtp->user_data, pkt, size);
1470 	return;
1471     }
1472 
1473     if (size < 0) {
1474 	return;
1475     }
1476 
1477     /* Make sure buffer is 32bit aligned */
1478     PJ_ASSERT_ON_FAIL( (((pj_ssize_t)pkt) & 0x03)==0, return );
1479 
1480     pj_lock_acquire(srtp->mutex);
1481 
1482     if (!srtp->session_inited) {
1483 	pj_lock_release(srtp->mutex);
1484 	return;
1485     }
1486     err = srtp_unprotect_rtcp(srtp->srtp_rx_ctx, (pj_uint8_t*)pkt, &len);
1487     if (err != srtp_err_status_ok) {
1488 	PJ_LOG(5,(srtp->pool->obj_name,
1489 		  "Failed to unprotect SRTCP, pkt size=%d, err=%s",
1490 		  size, get_libsrtp_errstr(err)));
1491     } else {
1492 	cb = srtp->rtcp_cb;
1493 	cb_data = srtp->user_data;
1494     }
1495 
1496     pj_lock_release(srtp->mutex);
1497 
1498     if (cb) {
1499 	(*cb)(cb_data, pkt, len);
1500     }
1501 }
1502 
1503 
transport_media_create(pjmedia_transport * tp,pj_pool_t * sdp_pool,unsigned options,const pjmedia_sdp_session * sdp_remote,unsigned media_index)1504 static pj_status_t transport_media_create(pjmedia_transport *tp,
1505 				          pj_pool_t *sdp_pool,
1506 					  unsigned options,
1507 				          const pjmedia_sdp_session *sdp_remote,
1508 					  unsigned media_index)
1509 {
1510     struct transport_srtp *srtp = (struct transport_srtp*) tp;
1511     unsigned member_tp_option;
1512     pj_status_t keying_status = PJ_SUCCESS;
1513     pj_status_t status;
1514     unsigned i;
1515 
1516     PJ_ASSERT_RETURN(tp, PJ_EINVAL);
1517 
1518     pj_bzero(&srtp->rx_policy_neg, sizeof(srtp->rx_policy_neg));
1519     pj_bzero(&srtp->tx_policy_neg, sizeof(srtp->tx_policy_neg));
1520 
1521     srtp->media_option = member_tp_option = options;
1522     srtp->offerer_side = (sdp_remote == NULL);
1523 
1524     if (srtp->offerer_side && srtp->setting.use == PJMEDIA_SRTP_DISABLED) {
1525 	/* If we are offerer and SRTP is disabled, simply bypass SRTP and
1526 	 * skip keying.
1527 	 */
1528 	srtp->bypass_srtp = PJ_TRUE;
1529 	srtp->keying_cnt = 0;
1530     } else {
1531 	/* If we are answerer and SRTP is disabled, we need to verify that
1532 	 * SRTP is disabled too in remote SDP, so we can't just skip keying.
1533 	 */
1534 	srtp->bypass_srtp = PJ_FALSE;
1535 	srtp->keying_cnt = srtp->all_keying_cnt;
1536 	for (i = 0; i < srtp->all_keying_cnt; ++i)
1537 	    srtp->keying[i] = srtp->all_keying[i];
1538 
1539 	member_tp_option |= PJMEDIA_TPMED_NO_TRANSPORT_CHECKING;
1540     }
1541 
1542     status = pjmedia_transport_media_create(srtp->member_tp, sdp_pool,
1543 					    member_tp_option, sdp_remote,
1544 					    media_index);
1545     if (status != PJ_SUCCESS)
1546 	return status;
1547 
1548     /* Invoke media_create() of all keying methods, keying actions for each
1549      * SRTP mode:
1550      * - DISABLED:
1551      *   - as offerer, nothing (keying is skipped).
1552      *   - as answerer, verify remote SDP, make sure it has SRTP disabled too,
1553      *     if not, return error.
1554      * - OPTIONAL:
1555      *   - as offerer, general initialization.
1556      *   - as answerer, optionally verify SRTP attr in remote SDP (if any).
1557      * - MANDATORY:
1558      *   - as offerer, general initialization.
1559      *   - as answerer, verify SRTP attr in remote SDP.
1560      */
1561     for (i=0; i < srtp->keying_cnt; ) {
1562 	pj_status_t st;
1563 	st = pjmedia_transport_media_create(srtp->keying[i], sdp_pool,
1564 					    options, sdp_remote,
1565 					    media_index);
1566 	if (st != PJ_SUCCESS) {
1567 	    /* This keying method returns error, remove it */
1568 	    pj_array_erase(srtp->keying, sizeof(srtp->keying[0]),
1569 			   srtp->keying_cnt, i);
1570 	    srtp->keying_cnt--;
1571 	    keying_status = st;
1572 	    continue;
1573 	} else if (srtp->offerer_side) {
1574 	    /* Currently we can send one keying only in outgoing offer */
1575 	    srtp->keying[0] = srtp->keying[i];
1576 	    srtp->keying_cnt = 1;
1577 	    break;
1578 	}
1579 
1580 	++i;
1581     }
1582 
1583     /* All keying method failed to process remote SDP? */
1584     if (srtp->keying_cnt == 0)
1585 	return keying_status;
1586 
1587     /* Bypass SRTP & skip keying as SRTP is disabled and verification on
1588      * remote SDP has been done.
1589      */
1590     if (srtp->setting.use == PJMEDIA_SRTP_DISABLED) {
1591 	srtp->bypass_srtp = PJ_TRUE;
1592 	srtp->keying_cnt = 0;
1593     }
1594 
1595     return PJ_SUCCESS;
1596 }
1597 
transport_encode_sdp(pjmedia_transport * tp,pj_pool_t * sdp_pool,pjmedia_sdp_session * sdp_local,const pjmedia_sdp_session * sdp_remote,unsigned media_index)1598 static pj_status_t transport_encode_sdp(pjmedia_transport *tp,
1599 					pj_pool_t *sdp_pool,
1600 					pjmedia_sdp_session *sdp_local,
1601 					const pjmedia_sdp_session *sdp_remote,
1602 					unsigned media_index)
1603 {
1604     struct transport_srtp *srtp = (struct transport_srtp*) tp;
1605     pj_status_t keying_status = PJ_SUCCESS;
1606     pj_status_t status;
1607     unsigned i;
1608 
1609     PJ_ASSERT_RETURN(tp && sdp_pool && sdp_local, PJ_EINVAL);
1610 
1611     pj_bzero(&srtp->rx_policy_neg, sizeof(srtp->rx_policy_neg));
1612     pj_bzero(&srtp->tx_policy_neg, sizeof(srtp->tx_policy_neg));
1613 
1614     srtp->offerer_side = (sdp_remote == NULL);
1615 
1616     if (!srtp->offerer_side && srtp->started) {
1617 	/* This is may be incoming reoffer that may change keying */
1618 	srtp->keying_cnt = srtp->all_keying_cnt;
1619 	for (i = 0; i < srtp->all_keying_cnt; ++i)
1620 	    srtp->keying[i] = srtp->all_keying[i];
1621     }
1622 
1623     status = pjmedia_transport_encode_sdp(srtp->member_tp, sdp_pool,
1624 					  sdp_local, sdp_remote, media_index);
1625     if (status != PJ_SUCCESS)
1626 	return status;
1627 
1628     /* Invoke encode_sdp() of all keying methods, keying actions for each
1629      * SRTP mode:
1630      * - DISABLED: nothing (keying is skipped)
1631      * - OPTIONAL:
1632      *   - as offerer, generate offer.
1633      *   - as answerer, if remote has the same SRTP keying in SDP, verify it,
1634      *     generate answer, start crypto nego.
1635      * - MANDATORY:
1636      *   - as offerer, generate offer.
1637      *   - as answerer, verify remote SDP, generate answer, start crypto nego.
1638      *
1639      * Note: because the SDP will be processed by other keying/components,
1640      *       keying must do verification on remote SDP first (e.g: keying
1641      *       is being used) before touching local SDP.
1642      */
1643     for (i=0; i < srtp->keying_cnt; ) {
1644 	pj_status_t st;
1645 	st = pjmedia_transport_encode_sdp(srtp->keying[i], sdp_pool,
1646 					  sdp_local, sdp_remote,
1647 					  media_index);
1648 	if (st != PJ_SUCCESS) {
1649 	    /* This keying method returns error, remove it */
1650 	    pj_array_erase(srtp->keying, sizeof(srtp->keying[0]),
1651 			   srtp->keying_cnt, i);
1652 	    srtp->keying_cnt--;
1653 	    keying_status = st;
1654 	    continue;
1655 	} else if (!srtp->offerer_side) {
1656 	    /* Answer with one keying only */
1657 	    srtp->keying[0] = srtp->keying[i];
1658 	    srtp->keying_cnt = 1;
1659 	    break;
1660 	}
1661 
1662 	i++;
1663     }
1664 
1665     /* All keying method failed to process remote SDP? */
1666     if (srtp->keying_cnt == 0) {
1667 	if (keying_status != PJ_SUCCESS) {
1668 	    DEACTIVATE_MEDIA(sdp_pool, sdp_local->media[media_index]);
1669 	}
1670 	return keying_status;
1671     }
1672 
1673     /* Bypass SRTP & skip keying as SRTP is disabled and verification on
1674      * remote SDP has been done.
1675      */
1676     if (srtp->setting.use == PJMEDIA_SRTP_DISABLED) {
1677 	srtp->bypass_srtp = PJ_TRUE;
1678 	srtp->keying_cnt = 0;
1679     }
1680 
1681     if (srtp->keying_cnt != 0) {
1682 	/* At this point for now, keying count should be 1 */
1683 	pj_assert(srtp->keying_cnt == 1);
1684 	PJ_LOG(4, (srtp->pool->obj_name, "SRTP uses keying method %s",
1685 		   ((int)srtp->keying[0]->type==PJMEDIA_SRTP_KEYING_SDES?
1686 		    "SDES":"DTLS-SRTP")));
1687     }
1688 
1689     return PJ_SUCCESS;
1690 }
1691 
1692 
transport_media_start(pjmedia_transport * tp,pj_pool_t * pool,const pjmedia_sdp_session * sdp_local,const pjmedia_sdp_session * sdp_remote,unsigned media_index)1693 static pj_status_t transport_media_start(pjmedia_transport *tp,
1694 				         pj_pool_t *pool,
1695 				         const pjmedia_sdp_session *sdp_local,
1696 				         const pjmedia_sdp_session *sdp_remote,
1697 				         unsigned media_index)
1698 {
1699     struct transport_srtp *srtp = (struct transport_srtp*) tp;
1700     pj_status_t keying_status = PJ_SUCCESS;
1701     pj_status_t status;
1702     unsigned i;
1703 
1704     PJ_ASSERT_RETURN(tp, PJ_EINVAL);
1705 
1706     /* At this point for now, keying count should be 0 or 1 */
1707     pj_assert(srtp->keying_cnt <= 1);
1708 
1709     srtp->started = PJ_TRUE;
1710 
1711     status = pjmedia_transport_media_start(srtp->member_tp, pool,
1712 					   sdp_local, sdp_remote,
1713 				           media_index);
1714     if (status != PJ_SUCCESS)
1715 	return status;
1716 
1717     /* Invoke media_start() of all keying methods, keying actions for each
1718      * SRTP mode:
1719      * - DISABLED: nothing (keying is skipped)
1720      * - OPTIONAL:
1721      *   - as offerer, if remote answer has the same SRTP keying in SDP,
1722      *     verify it and start crypto nego.
1723      *   - as answerer, start crypto nego if not yet (usually initated in
1724      *     encode_sdp()).
1725      * - MANDATORY:
1726      *   - as offerer, verify remote answer and start crypto nego.
1727      *   - as answerer, start crypto nego if not yet (usually initated in
1728      *     encode_sdp()).
1729      */
1730     for (i=0; i < srtp->keying_cnt; ) {
1731 	status = pjmedia_transport_media_start(srtp->keying[i], pool,
1732 					       sdp_local, sdp_remote,
1733 					       media_index);
1734 	if (status != PJ_SUCCESS) {
1735 	    /* This keying method returns error, remove it */
1736 	    pj_array_erase(srtp->keying, sizeof(srtp->keying[0]),
1737 			   srtp->keying_cnt, i);
1738 	    srtp->keying_cnt--;
1739 	    keying_status = status;
1740 	    continue;
1741 	}
1742 
1743 	if (!srtp_crypto_empty(&srtp->tx_policy_neg) &&
1744 	    !srtp_crypto_empty(&srtp->rx_policy_neg))
1745 	{
1746 	    /* SRTP nego is done */
1747 	    srtp->keying_cnt = 1;
1748 	    srtp->keying[0] = srtp->keying[i];
1749 	    srtp->keying_pending_cnt = 0;
1750 	    break;
1751 	}
1752 
1753 	i++;
1754     }
1755 
1756     /* All keying method failed to process remote SDP? */
1757     if (srtp->keying_cnt == 0)
1758 	return keying_status;
1759 
1760     /* If SRTP key is being negotiated, just return now.
1761      * The keying method should start the SRTP once keying nego is done.
1762      */
1763     if (srtp->keying_pending_cnt)
1764 	return PJ_SUCCESS;
1765 
1766     /* Start SRTP */
1767     status = start_srtp(srtp);
1768 
1769     return status;
1770 }
1771 
1772 
transport_media_stop(pjmedia_transport * tp)1773 static pj_status_t transport_media_stop(pjmedia_transport *tp)
1774 {
1775     struct transport_srtp *srtp = (struct transport_srtp*) tp;
1776     pj_status_t status;
1777     unsigned i;
1778 
1779     PJ_ASSERT_RETURN(tp, PJ_EINVAL);
1780 
1781     srtp->started = PJ_FALSE;
1782 
1783     /* Invoke media_stop() of all keying methods */
1784     for (i=0; i < srtp->keying_cnt; ++i) {
1785 	pjmedia_transport_media_stop(srtp->keying[i]);
1786     }
1787 
1788     /* Invoke media_stop() of member tp */
1789     status = pjmedia_transport_media_stop(srtp->member_tp);
1790     if (status != PJ_SUCCESS)
1791 	PJ_PERROR(4, (srtp->pool->obj_name, status,
1792 		      "SRTP failed stop underlying media transport."));
1793 
1794     /* Finally, stop SRTP */
1795     return pjmedia_transport_srtp_stop(tp);
1796 }
1797 
1798 
1799 /* Utility */
pjmedia_transport_srtp_decrypt_pkt(pjmedia_transport * tp,pj_bool_t is_rtp,void * pkt,int * pkt_len)1800 PJ_DEF(pj_status_t) pjmedia_transport_srtp_decrypt_pkt(pjmedia_transport *tp,
1801 						       pj_bool_t is_rtp,
1802 						       void *pkt,
1803 						       int *pkt_len)
1804 {
1805     transport_srtp *srtp = (transport_srtp *)tp;
1806     srtp_err_status_t err;
1807 
1808     if (srtp->bypass_srtp)
1809 	return PJ_SUCCESS;
1810 
1811     PJ_ASSERT_RETURN(tp && pkt && (*pkt_len>0), PJ_EINVAL);
1812     PJ_ASSERT_RETURN(srtp->session_inited, PJ_EINVALIDOP);
1813 
1814     /* Make sure buffer is 32bit aligned */
1815     PJ_ASSERT_ON_FAIL( (((pj_ssize_t)pkt) & 0x03)==0, return PJ_EINVAL);
1816 
1817     pj_lock_acquire(srtp->mutex);
1818 
1819     if (!srtp->session_inited) {
1820 	pj_lock_release(srtp->mutex);
1821 	return PJ_EINVALIDOP;
1822     }
1823 
1824     if (is_rtp)
1825 	err = srtp_unprotect(srtp->srtp_rx_ctx, pkt, pkt_len);
1826     else
1827 	err = srtp_unprotect_rtcp(srtp->srtp_rx_ctx, pkt, pkt_len);
1828 
1829     if (err != srtp_err_status_ok) {
1830 	PJ_LOG(5,(srtp->pool->obj_name,
1831 		  "Failed to unprotect SRTP, pkt size=%d, err=%s",
1832 		  *pkt_len, get_libsrtp_errstr(err)));
1833     }
1834 
1835     pj_lock_release(srtp->mutex);
1836 
1837     return (err==srtp_err_status_ok) ? PJ_SUCCESS :
1838 				       PJMEDIA_ERRNO_FROM_LIBSRTP(err);
1839 }
1840 
1841 #endif
1842