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)
43 * Useless stuff (because nothing depends on it):
44 * - non-nul key derivation rate
48 typedef struct srtp_proto_t
50 gcry_cipher_hd_t cipher;
79 # include <winsock2.h>
81 # include <netinet/in.h>
83 GCRY_THREAD_OPTION_PTHREAD_IMPL;
86 static bool libgcrypt_usable = false;
88 static void initonce_libgcrypt (void)
90 if ((gcry_check_version ("1.1.94") == NULL)
91 || gcry_control (GCRYCTL_DISABLE_SECMEM, 0)
92 || gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0)
94 || gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread)
99 libgcrypt_usable = true;
102 static int init_libgcrypt (void)
106 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
107 static pthread_once_t once = PTHREAD_ONCE_INIT;
109 pthread_mutex_lock (&mutex);
110 pthread_once (&once, initonce_libgcrypt);
111 retval = -libgcrypt_usable;
112 pthread_mutex_unlock (&mutex);
114 # warning FIXME: This is not thread-safe.
115 if (!libgcrypt_usable)
116 initonce_libgcrypt ();
117 retval = -libgcrypt_usable;
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 name cipher-suite name
164 * @param kdr key derivation rate
165 * @param flags OR'ed optional flags.
167 * @return NULL in case of error
170 srtp_create (const char *name, unsigned flags, unsigned kdr)
172 assert (name != NULL);
175 return NULL; // FIXME: KDR not implemented yet
178 int cipher = GCRY_CIPHER_AES, md = GCRY_MD_SHA1;
180 if (strcmp (name, "AES_CM_128_HMAC_SHA1_80") == 0)
183 if (strcmp (name, "AES_CM_128_HMAC_SHA1_32") == 0)
186 // F8_128_HMAC_SHA1_80 is not implemented
189 if ((flags & ~SRTP_FLAGS_MASK) || init_libgcrypt ())
192 srtp_session_t *s = malloc (sizeof (*s));
196 memset (s, 0, sizeof (*s));
199 s->tag_len = tag_len;
201 if (proto_create (&s->rtp, cipher, md) == 0)
203 if (proto_create (&s->rtcp, cipher, md) == 0)
205 proto_destroy (&s->rtp);
214 * AES-CM key derivation (saltlen = 14 bytes)
217 derive (gcry_cipher_hd_t prf, const void *salt,
218 const uint8_t *r, size_t rlen, uint8_t label,
219 void *out, size_t outlen)
223 memcpy (iv, salt, 14);
227 iv[13 - rlen] ^= label;
228 for (size_t i = 0; i < rlen; i++)
229 iv[sizeof (iv) - rlen + i] ^= r[i];
231 /* TODO: retry with CTR mode */
232 while (outlen >= sizeof (iv))
235 if (gcry_cipher_encrypt (prf, out, sizeof (iv), iv, sizeof (iv)))
237 outlen -= sizeof (iv);
238 out = ((uint8_t *)out) + sizeof (iv);
240 /* Increment IV in network byte order */
241 if (++iv[sizeof (iv) - 1] == 0)
242 ++iv[sizeof (iv) -2];
247 /* Truncated last AES output block */
248 if (gcry_cipher_encrypt (prf, iv, sizeof (iv), NULL, 0))
250 memcpy (out, iv, outlen);
258 proto_derive (srtp_proto_t *p, gcry_cipher_hd_t prf,
259 const void *salt, size_t saltlen,
260 const uint8_t *r, size_t rlen, bool rtcp)
266 uint8_t label = rtcp ? SRTCP_CRYPT : SRTP_CRYPT;
268 if (derive (prf, salt, r, rlen, label++, keybuf, 16)
269 || gcry_cipher_setkey (p->cipher, keybuf, 16)
270 || derive (prf, salt, r, rlen, label++, keybuf, 20)
271 || gcry_md_setkey (p->mac, keybuf, 20)
272 || derive (prf, salt, r, rlen, label, p->salt, 14))
280 * SRTP/SRTCP cipher/salt/MAC keys derivation.
283 srtp_derive (srtp_session_t *s, const void *key, size_t keylen,
284 const void *salt, size_t saltlen)
286 gcry_cipher_hd_t prf;
289 /* TODO: retry with CTR mode */
290 if (gcry_cipher_open (&prf, GCRY_CIPHER_AES, GCRY_CIPHER_MODE_ECB, 0)
291 || gcry_cipher_setkey (prf, key, keylen))
294 /* RTP key derivation */
297 uint64_t index = (((uint64_t)s->rtp_roc) << 16) | s->rtp_seq;
300 for (int i = sizeof (r) - 1; i >= 0; i--)
307 memset (r, 0, sizeof (r));
309 if (proto_derive (&s->rtp, prf, salt, saltlen, r, 6, false))
312 /* RTCP key derivation */
313 memcpy (r, &(uint32_t){ htonl (s->rtcp_index) }, 4);
314 if (proto_derive (&s->rtcp, prf, salt, saltlen, r, 4, true))
317 (void)gcry_cipher_close (prf);
323 * Sets (or resets) the master key and master salt for a SRTP session.
324 * This must be done at least once before using rtp_send(), rtp_recv(),
325 * rtcp_send() or rtcp_recv(). Also, rekeying is required every
326 * 2^48 RTP packets or 2^31 RTCP packets (whichever comes first),
327 * otherwise the protocol security might be broken.
329 * @return 0 on success, in case of error:
330 * EINVAL invalid or unsupported key/salt sizes combination
333 srtp_setkey (srtp_session_t *s, const void *key, size_t keylen,
334 const void *salt, size_t saltlen)
336 return srtp_derive (s, key, keylen, salt, saltlen) ? EINVAL : 0;
340 /** AES-CM encryption/decryption (ctr length = 16 bytes) */
342 ctr_crypt (gcry_cipher_hd_t hd, uint32_t *ctr, uint8_t *data, size_t len)
344 const size_t ctrlen = 16;
345 while (len >= ctrlen)
347 if (gcry_cipher_setctr (hd, ctr, ctrlen)
348 || gcry_cipher_encrypt (hd, data, ctrlen, NULL, 0))
353 ctr[3] = htonl (ntohl (ctr[3]) + 1);
358 /* Truncated last block */
359 uint8_t dummy[ctrlen];
360 memcpy (dummy, data, len);
361 memset (dummy + len, 0, ctrlen - len);
363 if (gcry_cipher_setctr (hd, ctr, ctrlen)
364 || gcry_cipher_encrypt (hd, dummy, ctrlen, data, ctrlen))
366 memcpy (data, dummy, len);
373 /** AES-CM for RTP (salt = 14 bytes + 2 nul bytes) */
375 rtp_crypt (gcry_cipher_hd_t hd, uint32_t ssrc, uint32_t roc, uint16_t seq,
376 const uint32_t *salt, uint8_t *data, size_t len)
378 /* Determines cryptographic counter (IV) */
380 counter[0] = salt[0];
381 counter[1] = salt[1] ^ ssrc;
382 counter[2] = salt[2] ^ htonl (roc);
383 counter[3] = salt[3] ^ htonl (seq << 16);
386 return ctr_crypt (hd, counter, data, len);
390 /** Message Authentication and Integrity for RTP */
391 static const uint8_t *
392 rtp_digest (gcry_md_hd_t md, const void *data, size_t len, uint32_t roc)
395 gcry_md_write (md, data, len);
396 gcry_md_write (md, &(uint32_t){ htonl (roc) }, 4);
397 return gcry_md_read (md, 0);
402 * Encrypts/decrypts a RTP packet and updates SRTP context
403 * (CTR block cypher mode of operation has identical encryption and
404 * decryption function).
406 * @param buf RTP packet to be en-/decrypted
407 * @param len RTP packet length
409 * @return 0 on success, in case of error:
410 * EINVAL malformatted RTP packet
412 static int srtp_crypt (srtp_session_t *s, uint8_t *buf, size_t len)
416 if ((len < 12) || ((buf[0] >> 6) != 2))
419 /* Computes encryption offset */
420 uint16_t offset = 12;
421 offset += (buf[0] & 0xf) * 4; // skips CSRC
431 memcpy (&extlen, buf + offset - 2, 2);
432 offset += htons (extlen); // skips RTP extension header
438 /* Determines RTP 48-bits counter and SSRC */
440 memcpy (&ssrc, buf + 8, 4);
442 uint16_t seq = (buf[2] << 8) | buf[3];
443 if (((seq - s->rtp_seq) & 0xffff) < 32768)
445 if (seq < s->rtp_seq)
446 s->rtp_roc++; /* Sequence number wrap */
450 if (seq > s->rtp_seq)
456 if (s->flags & SRTP_UNENCRYPTED)
459 if (rtp_crypt (s->rtp.cipher, ssrc, s->rtp_roc, seq, s->rtp.salt,
460 buf + offset, len - offset))
468 * Turns a RTP packet into a SRTP packet: encrypt it, then computes
469 * the authentication tag and appends it.
470 * Note that you can encrypt packet in disorder.
472 * @param buf RTP packet to be encrypted/digested
473 * @param lenp pointer to the RTP packet length on entry,
474 * set to the SRTP length on exit (undefined in case of error)
475 * @param bufsize size (bytes) of the packet buffer
477 * @return 0 on success, in case of error:
478 * EINVAL malformatted RTP packet or internal error
479 * ENOSPC bufsize is too small (to add authentication tag)
482 srtp_send (srtp_session_t *s, uint8_t *buf, size_t *lenp, size_t bufsize)
485 int val = srtp_crypt (s, buf, len);
489 if (s->flags & SRTP_UNAUTHENTICATED)
492 if (bufsize < (len + s->tag_len))
495 const uint8_t *tag = rtp_digest (s->rtp.mac, buf, len, s->rtp_roc);
496 memcpy (buf + len, tag, s->tag_len);
497 *lenp = len + s->tag_len;
504 * Turns a SRTP packet into a RTP packet: authenticates the packet,
507 * @param buf RTP packet to be digested/decrypted
508 * @param lenp pointer to the SRTP packet length on entry,
509 * set to the RTP length on exit (undefined in case of error)
511 * @return 0 on success, in case of error:
512 * EINVAL malformatted SRTP packet
513 * EACCES authentication failed (spoofed packet or out-of-sync)
516 srtp_recv (srtp_session_t *s, uint8_t *buf, size_t *lenp)
519 /* FIXME: anti-replay */
521 if (!(s->flags & SRTP_UNAUTHENTICATED))
523 if (len < s->tag_len)
527 const uint8_t *tag = rtp_digest (s->rtp.mac, buf, len, s->rtp_roc);
528 if (memcmp (buf + len, tag, s->tag_len))
534 return srtp_crypt (s, buf, len);
538 /** AES-CM for RTCP (salt = 14 bytes + 2 nul bytes) */
540 rtcp_crypt (gcry_cipher_hd_t hd, uint32_t ssrc, uint32_t index,
541 const uint32_t *salt, uint8_t *data, size_t len)
543 return rtp_crypt (hd, ssrc, index >> 16, index & 0xffff, salt, data, len);
547 /** Message Authentication and Integrity for RTCP */
548 static const uint8_t *
549 rtcp_digest (gcry_md_hd_t md, const void *data, size_t len)
552 gcry_md_write (md, data, len);
553 return gcry_md_read (md, 0);
558 * Encrypts/decrypts a RTCP packet and updates SRTCP context
559 * (CTR block cypher mode of operation has identical encryption and
560 * decryption function).
562 * @param buf RTCP packet to be en-/decrypted
563 * @param len RTCP packet length
565 * @return 0 on success, in case of error:
566 * EINVAL malformatted RTCP packet
568 static int srtcp_crypt (srtp_session_t *s, uint8_t *buf, size_t len)
572 /* 8-bytes unencrypted header, and 4-bytes unencrypted footer */
573 if ((len < 12) || ((buf[0] >> 6) != 2))
576 uint32_t index = s->rtcp_index++;
577 if (index == 0x7fffffff)
578 s->rtcp_index = 0; /* 31-bit wrap */
580 if (s->flags & SRTCP_UNENCRYPTED)
584 memcpy (&ssrc, buf + 4, 4);
586 if (rtcp_crypt (s->rtcp.cipher, ssrc, index, s->rtp.salt,
594 * Turns a RTCP packet into a SRTCP packet: encrypt it, then computes
595 * the authentication tag and appends it.
597 * @param buf RTCP packet to be encrypted/digested
598 * @param lenp pointer to the RTCP packet length on entry,
599 * set to the SRTCP length on exit (undefined in case of error)
600 * @param bufsize size (bytes) of the packet buffer
602 * @return 0 on success, in case of error:
603 * EINVAL malformatted RTCP packet or internal error
604 * ENOSPC bufsize is too small (to add index and authentication tag)
607 srtcp_send (srtp_session_t *s, uint8_t *buf, size_t *lenp, size_t bufsize)
610 if (bufsize < (len + 4 + s->tag_len))
613 uint32_t index = s->rtcp_index;
614 if ((s->flags & SRTCP_UNENCRYPTED) == 0)
615 index |= 0x80000000; /* Set Encrypted bit */
616 memcpy (buf + len, &(uint32_t){ htonl (index) }, 4);
618 int val = srtcp_crypt (s, buf, len);
622 len += 4; /* Digest SRTCP index too */
624 const uint8_t *tag = rtcp_digest (s->rtp.mac, buf, len);
625 memcpy (buf + len, tag, s->tag_len);
626 *lenp = len + s->tag_len;
632 * Turns a SRTCP packet into a RTCP packet: authenticates the packet,
635 * @param buf RTCP packet to be digested/decrypted
636 * @param lenp pointer to the SRTCP packet length on entry,
637 * set to the RTCP length on exit (undefined in case of error)
639 * @return 0 on success, in case of error:
640 * EINVAL malformatted SRTCP packet
641 * EACCES authentication failed (spoofed packet or out-of-sync)
644 srtcp_recv (srtp_session_t *s, uint8_t *buf, size_t *lenp)
647 /* FIXME: anti-replay ?? */
649 if (len < (4u + s->tag_len))
653 const uint8_t *tag = rtcp_digest (s->rtp.mac, buf, len);
654 if (memcmp (buf + len, tag, s->tag_len))
657 len -= 4; /* Remove SRTCP index before decryption */
660 return srtp_crypt (s, buf, len);