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