ssl split out common server and client ssl sources
[platform/upstream/libwebsockets.git] / lib / ssl-client.c
1 /*
2  * libwebsockets - small server side websockets and web server implementation
3  *
4  * Copyright (C) 2010-2014 Andy Green <andy@warmcat.com>
5  *
6  *  This library is free software; you can redistribute it and/or
7  *  modify it under the terms of the GNU Lesser General Public
8  *  License as published by the Free Software Foundation:
9  *  version 2.1 of the License.
10  *
11  *  This library is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  *  Lesser General Public License for more details.
15  *
16  *  You should have received a copy of the GNU Lesser General Public
17  *  License along with this library; if not, write to the Free Software
18  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19  *  MA  02110-1301  USA
20  */
21
22 #include "private-libwebsockets.h"
23 #ifndef USE_WOLFSSL
24  #include <openssl/err.h>
25 #endif
26
27 #ifdef LWS_HAVE_OPENSSL_ECDH_H
28 #include <openssl/ecdh.h>
29 #endif
30
31 extern int openssl_websocket_private_data_index,
32     openssl_SSL_CTX_private_data_index;
33
34 extern void
35 lws_ssl_bind_passphrase(SSL_CTX *ssl_ctx, struct lws_context_creation_info *info);
36
37 int
38 lws_ssl_client_bio_create(struct lws *wsi)
39 {
40         struct lws_context *context = wsi->context;
41 #if defined(CYASSL_SNI_HOST_NAME) || defined(WOLFSSL_SNI_HOST_NAME) || defined(SSL_CTRL_SET_TLSEXT_HOSTNAME)
42         const char *hostname = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_HOST);
43 #endif
44
45         wsi->ssl = SSL_new(wsi->vhost->ssl_client_ctx);
46 #ifndef USE_WOLFSSL
47         SSL_set_mode(wsi->ssl,  SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
48 #endif
49         /*
50          * use server name indication (SNI), if supported,
51          * when establishing connection
52          */
53 #ifdef USE_WOLFSSL
54 #ifdef USE_OLD_CYASSL
55 #ifdef CYASSL_SNI_HOST_NAME
56         CyaSSL_UseSNI(wsi->ssl, CYASSL_SNI_HOST_NAME, hostname, strlen(hostname));
57 #endif
58 #else
59 #ifdef WOLFSSL_SNI_HOST_NAME
60         wolfSSL_UseSNI(wsi->ssl, WOLFSSL_SNI_HOST_NAME, hostname, strlen(hostname));
61 #endif
62 #endif
63 #else
64 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
65         SSL_set_tlsext_host_name(wsi->ssl, hostname);
66 #endif
67 #endif
68
69 #ifdef USE_WOLFSSL
70         /*
71          * wolfSSL/CyaSSL does certificate verification differently
72          * from OpenSSL.
73          * If we should ignore the certificate, we need to set
74          * this before SSL_new and SSL_connect is called.
75          * Otherwise the connect will simply fail with error code -155
76          */
77 #ifdef USE_OLD_CYASSL
78         if (wsi->use_ssl == 2)
79                 CyaSSL_set_verify(wsi->ssl, SSL_VERIFY_NONE, NULL);
80 #else
81         if (wsi->use_ssl == 2)
82                 wolfSSL_set_verify(wsi->ssl, SSL_VERIFY_NONE, NULL);
83 #endif
84 #endif /* USE_WOLFSSL */
85
86         wsi->client_bio = BIO_new_socket(wsi->sock, BIO_NOCLOSE);
87         SSL_set_bio(wsi->ssl, wsi->client_bio, wsi->client_bio);
88
89 #ifdef USE_WOLFSSL
90 #ifdef USE_OLD_CYASSL
91         CyaSSL_set_using_nonblock(wsi->ssl, 1);
92 #else
93         wolfSSL_set_using_nonblock(wsi->ssl, 1);
94 #endif
95 #else
96         BIO_set_nbio(wsi->client_bio, 1); /* nonblocking */
97 #endif
98
99         SSL_set_ex_data(wsi->ssl, openssl_websocket_private_data_index,
100                         context);
101
102         return 0;
103 }
104
105 int
106 lws_ssl_client_connect1(struct lws *wsi)
107 {
108         struct lws_context *context = wsi->context;
109         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
110         char *p = (char *)&pt->serv_buf[0];
111         char *sb = p;
112         int n;
113
114         lws_latency_pre(context, wsi);
115         n = SSL_connect(wsi->ssl);
116         lws_latency(context, wsi,
117           "SSL_connect LWSCM_WSCL_ISSUE_HANDSHAKE", n, n > 0);
118
119         if (n < 0) {
120                 n = SSL_get_error(wsi->ssl, n);
121
122                 if (n == SSL_ERROR_WANT_READ)
123                         goto some_wait;
124
125                 if (n == SSL_ERROR_WANT_WRITE) {
126                         /*
127                          * wants us to retry connect due to
128                          * state of the underlying ssl layer...
129                          * but since it may be stalled on
130                          * blocked write, no incoming data may
131                          * arrive to trigger the retry.
132                          * Force (possibly many times if the SSL
133                          * state persists in returning the
134                          * condition code, but other sockets
135                          * are getting serviced inbetweentimes)
136                          * us to get called back when writable.
137                          */
138                         lwsl_info("%s: WANT_WRITE... retrying\n", __func__);
139                         lws_callback_on_writable(wsi);
140 some_wait:
141                         wsi->mode = LWSCM_WSCL_WAITING_SSL;
142
143                         return 0; /* no error */
144                 }
145                 n = -1;
146         }
147
148         if (n <= 0) {
149                 /*
150                  * retry if new data comes until we
151                  * run into the connection timeout or win
152                  */
153                 n = ERR_get_error();
154                 if (n != SSL_ERROR_NONE) {
155                         lwsl_err("SSL connect error %lu: %s\n",
156                                 n, ERR_error_string(n, sb));
157                         return 0;
158                 }
159         }
160
161         return 1;
162 }
163
164 int
165 lws_ssl_client_connect2(struct lws *wsi)
166 {
167         struct lws_context *context = wsi->context;
168         struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
169         char *p = (char *)&pt->serv_buf[0];
170         char *sb = p;
171         int n;
172
173         if (wsi->mode == LWSCM_WSCL_WAITING_SSL) {
174                 lws_latency_pre(context, wsi);
175                 n = SSL_connect(wsi->ssl);
176                 lws_latency(context, wsi,
177                             "SSL_connect LWSCM_WSCL_WAITING_SSL", n, n > 0);
178
179                 if (n < 0) {
180                         n = SSL_get_error(wsi->ssl, n);
181
182                         if (n == SSL_ERROR_WANT_READ) {
183                                 wsi->mode = LWSCM_WSCL_WAITING_SSL;
184
185                                 return 0; /* no error */
186                         }
187
188                         if (n == SSL_ERROR_WANT_WRITE) {
189                                 /*
190                                  * wants us to retry connect due to
191                                  * state of the underlying ssl layer...
192                                  * but since it may be stalled on
193                                  * blocked write, no incoming data may
194                                  * arrive to trigger the retry.
195                                  * Force (possibly many times if the SSL
196                                  * state persists in returning the
197                                  * condition code, but other sockets
198                                  * are getting serviced inbetweentimes)
199                                  * us to get called back when writable.
200                                  */
201                                 lwsl_info("SSL_connect WANT_WRITE... retrying\n");
202                                 lws_callback_on_writable(wsi);
203
204                                 wsi->mode = LWSCM_WSCL_WAITING_SSL;
205
206                                 return 0; /* no error */
207                         }
208                         n = -1;
209                 }
210
211                 if (n <= 0) {
212                         /*
213                          * retry if new data comes until we
214                          * run into the connection timeout or win
215                          */
216                         n = ERR_get_error();
217                         if (n != SSL_ERROR_NONE) {
218                                 lwsl_err("SSL connect error %lu: %s\n",
219                                          n, ERR_error_string(n, sb));
220                                 return 0;
221                         }
222                 }
223         }
224
225 #ifndef USE_WOLFSSL
226         /*
227          * See comment above about wolfSSL certificate
228          * verification
229          */
230         lws_latency_pre(context, wsi);
231         n = SSL_get_verify_result(wsi->ssl);
232         lws_latency(context, wsi,
233                 "SSL_get_verify_result LWS_CONNMODE..HANDSHAKE",
234                                                       n, n > 0);
235
236         if (n != X509_V_OK) {
237                 if ((n == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT ||
238                      n == X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN) && wsi->use_ssl == 2) {
239                         lwsl_notice("accepting self-signed certificate\n");
240                 } else {
241                         lwsl_err("server's cert didn't look good, X509_V_ERR = %d: %s\n",
242                                  n, ERR_error_string(n, sb));
243                         lws_close_free_wsi(wsi,
244                                 LWS_CLOSE_STATUS_NOSTATUS);
245                         return 0;
246                 }
247         }
248 #endif /* USE_WOLFSSL */
249
250         return 1;
251 }
252
253
254 int lws_context_init_client_ssl(struct lws_context_creation_info *info,
255                                 struct lws_vhost *vhost)
256 {
257         int error;
258         int n;
259         SSL_METHOD *method;
260         struct lws wsi;
261
262         if (!lws_check_opt(info->options, LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT))
263                 return 0;
264
265         if (info->provided_client_ssl_ctx) {
266                 /* use the provided OpenSSL context if given one */
267                 vhost->ssl_client_ctx = info->provided_client_ssl_ctx;
268                 /* nothing for lib to delete */
269                 vhost->user_supplied_ssl_ctx = 1;
270                 return 0;
271         }
272
273         if (info->port != CONTEXT_PORT_NO_LISTEN)
274                 return 0;
275
276         /* basic openssl init */
277
278         SSL_library_init();
279
280         OpenSSL_add_all_algorithms();
281         SSL_load_error_strings();
282
283         method = (SSL_METHOD *)SSLv23_client_method();
284         if (!method) {
285                 error = ERR_get_error();
286                 lwsl_err("problem creating ssl method %lu: %s\n",
287                         error, ERR_error_string(error,
288                                       (char *)vhost->context->pt[0].serv_buf));
289                 return 1;
290         }
291         /* create context */
292         vhost->ssl_client_ctx = SSL_CTX_new(method);
293         if (!vhost->ssl_client_ctx) {
294                 error = ERR_get_error();
295                 lwsl_err("problem creating ssl context %lu: %s\n",
296                         error, ERR_error_string(error,
297                                       (char *)vhost->context->pt[0].serv_buf));
298                 return 1;
299         }
300
301 #ifdef SSL_OP_NO_COMPRESSION
302         SSL_CTX_set_options(vhost->ssl_client_ctx,
303                                                  SSL_OP_NO_COMPRESSION);
304 #endif
305         SSL_CTX_set_options(vhost->ssl_client_ctx,
306                                        SSL_OP_CIPHER_SERVER_PREFERENCE);
307         if (info->ssl_cipher_list)
308                 SSL_CTX_set_cipher_list(vhost->ssl_client_ctx,
309                                                 info->ssl_cipher_list);
310
311 #ifdef LWS_SSL_CLIENT_USE_OS_CA_CERTS
312         if (!lws_check_opt(info->options, LWS_SERVER_OPTION_DISABLE_OS_CA_CERTS))
313                 /* loads OS default CA certs */
314                 SSL_CTX_set_default_verify_paths(vhost->ssl_client_ctx);
315 #endif
316
317         /* openssl init for cert verification (for client sockets) */
318         if (!info->ssl_ca_filepath) {
319                 if (!SSL_CTX_load_verify_locations(
320                         vhost->ssl_client_ctx, NULL,
321                                              LWS_OPENSSL_CLIENT_CERTS))
322                         lwsl_err(
323                             "Unable to load SSL Client certs from %s "
324                             "(set by --with-client-cert-dir= "
325                             "in configure) --  client ssl isn't "
326                             "going to work", LWS_OPENSSL_CLIENT_CERTS);
327         } else
328                 if (!SSL_CTX_load_verify_locations(
329                         vhost->ssl_client_ctx, info->ssl_ca_filepath,
330                                                           NULL))
331                         lwsl_err(
332                                 "Unable to load SSL Client certs "
333                                 "file from %s -- client ssl isn't "
334                                 "going to work", info->ssl_ca_filepath);
335                 else
336                         lwsl_info("loaded ssl_ca_filepath\n");
337
338         /*
339          * callback allowing user code to load extra verification certs
340          * helping the client to verify server identity
341          */
342
343         /* support for client-side certificate authentication */
344         if (info->ssl_cert_filepath) {
345                 n = SSL_CTX_use_certificate_chain_file(vhost->ssl_client_ctx,
346                                                        info->ssl_cert_filepath);
347                 if (n != 1) {
348                         lwsl_err("problem getting cert '%s' %lu: %s\n",
349                                 info->ssl_cert_filepath,
350                                 ERR_get_error(),
351                                 ERR_error_string(ERR_get_error(),
352                                 (char *)vhost->context->pt[0].serv_buf));
353                         return 1;
354                 }
355         }
356         if (info->ssl_private_key_filepath) {
357                 lws_ssl_bind_passphrase(vhost->ssl_client_ctx, info);
358                 /* set the private key from KeyFile */
359                 if (SSL_CTX_use_PrivateKey_file(vhost->ssl_client_ctx,
360                     info->ssl_private_key_filepath, SSL_FILETYPE_PEM) != 1) {
361                         lwsl_err("use_PrivateKey_file '%s' %lu: %s\n",
362                                 info->ssl_private_key_filepath,
363                                 ERR_get_error(),
364                                 ERR_error_string(ERR_get_error(),
365                                       (char *)vhost->context->pt[0].serv_buf));
366                         return 1;
367                 }
368
369                 /* verify private key */
370                 if (!SSL_CTX_check_private_key(vhost->ssl_client_ctx)) {
371                         lwsl_err("Private SSL key doesn't match cert\n");
372                         return 1;
373                 }
374         }
375
376         /*
377          * give him a fake wsi with context set, so he can use
378          * lws_get_context() in the callback
379          */
380         memset(&wsi, 0, sizeof(wsi));
381         wsi.vhost = vhost;
382         wsi.context = vhost->context;
383
384         vhost->protocols[0].callback(&wsi,
385                         LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS,
386                                        vhost->ssl_client_ctx, NULL, 0);
387
388         return 0;
389 }