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