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