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->useSSL = useSSL;
711 netconn->socketFD = -1;
712 netconn->security_flags = security_flags | server->security_flags;
713 netconn->mask_errors = mask_errors;
714 list_init(&netconn->pool_entry);
716 result = create_netconn_socket(server, netconn, timeout);
717 if (result != ERROR_SUCCESS) {
722 server_addref(server);
723 netconn->server = server;
728 void free_netconn(netconn_t *netconn)
730 server_release(netconn->server);
733 if (netconn->ssl_s) {
734 pSSL_shutdown(netconn->ssl_s);
735 pSSL_free(netconn->ssl_s);
739 closesocket(netconn->socketFD);
743 void NETCON_unload(void)
745 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
746 if (OpenSSL_crypto_handle)
749 wine_dlclose(OpenSSL_crypto_handle, NULL, 0);
751 if (OpenSSL_ssl_handle)
755 wine_dlclose(OpenSSL_ssl_handle, NULL, 0);
760 for (i = 0; i < num_ssl_locks; i++)
762 ssl_locks[i].DebugInfo->Spare[0] = 0;
763 DeleteCriticalSection(&ssl_locks[i]);
765 heap_free(ssl_locks);
770 /* translate a unix error code into a winsock one */
771 int sock_get_error( int err )
773 #if !defined(__MINGW32__) && !defined (_MSC_VER)
776 case EINTR: return WSAEINTR;
777 case EBADF: return WSAEBADF;
779 case EACCES: return WSAEACCES;
780 case EFAULT: return WSAEFAULT;
781 case EINVAL: return WSAEINVAL;
782 case EMFILE: return WSAEMFILE;
783 case EWOULDBLOCK: return WSAEWOULDBLOCK;
784 case EINPROGRESS: return WSAEINPROGRESS;
785 case EALREADY: return WSAEALREADY;
786 case ENOTSOCK: return WSAENOTSOCK;
787 case EDESTADDRREQ: return WSAEDESTADDRREQ;
788 case EMSGSIZE: return WSAEMSGSIZE;
789 case EPROTOTYPE: return WSAEPROTOTYPE;
790 case ENOPROTOOPT: return WSAENOPROTOOPT;
791 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
792 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
793 case EOPNOTSUPP: return WSAEOPNOTSUPP;
794 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
795 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
796 case EADDRINUSE: return WSAEADDRINUSE;
797 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
798 case ENETDOWN: return WSAENETDOWN;
799 case ENETUNREACH: return WSAENETUNREACH;
800 case ENETRESET: return WSAENETRESET;
801 case ECONNABORTED: return WSAECONNABORTED;
803 case ECONNRESET: return WSAECONNRESET;
804 case ENOBUFS: return WSAENOBUFS;
805 case EISCONN: return WSAEISCONN;
806 case ENOTCONN: return WSAENOTCONN;
807 case ESHUTDOWN: return WSAESHUTDOWN;
808 case ETOOMANYREFS: return WSAETOOMANYREFS;
809 case ETIMEDOUT: return WSAETIMEDOUT;
810 case ECONNREFUSED: return WSAECONNREFUSED;
811 case ELOOP: return WSAELOOP;
812 case ENAMETOOLONG: return WSAENAMETOOLONG;
813 case EHOSTDOWN: return WSAEHOSTDOWN;
814 case EHOSTUNREACH: return WSAEHOSTUNREACH;
815 case ENOTEMPTY: return WSAENOTEMPTY;
817 case EPROCLIM: return WSAEPROCLIM;
820 case EUSERS: return WSAEUSERS;
823 case EDQUOT: return WSAEDQUOT;
826 case ESTALE: return WSAESTALE;
829 case EREMOTE: return WSAEREMOTE;
831 default: errno=err; perror("sock_set_error"); return WSAEFAULT;
838 static DWORD netcon_secure_connect_setup(netconn_t *connection, long tls_option)
844 ssl_s = pSSL_new(ctx);
847 ERR("SSL_new failed: %s\n",
848 pERR_error_string(pERR_get_error(), 0));
849 return ERROR_OUTOFMEMORY;
852 pSSL_set_options(ssl_s, tls_option);
853 if (!pSSL_set_fd(ssl_s, connection->socketFD))
855 ERR("SSL_set_fd failed: %s\n",
856 pERR_error_string(pERR_get_error(), 0));
857 res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
861 if (!pSSL_set_ex_data(ssl_s, conn_idx, connection))
863 ERR("SSL_set_ex_data failed: %s\n",
864 pERR_error_string(pERR_get_error(), 0));
865 res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
868 if (pSSL_connect(ssl_s) <= 0)
870 res = (DWORD_PTR)pSSL_get_ex_data(ssl_s, error_idx);
872 res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
873 ERR("SSL_connect failed: %d\n", res);
877 connection->ssl_s = ssl_s;
879 bits = NETCON_GetCipherStrength(connection);
881 connection->security_flags |= SECURITY_FLAG_STRENGTH_STRONG;
883 connection->security_flags |= SECURITY_FLAG_STRENGTH_MEDIUM;
885 connection->security_flags |= SECURITY_FLAG_STRENGTH_WEAK;
886 connection->security_flags |= SECURITY_FLAG_SECURE;
888 if(connection->mask_errors)
889 connection->server->security_flags = connection->security_flags;
890 return ERROR_SUCCESS;
895 pSSL_shutdown(ssl_s);
902 /******************************************************************************
903 * NETCON_secure_connect
904 * Initiates a secure connection over an existing plaintext connection.
906 DWORD NETCON_secure_connect(netconn_t *connection)
908 DWORD res = ERROR_NOT_SUPPORTED;
910 /* can't connect if we are already connected */
911 if (connection->ssl_s)
913 ERR("already connected\n");
914 return ERROR_INTERNET_CANNOT_CONNECT;
917 /* connect with given TLS options */
918 res = netcon_secure_connect_setup(connection, get_tls_option());
919 if (res == ERROR_SUCCESS)
922 #ifdef SSL_OP_NO_TLSv1_2
923 /* FIXME: when got version alert and FIN from server */
924 /* fallback to connect without TLSv1.1/TLSv1.2 */
925 if (res == ERROR_INTERNET_SECURITY_CHANNEL_ERROR)
927 closesocket(connection->socketFD);
928 pSSL_CTX_set_options(ctx,SSL_OP_NO_TLSv1_1|SSL_OP_NO_TLSv1_2);
929 res = create_netconn_socket(connection->server, connection, 500);
930 if (res != ERROR_SUCCESS)
932 res = netcon_secure_connect_setup(connection, get_tls_option()|SSL_OP_NO_TLSv1_1|SSL_OP_NO_TLSv1_2);
939 /******************************************************************************
941 * Basically calls 'send()' unless we should use SSL
942 * number of chars send is put in *sent
944 DWORD NETCON_send(netconn_t *connection, const void *msg, size_t len, int flags,
947 if (!connection->useSSL)
949 *sent = send(connection->socketFD, msg, len, flags);
951 return sock_get_error(errno);
952 return ERROR_SUCCESS;
957 if(!connection->ssl_s) {
958 FIXME("not connected\n");
959 return ERROR_NOT_SUPPORTED;
962 FIXME("SSL_write doesn't support any flags (%08x)\n", flags);
963 *sent = pSSL_write(connection->ssl_s, msg, len);
964 if (*sent < 1 && len)
965 return ERROR_INTERNET_CONNECTION_ABORTED;
966 return ERROR_SUCCESS;
968 return ERROR_NOT_SUPPORTED;
973 /******************************************************************************
975 * Basically calls 'recv()' unless we should use SSL
976 * number of chars received is put in *recvd
978 DWORD NETCON_recv(netconn_t *connection, void *buf, size_t len, int flags,
979 int *recvd /* out */)
983 return ERROR_SUCCESS;
984 if (!connection->useSSL)
986 *recvd = recv(connection->socketFD, buf, len, flags);
987 return *recvd == -1 ? sock_get_error(errno) : ERROR_SUCCESS;
992 if(!connection->ssl_s) {
993 FIXME("not connected\n");
994 return ERROR_NOT_SUPPORTED;
996 *recvd = pSSL_read(connection->ssl_s, buf, len);
998 /* Check if EOF was received */
999 if(!*recvd && (pSSL_get_error(connection->ssl_s, *recvd)==SSL_ERROR_ZERO_RETURN
1000 || pSSL_get_error(connection->ssl_s, *recvd)==SSL_ERROR_SYSCALL))
1001 return ERROR_SUCCESS;
1003 return *recvd > 0 ? ERROR_SUCCESS : ERROR_INTERNET_CONNECTION_ABORTED;
1005 return ERROR_NOT_SUPPORTED;
1010 /******************************************************************************
1011 * NETCON_query_data_available
1012 * Returns the number of bytes of peeked data plus the number of bytes of
1013 * queued, but unread data.
1015 BOOL NETCON_query_data_available(netconn_t *connection, DWORD *available)
1019 if (!connection->useSSL)
1023 int retval = ioctlsocket(connection->socketFD, FIONREAD, &unread);
1026 TRACE("%d bytes of queued, but unread data\n", unread);
1027 *available += unread;
1033 #ifdef SONAME_LIBSSL
1034 *available = connection->ssl_s ? pSSL_pending(connection->ssl_s) : 0;
1040 BOOL NETCON_is_alive(netconn_t *netconn)
1046 len = recv(netconn->socketFD, &b, 1, MSG_PEEK|MSG_DONTWAIT);
1047 return len == 1 || (len == -1 && errno == EWOULDBLOCK);
1048 #elif defined(__MINGW32__) || defined(_MSC_VER)
1054 if(!ioctlsocket(netconn->socketFD, FIONBIO, &mode))
1057 len = recv(netconn->socketFD, &b, 1, MSG_PEEK);
1060 if(!ioctlsocket(netconn->socketFD, FIONBIO, &mode))
1063 return len == 1 || (len == -1 && errno == WSAEWOULDBLOCK);
1065 FIXME("not supported on this platform\n");
1070 LPCVOID NETCON_GetCert(netconn_t *connection)
1072 #ifdef SONAME_LIBSSL
1076 if (!connection->ssl_s)
1079 cert = pSSL_get_peer_certificate(connection->ssl_s);
1080 r = X509_to_cert_context(cert);
1087 int NETCON_GetCipherStrength(netconn_t *connection)
1089 #ifdef SONAME_LIBSSL
1090 #if defined(OPENSSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER >= 0x0090707f)
1091 const SSL_CIPHER *cipher;
1097 if (!connection->ssl_s)
1099 cipher = pSSL_get_current_cipher(connection->ssl_s);
1102 pSSL_CIPHER_get_bits(cipher, &bits);
1109 DWORD NETCON_set_timeout(netconn_t *connection, BOOL send, DWORD value)
1114 /* value is in milliseconds, convert to struct timeval */
1115 if (value == INFINITE)
1122 tv.tv_sec = value / 1000;
1123 tv.tv_usec = (value % 1000) * 1000;
1125 result = setsockopt(connection->socketFD, SOL_SOCKET,
1126 send ? SO_SNDTIMEO : SO_RCVTIMEO, (void*)&tv,
1130 WARN("setsockopt failed (%s)\n", strerror(errno));
1131 return sock_get_error(errno);
1133 return ERROR_SUCCESS;