2 * Copyright (c) 2015 Hendrik Leppkes
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
8 * License 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 GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with FFmpeg; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 /** Based on the CURL SChannel module */
26 #include "os_support.h"
30 #define SECURITY_WIN32
34 #define SCHANNEL_INITIAL_BUFFER_SIZE 4096
35 #define SCHANNEL_FREE_BUFFER_SIZE 1024
37 /* mingw does not define this symbol */
38 #ifndef SECBUFFER_ALERT
39 #define SECBUFFER_ALERT 17
42 typedef struct TLSContext {
46 CredHandle cred_handle;
47 TimeStamp cred_timestamp;
49 CtxtHandle ctxt_handle;
50 TimeStamp ctxt_timestamp;
63 SecPkgContext_StreamSizes sizes;
66 int connection_closed;
67 int sspi_close_notify;
70 static void init_sec_buffer(SecBuffer *buffer, unsigned long type,
71 void *data, unsigned long size)
73 buffer->cbBuffer = size;
74 buffer->BufferType = type;
75 buffer->pvBuffer = data;
78 static void init_sec_buffer_desc(SecBufferDesc *desc, SecBuffer *buffers,
79 unsigned long buffer_count)
81 desc->ulVersion = SECBUFFER_VERSION;
82 desc->pBuffers = buffers;
83 desc->cBuffers = buffer_count;
86 static int tls_shutdown_client(URLContext *h)
88 TLSContext *c = h->priv_data;
89 TLSShared *s = &c->tls_shared;
93 SecBufferDesc BuffDesc;
95 SECURITY_STATUS sspi_ret;
97 SecBufferDesc outbuf_desc;
99 DWORD dwshut = SCHANNEL_SHUTDOWN;
100 init_sec_buffer(&Buffer, SECBUFFER_TOKEN, &dwshut, sizeof(dwshut));
101 init_sec_buffer_desc(&BuffDesc, &Buffer, 1);
103 sspi_ret = ApplyControlToken(&c->ctxt_handle, &BuffDesc);
104 if (sspi_ret != SEC_E_OK)
105 av_log(h, AV_LOG_ERROR, "ApplyControlToken failed\n");
107 init_sec_buffer(&outbuf, SECBUFFER_EMPTY, NULL, 0);
108 init_sec_buffer_desc(&outbuf_desc, &outbuf, 1);
110 sspi_ret = InitializeSecurityContext(&c->cred_handle, &c->ctxt_handle, s->host,
111 c->request_flags, 0, 0, NULL, 0, &c->ctxt_handle,
112 &outbuf_desc, &c->context_flags, &c->ctxt_timestamp);
113 if (sspi_ret == SEC_E_OK || sspi_ret == SEC_I_CONTEXT_EXPIRED) {
114 ret = ffurl_write(s->tcp, outbuf.pvBuffer, outbuf.cbBuffer);
115 FreeContextBuffer(outbuf.pvBuffer);
116 if (ret < 0 || ret != outbuf.cbBuffer)
117 av_log(h, AV_LOG_ERROR, "Failed to send close message\n");
125 static int tls_close(URLContext *h)
127 TLSContext *c = h->priv_data;
129 tls_shutdown_client(h);
131 DeleteSecurityContext(&c->ctxt_handle);
132 FreeCredentialsHandle(&c->cred_handle);
134 av_freep(&c->enc_buf);
135 c->enc_buf_size = c->enc_buf_offset = 0;
137 av_freep(&c->dec_buf);
138 c->dec_buf_size = c->dec_buf_offset = 0;
140 if (c->tls_shared.tcp)
141 ffurl_close(c->tls_shared.tcp);
145 static int tls_client_handshake_loop(URLContext *h, int initial)
147 TLSContext *c = h->priv_data;
148 TLSShared *s = &c->tls_shared;
149 SECURITY_STATUS sspi_ret;
151 SecBufferDesc outbuf_desc;
153 SecBufferDesc inbuf_desc;
154 int i, ret = 0, read_data = initial;
156 if (c->enc_buf == NULL) {
157 c->enc_buf_offset = 0;
158 ret = av_reallocp(&c->enc_buf, SCHANNEL_INITIAL_BUFFER_SIZE);
161 c->enc_buf_size = SCHANNEL_INITIAL_BUFFER_SIZE;
164 if (c->dec_buf == NULL) {
165 c->dec_buf_offset = 0;
166 ret = av_reallocp(&c->dec_buf, SCHANNEL_INITIAL_BUFFER_SIZE);
169 c->dec_buf_size = SCHANNEL_INITIAL_BUFFER_SIZE;
173 if (c->enc_buf_size - c->enc_buf_offset < SCHANNEL_FREE_BUFFER_SIZE) {
174 c->enc_buf_size = c->enc_buf_offset + SCHANNEL_FREE_BUFFER_SIZE;
175 ret = av_reallocp(&c->enc_buf, c->enc_buf_size);
177 c->enc_buf_size = c->enc_buf_offset = 0;
183 ret = ffurl_read(c->tls_shared.tcp, c->enc_buf + c->enc_buf_offset,
184 c->enc_buf_size - c->enc_buf_offset);
186 av_log(h, AV_LOG_ERROR, "Failed to read handshake response\n");
189 c->enc_buf_offset += ret;
193 init_sec_buffer(&inbuf[0], SECBUFFER_TOKEN, av_malloc(c->enc_buf_offset), c->enc_buf_offset);
194 init_sec_buffer(&inbuf[1], SECBUFFER_EMPTY, NULL, 0);
195 init_sec_buffer_desc(&inbuf_desc, inbuf, 2);
197 if (inbuf[0].pvBuffer == NULL) {
198 av_log(h, AV_LOG_ERROR, "Failed to allocate input buffer\n");
199 ret = AVERROR(ENOMEM);
203 memcpy(inbuf[0].pvBuffer, c->enc_buf, c->enc_buf_offset);
206 init_sec_buffer(&outbuf[0], SECBUFFER_TOKEN, NULL, 0);
207 init_sec_buffer(&outbuf[1], SECBUFFER_ALERT, NULL, 0);
208 init_sec_buffer(&outbuf[2], SECBUFFER_EMPTY, NULL, 0);
209 init_sec_buffer_desc(&outbuf_desc, outbuf, 3);
211 sspi_ret = InitializeSecurityContext(&c->cred_handle, &c->ctxt_handle, s->host, c->request_flags,
212 0, 0, &inbuf_desc, 0, NULL, &outbuf_desc, &c->context_flags,
214 av_freep(&inbuf[0].pvBuffer);
216 if (sspi_ret == SEC_E_INCOMPLETE_MESSAGE) {
217 av_log(h, AV_LOG_DEBUG, "Received incomplete handshake, need more data\n");
222 /* remote requests a client certificate - attempt to continue without one anyway */
223 if (sspi_ret == SEC_I_INCOMPLETE_CREDENTIALS &&
224 !(c->request_flags & ISC_REQ_USE_SUPPLIED_CREDS)) {
225 av_log(h, AV_LOG_VERBOSE, "Client certificate has been requested, ignoring\n");
226 c->request_flags |= ISC_REQ_USE_SUPPLIED_CREDS;
231 /* continue handshake */
232 if (sspi_ret == SEC_I_CONTINUE_NEEDED || sspi_ret == SEC_E_OK) {
233 for (i = 0; i < 3; i++) {
234 if (outbuf[i].BufferType == SECBUFFER_TOKEN && outbuf[i].cbBuffer > 0) {
235 ret = ffurl_write(c->tls_shared.tcp, outbuf[i].pvBuffer, outbuf[i].cbBuffer);
236 if (ret < 0 || ret != outbuf[i].cbBuffer) {
237 av_log(h, AV_LOG_VERBOSE, "Failed to send handshake data\n");
243 if (outbuf[i].pvBuffer != NULL) {
244 FreeContextBuffer(outbuf[i].pvBuffer);
245 outbuf[i].pvBuffer = NULL;
249 if (sspi_ret == SEC_E_WRONG_PRINCIPAL)
250 av_log(h, AV_LOG_ERROR, "SNI or certificate check failed\n");
252 av_log(h, AV_LOG_ERROR, "Creating security context failed (0x%lx)\n", sspi_ret);
253 ret = AVERROR_UNKNOWN;
257 if (inbuf[1].BufferType == SECBUFFER_EXTRA && inbuf[1].cbBuffer > 0) {
258 if (c->enc_buf_offset > inbuf[1].cbBuffer) {
259 memmove(c->enc_buf, (c->enc_buf + c->enc_buf_offset) - inbuf[1].cbBuffer,
261 c->enc_buf_offset = inbuf[1].cbBuffer;
262 if (sspi_ret == SEC_I_CONTINUE_NEEDED) {
268 c->enc_buf_offset = 0;
271 if (sspi_ret == SEC_I_CONTINUE_NEEDED) {
282 /* free any remaining output data */
283 for (i = 0; i < 3; i++) {
284 if (outbuf[i].pvBuffer != NULL) {
285 FreeContextBuffer(outbuf[i].pvBuffer);
286 outbuf[i].pvBuffer = NULL;
293 static int tls_client_handshake(URLContext *h)
295 TLSContext *c = h->priv_data;
296 TLSShared *s = &c->tls_shared;
298 SecBufferDesc outbuf_desc;
299 SECURITY_STATUS sspi_ret;
302 init_sec_buffer(&outbuf, SECBUFFER_EMPTY, NULL, 0);
303 init_sec_buffer_desc(&outbuf_desc, &outbuf, 1);
305 c->request_flags = ISC_REQ_SEQUENCE_DETECT | ISC_REQ_REPLAY_DETECT |
306 ISC_REQ_CONFIDENTIALITY | ISC_REQ_ALLOCATE_MEMORY |
309 sspi_ret = InitializeSecurityContext(&c->cred_handle, NULL, s->host, c->request_flags, 0, 0,
310 NULL, 0, &c->ctxt_handle, &outbuf_desc, &c->context_flags,
312 if (sspi_ret != SEC_I_CONTINUE_NEEDED) {
313 av_log(h, AV_LOG_ERROR, "Unable to create initial security context (0x%lx)\n", sspi_ret);
314 ret = AVERROR_UNKNOWN;
318 ret = ffurl_write(s->tcp, outbuf.pvBuffer, outbuf.cbBuffer);
319 FreeContextBuffer(outbuf.pvBuffer);
320 if (ret < 0 || ret != outbuf.cbBuffer) {
321 av_log(h, AV_LOG_ERROR, "Failed to send initial handshake data\n");
326 return tls_client_handshake_loop(h, 1);
329 DeleteSecurityContext(&c->ctxt_handle);
333 static int tls_open(URLContext *h, const char *uri, int flags, AVDictionary **options)
335 TLSContext *c = h->priv_data;
336 TLSShared *s = &c->tls_shared;
337 SECURITY_STATUS sspi_ret;
338 SCHANNEL_CRED schannel_cred = { 0 };
341 if ((ret = ff_tls_open_underlying(s, h, uri, options)) < 0)
345 av_log(h, AV_LOG_ERROR, "TLS Listen Sockets with SChannel is not implemented.\n");
346 ret = AVERROR(EINVAL);
350 /* SChannel Options */
351 schannel_cred.dwVersion = SCHANNEL_CRED_VERSION;
354 schannel_cred.dwFlags = SCH_CRED_AUTO_CRED_VALIDATION |
355 SCH_CRED_REVOCATION_CHECK_CHAIN;
357 schannel_cred.dwFlags = SCH_CRED_MANUAL_CRED_VALIDATION |
358 SCH_CRED_IGNORE_NO_REVOCATION_CHECK |
359 SCH_CRED_IGNORE_REVOCATION_OFFLINE;
361 /* Get credential handle */
362 sspi_ret = AcquireCredentialsHandle(NULL, (TCHAR *)UNISP_NAME, SECPKG_CRED_OUTBOUND,
363 NULL, &schannel_cred, NULL, NULL, &c->cred_handle,
365 if (sspi_ret != SEC_E_OK) {
366 av_log(h, AV_LOG_ERROR, "Unable to acquire security credentials (0x%lx)\n", sspi_ret);
367 ret = AVERROR_UNKNOWN;
371 ret = tls_client_handshake(h);
384 static int tls_read(URLContext *h, uint8_t *buf, int len)
386 TLSContext *c = h->priv_data;
387 TLSShared *s = &c->tls_shared;
388 SECURITY_STATUS sspi_ret = SEC_E_OK;
390 SecBufferDesc inbuf_desc;
392 int min_enc_buf_size = len + SCHANNEL_FREE_BUFFER_SIZE;
394 if (len <= c->dec_buf_offset)
397 if (c->sspi_close_notify)
400 if (!c->connection_closed) {
401 size = c->enc_buf_size - c->enc_buf_offset;
402 if (size < SCHANNEL_FREE_BUFFER_SIZE || c->enc_buf_size < min_enc_buf_size) {
403 c->enc_buf_size = c->enc_buf_offset + SCHANNEL_FREE_BUFFER_SIZE;
404 if (c->enc_buf_size < min_enc_buf_size)
405 c->enc_buf_size = min_enc_buf_size;
406 ret = av_reallocp(&c->enc_buf, c->enc_buf_size);
408 c->enc_buf_size = c->enc_buf_offset = 0;
413 ret = ffurl_read(s->tcp, c->enc_buf + c->enc_buf_offset,
414 c->enc_buf_size - c->enc_buf_offset);
416 av_log(h, AV_LOG_ERROR, "Unable to read from socket\n");
419 c->connection_closed = 1;
421 c->enc_buf_offset += ret;
424 while (c->enc_buf_offset > 0 && sspi_ret == SEC_E_OK && c->dec_buf_offset < len) {
426 init_sec_buffer(&inbuf[0], SECBUFFER_DATA, c->enc_buf, c->enc_buf_offset);
428 /* additional buffers for possible output */
429 init_sec_buffer(&inbuf[1], SECBUFFER_EMPTY, NULL, 0);
430 init_sec_buffer(&inbuf[2], SECBUFFER_EMPTY, NULL, 0);
431 init_sec_buffer(&inbuf[3], SECBUFFER_EMPTY, NULL, 0);
432 init_sec_buffer_desc(&inbuf_desc, inbuf, 4);
434 sspi_ret = DecryptMessage(&c->ctxt_handle, &inbuf_desc, 0, NULL);
435 if (sspi_ret == SEC_E_OK || sspi_ret == SEC_I_RENEGOTIATE ||
436 sspi_ret == SEC_I_CONTEXT_EXPIRED) {
437 /* handle decrypted data */
438 if (inbuf[1].BufferType == SECBUFFER_DATA) {
439 /* grow buffer if needed */
440 size = inbuf[1].cbBuffer > SCHANNEL_FREE_BUFFER_SIZE ?
441 inbuf[1].cbBuffer : SCHANNEL_FREE_BUFFER_SIZE;
442 if (c->dec_buf_size - c->dec_buf_offset < size || c->dec_buf_size < len) {
443 c->dec_buf_size = c->dec_buf_offset + size;
444 if (c->dec_buf_size < len)
445 c->dec_buf_size = len;
446 ret = av_reallocp(&c->dec_buf, c->dec_buf_size);
448 c->dec_buf_size = c->dec_buf_offset = 0;
453 /* copy decrypted data to buffer */
454 size = inbuf[1].cbBuffer;
456 memcpy(c->dec_buf + c->dec_buf_offset, inbuf[1].pvBuffer, size);
457 c->dec_buf_offset += size;
460 if (inbuf[3].BufferType == SECBUFFER_EXTRA && inbuf[3].cbBuffer > 0) {
461 if (c->enc_buf_offset > inbuf[3].cbBuffer) {
462 memmove(c->enc_buf, (c->enc_buf + c->enc_buf_offset) - inbuf[3].cbBuffer,
464 c->enc_buf_offset = inbuf[3].cbBuffer;
467 c->enc_buf_offset = 0;
469 if (sspi_ret == SEC_I_RENEGOTIATE) {
470 if (c->enc_buf_offset) {
471 av_log(h, AV_LOG_ERROR, "Cannot renegotiate, encrypted data buffer not empty\n");
472 ret = AVERROR_UNKNOWN;
476 av_log(h, AV_LOG_VERBOSE, "Re-negotiating security context\n");
477 ret = tls_client_handshake_loop(h, 0);
483 } else if (sspi_ret == SEC_I_CONTEXT_EXPIRED) {
484 c->sspi_close_notify = 1;
485 if (!c->connection_closed) {
486 c->connection_closed = 1;
487 av_log(h, AV_LOG_VERBOSE, "Server closed the connection\n");
492 } else if (sspi_ret == SEC_E_INCOMPLETE_MESSAGE) {
493 ret = AVERROR(EAGAIN);
496 av_log(h, AV_LOG_ERROR, "Unable to decrypt message\n");
505 size = FFMIN(len, c->dec_buf_offset);
507 memcpy(buf, c->dec_buf, size);
508 memmove(c->dec_buf, c->dec_buf + size, c->dec_buf_offset - size);
509 c->dec_buf_offset -= size;
514 if (ret == 0 && !c->connection_closed)
515 ret = AVERROR(EAGAIN);
517 return ret < 0 ? ret : 0;
520 static int tls_write(URLContext *h, const uint8_t *buf, int len)
522 TLSContext *c = h->priv_data;
523 TLSShared *s = &c->tls_shared;
524 SECURITY_STATUS sspi_ret;
525 int ret = 0, data_size;
526 uint8_t *data = NULL;
528 SecBufferDesc outbuf_desc;
530 if (c->sizes.cbMaximumMessage == 0) {
531 sspi_ret = QueryContextAttributes(&c->ctxt_handle, SECPKG_ATTR_STREAM_SIZES, &c->sizes);
532 if (sspi_ret != SEC_E_OK)
533 return AVERROR_UNKNOWN;
536 /* limit how much data we can consume */
537 len = FFMIN(len, c->sizes.cbMaximumMessage);
539 data_size = c->sizes.cbHeader + len + c->sizes.cbTrailer;
540 data = av_malloc(data_size);
542 return AVERROR(ENOMEM);
544 init_sec_buffer(&outbuf[0], SECBUFFER_STREAM_HEADER,
545 data, c->sizes.cbHeader);
546 init_sec_buffer(&outbuf[1], SECBUFFER_DATA,
547 data + c->sizes.cbHeader, len);
548 init_sec_buffer(&outbuf[2], SECBUFFER_STREAM_TRAILER,
549 data + c->sizes.cbHeader + len,
551 init_sec_buffer(&outbuf[3], SECBUFFER_EMPTY, NULL, 0);
552 init_sec_buffer_desc(&outbuf_desc, outbuf, 4);
554 memcpy(outbuf[1].pvBuffer, buf, len);
556 sspi_ret = EncryptMessage(&c->ctxt_handle, 0, &outbuf_desc, 0);
557 if (sspi_ret == SEC_E_OK) {
558 len = outbuf[0].cbBuffer + outbuf[1].cbBuffer + outbuf[2].cbBuffer;
559 ret = ffurl_write(s->tcp, data, len);
560 if (ret < 0 || ret != len) {
562 av_log(h, AV_LOG_ERROR, "Writing encrypted data to socket failed\n");
566 av_log(h, AV_LOG_ERROR, "Encrypting data failed\n");
567 if (sspi_ret == SEC_E_INSUFFICIENT_MEMORY)
568 ret = AVERROR(ENOMEM);
576 return ret < 0 ? ret : outbuf[1].cbBuffer;
579 static const AVOption options[] = {
580 TLS_COMMON_OPTIONS(TLSContext, tls_shared),
584 static const AVClass tls_class = {
586 .item_name = av_default_item_name,
588 .version = LIBAVUTIL_VERSION_INT,
591 URLProtocol ff_tls_schannel_protocol = {
593 .url_open2 = tls_open,
594 .url_read = tls_read,
595 .url_write = tls_write,
596 .url_close = tls_close,
597 .priv_data_size = sizeof(TLSContext),
598 .flags = URL_PROTOCOL_FLAG_NETWORK,
599 .priv_data_class = &tls_class,