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:
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 AVIOContext *s = NULL;
73 CFDataRef data = NULL;
76 SecExternalFormat format = kSecFormatPEMSequence;
77 SecExternalFormat type = kSecItemTypeAggregate;
78 CFStringRef pathStr = CFStringCreateWithCString(NULL, path, 0x08000100);
80 ret = AVERROR(ENOMEM);
84 if ((ret = ffio_open_whitelist(&s, path, AVIO_FLAG_READ,
85 &h->interrupt_callback, NULL,
86 h->protocol_whitelist, h->protocol_blacklist)) < 0)
89 if ((ret = avio_size(s)) < 0)
93 ret = AVERROR_INVALIDDATA;
97 if (!(buf = av_malloc(ret))) {
98 ret = AVERROR(ENOMEM);
102 if ((ret = avio_read(s, buf, ret)) < 0)
105 data = CFDataCreate(kCFAllocatorDefault, buf, ret);
107 if (SecItemImport(data, pathStr, &format, &type,
108 0, NULL, NULL, array) != noErr || !array) {
109 ret = AVERROR_UNKNOWN;
113 if (CFArrayGetCount(*array) == 0) {
114 ret = AVERROR_INVALIDDATA;
129 static int load_ca(URLContext *h)
131 TLSContext *c = h->priv_data;
133 CFArrayRef array = NULL;
135 if ((ret = import_pem(h, c->tls_shared.ca_file, &array)) < 0)
138 if (!(c->ca_array = CFRetain(array))) {
139 ret = AVERROR(ENOMEM);
149 static int load_cert(URLContext *h)
151 TLSContext *c = h->priv_data;
153 CFArrayRef certArray = NULL;
154 CFArrayRef keyArray = NULL;
155 SecIdentityRef id = NULL;
156 CFMutableArrayRef outArray = NULL;
158 if ((ret = import_pem(h, c->tls_shared.cert_file, &certArray)) < 0)
161 if ((ret = import_pem(h, c->tls_shared.key_file, &keyArray)) < 0)
164 if (!(id = SecIdentityCreate(kCFAllocatorDefault,
165 (SecCertificateRef)CFArrayGetValueAtIndex(certArray, 0),
166 (SecKeyRef)CFArrayGetValueAtIndex(keyArray, 0)))) {
167 ret = AVERROR_UNKNOWN;
171 if (!(outArray = CFArrayCreateMutableCopy(kCFAllocatorDefault, 0, certArray))) {
172 ret = AVERROR(ENOMEM);
176 CFArraySetValueAtIndex(outArray, 0, id);
178 SSLSetCertificate(c->ssl_context, outArray);
182 CFRelease(certArray);
192 static OSStatus tls_read_cb(SSLConnectionRef connection, void *data, size_t *dataLength)
194 URLContext *h = (URLContext*)connection;
195 TLSContext *c = h->priv_data;
196 int read = ffurl_read_complete(c->tls_shared.tcp, data, *dataLength);
199 switch(AVUNERROR(read)) {
202 return errSSLClosedGraceful;
204 return errSSLClosedAbort;
206 return errSSLWouldBlock;
217 static OSStatus tls_write_cb(SSLConnectionRef connection, const void *data, size_t *dataLength)
219 URLContext *h = (URLContext*)connection;
220 TLSContext *c = h->priv_data;
221 int written = ffurl_write(c->tls_shared.tcp, data, *dataLength);
224 switch(AVUNERROR(written)) {
226 return errSSLWouldBlock;
228 c->lastErr = written;
232 *dataLength = written;
237 static int tls_close(URLContext *h)
239 TLSContext *c = h->priv_data;
240 if (c->ssl_context) {
241 SSLClose(c->ssl_context);
242 CFRelease(c->ssl_context);
245 CFRelease(c->ca_array);
246 if (c->tls_shared.tcp)
247 ffurl_close(c->tls_shared.tcp);
251 #define CHECK_ERROR(func, ...) do { \
252 OSStatus status = func(__VA_ARGS__); \
253 if (status != noErr) { \
254 ret = AVERROR_UNKNOWN; \
255 av_log(h, AV_LOG_ERROR, #func ": Error %i\n", (int)status); \
260 static int tls_open(URLContext *h, const char *uri, int flags, AVDictionary **options)
262 TLSContext *c = h->priv_data;
263 TLSShared *s = &c->tls_shared;
266 if ((ret = ff_tls_open_underlying(s, h, uri, options)) < 0)
269 c->ssl_context = SSLCreateContext(NULL, s->listen ? kSSLServerSide : kSSLClientSide, kSSLStreamType);
270 if (!c->ssl_context) {
271 av_log(h, AV_LOG_ERROR, "Unable to create SSL context\n");
272 ret = AVERROR(ENOMEM);
276 if ((ret = load_ca(h)) < 0)
279 if (s->ca_file || !s->verify)
280 CHECK_ERROR(SSLSetSessionOption, c->ssl_context, kSSLSessionOptionBreakOnServerAuth, true);
282 if ((ret = load_cert(h)) < 0)
284 CHECK_ERROR(SSLSetPeerDomainName, c->ssl_context, s->host, strlen(s->host));
285 CHECK_ERROR(SSLSetIOFuncs, c->ssl_context, tls_read_cb, tls_write_cb);
286 CHECK_ERROR(SSLSetConnection, c->ssl_context, h);
288 OSStatus status = SSLHandshake(c->ssl_context);
289 if (status == errSSLServerAuthCompleted) {
290 SecTrustRef peerTrust;
291 SecTrustResultType trustResult;
295 if (SSLCopyPeerTrust(c->ssl_context, &peerTrust) != noErr) {
296 ret = AVERROR(ENOMEM);
300 if (SecTrustSetAnchorCertificates(peerTrust, c->ca_array) != noErr) {
301 ret = AVERROR_UNKNOWN;
305 if (SecTrustEvaluate(peerTrust, &trustResult) != noErr) {
306 ret = AVERROR_UNKNOWN;
310 if (trustResult == kSecTrustResultProceed ||
311 trustResult == kSecTrustResultUnspecified) {
312 // certificate is trusted
313 status = errSSLWouldBlock; // so we call SSLHandshake again
314 } else if (trustResult == kSecTrustResultRecoverableTrustFailure) {
315 // not trusted, for some reason other than being expired
316 status = errSSLXCertChainInvalid;
318 // cannot use this certificate (fatal)
319 status = errSSLBadCert;
323 CFRelease(peerTrust);
328 av_log(h, AV_LOG_ERROR, "Unable to negotiate TLS/SSL session: %i\n", (int)status);
339 static int map_ssl_error(OSStatus status, size_t processed)
344 case errSSLClosedGraceful:
345 case errSSLClosedNoNotify:
352 static int tls_read(URLContext *h, uint8_t *buf, int size)
354 TLSContext *c = h->priv_data;
355 size_t processed = 0;
356 int ret = SSLRead(c->ssl_context, buf, size, &processed);
357 ret = map_ssl_error(ret, processed);
362 return print_tls_error(h, ret);
365 static int tls_write(URLContext *h, const uint8_t *buf, int size)
367 TLSContext *c = h->priv_data;
368 size_t processed = 0;
369 int ret = SSLWrite(c->ssl_context, buf, size, &processed);
370 ret = map_ssl_error(ret, processed);
375 return print_tls_error(h, ret);
378 static const AVOption options[] = {
379 TLS_COMMON_OPTIONS(TLSContext, tls_shared),
383 static const AVClass tls_class = {
385 .item_name = av_default_item_name,
387 .version = LIBAVUTIL_VERSION_INT,
390 const URLProtocol ff_tls_securetransport_protocol = {
392 .url_open2 = tls_open,
393 .url_read = tls_read,
394 .url_write = tls_write,
395 .url_close = tls_close,
396 .priv_data_size = sizeof(TLSContext),
397 .flags = URL_PROTOCOL_FLAG_NETWORK,
398 .priv_data_class = &tls_class,