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