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