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
38 * - ROC profil thingy (multicast really needs this)
41 * Requirements for conformance:
42 * - suites with NULL cipher
45 * Useless stuff (because nothing depends on it):
46 * - non-nul key derivation rate
50 typedef struct srtp_proto_t
52 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 session.
161 * @param name cipher-suite name
162 * @param kdr key derivation rate
163 * @param winsize anti-replay windows size (between 64 and 32767 inclusive)
164 * 0 disable replay attack protection (OK for send only)
165 * @param flags OR'ed optional flags.
167 * @return NULL in case of error
170 srtp_create (const char *name, unsigned flags, unsigned kdr, uint16_t winsize)
172 assert (name != NULL);
175 return NULL; // FIXME: KDR not implemented yet
177 return NULL; // FIXME: replay protection not implemented yet
180 int cipher = GCRY_CIPHER_AES, md = GCRY_MD_SHA1;
182 if (strcmp (name, "AES_CM_128_HMAC_SHA1_80") == 0)
185 if (strcmp (name, "AES_CM_128_HMAC_SHA1_32") == 0)
188 // F8_128_HMAC_SHA1_80 is not implemented
191 if ((flags & ~SRTP_FLAGS_MASK) || (winsize > 32767) || init_libgcrypt ())
194 srtp_session_t *s = malloc (sizeof (*s));
198 memset (s, 0, sizeof (*s));
202 if (proto_create (&s->rtp, cipher, md) == 0)
204 if (proto_create (&s->rtcp, cipher, md) == 0)
206 proto_destroy (&s->rtp);
215 * AES-CM key derivation (saltlen = 14 bytes)
218 derive (gcry_cipher_hd_t prf, const void *salt,
219 const uint8_t *r, size_t rlen, uint8_t label,
220 void *out, size_t outlen)
224 memcpy (iv, salt, 14);
228 iv[13 - rlen] ^= label;
229 for (size_t i = 0; i < rlen; i++)
230 iv[sizeof (iv) - rlen + i] ^= r[i];
232 /* TODO: retry with CTR mode */
233 while (outlen >= sizeof (iv))
236 if (gcry_cipher_encrypt (prf, out, sizeof (iv), iv, sizeof (iv)))
238 outlen -= sizeof (iv);
239 out = ((uint8_t *)out) + sizeof (iv);
241 /* Increment IV in network byte order */
242 if (++iv[sizeof (iv) - 1] == 0)
243 ++iv[sizeof (iv) -2];
248 /* Truncated last AES output block */
249 if (gcry_cipher_encrypt (prf, iv, sizeof (iv), NULL, 0))
251 memcpy (out, iv, outlen);
259 proto_derive (srtp_proto_t *p, gcry_cipher_hd_t prf,
260 const void *salt, size_t saltlen,
261 const uint8_t *r, size_t rlen, bool rtcp)
266 uint8_t cipherkey[16];
267 uint8_t label = rtcp ? SRTCP_CRYPT : SRTP_CRYPT;
269 if (derive (prf, salt, r, rlen, label++, cipherkey, 16)
270 || gcry_cipher_setkey (p->cipher, cipherkey, 16)
271 || derive (prf, salt, r, rlen, label++, NULL, 0) /* FIXME HMAC */
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);
324 * Sets (or resets) the master key and master salt for a SRTP session.
325 * This must be done at least once before using rtp_send(), rtp_recv(),
326 * rtcp_send() or rtcp_recv(). Also, rekeying is required every
327 * 2^48 RTP packets or 2^31 RTCP packets (whichever comes first),
328 * otherwise the protocol security might be broken.
330 * @return 0 on success, in case of error:
331 * EINVAL invalid or unsupported key/salt sizes combination
334 srtp_setkey (srtp_session_t *s, const void *key, size_t keylen,
335 const void *salt, size_t saltlen)
337 return srtp_derive (s, key, keylen, salt, saltlen) ? EINVAL : 0;
341 /** AES-CM encryption/decryption (ctr length = 16 bytes) */
343 encrypt (gcry_cipher_hd_t hd, uint32_t *ctr, uint8_t *data, size_t len)
345 const size_t ctrlen = 16;
346 while (len >= ctrlen)
348 if (gcry_cipher_setctr (hd, ctr, ctrlen)
349 || gcry_cipher_encrypt (hd, data, ctrlen, NULL, 0))
354 ctr[3] = htonl (ntohl (ctr[3]) + 1);
359 /* Truncated last block */
360 uint8_t dummy[ctrlen];
361 memcpy (dummy, data, len);
362 memset (dummy + len, 0, ctrlen - len);
364 if (gcry_cipher_setctr (hd, ctr, ctrlen)
365 || gcry_cipher_encrypt (hd, dummy, ctrlen, data, ctrlen))
367 memcpy (data, dummy, len);
374 /** AES-CM for RTP (salt = 14 bytes + 2 nul bytes) */
376 rtp_encrypt (gcry_cipher_hd_t hd, uint32_t ssrc, uint32_t roc, uint16_t seq,
377 const uint32_t *salt, uint8_t *data, size_t len)
379 /* Determines cryptographic counter (IV) */
381 counter[0] = salt[0];
382 counter[1] = salt[1] ^ ssrc;
383 counter[2] = salt[2] ^ htonl (roc);
384 counter[3] = salt[3] ^ htonl (seq << 16);
387 return encrypt (hd, counter, data, len);
392 * Encrypts/decrypts a RTP packet and updates SRTP context
393 * (CTR block cypher mode of operation has identical encryption and
394 * decryption function).
396 * @param buf RTP packet to be encrypted/digested
397 * @param len RTP packet length
399 * @return 0 on success, in case of error:
400 * EINVAL malformatted RTP packet
402 static int srtp_encrypt (srtp_session_t *s, uint8_t *buf, size_t len)
406 if ((len < 12) || ((buf[0] >> 6) != 2))
409 /* Computes encryption offset */
410 uint16_t offset = 12;
411 offset += (buf[0] & 0xf) * 4; // skips CSRC
421 memcpy (&extlen, buf + offset - 2, 2);
422 offset += htons (extlen);
428 /* Determines RTP 48-bits counter and SSRC */
430 memcpy (&ssrc, buf + 8, 4);
432 uint16_t seq = (buf[2] << 8) | buf[3];
433 if (((seq - s->rtp_seq) & 0xffff) < 32768)
435 if (seq < s->rtp_seq)
436 s->rtp_roc++; /* Sequence number wrap */
440 if (seq > s->rtp_seq)
446 if (s->flags & SRTP_UNENCRYPTED)
449 if (rtp_encrypt (s->rtp.cipher, ssrc, s->rtp_roc, seq, s->rtp.salt,
450 buf + offset, len - offset))
458 * Turns a RTP packet into a SRTP packet: encrypt it, then computes
459 * the authentication tag and appends it.
460 * Note that you can encrypt packet in disorder.
462 * @param buf RTP packet to be encrypted/digested
463 * @param lenp pointer to the RTP packet length on entry,
464 * set to the SRTP length on exit (undefined in case of error)
465 * @param bufsize size (bytes) of the packet buffer
467 * @return 0 on success, in case of error:
468 * EINVAL malformatted RTP packet
469 * ENOSPC bufsize is too small (to add authentication tag)
472 srtp_send (srtp_session_t *s, uint8_t *buf, size_t *lenp, size_t bufsize)
475 int val = srtp_encrypt (s, buf, len);
479 if (bufsize < (len + s->rtp.mac_len))
482 /* FIXME: HMAC and anti-replay */
488 * Turns a RTP packet into a SRTP packet: encrypt it, then computes
489 * the authentication tag and appends it.
490 * Note that you can encrypt packet in disorder.
492 * @param buf RTP packet to be decrypted/digested
493 * @param lenp pointer to the RTP packet length on entry,
494 * set to the SRTP length on exit (undefined in case of error)
496 * @return 0 on success, in case of error:
497 * EINVAL malformatted RTP packet
498 * EACCES authentication failed (spoofed packet or out-of-sync)
501 srtp_recv (srtp_session_t *s, uint8_t *buf, size_t *lenp)
504 int val = srtp_encrypt (s, buf, len);
508 /* FIXME: HMAC and anti-replay */