Libav
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 Libav.
6  *
7  * Libav 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  * Libav 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 Libav; 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 #if CONFIG_GNUTLS
28 #include <gnutls/gnutls.h>
29 #include <gnutls/x509.h>
30 #define TLS_read(c, buf, size) gnutls_record_recv(c->session, buf, size)
31 #define TLS_write(c, buf, size) gnutls_record_send(c->session, buf, size)
32 #define TLS_shutdown(c) gnutls_bye(c->session, GNUTLS_SHUT_RDWR)
33 #define TLS_free(c) do { \
34  if (c->session) \
35  gnutls_deinit(c->session); \
36  if (c->cred) \
37  gnutls_certificate_free_credentials(c->cred); \
38  } while (0)
39 #elif CONFIG_OPENSSL
40 #include <openssl/bio.h>
41 #include <openssl/ssl.h>
42 #include <openssl/err.h>
43 #define TLS_read(c, buf, size) SSL_read(c->ssl, buf, size)
44 #define TLS_write(c, buf, size) SSL_write(c->ssl, buf, size)
45 #define TLS_shutdown(c) SSL_shutdown(c->ssl)
46 #define TLS_free(c) do { \
47  if (c->ssl) \
48  SSL_free(c->ssl); \
49  if (c->ctx) \
50  SSL_CTX_free(c->ctx); \
51  } while (0)
52 #endif
53 #include "network.h"
54 #include "os_support.h"
55 #include "internal.h"
56 #if HAVE_POLL_H
57 #include <poll.h>
58 #endif
59 
60 typedef struct {
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  {"tls_verify", "Verify the peer certificate", OFFSET(verify), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, .flags = D|E },
84  {"cert_file", "Certificate file", OFFSET(cert_file), AV_OPT_TYPE_STRING, .flags = D|E },
85  {"key_file", "Private key file", OFFSET(key_file), AV_OPT_TYPE_STRING, .flags = D|E },
86  {"listen", "Listen for incoming connections", OFFSET(listen), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, .flags = D|E },
87  { NULL }
88 };
89 
90 static const AVClass tls_class = {
91  .class_name = "tls",
92  .item_name = av_default_item_name,
93  .option = options,
94  .version = LIBAVUTIL_VERSION_INT,
95 };
96 
97 static int do_tls_poll(URLContext *h, int ret)
98 {
99  TLSContext *c = h->priv_data;
100  struct pollfd p = { c->fd, 0, 0 };
101 #if CONFIG_GNUTLS
102  switch (ret) {
103  case GNUTLS_E_AGAIN:
104  case GNUTLS_E_INTERRUPTED:
105  break;
106  case GNUTLS_E_WARNING_ALERT_RECEIVED:
107  av_log(h, AV_LOG_WARNING, "%s\n", gnutls_strerror(ret));
108  break;
109  default:
110  av_log(h, AV_LOG_ERROR, "%s\n", gnutls_strerror(ret));
111  return AVERROR(EIO);
112  }
113  if (gnutls_record_get_direction(c->session))
114  p.events = POLLOUT;
115  else
116  p.events = POLLIN;
117 #elif CONFIG_OPENSSL
118  ret = SSL_get_error(c->ssl, ret);
119  if (ret == SSL_ERROR_WANT_READ) {
120  p.events = POLLIN;
121  } else if (ret == SSL_ERROR_WANT_WRITE) {
122  p.events = POLLOUT;
123  } else {
124  av_log(h, AV_LOG_ERROR, "%s\n", ERR_error_string(ERR_get_error(), NULL));
125  return AVERROR(EIO);
126  }
127 #endif
128  if (h->flags & AVIO_FLAG_NONBLOCK)
129  return AVERROR(EAGAIN);
130  while (1) {
131  int n = poll(&p, 1, 100);
132  if (n > 0)
133  break;
135  return AVERROR(EINTR);
136  }
137  return 0;
138 }
139 
140 static int tls_open(URLContext *h, const char *uri, int flags)
141 {
142  TLSContext *c = h->priv_data;
143  int ret;
144  int port;
145  char buf[200], host[200], opts[50] = "";
146  int numerichost = 0;
147  struct addrinfo hints = { 0 }, *ai = NULL;
148  const char *proxy_path;
149  int use_proxy;
150 
151  ff_tls_init();
152 
153  if (c->listen)
154  snprintf(opts, sizeof(opts), "?listen=1");
155 
156  av_url_split(NULL, 0, NULL, 0, host, sizeof(host), &port, NULL, 0, uri);
157  ff_url_join(buf, sizeof(buf), "tcp", NULL, host, port, "%s", opts);
158 
159  hints.ai_flags = AI_NUMERICHOST;
160  if (!getaddrinfo(host, NULL, &hints, &ai)) {
161  numerichost = 1;
162  freeaddrinfo(ai);
163  }
164 
165  proxy_path = getenv("http_proxy");
166  use_proxy = !ff_http_match_no_proxy(getenv("no_proxy"), host) &&
167  proxy_path && av_strstart(proxy_path, "http://", NULL);
168 
169  if (use_proxy) {
170  char proxy_host[200], proxy_auth[200], dest[200];
171  int proxy_port;
172  av_url_split(NULL, 0, proxy_auth, sizeof(proxy_auth),
173  proxy_host, sizeof(proxy_host), &proxy_port, NULL, 0,
174  proxy_path);
175  ff_url_join(dest, sizeof(dest), NULL, NULL, host, port, NULL);
176  ff_url_join(buf, sizeof(buf), "httpproxy", proxy_auth, proxy_host,
177  proxy_port, "/%s", dest);
178  }
179 
180  ret = ffurl_open(&c->tcp, buf, AVIO_FLAG_READ_WRITE,
181  &h->interrupt_callback, NULL);
182  if (ret)
183  goto fail;
184  c->fd = ffurl_get_file_handle(c->tcp);
185 
186 #if CONFIG_GNUTLS
187  gnutls_init(&c->session, c->listen ? GNUTLS_SERVER : GNUTLS_CLIENT);
188  if (!c->listen && !numerichost)
189  gnutls_server_name_set(c->session, GNUTLS_NAME_DNS, host, strlen(host));
190  gnutls_certificate_allocate_credentials(&c->cred);
191  if (c->ca_file)
192  gnutls_certificate_set_x509_trust_file(c->cred, c->ca_file, GNUTLS_X509_FMT_PEM);
193 #if GNUTLS_VERSION_MAJOR >= 3
194  else
195  gnutls_certificate_set_x509_system_trust(c->cred);
196 #endif
197  gnutls_certificate_set_verify_flags(c->cred, c->verify ?
198  GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT : 0);
199  if (c->cert_file && c->key_file) {
200  ret = gnutls_certificate_set_x509_key_file(c->cred,
201  c->cert_file, c->key_file,
202  GNUTLS_X509_FMT_PEM);
203  if (ret < 0) {
204  av_log(h, AV_LOG_ERROR,
205  "Unable to set cert/key files %s and %s: %s\n",
206  c->cert_file, c->key_file, gnutls_strerror(ret));
207  ret = AVERROR(EIO);
208  goto fail;
209  }
210  }
211  gnutls_credentials_set(c->session, GNUTLS_CRD_CERTIFICATE, c->cred);
212  gnutls_transport_set_ptr(c->session, (gnutls_transport_ptr_t)
213  (intptr_t) c->fd);
214  gnutls_priority_set_direct(c->session, "NORMAL", NULL);
215  while (1) {
216  ret = gnutls_handshake(c->session);
217  if (ret == 0)
218  break;
219  if ((ret = do_tls_poll(h, ret)) < 0)
220  goto fail;
221  }
222  if (c->verify) {
223  unsigned int status, cert_list_size;
224  gnutls_x509_crt_t cert;
225  const gnutls_datum_t *cert_list;
226  if ((ret = gnutls_certificate_verify_peers2(c->session, &status)) < 0) {
227  av_log(h, AV_LOG_ERROR, "Unable to verify peer certificate: %s\n",
228  gnutls_strerror(ret));
229  ret = AVERROR(EIO);
230  goto fail;
231  }
232  if (status & GNUTLS_CERT_INVALID) {
233  av_log(h, AV_LOG_ERROR, "Peer certificate failed verification\n");
234  ret = AVERROR(EIO);
235  goto fail;
236  }
237  if (gnutls_certificate_type_get(c->session) != GNUTLS_CRT_X509) {
238  av_log(h, AV_LOG_ERROR, "Unsupported certificate type\n");
239  ret = AVERROR(EIO);
240  goto fail;
241  }
242  gnutls_x509_crt_init(&cert);
243  cert_list = gnutls_certificate_get_peers(c->session, &cert_list_size);
244  gnutls_x509_crt_import(cert, cert_list, GNUTLS_X509_FMT_DER);
245  ret = gnutls_x509_crt_check_hostname(cert, host);
246  gnutls_x509_crt_deinit(cert);
247  if (!ret) {
248  av_log(h, AV_LOG_ERROR,
249  "The certificate's owner does not match hostname %s\n", host);
250  ret = AVERROR(EIO);
251  goto fail;
252  }
253  }
254 #elif CONFIG_OPENSSL
255  c->ctx = SSL_CTX_new(c->listen ? TLSv1_server_method() : TLSv1_client_method());
256  if (!c->ctx) {
257  av_log(h, AV_LOG_ERROR, "%s\n", ERR_error_string(ERR_get_error(), NULL));
258  ret = AVERROR(EIO);
259  goto fail;
260  }
261  if (c->ca_file)
262  SSL_CTX_load_verify_locations(c->ctx, c->ca_file, NULL);
263  if (c->cert_file && !SSL_CTX_use_certificate_chain_file(c->ctx, c->cert_file)) {
264  av_log(h, AV_LOG_ERROR, "Unable to load cert file %s: %s\n",
265  c->cert_file, ERR_error_string(ERR_get_error(), NULL));
266  ret = AVERROR(EIO);
267  goto fail;
268  }
269  if (c->key_file && !SSL_CTX_use_PrivateKey_file(c->ctx, c->key_file, SSL_FILETYPE_PEM)) {
270  av_log(h, AV_LOG_ERROR, "Unable to load key file %s: %s\n",
271  c->key_file, ERR_error_string(ERR_get_error(), NULL));
272  ret = AVERROR(EIO);
273  goto fail;
274  }
275  // Note, this doesn't check that the peer certificate actually matches
276  // the requested hostname.
277  if (c->verify)
278  SSL_CTX_set_verify(c->ctx, SSL_VERIFY_PEER, NULL);
279  c->ssl = SSL_new(c->ctx);
280  if (!c->ssl) {
281  av_log(h, AV_LOG_ERROR, "%s\n", ERR_error_string(ERR_get_error(), NULL));
282  ret = AVERROR(EIO);
283  goto fail;
284  }
285  SSL_set_fd(c->ssl, c->fd);
286  if (!c->listen && !numerichost)
287  SSL_set_tlsext_host_name(c->ssl, host);
288  while (1) {
289  ret = c->listen ? SSL_accept(c->ssl) : SSL_connect(c->ssl);
290  if (ret > 0)
291  break;
292  if (ret == 0) {
293  av_log(h, AV_LOG_ERROR, "Unable to negotiate TLS/SSL session\n");
294  ret = AVERROR(EIO);
295  goto fail;
296  }
297  if ((ret = do_tls_poll(h, ret)) < 0)
298  goto fail;
299  }
300 #endif
301  return 0;
302 fail:
303  TLS_free(c);
304  if (c->tcp)
305  ffurl_close(c->tcp);
306  ff_tls_deinit();
307  return ret;
308 }
309 
310 static int tls_read(URLContext *h, uint8_t *buf, int size)
311 {
312  TLSContext *c = h->priv_data;
313  while (1) {
314  int ret = TLS_read(c, buf, size);
315  if (ret > 0)
316  return ret;
317  if (ret == 0)
318  return AVERROR_EOF;
319  if ((ret = do_tls_poll(h, ret)) < 0)
320  return ret;
321  }
322  return 0;
323 }
324 
325 static int tls_write(URLContext *h, const uint8_t *buf, int size)
326 {
327  TLSContext *c = h->priv_data;
328  while (1) {
329  int ret = TLS_write(c, buf, size);
330  if (ret > 0)
331  return ret;
332  if (ret == 0)
333  return AVERROR_EOF;
334  if ((ret = do_tls_poll(h, ret)) < 0)
335  return ret;
336  }
337  return 0;
338 }
339 
340 static int tls_close(URLContext *h)
341 {
342  TLSContext *c = h->priv_data;
343  TLS_shutdown(c);
344  TLS_free(c);
345  ffurl_close(c->tcp);
346  ff_tls_deinit();
347  return 0;
348 }
349 
351  .name = "tls",
352  .url_open = tls_open,
353  .url_read = tls_read,
354  .url_write = tls_write,
355  .url_close = tls_close,
356  .priv_data_size = sizeof(TLSContext),
358  .priv_data_class = &tls_class,
359 };
void av_url_split(char *proto, int proto_size, char *authorization, int authorization_size, char *hostname, int hostname_size, int *port_ptr, char *path, int path_size, const char *url)
Split a URL string into components.
Definition: utils.c:2684
Definition: tls.c:60
int size
#define URL_PROTOCOL_FLAG_NETWORK
Definition: url.h:35
AVOption.
Definition: opt.h:234
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:129
AVIOInterruptCB interrupt_callback
Definition: url.h:50
int flags
Definition: url.h:46
#define freeaddrinfo
Definition: network.h:183
URLContext * tcp
Definition: tls.c:62
#define AI_NUMERICHOST
Definition: network.h:152
int verify
Definition: tls.c:72
const char * class_name
The name of the class; usually it is the same name as the context structure type to which the AVClass...
Definition: log.h:38
uint8_t
AVOptions.
miscellaneous OS support macros and functions.
static int tls_read(URLContext *h, uint8_t *buf, int size)
Definition: tls.c:310
static int flags
Definition: log.c:44
#define AVERROR_EOF
End of file.
Definition: error.h:51
static const AVOption options[]
Definition: tls.c:81
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:123
char * cert_file
Definition: tls.c:73
#define OFFSET(x)
Definition: tls.c:78
static int do_tls_poll(URLContext *h, int ret)
Definition: tls.c:97
#define AVERROR(e)
Definition: error.h:43
void av_log(void *avcl, int level, const char *fmt,...)
Definition: log.c:168
URLProtocol ff_tls_protocol
Definition: tls.c:350
static const AVClass tls_class
Definition: tls.c:90
int ff_http_match_no_proxy(const char *no_proxy, const char *hostname)
Definition: network.c:329
static int tls_open(URLContext *h, const char *uri, int flags)
Definition: tls.c:140
char * ca_file
Definition: tls.c:71
int ffurl_get_file_handle(URLContext *h)
Return the file descriptor associated with this URL.
Definition: avio.c:352
static int tls_close(URLContext *h)
Definition: tls.c:340
#define E
Definition: tls.c:80
LIBAVUTIL_VERSION_INT
Definition: eval.c:55
#define D
Definition: tls.c:79
int ff_url_join(char *str, int size, const char *proto, const char *authorization, const char *hostname, int port, const char *fmt,...)
Definition: url.c:36
NULL
Definition: eval.c:55
int ff_check_interrupt(AVIOInterruptCB *cb)
Check if the user has requested to interrup a blocking function associated with cb.
Definition: avio.c:381
#define AVIO_FLAG_NONBLOCK
Use non-blocking mode.
Definition: avio.h:311
av_default_item_name
Definition: dnxhdenc.c:52
Definition: url.h:41
#define AVIO_FLAG_READ_WRITE
read-write pseudo flag
Definition: avio.h:294
Describe the class of an AVClass context structure.
Definition: log.h:33
void * priv_data
Definition: url.h:44
int fd
Definition: tls.c:70
misc parsing utilities
const char * name
Definition: url.h:54
int ffurl_close(URLContext *h)
Close the resource accessed by the URLContext h, and free the memory used by it.
Definition: avio.c:297
int av_strstart(const char *str, const char *pfx, const char **ptr)
Return non-zero if pfx is a prefix of str.
Definition: avstring.c:32
#define getaddrinfo
Definition: network.h:182
Main libavformat public API header.
int ffurl_open(URLContext **puc, const char *filename, int flags, const AVIOInterruptCB *int_cb, AVDictionary **options)
Create an URLContext for accessing to the resource indicated by url, and open it. ...
Definition: avio.c:211
char * key_file
Definition: tls.c:74
static int tls_write(URLContext *h, const uint8_t *buf, int size)
Definition: tls.c:325
void ff_tls_init(void)
Definition: network.c:66
int ai_flags
Definition: network.h:103
int listen
Definition: tls.c:75
void ff_tls_deinit(void)
Definition: network.c:98
unbuffered private I/O API