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