📄 srtp.c
字号:
/* * Secure RTP with libgcrypt * Copyright (C) 2007 Rémi Denis-Courmont <rdenis # simphalempin , com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA *//* TODO: * Useless stuff (because nothing depends on it): * - non-nul key derivation rate * - MKI payload */#ifdef HAVE_CONFIG_H# include <config.h>#endif#include <stdint.h>#include <stddef.h>#include "srtp.h"#include <stdbool.h>#include <stdlib.h>#include <assert.h>#include <errno.h>#include <gcrypt.h>#ifdef WIN32# include <winsock2.h>#else# include <netinet/in.h># include <pthread.h>GCRY_THREAD_OPTION_PTHREAD_IMPL;#endif#define debug( ... ) (void)0typedef struct srtp_proto_t{ gcry_cipher_hd_t cipher; gcry_md_hd_t mac; uint64_t window; uint32_t salt[4];} srtp_proto_t;struct srtp_session_t{ srtp_proto_t rtp; srtp_proto_t rtcp; unsigned flags; unsigned kdr; uint32_t rtcp_index; uint32_t rtp_roc; uint16_t rtp_seq; uint16_t rtp_rcc; uint8_t tag_len;};enum{ SRTP_CRYPT, SRTP_AUTH, SRTP_SALT, SRTCP_CRYPT, SRTCP_AUTH, SRTCP_SALT};static inline unsigned rcc_mode (const srtp_session_t *s){ return (s->flags >> 4) & 3;}static bool libgcrypt_usable = false;static void initonce_libgcrypt (void){#ifndef WIN32 gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);#endif if ((gcry_check_version ("1.1.94") == NULL) || gcry_control (GCRYCTL_DISABLE_SECMEM, 0) || gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0)) return; libgcrypt_usable = true;}static int init_libgcrypt (void){ int retval;#ifndef WIN32 static pthread_once_t once = PTHREAD_ONCE_INIT; pthread_once (&once, initonce_libgcrypt);#else# warning FIXME: This is not thread-safe. if (!libgcrypt_usable) initonce_libgcrypt ();#endif retval = libgcrypt_usable ? 0 : -1; return retval;}static void proto_destroy (srtp_proto_t *p){ gcry_md_close (p->mac); gcry_cipher_close (p->cipher);}/** * Releases all resources associated with a Secure RTP session. */void srtp_destroy (srtp_session_t *s){ assert (s != NULL); proto_destroy (&s->rtcp); proto_destroy (&s->rtp); free (s);}static int proto_create (srtp_proto_t *p, int gcipher, int gmd){ if (gcry_cipher_open (&p->cipher, gcipher, GCRY_CIPHER_MODE_CTR, 0) == 0) { if (gcry_md_open (&p->mac, gmd, GCRY_MD_FLAG_HMAC) == 0) return 0; gcry_cipher_close (p->cipher); } return -1;}/** * Allocates a Secure RTP one-way session. * The same session cannot be used both ways because this would confuse * internal cryptographic counters; it is however of course feasible to open * multiple simultaneous sessions with the same master key. * * @param encr encryption algorithm number * @param auth authentication algortihm number * @param tag_len authentication tag byte length (NOT including RCC) * @param flags OR'ed optional flags. * * @return NULL in case of error */srtp_session_t *srtp_create (int encr, int auth, unsigned tag_len, int prf, unsigned flags){ if ((flags & ~SRTP_FLAGS_MASK) || init_libgcrypt ()) return NULL; int cipher, md; switch (encr) { case SRTP_ENCR_NULL: cipher = GCRY_CIPHER_NONE; break; case SRTP_ENCR_AES_CM: cipher = GCRY_CIPHER_AES; break; default: return NULL; } switch (auth) { case SRTP_AUTH_NULL: md = GCRY_MD_NONE; break; case SRTP_AUTH_HMAC_SHA1: md = GCRY_MD_SHA1; break; default: return NULL; } if (tag_len > gcry_md_get_algo_dlen (md)) return NULL; if (prf != SRTP_PRF_AES_CM) return NULL; srtp_session_t *s = malloc (sizeof (*s)); if (s == NULL) return NULL; memset (s, 0, sizeof (*s)); s->flags = flags; s->tag_len = tag_len; s->rtp_rcc = 1; /* Default RCC rate */ if (rcc_mode (s)) { if (tag_len < 4) goto error; } if (proto_create (&s->rtp, cipher, md) == 0) { if (proto_create (&s->rtcp, cipher, md) == 0) return s; proto_destroy (&s->rtp); }error: free (s); return NULL;}/** * Counter Mode encryption/decryption (ctr length = 16 bytes) * with non-padded (truncated) text */static intctr_crypt (gcry_cipher_hd_t hd, const void *ctr, uint8_t *data, size_t len){ const size_t ctrlen = 16; div_t d = div (len, ctrlen); if (gcry_cipher_setctr (hd, ctr, ctrlen) || gcry_cipher_encrypt (hd, data, d.quot * ctrlen, NULL, 0)) return -1; if (d.rem) { /* Truncated last block */ uint8_t dummy[ctrlen]; data += d.quot * ctrlen; memcpy (dummy, data, d.rem); memset (dummy + d.rem, 0, ctrlen - d.rem); if (gcry_cipher_encrypt (hd, dummy, ctrlen, data, ctrlen)) return -1; memcpy (data, dummy, d.rem); } return 0;}/** * AES-CM key derivation (saltlen = 14 bytes) */static intderive (gcry_cipher_hd_t prf, const void *salt, const uint8_t *r, size_t rlen, uint8_t label, void *out, size_t outlen){ uint8_t iv[16]; memcpy (iv, salt, 14); iv[14] = iv[15] = 0; assert (rlen < 14); iv[13 - rlen] ^= label; for (size_t i = 0; i < rlen; i++) iv[sizeof (iv) - rlen + i] ^= r[i]; memset (out, 0, outlen); return ctr_crypt (prf, iv, out, outlen);}static intproto_derive (srtp_proto_t *p, gcry_cipher_hd_t prf, const void *salt, size_t saltlen, const uint8_t *r, size_t rlen, bool rtcp){ if (saltlen != 14) return -1; uint8_t keybuf[20]; uint8_t label = rtcp ? SRTCP_CRYPT : SRTP_CRYPT; if (derive (prf, salt, r, rlen, label++, keybuf, 16) || gcry_cipher_setkey (p->cipher, keybuf, 16) || derive (prf, salt, r, rlen, label++, keybuf, 20) || gcry_md_setkey (p->mac, keybuf, 20) || derive (prf, salt, r, rlen, label, p->salt, 14)) return -1; return 0;}/** * SRTP/SRTCP cipher/salt/MAC keys derivation. */static intsrtp_derive (srtp_session_t *s, const void *key, size_t keylen, const void *salt, size_t saltlen){ gcry_cipher_hd_t prf; uint8_t r[6]; if (gcry_cipher_open (&prf, GCRY_CIPHER_AES, GCRY_CIPHER_MODE_CTR, 0) || gcry_cipher_setkey (prf, key, keylen)) return -1;#if 0 /* RTP key derivation */ if (s->kdr != 0) { uint64_t index = (((uint64_t)s->rtp_roc) << 16) | s->rtp_seq; index /= s->kdr; for (int i = sizeof (r) - 1; i >= 0; i--) { r[i] = index & 0xff; index = index >> 8; } } else#endif memset (r, 0, sizeof (r)); if (proto_derive (&s->rtp, prf, salt, saltlen, r, 6, false)) return -1; /* RTCP key derivation */ memcpy (r, &(uint32_t){ htonl (s->rtcp_index) }, 4); if (proto_derive (&s->rtcp, prf, salt, saltlen, r, 4, true)) return -1; (void)gcry_cipher_close (prf); return 0;}/** * Sets (or resets) the master key and master salt for a SRTP session. * This must be done at least once before using rtp_send(), rtp_recv(), * rtcp_send() or rtcp_recv(). Also, rekeying is required every * 2^48 RTP packets or 2^31 RTCP packets (whichever comes first), * otherwise the protocol security might be broken. * * @return 0 on success, in case of error: * EINVAL invalid or unsupported key/salt sizes combination */intsrtp_setkey (srtp_session_t *s, const void *key, size_t keylen, const void *salt, size_t saltlen){ return srtp_derive (s, key, keylen, salt, saltlen) ? EINVAL : 0;}static int hexdigit (char c){ if ((c >= '0') && (c <= '9')) return c - '0'; if ((c >= 'A') && (c <= 'F')) return c - 'A' + 0xA; if ((c >= 'a') && (c <= 'f')) return c - 'a' + 0xa; return -1;}static ssize_t hexstring (const char *in, uint8_t *out, size_t outlen){ size_t inlen = strlen (in); if ((inlen > (2 * outlen)) || (inlen & 1)) return -1; for (size_t i = 0; i < inlen; i += 2) { int a = hexdigit (in[i]), b = hexdigit (in[i + 1]); if ((a == -1) || (b == -1)) return -1; out[i / 2] = (a << 4) | b; } return inlen / 2;}/** * Sets (or resets) the master key and master salt for a SRTP session * from hexadecimal strings. See also srtp_setkey(). * * @return 0 on success, in case of error: * EINVAL invalid or unsupported key/salt sizes combination */intsrtp_setkeystring (srtp_session_t *s, const char *key, const char *salt){ uint8_t bkey[16]; /* TODO/NOTE: hard-coded for AES */ uint8_t bsalt[14]; /* TODO/NOTE: hard-coded for the PRF-AES-CM */ ssize_t bkeylen = hexstring (key, bkey, sizeof (bkey)); ssize_t bsaltlen = hexstring (salt, bsalt, sizeof (bsalt)); if ((bkeylen == -1) || (bsaltlen == -1)) return EINVAL; return srtp_setkey (s, bkey, bkeylen, bsalt, bsaltlen) ? EINVAL : 0;}/** * Sets Roll-over-Counter Carry (RCC) rate for the SRTP session. If not * specified (through this function), the default rate of ONE is assumed * (i.e. every RTP packets will carry the RoC). RCC rate is ignored if none * of the RCC mode has been selected. * * The RCC mode is selected through one of these flags for srtp_create(): * SRTP_RCC_MODE1: integrity protection only for RoC carrying packets * SRTP_RCC_MODE2: integrity protection for all packets * SRTP_RCC_MODE3: no integrity protection * * RCC mode 3 is insecure. Compared to plain RTP, it provides confidentiality * (through encryption) but is much more prone to DoS. It can only be used if * anti-spoofing protection is provided by lower network layers (e.g. IPsec, * or trusted routers and proper source address filtering).
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -