]> git.sesse.net Git - vlc/blob - libs/srtp/srtp.c
Untested support for RFC4771:
[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     if ((gcry_check_version ("1.1.94") == NULL)
94      || gcry_control (GCRYCTL_DISABLE_SECMEM, 0)
95      || gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0)
96 #ifndef WIN32
97      || gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread)
98 #endif
99        )
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_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
110     static pthread_once_t once = PTHREAD_ONCE_INIT;
111
112     pthread_mutex_lock (&mutex);
113     pthread_once (&once, initonce_libgcrypt);
114     retval = -libgcrypt_usable;
115     pthread_mutex_unlock (&mutex);
116 #else
117 # warning FIXME: This is not thread-safe.
118     if (!libgcrypt_usable)
119         initonce_libgcrypt ();
120     retval = -libgcrypt_usable;
121 #endif
122
123     return retval;
124
125 }
126
127
128 static void proto_destroy (srtp_proto_t *p)
129 {
130     gcry_md_close (p->mac);
131     gcry_cipher_close (p->cipher);
132 }
133
134
135 /**
136  * Releases all resources associated with a Secure RTP session.
137  */
138 void srtp_destroy (srtp_session_t *s)
139 {
140     assert (s != NULL);
141
142     proto_destroy (&s->rtcp);
143     proto_destroy (&s->rtp);
144     free (s);
145 }
146
147
148 static int proto_create (srtp_proto_t *p, int gcipher, int gmd)
149 {
150     if (gcry_cipher_open (&p->cipher, gcipher, GCRY_CIPHER_MODE_CTR, 0) == 0)
151     {
152         if (gcry_md_open (&p->mac, gmd, GCRY_MD_FLAG_HMAC) == 0)
153             return 0;
154         gcry_cipher_close (p->cipher);
155     }
156     return -1;
157 }
158
159
160 /**
161  * Allocates a Secure RTP one-way session.
162  * The same session cannot be used both ways because this would confuse
163  * internal cryptographic counters; it is however of course feasible to open
164  * multiple simultaneous sessions with the same master key.
165  *
166  * @param encr encryption algorithm number
167  * @param auth authentication algortihm number
168  * @param tag_len authentication tag byte length (NOT including RCC)
169  * @param flags OR'ed optional flags.
170  *
171  * @return NULL in case of error
172  */
173 srtp_session_t *
174 srtp_create (int encr, int auth, unsigned tag_len, int prf, unsigned flags)
175 {
176     if ((flags & ~SRTP_FLAGS_MASK) || init_libgcrypt ())
177         return NULL;
178
179     int cipher, md;
180     switch (encr)
181     {
182         case SRTP_ENCR_NULL:
183             cipher = GCRY_CIPHER_NONE;
184             break;
185
186         case SRTP_ENCR_AES_CM:
187             cipher = GCRY_CIPHER_AES;
188             break;
189
190         default:
191             return NULL;
192     }
193
194     switch (auth)
195     {
196         case SRTP_AUTH_NULL:
197             md = GCRY_MD_NONE;
198             break;
199
200         case SRTP_AUTH_HMAC_SHA1:
201             md = GCRY_MD_SHA1;
202             break;
203
204         default:
205             return NULL;
206     }
207
208     if (tag_len > gcry_md_get_algo_dlen (auth))
209         return NULL;
210
211     if (prf != SRTP_PRF_AES_CM)
212         return NULL;
213
214     srtp_session_t *s = malloc (sizeof (*s));
215     if (s == NULL)
216         return NULL;
217
218     memset (s, 0, sizeof (*s));
219     s->flags = flags;
220     s->tag_len = tag_len;
221     s->rtp_rcc = 1; /* Default RCC rate */
222     if (rcc_mode (s))
223     {
224         if (tag_len < 4)
225             goto error;
226     }
227
228     if (proto_create (&s->rtp, cipher, md) == 0)
229     {
230         if (proto_create (&s->rtcp, cipher, md) == 0)
231             return s;
232         proto_destroy (&s->rtp);
233     }
234
235 error:
236     free (s);
237     return NULL;
238 }
239
240
241 /**
242  * Counter Mode encryption/decryption (ctr length = 16 bytes)
243  * with non-padded (truncated) text
244  */
245 static int
246 ctr_crypt (gcry_cipher_hd_t hd, const void *ctr, uint8_t *data, size_t len)
247 {
248     const size_t ctrlen = 16;
249     div_t d = div (len, ctrlen);
250
251     if (gcry_cipher_setctr (hd, ctr, ctrlen)
252      || gcry_cipher_encrypt (hd, data, d.quot * ctrlen, NULL, 0))
253         return -1;
254
255     if (d.rem)
256     {
257         /* Truncated last block */
258         uint8_t dummy[ctrlen];
259         data += d.quot * ctrlen;
260         memcpy (dummy, data, d.rem);
261         memset (dummy + d.rem, 0, ctrlen - d.rem);
262
263         if (gcry_cipher_encrypt (hd, dummy, ctrlen, data, ctrlen))
264             return -1;
265         memcpy (data, dummy, d.rem);
266     }
267
268     return 0;
269 }
270
271
272 /**
273  * AES-CM key derivation (saltlen = 14 bytes)
274  */
275 static int
276 derive (gcry_cipher_hd_t prf, const void *salt,
277         const uint8_t *r, size_t rlen, uint8_t label,
278         void *out, size_t outlen)
279 {
280     uint8_t iv[16];
281
282     memcpy (iv, salt, 14);
283     iv[14] = iv[15] = 0;
284
285     assert (rlen < 14);
286     iv[13 - rlen] ^= label;
287     for (size_t i = 0; i < rlen; i++)
288         iv[sizeof (iv) - rlen + i] ^= r[i];
289
290     memset (out, 0, outlen);
291     return ctr_crypt (prf, iv, out, outlen);
292 }
293
294
295 static int
296 proto_derive (srtp_proto_t *p, gcry_cipher_hd_t prf,
297               const void *salt, size_t saltlen,
298               const uint8_t *r, size_t rlen, bool rtcp)
299 {
300     if (saltlen != 14)
301         return -1;
302
303     uint8_t keybuf[20];
304     uint8_t label = rtcp ? SRTCP_CRYPT : SRTP_CRYPT;
305
306     if (derive (prf, salt, r, rlen, label++, keybuf, 16)
307      || gcry_cipher_setkey (p->cipher, keybuf, 16)
308      || derive (prf, salt, r, rlen, label++, keybuf, 20)
309      || gcry_md_setkey (p->mac, keybuf, 20)
310      || derive (prf, salt, r, rlen, label, p->salt, 14))
311         return -1;
312
313     return 0;
314 }
315
316
317 /**
318  * SRTP/SRTCP cipher/salt/MAC keys derivation.
319  */
320 static int
321 srtp_derive (srtp_session_t *s, const void *key, size_t keylen,
322              const void *salt, size_t saltlen)
323 {
324     gcry_cipher_hd_t prf;
325     uint8_t r[6];
326
327     if (gcry_cipher_open (&prf, GCRY_CIPHER_AES, GCRY_CIPHER_MODE_CTR, 0)
328      || gcry_cipher_setkey (prf, key, keylen))
329         return -1;
330
331     /* RTP key derivation */
332     if (s->kdr != 0)
333     {
334         uint64_t index = (((uint64_t)s->rtp_roc) << 16) | s->rtp_seq;
335         index /= s->kdr;
336
337         for (int i = sizeof (r) - 1; i >= 0; i--)
338         {
339             r[i] = index & 0xff;
340             index = index >> 8;
341         }
342     }
343     else
344         memset (r, 0, sizeof (r));
345
346     if (proto_derive (&s->rtp, prf, salt, saltlen, r, 6, false))
347         return -1;
348
349     /* RTCP key derivation */
350     memcpy (r, &(uint32_t){ htonl (s->rtcp_index) }, 4);
351     if (proto_derive (&s->rtcp, prf, salt, saltlen, r, 4, true))
352         return -1;
353
354     (void)gcry_cipher_close (prf);
355     return 0;
356 }
357
358
359 /**
360  * Sets (or resets) the master key and master salt for a SRTP session.
361  * This must be done at least once before using rtp_send(), rtp_recv(),
362  * rtcp_send() or rtcp_recv(). Also, rekeying is required every
363  * 2^48 RTP packets or 2^31 RTCP packets (whichever comes first),
364  * otherwise the protocol security might be broken.
365  *
366  * @return 0 on success, in case of error:
367  *  EINVAL  invalid or unsupported key/salt sizes combination
368  */
369 int
370 srtp_setkey (srtp_session_t *s, const void *key, size_t keylen,
371              const void *salt, size_t saltlen)
372 {
373     return srtp_derive (s, key, keylen, salt, saltlen) ? EINVAL : 0;
374 }
375
376
377 /**
378  * Sets Roll-over-Counter Carry (RCC) rate for the SRTP session. If not
379  * specified (through this function), the default rate of ONE is assumed
380  * (i.e. every RTP packets will carry the RoC). RCC rate is ignored if none
381  * of the RCC mode has been selected.
382  *
383  * The RCC mode is selected through one of these flags for srtp_create():
384  *  SRTP_RCC_MODE1: integrity protection only for RoC carrying packets
385  *  SRTP_RCC_MODE2: integrity protection for all packets
386  *  SRTP_RCC_MODE3: no integrity protection
387  *
388  * RCC mode 3 is insecure. Compared to plain RTP, it provides confidentiality
389  * (through encryption) but is much more prone to DoS. It can only be used if
390  * anti-spoofing protection is provided by lower network layers (e.g. IPsec,
391  * or trusted routers and proper source address filtering).
392  *
393  * If RCC rate is 1, RCC mode 1 and 2 are functionally identical.
394  *
395  * @param rate RoC Carry rate (MUST NOT be zero)
396  */
397 void srtp_setrcc_rate (srtp_session_t *s, uint16_t rate)
398 {
399     assert (rate != 0);
400     s->rtp_rcc = rate;
401 }
402
403
404 /** AES-CM for RTP (salt = 14 bytes + 2 nul bytes) */
405 static int
406 rtp_crypt (gcry_cipher_hd_t hd, uint32_t ssrc, uint32_t roc, uint16_t seq,
407            const uint32_t *salt, uint8_t *data, size_t len)
408 {
409     /* Determines cryptographic counter (IV) */
410     uint32_t counter[4];
411     counter[0] = salt[0];
412     counter[1] = salt[1] ^ ssrc;
413     counter[2] = salt[2] ^ htonl (roc);
414     counter[3] = salt[3] ^ htonl (seq << 16);
415
416     /* Encryption */
417     return ctr_crypt (hd, counter, data, len);
418 }
419
420
421 /** Determines SRTP Roll-Over-Counter (in host-byte order) */
422 static uint32_t
423 srtp_compute_roc (const srtp_session_t *s, uint16_t seq)
424 {
425     uint32_t roc = s->rtp_roc;
426
427     if (((seq - s->rtp_seq) & 0xffff) < 0x8000)
428     {
429         /* Sequence is ahead, good */
430         if (seq < s->rtp_seq)
431             roc++; /* Sequence number wrap */
432     }
433     else
434     {
435         /* Sequence is late, bad */
436         if (seq > s->rtp_seq)
437             roc--; /* Wrap back */
438     }
439     return roc;
440 }
441
442
443 /** Returns RTP sequence (in host-byte order) */
444 static inline uint16_t rtp_seq (const uint8_t *buf)
445 {
446     return (buf[2] << 8) | buf[3];
447 }
448
449
450 /** Message Authentication and Integrity for RTP */
451 static const uint8_t *
452 rtp_digest (srtp_session_t *s, const uint8_t *data, size_t len,
453             uint32_t roc)
454 {
455     const gcry_md_hd_t md = s->rtp.mac;
456
457     gcry_md_reset (md);
458     gcry_md_write (md, data, len);
459     gcry_md_write (md, &(uint32_t){ htonl (roc) }, 4);
460     return gcry_md_read (md, 0);
461 }
462
463
464 /**
465  * Encrypts/decrypts a RTP packet and updates SRTP context
466  * (CTR block cypher mode of operation has identical encryption and
467  * decryption function).
468  *
469  * @param buf RTP packet to be en-/decrypted
470  * @param len RTP packet length
471  *
472  * @return 0 on success, in case of error:
473  *  EINVAL  malformatted RTP packet
474  *  EACCES  replayed packet or out-of-window or sync lost
475  */
476 static int srtp_crypt (srtp_session_t *s, uint8_t *buf, size_t len)
477 {
478     assert (s != NULL);
479
480     if ((len < 12) || ((buf[0] >> 6) != 2))
481         return EINVAL;
482
483     /* Computes encryption offset */
484     uint16_t offset = 12;
485     offset += (buf[0] & 0xf) * 4; // skips CSRC
486
487     if (buf[0] & 0x10)
488     {
489         uint16_t extlen;
490
491         offset += 4;
492         if (len < offset)
493             return EINVAL;
494
495         memcpy (&extlen, buf + offset - 2, 2);
496         offset += htons (extlen); // skips RTP extension header
497     }
498
499     if (len < offset)
500         return EINVAL;
501
502     /* Determines RTP 48-bits counter and SSRC */
503     uint16_t seq = rtp_seq (buf);
504     uint32_t roc = srtp_compute_roc (s, seq), ssrc;
505     memcpy (&ssrc, buf + 8, 4);
506
507     /* Updates ROC and sequence (it's safe now) */
508     int16_t diff = seq - s->rtp_seq;
509     if (diff > 0)
510     {
511         /* Sequence in the future, good */
512         s->rtp.window = s->rtp.window << diff;
513         s->rtp.window |= 1;
514         s->rtp_seq = seq, s->rtp_roc = roc;
515     }
516     else
517     {
518         /* Sequence in the past/present, bad */
519         diff = -diff;
520         if ((diff >= 64) || ((s->rtp.window >> diff) & 1))
521             return EACCES; /* Replay attack */
522         s->rtp.window |= 1 << diff;
523     }
524
525     /* Encrypt/Decrypt */
526     if (s->flags & SRTP_UNENCRYPTED)
527         return 0;
528
529     if (rtp_crypt (s->rtp.cipher, ssrc, roc, seq, s->rtp.salt,
530                    buf + offset, len - offset))
531         return EINVAL;
532
533     return 0;
534 }
535
536
537 /**
538  * Turns a RTP packet into a SRTP packet: encrypt it, then computes
539  * the authentication tag and appends it.
540  * Note that you can encrypt packet in disorder.
541  *
542  * @param buf RTP packet to be encrypted/digested
543  * @param lenp pointer to the RTP packet length on entry,
544  *             set to the SRTP length on exit (undefined on non-ENOSPC error)
545  * @param bufsize size (bytes) of the packet buffer
546  *
547  * @return 0 on success, in case of error:
548  *  EINVAL  malformatted RTP packet or internal error
549  *  ENOSPC  bufsize is too small to add authentication tag
550  *          (<lenp> will hold the required byte size)
551  *  EACCES  packet would trigger a replay error on receiver
552  */
553 int
554 srtp_send (srtp_session_t *s, uint8_t *buf, size_t *lenp, size_t bufsize)
555 {
556     size_t len = *lenp;
557     int val = srtp_crypt (s, buf, len);
558     if (val)
559         return val;
560
561     if (!(s->flags & SRTP_UNAUTHENTICATED))
562     {
563         size_t tag_len = s->tag_len;
564         *lenp = len + tag_len;
565         if (bufsize < (len + tag_len))
566             return ENOSPC;
567
568         uint32_t roc = srtp_compute_roc (s, rtp_seq (buf));
569         const uint8_t *tag = rtp_digest (s, buf, len, roc);
570         if (rcc_mode (s))
571         {
572             assert (s->rtp_rcc);
573             if ((rtp_seq (buf) % s->rtp_rcc) == 0)
574             {
575                 memcpy (buf + len, &(uint32_t){ htonl (s->rtp_roc) }, 4);
576                 len += 4;
577                 if (rcc_mode (s) == 3)
578                     tag_len = 0;
579                 else
580                     tag_len -= 4;
581             }
582             else
583             {
584                 if (rcc_mode (s) & 1)
585                     tag_len = 0;
586             }
587         }
588         memcpy (buf + len, tag, tag_len);
589     }
590
591     return 0;
592 }
593
594
595 /**
596  * Turns a SRTP packet into a RTP packet: authenticates the packet,
597  * then decrypts it.
598  *
599  * @param buf RTP packet to be digested/decrypted
600  * @param lenp pointer to the SRTP packet length on entry,
601  *             set to the RTP length on exit (undefined in case of error)
602  *
603  * @return 0 on success, in case of error:
604  *  EINVAL  malformatted SRTP packet
605  *  EACCES  authentication failed (spoofed packet or out-of-sync)
606  */
607 int
608 srtp_recv (srtp_session_t *s, uint8_t *buf, size_t *lenp)
609 {
610     size_t len = *lenp;
611     if (len < 12u)
612         return EINVAL;
613
614     if (!(s->flags & SRTP_UNAUTHENTICATED))
615     {
616         size_t tag_len = s->tag_len, roc_len = 0;
617         if (rcc_mode (s))
618         {
619             if ((rtp_seq (buf) % s->rtp_rcc) == 0)
620             {
621                 roc_len = 4;
622                 if (rcc_mode (s) == 3)
623                     tag_len = 0;
624                 else
625                     tag_len -= 4;
626             }
627             else
628             {
629                 if (rcc_mode (s) & 1)
630                     tag_len = 0; // RCC mode 1 or 3: no auth
631             }
632         }
633
634         if (len < (12u + roc_len + tag_len))
635             return EINVAL;
636         len -= roc_len + tag_len;
637
638         uint32_t roc = srtp_compute_roc (s, rtp_seq (buf)), rcc;
639         if (roc_len)
640         {
641             assert (roc_len == 4);
642             memcpy (&rcc, buf + len, 4);
643             rcc = ntohl (rcc);
644         }
645         else
646             rcc = roc;
647
648         const uint8_t *tag = rtp_digest (s, buf, len, rcc);
649         if (memcmp (buf + len + roc_len, tag, s->tag_len))
650             return EACCES;
651
652         if (roc_len)
653         {
654             /* Authenticated packet carried a Roll-Over-Counter */
655             s->rtp_roc += rcc - roc;
656             assert (srtp_compute_roc (s, rtp_seq (buf)) == rcc);
657         }
658         *lenp = len;
659     }
660
661     return srtp_crypt (s, buf, len);
662 }
663
664
665 /** AES-CM for RTCP (salt = 14 bytes + 2 nul bytes) */
666 static int
667 rtcp_crypt (gcry_cipher_hd_t hd, uint32_t ssrc, uint32_t index,
668             const uint32_t *salt, uint8_t *data, size_t len)
669 {
670     return rtp_crypt (hd, ssrc, index >> 16, index & 0xffff, salt, data, len);
671 }
672
673
674 /** Message Authentication and Integrity for RTCP */
675 static const uint8_t *
676 rtcp_digest (gcry_md_hd_t md, const void *data, size_t len)
677 {
678     gcry_md_reset (md);
679     gcry_md_write (md, data, len);
680     return gcry_md_read (md, 0);
681 }
682
683
684 /**
685  * Encrypts/decrypts a RTCP packet and updates SRTCP context
686  * (CTR block cypher mode of operation has identical encryption and
687  * decryption function).
688  *
689  * @param buf RTCP packet to be en-/decrypted
690  * @param len RTCP packet length
691  *
692  * @return 0 on success, in case of error:
693  *  EINVAL  malformatted RTCP packet
694  */
695 static int srtcp_crypt (srtp_session_t *s, uint8_t *buf, size_t len)
696 {
697     assert (s != NULL);
698
699     /* 8-bytes unencrypted header, and 4-bytes unencrypted footer */
700     if ((len < 12) || ((buf[0] >> 6) != 2))
701         return EINVAL;
702
703     uint32_t index;
704     memcpy (&index, buf + len, 4);
705     index = ntohl (index);
706     if (((index >> 31) != 0) != ((s->flags & SRTCP_UNENCRYPTED) == 0))
707         return EINVAL; // E-bit mismatch
708
709     index &= ~(1 << 31); // clear E-bit for counter
710
711     /* Updates SRTCP index (safe here) */
712     int32_t diff = index - s->rtcp_index;
713     if (diff > 0)
714     {
715         /* Packet in the future, good */
716         s->rtcp.window = s->rtcp.window << diff;
717         s->rtcp.window |= 1;
718         s->rtcp_index = index;
719     }
720     else
721     {
722         /* Packet in the past/present, bad */
723         diff = -diff;
724         if ((diff >= 64) || ((s->rtcp.window >> diff) & 1))
725             return EACCES; // replay attack!
726         s->rtp.window |= 1 << diff;
727     }
728
729     /* Crypts SRTCP */
730     if (s->flags & SRTCP_UNENCRYPTED)
731         return 0;
732
733     uint32_t ssrc;
734     memcpy (&ssrc, buf + 4, 4);
735
736     if (rtcp_crypt (s->rtcp.cipher, ssrc, index, s->rtp.salt,
737                     buf + 8, len - 8))
738         return EINVAL;
739     return 0;
740 }
741
742
743 /**
744  * Turns a RTCP packet into a SRTCP packet: encrypt it, then computes
745  * the authentication tag and appends it.
746  *
747  * @param buf RTCP packet to be encrypted/digested
748  * @param lenp pointer to the RTCP packet length on entry,
749  *             set to the SRTCP length on exit (undefined in case of error)
750  * @param bufsize size (bytes) of the packet buffer
751  *
752  * @return 0 on success, in case of error:
753  *  EINVAL  malformatted RTCP packet or internal error
754  *  ENOSPC  bufsize is too small (to add index and authentication tag)
755  */
756 int
757 srtcp_send (srtp_session_t *s, uint8_t *buf, size_t *lenp, size_t bufsize)
758 {
759     size_t len = *lenp;
760     if (bufsize < (len + 4 + s->tag_len))
761         return ENOSPC;
762
763     uint32_t index = ++s->rtcp_index;
764     if (index >> 31)
765         s->rtcp_index = index = 0; /* 31-bit wrap */
766
767     if ((s->flags & SRTCP_UNENCRYPTED) == 0)
768         index |= 0x80000000; /* Set Encrypted bit */
769     memcpy (buf + len, &(uint32_t){ htonl (index) }, 4);
770
771     int val = srtcp_crypt (s, buf, len);
772     if (val)
773         return val;
774
775     len += 4; /* Digests SRTCP index too */
776
777     const uint8_t *tag = rtcp_digest (s->rtp.mac, buf, len);
778     memcpy (buf + len, tag, s->tag_len);
779     *lenp = len + s->tag_len;
780     return 0;
781 }
782
783
784 /**
785  * Turns a SRTCP packet into a RTCP packet: authenticates the packet,
786  * then decrypts it.
787  *
788  * @param buf RTCP packet to be digested/decrypted
789  * @param lenp pointer to the SRTCP packet length on entry,
790  *             set to the RTCP length on exit (undefined in case of error)
791  *
792  * @return 0 on success, in case of error:
793  *  EINVAL  malformatted SRTCP packet
794  *  EACCES  authentication failed (spoofed packet or out-of-sync)
795  */
796 int
797 srtcp_recv (srtp_session_t *s, uint8_t *buf, size_t *lenp)
798 {
799     size_t len = *lenp;
800
801     if (len < (4u + s->tag_len))
802         return EINVAL;
803     len -= s->tag_len;
804
805     const uint8_t *tag = rtcp_digest (s->rtp.mac, buf, len);
806     if (memcmp (buf + len, tag, s->tag_len))
807          return EACCES;
808
809     len -= 4; /* Remove SRTCP index before decryption */
810     *lenp = len;
811     return srtp_crypt (s, buf, len);
812 }
813