]> git.sesse.net Git - vlc/blob - libs/srtp/srtp.c
Maintain the SRTCP index
[vlc] / libs / srtp / srtp.c
1 /*
2  * Secure RTP with libgcrypt
3  * Copyright (C) 2007  RĂ©mi Denis-Courmont <rdenis # simphalempin , com>
4  *
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.
9  *
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.
14  *
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
18  */
19
20 #ifdef HAVE_CONFIG_H
21 # include <config.h>
22 #endif
23
24 #include <stdint.h>
25 #include <stddef.h>
26
27 #include "srtp.h"
28
29 #include <stdbool.h>
30 #include <stdlib.h>
31 #include <assert.h>
32 #include <errno.h>
33
34 #include <gcrypt.h>
35
36 #define debug( ... ) (void)0
37
38 /* TODO:
39  * Useful stuff:
40  * - ROC profile thingy (multicast really needs this)
41  * - replay protection
42  *
43  * Useless stuff (because nothing depends on it):
44  * - non-nul key derivation rate
45  * - MKI payload
46  */
47
48 typedef struct srtp_proto_t
49 {
50     gcry_cipher_hd_t cipher;
51     gcry_md_hd_t     mac;
52     uint64_t         window;
53     uint32_t         salt[4];
54 } srtp_proto_t;
55
56 struct srtp_session_t
57 {
58     srtp_proto_t rtp;
59     srtp_proto_t rtcp;
60     unsigned flags;
61     unsigned kdr;
62     uint32_t rtcp_index;
63     uint32_t rtp_roc;
64     uint16_t rtp_seq;
65     uint8_t  tag_len;
66 };
67
68 enum
69 {
70     SRTP_CRYPT,
71     SRTP_AUTH,
72     SRTP_SALT,
73     SRTCP_CRYPT,
74     SRTCP_AUTH,
75     SRTCP_SALT
76 };
77
78 #ifdef WIN32
79 # include <winsock2.h>
80 #else
81 # include <netinet/in.h>
82 # include <pthread.h>
83 GCRY_THREAD_OPTION_PTHREAD_IMPL;
84 #endif
85
86 static bool libgcrypt_usable = false;
87
88 static void initonce_libgcrypt (void)
89 {
90     if ((gcry_check_version ("1.1.94") == NULL)
91      || gcry_control (GCRYCTL_DISABLE_SECMEM, 0)
92      || gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0)
93 #ifndef WIN32
94      || gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread)
95 #endif
96        )
97         return;
98
99     libgcrypt_usable = true;
100 }
101
102 static int init_libgcrypt (void)
103 {
104     int retval;
105 #ifndef WIN32
106     static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
107     static pthread_once_t once = PTHREAD_ONCE_INIT;
108
109     pthread_mutex_lock (&mutex);
110     pthread_once (&once, initonce_libgcrypt);
111     retval = -libgcrypt_usable;
112     pthread_mutex_unlock (&mutex);
113 #else
114 # warning FIXME: This is not thread-safe.
115     if (!libgcrypt_usable)
116         initonce_libgcrypt ();
117     retval = -libgcrypt_usable;
118 #endif
119
120     return retval;
121
122 }
123
124
125 static void proto_destroy (srtp_proto_t *p)
126 {
127     gcry_md_close (p->mac);
128     gcry_cipher_close (p->cipher);
129 }
130
131
132 /**
133  * Releases all resources associated with a Secure RTP session.
134  */
135 void srtp_destroy (srtp_session_t *s)
136 {
137     assert (s != NULL);
138
139     proto_destroy (&s->rtcp);
140     proto_destroy (&s->rtp);
141     free (s);
142 }
143
144
145 static int proto_create (srtp_proto_t *p, int gcipher, int gmd)
146 {
147     if (gcry_cipher_open (&p->cipher, gcipher, GCRY_CIPHER_MODE_CTR, 0) == 0)
148     {
149         if (gcry_md_open (&p->mac, gmd, GCRY_MD_FLAG_HMAC) == 0)
150             return 0;
151         gcry_cipher_close (p->cipher);
152     }
153     return -1;
154 }
155
156
157 /**
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.
162  *
163  * @param name cipher-suite name
164  * @param kdr key derivation rate
165  * @param flags OR'ed optional flags.
166  *
167  * @return NULL in case of error
168  */
169 srtp_session_t *
170 srtp_create (const char *name, unsigned flags, unsigned kdr)
171 {
172     assert (name != NULL);
173
174     if (kdr != 0)
175         return NULL; // FIXME: KDR not implemented yet
176
177     uint8_t tag_len;
178     int cipher = GCRY_CIPHER_AES, md = GCRY_MD_SHA1;
179
180     if (strcmp (name, "AES_CM_128_HMAC_SHA1_80") == 0)
181         tag_len = 10;
182     else
183     if (strcmp (name, "AES_CM_128_HMAC_SHA1_32") == 0)
184         tag_len = 4;
185     else
186     // F8_128_HMAC_SHA1_80 is not implemented
187         return NULL;
188
189     if ((flags & ~SRTP_FLAGS_MASK) || init_libgcrypt ())
190         return NULL;
191
192     srtp_session_t *s = malloc (sizeof (*s));
193     if (s == NULL)
194         return NULL;
195
196     memset (s, 0, sizeof (*s));
197     s->flags = flags;
198     s->kdr = kdr;
199     s->tag_len = tag_len;
200
201     if (proto_create (&s->rtp, cipher, md) == 0)
202     {
203         if (proto_create (&s->rtcp, cipher, md) == 0)
204             return s;
205         proto_destroy (&s->rtp);
206     }
207
208     free (s);
209     return NULL;
210 }
211
212
213 /**
214  * AES-CM key derivation (saltlen = 14 bytes)
215  */
216 static int
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)
220 {
221     uint8_t iv[16];
222
223     memcpy (iv, salt, 14);
224     iv[14] = iv[15] = 0;
225
226     assert (rlen < 14);
227     iv[13 - rlen] ^= label;
228     for (size_t i = 0; i < rlen; i++)
229         iv[sizeof (iv) - rlen + i] ^= r[i];
230
231     /* TODO: retry with CTR mode */
232     while (outlen >= sizeof (iv))
233     {
234         /* AES */
235         if (gcry_cipher_encrypt (prf, out, sizeof (iv), iv, sizeof (iv)))
236             return EINVAL;
237         outlen -= sizeof (iv);
238         out = ((uint8_t *)out) + sizeof (iv);
239
240         /* Increment IV in network byte order */
241         if (++iv[sizeof (iv) - 1] == 0)
242             ++iv[sizeof (iv) -2];
243     }
244
245     if (outlen > 0)
246     {
247         /* Truncated last AES output block */
248         if (gcry_cipher_encrypt (prf, iv, sizeof (iv), NULL, 0))
249             return -1;
250         memcpy (out, iv, outlen);
251     }
252
253     return 0;
254 }
255
256
257 static int
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)
261 {
262     if (saltlen != 14)
263         return -1;
264
265     uint8_t keybuf[20];
266     uint8_t label = rtcp ? SRTCP_CRYPT : SRTP_CRYPT;
267
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))
273         return -1;
274
275     return 0;
276 }
277
278
279 /**
280  * SRTP/SRTCP cipher/salt/MAC keys derivation.
281  */
282 static int
283 srtp_derive (srtp_session_t *s, const void *key, size_t keylen,
284              const void *salt, size_t saltlen)
285 {
286     gcry_cipher_hd_t prf;
287     uint8_t r[6];
288
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))
292         return -1;
293
294     /* RTP key derivation */
295     if (s->kdr != 0)
296     {
297         uint64_t index = (((uint64_t)s->rtp_roc) << 16) | s->rtp_seq;
298         index /= s->kdr;
299
300         for (int i = sizeof (r) - 1; i >= 0; i--)
301         {
302             r[i] = index & 0xff;
303             index = index >> 8;
304         }
305     }
306     else
307         memset (r, 0, sizeof (r));
308
309     if (proto_derive (&s->rtp, prf, salt, saltlen, r, 6, false))
310         return -1;
311
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))
315         return -1;
316
317     (void)gcry_cipher_close (prf);
318     return 0;
319 }
320
321
322 /**
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.
328  *
329  * @return 0 on success, in case of error:
330  *  EINVAL  invalid or unsupported key/salt sizes combination
331  */
332 int
333 srtp_setkey (srtp_session_t *s, const void *key, size_t keylen,
334              const void *salt, size_t saltlen)
335 {
336     return srtp_derive (s, key, keylen, salt, saltlen) ? EINVAL : 0;
337 }
338
339
340 /** AES-CM encryption/decryption (ctr length = 16 bytes) */
341 static int
342 ctr_crypt (gcry_cipher_hd_t hd, uint32_t *ctr, uint8_t *data, size_t len)
343 {
344     const size_t ctrlen = 16;
345     while (len >= ctrlen)
346     {
347         if (gcry_cipher_setctr (hd, ctr, ctrlen)
348          || gcry_cipher_encrypt (hd, data, ctrlen, NULL, 0))
349             return -1;
350
351         data += ctrlen;
352         len -= ctrlen;
353         ctr[3] = htonl (ntohl (ctr[3]) + 1);
354     }
355
356     if (len > 0)
357     {
358         /* Truncated last block */
359         uint8_t dummy[ctrlen];
360         memcpy (dummy, data, len);
361         memset (dummy + len, 0, ctrlen - len);
362
363         if (gcry_cipher_setctr (hd, ctr, ctrlen)
364          || gcry_cipher_encrypt (hd, dummy, ctrlen, data, ctrlen))
365             return -1;
366         memcpy (data, dummy, len);
367     }
368
369     return 0;
370 }
371
372
373 /** AES-CM for RTP (salt = 14 bytes + 2 nul bytes) */
374 static int
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)
377 {
378     /* Determines cryptographic counter (IV) */
379     uint32_t counter[4];
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);
384
385     /* Encryption */
386     return ctr_crypt (hd, counter, data, len);
387 }
388
389
390 /** Determines SRTP Roll-Over-Counter (in host-byte order) */
391 static uint32_t
392 srtp_compute_roc (const srtp_session_t *s, uint16_t seq)
393 {
394     uint32_t roc = s->rtp_roc;
395
396     if (((seq - s->rtp_seq) & 0xffff) < 0x8000)
397     {
398         /* Sequence is ahead, good */
399         if (seq < s->rtp_seq)
400             roc++; /* Sequence number wrap */
401     }
402     else
403     {
404         /* Sequence is late, bad */
405         if (seq > s->rtp_seq)
406             roc--; /* Wrap back */
407     }
408     return roc;
409 }
410
411
412 /** Returns RTP sequence (in host-byte order) */
413 static inline uint16_t rtp_seq (const uint8_t *buf)
414 {
415     return (buf[2] << 8) | buf[3];
416 }
417
418
419 /** Message Authentication and Integrity for RTP */
420 static const uint8_t *
421 rtp_digest (srtp_session_t *s, const uint8_t *data, size_t len)
422 {
423     const gcry_md_hd_t md = s->rtp.mac;
424     uint32_t roc = htonl (srtp_compute_roc (s, rtp_seq (data)));
425
426     gcry_md_reset (md);
427     gcry_md_write (md, data, len);
428     gcry_md_write (md, &roc, 4);
429     return gcry_md_read (md, 0);
430 }
431
432
433 /**
434  * Encrypts/decrypts a RTP packet and updates SRTP context
435  * (CTR block cypher mode of operation has identical encryption and
436  * decryption function).
437  *
438  * @param buf RTP packet to be en-/decrypted
439  * @param len RTP packet length
440  *
441  * @return 0 on success, in case of error:
442  *  EINVAL  malformatted RTP packet
443  */
444 static int srtp_crypt (srtp_session_t *s, uint8_t *buf, size_t len)
445 {
446     assert (s != NULL);
447
448     if ((len < 12) || ((buf[0] >> 6) != 2))
449         return EINVAL;
450
451     /* Computes encryption offset */
452     uint16_t offset = 12;
453     offset += (buf[0] & 0xf) * 4; // skips CSRC
454
455     if (buf[0] & 0x10)
456     {
457         uint16_t extlen;
458
459         offset += 4;
460         if (len < offset)
461             return EINVAL;
462
463         memcpy (&extlen, buf + offset - 2, 2);
464         offset += htons (extlen); // skips RTP extension header
465     }
466
467     if (len < offset)
468         return EINVAL;
469
470     /* Determines RTP 48-bits counter and SSRC */
471     uint16_t seq = rtp_seq (buf);
472     uint32_t roc = srtp_compute_roc (s, seq), ssrc;
473     memcpy (&ssrc, buf + 8, 4);
474
475     /* Updates ROC and sequence (it's safe now) */
476     if (roc > s->rtp_roc)
477         s->rtp_seq = seq, s->rtp_roc = roc;
478     else
479     if (seq > s->rtp_seq)
480         s->rtp_seq = seq;
481
482     /* Encrypt/Decrypt */
483     if (s->flags & SRTP_UNENCRYPTED)
484         return 0;
485
486     if (rtp_crypt (s->rtp.cipher, ssrc, roc, seq, s->rtp.salt,
487                    buf + offset, len - offset))
488         return EINVAL;
489
490     return 0;
491 }
492
493
494 /**
495  * Turns a RTP packet into a SRTP packet: encrypt it, then computes
496  * the authentication tag and appends it.
497  * Note that you can encrypt packet in disorder.
498  *
499  * @param buf RTP packet to be encrypted/digested
500  * @param lenp pointer to the RTP packet length on entry,
501  *             set to the SRTP length on exit (undefined in case of error)
502  * @param bufsize size (bytes) of the packet buffer
503  *
504  * @return 0 on success, in case of error:
505  *  EINVAL  malformatted RTP packet or internal error
506  *  ENOSPC  bufsize is too small (to add authentication tag)
507  */
508 int
509 srtp_send (srtp_session_t *s, uint8_t *buf, size_t *lenp, size_t bufsize)
510 {
511     size_t len = *lenp;
512     int val = srtp_crypt (s, buf, len);
513     if (val)
514         return val;
515
516     if (!(s->flags & SRTP_UNAUTHENTICATED))
517     {
518         if (bufsize < (len + s->tag_len))
519             return ENOSPC;
520
521         const uint8_t *tag = rtp_digest (s, buf, len);
522         memcpy (buf + len, tag, s->tag_len);
523         *lenp = len + s->tag_len;
524     }
525
526     return 0;
527 }
528
529
530 /**
531  * Turns a SRTP packet into a RTP packet: authenticates the packet,
532  * then decrypts it.
533  *
534  * @param buf RTP packet to be digested/decrypted
535  * @param lenp pointer to the SRTP packet length on entry,
536  *             set to the RTP length on exit (undefined in case of error)
537  *
538  * @return 0 on success, in case of error:
539  *  EINVAL  malformatted SRTP packet
540  *  EACCES  authentication failed (spoofed packet or out-of-sync)
541  */
542 int
543 srtp_recv (srtp_session_t *s, uint8_t *buf, size_t *lenp)
544 {
545     size_t len = *lenp;
546     /* FIXME: anti-replay */
547
548     if (!(s->flags & SRTP_UNAUTHENTICATED))
549     {
550         if (len < (12u + s->tag_len))
551             return EINVAL;
552         len -= s->tag_len;
553
554         const uint8_t *tag = rtp_digest (s, buf, len);
555         if (memcmp (buf + len, tag, s->tag_len))
556             return EACCES;
557
558         *lenp = len;
559     }
560
561     return srtp_crypt (s, buf, len);
562 }
563
564
565 /** AES-CM for RTCP (salt = 14 bytes + 2 nul bytes) */
566 static int
567 rtcp_crypt (gcry_cipher_hd_t hd, uint32_t ssrc, uint32_t index,
568             const uint32_t *salt, uint8_t *data, size_t len)
569 {
570     return rtp_crypt (hd, ssrc, index >> 16, index & 0xffff, salt, data, len);
571 }
572
573
574 /** Message Authentication and Integrity for RTCP */
575 static const uint8_t *
576 rtcp_digest (gcry_md_hd_t md, const void *data, size_t len)
577 {
578     gcry_md_reset (md);
579     gcry_md_write (md, data, len);
580     return gcry_md_read (md, 0);
581 }
582
583
584 /**
585  * Encrypts/decrypts a RTCP packet and updates SRTCP context
586  * (CTR block cypher mode of operation has identical encryption and
587  * decryption function).
588  *
589  * @param buf RTCP packet to be en-/decrypted
590  * @param len RTCP packet length
591  *
592  * @return 0 on success, in case of error:
593  *  EINVAL  malformatted RTCP packet
594  */
595 static int srtcp_crypt (srtp_session_t *s, uint8_t *buf, size_t len)
596 {
597     assert (s != NULL);
598
599     /* 8-bytes unencrypted header, and 4-bytes unencrypted footer */
600     if ((len < 12) || ((buf[0] >> 6) != 2))
601         return EINVAL;
602
603     uint32_t index = s->rtcp_index++;
604     if (index == 0x7fffffff)
605         s->rtcp_index = 0; /* 31-bit wrap */
606
607     if (s->flags & SRTCP_UNENCRYPTED)
608         return 0;
609
610     uint32_t ssrc;
611     memcpy (&ssrc, buf + 4, 4);
612
613     if (rtcp_crypt (s->rtcp.cipher, ssrc, index, s->rtp.salt,
614                     buf + 8, len - 8))
615         return EINVAL;
616     return 0;
617 }
618
619
620 /**
621  * Turns a RTCP packet into a SRTCP packet: encrypt it, then computes
622  * the authentication tag and appends it.
623  *
624  * @param buf RTCP packet to be encrypted/digested
625  * @param lenp pointer to the RTCP packet length on entry,
626  *             set to the SRTCP length on exit (undefined in case of error)
627  * @param bufsize size (bytes) of the packet buffer
628  *
629  * @return 0 on success, in case of error:
630  *  EINVAL  malformatted RTCP packet or internal error
631  *  ENOSPC  bufsize is too small (to add index and authentication tag)
632  */
633 int
634 srtcp_send (srtp_session_t *s, uint8_t *buf, size_t *lenp, size_t bufsize)
635 {
636     size_t len = *lenp;
637     if (bufsize < (len + 4 + s->tag_len))
638         return ENOSPC;
639
640     uint32_t index = s->rtcp_index;
641     if ((s->flags & SRTCP_UNENCRYPTED) == 0)
642         index |= 0x80000000; /* Set Encrypted bit */
643     memcpy (buf + len, &(uint32_t){ htonl (index) }, 4);
644
645     int val = srtcp_crypt (s, buf, len);
646     if (val)
647         return val;
648
649     len += 4; /* Digest SRTCP index too */
650
651     const uint8_t *tag = rtcp_digest (s->rtp.mac, buf, len);
652     memcpy (buf + len, tag, s->tag_len);
653     *lenp = len + s->tag_len;
654     s->rtcp_index++; /* Update index */
655     return 0;
656 }
657
658
659 /**
660  * Turns a SRTCP packet into a RTCP packet: authenticates the packet,
661  * then decrypts it.
662  *
663  * @param buf RTCP packet to be digested/decrypted
664  * @param lenp pointer to the SRTCP packet length on entry,
665  *             set to the RTCP length on exit (undefined in case of error)
666  *
667  * @return 0 on success, in case of error:
668  *  EINVAL  malformatted SRTCP packet
669  *  EACCES  authentication failed (spoofed packet or out-of-sync)
670  */
671 int
672 srtcp_recv (srtp_session_t *s, uint8_t *buf, size_t *lenp)
673 {
674     size_t len = *lenp;
675     /* FIXME: anti-replay ?? */
676
677     if (len < (4u + s->tag_len))
678         return EINVAL;
679     len -= s->tag_len;
680
681     const uint8_t *tag = rtcp_digest (s->rtp.mac, buf, len);
682     if (memcmp (buf + len, tag, s->tag_len))
683          return EACCES;
684
685     len -= 4; /* Remove SRTCP index before decryption */
686     uint32_t index;
687     memcpy (&index, buf + len, 4);
688     index = ntohl (index);
689     if (((index - s->rtcp_index) & 0xffffffff) < 0x80000000)
690         s->rtcp_index = index; /* Update index */
691
692     *lenp = len;
693     return srtp_crypt (s, buf, len);
694 }
695