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.

463 lines
14KB

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