res_srtp.c 16 KB

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