2 * Copyright (c) 2015 Rodger Combs
4 * This file is part of FFmpeg.
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.
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.
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
25 #include "avio_internal.h"
28 #include "os_support.h"
31 #include "libavcodec/internal.h"
32 #include "libavutil/avstring.h"
33 #include "libavutil/opt.h"
34 #include "libavutil/parseutils.h"
36 #include <Security/Security.h>
37 #include <Security/SecureTransport.h>
38 #include <CoreFoundation/CoreFoundation.h>
40 // We use a private API call here; it's good enough for WebKit.
41 SecIdentityRef SecIdentityCreate(CFAllocatorRef allocator, SecCertificateRef certificate, SecKeyRef privateKey);
44 typedef struct TLSContext {
47 SSLContextRef ssl_context;
52 static int print_tls_error(URLContext *h, int ret)
54 TLSContext *c = h->priv_data;
56 case errSSLWouldBlock:
57 return AVERROR(EAGAIN);
58 case errSSLXCertChainInvalid:
59 av_log(h, AV_LOG_ERROR, "Invalid certificate chain\n");
64 av_log(h, AV_LOG_ERROR, "IO Error: %i\n", ret);
70 static int import_pem(URLContext *h, char *path, CFArrayRef *array)
72 #if !HAVE_SECITEMIMPORT
73 return AVERROR_PATCHWELCOME;
75 AVIOContext *s = NULL;
76 CFDataRef data = NULL;
79 SecExternalFormat format = kSecFormatPEMSequence;
80 SecExternalFormat type = kSecItemTypeAggregate;
81 CFStringRef pathStr = CFStringCreateWithCString(NULL, path, 0x08000100);
83 ret = AVERROR(ENOMEM);
87 if ((ret = ffio_open_whitelist(&s, path, AVIO_FLAG_READ,
88 &h->interrupt_callback, NULL,
89 h->protocol_whitelist, h->protocol_blacklist)) < 0)
92 if ((ret = avio_size(s)) < 0)
96 ret = AVERROR_INVALIDDATA;
100 if (!(buf = av_malloc(ret))) {
101 ret = AVERROR(ENOMEM);
105 if ((ret = avio_read(s, buf, ret)) < 0)
108 data = CFDataCreate(kCFAllocatorDefault, buf, ret);
110 if (SecItemImport(data, pathStr, &format, &type,
111 0, NULL, NULL, array) != noErr || !array) {
112 ret = AVERROR_UNKNOWN;
116 if (CFArrayGetCount(*array) == 0) {
117 ret = AVERROR_INVALIDDATA;
133 static int load_ca(URLContext *h)
135 TLSContext *c = h->priv_data;
137 CFArrayRef array = NULL;
139 if ((ret = import_pem(h, c->tls_shared.ca_file, &array)) < 0)
142 if (!(c->ca_array = CFRetain(array))) {
143 ret = AVERROR(ENOMEM);
153 static int load_cert(URLContext *h)
155 TLSContext *c = h->priv_data;
157 CFArrayRef certArray = NULL;
158 CFArrayRef keyArray = NULL;
159 SecIdentityRef id = NULL;
160 CFMutableArrayRef outArray = NULL;
162 if ((ret = import_pem(h, c->tls_shared.cert_file, &certArray)) < 0)
165 if ((ret = import_pem(h, c->tls_shared.key_file, &keyArray)) < 0)
168 if (!(id = SecIdentityCreate(kCFAllocatorDefault,
169 (SecCertificateRef)CFArrayGetValueAtIndex(certArray, 0),
170 (SecKeyRef)CFArrayGetValueAtIndex(keyArray, 0)))) {
171 ret = AVERROR_UNKNOWN;
175 if (!(outArray = CFArrayCreateMutableCopy(kCFAllocatorDefault, 0, certArray))) {
176 ret = AVERROR(ENOMEM);
180 CFArraySetValueAtIndex(outArray, 0, id);
182 SSLSetCertificate(c->ssl_context, outArray);
186 CFRelease(certArray);
196 static OSStatus tls_read_cb(SSLConnectionRef connection, void *data, size_t *dataLength)
198 URLContext *h = (URLContext*)connection;
199 TLSContext *c = h->priv_data;
200 size_t requested = *dataLength;
201 int read = ffurl_read(c->tls_shared.tcp, data, requested);
204 switch(AVUNERROR(read)) {
207 return errSSLClosedGraceful;
209 return errSSLClosedAbort;
211 return errSSLWouldBlock;
218 if (read < requested)
219 return errSSLWouldBlock;
225 static OSStatus tls_write_cb(SSLConnectionRef connection, const void *data, size_t *dataLength)
227 URLContext *h = (URLContext*)connection;
228 TLSContext *c = h->priv_data;
229 int written = ffurl_write(c->tls_shared.tcp, data, *dataLength);
232 switch(AVUNERROR(written)) {
234 return errSSLWouldBlock;
236 c->lastErr = written;
240 *dataLength = written;
245 static int tls_close(URLContext *h)
247 TLSContext *c = h->priv_data;
248 if (c->ssl_context) {
249 SSLClose(c->ssl_context);
250 CFRelease(c->ssl_context);
253 CFRelease(c->ca_array);
254 ffurl_closep(&c->tls_shared.tcp);
258 #define CHECK_ERROR(func, ...) do { \
259 OSStatus status = func(__VA_ARGS__); \
260 if (status != noErr) { \
261 ret = AVERROR_UNKNOWN; \
262 av_log(h, AV_LOG_ERROR, #func ": Error %i\n", (int)status); \
267 static int tls_open(URLContext *h, const char *uri, int flags, AVDictionary **options)
269 TLSContext *c = h->priv_data;
270 TLSShared *s = &c->tls_shared;
273 if ((ret = ff_tls_open_underlying(s, h, uri, options)) < 0)
276 c->ssl_context = SSLCreateContext(NULL, s->listen ? kSSLServerSide : kSSLClientSide, kSSLStreamType);
277 if (!c->ssl_context) {
278 av_log(h, AV_LOG_ERROR, "Unable to create SSL context\n");
279 ret = AVERROR(ENOMEM);
283 if ((ret = load_ca(h)) < 0)
286 if (s->ca_file || !s->verify)
287 CHECK_ERROR(SSLSetSessionOption, c->ssl_context, kSSLSessionOptionBreakOnServerAuth, true);
289 if ((ret = load_cert(h)) < 0)
291 CHECK_ERROR(SSLSetPeerDomainName, c->ssl_context, s->host, strlen(s->host));
292 CHECK_ERROR(SSLSetIOFuncs, c->ssl_context, tls_read_cb, tls_write_cb);
293 CHECK_ERROR(SSLSetConnection, c->ssl_context, h);
295 OSStatus status = SSLHandshake(c->ssl_context);
296 if (status == errSSLServerAuthCompleted) {
297 SecTrustRef peerTrust;
298 SecTrustResultType trustResult;
302 if (SSLCopyPeerTrust(c->ssl_context, &peerTrust) != noErr) {
303 ret = AVERROR(ENOMEM);
307 if (SecTrustSetAnchorCertificates(peerTrust, c->ca_array) != noErr) {
308 ret = AVERROR_UNKNOWN;
312 if (SecTrustEvaluate(peerTrust, &trustResult) != noErr) {
313 ret = AVERROR_UNKNOWN;
317 if (trustResult == kSecTrustResultProceed ||
318 trustResult == kSecTrustResultUnspecified) {
319 // certificate is trusted
320 status = errSSLWouldBlock; // so we call SSLHandshake again
321 } else if (trustResult == kSecTrustResultRecoverableTrustFailure) {
322 // not trusted, for some reason other than being expired
323 status = errSSLXCertChainInvalid;
325 // cannot use this certificate (fatal)
326 status = errSSLBadCert;
330 CFRelease(peerTrust);
332 if (status == noErr) {
334 } else if (status != errSSLWouldBlock) {
335 av_log(h, AV_LOG_ERROR, "Unable to negotiate TLS/SSL session: %i\n", (int)status);
347 static int map_ssl_error(OSStatus status, size_t processed)
352 case errSSLClosedGraceful:
353 case errSSLClosedNoNotify:
355 case errSSLWouldBlock:
363 static int tls_read(URLContext *h, uint8_t *buf, int size)
365 TLSContext *c = h->priv_data;
366 size_t available = 0, processed = 0;
368 SSLGetBufferedReadSize(c->ssl_context, &available);
370 size = FFMIN(available, size);
371 ret = SSLRead(c->ssl_context, buf, size, &processed);
372 ret = map_ssl_error(ret, processed);
377 return print_tls_error(h, ret);
380 static int tls_write(URLContext *h, const uint8_t *buf, int size)
382 TLSContext *c = h->priv_data;
383 size_t processed = 0;
384 int ret = SSLWrite(c->ssl_context, buf, size, &processed);
385 ret = map_ssl_error(ret, processed);
390 return print_tls_error(h, ret);
393 static int tls_get_file_handle(URLContext *h)
395 TLSContext *c = h->priv_data;
396 return ffurl_get_file_handle(c->tls_shared.tcp);
399 static int tls_get_short_seek(URLContext *h)
401 TLSContext *s = h->priv_data;
402 return ffurl_get_short_seek(s->tls_shared.tcp);
405 static const AVOption options[] = {
406 TLS_COMMON_OPTIONS(TLSContext, tls_shared),
410 static const AVClass tls_class = {
412 .item_name = av_default_item_name,
414 .version = LIBAVUTIL_VERSION_INT,
417 const URLProtocol ff_tls_protocol = {
419 .url_open2 = tls_open,
420 .url_read = tls_read,
421 .url_write = tls_write,
422 .url_close = tls_close,
423 .url_get_file_handle = tls_get_file_handle,
424 .url_get_short_seek = tls_get_short_seek,
425 .priv_data_size = sizeof(TLSContext),
426 .flags = URL_PROTOCOL_FLAG_NETWORK,
427 .priv_data_class = &tls_class,