Removing registrar_expire from basic-pbx config
[asterisk/asterisk.git] / res / res_srtp.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2005, Mikael Magnusson
5  *
6  * Mikael Magnusson <mikma@users.sourceforge.net>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  *
18  * Builds on libSRTP http://srtp.sourceforge.net
19  */
20
21 /*! \file res_srtp.c
22  *
23  * \brief Secure RTP (SRTP)
24  *
25  * Secure RTP (SRTP)
26  * Specified in RFC 3711.
27  *
28  * \author Mikael Magnusson <mikma@users.sourceforge.net>
29  */
30
31 /*** MODULEINFO
32         <depend>srtp</depend>
33         <use type="external">openssl</use>
34         <support_level>core</support_level>
35 ***/
36
37 /* See https://wiki.asterisk.org/wiki/display/AST/Secure+Calling */
38
39 #include "asterisk.h"                   /* for NULL, size_t, memcpy, etc */
40
41 #include <math.h>                       /* for pow */
42
43 #if HAVE_SRTP_VERSION > 1
44 # include <srtp2/srtp.h>
45 # include "srtp/srtp_compat.h"
46 # include <openssl/rand.h>
47 #else
48 # include <srtp/srtp.h>
49 # ifdef HAVE_OPENSSL
50 #  include <openssl/rand.h>
51 # else
52 #  include <srtp/crypto_kernel.h>
53 # endif
54 #endif
55
56 #include "asterisk/astobj2.h"           /* for ao2_t_ref, etc */
57 #include "asterisk/frame.h"             /* for AST_FRIENDLY_OFFSET */
58 #include "asterisk/logger.h"            /* for ast_log, ast_debug, etc */
59 #include "asterisk/module.h"            /* for ast_module_info, etc */
60 #include "asterisk/sdp_srtp.h"
61 #include "asterisk/res_srtp.h"          /* for ast_srtp_cb, ast_srtp_suite, etc */
62 #include "asterisk/rtp_engine.h"        /* for ast_rtp_engine_register_srtp, etc */
63 #include "asterisk/utils.h"             /* for ast_free, ast_calloc */
64
65 struct ast_srtp {
66         struct ast_rtp_instance *rtp;
67         struct ao2_container *policies;
68         srtp_t session;
69         const struct ast_srtp_cb *cb;
70         void *data;
71         int warned;
72         unsigned char buf[8192 + AST_FRIENDLY_OFFSET];
73         unsigned char rtcpbuf[8192 + AST_FRIENDLY_OFFSET];
74 };
75
76 struct ast_srtp_policy {
77         srtp_policy_t sp;
78 };
79
80 /*! Tracks whether or not we've initialized the libsrtp library */
81 static int g_initialized = 0;
82
83 /* SRTP functions */
84 static int ast_srtp_create(struct ast_srtp **srtp, struct ast_rtp_instance *rtp, struct ast_srtp_policy *policy);
85 static int ast_srtp_replace(struct ast_srtp **srtp, struct ast_rtp_instance *rtp, struct ast_srtp_policy *policy);
86 static void ast_srtp_destroy(struct ast_srtp *srtp);
87 static int ast_srtp_add_stream(struct ast_srtp *srtp, struct ast_srtp_policy *policy);
88 static int ast_srtp_change_source(struct ast_srtp *srtp, unsigned int from_ssrc, unsigned int to_ssrc);
89
90 static int ast_srtp_unprotect(struct ast_srtp *srtp, void *buf, int *len, int rtcp);
91 static int ast_srtp_protect(struct ast_srtp *srtp, void **buf, int *len, int rtcp);
92 static void ast_srtp_set_cb(struct ast_srtp *srtp, const struct ast_srtp_cb *cb, void *data);
93 static int ast_srtp_get_random(unsigned char *key, size_t len);
94
95 /* Policy functions */
96 static struct ast_srtp_policy *ast_srtp_policy_alloc(void);
97 static void ast_srtp_policy_destroy(struct ast_srtp_policy *policy);
98 static int ast_srtp_policy_set_suite(struct ast_srtp_policy *policy, enum ast_srtp_suite suite);
99 static int ast_srtp_policy_set_master_key(struct ast_srtp_policy *policy, const unsigned char *key, size_t key_len, const unsigned char *salt, size_t salt_len);
100 static void ast_srtp_policy_set_ssrc(struct ast_srtp_policy *policy, unsigned long ssrc, int inbound);
101
102 static struct ast_srtp_res srtp_res = {
103         .create = ast_srtp_create,
104         .replace = ast_srtp_replace,
105         .destroy = ast_srtp_destroy,
106         .add_stream = ast_srtp_add_stream,
107         .change_source = ast_srtp_change_source,
108         .set_cb = ast_srtp_set_cb,
109         .unprotect = ast_srtp_unprotect,
110         .protect = ast_srtp_protect,
111         .get_random = ast_srtp_get_random
112 };
113
114 static struct ast_srtp_policy_res policy_res = {
115         .alloc = ast_srtp_policy_alloc,
116         .destroy = ast_srtp_policy_destroy,
117         .set_suite = ast_srtp_policy_set_suite,
118         .set_master_key = ast_srtp_policy_set_master_key,
119         .set_ssrc = ast_srtp_policy_set_ssrc
120 };
121
122 static const char *srtp_errstr(int err)
123 {
124         switch(err) {
125         case err_status_ok:
126                 return "nothing to report";
127         case err_status_fail:
128                 return "unspecified failure";
129         case err_status_bad_param:
130                 return "unsupported parameter";
131         case err_status_alloc_fail:
132                 return "couldn't allocate memory";
133         case err_status_dealloc_fail:
134                 return "couldn't deallocate properly";
135         case err_status_init_fail:
136                 return "couldn't initialize";
137         case err_status_terminus:
138                 return "can't process as much data as requested";
139         case err_status_auth_fail:
140                 return "authentication failure";
141         case err_status_cipher_fail:
142                 return "cipher failure";
143         case err_status_replay_fail:
144                 return "replay check failed (bad index)";
145         case err_status_replay_old:
146                 return "replay check failed (index too old)";
147         case err_status_algo_fail:
148                 return "algorithm failed test routine";
149         case err_status_no_such_op:
150                 return "unsupported operation";
151         case err_status_no_ctx:
152                 return "no appropriate context found";
153         case err_status_cant_check:
154                 return "unable to perform desired validation";
155         case err_status_key_expired:
156                 return "can't use key any more";
157         default:
158                 return "unknown";
159         }
160 }
161
162 static int policy_hash_fn(const void *obj, const int flags)
163 {
164         const struct ast_srtp_policy *policy = obj;
165
166         return policy->sp.ssrc.type == ssrc_specific ? policy->sp.ssrc.value : policy->sp.ssrc.type;
167 }
168
169 static int policy_cmp_fn(void *obj, void *arg, int flags)
170 {
171         const struct ast_srtp_policy *one = obj, *two = arg;
172
173         return one->sp.ssrc.type == two->sp.ssrc.type && one->sp.ssrc.value == two->sp.ssrc.value;
174 }
175
176 static struct ast_srtp_policy *find_policy(struct ast_srtp *srtp, const srtp_policy_t *policy, int flags)
177 {
178         struct ast_srtp_policy tmp = {
179                 .sp = {
180                         .ssrc.type = policy->ssrc.type,
181                         .ssrc.value = policy->ssrc.value,
182                 },
183         };
184
185         return ao2_t_find(srtp->policies, &tmp, flags, "Looking for policy");
186 }
187
188 static struct ast_srtp *res_srtp_new(void)
189 {
190         struct ast_srtp *srtp;
191
192         if (!(srtp = ast_calloc(1, sizeof(*srtp)))) {
193                 ast_log(LOG_ERROR, "Unable to allocate memory for srtp\n");
194                 return NULL;
195         }
196
197         srtp->policies = ao2_t_container_alloc_hash(AO2_ALLOC_OPT_LOCK_MUTEX, 0, 5,
198                 policy_hash_fn, NULL, policy_cmp_fn, "SRTP policy container");
199         if (!srtp->policies) {
200                 ast_free(srtp);
201                 return NULL;
202         }
203
204         srtp->warned = 1;
205
206         return srtp;
207 }
208
209 /*
210   struct ast_srtp_policy
211 */
212 static void srtp_event_cb(srtp_event_data_t *data)
213 {
214         switch (data->event) {
215         case event_ssrc_collision:
216                 ast_debug(1, "SSRC collision\n");
217                 break;
218         case event_key_soft_limit:
219                 ast_debug(1, "event_key_soft_limit\n");
220                 break;
221         case event_key_hard_limit:
222                 ast_debug(1, "event_key_hard_limit\n");
223                 break;
224         case event_packet_index_limit:
225                 ast_debug(1, "event_packet_index_limit\n");
226                 break;
227         }
228 }
229
230 static void ast_srtp_policy_set_ssrc(struct ast_srtp_policy *policy,
231                 unsigned long ssrc, int inbound)
232 {
233         if (ssrc) {
234                 policy->sp.ssrc.type = ssrc_specific;
235                 policy->sp.ssrc.value = ssrc;
236         } else {
237                 policy->sp.ssrc.type = inbound ? ssrc_any_inbound : ssrc_any_outbound;
238         }
239 }
240
241 static void policy_destructor(void *obj)
242 {
243         struct ast_srtp_policy *policy = obj;
244
245         if (policy->sp.key) {
246                 ast_free(policy->sp.key);
247                 policy->sp.key = NULL;
248         }
249 }
250
251 static struct ast_srtp_policy *ast_srtp_policy_alloc()
252 {
253         struct ast_srtp_policy *tmp;
254
255         if (!(tmp = ao2_t_alloc(sizeof(*tmp), policy_destructor, "Allocating policy"))) {
256                 ast_log(LOG_ERROR, "Unable to allocate memory for srtp_policy\n");
257         }
258
259         return tmp;
260 }
261
262 static void ast_srtp_policy_destroy(struct ast_srtp_policy *policy)
263 {
264         ao2_t_ref(policy, -1, "Destroying policy");
265 }
266
267 static int policy_set_suite(crypto_policy_t *p, enum ast_srtp_suite suite)
268 {
269         switch (suite) {
270         case AST_AES_CM_128_HMAC_SHA1_80:
271                 crypto_policy_set_aes_cm_128_hmac_sha1_80(p);
272                 return 0;
273
274         case AST_AES_CM_128_HMAC_SHA1_32:
275                 crypto_policy_set_aes_cm_128_hmac_sha1_32(p);
276                 return 0;
277
278 #ifdef HAVE_SRTP_192
279         case AST_AES_CM_192_HMAC_SHA1_80:
280                 crypto_policy_set_aes_cm_192_hmac_sha1_80(p);
281                 return 0;
282
283         case AST_AES_CM_192_HMAC_SHA1_32:
284                 crypto_policy_set_aes_cm_192_hmac_sha1_32(p);
285                 return 0;
286 #endif
287 #ifdef HAVE_SRTP_256
288         case AST_AES_CM_256_HMAC_SHA1_80:
289                 crypto_policy_set_aes_cm_256_hmac_sha1_80(p);
290                 return 0;
291
292         case AST_AES_CM_256_HMAC_SHA1_32:
293                 crypto_policy_set_aes_cm_256_hmac_sha1_32(p);
294                 return 0;
295 #endif
296 #ifdef HAVE_SRTP_GCM
297         case AST_AES_GCM_128:
298                 crypto_policy_set_aes_gcm_128_16_auth(p);
299                 return 0;
300
301         case AST_AES_GCM_256:
302                 crypto_policy_set_aes_gcm_256_16_auth(p);
303                 return 0;
304
305         case AST_AES_GCM_128_8:
306                 crypto_policy_set_aes_gcm_128_8_auth(p);
307                 return 0;
308
309         case AST_AES_GCM_256_8:
310                 crypto_policy_set_aes_gcm_256_8_auth(p);
311                 return 0;
312 #endif
313
314         default:
315                 ast_log(LOG_ERROR, "Invalid crypto suite: %u\n", suite);
316                 return -1;
317         }
318 }
319
320 static int ast_srtp_policy_set_suite(struct ast_srtp_policy *policy, enum ast_srtp_suite suite)
321 {
322         return policy_set_suite(&policy->sp.rtp, suite) | policy_set_suite(&policy->sp.rtcp, suite);
323 }
324
325 static int ast_srtp_policy_set_master_key(struct ast_srtp_policy *policy, const unsigned char *key, size_t key_len, const unsigned char *salt, size_t salt_len)
326 {
327         size_t size = key_len + salt_len;
328         unsigned char *master_key;
329
330         if (policy->sp.key) {
331                 ast_free(policy->sp.key);
332                 policy->sp.key = NULL;
333         }
334
335         if (!(master_key = ast_calloc(1, size))) {
336                 return -1;
337         }
338
339         memcpy(master_key, key, key_len);
340         memcpy(master_key + key_len, salt, salt_len);
341
342         policy->sp.key = master_key;
343
344         return 0;
345 }
346
347 static int ast_srtp_get_random(unsigned char *key, size_t len)
348 {
349 #ifdef HAVE_OPENSSL
350         return RAND_bytes(key, len) > 0 ? 0: -1;
351 #else
352         return crypto_get_random(key, len) != err_status_ok ? -1: 0;
353 #endif
354 }
355
356 static void ast_srtp_set_cb(struct ast_srtp *srtp, const struct ast_srtp_cb *cb, void *data)
357 {
358         if (!srtp) {
359                 return;
360         }
361
362         srtp->cb = cb;
363         srtp->data = data;
364 }
365
366 /* Vtable functions */
367 static int ast_srtp_unprotect(struct ast_srtp *srtp, void *buf, int *len, int rtcp)
368 {
369         int res = 0;
370         int i;
371         int retry = 0;
372         struct ast_rtp_instance_stats stats = {0,};
373
374 tryagain:
375
376         for (i = 0; i < 2; i++) {
377                 res = rtcp ? srtp_unprotect_rtcp(srtp->session, buf, len) : srtp_unprotect(srtp->session, buf, len);
378                 if (res != err_status_no_ctx) {
379                         break;
380                 }
381
382                 if (srtp->cb && srtp->cb->no_ctx) {
383                         if (ast_rtp_instance_get_stats(srtp->rtp, &stats, AST_RTP_INSTANCE_STAT_REMOTE_SSRC)) {
384                                 break;
385                         }
386                         if (srtp->cb->no_ctx(srtp->rtp, stats.remote_ssrc, srtp->data) < 0) {
387                                 break;
388                         }
389                 } else {
390                         break;
391                 }
392         }
393
394         if (retry == 0  && res == err_status_replay_old) {
395                 ast_log(AST_LOG_NOTICE, "SRTP unprotect failed with %s, retrying\n", srtp_errstr(res));
396
397                 if (srtp->session) {
398                         struct ast_srtp_policy *policy;
399                         struct ao2_iterator it;
400                         int policies_count;
401
402                         /* dealloc first */
403                         ast_debug(5, "SRTP destroy before re-create\n");
404                         srtp_dealloc(srtp->session);
405
406                         /* get the count */
407                         policies_count = ao2_container_count(srtp->policies);
408
409                         /* get the first to build up */
410                         it = ao2_iterator_init(srtp->policies, 0);
411                         policy = ao2_iterator_next(&it);
412
413                         ast_debug(5, "SRTP try to re-create\n");
414                         if (policy) {
415                                 int res_srtp_create = srtp_create(&srtp->session, &policy->sp);
416                                 if (res_srtp_create == err_status_ok) {
417                                         ast_debug(5, "SRTP re-created with first policy\n");
418                                         ao2_t_ref(policy, -1, "Unreffing first policy for re-creating srtp session");
419
420                                         /* if we have more than one policy, add them */
421                                         if (policies_count > 1) {
422                                                 ast_debug(5, "Add all the other %d policies\n",
423                                                         policies_count - 1);
424                                                 while ((policy = ao2_iterator_next(&it))) {
425                                                         srtp_add_stream(srtp->session, &policy->sp);
426                                                         ao2_t_ref(policy, -1, "Unreffing n-th policy for re-creating srtp session");
427                                                 }
428                                         }
429
430                                         retry++;
431                                         ao2_iterator_destroy(&it);
432                                         goto tryagain;
433                                 }
434                                 ast_log(LOG_ERROR, "SRTP session could not be re-created after unprotect failure: %s\n", srtp_errstr(res_srtp_create));
435
436                                 /* If srtp_create() fails with a previously alloced session, it will have been dealloced before returning. */
437                                 srtp->session = NULL;
438
439                                 ao2_t_ref(policy, -1, "Unreffing first policy after srtp_create failed");
440                         }
441                         ao2_iterator_destroy(&it);
442                 }
443         }
444
445         if (!srtp->session) {
446                 errno = EINVAL;
447                 return -1;
448         }
449
450         if (res != err_status_ok && res != err_status_replay_fail ) {
451                 /*
452                  * Authentication failures happen when an active attacker tries to
453                  * insert malicious RTP packets. Furthermore, authentication failures
454                  * happen, when the other party encrypts the sRTP data in an unexpected
455                  * way. This happens quite often with RTCP. Therefore, when you see
456                  * authentication failures, try to identify the implementation
457                  * (author and product name) used by your other party. Try to investigate
458                  * whether they use a custom library or an outdated version of libSRTP.
459                  */
460                 if (rtcp) {
461                         ast_verb(2, "SRTCP unprotect failed on SSRC %u because of %s\n",
462                                 ast_rtp_instance_get_ssrc(srtp->rtp), srtp_errstr(res));
463                 } else {
464                         if ((srtp->warned >= 10) && !((srtp->warned - 10) % 150)) {
465                                 ast_verb(2, "SRTP unprotect failed on SSRC %u because of %s %d\n",
466                                         ast_rtp_instance_get_ssrc(srtp->rtp), srtp_errstr(res), srtp->warned);
467                                 srtp->warned = 11;
468                         } else {
469                                 srtp->warned++;
470                         }
471                 }
472                 errno = EAGAIN;
473                 return -1;
474         }
475
476         return *len;
477 }
478
479 static int ast_srtp_protect(struct ast_srtp *srtp, void **buf, int *len, int rtcp)
480 {
481         int res;
482         unsigned char *localbuf;
483
484         if ((*len + SRTP_MAX_TRAILER_LEN) > sizeof(srtp->buf)) {
485                 return -1;
486         }
487
488         localbuf = rtcp ? srtp->rtcpbuf : srtp->buf;
489
490         memcpy(localbuf, *buf, *len);
491
492         if ((res = rtcp ? srtp_protect_rtcp(srtp->session, localbuf, len) : srtp_protect(srtp->session, localbuf, len)) != err_status_ok && res != err_status_replay_fail) {
493                 ast_log(LOG_WARNING, "SRTP protect: %s\n", srtp_errstr(res));
494                 return -1;
495         }
496
497         *buf = localbuf;
498         return *len;
499 }
500
501 static int ast_srtp_create(struct ast_srtp **srtp, struct ast_rtp_instance *rtp, struct ast_srtp_policy *policy)
502 {
503         struct ast_srtp *temp;
504
505         if (!(temp = res_srtp_new())) {
506                 return -1;
507         }
508         ast_module_ref(ast_module_info->self);
509
510         /* Any failures after this point can use ast_srtp_destroy to destroy the instance */
511         if (srtp_create(&temp->session, &policy->sp) != err_status_ok) {
512                 /* Session either wasn't created or was created and dealloced. */
513                 temp->session = NULL;
514                 ast_srtp_destroy(temp);
515                 return -1;
516         }
517
518         temp->rtp = rtp;
519         *srtp = temp;
520
521         ao2_t_link((*srtp)->policies, policy, "Created initial policy");
522
523         return 0;
524 }
525
526 static int ast_srtp_replace(struct ast_srtp **srtp, struct ast_rtp_instance *rtp, struct ast_srtp_policy *policy)
527 {
528         if ((*srtp) != NULL) {
529                 ast_srtp_destroy(*srtp);
530         }
531         return ast_srtp_create(srtp, rtp, policy);
532 }
533
534 static void ast_srtp_destroy(struct ast_srtp *srtp)
535 {
536         if (srtp->session) {
537                 srtp_dealloc(srtp->session);
538         }
539
540         ao2_t_callback(srtp->policies, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "Unallocate policy");
541         ao2_t_ref(srtp->policies, -1, "Destroying container");
542
543         ast_free(srtp);
544         ast_module_unref(ast_module_info->self);
545 }
546
547 static int ast_srtp_add_stream(struct ast_srtp *srtp, struct ast_srtp_policy *policy)
548 {
549         struct ast_srtp_policy *match;
550
551         /* For existing streams, replace if its an SSRC stream, or bail if its a wildcard */
552         if ((match = find_policy(srtp, &policy->sp, OBJ_POINTER))) {
553                 if (policy->sp.ssrc.type != ssrc_specific) {
554                         ast_log(AST_LOG_WARNING, "Cannot replace an existing wildcard policy\n");
555                         ao2_t_ref(match, -1, "Unreffing already existing policy");
556                         return -1;
557                 } else {
558                         if (srtp_remove_stream(srtp->session, match->sp.ssrc.value) != err_status_ok) {
559                                 ast_log(AST_LOG_WARNING, "Failed to remove SRTP stream for SSRC %u\n", match->sp.ssrc.value);
560                         }
561                         ao2_t_unlink(srtp->policies, match, "Remove existing match policy");
562                         ao2_t_ref(match, -1, "Unreffing already existing policy");
563                 }
564         }
565
566         ast_debug(3, "Adding new policy for %s %u\n",
567                 policy->sp.ssrc.type == ssrc_specific ? "SSRC" : "type",
568                 policy->sp.ssrc.type == ssrc_specific ? policy->sp.ssrc.value : policy->sp.ssrc.type);
569         if (srtp_add_stream(srtp->session, &policy->sp) != err_status_ok) {
570                 ast_log(AST_LOG_WARNING, "Failed to add SRTP stream for %s %u\n",
571                         policy->sp.ssrc.type == ssrc_specific ? "SSRC" : "type",
572                         policy->sp.ssrc.type == ssrc_specific ? policy->sp.ssrc.value : policy->sp.ssrc.type);
573                 return -1;
574         }
575
576         ao2_t_link(srtp->policies, policy, "Added additional stream");
577
578         return 0;
579 }
580
581 static int ast_srtp_change_source(struct ast_srtp *srtp, unsigned int from_ssrc, unsigned int to_ssrc)
582 {
583         struct ast_srtp_policy *match;
584         struct srtp_policy_t sp = {
585                 .ssrc.type = ssrc_specific,
586                 .ssrc.value = from_ssrc,
587         };
588         err_status_t status;
589
590         /* If we find a match, return and unlink it from the container so we
591          * can change the SSRC (which is part of the hash) and then have
592          * ast_srtp_add_stream link it back in if all is well */
593         if ((match = find_policy(srtp, &sp, OBJ_POINTER | OBJ_UNLINK))) {
594                 match->sp.ssrc.value = to_ssrc;
595                 if (ast_srtp_add_stream(srtp, match)) {
596                         ast_log(LOG_WARNING, "Couldn't add stream\n");
597                 } else if ((status = srtp_remove_stream(srtp->session, from_ssrc))) {
598                         ast_debug(3, "Couldn't remove stream (%u)\n", status);
599                 }
600                 ao2_t_ref(match, -1, "Unreffing found policy in change_source");
601         }
602
603         return 0;
604 }
605
606 struct ast_sdp_crypto {
607         char *a_crypto;
608         unsigned char local_key[SRTP_MAX_KEY_LEN];
609         int tag;
610         char local_key64[((SRTP_MAX_KEY_LEN) * 8 + 5) / 6 + 1];
611         unsigned char remote_key[SRTP_MAX_KEY_LEN];
612         int key_len;
613 };
614
615 static void res_sdp_crypto_dtor(struct ast_sdp_crypto *crypto)
616 {
617         if (crypto) {
618                 ast_free(crypto->a_crypto);
619                 crypto->a_crypto = NULL;
620                 ast_free(crypto);
621
622                 ast_module_unref(ast_module_info->self);
623         }
624 }
625
626 static struct ast_sdp_crypto *crypto_init_keys(struct ast_sdp_crypto *p, const int key_len)
627 {
628         unsigned char remote_key[key_len];
629
630         if (srtp_res.get_random(p->local_key, key_len) < 0) {
631                 return NULL;
632         }
633
634         ast_base64encode(p->local_key64, p->local_key, key_len, sizeof(p->local_key64));
635
636         p->key_len = ast_base64decode(remote_key, p->local_key64, sizeof(remote_key));
637
638         if (p->key_len != key_len) {
639                 ast_log(LOG_ERROR, "base64 encode/decode bad len %d != %d\n", p->key_len, key_len);
640                 return NULL;
641         }
642
643         if (memcmp(remote_key, p->local_key, p->key_len)) {
644                 ast_log(LOG_ERROR, "base64 encode/decode bad key\n");
645                 return NULL;
646         }
647
648         ast_debug(1 , "local_key64 %s len %zu\n", p->local_key64, strlen(p->local_key64));
649
650         return p;
651 }
652
653 static struct ast_sdp_crypto *sdp_crypto_alloc(const int key_len)
654 {
655         struct ast_sdp_crypto *p, *result;
656
657         if (!(p = ast_calloc(1, sizeof(*p)))) {
658                 return NULL;
659         }
660         p->tag = 1;
661         ast_module_ref(ast_module_info->self);
662
663         /* default is a key which uses AST_AES_CM_128_HMAC_SHA1_xx */
664         result = crypto_init_keys(p, key_len);
665         if (!result) {
666                 res_sdp_crypto_dtor(p);
667         }
668
669         return result;
670 }
671
672 static struct ast_sdp_crypto *res_sdp_crypto_alloc(void)
673 {
674         return sdp_crypto_alloc(SRTP_MASTER_KEY_LEN);
675 }
676
677 static int res_sdp_crypto_build_offer(struct ast_sdp_crypto *p, int taglen)
678 {
679         int res;
680
681         /* Rebuild the crypto line */
682         ast_free(p->a_crypto);
683         p->a_crypto = NULL;
684
685         if ((taglen & 0x007f) == 8) {
686                 res = ast_asprintf(&p->a_crypto, "%d AEAD_AES_%d_GCM_%d inline:%s",
687                         p->tag, 128 + ((taglen & 0x0300) >> 2), taglen & 0x007f, p->local_key64);
688         } else if ((taglen & 0x007f) == 16) {
689                 res = ast_asprintf(&p->a_crypto, "%d AEAD_AES_%d_GCM inline:%s",
690                         p->tag, 128 + ((taglen & 0x0300) >> 2), p->local_key64);
691         } else if ((taglen & 0x0300) && !(taglen & 0x0080)) {
692                 res = ast_asprintf(&p->a_crypto, "%d AES_%d_CM_HMAC_SHA1_%d inline:%s",
693                         p->tag, 128 + ((taglen & 0x0300) >> 2), taglen & 0x007f, p->local_key64);
694         } else {
695                 res = ast_asprintf(&p->a_crypto, "%d AES_CM_%d_HMAC_SHA1_%d inline:%s",
696                         p->tag, 128 + ((taglen & 0x0300) >> 2), taglen & 0x007f, p->local_key64);
697         }
698         if (res == -1 || !p->a_crypto) {
699                 ast_log(LOG_ERROR, "Could not allocate memory for crypto line\n");
700                 return -1;
701         }
702
703         ast_debug(1, "Crypto line: a=crypto:%s\n", p->a_crypto);
704
705         return 0;
706 }
707
708 static int set_crypto_policy(struct ast_srtp_policy *policy, int suite_val, const unsigned char *master_key, int key_len, unsigned long ssrc, int inbound)
709 {
710         if (policy_res.set_master_key(policy, master_key, key_len, NULL, 0) < 0) {
711                 return -1;
712         }
713
714         if (policy_res.set_suite(policy, suite_val)) {
715                 ast_log(LOG_WARNING, "Could not set remote SRTP suite\n");
716                 return -1;
717         }
718
719         policy_res.set_ssrc(policy, ssrc, inbound);
720
721         return 0;
722 }
723
724 static int crypto_activate(struct ast_sdp_crypto *p, int suite_val, unsigned char *remote_key, int key_len, struct ast_rtp_instance *rtp)
725 {
726         struct ast_srtp_policy *local_policy = NULL;
727         struct ast_srtp_policy *remote_policy = NULL;
728         struct ast_rtp_instance_stats stats = {0,};
729         int res = -1;
730
731         if (!p) {
732                 return -1;
733         }
734
735         if (!(local_policy = policy_res.alloc())) {
736                 return -1;
737         }
738
739         if (!(remote_policy = policy_res.alloc())) {
740                 goto err;
741         }
742
743         if (ast_rtp_instance_get_stats(rtp, &stats, AST_RTP_INSTANCE_STAT_LOCAL_SSRC)) {
744                 goto err;
745         }
746
747         if (set_crypto_policy(local_policy, suite_val, p->local_key, key_len, stats.local_ssrc, 0) < 0) {
748                 goto err;
749         }
750
751         if (set_crypto_policy(remote_policy, suite_val, remote_key, key_len, 0, 1) < 0) {
752                 goto err;
753         }
754
755         /* Add the SRTP policies */
756         if (ast_rtp_instance_add_srtp_policy(rtp, remote_policy, local_policy, 0)) {
757                 ast_log(LOG_WARNING, "Could not set SRTP policies\n");
758                 goto err;
759         }
760
761         ast_debug(1 , "SRTP policy activated\n");
762         res = 0;
763
764 err:
765         if (local_policy) {
766                 policy_res.destroy(local_policy);
767         }
768
769         if (remote_policy) {
770                 policy_res.destroy(remote_policy);
771         }
772
773         return res;
774 }
775
776 static int res_sdp_crypto_parse_offer(struct ast_rtp_instance *rtp, struct ast_sdp_srtp *srtp, const char *attr)
777 {
778         char *str = NULL;
779         char *tag = NULL;
780         char *suite = NULL;
781         char *key_params = NULL;
782         char *key_param = NULL;
783         char *session_params = NULL;
784         char *key_salt = NULL;       /* The actual master key and key salt */
785         char *lifetime = NULL;       /* Key lifetime (# of RTP packets) */
786         char *mki = NULL;            /* Master Key Index */
787         int found = 0;
788         int key_len_from_sdp;
789         int key_len_expected;
790         int tag_from_sdp;
791         int suite_val = 0;
792         unsigned char remote_key[SRTP_MAX_KEY_LEN];
793         int taglen;
794         double sdes_lifetime;
795         struct ast_sdp_crypto *crypto;
796         struct ast_sdp_srtp *tmp;
797
798         str = ast_strdupa(attr);
799
800         tag = strsep(&str, " ");
801         suite = strsep(&str, " ");
802         key_params = strsep(&str, " ");
803         session_params = strsep(&str, " ");
804
805         if (!tag || !suite) {
806                 ast_log(LOG_WARNING, "Unrecognized crypto attribute a=%s\n", attr);
807                 return -1;
808         }
809
810         /* RFC4568 9.1 - tag is 1-9 digits */
811         if (sscanf(tag, "%30d", &tag_from_sdp) != 1 || tag_from_sdp < 0 || tag_from_sdp > 999999999) {
812                 ast_log(LOG_WARNING, "Unacceptable a=crypto tag: %s\n", tag);
813                 return -1;
814         }
815
816         if (!ast_strlen_zero(session_params)) {
817                 ast_log(LOG_WARNING, "Unsupported crypto parameters: %s\n", session_params);
818                 return -1;
819         }
820
821         /* On egress, Asterisk sent several crypto lines in the SIP/SDP offer
822            The remote party might have choosen another line than the first */
823         for (tmp = srtp; tmp && tmp->crypto && tmp->crypto->tag != tag_from_sdp;) {
824                 tmp = AST_LIST_NEXT(tmp, sdp_srtp_list);
825         }
826         if (tmp) { /* tag matched an already created crypto line */
827                 unsigned int flags = tmp->flags;
828
829                 /* Make that crypto line the head of the list, not by changing the
830                    list structure but by exchanging the content of the list members */
831                 crypto = tmp->crypto;
832                 tmp->crypto = srtp->crypto;
833                 tmp->flags = srtp->flags;
834                 srtp->crypto = crypto;
835                 srtp->flags = flags;
836         } else {
837                 crypto = srtp->crypto;
838                 crypto->tag = tag_from_sdp;
839         }
840
841         if (!strcmp(suite, "AES_CM_128_HMAC_SHA1_80")) {
842                 suite_val = AST_AES_CM_128_HMAC_SHA1_80;
843                 ast_set_flag(srtp, AST_SRTP_CRYPTO_TAG_80);
844                 key_len_expected = 30;
845         } else if (!strcmp(suite, "AES_CM_128_HMAC_SHA1_32")) {
846                 suite_val = AST_AES_CM_128_HMAC_SHA1_32;
847                 ast_set_flag(srtp, AST_SRTP_CRYPTO_TAG_32);
848                 key_len_expected = 30;
849 #ifdef HAVE_SRTP_192
850         } else if (!strcmp(suite, "AES_192_CM_HMAC_SHA1_80")) {
851                 suite_val = AST_AES_CM_192_HMAC_SHA1_80;
852                 ast_set_flag(srtp, AST_SRTP_CRYPTO_TAG_80);
853                 ast_set_flag(srtp, AST_SRTP_CRYPTO_AES_192);
854                 key_len_expected = 38;
855         } else if (!strcmp(suite, "AES_192_CM_HMAC_SHA1_32")) {
856                 suite_val = AST_AES_CM_192_HMAC_SHA1_32;
857                 ast_set_flag(srtp, AST_SRTP_CRYPTO_TAG_32);
858                 ast_set_flag(srtp, AST_SRTP_CRYPTO_AES_192);
859                 key_len_expected = 38;
860         /* RFC used a different name while in draft, some still use that */
861         } else if (!strcmp(suite, "AES_CM_192_HMAC_SHA1_80")) {
862                 suite_val = AST_AES_CM_192_HMAC_SHA1_80;
863                 ast_set_flag(srtp, AST_SRTP_CRYPTO_TAG_80);
864                 ast_set_flag(srtp, AST_SRTP_CRYPTO_AES_192);
865                 ast_set_flag(srtp, AST_SRTP_CRYPTO_OLD_NAME);
866                 key_len_expected = 38;
867         } else if (!strcmp(suite, "AES_CM_192_HMAC_SHA1_32")) {
868                 suite_val = AST_AES_CM_192_HMAC_SHA1_32;
869                 ast_set_flag(srtp, AST_SRTP_CRYPTO_TAG_32);
870                 ast_set_flag(srtp, AST_SRTP_CRYPTO_AES_192);
871                 ast_set_flag(srtp, AST_SRTP_CRYPTO_OLD_NAME);
872                 key_len_expected = 38;
873 #endif
874 #ifdef HAVE_SRTP_256
875         } else if (!strcmp(suite, "AES_256_CM_HMAC_SHA1_80")) {
876                 suite_val = AST_AES_CM_256_HMAC_SHA1_80;
877                 ast_set_flag(srtp, AST_SRTP_CRYPTO_TAG_80);
878                 ast_set_flag(srtp, AST_SRTP_CRYPTO_AES_256);
879                 key_len_expected = 46;
880         } else if (!strcmp(suite, "AES_256_CM_HMAC_SHA1_32")) {
881                 suite_val = AST_AES_CM_256_HMAC_SHA1_32;
882                 ast_set_flag(srtp, AST_SRTP_CRYPTO_TAG_32);
883                 ast_set_flag(srtp, AST_SRTP_CRYPTO_AES_256);
884                 key_len_expected = 46;
885         /* RFC used a different name while in draft, some still use that */
886         } else if (!strcmp(suite, "AES_CM_256_HMAC_SHA1_80")) {
887                 suite_val = AST_AES_CM_256_HMAC_SHA1_80;
888                 ast_set_flag(srtp, AST_SRTP_CRYPTO_TAG_80);
889                 ast_set_flag(srtp, AST_SRTP_CRYPTO_AES_256);
890                 ast_set_flag(srtp, AST_SRTP_CRYPTO_OLD_NAME);
891                 key_len_expected = 46;
892         } else if (!strcmp(suite, "AES_CM_256_HMAC_SHA1_32")) {
893                 suite_val = AST_AES_CM_256_HMAC_SHA1_32;
894                 ast_set_flag(srtp, AST_SRTP_CRYPTO_TAG_32);
895                 ast_set_flag(srtp, AST_SRTP_CRYPTO_AES_256);
896                 ast_set_flag(srtp, AST_SRTP_CRYPTO_OLD_NAME);
897                 key_len_expected = 46;
898 #endif
899 #ifdef HAVE_SRTP_GCM
900         } else if (!strcmp(suite, "AEAD_AES_128_GCM")) {
901                 suite_val = AST_AES_GCM_128;
902                 ast_set_flag(srtp, AST_SRTP_CRYPTO_TAG_16);
903                 key_len_expected = AES_128_GCM_KEYSIZE_WSALT;
904         } else if (!strcmp(suite, "AEAD_AES_256_GCM")) {
905                 suite_val = AST_AES_GCM_256;
906                 ast_set_flag(srtp, AST_SRTP_CRYPTO_TAG_16);
907                 ast_set_flag(srtp, AST_SRTP_CRYPTO_AES_256);
908                 key_len_expected = AES_256_GCM_KEYSIZE_WSALT;
909         /* RFC contained a (too) short auth tag for RTP media, some still use that */
910         } else if (!strcmp(suite, "AEAD_AES_128_GCM_8")) {
911                 suite_val = AST_AES_GCM_128_8;
912                 ast_set_flag(srtp, AST_SRTP_CRYPTO_TAG_8);
913                 key_len_expected = AES_128_GCM_KEYSIZE_WSALT;
914         } else if (!strcmp(suite, "AEAD_AES_256_GCM_8")) {
915                 suite_val = AST_AES_GCM_256_8;
916                 ast_set_flag(srtp, AST_SRTP_CRYPTO_TAG_8);
917                 ast_set_flag(srtp, AST_SRTP_CRYPTO_AES_256);
918                 key_len_expected = AES_256_GCM_KEYSIZE_WSALT;
919 #endif
920         } else {
921                 ast_verb(1, "Unsupported crypto suite: %s\n", suite);
922                 return -1;
923         }
924
925         while ((key_param = strsep(&key_params, ";"))) {
926                 unsigned int n_lifetime;
927                 char *method = NULL;
928                 char *info = NULL;
929
930                 method = strsep(&key_param, ":");
931                 info = strsep(&key_param, ";");
932                 sdes_lifetime = 0;
933
934                 if (strcmp(method, "inline")) {
935                         continue;
936                 }
937
938                 key_salt = strsep(&info, "|");
939
940                 /* The next parameter can be either lifetime or MKI */
941                 lifetime = strsep(&info, "|");
942                 if (!lifetime) {
943                         found = 1;
944                         break;
945                 }
946
947                 mki = strchr(lifetime, ':');
948                 if (mki) {
949                         mki = lifetime;
950                         lifetime = NULL;
951                 } else {
952                         mki = strsep(&info, "|");
953                 }
954
955                 if (mki && *mki != '1') {
956                         ast_log(LOG_NOTICE, "Crypto MKI handling is not supported: ignoring attribute %s\n", attr);
957                         continue;
958                 }
959
960                 if (lifetime) {
961                         if (!strncmp(lifetime, "2^", 2)) {
962                                 char *lifetime_val = lifetime + 2;
963
964                                 /* Exponential lifetime */
965                                 if (sscanf(lifetime_val, "%30u", &n_lifetime) != 1) {
966                                         ast_log(LOG_NOTICE, "Failed to parse lifetime value in crypto attribute: %s\n", attr);
967                                         continue;
968                                 }
969
970                                 if (n_lifetime > 48) {
971                                         /* Yeah... that's a bit big. */
972                                         ast_log(LOG_NOTICE, "Crypto lifetime exponent of '%u' is a bit large; using 48\n", n_lifetime);
973                                         n_lifetime = 48;
974                                 }
975                                 sdes_lifetime = pow(2, n_lifetime);
976                         } else {
977                                 /* Decimal lifetime */
978                                 if (sscanf(lifetime, "%30u", &n_lifetime) != 1) {
979                                         ast_log(LOG_NOTICE, "Failed to parse lifetime value in crypto attribute: %s\n", attr);
980                                         continue;
981                                 }
982                                 sdes_lifetime = n_lifetime;
983                         }
984
985                         /* Accept anything above ~5.8 hours. Less than ~5.8; reject. */
986                         if (sdes_lifetime < 1048576) {
987                                 ast_log(LOG_NOTICE, "Rejecting crypto attribute '%s': lifetime '%f' too short\n", attr, sdes_lifetime);
988                                 continue;
989                         }
990                 }
991
992                 ast_debug(2, "Crypto attribute '%s' accepted with lifetime '%f', MKI '%s'\n",
993                         attr, sdes_lifetime, mki ? mki : "-");
994
995                 found = 1;
996                 break;
997         }
998
999         if (!found) {
1000                 ast_log(LOG_NOTICE, "SRTP crypto offer not acceptable: '%s'\n", attr);
1001                 return -1;
1002         }
1003
1004         key_len_from_sdp = ast_base64decode(remote_key, key_salt, sizeof(remote_key));
1005         if (key_len_from_sdp != key_len_expected) {
1006                 ast_log(LOG_WARNING, "SRTP descriptions key length is '%d', not '%d'\n",
1007                         key_len_from_sdp, key_len_expected);
1008                 return -1;
1009         }
1010
1011         /* on default, the key is 30 (AES-128); throw that away (only) when the suite changed actually */
1012         /* ingress: optional, but saves one expensive call to get_random(.) */
1013         /*  egress: required, because the local key was communicated before the remote key is processed */
1014         if (crypto->key_len != key_len_from_sdp) {
1015                 if (!crypto_init_keys(crypto, key_len_from_sdp)) {
1016                         return -1;
1017                 }
1018         } else if (!memcmp(crypto->remote_key, remote_key, key_len_from_sdp)) {
1019                 ast_debug(1, "SRTP remote key unchanged; maintaining current policy\n");
1020                 return 0;
1021         }
1022
1023         if (key_len_from_sdp > sizeof(crypto->remote_key)) {
1024                 ast_log(LOG_ERROR,
1025                         "SRTP key buffer is %zu although it must be at least %d bytes\n",
1026                         sizeof(crypto->remote_key), key_len_from_sdp);
1027                 return -1;
1028         }
1029         memcpy(crypto->remote_key, remote_key, key_len_from_sdp);
1030
1031         if (crypto_activate(crypto, suite_val, remote_key, key_len_from_sdp, rtp) < 0) {
1032                 return -1;
1033         }
1034
1035         if (ast_test_flag(srtp, AST_SRTP_CRYPTO_TAG_32)) {
1036                 taglen = 32;
1037         } else if (ast_test_flag(srtp, AST_SRTP_CRYPTO_TAG_16)) {
1038                 taglen = 16;
1039         } else if (ast_test_flag(srtp, AST_SRTP_CRYPTO_TAG_8)) {
1040                 taglen = 8;
1041         } else {
1042                 taglen = 80;
1043         }
1044         if (ast_test_flag(srtp, AST_SRTP_CRYPTO_AES_256)) {
1045                 taglen |= 0x0200;
1046         } else if (ast_test_flag(srtp, AST_SRTP_CRYPTO_AES_192)) {
1047                 taglen |= 0x0100;
1048         }
1049         if (ast_test_flag(srtp, AST_SRTP_CRYPTO_OLD_NAME)) {
1050                 taglen |= 0x0080;
1051         }
1052
1053         /* Finally, rebuild the crypto line */
1054         if (res_sdp_crypto_build_offer(crypto, taglen)) {
1055                 return -1;
1056         }
1057
1058         ast_set_flag(srtp, AST_SRTP_CRYPTO_OFFER_OK);
1059         return 0;
1060 }
1061
1062 static const char *res_sdp_srtp_get_attr(struct ast_sdp_srtp *srtp, int dtls_enabled, int default_taglen_32)
1063 {
1064         int taglen;
1065
1066         if (!srtp) {
1067                 return NULL;
1068         }
1069
1070         /* Set encryption properties */
1071         if (!srtp->crypto) {
1072                 if (AST_LIST_NEXT(srtp, sdp_srtp_list)) {
1073                         srtp->crypto = res_sdp_crypto_alloc();
1074                         ast_log(LOG_ERROR, "SRTP SDP list was not empty\n");
1075                 } else {
1076                         const int len = default_taglen_32 ? AST_SRTP_CRYPTO_TAG_32 : AST_SRTP_CRYPTO_TAG_80;
1077                         const int attr[][3] = {
1078                         /* This array creates the following list:
1079                          * a=crypto:1 AES_CM_128_HMAC_SHA1_ ...
1080                          * a=crypto:2 AEAD_AES_128_GCM ...
1081                          * a=crypto:3 AES_256_CM_HMAC_SHA1_ ...
1082                          * a=crypto:4 AEAD_AES_256_GCM ...
1083                          * a=crypto:5 AES_192_CM_HMAC_SHA1_ ...
1084                          * something like 'AEAD_AES_192_GCM' is not specified by the RFCs
1085                          *
1086                          * If you want to prefer another crypto suite or you want to
1087                          * exclude a suite, change this array and recompile Asterisk.
1088                          * This list cannot be changed from rtp.conf because you should
1089                          * know what you are doing. Especially AES-192 and AES-GCM are
1090                          * broken in many VoIP clients, see
1091                          * https://github.com/cisco/libsrtp/pull/170
1092                          * https://github.com/cisco/libsrtp/pull/184
1093                          * Furthermore, AES-GCM uses a shorter crypto-suite string which
1094                          * causes Nokia phones based on Symbian/S60 to reject the whole
1095                          * INVITE with status 500, even if a matching suite was offered.
1096                          * AES-256 might just waste your processor cycles, especially if
1097                          * your TLS transport is not secured with equivalent grade, see
1098                          * https://security.stackexchange.com/q/61361
1099                          * Therefore, AES-128 was preferred here.
1100                          *
1101                          * If you want to enable one of those defines, please, go for
1102                          * CFLAGS='-DENABLE_SRTP_AES_GCM' ./configure && sudo make install
1103                          */
1104                                 { len, 0, 30 },
1105 #if defined(HAVE_SRTP_GCM) && defined(ENABLE_SRTP_AES_GCM)
1106                                 { AST_SRTP_CRYPTO_TAG_16, 0, AES_128_GCM_KEYSIZE_WSALT },
1107 #endif
1108 #if defined(HAVE_SRTP_256) && defined(ENABLE_SRTP_AES_256)
1109                                 { len, AST_SRTP_CRYPTO_AES_256, 46 },
1110 #endif
1111 #if defined(HAVE_SRTP_GCM) && defined(ENABLE_SRTP_AES_GCM) && defined(ENABLE_SRTP_AES_256)
1112                                 { AST_SRTP_CRYPTO_TAG_16, AST_SRTP_CRYPTO_AES_256, AES_256_GCM_KEYSIZE_WSALT },
1113 #endif
1114 #if defined(HAVE_SRTP_192) && defined(ENABLE_SRTP_AES_192)
1115                                 { len, AST_SRTP_CRYPTO_AES_192, 38 },
1116 #endif
1117                         };
1118                         struct ast_sdp_srtp *tmp = srtp;
1119                         int i;
1120
1121                         for (i = 0; i < ARRAY_LEN(attr); i++) {
1122                                 if (attr[i][0]) {
1123                                         ast_set_flag(tmp, attr[i][0]);
1124                                 }
1125                                 if (attr[i][1]) {
1126                                         ast_set_flag(tmp, attr[i][1]);
1127                                 }
1128                                 tmp->crypto = sdp_crypto_alloc(attr[i][2]); /* key_len */
1129                                 tmp->crypto->tag = (i + 1); /* tag starts at 1 */
1130
1131                                 if (i < ARRAY_LEN(attr) - 1) {
1132                                         AST_LIST_NEXT(tmp, sdp_srtp_list) = ast_sdp_srtp_alloc();
1133                                         tmp = AST_LIST_NEXT(tmp, sdp_srtp_list);
1134                                 }
1135                         }
1136                 }
1137         }
1138
1139         if (dtls_enabled) {
1140                 /* If DTLS-SRTP is enabled the key details will be pulled from TLS */
1141                 return NULL;
1142         }
1143
1144         /* set the key length based on INVITE or settings */
1145         if (ast_test_flag(srtp, AST_SRTP_CRYPTO_TAG_80)) {
1146                 taglen = 80;
1147         } else if (ast_test_flag(srtp, AST_SRTP_CRYPTO_TAG_32)) {
1148                 taglen = 32;
1149         } else if (ast_test_flag(srtp, AST_SRTP_CRYPTO_TAG_16)) {
1150                 taglen = 16;
1151         } else if (ast_test_flag(srtp, AST_SRTP_CRYPTO_TAG_8)) {
1152                 taglen = 8;
1153         } else {
1154                 taglen = default_taglen_32 ? 32 : 80;
1155         }
1156         if (ast_test_flag(srtp, AST_SRTP_CRYPTO_AES_256)) {
1157                 taglen |= 0x0200;
1158         } else if (ast_test_flag(srtp, AST_SRTP_CRYPTO_AES_192)) {
1159                 taglen |= 0x0100;
1160         }
1161         if (ast_test_flag(srtp, AST_SRTP_CRYPTO_OLD_NAME)) {
1162                 taglen |= 0x0080;
1163         }
1164
1165         if (srtp->crypto && (res_sdp_crypto_build_offer(srtp->crypto, taglen) >= 0)) {
1166                 return srtp->crypto->a_crypto;
1167         }
1168
1169         ast_log(LOG_WARNING, "No SRTP key management enabled\n");
1170         return NULL;
1171 }
1172
1173 static struct ast_sdp_crypto_api res_sdp_crypto_api = {
1174         .dtor = res_sdp_crypto_dtor,
1175         .alloc = res_sdp_crypto_alloc,
1176         .build_offer = res_sdp_crypto_build_offer,
1177         .parse_offer = res_sdp_crypto_parse_offer,
1178         .get_attr = res_sdp_srtp_get_attr,
1179 };
1180
1181 static void res_srtp_shutdown(void)
1182 {
1183         ast_sdp_crypto_unregister(&res_sdp_crypto_api);
1184         ast_rtp_engine_unregister_srtp();
1185         srtp_install_event_handler(NULL);
1186 #ifdef HAVE_SRTP_SHUTDOWN
1187         srtp_shutdown();
1188 #endif
1189         g_initialized = 0;
1190 }
1191
1192 static int res_srtp_init(void)
1193 {
1194         if (g_initialized) {
1195                 return 0;
1196         }
1197
1198         if (srtp_init() != err_status_ok) {
1199                 ast_log(AST_LOG_WARNING, "Failed to initialize libsrtp\n");
1200                 return -1;
1201         }
1202
1203         srtp_install_event_handler(srtp_event_cb);
1204
1205         if (ast_rtp_engine_register_srtp(&srtp_res, &policy_res)) {
1206                 ast_log(AST_LOG_WARNING, "Failed to register SRTP with rtp engine\n");
1207                 res_srtp_shutdown();
1208                 return -1;
1209         }
1210
1211         if (ast_sdp_crypto_register(&res_sdp_crypto_api)) {
1212                 ast_log(AST_LOG_WARNING, "Failed to register SDP SRTP crypto API\n");
1213                 res_srtp_shutdown();
1214                 return -1;
1215         }
1216
1217 #ifdef HAVE_SRTP_GET_VERSION
1218         ast_verb(2, "%s initialized\n", srtp_get_version_string());
1219 #else
1220         ast_verb(2, "libsrtp initialized\n");
1221 #endif
1222
1223         g_initialized = 1;
1224         return 0;
1225 }
1226
1227 /*
1228  * Exported functions
1229  */
1230
1231 static int load_module(void)
1232 {
1233         return res_srtp_init();
1234 }
1235
1236 static int unload_module(void)
1237 {
1238         res_srtp_shutdown();
1239         return 0;
1240 }
1241
1242 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER, "Secure RTP (SRTP)",
1243         .support_level = AST_MODULE_SUPPORT_CORE,
1244         .load = load_module,
1245         .unload = unload_module,
1246         .load_pri = AST_MODPRI_CHANNEL_DEPEND,
1247 );