secur32: Move some GnuTLS-specific helper functions.
[wine/testsucceed.git] / dlls / secur32 / schannel.c
blob87391875bde17f9d1fa494809ad0733b4e158327
1 /* Copyright (C) 2005 Juan Lang
2 * Copyright 2008 Henri Verbeet
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
18 * This file implements the schannel provider, or, the SSL/TLS implementations.
20 #include "config.h"
21 #include "wine/port.h"
23 #include <stdarg.h>
24 #include <errno.h>
25 #include <limits.h>
26 #ifdef SONAME_LIBGNUTLS
27 #include <gnutls/gnutls.h>
28 #endif
30 #include "windef.h"
31 #include "winbase.h"
32 #include "winnls.h"
33 #include "sspi.h"
34 #include "schannel.h"
35 #include "secur32_priv.h"
36 #include "wine/debug.h"
37 #include "wine/library.h"
39 WINE_DEFAULT_DEBUG_CHANNEL(secur32);
41 #ifdef SONAME_LIBGNUTLS
43 static void *libgnutls_handle;
44 #define MAKE_FUNCPTR(f) static typeof(f) * p##f
45 MAKE_FUNCPTR(gnutls_alert_get);
46 MAKE_FUNCPTR(gnutls_alert_get_name);
47 MAKE_FUNCPTR(gnutls_certificate_allocate_credentials);
48 MAKE_FUNCPTR(gnutls_certificate_free_credentials);
49 MAKE_FUNCPTR(gnutls_certificate_get_peers);
50 MAKE_FUNCPTR(gnutls_cipher_get);
51 MAKE_FUNCPTR(gnutls_cipher_get_key_size);
52 MAKE_FUNCPTR(gnutls_credentials_set);
53 MAKE_FUNCPTR(gnutls_deinit);
54 MAKE_FUNCPTR(gnutls_global_deinit);
55 MAKE_FUNCPTR(gnutls_global_init);
56 MAKE_FUNCPTR(gnutls_global_set_log_function);
57 MAKE_FUNCPTR(gnutls_global_set_log_level);
58 MAKE_FUNCPTR(gnutls_handshake);
59 MAKE_FUNCPTR(gnutls_init);
60 MAKE_FUNCPTR(gnutls_kx_get);
61 MAKE_FUNCPTR(gnutls_mac_get);
62 MAKE_FUNCPTR(gnutls_mac_get_key_size);
63 MAKE_FUNCPTR(gnutls_perror);
64 MAKE_FUNCPTR(gnutls_protocol_get_version);
65 MAKE_FUNCPTR(gnutls_set_default_priority);
66 MAKE_FUNCPTR(gnutls_record_recv);
67 MAKE_FUNCPTR(gnutls_record_send);
68 MAKE_FUNCPTR(gnutls_transport_set_errno);
69 MAKE_FUNCPTR(gnutls_transport_set_ptr);
70 MAKE_FUNCPTR(gnutls_transport_set_pull_function);
71 MAKE_FUNCPTR(gnutls_transport_set_push_function);
72 #undef MAKE_FUNCPTR
75 static unsigned int schannel_get_cipher_block_size(gnutls_cipher_algorithm_t cipher)
77 const struct
79 gnutls_cipher_algorithm_t cipher;
80 unsigned int block_size;
82 algorithms[] =
84 {GNUTLS_CIPHER_3DES_CBC, 8},
85 {GNUTLS_CIPHER_AES_128_CBC, 16},
86 {GNUTLS_CIPHER_AES_256_CBC, 16},
87 {GNUTLS_CIPHER_ARCFOUR_128, 1},
88 {GNUTLS_CIPHER_ARCFOUR_40, 1},
89 {GNUTLS_CIPHER_DES_CBC, 8},
90 {GNUTLS_CIPHER_NULL, 1},
91 {GNUTLS_CIPHER_RC2_40_CBC, 8},
93 unsigned int i;
95 for (i = 0; i < sizeof(algorithms) / sizeof(*algorithms); ++i)
97 if (algorithms[i].cipher == cipher)
98 return algorithms[i].block_size;
101 FIXME("Unknown cipher %#x, returning 1\n", cipher);
103 return 1;
106 static DWORD schannel_get_protocol(gnutls_protocol_t proto)
108 /* FIXME: currently schannel only implements client connections, but
109 * there's no reason it couldn't be used for servers as well. The
110 * context doesn't tell us which it is, so assume client for now.
112 switch (proto)
114 case GNUTLS_SSL3: return SP_PROT_SSL3_CLIENT;
115 case GNUTLS_TLS1_0: return SP_PROT_TLS1_CLIENT;
116 default:
117 FIXME("unknown protocol %d\n", proto);
118 return 0;
122 static ALG_ID schannel_get_cipher_algid(gnutls_cipher_algorithm_t cipher)
124 switch (cipher)
126 case GNUTLS_CIPHER_UNKNOWN:
127 case GNUTLS_CIPHER_NULL: return 0;
128 case GNUTLS_CIPHER_ARCFOUR_40:
129 case GNUTLS_CIPHER_ARCFOUR_128: return CALG_RC4;
130 case GNUTLS_CIPHER_DES_CBC:
131 case GNUTLS_CIPHER_3DES_CBC: return CALG_DES;
132 case GNUTLS_CIPHER_AES_128_CBC:
133 case GNUTLS_CIPHER_AES_256_CBC: return CALG_AES;
134 case GNUTLS_CIPHER_RC2_40_CBC: return CALG_RC2;
135 default:
136 FIXME("unknown algorithm %d\n", cipher);
137 return 0;
141 static ALG_ID schannel_get_mac_algid(gnutls_mac_algorithm_t mac)
143 switch (mac)
145 case GNUTLS_MAC_UNKNOWN:
146 case GNUTLS_MAC_NULL: return 0;
147 case GNUTLS_MAC_MD5: return CALG_MD5;
148 case GNUTLS_MAC_SHA1:
149 case GNUTLS_MAC_SHA256:
150 case GNUTLS_MAC_SHA384:
151 case GNUTLS_MAC_SHA512: return CALG_SHA;
152 default:
153 FIXME("unknown algorithm %d\n", mac);
154 return 0;
158 static ALG_ID schannel_get_kx_algid(gnutls_kx_algorithm_t kx)
160 switch (kx)
162 case GNUTLS_KX_RSA: return CALG_RSA_KEYX;
163 case GNUTLS_KX_DHE_DSS:
164 case GNUTLS_KX_DHE_RSA: return CALG_DH_EPHEM;
165 default:
166 FIXME("unknown algorithm %d\n", kx);
167 return 0;
171 static SECURITY_STATUS schan_imp_get_session_peer_certificate(gnutls_session_t s,
172 PCCERT_CONTEXT *cert)
174 unsigned int list_size;
175 const gnutls_datum_t *datum;
177 datum = pgnutls_certificate_get_peers(s, &list_size);
178 if (datum)
180 *cert = CertCreateCertificateContext(X509_ASN_ENCODING, datum->data,
181 datum->size);
182 if (!*cert)
183 return GetLastError();
184 else
185 return SEC_E_OK;
187 else
188 return SEC_E_INTERNAL_ERROR;
191 static SECURITY_STATUS schan_imp_send(gnutls_session_t s, const void *buffer,
192 size_t *length)
194 ssize_t ret = pgnutls_record_send(s, buffer, *length);
195 if (ret >= 0)
196 *length = ret;
197 else if (ret == GNUTLS_E_AGAIN)
198 return SEC_I_CONTINUE_NEEDED;
199 else
201 pgnutls_perror(ret);
202 return SEC_E_INTERNAL_ERROR;
205 return SEC_E_OK;
208 static SECURITY_STATUS schan_imp_recv(gnutls_session_t s, void *buffer,
209 size_t *length)
211 ssize_t ret = pgnutls_record_recv(s, buffer, *length);
212 if (ret >= 0)
213 *length = ret;
214 else if (ret == GNUTLS_E_AGAIN)
215 return SEC_I_CONTINUE_NEEDED;
216 else
218 pgnutls_perror(ret);
219 return SEC_E_INTERNAL_ERROR;
222 return SEC_E_OK;
226 #define SCHAN_INVALID_HANDLE ~0UL
228 enum schan_handle_type
230 SCHAN_HANDLE_CRED,
231 SCHAN_HANDLE_CTX,
232 SCHAN_HANDLE_FREE
235 struct schan_handle
237 void *object;
238 enum schan_handle_type type;
241 struct schan_credentials
243 ULONG credential_use;
244 gnutls_certificate_credentials credentials;
247 struct schan_context
249 gnutls_session_t session;
250 ULONG req_ctx_attr;
253 struct schan_transport;
255 struct schan_buffers
257 SIZE_T offset;
258 SIZE_T limit;
259 const SecBufferDesc *desc;
260 int current_buffer_idx;
261 BOOL allow_buffer_resize;
262 int (*get_next_buffer)(const struct schan_transport *, struct schan_buffers *);
265 struct schan_transport
267 struct schan_context *ctx;
268 struct schan_buffers in;
269 struct schan_buffers out;
272 static struct schan_handle *schan_handle_table;
273 static struct schan_handle *schan_free_handles;
274 static SIZE_T schan_handle_table_size;
275 static SIZE_T schan_handle_count;
277 static ULONG_PTR schan_alloc_handle(void *object, enum schan_handle_type type)
279 struct schan_handle *handle;
281 if (schan_free_handles)
283 DWORD index = schan_free_handles - schan_handle_table;
284 /* Use a free handle */
285 handle = schan_free_handles;
286 if (handle->type != SCHAN_HANDLE_FREE)
288 ERR("Handle %d(%p) is in the free list, but has type %#x.\n", index, handle, handle->type);
289 return SCHAN_INVALID_HANDLE;
291 schan_free_handles = handle->object;
292 handle->object = object;
293 handle->type = type;
295 return index;
297 if (!(schan_handle_count < schan_handle_table_size))
299 /* Grow the table */
300 SIZE_T new_size = schan_handle_table_size + (schan_handle_table_size >> 1);
301 struct schan_handle *new_table = HeapReAlloc(GetProcessHeap(), 0, schan_handle_table, new_size * sizeof(*schan_handle_table));
302 if (!new_table)
304 ERR("Failed to grow the handle table\n");
305 return SCHAN_INVALID_HANDLE;
307 schan_handle_table = new_table;
308 schan_handle_table_size = new_size;
311 handle = &schan_handle_table[schan_handle_count++];
312 handle->object = object;
313 handle->type = type;
315 return handle - schan_handle_table;
318 static void *schan_free_handle(ULONG_PTR handle_idx, enum schan_handle_type type)
320 struct schan_handle *handle;
321 void *object;
323 if (handle_idx == SCHAN_INVALID_HANDLE) return NULL;
324 if (handle_idx >= schan_handle_count) return NULL;
325 handle = &schan_handle_table[handle_idx];
326 if (handle->type != type)
328 ERR("Handle %ld(%p) is not of type %#x\n", handle_idx, handle, type);
329 return NULL;
332 object = handle->object;
333 handle->object = schan_free_handles;
334 handle->type = SCHAN_HANDLE_FREE;
335 schan_free_handles = handle;
337 return object;
340 static void *schan_get_object(ULONG_PTR handle_idx, enum schan_handle_type type)
342 struct schan_handle *handle;
344 if (handle_idx == SCHAN_INVALID_HANDLE) return NULL;
345 if (handle_idx >= schan_handle_count) return NULL;
346 handle = &schan_handle_table[handle_idx];
347 if (handle->type != type)
349 ERR("Handle %ld(%p) is not of type %#x\n", handle_idx, handle, type);
350 return NULL;
353 return handle->object;
356 static SECURITY_STATUS schan_QueryCredentialsAttributes(
357 PCredHandle phCredential, ULONG ulAttribute, VOID *pBuffer)
359 SECURITY_STATUS ret;
361 switch (ulAttribute)
363 case SECPKG_ATTR_SUPPORTED_ALGS:
364 if (pBuffer)
366 /* FIXME: get from CryptoAPI */
367 FIXME("SECPKG_ATTR_SUPPORTED_ALGS: stub\n");
368 ret = SEC_E_UNSUPPORTED_FUNCTION;
370 else
371 ret = SEC_E_INTERNAL_ERROR;
372 break;
373 case SECPKG_ATTR_CIPHER_STRENGTHS:
374 if (pBuffer)
376 SecPkgCred_CipherStrengths *r = pBuffer;
378 /* FIXME: get from CryptoAPI */
379 FIXME("SECPKG_ATTR_CIPHER_STRENGTHS: semi-stub\n");
380 r->dwMinimumCipherStrength = 40;
381 r->dwMaximumCipherStrength = 168;
382 ret = SEC_E_OK;
384 else
385 ret = SEC_E_INTERNAL_ERROR;
386 break;
387 case SECPKG_ATTR_SUPPORTED_PROTOCOLS:
388 if (pBuffer)
390 /* FIXME: get from OpenSSL? */
391 FIXME("SECPKG_ATTR_SUPPORTED_PROTOCOLS: stub\n");
392 ret = SEC_E_UNSUPPORTED_FUNCTION;
394 else
395 ret = SEC_E_INTERNAL_ERROR;
396 break;
397 default:
398 ret = SEC_E_UNSUPPORTED_FUNCTION;
400 return ret;
403 static SECURITY_STATUS SEC_ENTRY schan_QueryCredentialsAttributesA(
404 PCredHandle phCredential, ULONG ulAttribute, PVOID pBuffer)
406 SECURITY_STATUS ret;
408 TRACE("(%p, %d, %p)\n", phCredential, ulAttribute, pBuffer);
410 switch (ulAttribute)
412 case SECPKG_CRED_ATTR_NAMES:
413 FIXME("SECPKG_CRED_ATTR_NAMES: stub\n");
414 ret = SEC_E_UNSUPPORTED_FUNCTION;
415 break;
416 default:
417 ret = schan_QueryCredentialsAttributes(phCredential, ulAttribute,
418 pBuffer);
420 return ret;
423 static SECURITY_STATUS SEC_ENTRY schan_QueryCredentialsAttributesW(
424 PCredHandle phCredential, ULONG ulAttribute, PVOID pBuffer)
426 SECURITY_STATUS ret;
428 TRACE("(%p, %d, %p)\n", phCredential, ulAttribute, pBuffer);
430 switch (ulAttribute)
432 case SECPKG_CRED_ATTR_NAMES:
433 FIXME("SECPKG_CRED_ATTR_NAMES: stub\n");
434 ret = SEC_E_UNSUPPORTED_FUNCTION;
435 break;
436 default:
437 ret = schan_QueryCredentialsAttributes(phCredential, ulAttribute,
438 pBuffer);
440 return ret;
443 static SECURITY_STATUS schan_CheckCreds(const SCHANNEL_CRED *schanCred)
445 SECURITY_STATUS st;
446 DWORD i;
448 TRACE("dwVersion = %d\n", schanCred->dwVersion);
449 TRACE("cCreds = %d\n", schanCred->cCreds);
450 TRACE("hRootStore = %p\n", schanCred->hRootStore);
451 TRACE("cMappers = %d\n", schanCred->cMappers);
452 TRACE("cSupportedAlgs = %d:\n", schanCred->cSupportedAlgs);
453 for (i = 0; i < schanCred->cSupportedAlgs; i++)
454 TRACE("%08x\n", schanCred->palgSupportedAlgs[i]);
455 TRACE("grbitEnabledProtocols = %08x\n", schanCred->grbitEnabledProtocols);
456 TRACE("dwMinimumCipherStrength = %d\n", schanCred->dwMinimumCipherStrength);
457 TRACE("dwMaximumCipherStrength = %d\n", schanCred->dwMaximumCipherStrength);
458 TRACE("dwSessionLifespan = %d\n", schanCred->dwSessionLifespan);
459 TRACE("dwFlags = %08x\n", schanCred->dwFlags);
460 TRACE("dwCredFormat = %d\n", schanCred->dwCredFormat);
462 switch (schanCred->dwVersion)
464 case SCH_CRED_V3:
465 case SCHANNEL_CRED_VERSION:
466 break;
467 default:
468 return SEC_E_INTERNAL_ERROR;
471 if (schanCred->cCreds == 0)
472 st = SEC_E_NO_CREDENTIALS;
473 else if (schanCred->cCreds > 1)
474 st = SEC_E_UNKNOWN_CREDENTIALS;
475 else
477 DWORD keySpec;
478 HCRYPTPROV csp;
479 BOOL ret, freeCSP;
481 ret = CryptAcquireCertificatePrivateKey(schanCred->paCred[0],
482 0, /* FIXME: what flags to use? */ NULL,
483 &csp, &keySpec, &freeCSP);
484 if (ret)
486 st = SEC_E_OK;
487 if (freeCSP)
488 CryptReleaseContext(csp, 0);
490 else
491 st = SEC_E_UNKNOWN_CREDENTIALS;
493 return st;
496 static SECURITY_STATUS schan_AcquireClientCredentials(const SCHANNEL_CRED *schanCred,
497 PCredHandle phCredential, PTimeStamp ptsExpiry)
499 struct schan_credentials *creds;
500 SECURITY_STATUS st = SEC_E_OK;
502 TRACE("schanCred %p, phCredential %p, ptsExpiry %p\n", schanCred, phCredential, ptsExpiry);
504 if (schanCred)
506 st = schan_CheckCreds(schanCred);
507 if (st == SEC_E_NO_CREDENTIALS)
508 st = SEC_E_OK;
511 /* For now, the only thing I'm interested in is the direction of the
512 * connection, so just store it.
514 if (st == SEC_E_OK)
516 ULONG_PTR handle;
517 int ret;
519 creds = HeapAlloc(GetProcessHeap(), 0, sizeof(*creds));
520 if (!creds) return SEC_E_INSUFFICIENT_MEMORY;
522 handle = schan_alloc_handle(creds, SCHAN_HANDLE_CRED);
523 if (handle == SCHAN_INVALID_HANDLE) goto fail;
525 creds->credential_use = SECPKG_CRED_OUTBOUND;
526 ret = pgnutls_certificate_allocate_credentials(&creds->credentials);
527 if (ret != GNUTLS_E_SUCCESS)
529 pgnutls_perror(ret);
530 schan_free_handle(handle, SCHAN_HANDLE_CRED);
531 goto fail;
534 phCredential->dwLower = handle;
535 phCredential->dwUpper = 0;
537 /* Outbound credentials have no expiry */
538 if (ptsExpiry)
540 ptsExpiry->LowPart = 0;
541 ptsExpiry->HighPart = 0;
544 return st;
546 fail:
547 HeapFree(GetProcessHeap(), 0, creds);
548 return SEC_E_INTERNAL_ERROR;
551 static SECURITY_STATUS schan_AcquireServerCredentials(const SCHANNEL_CRED *schanCred,
552 PCredHandle phCredential, PTimeStamp ptsExpiry)
554 SECURITY_STATUS st;
556 TRACE("schanCred %p, phCredential %p, ptsExpiry %p\n", schanCred, phCredential, ptsExpiry);
558 if (!schanCred) return SEC_E_NO_CREDENTIALS;
560 st = schan_CheckCreds(schanCred);
561 if (st == SEC_E_OK)
563 ULONG_PTR handle;
564 struct schan_credentials *creds;
566 creds = HeapAlloc(GetProcessHeap(), 0, sizeof(*creds));
567 if (!creds) return SEC_E_INSUFFICIENT_MEMORY;
568 creds->credential_use = SECPKG_CRED_INBOUND;
570 handle = schan_alloc_handle(creds, SCHAN_HANDLE_CRED);
571 if (handle == SCHAN_INVALID_HANDLE)
573 HeapFree(GetProcessHeap(), 0, creds);
574 return SEC_E_INTERNAL_ERROR;
577 phCredential->dwLower = handle;
578 phCredential->dwUpper = 0;
580 /* FIXME: get expiry from cert */
582 return st;
585 static SECURITY_STATUS schan_AcquireCredentialsHandle(ULONG fCredentialUse,
586 const SCHANNEL_CRED *schanCred, PCredHandle phCredential, PTimeStamp ptsExpiry)
588 SECURITY_STATUS ret;
590 if (fCredentialUse == SECPKG_CRED_OUTBOUND)
591 ret = schan_AcquireClientCredentials(schanCred, phCredential,
592 ptsExpiry);
593 else
594 ret = schan_AcquireServerCredentials(schanCred, phCredential,
595 ptsExpiry);
596 return ret;
599 static SECURITY_STATUS SEC_ENTRY schan_AcquireCredentialsHandleA(
600 SEC_CHAR *pszPrincipal, SEC_CHAR *pszPackage, ULONG fCredentialUse,
601 PLUID pLogonID, PVOID pAuthData, SEC_GET_KEY_FN pGetKeyFn,
602 PVOID pGetKeyArgument, PCredHandle phCredential, PTimeStamp ptsExpiry)
604 TRACE("(%s, %s, 0x%08x, %p, %p, %p, %p, %p, %p)\n",
605 debugstr_a(pszPrincipal), debugstr_a(pszPackage), fCredentialUse,
606 pLogonID, pAuthData, pGetKeyFn, pGetKeyArgument, phCredential, ptsExpiry);
607 return schan_AcquireCredentialsHandle(fCredentialUse,
608 pAuthData, phCredential, ptsExpiry);
611 static SECURITY_STATUS SEC_ENTRY schan_AcquireCredentialsHandleW(
612 SEC_WCHAR *pszPrincipal, SEC_WCHAR *pszPackage, ULONG fCredentialUse,
613 PLUID pLogonID, PVOID pAuthData, SEC_GET_KEY_FN pGetKeyFn,
614 PVOID pGetKeyArgument, PCredHandle phCredential, PTimeStamp ptsExpiry)
616 TRACE("(%s, %s, 0x%08x, %p, %p, %p, %p, %p, %p)\n",
617 debugstr_w(pszPrincipal), debugstr_w(pszPackage), fCredentialUse,
618 pLogonID, pAuthData, pGetKeyFn, pGetKeyArgument, phCredential, ptsExpiry);
619 return schan_AcquireCredentialsHandle(fCredentialUse,
620 pAuthData, phCredential, ptsExpiry);
623 static SECURITY_STATUS SEC_ENTRY schan_FreeCredentialsHandle(
624 PCredHandle phCredential)
626 struct schan_credentials *creds;
628 TRACE("phCredential %p\n", phCredential);
630 if (!phCredential) return SEC_E_INVALID_HANDLE;
632 creds = schan_free_handle(phCredential->dwLower, SCHAN_HANDLE_CRED);
633 if (!creds) return SEC_E_INVALID_HANDLE;
635 if (creds->credential_use == SECPKG_CRED_OUTBOUND)
636 pgnutls_certificate_free_credentials(creds->credentials);
637 HeapFree(GetProcessHeap(), 0, creds);
639 return SEC_E_OK;
642 static void init_schan_buffers(struct schan_buffers *s, const PSecBufferDesc desc,
643 int (*get_next_buffer)(const struct schan_transport *, struct schan_buffers *))
645 s->offset = 0;
646 s->limit = 0;
647 s->desc = desc;
648 s->current_buffer_idx = -1;
649 s->allow_buffer_resize = FALSE;
650 s->get_next_buffer = get_next_buffer;
653 static int schan_find_sec_buffer_idx(const SecBufferDesc *desc, unsigned int start_idx, ULONG buffer_type)
655 unsigned int i;
656 PSecBuffer buffer;
658 for (i = start_idx; i < desc->cBuffers; ++i)
660 buffer = &desc->pBuffers[i];
661 if (buffer->BufferType == buffer_type) return i;
664 return -1;
667 static void schan_resize_current_buffer(const struct schan_buffers *s, SIZE_T min_size)
669 SecBuffer *b = &s->desc->pBuffers[s->current_buffer_idx];
670 SIZE_T new_size = b->cbBuffer ? b->cbBuffer * 2 : 128;
671 void *new_data;
673 if (b->cbBuffer >= min_size || !s->allow_buffer_resize || min_size > UINT_MAX / 2) return;
675 while (new_size < min_size) new_size *= 2;
677 if (b->pvBuffer)
678 new_data = HeapReAlloc(GetProcessHeap(), 0, b->pvBuffer, new_size);
679 else
680 new_data = HeapAlloc(GetProcessHeap(), 0, new_size);
682 if (!new_data)
684 TRACE("Failed to resize %p from %d to %ld\n", b->pvBuffer, b->cbBuffer, new_size);
685 return;
688 b->cbBuffer = new_size;
689 b->pvBuffer = new_data;
692 static char *schan_get_buffer(const struct schan_transport *t, struct schan_buffers *s, size_t *count)
694 SIZE_T max_count;
695 PSecBuffer buffer;
697 if (!s->desc)
699 TRACE("No desc\n");
700 return NULL;
703 if (s->current_buffer_idx == -1)
705 /* Initial buffer */
706 int buffer_idx = s->get_next_buffer(t, s);
707 if (buffer_idx == -1)
709 TRACE("No next buffer\n");
710 return NULL;
712 s->current_buffer_idx = buffer_idx;
715 buffer = &s->desc->pBuffers[s->current_buffer_idx];
716 TRACE("Using buffer %d: cbBuffer %d, BufferType %#x, pvBuffer %p\n", s->current_buffer_idx, buffer->cbBuffer, buffer->BufferType, buffer->pvBuffer);
718 schan_resize_current_buffer(s, s->offset + *count);
719 max_count = buffer->cbBuffer - s->offset;
720 if (!max_count)
722 int buffer_idx;
724 s->allow_buffer_resize = FALSE;
725 buffer_idx = s->get_next_buffer(t, s);
726 if (buffer_idx == -1)
728 TRACE("No next buffer\n");
729 return NULL;
731 s->current_buffer_idx = buffer_idx;
732 s->offset = 0;
733 return schan_get_buffer(t, s, count);
736 if (*count > max_count) *count = max_count;
737 return (char *)buffer->pvBuffer + s->offset;
740 static ssize_t schan_pull(gnutls_transport_ptr_t transport, void *buff, size_t buff_len)
742 struct schan_transport *t = transport;
743 char *b;
745 TRACE("Pull %zu bytes\n", buff_len);
747 b = schan_get_buffer(t, &t->in, &buff_len);
748 if (!b)
750 pgnutls_transport_set_errno(t->ctx->session, EAGAIN);
751 return -1;
754 if (t->in.limit != 0 && t->in.offset + buff_len >= t->in.limit)
756 buff_len = t->in.limit - t->in.offset;
757 if (buff_len == 0)
759 pgnutls_transport_set_errno(t->ctx->session, EAGAIN);
760 return -1;
764 memcpy(buff, b, buff_len);
765 t->in.offset += buff_len;
767 TRACE("Read %zu bytes\n", buff_len);
769 return buff_len;
772 static ssize_t schan_push(gnutls_transport_ptr_t transport, const void *buff, size_t buff_len)
774 struct schan_transport *t = transport;
775 char *b;
777 TRACE("Push %zu bytes\n", buff_len);
779 b = schan_get_buffer(t, &t->out, &buff_len);
780 if (!b)
782 pgnutls_transport_set_errno(t->ctx->session, EAGAIN);
783 return -1;
786 memcpy(b, buff, buff_len);
787 t->out.offset += buff_len;
789 TRACE("Wrote %zu bytes\n", buff_len);
791 return buff_len;
794 static int schan_init_sec_ctx_get_next_buffer(const struct schan_transport *t, struct schan_buffers *s)
796 if (s->current_buffer_idx == -1)
798 int idx = schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
799 if (t->ctx->req_ctx_attr & ISC_REQ_ALLOCATE_MEMORY)
801 if (idx == -1)
803 idx = schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_EMPTY);
804 if (idx != -1) s->desc->pBuffers[idx].BufferType = SECBUFFER_TOKEN;
806 if (idx != -1 && !s->desc->pBuffers[idx].pvBuffer)
808 s->desc->pBuffers[idx].cbBuffer = 0;
809 s->allow_buffer_resize = TRUE;
812 return idx;
815 return -1;
818 static void dump_buffer_desc(SecBufferDesc *desc)
820 unsigned int i;
822 if (!desc) return;
823 TRACE("Buffer desc %p:\n", desc);
824 for (i = 0; i < desc->cBuffers; ++i)
826 SecBuffer *b = &desc->pBuffers[i];
827 TRACE("\tbuffer %u: cbBuffer %d, BufferType %#x pvBuffer %p\n", i, b->cbBuffer, b->BufferType, b->pvBuffer);
831 /***********************************************************************
832 * InitializeSecurityContextW
834 static SECURITY_STATUS SEC_ENTRY schan_InitializeSecurityContextW(
835 PCredHandle phCredential, PCtxtHandle phContext, SEC_WCHAR *pszTargetName,
836 ULONG fContextReq, ULONG Reserved1, ULONG TargetDataRep,
837 PSecBufferDesc pInput, ULONG Reserved2, PCtxtHandle phNewContext,
838 PSecBufferDesc pOutput, ULONG *pfContextAttr, PTimeStamp ptsExpiry)
840 struct schan_context *ctx;
841 struct schan_buffers *out_buffers;
842 struct schan_credentials *cred;
843 struct schan_transport transport;
844 int err;
846 TRACE("%p %p %s 0x%08x %d %d %p %d %p %p %p %p\n", phCredential, phContext,
847 debugstr_w(pszTargetName), fContextReq, Reserved1, TargetDataRep, pInput,
848 Reserved1, phNewContext, pOutput, pfContextAttr, ptsExpiry);
850 dump_buffer_desc(pInput);
851 dump_buffer_desc(pOutput);
853 if (!phContext)
855 ULONG_PTR handle;
857 if (!phCredential) return SEC_E_INVALID_HANDLE;
859 cred = schan_get_object(phCredential->dwLower, SCHAN_HANDLE_CRED);
860 if (!cred) return SEC_E_INVALID_HANDLE;
862 if (!(cred->credential_use & SECPKG_CRED_OUTBOUND))
864 WARN("Invalid credential use %#x\n", cred->credential_use);
865 return SEC_E_INVALID_HANDLE;
868 ctx = HeapAlloc(GetProcessHeap(), 0, sizeof(*ctx));
869 if (!ctx) return SEC_E_INSUFFICIENT_MEMORY;
871 handle = schan_alloc_handle(ctx, SCHAN_HANDLE_CTX);
872 if (handle == SCHAN_INVALID_HANDLE)
874 HeapFree(GetProcessHeap(), 0, ctx);
875 return SEC_E_INTERNAL_ERROR;
878 err = pgnutls_init(&ctx->session, GNUTLS_CLIENT);
879 if (err != GNUTLS_E_SUCCESS)
881 pgnutls_perror(err);
882 schan_free_handle(handle, SCHAN_HANDLE_CTX);
883 HeapFree(GetProcessHeap(), 0, ctx);
884 return SEC_E_INTERNAL_ERROR;
887 /* FIXME: We should be using the information from the credentials here. */
888 FIXME("Using hardcoded \"NORMAL\" priority\n");
889 err = pgnutls_set_default_priority(ctx->session);
890 if (err != GNUTLS_E_SUCCESS)
892 pgnutls_perror(err);
893 pgnutls_deinit(ctx->session);
894 schan_free_handle(handle, SCHAN_HANDLE_CTX);
895 HeapFree(GetProcessHeap(), 0, ctx);
898 err = pgnutls_credentials_set(ctx->session, GNUTLS_CRD_CERTIFICATE, cred->credentials);
899 if (err != GNUTLS_E_SUCCESS)
901 pgnutls_perror(err);
902 pgnutls_deinit(ctx->session);
903 schan_free_handle(handle, SCHAN_HANDLE_CTX);
904 HeapFree(GetProcessHeap(), 0, ctx);
907 pgnutls_transport_set_pull_function(ctx->session, schan_pull);
908 pgnutls_transport_set_push_function(ctx->session, schan_push);
910 phNewContext->dwLower = handle;
911 phNewContext->dwUpper = 0;
913 else
915 ctx = schan_get_object(phContext->dwLower, SCHAN_HANDLE_CTX);
918 ctx->req_ctx_attr = fContextReq;
920 transport.ctx = ctx;
921 init_schan_buffers(&transport.in, pInput, schan_init_sec_ctx_get_next_buffer);
922 init_schan_buffers(&transport.out, pOutput, schan_init_sec_ctx_get_next_buffer);
923 pgnutls_transport_set_ptr(ctx->session, &transport);
925 /* Perform the TLS handshake */
926 err = pgnutls_handshake(ctx->session);
928 if(transport.in.offset && transport.in.offset != pInput->pBuffers[0].cbBuffer) {
929 if(pInput->cBuffers<2 || pInput->pBuffers[1].BufferType!=SECBUFFER_EMPTY)
930 return SEC_E_INVALID_TOKEN;
932 pInput->pBuffers[1].BufferType = SECBUFFER_EXTRA;
933 pInput->pBuffers[1].cbBuffer = pInput->pBuffers[0].cbBuffer-transport.in.offset;
936 out_buffers = &transport.out;
937 if (out_buffers->current_buffer_idx != -1)
939 SecBuffer *buffer = &out_buffers->desc->pBuffers[out_buffers->current_buffer_idx];
940 buffer->cbBuffer = out_buffers->offset;
943 *pfContextAttr = 0;
944 if (ctx->req_ctx_attr & ISC_REQ_ALLOCATE_MEMORY)
945 *pfContextAttr |= ISC_RET_ALLOCATED_MEMORY;
947 switch(err)
949 case GNUTLS_E_SUCCESS:
950 TRACE("Handshake completed\n");
951 return SEC_E_OK;
953 case GNUTLS_E_AGAIN:
954 TRACE("Continue...\n");
955 return SEC_I_CONTINUE_NEEDED;
957 case GNUTLS_E_WARNING_ALERT_RECEIVED:
958 case GNUTLS_E_FATAL_ALERT_RECEIVED:
960 gnutls_alert_description_t alert = pgnutls_alert_get(ctx->session);
961 const char *alert_name = pgnutls_alert_get_name(alert);
962 WARN("ALERT: %d %s\n", alert, alert_name);
963 return SEC_E_INTERNAL_ERROR;
966 default:
967 pgnutls_perror(err);
968 return SEC_E_INTERNAL_ERROR;
972 /***********************************************************************
973 * InitializeSecurityContextA
975 static SECURITY_STATUS SEC_ENTRY schan_InitializeSecurityContextA(
976 PCredHandle phCredential, PCtxtHandle phContext, SEC_CHAR *pszTargetName,
977 ULONG fContextReq, ULONG Reserved1, ULONG TargetDataRep,
978 PSecBufferDesc pInput, ULONG Reserved2, PCtxtHandle phNewContext,
979 PSecBufferDesc pOutput, ULONG *pfContextAttr, PTimeStamp ptsExpiry)
981 SECURITY_STATUS ret;
982 SEC_WCHAR *target_name = NULL;
984 TRACE("%p %p %s %d %d %d %p %d %p %p %p %p\n", phCredential, phContext,
985 debugstr_a(pszTargetName), fContextReq, Reserved1, TargetDataRep, pInput,
986 Reserved1, phNewContext, pOutput, pfContextAttr, ptsExpiry);
988 if (pszTargetName)
990 INT len = MultiByteToWideChar(CP_ACP, 0, pszTargetName, -1, NULL, 0);
991 target_name = HeapAlloc(GetProcessHeap(), 0, len * sizeof(*target_name));
992 MultiByteToWideChar(CP_ACP, 0, pszTargetName, -1, target_name, len);
995 ret = schan_InitializeSecurityContextW(phCredential, phContext, target_name,
996 fContextReq, Reserved1, TargetDataRep, pInput, Reserved2,
997 phNewContext, pOutput, pfContextAttr, ptsExpiry);
999 HeapFree(GetProcessHeap(), 0, target_name);
1001 return ret;
1004 static SECURITY_STATUS SEC_ENTRY schan_QueryContextAttributesW(
1005 PCtxtHandle context_handle, ULONG attribute, PVOID buffer)
1007 struct schan_context *ctx;
1009 TRACE("context_handle %p, attribute %#x, buffer %p\n",
1010 context_handle, attribute, buffer);
1012 if (!context_handle) return SEC_E_INVALID_HANDLE;
1013 ctx = schan_get_object(context_handle->dwLower, SCHAN_HANDLE_CTX);
1015 switch(attribute)
1017 case SECPKG_ATTR_STREAM_SIZES:
1019 SecPkgContext_StreamSizes *stream_sizes = buffer;
1020 gnutls_mac_algorithm_t mac = pgnutls_mac_get(ctx->session);
1021 size_t mac_size = pgnutls_mac_get_key_size(mac);
1022 gnutls_cipher_algorithm_t cipher = pgnutls_cipher_get(ctx->session);
1023 unsigned int block_size = schannel_get_cipher_block_size(cipher);
1025 TRACE("Using %zu mac bytes, block size %u\n", mac_size, block_size);
1027 /* These are defined by the TLS RFC */
1028 stream_sizes->cbHeader = 5;
1029 stream_sizes->cbTrailer = mac_size + 256; /* Max 255 bytes padding + 1 for padding size */
1030 stream_sizes->cbMaximumMessage = 1 << 14;
1031 stream_sizes->cbBuffers = 4;
1032 stream_sizes->cbBlockSize = block_size;
1033 return SEC_E_OK;
1035 case SECPKG_ATTR_REMOTE_CERT_CONTEXT:
1037 PCCERT_CONTEXT *cert = buffer;
1038 return schan_imp_get_session_peer_certificate(ctx->session, cert);
1040 case SECPKG_ATTR_CONNECTION_INFO:
1042 SecPkgContext_ConnectionInfo *info = buffer;
1043 gnutls_protocol_t proto = pgnutls_protocol_get_version(ctx->session);
1044 gnutls_cipher_algorithm_t alg = pgnutls_cipher_get(ctx->session);
1045 gnutls_mac_algorithm_t mac = pgnutls_mac_get(ctx->session);
1046 gnutls_kx_algorithm_t kx = pgnutls_kx_get(ctx->session);
1048 info->dwProtocol = schannel_get_protocol(proto);
1049 info->aiCipher = schannel_get_cipher_algid(alg);
1050 info->dwCipherStrength = pgnutls_cipher_get_key_size(alg);
1051 info->aiHash = schannel_get_mac_algid(mac);
1052 info->dwHashStrength = pgnutls_mac_get_key_size(mac);
1053 info->aiExch = schannel_get_kx_algid(kx);
1054 /* FIXME: info->dwExchStrength? */
1055 info->dwExchStrength = 0;
1056 return SEC_E_OK;
1059 default:
1060 FIXME("Unhandled attribute %#x\n", attribute);
1061 return SEC_E_UNSUPPORTED_FUNCTION;
1065 static SECURITY_STATUS SEC_ENTRY schan_QueryContextAttributesA(
1066 PCtxtHandle context_handle, ULONG attribute, PVOID buffer)
1068 TRACE("context_handle %p, attribute %#x, buffer %p\n",
1069 context_handle, attribute, buffer);
1071 switch(attribute)
1073 case SECPKG_ATTR_STREAM_SIZES:
1074 return schan_QueryContextAttributesW(context_handle, attribute, buffer);
1075 case SECPKG_ATTR_REMOTE_CERT_CONTEXT:
1076 return schan_QueryContextAttributesW(context_handle, attribute, buffer);
1077 case SECPKG_ATTR_CONNECTION_INFO:
1078 return schan_QueryContextAttributesW(context_handle, attribute, buffer);
1080 default:
1081 FIXME("Unhandled attribute %#x\n", attribute);
1082 return SEC_E_UNSUPPORTED_FUNCTION;
1086 static int schan_encrypt_message_get_next_buffer(const struct schan_transport *t, struct schan_buffers *s)
1088 SecBuffer *b;
1090 if (s->current_buffer_idx == -1)
1091 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_STREAM_HEADER);
1093 b = &s->desc->pBuffers[s->current_buffer_idx];
1095 if (b->BufferType == SECBUFFER_STREAM_HEADER)
1096 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_DATA);
1098 if (b->BufferType == SECBUFFER_DATA)
1099 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_STREAM_TRAILER);
1101 return -1;
1104 static int schan_encrypt_message_get_next_buffer_token(const struct schan_transport *t, struct schan_buffers *s)
1106 SecBuffer *b;
1108 if (s->current_buffer_idx == -1)
1109 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
1111 b = &s->desc->pBuffers[s->current_buffer_idx];
1113 if (b->BufferType == SECBUFFER_TOKEN)
1115 int idx = schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
1116 if (idx != s->current_buffer_idx) return -1;
1117 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_DATA);
1120 if (b->BufferType == SECBUFFER_DATA)
1122 int idx = schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
1123 if (idx != -1)
1124 idx = schan_find_sec_buffer_idx(s->desc, idx + 1, SECBUFFER_TOKEN);
1125 return idx;
1128 return -1;
1131 static SECURITY_STATUS SEC_ENTRY schan_EncryptMessage(PCtxtHandle context_handle,
1132 ULONG quality, PSecBufferDesc message, ULONG message_seq_no)
1134 struct schan_transport transport;
1135 struct schan_context *ctx;
1136 struct schan_buffers *b;
1137 SecBuffer *buffer;
1138 SIZE_T data_size;
1139 char *data;
1140 ssize_t sent = 0;
1141 int idx;
1143 TRACE("context_handle %p, quality %d, message %p, message_seq_no %d\n",
1144 context_handle, quality, message, message_seq_no);
1146 if (!context_handle) return SEC_E_INVALID_HANDLE;
1147 ctx = schan_get_object(context_handle->dwLower, SCHAN_HANDLE_CTX);
1149 dump_buffer_desc(message);
1151 idx = schan_find_sec_buffer_idx(message, 0, SECBUFFER_DATA);
1152 if (idx == -1)
1154 WARN("No data buffer passed\n");
1155 return SEC_E_INTERNAL_ERROR;
1157 buffer = &message->pBuffers[idx];
1159 data_size = buffer->cbBuffer;
1160 data = HeapAlloc(GetProcessHeap(), 0, data_size);
1161 memcpy(data, buffer->pvBuffer, data_size);
1163 transport.ctx = ctx;
1164 init_schan_buffers(&transport.in, NULL, NULL);
1165 if (schan_find_sec_buffer_idx(message, 0, SECBUFFER_STREAM_HEADER) != -1)
1166 init_schan_buffers(&transport.out, message, schan_encrypt_message_get_next_buffer);
1167 else
1168 init_schan_buffers(&transport.out, message, schan_encrypt_message_get_next_buffer_token);
1169 pgnutls_transport_set_ptr(ctx->session, &transport);
1171 while (sent < data_size)
1173 size_t length = data_size - sent;
1174 SECURITY_STATUS status = schan_imp_send(ctx->session, data + sent, &length);
1175 if (status == SEC_I_CONTINUE_NEEDED)
1176 break;
1177 else if (status != SEC_E_OK)
1179 HeapFree(GetProcessHeap(), 0, data);
1180 ERR("Returning %d\n", status);
1181 return status;
1184 sent += length;
1187 TRACE("Sent %zd bytes\n", sent);
1189 b = &transport.out;
1190 b->desc->pBuffers[b->current_buffer_idx].cbBuffer = b->offset;
1191 HeapFree(GetProcessHeap(), 0, data);
1193 return SEC_E_OK;
1196 static int schan_decrypt_message_get_next_buffer(const struct schan_transport *t, struct schan_buffers *s)
1198 if (s->current_buffer_idx == -1)
1199 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_DATA);
1201 return -1;
1204 static int schan_validate_decrypt_buffer_desc(PSecBufferDesc message)
1206 int data_idx = -1;
1207 unsigned int empty_count = 0;
1208 unsigned int i;
1210 if (message->cBuffers < 4)
1212 WARN("Less than four buffers passed\n");
1213 return -1;
1216 for (i = 0; i < message->cBuffers; ++i)
1218 SecBuffer *b = &message->pBuffers[i];
1219 if (b->BufferType == SECBUFFER_DATA)
1221 if (data_idx != -1)
1223 WARN("More than one data buffer passed\n");
1224 return -1;
1226 data_idx = i;
1228 else if (b->BufferType == SECBUFFER_EMPTY)
1229 ++empty_count;
1232 if (data_idx == -1)
1234 WARN("No data buffer passed\n");
1235 return -1;
1238 if (empty_count < 3)
1240 WARN("Less than three empty buffers passed\n");
1241 return -1;
1244 return data_idx;
1247 static void schan_decrypt_fill_buffer(PSecBufferDesc message, ULONG buffer_type, void *data, ULONG size)
1249 int idx;
1250 SecBuffer *buffer;
1252 idx = schan_find_sec_buffer_idx(message, 0, SECBUFFER_EMPTY);
1253 buffer = &message->pBuffers[idx];
1255 buffer->BufferType = buffer_type;
1256 buffer->pvBuffer = data;
1257 buffer->cbBuffer = size;
1260 static SECURITY_STATUS SEC_ENTRY schan_DecryptMessage(PCtxtHandle context_handle,
1261 PSecBufferDesc message, ULONG message_seq_no, PULONG quality)
1263 struct schan_transport transport;
1264 struct schan_context *ctx;
1265 SecBuffer *buffer;
1266 SIZE_T data_size;
1267 char *data;
1268 unsigned expected_size;
1269 ssize_t received = 0;
1270 int idx;
1271 unsigned char *buf_ptr;
1273 TRACE("context_handle %p, message %p, message_seq_no %d, quality %p\n",
1274 context_handle, message, message_seq_no, quality);
1276 if (!context_handle) return SEC_E_INVALID_HANDLE;
1277 ctx = schan_get_object(context_handle->dwLower, SCHAN_HANDLE_CTX);
1279 dump_buffer_desc(message);
1281 idx = schan_validate_decrypt_buffer_desc(message);
1282 if (idx == -1)
1283 return SEC_E_INVALID_TOKEN;
1284 buffer = &message->pBuffers[idx];
1285 buf_ptr = buffer->pvBuffer;
1287 expected_size = 5 + ((buf_ptr[3] << 8) | buf_ptr[4]);
1288 if(buffer->cbBuffer < expected_size)
1290 TRACE("Expected %u bytes, but buffer only contains %u bytes\n", expected_size, buffer->cbBuffer);
1291 buffer->BufferType = SECBUFFER_MISSING;
1292 buffer->cbBuffer = expected_size - buffer->cbBuffer;
1294 /* This is a bit weird, but windows does it too */
1295 idx = schan_find_sec_buffer_idx(message, 0, SECBUFFER_EMPTY);
1296 buffer = &message->pBuffers[idx];
1297 buffer->BufferType = SECBUFFER_MISSING;
1298 buffer->cbBuffer = expected_size - buffer->cbBuffer;
1300 TRACE("Returning SEC_E_INCOMPLETE_MESSAGE\n");
1301 return SEC_E_INCOMPLETE_MESSAGE;
1304 data_size = buffer->cbBuffer;
1305 data = HeapAlloc(GetProcessHeap(), 0, data_size);
1307 transport.ctx = ctx;
1308 init_schan_buffers(&transport.in, message, schan_decrypt_message_get_next_buffer);
1309 transport.in.limit = expected_size;
1310 init_schan_buffers(&transport.out, NULL, NULL);
1311 pgnutls_transport_set_ptr(ctx->session, (gnutls_transport_ptr_t)&transport);
1313 while (received < data_size)
1315 size_t length = data_size - received;
1316 SECURITY_STATUS status = schan_imp_recv(ctx->session, data + received, &length);
1317 if (status == SEC_I_CONTINUE_NEEDED)
1319 if (!received)
1321 HeapFree(GetProcessHeap(), 0, data);
1322 TRACE("Returning SEC_E_INCOMPLETE_MESSAGE\n");
1323 return SEC_E_INCOMPLETE_MESSAGE;
1325 break;
1327 else if (status != SEC_E_OK)
1329 HeapFree(GetProcessHeap(), 0, data);
1330 ERR("Returning %d\n", status);
1331 return status;
1333 else if (!length)
1334 break;
1336 received += length;
1339 TRACE("Received %zd bytes\n", received);
1341 memcpy(buf_ptr + 5, data, received);
1342 HeapFree(GetProcessHeap(), 0, data);
1344 schan_decrypt_fill_buffer(message, SECBUFFER_DATA,
1345 buf_ptr + 5, received);
1347 schan_decrypt_fill_buffer(message, SECBUFFER_STREAM_TRAILER,
1348 buf_ptr + 5 + received, buffer->cbBuffer - 5 - received);
1350 if(buffer->cbBuffer > expected_size)
1351 schan_decrypt_fill_buffer(message, SECBUFFER_EXTRA,
1352 buf_ptr + expected_size, buffer->cbBuffer - expected_size);
1354 buffer->BufferType = SECBUFFER_STREAM_HEADER;
1355 buffer->cbBuffer = 5;
1357 return SEC_E_OK;
1360 static SECURITY_STATUS SEC_ENTRY schan_DeleteSecurityContext(PCtxtHandle context_handle)
1362 struct schan_context *ctx;
1364 TRACE("context_handle %p\n", context_handle);
1366 if (!context_handle) return SEC_E_INVALID_HANDLE;
1368 ctx = schan_free_handle(context_handle->dwLower, SCHAN_HANDLE_CTX);
1369 if (!ctx) return SEC_E_INVALID_HANDLE;
1371 pgnutls_deinit(ctx->session);
1372 HeapFree(GetProcessHeap(), 0, ctx);
1374 return SEC_E_OK;
1377 static void schan_gnutls_log(int level, const char *msg)
1379 TRACE("<%d> %s", level, msg);
1382 static const SecurityFunctionTableA schanTableA = {
1384 NULL, /* EnumerateSecurityPackagesA */
1385 schan_QueryCredentialsAttributesA,
1386 schan_AcquireCredentialsHandleA,
1387 schan_FreeCredentialsHandle,
1388 NULL, /* Reserved2 */
1389 schan_InitializeSecurityContextA,
1390 NULL, /* AcceptSecurityContext */
1391 NULL, /* CompleteAuthToken */
1392 schan_DeleteSecurityContext,
1393 NULL, /* ApplyControlToken */
1394 schan_QueryContextAttributesA,
1395 NULL, /* ImpersonateSecurityContext */
1396 NULL, /* RevertSecurityContext */
1397 NULL, /* MakeSignature */
1398 NULL, /* VerifySignature */
1399 FreeContextBuffer,
1400 NULL, /* QuerySecurityPackageInfoA */
1401 NULL, /* Reserved3 */
1402 NULL, /* Reserved4 */
1403 NULL, /* ExportSecurityContext */
1404 NULL, /* ImportSecurityContextA */
1405 NULL, /* AddCredentialsA */
1406 NULL, /* Reserved8 */
1407 NULL, /* QuerySecurityContextToken */
1408 schan_EncryptMessage,
1409 schan_DecryptMessage,
1410 NULL, /* SetContextAttributesA */
1413 static const SecurityFunctionTableW schanTableW = {
1415 NULL, /* EnumerateSecurityPackagesW */
1416 schan_QueryCredentialsAttributesW,
1417 schan_AcquireCredentialsHandleW,
1418 schan_FreeCredentialsHandle,
1419 NULL, /* Reserved2 */
1420 schan_InitializeSecurityContextW,
1421 NULL, /* AcceptSecurityContext */
1422 NULL, /* CompleteAuthToken */
1423 schan_DeleteSecurityContext,
1424 NULL, /* ApplyControlToken */
1425 schan_QueryContextAttributesW,
1426 NULL, /* ImpersonateSecurityContext */
1427 NULL, /* RevertSecurityContext */
1428 NULL, /* MakeSignature */
1429 NULL, /* VerifySignature */
1430 FreeContextBuffer,
1431 NULL, /* QuerySecurityPackageInfoW */
1432 NULL, /* Reserved3 */
1433 NULL, /* Reserved4 */
1434 NULL, /* ExportSecurityContext */
1435 NULL, /* ImportSecurityContextW */
1436 NULL, /* AddCredentialsW */
1437 NULL, /* Reserved8 */
1438 NULL, /* QuerySecurityContextToken */
1439 schan_EncryptMessage,
1440 schan_DecryptMessage,
1441 NULL, /* SetContextAttributesW */
1444 static const WCHAR schannelComment[] = { 'S','c','h','a','n','n','e','l',' ',
1445 'S','e','c','u','r','i','t','y',' ','P','a','c','k','a','g','e',0 };
1446 static const WCHAR schannelDllName[] = { 's','c','h','a','n','n','e','l','.','d','l','l',0 };
1448 void SECUR32_initSchannelSP(void)
1450 /* This is what Windows reports. This shouldn't break any applications
1451 * even though the functions are missing, because the wrapper will
1452 * return SEC_E_UNSUPPORTED_FUNCTION if our function is NULL.
1454 static const LONG caps =
1455 SECPKG_FLAG_INTEGRITY |
1456 SECPKG_FLAG_PRIVACY |
1457 SECPKG_FLAG_CONNECTION |
1458 SECPKG_FLAG_MULTI_REQUIRED |
1459 SECPKG_FLAG_EXTENDED_ERROR |
1460 SECPKG_FLAG_IMPERSONATION |
1461 SECPKG_FLAG_ACCEPT_WIN32_NAME |
1462 SECPKG_FLAG_STREAM;
1463 static const short version = 1;
1464 static const LONG maxToken = 16384;
1465 SEC_WCHAR *uniSPName = (SEC_WCHAR *)UNISP_NAME_W,
1466 *schannel = (SEC_WCHAR *)SCHANNEL_NAME_W;
1467 const SecPkgInfoW info[] = {
1468 { caps, version, UNISP_RPC_ID, maxToken, uniSPName, uniSPName },
1469 { caps, version, UNISP_RPC_ID, maxToken, schannel,
1470 (SEC_WCHAR *)schannelComment },
1472 SecureProvider *provider;
1473 int ret;
1475 libgnutls_handle = wine_dlopen(SONAME_LIBGNUTLS, RTLD_NOW, NULL, 0);
1476 if (!libgnutls_handle)
1478 WARN("Failed to load libgnutls.\n");
1479 return;
1482 #define LOAD_FUNCPTR(f) \
1483 if (!(p##f = wine_dlsym(libgnutls_handle, #f, NULL, 0))) \
1485 ERR("Failed to load %s\n", #f); \
1486 goto fail; \
1489 LOAD_FUNCPTR(gnutls_alert_get)
1490 LOAD_FUNCPTR(gnutls_alert_get_name)
1491 LOAD_FUNCPTR(gnutls_certificate_allocate_credentials)
1492 LOAD_FUNCPTR(gnutls_certificate_free_credentials)
1493 LOAD_FUNCPTR(gnutls_certificate_get_peers)
1494 LOAD_FUNCPTR(gnutls_cipher_get)
1495 LOAD_FUNCPTR(gnutls_cipher_get_key_size)
1496 LOAD_FUNCPTR(gnutls_credentials_set)
1497 LOAD_FUNCPTR(gnutls_deinit)
1498 LOAD_FUNCPTR(gnutls_global_deinit)
1499 LOAD_FUNCPTR(gnutls_global_init)
1500 LOAD_FUNCPTR(gnutls_global_set_log_function)
1501 LOAD_FUNCPTR(gnutls_global_set_log_level)
1502 LOAD_FUNCPTR(gnutls_handshake)
1503 LOAD_FUNCPTR(gnutls_init)
1504 LOAD_FUNCPTR(gnutls_kx_get)
1505 LOAD_FUNCPTR(gnutls_mac_get)
1506 LOAD_FUNCPTR(gnutls_mac_get_key_size)
1507 LOAD_FUNCPTR(gnutls_perror)
1508 LOAD_FUNCPTR(gnutls_protocol_get_version)
1509 LOAD_FUNCPTR(gnutls_set_default_priority)
1510 LOAD_FUNCPTR(gnutls_record_recv);
1511 LOAD_FUNCPTR(gnutls_record_send);
1512 LOAD_FUNCPTR(gnutls_transport_set_errno)
1513 LOAD_FUNCPTR(gnutls_transport_set_ptr)
1514 LOAD_FUNCPTR(gnutls_transport_set_pull_function)
1515 LOAD_FUNCPTR(gnutls_transport_set_push_function)
1516 #undef LOAD_FUNCPTR
1518 ret = pgnutls_global_init();
1519 if (ret != GNUTLS_E_SUCCESS)
1521 pgnutls_perror(ret);
1522 goto fail;
1525 if (TRACE_ON(secur32))
1527 pgnutls_global_set_log_level(4);
1528 pgnutls_global_set_log_function(schan_gnutls_log);
1531 schan_handle_table = HeapAlloc(GetProcessHeap(), 0, 64 * sizeof(*schan_handle_table));
1532 if (!schan_handle_table)
1534 ERR("Failed to allocate schannel handle table.\n");
1535 goto fail;
1537 schan_handle_table_size = 64;
1539 provider = SECUR32_addProvider(&schanTableA, &schanTableW, schannelDllName);
1540 if (!provider)
1542 ERR("Failed to add schannel provider.\n");
1543 goto fail;
1546 SECUR32_addPackages(provider, sizeof(info) / sizeof(info[0]), NULL, info);
1548 return;
1550 fail:
1551 HeapFree(GetProcessHeap(), 0, schan_handle_table);
1552 schan_handle_table = NULL;
1553 wine_dlclose(libgnutls_handle, NULL, 0);
1554 libgnutls_handle = NULL;
1555 return;
1558 void SECUR32_deinitSchannelSP(void)
1560 SIZE_T i = schan_handle_count;
1562 if (!libgnutls_handle) return;
1564 /* deinitialized sessions first because a pointer to the credentials
1565 * are stored for the session by calling gnutls_credentials_set. */
1566 while (i--)
1568 if (schan_handle_table[i].type == SCHAN_HANDLE_CTX)
1570 struct schan_context *ctx = schan_free_handle(i, SCHAN_HANDLE_CTX);
1571 pgnutls_deinit(ctx->session);
1572 HeapFree(GetProcessHeap(), 0, ctx);
1575 i = schan_handle_count;
1576 while (i--)
1578 if (schan_handle_table[i].type != SCHAN_HANDLE_FREE)
1580 struct schan_credentials *cred;
1581 cred = schan_free_handle(i, SCHAN_HANDLE_CRED);
1582 pgnutls_certificate_free_credentials(cred->credentials);
1583 HeapFree(GetProcessHeap(), 0, cred);
1586 HeapFree(GetProcessHeap(), 0, schan_handle_table);
1587 pgnutls_global_deinit();
1588 wine_dlclose(libgnutls_handle, NULL, 0);
1591 #else /* SONAME_LIBGNUTLS */
1593 void SECUR32_initSchannelSP(void)
1595 ERR("libgnutls not found, SSL connections will fail\n");
1598 void SECUR32_deinitSchannelSP(void) {}
1600 #endif /* SONAME_LIBGNUTLS */