dbghelp: Use local declarations of r_debug and link_map structs.
[wine.git] / dlls / secur32 / schannel.c
blob8063fd4d6b9eaa3fbef87fc2b6bb5f61cc2398fe
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;
65 static struct schan_handle *schan_handle_table;
66 static struct schan_handle *schan_free_handles;
67 static SIZE_T schan_handle_table_size;
68 static SIZE_T schan_handle_count;
70 /* Protocols enabled, only those may be used for the connection. */
71 static DWORD config_enabled_protocols;
73 /* Protocols disabled by default. They are enabled for using, but disabled when caller asks for default settings. */
74 static DWORD config_default_disabled_protocols;
76 static ULONG_PTR schan_alloc_handle(void *object, enum schan_handle_type type)
78 struct schan_handle *handle;
80 if (schan_free_handles)
82 DWORD index = schan_free_handles - schan_handle_table;
83 /* Use a free handle */
84 handle = schan_free_handles;
85 if (handle->type != SCHAN_HANDLE_FREE)
87 ERR("Handle %d(%p) is in the free list, but has type %#x.\n", index, handle, handle->type);
88 return SCHAN_INVALID_HANDLE;
90 schan_free_handles = handle->object;
91 handle->object = object;
92 handle->type = type;
94 return index;
96 if (!(schan_handle_count < schan_handle_table_size))
98 /* Grow the table */
99 SIZE_T new_size = schan_handle_table_size + (schan_handle_table_size >> 1);
100 struct schan_handle *new_table = heap_realloc(schan_handle_table, new_size * sizeof(*schan_handle_table));
101 if (!new_table)
103 ERR("Failed to grow the handle table\n");
104 return SCHAN_INVALID_HANDLE;
106 schan_handle_table = new_table;
107 schan_handle_table_size = new_size;
110 handle = &schan_handle_table[schan_handle_count++];
111 handle->object = object;
112 handle->type = type;
114 return handle - schan_handle_table;
117 static void *schan_free_handle(ULONG_PTR handle_idx, enum schan_handle_type type)
119 struct schan_handle *handle;
120 void *object;
122 if (handle_idx == SCHAN_INVALID_HANDLE) return NULL;
123 if (handle_idx >= schan_handle_count) return NULL;
124 handle = &schan_handle_table[handle_idx];
125 if (handle->type != type)
127 ERR("Handle %ld(%p) is not of type %#x\n", handle_idx, handle, type);
128 return NULL;
131 object = handle->object;
132 handle->object = schan_free_handles;
133 handle->type = SCHAN_HANDLE_FREE;
134 schan_free_handles = handle;
136 return object;
139 static void *schan_get_object(ULONG_PTR handle_idx, enum schan_handle_type type)
141 struct schan_handle *handle;
143 if (handle_idx == SCHAN_INVALID_HANDLE) return NULL;
144 if (handle_idx >= schan_handle_count) return NULL;
145 handle = &schan_handle_table[handle_idx];
146 if (handle->type != type)
148 ERR("Handle %ld(%p) is not of type %#x\n", handle_idx, handle, type);
149 return NULL;
152 return handle->object;
155 static void read_config(void)
157 DWORD enabled = 0, default_disabled = 0;
158 HKEY protocols_key, key;
159 WCHAR subkey_name[64];
160 unsigned i;
161 DWORD res;
163 static BOOL config_read = FALSE;
165 static const WCHAR protocol_config_key_name[] = {
166 'S','Y','S','T','E','M','\\',
167 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
168 'C','o','n','t','r','o','l','\\',
169 'S','e','c','u','r','i','t','y','P','r','o','v','i','d','e','r','s','\\',
170 'S','C','H','A','N','N','E','L','\\',
171 'P','r','o','t','o','c','o','l','s',0 };
173 static const WCHAR clientW[] = {'\\','C','l','i','e','n','t',0};
174 static const WCHAR enabledW[] = {'e','n','a','b','l','e','d',0};
175 static const WCHAR disabledbydefaultW[] = {'D','i','s','a','b','l','e','d','B','y','D','e','f','a','u','l','t',0};
177 static const struct {
178 WCHAR key_name[20];
179 DWORD prot_client_flag;
180 BOOL enabled; /* If no config is present, enable the protocol */
181 BOOL disabled_by_default; /* Disable if caller asks for default protocol set */
182 } protocol_config_keys[] = {
183 {{'S','S','L',' ','2','.','0',0}, SP_PROT_SSL2_CLIENT, FALSE, TRUE}, /* NOTE: TRUE, TRUE on Windows */
184 {{'S','S','L',' ','3','.','0',0}, SP_PROT_SSL3_CLIENT, TRUE, FALSE},
185 {{'T','L','S',' ','1','.','0',0}, SP_PROT_TLS1_0_CLIENT, TRUE, FALSE},
186 {{'T','L','S',' ','1','.','1',0}, SP_PROT_TLS1_1_CLIENT, TRUE, FALSE /* NOTE: not enabled by default on Windows */ },
187 {{'T','L','S',' ','1','.','2',0}, SP_PROT_TLS1_2_CLIENT, TRUE, FALSE /* NOTE: not enabled by default on Windows */ }
190 /* No need for thread safety */
191 if(config_read)
192 return;
194 res = RegOpenKeyExW(HKEY_LOCAL_MACHINE, protocol_config_key_name, 0, KEY_READ, &protocols_key);
195 if(res == ERROR_SUCCESS) {
196 DWORD type, size, value;
198 for(i = 0; i < ARRAY_SIZE(protocol_config_keys); i++) {
199 strcpyW(subkey_name, protocol_config_keys[i].key_name);
200 strcatW(subkey_name, clientW);
201 res = RegOpenKeyExW(protocols_key, subkey_name, 0, KEY_READ, &key);
202 if(res != ERROR_SUCCESS) {
203 if(protocol_config_keys[i].enabled)
204 enabled |= protocol_config_keys[i].prot_client_flag;
205 if(protocol_config_keys[i].disabled_by_default)
206 default_disabled |= protocol_config_keys[i].prot_client_flag;
207 continue;
210 size = sizeof(value);
211 res = RegQueryValueExW(key, enabledW, NULL, &type, (BYTE*)&value, &size);
212 if(res == ERROR_SUCCESS) {
213 if(type == REG_DWORD && value)
214 enabled |= protocol_config_keys[i].prot_client_flag;
215 }else if(protocol_config_keys[i].enabled) {
216 enabled |= protocol_config_keys[i].prot_client_flag;
219 size = sizeof(value);
220 res = RegQueryValueExW(key, disabledbydefaultW, NULL, &type, (BYTE*)&value, &size);
221 if(res == ERROR_SUCCESS) {
222 if(type != REG_DWORD || value)
223 default_disabled |= protocol_config_keys[i].prot_client_flag;
224 }else if(protocol_config_keys[i].disabled_by_default) {
225 default_disabled |= protocol_config_keys[i].prot_client_flag;
228 RegCloseKey(key);
230 }else {
231 /* No config, enable all known protocols. */
232 for(i = 0; i < ARRAY_SIZE(protocol_config_keys); i++) {
233 if(protocol_config_keys[i].enabled)
234 enabled |= protocol_config_keys[i].prot_client_flag;
235 if(protocol_config_keys[i].disabled_by_default)
236 default_disabled |= protocol_config_keys[i].prot_client_flag;
240 RegCloseKey(protocols_key);
242 config_enabled_protocols = enabled & schan_imp_enabled_protocols();
243 config_default_disabled_protocols = default_disabled;
244 config_read = TRUE;
246 TRACE("enabled %x, disabled by default %x\n", config_enabled_protocols, config_default_disabled_protocols);
249 static SECURITY_STATUS schan_QueryCredentialsAttributes(
250 PCredHandle phCredential, ULONG ulAttribute, VOID *pBuffer)
252 struct schan_credentials *cred;
253 SECURITY_STATUS ret;
255 cred = schan_get_object(phCredential->dwLower, SCHAN_HANDLE_CRED);
256 if(!cred)
257 return SEC_E_INVALID_HANDLE;
259 switch (ulAttribute)
261 case SECPKG_ATTR_SUPPORTED_ALGS:
262 if (pBuffer)
264 /* FIXME: get from CryptoAPI */
265 FIXME("SECPKG_ATTR_SUPPORTED_ALGS: stub\n");
266 ret = SEC_E_UNSUPPORTED_FUNCTION;
268 else
269 ret = SEC_E_INTERNAL_ERROR;
270 break;
271 case SECPKG_ATTR_CIPHER_STRENGTHS:
272 if (pBuffer)
274 SecPkgCred_CipherStrengths *r = pBuffer;
276 /* FIXME: get from CryptoAPI */
277 FIXME("SECPKG_ATTR_CIPHER_STRENGTHS: semi-stub\n");
278 r->dwMinimumCipherStrength = 40;
279 r->dwMaximumCipherStrength = 168;
280 ret = SEC_E_OK;
282 else
283 ret = SEC_E_INTERNAL_ERROR;
284 break;
285 case SECPKG_ATTR_SUPPORTED_PROTOCOLS:
286 if(pBuffer) {
287 /* Regardless of MSDN documentation, tests show that this attribute takes into account
288 * what protocols are enabled for given credential. */
289 ((SecPkgCred_SupportedProtocols*)pBuffer)->grbitProtocol = cred->enabled_protocols;
290 ret = SEC_E_OK;
291 }else {
292 ret = SEC_E_INTERNAL_ERROR;
294 break;
295 default:
296 ret = SEC_E_UNSUPPORTED_FUNCTION;
298 return ret;
301 static SECURITY_STATUS SEC_ENTRY schan_QueryCredentialsAttributesA(
302 PCredHandle phCredential, ULONG ulAttribute, PVOID pBuffer)
304 SECURITY_STATUS ret;
306 TRACE("(%p, %d, %p)\n", phCredential, ulAttribute, pBuffer);
308 switch (ulAttribute)
310 case SECPKG_CRED_ATTR_NAMES:
311 FIXME("SECPKG_CRED_ATTR_NAMES: stub\n");
312 ret = SEC_E_UNSUPPORTED_FUNCTION;
313 break;
314 default:
315 ret = schan_QueryCredentialsAttributes(phCredential, ulAttribute,
316 pBuffer);
318 return ret;
321 static SECURITY_STATUS SEC_ENTRY schan_QueryCredentialsAttributesW(
322 PCredHandle phCredential, ULONG ulAttribute, PVOID pBuffer)
324 SECURITY_STATUS ret;
326 TRACE("(%p, %d, %p)\n", phCredential, ulAttribute, pBuffer);
328 switch (ulAttribute)
330 case SECPKG_CRED_ATTR_NAMES:
331 FIXME("SECPKG_CRED_ATTR_NAMES: stub\n");
332 ret = SEC_E_UNSUPPORTED_FUNCTION;
333 break;
334 default:
335 ret = schan_QueryCredentialsAttributes(phCredential, ulAttribute,
336 pBuffer);
338 return ret;
341 static SECURITY_STATUS get_cert(const SCHANNEL_CRED *cred, CERT_CONTEXT const **cert)
343 SECURITY_STATUS status;
344 DWORD i;
346 TRACE("dwVersion = %u\n", cred->dwVersion);
347 TRACE("cCreds = %u\n", cred->cCreds);
348 TRACE("paCred = %p\n", cred->paCred);
349 TRACE("hRootStore = %p\n", cred->hRootStore);
350 TRACE("cMappers = %u\n", cred->cMappers);
351 TRACE("cSupportedAlgs = %u:\n", cred->cSupportedAlgs);
352 for (i = 0; i < cred->cSupportedAlgs; i++) TRACE("%08x\n", cred->palgSupportedAlgs[i]);
353 TRACE("grbitEnabledProtocols = %08x\n", cred->grbitEnabledProtocols);
354 TRACE("dwMinimumCipherStrength = %u\n", cred->dwMinimumCipherStrength);
355 TRACE("dwMaximumCipherStrength = %u\n", cred->dwMaximumCipherStrength);
356 TRACE("dwSessionLifespan = %u\n", cred->dwSessionLifespan);
357 TRACE("dwFlags = %08x\n", cred->dwFlags);
358 TRACE("dwCredFormat = %u\n", cred->dwCredFormat);
360 switch (cred->dwVersion)
362 case SCH_CRED_V3:
363 case SCHANNEL_CRED_VERSION:
364 break;
365 default:
366 return SEC_E_INTERNAL_ERROR;
369 if (!cred->cCreds) status = SEC_E_NO_CREDENTIALS;
370 else if (cred->cCreds > 1) status = SEC_E_UNKNOWN_CREDENTIALS;
371 else
373 DWORD spec;
374 HCRYPTPROV prov;
375 BOOL free;
377 if (CryptAcquireCertificatePrivateKey(cred->paCred[0], CRYPT_ACQUIRE_CACHE_FLAG, NULL, &prov, &spec, &free))
379 if (free) CryptReleaseContext(prov, 0);
380 *cert = cred->paCred[0];
381 status = SEC_E_OK;
383 else status = SEC_E_UNKNOWN_CREDENTIALS;
386 return status;
389 static SECURITY_STATUS schan_AcquireClientCredentials(const SCHANNEL_CRED *schanCred,
390 PCredHandle phCredential, PTimeStamp ptsExpiry)
392 struct schan_credentials *creds;
393 unsigned enabled_protocols;
394 ULONG_PTR handle;
395 SECURITY_STATUS status = SEC_E_OK;
396 const CERT_CONTEXT *cert = NULL;
398 TRACE("schanCred %p, phCredential %p, ptsExpiry %p\n", schanCred, phCredential, ptsExpiry);
400 if (schanCred)
402 status = get_cert(schanCred, &cert);
403 if (status != SEC_E_OK && status != SEC_E_NO_CREDENTIALS)
404 return status;
406 status = SEC_E_OK;
409 read_config();
410 if(schanCred && schanCred->grbitEnabledProtocols)
411 enabled_protocols = schanCred->grbitEnabledProtocols & config_enabled_protocols;
412 else
413 enabled_protocols = config_enabled_protocols & ~config_default_disabled_protocols;
414 if(!enabled_protocols) {
415 ERR("Could not find matching protocol\n");
416 return SEC_E_NO_AUTHENTICATING_AUTHORITY;
419 creds = heap_alloc(sizeof(*creds));
420 if (!creds) return SEC_E_INSUFFICIENT_MEMORY;
422 handle = schan_alloc_handle(creds, SCHAN_HANDLE_CRED);
423 if (handle == SCHAN_INVALID_HANDLE) goto fail;
425 creds->credential_use = SECPKG_CRED_OUTBOUND;
426 if (!schan_imp_allocate_certificate_credentials(creds, cert))
428 schan_free_handle(handle, SCHAN_HANDLE_CRED);
429 goto fail;
432 creds->enabled_protocols = enabled_protocols;
433 phCredential->dwLower = handle;
434 phCredential->dwUpper = 0;
436 /* Outbound credentials have no expiry */
437 if (ptsExpiry)
439 ptsExpiry->LowPart = 0;
440 ptsExpiry->HighPart = 0;
443 return status;
445 fail:
446 heap_free(creds);
447 return SEC_E_INTERNAL_ERROR;
450 static SECURITY_STATUS schan_AcquireServerCredentials(const SCHANNEL_CRED *schanCred,
451 PCredHandle phCredential, PTimeStamp ptsExpiry)
453 SECURITY_STATUS status;
454 const CERT_CONTEXT *cert = NULL;
456 TRACE("schanCred %p, phCredential %p, ptsExpiry %p\n", schanCred, phCredential, ptsExpiry);
458 if (!schanCred) return SEC_E_NO_CREDENTIALS;
460 status = get_cert(schanCred, &cert);
461 if (status == SEC_E_OK)
463 ULONG_PTR handle;
464 struct schan_credentials *creds;
466 creds = heap_alloc_zero(sizeof(*creds));
467 if (!creds) return SEC_E_INSUFFICIENT_MEMORY;
468 creds->credential_use = SECPKG_CRED_INBOUND;
470 handle = schan_alloc_handle(creds, SCHAN_HANDLE_CRED);
471 if (handle == SCHAN_INVALID_HANDLE)
473 heap_free(creds);
474 return SEC_E_INTERNAL_ERROR;
477 phCredential->dwLower = handle;
478 phCredential->dwUpper = 0;
480 /* FIXME: get expiry from cert */
482 return status;
485 static SECURITY_STATUS schan_AcquireCredentialsHandle(ULONG fCredentialUse,
486 const SCHANNEL_CRED *schanCred, PCredHandle phCredential, PTimeStamp ptsExpiry)
488 SECURITY_STATUS ret;
490 if (fCredentialUse == SECPKG_CRED_OUTBOUND)
491 ret = schan_AcquireClientCredentials(schanCred, phCredential,
492 ptsExpiry);
493 else
494 ret = schan_AcquireServerCredentials(schanCred, phCredential,
495 ptsExpiry);
496 return ret;
499 static SECURITY_STATUS SEC_ENTRY schan_AcquireCredentialsHandleA(
500 SEC_CHAR *pszPrincipal, SEC_CHAR *pszPackage, ULONG fCredentialUse,
501 PLUID pLogonID, PVOID pAuthData, SEC_GET_KEY_FN pGetKeyFn,
502 PVOID pGetKeyArgument, PCredHandle phCredential, PTimeStamp ptsExpiry)
504 TRACE("(%s, %s, 0x%08x, %p, %p, %p, %p, %p, %p)\n",
505 debugstr_a(pszPrincipal), debugstr_a(pszPackage), fCredentialUse,
506 pLogonID, pAuthData, pGetKeyFn, pGetKeyArgument, phCredential, ptsExpiry);
507 return schan_AcquireCredentialsHandle(fCredentialUse,
508 pAuthData, phCredential, ptsExpiry);
511 static SECURITY_STATUS SEC_ENTRY schan_AcquireCredentialsHandleW(
512 SEC_WCHAR *pszPrincipal, SEC_WCHAR *pszPackage, ULONG fCredentialUse,
513 PLUID pLogonID, PVOID pAuthData, SEC_GET_KEY_FN pGetKeyFn,
514 PVOID pGetKeyArgument, PCredHandle phCredential, PTimeStamp ptsExpiry)
516 TRACE("(%s, %s, 0x%08x, %p, %p, %p, %p, %p, %p)\n",
517 debugstr_w(pszPrincipal), debugstr_w(pszPackage), fCredentialUse,
518 pLogonID, pAuthData, pGetKeyFn, pGetKeyArgument, phCredential, ptsExpiry);
519 return schan_AcquireCredentialsHandle(fCredentialUse,
520 pAuthData, phCredential, ptsExpiry);
523 static SECURITY_STATUS SEC_ENTRY schan_FreeCredentialsHandle(
524 PCredHandle phCredential)
526 struct schan_credentials *creds;
528 TRACE("phCredential %p\n", phCredential);
530 if (!phCredential) return SEC_E_INVALID_HANDLE;
532 creds = schan_free_handle(phCredential->dwLower, SCHAN_HANDLE_CRED);
533 if (!creds) return SEC_E_INVALID_HANDLE;
535 if (creds->credential_use == SECPKG_CRED_OUTBOUND)
536 schan_imp_free_certificate_credentials(creds);
537 heap_free(creds);
539 return SEC_E_OK;
542 static void init_schan_buffers(struct schan_buffers *s, const PSecBufferDesc desc,
543 int (*get_next_buffer)(const struct schan_transport *, struct schan_buffers *))
545 s->offset = 0;
546 s->limit = ~0UL;
547 s->desc = desc;
548 s->current_buffer_idx = -1;
549 s->allow_buffer_resize = FALSE;
550 s->get_next_buffer = get_next_buffer;
553 static int schan_find_sec_buffer_idx(const SecBufferDesc *desc, unsigned int start_idx, ULONG buffer_type)
555 unsigned int i;
556 PSecBuffer buffer;
558 for (i = start_idx; i < desc->cBuffers; ++i)
560 buffer = &desc->pBuffers[i];
561 if (buffer->BufferType == buffer_type) return i;
564 return -1;
567 static void schan_resize_current_buffer(const struct schan_buffers *s, SIZE_T min_size)
569 SecBuffer *b = &s->desc->pBuffers[s->current_buffer_idx];
570 SIZE_T new_size = b->cbBuffer ? b->cbBuffer * 2 : 128;
571 void *new_data;
573 if (b->cbBuffer >= min_size || !s->allow_buffer_resize || min_size > UINT_MAX / 2) return;
575 while (new_size < min_size) new_size *= 2;
577 if (b->pvBuffer)
578 new_data = heap_realloc(b->pvBuffer, new_size);
579 else
580 new_data = heap_alloc(new_size);
582 if (!new_data)
584 TRACE("Failed to resize %p from %d to %ld\n", b->pvBuffer, b->cbBuffer, new_size);
585 return;
588 b->cbBuffer = new_size;
589 b->pvBuffer = new_data;
592 char *schan_get_buffer(const struct schan_transport *t, struct schan_buffers *s, SIZE_T *count)
594 SIZE_T max_count;
595 PSecBuffer buffer;
597 if (!s->desc)
599 TRACE("No desc\n");
600 return NULL;
603 if (s->current_buffer_idx == -1)
605 /* Initial buffer */
606 int buffer_idx = s->get_next_buffer(t, s);
607 if (buffer_idx == -1)
609 TRACE("No next buffer\n");
610 return NULL;
612 s->current_buffer_idx = buffer_idx;
615 buffer = &s->desc->pBuffers[s->current_buffer_idx];
616 TRACE("Using buffer %d: cbBuffer %d, BufferType %#x, pvBuffer %p\n", s->current_buffer_idx, buffer->cbBuffer, buffer->BufferType, buffer->pvBuffer);
618 schan_resize_current_buffer(s, s->offset + *count);
619 max_count = buffer->cbBuffer - s->offset;
620 if (s->limit != ~0UL && s->limit < max_count)
621 max_count = s->limit;
622 if (!max_count)
624 int buffer_idx;
626 s->allow_buffer_resize = FALSE;
627 buffer_idx = s->get_next_buffer(t, s);
628 if (buffer_idx == -1)
630 TRACE("No next buffer\n");
631 return NULL;
633 s->current_buffer_idx = buffer_idx;
634 s->offset = 0;
635 return schan_get_buffer(t, s, count);
638 if (*count > max_count)
639 *count = max_count;
640 if (s->limit != ~0UL)
641 s->limit -= *count;
643 return (char *)buffer->pvBuffer + s->offset;
646 /* schan_pull
647 * Read data from the transport input buffer.
649 * t - The session transport object.
650 * buff - The buffer into which to store the read data. Must be at least
651 * *buff_len bytes in length.
652 * buff_len - On input, *buff_len is the desired length to read. On successful
653 * return, *buff_len is the number of bytes actually read.
655 * Returns:
656 * 0 on success, in which case:
657 * *buff_len == 0 indicates end of file.
658 * *buff_len > 0 indicates that some data was read. May be less than
659 * what was requested, in which case the caller should call again if/
660 * when they want more.
661 * EAGAIN when no data could be read without blocking
662 * another errno-style error value on failure
665 int schan_pull(struct schan_transport *t, void *buff, size_t *buff_len)
667 char *b;
668 SIZE_T local_len = *buff_len;
670 TRACE("Pull %lu bytes\n", local_len);
672 *buff_len = 0;
674 b = schan_get_buffer(t, &t->in, &local_len);
675 if (!b)
676 return EAGAIN;
678 memcpy(buff, b, local_len);
679 t->in.offset += local_len;
681 TRACE("Read %lu bytes\n", local_len);
683 *buff_len = local_len;
684 return 0;
687 /* schan_push
688 * Write data to the transport output buffer.
690 * t - The session transport object.
691 * buff - The buffer of data to write. Must be at least *buff_len bytes in length.
692 * buff_len - On input, *buff_len is the desired length to write. On successful
693 * return, *buff_len is the number of bytes actually written.
695 * Returns:
696 * 0 on success
697 * *buff_len will be > 0 indicating how much data was written. May be less
698 * than what was requested, in which case the caller should call again
699 if/when they want to write more.
700 * EAGAIN when no data could be written without blocking
701 * another errno-style error value on failure
704 int schan_push(struct schan_transport *t, const void *buff, size_t *buff_len)
706 char *b;
707 SIZE_T local_len = *buff_len;
709 TRACE("Push %lu bytes\n", local_len);
711 *buff_len = 0;
713 b = schan_get_buffer(t, &t->out, &local_len);
714 if (!b)
715 return EAGAIN;
717 memcpy(b, buff, local_len);
718 t->out.offset += local_len;
720 TRACE("Wrote %lu bytes\n", local_len);
722 *buff_len = local_len;
723 return 0;
726 schan_imp_session schan_session_for_transport(struct schan_transport* t)
728 return t->ctx->session;
731 static int schan_init_sec_ctx_get_next_input_buffer(const struct schan_transport *t, struct schan_buffers *s)
733 if (s->current_buffer_idx != -1)
734 return -1;
735 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
738 static int schan_init_sec_ctx_get_next_output_buffer(const struct schan_transport *t, struct schan_buffers *s)
740 if (s->current_buffer_idx == -1)
742 int idx = schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
743 if (t->ctx->req_ctx_attr & ISC_REQ_ALLOCATE_MEMORY)
745 if (idx == -1)
747 idx = schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_EMPTY);
748 if (idx != -1) s->desc->pBuffers[idx].BufferType = SECBUFFER_TOKEN;
750 if (idx != -1 && !s->desc->pBuffers[idx].pvBuffer)
752 s->desc->pBuffers[idx].cbBuffer = 0;
753 s->allow_buffer_resize = TRUE;
756 return idx;
759 return -1;
762 static void dump_buffer_desc(SecBufferDesc *desc)
764 unsigned int i;
766 if (!desc) return;
767 TRACE("Buffer desc %p:\n", desc);
768 for (i = 0; i < desc->cBuffers; ++i)
770 SecBuffer *b = &desc->pBuffers[i];
771 TRACE("\tbuffer %u: cbBuffer %d, BufferType %#x pvBuffer %p\n", i, b->cbBuffer, b->BufferType, b->pvBuffer);
775 /***********************************************************************
776 * InitializeSecurityContextW
778 static SECURITY_STATUS SEC_ENTRY schan_InitializeSecurityContextW(
779 PCredHandle phCredential, PCtxtHandle phContext, SEC_WCHAR *pszTargetName,
780 ULONG fContextReq, ULONG Reserved1, ULONG TargetDataRep,
781 PSecBufferDesc pInput, ULONG Reserved2, PCtxtHandle phNewContext,
782 PSecBufferDesc pOutput, ULONG *pfContextAttr, PTimeStamp ptsExpiry)
784 struct schan_context *ctx;
785 struct schan_buffers *out_buffers;
786 struct schan_credentials *cred;
787 SIZE_T expected_size = ~0UL;
788 SECURITY_STATUS ret;
790 TRACE("%p %p %s 0x%08x %d %d %p %d %p %p %p %p\n", phCredential, phContext,
791 debugstr_w(pszTargetName), fContextReq, Reserved1, TargetDataRep, pInput,
792 Reserved1, phNewContext, pOutput, pfContextAttr, ptsExpiry);
794 dump_buffer_desc(pInput);
795 dump_buffer_desc(pOutput);
797 if (!phContext)
799 ULONG_PTR handle;
801 if (!phCredential) return SEC_E_INVALID_HANDLE;
803 cred = schan_get_object(phCredential->dwLower, SCHAN_HANDLE_CRED);
804 if (!cred) return SEC_E_INVALID_HANDLE;
806 if (!(cred->credential_use & SECPKG_CRED_OUTBOUND))
808 WARN("Invalid credential use %#x\n", cred->credential_use);
809 return SEC_E_INVALID_HANDLE;
812 ctx = heap_alloc(sizeof(*ctx));
813 if (!ctx) return SEC_E_INSUFFICIENT_MEMORY;
815 ctx->cert = NULL;
816 handle = schan_alloc_handle(ctx, SCHAN_HANDLE_CTX);
817 if (handle == SCHAN_INVALID_HANDLE)
819 heap_free(ctx);
820 return SEC_E_INTERNAL_ERROR;
823 if (!schan_imp_create_session(&ctx->session, cred))
825 schan_free_handle(handle, SCHAN_HANDLE_CTX);
826 heap_free(ctx);
827 return SEC_E_INTERNAL_ERROR;
830 ctx->transport.ctx = ctx;
831 schan_imp_set_session_transport(ctx->session, &ctx->transport);
833 if (pszTargetName && *pszTargetName)
835 UINT len = WideCharToMultiByte( CP_UNIXCP, 0, pszTargetName, -1, NULL, 0, NULL, NULL );
836 char *target = heap_alloc( len );
838 if (target)
840 WideCharToMultiByte( CP_UNIXCP, 0, pszTargetName, -1, target, len, NULL, NULL );
841 schan_imp_set_session_target( ctx->session, target );
842 heap_free( target );
845 phNewContext->dwLower = handle;
846 phNewContext->dwUpper = 0;
848 else
850 SIZE_T record_size = 0;
851 unsigned char *ptr;
852 SecBuffer *buffer;
853 int idx;
855 if (!pInput)
856 return SEC_E_INCOMPLETE_MESSAGE;
858 idx = schan_find_sec_buffer_idx(pInput, 0, SECBUFFER_TOKEN);
859 if (idx == -1)
860 return SEC_E_INCOMPLETE_MESSAGE;
862 buffer = &pInput->pBuffers[idx];
863 ptr = buffer->pvBuffer;
864 expected_size = 0;
866 while (buffer->cbBuffer > expected_size + 5)
868 record_size = 5 + ((ptr[3] << 8) | ptr[4]);
870 if (buffer->cbBuffer < expected_size + record_size)
871 break;
873 expected_size += record_size;
874 ptr += record_size;
877 if (!expected_size)
879 TRACE("Expected at least %lu bytes, but buffer only contains %u bytes.\n",
880 max(6, record_size), buffer->cbBuffer);
881 return SEC_E_INCOMPLETE_MESSAGE;
884 TRACE("Using expected_size %lu.\n", expected_size);
886 ctx = schan_get_object(phContext->dwLower, SCHAN_HANDLE_CTX);
889 ctx->req_ctx_attr = fContextReq;
891 init_schan_buffers(&ctx->transport.in, pInput, schan_init_sec_ctx_get_next_input_buffer);
892 ctx->transport.in.limit = expected_size;
893 init_schan_buffers(&ctx->transport.out, pOutput, schan_init_sec_ctx_get_next_output_buffer);
895 /* Perform the TLS handshake */
896 ret = schan_imp_handshake(ctx->session);
898 out_buffers = &ctx->transport.out;
899 if (out_buffers->current_buffer_idx != -1)
901 SecBuffer *buffer = &out_buffers->desc->pBuffers[out_buffers->current_buffer_idx];
902 buffer->cbBuffer = out_buffers->offset;
904 else if (out_buffers->desc && out_buffers->desc->cBuffers > 0)
906 SecBuffer *buffer = &out_buffers->desc->pBuffers[0];
907 buffer->cbBuffer = 0;
910 if(ctx->transport.in.offset && ctx->transport.in.offset != pInput->pBuffers[0].cbBuffer) {
911 if(pInput->cBuffers<2 || pInput->pBuffers[1].BufferType!=SECBUFFER_EMPTY)
912 return SEC_E_INVALID_TOKEN;
914 pInput->pBuffers[1].BufferType = SECBUFFER_EXTRA;
915 pInput->pBuffers[1].cbBuffer = pInput->pBuffers[0].cbBuffer-ctx->transport.in.offset;
918 *pfContextAttr = ISC_RET_REPLAY_DETECT | ISC_RET_SEQUENCE_DETECT | ISC_RET_CONFIDENTIALITY | ISC_RET_STREAM;
919 if (ctx->req_ctx_attr & ISC_REQ_ALLOCATE_MEMORY)
920 *pfContextAttr |= ISC_RET_ALLOCATED_MEMORY;
921 if (ctx->req_ctx_attr & ISC_REQ_USE_SUPPLIED_CREDS)
922 *pfContextAttr |= ISC_RET_USED_SUPPLIED_CREDS;
924 return ret;
927 /***********************************************************************
928 * InitializeSecurityContextA
930 static SECURITY_STATUS SEC_ENTRY schan_InitializeSecurityContextA(
931 PCredHandle phCredential, PCtxtHandle phContext, SEC_CHAR *pszTargetName,
932 ULONG fContextReq, ULONG Reserved1, ULONG TargetDataRep,
933 PSecBufferDesc pInput, ULONG Reserved2, PCtxtHandle phNewContext,
934 PSecBufferDesc pOutput, ULONG *pfContextAttr, PTimeStamp ptsExpiry)
936 SECURITY_STATUS ret;
937 SEC_WCHAR *target_name = NULL;
939 TRACE("%p %p %s %d %d %d %p %d %p %p %p %p\n", phCredential, phContext,
940 debugstr_a(pszTargetName), fContextReq, Reserved1, TargetDataRep, pInput,
941 Reserved1, phNewContext, pOutput, pfContextAttr, ptsExpiry);
943 if (pszTargetName)
945 INT len = MultiByteToWideChar(CP_ACP, 0, pszTargetName, -1, NULL, 0);
946 if (!(target_name = heap_alloc(len * sizeof(*target_name)))) return SEC_E_INSUFFICIENT_MEMORY;
947 MultiByteToWideChar(CP_ACP, 0, pszTargetName, -1, target_name, len);
950 ret = schan_InitializeSecurityContextW(phCredential, phContext, target_name,
951 fContextReq, Reserved1, TargetDataRep, pInput, Reserved2,
952 phNewContext, pOutput, pfContextAttr, ptsExpiry);
954 heap_free(target_name);
955 return ret;
958 static void *get_alg_name(ALG_ID id, BOOL wide)
960 static const struct {
961 ALG_ID alg_id;
962 const char* name;
963 const WCHAR nameW[8];
964 } alg_name_map[] = {
965 { CALG_ECDSA, "ECDSA", {'E','C','D','S','A',0} },
966 { CALG_RSA_SIGN, "RSA", {'R','S','A',0} },
967 { CALG_DES, "DES", {'D','E','S',0} },
968 { CALG_RC2, "RC2", {'R','C','2',0} },
969 { CALG_3DES, "3DES", {'3','D','E','S',0} },
970 { CALG_AES_128, "AES", {'A','E','S',0} },
971 { CALG_AES_192, "AES", {'A','E','S',0} },
972 { CALG_AES_256, "AES", {'A','E','S',0} },
973 { CALG_RC4, "RC4", {'R','C','4',0} },
975 unsigned i;
977 for (i = 0; i < ARRAY_SIZE(alg_name_map); i++)
978 if (alg_name_map[i].alg_id == id)
979 return wide ? (void*)alg_name_map[i].nameW : (void*)alg_name_map[i].name;
981 FIXME("Unknown ALG_ID %04x\n", id);
982 return NULL;
985 static SECURITY_STATUS ensure_remote_cert(struct schan_context *ctx)
987 HCERTSTORE cert_store;
988 SECURITY_STATUS status;
990 if(ctx->cert)
991 return SEC_E_OK;
993 cert_store = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0, CERT_STORE_CREATE_NEW_FLAG, NULL);
994 if(!cert_store)
995 return GetLastError();
997 status = schan_imp_get_session_peer_certificate(ctx->session, cert_store, &ctx->cert);
998 CertCloseStore(cert_store, 0);
999 return status;
1002 static SECURITY_STATUS SEC_ENTRY schan_QueryContextAttributesW(
1003 PCtxtHandle context_handle, ULONG attribute, PVOID buffer)
1005 struct schan_context *ctx;
1007 TRACE("context_handle %p, attribute %#x, buffer %p\n",
1008 context_handle, attribute, buffer);
1010 if (!context_handle) return SEC_E_INVALID_HANDLE;
1011 ctx = schan_get_object(context_handle->dwLower, SCHAN_HANDLE_CTX);
1013 switch(attribute)
1015 case SECPKG_ATTR_STREAM_SIZES:
1017 SecPkgContext_ConnectionInfo info;
1018 SECURITY_STATUS status = schan_imp_get_connection_info(ctx->session, &info);
1019 if (status == SEC_E_OK)
1021 SecPkgContext_StreamSizes *stream_sizes = buffer;
1022 SIZE_T mac_size = info.dwHashStrength;
1023 unsigned int block_size = schan_imp_get_session_cipher_block_size(ctx->session);
1024 unsigned int message_size = schan_imp_get_max_message_size(ctx->session);
1026 TRACE("Using %lu mac bytes, message size %u, block size %u\n",
1027 mac_size, message_size, block_size);
1029 /* These are defined by the TLS RFC */
1030 stream_sizes->cbHeader = 5;
1031 stream_sizes->cbTrailer = mac_size + 256; /* Max 255 bytes padding + 1 for padding size */
1032 stream_sizes->cbMaximumMessage = message_size;
1033 stream_sizes->cbBuffers = 4;
1034 stream_sizes->cbBlockSize = block_size;
1037 return status;
1039 case SECPKG_ATTR_KEY_INFO:
1041 SecPkgContext_ConnectionInfo conn_info;
1042 SECURITY_STATUS status = schan_imp_get_connection_info(ctx->session, &conn_info);
1043 if (status == SEC_E_OK)
1045 SecPkgContext_KeyInfoW *info = buffer;
1046 info->KeySize = conn_info.dwCipherStrength;
1047 info->SignatureAlgorithm = schan_imp_get_key_signature_algorithm(ctx->session);
1048 info->EncryptAlgorithm = conn_info.aiCipher;
1049 info->sSignatureAlgorithmName = get_alg_name(info->SignatureAlgorithm, TRUE);
1050 info->sEncryptAlgorithmName = get_alg_name(info->EncryptAlgorithm, TRUE);
1052 return status;
1054 case SECPKG_ATTR_REMOTE_CERT_CONTEXT:
1056 PCCERT_CONTEXT *cert = buffer;
1057 SECURITY_STATUS status;
1059 status = ensure_remote_cert(ctx);
1060 if(status != SEC_E_OK)
1061 return status;
1063 *cert = CertDuplicateCertificateContext(ctx->cert);
1064 return SEC_E_OK;
1066 case SECPKG_ATTR_CONNECTION_INFO:
1068 SecPkgContext_ConnectionInfo *info = buffer;
1069 return schan_imp_get_connection_info(ctx->session, info);
1071 case SECPKG_ATTR_ENDPOINT_BINDINGS:
1073 SecPkgContext_Bindings *bindings = buffer;
1074 CCRYPT_OID_INFO *info;
1075 ALG_ID hash_alg = CALG_SHA_256;
1076 BYTE hash[1024];
1077 DWORD hash_size;
1078 SECURITY_STATUS status;
1079 char *p;
1080 BOOL r;
1082 static const char prefix[] = "tls-server-end-point:";
1084 status = ensure_remote_cert(ctx);
1085 if(status != SEC_E_OK)
1086 return status;
1088 /* RFC 5929 */
1089 info = CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY, ctx->cert->pCertInfo->SignatureAlgorithm.pszObjId, 0);
1090 if(info && info->u.Algid != CALG_SHA1 && info->u.Algid != CALG_MD5)
1091 hash_alg = info->u.Algid;
1093 hash_size = sizeof(hash);
1094 r = CryptHashCertificate(0, hash_alg, 0, ctx->cert->pbCertEncoded, ctx->cert->cbCertEncoded, hash, &hash_size);
1095 if(!r)
1096 return GetLastError();
1098 bindings->BindingsLength = sizeof(*bindings->Bindings) + sizeof(prefix)-1 + hash_size;
1099 bindings->Bindings = heap_alloc_zero(bindings->BindingsLength);
1100 if(!bindings->Bindings)
1101 return SEC_E_INSUFFICIENT_MEMORY;
1103 bindings->Bindings->cbApplicationDataLength = sizeof(prefix)-1 + hash_size;
1104 bindings->Bindings->dwApplicationDataOffset = sizeof(*bindings->Bindings);
1106 p = (char*)(bindings->Bindings+1);
1107 memcpy(p, prefix, sizeof(prefix)-1);
1108 p += sizeof(prefix)-1;
1109 memcpy(p, hash, hash_size);
1110 return SEC_E_OK;
1113 default:
1114 FIXME("Unhandled attribute %#x\n", attribute);
1115 return SEC_E_UNSUPPORTED_FUNCTION;
1119 static SECURITY_STATUS SEC_ENTRY schan_QueryContextAttributesA(
1120 PCtxtHandle context_handle, ULONG attribute, PVOID buffer)
1122 TRACE("context_handle %p, attribute %#x, buffer %p\n",
1123 context_handle, attribute, buffer);
1125 switch(attribute)
1127 case SECPKG_ATTR_STREAM_SIZES:
1128 return schan_QueryContextAttributesW(context_handle, attribute, buffer);
1129 case SECPKG_ATTR_KEY_INFO:
1131 SECURITY_STATUS status = schan_QueryContextAttributesW(context_handle, attribute, buffer);
1132 if (status == SEC_E_OK)
1134 SecPkgContext_KeyInfoA *info = buffer;
1135 info->sSignatureAlgorithmName = get_alg_name(info->SignatureAlgorithm, FALSE);
1136 info->sEncryptAlgorithmName = get_alg_name(info->EncryptAlgorithm, FALSE);
1138 return status;
1140 case SECPKG_ATTR_REMOTE_CERT_CONTEXT:
1141 return schan_QueryContextAttributesW(context_handle, attribute, buffer);
1142 case SECPKG_ATTR_CONNECTION_INFO:
1143 return schan_QueryContextAttributesW(context_handle, attribute, buffer);
1144 case SECPKG_ATTR_ENDPOINT_BINDINGS:
1145 return schan_QueryContextAttributesW(context_handle, attribute, buffer);
1147 default:
1148 FIXME("Unhandled attribute %#x\n", attribute);
1149 return SEC_E_UNSUPPORTED_FUNCTION;
1153 static int schan_encrypt_message_get_next_buffer(const struct schan_transport *t, struct schan_buffers *s)
1155 SecBuffer *b;
1157 if (s->current_buffer_idx == -1)
1158 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_STREAM_HEADER);
1160 b = &s->desc->pBuffers[s->current_buffer_idx];
1162 if (b->BufferType == SECBUFFER_STREAM_HEADER)
1163 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_DATA);
1165 if (b->BufferType == SECBUFFER_DATA)
1166 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_STREAM_TRAILER);
1168 return -1;
1171 static int schan_encrypt_message_get_next_buffer_token(const struct schan_transport *t, struct schan_buffers *s)
1173 SecBuffer *b;
1175 if (s->current_buffer_idx == -1)
1176 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
1178 b = &s->desc->pBuffers[s->current_buffer_idx];
1180 if (b->BufferType == SECBUFFER_TOKEN)
1182 int idx = schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
1183 if (idx != s->current_buffer_idx) return -1;
1184 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_DATA);
1187 if (b->BufferType == SECBUFFER_DATA)
1189 int idx = schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
1190 if (idx != -1)
1191 idx = schan_find_sec_buffer_idx(s->desc, idx + 1, SECBUFFER_TOKEN);
1192 return idx;
1195 return -1;
1198 static SECURITY_STATUS SEC_ENTRY schan_EncryptMessage(PCtxtHandle context_handle,
1199 ULONG quality, PSecBufferDesc message, ULONG message_seq_no)
1201 struct schan_context *ctx;
1202 struct schan_buffers *b;
1203 SECURITY_STATUS status;
1204 SecBuffer *buffer;
1205 SIZE_T data_size;
1206 SIZE_T length;
1207 char *data;
1208 int idx;
1210 TRACE("context_handle %p, quality %d, message %p, message_seq_no %d\n",
1211 context_handle, quality, message, message_seq_no);
1213 if (!context_handle) return SEC_E_INVALID_HANDLE;
1214 ctx = schan_get_object(context_handle->dwLower, SCHAN_HANDLE_CTX);
1216 dump_buffer_desc(message);
1218 idx = schan_find_sec_buffer_idx(message, 0, SECBUFFER_DATA);
1219 if (idx == -1)
1221 WARN("No data buffer passed\n");
1222 return SEC_E_INTERNAL_ERROR;
1224 buffer = &message->pBuffers[idx];
1226 data_size = buffer->cbBuffer;
1227 data = heap_alloc(data_size);
1228 memcpy(data, buffer->pvBuffer, data_size);
1230 if (schan_find_sec_buffer_idx(message, 0, SECBUFFER_STREAM_HEADER) != -1)
1231 init_schan_buffers(&ctx->transport.out, message, schan_encrypt_message_get_next_buffer);
1232 else
1233 init_schan_buffers(&ctx->transport.out, message, schan_encrypt_message_get_next_buffer_token);
1235 length = data_size;
1236 status = schan_imp_send(ctx->session, data, &length);
1238 TRACE("Sent %ld bytes.\n", length);
1240 if (length != data_size)
1241 status = SEC_E_INTERNAL_ERROR;
1243 b = &ctx->transport.out;
1244 b->desc->pBuffers[b->current_buffer_idx].cbBuffer = b->offset;
1245 heap_free(data);
1247 TRACE("Returning %#x.\n", status);
1249 return status;
1252 static int schan_decrypt_message_get_next_buffer(const struct schan_transport *t, struct schan_buffers *s)
1254 if (s->current_buffer_idx == -1)
1255 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_DATA);
1257 return -1;
1260 static int schan_validate_decrypt_buffer_desc(PSecBufferDesc message)
1262 int data_idx = -1;
1263 unsigned int empty_count = 0;
1264 unsigned int i;
1266 if (message->cBuffers < 4)
1268 WARN("Less than four buffers passed\n");
1269 return -1;
1272 for (i = 0; i < message->cBuffers; ++i)
1274 SecBuffer *b = &message->pBuffers[i];
1275 if (b->BufferType == SECBUFFER_DATA)
1277 if (data_idx != -1)
1279 WARN("More than one data buffer passed\n");
1280 return -1;
1282 data_idx = i;
1284 else if (b->BufferType == SECBUFFER_EMPTY)
1285 ++empty_count;
1288 if (data_idx == -1)
1290 WARN("No data buffer passed\n");
1291 return -1;
1294 if (empty_count < 3)
1296 WARN("Less than three empty buffers passed\n");
1297 return -1;
1300 return data_idx;
1303 static void schan_decrypt_fill_buffer(PSecBufferDesc message, ULONG buffer_type, void *data, ULONG size)
1305 int idx;
1306 SecBuffer *buffer;
1308 idx = schan_find_sec_buffer_idx(message, 0, SECBUFFER_EMPTY);
1309 buffer = &message->pBuffers[idx];
1311 buffer->BufferType = buffer_type;
1312 buffer->pvBuffer = data;
1313 buffer->cbBuffer = size;
1316 static SECURITY_STATUS SEC_ENTRY schan_DecryptMessage(PCtxtHandle context_handle,
1317 PSecBufferDesc message, ULONG message_seq_no, PULONG quality)
1319 struct schan_context *ctx;
1320 SecBuffer *buffer;
1321 SIZE_T data_size;
1322 char *data;
1323 unsigned expected_size;
1324 SSIZE_T received = 0;
1325 int idx;
1326 unsigned char *buf_ptr;
1328 TRACE("context_handle %p, message %p, message_seq_no %d, quality %p\n",
1329 context_handle, message, message_seq_no, quality);
1331 if (!context_handle) return SEC_E_INVALID_HANDLE;
1332 ctx = schan_get_object(context_handle->dwLower, SCHAN_HANDLE_CTX);
1334 dump_buffer_desc(message);
1336 idx = schan_validate_decrypt_buffer_desc(message);
1337 if (idx == -1)
1338 return SEC_E_INVALID_TOKEN;
1339 buffer = &message->pBuffers[idx];
1340 buf_ptr = buffer->pvBuffer;
1342 expected_size = 5 + ((buf_ptr[3] << 8) | buf_ptr[4]);
1343 if(buffer->cbBuffer < expected_size)
1345 TRACE("Expected %u bytes, but buffer only contains %u bytes\n", expected_size, buffer->cbBuffer);
1346 buffer->BufferType = SECBUFFER_MISSING;
1347 buffer->cbBuffer = expected_size - buffer->cbBuffer;
1349 /* This is a bit weird, but windows does it too */
1350 idx = schan_find_sec_buffer_idx(message, 0, SECBUFFER_EMPTY);
1351 buffer = &message->pBuffers[idx];
1352 buffer->BufferType = SECBUFFER_MISSING;
1353 buffer->cbBuffer = expected_size - buffer->cbBuffer;
1355 TRACE("Returning SEC_E_INCOMPLETE_MESSAGE\n");
1356 return SEC_E_INCOMPLETE_MESSAGE;
1359 data_size = expected_size - 5;
1360 data = heap_alloc(data_size);
1362 init_schan_buffers(&ctx->transport.in, message, schan_decrypt_message_get_next_buffer);
1363 ctx->transport.in.limit = expected_size;
1365 while (received < data_size)
1367 SIZE_T length = data_size - received;
1368 SECURITY_STATUS status = schan_imp_recv(ctx->session, data + received, &length);
1370 if (status == SEC_I_CONTINUE_NEEDED)
1371 break;
1373 if (status != SEC_E_OK)
1375 heap_free(data);
1376 ERR("Returning %x\n", status);
1377 return status;
1380 if (!length)
1381 break;
1383 received += length;
1386 TRACE("Received %ld bytes\n", received);
1388 memcpy(buf_ptr + 5, data, received);
1389 heap_free(data);
1391 schan_decrypt_fill_buffer(message, SECBUFFER_DATA,
1392 buf_ptr + 5, received);
1394 schan_decrypt_fill_buffer(message, SECBUFFER_STREAM_TRAILER,
1395 buf_ptr + 5 + received, buffer->cbBuffer - 5 - received);
1397 if(buffer->cbBuffer > expected_size)
1398 schan_decrypt_fill_buffer(message, SECBUFFER_EXTRA,
1399 buf_ptr + expected_size, buffer->cbBuffer - expected_size);
1401 buffer->BufferType = SECBUFFER_STREAM_HEADER;
1402 buffer->cbBuffer = 5;
1404 return SEC_E_OK;
1407 static SECURITY_STATUS SEC_ENTRY schan_DeleteSecurityContext(PCtxtHandle context_handle)
1409 struct schan_context *ctx;
1411 TRACE("context_handle %p\n", context_handle);
1413 if (!context_handle) return SEC_E_INVALID_HANDLE;
1415 ctx = schan_free_handle(context_handle->dwLower, SCHAN_HANDLE_CTX);
1416 if (!ctx) return SEC_E_INVALID_HANDLE;
1418 if (ctx->cert)
1419 CertFreeCertificateContext(ctx->cert);
1420 schan_imp_dispose_session(ctx->session);
1421 heap_free(ctx);
1423 return SEC_E_OK;
1426 static const SecurityFunctionTableA schanTableA = {
1428 NULL, /* EnumerateSecurityPackagesA */
1429 schan_QueryCredentialsAttributesA,
1430 schan_AcquireCredentialsHandleA,
1431 schan_FreeCredentialsHandle,
1432 NULL, /* Reserved2 */
1433 schan_InitializeSecurityContextA,
1434 NULL, /* AcceptSecurityContext */
1435 NULL, /* CompleteAuthToken */
1436 schan_DeleteSecurityContext,
1437 NULL, /* ApplyControlToken */
1438 schan_QueryContextAttributesA,
1439 NULL, /* ImpersonateSecurityContext */
1440 NULL, /* RevertSecurityContext */
1441 NULL, /* MakeSignature */
1442 NULL, /* VerifySignature */
1443 FreeContextBuffer,
1444 NULL, /* QuerySecurityPackageInfoA */
1445 NULL, /* Reserved3 */
1446 NULL, /* Reserved4 */
1447 NULL, /* ExportSecurityContext */
1448 NULL, /* ImportSecurityContextA */
1449 NULL, /* AddCredentialsA */
1450 NULL, /* Reserved8 */
1451 NULL, /* QuerySecurityContextToken */
1452 schan_EncryptMessage,
1453 schan_DecryptMessage,
1454 NULL, /* SetContextAttributesA */
1457 static const SecurityFunctionTableW schanTableW = {
1459 NULL, /* EnumerateSecurityPackagesW */
1460 schan_QueryCredentialsAttributesW,
1461 schan_AcquireCredentialsHandleW,
1462 schan_FreeCredentialsHandle,
1463 NULL, /* Reserved2 */
1464 schan_InitializeSecurityContextW,
1465 NULL, /* AcceptSecurityContext */
1466 NULL, /* CompleteAuthToken */
1467 schan_DeleteSecurityContext,
1468 NULL, /* ApplyControlToken */
1469 schan_QueryContextAttributesW,
1470 NULL, /* ImpersonateSecurityContext */
1471 NULL, /* RevertSecurityContext */
1472 NULL, /* MakeSignature */
1473 NULL, /* VerifySignature */
1474 FreeContextBuffer,
1475 NULL, /* QuerySecurityPackageInfoW */
1476 NULL, /* Reserved3 */
1477 NULL, /* Reserved4 */
1478 NULL, /* ExportSecurityContext */
1479 NULL, /* ImportSecurityContextW */
1480 NULL, /* AddCredentialsW */
1481 NULL, /* Reserved8 */
1482 NULL, /* QuerySecurityContextToken */
1483 schan_EncryptMessage,
1484 schan_DecryptMessage,
1485 NULL, /* SetContextAttributesW */
1488 static const WCHAR schannelComment[] = { 'S','c','h','a','n','n','e','l',' ',
1489 'S','e','c','u','r','i','t','y',' ','P','a','c','k','a','g','e',0 };
1490 static const WCHAR schannelDllName[] = { 's','c','h','a','n','n','e','l','.','d','l','l',0 };
1492 void SECUR32_initSchannelSP(void)
1494 /* This is what Windows reports. This shouldn't break any applications
1495 * even though the functions are missing, because the wrapper will
1496 * return SEC_E_UNSUPPORTED_FUNCTION if our function is NULL.
1498 static const LONG caps =
1499 SECPKG_FLAG_INTEGRITY |
1500 SECPKG_FLAG_PRIVACY |
1501 SECPKG_FLAG_CONNECTION |
1502 SECPKG_FLAG_MULTI_REQUIRED |
1503 SECPKG_FLAG_EXTENDED_ERROR |
1504 SECPKG_FLAG_IMPERSONATION |
1505 SECPKG_FLAG_ACCEPT_WIN32_NAME |
1506 SECPKG_FLAG_STREAM;
1507 static const short version = 1;
1508 static const LONG maxToken = 16384;
1509 SEC_WCHAR *uniSPName = (SEC_WCHAR *)UNISP_NAME_W,
1510 *schannel = (SEC_WCHAR *)SCHANNEL_NAME_W;
1511 const SecPkgInfoW info[] = {
1512 { caps, version, UNISP_RPC_ID, maxToken, uniSPName, uniSPName },
1513 { caps, version, UNISP_RPC_ID, maxToken, schannel,
1514 (SEC_WCHAR *)schannelComment },
1516 SecureProvider *provider;
1518 if (!schan_imp_init())
1519 return;
1521 schan_handle_table = heap_alloc(64 * sizeof(*schan_handle_table));
1522 if (!schan_handle_table)
1524 ERR("Failed to allocate schannel handle table.\n");
1525 goto fail;
1527 schan_handle_table_size = 64;
1529 provider = SECUR32_addProvider(&schanTableA, &schanTableW, schannelDllName);
1530 if (!provider)
1532 ERR("Failed to add schannel provider.\n");
1533 goto fail;
1536 SECUR32_addPackages(provider, ARRAY_SIZE(info), NULL, info);
1538 return;
1540 fail:
1541 heap_free(schan_handle_table);
1542 schan_handle_table = NULL;
1543 schan_imp_deinit();
1544 return;
1547 void SECUR32_deinitSchannelSP(void)
1549 SIZE_T i = schan_handle_count;
1551 if (!schan_handle_table) return;
1553 /* deinitialized sessions first because a pointer to the credentials
1554 * may be stored for the session. */
1555 while (i--)
1557 if (schan_handle_table[i].type == SCHAN_HANDLE_CTX)
1559 struct schan_context *ctx = schan_free_handle(i, SCHAN_HANDLE_CTX);
1560 schan_imp_dispose_session(ctx->session);
1561 heap_free(ctx);
1564 i = schan_handle_count;
1565 while (i--)
1567 if (schan_handle_table[i].type != SCHAN_HANDLE_FREE)
1569 struct schan_credentials *cred;
1570 cred = schan_free_handle(i, SCHAN_HANDLE_CRED);
1571 schan_imp_free_certificate_credentials(cred);
1572 heap_free(cred);
1575 heap_free(schan_handle_table);
1576 schan_imp_deinit();
1579 #else /* SONAME_LIBGNUTLS || HAVE_SECURITY_SECURITY_H */
1581 void SECUR32_initSchannelSP(void)
1583 ERR("TLS library not found, SSL connections will fail\n");
1586 void SECUR32_deinitSchannelSP(void) {}
1588 #endif /* SONAME_LIBGNUTLS || HAVE_SECURITY_SECURITY_H */