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