Use threadsafe OpenSSL error functions
[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 #ifdef PSK_MAX_IDENTITY_LEN
122 static bool identity_is_safe(const char *identity)
123 {
124         char c;
125
126         if (!identity) return true;
127
128         while ((c = *(identity++)) != '\0') {
129                 if (isalpha((int) c) || isdigit((int) c) || isspace((int) c) ||
130                     (c == '@') || (c == '-') || (c == '_') || (c == '.')) {
131                         continue;
132                 }
133
134                 return false;
135         }
136
137         return true;
138 }
139
140 DIAG_OFF(format-nonliteral)
141 /** Print errors in the TLS thread local error stack
142  *
143  * Drains the thread local OpenSSL error queue, and prints out errors.
144  *
145  * @param[in] request   The current request (may be NULL).
146  * @param[in] msg       Error message describing the operation being attempted.
147  * @param[in] ap        Arguments for msg.
148  * @return the number of errors drained from the stack.
149  */
150 static int tls_verror_log(REQUEST *request, char const *msg, va_list ap)
151 {
152         unsigned long   error;
153         char            *p;
154         int             in_stack = 0;
155         char            buffer[256];
156
157         int             line;
158         char const      *file;
159
160         /*
161          *      Pop the first error, so ERR_peek_error()
162          *      can be used to determine if there are
163          *      multiple errors.
164          */
165         error = ERR_get_error_line(&file, &line);
166
167         if (msg) {
168                 p = talloc_vasprintf(request, msg, ap);
169
170                 /*
171                  *      Single line mode (there's only one error)
172                  */
173                 if (error && !ERR_peek_error()) {
174                         ERR_error_string_n(error, buffer, sizeof(buffer));
175
176                         /* Extra verbose */
177                         if ((request && RDEBUG_ENABLED3) || DEBUG_ENABLED3) {
178                                 ROPTIONAL(REDEBUG, ERROR, "%s: %s[%i]:%s", p, file, line, buffer);
179                         } else {
180                                 ROPTIONAL(REDEBUG, ERROR, "%s: %s", p, buffer);
181                         }
182
183                         talloc_free(p);
184
185                         return 1;
186                 }
187
188                 /*
189                  *      Print the error we were given, irrespective
190                  *      of whether there were any OpenSSL errors.
191                  */
192                 ROPTIONAL(RERROR, ERROR, "%s", p);
193                 talloc_free(p);
194         }
195
196         /*
197          *      Stack mode (there are multiple errors)
198          */
199         if (!error) return 0;
200         do {
201                 ERR_error_string_n(error, buffer, sizeof(buffer));
202                 /* Extra verbose */
203                 if ((request && RDEBUG_ENABLED3) || DEBUG_ENABLED3) {
204                         ROPTIONAL(REDEBUG, ERROR, "%s[%i]:%s", file, line, buffer);
205                 } else {
206                         ROPTIONAL(REDEBUG, ERROR, "%s", buffer);
207                 }
208                 in_stack++;
209         } while ((error = ERR_get_error_line(&file, &line)));
210
211         return in_stack;
212 }
213 DIAG_ON(format-nonliteral)
214
215 /** Print errors in the TLS thread local error stack
216  *
217  * Drains the thread local OpenSSL error queue, and prints out errors.
218  *
219  * @param[in] request   The current request (may be NULL).
220  * @param[in] msg       Error message describing the operation being attempted.
221  * @param[in] ...       Arguments for msg.
222  * @return the number of errors drained from the stack.
223  */
224 int tls_error_log(REQUEST *request, char const *msg, ...)
225 {
226         va_list ap;
227         int ret;
228
229         va_start(ap, msg);
230         ret = tls_verror_log(request, msg, ap);
231         va_end(ap);
232
233         return ret;
234 }
235
236 /** Print errors raised by OpenSSL I/O functions
237  *
238  * Drains the thread local OpenSSL error queue, and prints out errors
239  * based on the SSL handle and the return code of the I/O  function.
240  *
241  * OpenSSL lists I/O functions to be:
242  *   - SSL_connect
243  *   - SSL_accept
244  *   - SSL_do_handshake
245  *   - SSL_read
246  *   - SSL_peek
247  *   - SSL_write
248  *
249  * @param request       The current request (may be NULL).
250  * @param session       The current tls_session.
251  * @param ret           from the I/O operation.
252  * @param msg           Error message describing the operation being attempted.
253  * @param ...           Arguments for msg.
254  * @return
255  *      - 0 TLS session cannot continue.
256  *      - 1 TLS session may still be viable.
257  */
258 int tls_error_io_log(REQUEST *request, tls_session_t *session, int ret, char const *msg, ...)
259 {
260         int     error;
261         va_list ap;
262
263         if (ERR_peek_error()) {
264                 va_start(ap, msg);
265                 tls_verror_log(request, msg, ap);
266                 va_end(ap);
267         }
268
269         error = SSL_get_error(session->ssl, ret);
270         switch (error) {
271         /*
272          *      These seem to be harmless and already "dealt
273          *      with" by our non-blocking environment. NB:
274          *      "ZERO_RETURN" is the clean "error"
275          *      indicating a successfully closed SSL
276          *      tunnel. We let this happen because our IO
277          *      loop should not appear to have broken on
278          *      this condition - and outside the IO loop, the
279          *      "shutdown" state is checked.
280          *
281          *      Don't print anything if we ignore the error.
282          */
283         case SSL_ERROR_NONE:
284         case SSL_ERROR_WANT_READ:
285         case SSL_ERROR_WANT_WRITE:
286         case SSL_ERROR_WANT_X509_LOOKUP:
287         case SSL_ERROR_ZERO_RETURN:
288                 break;
289
290         /*
291          *      These seem to be indications of a genuine
292          *      error that should result in the SSL tunnel
293          *      being regarded as "dead".
294          */
295         case SSL_ERROR_SYSCALL:
296                 ROPTIONAL(REDEBUG, ERROR, "System call (I/O) error (%i)", ret);
297                 return 0;
298
299         case SSL_ERROR_SSL:
300                 ROPTIONAL(REDEBUG, ERROR, "TLS protocol error (%i)", ret);
301                 return 0;
302
303         /*
304          *      For any other errors that (a) exist, and (b)
305          *      crop up - we need to interpret what to do with
306          *      them - so "politely inform" the caller that
307          *      the code needs updating here.
308          */
309         default:
310                 ROPTIONAL(REDEBUG, ERROR, "TLS session error %i (%i)", error, ret);
311                 return 0;
312         }
313
314         return 1;
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 = (X509_STORE *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_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                                 RERROR("Couldn't get issuer_cert for %s", common_name);
2200                         } else {
2201                                 my_ok = ocsp_check(request, ocsp_store, issuer_cert, client_cert, conf);
2202                         }
2203                 }
2204 #endif
2205
2206                 /*
2207                  *      If OCSP returns fail (0), the certificate has expired.
2208                  *      Don't run the verify routines/
2209                  *
2210                  *      If OCSP returns success (1), we MAY want to run the verify section.
2211                  *      but only if verify_skip_if_ocsp_ok is false.
2212                  *
2213                  *      If OCSP returns skipped (2), we run the verify command, unless
2214                  *      conf->verify_skip_if_ocsp_ok is true.
2215                  */
2216                 if ((my_ok != 0)
2217 #ifdef HAVE_OPENSSL_OCSP_H
2218                     && conf->ocsp_enable && (my_ok != OCSP_STATUS_OK) && conf->verify_skip_if_ocsp_ok
2219 #endif
2220                         ) while (conf->verify_client_cert_cmd) {
2221                         char filename[256];
2222                         int fd;
2223                         FILE *fp;
2224
2225                         snprintf(filename, sizeof(filename), "%s/%s.client.XXXXXXXX",
2226                                  conf->verify_tmp_dir, main_config.name);
2227                         fd = mkstemp(filename);
2228                         if (fd < 0) {
2229                                 RDEBUG("Failed creating file in %s: %s",
2230                                        conf->verify_tmp_dir, fr_syserror(errno));
2231                                 break;
2232                         }
2233
2234                         fp = fdopen(fd, "w");
2235                         if (!fp) {
2236                                 close(fd);
2237                                 RDEBUG("Failed opening file %s: %s",
2238                                        filename, fr_syserror(errno));
2239                                 break;
2240                         }
2241
2242                         if (!PEM_write_X509(fp, client_cert)) {
2243                                 fclose(fp);
2244                                 RDEBUG("Failed writing certificate to file");
2245                                 goto do_unlink;
2246                         }
2247                         fclose(fp);
2248
2249                         if (!pair_make_request("TLS-Client-Cert-Filename",
2250                                              filename, T_OP_SET)) {
2251                                 RDEBUG("Failed creating TLS-Client-Cert-Filename");
2252
2253                                 goto do_unlink;
2254                         }
2255
2256                         RDEBUG("Verifying client certificate: %s", conf->verify_client_cert_cmd);
2257                         if (radius_exec_program(request, NULL, 0, NULL, request, conf->verify_client_cert_cmd,
2258                                                 request->packet->vps,
2259                                                 true, true, EXEC_TIMEOUT) != 0) {
2260                                 AUTH(LOG_PREFIX ": Certificate CN (%s) fails external verification!", common_name);
2261                                 my_ok = 0;
2262                         } else {
2263                                 RDEBUG("Client certificate CN %s passed external validation", common_name);
2264                         }
2265
2266                 do_unlink:
2267                         unlink(filename);
2268                         break;
2269                 }
2270         } /* depth == 0 */
2271
2272         if (certs && request && !my_ok) {
2273                 fr_pair_add(&request->packet->vps, fr_pair_list_copy(request->packet, *certs));
2274         }
2275
2276         if (RDEBUG_ENABLED3) {
2277                 RDEBUG3("chain-depth   : %d", depth);
2278                 RDEBUG3("error         : %d", err);
2279
2280                 if (identity) RDEBUG3("identity      : %s", *identity);
2281                 RDEBUG3("common name   : %s", common_name);
2282                 RDEBUG3("subject       : %s", subject);
2283                 RDEBUG3("issuer        : %s", issuer);
2284                 RDEBUG3("verify return : %d", my_ok);
2285         }
2286
2287         return (my_ok != 0);
2288 }
2289
2290
2291 #ifdef HAVE_OPENSSL_OCSP_H
2292 /*
2293  *      Create Global X509 revocation store and use it to verify
2294  *      OCSP responses
2295  *
2296  *      - Load the trusted CAs
2297  *      - Load the trusted issuer certificates
2298  */
2299 static X509_STORE *init_revocation_store(fr_tls_server_conf_t *conf)
2300 {
2301         X509_STORE *store = NULL;
2302
2303         store = X509_STORE_new();
2304
2305         /* Load the CAs we trust */
2306         if (conf->ca_file || conf->ca_path)
2307                 if (!X509_STORE_load_locations(store, conf->ca_file, conf->ca_path)) {
2308                         tls_error_log(NULL, "Error reading Trusted root CA list \"%s\"", conf->ca_file);
2309                         return NULL;
2310                 }
2311
2312 #ifdef X509_V_FLAG_CRL_CHECK
2313         if (conf->check_crl)
2314                 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK);
2315 #endif
2316 #ifdef X509_V_FLAG_CRL_CHECK_ALL
2317         if (conf->check_all_crl)
2318                 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK_ALL);
2319 #endif
2320         return store;
2321 }
2322 #endif  /* HAVE_OPENSSL_OCSP_H */
2323
2324 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
2325 #ifndef OPENSSL_NO_ECDH
2326 static int set_ecdh_curve(SSL_CTX *ctx, char const *ecdh_curve, bool disable_single_dh_use)
2327 {
2328         int      nid;
2329         EC_KEY  *ecdh;
2330
2331         if (!ecdh_curve || !*ecdh_curve) return 0;
2332
2333         nid = OBJ_sn2nid(ecdh_curve);
2334         if (!nid) {
2335                 ERROR(LOG_PREFIX ": Unknown ecdh_curve \"%s\"", ecdh_curve);
2336                 return -1;
2337         }
2338
2339         ecdh = EC_KEY_new_by_curve_name(nid);
2340         if (!ecdh) {
2341                 ERROR(LOG_PREFIX ": Unable to create new curve \"%s\"", ecdh_curve);
2342                 return -1;
2343         }
2344
2345         SSL_CTX_set_tmp_ecdh(ctx, ecdh);
2346
2347         if (!disable_single_dh_use) {
2348                 SSL_CTX_set_options(ctx, SSL_OP_SINGLE_ECDH_USE);
2349         }
2350
2351         EC_KEY_free(ecdh);
2352
2353         return 0;
2354 }
2355 #endif
2356 #endif
2357
2358 /*
2359  * DIE OPENSSL DIE DIE DIE
2360  *
2361  * What a palaver, just to free some data attached the
2362  * session. We need to do this because the "remove" callback
2363  * is called when refcount > 0 sometimes, if another thread
2364  * is using the session
2365  */
2366 static void sess_free_vps(UNUSED void *parent, void *data_ptr,
2367                                 UNUSED CRYPTO_EX_DATA *ad, UNUSED int idx,
2368                                 UNUSED long argl, UNUSED void *argp)
2369 {
2370         VALUE_PAIR *vp = data_ptr;
2371         if (!vp) return;
2372
2373         DEBUG2(LOG_PREFIX ": Freeing cached session VPs");
2374
2375         fr_pair_list_free(&vp);
2376 }
2377
2378 static void sess_free_certs(UNUSED void *parent, void *data_ptr,
2379                                 UNUSED CRYPTO_EX_DATA *ad, UNUSED int idx,
2380                                 UNUSED long argl, UNUSED void *argp)
2381 {
2382         VALUE_PAIR **certs = data_ptr;
2383         if (!certs) return;
2384
2385         DEBUG2(LOG_PREFIX ": Freeing cached session Certificates");
2386
2387         fr_pair_list_free(certs);
2388 }
2389
2390 /** Add all the default ciphers and message digests reate our context.
2391  *
2392  * This should be called exactly once from main, before reading the main config
2393  * or initialising any modules.
2394  */
2395 void tls_global_init(void)
2396 {
2397         SSL_load_error_strings();       /* readable error messages (examples show call before library_init) */
2398         SSL_library_init();             /* initialize library */
2399         OpenSSL_add_all_algorithms();   /* required for SHA2 in OpenSSL < 0.9.8o and 1.0.0.a */
2400         OPENSSL_config(NULL);
2401
2402         /*
2403          *      Initialize the index for the certificates.
2404          */
2405         fr_tls_ex_index_certs = SSL_SESSION_get_ex_new_index(0, NULL, NULL, NULL, sess_free_certs);
2406 }
2407
2408 #ifdef ENABLE_OPENSSL_VERSION_CHECK
2409 /** Check for vulnerable versions of libssl
2410  *
2411  * @param acknowledged The highest CVE number a user has confirmed is not present in the system's libssl.
2412  * @return 0 if the CVE specified by the user matches the most recent CVE we have, else -1.
2413  */
2414 int tls_global_version_check(char const *acknowledged)
2415 {
2416         uint64_t v;
2417
2418         if ((strcmp(acknowledged, libssl_defects[0].id) != 0) && (strcmp(acknowledged, "yes") != 0)) {
2419                 bool bad = false;
2420                 size_t i;
2421
2422                 /* Check for bad versions */
2423                 v = (uint64_t) SSLeay();
2424
2425                 for (i = 0; i < (sizeof(libssl_defects) / sizeof(*libssl_defects)); i++) {
2426                         libssl_defect_t *defect = &libssl_defects[i];
2427
2428                         if ((v >= defect->low) && (v <= defect->high)) {
2429                                 ERROR("Refusing to start with libssl version %s (in range %s)",
2430                                       ssl_version(), ssl_version_range(defect->low, defect->high));
2431                                 ERROR("Security advisory %s (%s)", defect->id, defect->name);
2432                                 ERROR("%s", defect->comment);
2433
2434                                 bad = true;
2435                         }
2436                 }
2437
2438                 if (bad) {
2439                         INFO("Once you have verified libssl has been correctly patched, "
2440                              "set security.allow_vulnerable_openssl = '%s'", libssl_defects[0].id);
2441                         return -1;
2442                 }
2443         }
2444
2445         return 0;
2446 }
2447 #endif
2448
2449 /** Free any memory alloced by libssl
2450  *
2451  */
2452 void tls_global_cleanup(void)
2453 {
2454         ERR_remove_state(0);
2455         ENGINE_cleanup();
2456         CONF_modules_unload(1);
2457         ERR_free_strings();
2458         EVP_cleanup();
2459         CRYPTO_cleanup_all_ex_data();
2460 }
2461
2462 /** Create SSL context
2463  *
2464  * - Load the trusted CAs
2465  * - Load the Private key & the certificate
2466  * - Set the Context options & Verify options
2467  */
2468 SSL_CTX *tls_init_ctx(fr_tls_server_conf_t *conf, int client)
2469 {
2470         SSL_CTX         *ctx;
2471         X509_STORE      *certstore;
2472         int             verify_mode = SSL_VERIFY_NONE;
2473         int             ctx_options = 0;
2474         int             ctx_tls_versions = 0;
2475         int             type;
2476
2477         /*
2478          *      SHA256 is in all versions of OpenSSL, but isn't
2479          *      initialized by default.  It's needed for WiMAX
2480          *      certificates.
2481          */
2482 #ifdef HAVE_OPENSSL_EVP_SHA256
2483         EVP_add_digest(EVP_sha256());
2484 #endif
2485
2486         ctx = SSL_CTX_new(SSLv23_method()); /* which is really "all known SSL / TLS methods".  Idiots. */
2487         if (!ctx) {
2488                 tls_error_log(NULL, "Failed creating TLS context");
2489                 return NULL;
2490         }
2491
2492         /*
2493          * Save the config on the context so that callbacks which
2494          * only get SSL_CTX* e.g. session persistence, can get it
2495          */
2496         SSL_CTX_set_app_data(ctx, conf);
2497
2498         /*
2499          * Identify the type of certificates that needs to be loaded
2500          */
2501         if (conf->file_type) {
2502                 type = SSL_FILETYPE_PEM;
2503         } else {
2504                 type = SSL_FILETYPE_ASN1;
2505         }
2506
2507         /*
2508          * Set the password to load private key
2509          */
2510         if (conf->private_key_password) {
2511 #ifdef __APPLE__
2512                 /*
2513                  * We don't want to put the private key password in eap.conf, so  check
2514                  * for our special string which indicates we should get the password
2515                  * programmatically.
2516                  */
2517                 char const* special_string = "Apple:UseCertAdmin";
2518                 if (strncmp(conf->private_key_password, special_string, strlen(special_string)) == 0) {
2519                         char cmd[256];
2520                         char *password;
2521                         long const max_password_len = 128;
2522                         snprintf(cmd, sizeof(cmd) - 1, "/usr/sbin/certadmin --get-private-key-passphrase \"%s\"",
2523                                  conf->private_key_file);
2524
2525                         DEBUG2(LOG_PREFIX ":  Getting private key passphrase using command \"%s\"", cmd);
2526
2527                         FILE* cmd_pipe = popen(cmd, "r");
2528                         if (!cmd_pipe) {
2529                                 ERROR(LOG_PREFIX ": %s command failed: Unable to get private_key_password", cmd);
2530                                 ERROR(LOG_PREFIX ": Error reading private_key_file %s", conf->private_key_file);
2531                                 return NULL;
2532                         }
2533
2534                         rad_const_free(conf->private_key_password);
2535                         password = talloc_array(conf, char, max_password_len);
2536                         if (!password) {
2537                                 ERROR(LOG_PREFIX ": Can't allocate space for private_key_password");
2538                                 ERROR(LOG_PREFIX ": Error reading private_key_file %s", conf->private_key_file);
2539                                 pclose(cmd_pipe);
2540                                 return NULL;
2541                         }
2542
2543                         fgets(password, max_password_len, cmd_pipe);
2544                         pclose(cmd_pipe);
2545
2546                         /* Get rid of newline at end of password. */
2547                         password[strlen(password) - 1] = '\0';
2548
2549                         DEBUG3(LOG_PREFIX ": Password from command = \"%s\"", password);
2550                         conf->private_key_password = password;
2551                 }
2552 #endif
2553
2554                 {
2555                         char *password;
2556
2557                         memcpy(&password, &conf->private_key_password, sizeof(password));
2558                         SSL_CTX_set_default_passwd_cb_userdata(ctx, password);
2559                         SSL_CTX_set_default_passwd_cb(ctx, cbtls_password);
2560                 }
2561         }
2562
2563 #ifdef PSK_MAX_IDENTITY_LEN
2564         if (!client) {
2565                 /*
2566                  *      No dynamic query exists.  There MUST be a
2567                  *      statically configured identity and password.
2568                  */
2569                 if (conf->psk_query && !*conf->psk_query) {
2570                         ERROR(LOG_PREFIX ": Invalid PSK Configuration: psk_query cannot be empty");
2571                         return NULL;
2572                 }
2573
2574                 /*
2575                  *      Set the callback only if we can check things.
2576                  */
2577                 if (conf->psk_identity || conf->psk_query) {
2578                         SSL_CTX_set_psk_server_callback(ctx, psk_server_callback);
2579                 }
2580
2581         } else if (conf->psk_query) {
2582                 ERROR(LOG_PREFIX ": Invalid PSK Configuration: psk_query cannot be used for outgoing connections");
2583                 return NULL;
2584         }
2585
2586         /*
2587          *      Now check that if PSK is being used, the config is valid.
2588          */
2589         if ((conf->psk_identity && !conf->psk_password) ||
2590             (!conf->psk_identity && conf->psk_password) ||
2591             (conf->psk_identity && !*conf->psk_identity) ||
2592             (conf->psk_password && !*conf->psk_password)) {
2593                 ERROR(LOG_PREFIX ": Invalid PSK Configuration: psk_identity or psk_password are empty");
2594                 return NULL;
2595         }
2596
2597         if (conf->psk_identity) {
2598                 size_t psk_len, hex_len;
2599                 uint8_t buffer[PSK_MAX_PSK_LEN];
2600
2601                 if (conf->certificate_file ||
2602                     conf->private_key_password || conf->private_key_file ||
2603                     conf->ca_file || conf->ca_path) {
2604                         ERROR(LOG_PREFIX ": When PSKs are used, No certificate configuration is permitted");
2605                         return NULL;
2606                 }
2607
2608                 if (client) {
2609                         SSL_CTX_set_psk_client_callback(ctx,
2610                                                         psk_client_callback);
2611                 }
2612
2613                 psk_len = strlen(conf->psk_password);
2614                 if (strlen(conf->psk_password) > (2 * PSK_MAX_PSK_LEN)) {
2615                         ERROR(LOG_PREFIX ": psk_hexphrase is too long (max %d)", PSK_MAX_PSK_LEN);
2616                         return NULL;
2617                 }
2618
2619                 /*
2620                  *      Check the password now, so that we don't have
2621                  *      errors at run-time.
2622                  */
2623                 hex_len = fr_hex2bin(buffer, sizeof(buffer), conf->psk_password, psk_len);
2624                 if (psk_len != (2 * hex_len)) {
2625                         ERROR(LOG_PREFIX ": psk_hexphrase is not all hex");
2626                         return NULL;
2627                 }
2628
2629                 goto post_ca;
2630         }
2631 #else
2632         (void) client;  /* -Wunused */
2633 #endif
2634
2635         /*
2636          *      Load our keys and certificates
2637          *
2638          *      If certificates are of type PEM then we can make use
2639          *      of cert chain authentication using openssl api call
2640          *      SSL_CTX_use_certificate_chain_file.  Please see how
2641          *      the cert chain needs to be given in PEM from
2642          *      openSSL.org
2643          */
2644         if (!conf->certificate_file) goto load_ca;
2645
2646         if (type == SSL_FILETYPE_PEM) {
2647                 if (!(SSL_CTX_use_certificate_chain_file(ctx, conf->certificate_file))) {
2648                         tls_error_log(NULL, "Failed reading certificate file \"%s\"",
2649                                       conf->certificate_file);
2650                         return NULL;
2651                 }
2652
2653         } else if (!(SSL_CTX_use_certificate_file(ctx, conf->certificate_file, type))) {
2654                 tls_error_log(NULL, "Failed reading certificate file \"%s\"",
2655                               conf->certificate_file);
2656                 return NULL;
2657         }
2658
2659         /* Load the CAs we trust */
2660 load_ca:
2661         if (conf->ca_file || conf->ca_path) {
2662                 if (!SSL_CTX_load_verify_locations(ctx, conf->ca_file, conf->ca_path)) {
2663                         tls_error_log(NULL, "Failed reading Trusted root CA list \"%s\"",
2664                                       conf->ca_file);
2665                         return NULL;
2666                 }
2667         }
2668         if (conf->ca_file && *conf->ca_file) SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(conf->ca_file));
2669
2670         if (conf->private_key_file) {
2671                 if (!(SSL_CTX_use_PrivateKey_file(ctx, conf->private_key_file, type))) {
2672                         tls_error_log(NULL, "Failed reading private key file \"%s\"",
2673                                       conf->private_key_file);
2674                         return NULL;
2675                 }
2676
2677                 /*
2678                  * Check if the loaded private key is the right one
2679                  */
2680                 if (!SSL_CTX_check_private_key(ctx)) {
2681                         ERROR(LOG_PREFIX ": Private key does not match the certificate public key");
2682                         return NULL;
2683                 }
2684         }
2685
2686 #ifdef PSK_MAX_IDENTITY_LEN
2687 post_ca:
2688 #endif
2689
2690         /*
2691          *      We never want SSLv2 or SSLv3.
2692          */
2693         ctx_options |= SSL_OP_NO_SSLv2;
2694         ctx_options |= SSL_OP_NO_SSLv3;
2695
2696         /*
2697          *      As of 3.0.5, we always allow TLSv1.1 and TLSv1.2.
2698          *      Though they can be *globally* disabled if necessary.x
2699          */
2700 #ifdef SSL_OP_NO_TLSv1
2701         if (conf->disable_tlsv1) ctx_options |= SSL_OP_NO_TLSv1;
2702
2703         ctx_tls_versions |= SSL_OP_NO_TLSv1;
2704 #endif
2705 #ifdef SSL_OP_NO_TLSv1_1
2706         if (conf->disable_tlsv1_1) ctx_options |= SSL_OP_NO_TLSv1_1;
2707
2708         ctx_tls_versions |= SSL_OP_NO_TLSv1_1;
2709 #endif
2710 #ifdef SSL_OP_NO_TLSv1_2
2711
2712         if (conf->disable_tlsv1_2) ctx_options |= SSL_OP_NO_TLSv1_2;
2713
2714         ctx_tls_versions |= SSL_OP_NO_TLSv1_2;
2715
2716 #endif
2717
2718         if ((ctx_options & ctx_tls_versions) == ctx_tls_versions) {
2719                 ERROR(LOG_PREFIX ": You have disabled all available TLS versions.  EAP will not work");
2720                 return NULL;
2721         }
2722
2723 #ifdef SSL_OP_NO_TICKET
2724         ctx_options |= SSL_OP_NO_TICKET;
2725 #endif
2726
2727         if (!conf->disable_single_dh_use) {
2728                 /*
2729                  *      SSL_OP_SINGLE_DH_USE must be used in order to prevent
2730                  *      small subgroup attacks and forward secrecy. Always
2731                  *      using SSL_OP_SINGLE_DH_USE has an impact on the
2732                  *      computer time needed during negotiation, but it is not
2733                  *      very large.
2734                  */
2735                 ctx_options |= SSL_OP_SINGLE_DH_USE;
2736         }
2737
2738         /*
2739          *      SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS to work around issues
2740          *      in Windows Vista client.
2741          *      http://www.openssl.org/~bodo/tls-cbc.txt
2742          *      http://www.nabble.com/(RADIATOR)-Radiator-Version-3.16-released-t2600070.html
2743          */
2744         ctx_options |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2745
2746         SSL_CTX_set_options(ctx, ctx_options);
2747
2748         /*
2749          *      TODO: Set the RSA & DH
2750          *      SSL_CTX_set_tmp_rsa_callback(ctx, cbtls_rsa);
2751          *      SSL_CTX_set_tmp_dh_callback(ctx, cbtls_dh);
2752          */
2753
2754         /*
2755          *      set the message callback to identify the type of
2756          *      message.  For every new session, there can be a
2757          *      different callback argument.
2758          *
2759          *      SSL_CTX_set_msg_callback(ctx, cbtls_msg);
2760          */
2761
2762         /*
2763          *      Set eliptical curve crypto configuration.
2764          */
2765 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
2766 #ifndef OPENSSL_NO_ECDH
2767         if (set_ecdh_curve(ctx, conf->ecdh_curve, conf->disable_single_dh_use) < 0) {
2768                 return NULL;
2769         }
2770 #endif
2771 #endif
2772
2773         /*
2774          *      OpenSSL will automatically create certificate chains,
2775          *      unless we tell it to not do that.  The problem is that
2776          *      it sometimes gets the chains right from a certificate
2777          *      signature view, but wrong from the clients view.
2778          */
2779         if (!conf->auto_chain) {
2780                 SSL_CTX_set_mode(ctx, SSL_MODE_NO_AUTO_CHAIN);
2781         }
2782
2783         /* Set Info callback */
2784         SSL_CTX_set_info_callback(ctx, cbtls_info);
2785
2786         /*
2787          *      Callbacks, etc. for session resumption.
2788          */
2789         if (conf->session_cache_enable) {
2790                 /*
2791                  *      Cache sessions on disk if requested.
2792                  */
2793                 if (conf->session_cache_path) {
2794                         SSL_CTX_sess_set_new_cb(ctx, cbtls_new_session);
2795                         SSL_CTX_sess_set_get_cb(ctx, cbtls_get_session);
2796                         SSL_CTX_sess_set_remove_cb(ctx, cbtls_remove_session);
2797                 }
2798
2799                 SSL_CTX_set_quiet_shutdown(ctx, 1);
2800                 if (fr_tls_ex_index_vps < 0)
2801                         fr_tls_ex_index_vps = SSL_SESSION_get_ex_new_index(0, NULL, NULL, NULL, sess_free_vps);
2802         }
2803
2804         /*
2805          *      Check the certificates for revocation.
2806          */
2807 #ifdef X509_V_FLAG_CRL_CHECK
2808         if (conf->check_crl) {
2809                 certstore = SSL_CTX_get_cert_store(ctx);
2810                 if (certstore == NULL) {
2811                         tls_error_log(NULL, "Error reading Certificate Store");
2812                         return NULL;
2813                 }
2814                 X509_STORE_set_flags(certstore, X509_V_FLAG_CRL_CHECK);
2815
2816 #ifdef X509_V_FLAG_CRL_CHECK_ALL
2817                 if (conf->check_all_crl)
2818                         X509_STORE_set_flags(certstore, X509_V_FLAG_CRL_CHECK_ALL);
2819 #endif
2820         }
2821 #endif
2822
2823         /*
2824          *      Set verify modes
2825          *      Always verify the peer certificate
2826          */
2827         verify_mode |= SSL_VERIFY_PEER;
2828         verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2829         verify_mode |= SSL_VERIFY_CLIENT_ONCE;
2830         SSL_CTX_set_verify(ctx, verify_mode, cbtls_verify);
2831
2832         if (conf->verify_depth) {
2833                 SSL_CTX_set_verify_depth(ctx, conf->verify_depth);
2834         }
2835
2836         /* Load randomness */
2837         if (conf->random_file) {
2838                 if (!(RAND_load_file(conf->random_file, 1024*10))) {
2839                         tls_error_log(NULL, "Failed loading randomness");
2840                         return NULL;
2841                 }
2842         }
2843
2844         /*
2845          * Set the cipher list if we were told to
2846          */
2847         if (conf->cipher_list) {
2848                 if (!SSL_CTX_set_cipher_list(ctx, conf->cipher_list)) {
2849                         tls_error_log(NULL, "Failed setting cipher list");
2850                         return NULL;
2851                 }
2852         }
2853
2854         /*
2855          *      Setup session caching
2856          */
2857         if (conf->session_cache_enable) {
2858                 /*
2859                  *      Create a unique context Id per EAP-TLS configuration.
2860                  */
2861                 if (conf->session_id_name) {
2862                         snprintf(conf->session_context_id, sizeof(conf->session_context_id),
2863                                  "FR eap %s", conf->session_id_name);
2864                 } else {
2865                         snprintf(conf->session_context_id, sizeof(conf->session_context_id),
2866                                  "FR eap %p", conf);
2867                 }
2868
2869                 /*
2870                  *      Cache it, and DON'T auto-clear it.
2871                  */
2872                 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER | SSL_SESS_CACHE_NO_AUTO_CLEAR);
2873
2874                 SSL_CTX_set_session_id_context(ctx,
2875                                                (unsigned char *) conf->session_context_id,
2876                                                (unsigned int) strlen(conf->session_context_id));
2877
2878                 /*
2879                  *      Our timeout is in hours, this is in seconds.
2880                  */
2881                 SSL_CTX_set_timeout(ctx, conf->session_timeout * 3600);
2882
2883                 /*
2884                  *      Set the maximum number of entries in the
2885                  *      session cache.
2886                  */
2887                 SSL_CTX_sess_set_cache_size(ctx, conf->session_cache_size);
2888
2889         } else {
2890                 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
2891         }
2892
2893         return ctx;
2894 }
2895
2896
2897 /*
2898  *      Free TLS client/server config
2899  *      Should not be called outside this code, as a callback is
2900  *      added to automatically free the data when the CONF_SECTION
2901  *      is freed.
2902  */
2903 static int _tls_server_conf_free(fr_tls_server_conf_t *conf)
2904 {
2905         if (conf->ctx) SSL_CTX_free(conf->ctx);
2906
2907 #ifdef HAVE_OPENSSL_OCSP_H
2908         if (conf->ocsp_store) X509_STORE_free(conf->ocsp_store);
2909         conf->ocsp_store = NULL;
2910 #endif
2911
2912 #ifndef NDEBUG
2913         memset(conf, 0, sizeof(*conf));
2914 #endif
2915         return 0;
2916 }
2917
2918 static fr_tls_server_conf_t *tls_server_conf_alloc(TALLOC_CTX *ctx)
2919 {
2920         fr_tls_server_conf_t *conf;
2921
2922         conf = talloc_zero(ctx, fr_tls_server_conf_t);
2923         if (!conf) {
2924                 ERROR(LOG_PREFIX ": Out of memory");
2925                 return NULL;
2926         }
2927
2928         talloc_set_destructor(conf, _tls_server_conf_free);
2929
2930         return conf;
2931 }
2932
2933 fr_tls_server_conf_t *tls_server_conf_parse(CONF_SECTION *cs)
2934 {
2935         fr_tls_server_conf_t *conf;
2936
2937         /*
2938          *      If cs has already been parsed there should be a cached copy
2939          *      of conf already stored, so just return that.
2940          */
2941         conf = cf_data_find(cs, "tls-conf");
2942         if (conf) {
2943                 DEBUG(LOG_PREFIX ": Using cached TLS configuration from previous invocation");
2944                 return conf;
2945         }
2946
2947         conf = tls_server_conf_alloc(cs);
2948
2949         if (cf_section_parse(cs, conf, tls_server_config) < 0) {
2950         error:
2951                 talloc_free(conf);
2952                 return NULL;
2953         }
2954
2955         /*
2956          *      Save people from their own stupidity.
2957          */
2958         if (conf->fragment_size < 100) conf->fragment_size = 100;
2959
2960         if (!conf->private_key_file) {
2961                 ERROR(LOG_PREFIX ": TLS Server requires a private key file");
2962                 goto error;
2963         }
2964
2965         if (!conf->certificate_file) {
2966                 ERROR(LOG_PREFIX ": TLS Server requires a certificate file");
2967                 goto error;
2968         }
2969
2970         /*
2971          *      Initialize TLS
2972          */
2973         conf->ctx = tls_init_ctx(conf, 0);
2974         if (conf->ctx == NULL) {
2975                 goto error;
2976         }
2977
2978 #ifdef HAVE_OPENSSL_OCSP_H
2979         /*
2980          *      Initialize OCSP Revocation Store
2981          */
2982         if (conf->ocsp_enable) {
2983                 conf->ocsp_store = init_revocation_store(conf);
2984                 if (conf->ocsp_store == NULL) goto error;
2985         }
2986 #endif /*HAVE_OPENSSL_OCSP_H*/
2987         {
2988                 char *dh_file;
2989
2990                 memcpy(&dh_file, &conf->dh_file, sizeof(dh_file));
2991                 if (load_dh_params(conf->ctx, dh_file) < 0) {
2992                         goto error;
2993                 }
2994         }
2995
2996         if (conf->verify_tmp_dir) {
2997                 if (chmod(conf->verify_tmp_dir, S_IRWXU) < 0) {
2998                         ERROR(LOG_PREFIX ": Failed changing permissions on %s: %s",
2999                               conf->verify_tmp_dir, fr_syserror(errno));
3000                         goto error;
3001                 }
3002         }
3003
3004         if (conf->verify_client_cert_cmd && !conf->verify_tmp_dir) {
3005                 ERROR(LOG_PREFIX ": You MUST set the verify directory in order to use verify_client_cmd");
3006                 goto error;
3007         }
3008
3009 #ifdef SSL_OP_NO_TLSv1_2
3010         /*
3011          *      OpenSSL 1.0.1f and 1.0.1g get the MS-MPPE keys wrong.
3012          */
3013 #if (OPENSSL_VERSION_NUMBER >= 0x10010060L) && (OPENSSL_VERSION_NUMBER < 0x10010060L)
3014         conf->disable_tlsv1_2 = true;
3015         WARN(LOG_PREFIX ": Disabling TLSv1.2 due to OpenSSL bugs");
3016 #endif
3017 #endif
3018
3019         /*
3020          *      Cache conf in cs in case we're asked to parse this again.
3021          */
3022         cf_data_add(cs, "tls-conf", conf, NULL);
3023
3024         return conf;
3025 }
3026
3027 fr_tls_server_conf_t *tls_client_conf_parse(CONF_SECTION *cs)
3028 {
3029         fr_tls_server_conf_t *conf;
3030
3031         conf = cf_data_find(cs, "tls-conf");
3032         if (conf) {
3033                 DEBUG2(LOG_PREFIX ": Using cached TLS configuration from previous invocation");
3034                 return conf;
3035         }
3036
3037         conf = tls_server_conf_alloc(cs);
3038
3039         if (cf_section_parse(cs, conf, tls_client_config) < 0) {
3040         error:
3041                 talloc_free(conf);
3042                 return NULL;
3043         }
3044
3045         /*
3046          *      Save people from their own stupidity.
3047          */
3048         if (conf->fragment_size < 100) conf->fragment_size = 100;
3049
3050         /*
3051          *      Initialize TLS
3052          */
3053         conf->ctx = tls_init_ctx(conf, 1);
3054         if (conf->ctx == NULL) {
3055                 goto error;
3056         }
3057
3058         {
3059                 char *dh_file;
3060
3061                 memcpy(&dh_file, &conf->dh_file, sizeof(dh_file));
3062                 if (load_dh_params(conf->ctx, dh_file) < 0) {
3063                         goto error;
3064                 }
3065         }
3066
3067         cf_data_add(cs, "tls-conf", conf, NULL);
3068
3069         return conf;
3070 }
3071
3072 int tls_success(tls_session_t *ssn, REQUEST *request)
3073 {
3074         VALUE_PAIR *vp, *vps = NULL;
3075         fr_tls_server_conf_t *conf;
3076         TALLOC_CTX *talloc_ctx;
3077
3078         conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssn->ssl, FR_TLS_EX_INDEX_CONF);
3079         rad_assert(conf != NULL);
3080
3081         talloc_ctx = SSL_get_ex_data(ssn->ssl, FR_TLS_EX_INDEX_TALLOC);
3082
3083         /*
3084          *      If there's no session resumption, delete the entry
3085          *      from the cache.  This means either it's disabled
3086          *      globally for this SSL context, OR we were told to
3087          *      disable it for this user.
3088          *
3089          *      This also means you can't turn it on just for one
3090          *      user.
3091          */
3092         if ((!ssn->allow_session_resumption) ||
3093             (((vp = fr_pair_find_by_num(request->config, PW_ALLOW_SESSION_RESUMPTION, 0, TAG_ANY)) != NULL) &&
3094              (vp->vp_integer == 0))) {
3095                 SSL_CTX_remove_session(ssn->ctx,
3096                                        ssn->ssl_session);
3097                 ssn->allow_session_resumption = false;
3098
3099                 /*
3100                  *      If we're in a resumed session and it's
3101                  *      not allowed,
3102                  */
3103                 if (SSL_session_reused(ssn->ssl)) {
3104                         RDEBUG("Forcibly stopping session resumption as it is not allowed");
3105                         return -1;
3106                 }
3107
3108         /*
3109          *      Else resumption IS allowed, so we store the
3110          *      user data in the cache.
3111          */
3112         } else if (!SSL_session_reused(ssn->ssl)) {
3113                 VALUE_PAIR **certs;
3114                 char buffer[2 * MAX_SESSION_SIZE + 1];
3115
3116                 tls_session_id(ssn->ssl_session, buffer, MAX_SESSION_SIZE);
3117
3118                 vp = fr_pair_list_copy_by_num(talloc_ctx, request->reply->vps, PW_USER_NAME, 0, TAG_ANY);
3119                 if (vp) fr_pair_add(&vps, vp);
3120
3121                 vp = fr_pair_list_copy_by_num(talloc_ctx, request->packet->vps, PW_STRIPPED_USER_NAME, 0, TAG_ANY);
3122                 if (vp) fr_pair_add(&vps, vp);
3123
3124                 vp = fr_pair_list_copy_by_num(talloc_ctx, request->packet->vps, PW_STRIPPED_USER_DOMAIN, 0, TAG_ANY);
3125                 if (vp) fr_pair_add(&vps, vp);
3126
3127                 vp = fr_pair_list_copy_by_num(talloc_ctx, request->reply->vps, PW_CHARGEABLE_USER_IDENTITY, 0, TAG_ANY);
3128                 if (vp) fr_pair_add(&vps, vp);
3129
3130                 vp = fr_pair_list_copy_by_num(talloc_ctx, request->reply->vps, PW_CACHED_SESSION_POLICY, 0, TAG_ANY);
3131                 if (vp) fr_pair_add(&vps, vp);
3132
3133                 certs = (VALUE_PAIR **)SSL_get_ex_data(ssn->ssl, fr_tls_ex_index_certs);
3134
3135                 /*
3136                  *      Hmm... the certs should probably be session data.
3137                  */
3138                 if (certs) {
3139                         /*
3140                          *      @todo: some go into reply, others into
3141                          *      request
3142                          */
3143                         fr_pair_add(&vps, fr_pair_list_copy(talloc_ctx, *certs));
3144
3145                         /*
3146                          *      Save the certs in the packet, so that we can see them.
3147                          */
3148                         fr_pair_add(&request->packet->vps, fr_pair_list_copy(request->packet, *certs));
3149                 }
3150
3151                 if (vps) {
3152                         SSL_SESSION_set_ex_data(ssn->ssl_session, fr_tls_ex_index_vps, vps);
3153                         rdebug_pair_list(L_DBG_LVL_2, request, vps, "  caching ");
3154
3155                         if (conf->session_cache_path) {
3156                                 /* write the VPs to the cache file */
3157                                 char filename[256], buf[1024];
3158                                 FILE *vp_file;
3159
3160                                 RDEBUG2("Saving session %s in the disk cache", buffer);
3161
3162                                 snprintf(filename, sizeof(filename), "%s%c%s.vps", conf->session_cache_path,
3163                                          FR_DIR_SEP, buffer);
3164                                 vp_file = fopen(filename, "w");
3165                                 if (vp_file == NULL) {
3166                                         RWDEBUG("Could not write session VPs to persistent cache: %s",
3167                                                 fr_syserror(errno));
3168                                 } else {
3169                                         VALUE_PAIR *prev = NULL;
3170                                         vp_cursor_t cursor;
3171                                         /* generate a dummy user-style entry which is easy to read back */
3172                                         fprintf(vp_file, "# SSL cached session\n");
3173                                         fprintf(vp_file, "%s\n\t", buffer);
3174
3175                                         for (vp = fr_cursor_init(&cursor, &vps);
3176                                              vp;
3177                                              vp = fr_cursor_next(&cursor)) {
3178                                                 /*
3179                                                  *      Terminate the previous line.
3180                                                  */
3181                                                 if (prev) fprintf(vp_file, ",\n\t");
3182
3183                                                 /*
3184                                                  *      Write this one.
3185                                                  */
3186                                                 vp_prints(buf, sizeof(buf), vp);
3187                                                 fputs(buf, vp_file);
3188                                                 prev = vp;
3189                                         }
3190
3191                                         /*
3192                                          *      Terminate the final line.
3193                                          */
3194                                         fprintf(vp_file, "\n");
3195                                         fclose(vp_file);
3196                                 }
3197                         } else {
3198                                 RDEBUG("Failed to find 'persist_dir' in TLS configuration.  Session will not be cached on disk.");
3199                         }
3200                 } else {
3201                         RDEBUG2("No information to cache: session caching will be disabled for session %s", buffer);
3202                         SSL_CTX_remove_session(ssn->ctx, ssn->ssl_session);
3203                 }
3204
3205         /*
3206          *      Else the session WAS allowed.  Copy the cached reply.
3207          */
3208         } else {
3209                 char buffer[2 * MAX_SESSION_SIZE + 1];
3210
3211                 tls_session_id(ssn->ssl_session, buffer, MAX_SESSION_SIZE);
3212
3213                 /*
3214                  *      The "restore VPs from OpenSSL cache" code is
3215                  *      now in eaptls_process()
3216                  */
3217
3218                 if (conf->session_cache_path) {
3219                         /* "touch" the cached session/vp file */
3220                         char filename[256];
3221
3222                         snprintf(filename, sizeof(filename), "%s%c%s.asn1",
3223                                  conf->session_cache_path, FR_DIR_SEP, buffer);
3224                         utime(filename, NULL);
3225                         snprintf(filename, sizeof(filename), "%s%c%s.vps",
3226                                  conf->session_cache_path, FR_DIR_SEP, buffer);
3227                         utime(filename, NULL);
3228                 }
3229
3230                 /*
3231                  *      Mark the request as resumed.
3232                  */
3233                 pair_make_request("EAP-Session-Resumed", "1", T_OP_SET);
3234         }
3235
3236         return 0;
3237 }
3238
3239
3240 void tls_fail(tls_session_t *ssn)
3241 {
3242         /*
3243          *      Force the session to NOT be cached.
3244          */
3245         SSL_CTX_remove_session(ssn->ctx, ssn->ssl_session);
3246 }
3247
3248 fr_tls_status_t tls_application_data(tls_session_t *ssn, REQUEST *request)
3249
3250 {
3251         int err;
3252         VALUE_PAIR **certs;
3253
3254         /*
3255          *      Decrypt the complete record.
3256          */
3257         err = BIO_write(ssn->into_ssl, ssn->dirty_in.data,
3258                         ssn->dirty_in.used);
3259         if (err != (int) ssn->dirty_in.used) {
3260                 record_init(&ssn->dirty_in);
3261                 RDEBUG("Failed writing %zd bytes to SSL BIO: %d", ssn->dirty_in.used, err);
3262                 return FR_TLS_FAIL;
3263         }
3264
3265         /*
3266          *      Clear the dirty buffer now that we are done with it
3267          *      and init the clean_out buffer to store decrypted data
3268          */
3269         record_init(&ssn->dirty_in);
3270         record_init(&ssn->clean_out);
3271
3272         /*
3273          *      Read (and decrypt) the tunneled data from the
3274          *      SSL session, and put it into the decrypted
3275          *      data buffer.
3276          */
3277         err = SSL_read(ssn->ssl, ssn->clean_out.data, sizeof(ssn->clean_out.data));
3278         if (err < 0) {
3279                 int code;
3280
3281                 RDEBUG("SSL_read Error");
3282
3283                 code = SSL_get_error(ssn->ssl, err);
3284                 switch (code) {
3285                 case SSL_ERROR_WANT_READ:
3286                         DEBUG("Error in fragmentation logic: SSL_WANT_READ");
3287                         return FR_TLS_MORE_FRAGMENTS;
3288
3289                 case SSL_ERROR_WANT_WRITE:
3290                         DEBUG("Error in fragmentation logic: SSL_WANT_WRITE");
3291                         break;
3292
3293                 default:
3294                         REDEBUG("Error in fragmentation logic");
3295                         tls_error_io_log(request, ssn, err,
3296                                          "Failed in " STRINGIFY(__FUNCTION__) " (SSL_read)");
3297                         break;
3298                 }
3299                 return FR_TLS_FAIL;
3300         }
3301
3302         if (err == 0) RWDEBUG("No data inside of the tunnel");
3303
3304         /*
3305          *      Passed all checks, successfully decrypted data
3306          */
3307         ssn->clean_out.used = err;
3308
3309         /*
3310          *      Add the certificates to intermediate packets, so that
3311          *      the inner tunnel policies can use them.
3312          */
3313         certs = (VALUE_PAIR **)SSL_get_ex_data(ssn->ssl, fr_tls_ex_index_certs);
3314
3315         if (certs) fr_pair_add(&request->packet->vps, fr_pair_list_copy(request->packet, *certs));
3316
3317         return FR_TLS_OK;
3318 }
3319
3320
3321 /*
3322  * Acknowledge received is for one of the following messages sent earlier
3323  * 1. Handshake completed Message, so now send, EAP-Success
3324  * 2. Alert Message, now send, EAP-Failure
3325  * 3. Fragment Message, now send, next Fragment
3326  */
3327 fr_tls_status_t tls_ack_handler(tls_session_t *ssn, REQUEST *request)
3328 {
3329         if (ssn == NULL){
3330                 REDEBUG("Unexpected ACK received:  No ongoing SSL session");
3331                 return FR_TLS_INVALID;
3332         }
3333         if (!ssn->info.initialized) {
3334                 RDEBUG("No SSL info available.  Waiting for more SSL data");
3335                 return FR_TLS_REQUEST;
3336         }
3337
3338         if ((ssn->info.content_type == handshake) && (ssn->info.origin == 0)) {
3339                 REDEBUG("Unexpected ACK received:  We sent no previous messages");
3340                 return FR_TLS_INVALID;
3341         }
3342
3343         switch (ssn->info.content_type) {
3344         case alert:
3345                 RDEBUG2("Peer ACKed our alert");
3346                 return FR_TLS_FAIL;
3347
3348         case handshake:
3349                 if ((ssn->info.handshake_type == handshake_finished) && (ssn->dirty_out.used == 0)) {
3350                         RDEBUG2("Peer ACKed our handshake fragment.  handshake is finished");
3351
3352                         /*
3353                          *      From now on all the content is
3354                          *      application data set it here as nobody else
3355                          *      sets it.
3356                          */
3357                         ssn->info.content_type = application_data;
3358                         return FR_TLS_SUCCESS;
3359                 } /* else more data to send */
3360
3361                 RDEBUG2("Peer ACKed our handshake fragment");
3362                 /* Fragmentation handler, send next fragment */
3363                 return FR_TLS_REQUEST;
3364
3365         case application_data:
3366                 RDEBUG2("Peer ACKed our application data fragment");
3367                 return FR_TLS_REQUEST;
3368
3369                 /*
3370                  *      For the rest of the conditions, switch over
3371                  *      to the default section below.
3372                  */
3373         default:
3374                 REDEBUG("Invalid ACK received: %d", ssn->info.content_type);
3375                 return FR_TLS_INVALID;
3376         }
3377 }
3378 #endif  /* WITH_TLS */
3379