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
21 * Useless stuff (because nothing depends on it):
22 * - non-nul key derivation rate
43 # include <winsock2.h>
45 # include <netinet/in.h>
47 GCRY_THREAD_OPTION_PTHREAD_IMPL;
50 #define debug( ... ) (void)0
52 typedef struct srtp_proto_t
54 gcry_cipher_hd_t cipher;
84 static inline unsigned rcc_mode (const srtp_session_t *s)
86 return (s->flags >> 4) & 3;
89 static bool libgcrypt_usable = false;
91 static void initonce_libgcrypt (void)
94 gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
97 if ((gcry_check_version ("1.1.94") == NULL)
98 || gcry_control (GCRYCTL_DISABLE_SECMEM, 0)
99 || gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0))
102 libgcrypt_usable = true;
105 static int init_libgcrypt (void)
109 static pthread_once_t once = PTHREAD_ONCE_INIT;
111 pthread_once (&once, initonce_libgcrypt);
113 # warning FIXME: This is not thread-safe.
114 if (!libgcrypt_usable)
115 initonce_libgcrypt ();
118 retval = libgcrypt_usable ? 0 : -1;
125 static void proto_destroy (srtp_proto_t *p)
127 gcry_md_close (p->mac);
128 gcry_cipher_close (p->cipher);
133 * Releases all resources associated with a Secure RTP session.
135 void srtp_destroy (srtp_session_t *s)
139 proto_destroy (&s->rtcp);
140 proto_destroy (&s->rtp);
145 static int proto_create (srtp_proto_t *p, int gcipher, int gmd)
147 if (gcry_cipher_open (&p->cipher, gcipher, GCRY_CIPHER_MODE_CTR, 0) == 0)
149 if (gcry_md_open (&p->mac, gmd, GCRY_MD_FLAG_HMAC) == 0)
151 gcry_cipher_close (p->cipher);
158 * Allocates a Secure RTP one-way session.
159 * The same session cannot be used both ways because this would confuse
160 * internal cryptographic counters; it is however of course feasible to open
161 * multiple simultaneous sessions with the same master key.
163 * @param encr encryption algorithm number
164 * @param auth authentication algortihm number
165 * @param tag_len authentication tag byte length (NOT including RCC)
166 * @param flags OR'ed optional flags.
168 * @return NULL in case of error
171 srtp_create (int encr, int auth, unsigned tag_len, int prf, unsigned flags)
173 if ((flags & ~SRTP_FLAGS_MASK) || init_libgcrypt ())
180 cipher = GCRY_CIPHER_NONE;
183 case SRTP_ENCR_AES_CM:
184 cipher = GCRY_CIPHER_AES;
197 case SRTP_AUTH_HMAC_SHA1:
205 if (tag_len > gcry_md_get_algo_dlen (md))
208 if (prf != SRTP_PRF_AES_CM)
211 srtp_session_t *s = malloc (sizeof (*s));
215 memset (s, 0, sizeof (*s));
217 s->tag_len = tag_len;
218 s->rtp_rcc = 1; /* Default RCC rate */
225 if (proto_create (&s->rtp, cipher, md) == 0)
227 if (proto_create (&s->rtcp, cipher, md) == 0)
229 proto_destroy (&s->rtp);
239 * Counter Mode encryption/decryption (ctr length = 16 bytes)
240 * with non-padded (truncated) text
243 ctr_crypt (gcry_cipher_hd_t hd, const void *ctr, uint8_t *data, size_t len)
245 const size_t ctrlen = 16;
246 div_t d = div (len, ctrlen);
248 if (gcry_cipher_setctr (hd, ctr, ctrlen)
249 || gcry_cipher_encrypt (hd, data, d.quot * ctrlen, NULL, 0))
254 /* Truncated last block */
255 uint8_t dummy[ctrlen];
256 data += d.quot * ctrlen;
257 memcpy (dummy, data, d.rem);
258 memset (dummy + d.rem, 0, ctrlen - d.rem);
260 if (gcry_cipher_encrypt (hd, dummy, ctrlen, data, ctrlen))
262 memcpy (data, dummy, d.rem);
270 * AES-CM key derivation (saltlen = 14 bytes)
273 derive (gcry_cipher_hd_t prf, const void *salt,
274 const uint8_t *r, size_t rlen, uint8_t label,
275 void *out, size_t outlen)
279 memcpy (iv, salt, 14);
283 iv[13 - rlen] ^= label;
284 for (size_t i = 0; i < rlen; i++)
285 iv[sizeof (iv) - rlen + i] ^= r[i];
287 memset (out, 0, outlen);
288 return ctr_crypt (prf, iv, out, outlen);
293 proto_derive (srtp_proto_t *p, gcry_cipher_hd_t prf,
294 const void *salt, size_t saltlen,
295 const uint8_t *r, size_t rlen, bool rtcp)
301 uint8_t label = rtcp ? SRTCP_CRYPT : SRTP_CRYPT;
303 if (derive (prf, salt, r, rlen, label++, keybuf, 16)
304 || gcry_cipher_setkey (p->cipher, keybuf, 16)
305 || derive (prf, salt, r, rlen, label++, keybuf, 20)
306 || gcry_md_setkey (p->mac, keybuf, 20)
307 || derive (prf, salt, r, rlen, label, p->salt, 14))
315 * SRTP/SRTCP cipher/salt/MAC keys derivation.
318 srtp_derive (srtp_session_t *s, const void *key, size_t keylen,
319 const void *salt, size_t saltlen)
321 gcry_cipher_hd_t prf;
324 if (gcry_cipher_open (&prf, GCRY_CIPHER_AES, GCRY_CIPHER_MODE_CTR, 0)
325 || gcry_cipher_setkey (prf, key, keylen))
329 /* RTP key derivation */
332 uint64_t index = (((uint64_t)s->rtp_roc) << 16) | s->rtp_seq;
335 for (int i = sizeof (r) - 1; i >= 0; i--)
343 memset (r, 0, sizeof (r));
345 if (proto_derive (&s->rtp, prf, salt, saltlen, r, 6, false))
348 /* RTCP key derivation */
349 memcpy (r, &(uint32_t){ htonl (s->rtcp_index) }, 4);
350 if (proto_derive (&s->rtcp, prf, salt, saltlen, r, 4, true))
353 (void)gcry_cipher_close (prf);
359 * Sets (or resets) the master key and master salt for a SRTP session.
360 * This must be done at least once before using rtp_send(), rtp_recv(),
361 * rtcp_send() or rtcp_recv(). Also, rekeying is required every
362 * 2^48 RTP packets or 2^31 RTCP packets (whichever comes first),
363 * otherwise the protocol security might be broken.
365 * @return 0 on success, in case of error:
366 * EINVAL invalid or unsupported key/salt sizes combination
369 srtp_setkey (srtp_session_t *s, const void *key, size_t keylen,
370 const void *salt, size_t saltlen)
372 return srtp_derive (s, key, keylen, salt, saltlen) ? EINVAL : 0;
377 * Sets Roll-over-Counter Carry (RCC) rate for the SRTP session. If not
378 * specified (through this function), the default rate of ONE is assumed
379 * (i.e. every RTP packets will carry the RoC). RCC rate is ignored if none
380 * of the RCC mode has been selected.
382 * The RCC mode is selected through one of these flags for srtp_create():
383 * SRTP_RCC_MODE1: integrity protection only for RoC carrying packets
384 * SRTP_RCC_MODE2: integrity protection for all packets
385 * SRTP_RCC_MODE3: no integrity protection
387 * RCC mode 3 is insecure. Compared to plain RTP, it provides confidentiality
388 * (through encryption) but is much more prone to DoS. It can only be used if
389 * anti-spoofing protection is provided by lower network layers (e.g. IPsec,
390 * or trusted routers and proper source address filtering).
392 * If RCC rate is 1, RCC mode 1 and 2 are functionally identical.
394 * @param rate RoC Carry rate (MUST NOT be zero)
396 void srtp_setrcc_rate (srtp_session_t *s, uint16_t rate)
403 /** AES-CM for RTP (salt = 14 bytes + 2 nul bytes) */
405 rtp_crypt (gcry_cipher_hd_t hd, uint32_t ssrc, uint32_t roc, uint16_t seq,
406 const uint32_t *salt, uint8_t *data, size_t len)
408 /* Determines cryptographic counter (IV) */
410 counter[0] = salt[0];
411 counter[1] = salt[1] ^ ssrc;
412 counter[2] = salt[2] ^ htonl (roc);
413 counter[3] = salt[3] ^ htonl (seq << 16);
416 return ctr_crypt (hd, counter, data, len);
420 /** Determines SRTP Roll-Over-Counter (in host-byte order) */
422 srtp_compute_roc (const srtp_session_t *s, uint16_t seq)
424 uint32_t roc = s->rtp_roc;
426 if (((seq - s->rtp_seq) & 0xffff) < 0x8000)
428 /* Sequence is ahead, good */
429 if (seq < s->rtp_seq)
430 roc++; /* Sequence number wrap */
434 /* Sequence is late, bad */
435 if (seq > s->rtp_seq)
436 roc--; /* Wrap back */
442 /** Returns RTP sequence (in host-byte order) */
443 static inline uint16_t rtp_seq (const uint8_t *buf)
445 return (buf[2] << 8) | buf[3];
449 /** Message Authentication and Integrity for RTP */
450 static const uint8_t *
451 rtp_digest (srtp_session_t *s, const uint8_t *data, size_t len,
454 const gcry_md_hd_t md = s->rtp.mac;
457 gcry_md_write (md, data, len);
458 gcry_md_write (md, &(uint32_t){ htonl (roc) }, 4);
459 return gcry_md_read (md, 0);
464 * Encrypts/decrypts a RTP packet and updates SRTP context
465 * (CTR block cypher mode of operation has identical encryption and
466 * decryption function).
468 * @param buf RTP packet to be en-/decrypted
469 * @param len RTP packet length
471 * @return 0 on success, in case of error:
472 * EINVAL malformatted RTP packet
473 * EACCES replayed packet or out-of-window or sync lost
475 static int srtp_crypt (srtp_session_t *s, uint8_t *buf, size_t len)
479 if ((len < 12) || ((buf[0] >> 6) != 2))
482 /* Computes encryption offset */
483 uint16_t offset = 12;
484 offset += (buf[0] & 0xf) * 4; // skips CSRC
494 memcpy (&extlen, buf + offset - 2, 2);
495 offset += htons (extlen); // skips RTP extension header
501 /* Determines RTP 48-bits counter and SSRC */
502 uint16_t seq = rtp_seq (buf);
503 uint32_t roc = srtp_compute_roc (s, seq), ssrc;
504 memcpy (&ssrc, buf + 8, 4);
506 /* Updates ROC and sequence (it's safe now) */
507 int16_t diff = seq - s->rtp_seq;
510 /* Sequence in the future, good */
511 s->rtp.window = s->rtp.window << diff;
513 s->rtp_seq = seq, s->rtp_roc = roc;
517 /* Sequence in the past/present, bad */
519 if ((diff >= 64) || ((s->rtp.window >> diff) & 1))
520 return EACCES; /* Replay attack */
521 s->rtp.window |= 1 << diff;
524 /* Encrypt/Decrypt */
525 if (s->flags & SRTP_UNENCRYPTED)
528 if (rtp_crypt (s->rtp.cipher, ssrc, roc, seq, s->rtp.salt,
529 buf + offset, len - offset))
537 * Turns a RTP packet into a SRTP packet: encrypt it, then computes
538 * the authentication tag and appends it.
539 * Note that you can encrypt packet in disorder.
541 * @param buf RTP packet to be encrypted/digested
542 * @param lenp pointer to the RTP packet length on entry,
543 * set to the SRTP length on exit (undefined on non-ENOSPC error)
544 * @param bufsize size (bytes) of the packet buffer
546 * @return 0 on success, in case of error:
547 * EINVAL malformatted RTP packet or internal error
548 * ENOSPC bufsize is too small to add authentication tag
549 * (<lenp> will hold the required byte size)
550 * EACCES packet would trigger a replay error on receiver
553 srtp_send (srtp_session_t *s, uint8_t *buf, size_t *lenp, size_t bufsize)
556 int val = srtp_crypt (s, buf, len);
560 if (!(s->flags & SRTP_UNAUTHENTICATED))
562 size_t tag_len = s->tag_len;
563 *lenp = len + tag_len;
564 if (bufsize < (len + tag_len))
567 uint32_t roc = srtp_compute_roc (s, rtp_seq (buf));
568 const uint8_t *tag = rtp_digest (s, buf, len, roc);
572 if ((rtp_seq (buf) % s->rtp_rcc) == 0)
574 memcpy (buf + len, &(uint32_t){ htonl (s->rtp_roc) }, 4);
576 if (rcc_mode (s) == 3)
583 if (rcc_mode (s) & 1)
587 memcpy (buf + len, tag, tag_len);
595 * Turns a SRTP packet into a RTP packet: authenticates the packet,
598 * @param buf RTP packet to be digested/decrypted
599 * @param lenp pointer to the SRTP packet length on entry,
600 * set to the RTP length on exit (undefined in case of error)
602 * @return 0 on success, in case of error:
603 * EINVAL malformatted SRTP packet
604 * EACCES authentication failed (spoofed packet or out-of-sync)
607 srtp_recv (srtp_session_t *s, uint8_t *buf, size_t *lenp)
613 if (!(s->flags & SRTP_UNAUTHENTICATED))
615 size_t tag_len = s->tag_len, roc_len = 0;
618 if ((rtp_seq (buf) % s->rtp_rcc) == 0)
621 if (rcc_mode (s) == 3)
628 if (rcc_mode (s) & 1)
629 tag_len = 0; // RCC mode 1 or 3: no auth
633 if (len < (12u + roc_len + tag_len))
635 len -= roc_len + tag_len;
637 uint32_t roc = srtp_compute_roc (s, rtp_seq (buf)), rcc;
640 assert (roc_len == 4);
641 memcpy (&rcc, buf + len, 4);
647 const uint8_t *tag = rtp_digest (s, buf, len, rcc);
649 printf ("Computed: 0x");
650 for (unsigned i = 0; i < tag_len; i++)
651 printf ("%02x", tag[i]);
652 printf ("\nReceived: 0x");
653 for (unsigned i = 0; i < tag_len; i++)
654 printf ("%02x", buf[len + roc_len + i]);
657 if (memcmp (buf + len + roc_len, tag, tag_len))
662 /* Authenticated packet carried a Roll-Over-Counter */
663 s->rtp_roc += rcc - roc;
664 assert (srtp_compute_roc (s, rtp_seq (buf)) == rcc);
669 return srtp_crypt (s, buf, len);
673 /** AES-CM for RTCP (salt = 14 bytes + 2 nul bytes) */
675 rtcp_crypt (gcry_cipher_hd_t hd, uint32_t ssrc, uint32_t index,
676 const uint32_t *salt, uint8_t *data, size_t len)
678 return rtp_crypt (hd, ssrc, index >> 16, index & 0xffff, salt, data, len);
682 /** Message Authentication and Integrity for RTCP */
683 static const uint8_t *
684 rtcp_digest (gcry_md_hd_t md, const void *data, size_t len)
687 gcry_md_write (md, data, len);
688 return gcry_md_read (md, 0);
693 * Encrypts/decrypts a RTCP packet and updates SRTCP context
694 * (CTR block cypher mode of operation has identical encryption and
695 * decryption function).
697 * @param buf RTCP packet to be en-/decrypted
698 * @param len RTCP packet length
700 * @return 0 on success, in case of error:
701 * EINVAL malformatted RTCP packet
703 static int srtcp_crypt (srtp_session_t *s, uint8_t *buf, size_t len)
707 /* 8-bytes unencrypted header, and 4-bytes unencrypted footer */
708 if ((len < 12) || ((buf[0] >> 6) != 2))
712 memcpy (&index, buf + len, 4);
713 index = ntohl (index);
714 if (((index >> 31) != 0) != ((s->flags & SRTCP_UNENCRYPTED) == 0))
715 return EINVAL; // E-bit mismatch
717 index &= ~(1 << 31); // clear E-bit for counter
719 /* Updates SRTCP index (safe here) */
720 int32_t diff = index - s->rtcp_index;
723 /* Packet in the future, good */
724 s->rtcp.window = s->rtcp.window << diff;
726 s->rtcp_index = index;
730 /* Packet in the past/present, bad */
732 if ((diff >= 64) || ((s->rtcp.window >> diff) & 1))
733 return EACCES; // replay attack!
734 s->rtp.window |= 1 << diff;
738 if (s->flags & SRTCP_UNENCRYPTED)
742 memcpy (&ssrc, buf + 4, 4);
744 if (rtcp_crypt (s->rtcp.cipher, ssrc, index, s->rtp.salt,
752 * Turns a RTCP packet into a SRTCP packet: encrypt it, then computes
753 * the authentication tag and appends it.
755 * @param buf RTCP packet to be encrypted/digested
756 * @param lenp pointer to the RTCP packet length on entry,
757 * set to the SRTCP length on exit (undefined in case of error)
758 * @param bufsize size (bytes) of the packet buffer
760 * @return 0 on success, in case of error:
761 * EINVAL malformatted RTCP packet or internal error
762 * ENOSPC bufsize is too small (to add index and authentication tag)
765 srtcp_send (srtp_session_t *s, uint8_t *buf, size_t *lenp, size_t bufsize)
768 if (bufsize < (len + 4 + s->tag_len))
771 uint32_t index = ++s->rtcp_index;
773 s->rtcp_index = index = 0; /* 31-bit wrap */
775 if ((s->flags & SRTCP_UNENCRYPTED) == 0)
776 index |= 0x80000000; /* Set Encrypted bit */
777 memcpy (buf + len, &(uint32_t){ htonl (index) }, 4);
779 int val = srtcp_crypt (s, buf, len);
783 len += 4; /* Digests SRTCP index too */
785 const uint8_t *tag = rtcp_digest (s->rtp.mac, buf, len);
786 memcpy (buf + len, tag, s->tag_len);
787 *lenp = len + s->tag_len;
793 * Turns a SRTCP packet into a RTCP packet: authenticates the packet,
796 * @param buf RTCP packet to be digested/decrypted
797 * @param lenp pointer to the SRTCP packet length on entry,
798 * set to the RTCP length on exit (undefined in case of error)
800 * @return 0 on success, in case of error:
801 * EINVAL malformatted SRTCP packet
802 * EACCES authentication failed (spoofed packet or out-of-sync)
805 srtcp_recv (srtp_session_t *s, uint8_t *buf, size_t *lenp)
809 if (len < (4u + s->tag_len))
813 const uint8_t *tag = rtcp_digest (s->rtp.mac, buf, len);
814 if (memcmp (buf + len, tag, s->tag_len))
817 len -= 4; /* Remove SRTCP index before decryption */
819 return srtp_crypt (s, buf, len);