Fix build errors
[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 #include <freeradius-devel/ident.h>
26 RCSID("$Id$")
27
28 #include <freeradius-devel/autoconf.h>
29 #include <freeradius-devel/radiusd.h>
30 #include <freeradius-devel/tls.h>
31 #include <freeradius-devel/rad_assert.h>
32
33 #ifdef HAVE_SYS_STAT_H
34 #include <sys/stat.h>
35 #endif
36
37 #ifdef WITH_TLS
38 #ifdef HAVE_OPENSSL_RAND_H
39 #include <openssl/rand.h>
40 #endif
41
42 #ifdef HAVE_OPENSSL_OCSP_H
43 #include <openssl/ocsp.h>
44 #endif
45
46 #ifdef HAVE_PTHREAD_H
47 #define PTHREAD_MUTEX_LOCK pthread_mutex_lock
48 #define PTHREAD_MUTEX_UNLOCK pthread_mutex_unlock
49 #else
50 #define PTHREAD_MUTEX_LOCK(_x)
51 #define PTHREAD_MUTEX_UNLOCK(_x)
52 #endif
53
54
55 /* record */
56 static void             record_init(record_t *buf);
57 static void             record_close(record_t *buf);
58 static unsigned int     record_plus(record_t *buf, const void *ptr,
59                                     unsigned int size);
60 static unsigned int     record_minus(record_t *buf, void *ptr,
61                                      unsigned int size);
62
63 tls_session_t *tls_new_session(SSL_CTX *ssl_ctx, int client_cert)
64 {
65         tls_session_t *state = NULL;
66         SSL *new_tls = NULL;
67
68         client_cert = client_cert; /* -Wunused.  See bug #350 */
69
70         if ((new_tls = SSL_new(ssl_ctx)) == NULL) {
71                 radlog(L_ERR, "SSL: Error creating new SSL: %s",
72                        ERR_error_string(ERR_get_error(), NULL));
73                 return NULL;
74         }
75
76         /* We use the SSL's "app_data" to indicate a call-back */
77         SSL_set_app_data(new_tls, NULL);
78
79         state = (tls_session_t *)malloc(sizeof(*state));
80         memset(state, 0, sizeof(*state));
81         session_init(state);
82
83         state->ctx = ssl_ctx;
84         state->ssl = new_tls;
85
86         /*
87          *      Initialize callbacks
88          */
89         state->record_init = record_init;
90         state->record_close = record_close;
91         state->record_plus = record_plus;
92         state->record_minus = record_minus;
93
94         /*
95          *      Create & hook the BIOs to handle the dirty side of the
96          *      SSL.  This is *very important* as we want to handle
97          *      the transmission part.  Now the only IO interface
98          *      that SSL is aware of, is our defined BIO buffers.
99          *
100          *      This means that all SSL IO is done to/from memory,
101          *      and we can update those BIOs from the packets we've
102          *      received.
103          */
104         state->into_ssl = BIO_new(BIO_s_mem());
105         state->from_ssl = BIO_new(BIO_s_mem());
106         SSL_set_bio(state->ssl, state->into_ssl, state->from_ssl);
107
108         /*
109          *      Add the message callback to identify what type of
110          *      message/handshake is passed
111          */
112         SSL_set_msg_callback(new_tls, cbtls_msg);
113         SSL_set_msg_callback_arg(new_tls, state);
114         SSL_set_info_callback(new_tls, cbtls_info);
115
116         /*
117          *      In Server mode we only accept.
118          */
119         SSL_set_accept_state(state->ssl);
120
121         return state;
122 }
123
124 /*
125  *      Print out some text describing the error.
126  */
127 static int int_ssl_check(REQUEST *request, SSL *s, int ret, const char *text)
128 {
129         int e;
130         unsigned long l;
131
132         if ((l = ERR_get_error()) != 0) {
133                 const char *p = ERR_error_string(l, NULL);
134                 VALUE_PAIR *vp;
135
136                 radlog(L_ERR, "SSL error %s", p);
137
138                 if (request) {
139                         vp = pairmake("Module-Failure-Message", p, T_OP_ADD);
140                         if (vp) pairadd(&request->packet->vps, vp);
141                 }
142         }
143         e = SSL_get_error(s, ret);
144
145         switch(e) {
146                 /*
147                  *      These seem to be harmless and already "dealt
148                  *      with" by our non-blocking environment. NB:
149                  *      "ZERO_RETURN" is the clean "error"
150                  *      indicating a successfully closed SSL
151                  *      tunnel. We let this happen because our IO
152                  *      loop should not appear to have broken on
153                  *      this condition - and outside the IO loop, the
154                  *      "shutdown" state is checked.
155                  *
156                  *      Don't print anything if we ignore the error.
157                  */
158         case SSL_ERROR_NONE:
159         case SSL_ERROR_WANT_READ:
160         case SSL_ERROR_WANT_WRITE:
161         case SSL_ERROR_WANT_X509_LOOKUP:
162         case SSL_ERROR_ZERO_RETURN:
163                 break;
164
165                 /*
166                  *      These seem to be indications of a genuine
167                  *      error that should result in the SSL tunnel
168                  *      being regarded as "dead".
169                  */
170         case SSL_ERROR_SYSCALL:
171                 radlog(L_ERR, "SSL: %s failed in a system call (%d), TLS session fails.",
172                        text, ret);
173                 return 0;
174
175         case SSL_ERROR_SSL:
176                 radlog(L_ERR, "SSL: %s failed inside of TLS (%d), TLS session fails.",
177                        text, ret);
178                 return 0;
179
180         default:
181                 /*
182                  *      For any other errors that (a) exist, and (b)
183                  *      crop up - we need to interpret what to do with
184                  *      them - so "politely inform" the caller that
185                  *      the code needs updating here.
186                  */
187                 radlog(L_ERR, "SSL: FATAL SSL error ..... %d\n", e);
188                 return 0;
189         }
190
191         return 1;
192 }
193
194 /*
195  * We are the server, we always get the dirty data
196  * (Handshake data is also considered as dirty data)
197  * During handshake, since SSL API handles itself,
198  * After clean-up, dirty_out will be filled with
199  * the data required for handshaking. So we check
200  * if dirty_out is empty then we simply send it back.
201  * As of now, if handshake is successful, then we keep going,
202  * otherwise we fail.
203  *
204  * Fill the Bio with the dirty data to clean it
205  * Get the cleaned data from SSL, if it is not Handshake data
206  */
207 int tls_handshake_recv(REQUEST *request, tls_session_t *ssn)
208 {
209         int err;
210
211         BIO_write(ssn->into_ssl, ssn->dirty_in.data, ssn->dirty_in.used);
212
213         err = SSL_read(ssn->ssl, ssn->clean_out.data + ssn->clean_out.used,
214                        sizeof(ssn->clean_out.data) - ssn->clean_out.used);
215         if (err > 0) {
216                 ssn->clean_out.used += err;
217                 record_init(&ssn->dirty_in);
218                 return 1;
219         }
220
221         if (!int_ssl_check(request, ssn->ssl, err, "SSL_read")) {
222                 return 0;
223         }
224
225         /* Some Extra STATE information for easy debugging */
226         if (SSL_is_init_finished(ssn->ssl)) {
227                 DEBUG2("SSL Connection Established\n");
228         }
229         if (SSL_in_init(ssn->ssl)) {
230                 DEBUG2("In SSL Handshake Phase\n");
231         }
232         if (SSL_in_before(ssn->ssl)) {
233                 DEBUG2("Before SSL Handshake Phase\n");
234         }
235         if (SSL_in_accept_init(ssn->ssl)) {
236                 DEBUG2("In SSL Accept mode \n");
237         }
238         if (SSL_in_connect_init(ssn->ssl)) {
239                 DEBUG2("In SSL Connect mode \n");
240         }
241
242         err = BIO_ctrl_pending(ssn->from_ssl);
243         if (err > 0) {
244                 err = BIO_read(ssn->from_ssl, ssn->dirty_out.data,
245                                sizeof(ssn->dirty_out.data));
246                 if (err > 0) {
247                         ssn->dirty_out.used = err;
248
249                 } else if (BIO_should_retry(ssn->from_ssl)) {
250                         record_init(&ssn->dirty_in);
251                         DEBUG2("  tls: Asking for more data in tunnel");
252                         return 1;
253
254                 } else {
255                         int_ssl_check(request, ssn->ssl, err, "BIO_read");
256                         record_init(&ssn->dirty_in);
257                         return 0;
258                 }
259         } else {
260                 DEBUG2("SSL Application Data");
261                 /* Its clean application data, do whatever we want */
262                 record_init(&ssn->clean_out);
263         }
264
265         /* We are done with dirty_in, reinitialize it */
266         record_init(&ssn->dirty_in);
267         return 1;
268 }
269
270 /*
271  *      Take clear-text user data, and encrypt it into the output buffer,
272  *      to send to the client at the other end of the SSL connection.
273  */
274 int tls_handshake_send(REQUEST *request, tls_session_t *ssn)
275 {
276         int err;
277
278         /*
279          *      If there's un-encrypted data in 'clean_in', then write
280          *      that data to the SSL session, and then call the BIO function
281          *      to get that encrypted data from the SSL session, into
282          *      a buffer which we can then package into an EAP packet.
283          *
284          *      Based on Server's logic this clean_in is expected to
285          *      contain the data to send to the client.
286          */
287         if (ssn->clean_in.used > 0) {
288                 int written;
289
290                 written = SSL_write(ssn->ssl, ssn->clean_in.data, ssn->clean_in.used);
291                 record_minus(&ssn->clean_in, NULL, written);
292
293                 /* Get the dirty data from Bio to send it */
294                 err = BIO_read(ssn->from_ssl, ssn->dirty_out.data,
295                                sizeof(ssn->dirty_out.data));
296                 if (err > 0) {
297                         ssn->dirty_out.used = err;
298                 } else {
299                         int_ssl_check(request, ssn->ssl, err, "handshake_send");
300                 }
301         }
302
303         return 1;
304 }
305
306 void session_init(tls_session_t *ssn)
307 {
308         ssn->ssl = NULL;
309         ssn->into_ssl = ssn->from_ssl = NULL;
310         record_init(&ssn->clean_in);
311         record_init(&ssn->clean_out);
312         record_init(&ssn->dirty_in);
313         record_init(&ssn->dirty_out);
314
315         memset(&ssn->info, 0, sizeof(ssn->info));
316
317         ssn->offset = 0;
318         ssn->fragment = 0;
319         ssn->tls_msg_len = 0;
320         ssn->length_flag = 0;
321         ssn->opaque = NULL;
322         ssn->free_opaque = NULL;
323 }
324
325 void session_close(tls_session_t *ssn)
326 {       
327         if (ssn->ssl->session) {
328                 VALUE_PAIR *vp;
329
330                 vp = SSL_SESSION_get_ex_data(ssn->ssl->session,
331                                              FR_TLS_EX_INDEX_VPS);
332                 if (vp) pairfree(&vp);
333         }
334
335         SSL_set_quiet_shutdown(ssn->ssl, 1);
336         SSL_shutdown(ssn->ssl);
337
338         if(ssn->ssl)
339                 SSL_free(ssn->ssl);
340 #if 0
341 /*
342  * WARNING: SSL_free seems to decrement the reference counts already,
343  *      so doing this might crash the application.
344  */
345         if(ssn->into_ssl)
346                 BIO_free(ssn->into_ssl);
347         if(ssn->from_ssl)
348                 BIO_free(ssn->from_ssl);
349 #endif
350         record_close(&ssn->clean_in);
351         record_close(&ssn->clean_out);
352         record_close(&ssn->dirty_in);
353         record_close(&ssn->dirty_out);
354         session_init(ssn);
355 }
356
357 void session_free(void *ssn)
358 {
359         tls_session_t *sess = (tls_session_t *)ssn;
360
361         if (!ssn) return;
362
363         /*
364          *      Free any opaque TTLS or PEAP data.
365          */
366         if ((sess->opaque) && (sess->free_opaque)) {
367                 sess->free_opaque(sess->opaque);
368                 sess->opaque = NULL;
369         }
370
371         session_close(sess);
372
373         free(sess);
374 }
375
376 static void record_init(record_t *rec)
377 {
378         rec->used = 0;
379 }
380
381 static void record_close(record_t *rec)
382 {
383         rec->used = 0;
384 }
385
386
387 /*
388  *      Copy data to the intermediate buffer, before we send
389  *      it somewhere.
390  */
391 static unsigned int record_plus(record_t *rec, const void *ptr,
392                                 unsigned int size)
393 {
394         unsigned int added = MAX_RECORD_SIZE - rec->used;
395
396         if(added > size)
397                 added = size;
398         if(added == 0)
399                 return 0;
400         memcpy(rec->data + rec->used, ptr, added);
401         rec->used += added;
402         return added;
403 }
404
405 /*
406  *      Take data from the buffer, and give it to the caller.
407  */
408 static unsigned int record_minus(record_t *rec, void *ptr,
409                                  unsigned int size)
410 {
411         unsigned int taken = rec->used;
412
413         if(taken > size)
414                 taken = size;
415         if(taken == 0)
416                 return 0;
417         if(ptr)
418                 memcpy(ptr, rec->data, taken);
419         rec->used -= taken;
420
421         /*
422          *      This is pretty bad...
423          */
424         if(rec->used > 0)
425                 memmove(rec->data, rec->data + taken, rec->used);
426         return taken;
427 }
428
429 void tls_session_information(tls_session_t *tls_session)
430 {
431         const char *str_write_p, *str_version, *str_content_type = "";
432         const char *str_details1 = "", *str_details2= "";
433         REQUEST *request;
434
435         /*
436          *      Don't print this out in the normal course of
437          *      operations.
438          */
439         if (debug_flag == 0) {
440                 return;
441         }
442
443         str_write_p = tls_session->info.origin ? ">>>" : "<<<";
444
445         switch (tls_session->info.version)
446         {
447         case SSL2_VERSION:
448                 str_version = "SSL 2.0";
449                 break;
450         case SSL3_VERSION:
451                 str_version = "SSL 3.0 ";
452                 break;
453         case TLS1_VERSION:
454                 str_version = "TLS 1.0 ";
455                 break;
456         default:
457                 str_version = "Unknown TLS version";
458                 break;
459         }
460
461         if (tls_session->info.version == SSL3_VERSION ||
462             tls_session->info.version == TLS1_VERSION) {
463                 switch (tls_session->info.content_type) {
464                 case SSL3_RT_CHANGE_CIPHER_SPEC:
465                         str_content_type = "ChangeCipherSpec";
466                         break;
467                 case SSL3_RT_ALERT:
468                         str_content_type = "Alert";
469                         break;
470                 case SSL3_RT_HANDSHAKE:
471                         str_content_type = "Handshake";
472                         break;
473                 case SSL3_RT_APPLICATION_DATA:
474                         str_content_type = "ApplicationData";
475                         break;
476                 default:
477                         str_content_type = "UnknownContentType";
478                         break;
479                 }
480
481                 if (tls_session->info.content_type == SSL3_RT_ALERT) {
482                         str_details1 = ", ???";
483
484                         if (tls_session->info.record_len == 2) {
485
486                                 switch (tls_session->info.alert_level) {
487                                 case SSL3_AL_WARNING:
488                                         str_details1 = ", warning";
489                                         break;
490                                 case SSL3_AL_FATAL:
491                                         str_details1 = ", fatal";
492                                         break;
493                                 }
494
495                                 str_details2 = " ???";
496                                 switch (tls_session->info.alert_description) {
497                                 case SSL3_AD_CLOSE_NOTIFY:
498                                         str_details2 = " close_notify";
499                                         break;
500                                 case SSL3_AD_UNEXPECTED_MESSAGE:
501                                         str_details2 = " unexpected_message";
502                                         break;
503                                 case SSL3_AD_BAD_RECORD_MAC:
504                                         str_details2 = " bad_record_mac";
505                                         break;
506                                 case TLS1_AD_DECRYPTION_FAILED:
507                                         str_details2 = " decryption_failed";
508                                         break;
509                                 case TLS1_AD_RECORD_OVERFLOW:
510                                         str_details2 = " record_overflow";
511                                         break;
512                                 case SSL3_AD_DECOMPRESSION_FAILURE:
513                                         str_details2 = " decompression_failure";
514                                         break;
515                                 case SSL3_AD_HANDSHAKE_FAILURE:
516                                         str_details2 = " handshake_failure";
517                                         break;
518                                 case SSL3_AD_BAD_CERTIFICATE:
519                                         str_details2 = " bad_certificate";
520                                         break;
521                                 case SSL3_AD_UNSUPPORTED_CERTIFICATE:
522                                         str_details2 = " unsupported_certificate";
523                                         break;
524                                 case SSL3_AD_CERTIFICATE_REVOKED:
525                                         str_details2 = " certificate_revoked";
526                                         break;
527                                 case SSL3_AD_CERTIFICATE_EXPIRED:
528                                         str_details2 = " certificate_expired";
529                                         break;
530                                 case SSL3_AD_CERTIFICATE_UNKNOWN:
531                                         str_details2 = " certificate_unknown";
532                                         break;
533                                 case SSL3_AD_ILLEGAL_PARAMETER:
534                                         str_details2 = " illegal_parameter";
535                                         break;
536                                 case TLS1_AD_UNKNOWN_CA:
537                                         str_details2 = " unknown_ca";
538                                         break;
539                                 case TLS1_AD_ACCESS_DENIED:
540                                         str_details2 = " access_denied";
541                                         break;
542                                 case TLS1_AD_DECODE_ERROR:
543                                         str_details2 = " decode_error";
544                                         break;
545                                 case TLS1_AD_DECRYPT_ERROR:
546                                         str_details2 = " decrypt_error";
547                                         break;
548                                 case TLS1_AD_EXPORT_RESTRICTION:
549                                         str_details2 = " export_restriction";
550                                         break;
551                                 case TLS1_AD_PROTOCOL_VERSION:
552                                         str_details2 = " protocol_version";
553                                         break;
554                                 case TLS1_AD_INSUFFICIENT_SECURITY:
555                                         str_details2 = " insufficient_security";
556                                         break;
557                                 case TLS1_AD_INTERNAL_ERROR:
558                                         str_details2 = " internal_error";
559                                         break;
560                                 case TLS1_AD_USER_CANCELLED:
561                                         str_details2 = " user_canceled";
562                                         break;
563                                 case TLS1_AD_NO_RENEGOTIATION:
564                                         str_details2 = " no_renegotiation";
565                                         break;
566                                 }
567                         }
568                 }
569
570                 if (tls_session->info.content_type == SSL3_RT_HANDSHAKE) {
571                         str_details1 = "???";
572
573                         if (tls_session->info.record_len > 0)
574                         switch (tls_session->info.handshake_type)
575                         {
576                         case SSL3_MT_HELLO_REQUEST:
577                                 str_details1 = ", HelloRequest";
578                                 break;
579                         case SSL3_MT_CLIENT_HELLO:
580                                 str_details1 = ", ClientHello";
581                                 break;
582                         case SSL3_MT_SERVER_HELLO:
583                                 str_details1 = ", ServerHello";
584                                 break;
585                         case SSL3_MT_CERTIFICATE:
586                                 str_details1 = ", Certificate";
587                                 break;
588                         case SSL3_MT_SERVER_KEY_EXCHANGE:
589                                 str_details1 = ", ServerKeyExchange";
590                                 break;
591                         case SSL3_MT_CERTIFICATE_REQUEST:
592                                 str_details1 = ", CertificateRequest";
593                                 break;
594                         case SSL3_MT_SERVER_DONE:
595                                 str_details1 = ", ServerHelloDone";
596                                 break;
597                         case SSL3_MT_CERTIFICATE_VERIFY:
598                                 str_details1 = ", CertificateVerify";
599                                 break;
600                         case SSL3_MT_CLIENT_KEY_EXCHANGE:
601                                 str_details1 = ", ClientKeyExchange";
602                                 break;
603                         case SSL3_MT_FINISHED:
604                                 str_details1 = ", Finished";
605                                 break;
606                         }
607                 }
608         }
609
610         snprintf(tls_session->info.info_description, 
611                  sizeof(tls_session->info.info_description),
612                  "%s %s%s [length %04lx]%s%s\n",
613                  str_write_p, str_version, str_content_type,
614                  (unsigned long)tls_session->info.record_len,
615                  str_details1, str_details2);
616
617         request = SSL_get_ex_data(tls_session->ssl, FR_TLS_EX_INDEX_REQUEST);
618
619         RDEBUG2("%s\n", tls_session->info.info_description);
620 }
621
622 static CONF_PARSER cache_config[] = {
623         { "enable", PW_TYPE_BOOLEAN,
624           offsetof(fr_tls_server_conf_t, session_cache_enable), NULL, "no" },
625         { "lifetime", PW_TYPE_INTEGER,
626           offsetof(fr_tls_server_conf_t, session_timeout), NULL, "24" },
627         { "max_entries", PW_TYPE_INTEGER,
628           offsetof(fr_tls_server_conf_t, session_cache_size), NULL, "255" },
629         { "name", PW_TYPE_STRING_PTR,
630           offsetof(fr_tls_server_conf_t, session_id_name), NULL, NULL},
631         { NULL, -1, 0, NULL, NULL }           /* end the list */
632 };
633
634 static CONF_PARSER verify_config[] = {
635         { "tmpdir", PW_TYPE_STRING_PTR,
636           offsetof(fr_tls_server_conf_t, verify_tmp_dir), NULL, NULL},
637         { "client", PW_TYPE_STRING_PTR,
638           offsetof(fr_tls_server_conf_t, verify_client_cert_cmd), NULL, NULL},
639         { NULL, -1, 0, NULL, NULL }           /* end the list */
640 };
641
642 #ifdef HAVE_OPENSSL_OCSP_H
643 static CONF_PARSER ocsp_config[] = {
644         { "enable", PW_TYPE_BOOLEAN,
645           offsetof(fr_tls_server_conf_t, ocsp_enable), NULL, "no"},
646         { "override_cert_url", PW_TYPE_BOOLEAN,
647           offsetof(fr_tls_server_conf_t, ocsp_override_url), NULL, "no"},
648         { "url", PW_TYPE_STRING_PTR,
649           offsetof(fr_tls_server_conf_t, ocsp_url), NULL, NULL },
650         { NULL, -1, 0, NULL, NULL }           /* end the list */
651 };
652 #endif
653
654 static CONF_PARSER tls_server_config[] = {
655         { "rsa_key_exchange", PW_TYPE_BOOLEAN,
656           offsetof(fr_tls_server_conf_t, rsa_key), NULL, "no" },
657         { "dh_key_exchange", PW_TYPE_BOOLEAN,
658           offsetof(fr_tls_server_conf_t, dh_key), NULL, "yes" },
659         { "rsa_key_length", PW_TYPE_INTEGER,
660           offsetof(fr_tls_server_conf_t, rsa_key_length), NULL, "512" },
661         { "dh_key_length", PW_TYPE_INTEGER,
662           offsetof(fr_tls_server_conf_t, dh_key_length), NULL, "512" },
663         { "verify_depth", PW_TYPE_INTEGER,
664           offsetof(fr_tls_server_conf_t, verify_depth), NULL, "0" },
665         { "CA_path", PW_TYPE_FILENAME,
666           offsetof(fr_tls_server_conf_t, ca_path), NULL, NULL },
667         { "pem_file_type", PW_TYPE_BOOLEAN,
668           offsetof(fr_tls_server_conf_t, file_type), NULL, "yes" },
669         { "private_key_file", PW_TYPE_FILENAME,
670           offsetof(fr_tls_server_conf_t, private_key_file), NULL, NULL },
671         { "certificate_file", PW_TYPE_FILENAME,
672           offsetof(fr_tls_server_conf_t, certificate_file), NULL, NULL },
673         { "CA_file", PW_TYPE_FILENAME,
674           offsetof(fr_tls_server_conf_t, ca_file), NULL, NULL },
675         { "private_key_password", PW_TYPE_STRING_PTR,
676           offsetof(fr_tls_server_conf_t, private_key_password), NULL, NULL },
677         { "dh_file", PW_TYPE_STRING_PTR,
678           offsetof(fr_tls_server_conf_t, dh_file), NULL, NULL },
679         { "random_file", PW_TYPE_STRING_PTR,
680           offsetof(fr_tls_server_conf_t, random_file), NULL, NULL },
681         { "fragment_size", PW_TYPE_INTEGER,
682           offsetof(fr_tls_server_conf_t, fragment_size), NULL, "1024" },
683         { "include_length", PW_TYPE_BOOLEAN,
684           offsetof(fr_tls_server_conf_t, include_length), NULL, "yes" },
685         { "check_crl", PW_TYPE_BOOLEAN,
686           offsetof(fr_tls_server_conf_t, check_crl), NULL, "no"},
687         { "allow_expired_crl", PW_TYPE_BOOLEAN,
688           offsetof(fr_tls_server_conf_t, allow_expired_crl), NULL, NULL},
689         { "check_cert_cn", PW_TYPE_STRING_PTR,
690           offsetof(fr_tls_server_conf_t, check_cert_cn), NULL, NULL},
691         { "cipher_list", PW_TYPE_STRING_PTR,
692           offsetof(fr_tls_server_conf_t, cipher_list), NULL, NULL},
693         { "check_cert_issuer", PW_TYPE_STRING_PTR,
694           offsetof(fr_tls_server_conf_t, check_cert_issuer), NULL, NULL},
695         { "make_cert_command", PW_TYPE_STRING_PTR,
696           offsetof(fr_tls_server_conf_t, make_cert_command), NULL, NULL},
697
698         { "cache", PW_TYPE_SUBSECTION, 0, NULL, (const void *) cache_config },
699
700         { "verify", PW_TYPE_SUBSECTION, 0, NULL, (const void *) verify_config },
701
702 #ifdef HAVE_OPENSSL_OCSP_H
703         { "ocsp", PW_TYPE_SUBSECTION, 0, NULL, (const void *) ocsp_config },
704 #endif
705
706         { NULL, -1, 0, NULL, NULL }           /* end the list */
707 };
708
709 /*
710  *      TODO: Check for the type of key exchange * like conf->dh_key
711  */
712 static int load_dh_params(SSL_CTX *ctx, char *file)
713 {
714         DH *dh = NULL;
715         BIO *bio;
716
717         if ((bio = BIO_new_file(file, "r")) == NULL) {
718                 radlog(L_ERR, "rlm_eap_tls: Unable to open DH file - %s", file);
719                 return -1;
720         }
721
722         dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
723         BIO_free(bio);
724         if (!dh) {
725                 DEBUG2("WARNING: rlm_eap_tls: Unable to set DH parameters.  DH cipher suites may not work!");
726                 DEBUG2("WARNING: Fix this by running the OpenSSL command listed in eap.conf");
727                 return 0;
728         }
729
730         if (SSL_CTX_set_tmp_dh(ctx, dh) < 0) {
731                 radlog(L_ERR, "rlm_eap_tls: Unable to set DH parameters");
732                 DH_free(dh);
733                 return -1;
734         }
735
736         DH_free(dh);
737         return 0;
738 }
739
740
741 /*
742  *      Generate ephemeral RSA keys.
743  */
744 static int generate_eph_rsa_key(SSL_CTX *ctx)
745 {
746         RSA *rsa;
747
748         rsa = RSA_generate_key(512, RSA_F4, NULL, NULL);
749
750         if (!SSL_CTX_set_tmp_rsa(ctx, rsa)) {
751                 radlog(L_ERR, "rlm_eap_tls: Couldn't set ephemeral RSA key");
752                 return -1;
753         }
754
755         RSA_free(rsa);
756         return 0;
757 }
758
759
760 /*
761  *      These functions don't do anything other than print debugging
762  *      messages.
763  *
764  *      FIXME: Write sessions to some long-term storage, so that
765  *             session resumption can still occur after the server
766  *             restarts.
767  */
768 #define MAX_SESSION_SIZE (256)
769
770 static void cbtls_remove_session(UNUSED SSL_CTX *ctx, SSL_SESSION *sess)
771 {
772         size_t size;
773         char buffer[2 * MAX_SESSION_SIZE + 1];
774
775         size = sess->session_id_length;
776         if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
777
778         fr_bin2hex(sess->session_id, buffer, size);
779
780         DEBUG2("  SSL: Removing session %s from the cache", buffer);
781         SSL_SESSION_free(sess);
782
783         return;
784 }
785
786 static int cbtls_new_session(UNUSED SSL *s, SSL_SESSION *sess)
787 {
788         size_t size;
789         char buffer[2 * MAX_SESSION_SIZE + 1];
790
791         size = sess->session_id_length;
792         if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
793
794         fr_bin2hex(sess->session_id, buffer, size);
795
796         DEBUG2("  SSL: adding session %s to cache", buffer);
797
798         return 1;
799 }
800
801 static SSL_SESSION *cbtls_get_session(UNUSED SSL *s,
802                                       unsigned char *data, int len,
803                                       UNUSED int *copy)
804 {
805         size_t size;
806         char buffer[2 * MAX_SESSION_SIZE + 1];
807
808         size = len;
809         if (size > MAX_SESSION_SIZE) size = MAX_SESSION_SIZE;
810
811         fr_bin2hex(data, buffer, size);
812
813         DEBUG2("  SSL: Client requested nonexistent cached session %s",
814                buffer);
815
816         return NULL;
817 }
818
819 #ifdef HAVE_OPENSSL_OCSP_H
820 /*
821  * This function extracts the OCSP Responder URL
822  * from an existing x509 certificate.
823  */
824 static int ocsp_parse_cert_url(X509 *cert, char **phost, char **pport,
825                                char **ppath, int *pssl)
826 {
827         int i;
828
829         AUTHORITY_INFO_ACCESS *aia;
830         ACCESS_DESCRIPTION *ad;
831
832         aia = X509_get_ext_d2i(cert, NID_info_access, NULL, NULL);
833
834         for (i = 0; i < sk_ACCESS_DESCRIPTION_num(aia); i++) {
835                 ad = sk_ACCESS_DESCRIPTION_value(aia, 0);
836                 if (OBJ_obj2nid(ad->method) == NID_ad_OCSP) {
837                         if (ad->location->type == GEN_URI) {
838                                 if(OCSP_parse_url(ad->location->d.ia5->data,
839                                         phost, pport, ppath, pssl))
840                                         return 1;
841                         }
842                 }
843         }
844         return 0;
845 }
846
847 /*
848  * This function sends a OCSP request to a defined OCSP responder
849  * and checks the OCSP response for correctness.
850  */
851 static int ocsp_check(X509_STORE *store, X509 *issuer_cert, X509 *client_cert,
852                       fr_tls_server_conf_t *conf)
853 {
854         OCSP_CERTID *certid;
855         OCSP_REQUEST *req;
856         OCSP_RESPONSE *resp;
857         OCSP_BASICRESP *bresp = NULL;
858         char *host = NULL;
859         char *port = NULL;
860         char *path = NULL;
861         int use_ssl = -1;
862         BIO *cbio;
863         int ocsp_ok;
864         int status;
865
866         /*
867          * Create OCSP Request
868          */
869         certid = OCSP_cert_to_id(NULL, client_cert, issuer_cert);
870         req = OCSP_REQUEST_new();
871         OCSP_request_add0_id(req, certid);
872         OCSP_request_add1_nonce(req, NULL, 8);
873
874         /*
875          * Send OCSP Request and get OCSP Response
876          */
877
878         /* Get OCSP responder URL */
879         if(conf->ocsp_override_url) {
880                 OCSP_parse_url(conf->ocsp_url, &host, &port, &path, &use_ssl);
881         }
882         else {
883                 ocsp_parse_cert_url(client_cert, &host, &port, &path, &use_ssl);
884         }
885
886         DEBUG2("[ocsp] --> Responder URL = http://%s:%s%s", host, port, path);
887
888         /* Setup BIO socket to OCSP responder */
889         cbio = BIO_new_connect(host);
890         BIO_set_conn_port(cbio, port);
891         BIO_do_connect(cbio);
892
893         /* Send OCSP request and wait for response */
894         resp = OCSP_sendreq_bio(cbio, path, req);
895         if(resp==0) {
896                 radlog(L_ERR, "Error: Couldn't get OCSP response");
897                 ocsp_ok = 0;
898                 goto ocsp_end;
899         }
900
901         /* Verify OCSP response */
902         status = OCSP_response_status(resp);
903         if(status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
904                 radlog(L_ERR, "Error: OCSP response status: %s", OCSP_response_status_str(status));
905                 ocsp_ok = 0;
906                 goto ocsp_end;
907         }
908         bresp = OCSP_response_get1_basic(resp);
909         if(OCSP_check_nonce(req, bresp)!=1) {
910                 radlog(L_ERR, "Error: OCSP response has wrong nonce value");
911                 ocsp_ok = 0;
912                 goto ocsp_end;
913         }
914         if(OCSP_basic_verify(bresp, NULL, store, 0)!=1){
915                 radlog(L_ERR, "Error: Couldn't verify OCSP basic response");
916                 ocsp_ok = 0;
917                 goto ocsp_end;
918         }
919
920         ocsp_ok = 1;
921
922 ocsp_end:
923         /* Free OCSP Stuff */
924         OCSP_REQUEST_free(req);
925         OCSP_RESPONSE_free(resp);
926         free(host);
927         free(port);
928         free(path);
929         BIO_free_all(cbio);
930         OCSP_BASICRESP_free(bresp);
931
932         if (ocsp_ok) {
933                 DEBUG2("[ocsp] --> Certificate is valid!");
934         } else {
935                 DEBUG2("[ocsp] --> Certificate has been expired/revoked!");
936         }
937
938         return ocsp_ok;
939 }
940 #endif  /* HAVE_OPENSSL_OCSP_H */
941
942 /*
943  *      For creating certificate attributes.
944  */
945 static const char *cert_attr_names[5][2] = {
946   { "TLS-Client-Cert-Serial",           "TLS-Cert-Serial" },
947   { "TLS-Client-Cert-Expiration",       "TLS-Cert-Expiration" },
948   { "TLS-Client-Cert-Subject",          "TLS-Cert-Subject" },
949   { "TLS-Client-Cert-Issuer",           "TLS-Cert-Issuer" },
950   { "TLS-Client-Cert-Common-Name",      "TLS-Cert-Common-Name" }
951 };
952
953 #define EAPTLS_SERIAL           (0)
954 #define EAPTLS_EXPIRATION       (1)
955 #define EAPTLS_SUBJECT          (2)
956 #define EAPTLS_ISSUER           (3)
957 #define EAPTLS_CN               (4)
958
959 /*
960  *      Before trusting a certificate, you must make sure that the
961  *      certificate is 'valid'. There are several steps that your
962  *      application can take in determining if a certificate is
963  *      valid. Commonly used steps are:
964  *
965  *      1.Verifying the certificate's signature, and verifying that
966  *      the certificate has been issued by a trusted Certificate
967  *      Authority.
968  *
969  *      2.Verifying that the certificate is valid for the present date
970  *      (i.e. it is being presented within its validity dates).
971  *
972  *      3.Verifying that the certificate has not been revoked by its
973  *      issuing Certificate Authority, by checking with respect to a
974  *      Certificate Revocation List (CRL).
975  *
976  *      4.Verifying that the credentials presented by the certificate
977  *      fulfill additional requirements specific to the application,
978  *      such as with respect to access control lists or with respect
979  *      to OCSP (Online Certificate Status Processing).
980  *
981  *      NOTE: This callback will be called multiple times based on the
982  *      depth of the root certificate chain
983  */
984 int cbtls_verify(int ok, X509_STORE_CTX *ctx)
985 {
986         char subject[1024]; /* Used for the subject name */
987         char issuer[1024]; /* Used for the issuer name */
988         char common_name[1024];
989         char cn_str[1024];
990         char buf[64];
991         X509 *client_cert;
992         X509 *issuer_cert;
993         SSL *ssl;
994         int err, depth, lookup;
995         fr_tls_server_conf_t *conf;
996         int my_ok = ok;
997         REQUEST *request;
998         ASN1_INTEGER *sn = NULL;
999         ASN1_TIME *asn_time = NULL;
1000         VALUE_PAIR **certs;
1001         char **identity;
1002 #ifdef HAVE_OPENSSL_OCSP_H
1003         X509_STORE *ocsp_store = NULL;
1004 #endif
1005
1006         client_cert = X509_STORE_CTX_get_current_cert(ctx);
1007         err = X509_STORE_CTX_get_error(ctx);
1008         depth = X509_STORE_CTX_get_error_depth(ctx);
1009
1010         lookup = depth;
1011
1012         /*
1013          *      Log client/issuing cert.  If there's an error, log
1014          *      issuing cert.
1015          */
1016         if ((lookup > 1) && !my_ok) lookup = 1;
1017
1018         /*
1019          * Retrieve the pointer to the SSL of the connection currently treated
1020          * and the application specific data stored into the SSL object.
1021          */
1022         ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
1023         conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1024         if (!conf) return 1;
1025
1026         request = (REQUEST *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_REQUEST);
1027
1028         if (!request) return 1; /* FIXME: outbound TLS */
1029
1030         rad_assert(request != NULL);
1031         certs = (VALUE_PAIR **)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CERTS);
1032         rad_assert(certs != NULL);
1033         identity = (char **)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_IDENTITY);
1034 #ifdef HAVE_OPENSSL_OCSP_H
1035         ocsp_store = (X509_STORE *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_STORE);
1036 #endif
1037
1038
1039         /*
1040          *      Get the Serial Number
1041          */
1042         buf[0] = '\0';
1043         sn = X509_get_serialNumber(client_cert);
1044
1045         /*
1046          *      For this next bit, we create the attributes *only* if
1047          *      we're at the client or issuing certificate.
1048          */
1049         if ((lookup <= 1) && sn && (sn->length < (sizeof(buf) / 2))) {
1050                 char *p = buf;
1051                 int i;
1052
1053                 for (i = 0; i < sn->length; i++) {
1054                         sprintf(p, "%02x", (unsigned int)sn->data[i]);
1055                         p += 2;
1056                 }
1057                 pairadd(certs,
1058                         pairmake(cert_attr_names[EAPTLS_SERIAL][lookup], buf, T_OP_SET));
1059         }
1060
1061
1062         /*
1063          *      Get the Expiration Date
1064          */
1065         buf[0] = '\0';
1066         asn_time = X509_get_notAfter(client_cert);
1067         if ((lookup <= 1) && asn_time && (asn_time->length < MAX_STRING_LEN)) {
1068                 memcpy(buf, (char*) asn_time->data, asn_time->length);
1069                 buf[asn_time->length] = '\0';
1070                 pairadd(certs,
1071                         pairmake(cert_attr_names[EAPTLS_EXPIRATION][lookup], buf, T_OP_SET));
1072         }
1073
1074         /*
1075          *      Get the Subject & Issuer
1076          */
1077         subject[0] = issuer[0] = '\0';
1078         X509_NAME_oneline(X509_get_subject_name(client_cert), subject,
1079                           sizeof(subject));
1080         subject[sizeof(subject) - 1] = '\0';
1081         if ((lookup <= 1) && subject[0] && (strlen(subject) < MAX_STRING_LEN)) {
1082                 pairadd(certs,
1083                         pairmake(cert_attr_names[EAPTLS_SUBJECT][lookup], subject, T_OP_SET));
1084         }
1085
1086         X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), issuer,
1087                           sizeof(issuer));
1088         issuer[sizeof(issuer) - 1] = '\0';
1089         if ((lookup <= 1) && issuer[0] && (strlen(issuer) < MAX_STRING_LEN)) {
1090                 pairadd(certs,
1091                         pairmake(cert_attr_names[EAPTLS_ISSUER][lookup], issuer, T_OP_SET));
1092         }
1093
1094         /*
1095          *      Get the Common Name
1096          */
1097         X509_NAME_get_text_by_NID(X509_get_subject_name(client_cert),
1098                                   NID_commonName, common_name, sizeof(common_name));
1099         common_name[sizeof(common_name) - 1] = '\0';
1100         if ((lookup <= 1) && common_name[0] && (strlen(common_name) < MAX_STRING_LEN)) {
1101                 pairadd(certs,
1102                         pairmake(cert_attr_names[EAPTLS_CN][lookup], common_name, T_OP_SET));
1103         }
1104
1105         /*
1106          *      If the CRL has expired, that might still be OK.
1107          */
1108         if (!my_ok &&
1109             (conf->allow_expired_crl) &&
1110             (err == X509_V_ERR_CRL_HAS_EXPIRED)) {
1111                 my_ok = 1;
1112                 X509_STORE_CTX_set_error( ctx, 0 );
1113         }
1114
1115         if (!my_ok) {
1116                 const char *p = X509_verify_cert_error_string(err);
1117                 radlog(L_ERR,"--> verify error:num=%d:%s\n",err, p);
1118                 radius_pairmake(request, &request->packet->vps,
1119                                 "Module-Failure-Message", p, T_OP_SET);
1120                 return my_ok;
1121         }
1122
1123         switch (ctx->error) {
1124
1125         case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
1126                 radlog(L_ERR, "issuer= %s\n", issuer);
1127                 break;
1128         case X509_V_ERR_CERT_NOT_YET_VALID:
1129         case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
1130                 radlog(L_ERR, "notBefore=");
1131 #if 0
1132                 ASN1_TIME_print(bio_err, X509_get_notBefore(ctx->current_cert));
1133 #endif
1134                 break;
1135         case X509_V_ERR_CERT_HAS_EXPIRED:
1136         case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
1137                 radlog(L_ERR, "notAfter=");
1138 #if 0
1139                 ASN1_TIME_print(bio_err, X509_get_notAfter(ctx->current_cert));
1140 #endif
1141                 break;
1142         }
1143
1144         /*
1145          *      If we're at the actual client cert, apply additional
1146          *      checks.
1147          */
1148         if (depth == 0) {
1149                 /*
1150                  *      If the conf tells us to, check cert issuer
1151                  *      against the specified value and fail
1152                  *      verification if they don't match.
1153                  */
1154                 if (conf->check_cert_issuer &&
1155                     (strcmp(issuer, conf->check_cert_issuer) != 0)) {
1156                         radlog(L_AUTH, "rlm_eap_tls: Certificate issuer (%s) does not match specified value (%s)!", issuer, conf->check_cert_issuer);
1157                         my_ok = 0;
1158                 }
1159
1160                 /*
1161                  *      If the conf tells us to, check the CN in the
1162                  *      cert against xlat'ed value, but only if the
1163                  *      previous checks passed.
1164                  */
1165                 if (my_ok && conf->check_cert_cn) {
1166                         if (!radius_xlat(cn_str, sizeof(cn_str), conf->check_cert_cn, request, NULL)) {
1167                                 radlog(L_ERR, "rlm_eap_tls (%s): xlat failed.",
1168                                        conf->check_cert_cn);
1169                                 /* if this fails, fail the verification */
1170                                 my_ok = 0;
1171                         } else {
1172                                 RDEBUG2("checking certificate CN (%s) with xlat'ed value (%s)", common_name, cn_str);
1173                                 if (strcmp(cn_str, common_name) != 0) {
1174                                         radlog(L_AUTH, "rlm_eap_tls: Certificate CN (%s) does not match specified value (%s)!", common_name, cn_str);
1175                                         my_ok = 0;
1176                                 }
1177                         }
1178                 } /* check_cert_cn */
1179
1180 #ifdef HAVE_OPENSSL_OCSP_H
1181                 if (my_ok && conf->ocsp_enable){
1182                         RDEBUG2("--> Starting OCSP Request");
1183                         if(X509_STORE_CTX_get1_issuer(&issuer_cert, ctx, client_cert)!=1) {
1184                                 radlog(L_ERR, "Error: Couldn't get issuer_cert for %s", common_name);
1185                         }
1186                         my_ok = ocsp_check(ocsp_store, issuer_cert, client_cert, conf);
1187                 }
1188 #endif
1189
1190                 while (conf->verify_client_cert_cmd) {
1191                         char filename[256];
1192                         int fd;
1193                         FILE *fp;
1194
1195                         snprintf(filename, sizeof(filename), "%s/%s.client.XXXXXXXX",
1196                                  conf->verify_tmp_dir, progname);
1197                         fd = mkstemp(filename);
1198                         if (fd < 0) {
1199                                 RDEBUG("Failed creating file in %s: %s",
1200                                        conf->verify_tmp_dir, strerror(errno));
1201                                 break;
1202                         }
1203
1204                         fp = fdopen(fd, "w");
1205                         if (!fp) {
1206                                 RDEBUG("Failed opening file %s: %s",
1207                                        filename, strerror(errno));
1208                                 break;
1209                         }
1210
1211                         if (!PEM_write_X509(fp, client_cert)) {
1212                                 fclose(fp);
1213                                 RDEBUG("Failed writing certificate to file");
1214                                 goto do_unlink;
1215                         }
1216                         fclose(fp);
1217
1218                         if (!radius_pairmake(request, &request->packet->vps,
1219                                              "TLS-Client-Cert-Filename",
1220                                              filename, T_OP_SET)) {
1221                                 RDEBUG("Failed creating TLS-Client-Cert-Filename");
1222
1223                                 goto do_unlink;
1224                         }
1225
1226                         RDEBUG("Verifying client certificate: %s",
1227                                conf->verify_client_cert_cmd);
1228                         if (radius_exec_program(conf->verify_client_cert_cmd,
1229                                                 request, 1, NULL, 0,
1230                                                 request->packet->vps,
1231                                                 NULL, 1) != 0) {
1232                                 radlog(L_AUTH, "rlm_eap_tls: Certificate CN (%s) fails external verification!", common_name);
1233                                 my_ok = 0;
1234                         } else {
1235                                 RDEBUG("Client certificate CN %s passed external validation", common_name);
1236                         }
1237
1238                 do_unlink:
1239                         unlink(filename);
1240                         break;
1241                 }
1242
1243
1244         } /* depth == 0 */
1245
1246         if (debug_flag > 0) {
1247                 RDEBUG2("chain-depth=%d, ", depth);
1248                 RDEBUG2("error=%d", err);
1249
1250                 RDEBUG2("--> User-Name = %s", *identity);
1251                 RDEBUG2("--> BUF-Name = %s", common_name);
1252                 RDEBUG2("--> subject = %s", subject);
1253                 RDEBUG2("--> issuer  = %s", issuer);
1254                 RDEBUG2("--> verify return:%d", my_ok);
1255         }
1256         return my_ok;
1257 }
1258
1259
1260 #ifdef HAVE_OPENSSL_OCSP_H
1261 /*
1262  *      Create Global X509 revocation store and use it to verify
1263  *      OCSP responses
1264  *
1265  *      - Load the trusted CAs
1266  *      - Load the trusted issuer certificates
1267  */
1268 static X509_STORE *init_revocation_store(fr_tls_server_conf_t *conf)
1269 {
1270         X509_STORE *store = NULL;
1271
1272         store = X509_STORE_new();
1273
1274         /* Load the CAs we trust */
1275         if (conf->ca_file || conf->ca_path)
1276                 if(!X509_STORE_load_locations(store, conf->ca_file, conf->ca_path)) {
1277                         radlog(L_ERR, "rlm_eap: X509_STORE error %s", ERR_error_string(ERR_get_error(), NULL));
1278                         radlog(L_ERR, "rlm_eap_tls: Error reading Trusted root CA list %s",conf->ca_file );
1279                         return NULL;
1280                 }
1281
1282 #ifdef X509_V_FLAG_CRL_CHECK
1283         if (conf->check_crl)
1284                 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK);
1285 #endif
1286         return store;
1287 }
1288 #endif  /* HAVE_OPENSSL_OCSP_H */
1289
1290 /*
1291  *      Create Global context SSL and use it in every new session
1292  *
1293  *      - Load the trusted CAs
1294  *      - Load the Private key & the certificate
1295  *      - Set the Context options & Verify options
1296  */
1297 static SSL_CTX *init_tls_ctx(fr_tls_server_conf_t *conf)
1298 {
1299         SSL_METHOD *meth;
1300         SSL_CTX *ctx;
1301         X509_STORE *certstore;
1302         int verify_mode = SSL_VERIFY_NONE;
1303         int ctx_options = 0;
1304         int type;
1305
1306         /*
1307          *      Add all the default ciphers and message digests
1308          *      Create our context.
1309          */
1310         SSL_library_init();
1311         SSL_load_error_strings();
1312
1313         /*
1314          *      SHA256 is in all versions of OpenSSL, but isn't
1315          *      initialized by default.  It's needed for WiMAX
1316          *      certificates.
1317          */
1318 #ifdef HAVE_OPENSSL_EVP_SHA256
1319         EVP_add_digest(EVP_sha256());
1320 #endif
1321
1322         meth = TLSv1_method();
1323         ctx = SSL_CTX_new(meth);
1324
1325         /*
1326          * Identify the type of certificates that needs to be loaded
1327          */
1328         if (conf->file_type) {
1329                 type = SSL_FILETYPE_PEM;
1330         } else {
1331                 type = SSL_FILETYPE_ASN1;
1332         }
1333
1334         /*
1335          * Set the password to load private key
1336          */
1337         if (conf->private_key_password) {
1338 #ifdef __APPLE__
1339                 /*
1340                  * We don't want to put the private key password in eap.conf, so  check
1341                  * for our special string which indicates we should get the password
1342                  * programmatically.
1343                  */
1344                 const char* special_string = "Apple:UseCertAdmin";
1345                 if (strncmp(conf->private_key_password,
1346                                         special_string,
1347                                         strlen(special_string)) == 0)
1348                 {
1349                         char cmd[256];
1350                         const long max_password_len = 128;
1351                         snprintf(cmd, sizeof(cmd) - 1,
1352                                          "/usr/sbin/certadmin --get-private-key-passphrase \"%s\"",
1353                                          conf->private_key_file);
1354
1355                         DEBUG2("rlm_eap: Getting private key passphrase using command \"%s\"", cmd);
1356
1357                         FILE* cmd_pipe = popen(cmd, "r");
1358                         if (!cmd_pipe) {
1359                                 radlog(L_ERR, "rlm_eap: %s command failed.      Unable to get private_key_password", cmd);
1360                                 radlog(L_ERR, "rlm_eap: Error reading private_key_file %s", conf->private_key_file);
1361                                 return NULL;
1362                         }
1363
1364                         free(conf->private_key_password);
1365                         conf->private_key_password = malloc(max_password_len * sizeof(char));
1366                         if (!conf->private_key_password) {
1367                                 radlog(L_ERR, "rlm_eap: Can't malloc space for private_key_password");
1368                                 radlog(L_ERR, "rlm_eap: Error reading private_key_file %s", conf->private_key_file);
1369                                 pclose(cmd_pipe);
1370                                 return NULL;
1371                         }
1372
1373                         fgets(conf->private_key_password, max_password_len, cmd_pipe);
1374                         pclose(cmd_pipe);
1375
1376                         /* Get rid of newline at end of password. */
1377                         conf->private_key_password[strlen(conf->private_key_password) - 1] = '\0';
1378                         DEBUG2("rlm_eap:  Password from command = \"%s\"", conf->private_key_password);
1379                 }
1380 #endif
1381                 SSL_CTX_set_default_passwd_cb_userdata(ctx, conf->private_key_password);
1382                 SSL_CTX_set_default_passwd_cb(ctx, cbtls_password);
1383         }
1384
1385         /*
1386          *      Load our keys and certificates
1387          *
1388          *      If certificates are of type PEM then we can make use
1389          *      of cert chain authentication using openssl api call
1390          *      SSL_CTX_use_certificate_chain_file.  Please see how
1391          *      the cert chain needs to be given in PEM from
1392          *      openSSL.org
1393          */
1394         if (type == SSL_FILETYPE_PEM) {
1395                 if (!(SSL_CTX_use_certificate_chain_file(ctx, conf->certificate_file))) {
1396                         radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
1397                         radlog(L_ERR, "rlm_eap_tls: Error reading certificate file %s", conf->certificate_file);
1398                         return NULL;
1399                 }
1400
1401         } else if (!(SSL_CTX_use_certificate_file(ctx, conf->certificate_file, type))) {
1402                 radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
1403                 radlog(L_ERR, "rlm_eap_tls: Error reading certificate file %s", conf->certificate_file);
1404                 return NULL;
1405         }
1406
1407         /* Load the CAs we trust */
1408         if (conf->ca_file || conf->ca_path) {
1409                 if (!SSL_CTX_load_verify_locations(ctx, conf->ca_file, conf->ca_path)) {
1410                         radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
1411                         radlog(L_ERR, "rlm_eap_tls: Error reading Trusted root CA list %s",conf->ca_file );
1412                         return NULL;
1413                 }
1414         }
1415         if (conf->ca_file && *conf->ca_file) SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(conf->ca_file));
1416         if (!(SSL_CTX_use_PrivateKey_file(ctx, conf->private_key_file, type))) {
1417                 radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
1418                 radlog(L_ERR, "rlm_eap_tls: Error reading private key file %s", conf->private_key_file);
1419                 return NULL;
1420         }
1421
1422         /*
1423          * Check if the loaded private key is the right one
1424          */
1425         if (!SSL_CTX_check_private_key(ctx)) {
1426                 radlog(L_ERR, "rlm_eap_tls: Private key does not match the certificate public key");
1427                 return NULL;
1428         }
1429
1430         /*
1431          *      Set ctx_options
1432          */
1433         ctx_options |= SSL_OP_NO_SSLv2;
1434         ctx_options |= SSL_OP_NO_SSLv3;
1435 #ifdef SSL_OP_NO_TICKET
1436         ctx_options |= SSL_OP_NO_TICKET ;
1437 #endif
1438
1439         /*
1440          *      SSL_OP_SINGLE_DH_USE must be used in order to prevent
1441          *      small subgroup attacks and forward secrecy. Always
1442          *      using
1443          *
1444          *      SSL_OP_SINGLE_DH_USE has an impact on the computer
1445          *      time needed during negotiation, but it is not very
1446          *      large.
1447          */
1448         ctx_options |= SSL_OP_SINGLE_DH_USE;
1449
1450         /*
1451          *      SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS to work around issues
1452          *      in Windows Vista client.
1453          *      http://www.openssl.org/~bodo/tls-cbc.txt
1454          *      http://www.nabble.com/(RADIATOR)-Radiator-Version-3.16-released-t2600070.html
1455          */
1456         ctx_options |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
1457
1458         SSL_CTX_set_options(ctx, ctx_options);
1459
1460         /*
1461          *      TODO: Set the RSA & DH
1462          *      SSL_CTX_set_tmp_rsa_callback(ctx, cbtls_rsa);
1463          *      SSL_CTX_set_tmp_dh_callback(ctx, cbtls_dh);
1464          */
1465
1466         /*
1467          *      set the message callback to identify the type of
1468          *      message.  For every new session, there can be a
1469          *      different callback argument.
1470          *
1471          *      SSL_CTX_set_msg_callback(ctx, cbtls_msg);
1472          */
1473
1474         /* Set Info callback */
1475         SSL_CTX_set_info_callback(ctx, cbtls_info);
1476
1477         /*
1478          *      Callbacks, etc. for session resumption.
1479          */
1480         if (conf->session_cache_enable) {
1481                 SSL_CTX_sess_set_new_cb(ctx, cbtls_new_session);
1482                 SSL_CTX_sess_set_get_cb(ctx, cbtls_get_session);
1483                 SSL_CTX_sess_set_remove_cb(ctx, cbtls_remove_session);
1484
1485                 SSL_CTX_set_quiet_shutdown(ctx, 1);
1486         }
1487
1488         /*
1489          *      Check the certificates for revocation.
1490          */
1491 #ifdef X509_V_FLAG_CRL_CHECK
1492         if (conf->check_crl) {
1493           certstore = SSL_CTX_get_cert_store(ctx);
1494           if (certstore == NULL) {
1495             radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
1496             radlog(L_ERR, "rlm_eap_tls: Error reading Certificate Store");
1497             return NULL;
1498           }
1499           X509_STORE_set_flags(certstore, X509_V_FLAG_CRL_CHECK);
1500         }
1501 #endif
1502
1503         /*
1504          *      Set verify modes
1505          *      Always verify the peer certificate
1506          */
1507         verify_mode |= SSL_VERIFY_PEER;
1508         verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1509         verify_mode |= SSL_VERIFY_CLIENT_ONCE;
1510         SSL_CTX_set_verify(ctx, verify_mode, cbtls_verify);
1511
1512         if (conf->verify_depth) {
1513                 SSL_CTX_set_verify_depth(ctx, conf->verify_depth);
1514         }
1515
1516         /* Load randomness */
1517         if (!(RAND_load_file(conf->random_file, 1024*1024))) {
1518                 radlog(L_ERR, "rlm_eap: SSL error %s", ERR_error_string(ERR_get_error(), NULL));
1519                 radlog(L_ERR, "rlm_eap_tls: Error loading randomness");
1520                 return NULL;
1521         }
1522
1523         /*
1524          * Set the cipher list if we were told to
1525          */
1526         if (conf->cipher_list) {
1527                 if (!SSL_CTX_set_cipher_list(ctx, conf->cipher_list)) {
1528                         radlog(L_ERR, "rlm_eap_tls: Error setting cipher list");
1529                         return NULL;
1530                 }
1531         }
1532
1533         /*
1534          *      Setup session caching
1535          */
1536         if (conf->session_cache_enable) {
1537                 /*
1538                  *      Create a unique context Id per EAP-TLS configuration.
1539                  */
1540                 if (conf->session_id_name) {
1541                         snprintf(conf->session_context_id,
1542                                  sizeof(conf->session_context_id),
1543                                  "FreeRADIUS EAP-TLS %s",
1544                                  conf->session_id_name);
1545                 } else {
1546                         snprintf(conf->session_context_id,
1547                                  sizeof(conf->session_context_id),
1548                                  "FreeRADIUS EAP-TLS %p", conf);
1549                 }
1550
1551                 /*
1552                  *      Cache it, and DON'T auto-clear it.
1553                  */
1554                 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER | SSL_SESS_CACHE_NO_AUTO_CLEAR);
1555
1556                 SSL_CTX_set_session_id_context(ctx,
1557                                                (unsigned char *) conf->session_context_id,
1558                                                (unsigned int) strlen(conf->session_context_id));
1559
1560                 /*
1561                  *      Our timeout is in hours, this is in seconds.
1562                  */
1563                 SSL_CTX_set_timeout(ctx, conf->session_timeout * 3600);
1564
1565                 /*
1566                  *      Set the maximum number of entries in the
1567                  *      session cache.
1568                  */
1569                 SSL_CTX_sess_set_cache_size(ctx, conf->session_cache_size);
1570
1571         } else {
1572                 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
1573         }
1574
1575         return ctx;
1576 }
1577
1578
1579 void tls_server_conf_free(fr_tls_server_conf_t *conf)
1580 {
1581         if (!conf) return;
1582
1583         if (conf->cs) cf_section_parse_free(conf->cs, conf);
1584
1585         if (conf->ctx) SSL_CTX_free(conf->ctx);
1586
1587 #ifdef HAVE_OPENSSL_OCSP_H
1588         if (conf->ocsp_store) X509_STORE_free(conf->ocsp_store);
1589         conf->ocsp_store = NULL;
1590 #endif
1591
1592         memset(conf, 0, sizeof(*conf));
1593         free(conf);
1594 }
1595
1596
1597 fr_tls_server_conf_t *tls_server_conf_parse(CONF_SECTION *cs)
1598 {
1599         fr_tls_server_conf_t *conf;
1600
1601         conf = malloc(sizeof(*conf));
1602         if (!conf) {
1603                 radlog(L_ERR, "Out of memory");
1604                 return NULL;
1605         }
1606         memset(conf, 0, sizeof(*conf));
1607
1608         if (cf_section_parse(cs, conf, tls_server_config) < 0) {
1609         error:
1610                 tls_server_conf_free(conf);
1611                 return NULL;
1612         }
1613
1614         /*
1615          *      Save people from their own stupidity.
1616          */
1617         if (conf->fragment_size < 100) conf->fragment_size = 100;
1618
1619         /*
1620          *      This magic makes the administrators life HUGELY easier
1621          *      on initial deployments.
1622          *
1623          *      If the server starts up in debugging mode, AND the
1624          *      bootstrap command is configured, AND it exists, AND
1625          *      there is no server certificate
1626          */
1627         if (conf->make_cert_command && (debug_flag >= 2)) {
1628                 struct stat buf;
1629
1630                 if ((stat(conf->make_cert_command, &buf) == 0) &&
1631                     (stat(conf->certificate_file, &buf) < 0) &&
1632                     (errno == ENOENT) &&
1633                     (radius_exec_program(conf->make_cert_command, NULL, 1,
1634                                          NULL, 0, NULL, NULL, 0) != 0)) {
1635                         goto error;
1636                 }
1637         }
1638
1639         if (!conf->private_key_file) {
1640                 radlog(L_ERR, "TLS Server requires a private key file");
1641                 goto error;
1642         }
1643
1644         if (!conf->private_key_password) {
1645                 radlog(L_ERR, "TLS Server requires a private key password");
1646                 goto error;
1647         }
1648
1649         if (!conf->certificate_file) {
1650                 radlog(L_ERR, "TLS Server requires a certificate file");
1651                 goto error;
1652         }
1653
1654         /*
1655          *      Initialize TLS
1656          */
1657         conf->ctx = init_tls_ctx(conf);
1658         if (conf->ctx == NULL) {
1659                 goto error;
1660         }
1661
1662 #ifdef HAVE_OPENSSL_OCSP_H
1663         /*
1664          *      Initialize OCSP Revocation Store
1665          */
1666         if (conf->ocsp_enable) {
1667                 conf->ocsp_store = init_revocation_store(conf);
1668                 if (conf->ocsp_store == NULL) goto error;
1669         }
1670 #endif HAVE_OPENSSL_OCSP_H
1671
1672         if (load_dh_params(conf->ctx, conf->dh_file) < 0) {
1673                 goto error;
1674         }
1675
1676         if (generate_eph_rsa_key(conf->ctx) < 0) {
1677                 goto error;
1678         }
1679
1680         if (conf->verify_tmp_dir) {
1681                 if (chmod(conf->verify_tmp_dir, S_IRWXU) < 0) {
1682                         radlog(L_ERR, "Failed changing permissions on %s: %s", conf->verify_tmp_dir, strerror(errno));
1683                         goto error;
1684                 }
1685         }
1686
1687         if (conf->verify_client_cert_cmd && !conf->verify_tmp_dir) {
1688                 radlog(L_ERR, "You MUST set the verify directory in order to use verify_client_cmd");
1689                 goto error;
1690         }
1691
1692         return conf;
1693 }
1694 #endif  /* WITH_TLS */
1695