blob: 2d5e6663be909f7cbb643e81fc16afe3fcc950df [file] [log] [blame]
Emeric Brun46591952012-05-18 15:47:34 +02001/*
2 * SSL data transfer functions between buffers and SOCK_STREAM sockets
3 *
4 * Copyright (C) 2012 EXCELIANCE, Emeric Brun <ebrun@exceliance.fr>
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
Willy Tarreau69845df2012-09-10 09:43:09 +020011 * Acknowledgement:
12 * We'd like to specially thank the Stud project authors for a very clean
13 * and well documented code which helped us understand how the OpenSSL API
14 * ought to be used in non-blocking mode. This is one difficult part which
15 * is not easy to get from the OpenSSL doc, and reading the Stud code made
16 * it much more obvious than the examples in the OpenSSL package. Keep up
17 * the good works, guys !
18 *
19 * Stud is an extremely efficient and scalable SSL/TLS proxy which combines
20 * particularly well with haproxy. For more info about this project, visit :
21 * https://github.com/bumptech/stud
22 *
Emeric Brun46591952012-05-18 15:47:34 +020023 */
24
25#define _GNU_SOURCE
Emeric Brunfc0421f2012-09-07 17:30:07 +020026#include <ctype.h>
27#include <dirent.h>
Emeric Brun46591952012-05-18 15:47:34 +020028#include <errno.h>
29#include <fcntl.h>
30#include <stdio.h>
31#include <stdlib.h>
Emeric Brunfc0421f2012-09-07 17:30:07 +020032#include <string.h>
33#include <unistd.h>
Emeric Brun46591952012-05-18 15:47:34 +020034
35#include <sys/socket.h>
36#include <sys/stat.h>
37#include <sys/types.h>
38
39#include <netinet/tcp.h>
40
41#include <openssl/ssl.h>
Emeric Brunfc0421f2012-09-07 17:30:07 +020042#include <openssl/x509.h>
43#include <openssl/x509v3.h>
44#include <openssl/x509.h>
45#include <openssl/err.h>
Emeric Brun46591952012-05-18 15:47:34 +020046
47#include <common/buffer.h>
48#include <common/compat.h>
49#include <common/config.h>
50#include <common/debug.h>
Willy Tarreau79eeafa2012-09-14 07:53:05 +020051#include <common/errors.h>
Emeric Brun46591952012-05-18 15:47:34 +020052#include <common/standard.h>
53#include <common/ticks.h>
54#include <common/time.h>
55
Emeric Brunfc0421f2012-09-07 17:30:07 +020056#include <ebsttree.h>
57
58#include <types/global.h>
59#include <types/ssl_sock.h>
60
Willy Tarreau7875d092012-09-10 08:20:03 +020061#include <proto/acl.h>
62#include <proto/arg.h>
Emeric Brun46591952012-05-18 15:47:34 +020063#include <proto/connection.h>
64#include <proto/fd.h>
65#include <proto/freq_ctr.h>
66#include <proto/frontend.h>
Willy Tarreau79eeafa2012-09-14 07:53:05 +020067#include <proto/listener.h>
Emeric Brun46591952012-05-18 15:47:34 +020068#include <proto/log.h>
Emeric Brunfc0421f2012-09-07 17:30:07 +020069#include <proto/shctx.h>
Emeric Brun46591952012-05-18 15:47:34 +020070#include <proto/ssl_sock.h>
71#include <proto/task.h>
72
Willy Tarreau403edff2012-09-06 11:58:37 +020073static int sslconns = 0;
Emeric Brune1f38db2012-09-03 20:36:47 +020074
75void ssl_sock_infocbk(const SSL *ssl, int where, int ret)
76{
77 struct connection *conn = (struct connection *)SSL_get_app_data(ssl);
78 (void)ret; /* shut gcc stupid warning */
79
80 if (where & SSL_CB_HANDSHAKE_START) {
81 /* Disable renegotiation (CVE-2009-3555) */
82 if (conn->flags & CO_FL_CONNECTED)
83 conn->flags |= CO_FL_ERROR;
84 }
Emeric Brunfc0421f2012-09-07 17:30:07 +020085}
86
87#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
88/* Sets the SSL ctx of <ssl> to match the advertised server name. Returns a
89 * warning when no match is found, which implies the default (first) cert
90 * will keep being used.
91 */
Willy Tarreau2a65ff02012-09-13 17:54:29 +020092static int ssl_sock_switchctx_cbk(SSL *ssl, int *al, struct bind_conf *s)
Emeric Brunfc0421f2012-09-07 17:30:07 +020093{
94 const char *servername;
95 const char *wildp = NULL;
96 struct ebmb_node *node;
97 int i;
98 (void)al; /* shut gcc stupid warning */
99
100 servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
101 if (!servername)
102 return SSL_TLSEXT_ERR_NOACK;
103
104 for (i = 0; i < trashlen; i++) {
105 if (!servername[i])
106 break;
107 trash[i] = tolower(servername[i]);
108 if (!wildp && (trash[i] == '.'))
109 wildp = &trash[i];
110 }
111 trash[i] = 0;
112
113 /* lookup in full qualified names */
114 node = ebst_lookup(&s->sni_ctx, trash);
115 if (!node) {
116 if (!wildp)
117 return SSL_TLSEXT_ERR_ALERT_WARNING;
118
119 /* lookup in full wildcards names */
120 node = ebst_lookup(&s->sni_w_ctx, wildp);
121 if (!node)
122 return SSL_TLSEXT_ERR_ALERT_WARNING;
123 }
124
125 /* switch ctx */
126 SSL_set_SSL_CTX(ssl, container_of(node, struct sni_ctx, name)->ctx);
127 return SSL_TLSEXT_ERR_OK;
128}
129#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
130
131/* Loads a certificate key and CA chain from a file. Returns 0 on error, -1 if
132 * an early error happens and the caller must call SSL_CTX_free() by itelf.
133 */
Willy Tarreau2a65ff02012-09-13 17:54:29 +0200134int ssl_sock_load_cert_chain_file(SSL_CTX *ctx, const char *file, struct bind_conf *s)
Emeric Brunfc0421f2012-09-07 17:30:07 +0200135{
136 BIO *in;
137 X509 *x = NULL, *ca;
138 int i, len, err;
139 int ret = -1;
140 int order = 0;
141 X509_NAME *xname;
142 char *str;
143 struct sni_ctx *sc;
144#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
145 STACK_OF(GENERAL_NAME) *names;
146#endif
147
148 in = BIO_new(BIO_s_file());
149 if (in == NULL)
150 goto end;
151
152 if (BIO_read_filename(in, file) <= 0)
153 goto end;
154
155 x = PEM_read_bio_X509_AUX(in, NULL, ctx->default_passwd_callback, ctx->default_passwd_callback_userdata);
156 if (x == NULL)
157 goto end;
158
159#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
160 names = X509_get_ext_d2i(x, NID_subject_alt_name, NULL, NULL);
161 if (names) {
162 for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
163 GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
164 if (name->type == GEN_DNS) {
165 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
166 if ((len = strlen(str))) {
167 int j;
168
169 if (*str != '*') {
170 sc = malloc(sizeof(struct sni_ctx) + len + 1);
171 for (j = 0; j < len; j++)
172 sc->name.key[j] = tolower(str[j]);
173 sc->name.key[len] = 0;
174 sc->order = order++;
175 sc->ctx = ctx;
176 ebst_insert(&s->sni_ctx, &sc->name);
177 }
178 else {
179 sc = malloc(sizeof(struct sni_ctx) + len);
180 for (j = 1; j < len; j++)
181 sc->name.key[j-1] = tolower(str[j]);
182 sc->name.key[len-1] = 0;
183 sc->order = order++;
184 sc->ctx = ctx;
185 ebst_insert(&s->sni_w_ctx, &sc->name);
186 }
187 }
188 OPENSSL_free(str);
189 }
190 }
191 }
192 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
193 }
194#endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
195
196 xname = X509_get_subject_name(x);
197 i = -1;
198 while ((i = X509_NAME_get_index_by_NID(xname, NID_commonName, i)) != -1) {
199 X509_NAME_ENTRY *entry = X509_NAME_get_entry(xname, i);
200 if (ASN1_STRING_to_UTF8((unsigned char **)&str, entry->value) >= 0) {
201 if ((len = strlen(str))) {
202 int j;
203
204 if (*str != '*') {
205 sc = malloc(sizeof(struct sni_ctx) + len + 1);
206 for (j = 0; j < len; j++)
207 sc->name.key[j] = tolower(str[j]);
208 sc->name.key[len] = 0;
209 sc->order = order++;
210 sc->ctx = ctx;
211 ebst_insert(&s->sni_ctx, &sc->name);
212 }
213 else {
214 sc = malloc(sizeof(struct sni_ctx) + len);
215 for (j = 1; j < len; j++)
216 sc->name.key[j-1] = tolower(str[j]);
217 sc->name.key[len-1] = 0;
218 sc->order = order++;
219 sc->ctx = ctx;
220 ebst_insert(&s->sni_w_ctx, &sc->name);
221 }
222 }
223 OPENSSL_free(str);
224 }
225 }
226
227 ret = 0; /* the caller must not free the SSL_CTX argument anymore */
228 if (!SSL_CTX_use_certificate(ctx, x))
229 goto end;
230
231 if (ctx->extra_certs != NULL) {
232 sk_X509_pop_free(ctx->extra_certs, X509_free);
233 ctx->extra_certs = NULL;
234 }
235
236 while ((ca = PEM_read_bio_X509(in, NULL, ctx->default_passwd_callback, ctx->default_passwd_callback_userdata))) {
237 if (!SSL_CTX_add_extra_chain_cert(ctx, ca)) {
238 X509_free(ca);
239 goto end;
240 }
241 }
242
243 err = ERR_get_error();
244 if (!err || (ERR_GET_LIB(err) == ERR_LIB_PEM && ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
245 /* we successfully reached the last cert in the file */
246 ret = 1;
247 }
248 ERR_clear_error();
249
250end:
251 if (x)
252 X509_free(x);
253
254 if (in)
255 BIO_free(in);
256
257 return ret;
258}
259
Willy Tarreau79eeafa2012-09-14 07:53:05 +0200260static int ssl_sock_load_cert_file(const char *path, struct bind_conf *bind_conf, struct proxy *curproxy, char **err)
Emeric Brunfc0421f2012-09-07 17:30:07 +0200261{
262 int ret;
263 SSL_CTX *ctx;
264
265 ctx = SSL_CTX_new(SSLv23_server_method());
266 if (!ctx) {
Willy Tarreau79eeafa2012-09-14 07:53:05 +0200267 if (err)
268 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
269 *err ? *err : "", path);
Emeric Brunfc0421f2012-09-07 17:30:07 +0200270 return 1;
271 }
272
273 if (SSL_CTX_use_PrivateKey_file(ctx, path, SSL_FILETYPE_PEM) <= 0) {
Willy Tarreau79eeafa2012-09-14 07:53:05 +0200274 if (err)
275 memprintf(err, "%sunable to load SSL private key from PEM file '%s'.\n",
276 *err ? *err : "", path);
Emeric Brunfc0421f2012-09-07 17:30:07 +0200277 SSL_CTX_free(ctx);
278 return 1;
279 }
280
Willy Tarreau2a65ff02012-09-13 17:54:29 +0200281 ret = ssl_sock_load_cert_chain_file(ctx, path, bind_conf);
Emeric Brunfc0421f2012-09-07 17:30:07 +0200282 if (ret <= 0) {
Willy Tarreau79eeafa2012-09-14 07:53:05 +0200283 if (err)
284 memprintf(err, "%sunable to load SSL certificate from PEM file '%s'.\n",
285 *err ? *err : "", path);
Emeric Brunfc0421f2012-09-07 17:30:07 +0200286 if (ret < 0) /* serious error, must do that ourselves */
287 SSL_CTX_free(ctx);
288 return 1;
289 }
290 /* we must not free the SSL_CTX anymore below, since it's already in
291 * the tree, so it will be discovered and cleaned in time.
292 */
293#ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
Willy Tarreau2a65ff02012-09-13 17:54:29 +0200294 if (bind_conf->default_ctx) {
Willy Tarreau79eeafa2012-09-14 07:53:05 +0200295 if (err)
296 memprintf(err, "%sthis version of openssl cannot load multiple SSL certificates.\n",
297 *err ? *err : "");
Emeric Brunfc0421f2012-09-07 17:30:07 +0200298 return 1;
299 }
300#endif
Willy Tarreau2a65ff02012-09-13 17:54:29 +0200301 if (!bind_conf->default_ctx)
302 bind_conf->default_ctx = ctx;
Emeric Brunfc0421f2012-09-07 17:30:07 +0200303
304 return 0;
305}
306
Willy Tarreau79eeafa2012-09-14 07:53:05 +0200307int ssl_sock_load_cert(char *path, struct bind_conf *bind_conf, struct proxy *curproxy, char **err)
Emeric Brunfc0421f2012-09-07 17:30:07 +0200308{
309 struct dirent *de;
310 DIR *dir;
311 struct stat buf;
312 int pathlen = 0;
313 char *end, *fp;
314 int cfgerr = 0;
315
316 if (!(dir = opendir(path)))
Willy Tarreau79eeafa2012-09-14 07:53:05 +0200317 return ssl_sock_load_cert_file(path, bind_conf, curproxy, err);
Emeric Brunfc0421f2012-09-07 17:30:07 +0200318
319 /* strip trailing slashes, including first one */
320 for (end = path + strlen(path) - 1; end >= path && *end == '/'; end--)
321 *end = 0;
322
323 if (end >= path)
324 pathlen = end + 1 - path;
325 fp = malloc(pathlen + 1 + NAME_MAX + 1);
326
327 while ((de = readdir(dir))) {
328 snprintf(fp, pathlen + 1 + NAME_MAX + 1, "%s/%s", path, de->d_name);
329 if (stat(fp, &buf) != 0) {
Willy Tarreau79eeafa2012-09-14 07:53:05 +0200330 if (err)
331 memprintf(err, "%sunable to stat SSL certificate from file '%s' : %s.\n",
332 *err ? *err : "", fp, strerror(errno));
Emeric Brunfc0421f2012-09-07 17:30:07 +0200333 cfgerr++;
334 continue;
335 }
336 if (!S_ISREG(buf.st_mode))
337 continue;
Willy Tarreau79eeafa2012-09-14 07:53:05 +0200338 cfgerr += ssl_sock_load_cert_file(fp, bind_conf, curproxy, err);
Emeric Brunfc0421f2012-09-07 17:30:07 +0200339 }
340 free(fp);
341 closedir(dir);
342 return cfgerr;
343}
344
345#ifndef SSL_OP_CIPHER_SERVER_PREFERENCE /* needs OpenSSL >= 0.9.7 */
346#define SSL_OP_CIPHER_SERVER_PREFERENCE 0
347#endif
348
349#ifndef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION /* needs OpenSSL >= 0.9.7 */
350#define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION 0
351#endif
352#ifndef SSL_OP_NO_COMPRESSION /* needs OpenSSL >= 0.9.9 */
353#define SSL_OP_NO_COMPRESSION 0
354#endif
355#ifndef SSL_MODE_RELEASE_BUFFERS /* needs OpenSSL >= 1.0.0 */
356#define SSL_MODE_RELEASE_BUFFERS 0
357#endif
Willy Tarreau2a65ff02012-09-13 17:54:29 +0200358int ssl_sock_prepare_ctx(struct bind_conf *bind_conf, SSL_CTX *ctx, struct proxy *curproxy)
Emeric Brunfc0421f2012-09-07 17:30:07 +0200359{
360 int cfgerr = 0;
361 int ssloptions =
362 SSL_OP_ALL | /* all known workarounds for bugs */
363 SSL_OP_NO_SSLv2 |
364 SSL_OP_NO_COMPRESSION |
365 SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION;
366 int sslmode =
367 SSL_MODE_ENABLE_PARTIAL_WRITE |
368 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
369 SSL_MODE_RELEASE_BUFFERS;
370
Willy Tarreau2a65ff02012-09-13 17:54:29 +0200371 if (bind_conf->nosslv3)
Emeric Brunfc0421f2012-09-07 17:30:07 +0200372 ssloptions |= SSL_OP_NO_SSLv3;
Willy Tarreau2a65ff02012-09-13 17:54:29 +0200373 if (bind_conf->notlsv1)
Emeric Brunfc0421f2012-09-07 17:30:07 +0200374 ssloptions |= SSL_OP_NO_TLSv1;
Willy Tarreau2a65ff02012-09-13 17:54:29 +0200375 if (bind_conf->prefer_server_ciphers)
Emeric Brunfc0421f2012-09-07 17:30:07 +0200376 ssloptions |= SSL_OP_CIPHER_SERVER_PREFERENCE;
377
378 SSL_CTX_set_options(ctx, ssloptions);
379 SSL_CTX_set_mode(ctx, sslmode);
380 SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
381
382 shared_context_set_cache(ctx);
Willy Tarreau2a65ff02012-09-13 17:54:29 +0200383 if (bind_conf->ciphers &&
384 !SSL_CTX_set_cipher_list(ctx, bind_conf->ciphers)) {
Emeric Brunfc0421f2012-09-07 17:30:07 +0200385 Alert("Proxy '%s': unable to set SSL cipher list to '%s' for bind '%s' at [%s:%d].\n",
Willy Tarreau2a65ff02012-09-13 17:54:29 +0200386 curproxy->id, bind_conf->ciphers, bind_conf->arg, bind_conf->file, bind_conf->line);
Emeric Brunfc0421f2012-09-07 17:30:07 +0200387 cfgerr++;
388 }
389
390 SSL_CTX_set_info_callback(ctx, ssl_sock_infocbk);
391#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
392 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_cbk);
Willy Tarreau2a65ff02012-09-13 17:54:29 +0200393 SSL_CTX_set_tlsext_servername_arg(ctx, bind_conf);
Emeric Brunfc0421f2012-09-07 17:30:07 +0200394#endif
395 return cfgerr;
396}
397
Willy Tarreau2a65ff02012-09-13 17:54:29 +0200398/* Walks down the two trees in bind_conf and prepares all certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +0200399 * be NULL, in which case nothing is done. Returns the number of errors
400 * encountered.
401 */
Willy Tarreau2a65ff02012-09-13 17:54:29 +0200402int ssl_sock_prepare_all_ctx(struct bind_conf *bind_conf, struct proxy *px)
Emeric Brunfc0421f2012-09-07 17:30:07 +0200403{
404 struct ebmb_node *node;
405 struct sni_ctx *sni;
406 int err = 0;
407
Willy Tarreau2a65ff02012-09-13 17:54:29 +0200408 if (!bind_conf || !bind_conf->is_ssl)
Emeric Brunfc0421f2012-09-07 17:30:07 +0200409 return 0;
410
Willy Tarreau2a65ff02012-09-13 17:54:29 +0200411 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +0200412 while (node) {
413 sni = ebmb_entry(node, struct sni_ctx, name);
414 if (!sni->order) /* only initialize the CTX on its first occurrence */
Willy Tarreau2a65ff02012-09-13 17:54:29 +0200415 err += ssl_sock_prepare_ctx(bind_conf, sni->ctx, px);
Emeric Brunfc0421f2012-09-07 17:30:07 +0200416 node = ebmb_next(node);
417 }
418
Willy Tarreau2a65ff02012-09-13 17:54:29 +0200419 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +0200420 while (node) {
421 sni = ebmb_entry(node, struct sni_ctx, name);
422 if (!sni->order) /* only initialize the CTX on its first occurrence */
Willy Tarreau2a65ff02012-09-13 17:54:29 +0200423 err += ssl_sock_prepare_ctx(bind_conf, sni->ctx, px);
Emeric Brunfc0421f2012-09-07 17:30:07 +0200424 node = ebmb_next(node);
425 }
426 return err;
427}
428
Willy Tarreau2a65ff02012-09-13 17:54:29 +0200429/* Walks down the two trees in bind_conf and frees all the certs. The pointer may
Emeric Brunfc0421f2012-09-07 17:30:07 +0200430 * be NULL, in which case nothing is done. The default_ctx is nullified too.
431 */
Willy Tarreau2a65ff02012-09-13 17:54:29 +0200432void ssl_sock_free_all_ctx(struct bind_conf *bind_conf)
Emeric Brunfc0421f2012-09-07 17:30:07 +0200433{
434 struct ebmb_node *node, *back;
435 struct sni_ctx *sni;
436
Willy Tarreau2a65ff02012-09-13 17:54:29 +0200437 if (!bind_conf || !bind_conf->is_ssl)
Emeric Brunfc0421f2012-09-07 17:30:07 +0200438 return;
439
Willy Tarreau2a65ff02012-09-13 17:54:29 +0200440 node = ebmb_first(&bind_conf->sni_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +0200441 while (node) {
442 sni = ebmb_entry(node, struct sni_ctx, name);
443 back = ebmb_next(node);
444 ebmb_delete(node);
445 if (!sni->order) /* only free the CTX on its first occurrence */
446 SSL_CTX_free(sni->ctx);
447 free(sni);
448 node = back;
449 }
450
Willy Tarreau2a65ff02012-09-13 17:54:29 +0200451 node = ebmb_first(&bind_conf->sni_w_ctx);
Emeric Brunfc0421f2012-09-07 17:30:07 +0200452 while (node) {
453 sni = ebmb_entry(node, struct sni_ctx, name);
454 back = ebmb_next(node);
455 ebmb_delete(node);
456 if (!sni->order) /* only free the CTX on its first occurrence */
457 SSL_CTX_free(sni->ctx);
458 free(sni);
459 node = back;
460 }
461
Willy Tarreau2a65ff02012-09-13 17:54:29 +0200462 bind_conf->default_ctx = NULL;
Emeric Brune1f38db2012-09-03 20:36:47 +0200463}
464
Emeric Brun46591952012-05-18 15:47:34 +0200465/*
466 * This function is called if SSL * context is not yet allocated. The function
467 * is designed to be called before any other data-layer operation and sets the
468 * handshake flag on the connection. It is safe to call it multiple times.
469 * It returns 0 on success and -1 in error case.
470 */
471static int ssl_sock_init(struct connection *conn)
472{
473 /* already initialized */
474 if (conn->data_ctx)
475 return 0;
476
Willy Tarreau403edff2012-09-06 11:58:37 +0200477 if (global.maxsslconn && sslconns >= global.maxsslconn)
478 return -1;
479
Emeric Brun46591952012-05-18 15:47:34 +0200480 /* If it is in client mode initiate SSL session
481 in connect state otherwise accept state */
482 if (target_srv(&conn->target)) {
Emeric Brun46591952012-05-18 15:47:34 +0200483 /* Alloc a new SSL session ctx */
484 conn->data_ctx = SSL_new(target_srv(&conn->target)->ssl_ctx.ctx);
485 if (!conn->data_ctx)
486 return -1;
487
488 SSL_set_connect_state(conn->data_ctx);
489 if (target_srv(&conn->target)->ssl_ctx.reused_sess)
490 SSL_set_session(conn->data_ctx, target_srv(&conn->target)->ssl_ctx.reused_sess);
491
492 /* set fd on SSL session context */
493 SSL_set_fd(conn->data_ctx, conn->t.sock.fd);
494
495 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +0200496 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Willy Tarreau403edff2012-09-06 11:58:37 +0200497
498 sslconns++;
Emeric Brun46591952012-05-18 15:47:34 +0200499 return 0;
500 }
501 else if (target_client(&conn->target)) {
Emeric Brun46591952012-05-18 15:47:34 +0200502 /* Alloc a new SSL session ctx */
Willy Tarreau2a65ff02012-09-13 17:54:29 +0200503 conn->data_ctx = SSL_new(target_client(&conn->target)->bind_conf->default_ctx);
Emeric Brun46591952012-05-18 15:47:34 +0200504 if (!conn->data_ctx)
505 return -1;
506
507 SSL_set_accept_state(conn->data_ctx);
508
509 /* set fd on SSL session context */
510 SSL_set_fd(conn->data_ctx, conn->t.sock.fd);
511
Emeric Brune1f38db2012-09-03 20:36:47 +0200512 /* set connection pointer */
513 SSL_set_app_data(conn->data_ctx, conn);
514
Emeric Brun46591952012-05-18 15:47:34 +0200515 /* leave init state and start handshake */
Willy Tarreau05737472012-09-04 08:03:39 +0200516 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
Willy Tarreau403edff2012-09-06 11:58:37 +0200517
518 sslconns++;
Emeric Brun46591952012-05-18 15:47:34 +0200519 return 0;
520 }
521 /* don't know how to handle such a target */
522 return -1;
523}
524
525
526/* This is the callback which is used when an SSL handshake is pending. It
527 * updates the FD status if it wants some polling before being called again.
528 * It returns 0 if it fails in a fatal way or needs to poll to go further,
529 * otherwise it returns non-zero and removes itself from the connection's
530 * flags (the bit is provided in <flag> by the caller).
531 */
532int ssl_sock_handshake(struct connection *conn, unsigned int flag)
533{
534 int ret;
535
536 if (!conn->data_ctx)
537 goto out_error;
538
539 ret = SSL_do_handshake(conn->data_ctx);
540 if (ret != 1) {
541 /* handshake did not complete, let's find why */
542 ret = SSL_get_error(conn->data_ctx, ret);
543
544 if (ret == SSL_ERROR_WANT_WRITE) {
545 /* SSL handshake needs to write, L4 connection may not be ready */
546 __conn_sock_stop_recv(conn);
547 __conn_sock_poll_send(conn);
548 return 0;
549 }
550 else if (ret == SSL_ERROR_WANT_READ) {
551 /* SSL handshake needs to read, L4 connection is ready */
552 if (conn->flags & CO_FL_WAIT_L4_CONN)
553 conn->flags &= ~CO_FL_WAIT_L4_CONN;
554 __conn_sock_stop_send(conn);
555 __conn_sock_poll_recv(conn);
556 return 0;
557 }
558 else {
559 /* Fail on all other handshake errors */
560 goto out_error;
561 }
562 }
563
564 /* Handshake succeeded */
565 if (target_srv(&conn->target)) {
566 if (!SSL_session_reused(conn->data_ctx)) {
567 /* check if session was reused, if not store current session on server for reuse */
568 if (target_srv(&conn->target)->ssl_ctx.reused_sess)
569 SSL_SESSION_free(target_srv(&conn->target)->ssl_ctx.reused_sess);
570
571 target_srv(&conn->target)->ssl_ctx.reused_sess = SSL_get1_session(conn->data_ctx);
572 }
573 }
574
575 /* The connection is now established at both layers, it's time to leave */
576 conn->flags &= ~(flag | CO_FL_WAIT_L4_CONN | CO_FL_WAIT_L6_CONN);
577 return 1;
578
579 out_error:
580 /* Fail on all other handshake errors */
581 conn->flags |= CO_FL_ERROR;
582 conn->flags &= ~flag;
583 return 0;
584}
585
586/* Receive up to <count> bytes from connection <conn>'s socket and store them
587 * into buffer <buf>. The caller must ensure that <count> is always smaller
588 * than the buffer's size. Only one call to recv() is performed, unless the
589 * buffer wraps, in which case a second call may be performed. The connection's
590 * flags are updated with whatever special event is detected (error, read0,
591 * empty). The caller is responsible for taking care of those events and
592 * avoiding the call if inappropriate. The function does not call the
593 * connection's polling update function, so the caller is responsible for this.
594 */
595static int ssl_sock_to_buf(struct connection *conn, struct buffer *buf, int count)
596{
597 int ret, done = 0;
598 int try = count;
599
600 if (!conn->data_ctx)
601 goto out_error;
602
603 if (conn->flags & CO_FL_HANDSHAKE)
604 /* a handshake was requested */
605 return 0;
606
607 /* compute the maximum block size we can read at once. */
608 if (buffer_empty(buf)) {
609 /* let's realign the buffer to optimize I/O */
610 buf->p = buf->data;
611 }
612 else if (buf->data + buf->o < buf->p &&
613 buf->p + buf->i < buf->data + buf->size) {
614 /* remaining space wraps at the end, with a moving limit */
615 if (try > buf->data + buf->size - (buf->p + buf->i))
616 try = buf->data + buf->size - (buf->p + buf->i);
617 }
618
619 /* read the largest possible block. For this, we perform only one call
620 * to recv() unless the buffer wraps and we exactly fill the first hunk,
621 * in which case we accept to do it once again. A new attempt is made on
622 * EINTR too.
623 */
624 while (try) {
625 ret = SSL_read(conn->data_ctx, bi_end(buf), try);
Emeric Brune1f38db2012-09-03 20:36:47 +0200626 if (conn->flags & CO_FL_ERROR) {
627 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
628 break;
629 }
Emeric Brun46591952012-05-18 15:47:34 +0200630 if (ret > 0) {
631 buf->i += ret;
632 done += ret;
633 if (ret < try)
634 break;
635 count -= ret;
636 try = count;
637 }
638 else if (ret == 0) {
639 goto read0;
640 }
641 else {
642 ret = SSL_get_error(conn->data_ctx, ret);
643 if (ret == SSL_ERROR_WANT_WRITE) {
644 /* handshake is running, and it needs to poll for a write event */
645 conn->flags |= CO_FL_SSL_WAIT_HS;
646 __conn_sock_poll_send(conn);
647 break;
648 }
649 else if (ret == SSL_ERROR_WANT_READ) {
650 /* we need to poll for retry a read later */
651 __conn_data_poll_recv(conn);
652 break;
653 }
654 /* otherwise it's a real error */
655 goto out_error;
656 }
657 }
658 return done;
659
660 read0:
661 conn_sock_read0(conn);
662 return done;
663 out_error:
664 conn->flags |= CO_FL_ERROR;
665 return done;
666}
667
668
669/* Send all pending bytes from buffer <buf> to connection <conn>'s socket.
670 * <flags> may contain MSG_MORE to make the system hold on without sending
671 * data too fast, but this flag is ignored at the moment.
672 * Only one call to send() is performed, unless the buffer wraps, in which case
673 * a second call may be performed. The connection's flags are updated with
674 * whatever special event is detected (error, empty). The caller is responsible
675 * for taking care of those events and avoiding the call if inappropriate. The
676 * function does not call the connection's polling update function, so the caller
677 * is responsible for this.
678 */
679static int ssl_sock_from_buf(struct connection *conn, struct buffer *buf, int flags)
680{
681 int ret, try, done;
682
683 done = 0;
684
685 if (!conn->data_ctx)
686 goto out_error;
687
688 if (conn->flags & CO_FL_HANDSHAKE)
689 /* a handshake was requested */
690 return 0;
691
692 /* send the largest possible block. For this we perform only one call
693 * to send() unless the buffer wraps and we exactly fill the first hunk,
694 * in which case we accept to do it once again.
695 */
696 while (buf->o) {
697 try = buf->o;
698 /* outgoing data may wrap at the end */
699 if (buf->data + try > buf->p)
700 try = buf->data + try - buf->p;
701
702 ret = SSL_write(conn->data_ctx, bo_ptr(buf), try);
Emeric Brune1f38db2012-09-03 20:36:47 +0200703 if (conn->flags & CO_FL_ERROR) {
704 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
705 break;
706 }
Emeric Brun46591952012-05-18 15:47:34 +0200707 if (ret > 0) {
708 buf->o -= ret;
709 done += ret;
710
711 if (likely(!buffer_len(buf)))
712 /* optimize data alignment in the buffer */
713 buf->p = buf->data;
714
715 /* if the system buffer is full, don't insist */
716 if (ret < try)
717 break;
718 }
719 else {
720 ret = SSL_get_error(conn->data_ctx, ret);
721 if (ret == SSL_ERROR_WANT_WRITE) {
722 /* we need to poll to retry a write later */
723 __conn_data_poll_send(conn);
724 break;
725 }
726 else if (ret == SSL_ERROR_WANT_READ) {
727 /* handshake is running, and
728 it needs to poll for a read event,
729 write polling must be disabled cause
730 we are sure we can't write anything more
731 before handshake re-performed */
732 conn->flags |= CO_FL_SSL_WAIT_HS;
733 __conn_sock_poll_recv(conn);
734 break;
735 }
736 goto out_error;
737 }
738 }
739 return done;
740
741 out_error:
742 conn->flags |= CO_FL_ERROR;
743 return done;
744}
745
746
747static void ssl_sock_close(struct connection *conn) {
748
749 if (conn->data_ctx) {
750 SSL_free(conn->data_ctx);
751 conn->data_ctx = NULL;
Willy Tarreau403edff2012-09-06 11:58:37 +0200752 sslconns--;
Emeric Brun46591952012-05-18 15:47:34 +0200753 }
Emeric Brun46591952012-05-18 15:47:34 +0200754}
755
756/* This function tries to perform a clean shutdown on an SSL connection, and in
757 * any case, flags the connection as reusable if no handshake was in progress.
758 */
759static void ssl_sock_shutw(struct connection *conn, int clean)
760{
761 if (conn->flags & CO_FL_HANDSHAKE)
762 return;
763 /* no handshake was in progress, try a clean ssl shutdown */
764 if (clean)
765 SSL_shutdown(conn->data_ctx);
766
767 /* force flag on ssl to keep session in cache regardless shutdown result */
768 SSL_set_shutdown(conn->data_ctx, SSL_SENT_SHUTDOWN);
769}
770
Willy Tarreau7875d092012-09-10 08:20:03 +0200771/***** Below are some sample fetching functions for ACL/patterns *****/
772
773/* boolean, returns true if data layer is SSL */
774static int
775smp_fetch_is_ssl(struct proxy *px, struct session *l4, void *l7, unsigned int opt,
776 const struct arg *args, struct sample *smp)
777{
778 smp->type = SMP_T_BOOL;
779 smp->data.uint = (l4->si[0].conn.data == &ssl_sock);
780 return 1;
781}
782
783/* boolean, returns true if data layer is SSL */
784static int
785smp_fetch_has_sni(struct proxy *px, struct session *l4, void *l7, unsigned int opt,
786 const struct arg *args, struct sample *smp)
787{
788#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
789 smp->type = SMP_T_BOOL;
790 smp->data.uint = (l4->si[0].conn.data == &ssl_sock) &&
Willy Tarreau3e394c92012-09-14 23:56:58 +0200791 l4->si[0].conn.data_ctx &&
Willy Tarreau7875d092012-09-10 08:20:03 +0200792 SSL_get_servername(l4->si[0].conn.data_ctx, TLSEXT_NAMETYPE_host_name) != NULL;
793 return 1;
794#else
795 return 0;
796#endif
797}
798
799static int
800smp_fetch_ssl_sni(struct proxy *px, struct session *l4, void *l7, unsigned int opt,
801 const struct arg *args, struct sample *smp)
802{
803#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
804 smp->flags = 0;
805 smp->type = SMP_T_CSTR;
806
Willy Tarreau3e394c92012-09-14 23:56:58 +0200807 if (!l4 || !l4->si[0].conn.data_ctx || l4->si[0].conn.data != &ssl_sock)
Willy Tarreau7875d092012-09-10 08:20:03 +0200808 return 0;
809
Willy Tarreau7875d092012-09-10 08:20:03 +0200810 smp->data.str.str = (char *)SSL_get_servername(l4->si[0].conn.data_ctx, TLSEXT_NAMETYPE_host_name);
Willy Tarreau3e394c92012-09-14 23:56:58 +0200811 if (!smp->data.str.str)
812 return 0;
813
Willy Tarreau7875d092012-09-10 08:20:03 +0200814 smp->data.str.len = strlen(smp->data.str.str);
815 return 1;
816#else
817 return 0;
818#endif
819}
820
Willy Tarreau79eeafa2012-09-14 07:53:05 +0200821/* parse the "ciphers" bind keyword */
822static int bind_parse_ciphers(char **args, int cur_arg, struct proxy *px, struct listener *last, char **err)
823{
824 if (!*args[cur_arg + 1]) {
825 if (err)
826 memprintf(err, "'%s' : missing cipher suite", args[cur_arg]);
827 return ERR_ALERT | ERR_FATAL;
828 }
829
830 px->listen->bind_conf->ciphers = strdup(args[cur_arg + 1]);
831 return 0;
832}
833
834/* parse the "crt" bind keyword */
835static int bind_parse_crt(char **args, int cur_arg, struct proxy *px, struct listener *last, char **err)
836{
837 if (!*args[cur_arg + 1]) {
838 if (err)
839 memprintf(err, "'%s' : missing certificate location", args[cur_arg]);
840 return ERR_ALERT | ERR_FATAL;
841 }
842
843 if (ssl_sock_load_cert(args[cur_arg + 1], px->listen->bind_conf, px, err) > 0)
844 return ERR_ALERT | ERR_FATAL;
845
846 return 0;
847}
848
849/* parse the "nosslv3" bind keyword */
850static int bind_parse_nosslv3(char **args, int cur_arg, struct proxy *px, struct listener *last, char **err)
851{
852 px->listen->bind_conf->nosslv3 = 1;
853 return 0;
854}
855
856/* parse the "notlsv1" bind keyword */
857static int bind_parse_notlsv1(char **args, int cur_arg, struct proxy *px, struct listener *last, char **err)
858{
859 px->listen->bind_conf->notlsv1 = 1;
860 return 0;
861}
862
863/* parse the "prefer-server-ciphers" bind keyword */
864static int bind_parse_psc(char **args, int cur_arg, struct proxy *px, struct listener *last, char **err)
865{
866 px->listen->bind_conf->prefer_server_ciphers = 1;
867 return 0;
868}
869
870/* parse the "ssl" bind keyword */
871static int bind_parse_ssl(char **args, int cur_arg, struct proxy *px, struct listener *last, char **err)
872{
873 px->listen->bind_conf->is_ssl = 1;
874 return 0;
875}
876
Willy Tarreau7875d092012-09-10 08:20:03 +0200877/* Note: must not be declared <const> as its list will be overwritten.
878 * Please take care of keeping this list alphabetically sorted.
879 */
880static struct sample_fetch_kw_list sample_fetch_keywords = {{ },{
881 { "is_ssl", smp_fetch_is_ssl, 0, NULL, SMP_T_BOOL, SMP_CAP_REQ|SMP_CAP_RES },
882 { "ssl_has_sni", smp_fetch_has_sni, 0, NULL, SMP_T_BOOL, SMP_CAP_REQ|SMP_CAP_RES },
883 { "ssl_sni", smp_fetch_ssl_sni, 0, NULL, SMP_T_CSTR, SMP_CAP_REQ|SMP_CAP_RES },
884 { NULL, NULL, 0, 0, 0 },
885}};
886
887/* Note: must not be declared <const> as its list will be overwritten.
888 * Please take care of keeping this list alphabetically sorted.
889 */
890static struct acl_kw_list acl_kws = {{ },{
891 { "is_ssl", acl_parse_int, smp_fetch_is_ssl, acl_match_nothing, ACL_USE_L6REQ_PERMANENT, 0 },
892 { "ssl_has_sni", acl_parse_int, smp_fetch_has_sni, acl_match_nothing, ACL_USE_L6REQ_PERMANENT, 0 },
893 { "ssl_sni", acl_parse_str, smp_fetch_ssl_sni, acl_match_str, ACL_USE_L6REQ_PERMANENT|ACL_MAY_LOOKUP, 0 },
894 { "ssl_sni_end", acl_parse_str, smp_fetch_ssl_sni, acl_match_end, ACL_USE_L6REQ_PERMANENT|ACL_MAY_LOOKUP, 0 },
895 { "ssl_sni_reg", acl_parse_str, smp_fetch_ssl_sni, acl_match_reg, ACL_USE_L6REQ_PERMANENT|ACL_MAY_LOOKUP, 0 },
896 { NULL, NULL, NULL, NULL },
897}};
898
Willy Tarreau79eeafa2012-09-14 07:53:05 +0200899/* Note: must not be declared <const> as its list will be overwritten.
900 * Please take care of keeping this list alphabetically sorted, doing so helps
901 * all code contributors.
902 * Optional keywords are also declared with a NULL ->parse() function so that
903 * the config parser can report an appropriate error when a known keyword was
904 * not enabled.
905 */
Willy Tarreau51fb7652012-09-18 18:24:39 +0200906static struct bind_kw_list bind_kws = { "SSL", { }, {
Willy Tarreau79eeafa2012-09-14 07:53:05 +0200907 { "ciphers", bind_parse_ciphers, 1 }, /* set SSL cipher suite */
908 { "crt", bind_parse_crt, 1 }, /* load SSL certificates from this location */
909 { "nosslv3", bind_parse_nosslv3, 0 }, /* disable SSLv3 */
910 { "notlsv1", bind_parse_notlsv1, 0 }, /* disable TLSv1 */
911 { "prefer-server-ciphers", bind_parse_psc, 0 }, /* prefer server ciphers */
912 { "ssl", bind_parse_ssl, 0 }, /* enable SSL processing */
913 { NULL, NULL, 0 },
914}};
Emeric Brun46591952012-05-18 15:47:34 +0200915
916/* data-layer operations for SSL sockets */
917struct data_ops ssl_sock = {
918 .snd_buf = ssl_sock_from_buf,
919 .rcv_buf = ssl_sock_to_buf,
920 .rcv_pipe = NULL,
921 .snd_pipe = NULL,
922 .shutr = NULL,
923 .shutw = ssl_sock_shutw,
924 .close = ssl_sock_close,
925 .init = ssl_sock_init,
926};
927
928__attribute__((constructor))
929static void __ssl_sock_init(void) {
930 STACK_OF(SSL_COMP)* cm;
931
932 SSL_library_init();
933 cm = SSL_COMP_get_compression_methods();
934 sk_SSL_COMP_zero(cm);
Willy Tarreau7875d092012-09-10 08:20:03 +0200935 sample_register_fetches(&sample_fetch_keywords);
936 acl_register_keywords(&acl_kws);
Willy Tarreau79eeafa2012-09-14 07:53:05 +0200937 bind_register_keywords(&bind_kws);
Emeric Brun46591952012-05-18 15:47:34 +0200938}
939
940/*
941 * Local variables:
942 * c-indent-level: 8
943 * c-basic-offset: 8
944 * End:
945 */