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