comctl32: Remove the masked background when 32bpp bitmaps have no alpha values.
[wine.git] / dlls / secur32 / schannel.c
blobe76a3e46c34587ab91204182e78e321c3e8d643b
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;
789 SecBuffer *buffer;
790 int idx;
792 TRACE("%p %p %s 0x%08x %d %d %p %d %p %p %p %p\n", phCredential, phContext,
793 debugstr_w(pszTargetName), fContextReq, Reserved1, TargetDataRep, pInput,
794 Reserved1, phNewContext, pOutput, pfContextAttr, ptsExpiry);
796 dump_buffer_desc(pInput);
797 dump_buffer_desc(pOutput);
799 if (!phContext)
801 ULONG_PTR handle;
803 if (!phCredential) return SEC_E_INVALID_HANDLE;
805 cred = schan_get_object(phCredential->dwLower, SCHAN_HANDLE_CRED);
806 if (!cred) return SEC_E_INVALID_HANDLE;
808 if (!(cred->credential_use & SECPKG_CRED_OUTBOUND))
810 WARN("Invalid credential use %#x\n", cred->credential_use);
811 return SEC_E_INVALID_HANDLE;
814 ctx = heap_alloc(sizeof(*ctx));
815 if (!ctx) return SEC_E_INSUFFICIENT_MEMORY;
817 ctx->cert = NULL;
818 handle = schan_alloc_handle(ctx, SCHAN_HANDLE_CTX);
819 if (handle == SCHAN_INVALID_HANDLE)
821 heap_free(ctx);
822 return SEC_E_INTERNAL_ERROR;
825 if (!schan_imp_create_session(&ctx->session, cred))
827 schan_free_handle(handle, SCHAN_HANDLE_CTX);
828 heap_free(ctx);
829 return SEC_E_INTERNAL_ERROR;
832 ctx->transport.ctx = ctx;
833 schan_imp_set_session_transport(ctx->session, &ctx->transport);
835 if (pszTargetName && *pszTargetName)
837 UINT len = WideCharToMultiByte( CP_UNIXCP, 0, pszTargetName, -1, NULL, 0, NULL, NULL );
838 char *target = heap_alloc( len );
840 if (target)
842 WideCharToMultiByte( CP_UNIXCP, 0, pszTargetName, -1, target, len, NULL, NULL );
843 schan_imp_set_session_target( ctx->session, target );
844 heap_free( target );
848 if (pInput && (idx = schan_find_sec_buffer_idx(pInput, 0, SECBUFFER_APPLICATION_PROTOCOLS)) != -1)
850 buffer = &pInput->pBuffers[idx];
851 schan_imp_set_application_protocols(ctx->session, buffer->pvBuffer, buffer->cbBuffer);
854 phNewContext->dwLower = handle;
855 phNewContext->dwUpper = 0;
857 else
859 SIZE_T record_size = 0;
860 unsigned char *ptr;
862 if (!pInput)
863 return SEC_E_INCOMPLETE_MESSAGE;
865 idx = schan_find_sec_buffer_idx(pInput, 0, SECBUFFER_TOKEN);
866 if (idx == -1)
867 return SEC_E_INCOMPLETE_MESSAGE;
869 buffer = &pInput->pBuffers[idx];
870 ptr = buffer->pvBuffer;
871 expected_size = 0;
873 while (buffer->cbBuffer > expected_size + 5)
875 record_size = 5 + ((ptr[3] << 8) | ptr[4]);
877 if (buffer->cbBuffer < expected_size + record_size)
878 break;
880 expected_size += record_size;
881 ptr += record_size;
884 if (!expected_size)
886 TRACE("Expected at least %lu bytes, but buffer only contains %u bytes.\n",
887 max(6, record_size), buffer->cbBuffer);
888 return SEC_E_INCOMPLETE_MESSAGE;
891 TRACE("Using expected_size %lu.\n", expected_size);
893 ctx = schan_get_object(phContext->dwLower, SCHAN_HANDLE_CTX);
896 ctx->req_ctx_attr = fContextReq;
898 init_schan_buffers(&ctx->transport.in, pInput, schan_init_sec_ctx_get_next_input_buffer);
899 ctx->transport.in.limit = expected_size;
900 init_schan_buffers(&ctx->transport.out, pOutput, schan_init_sec_ctx_get_next_output_buffer);
902 /* Perform the TLS handshake */
903 ret = schan_imp_handshake(ctx->session);
905 out_buffers = &ctx->transport.out;
906 if (out_buffers->current_buffer_idx != -1)
908 SecBuffer *buffer = &out_buffers->desc->pBuffers[out_buffers->current_buffer_idx];
909 buffer->cbBuffer = out_buffers->offset;
911 else if (out_buffers->desc && out_buffers->desc->cBuffers > 0)
913 SecBuffer *buffer = &out_buffers->desc->pBuffers[0];
914 buffer->cbBuffer = 0;
917 if(ctx->transport.in.offset && ctx->transport.in.offset != pInput->pBuffers[0].cbBuffer) {
918 if(pInput->cBuffers<2 || pInput->pBuffers[1].BufferType!=SECBUFFER_EMPTY)
919 return SEC_E_INVALID_TOKEN;
921 pInput->pBuffers[1].BufferType = SECBUFFER_EXTRA;
922 pInput->pBuffers[1].cbBuffer = pInput->pBuffers[0].cbBuffer-ctx->transport.in.offset;
925 *pfContextAttr = ISC_RET_REPLAY_DETECT | ISC_RET_SEQUENCE_DETECT | ISC_RET_CONFIDENTIALITY | ISC_RET_STREAM;
926 if (ctx->req_ctx_attr & ISC_REQ_ALLOCATE_MEMORY)
927 *pfContextAttr |= ISC_RET_ALLOCATED_MEMORY;
928 if (ctx->req_ctx_attr & ISC_REQ_USE_SUPPLIED_CREDS)
929 *pfContextAttr |= ISC_RET_USED_SUPPLIED_CREDS;
931 return ret;
934 /***********************************************************************
935 * InitializeSecurityContextA
937 static SECURITY_STATUS SEC_ENTRY schan_InitializeSecurityContextA(
938 PCredHandle phCredential, PCtxtHandle phContext, SEC_CHAR *pszTargetName,
939 ULONG fContextReq, ULONG Reserved1, ULONG TargetDataRep,
940 PSecBufferDesc pInput, ULONG Reserved2, PCtxtHandle phNewContext,
941 PSecBufferDesc pOutput, ULONG *pfContextAttr, PTimeStamp ptsExpiry)
943 SECURITY_STATUS ret;
944 SEC_WCHAR *target_name = NULL;
946 TRACE("%p %p %s %d %d %d %p %d %p %p %p %p\n", phCredential, phContext,
947 debugstr_a(pszTargetName), fContextReq, Reserved1, TargetDataRep, pInput,
948 Reserved1, phNewContext, pOutput, pfContextAttr, ptsExpiry);
950 if (pszTargetName)
952 INT len = MultiByteToWideChar(CP_ACP, 0, pszTargetName, -1, NULL, 0);
953 if (!(target_name = heap_alloc(len * sizeof(*target_name)))) return SEC_E_INSUFFICIENT_MEMORY;
954 MultiByteToWideChar(CP_ACP, 0, pszTargetName, -1, target_name, len);
957 ret = schan_InitializeSecurityContextW(phCredential, phContext, target_name,
958 fContextReq, Reserved1, TargetDataRep, pInput, Reserved2,
959 phNewContext, pOutput, pfContextAttr, ptsExpiry);
961 heap_free(target_name);
962 return ret;
965 static void *get_alg_name(ALG_ID id, BOOL wide)
967 static const struct {
968 ALG_ID alg_id;
969 const char* name;
970 const WCHAR nameW[8];
971 } alg_name_map[] = {
972 { CALG_ECDSA, "ECDSA", {'E','C','D','S','A',0} },
973 { CALG_RSA_SIGN, "RSA", {'R','S','A',0} },
974 { CALG_DES, "DES", {'D','E','S',0} },
975 { CALG_RC2, "RC2", {'R','C','2',0} },
976 { CALG_3DES, "3DES", {'3','D','E','S',0} },
977 { CALG_AES_128, "AES", {'A','E','S',0} },
978 { CALG_AES_192, "AES", {'A','E','S',0} },
979 { CALG_AES_256, "AES", {'A','E','S',0} },
980 { CALG_RC4, "RC4", {'R','C','4',0} },
982 unsigned i;
984 for (i = 0; i < ARRAY_SIZE(alg_name_map); i++)
985 if (alg_name_map[i].alg_id == id)
986 return wide ? (void*)alg_name_map[i].nameW : (void*)alg_name_map[i].name;
988 FIXME("Unknown ALG_ID %04x\n", id);
989 return NULL;
992 static SECURITY_STATUS ensure_remote_cert(struct schan_context *ctx)
994 HCERTSTORE cert_store;
995 SECURITY_STATUS status;
997 if(ctx->cert)
998 return SEC_E_OK;
1000 cert_store = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0, CERT_STORE_CREATE_NEW_FLAG, NULL);
1001 if(!cert_store)
1002 return GetLastError();
1004 status = schan_imp_get_session_peer_certificate(ctx->session, cert_store, &ctx->cert);
1005 CertCloseStore(cert_store, 0);
1006 return status;
1009 static SECURITY_STATUS SEC_ENTRY schan_QueryContextAttributesW(
1010 PCtxtHandle context_handle, ULONG attribute, PVOID buffer)
1012 struct schan_context *ctx;
1013 SECURITY_STATUS status;
1015 TRACE("context_handle %p, attribute %#x, buffer %p\n",
1016 context_handle, attribute, buffer);
1018 if (!context_handle) return SEC_E_INVALID_HANDLE;
1019 ctx = schan_get_object(context_handle->dwLower, SCHAN_HANDLE_CTX);
1021 switch(attribute)
1023 case SECPKG_ATTR_STREAM_SIZES:
1025 SecPkgContext_ConnectionInfo info;
1026 status = schan_imp_get_connection_info(ctx->session, &info);
1027 if (status == SEC_E_OK)
1029 SecPkgContext_StreamSizes *stream_sizes = buffer;
1030 SIZE_T mac_size = info.dwHashStrength;
1031 unsigned int block_size = schan_imp_get_session_cipher_block_size(ctx->session);
1032 unsigned int message_size = schan_imp_get_max_message_size(ctx->session);
1034 TRACE("Using %lu mac bytes, message size %u, block size %u\n",
1035 mac_size, message_size, block_size);
1037 /* These are defined by the TLS RFC */
1038 stream_sizes->cbHeader = 5;
1039 stream_sizes->cbTrailer = mac_size + 256; /* Max 255 bytes padding + 1 for padding size */
1040 stream_sizes->cbMaximumMessage = message_size;
1041 stream_sizes->cbBuffers = 4;
1042 stream_sizes->cbBlockSize = block_size;
1045 return status;
1047 case SECPKG_ATTR_KEY_INFO:
1049 SecPkgContext_ConnectionInfo conn_info;
1050 status = schan_imp_get_connection_info(ctx->session, &conn_info);
1051 if (status == SEC_E_OK)
1053 SecPkgContext_KeyInfoW *info = buffer;
1054 info->KeySize = conn_info.dwCipherStrength;
1055 info->SignatureAlgorithm = schan_imp_get_key_signature_algorithm(ctx->session);
1056 info->EncryptAlgorithm = conn_info.aiCipher;
1057 info->sSignatureAlgorithmName = get_alg_name(info->SignatureAlgorithm, TRUE);
1058 info->sEncryptAlgorithmName = get_alg_name(info->EncryptAlgorithm, TRUE);
1060 return status;
1062 case SECPKG_ATTR_REMOTE_CERT_CONTEXT:
1064 PCCERT_CONTEXT *cert = buffer;
1066 status = ensure_remote_cert(ctx);
1067 if(status != SEC_E_OK)
1068 return status;
1070 *cert = CertDuplicateCertificateContext(ctx->cert);
1071 return SEC_E_OK;
1073 case SECPKG_ATTR_CONNECTION_INFO:
1075 SecPkgContext_ConnectionInfo *info = buffer;
1076 return schan_imp_get_connection_info(ctx->session, info);
1078 case SECPKG_ATTR_ENDPOINT_BINDINGS:
1080 SecPkgContext_Bindings *bindings = buffer;
1081 CCRYPT_OID_INFO *info;
1082 ALG_ID hash_alg = CALG_SHA_256;
1083 BYTE hash[1024];
1084 DWORD hash_size;
1085 char *p;
1086 BOOL r;
1088 static const char prefix[] = "tls-server-end-point:";
1090 status = ensure_remote_cert(ctx);
1091 if(status != SEC_E_OK)
1092 return status;
1094 /* RFC 5929 */
1095 info = CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY, ctx->cert->pCertInfo->SignatureAlgorithm.pszObjId, 0);
1096 if(info && info->u.Algid != CALG_SHA1 && info->u.Algid != CALG_MD5)
1097 hash_alg = info->u.Algid;
1099 hash_size = sizeof(hash);
1100 r = CryptHashCertificate(0, hash_alg, 0, ctx->cert->pbCertEncoded, ctx->cert->cbCertEncoded, hash, &hash_size);
1101 if(!r)
1102 return GetLastError();
1104 bindings->BindingsLength = sizeof(*bindings->Bindings) + sizeof(prefix)-1 + hash_size;
1105 bindings->Bindings = heap_alloc_zero(bindings->BindingsLength);
1106 if(!bindings->Bindings)
1107 return SEC_E_INSUFFICIENT_MEMORY;
1109 bindings->Bindings->cbApplicationDataLength = sizeof(prefix)-1 + hash_size;
1110 bindings->Bindings->dwApplicationDataOffset = sizeof(*bindings->Bindings);
1112 p = (char*)(bindings->Bindings+1);
1113 memcpy(p, prefix, sizeof(prefix)-1);
1114 p += sizeof(prefix)-1;
1115 memcpy(p, hash, hash_size);
1116 return SEC_E_OK;
1118 case SECPKG_ATTR_APPLICATION_PROTOCOL:
1120 SecPkgContext_ApplicationProtocol *protocol = buffer;
1121 return schan_imp_get_application_protocol(ctx->session, protocol);
1124 default:
1125 FIXME("Unhandled attribute %#x\n", attribute);
1126 return SEC_E_UNSUPPORTED_FUNCTION;
1130 static SECURITY_STATUS SEC_ENTRY schan_QueryContextAttributesA(
1131 PCtxtHandle context_handle, ULONG attribute, PVOID buffer)
1133 TRACE("context_handle %p, attribute %#x, buffer %p\n",
1134 context_handle, attribute, buffer);
1136 switch(attribute)
1138 case SECPKG_ATTR_STREAM_SIZES:
1139 return schan_QueryContextAttributesW(context_handle, attribute, buffer);
1140 case SECPKG_ATTR_KEY_INFO:
1142 SECURITY_STATUS status = schan_QueryContextAttributesW(context_handle, attribute, buffer);
1143 if (status == SEC_E_OK)
1145 SecPkgContext_KeyInfoA *info = buffer;
1146 info->sSignatureAlgorithmName = get_alg_name(info->SignatureAlgorithm, FALSE);
1147 info->sEncryptAlgorithmName = get_alg_name(info->EncryptAlgorithm, FALSE);
1149 return status;
1151 case SECPKG_ATTR_REMOTE_CERT_CONTEXT:
1152 return schan_QueryContextAttributesW(context_handle, attribute, buffer);
1153 case SECPKG_ATTR_CONNECTION_INFO:
1154 return schan_QueryContextAttributesW(context_handle, attribute, buffer);
1155 case SECPKG_ATTR_ENDPOINT_BINDINGS:
1156 return schan_QueryContextAttributesW(context_handle, attribute, buffer);
1157 case SECPKG_ATTR_APPLICATION_PROTOCOL:
1158 return schan_QueryContextAttributesW(context_handle, attribute, buffer);
1160 default:
1161 FIXME("Unhandled attribute %#x\n", attribute);
1162 return SEC_E_UNSUPPORTED_FUNCTION;
1166 static int schan_encrypt_message_get_next_buffer(const struct schan_transport *t, struct schan_buffers *s)
1168 SecBuffer *b;
1170 if (s->current_buffer_idx == -1)
1171 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_STREAM_HEADER);
1173 b = &s->desc->pBuffers[s->current_buffer_idx];
1175 if (b->BufferType == SECBUFFER_STREAM_HEADER)
1176 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_DATA);
1178 if (b->BufferType == SECBUFFER_DATA)
1179 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_STREAM_TRAILER);
1181 return -1;
1184 static int schan_encrypt_message_get_next_buffer_token(const struct schan_transport *t, struct schan_buffers *s)
1186 SecBuffer *b;
1188 if (s->current_buffer_idx == -1)
1189 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
1191 b = &s->desc->pBuffers[s->current_buffer_idx];
1193 if (b->BufferType == SECBUFFER_TOKEN)
1195 int idx = schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
1196 if (idx != s->current_buffer_idx) return -1;
1197 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_DATA);
1200 if (b->BufferType == SECBUFFER_DATA)
1202 int idx = schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
1203 if (idx != -1)
1204 idx = schan_find_sec_buffer_idx(s->desc, idx + 1, SECBUFFER_TOKEN);
1205 return idx;
1208 return -1;
1211 static SECURITY_STATUS SEC_ENTRY schan_EncryptMessage(PCtxtHandle context_handle,
1212 ULONG quality, PSecBufferDesc message, ULONG message_seq_no)
1214 struct schan_context *ctx;
1215 struct schan_buffers *b;
1216 SECURITY_STATUS status;
1217 SecBuffer *buffer;
1218 SIZE_T data_size;
1219 SIZE_T length;
1220 char *data;
1221 int idx;
1223 TRACE("context_handle %p, quality %d, message %p, message_seq_no %d\n",
1224 context_handle, quality, message, message_seq_no);
1226 if (!context_handle) return SEC_E_INVALID_HANDLE;
1227 ctx = schan_get_object(context_handle->dwLower, SCHAN_HANDLE_CTX);
1229 dump_buffer_desc(message);
1231 idx = schan_find_sec_buffer_idx(message, 0, SECBUFFER_DATA);
1232 if (idx == -1)
1234 WARN("No data buffer passed\n");
1235 return SEC_E_INTERNAL_ERROR;
1237 buffer = &message->pBuffers[idx];
1239 data_size = buffer->cbBuffer;
1240 data = heap_alloc(data_size);
1241 memcpy(data, buffer->pvBuffer, data_size);
1243 if (schan_find_sec_buffer_idx(message, 0, SECBUFFER_STREAM_HEADER) != -1)
1244 init_schan_buffers(&ctx->transport.out, message, schan_encrypt_message_get_next_buffer);
1245 else
1246 init_schan_buffers(&ctx->transport.out, message, schan_encrypt_message_get_next_buffer_token);
1248 length = data_size;
1249 status = schan_imp_send(ctx->session, data, &length);
1251 TRACE("Sent %ld bytes.\n", length);
1253 if (length != data_size)
1254 status = SEC_E_INTERNAL_ERROR;
1256 b = &ctx->transport.out;
1257 b->desc->pBuffers[b->current_buffer_idx].cbBuffer = b->offset;
1258 heap_free(data);
1260 TRACE("Returning %#x.\n", status);
1262 return status;
1265 static int schan_decrypt_message_get_next_buffer(const struct schan_transport *t, struct schan_buffers *s)
1267 if (s->current_buffer_idx == -1)
1268 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_DATA);
1270 return -1;
1273 static int schan_validate_decrypt_buffer_desc(PSecBufferDesc message)
1275 int data_idx = -1;
1276 unsigned int empty_count = 0;
1277 unsigned int i;
1279 if (message->cBuffers < 4)
1281 WARN("Less than four buffers passed\n");
1282 return -1;
1285 for (i = 0; i < message->cBuffers; ++i)
1287 SecBuffer *b = &message->pBuffers[i];
1288 if (b->BufferType == SECBUFFER_DATA)
1290 if (data_idx != -1)
1292 WARN("More than one data buffer passed\n");
1293 return -1;
1295 data_idx = i;
1297 else if (b->BufferType == SECBUFFER_EMPTY)
1298 ++empty_count;
1301 if (data_idx == -1)
1303 WARN("No data buffer passed\n");
1304 return -1;
1307 if (empty_count < 3)
1309 WARN("Less than three empty buffers passed\n");
1310 return -1;
1313 return data_idx;
1316 static void schan_decrypt_fill_buffer(PSecBufferDesc message, ULONG buffer_type, void *data, ULONG size)
1318 int idx;
1319 SecBuffer *buffer;
1321 idx = schan_find_sec_buffer_idx(message, 0, SECBUFFER_EMPTY);
1322 buffer = &message->pBuffers[idx];
1324 buffer->BufferType = buffer_type;
1325 buffer->pvBuffer = data;
1326 buffer->cbBuffer = size;
1329 static SECURITY_STATUS SEC_ENTRY schan_DecryptMessage(PCtxtHandle context_handle,
1330 PSecBufferDesc message, ULONG message_seq_no, PULONG quality)
1332 struct schan_context *ctx;
1333 SecBuffer *buffer;
1334 SIZE_T data_size;
1335 char *data;
1336 unsigned expected_size;
1337 SSIZE_T received = 0;
1338 int idx;
1339 unsigned char *buf_ptr;
1341 TRACE("context_handle %p, message %p, message_seq_no %d, quality %p\n",
1342 context_handle, message, message_seq_no, quality);
1344 if (!context_handle) return SEC_E_INVALID_HANDLE;
1345 ctx = schan_get_object(context_handle->dwLower, SCHAN_HANDLE_CTX);
1347 dump_buffer_desc(message);
1349 idx = schan_validate_decrypt_buffer_desc(message);
1350 if (idx == -1)
1351 return SEC_E_INVALID_TOKEN;
1352 buffer = &message->pBuffers[idx];
1353 buf_ptr = buffer->pvBuffer;
1355 expected_size = 5 + ((buf_ptr[3] << 8) | buf_ptr[4]);
1356 if(buffer->cbBuffer < expected_size)
1358 TRACE("Expected %u bytes, but buffer only contains %u bytes\n", expected_size, buffer->cbBuffer);
1359 buffer->BufferType = SECBUFFER_MISSING;
1360 buffer->cbBuffer = expected_size - buffer->cbBuffer;
1362 /* This is a bit weird, but windows does it too */
1363 idx = schan_find_sec_buffer_idx(message, 0, SECBUFFER_EMPTY);
1364 buffer = &message->pBuffers[idx];
1365 buffer->BufferType = SECBUFFER_MISSING;
1366 buffer->cbBuffer = expected_size - buffer->cbBuffer;
1368 TRACE("Returning SEC_E_INCOMPLETE_MESSAGE\n");
1369 return SEC_E_INCOMPLETE_MESSAGE;
1372 data_size = expected_size - 5;
1373 data = heap_alloc(data_size);
1375 init_schan_buffers(&ctx->transport.in, message, schan_decrypt_message_get_next_buffer);
1376 ctx->transport.in.limit = expected_size;
1378 while (received < data_size)
1380 SIZE_T length = data_size - received;
1381 SECURITY_STATUS status = schan_imp_recv(ctx->session, data + received, &length);
1383 if (status == SEC_I_CONTINUE_NEEDED)
1384 break;
1386 if (status != SEC_E_OK)
1388 heap_free(data);
1389 ERR("Returning %x\n", status);
1390 return status;
1393 if (!length)
1394 break;
1396 received += length;
1399 TRACE("Received %ld bytes\n", received);
1401 memcpy(buf_ptr + 5, data, received);
1402 heap_free(data);
1404 schan_decrypt_fill_buffer(message, SECBUFFER_DATA,
1405 buf_ptr + 5, received);
1407 schan_decrypt_fill_buffer(message, SECBUFFER_STREAM_TRAILER,
1408 buf_ptr + 5 + received, buffer->cbBuffer - 5 - received);
1410 if(buffer->cbBuffer > expected_size)
1411 schan_decrypt_fill_buffer(message, SECBUFFER_EXTRA,
1412 buf_ptr + expected_size, buffer->cbBuffer - expected_size);
1414 buffer->BufferType = SECBUFFER_STREAM_HEADER;
1415 buffer->cbBuffer = 5;
1417 return SEC_E_OK;
1420 static SECURITY_STATUS SEC_ENTRY schan_DeleteSecurityContext(PCtxtHandle context_handle)
1422 struct schan_context *ctx;
1424 TRACE("context_handle %p\n", context_handle);
1426 if (!context_handle) return SEC_E_INVALID_HANDLE;
1428 ctx = schan_free_handle(context_handle->dwLower, SCHAN_HANDLE_CTX);
1429 if (!ctx) return SEC_E_INVALID_HANDLE;
1431 if (ctx->cert)
1432 CertFreeCertificateContext(ctx->cert);
1433 schan_imp_dispose_session(ctx->session);
1434 heap_free(ctx);
1436 return SEC_E_OK;
1439 static const SecurityFunctionTableA schanTableA = {
1441 NULL, /* EnumerateSecurityPackagesA */
1442 schan_QueryCredentialsAttributesA,
1443 schan_AcquireCredentialsHandleA,
1444 schan_FreeCredentialsHandle,
1445 NULL, /* Reserved2 */
1446 schan_InitializeSecurityContextA,
1447 NULL, /* AcceptSecurityContext */
1448 NULL, /* CompleteAuthToken */
1449 schan_DeleteSecurityContext,
1450 NULL, /* ApplyControlToken */
1451 schan_QueryContextAttributesA,
1452 NULL, /* ImpersonateSecurityContext */
1453 NULL, /* RevertSecurityContext */
1454 NULL, /* MakeSignature */
1455 NULL, /* VerifySignature */
1456 FreeContextBuffer,
1457 NULL, /* QuerySecurityPackageInfoA */
1458 NULL, /* Reserved3 */
1459 NULL, /* Reserved4 */
1460 NULL, /* ExportSecurityContext */
1461 NULL, /* ImportSecurityContextA */
1462 NULL, /* AddCredentialsA */
1463 NULL, /* Reserved8 */
1464 NULL, /* QuerySecurityContextToken */
1465 schan_EncryptMessage,
1466 schan_DecryptMessage,
1467 NULL, /* SetContextAttributesA */
1470 static const SecurityFunctionTableW schanTableW = {
1472 NULL, /* EnumerateSecurityPackagesW */
1473 schan_QueryCredentialsAttributesW,
1474 schan_AcquireCredentialsHandleW,
1475 schan_FreeCredentialsHandle,
1476 NULL, /* Reserved2 */
1477 schan_InitializeSecurityContextW,
1478 NULL, /* AcceptSecurityContext */
1479 NULL, /* CompleteAuthToken */
1480 schan_DeleteSecurityContext,
1481 NULL, /* ApplyControlToken */
1482 schan_QueryContextAttributesW,
1483 NULL, /* ImpersonateSecurityContext */
1484 NULL, /* RevertSecurityContext */
1485 NULL, /* MakeSignature */
1486 NULL, /* VerifySignature */
1487 FreeContextBuffer,
1488 NULL, /* QuerySecurityPackageInfoW */
1489 NULL, /* Reserved3 */
1490 NULL, /* Reserved4 */
1491 NULL, /* ExportSecurityContext */
1492 NULL, /* ImportSecurityContextW */
1493 NULL, /* AddCredentialsW */
1494 NULL, /* Reserved8 */
1495 NULL, /* QuerySecurityContextToken */
1496 schan_EncryptMessage,
1497 schan_DecryptMessage,
1498 NULL, /* SetContextAttributesW */
1501 static const WCHAR schannelComment[] = { 'S','c','h','a','n','n','e','l',' ',
1502 'S','e','c','u','r','i','t','y',' ','P','a','c','k','a','g','e',0 };
1503 static const WCHAR schannelDllName[] = { 's','c','h','a','n','n','e','l','.','d','l','l',0 };
1505 void SECUR32_initSchannelSP(void)
1507 /* This is what Windows reports. This shouldn't break any applications
1508 * even though the functions are missing, because the wrapper will
1509 * return SEC_E_UNSUPPORTED_FUNCTION if our function is NULL.
1511 static const LONG caps =
1512 SECPKG_FLAG_INTEGRITY |
1513 SECPKG_FLAG_PRIVACY |
1514 SECPKG_FLAG_CONNECTION |
1515 SECPKG_FLAG_MULTI_REQUIRED |
1516 SECPKG_FLAG_EXTENDED_ERROR |
1517 SECPKG_FLAG_IMPERSONATION |
1518 SECPKG_FLAG_ACCEPT_WIN32_NAME |
1519 SECPKG_FLAG_STREAM;
1520 static const short version = 1;
1521 static const LONG maxToken = 16384;
1522 SEC_WCHAR *uniSPName = (SEC_WCHAR *)UNISP_NAME_W,
1523 *schannel = (SEC_WCHAR *)SCHANNEL_NAME_W;
1524 const SecPkgInfoW info[] = {
1525 { caps, version, UNISP_RPC_ID, maxToken, uniSPName, uniSPName },
1526 { caps, version, UNISP_RPC_ID, maxToken, schannel,
1527 (SEC_WCHAR *)schannelComment },
1529 SecureProvider *provider;
1531 if (!schan_imp_init())
1532 return;
1534 schan_handle_table = heap_alloc(64 * sizeof(*schan_handle_table));
1535 if (!schan_handle_table)
1537 ERR("Failed to allocate schannel handle table.\n");
1538 goto fail;
1540 schan_handle_table_size = 64;
1542 provider = SECUR32_addProvider(&schanTableA, &schanTableW, schannelDllName);
1543 if (!provider)
1545 ERR("Failed to add schannel provider.\n");
1546 goto fail;
1549 SECUR32_addPackages(provider, ARRAY_SIZE(info), NULL, info);
1551 return;
1553 fail:
1554 heap_free(schan_handle_table);
1555 schan_handle_table = NULL;
1556 schan_imp_deinit();
1557 return;
1560 void SECUR32_deinitSchannelSP(void)
1562 SIZE_T i = schan_handle_count;
1564 if (!schan_handle_table) return;
1566 /* deinitialized sessions first because a pointer to the credentials
1567 * may be stored for the session. */
1568 while (i--)
1570 if (schan_handle_table[i].type == SCHAN_HANDLE_CTX)
1572 struct schan_context *ctx = schan_free_handle(i, SCHAN_HANDLE_CTX);
1573 schan_imp_dispose_session(ctx->session);
1574 heap_free(ctx);
1577 i = schan_handle_count;
1578 while (i--)
1580 if (schan_handle_table[i].type != SCHAN_HANDLE_FREE)
1582 struct schan_credentials *cred;
1583 cred = schan_free_handle(i, SCHAN_HANDLE_CRED);
1584 schan_imp_free_certificate_credentials(cred);
1585 heap_free(cred);
1588 heap_free(schan_handle_table);
1589 schan_imp_deinit();
1592 #else /* SONAME_LIBGNUTLS || HAVE_SECURITY_SECURITY_H */
1594 void SECUR32_initSchannelSP(void)
1596 ERR("TLS library not found, SSL connections will fail\n");
1599 void SECUR32_deinitSchannelSP(void) {}
1601 #endif /* SONAME_LIBGNUTLS || HAVE_SECURITY_SECURITY_H */