mf/samplegrabber: Handle paused state.
[wine.git] / dlls / secur32 / schannel.c
blob50a1c848c0e834466ee4e61f91f65c1c992f70a6
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 * EAGAIN when no data could be read without blocking
763 * another errno-style error value on failure
766 static int CDECL schan_pull(struct schan_transport *t, void *buff, size_t *buff_len)
768 char *b;
769 SIZE_T local_len = *buff_len;
771 TRACE("Pull %lu bytes\n", local_len);
773 *buff_len = 0;
775 b = schan_get_buffer(t, &t->in, &local_len);
776 if (!b)
777 return EAGAIN;
779 memcpy(buff, b, local_len);
780 t->in.offset += local_len;
782 TRACE("Read %lu bytes\n", local_len);
784 *buff_len = local_len;
785 return 0;
788 /* schan_push
789 * Write data to the transport output buffer.
791 * t - The session transport object.
792 * buff - The buffer of data to write. Must be at least *buff_len bytes in length.
793 * buff_len - On input, *buff_len is the desired length to write. On successful
794 * return, *buff_len is the number of bytes actually written.
796 * Returns:
797 * 0 on success
798 * *buff_len will be > 0 indicating how much data was written. May be less
799 * than what was requested, in which case the caller should call again
800 if/when they want to write more.
801 * EAGAIN when no data could be written without blocking
802 * another errno-style error value on failure
805 static int CDECL schan_push(struct schan_transport *t, const void *buff, size_t *buff_len)
807 char *b;
808 SIZE_T local_len = *buff_len;
810 TRACE("Push %lu bytes\n", local_len);
812 *buff_len = 0;
814 b = schan_get_buffer(t, &t->out, &local_len);
815 if (!b)
816 return EAGAIN;
818 memcpy(b, buff, local_len);
819 t->out.offset += local_len;
821 TRACE("Wrote %lu bytes\n", local_len);
823 *buff_len = local_len;
824 return 0;
827 static schan_session CDECL schan_get_session_for_transport(struct schan_transport* t)
829 return t->ctx->session;
832 static int schan_init_sec_ctx_get_next_input_buffer(const struct schan_transport *t, struct schan_buffers *s)
834 if (s->current_buffer_idx != -1)
835 return -1;
836 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
839 static int schan_init_sec_ctx_get_next_output_buffer(const struct schan_transport *t, struct schan_buffers *s)
841 if (s->current_buffer_idx == -1)
843 int idx = schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
844 if (t->ctx->req_ctx_attr & ISC_REQ_ALLOCATE_MEMORY)
846 if (idx == -1)
848 idx = schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_EMPTY);
849 if (idx != -1) s->desc->pBuffers[idx].BufferType = SECBUFFER_TOKEN;
851 if (idx != -1 && !s->desc->pBuffers[idx].pvBuffer)
853 s->desc->pBuffers[idx].cbBuffer = 0;
854 s->allow_buffer_resize = TRUE;
857 return idx;
860 return -1;
863 static void dump_buffer_desc(SecBufferDesc *desc)
865 unsigned int i;
867 if (!desc) return;
868 TRACE("Buffer desc %p:\n", desc);
869 for (i = 0; i < desc->cBuffers; ++i)
871 SecBuffer *b = &desc->pBuffers[i];
872 TRACE("\tbuffer %u: cbBuffer %d, BufferType %#x pvBuffer %p\n", i, b->cbBuffer, b->BufferType, b->pvBuffer);
876 #define HEADER_SIZE_TLS 5
877 #define HEADER_SIZE_DTLS 13
879 static inline SIZE_T read_record_size(const BYTE *buf, SIZE_T header_size)
881 return (buf[header_size - 2] << 8) | buf[header_size - 1];
884 static inline BOOL is_dtls_context(const struct schan_context *ctx)
886 return (ctx->header_size == HEADER_SIZE_DTLS);
889 /***********************************************************************
890 * InitializeSecurityContextW
892 static SECURITY_STATUS SEC_ENTRY schan_InitializeSecurityContextW(
893 PCredHandle phCredential, PCtxtHandle phContext, SEC_WCHAR *pszTargetName,
894 ULONG fContextReq, ULONG Reserved1, ULONG TargetDataRep,
895 PSecBufferDesc pInput, ULONG Reserved2, PCtxtHandle phNewContext,
896 PSecBufferDesc pOutput, ULONG *pfContextAttr, PTimeStamp ptsExpiry)
898 struct schan_context *ctx;
899 struct schan_buffers *out_buffers;
900 struct schan_credentials *cred;
901 SIZE_T expected_size = ~0UL;
902 SECURITY_STATUS ret;
903 SecBuffer *buffer;
904 int idx;
906 TRACE("%p %p %s 0x%08x %d %d %p %d %p %p %p %p\n", phCredential, phContext,
907 debugstr_w(pszTargetName), fContextReq, Reserved1, TargetDataRep, pInput,
908 Reserved1, phNewContext, pOutput, pfContextAttr, ptsExpiry);
910 dump_buffer_desc(pInput);
911 dump_buffer_desc(pOutput);
913 if (!phContext)
915 ULONG_PTR handle;
917 if (!phCredential) return SEC_E_INVALID_HANDLE;
919 cred = schan_get_object(phCredential->dwLower, SCHAN_HANDLE_CRED);
920 if (!cred) return SEC_E_INVALID_HANDLE;
922 if (!(cred->credential_use & SECPKG_CRED_OUTBOUND))
924 WARN("Invalid credential use %#x\n", cred->credential_use);
925 return SEC_E_INVALID_HANDLE;
928 if (!(ctx = malloc(sizeof(*ctx)))) return SEC_E_INSUFFICIENT_MEMORY;
930 ctx->cert = NULL;
931 handle = schan_alloc_handle(ctx, SCHAN_HANDLE_CTX);
932 if (handle == SCHAN_INVALID_HANDLE)
934 free(ctx);
935 return SEC_E_INTERNAL_ERROR;
938 if (!schan_funcs->create_session(&ctx->session, cred))
940 schan_free_handle(handle, SCHAN_HANDLE_CTX);
941 free(ctx);
942 return SEC_E_INTERNAL_ERROR;
945 if (cred->enabled_protocols & (SP_PROT_DTLS1_0_CLIENT | SP_PROT_DTLS1_2_CLIENT))
946 ctx->header_size = HEADER_SIZE_DTLS;
947 else
948 ctx->header_size = HEADER_SIZE_TLS;
950 ctx->transport.ctx = ctx;
951 schan_funcs->set_session_transport(ctx->session, &ctx->transport);
953 if (pszTargetName && *pszTargetName)
955 UINT len = WideCharToMultiByte( CP_UNIXCP, 0, pszTargetName, -1, NULL, 0, NULL, NULL );
956 char *target = malloc( len );
958 if (target)
960 WideCharToMultiByte( CP_UNIXCP, 0, pszTargetName, -1, target, len, NULL, NULL );
961 schan_funcs->set_session_target( ctx->session, target );
962 free( target );
966 if (pInput && (idx = schan_find_sec_buffer_idx(pInput, 0, SECBUFFER_APPLICATION_PROTOCOLS)) != -1)
968 buffer = &pInput->pBuffers[idx];
969 schan_funcs->set_application_protocols(ctx->session, buffer->pvBuffer, buffer->cbBuffer);
972 if (pInput && (idx = schan_find_sec_buffer_idx(pInput, 0, SECBUFFER_DTLS_MTU)) != -1)
974 buffer = &pInput->pBuffers[idx];
975 if (buffer->cbBuffer >= sizeof(WORD)) schan_funcs->set_dtls_mtu(ctx->session, *(WORD *)buffer->pvBuffer);
976 else WARN("invalid buffer size %u\n", buffer->cbBuffer);
979 phNewContext->dwLower = handle;
980 phNewContext->dwUpper = 0;
982 else
984 SIZE_T record_size = 0;
985 unsigned char *ptr;
987 ctx = schan_get_object(phContext->dwLower, SCHAN_HANDLE_CTX);
988 if (pInput)
990 idx = schan_find_sec_buffer_idx(pInput, 0, SECBUFFER_TOKEN);
991 if (idx == -1)
992 return SEC_E_INCOMPLETE_MESSAGE;
994 buffer = &pInput->pBuffers[idx];
995 ptr = buffer->pvBuffer;
996 expected_size = 0;
998 while (buffer->cbBuffer > expected_size + ctx->header_size)
1000 record_size = ctx->header_size + read_record_size(ptr, ctx->header_size);
1002 if (buffer->cbBuffer < expected_size + record_size)
1003 break;
1005 expected_size += record_size;
1006 ptr += record_size;
1009 if (!expected_size)
1011 TRACE("Expected at least %lu bytes, but buffer only contains %u bytes.\n",
1012 max(6, record_size), buffer->cbBuffer);
1013 return SEC_E_INCOMPLETE_MESSAGE;
1016 else if (!is_dtls_context(ctx)) return SEC_E_INCOMPLETE_MESSAGE;
1018 TRACE("Using expected_size %lu.\n", expected_size);
1021 ctx->req_ctx_attr = fContextReq;
1023 init_schan_buffers(&ctx->transport.in, pInput, schan_init_sec_ctx_get_next_input_buffer);
1024 ctx->transport.in.limit = expected_size;
1025 init_schan_buffers(&ctx->transport.out, pOutput, schan_init_sec_ctx_get_next_output_buffer);
1027 /* Perform the TLS handshake */
1028 ret = schan_funcs->handshake(ctx->session);
1030 out_buffers = &ctx->transport.out;
1031 if (out_buffers->current_buffer_idx != -1)
1033 SecBuffer *buffer = &out_buffers->desc->pBuffers[out_buffers->current_buffer_idx];
1034 buffer->cbBuffer = out_buffers->offset;
1036 else if (out_buffers->desc && out_buffers->desc->cBuffers > 0)
1038 SecBuffer *buffer = &out_buffers->desc->pBuffers[0];
1039 buffer->cbBuffer = 0;
1042 if(ctx->transport.in.offset && ctx->transport.in.offset != pInput->pBuffers[0].cbBuffer) {
1043 if(pInput->cBuffers<2 || pInput->pBuffers[1].BufferType!=SECBUFFER_EMPTY)
1044 return SEC_E_INVALID_TOKEN;
1046 pInput->pBuffers[1].BufferType = SECBUFFER_EXTRA;
1047 pInput->pBuffers[1].cbBuffer = pInput->pBuffers[0].cbBuffer-ctx->transport.in.offset;
1050 *pfContextAttr = ISC_RET_REPLAY_DETECT | ISC_RET_SEQUENCE_DETECT | ISC_RET_CONFIDENTIALITY | ISC_RET_STREAM;
1051 if (ctx->req_ctx_attr & ISC_REQ_EXTENDED_ERROR) *pfContextAttr |= ISC_RET_EXTENDED_ERROR;
1052 if (ctx->req_ctx_attr & ISC_REQ_DATAGRAM) *pfContextAttr |= ISC_RET_DATAGRAM;
1053 if (ctx->req_ctx_attr & ISC_REQ_ALLOCATE_MEMORY) *pfContextAttr |= ISC_RET_ALLOCATED_MEMORY;
1054 if (ctx->req_ctx_attr & ISC_REQ_USE_SUPPLIED_CREDS) *pfContextAttr |= ISC_RET_USED_SUPPLIED_CREDS;
1055 if (ctx->req_ctx_attr & ISC_REQ_MANUAL_CRED_VALIDATION) *pfContextAttr |= ISC_RET_MANUAL_CRED_VALIDATION;
1057 return ret;
1060 /***********************************************************************
1061 * InitializeSecurityContextA
1063 static SECURITY_STATUS SEC_ENTRY schan_InitializeSecurityContextA(
1064 PCredHandle phCredential, PCtxtHandle phContext, SEC_CHAR *pszTargetName,
1065 ULONG fContextReq, ULONG Reserved1, ULONG TargetDataRep,
1066 PSecBufferDesc pInput, ULONG Reserved2, PCtxtHandle phNewContext,
1067 PSecBufferDesc pOutput, ULONG *pfContextAttr, PTimeStamp ptsExpiry)
1069 SECURITY_STATUS ret;
1070 SEC_WCHAR *target_name = NULL;
1072 TRACE("%p %p %s %d %d %d %p %d %p %p %p %p\n", phCredential, phContext,
1073 debugstr_a(pszTargetName), fContextReq, Reserved1, TargetDataRep, pInput,
1074 Reserved1, phNewContext, pOutput, pfContextAttr, ptsExpiry);
1076 if (pszTargetName)
1078 INT len = MultiByteToWideChar(CP_ACP, 0, pszTargetName, -1, NULL, 0);
1079 if (!(target_name = malloc(len * sizeof(*target_name)))) return SEC_E_INSUFFICIENT_MEMORY;
1080 MultiByteToWideChar(CP_ACP, 0, pszTargetName, -1, target_name, len);
1083 ret = schan_InitializeSecurityContextW(phCredential, phContext, target_name,
1084 fContextReq, Reserved1, TargetDataRep, pInput, Reserved2,
1085 phNewContext, pOutput, pfContextAttr, ptsExpiry);
1087 free(target_name);
1088 return ret;
1091 static void *get_alg_name(ALG_ID id, BOOL wide)
1093 static const struct {
1094 ALG_ID alg_id;
1095 const char* name;
1096 const WCHAR nameW[8];
1097 } alg_name_map[] = {
1098 { CALG_ECDSA, "ECDSA", L"ECDSA" },
1099 { CALG_RSA_SIGN, "RSA", L"RSA" },
1100 { CALG_DES, "DES", L"DES" },
1101 { CALG_RC2, "RC2", L"RC2" },
1102 { CALG_3DES, "3DES", L"3DES" },
1103 { CALG_AES_128, "AES", L"AES" },
1104 { CALG_AES_192, "AES", L"AES" },
1105 { CALG_AES_256, "AES", L"AES" },
1106 { CALG_RC4, "RC4", L"RC4" },
1108 unsigned i;
1110 for (i = 0; i < ARRAY_SIZE(alg_name_map); i++)
1111 if (alg_name_map[i].alg_id == id)
1112 return wide ? (void*)alg_name_map[i].nameW : (void*)alg_name_map[i].name;
1114 FIXME("Unknown ALG_ID %04x\n", id);
1115 return NULL;
1118 static SECURITY_STATUS ensure_remote_cert(struct schan_context *ctx)
1120 HCERTSTORE store;
1121 PCCERT_CONTEXT cert = NULL;
1122 SECURITY_STATUS status;
1123 struct schan_cert_list list;
1125 if (ctx->cert) return SEC_E_OK;
1126 if (!(store = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0, CERT_STORE_CREATE_NEW_FLAG, NULL)))
1127 return GetLastError();
1129 if ((status = schan_funcs->get_session_peer_certificate(ctx->session, &list)) == SEC_E_OK)
1131 unsigned int i;
1132 for (i = 0; i < list.count; i++)
1134 if (!CertAddEncodedCertificateToStore(store, X509_ASN_ENCODING, list.certs[i].pbData,
1135 list.certs[i].cbData, CERT_STORE_ADD_REPLACE_EXISTING,
1136 i ? NULL : &cert))
1138 if (i) CertFreeCertificateContext(cert);
1139 return GetLastError();
1142 RtlFreeHeap(GetProcessHeap(), 0, list.certs);
1145 ctx->cert = cert;
1146 CertCloseStore(store, 0);
1147 return status;
1150 static SECURITY_STATUS SEC_ENTRY schan_QueryContextAttributesW(
1151 PCtxtHandle context_handle, ULONG attribute, PVOID buffer)
1153 struct schan_context *ctx;
1154 SECURITY_STATUS status;
1156 TRACE("context_handle %p, attribute %#x, buffer %p\n",
1157 context_handle, attribute, buffer);
1159 if (!context_handle) return SEC_E_INVALID_HANDLE;
1160 ctx = schan_get_object(context_handle->dwLower, SCHAN_HANDLE_CTX);
1162 switch(attribute)
1164 case SECPKG_ATTR_STREAM_SIZES:
1166 SecPkgContext_ConnectionInfo info;
1167 status = schan_funcs->get_connection_info(ctx->session, &info);
1168 if (status == SEC_E_OK)
1170 SecPkgContext_StreamSizes *stream_sizes = buffer;
1171 SIZE_T mac_size = info.dwHashStrength;
1172 unsigned int block_size = schan_funcs->get_session_cipher_block_size(ctx->session);
1173 unsigned int message_size = schan_funcs->get_max_message_size(ctx->session);
1175 TRACE("Using header size %lu mac bytes %lu, message size %u, block size %u\n",
1176 ctx->header_size, mac_size, message_size, block_size);
1178 /* These are defined by the TLS RFC */
1179 stream_sizes->cbHeader = ctx->header_size;
1180 stream_sizes->cbTrailer = mac_size + 256; /* Max 255 bytes padding + 1 for padding size */
1181 stream_sizes->cbMaximumMessage = message_size;
1182 stream_sizes->cbBuffers = 4;
1183 stream_sizes->cbBlockSize = block_size;
1186 return status;
1188 case SECPKG_ATTR_KEY_INFO:
1190 SecPkgContext_ConnectionInfo conn_info;
1191 status = schan_funcs->get_connection_info(ctx->session, &conn_info);
1192 if (status == SEC_E_OK)
1194 SecPkgContext_KeyInfoW *info = buffer;
1195 info->KeySize = conn_info.dwCipherStrength;
1196 info->SignatureAlgorithm = schan_funcs->get_key_signature_algorithm(ctx->session);
1197 info->EncryptAlgorithm = conn_info.aiCipher;
1198 info->sSignatureAlgorithmName = get_alg_name(info->SignatureAlgorithm, TRUE);
1199 info->sEncryptAlgorithmName = get_alg_name(info->EncryptAlgorithm, TRUE);
1201 return status;
1203 case SECPKG_ATTR_REMOTE_CERT_CONTEXT:
1205 PCCERT_CONTEXT *cert = buffer;
1207 status = ensure_remote_cert(ctx);
1208 if(status != SEC_E_OK)
1209 return status;
1211 *cert = CertDuplicateCertificateContext(ctx->cert);
1212 return SEC_E_OK;
1214 case SECPKG_ATTR_CONNECTION_INFO:
1216 SecPkgContext_ConnectionInfo *info = buffer;
1217 return schan_funcs->get_connection_info(ctx->session, info);
1219 case SECPKG_ATTR_ENDPOINT_BINDINGS:
1221 SecPkgContext_Bindings *bindings = buffer;
1222 CCRYPT_OID_INFO *info;
1223 ALG_ID hash_alg = CALG_SHA_256;
1224 BYTE hash[1024];
1225 DWORD hash_size;
1226 char *p;
1227 BOOL r;
1229 static const char prefix[] = "tls-server-end-point:";
1231 status = ensure_remote_cert(ctx);
1232 if(status != SEC_E_OK)
1233 return status;
1235 /* RFC 5929 */
1236 info = CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY, ctx->cert->pCertInfo->SignatureAlgorithm.pszObjId, 0);
1237 if(info && info->u.Algid != CALG_SHA1 && info->u.Algid != CALG_MD5)
1238 hash_alg = info->u.Algid;
1240 hash_size = sizeof(hash);
1241 r = CryptHashCertificate(0, hash_alg, 0, ctx->cert->pbCertEncoded, ctx->cert->cbCertEncoded, hash, &hash_size);
1242 if(!r)
1243 return GetLastError();
1245 bindings->BindingsLength = sizeof(*bindings->Bindings) + sizeof(prefix)-1 + hash_size;
1246 /* freed with FreeContextBuffer */
1247 bindings->Bindings = RtlAllocateHeap(GetProcessHeap(), HEAP_ZERO_MEMORY, bindings->BindingsLength);
1248 if(!bindings->Bindings)
1249 return SEC_E_INSUFFICIENT_MEMORY;
1251 bindings->Bindings->cbApplicationDataLength = sizeof(prefix)-1 + hash_size;
1252 bindings->Bindings->dwApplicationDataOffset = sizeof(*bindings->Bindings);
1254 p = (char*)(bindings->Bindings+1);
1255 memcpy(p, prefix, sizeof(prefix)-1);
1256 p += sizeof(prefix)-1;
1257 memcpy(p, hash, hash_size);
1258 return SEC_E_OK;
1260 case SECPKG_ATTR_UNIQUE_BINDINGS:
1262 SecPkgContext_Bindings *bindings = buffer;
1263 return schan_funcs->get_unique_channel_binding(ctx->session, bindings);
1265 case SECPKG_ATTR_APPLICATION_PROTOCOL:
1267 SecPkgContext_ApplicationProtocol *protocol = buffer;
1268 return schan_funcs->get_application_protocol(ctx->session, protocol);
1271 default:
1272 FIXME("Unhandled attribute %#x\n", attribute);
1273 return SEC_E_UNSUPPORTED_FUNCTION;
1277 static SECURITY_STATUS SEC_ENTRY schan_QueryContextAttributesA(
1278 PCtxtHandle context_handle, ULONG attribute, PVOID buffer)
1280 TRACE("context_handle %p, attribute %#x, buffer %p\n",
1281 context_handle, attribute, buffer);
1283 switch(attribute)
1285 case SECPKG_ATTR_STREAM_SIZES:
1286 return schan_QueryContextAttributesW(context_handle, attribute, buffer);
1287 case SECPKG_ATTR_KEY_INFO:
1289 SECURITY_STATUS status = schan_QueryContextAttributesW(context_handle, attribute, buffer);
1290 if (status == SEC_E_OK)
1292 SecPkgContext_KeyInfoA *info = buffer;
1293 info->sSignatureAlgorithmName = get_alg_name(info->SignatureAlgorithm, FALSE);
1294 info->sEncryptAlgorithmName = get_alg_name(info->EncryptAlgorithm, FALSE);
1296 return status;
1298 case SECPKG_ATTR_REMOTE_CERT_CONTEXT:
1299 return schan_QueryContextAttributesW(context_handle, attribute, buffer);
1300 case SECPKG_ATTR_CONNECTION_INFO:
1301 return schan_QueryContextAttributesW(context_handle, attribute, buffer);
1302 case SECPKG_ATTR_ENDPOINT_BINDINGS:
1303 return schan_QueryContextAttributesW(context_handle, attribute, buffer);
1304 case SECPKG_ATTR_UNIQUE_BINDINGS:
1305 return schan_QueryContextAttributesW(context_handle, attribute, buffer);
1306 case SECPKG_ATTR_APPLICATION_PROTOCOL:
1307 return schan_QueryContextAttributesW(context_handle, attribute, buffer);
1309 default:
1310 FIXME("Unhandled attribute %#x\n", attribute);
1311 return SEC_E_UNSUPPORTED_FUNCTION;
1315 static int schan_encrypt_message_get_next_buffer(const struct schan_transport *t, struct schan_buffers *s)
1317 SecBuffer *b;
1319 if (s->current_buffer_idx == -1)
1320 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_STREAM_HEADER);
1322 b = &s->desc->pBuffers[s->current_buffer_idx];
1324 if (b->BufferType == SECBUFFER_STREAM_HEADER)
1325 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_DATA);
1327 if (b->BufferType == SECBUFFER_DATA)
1328 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_STREAM_TRAILER);
1330 return -1;
1333 static int schan_encrypt_message_get_next_buffer_token(const struct schan_transport *t, struct schan_buffers *s)
1335 SecBuffer *b;
1337 if (s->current_buffer_idx == -1)
1338 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
1340 b = &s->desc->pBuffers[s->current_buffer_idx];
1342 if (b->BufferType == SECBUFFER_TOKEN)
1344 int idx = schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
1345 if (idx != s->current_buffer_idx) return -1;
1346 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_DATA);
1349 if (b->BufferType == SECBUFFER_DATA)
1351 int idx = schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
1352 if (idx != -1)
1353 idx = schan_find_sec_buffer_idx(s->desc, idx + 1, SECBUFFER_TOKEN);
1354 return idx;
1357 return -1;
1360 static SECURITY_STATUS SEC_ENTRY schan_EncryptMessage(PCtxtHandle context_handle,
1361 ULONG quality, PSecBufferDesc message, ULONG message_seq_no)
1363 struct schan_context *ctx;
1364 struct schan_buffers *b;
1365 SECURITY_STATUS status;
1366 SecBuffer *buffer;
1367 SIZE_T data_size;
1368 SIZE_T length;
1369 char *data;
1370 int idx;
1372 TRACE("context_handle %p, quality %d, message %p, message_seq_no %d\n",
1373 context_handle, quality, message, message_seq_no);
1375 if (!context_handle) return SEC_E_INVALID_HANDLE;
1376 ctx = schan_get_object(context_handle->dwLower, SCHAN_HANDLE_CTX);
1378 dump_buffer_desc(message);
1380 idx = schan_find_sec_buffer_idx(message, 0, SECBUFFER_DATA);
1381 if (idx == -1)
1383 WARN("No data buffer passed\n");
1384 return SEC_E_INTERNAL_ERROR;
1386 buffer = &message->pBuffers[idx];
1388 data_size = buffer->cbBuffer;
1389 data = malloc(data_size);
1390 memcpy(data, buffer->pvBuffer, data_size);
1392 if (schan_find_sec_buffer_idx(message, 0, SECBUFFER_STREAM_HEADER) != -1)
1393 init_schan_buffers(&ctx->transport.out, message, schan_encrypt_message_get_next_buffer);
1394 else
1395 init_schan_buffers(&ctx->transport.out, message, schan_encrypt_message_get_next_buffer_token);
1397 length = data_size;
1398 status = schan_funcs->send(ctx->session, data, &length);
1400 TRACE("Sent %ld bytes.\n", length);
1402 if (length != data_size)
1403 status = SEC_E_INTERNAL_ERROR;
1405 b = &ctx->transport.out;
1406 b->desc->pBuffers[b->current_buffer_idx].cbBuffer = b->offset;
1407 free(data);
1409 TRACE("Returning %#x.\n", status);
1411 return status;
1414 static int schan_decrypt_message_get_next_buffer(const struct schan_transport *t, struct schan_buffers *s)
1416 if (s->current_buffer_idx == -1)
1417 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_DATA);
1419 return -1;
1422 static int schan_validate_decrypt_buffer_desc(PSecBufferDesc message)
1424 int data_idx = -1;
1425 unsigned int empty_count = 0;
1426 unsigned int i;
1428 if (message->cBuffers < 4)
1430 WARN("Less than four buffers passed\n");
1431 return -1;
1434 for (i = 0; i < message->cBuffers; ++i)
1436 SecBuffer *b = &message->pBuffers[i];
1437 if (b->BufferType == SECBUFFER_DATA)
1439 if (data_idx != -1)
1441 WARN("More than one data buffer passed\n");
1442 return -1;
1444 data_idx = i;
1446 else if (b->BufferType == SECBUFFER_EMPTY)
1447 ++empty_count;
1450 if (data_idx == -1)
1452 WARN("No data buffer passed\n");
1453 return -1;
1456 if (empty_count < 3)
1458 WARN("Less than three empty buffers passed\n");
1459 return -1;
1462 return data_idx;
1465 static void schan_decrypt_fill_buffer(PSecBufferDesc message, ULONG buffer_type, void *data, ULONG size)
1467 int idx;
1468 SecBuffer *buffer;
1470 idx = schan_find_sec_buffer_idx(message, 0, SECBUFFER_EMPTY);
1471 buffer = &message->pBuffers[idx];
1473 buffer->BufferType = buffer_type;
1474 buffer->pvBuffer = data;
1475 buffer->cbBuffer = size;
1478 static SECURITY_STATUS SEC_ENTRY schan_DecryptMessage(PCtxtHandle context_handle,
1479 PSecBufferDesc message, ULONG message_seq_no, PULONG quality)
1481 SECURITY_STATUS status = SEC_E_OK;
1482 struct schan_context *ctx;
1483 SecBuffer *buffer;
1484 SIZE_T data_size;
1485 char *data;
1486 unsigned expected_size;
1487 SSIZE_T received = 0;
1488 int idx;
1489 unsigned char *buf_ptr;
1491 TRACE("context_handle %p, message %p, message_seq_no %d, quality %p\n",
1492 context_handle, message, message_seq_no, quality);
1494 if (!context_handle) return SEC_E_INVALID_HANDLE;
1495 ctx = schan_get_object(context_handle->dwLower, SCHAN_HANDLE_CTX);
1497 dump_buffer_desc(message);
1499 idx = schan_validate_decrypt_buffer_desc(message);
1500 if (idx == -1)
1501 return SEC_E_INVALID_TOKEN;
1502 buffer = &message->pBuffers[idx];
1503 buf_ptr = buffer->pvBuffer;
1505 expected_size = ctx->header_size + read_record_size(buf_ptr, ctx->header_size);
1506 if(buffer->cbBuffer < expected_size)
1508 TRACE("Expected %u bytes, but buffer only contains %u bytes\n", expected_size, buffer->cbBuffer);
1509 buffer->BufferType = SECBUFFER_MISSING;
1510 buffer->cbBuffer = expected_size - buffer->cbBuffer;
1512 /* This is a bit weird, but windows does it too */
1513 idx = schan_find_sec_buffer_idx(message, 0, SECBUFFER_EMPTY);
1514 buffer = &message->pBuffers[idx];
1515 buffer->BufferType = SECBUFFER_MISSING;
1516 buffer->cbBuffer = expected_size - buffer->cbBuffer;
1518 TRACE("Returning SEC_E_INCOMPLETE_MESSAGE\n");
1519 return SEC_E_INCOMPLETE_MESSAGE;
1522 data_size = expected_size - ctx->header_size;
1523 data = malloc(data_size);
1525 init_schan_buffers(&ctx->transport.in, message, schan_decrypt_message_get_next_buffer);
1526 ctx->transport.in.limit = expected_size;
1528 while (received < data_size)
1530 SIZE_T length = data_size - received;
1531 status = schan_funcs->recv(ctx->session, data + received, &length);
1533 if (status == SEC_I_RENEGOTIATE)
1534 break;
1536 if (status == SEC_I_CONTINUE_NEEDED)
1538 status = SEC_E_OK;
1539 break;
1542 if (status != SEC_E_OK)
1544 free(data);
1545 ERR("Returning %x\n", status);
1546 return status;
1549 if (!length)
1550 break;
1552 received += length;
1555 TRACE("Received %ld bytes\n", received);
1557 memcpy(buf_ptr + ctx->header_size, data, received);
1558 free(data);
1560 schan_decrypt_fill_buffer(message, SECBUFFER_DATA,
1561 buf_ptr + ctx->header_size, received);
1563 schan_decrypt_fill_buffer(message, SECBUFFER_STREAM_TRAILER,
1564 buf_ptr + ctx->header_size + received, buffer->cbBuffer - ctx->header_size - received);
1566 if(buffer->cbBuffer > expected_size)
1567 schan_decrypt_fill_buffer(message, SECBUFFER_EXTRA,
1568 buf_ptr + expected_size, buffer->cbBuffer - expected_size);
1570 buffer->BufferType = SECBUFFER_STREAM_HEADER;
1571 buffer->cbBuffer = ctx->header_size;
1573 return status;
1576 static SECURITY_STATUS SEC_ENTRY schan_DeleteSecurityContext(PCtxtHandle context_handle)
1578 struct schan_context *ctx;
1580 TRACE("context_handle %p\n", context_handle);
1582 if (!context_handle) return SEC_E_INVALID_HANDLE;
1584 ctx = schan_free_handle(context_handle->dwLower, SCHAN_HANDLE_CTX);
1585 if (!ctx) return SEC_E_INVALID_HANDLE;
1587 if (ctx->cert) CertFreeCertificateContext(ctx->cert);
1588 schan_funcs->dispose_session(ctx->session);
1589 free(ctx);
1590 return SEC_E_OK;
1593 static const SecurityFunctionTableA schanTableA = {
1595 NULL, /* EnumerateSecurityPackagesA */
1596 schan_QueryCredentialsAttributesA,
1597 schan_AcquireCredentialsHandleA,
1598 schan_FreeCredentialsHandle,
1599 NULL, /* Reserved2 */
1600 schan_InitializeSecurityContextA,
1601 NULL, /* AcceptSecurityContext */
1602 NULL, /* CompleteAuthToken */
1603 schan_DeleteSecurityContext,
1604 NULL, /* ApplyControlToken */
1605 schan_QueryContextAttributesA,
1606 NULL, /* ImpersonateSecurityContext */
1607 NULL, /* RevertSecurityContext */
1608 NULL, /* MakeSignature */
1609 NULL, /* VerifySignature */
1610 FreeContextBuffer,
1611 NULL, /* QuerySecurityPackageInfoA */
1612 NULL, /* Reserved3 */
1613 NULL, /* Reserved4 */
1614 NULL, /* ExportSecurityContext */
1615 NULL, /* ImportSecurityContextA */
1616 NULL, /* AddCredentialsA */
1617 NULL, /* Reserved8 */
1618 NULL, /* QuerySecurityContextToken */
1619 schan_EncryptMessage,
1620 schan_DecryptMessage,
1621 NULL, /* SetContextAttributesA */
1624 static const SecurityFunctionTableW schanTableW = {
1626 NULL, /* EnumerateSecurityPackagesW */
1627 schan_QueryCredentialsAttributesW,
1628 schan_AcquireCredentialsHandleW,
1629 schan_FreeCredentialsHandle,
1630 NULL, /* Reserved2 */
1631 schan_InitializeSecurityContextW,
1632 NULL, /* AcceptSecurityContext */
1633 NULL, /* CompleteAuthToken */
1634 schan_DeleteSecurityContext,
1635 NULL, /* ApplyControlToken */
1636 schan_QueryContextAttributesW,
1637 NULL, /* ImpersonateSecurityContext */
1638 NULL, /* RevertSecurityContext */
1639 NULL, /* MakeSignature */
1640 NULL, /* VerifySignature */
1641 FreeContextBuffer,
1642 NULL, /* QuerySecurityPackageInfoW */
1643 NULL, /* Reserved3 */
1644 NULL, /* Reserved4 */
1645 NULL, /* ExportSecurityContext */
1646 NULL, /* ImportSecurityContextW */
1647 NULL, /* AddCredentialsW */
1648 NULL, /* Reserved8 */
1649 NULL, /* QuerySecurityContextToken */
1650 schan_EncryptMessage,
1651 schan_DecryptMessage,
1652 NULL, /* SetContextAttributesW */
1655 const struct schan_callbacks schan_callbacks =
1657 schan_get_buffer,
1658 schan_get_session_for_transport,
1659 schan_pull,
1660 schan_push,
1663 void SECUR32_initSchannelSP(void)
1665 /* This is what Windows reports. This shouldn't break any applications
1666 * even though the functions are missing, because the wrapper will
1667 * return SEC_E_UNSUPPORTED_FUNCTION if our function is NULL.
1669 static const LONG caps =
1670 SECPKG_FLAG_INTEGRITY |
1671 SECPKG_FLAG_PRIVACY |
1672 SECPKG_FLAG_CONNECTION |
1673 SECPKG_FLAG_MULTI_REQUIRED |
1674 SECPKG_FLAG_EXTENDED_ERROR |
1675 SECPKG_FLAG_IMPERSONATION |
1676 SECPKG_FLAG_ACCEPT_WIN32_NAME |
1677 SECPKG_FLAG_STREAM;
1678 static const short version = 1;
1679 static const LONG maxToken = 16384;
1680 SEC_WCHAR *uniSPName = (SEC_WCHAR *)UNISP_NAME_W,
1681 *schannel = (SEC_WCHAR *)SCHANNEL_NAME_W;
1682 const SecPkgInfoW info[] = {
1683 { caps, version, UNISP_RPC_ID, maxToken, uniSPName, uniSPName },
1684 { caps, version, UNISP_RPC_ID, maxToken, schannel, (SEC_WCHAR *)L"Schannel Security Package" },
1686 SecureProvider *provider;
1688 if (!schan_funcs && __wine_init_unix_lib(hsecur32, DLL_PROCESS_ATTACH, &schan_callbacks, &schan_funcs))
1690 ERR( "no schannel support, expect problems\n" );
1691 return;
1694 schan_handle_table = malloc(64 * sizeof(*schan_handle_table));
1695 if (!schan_handle_table)
1697 ERR("Failed to allocate schannel handle table.\n");
1698 goto fail;
1700 schan_handle_table_size = 64;
1702 provider = SECUR32_addProvider(&schanTableA, &schanTableW, L"schannel.dll");
1703 if (!provider)
1705 ERR("Failed to add schannel provider.\n");
1706 goto fail;
1709 SECUR32_addPackages(provider, ARRAY_SIZE(info), NULL, info);
1710 return;
1712 fail:
1713 free(schan_handle_table);
1714 schan_handle_table = NULL;
1715 return;
1718 void SECUR32_deinitSchannelSP(void)
1720 SIZE_T i = schan_handle_count;
1722 if (!schan_handle_table) return;
1724 /* deinitialized sessions first because a pointer to the credentials
1725 * may be stored for the session. */
1726 while (i--)
1728 if (schan_handle_table[i].type == SCHAN_HANDLE_CTX)
1730 struct schan_context *ctx = schan_free_handle(i, SCHAN_HANDLE_CTX);
1731 schan_funcs->dispose_session(ctx->session);
1732 free(ctx);
1735 i = schan_handle_count;
1736 while (i--)
1738 if (schan_handle_table[i].type != SCHAN_HANDLE_FREE)
1740 struct schan_credentials *cred;
1741 cred = schan_free_handle(i, SCHAN_HANDLE_CRED);
1742 schan_funcs->free_certificate_credentials(cred);
1743 free(cred);
1746 free(schan_handle_table);
1748 __wine_init_unix_lib(hsecur32, DLL_PROCESS_DETACH, NULL, NULL);
1749 schan_funcs = NULL;