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