Audit of ao2_iterator_init() usage for v1.8.
[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"
39
40 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
41
42 #include <srtp/srtp.h>
43
44 #include "asterisk/lock.h"
45 #include "asterisk/sched.h"
46 #include "asterisk/module.h"
47 #include "asterisk/options.h"
48 #include "asterisk/rtp_engine.h"
49 #include "asterisk/astobj2.h"
50
51 struct ast_srtp {
52         struct ast_rtp_instance *rtp;
53         struct ao2_container *policies;
54         srtp_t session;
55         const struct ast_srtp_cb *cb;
56         void *data;
57         int warned;
58         unsigned char buf[8192 + AST_FRIENDLY_OFFSET];
59         unsigned char rtcpbuf[8192 + AST_FRIENDLY_OFFSET];
60 };
61
62 struct ast_srtp_policy {
63         srtp_policy_t sp;
64 };
65
66 static int g_initialized = 0;
67
68 /* SRTP functions */
69 static int ast_srtp_create(struct ast_srtp **srtp, struct ast_rtp_instance *rtp, struct ast_srtp_policy *policy);
70 static void ast_srtp_destroy(struct ast_srtp *srtp);
71 static int ast_srtp_add_stream(struct ast_srtp *srtp, struct ast_srtp_policy *policy);
72 static int ast_srtp_change_source(struct ast_srtp *srtp, unsigned int from_ssrc, unsigned int to_ssrc);
73
74 static int ast_srtp_unprotect(struct ast_srtp *srtp, void *buf, int *len, int rtcp);
75 static int ast_srtp_protect(struct ast_srtp *srtp, void **buf, int *len, int rtcp);
76 static void ast_srtp_set_cb(struct ast_srtp *srtp, const struct ast_srtp_cb *cb, void *data);
77 static int ast_srtp_get_random(unsigned char *key, size_t len);
78
79 /* Policy functions */
80 static struct ast_srtp_policy *ast_srtp_policy_alloc(void);
81 static void ast_srtp_policy_destroy(struct ast_srtp_policy *policy);
82 static int ast_srtp_policy_set_suite(struct ast_srtp_policy *policy, enum ast_srtp_suite suite);
83 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);
84 static void ast_srtp_policy_set_ssrc(struct ast_srtp_policy *policy, unsigned long ssrc, int inbound);
85
86 static struct ast_srtp_res srtp_res = {
87         .create = ast_srtp_create,
88         .destroy = ast_srtp_destroy,
89         .add_stream = ast_srtp_add_stream,
90         .change_source = ast_srtp_change_source,
91         .set_cb = ast_srtp_set_cb,
92         .unprotect = ast_srtp_unprotect,
93         .protect = ast_srtp_protect,
94         .get_random = ast_srtp_get_random
95 };
96
97 static struct ast_srtp_policy_res policy_res = {
98         .alloc = ast_srtp_policy_alloc,
99         .destroy = ast_srtp_policy_destroy,
100         .set_suite = ast_srtp_policy_set_suite,
101         .set_master_key = ast_srtp_policy_set_master_key,
102         .set_ssrc = ast_srtp_policy_set_ssrc
103 };
104
105 static const char *srtp_errstr(int err)
106 {
107         switch(err) {
108         case err_status_ok:
109                 return "nothing to report";
110         case err_status_fail:
111                 return "unspecified failure";
112         case err_status_bad_param:
113                 return "unsupported parameter";
114         case err_status_alloc_fail:
115                 return "couldn't allocate memory";
116         case err_status_dealloc_fail:
117                 return "couldn't deallocate properly";
118         case err_status_init_fail:
119                 return "couldn't initialize";
120         case err_status_terminus:
121                 return "can't process as much data as requested";
122         case err_status_auth_fail:
123                 return "authentication failure";
124         case err_status_cipher_fail:
125                 return "cipher failure";
126         case err_status_replay_fail:
127                 return "replay check failed (bad index)";
128         case err_status_replay_old:
129                 return "replay check failed (index too old)";
130         case err_status_algo_fail:
131                 return "algorithm failed test routine";
132         case err_status_no_such_op:
133                 return "unsupported operation";
134         case err_status_no_ctx:
135                 return "no appropriate context found";
136         case err_status_cant_check:
137                 return "unable to perform desired validation";
138         case err_status_key_expired:
139                 return "can't use key any more";
140         default:
141                 return "unknown";
142         }
143 }
144
145 static int policy_hash_fn(const void *obj, const int flags)
146 {
147         const struct ast_srtp_policy *policy = obj;
148
149         return policy->sp.ssrc.type == ssrc_specific ? policy->sp.ssrc.value : policy->sp.ssrc.type;
150 }
151
152 static int policy_cmp_fn(void *obj, void *arg, int flags)
153 {
154         const struct ast_srtp_policy *one = obj, *two = arg;
155
156         return one->sp.ssrc.type == two->sp.ssrc.type && one->sp.ssrc.value == two->sp.ssrc.value;
157 }
158
159 static struct ast_srtp_policy *find_policy(struct ast_srtp *srtp, const srtp_policy_t *policy, int flags)
160 {
161         struct ast_srtp_policy tmp = {
162                 .sp = {
163                         .ssrc.type = policy->ssrc.type,
164                         .ssrc.value = policy->ssrc.value,
165                 },
166         };
167
168         return ao2_t_find(srtp->policies, &tmp, flags, "Looking for policy");
169 }
170
171 static struct ast_srtp *res_srtp_new(void)
172 {
173         struct ast_srtp *srtp;
174
175         if (!(srtp = ast_calloc(1, sizeof(*srtp)))) {
176                 ast_log(LOG_ERROR, "Unable to allocate memory for srtp\n");
177                 return NULL;
178         }
179
180         if (!(srtp->policies = ao2_t_container_alloc(5, policy_hash_fn, policy_cmp_fn, "SRTP policy container"))) {
181                 ast_free(srtp);
182                 return NULL;
183         }
184         
185         srtp->warned = 1;
186
187         return srtp;
188 }
189
190 /*
191   struct ast_srtp_policy
192 */
193 static void srtp_event_cb(srtp_event_data_t *data)
194 {
195         switch (data->event) {
196         case event_ssrc_collision:
197                 ast_debug(1, "SSRC collision\n");
198                 break;
199         case event_key_soft_limit:
200                 ast_debug(1, "event_key_soft_limit\n");
201                 break;
202         case event_key_hard_limit:
203                 ast_debug(1, "event_key_hard_limit\n");
204                 break;
205         case event_packet_index_limit:
206                 ast_debug(1, "event_packet_index_limit\n");
207                 break;
208         }
209 }
210
211 static void ast_srtp_policy_set_ssrc(struct ast_srtp_policy *policy,
212                 unsigned long ssrc, int inbound)
213 {
214         if (ssrc) {
215                 policy->sp.ssrc.type = ssrc_specific;
216                 policy->sp.ssrc.value = ssrc;
217         } else {
218                 policy->sp.ssrc.type = inbound ? ssrc_any_inbound : ssrc_any_outbound;
219         }
220 }
221
222 static void policy_destructor(void *obj)
223 {
224         struct ast_srtp_policy *policy = obj;
225
226         if (policy->sp.key) {
227                 ast_free(policy->sp.key);
228                 policy->sp.key = NULL;
229         }
230 }
231
232 static struct ast_srtp_policy *ast_srtp_policy_alloc()
233 {
234         struct ast_srtp_policy *tmp;
235
236         if (!(tmp = ao2_t_alloc(sizeof(*tmp), policy_destructor, "Allocating policy"))) {
237                 ast_log(LOG_ERROR, "Unable to allocate memory for srtp_policy\n");
238         }
239
240         return tmp;
241 }
242
243 static void ast_srtp_policy_destroy(struct ast_srtp_policy *policy)
244 {
245         ao2_t_ref(policy, -1, "Destroying policy");
246 }
247
248 static int policy_set_suite(crypto_policy_t *p, enum ast_srtp_suite suite)
249 {
250         switch (suite) {
251         case AST_AES_CM_128_HMAC_SHA1_80:
252                 p->cipher_type = AES_128_ICM;
253                 p->cipher_key_len = 30;
254                 p->auth_type = HMAC_SHA1;
255                 p->auth_key_len = 20;
256                 p->auth_tag_len = 10;
257                 p->sec_serv = sec_serv_conf_and_auth;
258                 return 0;
259
260         case AST_AES_CM_128_HMAC_SHA1_32:
261                 p->cipher_type = AES_128_ICM;
262                 p->cipher_key_len = 30;
263                 p->auth_type = HMAC_SHA1;
264                 p->auth_key_len = 20;
265                 p->auth_tag_len = 4;
266                 p->sec_serv = sec_serv_conf_and_auth;
267                 return 0;
268
269         default:
270                 ast_log(LOG_ERROR, "Invalid crypto suite: %d\n", suite);
271                 return -1;
272         }
273 }
274
275 static int ast_srtp_policy_set_suite(struct ast_srtp_policy *policy, enum ast_srtp_suite suite)
276 {
277         return policy_set_suite(&policy->sp.rtp, suite) | policy_set_suite(&policy->sp.rtcp, suite);
278 }
279
280 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)
281 {
282         size_t size = key_len + salt_len;
283         unsigned char *master_key;
284
285         if (policy->sp.key) {
286                 ast_free(policy->sp.key);
287                 policy->sp.key = NULL;
288         }
289
290         if (!(master_key = ast_calloc(1, size))) {
291                 return -1;
292         }
293
294         memcpy(master_key, key, key_len);
295         memcpy(master_key + key_len, salt, salt_len);
296
297         policy->sp.key = master_key;
298
299         return 0;
300 }
301
302 static int ast_srtp_get_random(unsigned char *key, size_t len)
303 {
304         return crypto_get_random(key, len) != err_status_ok ? -1: 0;
305 }
306
307 static void ast_srtp_set_cb(struct ast_srtp *srtp, const struct ast_srtp_cb *cb, void *data)
308 {
309         if (!srtp) {
310                 return;
311         }
312
313         srtp->cb = cb;
314         srtp->data = data;
315 }
316
317 /* Vtable functions */
318 static int ast_srtp_unprotect(struct ast_srtp *srtp, void *buf, int *len, int rtcp)
319 {
320         int res = 0;
321         int i;
322         int retry = 0;
323         struct ast_rtp_instance_stats stats = {0,};
324
325 tryagain:
326
327         for (i = 0; i < 2; i++) {
328                 res = rtcp ? srtp_unprotect_rtcp(srtp->session, buf, len) : srtp_unprotect(srtp->session, buf, len);
329                 if (res != err_status_no_ctx) {
330                         break;
331                 }
332
333                 if (srtp->cb && srtp->cb->no_ctx) {
334                         if (ast_rtp_instance_get_stats(srtp->rtp, &stats, AST_RTP_INSTANCE_STAT_REMOTE_SSRC)) {
335                                 break;
336                         }
337                         if (srtp->cb->no_ctx(srtp->rtp, stats.remote_ssrc, srtp->data) < 0) {
338                                 break;
339                         }
340                 } else {
341                         break;
342                 }
343         }
344
345         if (retry == 0  && res == err_status_replay_old) {
346                 ast_log(LOG_WARNING, "SRTP unprotect: %s\n", srtp_errstr(res));
347
348                 if (srtp->session) {
349                         struct ast_srtp_policy *policy;
350                         struct ao2_iterator it;
351                         int policies_count;
352
353                         // dealloc first
354                         ast_log(LOG_WARNING, "SRTP destroy before re-create\n");
355                         srtp_dealloc(srtp->session);
356
357                         // get the count
358                         policies_count = ao2_container_count(srtp->policies);
359
360                         // get the first to build up
361                         it = ao2_iterator_init(srtp->policies, 0);
362                         policy = ao2_iterator_next(&it);
363
364                         ast_log(LOG_WARNING, "SRTP try to re-create\n");
365                         if (policy) {
366                                 if (srtp_create(&srtp->session, &policy->sp) == err_status_ok) {
367                                         ast_log(LOG_WARNING, "SRTP re-created with first policy\n");
368
369                                         // unref first element
370                                         ao2_t_ref(policy, -1, "Unreffing first policy for re-creating srtp session");
371
372                                         // if we have more than one policy, add them afterwards
373                                         if (policies_count > 1) {
374                                                 ast_log(LOG_WARNING, "Add all the other %d policies\n",
375                                                         policies_count - 1);
376                                                 while ((policy = ao2_iterator_next(&it))) {
377                                                         srtp_add_stream(srtp->session, &policy->sp);
378                                                         ao2_t_ref(policy, -1, "Unreffing n-th policy for re-creating srtp session");
379                                                 }
380                                         }
381
382                                         retry++;
383                                         ao2_iterator_destroy(&it);
384                                         goto tryagain;
385                                 }
386                                 ao2_t_ref(policy, -1, "Unreffing first policy after srtp_create failed");
387                         }
388                         ao2_iterator_destroy(&it);
389                 }
390         }
391
392         if (res != err_status_ok && res != err_status_replay_fail ) {
393                 if ((srtp->warned >= 10) && !((srtp->warned - 10) % 100)) {
394                         ast_log(LOG_WARNING, "SRTP unprotect: %s %d\n", srtp_errstr(res), srtp->warned);
395                         srtp->warned = 11;
396                 } else {
397                         srtp->warned++;
398                 }
399                 errno = EAGAIN;
400                 return -1;
401         }
402
403         return *len;
404 }
405
406 static int ast_srtp_protect(struct ast_srtp *srtp, void **buf, int *len, int rtcp)
407 {
408         int res;
409         unsigned char *localbuf;
410
411         if ((*len + SRTP_MAX_TRAILER_LEN) > sizeof(srtp->buf)) {
412                 return -1;
413         }
414         
415         localbuf = rtcp ? srtp->rtcpbuf : srtp->buf;
416
417         memcpy(localbuf, *buf, *len);
418
419         if ((res = rtcp ? srtp_protect_rtcp(srtp->session, localbuf, len) : srtp_protect(srtp->session, localbuf, len)) != err_status_ok && res != err_status_replay_fail) {
420                 ast_log(LOG_WARNING, "SRTP protect: %s\n", srtp_errstr(res));
421                 return -1;
422         }
423
424         *buf = localbuf;
425         return *len;
426 }
427
428 static int ast_srtp_create(struct ast_srtp **srtp, struct ast_rtp_instance *rtp, struct ast_srtp_policy *policy)
429 {
430         struct ast_srtp *temp;
431
432         if (!(temp = res_srtp_new())) {
433                 return -1;
434         }
435
436         if (srtp_create(&temp->session, &policy->sp) != err_status_ok) {
437                 return -1;
438         }
439
440         ast_module_ref(ast_module_info->self);
441         temp->rtp = rtp;
442         *srtp = temp;
443
444         ao2_t_link((*srtp)->policies, policy, "Created initial policy");
445
446         return 0;
447 }
448
449 static void ast_srtp_destroy(struct ast_srtp *srtp)
450 {
451         if (srtp->session) {
452                 srtp_dealloc(srtp->session);
453         }
454
455         ao2_t_callback(srtp->policies, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "Unallocate policy");
456         ao2_t_ref(srtp->policies, -1, "Destroying container");
457
458         ast_free(srtp);
459         ast_module_unref(ast_module_info->self);
460 }
461
462 static int ast_srtp_add_stream(struct ast_srtp *srtp, struct ast_srtp_policy *policy)
463 {
464         struct ast_srtp_policy *match;
465
466         if ((match = find_policy(srtp, &policy->sp, OBJ_POINTER))) {
467                 ast_debug(3, "Policy already exists, not re-adding\n");
468                 ao2_t_ref(match, -1, "Unreffing already existing policy");
469                 return -1;
470         }
471
472         if (srtp_add_stream(srtp->session, &policy->sp) != err_status_ok) {
473                 return -1;
474         }
475
476         ao2_t_link(srtp->policies, policy, "Added additional stream");
477
478         return 0;
479 }
480
481 static int ast_srtp_change_source(struct ast_srtp *srtp, unsigned int from_ssrc, unsigned int to_ssrc)
482 {
483         struct ast_srtp_policy *match;
484         struct srtp_policy_t sp = {
485                 .ssrc.type = ssrc_specific,
486                 .ssrc.value = from_ssrc,
487         };
488         err_status_t status;
489
490         /* If we find a mach, return and unlink it from the container so we
491          * can change the SSRC (which is part of the hash) and then have
492          * ast_srtp_add_stream link it back in if all is well */
493         if ((match = find_policy(srtp, &sp, OBJ_POINTER | OBJ_UNLINK))) {
494                 match->sp.ssrc.value = to_ssrc;
495                 if (ast_srtp_add_stream(srtp, match)) {
496                         ast_log(LOG_WARNING, "Couldn't add stream\n");
497                 } else if ((status = srtp_remove_stream(srtp->session, from_ssrc))) {
498                         ast_debug(3, "Couldn't remove stream (%d)\n", status);
499                 }
500                 ao2_t_ref(match, -1, "Unreffing found policy in change_source");
501         }
502
503         return 0;
504 }
505
506 static int res_srtp_init(void)
507 {
508         if (g_initialized) {
509                 return 0;
510         }
511
512         if (srtp_init() != err_status_ok) {
513                 return -1;
514         }
515
516         srtp_install_event_handler(srtp_event_cb);
517
518         return ast_rtp_engine_register_srtp(&srtp_res, &policy_res);
519 }
520
521 /*
522  * Exported functions
523  */
524
525 static int load_module(void)
526 {
527         return res_srtp_init();
528 }
529
530 static int unload_module(void)
531 {
532         ast_rtp_engine_unregister_srtp();
533         return 0;
534 }
535
536 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER, "Secure RTP (SRTP)",
537         .load = load_module,
538         .unload = unload_module,
539         .load_pri = AST_MODPRI_CHANNEL_DEPEND,
540 );