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