]> git.sesse.net Git - vlc/blob - libs/srtp/srtp.c
SRTP: support for parsing key and salt from a string
[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 /* TODO:
21  * Useless stuff (because nothing depends on it):
22  * - non-nul key derivation rate
23  * - MKI payload
24  */
25
26 #ifdef HAVE_CONFIG_H
27 # include <config.h>
28 #endif
29
30 #include <stdint.h>
31 #include <stddef.h>
32
33 #include "srtp.h"
34
35 #include <stdbool.h>
36 #include <stdlib.h>
37 #include <assert.h>
38 #include <errno.h>
39
40 #include <gcrypt.h>
41
42 #ifdef WIN32
43 # include <winsock2.h>
44 #else
45 # include <netinet/in.h>
46 # include <pthread.h>
47 GCRY_THREAD_OPTION_PTHREAD_IMPL;
48 #endif
49
50 #define debug( ... ) (void)0
51
52 typedef struct srtp_proto_t
53 {
54     gcry_cipher_hd_t cipher;
55     gcry_md_hd_t     mac;
56     uint64_t         window;
57     uint32_t         salt[4];
58 } srtp_proto_t;
59
60 struct srtp_session_t
61 {
62     srtp_proto_t rtp;
63     srtp_proto_t rtcp;
64     unsigned flags;
65     unsigned kdr;
66     uint32_t rtcp_index;
67     uint32_t rtp_roc;
68     uint16_t rtp_seq;
69     uint16_t rtp_rcc;
70     uint8_t  tag_len;
71 };
72
73 enum
74 {
75     SRTP_CRYPT,
76     SRTP_AUTH,
77     SRTP_SALT,
78     SRTCP_CRYPT,
79     SRTCP_AUTH,
80     SRTCP_SALT
81 };
82
83
84 static inline unsigned rcc_mode (const srtp_session_t *s)
85 {
86     return (s->flags >> 4) & 3;
87 }
88
89 static bool libgcrypt_usable = false;
90
91 static void initonce_libgcrypt (void)
92 {
93 #ifndef WIN32
94     gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
95 #endif
96
97     if ((gcry_check_version ("1.1.94") == NULL)
98      || gcry_control (GCRYCTL_DISABLE_SECMEM, 0)
99      || gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0))
100         return;
101
102     libgcrypt_usable = true;
103 }
104
105 static int init_libgcrypt (void)
106 {
107     int retval;
108 #ifndef WIN32
109     static pthread_once_t once = PTHREAD_ONCE_INIT;
110
111     pthread_once (&once, initonce_libgcrypt);
112 #else
113 # warning FIXME: This is not thread-safe.
114     if (!libgcrypt_usable)
115         initonce_libgcrypt ();
116 #endif
117
118     retval = libgcrypt_usable ? 0 : -1;
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 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.
167  *
168  * @return NULL in case of error
169  */
170 srtp_session_t *
171 srtp_create (int encr, int auth, unsigned tag_len, int prf, unsigned flags)
172 {
173     if ((flags & ~SRTP_FLAGS_MASK) || init_libgcrypt ())
174         return NULL;
175
176     int cipher, md;
177     switch (encr)
178     {
179         case SRTP_ENCR_NULL:
180             cipher = GCRY_CIPHER_NONE;
181             break;
182
183         case SRTP_ENCR_AES_CM:
184             cipher = GCRY_CIPHER_AES;
185             break;
186
187         default:
188             return NULL;
189     }
190
191     switch (auth)
192     {
193         case SRTP_AUTH_NULL:
194             md = GCRY_MD_NONE;
195             break;
196
197         case SRTP_AUTH_HMAC_SHA1:
198             md = GCRY_MD_SHA1;
199             break;
200
201         default:
202             return NULL;
203     }
204
205     if (tag_len > gcry_md_get_algo_dlen (md))
206         return NULL;
207
208     if (prf != SRTP_PRF_AES_CM)
209         return NULL;
210
211     srtp_session_t *s = malloc (sizeof (*s));
212     if (s == NULL)
213         return NULL;
214
215     memset (s, 0, sizeof (*s));
216     s->flags = flags;
217     s->tag_len = tag_len;
218     s->rtp_rcc = 1; /* Default RCC rate */
219     if (rcc_mode (s))
220     {
221         if (tag_len < 4)
222             goto error;
223     }
224
225     if (proto_create (&s->rtp, cipher, md) == 0)
226     {
227         if (proto_create (&s->rtcp, cipher, md) == 0)
228             return s;
229         proto_destroy (&s->rtp);
230     }
231
232 error:
233     free (s);
234     return NULL;
235 }
236
237
238 /**
239  * Counter Mode encryption/decryption (ctr length = 16 bytes)
240  * with non-padded (truncated) text
241  */
242 static int
243 ctr_crypt (gcry_cipher_hd_t hd, const void *ctr, uint8_t *data, size_t len)
244 {
245     const size_t ctrlen = 16;
246     div_t d = div (len, ctrlen);
247
248     if (gcry_cipher_setctr (hd, ctr, ctrlen)
249      || gcry_cipher_encrypt (hd, data, d.quot * ctrlen, NULL, 0))
250         return -1;
251
252     if (d.rem)
253     {
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);
259
260         if (gcry_cipher_encrypt (hd, dummy, ctrlen, data, ctrlen))
261             return -1;
262         memcpy (data, dummy, d.rem);
263     }
264
265     return 0;
266 }
267
268
269 /**
270  * AES-CM key derivation (saltlen = 14 bytes)
271  */
272 static int
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)
276 {
277     uint8_t iv[16];
278
279     memcpy (iv, salt, 14);
280     iv[14] = iv[15] = 0;
281
282     assert (rlen < 14);
283     iv[13 - rlen] ^= label;
284     for (size_t i = 0; i < rlen; i++)
285         iv[sizeof (iv) - rlen + i] ^= r[i];
286
287     memset (out, 0, outlen);
288     return ctr_crypt (prf, iv, out, outlen);
289 }
290
291
292 static int
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)
296 {
297     if (saltlen != 14)
298         return -1;
299
300     uint8_t keybuf[20];
301     uint8_t label = rtcp ? SRTCP_CRYPT : SRTP_CRYPT;
302
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))
308         return -1;
309
310     return 0;
311 }
312
313
314 /**
315  * SRTP/SRTCP cipher/salt/MAC keys derivation.
316  */
317 static int
318 srtp_derive (srtp_session_t *s, const void *key, size_t keylen,
319              const void *salt, size_t saltlen)
320 {
321     gcry_cipher_hd_t prf;
322     uint8_t r[6];
323
324     if (gcry_cipher_open (&prf, GCRY_CIPHER_AES, GCRY_CIPHER_MODE_CTR, 0)
325      || gcry_cipher_setkey (prf, key, keylen))
326         return -1;
327
328 #if 0
329     /* RTP key derivation */
330     if (s->kdr != 0)
331     {
332         uint64_t index = (((uint64_t)s->rtp_roc) << 16) | s->rtp_seq;
333         index /= s->kdr;
334
335         for (int i = sizeof (r) - 1; i >= 0; i--)
336         {
337             r[i] = index & 0xff;
338             index = index >> 8;
339         }
340     }
341     else
342 #endif
343         memset (r, 0, sizeof (r));
344
345     if (proto_derive (&s->rtp, prf, salt, saltlen, r, 6, false))
346         return -1;
347
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))
351         return -1;
352
353     (void)gcry_cipher_close (prf);
354     return 0;
355 }
356
357
358 /**
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.
364  *
365  * @return 0 on success, in case of error:
366  *  EINVAL  invalid or unsupported key/salt sizes combination
367  */
368 int
369 srtp_setkey (srtp_session_t *s, const void *key, size_t keylen,
370              const void *salt, size_t saltlen)
371 {
372     return srtp_derive (s, key, keylen, salt, saltlen) ? EINVAL : 0;
373 }
374
375 static int hexdigit (char c)
376 {
377     if ((c >= '0') && (c <= '9'))
378         return c - '0';
379     if ((c >= 'A') && (c <= 'F'))
380         return c - 'A' + 0xA;
381     if ((c >= 'a') && (c <= 'f'))
382         return c - 'a' + 0xa;
383     return -1;
384 }
385
386 static ssize_t hexstring (const char *in, uint8_t *out, size_t outlen)
387 {
388     size_t inlen = strlen (in);
389
390     if ((inlen > (2 * outlen)) || (inlen & 1))
391         return -1;
392
393     for (size_t i = 0; i < inlen; i += 2)
394     {
395         int a = hexdigit (in[2 * i]), b = hexdigit (in[2 * i + 1]);
396         if ((a == -1) || (b == -1))
397             return EINVAL;
398         out[i] = (a << 4) | b;
399     }
400     return inlen / 2;
401 }
402
403 /**
404  * Sets (or resets) the master key and master salt for a SRTP session
405  * from hexadecimal strings. See also srtp_setkey().
406  *
407  * @return 0 on success, in case of error:
408  *  EINVAL  invalid or unsupported key/salt sizes combination
409  */
410 int
411 srtp_setkeystring (srtp_session_t *s, const char *key, const char *salt)
412 {
413     uint8_t bkey[32]; /* TODO/NOTE: hard-coded for AES */
414     uint8_t bsalt[14]; /* TODO/NOTE: hard-coded for the PRF-AES-CM */
415     ssize_t bkeylen = hexstring (key, bkey, sizeof (bkey));
416     ssize_t bsaltlen = hexstring (salt, bsalt, sizeof (bsalt));
417
418     if ((bkeylen == -1) || (bsaltlen == -1))
419         return EINVAL;
420     return srtp_derive (s, bkey, bkeylen, bsalt, bsaltlen) ? EINVAL : 0;
421 }
422
423 /**
424  * Sets Roll-over-Counter Carry (RCC) rate for the SRTP session. If not
425  * specified (through this function), the default rate of ONE is assumed
426  * (i.e. every RTP packets will carry the RoC). RCC rate is ignored if none
427  * of the RCC mode has been selected.
428  *
429  * The RCC mode is selected through one of these flags for srtp_create():
430  *  SRTP_RCC_MODE1: integrity protection only for RoC carrying packets
431  *  SRTP_RCC_MODE2: integrity protection for all packets
432  *  SRTP_RCC_MODE3: no integrity protection
433  *
434  * RCC mode 3 is insecure. Compared to plain RTP, it provides confidentiality
435  * (through encryption) but is much more prone to DoS. It can only be used if
436  * anti-spoofing protection is provided by lower network layers (e.g. IPsec,
437  * or trusted routers and proper source address filtering).
438  *
439  * If RCC rate is 1, RCC mode 1 and 2 are functionally identical.
440  *
441  * @param rate RoC Carry rate (MUST NOT be zero)
442  */
443 void srtp_setrcc_rate (srtp_session_t *s, uint16_t rate)
444 {
445     assert (rate != 0);
446     s->rtp_rcc = rate;
447 }
448
449
450 /** AES-CM for RTP (salt = 14 bytes + 2 nul bytes) */
451 static int
452 rtp_crypt (gcry_cipher_hd_t hd, uint32_t ssrc, uint32_t roc, uint16_t seq,
453            const uint32_t *salt, uint8_t *data, size_t len)
454 {
455     /* Determines cryptographic counter (IV) */
456     uint32_t counter[4];
457     counter[0] = salt[0];
458     counter[1] = salt[1] ^ ssrc;
459     counter[2] = salt[2] ^ htonl (roc);
460     counter[3] = salt[3] ^ htonl (seq << 16);
461
462     /* Encryption */
463     return ctr_crypt (hd, counter, data, len);
464 }
465
466
467 /** Determines SRTP Roll-Over-Counter (in host-byte order) */
468 static uint32_t
469 srtp_compute_roc (const srtp_session_t *s, uint16_t seq)
470 {
471     uint32_t roc = s->rtp_roc;
472
473     if (((seq - s->rtp_seq) & 0xffff) < 0x8000)
474     {
475         /* Sequence is ahead, good */
476         if (seq < s->rtp_seq)
477             roc++; /* Sequence number wrap */
478     }
479     else
480     {
481         /* Sequence is late, bad */
482         if (seq > s->rtp_seq)
483             roc--; /* Wrap back */
484     }
485     return roc;
486 }
487
488
489 /** Returns RTP sequence (in host-byte order) */
490 static inline uint16_t rtp_seq (const uint8_t *buf)
491 {
492     return (buf[2] << 8) | buf[3];
493 }
494
495
496 /** Message Authentication and Integrity for RTP */
497 static const uint8_t *
498 rtp_digest (srtp_session_t *s, const uint8_t *data, size_t len,
499             uint32_t roc)
500 {
501     const gcry_md_hd_t md = s->rtp.mac;
502
503     gcry_md_reset (md);
504     gcry_md_write (md, data, len);
505     gcry_md_write (md, &(uint32_t){ htonl (roc) }, 4);
506     return gcry_md_read (md, 0);
507 }
508
509
510 /**
511  * Encrypts/decrypts a RTP packet and updates SRTP context
512  * (CTR block cypher mode of operation has identical encryption and
513  * decryption function).
514  *
515  * @param buf RTP packet to be en-/decrypted
516  * @param len RTP packet length
517  *
518  * @return 0 on success, in case of error:
519  *  EINVAL  malformatted RTP packet
520  *  EACCES  replayed packet or out-of-window or sync lost
521  */
522 static int srtp_crypt (srtp_session_t *s, uint8_t *buf, size_t len)
523 {
524     assert (s != NULL);
525
526     if ((len < 12) || ((buf[0] >> 6) != 2))
527         return EINVAL;
528
529     /* Computes encryption offset */
530     uint16_t offset = 12;
531     offset += (buf[0] & 0xf) * 4; // skips CSRC
532
533     if (buf[0] & 0x10)
534     {
535         uint16_t extlen;
536
537         offset += 4;
538         if (len < offset)
539             return EINVAL;
540
541         memcpy (&extlen, buf + offset - 2, 2);
542         offset += htons (extlen); // skips RTP extension header
543     }
544
545     if (len < offset)
546         return EINVAL;
547
548     /* Determines RTP 48-bits counter and SSRC */
549     uint16_t seq = rtp_seq (buf);
550     uint32_t roc = srtp_compute_roc (s, seq), ssrc;
551     memcpy (&ssrc, buf + 8, 4);
552
553     /* Updates ROC and sequence (it's safe now) */
554     int16_t diff = seq - s->rtp_seq;
555     if (diff > 0)
556     {
557         /* Sequence in the future, good */
558         s->rtp.window = s->rtp.window << diff;
559         s->rtp.window |= 1;
560         s->rtp_seq = seq, s->rtp_roc = roc;
561     }
562     else
563     {
564         /* Sequence in the past/present, bad */
565         diff = -diff;
566         if ((diff >= 64) || ((s->rtp.window >> diff) & 1))
567             return EACCES; /* Replay attack */
568         s->rtp.window |= 1 << diff;
569     }
570
571     /* Encrypt/Decrypt */
572     if (s->flags & SRTP_UNENCRYPTED)
573         return 0;
574
575     if (rtp_crypt (s->rtp.cipher, ssrc, roc, seq, s->rtp.salt,
576                    buf + offset, len - offset))
577         return EINVAL;
578
579     return 0;
580 }
581
582
583 /**
584  * Turns a RTP packet into a SRTP packet: encrypt it, then computes
585  * the authentication tag and appends it.
586  * Note that you can encrypt packet in disorder.
587  *
588  * @param buf RTP packet to be encrypted/digested
589  * @param lenp pointer to the RTP packet length on entry,
590  *             set to the SRTP length on exit (undefined on non-ENOSPC error)
591  * @param bufsize size (bytes) of the packet buffer
592  *
593  * @return 0 on success, in case of error:
594  *  EINVAL  malformatted RTP packet or internal error
595  *  ENOSPC  bufsize is too small to add authentication tag
596  *          (<lenp> will hold the required byte size)
597  *  EACCES  packet would trigger a replay error on receiver
598  */
599 int
600 srtp_send (srtp_session_t *s, uint8_t *buf, size_t *lenp, size_t bufsize)
601 {
602     size_t len = *lenp;
603     int val = srtp_crypt (s, buf, len);
604     if (val)
605         return val;
606
607     if (!(s->flags & SRTP_UNAUTHENTICATED))
608     {
609         size_t tag_len = s->tag_len;
610         *lenp = len + tag_len;
611         if (bufsize < (len + tag_len))
612             return ENOSPC;
613
614         uint32_t roc = srtp_compute_roc (s, rtp_seq (buf));
615         const uint8_t *tag = rtp_digest (s, buf, len, roc);
616         if (rcc_mode (s))
617         {
618             assert (s->rtp_rcc);
619             if ((rtp_seq (buf) % s->rtp_rcc) == 0)
620             {
621                 memcpy (buf + len, &(uint32_t){ htonl (s->rtp_roc) }, 4);
622                 len += 4;
623                 if (rcc_mode (s) == 3)
624                     tag_len = 0;
625                 else
626                     tag_len -= 4;
627             }
628             else
629             {
630                 if (rcc_mode (s) & 1)
631                     tag_len = 0;
632             }
633         }
634         memcpy (buf + len, tag, tag_len);
635     }
636
637     return 0;
638 }
639
640
641 /**
642  * Turns a SRTP packet into a RTP packet: authenticates the packet,
643  * then decrypts it.
644  *
645  * @param buf RTP packet to be digested/decrypted
646  * @param lenp pointer to the SRTP packet length on entry,
647  *             set to the RTP length on exit (undefined in case of error)
648  *
649  * @return 0 on success, in case of error:
650  *  EINVAL  malformatted SRTP packet
651  *  EACCES  authentication failed (spoofed packet or out-of-sync)
652  */
653 int
654 srtp_recv (srtp_session_t *s, uint8_t *buf, size_t *lenp)
655 {
656     size_t len = *lenp;
657     if (len < 12u)
658         return EINVAL;
659
660     if (!(s->flags & SRTP_UNAUTHENTICATED))
661     {
662         size_t tag_len = s->tag_len, roc_len = 0;
663         if (rcc_mode (s))
664         {
665             if ((rtp_seq (buf) % s->rtp_rcc) == 0)
666             {
667                 roc_len = 4;
668                 if (rcc_mode (s) == 3)
669                     tag_len = 0;
670                 else
671                     tag_len -= 4;
672             }
673             else
674             {
675                 if (rcc_mode (s) & 1)
676                     tag_len = 0; // RCC mode 1 or 3: no auth
677             }
678         }
679
680         if (len < (12u + roc_len + tag_len))
681             return EINVAL;
682         len -= roc_len + tag_len;
683
684         uint32_t roc = srtp_compute_roc (s, rtp_seq (buf)), rcc;
685         if (roc_len)
686         {
687             assert (roc_len == 4);
688             memcpy (&rcc, buf + len, 4);
689             rcc = ntohl (rcc);
690         }
691         else
692             rcc = roc;
693
694         const uint8_t *tag = rtp_digest (s, buf, len, rcc);
695 #if 0
696         printf ("Computed: 0x");
697         for (unsigned i = 0; i < tag_len; i++)
698             printf ("%02x", tag[i]);
699         printf ("\nReceived: 0x");
700         for (unsigned i = 0; i < tag_len; i++)
701             printf ("%02x", buf[len + roc_len + i]);
702         puts ("");
703 #endif
704         if (memcmp (buf + len + roc_len, tag, tag_len))
705             return EACCES;
706
707         if (roc_len)
708         {
709             /* Authenticated packet carried a Roll-Over-Counter */
710             s->rtp_roc += rcc - roc;
711             assert (srtp_compute_roc (s, rtp_seq (buf)) == rcc);
712         }
713         *lenp = len;
714     }
715
716     return srtp_crypt (s, buf, len);
717 }
718
719
720 /** AES-CM for RTCP (salt = 14 bytes + 2 nul bytes) */
721 static int
722 rtcp_crypt (gcry_cipher_hd_t hd, uint32_t ssrc, uint32_t index,
723             const uint32_t *salt, uint8_t *data, size_t len)
724 {
725     return rtp_crypt (hd, ssrc, index >> 16, index & 0xffff, salt, data, len);
726 }
727
728
729 /** Message Authentication and Integrity for RTCP */
730 static const uint8_t *
731 rtcp_digest (gcry_md_hd_t md, const void *data, size_t len)
732 {
733     gcry_md_reset (md);
734     gcry_md_write (md, data, len);
735     return gcry_md_read (md, 0);
736 }
737
738
739 /**
740  * Encrypts/decrypts a RTCP packet and updates SRTCP context
741  * (CTR block cypher mode of operation has identical encryption and
742  * decryption function).
743  *
744  * @param buf RTCP packet to be en-/decrypted
745  * @param len RTCP packet length
746  *
747  * @return 0 on success, in case of error:
748  *  EINVAL  malformatted RTCP packet
749  */
750 static int srtcp_crypt (srtp_session_t *s, uint8_t *buf, size_t len)
751 {
752     assert (s != NULL);
753
754     /* 8-bytes unencrypted header, and 4-bytes unencrypted footer */
755     if ((len < 12) || ((buf[0] >> 6) != 2))
756         return EINVAL;
757
758     uint32_t index;
759     memcpy (&index, buf + len, 4);
760     index = ntohl (index);
761     if (((index >> 31) != 0) != ((s->flags & SRTCP_UNENCRYPTED) == 0))
762         return EINVAL; // E-bit mismatch
763
764     index &= ~(1 << 31); // clear E-bit for counter
765
766     /* Updates SRTCP index (safe here) */
767     int32_t diff = index - s->rtcp_index;
768     if (diff > 0)
769     {
770         /* Packet in the future, good */
771         s->rtcp.window = s->rtcp.window << diff;
772         s->rtcp.window |= 1;
773         s->rtcp_index = index;
774     }
775     else
776     {
777         /* Packet in the past/present, bad */
778         diff = -diff;
779         if ((diff >= 64) || ((s->rtcp.window >> diff) & 1))
780             return EACCES; // replay attack!
781         s->rtp.window |= 1 << diff;
782     }
783
784     /* Crypts SRTCP */
785     if (s->flags & SRTCP_UNENCRYPTED)
786         return 0;
787
788     uint32_t ssrc;
789     memcpy (&ssrc, buf + 4, 4);
790
791     if (rtcp_crypt (s->rtcp.cipher, ssrc, index, s->rtp.salt,
792                     buf + 8, len - 8))
793         return EINVAL;
794     return 0;
795 }
796
797
798 /**
799  * Turns a RTCP packet into a SRTCP packet: encrypt it, then computes
800  * the authentication tag and appends it.
801  *
802  * @param buf RTCP packet to be encrypted/digested
803  * @param lenp pointer to the RTCP packet length on entry,
804  *             set to the SRTCP length on exit (undefined in case of error)
805  * @param bufsize size (bytes) of the packet buffer
806  *
807  * @return 0 on success, in case of error:
808  *  EINVAL  malformatted RTCP packet or internal error
809  *  ENOSPC  bufsize is too small (to add index and authentication tag)
810  */
811 int
812 srtcp_send (srtp_session_t *s, uint8_t *buf, size_t *lenp, size_t bufsize)
813 {
814     size_t len = *lenp;
815     if (bufsize < (len + 4 + s->tag_len))
816         return ENOSPC;
817
818     uint32_t index = ++s->rtcp_index;
819     if (index >> 31)
820         s->rtcp_index = index = 0; /* 31-bit wrap */
821
822     if ((s->flags & SRTCP_UNENCRYPTED) == 0)
823         index |= 0x80000000; /* Set Encrypted bit */
824     memcpy (buf + len, &(uint32_t){ htonl (index) }, 4);
825
826     int val = srtcp_crypt (s, buf, len);
827     if (val)
828         return val;
829
830     len += 4; /* Digests SRTCP index too */
831
832     const uint8_t *tag = rtcp_digest (s->rtp.mac, buf, len);
833     memcpy (buf + len, tag, s->tag_len);
834     *lenp = len + s->tag_len;
835     return 0;
836 }
837
838
839 /**
840  * Turns a SRTCP packet into a RTCP packet: authenticates the packet,
841  * then decrypts it.
842  *
843  * @param buf RTCP packet to be digested/decrypted
844  * @param lenp pointer to the SRTCP packet length on entry,
845  *             set to the RTCP length on exit (undefined in case of error)
846  *
847  * @return 0 on success, in case of error:
848  *  EINVAL  malformatted SRTCP packet
849  *  EACCES  authentication failed (spoofed packet or out-of-sync)
850  */
851 int
852 srtcp_recv (srtp_session_t *s, uint8_t *buf, size_t *lenp)
853 {
854     size_t len = *lenp;
855
856     if (len < (4u + s->tag_len))
857         return EINVAL;
858     len -= s->tag_len;
859
860     const uint8_t *tag = rtcp_digest (s->rtp.mac, buf, len);
861     if (memcmp (buf + len, tag, s->tag_len))
862          return EACCES;
863
864     len -= 4; /* Remove SRTCP index before decryption */
865     *lenp = len;
866     return srtp_crypt (s, buf, len);
867 }
868