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