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.

505 lines
15KB

  1. /*
  2. * TLS/SSL Protocol
  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 "url.h"
  23. #include "libavutil/avstring.h"
  24. #include "libavutil/opt.h"
  25. #include "libavutil/parseutils.h"
  26. #include "network.h"
  27. #include "os_support.h"
  28. #include "internal.h"
  29. #if CONFIG_GNUTLS
  30. #include <gnutls/gnutls.h>
  31. #include <gnutls/x509.h>
  32. #define TLS_read(c, buf, size) gnutls_record_recv((c)->session, (buf), (size))
  33. #define TLS_write(c, buf, size) gnutls_record_send((c)->session, (buf), (size))
  34. #define TLS_shutdown(c) gnutls_bye((c)->session, GNUTLS_SHUT_RDWR)
  35. #define TLS_free(c) do { \
  36. if ((c)->session) \
  37. gnutls_deinit((c)->session); \
  38. if ((c)->cred) \
  39. gnutls_certificate_free_credentials((c)->cred); \
  40. } while (0)
  41. static ssize_t gnutls_url_pull(gnutls_transport_ptr_t transport,
  42. void *buf, size_t len)
  43. {
  44. URLContext *h = (URLContext*) transport;
  45. int ret = ffurl_read(h, buf, len);
  46. if (ret >= 0)
  47. return ret;
  48. if (ret == AVERROR(EAGAIN))
  49. errno = EAGAIN;
  50. else
  51. errno = EIO;
  52. return -1;
  53. }
  54. static ssize_t gnutls_url_push(gnutls_transport_ptr_t transport,
  55. const void *buf, size_t len)
  56. {
  57. URLContext *h = (URLContext*) transport;
  58. int ret = ffurl_write(h, buf, len);
  59. if (ret >= 0)
  60. return ret;
  61. if (ret == AVERROR(EAGAIN))
  62. errno = EAGAIN;
  63. else
  64. errno = EIO;
  65. return -1;
  66. }
  67. #elif CONFIG_OPENSSL
  68. #include <openssl/bio.h>
  69. #include <openssl/ssl.h>
  70. #include <openssl/err.h>
  71. #define TLS_read(c, buf, size) SSL_read((c)->ssl, (buf), (size))
  72. #define TLS_write(c, buf, size) SSL_write((c)->ssl, (buf), (size))
  73. #define TLS_shutdown(c) SSL_shutdown((c)->ssl)
  74. #define TLS_free(c) do { \
  75. if ((c)->ssl) \
  76. SSL_free((c)->ssl); \
  77. if ((c)->ctx) \
  78. SSL_CTX_free((c)->ctx); \
  79. } while (0)
  80. static int url_bio_create(BIO *b)
  81. {
  82. b->init = 1;
  83. b->ptr = NULL;
  84. b->flags = 0;
  85. return 1;
  86. }
  87. static int url_bio_destroy(BIO *b)
  88. {
  89. return 1;
  90. }
  91. static int url_bio_bread(BIO *b, char *buf, int len)
  92. {
  93. URLContext *h = b->ptr;
  94. int ret = ffurl_read(h, buf, len);
  95. if (ret >= 0)
  96. return ret;
  97. BIO_clear_retry_flags(b);
  98. if (ret == AVERROR(EAGAIN))
  99. BIO_set_retry_read(b);
  100. return -1;
  101. }
  102. static int url_bio_bwrite(BIO *b, const char *buf, int len)
  103. {
  104. URLContext *h = b->ptr;
  105. int ret = ffurl_write(h, buf, len);
  106. if (ret >= 0)
  107. return ret;
  108. BIO_clear_retry_flags(b);
  109. if (ret == AVERROR(EAGAIN))
  110. BIO_set_retry_write(b);
  111. return -1;
  112. }
  113. static long url_bio_ctrl(BIO *b, int cmd, long num, void *ptr)
  114. {
  115. if (cmd == BIO_CTRL_FLUSH) {
  116. BIO_clear_retry_flags(b);
  117. return 1;
  118. }
  119. return 0;
  120. }
  121. static int url_bio_bputs(BIO *b, const char *str)
  122. {
  123. return url_bio_bwrite(b, str, strlen(str));
  124. }
  125. static BIO_METHOD url_bio_method = {
  126. .type = BIO_TYPE_SOURCE_SINK,
  127. .name = "urlprotocol bio",
  128. .bwrite = url_bio_bwrite,
  129. .bread = url_bio_bread,
  130. .bputs = url_bio_bputs,
  131. .bgets = NULL,
  132. .ctrl = url_bio_ctrl,
  133. .create = url_bio_create,
  134. .destroy = url_bio_destroy,
  135. };
  136. #endif
  137. #if HAVE_POLL_H
  138. #include <poll.h>
  139. #endif
  140. typedef struct TLSContext {
  141. const AVClass *class;
  142. URLContext *tcp;
  143. #if CONFIG_GNUTLS
  144. gnutls_session_t session;
  145. gnutls_certificate_credentials_t cred;
  146. #elif CONFIG_OPENSSL
  147. SSL_CTX *ctx;
  148. SSL *ssl;
  149. #endif
  150. int fd;
  151. char *ca_file;
  152. int verify;
  153. char *cert_file;
  154. char *key_file;
  155. int listen;
  156. } TLSContext;
  157. #define OFFSET(x) offsetof(TLSContext, x)
  158. #define D AV_OPT_FLAG_DECODING_PARAM
  159. #define E AV_OPT_FLAG_ENCODING_PARAM
  160. static const AVOption options[] = {
  161. {"ca_file", "Certificate Authority database file", OFFSET(ca_file), AV_OPT_TYPE_STRING, .flags = D|E },
  162. {"cafile", "Certificate Authority database file", OFFSET(ca_file), AV_OPT_TYPE_STRING, .flags = D|E },
  163. {"tls_verify", "Verify the peer certificate", OFFSET(verify), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, .flags = D|E },
  164. {"cert_file", "Certificate file", OFFSET(cert_file), AV_OPT_TYPE_STRING, .flags = D|E },
  165. {"key_file", "Private key file", OFFSET(key_file), AV_OPT_TYPE_STRING, .flags = D|E },
  166. {"listen", "Listen for incoming connections", OFFSET(listen), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, .flags = D|E },
  167. { NULL }
  168. };
  169. static const AVClass tls_class = {
  170. .class_name = "tls",
  171. .item_name = av_default_item_name,
  172. .option = options,
  173. .version = LIBAVUTIL_VERSION_INT,
  174. };
  175. static int do_tls_poll(URLContext *h, int ret)
  176. {
  177. TLSContext *c = h->priv_data;
  178. struct pollfd p = { c->fd, 0, 0 };
  179. #if CONFIG_GNUTLS
  180. switch (ret) {
  181. case GNUTLS_E_AGAIN:
  182. case GNUTLS_E_INTERRUPTED:
  183. break;
  184. case GNUTLS_E_WARNING_ALERT_RECEIVED:
  185. av_log(h, AV_LOG_WARNING, "%s\n", gnutls_strerror(ret));
  186. break;
  187. default:
  188. av_log(h, AV_LOG_ERROR, "%s\n", gnutls_strerror(ret));
  189. return AVERROR(EIO);
  190. }
  191. if (gnutls_record_get_direction(c->session))
  192. p.events = POLLOUT;
  193. else
  194. p.events = POLLIN;
  195. #elif CONFIG_OPENSSL
  196. ret = SSL_get_error(c->ssl, ret);
  197. if (ret == SSL_ERROR_WANT_READ) {
  198. p.events = POLLIN;
  199. } else if (ret == SSL_ERROR_WANT_WRITE) {
  200. p.events = POLLOUT;
  201. } else {
  202. av_log(h, AV_LOG_ERROR, "%s\n", ERR_error_string(ERR_get_error(), NULL));
  203. return AVERROR(EIO);
  204. }
  205. #endif
  206. if (h->flags & AVIO_FLAG_NONBLOCK)
  207. return AVERROR(EAGAIN);
  208. while (1) {
  209. int n = poll(&p, 1, 100);
  210. if (n > 0)
  211. break;
  212. if (ff_check_interrupt(&h->interrupt_callback))
  213. return AVERROR(EINTR);
  214. }
  215. return 0;
  216. }
  217. static void set_options(URLContext *h, const char *uri)
  218. {
  219. TLSContext *c = h->priv_data;
  220. char buf[1024];
  221. const char *p = strchr(uri, '?');
  222. if (!p)
  223. return;
  224. if (!c->ca_file && av_find_info_tag(buf, sizeof(buf), "cafile", p))
  225. c->ca_file = av_strdup(buf);
  226. if (!c->verify && av_find_info_tag(buf, sizeof(buf), "verify", p)) {
  227. char *endptr = NULL;
  228. c->verify = strtol(buf, &endptr, 10);
  229. if (buf == endptr)
  230. c->verify = 1;
  231. }
  232. if (!c->cert_file && av_find_info_tag(buf, sizeof(buf), "cert", p))
  233. c->cert_file = av_strdup(buf);
  234. if (!c->key_file && av_find_info_tag(buf, sizeof(buf), "key", p))
  235. c->key_file = av_strdup(buf);
  236. }
  237. static int tls_open(URLContext *h, const char *uri, int flags, AVDictionary **options)
  238. {
  239. TLSContext *c = h->priv_data;
  240. int ret;
  241. int port;
  242. const char *p;
  243. char buf[200], host[200], opts[50] = "";
  244. int numerichost = 0;
  245. struct addrinfo hints = { 0 }, *ai = NULL;
  246. const char *proxy_path;
  247. int use_proxy;
  248. #if CONFIG_OPENSSL
  249. BIO *bio;
  250. #endif
  251. if ((ret = ff_tls_init()) < 0)
  252. return ret;
  253. if (c->listen)
  254. snprintf(opts, sizeof(opts), "?listen=1");
  255. av_url_split(NULL, 0, NULL, 0, host, sizeof(host), &port, NULL, 0, uri);
  256. p = strchr(uri, '?');
  257. if (!p) {
  258. p = opts;
  259. } else {
  260. if (av_find_info_tag(opts, sizeof(opts), "listen", p))
  261. c->listen = 1;
  262. }
  263. ff_url_join(buf, sizeof(buf), "tcp", NULL, host, port, "%s", p);
  264. hints.ai_flags = AI_NUMERICHOST;
  265. if (!getaddrinfo(host, NULL, &hints, &ai)) {
  266. numerichost = 1;
  267. freeaddrinfo(ai);
  268. }
  269. proxy_path = getenv("http_proxy");
  270. use_proxy = !ff_http_match_no_proxy(getenv("no_proxy"), host) &&
  271. proxy_path && av_strstart(proxy_path, "http://", NULL);
  272. if (use_proxy) {
  273. char proxy_host[200], proxy_auth[200], dest[200];
  274. int proxy_port;
  275. av_url_split(NULL, 0, proxy_auth, sizeof(proxy_auth),
  276. proxy_host, sizeof(proxy_host), &proxy_port, NULL, 0,
  277. proxy_path);
  278. ff_url_join(dest, sizeof(dest), NULL, NULL, host, port, NULL);
  279. ff_url_join(buf, sizeof(buf), "httpproxy", proxy_auth, proxy_host,
  280. proxy_port, "/%s", dest);
  281. }
  282. ret = ffurl_open(&c->tcp, buf, AVIO_FLAG_READ_WRITE,
  283. &h->interrupt_callback, options);
  284. if (ret)
  285. goto fail;
  286. c->fd = ffurl_get_file_handle(c->tcp);
  287. #if CONFIG_GNUTLS
  288. gnutls_init(&c->session, c->listen ? GNUTLS_SERVER : GNUTLS_CLIENT);
  289. if (!c->listen && !numerichost)
  290. gnutls_server_name_set(c->session, GNUTLS_NAME_DNS, host, strlen(host));
  291. gnutls_certificate_allocate_credentials(&c->cred);
  292. set_options(h, uri);
  293. if (c->ca_file) {
  294. ret = gnutls_certificate_set_x509_trust_file(c->cred, c->ca_file, GNUTLS_X509_FMT_PEM);
  295. if (ret < 0)
  296. av_log(h, AV_LOG_ERROR, "%s\n", gnutls_strerror(ret));
  297. }
  298. #if GNUTLS_VERSION_MAJOR >= 3
  299. else
  300. gnutls_certificate_set_x509_system_trust(c->cred);
  301. #endif
  302. gnutls_certificate_set_verify_flags(c->cred, c->verify ?
  303. GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT : 0);
  304. if (c->cert_file && c->key_file) {
  305. ret = gnutls_certificate_set_x509_key_file(c->cred,
  306. c->cert_file, c->key_file,
  307. GNUTLS_X509_FMT_PEM);
  308. if (ret < 0) {
  309. av_log(h, AV_LOG_ERROR,
  310. "Unable to set cert/key files %s and %s: %s\n",
  311. c->cert_file, c->key_file, gnutls_strerror(ret));
  312. ret = AVERROR(EIO);
  313. goto fail;
  314. }
  315. } else if (c->cert_file || c->key_file)
  316. av_log(h, AV_LOG_ERROR, "cert and key required\n");
  317. gnutls_credentials_set(c->session, GNUTLS_CRD_CERTIFICATE, c->cred);
  318. c->tcp->flags |= AVIO_FLAG_NONBLOCK;
  319. gnutls_transport_set_pull_function(c->session, gnutls_url_pull);
  320. gnutls_transport_set_push_function(c->session, gnutls_url_push);
  321. gnutls_transport_set_ptr(c->session, c->tcp);
  322. gnutls_priority_set_direct(c->session, "NORMAL", NULL);
  323. while (1) {
  324. ret = gnutls_handshake(c->session);
  325. if (ret == 0)
  326. break;
  327. if ((ret = do_tls_poll(h, ret)) < 0)
  328. goto fail;
  329. }
  330. if (c->verify) {
  331. unsigned int status, cert_list_size;
  332. gnutls_x509_crt_t cert;
  333. const gnutls_datum_t *cert_list;
  334. if ((ret = gnutls_certificate_verify_peers2(c->session, &status)) < 0) {
  335. av_log(h, AV_LOG_ERROR, "Unable to verify peer certificate: %s\n",
  336. gnutls_strerror(ret));
  337. ret = AVERROR(EIO);
  338. goto fail;
  339. }
  340. if (status & GNUTLS_CERT_INVALID) {
  341. av_log(h, AV_LOG_ERROR, "Peer certificate failed verification\n");
  342. ret = AVERROR(EIO);
  343. goto fail;
  344. }
  345. if (gnutls_certificate_type_get(c->session) != GNUTLS_CRT_X509) {
  346. av_log(h, AV_LOG_ERROR, "Unsupported certificate type\n");
  347. ret = AVERROR(EIO);
  348. goto fail;
  349. }
  350. gnutls_x509_crt_init(&cert);
  351. cert_list = gnutls_certificate_get_peers(c->session, &cert_list_size);
  352. gnutls_x509_crt_import(cert, cert_list, GNUTLS_X509_FMT_DER);
  353. ret = gnutls_x509_crt_check_hostname(cert, host);
  354. gnutls_x509_crt_deinit(cert);
  355. if (!ret) {
  356. av_log(h, AV_LOG_ERROR,
  357. "The certificate's owner does not match hostname %s\n", host);
  358. ret = AVERROR(EIO);
  359. goto fail;
  360. }
  361. }
  362. #elif CONFIG_OPENSSL
  363. c->ctx = SSL_CTX_new(c->listen ? TLSv1_server_method() : TLSv1_client_method());
  364. if (!c->ctx) {
  365. av_log(h, AV_LOG_ERROR, "%s\n", ERR_error_string(ERR_get_error(), NULL));
  366. ret = AVERROR(EIO);
  367. goto fail;
  368. }
  369. set_options(h, uri);
  370. if (c->ca_file) {
  371. if (!SSL_CTX_load_verify_locations(c->ctx, c->ca_file, NULL))
  372. av_log(h, AV_LOG_ERROR, "SSL_CTX_load_verify_locations %s\n", ERR_error_string(ERR_get_error(), NULL));
  373. }
  374. if (c->cert_file && !SSL_CTX_use_certificate_chain_file(c->ctx, c->cert_file)) {
  375. av_log(h, AV_LOG_ERROR, "Unable to load cert file %s: %s\n",
  376. c->cert_file, ERR_error_string(ERR_get_error(), NULL));
  377. ret = AVERROR(EIO);
  378. goto fail;
  379. }
  380. if (c->key_file && !SSL_CTX_use_PrivateKey_file(c->ctx, c->key_file, SSL_FILETYPE_PEM)) {
  381. av_log(h, AV_LOG_ERROR, "Unable to load key file %s: %s\n",
  382. c->key_file, ERR_error_string(ERR_get_error(), NULL));
  383. ret = AVERROR(EIO);
  384. goto fail;
  385. }
  386. // Note, this doesn't check that the peer certificate actually matches
  387. // the requested hostname.
  388. if (c->verify)
  389. SSL_CTX_set_verify(c->ctx, SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT, NULL);
  390. c->ssl = SSL_new(c->ctx);
  391. if (!c->ssl) {
  392. av_log(h, AV_LOG_ERROR, "%s\n", ERR_error_string(ERR_get_error(), NULL));
  393. ret = AVERROR(EIO);
  394. goto fail;
  395. }
  396. bio = BIO_new(&url_bio_method);
  397. c->tcp->flags |= AVIO_FLAG_NONBLOCK;
  398. bio->ptr = c->tcp;
  399. SSL_set_bio(c->ssl, bio, bio);
  400. if (!c->listen && !numerichost)
  401. SSL_set_tlsext_host_name(c->ssl, host);
  402. while (1) {
  403. ret = c->listen ? SSL_accept(c->ssl) : SSL_connect(c->ssl);
  404. if (ret > 0)
  405. break;
  406. if (ret == 0) {
  407. av_log(h, AV_LOG_ERROR, "Unable to negotiate TLS/SSL session\n");
  408. ret = AVERROR(EIO);
  409. goto fail;
  410. }
  411. if ((ret = do_tls_poll(h, ret)) < 0)
  412. goto fail;
  413. }
  414. #endif
  415. return 0;
  416. fail:
  417. TLS_free(c);
  418. if (c->tcp)
  419. ffurl_close(c->tcp);
  420. ff_tls_deinit();
  421. return ret;
  422. }
  423. static int tls_read(URLContext *h, uint8_t *buf, int size)
  424. {
  425. TLSContext *c = h->priv_data;
  426. while (1) {
  427. int ret = TLS_read(c, buf, size);
  428. if (ret > 0)
  429. return ret;
  430. if (ret == 0)
  431. return AVERROR_EOF;
  432. if ((ret = do_tls_poll(h, ret)) < 0)
  433. return ret;
  434. }
  435. return 0;
  436. }
  437. static int tls_write(URLContext *h, const uint8_t *buf, int size)
  438. {
  439. TLSContext *c = h->priv_data;
  440. while (1) {
  441. int ret = TLS_write(c, buf, size);
  442. if (ret > 0)
  443. return ret;
  444. if (ret == 0)
  445. return AVERROR_EOF;
  446. if ((ret = do_tls_poll(h, ret)) < 0)
  447. return ret;
  448. }
  449. return 0;
  450. }
  451. static int tls_close(URLContext *h)
  452. {
  453. TLSContext *c = h->priv_data;
  454. TLS_shutdown(c);
  455. TLS_free(c);
  456. ffurl_close(c->tcp);
  457. ff_tls_deinit();
  458. return 0;
  459. }
  460. URLProtocol ff_tls_protocol = {
  461. .name = "tls",
  462. .url_open2 = tls_open,
  463. .url_read = tls_read,
  464. .url_write = tls_write,
  465. .url_close = tls_close,
  466. .priv_data_size = sizeof(TLSContext),
  467. .flags = URL_PROTOCOL_FLAG_NETWORK,
  468. .priv_data_class = &tls_class,
  469. };