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