FFmpeg
tls_mbedtls.c
Go to the documentation of this file.
1 /*
2  * TLS/SSL Protocol
3  * Copyright (c) 2018 Thomas Volkert
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 <mbedtls/version.h>
23 #include <mbedtls/ctr_drbg.h>
24 #include <mbedtls/entropy.h>
25 #include <mbedtls/net_sockets.h>
26 #include <mbedtls/platform.h>
27 #include <mbedtls/ssl.h>
28 #include <mbedtls/x509_crt.h>
29 
30 #include "avformat.h"
31 #include "internal.h"
32 #include "url.h"
33 #include "tls.h"
34 #include "libavutil/mem.h"
35 #include "libavutil/parseutils.h"
36 
37 typedef struct TLSContext {
38  const AVClass *class;
40  mbedtls_ssl_context ssl_context;
41  mbedtls_ssl_config ssl_config;
42  mbedtls_entropy_context entropy_context;
43  mbedtls_ctr_drbg_context ctr_drbg_context;
44  mbedtls_x509_crt ca_cert;
45  mbedtls_x509_crt own_cert;
46  mbedtls_pk_context priv_key;
47  char *priv_key_pw;
48 } TLSContext;
49 
50 #define OFFSET(x) offsetof(TLSContext, x)
51 
52 static int tls_close(URLContext *h)
53 {
54  TLSContext *tls_ctx = h->priv_data;
55 
56  mbedtls_ssl_close_notify(&tls_ctx->ssl_context);
57  mbedtls_pk_free(&tls_ctx->priv_key);
58  mbedtls_x509_crt_free(&tls_ctx->ca_cert);
59  mbedtls_x509_crt_free(&tls_ctx->own_cert);
60  mbedtls_ssl_free(&tls_ctx->ssl_context);
61  mbedtls_ssl_config_free(&tls_ctx->ssl_config);
62  mbedtls_ctr_drbg_free(&tls_ctx->ctr_drbg_context);
63  mbedtls_entropy_free(&tls_ctx->entropy_context);
64 
65  ffurl_closep(&tls_ctx->tls_shared.tcp);
66  return 0;
67 }
68 
69 static int handle_transport_error(URLContext *h, const char* func_name, int react_on_eagain, int ret)
70 {
71  switch (ret) {
72  case AVERROR(EAGAIN):
73  return react_on_eagain;
74  case AVERROR_EXIT:
75  return 0;
76  case AVERROR(EPIPE):
77  case AVERROR(ECONNRESET):
78  return MBEDTLS_ERR_NET_CONN_RESET;
79  default:
80  av_log(h, AV_LOG_ERROR, "%s returned 0x%x\n", func_name, ret);
81  errno = EIO;
82  return MBEDTLS_ERR_NET_SEND_FAILED;
83  }
84 }
85 
86 static int mbedtls_send(void *ctx, const unsigned char *buf, size_t len)
87 {
88  URLContext *h = (URLContext*) ctx;
89  int ret = ffurl_write(h, buf, len);
90  if (ret >= 0)
91  return ret;
92 
93  if (h->max_packet_size && len > h->max_packet_size)
94  return MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
95 
96  return handle_transport_error(h, "ffurl_write", MBEDTLS_ERR_SSL_WANT_WRITE, ret);
97 }
98 
99 static int mbedtls_recv(void *ctx, unsigned char *buf, size_t len)
100 {
101  URLContext *h = (URLContext*) ctx;
102  int ret = ffurl_read(h, buf, len);
103  if (ret >= 0)
104  return ret;
105 
106  if (h->max_packet_size && len > h->max_packet_size)
107  return MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
108 
109  return handle_transport_error(h, "ffurl_read", MBEDTLS_ERR_SSL_WANT_READ, ret);
110 }
111 
113 {
114  switch (ret) {
115  case MBEDTLS_ERR_PK_FILE_IO_ERROR:
116  av_log(h, AV_LOG_ERROR, "Read of key file failed. Is it actually there, are the access permissions correct?\n");
117  break;
118  case MBEDTLS_ERR_PK_PASSWORD_REQUIRED:
119  av_log(h, AV_LOG_ERROR, "A password for the private key is missing.\n");
120  break;
121  case MBEDTLS_ERR_PK_PASSWORD_MISMATCH:
122  av_log(h, AV_LOG_ERROR, "The given password for the private key is wrong.\n");
123  break;
124  default:
125  av_log(h, AV_LOG_ERROR, "mbedtls_pk_parse_key returned -0x%x\n", -ret);
126  break;
127  }
128 }
129 
131 {
132  switch (ret) {
133 #if MBEDTLS_VERSION_MAJOR < 3
134  case MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE:
135  av_log(h, AV_LOG_ERROR, "None of the common ciphersuites is usable. Was the local certificate correctly set?\n");
136  break;
137 #else
138  case MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE:
139  av_log(h, AV_LOG_ERROR, "TLS handshake failed.\n");
140  break;
141 #endif
142  case MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE:
143  av_log(h, AV_LOG_ERROR, "A fatal alert message was received from the peer, has the peer a correct certificate?\n");
144  break;
145  case MBEDTLS_ERR_SSL_CA_CHAIN_REQUIRED:
146  av_log(h, AV_LOG_ERROR, "No CA chain is set, but required to operate. Was the CA correctly set?\n");
147  break;
148  case MBEDTLS_ERR_NET_CONN_RESET:
149  av_log(h, AV_LOG_ERROR, "TLS handshake was aborted by peer.\n");
150  break;
151  default:
152  av_log(h, AV_LOG_ERROR, "mbedtls_ssl_handshake returned -0x%x\n", -ret);
153  break;
154  }
155 }
156 
157 static void parse_options(TLSContext *tls_ctxc, const char *uri)
158 {
159  char buf[1024];
160  const char *p = strchr(uri, '?');
161  if (!p)
162  return;
163 
164  if (!tls_ctxc->priv_key_pw && av_find_info_tag(buf, sizeof(buf), "key_password", p))
165  tls_ctxc->priv_key_pw = av_strdup(buf);
166 }
167 
168 static int tls_open(URLContext *h, const char *uri, int flags, AVDictionary **options)
169 {
170  TLSContext *tls_ctx = h->priv_data;
171  TLSShared *shr = &tls_ctx->tls_shared;
172  uint32_t verify_res_flags;
173  int ret;
174 
175  // parse additional options
176  parse_options(tls_ctx, uri);
177 
178  if ((ret = ff_tls_open_underlying(shr, h, uri, options)) < 0)
179  goto fail;
180 
181  mbedtls_ssl_init(&tls_ctx->ssl_context);
182  mbedtls_ssl_config_init(&tls_ctx->ssl_config);
183  mbedtls_entropy_init(&tls_ctx->entropy_context);
184  mbedtls_ctr_drbg_init(&tls_ctx->ctr_drbg_context);
185  mbedtls_x509_crt_init(&tls_ctx->ca_cert);
186  mbedtls_pk_init(&tls_ctx->priv_key);
187 
188  // load trusted CA
189  if (shr->ca_file) {
190  if ((ret = mbedtls_x509_crt_parse_file(&tls_ctx->ca_cert, shr->ca_file)) != 0) {
191  av_log(h, AV_LOG_ERROR, "mbedtls_x509_crt_parse_file for CA cert returned %d\n", ret);
192  goto fail;
193  }
194  }
195 
196  // load own certificate
197  if (shr->cert_file) {
198  if ((ret = mbedtls_x509_crt_parse_file(&tls_ctx->own_cert, shr->cert_file)) != 0) {
199  av_log(h, AV_LOG_ERROR, "mbedtls_x509_crt_parse_file for own cert returned %d\n", ret);
200  goto fail;
201  }
202  }
203 
204  // seed the random number generator
205  if ((ret = mbedtls_ctr_drbg_seed(&tls_ctx->ctr_drbg_context,
206  mbedtls_entropy_func,
207  &tls_ctx->entropy_context,
208  NULL, 0)) != 0) {
209  av_log(h, AV_LOG_ERROR, "mbedtls_ctr_drbg_seed returned %d\n", ret);
210  goto fail;
211  }
212 
213  // load key file
214  if (shr->key_file) {
215  if ((ret = mbedtls_pk_parse_keyfile(&tls_ctx->priv_key,
216  shr->key_file,
217  tls_ctx->priv_key_pw
218 #if MBEDTLS_VERSION_MAJOR >= 3
219  , mbedtls_ctr_drbg_random,
220  &tls_ctx->ctr_drbg_context
221 #endif
222  )) != 0) {
224  goto fail;
225  }
226  }
227 
228  if ((ret = mbedtls_ssl_config_defaults(&tls_ctx->ssl_config,
229  shr->listen ? MBEDTLS_SSL_IS_SERVER : MBEDTLS_SSL_IS_CLIENT,
230  MBEDTLS_SSL_TRANSPORT_STREAM,
231  MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
232  av_log(h, AV_LOG_ERROR, "mbedtls_ssl_config_defaults returned %d\n", ret);
233  goto fail;
234  }
235 
236  mbedtls_ssl_conf_authmode(&tls_ctx->ssl_config,
237  shr->verify ? MBEDTLS_SSL_VERIFY_REQUIRED : MBEDTLS_SSL_VERIFY_NONE);
238  mbedtls_ssl_conf_rng(&tls_ctx->ssl_config, mbedtls_ctr_drbg_random, &tls_ctx->ctr_drbg_context);
239  mbedtls_ssl_conf_ca_chain(&tls_ctx->ssl_config, &tls_ctx->ca_cert, NULL);
240 
241  // set own certificate and private key
242  if ((ret = mbedtls_ssl_conf_own_cert(&tls_ctx->ssl_config, &tls_ctx->own_cert, &tls_ctx->priv_key)) != 0) {
243  av_log(h, AV_LOG_ERROR, "mbedtls_ssl_conf_own_cert returned %d\n", ret);
244  goto fail;
245  }
246 
247  if ((ret = mbedtls_ssl_setup(&tls_ctx->ssl_context, &tls_ctx->ssl_config)) != 0) {
248  av_log(h, AV_LOG_ERROR, "mbedtls_ssl_setup returned %d\n", ret);
249  goto fail;
250  }
251 
252  if (!shr->listen && !shr->numerichost) {
253  if ((ret = mbedtls_ssl_set_hostname(&tls_ctx->ssl_context, shr->host)) != 0) {
254  av_log(h, AV_LOG_ERROR, "mbedtls_ssl_set_hostname returned %d\n", ret);
255  goto fail;
256  }
257  }
258 
259  // set I/O functions to use FFmpeg internal code for transport layer
260  mbedtls_ssl_set_bio(&tls_ctx->ssl_context, shr->tcp, mbedtls_send, mbedtls_recv, NULL);
261 
262  // ssl handshake
263  while ((ret = mbedtls_ssl_handshake(&tls_ctx->ssl_context)) != 0) {
264  if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
266  goto fail;
267  }
268  }
269 
270  if (shr->verify) {
271  // check the result of the certificate verification
272  if ((verify_res_flags = mbedtls_ssl_get_verify_result(&tls_ctx->ssl_context)) != 0) {
273  av_log(h, AV_LOG_ERROR, "mbedtls_ssl_get_verify_result reported problems "\
274  "with the certificate verification, returned flags: %u\n",
275  verify_res_flags);
276  if (verify_res_flags & MBEDTLS_X509_BADCERT_NOT_TRUSTED)
277  av_log(h, AV_LOG_ERROR, "The certificate is not correctly signed by the trusted CA.\n");
278  goto fail;
279  }
280  }
281 
282  return 0;
283 
284 fail:
285  tls_close(h);
286  return AVERROR(EIO);
287 }
288 
289 static int handle_tls_error(URLContext *h, const char* func_name, int ret)
290 {
291  switch (ret) {
292  case MBEDTLS_ERR_SSL_WANT_READ:
293  case MBEDTLS_ERR_SSL_WANT_WRITE:
294  return AVERROR(EAGAIN);
295  case MBEDTLS_ERR_NET_SEND_FAILED:
296  case MBEDTLS_ERR_NET_RECV_FAILED:
297  return AVERROR(EIO);
298  case MBEDTLS_ERR_NET_CONN_RESET:
299  case MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY:
300  av_log(h, AV_LOG_WARNING, "%s reported connection reset by peer\n", func_name);
301  return AVERROR_EOF;
302  default:
303  av_log(h, AV_LOG_ERROR, "%s returned -0x%x\n", func_name, -ret);
304  return AVERROR(EIO);
305  }
306 }
307 
308 static int tls_read(URLContext *h, uint8_t *buf, int size)
309 {
310  TLSContext *tls_ctx = h->priv_data;
311  int ret;
312 
313  tls_ctx->tls_shared.tcp->flags &= ~AVIO_FLAG_NONBLOCK;
314  tls_ctx->tls_shared.tcp->flags |= h->flags & AVIO_FLAG_NONBLOCK;
315  if ((ret = mbedtls_ssl_read(&tls_ctx->ssl_context, buf, size)) > 0) {
316  // return read length
317  return ret;
318  }
319 
320  return handle_tls_error(h, "mbedtls_ssl_read", ret);
321 }
322 
323 static int tls_write(URLContext *h, const uint8_t *buf, int size)
324 {
325  TLSContext *tls_ctx = h->priv_data;
326  int ret;
327 
328  tls_ctx->tls_shared.tcp->flags &= ~AVIO_FLAG_NONBLOCK;
329  tls_ctx->tls_shared.tcp->flags |= h->flags & AVIO_FLAG_NONBLOCK;
330  if ((ret = mbedtls_ssl_write(&tls_ctx->ssl_context, buf, size)) > 0) {
331  // return written length
332  return ret;
333  }
334 
335  return handle_tls_error(h, "mbedtls_ssl_write", ret);
336 }
337 
339 {
340  TLSContext *c = h->priv_data;
341  return ffurl_get_file_handle(c->tls_shared.tcp);
342 }
343 
345 {
346  TLSContext *s = h->priv_data;
347  return ffurl_get_short_seek(s->tls_shared.tcp);
348 }
349 
350 static const AVOption options[] = {
351  TLS_COMMON_OPTIONS(TLSContext, tls_shared), \
352  {"key_password", "Password for the private key file", OFFSET(priv_key_pw), AV_OPT_TYPE_STRING, .flags = TLS_OPTFL }, \
353  { NULL }
354 };
355 
356 static const AVClass tls_class = {
357  .class_name = "tls",
358  .item_name = av_default_item_name,
359  .option = options,
360  .version = LIBAVUTIL_VERSION_INT,
361 };
362 
364  .name = "tls",
365  .url_open2 = tls_open,
366  .url_read = tls_read,
367  .url_write = tls_write,
368  .url_close = tls_close,
369  .url_get_file_handle = tls_get_file_handle,
370  .url_get_short_seek = tls_get_short_seek,
371  .priv_data_size = sizeof(TLSContext),
373  .priv_data_class = &tls_class,
374 };
AV_LOG_WARNING
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:186
TLSContext
Definition: tls_gnutls.c:48
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
av_find_info_tag
int av_find_info_tag(char *arg, int arg_size, const char *tag1, const char *info)
Attempt to find a specific tag in a URL.
Definition: parseutils.c:753
URL_PROTOCOL_FLAG_NETWORK
#define URL_PROTOCOL_FLAG_NETWORK
Definition: url.h:33
TLSContext::entropy_context
mbedtls_entropy_context entropy_context
Definition: tls_mbedtls.c:42
AVERROR_EOF
#define AVERROR_EOF
End of file.
Definition: error.h:57
handle_pk_parse_error
static void handle_pk_parse_error(URLContext *h, int ret)
Definition: tls_mbedtls.c:112
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
AVOption
AVOption.
Definition: opt.h:357
AVDictionary
Definition: dict.c:34
URLProtocol
Definition: url.h:51
TLSShared::verify
int verify
Definition: tls.h:31
TLSShared::listen
int listen
Definition: tls.h:34
TLSContext::ctr_drbg_context
mbedtls_ctr_drbg_context ctr_drbg_context
Definition: tls_mbedtls.c:43
TLS_COMMON_OPTIONS
#define TLS_COMMON_OPTIONS(pstruct, options_field)
Definition: tls.h:46
fail
#define fail()
Definition: checkasm.h:181
ffurl_get_short_seek
int ffurl_get_short_seek(void *urlcontext)
Return the current short seek threshold value for this URL.
Definition: avio.c:838
TLSContext::ca_cert
mbedtls_x509_crt ca_cert
Definition: tls_mbedtls.c:44
tls_close
static int tls_close(URLContext *h)
Definition: tls_mbedtls.c:52
AV_LOG_ERROR
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:180
mbedtls_recv
static int mbedtls_recv(void *ctx, unsigned char *buf, size_t len)
Definition: tls_mbedtls.c:99
s
#define s(width, name)
Definition: cbs_vp9.c:198
TLS_OPTFL
#define TLS_OPTFL
Definition: tls.h:45
URLContext::flags
int flags
Definition: url.h:40
TLSContext::priv_key
mbedtls_pk_context priv_key
Definition: tls_mbedtls.c:46
ctx
AVFormatContext * ctx
Definition: movenc.c:49
TLSContext::ssl_context
mbedtls_ssl_context ssl_context
Definition: tls_mbedtls.c:40
internal.h
LIBAVUTIL_VERSION_INT
#define LIBAVUTIL_VERSION_INT
Definition: version.h:85
parse_options
static void parse_options(TLSContext *tls_ctxc, const char *uri)
Definition: tls_mbedtls.c:157
AVClass
Describe the class of an AVClass context structure.
Definition: log.h:66
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:237
parseutils.h
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
TLSShared::host
char * host
Definition: tls.h:36
OFFSET
#define OFFSET(x)
Definition: tls_mbedtls.c:50
ff_tls_protocol
const URLProtocol ff_tls_protocol
Definition: tls_mbedtls.c:363
TLSContext::ssl_config
mbedtls_ssl_config ssl_config
Definition: tls_mbedtls.c:41
mbedtls_send
static int mbedtls_send(void *ctx, const unsigned char *buf, size_t len)
Definition: tls_mbedtls.c:86
size
int size
Definition: twinvq_data.h:10344
handle_handshake_error
static void handle_handshake_error(URLContext *h, int ret)
Definition: tls_mbedtls.c:130
TLSContext::tls_shared
TLSShared tls_shared
Definition: tls_gnutls.c:50
URLProtocol::name
const char * name
Definition: url.h:52
tls_read
static int tls_read(URLContext *h, uint8_t *buf, int size)
Definition: tls_mbedtls.c:308
handle_transport_error
static int handle_transport_error(URLContext *h, const char *func_name, int react_on_eagain, int ret)
Definition: tls_mbedtls.c:69
options
static const AVOption options[]
Definition: tls_mbedtls.c:350
URLContext
Definition: url.h:35
url.h
len
int len
Definition: vorbis_enc_data.h:426
TLSShared::cert_file
char * cert_file
Definition: tls.h:32
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:588
ff_tls_open_underlying
int ff_tls_open_underlying(TLSShared *c, URLContext *parent, const char *uri, AVDictionary **options)
Definition: tls.c:67
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:71
TLSShared::ca_file
char * ca_file
Definition: tls.h:30
avformat.h
tls_class
static const AVClass tls_class
Definition: tls_mbedtls.c:356
tls.h
TLSContext::own_cert
mbedtls_x509_crt own_cert
Definition: tls_mbedtls.c:45
TLSShared::key_file
char * key_file
Definition: tls.h:33
tls_get_short_seek
static int tls_get_short_seek(URLContext *h)
Definition: tls_mbedtls.c:344
tls_open
static int tls_open(URLContext *h, const char *uri, int flags, AVDictionary **options)
Definition: tls_mbedtls.c:168
av_strdup
char * av_strdup(const char *s)
Duplicate a string.
Definition: mem.c:272
mem.h
tls_write
static int tls_write(URLContext *h, const uint8_t *buf, int size)
Definition: tls_mbedtls.c:323
TLSShared
Definition: tls.h:29
AVIO_FLAG_NONBLOCK
#define AVIO_FLAG_NONBLOCK
Use non-blocking mode.
Definition: avio.h:636
handle_tls_error
static int handle_tls_error(URLContext *h, const char *func_name, int ret)
Definition: tls_mbedtls.c:289
flags
#define flags(name, subs,...)
Definition: cbs_av1.c:474
tls_get_file_handle
static int tls_get_file_handle(URLContext *h)
Definition: tls_mbedtls.c:338
TLSContext::priv_key_pw
char * priv_key_pw
Definition: tls_mbedtls.c:47
TLSShared::numerichost
int numerichost
Definition: tls.h:40
av_log
#define av_log(a,...)
Definition: tableprint_vlc.h:27
h
h
Definition: vp9dsp_template.c:2038
AVERROR_EXIT
#define AVERROR_EXIT
Immediate exit was requested; the called function should not be restarted.
Definition: error.h:58
AV_OPT_TYPE_STRING
@ AV_OPT_TYPE_STRING
Definition: opt.h:249
ffurl_get_file_handle
int ffurl_get_file_handle(URLContext *h)
Return the file descriptor associated with this URL.
Definition: avio.c:814
TLSShared::tcp
URLContext * tcp
Definition: tls.h:42
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