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 profil thingy (multicast really needs this)
43 * Requirements for conformance:
44 * - suites with NULL cipher
47 * Useless stuff (because nothing depends on it):
48 * - non-nul key derivation rate
52 typedef struct srtp_proto_t
54 gcry_cipher_hd_t cipher;
82 # include <winsock2.h>
84 # include <netinet/in.h>
86 GCRY_THREAD_OPTION_PTHREAD_IMPL;
89 static bool libgcrypt_usable = false;
91 static void initonce_libgcrypt (void)
93 if ((gcry_check_version ("1.1.94") == NULL)
94 || gcry_control (GCRYCTL_DISABLE_SECMEM, 0)
95 || gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0)
97 || gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread)
102 libgcrypt_usable = true;
105 static int init_libgcrypt (void)
109 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
110 static pthread_once_t once = PTHREAD_ONCE_INIT;
112 pthread_mutex_lock (&mutex);
113 pthread_once (&once, initonce_libgcrypt);
114 retval = -libgcrypt_usable;
115 pthread_mutex_unlock (&mutex);
117 # warning FIXME: This is not thread-safe.
118 if (!libgcrypt_usable)
119 initonce_libgcrypt ();
120 retval = -libgcrypt_usable;
128 static void proto_destroy (srtp_proto_t *p)
130 gcry_md_close (p->mac);
131 gcry_cipher_close (p->cipher);
136 * Releases all resources associated with a Secure RTP session.
138 void srtp_destroy (srtp_session_t *s)
142 proto_destroy (&s->rtcp);
143 proto_destroy (&s->rtp);
148 static int proto_create (srtp_proto_t *p, int gcipher, int gmd)
150 if (gcry_cipher_open (&p->cipher, gcipher, GCRY_CIPHER_MODE_CTR, 0) == 0)
152 if (gcry_md_open (&p->mac, gmd, GCRY_MD_FLAG_HMAC) == 0)
154 gcry_cipher_close (p->cipher);
161 * Allocates a Secure RTP session.
163 * @param name cipher-suite name
164 * @param kdr key derivation rate
165 * @param winsize anti-replay windows size (between 64 and 32767 inclusive)
166 * 0 disable replay attack protection (OK for send only)
167 * @param flags OR'ed optional flags.
169 * @return NULL in case of error
172 srtp_create (const char *name, unsigned flags, unsigned kdr, uint16_t winsize)
174 assert (name != NULL);
177 return NULL; // FIXME: KDR not implemented yet
179 return NULL; // FIXME: replay protection not implemented yet
182 int cipher = GCRY_CIPHER_AES, md = GCRY_MD_SHA1;
184 if (strcmp (name, "AES_CM_128_HMAC_SHA1_80") == 0)
187 if (strcmp (name, "AES_CM_128_HMAC_SHA1_32") == 0)
190 // F8_128_HMAC_SHA1_80 is not implemented
193 if ((flags & ~SRTP_FLAGS_MASK) || (winsize > 32767) || init_libgcrypt ())
196 srtp_session_t *s = malloc (sizeof (*s));
200 memset (s, 0, sizeof (*s));
203 s->tag_len = tag_len;
205 if (proto_create (&s->rtp, cipher, md) == 0)
207 if (proto_create (&s->rtcp, cipher, md) == 0)
209 proto_destroy (&s->rtp);
218 * AES-CM key derivation (saltlen = 14 bytes)
221 derive (gcry_cipher_hd_t prf, const void *salt,
222 const uint8_t *r, size_t rlen, uint8_t label,
223 void *out, size_t outlen)
227 memcpy (iv, salt, 14);
231 iv[13 - rlen] ^= label;
232 for (size_t i = 0; i < rlen; i++)
233 iv[sizeof (iv) - rlen + i] ^= r[i];
235 /* TODO: retry with CTR mode */
236 while (outlen >= sizeof (iv))
239 if (gcry_cipher_encrypt (prf, out, sizeof (iv), iv, sizeof (iv)))
241 outlen -= sizeof (iv);
242 out = ((uint8_t *)out) + sizeof (iv);
244 /* Increment IV in network byte order */
245 if (++iv[sizeof (iv) - 1] == 0)
246 ++iv[sizeof (iv) -2];
251 /* Truncated last AES output block */
252 if (gcry_cipher_encrypt (prf, iv, sizeof (iv), NULL, 0))
254 memcpy (out, iv, outlen);
263 proto_derive (srtp_proto_t *p, gcry_cipher_hd_t prf,
264 const void *salt, size_t saltlen,
265 const uint8_t *r, size_t rlen, bool rtcp)
270 uint32_t cipherkey[4], authkey[5];
271 uint8_t label = rtcp ? SRTCP_CRYPT : SRTP_CRYPT;
273 if (derive (prf, salt, r, rlen, label++, cipherkey, 16)
274 || gcry_cipher_setkey (p->cipher, cipherkey, 16)
275 || derive (prf, salt, r, rlen, label++, authkey, 20)
276 || gcry_md_setkey (p->mac, authkey, 20)
277 || derive (prf, salt, r, rlen, label++, p->salt, 14))
280 debug (" cipher key: %08x%08x%08x%08x\n auth key: %08x%08x%08x%08x%08x\n",
281 ntohl (cipherkey[0]), ntohl (cipherkey[1]), ntohl (cipherkey[2]),
282 ntohl (cipherkey[3]), ntohl (authkey[0]), ntohl (authkey[1]),
283 ntohl (authkey[2]), ntohl (authkey[3]), ntohl (authkey[4]));
290 * SRTP/SRTCP cipher/salt/MAC keys derivation.
293 srtp_derive (srtp_session_t *s, const void *key, size_t keylen,
294 const void *salt, size_t saltlen)
296 gcry_cipher_hd_t prf;
299 /* TODO: retry with CTR mode */
300 if (gcry_cipher_open (&prf, GCRY_CIPHER_AES, GCRY_CIPHER_MODE_ECB, 0)
301 || gcry_cipher_setkey (prf, key, keylen))
304 /* RTP key derivation */
307 uint64_t index = (((uint64_t)s->rtp_roc) << 16) | s->rtp_seq;
310 for (int i = sizeof (r) - 1; i >= 0; i--)
317 memset (r, 0, sizeof (r));
319 if (proto_derive (&s->rtp, prf, salt, saltlen, r, 6, false))
322 /* RTCP key derivation */
323 memcpy (r, &(uint32_t){ htonl (s->rtcp_index) }, 4);
324 if (proto_derive (&s->rtcp, prf, salt, saltlen, r, 4, true))
327 (void)gcry_cipher_close (prf);
334 * Sets (or resets) the master key and master salt for a SRTP session.
335 * This must be done at least once before using rtp_send(), rtp_recv(),
336 * rtcp_send() or rtcp_recv(). Also, rekeying is required every
337 * 2^48 RTP packets or 2^31 RTCP packets (whichever comes first),
338 * otherwise the protocol security might be broken.
340 * @return 0 on success, in case of error:
341 * EINVAL invalid or unsupported key/salt sizes combination
344 srtp_setkey (srtp_session_t *s, const void *key, size_t keylen,
345 const void *salt, size_t saltlen)
347 return srtp_derive (s, key, keylen, salt, saltlen) ? EINVAL : 0;
351 /** AES-CM encryption/decryption (ctr length = 16 bytes) */
353 encrypt (gcry_cipher_hd_t hd, uint32_t *ctr, uint8_t *data, size_t len)
355 const size_t ctrlen = 16;
356 while (len >= ctrlen)
358 if (gcry_cipher_setctr (hd, ctr, ctrlen)
359 || gcry_cipher_encrypt (hd, data, ctrlen, NULL, 0))
364 ctr[3] = htonl (ntohl (ctr[3]) + 1);
369 /* Truncated last block */
370 uint8_t dummy[ctrlen];
371 memcpy (dummy, data, len);
372 memset (dummy + len, 0, ctrlen - len);
374 if (gcry_cipher_setctr (hd, ctr, ctrlen)
375 || gcry_cipher_encrypt (hd, dummy, ctrlen, data, ctrlen))
377 memcpy (data, dummy, len);
384 /** AES-CM for RTP (salt = 14 bytes + 2 nul bytes) */
386 rtp_encrypt (gcry_cipher_hd_t hd, uint32_t ssrc, uint32_t roc, uint16_t seq,
387 const uint32_t *salt, uint8_t *data, size_t len)
389 /* Determines cryptographic counter (IV) */
391 counter[0] = salt[0];
392 counter[1] = salt[1] ^ ssrc;
393 counter[2] = salt[2] ^ htonl (roc);
394 counter[3] = salt[3] ^ htonl (seq << 16);
397 return encrypt (hd, counter, data, len);
401 /** Message Authentication and Integrity for RTP */
402 static const uint8_t *
403 rtp_digest (gcry_md_hd_t md, const void *data, size_t len, uint32_t roc)
406 gcry_md_write (md, data, len);
407 gcry_md_write (md, &(uint32_t){ htonl (roc) }, 4);
408 return gcry_md_read (md, 0);
413 * Encrypts/decrypts a RTP packet and updates SRTP context
414 * (CTR block cypher mode of operation has identical encryption and
415 * decryption function).
417 * @param buf RTP packet to be encrypted/digested
418 * @param len RTP packet length
420 * @return 0 on success, in case of error:
421 * EINVAL malformatted RTP packet
423 static int srtp_crypt (srtp_session_t *s, uint8_t *buf, size_t len)
427 if ((len < 12) || ((buf[0] >> 6) != 2))
430 /* Computes encryption offset */
431 uint16_t offset = 12;
432 offset += (buf[0] & 0xf) * 4; // skips CSRC
442 memcpy (&extlen, buf + offset - 2, 2);
443 offset += htons (extlen); // skips RTP extension header
449 /* Determines RTP 48-bits counter and SSRC */
451 memcpy (&ssrc, buf + 8, 4);
453 uint16_t seq = (buf[2] << 8) | buf[3];
454 if (((seq - s->rtp_seq) & 0xffff) < 32768)
456 if (seq < s->rtp_seq)
457 s->rtp_roc++; /* Sequence number wrap */
461 if (seq > s->rtp_seq)
467 if (s->flags & SRTP_UNENCRYPTED)
470 if (rtp_encrypt (s->rtp.cipher, ssrc, s->rtp_roc, seq, s->rtp.salt,
471 buf + offset, len - offset))
479 * Turns a RTP packet into a SRTP packet: encrypt it, then computes
480 * the authentication tag and appends it.
481 * Note that you can encrypt packet in disorder.
483 * @param buf RTP packet to be encrypted/digested
484 * @param lenp pointer to the RTP packet length on entry,
485 * set to the SRTP length on exit (undefined in case of error)
486 * @param bufsize size (bytes) of the packet buffer
488 * @return 0 on success, in case of error:
489 * EINVAL malformatted RTP packet or internal error
490 * ENOSPC bufsize is too small (to add authentication tag)
493 srtp_send (srtp_session_t *s, uint8_t *buf, size_t *lenp, size_t bufsize)
496 int val = srtp_crypt (s, buf, len);
500 if (s->flags & SRTP_UNAUTHENTICATED)
503 if (bufsize < (len + s->tag_len))
506 const uint8_t *tag = rtp_digest (s->rtp.mac, buf, len, s->rtp_roc);
507 memcpy (buf + len, tag, s->tag_len);
508 *lenp = len + s->tag_len;
515 * Turns a SRTP packet into a RTP packet: authenticates the packet,
518 * @param buf RTP packet to be digested/decrypted
519 * @param lenp pointer to the RTP packet length on entry,
520 * set to the SRTP length on exit (undefined in case of error)
522 * @return 0 on success, in case of error:
523 * EINVAL malformatted SRTP packet
524 * EACCES authentication failed (spoofed packet or out-of-sync)
527 srtp_recv (srtp_session_t *s, uint8_t *buf, size_t *lenp)
531 if (!(s->flags & SRTP_UNAUTHENTICATED))
533 if (len < s->tag_len)
538 const uint8_t *tag = rtp_digest (s->rtp.mac, buf, len, s->rtp_roc);
539 debug (" Auth tag: %08x%08x%04x (wanted)\n"
540 " Auth tag: %08x%08x%04x (recv'd)\n",
541 ntohl (((uint32_t *)tag)[0]), ntohl (((uint32_t *)tag)[1]),
542 ntohs (((uint16_t *)tag)[4]),
543 ntohl (((uint32_t *)w)[0]), ntohl (((uint32_t *)w)[1]),
544 ntohs (((uint16_t *)w)[4]));
545 if (memcmp (buf + len, tag, s->tag_len))
549 /* FIXME: anti-replay */
551 return srtp_crypt (s, buf, len);