]> git.sesse.net Git - vlc/blob - libs/srtp/srtp.c
bbe1b404ef5592cecb18e811e156ae28e6a6099b
[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 #include <netinet/in.h>
37 #include <pthread.h>
38
39 /* TODO:
40  * Useful stuff:
41  * - ROC profil thingy (multicast really needs this)
42  * - replay protection
43  *
44  * Requirements for conformance:
45  * - suites with NULL cipher
46  * - SRTCP
47  *
48  * Useless stuff (because nothing depends on it):
49  * - non-nul key derivation rate
50  * - MKI payload
51  */
52
53 typedef struct srtp_proto_t
54 {
55     gcry_cipher_hd_t cipher;
56     gcry_md_hd_t     mac;
57     uint32_t         salt[4];
58     uint8_t          mac_len;
59 } srtp_proto_t;
60
61 struct srtp_session_t
62 {
63     srtp_proto_t rtp;
64     srtp_proto_t rtcp;
65     unsigned flags;
66     unsigned kdr;
67     uint32_t rtcp_index;
68     uint32_t rtp_roc;
69     uint16_t rtp_seq;
70 };
71
72 enum
73 {
74     SRTP_CRYPT,
75     SRTP_AUTH,
76     SRTP_SALT,
77     SRTCP_CRYPT,
78     SRTCP_AUTH,
79     SRTCP_SALT
80 };
81
82 #ifndef WIN32
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 session.
159  *
160  * @param name cipher-suite name
161  * @param kdr key derivation rate
162  * @param winsize anti-replay windows size (between 64 and 32767 inclusive)
163  *                0 disable replay attack protection (OK for send only)
164  * @param flags OR'ed optional flags.
165  *
166  * @return NULL in case of error
167  */
168 srtp_session_t *
169 srtp_create (const char *name, unsigned flags, unsigned kdr, uint16_t winsize)
170 {
171     assert (name != NULL);
172
173     if (kdr != 0)
174         return NULL; // FIXME: KDR not implemented yet
175     if (winsize != 0)
176         return NULL; // FIXME: replay protection not implemented yet
177
178     uint8_t mac_len;
179     int cipher = GCRY_CIPHER_AES, md = GCRY_MD_SHA1;
180
181     if (strcmp (name, "AES_CM_128_HMAC_SHA1_80") == 0)
182         mac_len = 80;
183     else
184     if (strcmp (name, "AES_CM_128_HMAC_SHA1_32") == 0)
185         mac_len = 32;
186     else
187     // F8_128_HMAC_SHA1_80 is not implemented
188         return NULL;
189
190     if ((flags & ~SRTP_FLAGS_MASK) || (winsize > 32767) || init_libgcrypt ())
191         return NULL;
192
193     srtp_session_t *s = malloc (sizeof (*s));
194     if (s == NULL)
195         return NULL;
196
197     memset (s, 0, sizeof (*s));
198     s->flags = flags;
199     s->kdr = kdr;
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 cipherkey[16];
266     uint8_t label = rtcp ? SRTCP_CRYPT : SRTP_CRYPT;
267
268     if (derive (prf, salt, r, rlen, label++, cipherkey, 16)
269      || gcry_cipher_setkey (p->cipher, cipherkey, 16)
270      || derive (prf, salt, r, rlen, label++, NULL, 0) /* FIXME HMAC */
271      || derive (prf, salt, r, rlen, label++, p->salt, 14))
272         return -1;
273
274     return 0;
275 }
276
277
278 /**
279  * SRTP/SRTCP cipher/salt/MAC keys derivation.
280  */
281 static int
282 srtp_derive (srtp_session_t *s, const void *key, size_t keylen,
283              const void *salt, size_t saltlen)
284 {
285     gcry_cipher_hd_t prf;
286     uint8_t r[6];
287
288     /* TODO: retry with CTR mode */
289     if (gcry_cipher_open (&prf, GCRY_CIPHER_AES, GCRY_CIPHER_MODE_ECB, 0)
290      || gcry_cipher_setkey (prf, key, keylen))
291         return -1;
292
293     /* RTP key derivation */
294     if (s->kdr != 0)
295     {
296         uint64_t index = (((uint64_t)s->rtp_roc) << 16) | s->rtp_seq;
297         index /= s->kdr;
298
299         for (int i = sizeof (r) - 1; i >= 0; i--)
300         {
301             r[i] = index & 0xff;
302             index = index >> 8;
303         }
304     }
305     else
306         memset (r, 0, sizeof (r));
307
308     if (proto_derive (&s->rtp, prf, salt, saltlen, r, 6, false))
309         return -1;
310
311     /* RTCP key derivation */
312     memcpy (r, &(uint32_t){ htonl (s->rtcp_index) }, 4);
313     if (proto_derive (&s->rtcp, prf, salt, saltlen, r, 4, true))
314         return -1;
315
316     (void)gcry_cipher_close (prf);
317     return 0;
318 }
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 encrypt (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 inline int
375 rtp_encrypt (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 encrypt (hd, counter, data, len);
387 }
388
389
390 /**
391  * Encrypts/decrypts a RTP packet and updates SRTP context
392  * (CTR block cypher mode of operation has identical encryption and
393  * decryption function).
394  *
395  * @param buf RTP packet to be encrypted/digested
396  * @param len RTP packet length
397  *
398  * @return 0 on success, in case of error:
399  *  EINVAL  malformatted RTP packet
400  */
401 static int srtp_encrypt (srtp_session_t *s, uint8_t *buf, size_t len)
402 {
403     assert (s != NULL);
404
405     if ((len < 12) || ((buf[0] >> 6) != 2))
406         return EINVAL;
407
408     /* Computes encryption offset */
409     uint16_t offset = 12;
410     offset += (buf[0] & 0xf) * 4; // skips CSRC
411
412     if (buf[0] & 0x10)
413     {
414         uint16_t extlen;
415
416         offset += 4;
417         if (len < offset)
418             return EINVAL;
419
420         memcpy (&extlen, buf + offset - 2, 2);
421         offset += htons (extlen);
422     }
423
424     if (len < offset)
425         return EINVAL;
426
427     /* Determines RTP 48-bits counter and SSRC */
428     uint32_t ssrc;
429     memcpy (&ssrc, buf + 8, 4);
430
431     uint16_t seq = (buf[2] << 8) | buf[3];
432     if (((seq - s->rtp_seq) & 0xffff) < 32768)
433     {
434         if (seq < s->rtp_seq)
435             s->rtp_roc++; /* Sequence number wrap */
436     }
437     else
438     {
439         if (seq > s->rtp_seq)
440             s->rtp_roc--;
441     }
442
443     s->rtp_seq = seq;
444
445     if (s->flags & SRTP_UNENCRYPTED)
446         return 0;
447
448     if (rtp_encrypt (s->rtp.cipher, ssrc, s->rtp_roc, seq, s->rtp.salt,
449                      buf + offset, len - offset))
450         return EINVAL;
451
452     return 0;
453 }
454
455
456 /**
457  * Turns a RTP packet into a SRTP packet: encrypt it, then computes
458  * the authentication tag and appends it.
459  * Note that you can encrypt packet in disorder.
460  *
461  * @param buf RTP packet to be encrypted/digested
462  * @param lenp pointer to the RTP packet length on entry,
463  *             set to the SRTP length on exit (undefined in case of error)
464  * @param bufsize size (bytes) of the packet buffer
465  *
466  * @return 0 on success, in case of error:
467  *  EINVAL  malformatted RTP packet
468  *  ENOBUFS bufsize is too small
469  */
470 int
471 srtp_send (srtp_session_t *s, uint8_t *buf, size_t *lenp, size_t bufsize)
472 {
473     size_t len = *lenp;
474     int val = srtp_encrypt (s, buf, len);
475     if (val)
476         return val;
477
478     if (bufsize < (len + s->rtp.mac_len))
479         return ENOBUFS;
480
481     /* FIXME: HMAC and anti-replay */
482     return 0;
483 }
484
485
486 /**
487  * Turns a RTP packet into a SRTP packet: encrypt it, then computes
488  * the authentication tag and appends it.
489  * Note that you can encrypt packet in disorder.
490  *
491  * @param buf RTP packet to be decrypted/digested
492  * @param lenp pointer to the RTP packet length on entry,
493  *             set to the SRTP length on exit (undefined in case of error)
494  *
495  * @return 0 on success, in case of error:
496  *  EINVAL  malformatted RTP packet
497  *  EACCES  authentication failed (spoofed packet or out-of-sync)
498  */
499 int
500 srtp_recv (srtp_session_t *s, uint8_t *buf, size_t *lenp)
501 {
502     size_t len = *lenp;
503     int val = srtp_encrypt (s, buf, len);
504     if (val)
505         return val;
506
507     /* FIXME: HMAC and anti-replay */
508     return 0;
509 }
510