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