configure: Allow specifying custom CFLAGS for LDAP.
[wine.git] / dlls / secur32 / schannel.c
blob82374efd55ce9328668f7bdc4ccbf0d16c4a047a
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 ULONG req_ctx_attr;
61 const CERT_CONTEXT *cert;
64 static struct schan_handle *schan_handle_table;
65 static struct schan_handle *schan_free_handles;
66 static SIZE_T schan_handle_table_size;
67 static SIZE_T schan_handle_count;
69 /* Protocols enabled, only those may be used for the connection. */
70 static DWORD config_enabled_protocols;
72 /* Protocols disabled by default. They are enabled for using, but disabled when caller asks for default settings. */
73 static DWORD config_default_disabled_protocols;
75 static ULONG_PTR schan_alloc_handle(void *object, enum schan_handle_type type)
77 struct schan_handle *handle;
79 if (schan_free_handles)
81 DWORD index = schan_free_handles - schan_handle_table;
82 /* Use a free handle */
83 handle = schan_free_handles;
84 if (handle->type != SCHAN_HANDLE_FREE)
86 ERR("Handle %d(%p) is in the free list, but has type %#x.\n", index, handle, handle->type);
87 return SCHAN_INVALID_HANDLE;
89 schan_free_handles = handle->object;
90 handle->object = object;
91 handle->type = type;
93 return index;
95 if (!(schan_handle_count < schan_handle_table_size))
97 /* Grow the table */
98 SIZE_T new_size = schan_handle_table_size + (schan_handle_table_size >> 1);
99 struct schan_handle *new_table = HeapReAlloc(GetProcessHeap(), 0, schan_handle_table, new_size * sizeof(*schan_handle_table));
100 if (!new_table)
102 ERR("Failed to grow the handle table\n");
103 return SCHAN_INVALID_HANDLE;
105 schan_handle_table = new_table;
106 schan_handle_table_size = new_size;
109 handle = &schan_handle_table[schan_handle_count++];
110 handle->object = object;
111 handle->type = type;
113 return handle - schan_handle_table;
116 static void *schan_free_handle(ULONG_PTR handle_idx, enum schan_handle_type type)
118 struct schan_handle *handle;
119 void *object;
121 if (handle_idx == SCHAN_INVALID_HANDLE) return NULL;
122 if (handle_idx >= schan_handle_count) return NULL;
123 handle = &schan_handle_table[handle_idx];
124 if (handle->type != type)
126 ERR("Handle %ld(%p) is not of type %#x\n", handle_idx, handle, type);
127 return NULL;
130 object = handle->object;
131 handle->object = schan_free_handles;
132 handle->type = SCHAN_HANDLE_FREE;
133 schan_free_handles = handle;
135 return object;
138 static void *schan_get_object(ULONG_PTR handle_idx, enum schan_handle_type type)
140 struct schan_handle *handle;
142 if (handle_idx == SCHAN_INVALID_HANDLE) return NULL;
143 if (handle_idx >= schan_handle_count) return NULL;
144 handle = &schan_handle_table[handle_idx];
145 if (handle->type != type)
147 ERR("Handle %ld(%p) is not of type %#x\n", handle_idx, handle, type);
148 return NULL;
151 return handle->object;
154 static void read_config(void)
156 DWORD enabled = 0, default_disabled = 0;
157 HKEY protocols_key, key;
158 WCHAR subkey_name[64];
159 unsigned i;
160 DWORD res;
162 static BOOL config_read = FALSE;
164 static const WCHAR protocol_config_key_name[] = {
165 'S','Y','S','T','E','M','\\',
166 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
167 'C','o','n','t','r','o','l','\\',
168 'S','e','c','u','r','i','t','y','P','r','o','v','i','d','e','r','s','\\',
169 'S','C','H','A','N','N','E','L','\\',
170 'P','r','o','t','o','c','o','l','s',0 };
172 static const WCHAR clientW[] = {'\\','C','l','i','e','n','t',0};
173 static const WCHAR enabledW[] = {'e','n','a','b','l','e','d',0};
174 static const WCHAR disabledbydefaultW[] = {'D','i','s','a','b','l','e','d','B','y','D','e','f','a','u','l','t',0};
176 static const struct {
177 WCHAR key_name[20];
178 DWORD prot_client_flag;
179 BOOL enabled; /* If no config is present, enable the protocol */
180 BOOL disabled_by_default; /* Disable if caller asks for default protocol set */
181 } protocol_config_keys[] = {
182 {{'S','S','L',' ','2','.','0',0}, SP_PROT_SSL2_CLIENT, FALSE, TRUE}, /* NOTE: TRUE, TRUE on Windows */
183 {{'S','S','L',' ','3','.','0',0}, SP_PROT_SSL3_CLIENT, TRUE, FALSE},
184 {{'T','L','S',' ','1','.','0',0}, SP_PROT_TLS1_0_CLIENT, TRUE, FALSE},
185 {{'T','L','S',' ','1','.','1',0}, SP_PROT_TLS1_1_CLIENT, TRUE, FALSE /* NOTE: not enabled by default on Windows */ },
186 {{'T','L','S',' ','1','.','2',0}, SP_PROT_TLS1_2_CLIENT, TRUE, FALSE /* NOTE: not enabled by default on Windows */ }
189 /* No need for thread safety */
190 if(config_read)
191 return;
193 res = RegOpenKeyExW(HKEY_LOCAL_MACHINE, protocol_config_key_name, 0, KEY_READ, &protocols_key);
194 if(res == ERROR_SUCCESS) {
195 DWORD type, size, value;
197 for(i=0; i < sizeof(protocol_config_keys)/sizeof(*protocol_config_keys); i++) {
198 strcpyW(subkey_name, protocol_config_keys[i].key_name);
199 strcatW(subkey_name, clientW);
200 res = RegOpenKeyExW(protocols_key, subkey_name, 0, KEY_READ, &key);
201 if(res != ERROR_SUCCESS) {
202 if(protocol_config_keys[i].enabled)
203 enabled |= protocol_config_keys[i].prot_client_flag;
204 if(protocol_config_keys[i].disabled_by_default)
205 default_disabled |= protocol_config_keys[i].prot_client_flag;
206 continue;
209 size = sizeof(value);
210 res = RegQueryValueExW(key, enabledW, NULL, &type, (BYTE*)&value, &size);
211 if(res == ERROR_SUCCESS) {
212 if(type == REG_DWORD && value)
213 enabled |= protocol_config_keys[i].prot_client_flag;
214 }else if(protocol_config_keys[i].enabled) {
215 enabled |= protocol_config_keys[i].prot_client_flag;
218 size = sizeof(value);
219 res = RegQueryValueExW(key, disabledbydefaultW, NULL, &type, (BYTE*)&value, &size);
220 if(res == ERROR_SUCCESS) {
221 if(type != REG_DWORD || value)
222 default_disabled |= protocol_config_keys[i].prot_client_flag;
223 }else if(protocol_config_keys[i].disabled_by_default) {
224 default_disabled |= protocol_config_keys[i].prot_client_flag;
227 RegCloseKey(key);
229 }else {
230 /* No config, enable all known protocols. */
231 for(i=0; i < sizeof(protocol_config_keys)/sizeof(*protocol_config_keys); i++) {
232 if(protocol_config_keys[i].enabled)
233 enabled |= protocol_config_keys[i].prot_client_flag;
234 if(protocol_config_keys[i].disabled_by_default)
235 default_disabled |= protocol_config_keys[i].prot_client_flag;
239 RegCloseKey(protocols_key);
241 config_enabled_protocols = enabled & schan_imp_enabled_protocols();
242 config_default_disabled_protocols = default_disabled;
243 config_read = TRUE;
245 TRACE("enabled %x, disabled by default %x\n", config_enabled_protocols, config_default_disabled_protocols);
248 static SECURITY_STATUS schan_QueryCredentialsAttributes(
249 PCredHandle phCredential, ULONG ulAttribute, VOID *pBuffer)
251 struct schan_credentials *cred;
252 SECURITY_STATUS ret;
254 cred = schan_get_object(phCredential->dwLower, SCHAN_HANDLE_CRED);
255 if(!cred)
256 return SEC_E_INVALID_HANDLE;
258 switch (ulAttribute)
260 case SECPKG_ATTR_SUPPORTED_ALGS:
261 if (pBuffer)
263 /* FIXME: get from CryptoAPI */
264 FIXME("SECPKG_ATTR_SUPPORTED_ALGS: stub\n");
265 ret = SEC_E_UNSUPPORTED_FUNCTION;
267 else
268 ret = SEC_E_INTERNAL_ERROR;
269 break;
270 case SECPKG_ATTR_CIPHER_STRENGTHS:
271 if (pBuffer)
273 SecPkgCred_CipherStrengths *r = pBuffer;
275 /* FIXME: get from CryptoAPI */
276 FIXME("SECPKG_ATTR_CIPHER_STRENGTHS: semi-stub\n");
277 r->dwMinimumCipherStrength = 40;
278 r->dwMaximumCipherStrength = 168;
279 ret = SEC_E_OK;
281 else
282 ret = SEC_E_INTERNAL_ERROR;
283 break;
284 case SECPKG_ATTR_SUPPORTED_PROTOCOLS:
285 if(pBuffer) {
286 /* Regardless of MSDN documentation, tests show that this attribute takes into account
287 * what protocols are enabled for given credential. */
288 ((SecPkgCred_SupportedProtocols*)pBuffer)->grbitProtocol = cred->enabled_protocols;
289 ret = SEC_E_OK;
290 }else {
291 ret = SEC_E_INTERNAL_ERROR;
293 break;
294 default:
295 ret = SEC_E_UNSUPPORTED_FUNCTION;
297 return ret;
300 static SECURITY_STATUS SEC_ENTRY schan_QueryCredentialsAttributesA(
301 PCredHandle phCredential, ULONG ulAttribute, PVOID pBuffer)
303 SECURITY_STATUS ret;
305 TRACE("(%p, %d, %p)\n", phCredential, ulAttribute, pBuffer);
307 switch (ulAttribute)
309 case SECPKG_CRED_ATTR_NAMES:
310 FIXME("SECPKG_CRED_ATTR_NAMES: stub\n");
311 ret = SEC_E_UNSUPPORTED_FUNCTION;
312 break;
313 default:
314 ret = schan_QueryCredentialsAttributes(phCredential, ulAttribute,
315 pBuffer);
317 return ret;
320 static SECURITY_STATUS SEC_ENTRY schan_QueryCredentialsAttributesW(
321 PCredHandle phCredential, ULONG ulAttribute, PVOID pBuffer)
323 SECURITY_STATUS ret;
325 TRACE("(%p, %d, %p)\n", phCredential, ulAttribute, pBuffer);
327 switch (ulAttribute)
329 case SECPKG_CRED_ATTR_NAMES:
330 FIXME("SECPKG_CRED_ATTR_NAMES: stub\n");
331 ret = SEC_E_UNSUPPORTED_FUNCTION;
332 break;
333 default:
334 ret = schan_QueryCredentialsAttributes(phCredential, ulAttribute,
335 pBuffer);
337 return ret;
340 static SECURITY_STATUS schan_CheckCreds(const SCHANNEL_CRED *schanCred)
342 SECURITY_STATUS st;
343 DWORD i;
345 TRACE("dwVersion = %d\n", schanCred->dwVersion);
346 TRACE("cCreds = %d\n", schanCred->cCreds);
347 TRACE("hRootStore = %p\n", schanCred->hRootStore);
348 TRACE("cMappers = %d\n", schanCred->cMappers);
349 TRACE("cSupportedAlgs = %d:\n", schanCred->cSupportedAlgs);
350 for (i = 0; i < schanCred->cSupportedAlgs; i++)
351 TRACE("%08x\n", schanCred->palgSupportedAlgs[i]);
352 TRACE("grbitEnabledProtocols = %08x\n", schanCred->grbitEnabledProtocols);
353 TRACE("dwMinimumCipherStrength = %d\n", schanCred->dwMinimumCipherStrength);
354 TRACE("dwMaximumCipherStrength = %d\n", schanCred->dwMaximumCipherStrength);
355 TRACE("dwSessionLifespan = %d\n", schanCred->dwSessionLifespan);
356 TRACE("dwFlags = %08x\n", schanCred->dwFlags);
357 TRACE("dwCredFormat = %d\n", schanCred->dwCredFormat);
359 switch (schanCred->dwVersion)
361 case SCH_CRED_V3:
362 case SCHANNEL_CRED_VERSION:
363 break;
364 default:
365 return SEC_E_INTERNAL_ERROR;
368 if (schanCred->cCreds == 0)
369 st = SEC_E_NO_CREDENTIALS;
370 else if (schanCred->cCreds > 1)
371 st = SEC_E_UNKNOWN_CREDENTIALS;
372 else
374 DWORD keySpec;
375 HCRYPTPROV csp;
376 BOOL ret, freeCSP;
378 ret = CryptAcquireCertificatePrivateKey(schanCred->paCred[0],
379 0, /* FIXME: what flags to use? */ NULL,
380 &csp, &keySpec, &freeCSP);
381 if (ret)
383 st = SEC_E_OK;
384 if (freeCSP)
385 CryptReleaseContext(csp, 0);
387 else
388 st = SEC_E_UNKNOWN_CREDENTIALS;
390 return st;
393 static SECURITY_STATUS schan_AcquireClientCredentials(const SCHANNEL_CRED *schanCred,
394 PCredHandle phCredential, PTimeStamp ptsExpiry)
396 struct schan_credentials *creds;
397 unsigned enabled_protocols;
398 ULONG_PTR handle;
399 SECURITY_STATUS st = SEC_E_OK;
401 TRACE("schanCred %p, phCredential %p, ptsExpiry %p\n", schanCred, phCredential, ptsExpiry);
403 if (schanCred)
405 st = schan_CheckCreds(schanCred);
406 if (st != SEC_E_OK && st != SEC_E_NO_CREDENTIALS)
407 return st;
409 st = SEC_E_OK;
412 read_config();
413 if(schanCred && schanCred->grbitEnabledProtocols)
414 enabled_protocols = schanCred->grbitEnabledProtocols & config_enabled_protocols;
415 else
416 enabled_protocols = config_enabled_protocols & ~config_default_disabled_protocols;
417 if(!enabled_protocols) {
418 ERR("Could not find matching protocol\n");
419 return SEC_E_NO_AUTHENTICATING_AUTHORITY;
422 /* For now, the only thing I'm interested in is the direction of the
423 * connection, so just store it.
425 creds = HeapAlloc(GetProcessHeap(), 0, sizeof(*creds));
426 if (!creds) return SEC_E_INSUFFICIENT_MEMORY;
428 handle = schan_alloc_handle(creds, SCHAN_HANDLE_CRED);
429 if (handle == SCHAN_INVALID_HANDLE) goto fail;
431 creds->credential_use = SECPKG_CRED_OUTBOUND;
432 if (!schan_imp_allocate_certificate_credentials(creds))
434 schan_free_handle(handle, SCHAN_HANDLE_CRED);
435 goto fail;
438 creds->enabled_protocols = enabled_protocols;
439 phCredential->dwLower = handle;
440 phCredential->dwUpper = 0;
442 /* Outbound credentials have no expiry */
443 if (ptsExpiry)
445 ptsExpiry->LowPart = 0;
446 ptsExpiry->HighPart = 0;
449 return st;
451 fail:
452 HeapFree(GetProcessHeap(), 0, creds);
453 return SEC_E_INTERNAL_ERROR;
456 static SECURITY_STATUS schan_AcquireServerCredentials(const SCHANNEL_CRED *schanCred,
457 PCredHandle phCredential, PTimeStamp ptsExpiry)
459 SECURITY_STATUS st;
461 TRACE("schanCred %p, phCredential %p, ptsExpiry %p\n", schanCred, phCredential, ptsExpiry);
463 if (!schanCred) return SEC_E_NO_CREDENTIALS;
465 st = schan_CheckCreds(schanCred);
466 if (st == SEC_E_OK)
468 ULONG_PTR handle;
469 struct schan_credentials *creds;
471 creds = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*creds));
472 if (!creds) return SEC_E_INSUFFICIENT_MEMORY;
473 creds->credential_use = SECPKG_CRED_INBOUND;
475 handle = schan_alloc_handle(creds, SCHAN_HANDLE_CRED);
476 if (handle == SCHAN_INVALID_HANDLE)
478 HeapFree(GetProcessHeap(), 0, creds);
479 return SEC_E_INTERNAL_ERROR;
482 phCredential->dwLower = handle;
483 phCredential->dwUpper = 0;
485 /* FIXME: get expiry from cert */
487 return st;
490 static SECURITY_STATUS schan_AcquireCredentialsHandle(ULONG fCredentialUse,
491 const SCHANNEL_CRED *schanCred, PCredHandle phCredential, PTimeStamp ptsExpiry)
493 SECURITY_STATUS ret;
495 if (fCredentialUse == SECPKG_CRED_OUTBOUND)
496 ret = schan_AcquireClientCredentials(schanCred, phCredential,
497 ptsExpiry);
498 else
499 ret = schan_AcquireServerCredentials(schanCred, phCredential,
500 ptsExpiry);
501 return ret;
504 static SECURITY_STATUS SEC_ENTRY schan_AcquireCredentialsHandleA(
505 SEC_CHAR *pszPrincipal, SEC_CHAR *pszPackage, ULONG fCredentialUse,
506 PLUID pLogonID, PVOID pAuthData, SEC_GET_KEY_FN pGetKeyFn,
507 PVOID pGetKeyArgument, PCredHandle phCredential, PTimeStamp ptsExpiry)
509 TRACE("(%s, %s, 0x%08x, %p, %p, %p, %p, %p, %p)\n",
510 debugstr_a(pszPrincipal), debugstr_a(pszPackage), fCredentialUse,
511 pLogonID, pAuthData, pGetKeyFn, pGetKeyArgument, phCredential, ptsExpiry);
512 return schan_AcquireCredentialsHandle(fCredentialUse,
513 pAuthData, phCredential, ptsExpiry);
516 static SECURITY_STATUS SEC_ENTRY schan_AcquireCredentialsHandleW(
517 SEC_WCHAR *pszPrincipal, SEC_WCHAR *pszPackage, ULONG fCredentialUse,
518 PLUID pLogonID, PVOID pAuthData, SEC_GET_KEY_FN pGetKeyFn,
519 PVOID pGetKeyArgument, PCredHandle phCredential, PTimeStamp ptsExpiry)
521 TRACE("(%s, %s, 0x%08x, %p, %p, %p, %p, %p, %p)\n",
522 debugstr_w(pszPrincipal), debugstr_w(pszPackage), fCredentialUse,
523 pLogonID, pAuthData, pGetKeyFn, pGetKeyArgument, phCredential, ptsExpiry);
524 return schan_AcquireCredentialsHandle(fCredentialUse,
525 pAuthData, phCredential, ptsExpiry);
528 static SECURITY_STATUS SEC_ENTRY schan_FreeCredentialsHandle(
529 PCredHandle phCredential)
531 struct schan_credentials *creds;
533 TRACE("phCredential %p\n", phCredential);
535 if (!phCredential) return SEC_E_INVALID_HANDLE;
537 creds = schan_free_handle(phCredential->dwLower, SCHAN_HANDLE_CRED);
538 if (!creds) return SEC_E_INVALID_HANDLE;
540 if (creds->credential_use == SECPKG_CRED_OUTBOUND)
541 schan_imp_free_certificate_credentials(creds);
542 HeapFree(GetProcessHeap(), 0, creds);
544 return SEC_E_OK;
547 static void init_schan_buffers(struct schan_buffers *s, const PSecBufferDesc desc,
548 int (*get_next_buffer)(const struct schan_transport *, struct schan_buffers *))
550 s->offset = 0;
551 s->limit = ~0UL;
552 s->desc = desc;
553 s->current_buffer_idx = -1;
554 s->allow_buffer_resize = FALSE;
555 s->get_next_buffer = get_next_buffer;
558 static int schan_find_sec_buffer_idx(const SecBufferDesc *desc, unsigned int start_idx, ULONG buffer_type)
560 unsigned int i;
561 PSecBuffer buffer;
563 for (i = start_idx; i < desc->cBuffers; ++i)
565 buffer = &desc->pBuffers[i];
566 if (buffer->BufferType == buffer_type) return i;
569 return -1;
572 static void schan_resize_current_buffer(const struct schan_buffers *s, SIZE_T min_size)
574 SecBuffer *b = &s->desc->pBuffers[s->current_buffer_idx];
575 SIZE_T new_size = b->cbBuffer ? b->cbBuffer * 2 : 128;
576 void *new_data;
578 if (b->cbBuffer >= min_size || !s->allow_buffer_resize || min_size > UINT_MAX / 2) return;
580 while (new_size < min_size) new_size *= 2;
582 if (b->pvBuffer)
583 new_data = HeapReAlloc(GetProcessHeap(), 0, b->pvBuffer, new_size);
584 else
585 new_data = HeapAlloc(GetProcessHeap(), 0, new_size);
587 if (!new_data)
589 TRACE("Failed to resize %p from %d to %ld\n", b->pvBuffer, b->cbBuffer, new_size);
590 return;
593 b->cbBuffer = new_size;
594 b->pvBuffer = new_data;
597 char *schan_get_buffer(const struct schan_transport *t, struct schan_buffers *s, SIZE_T *count)
599 SIZE_T max_count;
600 PSecBuffer buffer;
602 if (!s->desc)
604 TRACE("No desc\n");
605 return NULL;
608 if (s->current_buffer_idx == -1)
610 /* Initial buffer */
611 int buffer_idx = s->get_next_buffer(t, s);
612 if (buffer_idx == -1)
614 TRACE("No next buffer\n");
615 return NULL;
617 s->current_buffer_idx = buffer_idx;
620 buffer = &s->desc->pBuffers[s->current_buffer_idx];
621 TRACE("Using buffer %d: cbBuffer %d, BufferType %#x, pvBuffer %p\n", s->current_buffer_idx, buffer->cbBuffer, buffer->BufferType, buffer->pvBuffer);
623 schan_resize_current_buffer(s, s->offset + *count);
624 max_count = buffer->cbBuffer - s->offset;
625 if (s->limit != ~0UL && s->limit < max_count)
626 max_count = s->limit;
627 if (!max_count)
629 int buffer_idx;
631 s->allow_buffer_resize = FALSE;
632 buffer_idx = s->get_next_buffer(t, s);
633 if (buffer_idx == -1)
635 TRACE("No next buffer\n");
636 return NULL;
638 s->current_buffer_idx = buffer_idx;
639 s->offset = 0;
640 return schan_get_buffer(t, s, count);
643 if (*count > max_count)
644 *count = max_count;
645 if (s->limit != ~0UL)
646 s->limit -= *count;
648 return (char *)buffer->pvBuffer + s->offset;
651 /* schan_pull
652 * Read data from the transport input buffer.
654 * t - The session transport object.
655 * buff - The buffer into which to store the read data. Must be at least
656 * *buff_len bytes in length.
657 * buff_len - On input, *buff_len is the desired length to read. On successful
658 * return, *buff_len is the number of bytes actually read.
660 * Returns:
661 * 0 on success, in which case:
662 * *buff_len == 0 indicates end of file.
663 * *buff_len > 0 indicates that some data was read. May be less than
664 * what was requested, in which case the caller should call again if/
665 * when they want more.
666 * EAGAIN when no data could be read without blocking
667 * another errno-style error value on failure
670 int schan_pull(struct schan_transport *t, void *buff, size_t *buff_len)
672 char *b;
673 SIZE_T local_len = *buff_len;
675 TRACE("Pull %lu bytes\n", local_len);
677 *buff_len = 0;
679 b = schan_get_buffer(t, &t->in, &local_len);
680 if (!b)
681 return EAGAIN;
683 memcpy(buff, b, local_len);
684 t->in.offset += local_len;
686 TRACE("Read %lu bytes\n", local_len);
688 *buff_len = local_len;
689 return 0;
692 /* schan_push
693 * Write data to the transport output buffer.
695 * t - The session transport object.
696 * buff - The buffer of data to write. Must be at least *buff_len bytes in length.
697 * buff_len - On input, *buff_len is the desired length to write. On successful
698 * return, *buff_len is the number of bytes actually written.
700 * Returns:
701 * 0 on success
702 * *buff_len will be > 0 indicating how much data was written. May be less
703 * than what was requested, in which case the caller should call again
704 if/when they want to write more.
705 * EAGAIN when no data could be written without blocking
706 * another errno-style error value on failure
709 int schan_push(struct schan_transport *t, const void *buff, size_t *buff_len)
711 char *b;
712 SIZE_T local_len = *buff_len;
714 TRACE("Push %lu bytes\n", local_len);
716 *buff_len = 0;
718 b = schan_get_buffer(t, &t->out, &local_len);
719 if (!b)
720 return EAGAIN;
722 memcpy(b, buff, local_len);
723 t->out.offset += local_len;
725 TRACE("Wrote %lu bytes\n", local_len);
727 *buff_len = local_len;
728 return 0;
731 schan_imp_session schan_session_for_transport(struct schan_transport* t)
733 return t->ctx->session;
736 static int schan_init_sec_ctx_get_next_input_buffer(const struct schan_transport *t, struct schan_buffers *s)
738 if (s->current_buffer_idx != -1)
739 return -1;
740 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
743 static int schan_init_sec_ctx_get_next_output_buffer(const struct schan_transport *t, struct schan_buffers *s)
745 if (s->current_buffer_idx == -1)
747 int idx = schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
748 if (t->ctx->req_ctx_attr & ISC_REQ_ALLOCATE_MEMORY)
750 if (idx == -1)
752 idx = schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_EMPTY);
753 if (idx != -1) s->desc->pBuffers[idx].BufferType = SECBUFFER_TOKEN;
755 if (idx != -1 && !s->desc->pBuffers[idx].pvBuffer)
757 s->desc->pBuffers[idx].cbBuffer = 0;
758 s->allow_buffer_resize = TRUE;
761 return idx;
764 return -1;
767 static void dump_buffer_desc(SecBufferDesc *desc)
769 unsigned int i;
771 if (!desc) return;
772 TRACE("Buffer desc %p:\n", desc);
773 for (i = 0; i < desc->cBuffers; ++i)
775 SecBuffer *b = &desc->pBuffers[i];
776 TRACE("\tbuffer %u: cbBuffer %d, BufferType %#x pvBuffer %p\n", i, b->cbBuffer, b->BufferType, b->pvBuffer);
780 /***********************************************************************
781 * InitializeSecurityContextW
783 static SECURITY_STATUS SEC_ENTRY schan_InitializeSecurityContextW(
784 PCredHandle phCredential, PCtxtHandle phContext, SEC_WCHAR *pszTargetName,
785 ULONG fContextReq, ULONG Reserved1, ULONG TargetDataRep,
786 PSecBufferDesc pInput, ULONG Reserved2, PCtxtHandle phNewContext,
787 PSecBufferDesc pOutput, ULONG *pfContextAttr, PTimeStamp ptsExpiry)
789 struct schan_context *ctx;
790 struct schan_buffers *out_buffers;
791 struct schan_credentials *cred;
792 struct schan_transport transport;
793 SIZE_T expected_size = ~0UL;
794 SECURITY_STATUS ret;
796 TRACE("%p %p %s 0x%08x %d %d %p %d %p %p %p %p\n", phCredential, phContext,
797 debugstr_w(pszTargetName), fContextReq, Reserved1, TargetDataRep, pInput,
798 Reserved1, phNewContext, pOutput, pfContextAttr, ptsExpiry);
800 dump_buffer_desc(pInput);
801 dump_buffer_desc(pOutput);
803 if (!phContext)
805 ULONG_PTR handle;
807 if (!phCredential) return SEC_E_INVALID_HANDLE;
809 cred = schan_get_object(phCredential->dwLower, SCHAN_HANDLE_CRED);
810 if (!cred) return SEC_E_INVALID_HANDLE;
812 if (!(cred->credential_use & SECPKG_CRED_OUTBOUND))
814 WARN("Invalid credential use %#x\n", cred->credential_use);
815 return SEC_E_INVALID_HANDLE;
818 ctx = HeapAlloc(GetProcessHeap(), 0, sizeof(*ctx));
819 if (!ctx) return SEC_E_INSUFFICIENT_MEMORY;
821 ctx->cert = NULL;
822 handle = schan_alloc_handle(ctx, SCHAN_HANDLE_CTX);
823 if (handle == SCHAN_INVALID_HANDLE)
825 HeapFree(GetProcessHeap(), 0, ctx);
826 return SEC_E_INTERNAL_ERROR;
829 if (!schan_imp_create_session(&ctx->session, cred))
831 schan_free_handle(handle, SCHAN_HANDLE_CTX);
832 HeapFree(GetProcessHeap(), 0, ctx);
833 return SEC_E_INTERNAL_ERROR;
836 if (pszTargetName && *pszTargetName)
838 UINT len = WideCharToMultiByte( CP_UNIXCP, 0, pszTargetName, -1, NULL, 0, NULL, NULL );
839 char *target = HeapAlloc( GetProcessHeap(), 0, len );
841 if (target)
843 WideCharToMultiByte( CP_UNIXCP, 0, pszTargetName, -1, target, len, NULL, NULL );
844 schan_imp_set_session_target( ctx->session, target );
845 HeapFree( GetProcessHeap(), 0, target );
848 phNewContext->dwLower = handle;
849 phNewContext->dwUpper = 0;
851 else
853 SIZE_T record_size = 0;
854 unsigned char *ptr;
855 SecBuffer *buffer;
856 int idx;
858 if (!pInput)
859 return SEC_E_INCOMPLETE_MESSAGE;
861 idx = schan_find_sec_buffer_idx(pInput, 0, SECBUFFER_TOKEN);
862 if (idx == -1)
863 return SEC_E_INCOMPLETE_MESSAGE;
865 buffer = &pInput->pBuffers[idx];
866 ptr = buffer->pvBuffer;
867 expected_size = 0;
869 while (buffer->cbBuffer > expected_size + 5)
871 record_size = 5 + ((ptr[3] << 8) | ptr[4]);
873 if (buffer->cbBuffer < expected_size + record_size)
874 break;
876 expected_size += record_size;
877 ptr += record_size;
880 if (!expected_size)
882 TRACE("Expected at least %lu bytes, but buffer only contains %u bytes.\n",
883 max(6, record_size), buffer->cbBuffer);
884 return SEC_E_INCOMPLETE_MESSAGE;
887 TRACE("Using expected_size %lu.\n", expected_size);
889 ctx = schan_get_object(phContext->dwLower, SCHAN_HANDLE_CTX);
892 ctx->req_ctx_attr = fContextReq;
894 transport.ctx = ctx;
895 init_schan_buffers(&transport.in, pInput, schan_init_sec_ctx_get_next_input_buffer);
896 transport.in.limit = expected_size;
897 init_schan_buffers(&transport.out, pOutput, schan_init_sec_ctx_get_next_output_buffer);
898 schan_imp_set_session_transport(ctx->session, &transport);
900 /* Perform the TLS handshake */
901 ret = schan_imp_handshake(ctx->session);
903 if(transport.in.offset && transport.in.offset != pInput->pBuffers[0].cbBuffer) {
904 if(pInput->cBuffers<2 || pInput->pBuffers[1].BufferType!=SECBUFFER_EMPTY)
905 return SEC_E_INVALID_TOKEN;
907 pInput->pBuffers[1].BufferType = SECBUFFER_EXTRA;
908 pInput->pBuffers[1].cbBuffer = pInput->pBuffers[0].cbBuffer-transport.in.offset;
911 out_buffers = &transport.out;
912 if (out_buffers->current_buffer_idx != -1)
914 SecBuffer *buffer = &out_buffers->desc->pBuffers[out_buffers->current_buffer_idx];
915 buffer->cbBuffer = out_buffers->offset;
918 *pfContextAttr = 0;
919 if (ctx->req_ctx_attr & ISC_REQ_REPLAY_DETECT)
920 *pfContextAttr |= ISC_RET_REPLAY_DETECT;
921 if (ctx->req_ctx_attr & ISC_REQ_SEQUENCE_DETECT)
922 *pfContextAttr |= ISC_RET_SEQUENCE_DETECT;
923 if (ctx->req_ctx_attr & ISC_REQ_CONFIDENTIALITY)
924 *pfContextAttr |= ISC_RET_CONFIDENTIALITY;
925 if (ctx->req_ctx_attr & ISC_REQ_ALLOCATE_MEMORY)
926 *pfContextAttr |= ISC_RET_ALLOCATED_MEMORY;
927 if (ctx->req_ctx_attr & ISC_REQ_STREAM)
928 *pfContextAttr |= ISC_RET_STREAM;
930 return ret;
933 /***********************************************************************
934 * InitializeSecurityContextA
936 static SECURITY_STATUS SEC_ENTRY schan_InitializeSecurityContextA(
937 PCredHandle phCredential, PCtxtHandle phContext, SEC_CHAR *pszTargetName,
938 ULONG fContextReq, ULONG Reserved1, ULONG TargetDataRep,
939 PSecBufferDesc pInput, ULONG Reserved2, PCtxtHandle phNewContext,
940 PSecBufferDesc pOutput, ULONG *pfContextAttr, PTimeStamp ptsExpiry)
942 SECURITY_STATUS ret;
943 SEC_WCHAR *target_name = NULL;
945 TRACE("%p %p %s %d %d %d %p %d %p %p %p %p\n", phCredential, phContext,
946 debugstr_a(pszTargetName), fContextReq, Reserved1, TargetDataRep, pInput,
947 Reserved1, phNewContext, pOutput, pfContextAttr, ptsExpiry);
949 if (pszTargetName)
951 INT len = MultiByteToWideChar(CP_ACP, 0, pszTargetName, -1, NULL, 0);
952 target_name = HeapAlloc(GetProcessHeap(), 0, len * sizeof(*target_name));
953 MultiByteToWideChar(CP_ACP, 0, pszTargetName, -1, target_name, len);
956 ret = schan_InitializeSecurityContextW(phCredential, phContext, target_name,
957 fContextReq, Reserved1, TargetDataRep, pInput, Reserved2,
958 phNewContext, pOutput, pfContextAttr, ptsExpiry);
960 HeapFree(GetProcessHeap(), 0, 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 < sizeof(alg_name_map)/sizeof(alg_name_map[0]); 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;
1014 TRACE("context_handle %p, attribute %#x, buffer %p\n",
1015 context_handle, attribute, buffer);
1017 if (!context_handle) return SEC_E_INVALID_HANDLE;
1018 ctx = schan_get_object(context_handle->dwLower, SCHAN_HANDLE_CTX);
1020 switch(attribute)
1022 case SECPKG_ATTR_STREAM_SIZES:
1024 SecPkgContext_ConnectionInfo info;
1025 SECURITY_STATUS status = schan_imp_get_connection_info(ctx->session, &info);
1026 if (status == SEC_E_OK)
1028 SecPkgContext_StreamSizes *stream_sizes = buffer;
1029 SIZE_T mac_size = info.dwHashStrength;
1030 unsigned int block_size = schan_imp_get_session_cipher_block_size(ctx->session);
1031 unsigned int message_size = schan_imp_get_max_message_size(ctx->session);
1033 TRACE("Using %lu mac bytes, message size %u, block size %u\n",
1034 mac_size, message_size, block_size);
1036 /* These are defined by the TLS RFC */
1037 stream_sizes->cbHeader = 5;
1038 stream_sizes->cbTrailer = mac_size + 256; /* Max 255 bytes padding + 1 for padding size */
1039 stream_sizes->cbMaximumMessage = message_size;
1040 stream_sizes->cbBuffers = 4;
1041 stream_sizes->cbBlockSize = block_size;
1044 return status;
1046 case SECPKG_ATTR_KEY_INFO:
1048 SecPkgContext_ConnectionInfo conn_info;
1049 SECURITY_STATUS status = schan_imp_get_connection_info(ctx->session, &conn_info);
1050 if (status == SEC_E_OK)
1052 SecPkgContext_KeyInfoW *info = buffer;
1053 info->KeySize = conn_info.dwCipherStrength;
1054 info->SignatureAlgorithm = schan_imp_get_key_signature_algorithm(ctx->session);
1055 info->EncryptAlgorithm = conn_info.aiCipher;
1056 info->sSignatureAlgorithmName = get_alg_name(info->SignatureAlgorithm, TRUE);
1057 info->sEncryptAlgorithmName = get_alg_name(info->EncryptAlgorithm, TRUE);
1059 return status;
1061 case SECPKG_ATTR_REMOTE_CERT_CONTEXT:
1063 PCCERT_CONTEXT *cert = buffer;
1064 SECURITY_STATUS status;
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 SECURITY_STATUS status;
1086 char *p;
1087 BOOL r;
1089 static const char prefix[] = "tls-server-end-point:";
1091 status = ensure_remote_cert(ctx);
1092 if(status != SEC_E_OK)
1093 return status;
1095 /* RFC 5929 */
1096 info = CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY, ctx->cert->pCertInfo->SignatureAlgorithm.pszObjId, 0);
1097 if(info && info->u.Algid != CALG_SHA1 && info->u.Algid != CALG_MD5)
1098 hash_alg = info->u.Algid;
1100 hash_size = sizeof(hash);
1101 r = CryptHashCertificate(0, hash_alg, 0, ctx->cert->pbCertEncoded, ctx->cert->cbCertEncoded, hash, &hash_size);
1102 if(!r)
1103 return GetLastError();
1105 bindings->BindingsLength = sizeof(*bindings->Bindings) + sizeof(prefix)-1 + hash_size;
1106 bindings->Bindings = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, bindings->BindingsLength);
1107 if(!bindings->Bindings)
1108 return SEC_E_INSUFFICIENT_MEMORY;
1110 bindings->Bindings->cbApplicationDataLength = sizeof(prefix)-1 + hash_size;
1111 bindings->Bindings->dwApplicationDataOffset = sizeof(*bindings->Bindings);
1113 p = (char*)(bindings->Bindings+1);
1114 memcpy(p, prefix, sizeof(prefix)-1);
1115 p += sizeof(prefix)-1;
1116 memcpy(p, hash, hash_size);
1117 return SEC_E_OK;
1120 default:
1121 FIXME("Unhandled attribute %#x\n", attribute);
1122 return SEC_E_UNSUPPORTED_FUNCTION;
1126 static SECURITY_STATUS SEC_ENTRY schan_QueryContextAttributesA(
1127 PCtxtHandle context_handle, ULONG attribute, PVOID buffer)
1129 TRACE("context_handle %p, attribute %#x, buffer %p\n",
1130 context_handle, attribute, buffer);
1132 switch(attribute)
1134 case SECPKG_ATTR_STREAM_SIZES:
1135 return schan_QueryContextAttributesW(context_handle, attribute, buffer);
1136 case SECPKG_ATTR_KEY_INFO:
1138 SECURITY_STATUS status = schan_QueryContextAttributesW(context_handle, attribute, buffer);
1139 if (status == SEC_E_OK)
1141 SecPkgContext_KeyInfoA *info = buffer;
1142 info->sSignatureAlgorithmName = get_alg_name(info->SignatureAlgorithm, FALSE);
1143 info->sEncryptAlgorithmName = get_alg_name(info->EncryptAlgorithm, FALSE);
1145 return status;
1147 case SECPKG_ATTR_REMOTE_CERT_CONTEXT:
1148 return schan_QueryContextAttributesW(context_handle, attribute, buffer);
1149 case SECPKG_ATTR_CONNECTION_INFO:
1150 return schan_QueryContextAttributesW(context_handle, attribute, buffer);
1151 case SECPKG_ATTR_ENDPOINT_BINDINGS:
1152 return schan_QueryContextAttributesW(context_handle, attribute, buffer);
1154 default:
1155 FIXME("Unhandled attribute %#x\n", attribute);
1156 return SEC_E_UNSUPPORTED_FUNCTION;
1160 static int schan_encrypt_message_get_next_buffer(const struct schan_transport *t, struct schan_buffers *s)
1162 SecBuffer *b;
1164 if (s->current_buffer_idx == -1)
1165 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_STREAM_HEADER);
1167 b = &s->desc->pBuffers[s->current_buffer_idx];
1169 if (b->BufferType == SECBUFFER_STREAM_HEADER)
1170 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_DATA);
1172 if (b->BufferType == SECBUFFER_DATA)
1173 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_STREAM_TRAILER);
1175 return -1;
1178 static int schan_encrypt_message_get_next_buffer_token(const struct schan_transport *t, struct schan_buffers *s)
1180 SecBuffer *b;
1182 if (s->current_buffer_idx == -1)
1183 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
1185 b = &s->desc->pBuffers[s->current_buffer_idx];
1187 if (b->BufferType == SECBUFFER_TOKEN)
1189 int idx = schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
1190 if (idx != s->current_buffer_idx) return -1;
1191 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_DATA);
1194 if (b->BufferType == SECBUFFER_DATA)
1196 int idx = schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
1197 if (idx != -1)
1198 idx = schan_find_sec_buffer_idx(s->desc, idx + 1, SECBUFFER_TOKEN);
1199 return idx;
1202 return -1;
1205 static SECURITY_STATUS SEC_ENTRY schan_EncryptMessage(PCtxtHandle context_handle,
1206 ULONG quality, PSecBufferDesc message, ULONG message_seq_no)
1208 struct schan_transport transport;
1209 struct schan_context *ctx;
1210 struct schan_buffers *b;
1211 SECURITY_STATUS status;
1212 SecBuffer *buffer;
1213 SIZE_T data_size;
1214 SIZE_T length;
1215 char *data;
1216 int idx;
1218 TRACE("context_handle %p, quality %d, message %p, message_seq_no %d\n",
1219 context_handle, quality, message, message_seq_no);
1221 if (!context_handle) return SEC_E_INVALID_HANDLE;
1222 ctx = schan_get_object(context_handle->dwLower, SCHAN_HANDLE_CTX);
1224 dump_buffer_desc(message);
1226 idx = schan_find_sec_buffer_idx(message, 0, SECBUFFER_DATA);
1227 if (idx == -1)
1229 WARN("No data buffer passed\n");
1230 return SEC_E_INTERNAL_ERROR;
1232 buffer = &message->pBuffers[idx];
1234 data_size = buffer->cbBuffer;
1235 data = HeapAlloc(GetProcessHeap(), 0, data_size);
1236 memcpy(data, buffer->pvBuffer, data_size);
1238 transport.ctx = ctx;
1239 init_schan_buffers(&transport.in, NULL, NULL);
1240 if (schan_find_sec_buffer_idx(message, 0, SECBUFFER_STREAM_HEADER) != -1)
1241 init_schan_buffers(&transport.out, message, schan_encrypt_message_get_next_buffer);
1242 else
1243 init_schan_buffers(&transport.out, message, schan_encrypt_message_get_next_buffer_token);
1244 schan_imp_set_session_transport(ctx->session, &transport);
1246 length = data_size;
1247 status = schan_imp_send(ctx->session, data, &length);
1249 TRACE("Sent %ld bytes.\n", length);
1251 if (length != data_size)
1252 status = SEC_E_INTERNAL_ERROR;
1254 b = &transport.out;
1255 b->desc->pBuffers[b->current_buffer_idx].cbBuffer = b->offset;
1256 HeapFree(GetProcessHeap(), 0, data);
1258 TRACE("Returning %#x.\n", status);
1260 return status;
1263 static int schan_decrypt_message_get_next_buffer(const struct schan_transport *t, struct schan_buffers *s)
1265 if (s->current_buffer_idx == -1)
1266 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_DATA);
1268 return -1;
1271 static int schan_validate_decrypt_buffer_desc(PSecBufferDesc message)
1273 int data_idx = -1;
1274 unsigned int empty_count = 0;
1275 unsigned int i;
1277 if (message->cBuffers < 4)
1279 WARN("Less than four buffers passed\n");
1280 return -1;
1283 for (i = 0; i < message->cBuffers; ++i)
1285 SecBuffer *b = &message->pBuffers[i];
1286 if (b->BufferType == SECBUFFER_DATA)
1288 if (data_idx != -1)
1290 WARN("More than one data buffer passed\n");
1291 return -1;
1293 data_idx = i;
1295 else if (b->BufferType == SECBUFFER_EMPTY)
1296 ++empty_count;
1299 if (data_idx == -1)
1301 WARN("No data buffer passed\n");
1302 return -1;
1305 if (empty_count < 3)
1307 WARN("Less than three empty buffers passed\n");
1308 return -1;
1311 return data_idx;
1314 static void schan_decrypt_fill_buffer(PSecBufferDesc message, ULONG buffer_type, void *data, ULONG size)
1316 int idx;
1317 SecBuffer *buffer;
1319 idx = schan_find_sec_buffer_idx(message, 0, SECBUFFER_EMPTY);
1320 buffer = &message->pBuffers[idx];
1322 buffer->BufferType = buffer_type;
1323 buffer->pvBuffer = data;
1324 buffer->cbBuffer = size;
1327 static SECURITY_STATUS SEC_ENTRY schan_DecryptMessage(PCtxtHandle context_handle,
1328 PSecBufferDesc message, ULONG message_seq_no, PULONG quality)
1330 struct schan_transport transport;
1331 struct schan_context *ctx;
1332 SecBuffer *buffer;
1333 SIZE_T data_size;
1334 char *data;
1335 unsigned expected_size;
1336 SSIZE_T received = 0;
1337 int idx;
1338 unsigned char *buf_ptr;
1340 TRACE("context_handle %p, message %p, message_seq_no %d, quality %p\n",
1341 context_handle, message, message_seq_no, quality);
1343 if (!context_handle) return SEC_E_INVALID_HANDLE;
1344 ctx = schan_get_object(context_handle->dwLower, SCHAN_HANDLE_CTX);
1346 dump_buffer_desc(message);
1348 idx = schan_validate_decrypt_buffer_desc(message);
1349 if (idx == -1)
1350 return SEC_E_INVALID_TOKEN;
1351 buffer = &message->pBuffers[idx];
1352 buf_ptr = buffer->pvBuffer;
1354 expected_size = 5 + ((buf_ptr[3] << 8) | buf_ptr[4]);
1355 if(buffer->cbBuffer < expected_size)
1357 TRACE("Expected %u bytes, but buffer only contains %u bytes\n", expected_size, buffer->cbBuffer);
1358 buffer->BufferType = SECBUFFER_MISSING;
1359 buffer->cbBuffer = expected_size - buffer->cbBuffer;
1361 /* This is a bit weird, but windows does it too */
1362 idx = schan_find_sec_buffer_idx(message, 0, SECBUFFER_EMPTY);
1363 buffer = &message->pBuffers[idx];
1364 buffer->BufferType = SECBUFFER_MISSING;
1365 buffer->cbBuffer = expected_size - buffer->cbBuffer;
1367 TRACE("Returning SEC_E_INCOMPLETE_MESSAGE\n");
1368 return SEC_E_INCOMPLETE_MESSAGE;
1371 data_size = expected_size - 5;
1372 data = HeapAlloc(GetProcessHeap(), 0, data_size);
1374 transport.ctx = ctx;
1375 init_schan_buffers(&transport.in, message, schan_decrypt_message_get_next_buffer);
1376 transport.in.limit = expected_size;
1377 init_schan_buffers(&transport.out, NULL, NULL);
1378 schan_imp_set_session_transport(ctx->session, &transport);
1380 while (received < data_size)
1382 SIZE_T length = data_size - received;
1383 SECURITY_STATUS status = schan_imp_recv(ctx->session, data + received, &length);
1385 if (status == SEC_I_CONTINUE_NEEDED)
1386 break;
1388 if (status != SEC_E_OK)
1390 HeapFree(GetProcessHeap(), 0, data);
1391 ERR("Returning %x\n", status);
1392 return status;
1395 if (!length)
1396 break;
1398 received += length;
1401 TRACE("Received %ld bytes\n", received);
1403 memcpy(buf_ptr + 5, data, received);
1404 HeapFree(GetProcessHeap(), 0, data);
1406 schan_decrypt_fill_buffer(message, SECBUFFER_DATA,
1407 buf_ptr + 5, received);
1409 schan_decrypt_fill_buffer(message, SECBUFFER_STREAM_TRAILER,
1410 buf_ptr + 5 + received, buffer->cbBuffer - 5 - received);
1412 if(buffer->cbBuffer > expected_size)
1413 schan_decrypt_fill_buffer(message, SECBUFFER_EXTRA,
1414 buf_ptr + expected_size, buffer->cbBuffer - expected_size);
1416 buffer->BufferType = SECBUFFER_STREAM_HEADER;
1417 buffer->cbBuffer = 5;
1419 return SEC_E_OK;
1422 static SECURITY_STATUS SEC_ENTRY schan_DeleteSecurityContext(PCtxtHandle context_handle)
1424 struct schan_context *ctx;
1426 TRACE("context_handle %p\n", context_handle);
1428 if (!context_handle) return SEC_E_INVALID_HANDLE;
1430 ctx = schan_free_handle(context_handle->dwLower, SCHAN_HANDLE_CTX);
1431 if (!ctx) return SEC_E_INVALID_HANDLE;
1433 if (ctx->cert)
1434 CertFreeCertificateContext(ctx->cert);
1435 schan_imp_dispose_session(ctx->session);
1436 HeapFree(GetProcessHeap(), 0, ctx);
1438 return SEC_E_OK;
1441 static const SecurityFunctionTableA schanTableA = {
1443 NULL, /* EnumerateSecurityPackagesA */
1444 schan_QueryCredentialsAttributesA,
1445 schan_AcquireCredentialsHandleA,
1446 schan_FreeCredentialsHandle,
1447 NULL, /* Reserved2 */
1448 schan_InitializeSecurityContextA,
1449 NULL, /* AcceptSecurityContext */
1450 NULL, /* CompleteAuthToken */
1451 schan_DeleteSecurityContext,
1452 NULL, /* ApplyControlToken */
1453 schan_QueryContextAttributesA,
1454 NULL, /* ImpersonateSecurityContext */
1455 NULL, /* RevertSecurityContext */
1456 NULL, /* MakeSignature */
1457 NULL, /* VerifySignature */
1458 FreeContextBuffer,
1459 NULL, /* QuerySecurityPackageInfoA */
1460 NULL, /* Reserved3 */
1461 NULL, /* Reserved4 */
1462 NULL, /* ExportSecurityContext */
1463 NULL, /* ImportSecurityContextA */
1464 NULL, /* AddCredentialsA */
1465 NULL, /* Reserved8 */
1466 NULL, /* QuerySecurityContextToken */
1467 schan_EncryptMessage,
1468 schan_DecryptMessage,
1469 NULL, /* SetContextAttributesA */
1472 static const SecurityFunctionTableW schanTableW = {
1474 NULL, /* EnumerateSecurityPackagesW */
1475 schan_QueryCredentialsAttributesW,
1476 schan_AcquireCredentialsHandleW,
1477 schan_FreeCredentialsHandle,
1478 NULL, /* Reserved2 */
1479 schan_InitializeSecurityContextW,
1480 NULL, /* AcceptSecurityContext */
1481 NULL, /* CompleteAuthToken */
1482 schan_DeleteSecurityContext,
1483 NULL, /* ApplyControlToken */
1484 schan_QueryContextAttributesW,
1485 NULL, /* ImpersonateSecurityContext */
1486 NULL, /* RevertSecurityContext */
1487 NULL, /* MakeSignature */
1488 NULL, /* VerifySignature */
1489 FreeContextBuffer,
1490 NULL, /* QuerySecurityPackageInfoW */
1491 NULL, /* Reserved3 */
1492 NULL, /* Reserved4 */
1493 NULL, /* ExportSecurityContext */
1494 NULL, /* ImportSecurityContextW */
1495 NULL, /* AddCredentialsW */
1496 NULL, /* Reserved8 */
1497 NULL, /* QuerySecurityContextToken */
1498 schan_EncryptMessage,
1499 schan_DecryptMessage,
1500 NULL, /* SetContextAttributesW */
1503 static const WCHAR schannelComment[] = { 'S','c','h','a','n','n','e','l',' ',
1504 'S','e','c','u','r','i','t','y',' ','P','a','c','k','a','g','e',0 };
1505 static const WCHAR schannelDllName[] = { 's','c','h','a','n','n','e','l','.','d','l','l',0 };
1507 void SECUR32_initSchannelSP(void)
1509 /* This is what Windows reports. This shouldn't break any applications
1510 * even though the functions are missing, because the wrapper will
1511 * return SEC_E_UNSUPPORTED_FUNCTION if our function is NULL.
1513 static const LONG caps =
1514 SECPKG_FLAG_INTEGRITY |
1515 SECPKG_FLAG_PRIVACY |
1516 SECPKG_FLAG_CONNECTION |
1517 SECPKG_FLAG_MULTI_REQUIRED |
1518 SECPKG_FLAG_EXTENDED_ERROR |
1519 SECPKG_FLAG_IMPERSONATION |
1520 SECPKG_FLAG_ACCEPT_WIN32_NAME |
1521 SECPKG_FLAG_STREAM;
1522 static const short version = 1;
1523 static const LONG maxToken = 16384;
1524 SEC_WCHAR *uniSPName = (SEC_WCHAR *)UNISP_NAME_W,
1525 *schannel = (SEC_WCHAR *)SCHANNEL_NAME_W;
1526 const SecPkgInfoW info[] = {
1527 { caps, version, UNISP_RPC_ID, maxToken, uniSPName, uniSPName },
1528 { caps, version, UNISP_RPC_ID, maxToken, schannel,
1529 (SEC_WCHAR *)schannelComment },
1531 SecureProvider *provider;
1533 if (!schan_imp_init())
1534 return;
1536 schan_handle_table = HeapAlloc(GetProcessHeap(), 0, 64 * sizeof(*schan_handle_table));
1537 if (!schan_handle_table)
1539 ERR("Failed to allocate schannel handle table.\n");
1540 goto fail;
1542 schan_handle_table_size = 64;
1544 provider = SECUR32_addProvider(&schanTableA, &schanTableW, schannelDllName);
1545 if (!provider)
1547 ERR("Failed to add schannel provider.\n");
1548 goto fail;
1551 SECUR32_addPackages(provider, sizeof(info) / sizeof(info[0]), NULL, info);
1553 return;
1555 fail:
1556 HeapFree(GetProcessHeap(), 0, schan_handle_table);
1557 schan_handle_table = NULL;
1558 schan_imp_deinit();
1559 return;
1562 void SECUR32_deinitSchannelSP(void)
1564 SIZE_T i = schan_handle_count;
1566 if (!schan_handle_table) return;
1568 /* deinitialized sessions first because a pointer to the credentials
1569 * may be stored for the session. */
1570 while (i--)
1572 if (schan_handle_table[i].type == SCHAN_HANDLE_CTX)
1574 struct schan_context *ctx = schan_free_handle(i, SCHAN_HANDLE_CTX);
1575 schan_imp_dispose_session(ctx->session);
1576 HeapFree(GetProcessHeap(), 0, ctx);
1579 i = schan_handle_count;
1580 while (i--)
1582 if (schan_handle_table[i].type != SCHAN_HANDLE_FREE)
1584 struct schan_credentials *cred;
1585 cred = schan_free_handle(i, SCHAN_HANDLE_CRED);
1586 schan_imp_free_certificate_credentials(cred);
1587 HeapFree(GetProcessHeap(), 0, cred);
1590 HeapFree(GetProcessHeap(), 0, schan_handle_table);
1591 schan_imp_deinit();
1594 #else /* SONAME_LIBGNUTLS || HAVE_SECURITY_SECURITY_H */
1596 void SECUR32_initSchannelSP(void)
1598 ERR("TLS library not found, SSL connections will fail\n");
1601 void SECUR32_deinitSchannelSP(void) {}
1603 #endif /* SONAME_LIBGNUTLS || HAVE_SECURITY_SECURITY_H */