]> git.sesse.net Git - vlc/blob - libs/srtp/srtp.c
e6d09c97325949e082da2d00574bb68b4b9aa40b
[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
376 /**
377  * Sets Roll-over-Counter Carry (RCC) rate for the SRTP session. If not
378  * specified (through this function), the default rate of ONE is assumed
379  * (i.e. every RTP packets will carry the RoC). RCC rate is ignored if none
380  * of the RCC mode has been selected.
381  *
382  * The RCC mode is selected through one of these flags for srtp_create():
383  *  SRTP_RCC_MODE1: integrity protection only for RoC carrying packets
384  *  SRTP_RCC_MODE2: integrity protection for all packets
385  *  SRTP_RCC_MODE3: no integrity protection
386  *
387  * RCC mode 3 is insecure. Compared to plain RTP, it provides confidentiality
388  * (through encryption) but is much more prone to DoS. It can only be used if
389  * anti-spoofing protection is provided by lower network layers (e.g. IPsec,
390  * or trusted routers and proper source address filtering).
391  *
392  * If RCC rate is 1, RCC mode 1 and 2 are functionally identical.
393  *
394  * @param rate RoC Carry rate (MUST NOT be zero)
395  */
396 void srtp_setrcc_rate (srtp_session_t *s, uint16_t rate)
397 {
398     assert (rate != 0);
399     s->rtp_rcc = rate;
400 }
401
402
403 /** AES-CM for RTP (salt = 14 bytes + 2 nul bytes) */
404 static int
405 rtp_crypt (gcry_cipher_hd_t hd, uint32_t ssrc, uint32_t roc, uint16_t seq,
406            const uint32_t *salt, uint8_t *data, size_t len)
407 {
408     /* Determines cryptographic counter (IV) */
409     uint32_t counter[4];
410     counter[0] = salt[0];
411     counter[1] = salt[1] ^ ssrc;
412     counter[2] = salt[2] ^ htonl (roc);
413     counter[3] = salt[3] ^ htonl (seq << 16);
414
415     /* Encryption */
416     return ctr_crypt (hd, counter, data, len);
417 }
418
419
420 /** Determines SRTP Roll-Over-Counter (in host-byte order) */
421 static uint32_t
422 srtp_compute_roc (const srtp_session_t *s, uint16_t seq)
423 {
424     uint32_t roc = s->rtp_roc;
425
426     if (((seq - s->rtp_seq) & 0xffff) < 0x8000)
427     {
428         /* Sequence is ahead, good */
429         if (seq < s->rtp_seq)
430             roc++; /* Sequence number wrap */
431     }
432     else
433     {
434         /* Sequence is late, bad */
435         if (seq > s->rtp_seq)
436             roc--; /* Wrap back */
437     }
438     return roc;
439 }
440
441
442 /** Returns RTP sequence (in host-byte order) */
443 static inline uint16_t rtp_seq (const uint8_t *buf)
444 {
445     return (buf[2] << 8) | buf[3];
446 }
447
448
449 /** Message Authentication and Integrity for RTP */
450 static const uint8_t *
451 rtp_digest (srtp_session_t *s, const uint8_t *data, size_t len,
452             uint32_t roc)
453 {
454     const gcry_md_hd_t md = s->rtp.mac;
455
456     gcry_md_reset (md);
457     gcry_md_write (md, data, len);
458     gcry_md_write (md, &(uint32_t){ htonl (roc) }, 4);
459     return gcry_md_read (md, 0);
460 }
461
462
463 /**
464  * Encrypts/decrypts a RTP packet and updates SRTP context
465  * (CTR block cypher mode of operation has identical encryption and
466  * decryption function).
467  *
468  * @param buf RTP packet to be en-/decrypted
469  * @param len RTP packet length
470  *
471  * @return 0 on success, in case of error:
472  *  EINVAL  malformatted RTP packet
473  *  EACCES  replayed packet or out-of-window or sync lost
474  */
475 static int srtp_crypt (srtp_session_t *s, uint8_t *buf, size_t len)
476 {
477     assert (s != NULL);
478
479     if ((len < 12) || ((buf[0] >> 6) != 2))
480         return EINVAL;
481
482     /* Computes encryption offset */
483     uint16_t offset = 12;
484     offset += (buf[0] & 0xf) * 4; // skips CSRC
485
486     if (buf[0] & 0x10)
487     {
488         uint16_t extlen;
489
490         offset += 4;
491         if (len < offset)
492             return EINVAL;
493
494         memcpy (&extlen, buf + offset - 2, 2);
495         offset += htons (extlen); // skips RTP extension header
496     }
497
498     if (len < offset)
499         return EINVAL;
500
501     /* Determines RTP 48-bits counter and SSRC */
502     uint16_t seq = rtp_seq (buf);
503     uint32_t roc = srtp_compute_roc (s, seq), ssrc;
504     memcpy (&ssrc, buf + 8, 4);
505
506     /* Updates ROC and sequence (it's safe now) */
507     int16_t diff = seq - s->rtp_seq;
508     if (diff > 0)
509     {
510         /* Sequence in the future, good */
511         s->rtp.window = s->rtp.window << diff;
512         s->rtp.window |= 1;
513         s->rtp_seq = seq, s->rtp_roc = roc;
514     }
515     else
516     {
517         /* Sequence in the past/present, bad */
518         diff = -diff;
519         if ((diff >= 64) || ((s->rtp.window >> diff) & 1))
520             return EACCES; /* Replay attack */
521         s->rtp.window |= 1 << diff;
522     }
523
524     /* Encrypt/Decrypt */
525     if (s->flags & SRTP_UNENCRYPTED)
526         return 0;
527
528     if (rtp_crypt (s->rtp.cipher, ssrc, roc, seq, s->rtp.salt,
529                    buf + offset, len - offset))
530         return EINVAL;
531
532     return 0;
533 }
534
535
536 /**
537  * Turns a RTP packet into a SRTP packet: encrypt it, then computes
538  * the authentication tag and appends it.
539  * Note that you can encrypt packet in disorder.
540  *
541  * @param buf RTP packet to be encrypted/digested
542  * @param lenp pointer to the RTP packet length on entry,
543  *             set to the SRTP length on exit (undefined on non-ENOSPC error)
544  * @param bufsize size (bytes) of the packet buffer
545  *
546  * @return 0 on success, in case of error:
547  *  EINVAL  malformatted RTP packet or internal error
548  *  ENOSPC  bufsize is too small to add authentication tag
549  *          (<lenp> will hold the required byte size)
550  *  EACCES  packet would trigger a replay error on receiver
551  */
552 int
553 srtp_send (srtp_session_t *s, uint8_t *buf, size_t *lenp, size_t bufsize)
554 {
555     size_t len = *lenp;
556     int val = srtp_crypt (s, buf, len);
557     if (val)
558         return val;
559
560     if (!(s->flags & SRTP_UNAUTHENTICATED))
561     {
562         size_t tag_len = s->tag_len;
563         *lenp = len + tag_len;
564         if (bufsize < (len + tag_len))
565             return ENOSPC;
566
567         uint32_t roc = srtp_compute_roc (s, rtp_seq (buf));
568         const uint8_t *tag = rtp_digest (s, buf, len, roc);
569         if (rcc_mode (s))
570         {
571             assert (s->rtp_rcc);
572             if ((rtp_seq (buf) % s->rtp_rcc) == 0)
573             {
574                 memcpy (buf + len, &(uint32_t){ htonl (s->rtp_roc) }, 4);
575                 len += 4;
576                 if (rcc_mode (s) == 3)
577                     tag_len = 0;
578                 else
579                     tag_len -= 4;
580             }
581             else
582             {
583                 if (rcc_mode (s) & 1)
584                     tag_len = 0;
585             }
586         }
587         memcpy (buf + len, tag, tag_len);
588     }
589
590     return 0;
591 }
592
593
594 /**
595  * Turns a SRTP packet into a RTP packet: authenticates the packet,
596  * then decrypts it.
597  *
598  * @param buf RTP packet to be digested/decrypted
599  * @param lenp pointer to the SRTP packet length on entry,
600  *             set to the RTP length on exit (undefined in case of error)
601  *
602  * @return 0 on success, in case of error:
603  *  EINVAL  malformatted SRTP packet
604  *  EACCES  authentication failed (spoofed packet or out-of-sync)
605  */
606 int
607 srtp_recv (srtp_session_t *s, uint8_t *buf, size_t *lenp)
608 {
609     size_t len = *lenp;
610     if (len < 12u)
611         return EINVAL;
612
613     if (!(s->flags & SRTP_UNAUTHENTICATED))
614     {
615         size_t tag_len = s->tag_len, roc_len = 0;
616         if (rcc_mode (s))
617         {
618             if ((rtp_seq (buf) % s->rtp_rcc) == 0)
619             {
620                 roc_len = 4;
621                 if (rcc_mode (s) == 3)
622                     tag_len = 0;
623                 else
624                     tag_len -= 4;
625             }
626             else
627             {
628                 if (rcc_mode (s) & 1)
629                     tag_len = 0; // RCC mode 1 or 3: no auth
630             }
631         }
632
633         if (len < (12u + roc_len + tag_len))
634             return EINVAL;
635         len -= roc_len + tag_len;
636
637         uint32_t roc = srtp_compute_roc (s, rtp_seq (buf)), rcc;
638         if (roc_len)
639         {
640             assert (roc_len == 4);
641             memcpy (&rcc, buf + len, 4);
642             rcc = ntohl (rcc);
643         }
644         else
645             rcc = roc;
646
647         const uint8_t *tag = rtp_digest (s, buf, len, rcc);
648 #if 0
649         printf ("Computed: 0x");
650         for (unsigned i = 0; i < tag_len; i++)
651             printf ("%02x", tag[i]);
652         printf ("\nReceived: 0x");
653         for (unsigned i = 0; i < tag_len; i++)
654             printf ("%02x", buf[len + roc_len + i]);
655         puts ("");
656 #endif
657         if (memcmp (buf + len + roc_len, tag, tag_len))
658             return EACCES;
659
660         if (roc_len)
661         {
662             /* Authenticated packet carried a Roll-Over-Counter */
663             s->rtp_roc += rcc - roc;
664             assert (srtp_compute_roc (s, rtp_seq (buf)) == rcc);
665         }
666         *lenp = len;
667     }
668
669     return srtp_crypt (s, buf, len);
670 }
671
672
673 /** AES-CM for RTCP (salt = 14 bytes + 2 nul bytes) */
674 static int
675 rtcp_crypt (gcry_cipher_hd_t hd, uint32_t ssrc, uint32_t index,
676             const uint32_t *salt, uint8_t *data, size_t len)
677 {
678     return rtp_crypt (hd, ssrc, index >> 16, index & 0xffff, salt, data, len);
679 }
680
681
682 /** Message Authentication and Integrity for RTCP */
683 static const uint8_t *
684 rtcp_digest (gcry_md_hd_t md, const void *data, size_t len)
685 {
686     gcry_md_reset (md);
687     gcry_md_write (md, data, len);
688     return gcry_md_read (md, 0);
689 }
690
691
692 /**
693  * Encrypts/decrypts a RTCP packet and updates SRTCP context
694  * (CTR block cypher mode of operation has identical encryption and
695  * decryption function).
696  *
697  * @param buf RTCP packet to be en-/decrypted
698  * @param len RTCP packet length
699  *
700  * @return 0 on success, in case of error:
701  *  EINVAL  malformatted RTCP packet
702  */
703 static int srtcp_crypt (srtp_session_t *s, uint8_t *buf, size_t len)
704 {
705     assert (s != NULL);
706
707     /* 8-bytes unencrypted header, and 4-bytes unencrypted footer */
708     if ((len < 12) || ((buf[0] >> 6) != 2))
709         return EINVAL;
710
711     uint32_t index;
712     memcpy (&index, buf + len, 4);
713     index = ntohl (index);
714     if (((index >> 31) != 0) != ((s->flags & SRTCP_UNENCRYPTED) == 0))
715         return EINVAL; // E-bit mismatch
716
717     index &= ~(1 << 31); // clear E-bit for counter
718
719     /* Updates SRTCP index (safe here) */
720     int32_t diff = index - s->rtcp_index;
721     if (diff > 0)
722     {
723         /* Packet in the future, good */
724         s->rtcp.window = s->rtcp.window << diff;
725         s->rtcp.window |= 1;
726         s->rtcp_index = index;
727     }
728     else
729     {
730         /* Packet in the past/present, bad */
731         diff = -diff;
732         if ((diff >= 64) || ((s->rtcp.window >> diff) & 1))
733             return EACCES; // replay attack!
734         s->rtp.window |= 1 << diff;
735     }
736
737     /* Crypts SRTCP */
738     if (s->flags & SRTCP_UNENCRYPTED)
739         return 0;
740
741     uint32_t ssrc;
742     memcpy (&ssrc, buf + 4, 4);
743
744     if (rtcp_crypt (s->rtcp.cipher, ssrc, index, s->rtp.salt,
745                     buf + 8, len - 8))
746         return EINVAL;
747     return 0;
748 }
749
750
751 /**
752  * Turns a RTCP packet into a SRTCP packet: encrypt it, then computes
753  * the authentication tag and appends it.
754  *
755  * @param buf RTCP packet to be encrypted/digested
756  * @param lenp pointer to the RTCP packet length on entry,
757  *             set to the SRTCP length on exit (undefined in case of error)
758  * @param bufsize size (bytes) of the packet buffer
759  *
760  * @return 0 on success, in case of error:
761  *  EINVAL  malformatted RTCP packet or internal error
762  *  ENOSPC  bufsize is too small (to add index and authentication tag)
763  */
764 int
765 srtcp_send (srtp_session_t *s, uint8_t *buf, size_t *lenp, size_t bufsize)
766 {
767     size_t len = *lenp;
768     if (bufsize < (len + 4 + s->tag_len))
769         return ENOSPC;
770
771     uint32_t index = ++s->rtcp_index;
772     if (index >> 31)
773         s->rtcp_index = index = 0; /* 31-bit wrap */
774
775     if ((s->flags & SRTCP_UNENCRYPTED) == 0)
776         index |= 0x80000000; /* Set Encrypted bit */
777     memcpy (buf + len, &(uint32_t){ htonl (index) }, 4);
778
779     int val = srtcp_crypt (s, buf, len);
780     if (val)
781         return val;
782
783     len += 4; /* Digests SRTCP index too */
784
785     const uint8_t *tag = rtcp_digest (s->rtp.mac, buf, len);
786     memcpy (buf + len, tag, s->tag_len);
787     *lenp = len + s->tag_len;
788     return 0;
789 }
790
791
792 /**
793  * Turns a SRTCP packet into a RTCP packet: authenticates the packet,
794  * then decrypts it.
795  *
796  * @param buf RTCP packet to be digested/decrypted
797  * @param lenp pointer to the SRTCP packet length on entry,
798  *             set to the RTCP length on exit (undefined in case of error)
799  *
800  * @return 0 on success, in case of error:
801  *  EINVAL  malformatted SRTCP packet
802  *  EACCES  authentication failed (spoofed packet or out-of-sync)
803  */
804 int
805 srtcp_recv (srtp_session_t *s, uint8_t *buf, size_t *lenp)
806 {
807     size_t len = *lenp;
808
809     if (len < (4u + s->tag_len))
810         return EINVAL;
811     len -= s->tag_len;
812
813     const uint8_t *tag = rtcp_digest (s->rtp.mac, buf, len);
814     if (memcmp (buf + len, tag, s->tag_len))
815          return EACCES;
816
817     len -= 4; /* Remove SRTCP index before decryption */
818     *lenp = len;
819     return srtp_crypt (s, buf, len);
820 }
821