wined3d: Pass a wined3d_device_context to wined3d_cs_emit_blt_sub_resource().
[wine/zf.git] / dlls / secur32 / schannel.c
blob1dd3a0294016c8bc92d16581b9bfd8f62af48756
1 /* Copyright (C) 2005 Juan Lang
2 * Copyright 2008 Henri Verbeet
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
18 * This file implements the schannel provider, or, the SSL/TLS implementations.
20 #include "config.h"
21 #include "wine/port.h"
23 #include <stdarg.h>
24 #include <errno.h>
26 #define NONAMELESSUNION
27 #include "windef.h"
28 #include "winbase.h"
29 #include "winreg.h"
30 #include "winnls.h"
31 #include "sspi.h"
32 #include "schannel.h"
33 #include "secur32_priv.h"
35 #include "wine/unicode.h"
36 #include "wine/debug.h"
38 WINE_DEFAULT_DEBUG_CHANNEL(secur32);
40 #if defined(SONAME_LIBGNUTLS) || defined (HAVE_SECURITY_SECURITY_H)
42 #define SCHAN_INVALID_HANDLE ~0UL
44 enum schan_handle_type
46 SCHAN_HANDLE_CRED,
47 SCHAN_HANDLE_CTX,
48 SCHAN_HANDLE_FREE
51 struct schan_handle
53 void *object;
54 enum schan_handle_type type;
57 struct schan_context
59 schan_imp_session session;
60 struct schan_transport transport;
61 ULONG req_ctx_attr;
62 const CERT_CONTEXT *cert;
63 SIZE_T header_size;
66 static struct schan_handle *schan_handle_table;
67 static struct schan_handle *schan_free_handles;
68 static SIZE_T schan_handle_table_size;
69 static SIZE_T schan_handle_count;
71 /* Protocols enabled, only those may be used for the connection. */
72 static DWORD config_enabled_protocols;
74 /* Protocols disabled by default. They are enabled for using, but disabled when caller asks for default settings. */
75 static DWORD config_default_disabled_protocols;
77 static ULONG_PTR schan_alloc_handle(void *object, enum schan_handle_type type)
79 struct schan_handle *handle;
81 if (schan_free_handles)
83 DWORD index = schan_free_handles - schan_handle_table;
84 /* Use a free handle */
85 handle = schan_free_handles;
86 if (handle->type != SCHAN_HANDLE_FREE)
88 ERR("Handle %d(%p) is in the free list, but has type %#x.\n", index, handle, handle->type);
89 return SCHAN_INVALID_HANDLE;
91 schan_free_handles = handle->object;
92 handle->object = object;
93 handle->type = type;
95 return index;
97 if (!(schan_handle_count < schan_handle_table_size))
99 /* Grow the table */
100 SIZE_T new_size = schan_handle_table_size + (schan_handle_table_size >> 1);
101 struct schan_handle *new_table = heap_realloc(schan_handle_table, new_size * sizeof(*schan_handle_table));
102 if (!new_table)
104 ERR("Failed to grow the handle table\n");
105 return SCHAN_INVALID_HANDLE;
107 schan_handle_table = new_table;
108 schan_handle_table_size = new_size;
111 handle = &schan_handle_table[schan_handle_count++];
112 handle->object = object;
113 handle->type = type;
115 return handle - schan_handle_table;
118 static void *schan_free_handle(ULONG_PTR handle_idx, enum schan_handle_type type)
120 struct schan_handle *handle;
121 void *object;
123 if (handle_idx == SCHAN_INVALID_HANDLE) return NULL;
124 if (handle_idx >= schan_handle_count) return NULL;
125 handle = &schan_handle_table[handle_idx];
126 if (handle->type != type)
128 ERR("Handle %ld(%p) is not of type %#x\n", handle_idx, handle, type);
129 return NULL;
132 object = handle->object;
133 handle->object = schan_free_handles;
134 handle->type = SCHAN_HANDLE_FREE;
135 schan_free_handles = handle;
137 return object;
140 static void *schan_get_object(ULONG_PTR handle_idx, enum schan_handle_type type)
142 struct schan_handle *handle;
144 if (handle_idx == SCHAN_INVALID_HANDLE) return NULL;
145 if (handle_idx >= schan_handle_count) return NULL;
146 handle = &schan_handle_table[handle_idx];
147 if (handle->type != type)
149 ERR("Handle %ld(%p) is not of type %#x\n", handle_idx, handle, type);
150 return NULL;
153 return handle->object;
156 static void read_config(void)
158 DWORD enabled = 0, default_disabled = 0;
159 HKEY protocols_key, key;
160 WCHAR subkey_name[64];
161 unsigned i;
162 DWORD res;
164 static BOOL config_read = FALSE;
166 static const WCHAR protocol_config_key_name[] = {
167 'S','Y','S','T','E','M','\\',
168 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
169 'C','o','n','t','r','o','l','\\',
170 'S','e','c','u','r','i','t','y','P','r','o','v','i','d','e','r','s','\\',
171 'S','C','H','A','N','N','E','L','\\',
172 'P','r','o','t','o','c','o','l','s',0 };
174 static const WCHAR clientW[] = {'\\','C','l','i','e','n','t',0};
175 static const WCHAR enabledW[] = {'e','n','a','b','l','e','d',0};
176 static const WCHAR disabledbydefaultW[] = {'D','i','s','a','b','l','e','d','B','y','D','e','f','a','u','l','t',0};
178 static const struct {
179 WCHAR key_name[20];
180 DWORD prot_client_flag;
181 BOOL enabled; /* If no config is present, enable the protocol */
182 BOOL disabled_by_default; /* Disable if caller asks for default protocol set */
183 } protocol_config_keys[] = {
184 {{'S','S','L',' ','2','.','0',0}, SP_PROT_SSL2_CLIENT, FALSE, TRUE}, /* NOTE: TRUE, TRUE on Windows */
185 {{'S','S','L',' ','3','.','0',0}, SP_PROT_SSL3_CLIENT, TRUE, FALSE},
186 {{'T','L','S',' ','1','.','0',0}, SP_PROT_TLS1_0_CLIENT, TRUE, FALSE},
187 {{'T','L','S',' ','1','.','1',0}, SP_PROT_TLS1_1_CLIENT, TRUE, FALSE /* NOTE: not enabled by default on Windows */ },
188 {{'T','L','S',' ','1','.','2',0}, SP_PROT_TLS1_2_CLIENT, TRUE, FALSE /* NOTE: not enabled by default on Windows */ },
189 {{'D','T','L','S',' ','1','.','0',0}, SP_PROT_DTLS1_0_CLIENT, TRUE, TRUE },
190 {{'D','T','L','S',' ','1','.','2',0}, SP_PROT_DTLS1_2_CLIENT, TRUE, TRUE },
193 /* No need for thread safety */
194 if(config_read)
195 return;
197 res = RegOpenKeyExW(HKEY_LOCAL_MACHINE, protocol_config_key_name, 0, KEY_READ, &protocols_key);
198 if(res == ERROR_SUCCESS) {
199 DWORD type, size, value;
201 for(i = 0; i < ARRAY_SIZE(protocol_config_keys); i++) {
202 strcpyW(subkey_name, protocol_config_keys[i].key_name);
203 strcatW(subkey_name, clientW);
204 res = RegOpenKeyExW(protocols_key, subkey_name, 0, KEY_READ, &key);
205 if(res != ERROR_SUCCESS) {
206 if(protocol_config_keys[i].enabled)
207 enabled |= protocol_config_keys[i].prot_client_flag;
208 if(protocol_config_keys[i].disabled_by_default)
209 default_disabled |= protocol_config_keys[i].prot_client_flag;
210 continue;
213 size = sizeof(value);
214 res = RegQueryValueExW(key, enabledW, NULL, &type, (BYTE*)&value, &size);
215 if(res == ERROR_SUCCESS) {
216 if(type == REG_DWORD && value)
217 enabled |= protocol_config_keys[i].prot_client_flag;
218 }else if(protocol_config_keys[i].enabled) {
219 enabled |= protocol_config_keys[i].prot_client_flag;
222 size = sizeof(value);
223 res = RegQueryValueExW(key, disabledbydefaultW, NULL, &type, (BYTE*)&value, &size);
224 if(res == ERROR_SUCCESS) {
225 if(type != REG_DWORD || value)
226 default_disabled |= protocol_config_keys[i].prot_client_flag;
227 }else if(protocol_config_keys[i].disabled_by_default) {
228 default_disabled |= protocol_config_keys[i].prot_client_flag;
231 RegCloseKey(key);
233 }else {
234 /* No config, enable all known protocols. */
235 for(i = 0; i < ARRAY_SIZE(protocol_config_keys); i++) {
236 if(protocol_config_keys[i].enabled)
237 enabled |= protocol_config_keys[i].prot_client_flag;
238 if(protocol_config_keys[i].disabled_by_default)
239 default_disabled |= protocol_config_keys[i].prot_client_flag;
243 RegCloseKey(protocols_key);
245 config_enabled_protocols = enabled & schan_imp_enabled_protocols();
246 config_default_disabled_protocols = default_disabled;
247 config_read = TRUE;
249 TRACE("enabled %x, disabled by default %x\n", config_enabled_protocols, config_default_disabled_protocols);
252 static SECURITY_STATUS schan_QueryCredentialsAttributes(
253 PCredHandle phCredential, ULONG ulAttribute, VOID *pBuffer)
255 struct schan_credentials *cred;
256 SECURITY_STATUS ret;
258 cred = schan_get_object(phCredential->dwLower, SCHAN_HANDLE_CRED);
259 if(!cred)
260 return SEC_E_INVALID_HANDLE;
262 switch (ulAttribute)
264 case SECPKG_ATTR_SUPPORTED_ALGS:
265 if (pBuffer)
267 /* FIXME: get from CryptoAPI */
268 FIXME("SECPKG_ATTR_SUPPORTED_ALGS: stub\n");
269 ret = SEC_E_UNSUPPORTED_FUNCTION;
271 else
272 ret = SEC_E_INTERNAL_ERROR;
273 break;
274 case SECPKG_ATTR_CIPHER_STRENGTHS:
275 if (pBuffer)
277 SecPkgCred_CipherStrengths *r = pBuffer;
279 /* FIXME: get from CryptoAPI */
280 FIXME("SECPKG_ATTR_CIPHER_STRENGTHS: semi-stub\n");
281 r->dwMinimumCipherStrength = 40;
282 r->dwMaximumCipherStrength = 168;
283 ret = SEC_E_OK;
285 else
286 ret = SEC_E_INTERNAL_ERROR;
287 break;
288 case SECPKG_ATTR_SUPPORTED_PROTOCOLS:
289 if(pBuffer) {
290 /* Regardless of MSDN documentation, tests show that this attribute takes into account
291 * what protocols are enabled for given credential. */
292 ((SecPkgCred_SupportedProtocols*)pBuffer)->grbitProtocol = cred->enabled_protocols;
293 ret = SEC_E_OK;
294 }else {
295 ret = SEC_E_INTERNAL_ERROR;
297 break;
298 default:
299 ret = SEC_E_UNSUPPORTED_FUNCTION;
301 return ret;
304 static SECURITY_STATUS SEC_ENTRY schan_QueryCredentialsAttributesA(
305 PCredHandle phCredential, ULONG ulAttribute, PVOID pBuffer)
307 SECURITY_STATUS ret;
309 TRACE("(%p, %d, %p)\n", phCredential, ulAttribute, pBuffer);
311 switch (ulAttribute)
313 case SECPKG_CRED_ATTR_NAMES:
314 FIXME("SECPKG_CRED_ATTR_NAMES: stub\n");
315 ret = SEC_E_UNSUPPORTED_FUNCTION;
316 break;
317 default:
318 ret = schan_QueryCredentialsAttributes(phCredential, ulAttribute,
319 pBuffer);
321 return ret;
324 static SECURITY_STATUS SEC_ENTRY schan_QueryCredentialsAttributesW(
325 PCredHandle phCredential, ULONG ulAttribute, PVOID pBuffer)
327 SECURITY_STATUS ret;
329 TRACE("(%p, %d, %p)\n", phCredential, ulAttribute, pBuffer);
331 switch (ulAttribute)
333 case SECPKG_CRED_ATTR_NAMES:
334 FIXME("SECPKG_CRED_ATTR_NAMES: stub\n");
335 ret = SEC_E_UNSUPPORTED_FUNCTION;
336 break;
337 default:
338 ret = schan_QueryCredentialsAttributes(phCredential, ulAttribute,
339 pBuffer);
341 return ret;
344 static SECURITY_STATUS get_cert(const SCHANNEL_CRED *cred, CERT_CONTEXT const **cert)
346 SECURITY_STATUS status;
347 DWORD i;
349 TRACE("dwVersion = %u\n", cred->dwVersion);
350 TRACE("cCreds = %u\n", cred->cCreds);
351 TRACE("paCred = %p\n", cred->paCred);
352 TRACE("hRootStore = %p\n", cred->hRootStore);
353 TRACE("cMappers = %u\n", cred->cMappers);
354 TRACE("cSupportedAlgs = %u:\n", cred->cSupportedAlgs);
355 for (i = 0; i < cred->cSupportedAlgs; i++) TRACE("%08x\n", cred->palgSupportedAlgs[i]);
356 TRACE("grbitEnabledProtocols = %08x\n", cred->grbitEnabledProtocols);
357 TRACE("dwMinimumCipherStrength = %u\n", cred->dwMinimumCipherStrength);
358 TRACE("dwMaximumCipherStrength = %u\n", cred->dwMaximumCipherStrength);
359 TRACE("dwSessionLifespan = %u\n", cred->dwSessionLifespan);
360 TRACE("dwFlags = %08x\n", cred->dwFlags);
361 TRACE("dwCredFormat = %u\n", cred->dwCredFormat);
363 switch (cred->dwVersion)
365 case SCH_CRED_V3:
366 case SCHANNEL_CRED_VERSION:
367 break;
368 default:
369 return SEC_E_INTERNAL_ERROR;
372 if (!cred->cCreds) status = SEC_E_NO_CREDENTIALS;
373 else if (cred->cCreds > 1) status = SEC_E_UNKNOWN_CREDENTIALS;
374 else
376 DWORD spec;
377 HCRYPTPROV prov;
378 BOOL free;
380 if (CryptAcquireCertificatePrivateKey(cred->paCred[0], CRYPT_ACQUIRE_CACHE_FLAG, NULL, &prov, &spec, &free))
382 if (free) CryptReleaseContext(prov, 0);
383 *cert = cred->paCred[0];
384 status = SEC_E_OK;
386 else status = SEC_E_UNKNOWN_CREDENTIALS;
389 return status;
392 static SECURITY_STATUS schan_AcquireClientCredentials(const SCHANNEL_CRED *schanCred,
393 PCredHandle phCredential, PTimeStamp ptsExpiry)
395 struct schan_credentials *creds;
396 unsigned enabled_protocols;
397 ULONG_PTR handle;
398 SECURITY_STATUS status = SEC_E_OK;
399 const CERT_CONTEXT *cert = NULL;
401 TRACE("schanCred %p, phCredential %p, ptsExpiry %p\n", schanCred, phCredential, ptsExpiry);
403 if (schanCred)
405 const unsigned dtls_protocols = SP_PROT_DTLS_CLIENT | SP_PROT_DTLS1_2_CLIENT;
406 const unsigned tls_protocols = SP_PROT_TLS1_CLIENT | SP_PROT_TLS1_0_CLIENT | SP_PROT_TLS1_1_CLIENT |
407 SP_PROT_TLS1_2_CLIENT | SP_PROT_TLS1_3_CLIENT;
409 status = get_cert(schanCred, &cert);
410 if (status != SEC_E_OK && status != SEC_E_NO_CREDENTIALS)
411 return status;
413 if ((schanCred->grbitEnabledProtocols & tls_protocols) &&
414 (schanCred->grbitEnabledProtocols & dtls_protocols)) return SEC_E_ALGORITHM_MISMATCH;
416 status = SEC_E_OK;
419 read_config();
420 if(schanCred && schanCred->grbitEnabledProtocols)
421 enabled_protocols = schanCred->grbitEnabledProtocols & config_enabled_protocols;
422 else
423 enabled_protocols = config_enabled_protocols & ~config_default_disabled_protocols;
424 if(!enabled_protocols) {
425 ERR("Could not find matching protocol\n");
426 return SEC_E_NO_AUTHENTICATING_AUTHORITY;
429 creds = heap_alloc(sizeof(*creds));
430 if (!creds) return SEC_E_INSUFFICIENT_MEMORY;
432 handle = schan_alloc_handle(creds, SCHAN_HANDLE_CRED);
433 if (handle == SCHAN_INVALID_HANDLE) goto fail;
435 creds->credential_use = SECPKG_CRED_OUTBOUND;
436 if (!schan_imp_allocate_certificate_credentials(creds, cert))
438 schan_free_handle(handle, SCHAN_HANDLE_CRED);
439 goto fail;
442 creds->enabled_protocols = enabled_protocols;
443 phCredential->dwLower = handle;
444 phCredential->dwUpper = 0;
446 /* Outbound credentials have no expiry */
447 if (ptsExpiry)
449 ptsExpiry->LowPart = 0;
450 ptsExpiry->HighPart = 0;
453 return status;
455 fail:
456 heap_free(creds);
457 return SEC_E_INTERNAL_ERROR;
460 static SECURITY_STATUS schan_AcquireServerCredentials(const SCHANNEL_CRED *schanCred,
461 PCredHandle phCredential, PTimeStamp ptsExpiry)
463 SECURITY_STATUS status;
464 const CERT_CONTEXT *cert = NULL;
466 TRACE("schanCred %p, phCredential %p, ptsExpiry %p\n", schanCred, phCredential, ptsExpiry);
468 if (!schanCred) return SEC_E_NO_CREDENTIALS;
470 status = get_cert(schanCred, &cert);
471 if (status == SEC_E_OK)
473 ULONG_PTR handle;
474 struct schan_credentials *creds;
476 creds = heap_alloc_zero(sizeof(*creds));
477 if (!creds) return SEC_E_INSUFFICIENT_MEMORY;
478 creds->credential_use = SECPKG_CRED_INBOUND;
480 handle = schan_alloc_handle(creds, SCHAN_HANDLE_CRED);
481 if (handle == SCHAN_INVALID_HANDLE)
483 heap_free(creds);
484 return SEC_E_INTERNAL_ERROR;
487 phCredential->dwLower = handle;
488 phCredential->dwUpper = 0;
490 /* FIXME: get expiry from cert */
492 return status;
495 static SECURITY_STATUS schan_AcquireCredentialsHandle(ULONG fCredentialUse,
496 const SCHANNEL_CRED *schanCred, PCredHandle phCredential, PTimeStamp ptsExpiry)
498 SECURITY_STATUS ret;
500 if (fCredentialUse == SECPKG_CRED_OUTBOUND)
501 ret = schan_AcquireClientCredentials(schanCred, phCredential,
502 ptsExpiry);
503 else
504 ret = schan_AcquireServerCredentials(schanCred, phCredential,
505 ptsExpiry);
506 return ret;
509 static SECURITY_STATUS SEC_ENTRY schan_AcquireCredentialsHandleA(
510 SEC_CHAR *pszPrincipal, SEC_CHAR *pszPackage, ULONG fCredentialUse,
511 PLUID pLogonID, PVOID pAuthData, SEC_GET_KEY_FN pGetKeyFn,
512 PVOID pGetKeyArgument, PCredHandle phCredential, PTimeStamp ptsExpiry)
514 TRACE("(%s, %s, 0x%08x, %p, %p, %p, %p, %p, %p)\n",
515 debugstr_a(pszPrincipal), debugstr_a(pszPackage), fCredentialUse,
516 pLogonID, pAuthData, pGetKeyFn, pGetKeyArgument, phCredential, ptsExpiry);
517 return schan_AcquireCredentialsHandle(fCredentialUse,
518 pAuthData, phCredential, ptsExpiry);
521 static SECURITY_STATUS SEC_ENTRY schan_AcquireCredentialsHandleW(
522 SEC_WCHAR *pszPrincipal, SEC_WCHAR *pszPackage, ULONG fCredentialUse,
523 PLUID pLogonID, PVOID pAuthData, SEC_GET_KEY_FN pGetKeyFn,
524 PVOID pGetKeyArgument, PCredHandle phCredential, PTimeStamp ptsExpiry)
526 TRACE("(%s, %s, 0x%08x, %p, %p, %p, %p, %p, %p)\n",
527 debugstr_w(pszPrincipal), debugstr_w(pszPackage), fCredentialUse,
528 pLogonID, pAuthData, pGetKeyFn, pGetKeyArgument, phCredential, ptsExpiry);
529 return schan_AcquireCredentialsHandle(fCredentialUse,
530 pAuthData, phCredential, ptsExpiry);
533 static SECURITY_STATUS SEC_ENTRY schan_FreeCredentialsHandle(
534 PCredHandle phCredential)
536 struct schan_credentials *creds;
538 TRACE("phCredential %p\n", phCredential);
540 if (!phCredential) return SEC_E_INVALID_HANDLE;
542 creds = schan_free_handle(phCredential->dwLower, SCHAN_HANDLE_CRED);
543 if (!creds) return SEC_E_INVALID_HANDLE;
545 if (creds->credential_use == SECPKG_CRED_OUTBOUND)
546 schan_imp_free_certificate_credentials(creds);
547 heap_free(creds);
549 return SEC_E_OK;
552 static void init_schan_buffers(struct schan_buffers *s, const PSecBufferDesc desc,
553 int (*get_next_buffer)(const struct schan_transport *, struct schan_buffers *))
555 s->offset = 0;
556 s->limit = ~0UL;
557 s->desc = desc;
558 s->current_buffer_idx = -1;
559 s->allow_buffer_resize = FALSE;
560 s->get_next_buffer = get_next_buffer;
563 static int schan_find_sec_buffer_idx(const SecBufferDesc *desc, unsigned int start_idx, ULONG buffer_type)
565 unsigned int i;
566 PSecBuffer buffer;
568 for (i = start_idx; i < desc->cBuffers; ++i)
570 buffer = &desc->pBuffers[i];
571 if (buffer->BufferType == buffer_type) return i;
574 return -1;
577 static void schan_resize_current_buffer(const struct schan_buffers *s, SIZE_T min_size)
579 SecBuffer *b = &s->desc->pBuffers[s->current_buffer_idx];
580 SIZE_T new_size = b->cbBuffer ? b->cbBuffer * 2 : 128;
581 void *new_data;
583 if (b->cbBuffer >= min_size || !s->allow_buffer_resize || min_size > UINT_MAX / 2) return;
585 while (new_size < min_size) new_size *= 2;
587 if (b->pvBuffer)
588 new_data = heap_realloc(b->pvBuffer, new_size);
589 else
590 new_data = heap_alloc(new_size);
592 if (!new_data)
594 TRACE("Failed to resize %p from %d to %ld\n", b->pvBuffer, b->cbBuffer, new_size);
595 return;
598 b->cbBuffer = new_size;
599 b->pvBuffer = new_data;
602 char *schan_get_buffer(const struct schan_transport *t, struct schan_buffers *s, SIZE_T *count)
604 SIZE_T max_count;
605 PSecBuffer buffer;
607 if (!s->desc)
609 TRACE("No desc\n");
610 return NULL;
613 if (s->current_buffer_idx == -1)
615 /* Initial buffer */
616 int buffer_idx = s->get_next_buffer(t, s);
617 if (buffer_idx == -1)
619 TRACE("No next buffer\n");
620 return NULL;
622 s->current_buffer_idx = buffer_idx;
625 buffer = &s->desc->pBuffers[s->current_buffer_idx];
626 TRACE("Using buffer %d: cbBuffer %d, BufferType %#x, pvBuffer %p\n", s->current_buffer_idx, buffer->cbBuffer, buffer->BufferType, buffer->pvBuffer);
628 schan_resize_current_buffer(s, s->offset + *count);
629 max_count = buffer->cbBuffer - s->offset;
630 if (s->limit != ~0UL && s->limit < max_count)
631 max_count = s->limit;
632 if (!max_count)
634 int buffer_idx;
636 s->allow_buffer_resize = FALSE;
637 buffer_idx = s->get_next_buffer(t, s);
638 if (buffer_idx == -1)
640 TRACE("No next buffer\n");
641 return NULL;
643 s->current_buffer_idx = buffer_idx;
644 s->offset = 0;
645 return schan_get_buffer(t, s, count);
648 if (*count > max_count)
649 *count = max_count;
650 if (s->limit != ~0UL)
651 s->limit -= *count;
653 return (char *)buffer->pvBuffer + s->offset;
656 /* schan_pull
657 * Read data from the transport input buffer.
659 * t - The session transport object.
660 * buff - The buffer into which to store the read data. Must be at least
661 * *buff_len bytes in length.
662 * buff_len - On input, *buff_len is the desired length to read. On successful
663 * return, *buff_len is the number of bytes actually read.
665 * Returns:
666 * 0 on success, in which case:
667 * *buff_len == 0 indicates end of file.
668 * *buff_len > 0 indicates that some data was read. May be less than
669 * what was requested, in which case the caller should call again if/
670 * when they want more.
671 * EAGAIN when no data could be read without blocking
672 * another errno-style error value on failure
675 int schan_pull(struct schan_transport *t, void *buff, size_t *buff_len)
677 char *b;
678 SIZE_T local_len = *buff_len;
680 TRACE("Pull %lu bytes\n", local_len);
682 *buff_len = 0;
684 b = schan_get_buffer(t, &t->in, &local_len);
685 if (!b)
686 return EAGAIN;
688 memcpy(buff, b, local_len);
689 t->in.offset += local_len;
691 TRACE("Read %lu bytes\n", local_len);
693 *buff_len = local_len;
694 return 0;
697 /* schan_push
698 * Write data to the transport output buffer.
700 * t - The session transport object.
701 * buff - The buffer of data to write. Must be at least *buff_len bytes in length.
702 * buff_len - On input, *buff_len is the desired length to write. On successful
703 * return, *buff_len is the number of bytes actually written.
705 * Returns:
706 * 0 on success
707 * *buff_len will be > 0 indicating how much data was written. May be less
708 * than what was requested, in which case the caller should call again
709 if/when they want to write more.
710 * EAGAIN when no data could be written without blocking
711 * another errno-style error value on failure
714 int schan_push(struct schan_transport *t, const void *buff, size_t *buff_len)
716 char *b;
717 SIZE_T local_len = *buff_len;
719 TRACE("Push %lu bytes\n", local_len);
721 *buff_len = 0;
723 b = schan_get_buffer(t, &t->out, &local_len);
724 if (!b)
725 return EAGAIN;
727 memcpy(b, buff, local_len);
728 t->out.offset += local_len;
730 TRACE("Wrote %lu bytes\n", local_len);
732 *buff_len = local_len;
733 return 0;
736 schan_imp_session schan_session_for_transport(struct schan_transport* t)
738 return t->ctx->session;
741 static int schan_init_sec_ctx_get_next_input_buffer(const struct schan_transport *t, struct schan_buffers *s)
743 if (s->current_buffer_idx != -1)
744 return -1;
745 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
748 static int schan_init_sec_ctx_get_next_output_buffer(const struct schan_transport *t, struct schan_buffers *s)
750 if (s->current_buffer_idx == -1)
752 int idx = schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
753 if (t->ctx->req_ctx_attr & ISC_REQ_ALLOCATE_MEMORY)
755 if (idx == -1)
757 idx = schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_EMPTY);
758 if (idx != -1) s->desc->pBuffers[idx].BufferType = SECBUFFER_TOKEN;
760 if (idx != -1 && !s->desc->pBuffers[idx].pvBuffer)
762 s->desc->pBuffers[idx].cbBuffer = 0;
763 s->allow_buffer_resize = TRUE;
766 return idx;
769 return -1;
772 static void dump_buffer_desc(SecBufferDesc *desc)
774 unsigned int i;
776 if (!desc) return;
777 TRACE("Buffer desc %p:\n", desc);
778 for (i = 0; i < desc->cBuffers; ++i)
780 SecBuffer *b = &desc->pBuffers[i];
781 TRACE("\tbuffer %u: cbBuffer %d, BufferType %#x pvBuffer %p\n", i, b->cbBuffer, b->BufferType, b->pvBuffer);
785 #define HEADER_SIZE_TLS 5
786 #define HEADER_SIZE_DTLS 13
788 static inline SIZE_T read_record_size(const BYTE *buf, SIZE_T header_size)
790 return (buf[header_size - 2] << 8) | buf[header_size - 1];
793 static inline BOOL is_dtls_context(const struct schan_context *ctx)
795 return (ctx->header_size == HEADER_SIZE_DTLS);
798 /***********************************************************************
799 * InitializeSecurityContextW
801 static SECURITY_STATUS SEC_ENTRY schan_InitializeSecurityContextW(
802 PCredHandle phCredential, PCtxtHandle phContext, SEC_WCHAR *pszTargetName,
803 ULONG fContextReq, ULONG Reserved1, ULONG TargetDataRep,
804 PSecBufferDesc pInput, ULONG Reserved2, PCtxtHandle phNewContext,
805 PSecBufferDesc pOutput, ULONG *pfContextAttr, PTimeStamp ptsExpiry)
807 struct schan_context *ctx;
808 struct schan_buffers *out_buffers;
809 struct schan_credentials *cred;
810 SIZE_T expected_size = ~0UL;
811 SECURITY_STATUS ret;
812 SecBuffer *buffer;
813 int idx;
815 TRACE("%p %p %s 0x%08x %d %d %p %d %p %p %p %p\n", phCredential, phContext,
816 debugstr_w(pszTargetName), fContextReq, Reserved1, TargetDataRep, pInput,
817 Reserved1, phNewContext, pOutput, pfContextAttr, ptsExpiry);
819 dump_buffer_desc(pInput);
820 dump_buffer_desc(pOutput);
822 if (!phContext)
824 ULONG_PTR handle;
826 if (!phCredential) return SEC_E_INVALID_HANDLE;
828 cred = schan_get_object(phCredential->dwLower, SCHAN_HANDLE_CRED);
829 if (!cred) return SEC_E_INVALID_HANDLE;
831 if (!(cred->credential_use & SECPKG_CRED_OUTBOUND))
833 WARN("Invalid credential use %#x\n", cred->credential_use);
834 return SEC_E_INVALID_HANDLE;
837 ctx = heap_alloc(sizeof(*ctx));
838 if (!ctx) return SEC_E_INSUFFICIENT_MEMORY;
840 ctx->cert = NULL;
841 handle = schan_alloc_handle(ctx, SCHAN_HANDLE_CTX);
842 if (handle == SCHAN_INVALID_HANDLE)
844 heap_free(ctx);
845 return SEC_E_INTERNAL_ERROR;
848 if (!schan_imp_create_session(&ctx->session, cred))
850 schan_free_handle(handle, SCHAN_HANDLE_CTX);
851 heap_free(ctx);
852 return SEC_E_INTERNAL_ERROR;
855 if (cred->enabled_protocols & (SP_PROT_DTLS1_0_CLIENT | SP_PROT_DTLS1_2_CLIENT))
856 ctx->header_size = HEADER_SIZE_DTLS;
857 else
858 ctx->header_size = HEADER_SIZE_TLS;
860 ctx->transport.ctx = ctx;
861 schan_imp_set_session_transport(ctx->session, &ctx->transport);
863 if (pszTargetName && *pszTargetName)
865 UINT len = WideCharToMultiByte( CP_UNIXCP, 0, pszTargetName, -1, NULL, 0, NULL, NULL );
866 char *target = heap_alloc( len );
868 if (target)
870 WideCharToMultiByte( CP_UNIXCP, 0, pszTargetName, -1, target, len, NULL, NULL );
871 schan_imp_set_session_target( ctx->session, target );
872 heap_free( target );
876 if (pInput && (idx = schan_find_sec_buffer_idx(pInput, 0, SECBUFFER_APPLICATION_PROTOCOLS)) != -1)
878 buffer = &pInput->pBuffers[idx];
879 schan_imp_set_application_protocols(ctx->session, buffer->pvBuffer, buffer->cbBuffer);
882 if (pInput && (idx = schan_find_sec_buffer_idx(pInput, 0, SECBUFFER_DTLS_MTU)) != -1)
884 buffer = &pInput->pBuffers[idx];
885 if (buffer->cbBuffer >= sizeof(WORD)) schan_imp_set_dtls_mtu(ctx->session, *(WORD *)buffer->pvBuffer);
886 else WARN("invalid buffer size %u\n", buffer->cbBuffer);
889 phNewContext->dwLower = handle;
890 phNewContext->dwUpper = 0;
892 else
894 SIZE_T record_size = 0;
895 unsigned char *ptr;
897 ctx = schan_get_object(phContext->dwLower, SCHAN_HANDLE_CTX);
898 if (pInput)
900 idx = schan_find_sec_buffer_idx(pInput, 0, SECBUFFER_TOKEN);
901 if (idx == -1)
902 return SEC_E_INCOMPLETE_MESSAGE;
904 buffer = &pInput->pBuffers[idx];
905 ptr = buffer->pvBuffer;
906 expected_size = 0;
908 while (buffer->cbBuffer > expected_size + ctx->header_size)
910 record_size = ctx->header_size + read_record_size(ptr, ctx->header_size);
912 if (buffer->cbBuffer < expected_size + record_size)
913 break;
915 expected_size += record_size;
916 ptr += record_size;
919 if (!expected_size)
921 TRACE("Expected at least %lu bytes, but buffer only contains %u bytes.\n",
922 max(6, record_size), buffer->cbBuffer);
923 return SEC_E_INCOMPLETE_MESSAGE;
926 else if (!is_dtls_context(ctx)) return SEC_E_INCOMPLETE_MESSAGE;
928 TRACE("Using expected_size %lu.\n", expected_size);
931 ctx->req_ctx_attr = fContextReq;
933 init_schan_buffers(&ctx->transport.in, pInput, schan_init_sec_ctx_get_next_input_buffer);
934 ctx->transport.in.limit = expected_size;
935 init_schan_buffers(&ctx->transport.out, pOutput, schan_init_sec_ctx_get_next_output_buffer);
937 /* Perform the TLS handshake */
938 ret = schan_imp_handshake(ctx->session);
940 out_buffers = &ctx->transport.out;
941 if (out_buffers->current_buffer_idx != -1)
943 SecBuffer *buffer = &out_buffers->desc->pBuffers[out_buffers->current_buffer_idx];
944 buffer->cbBuffer = out_buffers->offset;
946 else if (out_buffers->desc && out_buffers->desc->cBuffers > 0)
948 SecBuffer *buffer = &out_buffers->desc->pBuffers[0];
949 buffer->cbBuffer = 0;
952 if(ctx->transport.in.offset && ctx->transport.in.offset != pInput->pBuffers[0].cbBuffer) {
953 if(pInput->cBuffers<2 || pInput->pBuffers[1].BufferType!=SECBUFFER_EMPTY)
954 return SEC_E_INVALID_TOKEN;
956 pInput->pBuffers[1].BufferType = SECBUFFER_EXTRA;
957 pInput->pBuffers[1].cbBuffer = pInput->pBuffers[0].cbBuffer-ctx->transport.in.offset;
960 *pfContextAttr = ISC_RET_REPLAY_DETECT | ISC_RET_SEQUENCE_DETECT | ISC_RET_CONFIDENTIALITY | ISC_RET_STREAM;
961 if (ctx->req_ctx_attr & ISC_REQ_EXTENDED_ERROR) *pfContextAttr |= ISC_RET_EXTENDED_ERROR;
962 if (ctx->req_ctx_attr & ISC_REQ_DATAGRAM) *pfContextAttr |= ISC_RET_DATAGRAM;
963 if (ctx->req_ctx_attr & ISC_REQ_ALLOCATE_MEMORY) *pfContextAttr |= ISC_RET_ALLOCATED_MEMORY;
964 if (ctx->req_ctx_attr & ISC_REQ_USE_SUPPLIED_CREDS) *pfContextAttr |= ISC_RET_USED_SUPPLIED_CREDS;
965 if (ctx->req_ctx_attr & ISC_REQ_MANUAL_CRED_VALIDATION) *pfContextAttr |= ISC_RET_MANUAL_CRED_VALIDATION;
967 return ret;
970 /***********************************************************************
971 * InitializeSecurityContextA
973 static SECURITY_STATUS SEC_ENTRY schan_InitializeSecurityContextA(
974 PCredHandle phCredential, PCtxtHandle phContext, SEC_CHAR *pszTargetName,
975 ULONG fContextReq, ULONG Reserved1, ULONG TargetDataRep,
976 PSecBufferDesc pInput, ULONG Reserved2, PCtxtHandle phNewContext,
977 PSecBufferDesc pOutput, ULONG *pfContextAttr, PTimeStamp ptsExpiry)
979 SECURITY_STATUS ret;
980 SEC_WCHAR *target_name = NULL;
982 TRACE("%p %p %s %d %d %d %p %d %p %p %p %p\n", phCredential, phContext,
983 debugstr_a(pszTargetName), fContextReq, Reserved1, TargetDataRep, pInput,
984 Reserved1, phNewContext, pOutput, pfContextAttr, ptsExpiry);
986 if (pszTargetName)
988 INT len = MultiByteToWideChar(CP_ACP, 0, pszTargetName, -1, NULL, 0);
989 if (!(target_name = heap_alloc(len * sizeof(*target_name)))) return SEC_E_INSUFFICIENT_MEMORY;
990 MultiByteToWideChar(CP_ACP, 0, pszTargetName, -1, target_name, len);
993 ret = schan_InitializeSecurityContextW(phCredential, phContext, target_name,
994 fContextReq, Reserved1, TargetDataRep, pInput, Reserved2,
995 phNewContext, pOutput, pfContextAttr, ptsExpiry);
997 heap_free(target_name);
998 return ret;
1001 static void *get_alg_name(ALG_ID id, BOOL wide)
1003 static const struct {
1004 ALG_ID alg_id;
1005 const char* name;
1006 const WCHAR nameW[8];
1007 } alg_name_map[] = {
1008 { CALG_ECDSA, "ECDSA", {'E','C','D','S','A',0} },
1009 { CALG_RSA_SIGN, "RSA", {'R','S','A',0} },
1010 { CALG_DES, "DES", {'D','E','S',0} },
1011 { CALG_RC2, "RC2", {'R','C','2',0} },
1012 { CALG_3DES, "3DES", {'3','D','E','S',0} },
1013 { CALG_AES_128, "AES", {'A','E','S',0} },
1014 { CALG_AES_192, "AES", {'A','E','S',0} },
1015 { CALG_AES_256, "AES", {'A','E','S',0} },
1016 { CALG_RC4, "RC4", {'R','C','4',0} },
1018 unsigned i;
1020 for (i = 0; i < ARRAY_SIZE(alg_name_map); i++)
1021 if (alg_name_map[i].alg_id == id)
1022 return wide ? (void*)alg_name_map[i].nameW : (void*)alg_name_map[i].name;
1024 FIXME("Unknown ALG_ID %04x\n", id);
1025 return NULL;
1028 static SECURITY_STATUS ensure_remote_cert(struct schan_context *ctx)
1030 HCERTSTORE cert_store;
1031 SECURITY_STATUS status;
1033 if(ctx->cert)
1034 return SEC_E_OK;
1036 cert_store = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0, CERT_STORE_CREATE_NEW_FLAG, NULL);
1037 if(!cert_store)
1038 return GetLastError();
1040 status = schan_imp_get_session_peer_certificate(ctx->session, cert_store, &ctx->cert);
1041 CertCloseStore(cert_store, 0);
1042 return status;
1045 static SECURITY_STATUS SEC_ENTRY schan_QueryContextAttributesW(
1046 PCtxtHandle context_handle, ULONG attribute, PVOID buffer)
1048 struct schan_context *ctx;
1049 SECURITY_STATUS status;
1051 TRACE("context_handle %p, attribute %#x, buffer %p\n",
1052 context_handle, attribute, buffer);
1054 if (!context_handle) return SEC_E_INVALID_HANDLE;
1055 ctx = schan_get_object(context_handle->dwLower, SCHAN_HANDLE_CTX);
1057 switch(attribute)
1059 case SECPKG_ATTR_STREAM_SIZES:
1061 SecPkgContext_ConnectionInfo info;
1062 status = schan_imp_get_connection_info(ctx->session, &info);
1063 if (status == SEC_E_OK)
1065 SecPkgContext_StreamSizes *stream_sizes = buffer;
1066 SIZE_T mac_size = info.dwHashStrength;
1067 unsigned int block_size = schan_imp_get_session_cipher_block_size(ctx->session);
1068 unsigned int message_size = schan_imp_get_max_message_size(ctx->session);
1070 TRACE("Using header size %lu mac bytes %lu, message size %u, block size %u\n",
1071 ctx->header_size, mac_size, message_size, block_size);
1073 /* These are defined by the TLS RFC */
1074 stream_sizes->cbHeader = ctx->header_size;
1075 stream_sizes->cbTrailer = mac_size + 256; /* Max 255 bytes padding + 1 for padding size */
1076 stream_sizes->cbMaximumMessage = message_size;
1077 stream_sizes->cbBuffers = 4;
1078 stream_sizes->cbBlockSize = block_size;
1081 return status;
1083 case SECPKG_ATTR_KEY_INFO:
1085 SecPkgContext_ConnectionInfo conn_info;
1086 status = schan_imp_get_connection_info(ctx->session, &conn_info);
1087 if (status == SEC_E_OK)
1089 SecPkgContext_KeyInfoW *info = buffer;
1090 info->KeySize = conn_info.dwCipherStrength;
1091 info->SignatureAlgorithm = schan_imp_get_key_signature_algorithm(ctx->session);
1092 info->EncryptAlgorithm = conn_info.aiCipher;
1093 info->sSignatureAlgorithmName = get_alg_name(info->SignatureAlgorithm, TRUE);
1094 info->sEncryptAlgorithmName = get_alg_name(info->EncryptAlgorithm, TRUE);
1096 return status;
1098 case SECPKG_ATTR_REMOTE_CERT_CONTEXT:
1100 PCCERT_CONTEXT *cert = buffer;
1102 status = ensure_remote_cert(ctx);
1103 if(status != SEC_E_OK)
1104 return status;
1106 *cert = CertDuplicateCertificateContext(ctx->cert);
1107 return SEC_E_OK;
1109 case SECPKG_ATTR_CONNECTION_INFO:
1111 SecPkgContext_ConnectionInfo *info = buffer;
1112 return schan_imp_get_connection_info(ctx->session, info);
1114 case SECPKG_ATTR_ENDPOINT_BINDINGS:
1116 SecPkgContext_Bindings *bindings = buffer;
1117 CCRYPT_OID_INFO *info;
1118 ALG_ID hash_alg = CALG_SHA_256;
1119 BYTE hash[1024];
1120 DWORD hash_size;
1121 char *p;
1122 BOOL r;
1124 static const char prefix[] = "tls-server-end-point:";
1126 status = ensure_remote_cert(ctx);
1127 if(status != SEC_E_OK)
1128 return status;
1130 /* RFC 5929 */
1131 info = CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY, ctx->cert->pCertInfo->SignatureAlgorithm.pszObjId, 0);
1132 if(info && info->u.Algid != CALG_SHA1 && info->u.Algid != CALG_MD5)
1133 hash_alg = info->u.Algid;
1135 hash_size = sizeof(hash);
1136 r = CryptHashCertificate(0, hash_alg, 0, ctx->cert->pbCertEncoded, ctx->cert->cbCertEncoded, hash, &hash_size);
1137 if(!r)
1138 return GetLastError();
1140 bindings->BindingsLength = sizeof(*bindings->Bindings) + sizeof(prefix)-1 + hash_size;
1141 bindings->Bindings = heap_alloc_zero(bindings->BindingsLength);
1142 if(!bindings->Bindings)
1143 return SEC_E_INSUFFICIENT_MEMORY;
1145 bindings->Bindings->cbApplicationDataLength = sizeof(prefix)-1 + hash_size;
1146 bindings->Bindings->dwApplicationDataOffset = sizeof(*bindings->Bindings);
1148 p = (char*)(bindings->Bindings+1);
1149 memcpy(p, prefix, sizeof(prefix)-1);
1150 p += sizeof(prefix)-1;
1151 memcpy(p, hash, hash_size);
1152 return SEC_E_OK;
1154 case SECPKG_ATTR_UNIQUE_BINDINGS:
1156 SecPkgContext_Bindings *bindings = buffer;
1157 return schan_imp_get_unique_channel_binding(ctx->session, bindings);
1159 case SECPKG_ATTR_APPLICATION_PROTOCOL:
1161 SecPkgContext_ApplicationProtocol *protocol = buffer;
1162 return schan_imp_get_application_protocol(ctx->session, protocol);
1165 default:
1166 FIXME("Unhandled attribute %#x\n", attribute);
1167 return SEC_E_UNSUPPORTED_FUNCTION;
1171 static SECURITY_STATUS SEC_ENTRY schan_QueryContextAttributesA(
1172 PCtxtHandle context_handle, ULONG attribute, PVOID buffer)
1174 TRACE("context_handle %p, attribute %#x, buffer %p\n",
1175 context_handle, attribute, buffer);
1177 switch(attribute)
1179 case SECPKG_ATTR_STREAM_SIZES:
1180 return schan_QueryContextAttributesW(context_handle, attribute, buffer);
1181 case SECPKG_ATTR_KEY_INFO:
1183 SECURITY_STATUS status = schan_QueryContextAttributesW(context_handle, attribute, buffer);
1184 if (status == SEC_E_OK)
1186 SecPkgContext_KeyInfoA *info = buffer;
1187 info->sSignatureAlgorithmName = get_alg_name(info->SignatureAlgorithm, FALSE);
1188 info->sEncryptAlgorithmName = get_alg_name(info->EncryptAlgorithm, FALSE);
1190 return status;
1192 case SECPKG_ATTR_REMOTE_CERT_CONTEXT:
1193 return schan_QueryContextAttributesW(context_handle, attribute, buffer);
1194 case SECPKG_ATTR_CONNECTION_INFO:
1195 return schan_QueryContextAttributesW(context_handle, attribute, buffer);
1196 case SECPKG_ATTR_ENDPOINT_BINDINGS:
1197 return schan_QueryContextAttributesW(context_handle, attribute, buffer);
1198 case SECPKG_ATTR_UNIQUE_BINDINGS:
1199 return schan_QueryContextAttributesW(context_handle, attribute, buffer);
1200 case SECPKG_ATTR_APPLICATION_PROTOCOL:
1201 return schan_QueryContextAttributesW(context_handle, attribute, buffer);
1203 default:
1204 FIXME("Unhandled attribute %#x\n", attribute);
1205 return SEC_E_UNSUPPORTED_FUNCTION;
1209 static int schan_encrypt_message_get_next_buffer(const struct schan_transport *t, struct schan_buffers *s)
1211 SecBuffer *b;
1213 if (s->current_buffer_idx == -1)
1214 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_STREAM_HEADER);
1216 b = &s->desc->pBuffers[s->current_buffer_idx];
1218 if (b->BufferType == SECBUFFER_STREAM_HEADER)
1219 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_DATA);
1221 if (b->BufferType == SECBUFFER_DATA)
1222 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_STREAM_TRAILER);
1224 return -1;
1227 static int schan_encrypt_message_get_next_buffer_token(const struct schan_transport *t, struct schan_buffers *s)
1229 SecBuffer *b;
1231 if (s->current_buffer_idx == -1)
1232 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
1234 b = &s->desc->pBuffers[s->current_buffer_idx];
1236 if (b->BufferType == SECBUFFER_TOKEN)
1238 int idx = schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
1239 if (idx != s->current_buffer_idx) return -1;
1240 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_DATA);
1243 if (b->BufferType == SECBUFFER_DATA)
1245 int idx = schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
1246 if (idx != -1)
1247 idx = schan_find_sec_buffer_idx(s->desc, idx + 1, SECBUFFER_TOKEN);
1248 return idx;
1251 return -1;
1254 static SECURITY_STATUS SEC_ENTRY schan_EncryptMessage(PCtxtHandle context_handle,
1255 ULONG quality, PSecBufferDesc message, ULONG message_seq_no)
1257 struct schan_context *ctx;
1258 struct schan_buffers *b;
1259 SECURITY_STATUS status;
1260 SecBuffer *buffer;
1261 SIZE_T data_size;
1262 SIZE_T length;
1263 char *data;
1264 int idx;
1266 TRACE("context_handle %p, quality %d, message %p, message_seq_no %d\n",
1267 context_handle, quality, message, message_seq_no);
1269 if (!context_handle) return SEC_E_INVALID_HANDLE;
1270 ctx = schan_get_object(context_handle->dwLower, SCHAN_HANDLE_CTX);
1272 dump_buffer_desc(message);
1274 idx = schan_find_sec_buffer_idx(message, 0, SECBUFFER_DATA);
1275 if (idx == -1)
1277 WARN("No data buffer passed\n");
1278 return SEC_E_INTERNAL_ERROR;
1280 buffer = &message->pBuffers[idx];
1282 data_size = buffer->cbBuffer;
1283 data = heap_alloc(data_size);
1284 memcpy(data, buffer->pvBuffer, data_size);
1286 if (schan_find_sec_buffer_idx(message, 0, SECBUFFER_STREAM_HEADER) != -1)
1287 init_schan_buffers(&ctx->transport.out, message, schan_encrypt_message_get_next_buffer);
1288 else
1289 init_schan_buffers(&ctx->transport.out, message, schan_encrypt_message_get_next_buffer_token);
1291 length = data_size;
1292 status = schan_imp_send(ctx->session, data, &length);
1294 TRACE("Sent %ld bytes.\n", length);
1296 if (length != data_size)
1297 status = SEC_E_INTERNAL_ERROR;
1299 b = &ctx->transport.out;
1300 b->desc->pBuffers[b->current_buffer_idx].cbBuffer = b->offset;
1301 heap_free(data);
1303 TRACE("Returning %#x.\n", status);
1305 return status;
1308 static int schan_decrypt_message_get_next_buffer(const struct schan_transport *t, struct schan_buffers *s)
1310 if (s->current_buffer_idx == -1)
1311 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_DATA);
1313 return -1;
1316 static int schan_validate_decrypt_buffer_desc(PSecBufferDesc message)
1318 int data_idx = -1;
1319 unsigned int empty_count = 0;
1320 unsigned int i;
1322 if (message->cBuffers < 4)
1324 WARN("Less than four buffers passed\n");
1325 return -1;
1328 for (i = 0; i < message->cBuffers; ++i)
1330 SecBuffer *b = &message->pBuffers[i];
1331 if (b->BufferType == SECBUFFER_DATA)
1333 if (data_idx != -1)
1335 WARN("More than one data buffer passed\n");
1336 return -1;
1338 data_idx = i;
1340 else if (b->BufferType == SECBUFFER_EMPTY)
1341 ++empty_count;
1344 if (data_idx == -1)
1346 WARN("No data buffer passed\n");
1347 return -1;
1350 if (empty_count < 3)
1352 WARN("Less than three empty buffers passed\n");
1353 return -1;
1356 return data_idx;
1359 static void schan_decrypt_fill_buffer(PSecBufferDesc message, ULONG buffer_type, void *data, ULONG size)
1361 int idx;
1362 SecBuffer *buffer;
1364 idx = schan_find_sec_buffer_idx(message, 0, SECBUFFER_EMPTY);
1365 buffer = &message->pBuffers[idx];
1367 buffer->BufferType = buffer_type;
1368 buffer->pvBuffer = data;
1369 buffer->cbBuffer = size;
1372 static SECURITY_STATUS SEC_ENTRY schan_DecryptMessage(PCtxtHandle context_handle,
1373 PSecBufferDesc message, ULONG message_seq_no, PULONG quality)
1375 SECURITY_STATUS status = SEC_E_OK;
1376 struct schan_context *ctx;
1377 SecBuffer *buffer;
1378 SIZE_T data_size;
1379 char *data;
1380 unsigned expected_size;
1381 SSIZE_T received = 0;
1382 int idx;
1383 unsigned char *buf_ptr;
1385 TRACE("context_handle %p, message %p, message_seq_no %d, quality %p\n",
1386 context_handle, message, message_seq_no, quality);
1388 if (!context_handle) return SEC_E_INVALID_HANDLE;
1389 ctx = schan_get_object(context_handle->dwLower, SCHAN_HANDLE_CTX);
1391 dump_buffer_desc(message);
1393 idx = schan_validate_decrypt_buffer_desc(message);
1394 if (idx == -1)
1395 return SEC_E_INVALID_TOKEN;
1396 buffer = &message->pBuffers[idx];
1397 buf_ptr = buffer->pvBuffer;
1399 expected_size = ctx->header_size + read_record_size(buf_ptr, ctx->header_size);
1400 if(buffer->cbBuffer < expected_size)
1402 TRACE("Expected %u bytes, but buffer only contains %u bytes\n", expected_size, buffer->cbBuffer);
1403 buffer->BufferType = SECBUFFER_MISSING;
1404 buffer->cbBuffer = expected_size - buffer->cbBuffer;
1406 /* This is a bit weird, but windows does it too */
1407 idx = schan_find_sec_buffer_idx(message, 0, SECBUFFER_EMPTY);
1408 buffer = &message->pBuffers[idx];
1409 buffer->BufferType = SECBUFFER_MISSING;
1410 buffer->cbBuffer = expected_size - buffer->cbBuffer;
1412 TRACE("Returning SEC_E_INCOMPLETE_MESSAGE\n");
1413 return SEC_E_INCOMPLETE_MESSAGE;
1416 data_size = expected_size - ctx->header_size;
1417 data = heap_alloc(data_size);
1419 init_schan_buffers(&ctx->transport.in, message, schan_decrypt_message_get_next_buffer);
1420 ctx->transport.in.limit = expected_size;
1422 while (received < data_size)
1424 SIZE_T length = data_size - received;
1425 status = schan_imp_recv(ctx->session, data + received, &length);
1427 if (status == SEC_I_RENEGOTIATE)
1428 break;
1430 if (status == SEC_I_CONTINUE_NEEDED)
1432 status = SEC_E_OK;
1433 break;
1436 if (status != SEC_E_OK)
1438 heap_free(data);
1439 ERR("Returning %x\n", status);
1440 return status;
1443 if (!length)
1444 break;
1446 received += length;
1449 TRACE("Received %ld bytes\n", received);
1451 memcpy(buf_ptr + ctx->header_size, data, received);
1452 heap_free(data);
1454 schan_decrypt_fill_buffer(message, SECBUFFER_DATA,
1455 buf_ptr + ctx->header_size, received);
1457 schan_decrypt_fill_buffer(message, SECBUFFER_STREAM_TRAILER,
1458 buf_ptr + ctx->header_size + received, buffer->cbBuffer - ctx->header_size - received);
1460 if(buffer->cbBuffer > expected_size)
1461 schan_decrypt_fill_buffer(message, SECBUFFER_EXTRA,
1462 buf_ptr + expected_size, buffer->cbBuffer - expected_size);
1464 buffer->BufferType = SECBUFFER_STREAM_HEADER;
1465 buffer->cbBuffer = ctx->header_size;
1467 return status;
1470 static SECURITY_STATUS SEC_ENTRY schan_DeleteSecurityContext(PCtxtHandle context_handle)
1472 struct schan_context *ctx;
1474 TRACE("context_handle %p\n", context_handle);
1476 if (!context_handle) return SEC_E_INVALID_HANDLE;
1478 ctx = schan_free_handle(context_handle->dwLower, SCHAN_HANDLE_CTX);
1479 if (!ctx) return SEC_E_INVALID_HANDLE;
1481 if (ctx->cert)
1482 CertFreeCertificateContext(ctx->cert);
1483 schan_imp_dispose_session(ctx->session);
1484 heap_free(ctx);
1486 return SEC_E_OK;
1489 static const SecurityFunctionTableA schanTableA = {
1491 NULL, /* EnumerateSecurityPackagesA */
1492 schan_QueryCredentialsAttributesA,
1493 schan_AcquireCredentialsHandleA,
1494 schan_FreeCredentialsHandle,
1495 NULL, /* Reserved2 */
1496 schan_InitializeSecurityContextA,
1497 NULL, /* AcceptSecurityContext */
1498 NULL, /* CompleteAuthToken */
1499 schan_DeleteSecurityContext,
1500 NULL, /* ApplyControlToken */
1501 schan_QueryContextAttributesA,
1502 NULL, /* ImpersonateSecurityContext */
1503 NULL, /* RevertSecurityContext */
1504 NULL, /* MakeSignature */
1505 NULL, /* VerifySignature */
1506 FreeContextBuffer,
1507 NULL, /* QuerySecurityPackageInfoA */
1508 NULL, /* Reserved3 */
1509 NULL, /* Reserved4 */
1510 NULL, /* ExportSecurityContext */
1511 NULL, /* ImportSecurityContextA */
1512 NULL, /* AddCredentialsA */
1513 NULL, /* Reserved8 */
1514 NULL, /* QuerySecurityContextToken */
1515 schan_EncryptMessage,
1516 schan_DecryptMessage,
1517 NULL, /* SetContextAttributesA */
1520 static const SecurityFunctionTableW schanTableW = {
1522 NULL, /* EnumerateSecurityPackagesW */
1523 schan_QueryCredentialsAttributesW,
1524 schan_AcquireCredentialsHandleW,
1525 schan_FreeCredentialsHandle,
1526 NULL, /* Reserved2 */
1527 schan_InitializeSecurityContextW,
1528 NULL, /* AcceptSecurityContext */
1529 NULL, /* CompleteAuthToken */
1530 schan_DeleteSecurityContext,
1531 NULL, /* ApplyControlToken */
1532 schan_QueryContextAttributesW,
1533 NULL, /* ImpersonateSecurityContext */
1534 NULL, /* RevertSecurityContext */
1535 NULL, /* MakeSignature */
1536 NULL, /* VerifySignature */
1537 FreeContextBuffer,
1538 NULL, /* QuerySecurityPackageInfoW */
1539 NULL, /* Reserved3 */
1540 NULL, /* Reserved4 */
1541 NULL, /* ExportSecurityContext */
1542 NULL, /* ImportSecurityContextW */
1543 NULL, /* AddCredentialsW */
1544 NULL, /* Reserved8 */
1545 NULL, /* QuerySecurityContextToken */
1546 schan_EncryptMessage,
1547 schan_DecryptMessage,
1548 NULL, /* SetContextAttributesW */
1551 static const WCHAR schannelComment[] = { 'S','c','h','a','n','n','e','l',' ',
1552 'S','e','c','u','r','i','t','y',' ','P','a','c','k','a','g','e',0 };
1553 static const WCHAR schannelDllName[] = { 's','c','h','a','n','n','e','l','.','d','l','l',0 };
1555 void SECUR32_initSchannelSP(void)
1557 /* This is what Windows reports. This shouldn't break any applications
1558 * even though the functions are missing, because the wrapper will
1559 * return SEC_E_UNSUPPORTED_FUNCTION if our function is NULL.
1561 static const LONG caps =
1562 SECPKG_FLAG_INTEGRITY |
1563 SECPKG_FLAG_PRIVACY |
1564 SECPKG_FLAG_CONNECTION |
1565 SECPKG_FLAG_MULTI_REQUIRED |
1566 SECPKG_FLAG_EXTENDED_ERROR |
1567 SECPKG_FLAG_IMPERSONATION |
1568 SECPKG_FLAG_ACCEPT_WIN32_NAME |
1569 SECPKG_FLAG_STREAM;
1570 static const short version = 1;
1571 static const LONG maxToken = 16384;
1572 SEC_WCHAR *uniSPName = (SEC_WCHAR *)UNISP_NAME_W,
1573 *schannel = (SEC_WCHAR *)SCHANNEL_NAME_W;
1574 const SecPkgInfoW info[] = {
1575 { caps, version, UNISP_RPC_ID, maxToken, uniSPName, uniSPName },
1576 { caps, version, UNISP_RPC_ID, maxToken, schannel,
1577 (SEC_WCHAR *)schannelComment },
1579 SecureProvider *provider;
1581 if (!schan_imp_init())
1582 return;
1584 schan_handle_table = heap_alloc(64 * sizeof(*schan_handle_table));
1585 if (!schan_handle_table)
1587 ERR("Failed to allocate schannel handle table.\n");
1588 goto fail;
1590 schan_handle_table_size = 64;
1592 provider = SECUR32_addProvider(&schanTableA, &schanTableW, schannelDllName);
1593 if (!provider)
1595 ERR("Failed to add schannel provider.\n");
1596 goto fail;
1599 SECUR32_addPackages(provider, ARRAY_SIZE(info), NULL, info);
1601 return;
1603 fail:
1604 heap_free(schan_handle_table);
1605 schan_handle_table = NULL;
1606 schan_imp_deinit();
1607 return;
1610 void SECUR32_deinitSchannelSP(void)
1612 SIZE_T i = schan_handle_count;
1614 if (!schan_handle_table) return;
1616 /* deinitialized sessions first because a pointer to the credentials
1617 * may be stored for the session. */
1618 while (i--)
1620 if (schan_handle_table[i].type == SCHAN_HANDLE_CTX)
1622 struct schan_context *ctx = schan_free_handle(i, SCHAN_HANDLE_CTX);
1623 schan_imp_dispose_session(ctx->session);
1624 heap_free(ctx);
1627 i = schan_handle_count;
1628 while (i--)
1630 if (schan_handle_table[i].type != SCHAN_HANDLE_FREE)
1632 struct schan_credentials *cred;
1633 cred = schan_free_handle(i, SCHAN_HANDLE_CRED);
1634 schan_imp_free_certificate_credentials(cred);
1635 heap_free(cred);
1638 heap_free(schan_handle_table);
1639 schan_imp_deinit();
1642 #else /* SONAME_LIBGNUTLS || HAVE_SECURITY_SECURITY_H */
1644 void SECUR32_initSchannelSP(void)
1646 ERR("TLS library not found, SSL connections will fail\n");
1649 void SECUR32_deinitSchannelSP(void) {}
1651 #endif /* SONAME_LIBGNUTLS || HAVE_SECURITY_SECURITY_H */