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.

410 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 pad[BLOCKSIZE];
  55. int pad_len;
  56. } CryptoContext;
  57. #define OFFSET(x) offsetof(CryptoContext, x)
  58. #define D AV_OPT_FLAG_DECODING_PARAM
  59. #define E AV_OPT_FLAG_ENCODING_PARAM
  60. static const AVOption options[] = {
  61. {"key", "AES encryption/decryption key", OFFSET(key), AV_OPT_TYPE_BINARY, .flags = D|E },
  62. {"iv", "AES encryption/decryption initialization vector", OFFSET(iv), AV_OPT_TYPE_BINARY, .flags = D|E },
  63. {"decryption_key", "AES decryption key", OFFSET(decrypt_key), AV_OPT_TYPE_BINARY, .flags = D },
  64. {"decryption_iv", "AES decryption initialization vector", OFFSET(decrypt_iv), AV_OPT_TYPE_BINARY, .flags = D },
  65. {"encryption_key", "AES encryption key", OFFSET(encrypt_key), AV_OPT_TYPE_BINARY, .flags = E },
  66. {"encryption_iv", "AES encryption initialization vector", OFFSET(encrypt_iv), AV_OPT_TYPE_BINARY, .flags = E },
  67. { NULL }
  68. };
  69. static const AVClass crypto_class = {
  70. .class_name = "crypto",
  71. .item_name = av_default_item_name,
  72. .option = options,
  73. .version = LIBAVUTIL_VERSION_INT,
  74. };
  75. static int set_aes_arg(CryptoContext *c, uint8_t **buf, int *buf_len,
  76. uint8_t *default_buf, int default_buf_len,
  77. const char *desc)
  78. {
  79. if (!*buf_len) {
  80. if (!default_buf_len) {
  81. av_log(c, AV_LOG_ERROR, "%s not set\n", desc);
  82. return AVERROR(EINVAL);
  83. } else if (default_buf_len != BLOCKSIZE) {
  84. av_log(c, AV_LOG_ERROR,
  85. "invalid %s size (%d bytes, block size is %d)\n",
  86. desc, default_buf_len, BLOCKSIZE);
  87. return AVERROR(EINVAL);
  88. }
  89. *buf = av_memdup(default_buf, default_buf_len);
  90. if (!*buf)
  91. return AVERROR(ENOMEM);
  92. *buf_len = default_buf_len;
  93. } else if (*buf_len != BLOCKSIZE) {
  94. av_log(c, AV_LOG_ERROR,
  95. "invalid %s size (%d bytes, block size is %d)\n",
  96. desc, *buf_len, BLOCKSIZE);
  97. return AVERROR(EINVAL);
  98. }
  99. return 0;
  100. }
  101. static int crypto_open2(URLContext *h, const char *uri, int flags, AVDictionary **options)
  102. {
  103. const char *nested_url;
  104. int ret = 0;
  105. CryptoContext *c = h->priv_data;
  106. c->flags = flags;
  107. if (!av_strstart(uri, "crypto+", &nested_url) &&
  108. !av_strstart(uri, "crypto:", &nested_url)) {
  109. av_log(h, AV_LOG_ERROR, "Unsupported url %s\n", uri);
  110. ret = AVERROR(EINVAL);
  111. goto err;
  112. }
  113. c->position = 0;
  114. if (flags & AVIO_FLAG_READ) {
  115. if ((ret = set_aes_arg(c, &c->decrypt_key, &c->decrypt_keylen,
  116. c->key, c->keylen, "decryption key")) < 0)
  117. goto err;
  118. if ((ret = set_aes_arg(c, &c->decrypt_iv, &c->decrypt_ivlen,
  119. c->iv, c->ivlen, "decryption IV")) < 0)
  120. goto err;
  121. }
  122. if (flags & AVIO_FLAG_WRITE) {
  123. if ((ret = set_aes_arg(c, &c->encrypt_key, &c->encrypt_keylen,
  124. c->key, c->keylen, "encryption key")) < 0)
  125. if (ret < 0)
  126. goto err;
  127. if ((ret = set_aes_arg(c, &c->encrypt_iv, &c->encrypt_ivlen,
  128. c->iv, c->ivlen, "encryption IV")) < 0)
  129. goto err;
  130. }
  131. if ((ret = ffurl_open_whitelist(&c->hd, nested_url, flags,
  132. &h->interrupt_callback, options,
  133. h->protocol_whitelist, h->protocol_blacklist, h)) < 0) {
  134. av_log(h, AV_LOG_ERROR, "Unable to open resource: %s\n", nested_url);
  135. goto err;
  136. }
  137. if (flags & AVIO_FLAG_READ) {
  138. c->aes_decrypt = av_aes_alloc();
  139. if (!c->aes_decrypt) {
  140. ret = AVERROR(ENOMEM);
  141. goto err;
  142. }
  143. ret = av_aes_init(c->aes_decrypt, c->decrypt_key, BLOCKSIZE*8, 1);
  144. if (ret < 0)
  145. goto err;
  146. // pass back information about the context we openned
  147. if (c->hd->is_streamed)
  148. h->is_streamed = c->hd->is_streamed;
  149. }
  150. if (flags & AVIO_FLAG_WRITE) {
  151. c->aes_encrypt = av_aes_alloc();
  152. if (!c->aes_encrypt) {
  153. ret = AVERROR(ENOMEM);
  154. goto err;
  155. }
  156. ret = av_aes_init(c->aes_encrypt, c->encrypt_key, BLOCKSIZE*8, 0);
  157. if (ret < 0)
  158. goto err;
  159. // for write, we must be streamed
  160. // - linear write only for crytpo aes-128-cbc
  161. h->is_streamed = 1;
  162. }
  163. c->pad_len = 0;
  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. uint8_t *out_buf;
  310. int ret = 0;
  311. total_size = size + c->pad_len;
  312. pad_len = total_size % BLOCKSIZE;
  313. out_size = total_size - pad_len;
  314. blocks = out_size / BLOCKSIZE;
  315. if (out_size) {
  316. out_buf = av_malloc(out_size);
  317. if (!out_buf)
  318. return AVERROR(ENOMEM);
  319. if (c->pad_len) {
  320. memcpy(&c->pad[c->pad_len], buf, BLOCKSIZE - c->pad_len);
  321. av_aes_crypt(c->aes_encrypt, out_buf, c->pad, 1, c->encrypt_iv, 0);
  322. blocks--;
  323. }
  324. av_aes_crypt(c->aes_encrypt, &out_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, out_buf, out_size);
  328. av_free(out_buf);
  329. if (ret < 0)
  330. return ret;
  331. memcpy(c->pad, &buf[size - pad_len], pad_len);
  332. } else
  333. memcpy(&c->pad[c->pad_len], buf, size);
  334. c->pad_len = pad_len;
  335. return size;
  336. }
  337. static int crypto_close(URLContext *h)
  338. {
  339. CryptoContext *c = h->priv_data;
  340. uint8_t out_buf[BLOCKSIZE];
  341. int ret, pad;
  342. if (c->aes_encrypt) {
  343. pad = BLOCKSIZE - c->pad_len;
  344. memset(&c->pad[c->pad_len], pad, pad);
  345. av_aes_crypt(c->aes_encrypt, out_buf, c->pad, 1, c->encrypt_iv, 0);
  346. if ((ret = ffurl_write(c->hd, out_buf, BLOCKSIZE)) < 0)
  347. return ret;
  348. }
  349. if (c->hd)
  350. ffurl_close(c->hd);
  351. av_freep(&c->aes_decrypt);
  352. av_freep(&c->aes_encrypt);
  353. return 0;
  354. }
  355. const URLProtocol ff_crypto_protocol = {
  356. .name = "crypto",
  357. .url_open2 = crypto_open2,
  358. .url_seek = crypto_seek,
  359. .url_read = crypto_read,
  360. .url_write = crypto_write,
  361. .url_close = crypto_close,
  362. .priv_data_size = sizeof(CryptoContext),
  363. .priv_data_class = &crypto_class,
  364. .flags = URL_PROTOCOL_FLAG_NESTED_SCHEME,
  365. };