add lws_init_vhost_client_ssl api to allow client ssl use on a vhost
[platform/upstream/libwebsockets.git] / lib / ssl-client.c
1 /*
2  * libwebsockets - small server side websockets and web server implementation
3  *
4  * Copyright (C) 2010-2016 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
24 extern int openssl_websocket_private_data_index,
25     openssl_SSL_CTX_private_data_index;
26
27 extern void
28 lws_ssl_bind_passphrase(SSL_CTX *ssl_ctx, struct lws_context_creation_info *info);
29
30 extern int lws_ssl_get_error(struct lws *wsi, int n);
31
32 int
33 lws_ssl_client_bio_create(struct lws *wsi)
34 {
35 #if defined(LWS_USE_POLARSSL)
36         return 0;
37 #else
38 #if defined(LWS_USE_MBEDTLS)
39 #else
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 #endif
104 #endif
105 }
106
107 int
108 lws_ssl_client_connect1(struct lws *wsi)
109 {
110         struct lws_context *context = wsi->context;
111         int n = 0;
112
113         lws_latency_pre(context, wsi);
114 #if defined(LWS_USE_POLARSSL)
115 #else
116 #if defined(LWS_USE_MBEDTLS)
117 #else
118         n = SSL_connect(wsi->ssl);
119 #endif
120 #endif
121         lws_latency(context, wsi,
122           "SSL_connect LWSCM_WSCL_ISSUE_HANDSHAKE", n, n > 0);
123
124         if (n < 0) {
125                 n = lws_ssl_get_error(wsi, n);
126
127                 if (n == SSL_ERROR_WANT_READ)
128                         goto some_wait;
129
130                 if (n == SSL_ERROR_WANT_WRITE) {
131                         /*
132                          * wants us to retry connect due to
133                          * state of the underlying ssl layer...
134                          * but since it may be stalled on
135                          * blocked write, no incoming data may
136                          * arrive to trigger the retry.
137                          * Force (possibly many times if the SSL
138                          * state persists in returning the
139                          * condition code, but other sockets
140                          * are getting serviced inbetweentimes)
141                          * us to get called back when writable.
142                          */
143                         lwsl_info("%s: WANT_WRITE... retrying\n", __func__);
144                         lws_callback_on_writable(wsi);
145 some_wait:
146                         wsi->mode = LWSCM_WSCL_WAITING_SSL;
147
148                         return 0; /* no error */
149                 }
150                 n = -1;
151         }
152
153         if (n <= 0) {
154                 /*
155                  * retry if new data comes until we
156                  * run into the connection timeout or win
157                  */
158 #if defined(LWS_USE_POLARSSL)
159 #else
160 #if defined(LWS_USE_MBEDTLS)
161 #else
162                 n = ERR_get_error();
163
164                 if (n != SSL_ERROR_NONE) {
165                         struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
166                         char *p = (char *)&pt->serv_buf[0];
167                         char *sb = p;
168                         lwsl_err("SSL connect error %lu: %s\n",
169                                 n, ERR_error_string(n, sb));
170                         return -1;
171                 }
172 #endif
173 #endif
174         }
175
176         return 1;
177 }
178
179 int
180 lws_ssl_client_connect2(struct lws *wsi)
181 {
182         struct lws_context *context = wsi->context;
183 #if defined(LWS_USE_POLARSSL)
184 #else
185 #if defined(LWS_USE_MBEDTLS)
186 #else
187         struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
188         char *p = (char *)&pt->serv_buf[0];
189         char *sb = p;
190 #endif
191 #endif
192         int n = 0;
193
194         if (wsi->mode == LWSCM_WSCL_WAITING_SSL) {
195                 lws_latency_pre(context, wsi);
196 #if defined(LWS_USE_POLARSSL)
197 #else
198 #if defined(LWS_USE_MBEDTLS)
199 #else
200                 n = SSL_connect(wsi->ssl);
201 #endif
202 #endif
203                 lws_latency(context, wsi,
204                             "SSL_connect LWSCM_WSCL_WAITING_SSL", n, n > 0);
205
206                 if (n < 0) {
207                         n = lws_ssl_get_error(wsi, n);
208
209                         if (n == SSL_ERROR_WANT_READ) {
210                                 wsi->mode = LWSCM_WSCL_WAITING_SSL;
211
212                                 return 0; /* no error */
213                         }
214
215                         if (n == SSL_ERROR_WANT_WRITE) {
216                                 /*
217                                  * wants us to retry connect due to
218                                  * state of the underlying ssl layer...
219                                  * but since it may be stalled on
220                                  * blocked write, no incoming data may
221                                  * arrive to trigger the retry.
222                                  * Force (possibly many times if the SSL
223                                  * state persists in returning the
224                                  * condition code, but other sockets
225                                  * are getting serviced inbetweentimes)
226                                  * us to get called back when writable.
227                                  */
228                                 lwsl_info("SSL_connect WANT_WRITE... retrying\n");
229                                 lws_callback_on_writable(wsi);
230
231                                 wsi->mode = LWSCM_WSCL_WAITING_SSL;
232
233                                 return 0; /* no error */
234                         }
235                         n = -1;
236                 }
237
238                 if (n <= 0) {
239                         /*
240                          * retry if new data comes until we
241                          * run into the connection timeout or win
242                          */
243 #if defined(LWS_USE_POLARSSL)
244 #else
245 #if defined(LWS_USE_MBEDTLS)
246 #else
247                         n = ERR_get_error();
248                         if (n != SSL_ERROR_NONE) {
249                                 lwsl_err("SSL connect error %lu: %s\n",
250                                          n, ERR_error_string(n, sb));
251                                 return -1;
252                         }
253 #endif
254 #endif
255                 }
256         }
257
258 #if defined(LWS_USE_POLARSSL)
259 #else
260 #if defined(LWS_USE_MBEDTLS)
261 #else
262 #ifndef USE_WOLFSSL
263         /*
264          * See comment above about wolfSSL certificate
265          * verification
266          */
267         lws_latency_pre(context, wsi);
268         n = SSL_get_verify_result(wsi->ssl);
269         lws_latency(context, wsi,
270                 "SSL_get_verify_result LWS_CONNMODE..HANDSHAKE",
271                                                       n, n > 0);
272
273         if (n != X509_V_OK) {
274                 if ((n == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT ||
275                      n == X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN) && wsi->use_ssl == 2) {
276                         lwsl_notice("accepting self-signed certificate\n");
277                 } else {
278                         lwsl_err("server's cert didn't look good, X509_V_ERR = %d: %s\n",
279                                  n, ERR_error_string(n, sb));
280                         lws_ssl_elaborate_error();
281                         lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
282                         return -1;
283                 }
284         }
285 #endif /* USE_WOLFSSL */
286 #endif
287 #endif
288
289         return 1;
290 }
291
292
293 int lws_context_init_client_ssl(struct lws_context_creation_info *info,
294                                 struct lws_vhost *vhost)
295 {
296 #if defined(LWS_USE_POLARSSL)
297         return 0;
298 #else
299 #if defined(LWS_USE_MBEDTLS)
300 #else
301         SSL_METHOD *method;
302         struct lws wsi;
303         int error;
304         int n;
305
306         if (!lws_check_opt(info->options, LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT))
307                 return 0;
308
309         if (info->provided_client_ssl_ctx) {
310                 /* use the provided OpenSSL context if given one */
311                 vhost->ssl_client_ctx = info->provided_client_ssl_ctx;
312                 /* nothing for lib to delete */
313                 vhost->user_supplied_ssl_ctx = 1;
314
315                 return 0;
316         }
317
318         if (info->port != CONTEXT_PORT_NO_LISTEN)
319                 return 0;
320
321         /* basic openssl init */
322
323         SSL_library_init();
324
325         OpenSSL_add_all_algorithms();
326         SSL_load_error_strings();
327
328         method = (SSL_METHOD *)SSLv23_client_method();
329         if (!method) {
330                 error = ERR_get_error();
331                 lwsl_err("problem creating ssl method %lu: %s\n",
332                         error, ERR_error_string(error,
333                                       (char *)vhost->context->pt[0].serv_buf));
334                 return 1;
335         }
336         /* create context */
337         vhost->ssl_client_ctx = SSL_CTX_new(method);
338         if (!vhost->ssl_client_ctx) {
339                 error = ERR_get_error();
340                 lwsl_err("problem creating ssl context %lu: %s\n",
341                         error, ERR_error_string(error,
342                                       (char *)vhost->context->pt[0].serv_buf));
343                 return 1;
344         }
345
346 #ifdef SSL_OP_NO_COMPRESSION
347         SSL_CTX_set_options(vhost->ssl_client_ctx, SSL_OP_NO_COMPRESSION);
348 #endif
349         SSL_CTX_set_options(vhost->ssl_client_ctx,
350                             SSL_OP_CIPHER_SERVER_PREFERENCE);
351         if (info->ssl_cipher_list)
352                 SSL_CTX_set_cipher_list(vhost->ssl_client_ctx,
353                                                 info->ssl_cipher_list);
354
355 #ifdef LWS_SSL_CLIENT_USE_OS_CA_CERTS
356         if (!lws_check_opt(info->options, LWS_SERVER_OPTION_DISABLE_OS_CA_CERTS))
357                 /* loads OS default CA certs */
358                 SSL_CTX_set_default_verify_paths(vhost->ssl_client_ctx);
359 #endif
360
361         /* openssl init for cert verification (for client sockets) */
362         if (!info->ssl_ca_filepath) {
363                 if (!SSL_CTX_load_verify_locations(
364                         vhost->ssl_client_ctx, NULL,
365                                              LWS_OPENSSL_CLIENT_CERTS))
366                         lwsl_err(
367                             "Unable to load SSL Client certs from %s "
368                             "(set by --with-client-cert-dir= "
369                             "in configure) --  client ssl isn't "
370                             "going to work", LWS_OPENSSL_CLIENT_CERTS);
371         } else
372                 if (!SSL_CTX_load_verify_locations(
373                         vhost->ssl_client_ctx, info->ssl_ca_filepath,
374                                                           NULL))
375                         lwsl_err(
376                                 "Unable to load SSL Client certs "
377                                 "file from %s -- client ssl isn't "
378                                 "going to work", info->ssl_ca_filepath);
379                 else
380                         lwsl_info("loaded ssl_ca_filepath\n");
381
382         /*
383          * callback allowing user code to load extra verification certs
384          * helping the client to verify server identity
385          */
386
387         /* support for client-side certificate authentication */
388         if (info->ssl_cert_filepath) {
389                 n = SSL_CTX_use_certificate_chain_file(vhost->ssl_client_ctx,
390                                                        info->ssl_cert_filepath);
391                 if (n != 1) {
392                         lwsl_err("problem getting cert '%s' %lu: %s\n",
393                                 info->ssl_cert_filepath,
394                                 ERR_get_error(),
395                                 ERR_error_string(ERR_get_error(),
396                                 (char *)vhost->context->pt[0].serv_buf));
397                         return 1;
398                 }
399         }
400         if (info->ssl_private_key_filepath) {
401                 lws_ssl_bind_passphrase(vhost->ssl_client_ctx, info);
402                 /* set the private key from KeyFile */
403                 if (SSL_CTX_use_PrivateKey_file(vhost->ssl_client_ctx,
404                     info->ssl_private_key_filepath, SSL_FILETYPE_PEM) != 1) {
405                         lwsl_err("use_PrivateKey_file '%s' %lu: %s\n",
406                                 info->ssl_private_key_filepath,
407                                 ERR_get_error(),
408                                 ERR_error_string(ERR_get_error(),
409                                       (char *)vhost->context->pt[0].serv_buf));
410                         return 1;
411                 }
412
413                 /* verify private key */
414                 if (!SSL_CTX_check_private_key(vhost->ssl_client_ctx)) {
415                         lwsl_err("Private SSL key doesn't match cert\n");
416                         return 1;
417                 }
418         }
419
420         /*
421          * give him a fake wsi with context set, so he can use
422          * lws_get_context() in the callback
423          */
424         memset(&wsi, 0, sizeof(wsi));
425         wsi.vhost = vhost;
426         wsi.context = vhost->context;
427
428         vhost->protocols[0].callback(&wsi,
429                         LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS,
430                                        vhost->ssl_client_ctx, NULL, 0);
431
432         return 0;
433 #endif
434 #endif
435 }