secur32: Set output buffer size to zero during handshake when no data needs to be...
[wine.git] / dlls / secur32 / schannel.c
blobf0d271e0d898d95ab0e0c16c52f6219eb0dd7a46
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 < sizeof(protocol_config_keys)/sizeof(*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 < sizeof(protocol_config_keys)/sizeof(*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 schan_CheckCreds(const SCHANNEL_CRED *schanCred)
343 SECURITY_STATUS st;
344 DWORD i;
346 TRACE("dwVersion = %d\n", schanCred->dwVersion);
347 TRACE("cCreds = %d\n", schanCred->cCreds);
348 TRACE("hRootStore = %p\n", schanCred->hRootStore);
349 TRACE("cMappers = %d\n", schanCred->cMappers);
350 TRACE("cSupportedAlgs = %d:\n", schanCred->cSupportedAlgs);
351 for (i = 0; i < schanCred->cSupportedAlgs; i++)
352 TRACE("%08x\n", schanCred->palgSupportedAlgs[i]);
353 TRACE("grbitEnabledProtocols = %08x\n", schanCred->grbitEnabledProtocols);
354 TRACE("dwMinimumCipherStrength = %d\n", schanCred->dwMinimumCipherStrength);
355 TRACE("dwMaximumCipherStrength = %d\n", schanCred->dwMaximumCipherStrength);
356 TRACE("dwSessionLifespan = %d\n", schanCred->dwSessionLifespan);
357 TRACE("dwFlags = %08x\n", schanCred->dwFlags);
358 TRACE("dwCredFormat = %d\n", schanCred->dwCredFormat);
360 switch (schanCred->dwVersion)
362 case SCH_CRED_V3:
363 case SCHANNEL_CRED_VERSION:
364 break;
365 default:
366 return SEC_E_INTERNAL_ERROR;
369 if (schanCred->cCreds == 0)
370 st = SEC_E_NO_CREDENTIALS;
371 else if (schanCred->cCreds > 1)
372 st = SEC_E_UNKNOWN_CREDENTIALS;
373 else
375 DWORD keySpec;
376 HCRYPTPROV csp;
377 BOOL ret, freeCSP;
379 ret = CryptAcquireCertificatePrivateKey(schanCred->paCred[0],
380 0, /* FIXME: what flags to use? */ NULL,
381 &csp, &keySpec, &freeCSP);
382 if (ret)
384 st = SEC_E_OK;
385 if (freeCSP)
386 CryptReleaseContext(csp, 0);
388 else
389 st = SEC_E_UNKNOWN_CREDENTIALS;
391 return st;
394 static SECURITY_STATUS schan_AcquireClientCredentials(const SCHANNEL_CRED *schanCred,
395 PCredHandle phCredential, PTimeStamp ptsExpiry)
397 struct schan_credentials *creds;
398 unsigned enabled_protocols;
399 ULONG_PTR handle;
400 SECURITY_STATUS st = SEC_E_OK;
402 TRACE("schanCred %p, phCredential %p, ptsExpiry %p\n", schanCred, phCredential, ptsExpiry);
404 if (schanCred)
406 st = schan_CheckCreds(schanCred);
407 if (st != SEC_E_OK && st != SEC_E_NO_CREDENTIALS)
408 return st;
410 st = SEC_E_OK;
413 read_config();
414 if(schanCred && schanCred->grbitEnabledProtocols)
415 enabled_protocols = schanCred->grbitEnabledProtocols & config_enabled_protocols;
416 else
417 enabled_protocols = config_enabled_protocols & ~config_default_disabled_protocols;
418 if(!enabled_protocols) {
419 ERR("Could not find matching protocol\n");
420 return SEC_E_NO_AUTHENTICATING_AUTHORITY;
423 /* For now, the only thing I'm interested in is the direction of the
424 * connection, so just store it.
426 creds = heap_alloc(sizeof(*creds));
427 if (!creds) return SEC_E_INSUFFICIENT_MEMORY;
429 handle = schan_alloc_handle(creds, SCHAN_HANDLE_CRED);
430 if (handle == SCHAN_INVALID_HANDLE) goto fail;
432 creds->credential_use = SECPKG_CRED_OUTBOUND;
433 if (!schan_imp_allocate_certificate_credentials(creds))
435 schan_free_handle(handle, SCHAN_HANDLE_CRED);
436 goto fail;
439 creds->enabled_protocols = enabled_protocols;
440 phCredential->dwLower = handle;
441 phCredential->dwUpper = 0;
443 /* Outbound credentials have no expiry */
444 if (ptsExpiry)
446 ptsExpiry->LowPart = 0;
447 ptsExpiry->HighPart = 0;
450 return st;
452 fail:
453 heap_free(creds);
454 return SEC_E_INTERNAL_ERROR;
457 static SECURITY_STATUS schan_AcquireServerCredentials(const SCHANNEL_CRED *schanCred,
458 PCredHandle phCredential, PTimeStamp ptsExpiry)
460 SECURITY_STATUS st;
462 TRACE("schanCred %p, phCredential %p, ptsExpiry %p\n", schanCred, phCredential, ptsExpiry);
464 if (!schanCred) return SEC_E_NO_CREDENTIALS;
466 st = schan_CheckCreds(schanCred);
467 if (st == SEC_E_OK)
469 ULONG_PTR handle;
470 struct schan_credentials *creds;
472 creds = heap_alloc_zero(sizeof(*creds));
473 if (!creds) return SEC_E_INSUFFICIENT_MEMORY;
474 creds->credential_use = SECPKG_CRED_INBOUND;
476 handle = schan_alloc_handle(creds, SCHAN_HANDLE_CRED);
477 if (handle == SCHAN_INVALID_HANDLE)
479 heap_free(creds);
480 return SEC_E_INTERNAL_ERROR;
483 phCredential->dwLower = handle;
484 phCredential->dwUpper = 0;
486 /* FIXME: get expiry from cert */
488 return st;
491 static SECURITY_STATUS schan_AcquireCredentialsHandle(ULONG fCredentialUse,
492 const SCHANNEL_CRED *schanCred, PCredHandle phCredential, PTimeStamp ptsExpiry)
494 SECURITY_STATUS ret;
496 if (fCredentialUse == SECPKG_CRED_OUTBOUND)
497 ret = schan_AcquireClientCredentials(schanCred, phCredential,
498 ptsExpiry);
499 else
500 ret = schan_AcquireServerCredentials(schanCred, phCredential,
501 ptsExpiry);
502 return ret;
505 static SECURITY_STATUS SEC_ENTRY schan_AcquireCredentialsHandleA(
506 SEC_CHAR *pszPrincipal, SEC_CHAR *pszPackage, ULONG fCredentialUse,
507 PLUID pLogonID, PVOID pAuthData, SEC_GET_KEY_FN pGetKeyFn,
508 PVOID pGetKeyArgument, PCredHandle phCredential, PTimeStamp ptsExpiry)
510 TRACE("(%s, %s, 0x%08x, %p, %p, %p, %p, %p, %p)\n",
511 debugstr_a(pszPrincipal), debugstr_a(pszPackage), fCredentialUse,
512 pLogonID, pAuthData, pGetKeyFn, pGetKeyArgument, phCredential, ptsExpiry);
513 return schan_AcquireCredentialsHandle(fCredentialUse,
514 pAuthData, phCredential, ptsExpiry);
517 static SECURITY_STATUS SEC_ENTRY schan_AcquireCredentialsHandleW(
518 SEC_WCHAR *pszPrincipal, SEC_WCHAR *pszPackage, ULONG fCredentialUse,
519 PLUID pLogonID, PVOID pAuthData, SEC_GET_KEY_FN pGetKeyFn,
520 PVOID pGetKeyArgument, PCredHandle phCredential, PTimeStamp ptsExpiry)
522 TRACE("(%s, %s, 0x%08x, %p, %p, %p, %p, %p, %p)\n",
523 debugstr_w(pszPrincipal), debugstr_w(pszPackage), fCredentialUse,
524 pLogonID, pAuthData, pGetKeyFn, pGetKeyArgument, phCredential, ptsExpiry);
525 return schan_AcquireCredentialsHandle(fCredentialUse,
526 pAuthData, phCredential, ptsExpiry);
529 static SECURITY_STATUS SEC_ENTRY schan_FreeCredentialsHandle(
530 PCredHandle phCredential)
532 struct schan_credentials *creds;
534 TRACE("phCredential %p\n", phCredential);
536 if (!phCredential) return SEC_E_INVALID_HANDLE;
538 creds = schan_free_handle(phCredential->dwLower, SCHAN_HANDLE_CRED);
539 if (!creds) return SEC_E_INVALID_HANDLE;
541 if (creds->credential_use == SECPKG_CRED_OUTBOUND)
542 schan_imp_free_certificate_credentials(creds);
543 heap_free(creds);
545 return SEC_E_OK;
548 static void init_schan_buffers(struct schan_buffers *s, const PSecBufferDesc desc,
549 int (*get_next_buffer)(const struct schan_transport *, struct schan_buffers *))
551 s->offset = 0;
552 s->limit = ~0UL;
553 s->desc = desc;
554 s->current_buffer_idx = -1;
555 s->allow_buffer_resize = FALSE;
556 s->get_next_buffer = get_next_buffer;
559 static int schan_find_sec_buffer_idx(const SecBufferDesc *desc, unsigned int start_idx, ULONG buffer_type)
561 unsigned int i;
562 PSecBuffer buffer;
564 for (i = start_idx; i < desc->cBuffers; ++i)
566 buffer = &desc->pBuffers[i];
567 if (buffer->BufferType == buffer_type) return i;
570 return -1;
573 static void schan_resize_current_buffer(const struct schan_buffers *s, SIZE_T min_size)
575 SecBuffer *b = &s->desc->pBuffers[s->current_buffer_idx];
576 SIZE_T new_size = b->cbBuffer ? b->cbBuffer * 2 : 128;
577 void *new_data;
579 if (b->cbBuffer >= min_size || !s->allow_buffer_resize || min_size > UINT_MAX / 2) return;
581 while (new_size < min_size) new_size *= 2;
583 if (b->pvBuffer)
584 new_data = heap_realloc(b->pvBuffer, new_size);
585 else
586 new_data = heap_alloc(new_size);
588 if (!new_data)
590 TRACE("Failed to resize %p from %d to %ld\n", b->pvBuffer, b->cbBuffer, new_size);
591 return;
594 b->cbBuffer = new_size;
595 b->pvBuffer = new_data;
598 char *schan_get_buffer(const struct schan_transport *t, struct schan_buffers *s, SIZE_T *count)
600 SIZE_T max_count;
601 PSecBuffer buffer;
603 if (!s->desc)
605 TRACE("No desc\n");
606 return NULL;
609 if (s->current_buffer_idx == -1)
611 /* Initial buffer */
612 int buffer_idx = s->get_next_buffer(t, s);
613 if (buffer_idx == -1)
615 TRACE("No next buffer\n");
616 return NULL;
618 s->current_buffer_idx = buffer_idx;
621 buffer = &s->desc->pBuffers[s->current_buffer_idx];
622 TRACE("Using buffer %d: cbBuffer %d, BufferType %#x, pvBuffer %p\n", s->current_buffer_idx, buffer->cbBuffer, buffer->BufferType, buffer->pvBuffer);
624 schan_resize_current_buffer(s, s->offset + *count);
625 max_count = buffer->cbBuffer - s->offset;
626 if (s->limit != ~0UL && s->limit < max_count)
627 max_count = s->limit;
628 if (!max_count)
630 int buffer_idx;
632 s->allow_buffer_resize = FALSE;
633 buffer_idx = s->get_next_buffer(t, s);
634 if (buffer_idx == -1)
636 TRACE("No next buffer\n");
637 return NULL;
639 s->current_buffer_idx = buffer_idx;
640 s->offset = 0;
641 return schan_get_buffer(t, s, count);
644 if (*count > max_count)
645 *count = max_count;
646 if (s->limit != ~0UL)
647 s->limit -= *count;
649 return (char *)buffer->pvBuffer + s->offset;
652 /* schan_pull
653 * Read data from the transport input buffer.
655 * t - The session transport object.
656 * buff - The buffer into which to store the read data. Must be at least
657 * *buff_len bytes in length.
658 * buff_len - On input, *buff_len is the desired length to read. On successful
659 * return, *buff_len is the number of bytes actually read.
661 * Returns:
662 * 0 on success, in which case:
663 * *buff_len == 0 indicates end of file.
664 * *buff_len > 0 indicates that some data was read. May be less than
665 * what was requested, in which case the caller should call again if/
666 * when they want more.
667 * EAGAIN when no data could be read without blocking
668 * another errno-style error value on failure
671 int schan_pull(struct schan_transport *t, void *buff, size_t *buff_len)
673 char *b;
674 SIZE_T local_len = *buff_len;
676 TRACE("Pull %lu bytes\n", local_len);
678 *buff_len = 0;
680 b = schan_get_buffer(t, &t->in, &local_len);
681 if (!b)
682 return EAGAIN;
684 memcpy(buff, b, local_len);
685 t->in.offset += local_len;
687 TRACE("Read %lu bytes\n", local_len);
689 *buff_len = local_len;
690 return 0;
693 /* schan_push
694 * Write data to the transport output buffer.
696 * t - The session transport object.
697 * buff - The buffer of data to write. Must be at least *buff_len bytes in length.
698 * buff_len - On input, *buff_len is the desired length to write. On successful
699 * return, *buff_len is the number of bytes actually written.
701 * Returns:
702 * 0 on success
703 * *buff_len will be > 0 indicating how much data was written. May be less
704 * than what was requested, in which case the caller should call again
705 if/when they want to write more.
706 * EAGAIN when no data could be written without blocking
707 * another errno-style error value on failure
710 int schan_push(struct schan_transport *t, const void *buff, size_t *buff_len)
712 char *b;
713 SIZE_T local_len = *buff_len;
715 TRACE("Push %lu bytes\n", local_len);
717 *buff_len = 0;
719 b = schan_get_buffer(t, &t->out, &local_len);
720 if (!b)
721 return EAGAIN;
723 memcpy(b, buff, local_len);
724 t->out.offset += local_len;
726 TRACE("Wrote %lu bytes\n", local_len);
728 *buff_len = local_len;
729 return 0;
732 schan_imp_session schan_session_for_transport(struct schan_transport* t)
734 return t->ctx->session;
737 static int schan_init_sec_ctx_get_next_input_buffer(const struct schan_transport *t, struct schan_buffers *s)
739 if (s->current_buffer_idx != -1)
740 return -1;
741 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
744 static int schan_init_sec_ctx_get_next_output_buffer(const struct schan_transport *t, struct schan_buffers *s)
746 if (s->current_buffer_idx == -1)
748 int idx = schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
749 if (t->ctx->req_ctx_attr & ISC_REQ_ALLOCATE_MEMORY)
751 if (idx == -1)
753 idx = schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_EMPTY);
754 if (idx != -1) s->desc->pBuffers[idx].BufferType = SECBUFFER_TOKEN;
756 if (idx != -1 && !s->desc->pBuffers[idx].pvBuffer)
758 s->desc->pBuffers[idx].cbBuffer = 0;
759 s->allow_buffer_resize = TRUE;
762 return idx;
765 return -1;
768 static void dump_buffer_desc(SecBufferDesc *desc)
770 unsigned int i;
772 if (!desc) return;
773 TRACE("Buffer desc %p:\n", desc);
774 for (i = 0; i < desc->cBuffers; ++i)
776 SecBuffer *b = &desc->pBuffers[i];
777 TRACE("\tbuffer %u: cbBuffer %d, BufferType %#x pvBuffer %p\n", i, b->cbBuffer, b->BufferType, b->pvBuffer);
781 /***********************************************************************
782 * InitializeSecurityContextW
784 static SECURITY_STATUS SEC_ENTRY schan_InitializeSecurityContextW(
785 PCredHandle phCredential, PCtxtHandle phContext, SEC_WCHAR *pszTargetName,
786 ULONG fContextReq, ULONG Reserved1, ULONG TargetDataRep,
787 PSecBufferDesc pInput, ULONG Reserved2, PCtxtHandle phNewContext,
788 PSecBufferDesc pOutput, ULONG *pfContextAttr, PTimeStamp ptsExpiry)
790 struct schan_context *ctx;
791 struct schan_buffers *out_buffers;
792 struct schan_credentials *cred;
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 = heap_alloc(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 heap_free(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 heap_free(ctx);
833 return SEC_E_INTERNAL_ERROR;
836 ctx->transport.ctx = ctx;
837 schan_imp_set_session_transport(ctx->session, &ctx->transport);
839 if (pszTargetName && *pszTargetName)
841 UINT len = WideCharToMultiByte( CP_UNIXCP, 0, pszTargetName, -1, NULL, 0, NULL, NULL );
842 char *target = heap_alloc( len );
844 if (target)
846 WideCharToMultiByte( CP_UNIXCP, 0, pszTargetName, -1, target, len, NULL, NULL );
847 schan_imp_set_session_target( ctx->session, target );
848 heap_free( target );
851 phNewContext->dwLower = handle;
852 phNewContext->dwUpper = 0;
854 else
856 SIZE_T record_size = 0;
857 unsigned char *ptr;
858 SecBuffer *buffer;
859 int idx;
861 if (!pInput)
862 return SEC_E_INCOMPLETE_MESSAGE;
864 idx = schan_find_sec_buffer_idx(pInput, 0, SECBUFFER_TOKEN);
865 if (idx == -1)
866 return SEC_E_INCOMPLETE_MESSAGE;
868 buffer = &pInput->pBuffers[idx];
869 ptr = buffer->pvBuffer;
870 expected_size = 0;
872 while (buffer->cbBuffer > expected_size + 5)
874 record_size = 5 + ((ptr[3] << 8) | ptr[4]);
876 if (buffer->cbBuffer < expected_size + record_size)
877 break;
879 expected_size += record_size;
880 ptr += record_size;
883 if (!expected_size)
885 TRACE("Expected at least %lu bytes, but buffer only contains %u bytes.\n",
886 max(6, record_size), buffer->cbBuffer);
887 return SEC_E_INCOMPLETE_MESSAGE;
890 TRACE("Using expected_size %lu.\n", expected_size);
892 ctx = schan_get_object(phContext->dwLower, SCHAN_HANDLE_CTX);
895 ctx->req_ctx_attr = fContextReq;
897 init_schan_buffers(&ctx->transport.in, pInput, schan_init_sec_ctx_get_next_input_buffer);
898 ctx->transport.in.limit = expected_size;
899 init_schan_buffers(&ctx->transport.out, pOutput, schan_init_sec_ctx_get_next_output_buffer);
901 /* Perform the TLS handshake */
902 ret = schan_imp_handshake(ctx->session);
904 out_buffers = &ctx->transport.out;
905 if (out_buffers->current_buffer_idx != -1)
907 SecBuffer *buffer = &out_buffers->desc->pBuffers[out_buffers->current_buffer_idx];
908 buffer->cbBuffer = out_buffers->offset;
910 else if (out_buffers->desc && out_buffers->desc->cBuffers > 0)
912 SecBuffer *buffer = &out_buffers->desc->pBuffers[0];
913 buffer->cbBuffer = 0;
916 if(ctx->transport.in.offset && ctx->transport.in.offset != pInput->pBuffers[0].cbBuffer) {
917 if(pInput->cBuffers<2 || pInput->pBuffers[1].BufferType!=SECBUFFER_EMPTY)
918 return SEC_E_INVALID_TOKEN;
920 pInput->pBuffers[1].BufferType = SECBUFFER_EXTRA;
921 pInput->pBuffers[1].cbBuffer = pInput->pBuffers[0].cbBuffer-ctx->transport.in.offset;
924 *pfContextAttr = 0;
925 if (ctx->req_ctx_attr & ISC_REQ_REPLAY_DETECT)
926 *pfContextAttr |= ISC_RET_REPLAY_DETECT;
927 if (ctx->req_ctx_attr & ISC_REQ_SEQUENCE_DETECT)
928 *pfContextAttr |= ISC_RET_SEQUENCE_DETECT;
929 if (ctx->req_ctx_attr & ISC_REQ_CONFIDENTIALITY)
930 *pfContextAttr |= ISC_RET_CONFIDENTIALITY;
931 if (ctx->req_ctx_attr & ISC_REQ_ALLOCATE_MEMORY)
932 *pfContextAttr |= ISC_RET_ALLOCATED_MEMORY;
933 if (ctx->req_ctx_attr & ISC_REQ_STREAM)
934 *pfContextAttr |= ISC_RET_STREAM;
936 return ret;
939 /***********************************************************************
940 * InitializeSecurityContextA
942 static SECURITY_STATUS SEC_ENTRY schan_InitializeSecurityContextA(
943 PCredHandle phCredential, PCtxtHandle phContext, SEC_CHAR *pszTargetName,
944 ULONG fContextReq, ULONG Reserved1, ULONG TargetDataRep,
945 PSecBufferDesc pInput, ULONG Reserved2, PCtxtHandle phNewContext,
946 PSecBufferDesc pOutput, ULONG *pfContextAttr, PTimeStamp ptsExpiry)
948 SECURITY_STATUS ret;
949 SEC_WCHAR *target_name = NULL;
951 TRACE("%p %p %s %d %d %d %p %d %p %p %p %p\n", phCredential, phContext,
952 debugstr_a(pszTargetName), fContextReq, Reserved1, TargetDataRep, pInput,
953 Reserved1, phNewContext, pOutput, pfContextAttr, ptsExpiry);
955 if (pszTargetName)
957 INT len = MultiByteToWideChar(CP_ACP, 0, pszTargetName, -1, NULL, 0);
958 if (!(target_name = heap_alloc(len * sizeof(*target_name)))) return SEC_E_INSUFFICIENT_MEMORY;
959 MultiByteToWideChar(CP_ACP, 0, pszTargetName, -1, target_name, len);
962 ret = schan_InitializeSecurityContextW(phCredential, phContext, target_name,
963 fContextReq, Reserved1, TargetDataRep, pInput, Reserved2,
964 phNewContext, pOutput, pfContextAttr, ptsExpiry);
966 heap_free(target_name);
967 return ret;
970 static void *get_alg_name(ALG_ID id, BOOL wide)
972 static const struct {
973 ALG_ID alg_id;
974 const char* name;
975 const WCHAR nameW[8];
976 } alg_name_map[] = {
977 { CALG_ECDSA, "ECDSA", {'E','C','D','S','A',0} },
978 { CALG_RSA_SIGN, "RSA", {'R','S','A',0} },
979 { CALG_DES, "DES", {'D','E','S',0} },
980 { CALG_RC2, "RC2", {'R','C','2',0} },
981 { CALG_3DES, "3DES", {'3','D','E','S',0} },
982 { CALG_AES_128, "AES", {'A','E','S',0} },
983 { CALG_AES_192, "AES", {'A','E','S',0} },
984 { CALG_AES_256, "AES", {'A','E','S',0} },
985 { CALG_RC4, "RC4", {'R','C','4',0} },
987 unsigned i;
989 for (i = 0; i < sizeof(alg_name_map)/sizeof(alg_name_map[0]); i++)
990 if (alg_name_map[i].alg_id == id)
991 return wide ? (void*)alg_name_map[i].nameW : (void*)alg_name_map[i].name;
993 FIXME("Unknown ALG_ID %04x\n", id);
994 return NULL;
997 static SECURITY_STATUS ensure_remote_cert(struct schan_context *ctx)
999 HCERTSTORE cert_store;
1000 SECURITY_STATUS status;
1002 if(ctx->cert)
1003 return SEC_E_OK;
1005 cert_store = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0, CERT_STORE_CREATE_NEW_FLAG, NULL);
1006 if(!cert_store)
1007 return GetLastError();
1009 status = schan_imp_get_session_peer_certificate(ctx->session, cert_store, &ctx->cert);
1010 CertCloseStore(cert_store, 0);
1011 return status;
1014 static SECURITY_STATUS SEC_ENTRY schan_QueryContextAttributesW(
1015 PCtxtHandle context_handle, ULONG attribute, PVOID buffer)
1017 struct schan_context *ctx;
1019 TRACE("context_handle %p, attribute %#x, buffer %p\n",
1020 context_handle, attribute, buffer);
1022 if (!context_handle) return SEC_E_INVALID_HANDLE;
1023 ctx = schan_get_object(context_handle->dwLower, SCHAN_HANDLE_CTX);
1025 switch(attribute)
1027 case SECPKG_ATTR_STREAM_SIZES:
1029 SecPkgContext_ConnectionInfo info;
1030 SECURITY_STATUS status = schan_imp_get_connection_info(ctx->session, &info);
1031 if (status == SEC_E_OK)
1033 SecPkgContext_StreamSizes *stream_sizes = buffer;
1034 SIZE_T mac_size = info.dwHashStrength;
1035 unsigned int block_size = schan_imp_get_session_cipher_block_size(ctx->session);
1036 unsigned int message_size = schan_imp_get_max_message_size(ctx->session);
1038 TRACE("Using %lu mac bytes, message size %u, block size %u\n",
1039 mac_size, message_size, block_size);
1041 /* These are defined by the TLS RFC */
1042 stream_sizes->cbHeader = 5;
1043 stream_sizes->cbTrailer = mac_size + 256; /* Max 255 bytes padding + 1 for padding size */
1044 stream_sizes->cbMaximumMessage = message_size;
1045 stream_sizes->cbBuffers = 4;
1046 stream_sizes->cbBlockSize = block_size;
1049 return status;
1051 case SECPKG_ATTR_KEY_INFO:
1053 SecPkgContext_ConnectionInfo conn_info;
1054 SECURITY_STATUS status = schan_imp_get_connection_info(ctx->session, &conn_info);
1055 if (status == SEC_E_OK)
1057 SecPkgContext_KeyInfoW *info = buffer;
1058 info->KeySize = conn_info.dwCipherStrength;
1059 info->SignatureAlgorithm = schan_imp_get_key_signature_algorithm(ctx->session);
1060 info->EncryptAlgorithm = conn_info.aiCipher;
1061 info->sSignatureAlgorithmName = get_alg_name(info->SignatureAlgorithm, TRUE);
1062 info->sEncryptAlgorithmName = get_alg_name(info->EncryptAlgorithm, TRUE);
1064 return status;
1066 case SECPKG_ATTR_REMOTE_CERT_CONTEXT:
1068 PCCERT_CONTEXT *cert = buffer;
1069 SECURITY_STATUS status;
1071 status = ensure_remote_cert(ctx);
1072 if(status != SEC_E_OK)
1073 return status;
1075 *cert = CertDuplicateCertificateContext(ctx->cert);
1076 return SEC_E_OK;
1078 case SECPKG_ATTR_CONNECTION_INFO:
1080 SecPkgContext_ConnectionInfo *info = buffer;
1081 return schan_imp_get_connection_info(ctx->session, info);
1083 case SECPKG_ATTR_ENDPOINT_BINDINGS:
1085 SecPkgContext_Bindings *bindings = buffer;
1086 CCRYPT_OID_INFO *info;
1087 ALG_ID hash_alg = CALG_SHA_256;
1088 BYTE hash[1024];
1089 DWORD hash_size;
1090 SECURITY_STATUS status;
1091 char *p;
1092 BOOL r;
1094 static const char prefix[] = "tls-server-end-point:";
1096 status = ensure_remote_cert(ctx);
1097 if(status != SEC_E_OK)
1098 return status;
1100 /* RFC 5929 */
1101 info = CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY, ctx->cert->pCertInfo->SignatureAlgorithm.pszObjId, 0);
1102 if(info && info->u.Algid != CALG_SHA1 && info->u.Algid != CALG_MD5)
1103 hash_alg = info->u.Algid;
1105 hash_size = sizeof(hash);
1106 r = CryptHashCertificate(0, hash_alg, 0, ctx->cert->pbCertEncoded, ctx->cert->cbCertEncoded, hash, &hash_size);
1107 if(!r)
1108 return GetLastError();
1110 bindings->BindingsLength = sizeof(*bindings->Bindings) + sizeof(prefix)-1 + hash_size;
1111 bindings->Bindings = heap_alloc_zero(bindings->BindingsLength);
1112 if(!bindings->Bindings)
1113 return SEC_E_INSUFFICIENT_MEMORY;
1115 bindings->Bindings->cbApplicationDataLength = sizeof(prefix)-1 + hash_size;
1116 bindings->Bindings->dwApplicationDataOffset = sizeof(*bindings->Bindings);
1118 p = (char*)(bindings->Bindings+1);
1119 memcpy(p, prefix, sizeof(prefix)-1);
1120 p += sizeof(prefix)-1;
1121 memcpy(p, hash, hash_size);
1122 return SEC_E_OK;
1125 default:
1126 FIXME("Unhandled attribute %#x\n", attribute);
1127 return SEC_E_UNSUPPORTED_FUNCTION;
1131 static SECURITY_STATUS SEC_ENTRY schan_QueryContextAttributesA(
1132 PCtxtHandle context_handle, ULONG attribute, PVOID buffer)
1134 TRACE("context_handle %p, attribute %#x, buffer %p\n",
1135 context_handle, attribute, buffer);
1137 switch(attribute)
1139 case SECPKG_ATTR_STREAM_SIZES:
1140 return schan_QueryContextAttributesW(context_handle, attribute, buffer);
1141 case SECPKG_ATTR_KEY_INFO:
1143 SECURITY_STATUS status = schan_QueryContextAttributesW(context_handle, attribute, buffer);
1144 if (status == SEC_E_OK)
1146 SecPkgContext_KeyInfoA *info = buffer;
1147 info->sSignatureAlgorithmName = get_alg_name(info->SignatureAlgorithm, FALSE);
1148 info->sEncryptAlgorithmName = get_alg_name(info->EncryptAlgorithm, FALSE);
1150 return status;
1152 case SECPKG_ATTR_REMOTE_CERT_CONTEXT:
1153 return schan_QueryContextAttributesW(context_handle, attribute, buffer);
1154 case SECPKG_ATTR_CONNECTION_INFO:
1155 return schan_QueryContextAttributesW(context_handle, attribute, buffer);
1156 case SECPKG_ATTR_ENDPOINT_BINDINGS:
1157 return schan_QueryContextAttributesW(context_handle, attribute, buffer);
1159 default:
1160 FIXME("Unhandled attribute %#x\n", attribute);
1161 return SEC_E_UNSUPPORTED_FUNCTION;
1165 static int schan_encrypt_message_get_next_buffer(const struct schan_transport *t, struct schan_buffers *s)
1167 SecBuffer *b;
1169 if (s->current_buffer_idx == -1)
1170 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_STREAM_HEADER);
1172 b = &s->desc->pBuffers[s->current_buffer_idx];
1174 if (b->BufferType == SECBUFFER_STREAM_HEADER)
1175 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_DATA);
1177 if (b->BufferType == SECBUFFER_DATA)
1178 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_STREAM_TRAILER);
1180 return -1;
1183 static int schan_encrypt_message_get_next_buffer_token(const struct schan_transport *t, struct schan_buffers *s)
1185 SecBuffer *b;
1187 if (s->current_buffer_idx == -1)
1188 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
1190 b = &s->desc->pBuffers[s->current_buffer_idx];
1192 if (b->BufferType == SECBUFFER_TOKEN)
1194 int idx = schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
1195 if (idx != s->current_buffer_idx) return -1;
1196 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_DATA);
1199 if (b->BufferType == SECBUFFER_DATA)
1201 int idx = schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
1202 if (idx != -1)
1203 idx = schan_find_sec_buffer_idx(s->desc, idx + 1, SECBUFFER_TOKEN);
1204 return idx;
1207 return -1;
1210 static SECURITY_STATUS SEC_ENTRY schan_EncryptMessage(PCtxtHandle context_handle,
1211 ULONG quality, PSecBufferDesc message, ULONG message_seq_no)
1213 struct schan_context *ctx;
1214 struct schan_buffers *b;
1215 SECURITY_STATUS status;
1216 SecBuffer *buffer;
1217 SIZE_T data_size;
1218 SIZE_T length;
1219 char *data;
1220 int idx;
1222 TRACE("context_handle %p, quality %d, message %p, message_seq_no %d\n",
1223 context_handle, quality, message, message_seq_no);
1225 if (!context_handle) return SEC_E_INVALID_HANDLE;
1226 ctx = schan_get_object(context_handle->dwLower, SCHAN_HANDLE_CTX);
1228 dump_buffer_desc(message);
1230 idx = schan_find_sec_buffer_idx(message, 0, SECBUFFER_DATA);
1231 if (idx == -1)
1233 WARN("No data buffer passed\n");
1234 return SEC_E_INTERNAL_ERROR;
1236 buffer = &message->pBuffers[idx];
1238 data_size = buffer->cbBuffer;
1239 data = heap_alloc(data_size);
1240 memcpy(data, buffer->pvBuffer, data_size);
1242 if (schan_find_sec_buffer_idx(message, 0, SECBUFFER_STREAM_HEADER) != -1)
1243 init_schan_buffers(&ctx->transport.out, message, schan_encrypt_message_get_next_buffer);
1244 else
1245 init_schan_buffers(&ctx->transport.out, message, schan_encrypt_message_get_next_buffer_token);
1247 length = data_size;
1248 status = schan_imp_send(ctx->session, data, &length);
1250 TRACE("Sent %ld bytes.\n", length);
1252 if (length != data_size)
1253 status = SEC_E_INTERNAL_ERROR;
1255 b = &ctx->transport.out;
1256 b->desc->pBuffers[b->current_buffer_idx].cbBuffer = b->offset;
1257 heap_free(data);
1259 TRACE("Returning %#x.\n", status);
1261 return status;
1264 static int schan_decrypt_message_get_next_buffer(const struct schan_transport *t, struct schan_buffers *s)
1266 if (s->current_buffer_idx == -1)
1267 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_DATA);
1269 return -1;
1272 static int schan_validate_decrypt_buffer_desc(PSecBufferDesc message)
1274 int data_idx = -1;
1275 unsigned int empty_count = 0;
1276 unsigned int i;
1278 if (message->cBuffers < 4)
1280 WARN("Less than four buffers passed\n");
1281 return -1;
1284 for (i = 0; i < message->cBuffers; ++i)
1286 SecBuffer *b = &message->pBuffers[i];
1287 if (b->BufferType == SECBUFFER_DATA)
1289 if (data_idx != -1)
1291 WARN("More than one data buffer passed\n");
1292 return -1;
1294 data_idx = i;
1296 else if (b->BufferType == SECBUFFER_EMPTY)
1297 ++empty_count;
1300 if (data_idx == -1)
1302 WARN("No data buffer passed\n");
1303 return -1;
1306 if (empty_count < 3)
1308 WARN("Less than three empty buffers passed\n");
1309 return -1;
1312 return data_idx;
1315 static void schan_decrypt_fill_buffer(PSecBufferDesc message, ULONG buffer_type, void *data, ULONG size)
1317 int idx;
1318 SecBuffer *buffer;
1320 idx = schan_find_sec_buffer_idx(message, 0, SECBUFFER_EMPTY);
1321 buffer = &message->pBuffers[idx];
1323 buffer->BufferType = buffer_type;
1324 buffer->pvBuffer = data;
1325 buffer->cbBuffer = size;
1328 static SECURITY_STATUS SEC_ENTRY schan_DecryptMessage(PCtxtHandle context_handle,
1329 PSecBufferDesc message, ULONG message_seq_no, PULONG quality)
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 = heap_alloc(data_size);
1374 init_schan_buffers(&ctx->transport.in, message, schan_decrypt_message_get_next_buffer);
1375 ctx->transport.in.limit = expected_size;
1377 while (received < data_size)
1379 SIZE_T length = data_size - received;
1380 SECURITY_STATUS status = schan_imp_recv(ctx->session, data + received, &length);
1382 if (status == SEC_I_CONTINUE_NEEDED)
1383 break;
1385 if (status != SEC_E_OK)
1387 heap_free(data);
1388 ERR("Returning %x\n", status);
1389 return status;
1392 if (!length)
1393 break;
1395 received += length;
1398 TRACE("Received %ld bytes\n", received);
1400 memcpy(buf_ptr + 5, data, received);
1401 heap_free(data);
1403 schan_decrypt_fill_buffer(message, SECBUFFER_DATA,
1404 buf_ptr + 5, received);
1406 schan_decrypt_fill_buffer(message, SECBUFFER_STREAM_TRAILER,
1407 buf_ptr + 5 + received, buffer->cbBuffer - 5 - received);
1409 if(buffer->cbBuffer > expected_size)
1410 schan_decrypt_fill_buffer(message, SECBUFFER_EXTRA,
1411 buf_ptr + expected_size, buffer->cbBuffer - expected_size);
1413 buffer->BufferType = SECBUFFER_STREAM_HEADER;
1414 buffer->cbBuffer = 5;
1416 return SEC_E_OK;
1419 static SECURITY_STATUS SEC_ENTRY schan_DeleteSecurityContext(PCtxtHandle context_handle)
1421 struct schan_context *ctx;
1423 TRACE("context_handle %p\n", context_handle);
1425 if (!context_handle) return SEC_E_INVALID_HANDLE;
1427 ctx = schan_free_handle(context_handle->dwLower, SCHAN_HANDLE_CTX);
1428 if (!ctx) return SEC_E_INVALID_HANDLE;
1430 if (ctx->cert)
1431 CertFreeCertificateContext(ctx->cert);
1432 schan_imp_dispose_session(ctx->session);
1433 heap_free(ctx);
1435 return SEC_E_OK;
1438 static const SecurityFunctionTableA schanTableA = {
1440 NULL, /* EnumerateSecurityPackagesA */
1441 schan_QueryCredentialsAttributesA,
1442 schan_AcquireCredentialsHandleA,
1443 schan_FreeCredentialsHandle,
1444 NULL, /* Reserved2 */
1445 schan_InitializeSecurityContextA,
1446 NULL, /* AcceptSecurityContext */
1447 NULL, /* CompleteAuthToken */
1448 schan_DeleteSecurityContext,
1449 NULL, /* ApplyControlToken */
1450 schan_QueryContextAttributesA,
1451 NULL, /* ImpersonateSecurityContext */
1452 NULL, /* RevertSecurityContext */
1453 NULL, /* MakeSignature */
1454 NULL, /* VerifySignature */
1455 FreeContextBuffer,
1456 NULL, /* QuerySecurityPackageInfoA */
1457 NULL, /* Reserved3 */
1458 NULL, /* Reserved4 */
1459 NULL, /* ExportSecurityContext */
1460 NULL, /* ImportSecurityContextA */
1461 NULL, /* AddCredentialsA */
1462 NULL, /* Reserved8 */
1463 NULL, /* QuerySecurityContextToken */
1464 schan_EncryptMessage,
1465 schan_DecryptMessage,
1466 NULL, /* SetContextAttributesA */
1469 static const SecurityFunctionTableW schanTableW = {
1471 NULL, /* EnumerateSecurityPackagesW */
1472 schan_QueryCredentialsAttributesW,
1473 schan_AcquireCredentialsHandleW,
1474 schan_FreeCredentialsHandle,
1475 NULL, /* Reserved2 */
1476 schan_InitializeSecurityContextW,
1477 NULL, /* AcceptSecurityContext */
1478 NULL, /* CompleteAuthToken */
1479 schan_DeleteSecurityContext,
1480 NULL, /* ApplyControlToken */
1481 schan_QueryContextAttributesW,
1482 NULL, /* ImpersonateSecurityContext */
1483 NULL, /* RevertSecurityContext */
1484 NULL, /* MakeSignature */
1485 NULL, /* VerifySignature */
1486 FreeContextBuffer,
1487 NULL, /* QuerySecurityPackageInfoW */
1488 NULL, /* Reserved3 */
1489 NULL, /* Reserved4 */
1490 NULL, /* ExportSecurityContext */
1491 NULL, /* ImportSecurityContextW */
1492 NULL, /* AddCredentialsW */
1493 NULL, /* Reserved8 */
1494 NULL, /* QuerySecurityContextToken */
1495 schan_EncryptMessage,
1496 schan_DecryptMessage,
1497 NULL, /* SetContextAttributesW */
1500 static const WCHAR schannelComment[] = { 'S','c','h','a','n','n','e','l',' ',
1501 'S','e','c','u','r','i','t','y',' ','P','a','c','k','a','g','e',0 };
1502 static const WCHAR schannelDllName[] = { 's','c','h','a','n','n','e','l','.','d','l','l',0 };
1504 void SECUR32_initSchannelSP(void)
1506 /* This is what Windows reports. This shouldn't break any applications
1507 * even though the functions are missing, because the wrapper will
1508 * return SEC_E_UNSUPPORTED_FUNCTION if our function is NULL.
1510 static const LONG caps =
1511 SECPKG_FLAG_INTEGRITY |
1512 SECPKG_FLAG_PRIVACY |
1513 SECPKG_FLAG_CONNECTION |
1514 SECPKG_FLAG_MULTI_REQUIRED |
1515 SECPKG_FLAG_EXTENDED_ERROR |
1516 SECPKG_FLAG_IMPERSONATION |
1517 SECPKG_FLAG_ACCEPT_WIN32_NAME |
1518 SECPKG_FLAG_STREAM;
1519 static const short version = 1;
1520 static const LONG maxToken = 16384;
1521 SEC_WCHAR *uniSPName = (SEC_WCHAR *)UNISP_NAME_W,
1522 *schannel = (SEC_WCHAR *)SCHANNEL_NAME_W;
1523 const SecPkgInfoW info[] = {
1524 { caps, version, UNISP_RPC_ID, maxToken, uniSPName, uniSPName },
1525 { caps, version, UNISP_RPC_ID, maxToken, schannel,
1526 (SEC_WCHAR *)schannelComment },
1528 SecureProvider *provider;
1530 if (!schan_imp_init())
1531 return;
1533 schan_handle_table = heap_alloc(64 * sizeof(*schan_handle_table));
1534 if (!schan_handle_table)
1536 ERR("Failed to allocate schannel handle table.\n");
1537 goto fail;
1539 schan_handle_table_size = 64;
1541 provider = SECUR32_addProvider(&schanTableA, &schanTableW, schannelDllName);
1542 if (!provider)
1544 ERR("Failed to add schannel provider.\n");
1545 goto fail;
1548 SECUR32_addPackages(provider, sizeof(info) / sizeof(info[0]), NULL, info);
1550 return;
1552 fail:
1553 heap_free(schan_handle_table);
1554 schan_handle_table = NULL;
1555 schan_imp_deinit();
1556 return;
1559 void SECUR32_deinitSchannelSP(void)
1561 SIZE_T i = schan_handle_count;
1563 if (!schan_handle_table) return;
1565 /* deinitialized sessions first because a pointer to the credentials
1566 * may be stored for the session. */
1567 while (i--)
1569 if (schan_handle_table[i].type == SCHAN_HANDLE_CTX)
1571 struct schan_context *ctx = schan_free_handle(i, SCHAN_HANDLE_CTX);
1572 schan_imp_dispose_session(ctx->session);
1573 heap_free(ctx);
1576 i = schan_handle_count;
1577 while (i--)
1579 if (schan_handle_table[i].type != SCHAN_HANDLE_FREE)
1581 struct schan_credentials *cred;
1582 cred = schan_free_handle(i, SCHAN_HANDLE_CRED);
1583 schan_imp_free_certificate_credentials(cred);
1584 heap_free(cred);
1587 heap_free(schan_handle_table);
1588 schan_imp_deinit();
1591 #else /* SONAME_LIBGNUTLS || HAVE_SECURITY_SECURITY_H */
1593 void SECUR32_initSchannelSP(void)
1595 ERR("TLS library not found, SSL connections will fail\n");
1598 void SECUR32_deinitSchannelSP(void) {}
1600 #endif /* SONAME_LIBGNUTLS || HAVE_SECURITY_SECURITY_H */