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
27 #include "os_support.h"
30 #include "libavcodec/internal.h"
31 #include "libavutil/avstring.h"
32 #include "libavutil/opt.h"
33 #include "libavutil/parseutils.h"
35 #include <Security/Security.h>
36 #include <Security/SecureTransport.h>
37 #include <CoreFoundation/CoreFoundation.h>
39 // We use a private API call here; it's good enough for WebKit.
40 SecIdentityRef SecIdentityCreate(CFAllocatorRef allocator, SecCertificateRef certificate, SecKeyRef privateKey);
43 typedef struct TLSContext {
46 SSLContextRef ssl_context;
51 static int print_tls_error(URLContext *h, int ret)
53 TLSContext *c = h->priv_data;
55 case errSSLWouldBlock:
57 case errSSLXCertChainInvalid:
58 av_log(h, AV_LOG_ERROR, "Invalid certificate chain\n");
63 av_log(h, AV_LOG_ERROR, "IO Error: %i\n", ret);
69 static int import_pem(URLContext *h, char *path, CFArrayRef *array)
71 AVIOContext *s = NULL;
72 CFDataRef data = NULL;
75 SecExternalFormat format = kSecFormatPEMSequence;
76 SecExternalFormat type = kSecItemTypeAggregate;
77 CFStringRef pathStr = CFStringCreateWithCString(NULL, path, 0x08000100);
79 ret = AVERROR(ENOMEM);
83 if ((ret = avio_open2(&s, path, AVIO_FLAG_READ,
84 &h->interrupt_callback, NULL)) < 0)
87 if ((ret = avio_size(s)) < 0)
91 ret = AVERROR_INVALIDDATA;
95 if (!(buf = av_malloc(ret))) {
96 ret = AVERROR(ENOMEM);
100 if ((ret = avio_read(s, buf, ret)) < 0)
103 data = CFDataCreate(kCFAllocatorDefault, buf, ret);
105 if (SecItemImport(data, pathStr, &format, &type,
106 0, NULL, NULL, array) != noErr || !array) {
107 ret = AVERROR_UNKNOWN;
111 if (CFArrayGetCount(*array) == 0) {
112 ret = AVERROR_INVALIDDATA;
127 static int load_ca(URLContext *h)
129 TLSContext *c = h->priv_data;
131 CFArrayRef array = NULL;
133 if ((ret = import_pem(h, c->tls_shared.ca_file, &array)) < 0)
136 if (!(c->ca_array = CFRetain(array))) {
137 ret = AVERROR(ENOMEM);
147 static int load_cert(URLContext *h)
149 TLSContext *c = h->priv_data;
151 CFArrayRef certArray = NULL;
152 CFArrayRef keyArray = NULL;
153 SecIdentityRef id = NULL;
154 CFMutableArrayRef outArray = NULL;
156 if ((ret = import_pem(h, c->tls_shared.cert_file, &certArray)) < 0)
159 if ((ret = import_pem(h, c->tls_shared.key_file, &keyArray)) < 0)
162 if (!(id = SecIdentityCreate(kCFAllocatorDefault,
163 (SecCertificateRef)CFArrayGetValueAtIndex(certArray, 0),
164 (SecKeyRef)CFArrayGetValueAtIndex(keyArray, 0)))) {
165 ret = AVERROR_UNKNOWN;
169 if (!(outArray = CFArrayCreateMutableCopy(kCFAllocatorDefault, 0, certArray))) {
170 ret = AVERROR(ENOMEM);
174 CFArraySetValueAtIndex(outArray, 0, id);
176 SSLSetCertificate(c->ssl_context, outArray);
180 CFRelease(certArray);
190 static OSStatus tls_read_cb(SSLConnectionRef connection, void *data, size_t *dataLength)
192 URLContext *h = (URLContext*)connection;
193 TLSContext *c = h->priv_data;
194 int read = ffurl_read_complete(c->tls_shared.tcp, data, *dataLength);
197 switch(AVUNERROR(read)) {
200 return errSSLClosedGraceful;
202 return errSSLClosedAbort;
204 return errSSLWouldBlock;
215 static OSStatus tls_write_cb(SSLConnectionRef connection, const void *data, size_t *dataLength)
217 URLContext *h = (URLContext*)connection;
218 TLSContext *c = h->priv_data;
219 int written = ffurl_write(c->tls_shared.tcp, data, *dataLength);
222 switch(AVUNERROR(written)) {
224 return errSSLWouldBlock;
226 c->lastErr = written;
230 *dataLength = written;
235 static int tls_close(URLContext *h)
237 TLSContext *c = h->priv_data;
238 if (c->ssl_context) {
239 SSLClose(c->ssl_context);
240 CFRelease(c->ssl_context);
243 CFRelease(c->ca_array);
244 if (c->tls_shared.tcp)
245 ffurl_close(c->tls_shared.tcp);
249 #define CHECK_ERROR(func, ...) do { \
250 OSStatus status = func(__VA_ARGS__); \
251 if (status != noErr) { \
252 ret = AVERROR_UNKNOWN; \
253 av_log(h, AV_LOG_ERROR, #func ": Error %i\n", (int)status); \
258 static int tls_open(URLContext *h, const char *uri, int flags, AVDictionary **options)
260 TLSContext *c = h->priv_data;
261 TLSShared *s = &c->tls_shared;
264 if ((ret = ff_tls_open_underlying(s, h, uri, options)) < 0)
267 c->ssl_context = SSLCreateContext(NULL, s->listen ? kSSLServerSide : kSSLClientSide, kSSLStreamType);
268 if (!c->ssl_context) {
269 av_log(h, AV_LOG_ERROR, "Unable to create SSL context\n");
270 ret = AVERROR(ENOMEM);
274 if ((ret = load_ca(h)) < 0)
277 if (s->ca_file || !s->verify)
278 CHECK_ERROR(SSLSetSessionOption, c->ssl_context, kSSLSessionOptionBreakOnServerAuth, true);
280 if ((ret = load_cert(h)) < 0)
282 CHECK_ERROR(SSLSetPeerDomainName, c->ssl_context, s->host, strlen(s->host));
283 CHECK_ERROR(SSLSetIOFuncs, c->ssl_context, tls_read_cb, tls_write_cb);
284 CHECK_ERROR(SSLSetConnection, c->ssl_context, h);
286 OSStatus status = SSLHandshake(c->ssl_context);
287 if (status == errSSLServerAuthCompleted) {
288 SecTrustRef peerTrust;
289 SecTrustResultType trustResult;
293 if (SSLCopyPeerTrust(c->ssl_context, &peerTrust) != noErr) {
294 ret = AVERROR(ENOMEM);
298 if (SecTrustSetAnchorCertificates(peerTrust, c->ca_array) != noErr) {
299 ret = AVERROR_UNKNOWN;
303 if (SecTrustEvaluate(peerTrust, &trustResult) != noErr) {
304 ret = AVERROR_UNKNOWN;
308 if (trustResult == kSecTrustResultProceed ||
309 trustResult == kSecTrustResultUnspecified) {
310 // certificate is trusted
311 status = errSSLWouldBlock; // so we call SSLHandshake again
312 } else if (trustResult == kSecTrustResultRecoverableTrustFailure) {
313 // not trusted, for some reason other than being expired
314 status = errSSLXCertChainInvalid;
316 // cannot use this certificate (fatal)
317 status = errSSLBadCert;
321 CFRelease(peerTrust);
326 av_log(h, AV_LOG_ERROR, "Unable to negotiate TLS/SSL session: %i\n", (int)status);
337 static int map_ssl_error(OSStatus status, size_t processed)
342 case errSSLClosedGraceful:
343 case errSSLClosedNoNotify:
350 static int tls_read(URLContext *h, uint8_t *buf, int size)
352 TLSContext *c = h->priv_data;
353 size_t processed = 0;
354 int ret = SSLRead(c->ssl_context, buf, size, &processed);
355 ret = map_ssl_error(ret, processed);
360 return print_tls_error(h, ret);
363 static int tls_write(URLContext *h, const uint8_t *buf, int size)
365 TLSContext *c = h->priv_data;
366 size_t processed = 0;
367 int ret = SSLWrite(c->ssl_context, buf, size, &processed);
368 ret = map_ssl_error(ret, processed);
373 return print_tls_error(h, ret);
376 static const AVOption options[] = {
377 TLS_COMMON_OPTIONS(TLSContext, tls_shared),
381 static const AVClass tls_class = {
383 .item_name = av_default_item_name,
385 .version = LIBAVUTIL_VERSION_INT,
388 URLProtocol ff_tls_securetransport_protocol = {
390 .url_open2 = tls_open,
391 .url_read = tls_read,
392 .url_write = tls_write,
393 .url_close = tls_close,
394 .priv_data_size = sizeof(TLSContext),
395 .flags = URL_PROTOCOL_FLAG_NETWORK,
396 .priv_data_class = &tls_class,