FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
crypto.c
Go to the documentation of this file.
1 /*
2  * Decryption protocol handler
3  * Copyright (c) 2011 Martin Storsjo
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21 
22 #include "avformat.h"
23 #include "libavutil/aes.h"
24 #include "libavutil/avstring.h"
25 #include "libavutil/opt.h"
26 #include "internal.h"
27 #include "url.h"
28 
29 // encourage reads of 4096 bytes - 1 block is always retained.
30 #define MAX_BUFFER_BLOCKS 257
31 #define BLOCKSIZE 16
32 
33 typedef struct CryptoContext {
34  const AVClass *class;
40  int64_t position; // position in file - used in seek
41  int flags;
42  int eof;
44  int keylen;
46  int ivlen;
55  struct AVAES *aes_decrypt;
56  struct AVAES *aes_encrypt;
57 
59  int pad_len;
60 
62 
63 #define OFFSET(x) offsetof(CryptoContext, x)
64 #define D AV_OPT_FLAG_DECODING_PARAM
65 #define E AV_OPT_FLAG_ENCODING_PARAM
66 static const AVOption options[] = {
67  {"key", "AES encryption/decryption key", OFFSET(key), AV_OPT_TYPE_BINARY, .flags = D|E },
68  {"iv", "AES encryption/decryption initialization vector", OFFSET(iv), AV_OPT_TYPE_BINARY, .flags = D|E },
69  {"decryption_key", "AES decryption key", OFFSET(decrypt_key), AV_OPT_TYPE_BINARY, .flags = D },
70  {"decryption_iv", "AES decryption initialization vector", OFFSET(decrypt_iv), AV_OPT_TYPE_BINARY, .flags = D },
71  {"encryption_key", "AES encryption key", OFFSET(encrypt_key), AV_OPT_TYPE_BINARY, .flags = E },
72  {"encryption_iv", "AES encryption initialization vector", OFFSET(encrypt_iv), AV_OPT_TYPE_BINARY, .flags = E },
73  { NULL }
74 };
75 
76 static const AVClass crypto_class = {
77  .class_name = "crypto",
78  .item_name = av_default_item_name,
79  .option = options,
80  .version = LIBAVUTIL_VERSION_INT,
81 };
82 
83 static int set_aes_arg(CryptoContext *c, uint8_t **buf, int *buf_len,
84  uint8_t *default_buf, int default_buf_len,
85  const char *desc)
86 {
87  if (!*buf_len) {
88  if (!default_buf_len) {
89  av_log(c, AV_LOG_ERROR, "%s not set\n", desc);
90  return AVERROR(EINVAL);
91  } else if (default_buf_len != BLOCKSIZE) {
93  "invalid %s size (%d bytes, block size is %d)\n",
94  desc, default_buf_len, BLOCKSIZE);
95  return AVERROR(EINVAL);
96  }
97  *buf = av_memdup(default_buf, default_buf_len);
98  if (!*buf)
99  return AVERROR(ENOMEM);
100  *buf_len = default_buf_len;
101  } else if (*buf_len != BLOCKSIZE) {
102  av_log(c, AV_LOG_ERROR,
103  "invalid %s size (%d bytes, block size is %d)\n",
104  desc, *buf_len, BLOCKSIZE);
105  return AVERROR(EINVAL);
106  }
107  return 0;
108 }
109 
110 static int crypto_open2(URLContext *h, const char *uri, int flags, AVDictionary **options)
111 {
112  const char *nested_url;
113  int ret = 0;
114  CryptoContext *c = h->priv_data;
115  c->flags = flags;
116 
117  if (!av_strstart(uri, "crypto+", &nested_url) &&
118  !av_strstart(uri, "crypto:", &nested_url)) {
119  av_log(h, AV_LOG_ERROR, "Unsupported url %s\n", uri);
120  ret = AVERROR(EINVAL);
121  goto err;
122  }
123 
124  c->position = 0;
125 
126  if (flags & AVIO_FLAG_READ) {
127  if ((ret = set_aes_arg(c, &c->decrypt_key, &c->decrypt_keylen,
128  c->key, c->keylen, "decryption key")) < 0)
129  goto err;
130  if ((ret = set_aes_arg(c, &c->decrypt_iv, &c->decrypt_ivlen,
131  c->iv, c->ivlen, "decryption IV")) < 0)
132  goto err;
133  }
134 
135  if (flags & AVIO_FLAG_WRITE) {
136  if ((ret = set_aes_arg(c, &c->encrypt_key, &c->encrypt_keylen,
137  c->key, c->keylen, "encryption key")) < 0)
138  if (ret < 0)
139  goto err;
140  if ((ret = set_aes_arg(c, &c->encrypt_iv, &c->encrypt_ivlen,
141  c->iv, c->ivlen, "encryption IV")) < 0)
142  goto err;
143  }
144 
145  if ((ret = ffurl_open_whitelist(&c->hd, nested_url, flags,
146  &h->interrupt_callback, options,
147  h->protocol_whitelist, h->protocol_blacklist, h)) < 0) {
148  av_log(h, AV_LOG_ERROR, "Unable to open resource: %s\n", nested_url);
149  goto err;
150  }
151 
152  if (flags & AVIO_FLAG_READ) {
153  c->aes_decrypt = av_aes_alloc();
154  if (!c->aes_decrypt) {
155  ret = AVERROR(ENOMEM);
156  goto err;
157  }
158  ret = av_aes_init(c->aes_decrypt, c->decrypt_key, BLOCKSIZE*8, 1);
159  if (ret < 0)
160  goto err;
161 
162  // pass back information about the context we openned
163  if (c->hd->is_streamed)
164  h->is_streamed = c->hd->is_streamed;
165  }
166 
167  if (flags & AVIO_FLAG_WRITE) {
168  c->aes_encrypt = av_aes_alloc();
169  if (!c->aes_encrypt) {
170  ret = AVERROR(ENOMEM);
171  goto err;
172  }
173  ret = av_aes_init(c->aes_encrypt, c->encrypt_key, BLOCKSIZE*8, 0);
174  if (ret < 0)
175  goto err;
176  // for write, we must be streamed
177  // - linear write only for crytpo aes-128-cbc
178  h->is_streamed = 1;
179  }
180 
181  c->pad_len = 0;
182 
183 err:
184  return ret;
185 }
186 
187 static int crypto_read(URLContext *h, uint8_t *buf, int size)
188 {
189  CryptoContext *c = h->priv_data;
190  int blocks;
191 retry:
192  if (c->outdata > 0) {
193  size = FFMIN(size, c->outdata);
194  memcpy(buf, c->outptr, size);
195  c->outptr += size;
196  c->outdata -= size;
197  c->position = c->position + size;
198  return size;
199  }
200  // We avoid using the last block until we've found EOF,
201  // since we'll remove PKCS7 padding at the end. So make
202  // sure we've got at least 2 blocks, so we can decrypt
203  // at least one.
204  while (c->indata - c->indata_used < 2*BLOCKSIZE) {
205  int n = ffurl_read(c->hd, c->inbuffer + c->indata,
206  sizeof(c->inbuffer) - c->indata);
207  if (n <= 0) {
208  c->eof = 1;
209  break;
210  }
211  c->indata += n;
212  }
213  blocks = (c->indata - c->indata_used) / BLOCKSIZE;
214  if (!blocks)
215  return AVERROR_EOF;
216  if (!c->eof)
217  blocks--;
219  blocks, c->decrypt_iv, 1);
220  c->outdata = BLOCKSIZE * blocks;
221  c->outptr = c->outbuffer;
222  c->indata_used += BLOCKSIZE * blocks;
223  if (c->indata_used >= sizeof(c->inbuffer)/2) {
224  memmove(c->inbuffer, c->inbuffer + c->indata_used,
225  c->indata - c->indata_used);
226  c->indata -= c->indata_used;
227  c->indata_used = 0;
228  }
229  if (c->eof) {
230  // Remove PKCS7 padding at the end
231  int padding = c->outbuffer[c->outdata - 1];
232  c->outdata -= padding;
233  }
234  goto retry;
235 }
236 
237 static int64_t crypto_seek(URLContext *h, int64_t pos, int whence)
238 {
239  CryptoContext *c = h->priv_data;
240  int64_t block;
241  int64_t newpos;
242 
243  if (c->flags & AVIO_FLAG_WRITE) {
244  av_log(h, AV_LOG_ERROR,
245  "Crypto: seek not supported for write\r\n");
246  /* seems the most appropriate error to return */
247  return AVERROR(ESPIPE);
248  }
249 
250  // reset eof, else we won't read it correctly if we already hit eof.
251  c->eof = 0;
252 
253  switch (whence) {
254  case SEEK_SET:
255  break;
256  case SEEK_CUR:
257  pos = pos + c->position;
258  break;
259  case SEEK_END: {
260  int64_t newpos = ffurl_seek( c->hd, pos, AVSEEK_SIZE );
261  if (newpos < 0) {
262  av_log(h, AV_LOG_ERROR,
263  "Crypto: seek_end - can't get file size (pos=%lld)\r\n", (long long int)pos);
264  return newpos;
265  }
266  pos = newpos - pos;
267  }
268  break;
269  case AVSEEK_SIZE: {
270  int64_t newpos = ffurl_seek( c->hd, pos, AVSEEK_SIZE );
271  return newpos;
272  }
273  break;
274  default:
275  av_log(h, AV_LOG_ERROR,
276  "Crypto: no support for seek where 'whence' is %d\r\n", whence);
277  return AVERROR(EINVAL);
278  }
279 
280  c->outdata = 0;
281  c->indata = 0;
282  c->indata_used = 0;
283  c->outptr = c->outbuffer;
284 
285  // identify the block containing the IV for the
286  // next block we will decrypt
287  block = pos/BLOCKSIZE;
288  if (block == 0) {
289  // restore the iv to the seed one - this is the iv for the FIRST block
290  memcpy( c->decrypt_iv, c->iv, c->ivlen );
291  c->position = 0;
292  } else {
293  // else, go back one block - we will get av_cyrpt to read this block
294  // which it will then store use as the iv.
295  // note that the DECRYPTED result will not be correct,
296  // but will be discarded
297  block--;
298  c->position = (block * BLOCKSIZE);
299  }
300 
301  newpos = ffurl_seek( c->hd, c->position, SEEK_SET );
302  if (newpos < 0) {
303  av_log(h, AV_LOG_ERROR,
304  "Crypto: nested protocol no support for seek or seek failed\n");
305  return newpos;
306  }
307 
308  // read and discard from here up to required position
309  // (which will set the iv correctly to it).
310  if (pos - c->position) {
311  uint8_t buff[BLOCKSIZE*2]; // maximum size of pos-c->position
312  int len = pos - c->position;
313  int res;
314 
315  while (len > 0) {
316  // note: this may not return all the bytes first time
317  res = crypto_read(h, buff, len);
318  if (res < 0)
319  break;
320  len -= res;
321  }
322 
323  // if we did not get all the bytes
324  if (len != 0) {
325  char errbuf[100] = "unknown error";
326  av_strerror(res, errbuf, sizeof(errbuf));
327  av_log(h, AV_LOG_ERROR,
328  "Crypto: discard read did not get all the bytes (%d remain) - read returned (%d)-%s\n",
329  len, res, errbuf);
330  return AVERROR(EINVAL);
331  }
332  }
333 
334  return c->position;
335 }
336 
337 static int crypto_write(URLContext *h, const unsigned char *buf, int size)
338 {
339  CryptoContext *c = h->priv_data;
340  int total_size, blocks, pad_len, out_size;
341  uint8_t *out_buf;
342  int ret = 0;
343 
344  total_size = size + c->pad_len;
345  pad_len = total_size % BLOCKSIZE;
346  out_size = total_size - pad_len;
347  blocks = out_size / BLOCKSIZE;
348 
349  if (out_size) {
350  out_buf = av_malloc(out_size);
351  if (!out_buf)
352  return AVERROR(ENOMEM);
353 
354  if (c->pad_len) {
355  memcpy(&c->pad[c->pad_len], buf, BLOCKSIZE - c->pad_len);
356  av_aes_crypt(c->aes_encrypt, out_buf, c->pad, 1, c->encrypt_iv, 0);
357  blocks--;
358  }
359 
360  av_aes_crypt(c->aes_encrypt, &out_buf[c->pad_len ? BLOCKSIZE : 0],
361  &buf[c->pad_len ? BLOCKSIZE - c->pad_len: 0],
362  blocks, c->encrypt_iv, 0);
363 
364  ret = ffurl_write(c->hd, out_buf, out_size);
365  av_free(out_buf);
366  if (ret < 0)
367  return ret;
368 
369  memcpy(c->pad, &buf[size - pad_len], pad_len);
370  } else
371  memcpy(&c->pad[c->pad_len], buf, size);
372 
373  c->pad_len = pad_len;
374 
375  return size;
376 }
377 
379 {
380  CryptoContext *c = h->priv_data;
381  uint8_t out_buf[BLOCKSIZE];
382  int ret, pad;
383 
384  if (c->aes_encrypt) {
385  pad = BLOCKSIZE - c->pad_len;
386  memset(&c->pad[c->pad_len], pad, pad);
387  av_aes_crypt(c->aes_encrypt, out_buf, c->pad, 1, c->encrypt_iv, 0);
388  if ((ret = ffurl_write(c->hd, out_buf, BLOCKSIZE)) < 0)
389  return ret;
390  }
391 
392  if (c->hd)
393  ffurl_close(c->hd);
394  av_freep(&c->aes_decrypt);
395  av_freep(&c->aes_encrypt);
396  return 0;
397 }
398 
400  .name = "crypto",
401  .url_open2 = crypto_open2,
402  .url_seek = crypto_seek,
403  .url_read = crypto_read,
404  .url_write = crypto_write,
405  .url_close = crypto_close,
406  .priv_data_size = sizeof(CryptoContext),
407  .priv_data_class = &crypto_class,
409 };
static int crypto_close(URLContext *h)
Definition: crypto.c:378
#define NULL
Definition: coverity.c:32
int ffurl_open_whitelist(URLContext **puc, const char *filename, int flags, const AVIOInterruptCB *int_cb, AVDictionary **options, const char *whitelist, const char *blacklist, URLContext *parent)
Create an URLContext for accessing to the resource indicated by url, and open it. ...
Definition: avio.c:309
uint8_t * iv
Definition: crypto.c:45
AVOption.
Definition: opt.h:245
int ivlen
Definition: crypto.c:46
#define LIBAVUTIL_VERSION_INT
Definition: version.h:85
int ffurl_write(URLContext *h, const unsigned char *buf, int size)
Write size bytes from buf to the resource accessed by h.
Definition: avio.c:421
const char * desc
Definition: nvenc.c:101
int is_streamed
true if streamed (no seek possible), default = false
Definition: url.h:45
int decrypt_ivlen
Definition: crypto.c:50
int64_t position
Definition: crypto.c:40
AVIOInterruptCB interrupt_callback
Definition: url.h:47
static int crypto_read(URLContext *h, uint8_t *buf, int size)
Definition: crypto.c:187
#define AVIO_FLAG_READ
read-only
Definition: avio.h:606
void av_aes_crypt(AVAES *a, uint8_t *dst, const uint8_t *src, int count, uint8_t *iv, int decrypt)
Encrypt or decrypt a buffer using a previously initialized context.
Definition: aes.c:163
#define AVIO_FLAG_WRITE
write-only
Definition: avio.h:607
int decrypt_keylen
Definition: crypto.c:48
int out_size
Definition: movenc.c:55
int encrypt_ivlen
Definition: crypto.c:54
static const AVOption options[]
Definition: crypto.c:66
uint8_t inbuffer[BLOCKSIZE *MAX_BUFFER_BLOCKS]
Definition: crypto.c:36
uint8_t * outptr
Definition: crypto.c:38
uint8_t * encrypt_key
Definition: crypto.c:51
#define E
Definition: crypto.c:65
uint8_t outbuffer[BLOCKSIZE *MAX_BUFFER_BLOCKS]
Definition: crypto.c:36
static int16_t block[64]
Definition: dct.c:113
const char * class_name
The name of the class; usually it is the same name as the context structure type to which the AVClass...
Definition: log.h:72
int keylen
Definition: crypto.c:44
uint8_t
#define av_malloc(s)
AVOptions.
#define AVERROR_EOF
End of file.
Definition: error.h:55
ptrdiff_t size
Definition: opengl_enc.c:101
#define av_log(a,...)
static int crypto_open2(URLContext *h, const char *uri, int flags, AVDictionary **options)
Definition: crypto.c:110
#define MAX_BUFFER_BLOCKS
Definition: crypto.c:30
#define BLOCKSIZE
Definition: crypto.c:31
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:176
struct AVAES * aes_decrypt
Definition: crypto.c:55
uint8_t * decrypt_key
Definition: crypto.c:47
int indata_used
Definition: crypto.c:39
const char * protocol_whitelist
Definition: url.h:49
av_default_item_name
#define AVERROR(e)
Definition: error.h:43
uint8_t pad[BLOCKSIZE]
Definition: crypto.c:58
#define URL_PROTOCOL_FLAG_NESTED_SCHEME
Definition: url.h:33
int pad_len
Definition: crypto.c:59
int outdata
Definition: crypto.c:39
struct AVAES * av_aes_alloc(void)
Allocate an AVAES context.
Definition: aes.c:31
struct AVAES * aes_encrypt
Definition: crypto.c:56
uint8_t * encrypt_iv
Definition: crypto.c:53
void * av_memdup(const void *p, size_t size)
Duplicate a buffer with av_malloc().
Definition: mem.c:299
#define D
Definition: crypto.c:64
uint8_t * key
Definition: crypto.c:43
#define FFMIN(a, b)
Definition: common.h:96
static const AVClass crypto_class
Definition: crypto.c:76
URLContext * hd
Definition: crypto.c:35
int n
Definition: avisynth_c.h:684
int indata
Definition: crypto.c:39
offset must point to a pointer immediately followed by an int for the length
Definition: opt.h:229
int av_aes_init(AVAES *a, const uint8_t *key, int key_bits, int decrypt)
Initialize an AVAES context.
Definition: aes.c:195
const char * protocol_blacklist
Definition: url.h:50
const URLProtocol ff_crypto_protocol
Definition: crypto.c:399
static int64_t crypto_seek(URLContext *h, int64_t pos, int whence)
Definition: crypto.c:237
uint8_t * decrypt_iv
Definition: crypto.c:49
void * buf
Definition: avisynth_c.h:690
Definition: url.h:38
Describe the class of an AVClass context structure.
Definition: log.h:67
void * priv_data
Definition: url.h:41
static int crypto_write(URLContext *h, const unsigned char *buf, int size)
Definition: crypto.c:337
const char * name
Definition: url.h:54
static int flags
Definition: cpu.c:47
int ffurl_close(URLContext *h)
Definition: avio.c:467
int av_strerror(int errnum, char *errbuf, size_t errbuf_size)
Put a description of the AVERROR code errnum in errbuf.
Definition: error.c:105
int av_strstart(const char *str, const char *pfx, const char **ptr)
Return non-zero if pfx is a prefix of str.
Definition: avstring.c:34
Main libavformat public API header.
int64_t ffurl_seek(URLContext *h, int64_t pos, int whence)
Change the position that will be used by the next read/write operation on the resource accessed by h...
Definition: avio.c:434
static int set_aes_arg(CryptoContext *c, uint8_t **buf, int *buf_len, uint8_t *default_buf, int default_buf_len, const char *desc)
Definition: crypto.c:83
static double c[64]
#define AVSEEK_SIZE
ORing this as the "whence" parameter to a seek function causes it to return the filesize without seek...
Definition: avio.h:485
#define av_free(p)
int len
#define OFFSET(x)
Definition: crypto.c:63
int flags
Definition: crypto.c:41
#define av_freep(p)
unbuffered private I/O API
int encrypt_keylen
Definition: crypto.c:52
int ffurl_read(URLContext *h, unsigned char *buf, int size)
Read up to size bytes from the resource accessed by h, and store the read bytes in buf...
Definition: avio.c:407