secur32: Properly handle GNUTLS_E_AGAIN in (GnuTLS) schan_imp_send().
[wine/multimedia.git] / dlls / secur32 / schannel.c
blob0355982c872b947d8930c07dfa732c8662b98555
1 /* Copyright (C) 2005 Juan Lang
2 * Copyright 2008 Henri Verbeet
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
18 * This file implements the schannel provider, or, the SSL/TLS implementations.
20 #include "config.h"
21 #include "wine/port.h"
23 #include <stdarg.h>
24 #include <errno.h>
26 #include "windef.h"
27 #include "winbase.h"
28 #include "winnls.h"
29 #include "sspi.h"
30 #include "schannel.h"
31 #include "secur32_priv.h"
32 #include "wine/debug.h"
34 WINE_DEFAULT_DEBUG_CHANNEL(secur32);
36 #if defined(SONAME_LIBGNUTLS) || defined (HAVE_SECURITY_SECURITY_H)
38 #define SCHAN_INVALID_HANDLE ~0UL
40 enum schan_handle_type
42 SCHAN_HANDLE_CRED,
43 SCHAN_HANDLE_CTX,
44 SCHAN_HANDLE_FREE
47 struct schan_handle
49 void *object;
50 enum schan_handle_type type;
53 struct schan_credentials
55 ULONG credential_use;
56 schan_imp_certificate_credentials credentials;
59 struct schan_context
61 schan_imp_session session;
62 ULONG req_ctx_attr;
65 static struct schan_handle *schan_handle_table;
66 static struct schan_handle *schan_free_handles;
67 static SIZE_T schan_handle_table_size;
68 static SIZE_T schan_handle_count;
70 static ULONG_PTR schan_alloc_handle(void *object, enum schan_handle_type type)
72 struct schan_handle *handle;
74 if (schan_free_handles)
76 DWORD index = schan_free_handles - schan_handle_table;
77 /* Use a free handle */
78 handle = schan_free_handles;
79 if (handle->type != SCHAN_HANDLE_FREE)
81 ERR("Handle %d(%p) is in the free list, but has type %#x.\n", index, handle, handle->type);
82 return SCHAN_INVALID_HANDLE;
84 schan_free_handles = handle->object;
85 handle->object = object;
86 handle->type = type;
88 return index;
90 if (!(schan_handle_count < schan_handle_table_size))
92 /* Grow the table */
93 SIZE_T new_size = schan_handle_table_size + (schan_handle_table_size >> 1);
94 struct schan_handle *new_table = HeapReAlloc(GetProcessHeap(), 0, schan_handle_table, new_size * sizeof(*schan_handle_table));
95 if (!new_table)
97 ERR("Failed to grow the handle table\n");
98 return SCHAN_INVALID_HANDLE;
100 schan_handle_table = new_table;
101 schan_handle_table_size = new_size;
104 handle = &schan_handle_table[schan_handle_count++];
105 handle->object = object;
106 handle->type = type;
108 return handle - schan_handle_table;
111 static void *schan_free_handle(ULONG_PTR handle_idx, enum schan_handle_type type)
113 struct schan_handle *handle;
114 void *object;
116 if (handle_idx == SCHAN_INVALID_HANDLE) return NULL;
117 if (handle_idx >= schan_handle_count) return NULL;
118 handle = &schan_handle_table[handle_idx];
119 if (handle->type != type)
121 ERR("Handle %ld(%p) is not of type %#x\n", handle_idx, handle, type);
122 return NULL;
125 object = handle->object;
126 handle->object = schan_free_handles;
127 handle->type = SCHAN_HANDLE_FREE;
128 schan_free_handles = handle;
130 return object;
133 static void *schan_get_object(ULONG_PTR handle_idx, enum schan_handle_type type)
135 struct schan_handle *handle;
137 if (handle_idx == SCHAN_INVALID_HANDLE) return NULL;
138 if (handle_idx >= schan_handle_count) return NULL;
139 handle = &schan_handle_table[handle_idx];
140 if (handle->type != type)
142 ERR("Handle %ld(%p) is not of type %#x\n", handle_idx, handle, type);
143 return NULL;
146 return handle->object;
149 static SECURITY_STATUS schan_QueryCredentialsAttributes(
150 PCredHandle phCredential, ULONG ulAttribute, VOID *pBuffer)
152 SECURITY_STATUS ret;
154 switch (ulAttribute)
156 case SECPKG_ATTR_SUPPORTED_ALGS:
157 if (pBuffer)
159 /* FIXME: get from CryptoAPI */
160 FIXME("SECPKG_ATTR_SUPPORTED_ALGS: stub\n");
161 ret = SEC_E_UNSUPPORTED_FUNCTION;
163 else
164 ret = SEC_E_INTERNAL_ERROR;
165 break;
166 case SECPKG_ATTR_CIPHER_STRENGTHS:
167 if (pBuffer)
169 SecPkgCred_CipherStrengths *r = pBuffer;
171 /* FIXME: get from CryptoAPI */
172 FIXME("SECPKG_ATTR_CIPHER_STRENGTHS: semi-stub\n");
173 r->dwMinimumCipherStrength = 40;
174 r->dwMaximumCipherStrength = 168;
175 ret = SEC_E_OK;
177 else
178 ret = SEC_E_INTERNAL_ERROR;
179 break;
180 case SECPKG_ATTR_SUPPORTED_PROTOCOLS:
181 if (pBuffer)
183 /* FIXME: get from OpenSSL? */
184 FIXME("SECPKG_ATTR_SUPPORTED_PROTOCOLS: stub\n");
185 ret = SEC_E_UNSUPPORTED_FUNCTION;
187 else
188 ret = SEC_E_INTERNAL_ERROR;
189 break;
190 default:
191 ret = SEC_E_UNSUPPORTED_FUNCTION;
193 return ret;
196 static SECURITY_STATUS SEC_ENTRY schan_QueryCredentialsAttributesA(
197 PCredHandle phCredential, ULONG ulAttribute, PVOID pBuffer)
199 SECURITY_STATUS ret;
201 TRACE("(%p, %d, %p)\n", phCredential, ulAttribute, pBuffer);
203 switch (ulAttribute)
205 case SECPKG_CRED_ATTR_NAMES:
206 FIXME("SECPKG_CRED_ATTR_NAMES: stub\n");
207 ret = SEC_E_UNSUPPORTED_FUNCTION;
208 break;
209 default:
210 ret = schan_QueryCredentialsAttributes(phCredential, ulAttribute,
211 pBuffer);
213 return ret;
216 static SECURITY_STATUS SEC_ENTRY schan_QueryCredentialsAttributesW(
217 PCredHandle phCredential, ULONG ulAttribute, PVOID pBuffer)
219 SECURITY_STATUS ret;
221 TRACE("(%p, %d, %p)\n", phCredential, ulAttribute, pBuffer);
223 switch (ulAttribute)
225 case SECPKG_CRED_ATTR_NAMES:
226 FIXME("SECPKG_CRED_ATTR_NAMES: stub\n");
227 ret = SEC_E_UNSUPPORTED_FUNCTION;
228 break;
229 default:
230 ret = schan_QueryCredentialsAttributes(phCredential, ulAttribute,
231 pBuffer);
233 return ret;
236 static SECURITY_STATUS schan_CheckCreds(const SCHANNEL_CRED *schanCred)
238 SECURITY_STATUS st;
239 DWORD i;
241 TRACE("dwVersion = %d\n", schanCred->dwVersion);
242 TRACE("cCreds = %d\n", schanCred->cCreds);
243 TRACE("hRootStore = %p\n", schanCred->hRootStore);
244 TRACE("cMappers = %d\n", schanCred->cMappers);
245 TRACE("cSupportedAlgs = %d:\n", schanCred->cSupportedAlgs);
246 for (i = 0; i < schanCred->cSupportedAlgs; i++)
247 TRACE("%08x\n", schanCred->palgSupportedAlgs[i]);
248 TRACE("grbitEnabledProtocols = %08x\n", schanCred->grbitEnabledProtocols);
249 TRACE("dwMinimumCipherStrength = %d\n", schanCred->dwMinimumCipherStrength);
250 TRACE("dwMaximumCipherStrength = %d\n", schanCred->dwMaximumCipherStrength);
251 TRACE("dwSessionLifespan = %d\n", schanCred->dwSessionLifespan);
252 TRACE("dwFlags = %08x\n", schanCred->dwFlags);
253 TRACE("dwCredFormat = %d\n", schanCred->dwCredFormat);
255 switch (schanCred->dwVersion)
257 case SCH_CRED_V3:
258 case SCHANNEL_CRED_VERSION:
259 break;
260 default:
261 return SEC_E_INTERNAL_ERROR;
264 if (schanCred->cCreds == 0)
265 st = SEC_E_NO_CREDENTIALS;
266 else if (schanCred->cCreds > 1)
267 st = SEC_E_UNKNOWN_CREDENTIALS;
268 else
270 DWORD keySpec;
271 HCRYPTPROV csp;
272 BOOL ret, freeCSP;
274 ret = CryptAcquireCertificatePrivateKey(schanCred->paCred[0],
275 0, /* FIXME: what flags to use? */ NULL,
276 &csp, &keySpec, &freeCSP);
277 if (ret)
279 st = SEC_E_OK;
280 if (freeCSP)
281 CryptReleaseContext(csp, 0);
283 else
284 st = SEC_E_UNKNOWN_CREDENTIALS;
286 return st;
289 static SECURITY_STATUS schan_AcquireClientCredentials(const SCHANNEL_CRED *schanCred,
290 PCredHandle phCredential, PTimeStamp ptsExpiry)
292 struct schan_credentials *creds;
293 SECURITY_STATUS st = SEC_E_OK;
295 TRACE("schanCred %p, phCredential %p, ptsExpiry %p\n", schanCred, phCredential, ptsExpiry);
297 if (schanCred)
299 st = schan_CheckCreds(schanCred);
300 if (st == SEC_E_NO_CREDENTIALS)
301 st = SEC_E_OK;
304 /* For now, the only thing I'm interested in is the direction of the
305 * connection, so just store it.
307 if (st == SEC_E_OK)
309 ULONG_PTR handle;
311 creds = HeapAlloc(GetProcessHeap(), 0, sizeof(*creds));
312 if (!creds) return SEC_E_INSUFFICIENT_MEMORY;
314 handle = schan_alloc_handle(creds, SCHAN_HANDLE_CRED);
315 if (handle == SCHAN_INVALID_HANDLE) goto fail;
317 creds->credential_use = SECPKG_CRED_OUTBOUND;
318 if (!schan_imp_allocate_certificate_credentials(&creds->credentials))
320 schan_free_handle(handle, SCHAN_HANDLE_CRED);
321 goto fail;
324 phCredential->dwLower = handle;
325 phCredential->dwUpper = 0;
327 /* Outbound credentials have no expiry */
328 if (ptsExpiry)
330 ptsExpiry->LowPart = 0;
331 ptsExpiry->HighPart = 0;
334 return st;
336 fail:
337 HeapFree(GetProcessHeap(), 0, creds);
338 return SEC_E_INTERNAL_ERROR;
341 static SECURITY_STATUS schan_AcquireServerCredentials(const SCHANNEL_CRED *schanCred,
342 PCredHandle phCredential, PTimeStamp ptsExpiry)
344 SECURITY_STATUS st;
346 TRACE("schanCred %p, phCredential %p, ptsExpiry %p\n", schanCred, phCredential, ptsExpiry);
348 if (!schanCred) return SEC_E_NO_CREDENTIALS;
350 st = schan_CheckCreds(schanCred);
351 if (st == SEC_E_OK)
353 ULONG_PTR handle;
354 struct schan_credentials *creds;
356 creds = HeapAlloc(GetProcessHeap(), 0, sizeof(*creds));
357 if (!creds) return SEC_E_INSUFFICIENT_MEMORY;
358 creds->credential_use = SECPKG_CRED_INBOUND;
360 handle = schan_alloc_handle(creds, SCHAN_HANDLE_CRED);
361 if (handle == SCHAN_INVALID_HANDLE)
363 HeapFree(GetProcessHeap(), 0, creds);
364 return SEC_E_INTERNAL_ERROR;
367 phCredential->dwLower = handle;
368 phCredential->dwUpper = 0;
370 /* FIXME: get expiry from cert */
372 return st;
375 static SECURITY_STATUS schan_AcquireCredentialsHandle(ULONG fCredentialUse,
376 const SCHANNEL_CRED *schanCred, PCredHandle phCredential, PTimeStamp ptsExpiry)
378 SECURITY_STATUS ret;
380 if (fCredentialUse == SECPKG_CRED_OUTBOUND)
381 ret = schan_AcquireClientCredentials(schanCred, phCredential,
382 ptsExpiry);
383 else
384 ret = schan_AcquireServerCredentials(schanCred, phCredential,
385 ptsExpiry);
386 return ret;
389 static SECURITY_STATUS SEC_ENTRY schan_AcquireCredentialsHandleA(
390 SEC_CHAR *pszPrincipal, SEC_CHAR *pszPackage, ULONG fCredentialUse,
391 PLUID pLogonID, PVOID pAuthData, SEC_GET_KEY_FN pGetKeyFn,
392 PVOID pGetKeyArgument, PCredHandle phCredential, PTimeStamp ptsExpiry)
394 TRACE("(%s, %s, 0x%08x, %p, %p, %p, %p, %p, %p)\n",
395 debugstr_a(pszPrincipal), debugstr_a(pszPackage), fCredentialUse,
396 pLogonID, pAuthData, pGetKeyFn, pGetKeyArgument, phCredential, ptsExpiry);
397 return schan_AcquireCredentialsHandle(fCredentialUse,
398 pAuthData, phCredential, ptsExpiry);
401 static SECURITY_STATUS SEC_ENTRY schan_AcquireCredentialsHandleW(
402 SEC_WCHAR *pszPrincipal, SEC_WCHAR *pszPackage, ULONG fCredentialUse,
403 PLUID pLogonID, PVOID pAuthData, SEC_GET_KEY_FN pGetKeyFn,
404 PVOID pGetKeyArgument, PCredHandle phCredential, PTimeStamp ptsExpiry)
406 TRACE("(%s, %s, 0x%08x, %p, %p, %p, %p, %p, %p)\n",
407 debugstr_w(pszPrincipal), debugstr_w(pszPackage), fCredentialUse,
408 pLogonID, pAuthData, pGetKeyFn, pGetKeyArgument, phCredential, ptsExpiry);
409 return schan_AcquireCredentialsHandle(fCredentialUse,
410 pAuthData, phCredential, ptsExpiry);
413 static SECURITY_STATUS SEC_ENTRY schan_FreeCredentialsHandle(
414 PCredHandle phCredential)
416 struct schan_credentials *creds;
418 TRACE("phCredential %p\n", phCredential);
420 if (!phCredential) return SEC_E_INVALID_HANDLE;
422 creds = schan_free_handle(phCredential->dwLower, SCHAN_HANDLE_CRED);
423 if (!creds) return SEC_E_INVALID_HANDLE;
425 if (creds->credential_use == SECPKG_CRED_OUTBOUND)
426 schan_imp_free_certificate_credentials(creds->credentials);
427 HeapFree(GetProcessHeap(), 0, creds);
429 return SEC_E_OK;
432 static void init_schan_buffers(struct schan_buffers *s, const PSecBufferDesc desc,
433 int (*get_next_buffer)(const struct schan_transport *, struct schan_buffers *))
435 s->offset = 0;
436 s->limit = 0;
437 s->desc = desc;
438 s->current_buffer_idx = -1;
439 s->allow_buffer_resize = FALSE;
440 s->get_next_buffer = get_next_buffer;
443 static int schan_find_sec_buffer_idx(const SecBufferDesc *desc, unsigned int start_idx, ULONG buffer_type)
445 unsigned int i;
446 PSecBuffer buffer;
448 for (i = start_idx; i < desc->cBuffers; ++i)
450 buffer = &desc->pBuffers[i];
451 if (buffer->BufferType == buffer_type) return i;
454 return -1;
457 static void schan_resize_current_buffer(const struct schan_buffers *s, SIZE_T min_size)
459 SecBuffer *b = &s->desc->pBuffers[s->current_buffer_idx];
460 SIZE_T new_size = b->cbBuffer ? b->cbBuffer * 2 : 128;
461 void *new_data;
463 if (b->cbBuffer >= min_size || !s->allow_buffer_resize || min_size > UINT_MAX / 2) return;
465 while (new_size < min_size) new_size *= 2;
467 if (b->pvBuffer)
468 new_data = HeapReAlloc(GetProcessHeap(), 0, b->pvBuffer, new_size);
469 else
470 new_data = HeapAlloc(GetProcessHeap(), 0, new_size);
472 if (!new_data)
474 TRACE("Failed to resize %p from %d to %ld\n", b->pvBuffer, b->cbBuffer, new_size);
475 return;
478 b->cbBuffer = new_size;
479 b->pvBuffer = new_data;
482 char *schan_get_buffer(const struct schan_transport *t, struct schan_buffers *s, SIZE_T *count)
484 SIZE_T max_count;
485 PSecBuffer buffer;
487 if (!s->desc)
489 TRACE("No desc\n");
490 return NULL;
493 if (s->current_buffer_idx == -1)
495 /* Initial buffer */
496 int buffer_idx = s->get_next_buffer(t, s);
497 if (buffer_idx == -1)
499 TRACE("No next buffer\n");
500 return NULL;
502 s->current_buffer_idx = buffer_idx;
505 buffer = &s->desc->pBuffers[s->current_buffer_idx];
506 TRACE("Using buffer %d: cbBuffer %d, BufferType %#x, pvBuffer %p\n", s->current_buffer_idx, buffer->cbBuffer, buffer->BufferType, buffer->pvBuffer);
508 schan_resize_current_buffer(s, s->offset + *count);
509 max_count = buffer->cbBuffer - s->offset;
510 if (!max_count)
512 int buffer_idx;
514 s->allow_buffer_resize = FALSE;
515 buffer_idx = s->get_next_buffer(t, s);
516 if (buffer_idx == -1)
518 TRACE("No next buffer\n");
519 return NULL;
521 s->current_buffer_idx = buffer_idx;
522 s->offset = 0;
523 return schan_get_buffer(t, s, count);
526 if (*count > max_count) *count = max_count;
527 return (char *)buffer->pvBuffer + s->offset;
530 /* schan_pull
531 * Read data from the transport input buffer.
533 * t - The session transport object.
534 * buff - The buffer into which to store the read data. Must be at least
535 * *buff_len bytes in length.
536 * buff_len - On input, *buff_len is the desired length to read. On successful
537 * return, *buff_len is the number of bytes actually read.
539 * Returns:
540 * 0 on success, in which case:
541 * *buff_len == 0 indicates end of file.
542 * *buff_len > 0 indicates that some data was read. May be less than
543 * what was requested, in which case the caller should call again if/
544 * when they want more.
545 * EAGAIN when no data could be read without blocking
546 * another errno-style error value on failure
549 int schan_pull(struct schan_transport *t, void *buff, size_t *buff_len)
551 char *b;
552 SIZE_T local_len = *buff_len;
554 TRACE("Pull %lu bytes\n", local_len);
556 *buff_len = 0;
558 b = schan_get_buffer(t, &t->in, &local_len);
559 if (!b)
560 return EAGAIN;
562 if (t->in.limit != 0 && t->in.offset + local_len >= t->in.limit)
564 local_len = t->in.limit - t->in.offset;
565 if (local_len == 0)
566 return EAGAIN;
569 memcpy(buff, b, local_len);
570 t->in.offset += local_len;
572 TRACE("Read %lu bytes\n", local_len);
574 *buff_len = local_len;
575 return 0;
578 /* schan_push
579 * Write data to the transport output buffer.
581 * t - The session transport object.
582 * buff - The buffer of data to write. Must be at least *buff_len bytes in length.
583 * buff_len - On input, *buff_len is the desired length to write. On successful
584 * return, *buff_len is the number of bytes actually written.
586 * Returns:
587 * 0 on success
588 * *buff_len will be > 0 indicating how much data was written. May be less
589 * than what was requested, in which case the caller should call again
590 if/when they want to write more.
591 * EAGAIN when no data could be written without blocking
592 * another errno-style error value on failure
595 int schan_push(struct schan_transport *t, const void *buff, size_t *buff_len)
597 char *b;
598 SIZE_T local_len = *buff_len;
600 TRACE("Push %lu bytes\n", local_len);
602 *buff_len = 0;
604 b = schan_get_buffer(t, &t->out, &local_len);
605 if (!b)
606 return EAGAIN;
608 memcpy(b, buff, local_len);
609 t->out.offset += local_len;
611 TRACE("Wrote %lu bytes\n", local_len);
613 *buff_len = local_len;
614 return 0;
617 schan_imp_session schan_session_for_transport(struct schan_transport* t)
619 return t->ctx->session;
622 static int schan_init_sec_ctx_get_next_buffer(const struct schan_transport *t, struct schan_buffers *s)
624 if (s->current_buffer_idx == -1)
626 int idx = schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
627 if (t->ctx->req_ctx_attr & ISC_REQ_ALLOCATE_MEMORY)
629 if (idx == -1)
631 idx = schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_EMPTY);
632 if (idx != -1) s->desc->pBuffers[idx].BufferType = SECBUFFER_TOKEN;
634 if (idx != -1 && !s->desc->pBuffers[idx].pvBuffer)
636 s->desc->pBuffers[idx].cbBuffer = 0;
637 s->allow_buffer_resize = TRUE;
640 return idx;
643 return -1;
646 static void dump_buffer_desc(SecBufferDesc *desc)
648 unsigned int i;
650 if (!desc) return;
651 TRACE("Buffer desc %p:\n", desc);
652 for (i = 0; i < desc->cBuffers; ++i)
654 SecBuffer *b = &desc->pBuffers[i];
655 TRACE("\tbuffer %u: cbBuffer %d, BufferType %#x pvBuffer %p\n", i, b->cbBuffer, b->BufferType, b->pvBuffer);
659 /***********************************************************************
660 * InitializeSecurityContextW
662 static SECURITY_STATUS SEC_ENTRY schan_InitializeSecurityContextW(
663 PCredHandle phCredential, PCtxtHandle phContext, SEC_WCHAR *pszTargetName,
664 ULONG fContextReq, ULONG Reserved1, ULONG TargetDataRep,
665 PSecBufferDesc pInput, ULONG Reserved2, PCtxtHandle phNewContext,
666 PSecBufferDesc pOutput, ULONG *pfContextAttr, PTimeStamp ptsExpiry)
668 struct schan_context *ctx;
669 struct schan_buffers *out_buffers;
670 struct schan_credentials *cred;
671 struct schan_transport transport;
672 SECURITY_STATUS ret;
674 TRACE("%p %p %s 0x%08x %d %d %p %d %p %p %p %p\n", phCredential, phContext,
675 debugstr_w(pszTargetName), fContextReq, Reserved1, TargetDataRep, pInput,
676 Reserved1, phNewContext, pOutput, pfContextAttr, ptsExpiry);
678 dump_buffer_desc(pInput);
679 dump_buffer_desc(pOutput);
681 if (!phContext)
683 ULONG_PTR handle;
685 if (!phCredential) return SEC_E_INVALID_HANDLE;
687 cred = schan_get_object(phCredential->dwLower, SCHAN_HANDLE_CRED);
688 if (!cred) return SEC_E_INVALID_HANDLE;
690 if (!(cred->credential_use & SECPKG_CRED_OUTBOUND))
692 WARN("Invalid credential use %#x\n", cred->credential_use);
693 return SEC_E_INVALID_HANDLE;
696 ctx = HeapAlloc(GetProcessHeap(), 0, sizeof(*ctx));
697 if (!ctx) return SEC_E_INSUFFICIENT_MEMORY;
699 handle = schan_alloc_handle(ctx, SCHAN_HANDLE_CTX);
700 if (handle == SCHAN_INVALID_HANDLE)
702 HeapFree(GetProcessHeap(), 0, ctx);
703 return SEC_E_INTERNAL_ERROR;
706 if (!schan_imp_create_session(&ctx->session, FALSE, cred->credentials))
708 schan_free_handle(handle, SCHAN_HANDLE_CTX);
709 HeapFree(GetProcessHeap(), 0, ctx);
710 return SEC_E_INTERNAL_ERROR;
713 phNewContext->dwLower = handle;
714 phNewContext->dwUpper = 0;
716 else
718 ctx = schan_get_object(phContext->dwLower, SCHAN_HANDLE_CTX);
721 ctx->req_ctx_attr = fContextReq;
723 transport.ctx = ctx;
724 init_schan_buffers(&transport.in, pInput, schan_init_sec_ctx_get_next_buffer);
725 init_schan_buffers(&transport.out, pOutput, schan_init_sec_ctx_get_next_buffer);
726 schan_imp_set_session_transport(ctx->session, &transport);
728 /* Perform the TLS handshake */
729 ret = schan_imp_handshake(ctx->session);
731 if(transport.in.offset && transport.in.offset != pInput->pBuffers[0].cbBuffer) {
732 if(pInput->cBuffers<2 || pInput->pBuffers[1].BufferType!=SECBUFFER_EMPTY)
733 return SEC_E_INVALID_TOKEN;
735 pInput->pBuffers[1].BufferType = SECBUFFER_EXTRA;
736 pInput->pBuffers[1].cbBuffer = pInput->pBuffers[0].cbBuffer-transport.in.offset;
739 out_buffers = &transport.out;
740 if (out_buffers->current_buffer_idx != -1)
742 SecBuffer *buffer = &out_buffers->desc->pBuffers[out_buffers->current_buffer_idx];
743 buffer->cbBuffer = out_buffers->offset;
746 *pfContextAttr = 0;
747 if (ctx->req_ctx_attr & ISC_REQ_ALLOCATE_MEMORY)
748 *pfContextAttr |= ISC_RET_ALLOCATED_MEMORY;
750 return ret;
753 /***********************************************************************
754 * InitializeSecurityContextA
756 static SECURITY_STATUS SEC_ENTRY schan_InitializeSecurityContextA(
757 PCredHandle phCredential, PCtxtHandle phContext, SEC_CHAR *pszTargetName,
758 ULONG fContextReq, ULONG Reserved1, ULONG TargetDataRep,
759 PSecBufferDesc pInput, ULONG Reserved2, PCtxtHandle phNewContext,
760 PSecBufferDesc pOutput, ULONG *pfContextAttr, PTimeStamp ptsExpiry)
762 SECURITY_STATUS ret;
763 SEC_WCHAR *target_name = NULL;
765 TRACE("%p %p %s %d %d %d %p %d %p %p %p %p\n", phCredential, phContext,
766 debugstr_a(pszTargetName), fContextReq, Reserved1, TargetDataRep, pInput,
767 Reserved1, phNewContext, pOutput, pfContextAttr, ptsExpiry);
769 if (pszTargetName)
771 INT len = MultiByteToWideChar(CP_ACP, 0, pszTargetName, -1, NULL, 0);
772 target_name = HeapAlloc(GetProcessHeap(), 0, len * sizeof(*target_name));
773 MultiByteToWideChar(CP_ACP, 0, pszTargetName, -1, target_name, len);
776 ret = schan_InitializeSecurityContextW(phCredential, phContext, target_name,
777 fContextReq, Reserved1, TargetDataRep, pInput, Reserved2,
778 phNewContext, pOutput, pfContextAttr, ptsExpiry);
780 HeapFree(GetProcessHeap(), 0, target_name);
782 return ret;
785 static SECURITY_STATUS SEC_ENTRY schan_QueryContextAttributesW(
786 PCtxtHandle context_handle, ULONG attribute, PVOID buffer)
788 struct schan_context *ctx;
790 TRACE("context_handle %p, attribute %#x, buffer %p\n",
791 context_handle, attribute, buffer);
793 if (!context_handle) return SEC_E_INVALID_HANDLE;
794 ctx = schan_get_object(context_handle->dwLower, SCHAN_HANDLE_CTX);
796 switch(attribute)
798 case SECPKG_ATTR_STREAM_SIZES:
800 SecPkgContext_ConnectionInfo info;
801 SECURITY_STATUS status = schan_imp_get_connection_info(ctx->session, &info);
802 if (status == SEC_E_OK)
804 SecPkgContext_StreamSizes *stream_sizes = buffer;
805 SIZE_T mac_size = info.dwHashStrength;
806 unsigned int block_size = schan_imp_get_session_cipher_block_size(ctx->session);
807 unsigned int message_size = schan_imp_get_max_message_size(ctx->session);
809 TRACE("Using %lu mac bytes, message size %u, block size %u\n",
810 mac_size, message_size, block_size);
812 /* These are defined by the TLS RFC */
813 stream_sizes->cbHeader = 5;
814 stream_sizes->cbTrailer = mac_size + 256; /* Max 255 bytes padding + 1 for padding size */
815 stream_sizes->cbMaximumMessage = message_size;
816 stream_sizes->cbBuffers = 4;
817 stream_sizes->cbBlockSize = block_size;
820 return status;
822 case SECPKG_ATTR_REMOTE_CERT_CONTEXT:
824 PCCERT_CONTEXT *cert = buffer;
825 return schan_imp_get_session_peer_certificate(ctx->session, cert);
827 case SECPKG_ATTR_CONNECTION_INFO:
829 SecPkgContext_ConnectionInfo *info = buffer;
830 return schan_imp_get_connection_info(ctx->session, info);
833 default:
834 FIXME("Unhandled attribute %#x\n", attribute);
835 return SEC_E_UNSUPPORTED_FUNCTION;
839 static SECURITY_STATUS SEC_ENTRY schan_QueryContextAttributesA(
840 PCtxtHandle context_handle, ULONG attribute, PVOID buffer)
842 TRACE("context_handle %p, attribute %#x, buffer %p\n",
843 context_handle, attribute, buffer);
845 switch(attribute)
847 case SECPKG_ATTR_STREAM_SIZES:
848 return schan_QueryContextAttributesW(context_handle, attribute, buffer);
849 case SECPKG_ATTR_REMOTE_CERT_CONTEXT:
850 return schan_QueryContextAttributesW(context_handle, attribute, buffer);
851 case SECPKG_ATTR_CONNECTION_INFO:
852 return schan_QueryContextAttributesW(context_handle, attribute, buffer);
854 default:
855 FIXME("Unhandled attribute %#x\n", attribute);
856 return SEC_E_UNSUPPORTED_FUNCTION;
860 static int schan_encrypt_message_get_next_buffer(const struct schan_transport *t, struct schan_buffers *s)
862 SecBuffer *b;
864 if (s->current_buffer_idx == -1)
865 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_STREAM_HEADER);
867 b = &s->desc->pBuffers[s->current_buffer_idx];
869 if (b->BufferType == SECBUFFER_STREAM_HEADER)
870 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_DATA);
872 if (b->BufferType == SECBUFFER_DATA)
873 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_STREAM_TRAILER);
875 return -1;
878 static int schan_encrypt_message_get_next_buffer_token(const struct schan_transport *t, struct schan_buffers *s)
880 SecBuffer *b;
882 if (s->current_buffer_idx == -1)
883 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
885 b = &s->desc->pBuffers[s->current_buffer_idx];
887 if (b->BufferType == SECBUFFER_TOKEN)
889 int idx = schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
890 if (idx != s->current_buffer_idx) return -1;
891 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_DATA);
894 if (b->BufferType == SECBUFFER_DATA)
896 int idx = schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_TOKEN);
897 if (idx != -1)
898 idx = schan_find_sec_buffer_idx(s->desc, idx + 1, SECBUFFER_TOKEN);
899 return idx;
902 return -1;
905 static SECURITY_STATUS SEC_ENTRY schan_EncryptMessage(PCtxtHandle context_handle,
906 ULONG quality, PSecBufferDesc message, ULONG message_seq_no)
908 struct schan_transport transport;
909 struct schan_context *ctx;
910 struct schan_buffers *b;
911 SECURITY_STATUS status;
912 SecBuffer *buffer;
913 SIZE_T data_size;
914 SIZE_T length;
915 char *data;
916 int idx;
918 TRACE("context_handle %p, quality %d, message %p, message_seq_no %d\n",
919 context_handle, quality, message, message_seq_no);
921 if (!context_handle) return SEC_E_INVALID_HANDLE;
922 ctx = schan_get_object(context_handle->dwLower, SCHAN_HANDLE_CTX);
924 dump_buffer_desc(message);
926 idx = schan_find_sec_buffer_idx(message, 0, SECBUFFER_DATA);
927 if (idx == -1)
929 WARN("No data buffer passed\n");
930 return SEC_E_INTERNAL_ERROR;
932 buffer = &message->pBuffers[idx];
934 data_size = buffer->cbBuffer;
935 data = HeapAlloc(GetProcessHeap(), 0, data_size);
936 memcpy(data, buffer->pvBuffer, data_size);
938 transport.ctx = ctx;
939 init_schan_buffers(&transport.in, NULL, NULL);
940 if (schan_find_sec_buffer_idx(message, 0, SECBUFFER_STREAM_HEADER) != -1)
941 init_schan_buffers(&transport.out, message, schan_encrypt_message_get_next_buffer);
942 else
943 init_schan_buffers(&transport.out, message, schan_encrypt_message_get_next_buffer_token);
944 schan_imp_set_session_transport(ctx->session, &transport);
946 length = data_size;
947 status = schan_imp_send(ctx->session, data, &length);
949 TRACE("Sent %ld bytes.\n", length);
951 if (length != data_size)
952 status = SEC_E_INTERNAL_ERROR;
954 b = &transport.out;
955 b->desc->pBuffers[b->current_buffer_idx].cbBuffer = b->offset;
956 HeapFree(GetProcessHeap(), 0, data);
958 TRACE("Returning %#x.\n", status);
960 return status;
963 static int schan_decrypt_message_get_next_buffer(const struct schan_transport *t, struct schan_buffers *s)
965 if (s->current_buffer_idx == -1)
966 return schan_find_sec_buffer_idx(s->desc, 0, SECBUFFER_DATA);
968 return -1;
971 static int schan_validate_decrypt_buffer_desc(PSecBufferDesc message)
973 int data_idx = -1;
974 unsigned int empty_count = 0;
975 unsigned int i;
977 if (message->cBuffers < 4)
979 WARN("Less than four buffers passed\n");
980 return -1;
983 for (i = 0; i < message->cBuffers; ++i)
985 SecBuffer *b = &message->pBuffers[i];
986 if (b->BufferType == SECBUFFER_DATA)
988 if (data_idx != -1)
990 WARN("More than one data buffer passed\n");
991 return -1;
993 data_idx = i;
995 else if (b->BufferType == SECBUFFER_EMPTY)
996 ++empty_count;
999 if (data_idx == -1)
1001 WARN("No data buffer passed\n");
1002 return -1;
1005 if (empty_count < 3)
1007 WARN("Less than three empty buffers passed\n");
1008 return -1;
1011 return data_idx;
1014 static void schan_decrypt_fill_buffer(PSecBufferDesc message, ULONG buffer_type, void *data, ULONG size)
1016 int idx;
1017 SecBuffer *buffer;
1019 idx = schan_find_sec_buffer_idx(message, 0, SECBUFFER_EMPTY);
1020 buffer = &message->pBuffers[idx];
1022 buffer->BufferType = buffer_type;
1023 buffer->pvBuffer = data;
1024 buffer->cbBuffer = size;
1027 static SECURITY_STATUS SEC_ENTRY schan_DecryptMessage(PCtxtHandle context_handle,
1028 PSecBufferDesc message, ULONG message_seq_no, PULONG quality)
1030 struct schan_transport transport;
1031 struct schan_context *ctx;
1032 SecBuffer *buffer;
1033 SIZE_T data_size;
1034 char *data;
1035 unsigned expected_size;
1036 SSIZE_T received = 0;
1037 int idx;
1038 unsigned char *buf_ptr;
1040 TRACE("context_handle %p, message %p, message_seq_no %d, quality %p\n",
1041 context_handle, message, message_seq_no, quality);
1043 if (!context_handle) return SEC_E_INVALID_HANDLE;
1044 ctx = schan_get_object(context_handle->dwLower, SCHAN_HANDLE_CTX);
1046 dump_buffer_desc(message);
1048 idx = schan_validate_decrypt_buffer_desc(message);
1049 if (idx == -1)
1050 return SEC_E_INVALID_TOKEN;
1051 buffer = &message->pBuffers[idx];
1052 buf_ptr = buffer->pvBuffer;
1054 expected_size = 5 + ((buf_ptr[3] << 8) | buf_ptr[4]);
1055 if(buffer->cbBuffer < expected_size)
1057 TRACE("Expected %u bytes, but buffer only contains %u bytes\n", expected_size, buffer->cbBuffer);
1058 buffer->BufferType = SECBUFFER_MISSING;
1059 buffer->cbBuffer = expected_size - buffer->cbBuffer;
1061 /* This is a bit weird, but windows does it too */
1062 idx = schan_find_sec_buffer_idx(message, 0, SECBUFFER_EMPTY);
1063 buffer = &message->pBuffers[idx];
1064 buffer->BufferType = SECBUFFER_MISSING;
1065 buffer->cbBuffer = expected_size - buffer->cbBuffer;
1067 TRACE("Returning SEC_E_INCOMPLETE_MESSAGE\n");
1068 return SEC_E_INCOMPLETE_MESSAGE;
1071 data_size = buffer->cbBuffer;
1072 data = HeapAlloc(GetProcessHeap(), 0, data_size);
1074 transport.ctx = ctx;
1075 init_schan_buffers(&transport.in, message, schan_decrypt_message_get_next_buffer);
1076 transport.in.limit = expected_size;
1077 init_schan_buffers(&transport.out, NULL, NULL);
1078 schan_imp_set_session_transport(ctx->session, &transport);
1080 while (received < data_size)
1082 SIZE_T length = data_size - received;
1083 SECURITY_STATUS status = schan_imp_recv(ctx->session, data + received, &length);
1084 if (status == SEC_I_CONTINUE_NEEDED)
1086 if (!received)
1088 HeapFree(GetProcessHeap(), 0, data);
1089 TRACE("Returning SEC_E_INCOMPLETE_MESSAGE\n");
1090 return SEC_E_INCOMPLETE_MESSAGE;
1092 break;
1094 else if (status != SEC_E_OK)
1096 HeapFree(GetProcessHeap(), 0, data);
1097 ERR("Returning %d\n", status);
1098 return status;
1100 else if (!length)
1101 break;
1103 received += length;
1106 TRACE("Received %ld bytes\n", received);
1108 memcpy(buf_ptr + 5, data, received);
1109 HeapFree(GetProcessHeap(), 0, data);
1111 schan_decrypt_fill_buffer(message, SECBUFFER_DATA,
1112 buf_ptr + 5, received);
1114 schan_decrypt_fill_buffer(message, SECBUFFER_STREAM_TRAILER,
1115 buf_ptr + 5 + received, buffer->cbBuffer - 5 - received);
1117 if(buffer->cbBuffer > expected_size)
1118 schan_decrypt_fill_buffer(message, SECBUFFER_EXTRA,
1119 buf_ptr + expected_size, buffer->cbBuffer - expected_size);
1121 buffer->BufferType = SECBUFFER_STREAM_HEADER;
1122 buffer->cbBuffer = 5;
1124 return SEC_E_OK;
1127 static SECURITY_STATUS SEC_ENTRY schan_DeleteSecurityContext(PCtxtHandle context_handle)
1129 struct schan_context *ctx;
1131 TRACE("context_handle %p\n", context_handle);
1133 if (!context_handle) return SEC_E_INVALID_HANDLE;
1135 ctx = schan_free_handle(context_handle->dwLower, SCHAN_HANDLE_CTX);
1136 if (!ctx) return SEC_E_INVALID_HANDLE;
1138 schan_imp_dispose_session(ctx->session);
1139 HeapFree(GetProcessHeap(), 0, ctx);
1141 return SEC_E_OK;
1144 static const SecurityFunctionTableA schanTableA = {
1146 NULL, /* EnumerateSecurityPackagesA */
1147 schan_QueryCredentialsAttributesA,
1148 schan_AcquireCredentialsHandleA,
1149 schan_FreeCredentialsHandle,
1150 NULL, /* Reserved2 */
1151 schan_InitializeSecurityContextA,
1152 NULL, /* AcceptSecurityContext */
1153 NULL, /* CompleteAuthToken */
1154 schan_DeleteSecurityContext,
1155 NULL, /* ApplyControlToken */
1156 schan_QueryContextAttributesA,
1157 NULL, /* ImpersonateSecurityContext */
1158 NULL, /* RevertSecurityContext */
1159 NULL, /* MakeSignature */
1160 NULL, /* VerifySignature */
1161 FreeContextBuffer,
1162 NULL, /* QuerySecurityPackageInfoA */
1163 NULL, /* Reserved3 */
1164 NULL, /* Reserved4 */
1165 NULL, /* ExportSecurityContext */
1166 NULL, /* ImportSecurityContextA */
1167 NULL, /* AddCredentialsA */
1168 NULL, /* Reserved8 */
1169 NULL, /* QuerySecurityContextToken */
1170 schan_EncryptMessage,
1171 schan_DecryptMessage,
1172 NULL, /* SetContextAttributesA */
1175 static const SecurityFunctionTableW schanTableW = {
1177 NULL, /* EnumerateSecurityPackagesW */
1178 schan_QueryCredentialsAttributesW,
1179 schan_AcquireCredentialsHandleW,
1180 schan_FreeCredentialsHandle,
1181 NULL, /* Reserved2 */
1182 schan_InitializeSecurityContextW,
1183 NULL, /* AcceptSecurityContext */
1184 NULL, /* CompleteAuthToken */
1185 schan_DeleteSecurityContext,
1186 NULL, /* ApplyControlToken */
1187 schan_QueryContextAttributesW,
1188 NULL, /* ImpersonateSecurityContext */
1189 NULL, /* RevertSecurityContext */
1190 NULL, /* MakeSignature */
1191 NULL, /* VerifySignature */
1192 FreeContextBuffer,
1193 NULL, /* QuerySecurityPackageInfoW */
1194 NULL, /* Reserved3 */
1195 NULL, /* Reserved4 */
1196 NULL, /* ExportSecurityContext */
1197 NULL, /* ImportSecurityContextW */
1198 NULL, /* AddCredentialsW */
1199 NULL, /* Reserved8 */
1200 NULL, /* QuerySecurityContextToken */
1201 schan_EncryptMessage,
1202 schan_DecryptMessage,
1203 NULL, /* SetContextAttributesW */
1206 static const WCHAR schannelComment[] = { 'S','c','h','a','n','n','e','l',' ',
1207 'S','e','c','u','r','i','t','y',' ','P','a','c','k','a','g','e',0 };
1208 static const WCHAR schannelDllName[] = { 's','c','h','a','n','n','e','l','.','d','l','l',0 };
1210 void SECUR32_initSchannelSP(void)
1212 /* This is what Windows reports. This shouldn't break any applications
1213 * even though the functions are missing, because the wrapper will
1214 * return SEC_E_UNSUPPORTED_FUNCTION if our function is NULL.
1216 static const LONG caps =
1217 SECPKG_FLAG_INTEGRITY |
1218 SECPKG_FLAG_PRIVACY |
1219 SECPKG_FLAG_CONNECTION |
1220 SECPKG_FLAG_MULTI_REQUIRED |
1221 SECPKG_FLAG_EXTENDED_ERROR |
1222 SECPKG_FLAG_IMPERSONATION |
1223 SECPKG_FLAG_ACCEPT_WIN32_NAME |
1224 SECPKG_FLAG_STREAM;
1225 static const short version = 1;
1226 static const LONG maxToken = 16384;
1227 SEC_WCHAR *uniSPName = (SEC_WCHAR *)UNISP_NAME_W,
1228 *schannel = (SEC_WCHAR *)SCHANNEL_NAME_W;
1229 const SecPkgInfoW info[] = {
1230 { caps, version, UNISP_RPC_ID, maxToken, uniSPName, uniSPName },
1231 { caps, version, UNISP_RPC_ID, maxToken, schannel,
1232 (SEC_WCHAR *)schannelComment },
1234 SecureProvider *provider;
1236 if (!schan_imp_init())
1237 return;
1239 schan_handle_table = HeapAlloc(GetProcessHeap(), 0, 64 * sizeof(*schan_handle_table));
1240 if (!schan_handle_table)
1242 ERR("Failed to allocate schannel handle table.\n");
1243 goto fail;
1245 schan_handle_table_size = 64;
1247 provider = SECUR32_addProvider(&schanTableA, &schanTableW, schannelDllName);
1248 if (!provider)
1250 ERR("Failed to add schannel provider.\n");
1251 goto fail;
1254 SECUR32_addPackages(provider, sizeof(info) / sizeof(info[0]), NULL, info);
1256 return;
1258 fail:
1259 HeapFree(GetProcessHeap(), 0, schan_handle_table);
1260 schan_handle_table = NULL;
1261 schan_imp_deinit();
1262 return;
1265 void SECUR32_deinitSchannelSP(void)
1267 SIZE_T i = schan_handle_count;
1269 if (!schan_handle_table) return;
1271 /* deinitialized sessions first because a pointer to the credentials
1272 * may be stored for the session. */
1273 while (i--)
1275 if (schan_handle_table[i].type == SCHAN_HANDLE_CTX)
1277 struct schan_context *ctx = schan_free_handle(i, SCHAN_HANDLE_CTX);
1278 schan_imp_dispose_session(ctx->session);
1279 HeapFree(GetProcessHeap(), 0, ctx);
1282 i = schan_handle_count;
1283 while (i--)
1285 if (schan_handle_table[i].type != SCHAN_HANDLE_FREE)
1287 struct schan_credentials *cred;
1288 cred = schan_free_handle(i, SCHAN_HANDLE_CRED);
1289 schan_imp_free_certificate_credentials(cred->credentials);
1290 HeapFree(GetProcessHeap(), 0, cred);
1293 HeapFree(GetProcessHeap(), 0, schan_handle_table);
1294 schan_imp_deinit();
1297 #else /* SONAME_LIBGNUTLS || HAVE_SECURITY_SECURITY_H */
1299 void SECUR32_initSchannelSP(void)
1301 ERR("TLS library not found, SSL connections will fail\n");
1304 void SECUR32_deinitSchannelSP(void) {}
1306 #endif /* SONAME_LIBGNUTLS || HAVE_SECURITY_SECURITY_H */