nsiproxy: Introduce IOCTL_NSIPROXY_WINE_GET_ALL_PARAMETERS.
[wine.git] / dlls / secur32 / schannel.c
blob515f01d08a373e38072147a9523d9bd0320e7ed9
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.
21 #include <assert.h>
22 #include <stdarg.h>
23 #include <stdlib.h>
24 #include <errno.h>
26 #define NONAMELESSUNION
27 #include "windef.h"
28 #include "winbase.h"
29 #include "winternl.h"
30 #include "winreg.h"
31 #include "winnls.h"
32 #include "lmcons.h"
33 #include "sspi.h"
34 #include "schannel.h"
36 #include "wine/debug.h"
37 #include "secur32_priv.h"
39 WINE_DEFAULT_DEBUG_CHANNEL(secur32);
41 const struct schan_funcs *schan_funcs = NULL;
43 #define SCHAN_INVALID_HANDLE ~0UL
45 enum schan_handle_type
47 SCHAN_HANDLE_CRED,
48 SCHAN_HANDLE_CTX,
49 SCHAN_HANDLE_FREE
52 struct schan_handle
54 void *object;
55 enum schan_handle_type type;
58 struct schan_context
60 schan_session session;
61 struct schan_transport transport;
62 ULONG req_ctx_attr;
63 const CERT_CONTEXT *cert;
64 SIZE_T header_size;
67 static struct schan_handle *schan_handle_table;
68 static struct schan_handle *schan_free_handles;
69 static SIZE_T schan_handle_table_size;
70 static SIZE_T schan_handle_count;
72 /* Protocols enabled, only those may be used for the connection. */
73 static DWORD config_enabled_protocols;
75 /* Protocols disabled by default. They are enabled for using, but disabled when caller asks for default settings. */
76 static DWORD config_default_disabled_protocols;
78 static ULONG_PTR schan_alloc_handle(void *object, enum schan_handle_type type)
80 struct schan_handle *handle;
82 if (schan_free_handles)
84 DWORD index = schan_free_handles - schan_handle_table;
85 /* Use a free handle */
86 handle = schan_free_handles;
87 if (handle->type != SCHAN_HANDLE_FREE)
89 ERR("Handle %d(%p) is in the free list, but has type %#x.\n", index, handle, handle->type);
90 return SCHAN_INVALID_HANDLE;
92 schan_free_handles = handle->object;
93 handle->object = object;
94 handle->type = type;
96 return index;
98 if (!(schan_handle_count < schan_handle_table_size))
100 /* Grow the table */
101 SIZE_T new_size = schan_handle_table_size + (schan_handle_table_size >> 1);
102 struct schan_handle *new_table = realloc(schan_handle_table, new_size * sizeof(*schan_handle_table));
103 if (!new_table)
105 ERR("Failed to grow the handle table\n");
106 return SCHAN_INVALID_HANDLE;
108 schan_handle_table = new_table;
109 schan_handle_table_size = new_size;
112 handle = &schan_handle_table[schan_handle_count++];
113 handle->object = object;
114 handle->type = type;
116 return handle - schan_handle_table;
119 static void *schan_free_handle(ULONG_PTR handle_idx, enum schan_handle_type type)
121 struct schan_handle *handle;
122 void *object;
124 if (handle_idx == SCHAN_INVALID_HANDLE) return NULL;
125 if (handle_idx >= schan_handle_count) return NULL;
126 handle = &schan_handle_table[handle_idx];
127 if (handle->type != type)
129 ERR("Handle %ld(%p) is not of type %#x\n", handle_idx, handle, type);
130 return NULL;
133 object = handle->object;
134 handle->object = schan_free_handles;
135 handle->type = SCHAN_HANDLE_FREE;
136 schan_free_handles = handle;
138 return object;
141 static void *schan_get_object(ULONG_PTR handle_idx, enum schan_handle_type type)
143 struct schan_handle *handle;
145 if (handle_idx == SCHAN_INVALID_HANDLE) return NULL;
146 if (handle_idx >= schan_handle_count) return NULL;
147 handle = &schan_handle_table[handle_idx];
148 if (handle->type != type)
150 ERR("Handle %ld(%p) is not of type %#x\n", handle_idx, handle, type);
151 return NULL;
154 return handle->object;
157 static void read_config(void)
159 DWORD enabled = 0, default_disabled = 0;
160 HKEY protocols_key, key;
161 WCHAR subkey_name[64];
162 unsigned i;
163 DWORD res;
165 static BOOL config_read = FALSE;
166 static const struct {
167 WCHAR key_name[20];
168 DWORD prot_client_flag;
169 BOOL enabled; /* If no config is present, enable the protocol */
170 BOOL disabled_by_default; /* Disable if caller asks for default protocol set */
171 } protocol_config_keys[] = {
172 { L"SSL 2.0", SP_PROT_SSL2_CLIENT, FALSE, TRUE }, /* NOTE: TRUE, TRUE on Windows */
173 { L"SSL 3.0", SP_PROT_SSL3_CLIENT, TRUE, FALSE },
174 { L"TLS 1.0", SP_PROT_TLS1_0_CLIENT, TRUE, FALSE },
175 { L"TLS 1.1", SP_PROT_TLS1_1_CLIENT, TRUE, FALSE /* NOTE: not enabled by default on Windows */ },
176 { L"TLS 1.2", SP_PROT_TLS1_2_CLIENT, TRUE, FALSE /* NOTE: not enabled by default on Windows */ },
177 { L"DTLS 1.0", SP_PROT_DTLS1_0_CLIENT, TRUE, TRUE },
178 { L"DTLS 1.2", SP_PROT_DTLS1_2_CLIENT, TRUE, TRUE },
181 /* No need for thread safety */
182 if(config_read)
183 return;
185 res = RegOpenKeyExW(HKEY_LOCAL_MACHINE,
186 L"SYSTEM\\CurrentControlSet\\Control\\SecurityProviders\\SCHANNEL\\Protocols", 0, KEY_READ,
187 &protocols_key);
188 if(res == ERROR_SUCCESS) {
189 DWORD type, size, value;
191 for(i = 0; i < ARRAY_SIZE(protocol_config_keys); i++) {
192 wcscpy(subkey_name, protocol_config_keys[i].key_name);
193 wcscat(subkey_name, L"\\Client");
194 res = RegOpenKeyExW(protocols_key, subkey_name, 0, KEY_READ, &key);
195 if(res != ERROR_SUCCESS) {
196 if(protocol_config_keys[i].enabled)
197 enabled |= protocol_config_keys[i].prot_client_flag;
198 if(protocol_config_keys[i].disabled_by_default)
199 default_disabled |= protocol_config_keys[i].prot_client_flag;
200 continue;
203 size = sizeof(value);
204 res = RegQueryValueExW(key, L"enabled", NULL, &type, (BYTE *)&value, &size);
205 if(res == ERROR_SUCCESS) {
206 if(type == REG_DWORD && value)
207 enabled |= protocol_config_keys[i].prot_client_flag;
208 }else if(protocol_config_keys[i].enabled) {
209 enabled |= protocol_config_keys[i].prot_client_flag;
212 size = sizeof(value);
213 res = RegQueryValueExW(key, L"DisabledByDefault", NULL, &type, (BYTE *)&value, &size);
214 if(res == ERROR_SUCCESS) {
215 if(type != REG_DWORD || value)
216 default_disabled |= protocol_config_keys[i].prot_client_flag;
217 }else if(protocol_config_keys[i].disabled_by_default) {
218 default_disabled |= protocol_config_keys[i].prot_client_flag;
221 RegCloseKey(key);
223 }else {
224 /* No config, enable all known protocols. */
225 for(i = 0; i < ARRAY_SIZE(protocol_config_keys); i++) {
226 if(protocol_config_keys[i].enabled)
227 enabled |= protocol_config_keys[i].prot_client_flag;
228 if(protocol_config_keys[i].disabled_by_default)
229 default_disabled |= protocol_config_keys[i].prot_client_flag;
233 RegCloseKey(protocols_key);
235 config_enabled_protocols = enabled & schan_funcs->get_enabled_protocols();
236 config_default_disabled_protocols = default_disabled;
237 config_read = TRUE;
239 TRACE("enabled %x, disabled by default %x\n", config_enabled_protocols, config_default_disabled_protocols);
242 static SECURITY_STATUS schan_QueryCredentialsAttributes(
243 PCredHandle phCredential, ULONG ulAttribute, VOID *pBuffer)
245 struct schan_credentials *cred;
246 SECURITY_STATUS ret;
248 cred = schan_get_object(phCredential->dwLower, SCHAN_HANDLE_CRED);
249 if(!cred)
250 return SEC_E_INVALID_HANDLE;
252 switch (ulAttribute)
254 case SECPKG_ATTR_SUPPORTED_ALGS:
255 if (pBuffer)
257 /* FIXME: get from CryptoAPI */
258 FIXME("SECPKG_ATTR_SUPPORTED_ALGS: stub\n");
259 ret = SEC_E_UNSUPPORTED_FUNCTION;
261 else
262 ret = SEC_E_INTERNAL_ERROR;
263 break;
264 case SECPKG_ATTR_CIPHER_STRENGTHS:
265 if (pBuffer)
267 SecPkgCred_CipherStrengths *r = pBuffer;
269 /* FIXME: get from CryptoAPI */
270 FIXME("SECPKG_ATTR_CIPHER_STRENGTHS: semi-stub\n");
271 r->dwMinimumCipherStrength = 40;
272 r->dwMaximumCipherStrength = 168;
273 ret = SEC_E_OK;
275 else
276 ret = SEC_E_INTERNAL_ERROR;
277 break;
278 case SECPKG_ATTR_SUPPORTED_PROTOCOLS:
279 if(pBuffer) {
280 /* Regardless of MSDN documentation, tests show that this attribute takes into account
281 * what protocols are enabled for given credential. */
282 ((SecPkgCred_SupportedProtocols*)pBuffer)->grbitProtocol = cred->enabled_protocols;
283 ret = SEC_E_OK;
284 }else {
285 ret = SEC_E_INTERNAL_ERROR;
287 break;
288 default:
289 ret = SEC_E_UNSUPPORTED_FUNCTION;
291 return ret;
294 static SECURITY_STATUS SEC_ENTRY schan_QueryCredentialsAttributesA(
295 PCredHandle phCredential, ULONG ulAttribute, PVOID pBuffer)
297 SECURITY_STATUS ret;
299 TRACE("(%p, %d, %p)\n", phCredential, ulAttribute, pBuffer);
301 switch (ulAttribute)
303 case SECPKG_CRED_ATTR_NAMES:
304 FIXME("SECPKG_CRED_ATTR_NAMES: stub\n");
305 ret = SEC_E_UNSUPPORTED_FUNCTION;
306 break;
307 default:
308 ret = schan_QueryCredentialsAttributes(phCredential, ulAttribute,
309 pBuffer);
311 return ret;
314 static SECURITY_STATUS SEC_ENTRY schan_QueryCredentialsAttributesW(
315 PCredHandle phCredential, ULONG ulAttribute, PVOID pBuffer)
317 SECURITY_STATUS ret;
319 TRACE("(%p, %d, %p)\n", phCredential, ulAttribute, pBuffer);
321 switch (ulAttribute)
323 case SECPKG_CRED_ATTR_NAMES:
324 FIXME("SECPKG_CRED_ATTR_NAMES: stub\n");
325 ret = SEC_E_UNSUPPORTED_FUNCTION;
326 break;
327 default:
328 ret = schan_QueryCredentialsAttributes(phCredential, ulAttribute,
329 pBuffer);
331 return ret;
334 static SECURITY_STATUS get_cert(const SCHANNEL_CRED *cred, CERT_CONTEXT const **cert)
336 SECURITY_STATUS status;
337 DWORD i;
339 TRACE("dwVersion = %u\n", cred->dwVersion);
340 TRACE("cCreds = %u\n", cred->cCreds);
341 TRACE("paCred = %p\n", cred->paCred);
342 TRACE("hRootStore = %p\n", cred->hRootStore);
343 TRACE("cMappers = %u\n", cred->cMappers);
344 TRACE("cSupportedAlgs = %u:\n", cred->cSupportedAlgs);
345 for (i = 0; i < cred->cSupportedAlgs; i++) TRACE("%08x\n", cred->palgSupportedAlgs[i]);
346 TRACE("grbitEnabledProtocols = %08x\n", cred->grbitEnabledProtocols);
347 TRACE("dwMinimumCipherStrength = %u\n", cred->dwMinimumCipherStrength);
348 TRACE("dwMaximumCipherStrength = %u\n", cred->dwMaximumCipherStrength);
349 TRACE("dwSessionLifespan = %u\n", cred->dwSessionLifespan);
350 TRACE("dwFlags = %08x\n", cred->dwFlags);
351 TRACE("dwCredFormat = %u\n", cred->dwCredFormat);
353 switch (cred->dwVersion)
355 case SCH_CRED_V3:
356 case SCHANNEL_CRED_VERSION:
357 break;
358 default:
359 return SEC_E_INTERNAL_ERROR;
362 if (!cred->cCreds) status = SEC_E_NO_CREDENTIALS;
363 else if (cred->cCreds > 1) status = SEC_E_UNKNOWN_CREDENTIALS;
364 else
366 DWORD spec;
367 HCRYPTPROV prov;
368 BOOL free;
370 if (CryptAcquireCertificatePrivateKey(cred->paCred[0], CRYPT_ACQUIRE_CACHE_FLAG, NULL, &prov, &spec, &free))
372 if (free) CryptReleaseContext(prov, 0);
373 *cert = cred->paCred[0];
374 status = SEC_E_OK;
376 else status = SEC_E_UNKNOWN_CREDENTIALS;
379 return status;
382 static WCHAR *get_key_container_path(const CERT_CONTEXT *ctx)
384 CERT_KEY_CONTEXT keyctx;
385 DWORD size = sizeof(keyctx), prov_size = 0;
386 CRYPT_KEY_PROV_INFO *prov;
387 WCHAR username[UNLEN + 1], *ret = NULL;
388 DWORD len = ARRAY_SIZE(username);
390 if (CertGetCertificateContextProperty(ctx, CERT_KEY_CONTEXT_PROP_ID, &keyctx, &size))
392 char *str;
393 if (!CryptGetProvParam(keyctx.hCryptProv, PP_CONTAINER, NULL, &size, 0)) return NULL;
394 if (!(str = RtlAllocateHeap(GetProcessHeap(), 0, size))) return NULL;
395 if (!CryptGetProvParam(keyctx.hCryptProv, PP_CONTAINER, (BYTE *)str, &size, 0)) return NULL;
397 len = MultiByteToWideChar(CP_ACP, 0, str, -1, NULL, 0);
398 if (!(ret = RtlAllocateHeap(GetProcessHeap(), 0, sizeof(L"Software\\Wine\\Crypto\\RSA\\") + len * sizeof(WCHAR))))
400 RtlFreeHeap(GetProcessHeap(), 0, str);
401 return NULL;
403 wcscpy(ret, L"Software\\Wine\\Crypto\\RSA\\");
404 MultiByteToWideChar(CP_ACP, 0, str, -1, ret + wcslen(ret), len);
405 RtlFreeHeap(GetProcessHeap(), 0, str);
407 else if (CertGetCertificateContextProperty(ctx, CERT_KEY_PROV_INFO_PROP_ID, NULL, &prov_size))
409 if (!(prov = RtlAllocateHeap(GetProcessHeap(), 0, prov_size))) return NULL;
410 if (!CertGetCertificateContextProperty(ctx, CERT_KEY_PROV_INFO_PROP_ID, prov, &prov_size))
412 RtlFreeHeap(GetProcessHeap(), 0, prov);
413 return NULL;
415 if (!(ret = RtlAllocateHeap(GetProcessHeap(), 0,
416 sizeof(L"Software\\Wine\\Crypto\\RSA\\") + wcslen(prov->pwszContainerName) * sizeof(WCHAR))))
418 RtlFreeHeap(GetProcessHeap(), 0, prov);
419 return NULL;
421 wcscpy(ret, L"Software\\Wine\\Crypto\\RSA\\");
422 wcscat(ret, prov->pwszContainerName);
423 RtlFreeHeap(GetProcessHeap(), 0, prov);
426 if (!ret && GetUserNameW(username, &len) &&
427 (ret = RtlAllocateHeap(GetProcessHeap(), 0, sizeof(L"Software\\Wine\\Crypto\\RSA\\") + len * sizeof(WCHAR))))
429 wcscpy(ret, L"Software\\Wine\\Crypto\\RSA\\");
430 wcscat(ret, username);
433 return ret;
436 #define MAX_LEAD_BYTES 8
437 static BYTE *get_key_blob(const CERT_CONTEXT *ctx, DWORD *size)
439 BYTE *buf, *ret = NULL;
440 DATA_BLOB blob_in, blob_out;
441 DWORD spec = 0, type, len;
442 WCHAR *path;
443 HKEY hkey;
445 if (!(path = get_key_container_path(ctx))) return NULL;
446 if (RegOpenKeyExW(HKEY_CURRENT_USER, path, 0, KEY_READ, &hkey))
448 RtlFreeHeap(GetProcessHeap(), 0, path);
449 return NULL;
451 RtlFreeHeap(GetProcessHeap(), 0, path);
453 if (!RegQueryValueExW(hkey, L"KeyExchangeKeyPair", 0, &type, NULL, &len)) spec = AT_KEYEXCHANGE;
454 else if (!RegQueryValueExW(hkey, L"SignatureKeyPair", 0, &type, NULL, &len)) spec = AT_SIGNATURE;
455 else
457 RegCloseKey(hkey);
458 return NULL;
461 if (!(buf = RtlAllocateHeap(GetProcessHeap(), 0, len + MAX_LEAD_BYTES)))
463 RegCloseKey(hkey);
464 return NULL;
467 if (!RegQueryValueExW(hkey, (spec == AT_KEYEXCHANGE) ? L"KeyExchangeKeyPair" : L"SignatureKeyPair", 0,
468 &type, buf, &len))
470 blob_in.pbData = buf;
471 blob_in.cbData = len;
472 if (CryptUnprotectData(&blob_in, NULL, NULL, NULL, NULL, 0, &blob_out))
474 assert(blob_in.cbData >= blob_out.cbData);
475 memcpy(buf, blob_out.pbData, blob_out.cbData);
476 LocalFree(blob_out.pbData);
477 *size = blob_out.cbData + MAX_LEAD_BYTES;
478 ret = buf;
481 else RtlFreeHeap(GetProcessHeap(), 0, buf);
483 RegCloseKey(hkey);
484 return ret;
487 static SECURITY_STATUS schan_AcquireClientCredentials(const SCHANNEL_CRED *schanCred,
488 PCredHandle phCredential, PTimeStamp ptsExpiry)
490 struct schan_credentials *creds;
491 unsigned enabled_protocols;
492 ULONG_PTR handle;
493 SECURITY_STATUS status = SEC_E_OK;
494 const CERT_CONTEXT *cert = NULL;
495 DATA_BLOB key_blob = {0};
497 TRACE("schanCred %p, phCredential %p, ptsExpiry %p\n", schanCred, phCredential, ptsExpiry);
499 if (schanCred)
501 const unsigned dtls_protocols = SP_PROT_DTLS_CLIENT | SP_PROT_DTLS1_2_CLIENT;
502 const unsigned tls_protocols = SP_PROT_TLS1_CLIENT | SP_PROT_TLS1_0_CLIENT | SP_PROT_TLS1_1_CLIENT |
503 SP_PROT_TLS1_2_CLIENT | SP_PROT_TLS1_3_CLIENT;
505 status = get_cert(schanCred, &cert);
506 if (status != SEC_E_OK && status != SEC_E_NO_CREDENTIALS)
507 return status;
509 if ((schanCred->grbitEnabledProtocols & tls_protocols) &&
510 (schanCred->grbitEnabledProtocols & dtls_protocols)) return SEC_E_ALGORITHM_MISMATCH;
512 status = SEC_E_OK;
515 read_config();
516 if(schanCred && schanCred->grbitEnabledProtocols)
517 enabled_protocols = schanCred->grbitEnabledProtocols & config_enabled_protocols;
518 else
519 enabled_protocols = config_enabled_protocols & ~config_default_disabled_protocols;
520 if(!enabled_protocols) {
521 ERR("Could not find matching protocol\n");
522 return SEC_E_NO_AUTHENTICATING_AUTHORITY;
525 if (!(creds = malloc(sizeof(*creds)))) return SEC_E_INSUFFICIENT_MEMORY;
526 creds->credential_use = SECPKG_CRED_OUTBOUND;
527 creds->enabled_protocols = enabled_protocols;
529 if (cert && !(key_blob.pbData = get_key_blob(cert, &key_blob.cbData))) goto fail;
530 if (!schan_funcs->allocate_certificate_credentials(creds, cert, &key_blob)) goto fail;
531 RtlFreeHeap(GetProcessHeap(), 0, key_blob.pbData);
533 handle = schan_alloc_handle(creds, SCHAN_HANDLE_CRED);
534 if (handle == SCHAN_INVALID_HANDLE) goto fail;
536 phCredential->dwLower = handle;
537 phCredential->dwUpper = 0;
539 /* Outbound credentials have no expiry */
540 if (ptsExpiry)
542 ptsExpiry->LowPart = 0;
543 ptsExpiry->HighPart = 0;
546 return status;
548 fail:
549 free(creds);
550 RtlFreeHeap(GetProcessHeap(), 0, key_blob.pbData);
551 return SEC_E_INTERNAL_ERROR;
554 static SECURITY_STATUS schan_AcquireServerCredentials(const SCHANNEL_CRED *schanCred,
555 PCredHandle phCredential, PTimeStamp ptsExpiry)
557 SECURITY_STATUS status;
558 const CERT_CONTEXT *cert = NULL;
560 TRACE("schanCred %p, phCredential %p, ptsExpiry %p\n", schanCred, phCredential, ptsExpiry);
562 if (!schanCred) return SEC_E_NO_CREDENTIALS;
564 status = get_cert(schanCred, &cert);
565 if (status == SEC_E_OK)
567 ULONG_PTR handle;
568 struct schan_credentials *creds;
570 if (!(creds = calloc(1, sizeof(*creds)))) return SEC_E_INSUFFICIENT_MEMORY;
571 creds->credential_use = SECPKG_CRED_INBOUND;
573 handle = schan_alloc_handle(creds, SCHAN_HANDLE_CRED);
574 if (handle == SCHAN_INVALID_HANDLE)
576 free(creds);
577 return SEC_E_INTERNAL_ERROR;
580 phCredential->dwLower = handle;
581 phCredential->dwUpper = 0;
583 /* FIXME: get expiry from cert */
585 return status;
588 static SECURITY_STATUS schan_AcquireCredentialsHandle(ULONG fCredentialUse,
589 const SCHANNEL_CRED *schanCred, PCredHandle phCredential, PTimeStamp ptsExpiry)
591 SECURITY_STATUS ret;
593 if (fCredentialUse == SECPKG_CRED_OUTBOUND)
594 ret = schan_AcquireClientCredentials(schanCred, phCredential,
595 ptsExpiry);
596 else
597 ret = schan_AcquireServerCredentials(schanCred, phCredential,
598 ptsExpiry);
599 return ret;
602 static SECURITY_STATUS SEC_ENTRY schan_AcquireCredentialsHandleA(
603 SEC_CHAR *pszPrincipal, SEC_CHAR *pszPackage, ULONG fCredentialUse,
604 PLUID pLogonID, PVOID pAuthData, SEC_GET_KEY_FN pGetKeyFn,
605 PVOID pGetKeyArgument, PCredHandle phCredential, PTimeStamp ptsExpiry)
607 TRACE("(%s, %s, 0x%08x, %p, %p, %p, %p, %p, %p)\n",
608 debugstr_a(pszPrincipal), debugstr_a(pszPackage), fCredentialUse,
609 pLogonID, pAuthData, pGetKeyFn, pGetKeyArgument, phCredential, ptsExpiry);
610 return schan_AcquireCredentialsHandle(fCredentialUse,
611 pAuthData, phCredential, ptsExpiry);
614 static SECURITY_STATUS SEC_ENTRY schan_AcquireCredentialsHandleW(
615 SEC_WCHAR *pszPrincipal, SEC_WCHAR *pszPackage, ULONG fCredentialUse,
616 PLUID pLogonID, PVOID pAuthData, SEC_GET_KEY_FN pGetKeyFn,
617 PVOID pGetKeyArgument, PCredHandle phCredential, PTimeStamp ptsExpiry)
619 TRACE("(%s, %s, 0x%08x, %p, %p, %p, %p, %p, %p)\n",
620 debugstr_w(pszPrincipal), debugstr_w(pszPackage), fCredentialUse,
621 pLogonID, pAuthData, pGetKeyFn, pGetKeyArgument, phCredential, ptsExpiry);
622 return schan_AcquireCredentialsHandle(fCredentialUse,
623 pAuthData, phCredential, ptsExpiry);
626 static SECURITY_STATUS SEC_ENTRY schan_FreeCredentialsHandle(
627 PCredHandle phCredential)
629 struct schan_credentials *creds;
631 TRACE("phCredential %p\n", phCredential);
633 if (!phCredential) return SEC_E_INVALID_HANDLE;
635 creds = schan_free_handle(phCredential->dwLower, SCHAN_HANDLE_CRED);
636 if (!creds) return SEC_E_INVALID_HANDLE;
638 if (creds->credential_use == SECPKG_CRED_OUTBOUND) schan_funcs->free_certificate_credentials(creds);
639 free(creds);
640 return SEC_E_OK;
643 static void init_schan_buffers(struct schan_buffers *s, const PSecBufferDesc desc,
644 int (*get_next_buffer)(const struct schan_transport *, struct schan_buffers *))
646 s->offset = 0;
647 s->limit = ~0UL;
648 s->desc = desc;
649 s->current_buffer_idx = -1;
650 s->allow_buffer_resize = FALSE;
651 s->get_next_buffer = get_next_buffer;
654 static int schan_find_sec_buffer_idx(const SecBufferDesc *desc, unsigned int start_idx, ULONG buffer_type)
656 unsigned int i;
657 PSecBuffer buffer;
659 for (i = start_idx; i < desc->cBuffers; ++i)
661 buffer = &desc->pBuffers[i];
662 if (buffer->BufferType == buffer_type) return i;
665 return -1;
668 static void schan_resize_current_buffer(const struct schan_buffers *s, SIZE_T min_size)
670 SecBuffer *b = &s->desc->pBuffers[s->current_buffer_idx];
671 SIZE_T new_size = b->cbBuffer ? b->cbBuffer * 2 : 128;
672 void *new_data;
674 if (b->cbBuffer >= min_size || !s->allow_buffer_resize || min_size > UINT_MAX / 2) return;
676 while (new_size < min_size) new_size *= 2;
678 if (b->pvBuffer) /* freed with FreeContextBuffer */
679 new_data = RtlReAllocateHeap(GetProcessHeap(), 0, b->pvBuffer, new_size);
680 else
681 new_data = RtlAllocateHeap(GetProcessHeap(), 0, new_size);
683 if (!new_data)
685 TRACE("Failed to resize %p from %d to %ld\n", b->pvBuffer, b->cbBuffer, new_size);
686 return;
689 b->cbBuffer = new_size;
690 b->pvBuffer = new_data;
693 static char * CDECL schan_get_buffer(const struct schan_transport *t, struct schan_buffers *s, SIZE_T *count)
695 SIZE_T max_count;
696 PSecBuffer buffer;
698 if (!s->desc)
700 TRACE("No desc\n");
701 return NULL;
704 if (s->current_buffer_idx == -1)
706 /* Initial buffer */
707 int buffer_idx = s->get_next_buffer(t, s);
708 if (buffer_idx == -1)
710 TRACE("No next buffer\n");
711 return NULL;
713 s->current_buffer_idx = buffer_idx;
716 buffer = &s->desc->pBuffers[s->current_buffer_idx];
717 TRACE("Using buffer %d: cbBuffer %d, BufferType %#x, pvBuffer %p\n", s->current_buffer_idx, buffer->cbBuffer, buffer->BufferType, buffer->pvBuffer);
719 schan_resize_current_buffer(s, s->offset + *count);
720 max_count = buffer->cbBuffer - s->offset;
721 if (s->limit != ~0UL && s->limit < max_count)
722 max_count = s->limit;
723 if (!max_count)
725 int buffer_idx;
727 s->allow_buffer_resize = FALSE;
728 buffer_idx = s->get_next_buffer(t, s);
729 if (buffer_idx == -1)
731 TRACE("No next buffer\n");
732 return NULL;
734 s->current_buffer_idx = buffer_idx;
735 s->offset = 0;
736 return schan_get_buffer(t, s, count);
739 if (*count > max_count)
740 *count = max_count;
741 if (s->limit != ~0UL)
742 s->limit -= *count;
744 return (char *)buffer->pvBuffer + s->offset;
747 /* schan_pull
748 * Read data from the transport input buffer.
750 * t - The session transport object.
751 * buff - The buffer into which to store the read data. Must be at least
752 * *buff_len bytes in length.
753 * buff_len - On input, *buff_len is the desired length to read. On successful
754 * return, *buff_len is the number of bytes actually read.
756 * Returns:
757 * 0 on success, in which case:
758 * *buff_len == 0 indicates end of file.
759 * *buff_len > 0 indicates that some data was read. May be less than
760 * what was requested, in which case the caller should call again if/
761 * when they want more.
762 * -1 when no data could be read without blocking
763 * another errno-style error value on failure
765 static int CDECL schan_pull(struct schan_transport *t, void *buff, size_t *buff_len)
767 char *b;
768 SIZE_T local_len = *buff_len;
770 TRACE("Pull %lu bytes\n", local_len);
772 *buff_len = 0;
774 b = schan_get_buffer(t, &t->in, &local_len);
775 if (!b)
776 return -1;
778 memcpy(buff, b, local_len);
779 t->in.offset += local_len;
781 TRACE("Read %lu bytes\n", local_len);
783 *buff_len = local_len;
784 return 0;
787 /* schan_push
788 * Write data to the transport output buffer.
790 * t - The session transport object.
791 * buff - The buffer of data to write. Must be at least *buff_len bytes in length.
792 * buff_len - On input, *buff_len is the desired length to write. On successful
793 * return, *buff_len is the number of bytes actually written.
795 * Returns:
796 * 0 on success
797 * *buff_len will be > 0 indicating how much data was written. May be less
798 * than what was requested, in which case the caller should call again
799 * if/when they want to write more.
800 * -1 when no data could be written without blocking
801 * another errno-style error value on failure
803 static int CDECL schan_push(struct schan_transport *t, const void *buff, size_t *buff_len)
805 char *b;
806 SIZE_T local_len = *buff_len;
808 TRACE("Push %lu bytes\n", local_len);
810 *buff_len = 0;
812 b = schan_get_buffer(t, &t->out, &local_len);
813 if (!b)
814 return -1;
816 memcpy(b, buff, local_len);
817 t->out.offset += local_len;
819 TRACE("Wrote %lu bytes\n", local_len);
821 *buff_len = local_len;
822 return 0;
825 static schan_session CDECL schan_get_session_for_transport(struct schan_transport* t)
827 return t->ctx->session;
830 static int schan_init_sec_ctx_get_next_input_buffer(const struct schan_transport *t, struct schan_buffers *s)
832 if (s->current_buffer_idx != -1)
833 return -1;
834 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
837 static int schan_init_sec_ctx_get_next_output_buffer(const struct schan_transport *t, struct schan_buffers *s)
839 if (s->current_buffer_idx == -1)
841 int idx = schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
842 if (t->ctx->req_ctx_attr & ISC_REQ_ALLOCATE_MEMORY)
844 if (idx == -1)
846 idx = schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_EMPTY);
847 if (idx != -1) s->desc->pBuffers[idx].BufferType = SECBUFFER_TOKEN;
849 if (idx != -1 && !s->desc->pBuffers[idx].pvBuffer)
851 s->desc->pBuffers[idx].cbBuffer = 0;
852 s->allow_buffer_resize = TRUE;
855 return idx;
858 return -1;
861 static void dump_buffer_desc(SecBufferDesc *desc)
863 unsigned int i;
865 if (!desc) return;
866 TRACE("Buffer desc %p:\n", desc);
867 for (i = 0; i < desc->cBuffers; ++i)
869 SecBuffer *b = &desc->pBuffers[i];
870 TRACE("\tbuffer %u: cbBuffer %d, BufferType %#x pvBuffer %p\n", i, b->cbBuffer, b->BufferType, b->pvBuffer);
874 #define HEADER_SIZE_TLS 5
875 #define HEADER_SIZE_DTLS 13
877 static inline SIZE_T read_record_size(const BYTE *buf, SIZE_T header_size)
879 return (buf[header_size - 2] << 8) | buf[header_size - 1];
882 /***********************************************************************
883 * InitializeSecurityContextW
885 static SECURITY_STATUS SEC_ENTRY schan_InitializeSecurityContextW(
886 PCredHandle phCredential, PCtxtHandle phContext, SEC_WCHAR *pszTargetName,
887 ULONG fContextReq, ULONG Reserved1, ULONG TargetDataRep,
888 PSecBufferDesc pInput, ULONG Reserved2, PCtxtHandle phNewContext,
889 PSecBufferDesc pOutput, ULONG *pfContextAttr, PTimeStamp ptsExpiry)
891 struct schan_context *ctx;
892 struct schan_buffers *out_buffers;
893 struct schan_credentials *cred;
894 SIZE_T expected_size = ~0UL;
895 SECURITY_STATUS ret;
896 SecBuffer *buffer;
897 int idx;
899 TRACE("%p %p %s 0x%08x %d %d %p %d %p %p %p %p\n", phCredential, phContext,
900 debugstr_w(pszTargetName), fContextReq, Reserved1, TargetDataRep, pInput,
901 Reserved1, phNewContext, pOutput, pfContextAttr, ptsExpiry);
903 dump_buffer_desc(pInput);
904 dump_buffer_desc(pOutput);
906 if (!phContext)
908 ULONG_PTR handle;
910 if (!phCredential) return SEC_E_INVALID_HANDLE;
912 cred = schan_get_object(phCredential->dwLower, SCHAN_HANDLE_CRED);
913 if (!cred) return SEC_E_INVALID_HANDLE;
915 if (!(cred->credential_use & SECPKG_CRED_OUTBOUND))
917 WARN("Invalid credential use %#x\n", cred->credential_use);
918 return SEC_E_INVALID_HANDLE;
921 if (!(ctx = malloc(sizeof(*ctx)))) return SEC_E_INSUFFICIENT_MEMORY;
923 ctx->cert = NULL;
924 handle = schan_alloc_handle(ctx, SCHAN_HANDLE_CTX);
925 if (handle == SCHAN_INVALID_HANDLE)
927 free(ctx);
928 return SEC_E_INTERNAL_ERROR;
931 if (!schan_funcs->create_session(&ctx->session, cred))
933 schan_free_handle(handle, SCHAN_HANDLE_CTX);
934 free(ctx);
935 return SEC_E_INTERNAL_ERROR;
938 if (cred->enabled_protocols & (SP_PROT_DTLS1_0_CLIENT | SP_PROT_DTLS1_2_CLIENT))
939 ctx->header_size = HEADER_SIZE_DTLS;
940 else
941 ctx->header_size = HEADER_SIZE_TLS;
943 ctx->transport.ctx = ctx;
944 schan_funcs->set_session_transport(ctx->session, &ctx->transport);
946 if (pszTargetName && *pszTargetName)
948 UINT len = WideCharToMultiByte( CP_UNIXCP, 0, pszTargetName, -1, NULL, 0, NULL, NULL );
949 char *target = malloc( len );
951 if (target)
953 WideCharToMultiByte( CP_UNIXCP, 0, pszTargetName, -1, target, len, NULL, NULL );
954 schan_funcs->set_session_target( ctx->session, target );
955 free( target );
959 if (pInput && (idx = schan_find_sec_buffer_idx(pInput, 0, SECBUFFER_APPLICATION_PROTOCOLS)) != -1)
961 buffer = &pInput->pBuffers[idx];
962 schan_funcs->set_application_protocols(ctx->session, buffer->pvBuffer, buffer->cbBuffer);
965 if (pInput && (idx = schan_find_sec_buffer_idx(pInput, 0, SECBUFFER_DTLS_MTU)) != -1)
967 buffer = &pInput->pBuffers[idx];
968 if (buffer->cbBuffer >= sizeof(WORD)) schan_funcs->set_dtls_mtu(ctx->session, *(WORD *)buffer->pvBuffer);
969 else WARN("invalid buffer size %u\n", buffer->cbBuffer);
972 phNewContext->dwLower = handle;
973 phNewContext->dwUpper = 0;
975 else
977 SIZE_T record_size = 0;
978 unsigned char *ptr;
980 ctx = schan_get_object(phContext->dwLower, SCHAN_HANDLE_CTX);
981 if (pInput)
983 idx = schan_find_sec_buffer_idx(pInput, 0, SECBUFFER_TOKEN);
984 if (idx == -1)
985 return SEC_E_INCOMPLETE_MESSAGE;
987 buffer = &pInput->pBuffers[idx];
988 ptr = buffer->pvBuffer;
989 expected_size = 0;
991 while (buffer->cbBuffer > expected_size + ctx->header_size)
993 record_size = ctx->header_size + read_record_size(ptr, ctx->header_size);
995 if (buffer->cbBuffer < expected_size + record_size)
996 break;
998 expected_size += record_size;
999 ptr += record_size;
1002 if (!expected_size)
1004 TRACE("Expected at least %lu bytes, but buffer only contains %u bytes.\n",
1005 max(6, record_size), buffer->cbBuffer);
1006 return SEC_E_INCOMPLETE_MESSAGE;
1009 else return SEC_E_INCOMPLETE_MESSAGE;
1011 TRACE("Using expected_size %lu.\n", expected_size);
1014 ctx->req_ctx_attr = fContextReq;
1016 init_schan_buffers(&ctx->transport.in, pInput, schan_init_sec_ctx_get_next_input_buffer);
1017 ctx->transport.in.limit = expected_size;
1018 init_schan_buffers(&ctx->transport.out, pOutput, schan_init_sec_ctx_get_next_output_buffer);
1020 /* Perform the TLS handshake */
1021 ret = schan_funcs->handshake(ctx->session);
1023 out_buffers = &ctx->transport.out;
1024 if (out_buffers->current_buffer_idx != -1)
1026 SecBuffer *buffer = &out_buffers->desc->pBuffers[out_buffers->current_buffer_idx];
1027 buffer->cbBuffer = out_buffers->offset;
1029 else if (out_buffers->desc && out_buffers->desc->cBuffers > 0)
1031 SecBuffer *buffer = &out_buffers->desc->pBuffers[0];
1032 buffer->cbBuffer = 0;
1035 if(ctx->transport.in.offset && ctx->transport.in.offset != pInput->pBuffers[0].cbBuffer) {
1036 if(pInput->cBuffers<2 || pInput->pBuffers[1].BufferType!=SECBUFFER_EMPTY)
1037 return SEC_E_INVALID_TOKEN;
1039 pInput->pBuffers[1].BufferType = SECBUFFER_EXTRA;
1040 pInput->pBuffers[1].cbBuffer = pInput->pBuffers[0].cbBuffer-ctx->transport.in.offset;
1043 *pfContextAttr = ISC_RET_REPLAY_DETECT | ISC_RET_SEQUENCE_DETECT | ISC_RET_CONFIDENTIALITY | ISC_RET_STREAM;
1044 if (ctx->req_ctx_attr & ISC_REQ_EXTENDED_ERROR) *pfContextAttr |= ISC_RET_EXTENDED_ERROR;
1045 if (ctx->req_ctx_attr & ISC_REQ_DATAGRAM) *pfContextAttr |= ISC_RET_DATAGRAM;
1046 if (ctx->req_ctx_attr & ISC_REQ_ALLOCATE_MEMORY) *pfContextAttr |= ISC_RET_ALLOCATED_MEMORY;
1047 if (ctx->req_ctx_attr & ISC_REQ_USE_SUPPLIED_CREDS) *pfContextAttr |= ISC_RET_USED_SUPPLIED_CREDS;
1048 if (ctx->req_ctx_attr & ISC_REQ_MANUAL_CRED_VALIDATION) *pfContextAttr |= ISC_RET_MANUAL_CRED_VALIDATION;
1050 return ret;
1053 /***********************************************************************
1054 * InitializeSecurityContextA
1056 static SECURITY_STATUS SEC_ENTRY schan_InitializeSecurityContextA(
1057 PCredHandle phCredential, PCtxtHandle phContext, SEC_CHAR *pszTargetName,
1058 ULONG fContextReq, ULONG Reserved1, ULONG TargetDataRep,
1059 PSecBufferDesc pInput, ULONG Reserved2, PCtxtHandle phNewContext,
1060 PSecBufferDesc pOutput, ULONG *pfContextAttr, PTimeStamp ptsExpiry)
1062 SECURITY_STATUS ret;
1063 SEC_WCHAR *target_name = NULL;
1065 TRACE("%p %p %s %d %d %d %p %d %p %p %p %p\n", phCredential, phContext,
1066 debugstr_a(pszTargetName), fContextReq, Reserved1, TargetDataRep, pInput,
1067 Reserved1, phNewContext, pOutput, pfContextAttr, ptsExpiry);
1069 if (pszTargetName)
1071 INT len = MultiByteToWideChar(CP_ACP, 0, pszTargetName, -1, NULL, 0);
1072 if (!(target_name = malloc(len * sizeof(*target_name)))) return SEC_E_INSUFFICIENT_MEMORY;
1073 MultiByteToWideChar(CP_ACP, 0, pszTargetName, -1, target_name, len);
1076 ret = schan_InitializeSecurityContextW(phCredential, phContext, target_name,
1077 fContextReq, Reserved1, TargetDataRep, pInput, Reserved2,
1078 phNewContext, pOutput, pfContextAttr, ptsExpiry);
1080 free(target_name);
1081 return ret;
1084 static void *get_alg_name(ALG_ID id, BOOL wide)
1086 static const struct {
1087 ALG_ID alg_id;
1088 const char* name;
1089 const WCHAR nameW[8];
1090 } alg_name_map[] = {
1091 { CALG_ECDSA, "ECDSA", L"ECDSA" },
1092 { CALG_RSA_SIGN, "RSA", L"RSA" },
1093 { CALG_DES, "DES", L"DES" },
1094 { CALG_RC2, "RC2", L"RC2" },
1095 { CALG_3DES, "3DES", L"3DES" },
1096 { CALG_AES_128, "AES", L"AES" },
1097 { CALG_AES_192, "AES", L"AES" },
1098 { CALG_AES_256, "AES", L"AES" },
1099 { CALG_RC4, "RC4", L"RC4" },
1101 unsigned i;
1103 for (i = 0; i < ARRAY_SIZE(alg_name_map); i++)
1104 if (alg_name_map[i].alg_id == id)
1105 return wide ? (void*)alg_name_map[i].nameW : (void*)alg_name_map[i].name;
1107 FIXME("Unknown ALG_ID %04x\n", id);
1108 return NULL;
1111 static SECURITY_STATUS ensure_remote_cert(struct schan_context *ctx)
1113 HCERTSTORE store;
1114 PCCERT_CONTEXT cert = NULL;
1115 SECURITY_STATUS status;
1116 struct schan_cert_list list;
1118 if (ctx->cert) return SEC_E_OK;
1119 if (!(store = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0, CERT_STORE_CREATE_NEW_FLAG, NULL)))
1120 return GetLastError();
1122 if ((status = schan_funcs->get_session_peer_certificate(ctx->session, &list)) == SEC_E_OK)
1124 unsigned int i;
1125 for (i = 0; i < list.count; i++)
1127 if (!CertAddEncodedCertificateToStore(store, X509_ASN_ENCODING, list.certs[i].pbData,
1128 list.certs[i].cbData, CERT_STORE_ADD_REPLACE_EXISTING,
1129 i ? NULL : &cert))
1131 if (i) CertFreeCertificateContext(cert);
1132 return GetLastError();
1135 RtlFreeHeap(GetProcessHeap(), 0, list.certs);
1138 ctx->cert = cert;
1139 CertCloseStore(store, 0);
1140 return status;
1143 static SECURITY_STATUS SEC_ENTRY schan_QueryContextAttributesW(
1144 PCtxtHandle context_handle, ULONG attribute, PVOID buffer)
1146 struct schan_context *ctx;
1147 SECURITY_STATUS status;
1149 TRACE("context_handle %p, attribute %#x, buffer %p\n",
1150 context_handle, attribute, buffer);
1152 if (!context_handle) return SEC_E_INVALID_HANDLE;
1153 ctx = schan_get_object(context_handle->dwLower, SCHAN_HANDLE_CTX);
1155 switch(attribute)
1157 case SECPKG_ATTR_STREAM_SIZES:
1159 SecPkgContext_ConnectionInfo info;
1160 status = schan_funcs->get_connection_info(ctx->session, &info);
1161 if (status == SEC_E_OK)
1163 SecPkgContext_StreamSizes *stream_sizes = buffer;
1164 SIZE_T mac_size = info.dwHashStrength;
1165 unsigned int block_size = schan_funcs->get_session_cipher_block_size(ctx->session);
1166 unsigned int message_size = schan_funcs->get_max_message_size(ctx->session);
1168 TRACE("Using header size %lu mac bytes %lu, message size %u, block size %u\n",
1169 ctx->header_size, mac_size, message_size, block_size);
1171 /* These are defined by the TLS RFC */
1172 stream_sizes->cbHeader = ctx->header_size;
1173 stream_sizes->cbTrailer = mac_size + 256; /* Max 255 bytes padding + 1 for padding size */
1174 stream_sizes->cbMaximumMessage = message_size;
1175 stream_sizes->cbBuffers = 4;
1176 stream_sizes->cbBlockSize = block_size;
1179 return status;
1181 case SECPKG_ATTR_KEY_INFO:
1183 SecPkgContext_ConnectionInfo conn_info;
1184 status = schan_funcs->get_connection_info(ctx->session, &conn_info);
1185 if (status == SEC_E_OK)
1187 SecPkgContext_KeyInfoW *info = buffer;
1188 info->KeySize = conn_info.dwCipherStrength;
1189 info->SignatureAlgorithm = schan_funcs->get_key_signature_algorithm(ctx->session);
1190 info->EncryptAlgorithm = conn_info.aiCipher;
1191 info->sSignatureAlgorithmName = get_alg_name(info->SignatureAlgorithm, TRUE);
1192 info->sEncryptAlgorithmName = get_alg_name(info->EncryptAlgorithm, TRUE);
1194 return status;
1196 case SECPKG_ATTR_REMOTE_CERT_CONTEXT:
1198 PCCERT_CONTEXT *cert = buffer;
1200 status = ensure_remote_cert(ctx);
1201 if(status != SEC_E_OK)
1202 return status;
1204 *cert = CertDuplicateCertificateContext(ctx->cert);
1205 return SEC_E_OK;
1207 case SECPKG_ATTR_CONNECTION_INFO:
1209 SecPkgContext_ConnectionInfo *info = buffer;
1210 return schan_funcs->get_connection_info(ctx->session, info);
1212 case SECPKG_ATTR_ENDPOINT_BINDINGS:
1214 SecPkgContext_Bindings *bindings = buffer;
1215 CCRYPT_OID_INFO *info;
1216 ALG_ID hash_alg = CALG_SHA_256;
1217 BYTE hash[1024];
1218 DWORD hash_size;
1219 char *p;
1220 BOOL r;
1222 static const char prefix[] = "tls-server-end-point:";
1224 status = ensure_remote_cert(ctx);
1225 if(status != SEC_E_OK)
1226 return status;
1228 /* RFC 5929 */
1229 info = CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY, ctx->cert->pCertInfo->SignatureAlgorithm.pszObjId, 0);
1230 if(info && info->u.Algid != CALG_SHA1 && info->u.Algid != CALG_MD5)
1231 hash_alg = info->u.Algid;
1233 hash_size = sizeof(hash);
1234 r = CryptHashCertificate(0, hash_alg, 0, ctx->cert->pbCertEncoded, ctx->cert->cbCertEncoded, hash, &hash_size);
1235 if(!r)
1236 return GetLastError();
1238 bindings->BindingsLength = sizeof(*bindings->Bindings) + sizeof(prefix)-1 + hash_size;
1239 /* freed with FreeContextBuffer */
1240 bindings->Bindings = RtlAllocateHeap(GetProcessHeap(), HEAP_ZERO_MEMORY, bindings->BindingsLength);
1241 if(!bindings->Bindings)
1242 return SEC_E_INSUFFICIENT_MEMORY;
1244 bindings->Bindings->cbApplicationDataLength = sizeof(prefix)-1 + hash_size;
1245 bindings->Bindings->dwApplicationDataOffset = sizeof(*bindings->Bindings);
1247 p = (char*)(bindings->Bindings+1);
1248 memcpy(p, prefix, sizeof(prefix)-1);
1249 p += sizeof(prefix)-1;
1250 memcpy(p, hash, hash_size);
1251 return SEC_E_OK;
1253 case SECPKG_ATTR_UNIQUE_BINDINGS:
1255 SecPkgContext_Bindings *bindings = buffer;
1256 return schan_funcs->get_unique_channel_binding(ctx->session, bindings);
1258 case SECPKG_ATTR_APPLICATION_PROTOCOL:
1260 SecPkgContext_ApplicationProtocol *protocol = buffer;
1261 return schan_funcs->get_application_protocol(ctx->session, protocol);
1264 default:
1265 FIXME("Unhandled attribute %#x\n", attribute);
1266 return SEC_E_UNSUPPORTED_FUNCTION;
1270 static SECURITY_STATUS SEC_ENTRY schan_QueryContextAttributesA(
1271 PCtxtHandle context_handle, ULONG attribute, PVOID buffer)
1273 TRACE("context_handle %p, attribute %#x, buffer %p\n",
1274 context_handle, attribute, buffer);
1276 switch(attribute)
1278 case SECPKG_ATTR_STREAM_SIZES:
1279 return schan_QueryContextAttributesW(context_handle, attribute, buffer);
1280 case SECPKG_ATTR_KEY_INFO:
1282 SECURITY_STATUS status = schan_QueryContextAttributesW(context_handle, attribute, buffer);
1283 if (status == SEC_E_OK)
1285 SecPkgContext_KeyInfoA *info = buffer;
1286 info->sSignatureAlgorithmName = get_alg_name(info->SignatureAlgorithm, FALSE);
1287 info->sEncryptAlgorithmName = get_alg_name(info->EncryptAlgorithm, FALSE);
1289 return status;
1291 case SECPKG_ATTR_REMOTE_CERT_CONTEXT:
1292 return schan_QueryContextAttributesW(context_handle, attribute, buffer);
1293 case SECPKG_ATTR_CONNECTION_INFO:
1294 return schan_QueryContextAttributesW(context_handle, attribute, buffer);
1295 case SECPKG_ATTR_ENDPOINT_BINDINGS:
1296 return schan_QueryContextAttributesW(context_handle, attribute, buffer);
1297 case SECPKG_ATTR_UNIQUE_BINDINGS:
1298 return schan_QueryContextAttributesW(context_handle, attribute, buffer);
1299 case SECPKG_ATTR_APPLICATION_PROTOCOL:
1300 return schan_QueryContextAttributesW(context_handle, attribute, buffer);
1302 default:
1303 FIXME("Unhandled attribute %#x\n", attribute);
1304 return SEC_E_UNSUPPORTED_FUNCTION;
1308 static int schan_encrypt_message_get_next_buffer(const struct schan_transport *t, struct schan_buffers *s)
1310 SecBuffer *b;
1312 if (s->current_buffer_idx == -1)
1313 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_STREAM_HEADER);
1315 b = &s->desc->pBuffers[s->current_buffer_idx];
1317 if (b->BufferType == SECBUFFER_STREAM_HEADER)
1318 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_DATA);
1320 if (b->BufferType == SECBUFFER_DATA)
1321 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_STREAM_TRAILER);
1323 return -1;
1326 static int schan_encrypt_message_get_next_buffer_token(const struct schan_transport *t, struct schan_buffers *s)
1328 SecBuffer *b;
1330 if (s->current_buffer_idx == -1)
1331 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
1333 b = &s->desc->pBuffers[s->current_buffer_idx];
1335 if (b->BufferType == SECBUFFER_TOKEN)
1337 int idx = schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
1338 if (idx != s->current_buffer_idx) return -1;
1339 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_DATA);
1342 if (b->BufferType == SECBUFFER_DATA)
1344 int idx = schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
1345 if (idx != -1)
1346 idx = schan_find_sec_buffer_idx(s->desc, idx + 1, SECBUFFER_TOKEN);
1347 return idx;
1350 return -1;
1353 static SECURITY_STATUS SEC_ENTRY schan_EncryptMessage(PCtxtHandle context_handle,
1354 ULONG quality, PSecBufferDesc message, ULONG message_seq_no)
1356 struct schan_context *ctx;
1357 struct schan_buffers *b;
1358 SECURITY_STATUS status;
1359 SecBuffer *buffer;
1360 SIZE_T data_size;
1361 SIZE_T length;
1362 char *data;
1363 int idx;
1365 TRACE("context_handle %p, quality %d, message %p, message_seq_no %d\n",
1366 context_handle, quality, message, message_seq_no);
1368 if (!context_handle) return SEC_E_INVALID_HANDLE;
1369 ctx = schan_get_object(context_handle->dwLower, SCHAN_HANDLE_CTX);
1371 dump_buffer_desc(message);
1373 idx = schan_find_sec_buffer_idx(message, 0, SECBUFFER_DATA);
1374 if (idx == -1)
1376 WARN("No data buffer passed\n");
1377 return SEC_E_INTERNAL_ERROR;
1379 buffer = &message->pBuffers[idx];
1381 data_size = buffer->cbBuffer;
1382 data = malloc(data_size);
1383 memcpy(data, buffer->pvBuffer, data_size);
1385 if (schan_find_sec_buffer_idx(message, 0, SECBUFFER_STREAM_HEADER) != -1)
1386 init_schan_buffers(&ctx->transport.out, message, schan_encrypt_message_get_next_buffer);
1387 else
1388 init_schan_buffers(&ctx->transport.out, message, schan_encrypt_message_get_next_buffer_token);
1390 length = data_size;
1391 status = schan_funcs->send(ctx->session, data, &length);
1393 TRACE("Sent %ld bytes.\n", length);
1395 if (length != data_size)
1396 status = SEC_E_INTERNAL_ERROR;
1398 b = &ctx->transport.out;
1399 b->desc->pBuffers[b->current_buffer_idx].cbBuffer = b->offset;
1400 free(data);
1402 TRACE("Returning %#x.\n", status);
1404 return status;
1407 static int schan_decrypt_message_get_next_buffer(const struct schan_transport *t, struct schan_buffers *s)
1409 if (s->current_buffer_idx == -1)
1410 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_DATA);
1412 return -1;
1415 static int schan_validate_decrypt_buffer_desc(PSecBufferDesc message)
1417 int data_idx = -1;
1418 unsigned int empty_count = 0;
1419 unsigned int i;
1421 if (message->cBuffers < 4)
1423 WARN("Less than four buffers passed\n");
1424 return -1;
1427 for (i = 0; i < message->cBuffers; ++i)
1429 SecBuffer *b = &message->pBuffers[i];
1430 if (b->BufferType == SECBUFFER_DATA)
1432 if (data_idx != -1)
1434 WARN("More than one data buffer passed\n");
1435 return -1;
1437 data_idx = i;
1439 else if (b->BufferType == SECBUFFER_EMPTY)
1440 ++empty_count;
1443 if (data_idx == -1)
1445 WARN("No data buffer passed\n");
1446 return -1;
1449 if (empty_count < 3)
1451 WARN("Less than three empty buffers passed\n");
1452 return -1;
1455 return data_idx;
1458 static void schan_decrypt_fill_buffer(PSecBufferDesc message, ULONG buffer_type, void *data, ULONG size)
1460 int idx;
1461 SecBuffer *buffer;
1463 idx = schan_find_sec_buffer_idx(message, 0, SECBUFFER_EMPTY);
1464 buffer = &message->pBuffers[idx];
1466 buffer->BufferType = buffer_type;
1467 buffer->pvBuffer = data;
1468 buffer->cbBuffer = size;
1471 static SECURITY_STATUS SEC_ENTRY schan_DecryptMessage(PCtxtHandle context_handle,
1472 PSecBufferDesc message, ULONG message_seq_no, PULONG quality)
1474 SECURITY_STATUS status = SEC_E_OK;
1475 struct schan_context *ctx;
1476 SecBuffer *buffer;
1477 SIZE_T data_size;
1478 char *data;
1479 unsigned expected_size;
1480 SSIZE_T received = 0;
1481 int idx;
1482 unsigned char *buf_ptr;
1484 TRACE("context_handle %p, message %p, message_seq_no %d, quality %p\n",
1485 context_handle, message, message_seq_no, quality);
1487 if (!context_handle) return SEC_E_INVALID_HANDLE;
1488 ctx = schan_get_object(context_handle->dwLower, SCHAN_HANDLE_CTX);
1490 dump_buffer_desc(message);
1492 idx = schan_validate_decrypt_buffer_desc(message);
1493 if (idx == -1)
1494 return SEC_E_INVALID_TOKEN;
1495 buffer = &message->pBuffers[idx];
1496 buf_ptr = buffer->pvBuffer;
1498 expected_size = ctx->header_size + read_record_size(buf_ptr, ctx->header_size);
1499 if(buffer->cbBuffer < expected_size)
1501 TRACE("Expected %u bytes, but buffer only contains %u bytes\n", expected_size, buffer->cbBuffer);
1502 buffer->BufferType = SECBUFFER_MISSING;
1503 buffer->cbBuffer = expected_size - buffer->cbBuffer;
1505 /* This is a bit weird, but windows does it too */
1506 idx = schan_find_sec_buffer_idx(message, 0, SECBUFFER_EMPTY);
1507 buffer = &message->pBuffers[idx];
1508 buffer->BufferType = SECBUFFER_MISSING;
1509 buffer->cbBuffer = expected_size - buffer->cbBuffer;
1511 TRACE("Returning SEC_E_INCOMPLETE_MESSAGE\n");
1512 return SEC_E_INCOMPLETE_MESSAGE;
1515 data_size = expected_size - ctx->header_size;
1516 data = malloc(data_size);
1518 init_schan_buffers(&ctx->transport.in, message, schan_decrypt_message_get_next_buffer);
1519 ctx->transport.in.limit = expected_size;
1521 while (received < data_size)
1523 SIZE_T length = data_size - received;
1524 status = schan_funcs->recv(ctx->session, data + received, &length);
1526 if (status == SEC_I_RENEGOTIATE)
1527 break;
1529 if (status == SEC_I_CONTINUE_NEEDED)
1531 status = SEC_E_OK;
1532 break;
1535 if (status != SEC_E_OK)
1537 free(data);
1538 ERR("Returning %x\n", status);
1539 return status;
1542 if (!length)
1543 break;
1545 received += length;
1548 TRACE("Received %ld bytes\n", received);
1550 memcpy(buf_ptr + ctx->header_size, data, received);
1551 free(data);
1553 schan_decrypt_fill_buffer(message, SECBUFFER_DATA,
1554 buf_ptr + ctx->header_size, received);
1556 schan_decrypt_fill_buffer(message, SECBUFFER_STREAM_TRAILER,
1557 buf_ptr + ctx->header_size + received, buffer->cbBuffer - ctx->header_size - received);
1559 if(buffer->cbBuffer > expected_size)
1560 schan_decrypt_fill_buffer(message, SECBUFFER_EXTRA,
1561 buf_ptr + expected_size, buffer->cbBuffer - expected_size);
1563 buffer->BufferType = SECBUFFER_STREAM_HEADER;
1564 buffer->cbBuffer = ctx->header_size;
1566 return status;
1569 static SECURITY_STATUS SEC_ENTRY schan_DeleteSecurityContext(PCtxtHandle context_handle)
1571 struct schan_context *ctx;
1573 TRACE("context_handle %p\n", context_handle);
1575 if (!context_handle) return SEC_E_INVALID_HANDLE;
1577 ctx = schan_free_handle(context_handle->dwLower, SCHAN_HANDLE_CTX);
1578 if (!ctx) return SEC_E_INVALID_HANDLE;
1580 if (ctx->cert) CertFreeCertificateContext(ctx->cert);
1581 schan_funcs->dispose_session(ctx->session);
1582 free(ctx);
1583 return SEC_E_OK;
1586 static const SecurityFunctionTableA schanTableA = {
1588 NULL, /* EnumerateSecurityPackagesA */
1589 schan_QueryCredentialsAttributesA,
1590 schan_AcquireCredentialsHandleA,
1591 schan_FreeCredentialsHandle,
1592 NULL, /* Reserved2 */
1593 schan_InitializeSecurityContextA,
1594 NULL, /* AcceptSecurityContext */
1595 NULL, /* CompleteAuthToken */
1596 schan_DeleteSecurityContext,
1597 NULL, /* ApplyControlToken */
1598 schan_QueryContextAttributesA,
1599 NULL, /* ImpersonateSecurityContext */
1600 NULL, /* RevertSecurityContext */
1601 NULL, /* MakeSignature */
1602 NULL, /* VerifySignature */
1603 FreeContextBuffer,
1604 NULL, /* QuerySecurityPackageInfoA */
1605 NULL, /* Reserved3 */
1606 NULL, /* Reserved4 */
1607 NULL, /* ExportSecurityContext */
1608 NULL, /* ImportSecurityContextA */
1609 NULL, /* AddCredentialsA */
1610 NULL, /* Reserved8 */
1611 NULL, /* QuerySecurityContextToken */
1612 schan_EncryptMessage,
1613 schan_DecryptMessage,
1614 NULL, /* SetContextAttributesA */
1617 static const SecurityFunctionTableW schanTableW = {
1619 NULL, /* EnumerateSecurityPackagesW */
1620 schan_QueryCredentialsAttributesW,
1621 schan_AcquireCredentialsHandleW,
1622 schan_FreeCredentialsHandle,
1623 NULL, /* Reserved2 */
1624 schan_InitializeSecurityContextW,
1625 NULL, /* AcceptSecurityContext */
1626 NULL, /* CompleteAuthToken */
1627 schan_DeleteSecurityContext,
1628 NULL, /* ApplyControlToken */
1629 schan_QueryContextAttributesW,
1630 NULL, /* ImpersonateSecurityContext */
1631 NULL, /* RevertSecurityContext */
1632 NULL, /* MakeSignature */
1633 NULL, /* VerifySignature */
1634 FreeContextBuffer,
1635 NULL, /* QuerySecurityPackageInfoW */
1636 NULL, /* Reserved3 */
1637 NULL, /* Reserved4 */
1638 NULL, /* ExportSecurityContext */
1639 NULL, /* ImportSecurityContextW */
1640 NULL, /* AddCredentialsW */
1641 NULL, /* Reserved8 */
1642 NULL, /* QuerySecurityContextToken */
1643 schan_EncryptMessage,
1644 schan_DecryptMessage,
1645 NULL, /* SetContextAttributesW */
1648 const struct schan_callbacks schan_callbacks =
1650 schan_get_buffer,
1651 schan_get_session_for_transport,
1652 schan_pull,
1653 schan_push,
1656 void SECUR32_initSchannelSP(void)
1658 /* This is what Windows reports. This shouldn't break any applications
1659 * even though the functions are missing, because the wrapper will
1660 * return SEC_E_UNSUPPORTED_FUNCTION if our function is NULL.
1662 static const LONG caps =
1663 SECPKG_FLAG_INTEGRITY |
1664 SECPKG_FLAG_PRIVACY |
1665 SECPKG_FLAG_CONNECTION |
1666 SECPKG_FLAG_MULTI_REQUIRED |
1667 SECPKG_FLAG_EXTENDED_ERROR |
1668 SECPKG_FLAG_IMPERSONATION |
1669 SECPKG_FLAG_ACCEPT_WIN32_NAME |
1670 SECPKG_FLAG_STREAM;
1671 static const short version = 1;
1672 static const LONG maxToken = 16384;
1673 SEC_WCHAR *uniSPName = (SEC_WCHAR *)UNISP_NAME_W,
1674 *schannel = (SEC_WCHAR *)SCHANNEL_NAME_W;
1675 const SecPkgInfoW info[] = {
1676 { caps, version, UNISP_RPC_ID, maxToken, uniSPName, uniSPName },
1677 { caps, version, UNISP_RPC_ID, maxToken, schannel, (SEC_WCHAR *)L"Schannel Security Package" },
1679 SecureProvider *provider;
1681 if (!schan_funcs && __wine_init_unix_lib(hsecur32, DLL_PROCESS_ATTACH, &schan_callbacks, &schan_funcs))
1683 ERR( "no schannel support, expect problems\n" );
1684 return;
1687 schan_handle_table = malloc(64 * sizeof(*schan_handle_table));
1688 if (!schan_handle_table)
1690 ERR("Failed to allocate schannel handle table.\n");
1691 goto fail;
1693 schan_handle_table_size = 64;
1695 provider = SECUR32_addProvider(&schanTableA, &schanTableW, L"schannel.dll");
1696 if (!provider)
1698 ERR("Failed to add schannel provider.\n");
1699 goto fail;
1702 SECUR32_addPackages(provider, ARRAY_SIZE(info), NULL, info);
1703 return;
1705 fail:
1706 free(schan_handle_table);
1707 schan_handle_table = NULL;
1708 return;
1711 void SECUR32_deinitSchannelSP(void)
1713 SIZE_T i = schan_handle_count;
1715 if (!schan_handle_table) return;
1717 /* deinitialized sessions first because a pointer to the credentials
1718 * may be stored for the session. */
1719 while (i--)
1721 if (schan_handle_table[i].type == SCHAN_HANDLE_CTX)
1723 struct schan_context *ctx = schan_free_handle(i, SCHAN_HANDLE_CTX);
1724 schan_funcs->dispose_session(ctx->session);
1725 free(ctx);
1728 i = schan_handle_count;
1729 while (i--)
1731 if (schan_handle_table[i].type != SCHAN_HANDLE_FREE)
1733 struct schan_credentials *cred;
1734 cred = schan_free_handle(i, SCHAN_HANDLE_CRED);
1735 schan_funcs->free_certificate_credentials(cred);
1736 free(cred);
1739 free(schan_handle_table);
1741 __wine_init_unix_lib(hsecur32, DLL_PROCESS_DETACH, NULL, NULL);
1742 schan_funcs = NULL;