lwsws redirect and correct vhost selection before accept
[platform/upstream/libwebsockets.git] / lib / ssl-server.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
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 static int
31 OpenSSL_verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx)
32 {
33         SSL *ssl;
34         int n;
35         struct lws_vhost *vh;
36         struct lws wsi;
37
38         ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
39                 SSL_get_ex_data_X509_STORE_CTX_idx());
40
41         /*
42          * !!! nasty openssl requires the index to come as a library-scope
43          * static
44          */
45         vh = SSL_get_ex_data(ssl, openssl_websocket_private_data_index);
46
47         /*
48          * give him a fake wsi with context set, so he can use lws_get_context()
49          * in the callback
50          */
51         memset(&wsi, 0, sizeof(wsi));
52         wsi.vhost = vh;
53         wsi.context = vh->context;
54
55         n = vh->protocols[0].callback(&wsi,
56                         LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION,
57                                            x509_ctx, ssl, preverify_ok);
58
59         /* convert return code from 0 = OK to 1 = OK */
60         return !n;
61 }
62
63 static int
64 lws_context_ssl_init_ecdh(struct lws_vhost *vhost)
65 {
66 #ifdef LWS_SSL_SERVER_WITH_ECDH_CERT
67         EC_KEY *EC_key = NULL;
68         EVP_PKEY *pkey;
69         int KeyType;
70         X509 *x;
71
72         if (!lws_check_opt(vhost->context->options, LWS_SERVER_OPTION_SSL_ECDH))
73                 return 0;
74
75         lwsl_notice(" Using ECDH certificate support\n");
76
77         /* Get X509 certificate from ssl context */
78         x = sk_X509_value(vhost->ssl_ctx->extra_certs, 0);
79         if (!x) {
80                 lwsl_err("%s: x is NULL\n", __func__);
81                 return 1;
82         }
83         /* Get the public key from certificate */
84         pkey = X509_get_pubkey(x);
85         if (!pkey) {
86                 lwsl_err("%s: pkey is NULL\n", __func__);
87
88                 return 1;
89         }
90         /* Get the key type */
91         KeyType = EVP_PKEY_type(pkey->type);
92
93         if (EVP_PKEY_EC != KeyType) {
94                 lwsl_notice("Key type is not EC\n");
95                 return 0;
96         }
97         /* Get the key */
98         EC_key = EVP_PKEY_get1_EC_KEY(pkey);
99         /* Set ECDH parameter */
100         if (!EC_key) {
101                 lwsl_err("%s: ECDH key is NULL \n", __func__);
102                 return 1;
103         }
104         SSL_CTX_set_tmp_ecdh(vhost->ssl_ctx, EC_key);
105         EC_KEY_free(EC_key);
106 #endif
107         return 0;
108 }
109
110 static int
111 lws_context_ssl_init_ecdh_curve(struct lws_context_creation_info *info,
112                                 struct lws_vhost *vhost)
113 {
114 #ifdef LWS_HAVE_OPENSSL_ECDH_H
115         EC_KEY *ecdh;
116         int ecdh_nid;
117         const char *ecdh_curve = "prime256v1";
118
119         if (info->ecdh_curve)
120                 ecdh_curve = info->ecdh_curve;
121
122         ecdh_nid = OBJ_sn2nid(ecdh_curve);
123         if (NID_undef == ecdh_nid) {
124                 lwsl_err("SSL: Unknown curve name '%s'", ecdh_curve);
125                 return 1;
126         }
127
128         ecdh = EC_KEY_new_by_curve_name(ecdh_nid);
129         if (NULL == ecdh) {
130                 lwsl_err("SSL: Unable to create curve '%s'", ecdh_curve);
131                 return 1;
132         }
133         SSL_CTX_set_tmp_ecdh(vhost->ssl_ctx, ecdh);
134         EC_KEY_free(ecdh);
135
136         SSL_CTX_set_options(vhost->ssl_ctx, SSL_OP_SINGLE_ECDH_USE);
137
138         lwsl_notice(" SSL ECDH curve '%s'\n", ecdh_curve);
139 #else
140         lwsl_notice(" OpenSSL doesn't support ECDH\n");
141 #endif
142         return 0;
143 }
144
145 #ifndef OPENSSL_NO_TLSEXT
146 static int
147 lws_ssl_server_name_cb(SSL *ssl, int *ad, void *arg)
148 {
149         struct lws_context *context;
150         struct lws_vhost *vhost, *vh;
151         const char *servername;
152         int port;
153
154         if (!ssl)
155                 return SSL_TLSEXT_ERR_NOACK;
156
157         context = (struct lws_context *)SSL_CTX_get_ex_data(
158                                         SSL_get_SSL_CTX(ssl),
159                                         openssl_SSL_CTX_private_data_index);
160
161         /*
162          * We can only get ssl accepted connections by using a vhost's ssl_ctx
163          * find out which listening one took us and only match vhosts on the
164          * same port.
165          */
166         vh = context->vhost_list;
167         while (vh) {
168                 if (vh->ssl_ctx == SSL_get_SSL_CTX(ssl))
169                         break;
170                 vh = vh->vhost_next;
171         }
172
173         assert(vh); /* we cannot get an ssl without using a vhost ssl_ctx */
174         port = vh->listen_port;
175
176         servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
177
178         if (servername) {
179                 vhost = lws_select_vhost(context, port, servername);
180                 if (vhost) {
181                         lwsl_notice("SNI: Found: %s (port %d)\n", servername, port);
182                         SSL_set_SSL_CTX(ssl, vhost->ssl_ctx);
183                         return SSL_TLSEXT_ERR_OK;
184                 }
185                 lwsl_err("SNI: Unknown ServerName: %s\n", servername);
186         }
187
188         return SSL_TLSEXT_ERR_OK;
189 }
190 #endif
191
192 LWS_VISIBLE int
193 lws_context_init_server_ssl(struct lws_context_creation_info *info,
194                             struct lws_vhost *vhost)
195 {
196         SSL_METHOD *method;
197         struct lws_context *context = vhost->context;
198         struct lws wsi;
199         int error;
200         int n;
201
202         if (!lws_check_opt(info->options, LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT)) {
203                 vhost->use_ssl = 0;
204                 return 0;
205         }
206
207         if (info->port != CONTEXT_PORT_NO_LISTEN) {
208
209                 vhost->use_ssl = info->ssl_cert_filepath != NULL;
210
211                 if (vhost->use_ssl && info->ssl_cipher_list)
212                         lwsl_notice(" SSL ciphers: '%s'\n", info->ssl_cipher_list);
213
214                 if (vhost->use_ssl)
215                         lwsl_notice(" Using SSL mode\n");
216                 else
217                         lwsl_notice(" Using non-SSL mode\n");
218         }
219
220         /*
221          * give him a fake wsi with context + vhost set, so he can use
222          * lws_get_context() in the callback
223          */
224         memset(&wsi, 0, sizeof(wsi));
225         wsi.vhost = vhost;
226         wsi.context = vhost->context;
227
228         /*
229          * Firefox insists on SSLv23 not SSLv3
230          * Konq disables SSLv2 by default now, SSLv23 works
231          *
232          * SSLv23_server_method() is the openssl method for "allow all TLS
233          * versions", compared to e.g. TLSv1_2_server_method() which only allows
234          * tlsv1.2. Unwanted versions must be disabled using SSL_CTX_set_options()
235          */
236
237         method = (SSL_METHOD *)SSLv23_server_method();
238         if (!method) {
239                 error = ERR_get_error();
240                 lwsl_err("problem creating ssl method %lu: %s\n",
241                         error, ERR_error_string(error,
242                                               (char *)context->pt[0].serv_buf));
243                 return 1;
244         }
245         vhost->ssl_ctx = SSL_CTX_new(method);   /* create context */
246         if (!vhost->ssl_ctx) {
247                 error = ERR_get_error();
248                 lwsl_err("problem creating ssl context %lu: %s\n",
249                         error, ERR_error_string(error,
250                                               (char *)context->pt[0].serv_buf));
251                 return 1;
252         }
253
254         /* associate the lws context with the SSL_CTX */
255
256         SSL_CTX_set_ex_data(vhost->ssl_ctx,
257                         openssl_SSL_CTX_private_data_index, vhost->context);
258
259         /* Disable SSLv2 and SSLv3 */
260         SSL_CTX_set_options(vhost->ssl_ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
261 #ifdef SSL_OP_NO_COMPRESSION
262         SSL_CTX_set_options(vhost->ssl_ctx, SSL_OP_NO_COMPRESSION);
263 #endif
264         SSL_CTX_set_options(vhost->ssl_ctx, SSL_OP_SINGLE_DH_USE);
265         SSL_CTX_set_options(vhost->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
266         if (info->ssl_cipher_list)
267                 SSL_CTX_set_cipher_list(vhost->ssl_ctx,
268                                                 info->ssl_cipher_list);
269
270         /* as a server, are we requiring clients to identify themselves? */
271
272         if (lws_check_opt(info->options, LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT)) {
273                 int verify_options = SSL_VERIFY_PEER;
274
275                 if (!lws_check_opt(info->options, LWS_SERVER_OPTION_PEER_CERT_NOT_REQUIRED))
276                         verify_options |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
277
278                 SSL_CTX_set_session_id_context(vhost->ssl_ctx,
279                                 (unsigned char *)context, sizeof(void *));
280
281                 /* absolutely require the client cert */
282
283                 SSL_CTX_set_verify(vhost->ssl_ctx,
284                        verify_options, OpenSSL_verify_callback);
285         }
286
287 #ifndef OPENSSL_NO_TLSEXT
288         SSL_CTX_set_tlsext_servername_callback(vhost->ssl_ctx,
289                                                lws_ssl_server_name_cb);
290 #endif
291
292         /*
293          * give user code a chance to load certs into the server
294          * allowing it to verify incoming client certs
295          */
296
297         if (info->ssl_ca_filepath &&
298             !SSL_CTX_load_verify_locations(vhost->ssl_ctx,
299                                            info->ssl_ca_filepath, NULL)) {
300                 lwsl_err("%s: SSL_CTX_load_verify_locations unhappy\n", __func__);
301         }
302
303         if (vhost->use_ssl) {
304                 if (lws_context_ssl_init_ecdh_curve(info, vhost))
305                         return -1;
306
307                 vhost->protocols[0].callback(&wsi,
308                         LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS,
309                         vhost->ssl_ctx, NULL, 0);
310         }
311
312         if (lws_check_opt(info->options, LWS_SERVER_OPTION_ALLOW_NON_SSL_ON_SSL_PORT))
313                 /* Normally SSL listener rejects non-ssl, optionally allow */
314                 vhost->allow_non_ssl_on_ssl_port = 1;
315
316         if (vhost->use_ssl) {
317                 /* openssl init for server sockets */
318
319                 /* set the local certificate from CertFile */
320                 n = SSL_CTX_use_certificate_chain_file(vhost->ssl_ctx,
321                                         info->ssl_cert_filepath);
322                 if (n != 1) {
323                         error = ERR_get_error();
324                         lwsl_err("problem getting cert '%s' %lu: %s\n",
325                                 info->ssl_cert_filepath,
326                                 error,
327                                 ERR_error_string(error,
328                                               (char *)context->pt[0].serv_buf));
329                         return 1;
330                 }
331                 lws_ssl_bind_passphrase(vhost->ssl_ctx, info);
332
333                 if (info->ssl_private_key_filepath != NULL) {
334                         /* set the private key from KeyFile */
335                         if (SSL_CTX_use_PrivateKey_file(vhost->ssl_ctx,
336                                      info->ssl_private_key_filepath,
337                                                        SSL_FILETYPE_PEM) != 1) {
338                                 error = ERR_get_error();
339                                 lwsl_err("ssl problem getting key '%s' %lu: %s\n",
340                                          info->ssl_private_key_filepath, error,
341                                          ERR_error_string(error,
342                                               (char *)context->pt[0].serv_buf));
343                                 return 1;
344                         }
345                 } else
346                         if (vhost->protocols[0].callback(&wsi,
347                                 LWS_CALLBACK_OPENSSL_CONTEXT_REQUIRES_PRIVATE_KEY,
348                                 vhost->ssl_ctx, NULL, 0)) {
349                                 lwsl_err("ssl private key not set\n");
350
351                                 return 1;
352                         }
353
354                 /* verify private key */
355                 if (!SSL_CTX_check_private_key(vhost->ssl_ctx)) {
356                         lwsl_err("Private SSL key doesn't match cert\n");
357                         return 1;
358                 }
359
360                 if (lws_context_ssl_init_ecdh(vhost))
361                         return 1;
362
363                 /*
364                  * SSL is happy and has a cert it's content with
365                  * If we're supporting HTTP2, initialize that
366                  */
367
368                 lws_context_init_http2_ssl(context);
369         }
370
371         return 0;
372 }
373