res_srtp: Add support for libsrtp2.1.
[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                 if ((srtp->warned >= 10) && !((srtp->warned - 10) % 100)) {
450                         ast_log(AST_LOG_WARNING, "SRTP unprotect failed with: %s %d\n", srtp_errstr(res), srtp->warned);
451                         srtp->warned = 11;
452                 } else {
453                         srtp->warned++;
454                 }
455                 errno = EAGAIN;
456                 return -1;
457         }
458
459         return *len;
460 }
461
462 static int ast_srtp_protect(struct ast_srtp *srtp, void **buf, int *len, int rtcp)
463 {
464         int res;
465         unsigned char *localbuf;
466
467         if ((*len + SRTP_MAX_TRAILER_LEN) > sizeof(srtp->buf)) {
468                 return -1;
469         }
470         
471         localbuf = rtcp ? srtp->rtcpbuf : srtp->buf;
472
473         memcpy(localbuf, *buf, *len);
474
475         if ((res = rtcp ? srtp_protect_rtcp(srtp->session, localbuf, len) : srtp_protect(srtp->session, localbuf, len)) != err_status_ok && res != err_status_replay_fail) {
476                 ast_log(LOG_WARNING, "SRTP protect: %s\n", srtp_errstr(res));
477                 return -1;
478         }
479
480         *buf = localbuf;
481         return *len;
482 }
483
484 static int ast_srtp_create(struct ast_srtp **srtp, struct ast_rtp_instance *rtp, struct ast_srtp_policy *policy)
485 {
486         struct ast_srtp *temp;
487
488         if (!(temp = res_srtp_new())) {
489                 return -1;
490         }
491         ast_module_ref(ast_module_info->self);
492
493         /* Any failures after this point can use ast_srtp_destroy to destroy the instance */
494         if (srtp_create(&temp->session, &policy->sp) != err_status_ok) {
495                 /* Session either wasn't created or was created and dealloced. */
496                 temp->session = NULL;
497                 ast_srtp_destroy(temp);
498                 return -1;
499         }
500
501         temp->rtp = rtp;
502         *srtp = temp;
503
504         ao2_t_link((*srtp)->policies, policy, "Created initial policy");
505
506         return 0;
507 }
508
509 static int ast_srtp_replace(struct ast_srtp **srtp, struct ast_rtp_instance *rtp, struct ast_srtp_policy *policy)
510 {
511         if ((*srtp) != NULL) {
512                 ast_srtp_destroy(*srtp);
513         }
514         return ast_srtp_create(srtp, rtp, policy);
515 }
516
517 static void ast_srtp_destroy(struct ast_srtp *srtp)
518 {
519         if (srtp->session) {
520                 srtp_dealloc(srtp->session);
521         }
522
523         ao2_t_callback(srtp->policies, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "Unallocate policy");
524         ao2_t_ref(srtp->policies, -1, "Destroying container");
525
526         ast_free(srtp);
527         ast_module_unref(ast_module_info->self);
528 }
529
530 static int ast_srtp_add_stream(struct ast_srtp *srtp, struct ast_srtp_policy *policy)
531 {
532         struct ast_srtp_policy *match;
533
534         /* For existing streams, replace if its an SSRC stream, or bail if its a wildcard */
535         if ((match = find_policy(srtp, &policy->sp, OBJ_POINTER))) {
536                 if (policy->sp.ssrc.type != ssrc_specific) {
537                         ast_log(AST_LOG_WARNING, "Cannot replace an existing wildcard policy\n");
538                         ao2_t_ref(match, -1, "Unreffing already existing policy");
539                         return -1;
540                 } else {
541                         if (srtp_remove_stream(srtp->session, match->sp.ssrc.value) != err_status_ok) {
542                                 ast_log(AST_LOG_WARNING, "Failed to remove SRTP stream for SSRC %u\n", match->sp.ssrc.value);
543                         }
544                         ao2_t_unlink(srtp->policies, match, "Remove existing match policy");
545                         ao2_t_ref(match, -1, "Unreffing already existing policy");
546                 }
547         }
548
549         ast_debug(3, "Adding new policy for %s %u\n",
550                 policy->sp.ssrc.type == ssrc_specific ? "SSRC" : "type",
551                 policy->sp.ssrc.type == ssrc_specific ? policy->sp.ssrc.value : policy->sp.ssrc.type);
552         if (srtp_add_stream(srtp->session, &policy->sp) != err_status_ok) {
553                 ast_log(AST_LOG_WARNING, "Failed to add SRTP stream for %s %u\n",
554                         policy->sp.ssrc.type == ssrc_specific ? "SSRC" : "type",
555                         policy->sp.ssrc.type == ssrc_specific ? policy->sp.ssrc.value : policy->sp.ssrc.type);
556                 return -1;
557         }
558
559         ao2_t_link(srtp->policies, policy, "Added additional stream");
560
561         return 0;
562 }
563
564 static int ast_srtp_change_source(struct ast_srtp *srtp, unsigned int from_ssrc, unsigned int to_ssrc)
565 {
566         struct ast_srtp_policy *match;
567         struct srtp_policy_t sp = {
568                 .ssrc.type = ssrc_specific,
569                 .ssrc.value = from_ssrc,
570         };
571         err_status_t status;
572
573         /* If we find a match, return and unlink it from the container so we
574          * can change the SSRC (which is part of the hash) and then have
575          * ast_srtp_add_stream link it back in if all is well */
576         if ((match = find_policy(srtp, &sp, OBJ_POINTER | OBJ_UNLINK))) {
577                 match->sp.ssrc.value = to_ssrc;
578                 if (ast_srtp_add_stream(srtp, match)) {
579                         ast_log(LOG_WARNING, "Couldn't add stream\n");
580                 } else if ((status = srtp_remove_stream(srtp->session, from_ssrc))) {
581                         ast_debug(3, "Couldn't remove stream (%u)\n", status);
582                 }
583                 ao2_t_ref(match, -1, "Unreffing found policy in change_source");
584         }
585
586         return 0;
587 }
588
589 struct ast_sdp_crypto {
590         char *a_crypto;
591         unsigned char local_key[SRTP_MAX_KEY_LEN];
592         int tag;
593         char local_key64[((SRTP_MAX_KEY_LEN) * 8 + 5) / 6 + 1];
594         unsigned char remote_key[SRTP_MAX_KEY_LEN];
595         int key_len;
596 };
597
598 static void res_sdp_crypto_dtor(struct ast_sdp_crypto *crypto)
599 {
600         if (crypto) {
601                 ast_free(crypto->a_crypto);
602                 crypto->a_crypto = NULL;
603                 ast_free(crypto);
604
605                 ast_module_unref(ast_module_info->self);
606         }
607 }
608
609 static struct ast_sdp_crypto *crypto_init_keys(struct ast_sdp_crypto *p, const int key_len)
610 {
611         unsigned char remote_key[key_len];
612
613         if (srtp_res.get_random(p->local_key, key_len) < 0) {
614                 return NULL;
615         }
616
617         ast_base64encode(p->local_key64, p->local_key, key_len, sizeof(p->local_key64));
618
619         p->key_len = ast_base64decode(remote_key, p->local_key64, sizeof(remote_key));
620
621         if (p->key_len != key_len) {
622                 ast_log(LOG_ERROR, "base64 encode/decode bad len %d != %d\n", p->key_len, key_len);
623                 return NULL;
624         }
625
626         if (memcmp(remote_key, p->local_key, p->key_len)) {
627                 ast_log(LOG_ERROR, "base64 encode/decode bad key\n");
628                 return NULL;
629         }
630
631         ast_debug(1 , "local_key64 %s len %zu\n", p->local_key64, strlen(p->local_key64));
632
633         return p;
634 }
635
636 static struct ast_sdp_crypto *sdp_crypto_alloc(const int key_len)
637 {
638         struct ast_sdp_crypto *p, *result;
639
640         if (!(p = ast_calloc(1, sizeof(*p)))) {
641                 return NULL;
642         }
643         p->tag = 1;
644         ast_module_ref(ast_module_info->self);
645
646         /* default is a key which uses AST_AES_CM_128_HMAC_SHA1_xx */
647         result = crypto_init_keys(p, key_len);
648         if (!result) {
649                 res_sdp_crypto_dtor(p);
650         }
651
652         return result;
653 }
654
655 static struct ast_sdp_crypto *res_sdp_crypto_alloc(void)
656 {
657         return sdp_crypto_alloc(SRTP_MASTER_KEY_LEN);
658 }
659
660 static int res_sdp_crypto_build_offer(struct ast_sdp_crypto *p, int taglen)
661 {
662         int res;
663
664         /* Rebuild the crypto line */
665         ast_free(p->a_crypto);
666         p->a_crypto = NULL;
667
668         if ((taglen & 0x007f) == 8) {
669                 res = ast_asprintf(&p->a_crypto, "%d AEAD_AES_%d_GCM_%d inline:%s",
670                         p->tag, 128 + ((taglen & 0x0300) >> 2), taglen & 0x007f, p->local_key64);
671         } else if ((taglen & 0x007f) == 16) {
672                 res = ast_asprintf(&p->a_crypto, "%d AEAD_AES_%d_GCM inline:%s",
673                         p->tag, 128 + ((taglen & 0x0300) >> 2), p->local_key64);
674         } else if ((taglen & 0x0300) && !(taglen & 0x0080)) {
675                 res = ast_asprintf(&p->a_crypto, "%d AES_%d_CM_HMAC_SHA1_%d inline:%s",
676                         p->tag, 128 + ((taglen & 0x0300) >> 2), taglen & 0x007f, p->local_key64);
677         } else {
678                 res = ast_asprintf(&p->a_crypto, "%d AES_CM_%d_HMAC_SHA1_%d inline:%s",
679                         p->tag, 128 + ((taglen & 0x0300) >> 2), taglen & 0x007f, p->local_key64);
680         }
681         if (res == -1 || !p->a_crypto) {
682                 ast_log(LOG_ERROR, "Could not allocate memory for crypto line\n");
683                 return -1;
684         }
685
686         ast_debug(1, "Crypto line: a=crypto:%s\n", p->a_crypto);
687
688         return 0;
689 }
690
691 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)
692 {
693         if (policy_res.set_master_key(policy, master_key, key_len, NULL, 0) < 0) {
694                 return -1;
695         }
696
697         if (policy_res.set_suite(policy, suite_val)) {
698                 ast_log(LOG_WARNING, "Could not set remote SRTP suite\n");
699                 return -1;
700         }
701
702         policy_res.set_ssrc(policy, ssrc, inbound);
703
704         return 0;
705 }
706
707 static int crypto_activate(struct ast_sdp_crypto *p, int suite_val, unsigned char *remote_key, int key_len, struct ast_rtp_instance *rtp)
708 {
709         struct ast_srtp_policy *local_policy = NULL;
710         struct ast_srtp_policy *remote_policy = NULL;
711         struct ast_rtp_instance_stats stats = {0,};
712         int res = -1;
713
714         if (!p) {
715                 return -1;
716         }
717
718         if (!(local_policy = policy_res.alloc())) {
719                 return -1;
720         }
721
722         if (!(remote_policy = policy_res.alloc())) {
723                 goto err;
724         }
725
726         if (ast_rtp_instance_get_stats(rtp, &stats, AST_RTP_INSTANCE_STAT_LOCAL_SSRC)) {
727                 goto err;
728         }
729
730         if (set_crypto_policy(local_policy, suite_val, p->local_key, key_len, stats.local_ssrc, 0) < 0) {
731                 goto err;
732         }
733
734         if (set_crypto_policy(remote_policy, suite_val, remote_key, key_len, 0, 1) < 0) {
735                 goto err;
736         }
737
738         /* Add the SRTP policies */
739         if (ast_rtp_instance_add_srtp_policy(rtp, remote_policy, local_policy, 0)) {
740                 ast_log(LOG_WARNING, "Could not set SRTP policies\n");
741                 goto err;
742         }
743
744         ast_debug(1 , "SRTP policy activated\n");
745         res = 0;
746
747 err:
748         if (local_policy) {
749                 policy_res.destroy(local_policy);
750         }
751
752         if (remote_policy) {
753                 policy_res.destroy(remote_policy);
754         }
755
756         return res;
757 }
758
759 static int res_sdp_crypto_parse_offer(struct ast_rtp_instance *rtp, struct ast_sdp_srtp *srtp, const char *attr)
760 {
761         char *str = NULL;
762         char *tag = NULL;
763         char *suite = NULL;
764         char *key_params = NULL;
765         char *key_param = NULL;
766         char *session_params = NULL;
767         char *key_salt = NULL;       /* The actual master key and key salt */
768         char *lifetime = NULL;       /* Key lifetime (# of RTP packets) */
769         char *mki = NULL;            /* Master Key Index */
770         int found = 0;
771         int key_len_from_sdp;
772         int key_len_expected;
773         int tag_from_sdp;
774         int suite_val = 0;
775         unsigned char remote_key[SRTP_MAX_KEY_LEN];
776         int taglen;
777         double sdes_lifetime;
778         struct ast_sdp_crypto *crypto;
779         struct ast_sdp_srtp *tmp;
780
781         str = ast_strdupa(attr);
782
783         tag = strsep(&str, " ");
784         suite = strsep(&str, " ");
785         key_params = strsep(&str, " ");
786         session_params = strsep(&str, " ");
787
788         if (!tag || !suite) {
789                 ast_log(LOG_WARNING, "Unrecognized crypto attribute a=%s\n", attr);
790                 return -1;
791         }
792
793         /* RFC4568 9.1 - tag is 1-9 digits */
794         if (sscanf(tag, "%30d", &tag_from_sdp) != 1 || tag_from_sdp < 0 || tag_from_sdp > 999999999) {
795                 ast_log(LOG_WARNING, "Unacceptable a=crypto tag: %s\n", tag);
796                 return -1;
797         }
798
799         if (!ast_strlen_zero(session_params)) {
800                 ast_log(LOG_WARNING, "Unsupported crypto parameters: %s\n", session_params);
801                 return -1;
802         }
803
804         /* On egress, Asterisk sent several crypto lines in the SIP/SDP offer
805            The remote party might have choosen another line than the first */
806         for (tmp = srtp; tmp && tmp->crypto && tmp->crypto->tag != tag_from_sdp;) {
807                 tmp = AST_LIST_NEXT(tmp, sdp_srtp_list);
808         }
809         if (tmp) { /* tag matched an already created crypto line */
810                 unsigned int flags = tmp->flags;
811
812                 /* Make that crypto line the head of the list, not by changing the
813                    list structure but by exchanging the content of the list members */
814                 crypto = tmp->crypto;
815                 tmp->crypto = srtp->crypto;
816                 tmp->flags = srtp->flags;
817                 srtp->crypto = crypto;
818                 srtp->flags = flags;
819         } else {
820                 crypto = srtp->crypto;
821                 crypto->tag = tag_from_sdp;
822         }
823
824         if (!strcmp(suite, "AES_CM_128_HMAC_SHA1_80")) {
825                 suite_val = AST_AES_CM_128_HMAC_SHA1_80;
826                 ast_set_flag(srtp, AST_SRTP_CRYPTO_TAG_80);
827                 key_len_expected = 30;
828         } else if (!strcmp(suite, "AES_CM_128_HMAC_SHA1_32")) {
829                 suite_val = AST_AES_CM_128_HMAC_SHA1_32;
830                 ast_set_flag(srtp, AST_SRTP_CRYPTO_TAG_32);
831                 key_len_expected = 30;
832 #ifdef HAVE_SRTP_192
833         } else if (!strcmp(suite, "AES_192_CM_HMAC_SHA1_80")) {
834                 suite_val = AST_AES_CM_192_HMAC_SHA1_80;
835                 ast_set_flag(srtp, AST_SRTP_CRYPTO_TAG_80);
836                 ast_set_flag(srtp, AST_SRTP_CRYPTO_AES_192);
837                 key_len_expected = 38;
838         } else if (!strcmp(suite, "AES_192_CM_HMAC_SHA1_32")) {
839                 suite_val = AST_AES_CM_192_HMAC_SHA1_32;
840                 ast_set_flag(srtp, AST_SRTP_CRYPTO_TAG_32);
841                 ast_set_flag(srtp, AST_SRTP_CRYPTO_AES_192);
842                 key_len_expected = 38;
843         /* RFC used a different name while in draft, some still use that */
844         } else if (!strcmp(suite, "AES_CM_192_HMAC_SHA1_80")) {
845                 suite_val = AST_AES_CM_192_HMAC_SHA1_80;
846                 ast_set_flag(srtp, AST_SRTP_CRYPTO_TAG_80);
847                 ast_set_flag(srtp, AST_SRTP_CRYPTO_AES_192);
848                 ast_set_flag(srtp, AST_SRTP_CRYPTO_OLD_NAME);
849                 key_len_expected = 38;
850         } else if (!strcmp(suite, "AES_CM_192_HMAC_SHA1_32")) {
851                 suite_val = AST_AES_CM_192_HMAC_SHA1_32;
852                 ast_set_flag(srtp, AST_SRTP_CRYPTO_TAG_32);
853                 ast_set_flag(srtp, AST_SRTP_CRYPTO_AES_192);
854                 ast_set_flag(srtp, AST_SRTP_CRYPTO_OLD_NAME);
855                 key_len_expected = 38;
856 #endif
857 #ifdef HAVE_SRTP_256
858         } else if (!strcmp(suite, "AES_256_CM_HMAC_SHA1_80")) {
859                 suite_val = AST_AES_CM_256_HMAC_SHA1_80;
860                 ast_set_flag(srtp, AST_SRTP_CRYPTO_TAG_80);
861                 ast_set_flag(srtp, AST_SRTP_CRYPTO_AES_256);
862                 key_len_expected = 46;
863         } else if (!strcmp(suite, "AES_256_CM_HMAC_SHA1_32")) {
864                 suite_val = AST_AES_CM_256_HMAC_SHA1_32;
865                 ast_set_flag(srtp, AST_SRTP_CRYPTO_TAG_32);
866                 ast_set_flag(srtp, AST_SRTP_CRYPTO_AES_256);
867                 key_len_expected = 46;
868         /* RFC used a different name while in draft, some still use that */
869         } else if (!strcmp(suite, "AES_CM_256_HMAC_SHA1_80")) {
870                 suite_val = AST_AES_CM_256_HMAC_SHA1_80;
871                 ast_set_flag(srtp, AST_SRTP_CRYPTO_TAG_80);
872                 ast_set_flag(srtp, AST_SRTP_CRYPTO_AES_256);
873                 ast_set_flag(srtp, AST_SRTP_CRYPTO_OLD_NAME);
874                 key_len_expected = 46;
875         } else if (!strcmp(suite, "AES_CM_256_HMAC_SHA1_32")) {
876                 suite_val = AST_AES_CM_256_HMAC_SHA1_32;
877                 ast_set_flag(srtp, AST_SRTP_CRYPTO_TAG_32);
878                 ast_set_flag(srtp, AST_SRTP_CRYPTO_AES_256);
879                 ast_set_flag(srtp, AST_SRTP_CRYPTO_OLD_NAME);
880                 key_len_expected = 46;
881 #endif
882 #ifdef HAVE_SRTP_GCM
883         } else if (!strcmp(suite, "AEAD_AES_128_GCM")) {
884                 suite_val = AST_AES_GCM_128;
885                 ast_set_flag(srtp, AST_SRTP_CRYPTO_TAG_16);
886                 key_len_expected = AES_128_GCM_KEYSIZE_WSALT;
887         } else if (!strcmp(suite, "AEAD_AES_256_GCM")) {
888                 suite_val = AST_AES_GCM_256;
889                 ast_set_flag(srtp, AST_SRTP_CRYPTO_TAG_16);
890                 ast_set_flag(srtp, AST_SRTP_CRYPTO_AES_256);
891                 key_len_expected = AES_256_GCM_KEYSIZE_WSALT;
892         /* RFC contained a (too) short auth tag for RTP media, some still use that */
893         } else if (!strcmp(suite, "AEAD_AES_128_GCM_8")) {
894                 suite_val = AST_AES_GCM_128_8;
895                 ast_set_flag(srtp, AST_SRTP_CRYPTO_TAG_8);
896                 key_len_expected = AES_128_GCM_KEYSIZE_WSALT;
897         } else if (!strcmp(suite, "AEAD_AES_256_GCM_8")) {
898                 suite_val = AST_AES_GCM_256_8;
899                 ast_set_flag(srtp, AST_SRTP_CRYPTO_TAG_8);
900                 ast_set_flag(srtp, AST_SRTP_CRYPTO_AES_256);
901                 key_len_expected = AES_256_GCM_KEYSIZE_WSALT;
902 #endif
903         } else {
904                 ast_verb(1, "Unsupported crypto suite: %s\n", suite);
905                 return -1;
906         }
907
908         while ((key_param = strsep(&key_params, ";"))) {
909                 unsigned int n_lifetime;
910                 char *method = NULL;
911                 char *info = NULL;
912
913                 method = strsep(&key_param, ":");
914                 info = strsep(&key_param, ";");
915                 sdes_lifetime = 0;
916
917                 if (strcmp(method, "inline")) {
918                         continue;
919                 }
920
921                 key_salt = strsep(&info, "|");
922
923                 /* The next parameter can be either lifetime or MKI */
924                 lifetime = strsep(&info, "|");
925                 if (!lifetime) {
926                         found = 1;
927                         break;
928                 }
929
930                 mki = strchr(lifetime, ':');
931                 if (mki) {
932                         mki = lifetime;
933                         lifetime = NULL;
934                 } else {
935                         mki = strsep(&info, "|");
936                 }
937
938                 if (mki && *mki != '1') {
939                         ast_log(LOG_NOTICE, "Crypto MKI handling is not supported: ignoring attribute %s\n", attr);
940                         continue;
941                 }
942
943                 if (lifetime) {
944                         if (!strncmp(lifetime, "2^", 2)) {
945                                 char *lifetime_val = lifetime + 2;
946
947                                 /* Exponential lifetime */
948                                 if (sscanf(lifetime_val, "%30u", &n_lifetime) != 1) {
949                                         ast_log(LOG_NOTICE, "Failed to parse lifetime value in crypto attribute: %s\n", attr);
950                                         continue;
951                                 }
952
953                                 if (n_lifetime > 48) {
954                                         /* Yeah... that's a bit big. */
955                                         ast_log(LOG_NOTICE, "Crypto lifetime exponent of '%u' is a bit large; using 48\n", n_lifetime);
956                                         n_lifetime = 48;
957                                 }
958                                 sdes_lifetime = pow(2, n_lifetime);
959                         } else {
960                                 /* Decimal lifetime */
961                                 if (sscanf(lifetime, "%30u", &n_lifetime) != 1) {
962                                         ast_log(LOG_NOTICE, "Failed to parse lifetime value in crypto attribute: %s\n", attr);
963                                         continue;
964                                 }
965                                 sdes_lifetime = n_lifetime;
966                         }
967
968                         /* Accept anything above 10 hours. Less than 10; reject. */
969                         if (sdes_lifetime < 1800000) {
970                                 ast_log(LOG_NOTICE, "Rejecting crypto attribute '%s': lifetime '%f' too short\n", attr, sdes_lifetime);
971                                 continue;
972                         }
973                 }
974
975                 ast_debug(2, "Crypto attribute '%s' accepted with lifetime '%f', MKI '%s'\n",
976                         attr, sdes_lifetime, mki ? mki : "-");
977
978                 found = 1;
979                 break;
980         }
981
982         if (!found) {
983                 ast_log(LOG_NOTICE, "SRTP crypto offer not acceptable: '%s'\n", attr);
984                 return -1;
985         }
986
987         key_len_from_sdp = ast_base64decode(remote_key, key_salt, sizeof(remote_key));
988         if (key_len_from_sdp != key_len_expected) {
989                 ast_log(LOG_WARNING, "SRTP descriptions key length is '%d', not '%d'\n",
990                         key_len_from_sdp, key_len_expected);
991                 return -1;
992         }
993
994         /* on default, the key is 30 (AES-128); throw that away (only) when the suite changed actually */
995         /* ingress: optional, but saves one expensive call to get_random(.) */
996         /*  egress: required, because the local key was communicated before the remote key is processed */
997         if (crypto->key_len != key_len_from_sdp) {
998                 if (!crypto_init_keys(crypto, key_len_from_sdp)) {
999                         return -1;
1000                 }
1001         } else if (!memcmp(crypto->remote_key, remote_key, key_len_from_sdp)) {
1002                 ast_debug(1, "SRTP remote key unchanged; maintaining current policy\n");
1003                 ast_set_flag(srtp, AST_SRTP_CRYPTO_OFFER_OK);
1004                 return 0;
1005         }
1006
1007         if (key_len_from_sdp > sizeof(crypto->remote_key)) {
1008                 ast_log(LOG_ERROR,
1009                         "SRTP key buffer is %zu although it must be at least %d bytes\n",
1010                         sizeof(crypto->remote_key), key_len_from_sdp);
1011                 return -1;
1012         }
1013         memcpy(crypto->remote_key, remote_key, key_len_from_sdp);
1014
1015         if (crypto_activate(crypto, suite_val, remote_key, key_len_from_sdp, rtp) < 0) {
1016                 return -1;
1017         }
1018
1019         if (ast_test_flag(srtp, AST_SRTP_CRYPTO_TAG_32)) {
1020                 taglen = 32;
1021         } else if (ast_test_flag(srtp, AST_SRTP_CRYPTO_TAG_16)) {
1022                 taglen = 16;
1023         } else if (ast_test_flag(srtp, AST_SRTP_CRYPTO_TAG_8)) {
1024                 taglen = 8;
1025         } else {
1026                 taglen = 80;
1027         }
1028         if (ast_test_flag(srtp, AST_SRTP_CRYPTO_AES_256)) {
1029                 taglen |= 0x0200;
1030         } else if (ast_test_flag(srtp, AST_SRTP_CRYPTO_AES_192)) {
1031                 taglen |= 0x0100;
1032         }
1033         if (ast_test_flag(srtp, AST_SRTP_CRYPTO_OLD_NAME)) {
1034                 taglen |= 0x0080;
1035         }
1036
1037         /* Finally, rebuild the crypto line */
1038         if (res_sdp_crypto_build_offer(crypto, taglen)) {
1039                 return -1;
1040         }
1041
1042         ast_set_flag(srtp, AST_SRTP_CRYPTO_OFFER_OK);
1043         return 0;
1044 }
1045
1046 static const char *res_sdp_srtp_get_attr(struct ast_sdp_srtp *srtp, int dtls_enabled, int default_taglen_32)
1047 {
1048         int taglen;
1049
1050         if (!srtp) {
1051                 return NULL;
1052         }
1053
1054         /* Set encryption properties */
1055         if (!srtp->crypto) {
1056                 if (AST_LIST_NEXT(srtp, sdp_srtp_list)) {
1057                         srtp->crypto = res_sdp_crypto_alloc();
1058                         ast_log(LOG_ERROR, "SRTP SDP list was not empty\n");
1059                 } else {
1060                         const int len = default_taglen_32 ? AST_SRTP_CRYPTO_TAG_32 : AST_SRTP_CRYPTO_TAG_80;
1061                         const int attr[][3] = {
1062                         /* This array creates the following list:
1063                          * a=crypto:1 AES_CM_128_HMAC_SHA1_ ...
1064                          * a=crypto:2 AEAD_AES_128_GCM ...
1065                          * a=crypto:3 AES_256_CM_HMAC_SHA1_ ...
1066                          * a=crypto:4 AEAD_AES_256_GCM ...
1067                          * a=crypto:5 AES_192_CM_HMAC_SHA1_ ...
1068                          * something like 'AEAD_AES_192_GCM' is not specified by the RFCs
1069                          *
1070                          * If you want to prefer another crypto suite or you want to
1071                          * exclude a suite, change this array and recompile Asterisk.
1072                          * This list cannot be changed from rtp.conf because you should
1073                          * know what you are doing. Especially AES-192 and AES-GCM are
1074                          * broken in many VoIP clients, see
1075                          * https://github.com/cisco/libsrtp/pull/170
1076                          * https://github.com/cisco/libsrtp/pull/184
1077                          * Furthermore, AES-GCM uses a shorter crypto-suite string which
1078                          * causes Nokia phones based on Symbian/S60 to reject the whole
1079                          * INVITE with status 500, even if a matching suite was offered.
1080                          * AES-256 might just waste your processor cycles, especially if
1081                          * your TLS transport is not secured with equivalent grade, see
1082                          * https://security.stackexchange.com/q/61361
1083                          * Therefore, AES-128 was preferred here.
1084                          *
1085                          * If you want to enable one of those defines, please, go for
1086                          * CFLAGS='-DENABLE_SRTP_AES_GCM' ./configure && sudo make install
1087                          */
1088                                 { len, 0, 30 },
1089 #if defined(HAVE_SRTP_GCM) && defined(ENABLE_SRTP_AES_GCM)
1090                                 { AST_SRTP_CRYPTO_TAG_16, 0, AES_128_GCM_KEYSIZE_WSALT },
1091 #endif
1092 #if defined(HAVE_SRTP_256) && defined(ENABLE_SRTP_AES_256)
1093                                 { len, AST_SRTP_CRYPTO_AES_256, 46 },
1094 #endif
1095 #if defined(HAVE_SRTP_GCM) && defined(ENABLE_SRTP_AES_GCM) && defined(ENABLE_SRTP_AES_256)
1096                                 { AST_SRTP_CRYPTO_TAG_16, AST_SRTP_CRYPTO_AES_256, AES_256_GCM_KEYSIZE_WSALT },
1097 #endif
1098 #if defined(HAVE_SRTP_192) && defined(ENABLE_SRTP_AES_192)
1099                                 { len, AST_SRTP_CRYPTO_AES_192, 38 },
1100 #endif
1101                         };
1102                         struct ast_sdp_srtp *tmp = srtp;
1103                         int i;
1104
1105                         for (i = 0; i < ARRAY_LEN(attr); i++) {
1106                                 if (attr[i][0]) {
1107                                         ast_set_flag(tmp, attr[i][0]);
1108                                 }
1109                                 if (attr[i][1]) {
1110                                         ast_set_flag(tmp, attr[i][1]);
1111                                 }
1112                                 tmp->crypto = sdp_crypto_alloc(attr[i][2]); /* key_len */
1113                                 tmp->crypto->tag = (i + 1); /* tag starts at 1 */
1114
1115                                 if (i < ARRAY_LEN(attr) - 1) {
1116                                         AST_LIST_NEXT(tmp, sdp_srtp_list) = ast_sdp_srtp_alloc();
1117                                         tmp = AST_LIST_NEXT(tmp, sdp_srtp_list);
1118                                 }
1119                         }
1120                 }
1121         }
1122
1123         if (dtls_enabled) {
1124                 /* If DTLS-SRTP is enabled the key details will be pulled from TLS */
1125                 return NULL;
1126         }
1127
1128         /* set the key length based on INVITE or settings */
1129         if (ast_test_flag(srtp, AST_SRTP_CRYPTO_TAG_80)) {
1130                 taglen = 80;
1131         } else if (ast_test_flag(srtp, AST_SRTP_CRYPTO_TAG_32)) {
1132                 taglen = 32;
1133         } else if (ast_test_flag(srtp, AST_SRTP_CRYPTO_TAG_16)) {
1134                 taglen = 16;
1135         } else if (ast_test_flag(srtp, AST_SRTP_CRYPTO_TAG_8)) {
1136                 taglen = 8;
1137         } else {
1138                 taglen = default_taglen_32 ? 32 : 80;
1139         }
1140         if (ast_test_flag(srtp, AST_SRTP_CRYPTO_AES_256)) {
1141                 taglen |= 0x0200;
1142         } else if (ast_test_flag(srtp, AST_SRTP_CRYPTO_AES_192)) {
1143                 taglen |= 0x0100;
1144         }
1145         if (ast_test_flag(srtp, AST_SRTP_CRYPTO_OLD_NAME)) {
1146                 taglen |= 0x0080;
1147         }
1148
1149         if (srtp->crypto && (res_sdp_crypto_build_offer(srtp->crypto, taglen) >= 0)) {
1150                 return srtp->crypto->a_crypto;
1151         }
1152
1153         ast_log(LOG_WARNING, "No SRTP key management enabled\n");
1154         return NULL;
1155 }
1156
1157 static struct ast_sdp_crypto_api res_sdp_crypto_api = {
1158         .dtor = res_sdp_crypto_dtor,
1159         .alloc = res_sdp_crypto_alloc,
1160         .build_offer = res_sdp_crypto_build_offer,
1161         .parse_offer = res_sdp_crypto_parse_offer,
1162         .get_attr = res_sdp_srtp_get_attr,
1163 };
1164
1165 static void res_srtp_shutdown(void)
1166 {
1167         ast_sdp_crypto_unregister(&res_sdp_crypto_api);
1168         ast_rtp_engine_unregister_srtp();
1169         srtp_install_event_handler(NULL);
1170 #ifdef HAVE_SRTP_SHUTDOWN
1171         srtp_shutdown();
1172 #endif
1173         g_initialized = 0;
1174 }
1175
1176 static int res_srtp_init(void)
1177 {
1178         if (g_initialized) {
1179                 return 0;
1180         }
1181
1182         if (srtp_init() != err_status_ok) {
1183                 ast_log(AST_LOG_WARNING, "Failed to initialize libsrtp\n");
1184                 return -1;
1185         }
1186
1187         srtp_install_event_handler(srtp_event_cb);
1188
1189         if (ast_rtp_engine_register_srtp(&srtp_res, &policy_res)) {
1190                 ast_log(AST_LOG_WARNING, "Failed to register SRTP with rtp engine\n");
1191                 res_srtp_shutdown();
1192                 return -1;
1193         }
1194
1195         if (ast_sdp_crypto_register(&res_sdp_crypto_api)) {
1196                 ast_log(AST_LOG_WARNING, "Failed to register SDP SRTP crypto API\n");
1197                 res_srtp_shutdown();
1198                 return -1;
1199         }
1200
1201         g_initialized = 1;
1202         return 0;
1203 }
1204
1205 /*
1206  * Exported functions
1207  */
1208
1209 static int load_module(void)
1210 {
1211         return res_srtp_init();
1212 }
1213
1214 static int unload_module(void)
1215 {
1216         res_srtp_shutdown();
1217         return 0;
1218 }
1219
1220 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER, "Secure RTP (SRTP)",
1221         .support_level = AST_MODULE_SUPPORT_CORE,
1222         .load = load_module,
1223         .unload = unload_module,
1224         .load_pri = AST_MODPRI_CHANNEL_DEPEND,
1225 );