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