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