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