Intermediate variable to avoid compiler warning
[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         if (request) {
980                 RDEBUG2("%s", tls_session->info.info_description);
981         } else {
982                 DEBUG2("%s", tls_session->info.info_description);
983         }
984 }
985
986 static CONF_PARSER cache_config[] = {
987         { "enable", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, session_cache_enable), "no" },
988
989         { "lifetime", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, session_timeout), "24" },
990         { "name", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, session_id_name), NULL },
991
992         { "max_entries", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, session_cache_size), "255" },
993         { "persist_dir", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, session_cache_path), NULL },
994         CONF_PARSER_TERMINATOR
995 };
996
997 static CONF_PARSER verify_config[] = {
998         { "tmpdir", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, verify_tmp_dir), NULL },
999         { "client", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, verify_client_cert_cmd), NULL },
1000         CONF_PARSER_TERMINATOR
1001 };
1002
1003 #ifdef HAVE_OPENSSL_OCSP_H
1004 static CONF_PARSER ocsp_config[] = {
1005         { "enable", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_enable), "no" },
1006         { "override_cert_url", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_override_url), "no" },
1007         { "url", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, ocsp_url), NULL },
1008         { "use_nonce", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_use_nonce), "yes" },
1009         { "timeout", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, ocsp_timeout), "yes" },
1010         { "softfail", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_softfail), "no" },
1011         CONF_PARSER_TERMINATOR
1012 };
1013 #endif
1014
1015 static CONF_PARSER tls_server_config[] = {
1016         { "rsa_key_exchange", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, rsa_key), "no" },
1017         { "dh_key_exchange", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, dh_key), "yes" },
1018         { "rsa_key_length", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, rsa_key_length), "512" },
1019         { "dh_key_length", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, dh_key_length), "512" },
1020         { "verify_depth", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, verify_depth), "0" },
1021         { "CA_path", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT | PW_TYPE_DEPRECATED, fr_tls_server_conf_t, ca_path), NULL },
1022         { "ca_path", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_path), NULL },
1023         { "pem_file_type", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, file_type), "yes" },
1024         { "private_key_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, private_key_file), NULL },
1025         { "certificate_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, certificate_file), NULL },
1026         { "CA_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT | PW_TYPE_DEPRECATED, fr_tls_server_conf_t, ca_file), NULL },
1027         { "ca_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_file), NULL },
1028         { "private_key_password", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_SECRET, fr_tls_server_conf_t, private_key_password), NULL },
1029 #ifdef PSK_MAX_IDENTITY_LEN
1030         { "psk_identity", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, psk_identity), NULL },
1031         { "psk_hexphrase", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_SECRET, fr_tls_server_conf_t, psk_password), NULL },
1032         { "psk_query", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, psk_query), NULL },
1033 #endif
1034         { "dh_file", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, dh_file), NULL },
1035         { "random_file", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, random_file), NULL },
1036         { "fragment_size", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, fragment_size), "1024" },
1037         { "include_length", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, include_length), "yes" },
1038         { "check_crl", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, check_crl), "no" },
1039 #ifdef X509_V_FLAG_CRL_CHECK_ALL
1040         { "check_all_crl", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, check_all_crl), "no" },
1041 #endif
1042         { "allow_expired_crl", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, allow_expired_crl), NULL },
1043         { "check_cert_cn", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_cn), NULL },
1044         { "cipher_list", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, cipher_list), NULL },
1045         { "check_cert_issuer", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_issuer), NULL },
1046         { "require_client_cert", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, require_client_cert), NULL },
1047
1048 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
1049 #ifndef OPENSSL_NO_ECDH
1050         { "ecdh_curve", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, ecdh_curve), "prime256v1" },
1051 #endif
1052 #endif
1053
1054 #ifdef SSL_OP_NO_TLSv1
1055         { "disable_tlsv1", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1), NULL },
1056 #endif
1057
1058 #ifdef SSL_OP_NO_TLSv1_1
1059         { "disable_tlsv1_1", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1_1), NULL },
1060 #endif
1061
1062 #ifdef SSL_OP_NO_TLSv1_2
1063         { "disable_tlsv1_2", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1_2), NULL },
1064 #endif
1065
1066         { "cache", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) cache_config },
1067
1068         { "verify", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) verify_config },
1069
1070 #ifdef HAVE_OPENSSL_OCSP_H
1071         { "ocsp", FR_CONF_POINTER(PW_TYPE_SUBSECTION, NULL), (void const *) ocsp_config },
1072 #endif
1073         CONF_PARSER_TERMINATOR
1074 };
1075
1076
1077 static CONF_PARSER tls_client_config[] = {
1078         { "rsa_key_exchange", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, rsa_key), "no" },
1079         { "dh_key_exchange", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, dh_key), "yes" },
1080         { "rsa_key_length", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, rsa_key_length), "512" },
1081         { "dh_key_length", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, dh_key_length), "512" },
1082         { "verify_depth", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, verify_depth), "0" },
1083         { "ca_path", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_path), NULL },
1084         { "pem_file_type", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, file_type), "yes" },
1085         { "private_key_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, private_key_file), NULL },
1086         { "certificate_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, certificate_file), NULL },
1087         { "ca_file", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_file), NULL },
1088         { "private_key_password", FR_CONF_OFFSET(PW_TYPE_STRING | PW_TYPE_SECRET, fr_tls_server_conf_t, private_key_password), NULL },
1089         { "dh_file", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, dh_file), NULL },
1090         { "random_file", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, random_file), NULL },
1091         { "fragment_size", FR_CONF_OFFSET(PW_TYPE_INTEGER, fr_tls_server_conf_t, fragment_size), "1024" },
1092         { "include_length", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, include_length), "yes" },
1093         { "check_crl", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, check_crl), "no" },
1094         { "check_cert_cn", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_cn), NULL },
1095         { "cipher_list", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, cipher_list), NULL },
1096         { "check_cert_issuer", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_issuer), NULL },
1097
1098 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
1099 #ifndef OPENSSL_NO_ECDH
1100         { "ecdh_curve", FR_CONF_OFFSET(PW_TYPE_STRING, fr_tls_server_conf_t, ecdh_curve), "prime256v1" },
1101 #endif
1102 #endif
1103
1104 #ifdef SSL_OP_NO_TLSv1
1105         { "disable_tlsv1", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1), NULL },
1106 #endif
1107
1108 #ifdef SSL_OP_NO_TLSv1_1
1109         { "disable_tlsv1_1", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1_1), NULL },
1110 #endif
1111
1112 #ifdef SSL_OP_NO_TLSv1_2
1113         { "disable_tlsv1_2", FR_CONF_OFFSET(PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1_2), NULL },
1114 #endif
1115         CONF_PARSER_TERMINATOR
1116 };
1117
1118
1119 /*
1120  *      TODO: Check for the type of key exchange * like conf->dh_key
1121  */
1122 static int load_dh_params(SSL_CTX *ctx, char *file)
1123 {
1124         DH *dh = NULL;
1125         BIO *bio;
1126
1127         if (!file) return 0;
1128
1129         if ((bio = BIO_new_file(file, "r")) == NULL) {
1130                 ERROR(LOG_PREFIX ": Unable to open DH file - %s", file);
1131                 return -1;
1132         }
1133
1134         dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
1135         BIO_free(bio);
1136         if (!dh) {
1137                 WARN(LOG_PREFIX ": Unable to set DH parameters.  DH cipher suites may not work!");
1138                 WARN(LOG_PREFIX ": Fix this by running the OpenSSL command listed in eap.conf");
1139                 return 0;
1140         }
1141
1142         if (SSL_CTX_set_tmp_dh(ctx, dh) < 0) {
1143                 ERROR(LOG_PREFIX ": Unable to set DH parameters");
1144                 DH_free(dh);
1145                 return -1;
1146         }
1147
1148         DH_free(dh);
1149         return 0;
1150 }
1151
1152
1153 /*
1154  *      Print debugging messages, and free data.
1155  */
1156 static void cbtls_remove_session(SSL_CTX *ctx, SSL_SESSION *sess)
1157 {
1158         char                    buffer[2 * MAX_SESSION_SIZE + 1];
1159         fr_tls_server_conf_t    *conf;
1160
1161         tls_session_id(sess, buffer, MAX_SESSION_SIZE);
1162
1163         conf = (fr_tls_server_conf_t *)SSL_CTX_get_app_data(ctx);
1164         if (!conf) {
1165                 DEBUG(LOG_PREFIX ": Failed to find TLS configuration in session");
1166                 return;
1167         }
1168
1169         {
1170                 int rv;
1171                 char filename[256];
1172
1173                 DEBUG2(LOG_PREFIX ": Removing session %s from the cache", buffer);
1174
1175                 /* remove session and any cached VPs */
1176                 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
1177                          conf->session_cache_path, FR_DIR_SEP, buffer);
1178                 rv = unlink(filename);
1179                 if (rv != 0) {
1180                         DEBUG2(LOG_PREFIX ": Could not remove persisted session file %s: %s",
1181                                filename, fr_syserror(errno));
1182                 }
1183                 /* VPs might be absent; might not have been written to disk yet */
1184                 snprintf(filename, sizeof(filename), "%s%c%s.vps",
1185                          conf->session_cache_path, FR_DIR_SEP, buffer);
1186                 unlink(filename);
1187         }
1188
1189         return;
1190 }
1191
1192 static int cbtls_new_session(SSL *ssl, SSL_SESSION *sess)
1193 {
1194         char                    buffer[2 * MAX_SESSION_SIZE + 1];
1195         fr_tls_server_conf_t    *conf;
1196         unsigned char           *sess_blob = NULL;
1197
1198         REQUEST                 *request = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_REQUEST);
1199
1200         conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1201         if (!conf) {
1202                 RWDEBUG("Failed to find TLS configuration in session");
1203                 return 0;
1204         }
1205
1206         tls_session_id(sess, buffer, MAX_SESSION_SIZE);
1207
1208         {
1209                 int fd, rv, todo, blob_len;
1210                 char filename[256];
1211                 unsigned char *p;
1212
1213                 RDEBUG2("Serialising session %s, and storing in cache", buffer);
1214
1215                 /* find out what length data we need */
1216                 blob_len = i2d_SSL_SESSION(sess, NULL);
1217                 if (blob_len < 1) {
1218                         /* something went wrong */
1219                         RWDEBUG("Session serialisation failed, couldn't determine required buffer length");
1220                         return 0;
1221                 }
1222
1223
1224                 /* Do not convert to TALLOC - Thread safety */
1225                 /* alloc and convert to ASN.1 */
1226                 sess_blob = malloc(blob_len);
1227                 if (!sess_blob) {
1228                         RWDEBUG("Session serialisation failed, couldn't allocate buffer (%d bytes)", blob_len);
1229                         return 0;
1230                 }
1231                 /* openssl mutates &p */
1232                 p = sess_blob;
1233                 rv = i2d_SSL_SESSION(sess, &p);
1234                 if (rv != blob_len) {
1235                         RWDEBUG("Session serialisation failed");
1236                         goto error;
1237                 }
1238
1239                 /* open output file */
1240                 snprintf(filename, sizeof(filename), "%s%c%s.asn1",
1241                          conf->session_cache_path, FR_DIR_SEP, buffer);
1242                 fd = open(filename, O_RDWR|O_CREAT|O_EXCL, 0600);
1243                 if (fd < 0) {
1244                         RERROR("Session serialisation failed, failed opening session file %s: %s",
1245                               filename, fr_syserror(errno));
1246                         goto error;
1247                 }
1248
1249                 todo = blob_len;
1250                 p = sess_blob;
1251                 while (todo > 0) {
1252                         rv = write(fd, p, todo);
1253                         if (rv < 1) {
1254                                 RWDEBUG("Failed writing session: %s", fr_syserror(errno));
1255                                 close(fd);
1256                                 goto error;
1257                         }
1258                         p += rv;
1259                         todo -= rv;
1260                 }
1261                 close(fd);
1262                 RWDEBUG("Wrote session %s to %s (%d bytes)", buffer, filename, blob_len);
1263         }
1264
1265 error:
1266         free(sess_blob);
1267
1268         return 0;
1269 }
1270
1271 static SSL_SESSION *cbtls_get_session(SSL *ssl, unsigned char *data, int len, int *copy)
1272 {
1273         size_t                  size;
1274         char                    buffer[2 * MAX_SESSION_SIZE + 1];
1275         fr_tls_server_conf_t    *conf;
1276         TALLOC_CTX              *talloc_ctx;
1277
1278         SSL_SESSION             *sess = NULL;
1279         unsigned char           *sess_data = NULL;
1280         PAIR_LIST               *pairlist = NULL;
1281
1282         REQUEST                 *request = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_REQUEST);
1283
1284         rad_assert(request != NULL);
1285
1286         size = len;
1287         if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
1288
1289         fr_bin2hex(buffer, data, size);
1290
1291         RDEBUG2("Peer requested cached session: %s", buffer);
1292
1293         *copy = 0;
1294
1295         conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1296         if (!conf) {
1297                 RWDEBUG("Failed to find TLS configuration in session");
1298                 return NULL;
1299         }
1300
1301         talloc_ctx = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_TALLOC);
1302
1303         {
1304                 int             rv, fd, todo;
1305                 char            filename[256];
1306                 unsigned char   *p;
1307                 unsigned char const *q;
1308                 struct stat     st;
1309                 VALUE_PAIR      *vps = NULL;
1310
1311                 /* read in the cached VPs from the .vps file */
1312                 snprintf(filename, sizeof(filename), "%s%c%s.vps",
1313                          conf->session_cache_path, FR_DIR_SEP, buffer);
1314                 rv = pairlist_read(talloc_ctx, filename, &pairlist, 1);
1315                 if (rv < 0) {
1316                         /* not safe to un-persist a session w/o VPs */
1317                         RWDEBUG("Failed loading persisted VPs for session %s", buffer);
1318                         goto err;
1319                 }
1320
1321                 /* load the actual SSL session */
1322                 snprintf(filename, sizeof(filename), "%s%c%s.asn1", conf->session_cache_path, FR_DIR_SEP, buffer);
1323                 fd = open(filename, O_RDONLY);
1324                 if (fd < 0) {
1325                         RWDEBUG("No persisted session file %s: %s", filename, fr_syserror(errno));
1326                         goto err;
1327                 }
1328
1329                 rv = fstat(fd, &st);
1330                 if (rv < 0) {
1331                         RWDEBUG("Failed stating persisted session file %s: %s", filename, fr_syserror(errno));
1332                         close(fd);
1333                         goto err;
1334                 }
1335
1336                 sess_data = talloc_array(NULL, unsigned char, st.st_size);
1337                 if (!sess_data) {
1338                         RWDEBUG("Failed allocating buffer for persisted session (%d bytes)", (int) st.st_size);
1339                         close(fd);
1340                         goto err;
1341                 }
1342
1343                 p = sess_data;
1344                 todo = st.st_size;
1345                 while (todo > 0) {
1346                         rv = read(fd, p, todo);
1347                         if (rv < 1) {
1348                                 RWDEBUG("Failed reading persisted session: %s", fr_syserror(errno));
1349                                 close(fd);
1350                                 goto err;
1351                         }
1352                         todo -= rv;
1353                         p += rv;
1354                 }
1355                 close(fd);
1356
1357                 /* openssl mutates &p */
1358                 q = sess_data;
1359                 sess = d2i_SSL_SESSION(NULL, &q, st.st_size);
1360
1361                 if (!sess) {
1362                         RWDEBUG("Failed loading persisted session: %s", ERR_error_string(ERR_get_error(), NULL));
1363                         goto err;
1364                 }
1365
1366                 /* move the cached VPs into the session */
1367                 fr_pair_list_mcopy_by_num(talloc_ctx, &vps, &pairlist->reply, 0, 0, TAG_ANY);
1368
1369                 SSL_SESSION_set_ex_data(sess, fr_tls_ex_index_vps, vps);
1370                 RWDEBUG("Successfully restored session %s", buffer);
1371                 rdebug_pair_list(L_DBG_LVL_2, request, vps, "reply:");
1372         }
1373 err:
1374         if (sess_data) talloc_free(sess_data);
1375         if (pairlist) pairlist_free(&pairlist);
1376
1377         return sess;
1378 }
1379
1380 #ifdef HAVE_OPENSSL_OCSP_H
1381
1382 /** Extract components of OCSP responser URL from a certificate
1383  *
1384  * @param[in] cert to extract URL from.
1385  * @param[out] host_out Portion of the URL (must be freed with free()).
1386  * @param[out] port_out Port portion of the URL (must be freed with free()).
1387  * @param[out] path_out Path portion of the URL (must be freed with free()).
1388  * @param[out] is_https Whether the responder should be contacted using https.
1389  * @return
1390  *      - 0 if no valid URL is contained in the certificate.
1391  *      - 1 if a URL was found and parsed.
1392  *      - -1 if at least one URL was found, but none could be parsed.
1393  */
1394 static int ocsp_parse_cert_url(X509 *cert, char **host_out, char **port_out,
1395                                char **path_out, int *is_https)
1396 {
1397         int                     i;
1398         bool                    found_uri = false;
1399
1400         AUTHORITY_INFO_ACCESS   *aia;
1401         ACCESS_DESCRIPTION      *ad;
1402
1403         aia = X509_get_ext_d2i(cert, NID_info_access, NULL, NULL);
1404
1405         for (i = 0; i < sk_ACCESS_DESCRIPTION_num(aia); i++) {
1406                 ad = sk_ACCESS_DESCRIPTION_value(aia, i);
1407                 if (OBJ_obj2nid(ad->method) != NID_ad_OCSP) continue;
1408                 if (ad->location->type != GEN_URI) continue;
1409                 found_uri = true;
1410
1411                 if (OCSP_parse_url((char *) ad->location->d.ia5->data, host_out,
1412                                    port_out, path_out, is_https)) return 1;
1413         }
1414         return found_uri ? -1 : 0;
1415 }
1416
1417 /*
1418  * This function sends a OCSP request to a defined OCSP responder
1419  * and checks the OCSP response for correctness.
1420  */
1421
1422 /* Maximum leeway in validity period: default 5 minutes */
1423 #define MAX_VALIDITY_PERIOD     (5 * 60)
1424
1425 static int ocsp_check(REQUEST *request, X509_STORE *store, X509 *issuer_cert, X509 *client_cert,
1426                       fr_tls_server_conf_t *conf)
1427 {
1428         OCSP_CERTID     *certid;
1429         OCSP_REQUEST    *req;
1430         OCSP_RESPONSE   *resp = NULL;
1431         OCSP_BASICRESP  *bresp = NULL;
1432         char            *host = NULL;
1433         char            *port = NULL;
1434         char            *path = NULL;
1435         char            hostheader[1024];
1436         int             use_ssl = -1;
1437         long            nsec = MAX_VALIDITY_PERIOD, maxage = -1;
1438         BIO             *cbio, *bio_out;
1439         int             ocsp_ok = 0;
1440         int             status;
1441         ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
1442         int             reason;
1443 #if OPENSSL_VERSION_NUMBER >= 0x1000003f
1444         OCSP_REQ_CTX    *ctx;
1445         int             rc;
1446         struct timeval  now;
1447         struct timeval  when;
1448 #endif
1449
1450         /*
1451          * Create OCSP Request
1452          */
1453         certid = OCSP_cert_to_id(NULL, client_cert, issuer_cert);
1454         req = OCSP_REQUEST_new();
1455         OCSP_request_add0_id(req, certid);
1456         if (conf->ocsp_use_nonce) OCSP_request_add1_nonce(req, NULL, 8);
1457
1458         /*
1459          * Send OCSP Request and get OCSP Response
1460          */
1461
1462         /* Get OCSP responder URL */
1463         if (conf->ocsp_override_url) {
1464                 char *url;
1465
1466         use_ocsp_url:
1467                 memcpy(&url, &conf->ocsp_url, sizeof(url));
1468                 /* Reading the libssl src, they do a strdup on the URL, so it could of been const *sigh* */
1469                 OCSP_parse_url(url, &host, &port, &path, &use_ssl);
1470                 if (!host || !port || !path) {
1471                         RWDEBUG("ocsp: Host or port or path missing from configured URL \"%s\".  Not doing OCSP", url);
1472                         ocsp_ok = 2;
1473                         goto ocsp_skip;
1474                 }
1475         } else {
1476                 int ret;
1477
1478                 ret = ocsp_parse_cert_url(client_cert, &host, &port, &path, &use_ssl);
1479                 switch (ret) {
1480                 case -1:
1481                         RWDEBUG("ocsp: Invalid URL in certificate.  Not doing OCSP");
1482                         break;
1483
1484                 case 0:
1485                         if (conf->ocsp_url) {
1486                                 RWDEBUG("ocsp: No OCSP URL in certificate, falling back to configured URL");
1487                                 goto use_ocsp_url;
1488                         }
1489                         RWDEBUG("ocsp: No OCSP URL in certificate.  Not doing OCSP");
1490                         ocsp_ok = 2;
1491                         goto ocsp_skip;
1492
1493                 case 1:
1494                         break;
1495                 }
1496         }
1497
1498         RDEBUG2("ocsp: Using responder URL \"http://%s:%s%s\"", host, port, path);
1499
1500         /* Check host and port length are sane, then create Host: HTTP header */
1501         if ((strlen(host) + strlen(port) + 2) > sizeof(hostheader)) {
1502                 RWDEBUG("ocsp: Host and port too long");
1503                 goto ocsp_skip;
1504         }
1505         snprintf(hostheader, sizeof(hostheader), "%s:%s", host, port);
1506
1507         /* Setup BIO socket to OCSP responder */
1508         cbio = BIO_new_connect(host);
1509
1510         bio_out = NULL;
1511         if (rad_debug_lvl) {
1512                 if (default_log.dst == L_DST_STDOUT) {
1513                         bio_out = BIO_new_fp(stdout, BIO_NOCLOSE);
1514                 } else if (default_log.dst == L_DST_STDERR) {
1515                         bio_out = BIO_new_fp(stderr, BIO_NOCLOSE);
1516                 }
1517         }
1518
1519         BIO_set_conn_port(cbio, port);
1520 #if OPENSSL_VERSION_NUMBER < 0x1000003f
1521         BIO_do_connect(cbio);
1522
1523         /* Send OCSP request and wait for response */
1524         resp = OCSP_sendreq_bio(cbio, path, req);
1525         if (!resp) {
1526                 REDEBUG("ocsp: Couldn't get OCSP response");
1527                 ocsp_ok = 2;
1528                 goto ocsp_end;
1529         }
1530 #else
1531         if (conf->ocsp_timeout)
1532                 BIO_set_nbio(cbio, 1);
1533
1534         rc = BIO_do_connect(cbio);
1535         if ((rc <= 0) && ((!conf->ocsp_timeout) || !BIO_should_retry(cbio))) {
1536                 REDEBUG("ocsp: Couldn't connect to OCSP responder");
1537                 ocsp_ok = 2;
1538                 goto ocsp_end;
1539         }
1540
1541         ctx = OCSP_sendreq_new(cbio, path, NULL, -1);
1542         if (!ctx) {
1543                 REDEBUG("ocsp: Couldn't create OCSP request");
1544                 ocsp_ok = 2;
1545                 goto ocsp_end;
1546         }
1547
1548         if (!OCSP_REQ_CTX_add1_header(ctx, "Host", hostheader)) {
1549                 REDEBUG("ocsp: Couldn't set Host header");
1550                 ocsp_ok = 2;
1551                 goto ocsp_end;
1552         }
1553
1554         if (!OCSP_REQ_CTX_set1_req(ctx, req)) {
1555                 REDEBUG("ocsp: Couldn't add data to OCSP request");
1556                 ocsp_ok = 2;
1557                 goto ocsp_end;
1558         }
1559
1560         gettimeofday(&when, NULL);
1561         when.tv_sec += conf->ocsp_timeout;
1562
1563         do {
1564                 rc = OCSP_sendreq_nbio(&resp, ctx);
1565                 if (conf->ocsp_timeout) {
1566                         gettimeofday(&now, NULL);
1567                         if (!timercmp(&now, &when, <))
1568                                 break;
1569                 }
1570         } while ((rc == -1) && BIO_should_retry(cbio));
1571
1572         if (conf->ocsp_timeout && (rc == -1) && BIO_should_retry(cbio)) {
1573                 REDEBUG("ocsp: Response timed out");
1574                 ocsp_ok = 2;
1575                 goto ocsp_end;
1576         }
1577
1578         OCSP_REQ_CTX_free(ctx);
1579
1580         if (rc == 0) {
1581                 REDEBUG("ocsp: Couldn't get OCSP response");
1582                 ocsp_ok = 2;
1583                 goto ocsp_end;
1584         }
1585 #endif
1586
1587         /* Verify OCSP response status */
1588         status = OCSP_response_status(resp);
1589         if (status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
1590                 REDEBUG("ocsp: Response status: %s", OCSP_response_status_str(status));
1591                 goto ocsp_end;
1592         }
1593         bresp = OCSP_response_get1_basic(resp);
1594         if (conf->ocsp_use_nonce && OCSP_check_nonce(req, bresp)!=1) {
1595                 REDEBUG("ocsp: Response has wrong nonce value");
1596                 goto ocsp_end;
1597         }
1598         if (OCSP_basic_verify(bresp, NULL, store, 0)!=1){
1599                 REDEBUG("ocsp: Couldn't verify OCSP basic response");
1600                 goto ocsp_end;
1601         }
1602
1603         /*      Verify OCSP cert status */
1604         if (!OCSP_resp_find_status(bresp, certid, &status, &reason, &rev, &thisupd, &nextupd)) {
1605                 REDEBUG("ocsp: No Status found");
1606                 goto ocsp_end;
1607         }
1608
1609         if (!OCSP_check_validity(thisupd, nextupd, nsec, maxage)) {
1610                 if (bio_out) {
1611                         BIO_puts(bio_out, "WARNING: Status times invalid.\n");
1612                         ERR_print_errors(bio_out);
1613                 }
1614                 goto ocsp_end;
1615         }
1616
1617         if (bio_out) {
1618                 BIO_puts(bio_out, "\tThis Update: ");
1619                 ASN1_GENERALIZEDTIME_print(bio_out, thisupd);
1620                 BIO_puts(bio_out, "\n");
1621                 if (nextupd) {
1622                         BIO_puts(bio_out, "\tNext Update: ");
1623                         ASN1_GENERALIZEDTIME_print(bio_out, nextupd);
1624                         BIO_puts(bio_out, "\n");
1625                 }
1626         }
1627
1628         switch (status) {
1629         case V_OCSP_CERTSTATUS_GOOD:
1630                 RDEBUG2("ocsp: Cert status: good");
1631                 ocsp_ok = 1;
1632                 break;
1633
1634         default:
1635                 /* REVOKED / UNKNOWN */
1636                 REDEBUG("ocsp: Cert status: %s", OCSP_cert_status_str(status));
1637                 if (reason != -1) REDEBUG("ocsp: Reason: %s", OCSP_crl_reason_str(reason));
1638
1639                 if (bio_out) {
1640                         BIO_puts(bio_out, "\tRevocation Time: ");
1641                         ASN1_GENERALIZEDTIME_print(bio_out, rev);
1642                         BIO_puts(bio_out, "\n");
1643                 }
1644                 break;
1645         }
1646
1647 ocsp_end:
1648         /* Free OCSP Stuff */
1649         OCSP_REQUEST_free(req);
1650         OCSP_RESPONSE_free(resp);
1651         free(host);
1652         free(port);
1653         free(path);
1654         BIO_free_all(cbio);
1655         if (bio_out) BIO_free(bio_out);
1656         OCSP_BASICRESP_free(bresp);
1657
1658  ocsp_skip:
1659         switch (ocsp_ok) {
1660         case 1:
1661                 RDEBUG2("ocsp: Certificate is valid");
1662                 break;
1663
1664         case 2:
1665                 if (conf->ocsp_softfail) {
1666                         RWDEBUG("ocsp: Unable to check certificate, assuming it's valid");
1667                         RWDEBUG("ocsp: This may be insecure");
1668                         ocsp_ok = 1;
1669                 } else {
1670                         REDEBUG("ocsp: Unable to check certificate, failing");
1671                         ocsp_ok = 0;
1672                 }
1673                 break;
1674
1675         default:
1676                 REDEBUG("ocsp: Certificate has been expired/revoked");
1677                 break;
1678         }
1679
1680         return ocsp_ok;
1681 }
1682 #endif  /* HAVE_OPENSSL_OCSP_H */
1683
1684 /*
1685  *      For creating certificate attributes.
1686  */
1687 static char const *cert_attr_names[8][2] = {
1688         { "TLS-Client-Cert-Serial",                     "TLS-Cert-Serial" },
1689         { "TLS-Client-Cert-Expiration",                 "TLS-Cert-Expiration" },
1690         { "TLS-Client-Cert-Subject",                    "TLS-Cert-Subject" },
1691         { "TLS-Client-Cert-Issuer",                     "TLS-Cert-Issuer" },
1692         { "TLS-Client-Cert-Common-Name",                "TLS-Cert-Common-Name" },
1693         { "TLS-Client-Cert-Subject-Alt-Name-Email",     "TLS-Cert-Subject-Alt-Name-Email" },
1694         { "TLS-Client-Cert-Subject-Alt-Name-Dns",       "TLS-Cert-Subject-Alt-Name-Dns" },
1695         { "TLS-Client-Cert-Subject-Alt-Name-Upn",       "TLS-Cert-Subject-Alt-Name-Upn" }
1696 };
1697
1698 #define FR_TLS_SERIAL           (0)
1699 #define FR_TLS_EXPIRATION       (1)
1700 #define FR_TLS_SUBJECT          (2)
1701 #define FR_TLS_ISSUER           (3)
1702 #define FR_TLS_CN               (4)
1703 #define FR_TLS_SAN_EMAIL        (5)
1704 #define FR_TLS_SAN_DNS          (6)
1705 #define FR_TLS_SAN_UPN          (7)
1706
1707 /*
1708  *      Before trusting a certificate, you must make sure that the
1709  *      certificate is 'valid'. There are several steps that your
1710  *      application can take in determining if a certificate is
1711  *      valid. Commonly used steps are:
1712  *
1713  *      1.Verifying the certificate's signature, and verifying that
1714  *      the certificate has been issued by a trusted Certificate
1715  *      Authority.
1716  *
1717  *      2.Verifying that the certificate is valid for the present date
1718  *      (i.e. it is being presented within its validity dates).
1719  *
1720  *      3.Verifying that the certificate has not been revoked by its
1721  *      issuing Certificate Authority, by checking with respect to a
1722  *      Certificate Revocation List (CRL).
1723  *
1724  *      4.Verifying that the credentials presented by the certificate
1725  *      fulfill additional requirements specific to the application,
1726  *      such as with respect to access control lists or with respect
1727  *      to OCSP (Online Certificate Status Processing).
1728  *
1729  *      NOTE: This callback will be called multiple times based on the
1730  *      depth of the root certificate chain
1731  */
1732 int cbtls_verify(int ok, X509_STORE_CTX *ctx)
1733 {
1734         char            subject[1024]; /* Used for the subject name */
1735         char            issuer[1024]; /* Used for the issuer name */
1736         char            attribute[1024];
1737         char            value[1024];
1738         char            common_name[1024];
1739         char            cn_str[1024];
1740         char            buf[64];
1741         X509            *client_cert;
1742         X509_CINF       *client_inf;
1743         STACK_OF(X509_EXTENSION) *ext_list;
1744         SSL             *ssl;
1745         int             err, depth, lookup, loc;
1746         fr_tls_server_conf_t *conf;
1747         int             my_ok = ok;
1748
1749         ASN1_INTEGER    *sn = NULL;
1750         ASN1_TIME       *asn_time = NULL;
1751         VALUE_PAIR      **certs;
1752         char **identity;
1753 #ifdef HAVE_OPENSSL_OCSP_H
1754         X509_STORE      *ocsp_store = NULL;
1755         X509            *issuer_cert;
1756 #endif
1757         VALUE_PAIR      *vp;
1758         TALLOC_CTX      *talloc_ctx;
1759
1760         REQUEST         *request;
1761
1762         client_cert = X509_STORE_CTX_get_current_cert(ctx);
1763         err = X509_STORE_CTX_get_error(ctx);
1764         depth = X509_STORE_CTX_get_error_depth(ctx);
1765
1766         lookup = depth;
1767
1768         /*
1769          *      Log client/issuing cert.  If there's an error, log
1770          *      issuing cert.
1771          */
1772         if ((lookup > 1) && !my_ok) lookup = 1;
1773
1774         /*
1775          * Retrieve the pointer to the SSL of the connection currently treated
1776          * and the application specific data stored into the SSL object.
1777          */
1778         ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
1779         conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1780         if (!conf) return 1;
1781
1782         request = (REQUEST *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_REQUEST);
1783         rad_assert(request != NULL);
1784         certs = (VALUE_PAIR **)SSL_get_ex_data(ssl, fr_tls_ex_index_certs);
1785
1786         identity = (char **)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_IDENTITY);
1787 #ifdef HAVE_OPENSSL_OCSP_H
1788         ocsp_store = (X509_STORE *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_STORE);
1789 #endif
1790
1791         talloc_ctx = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_TALLOC);
1792
1793         /*
1794          *      Get the Serial Number
1795          */
1796         buf[0] = '\0';
1797         sn = X509_get_serialNumber(client_cert);
1798
1799         RDEBUG2("Creating attributes from certificate OIDs");
1800         RINDENT();
1801
1802         /*
1803          *      For this next bit, we create the attributes *only* if
1804          *      we're at the client or issuing certificate, AND we
1805          *      have a user identity.  i.e. we don't create the
1806          *      attributes for RadSec connections.
1807          */
1808         if (certs && identity &&
1809             (lookup <= 1) && sn && ((size_t) sn->length < (sizeof(buf) / 2))) {
1810                 char *p = buf;
1811                 int i;
1812
1813                 for (i = 0; i < sn->length; i++) {
1814                         sprintf(p, "%02x", (unsigned int)sn->data[i]);
1815                         p += 2;
1816                 }
1817                 vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_SERIAL][lookup], buf, T_OP_SET);
1818                 rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
1819         }
1820
1821
1822         /*
1823          *      Get the Expiration Date
1824          */
1825         buf[0] = '\0';
1826         asn_time = X509_get_notAfter(client_cert);
1827         if (certs && identity && (lookup <= 1) && asn_time &&
1828             (asn_time->length < (int) sizeof(buf))) {
1829                 memcpy(buf, (char*) asn_time->data, asn_time->length);
1830                 buf[asn_time->length] = '\0';
1831                 vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_EXPIRATION][lookup], buf, T_OP_SET);
1832                 rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
1833         }
1834
1835         /*
1836          *      Get the Subject & Issuer
1837          */
1838         subject[0] = issuer[0] = '\0';
1839         X509_NAME_oneline(X509_get_subject_name(client_cert), subject,
1840                           sizeof(subject));
1841         subject[sizeof(subject) - 1] = '\0';
1842         if (certs && identity && (lookup <= 1) && subject[0]) {
1843                 vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_SUBJECT][lookup], subject, T_OP_SET);
1844                 rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
1845         }
1846
1847         X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), issuer,
1848                           sizeof(issuer));
1849         issuer[sizeof(issuer) - 1] = '\0';
1850         if (certs && identity && (lookup <= 1) && issuer[0]) {
1851                 vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_ISSUER][lookup], issuer, T_OP_SET);
1852                 rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
1853         }
1854
1855         /*
1856          *      Get the Common Name, if there is a subject.
1857          */
1858         X509_NAME_get_text_by_NID(X509_get_subject_name(client_cert),
1859                                   NID_commonName, common_name, sizeof(common_name));
1860         common_name[sizeof(common_name) - 1] = '\0';
1861         if (certs && identity && (lookup <= 1) && common_name[0] && subject[0]) {
1862                 vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_CN][lookup], common_name, T_OP_SET);
1863                 rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
1864         }
1865
1866         /*
1867          *      Get the RFC822 Subject Alternative Name
1868          */
1869         loc = X509_get_ext_by_NID(client_cert, NID_subject_alt_name, 0);
1870         if (certs && (lookup <= 1) && (loc >= 0)) {
1871                 X509_EXTENSION *ext = NULL;
1872                 GENERAL_NAMES *names = NULL;
1873                 int i;
1874
1875                 if ((ext = X509_get_ext(client_cert, loc)) &&
1876                     (names = X509V3_EXT_d2i(ext))) {
1877                         for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
1878                                 GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
1879
1880                                 switch (name->type) {
1881 #ifdef GEN_EMAIL
1882                                 case GEN_EMAIL:
1883                                         vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_SAN_EMAIL][lookup],
1884                                                       (char *) ASN1_STRING_data(name->d.rfc822Name), T_OP_SET);
1885                                         rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
1886                                         break;
1887 #endif  /* GEN_EMAIL */
1888 #ifdef GEN_DNS
1889                                 case GEN_DNS:
1890                                         vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_SAN_DNS][lookup],
1891                                                       (char *) ASN1_STRING_data(name->d.dNSName), T_OP_SET);
1892                                         rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
1893                                         break;
1894 #endif  /* GEN_DNS */
1895 #ifdef GEN_OTHERNAME
1896                                 case GEN_OTHERNAME:
1897                                         /* look for a MS UPN */
1898                                         if (NID_ms_upn == OBJ_obj2nid(name->d.otherName->type_id)) {
1899                                             /* we've got a UPN - Must be ASN1-encoded UTF8 string */
1900                                             if (name->d.otherName->value->type == V_ASN1_UTF8STRING) {
1901                                                     vp = fr_pair_make(talloc_ctx, certs, cert_attr_names[FR_TLS_SAN_UPN][lookup],
1902                                                                   (char *) ASN1_STRING_data(name->d.otherName->value->value.utf8string), T_OP_SET);
1903                                                     rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
1904                                                 break;
1905                                             } else {
1906                                                 RWARN("Invalid UPN in Subject Alt Name (should be UTF-8)");
1907                                                 break;
1908                                             }
1909                                         }
1910                                         break;
1911 #endif  /* GEN_OTHERNAME */
1912                                 default:
1913                                         /* XXX TODO handle other SAN types */
1914                                         break;
1915                                 }
1916                         }
1917                 }
1918                 if (names != NULL)
1919                         sk_GENERAL_NAME_free(names);
1920         }
1921
1922         /*
1923          *      If the CRL has expired, that might still be OK.
1924          */
1925         if (!my_ok &&
1926             (conf->allow_expired_crl) &&
1927             (err == X509_V_ERR_CRL_HAS_EXPIRED)) {
1928                 my_ok = 1;
1929                 X509_STORE_CTX_set_error( ctx, 0 );
1930         }
1931
1932         if (!my_ok) {
1933                 char const *p = X509_verify_cert_error_string(err);
1934                 RERROR("SSL says error %d : %s", err, p);
1935                 REXDENT();
1936                 return my_ok;
1937         }
1938
1939         if (lookup == 0) {
1940                 client_inf = client_cert->cert_info;
1941                 ext_list = client_inf->extensions;
1942         } else {
1943                 ext_list = NULL;
1944         }
1945
1946         /*
1947          *      Grab the X509 extensions, and create attributes out of them.
1948          *      For laziness, we re-use the OpenSSL names
1949          */
1950         if (certs && (sk_X509_EXTENSION_num(ext_list) > 0)) {
1951                 int i, len;
1952                 char *p;
1953                 BIO *out;
1954
1955                 out = BIO_new(BIO_s_mem());
1956                 strlcpy(attribute, "TLS-Client-Cert-", sizeof(attribute));
1957
1958                 for (i = 0; i < sk_X509_EXTENSION_num(ext_list); i++) {
1959                         ASN1_OBJECT *obj;
1960                         X509_EXTENSION *ext;
1961
1962                         ext = sk_X509_EXTENSION_value(ext_list, i);
1963
1964                         obj = X509_EXTENSION_get_object(ext);
1965                         i2a_ASN1_OBJECT(out, obj);
1966                         len = BIO_read(out, attribute + 16 , sizeof(attribute) - 16 - 1);
1967                         if (len <= 0) continue;
1968
1969                         attribute[16 + len] = '\0';
1970
1971                         for (p = attribute + 16; *p != '\0'; p++) {
1972                                 if (*p == ' ') *p = '-';
1973                         }
1974
1975                         X509V3_EXT_print(out, ext, 0, 0);
1976                         len = BIO_read(out, value , sizeof(value) - 1);
1977                         if (len <= 0) continue;
1978
1979                         value[len] = '\0';
1980
1981                         vp = fr_pair_make(talloc_ctx, certs, attribute, value, T_OP_ADD);
1982                         if (!vp) {
1983                                 RDEBUG3("Skipping %s += '%s'.  Please check that both the "
1984                                         "attribute and value are defined in the dictionaries",
1985                                         attribute, value);
1986                         } else {
1987                                 /*
1988                                  *      rdebug_pair_list indents (so pre REXDENT())
1989                                  */
1990                                 REXDENT();
1991                                 rdebug_pair_list(L_DBG_LVL_2, request, vp, NULL);
1992                                 RINDENT();
1993                         }
1994                 }
1995
1996                 BIO_free_all(out);
1997         }
1998
1999         REXDENT();
2000
2001         switch (ctx->error) {
2002         case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
2003                 RERROR("issuer=%s", issuer);
2004                 break;
2005
2006         case X509_V_ERR_CERT_NOT_YET_VALID:
2007         case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
2008                 RERROR("notBefore=");
2009 #if 0
2010                 ASN1_TIME_print(bio_err, X509_get_notBefore(ctx->current_cert));
2011 #endif
2012                 break;
2013
2014         case X509_V_ERR_CERT_HAS_EXPIRED:
2015         case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
2016                 RERROR("notAfter=");
2017 #if 0
2018                 ASN1_TIME_print(bio_err, X509_get_notAfter(ctx->current_cert));
2019 #endif
2020                 break;
2021         }
2022
2023         /*
2024          *      If we're at the actual client cert, apply additional
2025          *      checks.
2026          */
2027         if (depth == 0) {
2028                 /*
2029                  *      If the conf tells us to, check cert issuer
2030                  *      against the specified value and fail
2031                  *      verification if they don't match.
2032                  */
2033                 if (conf->check_cert_issuer &&
2034                     (strcmp(issuer, conf->check_cert_issuer) != 0)) {
2035                         AUTH(LOG_PREFIX ": Certificate issuer (%s) does not match specified value (%s)!",
2036                              issuer, conf->check_cert_issuer);
2037                         my_ok = 0;
2038                 }
2039
2040                 /*
2041                  *      If the conf tells us to, check the CN in the
2042                  *      cert against xlat'ed value, but only if the
2043                  *      previous checks passed.
2044                  */
2045                 if (my_ok && conf->check_cert_cn) {
2046                         if (radius_xlat(cn_str, sizeof(cn_str), request, conf->check_cert_cn, NULL, NULL) < 0) {
2047                                 /* if this fails, fail the verification */
2048                                 my_ok = 0;
2049                         } else {
2050                                 RDEBUG2("checking certificate CN (%s) with xlat'ed value (%s)", common_name, cn_str);
2051                                 if (strcmp(cn_str, common_name) != 0) {
2052                                         AUTH(LOG_PREFIX ": Certificate CN (%s) does not match specified value (%s)!",
2053                                              common_name, cn_str);
2054                                         my_ok = 0;
2055                                 }
2056                         }
2057                 } /* check_cert_cn */
2058
2059 #ifdef HAVE_OPENSSL_OCSP_H
2060                 if (my_ok && conf->ocsp_enable){
2061                         RDEBUG2("Starting OCSP Request");
2062                         if (X509_STORE_CTX_get1_issuer(&issuer_cert, ctx, client_cert) != 1) {
2063                                 RERROR("Couldn't get issuer_cert for %s", common_name);
2064                         } else {
2065                                 my_ok = ocsp_check(request, ocsp_store, issuer_cert, client_cert, conf);
2066                         }
2067                 }
2068 #endif
2069
2070                 while (conf->verify_client_cert_cmd) {
2071                         char filename[256];
2072                         int fd;
2073                         FILE *fp;
2074
2075                         snprintf(filename, sizeof(filename), "%s/%s.client.XXXXXXXX",
2076                                  conf->verify_tmp_dir, progname);
2077                         fd = mkstemp(filename);
2078                         if (fd < 0) {
2079                                 RDEBUG("Failed creating file in %s: %s",
2080                                        conf->verify_tmp_dir, fr_syserror(errno));
2081                                 break;
2082                         }
2083
2084                         fp = fdopen(fd, "w");
2085                         if (!fp) {
2086                                 close(fd);
2087                                 RDEBUG("Failed opening file %s: %s",
2088                                        filename, fr_syserror(errno));
2089                                 break;
2090                         }
2091
2092                         if (!PEM_write_X509(fp, client_cert)) {
2093                                 fclose(fp);
2094                                 RDEBUG("Failed writing certificate to file");
2095                                 goto do_unlink;
2096                         }
2097                         fclose(fp);
2098
2099                         if (!pair_make_request("TLS-Client-Cert-Filename",
2100                                              filename, T_OP_SET)) {
2101                                 RDEBUG("Failed creating TLS-Client-Cert-Filename");
2102
2103                                 goto do_unlink;
2104                         }
2105
2106                         RDEBUG("Verifying client certificate: %s", conf->verify_client_cert_cmd);
2107                         if (radius_exec_program(request, NULL, 0, NULL, request, conf->verify_client_cert_cmd,
2108                                                 request->packet->vps,
2109                                                 true, true, EXEC_TIMEOUT) != 0) {
2110                                 AUTH(LOG_PREFIX ": Certificate CN (%s) fails external verification!", common_name);
2111                                 my_ok = 0;
2112                         } else {
2113                                 RDEBUG("Client certificate CN %s passed external validation", common_name);
2114                         }
2115
2116                 do_unlink:
2117                         unlink(filename);
2118                         break;
2119                 }
2120
2121
2122         } /* depth == 0 */
2123
2124         if (RDEBUG_ENABLED3) {
2125                 RDEBUG3("chain-depth   : %d", depth);
2126                 RDEBUG3("error         : %d", err);
2127
2128                 if (identity) RDEBUG3("identity      : %s", *identity);
2129                 RDEBUG3("common name   : %s", common_name);
2130                 RDEBUG3("subject       : %s", subject);
2131                 RDEBUG3("issuer        : %s", issuer);
2132                 RDEBUG3("verify return : %d", my_ok);
2133         }
2134         return my_ok;
2135 }
2136
2137
2138 #ifdef HAVE_OPENSSL_OCSP_H
2139 /*
2140  *      Create Global X509 revocation store and use it to verify
2141  *      OCSP responses
2142  *
2143  *      - Load the trusted CAs
2144  *      - Load the trusted issuer certificates
2145  */
2146 static X509_STORE *init_revocation_store(fr_tls_server_conf_t *conf)
2147 {
2148         X509_STORE *store = NULL;
2149
2150         store = X509_STORE_new();
2151
2152         /* Load the CAs we trust */
2153         if (conf->ca_file || conf->ca_path)
2154                 if(!X509_STORE_load_locations(store, conf->ca_file, conf->ca_path)) {
2155                         ERROR(LOG_PREFIX ": X509_STORE error %s", ERR_error_string(ERR_get_error(), NULL));
2156                         ERROR(LOG_PREFIX ": Error reading Trusted root CA list %s",conf->ca_file );
2157                         return NULL;
2158                 }
2159
2160 #ifdef X509_V_FLAG_CRL_CHECK
2161         if (conf->check_crl)
2162                 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK);
2163 #endif
2164 #ifdef X509_V_FLAG_CRL_CHECK_ALL
2165         if (conf->check_all_crl)
2166                 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK_ALL);
2167 #endif
2168         return store;
2169 }
2170 #endif  /* HAVE_OPENSSL_OCSP_H */
2171
2172 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
2173 #ifndef OPENSSL_NO_ECDH
2174 static int set_ecdh_curve(SSL_CTX *ctx, char const *ecdh_curve)
2175 {
2176         int      nid;
2177         EC_KEY  *ecdh;
2178
2179         if (!ecdh_curve || !*ecdh_curve) return 0;
2180
2181         nid = OBJ_sn2nid(ecdh_curve);
2182         if (!nid) {
2183                 ERROR(LOG_PREFIX ": Unknown ecdh_curve \"%s\"", ecdh_curve);
2184                 return -1;
2185         }
2186
2187         ecdh = EC_KEY_new_by_curve_name(nid);
2188         if (!ecdh) {
2189                 ERROR(LOG_PREFIX ": Unable to create new curve \"%s\"", ecdh_curve);
2190                 return -1;
2191         }
2192
2193         SSL_CTX_set_tmp_ecdh(ctx, ecdh);
2194
2195         SSL_CTX_set_options(ctx, SSL_OP_SINGLE_ECDH_USE);
2196
2197         EC_KEY_free(ecdh);
2198
2199         return 0;
2200 }
2201 #endif
2202 #endif
2203
2204 /*
2205  * DIE OPENSSL DIE DIE DIE
2206  *
2207  * What a palaver, just to free some data attached the
2208  * session. We need to do this because the "remove" callback
2209  * is called when refcount > 0 sometimes, if another thread
2210  * is using the session
2211  */
2212 static void sess_free_vps(UNUSED void *parent, void *data_ptr,
2213                                 UNUSED CRYPTO_EX_DATA *ad, UNUSED int idx,
2214                                 UNUSED long argl, UNUSED void *argp)
2215 {
2216         VALUE_PAIR *vp = data_ptr;
2217         if (!vp) return;
2218
2219         DEBUG2(LOG_PREFIX ": Freeing cached session VPs");
2220
2221         fr_pair_list_free(&vp);
2222 }
2223
2224 static void sess_free_certs(UNUSED void *parent, void *data_ptr,
2225                                 UNUSED CRYPTO_EX_DATA *ad, UNUSED int idx,
2226                                 UNUSED long argl, UNUSED void *argp)
2227 {
2228         VALUE_PAIR **certs = data_ptr;
2229         if (!certs) return;
2230
2231         DEBUG2(LOG_PREFIX ": Freeing cached session Certificates");
2232
2233         fr_pair_list_free(certs);
2234 }
2235
2236 /** Add all the default ciphers and message digests reate our context.
2237  *
2238  * This should be called exactly once from main, before reading the main config
2239  * or initialising any modules.
2240  */
2241 void tls_global_init(void)
2242 {
2243         SSL_load_error_strings();       /* readable error messages (examples show call before library_init) */
2244         SSL_library_init();             /* initialize library */
2245         OpenSSL_add_all_algorithms();   /* required for SHA2 in OpenSSL < 0.9.8o and 1.0.0.a */
2246         OPENSSL_config(NULL);
2247
2248         /*
2249          *      Initialize the index for the certificates.
2250          */
2251         fr_tls_ex_index_certs = SSL_SESSION_get_ex_new_index(0, NULL, NULL, NULL, sess_free_certs);
2252 }
2253
2254 #ifdef ENABLE_OPENSSL_VERSION_CHECK
2255 /** Check for vulnerable versions of libssl
2256  *
2257  * @param acknowledged The highest CVE number a user has confirmed is not present in the system's libssl.
2258  * @return 0 if the CVE specified by the user matches the most recent CVE we have, else -1.
2259  */
2260 int tls_global_version_check(char const *acknowledged)
2261 {
2262         uint64_t v;
2263
2264         if ((strcmp(acknowledged, libssl_defects[0].id) != 0) && (strcmp(acknowledged, "yes") != 0)) {
2265                 bool bad = false;
2266                 size_t i;
2267
2268                 /* Check for bad versions */
2269                 v = (uint64_t) SSLeay();
2270
2271                 for (i = 0; i < (sizeof(libssl_defects) / sizeof(*libssl_defects)); i++) {
2272                         libssl_defect_t *defect = &libssl_defects[i];
2273
2274                         if ((v >= defect->low) && (v <= defect->high)) {
2275                                 ERROR("Refusing to start with libssl version %s (in range %s)",
2276                                       ssl_version(), ssl_version_range(defect->low, defect->high));
2277                                 ERROR("Security advisory %s (%s)", defect->id, defect->name);
2278                                 ERROR("%s", defect->comment);
2279
2280                                 bad = true;
2281                         }
2282                 }
2283
2284                 if (bad) {
2285                         INFO("Once you have verified libssl has been correctly patched, "
2286                              "set security.allow_vulnerable_openssl = '%s'", libssl_defects[0].id);
2287                         return -1;
2288                 }
2289         }
2290
2291         return 0;
2292 }
2293 #endif
2294
2295 /** Free any memory alloced by libssl
2296  *
2297  */
2298 void tls_global_cleanup(void)
2299 {
2300         ERR_remove_state(0);
2301         ENGINE_cleanup();
2302         CONF_modules_unload(1);
2303         ERR_free_strings();
2304         EVP_cleanup();
2305         CRYPTO_cleanup_all_ex_data();
2306 }
2307
2308 /** Create SSL context
2309  *
2310  * - Load the trusted CAs
2311  * - Load the Private key & the certificate
2312  * - Set the Context options & Verify options
2313  */
2314 SSL_CTX *tls_init_ctx(fr_tls_server_conf_t *conf, int client)
2315 {
2316         SSL_CTX         *ctx;
2317         X509_STORE      *certstore;
2318         int             verify_mode = SSL_VERIFY_NONE;
2319         int             ctx_options = 0;
2320         int             ctx_tls_versions = 0;
2321         int             type;
2322
2323         /*
2324          *      SHA256 is in all versions of OpenSSL, but isn't
2325          *      initialized by default.  It's needed for WiMAX
2326          *      certificates.
2327          */
2328 #ifdef HAVE_OPENSSL_EVP_SHA256
2329         EVP_add_digest(EVP_sha256());
2330 #endif
2331
2332         ctx = SSL_CTX_new(SSLv23_method()); /* which is really "all known SSL / TLS methods".  Idiots. */
2333         if (!ctx) {
2334                 int err;
2335                 while ((err = ERR_get_error())) {
2336                         ERROR(LOG_PREFIX ": Failed creating SSL context: %s", ERR_error_string(err, NULL));
2337                         return NULL;
2338                 }
2339         }
2340
2341         /*
2342          * Save the config on the context so that callbacks which
2343          * only get SSL_CTX* e.g. session persistence, can get it
2344          */
2345         SSL_CTX_set_app_data(ctx, conf);
2346
2347         /*
2348          * Identify the type of certificates that needs to be loaded
2349          */
2350         if (conf->file_type) {
2351                 type = SSL_FILETYPE_PEM;
2352         } else {
2353                 type = SSL_FILETYPE_ASN1;
2354         }
2355
2356         /*
2357          * Set the password to load private key
2358          */
2359         if (conf->private_key_password) {
2360 #ifdef __APPLE__
2361                 /*
2362                  * We don't want to put the private key password in eap.conf, so  check
2363                  * for our special string which indicates we should get the password
2364                  * programmatically.
2365                  */
2366                 char const* special_string = "Apple:UseCertAdmin";
2367                 if (strncmp(conf->private_key_password, special_string, strlen(special_string)) == 0) {
2368                         char cmd[256];
2369                         char *password;
2370                         long const max_password_len = 128;
2371                         snprintf(cmd, sizeof(cmd) - 1, "/usr/sbin/certadmin --get-private-key-passphrase \"%s\"",
2372                                  conf->private_key_file);
2373
2374                         DEBUG2(LOG_PREFIX ":  Getting private key passphrase using command \"%s\"", cmd);
2375
2376                         FILE* cmd_pipe = popen(cmd, "r");
2377                         if (!cmd_pipe) {
2378                                 ERROR(LOG_PREFIX ": %s command failed: Unable to get private_key_password", cmd);
2379                                 ERROR(LOG_PREFIX ": Error reading private_key_file %s", conf->private_key_file);
2380                                 return NULL;
2381                         }
2382
2383                         rad_const_free(conf->private_key_password);
2384                         password = talloc_array(conf, char, max_password_len);
2385                         if (!password) {
2386                                 ERROR(LOG_PREFIX ": Can't allocate space for private_key_password");
2387                                 ERROR(LOG_PREFIX ": Error reading private_key_file %s", conf->private_key_file);
2388                                 pclose(cmd_pipe);
2389                                 return NULL;
2390                         }
2391
2392                         fgets(password, max_password_len, cmd_pipe);
2393                         pclose(cmd_pipe);
2394
2395                         /* Get rid of newline at end of password. */
2396                         password[strlen(password) - 1] = '\0';
2397
2398                         DEBUG3(LOG_PREFIX ": Password from command = \"%s\"", password);
2399                         conf->private_key_password = password;
2400                 }
2401 #endif
2402
2403                 {
2404                         char *password;
2405
2406                         memcpy(&password, &conf->private_key_password, sizeof(password));
2407                         SSL_CTX_set_default_passwd_cb_userdata(ctx, password);
2408                         SSL_CTX_set_default_passwd_cb(ctx, cbtls_password);
2409                 }
2410         }
2411
2412 #ifdef PSK_MAX_IDENTITY_LEN
2413         if (!client) {
2414                 /*
2415                  *      No dynamic query exists.  There MUST be a
2416                  *      statically configured identity and password.
2417                  */
2418                 if (conf->psk_query && !*conf->psk_query) {
2419                         ERROR(LOG_PREFIX ": Invalid PSK Configuration: psk_query cannot be empty");
2420                         return NULL;
2421                 }
2422
2423                 /*
2424                  *      Set the callback only if we can check things.
2425                  */
2426                 if (conf->psk_identity || conf->psk_query) {
2427                         SSL_CTX_set_psk_server_callback(ctx, psk_server_callback);
2428                 }
2429
2430         } else if (conf->psk_query) {
2431                 ERROR(LOG_PREFIX ": Invalid PSK Configuration: psk_query cannot be used for outgoing connections");
2432                 return NULL;
2433         }
2434
2435         /*
2436          *      Now check that if PSK is being used, the config is valid.
2437          */
2438         if ((conf->psk_identity && !conf->psk_password) ||
2439             (!conf->psk_identity && conf->psk_password) ||
2440             (conf->psk_identity && !*conf->psk_identity) ||
2441             (conf->psk_password && !*conf->psk_password)) {
2442                 ERROR(LOG_PREFIX ": Invalid PSK Configuration: psk_identity or psk_password are empty");
2443                 return NULL;
2444         }
2445
2446         if (conf->psk_identity) {
2447                 size_t psk_len, hex_len;
2448                 uint8_t buffer[PSK_MAX_PSK_LEN];
2449
2450                 if (conf->certificate_file ||
2451                     conf->private_key_password || conf->private_key_file ||
2452                     conf->ca_file || conf->ca_path) {
2453                         ERROR(LOG_PREFIX ": When PSKs are used, No certificate configuration is permitted");
2454                         return NULL;
2455                 }
2456
2457                 if (client) {
2458                         SSL_CTX_set_psk_client_callback(ctx,
2459                                                         psk_client_callback);
2460                 }
2461
2462                 psk_len = strlen(conf->psk_password);
2463                 if (strlen(conf->psk_password) > (2 * PSK_MAX_PSK_LEN)) {
2464                         ERROR(LOG_PREFIX ": psk_hexphrase is too long (max %d)", PSK_MAX_PSK_LEN);
2465                         return NULL;
2466                 }
2467
2468                 /*
2469                  *      Check the password now, so that we don't have
2470                  *      errors at run-time.
2471                  */
2472                 hex_len = fr_hex2bin(buffer, sizeof(buffer), conf->psk_password, psk_len);
2473                 if (psk_len != (2 * hex_len)) {
2474                         ERROR(LOG_PREFIX ": psk_hexphrase is not all hex");
2475                         return NULL;
2476                 }
2477
2478                 goto post_ca;
2479         }
2480 #else
2481         (void) client;  /* -Wunused */
2482 #endif
2483
2484         /*
2485          *      Load our keys and certificates
2486          *
2487          *      If certificates are of type PEM then we can make use
2488          *      of cert chain authentication using openssl api call
2489          *      SSL_CTX_use_certificate_chain_file.  Please see how
2490          *      the cert chain needs to be given in PEM from
2491          *      openSSL.org
2492          */
2493         if (!conf->certificate_file) goto load_ca;
2494
2495         if (type == SSL_FILETYPE_PEM) {
2496                 if (!(SSL_CTX_use_certificate_chain_file(ctx, conf->certificate_file))) {
2497                         ERROR(LOG_PREFIX ": Error reading certificate file %s:%s", conf->certificate_file,
2498                               ERR_error_string(ERR_get_error(), NULL));
2499                         return NULL;
2500                 }
2501
2502         } else if (!(SSL_CTX_use_certificate_file(ctx, conf->certificate_file, type))) {
2503                 ERROR(LOG_PREFIX ": Error reading certificate file %s:%s",
2504                       conf->certificate_file,
2505                       ERR_error_string(ERR_get_error(), NULL));
2506                 return NULL;
2507         }
2508
2509         /* Load the CAs we trust */
2510 load_ca:
2511         if (conf->ca_file || conf->ca_path) {
2512                 if (!SSL_CTX_load_verify_locations(ctx, conf->ca_file, conf->ca_path)) {
2513                         ERROR(LOG_PREFIX ": SSL error %s", ERR_error_string(ERR_get_error(), NULL));
2514                         ERROR(LOG_PREFIX ": Error reading Trusted root CA list %s",conf->ca_file );
2515                         return NULL;
2516                 }
2517         }
2518         if (conf->ca_file && *conf->ca_file) SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(conf->ca_file));
2519
2520         if (conf->private_key_file) {
2521                 if (!(SSL_CTX_use_PrivateKey_file(ctx, conf->private_key_file, type))) {
2522                         ERROR(LOG_PREFIX ": Failed reading private key file %s:%s",
2523                               conf->private_key_file,
2524                               ERR_error_string(ERR_get_error(), NULL));
2525                         return NULL;
2526                 }
2527
2528                 /*
2529                  * Check if the loaded private key is the right one
2530                  */
2531                 if (!SSL_CTX_check_private_key(ctx)) {
2532                         ERROR(LOG_PREFIX ": Private key does not match the certificate public key");
2533                         return NULL;
2534                 }
2535         }
2536
2537 #ifdef PSK_MAX_IDENTITY_LEN
2538 post_ca:
2539 #endif
2540
2541         /*
2542          *      We never want SSLv2 or SSLv3.
2543          */
2544         ctx_options |= SSL_OP_NO_SSLv2;
2545         ctx_options |= SSL_OP_NO_SSLv3;
2546
2547         /*
2548          *      As of 3.0.5, we always allow TLSv1.1 and TLSv1.2.
2549          *      Though they can be *globally* disabled if necessary.x
2550          */
2551 #ifdef SSL_OP_NO_TLSv1
2552         if (conf->disable_tlsv1) ctx_options |= SSL_OP_NO_TLSv1;
2553
2554         ctx_tls_versions |= SSL_OP_NO_TLSv1;
2555 #endif
2556 #ifdef SSL_OP_NO_TLSv1_1
2557         if (conf->disable_tlsv1_1) ctx_options |= SSL_OP_NO_TLSv1_1;
2558
2559         ctx_tls_versions |= SSL_OP_NO_TLSv1_1;
2560 #endif
2561 #ifdef SSL_OP_NO_TLSv1_2
2562         if (conf->disable_tlsv1_2) ctx_options |= SSL_OP_NO_TLSv1_2;
2563
2564         ctx_tls_versions |= SSL_OP_NO_TLSv1_2;
2565 #endif
2566
2567         if ((ctx_options & ctx_tls_versions) == ctx_tls_versions) {
2568                 ERROR(LOG_PREFIX ": You have disabled all available TLS versions.  EAP will not work");
2569                 return NULL;
2570         }
2571
2572 #ifdef SSL_OP_NO_TICKET
2573         ctx_options |= SSL_OP_NO_TICKET;
2574 #endif
2575
2576         /*
2577          *      SSL_OP_SINGLE_DH_USE must be used in order to prevent
2578          *      small subgroup attacks and forward secrecy. Always
2579          *      using
2580          *
2581          *      SSL_OP_SINGLE_DH_USE has an impact on the computer
2582          *      time needed during negotiation, but it is not very
2583          *      large.
2584          */
2585         ctx_options |= SSL_OP_SINGLE_DH_USE;
2586
2587         /*
2588          *      SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS to work around issues
2589          *      in Windows Vista client.
2590          *      http://www.openssl.org/~bodo/tls-cbc.txt
2591          *      http://www.nabble.com/(RADIATOR)-Radiator-Version-3.16-released-t2600070.html
2592          */
2593         ctx_options |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2594
2595         SSL_CTX_set_options(ctx, ctx_options);
2596
2597         /*
2598          *      TODO: Set the RSA & DH
2599          *      SSL_CTX_set_tmp_rsa_callback(ctx, cbtls_rsa);
2600          *      SSL_CTX_set_tmp_dh_callback(ctx, cbtls_dh);
2601          */
2602
2603         /*
2604          *      set the message callback to identify the type of
2605          *      message.  For every new session, there can be a
2606          *      different callback argument.
2607          *
2608          *      SSL_CTX_set_msg_callback(ctx, cbtls_msg);
2609          */
2610
2611         /*
2612          *      Set eliptical curve crypto configuration.
2613          */
2614 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
2615 #ifndef OPENSSL_NO_ECDH
2616         if (set_ecdh_curve(ctx, conf->ecdh_curve) < 0) {
2617                 return NULL;
2618         }
2619 #endif
2620 #endif
2621
2622         /* Set Info callback */
2623         SSL_CTX_set_info_callback(ctx, cbtls_info);
2624
2625         /*
2626          *      Callbacks, etc. for session resumption.
2627          */
2628         if (conf->session_cache_enable) {
2629                 /*
2630                  *      Cache sessions on disk if requested.
2631                  */
2632                 if (conf->session_cache_path) {
2633                         SSL_CTX_sess_set_new_cb(ctx, cbtls_new_session);
2634                         SSL_CTX_sess_set_get_cb(ctx, cbtls_get_session);
2635                         SSL_CTX_sess_set_remove_cb(ctx, cbtls_remove_session);
2636                 }
2637
2638                 SSL_CTX_set_quiet_shutdown(ctx, 1);
2639                 if (fr_tls_ex_index_vps < 0)
2640                         fr_tls_ex_index_vps = SSL_SESSION_get_ex_new_index(0, NULL, NULL, NULL, sess_free_vps);
2641         }
2642
2643         /*
2644          *      Check the certificates for revocation.
2645          */
2646 #ifdef X509_V_FLAG_CRL_CHECK
2647         if (conf->check_crl) {
2648                 certstore = SSL_CTX_get_cert_store(ctx);
2649                 if (certstore == NULL) {
2650                         ERROR(LOG_PREFIX ": SSL error %s", ERR_error_string(ERR_get_error(), NULL));
2651                         ERROR(LOG_PREFIX ": Error reading Certificate Store");
2652                         return NULL;
2653                 }
2654                 X509_STORE_set_flags(certstore, X509_V_FLAG_CRL_CHECK);
2655
2656 #ifdef X509_V_FLAG_CRL_CHECK_ALL
2657                 if (conf->check_all_crl)
2658                         X509_STORE_set_flags(certstore, X509_V_FLAG_CRL_CHECK_ALL);
2659 #endif
2660         }
2661 #endif
2662
2663         /*
2664          *      Set verify modes
2665          *      Always verify the peer certificate
2666          */
2667         verify_mode |= SSL_VERIFY_PEER;
2668         verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2669         verify_mode |= SSL_VERIFY_CLIENT_ONCE;
2670         SSL_CTX_set_verify(ctx, verify_mode, cbtls_verify);
2671
2672         if (conf->verify_depth) {
2673                 SSL_CTX_set_verify_depth(ctx, conf->verify_depth);
2674         }
2675
2676         /* Load randomness */
2677         if (conf->random_file) {
2678                 if (!(RAND_load_file(conf->random_file, 1024*10))) {
2679                         ERROR(LOG_PREFIX ": SSL error %s", ERR_error_string(ERR_get_error(), NULL));
2680                         ERROR(LOG_PREFIX ": Error loading randomness");
2681                         return NULL;
2682                 }
2683         }
2684
2685         /*
2686          * Set the cipher list if we were told to
2687          */
2688         if (conf->cipher_list) {
2689                 if (!SSL_CTX_set_cipher_list(ctx, conf->cipher_list)) {
2690                         ERROR(LOG_PREFIX ": Error setting cipher list");
2691                         return NULL;
2692                 }
2693         }
2694
2695         /*
2696          *      Setup session caching
2697          */
2698         if (conf->session_cache_enable) {
2699                 /*
2700                  *      Create a unique context Id per EAP-TLS configuration.
2701                  */
2702                 if (conf->session_id_name) {
2703                         snprintf(conf->session_context_id, sizeof(conf->session_context_id),
2704                                  "FR eap %s", conf->session_id_name);
2705                 } else {
2706                         snprintf(conf->session_context_id, sizeof(conf->session_context_id),
2707                                  "FR eap %p", conf);
2708                 }
2709
2710                 /*
2711                  *      Cache it, and DON'T auto-clear it.
2712                  */
2713                 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER | SSL_SESS_CACHE_NO_AUTO_CLEAR);
2714
2715                 SSL_CTX_set_session_id_context(ctx,
2716                                                (unsigned char *) conf->session_context_id,
2717                                                (unsigned int) strlen(conf->session_context_id));
2718
2719                 /*
2720                  *      Our timeout is in hours, this is in seconds.
2721                  */
2722                 SSL_CTX_set_timeout(ctx, conf->session_timeout * 3600);
2723
2724                 /*
2725                  *      Set the maximum number of entries in the
2726                  *      session cache.
2727                  */
2728                 SSL_CTX_sess_set_cache_size(ctx, conf->session_cache_size);
2729
2730         } else {
2731                 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
2732         }
2733
2734         return ctx;
2735 }
2736
2737
2738 /*
2739  *      Free TLS client/server config
2740  *      Should not be called outside this code, as a callback is
2741  *      added to automatically free the data when the CONF_SECTION
2742  *      is freed.
2743  */
2744 static int _tls_server_conf_free(fr_tls_server_conf_t *conf)
2745 {
2746         if (conf->ctx) SSL_CTX_free(conf->ctx);
2747
2748 #ifdef HAVE_OPENSSL_OCSP_H
2749         if (conf->ocsp_store) X509_STORE_free(conf->ocsp_store);
2750         conf->ocsp_store = NULL;
2751 #endif
2752
2753 #ifndef NDEBUG
2754         memset(conf, 0, sizeof(*conf));
2755 #endif
2756         return 0;
2757 }
2758
2759 static fr_tls_server_conf_t *tls_server_conf_alloc(TALLOC_CTX *ctx)
2760 {
2761         fr_tls_server_conf_t *conf;
2762
2763         conf = talloc_zero(ctx, fr_tls_server_conf_t);
2764         if (!conf) {
2765                 ERROR(LOG_PREFIX ": Out of memory");
2766                 return NULL;
2767         }
2768
2769         talloc_set_destructor(conf, _tls_server_conf_free);
2770
2771         return conf;
2772 }
2773
2774 fr_tls_server_conf_t *tls_server_conf_parse(CONF_SECTION *cs)
2775 {
2776         fr_tls_server_conf_t *conf;
2777
2778         /*
2779          *      If cs has already been parsed there should be a cached copy
2780          *      of conf already stored, so just return that.
2781          */
2782         conf = cf_data_find(cs, "tls-conf");
2783         if (conf) {
2784                 DEBUG(LOG_PREFIX ": Using cached TLS configuration from previous invocation");
2785                 return conf;
2786         }
2787
2788         conf = tls_server_conf_alloc(cs);
2789
2790         if (cf_section_parse(cs, conf, tls_server_config) < 0) {
2791         error:
2792                 talloc_free(conf);
2793                 return NULL;
2794         }
2795
2796         /*
2797          *      Save people from their own stupidity.
2798          */
2799         if (conf->fragment_size < 100) conf->fragment_size = 100;
2800
2801         if (!conf->private_key_file) {
2802                 ERROR(LOG_PREFIX ": TLS Server requires a private key file");
2803                 goto error;
2804         }
2805
2806         if (!conf->certificate_file) {
2807                 ERROR(LOG_PREFIX ": TLS Server requires a certificate file");
2808                 goto error;
2809         }
2810
2811         /*
2812          *      Initialize TLS
2813          */
2814         conf->ctx = tls_init_ctx(conf, 0);
2815         if (conf->ctx == NULL) {
2816                 goto error;
2817         }
2818
2819 #ifdef HAVE_OPENSSL_OCSP_H
2820         /*
2821          *      Initialize OCSP Revocation Store
2822          */
2823         if (conf->ocsp_enable) {
2824                 conf->ocsp_store = init_revocation_store(conf);
2825                 if (conf->ocsp_store == NULL) goto error;
2826         }
2827 #endif /*HAVE_OPENSSL_OCSP_H*/
2828         {
2829                 char *dh_file;
2830
2831                 memcpy(&dh_file, &conf->dh_file, sizeof(dh_file));
2832                 if (load_dh_params(conf->ctx, dh_file) < 0) {
2833                         goto error;
2834                 }
2835         }
2836
2837         if (conf->verify_tmp_dir) {
2838                 if (chmod(conf->verify_tmp_dir, S_IRWXU) < 0) {
2839                         ERROR(LOG_PREFIX ": Failed changing permissions on %s: %s",
2840                               conf->verify_tmp_dir, fr_syserror(errno));
2841                         goto error;
2842                 }
2843         }
2844
2845         if (conf->verify_client_cert_cmd && !conf->verify_tmp_dir) {
2846                 ERROR(LOG_PREFIX ": You MUST set the verify directory in order to use verify_client_cmd");
2847                 goto error;
2848         }
2849
2850         /*
2851          *      Cache conf in cs in case we're asked to parse this again.
2852          */
2853         cf_data_add(cs, "tls-conf", conf, NULL);
2854
2855         return conf;
2856 }
2857
2858 fr_tls_server_conf_t *tls_client_conf_parse(CONF_SECTION *cs)
2859 {
2860         fr_tls_server_conf_t *conf;
2861
2862         conf = cf_data_find(cs, "tls-conf");
2863         if (conf) {
2864                 DEBUG2(LOG_PREFIX ": Using cached TLS configuration from previous invocation");
2865                 return conf;
2866         }
2867
2868         conf = tls_server_conf_alloc(cs);
2869
2870         if (cf_section_parse(cs, conf, tls_client_config) < 0) {
2871         error:
2872                 talloc_free(conf);
2873                 return NULL;
2874         }
2875
2876         /*
2877          *      Save people from their own stupidity.
2878          */
2879         if (conf->fragment_size < 100) conf->fragment_size = 100;
2880
2881         /*
2882          *      Initialize TLS
2883          */
2884         conf->ctx = tls_init_ctx(conf, 1);
2885         if (conf->ctx == NULL) {
2886                 goto error;
2887         }
2888
2889         {
2890                 char *dh_file;
2891
2892                 memcpy(&dh_file, &conf->dh_file, sizeof(dh_file));
2893                 if (load_dh_params(conf->ctx, dh_file) < 0) {
2894                         goto error;
2895                 }
2896         }
2897
2898         cf_data_add(cs, "tls-conf", conf, NULL);
2899
2900         return conf;
2901 }
2902
2903 int tls_success(tls_session_t *ssn, REQUEST *request)
2904 {
2905         VALUE_PAIR *vp, *vps = NULL;
2906         fr_tls_server_conf_t *conf;
2907         TALLOC_CTX *talloc_ctx;
2908
2909         conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssn->ssl, FR_TLS_EX_INDEX_CONF);
2910         rad_assert(conf != NULL);
2911
2912         talloc_ctx = SSL_get_ex_data(ssn->ssl, FR_TLS_EX_INDEX_TALLOC);
2913
2914         /*
2915          *      If there's no session resumption, delete the entry
2916          *      from the cache.  This means either it's disabled
2917          *      globally for this SSL context, OR we were told to
2918          *      disable it for this user.
2919          *
2920          *      This also means you can't turn it on just for one
2921          *      user.
2922          */
2923         if ((!ssn->allow_session_resumption) ||
2924             (((vp = fr_pair_find_by_num(request->config, PW_ALLOW_SESSION_RESUMPTION, 0, TAG_ANY)) != NULL) &&
2925              (vp->vp_integer == 0))) {
2926                 SSL_CTX_remove_session(ssn->ctx,
2927                                        ssn->ssl_session);
2928                 ssn->allow_session_resumption = false;
2929
2930                 /*
2931                  *      If we're in a resumed session and it's
2932                  *      not allowed,
2933                  */
2934                 if (SSL_session_reused(ssn->ssl)) {
2935                         RDEBUG("Forcibly stopping session resumption as it is not allowed");
2936                         return -1;
2937                 }
2938
2939         /*
2940          *      Else resumption IS allowed, so we store the
2941          *      user data in the cache.
2942          */
2943         } else if (!SSL_session_reused(ssn->ssl)) {
2944                 VALUE_PAIR **certs;
2945                 char buffer[2 * MAX_SESSION_SIZE + 1];
2946
2947                 tls_session_id(ssn->ssl_session, buffer, MAX_SESSION_SIZE);
2948
2949                 vp = fr_pair_list_copy_by_num(talloc_ctx, request->reply->vps, PW_USER_NAME, 0, TAG_ANY);
2950                 if (vp) fr_pair_add(&vps, vp);
2951
2952                 vp = fr_pair_list_copy_by_num(talloc_ctx, request->packet->vps, PW_STRIPPED_USER_NAME, 0, TAG_ANY);
2953                 if (vp) fr_pair_add(&vps, vp);
2954
2955                 vp = fr_pair_list_copy_by_num(talloc_ctx, request->packet->vps, PW_STRIPPED_USER_DOMAIN, 0, TAG_ANY);
2956                 if (vp) fr_pair_add(&vps, vp);
2957
2958                 vp = fr_pair_list_copy_by_num(talloc_ctx, request->reply->vps, PW_CHARGEABLE_USER_IDENTITY, 0, TAG_ANY);
2959                 if (vp) fr_pair_add(&vps, vp);
2960
2961                 vp = fr_pair_list_copy_by_num(talloc_ctx, request->reply->vps, PW_CACHED_SESSION_POLICY, 0, TAG_ANY);
2962                 if (vp) fr_pair_add(&vps, vp);
2963
2964                 certs = (VALUE_PAIR **)SSL_get_ex_data(ssn->ssl, fr_tls_ex_index_certs);
2965
2966                 /*
2967                  *      Hmm... the certs should probably be session data.
2968                  */
2969                 if (certs) {
2970                         /*
2971                          *      @todo: some go into reply, others into
2972                          *      request
2973                          */
2974                         fr_pair_add(&vps, fr_pair_list_copy(talloc_ctx, *certs));
2975
2976                         /*
2977                          *      Save the certs in the packet, so that we can see them.
2978                          */
2979                         fr_pair_add(&request->packet->vps, fr_pair_list_copy(request->packet, *certs));
2980                 }
2981
2982                 if (vps) {
2983                         SSL_SESSION_set_ex_data(ssn->ssl_session, fr_tls_ex_index_vps, vps);
2984                         rdebug_pair_list(L_DBG_LVL_2, request, vps, "  caching ");
2985
2986                         if (conf->session_cache_path) {
2987                                 /* write the VPs to the cache file */
2988                                 char filename[256], buf[1024];
2989                                 FILE *vp_file;
2990
2991                                 RDEBUG2("Saving session %s in the disk cache", buffer);
2992
2993                                 snprintf(filename, sizeof(filename), "%s%c%s.vps", conf->session_cache_path,
2994                                          FR_DIR_SEP, buffer);
2995                                 vp_file = fopen(filename, "w");
2996                                 if (vp_file == NULL) {
2997                                         RWDEBUG("Could not write session VPs to persistent cache: %s",
2998                                                 fr_syserror(errno));
2999                                 } else {
3000                                         VALUE_PAIR *prev = NULL;
3001                                         vp_cursor_t cursor;
3002                                         /* generate a dummy user-style entry which is easy to read back */
3003                                         fprintf(vp_file, "# SSL cached session\n");
3004                                         fprintf(vp_file, "%s\n\t", buffer);
3005
3006                                         for (vp = fr_cursor_init(&cursor, &vps);
3007                                              vp;
3008                                              vp = fr_cursor_next(&cursor)) {
3009                                                 /*
3010                                                  *      Terminate the previous line.
3011                                                  */
3012                                                 if (prev) fprintf(vp_file, ",\n\t");
3013
3014                                                 /*
3015                                                  *      Write this one.
3016                                                  */
3017                                                 vp_prints(buf, sizeof(buf), vp);
3018                                                 fputs(buf, vp_file);
3019                                                 prev = vp;
3020                                         }
3021
3022                                         /*
3023                                          *      Terminate the final line.
3024                                          */
3025                                         fprintf(vp_file, "\n");
3026                                         fclose(vp_file);
3027                                 }
3028                         } else {
3029                                 RDEBUG("Failed to find 'persist_dir' in TLS configuration.  Session will not be cached on disk.");
3030                         }
3031                 } else {
3032                         RDEBUG2("No information to cache: session caching will be disabled for session %s", buffer);
3033                         SSL_CTX_remove_session(ssn->ctx, ssn->ssl_session);
3034                 }
3035
3036         /*
3037          *      Else the session WAS allowed.  Copy the cached reply.
3038          */
3039         } else {
3040                 char buffer[2 * MAX_SESSION_SIZE + 1];
3041
3042                 tls_session_id(ssn->ssl_session, buffer, MAX_SESSION_SIZE);
3043
3044                 /*
3045                  *      The "restore VPs from OpenSSL cache" code is
3046                  *      now in eaptls_process()
3047                  */
3048
3049                 if (conf->session_cache_path) {
3050                         /* "touch" the cached session/vp file */
3051                         char filename[256];
3052
3053                         snprintf(filename, sizeof(filename), "%s%c%s.asn1",
3054                                  conf->session_cache_path, FR_DIR_SEP, buffer);
3055                         utime(filename, NULL);
3056                         snprintf(filename, sizeof(filename), "%s%c%s.vps",
3057                                  conf->session_cache_path, FR_DIR_SEP, buffer);
3058                         utime(filename, NULL);
3059                 }
3060
3061                 /*
3062                  *      Mark the request as resumed.
3063                  */
3064                 pair_make_request("EAP-Session-Resumed", "1", T_OP_SET);
3065         }
3066
3067         return 0;
3068 }
3069
3070
3071 void tls_fail(tls_session_t *ssn)
3072 {
3073         /*
3074          *      Force the session to NOT be cached.
3075          */
3076         SSL_CTX_remove_session(ssn->ctx, ssn->ssl_session);
3077 }
3078
3079 fr_tls_status_t tls_application_data(tls_session_t *ssn, REQUEST *request)
3080
3081 {
3082         int err;
3083         VALUE_PAIR **certs;
3084
3085         /*
3086          *      Decrypt the complete record.
3087          */
3088         err = BIO_write(ssn->into_ssl, ssn->dirty_in.data,
3089                         ssn->dirty_in.used);
3090         if (err != (int) ssn->dirty_in.used) {
3091                 record_init(&ssn->dirty_in);
3092                 RDEBUG("Failed writing %zd bytes to SSL BIO: %d", ssn->dirty_in.used, err);
3093                 return FR_TLS_FAIL;
3094         }
3095
3096         /*
3097          *      Clear the dirty buffer now that we are done with it
3098          *      and init the clean_out buffer to store decrypted data
3099          */
3100         record_init(&ssn->dirty_in);
3101         record_init(&ssn->clean_out);
3102
3103         /*
3104          *      Read (and decrypt) the tunneled data from the
3105          *      SSL session, and put it into the decrypted
3106          *      data buffer.
3107          */
3108         err = SSL_read(ssn->ssl, ssn->clean_out.data, sizeof(ssn->clean_out.data));
3109         if (err < 0) {
3110                 int code;
3111
3112                 RDEBUG("SSL_read Error");
3113
3114                 code = SSL_get_error(ssn->ssl, err);
3115                 switch (code) {
3116                 case SSL_ERROR_WANT_READ:
3117                         DEBUG("Error in fragmentation logic: SSL_WANT_READ");
3118                         return FR_TLS_MORE_FRAGMENTS;
3119
3120                 case SSL_ERROR_WANT_WRITE:
3121                         DEBUG("Error in fragmentation logic: SSL_WANT_WRITE");
3122                         break;
3123
3124                 default:
3125                         DEBUG("Error in fragmentation logic: %s", ERR_error_string(code, NULL));
3126
3127                         /*
3128                          *      FIXME: Call int_ssl_check?
3129                          */
3130                         break;
3131                 }
3132                 return FR_TLS_FAIL;
3133         }
3134
3135         if (err == 0) RWDEBUG("No data inside of the tunnel");
3136
3137         /*
3138          *      Passed all checks, successfully decrypted data
3139          */
3140         ssn->clean_out.used = err;
3141
3142         /*
3143          *      Add the certificates to intermediate packets, so that
3144          *      the inner tunnel policies can use them.
3145          */
3146         certs = (VALUE_PAIR **)SSL_get_ex_data(ssn->ssl, fr_tls_ex_index_certs);
3147
3148         if (certs) fr_pair_add(&request->packet->vps, fr_pair_list_copy(request->packet, *certs));
3149
3150         return FR_TLS_OK;
3151 }
3152
3153
3154 /*
3155  * Acknowledge received is for one of the following messages sent earlier
3156  * 1. Handshake completed Message, so now send, EAP-Success
3157  * 2. Alert Message, now send, EAP-Failure
3158  * 3. Fragment Message, now send, next Fragment
3159  */
3160 fr_tls_status_t tls_ack_handler(tls_session_t *ssn, REQUEST *request)
3161 {
3162         if (ssn == NULL){
3163                 REDEBUG("Unexpected ACK received:  No ongoing SSL session");
3164                 return FR_TLS_INVALID;
3165         }
3166         if (!ssn->info.initialized) {
3167                 RDEBUG("No SSL info available.  Waiting for more SSL data");
3168                 return FR_TLS_REQUEST;
3169         }
3170
3171         if ((ssn->info.content_type == handshake) && (ssn->info.origin == 0)) {
3172                 REDEBUG("Unexpected ACK received:  We sent no previous messages");
3173                 return FR_TLS_INVALID;
3174         }
3175
3176         switch (ssn->info.content_type) {
3177         case alert:
3178                 RDEBUG2("Peer ACKed our alert");
3179                 return FR_TLS_FAIL;
3180
3181         case handshake:
3182                 if ((ssn->info.handshake_type == handshake_finished) && (ssn->dirty_out.used == 0)) {
3183                         RDEBUG2("Peer ACKed our handshake fragment.  handshake is finished");
3184
3185                         /*
3186                          *      From now on all the content is
3187                          *      application data set it here as nobody else
3188                          *      sets it.
3189                          */
3190                         ssn->info.content_type = application_data;
3191                         return FR_TLS_SUCCESS;
3192                 } /* else more data to send */
3193
3194                 RDEBUG2("Peer ACKed our handshake fragment");
3195                 /* Fragmentation handler, send next fragment */
3196                 return FR_TLS_REQUEST;
3197
3198         case application_data:
3199                 RDEBUG2("Peer ACKed our application data fragment");
3200                 return FR_TLS_REQUEST;
3201
3202                 /*
3203                  *      For the rest of the conditions, switch over
3204                  *      to the default section below.
3205                  */
3206         default:
3207                 REDEBUG("Invalid ACK received: %d", ssn->info.content_type);
3208                 return FR_TLS_INVALID;
3209         }
3210 }
3211 #endif  /* WITH_TLS */
3212