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