]> git.sesse.net Git - ffmpeg/blob - libavformat/tls.c
rtpenc_mpegts: Set chain->rtp_ctx only after avformat_write_header succeeded
[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 #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 TLSContext {
61     const AVClass *class;
62     URLContext *tcp;
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;
134         if (ff_check_interrupt(&h->interrupt_callback))
135             return AVERROR(EINTR);
136     }
137     return 0;
138 }
139
140 static int tls_open(URLContext *h, const char *uri, int flags, AVDictionary **options)
141 {
142     TLSContext *c = h->priv_data;
143     int ret;
144     int port;
145     const char *p;
146     char buf[200], host[200], opts[50] = "";
147     int numerichost = 0;
148     struct addrinfo hints = { 0 }, *ai = NULL;
149     const char *proxy_path;
150     int use_proxy;
151
152     ff_tls_init();
153
154     if (c->listen)
155         snprintf(opts, sizeof(opts), "?listen=1");
156
157     av_url_split(NULL, 0, NULL, 0, host, sizeof(host), &port, NULL, 0, uri);
158
159     p = strchr(uri, '?');
160
161     if (!p) {
162         p = opts;
163     } else {
164         if (av_find_info_tag(opts, sizeof(opts), "listen", p))
165             c->listen = 1;
166     }
167
168     ff_url_join(buf, sizeof(buf), "tcp", NULL, host, port, "%s", p);
169
170     hints.ai_flags = AI_NUMERICHOST;
171     if (!getaddrinfo(host, NULL, &hints, &ai)) {
172         numerichost = 1;
173         freeaddrinfo(ai);
174     }
175
176     proxy_path = getenv("http_proxy");
177     use_proxy = !ff_http_match_no_proxy(getenv("no_proxy"), host) &&
178                 proxy_path && av_strstart(proxy_path, "http://", NULL);
179
180     if (use_proxy) {
181         char proxy_host[200], proxy_auth[200], dest[200];
182         int proxy_port;
183         av_url_split(NULL, 0, proxy_auth, sizeof(proxy_auth),
184                      proxy_host, sizeof(proxy_host), &proxy_port, NULL, 0,
185                      proxy_path);
186         ff_url_join(dest, sizeof(dest), NULL, NULL, host, port, NULL);
187         ff_url_join(buf, sizeof(buf), "httpproxy", proxy_auth, proxy_host,
188                     proxy_port, "/%s", dest);
189     }
190
191     ret = ffurl_open(&c->tcp, buf, AVIO_FLAG_READ_WRITE,
192                      &h->interrupt_callback, options);
193     if (ret)
194         goto fail;
195     c->fd = ffurl_get_file_handle(c->tcp);
196
197 #if CONFIG_GNUTLS
198     gnutls_init(&c->session, c->listen ? GNUTLS_SERVER : GNUTLS_CLIENT);
199     if (!c->listen && !numerichost)
200         gnutls_server_name_set(c->session, GNUTLS_NAME_DNS, host, strlen(host));
201     gnutls_certificate_allocate_credentials(&c->cred);
202     if (c->ca_file)
203         gnutls_certificate_set_x509_trust_file(c->cred, c->ca_file, GNUTLS_X509_FMT_PEM);
204 #if GNUTLS_VERSION_MAJOR >= 3
205     else
206         gnutls_certificate_set_x509_system_trust(c->cred);
207 #endif
208     gnutls_certificate_set_verify_flags(c->cred, c->verify ?
209                                         GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT : 0);
210     if (c->cert_file && c->key_file) {
211         ret = gnutls_certificate_set_x509_key_file(c->cred,
212                                                    c->cert_file, c->key_file,
213                                                    GNUTLS_X509_FMT_PEM);
214         if (ret < 0) {
215             av_log(h, AV_LOG_ERROR,
216                    "Unable to set cert/key files %s and %s: %s\n",
217                    c->cert_file, c->key_file, gnutls_strerror(ret));
218             ret = AVERROR(EIO);
219             goto fail;
220         }
221     }
222     gnutls_credentials_set(c->session, GNUTLS_CRD_CERTIFICATE, c->cred);
223     gnutls_transport_set_ptr(c->session, (gnutls_transport_ptr_t)
224                                          (intptr_t) c->fd);
225     gnutls_priority_set_direct(c->session, "NORMAL", NULL);
226     while (1) {
227         ret = gnutls_handshake(c->session);
228         if (ret == 0)
229             break;
230         if ((ret = do_tls_poll(h, ret)) < 0)
231             goto fail;
232     }
233     if (c->verify) {
234         unsigned int status, cert_list_size;
235         gnutls_x509_crt_t cert;
236         const gnutls_datum_t *cert_list;
237         if ((ret = gnutls_certificate_verify_peers2(c->session, &status)) < 0) {
238             av_log(h, AV_LOG_ERROR, "Unable to verify peer certificate: %s\n",
239                                     gnutls_strerror(ret));
240             ret = AVERROR(EIO);
241             goto fail;
242         }
243         if (status & GNUTLS_CERT_INVALID) {
244             av_log(h, AV_LOG_ERROR, "Peer certificate failed verification\n");
245             ret = AVERROR(EIO);
246             goto fail;
247         }
248         if (gnutls_certificate_type_get(c->session) != GNUTLS_CRT_X509) {
249             av_log(h, AV_LOG_ERROR, "Unsupported certificate type\n");
250             ret = AVERROR(EIO);
251             goto fail;
252         }
253         gnutls_x509_crt_init(&cert);
254         cert_list = gnutls_certificate_get_peers(c->session, &cert_list_size);
255         gnutls_x509_crt_import(cert, cert_list, GNUTLS_X509_FMT_DER);
256         ret = gnutls_x509_crt_check_hostname(cert, host);
257         gnutls_x509_crt_deinit(cert);
258         if (!ret) {
259             av_log(h, AV_LOG_ERROR,
260                    "The certificate's owner does not match hostname %s\n", host);
261             ret = AVERROR(EIO);
262             goto fail;
263         }
264     }
265 #elif CONFIG_OPENSSL
266     c->ctx = SSL_CTX_new(c->listen ? TLSv1_server_method() : TLSv1_client_method());
267     if (!c->ctx) {
268         av_log(h, AV_LOG_ERROR, "%s\n", ERR_error_string(ERR_get_error(), NULL));
269         ret = AVERROR(EIO);
270         goto fail;
271     }
272     if (c->ca_file)
273         SSL_CTX_load_verify_locations(c->ctx, c->ca_file, NULL);
274     if (c->cert_file && !SSL_CTX_use_certificate_chain_file(c->ctx, c->cert_file)) {
275         av_log(h, AV_LOG_ERROR, "Unable to load cert file %s: %s\n",
276                c->cert_file, ERR_error_string(ERR_get_error(), NULL));
277         ret = AVERROR(EIO);
278         goto fail;
279     }
280     if (c->key_file && !SSL_CTX_use_PrivateKey_file(c->ctx, c->key_file, SSL_FILETYPE_PEM)) {
281         av_log(h, AV_LOG_ERROR, "Unable to load key file %s: %s\n",
282                c->key_file, ERR_error_string(ERR_get_error(), NULL));
283         ret = AVERROR(EIO);
284         goto fail;
285     }
286     // Note, this doesn't check that the peer certificate actually matches
287     // the requested hostname.
288     if (c->verify)
289         SSL_CTX_set_verify(c->ctx, SSL_VERIFY_PEER, NULL);
290     c->ssl = SSL_new(c->ctx);
291     if (!c->ssl) {
292         av_log(h, AV_LOG_ERROR, "%s\n", ERR_error_string(ERR_get_error(), NULL));
293         ret = AVERROR(EIO);
294         goto fail;
295     }
296     SSL_set_fd(c->ssl, c->fd);
297     if (!c->listen && !numerichost)
298         SSL_set_tlsext_host_name(c->ssl, host);
299     while (1) {
300         ret = c->listen ? SSL_accept(c->ssl) : SSL_connect(c->ssl);
301         if (ret > 0)
302             break;
303         if (ret == 0) {
304             av_log(h, AV_LOG_ERROR, "Unable to negotiate TLS/SSL session\n");
305             ret = AVERROR(EIO);
306             goto fail;
307         }
308         if ((ret = do_tls_poll(h, ret)) < 0)
309             goto fail;
310     }
311 #endif
312     return 0;
313 fail:
314     TLS_free(c);
315     if (c->tcp)
316         ffurl_close(c->tcp);
317     ff_tls_deinit();
318     return ret;
319 }
320
321 static int tls_read(URLContext *h, uint8_t *buf, int size)
322 {
323     TLSContext *c = h->priv_data;
324     while (1) {
325         int ret = TLS_read(c, buf, size);
326         if (ret > 0)
327             return ret;
328         if (ret == 0)
329             return AVERROR_EOF;
330         if ((ret = do_tls_poll(h, ret)) < 0)
331             return ret;
332     }
333     return 0;
334 }
335
336 static int tls_write(URLContext *h, const uint8_t *buf, int size)
337 {
338     TLSContext *c = h->priv_data;
339     while (1) {
340         int ret = TLS_write(c, buf, size);
341         if (ret > 0)
342             return ret;
343         if (ret == 0)
344             return AVERROR_EOF;
345         if ((ret = do_tls_poll(h, ret)) < 0)
346             return ret;
347     }
348     return 0;
349 }
350
351 static int tls_close(URLContext *h)
352 {
353     TLSContext *c = h->priv_data;
354     TLS_shutdown(c);
355     TLS_free(c);
356     ffurl_close(c->tcp);
357     ff_tls_deinit();
358     return 0;
359 }
360
361 URLProtocol ff_tls_protocol = {
362     .name           = "tls",
363     .url_open2      = tls_open,
364     .url_read       = tls_read,
365     .url_write      = tls_write,
366     .url_close      = tls_close,
367     .priv_data_size = sizeof(TLSContext),
368     .flags          = URL_PROTOCOL_FLAG_NETWORK,
369     .priv_data_class = &tls_class,
370 };