2 * Wininet - networking layer. Uses unix sockets or OpenSSL.
4 * Copyright 2002 TransGaming Technologies Inc.
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
24 #include "wine/port.h"
26 #define NONAMELESSUNION
28 #if defined(__MINGW32__) || defined (_MSC_VER)
32 #include <sys/types.h>
36 #ifdef HAVE_SYS_POLL_H
37 # include <sys/poll.h>
39 #ifdef HAVE_SYS_TIME_H
40 # include <sys/time.h>
42 #ifdef HAVE_SYS_SOCKET_H
43 # include <sys/socket.h>
45 #ifdef HAVE_SYS_FILIO_H
46 # include <sys/filio.h>
51 #ifdef HAVE_SYS_IOCTL_H
52 # include <sys/ioctl.h>
58 #ifdef HAVE_NETINET_IN_H
59 # include <netinet/in.h>
61 #ifdef HAVE_NETINET_TCP_H
62 # include <netinet/tcp.h>
64 #ifdef HAVE_OPENSSL_SSL_H
65 # include <openssl/ssl.h>
66 # include <openssl/opensslv.h>
78 #include "wine/library.h"
84 #include "wine/debug.h"
87 /* To avoid conflicts with the Unix socket headers. we only need it for
88 * the error codes anyway. */
92 #define RESPONSE_TIMEOUT 30 /* FROM internet.c */
95 WINE_DEFAULT_DEBUG_CHANNEL(wininet);
98 * This should use winsock - To use winsock the functions will have to change a bit
99 * as they are designed for unix sockets.
100 * SSL stuff should use crypt32.dll
105 #include <openssl/err.h>
107 static void *OpenSSL_ssl_handle;
108 static void *OpenSSL_crypto_handle;
110 #if defined(OPENSSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER > 0x10000000)
111 static const SSL_METHOD *meth;
113 static SSL_METHOD *meth;
116 static int error_idx;
119 #define MAKE_FUNCPTR(f) static typeof(f) * p##f
121 /* OpenSSL functions that we use */
122 MAKE_FUNCPTR(SSL_library_init);
123 MAKE_FUNCPTR(SSL_load_error_strings);
124 MAKE_FUNCPTR(SSLv23_method);
125 MAKE_FUNCPTR(SSL_CTX_free);
126 MAKE_FUNCPTR(SSL_CTX_new);
127 MAKE_FUNCPTR(SSL_CTX_ctrl);
128 MAKE_FUNCPTR(SSL_new);
129 MAKE_FUNCPTR(SSL_free);
130 MAKE_FUNCPTR(SSL_ctrl);
131 MAKE_FUNCPTR(SSL_set_fd);
132 MAKE_FUNCPTR(SSL_connect);
133 MAKE_FUNCPTR(SSL_shutdown);
134 MAKE_FUNCPTR(SSL_write);
135 MAKE_FUNCPTR(SSL_read);
136 MAKE_FUNCPTR(SSL_pending);
137 MAKE_FUNCPTR(SSL_get_error);
138 MAKE_FUNCPTR(SSL_get_ex_new_index);
139 MAKE_FUNCPTR(SSL_get_ex_data);
140 MAKE_FUNCPTR(SSL_set_ex_data);
141 MAKE_FUNCPTR(SSL_get_ex_data_X509_STORE_CTX_idx);
142 MAKE_FUNCPTR(SSL_get_peer_certificate);
143 MAKE_FUNCPTR(SSL_CTX_get_timeout);
144 MAKE_FUNCPTR(SSL_CTX_set_timeout);
145 MAKE_FUNCPTR(SSL_CTX_set_default_verify_paths);
146 MAKE_FUNCPTR(SSL_CTX_set_verify);
147 MAKE_FUNCPTR(SSL_get_current_cipher);
148 MAKE_FUNCPTR(SSL_CIPHER_get_bits);
150 /* OpenSSL's libcrypto functions that we use */
151 MAKE_FUNCPTR(BIO_new_fp);
152 MAKE_FUNCPTR(CRYPTO_num_locks);
153 MAKE_FUNCPTR(CRYPTO_set_id_callback);
154 MAKE_FUNCPTR(CRYPTO_set_locking_callback);
155 MAKE_FUNCPTR(ERR_free_strings);
156 MAKE_FUNCPTR(ERR_get_error);
157 MAKE_FUNCPTR(ERR_error_string);
158 MAKE_FUNCPTR(X509_STORE_CTX_get_ex_data);
159 MAKE_FUNCPTR(X509_STORE_CTX_get_chain);
160 MAKE_FUNCPTR(i2d_X509);
161 MAKE_FUNCPTR(sk_num);
162 MAKE_FUNCPTR(sk_value);
165 static CRITICAL_SECTION *ssl_locks;
166 static unsigned int num_ssl_locks;
168 static unsigned long ssl_thread_id(void)
170 return GetCurrentThreadId();
173 static void ssl_lock_callback(int mode, int type, const char *file, int line)
175 if (mode & CRYPTO_LOCK)
176 EnterCriticalSection(&ssl_locks[type]);
178 LeaveCriticalSection(&ssl_locks[type]);
181 static PCCERT_CONTEXT X509_to_cert_context(X509 *cert)
183 unsigned char* buffer,*p;
185 BOOL malloced = FALSE;
189 len = pi2d_X509(cert,&p);
191 * SSL 0.9.7 and above malloc the buffer if it is null.
192 * however earlier version do not and so we would need to alloc the buffer.
194 * see the i2d_X509 man page for more details.
198 buffer = heap_alloc(len);
200 len = pi2d_X509(cert,&p);
208 ret = CertCreateCertificateContext(X509_ASN_ENCODING,buffer,len);
218 static DWORD netconn_verify_cert(netconn_t *conn, PCCERT_CONTEXT cert, HCERTSTORE store)
221 CERT_CHAIN_PARA chainPara = { sizeof(chainPara), { 0 } };
222 PCCERT_CHAIN_CONTEXT chain;
223 char oid_server_auth[] = szOID_PKIX_KP_SERVER_AUTH;
224 char *server_auth[] = { oid_server_auth };
225 DWORD err = ERROR_SUCCESS, chainFlags = 0, errors;
227 static const DWORD supportedErrors =
228 CERT_TRUST_IS_NOT_TIME_VALID |
229 CERT_TRUST_IS_UNTRUSTED_ROOT |
230 CERT_TRUST_IS_PARTIAL_CHAIN |
231 CERT_TRUST_IS_OFFLINE_REVOCATION |
232 CERT_TRUST_REVOCATION_STATUS_UNKNOWN |
233 CERT_TRUST_IS_REVOKED |
234 CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
236 TRACE("verifying %s\n", debugstr_w(conn->server->name));
238 chainPara.RequestedUsage.Usage.cUsageIdentifier = 1;
239 chainPara.RequestedUsage.Usage.rgpszUsageIdentifier = server_auth;
240 if (!(conn->security_flags & SECURITY_FLAG_IGNORE_REVOCATION))
241 chainFlags |= CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT;
243 if (!(ret = CertGetCertificateChain(NULL, cert, NULL, store, &chainPara, chainFlags, NULL, &chain))) {
245 return GetLastError();
248 errors = chain->TrustStatus.dwErrorStatus;
251 /* This seems strange, but that's what tests show */
252 if(errors & (CERT_TRUST_IS_PARTIAL_CHAIN|CERT_TRUST_IS_OFFLINE_REVOCATION)) {
253 WARN("ERROR_INTERNET_SEC_CERT_REV_FAILED\n");
254 err = ERROR_INTERNET_SEC_CERT_REV_FAILED;
255 if(conn->mask_errors)
256 conn->security_flags |= _SECURITY_FLAG_CERT_REV_FAILED;
257 if(!(conn->security_flags & SECURITY_FLAG_IGNORE_REVOCATION))
261 if (chain->TrustStatus.dwErrorStatus & ~supportedErrors) {
262 WARN("error status %x\n", chain->TrustStatus.dwErrorStatus & ~supportedErrors);
263 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_INVALID_CERT;
264 errors &= supportedErrors;
265 if(!conn->mask_errors)
267 WARN("unknown error flags\n");
270 if(errors & CERT_TRUST_IS_NOT_TIME_VALID) {
271 WARN("CERT_TRUST_IS_NOT_TIME_VALID\n");
272 if(!(conn->security_flags & SECURITY_FLAG_IGNORE_CERT_DATE_INVALID)) {
273 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_CERT_DATE_INVALID;
274 if(!conn->mask_errors)
276 conn->security_flags |= _SECURITY_FLAG_CERT_INVALID_DATE;
278 errors &= ~CERT_TRUST_IS_NOT_TIME_VALID;
281 if(errors & CERT_TRUST_IS_UNTRUSTED_ROOT) {
282 WARN("CERT_TRUST_IS_UNTRUSTED_ROOT\n");
283 if(!(conn->security_flags & SECURITY_FLAG_IGNORE_UNKNOWN_CA)) {
284 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_INVALID_CA;
285 if(!conn->mask_errors)
287 conn->security_flags |= _SECURITY_FLAG_CERT_INVALID_CA;
289 errors &= ~CERT_TRUST_IS_UNTRUSTED_ROOT;
292 if(errors & CERT_TRUST_IS_PARTIAL_CHAIN) {
293 WARN("CERT_TRUST_IS_PARTIAL_CHAIN\n");
294 if(!(conn->security_flags & SECURITY_FLAG_IGNORE_UNKNOWN_CA)) {
295 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_INVALID_CA;
296 if(!conn->mask_errors)
298 conn->security_flags |= _SECURITY_FLAG_CERT_INVALID_CA;
300 errors &= ~CERT_TRUST_IS_PARTIAL_CHAIN;
303 if(errors & (CERT_TRUST_IS_OFFLINE_REVOCATION | CERT_TRUST_REVOCATION_STATUS_UNKNOWN)) {
304 WARN("CERT_TRUST_IS_OFFLINE_REVOCATION | CERT_TRUST_REVOCATION_STATUS_UNKNOWN\n");
305 if(!(conn->security_flags & SECURITY_FLAG_IGNORE_REVOCATION)) {
306 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_CERT_NO_REV;
307 if(!conn->mask_errors)
309 conn->security_flags |= _SECURITY_FLAG_CERT_REV_FAILED;
311 errors &= ~(CERT_TRUST_IS_OFFLINE_REVOCATION | CERT_TRUST_REVOCATION_STATUS_UNKNOWN);
314 if(errors & CERT_TRUST_IS_REVOKED) {
315 WARN("CERT_TRUST_IS_REVOKED\n");
316 if(!(conn->security_flags & SECURITY_FLAG_IGNORE_REVOCATION)) {
317 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_CERT_REVOKED;
318 if(!conn->mask_errors)
320 WARN("TRUST_IS_OFFLINE_REVOCATION | CERT_TRUST_REVOCATION_STATUS_UNKNOWN, unknown error flags\n");
322 errors &= ~CERT_TRUST_IS_REVOKED;
325 if(errors & CERT_TRUST_IS_NOT_VALID_FOR_USAGE) {
326 WARN("CERT_TRUST_IS_NOT_VALID_FOR_USAGE\n");
327 if(!(conn->security_flags & SECURITY_FLAG_IGNORE_WRONG_USAGE)) {
328 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_INVALID_CERT;
329 if(!conn->mask_errors)
331 WARN("CERT_TRUST_IS_NOT_VALID_FOR_USAGE, unknown error flags\n");
333 errors &= ~CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
336 if(err == ERROR_INTERNET_SEC_CERT_REV_FAILED) {
337 assert(conn->security_flags & SECURITY_FLAG_IGNORE_REVOCATION);
342 if(!err || conn->mask_errors) {
343 CERT_CHAIN_POLICY_PARA policyPara;
344 SSL_EXTRA_CERT_CHAIN_POLICY_PARA sslExtraPolicyPara;
345 CERT_CHAIN_POLICY_STATUS policyStatus;
346 CERT_CHAIN_CONTEXT chainCopy;
348 /* Clear chain->TrustStatus.dwErrorStatus so
349 * CertVerifyCertificateChainPolicy will verify additional checks
350 * rather than stopping with an existing, ignored error.
352 memcpy(&chainCopy, chain, sizeof(chainCopy));
353 chainCopy.TrustStatus.dwErrorStatus = 0;
354 sslExtraPolicyPara.u.cbSize = sizeof(sslExtraPolicyPara);
355 sslExtraPolicyPara.dwAuthType = AUTHTYPE_SERVER;
356 sslExtraPolicyPara.pwszServerName = conn->server->name;
357 sslExtraPolicyPara.fdwChecks = conn->security_flags;
358 policyPara.cbSize = sizeof(policyPara);
359 policyPara.dwFlags = 0;
360 policyPara.pvExtraPolicyPara = &sslExtraPolicyPara;
361 ret = CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL,
362 &chainCopy, &policyPara, &policyStatus);
363 /* Any error in the policy status indicates that the
364 * policy couldn't be verified.
367 if(policyStatus.dwError == CERT_E_CN_NO_MATCH) {
368 WARN("CERT_E_CN_NO_MATCH\n");
369 if(conn->mask_errors)
370 conn->security_flags |= _SECURITY_FLAG_CERT_INVALID_CN;
371 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_CERT_CN_INVALID;
372 }else if(policyStatus.dwError) {
373 WARN("policyStatus.dwError %x\n", policyStatus.dwError);
374 if(conn->mask_errors)
375 WARN("unknown error flags for policy status %x\n", policyStatus.dwError);
376 err = conn->mask_errors && err ? ERROR_INTERNET_SEC_CERT_ERRORS : ERROR_INTERNET_SEC_INVALID_CERT;
379 err = GetLastError();
384 WARN("failed %u\n", err);
385 CertFreeCertificateChain(chain);
386 if(conn->server->cert_chain) {
387 CertFreeCertificateChain(conn->server->cert_chain);
388 conn->server->cert_chain = NULL;
390 if(conn->mask_errors)
391 conn->server->security_flags |= conn->security_flags & _SECURITY_ERROR_FLAGS_MASK;
395 /* FIXME: Reuse cached chain */
396 if(conn->server->cert_chain)
397 CertFreeCertificateChain(chain);
399 conn->server->cert_chain = chain;
400 return ERROR_SUCCESS;
403 static int netconn_secure_verify(int preverify_ok, X509_STORE_CTX *ctx)
407 HCERTSTORE store = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0,
408 CERT_STORE_CREATE_NEW_FLAG, NULL);
411 ssl = pX509_STORE_CTX_get_ex_data(ctx,
412 pSSL_get_ex_data_X509_STORE_CTX_idx());
413 conn = pSSL_get_ex_data(ssl, conn_idx);
418 PCCERT_CONTEXT endCert = NULL;
419 struct stack_st *chain = (struct stack_st *)pX509_STORE_CTX_get_chain( ctx );
422 for (i = 0; ret && i < psk_num(chain); i++)
424 PCCERT_CONTEXT context;
426 cert = (X509 *)psk_value(chain, i);
427 if ((context = X509_to_cert_context(cert)))
429 ret = CertAddCertificateContextToStore(store, context,
430 CERT_STORE_ADD_ALWAYS, i ? NULL : &endCert);
431 CertFreeCertificateContext(context);
434 if (!endCert) ret = FALSE;
437 DWORD_PTR err = netconn_verify_cert(conn, endCert, store);
441 pSSL_set_ex_data(ssl, error_idx, (void *)err);
445 CertFreeCertificateContext(endCert);
446 CertCloseStore(store, 0);
451 static long get_tls_option(void) {
452 long tls_option = SSL_OP_NO_SSLv2; /* disable SSLv2 for security reason, secur32/Schannel(GnuTLS) don't support it */
453 #ifdef SSL_OP_NO_TLSv1_2
454 DWORD type, val, size;
455 HKEY hkey,tls12_client,tls11_client;
457 const WCHAR Schannel_Prot[] = { /* SYSTEM\\CurrentControlSet\\Control\\SecurityProviders\\SCANNEL\\Protocols */
458 'S','Y','S','T','E','M','\\',
459 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
460 'C','o','n','t','r','o','l','\\',
461 'S','e','c','u','r','i','t','y','P','r','o','v','i','d','e','r','s','\\',
462 'S','C','H','A','N','N','E','L','\\',
463 'P','r','o','t','o','c','o','l','s',0 };
464 const WCHAR TLS12_Client[] = {'T','L','S',' ','1','.','2','\\','C','l','i','e','n','t',0};
465 const WCHAR TLS11_Client[] = {'T','L','S',' ','1','.','1','\\','C','l','i','e','n','t',0};
466 const WCHAR DisabledByDefault[] = {'D','i','s','a','b','l','e','d','B','y','D','e','f','a','u','l','t',0};
468 res = RegOpenKeyExW(HKEY_LOCAL_MACHINE,
471 if (res != ERROR_SUCCESS) { /* enabled TLSv1.1/1.2 when no registry entry */
474 if (RegOpenKeyExW(hkey, TLS12_Client, 0, KEY_READ, &tls12_client) == ERROR_SUCCESS) {
475 size = sizeof(DWORD);
476 if (RegQueryValueExW(tls12_client, DisabledByDefault, NULL, &type, (LPBYTE) &val, &size) == ERROR_SUCCESS
477 && type == REG_DWORD) {
478 tls_option |= val?SSL_OP_NO_TLSv1_2:0;
480 RegCloseKey(tls12_client);
482 if (RegOpenKeyExW(hkey, TLS11_Client, 0, KEY_READ, &tls11_client) == ERROR_SUCCESS) {
483 size = sizeof(DWORD);
484 if (RegQueryValueExW(tls11_client, DisabledByDefault, NULL, &type, (LPBYTE) &val, &size) == ERROR_SUCCESS
485 && type == REG_DWORD) {
486 tls_option |= val?SSL_OP_NO_TLSv1_1:0;
488 RegCloseKey(tls11_client);
494 #endif /* SONAME_LIBSSL */
496 static CRITICAL_SECTION init_ssl_cs;
497 static CRITICAL_SECTION_DEBUG init_ssl_cs_debug =
500 { &init_ssl_cs_debug.ProcessLocksList,
501 &init_ssl_cs_debug.ProcessLocksList },
502 0, 0, { (DWORD_PTR)(__FILE__ ": init_ssl_cs") }
504 static CRITICAL_SECTION init_ssl_cs = { &init_ssl_cs_debug, -1, 0, 0, 0, 0 };
506 static DWORD init_openssl(void)
508 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
511 if(OpenSSL_ssl_handle)
512 return ERROR_SUCCESS;
514 OpenSSL_ssl_handle = wine_dlopen(SONAME_LIBSSL, RTLD_NOW, NULL, 0);
515 if(!OpenSSL_ssl_handle) {
516 ERR("trying to use a SSL connection, but couldn't load %s. Expect trouble.\n", SONAME_LIBSSL);
517 return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
520 OpenSSL_crypto_handle = wine_dlopen(SONAME_LIBCRYPTO, RTLD_NOW, NULL, 0);
521 if(!OpenSSL_crypto_handle) {
522 ERR("trying to use a SSL connection, but couldn't load %s. Expect trouble.\n", SONAME_LIBCRYPTO);
523 return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
526 /* mmm nice ugly macroness */
528 p##x = wine_dlsym(OpenSSL_ssl_handle, #x, NULL, 0); \
530 ERR("failed to load symbol %s\n", #x); \
531 return ERROR_INTERNET_SECURITY_CHANNEL_ERROR; \
534 DYNSSL(SSL_library_init);
535 DYNSSL(SSL_load_error_strings);
536 DYNSSL(SSLv23_method);
537 DYNSSL(SSL_CTX_free);
539 DYNSSL(SSL_CTX_ctrl);
545 DYNSSL(SSL_shutdown);
549 DYNSSL(SSL_get_error);
550 DYNSSL(SSL_get_ex_new_index);
551 DYNSSL(SSL_get_ex_data);
552 DYNSSL(SSL_set_ex_data);
553 DYNSSL(SSL_get_ex_data_X509_STORE_CTX_idx);
554 DYNSSL(SSL_get_peer_certificate);
555 DYNSSL(SSL_CTX_get_timeout);
556 DYNSSL(SSL_CTX_set_timeout);
557 DYNSSL(SSL_CTX_set_default_verify_paths);
558 DYNSSL(SSL_CTX_set_verify);
559 DYNSSL(SSL_get_current_cipher);
560 DYNSSL(SSL_CIPHER_get_bits);
563 #define DYNCRYPTO(x) \
564 p##x = wine_dlsym(OpenSSL_crypto_handle, #x, NULL, 0); \
566 ERR("failed to load symbol %s\n", #x); \
567 return ERROR_INTERNET_SECURITY_CHANNEL_ERROR; \
570 DYNCRYPTO(BIO_new_fp);
571 DYNCRYPTO(CRYPTO_num_locks);
572 DYNCRYPTO(CRYPTO_set_id_callback);
573 DYNCRYPTO(CRYPTO_set_locking_callback);
574 DYNCRYPTO(ERR_free_strings);
575 DYNCRYPTO(ERR_get_error);
576 DYNCRYPTO(ERR_error_string);
577 DYNCRYPTO(X509_STORE_CTX_get_ex_data);
578 DYNCRYPTO(X509_STORE_CTX_get_chain);
584 #define pSSL_CTX_set_options(ctx,op) \
585 pSSL_CTX_ctrl((ctx),SSL_CTRL_OPTIONS,(op),NULL)
586 #define pSSL_set_options(ssl,op) \
587 pSSL_ctrl((ssl),SSL_CTRL_OPTIONS,(op),NULL)
590 pSSL_load_error_strings();
591 pBIO_new_fp(stderr, BIO_NOCLOSE); /* FIXME: should use winedebug stuff */
593 meth = pSSLv23_method();
594 ctx = pSSL_CTX_new(meth);
595 pSSL_CTX_set_options(ctx, get_tls_option());
596 if(!pSSL_CTX_set_default_verify_paths(ctx)) {
597 ERR("SSL_CTX_set_default_verify_paths failed: %s\n",
598 pERR_error_string(pERR_get_error(), 0));
599 return ERROR_OUTOFMEMORY;
602 error_idx = pSSL_get_ex_new_index(0, (void *)"error index", NULL, NULL, NULL);
603 if(error_idx == -1) {
604 ERR("SSL_get_ex_new_index failed; %s\n", pERR_error_string(pERR_get_error(), 0));
605 return ERROR_OUTOFMEMORY;
608 conn_idx = pSSL_get_ex_new_index(0, (void *)"netconn index", NULL, NULL, NULL);
610 ERR("SSL_get_ex_new_index failed; %s\n", pERR_error_string(pERR_get_error(), 0));
611 return ERROR_OUTOFMEMORY;
614 pSSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, netconn_secure_verify);
616 pCRYPTO_set_id_callback(ssl_thread_id);
617 num_ssl_locks = pCRYPTO_num_locks();
618 ssl_locks = heap_alloc(num_ssl_locks * sizeof(CRITICAL_SECTION));
620 return ERROR_OUTOFMEMORY;
622 for(i = 0; i < num_ssl_locks; i++)
624 InitializeCriticalSection(&ssl_locks[i]);
625 ssl_locks[i].DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": ssl_locks");
627 pCRYPTO_set_locking_callback(ssl_lock_callback);
629 return ERROR_SUCCESS;
631 FIXME("can't use SSL, not compiled in.\n");
632 return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
636 static DWORD create_netconn_socket(server_t *server, netconn_t *netconn, DWORD timeout)
640 assert(server->addr_len);
641 result = netconn->socketFD = socket(server->addr.ss_family, SOCK_STREAM, 0);
644 ioctlsocket(netconn->socketFD, FIONBIO, &flag);
645 result = connect(netconn->socketFD, (struct sockaddr*)&server->addr, server->addr_len);
648 if (sock_get_error(errno) == WSAEINPROGRESS) {
652 pfd.fd = netconn->socketFD;
653 pfd.events = POLLOUT;
654 res = poll(&pfd, 1, timeout);
657 closesocket(netconn->socketFD);
658 return ERROR_INTERNET_CANNOT_CONNECT;
663 socklen_t len = sizeof(err);
664 if (!getsockopt(netconn->socketFD, SOL_SOCKET, SO_ERROR, &err, &len) && !err)
670 closesocket(netconn->socketFD);
673 ioctlsocket(netconn->socketFD, FIONBIO, &flag);
677 return sock_get_error(errno);
681 result = setsockopt(netconn->socketFD, IPPROTO_TCP, TCP_NODELAY, (void*)&flag, sizeof(flag));
683 WARN("setsockopt(TCP_NODELAY) failed\n");
686 return ERROR_SUCCESS;
689 DWORD create_netconn(BOOL useSSL, server_t *server, DWORD security_flags, BOOL mask_errors, DWORD timeout, netconn_t **ret)
697 TRACE("using SSL connection\n");
699 EnterCriticalSection(&init_ssl_cs);
700 res = init_openssl();
701 LeaveCriticalSection(&init_ssl_cs);
702 if(res != ERROR_SUCCESS)
706 netconn = heap_alloc_zero(sizeof(*netconn));
708 return ERROR_OUTOFMEMORY;
710 netconn->socketFD = -1;
711 netconn->security_flags = security_flags | server->security_flags;
712 netconn->mask_errors = mask_errors;
713 list_init(&netconn->pool_entry);
715 result = create_netconn_socket(server, netconn, timeout);
716 if (result != ERROR_SUCCESS) {
721 server_addref(server);
722 netconn->server = server;
727 void free_netconn(netconn_t *netconn)
729 server_release(netconn->server);
732 if (netconn->ssl_s) {
733 pSSL_shutdown(netconn->ssl_s);
734 pSSL_free(netconn->ssl_s);
738 closesocket(netconn->socketFD);
742 void NETCON_unload(void)
744 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
745 if (OpenSSL_crypto_handle)
748 wine_dlclose(OpenSSL_crypto_handle, NULL, 0);
750 if (OpenSSL_ssl_handle)
754 wine_dlclose(OpenSSL_ssl_handle, NULL, 0);
759 for (i = 0; i < num_ssl_locks; i++)
761 ssl_locks[i].DebugInfo->Spare[0] = 0;
762 DeleteCriticalSection(&ssl_locks[i]);
764 heap_free(ssl_locks);
769 /* translate a unix error code into a winsock one */
770 int sock_get_error( int err )
772 #if !defined(__MINGW32__) && !defined (_MSC_VER)
775 case EINTR: return WSAEINTR;
776 case EBADF: return WSAEBADF;
778 case EACCES: return WSAEACCES;
779 case EFAULT: return WSAEFAULT;
780 case EINVAL: return WSAEINVAL;
781 case EMFILE: return WSAEMFILE;
782 case EWOULDBLOCK: return WSAEWOULDBLOCK;
783 case EINPROGRESS: return WSAEINPROGRESS;
784 case EALREADY: return WSAEALREADY;
785 case ENOTSOCK: return WSAENOTSOCK;
786 case EDESTADDRREQ: return WSAEDESTADDRREQ;
787 case EMSGSIZE: return WSAEMSGSIZE;
788 case EPROTOTYPE: return WSAEPROTOTYPE;
789 case ENOPROTOOPT: return WSAENOPROTOOPT;
790 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
791 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
792 case EOPNOTSUPP: return WSAEOPNOTSUPP;
793 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
794 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
795 case EADDRINUSE: return WSAEADDRINUSE;
796 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
797 case ENETDOWN: return WSAENETDOWN;
798 case ENETUNREACH: return WSAENETUNREACH;
799 case ENETRESET: return WSAENETRESET;
800 case ECONNABORTED: return WSAECONNABORTED;
802 case ECONNRESET: return WSAECONNRESET;
803 case ENOBUFS: return WSAENOBUFS;
804 case EISCONN: return WSAEISCONN;
805 case ENOTCONN: return WSAENOTCONN;
806 case ESHUTDOWN: return WSAESHUTDOWN;
807 case ETOOMANYREFS: return WSAETOOMANYREFS;
808 case ETIMEDOUT: return WSAETIMEDOUT;
809 case ECONNREFUSED: return WSAECONNREFUSED;
810 case ELOOP: return WSAELOOP;
811 case ENAMETOOLONG: return WSAENAMETOOLONG;
812 case EHOSTDOWN: return WSAEHOSTDOWN;
813 case EHOSTUNREACH: return WSAEHOSTUNREACH;
814 case ENOTEMPTY: return WSAENOTEMPTY;
816 case EPROCLIM: return WSAEPROCLIM;
819 case EUSERS: return WSAEUSERS;
822 case EDQUOT: return WSAEDQUOT;
825 case ESTALE: return WSAESTALE;
828 case EREMOTE: return WSAEREMOTE;
830 default: errno=err; perror("sock_set_error"); return WSAEFAULT;
837 static DWORD netcon_secure_connect_setup(netconn_t *connection, long tls_option)
843 ssl_s = pSSL_new(ctx);
846 ERR("SSL_new failed: %s\n",
847 pERR_error_string(pERR_get_error(), 0));
848 return ERROR_OUTOFMEMORY;
851 pSSL_set_options(ssl_s, tls_option);
852 if (!pSSL_set_fd(ssl_s, connection->socketFD))
854 ERR("SSL_set_fd failed: %s\n",
855 pERR_error_string(pERR_get_error(), 0));
856 res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
860 if (!pSSL_set_ex_data(ssl_s, conn_idx, connection))
862 ERR("SSL_set_ex_data failed: %s\n",
863 pERR_error_string(pERR_get_error(), 0));
864 res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
867 if (pSSL_connect(ssl_s) <= 0)
869 res = (DWORD_PTR)pSSL_get_ex_data(ssl_s, error_idx);
871 res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
872 ERR("SSL_connect failed: %d\n", res);
876 connection->ssl_s = ssl_s;
878 bits = NETCON_GetCipherStrength(connection);
880 connection->security_flags |= SECURITY_FLAG_STRENGTH_STRONG;
882 connection->security_flags |= SECURITY_FLAG_STRENGTH_MEDIUM;
884 connection->security_flags |= SECURITY_FLAG_STRENGTH_WEAK;
885 connection->security_flags |= SECURITY_FLAG_SECURE;
887 if(connection->mask_errors)
888 connection->server->security_flags = connection->security_flags;
889 return ERROR_SUCCESS;
894 pSSL_shutdown(ssl_s);
901 /******************************************************************************
902 * NETCON_secure_connect
903 * Initiates a secure connection over an existing plaintext connection.
905 DWORD NETCON_secure_connect(netconn_t *connection, server_t *server)
907 DWORD res = ERROR_NOT_SUPPORTED;
909 /* can't connect if we are already connected */
910 if (connection->ssl_s)
912 ERR("already connected\n");
913 return ERROR_INTERNET_CANNOT_CONNECT;
916 connection->useSSL = TRUE;
917 if(server != connection->server) {
918 server_release(connection->server);
919 server_addref(server);
920 connection->server = server;
923 /* connect with given TLS options */
924 res = netcon_secure_connect_setup(connection, get_tls_option());
925 if (res == ERROR_SUCCESS)
928 #ifdef SSL_OP_NO_TLSv1_2
929 /* FIXME: when got version alert and FIN from server */
930 /* fallback to connect without TLSv1.1/TLSv1.2 */
931 if (res == ERROR_INTERNET_SECURITY_CHANNEL_ERROR)
933 closesocket(connection->socketFD);
934 pSSL_CTX_set_options(ctx,SSL_OP_NO_TLSv1_1|SSL_OP_NO_TLSv1_2);
935 res = create_netconn_socket(connection->server, connection, 500);
936 if (res != ERROR_SUCCESS)
938 res = netcon_secure_connect_setup(connection, get_tls_option()|SSL_OP_NO_TLSv1_1|SSL_OP_NO_TLSv1_2);
945 /******************************************************************************
947 * Basically calls 'send()' unless we should use SSL
948 * number of chars send is put in *sent
950 DWORD NETCON_send(netconn_t *connection, const void *msg, size_t len, int flags,
953 if (!connection->useSSL)
955 *sent = send(connection->socketFD, msg, len, flags);
957 return sock_get_error(errno);
958 return ERROR_SUCCESS;
963 if(!connection->ssl_s) {
964 FIXME("not connected\n");
965 return ERROR_NOT_SUPPORTED;
968 FIXME("SSL_write doesn't support any flags (%08x)\n", flags);
969 *sent = pSSL_write(connection->ssl_s, msg, len);
970 if (*sent < 1 && len)
971 return ERROR_INTERNET_CONNECTION_ABORTED;
972 return ERROR_SUCCESS;
974 return ERROR_NOT_SUPPORTED;
979 /******************************************************************************
981 * Basically calls 'recv()' unless we should use SSL
982 * number of chars received is put in *recvd
984 DWORD NETCON_recv(netconn_t *connection, void *buf, size_t len, int flags,
985 int *recvd /* out */)
989 return ERROR_SUCCESS;
990 if (!connection->useSSL)
992 *recvd = recv(connection->socketFD, buf, len, flags);
993 return *recvd == -1 ? sock_get_error(errno) : ERROR_SUCCESS;
998 if(!connection->ssl_s) {
999 FIXME("not connected\n");
1000 return ERROR_NOT_SUPPORTED;
1002 *recvd = pSSL_read(connection->ssl_s, buf, len);
1004 /* Check if EOF was received */
1005 if(!*recvd && (pSSL_get_error(connection->ssl_s, *recvd)==SSL_ERROR_ZERO_RETURN
1006 || pSSL_get_error(connection->ssl_s, *recvd)==SSL_ERROR_SYSCALL))
1007 return ERROR_SUCCESS;
1009 return *recvd > 0 ? ERROR_SUCCESS : ERROR_INTERNET_CONNECTION_ABORTED;
1011 return ERROR_NOT_SUPPORTED;
1016 /******************************************************************************
1017 * NETCON_query_data_available
1018 * Returns the number of bytes of peeked data plus the number of bytes of
1019 * queued, but unread data.
1021 BOOL NETCON_query_data_available(netconn_t *connection, DWORD *available)
1025 if (!connection->useSSL)
1029 int retval = ioctlsocket(connection->socketFD, FIONREAD, &unread);
1032 TRACE("%d bytes of queued, but unread data\n", unread);
1033 *available += unread;
1039 #ifdef SONAME_LIBSSL
1040 *available = connection->ssl_s ? pSSL_pending(connection->ssl_s) : 0;
1046 BOOL NETCON_is_alive(netconn_t *netconn)
1052 len = recv(netconn->socketFD, &b, 1, MSG_PEEK|MSG_DONTWAIT);
1053 return len == 1 || (len == -1 && errno == EWOULDBLOCK);
1054 #elif defined(__MINGW32__) || defined(_MSC_VER)
1060 if(!ioctlsocket(netconn->socketFD, FIONBIO, &mode))
1063 len = recv(netconn->socketFD, &b, 1, MSG_PEEK);
1066 if(!ioctlsocket(netconn->socketFD, FIONBIO, &mode))
1069 return len == 1 || (len == -1 && errno == WSAEWOULDBLOCK);
1071 FIXME("not supported on this platform\n");
1076 LPCVOID NETCON_GetCert(netconn_t *connection)
1078 #ifdef SONAME_LIBSSL
1082 if (!connection->ssl_s)
1085 cert = pSSL_get_peer_certificate(connection->ssl_s);
1086 r = X509_to_cert_context(cert);
1093 int NETCON_GetCipherStrength(netconn_t *connection)
1095 #ifdef SONAME_LIBSSL
1096 #if defined(OPENSSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER >= 0x0090707f)
1097 const SSL_CIPHER *cipher;
1103 if (!connection->ssl_s)
1105 cipher = pSSL_get_current_cipher(connection->ssl_s);
1108 pSSL_CIPHER_get_bits(cipher, &bits);
1115 DWORD NETCON_set_timeout(netconn_t *connection, BOOL send, DWORD value)
1120 /* value is in milliseconds, convert to struct timeval */
1121 if (value == INFINITE)
1128 tv.tv_sec = value / 1000;
1129 tv.tv_usec = (value % 1000) * 1000;
1131 result = setsockopt(connection->socketFD, SOL_SOCKET,
1132 send ? SO_SNDTIMEO : SO_RCVTIMEO, (void*)&tv,
1136 WARN("setsockopt failed (%s)\n", strerror(errno));
1137 return sock_get_error(errno);
1139 return ERROR_SUCCESS;