You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

406 lines
13KB

  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. #include "avformat.h"
  22. #include "libavutil/aes.h"
  23. #include "libavutil/avstring.h"
  24. #include "libavutil/opt.h"
  25. #include "internal.h"
  26. #include "url.h"
  27. // encourage reads of 4096 bytes - 1 block is always retained.
  28. #define MAX_BUFFER_BLOCKS 257
  29. #define BLOCKSIZE 16
  30. typedef struct CryptoContext {
  31. const AVClass *class;
  32. URLContext *hd;
  33. uint8_t inbuffer [BLOCKSIZE*MAX_BUFFER_BLOCKS],
  34. outbuffer[BLOCKSIZE*MAX_BUFFER_BLOCKS];
  35. uint8_t *outptr;
  36. int indata, indata_used, outdata;
  37. int64_t position; // position in file - used in seek
  38. int flags;
  39. int eof;
  40. uint8_t *key;
  41. int keylen;
  42. uint8_t *iv;
  43. int ivlen;
  44. uint8_t *decrypt_key;
  45. int decrypt_keylen;
  46. uint8_t *decrypt_iv;
  47. int decrypt_ivlen;
  48. uint8_t *encrypt_key;
  49. int encrypt_keylen;
  50. uint8_t *encrypt_iv;
  51. int encrypt_ivlen;
  52. struct AVAES *aes_decrypt;
  53. struct AVAES *aes_encrypt;
  54. uint8_t *write_buf;
  55. unsigned int write_buf_size;
  56. uint8_t pad[BLOCKSIZE];
  57. int pad_len;
  58. } CryptoContext;
  59. #define OFFSET(x) offsetof(CryptoContext, x)
  60. #define D AV_OPT_FLAG_DECODING_PARAM
  61. #define E AV_OPT_FLAG_ENCODING_PARAM
  62. static const AVOption options[] = {
  63. {"key", "AES encryption/decryption key", OFFSET(key), AV_OPT_TYPE_BINARY, .flags = D|E },
  64. {"iv", "AES encryption/decryption initialization vector", OFFSET(iv), AV_OPT_TYPE_BINARY, .flags = D|E },
  65. {"decryption_key", "AES decryption key", OFFSET(decrypt_key), AV_OPT_TYPE_BINARY, .flags = D },
  66. {"decryption_iv", "AES decryption initialization vector", OFFSET(decrypt_iv), AV_OPT_TYPE_BINARY, .flags = D },
  67. {"encryption_key", "AES encryption key", OFFSET(encrypt_key), AV_OPT_TYPE_BINARY, .flags = E },
  68. {"encryption_iv", "AES encryption initialization vector", OFFSET(encrypt_iv), AV_OPT_TYPE_BINARY, .flags = E },
  69. { NULL }
  70. };
  71. static const AVClass crypto_class = {
  72. .class_name = "crypto",
  73. .item_name = av_default_item_name,
  74. .option = options,
  75. .version = LIBAVUTIL_VERSION_INT,
  76. };
  77. static int set_aes_arg(URLContext *h, uint8_t **buf, int *buf_len,
  78. uint8_t *default_buf, int default_buf_len,
  79. const char *desc)
  80. {
  81. if (!*buf_len) {
  82. if (!default_buf_len) {
  83. av_log(h, AV_LOG_ERROR, "%s not set\n", desc);
  84. return AVERROR(EINVAL);
  85. } else if (default_buf_len != BLOCKSIZE) {
  86. av_log(h, AV_LOG_ERROR,
  87. "invalid %s size (%d bytes, block size is %d)\n",
  88. desc, default_buf_len, BLOCKSIZE);
  89. return AVERROR(EINVAL);
  90. }
  91. *buf = av_memdup(default_buf, default_buf_len);
  92. if (!*buf)
  93. return AVERROR(ENOMEM);
  94. *buf_len = default_buf_len;
  95. } else if (*buf_len != BLOCKSIZE) {
  96. av_log(h, AV_LOG_ERROR,
  97. "invalid %s size (%d bytes, block size is %d)\n",
  98. desc, *buf_len, BLOCKSIZE);
  99. return AVERROR(EINVAL);
  100. }
  101. return 0;
  102. }
  103. static int crypto_open2(URLContext *h, const char *uri, int flags, AVDictionary **options)
  104. {
  105. const char *nested_url;
  106. int ret = 0;
  107. CryptoContext *c = h->priv_data;
  108. c->flags = flags;
  109. if (!av_strstart(uri, "crypto+", &nested_url) &&
  110. !av_strstart(uri, "crypto:", &nested_url)) {
  111. av_log(h, AV_LOG_ERROR, "Unsupported url %s\n", uri);
  112. ret = AVERROR(EINVAL);
  113. goto err;
  114. }
  115. if (flags & AVIO_FLAG_READ) {
  116. if ((ret = set_aes_arg(h, &c->decrypt_key, &c->decrypt_keylen,
  117. c->key, c->keylen, "decryption key")) < 0)
  118. goto err;
  119. if ((ret = set_aes_arg(h, &c->decrypt_iv, &c->decrypt_ivlen,
  120. c->iv, c->ivlen, "decryption IV")) < 0)
  121. goto err;
  122. }
  123. if (flags & AVIO_FLAG_WRITE) {
  124. if ((ret = set_aes_arg(h, &c->encrypt_key, &c->encrypt_keylen,
  125. c->key, c->keylen, "encryption key")) < 0)
  126. if (ret < 0)
  127. goto err;
  128. if ((ret = set_aes_arg(h, &c->encrypt_iv, &c->encrypt_ivlen,
  129. c->iv, c->ivlen, "encryption IV")) < 0)
  130. goto err;
  131. }
  132. if ((ret = ffurl_open_whitelist(&c->hd, nested_url, flags,
  133. &h->interrupt_callback, options,
  134. h->protocol_whitelist, h->protocol_blacklist, h)) < 0) {
  135. av_log(h, AV_LOG_ERROR, "Unable to open resource: %s\n", nested_url);
  136. goto err;
  137. }
  138. if (flags & AVIO_FLAG_READ) {
  139. c->aes_decrypt = av_aes_alloc();
  140. if (!c->aes_decrypt) {
  141. ret = AVERROR(ENOMEM);
  142. goto err;
  143. }
  144. ret = av_aes_init(c->aes_decrypt, c->decrypt_key, BLOCKSIZE * 8, 1);
  145. if (ret < 0)
  146. goto err;
  147. // pass back information about the context we openned
  148. if (c->hd->is_streamed)
  149. h->is_streamed = c->hd->is_streamed;
  150. }
  151. if (flags & AVIO_FLAG_WRITE) {
  152. c->aes_encrypt = av_aes_alloc();
  153. if (!c->aes_encrypt) {
  154. ret = AVERROR(ENOMEM);
  155. goto err;
  156. }
  157. ret = av_aes_init(c->aes_encrypt, c->encrypt_key, BLOCKSIZE * 8, 0);
  158. if (ret < 0)
  159. goto err;
  160. // for write, we must be streamed
  161. // - linear write only for crytpo aes-128-cbc
  162. h->is_streamed = 1;
  163. }
  164. err:
  165. return ret;
  166. }
  167. static int crypto_read(URLContext *h, uint8_t *buf, int size)
  168. {
  169. CryptoContext *c = h->priv_data;
  170. int blocks;
  171. retry:
  172. if (c->outdata > 0) {
  173. size = FFMIN(size, c->outdata);
  174. memcpy(buf, c->outptr, size);
  175. c->outptr += size;
  176. c->outdata -= size;
  177. c->position = c->position + size;
  178. return size;
  179. }
  180. // We avoid using the last block until we've found EOF,
  181. // since we'll remove PKCS7 padding at the end. So make
  182. // sure we've got at least 2 blocks, so we can decrypt
  183. // at least one.
  184. while (c->indata - c->indata_used < 2*BLOCKSIZE) {
  185. int n = ffurl_read(c->hd, c->inbuffer + c->indata,
  186. sizeof(c->inbuffer) - c->indata);
  187. if (n <= 0) {
  188. c->eof = 1;
  189. break;
  190. }
  191. c->indata += n;
  192. }
  193. blocks = (c->indata - c->indata_used) / BLOCKSIZE;
  194. if (!blocks)
  195. return AVERROR_EOF;
  196. if (!c->eof)
  197. blocks--;
  198. av_aes_crypt(c->aes_decrypt, c->outbuffer, c->inbuffer + c->indata_used,
  199. blocks, c->decrypt_iv, 1);
  200. c->outdata = BLOCKSIZE * blocks;
  201. c->outptr = c->outbuffer;
  202. c->indata_used += BLOCKSIZE * blocks;
  203. if (c->indata_used >= sizeof(c->inbuffer)/2) {
  204. memmove(c->inbuffer, c->inbuffer + c->indata_used,
  205. c->indata - c->indata_used);
  206. c->indata -= c->indata_used;
  207. c->indata_used = 0;
  208. }
  209. if (c->eof) {
  210. // Remove PKCS7 padding at the end
  211. int padding = c->outbuffer[c->outdata - 1];
  212. c->outdata -= padding;
  213. }
  214. goto retry;
  215. }
  216. static int64_t crypto_seek(URLContext *h, int64_t pos, int whence)
  217. {
  218. CryptoContext *c = h->priv_data;
  219. int64_t block;
  220. int64_t newpos;
  221. if (c->flags & AVIO_FLAG_WRITE) {
  222. av_log(h, AV_LOG_ERROR,
  223. "Crypto: seek not supported for write\r\n");
  224. /* seems the most appropriate error to return */
  225. return AVERROR(ESPIPE);
  226. }
  227. // reset eof, else we won't read it correctly if we already hit eof.
  228. c->eof = 0;
  229. switch (whence) {
  230. case SEEK_SET:
  231. break;
  232. case SEEK_CUR:
  233. pos = pos + c->position;
  234. break;
  235. case SEEK_END: {
  236. int64_t newpos = ffurl_seek( c->hd, pos, AVSEEK_SIZE );
  237. if (newpos < 0) {
  238. av_log(h, AV_LOG_ERROR,
  239. "Crypto: seek_end - can't get file size (pos=%lld)\r\n", (long long int)pos);
  240. return newpos;
  241. }
  242. pos = newpos - pos;
  243. }
  244. break;
  245. case AVSEEK_SIZE: {
  246. int64_t newpos = ffurl_seek( c->hd, pos, AVSEEK_SIZE );
  247. return newpos;
  248. }
  249. break;
  250. default:
  251. av_log(h, AV_LOG_ERROR,
  252. "Crypto: no support for seek where 'whence' is %d\r\n", whence);
  253. return AVERROR(EINVAL);
  254. }
  255. c->outdata = 0;
  256. c->indata = 0;
  257. c->indata_used = 0;
  258. c->outptr = c->outbuffer;
  259. // identify the block containing the IV for the
  260. // next block we will decrypt
  261. block = pos/BLOCKSIZE;
  262. if (block == 0) {
  263. // restore the iv to the seed one - this is the iv for the FIRST block
  264. memcpy( c->decrypt_iv, c->iv, c->ivlen );
  265. c->position = 0;
  266. } else {
  267. // else, go back one block - we will get av_cyrpt to read this block
  268. // which it will then store use as the iv.
  269. // note that the DECRYPTED result will not be correct,
  270. // but will be discarded
  271. block--;
  272. c->position = (block * BLOCKSIZE);
  273. }
  274. newpos = ffurl_seek( c->hd, c->position, SEEK_SET );
  275. if (newpos < 0) {
  276. av_log(h, AV_LOG_ERROR,
  277. "Crypto: nested protocol no support for seek or seek failed\n");
  278. return newpos;
  279. }
  280. // read and discard from here up to required position
  281. // (which will set the iv correctly to it).
  282. if (pos - c->position) {
  283. uint8_t buff[BLOCKSIZE*2]; // maximum size of pos-c->position
  284. int len = pos - c->position;
  285. int res;
  286. while (len > 0) {
  287. // note: this may not return all the bytes first time
  288. res = crypto_read(h, buff, len);
  289. if (res < 0)
  290. break;
  291. len -= res;
  292. }
  293. // if we did not get all the bytes
  294. if (len != 0) {
  295. char errbuf[100] = "unknown error";
  296. av_strerror(res, errbuf, sizeof(errbuf));
  297. av_log(h, AV_LOG_ERROR,
  298. "Crypto: discard read did not get all the bytes (%d remain) - read returned (%d)-%s\n",
  299. len, res, errbuf);
  300. return AVERROR(EINVAL);
  301. }
  302. }
  303. return c->position;
  304. }
  305. static int crypto_write(URLContext *h, const unsigned char *buf, int size)
  306. {
  307. CryptoContext *c = h->priv_data;
  308. int total_size, blocks, pad_len, out_size;
  309. int ret = 0;
  310. total_size = size + c->pad_len;
  311. pad_len = total_size % BLOCKSIZE;
  312. out_size = total_size - pad_len;
  313. blocks = out_size / BLOCKSIZE;
  314. if (out_size) {
  315. av_fast_malloc(&c->write_buf, &c->write_buf_size, out_size);
  316. if (!c->write_buf)
  317. return AVERROR(ENOMEM);
  318. if (c->pad_len) {
  319. memcpy(&c->pad[c->pad_len], buf, BLOCKSIZE - c->pad_len);
  320. av_aes_crypt(c->aes_encrypt, c->write_buf, c->pad, 1, c->encrypt_iv, 0);
  321. blocks--;
  322. }
  323. av_aes_crypt(c->aes_encrypt,
  324. &c->write_buf[c->pad_len ? BLOCKSIZE : 0],
  325. &buf[c->pad_len ? BLOCKSIZE - c->pad_len : 0],
  326. blocks, c->encrypt_iv, 0);
  327. ret = ffurl_write(c->hd, c->write_buf, out_size);
  328. if (ret < 0)
  329. return ret;
  330. memcpy(c->pad, &buf[size - pad_len], pad_len);
  331. } else
  332. memcpy(&c->pad[c->pad_len], buf, size);
  333. c->pad_len = pad_len;
  334. return size;
  335. }
  336. static int crypto_close(URLContext *h)
  337. {
  338. CryptoContext *c = h->priv_data;
  339. int ret = 0;
  340. if (c->aes_encrypt) {
  341. uint8_t out_buf[BLOCKSIZE];
  342. int pad = BLOCKSIZE - c->pad_len;
  343. memset(&c->pad[c->pad_len], pad, pad);
  344. av_aes_crypt(c->aes_encrypt, out_buf, c->pad, 1, c->encrypt_iv, 0);
  345. ret = ffurl_write(c->hd, out_buf, BLOCKSIZE);
  346. }
  347. ffurl_closep(&c->hd);
  348. av_freep(&c->aes_decrypt);
  349. av_freep(&c->aes_encrypt);
  350. av_freep(&c->write_buf);
  351. return ret;
  352. }
  353. const URLProtocol ff_crypto_protocol = {
  354. .name = "crypto",
  355. .url_open2 = crypto_open2,
  356. .url_seek = crypto_seek,
  357. .url_read = crypto_read,
  358. .url_write = crypto_write,
  359. .url_close = crypto_close,
  360. .priv_data_size = sizeof(CryptoContext),
  361. .priv_data_class = &crypto_class,
  362. .flags = URL_PROTOCOL_FLAG_NESTED_SCHEME,
  363. };