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