FFmpeg
Loading...
Searching...
No Matches
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#include <mbedtls/debug.h>
30#include <mbedtls/timing.h>
31#ifdef MBEDTLS_PSA_CRYPTO_C
32#include <psa/crypto.h>
33#endif
34
35#include "config_components.h"
36
37#include "avformat.h"
38#include "internal.h"
39#include "network.h"
40#include "url.h"
41#include "tls.h"
42#include "libavutil/mem.h"
44#include "libavutil/avstring.h"
46
47static int mbedtls_x509_fingerprint(char *cert_buf, size_t cert_sz, char **fingerprint)
48{
49 unsigned char md[32];
50 size_t n = sizeof(md);
51 AVBPrint buf;
52 int ret;
53 mbedtls_x509_crt crt;
54
55 mbedtls_x509_crt_init(&crt);
56
57 if ((ret = mbedtls_x509_crt_parse(&crt, cert_buf, cert_sz)) != 0) {
58 mbedtls_x509_crt_free(&crt);
59 return AVERROR(EINVAL);
60 }
61
62 if ((ret = mbedtls_sha256(crt.raw.p, crt.raw.len, md, 0)) != 0) {
63 mbedtls_x509_crt_free(&crt);
64 return AVERROR(EINVAL);
65 }
66
67 av_bprint_init(&buf, n*3, n*3);
68
69 for (int i = 0; i < n - 1; i++)
70 av_bprintf(&buf, "%02X:", md[i]);
71 av_bprintf(&buf, "%02X", md[n - 1]);
72
73 return av_bprint_finalize(&buf, fingerprint);
74}
75
76int ff_ssl_read_key_cert(char *key_url, char *cert_url, char *key_buf, size_t key_sz, char *cert_buf, size_t cert_sz, char **fingerprint)
77{
78 int ret = 0;
79 AVBPrint key_bp, cert_bp;
82
83 ret = ff_url_read_all(key_url, &key_bp);
84 if (ret < 0) {
85 av_log(NULL, AV_LOG_ERROR, "TLS: Failed to open key file %s\n", key_url);
86 goto end;
87 }
88
89 ret = ff_url_read_all(cert_url, &cert_bp);
90 if (ret < 0) {
91 av_log(NULL, AV_LOG_ERROR, "TLS: Failed to open cert file %s\n", cert_url);
92 goto end;
93 }
94
95 if (key_sz < key_bp.size || cert_sz < cert_bp.size) {
96 av_log(NULL, AV_LOG_ERROR, "TLS: Key or Cert buffer is too samall\n");
98 goto end;
99 }
100
101 key_buf = key_bp.str;
102 cert_buf = cert_bp.str;
103
104 ret = mbedtls_x509_fingerprint(cert_buf, cert_sz, fingerprint);
105 if (ret < 0)
106 av_log(NULL, AV_LOG_ERROR, "TLS: Failed to generate fingerprint\n");
107end:
108 av_bprint_finalize(&key_bp, NULL);
109 av_bprint_finalize(&cert_bp, NULL);
110 return ret;
111}
112
113static int mbedtls_gen_pkey(mbedtls_pk_context *key)
114{
115 int ret = 0;
116 mbedtls_entropy_context entropy;
117 mbedtls_ctr_drbg_context ctr_drbg;
118
119 mbedtls_entropy_init(&entropy);
120 mbedtls_ctr_drbg_init(&ctr_drbg);
121
122 if ((ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func,
123 &entropy, NULL, 0)) != 0) {
124 av_log(NULL, AV_LOG_ERROR, "mbedtls_ctr_drbg_seed returned %d\n", ret);
125 goto end;
126 }
127
128 if ((ret = mbedtls_pk_setup(key,
129 mbedtls_pk_info_from_type(MBEDTLS_PK_ECKEY))) != 0) {
130 av_log(NULL, AV_LOG_ERROR, "mbedtls_pk_setup returned %d\n", ret);
131 goto end;
132 }
133 /**
134 * See RFC 8827 section 6.5,
135 * All implementations MUST support DTLS 1.2 with the
136 * TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 cipher suite
137 * and the P-256 curve.
138 */
139 if ((ret = mbedtls_ecp_gen_key(MBEDTLS_ECP_DP_SECP256R1,
140 mbedtls_pk_ec(*key),
141 mbedtls_ctr_drbg_random, &ctr_drbg)) != 0) {
142 av_log(NULL, AV_LOG_ERROR, "mbedtls_ecp_gen_key returned %d\n", ret);
143 goto end;
144 }
145end:
146 mbedtls_entropy_free(&entropy);
147 mbedtls_ctr_drbg_free(&ctr_drbg);
148 return ret;
149}
150
151static int mbedtls_gen_x509_cert(mbedtls_pk_context *key, char *cert_buf, size_t cert_sz)
152{
153 int ret = 0;
154 const char *name = "CN=lavf";
155 time_t now;
156 struct tm tm;
157 char not_before[16], not_after[16];
158 unsigned char serial[20];
159 mbedtls_entropy_context entropy;
160 mbedtls_ctr_drbg_context ctr_drbg;
161 mbedtls_x509write_cert crt;
162
163 mbedtls_entropy_init(&entropy);
164 mbedtls_ctr_drbg_init(&ctr_drbg);
165 mbedtls_x509write_crt_init(&crt);
166
167 if ((ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, NULL, 0)) != 0) {
168 av_log(NULL, AV_LOG_ERROR, "mbedtls_ctr_drbg_seed returned %d\n", ret);
169 goto end;
170 }
171
172 mbedtls_x509write_crt_set_subject_key(&crt, key);
173 mbedtls_x509write_crt_set_issuer_key(&crt, key);
174 if ((ret = mbedtls_x509write_crt_set_subject_name(&crt, name)) != 0) {
175 av_log(NULL, AV_LOG_ERROR, "mbedtls_x509write_crt_set_subject_name returned %d\n", ret);
176 goto end;
177 }
178
179 if ((ret = mbedtls_x509write_crt_set_issuer_name(&crt, name)) != 0) {
180 av_log(NULL, AV_LOG_ERROR, "mbedtls_x509write_crt_set_issuer_name returned %d\n", ret);
181 goto end;
182 }
183 mbedtls_x509write_crt_set_version(&crt, MBEDTLS_X509_CRT_VERSION_3);
184 mbedtls_x509write_crt_set_md_alg(&crt, MBEDTLS_MD_SHA256);
185
186 ret = av_random_bytes((uint8_t *)serial, sizeof(serial));
187 if (ret < 0) {
188 av_log(NULL, AV_LOG_ERROR, "Failed to generate random serial number!\n");
189 return ret;
190 }
191
192 if ((ret = mbedtls_x509write_crt_set_serial_raw(&crt, serial, sizeof(serial))) != 0) {
193 av_log(NULL, AV_LOG_ERROR, "mbedtls_x509write_crt_set_serial_raw returned %d\n", ret);
194 goto end;
195 }
196
197 time(&now);
198 gmtime_r(&now, &tm);
199 strftime(not_before, sizeof(not_before), "%Y%m%d%H%M%S", &tm);
200 tm.tm_year += 1;
201 strftime(not_after, sizeof(not_after), "%Y%m%d%H%M%S", &tm);
202
203 if ((ret = mbedtls_x509write_crt_set_validity(&crt, not_before, not_after)) != 0) {
204 av_log(NULL, AV_LOG_ERROR, "mbedtls_x509write_crt_set_validity returned %d\n", ret);
205 goto end;
206 }
207
208 if ((ret = mbedtls_x509write_crt_pem(&crt, cert_buf, cert_sz,
209 mbedtls_ctr_drbg_random, &ctr_drbg)) != 0) {
210 av_log(NULL, AV_LOG_ERROR, "mbedtls_x509write_crt_pem returned %d\n", ret);
211 return ret;
212 }
213
214end:
215 mbedtls_entropy_free(&entropy);
216 mbedtls_ctr_drbg_free(&ctr_drbg);
217 mbedtls_x509write_crt_free(&crt);
218 return ret;
219}
220
221int ff_ssl_gen_key_cert(char *key_buf, size_t key_sz, char *cert_buf, size_t cert_sz, char **fingerprint)
222{
223 int ret = 0;
224 mbedtls_pk_context key;
225
226 mbedtls_pk_init(&key);
227
228 if ((ret = mbedtls_gen_pkey(&key)) != 0)
229 goto end;
230
231 if ((ret = mbedtls_pk_write_key_pem(&key, key_buf, key_sz)) != 0)
232 goto end;
233
234 if ((ret = mbedtls_gen_x509_cert(&key, cert_buf, cert_sz)) != 0)
235 goto end;
236
237 ret = mbedtls_x509_fingerprint(cert_buf, cert_sz, fingerprint);
238 if (ret < 0)
239 av_log(NULL, AV_LOG_ERROR, "TLS: Failed to generate fingerprint\n");
240
241end:
242 mbedtls_pk_free(&key);
243 return ret;
244}
245
246typedef struct dtls_srtp_keys {
247 unsigned char master_secret[48];
248 unsigned char randbytes[64];
249 mbedtls_tls_prf_types tls_prf_type;
251
252typedef struct TLSContext {
254 mbedtls_ssl_context ssl_context;
255 mbedtls_ssl_config ssl_config;
256 mbedtls_entropy_context entropy_context;
257 mbedtls_ctr_drbg_context ctr_drbg_context;
258 mbedtls_timing_delay_context timer;
259 mbedtls_x509_crt ca_cert;
260 mbedtls_x509_crt own_cert;
261 mbedtls_pk_context priv_key;
265 socklen_t dest_addr_len;
266} TLSContext;
267
269{
270 TLSContext *tls_ctx = h->priv_data;
271 TLSShared *shr = &tls_ctx->tls_shared;
272
273 if (shr->is_dtls)
274 shr->udp = sock;
275 else
276 shr->tcp = sock;
277
278 return 0;
279}
280
281#if defined(MBEDTLS_SSL_DTLS_SRTP)
282static void dtls_srtp_key_derivation(void *p_expkey,
283 mbedtls_ssl_key_export_type secret_type,
284 const unsigned char *secret,
285 size_t secret_len,
286 const unsigned char client_random[32],
287 const unsigned char server_random[32],
288 mbedtls_tls_prf_types tls_prf_type)
289{
290 dtls_srtp_keys *keys = (dtls_srtp_keys *) p_expkey;
291
292 if (secret_len != sizeof(keys->master_secret))
293 return;
294
295 memcpy(keys->master_secret, secret, secret_len);
296 memcpy(keys->randbytes, client_random, 32);
297 memcpy(keys->randbytes + 32, server_random, 32);
298 keys->tls_prf_type = tls_prf_type;
299}
300#endif
301
302int ff_dtls_export_materials(URLContext *h, char *dtls_srtp_materials, size_t materials_sz)
303{
304 int ret = 0;
305 TLSContext *tls_ctx = h->priv_data;
306#if defined(MBEDTLS_SSL_DTLS_SRTP)
307 const char* dst = "EXTRACTOR-dtls_srtp";
308 mbedtls_dtls_srtp_info dtls_srtp_negotiation_result;
309 mbedtls_ssl_get_dtls_srtp_negotiation_result(&tls_ctx->ssl_context, &dtls_srtp_negotiation_result);
310
311 if ((ret = mbedtls_ssl_tls_prf(tls_ctx->srtp_key.tls_prf_type,
312 tls_ctx->srtp_key.master_secret,
313 sizeof(tls_ctx->srtp_key.master_secret),
314 dst,
315 tls_ctx->srtp_key.randbytes,
316 sizeof(tls_ctx->srtp_key.randbytes),
317 dtls_srtp_materials,
318 materials_sz)) != 0) {
319 av_log(h, AV_LOG_ERROR,"mbedtls_ssl_tls_prf returned %d\n", ret);
320 ret = AVERROR(EINVAL);
321 }
322#else
323 av_log(h, AV_LOG_ERROR, "DTLS-SRTP is not supported in this mbedtls build\n");
324 ret = AVERROR(ENOSYS);
325#endif
326 return ret;
327}
328
329#define OFFSET(x) offsetof(TLSContext, x)
330
332{
333 TLSContext *tls_ctx = h->priv_data;
334 TLSShared *shr = &tls_ctx->tls_shared;
335
336 mbedtls_ssl_close_notify(&tls_ctx->ssl_context);
337 mbedtls_pk_free(&tls_ctx->priv_key);
338 mbedtls_x509_crt_free(&tls_ctx->ca_cert);
339 mbedtls_x509_crt_free(&tls_ctx->own_cert);
340 mbedtls_ssl_free(&tls_ctx->ssl_context);
341 mbedtls_ssl_config_free(&tls_ctx->ssl_config);
342 mbedtls_ctr_drbg_free(&tls_ctx->ctr_drbg_context);
343 mbedtls_entropy_free(&tls_ctx->entropy_context);
344 if (!shr->external_sock)
345 ffurl_closep(shr->is_dtls ? &shr->udp : &shr->tcp);
346 return 0;
347}
348
349static int handle_transport_error(URLContext *h, const char* func_name, int react_on_eagain, int ret)
350{
351 switch (ret) {
352 case AVERROR(EAGAIN):
353 return react_on_eagain;
354 case AVERROR_EXIT:
355 return 0;
356 case AVERROR(EPIPE):
357 case AVERROR(ECONNRESET):
358 return MBEDTLS_ERR_NET_CONN_RESET;
359 default:
360 av_log(h, AV_LOG_ERROR, "%s returned 0x%x\n", func_name, ret);
361 errno = EIO;
362 return MBEDTLS_ERR_NET_SEND_FAILED;
363 }
364}
365
366static int mbedtls_send(void *ctx, const unsigned char *buf, size_t len)
367{
368 TLSContext *tls_ctx = (TLSContext*) ctx;
369 TLSShared *shr = &tls_ctx->tls_shared;
370 URLContext *h = shr->is_dtls ? shr->udp : shr->tcp;
371 int ret = ffurl_write(h, buf, len);
372 if (ret >= 0)
373 return ret;
374
375 if (h->max_packet_size && len > h->max_packet_size)
376 return MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
377
378 return handle_transport_error(h, "ffurl_write", MBEDTLS_ERR_SSL_WANT_WRITE, ret);
379}
380
381static int mbedtls_recv(void *ctx, unsigned char *buf, size_t len)
382{
383 TLSContext *tls_ctx = (TLSContext*) ctx;
384 TLSShared *shr = &tls_ctx->tls_shared;
385 URLContext *h = shr->is_dtls ? shr->udp : shr->tcp;
386 int ret = ffurl_read(h, buf, len);
387 if (ret >= 0) {
388#if CONFIG_UDP_PROTOCOL
389 if (shr->is_dtls && shr->listen && !tls_ctx->dest_addr_len) {
390 int err_ret;
391
392 ff_udp_get_last_recv_addr(shr->udp, &tls_ctx->dest_addr, &tls_ctx->dest_addr_len);
393 err_ret = ff_udp_set_remote_addr(shr->udp, (struct sockaddr *)&tls_ctx->dest_addr, tls_ctx->dest_addr_len, 1);
394 if (err_ret < 0) {
395 av_log(tls_ctx, AV_LOG_ERROR, "Failed connecting udp context\n");
396 return err_ret;
397 }
398 av_log(tls_ctx, AV_LOG_TRACE, "Set UDP remote addr on UDP socket, now 'connected'\n");
399 }
400#endif
401 /* Skip non-DTLS packets such as STUN to avoid failures. */
402 if (shr->is_dtls && !ff_is_dtls_packet(buf, ret))
403 return MBEDTLS_ERR_SSL_WANT_READ;
404 return ret;
405 }
406 if (h->max_packet_size && len > h->max_packet_size)
407 return MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
408
409 return handle_transport_error(h, "ffurl_read", MBEDTLS_ERR_SSL_WANT_READ, ret);
410}
411
412static void mbedtls_debug(void *ctx, int lvl, const char *file, int line, const char *msg)
413{
415 int av_lvl = lvl >= 4 ? AV_LOG_TRACE : AV_LOG_DEBUG;
416 av_log(h, av_lvl, "%s:%d: %s", av_basename(file), line, msg);
417}
418
419static void handle_pk_parse_error(URLContext *h, int ret)
420{
421 switch (ret) {
422 case MBEDTLS_ERR_PK_FILE_IO_ERROR:
423 av_log(h, AV_LOG_ERROR, "Read of key file failed. Is it actually there, are the access permissions correct?\n");
424 break;
425 case MBEDTLS_ERR_PK_PASSWORD_REQUIRED:
426 av_log(h, AV_LOG_ERROR, "A password for the private key is missing.\n");
427 break;
428 case MBEDTLS_ERR_PK_PASSWORD_MISMATCH:
429 av_log(h, AV_LOG_ERROR, "The given password for the private key is wrong.\n");
430 break;
431 default:
432 av_log(h, AV_LOG_ERROR, "mbedtls_pk_parse_key returned -0x%x\n", -ret);
433 break;
434 }
435}
436
437static void handle_handshake_error(URLContext *h, int ret)
438{
439 switch (ret) {
440#if MBEDTLS_VERSION_MAJOR < 3
441 case MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE:
442 av_log(h, AV_LOG_ERROR, "None of the common ciphersuites is usable. Was the local certificate correctly set?\n");
443 break;
444#else
445 case MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE:
446 av_log(h, AV_LOG_ERROR, "TLS handshake failed.\n");
447 break;
448 case MBEDTLS_ERR_SSL_BAD_PROTOCOL_VERSION:
449 av_log(h, AV_LOG_ERROR, "TLS protocol version mismatch.\n");
450 break;
451#endif
452 case MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE:
453 av_log(h, AV_LOG_ERROR, "A fatal alert message was received from the peer, has the peer a correct certificate?\n");
454 break;
455 case MBEDTLS_ERR_SSL_CA_CHAIN_REQUIRED:
456 av_log(h, AV_LOG_ERROR, "No CA chain is set, but required to operate. Was the CA correctly set?\n");
457 break;
458 case MBEDTLS_ERR_SSL_INTERNAL_ERROR:
459 av_log(h, AV_LOG_ERROR, "Internal error encountered.\n");
460 break;
461 case MBEDTLS_ERR_NET_CONN_RESET:
462 av_log(h, AV_LOG_ERROR, "TLS handshake was aborted by peer.\n");
463 break;
464 case MBEDTLS_ERR_X509_CERT_VERIFY_FAILED:
465 av_log(h, AV_LOG_ERROR, "Certificate verification failed.\n");
466 break;
467 default:
468 av_log(h, AV_LOG_ERROR, "mbedtls_ssl_handshake returned -0x%x\n", -ret);
469 break;
470 }
471}
472
474{
475 TLSContext *tls_ctx = h->priv_data;
476 TLSShared *shr = &tls_ctx->tls_shared;
477 URLContext *uc = shr->is_dtls ? shr->udp : shr->tcp;
478 uint32_t verify_res_flags;
479 int ret;
480
482
483 while (1) {
484 ret = mbedtls_ssl_handshake(&tls_ctx->ssl_context);
485
486 if (!ret)
487 break;
488 if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
490 return ret;
491 }
492 }
493
494 if (shr->verify) {
495 // check the result of the certificate verification
496 if ((verify_res_flags = mbedtls_ssl_get_verify_result(&tls_ctx->ssl_context)) != 0) {
497 av_log(h, AV_LOG_ERROR, "mbedtls_ssl_get_verify_result reported problems "\
498 "with the certificate verification, returned flags: %"PRIu32"\n",
499 verify_res_flags);
500 if (verify_res_flags & MBEDTLS_X509_BADCERT_NOT_TRUSTED)
501 av_log(h, AV_LOG_ERROR, "The certificate is not correctly signed by the trusted CA.\n");
502 return AVERROR(EIO);
503 }
504 }
505
506 return ret;
507}
508
509static int tls_open(URLContext *h, const char *uri, int flags, AVDictionary **options)
510{
511 TLSContext *tls_ctx = h->priv_data;
512 TLSShared *shr = &tls_ctx->tls_shared;
513 uint32_t verify_res_flags;
514 int ret;
515#if defined(MBEDTLS_SSL_DTLS_SRTP)
516 const mbedtls_ssl_srtp_profile profiles[] = {
517 MBEDTLS_TLS_SRTP_AES128_CM_HMAC_SHA1_80,
518 MBEDTLS_TLS_SRTP_UNSET
519 };
520#endif
521
522 if (!shr->external_sock) {
523 if ((ret = ff_tls_open_underlying(shr, h, uri, options)) < 0)
524 goto fail;
525 } else if (!shr->host) {
526 if ((ret = ff_tls_parse_host(shr, shr->underlying_host, sizeof(shr->underlying_host), NULL, uri)) < 0)
527 goto fail;
528 }
529
530#ifdef MBEDTLS_PSA_CRYPTO_C
531 if ((ret = psa_crypto_init()) != PSA_SUCCESS) {
532 av_log(h, AV_LOG_ERROR, "psa_crypto_init returned %d\n", ret);
533 goto fail;
534 }
535#endif
536
537 mbedtls_ssl_init(&tls_ctx->ssl_context);
538 mbedtls_ssl_config_init(&tls_ctx->ssl_config);
539 mbedtls_entropy_init(&tls_ctx->entropy_context);
540 mbedtls_ctr_drbg_init(&tls_ctx->ctr_drbg_context);
541 mbedtls_x509_crt_init(&tls_ctx->ca_cert);
542 mbedtls_pk_init(&tls_ctx->priv_key);
543
545 mbedtls_ssl_conf_dbg(&tls_ctx->ssl_config, mbedtls_debug, shr->is_dtls ? shr->udp : shr->tcp);
546 /*
547 * Note: we can't call mbedtls_debug_set_threshold() here because
548 * it's global state. The user is thus expected to manage this.
549 */
550 }
551
552 // load trusted CA
553 if (shr->ca_file) {
554 if ((ret = mbedtls_x509_crt_parse_file(&tls_ctx->ca_cert, shr->ca_file)) != 0) {
555 av_log(h, AV_LOG_ERROR, "mbedtls_x509_crt_parse_file for CA cert returned %d\n", ret);
556 goto fail;
557 }
558 }
559
560 // load own certificate
561 if (shr->cert_file) {
562 if ((ret = mbedtls_x509_crt_parse_file(&tls_ctx->own_cert, shr->cert_file)) != 0) {
563 av_log(h, AV_LOG_ERROR, "mbedtls_x509_crt_parse_file for own cert returned %d\n", ret);
564 goto fail;
565 }
566 } else if (shr->cert_buf) {
567 if ((ret = mbedtls_x509_crt_parse(&tls_ctx->own_cert, shr->cert_buf, strlen(shr->cert_buf) + 1)) != 0) {
568 av_log(h, AV_LOG_ERROR, "mbedtls_x509_crt_parse for own cert returned %d\n", ret);
569 goto fail;
570 }
571 }
572
573 // seed the random number generator
574 if ((ret = mbedtls_ctr_drbg_seed(&tls_ctx->ctr_drbg_context,
575 mbedtls_entropy_func,
576 &tls_ctx->entropy_context,
577 NULL, 0)) != 0) {
578 av_log(h, AV_LOG_ERROR, "mbedtls_ctr_drbg_seed returned %d\n", ret);
579 goto fail;
580 }
581
582 // load key file
583 if (shr->key_file) {
584 if ((ret = mbedtls_pk_parse_keyfile(&tls_ctx->priv_key,
585 shr->key_file,
586 tls_ctx->priv_key_pw
587#if MBEDTLS_VERSION_MAJOR >= 3
588 , mbedtls_ctr_drbg_random,
589 &tls_ctx->ctr_drbg_context
590#endif
591 )) != 0) {
593 goto fail;
594 }
595 } else if (shr->key_buf) {
596 if ((ret = mbedtls_pk_parse_key(&tls_ctx->priv_key,
597 shr->key_buf,
598 strlen(shr->key_buf) + 1,
599 NULL,
600 0
601#if MBEDTLS_VERSION_MAJOR >= 3
602 , mbedtls_ctr_drbg_random,
603 &tls_ctx->ctr_drbg_context
604#endif
605 )) != 0) {
607 goto fail;
608 }
609 }
610
611 if (shr->listen && !shr->cert_file && !shr->cert_buf && !shr->key_file && !shr->key_buf) {
612 char buf[4096];
613 if ((ret = mbedtls_gen_pkey(&tls_ctx->priv_key)) != 0) {
614 av_log(h, AV_LOG_ERROR, "failed to generate priv_key, returned %d\n", ret);
615 goto fail;
616 }
617 if ((ret = mbedtls_gen_x509_cert(&tls_ctx->priv_key, buf, sizeof(buf))) != 0) {
618 av_log(h, AV_LOG_ERROR, "failed to generate cert, returned %d\n", ret);
619 goto fail;
620 }
621 if ((ret = mbedtls_x509_crt_parse(&tls_ctx->own_cert, buf, sizeof(buf))) != 0) {
622 av_log(h, AV_LOG_ERROR, "failed to parse generated cert, returned %d\n", ret);
623 goto fail;
624 }
625 }
626
627 if ((ret = mbedtls_ssl_config_defaults(&tls_ctx->ssl_config,
628 shr->listen ? MBEDTLS_SSL_IS_SERVER : MBEDTLS_SSL_IS_CLIENT,
629 shr->is_dtls ? MBEDTLS_SSL_TRANSPORT_DATAGRAM : MBEDTLS_SSL_TRANSPORT_STREAM,
630 MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
631 av_log(h, AV_LOG_ERROR, "mbedtls_ssl_config_defaults returned %d\n", ret);
632 goto fail;
633 }
634
635#ifdef MBEDTLS_SSL_PROTO_TLS1_3
636 // this version does not allow disabling certificate verification with TLSv1.3 (yes, really).
637 if (mbedtls_version_get_number() == 0x03060000 && !shr->verify) {
638 av_log(h, AV_LOG_INFO, "Forcing TLSv1.2 because certificate verification is disabled\n");
639 mbedtls_ssl_conf_max_tls_version(&tls_ctx->ssl_config, MBEDTLS_SSL_VERSION_TLS1_2);
640 }
641#endif
642
643 // not VERIFY_REQUIRED because we manually check after handshake
644 mbedtls_ssl_conf_authmode(&tls_ctx->ssl_config,
645 shr->verify ? MBEDTLS_SSL_VERIFY_OPTIONAL : MBEDTLS_SSL_VERIFY_NONE);
646 mbedtls_ssl_conf_rng(&tls_ctx->ssl_config, mbedtls_ctr_drbg_random, &tls_ctx->ctr_drbg_context);
647 mbedtls_ssl_conf_ca_chain(&tls_ctx->ssl_config, &tls_ctx->ca_cert, NULL);
648
649 // set own certificate and private key
650 if ((ret = mbedtls_ssl_conf_own_cert(&tls_ctx->ssl_config, &tls_ctx->own_cert, &tls_ctx->priv_key)) != 0) {
651 av_log(h, AV_LOG_ERROR, "mbedtls_ssl_conf_own_cert returned %d\n", ret);
652 goto fail;
653 }
654 if (shr->is_dtls) {
655 mbedtls_ssl_conf_dtls_cookies(&tls_ctx->ssl_config, NULL, NULL, NULL);
656 if (shr->use_srtp) {
657#if defined(MBEDTLS_SSL_DTLS_SRTP)
658 if ((ret = mbedtls_ssl_conf_dtls_srtp_protection_profiles(&tls_ctx->ssl_config, profiles)) != 0) {
659 av_log(h, AV_LOG_ERROR, "mbedtls_ssl_conf_dtls_srtp_protection_profiles returned %d\n", ret);
660 goto fail;
661 }
662 mbedtls_ssl_set_export_keys_cb(&tls_ctx->ssl_context, dtls_srtp_key_derivation, &tls_ctx->srtp_key);
663#else
664 av_log(h, AV_LOG_ERROR, "DTLS-SRTP is not supported in this mbedtls build\n");
665 ret = AVERROR(ENOSYS);
666 goto fail;
667#endif
668 }
669
670 }
671 if ((ret = mbedtls_ssl_setup(&tls_ctx->ssl_context, &tls_ctx->ssl_config)) != 0) {
672 av_log(h, AV_LOG_ERROR, "mbedtls_ssl_setup returned %d\n", ret);
673 goto fail;
674 }
675
676 if (!shr->listen && !shr->numerichost) {
677 if ((ret = mbedtls_ssl_set_hostname(&tls_ctx->ssl_context, shr->host)) != 0) {
678 av_log(h, AV_LOG_ERROR, "mbedtls_ssl_set_hostname returned %d\n", ret);
679 goto fail;
680 }
681 }
682
683 // set I/O functions to use FFmpeg internal code for transport layer
684 mbedtls_ssl_set_bio(&tls_ctx->ssl_context, tls_ctx, mbedtls_send, mbedtls_recv, NULL);
685
686 if (shr->is_dtls) {
687 mbedtls_ssl_set_timer_cb(&tls_ctx->ssl_context, &tls_ctx->timer, mbedtls_timing_set_delay, mbedtls_timing_get_delay);
688 if (shr->mtu)
689 mbedtls_ssl_set_mtu(&tls_ctx->ssl_context, shr->mtu);
690 }
691 if (!shr->external_sock) {
692 ret = tls_handshake(h);
693 if (ret < 0)
694 goto fail;
695 }
696
697 if (shr->verify) {
698 // check the result of the certificate verification
699 if ((verify_res_flags = mbedtls_ssl_get_verify_result(&tls_ctx->ssl_context)) != 0) {
700 av_log(h, AV_LOG_ERROR, "mbedtls_ssl_get_verify_result reported problems "\
701 "with the certificate verification, returned flags: %"PRIu32"\n",
702 verify_res_flags);
703 if (verify_res_flags & MBEDTLS_X509_BADCERT_NOT_TRUSTED)
704 av_log(h, AV_LOG_ERROR, "The certificate is not correctly signed by the trusted CA.\n");
705 goto fail;
706 }
707 }
708
709 return 0;
710
711fail:
712 tls_close(h);
713 return AVERROR(EIO);
714}
715
716static int dtls_open(URLContext *h, const char *uri, int flags, AVDictionary **options)
717{
718 TLSContext *tls_ctx = h->priv_data;
719 TLSShared *shr = &tls_ctx->tls_shared;
720 shr->is_dtls = 1;
721 return tls_open(h, uri, flags, options);
722}
723
724static int handle_tls_error(URLContext *h, const char* func_name, int ret)
725{
726 switch (ret) {
727 case MBEDTLS_ERR_SSL_WANT_READ:
728 case MBEDTLS_ERR_SSL_WANT_WRITE:
729#ifdef MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET
730 case MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET:
731#endif
732 return AVERROR(EAGAIN);
733 case MBEDTLS_ERR_NET_SEND_FAILED:
734 case MBEDTLS_ERR_NET_RECV_FAILED:
735 return AVERROR(EIO);
736 case MBEDTLS_ERR_NET_CONN_RESET:
737 case MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY:
738 av_log(h, AV_LOG_WARNING, "%s reported connection reset by peer\n", func_name);
739 return AVERROR_EOF;
740 default:
741 av_log(h, AV_LOG_ERROR, "%s returned -0x%x\n", func_name, -ret);
742 return AVERROR(EIO);
743 }
744}
745
746static int tls_read(URLContext *h, uint8_t *buf, int size)
747{
748 TLSContext *tls_ctx = h->priv_data;
749 TLSShared *shr = &tls_ctx->tls_shared;
750 URLContext *uc = shr->is_dtls ? shr->udp : shr->tcp;
751 int ret;
752
754 uc->flags |= h->flags & AVIO_FLAG_NONBLOCK;
755 if ((ret = mbedtls_ssl_read(&tls_ctx->ssl_context, buf, size)) > 0) {
756 // return read length
757 return ret;
758 }
759
760 return handle_tls_error(h, "mbedtls_ssl_read", ret);
761}
762
763static int tls_write(URLContext *h, const uint8_t *buf, int size)
764{
765 TLSContext *tls_ctx = h->priv_data;
766 TLSShared *shr = &tls_ctx->tls_shared;
767 URLContext *uc = shr->is_dtls ? shr->udp : shr->tcp;
768 int ret;
769
771 uc->flags |= h->flags & AVIO_FLAG_NONBLOCK;
772 if ((ret = mbedtls_ssl_write(&tls_ctx->ssl_context, buf, size)) > 0) {
773 // return written length
774 return ret;
775 }
776
777 return handle_tls_error(h, "mbedtls_ssl_write", ret);
778}
779
781{
782 TLSContext *c = h->priv_data;
783 return ffurl_get_file_handle(c->tls_shared.tcp);
784}
785
787{
788 TLSContext *s = h->priv_data;
789 return ffurl_get_short_seek(s->tls_shared.tcp);
790}
791
792static const AVOption options[] = {
793 TLS_COMMON_OPTIONS(TLSContext, tls_shared), \
794 {"key_password", "Password for the private key file", OFFSET(priv_key_pw), AV_OPT_TYPE_STRING, .flags = TLS_OPTFL }, \
795 { NULL }
796};
797
798static const AVClass tls_class = {
799 .class_name = "tls",
800 .item_name = av_default_item_name,
801 .option = options,
802 .version = LIBAVUTIL_VERSION_INT,
803};
804
806 .name = "tls",
807 .url_open2 = tls_open,
808 .url_read = tls_read,
809 .url_write = tls_write,
810 .url_close = tls_close,
811 .url_get_file_handle = tls_get_file_handle,
812 .url_get_short_seek = tls_get_short_seek,
813 .priv_data_size = sizeof(TLSContext),
815 .priv_data_class = &tls_class,
816};
817
818static const AVClass dtls_class = {
819 .class_name = "dtls",
820 .item_name = av_default_item_name,
821 .option = options,
822 .version = LIBAVUTIL_VERSION_INT,
823};
824
826 .name = "dtls",
827 .url_open2 = dtls_open,
828 .url_handshake = tls_handshake,
829 .url_read = tls_read,
830 .url_write = tls_write,
831 .url_close = tls_close,
832 .url_get_file_handle = tls_get_file_handle,
833 .url_get_short_seek = tls_get_short_seek,
834 .priv_data_size = sizeof(TLSContext),
836 .priv_data_class = &dtls_class,
837};
uint8_t ptrdiff_t const uint8_t ptrdiff_t int intptr_t intptr_t int int16_t * dst
Definition dsp.h:87
Main libavformat public API header.
int ffurl_closep(URLContext **hh)
Close the resource accessed by the URLContext h, and free the memory used by it.
Definition avio.c:656
int ffurl_get_short_seek(void *urlcontext)
Return the current short seek threshold value for this URL.
Definition avio.c:906
int ffurl_get_file_handle(URLContext *h)
Return the file descriptor associated with this URL.
Definition avio.c:882
#define AVIO_FLAG_NONBLOCK
Use non-blocking mode.
Definition avio.h:636
void av_bprintf(AVBPrint *buf, const char *fmt,...)
Definition bprint.c:122
void av_bprint_init(AVBPrint *buf, unsigned size_init, unsigned size_max)
Definition bprint.c:69
#define flags(name, subs,...)
Definition cbs_h264.c:74
#define i(width, name, range_min, range_max)
Definition cbs_h264.c:63
#define s(width, name)
Definition cbs_vp9.c:198
#define NULL
Definition coverity.c:32
const char * key
#define fail
Definition test.h:479
@ AV_OPT_TYPE_STRING
Underlying C type is a uint8_t* that is either NULL or points to a C string allocated with the av_mal...
Definition opt.h:275
int av_bprint_finalize(AVBPrint *buf, char **ret_str)
Finalize a print buffer.
Definition bprint.c:235
int av_random_bytes(uint8_t *buf, size_t len)
Generate cryptographically secure random data, i.e.
#define AVERROR_EXIT
Immediate exit was requested; the called function should not be restarted.
Definition error.h:58
#define AVERROR_BUFFER_TOO_SMALL
Buffer too small.
Definition error.h:53
#define AVERROR_EOF
End of file.
Definition error.h:57
#define AVERROR(e)
Definition error.h:45
#define AV_LOG_TRACE
Extremely verbose debugging, useful for libav* development.
Definition log.h:236
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition log.h:231
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition log.h:216
#define AV_LOG_INFO
Standard information.
Definition log.h:221
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition log.h:210
const char * av_default_item_name(void *ptr)
Return the context name.
Definition log.c:241
int av_log_get_level(void)
Get the current log level.
Definition log.c:471
const char * av_basename(const char *path)
Thread safe basename.
Definition avstring.c:253
#define LIBAVUTIL_VERSION_INT
Definition version.h:85
static const AVProfile profiles[]
Memory handling functions.
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
void ff_udp_get_last_recv_addr(URLContext *h, struct sockaddr_storage *addr, socklen_t *addr_len)
Definition udp.c:510
misc parsing utilities
const URLProtocol ff_dtls_protocol
Definition tls_gnutls.c:791
const URLProtocol ff_tls_protocol
Definition tls_gnutls.c:771
const char * name
Definition qsvenc.c:142
Describe the class of an AVClass context structure.
Definition log.h:76
AVOption.
Definition opt.h:428
dtls_srtp_keys srtp_key
char * priv_key_pw
socklen_t dest_addr_len
Definition tls_gnutls.c:343
mbedtls_ctr_drbg_context ctr_drbg_context
mbedtls_ssl_context ssl_context
mbedtls_ssl_config ssl_config
mbedtls_x509_crt ca_cert
struct sockaddr_storage dest_addr
Definition tls_gnutls.c:342
mbedtls_timing_delay_context timer
mbedtls_pk_context priv_key
mbedtls_x509_crt own_cert
mbedtls_entropy_context entropy_context
TLSShared tls_shared
Definition tls_gnutls.c:337
char underlying_host[200]
Definition tls.h:67
int use_srtp
Definition tls.h:75
int listen
Definition tls.h:62
int numerichost
Definition tls.h:68
int verify
Definition tls.h:59
char * ca_file
Definition tls.h:58
URLContext * udp
Definition tls.h:71
int is_dtls
Definition tls.h:74
int mtu
The size of RTP packet, should generally be set to MTU.
Definition tls.h:85
int external_sock
Definition tls.h:70
URLContext * tcp
Definition tls.h:72
char * key_file
Definition tls.h:61
char * key_buf
Definition tls.h:79
char * host
Definition tls.h:64
char * cert_buf
Definition tls.h:78
char * cert_file
Definition tls.h:60
int flags
Definition url.h:40
mbedtls_tls_prf_types tls_prf_type
unsigned char master_secret[48]
unsigned char randbytes[64]
#define av_log(a,...)
static AVFormatContext * ctx
Definition movenc.c:49
#define gmtime_r
int ff_url_read_all(const char *url, AVBPrint *bp)
Read all data from the given URL url and store it in the given buffer bp.
Definition tls.c:128
int ff_tls_open_underlying(TLSShared *c, URLContext *parent, const char *uri, AVDictionary **options)
Definition tls.c:54
int ff_tls_parse_host(TLSShared *s, char *hostname, int hostname_size, int *port_ptr, const char *uri)
Definition tls.c:35
int ff_is_dtls_packet(const uint8_t *buf, int size)
Whether the packet is a DTLS packet, as defined by RFC 5764 Section 5.1.2.
Definition tls.c:167
#define MAX_CERTIFICATE_SIZE
Maximum size limit of a certificate and private key size.
Definition tls.h:34
#define TLS_COMMON_OPTIONS(pstruct, options_field)
Definition tls.h:101
#define TLS_OPTFL
Definition tls.h:88
static int tls_handshake(URLContext *h)
Definition tls_gnutls.c:506
static int tls_close(URLContext *h)
Definition tls_gnutls.c:419
static const AVClass tls_class
Definition tls_gnutls.c:764
static int tls_read(URLContext *h, uint8_t *buf, int size)
Definition tls_gnutls.c:707
static int dtls_open(URLContext *h, const char *uri, int flags, AVDictionary **options)
Definition tls_gnutls.c:699
static int tls_open(URLContext *h, const char *uri, int flags, AVDictionary **options)
Definition tls_gnutls.c:532
static int tls_get_short_seek(URLContext *h)
Definition tls_gnutls.c:753
static int tls_write(URLContext *h, const uint8_t *buf, int size)
Definition tls_gnutls.c:724
static const AVClass dtls_class
Definition tls_gnutls.c:784
static int tls_get_file_handle(URLContext *h)
Definition tls_gnutls.c:747
static int mbedtls_gen_x509_cert(mbedtls_pk_context *key, char *cert_buf, size_t cert_sz)
static int tls_handshake(URLContext *h)
static int tls_close(URLContext *h)
static int mbedtls_x509_fingerprint(char *cert_buf, size_t cert_sz, char **fingerprint)
Definition tls_mbedtls.c:47
static void handle_pk_parse_error(URLContext *h, int ret)
int ff_ssl_gen_key_cert(char *key_buf, size_t key_sz, char *cert_buf, size_t cert_sz, char **fingerprint)
static void handle_handshake_error(URLContext *h, int ret)
int ff_ssl_read_key_cert(char *key_url, char *cert_url, char *key_buf, size_t key_sz, char *cert_buf, size_t cert_sz, char **fingerprint)
Definition tls_mbedtls.c:76
static int tls_read(URLContext *h, uint8_t *buf, int size)
static int handle_tls_error(URLContext *h, const char *func_name, int ret)
static int dtls_open(URLContext *h, const char *uri, int flags, AVDictionary **options)
int ff_dtls_export_materials(URLContext *h, char *dtls_srtp_materials, size_t materials_sz)
static int handle_transport_error(URLContext *h, const char *func_name, int react_on_eagain, int ret)
static int tls_open(URLContext *h, const char *uri, int flags, AVDictionary **options)
static int mbedtls_gen_pkey(mbedtls_pk_context *key)
static int tls_get_short_seek(URLContext *h)
static void mbedtls_debug(void *ctx, int lvl, const char *file, int line, const char *msg)
static int tls_write(URLContext *h, const uint8_t *buf, int size)
static int mbedtls_send(void *ctx, const unsigned char *buf, size_t len)
static int mbedtls_recv(void *ctx, unsigned char *buf, size_t len)
#define OFFSET(x)
static int tls_get_file_handle(URLContext *h)
int ff_tls_set_external_socket(URLContext *h, URLContext *sock)
int size
unbuffered private I/O API
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:204
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:183
#define URL_PROTOCOL_FLAG_NETWORK
Definition url.h:33
#define md
int len
static double c[64]