1
2 /*
3 * SSL/TLS transport layer over SOCK_STREAM sockets
4 *
5 * Copyright (C) 2012 EXCELIANCE, Emeric Brun <ebrun@exceliance.fr>
6 *
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version
10 * 2 of the License, or (at your option) any later version.
11 *
12 * Acknowledgement:
13 * We'd like to specially thank the Stud project authors for a very clean
14 * and well documented code which helped us understand how the OpenSSL API
15 * ought to be used in non-blocking mode. This is one difficult part which
16 * is not easy to get from the OpenSSL doc, and reading the Stud code made
17 * it much more obvious than the examples in the OpenSSL package. Keep up
18 * the good works, guys !
19 *
20 * Stud is an extremely efficient and scalable SSL/TLS proxy which combines
21 * particularly well with haproxy. For more info about this project, visit :
22 * https://github.com/bumptech/stud
23 *
24 */
25
26 #define _GNU_SOURCE
27 #include <ctype.h>
28 #include <dirent.h>
29 #include <errno.h>
30 #include <fcntl.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <unistd.h>
35
36 #include <sys/socket.h>
37 #include <sys/stat.h>
38 #include <sys/types.h>
39 #include <netdb.h>
40 #include <netinet/tcp.h>
41
42 #include <openssl/crypto.h>
43 #include <openssl/ssl.h>
44 #include <openssl/x509.h>
45 #include <openssl/x509v3.h>
46 #include <openssl/err.h>
47 #include <openssl/rand.h>
48 #if (defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP)
49 #include <openssl/ocsp.h>
50 #endif
51 #ifndef OPENSSL_NO_DH
52 #include <openssl/dh.h>
53 #endif
54
55 #include <import/lru.h>
56 #include <import/xxhash.h>
57
58 #include <common/buffer.h>
59 #include <common/compat.h>
60 #include <common/config.h>
61 #include <common/debug.h>
62 #include <common/errors.h>
63 #include <common/standard.h>
64 #include <common/ticks.h>
65 #include <common/time.h>
66 #include <common/cfgparse.h>
67 #include <common/base64.h>
68
69 #include <ebsttree.h>
70
71 #include <types/applet.h>
72 #include <types/cli.h>
73 #include <types/global.h>
74 #include <types/ssl_sock.h>
75 #include <types/stats.h>
76
77 #include <proto/acl.h>
78 #include <proto/arg.h>
79 #include <proto/channel.h>
80 #include <proto/connection.h>
81 #include <proto/cli.h>
82 #include <proto/fd.h>
83 #include <proto/freq_ctr.h>
84 #include <proto/frontend.h>
85 #include <proto/listener.h>
86 #include <proto/openssl-compat.h>
87 #include <proto/pattern.h>
88 #include <proto/proto_tcp.h>
89 #include <proto/server.h>
90 #include <proto/stream_interface.h>
91 #include <proto/log.h>
92 #include <proto/proxy.h>
93 #include <proto/shctx.h>
94 #include <proto/ssl_sock.h>
95 #include <proto/stream.h>
96 #include <proto/task.h>
97
98 /* Warning, these are bits, not integers! */
99 #define SSL_SOCK_ST_FL_VERIFY_DONE 0x00000001
100 #define SSL_SOCK_ST_FL_16K_WBFSIZE 0x00000002
101 #define SSL_SOCK_SEND_UNLIMITED 0x00000004
102 #define SSL_SOCK_RECV_HEARTBEAT 0x00000008
103
104 /* bits 0xFFFF0000 are reserved to store verify errors */
105
106 /* Verify errors macros */
107 #define SSL_SOCK_CA_ERROR_TO_ST(e) (((e > 63) ? 63 : e) << (16))
108 #define SSL_SOCK_CAEDEPTH_TO_ST(d) (((d > 15) ? 15 : d) << (6+16))
109 #define SSL_SOCK_CRTERROR_TO_ST(e) (((e > 63) ? 63 : e) << (4+6+16))
110
111 #define SSL_SOCK_ST_TO_CA_ERROR(s) ((s >> (16)) & 63)
112 #define SSL_SOCK_ST_TO_CAEDEPTH(s) ((s >> (6+16)) & 15)
113 #define SSL_SOCK_ST_TO_CRTERROR(s) ((s >> (4+6+16)) & 63)
114
115 /* Supported hash function for TLS tickets */
116 #ifdef OPENSSL_NO_SHA256
117 #define HASH_FUNCT EVP_sha1
118 #else
119 #define HASH_FUNCT EVP_sha256
120 #endif /* OPENSSL_NO_SHA256 */
121
122 /* server and bind verify method, it uses a global value as default */
123 enum {
124 SSL_SOCK_VERIFY_DEFAULT = 0,
125 SSL_SOCK_VERIFY_REQUIRED = 1,
126 SSL_SOCK_VERIFY_OPTIONAL = 2,
127 SSL_SOCK_VERIFY_NONE = 3,
128 };
129
130 int sslconns = 0;
131 int totalsslconns = 0;
132
133 #if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
134 struct list tlskeys_reference = LIST_HEAD_INIT(tlskeys_reference);
135 #endif
136
137 #ifndef OPENSSL_NO_DH
138 static int ssl_dh_ptr_index = -1;
139 static DH *global_dh = NULL;
140 static DH *local_dh_1024 = NULL;
141 static DH *local_dh_2048 = NULL;
142 static DH *local_dh_4096 = NULL;
143 #endif /* OPENSSL_NO_DH */
144
145 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
146 /* X509V3 Extensions that will be added on generated certificates */
147 #define X509V3_EXT_SIZE 5
148 static char *x509v3_ext_names[X509V3_EXT_SIZE] = {
149 "basicConstraints",
150 "nsComment",
151 "subjectKeyIdentifier",
152 "authorityKeyIdentifier",
153 "keyUsage",
154 };
155 static char *x509v3_ext_values[X509V3_EXT_SIZE] = {
156 "CA:FALSE",
157 "\"OpenSSL Generated Certificate\"",
158 "hash",
159 "keyid,issuer:always",
160 "nonRepudiation,digitalSignature,keyEncipherment"
161 };
162
163 /* LRU cache to store generated certificate */
164 static struct lru64_head *ssl_ctx_lru_tree = NULL;
165 static unsigned int ssl_ctx_lru_seed = 0;
166 #endif // SSL_CTRL_SET_TLSEXT_HOSTNAME
167
168 #if OPENSSL_VERSION_NUMBER >= 0x1000200fL
169 /* The order here matters for picking a default context,
170 * keep the most common keytype at the bottom of the list
171 */
172 const char *SSL_SOCK_KEYTYPE_NAMES[] = {
173 "dsa",
174 "ecdsa",
175 "rsa"
176 };
177 #define SSL_SOCK_NUM_KEYTYPES 3
178 #else
179 #define SSL_SOCK_NUM_KEYTYPES 1
180 #endif
181
182 #if (defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP)
183 /*
184 * struct alignment works here such that the key.key is the same as key_data
185 * Do not change the placement of key_data
186 */
187 struct certificate_ocsp {
188 struct ebmb_node key;
189 unsigned char key_data[OCSP_MAX_CERTID_ASN1_LENGTH];
190 struct chunk response;
191 long expire;
192 };
193
194 struct ocsp_cbk_arg {
195 int is_single;
196 int single_kt;
197 union {
198 struct certificate_ocsp *s_ocsp;
199 /*
200 * m_ocsp will have multiple entries dependent on key type
201 * Entry 0 - DSA
202 * Entry 1 - ECDSA
203 * Entry 2 - RSA
204 */
205 struct certificate_ocsp *m_ocsp[SSL_SOCK_NUM_KEYTYPES];
206 };
207 };
208
209 /*
210 * This function gives the detail of the SSL error. It is used only
211 * if the debug mode and the verbose mode are activated. It dump all
212 * the SSL error until the stack was empty.
213 */
ssl_sock_dump_errors(struct connection * conn)214 static forceinline void ssl_sock_dump_errors(struct connection *conn)
215 {
216 unsigned long ret;
217
218 if (unlikely(global.mode & MODE_DEBUG)) {
219 while(1) {
220 ret = ERR_get_error();
221 if (ret == 0)
222 return;
223 fprintf(stderr, "fd[%#x] OpenSSL error[0x%lx] %s: %s\n",
224 conn->t.sock.fd, ret,
225 ERR_func_error_string(ret), ERR_reason_error_string(ret));
226 }
227 }
228 }
229
230 /*
231 * This function returns the number of seconds elapsed
232 * since the Epoch, 1970-01-01 00:00:00 +0000 (UTC) and the
233 * date presented un ASN1_GENERALIZEDTIME.
234 *
235 * In parsing error case, it returns -1.
236 */
asn1_generalizedtime_to_epoch(ASN1_GENERALIZEDTIME * d)237 static long asn1_generalizedtime_to_epoch(ASN1_GENERALIZEDTIME *d)
238 {
239 long epoch;
240 char *p, *end;
241 const unsigned short month_offset[12] = {
242 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
243 };
244 int year, month;
245
246 if (!d || (d->type != V_ASN1_GENERALIZEDTIME)) return -1;
247
248 p = (char *)d->data;
249 end = p + d->length;
250
251 if (end - p < 4) return -1;
252 year = 1000 * (p[0] - '0') + 100 * (p[1] - '0') + 10 * (p[2] - '0') + p[3] - '0';
253 p += 4;
254 if (end - p < 2) return -1;
255 month = 10 * (p[0] - '0') + p[1] - '0';
256 if (month < 1 || month > 12) return -1;
257 /* Compute the number of seconds since 1 jan 1970 and the beginning of current month
258 We consider leap years and the current month (<marsh or not) */
259 epoch = ( ((year - 1970) * 365)
260 + ((year - (month < 3)) / 4 - (year - (month < 3)) / 100 + (year - (month < 3)) / 400)
261 - ((1970 - 1) / 4 - (1970 - 1) / 100 + (1970 - 1) / 400)
262 + month_offset[month-1]
263 ) * 24 * 60 * 60;
264 p += 2;
265 if (end - p < 2) return -1;
266 /* Add the number of seconds of completed days of current month */
267 epoch += (10 * (p[0] - '0') + p[1] - '0' - 1) * 24 * 60 * 60;
268 p += 2;
269 if (end - p < 2) return -1;
270 /* Add the completed hours of the current day */
271 epoch += (10 * (p[0] - '0') + p[1] - '0') * 60 * 60;
272 p += 2;
273 if (end - p < 2) return -1;
274 /* Add the completed minutes of the current hour */
275 epoch += (10 * (p[0] - '0') + p[1] - '0') * 60;
276 p += 2;
277 if (p == end) return -1;
278 /* Test if there is available seconds */
279 if (p[0] < '0' || p[0] > '9')
280 goto nosec;
281 if (end - p < 2) return -1;
282 /* Add the seconds of the current minute */
283 epoch += 10 * (p[0] - '0') + p[1] - '0';
284 p += 2;
285 if (p == end) return -1;
286 /* Ignore seconds float part if present */
287 if (p[0] == '.') {
288 do {
289 if (++p == end) return -1;
290 } while (p[0] >= '0' && p[0] <= '9');
291 }
292
293 nosec:
294 if (p[0] == 'Z') {
295 if (end - p != 1) return -1;
296 return epoch;
297 }
298 else if (p[0] == '+') {
299 if (end - p != 5) return -1;
300 /* Apply timezone offset */
301 return epoch - ((10 * (p[1] - '0') + p[2] - '0') * 60 * 60 + (10 * (p[3] - '0') + p[4] - '0')) * 60;
302 }
303 else if (p[0] == '-') {
304 if (end - p != 5) return -1;
305 /* Apply timezone offset */
306 return epoch + ((10 * (p[1] - '0') + p[2] - '0') * 60 * 60 + (10 * (p[3] - '0') + p[4] - '0')) * 60;
307 }
308
309 return -1;
310 }
311
312 static struct eb_root cert_ocsp_tree = EB_ROOT_UNIQUE;
313
314 /* This function starts to check if the OCSP response (in DER format) contained
315 * in chunk 'ocsp_response' is valid (else exits on error).
316 * If 'cid' is not NULL, it will be compared to the OCSP certificate ID
317 * contained in the OCSP Response and exits on error if no match.
318 * If it's a valid OCSP Response:
319 * If 'ocsp' is not NULL, the chunk is copied in the OCSP response's container
320 * pointed by 'ocsp'.
321 * If 'ocsp' is NULL, the function looks up into the OCSP response's
322 * containers tree (using as index the ASN1 form of the OCSP Certificate ID extracted
323 * from the response) and exits on error if not found. Finally, If an OCSP response is
324 * already present in the container, it will be overwritten.
325 *
326 * Note: OCSP response containing more than one OCSP Single response is not
327 * considered valid.
328 *
329 * Returns 0 on success, 1 in error case.
330 */
ssl_sock_load_ocsp_response(struct chunk * ocsp_response,struct certificate_ocsp * ocsp,OCSP_CERTID * cid,char ** err)331 static int ssl_sock_load_ocsp_response(struct chunk *ocsp_response, struct certificate_ocsp *ocsp, OCSP_CERTID *cid, char **err)
332 {
333 OCSP_RESPONSE *resp;
334 OCSP_BASICRESP *bs = NULL;
335 OCSP_SINGLERESP *sr;
336 OCSP_CERTID *id;
337 unsigned char *p = (unsigned char *)ocsp_response->str;
338 int rc , count_sr;
339 ASN1_GENERALIZEDTIME *revtime, *thisupd, *nextupd = NULL;
340 int reason;
341 int ret = 1;
342
343 resp = d2i_OCSP_RESPONSE(NULL, (const unsigned char **)&p, ocsp_response->len);
344 if (!resp) {
345 memprintf(err, "Unable to parse OCSP response");
346 goto out;
347 }
348
349 rc = OCSP_response_status(resp);
350 if (rc != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
351 memprintf(err, "OCSP response status not successful");
352 goto out;
353 }
354
355 bs = OCSP_response_get1_basic(resp);
356 if (!bs) {
357 memprintf(err, "Failed to get basic response from OCSP Response");
358 goto out;
359 }
360
361 count_sr = OCSP_resp_count(bs);
362 if (count_sr > 1) {
363 memprintf(err, "OCSP response ignored because contains multiple single responses (%d)", count_sr);
364 goto out;
365 }
366
367 sr = OCSP_resp_get0(bs, 0);
368 if (!sr) {
369 memprintf(err, "Failed to get OCSP single response");
370 goto out;
371 }
372
373 id = (OCSP_CERTID*)OCSP_SINGLERESP_get0_id(sr);
374
375 rc = OCSP_single_get0_status(sr, &reason, &revtime, &thisupd, &nextupd);
376 if (rc != V_OCSP_CERTSTATUS_GOOD && rc != V_OCSP_CERTSTATUS_REVOKED) {
377 memprintf(err, "OCSP single response: certificate status is unknown");
378 goto out;
379 }
380
381 if (!nextupd) {
382 memprintf(err, "OCSP single response: missing nextupdate");
383 goto out;
384 }
385
386 rc = OCSP_check_validity(thisupd, nextupd, OCSP_MAX_RESPONSE_TIME_SKEW, -1);
387 if (!rc) {
388 memprintf(err, "OCSP single response: no longer valid.");
389 goto out;
390 }
391
392 if (cid) {
393 if (OCSP_id_cmp(id, cid)) {
394 memprintf(err, "OCSP single response: Certificate ID does not match certificate and issuer");
395 goto out;
396 }
397 }
398
399 if (!ocsp) {
400 unsigned char key[OCSP_MAX_CERTID_ASN1_LENGTH];
401 unsigned char *p;
402
403 rc = i2d_OCSP_CERTID(id, NULL);
404 if (!rc) {
405 memprintf(err, "OCSP single response: Unable to encode Certificate ID");
406 goto out;
407 }
408
409 if (rc > OCSP_MAX_CERTID_ASN1_LENGTH) {
410 memprintf(err, "OCSP single response: Certificate ID too long");
411 goto out;
412 }
413
414 p = key;
415 memset(key, 0, OCSP_MAX_CERTID_ASN1_LENGTH);
416 i2d_OCSP_CERTID(id, &p);
417 ocsp = (struct certificate_ocsp *)ebmb_lookup(&cert_ocsp_tree, key, OCSP_MAX_CERTID_ASN1_LENGTH);
418 if (!ocsp) {
419 memprintf(err, "OCSP single response: Certificate ID does not match any certificate or issuer");
420 goto out;
421 }
422 }
423
424 /* According to comments on "chunk_dup", the
425 previous chunk buffer will be freed */
426 if (!chunk_dup(&ocsp->response, ocsp_response)) {
427 memprintf(err, "OCSP response: Memory allocation error");
428 goto out;
429 }
430
431 ocsp->expire = asn1_generalizedtime_to_epoch(nextupd) - OCSP_MAX_RESPONSE_TIME_SKEW;
432
433 ret = 0;
434 out:
435 ERR_clear_error();
436
437 if (bs)
438 OCSP_BASICRESP_free(bs);
439
440 if (resp)
441 OCSP_RESPONSE_free(resp);
442
443 return ret;
444 }
445 /*
446 * External function use to update the OCSP response in the OCSP response's
447 * containers tree. The chunk 'ocsp_response' must contain the OCSP response
448 * to update in DER format.
449 *
450 * Returns 0 on success, 1 in error case.
451 */
ssl_sock_update_ocsp_response(struct chunk * ocsp_response,char ** err)452 int ssl_sock_update_ocsp_response(struct chunk *ocsp_response, char **err)
453 {
454 return ssl_sock_load_ocsp_response(ocsp_response, NULL, NULL, err);
455 }
456
457 /*
458 * This function load the OCSP Resonse in DER format contained in file at
459 * path 'ocsp_path' and call 'ssl_sock_load_ocsp_response'
460 *
461 * Returns 0 on success, 1 in error case.
462 */
ssl_sock_load_ocsp_response_from_file(const char * ocsp_path,struct certificate_ocsp * ocsp,OCSP_CERTID * cid,char ** err)463 static int ssl_sock_load_ocsp_response_from_file(const char *ocsp_path, struct certificate_ocsp *ocsp, OCSP_CERTID *cid, char **err)
464 {
465 int fd = -1;
466 int r = 0;
467 int ret = 1;
468
469 fd = open(ocsp_path, O_RDONLY);
470 if (fd == -1) {
471 memprintf(err, "Error opening OCSP response file");
472 goto end;
473 }
474
475 trash.len = 0;
476 while (trash.len < trash.size) {
477 r = read(fd, trash.str + trash.len, trash.size - trash.len);
478 if (r < 0) {
479 if (errno == EINTR)
480 continue;
481
482 memprintf(err, "Error reading OCSP response from file");
483 goto end;
484 }
485 else if (r == 0) {
486 break;
487 }
488 trash.len += r;
489 }
490
491 close(fd);
492 fd = -1;
493
494 ret = ssl_sock_load_ocsp_response(&trash, ocsp, cid, err);
495 end:
496 if (fd != -1)
497 close(fd);
498
499 return ret;
500 }
501
502 #if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
ssl_tlsext_ticket_key_cb(SSL * s,unsigned char key_name[16],unsigned char * iv,EVP_CIPHER_CTX * ectx,HMAC_CTX * hctx,int enc)503 static int ssl_tlsext_ticket_key_cb(SSL *s, unsigned char key_name[16], unsigned char *iv, EVP_CIPHER_CTX *ectx, HMAC_CTX *hctx, int enc)
504 {
505 struct tls_sess_key *keys;
506 struct connection *conn;
507 int head;
508 int i;
509
510 conn = SSL_get_app_data(s);
511 keys = objt_listener(conn->target)->bind_conf->keys_ref->tlskeys;
512 head = objt_listener(conn->target)->bind_conf->keys_ref->tls_ticket_enc_index;
513
514 if (enc) {
515 memcpy(key_name, keys[head].name, 16);
516
517 if(!RAND_pseudo_bytes(iv, EVP_MAX_IV_LENGTH))
518 return -1;
519
520 if(!EVP_EncryptInit_ex(ectx, EVP_aes_128_cbc(), NULL, keys[head].aes_key, iv))
521 return -1;
522
523 HMAC_Init_ex(hctx, keys[head].hmac_key, 16, HASH_FUNCT(), NULL);
524
525 return 1;
526 } else {
527 for (i = 0; i < TLS_TICKETS_NO; i++) {
528 if (!memcmp(key_name, keys[(head + i) % TLS_TICKETS_NO].name, 16))
529 goto found;
530 }
531 return 0;
532
533 found:
534 HMAC_Init_ex(hctx, keys[(head + i) % TLS_TICKETS_NO].hmac_key, 16, HASH_FUNCT(), NULL);
535 if(!EVP_DecryptInit_ex(ectx, EVP_aes_128_cbc(), NULL, keys[(head + i) % TLS_TICKETS_NO].aes_key, iv))
536 return -1;
537 /* 2 for key renewal, 1 if current key is still valid */
538 return i ? 2 : 1;
539 }
540 }
541
tlskeys_ref_lookup(const char * filename)542 struct tls_keys_ref *tlskeys_ref_lookup(const char *filename)
543 {
544 struct tls_keys_ref *ref;
545
546 list_for_each_entry(ref, &tlskeys_reference, list)
547 if (ref->filename && strcmp(filename, ref->filename) == 0)
548 return ref;
549 return NULL;
550 }
551
tlskeys_ref_lookupid(int unique_id)552 struct tls_keys_ref *tlskeys_ref_lookupid(int unique_id)
553 {
554 struct tls_keys_ref *ref;
555
556 list_for_each_entry(ref, &tlskeys_reference, list)
557 if (ref->unique_id == unique_id)
558 return ref;
559 return NULL;
560 }
561
ssl_sock_update_tlskey(char * filename,struct chunk * tlskey,char ** err)562 int ssl_sock_update_tlskey(char *filename, struct chunk *tlskey, char **err) {
563 struct tls_keys_ref *ref = tlskeys_ref_lookup(filename);
564
565 if(!ref) {
566 memprintf(err, "Unable to locate the referenced filename: %s", filename);
567 return 1;
568 }
569
570 memcpy((char *) (ref->tlskeys + ((ref->tls_ticket_enc_index + 2) % TLS_TICKETS_NO)), tlskey->str, tlskey->len);
571 ref->tls_ticket_enc_index = (ref->tls_ticket_enc_index + 1) % TLS_TICKETS_NO;
572
573 return 0;
574 }
575
576 /* This function finalize the configuration parsing. Its set all the
577 * automatic ids
578 */
tlskeys_finalize_config(void)579 void tlskeys_finalize_config(void)
580 {
581 int i = 0;
582 struct tls_keys_ref *ref, *ref2, *ref3;
583 struct list tkr = LIST_HEAD_INIT(tkr);
584
585 list_for_each_entry(ref, &tlskeys_reference, list) {
586 if (ref->unique_id == -1) {
587 /* Look for the first free id. */
588 while (1) {
589 list_for_each_entry(ref2, &tlskeys_reference, list) {
590 if (ref2->unique_id == i) {
591 i++;
592 break;
593 }
594 }
595 if (&ref2->list == &tlskeys_reference)
596 break;
597 }
598
599 /* Uses the unique id and increment it for the next entry. */
600 ref->unique_id = i;
601 i++;
602 }
603 }
604
605 /* This sort the reference list by id. */
606 list_for_each_entry_safe(ref, ref2, &tlskeys_reference, list) {
607 LIST_DEL(&ref->list);
608 list_for_each_entry(ref3, &tkr, list) {
609 if (ref->unique_id < ref3->unique_id) {
610 LIST_ADDQ(&ref3->list, &ref->list);
611 break;
612 }
613 }
614 if (&ref3->list == &tkr)
615 LIST_ADDQ(&tkr, &ref->list);
616 }
617
618 /* swap root */
619 LIST_ADD(&tkr, &tlskeys_reference);
620 LIST_DEL(&tkr);
621 }
622
623 #endif /* SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB */
624
ssl_sock_get_ocsp_arg_kt_index(int evp_keytype)625 int ssl_sock_get_ocsp_arg_kt_index(int evp_keytype)
626 {
627 switch (evp_keytype) {
628 case EVP_PKEY_RSA:
629 return 2;
630 case EVP_PKEY_DSA:
631 return 0;
632 case EVP_PKEY_EC:
633 return 1;
634 }
635
636 return -1;
637 }
638
639 /*
640 * Callback used to set OCSP status extension content in server hello.
641 */
ssl_sock_ocsp_stapling_cbk(SSL * ssl,void * arg)642 int ssl_sock_ocsp_stapling_cbk(SSL *ssl, void *arg)
643 {
644 struct certificate_ocsp *ocsp;
645 struct ocsp_cbk_arg *ocsp_arg;
646 char *ssl_buf;
647 EVP_PKEY *ssl_pkey;
648 int key_type;
649 int index;
650
651 ocsp_arg = arg;
652
653 ssl_pkey = SSL_get_privatekey(ssl);
654 if (!ssl_pkey)
655 return SSL_TLSEXT_ERR_NOACK;
656
657 key_type = EVP_PKEY_base_id(ssl_pkey);
658
659 if (ocsp_arg->is_single && ocsp_arg->single_kt == key_type)
660 ocsp = ocsp_arg->s_ocsp;
661 else {
662 /* For multiple certs per context, we have to find the correct OCSP response based on
663 * the certificate type
664 */
665 index = ssl_sock_get_ocsp_arg_kt_index(key_type);
666
667 if (index < 0)
668 return SSL_TLSEXT_ERR_NOACK;
669
670 ocsp = ocsp_arg->m_ocsp[index];
671
672 }
673
674 if (!ocsp ||
675 !ocsp->response.str ||
676 !ocsp->response.len ||
677 (ocsp->expire < now.tv_sec))
678 return SSL_TLSEXT_ERR_NOACK;
679
680 ssl_buf = OPENSSL_malloc(ocsp->response.len);
681 if (!ssl_buf)
682 return SSL_TLSEXT_ERR_NOACK;
683
684 memcpy(ssl_buf, ocsp->response.str, ocsp->response.len);
685 SSL_set_tlsext_status_ocsp_resp(ssl, ssl_buf, ocsp->response.len);
686
687 return SSL_TLSEXT_ERR_OK;
688 }
689
690 /*
691 * This function enables the handling of OCSP status extension on 'ctx' if a
692 * file name 'cert_path' suffixed using ".ocsp" is present.
693 * To enable OCSP status extension, the issuer's certificate is mandatory.
694 * It should be present in the certificate's extra chain builded from file
695 * 'cert_path'. If not found, the issuer certificate is loaded from a file
696 * named 'cert_path' suffixed using '.issuer'.
697 *
698 * In addition, ".ocsp" file content is loaded as a DER format of an OCSP
699 * response. If file is empty or content is not a valid OCSP response,
700 * OCSP status extension is enabled but OCSP response is ignored (a warning
701 * is displayed).
702 *
703 * Returns 1 if no ".ocsp" file found, 0 if OCSP status extension is
704 * succesfully enabled, or -1 in other error case.
705 */
ssl_sock_load_ocsp(SSL_CTX * ctx,const char * cert_path)706 static int ssl_sock_load_ocsp(SSL_CTX *ctx, const char *cert_path)
707 {
708
709 BIO *in = NULL;
710 X509 *x, *xi = NULL, *issuer = NULL;
711 STACK_OF(X509) *chain = NULL;
712 OCSP_CERTID *cid = NULL;
713 SSL *ssl;
714 char ocsp_path[MAXPATHLEN+1];
715 int i, ret = -1;
716 struct stat st;
717 struct certificate_ocsp *ocsp = NULL, *iocsp;
718 char *warn = NULL;
719 unsigned char *p;
720 pem_password_cb *passwd_cb;
721 void *passwd_cb_userdata;
722 void (*callback) (void);
723
724 snprintf(ocsp_path, MAXPATHLEN+1, "%s.ocsp", cert_path);
725
726 if (stat(ocsp_path, &st))
727 return 1;
728
729 ssl = SSL_new(ctx);
730 if (!ssl)
731 goto out;
732
733 x = SSL_get_certificate(ssl);
734 if (!x)
735 goto out;
736
737 /* Try to lookup for issuer in certificate extra chain */
738 #ifdef SSL_CTRL_GET_EXTRA_CHAIN_CERTS
739 SSL_CTX_get_extra_chain_certs(ctx, &chain);
740 #else
741 chain = ctx->extra_certs;
742 #endif
743 for (i = 0; i < sk_X509_num(chain); i++) {
744 issuer = sk_X509_value(chain, i);
745 if (X509_check_issued(issuer, x) == X509_V_OK)
746 break;
747 else
748 issuer = NULL;
749 }
750
751 /* If not found try to load issuer from a suffixed file */
752 if (!issuer) {
753 char issuer_path[MAXPATHLEN+1];
754
755 in = BIO_new(BIO_s_file());
756 if (!in)
757 goto out;
758
759 snprintf(issuer_path, MAXPATHLEN+1, "%s.issuer", cert_path);
760 if (BIO_read_filename(in, issuer_path) <= 0)
761 goto out;
762
763 passwd_cb = SSL_CTX_get_default_passwd_cb(ctx);
764 passwd_cb_userdata = SSL_CTX_get_default_passwd_cb_userdata(ctx);
765
766 xi = PEM_read_bio_X509_AUX(in, NULL, passwd_cb, passwd_cb_userdata);
767 if (!xi)
768 goto out;
769
770 if (X509_check_issued(xi, x) != X509_V_OK)
771 goto out;
772
773 issuer = xi;
774 }
775
776 cid = OCSP_cert_to_id(0, x, issuer);
777 if (!cid)
778 goto out;
779
780 i = i2d_OCSP_CERTID(cid, NULL);
781 if (!i || (i > OCSP_MAX_CERTID_ASN1_LENGTH))
782 goto out;
783
784 ocsp = calloc(1, sizeof(*ocsp));
785 if (!ocsp)
786 goto out;
787
788 p = ocsp->key_data;
789 i2d_OCSP_CERTID(cid, &p);
790
791 iocsp = (struct certificate_ocsp *)ebmb_insert(&cert_ocsp_tree, &ocsp->key, OCSP_MAX_CERTID_ASN1_LENGTH);
792 if (iocsp == ocsp)
793 ocsp = NULL;
794
795 #ifndef SSL_CTX_get_tlsext_status_cb
796 #ifndef SSL_CTRL_GET_TLSEXT_STATUS_REQ_CB
797 #define SSL_CTRL_GET_TLSEXT_STATUS_REQ_CB 128
798 #endif
799 # define SSL_CTX_get_tlsext_status_cb(ctx, cb) \
800 *cb = SSL_CTX_ctrl(ctx,SSL_CTRL_GET_TLSEXT_STATUS_REQ_CB,0, (void (**)(void))cb)
801 #endif
802 SSL_CTX_get_tlsext_status_cb(ctx, &callback);
803
804 if (!callback) {
805 struct ocsp_cbk_arg *cb_arg;
806 EVP_PKEY *pkey;
807
808 cb_arg = calloc(1, sizeof(*cb_arg));
809 if (!cb_arg)
810 goto out;
811
812 cb_arg->is_single = 1;
813 cb_arg->s_ocsp = iocsp;
814
815 pkey = X509_get_pubkey(x);
816 cb_arg->single_kt = EVP_PKEY_base_id(pkey);
817 EVP_PKEY_free(pkey);
818
819 SSL_CTX_set_tlsext_status_cb(ctx, ssl_sock_ocsp_stapling_cbk);
820 SSL_CTX_set_tlsext_status_arg(ctx, cb_arg);
821 } else {
822 /*
823 * If the ctx has a status CB, then we have previously set an OCSP staple for this ctx
824 * Update that cb_arg with the new cert's staple
825 */
826 struct ocsp_cbk_arg *cb_arg;
827 struct certificate_ocsp *tmp_ocsp;
828 int index;
829 int key_type;
830 EVP_PKEY *pkey;
831
832 #if defined(SSL_CTX_get_tlsext_status_arg) || defined(LIBRESSL_VERSION_NUMBER)
833 #ifndef SSL_CTRL_GET_TLSEXT_STATUS_REQ_CB_ARG
834 #define SSL_CTRL_GET_TLSEXT_STATUS_REQ_CB_ARG 129
835 #endif
836 SSL_CTX_ctrl(ctx, SSL_CTRL_GET_TLSEXT_STATUS_REQ_CB_ARG, 0, &cb_arg);
837 #else
838 cb_arg = ctx->tlsext_status_arg;
839 #endif
840
841 /*
842 * The following few lines will convert cb_arg from a single ocsp to multi ocsp
843 * the order of operations below matter, take care when changing it
844 */
845 tmp_ocsp = cb_arg->s_ocsp;
846 index = ssl_sock_get_ocsp_arg_kt_index(cb_arg->single_kt);
847 cb_arg->s_ocsp = NULL;
848 cb_arg->m_ocsp[index] = tmp_ocsp;
849 cb_arg->is_single = 0;
850 cb_arg->single_kt = 0;
851
852 pkey = X509_get_pubkey(x);
853 key_type = EVP_PKEY_base_id(pkey);
854 EVP_PKEY_free(pkey);
855
856 index = ssl_sock_get_ocsp_arg_kt_index(key_type);
857 if (index >= 0 && !cb_arg->m_ocsp[index])
858 cb_arg->m_ocsp[index] = iocsp;
859
860 }
861
862 ret = 0;
863
864 warn = NULL;
865 if (ssl_sock_load_ocsp_response_from_file(ocsp_path, iocsp, cid, &warn)) {
866 memprintf(&warn, "Loading '%s': %s. Content will be ignored", ocsp_path, warn ? warn : "failure");
867 Warning("%s.\n", warn);
868 }
869
870 out:
871 if (ssl)
872 SSL_free(ssl);
873
874 if (in)
875 BIO_free(in);
876
877 if (xi)
878 X509_free(xi);
879
880 if (cid)
881 OCSP_CERTID_free(cid);
882
883 if (ocsp)
884 free(ocsp);
885
886 if (warn)
887 free(warn);
888
889
890 return ret;
891 }
892
893 #endif
894
895 #if (OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined OPENSSL_NO_TLSEXT && !defined OPENSSL_IS_BORINGSSL && !defined LIBRESSL_VERSION_NUMBER)
896
897 #define CT_EXTENSION_TYPE 18
898
899 static int sctl_ex_index = -1;
900
901 /*
902 * Try to parse Signed Certificate Timestamp List structure. This function
903 * makes only basic test if the data seems like SCTL. No signature validation
904 * is performed.
905 */
ssl_sock_parse_sctl(struct chunk * sctl)906 static int ssl_sock_parse_sctl(struct chunk *sctl)
907 {
908 int ret = 1;
909 int len, pos, sct_len;
910 unsigned char *data;
911
912 if (sctl->len < 2)
913 goto out;
914
915 data = (unsigned char *)sctl->str;
916 len = (data[0] << 8) | data[1];
917
918 if (len + 2 != sctl->len)
919 goto out;
920
921 data = data + 2;
922 pos = 0;
923 while (pos < len) {
924 if (len - pos < 2)
925 goto out;
926
927 sct_len = (data[pos] << 8) | data[pos + 1];
928 if (pos + sct_len + 2 > len)
929 goto out;
930
931 pos += sct_len + 2;
932 }
933
934 ret = 0;
935
936 out:
937 return ret;
938 }
939
ssl_sock_load_sctl_from_file(const char * sctl_path,struct chunk ** sctl)940 static int ssl_sock_load_sctl_from_file(const char *sctl_path, struct chunk **sctl)
941 {
942 int fd = -1;
943 int r = 0;
944 int ret = 1;
945
946 *sctl = NULL;
947
948 fd = open(sctl_path, O_RDONLY);
949 if (fd == -1)
950 goto end;
951
952 trash.len = 0;
953 while (trash.len < trash.size) {
954 r = read(fd, trash.str + trash.len, trash.size - trash.len);
955 if (r < 0) {
956 if (errno == EINTR)
957 continue;
958
959 goto end;
960 }
961 else if (r == 0) {
962 break;
963 }
964 trash.len += r;
965 }
966
967 ret = ssl_sock_parse_sctl(&trash);
968 if (ret)
969 goto end;
970
971 *sctl = calloc(1, sizeof(**sctl));
972 if (!chunk_dup(*sctl, &trash)) {
973 free(*sctl);
974 *sctl = NULL;
975 goto end;
976 }
977
978 end:
979 if (fd != -1)
980 close(fd);
981
982 return ret;
983 }
984
ssl_sock_sctl_add_cbk(SSL * ssl,unsigned ext_type,const unsigned char ** out,size_t * outlen,int * al,void * add_arg)985 int ssl_sock_sctl_add_cbk(SSL *ssl, unsigned ext_type, const unsigned char **out, size_t *outlen, int *al, void *add_arg)
986 {
987 struct chunk *sctl = add_arg;
988
989 *out = (unsigned char *)sctl->str;
990 *outlen = sctl->len;
991
992 return 1;
993 }
994
ssl_sock_sctl_parse_cbk(SSL * s,unsigned int ext_type,const unsigned char * in,size_t inlen,int * al,void * parse_arg)995 int ssl_sock_sctl_parse_cbk(SSL *s, unsigned int ext_type, const unsigned char *in, size_t inlen, int *al, void *parse_arg)
996 {
997 return 1;
998 }
999
ssl_sock_load_sctl(SSL_CTX * ctx,const char * cert_path)1000 static int ssl_sock_load_sctl(SSL_CTX *ctx, const char *cert_path)
1001 {
1002 char sctl_path[MAXPATHLEN+1];
1003 int ret = -1;
1004 struct stat st;
1005 struct chunk *sctl = NULL;
1006
1007 snprintf(sctl_path, MAXPATHLEN+1, "%s.sctl", cert_path);
1008
1009 if (stat(sctl_path, &st))
1010 return 1;
1011
1012 if (ssl_sock_load_sctl_from_file(sctl_path, &sctl))
1013 goto out;
1014
1015 if (!SSL_CTX_add_server_custom_ext(ctx, CT_EXTENSION_TYPE, ssl_sock_sctl_add_cbk, NULL, sctl, ssl_sock_sctl_parse_cbk, NULL)) {
1016 free(sctl);
1017 goto out;
1018 }
1019
1020 SSL_CTX_set_ex_data(ctx, sctl_ex_index, sctl);
1021
1022 ret = 0;
1023
1024 out:
1025 return ret;
1026 }
1027
1028 #endif
1029
ssl_sock_infocbk(const SSL * ssl,int where,int ret)1030 void ssl_sock_infocbk(const SSL *ssl, int where, int ret)
1031 {
1032 struct connection *conn = SSL_get_app_data(ssl);
1033 BIO *write_bio;
1034 (void)ret; /* shut gcc stupid warning */
1035
1036 if (where & SSL_CB_HANDSHAKE_START) {
1037 /* Disable renegotiation (CVE-2009-3555) */
1038 if (conn->flags & CO_FL_CONNECTED) {
1039 conn->flags |= CO_FL_ERROR;
1040 conn->err_code = CO_ER_SSL_RENEG;
1041 }
1042 }
1043
1044 if ((where & SSL_CB_ACCEPT_LOOP) == SSL_CB_ACCEPT_LOOP) {
1045 if (!(conn->xprt_st & SSL_SOCK_ST_FL_16K_WBFSIZE)) {
1046 /* Long certificate chains optimz
1047 If write and read bios are differents, we
1048 consider that the buffering was activated,
1049 so we rise the output buffer size from 4k
1050 to 16k */
1051 write_bio = SSL_get_wbio(ssl);
1052 if (write_bio != SSL_get_rbio(ssl)) {
1053 BIO_set_write_buffer_size(write_bio, 16384);
1054 conn->xprt_st |= SSL_SOCK_ST_FL_16K_WBFSIZE;
1055 }
1056 }
1057 }
1058 }
1059
1060 /* Callback is called for each certificate of the chain during a verify
1061 ok is set to 1 if preverify detect no error on current certificate.
1062 Returns 0 to break the handshake, 1 otherwise. */
ssl_sock_bind_verifycbk(int ok,X509_STORE_CTX * x_store)1063 int ssl_sock_bind_verifycbk(int ok, X509_STORE_CTX *x_store)
1064 {
1065 SSL *ssl;
1066 struct connection *conn;
1067 int err, depth;
1068
1069 ssl = X509_STORE_CTX_get_ex_data(x_store, SSL_get_ex_data_X509_STORE_CTX_idx());
1070 conn = SSL_get_app_data(ssl);
1071
1072 conn->xprt_st |= SSL_SOCK_ST_FL_VERIFY_DONE;
1073
1074 if (ok) /* no errors */
1075 return ok;
1076
1077 depth = X509_STORE_CTX_get_error_depth(x_store);
1078 err = X509_STORE_CTX_get_error(x_store);
1079
1080 /* check if CA error needs to be ignored */
1081 if (depth > 0) {
1082 if (!SSL_SOCK_ST_TO_CA_ERROR(conn->xprt_st)) {
1083 conn->xprt_st |= SSL_SOCK_CA_ERROR_TO_ST(err);
1084 conn->xprt_st |= SSL_SOCK_CAEDEPTH_TO_ST(depth);
1085 }
1086
1087 if (objt_listener(conn->target)->bind_conf->ca_ignerr & (1ULL << err)) {
1088 ssl_sock_dump_errors(conn);
1089 ERR_clear_error();
1090 return 1;
1091 }
1092
1093 conn->err_code = CO_ER_SSL_CA_FAIL;
1094 return 0;
1095 }
1096
1097 if (!SSL_SOCK_ST_TO_CRTERROR(conn->xprt_st))
1098 conn->xprt_st |= SSL_SOCK_CRTERROR_TO_ST(err);
1099
1100 /* check if certificate error needs to be ignored */
1101 if (objt_listener(conn->target)->bind_conf->crt_ignerr & (1ULL << err)) {
1102 ssl_sock_dump_errors(conn);
1103 ERR_clear_error();
1104 return 1;
1105 }
1106
1107 conn->err_code = CO_ER_SSL_CRT_FAIL;
1108 return 0;
1109 }
1110
1111 /* Callback is called for ssl protocol analyse */
ssl_sock_msgcbk(int write_p,int version,int content_type,const void * buf,size_t len,SSL * ssl,void * arg)1112 void ssl_sock_msgcbk(int write_p, int version, int content_type, const void *buf, size_t len, SSL *ssl, void *arg)
1113 {
1114 #ifdef TLS1_RT_HEARTBEAT
1115 /* test heartbeat received (write_p is set to 0
1116 for a received record) */
1117 if ((content_type == TLS1_RT_HEARTBEAT) && (write_p == 0)) {
1118 struct connection *conn = SSL_get_app_data(ssl);
1119 const unsigned char *p = buf;
1120 unsigned int payload;
1121
1122 conn->xprt_st |= SSL_SOCK_RECV_HEARTBEAT;
1123
1124 /* Check if this is a CVE-2014-0160 exploitation attempt. */
1125 if (*p != TLS1_HB_REQUEST)
1126 return;
1127
1128 if (len < 1 + 2 + 16) /* 1 type + 2 size + 0 payload + 16 padding */
1129 goto kill_it;
1130
1131 payload = (p[1] * 256) + p[2];
1132 if (3 + payload + 16 <= len)
1133 return; /* OK no problem */
1134 kill_it:
1135 /* We have a clear heartbleed attack (CVE-2014-0160), the
1136 * advertised payload is larger than the advertised packet
1137 * length, so we have garbage in the buffer between the
1138 * payload and the end of the buffer (p+len). We can't know
1139 * if the SSL stack is patched, and we don't know if we can
1140 * safely wipe out the area between p+3+len and payload.
1141 * So instead, we prevent the response from being sent by
1142 * setting the max_send_fragment to 0 and we report an SSL
1143 * error, which will kill this connection. It will be reported
1144 * above as SSL_ERROR_SSL while an other handshake failure with
1145 * a heartbeat message will be reported as SSL_ERROR_SYSCALL.
1146 */
1147 ssl->max_send_fragment = 0;
1148 SSLerr(SSL_F_TLS1_HEARTBEAT, SSL_R_SSL_HANDSHAKE_FAILURE);
1149 return;
1150 }
1151 #endif
1152 }
1153
1154 #ifdef OPENSSL_NPN_NEGOTIATED
1155 /* This callback is used so that the server advertises the list of
1156 * negociable protocols for NPN.
1157 */
ssl_sock_advertise_npn_protos(SSL * s,const unsigned char ** data,unsigned int * len,void * arg)1158 static int ssl_sock_advertise_npn_protos(SSL *s, const unsigned char **data,
1159 unsigned int *len, void *arg)
1160 {
1161 struct bind_conf *conf = arg;
1162
1163 *data = (const unsigned char *)conf->npn_str;
1164 *len = conf->npn_len;
1165 return SSL_TLSEXT_ERR_OK;
1166 }
1167 #endif
1168
1169 #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
1170 /* This callback is used so that the server advertises the list of
1171 * negociable protocols for ALPN.
1172 */
ssl_sock_advertise_alpn_protos(SSL * s,const unsigned char ** out,unsigned char * outlen,const unsigned char * server,unsigned int server_len,void * arg)1173 static int ssl_sock_advertise_alpn_protos(SSL *s, const unsigned char **out,
1174 unsigned char *outlen,
1175 const unsigned char *server,
1176 unsigned int server_len, void *arg)
1177 {
1178 struct bind_conf *conf = arg;
1179
1180 if (SSL_select_next_proto((unsigned char**) out, outlen, (const unsigned char *)conf->alpn_str,
1181 conf->alpn_len, server, server_len) != OPENSSL_NPN_NEGOTIATED) {
1182 return SSL_TLSEXT_ERR_NOACK;
1183 }
1184 return SSL_TLSEXT_ERR_OK;
1185 }
1186 #endif
1187
1188 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
1189 static DH *ssl_get_tmp_dh(SSL *ssl, int export, int keylen);
1190
1191 /* Create a X509 certificate with the specified servername and serial. This
1192 * function returns a SSL_CTX object or NULL if an error occurs. */
1193 static SSL_CTX *
ssl_sock_do_create_cert(const char * servername,struct bind_conf * bind_conf,SSL * ssl)1194 ssl_sock_do_create_cert(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
1195 {
1196 static unsigned int serial = 0;
1197
1198 X509 *cacert = bind_conf->ca_sign_cert;
1199 EVP_PKEY *capkey = bind_conf->ca_sign_pkey;
1200 SSL_CTX *ssl_ctx = NULL;
1201 X509 *newcrt = NULL;
1202 EVP_PKEY *pkey = NULL;
1203 X509_NAME *name;
1204 const EVP_MD *digest;
1205 X509V3_CTX ctx;
1206 unsigned int i;
1207 int key_type;
1208
1209 /* Get the private key of the defautl certificate and use it */
1210 if (!(pkey = SSL_get_privatekey(ssl)))
1211 goto mkcert_error;
1212
1213 /* Create the certificate */
1214 if (!(newcrt = X509_new()))
1215 goto mkcert_error;
1216
1217 /* Set version number for the certificate (X509v3) and the serial
1218 * number */
1219 if (X509_set_version(newcrt, 2L) != 1)
1220 goto mkcert_error;
1221 if (!serial)
1222 serial = now_ms;
1223 ASN1_INTEGER_set(X509_get_serialNumber(newcrt), serial++);
1224
1225 /* Set duration for the certificate */
1226 if (!X509_gmtime_adj(X509_get_notBefore(newcrt), (long)-60*60*24) ||
1227 !X509_gmtime_adj(X509_get_notAfter(newcrt),(long)60*60*24*365))
1228 goto mkcert_error;
1229
1230 /* set public key in the certificate */
1231 if (X509_set_pubkey(newcrt, pkey) != 1)
1232 goto mkcert_error;
1233
1234 /* Set issuer name from the CA */
1235 if (!(name = X509_get_subject_name(cacert)))
1236 goto mkcert_error;
1237 if (X509_set_issuer_name(newcrt, name) != 1)
1238 goto mkcert_error;
1239
1240 /* Set the subject name using the same, but the CN */
1241 name = X509_NAME_dup(name);
1242 if (X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
1243 (const unsigned char *)servername,
1244 -1, -1, 0) != 1) {
1245 X509_NAME_free(name);
1246 goto mkcert_error;
1247 }
1248 if (X509_set_subject_name(newcrt, name) != 1) {
1249 X509_NAME_free(name);
1250 goto mkcert_error;
1251 }
1252 X509_NAME_free(name);
1253
1254 /* Add x509v3 extensions as specified */
1255 X509V3_set_ctx(&ctx, cacert, newcrt, NULL, NULL, 0);
1256 for (i = 0; i < X509V3_EXT_SIZE; i++) {
1257 X509_EXTENSION *ext;
1258
1259 if (!(ext = X509V3_EXT_conf(NULL, &ctx, x509v3_ext_names[i], x509v3_ext_values[i])))
1260 goto mkcert_error;
1261 if (!X509_add_ext(newcrt, ext, -1)) {
1262 X509_EXTENSION_free(ext);
1263 goto mkcert_error;
1264 }
1265 X509_EXTENSION_free(ext);
1266 }
1267
1268 /* Sign the certificate with the CA private key */
1269
1270 key_type = EVP_PKEY_base_id(capkey);
1271
1272 if (key_type == EVP_PKEY_DSA)
1273 digest = EVP_sha1();
1274 else if (key_type == EVP_PKEY_RSA)
1275 digest = EVP_sha256();
1276 else if (key_type == EVP_PKEY_EC)
1277 digest = EVP_sha256();
1278 else {
1279 #if (OPENSSL_VERSION_NUMBER >= 0x1000000fL)
1280 int nid;
1281
1282 if (EVP_PKEY_get_default_digest_nid(capkey, &nid) <= 0)
1283 goto mkcert_error;
1284 if (!(digest = EVP_get_digestbynid(nid)))
1285 goto mkcert_error;
1286 #else
1287 goto mkcert_error;
1288 #endif
1289 }
1290
1291 if (!(X509_sign(newcrt, capkey, digest)))
1292 goto mkcert_error;
1293
1294 /* Create and set the new SSL_CTX */
1295 if (!(ssl_ctx = SSL_CTX_new(SSLv23_server_method())))
1296 goto mkcert_error;
1297 if (!SSL_CTX_use_PrivateKey(ssl_ctx, pkey))
1298 goto mkcert_error;
1299 if (!SSL_CTX_use_certificate(ssl_ctx, newcrt))
1300 goto mkcert_error;
1301 if (!SSL_CTX_check_private_key(ssl_ctx))
1302 goto mkcert_error;
1303
1304 if (newcrt) X509_free(newcrt);
1305
1306 SSL_CTX_set_tmp_dh_callback(ssl_ctx, ssl_get_tmp_dh);
1307 #if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
1308 {
1309 const char *ecdhe = (bind_conf->ecdhe ? bind_conf->ecdhe : ECDHE_DEFAULT_CURVE);
1310 EC_KEY *ecc;
1311 int nid;
1312
1313 if ((nid = OBJ_sn2nid(ecdhe)) == NID_undef)
1314 goto end;
1315 if (!(ecc = EC_KEY_new_by_curve_name(nid)))
1316 goto end;
1317 SSL_CTX_set_tmp_ecdh(ssl_ctx, ecc);
1318 EC_KEY_free(ecc);
1319 }
1320 #endif
1321 end:
1322 return ssl_ctx;
1323
1324 mkcert_error:
1325 if (ssl_ctx) SSL_CTX_free(ssl_ctx);
1326 if (newcrt) X509_free(newcrt);
1327 return NULL;
1328 }
1329
1330 SSL_CTX *
ssl_sock_create_cert(struct connection * conn,const char * servername,unsigned int key)1331 ssl_sock_create_cert(struct connection *conn, const char *servername, unsigned int key)
1332 {
1333 struct bind_conf *bind_conf = objt_listener(conn->target)->bind_conf;
1334
1335 return ssl_sock_do_create_cert(servername, bind_conf, conn->xprt_ctx);
1336 }
1337
1338 /* Do a lookup for a certificate in the LRU cache used to store generated
1339 * certificates. */
1340 SSL_CTX *
ssl_sock_get_generated_cert(unsigned int key,struct bind_conf * bind_conf)1341 ssl_sock_get_generated_cert(unsigned int key, struct bind_conf *bind_conf)
1342 {
1343 struct lru64 *lru = NULL;
1344
1345 if (ssl_ctx_lru_tree) {
1346 lru = lru64_lookup(key, ssl_ctx_lru_tree, bind_conf->ca_sign_cert, 0);
1347 if (lru && lru->domain)
1348 return (SSL_CTX *)lru->data;
1349 }
1350 return NULL;
1351 }
1352
1353 /* Set a certificate int the LRU cache used to store generated
1354 * certificate. Return 0 on success, otherwise -1 */
1355 int
ssl_sock_set_generated_cert(SSL_CTX * ssl_ctx,unsigned int key,struct bind_conf * bind_conf)1356 ssl_sock_set_generated_cert(SSL_CTX *ssl_ctx, unsigned int key, struct bind_conf *bind_conf)
1357 {
1358 struct lru64 *lru = NULL;
1359
1360 if (ssl_ctx_lru_tree) {
1361 lru = lru64_get(key, ssl_ctx_lru_tree, bind_conf->ca_sign_cert, 0);
1362 if (!lru)
1363 return -1;
1364 if (lru->domain && lru->data)
1365 lru->free((SSL_CTX *)lru->data);
1366 lru64_commit(lru, ssl_ctx, bind_conf->ca_sign_cert, 0, (void (*)(void *))SSL_CTX_free);
1367 return 0;
1368 }
1369 return -1;
1370 }
1371
1372 /* Compute the key of the certificate. */
1373 unsigned int
ssl_sock_generated_cert_key(const void * data,size_t len)1374 ssl_sock_generated_cert_key(const void *data, size_t len)
1375 {
1376 return XXH32(data, len, ssl_ctx_lru_seed);
1377 }
1378
1379 /* Generate a cert and immediately assign it to the SSL session so that the cert's
1380 * refcount is maintained regardless of the cert's presence in the LRU cache.
1381 */
1382 static SSL_CTX *
ssl_sock_generate_certificate(const char * servername,struct bind_conf * bind_conf,SSL * ssl)1383 ssl_sock_generate_certificate(const char *servername, struct bind_conf *bind_conf, SSL *ssl)
1384 {
1385 X509 *cacert = bind_conf->ca_sign_cert;
1386 SSL_CTX *ssl_ctx = NULL;
1387 struct lru64 *lru = NULL;
1388 unsigned int key;
1389
1390 key = ssl_sock_generated_cert_key(servername, strlen(servername));
1391 if (ssl_ctx_lru_tree) {
1392 lru = lru64_get(key, ssl_ctx_lru_tree, cacert, 0);
1393 if (lru && lru->domain)
1394 ssl_ctx = (SSL_CTX *)lru->data;
1395 if (!ssl_ctx && lru) {
1396 ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
1397 lru64_commit(lru, ssl_ctx, cacert, 0, (void (*)(void *))SSL_CTX_free);
1398 }
1399 SSL_set_SSL_CTX(ssl, ssl_ctx);
1400 }
1401 else {
1402 ssl_ctx = ssl_sock_do_create_cert(servername, bind_conf, ssl);
1403 SSL_set_SSL_CTX(ssl, ssl_ctx);
1404 /* No LRU cache, this CTX will be released as soon as the session dies */
1405 SSL_CTX_free(ssl_ctx);
1406 }
1407 return ssl_ctx;
1408 }
1409
1410 /* Sets the SSL ctx of <ssl> to match the advertised server name. Returns a
1411 * warning when no match is found, which implies the default (first) cert
1412 * will keep being used.
1413 */
ssl_sock_switchctx_cbk(SSL * ssl,int * al,struct bind_conf * s)1414 static int ssl_sock_switchctx_cbk(SSL *ssl, int *al, struct bind_conf *s)
1415 {
1416 const char *servername;
1417 const char *wildp = NULL;
1418 struct ebmb_node *node, *n;
1419 int i;
1420 (void)al; /* shut gcc stupid warning */
1421
1422 servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
1423 if (!servername) {
1424 if (s->generate_certs) {
1425 struct connection *conn = SSL_get_app_data(ssl);
1426 unsigned int key;
1427 SSL_CTX *ctx;
1428
1429 conn_get_to_addr(conn);
1430 if (conn->flags & CO_FL_ADDR_TO_SET) {
1431 key = ssl_sock_generated_cert_key(&conn->addr.to, get_addr_len(&conn->addr.to));
1432 ctx = ssl_sock_get_generated_cert(key, s);
1433 if (ctx) {
1434 /* switch ctx */
1435 SSL_set_SSL_CTX(ssl, ctx);
1436 return SSL_TLSEXT_ERR_OK;
1437 }
1438 }
1439 }
1440
1441 return (s->strict_sni ?
1442 SSL_TLSEXT_ERR_ALERT_FATAL :
1443 SSL_TLSEXT_ERR_NOACK);
1444 }
1445
1446 for (i = 0; i < trash.size; i++) {
1447 if (!servername[i])
1448 break;
1449 trash.str[i] = tolower(servername[i]);
1450 if (!wildp && (trash.str[i] == '.'))
1451 wildp = &trash.str[i];
1452 }
1453 trash.str[i] = 0;
1454
1455 node = NULL;
1456 /* lookup in full qualified names */
1457 for (n = ebst_lookup(&s->sni_ctx, trash.str); n; n = ebmb_next_dup(n)) {
1458 /* lookup a not neg filter */
1459 if (!container_of(n, struct sni_ctx, name)->neg) {
1460 node = n;
1461 break;
1462 }
1463 }
1464 if (!node && wildp) {
1465 /* lookup in wildcards names */
1466 for (n = ebst_lookup(&s->sni_w_ctx, wildp); n; n = ebmb_next_dup(n)) {
1467 /* lookup a not neg filter */
1468 if (!container_of(n, struct sni_ctx, name)->neg) {
1469 node = n;
1470 break;
1471 }
1472 }
1473 }
1474 if (!node) {
1475 SSL_CTX *ctx;
1476 if (s->generate_certs &&
1477 (ctx = ssl_sock_generate_certificate(servername, s, ssl))) {
1478 /* switch ctx */
1479 return SSL_TLSEXT_ERR_OK;
1480 }
1481 return (s->strict_sni ?
1482 SSL_TLSEXT_ERR_ALERT_FATAL :
1483 SSL_TLSEXT_ERR_OK);
1484 }
1485
1486 /* switch ctx */
1487 SSL_set_SSL_CTX(ssl, container_of(node, struct sni_ctx, name)->ctx);
1488 return SSL_TLSEXT_ERR_OK;
1489 }
1490 #endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
1491
1492 #ifndef OPENSSL_NO_DH
1493
ssl_get_dh_1024(void)1494 static DH * ssl_get_dh_1024(void)
1495 {
1496 static unsigned char dh1024_p[]={
1497 0xFA,0xF9,0x2A,0x22,0x2A,0xA7,0x7F,0xE1,0x67,0x4E,0x53,0xF7,
1498 0x56,0x13,0xC3,0xB1,0xE3,0x29,0x6B,0x66,0x31,0x6A,0x7F,0xB3,
1499 0xC2,0x68,0x6B,0xCB,0x1D,0x57,0x39,0x1D,0x1F,0xFF,0x1C,0xC9,
1500 0xA6,0xA4,0x98,0x82,0x31,0x5D,0x25,0xFF,0x8A,0xE0,0x73,0x96,
1501 0x81,0xC8,0x83,0x79,0xC1,0x5A,0x04,0xF8,0x37,0x0D,0xA8,0x3D,
1502 0xAE,0x74,0xBC,0xDB,0xB6,0xA4,0x75,0xD9,0x71,0x8A,0xA0,0x17,
1503 0x9E,0x2D,0xC8,0xA8,0xDF,0x2C,0x5F,0x82,0x95,0xF8,0x92,0x9B,
1504 0xA7,0x33,0x5F,0x89,0x71,0xC8,0x2D,0x6B,0x18,0x86,0xC4,0x94,
1505 0x22,0xA5,0x52,0x8D,0xF6,0xF6,0xD2,0x37,0x92,0x0F,0xA5,0xCC,
1506 0xDB,0x7B,0x1D,0x3D,0xA1,0x31,0xB7,0x80,0x8F,0x0B,0x67,0x5E,
1507 0x36,0xA5,0x60,0x0C,0xF1,0x95,0x33,0x8B,
1508 };
1509 static unsigned char dh1024_g[]={
1510 0x02,
1511 };
1512
1513 BIGNUM *p;
1514 BIGNUM *g;
1515 DH *dh = DH_new();
1516 if (dh) {
1517 p = BN_bin2bn(dh1024_p, sizeof dh1024_p, NULL);
1518 g = BN_bin2bn(dh1024_g, sizeof dh1024_g, NULL);
1519
1520 if (!p || !g) {
1521 DH_free(dh);
1522 dh = NULL;
1523 } else {
1524 DH_set0_pqg(dh, p, NULL, g);
1525 }
1526 }
1527 return dh;
1528 }
1529
ssl_get_dh_2048(void)1530 static DH *ssl_get_dh_2048(void)
1531 {
1532 static unsigned char dh2048_p[]={
1533 0xEC,0x86,0xF8,0x70,0xA0,0x33,0x16,0xEC,0x05,0x1A,0x73,0x59,
1534 0xCD,0x1F,0x8B,0xF8,0x29,0xE4,0xD2,0xCF,0x52,0xDD,0xC2,0x24,
1535 0x8D,0xB5,0x38,0x9A,0xFB,0x5C,0xA4,0xE4,0xB2,0xDA,0xCE,0x66,
1536 0x50,0x74,0xA6,0x85,0x4D,0x4B,0x1D,0x30,0xB8,0x2B,0xF3,0x10,
1537 0xE9,0xA7,0x2D,0x05,0x71,0xE7,0x81,0xDF,0x8B,0x59,0x52,0x3B,
1538 0x5F,0x43,0x0B,0x68,0xF1,0xDB,0x07,0xBE,0x08,0x6B,0x1B,0x23,
1539 0xEE,0x4D,0xCC,0x9E,0x0E,0x43,0xA0,0x1E,0xDF,0x43,0x8C,0xEC,
1540 0xBE,0xBE,0x90,0xB4,0x51,0x54,0xB9,0x2F,0x7B,0x64,0x76,0x4E,
1541 0x5D,0xD4,0x2E,0xAE,0xC2,0x9E,0xAE,0x51,0x43,0x59,0xC7,0x77,
1542 0x9C,0x50,0x3C,0x0E,0xED,0x73,0x04,0x5F,0xF1,0x4C,0x76,0x2A,
1543 0xD8,0xF8,0xCF,0xFC,0x34,0x40,0xD1,0xB4,0x42,0x61,0x84,0x66,
1544 0x42,0x39,0x04,0xF8,0x68,0xB2,0x62,0xD7,0x55,0xED,0x1B,0x74,
1545 0x75,0x91,0xE0,0xC5,0x69,0xC1,0x31,0x5C,0xDB,0x7B,0x44,0x2E,
1546 0xCE,0x84,0x58,0x0D,0x1E,0x66,0x0C,0xC8,0x44,0x9E,0xFD,0x40,
1547 0x08,0x67,0x5D,0xFB,0xA7,0x76,0x8F,0x00,0x11,0x87,0xE9,0x93,
1548 0xF9,0x7D,0xC4,0xBC,0x74,0x55,0x20,0xD4,0x4A,0x41,0x2F,0x43,
1549 0x42,0x1A,0xC1,0xF2,0x97,0x17,0x49,0x27,0x37,0x6B,0x2F,0x88,
1550 0x7E,0x1C,0xA0,0xA1,0x89,0x92,0x27,0xD9,0x56,0x5A,0x71,0xC1,
1551 0x56,0x37,0x7E,0x3A,0x9D,0x05,0xE7,0xEE,0x5D,0x8F,0x82,0x17,
1552 0xBC,0xE9,0xC2,0x93,0x30,0x82,0xF9,0xF4,0xC9,0xAE,0x49,0xDB,
1553 0xD0,0x54,0xB4,0xD9,0x75,0x4D,0xFA,0x06,0xB8,0xD6,0x38,0x41,
1554 0xB7,0x1F,0x77,0xF3,
1555 };
1556 static unsigned char dh2048_g[]={
1557 0x02,
1558 };
1559
1560 BIGNUM *p;
1561 BIGNUM *g;
1562 DH *dh = DH_new();
1563 if (dh) {
1564 p = BN_bin2bn(dh2048_p, sizeof dh2048_p, NULL);
1565 g = BN_bin2bn(dh2048_g, sizeof dh2048_g, NULL);
1566
1567 if (!p || !g) {
1568 DH_free(dh);
1569 dh = NULL;
1570 } else {
1571 DH_set0_pqg(dh, p, NULL, g);
1572 }
1573 }
1574 return dh;
1575 }
1576
ssl_get_dh_4096(void)1577 static DH *ssl_get_dh_4096(void)
1578 {
1579 static unsigned char dh4096_p[]={
1580 0xDE,0x16,0x94,0xCD,0x99,0x58,0x07,0xF1,0xF7,0x32,0x96,0x11,
1581 0x04,0x82,0xD4,0x84,0x72,0x80,0x99,0x06,0xCA,0xF0,0xA3,0x68,
1582 0x07,0xCE,0x64,0x50,0xE7,0x74,0x45,0x20,0x80,0x5E,0x4D,0xAD,
1583 0xA5,0xB6,0xED,0xFA,0x80,0x6C,0x3B,0x35,0xC4,0x9A,0x14,0x6B,
1584 0x32,0xBB,0xFD,0x1F,0x17,0x8E,0xB7,0x1F,0xD6,0xFA,0x3F,0x7B,
1585 0xEE,0x16,0xA5,0x62,0x33,0x0D,0xED,0xBC,0x4E,0x58,0xE5,0x47,
1586 0x4D,0xE9,0xAB,0x8E,0x38,0xD3,0x6E,0x90,0x57,0xE3,0x22,0x15,
1587 0x33,0xBD,0xF6,0x43,0x45,0xB5,0x10,0x0A,0xBE,0x2C,0xB4,0x35,
1588 0xB8,0x53,0x8D,0xAD,0xFB,0xA7,0x1F,0x85,0x58,0x41,0x7A,0x79,
1589 0x20,0x68,0xB3,0xE1,0x3D,0x08,0x76,0xBF,0x86,0x0D,0x49,0xE3,
1590 0x82,0x71,0x8C,0xB4,0x8D,0x81,0x84,0xD4,0xE7,0xBE,0x91,0xDC,
1591 0x26,0x39,0x48,0x0F,0x35,0xC4,0xCA,0x65,0xE3,0x40,0x93,0x52,
1592 0x76,0x58,0x7D,0xDD,0x51,0x75,0xDC,0x69,0x61,0xBF,0x47,0x2C,
1593 0x16,0x68,0x2D,0xC9,0x29,0xD3,0xE6,0xC0,0x99,0x48,0xA0,0x9A,
1594 0xC8,0x78,0xC0,0x6D,0x81,0x67,0x12,0x61,0x3F,0x71,0xBA,0x41,
1595 0x1F,0x6C,0x89,0x44,0x03,0xBA,0x3B,0x39,0x60,0xAA,0x28,0x55,
1596 0x59,0xAE,0xB8,0xFA,0xCB,0x6F,0xA5,0x1A,0xF7,0x2B,0xDD,0x52,
1597 0x8A,0x8B,0xE2,0x71,0xA6,0x5E,0x7E,0xD8,0x2E,0x18,0xE0,0x66,
1598 0xDF,0xDD,0x22,0x21,0x99,0x52,0x73,0xA6,0x33,0x20,0x65,0x0E,
1599 0x53,0xE7,0x6B,0x9B,0xC5,0xA3,0x2F,0x97,0x65,0x76,0xD3,0x47,
1600 0x23,0x77,0x12,0xB6,0x11,0x7B,0x24,0xED,0xF1,0xEF,0xC0,0xE2,
1601 0xA3,0x7E,0x67,0x05,0x3E,0x96,0x4D,0x45,0xC2,0x18,0xD1,0x73,
1602 0x9E,0x07,0xF3,0x81,0x6E,0x52,0x63,0xF6,0x20,0x76,0xB9,0x13,
1603 0xD2,0x65,0x30,0x18,0x16,0x09,0x16,0x9E,0x8F,0xF1,0xD2,0x10,
1604 0x5A,0xD3,0xD4,0xAF,0x16,0x61,0xDA,0x55,0x2E,0x18,0x5E,0x14,
1605 0x08,0x54,0x2E,0x2A,0x25,0xA2,0x1A,0x9B,0x8B,0x32,0xA9,0xFD,
1606 0xC2,0x48,0x96,0xE1,0x80,0xCA,0xE9,0x22,0x17,0xBB,0xCE,0x3E,
1607 0x9E,0xED,0xC7,0xF1,0x1F,0xEC,0x17,0x21,0xDC,0x7B,0x82,0x48,
1608 0x8E,0xBB,0x4B,0x9D,0x5B,0x04,0x04,0xDA,0xDB,0x39,0xDF,0x01,
1609 0x40,0xC3,0xAA,0x26,0x23,0x89,0x75,0xC6,0x0B,0xD0,0xA2,0x60,
1610 0x6A,0xF1,0xCC,0x65,0x18,0x98,0x1B,0x52,0xD2,0x74,0x61,0xCC,
1611 0xBD,0x60,0xAE,0xA3,0xA0,0x66,0x6A,0x16,0x34,0x92,0x3F,0x41,
1612 0x40,0x31,0x29,0xC0,0x2C,0x63,0xB2,0x07,0x8D,0xEB,0x94,0xB8,
1613 0xE8,0x47,0x92,0x52,0x93,0x6A,0x1B,0x7E,0x1A,0x61,0xB3,0x1B,
1614 0xF0,0xD6,0x72,0x9B,0xF1,0xB0,0xAF,0xBF,0x3E,0x65,0xEF,0x23,
1615 0x1D,0x6F,0xFF,0x70,0xCD,0x8A,0x4C,0x8A,0xA0,0x72,0x9D,0xBE,
1616 0xD4,0xBB,0x24,0x47,0x4A,0x68,0xB5,0xF5,0xC6,0xD5,0x7A,0xCD,
1617 0xCA,0x06,0x41,0x07,0xAD,0xC2,0x1E,0xE6,0x54,0xA7,0xAD,0x03,
1618 0xD9,0x12,0xC1,0x9C,0x13,0xB1,0xC9,0x0A,0x43,0x8E,0x1E,0x08,
1619 0xCE,0x50,0x82,0x73,0x5F,0xA7,0x55,0x1D,0xD9,0x59,0xAC,0xB5,
1620 0xEA,0x02,0x7F,0x6C,0x5B,0x74,0x96,0x98,0x67,0x24,0xA3,0x0F,
1621 0x15,0xFC,0xA9,0x7D,0x3E,0x67,0xD1,0x70,0xF8,0x97,0xF3,0x67,
1622 0xC5,0x8C,0x88,0x44,0x08,0x02,0xC7,0x2B,
1623 };
1624 static unsigned char dh4096_g[]={
1625 0x02,
1626 };
1627
1628 BIGNUM *p;
1629 BIGNUM *g;
1630 DH *dh = DH_new();
1631 if (dh) {
1632 p = BN_bin2bn(dh4096_p, sizeof dh4096_p, NULL);
1633 g = BN_bin2bn(dh4096_g, sizeof dh4096_g, NULL);
1634
1635 if (!p || !g) {
1636 DH_free(dh);
1637 dh = NULL;
1638 } else {
1639 DH_set0_pqg(dh, p, NULL, g);
1640 }
1641 }
1642 return dh;
1643 }
1644
1645 /* Returns Diffie-Hellman parameters matching the private key length
1646 but not exceeding global.tune.ssl_default_dh_param */
ssl_get_tmp_dh(SSL * ssl,int export,int keylen)1647 static DH *ssl_get_tmp_dh(SSL *ssl, int export, int keylen)
1648 {
1649 DH *dh = NULL;
1650 EVP_PKEY *pkey = SSL_get_privatekey(ssl);
1651 int type;
1652
1653 type = pkey ? EVP_PKEY_base_id(pkey) : EVP_PKEY_NONE;
1654
1655 /* The keylen supplied by OpenSSL can only be 512 or 1024.
1656 See ssl3_send_server_key_exchange() in ssl/s3_srvr.c
1657 */
1658 if (type == EVP_PKEY_RSA || type == EVP_PKEY_DSA) {
1659 keylen = EVP_PKEY_bits(pkey);
1660 }
1661
1662 if (keylen > global.tune.ssl_default_dh_param) {
1663 keylen = global.tune.ssl_default_dh_param;
1664 }
1665
1666 if (keylen >= 4096) {
1667 dh = local_dh_4096;
1668 }
1669 else if (keylen >= 2048) {
1670 dh = local_dh_2048;
1671 }
1672 else {
1673 dh = local_dh_1024;
1674 }
1675
1676 return dh;
1677 }
1678
ssl_sock_get_dh_from_file(const char * filename)1679 static DH * ssl_sock_get_dh_from_file(const char *filename)
1680 {
1681 DH *dh = NULL;
1682 BIO *in = BIO_new(BIO_s_file());
1683
1684 if (in == NULL)
1685 goto end;
1686
1687 if (BIO_read_filename(in, filename) <= 0)
1688 goto end;
1689
1690 dh = PEM_read_bio_DHparams(in, NULL, NULL, NULL);
1691
1692 end:
1693 if (in)
1694 BIO_free(in);
1695
1696 ERR_clear_error();
1697
1698 return dh;
1699 }
1700
ssl_sock_load_global_dh_param_from_file(const char * filename)1701 int ssl_sock_load_global_dh_param_from_file(const char *filename)
1702 {
1703 global_dh = ssl_sock_get_dh_from_file(filename);
1704
1705 if (global_dh) {
1706 return 0;
1707 }
1708
1709 return -1;
1710 }
1711
1712 /* Loads Diffie-Hellman parameter from a file. Returns 1 if loaded, else -1
1713 if an error occured, and 0 if parameter not found. */
ssl_sock_load_dh_params(SSL_CTX * ctx,const char * file)1714 int ssl_sock_load_dh_params(SSL_CTX *ctx, const char *file)
1715 {
1716 int ret = -1;
1717 DH *dh = ssl_sock_get_dh_from_file(file);
1718
1719 if (dh) {
1720 ret = 1;
1721 SSL_CTX_set_tmp_dh(ctx, dh);
1722
1723 if (ssl_dh_ptr_index >= 0) {
1724 /* store a pointer to the DH params to avoid complaining about
1725 ssl-default-dh-param not being set for this SSL_CTX */
1726 SSL_CTX_set_ex_data(ctx, ssl_dh_ptr_index, dh);
1727 }
1728 }
1729 else if (global_dh) {
1730 SSL_CTX_set_tmp_dh(ctx, global_dh);
1731 ret = 0; /* DH params not found */
1732 }
1733 else {
1734 /* Clear openssl global errors stack */
1735 ERR_clear_error();
1736
1737 if (global.tune.ssl_default_dh_param <= 1024) {
1738 /* we are limited to DH parameter of 1024 bits anyway */
1739 if (local_dh_1024 == NULL)
1740 local_dh_1024 = ssl_get_dh_1024();
1741
1742 if (local_dh_1024 == NULL)
1743 goto end;
1744
1745 SSL_CTX_set_tmp_dh(ctx, local_dh_1024);
1746 }
1747 else {
1748 SSL_CTX_set_tmp_dh_callback(ctx, ssl_get_tmp_dh);
1749 }
1750
1751 ret = 0; /* DH params not found */
1752 }
1753
1754 end:
1755 if (dh)
1756 DH_free(dh);
1757
1758 return ret;
1759 }
1760 #endif
1761
ssl_sock_add_cert_sni(SSL_CTX * ctx,struct bind_conf * s,char * name,int order)1762 static int ssl_sock_add_cert_sni(SSL_CTX *ctx, struct bind_conf *s, char *name, int order)
1763 {
1764 struct sni_ctx *sc;
1765 int wild = 0, neg = 0;
1766 struct ebmb_node *node;
1767
1768 if (*name == '!') {
1769 neg = 1;
1770 name++;
1771 }
1772 if (*name == '*') {
1773 wild = 1;
1774 name++;
1775 }
1776 /* !* filter is a nop */
1777 if (neg && wild)
1778 return order;
1779 if (*name) {
1780 int j, len;
1781 len = strlen(name);
1782 for (j = 0; j < len && j < trash.size; j++)
1783 trash.str[j] = tolower(name[j]);
1784 if (j >= trash.size)
1785 return -1;
1786 trash.str[j] = 0;
1787
1788 /* Check for duplicates. */
1789 if (wild)
1790 node = ebst_lookup(&s->sni_w_ctx, trash.str);
1791 else
1792 node = ebst_lookup(&s->sni_ctx, trash.str);
1793 for (; node; node = ebmb_next_dup(node)) {
1794 sc = ebmb_entry(node, struct sni_ctx, name);
1795 if (sc->ctx == ctx && sc->neg == neg)
1796 return order;
1797 }
1798
1799 sc = malloc(sizeof(struct sni_ctx) + len + 1);
1800 if (!sc)
1801 return -1;
1802 memcpy(sc->name.key, trash.str, len + 1);
1803 sc->ctx = ctx;
1804 sc->order = order++;
1805 sc->neg = neg;
1806 if (wild)
1807 ebst_insert(&s->sni_w_ctx, &sc->name);
1808 else
1809 ebst_insert(&s->sni_ctx, &sc->name);
1810 }
1811 return order;
1812 }
1813
1814
1815 /* The following code is used for loading multiple crt files into
1816 * SSL_CTX's based on CN/SAN
1817 */
1818 #if OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined(LIBRESSL_VERSION_NUMBER)
1819 /* This is used to preload the certifcate, private key
1820 * and Cert Chain of a file passed in via the crt
1821 * argument
1822 *
1823 * This way, we do not have to read the file multiple times
1824 */
1825 struct cert_key_and_chain {
1826 X509 *cert;
1827 EVP_PKEY *key;
1828 unsigned int num_chain_certs;
1829 /* This is an array of X509 pointers */
1830 X509 **chain_certs;
1831 };
1832
1833 #define SSL_SOCK_POSSIBLE_KT_COMBOS (1<<(SSL_SOCK_NUM_KEYTYPES))
1834
1835 struct key_combo_ctx {
1836 SSL_CTX *ctx;
1837 int order;
1838 };
1839
1840 /* Map used for processing multiple keypairs for a single purpose
1841 *
1842 * This maps CN/SNI name to certificate type
1843 */
1844 struct sni_keytype {
1845 int keytypes; /* BITMASK for keytypes */
1846 struct ebmb_node name; /* node holding the servername value */
1847 };
1848
1849
1850 /* Frees the contents of a cert_key_and_chain
1851 */
ssl_sock_free_cert_key_and_chain_contents(struct cert_key_and_chain * ckch)1852 static void ssl_sock_free_cert_key_and_chain_contents(struct cert_key_and_chain *ckch)
1853 {
1854 int i;
1855
1856 if (!ckch)
1857 return;
1858
1859 /* Free the certificate and set pointer to NULL */
1860 if (ckch->cert)
1861 X509_free(ckch->cert);
1862 ckch->cert = NULL;
1863
1864 /* Free the key and set pointer to NULL */
1865 if (ckch->key)
1866 EVP_PKEY_free(ckch->key);
1867 ckch->key = NULL;
1868
1869 /* Free each certificate in the chain */
1870 for (i = 0; i < ckch->num_chain_certs; i++) {
1871 if (ckch->chain_certs[i])
1872 X509_free(ckch->chain_certs[i]);
1873 }
1874
1875 /* Free the chain obj itself and set to NULL */
1876 if (ckch->num_chain_certs > 0) {
1877 free(ckch->chain_certs);
1878 ckch->num_chain_certs = 0;
1879 ckch->chain_certs = NULL;
1880 }
1881
1882 }
1883
1884 /* checks if a key and cert exists in the ckch
1885 */
ssl_sock_is_ckch_valid(struct cert_key_and_chain * ckch)1886 static int ssl_sock_is_ckch_valid(struct cert_key_and_chain *ckch)
1887 {
1888 return (ckch->cert != NULL && ckch->key != NULL);
1889 }
1890
1891
1892 /* Loads the contents of a crt file (path) into a cert_key_and_chain
1893 * This allows us to carry the contents of the file without having to
1894 * read the file multiple times.
1895 *
1896 * returns:
1897 * 0 on Success
1898 * 1 on SSL Failure
1899 * 2 on file not found
1900 */
ssl_sock_load_crt_file_into_ckch(const char * path,struct cert_key_and_chain * ckch,char ** err)1901 static int ssl_sock_load_crt_file_into_ckch(const char *path, struct cert_key_and_chain *ckch, char **err)
1902 {
1903
1904 BIO *in;
1905 X509 *ca = NULL;
1906 int ret = 1;
1907
1908 ssl_sock_free_cert_key_and_chain_contents(ckch);
1909
1910 in = BIO_new(BIO_s_file());
1911 if (in == NULL)
1912 goto end;
1913
1914 if (BIO_read_filename(in, path) <= 0)
1915 goto end;
1916
1917 /* Read Private Key */
1918 ckch->key = PEM_read_bio_PrivateKey(in, NULL, NULL, NULL);
1919 if (ckch->key == NULL) {
1920 memprintf(err, "%sunable to load private key from file '%s'.\n",
1921 err && *err ? *err : "", path);
1922 goto end;
1923 }
1924
1925 /* Seek back to beginning of file */
1926 if (BIO_reset(in) == -1) {
1927 memprintf(err, "%san error occurred while reading the file '%s'.\n",
1928 err && *err ? *err : "", path);
1929 goto end;
1930 }
1931
1932 /* Read Certificate */
1933 ckch->cert = PEM_read_bio_X509_AUX(in, NULL, NULL, NULL);
1934 if (ckch->cert == NULL) {
1935 memprintf(err, "%sunable to load certificate from file '%s'.\n",
1936 err && *err ? *err : "", path);
1937 goto end;
1938 }
1939
1940 /* Read Certificate Chain */
1941 while ((ca = PEM_read_bio_X509(in, NULL, NULL, NULL))) {
1942 /* Grow the chain certs */
1943 ckch->num_chain_certs++;
1944 ckch->chain_certs = realloc(ckch->chain_certs, (ckch->num_chain_certs * sizeof(X509 *)));
1945
1946 /* use - 1 here since we just incremented it above */
1947 ckch->chain_certs[ckch->num_chain_certs - 1] = ca;
1948 }
1949 ret = ERR_get_error();
1950 if (ret && (ERR_GET_LIB(ret) != ERR_LIB_PEM && ERR_GET_REASON(ret) != PEM_R_NO_START_LINE)) {
1951 memprintf(err, "%sunable to load certificate chain from file '%s'.\n",
1952 err && *err ? *err : "", path);
1953 ret = 1;
1954 goto end;
1955 }
1956
1957 ret = 0;
1958
1959 end:
1960
1961 ERR_clear_error();
1962 if (in)
1963 BIO_free(in);
1964
1965 /* Something went wrong in one of the reads */
1966 if (ret != 0)
1967 ssl_sock_free_cert_key_and_chain_contents(ckch);
1968
1969 return ret;
1970 }
1971
1972 /* Loads the info in ckch into ctx
1973 * Currently, this does not process any information about ocsp, dhparams or
1974 * sctl
1975 * Returns
1976 * 0 on success
1977 * 1 on failure
1978 */
ssl_sock_put_ckch_into_ctx(const char * path,const struct cert_key_and_chain * ckch,SSL_CTX * ctx,char ** err)1979 static int ssl_sock_put_ckch_into_ctx(const char *path, const struct cert_key_and_chain *ckch, SSL_CTX *ctx, char **err)
1980 {
1981 int i = 0;
1982
1983 if (SSL_CTX_use_PrivateKey(ctx, ckch->key) <= 0) {
1984 memprintf(err, "%sunable to load SSL private key into SSL Context '%s'.\n",
1985 err && *err ? *err : "", path);
1986 return 1;
1987 }
1988
1989 if (!SSL_CTX_use_certificate(ctx, ckch->cert)) {
1990 memprintf(err, "%sunable to load SSL certificate into SSL Context '%s'.\n",
1991 err && *err ? *err : "", path);
1992 return 1;
1993 }
1994
1995 /* Load all certs in the ckch into the ctx_chain for the ssl_ctx */
1996 for (i = 0; i < ckch->num_chain_certs; i++) {
1997 if (!SSL_CTX_add1_chain_cert(ctx, ckch->chain_certs[i])) {
1998 memprintf(err, "%sunable to load chain certificate #%d into SSL Context '%s'. Make sure you are linking against Openssl >= 1.0.2.\n",
1999 err && *err ? *err : "", (i+1), path);
2000 return 1;
2001 }
2002 }
2003
2004 if (SSL_CTX_check_private_key(ctx) <= 0) {
2005 memprintf(err, "%sinconsistencies between private key and certificate loaded from PEM file '%s'.\n",
2006 err && *err ? *err : "", path);
2007 return 1;
2008 }
2009
2010 return 0;
2011 }
2012
2013
ssl_sock_populate_sni_keytypes_hplr(const char * str,struct eb_root * sni_keytypes,int key_index)2014 static int ssl_sock_populate_sni_keytypes_hplr(const char *str, struct eb_root *sni_keytypes, int key_index)
2015 {
2016 struct sni_keytype *s_kt = NULL;
2017 struct ebmb_node *node;
2018 int i;
2019
2020 for (i = 0; i < trash.size; i++) {
2021 if (!str[i])
2022 break;
2023 trash.str[i] = tolower(str[i]);
2024 }
2025 trash.str[i] = 0;
2026 node = ebst_lookup(sni_keytypes, trash.str);
2027 if (!node) {
2028 /* CN not found in tree */
2029 s_kt = malloc(sizeof(struct sni_keytype) + i + 1);
2030 /* Using memcpy here instead of strncpy.
2031 * strncpy will cause sig_abrt errors under certain versions of gcc with -O2
2032 * See: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=60792
2033 */
2034 if (!s_kt)
2035 return -1;
2036
2037 memcpy(s_kt->name.key, trash.str, i+1);
2038 s_kt->keytypes = 0;
2039 ebst_insert(sni_keytypes, &s_kt->name);
2040 } else {
2041 /* CN found in tree */
2042 s_kt = container_of(node, struct sni_keytype, name);
2043 }
2044
2045 /* Mark that this CN has the keytype of key_index via keytypes mask */
2046 s_kt->keytypes |= 1<<key_index;
2047
2048 return 0;
2049
2050 }
2051
2052
2053 /* Given a path that does not exist, try to check for path.rsa, path.dsa and path.ecdsa files.
2054 * If any are found, group these files into a set of SSL_CTX*
2055 * based on shared and unique CN and SAN entries. Add these SSL_CTX* to the SNI tree.
2056 *
2057 * This will allow the user to explictly group multiple cert/keys for a single purpose
2058 *
2059 * Returns
2060 * 0 on success
2061 * 1 on failure
2062 */
ssl_sock_load_multi_cert(const char * path,struct bind_conf * bind_conf,struct proxy * curproxy,char ** sni_filter,int fcount,char ** err)2063 static int ssl_sock_load_multi_cert(const char *path, struct bind_conf *bind_conf, struct proxy *curproxy, char **sni_filter, int fcount, char **err)
2064 {
2065 char fp[MAXPATHLEN+1] = {0};
2066 int n = 0;
2067 int i = 0;
2068 struct cert_key_and_chain certs_and_keys[SSL_SOCK_NUM_KEYTYPES] = { {0} };
2069 struct eb_root sni_keytypes_map = { {0} };
2070 struct ebmb_node *node;
2071 struct ebmb_node *next;
2072 /* Array of SSL_CTX pointers corresponding to each possible combo
2073 * of keytypes
2074 */
2075 struct key_combo_ctx key_combos[SSL_SOCK_POSSIBLE_KT_COMBOS] = { {0} };
2076 int rv = 0;
2077 X509_NAME *xname = NULL;
2078 char *str = NULL;
2079 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
2080 STACK_OF(GENERAL_NAME) *names = NULL;
2081 #endif
2082
2083 /* Load all possible certs and keys */
2084 for (n = 0; n < SSL_SOCK_NUM_KEYTYPES; n++) {
2085 struct stat buf;
2086
2087 snprintf(fp, sizeof(fp), "%s.%s", path, SSL_SOCK_KEYTYPE_NAMES[n]);
2088 if (stat(fp, &buf) == 0) {
2089 if (ssl_sock_load_crt_file_into_ckch(fp, &certs_and_keys[n], err) == 1) {
2090 rv = 1;
2091 goto end;
2092 }
2093 }
2094 }
2095
2096 /* Process each ckch and update keytypes for each CN/SAN
2097 * for example, if CN/SAN www.a.com is associated with
2098 * certs with keytype 0 and 2, then at the end of the loop,
2099 * www.a.com will have:
2100 * keyindex = 0 | 1 | 4 = 5
2101 */
2102 for (n = 0; n < SSL_SOCK_NUM_KEYTYPES; n++) {
2103 int ret;
2104
2105 if (!ssl_sock_is_ckch_valid(&certs_and_keys[n]))
2106 continue;
2107
2108 if (fcount) {
2109 for (i = 0; i < fcount; i++) {
2110 ret = ssl_sock_populate_sni_keytypes_hplr(sni_filter[i], &sni_keytypes_map, n);
2111 if (ret < 0) {
2112 memprintf(err, "%sunable to allocate SSL context.\n",
2113 err && *err ? *err : "");
2114 rv = 1;
2115 goto end;
2116 }
2117 }
2118 } else {
2119 /* A lot of the following code is OpenSSL boilerplate for processing CN's and SAN's,
2120 * so the line that contains logic is marked via comments
2121 */
2122 xname = X509_get_subject_name(certs_and_keys[n].cert);
2123 i = -1;
2124 while ((i = X509_NAME_get_index_by_NID(xname, NID_commonName, i)) != -1) {
2125 X509_NAME_ENTRY *entry = X509_NAME_get_entry(xname, i);
2126 ASN1_STRING *value;
2127 value = X509_NAME_ENTRY_get_data(entry);
2128 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
2129 /* Important line is here */
2130 ret = ssl_sock_populate_sni_keytypes_hplr(str, &sni_keytypes_map, n);
2131
2132 OPENSSL_free(str);
2133 str = NULL;
2134 if (ret < 0) {
2135 memprintf(err, "%sunable to allocate SSL context.\n",
2136 err && *err ? *err : "");
2137 rv = 1;
2138 goto end;
2139 }
2140 }
2141 }
2142
2143 /* Do the above logic for each SAN */
2144 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
2145 names = X509_get_ext_d2i(certs_and_keys[n].cert, NID_subject_alt_name, NULL, NULL);
2146 if (names) {
2147 for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
2148 GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
2149
2150 if (name->type == GEN_DNS) {
2151 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
2152 /* Important line is here */
2153 ret = ssl_sock_populate_sni_keytypes_hplr(str, &sni_keytypes_map, n);
2154
2155 OPENSSL_free(str);
2156 str = NULL;
2157 if (ret < 0) {
2158 memprintf(err, "%sunable to allocate SSL context.\n",
2159 err && *err ? *err : "");
2160 rv = 1;
2161 goto end;
2162 }
2163 }
2164 }
2165 }
2166 }
2167 }
2168 #endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
2169 }
2170
2171 /* If no files found, return error */
2172 if (eb_is_empty(&sni_keytypes_map)) {
2173 memprintf(err, "%sunable to load SSL certificate file '%s' file does not exist.\n",
2174 err && *err ? *err : "", path);
2175 rv = 1;
2176 goto end;
2177 }
2178
2179 /* We now have a map of CN/SAN to keytypes that are loaded in
2180 * Iterate through the map to create the SSL_CTX's (if needed)
2181 * and add each CTX to the SNI tree
2182 *
2183 * Some math here:
2184 * There are 2^n - 1 possibile combinations, each unique
2185 * combination is denoted by the key in the map. Each key
2186 * has a value between 1 and 2^n - 1. Conveniently, the array
2187 * of SSL_CTX* is sized 2^n. So, we can simply use the i'th
2188 * entry in the array to correspond to the unique combo (key)
2189 * associated with i. This unique key combo (i) will be associated
2190 * with combos[i-1]
2191 */
2192
2193 node = ebmb_first(&sni_keytypes_map);
2194 while (node) {
2195 SSL_CTX *cur_ctx;
2196 char cur_file[MAXPATHLEN+1];
2197
2198 str = (char *)container_of(node, struct sni_keytype, name)->name.key;
2199 i = container_of(node, struct sni_keytype, name)->keytypes;
2200 cur_ctx = key_combos[i-1].ctx;
2201
2202 if (cur_ctx == NULL) {
2203 /* need to create SSL_CTX */
2204 cur_ctx = SSL_CTX_new(SSLv23_server_method());
2205 if (cur_ctx == NULL) {
2206 memprintf(err, "%sunable to allocate SSL context.\n",
2207 err && *err ? *err : "");
2208 rv = 1;
2209 goto end;
2210 }
2211
2212 /* Load all required certs/keys/chains/OCSPs info into SSL_CTX */
2213 for (n = 0; n < SSL_SOCK_NUM_KEYTYPES; n++) {
2214 if (i & (1<<n)) {
2215 /* Key combo contains ckch[n] */
2216 snprintf(cur_file, MAXPATHLEN+1, "%s.%s", path, SSL_SOCK_KEYTYPE_NAMES[n]);
2217 if (ssl_sock_put_ckch_into_ctx(cur_file, &certs_and_keys[n], cur_ctx, err) != 0) {
2218 SSL_CTX_free(cur_ctx);
2219 rv = 1;
2220 goto end;
2221 }
2222
2223 #if (defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP)
2224 /* Load OCSP Info into context */
2225 if (ssl_sock_load_ocsp(cur_ctx, cur_file) < 0) {
2226 if (err)
2227 memprintf(err, "%s '%s.ocsp' is present and activates OCSP but it is impossible to compute the OCSP certificate ID (maybe the issuer could not be found)'.\n",
2228 *err ? *err : "", cur_file);
2229 SSL_CTX_free(cur_ctx);
2230 rv = 1;
2231 goto end;
2232 }
2233 #endif
2234 }
2235 }
2236
2237 /* Load DH params into the ctx to support DHE keys */
2238 #ifndef OPENSSL_NO_DH
2239 if (ssl_dh_ptr_index >= 0)
2240 SSL_CTX_set_ex_data(cur_ctx, ssl_dh_ptr_index, NULL);
2241
2242 rv = ssl_sock_load_dh_params(cur_ctx, NULL);
2243 if (rv < 0) {
2244 if (err)
2245 memprintf(err, "%sunable to load DH parameters from file '%s'.\n",
2246 *err ? *err : "", path);
2247 rv = 1;
2248 goto end;
2249 }
2250 #endif
2251
2252 /* Update key_combos */
2253 key_combos[i-1].ctx = cur_ctx;
2254 }
2255
2256 /* Update SNI Tree */
2257 key_combos[i-1].order = ssl_sock_add_cert_sni(cur_ctx, bind_conf, str, key_combos[i-1].order);
2258 if (key_combos[i-1].order < 0) {
2259 memprintf(err, "%sunable to create a sni context.\n", err && *err ? *err : "");
2260 rv = 1;
2261 goto end;
2262 }
2263 node = ebmb_next(node);
2264 }
2265
2266
2267 /* Mark a default context if none exists, using the ctx that has the most shared keys */
2268 if (!bind_conf->default_ctx) {
2269 for (i = SSL_SOCK_POSSIBLE_KT_COMBOS - 1; i >= 0; i--) {
2270 if (key_combos[i].ctx) {
2271 bind_conf->default_ctx = key_combos[i].ctx;
2272 break;
2273 }
2274 }
2275 }
2276
2277 end:
2278
2279 if (names)
2280 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
2281
2282 for (n = 0; n < SSL_SOCK_NUM_KEYTYPES; n++)
2283 ssl_sock_free_cert_key_and_chain_contents(&certs_and_keys[n]);
2284
2285 node = ebmb_first(&sni_keytypes_map);
2286 while (node) {
2287 next = ebmb_next(node);
2288 ebmb_delete(node);
2289 free(ebmb_entry(node, struct sni_keytype, name));
2290 node = next;
2291 }
2292
2293 return rv;
2294 }
2295 #else
2296 /* This is a dummy, that just logs an error and returns error */
ssl_sock_load_multi_cert(const char * path,struct bind_conf * bind_conf,struct proxy * curproxy,char ** sni_filter,int fcount,char ** err)2297 static int ssl_sock_load_multi_cert(const char *path, struct bind_conf *bind_conf, struct proxy *curproxy, char **sni_filter, int fcount, char **err)
2298 {
2299 memprintf(err, "%sunable to stat SSL certificate from file '%s' : %s.\n",
2300 err && *err ? *err : "", path, strerror(errno));
2301 return 1;
2302 }
2303
2304 #endif /* #if OPENSSL_VERSION_NUMBER >= 0x1000200fL: Support for loading multiple certs into a single SSL_CTX */
2305
2306 /* Loads a certificate key and CA chain from a file. Returns 0 on error, -1 if
2307 * an early error happens and the caller must call SSL_CTX_free() by itelf.
2308 */
ssl_sock_load_cert_chain_file(SSL_CTX * ctx,const char * file,struct bind_conf * s,char ** sni_filter,int fcount)2309 static int ssl_sock_load_cert_chain_file(SSL_CTX *ctx, const char *file, struct bind_conf *s, char **sni_filter, int fcount)
2310 {
2311 BIO *in;
2312 X509 *x = NULL, *ca;
2313 int i, err;
2314 int ret = -1;
2315 int order = 0;
2316 X509_NAME *xname;
2317 char *str;
2318 pem_password_cb *passwd_cb;
2319 void *passwd_cb_userdata;
2320
2321 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
2322 STACK_OF(GENERAL_NAME) *names;
2323 #endif
2324
2325 in = BIO_new(BIO_s_file());
2326 if (in == NULL)
2327 goto end;
2328
2329 if (BIO_read_filename(in, file) <= 0)
2330 goto end;
2331
2332
2333 passwd_cb = SSL_CTX_get_default_passwd_cb(ctx);
2334 passwd_cb_userdata = SSL_CTX_get_default_passwd_cb_userdata(ctx);
2335
2336 x = PEM_read_bio_X509_AUX(in, NULL, passwd_cb, passwd_cb_userdata);
2337 if (x == NULL)
2338 goto end;
2339
2340 if (fcount) {
2341 while (fcount--) {
2342 order = ssl_sock_add_cert_sni(ctx, s, sni_filter[fcount], order);
2343 if (order < 0)
2344 goto end;
2345 }
2346 }
2347 else {
2348 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
2349 names = X509_get_ext_d2i(x, NID_subject_alt_name, NULL, NULL);
2350 if (names) {
2351 for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
2352 GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
2353 if (name->type == GEN_DNS) {
2354 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
2355 order = ssl_sock_add_cert_sni(ctx, s, str, order);
2356 OPENSSL_free(str);
2357 if (order < 0)
2358 goto end;
2359 }
2360 }
2361 }
2362 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
2363 }
2364 #endif /* SSL_CTRL_SET_TLSEXT_HOSTNAME */
2365 xname = X509_get_subject_name(x);
2366 i = -1;
2367 while ((i = X509_NAME_get_index_by_NID(xname, NID_commonName, i)) != -1) {
2368 X509_NAME_ENTRY *entry = X509_NAME_get_entry(xname, i);
2369 ASN1_STRING *value;
2370
2371 value = X509_NAME_ENTRY_get_data(entry);
2372 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
2373 order = ssl_sock_add_cert_sni(ctx, s, str, order);
2374 OPENSSL_free(str);
2375 if (order < 0)
2376 goto end;
2377 }
2378 }
2379 }
2380
2381 ret = 0; /* the caller must not free the SSL_CTX argument anymore */
2382 if (!SSL_CTX_use_certificate(ctx, x))
2383 goto end;
2384
2385 #ifdef SSL_CTX_clear_extra_chain_certs
2386 SSL_CTX_clear_extra_chain_certs(ctx);
2387 #else
2388 if (ctx->extra_certs != NULL) {
2389 sk_X509_pop_free(ctx->extra_certs, X509_free);
2390 ctx->extra_certs = NULL;
2391 }
2392 #endif
2393
2394 while ((ca = PEM_read_bio_X509(in, NULL, passwd_cb, passwd_cb_userdata))) {
2395 if (!SSL_CTX_add_extra_chain_cert(ctx, ca)) {
2396 X509_free(ca);
2397 goto end;
2398 }
2399 }
2400
2401 err = ERR_get_error();
2402 if (!err || (ERR_GET_LIB(err) == ERR_LIB_PEM && ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
2403 /* we successfully reached the last cert in the file */
2404 ret = 1;
2405 }
2406 ERR_clear_error();
2407
2408 end:
2409 if (x)
2410 X509_free(x);
2411
2412 if (in)
2413 BIO_free(in);
2414
2415 return ret;
2416 }
2417
ssl_sock_load_cert_file(const char * path,struct bind_conf * bind_conf,struct proxy * curproxy,char ** sni_filter,int fcount,char ** err)2418 static int ssl_sock_load_cert_file(const char *path, struct bind_conf *bind_conf, struct proxy *curproxy, char **sni_filter, int fcount, char **err)
2419 {
2420 int ret;
2421 SSL_CTX *ctx;
2422
2423 ctx = SSL_CTX_new(SSLv23_server_method());
2424 if (!ctx) {
2425 memprintf(err, "%sunable to allocate SSL context for cert '%s'.\n",
2426 err && *err ? *err : "", path);
2427 return 1;
2428 }
2429
2430 if (SSL_CTX_use_PrivateKey_file(ctx, path, SSL_FILETYPE_PEM) <= 0) {
2431 memprintf(err, "%sunable to load SSL private key from PEM file '%s'.\n",
2432 err && *err ? *err : "", path);
2433 SSL_CTX_free(ctx);
2434 return 1;
2435 }
2436
2437 ret = ssl_sock_load_cert_chain_file(ctx, path, bind_conf, sni_filter, fcount);
2438 if (ret <= 0) {
2439 memprintf(err, "%sunable to load SSL certificate from PEM file '%s'.\n",
2440 err && *err ? *err : "", path);
2441 if (ret < 0) /* serious error, must do that ourselves */
2442 SSL_CTX_free(ctx);
2443 return 1;
2444 }
2445
2446 if (SSL_CTX_check_private_key(ctx) <= 0) {
2447 memprintf(err, "%sinconsistencies between private key and certificate loaded from PEM file '%s'.\n",
2448 err && *err ? *err : "", path);
2449 return 1;
2450 }
2451
2452 /* we must not free the SSL_CTX anymore below, since it's already in
2453 * the tree, so it will be discovered and cleaned in time.
2454 */
2455 #ifndef OPENSSL_NO_DH
2456 /* store a NULL pointer to indicate we have not yet loaded
2457 a custom DH param file */
2458 if (ssl_dh_ptr_index >= 0) {
2459 SSL_CTX_set_ex_data(ctx, ssl_dh_ptr_index, NULL);
2460 }
2461
2462 ret = ssl_sock_load_dh_params(ctx, path);
2463 if (ret < 0) {
2464 if (err)
2465 memprintf(err, "%sunable to load DH parameters from file '%s'.\n",
2466 *err ? *err : "", path);
2467 return 1;
2468 }
2469 #endif
2470
2471 #if (defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP)
2472 ret = ssl_sock_load_ocsp(ctx, path);
2473 if (ret < 0) {
2474 if (err)
2475 memprintf(err, "%s '%s.ocsp' is present and activates OCSP but it is impossible to compute the OCSP certificate ID (maybe the issuer could not be found)'.\n",
2476 *err ? *err : "", path);
2477 return 1;
2478 }
2479 #endif
2480
2481 #if (OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined OPENSSL_NO_TLSEXT && !defined OPENSSL_IS_BORINGSSL && !defined LIBRESSL_VERSION_NUMBER)
2482 if (sctl_ex_index >= 0) {
2483 ret = ssl_sock_load_sctl(ctx, path);
2484 if (ret < 0) {
2485 if (err)
2486 memprintf(err, "%s '%s.sctl' is present but cannot be read or parsed'.\n",
2487 *err ? *err : "", path);
2488 return 1;
2489 }
2490 }
2491 #endif
2492
2493 #ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
2494 if (bind_conf->default_ctx) {
2495 memprintf(err, "%sthis version of openssl cannot load multiple SSL certificates.\n",
2496 err && *err ? *err : "");
2497 return 1;
2498 }
2499 #endif
2500 if (!bind_conf->default_ctx)
2501 bind_conf->default_ctx = ctx;
2502
2503 return 0;
2504 }
2505
ssl_sock_load_cert(char * path,struct bind_conf * bind_conf,struct proxy * curproxy,char ** err)2506 int ssl_sock_load_cert(char *path, struct bind_conf *bind_conf, struct proxy *curproxy, char **err)
2507 {
2508 struct dirent **de_list;
2509 int i, n;
2510 DIR *dir;
2511 struct stat buf;
2512 char *end;
2513 char fp[MAXPATHLEN+1];
2514 int cfgerr = 0;
2515 #if OPENSSL_VERSION_NUMBER >= 0x1000200fL
2516 int is_bundle;
2517 int j;
2518 #endif
2519
2520 if (stat(path, &buf) == 0) {
2521 dir = opendir(path);
2522 if (!dir)
2523 return ssl_sock_load_cert_file(path, bind_conf, curproxy, NULL, 0, err);
2524
2525 /* strip trailing slashes, including first one */
2526 for (end = path + strlen(path) - 1; end >= path && *end == '/'; end--)
2527 *end = 0;
2528
2529 n = scandir(path, &de_list, 0, alphasort);
2530 if (n < 0) {
2531 memprintf(err, "%sunable to scan directory '%s' : %s.\n",
2532 err && *err ? *err : "", path, strerror(errno));
2533 cfgerr++;
2534 }
2535 else {
2536 for (i = 0; i < n; i++) {
2537 struct dirent *de = de_list[i];
2538
2539 end = strrchr(de->d_name, '.');
2540 if (end && (!strcmp(end, ".issuer") || !strcmp(end, ".ocsp") || !strcmp(end, ".sctl")))
2541 goto ignore_entry;
2542
2543 snprintf(fp, sizeof(fp), "%s/%s", path, de->d_name);
2544 if (stat(fp, &buf) != 0) {
2545 memprintf(err, "%sunable to stat SSL certificate from file '%s' : %s.\n",
2546 err && *err ? *err : "", fp, strerror(errno));
2547 cfgerr++;
2548 goto ignore_entry;
2549 }
2550 if (!S_ISREG(buf.st_mode))
2551 goto ignore_entry;
2552
2553 #if OPENSSL_VERSION_NUMBER >= 0x1000200fL
2554 is_bundle = 0;
2555 /* Check if current entry in directory is part of a multi-cert bundle */
2556
2557 if (end) {
2558 for (j = 0; j < SSL_SOCK_NUM_KEYTYPES; j++) {
2559 if (!strcmp(end + 1, SSL_SOCK_KEYTYPE_NAMES[j])) {
2560 is_bundle = 1;
2561 break;
2562 }
2563 }
2564
2565 if (is_bundle) {
2566 int dp_len;
2567
2568 dp_len = end - de->d_name;
2569
2570 /* increment i and free de until we get to a non-bundle cert
2571 * Note here that we look at de_list[i + 1] before freeing de
2572 * this is important since ignore_entry will free de. This also
2573 * guarantees that de->d_name continues to hold the same prefix.
2574 */
2575 while (i + 1 < n && !strncmp(de_list[i + 1]->d_name, de->d_name, dp_len)) {
2576 free(de);
2577 i++;
2578 de = de_list[i];
2579 }
2580
2581 snprintf(fp, sizeof(fp), "%s/%.*s", path, dp_len, de->d_name);
2582 cfgerr += ssl_sock_load_multi_cert(fp, bind_conf, curproxy, NULL, 0, err);
2583 /* Successfully processed the bundle */
2584 goto ignore_entry;
2585 }
2586 }
2587
2588 #endif
2589 cfgerr += ssl_sock_load_cert_file(fp, bind_conf, curproxy, NULL, 0, err);
2590 ignore_entry:
2591 free(de);
2592 }
2593 free(de_list);
2594 }
2595 closedir(dir);
2596 return cfgerr;
2597 }
2598
2599 cfgerr = ssl_sock_load_multi_cert(path, bind_conf, curproxy, NULL, 0, err);
2600
2601 return cfgerr;
2602 }
2603
2604 /* Make sure openssl opens /dev/urandom before the chroot. The work is only
2605 * done once. Zero is returned if the operation fails. No error is returned
2606 * if the random is said as not implemented, because we expect that openssl
2607 * will use another method once needed.
2608 */
ssl_initialize_random()2609 static int ssl_initialize_random()
2610 {
2611 unsigned char random;
2612 static int random_initialized = 0;
2613
2614 if (!random_initialized && RAND_bytes(&random, 1) != 0)
2615 random_initialized = 1;
2616
2617 return random_initialized;
2618 }
2619
ssl_sock_load_cert_list_file(char * file,struct bind_conf * bind_conf,struct proxy * curproxy,char ** err)2620 int ssl_sock_load_cert_list_file(char *file, struct bind_conf *bind_conf, struct proxy *curproxy, char **err)
2621 {
2622 char thisline[LINESIZE*CRTLIST_FACTOR];
2623 FILE *f;
2624 struct stat buf;
2625 int linenum = 0;
2626 int cfgerr = 0;
2627
2628 if ((f = fopen(file, "r")) == NULL) {
2629 memprintf(err, "cannot open file '%s' : %s", file, strerror(errno));
2630 return 1;
2631 }
2632
2633 while (fgets(thisline, sizeof(thisline), f) != NULL) {
2634 int arg;
2635 int newarg;
2636 char *end;
2637 char *args[MAX_LINE_ARGS*CRTLIST_FACTOR + 1];
2638 char *line = thisline;
2639
2640 linenum++;
2641 end = line + strlen(line);
2642 if (end-line == sizeof(thisline)-1 && *(end-1) != '\n') {
2643 /* Check if we reached the limit and the last char is not \n.
2644 * Watch out for the last line without the terminating '\n'!
2645 */
2646 memprintf(err, "line %d too long in file '%s', limit is %d characters",
2647 linenum, file, (int)sizeof(thisline)-1);
2648 cfgerr = 1;
2649 break;
2650 }
2651
2652 arg = 0;
2653 newarg = 1;
2654 while (*line) {
2655 if (*line == '#' || *line == '\n' || *line == '\r') {
2656 /* end of string, end of loop */
2657 *line = 0;
2658 break;
2659 }
2660 else if (isspace(*line)) {
2661 newarg = 1;
2662 *line = 0;
2663 }
2664 else if (newarg) {
2665 if (arg == MAX_LINE_ARGS*CRTLIST_FACTOR) {
2666 memprintf(err, "too many args on line %d in file '%s'.",
2667 linenum, file);
2668 cfgerr = 1;
2669 break;
2670 }
2671 newarg = 0;
2672 args[arg++] = line;
2673 }
2674 line++;
2675 }
2676 if (cfgerr)
2677 break;
2678
2679 /* empty line */
2680 if (!arg)
2681 continue;
2682
2683 if (stat(args[0], &buf) == 0) {
2684 cfgerr = ssl_sock_load_cert_file(args[0], bind_conf, curproxy, &args[1], arg-1, err);
2685 } else {
2686 cfgerr = ssl_sock_load_multi_cert(args[0], bind_conf, curproxy, &args[1], arg-1, err);
2687 }
2688
2689 if (cfgerr) {
2690 memprintf(err, "error processing line %d in file '%s' : %s", linenum, file, *err);
2691 break;
2692 }
2693 }
2694 fclose(f);
2695 return cfgerr;
2696 }
2697
2698 #ifndef SSL_OP_CIPHER_SERVER_PREFERENCE /* needs OpenSSL >= 0.9.7 */
2699 #define SSL_OP_CIPHER_SERVER_PREFERENCE 0
2700 #endif
2701
2702 #ifndef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION /* needs OpenSSL >= 0.9.7 */
2703 #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION 0
2704 #define SSL_renegotiate_pending(arg) 0
2705 #endif
2706 #ifndef SSL_OP_SINGLE_ECDH_USE /* needs OpenSSL >= 0.9.8 */
2707 #define SSL_OP_SINGLE_ECDH_USE 0
2708 #endif
2709 #ifndef SSL_OP_NO_TICKET /* needs OpenSSL >= 0.9.8 */
2710 #define SSL_OP_NO_TICKET 0
2711 #endif
2712 #ifndef SSL_OP_NO_COMPRESSION /* needs OpenSSL >= 0.9.9 */
2713 #define SSL_OP_NO_COMPRESSION 0
2714 #endif
2715 #ifndef SSL_OP_NO_TLSv1_1 /* needs OpenSSL >= 1.0.1 */
2716 #define SSL_OP_NO_TLSv1_1 0
2717 #endif
2718 #ifndef SSL_OP_NO_TLSv1_2 /* needs OpenSSL >= 1.0.1 */
2719 #define SSL_OP_NO_TLSv1_2 0
2720 #endif
2721 #ifndef SSL_OP_SINGLE_DH_USE /* needs OpenSSL >= 0.9.6 */
2722 #define SSL_OP_SINGLE_DH_USE 0
2723 #endif
2724 #ifndef SSL_OP_SINGLE_ECDH_USE /* needs OpenSSL >= 1.0.0 */
2725 #define SSL_OP_SINGLE_ECDH_USE 0
2726 #endif
2727 #ifndef SSL_MODE_RELEASE_BUFFERS /* needs OpenSSL >= 1.0.0 */
2728 #define SSL_MODE_RELEASE_BUFFERS 0
2729 #endif
2730 #ifndef SSL_MODE_SMALL_BUFFERS /* needs small_records.patch */
2731 #define SSL_MODE_SMALL_BUFFERS 0
2732 #endif
2733
ssl_sock_prepare_ctx(struct bind_conf * bind_conf,SSL_CTX * ctx,struct proxy * curproxy)2734 int ssl_sock_prepare_ctx(struct bind_conf *bind_conf, SSL_CTX *ctx, struct proxy *curproxy)
2735 {
2736 int cfgerr = 0;
2737 int verify = SSL_VERIFY_NONE;
2738 long ssloptions =
2739 SSL_OP_ALL | /* all known workarounds for bugs */
2740 SSL_OP_NO_SSLv2 |
2741 SSL_OP_NO_COMPRESSION |
2742 SSL_OP_SINGLE_DH_USE |
2743 SSL_OP_SINGLE_ECDH_USE |
2744 SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION |
2745 SSL_OP_CIPHER_SERVER_PREFERENCE;
2746 long sslmode =
2747 SSL_MODE_ENABLE_PARTIAL_WRITE |
2748 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
2749 SSL_MODE_RELEASE_BUFFERS |
2750 SSL_MODE_SMALL_BUFFERS;
2751 STACK_OF(SSL_CIPHER) * ciphers = NULL;
2752 const SSL_CIPHER * cipher = NULL;
2753 char cipher_description[128];
2754 /* The description of ciphers using an Ephemeral Diffie Hellman key exchange
2755 contains " Kx=DH " or " Kx=DH(". Beware of " Kx=DH/",
2756 which is not ephemeral DH. */
2757 const char dhe_description[] = " Kx=DH ";
2758 const char dhe_export_description[] = " Kx=DH(";
2759 int idx = 0;
2760 int dhe_found = 0;
2761 SSL *ssl = NULL;
2762
2763 /* Make sure openssl opens /dev/urandom before the chroot */
2764 if (!ssl_initialize_random()) {
2765 Alert("OpenSSL random data generator initialization failed.\n");
2766 cfgerr++;
2767 }
2768
2769 if (bind_conf->ssl_options & BC_SSL_O_NO_SSLV3)
2770 ssloptions |= SSL_OP_NO_SSLv3;
2771 if (bind_conf->ssl_options & BC_SSL_O_NO_TLSV10)
2772 ssloptions |= SSL_OP_NO_TLSv1;
2773 if (bind_conf->ssl_options & BC_SSL_O_NO_TLSV11)
2774 ssloptions |= SSL_OP_NO_TLSv1_1;
2775 if (bind_conf->ssl_options & BC_SSL_O_NO_TLSV12)
2776 ssloptions |= SSL_OP_NO_TLSv1_2;
2777 if (bind_conf->ssl_options & BC_SSL_O_NO_TLS_TICKETS)
2778 ssloptions |= SSL_OP_NO_TICKET;
2779 if (bind_conf->ssl_options & BC_SSL_O_USE_SSLV3) {
2780 #ifndef OPENSSL_NO_SSL3
2781 SSL_CTX_set_ssl_version(ctx, SSLv3_server_method());
2782 #else
2783 Alert("SSLv3 support requested but unavailable.\n");
2784 cfgerr++;
2785 #endif
2786 }
2787 if (bind_conf->ssl_options & BC_SSL_O_USE_TLSV10)
2788 SSL_CTX_set_ssl_version(ctx, TLSv1_server_method());
2789 #if SSL_OP_NO_TLSv1_1
2790 if (bind_conf->ssl_options & BC_SSL_O_USE_TLSV11)
2791 SSL_CTX_set_ssl_version(ctx, TLSv1_1_server_method());
2792 #endif
2793 #if SSL_OP_NO_TLSv1_2
2794 if (bind_conf->ssl_options & BC_SSL_O_USE_TLSV12)
2795 SSL_CTX_set_ssl_version(ctx, TLSv1_2_server_method());
2796 #endif
2797
2798 SSL_CTX_set_options(ctx, ssloptions);
2799 SSL_CTX_set_mode(ctx, sslmode);
2800 switch (bind_conf->verify) {
2801 case SSL_SOCK_VERIFY_NONE:
2802 verify = SSL_VERIFY_NONE;
2803 break;
2804 case SSL_SOCK_VERIFY_OPTIONAL:
2805 verify = SSL_VERIFY_PEER;
2806 break;
2807 case SSL_SOCK_VERIFY_REQUIRED:
2808 verify = SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2809 break;
2810 }
2811 SSL_CTX_set_verify(ctx, verify, ssl_sock_bind_verifycbk);
2812 if (verify & SSL_VERIFY_PEER) {
2813 if (bind_conf->ca_file) {
2814 /* load CAfile to verify */
2815 if (!SSL_CTX_load_verify_locations(ctx, bind_conf->ca_file, NULL)) {
2816 Alert("Proxy '%s': unable to load CA file '%s' for bind '%s' at [%s:%d].\n",
2817 curproxy->id, bind_conf->ca_file, bind_conf->arg, bind_conf->file, bind_conf->line);
2818 cfgerr++;
2819 }
2820 /* set CA names fo client cert request, function returns void */
2821 SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(bind_conf->ca_file));
2822 }
2823 else {
2824 Alert("Proxy '%s': verify is enabled but no CA file specified for bind '%s' at [%s:%d].\n",
2825 curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
2826 cfgerr++;
2827 }
2828 #ifdef X509_V_FLAG_CRL_CHECK
2829 if (bind_conf->crl_file) {
2830 X509_STORE *store = SSL_CTX_get_cert_store(ctx);
2831
2832 if (!store || !X509_STORE_load_locations(store, bind_conf->crl_file, NULL)) {
2833 Alert("Proxy '%s': unable to configure CRL file '%s' for bind '%s' at [%s:%d].\n",
2834 curproxy->id, bind_conf->crl_file, bind_conf->arg, bind_conf->file, bind_conf->line);
2835 cfgerr++;
2836 }
2837 else {
2838 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
2839 }
2840 }
2841 #endif
2842 ERR_clear_error();
2843 }
2844
2845 #if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
2846 if(bind_conf->keys_ref) {
2847 if (!SSL_CTX_set_tlsext_ticket_key_cb(ctx, ssl_tlsext_ticket_key_cb)) {
2848 Alert("Proxy '%s': unable to set callback for TLS ticket validation for bind '%s' at [%s:%d].\n",
2849 curproxy->id, bind_conf->arg, bind_conf->file, bind_conf->line);
2850 cfgerr++;
2851 }
2852 }
2853 #endif
2854
2855 if (global.tune.ssllifetime)
2856 SSL_CTX_set_timeout(ctx, global.tune.ssllifetime);
2857
2858 shared_context_set_cache(ctx);
2859 if (bind_conf->ciphers &&
2860 !SSL_CTX_set_cipher_list(ctx, bind_conf->ciphers)) {
2861 Alert("Proxy '%s': unable to set SSL cipher list to '%s' for bind '%s' at [%s:%d].\n",
2862 curproxy->id, bind_conf->ciphers, bind_conf->arg, bind_conf->file, bind_conf->line);
2863 cfgerr++;
2864 }
2865
2866 /* If tune.ssl.default-dh-param has not been set,
2867 neither has ssl-default-dh-file and no static DH
2868 params were in the certificate file. */
2869 if (global.tune.ssl_default_dh_param == 0 &&
2870 global_dh == NULL &&
2871 (ssl_dh_ptr_index == -1 ||
2872 SSL_CTX_get_ex_data(ctx, ssl_dh_ptr_index) == NULL)) {
2873
2874 ssl = SSL_new(ctx);
2875
2876 if (ssl) {
2877 ciphers = SSL_get_ciphers(ssl);
2878
2879 if (ciphers) {
2880 for (idx = 0; idx < sk_SSL_CIPHER_num(ciphers); idx++) {
2881 cipher = sk_SSL_CIPHER_value(ciphers, idx);
2882 if (SSL_CIPHER_description(cipher, cipher_description, sizeof (cipher_description)) == cipher_description) {
2883 if (strstr(cipher_description, dhe_description) != NULL ||
2884 strstr(cipher_description, dhe_export_description) != NULL) {
2885 dhe_found = 1;
2886 break;
2887 }
2888 }
2889 }
2890 }
2891 SSL_free(ssl);
2892 ssl = NULL;
2893 }
2894
2895 if (dhe_found) {
2896 Warning("Setting tune.ssl.default-dh-param to 1024 by default, if your workload permits it you should set it to at least 2048. Please set a value >= 1024 to make this warning disappear.\n");
2897 }
2898
2899 global.tune.ssl_default_dh_param = 1024;
2900 }
2901
2902 #ifndef OPENSSL_NO_DH
2903 if (global.tune.ssl_default_dh_param >= 1024) {
2904 if (local_dh_1024 == NULL) {
2905 local_dh_1024 = ssl_get_dh_1024();
2906 }
2907 if (global.tune.ssl_default_dh_param >= 2048) {
2908 if (local_dh_2048 == NULL) {
2909 local_dh_2048 = ssl_get_dh_2048();
2910 }
2911 if (global.tune.ssl_default_dh_param >= 4096) {
2912 if (local_dh_4096 == NULL) {
2913 local_dh_4096 = ssl_get_dh_4096();
2914 }
2915 }
2916 }
2917 }
2918 #endif /* OPENSSL_NO_DH */
2919
2920 SSL_CTX_set_info_callback(ctx, ssl_sock_infocbk);
2921 #if OPENSSL_VERSION_NUMBER >= 0x00907000L
2922 SSL_CTX_set_msg_callback(ctx, ssl_sock_msgcbk);
2923 #endif
2924
2925 #ifdef OPENSSL_NPN_NEGOTIATED
2926 if (bind_conf->npn_str)
2927 SSL_CTX_set_next_protos_advertised_cb(ctx, ssl_sock_advertise_npn_protos, bind_conf);
2928 #endif
2929 #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
2930 if (bind_conf->alpn_str)
2931 SSL_CTX_set_alpn_select_cb(ctx, ssl_sock_advertise_alpn_protos, bind_conf);
2932 #endif
2933
2934 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
2935 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_cbk);
2936 SSL_CTX_set_tlsext_servername_arg(ctx, bind_conf);
2937 #endif
2938 #if defined(SSL_CTX_set_tmp_ecdh) && !defined(OPENSSL_NO_ECDH)
2939 {
2940 int i;
2941 EC_KEY *ecdh;
2942
2943 i = OBJ_sn2nid(bind_conf->ecdhe ? bind_conf->ecdhe : ECDHE_DEFAULT_CURVE);
2944 if (!i || ((ecdh = EC_KEY_new_by_curve_name(i)) == NULL)) {
2945 Alert("Proxy '%s': unable to set elliptic named curve to '%s' for bind '%s' at [%s:%d].\n",
2946 curproxy->id, bind_conf->ecdhe ? bind_conf->ecdhe : ECDHE_DEFAULT_CURVE,
2947 bind_conf->arg, bind_conf->file, bind_conf->line);
2948 cfgerr++;
2949 }
2950 else {
2951 SSL_CTX_set_tmp_ecdh(ctx, ecdh);
2952 EC_KEY_free(ecdh);
2953 }
2954 }
2955 #endif
2956
2957 return cfgerr;
2958 }
2959
ssl_sock_srv_hostcheck(const char * pattern,const char * hostname)2960 static int ssl_sock_srv_hostcheck(const char *pattern, const char *hostname)
2961 {
2962 const char *pattern_wildcard, *pattern_left_label_end, *hostname_left_label_end;
2963 size_t prefixlen, suffixlen;
2964
2965 /* Trivial case */
2966 if (strcasecmp(pattern, hostname) == 0)
2967 return 1;
2968
2969 /* The rest of this logic is based on RFC 6125, section 6.4.3
2970 * (http://tools.ietf.org/html/rfc6125#section-6.4.3) */
2971
2972 pattern_wildcard = NULL;
2973 pattern_left_label_end = pattern;
2974 while (*pattern_left_label_end != '.') {
2975 switch (*pattern_left_label_end) {
2976 case 0:
2977 /* End of label not found */
2978 return 0;
2979 case '*':
2980 /* If there is more than one wildcards */
2981 if (pattern_wildcard)
2982 return 0;
2983 pattern_wildcard = pattern_left_label_end;
2984 break;
2985 }
2986 pattern_left_label_end++;
2987 }
2988
2989 /* If it's not trivial and there is no wildcard, it can't
2990 * match */
2991 if (!pattern_wildcard)
2992 return 0;
2993
2994 /* Make sure all labels match except the leftmost */
2995 hostname_left_label_end = strchr(hostname, '.');
2996 if (!hostname_left_label_end
2997 || strcasecmp(pattern_left_label_end, hostname_left_label_end) != 0)
2998 return 0;
2999
3000 /* Make sure the leftmost label of the hostname is long enough
3001 * that the wildcard can match */
3002 if (hostname_left_label_end - hostname < (pattern_left_label_end - pattern) - 1)
3003 return 0;
3004
3005 /* Finally compare the string on either side of the
3006 * wildcard */
3007 prefixlen = pattern_wildcard - pattern;
3008 suffixlen = pattern_left_label_end - (pattern_wildcard + 1);
3009 if ((prefixlen && (strncasecmp(pattern, hostname, prefixlen) != 0))
3010 || (suffixlen && (strncasecmp(pattern_wildcard + 1, hostname_left_label_end - suffixlen, suffixlen) != 0)))
3011 return 0;
3012
3013 return 1;
3014 }
3015
ssl_sock_srv_verifycbk(int ok,X509_STORE_CTX * ctx)3016 static int ssl_sock_srv_verifycbk(int ok, X509_STORE_CTX *ctx)
3017 {
3018 SSL *ssl;
3019 struct connection *conn;
3020 char *servername;
3021
3022 int depth;
3023 X509 *cert;
3024 STACK_OF(GENERAL_NAME) *alt_names;
3025 int i;
3026 X509_NAME *cert_subject;
3027 char *str;
3028
3029 if (ok == 0)
3030 return ok;
3031
3032 ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
3033 conn = SSL_get_app_data(ssl);
3034
3035 servername = objt_server(conn->target)->ssl_ctx.verify_host;
3036
3037 /* We only need to verify the CN on the actual server cert,
3038 * not the indirect CAs */
3039 depth = X509_STORE_CTX_get_error_depth(ctx);
3040 if (depth != 0)
3041 return ok;
3042
3043 /* At this point, the cert is *not* OK unless we can find a
3044 * hostname match */
3045 ok = 0;
3046
3047 cert = X509_STORE_CTX_get_current_cert(ctx);
3048 /* It seems like this might happen if verify peer isn't set */
3049 if (!cert)
3050 return ok;
3051
3052 alt_names = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
3053 if (alt_names) {
3054 for (i = 0; !ok && i < sk_GENERAL_NAME_num(alt_names); i++) {
3055 GENERAL_NAME *name = sk_GENERAL_NAME_value(alt_names, i);
3056 if (name->type == GEN_DNS) {
3057 #if OPENSSL_VERSION_NUMBER < 0x00907000L
3058 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.ia5) >= 0) {
3059 #else
3060 if (ASN1_STRING_to_UTF8((unsigned char **)&str, name->d.dNSName) >= 0) {
3061 #endif
3062 ok = ssl_sock_srv_hostcheck(str, servername);
3063 OPENSSL_free(str);
3064 }
3065 }
3066 }
3067 sk_GENERAL_NAME_pop_free(alt_names, GENERAL_NAME_free);
3068 }
3069
3070 cert_subject = X509_get_subject_name(cert);
3071 i = -1;
3072 while (!ok && (i = X509_NAME_get_index_by_NID(cert_subject, NID_commonName, i)) != -1) {
3073 X509_NAME_ENTRY *entry = X509_NAME_get_entry(cert_subject, i);
3074 ASN1_STRING *value;
3075 value = X509_NAME_ENTRY_get_data(entry);
3076 if (ASN1_STRING_to_UTF8((unsigned char **)&str, value) >= 0) {
3077 ok = ssl_sock_srv_hostcheck(str, servername);
3078 OPENSSL_free(str);
3079 }
3080 }
3081
3082 return ok;
3083 }
3084
3085 /* prepare ssl context from servers options. Returns an error count */
3086 int ssl_sock_prepare_srv_ctx(struct server *srv, struct proxy *curproxy)
3087 {
3088 int cfgerr = 0;
3089 long options =
3090 SSL_OP_ALL | /* all known workarounds for bugs */
3091 SSL_OP_NO_SSLv2 |
3092 SSL_OP_NO_COMPRESSION;
3093 long mode =
3094 SSL_MODE_ENABLE_PARTIAL_WRITE |
3095 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
3096 SSL_MODE_RELEASE_BUFFERS |
3097 SSL_MODE_SMALL_BUFFERS;
3098 int verify = SSL_VERIFY_NONE;
3099
3100 /* Make sure openssl opens /dev/urandom before the chroot */
3101 if (!ssl_initialize_random()) {
3102 Alert("OpenSSL random data generator initialization failed.\n");
3103 cfgerr++;
3104 }
3105
3106 /* Automatic memory computations need to know we use SSL there */
3107 global.ssl_used_backend = 1;
3108
3109 /* Initiate SSL context for current server */
3110 srv->ssl_ctx.reused_sess = NULL;
3111 if (srv->use_ssl)
3112 srv->xprt = &ssl_sock;
3113 if (srv->check.use_ssl)
3114 srv->check.xprt = &ssl_sock;
3115
3116 srv->ssl_ctx.ctx = SSL_CTX_new(SSLv23_client_method());
3117 if (!srv->ssl_ctx.ctx) {
3118 Alert("config : %s '%s', server '%s': unable to allocate ssl context.\n",
3119 proxy_type_str(curproxy), curproxy->id,
3120 srv->id);
3121 cfgerr++;
3122 return cfgerr;
3123 }
3124 if (srv->ssl_ctx.client_crt) {
3125 if (SSL_CTX_use_PrivateKey_file(srv->ssl_ctx.ctx, srv->ssl_ctx.client_crt, SSL_FILETYPE_PEM) <= 0) {
3126 Alert("config : %s '%s', server '%s': unable to load SSL private key from PEM file '%s'.\n",
3127 proxy_type_str(curproxy), curproxy->id,
3128 srv->id, srv->ssl_ctx.client_crt);
3129 cfgerr++;
3130 }
3131 else if (SSL_CTX_use_certificate_chain_file(srv->ssl_ctx.ctx, srv->ssl_ctx.client_crt) <= 0) {
3132 Alert("config : %s '%s', server '%s': unable to load ssl certificate from PEM file '%s'.\n",
3133 proxy_type_str(curproxy), curproxy->id,
3134 srv->id, srv->ssl_ctx.client_crt);
3135 cfgerr++;
3136 }
3137 else if (SSL_CTX_check_private_key(srv->ssl_ctx.ctx) <= 0) {
3138 Alert("config : %s '%s', server '%s': inconsistencies between private key and certificate loaded from PEM file '%s'.\n",
3139 proxy_type_str(curproxy), curproxy->id,
3140 srv->id, srv->ssl_ctx.client_crt);
3141 cfgerr++;
3142 }
3143 }
3144
3145 if (srv->ssl_ctx.options & SRV_SSL_O_NO_SSLV3)
3146 options |= SSL_OP_NO_SSLv3;
3147 if (srv->ssl_ctx.options & SRV_SSL_O_NO_TLSV10)
3148 options |= SSL_OP_NO_TLSv1;
3149 if (srv->ssl_ctx.options & SRV_SSL_O_NO_TLSV11)
3150 options |= SSL_OP_NO_TLSv1_1;
3151 if (srv->ssl_ctx.options & SRV_SSL_O_NO_TLSV12)
3152 options |= SSL_OP_NO_TLSv1_2;
3153 if (srv->ssl_ctx.options & SRV_SSL_O_NO_TLS_TICKETS)
3154 options |= SSL_OP_NO_TICKET;
3155 if (srv->ssl_ctx.options & SRV_SSL_O_USE_SSLV3) {
3156 #ifndef OPENSSL_NO_SSL3
3157 SSL_CTX_set_ssl_version(srv->ssl_ctx.ctx, SSLv3_client_method());
3158 #else
3159 Alert("SSLv3 support requested but unavailable.\n");
3160 cfgerr++;
3161 #endif
3162 }
3163 if (srv->ssl_ctx.options & SRV_SSL_O_USE_TLSV10)
3164 SSL_CTX_set_ssl_version(srv->ssl_ctx.ctx, TLSv1_client_method());
3165 #if SSL_OP_NO_TLSv1_1
3166 if (srv->ssl_ctx.options & SRV_SSL_O_USE_TLSV11)
3167 SSL_CTX_set_ssl_version(srv->ssl_ctx.ctx, TLSv1_1_client_method());
3168 #endif
3169 #if SSL_OP_NO_TLSv1_2
3170 if (srv->ssl_ctx.options & SRV_SSL_O_USE_TLSV12)
3171 SSL_CTX_set_ssl_version(srv->ssl_ctx.ctx, TLSv1_2_client_method());
3172 #endif
3173
3174 SSL_CTX_set_options(srv->ssl_ctx.ctx, options);
3175 SSL_CTX_set_mode(srv->ssl_ctx.ctx, mode);
3176
3177 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
3178 verify = SSL_VERIFY_PEER;
3179
3180 switch (srv->ssl_ctx.verify) {
3181 case SSL_SOCK_VERIFY_NONE:
3182 verify = SSL_VERIFY_NONE;
3183 break;
3184 case SSL_SOCK_VERIFY_REQUIRED:
3185 verify = SSL_VERIFY_PEER;
3186 break;
3187 }
3188 SSL_CTX_set_verify(srv->ssl_ctx.ctx,
3189 verify,
3190 srv->ssl_ctx.verify_host ? ssl_sock_srv_verifycbk : NULL);
3191 if (verify & SSL_VERIFY_PEER) {
3192 if (srv->ssl_ctx.ca_file) {
3193 /* load CAfile to verify */
3194 if (!SSL_CTX_load_verify_locations(srv->ssl_ctx.ctx, srv->ssl_ctx.ca_file, NULL)) {
3195 Alert("Proxy '%s', server '%s' [%s:%d] unable to load CA file '%s'.\n",
3196 curproxy->id, srv->id,
3197 srv->conf.file, srv->conf.line, srv->ssl_ctx.ca_file);
3198 cfgerr++;
3199 }
3200 }
3201 else {
3202 if (global.ssl_server_verify == SSL_SERVER_VERIFY_REQUIRED)
3203 Alert("Proxy '%s', server '%s' [%s:%d] verify is enabled by default but no CA file specified. If you're running on a LAN where you're certain to trust the server's certificate, please set an explicit 'verify none' statement on the 'server' line, or use 'ssl-server-verify none' in the global section to disable server-side verifications by default.\n",
3204 curproxy->id, srv->id,
3205 srv->conf.file, srv->conf.line);
3206 else
3207 Alert("Proxy '%s', server '%s' [%s:%d] verify is enabled but no CA file specified.\n",
3208 curproxy->id, srv->id,
3209 srv->conf.file, srv->conf.line);
3210 cfgerr++;
3211 }
3212 #ifdef X509_V_FLAG_CRL_CHECK
3213 if (srv->ssl_ctx.crl_file) {
3214 X509_STORE *store = SSL_CTX_get_cert_store(srv->ssl_ctx.ctx);
3215
3216 if (!store || !X509_STORE_load_locations(store, srv->ssl_ctx.crl_file, NULL)) {
3217 Alert("Proxy '%s', server '%s' [%s:%d] unable to configure CRL file '%s'.\n",
3218 curproxy->id, srv->id,
3219 srv->conf.file, srv->conf.line, srv->ssl_ctx.crl_file);
3220 cfgerr++;
3221 }
3222 else {
3223 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
3224 }
3225 }
3226 #endif
3227 }
3228
3229 if (global.tune.ssllifetime)
3230 SSL_CTX_set_timeout(srv->ssl_ctx.ctx, global.tune.ssllifetime);
3231
3232 SSL_CTX_set_session_cache_mode(srv->ssl_ctx.ctx, SSL_SESS_CACHE_OFF);
3233 if (srv->ssl_ctx.ciphers &&
3234 !SSL_CTX_set_cipher_list(srv->ssl_ctx.ctx, srv->ssl_ctx.ciphers)) {
3235 Alert("Proxy '%s', server '%s' [%s:%d] : unable to set SSL cipher list to '%s'.\n",
3236 curproxy->id, srv->id,
3237 srv->conf.file, srv->conf.line, srv->ssl_ctx.ciphers);
3238 cfgerr++;
3239 }
3240
3241 return cfgerr;
3242 }
3243
3244 /* Walks down the two trees in bind_conf and prepares all certs. The pointer may
3245 * be NULL, in which case nothing is done. Returns the number of errors
3246 * encountered.
3247 */
3248 int ssl_sock_prepare_all_ctx(struct bind_conf *bind_conf, struct proxy *px)
3249 {
3250 struct ebmb_node *node;
3251 struct sni_ctx *sni;
3252 int err = 0;
3253
3254 if (!bind_conf || !bind_conf->is_ssl)
3255 return 0;
3256
3257 /* Automatic memory computations need to know we use SSL there */
3258 global.ssl_used_frontend = 1;
3259
3260 if (bind_conf->default_ctx)
3261 err += ssl_sock_prepare_ctx(bind_conf, bind_conf->default_ctx, px);
3262
3263 node = ebmb_first(&bind_conf->sni_ctx);
3264 while (node) {
3265 sni = ebmb_entry(node, struct sni_ctx, name);
3266 if (!sni->order && sni->ctx != bind_conf->default_ctx)
3267 /* only initialize the CTX on its first occurrence and
3268 if it is not the default_ctx */
3269 err += ssl_sock_prepare_ctx(bind_conf, sni->ctx, px);
3270 node = ebmb_next(node);
3271 }
3272
3273 node = ebmb_first(&bind_conf->sni_w_ctx);
3274 while (node) {
3275 sni = ebmb_entry(node, struct sni_ctx, name);
3276 if (!sni->order && sni->ctx != bind_conf->default_ctx)
3277 /* only initialize the CTX on its first occurrence and
3278 if it is not the default_ctx */
3279 err += ssl_sock_prepare_ctx(bind_conf, sni->ctx, px);
3280 node = ebmb_next(node);
3281 }
3282 return err;
3283 }
3284
3285
3286 /* release ssl context allocated for servers. */
3287 void ssl_sock_free_srv_ctx(struct server *srv)
3288 {
3289 if (srv->ssl_ctx.ctx)
3290 SSL_CTX_free(srv->ssl_ctx.ctx);
3291 }
3292
3293 /* Walks down the two trees in bind_conf and frees all the certs. The pointer may
3294 * be NULL, in which case nothing is done. The default_ctx is nullified too.
3295 */
3296 void ssl_sock_free_all_ctx(struct bind_conf *bind_conf)
3297 {
3298 struct ebmb_node *node, *back;
3299 struct sni_ctx *sni;
3300
3301 if (!bind_conf || !bind_conf->is_ssl)
3302 return;
3303
3304 node = ebmb_first(&bind_conf->sni_ctx);
3305 while (node) {
3306 sni = ebmb_entry(node, struct sni_ctx, name);
3307 back = ebmb_next(node);
3308 ebmb_delete(node);
3309 if (!sni->order) /* only free the CTX on its first occurrence */
3310 SSL_CTX_free(sni->ctx);
3311 free(sni);
3312 node = back;
3313 }
3314
3315 node = ebmb_first(&bind_conf->sni_w_ctx);
3316 while (node) {
3317 sni = ebmb_entry(node, struct sni_ctx, name);
3318 back = ebmb_next(node);
3319 ebmb_delete(node);
3320 if (!sni->order) /* only free the CTX on its first occurrence */
3321 SSL_CTX_free(sni->ctx);
3322 free(sni);
3323 node = back;
3324 }
3325
3326 bind_conf->default_ctx = NULL;
3327 }
3328
3329 /* Load CA cert file and private key used to generate certificates */
3330 int
3331 ssl_sock_load_ca(struct bind_conf *bind_conf, struct proxy *px)
3332 {
3333 FILE *fp;
3334 X509 *cacert = NULL;
3335 EVP_PKEY *capkey = NULL;
3336 int err = 0;
3337
3338 if (!bind_conf || !bind_conf->generate_certs)
3339 return err;
3340
3341 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
3342 if (global.tune.ssl_ctx_cache)
3343 ssl_ctx_lru_tree = lru64_new(global.tune.ssl_ctx_cache);
3344 ssl_ctx_lru_seed = (unsigned int)time(NULL);
3345 #endif
3346
3347 if (!bind_conf->ca_sign_file) {
3348 Alert("Proxy '%s': cannot enable certificate generation, "
3349 "no CA certificate File configured at [%s:%d].\n",
3350 px->id, bind_conf->file, bind_conf->line);
3351 goto load_error;
3352 }
3353
3354 /* read in the CA certificate */
3355 if (!(fp = fopen(bind_conf->ca_sign_file, "r"))) {
3356 Alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d].\n",
3357 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
3358 goto load_error;
3359 }
3360 if (!(cacert = PEM_read_X509(fp, NULL, NULL, NULL))) {
3361 Alert("Proxy '%s': Failed to read CA certificate file '%s' at [%s:%d].\n",
3362 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
3363 goto read_error;
3364 }
3365 rewind(fp);
3366 if (!(capkey = PEM_read_PrivateKey(fp, NULL, NULL, bind_conf->ca_sign_pass))) {
3367 Alert("Proxy '%s': Failed to read CA private key file '%s' at [%s:%d].\n",
3368 px->id, bind_conf->ca_sign_file, bind_conf->file, bind_conf->line);
3369 goto read_error;
3370 }
3371
3372 fclose (fp);
3373 bind_conf->ca_sign_cert = cacert;
3374 bind_conf->ca_sign_pkey = capkey;
3375 return err;
3376
3377 read_error:
3378 fclose (fp);
3379 if (capkey) EVP_PKEY_free(capkey);
3380 if (cacert) X509_free(cacert);
3381 load_error:
3382 bind_conf->generate_certs = 0;
3383 err++;
3384 return err;
3385 }
3386
3387 /* Release CA cert and private key used to generate certificated */
3388 void
3389 ssl_sock_free_ca(struct bind_conf *bind_conf)
3390 {
3391 if (!bind_conf)
3392 return;
3393
3394 if (bind_conf->ca_sign_pkey)
3395 EVP_PKEY_free(bind_conf->ca_sign_pkey);
3396 if (bind_conf->ca_sign_cert)
3397 X509_free(bind_conf->ca_sign_cert);
3398 bind_conf->ca_sign_pkey = NULL;
3399 bind_conf->ca_sign_cert = NULL;
3400 }
3401
3402 /*
3403 * This function is called if SSL * context is not yet allocated. The function
3404 * is designed to be called before any other data-layer operation and sets the
3405 * handshake flag on the connection. It is safe to call it multiple times.
3406 * It returns 0 on success and -1 in error case.
3407 */
3408 static int ssl_sock_init(struct connection *conn)
3409 {
3410 /* already initialized */
3411 if (conn->xprt_ctx)
3412 return 0;
3413
3414 if (!conn_ctrl_ready(conn))
3415 return 0;
3416
3417 if (global.maxsslconn && sslconns >= global.maxsslconn) {
3418 conn->err_code = CO_ER_SSL_TOO_MANY;
3419 return -1;
3420 }
3421
3422 /* If it is in client mode initiate SSL session
3423 in connect state otherwise accept state */
3424 if (objt_server(conn->target)) {
3425 int may_retry = 1;
3426
3427 retry_connect:
3428 /* Alloc a new SSL session ctx */
3429 conn->xprt_ctx = SSL_new(objt_server(conn->target)->ssl_ctx.ctx);
3430 if (!conn->xprt_ctx) {
3431 if (may_retry--) {
3432 pool_gc2();
3433 goto retry_connect;
3434 }
3435 conn->err_code = CO_ER_SSL_NO_MEM;
3436 return -1;
3437 }
3438
3439 /* set fd on SSL session context */
3440 if (!SSL_set_fd(conn->xprt_ctx, conn->t.sock.fd)) {
3441 SSL_free(conn->xprt_ctx);
3442 conn->xprt_ctx = NULL;
3443 if (may_retry--) {
3444 pool_gc2();
3445 goto retry_connect;
3446 }
3447 conn->err_code = CO_ER_SSL_NO_MEM;
3448 return -1;
3449 }
3450
3451 /* set connection pointer */
3452 if (!SSL_set_app_data(conn->xprt_ctx, conn)) {
3453 SSL_free(conn->xprt_ctx);
3454 conn->xprt_ctx = NULL;
3455 if (may_retry--) {
3456 pool_gc2();
3457 goto retry_connect;
3458 }
3459 conn->err_code = CO_ER_SSL_NO_MEM;
3460 return -1;
3461 }
3462
3463 SSL_set_connect_state(conn->xprt_ctx);
3464 if (objt_server(conn->target)->ssl_ctx.reused_sess) {
3465 if(!SSL_set_session(conn->xprt_ctx, objt_server(conn->target)->ssl_ctx.reused_sess)) {
3466 SSL_SESSION_free(objt_server(conn->target)->ssl_ctx.reused_sess);
3467 objt_server(conn->target)->ssl_ctx.reused_sess = NULL;
3468 }
3469 }
3470
3471 /* leave init state and start handshake */
3472 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
3473
3474 sslconns++;
3475 totalsslconns++;
3476 return 0;
3477 }
3478 else if (objt_listener(conn->target)) {
3479 int may_retry = 1;
3480
3481 retry_accept:
3482 /* Alloc a new SSL session ctx */
3483 conn->xprt_ctx = SSL_new(objt_listener(conn->target)->bind_conf->default_ctx);
3484 if (!conn->xprt_ctx) {
3485 if (may_retry--) {
3486 pool_gc2();
3487 goto retry_accept;
3488 }
3489 conn->err_code = CO_ER_SSL_NO_MEM;
3490 return -1;
3491 }
3492
3493 /* set fd on SSL session context */
3494 if (!SSL_set_fd(conn->xprt_ctx, conn->t.sock.fd)) {
3495 SSL_free(conn->xprt_ctx);
3496 conn->xprt_ctx = NULL;
3497 if (may_retry--) {
3498 pool_gc2();
3499 goto retry_accept;
3500 }
3501 conn->err_code = CO_ER_SSL_NO_MEM;
3502 return -1;
3503 }
3504
3505 /* set connection pointer */
3506 if (!SSL_set_app_data(conn->xprt_ctx, conn)) {
3507 SSL_free(conn->xprt_ctx);
3508 conn->xprt_ctx = NULL;
3509 if (may_retry--) {
3510 pool_gc2();
3511 goto retry_accept;
3512 }
3513 conn->err_code = CO_ER_SSL_NO_MEM;
3514 return -1;
3515 }
3516
3517 SSL_set_accept_state(conn->xprt_ctx);
3518
3519 /* leave init state and start handshake */
3520 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
3521
3522 sslconns++;
3523 totalsslconns++;
3524 return 0;
3525 }
3526 /* don't know how to handle such a target */
3527 conn->err_code = CO_ER_SSL_NO_TARGET;
3528 return -1;
3529 }
3530
3531
3532 /* This is the callback which is used when an SSL handshake is pending. It
3533 * updates the FD status if it wants some polling before being called again.
3534 * It returns 0 if it fails in a fatal way or needs to poll to go further,
3535 * otherwise it returns non-zero and removes itself from the connection's
3536 * flags (the bit is provided in <flag> by the caller).
3537 */
3538 int ssl_sock_handshake(struct connection *conn, unsigned int flag)
3539 {
3540 int ret;
3541
3542 if (!conn_ctrl_ready(conn))
3543 return 0;
3544
3545 if (!conn->xprt_ctx)
3546 goto out_error;
3547
3548 /* If we use SSL_do_handshake to process a reneg initiated by
3549 * the remote peer, it sometimes returns SSL_ERROR_SSL.
3550 * Usually SSL_write and SSL_read are used and process implicitly
3551 * the reneg handshake.
3552 * Here we use SSL_peek as a workaround for reneg.
3553 */
3554 if ((conn->flags & CO_FL_CONNECTED) && SSL_renegotiate_pending(conn->xprt_ctx)) {
3555 char c;
3556
3557 ret = SSL_peek(conn->xprt_ctx, &c, 1);
3558 if (ret <= 0) {
3559 /* handshake may have not been completed, let's find why */
3560 ret = SSL_get_error(conn->xprt_ctx, ret);
3561 if (ret == SSL_ERROR_WANT_WRITE) {
3562 /* SSL handshake needs to write, L4 connection may not be ready */
3563 __conn_sock_stop_recv(conn);
3564 __conn_sock_want_send(conn);
3565 fd_cant_send(conn->t.sock.fd);
3566 return 0;
3567 }
3568 else if (ret == SSL_ERROR_WANT_READ) {
3569 /* handshake may have been completed but we have
3570 * no more data to read.
3571 */
3572 if (!SSL_renegotiate_pending(conn->xprt_ctx)) {
3573 ret = 1;
3574 goto reneg_ok;
3575 }
3576 /* SSL handshake needs to read, L4 connection is ready */
3577 if (conn->flags & CO_FL_WAIT_L4_CONN)
3578 conn->flags &= ~CO_FL_WAIT_L4_CONN;
3579 __conn_sock_stop_send(conn);
3580 __conn_sock_want_recv(conn);
3581 fd_cant_recv(conn->t.sock.fd);
3582 return 0;
3583 }
3584 else if (ret == SSL_ERROR_SYSCALL) {
3585 /* if errno is null, then connection was successfully established */
3586 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
3587 conn->flags &= ~CO_FL_WAIT_L4_CONN;
3588 if (!conn->err_code) {
3589 int empty_handshake;
3590 #if (OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(LIBRESSL_VERSION_NUMBER)
3591 OSSL_HANDSHAKE_STATE state = SSL_get_state((SSL *)conn->xprt_ctx);
3592 empty_handshake = state == TLS_ST_BEFORE;
3593 #else
3594 empty_handshake = SSL_state((SSL *)conn->xprt_ctx) == SSL_ST_BEFORE;
3595 #endif
3596
3597 if (empty_handshake) {
3598 if (!errno) {
3599 if (conn->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
3600 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
3601 else
3602 conn->err_code = CO_ER_SSL_EMPTY;
3603 }
3604 else {
3605 if (conn->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
3606 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
3607 else
3608 conn->err_code = CO_ER_SSL_ABORT;
3609 }
3610 }
3611 else {
3612 if (conn->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
3613 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
3614 else
3615 conn->err_code = CO_ER_SSL_HANDSHAKE;
3616 }
3617 }
3618 goto out_error;
3619 }
3620 else {
3621 /* Fail on all other handshake errors */
3622 /* Note: OpenSSL may leave unread bytes in the socket's
3623 * buffer, causing an RST to be emitted upon close() on
3624 * TCP sockets. We first try to drain possibly pending
3625 * data to avoid this as much as possible.
3626 */
3627 conn_sock_drain(conn);
3628 if (!conn->err_code)
3629 conn->err_code = (conn->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
3630 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
3631 goto out_error;
3632 }
3633 }
3634 /* read some data: consider handshake completed */
3635 goto reneg_ok;
3636 }
3637
3638 ret = SSL_do_handshake(conn->xprt_ctx);
3639 if (ret != 1) {
3640 /* handshake did not complete, let's find why */
3641 ret = SSL_get_error(conn->xprt_ctx, ret);
3642
3643 if (ret == SSL_ERROR_WANT_WRITE) {
3644 /* SSL handshake needs to write, L4 connection may not be ready */
3645 __conn_sock_stop_recv(conn);
3646 __conn_sock_want_send(conn);
3647 fd_cant_send(conn->t.sock.fd);
3648 return 0;
3649 }
3650 else if (ret == SSL_ERROR_WANT_READ) {
3651 /* SSL handshake needs to read, L4 connection is ready */
3652 if (conn->flags & CO_FL_WAIT_L4_CONN)
3653 conn->flags &= ~CO_FL_WAIT_L4_CONN;
3654 __conn_sock_stop_send(conn);
3655 __conn_sock_want_recv(conn);
3656 fd_cant_recv(conn->t.sock.fd);
3657 return 0;
3658 }
3659 else if (ret == SSL_ERROR_SYSCALL) {
3660 #if (OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(LIBRESSL_VERSION_NUMBER)
3661 OSSL_HANDSHAKE_STATE state;
3662 #endif
3663 int empty_handshake;
3664 /* if errno is null, then connection was successfully established */
3665 if (!errno && conn->flags & CO_FL_WAIT_L4_CONN)
3666 conn->flags &= ~CO_FL_WAIT_L4_CONN;
3667
3668 #if (OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(LIBRESSL_VERSION_NUMBER)
3669 state = SSL_get_state((SSL *)conn->xprt_ctx);
3670 empty_handshake = state == TLS_ST_BEFORE;
3671 #else
3672 empty_handshake = SSL_state((SSL *)conn->xprt_ctx) == SSL_ST_BEFORE;
3673 #endif
3674 if (empty_handshake) {
3675 if (!errno) {
3676 if (conn->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
3677 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
3678 else
3679 conn->err_code = CO_ER_SSL_EMPTY;
3680 }
3681 else {
3682 if (conn->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
3683 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
3684 else
3685 conn->err_code = CO_ER_SSL_ABORT;
3686 }
3687 }
3688 else {
3689 if (conn->xprt_st & SSL_SOCK_RECV_HEARTBEAT)
3690 conn->err_code = CO_ER_SSL_HANDSHAKE_HB;
3691 else
3692 conn->err_code = CO_ER_SSL_HANDSHAKE;
3693 }
3694 goto out_error;
3695 }
3696 else {
3697 /* Fail on all other handshake errors */
3698 /* Note: OpenSSL may leave unread bytes in the socket's
3699 * buffer, causing an RST to be emitted upon close() on
3700 * TCP sockets. We first try to drain possibly pending
3701 * data to avoid this as much as possible.
3702 */
3703 conn_sock_drain(conn);
3704 if (!conn->err_code)
3705 conn->err_code = (conn->xprt_st & SSL_SOCK_RECV_HEARTBEAT) ?
3706 CO_ER_SSL_KILLED_HB : CO_ER_SSL_HANDSHAKE;
3707 goto out_error;
3708 }
3709 }
3710
3711 reneg_ok:
3712 /* Handshake succeeded */
3713 if (!SSL_session_reused(conn->xprt_ctx)) {
3714 if (objt_server(conn->target)) {
3715 update_freq_ctr(&global.ssl_be_keys_per_sec, 1);
3716 if (global.ssl_be_keys_per_sec.curr_ctr > global.ssl_be_keys_max)
3717 global.ssl_be_keys_max = global.ssl_be_keys_per_sec.curr_ctr;
3718
3719 /* check if session was reused, if not store current session on server for reuse */
3720 if (objt_server(conn->target)->ssl_ctx.reused_sess) {
3721 SSL_SESSION_free(objt_server(conn->target)->ssl_ctx.reused_sess);
3722 objt_server(conn->target)->ssl_ctx.reused_sess = NULL;
3723 }
3724
3725 if (!(objt_server(conn->target)->ssl_ctx.options & SRV_SSL_O_NO_REUSE))
3726 objt_server(conn->target)->ssl_ctx.reused_sess = SSL_get1_session(conn->xprt_ctx);
3727 }
3728 else {
3729 update_freq_ctr(&global.ssl_fe_keys_per_sec, 1);
3730 if (global.ssl_fe_keys_per_sec.curr_ctr > global.ssl_fe_keys_max)
3731 global.ssl_fe_keys_max = global.ssl_fe_keys_per_sec.curr_ctr;
3732 }
3733 }
3734
3735 /* The connection is now established at both layers, it's time to leave */
3736 conn->flags &= ~(flag | CO_FL_WAIT_L4_CONN | CO_FL_WAIT_L6_CONN);
3737 return 1;
3738
3739 out_error:
3740 /* Clear openssl global errors stack */
3741 ssl_sock_dump_errors(conn);
3742 ERR_clear_error();
3743
3744 /* free resumed session if exists */
3745 if (objt_server(conn->target) && objt_server(conn->target)->ssl_ctx.reused_sess) {
3746 SSL_SESSION_free(objt_server(conn->target)->ssl_ctx.reused_sess);
3747 objt_server(conn->target)->ssl_ctx.reused_sess = NULL;
3748 }
3749
3750 /* Fail on all other handshake errors */
3751 conn->flags |= CO_FL_ERROR;
3752 if (!conn->err_code)
3753 conn->err_code = CO_ER_SSL_HANDSHAKE;
3754 return 0;
3755 }
3756
3757 /* Receive up to <count> bytes from connection <conn>'s socket and store them
3758 * into buffer <buf>. Only one call to recv() is performed, unless the
3759 * buffer wraps, in which case a second call may be performed. The connection's
3760 * flags are updated with whatever special event is detected (error, read0,
3761 * empty). The caller is responsible for taking care of those events and
3762 * avoiding the call if inappropriate. The function does not call the
3763 * connection's polling update function, so the caller is responsible for this.
3764 */
3765 static int ssl_sock_to_buf(struct connection *conn, struct buffer *buf, int count)
3766 {
3767 int ret, done = 0;
3768 int try;
3769
3770 if (!conn->xprt_ctx)
3771 goto out_error;
3772
3773 if (conn->flags & CO_FL_HANDSHAKE)
3774 /* a handshake was requested */
3775 return 0;
3776
3777 /* let's realign the buffer to optimize I/O */
3778 if (buffer_empty(buf))
3779 buf->p = buf->data;
3780
3781 /* read the largest possible block. For this, we perform only one call
3782 * to recv() unless the buffer wraps and we exactly fill the first hunk,
3783 * in which case we accept to do it once again. A new attempt is made on
3784 * EINTR too.
3785 */
3786 while (count > 0) {
3787 /* first check if we have some room after p+i */
3788 try = buf->data + buf->size - (buf->p + buf->i);
3789 /* otherwise continue between data and p-o */
3790 if (try <= 0) {
3791 try = buf->p - (buf->data + buf->o);
3792 if (try <= 0)
3793 break;
3794 }
3795 if (try > count)
3796 try = count;
3797
3798 ret = SSL_read(conn->xprt_ctx, bi_end(buf), try);
3799 if (conn->flags & CO_FL_ERROR) {
3800 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
3801 goto out_error;
3802 }
3803 if (ret > 0) {
3804 buf->i += ret;
3805 done += ret;
3806 if (ret < try)
3807 break;
3808 count -= ret;
3809 }
3810 else if (ret == 0) {
3811 ret = SSL_get_error(conn->xprt_ctx, ret);
3812 if (ret != SSL_ERROR_ZERO_RETURN) {
3813 /* error on protocol or underlying transport */
3814 if ((ret != SSL_ERROR_SYSCALL)
3815 || (errno && (errno != EAGAIN)))
3816 conn->flags |= CO_FL_ERROR;
3817
3818 /* Clear openssl global errors stack */
3819 ssl_sock_dump_errors(conn);
3820 ERR_clear_error();
3821 }
3822 goto read0;
3823 }
3824 else {
3825 ret = SSL_get_error(conn->xprt_ctx, ret);
3826 if (ret == SSL_ERROR_WANT_WRITE) {
3827 /* handshake is running, and it needs to enable write */
3828 conn->flags |= CO_FL_SSL_WAIT_HS;
3829 __conn_sock_want_send(conn);
3830 break;
3831 }
3832 else if (ret == SSL_ERROR_WANT_READ) {
3833 if (SSL_renegotiate_pending(conn->xprt_ctx)) {
3834 /* handshake is running, and it may need to re-enable read */
3835 conn->flags |= CO_FL_SSL_WAIT_HS;
3836 __conn_sock_want_recv(conn);
3837 break;
3838 }
3839 /* we need to poll for retry a read later */
3840 fd_cant_recv(conn->t.sock.fd);
3841 break;
3842 }
3843 /* otherwise it's a real error */
3844 goto out_error;
3845 }
3846 }
3847 return done;
3848
3849 read0:
3850 conn_sock_read0(conn);
3851 return done;
3852 out_error:
3853 /* Clear openssl global errors stack */
3854 ssl_sock_dump_errors(conn);
3855 ERR_clear_error();
3856
3857 conn->flags |= CO_FL_ERROR;
3858 return done;
3859 }
3860
3861
3862 /* Send all pending bytes from buffer <buf> to connection <conn>'s socket.
3863 * <flags> may contain some CO_SFL_* flags to hint the system about other
3864 * pending data for example, but this flag is ignored at the moment.
3865 * Only one call to send() is performed, unless the buffer wraps, in which case
3866 * a second call may be performed. The connection's flags are updated with
3867 * whatever special event is detected (error, empty). The caller is responsible
3868 * for taking care of those events and avoiding the call if inappropriate. The
3869 * function does not call the connection's polling update function, so the caller
3870 * is responsible for this.
3871 */
3872 static int ssl_sock_from_buf(struct connection *conn, struct buffer *buf, int flags)
3873 {
3874 int ret, try, done;
3875
3876 done = 0;
3877
3878 if (!conn->xprt_ctx)
3879 goto out_error;
3880
3881 if (conn->flags & CO_FL_HANDSHAKE)
3882 /* a handshake was requested */
3883 return 0;
3884
3885 /* send the largest possible block. For this we perform only one call
3886 * to send() unless the buffer wraps and we exactly fill the first hunk,
3887 * in which case we accept to do it once again.
3888 */
3889 while (buf->o) {
3890 try = bo_contig_data(buf);
3891
3892 if (!(flags & CO_SFL_STREAMER) &&
3893 !(conn->xprt_st & SSL_SOCK_SEND_UNLIMITED) &&
3894 global.tune.ssl_max_record && try > global.tune.ssl_max_record) {
3895 try = global.tune.ssl_max_record;
3896 }
3897 else {
3898 /* we need to keep the information about the fact that
3899 * we're not limiting the upcoming send(), because if it
3900 * fails, we'll have to retry with at least as many data.
3901 */
3902 conn->xprt_st |= SSL_SOCK_SEND_UNLIMITED;
3903 }
3904
3905 ret = SSL_write(conn->xprt_ctx, bo_ptr(buf), try);
3906
3907 if (conn->flags & CO_FL_ERROR) {
3908 /* CO_FL_ERROR may be set by ssl_sock_infocbk */
3909 goto out_error;
3910 }
3911 if (ret > 0) {
3912 conn->xprt_st &= ~SSL_SOCK_SEND_UNLIMITED;
3913
3914 buf->o -= ret;
3915 done += ret;
3916
3917 if (likely(buffer_empty(buf)))
3918 /* optimize data alignment in the buffer */
3919 buf->p = buf->data;
3920
3921 /* if the system buffer is full, don't insist */
3922 if (ret < try)
3923 break;
3924 }
3925 else {
3926 ret = SSL_get_error(conn->xprt_ctx, ret);
3927 if (ret == SSL_ERROR_WANT_WRITE) {
3928 if (SSL_renegotiate_pending(conn->xprt_ctx)) {
3929 /* handshake is running, and it may need to re-enable write */
3930 conn->flags |= CO_FL_SSL_WAIT_HS;
3931 __conn_sock_want_send(conn);
3932 break;
3933 }
3934 /* we need to poll to retry a write later */
3935 fd_cant_send(conn->t.sock.fd);
3936 break;
3937 }
3938 else if (ret == SSL_ERROR_WANT_READ) {
3939 /* handshake is running, and it needs to enable read */
3940 conn->flags |= CO_FL_SSL_WAIT_HS;
3941 __conn_sock_want_recv(conn);
3942 break;
3943 }
3944 goto out_error;
3945 }
3946 }
3947 return done;
3948
3949 out_error:
3950 /* Clear openssl global errors stack */
3951 ssl_sock_dump_errors(conn);
3952 ERR_clear_error();
3953
3954 conn->flags |= CO_FL_ERROR;
3955 return done;
3956 }
3957
3958 static void ssl_sock_close(struct connection *conn) {
3959
3960 if (conn->xprt_ctx) {
3961 SSL_free(conn->xprt_ctx);
3962 conn->xprt_ctx = NULL;
3963 sslconns--;
3964 }
3965 }
3966
3967 /* This function tries to perform a clean shutdown on an SSL connection, and in
3968 * any case, flags the connection as reusable if no handshake was in progress.
3969 */
3970 static void ssl_sock_shutw(struct connection *conn, int clean)
3971 {
3972 if (conn->flags & CO_FL_HANDSHAKE)
3973 return;
3974 /* no handshake was in progress, try a clean ssl shutdown */
3975 if (clean && (SSL_shutdown(conn->xprt_ctx) <= 0)) {
3976 /* Clear openssl global errors stack */
3977 ssl_sock_dump_errors(conn);
3978 ERR_clear_error();
3979 }
3980
3981 /* force flag on ssl to keep session in cache regardless shutdown result */
3982 SSL_set_shutdown(conn->xprt_ctx, SSL_SENT_SHUTDOWN);
3983 }
3984
3985 /* used for logging, may be changed for a sample fetch later */
3986 const char *ssl_sock_get_cipher_name(struct connection *conn)
3987 {
3988 if (!conn->xprt && !conn->xprt_ctx)
3989 return NULL;
3990 return SSL_get_cipher_name(conn->xprt_ctx);
3991 }
3992
3993 /* used for logging, may be changed for a sample fetch later */
3994 const char *ssl_sock_get_proto_version(struct connection *conn)
3995 {
3996 if (!conn->xprt && !conn->xprt_ctx)
3997 return NULL;
3998 return SSL_get_version(conn->xprt_ctx);
3999 }
4000
4001 /* Extract a serial from a cert, and copy it to a chunk.
4002 * Returns 1 if serial is found and copied, 0 if no serial found and
4003 * -1 if output is not large enough.
4004 */
4005 static int
4006 ssl_sock_get_serial(X509 *crt, struct chunk *out)
4007 {
4008 ASN1_INTEGER *serial;
4009
4010 serial = X509_get_serialNumber(crt);
4011 if (!serial)
4012 return 0;
4013
4014 if (out->size < serial->length)
4015 return -1;
4016
4017 memcpy(out->str, serial->data, serial->length);
4018 out->len = serial->length;
4019 return 1;
4020 }
4021
4022 /* Extract a cert to der, and copy it to a chunk.
4023 * Returns 1 if cert is found and copied, 0 on der convertion failure and
4024 * -1 if output is not large enough.
4025 */
4026 static int
4027 ssl_sock_crt2der(X509 *crt, struct chunk *out)
4028 {
4029 int len;
4030 unsigned char *p = (unsigned char *)out->str;;
4031
4032 len =i2d_X509(crt, NULL);
4033 if (len <= 0)
4034 return 1;
4035
4036 if (out->size < len)
4037 return -1;
4038
4039 i2d_X509(crt,&p);
4040 out->len = len;
4041 return 1;
4042 }
4043
4044
4045 /* Copy Date in ASN1_UTCTIME format in struct chunk out.
4046 * Returns 1 if serial is found and copied, 0 if no valid time found
4047 * and -1 if output is not large enough.
4048 */
4049 static int
4050 ssl_sock_get_time(ASN1_TIME *tm, struct chunk *out)
4051 {
4052 if (tm->type == V_ASN1_GENERALIZEDTIME) {
4053 ASN1_GENERALIZEDTIME *gentm = (ASN1_GENERALIZEDTIME *)tm;
4054
4055 if (gentm->length < 12)
4056 return 0;
4057 if (gentm->data[0] != 0x32 || gentm->data[1] != 0x30)
4058 return 0;
4059 if (out->size < gentm->length-2)
4060 return -1;
4061
4062 memcpy(out->str, gentm->data+2, gentm->length-2);
4063 out->len = gentm->length-2;
4064 return 1;
4065 }
4066 else if (tm->type == V_ASN1_UTCTIME) {
4067 ASN1_UTCTIME *utctm = (ASN1_UTCTIME *)tm;
4068
4069 if (utctm->length < 10)
4070 return 0;
4071 if (utctm->data[0] >= 0x35)
4072 return 0;
4073 if (out->size < utctm->length)
4074 return -1;
4075
4076 memcpy(out->str, utctm->data, utctm->length);
4077 out->len = utctm->length;
4078 return 1;
4079 }
4080
4081 return 0;
4082 }
4083
4084 /* Extract an entry from a X509_NAME and copy its value to an output chunk.
4085 * Returns 1 if entry found, 0 if entry not found, or -1 if output not large enough.
4086 */
4087 static int
4088 ssl_sock_get_dn_entry(X509_NAME *a, const struct chunk *entry, int pos, struct chunk *out)
4089 {
4090 X509_NAME_ENTRY *ne;
4091 ASN1_OBJECT *obj;
4092 ASN1_STRING *data;
4093 const unsigned char *data_ptr;
4094 int data_len;
4095 int i, j, n;
4096 int cur = 0;
4097 const char *s;
4098 char tmp[128];
4099 int name_count;
4100
4101 name_count = X509_NAME_entry_count(a);
4102
4103 out->len = 0;
4104 for (i = 0; i < name_count; i++) {
4105 if (pos < 0)
4106 j = (name_count-1) - i;
4107 else
4108 j = i;
4109
4110 ne = X509_NAME_get_entry(a, j);
4111 obj = X509_NAME_ENTRY_get_object(ne);
4112 data = X509_NAME_ENTRY_get_data(ne);
4113 data_ptr = ASN1_STRING_get0_data(data);
4114 data_len = ASN1_STRING_length(data);
4115 n = OBJ_obj2nid(obj);
4116 if ((n == NID_undef) || ((s = OBJ_nid2sn(n)) == NULL)) {
4117 i2t_ASN1_OBJECT(tmp, sizeof(tmp), obj);
4118 s = tmp;
4119 }
4120
4121 if (chunk_strcasecmp(entry, s) != 0)
4122 continue;
4123
4124 if (pos < 0)
4125 cur--;
4126 else
4127 cur++;
4128
4129 if (cur != pos)
4130 continue;
4131
4132 if (data_len > out->size)
4133 return -1;
4134
4135 memcpy(out->str, data_ptr, data_len);
4136 out->len = data_len;
4137 return 1;
4138 }
4139
4140 return 0;
4141
4142 }
4143
4144 /* Extract and format full DN from a X509_NAME and copy result into a chunk
4145 * Returns 1 if dn entries exits, 0 if no dn entry found or -1 if output is not large enough.
4146 */
4147 static int
4148 ssl_sock_get_dn_oneline(X509_NAME *a, struct chunk *out)
4149 {
4150 X509_NAME_ENTRY *ne;
4151 ASN1_OBJECT *obj;
4152 ASN1_STRING *data;
4153 const unsigned char *data_ptr;
4154 int data_len;
4155 int i, n, ln;
4156 int l = 0;
4157 const char *s;
4158 char *p;
4159 char tmp[128];
4160 int name_count;
4161
4162
4163 name_count = X509_NAME_entry_count(a);
4164
4165 out->len = 0;
4166 p = out->str;
4167 for (i = 0; i < name_count; i++) {
4168 ne = X509_NAME_get_entry(a, i);
4169 obj = X509_NAME_ENTRY_get_object(ne);
4170 data = X509_NAME_ENTRY_get_data(ne);
4171 data_ptr = ASN1_STRING_get0_data(data);
4172 data_len = ASN1_STRING_length(data);
4173 n = OBJ_obj2nid(obj);
4174 if ((n == NID_undef) || ((s = OBJ_nid2sn(n)) == NULL)) {
4175 i2t_ASN1_OBJECT(tmp, sizeof(tmp), obj);
4176 s = tmp;
4177 }
4178 ln = strlen(s);
4179
4180 l += 1 + ln + 1 + data_len;
4181 if (l > out->size)
4182 return -1;
4183 out->len = l;
4184
4185 *(p++)='/';
4186 memcpy(p, s, ln);
4187 p += ln;
4188 *(p++)='=';
4189 memcpy(p, data_ptr, data_len);
4190 p += data_len;
4191 }
4192
4193 if (!out->len)
4194 return 0;
4195
4196 return 1;
4197 }
4198
4199 char *ssl_sock_get_version(struct connection *conn)
4200 {
4201 if (!ssl_sock_is_ssl(conn))
4202 return NULL;
4203
4204 return (char *)SSL_get_version(conn->xprt_ctx);
4205 }
4206
4207 /* Sets advertised SNI for outgoing connections. Please set <hostname> to NULL
4208 * to disable SNI.
4209 */
4210 void ssl_sock_set_servername(struct connection *conn, const char *hostname)
4211 {
4212 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
4213 char *prev_name;
4214
4215 if (!ssl_sock_is_ssl(conn))
4216 return;
4217
4218 /* if the SNI changes, we must destroy the reusable context so that a
4219 * new connection will present a new SNI. As an optimization we could
4220 * later imagine having a small cache of ssl_ctx to hold a few SNI per
4221 * server.
4222 */
4223 prev_name = (char *)SSL_get_servername(conn->xprt_ctx, TLSEXT_NAMETYPE_host_name);
4224 if ((!prev_name && hostname) ||
4225 (prev_name && (!hostname || strcmp(hostname, prev_name) != 0)))
4226 SSL_set_session(conn->xprt_ctx, NULL);
4227
4228 SSL_set_tlsext_host_name(conn->xprt_ctx, hostname);
4229 #endif
4230 }
4231
4232 /* Extract peer certificate's common name into the chunk dest
4233 * Returns
4234 * the len of the extracted common name
4235 * or 0 if no CN found in DN
4236 * or -1 on error case (i.e. no peer certificate)
4237 */
4238 int ssl_sock_get_remote_common_name(struct connection *conn, struct chunk *dest)
4239 {
4240 X509 *crt = NULL;
4241 X509_NAME *name;
4242 const char find_cn[] = "CN";
4243 const struct chunk find_cn_chunk = {
4244 .str = (char *)&find_cn,
4245 .len = sizeof(find_cn)-1
4246 };
4247 int result = -1;
4248
4249 if (!ssl_sock_is_ssl(conn))
4250 goto out;
4251
4252 /* SSL_get_peer_certificate, it increase X509 * ref count */
4253 crt = SSL_get_peer_certificate(conn->xprt_ctx);
4254 if (!crt)
4255 goto out;
4256
4257 name = X509_get_subject_name(crt);
4258 if (!name)
4259 goto out;
4260
4261 result = ssl_sock_get_dn_entry(name, &find_cn_chunk, 1, dest);
4262 out:
4263 if (crt)
4264 X509_free(crt);
4265
4266 return result;
4267 }
4268
4269 /* returns 1 if client passed a certificate for this session, 0 if not */
4270 int ssl_sock_get_cert_used_sess(struct connection *conn)
4271 {
4272 X509 *crt = NULL;
4273
4274 if (!ssl_sock_is_ssl(conn))
4275 return 0;
4276
4277 /* SSL_get_peer_certificate, it increase X509 * ref count */
4278 crt = SSL_get_peer_certificate(conn->xprt_ctx);
4279 if (!crt)
4280 return 0;
4281
4282 X509_free(crt);
4283 return 1;
4284 }
4285
4286 /* returns 1 if client passed a certificate for this connection, 0 if not */
4287 int ssl_sock_get_cert_used_conn(struct connection *conn)
4288 {
4289 if (!ssl_sock_is_ssl(conn))
4290 return 0;
4291
4292 return SSL_SOCK_ST_FL_VERIFY_DONE & conn->xprt_st ? 1 : 0;
4293 }
4294
4295 /* returns result from SSL verify */
4296 unsigned int ssl_sock_get_verify_result(struct connection *conn)
4297 {
4298 if (!ssl_sock_is_ssl(conn))
4299 return (unsigned int)X509_V_ERR_APPLICATION_VERIFICATION;
4300
4301 return (unsigned int)SSL_get_verify_result(conn->xprt_ctx);
4302 }
4303
4304 /***** Below are some sample fetching functions for ACL/patterns *****/
4305
4306 /* boolean, returns true if client cert was present */
4307 static int
4308 smp_fetch_ssl_fc_has_crt(const struct arg *args, struct sample *smp, const char *kw, void *private)
4309 {
4310 struct connection *conn;
4311
4312 conn = objt_conn(smp->sess->origin);
4313 if (!conn || conn->xprt != &ssl_sock)
4314 return 0;
4315
4316 if (!(conn->flags & CO_FL_CONNECTED)) {
4317 smp->flags |= SMP_F_MAY_CHANGE;
4318 return 0;
4319 }
4320
4321 smp->flags = 0;
4322 smp->data.type = SMP_T_BOOL;
4323 smp->data.u.sint = SSL_SOCK_ST_FL_VERIFY_DONE & conn->xprt_st ? 1 : 0;
4324
4325 return 1;
4326 }
4327
4328 /* binary, returns a certificate in a binary chunk (der/raw).
4329 * The 5th keyword char is used to know if SSL_get_certificate or SSL_get_peer_certificate
4330 * should be use.
4331 */
4332 static int
4333 smp_fetch_ssl_x_der(const struct arg *args, struct sample *smp, const char *kw, void *private)
4334 {
4335 int cert_peer = (kw[4] == 'c') ? 1 : 0;
4336 X509 *crt = NULL;
4337 int ret = 0;
4338 struct chunk *smp_trash;
4339 struct connection *conn;
4340
4341 conn = objt_conn(smp->sess->origin);
4342 if (!conn || conn->xprt != &ssl_sock)
4343 return 0;
4344
4345 if (!(conn->flags & CO_FL_CONNECTED)) {
4346 smp->flags |= SMP_F_MAY_CHANGE;
4347 return 0;
4348 }
4349
4350 if (cert_peer)
4351 crt = SSL_get_peer_certificate(conn->xprt_ctx);
4352 else
4353 crt = SSL_get_certificate(conn->xprt_ctx);
4354
4355 if (!crt)
4356 goto out;
4357
4358 smp_trash = get_trash_chunk();
4359 if (ssl_sock_crt2der(crt, smp_trash) <= 0)
4360 goto out;
4361
4362 smp->data.u.str = *smp_trash;
4363 smp->data.type = SMP_T_BIN;
4364 ret = 1;
4365 out:
4366 /* SSL_get_peer_certificate, it increase X509 * ref count */
4367 if (cert_peer && crt)
4368 X509_free(crt);
4369 return ret;
4370 }
4371
4372 /* binary, returns serial of certificate in a binary chunk.
4373 * The 5th keyword char is used to know if SSL_get_certificate or SSL_get_peer_certificate
4374 * should be use.
4375 */
4376 static int
4377 smp_fetch_ssl_x_serial(const struct arg *args, struct sample *smp, const char *kw, void *private)
4378 {
4379 int cert_peer = (kw[4] == 'c') ? 1 : 0;
4380 X509 *crt = NULL;
4381 int ret = 0;
4382 struct chunk *smp_trash;
4383 struct connection *conn;
4384
4385 conn = objt_conn(smp->sess->origin);
4386 if (!conn || conn->xprt != &ssl_sock)
4387 return 0;
4388
4389 if (!(conn->flags & CO_FL_CONNECTED)) {
4390 smp->flags |= SMP_F_MAY_CHANGE;
4391 return 0;
4392 }
4393
4394 if (cert_peer)
4395 crt = SSL_get_peer_certificate(conn->xprt_ctx);
4396 else
4397 crt = SSL_get_certificate(conn->xprt_ctx);
4398
4399 if (!crt)
4400 goto out;
4401
4402 smp_trash = get_trash_chunk();
4403 if (ssl_sock_get_serial(crt, smp_trash) <= 0)
4404 goto out;
4405
4406 smp->data.u.str = *smp_trash;
4407 smp->data.type = SMP_T_BIN;
4408 ret = 1;
4409 out:
4410 /* SSL_get_peer_certificate, it increase X509 * ref count */
4411 if (cert_peer && crt)
4412 X509_free(crt);
4413 return ret;
4414 }
4415
4416 /* binary, returns the client certificate's SHA-1 fingerprint (SHA-1 hash of DER-encoded certificate) in a binary chunk.
4417 * The 5th keyword char is used to know if SSL_get_certificate or SSL_get_peer_certificate
4418 * should be use.
4419 */
4420 static int
4421 smp_fetch_ssl_x_sha1(const struct arg *args, struct sample *smp, const char *kw, void *private)
4422 {
4423 int cert_peer = (kw[4] == 'c') ? 1 : 0;
4424 X509 *crt = NULL;
4425 const EVP_MD *digest;
4426 int ret = 0;
4427 struct chunk *smp_trash;
4428 struct connection *conn;
4429
4430 conn = objt_conn(smp->sess->origin);
4431 if (!conn || conn->xprt != &ssl_sock)
4432 return 0;
4433
4434 if (!(conn->flags & CO_FL_CONNECTED)) {
4435 smp->flags |= SMP_F_MAY_CHANGE;
4436 return 0;
4437 }
4438
4439 if (cert_peer)
4440 crt = SSL_get_peer_certificate(conn->xprt_ctx);
4441 else
4442 crt = SSL_get_certificate(conn->xprt_ctx);
4443 if (!crt)
4444 goto out;
4445
4446 smp_trash = get_trash_chunk();
4447 digest = EVP_sha1();
4448 X509_digest(crt, digest, (unsigned char *)smp_trash->str, (unsigned int *)&smp_trash->len);
4449
4450 smp->data.u.str = *smp_trash;
4451 smp->data.type = SMP_T_BIN;
4452 ret = 1;
4453 out:
4454 /* SSL_get_peer_certificate, it increase X509 * ref count */
4455 if (cert_peer && crt)
4456 X509_free(crt);
4457 return ret;
4458 }
4459
4460 /* string, returns certificate's notafter date in ASN1_UTCTIME format.
4461 * The 5th keyword char is used to know if SSL_get_certificate or SSL_get_peer_certificate
4462 * should be use.
4463 */
4464 static int
4465 smp_fetch_ssl_x_notafter(const struct arg *args, struct sample *smp, const char *kw, void *private)
4466 {
4467 int cert_peer = (kw[4] == 'c') ? 1 : 0;
4468 X509 *crt = NULL;
4469 int ret = 0;
4470 struct chunk *smp_trash;
4471 struct connection *conn;
4472
4473 conn = objt_conn(smp->sess->origin);
4474 if (!conn || conn->xprt != &ssl_sock)
4475 return 0;
4476
4477 if (!(conn->flags & CO_FL_CONNECTED)) {
4478 smp->flags |= SMP_F_MAY_CHANGE;
4479 return 0;
4480 }
4481
4482 if (cert_peer)
4483 crt = SSL_get_peer_certificate(conn->xprt_ctx);
4484 else
4485 crt = SSL_get_certificate(conn->xprt_ctx);
4486 if (!crt)
4487 goto out;
4488
4489 smp_trash = get_trash_chunk();
4490 if (ssl_sock_get_time(X509_get_notAfter(crt), smp_trash) <= 0)
4491 goto out;
4492
4493 smp->data.u.str = *smp_trash;
4494 smp->data.type = SMP_T_STR;
4495 ret = 1;
4496 out:
4497 /* SSL_get_peer_certificate, it increase X509 * ref count */
4498 if (cert_peer && crt)
4499 X509_free(crt);
4500 return ret;
4501 }
4502
4503 /* string, returns a string of a formatted full dn \C=..\O=..\OU=.. \CN=.. of certificate's issuer
4504 * The 5th keyword char is used to know if SSL_get_certificate or SSL_get_peer_certificate
4505 * should be use.
4506 */
4507 static int
4508 smp_fetch_ssl_x_i_dn(const struct arg *args, struct sample *smp, const char *kw, void *private)
4509 {
4510 int cert_peer = (kw[4] == 'c') ? 1 : 0;
4511 X509 *crt = NULL;
4512 X509_NAME *name;
4513 int ret = 0;
4514 struct chunk *smp_trash;
4515 struct connection *conn;
4516
4517 conn = objt_conn(smp->sess->origin);
4518 if (!conn || conn->xprt != &ssl_sock)
4519 return 0;
4520
4521 if (!(conn->flags & CO_FL_CONNECTED)) {
4522 smp->flags |= SMP_F_MAY_CHANGE;
4523 return 0;
4524 }
4525
4526 if (cert_peer)
4527 crt = SSL_get_peer_certificate(conn->xprt_ctx);
4528 else
4529 crt = SSL_get_certificate(conn->xprt_ctx);
4530 if (!crt)
4531 goto out;
4532
4533 name = X509_get_issuer_name(crt);
4534 if (!name)
4535 goto out;
4536
4537 smp_trash = get_trash_chunk();
4538 if (args && args[0].type == ARGT_STR) {
4539 int pos = 1;
4540
4541 if (args[1].type == ARGT_SINT)
4542 pos = args[1].data.sint;
4543
4544 if (ssl_sock_get_dn_entry(name, &args[0].data.str, pos, smp_trash) <= 0)
4545 goto out;
4546 }
4547 else if (ssl_sock_get_dn_oneline(name, smp_trash) <= 0)
4548 goto out;
4549
4550 smp->data.type = SMP_T_STR;
4551 smp->data.u.str = *smp_trash;
4552 ret = 1;
4553 out:
4554 /* SSL_get_peer_certificate, it increase X509 * ref count */
4555 if (cert_peer && crt)
4556 X509_free(crt);
4557 return ret;
4558 }
4559
4560 /* string, returns notbefore date in ASN1_UTCTIME format.
4561 * The 5th keyword char is used to know if SSL_get_certificate or SSL_get_peer_certificate
4562 * should be use.
4563 */
4564 static int
4565 smp_fetch_ssl_x_notbefore(const struct arg *args, struct sample *smp, const char *kw, void *private)
4566 {
4567 int cert_peer = (kw[4] == 'c') ? 1 : 0;
4568 X509 *crt = NULL;
4569 int ret = 0;
4570 struct chunk *smp_trash;
4571 struct connection *conn;
4572
4573 conn = objt_conn(smp->sess->origin);
4574 if (!conn || conn->xprt != &ssl_sock)
4575 return 0;
4576
4577 if (!(conn->flags & CO_FL_CONNECTED)) {
4578 smp->flags |= SMP_F_MAY_CHANGE;
4579 return 0;
4580 }
4581
4582 if (cert_peer)
4583 crt = SSL_get_peer_certificate(conn->xprt_ctx);
4584 else
4585 crt = SSL_get_certificate(conn->xprt_ctx);
4586 if (!crt)
4587 goto out;
4588
4589 smp_trash = get_trash_chunk();
4590 if (ssl_sock_get_time(X509_get_notBefore(crt), smp_trash) <= 0)
4591 goto out;
4592
4593 smp->data.u.str = *smp_trash;
4594 smp->data.type = SMP_T_STR;
4595 ret = 1;
4596 out:
4597 /* SSL_get_peer_certificate, it increase X509 * ref count */
4598 if (cert_peer && crt)
4599 X509_free(crt);
4600 return ret;
4601 }
4602
4603 /* string, returns a string of a formatted full dn \C=..\O=..\OU=.. \CN=.. of certificate's subject
4604 * The 5th keyword char is used to know if SSL_get_certificate or SSL_get_peer_certificate
4605 * should be use.
4606 */
4607 static int
4608 smp_fetch_ssl_x_s_dn(const struct arg *args, struct sample *smp, const char *kw, void *private)
4609 {
4610 int cert_peer = (kw[4] == 'c') ? 1 : 0;
4611 X509 *crt = NULL;
4612 X509_NAME *name;
4613 int ret = 0;
4614 struct chunk *smp_trash;
4615 struct connection *conn;
4616
4617 conn = objt_conn(smp->sess->origin);
4618 if (!conn || conn->xprt != &ssl_sock)
4619 return 0;
4620
4621 if (!(conn->flags & CO_FL_CONNECTED)) {
4622 smp->flags |= SMP_F_MAY_CHANGE;
4623 return 0;
4624 }
4625
4626 if (cert_peer)
4627 crt = SSL_get_peer_certificate(conn->xprt_ctx);
4628 else
4629 crt = SSL_get_certificate(conn->xprt_ctx);
4630 if (!crt)
4631 goto out;
4632
4633 name = X509_get_subject_name(crt);
4634 if (!name)
4635 goto out;
4636
4637 smp_trash = get_trash_chunk();
4638 if (args && args[0].type == ARGT_STR) {
4639 int pos = 1;
4640
4641 if (args[1].type == ARGT_SINT)
4642 pos = args[1].data.sint;
4643
4644 if (ssl_sock_get_dn_entry(name, &args[0].data.str, pos, smp_trash) <= 0)
4645 goto out;
4646 }
4647 else if (ssl_sock_get_dn_oneline(name, smp_trash) <= 0)
4648 goto out;
4649
4650 smp->data.type = SMP_T_STR;
4651 smp->data.u.str = *smp_trash;
4652 ret = 1;
4653 out:
4654 /* SSL_get_peer_certificate, it increase X509 * ref count */
4655 if (cert_peer && crt)
4656 X509_free(crt);
4657 return ret;
4658 }
4659
4660 /* integer, returns true if current session use a client certificate */
4661 static int
4662 smp_fetch_ssl_c_used(const struct arg *args, struct sample *smp, const char *kw, void *private)
4663 {
4664 X509 *crt;
4665 struct connection *conn;
4666
4667 conn = objt_conn(smp->sess->origin);
4668 if (!conn || conn->xprt != &ssl_sock)
4669 return 0;
4670
4671 if (!(conn->flags & CO_FL_CONNECTED)) {
4672 smp->flags |= SMP_F_MAY_CHANGE;
4673 return 0;
4674 }
4675
4676 /* SSL_get_peer_certificate returns a ptr on allocated X509 struct */
4677 crt = SSL_get_peer_certificate(conn->xprt_ctx);
4678 if (crt) {
4679 X509_free(crt);
4680 }
4681
4682 smp->data.type = SMP_T_BOOL;
4683 smp->data.u.sint = (crt != NULL);
4684 return 1;
4685 }
4686
4687 /* integer, returns the certificate version
4688 * The 5th keyword char is used to know if SSL_get_certificate or SSL_get_peer_certificate
4689 * should be use.
4690 */
4691 static int
4692 smp_fetch_ssl_x_version(const struct arg *args, struct sample *smp, const char *kw, void *private)
4693 {
4694 int cert_peer = (kw[4] == 'c') ? 1 : 0;
4695 X509 *crt;
4696 struct connection *conn;
4697
4698 conn = objt_conn(smp->sess->origin);
4699 if (!conn || conn->xprt != &ssl_sock)
4700 return 0;
4701
4702 if (!(conn->flags & CO_FL_CONNECTED)) {
4703 smp->flags |= SMP_F_MAY_CHANGE;
4704 return 0;
4705 }
4706
4707 if (cert_peer)
4708 crt = SSL_get_peer_certificate(conn->xprt_ctx);
4709 else
4710 crt = SSL_get_certificate(conn->xprt_ctx);
4711 if (!crt)
4712 return 0;
4713
4714 smp->data.u.sint = (unsigned int)(1 + X509_get_version(crt));
4715 /* SSL_get_peer_certificate increase X509 * ref count */
4716 if (cert_peer)
4717 X509_free(crt);
4718 smp->data.type = SMP_T_SINT;
4719
4720 return 1;
4721 }
4722
4723 /* string, returns the certificate's signature algorithm.
4724 * The 5th keyword char is used to know if SSL_get_certificate or SSL_get_peer_certificate
4725 * should be use.
4726 */
4727 static int
4728 smp_fetch_ssl_x_sig_alg(const struct arg *args, struct sample *smp, const char *kw, void *private)
4729 {
4730 int cert_peer = (kw[4] == 'c') ? 1 : 0;
4731 X509 *crt;
4732 __OPENSSL_110_CONST__ ASN1_OBJECT *algorithm;
4733 int nid;
4734 struct connection *conn;
4735
4736 conn = objt_conn(smp->sess->origin);
4737 if (!conn || conn->xprt != &ssl_sock)
4738 return 0;
4739
4740 if (!(conn->flags & CO_FL_CONNECTED)) {
4741 smp->flags |= SMP_F_MAY_CHANGE;
4742 return 0;
4743 }
4744
4745 if (cert_peer)
4746 crt = SSL_get_peer_certificate(conn->xprt_ctx);
4747 else
4748 crt = SSL_get_certificate(conn->xprt_ctx);
4749 if (!crt)
4750 return 0;
4751
4752 X509_ALGOR_get0(&algorithm, NULL, NULL, X509_get0_tbs_sigalg(crt));
4753 nid = OBJ_obj2nid(algorithm);
4754
4755 smp->data.u.str.str = (char *)OBJ_nid2sn(nid);
4756 if (!smp->data.u.str.str) {
4757 /* SSL_get_peer_certificate increase X509 * ref count */
4758 if (cert_peer)
4759 X509_free(crt);
4760 return 0;
4761 }
4762
4763 smp->data.type = SMP_T_STR;
4764 smp->flags |= SMP_F_CONST;
4765 smp->data.u.str.len = strlen(smp->data.u.str.str);
4766 /* SSL_get_peer_certificate increase X509 * ref count */
4767 if (cert_peer)
4768 X509_free(crt);
4769
4770 return 1;
4771 }
4772
4773 /* string, returns the certificate's key algorithm.
4774 * The 5th keyword char is used to know if SSL_get_certificate or SSL_get_peer_certificate
4775 * should be use.
4776 */
4777 static int
4778 smp_fetch_ssl_x_key_alg(const struct arg *args, struct sample *smp, const char *kw, void *private)
4779 {
4780 int cert_peer = (kw[4] == 'c') ? 1 : 0;
4781 X509 *crt;
4782 ASN1_OBJECT *algorithm;
4783 int nid;
4784 struct connection *conn;
4785
4786 conn = objt_conn(smp->sess->origin);
4787 if (!conn || conn->xprt != &ssl_sock)
4788 return 0;
4789
4790 if (!(conn->flags & CO_FL_CONNECTED)) {
4791 smp->flags |= SMP_F_MAY_CHANGE;
4792 return 0;
4793 }
4794
4795 if (cert_peer)
4796 crt = SSL_get_peer_certificate(conn->xprt_ctx);
4797 else
4798 crt = SSL_get_certificate(conn->xprt_ctx);
4799 if (!crt)
4800 return 0;
4801
4802 X509_PUBKEY_get0_param(&algorithm, NULL, NULL, NULL, X509_get_X509_PUBKEY(crt));
4803 nid = OBJ_obj2nid(algorithm);
4804
4805 smp->data.u.str.str = (char *)OBJ_nid2sn(nid);
4806 if (!smp->data.u.str.str) {
4807 /* SSL_get_peer_certificate increase X509 * ref count */
4808 if (cert_peer)
4809 X509_free(crt);
4810 return 0;
4811 }
4812
4813 smp->data.type = SMP_T_STR;
4814 smp->flags |= SMP_F_CONST;
4815 smp->data.u.str.len = strlen(smp->data.u.str.str);
4816 if (cert_peer)
4817 X509_free(crt);
4818
4819 return 1;
4820 }
4821
4822 /* boolean, returns true if front conn. transport layer is SSL.
4823 * This function is also usable on backend conn if the fetch keyword 5th
4824 * char is 'b'.
4825 */
4826 static int
4827 smp_fetch_ssl_fc(const struct arg *args, struct sample *smp, const char *kw, void *private)
4828 {
4829 struct connection *conn = objt_conn((kw[4] != 'b') ? smp->sess->origin :
4830 smp->strm ? smp->strm->si[1].end : NULL);
4831
4832 smp->data.type = SMP_T_BOOL;
4833 smp->data.u.sint = (conn && conn->xprt == &ssl_sock);
4834 return 1;
4835 }
4836
4837 /* boolean, returns true if client present a SNI */
4838 static int
4839 smp_fetch_ssl_fc_has_sni(const struct arg *args, struct sample *smp, const char *kw, void *private)
4840 {
4841 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
4842 struct connection *conn = objt_conn(smp->sess->origin);
4843
4844 smp->data.type = SMP_T_BOOL;
4845 smp->data.u.sint = (conn && conn->xprt == &ssl_sock) &&
4846 conn->xprt_ctx &&
4847 SSL_get_servername(conn->xprt_ctx, TLSEXT_NAMETYPE_host_name) != NULL;
4848 return 1;
4849 #else
4850 return 0;
4851 #endif
4852 }
4853
4854 /* boolean, returns true if client session has been resumed */
4855 static int
4856 smp_fetch_ssl_fc_is_resumed(const struct arg *args, struct sample *smp, const char *kw, void *private)
4857 {
4858 struct connection *conn = objt_conn(smp->sess->origin);
4859
4860 smp->data.type = SMP_T_BOOL;
4861 smp->data.u.sint = (conn && conn->xprt == &ssl_sock) &&
4862 conn->xprt_ctx &&
4863 SSL_session_reused(conn->xprt_ctx);
4864 return 1;
4865 }
4866
4867 /* string, returns the used cipher if front conn. transport layer is SSL.
4868 * This function is also usable on backend conn if the fetch keyword 5th
4869 * char is 'b'.
4870 */
4871 static int
4872 smp_fetch_ssl_fc_cipher(const struct arg *args, struct sample *smp, const char *kw, void *private)
4873 {
4874 struct connection *conn = objt_conn((kw[4] != 'b') ? smp->sess->origin :
4875 smp->strm ? smp->strm->si[1].end : NULL);
4876
4877 smp->flags = 0;
4878 if (!conn || !conn->xprt_ctx || conn->xprt != &ssl_sock)
4879 return 0;
4880
4881 smp->data.u.str.str = (char *)SSL_get_cipher_name(conn->xprt_ctx);
4882 if (!smp->data.u.str.str)
4883 return 0;
4884
4885 smp->data.type = SMP_T_STR;
4886 smp->flags |= SMP_F_CONST;
4887 smp->data.u.str.len = strlen(smp->data.u.str.str);
4888
4889 return 1;
4890 }
4891
4892 /* integer, returns the algoritm's keysize if front conn. transport layer
4893 * is SSL.
4894 * This function is also usable on backend conn if the fetch keyword 5th
4895 * char is 'b'.
4896 */
4897 static int
4898 smp_fetch_ssl_fc_alg_keysize(const struct arg *args, struct sample *smp, const char *kw, void *private)
4899 {
4900 struct connection *conn = objt_conn((kw[4] != 'b') ? smp->sess->origin :
4901 smp->strm ? smp->strm->si[1].end : NULL);
4902
4903 int sint;
4904
4905 smp->flags = 0;
4906 if (!conn || !conn->xprt_ctx || conn->xprt != &ssl_sock)
4907 return 0;
4908
4909 if (!SSL_get_cipher_bits(conn->xprt_ctx, &sint))
4910 return 0;
4911
4912 smp->data.u.sint = sint;
4913 smp->data.type = SMP_T_SINT;
4914
4915 return 1;
4916 }
4917
4918 /* integer, returns the used keysize if front conn. transport layer is SSL.
4919 * This function is also usable on backend conn if the fetch keyword 5th
4920 * char is 'b'.
4921 */
4922 static int
4923 smp_fetch_ssl_fc_use_keysize(const struct arg *args, struct sample *smp, const char *kw, void *private)
4924 {
4925 struct connection *conn = objt_conn((kw[4] != 'b') ? smp->sess->origin :
4926 smp->strm ? smp->strm->si[1].end : NULL);
4927
4928 smp->flags = 0;
4929 if (!conn || !conn->xprt_ctx || conn->xprt != &ssl_sock)
4930 return 0;
4931
4932 smp->data.u.sint = (unsigned int)SSL_get_cipher_bits(conn->xprt_ctx, NULL);
4933 if (!smp->data.u.sint)
4934 return 0;
4935
4936 smp->data.type = SMP_T_SINT;
4937
4938 return 1;
4939 }
4940
4941 #ifdef OPENSSL_NPN_NEGOTIATED
4942 static int
4943 smp_fetch_ssl_fc_npn(const struct arg *args, struct sample *smp, const char *kw, void *private)
4944 {
4945 struct connection *conn;
4946
4947 smp->flags = SMP_F_CONST;
4948 smp->data.type = SMP_T_STR;
4949
4950 conn = objt_conn(smp->sess->origin);
4951 if (!conn || !conn->xprt_ctx || conn->xprt != &ssl_sock)
4952 return 0;
4953
4954 smp->data.u.str.str = NULL;
4955 SSL_get0_next_proto_negotiated(conn->xprt_ctx,
4956 (const unsigned char **)&smp->data.u.str.str, (unsigned *)&smp->data.u.str.len);
4957
4958 if (!smp->data.u.str.str)
4959 return 0;
4960
4961 return 1;
4962 }
4963 #endif
4964
4965 #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
4966 static int
4967 smp_fetch_ssl_fc_alpn(const struct arg *args, struct sample *smp, const char *kw, void *private)
4968 {
4969 struct connection *conn;
4970
4971 smp->flags = SMP_F_CONST;
4972 smp->data.type = SMP_T_STR;
4973
4974 conn = objt_conn(smp->sess->origin);
4975 if (!conn || !conn->xprt_ctx || conn->xprt != &ssl_sock)
4976 return 0;
4977
4978 smp->data.u.str.str = NULL;
4979 SSL_get0_alpn_selected(conn->xprt_ctx,
4980 (const unsigned char **)&smp->data.u.str.str, (unsigned *)&smp->data.u.str.len);
4981
4982 if (!smp->data.u.str.str)
4983 return 0;
4984
4985 return 1;
4986 }
4987 #endif
4988
4989 /* string, returns the used protocol if front conn. transport layer is SSL.
4990 * This function is also usable on backend conn if the fetch keyword 5th
4991 * char is 'b'.
4992 */
4993 static int
4994 smp_fetch_ssl_fc_protocol(const struct arg *args, struct sample *smp, const char *kw, void *private)
4995 {
4996 struct connection *conn = objt_conn((kw[4] != 'b') ? smp->sess->origin :
4997 smp->strm ? smp->strm->si[1].end : NULL);
4998
4999 smp->flags = 0;
5000 if (!conn || !conn->xprt_ctx || conn->xprt != &ssl_sock)
5001 return 0;
5002
5003 smp->data.u.str.str = (char *)SSL_get_version(conn->xprt_ctx);
5004 if (!smp->data.u.str.str)
5005 return 0;
5006
5007 smp->data.type = SMP_T_STR;
5008 smp->flags = SMP_F_CONST;
5009 smp->data.u.str.len = strlen(smp->data.u.str.str);
5010
5011 return 1;
5012 }
5013
5014 /* binary, returns the SSL stream id if front conn. transport layer is SSL.
5015 * This function is also usable on backend conn if the fetch keyword 5th
5016 * char is 'b'.
5017 */
5018 static int
5019 smp_fetch_ssl_fc_session_id(const struct arg *args, struct sample *smp, const char *kw, void *private)
5020 {
5021 #if OPENSSL_VERSION_NUMBER > 0x0090800fL
5022 struct connection *conn = objt_conn((kw[4] != 'b') ? smp->sess->origin :
5023 smp->strm ? smp->strm->si[1].end : NULL);
5024
5025 SSL_SESSION *ssl_sess;
5026
5027 smp->flags = SMP_F_CONST;
5028 smp->data.type = SMP_T_BIN;
5029
5030 if (!conn || !conn->xprt_ctx || conn->xprt != &ssl_sock)
5031 return 0;
5032
5033 ssl_sess = SSL_get_session(conn->xprt_ctx);
5034 if (!ssl_sess)
5035 return 0;
5036
5037 smp->data.u.str.str = (char *)SSL_SESSION_get_id(ssl_sess, (unsigned int *)&smp->data.u.str.len);
5038 if (!smp->data.u.str.str || !smp->data.u.str.len)
5039 return 0;
5040
5041 return 1;
5042 #else
5043 return 0;
5044 #endif
5045 }
5046
5047 static int
5048 smp_fetch_ssl_fc_sni(const struct arg *args, struct sample *smp, const char *kw, void *private)
5049 {
5050 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
5051 struct connection *conn;
5052
5053 smp->flags = SMP_F_CONST;
5054 smp->data.type = SMP_T_STR;
5055
5056 conn = objt_conn(smp->sess->origin);
5057 if (!conn || !conn->xprt_ctx || conn->xprt != &ssl_sock)
5058 return 0;
5059
5060 smp->data.u.str.str = (char *)SSL_get_servername(conn->xprt_ctx, TLSEXT_NAMETYPE_host_name);
5061 if (!smp->data.u.str.str)
5062 return 0;
5063
5064 smp->data.u.str.len = strlen(smp->data.u.str.str);
5065 return 1;
5066 #else
5067 return 0;
5068 #endif
5069 }
5070
5071 static int
5072 smp_fetch_ssl_fc_unique_id(const struct arg *args, struct sample *smp, const char *kw, void *private)
5073 {
5074 #if OPENSSL_VERSION_NUMBER > 0x0090800fL
5075 struct connection *conn = objt_conn((kw[4] != 'b') ? smp->sess->origin :
5076 smp->strm ? smp->strm->si[1].end : NULL);
5077
5078 int finished_len;
5079 struct chunk *finished_trash;
5080
5081 smp->flags = 0;
5082 if (!conn || !conn->xprt_ctx || conn->xprt != &ssl_sock)
5083 return 0;
5084
5085 if (!(conn->flags & CO_FL_CONNECTED)) {
5086 smp->flags |= SMP_F_MAY_CHANGE;
5087 return 0;
5088 }
5089
5090 finished_trash = get_trash_chunk();
5091 if (!SSL_session_reused(conn->xprt_ctx))
5092 finished_len = SSL_get_peer_finished(conn->xprt_ctx, finished_trash->str, finished_trash->size);
5093 else
5094 finished_len = SSL_get_finished(conn->xprt_ctx, finished_trash->str, finished_trash->size);
5095
5096 if (!finished_len)
5097 return 0;
5098
5099 finished_trash->len = finished_len;
5100 smp->data.u.str = *finished_trash;
5101 smp->data.type = SMP_T_BIN;
5102
5103 return 1;
5104 #else
5105 return 0;
5106 #endif
5107 }
5108
5109 /* integer, returns the first verify error in CA chain of client certificate chain. */
5110 static int
5111 smp_fetch_ssl_c_ca_err(const struct arg *args, struct sample *smp, const char *kw, void *private)
5112 {
5113 struct connection *conn;
5114
5115 conn = objt_conn(smp->sess->origin);
5116 if (!conn || conn->xprt != &ssl_sock)
5117 return 0;
5118
5119 if (!(conn->flags & CO_FL_CONNECTED)) {
5120 smp->flags = SMP_F_MAY_CHANGE;
5121 return 0;
5122 }
5123
5124 smp->data.type = SMP_T_SINT;
5125 smp->data.u.sint = (unsigned long long int)SSL_SOCK_ST_TO_CA_ERROR(conn->xprt_st);
5126 smp->flags = 0;
5127
5128 return 1;
5129 }
5130
5131 /* integer, returns the depth of the first verify error in CA chain of client certificate chain. */
5132 static int
5133 smp_fetch_ssl_c_ca_err_depth(const struct arg *args, struct sample *smp, const char *kw, void *private)
5134 {
5135 struct connection *conn;
5136
5137 conn = objt_conn(smp->sess->origin);
5138 if (!conn || conn->xprt != &ssl_sock)
5139 return 0;
5140
5141 if (!(conn->flags & CO_FL_CONNECTED)) {
5142 smp->flags = SMP_F_MAY_CHANGE;
5143 return 0;
5144 }
5145
5146 smp->data.type = SMP_T_SINT;
5147 smp->data.u.sint = (long long int)SSL_SOCK_ST_TO_CAEDEPTH(conn->xprt_st);
5148 smp->flags = 0;
5149
5150 return 1;
5151 }
5152
5153 /* integer, returns the first verify error on client certificate */
5154 static int
5155 smp_fetch_ssl_c_err(const struct arg *args, struct sample *smp, const char *kw, void *private)
5156 {
5157 struct connection *conn;
5158
5159 conn = objt_conn(smp->sess->origin);
5160 if (!conn || conn->xprt != &ssl_sock)
5161 return 0;
5162
5163 if (!(conn->flags & CO_FL_CONNECTED)) {
5164 smp->flags = SMP_F_MAY_CHANGE;
5165 return 0;
5166 }
5167
5168 smp->data.type = SMP_T_SINT;
5169 smp->data.u.sint = (long long int)SSL_SOCK_ST_TO_CRTERROR(conn->xprt_st);
5170 smp->flags = 0;
5171
5172 return 1;
5173 }
5174
5175 /* integer, returns the verify result on client cert */
5176 static int
5177 smp_fetch_ssl_c_verify(const struct arg *args, struct sample *smp, const char *kw, void *private)
5178 {
5179 struct connection *conn;
5180
5181 conn = objt_conn(smp->sess->origin);
5182 if (!conn || conn->xprt != &ssl_sock)
5183 return 0;
5184
5185 if (!(conn->flags & CO_FL_CONNECTED)) {
5186 smp->flags = SMP_F_MAY_CHANGE;
5187 return 0;
5188 }
5189
5190 if (!conn->xprt_ctx)
5191 return 0;
5192
5193 smp->data.type = SMP_T_SINT;
5194 smp->data.u.sint = (long long int)SSL_get_verify_result(conn->xprt_ctx);
5195 smp->flags = 0;
5196
5197 return 1;
5198 }
5199
5200 /* parse the "ca-file" bind keyword */
5201 static int bind_parse_ca_file(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
5202 {
5203 if (!*args[cur_arg + 1]) {
5204 if (err)
5205 memprintf(err, "'%s' : missing CAfile path", args[cur_arg]);
5206 return ERR_ALERT | ERR_FATAL;
5207 }
5208
5209 if ((*args[cur_arg + 1] != '/') && global.ca_base)
5210 memprintf(&conf->ca_file, "%s/%s", global.ca_base, args[cur_arg + 1]);
5211 else
5212 memprintf(&conf->ca_file, "%s", args[cur_arg + 1]);
5213
5214 return 0;
5215 }
5216
5217 /* parse the "ca-sign-file" bind keyword */
5218 static int bind_parse_ca_sign_file(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
5219 {
5220 if (!*args[cur_arg + 1]) {
5221 if (err)
5222 memprintf(err, "'%s' : missing CAfile path", args[cur_arg]);
5223 return ERR_ALERT | ERR_FATAL;
5224 }
5225
5226 if ((*args[cur_arg + 1] != '/') && global.ca_base)
5227 memprintf(&conf->ca_sign_file, "%s/%s", global.ca_base, args[cur_arg + 1]);
5228 else
5229 memprintf(&conf->ca_sign_file, "%s", args[cur_arg + 1]);
5230
5231 return 0;
5232 }
5233
5234 /* parse the "ca-sign-pass" bind keyword */
5235 static int bind_parse_ca_sign_pass(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
5236 {
5237 if (!*args[cur_arg + 1]) {
5238 if (err)
5239 memprintf(err, "'%s' : missing CAkey password", args[cur_arg]);
5240 return ERR_ALERT | ERR_FATAL;
5241 }
5242 memprintf(&conf->ca_sign_pass, "%s", args[cur_arg + 1]);
5243 return 0;
5244 }
5245
5246 /* parse the "ciphers" bind keyword */
5247 static int bind_parse_ciphers(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
5248 {
5249 if (!*args[cur_arg + 1]) {
5250 memprintf(err, "'%s' : missing cipher suite", args[cur_arg]);
5251 return ERR_ALERT | ERR_FATAL;
5252 }
5253
5254 free(conf->ciphers);
5255 conf->ciphers = strdup(args[cur_arg + 1]);
5256 return 0;
5257 }
5258
5259 /* parse the "crt" bind keyword */
5260 static int bind_parse_crt(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
5261 {
5262 char path[MAXPATHLEN];
5263
5264 if (!*args[cur_arg + 1]) {
5265 memprintf(err, "'%s' : missing certificate location", args[cur_arg]);
5266 return ERR_ALERT | ERR_FATAL;
5267 }
5268
5269 if ((*args[cur_arg + 1] != '/' ) && global.crt_base) {
5270 if ((strlen(global.crt_base) + 1 + strlen(args[cur_arg + 1]) + 1) > MAXPATHLEN) {
5271 memprintf(err, "'%s' : path too long", args[cur_arg]);
5272 return ERR_ALERT | ERR_FATAL;
5273 }
5274 snprintf(path, sizeof(path), "%s/%s", global.crt_base, args[cur_arg + 1]);
5275 if (ssl_sock_load_cert(path, conf, px, err) > 0)
5276 return ERR_ALERT | ERR_FATAL;
5277
5278 return 0;
5279 }
5280
5281 if (ssl_sock_load_cert(args[cur_arg + 1], conf, px, err) > 0)
5282 return ERR_ALERT | ERR_FATAL;
5283
5284 return 0;
5285 }
5286
5287 /* parse the "crt-list" bind keyword */
5288 static int bind_parse_crt_list(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
5289 {
5290 if (!*args[cur_arg + 1]) {
5291 memprintf(err, "'%s' : missing certificate location", args[cur_arg]);
5292 return ERR_ALERT | ERR_FATAL;
5293 }
5294
5295 if (ssl_sock_load_cert_list_file(args[cur_arg + 1], conf, px, err) > 0) {
5296 memprintf(err, "'%s' : %s", args[cur_arg], *err);
5297 return ERR_ALERT | ERR_FATAL;
5298 }
5299
5300 return 0;
5301 }
5302
5303 /* parse the "crl-file" bind keyword */
5304 static int bind_parse_crl_file(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
5305 {
5306 #ifndef X509_V_FLAG_CRL_CHECK
5307 if (err)
5308 memprintf(err, "'%s' : library does not support CRL verify", args[cur_arg]);
5309 return ERR_ALERT | ERR_FATAL;
5310 #else
5311 if (!*args[cur_arg + 1]) {
5312 if (err)
5313 memprintf(err, "'%s' : missing CRLfile path", args[cur_arg]);
5314 return ERR_ALERT | ERR_FATAL;
5315 }
5316
5317 if ((*args[cur_arg + 1] != '/') && global.ca_base)
5318 memprintf(&conf->crl_file, "%s/%s", global.ca_base, args[cur_arg + 1]);
5319 else
5320 memprintf(&conf->crl_file, "%s", args[cur_arg + 1]);
5321
5322 return 0;
5323 #endif
5324 }
5325
5326 /* parse the "ecdhe" bind keyword keyword */
5327 static int bind_parse_ecdhe(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
5328 {
5329 #if OPENSSL_VERSION_NUMBER < 0x0090800fL
5330 if (err)
5331 memprintf(err, "'%s' : library does not support elliptic curve Diffie-Hellman (too old)", args[cur_arg]);
5332 return ERR_ALERT | ERR_FATAL;
5333 #elif defined(OPENSSL_NO_ECDH)
5334 if (err)
5335 memprintf(err, "'%s' : library does not support elliptic curve Diffie-Hellman (disabled via OPENSSL_NO_ECDH)", args[cur_arg]);
5336 return ERR_ALERT | ERR_FATAL;
5337 #else
5338 if (!*args[cur_arg + 1]) {
5339 if (err)
5340 memprintf(err, "'%s' : missing named curve", args[cur_arg]);
5341 return ERR_ALERT | ERR_FATAL;
5342 }
5343
5344 conf->ecdhe = strdup(args[cur_arg + 1]);
5345
5346 return 0;
5347 #endif
5348 }
5349
5350 /* parse the "crt-ignore-err" and "ca-ignore-err" bind keywords */
5351 static int bind_parse_ignore_err(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
5352 {
5353 int code;
5354 char *p = args[cur_arg + 1];
5355 unsigned long long *ignerr = &conf->crt_ignerr;
5356
5357 if (!*p) {
5358 if (err)
5359 memprintf(err, "'%s' : missing error IDs list", args[cur_arg]);
5360 return ERR_ALERT | ERR_FATAL;
5361 }
5362
5363 if (strcmp(args[cur_arg], "ca-ignore-err") == 0)
5364 ignerr = &conf->ca_ignerr;
5365
5366 if (strcmp(p, "all") == 0) {
5367 *ignerr = ~0ULL;
5368 return 0;
5369 }
5370
5371 while (p) {
5372 code = atoi(p);
5373 if ((code <= 0) || (code > 63)) {
5374 if (err)
5375 memprintf(err, "'%s' : ID '%d' out of range (1..63) in error IDs list '%s'",
5376 args[cur_arg], code, args[cur_arg + 1]);
5377 return ERR_ALERT | ERR_FATAL;
5378 }
5379 *ignerr |= 1ULL << code;
5380 p = strchr(p, ',');
5381 if (p)
5382 p++;
5383 }
5384
5385 return 0;
5386 }
5387
5388 /* parse the "force-sslv3" bind keyword */
5389 static int bind_parse_force_sslv3(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
5390 {
5391 conf->ssl_options |= BC_SSL_O_USE_SSLV3;
5392 return 0;
5393 }
5394
5395 /* parse the "force-tlsv10" bind keyword */
5396 static int bind_parse_force_tlsv10(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
5397 {
5398 conf->ssl_options |= BC_SSL_O_USE_TLSV10;
5399 return 0;
5400 }
5401
5402 /* parse the "force-tlsv11" bind keyword */
5403 static int bind_parse_force_tlsv11(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
5404 {
5405 #if SSL_OP_NO_TLSv1_1
5406 conf->ssl_options |= BC_SSL_O_USE_TLSV11;
5407 return 0;
5408 #else
5409 if (err)
5410 memprintf(err, "'%s' : library does not support protocol TLSv1.1", args[cur_arg]);
5411 return ERR_ALERT | ERR_FATAL;
5412 #endif
5413 }
5414
5415 /* parse the "force-tlsv12" bind keyword */
5416 static int bind_parse_force_tlsv12(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
5417 {
5418 #if SSL_OP_NO_TLSv1_2
5419 conf->ssl_options |= BC_SSL_O_USE_TLSV12;
5420 return 0;
5421 #else
5422 if (err)
5423 memprintf(err, "'%s' : library does not support protocol TLSv1.2", args[cur_arg]);
5424 return ERR_ALERT | ERR_FATAL;
5425 #endif
5426 }
5427
5428
5429 /* parse the "no-tls-tickets" bind keyword */
5430 static int bind_parse_no_tls_tickets(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
5431 {
5432 conf->ssl_options |= BC_SSL_O_NO_TLS_TICKETS;
5433 return 0;
5434 }
5435
5436
5437 /* parse the "no-sslv3" bind keyword */
5438 static int bind_parse_no_sslv3(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
5439 {
5440 conf->ssl_options |= BC_SSL_O_NO_SSLV3;
5441 return 0;
5442 }
5443
5444 /* parse the "no-tlsv10" bind keyword */
5445 static int bind_parse_no_tlsv10(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
5446 {
5447 conf->ssl_options |= BC_SSL_O_NO_TLSV10;
5448 return 0;
5449 }
5450
5451 /* parse the "no-tlsv11" bind keyword */
5452 static int bind_parse_no_tlsv11(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
5453 {
5454 conf->ssl_options |= BC_SSL_O_NO_TLSV11;
5455 return 0;
5456 }
5457
5458 /* parse the "no-tlsv12" bind keyword */
5459 static int bind_parse_no_tlsv12(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
5460 {
5461 conf->ssl_options |= BC_SSL_O_NO_TLSV12;
5462 return 0;
5463 }
5464
5465 /* parse the "npn" bind keyword */
5466 static int bind_parse_npn(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
5467 {
5468 #ifdef OPENSSL_NPN_NEGOTIATED
5469 char *p1, *p2;
5470
5471 if (!*args[cur_arg + 1]) {
5472 memprintf(err, "'%s' : missing the comma-delimited NPN protocol suite", args[cur_arg]);
5473 return ERR_ALERT | ERR_FATAL;
5474 }
5475
5476 free(conf->npn_str);
5477
5478 /* the NPN string is built as a suite of (<len> <name>)*,
5479 * so we reuse each comma to store the next <len> and need
5480 * one more for the end of the string.
5481 */
5482 conf->npn_len = strlen(args[cur_arg + 1]) + 1;
5483 conf->npn_str = calloc(1, conf->npn_len + 1);
5484 memcpy(conf->npn_str + 1, args[cur_arg + 1], conf->npn_len);
5485
5486 /* replace commas with the name length */
5487 p1 = conf->npn_str;
5488 p2 = p1 + 1;
5489 while (1) {
5490 p2 = memchr(p1 + 1, ',', conf->npn_str + conf->npn_len - (p1 + 1));
5491 if (!p2)
5492 p2 = p1 + 1 + strlen(p1 + 1);
5493
5494 if (p2 - (p1 + 1) > 255) {
5495 *p2 = '\0';
5496 memprintf(err, "'%s' : NPN protocol name too long : '%s'", args[cur_arg], p1 + 1);
5497 return ERR_ALERT | ERR_FATAL;
5498 }
5499
5500 *p1 = p2 - (p1 + 1);
5501 p1 = p2;
5502
5503 if (!*p2)
5504 break;
5505
5506 *(p2++) = '\0';
5507 }
5508 return 0;
5509 #else
5510 if (err)
5511 memprintf(err, "'%s' : library does not support TLS NPN extension", args[cur_arg]);
5512 return ERR_ALERT | ERR_FATAL;
5513 #endif
5514 }
5515
5516 /* parse the "alpn" bind keyword */
5517 static int bind_parse_alpn(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
5518 {
5519 #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
5520 char *p1, *p2;
5521
5522 if (!*args[cur_arg + 1]) {
5523 memprintf(err, "'%s' : missing the comma-delimited ALPN protocol suite", args[cur_arg]);
5524 return ERR_ALERT | ERR_FATAL;
5525 }
5526
5527 free(conf->alpn_str);
5528
5529 /* the ALPN string is built as a suite of (<len> <name>)*,
5530 * so we reuse each comma to store the next <len> and need
5531 * one more for the end of the string.
5532 */
5533 conf->alpn_len = strlen(args[cur_arg + 1]) + 1;
5534 conf->alpn_str = calloc(1, conf->alpn_len + 1);
5535 memcpy(conf->alpn_str + 1, args[cur_arg + 1], conf->alpn_len);
5536
5537 /* replace commas with the name length */
5538 p1 = conf->alpn_str;
5539 p2 = p1 + 1;
5540 while (1) {
5541 p2 = memchr(p1 + 1, ',', conf->alpn_str + conf->alpn_len - (p1 + 1));
5542 if (!p2)
5543 p2 = p1 + 1 + strlen(p1 + 1);
5544
5545 if (p2 - (p1 + 1) > 255) {
5546 *p2 = '\0';
5547 memprintf(err, "'%s' : ALPN protocol name too long : '%s'", args[cur_arg], p1 + 1);
5548 return ERR_ALERT | ERR_FATAL;
5549 }
5550
5551 *p1 = p2 - (p1 + 1);
5552 p1 = p2;
5553
5554 if (!*p2)
5555 break;
5556
5557 *(p2++) = '\0';
5558 }
5559 return 0;
5560 #else
5561 if (err)
5562 memprintf(err, "'%s' : library does not support TLS ALPN extension", args[cur_arg]);
5563 return ERR_ALERT | ERR_FATAL;
5564 #endif
5565 }
5566
5567 /* parse the "ssl" bind keyword */
5568 static int bind_parse_ssl(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
5569 {
5570 struct listener *l;
5571
5572 conf->is_ssl = 1;
5573
5574 if (global.listen_default_ciphers && !conf->ciphers)
5575 conf->ciphers = strdup(global.listen_default_ciphers);
5576 conf->ssl_options |= global.listen_default_ssloptions;
5577
5578 list_for_each_entry(l, &conf->listeners, by_bind)
5579 l->xprt = &ssl_sock;
5580
5581 return 0;
5582 }
5583
5584 /* parse the "generate-certificates" bind keyword */
5585 static int bind_parse_generate_certs(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
5586 {
5587 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
5588 conf->generate_certs = 1;
5589 #else
5590 memprintf(err, "%sthis version of openssl cannot generate SSL certificates.\n",
5591 err && *err ? *err : "");
5592 #endif
5593 return 0;
5594 }
5595
5596 /* parse the "strict-sni" bind keyword */
5597 static int bind_parse_strict_sni(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
5598 {
5599 conf->strict_sni = 1;
5600 return 0;
5601 }
5602
5603 /* parse the "tls-ticket-keys" bind keyword */
5604 static int bind_parse_tls_ticket_keys(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
5605 {
5606 #if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
5607 FILE *f = NULL;
5608 int i = 0;
5609 char thisline[LINESIZE];
5610 struct tls_keys_ref *keys_ref = NULL;
5611
5612 if (!*args[cur_arg + 1]) {
5613 if (err)
5614 memprintf(err, "'%s' : missing TLS ticket keys file path", args[cur_arg]);
5615 goto fail;
5616 }
5617
5618 keys_ref = tlskeys_ref_lookup(args[cur_arg + 1]);
5619 if(keys_ref) {
5620 conf->keys_ref = keys_ref;
5621 return 0;
5622 }
5623
5624 keys_ref = calloc(1, sizeof(*keys_ref));
5625 if (!keys_ref) {
5626 if (err)
5627 memprintf(err, "'%s' : allocation error", args[cur_arg+1]);
5628 goto fail;
5629 }
5630
5631 keys_ref->tlskeys = malloc(TLS_TICKETS_NO * sizeof(struct tls_sess_key));
5632 if (!keys_ref->tlskeys) {
5633 if (err)
5634 memprintf(err, "'%s' : allocation error", args[cur_arg+1]);
5635 goto fail;
5636 }
5637
5638 if ((f = fopen(args[cur_arg + 1], "r")) == NULL) {
5639 if (err)
5640 memprintf(err, "'%s' : unable to load ssl tickets keys file", args[cur_arg+1]);
5641 goto fail;
5642 }
5643
5644 keys_ref->filename = strdup(args[cur_arg + 1]);
5645 if (!keys_ref->filename) {
5646 if (err)
5647 memprintf(err, "'%s' : allocation error", args[cur_arg+1]);
5648 goto fail;
5649 }
5650
5651 while (fgets(thisline, sizeof(thisline), f) != NULL) {
5652 int len = strlen(thisline);
5653 /* Strip newline characters from the end */
5654 if(thisline[len - 1] == '\n')
5655 thisline[--len] = 0;
5656
5657 if(thisline[len - 1] == '\r')
5658 thisline[--len] = 0;
5659
5660 if (base64dec(thisline, len, (char *) (keys_ref->tlskeys + i % TLS_TICKETS_NO), sizeof(struct tls_sess_key)) != sizeof(struct tls_sess_key)) {
5661 if (err)
5662 memprintf(err, "'%s' : unable to decode base64 key on line %d", args[cur_arg+1], i + 1);
5663 goto fail;
5664 }
5665 i++;
5666 }
5667
5668 if (i < TLS_TICKETS_NO) {
5669 if (err)
5670 memprintf(err, "'%s' : please supply at least %d keys in the tls-tickets-file", args[cur_arg+1], TLS_TICKETS_NO);
5671 goto fail;
5672 }
5673
5674 fclose(f);
5675
5676 /* Use penultimate key for encryption, handle when TLS_TICKETS_NO = 1 */
5677 i -= 2;
5678 keys_ref->tls_ticket_enc_index = i < 0 ? 0 : i % TLS_TICKETS_NO;
5679 keys_ref->unique_id = -1;
5680 conf->keys_ref = keys_ref;
5681
5682 LIST_ADD(&tlskeys_reference, &keys_ref->list);
5683
5684 return 0;
5685
5686 fail:
5687 if (f)
5688 fclose(f);
5689 if (keys_ref) {
5690 free(keys_ref->filename);
5691 free(keys_ref->tlskeys);
5692 free(keys_ref);
5693 }
5694 return ERR_ALERT | ERR_FATAL;
5695
5696 #else
5697 if (err)
5698 memprintf(err, "'%s' : TLS ticket callback extension not supported", args[cur_arg]);
5699 return ERR_ALERT | ERR_FATAL;
5700 #endif /* SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB */
5701 }
5702
5703 /* parse the "verify" bind keyword */
5704 static int bind_parse_verify(char **args, int cur_arg, struct proxy *px, struct bind_conf *conf, char **err)
5705 {
5706 if (!*args[cur_arg + 1]) {
5707 if (err)
5708 memprintf(err, "'%s' : missing verify method", args[cur_arg]);
5709 return ERR_ALERT | ERR_FATAL;
5710 }
5711
5712 if (strcmp(args[cur_arg + 1], "none") == 0)
5713 conf->verify = SSL_SOCK_VERIFY_NONE;
5714 else if (strcmp(args[cur_arg + 1], "optional") == 0)
5715 conf->verify = SSL_SOCK_VERIFY_OPTIONAL;
5716 else if (strcmp(args[cur_arg + 1], "required") == 0)
5717 conf->verify = SSL_SOCK_VERIFY_REQUIRED;
5718 else {
5719 if (err)
5720 memprintf(err, "'%s' : unknown verify method '%s', only 'none', 'optional', and 'required' are supported\n",
5721 args[cur_arg], args[cur_arg + 1]);
5722 return ERR_ALERT | ERR_FATAL;
5723 }
5724
5725 return 0;
5726 }
5727
5728 /************** "server" keywords ****************/
5729
5730 /* parse the "ca-file" server keyword */
5731 static int srv_parse_ca_file(char **args, int *cur_arg, struct proxy *px, struct server *newsrv, char **err)
5732 {
5733 if (!*args[*cur_arg + 1]) {
5734 if (err)
5735 memprintf(err, "'%s' : missing CAfile path", args[*cur_arg]);
5736 return ERR_ALERT | ERR_FATAL;
5737 }
5738
5739 if ((*args[*cur_arg + 1] != '/') && global.ca_base)
5740 memprintf(&newsrv->ssl_ctx.ca_file, "%s/%s", global.ca_base, args[*cur_arg + 1]);
5741 else
5742 memprintf(&newsrv->ssl_ctx.ca_file, "%s", args[*cur_arg + 1]);
5743
5744 return 0;
5745 }
5746
5747 /* parse the "check-ssl" server keyword */
5748 static int srv_parse_check_ssl(char **args, int *cur_arg, struct proxy *px, struct server *newsrv, char **err)
5749 {
5750 newsrv->check.use_ssl = 1;
5751 if (global.connect_default_ciphers && !newsrv->ssl_ctx.ciphers)
5752 newsrv->ssl_ctx.ciphers = strdup(global.connect_default_ciphers);
5753 newsrv->ssl_ctx.options |= global.connect_default_ssloptions;
5754 return 0;
5755 }
5756
5757 /* parse the "ciphers" server keyword */
5758 static int srv_parse_ciphers(char **args, int *cur_arg, struct proxy *px, struct server *newsrv, char **err)
5759 {
5760 if (!*args[*cur_arg + 1]) {
5761 memprintf(err, "'%s' : missing cipher suite", args[*cur_arg]);
5762 return ERR_ALERT | ERR_FATAL;
5763 }
5764
5765 free(newsrv->ssl_ctx.ciphers);
5766 newsrv->ssl_ctx.ciphers = strdup(args[*cur_arg + 1]);
5767 return 0;
5768 }
5769
5770 /* parse the "crl-file" server keyword */
5771 static int srv_parse_crl_file(char **args, int *cur_arg, struct proxy *px, struct server *newsrv, char **err)
5772 {
5773 #ifndef X509_V_FLAG_CRL_CHECK
5774 if (err)
5775 memprintf(err, "'%s' : library does not support CRL verify", args[*cur_arg]);
5776 return ERR_ALERT | ERR_FATAL;
5777 #else
5778 if (!*args[*cur_arg + 1]) {
5779 if (err)
5780 memprintf(err, "'%s' : missing CRLfile path", args[*cur_arg]);
5781 return ERR_ALERT | ERR_FATAL;
5782 }
5783
5784 if ((*args[*cur_arg + 1] != '/') && global.ca_base)
5785 memprintf(&newsrv->ssl_ctx.crl_file, "%s/%s", global.ca_base, args[*cur_arg + 1]);
5786 else
5787 memprintf(&newsrv->ssl_ctx.crl_file, "%s", args[*cur_arg + 1]);
5788
5789 return 0;
5790 #endif
5791 }
5792
5793 /* parse the "crt" server keyword */
5794 static int srv_parse_crt(char **args, int *cur_arg, struct proxy *px, struct server *newsrv, char **err)
5795 {
5796 if (!*args[*cur_arg + 1]) {
5797 if (err)
5798 memprintf(err, "'%s' : missing certificate file path", args[*cur_arg]);
5799 return ERR_ALERT | ERR_FATAL;
5800 }
5801
5802 if ((*args[*cur_arg + 1] != '/') && global.crt_base)
5803 memprintf(&newsrv->ssl_ctx.client_crt, "%s/%s", global.crt_base, args[*cur_arg + 1]);
5804 else
5805 memprintf(&newsrv->ssl_ctx.client_crt, "%s", args[*cur_arg + 1]);
5806
5807 return 0;
5808 }
5809
5810 /* parse the "force-sslv3" server keyword */
5811 static int srv_parse_force_sslv3(char **args, int *cur_arg, struct proxy *px, struct server *newsrv, char **err)
5812 {
5813 newsrv->ssl_ctx.options |= SRV_SSL_O_USE_SSLV3;
5814 return 0;
5815 }
5816
5817 /* parse the "force-tlsv10" server keyword */
5818 static int srv_parse_force_tlsv10(char **args, int *cur_arg, struct proxy *px, struct server *newsrv, char **err)
5819 {
5820 newsrv->ssl_ctx.options |= SRV_SSL_O_USE_TLSV10;
5821 return 0;
5822 }
5823
5824 /* parse the "force-tlsv11" server keyword */
5825 static int srv_parse_force_tlsv11(char **args, int *cur_arg, struct proxy *px, struct server *newsrv, char **err)
5826 {
5827 #if SSL_OP_NO_TLSv1_1
5828 newsrv->ssl_ctx.options |= SRV_SSL_O_USE_TLSV11;
5829 return 0;
5830 #else
5831 if (err)
5832 memprintf(err, "'%s' : library does not support protocol TLSv1.1", args[*cur_arg]);
5833 return ERR_ALERT | ERR_FATAL;
5834 #endif
5835 }
5836
5837 /* parse the "force-tlsv12" server keyword */
5838 static int srv_parse_force_tlsv12(char **args, int *cur_arg, struct proxy *px, struct server *newsrv, char **err)
5839 {
5840 #if SSL_OP_NO_TLSv1_2
5841 newsrv->ssl_ctx.options |= SRV_SSL_O_USE_TLSV12;
5842 return 0;
5843 #else
5844 if (err)
5845 memprintf(err, "'%s' : library does not support protocol TLSv1.2", args[*cur_arg]);
5846 return ERR_ALERT | ERR_FATAL;
5847 #endif
5848 }
5849
5850 /* parse the "no-ssl-reuse" server keyword */
5851 static int srv_parse_no_ssl_reuse(char **args, int *cur_arg, struct proxy *px, struct server *newsrv, char **err)
5852 {
5853 newsrv->ssl_ctx.options |= SRV_SSL_O_NO_REUSE;
5854 return 0;
5855 }
5856
5857 /* parse the "no-sslv3" server keyword */
5858 static int srv_parse_no_sslv3(char **args, int *cur_arg, struct proxy *px, struct server *newsrv, char **err)
5859 {
5860 newsrv->ssl_ctx.options |= SRV_SSL_O_NO_SSLV3;
5861 return 0;
5862 }
5863
5864 /* parse the "no-tlsv10" server keyword */
5865 static int srv_parse_no_tlsv10(char **args, int *cur_arg, struct proxy *px, struct server *newsrv, char **err)
5866 {
5867 newsrv->ssl_ctx.options |= SRV_SSL_O_NO_TLSV10;
5868 return 0;
5869 }
5870
5871 /* parse the "no-tlsv11" server keyword */
5872 static int srv_parse_no_tlsv11(char **args, int *cur_arg, struct proxy *px, struct server *newsrv, char **err)
5873 {
5874 newsrv->ssl_ctx.options |= SRV_SSL_O_NO_TLSV11;
5875 return 0;
5876 }
5877
5878 /* parse the "no-tlsv12" server keyword */
5879 static int srv_parse_no_tlsv12(char **args, int *cur_arg, struct proxy *px, struct server *newsrv, char **err)
5880 {
5881 newsrv->ssl_ctx.options |= SRV_SSL_O_NO_TLSV12;
5882 return 0;
5883 }
5884
5885 /* parse the "no-tls-tickets" server keyword */
5886 static int srv_parse_no_tls_tickets(char **args, int *cur_arg, struct proxy *px, struct server *newsrv, char **err)
5887 {
5888 newsrv->ssl_ctx.options |= SRV_SSL_O_NO_TLS_TICKETS;
5889 return 0;
5890 }
5891 /* parse the "send-proxy-v2-ssl" server keyword */
5892 static int srv_parse_send_proxy_ssl(char **args, int *cur_arg, struct proxy *px, struct server *newsrv, char **err)
5893 {
5894 newsrv->pp_opts |= SRV_PP_V2;
5895 newsrv->pp_opts |= SRV_PP_V2_SSL;
5896 return 0;
5897 }
5898
5899 /* parse the "send-proxy-v2-ssl-cn" server keyword */
5900 static int srv_parse_send_proxy_cn(char **args, int *cur_arg, struct proxy *px, struct server *newsrv, char **err)
5901 {
5902 newsrv->pp_opts |= SRV_PP_V2;
5903 newsrv->pp_opts |= SRV_PP_V2_SSL;
5904 newsrv->pp_opts |= SRV_PP_V2_SSL_CN;
5905 return 0;
5906 }
5907
5908 /* parse the "sni" server keyword */
5909 static int srv_parse_sni(char **args, int *cur_arg, struct proxy *px, struct server *newsrv, char **err)
5910 {
5911 #ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
5912 memprintf(err, "'%s' : the current SSL library doesn't support the SNI TLS extension", args[*cur_arg]);
5913 return ERR_ALERT | ERR_FATAL;
5914 #else
5915 int idx;
5916 struct sample_expr *expr;
5917
5918 if (!*args[*cur_arg + 1]) {
5919 memprintf(err, "'%s' : missing sni expression", args[*cur_arg]);
5920 return ERR_ALERT | ERR_FATAL;
5921 }
5922
5923 idx = (*cur_arg) + 1;
5924 px->conf.args.ctx = ARGC_SRV;
5925
5926 expr = sample_parse_expr((char **)args, &idx, px->conf.file, px->conf.line, err, &px->conf.args);
5927 if (!expr) {
5928 memprintf(err, "error detected while parsing sni expression : %s", *err);
5929 return ERR_ALERT | ERR_FATAL;
5930 }
5931
5932 if (!(expr->fetch->val & SMP_VAL_BE_SRV_CON)) {
5933 memprintf(err, "error detected while parsing sni expression : "
5934 " fetch method '%s' extracts information from '%s', none of which is available here.\n",
5935 args[idx-1], sample_src_names(expr->fetch->use));
5936 return ERR_ALERT | ERR_FATAL;
5937 }
5938
5939 px->http_needed |= !!(expr->fetch->use & SMP_USE_HTTP_ANY);
5940 newsrv->ssl_ctx.sni = expr;
5941 return 0;
5942 #endif
5943 }
5944
5945 /* parse the "ssl" server keyword */
5946 static int srv_parse_ssl(char **args, int *cur_arg, struct proxy *px, struct server *newsrv, char **err)
5947 {
5948 newsrv->use_ssl = 1;
5949 if (global.connect_default_ciphers && !newsrv->ssl_ctx.ciphers)
5950 newsrv->ssl_ctx.ciphers = strdup(global.connect_default_ciphers);
5951 return 0;
5952 }
5953
5954 /* parse the "verify" server keyword */
5955 static int srv_parse_verify(char **args, int *cur_arg, struct proxy *px, struct server *newsrv, char **err)
5956 {
5957 if (!*args[*cur_arg + 1]) {
5958 if (err)
5959 memprintf(err, "'%s' : missing verify method", args[*cur_arg]);
5960 return ERR_ALERT | ERR_FATAL;
5961 }
5962
5963 if (strcmp(args[*cur_arg + 1], "none") == 0)
5964 newsrv->ssl_ctx.verify = SSL_SOCK_VERIFY_NONE;
5965 else if (strcmp(args[*cur_arg + 1], "required") == 0)
5966 newsrv->ssl_ctx.verify = SSL_SOCK_VERIFY_REQUIRED;
5967 else {
5968 if (err)
5969 memprintf(err, "'%s' : unknown verify method '%s', only 'none' and 'required' are supported\n",
5970 args[*cur_arg], args[*cur_arg + 1]);
5971 return ERR_ALERT | ERR_FATAL;
5972 }
5973
5974 return 0;
5975 }
5976
5977 /* parse the "verifyhost" server keyword */
5978 static int srv_parse_verifyhost(char **args, int *cur_arg, struct proxy *px, struct server *newsrv, char **err)
5979 {
5980 if (!*args[*cur_arg + 1]) {
5981 if (err)
5982 memprintf(err, "'%s' : missing hostname to verify against", args[*cur_arg]);
5983 return ERR_ALERT | ERR_FATAL;
5984 }
5985
5986 newsrv->ssl_ctx.verify_host = strdup(args[*cur_arg + 1]);
5987
5988 return 0;
5989 }
5990
5991 /* parse the "ssl-default-bind-options" keyword in global section */
5992 static int ssl_parse_default_bind_options(char **args, int section_type, struct proxy *curpx,
5993 struct proxy *defpx, const char *file, int line,
5994 char **err) {
5995 int i = 1;
5996
5997 if (*(args[i]) == 0) {
5998 memprintf(err, "global statement '%s' expects an option as an argument.", args[0]);
5999 return -1;
6000 }
6001 while (*(args[i])) {
6002 if (!strcmp(args[i], "no-sslv3"))
6003 global.listen_default_ssloptions |= BC_SSL_O_NO_SSLV3;
6004 else if (!strcmp(args[i], "no-tlsv10"))
6005 global.listen_default_ssloptions |= BC_SSL_O_NO_TLSV10;
6006 else if (!strcmp(args[i], "no-tlsv11"))
6007 global.listen_default_ssloptions |= BC_SSL_O_NO_TLSV11;
6008 else if (!strcmp(args[i], "no-tlsv12"))
6009 global.listen_default_ssloptions |= BC_SSL_O_NO_TLSV12;
6010 else if (!strcmp(args[i], "force-sslv3"))
6011 global.listen_default_ssloptions |= BC_SSL_O_USE_SSLV3;
6012 else if (!strcmp(args[i], "force-tlsv10"))
6013 global.listen_default_ssloptions |= BC_SSL_O_USE_TLSV10;
6014 else if (!strcmp(args[i], "force-tlsv11")) {
6015 #if SSL_OP_NO_TLSv1_1
6016 global.listen_default_ssloptions |= BC_SSL_O_USE_TLSV11;
6017 #else
6018 memprintf(err, "'%s' '%s': library does not support protocol TLSv1.1", args[0], args[i]);
6019 return -1;
6020 #endif
6021 }
6022 else if (!strcmp(args[i], "force-tlsv12")) {
6023 #if SSL_OP_NO_TLSv1_2
6024 global.listen_default_ssloptions |= BC_SSL_O_USE_TLSV12;
6025 #else
6026 memprintf(err, "'%s' '%s': library does not support protocol TLSv1.2", args[0], args[i]);
6027 return -1;
6028 #endif
6029 }
6030 else if (!strcmp(args[i], "no-tls-tickets"))
6031 global.listen_default_ssloptions |= BC_SSL_O_NO_TLS_TICKETS;
6032 else {
6033 memprintf(err, "unknown option '%s' on global statement '%s'.", args[i], args[0]);
6034 return -1;
6035 }
6036 i++;
6037 }
6038 return 0;
6039 }
6040
6041 /* parse the "ssl-default-server-options" keyword in global section */
6042 static int ssl_parse_default_server_options(char **args, int section_type, struct proxy *curpx,
6043 struct proxy *defpx, const char *file, int line,
6044 char **err) {
6045 int i = 1;
6046
6047 if (*(args[i]) == 0) {
6048 memprintf(err, "global statement '%s' expects an option as an argument.", args[0]);
6049 return -1;
6050 }
6051 while (*(args[i])) {
6052 if (!strcmp(args[i], "no-sslv3"))
6053 global.connect_default_ssloptions |= SRV_SSL_O_NO_SSLV3;
6054 else if (!strcmp(args[i], "no-tlsv10"))
6055 global.connect_default_ssloptions |= SRV_SSL_O_NO_TLSV10;
6056 else if (!strcmp(args[i], "no-tlsv11"))
6057 global.connect_default_ssloptions |= SRV_SSL_O_NO_TLSV11;
6058 else if (!strcmp(args[i], "no-tlsv12"))
6059 global.connect_default_ssloptions |= SRV_SSL_O_NO_TLSV12;
6060 else if (!strcmp(args[i], "force-sslv3"))
6061 global.connect_default_ssloptions |= SRV_SSL_O_USE_SSLV3;
6062 else if (!strcmp(args[i], "force-tlsv10"))
6063 global.connect_default_ssloptions |= SRV_SSL_O_USE_TLSV10;
6064 else if (!strcmp(args[i], "force-tlsv11")) {
6065 #if SSL_OP_NO_TLSv1_1
6066 global.connect_default_ssloptions |= SRV_SSL_O_USE_TLSV11;
6067 #else
6068 memprintf(err, "'%s' '%s': library does not support protocol TLSv1.1", args[0], args[i]);
6069 return -1;
6070 #endif
6071 }
6072 else if (!strcmp(args[i], "force-tlsv12")) {
6073 #if SSL_OP_NO_TLSv1_2
6074 global.connect_default_ssloptions |= SRV_SSL_O_USE_TLSV12;
6075 #else
6076 memprintf(err, "'%s' '%s': library does not support protocol TLSv1.2", args[0], args[i]);
6077 return -1;
6078 #endif
6079 }
6080 else if (!strcmp(args[i], "no-tls-tickets"))
6081 global.connect_default_ssloptions |= SRV_SSL_O_NO_TLS_TICKETS;
6082 else {
6083 memprintf(err, "unknown option '%s' on global statement '%s'.", args[i], args[0]);
6084 return -1;
6085 }
6086 i++;
6087 }
6088 return 0;
6089 }
6090
6091 /* This function is used with TLS ticket keys management. It permits to browse
6092 * each reference. The variable <getnext> must contain the current node,
6093 * <end> point to the root node.
6094 */
6095 #if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
6096 static inline
6097 struct tls_keys_ref *tlskeys_list_get_next(struct tls_keys_ref *getnext, struct list *end)
6098 {
6099 struct tls_keys_ref *ref = getnext;
6100
6101 while (1) {
6102
6103 /* Get next list entry. */
6104 ref = LIST_NEXT(&ref->list, struct tls_keys_ref *, list);
6105
6106 /* If the entry is the last of the list, return NULL. */
6107 if (&ref->list == end)
6108 return NULL;
6109
6110 return ref;
6111 }
6112 }
6113
6114 static inline
6115 struct tls_keys_ref *tlskeys_ref_lookup_ref(const char *reference)
6116 {
6117 int id;
6118 char *error;
6119
6120 /* If the reference starts by a '#', this is numeric id. */
6121 if (reference[0] == '#') {
6122 /* Try to convert the numeric id. If the conversion fails, the lookup fails. */
6123 id = strtol(reference + 1, &error, 10);
6124 if (*error != '\0')
6125 return NULL;
6126
6127 /* Perform the unique id lookup. */
6128 return tlskeys_ref_lookupid(id);
6129 }
6130
6131 /* Perform the string lookup. */
6132 return tlskeys_ref_lookup(reference);
6133 }
6134 #endif
6135
6136
6137 #if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
6138
6139 static int cli_io_handler_tlskeys_files(struct appctx *appctx);
6140
6141 static inline int cli_io_handler_tlskeys_entries(struct appctx *appctx) {
6142 return cli_io_handler_tlskeys_files(appctx);
6143 }
6144
6145 static int cli_io_handler_tlskeys_files(struct appctx *appctx) {
6146
6147 struct stream_interface *si = appctx->owner;
6148
6149 switch (appctx->st2) {
6150 case STAT_ST_INIT:
6151 /* Display the column headers. If the message cannot be sent,
6152 * quit the fucntion with returning 0. The function is called
6153 * later and restart at the state "STAT_ST_INIT".
6154 */
6155 chunk_reset(&trash);
6156
6157 if (appctx->io_handler == cli_io_handler_tlskeys_entries)
6158 chunk_appendf(&trash, "# id secret\n");
6159 else
6160 chunk_appendf(&trash, "# id (file)\n");
6161
6162 if (bi_putchk(si_ic(si), &trash) == -1) {
6163 si_applet_cant_put(si);
6164 return 0;
6165 }
6166
6167 appctx->ctx.tlskeys.dump_keys_index = 0;
6168
6169 /* Now, we start the browsing of the references lists.
6170 * Note that the following call to LIST_ELEM return bad pointer. The only
6171 * available field of this pointer is <list>. It is used with the function
6172 * tlskeys_list_get_next() for retruning the first available entry
6173 */
6174 if (appctx->ctx.tlskeys.ref == NULL) {
6175 appctx->ctx.tlskeys.ref = LIST_ELEM(&tlskeys_reference, struct tls_keys_ref *, list);
6176 appctx->ctx.tlskeys.ref = tlskeys_list_get_next(appctx->ctx.tlskeys.ref, &tlskeys_reference);
6177 }
6178
6179 appctx->st2 = STAT_ST_LIST;
6180 /* fall through */
6181
6182 case STAT_ST_LIST:
6183 while (appctx->ctx.tlskeys.ref) {
6184 int head = appctx->ctx.tlskeys.ref->tls_ticket_enc_index;
6185
6186 chunk_reset(&trash);
6187 if (appctx->io_handler == cli_io_handler_tlskeys_entries && appctx->ctx.tlskeys.dump_keys_index == 0)
6188 chunk_appendf(&trash, "# ");
6189 if (appctx->ctx.tlskeys.dump_keys_index == 0)
6190 chunk_appendf(&trash, "%d (%s)\n", appctx->ctx.tlskeys.ref->unique_id,
6191 appctx->ctx.tlskeys.ref->filename);
6192 if (appctx->io_handler == cli_io_handler_tlskeys_entries) {
6193 while (appctx->ctx.tlskeys.dump_keys_index < TLS_TICKETS_NO) {
6194 struct chunk *t2 = get_trash_chunk();
6195
6196 chunk_reset(t2);
6197 /* should never fail here because we dump only a key in the t2 buffer */
6198 t2->len = a2base64((char *)(appctx->ctx.tlskeys.ref->tlskeys + (head + 2 + appctx->ctx.tlskeys.dump_keys_index) % TLS_TICKETS_NO),
6199 sizeof(struct tls_sess_key), t2->str, t2->size);
6200 chunk_appendf(&trash, "%d.%d %s\n", appctx->ctx.tlskeys.ref->unique_id, appctx->ctx.tlskeys.dump_keys_index, t2->str);
6201
6202 if (bi_putchk(si_ic(si), &trash) == -1) {
6203 /* let's try again later from this stream. We add ourselves into
6204 * this stream's users so that it can remove us upon termination.
6205 */
6206 si_applet_cant_put(si);
6207 return 0;
6208 }
6209 appctx->ctx.tlskeys.dump_keys_index++;
6210 }
6211 appctx->ctx.tlskeys.dump_keys_index = 0;
6212 }
6213 if (bi_putchk(si_ic(si), &trash) == -1) {
6214 /* let's try again later from this stream. We add ourselves into
6215 * this stream's users so that it can remove us upon termination.
6216 */
6217 si_applet_cant_put(si);
6218 return 0;
6219 }
6220
6221 if (appctx->ctx.tlskeys.dump_all == 0) /* don't display everything if not necessary */
6222 break;
6223
6224 /* get next list entry and check the end of the list */
6225 appctx->ctx.tlskeys.ref = tlskeys_list_get_next(appctx->ctx.tlskeys.ref, &tlskeys_reference);
6226
6227 }
6228
6229 appctx->st2 = STAT_ST_FIN;
6230 /* fall through */
6231
6232 default:
6233 appctx->st2 = STAT_ST_FIN;
6234 return 1;
6235 }
6236 return 0;
6237 }
6238
6239 #endif
6240
6241 static int cli_parse_show_tlskeys(char **args, struct appctx *appctx, void *private)
6242 {
6243 appctx->ctx.tlskeys.dump_all = 0;
6244 /* no parameter, shows only file list */
6245 if (!*args[2]) {
6246 appctx->ctx.tlskeys.dump_all = 1;
6247 appctx->io_handler = cli_io_handler_tlskeys_files;
6248 return 0;
6249 }
6250
6251 if (args[2][0] == '*') {
6252 /* list every TLS ticket keys */
6253 appctx->ctx.tlskeys.ref = NULL;
6254 appctx->ctx.tlskeys.dump_all = 1;
6255 } else {
6256 appctx->ctx.tlskeys.ref = tlskeys_ref_lookup_ref(args[2]);
6257 if (!appctx->ctx.tlskeys.ref) {
6258 appctx->ctx.cli.msg = "'show tls-keys' unable to locate referenced filename\n";
6259 appctx->st0 = CLI_ST_PRINT;
6260 return 1;
6261 }
6262 }
6263 appctx->io_handler = cli_io_handler_tlskeys_entries;
6264 return 0;
6265 }
6266
6267
6268 static int cli_parse_set_tlskeys(char **args, struct appctx *appctx, void *private)
6269 {
6270 /* Expect two parameters: the filename and the new new TLS key in encoding */
6271 if (!*args[3] || !*args[4]) {
6272 appctx->ctx.cli.msg = "'set ssl tls-key' expects a filename and the new TLS key in base64 encoding.\n";
6273 appctx->st0 = CLI_ST_PRINT;
6274 return 1;
6275 }
6276
6277 appctx->ctx.tlskeys.ref = tlskeys_ref_lookup_ref(args[3]);
6278 if(!appctx->ctx.tlskeys.ref) {
6279 appctx->ctx.cli.msg = "'set ssl tls-key' unable to locate referenced filename\n";
6280 appctx->st0 = CLI_ST_PRINT;
6281 return 1;
6282 }
6283
6284 trash.len = base64dec(args[4], strlen(args[4]), trash.str, trash.size);
6285 if (trash.len != sizeof(struct tls_sess_key)) {
6286 appctx->ctx.cli.msg = "'set ssl tls-key' received invalid base64 encoded TLS key.\n";
6287 appctx->st0 = CLI_ST_PRINT;
6288 return 1;
6289 }
6290
6291 memcpy(appctx->ctx.tlskeys.ref->tlskeys + ((appctx->ctx.tlskeys.ref->tls_ticket_enc_index + 2) % TLS_TICKETS_NO), trash.str, trash.len);
6292 appctx->ctx.tlskeys.ref->tls_ticket_enc_index = (appctx->ctx.tlskeys.ref->tls_ticket_enc_index + 1) % TLS_TICKETS_NO;
6293
6294 appctx->ctx.cli.msg = "TLS ticket key updated!";
6295 appctx->st0 = CLI_ST_PRINT;
6296 return 1;
6297
6298 }
6299
6300 static int cli_parse_set_ocspresponse(char **args, struct appctx *appctx, void *private)
6301 {
6302 #if (defined SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB && !defined OPENSSL_NO_OCSP)
6303 char *err = NULL;
6304
6305 /* Expect one parameter: the new response in base64 encoding */
6306 if (!*args[3]) {
6307 appctx->ctx.cli.msg = "'set ssl ocsp-response' expects response in base64 encoding.\n";
6308 appctx->st0 = CLI_ST_PRINT;
6309 return 1;
6310 }
6311
6312 trash.len = base64dec(args[3], strlen(args[3]), trash.str, trash.size);
6313 if (trash.len < 0) {
6314 appctx->ctx.cli.msg = "'set ssl ocsp-response' received invalid base64 encoded response.\n";
6315 appctx->st0 = CLI_ST_PRINT;
6316 return 1;
6317 }
6318
6319 if (ssl_sock_update_ocsp_response(&trash, &err)) {
6320 if (err) {
6321 memprintf(&err, "%s.\n", err);
6322 appctx->ctx.cli.err = err;
6323 appctx->st0 = CLI_ST_PRINT_FREE;
6324 }
6325 return 1;
6326 }
6327 appctx->ctx.cli.msg = "OCSP Response updated!";
6328 appctx->st0 = CLI_ST_PRINT;
6329 return 1;
6330 #else
6331 appctx->ctx.cli.msg = "HAProxy was compiled against a version of OpenSSL that doesn't support OCSP stapling.\n";
6332 appctx->st0 = CLI_ST_PRINT;
6333 return 1;
6334 #endif
6335
6336 }
6337
6338 /* register cli keywords */
6339 static struct cli_kw_list cli_kws = {{ },{
6340 #if (defined SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB && TLS_TICKETS_NO > 0)
6341 { { "show", "tls-keys", NULL }, "show tls-keys [id|*]: show tls keys references or dump tls ticket keys when id specified", cli_parse_show_tlskeys, NULL },
6342 { { "set", "ssl", "tls-key", NULL }, "set ssl tls-key [id|keyfile] <tlskey>: set the next TLS key for the <id> or <keyfile> listener to <tlskey>", cli_parse_set_tlskeys, NULL },
6343 { { "set", "ssl", "tls-keys", NULL }, NULL, cli_parse_set_tlskeys, NULL },
6344 { { "set", "ssl", "ocsp-response", NULL }, NULL, cli_parse_set_ocspresponse, NULL },
6345 #endif
6346 { { NULL }, NULL, NULL, NULL }
6347 }};
6348
6349
6350
6351 /* Note: must not be declared <const> as its list will be overwritten.
6352 * Please take care of keeping this list alphabetically sorted.
6353 */
6354 static struct sample_fetch_kw_list sample_fetch_keywords = {ILH, {
6355 { "ssl_bc", smp_fetch_ssl_fc, 0, NULL, SMP_T_BOOL, SMP_USE_L5SRV },
6356 { "ssl_bc_alg_keysize", smp_fetch_ssl_fc_alg_keysize, 0, NULL, SMP_T_SINT, SMP_USE_L5SRV },
6357 { "ssl_bc_cipher", smp_fetch_ssl_fc_cipher, 0, NULL, SMP_T_STR, SMP_USE_L5SRV },
6358 { "ssl_bc_protocol", smp_fetch_ssl_fc_protocol, 0, NULL, SMP_T_STR, SMP_USE_L5SRV },
6359 { "ssl_bc_unique_id", smp_fetch_ssl_fc_unique_id, 0, NULL, SMP_T_BIN, SMP_USE_L5SRV },
6360 { "ssl_bc_use_keysize", smp_fetch_ssl_fc_use_keysize, 0, NULL, SMP_T_SINT, SMP_USE_L5SRV },
6361 { "ssl_bc_session_id", smp_fetch_ssl_fc_session_id, 0, NULL, SMP_T_BIN, SMP_USE_L5SRV },
6362 { "ssl_c_ca_err", smp_fetch_ssl_c_ca_err, 0, NULL, SMP_T_SINT, SMP_USE_L5CLI },
6363 { "ssl_c_ca_err_depth", smp_fetch_ssl_c_ca_err_depth, 0, NULL, SMP_T_SINT, SMP_USE_L5CLI },
6364 { "ssl_c_der", smp_fetch_ssl_x_der, 0, NULL, SMP_T_BIN, SMP_USE_L5CLI },
6365 { "ssl_c_err", smp_fetch_ssl_c_err, 0, NULL, SMP_T_SINT, SMP_USE_L5CLI },
6366 { "ssl_c_i_dn", smp_fetch_ssl_x_i_dn, ARG2(0,STR,SINT), NULL, SMP_T_STR, SMP_USE_L5CLI },
6367 { "ssl_c_key_alg", smp_fetch_ssl_x_key_alg, 0, NULL, SMP_T_STR, SMP_USE_L5CLI },
6368 { "ssl_c_notafter", smp_fetch_ssl_x_notafter, 0, NULL, SMP_T_STR, SMP_USE_L5CLI },
6369 { "ssl_c_notbefore", smp_fetch_ssl_x_notbefore, 0, NULL, SMP_T_STR, SMP_USE_L5CLI },
6370 { "ssl_c_sig_alg", smp_fetch_ssl_x_sig_alg, 0, NULL, SMP_T_STR, SMP_USE_L5CLI },
6371 { "ssl_c_s_dn", smp_fetch_ssl_x_s_dn, ARG2(0,STR,SINT), NULL, SMP_T_STR, SMP_USE_L5CLI },
6372 { "ssl_c_serial", smp_fetch_ssl_x_serial, 0, NULL, SMP_T_BIN, SMP_USE_L5CLI },
6373 { "ssl_c_sha1", smp_fetch_ssl_x_sha1, 0, NULL, SMP_T_BIN, SMP_USE_L5CLI },
6374 { "ssl_c_used", smp_fetch_ssl_c_used, 0, NULL, SMP_T_BOOL, SMP_USE_L5CLI },
6375 { "ssl_c_verify", smp_fetch_ssl_c_verify, 0, NULL, SMP_T_SINT, SMP_USE_L5CLI },
6376 { "ssl_c_version", smp_fetch_ssl_x_version, 0, NULL, SMP_T_SINT, SMP_USE_L5CLI },
6377 { "ssl_f_der", smp_fetch_ssl_x_der, 0, NULL, SMP_T_BIN, SMP_USE_L5CLI },
6378 { "ssl_f_i_dn", smp_fetch_ssl_x_i_dn, ARG2(0,STR,SINT), NULL, SMP_T_STR, SMP_USE_L5CLI },
6379 { "ssl_f_key_alg", smp_fetch_ssl_x_key_alg, 0, NULL, SMP_T_STR, SMP_USE_L5CLI },
6380 { "ssl_f_notafter", smp_fetch_ssl_x_notafter, 0, NULL, SMP_T_STR, SMP_USE_L5CLI },
6381 { "ssl_f_notbefore", smp_fetch_ssl_x_notbefore, 0, NULL, SMP_T_STR, SMP_USE_L5CLI },
6382 { "ssl_f_sig_alg", smp_fetch_ssl_x_sig_alg, 0, NULL, SMP_T_STR, SMP_USE_L5CLI },
6383 { "ssl_f_s_dn", smp_fetch_ssl_x_s_dn, ARG2(0,STR,SINT), NULL, SMP_T_STR, SMP_USE_L5CLI },
6384 { "ssl_f_serial", smp_fetch_ssl_x_serial, 0, NULL, SMP_T_BIN, SMP_USE_L5CLI },
6385 { "ssl_f_sha1", smp_fetch_ssl_x_sha1, 0, NULL, SMP_T_BIN, SMP_USE_L5CLI },
6386 { "ssl_f_version", smp_fetch_ssl_x_version, 0, NULL, SMP_T_SINT, SMP_USE_L5CLI },
6387 { "ssl_fc", smp_fetch_ssl_fc, 0, NULL, SMP_T_BOOL, SMP_USE_L5CLI },
6388 { "ssl_fc_alg_keysize", smp_fetch_ssl_fc_alg_keysize, 0, NULL, SMP_T_SINT, SMP_USE_L5CLI },
6389 { "ssl_fc_cipher", smp_fetch_ssl_fc_cipher, 0, NULL, SMP_T_STR, SMP_USE_L5CLI },
6390 { "ssl_fc_has_crt", smp_fetch_ssl_fc_has_crt, 0, NULL, SMP_T_BOOL, SMP_USE_L5CLI },
6391 { "ssl_fc_has_sni", smp_fetch_ssl_fc_has_sni, 0, NULL, SMP_T_BOOL, SMP_USE_L5CLI },
6392 { "ssl_fc_is_resumed", smp_fetch_ssl_fc_is_resumed, 0, NULL, SMP_T_BOOL, SMP_USE_L5CLI },
6393 #ifdef OPENSSL_NPN_NEGOTIATED
6394 { "ssl_fc_npn", smp_fetch_ssl_fc_npn, 0, NULL, SMP_T_STR, SMP_USE_L5CLI },
6395 #endif
6396 #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
6397 { "ssl_fc_alpn", smp_fetch_ssl_fc_alpn, 0, NULL, SMP_T_STR, SMP_USE_L5CLI },
6398 #endif
6399 { "ssl_fc_protocol", smp_fetch_ssl_fc_protocol, 0, NULL, SMP_T_STR, SMP_USE_L5CLI },
6400 { "ssl_fc_unique_id", smp_fetch_ssl_fc_unique_id, 0, NULL, SMP_T_BIN, SMP_USE_L5CLI },
6401 { "ssl_fc_use_keysize", smp_fetch_ssl_fc_use_keysize, 0, NULL, SMP_T_SINT, SMP_USE_L5CLI },
6402 { "ssl_fc_session_id", smp_fetch_ssl_fc_session_id, 0, NULL, SMP_T_BIN, SMP_USE_L5CLI },
6403 { "ssl_fc_sni", smp_fetch_ssl_fc_sni, 0, NULL, SMP_T_STR, SMP_USE_L5CLI },
6404 { NULL, NULL, 0, 0, 0 },
6405 }};
6406
6407 /* Note: must not be declared <const> as its list will be overwritten.
6408 * Please take care of keeping this list alphabetically sorted.
6409 */
6410 static struct acl_kw_list acl_kws = {ILH, {
6411 { "ssl_fc_sni_end", "ssl_fc_sni", PAT_MATCH_END },
6412 { "ssl_fc_sni_reg", "ssl_fc_sni", PAT_MATCH_REG },
6413 { /* END */ },
6414 }};
6415
6416 /* Note: must not be declared <const> as its list will be overwritten.
6417 * Please take care of keeping this list alphabetically sorted, doing so helps
6418 * all code contributors.
6419 * Optional keywords are also declared with a NULL ->parse() function so that
6420 * the config parser can report an appropriate error when a known keyword was
6421 * not enabled.
6422 */
6423 static struct bind_kw_list bind_kws = { "SSL", { }, {
6424 { "alpn", bind_parse_alpn, 1 }, /* set ALPN supported protocols */
6425 { "ca-file", bind_parse_ca_file, 1 }, /* set CAfile to process verify on client cert */
6426 { "ca-ignore-err", bind_parse_ignore_err, 1 }, /* set error IDs to ignore on verify depth > 0 */
6427 { "ca-sign-file", bind_parse_ca_sign_file, 1 }, /* set CAFile used to generate and sign server certs */
6428 { "ca-sign-pass", bind_parse_ca_sign_pass, 1 }, /* set CAKey passphrase */
6429 { "ciphers", bind_parse_ciphers, 1 }, /* set SSL cipher suite */
6430 { "crl-file", bind_parse_crl_file, 1 }, /* set certificat revocation list file use on client cert verify */
6431 { "crt", bind_parse_crt, 1 }, /* load SSL certificates from this location */
6432 { "crt-ignore-err", bind_parse_ignore_err, 1 }, /* set error IDs to ingore on verify depth == 0 */
6433 { "crt-list", bind_parse_crt_list, 1 }, /* load a list of crt from this location */
6434 { "ecdhe", bind_parse_ecdhe, 1 }, /* defines named curve for elliptic curve Diffie-Hellman */
6435 { "force-sslv3", bind_parse_force_sslv3, 0 }, /* force SSLv3 */
6436 { "force-tlsv10", bind_parse_force_tlsv10, 0 }, /* force TLSv10 */
6437 { "force-tlsv11", bind_parse_force_tlsv11, 0 }, /* force TLSv11 */
6438 { "force-tlsv12", bind_parse_force_tlsv12, 0 }, /* force TLSv12 */
6439 { "generate-certificates", bind_parse_generate_certs, 0 }, /* enable the server certificates generation */
6440 { "no-sslv3", bind_parse_no_sslv3, 0 }, /* disable SSLv3 */
6441 { "no-tlsv10", bind_parse_no_tlsv10, 0 }, /* disable TLSv10 */
6442 { "no-tlsv11", bind_parse_no_tlsv11, 0 }, /* disable TLSv11 */
6443 { "no-tlsv12", bind_parse_no_tlsv12, 0 }, /* disable TLSv12 */
6444 { "no-tls-tickets", bind_parse_no_tls_tickets, 0 }, /* disable session resumption tickets */
6445 { "ssl", bind_parse_ssl, 0 }, /* enable SSL processing */
6446 { "strict-sni", bind_parse_strict_sni, 0 }, /* refuse negotiation if sni doesn't match a certificate */
6447 { "tls-ticket-keys", bind_parse_tls_ticket_keys, 1 }, /* set file to load TLS ticket keys from */
6448 { "verify", bind_parse_verify, 1 }, /* set SSL verify method */
6449 { "npn", bind_parse_npn, 1 }, /* set NPN supported protocols */
6450 { NULL, NULL, 0 },
6451 }};
6452
6453 /* Note: must not be declared <const> as its list will be overwritten.
6454 * Please take care of keeping this list alphabetically sorted, doing so helps
6455 * all code contributors.
6456 * Optional keywords are also declared with a NULL ->parse() function so that
6457 * the config parser can report an appropriate error when a known keyword was
6458 * not enabled.
6459 */
6460 static struct srv_kw_list srv_kws = { "SSL", { }, {
6461 { "ca-file", srv_parse_ca_file, 1, 0 }, /* set CAfile to process verify server cert */
6462 { "check-ssl", srv_parse_check_ssl, 0, 0 }, /* enable SSL for health checks */
6463 { "ciphers", srv_parse_ciphers, 1, 0 }, /* select the cipher suite */
6464 { "crl-file", srv_parse_crl_file, 1, 0 }, /* set certificate revocation list file use on server cert verify */
6465 { "crt", srv_parse_crt, 1, 0 }, /* set client certificate */
6466 { "force-sslv3", srv_parse_force_sslv3, 0, 0 }, /* force SSLv3 */
6467 { "force-tlsv10", srv_parse_force_tlsv10, 0, 0 }, /* force TLSv10 */
6468 { "force-tlsv11", srv_parse_force_tlsv11, 0, 0 }, /* force TLSv11 */
6469 { "force-tlsv12", srv_parse_force_tlsv12, 0, 0 }, /* force TLSv12 */
6470 { "no-ssl-reuse", srv_parse_no_ssl_reuse, 0, 0 }, /* disable session reuse */
6471 { "no-sslv3", srv_parse_no_sslv3, 0, 0 }, /* disable SSLv3 */
6472 { "no-tlsv10", srv_parse_no_tlsv10, 0, 0 }, /* disable TLSv10 */
6473 { "no-tlsv11", srv_parse_no_tlsv11, 0, 0 }, /* disable TLSv11 */
6474 { "no-tlsv12", srv_parse_no_tlsv12, 0, 0 }, /* disable TLSv12 */
6475 { "no-tls-tickets", srv_parse_no_tls_tickets, 0, 0 }, /* disable session resumption tickets */
6476 { "send-proxy-v2-ssl", srv_parse_send_proxy_ssl, 0, 0 }, /* send PROXY protocol header v2 with SSL info */
6477 { "send-proxy-v2-ssl-cn", srv_parse_send_proxy_cn, 0, 0 }, /* send PROXY protocol header v2 with CN */
6478 { "sni", srv_parse_sni, 1, 0 }, /* send SNI extension */
6479 { "ssl", srv_parse_ssl, 0, 0 }, /* enable SSL processing */
6480 { "verify", srv_parse_verify, 1, 0 }, /* set SSL verify method */
6481 { "verifyhost", srv_parse_verifyhost, 1, 0 }, /* require that SSL cert verifies for hostname */
6482 { NULL, NULL, 0, 0 },
6483 }};
6484
6485 static struct cfg_kw_list cfg_kws = {ILH, {
6486 { CFG_GLOBAL, "ssl-default-bind-options", ssl_parse_default_bind_options },
6487 { CFG_GLOBAL, "ssl-default-server-options", ssl_parse_default_server_options },
6488 { 0, NULL, NULL },
6489 }};
6490
6491 /* transport-layer operations for SSL sockets */
6492 struct xprt_ops ssl_sock = {
6493 .snd_buf = ssl_sock_from_buf,
6494 .rcv_buf = ssl_sock_to_buf,
6495 .rcv_pipe = NULL,
6496 .snd_pipe = NULL,
6497 .shutr = NULL,
6498 .shutw = ssl_sock_shutw,
6499 .close = ssl_sock_close,
6500 .init = ssl_sock_init,
6501 .name = "SSL",
6502 };
6503
6504 #if (OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined OPENSSL_NO_TLSEXT && !defined OPENSSL_IS_BORINGSSL && !defined LIBRESSL_VERSION_NUMBER)
6505
6506 static void ssl_sock_sctl_free_func(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx, long argl, void *argp)
6507 {
6508 if (ptr) {
6509 chunk_destroy(ptr);
6510 free(ptr);
6511 }
6512 }
6513
6514 #endif
6515
6516 __attribute__((constructor))
6517 static void __ssl_sock_init(void)
6518 {
6519 STACK_OF(SSL_COMP)* cm;
6520
6521 #ifdef LISTEN_DEFAULT_CIPHERS
6522 global.listen_default_ciphers = LISTEN_DEFAULT_CIPHERS;
6523 #endif
6524 #ifdef CONNECT_DEFAULT_CIPHERS
6525 global.connect_default_ciphers = CONNECT_DEFAULT_CIPHERS;
6526 #endif
6527 if (global.listen_default_ciphers)
6528 global.listen_default_ciphers = strdup(global.listen_default_ciphers);
6529 if (global.connect_default_ciphers)
6530 global.connect_default_ciphers = strdup(global.connect_default_ciphers);
6531 global.listen_default_ssloptions = BC_SSL_O_NONE;
6532 global.connect_default_ssloptions = SRV_SSL_O_NONE;
6533
6534 SSL_library_init();
6535 cm = SSL_COMP_get_compression_methods();
6536 sk_SSL_COMP_zero(cm);
6537 #if (OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined OPENSSL_NO_TLSEXT && !defined OPENSSL_IS_BORINGSSL && !defined LIBRESSL_VERSION_NUMBER)
6538 sctl_ex_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, ssl_sock_sctl_free_func);
6539 #endif
6540 sample_register_fetches(&sample_fetch_keywords);
6541 acl_register_keywords(&acl_kws);
6542 bind_register_keywords(&bind_kws);
6543 srv_register_keywords(&srv_kws);
6544 cfg_register_keywords(&cfg_kws);
6545 cli_register_kw(&cli_kws);
6546
6547 global.ssl_session_max_cost = SSL_SESSION_MAX_COST;
6548 global.ssl_handshake_max_cost = SSL_HANDSHAKE_MAX_COST;
6549
6550 #ifndef OPENSSL_NO_DH
6551 ssl_dh_ptr_index = SSL_CTX_get_ex_new_index(0, NULL, NULL, NULL, NULL);
6552 #endif
6553
6554 /* Load SSL string for the verbose & debug mode. */
6555 ERR_load_SSL_strings();
6556 }
6557
6558 __attribute__((destructor))
6559 static void __ssl_sock_deinit(void)
6560 {
6561 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
6562 lru64_destroy(ssl_ctx_lru_tree);
6563 #endif
6564
6565 #ifndef OPENSSL_NO_DH
6566 if (local_dh_1024) {
6567 DH_free(local_dh_1024);
6568 local_dh_1024 = NULL;
6569 }
6570
6571 if (local_dh_2048) {
6572 DH_free(local_dh_2048);
6573 local_dh_2048 = NULL;
6574 }
6575
6576 if (local_dh_4096) {
6577 DH_free(local_dh_4096);
6578 local_dh_4096 = NULL;
6579 }
6580
6581 if (global_dh) {
6582 DH_free(global_dh);
6583 global_dh = NULL;
6584 }
6585 #endif
6586
6587 ERR_remove_state(0);
6588 ERR_free_strings();
6589
6590 EVP_cleanup();
6591
6592 #if OPENSSL_VERSION_NUMBER >= 0x00907000L
6593 CRYPTO_cleanup_all_ex_data();
6594 #endif
6595 }
6596
6597
6598 /*
6599 * Local variables:
6600 * c-indent-level: 8
6601 * c-basic-offset: 8
6602 * End:
6603 */
6604