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