user32: Define a global list of parameter registry keys and store an index in the...
[wine] / dlls / wininet / netconnection.c
1 /*
2  * Wininet - networking layer. Uses unix sockets or OpenSSL.
3  *
4  * Copyright 2002 TransGaming Technologies Inc.
5  *
6  * David Hammerton
7  *
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.
12  *
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.
17  *
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
21  */
22
23 #include "config.h"
24 #include "wine/port.h"
25
26 #define NONAMELESSUNION
27
28 #if defined(__MINGW32__) || defined (_MSC_VER)
29 #include <ws2tcpip.h>
30 #endif
31
32 #include <sys/types.h>
33 #ifdef HAVE_POLL_H
34 #include <poll.h>
35 #endif
36 #ifdef HAVE_SYS_POLL_H
37 # include <sys/poll.h>
38 #endif
39 #ifdef HAVE_SYS_TIME_H
40 # include <sys/time.h>
41 #endif
42 #ifdef HAVE_SYS_SOCKET_H
43 # include <sys/socket.h>
44 #endif
45 #ifdef HAVE_SYS_FILIO_H
46 # include <sys/filio.h>
47 #endif
48 #ifdef HAVE_UNISTD_H
49 # include <unistd.h>
50 #endif
51 #ifdef HAVE_SYS_IOCTL_H
52 # include <sys/ioctl.h>
53 #endif
54 #include <time.h>
55 #ifdef HAVE_NETDB_H
56 # include <netdb.h>
57 #endif
58 #ifdef HAVE_NETINET_IN_H
59 # include <netinet/in.h>
60 #endif
61 #ifdef HAVE_NETINET_TCP_H
62 # include <netinet/tcp.h>
63 #endif
64 #ifdef HAVE_OPENSSL_SSL_H
65 # include <openssl/ssl.h>
66 # include <openssl/opensslv.h>
67 #undef FAR
68 #undef DSA
69 #endif
70
71 #include <stdarg.h>
72 #include <stdlib.h>
73 #include <string.h>
74 #include <stdio.h>
75 #include <errno.h>
76 #include <assert.h>
77
78 #include "wine/library.h"
79 #include "windef.h"
80 #include "winbase.h"
81 #include "wininet.h"
82 #include "winerror.h"
83
84 #include "wine/debug.h"
85 #include "internet.h"
86
87 /* To avoid conflicts with the Unix socket headers. we only need it for
88  * the error codes anyway. */
89 #define USE_WS_PREFIX
90 #include "winsock2.h"
91
92 #define RESPONSE_TIMEOUT        30            /* FROM internet.c */
93
94
95 WINE_DEFAULT_DEBUG_CHANNEL(wininet);
96
97 /* FIXME!!!!!!
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
101  */
102
103 #ifdef SONAME_LIBSSL
104
105 #include <openssl/err.h>
106
107 static void *OpenSSL_ssl_handle;
108 static void *OpenSSL_crypto_handle;
109
110 #if defined(OPENSSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER > 0x10000000)
111 static const SSL_METHOD *meth;
112 #else
113 static SSL_METHOD *meth;
114 #endif
115 static SSL_CTX *ctx;
116 static int error_idx;
117 static int conn_idx;
118
119 #define MAKE_FUNCPTR(f) static typeof(f) * p##f
120
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);
149
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);
163 #undef MAKE_FUNCPTR
164
165 static CRITICAL_SECTION *ssl_locks;
166 static unsigned int num_ssl_locks;
167
168 static unsigned long ssl_thread_id(void)
169 {
170     return GetCurrentThreadId();
171 }
172
173 static void ssl_lock_callback(int mode, int type, const char *file, int line)
174 {
175     if (mode & CRYPTO_LOCK)
176         EnterCriticalSection(&ssl_locks[type]);
177     else
178         LeaveCriticalSection(&ssl_locks[type]);
179 }
180
181 static PCCERT_CONTEXT X509_to_cert_context(X509 *cert)
182 {
183     unsigned char* buffer,*p;
184     INT len;
185     BOOL malloced = FALSE;
186     PCCERT_CONTEXT ret;
187
188     p = NULL;
189     len = pi2d_X509(cert,&p);
190     /*
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.
193      *
194      * see the i2d_X509 man page for more details.
195      */
196     if (!p)
197     {
198         buffer = heap_alloc(len);
199         p = buffer;
200         len = pi2d_X509(cert,&p);
201     }
202     else
203     {
204         buffer = p;
205         malloced = TRUE;
206     }
207
208     ret = CertCreateCertificateContext(X509_ASN_ENCODING,buffer,len);
209
210     if (malloced)
211         free(buffer);
212     else
213         heap_free(buffer);
214
215     return ret;
216 }
217
218 static DWORD netconn_verify_cert(netconn_t *conn, PCCERT_CONTEXT cert, HCERTSTORE store)
219 {
220     BOOL ret;
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;
226
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;
235
236     TRACE("verifying %s\n", debugstr_w(conn->server->name));
237
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;
242
243     if (!(ret = CertGetCertificateChain(NULL, cert, NULL, store, &chainPara, chainFlags, NULL, &chain))) {
244         TRACE("failed\n");
245         return GetLastError();
246     }
247
248     errors = chain->TrustStatus.dwErrorStatus;
249
250     do {
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))
258                 break;
259         }
260
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)
266                 break;
267             WARN("unknown error flags\n");
268         }
269
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)
275                     break;
276                 conn->security_flags |= _SECURITY_FLAG_CERT_INVALID_DATE;
277             }
278             errors &= ~CERT_TRUST_IS_NOT_TIME_VALID;
279         }
280
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)
286                     break;
287                 conn->security_flags |= _SECURITY_FLAG_CERT_INVALID_CA;
288             }
289             errors &= ~CERT_TRUST_IS_UNTRUSTED_ROOT;
290         }
291
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)
297                     break;
298                 conn->security_flags |= _SECURITY_FLAG_CERT_INVALID_CA;
299             }
300             errors &= ~CERT_TRUST_IS_PARTIAL_CHAIN;
301         }
302
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)
308                     break;
309                 conn->security_flags |= _SECURITY_FLAG_CERT_REV_FAILED;
310             }
311             errors &= ~(CERT_TRUST_IS_OFFLINE_REVOCATION | CERT_TRUST_REVOCATION_STATUS_UNKNOWN);
312         }
313
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)
319                     break;
320                 WARN("TRUST_IS_OFFLINE_REVOCATION | CERT_TRUST_REVOCATION_STATUS_UNKNOWN, unknown error flags\n");
321             }
322             errors &= ~CERT_TRUST_IS_REVOKED;
323         }
324
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)
330                     break;
331                 WARN("CERT_TRUST_IS_NOT_VALID_FOR_USAGE, unknown error flags\n");
332             }
333             errors &= ~CERT_TRUST_IS_NOT_VALID_FOR_USAGE;
334         }
335
336         if(err == ERROR_INTERNET_SEC_CERT_REV_FAILED) {
337             assert(conn->security_flags & SECURITY_FLAG_IGNORE_REVOCATION);
338             err = ERROR_SUCCESS;
339         }
340     }while(0);
341
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;
347
348         /* Clear chain->TrustStatus.dwErrorStatus so
349          * CertVerifyCertificateChainPolicy will verify additional checks
350          * rather than stopping with an existing, ignored error.
351          */
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.
365          */
366         if(ret) {
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;
377             }
378         }else {
379             err = GetLastError();
380         }
381     }
382
383     if(err) {
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;
389         }
390         if(conn->mask_errors)
391             conn->server->security_flags |= conn->security_flags & _SECURITY_ERROR_FLAGS_MASK;
392         return err;
393     }
394
395     /* FIXME: Reuse cached chain */
396     if(conn->server->cert_chain)
397         CertFreeCertificateChain(chain);
398     else
399         conn->server->cert_chain = chain;
400     return ERROR_SUCCESS;
401 }
402
403 static int netconn_secure_verify(int preverify_ok, X509_STORE_CTX *ctx)
404 {
405     SSL *ssl;
406     BOOL ret = FALSE;
407     HCERTSTORE store = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0,
408         CERT_STORE_CREATE_NEW_FLAG, NULL);
409     netconn_t *conn;
410
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);
414     if (store)
415     {
416         X509 *cert;
417         int i;
418         PCCERT_CONTEXT endCert = NULL;
419         struct stack_st *chain = (struct stack_st *)pX509_STORE_CTX_get_chain( ctx );
420
421         ret = TRUE;
422         for (i = 0; ret && i < psk_num(chain); i++)
423         {
424             PCCERT_CONTEXT context;
425
426             cert = (X509 *)psk_value(chain, i);
427             if ((context = X509_to_cert_context(cert)))
428             {
429                 ret = CertAddCertificateContextToStore(store, context,
430                         CERT_STORE_ADD_ALWAYS, i ? NULL : &endCert);
431                 CertFreeCertificateContext(context);
432             }
433         }
434         if (!endCert) ret = FALSE;
435         if (ret)
436         {
437             DWORD_PTR err = netconn_verify_cert(conn, endCert, store);
438
439             if (err)
440             {
441                 pSSL_set_ex_data(ssl, error_idx, (void *)err);
442                 ret = FALSE;
443             }
444         }
445         CertFreeCertificateContext(endCert);
446         CertCloseStore(store, 0);
447     }
448     return ret;
449 }
450
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;
456     LONG res;
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};
467
468     res = RegOpenKeyExW(HKEY_LOCAL_MACHINE,
469           Schannel_Prot,
470           0, KEY_READ, &hkey);
471     if (res != ERROR_SUCCESS) { /* enabled TLSv1.1/1.2 when no registry entry */
472         return tls_option;
473     }
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;
479         }
480         RegCloseKey(tls12_client);
481     }
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;
487         }
488         RegCloseKey(tls11_client);
489     }
490     RegCloseKey(hkey);
491 #endif
492     return tls_option;
493 }
494 #endif /* SONAME_LIBSSL */
495
496 static CRITICAL_SECTION init_ssl_cs;
497 static CRITICAL_SECTION_DEBUG init_ssl_cs_debug =
498 {
499     0, 0, &init_ssl_cs,
500     { &init_ssl_cs_debug.ProcessLocksList,
501       &init_ssl_cs_debug.ProcessLocksList },
502     0, 0, { (DWORD_PTR)(__FILE__ ": init_ssl_cs") }
503 };
504 static CRITICAL_SECTION init_ssl_cs = { &init_ssl_cs_debug, -1, 0, 0, 0, 0 };
505
506 static DWORD init_openssl(void)
507 {
508 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
509     int i;
510
511     if(OpenSSL_ssl_handle)
512         return ERROR_SUCCESS;
513
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;
518     }
519
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;
524     }
525
526     /* mmm nice ugly macroness */
527 #define DYNSSL(x) \
528     p##x = wine_dlsym(OpenSSL_ssl_handle, #x, NULL, 0); \
529     if (!p##x) { \
530         ERR("failed to load symbol %s\n", #x); \
531         return ERROR_INTERNET_SECURITY_CHANNEL_ERROR; \
532     }
533
534     DYNSSL(SSL_library_init);
535     DYNSSL(SSL_load_error_strings);
536     DYNSSL(SSLv23_method);
537     DYNSSL(SSL_CTX_free);
538     DYNSSL(SSL_CTX_new);
539     DYNSSL(SSL_CTX_ctrl);
540     DYNSSL(SSL_new);
541     DYNSSL(SSL_free);
542     DYNSSL(SSL_ctrl);
543     DYNSSL(SSL_set_fd);
544     DYNSSL(SSL_connect);
545     DYNSSL(SSL_shutdown);
546     DYNSSL(SSL_write);
547     DYNSSL(SSL_read);
548     DYNSSL(SSL_pending);
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);
561 #undef DYNSSL
562
563 #define DYNCRYPTO(x) \
564     p##x = wine_dlsym(OpenSSL_crypto_handle, #x, NULL, 0); \
565     if (!p##x) { \
566         ERR("failed to load symbol %s\n", #x); \
567         return ERROR_INTERNET_SECURITY_CHANNEL_ERROR; \
568     }
569
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);
579     DYNCRYPTO(i2d_X509);
580     DYNCRYPTO(sk_num);
581     DYNCRYPTO(sk_value);
582 #undef DYNCRYPTO
583
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)
588
589     pSSL_library_init();
590     pSSL_load_error_strings();
591     pBIO_new_fp(stderr, BIO_NOCLOSE); /* FIXME: should use winedebug stuff */
592
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;
600     }
601
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;
606     }
607
608     conn_idx = pSSL_get_ex_new_index(0, (void *)"netconn index", NULL, NULL, NULL);
609     if(conn_idx == -1) {
610         ERR("SSL_get_ex_new_index failed; %s\n", pERR_error_string(pERR_get_error(), 0));
611         return ERROR_OUTOFMEMORY;
612     }
613
614     pSSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, netconn_secure_verify);
615
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));
619     if(!ssl_locks)
620         return ERROR_OUTOFMEMORY;
621
622     for(i = 0; i < num_ssl_locks; i++)
623     {
624         InitializeCriticalSection(&ssl_locks[i]);
625         ssl_locks[i].DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": ssl_locks");
626     }
627     pCRYPTO_set_locking_callback(ssl_lock_callback);
628
629     return ERROR_SUCCESS;
630 #else
631     FIXME("can't use SSL, not compiled in.\n");
632     return ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
633 #endif
634 }
635
636 static DWORD create_netconn_socket(server_t *server, netconn_t *netconn, DWORD timeout)
637 {
638     int result, flag;
639
640     assert(server->addr_len);
641     result = netconn->socketFD = socket(server->addr.ss_family, SOCK_STREAM, 0);
642     if(result != -1) {
643         flag = 1;
644         ioctlsocket(netconn->socketFD, FIONBIO, &flag);
645         result = connect(netconn->socketFD, (struct sockaddr*)&server->addr, server->addr_len);
646         if(result == -1)
647         {
648             if (sock_get_error(errno) == WSAEINPROGRESS) {
649                 struct pollfd pfd;
650                 int res;
651
652                 pfd.fd = netconn->socketFD;
653                 pfd.events = POLLOUT;
654                 res = poll(&pfd, 1, timeout);
655                 if (!res)
656                 {
657                     closesocket(netconn->socketFD);
658                     return ERROR_INTERNET_CANNOT_CONNECT;
659                 }
660                 else if (res > 0)
661                 {
662                     int err;
663                     socklen_t len = sizeof(err);
664                     if (!getsockopt(netconn->socketFD, SOL_SOCKET, SO_ERROR, &err, &len) && !err)
665                         result = 0;
666                 }
667             }
668         }
669         if(result == -1)
670             closesocket(netconn->socketFD);
671         else {
672             flag = 0;
673             ioctlsocket(netconn->socketFD, FIONBIO, &flag);
674         }
675     }
676     if(result == -1)
677         return sock_get_error(errno);
678
679 #ifdef TCP_NODELAY
680     flag = 1;
681     result = setsockopt(netconn->socketFD, IPPROTO_TCP, TCP_NODELAY, (void*)&flag, sizeof(flag));
682     if(result < 0)
683         WARN("setsockopt(TCP_NODELAY) failed\n");
684 #endif
685
686     return ERROR_SUCCESS;
687 }
688
689 DWORD create_netconn(BOOL useSSL, server_t *server, DWORD security_flags, BOOL mask_errors, DWORD timeout, netconn_t **ret)
690 {
691     netconn_t *netconn;
692     int result;
693
694     if(useSSL) {
695         DWORD res;
696
697         TRACE("using SSL connection\n");
698
699         EnterCriticalSection(&init_ssl_cs);
700         res = init_openssl();
701         LeaveCriticalSection(&init_ssl_cs);
702         if(res != ERROR_SUCCESS)
703             return res;
704     }
705
706     netconn = heap_alloc_zero(sizeof(*netconn));
707     if(!netconn)
708         return ERROR_OUTOFMEMORY;
709
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);
715
716     result = create_netconn_socket(server, netconn, timeout);
717     if (result != ERROR_SUCCESS) {
718         heap_free(netconn);
719         return result;
720     }
721
722     server_addref(server);
723     netconn->server = server;
724     *ret = netconn;
725     return result;
726 }
727
728 void free_netconn(netconn_t *netconn)
729 {
730     server_release(netconn->server);
731
732 #ifdef SONAME_LIBSSL
733     if (netconn->ssl_s) {
734         pSSL_shutdown(netconn->ssl_s);
735         pSSL_free(netconn->ssl_s);
736     }
737 #endif
738
739     closesocket(netconn->socketFD);
740     heap_free(netconn);
741 }
742
743 void NETCON_unload(void)
744 {
745 #if defined(SONAME_LIBSSL) && defined(SONAME_LIBCRYPTO)
746     if (OpenSSL_crypto_handle)
747     {
748         pERR_free_strings();
749         wine_dlclose(OpenSSL_crypto_handle, NULL, 0);
750     }
751     if (OpenSSL_ssl_handle)
752     {
753         if (ctx)
754             pSSL_CTX_free(ctx);
755         wine_dlclose(OpenSSL_ssl_handle, NULL, 0);
756     }
757     if (ssl_locks)
758     {
759         int i;
760         for (i = 0; i < num_ssl_locks; i++)
761         {
762             ssl_locks[i].DebugInfo->Spare[0] = 0;
763             DeleteCriticalSection(&ssl_locks[i]);
764         }
765         heap_free(ssl_locks);
766     }
767 #endif
768 }
769
770 /* translate a unix error code into a winsock one */
771 int sock_get_error( int err )
772 {
773 #if !defined(__MINGW32__) && !defined (_MSC_VER)
774     switch (err)
775     {
776         case EINTR:             return WSAEINTR;
777         case EBADF:             return WSAEBADF;
778         case EPERM:
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;
802         case EPIPE:
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;
816 #ifdef EPROCLIM
817         case EPROCLIM:          return WSAEPROCLIM;
818 #endif
819 #ifdef EUSERS
820         case EUSERS:            return WSAEUSERS;
821 #endif
822 #ifdef EDQUOT
823         case EDQUOT:            return WSAEDQUOT;
824 #endif
825 #ifdef ESTALE
826         case ESTALE:            return WSAESTALE;
827 #endif
828 #ifdef EREMOTE
829         case EREMOTE:           return WSAEREMOTE;
830 #endif
831     default: errno=err; perror("sock_set_error"); return WSAEFAULT;
832     }
833 #endif
834     return err;
835 }
836
837 #ifdef SONAME_LIBSSL
838 static DWORD netcon_secure_connect_setup(netconn_t *connection, long tls_option)
839 {
840     void *ssl_s;
841     DWORD res;
842     int bits;
843
844     ssl_s = pSSL_new(ctx);
845     if (!ssl_s)
846     {
847         ERR("SSL_new failed: %s\n",
848             pERR_error_string(pERR_get_error(), 0));
849         return ERROR_OUTOFMEMORY;
850     }
851
852     pSSL_set_options(ssl_s, tls_option);
853     if (!pSSL_set_fd(ssl_s, connection->socketFD))
854     {
855         ERR("SSL_set_fd failed: %s\n",
856             pERR_error_string(pERR_get_error(), 0));
857         res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
858         goto fail;
859     }
860
861     if (!pSSL_set_ex_data(ssl_s, conn_idx, connection))
862     {
863         ERR("SSL_set_ex_data failed: %s\n",
864             pERR_error_string(pERR_get_error(), 0));
865         res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
866         goto fail;
867     }
868     if (pSSL_connect(ssl_s) <= 0)
869     {
870         res = (DWORD_PTR)pSSL_get_ex_data(ssl_s, error_idx);
871         if (!res)
872             res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR;
873         ERR("SSL_connect failed: %d\n", res);
874         goto fail;
875     }
876
877     connection->ssl_s = ssl_s;
878
879     bits = NETCON_GetCipherStrength(connection);
880     if (bits >= 128)
881         connection->security_flags |= SECURITY_FLAG_STRENGTH_STRONG;
882     else if (bits >= 56)
883         connection->security_flags |= SECURITY_FLAG_STRENGTH_MEDIUM;
884     else
885         connection->security_flags |= SECURITY_FLAG_STRENGTH_WEAK;
886     connection->security_flags |= SECURITY_FLAG_SECURE;
887
888     if(connection->mask_errors)
889         connection->server->security_flags = connection->security_flags;
890     return ERROR_SUCCESS;
891
892 fail:
893     if (ssl_s)
894     {
895         pSSL_shutdown(ssl_s);
896         pSSL_free(ssl_s);
897     }
898     return res;
899 }
900 #endif
901
902 /******************************************************************************
903  * NETCON_secure_connect
904  * Initiates a secure connection over an existing plaintext connection.
905  */
906 DWORD NETCON_secure_connect(netconn_t *connection)
907 {
908     DWORD res = ERROR_NOT_SUPPORTED;
909 #ifdef SONAME_LIBSSL
910     /* can't connect if we are already connected */
911     if (connection->ssl_s)
912     {
913         ERR("already connected\n");
914         return ERROR_INTERNET_CANNOT_CONNECT;
915     }
916
917     /* connect with given TLS options */
918     res = netcon_secure_connect_setup(connection, get_tls_option());
919     if (res == ERROR_SUCCESS)
920         return res;
921
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)
926     {
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)
931             return res;
932         res = netcon_secure_connect_setup(connection, get_tls_option()|SSL_OP_NO_TLSv1_1|SSL_OP_NO_TLSv1_2);
933     }
934 #endif
935 #endif
936     return res;
937 }
938
939 /******************************************************************************
940  * NETCON_send
941  * Basically calls 'send()' unless we should use SSL
942  * number of chars send is put in *sent
943  */
944 DWORD NETCON_send(netconn_t *connection, const void *msg, size_t len, int flags,
945                 int *sent /* out */)
946 {
947     if (!connection->useSSL)
948     {
949         *sent = send(connection->socketFD, msg, len, flags);
950         if (*sent == -1)
951             return sock_get_error(errno);
952         return ERROR_SUCCESS;
953     }
954     else
955     {
956 #ifdef SONAME_LIBSSL
957         if(!connection->ssl_s) {
958             FIXME("not connected\n");
959             return ERROR_NOT_SUPPORTED;
960         }
961         if (flags)
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;
967 #else
968         return ERROR_NOT_SUPPORTED;
969 #endif
970     }
971 }
972
973 /******************************************************************************
974  * NETCON_recv
975  * Basically calls 'recv()' unless we should use SSL
976  * number of chars received is put in *recvd
977  */
978 DWORD NETCON_recv(netconn_t *connection, void *buf, size_t len, int flags,
979                 int *recvd /* out */)
980 {
981     *recvd = 0;
982     if (!len)
983         return ERROR_SUCCESS;
984     if (!connection->useSSL)
985     {
986         *recvd = recv(connection->socketFD, buf, len, flags);
987         return *recvd == -1 ? sock_get_error(errno) :  ERROR_SUCCESS;
988     }
989     else
990     {
991 #ifdef SONAME_LIBSSL
992         if(!connection->ssl_s) {
993             FIXME("not connected\n");
994             return ERROR_NOT_SUPPORTED;
995         }
996         *recvd = pSSL_read(connection->ssl_s, buf, len);
997
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;
1002
1003         return *recvd > 0 ? ERROR_SUCCESS : ERROR_INTERNET_CONNECTION_ABORTED;
1004 #else
1005         return ERROR_NOT_SUPPORTED;
1006 #endif
1007     }
1008 }
1009
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.
1014  */
1015 BOOL NETCON_query_data_available(netconn_t *connection, DWORD *available)
1016 {
1017     *available = 0;
1018
1019     if (!connection->useSSL)
1020     {
1021 #ifdef FIONREAD
1022         int unread;
1023         int retval = ioctlsocket(connection->socketFD, FIONREAD, &unread);
1024         if (!retval)
1025         {
1026             TRACE("%d bytes of queued, but unread data\n", unread);
1027             *available += unread;
1028         }
1029 #endif
1030     }
1031     else
1032     {
1033 #ifdef SONAME_LIBSSL
1034         *available = connection->ssl_s ? pSSL_pending(connection->ssl_s) : 0;
1035 #endif
1036     }
1037     return TRUE;
1038 }
1039
1040 BOOL NETCON_is_alive(netconn_t *netconn)
1041 {
1042 #ifdef MSG_DONTWAIT
1043     ssize_t len;
1044     BYTE b;
1045
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)
1049     ULONG mode;
1050     int len;
1051     char b;
1052
1053     mode = 1;
1054     if(!ioctlsocket(netconn->socketFD, FIONBIO, &mode))
1055         return FALSE;
1056
1057     len = recv(netconn->socketFD, &b, 1, MSG_PEEK);
1058
1059     mode = 0;
1060     if(!ioctlsocket(netconn->socketFD, FIONBIO, &mode))
1061         return FALSE;
1062
1063     return len == 1 || (len == -1 && errno == WSAEWOULDBLOCK);
1064 #else
1065     FIXME("not supported on this platform\n");
1066     return TRUE;
1067 #endif
1068 }
1069
1070 LPCVOID NETCON_GetCert(netconn_t *connection)
1071 {
1072 #ifdef SONAME_LIBSSL
1073     X509* cert;
1074     LPCVOID r = NULL;
1075
1076     if (!connection->ssl_s)
1077         return NULL;
1078
1079     cert = pSSL_get_peer_certificate(connection->ssl_s);
1080     r = X509_to_cert_context(cert);
1081     return r;
1082 #else
1083     return NULL;
1084 #endif
1085 }
1086
1087 int NETCON_GetCipherStrength(netconn_t *connection)
1088 {
1089 #ifdef SONAME_LIBSSL
1090 #if defined(OPENSSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER >= 0x0090707f)
1091     const SSL_CIPHER *cipher;
1092 #else
1093     SSL_CIPHER *cipher;
1094 #endif
1095     int bits = 0;
1096
1097     if (!connection->ssl_s)
1098         return 0;
1099     cipher = pSSL_get_current_cipher(connection->ssl_s);
1100     if (!cipher)
1101         return 0;
1102     pSSL_CIPHER_get_bits(cipher, &bits);
1103     return bits;
1104 #else
1105     return 0;
1106 #endif
1107 }
1108
1109 DWORD NETCON_set_timeout(netconn_t *connection, BOOL send, DWORD value)
1110 {
1111     int result;
1112     struct timeval tv;
1113
1114     /* value is in milliseconds, convert to struct timeval */
1115     if (value == INFINITE)
1116     {
1117         tv.tv_sec = 0;
1118         tv.tv_usec = 0;
1119     }
1120     else
1121     {
1122         tv.tv_sec = value / 1000;
1123         tv.tv_usec = (value % 1000) * 1000;
1124     }
1125     result = setsockopt(connection->socketFD, SOL_SOCKET,
1126                         send ? SO_SNDTIMEO : SO_RCVTIMEO, (void*)&tv,
1127                         sizeof(tv));
1128     if (result == -1)
1129     {
1130         WARN("setsockopt failed (%s)\n", strerror(errno));
1131         return sock_get_error(errno);
1132     }
1133     return ERROR_SUCCESS;
1134 }