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