All Data Structures Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
tls.c
Go to the documentation of this file.
1 /*
2  * tls.c
3  *
4  * Version: $Id: 95763a7bfc7c90b485e54ba3c784895c97d77663 $
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: 95763a7bfc7c90b485e54ba3c784895c97d77663 $")
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/modules.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 HAVE_FCNTL_H
38 #include <fcntl.h>
39 #endif
40 
41 #ifdef HAVE_UTIME_H
42 #include <utime.h>
43 #endif
44 #include <ctype.h>
45 
46 #ifdef WITH_TLS
47 # ifdef HAVE_OPENSSL_RAND_H
48 # include <openssl/rand.h>
49 # endif
50 
51 # ifdef HAVE_OPENSSL_OCSP_H
52 # include <openssl/ocsp.h>
53 # endif
54 
55 # ifdef HAVE_OPENSSL_EVP_H
56 # include <openssl/evp.h>
57 # endif
58 # include <openssl/ssl.h>
59 
60 #define LOG_PREFIX "tls"
61 
62 #ifdef ENABLE_OPENSSL_VERSION_CHECK
63 typedef struct libssl_defect {
64  uint64_t high; //!< The last version number this defect affected.
65  uint64_t low; //!< The first version this defect affected.
66 
67  char const *id; //!< CVE (or other ID)
68  char const *name; //!< As known in the media...
69  char const *comment; //!< Where to get more information.
70 } libssl_defect_t;
71 
72 /* Record critical defects in libssl here (newest first)*/
73 static libssl_defect_t libssl_defects[] =
74 {
75  {
76  .low = 0x010001000, /* 1.0.1 */
77  .high = 0x01000106f, /* 1.0.1f */
78  .id = "CVE-2014-0160",
79  .name = "Heartbleed",
80  .comment = "For more information see http://heartbleed.com"
81  }
82 };
83 #endif /* ENABLE_OPENSSL_VERSION_CHECK */
84 
85 #ifdef WITH_TLS
86 static bool tls_done_init = false;
87 #endif
88 
89 FR_NAME_NUMBER const fr_tls_status_table[] = {
90  { "invalid", FR_TLS_INVALID },
91  { "request", FR_TLS_REQUEST },
92  { "response", FR_TLS_RESPONSE },
93  { "success", FR_TLS_SUCCESS },
94  { "fail", FR_TLS_FAIL },
95  { "noop", FR_TLS_NOOP },
96 
97  { "start", FR_TLS_START },
98  { "ok", FR_TLS_RECORD_COMPLETE },
99  { "ack", FR_TLS_ACK },
100  { "first fragment", FR_TLS_RECORD_FRAGMENT_INIT },
101  { "more fragments", FR_TLS_RECORD_FRAGMENT_MORE },
102  { "handled", FR_TLS_HANDLED },
103  { NULL , -1},
104 };
105 
106 /* Session */
107 static void session_init(tls_session_t *session);
108 
109 /* record */
110 static void record_init(tls_record_t *record);
111 static void record_close(tls_record_t *record);
112 static unsigned int record_from_buff(tls_record_t *record, void const *in, unsigned int inlen);
113 static unsigned int record_to_buff(tls_record_t *record, void *out, unsigned int outlen);
114 
115 /*
116  * If we're linking against OpenSSL, then it is the
117  * duty of the application, if it is multithreaded,
118  * to provide OpenSSL with appropriate thread id
119  * and mutex locking functions
120  *
121  * Note: this only implements static callbacks.
122  * OpenSSL does not use dynamic locking callbacks
123  * right now, but may in the future, so we will have
124  * to add them at some point.
125  */
126 static pthread_mutex_t *tls_static_mutexes = NULL;
127 
128 #ifdef PSK_MAX_IDENTITY_LEN
129 /** Verify the PSK identity contains no reserved chars
130  *
131  * @param identity to check.
132  * @return
133  * - true identity does not contain reserved chars.
134  * - false identity contains reserved chars.
135  */
136 static bool tls_psk_identity_is_safe(const char *identity)
137 {
138  char c;
139 
140  if (!identity) return true;
141 
142  while ((c = *(identity++)) != '\0') {
143  if (isalpha((int) c) || isdigit((int) c) || isspace((int) c) ||
144  (c == '@') || (c == '-') || (c == '_') || (c == '.')) {
145  continue;
146  }
147 
148  return false;
149  }
150 
151  return true;
152 }
153 
154 
155 /** Determine the PSK to use
156  *
157  *
158  */
159 static unsigned int tls_psk_server_cb(SSL *ssl, const char *identity,
160  unsigned char *psk, unsigned int max_psk_len)
161 {
162  unsigned int psk_len = 0;
163  fr_tls_server_conf_t *conf;
164  REQUEST *request;
165 
166  conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
167  if (!conf) return 0;
168 
169  request = (REQUEST *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_REQUEST);
170  if (request && conf->psk_query) {
171  size_t hex_len;
172  VALUE_PAIR *vp;
173  char buffer[2 * PSK_MAX_PSK_LEN + 4]; /* allow for too-long keys */
174 
175  /*
176  * The passed identity is weird. Deny it.
177  */
178  if (!tls_psk_identity_is_safe(identity)) {
179  RWDEBUG("Invalid characters in PSK identity %s", identity);
180  return 0;
181  }
182 
183  vp = pair_make_request("TLS-PSK-Identity", identity, T_OP_SET);
184  if (!vp) return 0;
185 
186  hex_len = radius_xlat(buffer, sizeof(buffer), request, conf->psk_query,
187  NULL, NULL);
188  if (!hex_len) {
189  RWDEBUG("PSK expansion returned an empty string.");
190  return 0;
191  }
192 
193  /*
194  * The returned key is truncated at MORE than
195  * OpenSSL can handle. That way we can detect
196  * the truncation, and complain about it.
197  */
198  if (hex_len > (2 * max_psk_len)) {
199  RWDEBUG("Returned PSK is too long (%u > %u)", (unsigned int) hex_len, 2 * max_psk_len);
200  return 0;
201  }
202 
203  /*
204  * Leave the TLS-PSK-Identity in the request, and
205  * convert the expansion from printable string
206  * back to hex.
207  */
208  return fr_hex2bin(psk, max_psk_len, buffer, hex_len);
209  }
210 
211  if (!conf->psk_identity) {
212  DEBUG("No static PSK identity set. Rejecting the user");
213  return 0;
214  }
215 
216  /*
217  * No REQUEST, or no dynamic query. Just look for a
218  * static identity.
219  */
220  if (strcmp(identity, conf->psk_identity) != 0) {
221  ERROR("Supplied PSK identity %s does not match configuration. Rejecting.",
222  identity);
223  return 0;
224  }
225 
226  psk_len = strlen(conf->psk_password);
227  if (psk_len > (2 * max_psk_len)) return 0;
228 
229  return fr_hex2bin(psk, max_psk_len, conf->psk_password, psk_len);
230 }
231 
232 static unsigned int tls_psk_client_cb(SSL *ssl, UNUSED char const *hint,
233  char *identity, unsigned int max_identity_len,
234  unsigned char *psk, unsigned int max_psk_len)
235 {
236  unsigned int psk_len;
237  fr_tls_server_conf_t *conf;
238 
239  conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl,
240  FR_TLS_EX_INDEX_CONF);
241  if (!conf) return 0;
242 
243  psk_len = strlen(conf->psk_password);
244  if (psk_len > (2 * max_psk_len)) return 0;
245 
246  strlcpy(identity, conf->psk_identity, max_identity_len);
247 
248  return fr_hex2bin(psk, max_psk_len, conf->psk_password, psk_len);
249 }
250 
251 #endif
252 
253 #define MAX_SESSION_SIZE (256)
254 
255 /** Retrieve session ID (in binary form) from the session
256  *
257  * @param[out] out Where to write the session id.
258  * @param[in] outlen length of output buffer.
259  * @param[in] tls_session to get Id for.
260  * @return
261  * - -1 on failure (buffer too small).
262  * - >0 on success, the number of bytes written.
263  */
264 ssize_t tls_session_id(uint8_t *out, size_t outlen, SSL_SESSION *tls_session)
265 {
266 #if OPENSSL_VERSION_NUMBER < 0x10001000L
267  size_t len;
268 
269  len = tls_session->session_id_length;
270  if (len > outlen) return -1;
271  memcpy(out, tls_session->session_id, len);
272 
273  return (ssize_t)len;
274 #else
275  unsigned int len;
276  uint8_t const *p;
277 
278  p = SSL_SESSION_get_id(tls_session, &len);
279  if (len > outlen) return -1;
280  memcpy(out, p, len);
281 
282  return (ssize_t)len;
283 #endif
284 }
285 
286 /** Free a TLS session and any associated OpenSSL data
287  *
288  * @param session to free.
289  * @return 0.
290  */
291 static int _tls_session_free(tls_session_t *session)
292 {
293  SSL_set_quiet_shutdown(session->ssl, 1);
294  SSL_shutdown(session->ssl);
295 
296  if (session->ssl) {
297  SSL_free(session->ssl);
298  session->ssl = NULL;
299  }
300 
301  return 0;
302 }
303 
304 /** Create a new client TLS session
305  *
306  * Configures a new client TLS session, configuring options, setting callbacks etc...
307  *
308  * @param ctx to alloc session data in. Should usually be NULL unless the lifetime of the
309  * session is tied to another talloc'd object.
310  * @param conf to use to configure the tls session.
311  * @param fd OpenSSL should read from/write to.
312  * @return
313  * - A new session on success.
314  * - NULL on error.
315  */
316 tls_session_t *tls_session_init_client(TALLOC_CTX *ctx, fr_tls_server_conf_t *conf, int fd)
317 {
318  int verify_mode;
319  tls_session_t *session = NULL;
320  REQUEST *request;
321 
322  session = talloc_zero(ctx, tls_session_t);
323  if (!session) return NULL;
324 
325  talloc_set_destructor(session, _tls_session_free);
326 
327  session->ctx = conf->ctx[(conf->ctx_count == 1) ? 0 : conf->ctx_next++ % conf->ctx_count]; /* mutex not needed */
328  SSL_CTX_set_mode(session->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_AUTO_RETRY);
329 
330  session->ssl = SSL_new(session->ctx);
331  if (!session->ssl) {
332  talloc_free(session);
333  return NULL;
334  }
335 
336  request = request_alloc(session);
337  SSL_set_ex_data(session->ssl, FR_TLS_EX_INDEX_REQUEST, (void *)request);
338 
339  /*
340  * Add the message callback to identify what type of
341  * message/handshake is passed
342  */
343  SSL_set_msg_callback(session->ssl, cbtls_msg);
344  SSL_set_msg_callback_arg(session->ssl, session);
345  SSL_set_info_callback(session->ssl, cbtls_info);
346 
347  /*
348  * Always verify the peer certificate.
349  */
350  DEBUG2("Requiring Server certificate");
351  verify_mode = SSL_VERIFY_PEER;
352  verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
353  SSL_set_verify(session->ssl, verify_mode, cbtls_verify);
354 
355  SSL_set_ex_data(session->ssl, FR_TLS_EX_INDEX_CONF, (void *)conf);
356  SSL_set_ex_data(session->ssl, FR_TLS_EX_INDEX_TLS_SESSION, (void *)session);
357  SSL_set_fd(session->ssl, fd);
358  if (SSL_connect(session->ssl) <= 0) {
359  int err;
360  while ((err = ERR_get_error())) ERROR("tls: %s", ERR_error_string(err, NULL));
361  talloc_free(session);
362 
363  return NULL;
364  }
365 
366  session->mtu = conf->fragment_size;
367 
368  return session;
369 }
370 
371 /** Create a new server TLS session
372  *
373  * Configures a new server TLS session, configuring options, setting callbacks etc...
374  *
375  * @param ctx to alloc session data in. Should usually be NULL unless the lifetime of the
376  * session is tied to another talloc'd object.
377  * @param conf to use to configure the tls session.
378  * @param request The current #REQUEST.
379  * @param client_cert Whether to require a client_cert.
380  * @return
381  * - A new session on success.
382  * - NULL on error.
383  */
384 tls_session_t *tls_session_init_server(TALLOC_CTX *ctx, fr_tls_server_conf_t *conf, REQUEST *request, bool client_cert)
385 {
386  tls_session_t *session = NULL;
387  SSL *new_tls = NULL;
388  int verify_mode = 0;
389  VALUE_PAIR *vp;
390  SSL_CTX *ssl_ctx;
391 
392  rad_assert(request != NULL);
393  rad_assert(conf->ctx_count > 0);
394 
395  RDEBUG2("Initiating new EAP-TLS session");
396 
397  ssl_ctx = conf->ctx[(conf->ctx_count == 1) ? 0 : conf->ctx_next++ % conf->ctx_count]; /* mutex not needed */
398 
399  /*
400  * Manually flush the sessions every so often. If HALF
401  * of the session lifetime has passed since we last
402  * flushed, then flush it again.
403  *
404  * FIXME: Also do it every N sessions?
405  */
406  if (conf->session_cache_enable && !conf->session_cache_server &&
407  ((conf->session_last_flushed + ((int)conf->session_timeout * 1800)) <= request->timestamp.tv_sec)){
408  RDEBUG2("Flushing TLS sessions (of #%ld)", SSL_CTX_sess_number(ssl_ctx));
409 
410  SSL_CTX_flush_sessions(ssl_ctx, request->timestamp.tv_sec);
411  conf->session_last_flushed = request->timestamp.tv_sec;
412  }
413 
414  new_tls = SSL_new(ssl_ctx);
415  if (new_tls == NULL) {
416  RERROR("Error creating new TLS session: %s", ERR_error_string(ERR_get_error(), NULL));
417 
418  return NULL;
419  }
420 
421  /* We use the SSL's "app_data" to indicate a call-back */
422  SSL_set_app_data(new_tls, NULL);
423 
424  session = talloc_zero(ctx, tls_session_t);
425  if (session == NULL) {
426  RERROR("Error allocating memory for TLS session");
427  SSL_free(new_tls);
428 
429  return NULL;
430  }
431  session_init(session);
432  talloc_set_destructor(session, _tls_session_free);
433 
434  session->ctx = ssl_ctx;
435  session->ssl = new_tls;
436 
437  /*
438  * Initialize callbacks
439  */
440  session->record_init = record_init;
441  session->record_close = record_close;
442  session->record_from_buff = record_from_buff;
443  session->record_to_buff = record_to_buff;
444 
445  /*
446  * Create & hook the BIOs to handle the dirty side of the
447  * SSL. This is *very important* as we want to handle
448  * the transmission part. Now the only IO interface
449  * that SSL is aware of, is our defined BIO buffers.
450  *
451  * This means that all SSL IO is done to/from memory,
452  * and we can update those BIOs from the packets we've
453  * received.
454  */
455  session->into_ssl = BIO_new(BIO_s_mem());
456  session->from_ssl = BIO_new(BIO_s_mem());
457  SSL_set_bio(session->ssl, session->into_ssl, session->from_ssl);
458 
459  /*
460  * Add the message callback to identify what type of
461  * message/handshake is passed
462  */
463  SSL_set_msg_callback(new_tls, cbtls_msg);
464  SSL_set_msg_callback_arg(new_tls, session);
465  SSL_set_info_callback(new_tls, cbtls_info);
466 
467  /*
468  * In Server mode we only accept.
469  */
470  SSL_set_accept_state(session->ssl);
471 
472  /*
473  * Verify the peer certificate, if asked.
474  */
475  if (client_cert) {
476  RDEBUG2("Setting verify mode to require certificate from client");
477  verify_mode = SSL_VERIFY_PEER;
478  verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
479  verify_mode |= SSL_VERIFY_CLIENT_ONCE;
480  }
481  SSL_set_verify(session->ssl, verify_mode, cbtls_verify);
482 
483  SSL_set_ex_data(session->ssl, FR_TLS_EX_INDEX_CONF, (void *)conf);
484  SSL_set_ex_data(session->ssl, FR_TLS_EX_INDEX_TLS_SESSION, (void *)session);
485  session->length_flag = conf->include_length;
486 
487  /*
488  * We use default fragment size, unless the Framed-MTU
489  * tells us it's too big. Note that we do NOT account
490  * for the EAP-TLS headers if conf->fragment_size is
491  * large, because that config item looks to be confusing.
492  *
493  * i.e. it should REALLY be called MTU, and the code here
494  * should figure out what that means for TLS fragment size.
495  * asking the administrator to know the internal details
496  * of EAP-TLS in order to calculate fragment sizes is
497  * just too much.
498  */
499  session->mtu = conf->fragment_size;
500  vp = fr_pair_find_by_num(request->packet->vps, 0, PW_FRAMED_MTU, TAG_ANY);
501  if (vp && (vp->vp_integer > 100) && (vp->vp_integer < session->mtu)) {
502  session->mtu = vp->vp_integer;
503  }
504 
505  if (conf->session_cache_enable) session->allow_session_resumption = true; /* otherwise it's false */
506 
507  return session;
508 }
509 
510 /*
511  * Print out some text describing the error.
512  */
513 static int tls_error_log(REQUEST *request, SSL *s, int ret, char const *text)
514 {
515  int e;
516  unsigned long l;
517 
518  if ((l = ERR_get_error()) != 0) {
519  char const *p = ERR_error_string(l, NULL);
520 
521  if (p) ROPTIONAL(REDEBUG, ERROR, "TLS says: %s", p);
522  }
523 
524  e = SSL_get_error(s, ret);
525  switch (e) {
526  /*
527  * These seem to be harmless and already "dealt
528  * with" by our non-blocking environment. NB:
529  * "ZERO_RETURN" is the clean "error"
530  * indicating a successfully closed SSL
531  * tunnel. We let this happen because our IO
532  * loop should not appear to have broken on
533  * this condition - and outside the IO loop, the
534  * "shutdown" state is checked.
535  *
536  * Don't print anything if we ignore the error.
537  */
538  case SSL_ERROR_NONE:
539  case SSL_ERROR_WANT_READ:
540  case SSL_ERROR_WANT_WRITE:
541  case SSL_ERROR_WANT_X509_LOOKUP:
542  case SSL_ERROR_ZERO_RETURN:
543  break;
544 
545  /*
546  * These seem to be indications of a genuine
547  * error that should result in the SSL tunnel
548  * being regarded as "dead".
549  */
550  case SSL_ERROR_SYSCALL:
551  ROPTIONAL(REDEBUG, ERROR, "%s failed in a system call (%d), TLS session failed", text, ret);
552  return 0;
553 
554  case SSL_ERROR_SSL:
555  ROPTIONAL(REDEBUG, ERROR, "%s failed inside of TLS (%d), TLS session failed", text, ret);
556  return 0;
557 
558  /*
559  * For any other errors that (a) exist, and (b)
560  * crop up - we need to interpret what to do with
561  * them - so "politely inform" the caller that
562  * the code needs updating here.
563  */
564  default:
565  ROPTIONAL(REDEBUG, ERROR, "FATAL TLS error: %d", e);
566  return 0;
567  }
568 
569  return 1;
570 }
571 
572 /*
573  * We are the server, we always get the dirty data
574  * (Handshake data is also considered as dirty data)
575  * During handshake, since SSL API handles itself,
576  * After clean-up, dirty_out will be filled with
577  * the data required for handshaking. So we check
578  * if dirty_out is empty then we simply send it back.
579  * As of now, if handshake is successful, then we keep going,
580  * otherwise we fail.
581  *
582  * Fill the Bio with the dirty data to clean it
583  * Get the cleaned data from SSL, if it is not Handshake data
584  */
585 int tls_handshake_recv(REQUEST *request, tls_session_t *session)
586 {
587  int err;
588 
589  if (session->invalid_hb_used) return 0;
590 
591  err = BIO_write(session->into_ssl, session->dirty_in.data, session->dirty_in.used);
592  if (err != (int) session->dirty_in.used) {
593  REDEBUG("Failed writing %zd bytes to TLS BIO: %d", session->dirty_in.used, err);
594  record_init(&session->dirty_in);
595  return 0;
596  }
597  record_init(&session->dirty_in);
598 
599  err = SSL_read(session->ssl, session->clean_out.data + session->clean_out.used,
600  sizeof(session->clean_out.data) - session->clean_out.used);
601  if (err > 0) {
602  session->clean_out.used += err;
603  return 1;
604  }
605 
606  if (!tls_error_log(request, session->ssl, err, "TLS_read")) return 0;
607 
608  /* Some Extra STATE information for easy debugging */
609  if (SSL_is_init_finished(session->ssl)) {
610  SSL_CIPHER const *cipher;
611  char buffer[256];
612 
613  cipher = SSL_get_current_cipher(session->ssl);
614 
615  RDEBUG2("TLS established with cipher suite: %s",
616  SSL_CIPHER_description(cipher, buffer, sizeof(buffer)));
617  }
618  if (SSL_in_init(session->ssl)) RDEBUG2("In TLS handshake phase");
619  if (SSL_in_before(session->ssl)) RDEBUG2("Before TLS handshake phase");
620  if (SSL_in_accept_init(session->ssl)) RDEBUG2("In TLS accept mode");
621  if (SSL_in_connect_init(session->ssl)) RDEBUG2("In TLS connect mode");
622 
623 #if OPENSSL_VERSION_NUMBER >= 0x10001000L
624  /*
625  * Cache the SSL_SESSION pointer.
626  */
627  if (!session->ssl_session && SSL_is_init_finished(session->ssl)) {
628  session->ssl_session = SSL_get_session(session->ssl);
629  if (!session->ssl_session) {
630  RDEBUG("Failed getting TLS session");
631  return 0;
632  }
633  }
634 #endif
635 
636  err = BIO_ctrl_pending(session->from_ssl);
637  if (err > 0) {
638  err = BIO_read(session->from_ssl, session->dirty_out.data,
639  sizeof(session->dirty_out.data));
640  if (err > 0) {
641  session->dirty_out.used = err;
642 
643  } else if (BIO_should_retry(session->from_ssl)) {
644  record_init(&session->dirty_in);
645  RDEBUG2("Asking for more data in tunnel");
646  return 1;
647 
648  } else {
649  tls_error_log(request, session->ssl, err, "BIO_read");
650  record_init(&session->dirty_in);
651  return 0;
652  }
653  } else {
654  RDEBUG2("Recived TLS Application Data");
655  /* Its clean application data, do whatever we want */
656  record_init(&session->clean_out);
657  }
658 
659  /* We are done with dirty_in, reinitialize it */
660  record_init(&session->dirty_in);
661  return 1;
662 }
663 
664 /*
665  * Take cleartext user data, and encrypt it into the output buffer,
666  * to send to the client at the other end of the SSL connection.
667  */
668 int tls_handshake_send(REQUEST *request, tls_session_t *session)
669 {
670  int err;
671 
672  /*
673  * If there's un-encrypted data in 'clean_in', then write
674  * that data to the SSL session, and then call the BIO function
675  * to get that encrypted data from the SSL session, into
676  * a buffer which we can then package into an EAP packet.
677  *
678  * Based on Server's logic this clean_in is expected to
679  * contain the data to send to the client.
680  */
681  if (session->clean_in.used > 0) {
682  int written;
683 
684  written = SSL_write(session->ssl, session->clean_in.data, session->clean_in.used);
685  record_to_buff(&session->clean_in, NULL, written);
686 
687  /* Get the dirty data from Bio to send it */
688  err = BIO_read(session->from_ssl, session->dirty_out.data,
689  sizeof(session->dirty_out.data));
690  if (err > 0) {
691  session->dirty_out.used = err;
692  } else {
693  tls_error_log(request, session->ssl, err, "handshake_send");
694  }
695  }
696 
697  return 1;
698 }
699 
700 static void session_init(tls_session_t *session)
701 {
702  session->ssl = NULL;
703  session->into_ssl = session->from_ssl = NULL;
704  record_init(&session->clean_in);
705  record_init(&session->clean_out);
706  record_init(&session->dirty_in);
707  record_init(&session->dirty_out);
708 
709  memset(&session->info, 0, sizeof(session->info));
710 
711  session->mtu = 0;
712  session->record_out_started = false;
713  session->record_out_total_len = 0;
714  session->length_flag = false;
715  session->opaque = NULL;
716 }
717 
718 static void record_init(tls_record_t *rec)
719 {
720  rec->used = 0;
721 }
722 
723 static void record_close(tls_record_t *rec)
724 {
725  rec->used = 0;
726 }
727 
728 
729 /** Copy data to the intermediate buffer, before we send it somewhere
730  *
731  */
732 static unsigned int record_from_buff(tls_record_t *record, void const *in, unsigned int inlen)
733 {
734  unsigned int added = MAX_RECORD_SIZE - record->used;
735 
736  if (added > inlen) added = inlen;
737  if (added == 0) return 0;
738 
739  memcpy(record->data + record->used, in, added);
740  record->used += added;
741 
742  return added;
743 }
744 
745 /** Take data from the buffer, and give it to the caller
746  *
747  */
748 static unsigned int record_to_buff(tls_record_t *record, void *out, unsigned int outlen)
749 {
750  unsigned int taken = record->used;
751 
752  if (taken > outlen) taken = outlen;
753  if (taken == 0) return 0;
754  if (out) memcpy(out, record->data, taken);
755 
756  record->used -= taken;
757 
758  /*
759  * This is pretty bad...
760  */
761  if (record->used > 0) memmove(record->data, record->data + taken, record->used);
762 
763  return taken;
764 }
765 
766 void tls_session_information(tls_session_t *tls_session)
767 {
768  char const *str_write_p, *str_version, *str_content_type = "";
769  char const *str_details1 = "", *str_details2= "";
770  REQUEST *request;
771  char buffer[32];
772  char content_type[20];
773 
774  /*
775  * Don't print this out in the normal course of
776  * operations.
777  */
778  if (rad_debug_lvl == 0) return;
779 
780  str_write_p = tls_session->info.origin ? ">>> send" : "<<< recv";
781 
782  switch (tls_session->info.version) {
783  case SSL2_VERSION:
784  str_version = "SSL 2.0 ";
785  break;
786 
787  case SSL3_VERSION:
788  str_version = "SSL 3.0 ";
789  break;
790 
791  case TLS1_VERSION:
792  str_version = "TLS 1.0 ";
793  break;
794 
795 #ifdef TLS1_1_VERSION
796  case TLS1_1_VERSION:
797  str_version = "TLS 1.1 ";
798  break;
799 #endif
800 #ifdef TLS1_2_VERSION
801  case TLS1_2_VERSION:
802  str_version = "TLS 1.2 ";
803  break;
804 #endif
805 #ifdef TLS1_3_VERSON
806  case TLS1_3_VERSION:
807  str_version = "TLS 1.3 ";
808  break;
809 #endif
810 
811  default:
812  if (tls_session->info.version) {
813  sprintf(buffer, "UNKNOWN TLS VERSION 0x%04x", tls_session->info.version);
814  str_version = buffer;
815  } else {
816  str_version = "";
817  }
818  break;
819  }
820 
821  /*
822  * TLS 1.0, 1.1, 1.2 content types are the same as SSLv3
823  */
824  switch (tls_session->info.content_type) {
825  case SSL3_RT_CHANGE_CIPHER_SPEC:
826  str_content_type = "change_cipher_spec ";
827  break;
828 
829  case SSL3_RT_ALERT:
830  str_content_type = "alert ";
831  break;
832 
833  case SSL3_RT_HANDSHAKE:
834  str_content_type = "handshake ";
835  break;
836 
837  case SSL3_RT_APPLICATION_DATA:
838  str_content_type = "application_data ";
839  break;
840 
841  case TLS1_RT_HEARTBEAT:
842  str_content_type = "heartbeat ";
843  break;
844 
845 #ifdef TLS1_RT_CRYPTO
846  case TLS1_RT_CRYPTO:
847  str_content_type = "crypto ";
848  break;
849 #endif
850 
851 #ifdef TLS1_RT_CRYPTO_PREMASTER
852  case TLS1_RT_CRYPTO_PREMASTER:
853  str_content_type = "crypto_premaster ";
854  break;
855 #endif
856 
857 #ifdef TLS1_RT_CRYPTO_CLIENT_RANDOM
858  case TLS1_RT_CRYPTO_CLIENT_RANDOM:
859  str_content_type = "client_random ";
860  break;
861 #endif
862 
863 #ifdef TLS1_RT_CRYPTO_SERVER_RANDOM
864  case TLS1_RT_CRYPTO_SERVER_RANDOM:
865  str_content_type = "server_random ";
866  break;
867 #endif
868 
869 #ifdef TLS1_RT_CRYPTO_MASTER
870  case TLS1_RT_CRYPTO_MASTER:
871  str_content_type = "crypto_master ";
872  break;
873 #endif
874 
875 #ifdef TLS1_RT_CRYPTO_READ
876  case TLS1_RT_CRYPTO_READ:
877  str_content_type = "crypto_read ";
878  break;
879 #endif
880 
881 #ifdef TLS1_RT_CRYPTO_WRITE
882  case TLS1_RT_CRYPTO_WRITE:
883  str_content_type = "crypto_write ";
884  break;
885 #endif
886 
887 #ifdef TLS1_RT_CRYPTO_MAC
888  case TLS1_RT_CRYPTO_MAC:
889  str_content_type = "crypto_mac ";
890  break;
891 #endif
892 
893 #ifdef TLS1_RT_CRYPTO_KEY
894  case TLS1_RT_CRYPTO_KEY:
895  str_content_type = "crypto_key ";
896  break;
897 #endif
898 
899 #ifdef TLS1_RT_CRYPTO_IV
900  case TLS1_RT_CRYPTO_IV:
901  str_content_type = "crypto_iv ";
902  break;
903 #endif
904 
905 #ifdef TLS1_RT_CRYPTO_FIXED_IV
906  case TLS1_RT_CRYPTO_FIXED_IV:
907  str_content_type = "crypto_fixed_iv ";
908  break;
909 #endif
910 
911  default:
912  snprintf(content_type, sizeof(content_type), "unknown content type %i", tls_session->info.content_type );
913  str_content_type = content_type;
914  break;
915  }
916 
917  if (tls_session->info.content_type == SSL3_RT_ALERT) {
918  str_details1 = ", ???";
919 
920  if (tls_session->info.record_len == 2) {
921 
922  switch (tls_session->info.alert_level) {
923  case SSL3_AL_WARNING:
924  str_details1 = ", warning";
925  break;
926  case SSL3_AL_FATAL:
927  str_details1 = ", fatal";
928  break;
929  }
930 
931  str_details2 = " ???";
932  switch (tls_session->info.alert_description) {
933  case SSL3_AD_CLOSE_NOTIFY:
934  str_details2 = " close_notify";
935  break;
936 
937  case SSL3_AD_UNEXPECTED_MESSAGE:
938  str_details2 = " unexpected_message";
939  break;
940 
941  case SSL3_AD_BAD_RECORD_MAC:
942  str_details2 = " bad_record_mac";
943  break;
944 
945  case TLS1_AD_DECRYPTION_FAILED:
946  str_details2 = " decryption_failed";
947  break;
948 
949  case TLS1_AD_RECORD_OVERFLOW:
950  str_details2 = " record_overflow";
951  break;
952 
953  case SSL3_AD_DECOMPRESSION_FAILURE:
954  str_details2 = " decompression_failure";
955  break;
956 
957  case SSL3_AD_HANDSHAKE_FAILURE:
958  str_details2 = " handshake_failure";
959  break;
960 
961  case SSL3_AD_BAD_CERTIFICATE:
962  str_details2 = " bad_certificate";
963  break;
964 
965  case SSL3_AD_UNSUPPORTED_CERTIFICATE:
966  str_details2 = " unsupported_certificate";
967  break;
968 
969  case SSL3_AD_CERTIFICATE_REVOKED:
970  str_details2 = " certificate_revoked";
971  break;
972 
973  case SSL3_AD_CERTIFICATE_EXPIRED:
974  str_details2 = " certificate_expired";
975  break;
976 
977  case SSL3_AD_CERTIFICATE_UNKNOWN:
978  str_details2 = " certificate_unknown";
979  break;
980 
981  case SSL3_AD_ILLEGAL_PARAMETER:
982  str_details2 = " illegal_parameter";
983  break;
984 
985  case TLS1_AD_UNKNOWN_CA:
986  str_details2 = " unknown_ca";
987  break;
988 
989  case TLS1_AD_ACCESS_DENIED:
990  str_details2 = " access_denied";
991  break;
992 
993  case TLS1_AD_DECODE_ERROR:
994  str_details2 = " decode_error";
995  break;
996 
997  case TLS1_AD_DECRYPT_ERROR:
998  str_details2 = " decrypt_error";
999  break;
1000 
1001  case TLS1_AD_EXPORT_RESTRICTION:
1002  str_details2 = " export_restriction";
1003  break;
1004 
1005  case TLS1_AD_PROTOCOL_VERSION:
1006  str_details2 = " protocol_version";
1007  break;
1008 
1009  case TLS1_AD_INSUFFICIENT_SECURITY:
1010  str_details2 = " insufficient_security";
1011  break;
1012 
1013  case TLS1_AD_INTERNAL_ERROR:
1014  str_details2 = " internal_error";
1015  break;
1016 
1017  case TLS1_AD_USER_CANCELLED:
1018  str_details2 = " user_canceled";
1019  break;
1020 
1021  case TLS1_AD_NO_RENEGOTIATION:
1022  str_details2 = " no_renegotiation";
1023  break;
1024  }
1025  }
1026  }
1027 
1028  if (tls_session->info.content_type == SSL3_RT_HANDSHAKE) {
1029  str_details1 = "???";
1030 
1031  if (tls_session->info.record_len > 0) switch (tls_session->info.handshake_type) {
1032  case SSL3_MT_HELLO_REQUEST:
1033  str_details1 = ", hello_request";
1034  break;
1035 
1036  case SSL3_MT_CLIENT_HELLO:
1037  str_details1 = ", client_hello";
1038  break;
1039 
1040  case SSL3_MT_SERVER_HELLO:
1041  str_details1 = ", server_hello";
1042  break;
1043 
1044  case SSL3_MT_CERTIFICATE:
1045  str_details1 = ", certificate";
1046  break;
1047 
1048  case SSL3_MT_SERVER_KEY_EXCHANGE:
1049  str_details1 = ", server_key_exchange";
1050  break;
1051 
1052  case SSL3_MT_CERTIFICATE_REQUEST:
1053  str_details1 = ", certificate_request";
1054  break;
1055 
1056  case SSL3_MT_SERVER_DONE:
1057  str_details1 = ", server_hello_done";
1058  break;
1059 
1060  case SSL3_MT_CERTIFICATE_VERIFY:
1061  str_details1 = ", certificate_verify";
1062  break;
1063 
1064  case SSL3_MT_CLIENT_KEY_EXCHANGE:
1065  str_details1 = ", client_key_exchange";
1066  break;
1067 
1068  case SSL3_MT_FINISHED:
1069  str_details1 = ", finished";
1070  break;
1071  }
1072  }
1073 
1074  snprintf(tls_session->info.info_description,
1075  sizeof(tls_session->info.info_description),
1076  "%s %s%s[length %lu]%s%s\n",
1077  str_write_p, str_version, str_content_type,
1078  (unsigned long)tls_session->info.record_len,
1079  str_details1, str_details2);
1080 
1081  request = SSL_get_ex_data(tls_session->ssl, FR_TLS_EX_INDEX_REQUEST);
1082  ROPTIONAL(RDEBUG2, DEBUG2, "%s", tls_session->info.info_description);
1083 }
1084 
1085 static CONF_PARSER cache_config[] = {
1086  { FR_CONF_OFFSET("enable", PW_TYPE_BOOLEAN, fr_tls_server_conf_t, session_cache_enable), .dflt = "no" },
1087 
1088  { FR_CONF_OFFSET("name", PW_TYPE_STRING, fr_tls_server_conf_t, session_id_name) },
1089 
1090  { FR_CONF_OFFSET("virtual_server", PW_TYPE_STRING, fr_tls_server_conf_t, session_cache_server) },
1091 
1092  { FR_CONF_OFFSET("lifetime", PW_TYPE_INTEGER | PW_TYPE_DEPRECATED, fr_tls_server_conf_t, session_timeout), .dflt = "24" },
1093  { FR_CONF_OFFSET("max_entries", PW_TYPE_INTEGER | PW_TYPE_DEPRECATED, fr_tls_server_conf_t, session_cache_size), .dflt = "255" },
1094  { FR_CONF_DEPRECATED("persist_dir", PW_TYPE_STRING | PW_TYPE_DEPRECATED, fr_tls_server_conf_t, NULL) },
1095 
1097 };
1098 
1099 static CONF_PARSER verify_config[] = {
1100  { FR_CONF_OFFSET("tmpdir", PW_TYPE_STRING, fr_tls_server_conf_t, verify_tmp_dir) },
1101  { FR_CONF_OFFSET("client", PW_TYPE_STRING, fr_tls_server_conf_t, verify_client_cert_cmd) },
1103 };
1104 
1105 #ifdef HAVE_OPENSSL_OCSP_H
1106 static CONF_PARSER ocsp_config[] = {
1107  { FR_CONF_OFFSET("enable", PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_enable), .dflt = "no" },
1108 
1109  { FR_CONF_OFFSET("virtual_server", PW_TYPE_STRING, fr_tls_server_conf_t, ocsp_cache_server) },
1110 
1111  { FR_CONF_OFFSET("override_cert_url", PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_override_url), .dflt = "no" },
1112  { FR_CONF_OFFSET("url", PW_TYPE_STRING, fr_tls_server_conf_t, ocsp_url) },
1113  { FR_CONF_OFFSET("use_nonce", PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_use_nonce), .dflt = "yes" },
1114  { FR_CONF_OFFSET("timeout", PW_TYPE_INTEGER, fr_tls_server_conf_t, ocsp_timeout), .dflt = "yes" },
1115  { FR_CONF_OFFSET("softfail", PW_TYPE_BOOLEAN, fr_tls_server_conf_t, ocsp_softfail), .dflt = "no" },
1117 };
1118 #endif
1119 
1120 static CONF_PARSER tls_server_config[] = {
1121  { FR_CONF_OFFSET("verify_depth", PW_TYPE_INTEGER, fr_tls_server_conf_t, verify_depth), .dflt = "0" },
1122  { FR_CONF_OFFSET("ca_path", PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_path) },
1123  { FR_CONF_OFFSET("pem_file_type", PW_TYPE_BOOLEAN, fr_tls_server_conf_t, file_type), .dflt = "yes" },
1124  { FR_CONF_OFFSET("private_key_file", PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, private_key_file) },
1125  { FR_CONF_OFFSET("certificate_file", PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, certificate_file) },
1126  { FR_CONF_OFFSET("ca_file", PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_file) },
1127  { FR_CONF_OFFSET("private_key_password", PW_TYPE_STRING | PW_TYPE_SECRET, fr_tls_server_conf_t, private_key_password) },
1128 #ifdef PSK_MAX_IDENTITY_LEN
1129  { FR_CONF_OFFSET("psk_identity", PW_TYPE_STRING, fr_tls_server_conf_t, psk_identity) },
1130  { FR_CONF_OFFSET("psk_hexphrase", PW_TYPE_STRING | PW_TYPE_SECRET, fr_tls_server_conf_t, psk_password) },
1131  { FR_CONF_OFFSET("psk_query", PW_TYPE_STRING, fr_tls_server_conf_t, psk_query) },
1132 #endif
1133  { FR_CONF_OFFSET("dh_file", PW_TYPE_STRING, fr_tls_server_conf_t, dh_file) },
1134  { FR_CONF_OFFSET("random_file", PW_TYPE_STRING, fr_tls_server_conf_t, random_file) },
1135  { FR_CONF_OFFSET("fragment_size", PW_TYPE_INTEGER, fr_tls_server_conf_t, fragment_size), .dflt = "1024" },
1136  { FR_CONF_OFFSET("include_length", PW_TYPE_BOOLEAN, fr_tls_server_conf_t, include_length), .dflt = "yes" },
1137  { FR_CONF_OFFSET("auto_chain", PW_TYPE_BOOLEAN, fr_tls_server_conf_t, auto_chain), .dflt = "yes" },
1138  { FR_CONF_OFFSET("disable_single_dh_use", PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_single_dh_use) },
1139  { FR_CONF_OFFSET("check_crl", PW_TYPE_BOOLEAN, fr_tls_server_conf_t, check_crl), .dflt = "no" },
1140 #ifdef X509_V_FLAG_CRL_CHECK_ALL
1141  { FR_CONF_OFFSET("check_all_crl", PW_TYPE_BOOLEAN, fr_tls_server_conf_t, check_all_crl), .dflt = "no" },
1142 #endif
1143  { FR_CONF_OFFSET("allow_expired_crl", PW_TYPE_BOOLEAN, fr_tls_server_conf_t, allow_expired_crl) },
1144  { FR_CONF_OFFSET("check_cert_cn", PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_cn) },
1145  { FR_CONF_OFFSET("cipher_list", PW_TYPE_STRING, fr_tls_server_conf_t, cipher_list) },
1146  { FR_CONF_OFFSET("check_cert_issuer", PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_issuer) },
1147  { FR_CONF_OFFSET("require_client_cert", PW_TYPE_BOOLEAN, fr_tls_server_conf_t, require_client_cert) },
1148 
1149 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
1150 #ifndef OPENSSL_NO_ECDH
1151  { FR_CONF_OFFSET("ecdh_curve", PW_TYPE_STRING, fr_tls_server_conf_t, ecdh_curve), .dflt = "prime256v1" },
1152 #endif
1153 #endif
1154 
1155 #ifdef SSL_OP_NO_TLSv1
1156  { FR_CONF_OFFSET("disable_tlsv1", PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1) },
1157 #endif
1158 
1159 #ifdef SSL_OP_NO_TLSv1_1
1160  { FR_CONF_OFFSET("disable_tlsv1_1", PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1_1) },
1161 #endif
1162 
1163 #ifdef SSL_OP_NO_TLSv1_2
1164  { FR_CONF_OFFSET("disable_tlsv1_2", PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1_2) },
1165 #endif
1166 
1167  { FR_CONF_POINTER("cache", PW_TYPE_SUBSECTION, NULL), .dflt = (void const *) cache_config },
1168 
1169  { FR_CONF_POINTER("verify", PW_TYPE_SUBSECTION, NULL), .dflt = (void const *) verify_config },
1170 
1171 #ifdef HAVE_OPENSSL_OCSP_H
1172  { FR_CONF_POINTER("ocsp", PW_TYPE_SUBSECTION, NULL), .dflt = (void const *) ocsp_config },
1173 #endif
1175 };
1176 
1177 
1178 static CONF_PARSER tls_client_config[] = {
1179  { FR_CONF_OFFSET("verify_depth", PW_TYPE_INTEGER, fr_tls_server_conf_t, verify_depth), .dflt = "0" },
1180  { FR_CONF_OFFSET("ca_path", PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_path) },
1181  { FR_CONF_OFFSET("pem_file_type", PW_TYPE_BOOLEAN, fr_tls_server_conf_t, file_type), .dflt = "yes" },
1182  { FR_CONF_OFFSET("private_key_file", PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, private_key_file) },
1183  { FR_CONF_OFFSET("certificate_file", PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, certificate_file) },
1184  { FR_CONF_OFFSET("ca_file", PW_TYPE_FILE_INPUT, fr_tls_server_conf_t, ca_file) },
1185  { FR_CONF_OFFSET("private_key_password", PW_TYPE_STRING | PW_TYPE_SECRET, fr_tls_server_conf_t, private_key_password) },
1186  { FR_CONF_OFFSET("dh_file", PW_TYPE_STRING, fr_tls_server_conf_t, dh_file) },
1187  { FR_CONF_OFFSET("random_file", PW_TYPE_STRING, fr_tls_server_conf_t, random_file) },
1188  { FR_CONF_OFFSET("fragment_size", PW_TYPE_INTEGER, fr_tls_server_conf_t, fragment_size), .dflt = "1024" },
1189  { FR_CONF_OFFSET("include_length", PW_TYPE_BOOLEAN, fr_tls_server_conf_t, include_length), .dflt = "yes" },
1190  { FR_CONF_OFFSET("check_crl", PW_TYPE_BOOLEAN, fr_tls_server_conf_t, check_crl), .dflt = "no" },
1191  { FR_CONF_OFFSET("check_cert_cn", PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_cn) },
1192  { FR_CONF_OFFSET("cipher_list", PW_TYPE_STRING, fr_tls_server_conf_t, cipher_list) },
1193  { FR_CONF_OFFSET("check_cert_issuer", PW_TYPE_STRING, fr_tls_server_conf_t, check_cert_issuer) },
1194 
1195 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
1196 #ifndef OPENSSL_NO_ECDH
1197  { FR_CONF_OFFSET("ecdh_curve", PW_TYPE_STRING, fr_tls_server_conf_t, ecdh_curve), .dflt = "prime256v1" },
1198 #endif
1199 #endif
1200 
1201 #ifdef SSL_OP_NO_TLSv1
1202  { FR_CONF_OFFSET("disable_tlsv1", PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1) },
1203 #endif
1204 
1205 #ifdef SSL_OP_NO_TLSv1_1
1206  { FR_CONF_OFFSET("disable_tlsv1_1", PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1_1) },
1207 #endif
1208 
1209 #ifdef SSL_OP_NO_TLSv1_2
1210  { FR_CONF_OFFSET("disable_tlsv1_2", PW_TYPE_BOOLEAN, fr_tls_server_conf_t, disable_tlsv1_2) },
1211 #endif
1213 };
1214 
1215 
1216 /*
1217  * TODO: Check for the type of key exchange * like conf->dh_key
1218  */
1219 static int load_dh_params(SSL_CTX *ctx, char *file)
1220 {
1221  DH *dh = NULL;
1222  BIO *bio;
1223 
1224  if (!file) return 0;
1225 
1226  if ((bio = BIO_new_file(file, "r")) == NULL) {
1227  ERROR(LOG_PREFIX ": Unable to open DH file - %s", file);
1228  return -1;
1229  }
1230 
1231  dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
1232  BIO_free(bio);
1233  if (!dh) {
1234  WARN(LOG_PREFIX ": Unable to set DH parameters. DH cipher suites may not work!");
1235  WARN(LOG_PREFIX ": Fix this by generating the DH parameter file");
1236  return 0;
1237  }
1238 
1239  if (SSL_CTX_set_tmp_dh(ctx, dh) < 0) {
1240  ERROR(LOG_PREFIX ": Unable to set DH parameters");
1241  DH_free(dh);
1242  return -1;
1243  }
1244 
1245  DH_free(dh);
1246  return 0;
1247 }
1248 
1249 /** Macros that match the hardcoded values of the TLS-Session-Cache-Attribute
1250  */
1251 typedef enum {
1252  CACHE_ACTION_SESSION_READ = 1, //!< Retrieve session data from the cache.
1253  CACHE_ACTION_SESSION_WRITE = 2, //!< Write session data to the cache.
1254  CACHE_ACTION_SESSION_DELETE = 3, //!< Delete session data from the cache.
1255  CACHE_ACTION_OCSP_READ = 4, //!< Read cached OCSP status.
1256  CACHE_ACTION_OCSP_WRITE = 5 //!< Write OCSP status.
1257 } tls_cache_action_t;
1258 
1259 /** Add attributes identifying the TLS session to be acted upon, and the action to be performed
1260  *
1261  * Adds the following attributes to the request:
1262  *
1263  * - &request:TLS-Session-Id
1264  * - &control:TLS-Session-Cache-Action
1265  *
1266  * Session identity will contain the binary session key used to create, retrieve
1267  * and delete cache entries related to the SSL session.
1268  *
1269  * Session-Cache-Action will contain the action to be performed. This is then
1270  * utilised by unlang policy (in a virtual server called with these attributes)
1271  * to perform different actions.
1272  *
1273  * @todo Add attribute representing session validity period.
1274  * @todo Move adding TLS-Session-Cache-Action to cache_process and remove it again after calling
1275  * the virtual server.
1276  *
1277  * @param[in] request The current request.
1278  * @param[in] key Identifier for the session.
1279  * @param[in] key_len Length of the key.
1280  * @param[in] action being performed (written to &control:TLS-Session-Cache-Action).
1281  * @return
1282  * - 0 on success.
1283  * - -1 on failure.
1284  */
1285 static int cache_key_add(REQUEST *request, uint8_t *key, size_t key_len, tls_cache_action_t action)
1286 {
1287  VALUE_PAIR *vp;
1288 
1289  fr_pair_delete_by_num(&request->packet->vps, 0, PW_TLS_SESSION_ID, TAG_ANY);
1290  fr_pair_delete_by_num(&request->config, 0, PW_TLS_SESSION_CACHE_ACTION, TAG_ANY);
1291 
1292  vp = fr_pair_afrom_num(request->packet, 0, PW_TLS_SESSION_ID);
1293  if (!vp) return -1;
1294 
1295  fr_pair_value_memcpy(vp, key, key_len);
1296  fr_pair_add(&request->packet->vps, vp);
1297  RINDENT();
1298  rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
1299  REXDENT();
1300 
1301  vp = fr_pair_afrom_num(request, 0, PW_TLS_SESSION_CACHE_ACTION);
1302  if (!vp) return -1;
1303 
1304  vp->vp_integer = action;
1305  fr_pair_add(&request->config, vp);
1306  RINDENT();
1307  rdebug_pair(L_DBG_LVL_2, request, vp, "&config:");
1308  REXDENT();
1309  return 0;
1310 }
1311 
1312 /** Execute the virtual server configured to perform cache actions
1313  *
1314  * @param[in] request The current request.
1315  * @param[in] virtual_server Name of the virtual server to execute.
1316  * @param[in] autz_type The authorize sub-section to execute.
1317  * @return the rcode from the virtual server.
1318  */
1319 static rlm_rcode_t cache_process(REQUEST *request, char const *virtual_server, int autz_type)
1320 {
1321  rlm_rcode_t rcode;
1322 
1323  /*
1324  * Save the current status of the request.
1325  */
1326  char const *server = request->server;
1327  char const *module = request->module;
1328  char const *component = request->component;
1329 
1330  /*
1331  * Run it through the appropriate virtual server.
1332  */
1333  request->server = virtual_server;
1334  request->module = "cache";
1335 
1336  rcode = process_authorize(autz_type + 1000, request);
1337 
1338  /*
1339  * Restore the original status of the request.
1340  */
1341  request->server = server;
1342  request->module = module;
1343  request->component = component;
1344 
1345  fr_pair_delete_by_num(&request->config, 0, PW_TLS_SESSION_CACHE_ACTION, TAG_ANY);
1346 
1347  return rcode;
1348 }
1349 
1350 /** Write a newly created session to the cache
1351  *
1352  * @param[in] ssl session state.
1353  * @param[in] sess to serialise and write to the cache.
1354  * @return 0. What we return is not used by OpenSSL to indicate success or failure,
1355  * but to indicate whether it should free its copy of the session data.
1356  */
1357 static int cache_write_session(SSL *ssl, SSL_SESSION *sess)
1358 {
1359  fr_tls_server_conf_t *conf;
1360  REQUEST *request;
1361  size_t len, rcode;
1362  ssize_t slen;
1363  uint8_t *p, *data = NULL;
1364  VALUE_PAIR *vp;
1365  uint8_t buffer[MAX_SESSION_SIZE];
1366 
1367  request = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_REQUEST);
1368  conf = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1369 
1370  slen = tls_session_id(buffer, sizeof(buffer), sess);
1371  if (slen < 0) {
1372  REDEBUG("Session ID buffer to small");
1373  return 0;
1374  }
1375  if (cache_key_add(request, (uint8_t *) buffer, (size_t)slen, CACHE_ACTION_SESSION_WRITE) < 0) {
1376  RWDEBUG("Failed adding session key to the request");
1377  return 0;
1378  }
1379 
1380  /* find out what length data we need */
1381  len = i2d_SSL_SESSION(sess, NULL);
1382  if (len < 1) {
1383  /* something went wrong */
1384  RWDEBUG("Session serialisation failed, couldn't determine required buffer length");
1385  return 0;
1386  }
1387 
1388  /* alloc and convert to ASN.1 */
1389  data = talloc_array(NULL, uint8_t, len);
1390  if (!data) {
1391  RWDEBUG("Session serialisation failed, couldn't allocate buffer (%zd bytes)", len);
1392  return 0;
1393  }
1394 
1395  /* openssl mutates &p */
1396  p = data;
1397  rcode = i2d_SSL_SESSION(sess, &p);
1398  if (rcode != len) {
1399  RWDEBUG("Session serialisation failed");
1400  goto error;
1401  }
1402 
1403  /*
1404  * Put the SSL data into an attribute.
1405  */
1406  vp = fr_pair_afrom_num(request->state, 0, PW_TLS_SESSION_DATA);
1407  if (!vp) goto error;
1408 
1409  fr_pair_value_memsteal(vp, data);
1410  RINDENT();
1411  rdebug_pair(L_DBG_LVL_2, request, vp, "&session-state:");
1412  REXDENT();
1413  fr_pair_add(&request->state, vp);
1414  data = NULL;
1415 
1416  /*
1417  * Call the virtual server to write the session
1418  */
1419  switch (cache_process(request, conf->session_cache_server, CACHE_ACTION_SESSION_WRITE)) {
1420  case RLM_MODULE_OK:
1421  case RLM_MODULE_UPDATED:
1422  break;
1423 
1424  default:
1425  RWDEBUG("Failed storing session data");
1426  break;
1427  }
1428 
1429  /*
1430  * Ensure that the session data can't be used by anyone else.
1431  */
1432  fr_pair_delete_by_num(&request->state, 0, PW_TLS_SESSION_DATA, TAG_ANY);
1433 
1434 error:
1435  if (data) talloc_free(data);
1436 
1437  return 0;
1438 }
1439 
1440 /** Read session data from the cache
1441  *
1442  * @param[in] ssl session state.
1443  * @param[in] key to retrieve session data for.
1444  * @param[in] key_len The length of the key.
1445  * @param[out] copy Indicates whether OpenSSL should increment the reference
1446  * count on SSL_SESSION to prevent it being automatically freed. We always
1447  * set this to 0.
1448  * @return
1449  * - Deserialised session data on success.
1450  * - NULL on error.
1451  */
1452 static SSL_SESSION *cache_read_session(SSL *ssl, unsigned char *key, int key_len, int *copy)
1453 {
1454  fr_tls_server_conf_t *conf;
1455  REQUEST *request;
1456  unsigned char const **p;
1457  uint8_t const *q;
1458  VALUE_PAIR *vp;
1459  SSL_SESSION *sess;
1460 
1461  request = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_REQUEST);
1462  conf = SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
1463 
1464  if (cache_key_add(request, key, key_len, CACHE_ACTION_SESSION_READ) < 0) {
1465  RWDEBUG("Failed adding session key to the request");
1466  return NULL;
1467  }
1468 
1469  *copy = 0;
1470 
1471  /*
1472  * Call the virtual server to read the session
1473  */
1474  switch (cache_process(request, conf->session_cache_server, CACHE_ACTION_SESSION_READ)) {
1475  case RLM_MODULE_OK:
1476  case RLM_MODULE_UPDATED:
1477  break;
1478 
1479  default:
1480  RWDEBUG("Failed acquiring session data");
1481  return NULL;
1482  }
1483 
1484  vp = fr_pair_find_by_num(request->state, 0, PW_TLS_SESSION_DATA, TAG_ANY);
1485  if (!vp) {
1486  RWDEBUG("No cached session found");
1487  return NULL;
1488  }
1489 
1490  q = vp->vp_octets; /* openssl will mutate q, so we can't use vp_octets directly */
1491  p = (unsigned char const **)&q;
1492 
1493  sess = d2i_SSL_SESSION(NULL, p, vp->vp_length);
1494  if (!sess) {
1495  RWDEBUG("Failed loading persisted session: %s", ERR_error_string(ERR_get_error(), NULL));
1496  return NULL;
1497  }
1498  RDEBUG3("Read %zu bytes of session data. Session deserialized successfully", vp->vp_length);
1499 
1500  /*
1501  * Ensure that the session data can't be used by anyone else.
1502  */
1503  fr_pair_delete_by_num(&request->state, 0, PW_TLS_SESSION_DATA, TAG_ANY);
1504 
1505  return sess;
1506 }
1507 
1508 /** Delete session data from the cache
1509  *
1510  * @param[in] ctx Current ssl context.
1511  * @param[in] sess to be deleted.
1512  */
1513 static void cache_delete_session(SSL_CTX *ctx, SSL_SESSION *sess)
1514 {
1515  fr_tls_server_conf_t *conf;
1516  REQUEST *request;
1517  uint8_t buffer[MAX_SESSION_SIZE];
1518  ssize_t slen;
1519 
1520  conf = SSL_CTX_get_app_data(ctx);
1521 
1522  /*
1523  * We need a fake request for the virtual server, but we
1524  * don't have a parent request to base it on. So just
1525  * invent one.
1526  */
1527  request = request_alloc(NULL);
1528  request->packet = fr_radius_alloc(request, false);
1529  request->reply = fr_radius_alloc(request, false);
1530 
1531  slen = tls_session_id(buffer, sizeof(buffer), sess);
1532  if (slen < 0) {
1533  RWDEBUG("Session ID buffer too small");
1534  error:
1535  talloc_free(request);
1536  return;
1537  }
1538 
1539  if (cache_key_add(request, buffer, (size_t)slen, CACHE_ACTION_SESSION_DELETE) < 0) {
1540  RWDEBUG("Failed adding session key to the request");
1541  goto error;
1542  }
1543 
1544  /*
1545  * Call the virtual server to delete the session
1546  */
1547  switch (cache_process(request, conf->session_cache_server, CACHE_ACTION_SESSION_DELETE)) {
1548  case RLM_MODULE_OK:
1549  case RLM_MODULE_UPDATED:
1550  case RLM_MODULE_NOTFOUND:
1551  case RLM_MODULE_NOOP:
1552  break;
1553 
1554  default:
1555  RWDEBUG("Failed deleting session data");
1556  goto error;
1557  }
1558 
1559  /*
1560  * Delete the fake request we created.
1561  */
1562  talloc_free(request);
1563 }
1564 
1565 #define MAX_SESSION_SIZE (256)
1566 
1567 #ifdef HAVE_OPENSSL_OCSP_H
1568 /** Convert OpenSSL's ASN1_TIME to an epoch time
1569  *
1570  * @param asn1 The ASN1_TIME to convert.
1571  * @return The ASN1_TIME converted to epoch time.
1572  */
1573 static time_t ocsp_asn1time_to_epoch(ASN1_TIME const *asn1){
1574  struct tm t;
1575  const char *str = (const char *)asn1->data;
1576  size_t i = 0;
1577 
1578  memset(&t, 0, sizeof(t));
1579 
1580  if (asn1->type == V_ASN1_UTCTIME) {/* two digit year */
1581  t.tm_year = (str[i++] - '0') * 10;
1582  t.tm_year += (str[i++] - '0');
1583  if (t.tm_year < 70) t.tm_year += 100;
1584  } else if (asn1->type == V_ASN1_GENERALIZEDTIME) {/* four digit year */
1585  t.tm_year = (str[i++] - '0') * 1000;
1586  t.tm_year += (str[i++] - '0') * 100;
1587  t.tm_year += (str[i++] - '0') * 10;
1588  t.tm_year += (str[i++] - '0');
1589  t.tm_year -= 1900;
1590  }
1591 
1592  t.tm_mon = (str[i++] - '0') * 10;
1593  t.tm_mon += (str[i++] - '0') - 1; // -1 since January is 0 not 1.
1594  t.tm_mday = (str[i++] - '0') * 10;
1595  t.tm_mday += (str[i++] - '0');
1596  t.tm_hour = (str[i++] - '0') * 10;
1597  t.tm_hour += (str[i++] - '0');
1598  t.tm_min = (str[i++] - '0') * 10;
1599  t.tm_min += (str[i++] - '0');
1600  t.tm_sec = (str[i++] - '0') * 10;
1601  t.tm_sec += (str[i++] - '0');
1602 
1603  /* Apparently OpenSSL converts all timestamps to UTC? Maybe? */
1604  return mktime(&t);
1605 }
1606 
1607 /** Extract components of OCSP responser URL from a certificate
1608  *
1609  * @param[in] cert to extract URL from.
1610  * @param[out] host_out Portion of the URL (must be freed with free()).
1611  * @param[out] port_out Port portion of the URL (must be freed with free()).
1612  * @param[out] path_out Path portion of the URL (must be freed with free()).
1613  * @param[out] is_https Whether the responder should be contacted using https.
1614  * @return
1615  * - 0 if no valid URL is contained in the certificate.
1616  * - 1 if a URL was found and parsed.
1617  * - -1 if at least one URL was found, but none could be parsed.
1618  */
1619 static int ocsp_parse_cert_url(X509 *cert, char **host_out, char **port_out, char **path_out, int *is_https)
1620 {
1621  int i;
1622  bool found_uri = false;
1623 
1624  AUTHORITY_INFO_ACCESS *aia;
1625  ACCESS_DESCRIPTION *ad;
1626 
1627  aia = X509_get_ext_d2i(cert, NID_info_access, NULL, NULL);
1628 
1629  for (i = 0; i < sk_ACCESS_DESCRIPTION_num(aia); i++) {
1630  ad = sk_ACCESS_DESCRIPTION_value(aia, i);
1631  if (OBJ_obj2nid(ad->method) != NID_ad_OCSP) continue;
1632  if (ad->location->type != GEN_URI) continue;
1633  found_uri = true;
1634 
1635  if (OCSP_parse_url((char *) ad->location->d.ia5->data, host_out,
1636  port_out, path_out, is_https)) return 1;
1637  }
1638  return found_uri ? -1 : 0;
1639 }
1640 
1641 /** Drain log messages from an OpenSSL bio and print them using the specified logging macro
1642  *
1643  * @param _macro Logging macro e.g. RDEBUG.
1644  * @param _prefix Prefix, should be "" if not used.
1645  * @param _queue OpenSSL BIO.
1646  */
1647 #define SSL_DRAIN_LOG_QUEUE(_macro, _prefix, _queue) \
1648 do {\
1649  char const *_p = NULL, *_q, *_end; \
1650  size_t _len; \
1651  _len = BIO_get_mem_data(_queue, &_p); \
1652  _end = _p + _len; \
1653  if (!_p) break; \
1654  while ((_q = memchr(_p, '\n', _end - _p))) { \
1655  _macro(_prefix "%.*s", (int) (_q - _p), _p); \
1656  _p = _q + 1; \
1657  } \
1658  if (_p != _end) _macro(_prefix "%.*s", (int) (_end - _p), _p); \
1659  (void) BIO_reset(_queue); \
1660 } while (0)
1661 
1662 /** Drain errors from an OpenSSL bio and print print them using the specified logging macro
1663  *
1664  * @param _macro Logging macro e.g. RDEBUG.
1665  * @param _prefix Prefix, should be "" if not used.
1666  * @param _queue OpenSSL BIO.
1667  */
1668 #define SSL_DRAIN_ERROR_QUEUE(_macro, _prefix, _queue) \
1669 do {\
1670  ERR_print_errors(_queue); \
1671  SSL_DRAIN_LOG_QUEUE(_macro, _prefix, _queue); \
1672 } while (0)
1673 
1674 /* Maximum leeway in validity period: default 5 minutes */
1675 #define MAX_VALIDITY_PERIOD (5 * 60)
1676 
1677 typedef enum {
1678  OCSP_STATUS_FAILED = 0,
1679  OCSP_STATUS_OK = 1,
1680  OCSP_STATUS_SKIPPED = 2,
1681 } ocsp_status_t;
1682 
1683 /*
1684  * This function sends a OCSP request to a defined OCSP responder
1685  * and checks the OCSP response for correctness.
1686  */
1687 static int ocsp_check(REQUEST *request, X509_STORE *store,
1688  X509 *issuer_cert, X509 *client_cert,
1689  fr_tls_server_conf_t *conf)
1690 {
1691  OCSP_CERTID *certid;
1692  OCSP_REQUEST *req = NULL;
1693  OCSP_RESPONSE *resp = NULL;
1694  OCSP_BASICRESP *bresp = NULL;
1695  char *host = NULL;
1696  char *port = NULL;
1697  char *path = NULL;
1698  char host_header[1024];
1699  int use_ssl = -1;
1700  long this_fudge = MAX_VALIDITY_PERIOD, this_max_age = -1;
1701  BIO *conn = NULL, *ssl_log = NULL;
1702  int ocsp_status = 0;
1703  ocsp_status_t status;
1704  ASN1_GENERALIZEDTIME *rev, *this_update, *next_update;
1705  int reason;
1706 #if OPENSSL_VERSION_NUMBER >= 0x1000003f
1707  OCSP_REQ_CTX *ctx;
1708  int rc;
1709  struct timeval when;
1710 #endif
1711  struct timeval now = { 0, 0 };
1712  time_t next;
1713  VALUE_PAIR *vp;
1714 
1715  if (conf->ocsp_cache_server) switch (cache_process(request, conf->ocsp_cache_server,
1716  CACHE_ACTION_OCSP_READ)) {
1717  case RLM_MODULE_REJECT:
1718  REDEBUG("Told to force OCSP validation failure by virtual server");
1719  return OCSP_STATUS_FAILED;
1720 
1721  case RLM_MODULE_OK:
1722  case RLM_MODULE_UPDATED:
1723  /*
1724  * These are fine for OCSP too, we dont' *expect* to always
1725  * have a cached OCSP status.
1726  */
1727  case RLM_MODULE_NOTFOUND:
1728  case RLM_MODULE_NOOP:
1729  break;
1730 
1731  default:
1732  RWDEBUG("Failed retrieving cached OCSP status");
1733  break;
1734  }
1735 
1736  /*
1737  * Allow us to cache the OCSP verified state externally
1738  */
1739  vp = fr_pair_find_by_num(request->config, 0, PW_TLS_OCSP_CERT_VALID, TAG_ANY);
1740  if (vp) switch (vp->vp_integer) {
1741  case 0: /* no */
1742  RDEBUG2("Found &control:TLS-OCSP-Cert-Valid = no, forcing OCSP failure");
1743  return OCSP_STATUS_FAILED;
1744 
1745  case 1: /* yes */
1746  RDEBUG2("Found &control:TLS-OCSP-Cert-Valid = yes, forcing OCSP success");
1747  return OCSP_STATUS_OK;
1748 
1749  case 2: /* skipped */
1750  RDEBUG2("Found &control:TLS-OCSP-Cert-Valid = skipped, skipping OCSP check");
1751  return conf->ocsp_softfail ? OCSP_STATUS_OK : OCSP_STATUS_FAILED;
1752 
1753  case 3: /* unknown */
1754  default:
1755  break;
1756  }
1757 
1758  /*
1759  * Setup logging for this OCSP operation
1760  */
1761  ssl_log = BIO_new(BIO_s_mem());
1762  if (!ssl_log) {
1763  REDEBUG("Failed creating log queue");
1764  ocsp_status = OCSP_STATUS_SKIPPED;
1765  goto finish;
1766  }
1767 
1768  /*
1769  * Create OCSP Request
1770  */
1771  certid = OCSP_cert_to_id(NULL, client_cert, issuer_cert);
1772  req = OCSP_REQUEST_new();
1773  OCSP_request_add0_id(req, certid);
1774  if (conf->ocsp_use_nonce) OCSP_request_add1_nonce(req, NULL, 8);
1775 
1776  /*
1777  * Send OCSP Request and get OCSP Response
1778  */
1779 
1780  /* Get OCSP responder URL */
1781  if (conf->ocsp_override_url) {
1782  char *url;
1783 
1784  use_ocsp_url:
1785  memcpy(&url, &conf->ocsp_url, sizeof(url));
1786  /* Reading the libssl src, they do a strdup on the URL, so it could of been const *sigh* */
1787  OCSP_parse_url(url, &host, &port, &path, &use_ssl);
1788  if (!host || !port || !path) {
1789  RWDEBUG("ocsp: Host or port or path missing from configured URL \"%s\". Not doing OCSP", url);
1790  goto skipped;
1791  }
1792  } else {
1793  int ret;
1794 
1795  ret = ocsp_parse_cert_url(client_cert, &host, &port, &path, &use_ssl);
1796  switch (ret) {
1797  case -1:
1798  RWDEBUG("ocsp: Invalid URL in certificate. Not doing OCSP");
1799  break;
1800 
1801  case 0:
1802  if (conf->ocsp_url) {
1803  RWDEBUG("ocsp: No OCSP URL in certificate, falling back to configured URL");
1804  goto use_ocsp_url;
1805  }
1806  RWDEBUG("ocsp: No OCSP URL in certificate. Not doing OCSP");
1807  goto skipped;
1808 
1809  case 1:
1810  rad_assert(host && port && path);
1811  break;
1812  }
1813  }
1814 
1815  RDEBUG2("ocsp: Using responder URL \"http://%s:%s%s\"", host, port, path);
1816 
1817  /* Check host and port length are sane, then create Host: HTTP header */
1818  if ((strlen(host) + strlen(port) + 2) > sizeof(host_header)) {
1819  RWDEBUG("ocsp: Host and port too long");
1820  goto skipped;
1821  }
1822  snprintf(host_header, sizeof(host_header), "%s:%s", host, port);
1823 
1824  /* Setup BIO socket to OCSP responder */
1825  conn = BIO_new_connect(host);
1826  BIO_set_conn_port(conn, port);
1827 
1828 #if OPENSSL_VERSION_NUMBER < 0x1000003f
1829  BIO_do_connect(conn);
1830 
1831  /* Send OCSP request and wait for response */
1832  resp = OCSP_sendreq_bio(conn, path, req);
1833  if (!resp) {
1834  REDEBUG("ocsp: Couldn't get OCSP response");
1835  ocsp_status = OCSP_STATUS_SKIPPED;
1836  goto finish;
1837  }
1838 #else
1839  if (conf->ocsp_timeout) BIO_set_nbio(conn, 1);
1840 
1841  rc = BIO_do_connect(conn);
1842  if ((rc <= 0) && ((!conf->ocsp_timeout) || !BIO_should_retry(conn))) {
1843  REDEBUG("ocsp: Couldn't connect to OCSP responder");
1844  SSL_DRAIN_ERROR_QUEUE(REDEBUG, "ocsp: ", ssl_log);
1845  ocsp_status = OCSP_STATUS_SKIPPED;
1846  goto finish;
1847  }
1848 
1849  ctx = OCSP_sendreq_new(conn, path, NULL, -1);
1850  if (!ctx) {
1851  REDEBUG("ocsp: Couldn't create OCSP request");
1852  ocsp_status = OCSP_STATUS_SKIPPED;
1853  goto finish;
1854  }
1855 
1856  if (!OCSP_REQ_CTX_add1_header(ctx, "Host", host_header)) {
1857  REDEBUG("ocsp: Couldn't set Host header");
1858  ocsp_status = OCSP_STATUS_SKIPPED;
1859  goto finish;
1860  }
1861 
1862  if (!OCSP_REQ_CTX_set1_req(ctx, req)) {
1863  REDEBUG("ocsp: Couldn't add data to OCSP request");
1864  ocsp_status = OCSP_STATUS_SKIPPED;
1865  goto finish;
1866  }
1867 
1868  gettimeofday(&when, NULL);
1869  when.tv_sec += conf->ocsp_timeout;
1870 
1871  do {
1872  rc = OCSP_sendreq_nbio(&resp, ctx);
1873  if (conf->ocsp_timeout) {
1874  gettimeofday(&now, NULL);
1875  if (!timercmp(&now, &when, <)) break;
1876  }
1877  } while ((rc == -1) && BIO_should_retry(conn));
1878 
1879  if (conf->ocsp_timeout && (rc == -1) && BIO_should_retry(conn)) {
1880  REDEBUG("ocsp: Response timed out");
1881  ocsp_status = OCSP_STATUS_SKIPPED;
1882  goto finish;
1883  }
1884 
1885  OCSP_REQ_CTX_free(ctx);
1886 
1887  if (rc == 0) {
1888  REDEBUG("ocsp: Couldn't get OCSP response");
1889  SSL_DRAIN_ERROR_QUEUE(REDEBUG, "ocsp: ", ssl_log);
1890  ocsp_status = OCSP_STATUS_SKIPPED;
1891  goto finish;
1892  }
1893 #endif
1894 
1895  /* Verify OCSP response status */
1896  status = OCSP_response_status(resp);
1897  if (status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
1898  REDEBUG("ocsp: Response status: %s", OCSP_response_status_str(status));
1899  goto finish;
1900  }
1901  bresp = OCSP_response_get1_basic(resp);
1902  if (conf->ocsp_use_nonce && OCSP_check_nonce(req, bresp)!=1) {
1903  REDEBUG("ocsp: Response has wrong nonce value");
1904  goto finish;
1905  }
1906  if (OCSP_basic_verify(bresp, NULL, store, 0)!=1){
1907  REDEBUG("ocsp: Couldn't verify OCSP basic response");
1908  goto finish;
1909  }
1910 
1911  /* Verify OCSP cert status */
1912  if (!OCSP_resp_find_status(bresp, certid, (int *)&status, &reason, &rev, &this_update, &next_update)) {
1913  REDEBUG("ocsp: No Status found");
1914  goto finish;
1915  }
1916 
1917  /*
1918  * Here we check the fields 'thisUpdate' and 'nextUpdate'
1919  * from the OCSP response against the server's time.
1920  *
1921  * this_fudge is the number of seconds +- between the current
1922  * time and this_update.
1923  *
1924  * The default for this_fudge is 300, defined by MAX_VALIDITY_PERIOD.
1925  */
1926  if (!OCSP_check_validity(this_update, next_update, this_fudge, this_max_age)) {
1927  /*
1928  * We want this to show up in the global log
1929  * so someone will fix it...
1930  */
1931  RATE_LIMIT(RERROR("ocsp: Delta +/- between OCSP response time and our time is greater than %li "
1932  "seconds. Check servers are synchronised to a common time source",
1933  this_fudge));
1934  SSL_DRAIN_ERROR_QUEUE(REDEBUG, "ocsp: ", ssl_log);
1935  goto finish;
1936  }
1937 
1938  /*
1939  * Print any messages we may have accumulated
1940  */
1941  SSL_DRAIN_ERROR_QUEUE(REDEBUG, "ocsp: ", ssl_log);
1942  if (RDEBUG_ENABLED) {
1943  RDEBUG2("ocsp: OCSP response valid from:");
1944  ASN1_GENERALIZEDTIME_print(ssl_log, this_update);
1945  RINDENT();
1946  SSL_DRAIN_LOG_QUEUE(RDEBUG2, "", ssl_log);
1947  REXDENT();
1948 
1949  RDEBUG2("ocsp: New information available at:");
1950  ASN1_GENERALIZEDTIME_print(ssl_log, next_update);
1951  RINDENT();
1952  SSL_DRAIN_LOG_QUEUE(RDEBUG2, "", ssl_log);
1953  REXDENT();
1954  }
1955 
1956  /*
1957  * Sometimes we already know what 'now' is depending
1958  * on the code path, other times we don't.
1959  */
1960  if (now.tv_sec == 0) gettimeofday(&now, NULL);
1961  next = ocsp_asn1time_to_epoch(next_update);
1962  if (now.tv_sec < next){
1963  RDEBUG2("ocsp: Adding OCSP TTL attribute");
1964  RINDENT();
1965  vp = pair_make_request("TLS-OCSP-Next-Update", NULL, T_OP_SET);
1966  vp->vp_integer = next - now.tv_sec;
1967  rdebug_pair(L_DBG_LVL_2, request, vp, NULL);
1968  REXDENT();
1969  } else {
1970  RDEBUG2("ocsp: Update time is in the past. Not adding &TLS-OCSP-Next-Update");
1971  }
1972 
1973  switch (status) {
1974  case V_OCSP_CERTSTATUS_GOOD:
1975  RDEBUG2("ocsp: Cert status: good");
1976  ocsp_status = OCSP_STATUS_OK;
1977  break;
1978 
1979  default:
1980  /* REVOKED / UNKNOWN */
1981  REDEBUG("ocsp: Cert status: %s", OCSP_cert_status_str(status));
1982  if (reason != -1) REDEBUG("ocsp: Reason: %s", OCSP_crl_reason_str(reason));
1983 
1984  /*
1985  * Print any messages we may have accumulated
1986  */
1987  SSL_DRAIN_LOG_QUEUE(RDEBUG, "ocsp: ", ssl_log);
1988  if (RDEBUG_ENABLED) {
1989  RDEBUG2("ocsp: Revocation time:");
1990  ASN1_GENERALIZEDTIME_print(ssl_log, rev);
1991  RINDENT();
1992  SSL_DRAIN_LOG_QUEUE(RDEBUG2, "", ssl_log);
1993  REXDENT();
1994  }
1995  break;
1996  }
1997 
1998 finish:
1999  /* Free OCSP Stuff */
2000  OCSP_REQUEST_free(req);
2001  OCSP_RESPONSE_free(resp);
2002  free(host);
2003  free(port);
2004  free(path);
2005  BIO_free_all(conn);
2006  BIO_free(ssl_log);
2007  OCSP_BASICRESP_free(bresp);
2008 
2009  switch (ocsp_status) {
2010  case OCSP_STATUS_OK:
2011  RDEBUG2("ocsp: Certificate is valid");
2012  vp = pair_make_request("TLS-OCSP-Cert-Valid", NULL, T_OP_SET);
2013  vp->vp_integer = 1; /* yes */
2014  ocsp_status = OCSP_STATUS_OK;
2015  break;
2016 
2017  case OCSP_STATUS_SKIPPED:
2018  skipped:
2019  vp = pair_make_request("TLS-OCSP-Cert-Valid", NULL, T_OP_SET);
2020  vp->vp_integer = 2; /* skipped */
2021  if (conf->ocsp_softfail) {
2022  RWDEBUG("ocsp: Unable to check certificate, assuming it's valid");
2023  RWDEBUG("ocsp: This may be insecure");
2024  ocsp_status = OCSP_STATUS_OK;
2025  } else {
2026  REDEBUG("ocsp: Unable to check certificate, failing");
2027  ocsp_status = OCSP_STATUS_FAILED;
2028  }
2029  break;
2030 
2031  default:
2032  vp = pair_make_request("TLS-OCSP-Cert-Valid", NULL, T_OP_SET);
2033  vp->vp_integer = 0; /* no */
2034  REDEBUG("ocsp: Failed to validate certificate");
2035  break;
2036  }
2037 
2038  if (conf->ocsp_cache_server) switch (cache_process(request, conf->ocsp_cache_server, CACHE_ACTION_OCSP_WRITE)) {
2039  case RLM_MODULE_OK:
2040  case RLM_MODULE_UPDATED:
2041  break;
2042 
2043  default:
2044  RWDEBUG("Failed writing cached OCSP status");
2045  break;
2046  }
2047 
2048  return ocsp_status;
2049 }
2050 #endif /* HAVE_OPENSSL_OCSP_H */
2051 
2052 /*
2053  * For creating certificate attributes.
2054  */
2055 static char const *cert_attr_names[8][2] = {
2056  { "TLS-Client-Cert-Serial", "TLS-Cert-Serial" },
2057  { "TLS-Client-Cert-Expiration", "TLS-Cert-Expiration" },
2058  { "TLS-Client-Cert-Subject", "TLS-Cert-Subject" },
2059  { "TLS-Client-Cert-Issuer", "TLS-Cert-Issuer" },
2060  { "TLS-Client-Cert-Common-Name", "TLS-Cert-Common-Name" },
2061  { "TLS-Client-Cert-Subject-Alt-Name-Email", "TLS-Cert-Subject-Alt-Name-Email" },
2062  { "TLS-Client-Cert-Subject-Alt-Name-Dns", "TLS-Cert-Subject-Alt-Name-Dns" },
2063  { "TLS-Client-Cert-Subject-Alt-Name-Upn", "TLS-Cert-Subject-Alt-Name-Upn" }
2064 };
2065 
2066 #define FR_TLS_SERIAL (0)
2067 #define FR_TLS_EXPIRATION (1)
2068 #define FR_TLS_SUBJECT (2)
2069 #define FR_TLS_ISSUER (3)
2070 #define FR_TLS_CN (4)
2071 #define FR_TLS_SAN_EMAIL (5)
2072 #define FR_TLS_SAN_DNS (6)
2073 #define FR_TLS_SAN_UPN (7)
2074 
2075 /*
2076  * Before trusting a certificate, you must make sure that the
2077  * certificate is 'valid'. There are several steps that your
2078  * application can take in determining if a certificate is
2079  * valid. Commonly used steps are:
2080  *
2081  * 1.Verifying the certificate's signature, and verifying that
2082  * the certificate has been issued by a trusted Certificate
2083  * Authority.
2084  *
2085  * 2.Verifying that the certificate is valid for the present date
2086  * (i.e. it is being presented within its validity dates).
2087  *
2088  * 3.Verifying that the certificate has not been revoked by its
2089  * issuing Certificate Authority, by checking with respect to a
2090  * Certificate Revocation List (CRL).
2091  *
2092  * 4.Verifying that the credentials presented by the certificate
2093  * fulfill additional requirements specific to the application,
2094  * such as with respect to access control lists or with respect
2095  * to OCSP (Online Certificate Status Processing).
2096  *
2097  * NOTE: This callback will be called multiple times based on the
2098  * depth of the root certificate chain
2099  */
2100 int cbtls_verify(int ok, X509_STORE_CTX *ctx)
2101 {
2102  char subject[1024]; /* Used for the subject name */
2103  char issuer[1024]; /* Used for the issuer name */
2104  char attribute[1024];
2105  char value[1024];
2106  char common_name[1024];
2107  char cn_str[1024];
2108  char buf[64];
2109  X509 *client_cert;
2110  X509_CINF *client_inf;
2111  STACK_OF(X509_EXTENSION) *ext_list;
2112  SSL *ssl;
2113  int err, depth, lookup, loc;
2114  fr_tls_server_conf_t *conf;
2115  int my_ok = ok;
2116 
2117  ASN1_INTEGER *sn = NULL;
2118  ASN1_TIME *asn_time = NULL;
2119  VALUE_PAIR *cert_vps = NULL;
2120  vp_cursor_t cursor;
2121 
2122  char **identity;
2123 #ifdef HAVE_OPENSSL_OCSP_H
2124  X509_STORE *ocsp_store = NULL;
2125  X509 *issuer_cert;
2126 #endif
2127  VALUE_PAIR *vp;
2128 
2129  REQUEST *request;
2130 
2131 #define ADD_CERT_ATTR(_name, _value) \
2132 do { \
2133  VALUE_PAIR *_vp; \
2134  _vp = fr_pair_make(request, NULL, _name, _value, T_OP_SET); \
2135  if (_vp) { \
2136  fr_cursor_insert(&cursor, _vp); \
2137  } else { \
2138  RWDEBUG("Failed creating attribute %s: %s", _name, fr_strerror()); \
2139  } \
2140 } while (0)
2141 
2142  client_cert = X509_STORE_CTX_get_current_cert(ctx);
2143  err = X509_STORE_CTX_get_error(ctx);
2144  depth = X509_STORE_CTX_get_error_depth(ctx);
2145 
2146  lookup = depth;
2147 
2148  /*
2149  * Log client/issuing cert. If there's an error, log
2150  * issuing cert.
2151  */
2152  if ((lookup > 1) && !my_ok) lookup = 1;
2153 
2154  /*
2155  * Retrieve the pointer to the SSL of the connection currently treated
2156  * and the application specific data stored into the SSL object.
2157  */
2158  ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
2159  conf = (fr_tls_server_conf_t *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_CONF);
2160  if (!conf) return 1;
2161 
2162  request = (REQUEST *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_REQUEST);
2163  rad_assert(request != NULL);
2164 
2165  fr_cursor_init(&cursor, &cert_vps);
2166 
2167  identity = (char **)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_IDENTITY);
2168 #ifdef HAVE_OPENSSL_OCSP_H
2169  ocsp_store = (X509_STORE *)SSL_get_ex_data(ssl, FR_TLS_EX_INDEX_STORE);
2170 #endif
2171 
2172  /*
2173  * Get the Serial Number
2174  */
2175  buf[0] = '\0';
2176  sn = X509_get_serialNumber(client_cert);
2177 
2178  RDEBUG2("Creating attributes from certificate OIDs");
2179 
2180  /*
2181  * For this next bit, we create the attributes *only* if
2182  * we're at the client or issuing certificate, AND we
2183  * have a user identity. i.e. we don't create the
2184  * attributes for RadSec connections.
2185  */
2186  if (identity && (lookup <= 1) && sn && ((size_t) sn->length < (sizeof(buf) / 2))) {
2187  char *p = buf;
2188  int i;
2189 
2190  for (i = 0; i < sn->length; i++) {
2191  sprintf(p, "%02x", (unsigned int)sn->data[i]);
2192  p += 2;
2193  }
2194  ADD_CERT_ATTR(cert_attr_names[FR_TLS_SERIAL][lookup], buf);
2195  }
2196 
2197 
2198  /*
2199  * Get the Expiration Date
2200  */
2201  buf[0] = '\0';
2202  asn_time = X509_get_notAfter(client_cert);
2203  if (identity && (lookup <= 1) && asn_time && (asn_time->length < (int) sizeof(buf))) {
2204  memcpy(buf, (char*) asn_time->data, asn_time->length);
2205  buf[asn_time->length] = '\0';
2206  ADD_CERT_ATTR(cert_attr_names[FR_TLS_EXPIRATION][lookup], buf);
2207  }
2208 
2209  /*
2210  * Get the Subject & Issuer
2211  */
2212  subject[0] = issuer[0] = '\0';
2213  X509_NAME_oneline(X509_get_subject_name(client_cert), subject,
2214  sizeof(subject));
2215  subject[sizeof(subject) - 1] = '\0';
2216  if (identity && (lookup <= 1) && subject[0]) {
2217  ADD_CERT_ATTR(cert_attr_names[FR_TLS_SUBJECT][lookup], subject);
2218  }
2219 
2220  X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), issuer,
2221  sizeof(issuer));
2222  issuer[sizeof(issuer) - 1] = '\0';
2223  if (identity && (lookup <= 1) && issuer[0]) {
2224  ADD_CERT_ATTR(cert_attr_names[FR_TLS_ISSUER][lookup], issuer);
2225  }
2226 
2227  /*
2228  * Get the Common Name, if there is a subject.
2229  */
2230  X509_NAME_get_text_by_NID(X509_get_subject_name(client_cert),
2231  NID_commonName, common_name, sizeof(common_name));
2232  common_name[sizeof(common_name) - 1] = '\0';
2233  if (identity && (lookup <= 1) && common_name[0] && subject[0]) {
2234  ADD_CERT_ATTR(cert_attr_names[FR_TLS_CN][lookup], common_name);
2235  }
2236 
2237  /*
2238  * Get the RFC822 Subject Alternative Name
2239  */
2240  loc = X509_get_ext_by_NID(client_cert, NID_subject_alt_name, 0);
2241  if ((lookup <= 1) && (loc >= 0)) {
2242  X509_EXTENSION *ext = NULL;
2243  GENERAL_NAMES *names = NULL;
2244  int i;
2245 
2246  if ((ext = X509_get_ext(client_cert, loc)) &&
2247  (names = X509V3_EXT_d2i(ext))) {
2248  for (i = 0; i < sk_GENERAL_NAME_num(names); i++) {
2249  GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);
2250 
2251  switch (name->type) {
2252 #ifdef GEN_EMAIL
2253  case GEN_EMAIL:
2254  ADD_CERT_ATTR(cert_attr_names[FR_TLS_SAN_EMAIL][lookup],
2255  (char *) ASN1_STRING_data(name->d.rfc822Name));
2256  break;
2257 #endif /* GEN_EMAIL */
2258 #ifdef GEN_DNS
2259  case GEN_DNS:
2260  ADD_CERT_ATTR(cert_attr_names[FR_TLS_SAN_DNS][lookup],
2261  (char *) ASN1_STRING_data(name->d.dNSName));
2262  break;
2263 #endif /* GEN_DNS */
2264 #ifdef GEN_OTHERNAME
2265  case GEN_OTHERNAME:
2266  /* look for a MS UPN */
2267  if (NID_ms_upn != OBJ_obj2nid(name->d.otherName->type_id)) break;
2268 
2269  /* we've got a UPN - Must be ASN1-encoded UTF8 string */
2270  if (name->d.otherName->value->type == V_ASN1_UTF8STRING) {
2271  ADD_CERT_ATTR(cert_attr_names[FR_TLS_SAN_UPN][lookup],
2272  (char *) name->d.otherName->value->value.utf8string);
2273  break;
2274  }
2275 
2276  RWARN("Invalid UPN in Subject Alt Name (should be UTF-8)");
2277  break;
2278 #endif /* GEN_OTHERNAME */
2279  default:
2280  /* XXX TODO handle other SAN types */
2281  break;
2282  }
2283  }
2284  }
2285  if (names != NULL) sk_GENERAL_NAME_free(names);
2286  }
2287 
2288  /*
2289  * If the CRL has expired, that might still be OK.
2290  */
2291  if (!my_ok &&
2292  (conf->allow_expired_crl) &&
2293  (err == X509_V_ERR_CRL_HAS_EXPIRED)) {
2294  my_ok = 1;
2295  X509_STORE_CTX_set_error( ctx, 0 );
2296  }
2297 
2298  if (!my_ok) {
2299  char const *p = X509_verify_cert_error_string(err);
2300  RERROR("TLS error: %s (%i)", p, err);
2301  REXDENT();
2302  fr_pair_list_free(&cert_vps);
2303  return my_ok;
2304  }
2305 
2306  if (lookup == 0) {
2307  client_inf = client_cert->cert_info;
2308  ext_list = client_inf->extensions;
2309  } else {
2310  ext_list = NULL;
2311  }
2312 
2313  /*
2314  * Grab the X509 extensions, and create attributes out of them.
2315  * For laziness, we re-use the OpenSSL names
2316  */
2317  if (sk_X509_EXTENSION_num(ext_list) > 0) {
2318  int i, len;
2319  char *p;
2320  BIO *out;
2321 
2322  out = BIO_new(BIO_s_mem());
2323  strlcpy(attribute, "TLS-Client-Cert-", sizeof(attribute));
2324 
2325  for (i = 0; i < sk_X509_EXTENSION_num(ext_list); i++) {
2326  ASN1_OBJECT *obj;
2327  X509_EXTENSION *ext;
2328 
2329  ext = sk_X509_EXTENSION_value(ext_list, i);
2330 
2331  obj = X509_EXTENSION_get_object(ext);
2332  i2a_ASN1_OBJECT(out, obj);
2333  len = BIO_read(out, attribute + 16 , sizeof(attribute) - 16 - 1);
2334  if (len <= 0) continue;
2335 
2336  attribute[16 + len] = '\0';
2337 
2338  for (p = attribute + 16; *p != '\0'; p++) {
2339  if (*p == ' ') *p = '-';
2340  }
2341 
2342  X509V3_EXT_print(out, ext, 0, 0);
2343  len = BIO_read(out, value , sizeof(value) - 1);
2344  if (len <= 0) continue;
2345 
2346  value[len] = '\0';
2347 
2348  vp = fr_pair_make(request, NULL, attribute, value, T_OP_ADD);
2349  if (!vp) {
2350  RDEBUG3("Skipping %s += '%s'. Please check that both the "
2351  "attribute and value are defined in the dictionaries",
2352  attribute, value);
2353  } else {
2354  fr_cursor_insert(&cursor, vp);
2355  }
2356  }
2357 
2358  BIO_free_all(out);
2359  }
2360 
2361  /*
2362  * Add a copy of the cert_vps to session state.
2363  */
2364  if (cert_vps) {
2365  /*
2366  * Print out all the pairs we have so far
2367  */
2368  rdebug_pair_list(L_DBG_LVL_2, request, cert_vps, "&session-state:");
2369 
2370  /*
2371  * cert_vps have a different talloc parent, so we
2372  * can't just reference them.
2373  */
2374  fr_pair_list_mcopy_by_num(request->state_ctx, &request->state, &cert_vps, 0, 0, TAG_ANY);
2375  fr_pair_list_free(&cert_vps);
2376  }
2377 
2378  switch (ctx->error) {
2379  case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
2380  RERROR("issuer=%s", issuer);
2381  break;
2382 
2383  case X509_V_ERR_CERT_NOT_YET_VALID:
2384  case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
2385  RERROR("notBefore=");
2386 #if 0
2387  ASN1_TIME_print(bio_err, X509_get_notBefore(ctx->current_cert));
2388 #endif
2389  break;
2390 
2391  case X509_V_ERR_CERT_HAS_EXPIRED:
2392  case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
2393  RERROR("notAfter=");
2394 #if 0
2395  ASN1_TIME_print(bio_err, X509_get_notAfter(ctx->current_cert));
2396 #endif
2397  break;
2398  }
2399 
2400  /*
2401  * If we're at the actual client cert, apply additional
2402  * checks.
2403  */
2404  if (depth == 0) {
2405  /*
2406  * If the conf tells us to, check cert issuer
2407  * against the specified value and fail
2408  * verification if they don't match.
2409  */
2410  if (conf->check_cert_issuer &&
2411  (strcmp(issuer, conf->check_cert_issuer) != 0)) {
2412  AUTH(LOG_PREFIX ": Certificate issuer (%s) does not match specified value (%s)!",
2413  issuer, conf->check_cert_issuer);
2414  my_ok = 0;
2415  }
2416 
2417  /*
2418  * If the conf tells us to, check the CN in the
2419  * cert against xlat'ed value, but only if the
2420  * previous checks passed.
2421  */
2422  if (my_ok && conf->check_cert_cn) {
2423  if (radius_xlat(cn_str, sizeof(cn_str), request, conf->check_cert_cn, NULL, NULL) < 0) {
2424  /* if this fails, fail the verification */
2425  my_ok = 0;
2426  } else {
2427  RDEBUG2("checking certificate CN (%s) with xlat'ed value (%s)", common_name, cn_str);
2428  if (strcmp(cn_str, common_name) != 0) {
2429  AUTH(LOG_PREFIX ": Certificate CN (%s) does not match specified value (%s)!",
2430  common_name, cn_str);
2431  my_ok = 0;
2432  }
2433  }
2434  } /* check_cert_cn */
2435 
2436  while (conf->verify_client_cert_cmd) {
2437  char filename[256];
2438  int fd;
2439  FILE *fp;
2440 
2441  snprintf(filename, sizeof(filename), "%s/%s.client.XXXXXXXX",
2442  conf->verify_tmp_dir, main_config.name);
2443  fd = mkstemp(filename);
2444  if (fd < 0) {
2445  RDEBUG("Failed creating file in %s: %s",
2446  conf->verify_tmp_dir, fr_syserror(errno));
2447  break;
2448  }
2449 
2450  fp = fdopen(fd, "w");
2451  if (!fp) {
2452  close(fd);
2453  RDEBUG("Failed opening file %s: %s",
2454  filename, fr_syserror(errno));
2455  break;
2456  }
2457 
2458  if (!PEM_write_X509(fp, client_cert)) {
2459  fclose(fp);
2460  RDEBUG("Failed writing certificate to file");
2461  goto do_unlink;
2462  }
2463  fclose(fp);
2464 
2465  if (!pair_make_request("TLS-Client-Cert-Filename",
2466  filename, T_OP_SET)) {
2467  RDEBUG("Failed creating TLS-Client-Cert-Filename");
2468 
2469  goto do_unlink;
2470  }
2471 
2472  RDEBUG("Verifying client certificate: %s", conf->verify_client_cert_cmd);
2473  if (radius_exec_program(request, NULL, 0, NULL, request, conf->verify_client_cert_cmd,
2474  request->packet->vps,
2475  true, true, EXEC_TIMEOUT) != 0) {
2476  AUTH(LOG_PREFIX ": Certificate CN (%s) fails external verification!", common_name);
2477  my_ok = 0;
2478  } else {
2479  RDEBUG("Client certificate CN %s passed external validation", common_name);
2480  }
2481 
2482  do_unlink:
2483  unlink(filename);
2484  break;
2485  }
2486 
2487 #ifdef HAVE_OPENSSL_OCSP_H
2488  /*
2489  * Do OCSP last, so we have the complete set of attributes
2490  * available for the virtual server.
2491  *
2492  * Fixme: Do we want to store the matching TLS-Client-cert-Filename?
2493  */
2494  if (my_ok && conf->ocsp_enable){
2495  RDEBUG2("Starting OCSP Request");
2496  if (X509_STORE_CTX_get1_issuer(&issuer_cert, ctx, client_cert) != 1) {
2497  RERROR("Couldn't get issuer_cert for %s", common_name);
2498  } else {
2499  my_ok = ocsp_check(request, ocsp_store, issuer_cert, client_cert, conf);
2500  }
2501  }
2502 #endif
2503  } /* depth == 0 */
2504 
2505  if (RDEBUG_ENABLED3) {
2506  RDEBUG3("chain-depth : %d", depth);
2507  RDEBUG3("error : %d", err);
2508 
2509  if (identity) RDEBUG3("identity : %s", *identity);
2510  RDEBUG3("common name : %s", common_name);
2511  RDEBUG3("subject : %s", subject);
2512  RDEBUG3("issuer : %s", issuer);
2513  RDEBUG3("verify return : %d", my_ok);
2514  }
2515  return my_ok;
2516 }
2517 
2518 
2519 #ifdef HAVE_OPENSSL_OCSP_H
2520 /*
2521  * Create Global X509 revocation store and use it to verify
2522  * OCSP responses
2523  *
2524  * - Load the trusted CAs
2525  * - Load the trusted issuer certificates
2526  */
2527 static X509_STORE *init_revocation_store(fr_tls_server_conf_t *conf)
2528 {
2529  X509_STORE *store = NULL;
2530 
2531  store = X509_STORE_new();
2532 
2533  /* Load the CAs we trust */
2534  if (conf->ca_file || conf->ca_path)
2535  if(!X509_STORE_load_locations(store, conf->ca_file, conf->ca_path)) {
2536  ERROR(LOG_PREFIX ": X509_STORE error %s", ERR_error_string(ERR_get_error(), NULL));
2537  ERROR(LOG_PREFIX ": Error reading Trusted root CA list %s",conf->ca_file );
2538  return NULL;
2539  }
2540 
2541 #ifdef X509_V_FLAG_CRL_CHECK
2542  if (conf->check_crl)
2543  X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK);
2544 #endif
2545 #ifdef X509_V_FLAG_CRL_CHECK_ALL
2546  if (conf->check_all_crl)
2547  X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK_ALL);
2548 #endif
2549  return store;
2550 }
2551 #endif /* HAVE_OPENSSL_OCSP_H */
2552 
2553 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
2554 #ifndef OPENSSL_NO_ECDH
2555 static int set_ecdh_curve(SSL_CTX *ctx, char const *ecdh_curve, bool disable_single_dh_use)
2556 {
2557  int nid;
2558  EC_KEY *ecdh;
2559 
2560  if (!ecdh_curve || !*ecdh_curve) return 0;
2561 
2562  nid = OBJ_sn2nid(ecdh_curve);
2563  if (!nid) {
2564  ERROR(LOG_PREFIX ": Unknown ecdh_curve \"%s\"", ecdh_curve);
2565  return -1;
2566  }
2567 
2568  ecdh = EC_KEY_new_by_curve_name(nid);
2569  if (!ecdh) {
2570  ERROR(LOG_PREFIX ": Unable to create new curve \"%s\"", ecdh_curve);
2571  return -1;
2572  }
2573 
2574  SSL_CTX_set_tmp_ecdh(ctx, ecdh);
2575 
2576  if (!disable_single_dh_use) {
2577  SSL_CTX_set_options(ctx, SSL_OP_SINGLE_ECDH_USE);
2578  }
2579 
2580  EC_KEY_free(ecdh);
2581 
2582  return 0;
2583 }
2584 #endif
2585 #endif
2586 
2587 static unsigned long _tls_thread_id(void)
2588 {
2589  unsigned long ret;
2590  pthread_t thread = pthread_self();
2591 
2592  if (sizeof(ret) >= sizeof(thread)) {
2593  memcpy(&ret, &thread, sizeof(thread));
2594  } else {
2595  memcpy(&ret, &thread, sizeof(ret));
2596  }
2597 
2598  return ret;
2599 }
2600 
2601 static void _tls_lock(int mode, int n, UNUSED char const *file, UNUSED int line)
2602 {
2603  if (mode & CRYPTO_LOCK) {
2604  pthread_mutex_lock(&(tls_static_mutexes[n]));
2605  } else {
2606  pthread_mutex_unlock(&(tls_static_mutexes[n]));
2607  }
2608 }
2609 
2610 /** Free the static mutexes we allocated for OpenSSL
2611  *
2612  */
2613 static int _tls_static_mutexes_free(pthread_mutex_t *mutexes)
2614 {
2615  size_t i;
2616 
2617  /*
2618  * Ensure OpenSSL doesn't use the locks
2619  */
2620  CRYPTO_set_id_callback(NULL);
2621  CRYPTO_set_locking_callback(NULL);
2622 
2623  /*
2624  * Destroy all the mutexes
2625  */
2626  for (i = 0; i < talloc_array_length(mutexes); i++) pthread_mutex_destroy(&(mutexes[i]));
2627 
2628  return 0;
2629 }
2630 
2631 /** OpenSSL uses static mutexes which we need to initialise
2632  *
2633  * @note Yes, these really are global.
2634  *
2635  * @param ctx to alloc mutexes/array in.
2636  * @return array of mutexes.
2637  */
2638 static pthread_mutex_t *tls_mutexes_init(TALLOC_CTX *ctx)
2639 {
2640  int i = 0;
2641  pthread_mutex_t *mutexes;
2642 
2643 #define SETUP_CRYPTO_LOCK if (i < CRYPTO_num_locks()) pthread_mutex_init(&(mutexes[i++]), NULL)
2644 
2645  mutexes = talloc_array(ctx, pthread_mutex_t, CRYPTO_num_locks());
2646  if (!mutexes) {
2647  ERROR("Error allocating memory for OpenSSL mutexes!");
2648  return NULL;
2649  }
2650 
2651  talloc_set_destructor(mutexes, _tls_static_mutexes_free);
2652 
2653  /*
2654  * Some profiling tools only give us the line the mutex
2655  * was initialised on. In that case this allows us to
2656  * see which of the mutexes in the profiling tool relates
2657  * to which OpenSSL mutex.
2658  *
2659  * OpenSSL locks are usually indexed from 1, but just to
2660  * be sure we initialise index 0 too.
2661  */
2662  SETUP_CRYPTO_LOCK; /* UNUSED */
2663  SETUP_CRYPTO_LOCK; /* 1 - CRYPTO_LOCK_ERR */
2664  SETUP_CRYPTO_LOCK; /* 2 - CRYPTO_LOCK_EX_DATA */
2665  SETUP_CRYPTO_LOCK; /* 3 - CRYPTO_LOCK_X509 */
2666  SETUP_CRYPTO_LOCK; /* 4 - CRYPTO_LOCK_X509_INFO */
2667  SETUP_CRYPTO_LOCK; /* 5 - CRYPTO_LOCK_X509_PKEY */
2668  SETUP_CRYPTO_LOCK; /* 6 - CRYPTO_LOCK_X509_CRL */
2669  SETUP_CRYPTO_LOCK; /* 7 - CRYPTO_LOCK_X509_REQ */
2670  SETUP_CRYPTO_LOCK; /* 8 - CRYPTO_LOCK_DSA */
2671  SETUP_CRYPTO_LOCK; /* 9 - CRYPTO_LOCK_RSA */
2672  SETUP_CRYPTO_LOCK; /* 10 - CRYPTO_LOCK_EVP_PKEY */
2673  SETUP_CRYPTO_LOCK; /* 11 - CRYPTO_LOCK_X509_STORE */
2674  SETUP_CRYPTO_LOCK; /* 12 - CRYPTO_LOCK_SSL_CTX */
2675  SETUP_CRYPTO_LOCK; /* 13 - CRYPTO_LOCK_SSL_CERT */
2676  SETUP_CRYPTO_LOCK; /* 14 - CRYPTO_LOCK_SSL_SESSION */
2677  SETUP_CRYPTO_LOCK; /* 15 - CRYPTO_LOCK_SSL_SESS_CERT */
2678  SETUP_CRYPTO_LOCK; /* 16 - CRYPTO_LOCK_SSL */
2679  SETUP_CRYPTO_LOCK; /* 17 - CRYPTO_LOCK_SSL_METHOD */
2680  SETUP_CRYPTO_LOCK; /* 18 - CRYPTO_LOCK_RAND */
2681  SETUP_CRYPTO_LOCK; /* 19 - CRYPTO_LOCK_RAND2 */
2682  SETUP_CRYPTO_LOCK; /* 20 - CRYPTO_LOCK_MALLOC */
2683  SETUP_CRYPTO_LOCK; /* 21 - CRYPTO_LOCK_BIO */
2684  SETUP_CRYPTO_LOCK; /* 22 - CRYPTO_LOCK_GETHOSTBYNAME */
2685  SETUP_CRYPTO_LOCK; /* 23 - CRYPTO_LOCK_GETSERVBYNAME */
2686  SETUP_CRYPTO_LOCK; /* 24 - CRYPTO_LOCK_READDIR */
2687  SETUP_CRYPTO_LOCK; /* 25 - CRYPTO_LOCRYPTO_LOCK_RSA_BLINDING */
2688  SETUP_CRYPTO_LOCK; /* 26 - CRYPTO_LOCK_DH */
2689  SETUP_CRYPTO_LOCK; /* 27 - CRYPTO_LOCK_MALLOC2 */
2690  SETUP_CRYPTO_LOCK; /* 28 - CRYPTO_LOCK_DSO */
2691  SETUP_CRYPTO_LOCK; /* 29 - CRYPTO_LOCK_DYNLOCK */
2692  SETUP_CRYPTO_LOCK; /* 30 - CRYPTO_LOCK_ENGINE */
2693  SETUP_CRYPTO_LOCK; /* 31 - CRYPTO_LOCK_UI */
2694  SETUP_CRYPTO_LOCK; /* 32 - CRYPTO_LOCK_ECDSA */
2695  SETUP_CRYPTO_LOCK; /* 33 - CRYPTO_LOCK_EC */
2696  SETUP_CRYPTO_LOCK; /* 34 - CRYPTO_LOCK_ECDH */
2697  SETUP_CRYPTO_LOCK; /* 35 - CRYPTO_LOCK_BN */
2698  SETUP_CRYPTO_LOCK; /* 36 - CRYPTO_LOCK_EC_PRE_COMP */
2699  SETUP_CRYPTO_LOCK; /* 37 - CRYPTO_LOCK_STORE */
2700  SETUP_CRYPTO_LOCK; /* 38 - CRYPTO_LOCK_COMP */
2701  SETUP_CRYPTO_LOCK; /* 39 - CRYPTO_LOCK_FIPS */
2702  SETUP_CRYPTO_LOCK; /* 40 - CRYPTO_LOCK_FIPS2 */
2703 
2704  /*
2705  * Incase more are added *sigh*
2706  */
2707  while (i < CRYPTO_num_locks()) SETUP_CRYPTO_LOCK;
2708 
2709  CRYPTO_set_id_callback(_tls_thread_id);
2710  CRYPTO_set_locking_callback(_tls_lock);
2711 
2712  return mutexes;
2713 }
2714 
2715 /** Add all the default ciphers and message digests to our context.
2716  *
2717  * This should be called exactly once from main, before reading the main config
2718  * or initialising any modules.
2719  */
2720 int tls_global_init(void)
2721 {
2722  ENGINE *rand_engine;
2723 
2724  if (tls_done_init) return 0;
2725 
2726  SSL_load_error_strings(); /* Readable error messages (examples show call before library_init) */
2727  SSL_library_init(); /* Initialize library */
2728  OpenSSL_add_all_algorithms(); /* Required for SHA2 in OpenSSL < 0.9.8o and 1.0.0.a */
2729  ENGINE_load_builtin_engines(); /* Needed to load AES-NI engine (also loads rdrand, boo) */
2730 
2731  /*
2732  * SHA256 is in all versions of OpenSSL, but isn't
2733  * initialized by default. It's needed for WiMAX
2734  * certificates.
2735  */
2736 #ifdef HAVE_OPENSSL_EVP_SHA256
2737  EVP_add_digest(EVP_sha256());
2738 #endif
2739  OPENSSL_config(NULL);
2740 
2741  /*
2742  * Mirror the paranoia found elsewhere on the net,
2743  * and disable rdrand as the default random number
2744  * generator.
2745  */
2746  rand_engine = ENGINE_get_default_RAND();
2747  if (rand_engine && (strcmp(ENGINE_get_id(rand_engine), "rdrand") == 0)) ENGINE_unregister_RAND(rand_engine);
2748  ENGINE_register_all_complete();
2749 
2750  /*
2751  * If we're linking with OpenSSL too, then we need
2752  * to set up the mutexes and enable the thread callbacks.
2753  */
2754  tls_static_mutexes = tls_mutexes_init(NULL);
2755  if (!tls_static_mutexes) {
2756  ERROR("FATAL: Failed to set up SSL mutexes");
2757  return -1;
2758  }
2759 
2760  tls_done_init = true;
2761 
2762  return 0;
2763 }
2764 
2765 /** Free any memory alloced by libssl
2766  *
2767  */
2768 void tls_global_cleanup(void)
2769 {
2770  ERR_remove_state(0);
2771  ENGINE_cleanup();
2772  CONF_modules_unload(1);
2773  ERR_free_strings();
2774  EVP_cleanup();
2775  CRYPTO_cleanup_all_ex_data();
2776 
2777  TALLOC_FREE(tls_static_mutexes);
2778 
2779  tls_done_init = false;
2780 }
2781 
2782 #ifdef ENABLE_OPENSSL_VERSION_CHECK
2783 /** Check for vulnerable versions of libssl
2784  *
2785  * @param acknowledged The highest CVE number a user has confirmed is not present in the system's
2786  * libssl.
2787  * @return 0 if the CVE specified by the user matches the most recent CVE we have, else -1.
2788  */
2789 int tls_global_version_check(char const *acknowledged)
2790 {
2791  uint64_t v;
2792 
2793  if ((strcmp(acknowledged, libssl_defects[0].id) != 0) && (strcmp(acknowledged, "yes") != 0)) {
2794  bool bad = false;
2795  size_t i;
2796 
2797  /* Check for bad versions */
2798  v = (uint64_t) SSLeay();
2799 
2800  for (i = 0; i < (sizeof(libssl_defects) / sizeof(*libssl_defects)); i++) {
2801  libssl_defect_t *defect = &libssl_defects[i];
2802 
2803  if ((v >= defect->low) && (v <= defect->high)) {
2804  ERROR("Refusing to start with libssl version %s (in range %s)",
2805  ssl_version(), ssl_version_range(defect->low, defect->high));
2806  ERROR("Security advisory %s (%s)", defect->id, defect->name);
2807  ERROR("%s", defect->comment);
2808 
2809  bad = true;
2810  }
2811  }
2812 
2813  if (bad) {
2814  INFO("Once you have verified libssl has been correctly patched, "
2815  "set security.allow_vulnerable_openssl = '%s'", libssl_defects[0].id);
2816  return -1;
2817  }
2818  }
2819 
2820  return 0;
2821 }
2822 #endif
2823 
2824 #ifdef __APPLE__
2825 /** Use certadmin to retrieve the password for the private key
2826  *
2827  */
2828 static int tls_certadmin_password(fr_tls_server_conf_t *conf)
2829 {
2830  if (!conf->private_key_password) return 0;
2831 
2832  /*
2833  * Set the password to load private key
2834  */
2835 
2836  /*
2837  * We don't want to put the private key password in eap.conf, so check
2838  * for our special string which indicates we should get the password
2839  * programmatically.
2840  */
2841  char const* special_string = "Apple:UseCertAdmin";
2842  if (strncmp(conf->private_key_password, special_string, strlen(special_string)) == 0) {
2843  char cmd[256];
2844  char *password;
2845  long const max_password_len = 128;
2846  snprintf(cmd, sizeof(cmd) - 1, "/usr/sbin/certadmin --get-private-key-passphrase \"%s\"",
2847  conf->private_key_file);
2848 
2849  DEBUG2(LOG_PREFIX ": Getting private key passphrase using command \"%s\"", cmd);
2850 
2851  FILE* cmd_pipe = popen(cmd, "r");
2852  if (!cmd_pipe) {
2853  ERROR(LOG_PREFIX ": %s command failed: Unable to get private_key_password", cmd);
2854  ERROR(LOG_PREFIX ": Error reading private_key_file %s", conf->private_key_file);
2855  return -1;
2856  }
2857 
2858  rad_const_free(conf->private_key_password);
2859  password = talloc_array(conf, char, max_password_len);
2860  if (!password) {
2861  ERROR(LOG_PREFIX ": Can't allocate space for private_key_password");
2862  ERROR(LOG_PREFIX ": Error reading private_key_file %s", conf->private_key_file);
2863  pclose(cmd_pipe);
2864  return -1;
2865  }
2866 
2867  fgets(password, max_password_len, cmd_pipe);
2868  pclose(cmd_pipe);
2869 
2870  /* Get rid of newline at end of password. */
2871  password[strlen(password) - 1] = '\0';
2872 
2873  DEBUG3(LOG_PREFIX ": Password from command = \"%s\"", password);
2874  conf->private_key_password = password;
2875  }
2876 
2877  return 0;
2878 }
2879 #endif
2880 
2881 /** Create SSL context
2882  *
2883  * - Load the trusted CAs
2884  * - Load the Private key & the certificate
2885  * - Set the Context options & Verify options
2886  */
2887 SSL_CTX *tls_init_ctx(fr_tls_server_conf_t const *conf, bool client)
2888 {
2889  SSL_CTX *ctx;
2890  X509_STORE *cert_vpstore;
2891  int verify_mode = SSL_VERIFY_NONE;
2892  int ctx_options = 0;
2893  int ctx_tls_versions = 0;
2894  int type;
2895  void *app_data_index;
2896 
2897  ctx = SSL_CTX_new(SSLv23_method()); /* which is really "all known SSL / TLS methods". Idiots. */
2898  if (!ctx) {
2899  int err;
2900  while ((err = ERR_get_error())) {
2901  ERROR(LOG_PREFIX ": Failed creating TLS context: %s", ERR_error_string(err, NULL));
2902  return NULL;
2903  }
2904  }
2905 
2906  /*
2907  * Save the config on the context so that callbacks which
2908  * only get SSL_CTX* e.g. session persistence, can get it
2909  */
2910  memcpy(&app_data_index, &conf, sizeof(app_data_index));
2911  SSL_CTX_set_app_data(ctx, app_data_index);
2912 
2913  /*
2914  * Identify the type of certificates that needs to be loaded
2915  */
2916  if (conf->file_type) {
2917  type = SSL_FILETYPE_PEM;
2918  } else {
2919  type = SSL_FILETYPE_ASN1;
2920  }
2921 
2922  /*
2923  * Set the private key password (this should have been retrieved earlier)
2924  */
2925  {
2926  char *password;
2927 
2928  memcpy(&password, &conf->private_key_password, sizeof(password));
2929  SSL_CTX_set_default_passwd_cb_userdata(ctx, password);
2930  SSL_CTX_set_default_passwd_cb(ctx, cbtls_password);
2931  }
2932 
2933 #ifdef PSK_MAX_IDENTITY_LEN
2934  if (!client) {
2935  /*
2936  * No dynamic query exists. There MUST be a
2937  * statically configured identity and password.
2938  */
2939  if (conf->psk_query && !*conf->psk_query) {
2940  ERROR(LOG_PREFIX ": Invalid PSK Configuration: psk_query cannot be empty");
2941  return NULL;
2942  }
2943 
2944  /*
2945  * Set the callback only if we can check things.
2946  */
2947  if (conf->psk_identity || conf->psk_query) {
2948  SSL_CTX_set_psk_server_callback(ctx, tls_psk_server_cb);
2949  }
2950 
2951  } else if (conf->psk_query) {
2952  ERROR(LOG_PREFIX ": Invalid PSK Configuration: psk_query cannot be used for outgoing connections");
2953  return NULL;
2954  }
2955 
2956  /*
2957  * Now check that if PSK is being used, the config is valid.
2958  */
2959  if ((conf->psk_identity && !conf->psk_password) ||
2960  (!conf->psk_identity && conf->psk_password) ||
2961  (conf->psk_identity && !*conf->psk_identity) ||
2962  (conf->psk_password && !*conf->psk_password)) {
2963  ERROR(LOG_PREFIX ": Invalid PSK Configuration: psk_identity or psk_password are empty");
2964  return NULL;
2965  }
2966 
2967  if (conf->psk_identity) {
2968  size_t psk_len, hex_len;
2969  uint8_t buffer[PSK_MAX_PSK_LEN];
2970 
2971  if (conf->certificate_file ||
2972  conf->private_key_password || conf->private_key_file ||
2973  conf->ca_file || conf->ca_path) {
2974  ERROR(LOG_PREFIX ": When PSKs are used, No certificate configuration is permitted");
2975  return NULL;
2976  }
2977 
2978  if (client) {
2979  SSL_CTX_set_psk_client_callback(ctx, tls_psk_client_cb);
2980  }
2981 
2982  psk_len = strlen(conf->psk_password);
2983  if (strlen(conf->psk_password) > (2 * PSK_MAX_PSK_LEN)) {
2984  ERROR(LOG_PREFIX ": psk_hexphrase is too long (max %d)", PSK_MAX_PSK_LEN);
2985  return NULL;
2986  }
2987 
2988  /*
2989  * Check the password now, so that we don't have
2990  * errors at run-time.
2991  */
2992  hex_len = fr_hex2bin(buffer, sizeof(buffer), conf->psk_password, psk_len);
2993  if (psk_len != (2 * hex_len)) {
2994  ERROR(LOG_PREFIX ": psk_hexphrase is not all hex");
2995  return NULL;
2996  }
2997 
2998  goto post_ca;
2999  }
3000 #else
3001  (void) client; /* -Wunused */
3002 #endif
3003 
3004  /*
3005  * Load our keys and certificates
3006  *
3007  * If certificates are of type PEM then we can make use
3008  * of cert chain authentication using openssl api call
3009  * SSL_CTX_use_certificate_chain_file. Please see how
3010  * the cert chain needs to be given in PEM from
3011  * openSSL.org
3012  */
3013  if (!conf->certificate_file) goto load_ca;
3014 
3015  if (type == SSL_FILETYPE_PEM) {
3016  if (!(SSL_CTX_use_certificate_chain_file(ctx, conf->certificate_file))) {
3017  ERROR(LOG_PREFIX ": Error reading certificate file %s:%s", conf->certificate_file,
3018  ERR_error_string(ERR_get_error(), NULL));
3019  return NULL;
3020  }
3021 
3022  } else if (!(SSL_CTX_use_certificate_file(ctx, conf->certificate_file, type))) {
3023  ERROR(LOG_PREFIX ": Error reading certificate file %s:%s",
3024  conf->certificate_file,
3025  ERR_error_string(ERR_get_error(), NULL));
3026  return NULL;
3027  }
3028 
3029  /* Load the CAs we trust */
3030 load_ca:
3031  if (conf->ca_file || conf->ca_path) {
3032  if (!SSL_CTX_load_verify_locations(ctx, conf->ca_file, conf->ca_path)) {
3033  ERROR(LOG_PREFIX ": TLS error: %s", ERR_error_string(ERR_get_error(), NULL));
3034  ERROR(LOG_PREFIX ": Error reading Trusted root CA list %s",conf->ca_file );
3035  return NULL;
3036  }
3037  }
3038  if (conf->ca_file && *conf->ca_file) SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(conf->ca_file));
3039 
3040  if (conf->private_key_file) {
3041  if (!(SSL_CTX_use_PrivateKey_file(ctx, conf->private_key_file, type))) {
3042  ERROR(LOG_PREFIX ": Failed reading private key file %s:%s",
3043  conf->private_key_file,
3044  ERR_error_string(ERR_get_error(), NULL));
3045  return NULL;
3046  }
3047 
3048  /*
3049  * Check if the loaded private key is the right one
3050  */
3051  if (!SSL_CTX_check_private_key(ctx)) {
3052  ERROR(LOG_PREFIX ": Private key does not match the certificate public key");
3053  return NULL;
3054  }
3055  }
3056 
3057 #ifdef PSK_MAX_IDENTITY_LEN
3058 post_ca:
3059 #endif
3060 
3061  /*
3062  * We never want SSLv2 or SSLv3.
3063  */
3064  ctx_options |= SSL_OP_NO_SSLv2;
3065  ctx_options |= SSL_OP_NO_SSLv3;
3066 
3067  /*
3068  * As of 3.0.5, we always allow TLSv1.1 and TLSv1.2.
3069  * Though they can be *globally* disabled if necessary.x
3070  */
3071 #ifdef SSL_OP_NO_TLSv1
3072  if (conf->disable_tlsv1) ctx_options |= SSL_OP_NO_TLSv1;
3073 
3074  ctx_tls_versions |= SSL_OP_NO_TLSv1;
3075 #endif
3076 #ifdef SSL_OP_NO_TLSv1_1
3077  if (conf->disable_tlsv1_1) ctx_options |= SSL_OP_NO_TLSv1_1;
3078 
3079  ctx_tls_versions |= SSL_OP_NO_TLSv1_1;
3080 #endif
3081 #ifdef SSL_OP_NO_TLSv1_2
3082  if (conf->disable_tlsv1_2) ctx_options |= SSL_OP_NO_TLSv1_2;
3083 
3084  ctx_tls_versions |= SSL_OP_NO_TLSv1_2;
3085 #endif
3086 
3087  if ((ctx_options & ctx_tls_versions) == ctx_tls_versions) {
3088  ERROR(LOG_PREFIX ": You have disabled all available TLS versions. EAP will not work");
3089  return NULL;
3090  }
3091 
3092 #ifdef SSL_OP_NO_TICKET
3093  ctx_options |= SSL_OP_NO_TICKET;
3094 #endif
3095 
3096  if (!conf->disable_single_dh_use) {
3097  /*
3098  * SSL_OP_SINGLE_DH_USE must be used in order to prevent
3099  * small subgroup attacks and forward secrecy. Always
3100  * using SSL_OP_SINGLE_DH_USE has an impact on the
3101  * computer time needed during negotiation, but it is not
3102  * very large.
3103  */
3104  ctx_options |= SSL_OP_SINGLE_DH_USE;
3105  }
3106 
3107  /*
3108  * SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS to work around issues
3109  * in Windows Vista client.
3110  * http://www.openssl.org/~bodo/tls-cbc.txt
3111  * http://www.nabble.com/(RADIATOR)-Radiator-Version-3.16-released-t2600070.html
3112  */
3113  ctx_options |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
3114 
3115  SSL_CTX_set_options(ctx, ctx_options);
3116 
3117  /*
3118  * TODO: Set the RSA & DH
3119  * SSL_CTX_set_tmp_rsa_callback(ctx, cbtls_rsa);
3120  * SSL_CTX_set_tmp_dh_callback(ctx, cbtls_dh);
3121  */
3122 
3123  /*
3124  * set the message callback to identify the type of
3125  * message. For every new session, there can be a
3126  * different callback argument.
3127  *
3128  * SSL_CTX_set_msg_callback(ctx, cbtls_msg);
3129  */
3130 
3131  /*
3132  * Set eliptical curve crypto configuration.
3133  */
3134 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
3135 #ifndef OPENSSL_NO_ECDH
3136  if (set_ecdh_curve(ctx, conf->ecdh_curve, conf->disable_single_dh_use) < 0) {
3137  return NULL;
3138  }
3139 #endif
3140 #endif
3141 
3142  /*
3143  * OpenSSL will automatically create certificate chains,
3144  * unless we tell it to not do that. The problem is that
3145  * it sometimes gets the chains right from a certificate
3146  * signature view, but wrong from the clients view.
3147  */
3148  if (!conf->auto_chain) {
3149  SSL_CTX_set_mode(ctx, SSL_MODE_NO_AUTO_CHAIN);
3150  }
3151 
3152  /* Set Info callback */
3153  SSL_CTX_set_info_callback(ctx, cbtls_info);
3154 
3155  /*
3156  * Callbacks, etc. for session resumption.
3157  */
3158  if (conf->session_cache_enable) {
3159  if (conf->session_cache_server) {
3160  SSL_CTX_sess_set_new_cb(ctx, cache_write_session);
3161  SSL_CTX_sess_set_get_cb(ctx, cache_read_session);
3162  SSL_CTX_sess_set_remove_cb(ctx, cache_delete_session);
3163  }
3164 
3165  SSL_CTX_set_quiet_shutdown(ctx, 1);
3166  }
3167 
3168  /*
3169  * Check the certificates for revocation.
3170  */
3171 #ifdef X509_V_FLAG_CRL_CHECK
3172  if (conf->check_crl) {
3173  cert_vpstore = SSL_CTX_get_cert_store(ctx);
3174  if (cert_vpstore == NULL) {
3175  ERROR(LOG_PREFIX ": SSL error %s", ERR_error_string(ERR_get_error(), NULL));
3176  ERROR(LOG_PREFIX ": Error reading Certificate Store");
3177  return NULL;
3178  }
3179  X509_STORE_set_flags(cert_vpstore, X509_V_FLAG_CRL_CHECK);
3180 
3181 #ifdef X509_V_FLAG_CRL_CHECK_ALL
3182  if (conf->check_all_crl)
3183  X509_STORE_set_flags(cert_vpstore, X509_V_FLAG_CRL_CHECK_ALL);
3184 #endif
3185  }
3186 #endif
3187 
3188  /*
3189  * Set verify modes
3190  * Always verify the peer certificate
3191  */
3192  verify_mode |= SSL_VERIFY_PEER;
3193  verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
3194  verify_mode |= SSL_VERIFY_CLIENT_ONCE;
3195  SSL_CTX_set_verify(ctx, verify_mode, cbtls_verify);
3196 
3197  if (conf->verify_depth) {
3198  SSL_CTX_set_verify_depth(ctx, conf->verify_depth);
3199  }
3200 
3201  /* Load randomness */
3202  if (conf->random_file) {
3203  if (!(RAND_load_file(conf->random_file, 1024*10))) {
3204  ERROR(LOG_PREFIX ": SSL error %s", ERR_error_string(ERR_get_error(), NULL));
3205  ERROR(LOG_PREFIX ": Error loading randomness");
3206  return NULL;
3207  }
3208  }
3209 
3210  /*
3211  * Set the cipher list if we were told to
3212  */
3213  if (conf->cipher_list) {
3214  if (!SSL_CTX_set_cipher_list(ctx, conf->cipher_list)) {
3215  ERROR(LOG_PREFIX ": Error setting cipher list");
3216  return NULL;
3217  }
3218  }
3219 
3220  /*
3221  * Setup session caching
3222  */
3223  if (conf->session_cache_enable) {
3224  /*
3225  * If a virtual server is caching the TLS
3226  * sessions, then don't use the internal cache.
3227  */
3228  if (conf->session_cache_server) {
3229  SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER | SSL_SESS_CACHE_NO_INTERNAL);
3230 
3231  } else { /* in-memory cache. */
3232  /*
3233  * Cache it, and DON'T auto-clear it.
3234  */
3235  SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER | SSL_SESS_CACHE_NO_AUTO_CLEAR);
3236 
3237  /*
3238  * Our timeout is in hours, this is in seconds.
3239  */
3240  SSL_CTX_set_timeout(ctx, conf->session_timeout * 3600);
3241 
3242  /*
3243  * Set the maximum number of entries in the
3244  * session cache.
3245  */
3246  SSL_CTX_sess_set_cache_size(ctx, conf->session_cache_size);
3247  }
3248 
3249  /*
3250  * This sets the context sessions can be resumed in.
3251  * This is to prevent sessions being created by one application
3252  * and used by another. In our case it prevents sessions being
3253  * reused between modules, or TLS server components such as
3254  * RADSEC.
3255  *
3256  * A context must always be set when doing session resumption
3257  * otherwise session resumption will fail.
3258  */
3259  SSL_CTX_set_session_id_context(ctx,
3260  (unsigned char const *) conf->session_context_id,
3261  (unsigned int) strlen(conf->session_context_id));
3262  } else {
3263  SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);
3264  }
3265 
3266  /*
3267  * Load dh params
3268  */
3269  if (conf->dh_file) {
3270  char *dh_file;
3271 
3272  memcpy(&dh_file, &conf->dh_file, sizeof(dh_file));
3273  if (load_dh_params(ctx, dh_file) < 0) return NULL;
3274  }
3275 
3276  return ctx;
3277 }
3278 
3279 
3280 /*
3281  * Free TLS client/server config
3282  * Should not be called outside this code, as a callback is
3283  * added to automatically free the data when the CONF_SECTION
3284  * is freed.
3285  */
3286 static int _tls_server_conf_free(fr_tls_server_conf_t *conf)
3287 {
3288  uint32_t i;
3289 
3290  for (i = 0; i < conf->ctx_count; i++) SSL_CTX_free(conf->ctx[i]);
3291 
3292 #ifdef HAVE_OPENSSL_OCSP_H
3293  if (conf->ocsp_store) X509_STORE_free(conf->ocsp_store);
3294  conf->ocsp_store = NULL;
3295 #endif
3296 
3297 #ifndef NDEBUG
3298  memset(conf, 0, sizeof(*conf));
3299 #endif
3300  return 0;
3301 }
3302 
3303 static fr_tls_server_conf_t *tls_server_conf_alloc(TALLOC_CTX *ctx)
3304 {
3305  fr_tls_server_conf_t *conf;
3306 
3307  conf = talloc_zero(ctx, fr_tls_server_conf_t);
3308  if (!conf) {
3309  ERROR(LOG_PREFIX ": Out of memory");
3310  return NULL;
3311  }
3312 
3313  talloc_set_destructor(conf, _tls_server_conf_free);
3314 
3315  return conf;
3316 }
3317 
3318 fr_tls_server_conf_t *tls_server_conf_parse(CONF_SECTION *cs)
3319 {
3320  fr_tls_server_conf_t *conf;
3321  uint32_t i;
3322 
3323  /*
3324  * If cs has already been parsed there should be a cached copy
3325  * of conf already stored, so just return that.
3326  */
3327  conf = cf_data_find(cs, "tls-conf");
3328  if (conf) {
3329  DEBUG(LOG_PREFIX ": Using cached TLS configuration from previous invocation");
3330  return conf;
3331  }
3332 
3333  conf = tls_server_conf_alloc(cs);
3334 
3335  if (cf_section_parse(cs, conf, tls_server_config) < 0) {
3336  error:
3337  talloc_free(conf);
3338  return NULL;
3339  }
3340 
3341  /*
3342  * Save people from their own stupidity.
3343  */
3344  if (conf->fragment_size < 100) conf->fragment_size = 100;
3345 
3346  if (!conf->private_key_file) {
3347  ERROR(LOG_PREFIX ": TLS Server requires a private key file");
3348  goto error;
3349  }
3350 
3351  if (!conf->certificate_file) {
3352  ERROR(LOG_PREFIX ": TLS Server requires a certificate file");
3353  goto error;
3354  }
3355 
3356  /*
3357  * Setup session caching
3358  */
3359  if (conf->session_cache_enable && conf->session_cache_server) {
3360  /*
3361  * Create a unique context Id per EAP-TLS configuration.
3362  */
3363  if (conf->session_id_name) {
3364  snprintf(conf->session_context_id, sizeof(conf->session_context_id),
3365  "FR eap %s", conf->session_id_name);
3366  } else {
3367  snprintf(conf->session_context_id, sizeof(conf->session_context_id),
3368  "FR eap %p", conf);
3369  }
3370  }
3371 
3372 #ifdef __APPLE__
3373  if (tls_certadmin_password(conf) < 0) goto error;
3374 #endif
3375 
3376  if (!main_config.spawn_workers) {
3377  conf->ctx_count = 1;
3378  } else {
3379  conf->ctx_count = thread_pool_max_threads() * 2; /* Reduce contention */
3380  rad_assert(conf->ctx_count > 0);
3381  }
3382 
3383  /*
3384  * Initialize TLS
3385  */
3386  conf->ctx = talloc_array(conf, SSL_CTX *, conf->ctx_count);
3387  for (i = 0; i < conf->ctx_count; i++) {
3388  conf->ctx[i] = tls_init_ctx(conf, false);
3389  if (conf->ctx == NULL) goto error;
3390  }
3391 
3392 #ifdef HAVE_OPENSSL_OCSP_H
3393  /*
3394  * Initialize OCSP Revocation Store
3395  */
3396  if (conf->ocsp_enable) {
3397  conf->ocsp_store = init_revocation_store(conf);
3398  if (conf->ocsp_store == NULL) goto error;
3399  }
3400 #endif /*HAVE_OPENSSL_OCSP_H*/
3401 
3402  if (conf->verify_tmp_dir) {
3403  if (chmod(conf->verify_tmp_dir, S_IRWXU) < 0) {
3404  ERROR(LOG_PREFIX ": Failed changing permissions on %s: %s",
3405  conf->verify_tmp_dir, fr_syserror(errno));
3406  goto error;
3407  }
3408  }
3409 
3410  if (conf->verify_client_cert_cmd && !conf->verify_tmp_dir) {
3411  ERROR(LOG_PREFIX ": You MUST set the verify directory in order to use verify_client_cmd");
3412  goto error;
3413  }
3414 
3415  if (conf->session_cache_server &&
3416  !cf_section_sub_find_name2(main_config.config, "server", conf->session_cache_server)) {
3417  ERROR(LOG_PREFIX ": No such virtual server '%s'", conf->session_cache_server);
3418  goto error;
3419  }
3420 
3421  if (conf->ocsp_cache_server &&
3422  !cf_section_sub_find_name2(main_config.config, "server", conf->ocsp_cache_server)) {
3423  ERROR(LOG_PREFIX ": No such virtual server '%s'", conf->ocsp_cache_server);
3424  goto error;
3425  }
3426 
3427  /*
3428  * Cache conf in cs in case we're asked to parse this again.
3429  */
3430  cf_data_add(cs, "tls-conf", conf, NULL);
3431 
3432  return conf;
3433 }
3434 
3435 fr_tls_server_conf_t *tls_client_conf_parse(CONF_SECTION *cs)
3436 {
3437  fr_tls_server_conf_t *conf;
3438  uint32_t i;
3439 
3440  conf = cf_data_find(cs, "tls-conf");
3441  if (conf) {
3442  DEBUG2(LOG_PREFIX ": Using cached TLS configuration from previous invocation");
3443  return conf;
3444  }
3445 
3446  conf = tls_server_conf_alloc(cs);
3447 
3448  if (cf_section_parse(cs, conf, tls_client_config) < 0) {
3449  error:
3450  talloc_free(conf);
3451  return NULL;
3452  }
3453 
3454  /*
3455  * Save people from their own stupidity.
3456  */
3457  if (conf->fragment_size < 100) conf->fragment_size = 100;
3458 
3459  /*
3460  * Initialize TLS
3461  */
3462  if (!main_config.spawn_workers) {
3463  conf->ctx_count = 1;
3464  } else {
3465  conf->ctx_count = thread_pool_max_threads() * 2; /* Even one context per thread will lead to contention */
3466  rad_assert(conf->ctx_count > 0);
3467  }
3468 
3469 #ifdef __APPLE__
3470  if (tls_certadmin_password(conf) < 0) goto error;
3471 #endif
3472 
3473  conf->ctx = talloc_array(conf, SSL_CTX *, conf->ctx_count);
3474  for (i = 0; i < conf->ctx_count; i++) {
3475  conf->ctx[i] = tls_init_ctx(conf, true);
3476  if (conf->ctx[i] == NULL) goto error;
3477  }
3478 
3479  cf_data_add(cs, "tls-conf", conf, NULL);
3480 
3481  return conf;
3482 }
3483 
3484 /** Sets up TLS session so that it can later be resumed
3485  *
3486  */
3487 int tls_success(tls_session_t *session, REQUEST *request)
3488 {
3489  VALUE_PAIR *vp;
3490  fr_tls_server_conf_t *conf;
3491 
3492  conf = (fr_tls_server_conf_t *)SSL_get_ex_data(session->ssl, FR_TLS_EX_INDEX_CONF);
3493 #ifndef NDEBUG
3494  rad_assert(conf != NULL);
3495 #else
3496  if (!conf) {
3497  REDEBUG("Failed retrieving TLS configuration from SSL session");
3498  return -1;
3499  }
3500 #endif
3501  /*
3502  * If there's no session resumption, delete the entry
3503  * from the cache. This means either it's disabled
3504  * globally for this SSL context, OR we were told to
3505  * disable it for this user.
3506  *
3507  * This also means you can't turn it on just for one
3508  * user.
3509  */
3510  if ((!session->allow_session_resumption) ||
3511  (((vp = fr_pair_find_by_num(request->config, 0, PW_ALLOW_SESSION_RESUMPTION, TAG_ANY)) != NULL) &&
3512  (vp->vp_integer == 0))) {
3513  SSL_CTX_remove_session(session->ctx, session->ssl->session);
3514  session->allow_session_resumption = false;
3515 
3516  /*
3517  * If we're in a resumed session and it's
3518  * not allowed,
3519  */
3520  if (SSL_session_reused(session->ssl)) {
3521  REDEBUG("Forcibly stopping session resumption as it is not allowed");
3522  return -1;
3523  }
3524 
3525  /*
3526  * Else resumption IS allowed, so we store the
3527  * user data in the cache.
3528  */
3529  } else if (SSL_session_reused(session->ssl)) {
3530  /*
3531  * Mark the request as resumed.
3532  */
3533  pair_make_request("EAP-Session-Resumed", "1", T_OP_SET);
3534  }
3535 
3536  return 0;
3537 }
3538 
3539 
3540 void tls_fail(tls_session_t *session)
3541 {
3542  /*
3543  * Force the session to NOT be cached.
3544  */
3545  SSL_CTX_remove_session(session->ctx, session->ssl->session);
3546 }
3547 
3548 fr_tls_status_t tls_application_data(tls_session_t *session, REQUEST *request)
3549 {
3550  int err;
3551 
3552  /*
3553  * Decrypt the complete record.
3554  */
3555  err = BIO_write(session->into_ssl, session->dirty_in.data, session->dirty_in.used);
3556  if (err != (int) session->dirty_in.used) {
3557  record_init(&session->dirty_in);
3558  RDEBUG("Failed writing %zd bytes to SSL BIO: %d", session->dirty_in.used, err);
3559  return FR_TLS_FAIL;
3560  }
3561 
3562  /*
3563  * Clear the dirty buffer now that we are done with it
3564  * and init the clean_out buffer to store decrypted data
3565  */
3566  record_init(&session->dirty_in);
3567  record_init(&session->clean_out);
3568 
3569  /*
3570  * Read (and decrypt) the tunneled data from the
3571  * SSL session, and put it into the decrypted
3572  * data buffer.
3573  */
3574  err = SSL_read(session->ssl, session->clean_out.data, sizeof(session->clean_out.data));
3575  if (err < 0) {
3576  int code;
3577 
3578  code = SSL_get_error(session->ssl, err);
3579  switch (code) {
3580  case SSL_ERROR_WANT_READ:
3581  RWDEBUG("Peer indicated record was complete, but OpenSSL returned SSL_WANT_READ. "
3582  "Attempting to continue");
3583  return FR_TLS_RECORD_FRAGMENT_MORE;
3584 
3585  case SSL_ERROR_WANT_WRITE:
3586  DEBUG("Error in fragmentation logic: SSL_WANT_WRITE");
3587  break;
3588 
3589  default:
3590  DEBUG("Error in fragmentation logic: %s", ERR_error_string(code, NULL));
3591 
3592  /*
3593  * FIXME: Call tls_error_log?
3594  */
3595  break;
3596  }
3597  return FR_TLS_FAIL;
3598  }
3599 
3600  if (err == 0) RWDEBUG("No data inside of the tunnel");
3601 
3602  /*
3603  * Passed all checks, successfully decrypted data
3604  */
3605  session->clean_out.used = err;
3606 
3607  return FR_TLS_RECORD_COMPLETE;
3608 }
3609 
3610 
3611 /*
3612  * Acknowledge received is for one of the following messages sent earlier
3613  * 1. Handshake completed Message, so now send, EAP-Success
3614  * 2. Alert Message, now send, EAP-Failure
3615  * 3. Fragment Message, now send, next Fragment
3616  */
3617 fr_tls_status_t tls_ack_handler(tls_session_t *session, REQUEST *request)
3618 {
3619  if (session == NULL){
3620  REDEBUG("Unexpected ACK received: No ongoing SSL session");
3621  return FR_TLS_INVALID;
3622  }
3623  if (!session->info.initialized) {
3624  RDEBUG("No SSL info available. Waiting for more SSL data");
3625  return FR_TLS_REQUEST;
3626  }
3627 
3628  if ((session->info.content_type == handshake) && (session->info.origin == 0)) {
3629  REDEBUG("Unexpected ACK received: We sent no previous messages");
3630  return FR_TLS_INVALID;
3631  }
3632 
3633  switch (session->info.content_type) {
3634  case alert:
3635  RDEBUG2("Peer ACKed our alert");
3636  return FR_TLS_FAIL;
3637 
3638  case handshake:
3639  if ((session->info.handshake_type == handshake_finished) && (session->dirty_out.used == 0)) {
3640  RDEBUG2("Peer ACKed our handshake fragment. handshake is finished");
3641 
3642  /*
3643  * From now on all the content is
3644  * application data set it here as nobody else
3645  * sets it.
3646  */
3647  session->info.content_type = application_data;
3648  return FR_TLS_SUCCESS;
3649  } /* else more data to send */
3650 
3651  RDEBUG2("Peer ACKed our handshake fragment");
3652  /* Fragmentation handler, send next fragment */
3653  return FR_TLS_REQUEST;
3654 
3655  case application_data:
3656  RDEBUG2("Peer ACKed our application data fragment");
3657  return FR_TLS_REQUEST;
3658 
3659  /*
3660  * For the rest of the conditions, switch over
3661  * to the default section below.
3662  */
3663  default:
3664  REDEBUG("Invalid ACK received: %d", session->info.content_type);
3665  return FR_TLS_INVALID;
3666  }
3667 }
3668 #endif /* WITH_TLS */
void fr_pair_list_free(VALUE_PAIR **)
Free memory used by a valuepair list.
Definition: pair.c:544
#define PW_TYPE_FILE_INPUT
File matching value must exist, and must be readable.
Definition: conffile.h:204
int radius_exec_program(TALLOC_CTX *ctx, char *out, size_t outlen, VALUE_PAIR **output_pairs, REQUEST *request, char const *cmd, VALUE_PAIR *input_pairs, bool exec_wait, bool shell_escape, int timeout) CC_HINT(nonnull(5
2nd highest priority debug messages (-xx | -X).
Definition: log.h:52
VALUE_PAIR * config
VALUE_PAIR (s) used to set per request parameters for modules and the server core at runtime...
Definition: radiusd.h:227
#define RINDENT()
Indent R* messages by one level.
Definition: log.h:265
#define DEBUG3(fmt,...)
Definition: log.h:177
#define RERROR(fmt,...)
Definition: log.h:207
rlm_rcode_t process_authorize(int type, REQUEST *request)
Definition: modules.c:2098
#define AUTH(fmt,...)
Definition: log.h:139
#define RDEBUG_ENABLED3
True if request debug level 1-3 messages are enabled.
Definition: log.h:239
Main server configuration.
Definition: radiusd.h:108
void rdebug_pair(log_lvl_t level, REQUEST *, VALUE_PAIR *, char const *)
Print a single valuepair to stderr or error log.
Definition: pair.c:739
The module is OK, continue.
Definition: radiusd.h:91
VALUE_PAIR * fr_pair_afrom_num(TALLOC_CTX *ctx, unsigned int vendor, unsigned int attr)
Create a new valuepair.
Definition: pair.c:106
void fr_pair_list_mcopy_by_num(TALLOC_CTX *ctx, VALUE_PAIR **to, VALUE_PAIR **from, unsigned int vendor, unsigned int attr, int8_t tag)
Copy / delete matching pairs between VALUE_PAIR lists.
Definition: pair.c:1823
#define RWARN(fmt,...)
Definition: log.h:206
uint32_t thread_pool_max_threads(void)
#define INFO(fmt,...)
Definition: log.h:143
static char const * name
#define LOG_PREFIX
Definition: eap.h:37
#define RDEBUG_ENABLED
True if request debug level 1 messages are enabled.
Definition: log.h:237
#define UNUSED
Definition: libradius.h:134
VALUE_PAIR * vps
Result of decoding the packet into VALUE_PAIRs.
Definition: libradius.h:162
#define CONF_PARSER_TERMINATOR
Definition: conffile.h:289
#define pair_make_request(_a, _b, _c)
Definition: radiusd.h:545
VALUE_PAIR * fr_cursor_init(vp_cursor_t *cursor, VALUE_PAIR *const *node)
Setup a cursor to iterate over attribute pairs.
Definition: cursor.c:60
PUBLIC int snprintf(char *string, size_t length, char *format, va_alist)
Definition: snprintf.c:686
#define PW_TYPE_SECRET
Only print value if debug level >= 3.
Definition: conffile.h:202
#define PW_TYPE_DEPRECATED
If a matching CONF_PAIR is found, error out with a deprecated message.
Definition: conffile.h:199
char const * name
Name of the daemon, usually 'radiusd'.
Definition: radiusd.h:109
#define PW_TYPE_SUBSECTION
Definition: conffile.h:188
Defines a CONF_PAIR to C data type mapping.
Definition: conffile.h:267
Abstraction to allow iterating over different configurations of VALUE_PAIRs.
Definition: pair.h:144
#define rad_assert(expr)
Definition: rad_assert.h:38
char const * fr_syserror(int num)
Guaranteed to be thread-safe version of strerror.
Definition: log.c:238
#define pthread_mutex_unlock(_x)
Definition: rlm_eap.h:78
#define DEBUG(fmt,...)
Definition: log.h:175
char const * ssl_version_range(uint32_t low, uint32_t high)
char const * component
Section the request is in.
Definition: radiusd.h:254
void fr_cursor_insert(vp_cursor_t *cursor, VALUE_PAIR *vp)
Insert a single VALUE_PAIR at the end of the list.
Definition: cursor.c:321
void fr_pair_add(VALUE_PAIR **head, VALUE_PAIR *vp)
Add a VP to the end of the list.
Definition: pair.c:659
size_t fr_hex2bin(uint8_t *bin, size_t outlen, char const *hex, size_t inlen)
Convert hex strings to binary data.
Definition: misc.c:220
#define DEBUG2(fmt,...)
Definition: log.h:176
RADIUS_PACKET * fr_radius_alloc(TALLOC_CTX *ctx, bool new_vector)
Allocate a new RADIUS_PACKET.
Definition: radius.c:1651
int cf_section_parse(CONF_SECTION *, void *base, CONF_PARSER const *variables)
Parse a configuration section into user-supplied variables.
Definition: conffile.c:2234
Immediately reject the request.
Definition: radiusd.h:89
TALLOC_CTX * state_ctx
for request->state
Definition: radiusd.h:230
Definition: token.h:43
#define ROPTIONAL(_l_request, _l_global, fmt,...)
Use different logging functions depending on whether request is NULL or not.
Definition: log.h:357
Stores an attribute, a value and various bits of other data.
Definition: pair.h:112
void rad_const_free(void const *ptr)
Definition: util.c:424
RADIUS_PACKET * reply
Outgoing response.
Definition: radiusd.h:225
int cf_data_add(CONF_SECTION *, char const *, void *, void(*)(void *))
Definition: conffile.c:4018
#define REXDENT()
Exdent (unindent) R* messages by one level.
Definition: log.h:272
A truth value.
Definition: radius.h:56
#define FR_CONF_DEPRECATED(_n, _t, _p, _f)
Definition: conffile.h:179
Definition: token.h:45
32 Bit unsigned integer.
Definition: radius.h:34
enum rlm_rcodes rlm_rcode_t
Return codes indicating the result of the module call.
ssize_t radius_xlat(char *out, size_t outlen, REQUEST *request, char const *fmt, xlat_escape_t escape, void *escape_ctx) CC_HINT(nonnull(1
static rs_t * conf
Definition: radsniff.c:46
void rdebug_pair_list(log_lvl_t level, REQUEST *, VALUE_PAIR *, char const *)
Print a list of VALUE_PAIRs.
Definition: pair.c:757
void fr_pair_delete_by_num(VALUE_PAIR **head, unsigned int vendor, unsigned int attr, int8_t tag)
Delete matching pairs.
Definition: pair.c:797
char identity[]
Definition: eap_pwd.h:630
Module succeeded without doing anything.
Definition: radiusd.h:96
#define RDEBUG2(fmt,...)
Definition: log.h:244
uint8_t data[]
Definition: eap_pwd.h:625
char const * ssl_version(void)
Definition: version.c:193
void fr_pair_value_memsteal(VALUE_PAIR *vp, uint8_t const *src)
Reparent an allocated octet buffer to a VALUE_PAIR.
Definition: pair.c:1933
#define TAG_ANY
Definition: pair.h:191
CONF_SECTION * config
Root of the server config.
Definition: radiusd.h:110
struct timeval timestamp
When we started processing the request.
Definition: radiusd.h:214
#define FR_CONF_OFFSET(_n, _t, _s, _f)
Definition: conffile.h:168
log_lvl_t rad_debug_lvl
Global debugging level.
Definition: log.c:49
VALUE_PAIR * state
VALUE_PAIR (s) available over the lifetime of the authentication attempt.
Definition: radiusd.h:231
RADIUS_PACKET * packet
Incoming request.
Definition: radiusd.h:221
#define WARN(fmt,...)
Definition: log.h:144
#define RATE_LIMIT(_x)
Rate limit messages.
Definition: log.h:380
#define REDEBUG(fmt,...)
Definition: log.h:254
#define EXEC_TIMEOUT
Definition: radiusd.h:329
VALUE_PAIR * fr_pair_find_by_num(VALUE_PAIR *head, unsigned int vendor, unsigned int attr, int8_t tag)
Find the pair with the matching attribute.
Definition: pair.c:639
#define pthread_mutex_lock(_x)
Definition: rlm_eap.h:77
size_t strlcpy(char *dst, char const *src, size_t siz)
Definition: strlcpy.c:38
void * cf_data_find(CONF_SECTION const *, char const *)
Definition: conffile.c:3981
String of printable characters.
Definition: radius.h:33
#define FR_CONF_POINTER(_n, _t, _p)
Definition: conffile.h:172
bool spawn_workers
Should the server spawn threads.
Definition: radiusd.h:122
#define RWDEBUG(fmt,...)
Definition: log.h:251
CONF_SECTION * cf_section_sub_find_name2(CONF_SECTION const *, char const *name1, char const *name2)
Find a CONF_SECTION with both names.
Definition: conffile.c:3728
User not found.
Definition: radiusd.h:95
#define pthread_mutex_destroy(_x)
Definition: rlm_eap.h:76
#define RCSID(id)
Definition: build.h:135
OK (pairs modified).
Definition: radiusd.h:97
char const * module
Module the request is currently being processed by.
Definition: radiusd.h:253
VALUE_PAIR * fr_pair_make(TALLOC_CTX *ctx, VALUE_PAIR **vps, char const *attribute, char const *value, FR_TOKEN op)
Create a VALUE_PAIR from ASCII strings.
Definition: pair.c:338
#define RDEBUG(fmt,...)
Definition: log.h:243
#define ERROR(fmt,...)
Definition: log.h:145
void fr_pair_value_memcpy(VALUE_PAIR *vp, uint8_t const *src, size_t len)
Copy data into an "octets" data type.
Definition: pair.c:1905
REQUEST * request_alloc(TALLOC_CTX *ctx)
Create a new REQUEST data structure.
Definition: request.c:85
char const * server
Definition: radiusd.h:289
#define USES_APPLE_DEPRECATED_API
Definition: build.h:122
#define RDEBUG3(fmt,...)
Definition: log.h:245