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