FFmpeg
tls_gnutls.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 <errno.h>
23 
24 #include <gnutls/gnutls.h>
25 #include <gnutls/dtls.h>
26 #include <gnutls/x509.h>
27 
28 #include "avformat.h"
29 #include "network.h"
30 #include "os_support.h"
31 #include "url.h"
32 #include "tls.h"
33 #include "libavutil/opt.h"
34 #include "libavutil/thread.h"
35 
36 #ifndef GNUTLS_VERSION_NUMBER
37 #define GNUTLS_VERSION_NUMBER LIBGNUTLS_VERSION_NUMBER
38 #endif
39 
40 #if HAVE_THREADS && GNUTLS_VERSION_NUMBER <= 0x020b00
41 #include <gcrypt.h>
42 GCRY_THREAD_OPTION_PTHREAD_IMPL;
43 #endif
44 
45 typedef struct TLSContext {
47  gnutls_session_t session;
48  gnutls_certificate_credentials_t cred;
50  int io_err;
52  socklen_t dest_addr_len;
53 } TLSContext;
54 
56 
57 void ff_gnutls_init(void)
58 {
60 #if HAVE_THREADS && GNUTLS_VERSION_NUMBER < 0x020b00
61  if (gcry_control(GCRYCTL_ANY_INITIALIZATION_P) == 0)
62  gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
63 #endif
64  gnutls_global_init();
66 }
67 
68 void ff_gnutls_deinit(void)
69 {
71  gnutls_global_deinit();
73 }
74 
75 static int print_tls_error(URLContext *h, int ret)
76 {
77  TLSContext *c = h->priv_data;
78  switch (ret) {
79  case GNUTLS_E_AGAIN:
80  return AVERROR(EAGAIN);
81  case GNUTLS_E_INTERRUPTED:
82 #ifdef GNUTLS_E_PREMATURE_TERMINATION
83  case GNUTLS_E_PREMATURE_TERMINATION:
84 #endif
85  break;
86  case GNUTLS_E_WARNING_ALERT_RECEIVED:
87  av_log(h, AV_LOG_WARNING, "%s\n", gnutls_strerror(ret));
88  break;
89  default:
90  av_log(h, AV_LOG_ERROR, "%s\n", gnutls_strerror(ret));
91  break;
92  }
93  if (c->io_err) {
94  av_log(h, AV_LOG_ERROR, "IO error: %s\n", av_err2str(c->io_err));
95  ret = c->io_err;
96  c->io_err = 0;
97  return ret;
98  }
99  return AVERROR(EIO);
100 }
101 
102 static int tls_close(URLContext *h)
103 {
104  TLSContext *c = h->priv_data;
105  TLSShared *s = &c->tls_shared;
106  if (c->need_shutdown)
107  gnutls_bye(c->session, GNUTLS_SHUT_WR);
108  if (c->session)
109  gnutls_deinit(c->session);
110  if (c->cred)
111  gnutls_certificate_free_credentials(c->cred);
112  if (!s->external_sock)
113  ffurl_closep(s->is_dtls ? &s->udp : &s->tcp);
115  return 0;
116 }
117 
118 static ssize_t gnutls_url_pull(gnutls_transport_ptr_t transport,
119  void *buf, size_t len)
120 {
121  TLSContext *c = (TLSContext*) transport;
122  TLSShared *s = &c->tls_shared;
123  URLContext *uc = s->is_dtls ? s->udp : s->tcp;
124  int ret = ffurl_read(uc, buf, len);
125  if (ret >= 0) {
126  if (s->is_dtls && s->listen && !c->dest_addr_len) {
127  int err_ret;
128 
129  ff_udp_get_last_recv_addr(s->udp, &c->dest_addr, &c->dest_addr_len);
130  err_ret = ff_udp_set_remote_addr(s->udp, (struct sockaddr *)&c->dest_addr, c->dest_addr_len, 1);
131  if (err_ret < 0) {
132  av_log(c, AV_LOG_ERROR, "Failed connecting udp context\n");
133  return err_ret;
134  }
135  av_log(c, AV_LOG_TRACE, "Set UDP remote addr on UDP socket, now 'connected'\n");
136  }
137  return ret;
138  }
139  if (ret == AVERROR_EXIT)
140  return 0;
141  if (ret == AVERROR(EAGAIN)) {
142  errno = EAGAIN;
143  } else {
144  errno = EIO;
145  c->io_err = ret;
146  }
147  return -1;
148 }
149 
150 static ssize_t gnutls_url_push(gnutls_transport_ptr_t transport,
151  const void *buf, size_t len)
152 {
153  TLSContext *c = (TLSContext*) transport;
154  TLSShared *s = &c->tls_shared;
155  URLContext *uc = s->is_dtls ? s->udp : s->tcp;
156  int ret = ffurl_write(uc, buf, len);
157  if (ret >= 0)
158  return ret;
159  if (ret == AVERROR_EXIT)
160  return 0;
161  if (ret == AVERROR(EAGAIN)) {
162  errno = EAGAIN;
163  } else {
164  errno = EIO;
165  c->io_err = ret;
166  }
167  return -1;
168 }
169 
170 static int gnutls_pull_timeout(gnutls_transport_ptr_t ptr, unsigned int ms)
171 {
172  TLSContext *c = (TLSContext*) ptr;
173  TLSShared *s = &c->tls_shared;
174  int ret;
175  fd_set rfds;
176  struct timeval tv;
177  int sockfd = ffurl_get_file_handle(s->udp);
178  if (sockfd < 0)
179  return 0;
180 
181  FD_ZERO(&rfds);
182  FD_SET(sockfd, &rfds);
183 
184  tv.tv_sec = ms / 1000;
185  tv.tv_usec = (ms % 1000) * 1000;
186 
187  ret = select(sockfd + 1, &rfds, NULL, NULL, &tv);
188  if (ret <= 0)
189  return ret;
190  return 1;
191 }
192 
194 {
195  TLSContext *c = h->priv_data;
196  TLSShared *s = &c->tls_shared;
197  URLContext *uc = s->is_dtls ? s->udp : s->tcp;
198  int ret;
199 
200  uc->flags &= ~AVIO_FLAG_NONBLOCK;
201 
202  do {
203  if (ff_check_interrupt(&h->interrupt_callback)) {
204  ret = AVERROR_EXIT;
205  goto end;
206  }
207 
208  ret = gnutls_handshake(c->session);
209  if (gnutls_error_is_fatal(ret)) {
210  ret = print_tls_error(h, ret);
211  goto end;
212  }
213  } while (ret);
214 
215 end:
216  return ret;
217 }
218 
219 static int tls_open(URLContext *h, const char *uri, int flags, AVDictionary **options)
220 {
221  TLSContext *c = h->priv_data;
222  TLSShared *s = &c->tls_shared;
223  uint16_t gnutls_flags = 0;
224  int ret;
225 
226  ff_gnutls_init();
227 
228  if ((ret = ff_tls_open_underlying(s, h, uri, options)) < 0)
229  goto fail;
230 
231  if (s->is_dtls)
232  gnutls_flags |= GNUTLS_DATAGRAM;
233 
234  if (s->listen)
235  gnutls_flags |= GNUTLS_SERVER;
236  else
237  gnutls_flags |= GNUTLS_CLIENT;
238  gnutls_init(&c->session, gnutls_flags);
239  if (!s->listen && !s->numerichost)
240  gnutls_server_name_set(c->session, GNUTLS_NAME_DNS, s->host, strlen(s->host));
241  gnutls_certificate_allocate_credentials(&c->cred);
242  if (s->ca_file) {
243  ret = gnutls_certificate_set_x509_trust_file(c->cred, s->ca_file, GNUTLS_X509_FMT_PEM);
244  if (ret < 0)
245  av_log(h, AV_LOG_ERROR, "%s\n", gnutls_strerror(ret));
246  }
247 #if GNUTLS_VERSION_NUMBER >= 0x030020
248  else
249  gnutls_certificate_set_x509_system_trust(c->cred);
250 #endif
251  gnutls_certificate_set_verify_flags(c->cred, s->verify ?
252  GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT : 0);
253  if (s->cert_file && s->key_file) {
254  ret = gnutls_certificate_set_x509_key_file(c->cred,
255  s->cert_file, s->key_file,
256  GNUTLS_X509_FMT_PEM);
257  if (ret < 0) {
259  "Unable to set cert/key files %s and %s: %s\n",
260  s->cert_file, s->key_file, gnutls_strerror(ret));
261  ret = AVERROR(EIO);
262  goto fail;
263  }
264  } else if (s->cert_file || s->key_file)
265  av_log(h, AV_LOG_ERROR, "cert and key required\n");
266  gnutls_credentials_set(c->session, GNUTLS_CRD_CERTIFICATE, c->cred);
267  gnutls_transport_set_pull_function(c->session, gnutls_url_pull);
268  gnutls_transport_set_push_function(c->session, gnutls_url_push);
269  gnutls_transport_set_ptr(c->session, c);
270  if (s->is_dtls) {
271  gnutls_transport_set_pull_timeout_function(c->session, gnutls_pull_timeout);
272  if (s->mtu)
273  gnutls_dtls_set_mtu(c->session, s->mtu);
274  }
275  gnutls_set_default_priority(c->session);
276  ret = tls_handshake(h);
277  if (ret < 0)
278  goto fail;
279  c->need_shutdown = 1;
280  if (s->verify) {
281  unsigned int status, cert_list_size;
282  gnutls_x509_crt_t cert;
283  const gnutls_datum_t *cert_list;
284  if ((ret = gnutls_certificate_verify_peers2(c->session, &status)) < 0) {
285  av_log(h, AV_LOG_ERROR, "Unable to verify peer certificate: %s\n",
286  gnutls_strerror(ret));
287  ret = AVERROR(EIO);
288  goto fail;
289  }
290  if (status & GNUTLS_CERT_INVALID) {
291  av_log(h, AV_LOG_ERROR, "Peer certificate failed verification\n");
292  ret = AVERROR(EIO);
293  goto fail;
294  }
295  if (gnutls_certificate_type_get(c->session) != GNUTLS_CRT_X509) {
296  av_log(h, AV_LOG_ERROR, "Unsupported certificate type\n");
297  ret = AVERROR(EIO);
298  goto fail;
299  }
300  gnutls_x509_crt_init(&cert);
301  cert_list = gnutls_certificate_get_peers(c->session, &cert_list_size);
302  gnutls_x509_crt_import(cert, cert_list, GNUTLS_X509_FMT_DER);
303  ret = gnutls_x509_crt_check_hostname(cert, s->host);
304  gnutls_x509_crt_deinit(cert);
305  if (!ret) {
307  "The certificate's owner does not match hostname %s\n", s->host);
308  ret = AVERROR(EIO);
309  goto fail;
310  }
311  }
312 
313  return 0;
314 fail:
315  tls_close(h);
316  return ret;
317 }
318 
319 static int dtls_open(URLContext *h, const char *uri, int flags, AVDictionary **options)
320 {
321  TLSContext *c = h->priv_data;
322  TLSShared *s = &c->tls_shared;
323  s->is_dtls = 1;
324  return tls_open(h, uri, flags, options);
325 }
326 
327 static int tls_read(URLContext *h, uint8_t *buf, int size)
328 {
329  TLSContext *c = h->priv_data;
330  TLSShared *s = &c->tls_shared;
331  URLContext *uc = s->is_dtls ? s->udp : s->tcp;
332  int ret;
333  // Set or clear the AVIO_FLAG_NONBLOCK on c->tls_shared.tcp
334  uc->flags &= ~AVIO_FLAG_NONBLOCK;
335  uc->flags |= h->flags & AVIO_FLAG_NONBLOCK;
336  ret = gnutls_record_recv(c->session, buf, size);
337  if (ret > 0)
338  return ret;
339  if (ret == 0)
340  return AVERROR_EOF;
341  return print_tls_error(h, ret);
342 }
343 
344 static int tls_write(URLContext *h, const uint8_t *buf, int size)
345 {
346  TLSContext *c = h->priv_data;
347  TLSShared *s = &c->tls_shared;
348  URLContext *uc = s->is_dtls ? s->udp : s->tcp;
349  int ret;
350  // Set or clear the AVIO_FLAG_NONBLOCK on c->tls_shared.tcp
351  uc->flags &= ~AVIO_FLAG_NONBLOCK;
352  uc->flags |= h->flags & AVIO_FLAG_NONBLOCK;
353  ret = gnutls_record_send(c->session, buf, size);
354  if (ret > 0)
355  return ret;
356  if (ret == 0)
357  return AVERROR_EOF;
358  return print_tls_error(h, ret);
359 }
360 
362 {
363  TLSContext *c = h->priv_data;
364  return ffurl_get_file_handle(c->tls_shared.tcp);
365 }
366 
368 {
369  TLSContext *s = h->priv_data;
370  return ffurl_get_short_seek(s->tls_shared.tcp);
371 }
372 
373 static const AVOption options[] = {
374  TLS_COMMON_OPTIONS(TLSContext, tls_shared),
375  { NULL }
376 };
377 
378 static const AVClass tls_class = {
379  .class_name = "tls",
380  .item_name = av_default_item_name,
381  .option = options,
382  .version = LIBAVUTIL_VERSION_INT,
383 };
384 
386  .name = "tls",
387  .url_open2 = tls_open,
388  .url_read = tls_read,
389  .url_write = tls_write,
390  .url_close = tls_close,
391  .url_get_file_handle = tls_get_file_handle,
392  .url_get_short_seek = tls_get_short_seek,
393  .priv_data_size = sizeof(TLSContext),
395  .priv_data_class = &tls_class,
396 };
397 
398 static const AVClass dtls_class = {
399  .class_name = "dtls",
400  .item_name = av_default_item_name,
401  .option = options,
402  .version = LIBAVUTIL_VERSION_INT,
403 };
404 
406  .name = "dtls",
407  .url_open2 = dtls_open,
408  .url_handshake = tls_handshake,
409  .url_read = tls_read,
410  .url_write = tls_write,
411  .url_close = tls_close,
412  .url_get_file_handle = tls_get_file_handle,
413  .url_get_short_seek = tls_get_short_seek,
414  .priv_data_size = sizeof(TLSContext),
416  .priv_data_class = &dtls_class,
417 };
ff_gnutls_init
void ff_gnutls_init(void)
Definition: tls_gnutls.c:57
flags
const SwsFlags flags[]
Definition: swscale.c:61
AV_LOG_WARNING
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:216
TLSContext
Definition: tls_gnutls.c:45
AVERROR
Filter the word “frame” indicates either a video frame or a group of audio as stored in an AVFrame structure Format for each input and each output the list of supported formats For video that means pixel format For audio that means channel sample they are references to shared objects When the negotiation mechanism computes the intersection of the formats supported at each end of a all references to both lists are replaced with a reference to the intersection And when a single format is eventually chosen for a link amongst the remaining all references to the list are updated That means that if a filter requires that its input and output have the same format amongst a supported all it has to do is use a reference to the same list of formats query_formats can leave some formats unset and return AVERROR(EAGAIN) to cause the negotiation mechanism toagain later. That can be used by filters with complex requirements to use the format negotiated on one link to set the formats supported on another. Frame references ownership and permissions
opt.h
URL_PROTOCOL_FLAG_NETWORK
#define URL_PROTOCOL_FLAG_NETWORK
Definition: url.h:33
gnutls_url_pull
static ssize_t gnutls_url_pull(gnutls_transport_ptr_t transport, void *buf, size_t len)
Definition: tls_gnutls.c:118
thread.h
AVERROR_EOF
#define AVERROR_EOF
End of file.
Definition: error.h:57
ffurl_write
static int ffurl_write(URLContext *h, const uint8_t *buf, int size)
Write size bytes from buf to the resource accessed by h.
Definition: url.h:202
print_tls_error
static int print_tls_error(URLContext *h, int ret)
Definition: tls_gnutls.c:75
AVOption
AVOption.
Definition: opt.h:429
tls_class
static const AVClass tls_class
Definition: tls_gnutls.c:378
tls_write
static int tls_write(URLContext *h, const uint8_t *buf, int size)
Definition: tls_gnutls.c:344
AVDictionary
Definition: dict.c:32
URLProtocol
Definition: url.h:51
os_support.h
sockaddr_storage
Definition: network.h:111
ff_mutex_unlock
static int ff_mutex_unlock(AVMutex *mutex)
Definition: thread.h:189
TLSContext::cred
gnutls_certificate_credentials_t cred
Definition: tls_gnutls.c:48
TLS_COMMON_OPTIONS
#define TLS_COMMON_OPTIONS(pstruct, options_field)
Definition: tls.h:88
fail
#define fail()
Definition: checkasm.h:216
ffurl_get_short_seek
int ffurl_get_short_seek(void *urlcontext)
Return the current short seek threshold value for this URL.
Definition: avio.c:839
gnutls_mutex
static AVMutex gnutls_mutex
Definition: tls_gnutls.c:55
ff_check_interrupt
int ff_check_interrupt(AVIOInterruptCB *cb)
Check if the user has requested to interrupt a blocking function associated with cb.
Definition: avio.c:855
AV_LOG_TRACE
#define AV_LOG_TRACE
Extremely verbose debugging, useful for libav* development.
Definition: log.h:236
tls_open
static int tls_open(URLContext *h, const char *uri, int flags, AVDictionary **options)
Definition: tls_gnutls.c:219
AV_LOG_ERROR
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:210
AVMutex
#define AVMutex
Definition: thread.h:184
s
#define s(width, name)
Definition: cbs_vp9.c:198
URLContext::flags
int flags
Definition: url.h:40
dtls_class
static const AVClass dtls_class
Definition: tls_gnutls.c:398
tls_close
static int tls_close(URLContext *h)
Definition: tls_gnutls.c:102
ff_udp_set_remote_addr
int ff_udp_set_remote_addr(URLContext *h, const struct sockaddr *dest_addr, socklen_t dest_addr_len, int do_connect)
This function is identical to ff_udp_set_remote_url, except that it takes a sockaddr directly.
Definition: udp.c:472
LIBAVUTIL_VERSION_INT
#define LIBAVUTIL_VERSION_INT
Definition: version.h:85
AVClass
Describe the class of an AVClass context structure.
Definition: log.h:76
NULL
#define NULL
Definition: coverity.c:32
av_default_item_name
const char * av_default_item_name(void *ptr)
Return the context name.
Definition: log.c:242
ff_udp_get_last_recv_addr
void ff_udp_get_last_recv_addr(URLContext *h, struct sockaddr_storage *addr, socklen_t *addr_len)
Definition: udp.c:510
options
Definition: swscale.c:43
c
Undefined Behavior In the C some operations are like signed integer dereferencing freed accessing outside allocated Undefined Behavior must not occur in a C it is not safe even if the output of undefined operations is unused The unsafety may seem nit picking but Optimizing compilers have in fact optimized code on the assumption that no undefined Behavior occurs Optimizing code based on wrong assumptions can and has in some cases lead to effects beyond the output of computations The signed integer overflow problem in speed critical code Code which is highly optimized and works with signed integers sometimes has the problem that often the output of the computation does not c
Definition: undefined.txt:32
av_err2str
#define av_err2str(errnum)
Convenience macro, the return value should be used only directly in function arguments but never stan...
Definition: error.h:122
AV_MUTEX_INITIALIZER
#define AV_MUTEX_INITIALIZER
Definition: thread.h:185
size
int size
Definition: twinvq_data.h:10344
TLSContext::tls_shared
TLSShared tls_shared
Definition: tls_gnutls.c:46
URLProtocol::name
const char * name
Definition: url.h:52
TLSContext::io_err
int io_err
Definition: tls_gnutls.c:50
tls_get_file_handle
static int tls_get_file_handle(URLContext *h)
Definition: tls_gnutls.c:361
gnutls_url_push
static ssize_t gnutls_url_push(gnutls_transport_ptr_t transport, const void *buf, size_t len)
Definition: tls_gnutls.c:150
ff_mutex_lock
static int ff_mutex_lock(AVMutex *mutex)
Definition: thread.h:188
TLSContext::dest_addr
struct sockaddr_storage dest_addr
Definition: tls_gnutls.c:51
tls_handshake
static int tls_handshake(URLContext *h)
Definition: tls_gnutls.c:193
tls_get_short_seek
static int tls_get_short_seek(URLContext *h)
Definition: tls_gnutls.c:367
URLContext
Definition: url.h:35
dtls_open
static int dtls_open(URLContext *h, const char *uri, int flags, AVDictionary **options)
Definition: tls_gnutls.c:319
TLSContext::dest_addr_len
socklen_t dest_addr_len
Definition: tls_gnutls.c:52
ff_tls_protocol
const URLProtocol ff_tls_protocol
Definition: tls_gnutls.c:385
url.h
len
int len
Definition: vorbis_enc_data.h:426
ffurl_closep
int ffurl_closep(URLContext **hh)
Close the resource accessed by the URLContext h, and free the memory used by it.
Definition: avio.c:589
ff_tls_open_underlying
int ff_tls_open_underlying(TLSShared *c, URLContext *parent, const char *uri, AVDictionary **options)
Definition: tls.c:34
ret
ret
Definition: filter_design.txt:187
AVClass::class_name
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:81
avformat.h
network.h
tls.h
status
ov_status_e status
Definition: dnn_backend_openvino.c:100
ff_dtls_protocol
const URLProtocol ff_dtls_protocol
Definition: tls_gnutls.c:405
TLSContext::need_shutdown
int need_shutdown
Definition: tls_gnutls.c:49
options
static const AVOption options[]
Definition: tls_gnutls.c:373
gnutls_pull_timeout
static int gnutls_pull_timeout(gnutls_transport_ptr_t ptr, unsigned int ms)
Definition: tls_gnutls.c:170
tls_read
static int tls_read(URLContext *h, uint8_t *buf, int size)
Definition: tls_gnutls.c:327
TLSContext::session
gnutls_session_t session
Definition: tls_gnutls.c:47
TLSShared
Definition: tls.h:37
AVIO_FLAG_NONBLOCK
#define AVIO_FLAG_NONBLOCK
Use non-blocking mode.
Definition: avio.h:636
av_log
#define av_log(a,...)
Definition: tableprint_vlc.h:27
h
h
Definition: vp9dsp_template.c:2070
AVERROR_EXIT
#define AVERROR_EXIT
Immediate exit was requested; the called function should not be restarted.
Definition: error.h:58
ff_gnutls_deinit
void ff_gnutls_deinit(void)
Definition: tls_gnutls.c:68
ffurl_get_file_handle
int ffurl_get_file_handle(URLContext *h)
Return the file descriptor associated with this URL.
Definition: avio.c:815
ffurl_read
static int ffurl_read(URLContext *h, uint8_t *buf, int size)
Read up to size bytes from the resource accessed by h, and store the read bytes in buf.
Definition: url.h:181