secur32: Make no-implementation error message non-GnuTLS-specific.
[wine/multimedia.git] / dlls / secur32 / schannel.c
blob4cebf4bd3ca2769ab235597b5c221502389ee73e
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 typedef struct schan_imp_session_opaque *schan_imp_session;
76 typedef struct schan_imp_certificate_credentials_opaque *schan_imp_certificate_credentials;
78 struct schan_transport;
81 static int schan_pull(struct schan_transport *t, void *buff, size_t *buff_len);
82 static int schan_push(struct schan_transport *t, const void *buff, size_t *buff_len);
84 static schan_imp_session schan_session_for_transport(struct schan_transport* t);
87 static ssize_t schan_pull_adapter(gnutls_transport_ptr_t transport,
88 void *buff, size_t buff_len)
90 struct schan_transport *t = (struct schan_transport*)transport;
91 gnutls_session_t s = (gnutls_session_t)schan_session_for_transport(t);
93 int ret = schan_pull(transport, buff, &buff_len);
94 if (ret)
96 pgnutls_transport_set_errno(s, ret);
97 return -1;
100 return buff_len;
103 static ssize_t schan_push_adapter(gnutls_transport_ptr_t transport,
104 const void *buff, size_t buff_len)
106 struct schan_transport *t = (struct schan_transport*)transport;
107 gnutls_session_t s = (gnutls_session_t)schan_session_for_transport(t);
109 int ret = schan_push(transport, buff, &buff_len);
110 if (ret)
112 pgnutls_transport_set_errno(s, ret);
113 return -1;
116 return buff_len;
119 static BOOL schan_imp_create_session(schan_imp_session *session, BOOL is_server,
120 schan_imp_certificate_credentials cred)
122 gnutls_session_t *s = (gnutls_session_t*)session;
124 int err = pgnutls_init(s, is_server ? GNUTLS_SERVER : GNUTLS_CLIENT);
125 if (err != GNUTLS_E_SUCCESS)
127 pgnutls_perror(err);
128 return FALSE;
131 /* FIXME: We should be using the information from the credentials here. */
132 FIXME("Using hardcoded \"NORMAL\" priority\n");
133 err = pgnutls_set_default_priority(*s);
134 if (err != GNUTLS_E_SUCCESS)
136 pgnutls_perror(err);
137 pgnutls_deinit(*s);
138 return FALSE;
141 err = pgnutls_credentials_set(*s, GNUTLS_CRD_CERTIFICATE,
142 (gnutls_certificate_credentials)cred);
143 if (err != GNUTLS_E_SUCCESS)
145 pgnutls_perror(err);
146 pgnutls_deinit(*s);
147 return FALSE;
150 pgnutls_transport_set_pull_function(*s, schan_pull_adapter);
151 pgnutls_transport_set_push_function(*s, schan_push_adapter);
153 return TRUE;
156 static void schan_imp_dispose_session(schan_imp_session session)
158 gnutls_session_t s = (gnutls_session_t)session;
159 pgnutls_deinit(s);
162 static void schan_imp_set_session_transport(schan_imp_session session,
163 struct schan_transport *t)
165 gnutls_session_t s = (gnutls_session_t)session;
166 pgnutls_transport_set_ptr(s, (gnutls_transport_ptr_t)t);
169 static SECURITY_STATUS schan_imp_handshake(schan_imp_session session)
171 gnutls_session_t s = (gnutls_session_t)session;
172 int err = pgnutls_handshake(s);
173 switch(err)
175 case GNUTLS_E_SUCCESS:
176 TRACE("Handshake completed\n");
177 return SEC_E_OK;
179 case GNUTLS_E_AGAIN:
180 TRACE("Continue...\n");
181 return SEC_I_CONTINUE_NEEDED;
183 case GNUTLS_E_WARNING_ALERT_RECEIVED:
184 case GNUTLS_E_FATAL_ALERT_RECEIVED:
186 gnutls_alert_description_t alert = pgnutls_alert_get(s);
187 const char *alert_name = pgnutls_alert_get_name(alert);
188 WARN("ALERT: %d %s\n", alert, alert_name);
189 return SEC_E_INTERNAL_ERROR;
192 default:
193 pgnutls_perror(err);
194 return SEC_E_INTERNAL_ERROR;
197 /* Never reached */
198 return SEC_E_OK;
201 static unsigned int schannel_get_cipher_block_size(gnutls_cipher_algorithm_t cipher)
203 const struct
205 gnutls_cipher_algorithm_t cipher;
206 unsigned int block_size;
208 algorithms[] =
210 {GNUTLS_CIPHER_3DES_CBC, 8},
211 {GNUTLS_CIPHER_AES_128_CBC, 16},
212 {GNUTLS_CIPHER_AES_256_CBC, 16},
213 {GNUTLS_CIPHER_ARCFOUR_128, 1},
214 {GNUTLS_CIPHER_ARCFOUR_40, 1},
215 {GNUTLS_CIPHER_DES_CBC, 8},
216 {GNUTLS_CIPHER_NULL, 1},
217 {GNUTLS_CIPHER_RC2_40_CBC, 8},
219 unsigned int i;
221 for (i = 0; i < sizeof(algorithms) / sizeof(*algorithms); ++i)
223 if (algorithms[i].cipher == cipher)
224 return algorithms[i].block_size;
227 FIXME("Unknown cipher %#x, returning 1\n", cipher);
229 return 1;
232 static DWORD schannel_get_protocol(gnutls_protocol_t proto)
234 /* FIXME: currently schannel only implements client connections, but
235 * there's no reason it couldn't be used for servers as well. The
236 * context doesn't tell us which it is, so assume client for now.
238 switch (proto)
240 case GNUTLS_SSL3: return SP_PROT_SSL3_CLIENT;
241 case GNUTLS_TLS1_0: return SP_PROT_TLS1_CLIENT;
242 default:
243 FIXME("unknown protocol %d\n", proto);
244 return 0;
248 static ALG_ID schannel_get_cipher_algid(gnutls_cipher_algorithm_t cipher)
250 switch (cipher)
252 case GNUTLS_CIPHER_UNKNOWN:
253 case GNUTLS_CIPHER_NULL: return 0;
254 case GNUTLS_CIPHER_ARCFOUR_40:
255 case GNUTLS_CIPHER_ARCFOUR_128: return CALG_RC4;
256 case GNUTLS_CIPHER_DES_CBC:
257 case GNUTLS_CIPHER_3DES_CBC: return CALG_DES;
258 case GNUTLS_CIPHER_AES_128_CBC:
259 case GNUTLS_CIPHER_AES_256_CBC: return CALG_AES;
260 case GNUTLS_CIPHER_RC2_40_CBC: return CALG_RC2;
261 default:
262 FIXME("unknown algorithm %d\n", cipher);
263 return 0;
267 static ALG_ID schannel_get_mac_algid(gnutls_mac_algorithm_t mac)
269 switch (mac)
271 case GNUTLS_MAC_UNKNOWN:
272 case GNUTLS_MAC_NULL: return 0;
273 case GNUTLS_MAC_MD5: return CALG_MD5;
274 case GNUTLS_MAC_SHA1:
275 case GNUTLS_MAC_SHA256:
276 case GNUTLS_MAC_SHA384:
277 case GNUTLS_MAC_SHA512: return CALG_SHA;
278 default:
279 FIXME("unknown algorithm %d\n", mac);
280 return 0;
284 static ALG_ID schannel_get_kx_algid(gnutls_kx_algorithm_t kx)
286 switch (kx)
288 case GNUTLS_KX_RSA: return CALG_RSA_KEYX;
289 case GNUTLS_KX_DHE_DSS:
290 case GNUTLS_KX_DHE_RSA: return CALG_DH_EPHEM;
291 default:
292 FIXME("unknown algorithm %d\n", kx);
293 return 0;
297 static unsigned int schan_imp_get_session_cipher_block_size(schan_imp_session session)
299 gnutls_session_t s = (gnutls_session_t)session;
300 gnutls_cipher_algorithm_t cipher = pgnutls_cipher_get(s);
301 return schannel_get_cipher_block_size(cipher);
304 static SECURITY_STATUS schan_imp_get_connection_info(schan_imp_session session,
305 SecPkgContext_ConnectionInfo *info)
307 gnutls_session_t s = (gnutls_session_t)session;
308 gnutls_protocol_t proto = pgnutls_protocol_get_version(s);
309 gnutls_cipher_algorithm_t alg = pgnutls_cipher_get(s);
310 gnutls_mac_algorithm_t mac = pgnutls_mac_get(s);
311 gnutls_kx_algorithm_t kx = pgnutls_kx_get(s);
313 info->dwProtocol = schannel_get_protocol(proto);
314 info->aiCipher = schannel_get_cipher_algid(alg);
315 info->dwCipherStrength = pgnutls_cipher_get_key_size(alg);
316 info->aiHash = schannel_get_mac_algid(mac);
317 info->dwHashStrength = pgnutls_mac_get_key_size(mac);
318 info->aiExch = schannel_get_kx_algid(kx);
319 /* FIXME: info->dwExchStrength? */
320 info->dwExchStrength = 0;
321 return SEC_E_OK;
324 static SECURITY_STATUS schan_imp_get_session_peer_certificate(schan_imp_session session,
325 PCCERT_CONTEXT *cert)
327 gnutls_session_t s = (gnutls_session_t)session;
328 unsigned int list_size;
329 const gnutls_datum_t *datum;
331 datum = pgnutls_certificate_get_peers(s, &list_size);
332 if (datum)
334 *cert = CertCreateCertificateContext(X509_ASN_ENCODING, datum->data,
335 datum->size);
336 if (!*cert)
337 return GetLastError();
338 else
339 return SEC_E_OK;
341 else
342 return SEC_E_INTERNAL_ERROR;
345 static SECURITY_STATUS schan_imp_send(schan_imp_session session, const void *buffer,
346 size_t *length)
348 gnutls_session_t s = (gnutls_session_t)session;
349 ssize_t ret = pgnutls_record_send(s, buffer, *length);
350 if (ret >= 0)
351 *length = ret;
352 else if (ret == GNUTLS_E_AGAIN)
353 return SEC_I_CONTINUE_NEEDED;
354 else
356 pgnutls_perror(ret);
357 return SEC_E_INTERNAL_ERROR;
360 return SEC_E_OK;
363 static SECURITY_STATUS schan_imp_recv(schan_imp_session session, void *buffer,
364 size_t *length)
366 gnutls_session_t s = (gnutls_session_t)session;
367 ssize_t ret = pgnutls_record_recv(s, buffer, *length);
368 if (ret >= 0)
369 *length = ret;
370 else if (ret == GNUTLS_E_AGAIN)
371 return SEC_I_CONTINUE_NEEDED;
372 else
374 pgnutls_perror(ret);
375 return SEC_E_INTERNAL_ERROR;
378 return SEC_E_OK;
381 static BOOL schan_imp_allocate_certificate_credentials(schan_imp_certificate_credentials *c)
383 int ret = pgnutls_certificate_allocate_credentials((gnutls_certificate_credentials*)c);
384 if (ret != GNUTLS_E_SUCCESS)
385 pgnutls_perror(ret);
386 return (ret == GNUTLS_E_SUCCESS);
389 static void schan_imp_free_certificate_credentials(schan_imp_certificate_credentials c)
391 pgnutls_certificate_free_credentials((gnutls_certificate_credentials)c);
394 static void schan_gnutls_log(int level, const char *msg)
396 TRACE("<%d> %s", level, msg);
399 static BOOL schan_imp_init(void)
401 int ret;
403 libgnutls_handle = wine_dlopen(SONAME_LIBGNUTLS, RTLD_NOW, NULL, 0);
404 if (!libgnutls_handle)
406 WARN("Failed to load libgnutls.\n");
407 return FALSE;
410 #define LOAD_FUNCPTR(f) \
411 if (!(p##f = wine_dlsym(libgnutls_handle, #f, NULL, 0))) \
413 ERR("Failed to load %s\n", #f); \
414 goto fail; \
417 LOAD_FUNCPTR(gnutls_alert_get)
418 LOAD_FUNCPTR(gnutls_alert_get_name)
419 LOAD_FUNCPTR(gnutls_certificate_allocate_credentials)
420 LOAD_FUNCPTR(gnutls_certificate_free_credentials)
421 LOAD_FUNCPTR(gnutls_certificate_get_peers)
422 LOAD_FUNCPTR(gnutls_cipher_get)
423 LOAD_FUNCPTR(gnutls_cipher_get_key_size)
424 LOAD_FUNCPTR(gnutls_credentials_set)
425 LOAD_FUNCPTR(gnutls_deinit)
426 LOAD_FUNCPTR(gnutls_global_deinit)
427 LOAD_FUNCPTR(gnutls_global_init)
428 LOAD_FUNCPTR(gnutls_global_set_log_function)
429 LOAD_FUNCPTR(gnutls_global_set_log_level)
430 LOAD_FUNCPTR(gnutls_handshake)
431 LOAD_FUNCPTR(gnutls_init)
432 LOAD_FUNCPTR(gnutls_kx_get)
433 LOAD_FUNCPTR(gnutls_mac_get)
434 LOAD_FUNCPTR(gnutls_mac_get_key_size)
435 LOAD_FUNCPTR(gnutls_perror)
436 LOAD_FUNCPTR(gnutls_protocol_get_version)
437 LOAD_FUNCPTR(gnutls_set_default_priority)
438 LOAD_FUNCPTR(gnutls_record_recv);
439 LOAD_FUNCPTR(gnutls_record_send);
440 LOAD_FUNCPTR(gnutls_transport_set_errno)
441 LOAD_FUNCPTR(gnutls_transport_set_ptr)
442 LOAD_FUNCPTR(gnutls_transport_set_pull_function)
443 LOAD_FUNCPTR(gnutls_transport_set_push_function)
444 #undef LOAD_FUNCPTR
446 ret = pgnutls_global_init();
447 if (ret != GNUTLS_E_SUCCESS)
449 pgnutls_perror(ret);
450 goto fail;
453 if (TRACE_ON(secur32))
455 pgnutls_global_set_log_level(4);
456 pgnutls_global_set_log_function(schan_gnutls_log);
459 return TRUE;
461 fail:
462 wine_dlclose(libgnutls_handle, NULL, 0);
463 libgnutls_handle = NULL;
464 return FALSE;
467 static void schan_imp_deinit(void)
469 pgnutls_global_deinit();
470 wine_dlclose(libgnutls_handle, NULL, 0);
471 libgnutls_handle = NULL;
475 #define SCHAN_INVALID_HANDLE ~0UL
477 enum schan_handle_type
479 SCHAN_HANDLE_CRED,
480 SCHAN_HANDLE_CTX,
481 SCHAN_HANDLE_FREE
484 struct schan_handle
486 void *object;
487 enum schan_handle_type type;
490 struct schan_credentials
492 ULONG credential_use;
493 schan_imp_certificate_credentials credentials;
496 struct schan_context
498 schan_imp_session session;
499 ULONG req_ctx_attr;
502 struct schan_buffers
504 SIZE_T offset;
505 SIZE_T limit;
506 const SecBufferDesc *desc;
507 int current_buffer_idx;
508 BOOL allow_buffer_resize;
509 int (*get_next_buffer)(const struct schan_transport *, struct schan_buffers *);
512 struct schan_transport
514 struct schan_context *ctx;
515 struct schan_buffers in;
516 struct schan_buffers out;
519 static struct schan_handle *schan_handle_table;
520 static struct schan_handle *schan_free_handles;
521 static SIZE_T schan_handle_table_size;
522 static SIZE_T schan_handle_count;
524 static ULONG_PTR schan_alloc_handle(void *object, enum schan_handle_type type)
526 struct schan_handle *handle;
528 if (schan_free_handles)
530 DWORD index = schan_free_handles - schan_handle_table;
531 /* Use a free handle */
532 handle = schan_free_handles;
533 if (handle->type != SCHAN_HANDLE_FREE)
535 ERR("Handle %d(%p) is in the free list, but has type %#x.\n", index, handle, handle->type);
536 return SCHAN_INVALID_HANDLE;
538 schan_free_handles = handle->object;
539 handle->object = object;
540 handle->type = type;
542 return index;
544 if (!(schan_handle_count < schan_handle_table_size))
546 /* Grow the table */
547 SIZE_T new_size = schan_handle_table_size + (schan_handle_table_size >> 1);
548 struct schan_handle *new_table = HeapReAlloc(GetProcessHeap(), 0, schan_handle_table, new_size * sizeof(*schan_handle_table));
549 if (!new_table)
551 ERR("Failed to grow the handle table\n");
552 return SCHAN_INVALID_HANDLE;
554 schan_handle_table = new_table;
555 schan_handle_table_size = new_size;
558 handle = &schan_handle_table[schan_handle_count++];
559 handle->object = object;
560 handle->type = type;
562 return handle - schan_handle_table;
565 static void *schan_free_handle(ULONG_PTR handle_idx, enum schan_handle_type type)
567 struct schan_handle *handle;
568 void *object;
570 if (handle_idx == SCHAN_INVALID_HANDLE) return NULL;
571 if (handle_idx >= schan_handle_count) return NULL;
572 handle = &schan_handle_table[handle_idx];
573 if (handle->type != type)
575 ERR("Handle %ld(%p) is not of type %#x\n", handle_idx, handle, type);
576 return NULL;
579 object = handle->object;
580 handle->object = schan_free_handles;
581 handle->type = SCHAN_HANDLE_FREE;
582 schan_free_handles = handle;
584 return object;
587 static void *schan_get_object(ULONG_PTR handle_idx, enum schan_handle_type type)
589 struct schan_handle *handle;
591 if (handle_idx == SCHAN_INVALID_HANDLE) return NULL;
592 if (handle_idx >= schan_handle_count) return NULL;
593 handle = &schan_handle_table[handle_idx];
594 if (handle->type != type)
596 ERR("Handle %ld(%p) is not of type %#x\n", handle_idx, handle, type);
597 return NULL;
600 return handle->object;
603 static SECURITY_STATUS schan_QueryCredentialsAttributes(
604 PCredHandle phCredential, ULONG ulAttribute, VOID *pBuffer)
606 SECURITY_STATUS ret;
608 switch (ulAttribute)
610 case SECPKG_ATTR_SUPPORTED_ALGS:
611 if (pBuffer)
613 /* FIXME: get from CryptoAPI */
614 FIXME("SECPKG_ATTR_SUPPORTED_ALGS: stub\n");
615 ret = SEC_E_UNSUPPORTED_FUNCTION;
617 else
618 ret = SEC_E_INTERNAL_ERROR;
619 break;
620 case SECPKG_ATTR_CIPHER_STRENGTHS:
621 if (pBuffer)
623 SecPkgCred_CipherStrengths *r = pBuffer;
625 /* FIXME: get from CryptoAPI */
626 FIXME("SECPKG_ATTR_CIPHER_STRENGTHS: semi-stub\n");
627 r->dwMinimumCipherStrength = 40;
628 r->dwMaximumCipherStrength = 168;
629 ret = SEC_E_OK;
631 else
632 ret = SEC_E_INTERNAL_ERROR;
633 break;
634 case SECPKG_ATTR_SUPPORTED_PROTOCOLS:
635 if (pBuffer)
637 /* FIXME: get from OpenSSL? */
638 FIXME("SECPKG_ATTR_SUPPORTED_PROTOCOLS: stub\n");
639 ret = SEC_E_UNSUPPORTED_FUNCTION;
641 else
642 ret = SEC_E_INTERNAL_ERROR;
643 break;
644 default:
645 ret = SEC_E_UNSUPPORTED_FUNCTION;
647 return ret;
650 static SECURITY_STATUS SEC_ENTRY schan_QueryCredentialsAttributesA(
651 PCredHandle phCredential, ULONG ulAttribute, PVOID pBuffer)
653 SECURITY_STATUS ret;
655 TRACE("(%p, %d, %p)\n", phCredential, ulAttribute, pBuffer);
657 switch (ulAttribute)
659 case SECPKG_CRED_ATTR_NAMES:
660 FIXME("SECPKG_CRED_ATTR_NAMES: stub\n");
661 ret = SEC_E_UNSUPPORTED_FUNCTION;
662 break;
663 default:
664 ret = schan_QueryCredentialsAttributes(phCredential, ulAttribute,
665 pBuffer);
667 return ret;
670 static SECURITY_STATUS SEC_ENTRY schan_QueryCredentialsAttributesW(
671 PCredHandle phCredential, ULONG ulAttribute, PVOID pBuffer)
673 SECURITY_STATUS ret;
675 TRACE("(%p, %d, %p)\n", phCredential, ulAttribute, pBuffer);
677 switch (ulAttribute)
679 case SECPKG_CRED_ATTR_NAMES:
680 FIXME("SECPKG_CRED_ATTR_NAMES: stub\n");
681 ret = SEC_E_UNSUPPORTED_FUNCTION;
682 break;
683 default:
684 ret = schan_QueryCredentialsAttributes(phCredential, ulAttribute,
685 pBuffer);
687 return ret;
690 static SECURITY_STATUS schan_CheckCreds(const SCHANNEL_CRED *schanCred)
692 SECURITY_STATUS st;
693 DWORD i;
695 TRACE("dwVersion = %d\n", schanCred->dwVersion);
696 TRACE("cCreds = %d\n", schanCred->cCreds);
697 TRACE("hRootStore = %p\n", schanCred->hRootStore);
698 TRACE("cMappers = %d\n", schanCred->cMappers);
699 TRACE("cSupportedAlgs = %d:\n", schanCred->cSupportedAlgs);
700 for (i = 0; i < schanCred->cSupportedAlgs; i++)
701 TRACE("%08x\n", schanCred->palgSupportedAlgs[i]);
702 TRACE("grbitEnabledProtocols = %08x\n", schanCred->grbitEnabledProtocols);
703 TRACE("dwMinimumCipherStrength = %d\n", schanCred->dwMinimumCipherStrength);
704 TRACE("dwMaximumCipherStrength = %d\n", schanCred->dwMaximumCipherStrength);
705 TRACE("dwSessionLifespan = %d\n", schanCred->dwSessionLifespan);
706 TRACE("dwFlags = %08x\n", schanCred->dwFlags);
707 TRACE("dwCredFormat = %d\n", schanCred->dwCredFormat);
709 switch (schanCred->dwVersion)
711 case SCH_CRED_V3:
712 case SCHANNEL_CRED_VERSION:
713 break;
714 default:
715 return SEC_E_INTERNAL_ERROR;
718 if (schanCred->cCreds == 0)
719 st = SEC_E_NO_CREDENTIALS;
720 else if (schanCred->cCreds > 1)
721 st = SEC_E_UNKNOWN_CREDENTIALS;
722 else
724 DWORD keySpec;
725 HCRYPTPROV csp;
726 BOOL ret, freeCSP;
728 ret = CryptAcquireCertificatePrivateKey(schanCred->paCred[0],
729 0, /* FIXME: what flags to use? */ NULL,
730 &csp, &keySpec, &freeCSP);
731 if (ret)
733 st = SEC_E_OK;
734 if (freeCSP)
735 CryptReleaseContext(csp, 0);
737 else
738 st = SEC_E_UNKNOWN_CREDENTIALS;
740 return st;
743 static SECURITY_STATUS schan_AcquireClientCredentials(const SCHANNEL_CRED *schanCred,
744 PCredHandle phCredential, PTimeStamp ptsExpiry)
746 struct schan_credentials *creds;
747 SECURITY_STATUS st = SEC_E_OK;
749 TRACE("schanCred %p, phCredential %p, ptsExpiry %p\n", schanCred, phCredential, ptsExpiry);
751 if (schanCred)
753 st = schan_CheckCreds(schanCred);
754 if (st == SEC_E_NO_CREDENTIALS)
755 st = SEC_E_OK;
758 /* For now, the only thing I'm interested in is the direction of the
759 * connection, so just store it.
761 if (st == SEC_E_OK)
763 ULONG_PTR handle;
765 creds = HeapAlloc(GetProcessHeap(), 0, sizeof(*creds));
766 if (!creds) return SEC_E_INSUFFICIENT_MEMORY;
768 handle = schan_alloc_handle(creds, SCHAN_HANDLE_CRED);
769 if (handle == SCHAN_INVALID_HANDLE) goto fail;
771 creds->credential_use = SECPKG_CRED_OUTBOUND;
772 if (!schan_imp_allocate_certificate_credentials(&creds->credentials))
774 schan_free_handle(handle, SCHAN_HANDLE_CRED);
775 goto fail;
778 phCredential->dwLower = handle;
779 phCredential->dwUpper = 0;
781 /* Outbound credentials have no expiry */
782 if (ptsExpiry)
784 ptsExpiry->LowPart = 0;
785 ptsExpiry->HighPart = 0;
788 return st;
790 fail:
791 HeapFree(GetProcessHeap(), 0, creds);
792 return SEC_E_INTERNAL_ERROR;
795 static SECURITY_STATUS schan_AcquireServerCredentials(const SCHANNEL_CRED *schanCred,
796 PCredHandle phCredential, PTimeStamp ptsExpiry)
798 SECURITY_STATUS st;
800 TRACE("schanCred %p, phCredential %p, ptsExpiry %p\n", schanCred, phCredential, ptsExpiry);
802 if (!schanCred) return SEC_E_NO_CREDENTIALS;
804 st = schan_CheckCreds(schanCred);
805 if (st == SEC_E_OK)
807 ULONG_PTR handle;
808 struct schan_credentials *creds;
810 creds = HeapAlloc(GetProcessHeap(), 0, sizeof(*creds));
811 if (!creds) return SEC_E_INSUFFICIENT_MEMORY;
812 creds->credential_use = SECPKG_CRED_INBOUND;
814 handle = schan_alloc_handle(creds, SCHAN_HANDLE_CRED);
815 if (handle == SCHAN_INVALID_HANDLE)
817 HeapFree(GetProcessHeap(), 0, creds);
818 return SEC_E_INTERNAL_ERROR;
821 phCredential->dwLower = handle;
822 phCredential->dwUpper = 0;
824 /* FIXME: get expiry from cert */
826 return st;
829 static SECURITY_STATUS schan_AcquireCredentialsHandle(ULONG fCredentialUse,
830 const SCHANNEL_CRED *schanCred, PCredHandle phCredential, PTimeStamp ptsExpiry)
832 SECURITY_STATUS ret;
834 if (fCredentialUse == SECPKG_CRED_OUTBOUND)
835 ret = schan_AcquireClientCredentials(schanCred, phCredential,
836 ptsExpiry);
837 else
838 ret = schan_AcquireServerCredentials(schanCred, phCredential,
839 ptsExpiry);
840 return ret;
843 static SECURITY_STATUS SEC_ENTRY schan_AcquireCredentialsHandleA(
844 SEC_CHAR *pszPrincipal, SEC_CHAR *pszPackage, ULONG fCredentialUse,
845 PLUID pLogonID, PVOID pAuthData, SEC_GET_KEY_FN pGetKeyFn,
846 PVOID pGetKeyArgument, PCredHandle phCredential, PTimeStamp ptsExpiry)
848 TRACE("(%s, %s, 0x%08x, %p, %p, %p, %p, %p, %p)\n",
849 debugstr_a(pszPrincipal), debugstr_a(pszPackage), fCredentialUse,
850 pLogonID, pAuthData, pGetKeyFn, pGetKeyArgument, phCredential, ptsExpiry);
851 return schan_AcquireCredentialsHandle(fCredentialUse,
852 pAuthData, phCredential, ptsExpiry);
855 static SECURITY_STATUS SEC_ENTRY schan_AcquireCredentialsHandleW(
856 SEC_WCHAR *pszPrincipal, SEC_WCHAR *pszPackage, ULONG fCredentialUse,
857 PLUID pLogonID, PVOID pAuthData, SEC_GET_KEY_FN pGetKeyFn,
858 PVOID pGetKeyArgument, PCredHandle phCredential, PTimeStamp ptsExpiry)
860 TRACE("(%s, %s, 0x%08x, %p, %p, %p, %p, %p, %p)\n",
861 debugstr_w(pszPrincipal), debugstr_w(pszPackage), fCredentialUse,
862 pLogonID, pAuthData, pGetKeyFn, pGetKeyArgument, phCredential, ptsExpiry);
863 return schan_AcquireCredentialsHandle(fCredentialUse,
864 pAuthData, phCredential, ptsExpiry);
867 static SECURITY_STATUS SEC_ENTRY schan_FreeCredentialsHandle(
868 PCredHandle phCredential)
870 struct schan_credentials *creds;
872 TRACE("phCredential %p\n", phCredential);
874 if (!phCredential) return SEC_E_INVALID_HANDLE;
876 creds = schan_free_handle(phCredential->dwLower, SCHAN_HANDLE_CRED);
877 if (!creds) return SEC_E_INVALID_HANDLE;
879 if (creds->credential_use == SECPKG_CRED_OUTBOUND)
880 schan_imp_free_certificate_credentials(creds->credentials);
881 HeapFree(GetProcessHeap(), 0, creds);
883 return SEC_E_OK;
886 static void init_schan_buffers(struct schan_buffers *s, const PSecBufferDesc desc,
887 int (*get_next_buffer)(const struct schan_transport *, struct schan_buffers *))
889 s->offset = 0;
890 s->limit = 0;
891 s->desc = desc;
892 s->current_buffer_idx = -1;
893 s->allow_buffer_resize = FALSE;
894 s->get_next_buffer = get_next_buffer;
897 static int schan_find_sec_buffer_idx(const SecBufferDesc *desc, unsigned int start_idx, ULONG buffer_type)
899 unsigned int i;
900 PSecBuffer buffer;
902 for (i = start_idx; i < desc->cBuffers; ++i)
904 buffer = &desc->pBuffers[i];
905 if (buffer->BufferType == buffer_type) return i;
908 return -1;
911 static void schan_resize_current_buffer(const struct schan_buffers *s, SIZE_T min_size)
913 SecBuffer *b = &s->desc->pBuffers[s->current_buffer_idx];
914 SIZE_T new_size = b->cbBuffer ? b->cbBuffer * 2 : 128;
915 void *new_data;
917 if (b->cbBuffer >= min_size || !s->allow_buffer_resize || min_size > UINT_MAX / 2) return;
919 while (new_size < min_size) new_size *= 2;
921 if (b->pvBuffer)
922 new_data = HeapReAlloc(GetProcessHeap(), 0, b->pvBuffer, new_size);
923 else
924 new_data = HeapAlloc(GetProcessHeap(), 0, new_size);
926 if (!new_data)
928 TRACE("Failed to resize %p from %d to %ld\n", b->pvBuffer, b->cbBuffer, new_size);
929 return;
932 b->cbBuffer = new_size;
933 b->pvBuffer = new_data;
936 static char *schan_get_buffer(const struct schan_transport *t, struct schan_buffers *s, size_t *count)
938 SIZE_T max_count;
939 PSecBuffer buffer;
941 if (!s->desc)
943 TRACE("No desc\n");
944 return NULL;
947 if (s->current_buffer_idx == -1)
949 /* Initial buffer */
950 int buffer_idx = s->get_next_buffer(t, s);
951 if (buffer_idx == -1)
953 TRACE("No next buffer\n");
954 return NULL;
956 s->current_buffer_idx = buffer_idx;
959 buffer = &s->desc->pBuffers[s->current_buffer_idx];
960 TRACE("Using buffer %d: cbBuffer %d, BufferType %#x, pvBuffer %p\n", s->current_buffer_idx, buffer->cbBuffer, buffer->BufferType, buffer->pvBuffer);
962 schan_resize_current_buffer(s, s->offset + *count);
963 max_count = buffer->cbBuffer - s->offset;
964 if (!max_count)
966 int buffer_idx;
968 s->allow_buffer_resize = FALSE;
969 buffer_idx = s->get_next_buffer(t, s);
970 if (buffer_idx == -1)
972 TRACE("No next buffer\n");
973 return NULL;
975 s->current_buffer_idx = buffer_idx;
976 s->offset = 0;
977 return schan_get_buffer(t, s, count);
980 if (*count > max_count) *count = max_count;
981 return (char *)buffer->pvBuffer + s->offset;
984 /* schan_pull
985 * Read data from the transport input buffer.
987 * t - The session transport object.
988 * buff - The buffer into which to store the read data. Must be at least
989 * *buff_len bytes in length.
990 * buff_len - On input, *buff_len is the desired length to read. On successful
991 * return, *buff_len is the number of bytes actually read.
993 * Returns:
994 * 0 on success, in which case:
995 * *buff_len == 0 indicates end of file.
996 * *buff_len > 0 indicates that some data was read. May be less than
997 * what was requested, in which case the caller should call again if/
998 * when they want more.
999 * EAGAIN when no data could be read without blocking
1000 * another errno-style error value on failure
1003 static int schan_pull(struct schan_transport *t, void *buff, size_t *buff_len)
1005 char *b;
1006 size_t local_len = *buff_len;
1008 TRACE("Pull %zu bytes\n", local_len);
1010 *buff_len = 0;
1012 b = schan_get_buffer(t, &t->in, &local_len);
1013 if (!b)
1014 return EAGAIN;
1016 if (t->in.limit != 0 && t->in.offset + local_len >= t->in.limit)
1018 local_len = t->in.limit - t->in.offset;
1019 if (local_len == 0)
1020 return EAGAIN;
1023 memcpy(buff, b, local_len);
1024 t->in.offset += local_len;
1026 TRACE("Read %zu bytes\n", local_len);
1028 *buff_len = local_len;
1029 return 0;
1032 /* schan_push
1033 * Write data to the transport output buffer.
1035 * t - The session transport object.
1036 * buff - The buffer of data to write. Must be at least *buff_len bytes in length.
1037 * buff_len - On input, *buff_len is the desired length to write. On successful
1038 * return, *buff_len is the number of bytes actually written.
1040 * Returns:
1041 * 0 on success
1042 * *buff_len will be > 0 indicating how much data was written. May be less
1043 * than what was requested, in which case the caller should call again
1044 if/when they want to write more.
1045 * EAGAIN when no data could be written without blocking
1046 * another errno-style error value on failure
1049 static int schan_push(struct schan_transport *t, const void *buff, size_t *buff_len)
1051 char *b;
1052 size_t local_len = *buff_len;
1054 TRACE("Push %zu bytes\n", local_len);
1056 *buff_len = 0;
1058 b = schan_get_buffer(t, &t->out, &local_len);
1059 if (!b)
1060 return EAGAIN;
1062 memcpy(b, buff, local_len);
1063 t->out.offset += local_len;
1065 TRACE("Wrote %zu bytes\n", local_len);
1067 *buff_len = local_len;
1068 return 0;
1071 static schan_imp_session schan_session_for_transport(struct schan_transport* t)
1073 return t->ctx->session;
1076 static int schan_init_sec_ctx_get_next_buffer(const struct schan_transport *t, struct schan_buffers *s)
1078 if (s->current_buffer_idx == -1)
1080 int idx = schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
1081 if (t->ctx->req_ctx_attr & ISC_REQ_ALLOCATE_MEMORY)
1083 if (idx == -1)
1085 idx = schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_EMPTY);
1086 if (idx != -1) s->desc->pBuffers[idx].BufferType = SECBUFFER_TOKEN;
1088 if (idx != -1 && !s->desc->pBuffers[idx].pvBuffer)
1090 s->desc->pBuffers[idx].cbBuffer = 0;
1091 s->allow_buffer_resize = TRUE;
1094 return idx;
1097 return -1;
1100 static void dump_buffer_desc(SecBufferDesc *desc)
1102 unsigned int i;
1104 if (!desc) return;
1105 TRACE("Buffer desc %p:\n", desc);
1106 for (i = 0; i < desc->cBuffers; ++i)
1108 SecBuffer *b = &desc->pBuffers[i];
1109 TRACE("\tbuffer %u: cbBuffer %d, BufferType %#x pvBuffer %p\n", i, b->cbBuffer, b->BufferType, b->pvBuffer);
1113 /***********************************************************************
1114 * InitializeSecurityContextW
1116 static SECURITY_STATUS SEC_ENTRY schan_InitializeSecurityContextW(
1117 PCredHandle phCredential, PCtxtHandle phContext, SEC_WCHAR *pszTargetName,
1118 ULONG fContextReq, ULONG Reserved1, ULONG TargetDataRep,
1119 PSecBufferDesc pInput, ULONG Reserved2, PCtxtHandle phNewContext,
1120 PSecBufferDesc pOutput, ULONG *pfContextAttr, PTimeStamp ptsExpiry)
1122 struct schan_context *ctx;
1123 struct schan_buffers *out_buffers;
1124 struct schan_credentials *cred;
1125 struct schan_transport transport;
1126 SECURITY_STATUS ret;
1128 TRACE("%p %p %s 0x%08x %d %d %p %d %p %p %p %p\n", phCredential, phContext,
1129 debugstr_w(pszTargetName), fContextReq, Reserved1, TargetDataRep, pInput,
1130 Reserved1, phNewContext, pOutput, pfContextAttr, ptsExpiry);
1132 dump_buffer_desc(pInput);
1133 dump_buffer_desc(pOutput);
1135 if (!phContext)
1137 ULONG_PTR handle;
1139 if (!phCredential) return SEC_E_INVALID_HANDLE;
1141 cred = schan_get_object(phCredential->dwLower, SCHAN_HANDLE_CRED);
1142 if (!cred) return SEC_E_INVALID_HANDLE;
1144 if (!(cred->credential_use & SECPKG_CRED_OUTBOUND))
1146 WARN("Invalid credential use %#x\n", cred->credential_use);
1147 return SEC_E_INVALID_HANDLE;
1150 ctx = HeapAlloc(GetProcessHeap(), 0, sizeof(*ctx));
1151 if (!ctx) return SEC_E_INSUFFICIENT_MEMORY;
1153 handle = schan_alloc_handle(ctx, SCHAN_HANDLE_CTX);
1154 if (handle == SCHAN_INVALID_HANDLE)
1156 HeapFree(GetProcessHeap(), 0, ctx);
1157 return SEC_E_INTERNAL_ERROR;
1160 if (!schan_imp_create_session(&ctx->session, FALSE, cred->credentials))
1162 schan_free_handle(handle, SCHAN_HANDLE_CTX);
1163 HeapFree(GetProcessHeap(), 0, ctx);
1164 return SEC_E_INTERNAL_ERROR;
1167 phNewContext->dwLower = handle;
1168 phNewContext->dwUpper = 0;
1170 else
1172 ctx = schan_get_object(phContext->dwLower, SCHAN_HANDLE_CTX);
1175 ctx->req_ctx_attr = fContextReq;
1177 transport.ctx = ctx;
1178 init_schan_buffers(&transport.in, pInput, schan_init_sec_ctx_get_next_buffer);
1179 init_schan_buffers(&transport.out, pOutput, schan_init_sec_ctx_get_next_buffer);
1180 schan_imp_set_session_transport(ctx->session, &transport);
1182 /* Perform the TLS handshake */
1183 ret = schan_imp_handshake(ctx->session);
1185 if(transport.in.offset && transport.in.offset != pInput->pBuffers[0].cbBuffer) {
1186 if(pInput->cBuffers<2 || pInput->pBuffers[1].BufferType!=SECBUFFER_EMPTY)
1187 return SEC_E_INVALID_TOKEN;
1189 pInput->pBuffers[1].BufferType = SECBUFFER_EXTRA;
1190 pInput->pBuffers[1].cbBuffer = pInput->pBuffers[0].cbBuffer-transport.in.offset;
1193 out_buffers = &transport.out;
1194 if (out_buffers->current_buffer_idx != -1)
1196 SecBuffer *buffer = &out_buffers->desc->pBuffers[out_buffers->current_buffer_idx];
1197 buffer->cbBuffer = out_buffers->offset;
1200 *pfContextAttr = 0;
1201 if (ctx->req_ctx_attr & ISC_REQ_ALLOCATE_MEMORY)
1202 *pfContextAttr |= ISC_RET_ALLOCATED_MEMORY;
1204 return ret;
1207 /***********************************************************************
1208 * InitializeSecurityContextA
1210 static SECURITY_STATUS SEC_ENTRY schan_InitializeSecurityContextA(
1211 PCredHandle phCredential, PCtxtHandle phContext, SEC_CHAR *pszTargetName,
1212 ULONG fContextReq, ULONG Reserved1, ULONG TargetDataRep,
1213 PSecBufferDesc pInput, ULONG Reserved2, PCtxtHandle phNewContext,
1214 PSecBufferDesc pOutput, ULONG *pfContextAttr, PTimeStamp ptsExpiry)
1216 SECURITY_STATUS ret;
1217 SEC_WCHAR *target_name = NULL;
1219 TRACE("%p %p %s %d %d %d %p %d %p %p %p %p\n", phCredential, phContext,
1220 debugstr_a(pszTargetName), fContextReq, Reserved1, TargetDataRep, pInput,
1221 Reserved1, phNewContext, pOutput, pfContextAttr, ptsExpiry);
1223 if (pszTargetName)
1225 INT len = MultiByteToWideChar(CP_ACP, 0, pszTargetName, -1, NULL, 0);
1226 target_name = HeapAlloc(GetProcessHeap(), 0, len * sizeof(*target_name));
1227 MultiByteToWideChar(CP_ACP, 0, pszTargetName, -1, target_name, len);
1230 ret = schan_InitializeSecurityContextW(phCredential, phContext, target_name,
1231 fContextReq, Reserved1, TargetDataRep, pInput, Reserved2,
1232 phNewContext, pOutput, pfContextAttr, ptsExpiry);
1234 HeapFree(GetProcessHeap(), 0, target_name);
1236 return ret;
1239 static SECURITY_STATUS SEC_ENTRY schan_QueryContextAttributesW(
1240 PCtxtHandle context_handle, ULONG attribute, PVOID buffer)
1242 struct schan_context *ctx;
1244 TRACE("context_handle %p, attribute %#x, buffer %p\n",
1245 context_handle, attribute, buffer);
1247 if (!context_handle) return SEC_E_INVALID_HANDLE;
1248 ctx = schan_get_object(context_handle->dwLower, SCHAN_HANDLE_CTX);
1250 switch(attribute)
1252 case SECPKG_ATTR_STREAM_SIZES:
1254 SecPkgContext_ConnectionInfo info;
1255 SECURITY_STATUS status = schan_imp_get_connection_info(ctx->session, &info);
1256 if (status == SEC_E_OK)
1258 SecPkgContext_StreamSizes *stream_sizes = buffer;
1259 size_t mac_size = info.dwHashStrength;
1260 unsigned int block_size = schan_imp_get_session_cipher_block_size(ctx->session);
1262 TRACE("Using %zu mac bytes, block size %u\n", mac_size, block_size);
1264 /* These are defined by the TLS RFC */
1265 stream_sizes->cbHeader = 5;
1266 stream_sizes->cbTrailer = mac_size + 256; /* Max 255 bytes padding + 1 for padding size */
1267 stream_sizes->cbMaximumMessage = 1 << 14;
1268 stream_sizes->cbBuffers = 4;
1269 stream_sizes->cbBlockSize = block_size;
1272 return status;
1274 case SECPKG_ATTR_REMOTE_CERT_CONTEXT:
1276 PCCERT_CONTEXT *cert = buffer;
1277 return schan_imp_get_session_peer_certificate(ctx->session, cert);
1279 case SECPKG_ATTR_CONNECTION_INFO:
1281 SecPkgContext_ConnectionInfo *info = buffer;
1282 return schan_imp_get_connection_info(ctx->session, info);
1285 default:
1286 FIXME("Unhandled attribute %#x\n", attribute);
1287 return SEC_E_UNSUPPORTED_FUNCTION;
1291 static SECURITY_STATUS SEC_ENTRY schan_QueryContextAttributesA(
1292 PCtxtHandle context_handle, ULONG attribute, PVOID buffer)
1294 TRACE("context_handle %p, attribute %#x, buffer %p\n",
1295 context_handle, attribute, buffer);
1297 switch(attribute)
1299 case SECPKG_ATTR_STREAM_SIZES:
1300 return schan_QueryContextAttributesW(context_handle, attribute, buffer);
1301 case SECPKG_ATTR_REMOTE_CERT_CONTEXT:
1302 return schan_QueryContextAttributesW(context_handle, attribute, buffer);
1303 case SECPKG_ATTR_CONNECTION_INFO:
1304 return schan_QueryContextAttributesW(context_handle, attribute, buffer);
1306 default:
1307 FIXME("Unhandled attribute %#x\n", attribute);
1308 return SEC_E_UNSUPPORTED_FUNCTION;
1312 static int schan_encrypt_message_get_next_buffer(const struct schan_transport *t, struct schan_buffers *s)
1314 SecBuffer *b;
1316 if (s->current_buffer_idx == -1)
1317 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_STREAM_HEADER);
1319 b = &s->desc->pBuffers[s->current_buffer_idx];
1321 if (b->BufferType == SECBUFFER_STREAM_HEADER)
1322 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_DATA);
1324 if (b->BufferType == SECBUFFER_DATA)
1325 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_STREAM_TRAILER);
1327 return -1;
1330 static int schan_encrypt_message_get_next_buffer_token(const struct schan_transport *t, struct schan_buffers *s)
1332 SecBuffer *b;
1334 if (s->current_buffer_idx == -1)
1335 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
1337 b = &s->desc->pBuffers[s->current_buffer_idx];
1339 if (b->BufferType == SECBUFFER_TOKEN)
1341 int idx = schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
1342 if (idx != s->current_buffer_idx) return -1;
1343 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_DATA);
1346 if (b->BufferType == SECBUFFER_DATA)
1348 int idx = schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
1349 if (idx != -1)
1350 idx = schan_find_sec_buffer_idx(s->desc, idx + 1, SECBUFFER_TOKEN);
1351 return idx;
1354 return -1;
1357 static SECURITY_STATUS SEC_ENTRY schan_EncryptMessage(PCtxtHandle context_handle,
1358 ULONG quality, PSecBufferDesc message, ULONG message_seq_no)
1360 struct schan_transport transport;
1361 struct schan_context *ctx;
1362 struct schan_buffers *b;
1363 SecBuffer *buffer;
1364 SIZE_T data_size;
1365 char *data;
1366 ssize_t sent = 0;
1367 int idx;
1369 TRACE("context_handle %p, quality %d, message %p, message_seq_no %d\n",
1370 context_handle, quality, message, message_seq_no);
1372 if (!context_handle) return SEC_E_INVALID_HANDLE;
1373 ctx = schan_get_object(context_handle->dwLower, SCHAN_HANDLE_CTX);
1375 dump_buffer_desc(message);
1377 idx = schan_find_sec_buffer_idx(message, 0, SECBUFFER_DATA);
1378 if (idx == -1)
1380 WARN("No data buffer passed\n");
1381 return SEC_E_INTERNAL_ERROR;
1383 buffer = &message->pBuffers[idx];
1385 data_size = buffer->cbBuffer;
1386 data = HeapAlloc(GetProcessHeap(), 0, data_size);
1387 memcpy(data, buffer->pvBuffer, data_size);
1389 transport.ctx = ctx;
1390 init_schan_buffers(&transport.in, NULL, NULL);
1391 if (schan_find_sec_buffer_idx(message, 0, SECBUFFER_STREAM_HEADER) != -1)
1392 init_schan_buffers(&transport.out, message, schan_encrypt_message_get_next_buffer);
1393 else
1394 init_schan_buffers(&transport.out, message, schan_encrypt_message_get_next_buffer_token);
1395 schan_imp_set_session_transport(ctx->session, &transport);
1397 while (sent < data_size)
1399 size_t length = data_size - sent;
1400 SECURITY_STATUS status = schan_imp_send(ctx->session, data + sent, &length);
1401 if (status == SEC_I_CONTINUE_NEEDED)
1402 break;
1403 else if (status != SEC_E_OK)
1405 HeapFree(GetProcessHeap(), 0, data);
1406 ERR("Returning %d\n", status);
1407 return status;
1410 sent += length;
1413 TRACE("Sent %zd bytes\n", sent);
1415 b = &transport.out;
1416 b->desc->pBuffers[b->current_buffer_idx].cbBuffer = b->offset;
1417 HeapFree(GetProcessHeap(), 0, data);
1419 return SEC_E_OK;
1422 static int schan_decrypt_message_get_next_buffer(const struct schan_transport *t, struct schan_buffers *s)
1424 if (s->current_buffer_idx == -1)
1425 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_DATA);
1427 return -1;
1430 static int schan_validate_decrypt_buffer_desc(PSecBufferDesc message)
1432 int data_idx = -1;
1433 unsigned int empty_count = 0;
1434 unsigned int i;
1436 if (message->cBuffers < 4)
1438 WARN("Less than four buffers passed\n");
1439 return -1;
1442 for (i = 0; i < message->cBuffers; ++i)
1444 SecBuffer *b = &message->pBuffers[i];
1445 if (b->BufferType == SECBUFFER_DATA)
1447 if (data_idx != -1)
1449 WARN("More than one data buffer passed\n");
1450 return -1;
1452 data_idx = i;
1454 else if (b->BufferType == SECBUFFER_EMPTY)
1455 ++empty_count;
1458 if (data_idx == -1)
1460 WARN("No data buffer passed\n");
1461 return -1;
1464 if (empty_count < 3)
1466 WARN("Less than three empty buffers passed\n");
1467 return -1;
1470 return data_idx;
1473 static void schan_decrypt_fill_buffer(PSecBufferDesc message, ULONG buffer_type, void *data, ULONG size)
1475 int idx;
1476 SecBuffer *buffer;
1478 idx = schan_find_sec_buffer_idx(message, 0, SECBUFFER_EMPTY);
1479 buffer = &message->pBuffers[idx];
1481 buffer->BufferType = buffer_type;
1482 buffer->pvBuffer = data;
1483 buffer->cbBuffer = size;
1486 static SECURITY_STATUS SEC_ENTRY schan_DecryptMessage(PCtxtHandle context_handle,
1487 PSecBufferDesc message, ULONG message_seq_no, PULONG quality)
1489 struct schan_transport transport;
1490 struct schan_context *ctx;
1491 SecBuffer *buffer;
1492 SIZE_T data_size;
1493 char *data;
1494 unsigned expected_size;
1495 ssize_t received = 0;
1496 int idx;
1497 unsigned char *buf_ptr;
1499 TRACE("context_handle %p, message %p, message_seq_no %d, quality %p\n",
1500 context_handle, message, message_seq_no, quality);
1502 if (!context_handle) return SEC_E_INVALID_HANDLE;
1503 ctx = schan_get_object(context_handle->dwLower, SCHAN_HANDLE_CTX);
1505 dump_buffer_desc(message);
1507 idx = schan_validate_decrypt_buffer_desc(message);
1508 if (idx == -1)
1509 return SEC_E_INVALID_TOKEN;
1510 buffer = &message->pBuffers[idx];
1511 buf_ptr = buffer->pvBuffer;
1513 expected_size = 5 + ((buf_ptr[3] << 8) | buf_ptr[4]);
1514 if(buffer->cbBuffer < expected_size)
1516 TRACE("Expected %u bytes, but buffer only contains %u bytes\n", expected_size, buffer->cbBuffer);
1517 buffer->BufferType = SECBUFFER_MISSING;
1518 buffer->cbBuffer = expected_size - buffer->cbBuffer;
1520 /* This is a bit weird, but windows does it too */
1521 idx = schan_find_sec_buffer_idx(message, 0, SECBUFFER_EMPTY);
1522 buffer = &message->pBuffers[idx];
1523 buffer->BufferType = SECBUFFER_MISSING;
1524 buffer->cbBuffer = expected_size - buffer->cbBuffer;
1526 TRACE("Returning SEC_E_INCOMPLETE_MESSAGE\n");
1527 return SEC_E_INCOMPLETE_MESSAGE;
1530 data_size = buffer->cbBuffer;
1531 data = HeapAlloc(GetProcessHeap(), 0, data_size);
1533 transport.ctx = ctx;
1534 init_schan_buffers(&transport.in, message, schan_decrypt_message_get_next_buffer);
1535 transport.in.limit = expected_size;
1536 init_schan_buffers(&transport.out, NULL, NULL);
1537 schan_imp_set_session_transport(ctx->session, &transport);
1539 while (received < data_size)
1541 size_t length = data_size - received;
1542 SECURITY_STATUS status = schan_imp_recv(ctx->session, data + received, &length);
1543 if (status == SEC_I_CONTINUE_NEEDED)
1545 if (!received)
1547 HeapFree(GetProcessHeap(), 0, data);
1548 TRACE("Returning SEC_E_INCOMPLETE_MESSAGE\n");
1549 return SEC_E_INCOMPLETE_MESSAGE;
1551 break;
1553 else if (status != SEC_E_OK)
1555 HeapFree(GetProcessHeap(), 0, data);
1556 ERR("Returning %d\n", status);
1557 return status;
1559 else if (!length)
1560 break;
1562 received += length;
1565 TRACE("Received %zd bytes\n", received);
1567 memcpy(buf_ptr + 5, data, received);
1568 HeapFree(GetProcessHeap(), 0, data);
1570 schan_decrypt_fill_buffer(message, SECBUFFER_DATA,
1571 buf_ptr + 5, received);
1573 schan_decrypt_fill_buffer(message, SECBUFFER_STREAM_TRAILER,
1574 buf_ptr + 5 + received, buffer->cbBuffer - 5 - received);
1576 if(buffer->cbBuffer > expected_size)
1577 schan_decrypt_fill_buffer(message, SECBUFFER_EXTRA,
1578 buf_ptr + expected_size, buffer->cbBuffer - expected_size);
1580 buffer->BufferType = SECBUFFER_STREAM_HEADER;
1581 buffer->cbBuffer = 5;
1583 return SEC_E_OK;
1586 static SECURITY_STATUS SEC_ENTRY schan_DeleteSecurityContext(PCtxtHandle context_handle)
1588 struct schan_context *ctx;
1590 TRACE("context_handle %p\n", context_handle);
1592 if (!context_handle) return SEC_E_INVALID_HANDLE;
1594 ctx = schan_free_handle(context_handle->dwLower, SCHAN_HANDLE_CTX);
1595 if (!ctx) return SEC_E_INVALID_HANDLE;
1597 schan_imp_dispose_session(ctx->session);
1598 HeapFree(GetProcessHeap(), 0, ctx);
1600 return SEC_E_OK;
1603 static const SecurityFunctionTableA schanTableA = {
1605 NULL, /* EnumerateSecurityPackagesA */
1606 schan_QueryCredentialsAttributesA,
1607 schan_AcquireCredentialsHandleA,
1608 schan_FreeCredentialsHandle,
1609 NULL, /* Reserved2 */
1610 schan_InitializeSecurityContextA,
1611 NULL, /* AcceptSecurityContext */
1612 NULL, /* CompleteAuthToken */
1613 schan_DeleteSecurityContext,
1614 NULL, /* ApplyControlToken */
1615 schan_QueryContextAttributesA,
1616 NULL, /* ImpersonateSecurityContext */
1617 NULL, /* RevertSecurityContext */
1618 NULL, /* MakeSignature */
1619 NULL, /* VerifySignature */
1620 FreeContextBuffer,
1621 NULL, /* QuerySecurityPackageInfoA */
1622 NULL, /* Reserved3 */
1623 NULL, /* Reserved4 */
1624 NULL, /* ExportSecurityContext */
1625 NULL, /* ImportSecurityContextA */
1626 NULL, /* AddCredentialsA */
1627 NULL, /* Reserved8 */
1628 NULL, /* QuerySecurityContextToken */
1629 schan_EncryptMessage,
1630 schan_DecryptMessage,
1631 NULL, /* SetContextAttributesA */
1634 static const SecurityFunctionTableW schanTableW = {
1636 NULL, /* EnumerateSecurityPackagesW */
1637 schan_QueryCredentialsAttributesW,
1638 schan_AcquireCredentialsHandleW,
1639 schan_FreeCredentialsHandle,
1640 NULL, /* Reserved2 */
1641 schan_InitializeSecurityContextW,
1642 NULL, /* AcceptSecurityContext */
1643 NULL, /* CompleteAuthToken */
1644 schan_DeleteSecurityContext,
1645 NULL, /* ApplyControlToken */
1646 schan_QueryContextAttributesW,
1647 NULL, /* ImpersonateSecurityContext */
1648 NULL, /* RevertSecurityContext */
1649 NULL, /* MakeSignature */
1650 NULL, /* VerifySignature */
1651 FreeContextBuffer,
1652 NULL, /* QuerySecurityPackageInfoW */
1653 NULL, /* Reserved3 */
1654 NULL, /* Reserved4 */
1655 NULL, /* ExportSecurityContext */
1656 NULL, /* ImportSecurityContextW */
1657 NULL, /* AddCredentialsW */
1658 NULL, /* Reserved8 */
1659 NULL, /* QuerySecurityContextToken */
1660 schan_EncryptMessage,
1661 schan_DecryptMessage,
1662 NULL, /* SetContextAttributesW */
1665 static const WCHAR schannelComment[] = { 'S','c','h','a','n','n','e','l',' ',
1666 'S','e','c','u','r','i','t','y',' ','P','a','c','k','a','g','e',0 };
1667 static const WCHAR schannelDllName[] = { 's','c','h','a','n','n','e','l','.','d','l','l',0 };
1669 void SECUR32_initSchannelSP(void)
1671 /* This is what Windows reports. This shouldn't break any applications
1672 * even though the functions are missing, because the wrapper will
1673 * return SEC_E_UNSUPPORTED_FUNCTION if our function is NULL.
1675 static const LONG caps =
1676 SECPKG_FLAG_INTEGRITY |
1677 SECPKG_FLAG_PRIVACY |
1678 SECPKG_FLAG_CONNECTION |
1679 SECPKG_FLAG_MULTI_REQUIRED |
1680 SECPKG_FLAG_EXTENDED_ERROR |
1681 SECPKG_FLAG_IMPERSONATION |
1682 SECPKG_FLAG_ACCEPT_WIN32_NAME |
1683 SECPKG_FLAG_STREAM;
1684 static const short version = 1;
1685 static const LONG maxToken = 16384;
1686 SEC_WCHAR *uniSPName = (SEC_WCHAR *)UNISP_NAME_W,
1687 *schannel = (SEC_WCHAR *)SCHANNEL_NAME_W;
1688 const SecPkgInfoW info[] = {
1689 { caps, version, UNISP_RPC_ID, maxToken, uniSPName, uniSPName },
1690 { caps, version, UNISP_RPC_ID, maxToken, schannel,
1691 (SEC_WCHAR *)schannelComment },
1693 SecureProvider *provider;
1695 if (!schan_imp_init())
1696 return;
1698 schan_handle_table = HeapAlloc(GetProcessHeap(), 0, 64 * sizeof(*schan_handle_table));
1699 if (!schan_handle_table)
1701 ERR("Failed to allocate schannel handle table.\n");
1702 goto fail;
1704 schan_handle_table_size = 64;
1706 provider = SECUR32_addProvider(&schanTableA, &schanTableW, schannelDllName);
1707 if (!provider)
1709 ERR("Failed to add schannel provider.\n");
1710 goto fail;
1713 SECUR32_addPackages(provider, sizeof(info) / sizeof(info[0]), NULL, info);
1715 return;
1717 fail:
1718 HeapFree(GetProcessHeap(), 0, schan_handle_table);
1719 schan_handle_table = NULL;
1720 schan_imp_deinit();
1721 return;
1724 void SECUR32_deinitSchannelSP(void)
1726 SIZE_T i = schan_handle_count;
1728 if (!schan_handle_table) return;
1730 /* deinitialized sessions first because a pointer to the credentials
1731 * may be stored for the session. */
1732 while (i--)
1734 if (schan_handle_table[i].type == SCHAN_HANDLE_CTX)
1736 struct schan_context *ctx = schan_free_handle(i, SCHAN_HANDLE_CTX);
1737 schan_imp_dispose_session(ctx->session);
1738 HeapFree(GetProcessHeap(), 0, ctx);
1741 i = schan_handle_count;
1742 while (i--)
1744 if (schan_handle_table[i].type != SCHAN_HANDLE_FREE)
1746 struct schan_credentials *cred;
1747 cred = schan_free_handle(i, SCHAN_HANDLE_CRED);
1748 schan_imp_free_certificate_credentials(cred->credentials);
1749 HeapFree(GetProcessHeap(), 0, cred);
1752 HeapFree(GetProcessHeap(), 0, schan_handle_table);
1753 schan_imp_deinit();
1756 #else /* SONAME_LIBGNUTLS */
1758 void SECUR32_initSchannelSP(void)
1760 ERR("TLS library not found, SSL connections will fail\n");
1763 void SECUR32_deinitSchannelSP(void) {}
1765 #endif /* SONAME_LIBGNUTLS */