read the TLS data first, before the VPs
[freeradius.git] / src / main / tls.c
1 /*
2  * tls.c
3  *
4  * Version:     $Id$
5  *
6  *   This program is free software; you can redistribute it and/or modify
7  *   it under the terms of the GNU General Public License as published by
8  *   the Free Software Foundation; either version 2 of the License, or
9  *   (at your option) any later version.
10  *
11  *   This program is distributed in the hope that it will be useful,
12  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *   GNU General Public License for more details.
15  *
16  *   You should have received a copy of the GNU General Public License
17  *   along with this program; if not, write to the Free Software
18  *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  *
20  * Copyright 2001  hereUare Communications, Inc. <raghud@hereuare.com>
21  * Copyright 2003  Alan DeKok <aland@freeradius.org>
22  * Copyright 2006  The FreeRADIUS server project
23  */
24
25 RCSID("$Id$")
26 USES_APPLE_DEPRECATED_API       /* OpenSSL API has been deprecated by Apple */
27
28 #include <freeradius-devel/radiusd.h>
29 #include <freeradius-devel/process.h>
30 #include <freeradius-devel/rad_assert.h>
31
32 #ifdef HAVE_SYS_STAT_H
33 #include <sys/stat.h>
34 #endif
35
36 #ifdef HAVE_FCNTL_H
37 #include <fcntl.h>
38 #endif
39
40 #ifdef HAVE_UTIME_H
41 #include <utime.h>
42 #endif
43 #include <ctype.h>
44
45 #ifdef WITH_TLS
46 #  ifdef HAVE_OPENSSL_RAND_H
47 #    include <openssl/rand.h>
48 #  endif
49
50 #  ifdef HAVE_OPENSSL_OCSP_H
51 #    include <openssl/ocsp.h>
52 #  endif
53
54 #  ifdef HAVE_OPENSSL_EVP_H
55 #    include <openssl/evp.h>
56 #  endif
57 #  include <openssl/ssl.h>
58
59 #define LOG_PREFIX "tls"
60
61 #ifdef ENABLE_OPENSSL_VERSION_CHECK
62 typedef struct libssl_defect {
63         uint64_t        high;
64         uint64_t        low;
65
66         char const      *id;
67         char const      *name;
68         char const      *comment;
69 } libssl_defect_t;
70
71 /* Record critical defects in libssl here, new versions of OpenSSL to older versions of OpenSSL.  */
72 static libssl_defect_t libssl_defects[] =
73 {
74         {
75                 .low            = 0x01010101f,          /* 1.1.0a */
76                 .high           = 0x01010101f,          /* 1.1.0a */
77                 .id             = "CVE-2016-6309",
78                 .name           = "OCSP status request extension",
79                 .comment        = "For more information see https://www.openssl.org/news/secadv/20160926.txt"
80         },
81         {
82                 .low            = 0x01010100f,          /* 1.1.0  */
83                 .high           = 0x01010100f,          /* 1.1.0  */
84                 .id             = "CVE-2016-6304",
85                 .name           = "OCSP status request extension",
86                 .comment        = "For more information see https://www.openssl.org/news/secadv/20160922.txt"
87         },
88         {
89                 .low            = 0x01000209f,          /* 1.0.2i */
90                 .high           = 0x01000209f,          /* 1.0.2i */
91                 .id             = "CVE-2016-7052",
92                 .name           = "OCSP status request extension",
93                 .comment        = "For more information see https://www.openssl.org/news/secadv/20160926.txt"
94         },
95         {
96                 .low            = 0x01000200f,          /* 1.0.2  */
97                 .high           = 0x01000208f,          /* 1.0.2h */
98                 .id             = "CVE-2016-6304",
99                 .name           = "OCSP status request extension",
100                 .comment        = "For more information see https://www.openssl.org/news/secadv/20160922.txt"
101         },
102         {
103                 .low            = 0x01000100f,          /* 1.0.1  */
104                 .high           = 0x01000114f,          /* 1.0.1t */
105                 .id             = "CVE-2016-6304",
106                 .name           = "OCSP status request extension",
107                 .comment        = "For more information see https://www.openssl.org/news/secadv/20160922.txt"
108         },
109         {
110                 .low            = 0x010001000,          /* 1.0.1  */
111                 .high           = 0x01000106f,          /* 1.0.1f */
112                 .id             = "CVE-2014-0160",
113                 .name           = "Heartbleed",
114                 .comment        = "For more information see http://heartbleed.com"
115         },
116 };
117 #endif /* ENABLE_OPENSSL_VERSION_CHECK */
118
119 FR_NAME_NUMBER const fr_tls_status_table[] = {
120         { "invalid",                    FR_TLS_INVALID },
121         { "request",                    FR_TLS_REQUEST },
122         { "response",                   FR_TLS_RESPONSE },
123         { "success",                    FR_TLS_SUCCESS },
124         { "fail",                       FR_TLS_FAIL },
125         { "noop",                       FR_TLS_NOOP },
126
127         { "start",                      FR_TLS_START },
128         { "ok",                         FR_TLS_OK },
129         { "ack",                        FR_TLS_ACK },
130         { "first fragment",             FR_TLS_FIRST_FRAGMENT },
131         { "more fragments",             FR_TLS_MORE_FRAGMENTS },
132         { "length included",            FR_TLS_LENGTH_INCLUDED },
133         { "more fragments with length", FR_TLS_MORE_FRAGMENTS_WITH_LENGTH },
134         { "handled",                    FR_TLS_HANDLED },
135         {  NULL ,                       -1},
136 };
137
138 /* index we use to store cached session VPs
139  * needs to be dynamic so we can supply a "free" function
140  */
141 int fr_tls_ex_index_vps = -1;
142 int fr_tls_ex_index_certs = -1;
143
144 /* Session */
145 static void             session_close(tls_session_t *ssn);
146 static void             session_init(tls_session_t *ssn);
147
148 /* record */
149 static void             record_init(record_t *buf);
150 static void             record_close(record_t *buf);
151 static unsigned int     record_plus(record_t *buf, void const *ptr,
152                                     unsigned int size);
153 static unsigned int     record_minus(record_t *buf, void *ptr,
154                                      unsigned int size);
155
156 DIAG_OFF(format-nonliteral)
157 /** Print errors in the TLS thread local error stack
158  *
159  * Drains the thread local OpenSSL error queue, and prints out errors.
160  *
161  * @param[in] request   The current request (may be NULL).
162  * @param[in] msg       Error message describing the operation being attempted.
163  * @param[in] ap        Arguments for msg.
164  * @return the number of errors drained from the stack.
165  */
166 static int tls_verror_log(REQUEST *request, char const *msg, va_list ap)
167 {
168         unsigned long   error;
169         char            *p;
170         int             in_stack = 0;
171         char            buffer[256];
172
173         int             line;
174         char const      *file;
175
176         /*
177          *      Pop the first error, so ERR_peek_error()
178          *      can be used to determine if there are
179          *      multiple errors.
180          */
181         error = ERR_get_error_line(&file, &line);
182
183         if (msg) {
184                 p = talloc_vasprintf(request, msg, ap);
185
186                 /*
187                  *      Single line mode (there's only one error)
188                  */
189                 if (error && !ERR_peek_error()) {
190                         ERR_error_string_n(error, buffer, sizeof(buffer));
191
192                         /* Extra verbose */
193                         if ((request && RDEBUG_ENABLED3) || DEBUG_ENABLED3) {
194                                 ROPTIONAL(REDEBUG, ERROR, "%s: %s[%i]:%s", p, file, line, buffer);
195                         } else {
196                                 ROPTIONAL(REDEBUG, ERROR, "%s: %s", p, buffer);
197                         }
198
199                         talloc_free(p);
200
201                         return 1;
202                 }
203
204                 /*
205                  *      Print the error we were given, irrespective
206                  *      of whether there were any OpenSSL errors.
207                  */
208                 ROPTIONAL(RERROR, ERROR, "%s", p);
209                 talloc_free(p);
210         }
211
212         /*
213          *      Stack mode (there are multiple errors)
214          */
215         if (!error) return 0;
216         do {
217                 ERR_error_string_n(error, buffer, sizeof(buffer));
218                 /* Extra verbose */
219                 if ((request && RDEBUG_ENABLED3) || DEBUG_ENABLED3) {
220                         ROPTIONAL(REDEBUG, ERROR, "%s[%i]:%s", file, line, buffer);
221                 } else {
222                         ROPTIONAL(REDEBUG, ERROR, "%s", buffer);
223                 }
224                 in_stack++;
225         } while ((error = ERR_get_error_line(&file, &line)));
226
227         return in_stack;
228 }
229 DIAG_ON(format-nonliteral)
230
231 /** Print errors in the TLS thread local error stack
232  *
233  * Drains the thread local OpenSSL error queue, and prints out errors.
234  *
235  * @param[in] request   The current request (may be NULL).
236  * @param[in] msg       Error message describing the operation being attempted.
237  * @param[in] ...       Arguments for msg.
238  * @return the number of errors drained from the stack.
239  */
240 int tls_error_log(REQUEST *request, char const *msg, ...)
241 {
242         va_list ap;
243         int ret;
244
245         va_start(ap, msg);
246         ret = tls_verror_log(request, msg, ap);
247         va_end(ap);
248
249         return ret;
250 }
251
252 /** Print errors raised by OpenSSL I/O functions
253  *
254  * Drains the thread local OpenSSL error queue, and prints out errors
255  * based on the SSL handle and the return code of the I/O  function.
256  *
257  * OpenSSL lists I/O functions to be:
258  *   - SSL_connect
259  *   - SSL_accept
260  *   - SSL_do_handshake
261  *   - SSL_read
262  *   - SSL_peek
263  *   - SSL_write
264  *
265  * @param request       The current request (may be NULL).
266  * @param session       The current tls_session.
267  * @param ret           from the I/O operation.
268  * @param msg           Error message describing the operation being attempted.
269  * @param ...           Arguments for msg.
270  * @return
271  *      - 0 TLS session cannot continue.
272  *      - 1 TLS session may still be viable.
273  */
274 int tls_error_io_log(REQUEST *request, tls_session_t *session, int ret, char const *msg, ...)
275 {
276         int     error;
277         va_list ap;
278
279         if (ERR_peek_error()) {
280                 va_start(ap, msg);
281                 tls_verror_log(request, msg, ap);
282                 va_end(ap);
283         }
284
285         error = SSL_get_error(session->ssl, ret);
286         switch (error) {
287         /*
288          *      These seem to be harmless and already "dealt
289          *      with" by our non-blocking environment. NB:
290          *      "ZERO_RETURN" is the clean "error"
291          *      indicating a successfully closed SSL
292          *      tunnel. We let this happen because our IO
293          *      loop should not appear to have broken on
294          *      this condition - and outside the IO loop, the
295          *      "shutdown" state is checked.
296          *
297          *      Don't print anything if we ignore the error.
298          */
299         case SSL_ERROR_NONE:
300         case SSL_ERROR_WANT_READ:
301         case SSL_ERROR_WANT_WRITE:
302         case SSL_ERROR_WANT_X509_LOOKUP:
303         case SSL_ERROR_ZERO_RETURN:
304                 break;
305
306         /*
307          *      These seem to be indications of a genuine
308          *      error that should result in the SSL tunnel
309          *      being regarded as "dead".
310          */
311         case SSL_ERROR_SYSCALL:
312                 ROPTIONAL(REDEBUG, ERROR, "System call (I/O) error (%i)", ret);
313                 return 0;
314
315         case SSL_ERROR_SSL:
316                 ROPTIONAL(REDEBUG, ERROR, "TLS protocol error (%i)", ret);
317                 return 0;
318
319         /*
320          *      For any other errors that (a) exist, and (b)
321          *      crop up - we need to interpret what to do with
322          *      them - so "politely inform" the caller that
323          *      the code needs updating here.
324          */
325         default:
326                 ROPTIONAL(REDEBUG, ERROR, "TLS session error %i (%i)", error, ret);
327                 return 0;
328         }
329
330         return 1;
331 }
332
333 #ifdef PSK_MAX_IDENTITY_LEN
334 static bool identity_is_safe(const char *identity)
335 {
336         char c;
337
338         if (!identity) return true;
339
340         while ((c = *(identity++)) != '\0') {
341                 if (isalpha((int) c) || isdigit((int) c) || isspace((int) c) ||
342                     (c == '@') || (c == '-') || (c == '_') || (c == '.')) {
343                         continue;
344                 }
345
346                 return false;
347         }
348
349         return true;
350 }
351
352 /*
353  *      When a client uses TLS-PSK to talk to a server, this callback
354  *      is used by the server to determine the PSK to use.
355  */
356 static unsigned int psk_server_callback(SSL *ssl, const char *identity,
357                                         unsigned char *psk,
358                                         unsigned int max_psk_len)
359 {
360         unsigned int psk_len = 0;
361         fr_tls_server_conf_t *conf;
362         REQUEST *request;
363
364         conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl,
365                                                        FR_TLS_EX_INDEX_CONF);
366         if (!conf) return 0;
367
368         request = (REQUEST *)SSL_get_ex_data(ssl,
369                                              FR_TLS_EX_INDEX_REQUEST);
370         if (request && conf->psk_query) {
371                 size_t hex_len;
372                 VALUE_PAIR *vp;
373                 char buffer[2 * PSK_MAX_PSK_LEN + 4]; /* allow for too-long keys */
374
375                 /*
376                  *      The passed identity is weird.  Deny it.
377                  */
378                 if (!identity_is_safe(identity)) {
379                         RWDEBUG("Invalid characters in PSK identity %s", identity);
380                         return 0;
381                 }
382
383                 vp = pair_make_request("TLS-PSK-Identity", identity, T_OP_SET);
384                 if (!vp) return 0;
385
386                 hex_len = radius_xlat(buffer, sizeof(buffer), request, conf->psk_query,
387                                       NULL, NULL);
388                 if (!hex_len) {
389                         RWDEBUG("PSK expansion returned an empty string.");
390                         return 0;
391                 }
392
393                 /*
394                  *      The returned key is truncated at MORE than
395                  *      OpenSSL can handle.  That way we can detect
396                  *      the truncation, and complain about it.
397                  */
398                 if (hex_len > (2 * max_psk_len)) {
399                         RWDEBUG("Returned PSK is too long (%u > %u)",
400                                 (unsigned int) hex_len, 2 * max_psk_len);
401                         return 0;
402                 }
403
404                 /*
405                  *      Leave the TLS-PSK-Identity in the request, and
406                  *      convert the expansion from printable string
407                  *      back to hex.
408                  */
409                 return fr_hex2bin(psk, max_psk_len, buffer, hex_len);
410         }
411
412         if (!conf->psk_identity) {
413                 DEBUG("No static PSK identity set.  Rejecting the user");
414                 return 0;
415         }
416
417         /*
418          *      No REQUEST, or no dynamic query.  Just look for a
419          *      static identity.
420          */
421         if (strcmp(identity, conf->psk_identity) != 0) {
422                 ERROR("Supplied PSK identity %s does not match configuration.  Rejecting.",
423                       identity);
424                 return 0;
425         }
426
427         psk_len = strlen(conf->psk_password);
428         if (psk_len > (2 * max_psk_len)) return 0;
429
430         return fr_hex2bin(psk, max_psk_len, conf->psk_password, psk_len);
431 }
432
433 static unsigned int psk_client_callback(SSL *ssl, UNUSED char const *hint,
434                                         char *identity, unsigned int max_identity_len,
435                                         unsigned char *psk, unsigned int max_psk_len)
436 {
437         unsigned int psk_len;
438         fr_tls_server_conf_t *conf;
439
440         conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl,
441                                                        FR_TLS_EX_INDEX_CONF);
442         if (!conf) return 0;
443
444         psk_len = strlen(conf->psk_password);
445         if (psk_len > (2 * max_psk_len)) return 0;
446
447         strlcpy(identity, conf->psk_identity, max_identity_len);
448
449         return fr_hex2bin(psk, max_psk_len, conf->psk_password, psk_len);
450 }
451
452 #endif
453
454 #define MAX_SESSION_SIZE (256)
455
456
457 void tls_session_id(SSL_SESSION *ssn, char *buffer, size_t bufsize)
458 {
459 #if OPENSSL_VERSION_NUMBER < 0x10001000L
460         size_t size;
461
462         size = ssn->session_id_length;
463         if (size > bufsize) size = bufsize;
464
465         fr_bin2hex(buffer, ssn->session_id, size);
466 #else
467         unsigned int size;
468         uint8_t const *p;
469
470         p = SSL_SESSION_get_id(ssn, &size);
471         if (size > bufsize) size = bufsize;
472
473         fr_bin2hex(buffer, p, size);
474
475 #endif
476 }
477
478
479
480 static int _tls_session_free(tls_session_t *ssn)
481 {
482         /*
483          *      Free any opaque TTLS or PEAP data.
484          */
485         if ((ssn->opaque) && (ssn->free_opaque)) {
486                 ssn->free_opaque(ssn->opaque);
487                 ssn->opaque = NULL;
488         }
489
490         session_close(ssn);
491
492         return 0;
493 }
494
495 tls_session_t *tls_new_client_session(TALLOC_CTX *ctx, fr_tls_server_conf_t *conf, int fd)
496 {
497         int ret;
498         int verify_mode;
499         tls_session_t *ssn = NULL;
500         REQUEST *request;
501
502         ssn = talloc_zero(ctx, tls_session_t);
503         if (!ssn) return NULL;
504
505         talloc_set_destructor(ssn, _tls_session_free);
506
507         ssn->ctx = conf->ctx;
508
509         SSL_CTX_set_mode(ssn->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_AUTO_RETRY);
510
511         ssn->ssl = SSL_new(ssn->ctx);
512         if (!ssn->ssl) {
513                 talloc_free(ssn);
514                 return NULL;
515         }
516
517         request = request_alloc(ssn);
518         SSL_set_ex_data(ssn->ssl, FR_TLS_EX_INDEX_REQUEST, (void *)request);
519
520         /*
521          *      Add the message callback to identify what type of
522          *      message/handshake is passed
523          */
524         SSL_set_msg_callback(ssn->ssl, cbtls_msg);
525         SSL_set_msg_callback_arg(ssn->ssl, ssn);
526         SSL_set_info_callback(ssn->ssl, cbtls_info);
527
528         /*
529          *      Always verify the peer certificate.
530          */
531         DEBUG2("Requiring Server certificate");
532         verify_mode = SSL_VERIFY_PEER;
533         verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
534         SSL_set_verify(ssn->ssl, verify_mode, cbtls_verify);
535
536         SSL_set_ex_data(ssn->ssl, FR_TLS_EX_INDEX_CONF, (void *)conf);
537         SSL_set_ex_data(ssn->ssl, FR_TLS_EX_INDEX_SSN, (void *)ssn);
538         SSL_set_fd(ssn->ssl, fd);
539         ret = SSL_connect(ssn->ssl);
540         if (ret <= 0) {
541                 tls_error_io_log(NULL, ssn, ret, "Failed in " STRINGIFY(__FUNCTION__) " (SSL_connect)");
542                 talloc_free(ssn);
543
544                 return NULL;
545         }
546
547         ssn->mtu = conf->fragment_size;
548
549         return ssn;
550 }
551
552
553 /** Create a new TLS session
554  *
555  * Configures a new TLS session, configuring options, setting callbacks etc...
556  *
557  * @param ctx to alloc session data in. Should usually be NULL unless the lifetime of the
558  *      session is tied to another talloc'd object.
559  * @param conf to use to configure the tls session.
560  * @param request The current #REQUEST.
561  * @param client_cert Whether to require a client_cert.
562  * @return a new session on success, or NULL on error.
563  */
564 tls_session_t *tls_new_session(TALLOC_CTX *ctx, fr_tls_server_conf_t *conf, REQUEST *request, bool client_cert)
565 {
566         tls_session_t   *state = NULL;
567         SSL             *new_tls = NULL;
568         int             verify_mode = 0;
569         VALUE_PAIR      *vp;
570
571         rad_assert(request != NULL);
572
573         RDEBUG2("Initiating new EAP-TLS session");
574
575         /*
576          *      Manually flush the sessions every so often.  If HALF
577          *      of the session lifetime has passed since we last
578          *      flushed, then flush it again.
579          *
580          *      FIXME: Also do it every N sessions?
581          */
582         if (conf->session_cache_enable &&
583             ((conf->session_last_flushed + ((int)conf->session_timeout * 1800)) <= request->timestamp)){
584                 RDEBUG2("Flushing SSL sessions (of #%ld)", SSL_CTX_sess_number(conf->ctx));
585
586                 SSL_CTX_flush_sessions(conf->ctx, request->timestamp);
587                 conf->session_last_flushed = request->timestamp;
588         }
589
590         new_tls = SSL_new(conf->ctx);
591         if (new_tls == NULL) {
592                 tls_error_log(request, "Error creating new TLS session");
593                 return NULL;
594         }
595
596         /* We use the SSL's "app_data" to indicate a call-back */
597         SSL_set_app_data(new_tls, NULL);
598
599         if ((state = talloc_zero(ctx, tls_session_t)) == NULL) {
600                 RERROR("Error allocating memory for SSL state");
601                 return NULL;
602         }
603         session_init(state);
604         talloc_set_destructor(state, _tls_session_free);
605
606         state->ctx = conf->ctx;
607         state->ssl = new_tls;
608
609         /*
610          *      Initialize callbacks
611          */
612         state->record_init = record_init;
613         state->record_close = record_close;
614         state->record_plus = record_plus;
615         state->record_minus = record_minus;
616
617         /*
618          *      Create & hook the BIOs to handle the dirty side of the
619          *      SSL.  This is *very important* as we want to handle
620          *      the transmission part.  Now the only IO interface
621          *      that SSL is aware of, is our defined BIO buffers.
622          *
623          *      This means that all SSL IO is done to/from memory,
624          *      and we can update those BIOs from the packets we've
625          *      received.
626          */
627         state->into_ssl = BIO_new(BIO_s_mem());
628         state->from_ssl = BIO_new(BIO_s_mem());
629         SSL_set_bio(state->ssl, state->into_ssl, state->from_ssl);
630
631         /*
632          *      Add the message callback to identify what type of
633          *      message/handshake is passed
634          */
635         SSL_set_msg_callback(new_tls, cbtls_msg);
636         SSL_set_msg_callback_arg(new_tls, state);
637         SSL_set_info_callback(new_tls, cbtls_info);
638
639         /*
640          *      In Server mode we only accept.
641          */
642         SSL_set_accept_state(state->ssl);
643
644         /*
645          *      Verify the peer certificate, if asked.
646          */
647         if (client_cert) {
648                 RDEBUG2("Setting verify mode to require certificate from client");
649                 verify_mode = SSL_VERIFY_PEER;
650                 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
651                 verify_mode |= SSL_VERIFY_CLIENT_ONCE;
652         }
653         SSL_set_verify(state->ssl, verify_mode, cbtls_verify);
654
655         SSL_set_ex_data(state->ssl, FR_TLS_EX_INDEX_CONF, (void *)conf);
656         SSL_set_ex_data(state->ssl, FR_TLS_EX_INDEX_SSN, (void *)state);
657         state->length_flag = conf->include_length;
658
659         /*
660          *      We use default fragment size, unless the Framed-MTU
661          *      tells us it's too big.  Note that we do NOT account
662          *      for the EAP-TLS headers if conf->fragment_size is
663          *      large, because that config item looks to be confusing.
664          *
665          *      i.e. it should REALLY be called MTU, and the code here
666          *      should figure out what that means for TLS fragment size.
667          *      asking the administrator to know the internal details
668          *      of EAP-TLS in order to calculate fragment sizes is
669          *      just too much.
670          */
671         state->mtu = conf->fragment_size;
672         vp = fr_pair_find_by_num(request->packet->vps, PW_FRAMED_MTU, 0, TAG_ANY);
673         if (vp && (vp->vp_integer > 100) && (vp->vp_integer < state->mtu)) {
674                 state->mtu = vp->vp_integer;
675         }
676
677         if (conf->session_cache_enable) state->allow_session_resumption = true; /* otherwise it's false */
678
679         return state;
680 }
681
682 /*
683  * We are the server, we always get the dirty data
684  * (Handshake data is also considered as dirty data)
685  * During handshake, since SSL API handles itself,
686  * After clean-up, dirty_out will be filled with
687  * the data required for handshaking. So we check
688  * if dirty_out is empty then we simply send it back.
689  * As of now, if handshake is successful, then we keep going,
690  * otherwise we fail.
691  *
692  * Fill the Bio with the dirty data to clean it
693  * Get the cleaned data from SSL, if it is not Handshake data
694  */
695 int tls_handshake_recv(REQUEST *request, tls_session_t *ssn)
696 {
697         int err;
698
699         if (ssn->invalid_hb_used) return 0;
700
701         err = BIO_write(ssn->into_ssl, ssn->dirty_in.data, ssn->dirty_in.used);
702         if (err != (int) ssn->dirty_in.used) {
703                 REDEBUG("Failed writing %zd bytes to SSL BIO: %d", ssn->dirty_in.used, err);
704                 record_init(&ssn->dirty_in);
705                 return 0;
706         }
707         record_init(&ssn->dirty_in);
708
709         err = SSL_read(ssn->ssl, ssn->clean_out.data + ssn->clean_out.used,
710                        sizeof(ssn->clean_out.data) - ssn->clean_out.used);
711         if (err > 0) {
712                 ssn->clean_out.used += err;
713                 return 1;
714         }
715
716         if (!tls_error_io_log(request, ssn, err, "Failed in " STRINGIFY(__FUNCTION__) " (SSL_read)")) return 0;
717
718         /* Some Extra STATE information for easy debugging */
719         if (SSL_is_init_finished(ssn->ssl)) RDEBUG2("SSL Connection Established");
720         if (SSL_in_init(ssn->ssl)) RDEBUG2("In SSL Handshake Phase");
721         if (SSL_in_before(ssn->ssl)) RDEBUG2("Before SSL Handshake Phase");
722         if (SSL_in_accept_init(ssn->ssl)) RDEBUG2("In SSL Accept mode");
723         if (SSL_in_connect_init(ssn->ssl)) RDEBUG2("In SSL Connect mode");
724
725 #if OPENSSL_VERSION_NUMBER >= 0x10001000L
726         /*
727          *      Cache the SSL_SESSION pointer.
728          */
729         if (!ssn->ssl_session && SSL_is_init_finished(ssn->ssl)) {
730                 ssn->ssl_session = SSL_get_session(ssn->ssl);
731                 if (!ssn->ssl_session) {
732                         RDEBUG("Failed getting SSL session");
733                         return 0;
734                 }
735         }
736 #endif
737
738         err = BIO_ctrl_pending(ssn->from_ssl);
739         if (err > 0) {
740                 err = BIO_read(ssn->from_ssl, ssn->dirty_out.data,
741                                sizeof(ssn->dirty_out.data));
742                 if (err > 0) {
743                         ssn->dirty_out.used = err;
744
745                 } else if (BIO_should_retry(ssn->from_ssl)) {
746                         record_init(&ssn->dirty_in);
747                         RDEBUG2("Asking for more data in tunnel");
748                         return 1;
749
750                 } else {
751                         tls_error_log(NULL, NULL);
752                         record_init(&ssn->dirty_in);
753                         return 0;
754                 }
755         } else {
756                 RDEBUG2("SSL Application Data");
757                 /* Its clean application data, do whatever we want */
758                 record_init(&ssn->clean_out);
759         }
760
761         /* We are done with dirty_in, reinitialize it */
762         record_init(&ssn->dirty_in);
763         return 1;
764 }
765
766 /*
767  *      Take cleartext user data, and encrypt it into the output buffer,
768  *      to send to the client at the other end of the SSL connection.
769  */
770 int tls_handshake_send(REQUEST *request, tls_session_t *ssn)
771 {
772         int err;
773
774         /*
775          *      If there's un-encrypted data in 'clean_in', then write
776          *      that data to the SSL session, and then call the BIO function
777          *      to get that encrypted data from the SSL session, into
778          *      a buffer which we can then package into an EAP packet.
779          *
780          *      Based on Server's logic this clean_in is expected to
781          *      contain the data to send to the client.
782          */
783         if (ssn->clean_in.used > 0) {
784                 int written;
785
786                 written = SSL_write(ssn->ssl, ssn->clean_in.data, ssn->clean_in.used);
787                 record_minus(&ssn->clean_in, NULL, written);
788
789                 /* Get the dirty data from Bio to send it */
790                 err = BIO_read(ssn->from_ssl, ssn->dirty_out.data,
791                                sizeof(ssn->dirty_out.data));
792                 if (err > 0) {
793                         ssn->dirty_out.used = err;
794                 } else {
795                         if (!tls_error_io_log(request, ssn, err,
796                                               "Failed in " STRINGIFY(__FUNCTION__) " (SSL_write)")) {
797                                 return 0;
798                         }
799                 }
800         }
801
802         return 1;
803 }
804
805 static void session_init(tls_session_t *ssn)
806 {
807         ssn->ssl = NULL;
808         ssn->into_ssl = ssn->from_ssl = NULL;
809         record_init(&ssn->clean_in);
810         record_init(&ssn->clean_out);
811         record_init(&ssn->dirty_in);
812         record_init(&ssn->dirty_out);
813
814         memset(&ssn->info, 0, sizeof(ssn->info));
815
816         ssn->mtu = 0;
817         ssn->fragment = false;
818         ssn->tls_msg_len = 0;
819         ssn->length_flag = false;
820         ssn->opaque = NULL;
821         ssn->free_opaque = NULL;
822 }
823
824 static void session_close(tls_session_t *ssn)
825 {
826         SSL_set_quiet_shutdown(ssn->ssl, 1);
827         SSL_shutdown(ssn->ssl);
828
829         if (ssn->ssl) {
830                 SSL_free(ssn->ssl);
831                 ssn->ssl = NULL;
832         }
833
834         record_close(&ssn->clean_in);
835         record_close(&ssn->clean_out);
836         record_close(&ssn->dirty_in);
837         record_close(&ssn->dirty_out);
838         session_init(ssn);
839 }
840
841 static void record_init(record_t *rec)
842 {
843         rec->used = 0;
844 }
845
846 static void record_close(record_t *rec)
847 {
848         rec->used = 0;
849 }
850
851
852 /*
853  *      Copy data to the intermediate buffer, before we send
854  *      it somewhere.
855  */
856 static unsigned int record_plus(record_t *rec, void const *ptr,
857                                 unsigned int size)
858 {
859         unsigned int added = MAX_RECORD_SIZE - rec->used;
860
861         if(added > size)
862                 added = size;
863         if(added == 0)
864                 return 0;
865         memcpy(rec->data + rec->used, ptr, added);
866         rec->used += added;
867         return added;
868 }
869
870 /*
871  *      Take data from the buffer, and give it to the caller.
872  */
873 static unsigned int record_minus(record_t *rec, void *ptr,
874                                  unsigned int size)
875 {
876         unsigned int taken = rec->used;
877
878         if(taken > size)
879                 taken = size;
880         if(taken == 0)
881                 return 0;
882         if(ptr)
883                 memcpy(ptr, rec->data, taken);
884         rec->used -= taken;
885
886         /*
887          *      This is pretty bad...
888          */
889         if (rec->used > 0) memmove(rec->data, rec->data + taken, rec->used);
890
891         return taken;
892 }
893
894 void tls_session_information(tls_session_t *tls_session)
895 {
896         char const *str_write_p, *str_version, *str_content_type = "";
897         char const *str_details1 = "", *str_details2= "";
898         REQUEST *request;
899         char buffer[32];
900
901         /*
902          *      Don't print this out in the normal course of
903          *      operations.
904          */
905         if (rad_debug_lvl == 0) return;
906
907         str_write_p = tls_session->info.origin ? ">>> send" : "<<< recv";
908
909         switch (tls_session->info.version) {
910         case SSL2_VERSION:
911                 str_version = "SSL 2.0 ";
912                 break;
913         case SSL3_VERSION:
914                 str_version = "SSL 3.0 ";
915                 break;
916         case TLS1_VERSION:
917                 str_version = "TLS 1.0 ";
918                 break;
919 #ifdef TLS1_1_VERSION
920         case TLS1_1_VERSION:
921                 str_version = "TLS 1.1 ";
922                 break;
923 #endif
924 #ifdef TLS1_2_VERSION
925         case TLS1_2_VERSION:
926                 str_version = "TLS 1.2 ";
927                 break;
928 #endif
929 #ifdef TLS1_3_VERSON
930         case TLS1_3_VERSION:
931                 str_version = "TLS 1.3 ";
932                 break;
933 #endif
934
935         default:
936                 sprintf(buffer, "UNKNOWN TLS VERSION ?%04X?", tls_session->info.version);
937                 str_version = buffer;
938                 break;
939         }
940
941         if (tls_session->info.version == SSL3_VERSION ||
942             tls_session->info.version == TLS1_VERSION) {
943                 switch (tls_session->info.content_type) {
944                 case SSL3_RT_CHANGE_CIPHER_SPEC:
945                         str_content_type = "ChangeCipherSpec";
946                         break;
947
948                 case SSL3_RT_ALERT:
949                         str_content_type = "Alert";
950                         break;
951
952                 case SSL3_RT_HANDSHAKE:
953                         str_content_type = "Handshake";
954                         break;
955
956                 case SSL3_RT_APPLICATION_DATA:
957                         str_content_type = "ApplicationData";
958                         break;
959
960                 default:
961                         str_content_type = "UnknownContentType";
962                         break;
963                 }
964
965                 if (tls_session->info.content_type == SSL3_RT_ALERT) {
966                         str_details1 = ", ???";
967
968                         if (tls_session->info.record_len == 2) {
969
970                                 switch (tls_session->info.alert_level) {
971                                 case SSL3_AL_WARNING:
972                                         str_details1 = ", warning";
973                                         break;
974                                 case SSL3_AL_FATAL:
975                                         str_details1 = ", fatal";
976                                         break;
977                                 }
978
979                                 str_details2 = " ???";
980                                 switch (tls_session->info.alert_description) {
981                                 case SSL3_AD_CLOSE_NOTIFY:
982                                         str_details2 = " close_notify";
983                                         break;
984
985                                 case SSL3_AD_UNEXPECTED_MESSAGE:
986                                         str_details2 = " unexpected_message";
987                                         break;
988
989                                 case SSL3_AD_BAD_RECORD_MAC:
990                                         str_details2 = " bad_record_mac";
991                                         break;
992
993                                 case TLS1_AD_DECRYPTION_FAILED:
994                                         str_details2 = " decryption_failed";
995                                         break;
996
997                                 case TLS1_AD_RECORD_OVERFLOW:
998                                         str_details2 = " record_overflow";
999                                         break;
1000
1001                                 case SSL3_AD_DECOMPRESSION_FAILURE:
1002                                         str_details2 = " decompression_failure";
1003                                         break;
1004
1005                                 case SSL3_AD_HANDSHAKE_FAILURE:
1006                                         str_details2 = " handshake_failure";
1007                                         break;
1008
1009                                 case SSL3_AD_BAD_CERTIFICATE:
1010                                         str_details2 = " bad_certificate";
1011                                         break;
1012
1013                                 case SSL3_AD_UNSUPPORTED_CERTIFICATE:
1014                                         str_details2 = " unsupported_certificate";
1015                                         break;
1016
1017                                 case SSL3_AD_CERTIFICATE_REVOKED:
1018                                         str_details2 = " certificate_revoked";
1019                                         break;
1020
1021                                 case SSL3_AD_CERTIFICATE_EXPIRED:
1022                                         str_details2 = " certificate_expired";
1023                                         break;
1024
1025                                 case SSL3_AD_CERTIFICATE_UNKNOWN:
1026                                         str_details2 = " certificate_unknown";
1027                                         break;
1028
1029                                 case SSL3_AD_ILLEGAL_PARAMETER:
1030                                         str_details2 = " illegal_parameter";
1031                                         break;
1032
1033                                 case TLS1_AD_UNKNOWN_CA:
1034                                         str_details2 = " unknown_ca";
1035                                         break;
1036
1037                                 case TLS1_AD_ACCESS_DENIED:
1038                                         str_details2 = " access_denied";
1039                                         break;
1040
1041                                 case TLS1_AD_DECODE_ERROR:
1042                                         str_details2 = " decode_error";
1043                                         break;
1044
1045                                 case TLS1_AD_DECRYPT_ERROR:
1046                                         str_details2 = " decrypt_error";
1047                                         break;
1048
1049                                 case TLS1_AD_EXPORT_RESTRICTION:
1050                                         str_details2 = " export_restriction";
1051                                         break;
1052
1053                                 case TLS1_AD_PROTOCOL_VERSION:
1054                                         str_details2 = " protocol_version";
1055                                         break;
1056
1057                                 case TLS1_AD_INSUFFICIENT_SECURITY:
1058                                         str_details2 = " insufficient_security";
1059                                         break;
1060
1061                                 case TLS1_AD_INTERNAL_ERROR:
1062                                         str_details2 = " internal_error";
1063                                         break;
1064
1065                                 case TLS1_AD_USER_CANCELLED:
1066                                         str_details2 = " user_canceled";
1067                                         break;
1068
1069                                 case TLS1_AD_NO_RENEGOTIATION:
1070                                         str_details2 = " no_renegotiation";
1071                                         break;
1072                                 }
1073                         }
1074                 }
1075
1076                 if (tls_session->info.content_type == SSL3_RT_HANDSHAKE) {
1077                         str_details1 = "???";
1078
1079                         if (tls_session->info.record_len > 0) switch (tls_session->info.handshake_type) {
1080                         case SSL3_MT_HELLO_REQUEST:
1081                                 str_details1 = ", HelloRequest";
1082                                 break;
1083
1084                         case SSL3_MT_CLIENT_HELLO:
1085                                 str_details1 = ", ClientHello";
1086                                 break;
1087
1088                         case SSL3_MT_SERVER_HELLO:
1089                                 str_details1 = ", ServerHello";
1090                                 break;
1091
1092                         case SSL3_MT_CERTIFICATE:
1093                                 str_details1 = ", Certificate";
1094                                 break;
1095
1096                         case SSL3_MT_SERVER_KEY_EXCHANGE:
1097                                 str_details1 = ", ServerKeyExchange";
1098                                 break;
1099
1100                         case SSL3_MT_CERTIFICATE_REQUEST:
1101                                 str_details1 = ", CertificateRequest";
1102                                 break;
1103
1104                         case SSL3_MT_SERVER_DONE:
1105                                 str_details1 = ", ServerHelloDone";
1106                                 break;
1107
1108                         case SSL3_MT_CERTIFICATE_VERIFY:
1109                                 str_details1 = ", CertificateVerify";
1110                                 break;
1111
1112                         case SSL3_MT_CLIENT_KEY_EXCHANGE:
1113                                 str_details1 = ", ClientKeyExchange";
1114                                 break;
1115
1116                         case SSL3_MT_FINISHED:
1117                                 str_details1 = ", Finished";
1118                                 break;
1119                         }
1120                 }
1121         }
1122
1123         snprintf(tls_session->info.info_description,
1124                  sizeof(tls_session->info.info_description),
1125                  "%s %s%s [length %04lx]%s%s\n",
1126                  str_write_p, str_version, str_content_type,
1127                  (unsigned long)tls_session->info.record_len,
1128                  str_details1, str_details2);
1129
1130         request = SSL_get_ex_data(tls_session->ssl, FR_TLS_EX_INDEX_REQUEST);
1131         ROPTIONAL(RDEBUG2, DEBUG2, "%s", tls_session->info.info_description);
1132 }
1133
1134 static CONF_PARSER cache_config[] = {
1135         { "enable", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, session_cache_enable), "no" },
1136
1137         { "lifetime", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, session_timeout), "24" },
1138         { "name", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, session_id_name), NULL },
1139
1140         { "max_entries", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, session_cache_size), "255" },
1141         { "persist_dir", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, session_cache_path), NULL },
1142         CONF_PARSER_TERMINATOR
1143 };
1144
1145 static CONF_PARSER verify_config[] = {
1146         { "skip_if_ocsp_ok", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, verify_skip_if_ocsp_ok), "no" },
1147         { "tmpdir", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, verify_tmp_dir), NULL },
1148         { "client", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, verify_client_cert_cmd), NULL },
1149         CONF_PARSER_TERMINATOR
1150 };
1151
1152 #ifdef HAVE_OPENSSL_OCSP_H
1153 static CONF_PARSER ocsp_config[] = {
1154         { "enable", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_enable), "no" },
1155         { "override_cert_url", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_override_url), "no" },
1156         { "url", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, ocsp_url), NULL },
1157         { "use_nonce", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_use_nonce), "yes" },
1158         { "timeout", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, ocsp_timeout), "yes" },
1159         { "softfail", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_softfail), "no" },
1160         CONF_PARSER_TERMINATOR
1161 };
1162 #endif
1163
1164 static CONF_PARSER tls_server_config[] = {
1165         { "verify_depth", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, verify_depth), "0" },
1166         { "CA_path", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT | PW_TYPE_DEPRECATED, fr_tls_server_conf_t, ca_path), NULL },
1167         { "ca_path", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_path), NULL },
1168         { "pem_file_type", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, file_type), "yes" },
1169         { "private_key_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, private_key_file), NULL },
1170         { "certificate_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, certificate_file), NULL },
1171         { "CA_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT | PW_TYPE_DEPRECATED, fr_tls_server_conf_t, ca_file), NULL },
1172         { "ca_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_file), NULL },
1173         { "private_key_password", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_SECRET, fr_tls_server_conf_t, private_key_password), NULL },
1174 #ifdef PSK_MAX_IDENTITY_LEN
1175         { "psk_identity", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, psk_identity), NULL },
1176         { "psk_hexphrase", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_SECRET, fr_tls_server_conf_t, psk_password), NULL },
1177         { "psk_query", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, psk_query), NULL },
1178 #endif
1179         { "dh_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, dh_file), NULL },
1180         { "random_file", FR_CONF_OFFSET(PW_TYPE_FILE_EXISTS, fr_tls_server_conf_t, random_file), NULL },
1181         { "fragment_size", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, fragment_size), "1024" },
1182         { "include_length", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, include_length), "yes" },
1183         { "auto_chain", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, auto_chain), "yes" },
1184         { "disable_single_dh_use", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_single_dh_use), NULL },
1185         { "check_crl", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, check_crl), "no" },
1186 #ifdef X509_V_FLAG_CRL_CHECK_ALL
1187         { "check_all_crl", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, check_all_crl), "no" },
1188 #endif
1189         { "allow_expired_crl", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, allow_expired_crl), NULL },
1190         { "check_cert_cn", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_cn), NULL },
1191         { "cipher_list", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, cipher_list), NULL },
1192         { "cipher_server_preference", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, cipher_server_preference), NULL },
1193         { "check_cert_issuer", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_issuer), NULL },
1194         { "require_client_cert", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, require_client_cert), NULL },
1195
1196 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
1197 #ifndef OPENSSL_NO_ECDH
1198         { "ecdh_curve", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, ecdh_curve), "prime256v1" },
1199 #endif
1200 #endif
1201
1202 #ifdef SSL_OP_NO_TLSv1
1203         { "disable_tlsv1", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1), NULL },
1204 #endif
1205
1206 #ifdef SSL_OP_NO_TLSv1_1
1207         { "disable_tlsv1_1", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1_1), NULL },
1208 #endif
1209
1210 #ifdef SSL_OP_NO_TLSv1_2
1211         { "disable_tlsv1_2", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1_2), NULL },
1212 #endif
1213
1214         { "cache", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) cache_config },
1215
1216         { "verify", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) verify_config },
1217
1218 #ifdef HAVE_OPENSSL_OCSP_H
1219         { "ocsp", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) ocsp_config },
1220 #endif
1221         CONF_PARSER_TERMINATOR
1222 };
1223
1224
1225 static CONF_PARSER tls_client_config[] = {
1226         { "verify_depth", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, verify_depth), "0" },
1227         { "ca_path", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_path), NULL },
1228         { "pem_file_type", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, file_type), "yes" },
1229         { "private_key_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, private_key_file), NULL },
1230         { "certificate_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, certificate_file), NULL },
1231         { "ca_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_file), NULL },
1232         { "private_key_password", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_SECRET, fr_tls_server_conf_t, private_key_password), NULL },
1233         { "dh_file", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, dh_file), NULL },
1234         { "random_file", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, random_file), NULL },
1235         { "fragment_size", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, fragment_size), "1024" },
1236         { "include_length", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, include_length), "yes" },
1237         { "check_crl", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, check_crl), "no" },
1238         { "check_cert_cn", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_cn), NULL },
1239         { "cipher_list", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, cipher_list), NULL },
1240         { "check_cert_issuer", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_issuer), NULL },
1241
1242 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
1243 #ifndef OPENSSL_NO_ECDH
1244         { "ecdh_curve", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, ecdh_curve), "prime256v1" },
1245 #endif
1246 #endif
1247
1248 #ifdef SSL_OP_NO_TLSv1
1249         { "disable_tlsv1", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1), NULL },
1250 #endif
1251
1252 #ifdef SSL_OP_NO_TLSv1_1
1253         { "disable_tlsv1_1", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1_1), NULL },
1254 #endif
1255
1256 #ifdef SSL_OP_NO_TLSv1_2
1257         { "disable_tlsv1_2", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1_2), NULL },
1258 #endif
1259         CONF_PARSER_TERMINATOR
1260 };
1261
1262
1263 /*
1264  *      TODO: Check for the type of key exchange * like conf->dh_key
1265  */
1266 static int load_dh_params(SSL_CTX *ctx, char *file)
1267 {
1268         DH *dh = NULL;
1269         BIO *bio;
1270
1271         if (!file) return 0;
1272
1273         if ((bio = BIO_new_file(file, "r")) == NULL) {
1274                 ERROR(LOG_PREFIX ": Unable to open DH file - %s", file);
1275                 return -1;
1276         }
1277
1278         dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
1279         BIO_free(bio);
1280         if (!dh) {
1281                 WARN(LOG_PREFIX ": Unable to set DH parameters.  DH cipher suites may not work!");
1282                 WARN(LOG_PREFIX ": Fix this by running the OpenSSL command listed in eap.conf");
1283                 return 0;
1284         }
1285
1286         if (SSL_CTX_set_tmp_dh(ctx, dh) < 0) {
1287                 ERROR(LOG_PREFIX ": Unable to set DH parameters");
1288                 DH_free(dh);
1289                 return -1;
1290         }
1291
1292         DH_free(dh);
1293         return 0;
1294 }
1295
1296
1297 /*
1298  *      Print debugging messages, and free data.
1299  */
1300 static void cbtls_remove_session(SSL_CTX *ctx, SSL_SESSION *sess)
1301 {
1302         char                    buffer[2 * MAX_SESSION_SIZE + 1];
1303         fr_tls_server_conf_t    *conf;
1304
1305         tls_session_id(sess, buffer, MAX_SESSION_SIZE);
1306
1307         conf = (fr_tls_server_conf_t *)SSL_CTX_get_app_data(ctx);
1308         if (!conf) {
1309                 DEBUG(LOG_PREFIX ": Failed to find TLS configuration in session");
1310                 return;
1311         }
1312
1313         {
1314                 int rv;
1315                 char filename[256];
1316
1317                 DEBUG2(LOG_PREFIX ": Removing session %s from the cache", buffer);
1318
1319                 /* remove session and any cached VPs */
1320                 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
1321                          conf->session_cache_path, FR_DIR_SEP, buffer);
1322                 rv = unlink(filename);
1323                 if (rv != 0) {
1324                         DEBUG2(LOG_PREFIX ": Could not remove persisted session file %s: %s",
1325                                filename, fr_syserror(errno));
1326                 }
1327                 /* VPs might be absent; might not have been written to disk yet */
1328                 snprintf(filename, sizeof(filename), "%s%c%s.vps",
1329                          conf->session_cache_path, FR_DIR_SEP, buffer);
1330                 unlink(filename);
1331         }
1332
1333         return;
1334 }
1335
1336 static int cbtls_new_session(SSL *ssl, SSL_SESSION *sess)
1337 {
1338         char                    buffer[2 * MAX_SESSION_SIZE + 1];
1339         fr_tls_server_conf_t    *conf;
1340         unsigned char           *sess_blob = NULL;
1341
1342         REQUEST                 *request = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_REQUEST);
1343
1344         conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1345         if (!conf) {
1346                 RWDEBUG("Failed to find TLS configuration in session");
1347                 return 0;
1348         }
1349
1350         tls_session_id(sess, buffer, MAX_SESSION_SIZE);
1351
1352         {
1353                 int fd, rv, todo, blob_len;
1354                 char filename[256];
1355                 unsigned char *p;
1356
1357                 RDEBUG2("Serialising session %s, and storing in cache", buffer);
1358
1359                 /* find out what length data we need */
1360                 blob_len = i2d_SSL_SESSION(sess, NULL);
1361                 if (blob_len < 1) {
1362                         /* something went wrong */
1363                         RWDEBUG("Session serialisation failed, couldn't determine required buffer length");
1364                         return 0;
1365                 }
1366
1367
1368                 /* Do not convert to TALLOC - Thread safety */
1369                 /* alloc and convert to ASN.1 */
1370                 sess_blob = malloc(blob_len);
1371                 if (!sess_blob) {
1372                         RWDEBUG("Session serialisation failed, couldn't allocate buffer (%d bytes)", blob_len);
1373                         return 0;
1374                 }
1375                 /* openssl mutates &p */
1376                 p = sess_blob;
1377                 rv = i2d_SSL_SESSION(sess, &p);
1378                 if (rv != blob_len) {
1379                         RWDEBUG("Session serialisation failed");
1380                         goto error;
1381                 }
1382
1383                 /* open output file */
1384                 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
1385                          conf->session_cache_path, FR_DIR_SEP, buffer);
1386                 fd = open(filename, O_RDWR|O_CREAT|O_EXCL, 0600);
1387                 if (fd < 0) {
1388                         RERROR("Session serialisation failed, failed opening session file %s: %s",
1389                               filename, fr_syserror(errno));
1390                         goto error;
1391                 }
1392
1393                 todo = blob_len;
1394                 p = sess_blob;
1395                 while (todo > 0) {
1396                         rv = write(fd, p, todo);
1397                         if (rv < 1) {
1398                                 RWDEBUG("Failed writing session: %s", fr_syserror(errno));
1399                                 close(fd);
1400                                 goto error;
1401                         }
1402                         p += rv;
1403                         todo -= rv;
1404                 }
1405                 close(fd);
1406                 RWDEBUG("Wrote session %s to %s (%d bytes)", buffer, filename, blob_len);
1407         }
1408
1409 error:
1410         free(sess_blob);
1411
1412         return 0;
1413 }
1414
1415 #if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
1416 static SSL_SESSION *cbtls_get_session(SSL *ssl, unsigned char *data, int len, int *copy)
1417 #else
1418 static SSL_SESSION *cbtls_get_session(SSL *ssl, const unsigned char *data, int len, int *copy)
1419 #endif
1420 {
1421         size_t                  size;
1422         char                    buffer[2 * MAX_SESSION_SIZE + 1];
1423         fr_tls_server_conf_t    *conf;
1424         TALLOC_CTX              *talloc_ctx;
1425
1426         SSL_SESSION             *sess = NULL;
1427         unsigned char           *sess_data = NULL;
1428         PAIR_LIST               *pairlist = NULL;
1429
1430         REQUEST                 *request = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_REQUEST);
1431
1432         rad_assert(request != NULL);
1433
1434         size = len;
1435         if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
1436
1437         fr_bin2hex(buffer, data, size);
1438
1439         RDEBUG2("Peer requested cached session: %s", buffer);
1440
1441         *copy = 0;
1442
1443         conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1444         if (!conf) {
1445                 RWDEBUG("Failed to find TLS configuration in session");
1446                 return NULL;
1447         }
1448
1449         talloc_ctx = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_TALLOC);
1450
1451         {
1452                 int             rv, fd, todo;
1453                 char            filename[256];
1454
1455                 unsigned char const     **o;
1456                 unsigned char           **p;
1457                 uint8_t                 *q;
1458
1459                 struct stat     st;
1460                 VALUE_PAIR      *vps = NULL;
1461
1462                 /* load the actual SSL session */
1463                 snprintf(filename, sizeof(filename), "%s%c%s.asn1", conf->session_cache_path, FR_DIR_SEP, buffer);
1464                 fd = open(filename, O_RDONLY);
1465                 if (fd < 0) {
1466                         RWDEBUG("No persisted session file %s: %s", filename, fr_syserror(errno));
1467                         goto err;
1468                 }
1469
1470                 rv = fstat(fd, &st);
1471                 if (rv < 0) {
1472                         RWDEBUG("Failed stating persisted session file %s: %s", filename, fr_syserror(errno));
1473                         close(fd);
1474                         goto err;
1475                 }
1476
1477                 sess_data = talloc_array(NULL, unsigned char, st.st_size);
1478                 if (!sess_data) {
1479                         RWDEBUG("Failed allocating buffer for persisted session (%d bytes)", (int) st.st_size);
1480                         close(fd);
1481                         goto err;
1482                 }
1483
1484                 q = sess_data;
1485                 todo = st.st_size;
1486                 while (todo > 0) {
1487                         rv = read(fd, q, todo);
1488                         if (rv < 1) {
1489                                 RWDEBUG("Failed reading persisted session: %s", fr_syserror(errno));
1490                                 close(fd);
1491                                 goto err;
1492                         }
1493                         todo -= rv;
1494                         q += rv;
1495                 }
1496                 close(fd);
1497
1498                 /*
1499                  *      OpenSSL mutates what's passed in, so we assign sess_data to q,
1500                  *      so the value of q gets mutated, and not the value of sess_data.
1501                  *
1502                  *      We then need a pointer to hold &q, but it can't be const, because
1503                  *      clang complains about lack of consting in nested pointer types.
1504                  *
1505                  *      So we memcpy the value of that pointer, to one that
1506                  *      does have a const, which we then pass into d2i_SSL_SESSION *sigh*.
1507                  */
1508                 q = sess_data;
1509                 p = &q;
1510                 memcpy(&o, &p, sizeof(o));
1511                 sess = d2i_SSL_SESSION(NULL, o, st.st_size);
1512                 if (!sess) {
1513                         RWDEBUG("Failed loading persisted session: %s", ERR_error_string(ERR_get_error(), NULL));
1514                         goto err;
1515                 }
1516
1517                 /* read in the cached VPs from the .vps file */
1518                 snprintf(filename, sizeof(filename), "%s%c%s.vps",
1519                          conf->session_cache_path, FR_DIR_SEP, buffer);
1520                 rv = pairlist_read(talloc_ctx, filename, &pairlist, 1);
1521                 if (rv < 0) {
1522                         /* not safe to un-persist a session w/o VPs */
1523                         RWDEBUG("Failed loading persisted VPs for session %s", buffer);
1524                         goto err;
1525                 }
1526
1527                 /* move the cached VPs into the session */
1528                 fr_pair_list_mcopy_by_num(talloc_ctx, &vps, &pairlist->reply, 0, 0, TAG_ANY);
1529
1530                 SSL_SESSION_set_ex_data(sess, fr_tls_ex_index_vps, vps);
1531                 RWDEBUG("Successfully restored session %s", buffer);
1532                 rdebug_pair_list(L_DBG_LVL_2, request, vps, "reply:");
1533         }
1534 err:
1535         if (sess_data) talloc_free(sess_data);
1536         if (pairlist) pairlist_free(&pairlist);
1537
1538         return sess;
1539 }
1540
1541 #ifdef HAVE_OPENSSL_OCSP_H
1542
1543 /** Extract components of OCSP responser URL from a certificate
1544  *
1545  * @param[in] cert to extract URL from.
1546  * @param[out] host_out Portion of the URL (must be freed with free()).
1547  * @param[out] port_out Port portion of the URL (must be freed with free()).
1548  * @param[out] path_out Path portion of the URL (must be freed with free()).
1549  * @param[out] is_https Whether the responder should be contacted using https.
1550  * @return
1551  *      - 0 if no valid URL is contained in the certificate.
1552  *      - 1 if a URL was found and parsed.
1553  *      - -1 if at least one URL was found, but none could be parsed.
1554  */
1555 static int ocsp_parse_cert_url(X509 *cert, char **host_out, char **port_out,
1556                                char **path_out, int *is_https)
1557 {
1558         int                     i;
1559         bool                    found_uri = false;
1560
1561         AUTHORITY_INFO_ACCESS   *aia;
1562         ACCESS_DESCRIPTION      *ad;
1563
1564         aia = X509_get_ext_d2i(cert, NID_info_access, NULL, NULL);
1565
1566         for (i = 0; i < sk_ACCESS_DESCRIPTION_num(aia); i++) {
1567                 ad = sk_ACCESS_DESCRIPTION_value(aia, i);
1568                 if (OBJ_obj2nid(ad->method) != NID_ad_OCSP) continue;
1569                 if (ad->location->type != GEN_URI) continue;
1570                 found_uri = true;
1571
1572                 if (OCSP_parse_url((char *) ad->location->d.ia5->data, host_out,
1573                                    port_out, path_out, is_https)) return 1;
1574         }
1575         return found_uri ? -1 : 0;
1576 }
1577
1578 /*
1579  * This function sends a OCSP request to a defined OCSP responder
1580  * and checks the OCSP response for correctness.
1581  */
1582
1583 /* Maximum leeway in validity period: default 5 minutes */
1584 #define MAX_VALIDITY_PERIOD     (5 * 60)
1585
1586 typedef enum {
1587         OCSP_STATUS_FAILED      = 0,
1588         OCSP_STATUS_OK          = 1,
1589         OCSP_STATUS_SKIPPED     = 2,
1590 } ocsp_status_t;
1591
1592 static ocsp_status_t ocsp_check(REQUEST *request, X509_STORE *store, X509 *issuer_cert, X509 *client_cert,
1593                                 fr_tls_server_conf_t *conf)
1594 {
1595         OCSP_CERTID     *certid;
1596         OCSP_REQUEST    *req;
1597         OCSP_RESPONSE   *resp = NULL;
1598         OCSP_BASICRESP  *bresp = NULL;
1599         char            *host = NULL;
1600         char            *port = NULL;
1601         char            *path = NULL;
1602         char            hostheader[1024];
1603         int             use_ssl = -1;
1604         long            nsec = MAX_VALIDITY_PERIOD, maxage = -1;
1605         BIO             *cbio, *bio_out;
1606         ocsp_status_t   ocsp_status = OCSP_STATUS_FAILED;
1607         int             status;
1608         ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
1609         int             reason;
1610 #if OPENSSL_VERSION_NUMBER >= 0x1000003f
1611         OCSP_REQ_CTX    *ctx;
1612         int             rc;
1613         struct timeval  now;
1614         struct timeval  when;
1615 #endif
1616         VALUE_PAIR      *vp;
1617
1618         /*
1619          * Create OCSP Request
1620          */
1621         certid = OCSP_cert_to_id(NULL, client_cert, issuer_cert);
1622         req = OCSP_REQUEST_new();
1623         OCSP_request_add0_id(req, certid);
1624         if (conf->ocsp_use_nonce) OCSP_request_add1_nonce(req, NULL, 8);
1625
1626         /*
1627          * Send OCSP Request and get OCSP Response
1628          */
1629
1630         /* Get OCSP responder URL */
1631         if (conf->ocsp_override_url) {
1632                 char *url;
1633
1634         use_ocsp_url:
1635                 memcpy(&url, &conf->ocsp_url, sizeof(url));
1636                 /* Reading the libssl src, they do a strdup on the URL, so it could of been const *sigh* */
1637                 OCSP_parse_url(url, &host, &port, &path, &use_ssl);
1638                 if (!host || !port || !path) {
1639                         RWDEBUG("ocsp: Host or port or path missing from configured URL \"%s\".  Not doing OCSP", url);
1640                         goto skipped;
1641                 }
1642         } else {
1643                 int ret;
1644
1645                 ret = ocsp_parse_cert_url(client_cert, &host, &port, &path, &use_ssl);
1646                 switch (ret) {
1647                 case -1:
1648                         RWDEBUG("ocsp: Invalid URL in certificate.  Not doing OCSP");
1649                         break;
1650
1651                 case 0:
1652                         if (conf->ocsp_url) {
1653                                 RWDEBUG("ocsp: No OCSP URL in certificate, falling back to configured URL");
1654                                 goto use_ocsp_url;
1655                         }
1656                         RWDEBUG("ocsp: No OCSP URL in certificate.  Not doing OCSP");
1657                         goto skipped;
1658
1659                 case 1:
1660                         break;
1661                 }
1662         }
1663
1664         RDEBUG2("ocsp: Using responder URL \"http://%s:%s%s\"", host, port, path);
1665
1666         /* Check host and port length are sane, then create Host: HTTP header */
1667         if ((strlen(host) + strlen(port) + 2) > sizeof(hostheader)) {
1668                 RWDEBUG("ocsp: Host and port too long");
1669                 goto skipped;
1670         }
1671         snprintf(hostheader, sizeof(hostheader), "%s:%s", host, port);
1672
1673         /* Setup BIO socket to OCSP responder */
1674         cbio = BIO_new_connect(host);
1675
1676         bio_out = NULL;
1677         if (rad_debug_lvl) {
1678                 if (default_log.dst == L_DST_STDOUT) {
1679                         bio_out = BIO_new_fp(stdout, BIO_NOCLOSE);
1680                 } else if (default_log.dst == L_DST_STDERR) {
1681                         bio_out = BIO_new_fp(stderr, BIO_NOCLOSE);
1682                 }
1683         }
1684
1685         BIO_set_conn_port(cbio, port);
1686 #if OPENSSL_VERSION_NUMBER < 0x1000003f
1687         BIO_do_connect(cbio);
1688
1689         /* Send OCSP request and wait for response */
1690         resp = OCSP_sendreq_bio(cbio, path, req);
1691         if (!resp) {
1692                 REDEBUG("ocsp: Couldn't get OCSP response");
1693                 ocsp_status = OCSP_STATUS_SKIPPED;
1694                 goto ocsp_end;
1695         }
1696 #else
1697         if (conf->ocsp_timeout)
1698                 BIO_set_nbio(cbio, 1);
1699
1700         rc = BIO_do_connect(cbio);
1701         if ((rc <= 0) && ((!conf->ocsp_timeout) || !BIO_should_retry(cbio))) {
1702                 REDEBUG("ocsp: Couldn't connect to OCSP responder");
1703                 ocsp_status = OCSP_STATUS_SKIPPED;
1704                 goto ocsp_end;
1705         }
1706
1707         ctx = OCSP_sendreq_new(cbio, path, NULL, -1);
1708         if (!ctx) {
1709                 REDEBUG("ocsp: Couldn't create OCSP request");
1710                 ocsp_status = OCSP_STATUS_SKIPPED;
1711                 goto ocsp_end;
1712         }
1713
1714         if (!OCSP_REQ_CTX_add1_header(ctx, "Host", hostheader)) {
1715                 REDEBUG("ocsp: Couldn't set Host header");
1716                 ocsp_status = OCSP_STATUS_SKIPPED;
1717                 goto ocsp_end;
1718         }
1719
1720         if (!OCSP_REQ_CTX_set1_req(ctx, req)) {
1721                 REDEBUG("ocsp: Couldn't add data to OCSP request");
1722                 ocsp_status = OCSP_STATUS_SKIPPED;
1723                 goto ocsp_end;
1724         }
1725
1726         gettimeofday(&when, NULL);
1727         when.tv_sec += conf->ocsp_timeout;
1728
1729         do {
1730                 rc = OCSP_sendreq_nbio(&resp, ctx);
1731                 if (conf->ocsp_timeout) {
1732                         gettimeofday(&now, NULL);
1733                         if (!timercmp(&now, &when, <))
1734                                 break;
1735                 }
1736         } while ((rc == -1) && BIO_should_retry(cbio));
1737
1738         if (conf->ocsp_timeout && (rc == -1) && BIO_should_retry(cbio)) {
1739                 REDEBUG("ocsp: Response timed out");
1740                 ocsp_status = OCSP_STATUS_SKIPPED;
1741                 goto ocsp_end;
1742         }
1743
1744         OCSP_REQ_CTX_free(ctx);
1745
1746         if (rc == 0) {
1747                 REDEBUG("ocsp: Couldn't get OCSP response");
1748                 ocsp_status = OCSP_STATUS_SKIPPED;
1749                 goto ocsp_end;
1750         }
1751 #endif
1752
1753         /* Verify OCSP response status */
1754         status = OCSP_response_status(resp);
1755         if (status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
1756                 REDEBUG("ocsp: Response status: %s", OCSP_response_status_str(status));
1757                 goto ocsp_end;
1758         }
1759         bresp = OCSP_response_get1_basic(resp);
1760         if (conf->ocsp_use_nonce && OCSP_check_nonce(req, bresp)!=1) {
1761                 REDEBUG("ocsp: Response has wrong nonce value");
1762                 goto ocsp_end;
1763         }
1764         if (OCSP_basic_verify(bresp, NULL, store, 0)!=1){
1765                 REDEBUG("ocsp: Couldn't verify OCSP basic response");
1766                 goto ocsp_end;
1767         }
1768
1769         /*      Verify OCSP cert status */
1770         if (!OCSP_resp_find_status(bresp, certid, &status, &reason, &rev, &thisupd, &nextupd)) {
1771                 REDEBUG("ocsp: No Status found");
1772                 goto ocsp_end;
1773         }
1774
1775         if (!OCSP_check_validity(thisupd, nextupd, nsec, maxage)) {
1776                 if (bio_out) {
1777                         BIO_puts(bio_out, "WARNING: Status times invalid.\n");
1778                         ERR_print_errors(bio_out);
1779                 }
1780                 goto ocsp_end;
1781         }
1782
1783         if (bio_out) {
1784                 BIO_puts(bio_out, "\tThis Update: ");
1785                 ASN1_GENERALIZEDTIME_print(bio_out, thisupd);
1786                 BIO_puts(bio_out, "\n");
1787                 if (nextupd) {
1788                         BIO_puts(bio_out, "\tNext Update: ");
1789                         ASN1_GENERALIZEDTIME_print(bio_out, nextupd);
1790                         BIO_puts(bio_out, "\n");
1791                 }
1792         }
1793
1794         switch (status) {
1795         case V_OCSP_CERTSTATUS_GOOD:
1796                 RDEBUG2("ocsp: Cert status: good");
1797                 vp = pair_make_request("TLS-OCSP-Cert-Valid", NULL, T_OP_SET);
1798                 vp->vp_integer = 1;     /* yes */
1799                 ocsp_status = OCSP_STATUS_OK;
1800                 break;
1801
1802         default:
1803                 /* REVOKED / UNKNOWN */
1804                 REDEBUG("ocsp: Cert status: %s", OCSP_cert_status_str(status));
1805                 if (reason != -1) REDEBUG("ocsp: Reason: %s", OCSP_crl_reason_str(reason));
1806
1807                 if (bio_out) {
1808                         BIO_puts(bio_out, "\tRevocation Time: ");
1809                         ASN1_GENERALIZEDTIME_print(bio_out, rev);
1810                         BIO_puts(bio_out, "\n");
1811                 }
1812                 break;
1813         }
1814
1815 ocsp_end:
1816         /* Free OCSP Stuff */
1817         OCSP_REQUEST_free(req);
1818         OCSP_RESPONSE_free(resp);
1819         free(host);
1820         free(port);
1821         free(path);
1822         BIO_free_all(cbio);
1823         if (bio_out) BIO_free(bio_out);
1824         OCSP_BASICRESP_free(bresp);
1825
1826         switch (ocsp_status) {
1827         case OCSP_STATUS_OK:
1828                 RDEBUG2("ocsp: Certificate is valid");
1829                 break;
1830
1831         case OCSP_STATUS_SKIPPED:
1832         skipped:
1833                 vp = pair_make_request("TLS-OCSP-Cert-Valid", NULL, T_OP_SET);
1834                 vp->vp_integer = 2;     /* skipped */
1835                 if (conf->ocsp_softfail) {
1836                         RWDEBUG("ocsp: Unable to check certificate, assuming it's valid");
1837                         RWDEBUG("ocsp: This may be insecure");
1838
1839                         /* Remove OpenSSL errors from queue or handshake will fail */
1840                         while (ERR_get_error());
1841
1842                         ocsp_status = OCSP_STATUS_SKIPPED;
1843                 } else {
1844                         REDEBUG("ocsp: Unable to check certificate, failing");
1845                         ocsp_status = OCSP_STATUS_FAILED;
1846                 }
1847                 break;
1848
1849         default:
1850                 vp = pair_make_request("TLS-OCSP-Cert-Valid", NULL, T_OP_SET);
1851                 vp->vp_integer = 0;     /* no */
1852                 REDEBUG("ocsp: Certificate has been expired/revoked");
1853                 break;
1854         }
1855
1856         return ocsp_status;
1857 }
1858 #endif  /* HAVE_OPENSSL_OCSP_H */
1859
1860 /*
1861  *      For creating certificate attributes.
1862  */
1863 static char const *cert_attr_names[8][2] = {
1864         { "TLS-Client-Cert-Serial",                     "TLS-Cert-Serial" },
1865         { "TLS-Client-Cert-Expiration",                 "TLS-Cert-Expiration" },
1866         { "TLS-Client-Cert-Subject",                    "TLS-Cert-Subject" },
1867         { "TLS-Client-Cert-Issuer",                     "TLS-Cert-Issuer" },
1868         { "TLS-Client-Cert-Common-Name",                "TLS-Cert-Common-Name" },
1869         { "TLS-Client-Cert-Subject-Alt-Name-Email",     "TLS-Cert-Subject-Alt-Name-Email" },
1870         { "TLS-Client-Cert-Subject-Alt-Name-Dns",       "TLS-Cert-Subject-Alt-Name-Dns" },
1871         { "TLS-Client-Cert-Subject-Alt-Name-Upn",       "TLS-Cert-Subject-Alt-Name-Upn" }
1872 };
1873
1874 #define FR_TLS_SERIAL           (0)
1875 #define FR_TLS_EXPIRATION       (1)
1876 #define FR_TLS_SUBJECT          (2)
1877 #define FR_TLS_ISSUER           (3)
1878 #define FR_TLS_CN               (4)
1879 #define FR_TLS_SAN_EMAIL        (5)
1880 #define FR_TLS_SAN_DNS          (6)
1881 #define FR_TLS_SAN_UPN          (7)
1882
1883 /*
1884  *      Before trusting a certificate, you must make sure that the
1885  *      certificate is 'valid'. There are several steps that your
1886  *      application can take in determining if a certificate is
1887  *      valid. Commonly used steps are:
1888  *
1889  *      1.Verifying the certificate's signature, and verifying that
1890  *      the certificate has been issued by a trusted Certificate
1891  *      Authority.
1892  *
1893  *      2.Verifying that the certificate is valid for the present date
1894  *      (i.e. it is being presented within its validity dates).
1895  *
1896  *      3.Verifying that the certificate has not been revoked by its
1897  *      issuing Certificate Authority, by checking with respect to a
1898  *      Certificate Revocation List (CRL).
1899  *
1900  *      4.Verifying that the credentials presented by the certificate
1901  *      fulfill additional requirements specific to the application,
1902  *      such as with respect to access control lists or with respect
1903  *      to OCSP (Online Certificate Status Processing).
1904  *
1905  *      NOTE: This callback will be called multiple times based on the
1906  *      depth of the root certificate chain
1907  */
1908 int cbtls_verify(int ok, X509_STORE_CTX *ctx)
1909 {
1910         char            subject[1024]; /* Used for the subject name */
1911         char            issuer[1024]; /* Used for the issuer name */
1912         char            attribute[1024];
1913         char            value[1024];
1914         char            common_name[1024];
1915         char            cn_str[1024];
1916         char            buf[64];
1917         X509            *client_cert;
1918 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
1919         const STACK_OF(X509_EXTENSION) *ext_list;
1920 #else
1921         STACK_OF(X509_EXTENSION) *ext_list;
1922 #endif
1923         SSL             *ssl;
1924         int             err, depth, lookup, loc;
1925         fr_tls_server_conf_t *conf;
1926         int             my_ok = ok;
1927
1928         ASN1_INTEGER    *sn = NULL;
1929         ASN1_TIME       *asn_time = NULL;
1930         VALUE_PAIR      **certs;
1931         char **identity;
1932 #ifdef HAVE_OPENSSL_OCSP_H
1933         X509_STORE      *ocsp_store = NULL;
1934         X509            *issuer_cert;
1935         bool            do_verify = false;
1936 #endif
1937         VALUE_PAIR      *vp;
1938         TALLOC_CTX      *talloc_ctx;
1939
1940         REQUEST         *request;
1941
1942         client_cert = X509_STORE_CTX_get_current_cert(ctx);
1943         err = X509_STORE_CTX_get_error(ctx);
1944         depth = X509_STORE_CTX_get_error_depth(ctx);
1945
1946         lookup = depth;
1947
1948         /*
1949          *      Log client/issuing cert.  If there's an error, log
1950          *      issuing cert.
1951          */
1952         if ((lookup > 1) && !my_ok) lookup = 1;
1953
1954         /*
1955          * Retrieve the pointer to the SSL of the connection currently treated
1956          * and the application specific data stored into the SSL object.
1957          */
1958         ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
1959         conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1960         if (!conf) return 1;
1961
1962         request = (REQUEST *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_REQUEST);
1963         rad_assert(request != NULL);
1964         certs = (VALUE_PAIR **)SSL_get_ex_data(ssl, fr_tls_ex_index_certs);
1965
1966         identity = (char **)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_IDENTITY);
1967 #ifdef HAVE_OPENSSL_OCSP_H
1968         ocsp_store = conf->ocsp_store;
1969 #endif
1970
1971         talloc_ctx = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_TALLOC);
1972
1973         /*
1974          *      Get the Serial Number
1975          */
1976         buf[0] = '\0';
1977         sn = X509_get_serialNumber(client_cert);
1978
1979         RDEBUG2("Creating attributes from certificate OIDs");
1980         RINDENT();
1981
1982         /*
1983          *      For this next bit, we create the attributes *only* if
1984          *      we're at the client or issuing certificate, AND we
1985          *      have a user identity.  i.e. we don't create the
1986          *      attributes for RadSec connections.
1987          */
1988         if (certs && identity &&
1989             (lookup <= 1) && sn && ((size_t) sn->length < (sizeof(buf) / 2))) {
1990                 char *p = buf;
1991                 int i;
1992
1993                 for (i = 0; i < sn->length; i++) {
1994                         sprintf(p, "%02x", (unsigned int)sn->data[i]);
1995                         p += 2;
1996                 }
1997                 vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_SERIAL][lookup], buf, T_OP_SET);
1998                 rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
1999         }
2000
2001
2002         /*
2003          *      Get the Expiration Date
2004          */
2005         buf[0] = '\0';
2006         asn_time = X509_get_notAfter(client_cert);
2007         if (certs && identity && (lookup <= 1) && asn_time &&
2008             (asn_time->length < (int) sizeof(buf))) {
2009                 memcpy(buf, (char*) asn_time->data, asn_time->length);
2010                 buf[asn_time->length] = '\0';
2011                 vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_EXPIRATION][lookup], buf, T_OP_SET);
2012                 rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
2013         }
2014
2015         /*
2016          *      Get the Subject & Issuer
2017          */
2018         subject[0] = issuer[0] = '\0';
2019         X509_NAME_oneline(X509_get_subject_name(client_cert), subject,
2020                           sizeof(subject));
2021         subject[sizeof(subject) - 1] = '\0';
2022         if (certs && identity && (lookup <= 1) && subject[0]) {
2023                 vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_SUBJECT][lookup], subject, T_OP_SET);
2024                 rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
2025         }
2026
2027         X509_NAME_oneline(X509_get_issuer_name(client_cert), issuer,
2028                           sizeof(issuer));
2029         issuer[sizeof(issuer) - 1] = '\0';
2030         if (certs && identity && (lookup <= 1) && issuer[0]) {
2031                 vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_ISSUER][lookup], issuer, T_OP_SET);
2032                 rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
2033         }
2034
2035         /*
2036          *      Get the Common Name, if there is a subject.
2037          */
2038         X509_NAME_get_text_by_NID(X509_get_subject_name(client_cert),
2039                                   NID_commonName, common_name, sizeof(common_name));
2040         common_name[sizeof(common_name) - 1] = '\0';
2041         if (certs && identity && (lookup <= 1) && common_name[0] && subject[0]) {
2042                 vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_CN][lookup], common_name, T_OP_SET);
2043                 rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
2044         }
2045
2046         /*
2047          *      Get the RFC822 Subject Alternative Name
2048          */
2049         loc = X509_get_ext_by_NID(client_cert, NID_subject_alt_name, 0);
2050         if (certs && (lookup <= 1) && (loc >= 0)) {
2051                 X509_EXTENSION *ext = NULL;
2052                 GENERAL_NAMES *names = NULL;
2053                 int i;
2054
2055                 if ((ext = X509_get_ext(client_cert, loc)) &&
2056                     (names = X509V3_EXT_d2i(ext))) {
2057                         for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
2058                                 GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
2059
2060                                 switch (name->type) {
2061 #ifdef GEN_EMAIL
2062                                 case GEN_EMAIL:
2063                                         vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_SAN_EMAIL][lookup],
2064                                                       (char const *) ASN1_STRING_get0_data(name->d.rfc822Name), T_OP_SET);
2065                                         rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
2066                                         break;
2067 #endif  /* GEN_EMAIL */
2068 #ifdef GEN_DNS
2069                                 case GEN_DNS:
2070                                         vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_SAN_DNS][lookup],
2071                                                       (char const *) ASN1_STRING_get0_data(name->d.dNSName), T_OP_SET);
2072                                         rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
2073                                         break;
2074 #endif  /* GEN_DNS */
2075 #ifdef GEN_OTHERNAME
2076                                 case GEN_OTHERNAME:
2077                                         /* look for a MS UPN */
2078                                         if (NID_ms_upn == OBJ_obj2nid(name->d.otherName->type_id)) {
2079                                             /* we've got a UPN - Must be ASN1-encoded UTF8 string */
2080                                             if (name->d.otherName->value->type == V_ASN1_UTF8STRING) {
2081                                                     vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_SAN_UPN][lookup],
2082                                                                   (char const *) ASN1_STRING_get0_data(name->d.otherName->value->value.utf8string), T_OP_SET);
2083                                                     rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
2084                                                 break;
2085                                             } else {
2086                                                 RWARN("Invalid UPN in Subject Alt Name (should be UTF-8)");
2087                                                 break;
2088                                             }
2089                                         }
2090                                         break;
2091 #endif  /* GEN_OTHERNAME */
2092                                 default:
2093                                         /* XXX TODO handle other SAN types */
2094                                         break;
2095                                 }
2096                         }
2097                 }
2098                 if (names != NULL)
2099                         sk_GENERAL_NAME_free(names);
2100         }
2101
2102         /*
2103          *      If the CRL has expired, that might still be OK.
2104          */
2105         if (!my_ok &&
2106             (conf->allow_expired_crl) &&
2107             (err == X509_V_ERR_CRL_HAS_EXPIRED)) {
2108                 my_ok = 1;
2109                 X509_STORE_CTX_set_error( ctx, 0 );
2110         }
2111
2112         if (!my_ok) {
2113                 char const *p = X509_verify_cert_error_string(err);
2114                 RERROR("SSL says error %d : %s", err, p);
2115                 REXDENT();
2116                 return my_ok;
2117         }
2118
2119         if (lookup == 0) {
2120 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
2121                 ext_list = X509_get0_extensions(client_cert);
2122 #else
2123                 X509_CINF       *client_inf;
2124                 client_inf = client_cert->cert_info;
2125                 ext_list = client_inf->extensions;
2126 #endif
2127         } else {
2128                 ext_list = NULL;
2129         }
2130
2131         /*
2132          *      Grab the X509 extensions, and create attributes out of them.
2133          *      For laziness, we re-use the OpenSSL names
2134          */
2135         if (certs && (sk_X509_EXTENSION_num(ext_list) > 0)) {
2136                 int i, len;
2137                 char *p;
2138                 BIO *out;
2139
2140                 out = BIO_new(BIO_s_mem());
2141                 strlcpy(attribute, "TLS-Client-Cert-", sizeof(attribute));
2142
2143                 for (i = 0; i < sk_X509_EXTENSION_num(ext_list); i++) {
2144                         ASN1_OBJECT *obj;
2145                         X509_EXTENSION *ext;
2146
2147                         ext = sk_X509_EXTENSION_value(ext_list, i);
2148
2149                         obj = X509_EXTENSION_get_object(ext);
2150                         i2a_ASN1_OBJECT(out, obj);
2151                         len = BIO_read(out, attribute + 16 , sizeof(attribute) - 16 - 1);
2152                         if (len <= 0) continue;
2153
2154                         attribute[16 + len] = '\0';
2155
2156                         for (p = attribute + 16; *p != '\0'; p++) {
2157                                 if (*p == ' ') *p = '-';
2158                         }
2159
2160                         X509V3_EXT_print(out, ext, 0, 0);
2161                         len = BIO_read(out, value , sizeof(value) - 1);
2162                         if (len <= 0) continue;
2163
2164                         value[len] = '\0';
2165
2166                         vp = fr_pair_make(talloc_ctx, certs, attribute, value, T_OP_ADD);
2167                         if (!vp) {
2168                                 RDEBUG3("Skipping %s += '%s'.  Please check that both the "
2169                                         "attribute and value are defined in the dictionaries",
2170                                         attribute, value);
2171                         } else {
2172                                 /*
2173                                  *      rdebug_pair_list indents (so pre REXDENT())
2174                                  */
2175                                 REXDENT();
2176                                 rdebug_pair_list(L_DBG_LVL_2, request, vp, NULL);
2177                                 RINDENT();
2178                         }
2179                 }
2180
2181                 BIO_free_all(out);
2182         }
2183
2184         REXDENT();
2185
2186         switch (X509_STORE_CTX_get_error(ctx)) {
2187         case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
2188                 RERROR("issuer=%s", issuer);
2189                 break;
2190
2191         case X509_V_ERR_CERT_NOT_YET_VALID:
2192         case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
2193                 RERROR("notBefore=");
2194 #if 0
2195                 ASN1_TIME_print(bio_err, X509_get_notBefore(ctx->current_cert));
2196 #endif
2197                 break;
2198
2199         case X509_V_ERR_CERT_HAS_EXPIRED:
2200         case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
2201                 RERROR("notAfter=");
2202 #if 0
2203                 ASN1_TIME_print(bio_err, X509_get_notAfter(ctx->current_cert));
2204 #endif
2205                 break;
2206         }
2207
2208         /*
2209          *      If we're at the actual client cert, apply additional
2210          *      checks.
2211          */
2212         if (depth == 0) {
2213                 /*
2214                  *      If the conf tells us to, check cert issuer
2215                  *      against the specified value and fail
2216                  *      verification if they don't match.
2217                  */
2218                 if (conf->check_cert_issuer &&
2219                     (strcmp(issuer, conf->check_cert_issuer) != 0)) {
2220                         AUTH(LOG_PREFIX ": Certificate issuer (%s) does not match specified value (%s)!",
2221                              issuer, conf->check_cert_issuer);
2222                         my_ok = 0;
2223                 }
2224
2225                 /*
2226                  *      If the conf tells us to, check the CN in the
2227                  *      cert against xlat'ed value, but only if the
2228                  *      previous checks passed.
2229                  */
2230                 if (my_ok && conf->check_cert_cn) {
2231                         if (radius_xlat(cn_str, sizeof(cn_str), request, conf->check_cert_cn, NULL, NULL) < 0) {
2232                                 /* if this fails, fail the verification */
2233                                 my_ok = 0;
2234                         } else {
2235                                 RDEBUG2("checking certificate CN (%s) with xlat'ed value (%s)", common_name, cn_str);
2236                                 if (strcmp(cn_str, common_name) != 0) {
2237                                         AUTH(LOG_PREFIX ": Certificate CN (%s) does not match specified value (%s)!",
2238                                              common_name, cn_str);
2239                                         my_ok = 0;
2240                                 }
2241                         }
2242                 } /* check_cert_cn */
2243
2244 #ifdef HAVE_OPENSSL_OCSP_H
2245                 if (my_ok) {
2246                         /*
2247                          *      No OCSP, allow external verification.
2248                          */
2249                         if (!conf->ocsp_enable) {
2250                                 do_verify = true;
2251
2252                         } else {
2253                                 RDEBUG2("Starting OCSP Request");
2254                                 if ((X509_STORE_CTX_get1_issuer(&issuer_cert, ctx, client_cert) != 1) ||
2255                                     !issuer_cert) {
2256                                         /*
2257                                          *      Allow for external verify.
2258                                          */
2259                                         RERROR("Couldn't get issuer_cert for %s", common_name);
2260                                         do_verify = true;
2261
2262                                 } else {
2263                                         /*
2264                                          *      Do the full OCSP checks.
2265                                          *
2266                                          *      If they fail, don't run the external verify.  We don't want
2267                                          *      to allow admins to force authentication success for bad
2268                                          *      certificates.
2269                                          *
2270                                          *      If the OCSP checks succeed, check whether we still want to
2271                                          *      run the external verification routine.  If it's marked as
2272                                          *      "skip verify on OK", then we don't do verify.
2273                                          */
2274                                         my_ok = ocsp_check(request, ocsp_store, issuer_cert, client_cert, conf);
2275                                         if (my_ok != OCSP_STATUS_FAILED) {
2276                                                 do_verify = !conf->verify_skip_if_ocsp_ok;
2277                                         }
2278                                 }
2279                         }
2280                 }
2281 #endif
2282
2283                 if ((my_ok != OCSP_STATUS_FAILED)
2284 #ifdef HAVE_OPENSSL_OCSP_H
2285                     && do_verify
2286 #endif
2287                         ) while (conf->verify_client_cert_cmd) {
2288                         char filename[256];
2289                         int fd;
2290                         FILE *fp;
2291
2292                         snprintf(filename, sizeof(filename), "%s/%s.client.XXXXXXXX",
2293                                  conf->verify_tmp_dir, main_config.name);
2294                         fd = mkstemp(filename);
2295                         if (fd < 0) {
2296                                 RDEBUG("Failed creating file in %s: %s",
2297                                        conf->verify_tmp_dir, fr_syserror(errno));
2298                                 break;
2299                         }
2300
2301                         fp = fdopen(fd, "w");
2302                         if (!fp) {
2303                                 close(fd);
2304                                 RDEBUG("Failed opening file %s: %s",
2305                                        filename, fr_syserror(errno));
2306                                 break;
2307                         }
2308
2309                         if (!PEM_write_X509(fp, client_cert)) {
2310                                 fclose(fp);
2311                                 RDEBUG("Failed writing certificate to file");
2312                                 goto do_unlink;
2313                         }
2314                         fclose(fp);
2315
2316                         if (!pair_make_request("TLS-Client-Cert-Filename",
2317                                              filename, T_OP_SET)) {
2318                                 RDEBUG("Failed creating TLS-Client-Cert-Filename");
2319
2320                                 goto do_unlink;
2321                         }
2322
2323                         RDEBUG("Verifying client certificate: %s", conf->verify_client_cert_cmd);
2324                         if (radius_exec_program(request, NULL, 0, NULL, request, conf->verify_client_cert_cmd,
2325                                                 request->packet->vps,
2326                                                 true, true, EXEC_TIMEOUT) != 0) {
2327                                 AUTH(LOG_PREFIX ": Certificate CN (%s) fails external verification!", common_name);
2328                                 my_ok = 0;
2329                         } else {
2330                                 RDEBUG("Client certificate CN %s passed external validation", common_name);
2331                         }
2332
2333                 do_unlink:
2334                         unlink(filename);
2335                         break;
2336                 }
2337         } /* depth == 0 */
2338
2339         if (certs && request && !my_ok) {
2340                 fr_pair_add(&request->packet->vps, fr_pair_list_copy(request->packet, *certs));
2341         }
2342
2343         if (RDEBUG_ENABLED3) {
2344                 RDEBUG3("chain-depth   : %d", depth);
2345                 RDEBUG3("error         : %d", err);
2346
2347                 if (identity) RDEBUG3("identity      : %s", *identity);
2348                 RDEBUG3("common name   : %s", common_name);
2349                 RDEBUG3("subject       : %s", subject);
2350                 RDEBUG3("issuer        : %s", issuer);
2351                 RDEBUG3("verify return : %d", my_ok);
2352         }
2353
2354         return (my_ok != 0);
2355 }
2356
2357
2358 #ifdef HAVE_OPENSSL_OCSP_H
2359 /*
2360  *      Create Global X509 revocation store and use it to verify
2361  *      OCSP responses
2362  *
2363  *      - Load the trusted CAs
2364  *      - Load the trusted issuer certificates
2365  */
2366 static X509_STORE *init_revocation_store(fr_tls_server_conf_t *conf)
2367 {
2368         X509_STORE *store = NULL;
2369
2370         store = X509_STORE_new();
2371
2372         /* Load the CAs we trust */
2373         if (conf->ca_file || conf->ca_path)
2374                 if (!X509_STORE_load_locations(store, conf->ca_file, conf->ca_path)) {
2375                         tls_error_log(NULL, "Error reading Trusted root CA list \"%s\"", conf->ca_file);
2376                         return NULL;
2377                 }
2378
2379 #ifdef X509_V_FLAG_CRL_CHECK
2380         if (conf->check_crl)
2381                 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK);
2382 #endif
2383 #ifdef X509_V_FLAG_CRL_CHECK_ALL
2384         if (conf->check_all_crl)
2385                 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK_ALL);
2386 #endif
2387         return store;
2388 }
2389 #endif  /* HAVE_OPENSSL_OCSP_H */
2390
2391 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
2392 #ifndef OPENSSL_NO_ECDH
2393 static int set_ecdh_curve(SSL_CTX *ctx, char const *ecdh_curve, bool disable_single_dh_use)
2394 {
2395         int      nid;
2396         EC_KEY  *ecdh;
2397
2398         if (!ecdh_curve || !*ecdh_curve) return 0;
2399
2400         nid = OBJ_sn2nid(ecdh_curve);
2401         if (!nid) {
2402                 ERROR(LOG_PREFIX ": Unknown ecdh_curve \"%s\"", ecdh_curve);
2403                 return -1;
2404         }
2405
2406         ecdh = EC_KEY_new_by_curve_name(nid);
2407         if (!ecdh) {
2408                 ERROR(LOG_PREFIX ": Unable to create new curve \"%s\"", ecdh_curve);
2409                 return -1;
2410         }
2411
2412         SSL_CTX_set_tmp_ecdh(ctx, ecdh);
2413
2414         if (!disable_single_dh_use) {
2415                 SSL_CTX_set_options(ctx, SSL_OP_SINGLE_ECDH_USE);
2416         }
2417
2418         EC_KEY_free(ecdh);
2419
2420         return 0;
2421 }
2422 #endif
2423 #endif
2424
2425 /*
2426  * DIE OPENSSL DIE DIE DIE
2427  *
2428  * What a palaver, just to free some data attached the
2429  * session. We need to do this because the "remove" callback
2430  * is called when refcount > 0 sometimes, if another thread
2431  * is using the session
2432  */
2433 static void sess_free_vps(UNUSED void *parent, void *data_ptr,
2434                                 UNUSED CRYPTO_EX_DATA *ad, UNUSED int idx,
2435                                 UNUSED long argl, UNUSED void *argp)
2436 {
2437         VALUE_PAIR *vp = data_ptr;
2438         if (!vp) return;
2439
2440         DEBUG2(LOG_PREFIX ": Freeing cached session VPs");
2441
2442         fr_pair_list_free(&vp);
2443 }
2444
2445 static void sess_free_certs(UNUSED void *parent, void *data_ptr,
2446                                 UNUSED CRYPTO_EX_DATA *ad, UNUSED int idx,
2447                                 UNUSED long argl, UNUSED void *argp)
2448 {
2449         VALUE_PAIR **certs = data_ptr;
2450         if (!certs) return;
2451
2452         DEBUG2(LOG_PREFIX ": Freeing cached session Certificates");
2453
2454         fr_pair_list_free(certs);
2455 }
2456
2457 /** Add all the default ciphers and message digests reate our context.
2458  *
2459  * This should be called exactly once from main, before reading the main config
2460  * or initialising any modules.
2461  */
2462 void tls_global_init(void)
2463 {
2464         SSL_load_error_strings();       /* readable error messages (examples show call before library_init) */
2465         SSL_library_init();             /* initialize library */
2466         OpenSSL_add_all_algorithms();   /* required for SHA2 in OpenSSL < 0.9.8o and 1.0.0.a */
2467         CONF_modules_load_file(NULL, NULL, 0);
2468
2469         /*
2470          *      Initialize the index for the certificates.
2471          */
2472         fr_tls_ex_index_certs = SSL_SESSION_get_ex_new_index(0, NULL, NULL, NULL, sess_free_certs);
2473 }
2474
2475 #ifdef ENABLE_OPENSSL_VERSION_CHECK
2476 /** Check for vulnerable versions of libssl
2477  *
2478  * @param acknowledged The highest CVE number a user has confirmed is not present in the system's libssl.
2479  * @return 0 if the CVE specified by the user matches the most recent CVE we have, else -1.
2480  */
2481 int tls_global_version_check(char const *acknowledged)
2482 {
2483         uint64_t v;
2484         bool bad = false;
2485         size_t i;
2486
2487         if (strcmp(acknowledged, "yes") == 0) return 0;
2488
2489         /* Check for bad versions */
2490         v = (uint64_t) SSLeay();
2491
2492         for (i = 0; i < (sizeof(libssl_defects) / sizeof(*libssl_defects)); i++) {
2493                 libssl_defect_t *defect = &libssl_defects[i];
2494
2495                 if ((v >= defect->low) && (v <= defect->high)) {
2496                         /*
2497                          *      If the CVE is acknowledged, allow it.
2498                          */
2499                         if (!bad && (strcmp(acknowledged, defect->id) == 0)) return 0;
2500
2501                         ERROR("Refusing to start with libssl version %s (in range %s)",
2502                               ssl_version(), ssl_version_range(defect->low, defect->high));
2503                         ERROR("Security advisory %s (%s)", defect->id, defect->name);
2504                         ERROR("%s", defect->comment);
2505
2506                         /*
2507                          *      Only warn about the first one...
2508                          */
2509                         if (!bad) {
2510                                 INFO("Once you have verified libssl has been correctly patched, "
2511                                      "set security.allow_vulnerable_openssl = '%s'", defect->id);
2512
2513                                 bad = true;
2514                         }
2515                 }
2516         }
2517
2518         if (bad) return -1;
2519
2520         return 0;
2521 }
2522 #endif
2523
2524 /** Free any memory alloced by libssl
2525  *
2526  */
2527 void tls_global_cleanup(void)
2528 {
2529 #if OPENSSL_VERSION_NUMBER < 0x10000000L
2530         ERR_remove_state(0);
2531 #elif OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
2532         ERR_remove_thread_state(NULL);
2533 #endif
2534         ENGINE_cleanup();
2535         CONF_modules_unload(1);
2536         ERR_free_strings();
2537         EVP_cleanup();
2538         CRYPTO_cleanup_all_ex_data();
2539 }
2540
2541 /** Create SSL context
2542  *
2543  * - Load the trusted CAs
2544  * - Load the Private key & the certificate
2545  * - Set the Context options & Verify options
2546  */
2547 SSL_CTX *tls_init_ctx(fr_tls_server_conf_t *conf, int client)
2548 {
2549         SSL_CTX         *ctx;
2550         X509_STORE      *certstore;
2551         int             verify_mode = SSL_VERIFY_NONE;
2552         int             ctx_options = 0;
2553         int             ctx_tls_versions = 0;
2554         int             type;
2555
2556         /*
2557          *      SHA256 is in all versions of OpenSSL, but isn't
2558          *      initialized by default.  It's needed for WiMAX
2559          *      certificates.
2560          */
2561 #ifdef HAVE_OPENSSL_EVP_SHA256
2562         EVP_add_digest(EVP_sha256());
2563 #endif
2564
2565         ctx = SSL_CTX_new(SSLv23_method()); /* which is really "all known SSL / TLS methods".  Idiots. */
2566         if (!ctx) {
2567                 tls_error_log(NULL, "Failed creating TLS context");
2568                 return NULL;
2569         }
2570
2571         /*
2572          * Save the config on the context so that callbacks which
2573          * only get SSL_CTX* e.g. session persistence, can get it
2574          */
2575         SSL_CTX_set_app_data(ctx, conf);
2576
2577         /*
2578          * Identify the type of certificates that needs to be loaded
2579          */
2580         if (conf->file_type) {
2581                 type = SSL_FILETYPE_PEM;
2582         } else {
2583                 type = SSL_FILETYPE_ASN1;
2584         }
2585
2586         /*
2587          * Set the password to load private key
2588          */
2589         if (conf->private_key_password) {
2590 #ifdef __APPLE__
2591                 /*
2592                  * We don't want to put the private key password in eap.conf, so  check
2593                  * for our special string which indicates we should get the password
2594                  * programmatically.
2595                  */
2596                 char const* special_string = "Apple:UseCertAdmin";
2597                 if (strncmp(conf->private_key_password, special_string, strlen(special_string)) == 0) {
2598                         char cmd[256];
2599                         char *password;
2600                         long const max_password_len = 128;
2601                         snprintf(cmd, sizeof(cmd) - 1, "/usr/sbin/certadmin --get-private-key-passphrase \"%s\"",
2602                                  conf->private_key_file);
2603
2604                         DEBUG2(LOG_PREFIX ":  Getting private key passphrase using command \"%s\"", cmd);
2605
2606                         FILE* cmd_pipe = popen(cmd, "r");
2607                         if (!cmd_pipe) {
2608                                 ERROR(LOG_PREFIX ": %s command failed: Unable to get private_key_password", cmd);
2609                                 ERROR(LOG_PREFIX ": Error reading private_key_file %s", conf->private_key_file);
2610                                 return NULL;
2611                         }
2612
2613                         rad_const_free(conf->private_key_password);
2614                         password = talloc_array(conf, char, max_password_len);
2615                         if (!password) {
2616                                 ERROR(LOG_PREFIX ": Can't allocate space for private_key_password");
2617                                 ERROR(LOG_PREFIX ": Error reading private_key_file %s", conf->private_key_file);
2618                                 pclose(cmd_pipe);
2619                                 return NULL;
2620                         }
2621
2622                         fgets(password, max_password_len, cmd_pipe);
2623                         pclose(cmd_pipe);
2624
2625                         /* Get rid of newline at end of password. */
2626                         password[strlen(password) - 1] = '\0';
2627
2628                         DEBUG3(LOG_PREFIX ": Password from command = \"%s\"", password);
2629                         conf->private_key_password = password;
2630                 }
2631 #endif
2632
2633                 {
2634                         char *password;
2635
2636                         memcpy(&password, &conf->private_key_password, sizeof(password));
2637                         SSL_CTX_set_default_passwd_cb_userdata(ctx, password);
2638                         SSL_CTX_set_default_passwd_cb(ctx, cbtls_password);
2639                 }
2640         }
2641
2642 #ifdef PSK_MAX_IDENTITY_LEN
2643         if (!client) {
2644                 /*
2645                  *      No dynamic query exists.  There MUST be a
2646                  *      statically configured identity and password.
2647                  */
2648                 if (conf->psk_query && !*conf->psk_query) {
2649                         ERROR(LOG_PREFIX ": Invalid PSK Configuration: psk_query cannot be empty");
2650                         return NULL;
2651                 }
2652
2653                 /*
2654                  *      Set the callback only if we can check things.
2655                  */
2656                 if (conf->psk_identity || conf->psk_query) {
2657                         SSL_CTX_set_psk_server_callback(ctx, psk_server_callback);
2658                 }
2659
2660         } else if (conf->psk_query) {
2661                 ERROR(LOG_PREFIX ": Invalid PSK Configuration: psk_query cannot be used for outgoing connections");
2662                 return NULL;
2663         }
2664
2665         /*
2666          *      Now check that if PSK is being used, the config is valid.
2667          */
2668         if ((conf->psk_identity && !conf->psk_password) ||
2669             (!conf->psk_identity && conf->psk_password) ||
2670             (conf->psk_identity && !*conf->psk_identity) ||
2671             (conf->psk_password && !*conf->psk_password)) {
2672                 ERROR(LOG_PREFIX ": Invalid PSK Configuration: psk_identity or psk_password are empty");
2673                 return NULL;
2674         }
2675
2676         if (conf->psk_identity) {
2677                 size_t psk_len, hex_len;
2678                 uint8_t buffer[PSK_MAX_PSK_LEN];
2679
2680                 if (conf->certificate_file ||
2681                     conf->private_key_password || conf->private_key_file ||
2682                     conf->ca_file || conf->ca_path) {
2683                         ERROR(LOG_PREFIX ": When PSKs are used, No certificate configuration is permitted");
2684                         return NULL;
2685                 }
2686
2687                 if (client) {
2688                         SSL_CTX_set_psk_client_callback(ctx,
2689                                                         psk_client_callback);
2690                 }
2691
2692                 psk_len = strlen(conf->psk_password);
2693                 if (strlen(conf->psk_password) > (2 * PSK_MAX_PSK_LEN)) {
2694                         ERROR(LOG_PREFIX ": psk_hexphrase is too long (max %d)", PSK_MAX_PSK_LEN);
2695                         return NULL;
2696                 }
2697
2698                 /*
2699                  *      Check the password now, so that we don't have
2700                  *      errors at run-time.
2701                  */
2702                 hex_len = fr_hex2bin(buffer, sizeof(buffer), conf->psk_password, psk_len);
2703                 if (psk_len != (2 * hex_len)) {
2704                         ERROR(LOG_PREFIX ": psk_hexphrase is not all hex");
2705                         return NULL;
2706                 }
2707
2708                 goto post_ca;
2709         }
2710 #else
2711         (void) client;  /* -Wunused */
2712 #endif
2713
2714         /*
2715          *      Load our keys and certificates
2716          *
2717          *      If certificates are of type PEM then we can make use
2718          *      of cert chain authentication using openssl api call
2719          *      SSL_CTX_use_certificate_chain_file.  Please see how
2720          *      the cert chain needs to be given in PEM from
2721          *      openSSL.org
2722          */
2723         if (!conf->certificate_file) goto load_ca;
2724
2725         if (type == SSL_FILETYPE_PEM) {
2726                 if (!(SSL_CTX_use_certificate_chain_file(ctx, conf->certificate_file))) {
2727                         tls_error_log(NULL, "Failed reading certificate file \"%s\"",
2728                                       conf->certificate_file);
2729                         return NULL;
2730                 }
2731
2732         } else if (!(SSL_CTX_use_certificate_file(ctx, conf->certificate_file, type))) {
2733                 tls_error_log(NULL, "Failed reading certificate file \"%s\"",
2734                               conf->certificate_file);
2735                 return NULL;
2736         }
2737
2738         /* Load the CAs we trust */
2739 load_ca:
2740         if (conf->ca_file || conf->ca_path) {
2741                 if (!SSL_CTX_load_verify_locations(ctx, conf->ca_file, conf->ca_path)) {
2742                         tls_error_log(NULL, "Failed reading Trusted root CA list \"%s\"",
2743                                       conf->ca_file);
2744                         return NULL;
2745                 }
2746         }
2747         if (conf->ca_file && *conf->ca_file) SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(conf->ca_file));
2748
2749         if (conf->private_key_file) {
2750                 if (!(SSL_CTX_use_PrivateKey_file(ctx, conf->private_key_file, type))) {
2751                         tls_error_log(NULL, "Failed reading private key file \"%s\"",
2752                                       conf->private_key_file);
2753                         return NULL;
2754                 }
2755
2756                 /*
2757                  * Check if the loaded private key is the right one
2758                  */
2759                 if (!SSL_CTX_check_private_key(ctx)) {
2760                         ERROR(LOG_PREFIX ": Private key does not match the certificate public key");
2761                         return NULL;
2762                 }
2763         }
2764
2765 #ifdef PSK_MAX_IDENTITY_LEN
2766 post_ca:
2767 #endif
2768
2769         /*
2770          *      We never want SSLv2 or SSLv3.
2771          */
2772         ctx_options |= SSL_OP_NO_SSLv2;
2773         ctx_options |= SSL_OP_NO_SSLv3;
2774
2775         /*
2776          *      As of 3.0.5, we always allow TLSv1.1 and TLSv1.2.
2777          *      Though they can be *globally* disabled if necessary.x
2778          */
2779 #ifdef SSL_OP_NO_TLSv1
2780         if (conf->disable_tlsv1) ctx_options |= SSL_OP_NO_TLSv1;
2781
2782         ctx_tls_versions |= SSL_OP_NO_TLSv1;
2783 #endif
2784 #ifdef SSL_OP_NO_TLSv1_1
2785         if (conf->disable_tlsv1_1) ctx_options |= SSL_OP_NO_TLSv1_1;
2786
2787         ctx_tls_versions |= SSL_OP_NO_TLSv1_1;
2788 #endif
2789 #ifdef SSL_OP_NO_TLSv1_2
2790
2791         if (conf->disable_tlsv1_2) ctx_options |= SSL_OP_NO_TLSv1_2;
2792
2793         ctx_tls_versions |= SSL_OP_NO_TLSv1_2;
2794
2795 #endif
2796
2797         if ((ctx_options & ctx_tls_versions) == ctx_tls_versions) {
2798                 ERROR(LOG_PREFIX ": You have disabled all available TLS versions.  EAP will not work");
2799                 return NULL;
2800         }
2801
2802 #ifdef SSL_OP_NO_TICKET
2803         ctx_options |= SSL_OP_NO_TICKET;
2804 #endif
2805
2806         if (!conf->disable_single_dh_use) {
2807                 /*
2808                  *      SSL_OP_SINGLE_DH_USE must be used in order to prevent
2809                  *      small subgroup attacks and forward secrecy. Always
2810                  *      using SSL_OP_SINGLE_DH_USE has an impact on the
2811                  *      computer time needed during negotiation, but it is not
2812                  *      very large.
2813                  */
2814                 ctx_options |= SSL_OP_SINGLE_DH_USE;
2815         }
2816
2817         /*
2818          *      SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS to work around issues
2819          *      in Windows Vista client.
2820          *      http://www.openssl.org/~bodo/tls-cbc.txt
2821          *      http://www.nabble.com/(RADIATOR)-Radiator-Version-3.16-released-t2600070.html
2822          */
2823         ctx_options |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2824
2825         if (conf->cipher_server_preference) {
2826                 /*
2827                  *      SSL_OP_CIPHER_SERVER_PREFERENCE to follow best practice
2828                  *      of nowday's TLS: do not allow poorly-selected ciphers from
2829                  *      client to take preference
2830                  */
2831                 ctx_options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
2832         }
2833
2834         SSL_CTX_set_options(ctx, ctx_options);
2835
2836         /*
2837          *      TODO: Set the RSA & DH
2838          *      SSL_CTX_set_tmp_rsa_callback(ctx, cbtls_rsa);
2839          *      SSL_CTX_set_tmp_dh_callback(ctx, cbtls_dh);
2840          */
2841
2842         /*
2843          *      set the message callback to identify the type of
2844          *      message.  For every new session, there can be a
2845          *      different callback argument.
2846          *
2847          *      SSL_CTX_set_msg_callback(ctx, cbtls_msg);
2848          */
2849
2850         /*
2851          *      Set eliptical curve crypto configuration.
2852          */
2853 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
2854 #ifndef OPENSSL_NO_ECDH
2855         if (set_ecdh_curve(ctx, conf->ecdh_curve, conf->disable_single_dh_use) < 0) {
2856                 return NULL;
2857         }
2858 #endif
2859 #endif
2860
2861         /*
2862          *      OpenSSL will automatically create certificate chains,
2863          *      unless we tell it to not do that.  The problem is that
2864          *      it sometimes gets the chains right from a certificate
2865          *      signature view, but wrong from the clients view.
2866          */
2867         if (!conf->auto_chain) {
2868                 SSL_CTX_set_mode(ctx, SSL_MODE_NO_AUTO_CHAIN);
2869         }
2870
2871         /* Set Info callback */
2872         SSL_CTX_set_info_callback(ctx, cbtls_info);
2873
2874         /*
2875          *      Callbacks, etc. for session resumption.
2876          */
2877         if (conf->session_cache_enable) {
2878                 /*
2879                  *      Cache sessions on disk if requested.
2880                  */
2881                 if (conf->session_cache_path) {
2882                         SSL_CTX_sess_set_new_cb(ctx, cbtls_new_session);
2883                         SSL_CTX_sess_set_get_cb(ctx, cbtls_get_session);
2884                         SSL_CTX_sess_set_remove_cb(ctx, cbtls_remove_session);
2885                 }
2886
2887                 SSL_CTX_set_quiet_shutdown(ctx, 1);
2888                 if (fr_tls_ex_index_vps < 0)
2889                         fr_tls_ex_index_vps = SSL_SESSION_get_ex_new_index(0, NULL, NULL, NULL, sess_free_vps);
2890         }
2891
2892         /*
2893          *      Check the certificates for revocation.
2894          */
2895 #ifdef X509_V_FLAG_CRL_CHECK
2896         if (conf->check_crl) {
2897                 certstore = SSL_CTX_get_cert_store(ctx);
2898                 if (certstore == NULL) {
2899                         tls_error_log(NULL, "Error reading Certificate Store");
2900                         return NULL;
2901                 }
2902                 X509_STORE_set_flags(certstore, X509_V_FLAG_CRL_CHECK);
2903
2904 #ifdef X509_V_FLAG_CRL_CHECK_ALL
2905                 if (conf->check_all_crl)
2906                         X509_STORE_set_flags(certstore, X509_V_FLAG_CRL_CHECK_ALL);
2907 #endif
2908         }
2909 #endif
2910
2911         /*
2912          *      Set verify modes
2913          *      Always verify the peer certificate
2914          */
2915         verify_mode |= SSL_VERIFY_PEER;
2916         verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2917         verify_mode |= SSL_VERIFY_CLIENT_ONCE;
2918         SSL_CTX_set_verify(ctx, verify_mode, cbtls_verify);
2919
2920         if (conf->verify_depth) {
2921                 SSL_CTX_set_verify_depth(ctx, conf->verify_depth);
2922         }
2923
2924         /* Load randomness */
2925         if (conf->random_file) {
2926                 if (!(RAND_load_file(conf->random_file, 1024*10))) {
2927                         tls_error_log(NULL, "Failed loading randomness");
2928                         return NULL;
2929                 }
2930         }
2931
2932         /*
2933          * Set the cipher list if we were told to
2934          */
2935         if (conf->cipher_list) {
2936                 if (!SSL_CTX_set_cipher_list(ctx, conf->cipher_list)) {
2937                         tls_error_log(NULL, "Failed setting cipher list");
2938                         return NULL;
2939                 }
2940         }
2941
2942         /*
2943          *      Setup session caching
2944          */
2945         if (conf->session_cache_enable) {
2946                 /*
2947                  *      Create a unique context Id per EAP-TLS configuration.
2948                  */
2949                 if (conf->session_id_name) {
2950                         snprintf(conf->session_context_id, sizeof(conf->session_context_id),
2951                                  "FR eap %s", conf->session_id_name);
2952                 } else {
2953                         snprintf(conf->session_context_id, sizeof(conf->session_context_id),
2954                                  "FR eap %p", conf);
2955                 }
2956
2957                 /*
2958                  *      Cache it, and DON'T auto-clear it.
2959                  */
2960                 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER | SSL_SESS_CACHE_NO_AUTO_CLEAR);
2961
2962                 SSL_CTX_set_session_id_context(ctx,
2963                                                (unsigned char *) conf->session_context_id,
2964                                                (unsigned int) strlen(conf->session_context_id));
2965
2966                 /*
2967                  *      Our timeout is in hours, this is in seconds.
2968                  */
2969                 SSL_CTX_set_timeout(ctx, conf->session_timeout * 3600);
2970
2971                 /*
2972                  *      Set the maximum number of entries in the
2973                  *      session cache.
2974                  */
2975                 SSL_CTX_sess_set_cache_size(ctx, conf->session_cache_size);
2976
2977         } else {
2978                 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
2979         }
2980
2981         return ctx;
2982 }
2983
2984
2985 /*
2986  *      Free TLS client/server config
2987  *      Should not be called outside this code, as a callback is
2988  *      added to automatically free the data when the CONF_SECTION
2989  *      is freed.
2990  */
2991 static int _tls_server_conf_free(fr_tls_server_conf_t *conf)
2992 {
2993         if (conf->ctx) SSL_CTX_free(conf->ctx);
2994
2995 #ifdef HAVE_OPENSSL_OCSP_H
2996         if (conf->ocsp_store) X509_STORE_free(conf->ocsp_store);
2997         conf->ocsp_store = NULL;
2998 #endif
2999
3000 #ifndef NDEBUG
3001         memset(conf, 0, sizeof(*conf));
3002 #endif
3003         return 0;
3004 }
3005
3006 static fr_tls_server_conf_t *tls_server_conf_alloc(TALLOC_CTX *ctx)
3007 {
3008         fr_tls_server_conf_t *conf;
3009
3010         conf = talloc_zero(ctx, fr_tls_server_conf_t);
3011         if (!conf) {
3012                 ERROR(LOG_PREFIX ": Out of memory");
3013                 return NULL;
3014         }
3015
3016         talloc_set_destructor(conf, _tls_server_conf_free);
3017
3018         return conf;
3019 }
3020
3021 fr_tls_server_conf_t *tls_server_conf_parse(CONF_SECTION *cs)
3022 {
3023         fr_tls_server_conf_t *conf;
3024
3025         /*
3026          *      If cs has already been parsed there should be a cached copy
3027          *      of conf already stored, so just return that.
3028          */
3029         conf = cf_data_find(cs, "tls-conf");
3030         if (conf) {
3031                 DEBUG(LOG_PREFIX ": Using cached TLS configuration from previous invocation");
3032                 return conf;
3033         }
3034
3035         conf = tls_server_conf_alloc(cs);
3036
3037         if (cf_section_parse(cs, conf, tls_server_config) < 0) {
3038         error:
3039                 talloc_free(conf);
3040                 return NULL;
3041         }
3042
3043         /*
3044          *      Save people from their own stupidity.
3045          */
3046         if (conf->fragment_size < 100) conf->fragment_size = 100;
3047
3048         if (!conf->private_key_file) {
3049                 ERROR(LOG_PREFIX ": TLS Server requires a private key file");
3050                 goto error;
3051         }
3052
3053         if (!conf->certificate_file) {
3054                 ERROR(LOG_PREFIX ": TLS Server requires a certificate file");
3055                 goto error;
3056         }
3057
3058         /*
3059          *      Initialize TLS
3060          */
3061         conf->ctx = tls_init_ctx(conf, 0);
3062         if (conf->ctx == NULL) {
3063                 goto error;
3064         }
3065
3066 #ifdef HAVE_OPENSSL_OCSP_H
3067         /*
3068          *      Initialize OCSP Revocation Store
3069          */
3070         if (conf->ocsp_enable) {
3071                 conf->ocsp_store = init_revocation_store(conf);
3072                 if (conf->ocsp_store == NULL) goto error;
3073         }
3074 #endif /*HAVE_OPENSSL_OCSP_H*/
3075         {
3076                 char *dh_file;
3077
3078                 memcpy(&dh_file, &conf->dh_file, sizeof(dh_file));
3079                 if (load_dh_params(conf->ctx, dh_file) < 0) {
3080                         goto error;
3081                 }
3082         }
3083
3084         if (conf->verify_tmp_dir) {
3085                 if (chmod(conf->verify_tmp_dir, S_IRWXU) < 0) {
3086                         ERROR(LOG_PREFIX ": Failed changing permissions on %s: %s",
3087                               conf->verify_tmp_dir, fr_syserror(errno));
3088                         goto error;
3089                 }
3090         }
3091
3092         if (conf->verify_client_cert_cmd && !conf->verify_tmp_dir) {
3093                 ERROR(LOG_PREFIX ": You MUST set the verify directory in order to use verify_client_cmd");
3094                 goto error;
3095         }
3096
3097 #ifdef SSL_OP_NO_TLSv1_2
3098         /*
3099          *      OpenSSL 1.0.1f and 1.0.1g get the MS-MPPE keys wrong.
3100          */
3101 #if (OPENSSL_VERSION_NUMBER >= 0x10010060L) && (OPENSSL_VERSION_NUMBER < 0x10010060L)
3102         conf->disable_tlsv1_2 = true;
3103         WARN(LOG_PREFIX ": Disabling TLSv1.2 due to OpenSSL bugs");
3104 #endif
3105 #endif
3106
3107         /*
3108          *      Cache conf in cs in case we're asked to parse this again.
3109          */
3110         cf_data_add(cs, "tls-conf", conf, NULL);
3111
3112         return conf;
3113 }
3114
3115 fr_tls_server_conf_t *tls_client_conf_parse(CONF_SECTION *cs)
3116 {
3117         fr_tls_server_conf_t *conf;
3118
3119         conf = cf_data_find(cs, "tls-conf");
3120         if (conf) {
3121                 DEBUG2(LOG_PREFIX ": Using cached TLS configuration from previous invocation");
3122                 return conf;
3123         }
3124
3125         conf = tls_server_conf_alloc(cs);
3126
3127         if (cf_section_parse(cs, conf, tls_client_config) < 0) {
3128         error:
3129                 talloc_free(conf);
3130                 return NULL;
3131         }
3132
3133         /*
3134          *      Save people from their own stupidity.
3135          */
3136         if (conf->fragment_size < 100) conf->fragment_size = 100;
3137
3138         /*
3139          *      Initialize TLS
3140          */
3141         conf->ctx = tls_init_ctx(conf, 1);
3142         if (conf->ctx == NULL) {
3143                 goto error;
3144         }
3145
3146         {
3147                 char *dh_file;
3148
3149                 memcpy(&dh_file, &conf->dh_file, sizeof(dh_file));
3150                 if (load_dh_params(conf->ctx, dh_file) < 0) {
3151                         goto error;
3152                 }
3153         }
3154
3155         cf_data_add(cs, "tls-conf", conf, NULL);
3156
3157         return conf;
3158 }
3159
3160 int tls_success(tls_session_t *ssn, REQUEST *request)
3161 {
3162         VALUE_PAIR *vp, *vps = NULL;
3163         fr_tls_server_conf_t *conf;
3164         TALLOC_CTX *talloc_ctx;
3165
3166         conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssn->ssl, FR_TLS_EX_INDEX_CONF);
3167         rad_assert(conf != NULL);
3168
3169         talloc_ctx = SSL_get_ex_data(ssn->ssl, FR_TLS_EX_INDEX_TALLOC);
3170
3171         /*
3172          *      If there's no session resumption, delete the entry
3173          *      from the cache.  This means either it's disabled
3174          *      globally for this SSL context, OR we were told to
3175          *      disable it for this user.
3176          *
3177          *      This also means you can't turn it on just for one
3178          *      user.
3179          */
3180         if ((!ssn->allow_session_resumption) ||
3181             (((vp = fr_pair_find_by_num(request->config, PW_ALLOW_SESSION_RESUMPTION, 0, TAG_ANY)) != NULL) &&
3182              (vp->vp_integer == 0))) {
3183                 SSL_CTX_remove_session(ssn->ctx,
3184                                        ssn->ssl_session);
3185                 ssn->allow_session_resumption = false;
3186
3187                 /*
3188                  *      If we're in a resumed session and it's
3189                  *      not allowed,
3190                  */
3191                 if (SSL_session_reused(ssn->ssl)) {
3192                         RDEBUG("Forcibly stopping session resumption as it is not allowed");
3193                         return -1;
3194                 }
3195
3196         /*
3197          *      Else resumption IS allowed, so we store the
3198          *      user data in the cache.
3199          */
3200         } else if (!SSL_session_reused(ssn->ssl)) {
3201                 VALUE_PAIR **certs;
3202                 char buffer[2 * MAX_SESSION_SIZE + 1];
3203
3204                 tls_session_id(ssn->ssl_session, buffer, MAX_SESSION_SIZE);
3205
3206                 vp = fr_pair_list_copy_by_num(talloc_ctx, request->reply->vps, PW_USER_NAME, 0, TAG_ANY);
3207                 if (vp) fr_pair_add(&vps, vp);
3208
3209                 vp = fr_pair_list_copy_by_num(talloc_ctx, request->packet->vps, PW_STRIPPED_USER_NAME, 0, TAG_ANY);
3210                 if (vp) fr_pair_add(&vps, vp);
3211
3212                 vp = fr_pair_list_copy_by_num(talloc_ctx, request->packet->vps, PW_STRIPPED_USER_DOMAIN, 0, TAG_ANY);
3213                 if (vp) fr_pair_add(&vps, vp);
3214
3215                 vp = fr_pair_list_copy_by_num(talloc_ctx, request->reply->vps, PW_CHARGEABLE_USER_IDENTITY, 0, TAG_ANY);
3216                 if (vp) fr_pair_add(&vps, vp);
3217
3218                 vp = fr_pair_list_copy_by_num(talloc_ctx, request->reply->vps, PW_CACHED_SESSION_POLICY, 0, TAG_ANY);
3219                 if (vp) fr_pair_add(&vps, vp);
3220
3221                 certs = (VALUE_PAIR **)SSL_get_ex_data(ssn->ssl, fr_tls_ex_index_certs);
3222
3223                 /*
3224                  *      Hmm... the certs should probably be session data.
3225                  */
3226                 if (certs) {
3227                         /*
3228                          *      @todo: some go into reply, others into
3229                          *      request
3230                          */
3231                         fr_pair_add(&vps, fr_pair_list_copy(talloc_ctx, *certs));
3232
3233                         /*
3234                          *      Save the certs in the packet, so that we can see them.
3235                          */
3236                         fr_pair_add(&request->packet->vps, fr_pair_list_copy(request->packet, *certs));
3237                 }
3238
3239                 if (vps) {
3240                         SSL_SESSION_set_ex_data(ssn->ssl_session, fr_tls_ex_index_vps, vps);
3241                         rdebug_pair_list(L_DBG_LVL_2, request, vps, "  caching ");
3242
3243                         if (conf->session_cache_path) {
3244                                 /* write the VPs to the cache file */
3245                                 char filename[256], buf[1024];
3246                                 FILE *vp_file;
3247
3248                                 RDEBUG2("Saving session %s in the disk cache", buffer);
3249
3250                                 snprintf(filename, sizeof(filename), "%s%c%s.vps", conf->session_cache_path,
3251                                          FR_DIR_SEP, buffer);
3252                                 vp_file = fopen(filename, "w");
3253                                 if (vp_file == NULL) {
3254                                         RWDEBUG("Could not write session VPs to persistent cache: %s",
3255                                                 fr_syserror(errno));
3256                                 } else {
3257                                         VALUE_PAIR *prev = NULL;
3258                                         vp_cursor_t cursor;
3259                                         /* generate a dummy user-style entry which is easy to read back */
3260                                         fprintf(vp_file, "# SSL cached session\n");
3261                                         fprintf(vp_file, "%s\n\t", buffer);
3262
3263                                         for (vp = fr_cursor_init(&cursor, &vps);
3264                                              vp;
3265                                              vp = fr_cursor_next(&cursor)) {
3266                                                 /*
3267                                                  *      Terminate the previous line.
3268                                                  */
3269                                                 if (prev) fprintf(vp_file, ",\n\t");
3270
3271                                                 /*
3272                                                  *      Write this one.
3273                                                  */
3274                                                 vp_prints(buf, sizeof(buf), vp);
3275                                                 fputs(buf, vp_file);
3276                                                 prev = vp;
3277                                         }
3278
3279                                         /*
3280                                          *      Terminate the final line.
3281                                          */
3282                                         fprintf(vp_file, "\n");
3283                                         fclose(vp_file);
3284                                 }
3285                         } else {
3286                                 RDEBUG("Failed to find 'persist_dir' in TLS configuration.  Session will not be cached on disk.");
3287                         }
3288                 } else {
3289                         RDEBUG2("No information to cache: session caching will be disabled for session %s", buffer);
3290                         SSL_CTX_remove_session(ssn->ctx, ssn->ssl_session);
3291                 }
3292
3293         /*
3294          *      Else the session WAS allowed.  Copy the cached reply.
3295          */
3296         } else {
3297                 char buffer[2 * MAX_SESSION_SIZE + 1];
3298
3299                 tls_session_id(ssn->ssl_session, buffer, MAX_SESSION_SIZE);
3300
3301                 /*
3302                  *      The "restore VPs from OpenSSL cache" code is
3303                  *      now in eaptls_process()
3304                  */
3305
3306                 if (conf->session_cache_path) {
3307                         /* "touch" the cached session/vp file */
3308                         char filename[256];
3309
3310                         snprintf(filename, sizeof(filename), "%s%c%s.asn1",
3311                                  conf->session_cache_path, FR_DIR_SEP, buffer);
3312                         utime(filename, NULL);
3313                         snprintf(filename, sizeof(filename), "%s%c%s.vps",
3314                                  conf->session_cache_path, FR_DIR_SEP, buffer);
3315                         utime(filename, NULL);
3316                 }
3317
3318                 /*
3319                  *      Mark the request as resumed.
3320                  */
3321                 pair_make_request("EAP-Session-Resumed", "1", T_OP_SET);
3322         }
3323
3324         return 0;
3325 }
3326
3327
3328 void tls_fail(tls_session_t *ssn)
3329 {
3330         /*
3331          *      Force the session to NOT be cached.
3332          */
3333         SSL_CTX_remove_session(ssn->ctx, ssn->ssl_session);
3334 }
3335
3336 fr_tls_status_t tls_application_data(tls_session_t *ssn, REQUEST *request)
3337
3338 {
3339         int err;
3340         VALUE_PAIR **certs;
3341
3342         /*
3343          *      Decrypt the complete record.
3344          */
3345         err = BIO_write(ssn->into_ssl, ssn->dirty_in.data,
3346                         ssn->dirty_in.used);
3347         if (err != (int) ssn->dirty_in.used) {
3348                 record_init(&ssn->dirty_in);
3349                 RDEBUG("Failed writing %zd bytes to SSL BIO: %d", ssn->dirty_in.used, err);
3350                 return FR_TLS_FAIL;
3351         }
3352
3353         /*
3354          *      Clear the dirty buffer now that we are done with it
3355          *      and init the clean_out buffer to store decrypted data
3356          */
3357         record_init(&ssn->dirty_in);
3358         record_init(&ssn->clean_out);
3359
3360         /*
3361          *      Read (and decrypt) the tunneled data from the
3362          *      SSL session, and put it into the decrypted
3363          *      data buffer.
3364          */
3365         err = SSL_read(ssn->ssl, ssn->clean_out.data, sizeof(ssn->clean_out.data));
3366         if (err < 0) {
3367                 int code;
3368
3369                 RDEBUG("SSL_read Error");
3370
3371                 code = SSL_get_error(ssn->ssl, err);
3372                 switch (code) {
3373                 case SSL_ERROR_WANT_READ:
3374                         DEBUG("Error in fragmentation logic: SSL_WANT_READ");
3375                         return FR_TLS_MORE_FRAGMENTS;
3376
3377                 case SSL_ERROR_WANT_WRITE:
3378                         DEBUG("Error in fragmentation logic: SSL_WANT_WRITE");
3379                         break;
3380
3381                 default:
3382                         REDEBUG("Error in fragmentation logic");
3383                         tls_error_io_log(request, ssn, err,
3384                                          "Failed in " STRINGIFY(__FUNCTION__) " (SSL_read)");
3385                         break;
3386                 }
3387                 return FR_TLS_FAIL;
3388         }
3389
3390         if (err == 0) RWDEBUG("No data inside of the tunnel");
3391
3392         /*
3393          *      Passed all checks, successfully decrypted data
3394          */
3395         ssn->clean_out.used = err;
3396
3397         /*
3398          *      Add the certificates to intermediate packets, so that
3399          *      the inner tunnel policies can use them.
3400          */
3401         certs = (VALUE_PAIR **)SSL_get_ex_data(ssn->ssl, fr_tls_ex_index_certs);
3402
3403         if (certs) fr_pair_add(&request->packet->vps, fr_pair_list_copy(request->packet, *certs));
3404
3405         return FR_TLS_OK;
3406 }
3407
3408
3409 /*
3410  * Acknowledge received is for one of the following messages sent earlier
3411  * 1. Handshake completed Message, so now send, EAP-Success
3412  * 2. Alert Message, now send, EAP-Failure
3413  * 3. Fragment Message, now send, next Fragment
3414  */
3415 fr_tls_status_t tls_ack_handler(tls_session_t *ssn, REQUEST *request)
3416 {
3417         if (ssn == NULL){
3418                 REDEBUG("Unexpected ACK received:  No ongoing SSL session");
3419                 return FR_TLS_INVALID;
3420         }
3421         if (!ssn->info.initialized) {
3422                 RDEBUG("No SSL info available.  Waiting for more SSL data");
3423                 return FR_TLS_REQUEST;
3424         }
3425
3426         if ((ssn->info.content_type == handshake) && (ssn->info.origin == 0)) {
3427                 REDEBUG("Unexpected ACK received:  We sent no previous messages");
3428                 return FR_TLS_INVALID;
3429         }
3430
3431         switch (ssn->info.content_type) {
3432         case alert:
3433                 RDEBUG2("Peer ACKed our alert");
3434                 return FR_TLS_FAIL;
3435
3436         case handshake:
3437                 if ((ssn->info.handshake_type == handshake_finished) && (ssn->dirty_out.used == 0)) {
3438                         RDEBUG2("Peer ACKed our handshake fragment.  handshake is finished");
3439
3440                         /*
3441                          *      From now on all the content is
3442                          *      application data set it here as nobody else
3443                          *      sets it.
3444                          */
3445                         ssn->info.content_type = application_data;
3446                         return FR_TLS_SUCCESS;
3447                 } /* else more data to send */
3448
3449                 RDEBUG2("Peer ACKed our handshake fragment");
3450                 /* Fragmentation handler, send next fragment */
3451                 return FR_TLS_REQUEST;
3452
3453         case application_data:
3454                 RDEBUG2("Peer ACKed our application data fragment");
3455                 return FR_TLS_REQUEST;
3456
3457                 /*
3458                  *      For the rest of the conditions, switch over
3459                  *      to the default section below.
3460                  */
3461         default:
3462                 REDEBUG("Invalid ACK received: %d", ssn->info.content_type);
3463                 return FR_TLS_INVALID;
3464         }
3465 }
3466 #endif  /* WITH_TLS */
3467