]> git.sesse.net Git - vlc/blob - libs/srtp/srtp.c
Partial Win32 compile fix
[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 /* TODO:
37  * Useful stuff:
38  * - ROC profil thingy (multicast really needs this)
39  * - replay protection
40  *
41  * Requirements for conformance:
42  * - suites with NULL cipher
43  * - SRTCP
44  *
45  * Useless stuff (because nothing depends on it):
46  * - non-nul key derivation rate
47  * - MKI payload
48  */
49
50 typedef struct srtp_proto_t
51 {
52     gcry_cipher_hd_t cipher;
53     gcry_md_hd_t     mac;
54     uint32_t         salt[4];
55     uint8_t          mac_len;
56 } srtp_proto_t;
57
58 struct srtp_session_t
59 {
60     srtp_proto_t rtp;
61     srtp_proto_t rtcp;
62     unsigned flags;
63     unsigned kdr;
64     uint32_t rtcp_index;
65     uint32_t rtp_roc;
66     uint16_t rtp_seq;
67 };
68
69 enum
70 {
71     SRTP_CRYPT,
72     SRTP_AUTH,
73     SRTP_SALT,
74     SRTCP_CRYPT,
75     SRTCP_AUTH,
76     SRTCP_SALT
77 };
78
79 #ifdef WIN32
80 # include <winsock2.h>
81 #else
82 # include <netinet/in.h>
83 # include <pthread.h>
84 GCRY_THREAD_OPTION_PTHREAD_IMPL;
85 #endif
86
87 static bool libgcrypt_usable = false;
88
89 static void initonce_libgcrypt (void)
90 {
91     if ((gcry_check_version ("1.1.94") == NULL)
92      || gcry_control (GCRYCTL_DISABLE_SECMEM, 0)
93      || gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0)
94 #ifndef WIN32
95      || gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread)
96 #endif
97        )
98         return;
99
100     libgcrypt_usable = true;
101 }
102
103 static int init_libgcrypt (void)
104 {
105     int retval;
106 #ifndef WIN32
107     static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
108     static pthread_once_t once = PTHREAD_ONCE_INIT;
109
110     pthread_mutex_lock (&mutex);
111     pthread_once (&once, initonce_libgcrypt);
112     retval = -libgcrypt_usable;
113     pthread_mutex_unlock (&mutex);
114 #else
115 # warning FIXME: This is not thread-safe.
116     if (!libgcrypt_usable)
117         initonce_libgcrypt ();
118     retval = -libgcrypt_usable;
119 #endif
120
121     return retval;
122
123 }
124
125
126 static void proto_destroy (srtp_proto_t *p)
127 {
128     gcry_md_close (p->mac);
129     gcry_cipher_close (p->cipher);
130 }
131
132
133 /**
134  * Releases all resources associated with a Secure RTP session.
135  */
136 void srtp_destroy (srtp_session_t *s)
137 {
138     assert (s != NULL);
139
140     proto_destroy (&s->rtcp);
141     proto_destroy (&s->rtp);
142     free (s);
143 }
144
145
146 static int proto_create (srtp_proto_t *p, int gcipher, int gmd)
147 {
148     if (gcry_cipher_open (&p->cipher, gcipher, GCRY_CIPHER_MODE_CTR, 0) == 0)
149     {
150         if (gcry_md_open (&p->mac, gmd, GCRY_MD_FLAG_HMAC) == 0)
151             return 0;
152         gcry_cipher_close (p->cipher);
153     }
154     return -1;
155 }
156
157
158 /**
159  * Allocates a Secure RTP session.
160  *
161  * @param name cipher-suite name
162  * @param kdr key derivation rate
163  * @param winsize anti-replay windows size (between 64 and 32767 inclusive)
164  *                0 disable replay attack protection (OK for send only)
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, uint16_t winsize)
171 {
172     assert (name != NULL);
173
174     if (kdr != 0)
175         return NULL; // FIXME: KDR not implemented yet
176     if (winsize != 0)
177         return NULL; // FIXME: replay protection not implemented yet
178
179     uint8_t mac_len;
180     int cipher = GCRY_CIPHER_AES, md = GCRY_MD_SHA1;
181
182     if (strcmp (name, "AES_CM_128_HMAC_SHA1_80") == 0)
183         mac_len = 80;
184     else
185     if (strcmp (name, "AES_CM_128_HMAC_SHA1_32") == 0)
186         mac_len = 32;
187     else
188     // F8_128_HMAC_SHA1_80 is not implemented
189         return NULL;
190
191     if ((flags & ~SRTP_FLAGS_MASK) || (winsize > 32767) || init_libgcrypt ())
192         return NULL;
193
194     srtp_session_t *s = malloc (sizeof (*s));
195     if (s == NULL)
196         return NULL;
197
198     memset (s, 0, sizeof (*s));
199     s->flags = flags;
200     s->kdr = kdr;
201
202     if (proto_create (&s->rtp, cipher, md) == 0)
203     {
204         if (proto_create (&s->rtcp, cipher, md) == 0)
205             return s;
206         proto_destroy (&s->rtp);
207     }
208
209     free (s);
210     return NULL;
211 }
212
213
214 /**
215  * AES-CM key derivation (saltlen = 14 bytes)
216  */
217 static int
218 derive (gcry_cipher_hd_t prf, const void *salt,
219         const uint8_t *r, size_t rlen, uint8_t label,
220         void *out, size_t outlen)
221 {
222     uint8_t iv[16];
223
224     memcpy (iv, salt, 14);
225     iv[14] = iv[15] = 0;
226
227     assert (rlen < 14);
228     iv[13 - rlen] ^= label;
229     for (size_t i = 0; i < rlen; i++)
230         iv[sizeof (iv) - rlen + i] ^= r[i];
231
232     /* TODO: retry with CTR mode */
233     while (outlen >= sizeof (iv))
234     {
235         /* AES */
236         if (gcry_cipher_encrypt (prf, out, sizeof (iv), iv, sizeof (iv)))
237             return EINVAL;
238         outlen -= sizeof (iv);
239         out = ((uint8_t *)out) + sizeof (iv);
240
241         /* Increment IV in network byte order */
242         if (++iv[sizeof (iv) - 1] == 0)
243             ++iv[sizeof (iv) -2];
244     }
245
246     if (outlen > 0)
247     {
248         /* Truncated last AES output block */
249         if (gcry_cipher_encrypt (prf, iv, sizeof (iv), NULL, 0))
250             return -1;
251         memcpy (out, iv, outlen);
252     }
253
254     return 0;
255 }
256
257
258 static int
259 proto_derive (srtp_proto_t *p, gcry_cipher_hd_t prf,
260               const void *salt, size_t saltlen,
261               const uint8_t *r, size_t rlen, bool rtcp)
262 {
263     if (saltlen != 14)
264         return -1;
265
266     uint8_t cipherkey[16];
267     uint8_t label = rtcp ? SRTCP_CRYPT : SRTP_CRYPT;
268
269     if (derive (prf, salt, r, rlen, label++, cipherkey, 16)
270      || gcry_cipher_setkey (p->cipher, cipherkey, 16)
271      || derive (prf, salt, r, rlen, label++, NULL, 0) /* FIXME HMAC */
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 /**
324  * Sets (or resets) the master key and master salt for a SRTP session.
325  * This must be done at least once before using rtp_send(), rtp_recv(),
326  * rtcp_send() or rtcp_recv(). Also, rekeying is required every
327  * 2^48 RTP packets or 2^31 RTCP packets (whichever comes first),
328  * otherwise the protocol security might be broken.
329  *
330  * @return 0 on success, in case of error:
331  *  EINVAL  invalid or unsupported key/salt sizes combination
332  */
333 int
334 srtp_setkey (srtp_session_t *s, const void *key, size_t keylen,
335              const void *salt, size_t saltlen)
336 {
337     return srtp_derive (s, key, keylen, salt, saltlen) ? EINVAL : 0;
338 }
339
340
341 /** AES-CM encryption/decryption (ctr length = 16 bytes) */
342 static int
343 encrypt (gcry_cipher_hd_t hd, uint32_t *ctr, uint8_t *data, size_t len)
344 {
345     const size_t ctrlen = 16;
346     while (len >= ctrlen)
347     {
348         if (gcry_cipher_setctr (hd, ctr, ctrlen)
349          || gcry_cipher_encrypt (hd, data, ctrlen, NULL, 0))
350             return -1;
351
352         data += ctrlen;
353         len -= ctrlen;
354         ctr[3] = htonl (ntohl (ctr[3]) + 1);
355     }
356
357     if (len > 0)
358     {
359         /* Truncated last block */
360         uint8_t dummy[ctrlen];
361         memcpy (dummy, data, len);
362         memset (dummy + len, 0, ctrlen - len);
363
364         if (gcry_cipher_setctr (hd, ctr, ctrlen)
365          || gcry_cipher_encrypt (hd, dummy, ctrlen, data, ctrlen))
366             return -1;
367         memcpy (data, dummy, len);
368     }
369
370     return 0;
371 }
372
373
374 /** AES-CM for RTP (salt = 14 bytes + 2 nul bytes) */
375 static inline int
376 rtp_encrypt (gcry_cipher_hd_t hd, uint32_t ssrc, uint32_t roc, uint16_t seq,
377              const uint32_t *salt, uint8_t *data, size_t len)
378 {
379     /* Determines cryptographic counter (IV) */
380     uint32_t counter[4];
381     counter[0] = salt[0];
382     counter[1] = salt[1] ^ ssrc;
383     counter[2] = salt[2] ^ htonl (roc);
384     counter[3] = salt[3] ^ htonl (seq << 16);
385
386     /* Encryption */
387     return encrypt (hd, counter, data, len);
388 }
389
390
391 /**
392  * Encrypts/decrypts a RTP packet and updates SRTP context
393  * (CTR block cypher mode of operation has identical encryption and
394  * decryption function).
395  *
396  * @param buf RTP packet to be encrypted/digested
397  * @param len RTP packet length
398  *
399  * @return 0 on success, in case of error:
400  *  EINVAL  malformatted RTP packet
401  */
402 static int srtp_encrypt (srtp_session_t *s, uint8_t *buf, size_t len)
403 {
404     assert (s != NULL);
405
406     if ((len < 12) || ((buf[0] >> 6) != 2))
407         return EINVAL;
408
409     /* Computes encryption offset */
410     uint16_t offset = 12;
411     offset += (buf[0] & 0xf) * 4; // skips CSRC
412
413     if (buf[0] & 0x10)
414     {
415         uint16_t extlen;
416
417         offset += 4;
418         if (len < offset)
419             return EINVAL;
420
421         memcpy (&extlen, buf + offset - 2, 2);
422         offset += htons (extlen);
423     }
424
425     if (len < offset)
426         return EINVAL;
427
428     /* Determines RTP 48-bits counter and SSRC */
429     uint32_t ssrc;
430     memcpy (&ssrc, buf + 8, 4);
431
432     uint16_t seq = (buf[2] << 8) | buf[3];
433     if (((seq - s->rtp_seq) & 0xffff) < 32768)
434     {
435         if (seq < s->rtp_seq)
436             s->rtp_roc++; /* Sequence number wrap */
437     }
438     else
439     {
440         if (seq > s->rtp_seq)
441             s->rtp_roc--;
442     }
443
444     s->rtp_seq = seq;
445
446     if (s->flags & SRTP_UNENCRYPTED)
447         return 0;
448
449     if (rtp_encrypt (s->rtp.cipher, ssrc, s->rtp_roc, seq, s->rtp.salt,
450                      buf + offset, len - offset))
451         return EINVAL;
452
453     return 0;
454 }
455
456
457 /**
458  * Turns a RTP packet into a SRTP packet: encrypt it, then computes
459  * the authentication tag and appends it.
460  * Note that you can encrypt packet in disorder.
461  *
462  * @param buf RTP packet to be encrypted/digested
463  * @param lenp pointer to the RTP packet length on entry,
464  *             set to the SRTP length on exit (undefined in case of error)
465  * @param bufsize size (bytes) of the packet buffer
466  *
467  * @return 0 on success, in case of error:
468  *  EINVAL  malformatted RTP packet
469  *  ENOSPC  bufsize is too small (to add authentication tag)
470  */
471 int
472 srtp_send (srtp_session_t *s, uint8_t *buf, size_t *lenp, size_t bufsize)
473 {
474     size_t len = *lenp;
475     int val = srtp_encrypt (s, buf, len);
476     if (val)
477         return val;
478
479     if (bufsize < (len + s->rtp.mac_len))
480         return ENOSPC;
481
482     /* FIXME: HMAC and anti-replay */
483     return 0;
484 }
485
486
487 /**
488  * Turns a RTP packet into a SRTP packet: encrypt it, then computes
489  * the authentication tag and appends it.
490  * Note that you can encrypt packet in disorder.
491  *
492  * @param buf RTP packet to be decrypted/digested
493  * @param lenp pointer to the RTP packet length on entry,
494  *             set to the SRTP length on exit (undefined in case of error)
495  *
496  * @return 0 on success, in case of error:
497  *  EINVAL  malformatted RTP packet
498  *  EACCES  authentication failed (spoofed packet or out-of-sync)
499  */
500 int
501 srtp_recv (srtp_session_t *s, uint8_t *buf, size_t *lenp)
502 {
503     size_t len = *lenp;
504     int val = srtp_encrypt (s, buf, len);
505     if (val)
506         return val;
507
508     /* FIXME: HMAC and anti-replay */
509     return 0;
510 }
511