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