FFmpeg
Loading...
Searching...
No Matches
tls_securetransport.c
Go to the documentation of this file.
1/*
2 * Copyright (c) 2015 rcombs
3 *
4 * This file is part of FFmpeg.
5 *
6 * FFmpeg is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public License
8 * as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
10 *
11 * FFmpeg is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with FFmpeg; if not, write to the Free Software * Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19 */
20
21#include <errno.h>
22
23
24#include "avformat.h"
25#include "avio_internal.h"
26#include "internal.h"
27#include "network.h"
28#include "os_support.h"
29#include "url.h"
30#include "tls.h"
31#include "libavcodec/internal.h"
33#include "libavutil/avstring.h"
34#include "libavutil/mem.h"
35#include "libavutil/opt.h"
37
38#include <Security/Security.h>
39#include <Security/SecureTransport.h>
40#include <CoreFoundation/CoreFoundation.h>
41
42// We use a private API call here; it's good enough for WebKit.
43SecIdentityRef SecIdentityCreate(CFAllocatorRef allocator, SecCertificateRef certificate, SecKeyRef privateKey);
44#define ioErr -36
45
46typedef struct TLSContext {
48 SSLContextRef ssl_context;
49 CFArrayRef ca_array;
52
53static int print_tls_error(URLContext *h, int ret)
54{
55 TLSContext *c = h->priv_data;
56 switch (ret) {
57 case errSSLWouldBlock:
58 return AVERROR(EAGAIN);
59 case errSSLXCertChainInvalid:
60 av_log(h, AV_LOG_ERROR, "Invalid certificate chain\n");
61 return AVERROR(EIO);
62 case ioErr:
63 return c->lastErr;
64 default:
65 av_log(h, AV_LOG_ERROR, "IO Error: %i\n", ret);
66 return AVERROR(EIO);
67 }
68 return AVERROR(EIO);
69}
70
71static int import_pem(URLContext *h, char *path, CFArrayRef *array)
72{
73#if !HAVE_SECITEMIMPORT
75#else
77 CFDataRef data = NULL;
78 int64_t ret = 0;
79 char *buf = NULL;
80 SecExternalFormat format = kSecFormatPEMSequence;
81 SecExternalFormat type = kSecItemTypeAggregate;
82 CFStringRef pathStr = CFStringCreateWithCString(NULL, path, 0x08000100);
83 if (!pathStr) {
84 ret = AVERROR(ENOMEM);
85 goto end;
86 }
87
88 if ((ret = ffio_open_whitelist(&s, path, AVIO_FLAG_READ,
89 &h->interrupt_callback, NULL,
90 h->protocol_whitelist, h->protocol_blacklist)) < 0)
91 goto end;
92
93 if ((ret = avio_size(s)) < 0)
94 goto end;
95
96 if (ret == 0) {
98 goto end;
99 }
100
101 if (!(buf = av_malloc(ret))) {
102 ret = AVERROR(ENOMEM);
103 goto end;
104 }
105
106 if ((ret = avio_read(s, buf, ret)) < 0)
107 goto end;
108
109 data = CFDataCreate(kCFAllocatorDefault, buf, ret);
110
111 if (SecItemImport(data, pathStr, &format, &type,
112 0, NULL, NULL, array) != noErr || !array) {
113 ret = AVERROR_UNKNOWN;
114 goto end;
115 }
116
117 if (CFArrayGetCount(*array) == 0) {
119 goto end;
120 }
121
122end:
123 av_free(buf);
124 if (pathStr)
125 CFRelease(pathStr);
126 if (data)
127 CFRelease(data);
128 if (s)
129 avio_close(s);
130 return ret;
131#endif
132}
133
134static int load_ca(URLContext *h)
135{
136 TLSContext *c = h->priv_data;
137 int ret = 0;
138 CFArrayRef array = NULL;
139
140 if ((ret = import_pem(h, c->tls_shared.ca_file, &array)) < 0)
141 goto end;
142
143 if (!(c->ca_array = CFRetain(array))) {
144 ret = AVERROR(ENOMEM);
145 goto end;
146 }
147
148end:
149 if (array)
150 CFRelease(array);
151 return ret;
152}
153
155{
156 TLSContext *c = h->priv_data;
157 int ret = 0;
158 CFArrayRef certArray = NULL;
159 CFArrayRef keyArray = NULL;
160 SecIdentityRef id = NULL;
161 CFMutableArrayRef outArray = NULL;
162
163 if ((ret = import_pem(h, c->tls_shared.cert_file, &certArray)) < 0)
164 goto end;
165
166 if ((ret = import_pem(h, c->tls_shared.key_file, &keyArray)) < 0)
167 goto end;
168
169 if (!(id = SecIdentityCreate(kCFAllocatorDefault,
170 (SecCertificateRef)CFArrayGetValueAtIndex(certArray, 0),
171 (SecKeyRef)CFArrayGetValueAtIndex(keyArray, 0)))) {
172 ret = AVERROR_UNKNOWN;
173 goto end;
174 }
175
176 if (!(outArray = CFArrayCreateMutableCopy(kCFAllocatorDefault, 0, certArray))) {
177 ret = AVERROR(ENOMEM);
178 goto end;
179 }
180
181 CFArraySetValueAtIndex(outArray, 0, id);
182
183 SSLSetCertificate(c->ssl_context, outArray);
184
185end:
186 if (certArray)
187 CFRelease(certArray);
188 if (keyArray)
189 CFRelease(keyArray);
190 if (outArray)
191 CFRelease(outArray);
192 if (id)
193 CFRelease(id);
194 return ret;
195}
196
197static OSStatus tls_read_cb(SSLConnectionRef connection, void *data, size_t *dataLength)
198{
199 URLContext *h = (URLContext*)connection;
200 TLSContext *c = h->priv_data;
201 size_t requested = *dataLength;
202 int read = ffurl_read(c->tls_shared.tcp, data, requested);
203 if (read <= 0) {
204 *dataLength = 0;
205 switch(AVUNERROR(read)) {
206 case ENOENT:
207 case 0:
208 return errSSLClosedGraceful;
209 case ECONNRESET:
210 return errSSLClosedAbort;
211 case EAGAIN:
212 return errSSLWouldBlock;
213 default:
214 c->lastErr = read;
215 return ioErr;
216 }
217 } else {
218 *dataLength = read;
219 if (read < requested)
220 return errSSLWouldBlock;
221 else
222 return noErr;
223 }
224}
225
226static OSStatus tls_write_cb(SSLConnectionRef connection, const void *data, size_t *dataLength)
227{
228 URLContext *h = (URLContext*)connection;
229 TLSContext *c = h->priv_data;
230 int written = ffurl_write(c->tls_shared.tcp, data, *dataLength);
231 if (written <= 0) {
232 *dataLength = 0;
233 switch(AVUNERROR(written)) {
234 case EAGAIN:
235 return errSSLWouldBlock;
236 default:
237 c->lastErr = written;
238 return ioErr;
239 }
240 } else {
241 *dataLength = written;
242 return noErr;
243 }
244}
245
247{
248 TLSContext *c = h->priv_data;
249 if (c->ssl_context) {
250 SSLClose(c->ssl_context);
251 CFRelease(c->ssl_context);
252 }
253 if (c->ca_array)
254 CFRelease(c->ca_array);
255 ffurl_closep(&c->tls_shared.tcp);
256 return 0;
257}
258
259#define CHECK_ERROR(func, ...) do { \
260 OSStatus status = func(__VA_ARGS__); \
261 if (status != noErr) { \
262 ret = AVERROR_UNKNOWN; \
263 av_log(h, AV_LOG_ERROR, #func ": Error %i\n", (int)status); \
264 goto fail; \
265 } \
266 } while (0)
267
268static int tls_open(URLContext *h, const char *uri, int flags, AVDictionary **options)
269{
270 TLSContext *c = h->priv_data;
271 TLSShared *s = &c->tls_shared;
272 int ret;
273
274 if ((ret = ff_tls_open_underlying(s, h, uri, options)) < 0)
275 goto fail;
276
277 c->ssl_context = SSLCreateContext(NULL, s->listen ? kSSLServerSide : kSSLClientSide, kSSLStreamType);
278 if (!c->ssl_context) {
279 av_log(h, AV_LOG_ERROR, "Unable to create SSL context\n");
280 ret = AVERROR(ENOMEM);
281 goto fail;
282 }
283 if (s->ca_file) {
284 if ((ret = load_ca(h)) < 0)
285 goto fail;
286 }
287 if (s->ca_file || !s->verify)
288 CHECK_ERROR(SSLSetSessionOption, c->ssl_context, kSSLSessionOptionBreakOnServerAuth, true);
289 if (s->cert_file)
290 if ((ret = load_cert(h)) < 0)
291 goto fail;
292 CHECK_ERROR(SSLSetPeerDomainName, c->ssl_context, s->host, strlen(s->host));
293 CHECK_ERROR(SSLSetIOFuncs, c->ssl_context, tls_read_cb, tls_write_cb);
294 CHECK_ERROR(SSLSetConnection, c->ssl_context, h);
295 while (1) {
296 OSStatus status = SSLHandshake(c->ssl_context);
297 if (status == errSSLServerAuthCompleted) {
298 SecTrustRef peerTrust;
299 SecTrustResultType trustResult;
300 if (!s->verify)
301 continue;
302
303 if (SSLCopyPeerTrust(c->ssl_context, &peerTrust) != noErr) {
304 ret = AVERROR(ENOMEM);
305 goto fail;
306 }
307
308 if (SecTrustSetAnchorCertificates(peerTrust, c->ca_array) != noErr) {
309 ret = AVERROR_UNKNOWN;
310 goto fail;
311 }
312
313 if (SecTrustEvaluate(peerTrust, &trustResult) != noErr) {
314 ret = AVERROR_UNKNOWN;
315 goto fail;
316 }
317
318 if (trustResult == kSecTrustResultProceed ||
319 trustResult == kSecTrustResultUnspecified) {
320 // certificate is trusted
321 status = errSSLWouldBlock; // so we call SSLHandshake again
322 } else if (trustResult == kSecTrustResultRecoverableTrustFailure) {
323 // not trusted, for some reason other than being expired
324 status = errSSLXCertChainInvalid;
325 } else {
326 // cannot use this certificate (fatal)
327 status = errSSLBadCert;
328 }
329
330 if (peerTrust)
331 CFRelease(peerTrust);
332 }
333 if (status == noErr) {
334 break;
335 } else if (status != errSSLWouldBlock) {
336 av_log(h, AV_LOG_ERROR, "Unable to negotiate TLS/SSL session: %i\n", (int)status);
337 ret = AVERROR(EIO);
338 goto fail;
339 }
340 }
341
342 return 0;
343fail:
344 tls_close(h);
345 return ret;
346}
347
348static int map_ssl_error(OSStatus status, size_t processed)
349{
350 switch (status) {
351 case noErr:
352 return processed;
353 case errSSLClosedGraceful:
354 case errSSLClosedNoNotify:
355 return 0;
356 case errSSLWouldBlock:
357 if (processed > 0)
358 return processed;
360 default:
361 return (int)status;
362 }
363}
364
365static int tls_read(URLContext *h, uint8_t *buf, int size)
366{
367 TLSContext *c = h->priv_data;
368 size_t available = 0, processed = 0;
369 int ret;
370 SSLGetBufferedReadSize(c->ssl_context, &available);
371 if (available)
372 size = FFMIN(available, size);
373 ret = SSLRead(c->ssl_context, buf, size, &processed);
374 ret = map_ssl_error(ret, processed);
375 if (ret > 0)
376 return ret;
377 if (ret == 0)
378 return AVERROR_EOF;
379 return print_tls_error(h, ret);
380}
381
382static int tls_write(URLContext *h, const uint8_t *buf, int size)
383{
384 TLSContext *c = h->priv_data;
385 size_t processed = 0;
386 int ret = SSLWrite(c->ssl_context, buf, size, &processed);
387 ret = map_ssl_error(ret, processed);
388 if (ret > 0)
389 return ret;
390 if (ret == 0)
391 return AVERROR_EOF;
392 return print_tls_error(h, ret);
393}
394
396{
397 TLSContext *c = h->priv_data;
398 return ffurl_get_file_handle(c->tls_shared.tcp);
399}
400
402{
403 TLSContext *s = h->priv_data;
404 return ffurl_get_short_seek(s->tls_shared.tcp);
405}
406
407static const AVOption options[] = {
408 TLS_COMMON_OPTIONS(TLSContext, tls_shared),
409 { NULL }
410};
411
412static const AVClass tls_class = {
413 .class_name = "tls",
414 .item_name = av_default_item_name,
415 .option = options,
416 .version = LIBAVUTIL_VERSION_INT,
417};
418
420 .name = "tls",
421 .url_open2 = tls_open,
422 .url_read = tls_read,
423 .url_write = tls_write,
424 .url_close = tls_close,
425 .url_get_file_handle = tls_get_file_handle,
426 .url_get_short_seek = tls_get_short_seek,
427 .priv_data_size = sizeof(TLSContext),
429 .priv_data_class = &tls_class,
430};
static const char *const format[]
Definition af_aiir.c:444
Main libavformat public API header.
int ffio_open_whitelist(AVIOContext **s, const char *filename, int flags, const AVIOInterruptCB *int_cb, AVDictionary **options, const char *whitelist, const char *blacklist)
Definition avio.c:551
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
int avio_close(AVIOContext *s)
Close the resource accessed by the AVIOContext s and free it.
Definition avio.c:684
#define AVIO_FLAG_READ
read-only
Definition avio.h:617
int64_t avio_size(AVIOContext *s)
Get the filesize.
Definition aviobuf.c:326
int avio_read(AVIOContext *s, unsigned char *buf, int size)
Read size bytes from AVIOContext into buf.
Definition aviobuf.c:615
static uint32_t BS_FUNC read(BSCTX *bc, unsigned int n)
Return n bits from the buffer, n has to be in the 0-32 range.
#define flags(name, subs,...)
Definition cbs_h264.c:74
#define s(width, name)
Definition cbs_vp9.c:198
#define NULL
Definition coverity.c:32
long long int64_t
Definition coverity.c:34
#define fail
Definition test.h:479
#define AVUNERROR(e)
Definition error.h:46
#define AVERROR_UNKNOWN
Unknown error, typically from an external library.
Definition error.h:73
#define AVERROR_PATCHWELCOME
Not yet implemented in FFmpeg, patches welcome.
Definition error.h:64
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition error.h:61
#define AVERROR_EOF
End of file.
Definition error.h:57
#define AVERROR(e)
Definition error.h:45
#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
#define LIBAVUTIL_VERSION_INT
Definition version.h:85
cl_device_type type
common internal api header.
Macro definitions for various function/variable attributes.
#define av_fallthrough
Definition attributes.h:67
#define FFMIN(a, b)
Definition macros.h:49
Memory handling functions.
const char data[16]
Definition mxf.c:149
#define av_malloc(s)
Definition ops_static.c:52
AVOptions.
miscellaneous OS support macros and functions.
misc parsing utilities
const URLProtocol ff_tls_protocol
Definition tls_gnutls.c:771
Describe the class of an AVClass context structure.
Definition log.h:76
Bytestream IO Context.
Definition avio.h:160
AVOption.
Definition opt.h:428
mbedtls_ssl_context ssl_context
CFArrayRef ca_array
TLSShared tls_shared
Definition tls_gnutls.c:337
#define av_free(p)
#define av_log(a,...)
static int array[MAX_W *MAX_W]
int ff_tls_open_underlying(TLSShared *c, URLContext *parent, const char *uri, AVDictionary **options)
Definition tls.c:54
#define TLS_COMMON_OPTIONS(pstruct, options_field)
Definition tls.h:101
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 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 int tls_get_file_handle(URLContext *h)
Definition tls_gnutls.c:747
static OSStatus tls_read_cb(SSLConnectionRef connection, void *data, size_t *dataLength)
static int load_ca(URLContext *h)
static int import_pem(URLContext *h, char *path, CFArrayRef *array)
static int tls_close(URLContext *h)
static OSStatus tls_write_cb(SSLConnectionRef connection, const void *data, size_t *dataLength)
static int map_ssl_error(OSStatus status, size_t processed)
static int tls_read(URLContext *h, uint8_t *buf, int size)
SecIdentityRef SecIdentityCreate(CFAllocatorRef allocator, SecCertificateRef certificate, SecKeyRef privateKey)
#define ioErr
static int tls_open(URLContext *h, const char *uri, int flags, AVDictionary **options)
static int load_cert(URLContext *h)
static int tls_get_short_seek(URLContext *h)
static int tls_write(URLContext *h, const uint8_t *buf, int size)
static int print_tls_error(URLContext *h, int ret)
#define CHECK_ERROR(func,...)
static int tls_get_file_handle(URLContext *h)
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
static double c[64]