2 * Secure RTP with libgcrypt
3 * Copyright (C) 2007 RĂ©mi Denis-Courmont <rdenis # simphalempin , com>
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
36 #define debug( ... ) (void)0
40 * - ROC profile thingy (multicast really needs this)
42 * Useless stuff (because nothing depends on it):
43 * - non-nul key derivation rate
47 typedef struct srtp_proto_t
49 gcry_cipher_hd_t cipher;
80 # include <winsock2.h>
82 # include <netinet/in.h>
84 GCRY_THREAD_OPTION_PTHREAD_IMPL;
87 static bool libgcrypt_usable = false;
89 static void initonce_libgcrypt (void)
91 if ((gcry_check_version ("1.1.94") == NULL)
92 || gcry_control (GCRYCTL_DISABLE_SECMEM, 0)
93 || gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0)
95 || gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread)
100 libgcrypt_usable = true;
103 static int init_libgcrypt (void)
107 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
108 static pthread_once_t once = PTHREAD_ONCE_INIT;
110 pthread_mutex_lock (&mutex);
111 pthread_once (&once, initonce_libgcrypt);
112 retval = -libgcrypt_usable;
113 pthread_mutex_unlock (&mutex);
115 # warning FIXME: This is not thread-safe.
116 if (!libgcrypt_usable)
117 initonce_libgcrypt ();
118 retval = -libgcrypt_usable;
126 static void proto_destroy (srtp_proto_t *p)
128 gcry_md_close (p->mac);
129 gcry_cipher_close (p->cipher);
134 * Releases all resources associated with a Secure RTP session.
136 void srtp_destroy (srtp_session_t *s)
140 proto_destroy (&s->rtcp);
141 proto_destroy (&s->rtp);
146 static int proto_create (srtp_proto_t *p, int gcipher, int gmd)
148 if (gcry_cipher_open (&p->cipher, gcipher, GCRY_CIPHER_MODE_CTR, 0) == 0)
150 if (gcry_md_open (&p->mac, gmd, GCRY_MD_FLAG_HMAC) == 0)
152 gcry_cipher_close (p->cipher);
159 * Allocates a Secure RTP one-way session.
160 * The same session cannot be used both ways because this would confuse
161 * internal cryptographic counters; it is however of course feasible to open
162 * multiple simultaneous sessions with the same master key.
164 * @param encr encryption algorithm number
165 * @param auth authentication algortihm number
166 * @param tag_len authentication tag byte length (NOT including RCC)
167 * @param flags OR'ed optional flags.
169 * @return NULL in case of error
172 srtp_create (int encr, int auth, unsigned tag_len, int prf, unsigned flags)
174 if ((flags & ~SRTP_FLAGS_MASK) || init_libgcrypt ())
181 cipher = GCRY_CIPHER_NONE;
184 case SRTP_ENCR_AES_CM:
185 cipher = GCRY_CIPHER_AES;
198 case SRTP_AUTH_HMAC_SHA1:
206 if (tag_len > gcry_md_get_algo_dlen (auth))
209 if (prf != SRTP_PRF_AES_CM)
212 srtp_session_t *s = malloc (sizeof (*s));
216 memset (s, 0, sizeof (*s));
218 s->tag_len = tag_len;
220 if (proto_create (&s->rtp, cipher, md) == 0)
222 if (proto_create (&s->rtcp, cipher, md) == 0)
224 proto_destroy (&s->rtp);
233 * Counter Mode encryption/decryption (ctr length = 16 bytes)
234 * with non-padded (truncated) text
237 ctr_crypt (gcry_cipher_hd_t hd, const void *ctr, uint8_t *data, size_t len)
239 const size_t ctrlen = 16;
240 div_t d = div (len, ctrlen);
242 if (gcry_cipher_setctr (hd, ctr, ctrlen)
243 || gcry_cipher_encrypt (hd, data, d.quot * ctrlen, NULL, 0))
248 /* Truncated last block */
249 uint8_t dummy[ctrlen];
250 data += d.quot * ctrlen;
251 memcpy (dummy, data, d.rem);
252 memset (dummy + d.rem, 0, ctrlen - d.rem);
254 if (gcry_cipher_encrypt (hd, dummy, ctrlen, data, ctrlen))
256 memcpy (data, dummy, d.rem);
264 * AES-CM key derivation (saltlen = 14 bytes)
267 derive (gcry_cipher_hd_t prf, const void *salt,
268 const uint8_t *r, size_t rlen, uint8_t label,
269 void *out, size_t outlen)
273 memcpy (iv, salt, 14);
277 iv[13 - rlen] ^= label;
278 for (size_t i = 0; i < rlen; i++)
279 iv[sizeof (iv) - rlen + i] ^= r[i];
281 memset (out, 0, outlen);
282 return ctr_crypt (prf, iv, out, outlen);
287 proto_derive (srtp_proto_t *p, gcry_cipher_hd_t prf,
288 const void *salt, size_t saltlen,
289 const uint8_t *r, size_t rlen, bool rtcp)
295 uint8_t label = rtcp ? SRTCP_CRYPT : SRTP_CRYPT;
297 if (derive (prf, salt, r, rlen, label++, keybuf, 16)
298 || gcry_cipher_setkey (p->cipher, keybuf, 16)
299 || derive (prf, salt, r, rlen, label++, keybuf, 20)
300 || gcry_md_setkey (p->mac, keybuf, 20)
301 || derive (prf, salt, r, rlen, label, p->salt, 14))
309 * SRTP/SRTCP cipher/salt/MAC keys derivation.
312 srtp_derive (srtp_session_t *s, const void *key, size_t keylen,
313 const void *salt, size_t saltlen)
315 gcry_cipher_hd_t prf;
318 if (gcry_cipher_open (&prf, GCRY_CIPHER_AES, GCRY_CIPHER_MODE_CTR, 0)
319 || gcry_cipher_setkey (prf, key, keylen))
322 /* RTP key derivation */
325 uint64_t index = (((uint64_t)s->rtp_roc) << 16) | s->rtp_seq;
328 for (int i = sizeof (r) - 1; i >= 0; i--)
335 memset (r, 0, sizeof (r));
337 if (proto_derive (&s->rtp, prf, salt, saltlen, r, 6, false))
340 /* RTCP key derivation */
341 memcpy (r, &(uint32_t){ htonl (s->rtcp_index) }, 4);
342 if (proto_derive (&s->rtcp, prf, salt, saltlen, r, 4, true))
345 (void)gcry_cipher_close (prf);
351 * Sets (or resets) the master key and master salt for a SRTP session.
352 * This must be done at least once before using rtp_send(), rtp_recv(),
353 * rtcp_send() or rtcp_recv(). Also, rekeying is required every
354 * 2^48 RTP packets or 2^31 RTCP packets (whichever comes first),
355 * otherwise the protocol security might be broken.
357 * @return 0 on success, in case of error:
358 * EINVAL invalid or unsupported key/salt sizes combination
361 srtp_setkey (srtp_session_t *s, const void *key, size_t keylen,
362 const void *salt, size_t saltlen)
364 return srtp_derive (s, key, keylen, salt, saltlen) ? EINVAL : 0;
369 * Sets Roll-over-Counter Carry (RCC) rate for the SRTP session. If not
370 * specified (through this function), the default rate of ONE is assumed
371 * (i.e. every RTP packets will carry the RoC). RCC rate is ignored if none
372 * of the RCC mode has been selected.
374 * The RCC mode is selected through one of these flags for srtp_create():
375 * SRTP_RCC_MODE1: integrity protection only for RoC carrying packets
376 * SRTP_RCC_MODE2: integrity protection for all packets
377 * SRTP_RCC_MODE3: no integrity protection
379 * RCC mode 3 is insecure. Compared to plain RTP, it provides confidentiality
380 * (through encryption) but is much more prone to DoS. It can only be used if
381 * anti-spoofing protection is provided by lower network layers (e.g. IPsec,
382 * or trusted routers and proper source address filtering).
384 * If RCC rate is 1, RCC mode 1 and 2 are functionally identical.
386 * @param rate RoC Carry rate (MUST NOT be zero)
388 void srtp_setrcc_rate (srtp_session_t *s, uint16_t rate)
395 /** AES-CM for RTP (salt = 14 bytes + 2 nul bytes) */
397 rtp_crypt (gcry_cipher_hd_t hd, uint32_t ssrc, uint32_t roc, uint16_t seq,
398 const uint32_t *salt, uint8_t *data, size_t len)
400 /* Determines cryptographic counter (IV) */
402 counter[0] = salt[0];
403 counter[1] = salt[1] ^ ssrc;
404 counter[2] = salt[2] ^ htonl (roc);
405 counter[3] = salt[3] ^ htonl (seq << 16);
408 return ctr_crypt (hd, counter, data, len);
412 /** Determines SRTP Roll-Over-Counter (in host-byte order) */
414 srtp_compute_roc (const srtp_session_t *s, uint16_t seq)
416 uint32_t roc = s->rtp_roc;
418 if (((seq - s->rtp_seq) & 0xffff) < 0x8000)
420 /* Sequence is ahead, good */
421 if (seq < s->rtp_seq)
422 roc++; /* Sequence number wrap */
426 /* Sequence is late, bad */
427 if (seq > s->rtp_seq)
428 roc--; /* Wrap back */
434 /** Returns RTP sequence (in host-byte order) */
435 static inline uint16_t rtp_seq (const uint8_t *buf)
437 return (buf[2] << 8) | buf[3];
441 /** Message Authentication and Integrity for RTP */
442 static const uint8_t *
443 rtp_digest (srtp_session_t *s, const uint8_t *data, size_t len)
445 const gcry_md_hd_t md = s->rtp.mac;
446 uint32_t roc = htonl (srtp_compute_roc (s, rtp_seq (data)));
449 gcry_md_write (md, data, len);
450 gcry_md_write (md, &roc, 4);
451 return gcry_md_read (md, 0);
456 * Encrypts/decrypts a RTP packet and updates SRTP context
457 * (CTR block cypher mode of operation has identical encryption and
458 * decryption function).
460 * @param buf RTP packet to be en-/decrypted
461 * @param len RTP packet length
463 * @return 0 on success, in case of error:
464 * EINVAL malformatted RTP packet
465 * EACCES replayed packet or out-of-window or sync lost
467 static int srtp_crypt (srtp_session_t *s, uint8_t *buf, size_t len)
471 if ((len < 12) || ((buf[0] >> 6) != 2))
474 /* Computes encryption offset */
475 uint16_t offset = 12;
476 offset += (buf[0] & 0xf) * 4; // skips CSRC
486 memcpy (&extlen, buf + offset - 2, 2);
487 offset += htons (extlen); // skips RTP extension header
493 /* Determines RTP 48-bits counter and SSRC */
494 uint16_t seq = rtp_seq (buf);
495 uint32_t roc = srtp_compute_roc (s, seq), ssrc;
496 memcpy (&ssrc, buf + 8, 4);
498 /* Updates ROC and sequence (it's safe now) */
499 int16_t diff = seq - s->rtp_seq;
502 /* Sequence in the future, good */
503 s->rtp.window = s->rtp.window << diff;
505 s->rtp_seq = seq, s->rtp_roc = roc;
509 /* Sequence in the past/present, bad */
511 if ((diff >= 64) || ((s->rtp.window >> diff) & 1))
512 return EACCES; /* Replay attack */
513 s->rtp.window |= 1 << diff;
516 /* Encrypt/Decrypt */
517 if (s->flags & SRTP_UNENCRYPTED)
520 if (rtp_crypt (s->rtp.cipher, ssrc, roc, seq, s->rtp.salt,
521 buf + offset, len - offset))
529 * Turns a RTP packet into a SRTP packet: encrypt it, then computes
530 * the authentication tag and appends it.
531 * Note that you can encrypt packet in disorder.
533 * @param buf RTP packet to be encrypted/digested
534 * @param lenp pointer to the RTP packet length on entry,
535 * set to the SRTP length on exit (undefined in case of error)
536 * @param bufsize size (bytes) of the packet buffer
538 * @return 0 on success, in case of error:
539 * EINVAL malformatted RTP packet or internal error
540 * ENOSPC bufsize is too small (to add authentication tag)
541 * EACCES packet would trigger a replay error on receiver
544 srtp_send (srtp_session_t *s, uint8_t *buf, size_t *lenp, size_t bufsize)
547 int val = srtp_crypt (s, buf, len);
551 if (!(s->flags & SRTP_UNAUTHENTICATED))
553 if (bufsize < (len + s->tag_len))
556 const uint8_t *tag = rtp_digest (s, buf, len);
557 memcpy (buf + len, tag, s->tag_len);
558 *lenp = len + s->tag_len;
566 * Turns a SRTP packet into a RTP packet: authenticates the packet,
569 * @param buf RTP packet to be digested/decrypted
570 * @param lenp pointer to the SRTP packet length on entry,
571 * set to the RTP length on exit (undefined in case of error)
573 * @return 0 on success, in case of error:
574 * EINVAL malformatted SRTP packet
575 * EACCES authentication failed (spoofed packet or out-of-sync)
578 srtp_recv (srtp_session_t *s, uint8_t *buf, size_t *lenp)
582 if (!(s->flags & SRTP_UNAUTHENTICATED))
584 if (len < (12u + s->tag_len))
588 const uint8_t *tag = rtp_digest (s, buf, len);
589 if (memcmp (buf + len, tag, s->tag_len))
595 return srtp_crypt (s, buf, len);
599 /** AES-CM for RTCP (salt = 14 bytes + 2 nul bytes) */
601 rtcp_crypt (gcry_cipher_hd_t hd, uint32_t ssrc, uint32_t index,
602 const uint32_t *salt, uint8_t *data, size_t len)
604 return rtp_crypt (hd, ssrc, index >> 16, index & 0xffff, salt, data, len);
608 /** Message Authentication and Integrity for RTCP */
609 static const uint8_t *
610 rtcp_digest (gcry_md_hd_t md, const void *data, size_t len)
613 gcry_md_write (md, data, len);
614 return gcry_md_read (md, 0);
619 * Encrypts/decrypts a RTCP packet and updates SRTCP context
620 * (CTR block cypher mode of operation has identical encryption and
621 * decryption function).
623 * @param buf RTCP packet to be en-/decrypted
624 * @param len RTCP packet length
626 * @return 0 on success, in case of error:
627 * EINVAL malformatted RTCP packet
629 static int srtcp_crypt (srtp_session_t *s, uint8_t *buf, size_t len)
633 /* 8-bytes unencrypted header, and 4-bytes unencrypted footer */
634 if ((len < 12) || ((buf[0] >> 6) != 2))
638 memcpy (&index, buf + len, 4);
639 index = ntohl (index);
640 if (((index >> 31) != 0) != ((s->flags & SRTCP_UNENCRYPTED) == 0))
641 return EINVAL; // E-bit mismatch
643 index &= ~(1 << 31); // clear E-bit for counter
645 /* Updates SRTCP index (safe here) */
646 int32_t diff = index - s->rtcp_index;
649 /* Packet in the future, good */
650 s->rtcp.window = s->rtcp.window << diff;
652 s->rtcp_index = index;
656 /* Packet in the past/present, bad */
658 if ((diff >= 64) || ((s->rtcp.window >> diff) & 1))
659 return EACCES; // replay attack!
660 s->rtp.window |= 1 << diff;
664 if (s->flags & SRTCP_UNENCRYPTED)
668 memcpy (&ssrc, buf + 4, 4);
670 if (rtcp_crypt (s->rtcp.cipher, ssrc, index, s->rtp.salt,
678 * Turns a RTCP packet into a SRTCP packet: encrypt it, then computes
679 * the authentication tag and appends it.
681 * @param buf RTCP packet to be encrypted/digested
682 * @param lenp pointer to the RTCP packet length on entry,
683 * set to the SRTCP length on exit (undefined in case of error)
684 * @param bufsize size (bytes) of the packet buffer
686 * @return 0 on success, in case of error:
687 * EINVAL malformatted RTCP packet or internal error
688 * ENOSPC bufsize is too small (to add index and authentication tag)
691 srtcp_send (srtp_session_t *s, uint8_t *buf, size_t *lenp, size_t bufsize)
694 if (bufsize < (len + 4 + s->tag_len))
697 uint32_t index = ++s->rtcp_index;
699 s->rtcp_index = index = 0; /* 31-bit wrap */
701 if ((s->flags & SRTCP_UNENCRYPTED) == 0)
702 index |= 0x80000000; /* Set Encrypted bit */
703 memcpy (buf + len, &(uint32_t){ htonl (index) }, 4);
705 int val = srtcp_crypt (s, buf, len);
709 len += 4; /* Digests SRTCP index too */
711 const uint8_t *tag = rtcp_digest (s->rtp.mac, buf, len);
712 memcpy (buf + len, tag, s->tag_len);
713 *lenp = len + s->tag_len;
719 * Turns a SRTCP packet into a RTCP packet: authenticates the packet,
722 * @param buf RTCP packet to be digested/decrypted
723 * @param lenp pointer to the SRTCP packet length on entry,
724 * set to the RTCP length on exit (undefined in case of error)
726 * @return 0 on success, in case of error:
727 * EINVAL malformatted SRTCP packet
728 * EACCES authentication failed (spoofed packet or out-of-sync)
731 srtcp_recv (srtp_session_t *s, uint8_t *buf, size_t *lenp)
735 if (len < (4u + s->tag_len))
739 const uint8_t *tag = rtcp_digest (s->rtp.mac, buf, len);
740 if (memcmp (buf + len, tag, s->tag_len))
743 len -= 4; /* Remove SRTCP index before decryption */
745 return srtp_crypt (s, buf, len);