The FreeRADIUS server $Id: a4e7f8c94e8038b7627bcf52356b7ed15955c1d7 $
Loading...
Searching...
No Matches
unit_test_tls.c
Go to the documentation of this file.
1/*
2 * This program is free software; you can redistribute it and/or modify
3 * it under the terms of the GNU General Public License as published by
4 * the Free Software Foundation; either version 2 of the License, or
5 * (at your option) any later version.
6 *
7 * This program is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 * GNU General Public License for more details.
11 *
12 * You should have received a copy of the GNU General Public License
13 * along with this program; if not, write to the Free Software
14 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
15 */
16/**
17 * $Id: ca10904a78e3f4268d7eb89e51cb7f0071d3c441 $
18 *
19 * @file unit_test_tls.c
20 * @brief TLS server test framework
21 *
22 * This program loads the "tls" protocol and reads two top-level sections
23 * from unit_test_tls.conf. The "tls" section supplies the TLS server
24 * context, and takes exactly the items that a TLS configuration takes
25 * anywhere else in the server. The "unit_test_tls" section supplies what
26 * steers the test program itself, which is the address of the listening TCP
27 * socket and whether a client certificate is required.
28 *
29 * One connection is accepted, and the TLS handshake for that connection is
30 * run to completion.
31 *
32 * The handshake runs on a persistent asynchronous interpreter, the same way
33 * radiusd runs one. A persistent interpreter keeps the handshake state
34 * across the several rounds of a single connection.
35 *
36 * The "virtual_server" item in the "tls" section names a virtual server.
37 * That virtual server supplies the "verify certificate", "load session",
38 * "store session" and "clear session" sections which the handshake calls.
39 *
40 * To run the test, start unit_test_tls with the test configuration, then
41 * connect to the listening socket:
42 *
43 * @code
44 * ./scripts/bin/unit_test_tls -d src/tests/tls -X
45 *
46 * openssl s_client -connect 127.0.0.1:2083 \
47 * -cert raddb/certs/rsa/client.pem \
48 * -key raddb/certs/rsa/client.key -pass pass:whatever \
49 * -CAfile raddb/certs/rsa/ca.pem
50 * @endcode
51 *
52 * src/tests/tls/unit_test_tls.conf documents every configuration item.
53 *
54 * @copyright 2025 The FreeRADIUS server project
55 */
56RCSID("$Id: ca10904a78e3f4268d7eb89e51cb7f0071d3c441 $")
57
58#include <freeradius-devel/server/base.h>
59#include <freeradius-devel/server/module_rlm.h>
60
61#include <freeradius-devel/io/listen.h>
62#include <freeradius-devel/io/thread.h>
63
64#include <freeradius-devel/tls/base.h>
65#include <freeradius-devel/tls/dtls.h>
66#include <freeradius-devel/tls/strerror.h>
67#include <freeradius-devel/tls/version.h>
68#include <freeradius-devel/tls/connection.h>
69#include <freeradius-devel/util/misc.h>
70
71#include <freeradius-devel/unlang/base.h>
72#include <freeradius-devel/unlang/function.h>
73#include <freeradius-devel/unlang/interpret.h>
74
75#include <freeradius-devel/util/socket.h>
76
77#include <freeradius-devel/protocol/freeradius/freeradius.internal.h>
78
79#ifdef HAVE_GETOPT_H
80# include <getopt.h>
81#endif
82
83#include <sys/wait.h>
84
85#define EXIT_WITH_FAILURE \
86do { \
87 ret = EXIT_FAILURE; \
88 goto cleanup; \
89} while (0)
90
91char const *radiusd_version = RADIUSD_VERSION_BUILD("unit_test_tls");
92
94static fr_dict_t const *dict_tls;
95
98 { .out = &dict_freeradius, .proto = "freeradius" },
99 { .out = &dict_tls, .proto = "tls" },
101};
102
103/** The "unit_test_tls" section
104 *
105 * The items at the top level steer the test program and do not configure
106 * TLS. The TLS configuration for each role is a subsection.
107 * `fr_tls_server_config` and `fr_tls_client_config` parse the subsections,
108 * so each subsection takes exactly the items that a `tls { ... }` section
109 * takes anywhere else in the server.
110 */
111/** One transport's socket, named by `transport` in the configuration
112 *
113 */
114typedef struct {
115 fr_ipaddr_t ipaddr; //!< Address of the listening socket.
116 uint16_t port; //!< Port of the listening socket.
118
119typedef struct {
120 char const *transport; //!< "tcp" or "udp", naming the subsection below
121 ///< which holds the socket.
122 int socket_type; //!< SOCK_STREAM or SOCK_DGRAM, from `transport`.
123
124 unit_test_tls_socket_t tcp; //!< The `tcp { ... }` subsection.
125 unit_test_tls_socket_t udp; //!< The `udp { ... }` subsection.
126
127 fr_ipaddr_t ipaddr; //!< Address of the listening socket, copied from
128 ///< whichever subsection `transport` named.
129 uint16_t port; //!< Port of the listening socket, and the default
130 ///< port for -s.
131 uint32_t drop_datagram; //!< Drop this datagram rather than sending it,
132 ///< counting from one. Zero drops nothing.
133 bool require_client_certificate; //!< Whether the client has to present a certificate.
134
135 fr_tls_conf_t *server; //!< The `server { ... }` subsection.
136 fr_tls_conf_t *client; //!< The `client { ... }` subsection, used with `-s`.
138
139/** The socket items, parsed once per transport subsection
140 *
141 */
151
152/** Protocols which the test program can negotiate
153 *
154 * The names are the ones that RFC 9765 defines for RADIUS, plus one name that no entry of the RFC matches, which
155 * the tests use as a peer that shares nothing with the other end.
156 */
162
163static fr_tls_alpn_t const unit_test_tls_alpn_table[] = {
164 { .id = UTT_ALPN_RADIUS_1_1, .name = "radius/1.1", .conf_name = "radius_v1_1", .flags = FR_TLS_ALPN_STICKY },
165 { .id = UTT_ALPN_RADIUS_1_0, .name = "radius/1.0", .conf_name = "radius_v1_0", .flags = FR_TLS_ALPN_DEFAULT },
166 { .id = UTT_ALPN_HTTP_1_1, .name = "http/1.1", .conf_name = "http_1_1" },
167 FR_TLS_ALPN_TABLE_TERMINATOR
168};
169
170/** The `alpn` subsection has no rules of its own
171 *
172 * fr_tls_alpn_parse() reads the items of the section itself, so the section needs no rules to parse them.
173 */
177
178/** The rules for the `server` and `client` subsections
179 *
180 * Each includes the rules of the TLS library, and adds the `alpn` subsection, which only the application can
181 * add because only the application has the table. `virtual_server` is at offset 0 of #fr_tls_conf_t, so the
182 * rules of the library keep the offsets that they were written with.
183 */
185 { FR_CONF_OFFSET_REF(fr_tls_conf_t, virtual_server, fr_tls_server_config) },
187 .func = fr_tls_alpn_parse, .uctx = unit_test_tls_alpn_table },
189};
190
192 { FR_CONF_OFFSET_REF(fr_tls_conf_t, virtual_server, fr_tls_client_config) },
194 .func = fr_tls_alpn_parse, .uctx = unit_test_tls_alpn_table },
196};
197
199 /*
200 * `transport` names a subsection, the way a listener's
201 * `transport` does, see common_transport_parse() in
202 * src/lib/bio/fd_config.c. The socket items live in that
203 * subsection rather than here, so that a configuration which
204 * names one transport cannot carry another one's settings.
205 */
206 { FR_CONF_OFFSET("transport", unit_test_tls_conf_t, transport), .dflt = "tcp" },
207
212
213 /*
214 * Lose a datagram on purpose, so that a test can see the
215 * retransmission which recovers from it. Zero loses nothing.
216 */
217 { FR_CONF_OFFSET("drop_datagram", unit_test_tls_conf_t, drop_datagram) },
218
219 { FR_CONF_OFFSET("require_client_certificate", unit_test_tls_conf_t, require_client_certificate),
220 .dflt = "no" },
221
222 /*
223 * A test file may hold only the role that the test runs, so
224 * either subsection may be missing.
225 */
227 .subcs_type = "fr_tls_conf_t" },
229 .subcs_type = "fr_tls_conf_t" },
230
232};
233
234/** State of the test program
235 *
236 * The interpreter and the runnable heap live for the whole of the connection.
237 * A TLS handshake takes several rounds, and each round may yield while a
238 * virtual server section runs. The interpreter and the runnable heap
239 * therefore cannot be allocated once per round.
240 */
241typedef struct {
242 fr_event_list_t *el; //!< Event list everything runs on.
243 unlang_interpret_t *intp; //!< Interpreter for the connection.
244 fr_heap_t *runnable; //!< Requests the interpreter has marked runnable.
245 int yielded; //!< How many requests are currently yielded.
246
247 unit_test_tls_conf_t conf; //!< Parsed "unit_test_tls" section.
248 SSL_CTX *ssl_ctx; //!< Context built from the "tls" section.
249
250 fr_tls_connection_t *conn; //!< State of the connection being run.
251
252 unsigned int count; //!< How many connections to run.
253 bool alert; //!< Reject the peer with a TLS alert, see -A.
254 bool invalid; //!< Mark the session invalid mid-handshake, see -I.
255 bool nonblock; //!< Put the connection socket in non-blocking mode, see -B.
256 bool client; //!< Act as the client and connect to a server,
257 ///< rather than accept a connection. Copied into
258 ///< every connection this program allocates.
259
260 bool app_data; //!< Send one byte of application data once the
261 ///< handshake is done, see -P.
262
263 bool hold; //!< Once connected, send nothing and stay
264 ///< connected, see -H.
265
266 bool reject; //!< Reject the session once the handshake
267 ///< succeeds, see -R.
268 bool network_fail; //!< Fail the session with a network error once
269 ///< the handshake succeeds, see -N.
270 bool abort_pending; //!< Free the connection once the handshake
271 ///< succeeds, while `store session` is still
272 ///< queued, see -Q.
273 unsigned int connections; //!< How many connections have been run so far.
274 fr_ipaddr_t server_ipaddr; //!< Server named by -s.
275 uint16_t server_port; //!< Port from -s, or from the configuration.
276
277 int sockfd; //!< Listening socket.
278 fr_event_fd_t *accept_ef; //!< Read event for sockfd, while waiting in
279 ///< tls_socket_accept().
280 bool accepting; //!< Waiting in tls_socket_accept().
281
282 char const *command; //!< Command to run, see -e.
283 pid_t command_pid; //!< Command started by -e, or 0.
284 fr_event_pid_t const *command_ev; //!< Waits for the command to exit.
285 bool command_exited; //!< The command has exited.
286 bool command_waiting; //!< Waiting in tls_command_wait().
287
288 int fd; //!< Accepted or connected socket.
289
290 uint32_t datagrams; //!< How many datagrams this connection has been
291 ///< asked to write, counting from one. Only used
292 ///< by `drop_datagram`.
293
294 uint8_t *first; //!< The datagram which named the peer, read from
295 ///< the listening socket before the connection's
296 ///< socket existed. Handed to the connection once
297 ///< the connection is running.
298 size_t first_len; //!< Length of `first`.
299 fr_event_fd_t *ef; //!< Read and write events for fd.
300 bool write_blocked; //!< True while the socket has no room for a
301 ///< record and the write event is active, see
302 ///< tls_connection_write_wait().
303 bool read_paused; //!< True while the read event is suspended, because
304 ///< fr_tls_connection_recv_room() returned 0, see
305 ///< _tls_connection_read().
306
307 unsigned char *alpn; //!< Protocol list built by -L, in the wire format
308 ///< fr_tls_conf_t expects. NULL means no ALPN.
309 bool alpn_required; //!< Set by -l.
310
311 bool done; //!< Set once the connection has a result.
312 int ret; //!< Exit status.
314
315static void usage(main_config_t const *config, int status);
316static void tls_request_failed(unit_test_tls_t *utt);
317
318/*
319 * Interpreter callbacks.
320 *
321 * The callbacks below mirror the set in
322 * src/lib/unlang/interpret_synchronous.c and src/lib/io/coord_pair.c. The
323 * one difference is that a post-event handler drains the runnable heap,
324 * rather than a loop inside the caller, so the event loop decides when
325 * each request runs.
326 */
327
328/** Schedule a request, once
329 *
330 * A request reaches the heap from two directions: the interpreter creating it,
331 * and the interpreter marking it runnable again. Inserting a request which is
332 * already on the heap puts it there twice, and popping it then returns a
333 * request which the heap still holds, which the interpreter refuses to run.
334 */
336{
337 if (fr_heap_entry_inserted(request->runnable)) return;
338
340}
341
342/** An internal request created by the interpreter has to run on ours
343 *
344 * The subrequests created for the "verify certificate" section and for the
345 * session cache sections reach this callback.
346 *
347 * fr_tls_call_push() pushes each of them as a detachable subrequest, which
348 * the parent waits on rather than running inline, so the subrequest has to be
349 * scheduled here or nothing ever runs it.
350 */
351static void _request_init_internal(request_t *request, void *uctx)
352{
353 unit_test_tls_t *utt = talloc_get_type_abort(uctx, unit_test_tls_t);
354
355 RDEBUG3("Initialising internal request");
356
358
359 /*
360 * interpret_child_init() calls this, and nothing else schedules
361 * the child, so a subrequest which is not put on the heap here
362 * never runs at all.
363 */
365}
366
368{
369 RDEBUG3("Done external request");
370
371 /*
372 * main() allocated the request, and the request has to survive
373 * until the connection is done with, so this callback does not
374 * free the request.
375 */
376}
377
379{
380 RDEBUG3("Done internal request");
381
382 /* The code which created the internal request frees the request */
383}
384
386{
387 RDEBUG3("Done detached request");
388
389 /*
390 * Nothing else can free a detached request, so this callback
391 * frees the detached request.
392 */
394}
395
396static void _request_detach(request_t *request, UNUSED void *uctx)
397{
398 RDEBUG3("Request detached");
399
400 if (request_detach(request) < 0) RPEDEBUG("Failed detaching request");
401}
402
403static void _request_yield(request_t *request, void *uctx)
404{
405 unit_test_tls_t *utt = talloc_get_type_abort(uctx, unit_test_tls_t);
406
407 utt->yielded++;
408
409 RDEBUG3("Request yielded");
410}
411
412static void _request_resume(request_t *request, UNUSED void *uctx)
413{
414 RDEBUG3("Request resumed");
415}
416
417static void _request_runnable(request_t *request, void *uctx)
418{
419 unit_test_tls_t *utt = talloc_get_type_abort(uctx, unit_test_tls_t);
420
421 fr_assert(utt->yielded > 0);
422 utt->yielded--;
423
425}
426
427static bool _request_scheduled(request_t const *request, UNUSED void *uctx)
428{
429 return fr_heap_entry_inserted(request->runnable);
430}
431
432/** Stop the event loop, recording why
433 *
434 * The connection carries the result, so the exit status is decided here
435 * rather than by the state machine. A process exit status is this program's
436 * notion of a result, and no part of a TLS connection should have to know
437 * about one.
438 */
439static void tls_request_close(fr_tls_connection_t *conn)
440{
441 unit_test_tls_t *utt = talloc_get_type_abort(conn->uctx, unit_test_tls_t);
442
443 if (utt->done) return;
444
445
446 utt->done = true;
447 utt->ret = conn->failed ? EXIT_FAILURE : EXIT_SUCCESS;
448
449 fr_event_loop_exit(utt->el, 1);
450}
451
452/** The connection is up, and can carry application data
453 *
454 * unit_test_tls has no application data to send, so a connection which
455 * reaches this point has done everything it was going to do. A program which
456 * did have data to send would send it here, and close when it was done.
457 */
458static void tls_request_connected(fr_tls_connection_t *conn)
459{
460 unit_test_tls_t *utt = talloc_get_type_abort(conn->uctx, unit_test_tls_t);
461
462 DEBUG2("Connection is up and can carry application data");
463
464 /*
465 * Send one byte of application data, which tells the peer that
466 * every session ticket we were going to send has already gone.
467 *
468 * This used to test fr_tls_session_is_init_finished() after
469 * every pass of the interpreter. The connected callback says
470 * the same thing and says it once, because the connection only
471 * reaches TLS_CONNECTION_CONNECTED when every ticket section has
472 * run.
473 */
474 if (utt->app_data && !conn->client) {
475 fr_tls_session_t *tls_session = conn->tls_session;
476
477 fr_dbuff_in_bytes(&tls_session->clean_in, 0x00);
478 if (fr_tls_session_send(conn->request, tls_session) < 0) {
479 ERROR("Failed encrypting the application data");
481 return;
482 }
483
484 if (fr_tls_connection_write(conn) < 0) {
485 ERROR("Failed sending the application data");
487 return;
488 }
489
490 DEBUG("Sent one byte of application data");
491 }
492
493 /*
494 * -H holds the connection open with nothing more to say. A
495 * peer which is still owed a session ticket or a byte of
496 * application data then waits for something which never
497 * arrives, which is what the post-handshake timer is for.
498 *
499 * The connection still ends: the peer gives up, closes, and
500 * this end sees EOF.
501 */
502 if (utt->hold) {
503 DEBUG("Holding the connection open, sending nothing");
504 return;
505 }
506
507 tls_request_close(conn);
508}
509
510/** Record a failure this program cannot recover from, and stop
511 *
512 * tls_request_close() reads the result from the connection, so a failure
513 * has to reach the connection before the callback runs.
514 */
516{
517 utt->conn->failed = TLS_CONNECTION_FAIL_APPLICATION;
519}
520
523 { 0 }
524};
525
528 { 0 }
529};
530
531/** Start or stop waiting for the socket to have room for more records
532 *
533 * _tls_connection_start() inserts the write event with the socket and then
534 * suspends the write event, because a socket which has room fires the write
535 * event on every pass of the event loop. tls_connection_write_wait() resumes
536 * the write event only while a record is waiting for room.
537 *
538 * A suspend reads the active callback and a resume reads the suspended
539 * callback, so a suspend and a resume have to alternate. `write_blocked`
540 * records whether the write event is active, so a suspend never follows a
541 * suspend.
542 */
544{
545 if (!utt->ef || (utt->write_blocked == wait)) return 0;
546
548 wait ? resume_write : pause_write) < 0) {
549 PERROR("Failed updating the write event for the connection");
550 return -1;
551 }
552
553 utt->write_blocked = wait;
554
555 return 0;
556}
557
558/** Write whatever OpenSSL has produced out to the connection
559 *
560 * The TLS session reads and writes memory BIOs, which are OpenSSL's in-memory
561 * I/O buffers, and never a socket. Writing each record to the socket is
562 * therefore the caller's job. The EAP code in src/lib/eap/tls.c writes
563 * records the same way.
564 */
565static ssize_t tls_connection_write(fr_tls_connection_t *conn, uint8_t const *data, size_t size)
566{
567 unit_test_tls_t *utt = talloc_get_type_abort(conn->uctx, unit_test_tls_t);
568 ssize_t slen;
569
570 /*
571 * Lose this one on purpose. Telling the connection that the
572 * whole datagram went out is what a real loss looks like from
573 * here: the sender has no idea, and only the retransmission
574 * timer recovers.
575 */
576 utt->datagrams++;
577 if (utt->conf.drop_datagram && (utt->datagrams == utt->conf.drop_datagram)) {
578 DEBUG("Dropping datagram %u of %zu bytes", utt->datagrams, size);
579 return (ssize_t) size;
580 }
581
582 /*
583 * EINTR means the write never happened, so the same octets are
584 * written again. Every other error leaves this loop.
585 */
586 for (;;) {
587 slen = write(utt->fd, data, size);
588 if (slen >= 0) break;
589
590 switch (fr_tls_connection_io_error(conn, slen)) {
591 case FR_TLS_CONNECTION_IO_RETRY:
592 continue;
593
594 case FR_TLS_CONNECTION_IO_BLOCKED:
595 /*
596 * The octets stay in the connection's buffer, and
597 * _tls_connection_write() asks the connection to
598 * write them again once the socket has room.
599 * Nothing was lost, so this is not a failure.
600 */
601 DEBUG3("Blocked writing %zu bytes to the connection", size);
602
603 if (tls_connection_write_wait(utt, true) < 0) return -1;
604 return 0;
605
606 case FR_TLS_CONNECTION_IO_EOF:
607 ERROR("Connection closed by the peer while writing to it");
608 return -1;
609
610 /*
611 * write() failed, so the classification cannot be "no
612 * error". Treat the impossible value as fatal rather
613 * than carrying on.
614 */
615 case FR_TLS_CONNECTION_IO_OK:
616 case FR_TLS_CONNECTION_IO_FATAL:
617 break;
618 }
619
620 ERROR("Failed writing to connection: %s", fr_syserror(conn->error));
621 return -1;
622 }
623
624 if (slen == 0) {
625 ERROR("Wrote no data to connection");
626 return -1;
627 }
628
629 /*
630 * Something went out, so the socket had room. Stop waiting for
631 * room, which is a no-op when we were not waiting. Whether more
632 * is queued behind this is the connection's business, not ours.
633 */
634 if (tls_connection_write_wait(utt, false) < 0) return -1;
635
636 DEBUG3("Wrote %zd bytes to the connection", slen);
637
638 return slen;
639}
640
641/** The socket is ready for writes.
642 *
643 * Run the connection state machine, which either flushes pending
644 * data, or keeps going with the next TLS state.
645 *
646 * The event loop calls _tls_connection_write() only after a write blocked,
647 * see tls_connection_write_wait().
648 */
649static void _tls_connection_write(UNUSED fr_event_list_t *el, UNUSED int fd, UNUSED int flags, void *uctx)
650{
651 unit_test_tls_t *utt = talloc_get_type_abort(uctx, unit_test_tls_t);
652
653 /*
654 * @todo - arguably remove the socket from the event list.
655 */
656 if (utt->done) return;
657
658 /*
659 * fr_tls_connection_process() writes the rest of `dirty_out` and
660 * then re-checks the connection. The re-check ends a connection
661 * whose handshake finished while a record was still queued.
662 * Calling tls_connection_write() alone would not end the
663 * connection.
664 */
665 fr_tls_connection_process(utt->conn);
666}
667
670 { 0 }
671};
672
675 { 0 }
676};
677
678/** OpenSSL has read from `dirty_in`, so start reading the socket again
679 *
680 * fr_tls_connection_process() calls this function only after
681 * fr_tls_connection_recv_room() returned 0, and _tls_connection_read()
682 * suspended the read event.
683 */
684static void tls_connection_recv_resume(fr_tls_connection_t *conn)
685{
686 unit_test_tls_t *utt = talloc_get_type_abort(conn->uctx, unit_test_tls_t);
687
688 if (!utt->ef || !utt->read_paused) return;
689
691 PERROR("Failed resuming the read event for the connection");
693 return;
694 }
695
696 utt->read_paused = false;
697 DEBUG3("Resumed reading from the connection");
698}
699
700/** A record arrived on the connection, so hand the record to the connection
701 *
702 * Reading the socket is all this program does here. Everything the record
703 * means to TLS is fr_tls_connection_recv()'s business.
704 *
705 * This function reads at most what fr_tls_connection_recv_room() returns.
706 * The rest of the data stays in the socket until OpenSSL has read from
707 * `dirty_in`. A socket with unread data fires the read event on every pass
708 * of the event loop. Because of that, when fr_tls_connection_recv_room()
709 * returns 0, this function suspends the read event.
710 * tls_connection_recv_resume() then resumes the read event.
711 */
712static void _tls_connection_read(UNUSED fr_event_list_t *el, int fd, UNUSED int flags, void *uctx)
713{
714 unit_test_tls_t *utt = talloc_get_type_abort(uctx, unit_test_tls_t);
715 uint8_t buf[SSL3_RT_MAX_PLAIN_LENGTH];
716 size_t room;
717 ssize_t slen;
718
719 if (utt->done) return;
720
721 room = fr_tls_connection_recv_room(utt->conn);
722 if (room == 0) {
723 DEBUG3("No room for more data, waiting for OpenSSL to read what the connection holds");
724
726 PERROR("Failed suspending the read event for the connection");
728 return;
729 }
730
731 utt->read_paused = true;
732 return;
733 }
734 if (room > sizeof(buf)) room = sizeof(buf);
735
736 slen = read(fd, buf, room);
737 if (slen <= 0) {
738 /*
739 * The connection records what happened, and ends itself
740 * when the result ends it. Nothing is left to do here
741 * but say which way the call was going.
742 */
743 switch (fr_tls_connection_io_error(utt->conn, slen)) {
744 /*
745 * An interrupted read and a blocked read both wait
746 * for the next read event. A socket which still
747 * holds a record fires the read event again, so
748 * returning here loses no data.
749 */
750 case FR_TLS_CONNECTION_IO_RETRY:
751 case FR_TLS_CONNECTION_IO_BLOCKED:
752 DEBUG3("Blocked reading from the connection");
753 break;
754
755 case FR_TLS_CONNECTION_IO_EOF:
756 DEBUG2("Peer closed the connection on fd %d, read returned EOF", fd);
757 break;
758
759 /*
760 * read() failed, so the classification cannot be "no
761 * error". Treat the impossible value as fatal rather
762 * than carrying on.
763 */
764 case FR_TLS_CONNECTION_IO_OK:
765 case FR_TLS_CONNECTION_IO_FATAL:
766 ERROR("Failed reading from connection: %s", fr_syserror(utt->conn->error));
767 break;
768 }
769
770 return;
771 }
772
773 fr_tls_connection_recv(utt->conn, buf, (size_t) slen);
774}
775
776/** The connection failed at the socket level
777 *
778 */
779static void _tls_connection_error(UNUSED fr_event_list_t *el, int fd, int flags, int fd_errno,
780 void *uctx)
781{
782 unit_test_tls_t *utt = talloc_get_type_abort(uctx, unit_test_tls_t);
783
784 if (fd_errno == 0) {
785 DEBUG2("Peer closed the connection on fd %d, event loop reported EOF (flags 0x%x)", fd, (unsigned int)flags);
786 (void) fr_tls_connection_io_error(utt->conn, 0);
787 return;
788 }
789
790 ERROR("Error on connection: %s", fr_syserror(fd_errno));
791
792 /*
793 * The event loop reports the error rather than leaving it in
794 * errno, so put it back where the classifier reads it.
795 */
796 errno = fd_errno;
797 (void) fr_tls_connection_io_error(utt->conn, -1);
798}
799
800/** Drain the runnable heap once per pass of the event loop
801 *
802 * A handshake round yields whenever the round runs a virtual server section.
803 * When that section finishes, unlang_interpret_mark_runnable() puts the
804 * request on the runnable heap, and this drains the heap again.
805 */
807{
808 unit_test_tls_t *utt = talloc_get_type_abort(uctx, unit_test_tls_t);
810
811 /*
812 * Stand in for an application which rejects a peer outright.
813 *
814 * `pending` says a record has arrived and the handshake has not
815 * read it yet. This hook used to live in _tls_connection_read(),
816 * where its position said the same thing, and the comment there
817 * warned that raising the alert before a record arrives sends it
818 * into an empty handshake, where it is lost. The test cannot
819 * tell: removing this test passes six suite runs out of six,
820 * because a server runs no handshake round until a record
821 * arrives. A client runs one straight away, so keep the test.
822 *
823 * Raising the alert later, with the other two hooks below, is
824 * too late. Those run after the round, and the round which
825 * would have carried the alert has gone.
826 */
827 /*
828 * Stand in for a record which FreeRADIUS itself refuses.
829 *
830 * fr_tls_session_msg_cb() marks such a session invalid and
831 * lets the round finish. The round after that refuses to
832 * continue, records FR_ERROR_VALUE_SESSION_INVALID, and sends
833 * the peer a fatal alert. Setting the flag here reaches that
834 * second round without having to feed the handshake a
835 * malformed record.
836 *
837 * `pending` places this before a round, for the same reason
838 * the alert hook below is placed there.
839 */
840 if (utt->invalid && utt->conn->tls_session && utt->conn->pending &&
841 (utt->connections == utt->count)) {
842 utt->invalid = false;
843 utt->conn->tls_session->invalid = true;
844 }
845
846 if (utt->alert && utt->conn->tls_session && utt->conn->pending &&
847 (utt->connections == utt->count)) {
848 utt->alert = false;
849
850 if (fr_tls_session_alert(utt->conn->request, utt->conn->tls_session,
851 SSL3_AL_FATAL, SSL_AD_ACCESS_DENIED) < 0) {
852 ERROR("Failed raising the TLS alert");
854 return;
855 }
856 }
857
858 while (fr_heap_pop((void **)&request, &utt->runnable) == 0) {
859 if (!request) break;
860
862
863 /*
864 * Only the connection's own request advances the
865 * handshake. A subrequest returns the subrequest's
866 * result through the interpreter.
867 *
868 * The connection's own IO is not done here any more.
869 * tls_connection_frame_process() does it, inside
870 * src/lib/tls, at the point the connection is about to
871 * wait for the peer. A real listener has no hook here,
872 * so nothing which a real listener cannot do belongs
873 * here either.
874 */
875 if (request == utt->conn->request) {
876 /*
877 * Stand in for an application which rejects a
878 * session after the handshake succeeded. The
879 * handshake has finished, so OpenSSL has asked
880 * for the session to be cached, and the
881 * connection is about to run its cache
882 * operations. Failing it here makes those
883 * operations a deny and a clear rather than a
884 * store, which is what rlm_eap_tls does when
885 * policy rejects.
886 */
887 if ((utt->reject || utt->network_fail) && (utt->connections == utt->count) &&
888 fr_tls_session_is_init_finished(utt->conn->tls_session)) {
889 INFO("%s the session after a successful handshake",
890 utt->network_fail ? "Failing, with a network error," : "Rejecting");
891
892 /*
893 * Record the reason, and nothing else.
894 * The handshake has finished, so OpenSSL
895 * has asked for the session to be cached,
896 * and the connection frame is about to run
897 * that cache work. The frame reads
898 * `failed` to decide whether the work is a
899 * store or a deny and a clear, which is
900 * what rlm_eap_tls does when policy
901 * rejects.
902 *
903 * fr_tls_connection_failed() would instead
904 * report the connection finished here, and
905 * the queued cache work would never be
906 * drained. src/lib/tls/session.c asserts
907 * on exactly that.
908 */
909 utt->conn->failed = utt->network_fail ? TLS_CONNECTION_FAIL_SYSCALL :
910 TLS_CONNECTION_FAIL_APPLICATION;
911 }
912
913 /*
914 * Free the connection while `store session` is
915 * still queued. The handshake has finished, so
916 * OpenSSL has asked for the session to be cached
917 * and the connection is about to run that work,
918 * but it has not run yet. Closing now frees the
919 * session with the operation still pending, which
920 * is the path session.c used to assert on and now
921 * discards. This is deterministic: it does not
922 * depend on when the peer closes.
923 */
924 if (utt->abort_pending && (utt->connections == utt->count) &&
925 fr_tls_session_is_init_finished(utt->conn->tls_session)) {
926 INFO("Aborting the connection with cache operations still queued");
928 return;
929 }
930 }
931
932 if (utt->done) return;
933 }
934}
935
936/** Open the listening socket described by the "unit_test_tls" section
937 *
938 */
940{
941 int sockfd;
942 fr_ipaddr_t ipaddr = utt->conf.ipaddr;
943 uint16_t port = utt->conf.port;
944
945 /*
946 * The items are not marked as required, because a client has no
947 * listening socket, and so needs neither of them.
948 */
949 if ((ipaddr.af == AF_UNSPEC) || !port) {
950 ERROR("Both 'ipaddr' and 'port' must be set in the 'unit_test_tls' section "
951 "when listening for a connection");
952 return -1;
953 }
954
955 if (utt->conf.socket_type == SOCK_DGRAM) {
956 sockfd = fr_socket_server_udp(&ipaddr, &port, NULL, false);
957 } else {
958 sockfd = fr_socket_server_tcp(&ipaddr, &port, NULL, false);
959 }
960 if (sockfd < 0) {
961 PERROR("Failed opening %s socket", utt->conf.transport);
962 return -1;
963 }
964
965 /*
966 * A datagram connection runs on its own socket bound to the
967 * same address and port as this one, see
968 * tls_socket_accept_one(). Both have to ask for the port
969 * before they bind, or the second bind fails.
970 */
971 if (utt->conf.socket_type == SOCK_DGRAM) {
972 int on = 1;
973
974 if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEPORT, &on, sizeof(on)) < 0) {
975 ERROR("Failed setting SO_REUSEPORT: %s", fr_syserror(errno));
976 close(sockfd);
977 return -1;
978 }
979 }
980
981 if (fr_socket_bind(sockfd, NULL, &ipaddr, &port) < 0) {
982 PERROR("Failed binding %s socket", utt->conf.transport);
983 close(sockfd);
984 return -1;
985 }
986
987 /*
988 * A datagram socket has no queue of connections to listen for.
989 * The first datagram to arrive is what stands in for a
990 * connection, see tls_socket_accept_one().
991 */
992 if ((utt->conf.socket_type == SOCK_STREAM) && (listen(sockfd, 8) < 0)) {
993 ERROR("Failed listening on TCP socket: %s", fr_syserror(errno));
994 close(sockfd);
995 return -1;
996 }
997
998 /*
999 * tls_socket_accept() waits for the socket in the event loop,
1000 * and then accepts without blocking.
1001 */
1002 if (fr_nonblock(sockfd) < 0) {
1003 PERROR("Failed setting the listening socket non-blocking");
1004 close(sockfd);
1005 return -1;
1006 }
1007
1008 INFO("Listening on %pV port %u using %s", fr_box_ipaddr(ipaddr), port, utt->conf.transport);
1009
1010 utt->sockfd = sockfd;
1011
1012 return 0;
1013}
1014
1015/** Accept a connection, if the listening socket has one queued
1016 *
1017 * @return
1018 * - 1 if a connection was accepted.
1019 * - 0 if no connection is queued.
1020 * - -1 on error.
1021 */
1023{
1024 int fd;
1025
1026 /*
1027 * A datagram socket is not listening, so there is nothing to
1028 * accept. The first ClientHello names the peer, and the
1029 * connection runs on a second socket which is connect()ed to
1030 * that peer: the kernel then delivers that peer's datagrams to
1031 * the connected socket in preference to this one, and read()
1032 * and write() work as they do on a stream.
1033 *
1034 * The connection cannot run on this socket. connect() is a
1035 * property of the socket rather than of the descriptor, so
1036 * connecting this one, or any descriptor duplicated from it,
1037 * would leave the listening socket bound to one peer for the
1038 * rest of the program.
1039 */
1040 if (utt->conf.socket_type == SOCK_DGRAM) {
1041 struct sockaddr_storage peer;
1042 socklen_t peerlen;
1043 uint8_t buf[FR_TLS_MAX_PACKET_SIZE];
1044 ssize_t slen;
1045 fr_ipaddr_t ipaddr = utt->conf.ipaddr;
1046 uint16_t port = utt->conf.port;
1047 int on = 1;
1048
1049 /*
1050 * Read the datagram rather than peeking at it. It is
1051 * queued on this socket, and the connection's socket
1052 * does not exist yet, so leaving it here would leave it
1053 * somewhere the connection never reads. It is given to
1054 * the connection once the connection is running, see
1055 * tls_connection_run().
1056 */
1057 for (;;) {
1058 peerlen = sizeof(peer);
1059
1060 slen = recvfrom(utt->sockfd, buf, sizeof(buf), 0, (struct sockaddr *) &peer, &peerlen);
1061 if (slen < 0) {
1062 if ((errno == EAGAIN) || (errno == EWOULDBLOCK) || (errno == EINTR)) return 0;
1063
1064 ERROR("Failed reading the first datagram: %s", fr_syserror(errno));
1065 return -1;
1066 }
1067
1068 /*
1069 * Filter input packets by ClientHello.
1070 *
1071 * Even if we connect() sockets, the connected socket could go away. Packets for
1072 * that (old) socket are then received by the original accept socket. We don't
1073 * know what to do with them, as the DTLS session goes away when the socket goes
1074 * away.
1075 *
1076 * The main accept socket doesn't read its FD while the DTLS session is
1077 * running, so packets might pile up here. This is only a problem for
1078 * unit_test_tls, as a real server would keep reading the accept socket.
1079 *
1080 * @todo - keep some kind or more long-lived RBtree of client source IP/port and
1081 * DTLS session. It is at least theoretically possible that we could re-liven
1082 * the DTLS connection.
1083 *
1084 * A server which takes one of those old datagrams as a new connection request
1085 * will try to start a connection to a peer which has already gone. The real
1086 * peer's handshake stays queued here, and the handshake never completes.
1087 *
1088 * The solution (hack) is to just discard anything that doesn't look like a
1089 * ClientHello.
1090 *
1091 * A ClientHello is a handshake record in epoch 0 whose first message is a
1092 * client_hello. RFC 6347 Section 4.1 gives the record header, which is
1093 * DTLS1_RT_HEADER_LENGTH octets of type, version, epoch, sequence number, and
1094 * length. Section 4.3.2 gives the handshake message types. A discarded
1095 * datagram looks to the peer like a lost datagram, and the peer retransmits, see
1096 * Section 4.2.4.
1097 */
1098 if ((slen > (ssize_t) DTLS1_RT_HEADER_LENGTH) &&
1099 (buf[0] == SSL3_RT_HANDSHAKE) &&
1100 (buf[3] == 0) && (buf[4] == 0) &&
1101 (buf[DTLS1_RT_HEADER_LENGTH] == SSL3_MT_CLIENT_HELLO)) break;
1102
1103 DEBUG2("Discarding a %zd byte datagram which does not start a connection", slen);
1104 }
1105
1106 fd = fr_socket_server_udp(&ipaddr, &port, NULL, false);
1107 if (fd < 0) {
1108 PERROR("Failed opening the connection's datagram socket");
1109 return -1;
1110 }
1111
1112 if (setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &on, sizeof(on)) < 0) {
1113 ERROR("Failed setting SO_REUSEPORT: %s", fr_syserror(errno));
1114 close(fd);
1115 return -1;
1116 }
1117
1118 if (fr_socket_bind(fd, NULL, &ipaddr, &port) < 0) {
1119 PERROR("Failed binding the connection's datagram socket");
1120 close(fd);
1121 return -1;
1122 }
1123
1124 if (connect(fd, (struct sockaddr *) &peer, peerlen) < 0) {
1125 ERROR("Failed connecting to the peer: %s", fr_syserror(errno));
1126 close(fd);
1127 return -1;
1128 }
1129
1130 MEM(utt->first = talloc_memdup(utt, buf, (size_t) slen));
1131 utt->first_len = (size_t) slen;
1132
1133 utt->fd = fd;
1134
1135 return 1;
1136 }
1137
1138 fd = accept(utt->sockfd, NULL, NULL);
1139 if (fd < 0) {
1140 if ((errno == EAGAIN) || (errno == EWOULDBLOCK) || (errno == EINTR)) return 0;
1141
1142 ERROR("Failed accepting connection: %s", fr_syserror(errno));
1143 return -1;
1144 }
1145
1146 /*
1147 * Some systems give the accepted socket the O_NONBLOCK flag of
1148 * the listening socket, and some don't. Clear it, so the socket
1149 * is blocking unless -B asks otherwise.
1150 */
1151 if (fr_blocking(fd) < 0) {
1152 PERROR("Failed setting the connection socket blocking");
1153 close(fd);
1154 return -1;
1155 }
1156
1157 utt->fd = fd;
1158
1159 return 1;
1160}
1161
1162/** Accept the connection once the listening socket is readable
1163 *
1164 */
1165static void _tls_socket_accept(fr_event_list_t *el, UNUSED int fd, UNUSED int flags, void *uctx)
1166{
1167 unit_test_tls_t *utt = talloc_get_type_abort(uctx, unit_test_tls_t);
1168
1169 if (tls_socket_accept_one(utt) == 0) return;
1170
1172}
1173
1174/** Stop waiting for a connection if the listening socket fails
1175 *
1176 */
1177static void _tls_socket_error(fr_event_list_t *el, UNUSED int fd, UNUSED int flags, int fd_errno, UNUSED void *uctx)
1178{
1179 ERROR("Listening socket failed: %s", fr_syserror(fd_errno));
1180
1182}
1183
1184/** Start waiting for a connection, from inside the event loop
1185 *
1186 * See tls_connection_run() for why this runs from inside the event loop.
1187 */
1189{
1190 unit_test_tls_t *utt = talloc_get_type_abort(uctx, unit_test_tls_t);
1191
1192 /*
1193 * The command exited before this connection, so the only
1194 * connection which can arrive is one already queued.
1195 */
1196 if (utt->command_exited) {
1197 if (tls_socket_accept_one(utt) == 0) ERROR("The command exited without connecting");
1198
1200 return;
1201 }
1202
1203 if (fr_event_fd_insert(utt, &utt->accept_ef, el, utt->sockfd,
1204 _tls_socket_accept, NULL, _tls_socket_error, utt) < 0) {
1205 PERROR("Failed adding the listening socket to the event loop");
1207 }
1208}
1209
1210/** Wait for a connection, or for the command started by -e to exit without connecting
1211 *
1212 * @return
1213 * - 0 with utt->fd set to the accepted connection.
1214 * - -1 on failure.
1215 */
1217{
1218 fr_event_user_t *ev = NULL;
1219
1220 INFO("Waiting for a connection");
1221
1222 if (fr_event_user_insert(utt, utt->el, &ev, true, _tls_socket_accept_start, utt) < 0) {
1223 PERROR("Failed scheduling the wait for a connection");
1224 return -1;
1225 }
1226
1227 utt->accepting = true;
1228 (void) fr_event_loop(utt->el);
1229 utt->accepting = false;
1230
1231 if (utt->accept_ef) {
1232 (void) fr_event_fd_delete(utt->el, utt->sockfd, FR_EVENT_FILTER_IO);
1233 utt->accept_ef = NULL;
1234 }
1235 TALLOC_FREE(ev);
1236
1237 return (utt->fd < 0) ? -1 : 0;
1238}
1239
1240/** Record that the command started by -e has exited
1241 *
1242 * If the server is waiting for a connection, a command which exits has either
1243 * connected already, and the connection is queued, or never will.
1244 */
1245static void _tls_command_exit(fr_event_list_t *el, pid_t pid, int status, void *uctx)
1246{
1247 unit_test_tls_t *utt = talloc_get_type_abort(uctx, unit_test_tls_t);
1248
1249 utt->command_exited = true;
1250
1251 if (WIFEXITED(status)) {
1252 INFO("Command (PID %ld) exited with status %d", (long)pid, WEXITSTATUS(status));
1253 } else if (WIFSIGNALED(status)) {
1254 INFO("Command (PID %ld) was killed by signal %d", (long)pid, WTERMSIG(status));
1255 }
1256
1257 if (utt->accepting) {
1258 if (tls_socket_accept_one(utt) == 0) ERROR("The command exited without connecting");
1259
1261 return;
1262 }
1263
1265}
1266
1267/** Start the command named by -e
1268 *
1269 * A server starts the command once it is listening. A command which connects
1270 * to the server connects to a socket which is already listening, so it can't
1271 * be refused, and the server sees the command exit, so it never waits for a
1272 * peer which has gone.
1273 *
1274 * A client starts the command once its first connection succeeds.
1275 */
1276static int tls_command_start(unit_test_tls_t *utt, char const *command)
1277{
1278 pid_t pid;
1279 sigset_t set;
1280
1281 pid = fork();
1282 if (pid < 0) {
1283 ERROR("Failed forking the command: %s", fr_syserror(errno));
1284 return -1;
1285 }
1286
1287 if (pid == 0) {
1288 /*
1289 * Only async-signal-safe calls between fork() and exec.
1290 * The command gets neither of our sockets, so the peer
1291 * sees the connection close when we close it, and it
1292 * gets an empty signal mask, not ours.
1293 */
1294 if (utt->sockfd >= 0) close(utt->sockfd);
1295 if (utt->fd >= 0) close(utt->fd);
1296 sigemptyset(&set);
1297 sigprocmask(SIG_SETMASK, &set, NULL);
1298 execl("/bin/sh", "sh", "-c", command, (char *)NULL);
1299 _exit(127);
1300 }
1301
1302 INFO("Started command (PID %ld): %s", (long)pid, command);
1303
1304 utt->command_pid = pid;
1305
1306 if (fr_event_pid_wait(utt, utt->el, &utt->command_ev, pid, _tls_command_exit, utt) < 0) {
1307 PERROR("Failed waiting for the command to exit");
1308 return -1;
1309 }
1310
1311 return 0;
1312}
1313
1314/** Wait for the command started by -e to exit, so its output is complete
1315 *
1316 */
1318{
1319 if (!utt->command_pid || utt->command_exited) return;
1320
1321 utt->command_waiting = true;
1322 (void) fr_event_loop(utt->el);
1323 utt->command_waiting = false;
1324}
1325
1326/** Connect to the server named by -s
1327 *
1328 */
1330{
1331 int fd;
1333
1334 fr_inet_ntop(buffer, sizeof(buffer), &utt->server_ipaddr);
1335
1336 if (utt->conf.socket_type == SOCK_DGRAM) {
1337 fd = fr_socket_client_udp(NULL, NULL, NULL, &utt->server_ipaddr, utt->server_port, false);
1338 } else {
1339 fd = fr_socket_client_tcp(NULL, NULL, &utt->server_ipaddr, utt->server_port, false);
1340 }
1341 if (fd < 0) {
1342 PERROR("Failed connecting to %s port %u", buffer, utt->server_port);
1343 return -1;
1344 }
1345
1346 INFO("Connected to %s port %u on fd %d", buffer, utt->server_port, fd);
1347
1348 utt->fd = fd;
1349
1350 return 0;
1351}
1352
1353/** Build an internal client.
1354 *
1355 * unit_test_tls accepts packets from anywhere (for now), and doesn't read "client" configuration sections.
1356 *
1357 * The client is built by allocating a CONF_SECTION rather than by filling in #fr_client_t manually, which
1358 * allows fields to be examined by `%request.client()`.
1359 *
1360 * "proto = tls" sets both the protocol and tls_required. It also fixes the
1361 * secret at "radsec", so that is the secret set here.
1362 */
1363static fr_client_t *tls_client_alloc(TALLOC_CTX *ctx, fr_ipaddr_t const *ipaddr)
1364{
1365 CONF_SECTION *cs;
1366 fr_client_t *client;
1368
1369 /*
1370 * Written without a prefix, the way a person would write it in
1371 * a "client" section. The "ipaddr" item is a COMBO_IP_PREFIX,
1372 * so a bare host address parses as a /32 or a /128.
1373 */
1374 fr_inet_ntop(buffer, sizeof(buffer), ipaddr);
1375
1376 MEM(cs = cf_section_alloc(ctx, NULL, "client", "unit_test_tls"));
1378 MEM(cf_pair_alloc(cs, "proto", "tls", T_OP_EQ, T_BARE_WORD, T_BARE_WORD));
1379 MEM(cf_pair_alloc(cs, "secret", "radsec", T_OP_EQ, T_BARE_WORD, T_DOUBLE_QUOTED_STRING));
1380 MEM(cf_pair_alloc(cs, "shortname", "unit_test_tls", T_OP_EQ, T_BARE_WORD, T_DOUBLE_QUOTED_STRING));
1381 MEM(cf_pair_alloc(cs, "nas_type", "test", T_OP_EQ, T_BARE_WORD, T_DOUBLE_QUOTED_STRING));
1382
1383 client = client_afrom_cs(ctx, cs, NULL, 0);
1384 if (!client) {
1385 PERROR("Failed creating the client for %s", buffer);
1386 talloc_free(cs);
1387 return NULL;
1388 }
1389
1390 /*
1391 * The client has to outlive the section it was built from,
1392 * because %request.client() reads the section.
1393 */
1394 talloc_steal(client, cs);
1395
1396 return client;
1397}
1398
1399/** Build the request the handshake runs under
1400 *
1401 * The TLS code reads the control list for TLS-Session-Cert-File and
1402 * TLS-Session-Require-Client-Certificate, and writes the negotiated version
1403 * and cipher suite into the session-state list, so a real request is needed.
1404 */
1405static request_t *tls_request_alloc(TALLOC_CTX *ctx, int fd, int socket_type)
1406{
1408 struct sockaddr_storage sa;
1409 socklen_t salen;
1410
1411 static uint64_t number = 0;
1412
1414 if (!request) return NULL;
1415
1416 if (!request->packet) request->packet = fr_packet_alloc(request, false);
1417 if (!request->reply) request->reply = fr_packet_alloc(request, false);
1418
1419 request->packet->timestamp = fr_time();
1420
1421 request->packet->socket.type = socket_type;
1422 request->packet->socket.fd = fd;
1423
1424 salen = sizeof(sa);
1425 if (getpeername(fd, (struct sockaddr *) &sa, &salen) == 0) {
1426 (void) fr_ipaddr_from_sockaddr(&request->packet->socket.inet.src_ipaddr,
1427 &request->packet->socket.inet.src_port, &sa, salen);
1428 request->packet->socket.af = request->packet->socket.inet.src_ipaddr.af;
1429 }
1430
1431 salen = sizeof(sa);
1432 if (getsockname(fd, (struct sockaddr *) &sa, &salen) == 0) {
1433 (void) fr_ipaddr_from_sockaddr(&request->packet->socket.inet.dst_ipaddr,
1434 &request->packet->socket.inet.dst_port, &sa, salen);
1435 }
1436
1437 /*
1438 * The client is the far end of the connection we just accepted.
1439 */
1440 request->client = tls_client_alloc(request, &request->packet->socket.inet.src_ipaddr);
1441 if (!request->client) {
1443 return NULL;
1444 }
1445
1446 request->number = number++;
1447 request->name = talloc_typed_asprintf(request, "%" PRIu64, request->number);
1448 request->master_state = REQUEST_ACTIVE;
1449
1450 request->log.dst = talloc_zero(request, log_dst_t);
1451 request->log.dst->func = vlog_request;
1452 request->log.dst->uctx = &default_log;
1453 request->log.dst->lvl = fr_debug_lvl;
1454
1455 request->log.lvl = fr_debug_lvl;
1456 request->async = talloc_zero(request, fr_async_t);
1457 request->async->request = request;
1458
1459 if (fr_packet_pairs_from_packet(request->request_ctx, &request->request_pairs, request->packet) < 0) {
1460 ERROR("Failed converting connection addresses to attributes");
1462 return NULL;
1463 }
1464
1465 return request;
1466}
1467
1468/** Add the connection to the event loop, and get it moving
1469 *
1470 * Runs from inside the event loop, see tls_connection_run().
1471 */
1473{
1474 unit_test_tls_t *utt = talloc_get_type_abort(uctx, unit_test_tls_t);
1475
1476 /*
1477 * Nothing polls. A handshake round starts when a record arrives,
1478 * and a yielded round resumes when the interpreter marks the
1479 * request runnable.
1480 *
1481 * fr_event_fd_insert() below adds the write event along with the
1482 * socket, and the call to tls_connection_write_wait() then
1483 * suspends the write event, for the reason
1484 * tls_connection_write_wait() gives.
1485 */
1486 if (fr_event_fd_insert(utt, &utt->ef, el, utt->fd,
1488 PERROR("Failed adding the connection to the event loop");
1489 tls_request_failed(utt);
1490 return;
1491 }
1492
1493 /*
1494 * fr_event_fd_insert() added the socket with the write event
1495 * active, which is the state `write_blocked` records, so set
1496 * `write_blocked` to true and then suspend the write event. No
1497 * record is waiting for room yet.
1498 */
1499 utt->write_blocked = true;
1500 if (tls_connection_write_wait(utt, false) < 0) {
1501 tls_request_failed(utt);
1502 return;
1503 }
1504
1505 /*
1506 * Run `new session { ... }` and, for a client, `load session`.
1507 * A server then waits for the ClientHello. A client has to send
1508 * it.
1509 */
1510 fr_tls_connection_wake(utt->conn);
1511}
1512
1513/** Run one connection from the first byte to the last
1514 *
1515 * Everything which belongs to a single connection is allocated here and freed
1516 * again at the end, so that the next connection starts clean. What survives
1517 * is what the cache needs: the interpreter, the modules, and so the sessions
1518 * a policy stored.
1519 */
1521{
1522 int ret = -1;
1523 fr_event_user_t *ev = NULL;
1524 request_t *stale;
1525
1526 utt->connections++;
1527
1528 /*
1529 * A connection of its own for each connection, rather than one
1530 * connection reset by hand between them. Everything the
1531 * library puts on a connection then goes when the connection
1532 * goes, and this program has nothing to remember to clear.
1533 */
1534 TALLOC_FREE(utt->conn);
1535 MEM(utt->conn = fr_tls_connection_alloc(utt, utt->el->tl,
1539 utt->conn->uctx = utt;
1540 utt->conn->client = utt->client;
1541 utt->conn->recv_resume = tls_connection_recv_resume;
1542
1543
1544
1545 utt->done = false;
1546 utt->ret = EXIT_SUCCESS;
1547 utt->fd = -1;
1548 utt->ef = NULL;
1549 utt->write_blocked = false;
1550 utt->read_paused = false;
1551
1552 /*
1553 * Get a connection, one way or the other.
1554 */
1555 if (utt->conn->client) {
1556 if (tls_socket_connect(utt) < 0) return -1;
1557
1558 if (utt->command && !utt->command_pid && (tls_command_start(utt, utt->command) < 0)) return -1;
1559 } else {
1560 if (tls_socket_accept(utt) < 0) return -1;
1561 }
1562
1563 /*
1564 * One place for both roles: the client has just connected,
1565 * and the server has just accepted. Neither socket inherits
1566 * the flag from the listening socket, so both are set here.
1567 */
1568 if (utt->nonblock && (fr_nonblock(utt->fd) < 0)) {
1569 PERROR("Failed setting the connection socket non-blocking");
1570 return -1;
1571 }
1572
1573 utt->conn->request = tls_request_alloc(utt, utt->fd, utt->conf.socket_type);
1574 if (!utt->conn->request) goto finish;
1575
1576 unlang_interpret_set(utt->conn->request, utt->intp);
1577
1578 /*
1579 * Name the connection for the log, now that the socket is known.
1580 * The library gives every connection a name of its own, so the
1581 * old one is freed rather than leaked. Only the application
1582 * knows what identifies a connection, which is why the library
1583 * does not do this itself.
1584 */
1585 {
1586 fr_socket_t *socket = &utt->conn->request->packet->socket;
1587
1588 talloc_const_free(utt->conn->name);
1589 utt->conn->name = fr_asprintf(utt->conn, "%s from %pV:%u to %pV:%u",
1590 (socket->type == SOCK_DGRAM) ? "DTLS" : "TLS",
1591 fr_box_ipaddr(socket->inet.src_ipaddr), socket->inet.src_port,
1592 fr_box_ipaddr(socket->inet.dst_ipaddr), socket->inet.dst_port);
1593 if (!utt->conn->name) goto finish;
1594
1595 DEBUG2("Connection is %s", utt->conn->name);
1596 }
1597
1598 /*
1599 * Both roles run the same handshake driver. Passing the request
1600 * to fr_tls_session_alloc_client() is what gives a client the
1601 * memory BIOs and the certificate validation callback which the
1602 * driver needs, see src/lib/tls/session.c.
1603 */
1604 if (utt->conn->client) {
1605 utt->conn->tls_session = fr_tls_session_alloc_client(utt->conn->request, utt->ssl_ctx, utt->conn->request);
1606 } else {
1607 INFO("Accepted connection from %pV on fd %d",
1608 fr_box_ipaddr(utt->conn->request->packet->socket.inet.src_ipaddr), utt->fd);
1609
1610 utt->conn->tls_session = fr_tls_session_alloc_server(utt->conn->request, utt->ssl_ctx, utt->conn->request,
1612 }
1613
1614 if (!utt->conn->tls_session) {
1615 PERROR("Failed creating the TLS session");
1616 goto finish;
1617 }
1618
1619 /*
1620 * Start the request with a new session, then run the
1621 * interpreter once so that the first frame yields.
1622 * unlang_interpret_mark_runnable() acts only on a
1623 * yielded frame.
1624 */
1625 /*
1626 * Bind the DTLS cookie to the socket this connection runs on.
1627 * The library hashes the whole structure with a key of its own
1628 * and never reads it, and the structure is what the rest of
1629 * the server uses to say which DTLS session a datagram belongs
1630 * to.
1631 */
1632 if (utt->conf.socket_type == SOCK_DGRAM) {
1633 utt->conn->tls_session->cookie = &utt->conn->request->packet->socket;
1634 }
1635
1636 if (fr_tls_connection_push(utt->conn) < 0) {
1637 PERROR("Failed starting new TLS connection");
1638 goto finish;
1639 }
1640
1641 (void) unlang_interpret(utt->conn->request, UNLANG_REQUEST_RESUME);
1642
1643 /*
1644 * A datagram connection starts with a datagram which was read
1645 * from the listening socket, because that is what named the
1646 * peer. The connection's socket never saw it, so hand it over
1647 * now that there is a connection to hand it to.
1648 */
1649 if (utt->first) {
1650 uint8_t *first = utt->first;
1651 size_t first_len = utt->first_len;
1652
1653 utt->first = NULL;
1654 utt->first_len = 0;
1655
1656 DEBUG3("Handing the connection the %zu byte datagram which named the peer", first_len);
1657 fr_tls_connection_recv(utt->conn, first, first_len);
1658 talloc_free(first);
1659 }
1660
1661 if (fr_event_post_insert(utt->el, _tls_runnable, utt) < 0) {
1662 PERROR("Failed adding the runnable handler to the event loop");
1663 goto finish;
1664 }
1665
1666 /*
1667 * The connection is started from inside the event loop rather
1668 * than here. Ending the previous connection left the loop
1669 * flagged as exiting, and fr_event_fd_insert() refuses to add a
1670 * socket to a loop in that state. fr_event_loop() clears the
1671 * flag as it starts, so a user event which fires immediately is
1672 * the first point at which the socket can be added.
1673 */
1674 if (fr_event_user_insert(utt, utt->el, &ev, true, _tls_connection_start, utt) < 0) {
1675 PERROR("Failed scheduling the start of the connection");
1676 goto finish;
1677 }
1678
1679 (void) fr_event_loop(utt->el);
1680
1681 ret = 0;
1682
1683finish:
1684 if (utt->ef) {
1685 (void) fr_event_fd_delete(utt->el, utt->fd, FR_EVENT_FILTER_IO);
1686 utt->ef = NULL;
1687 }
1688 (void) fr_event_post_delete(utt->el, _tls_runnable, utt);
1689
1690 /*
1691 * The user event is allocated in utt, which outlives the event
1692 * list. The destructor of the user event removes it from the
1693 * event list, so free it while the event list still exists.
1694 */
1695 TALLOC_FREE(ev);
1696
1697 /*
1698 * The connection frame is still yielded, so cancel the request to
1699 * unwind the stack before the request is freed.
1700 */
1701 if (utt->conn->request) unlang_interpret_signal(utt->conn->request, FR_SIGNAL_CANCEL);
1702
1703 /*
1704 * Empty the heap before the requests on it are freed. Popping
1705 * clears each entry's index, so nothing is left pointing at
1706 * memory the request pool is about to hand out again.
1707 */
1708 while (fr_heap_pop((void **)&stale, &utt->runnable) == 0) {
1709 if (!stale) break;
1710 }
1711 utt->yielded = 0;
1712
1713 TALLOC_FREE(utt->conn->tls_session);
1714 TALLOC_FREE(utt->conn->request);
1715
1716 if (utt->fd >= 0) {
1717 close(utt->fd);
1718 utt->fd = -1;
1719 }
1720
1721 return ret;
1722}
1723
1724/** Turn a comma separated list of names into the wire format ALPN uses
1725 *
1726 * Each name becomes one length octet followed by the name. There is no
1727 * terminator, so the caller takes the length from the array itself.
1728 *
1729 * @param[in] ctx to allocate in.
1730 * @param[in] names comma separated, in order of preference.
1731 * @return
1732 * - the list, whose talloc array length is the length of the list.
1733 * - NULL if a name is empty or longer than 255 octets.
1734 */
1735static unsigned char *tls_alpn_build(TALLOC_CTX *ctx, char const *names)
1736{
1737 unsigned char *alpn, *p;
1738 char const *q;
1739 size_t len;
1740
1741 /*
1742 * One length octet per name, and the names themselves. The
1743 * separators become those length octets, and the first name has
1744 * no separator before it, so one more octet than the string.
1745 */
1746 MEM(alpn = talloc_zero_array(ctx, unsigned char, strlen(names) + 1));
1747 p = alpn;
1748
1749 for (q = names; *q != '\0'; q += len) {
1750 len = strcspn(q, ",");
1751 if ((len == 0) || (len > 255)) {
1752 ERROR("Each ALPN protocol name must be between 1 and 255 characters");
1753 talloc_free(alpn);
1754 return NULL;
1755 }
1756
1757 *p++ = (unsigned char) len;
1758 memcpy(p, q, len);
1759 p += len;
1760
1761 if (q[len] == ',') len++; /* step over the separator */
1762 }
1763
1764 /*
1765 * A trailing separator, or a repeated one, leaves the array
1766 * longer than what was written into it. Shrink it so the array
1767 * length is the length of the list.
1768 */
1769 MEM(alpn = talloc_realloc(ctx, alpn, unsigned char, (size_t) (p - alpn)));
1770
1771 return alpn;
1772}
1773
1774/** Turn a comma separated list of names into ids of the test table
1775 *
1776 * @param[in] ctx to allocate the array in.
1777 * @param[in] names comma separated, in the order of preference.
1778 * @param[out] num number of ids returned.
1779 * @return
1780 * - the ids.
1781 * - NULL if a name is not in the table.
1782 */
1783static int *tls_alpn_ids(TALLOC_CTX *ctx, char const *names, size_t *num)
1784{
1785 int *ids;
1786 char const *q;
1787 size_t len, n = 0;
1788
1789 MEM(ids = talloc_zero_array(ctx, int, strlen(names) + 1));
1790
1791 for (q = names; *q != '\0'; q += len) {
1792 fr_tls_alpn_t const *entry;
1793
1794 len = strcspn(q, ",");
1795
1796 for (entry = unit_test_tls_alpn_table; entry->name; entry++) {
1797 if ((strlen(entry->name) == len) && (strncmp(entry->name, q, len) == 0)) break;
1798 }
1799
1800 if (!entry->name) {
1801 ERROR("ALPN name \"%.*s\" is not in the table of the test program", (int) len, q);
1802 talloc_free(ids);
1803 return NULL;
1804 }
1805
1806 ids[n++] = entry->id;
1807
1808 if (q[len] == ',') len++; /* step over the separator */
1809 }
1810
1811 *num = n;
1812
1813 return ids;
1814}
1815
1816int main(int argc, char *argv[])
1817{
1818 int ret = EXIT_SUCCESS;
1819 int c;
1820 char const *receipt_file = NULL;
1821 char const *command = NULL;
1822 char const *server = NULL;
1823 unsigned int count = 1;
1824 bool alert = false;
1825 bool invalid = false;
1826 bool nonblock = false;
1827 bool reject = false;
1828 bool network_fail = false;
1829 bool abort_pending = false;
1830 bool app_data = false;
1831 bool delay_tickets = false;
1832 bool hold = false;
1833 bool client = false;
1834 char const *alpn_names = NULL;
1835 bool alpn_required = false;
1836 bool alpn_raw = false;
1837 unsigned int i;
1838
1839 TALLOC_CTX *autofree;
1840 TALLOC_CTX *thread_ctx;
1841
1842 char *p;
1844
1845 fr_dict_t *dict = NULL;
1846 fr_dict_t const *dict_check;
1847
1848 virtual_server_t const *vs;
1849 CONF_SECTION *utt_cs;
1850
1851 unit_test_tls_t *utt = NULL;
1852 fr_tls_conf_t *conf = NULL;
1853
1854 /*
1855 * Must be called first, so the handler is called last
1856 */
1858
1860 thread_ctx = talloc_new(autofree);
1861
1863 if (!config) {
1864 fr_perror("unit_test_tls");
1865 fr_exit_now(EXIT_FAILURE);
1866 }
1867
1868 p = strrchr(argv[0], FR_DIR_SEP);
1869 if (!p) {
1870 main_config_name_set_default(config, argv[0], false);
1871 } else {
1872 main_config_name_set_default(config, p + 1, false);
1873 }
1874
1876
1877 if (fr_fault_setup(autofree, getenv("PANIC_ACTION"), argv[0], PANIC_ACTION_SIGNALS) < 0) {
1878 fr_perror("%s", config->name);
1879 fr_exit_now(EXIT_FAILURE);
1880 }
1881#ifdef NDEBUG
1883#endif
1884
1885 fr_debug_lvl = 0;
1886 fr_time_start();
1887
1888 /*
1889 * The tests should have only IPs, not host names.
1890 */
1892
1893 /*
1894 * We always log to stdout.
1895 */
1897 default_log.fd = STDOUT_FILENO;
1898 default_log.print_level = true;
1899
1900 /* Process the options. */
1901 while ((c = getopt(argc, argv, "aABc:Cd:D:e:hHIlL:Mn:NPQr:Rs:TxX")) != -1) {
1902 switch (c) {
1903 case 'A':
1904 alert = true;
1905 break;
1906
1907 case 'B':
1908 nonblock = true;
1909 break;
1910
1911 case 'N':
1912 network_fail = true;
1913 break;
1914
1915 case 'R':
1916 reject = true;
1917 break;
1918
1919 case 'Q':
1920 abort_pending = true;
1921 break;
1922
1923 case 'c':
1924 count = (unsigned int) atoi(optarg);
1925 if (!count) {
1926 fprintf(stderr, "Invalid value \"%s\" for -c\n", optarg);
1927 fr_exit_now(EXIT_FAILURE);
1928 }
1929 break;
1930
1931 case 'C':
1932 check_config = true;
1933 break;
1934
1935 case 'd':
1937 break;
1938
1939 case 'D':
1941 break;
1942
1943 case 'h':
1944 usage(config, EXIT_SUCCESS);
1945 break;
1946
1947 case 'I':
1948 invalid = true;
1949 break;
1950
1951 case 'a':
1952 alpn_raw = true;
1953 break;
1954
1955 case 'l':
1956 alpn_required = true;
1957 break;
1958
1959 case 'L':
1960 alpn_names = optarg;
1961 break;
1962
1963 case 'M':
1964 talloc_enable_leak_report();
1965 break;
1966
1967 case 'n':
1968 config->name = optarg;
1969 break;
1970
1971 case 'H':
1972 hold = true;
1973 break;
1974
1975 case 'P':
1976 app_data = true;
1977 break;
1978
1979 case 'T':
1980 delay_tickets = true;
1981 break;
1982
1983 case 'e':
1984 command = optarg;
1985 break;
1986
1987 case 'r':
1988 receipt_file = optarg;
1989 break;
1990
1991 case 's':
1992 server = optarg;
1993 break;
1994
1995 case 'X':
1996 fr_debug_lvl += 2;
1997 default_log.print_level = true;
1998 break;
1999
2000 case 'x':
2001 fr_debug_lvl++;
2002 if (fr_debug_lvl > 2) default_log.print_level = true;
2003 break;
2004
2005 default:
2006 usage(config, EXIT_FAILURE);
2007 break;
2008 }
2009 }
2010
2011 if (receipt_file && (fr_unlink(receipt_file) < 0)) {
2012 fr_perror("%s", config->name);
2014 }
2015
2016 /*
2017 * A mismatch between the OpenSSL headers used at build time and the
2018 * linked OpenSSL library makes this program exit now, rather than
2019 * crash later.
2020 */
2022
2023 /*
2024 * fr_openssl_init() must be called before *ANY* OpenSSL functions are
2025 * used, which is why
2026 * fr_openssl_init() is called so early.
2027 */
2028 if (fr_openssl_init() < 0) EXIT_WITH_FAILURE;
2029
2031
2032 /*
2033 * Mismatch between the binary and the libraries it links against
2034 */
2036 fr_perror("%s", config->name);
2038 }
2039
2040 /*
2041 * Initialise the dynamic loader infrastructure, which the config
2042 * file parser uses.
2043 */
2044 modules_init(config->lib_dir);
2045
2046 if (!fr_dict_global_ctx_init(NULL, true, config->dict_dir)) {
2047 fr_perror("%s", config->name);
2049 }
2050
2052 fr_perror("%s", config->name);
2054 }
2055
2056 if (fr_tls_dict_init() < 0) EXIT_WITH_FAILURE;
2057
2058 /*
2059 * Load the custom dictionary
2060 */
2061 if (fr_dict_read(dict, config->confdir, FR_DICTIONARY_FILE) == -1) {
2062 PERROR("Failed to initialize the dictionaries");
2064 }
2065
2067 fr_perror("%s", config->name);
2069 }
2070
2071 if (request_global_init() < 0) {
2072 fr_perror("%s", config->name);
2074 }
2075
2076 /*
2077 * The triggers are run-time expansions, so the triggers need the
2078 * main event loop.
2079 */
2080 if (main_loop_init() < 0) {
2081 PERROR("Failed initialising main event loop");
2083 }
2084
2085 if (unlang_global_init() < 0) {
2086 fr_perror("%s", config->name);
2088 }
2089
2090 if (modules_rlm_init() < 0) {
2091 fr_perror("%s", config->name);
2093 }
2094
2095 if (virtual_servers_init() < 0) {
2096 fr_perror("%s", config->name);
2098 }
2099
2101
2102 MEM(utt = talloc_zero(autofree, unit_test_tls_t));
2103 utt->sockfd = utt->fd = -1;
2104 utt->ret = EXIT_SUCCESS;
2105 utt->count = count;
2106 utt->alert = alert;
2107 utt->invalid = invalid;
2108 utt->nonblock = nonblock;
2109 utt->app_data = app_data;
2110 utt->hold = hold;
2111 utt->reject = reject;
2112 utt->network_fail = network_fail;
2113 utt->abort_pending = abort_pending;
2114
2115
2116 /*
2117 * Bootstrap and instantiate the virtual servers and the modules
2118 * that the virtual servers use. The TLS subsections name a
2119 * virtual server, so server_init() has to run before
2120 * cf_section_parse() reads the `unit_test_tls` section.
2121 */
2122 if (server_init(config->root_cs, config->confdir, dict) < 0) EXIT_WITH_FAILURE;
2123
2124 vs = virtual_server_find("tls");
2125 if (!vs) {
2126 ERROR("Cannot find virtual server 'tls'");
2128 }
2129
2130 dict_check = virtual_server_dict_by_name("tls");
2131 if (!dict_check || !fr_dict_compatible(dict_check, dict_tls)) {
2132 ERROR("Virtual server 'tls' must have 'namespace = tls'");
2134 }
2135
2136 /*
2137 * Parse the settings that steer the test program, with the TLS
2138 * configuration for each role as a subsection. The TLS rows
2139 * resolve the `virtual_server` item through
2140 * virtual_server_cf_parse(), so server_init() had to run first.
2141 * cf_section_parse_pass2() then resolves the expansions in the
2142 * TLS subsections.
2143 */
2144 utt_cs = cf_section_find(config->root_cs, "unit_test_tls", NULL);
2145 if (!utt_cs) {
2146 ERROR("Cannot find a top-level 'unit_test_tls { ... }' section in %s.conf", config->name);
2148 }
2149
2151
2152 if ((cf_section_parse(utt, &utt->conf, utt_cs) < 0) ||
2153 (cf_section_parse_pass2(&utt->conf, utt_cs) < 0)) {
2154 cf_log_perr(utt_cs, "Failed parsing the 'unit_test_tls' section");
2156 }
2157
2158 /*
2159 * Resolve `transport` into the socket it names, and into the
2160 * socket type which the TLS configuration below is given.
2161 */
2162 if (strcmp(utt->conf.transport, "tcp") == 0) {
2163 utt->conf.socket_type = SOCK_STREAM;
2164 utt->conf.ipaddr = utt->conf.tcp.ipaddr;
2165 utt->conf.port = utt->conf.tcp.port;
2166
2167 } else if (strcmp(utt->conf.transport, "udp") == 0) {
2168 utt->conf.socket_type = SOCK_DGRAM;
2169 utt->conf.ipaddr = utt->conf.udp.ipaddr;
2170 utt->conf.port = utt->conf.udp.port;
2171
2172 } else {
2173 cf_log_err(utt_cs, "Invalid transport name \"%s\", expected \"tcp\" or \"udp\"",
2174 utt->conf.transport);
2176 }
2177
2178 /*
2179 * -s turns the program around: instead of listening for a
2180 * connection, it makes one.
2181 */
2182 if (server) {
2183 utt->client = client = true;
2184
2185 if (fr_inet_pton_port(&utt->server_ipaddr, &utt->server_port, server,
2186 -1, AF_UNSPEC, true, false) < 0) {
2187 PERROR("Invalid value \"%s\" for -s", server);
2189 }
2190
2191 /*
2192 * fr_inet_pton_port() clears the port before it starts,
2193 * so a missing port is zero here, and not the default.
2194 */
2195 if (!utt->server_port) utt->server_port = utt->conf.port;
2196
2197 if (!utt->server_port) {
2198 ERROR("No port given in -s, and no 'port' in the 'unit_test_tls' section");
2200 }
2201 }
2202
2203 conf = client ? utt->conf.client : utt->conf.server;
2204 if (!conf) {
2205 cf_log_err(utt_cs, "Cannot run as %s, the 'unit_test_tls' section has no '%s { ... }' subsection",
2206 client ? "client" : "server", client ? "client" : "server");
2208 }
2209
2210 conf->delayed_tickets = delay_tickets;
2211
2212 /*
2213 * -L sets the ALPN list from names in the table of the test program, which is how an application
2214 * that uses the library's table sets it. The `alpn` section of the configuration file does the same
2215 * for the names it lists. -a sets the raw fields instead, which is how an application sets them
2216 * when it does not use a table. See src/lib/tls/alpn.c.
2217 *
2218 * -l sets `alpn_required` for the raw fields. With a table, the library derives `alpn_required`
2219 * from the entries.
2220 */
2221 if (alpn_names && !alpn_raw) {
2222 int *ids;
2223 size_t num = 0;
2224
2225 ids = tls_alpn_ids(utt, alpn_names, &num);
2226 if (!ids) EXIT_WITH_FAILURE;
2227
2228 if (fr_tls_alpn_set(conf, conf, unit_test_tls_alpn_table, ids, num) < 0) EXIT_WITH_FAILURE;
2229
2230 talloc_free(ids);
2231 } else if (alpn_names) {
2232 utt->alpn = tls_alpn_build(utt, alpn_names);
2233 if (!utt->alpn) EXIT_WITH_FAILURE;
2234
2235 conf->alpn = utt->alpn;
2236 conf->sizeof_alpn = talloc_array_length(utt->alpn);
2237 }
2238 if (!conf->alpn_table) conf->alpn_required = alpn_required;
2239
2240 /*
2241 * The transport is set by the application for the same reason
2242 * the ALPN strings are: one `tls { ... }` section is parsed by
2243 * the same rules everywhere, and only the application knows
2244 * what it opened the socket as.
2245 */
2246 conf->socket_type = utt->conf.socket_type;
2247
2248 utt->ssl_ctx = fr_tls_ctx_alloc(conf, client);
2249 if (!utt->ssl_ctx) {
2250 cf_log_perr(utt_cs, "Failed creating the TLS context");
2252 }
2253
2254 /*
2255 * The configuration parsed without error, so exit with success.
2256 */
2257 if (check_config) {
2258 DEBUG("Configuration appears to be OK");
2259 goto cleanup;
2260 }
2261
2262 utt->el = main_loop_event_list();
2263 fr_assert(utt->el != NULL);
2264
2265
2267
2268 /*
2269 * Simulate thread-specific instantiation
2270 */
2272 if (fr_thread_instantiate(thread_ctx, utt->el) < 0) {
2273 fr_perror("%s", config->name);
2275 }
2276
2277 if (modules_rlm_coord_attach(utt->el) < 0) {
2278 fr_perror("%s", config->name);
2280 }
2281
2282 if (fr_coord_pre_event_insert(utt->el) < 0) {
2283 fr_strerror_const("Failed adding coordinator pre-check to event list");
2285 }
2286
2287 if (fr_coord_post_event_insert(utt->el) < 0) {
2288 fr_strerror_const("Failed adding coordinator post-check to event list");
2290 }
2291
2292 /*
2293 * Set the panic action (if required)
2294 */
2295 {
2296 char const *panic_action = NULL;
2297
2298 panic_action = getenv("PANIC_ACTION");
2299 if (!panic_action) panic_action = config->panic_action;
2300
2302 fr_perror("%s", config->name);
2304 }
2305 }
2306
2307 setlinebuf(stdout); /* line buffered output */
2308
2309 /*
2310 * One interpreter, one runnable heap and one request for the
2311 * whole connection. The unit_test_tls_t documentation says why.
2312 */
2313 MEM(utt->runnable = fr_heap_talloc_alloc(utt, fr_pointer_cmp, request_t, runnable, 0));
2314
2315 utt->intp = unlang_interpret_init(utt, utt->el,
2317 .init_internal = _request_init_internal,
2318
2319 .done_external = _request_done_external,
2320 .done_internal = _request_done_internal,
2321 .done_detached = _request_done_detached,
2322
2323 .detach = _request_detach,
2324 .yield = _request_yield,
2325 .resume = _request_resume,
2326 .mark_runnable = _request_runnable,
2327 .scheduled = _request_scheduled,
2328 }, utt);
2329 if (!utt->intp) {
2330 fr_perror("%s", config->name);
2332 }
2333
2334 /*
2335 * Subrequests created by the TLS code inherit the thread default,
2336 * so the thread default has to point at the connection's
2337 * interpreter.
2338 */
2340
2341 /*
2342 * A server has one listening socket for every connection it
2343 * accepts, so it is opened once, here.
2344 */
2345 if (!utt->client && (tls_socket_open(utt) < 0)) EXIT_WITH_FAILURE;
2346
2347 /*
2348 * A server starts the command once it is listening. A client
2349 * starts it once the first connection succeeds, see
2350 * tls_connection_run().
2351 */
2352 utt->command = command;
2353 if (!utt->client && command && (tls_command_start(utt, command) < 0)) EXIT_WITH_FAILURE;
2354
2355 for (i = 0; i < utt->count; i++) {
2357
2358 if (utt->ret != EXIT_SUCCESS) break;
2359 }
2360
2361 tls_command_wait(utt);
2362
2363 ret = utt->ret;
2364
2365cleanup:
2366 if (utt) {
2367 /*
2368 * tls_connection_run() cleans up everything which belongs
2369 * to one connection. What is left here is what outlives
2370 * them.
2371 */
2372 if (utt->ssl_ctx) SSL_CTX_free(utt->ssl_ctx);
2373
2374 if (utt->sockfd >= 0) close(utt->sockfd);
2375
2376 /*
2377 * A failure left the client running. The reap below
2378 * signals it if it doesn't exit by itself.
2379 */
2380 if (utt->command_pid && !utt->command_exited) {
2382 (void) fr_event_pid_reap(utt->el, utt->command_pid, NULL, NULL);
2383 }
2384 }
2385
2387
2388 /*
2389 * Detach from coordinators.
2390 */
2391 if (utt && utt->el && (modules_rlm_coord_detach() > 0)) {
2392 if (unlikely(fr_coord_close_event_insert(utt->el) < 0)) {
2393 ERROR("Failed setting up coordinator close events");
2394 }
2395 fr_event_loop(utt->el);
2396 }
2397
2398 /*
2399 * Free thread data
2400 */
2401 talloc_free(thread_ctx);
2402
2404
2406
2407 if (utt && utt->el) fr_event_list_reap_signal(utt->el, fr_time_delta_from_sec(5), SIGKILL);
2408
2410
2412
2413 server_free();
2414
2415 /*
2416 * Virtual servers need to be freed before modules
2417 * as state entries containing data with module-specific
2418 * destructors may exist.
2419 */
2421
2423
2425
2426 fr_tls_dict_free();
2427
2429
2430 if (fr_dict_free(&dict, __FILE__) < 0) {
2431 fr_perror("unit_test_tls - dict");
2432 ret = EXIT_FAILURE;
2433 }
2434
2435 fr_openssl_free();
2436
2437 if (receipt_file && (ret == EXIT_SUCCESS) && (fr_touch(NULL, receipt_file, 0644, true, 0755) <= 0)) {
2438 fr_perror("unit_test_tls");
2439 ret = EXIT_FAILURE;
2440 }
2441
2442 if (talloc_free(autofree) < 0) {
2443 fr_perror("unit_test_tls - autofree");
2444 ret = EXIT_FAILURE;
2445 }
2446
2447 /*
2448 * Ensure our atexit handlers run before any other
2449 * atexit handlers registered by third party libraries.
2450 */
2452
2453 return ret;
2454}
2455
2456/*
2457 * Display the syntax for starting this program.
2458 */
2459static NEVER_RETURNS void usage(main_config_t const *config, int status)
2460{
2461 FILE *output = status ? stderr : stdout;
2462
2463 fprintf(output, "Usage: %s [options]\n", config->name);
2464 fprintf(output, "Options:\n");
2465 fprintf(output, " -A Reject the peer with a fatal TLS alert on the last connection,\n");
2466 fprintf(output, " rather than completing the handshake. With -c 2 the first\n");
2467 fprintf(output, " connection fills the session cache, so the alert then has a\n");
2468 fprintf(output, " session to clear. Used to test the alert and clear paths.\n");
2469 fprintf(output, " -B Put the connection socket in non-blocking mode, so that a read()\n");
2470 fprintf(output, " or a write() which would wait returns EAGAIN instead. The event\n");
2471 fprintf(output, " loop already waits for the socket to be readable or writable, so\n");
2472 fprintf(output, " this exercises the EAGAIN paths rather than changing what runs.\n");
2473 fprintf(output, " -I Mark the session invalid part way through the handshake on the\n");
2474 fprintf(output, " last connection, the way fr_tls_session_msg_cb() marks a record\n");
2475 fprintf(output, " FreeRADIUS refuses. The next round then refuses to continue, and\n");
2476 fprintf(output, " sends the peer a fatal alert saying so.\n");
2477 fprintf(output, " -R Reject the session once the handshake has succeeded on the last\n");
2478 fprintf(output, " connection, as policy would. The cached session is then cleared\n");
2479 fprintf(output, " rather than stored. With -c 2 the first connection fills the\n");
2480 fprintf(output, " cache and the second resumes from it before being rejected, so\n");
2481 fprintf(output, " the clear then has a loaded session to remove.\n");
2482 fprintf(output, " -Q Free the connection on the last connection once the handshake\n");
2483 fprintf(output, " has succeeded, while `store session` is still queued, to\n");
2484 fprintf(output, " exercise the path that discards queued cache operations.\n");
2485 fprintf(output, " -N Fail the session with a network error on the last connection,\n");
2486 fprintf(output, " once the handshake succeeds, to simulate the peer closing the\n");
2487 fprintf(output, " connection. With -c 2 the second connection loads a session\n");
2488 fprintf(output, " from the cache. A network error does not clear the loaded\n");
2489 fprintf(output, " session, and the session stays in the cache.\n");
2490 fprintf(output, " -H Once the connection is up, send nothing and hold it open.\n");
2491 fprintf(output, " A peer which is still owed a session ticket or a byte of\n");
2492 fprintf(output, " application data then waits for something which never\n");
2493 fprintf(output, " arrives, which is what exercises the post-handshake timer.\n");
2494 fprintf(output, " -c <count> Run <count> connections, one after another. Session resumption\n");
2495 fprintf(output, " needs two: one to fill the cache, one to resume from it.\n");
2496 fprintf(output, " -C Check configuration and exit.\n");
2497 fprintf(output, " -d <confdir> Configuration file directory. (defaults to " CONFDIR ").\n");
2498 fprintf(output, " -D <dict_dir> Dictionary files are in \"dict_dir/*\".\n");
2499 fprintf(output, " -e <command> Run <command> in a shell. A server runs it once it is\n");
2500 fprintf(output, " listening, so <command> can be what connects to the server,\n");
2501 fprintf(output, " such as openssl s_client. If <command> exits without\n");
2502 fprintf(output, " connecting, the server fails instead of waiting. With -s,\n");
2503 fprintf(output, " it runs once the first connection succeeds. Either way,\n");
2504 fprintf(output, " unit_test_tls waits for <command> to exit before it exits.\n");
2505 fprintf(output, " -h Print this help message.\n");
2506 fprintf(output, " -M Enable talloc leak reporting.\n");
2507 fprintf(output, " -n <name> Read ${confdir}/name.conf instead of ${confdir}/unit_test_tls.conf.\n");
2508 fprintf(output, " -P Server only. Send one byte of application data, 0x00, once the\n");
2509 fprintf(output, " handshake is done. A server sends every session ticket before\n");
2510 fprintf(output, " its first byte of application data, so this tells a client that\n");
2511 fprintf(output, " no ticket is still on its way.\n");
2512 fprintf(output, " -r <receipt_file> Create <receipt_file> when the program exits successfully.\n");
2513 fprintf(output, " -T Delay stateless TLS 1.3 session tickets, as EAP does. The server\n");
2514 fprintf(output, " sends none in the handshake.\n");
2515 fprintf(output, " -s <server[:port]> Connect to <server> as a TLS client, instead of listening\n");
2516 fprintf(output, " for a connection. Reads the 'tls client' section. The port\n");
2517 fprintf(output, " defaults to 'port' from the 'unit_test_tls' section.\n");
2518 fprintf(output, " -X Turn on full debugging.\n");
2519 fprintf(output, " -x Turn on additional debugging. (-xx gives more debugging).\n");
2520
2521 fr_exit_now(status);
2522}
static int const char char buffer[256]
Definition acutest.h:641
int n
Definition acutest.h:642
int fr_atexit_global_setup(void)
Setup the atexit handler, should be called at the start of a program's execution.
Definition atexit.c:179
int fr_atexit_global_trigger_all(void)
Cause all global free triggers to fire.
Definition atexit.c:310
#define fr_atexit_thread_trigger_all(...)
Definition atexit.h:236
static uint8_t request[4]
#define UNCONST(_type, _ptr)
Remove const qualification from a pointer.
Definition build.h:203
#define RCSID(id)
Definition build.h:609
#define NEVER_RETURNS
Should be placed before the function return type.
Definition build.h:413
#define unlikely(_x)
Definition build.h:492
#define UNUSED
Definition build.h:415
bool check_config
Definition cf_file.c:61
int cf_section_parse(TALLOC_CTX *ctx, void *base, CONF_SECTION *cs)
Parse a configuration section into user-supplied variables.
Definition cf_parse.c:1360
int cf_section_parse_pass2(void *base, CONF_SECTION *cs)
Fixup xlat expansions and attributes.
Definition cf_parse.c:1680
#define CONF_PARSER_TERMINATOR
Definition cf_parse.h:722
cf_parse_t func
Override default parsing behaviour for the specified type with a custom parsing function.
Definition cf_parse.h:666
#define FR_CONF_OFFSET(_name, _struct, _field)
conf_parser_t which parses a single CONF_PAIR, writing the result to a field in a struct
Definition cf_parse.h:280
conf_parser_flags_t flags
Flags which control parsing behaviour.
Definition cf_parse.h:655
@ CONF_FLAG_OK_MISSING
OK if it's missing.
Definition cf_parse.h:491
#define FR_CONF_SUBSECTION_ALLOC(_name, _flags, _struct, _field, _subcs)
conf_parser_t which allocates a struct and populates it from a subsection
Definition cf_parse.h:384
#define cf_section_rules_push(_cs, _rule)
Definition cf_parse.h:754
#define FR_CONF_OFFSET_REF(_struct, _field, _subcs)
conf_parser_t which populates a sub-struct using a CONF_SECTION
Definition cf_parse.h:337
#define FR_CONF_OFFSET_SUBSECTION(_name, _flags, _struct, _field, _subcs)
conf_parser_t which populates a sub-struct using a CONF_SECTION
Definition cf_parse.h:309
#define FR_CONF_OFFSET_TYPE_FLAGS(_name, _type, _flags, _struct, _field)
conf_parser_t which parses a single CONF_PAIR, writing the result to a field in a struct
Definition cf_parse.h:238
Defines a CONF_PAIR to C data type mapping.
Definition cf_parse.h:649
A section grouping multiple CONF_PAIR.
Definition cf_priv.h:106
CONF_PAIR * cf_pair_alloc(CONF_SECTION *parent, char const *attr, char const *value, fr_token_t op, fr_token_t lhs_quote, fr_token_t rhs_quote)
Allocate a CONF_PAIR.
Definition cf_util.c:1487
CONF_SECTION * cf_section_find(CONF_SECTION const *cs, char const *name1, char const *name2)
Find a CONF_SECTION with name1 and optionally name2.
Definition cf_util.c:1247
#define cf_log_err(_cf, _fmt,...)
Definition cf_util.h:340
#define cf_log_perr(_cf, _fmt,...)
Definition cf_util.h:347
#define cf_section_alloc(_ctx, _parent, _name1, _name2)
Definition cf_util.h:198
TALLOC_CTX * autofree
Definition common.c:29
fr_dict_t * dict
Definition common.c:31
int fr_coords_create(TALLOC_CTX *ctx, fr_event_list_t *el)
Start coordinators in single threaded mode.
Definition coord.c:626
void fr_coords_destroy(void)
Clean up coordinators in single threaded mode.
Definition coord.c:608
int fr_coord_close_event_insert(fr_event_list_t *el)
Definition coord.c:907
int fr_coord_post_event_insert(fr_event_list_t *el)
Insert instance specific post-event callbacks.
Definition coord.c:863
int fr_coord_pre_event_insert(fr_event_list_t *el)
Insert instance specific pre-event callbacks.
Definition coord.c:838
#define fr_dbuff_in_bytes(_dbuff_or_marker,...)
Copy a byte sequence into a dbuff or marker.
Definition dbuff.h:1518
static char panic_action[512]
The command to execute when panicking.
Definition debug.c:66
void fr_disable_null_tracking_on_free(TALLOC_CTX *ctx)
Disable the null tracking context when a talloc chunk is freed.
Definition debug.c:1031
void fr_talloc_fault_setup(void)
Register talloc fault handlers.
Definition debug.c:1047
int fr_fault_setup(TALLOC_CTX *ctx, char const *cmd, char const *program, unsigned long fault_signals)
Registers signal handlers to execute panic_action on fatal signal.
Definition debug.c:1071
#define PANIC_ACTION_SIGNALS
Definition debug.h:133
#define MEM(x)
Definition debug.h:38
#define fr_exit_now(_x)
Exit without calling atexit() handlers, producing a log message in debug builds.
Definition debug.h:272
void dependency_version_print(void)
Definition dependency.c:364
#define ERROR(fmt,...)
Definition dhcpclient.c:40
static int sockfd
Definition dhcpclient.c:55
#define DEBUG(fmt,...)
Definition dhcpclient.c:38
static NEVER_RETURNS void usage(void)
Definition dhcpclient.c:113
#define fr_dict_autofree(_to_free)
Definition dict.h:942
bool fr_dict_compatible(fr_dict_t const *dict1, fr_dict_t const *dict2)
See if two dictionaries have the same end parent.
Definition dict_util.c:2956
fr_dict_t const ** out
Where to write a pointer to the loaded/resolved fr_dict_t.
Definition dict.h:329
int fr_dict_read(fr_dict_t *dict, char const *dict_dir, char const *filename))
Read supplementary attribute definitions into an existing dictionary.
int fr_dict_free(fr_dict_t **dict, char const *dependent)
Decrement the reference count on a previously loaded dictionary.
Definition dict_util.c:4474
#define fr_dict_autoload(_to_load)
Definition dict.h:939
#define DICT_AUTOLOAD_TERMINATOR
Definition dict.h:335
fr_dict_gctx_t * fr_dict_global_ctx_init(TALLOC_CTX *ctx, bool free_at_exit, char const *dict_dir))
Initialise the global protocol hashes.
Definition dict_util.c:4858
Specifies a dictionary which must be loaded/loadable for the module to function.
Definition dict.h:328
int fr_dict_internal_afrom_file(fr_dict_t **out, char const *dict_subdir, char const *dependent)
(Re-)Initialize the special internal dictionary
#define fr_event_fd_insert(...)
Definition event.h:251
#define fr_event_filter_update(...)
Definition event.h:243
#define fr_event_pid_reap(...)
Definition event.h:278
#define FR_EVENT_RESUME(_s, _f)
Re-add the filter for a func from kevent.
Definition event.h:135
#define FR_EVENT_SUSPEND(_s, _f)
Temporarily remove the filter for a func from kevent.
Definition event.h:119
#define fr_event_pid_wait(...)
Definition event.h:272
@ FR_EVENT_FILTER_IO
Combined filter for read/write functions/.
Definition event.h:87
#define fr_event_user_insert(_ctx, _el, _ev_p, _trigger, _callback, _uctx)
Definition event.h:285
Callbacks for the FR_EVENT_FILTER_IO filter.
Definition event.h:192
Structure describing a modification to a filter's state.
Definition event.h:100
int fr_heap_insert(fr_heap_t **hp, void *data)
Insert a new element into the heap.
Definition heap.c:149
int fr_heap_pop(void **out, fr_heap_t **hp)
Remove a node from the heap.
Definition heap.c:359
static bool fr_heap_entry_inserted(fr_heap_index_t heap_idx)
Check if an entry is inserted into a heap.
Definition heap.h:126
#define fr_heap_talloc_alloc(_ctx, _cmp, _talloc_type, _field, _init)
Creates a heap that verifies elements are of a specific talloc type.
Definition heap.h:117
The main heap structure.
Definition heap.h:68
talloc_free(hp)
int fr_ipaddr_from_sockaddr(fr_ipaddr_t *ipaddr, uint16_t *port, struct sockaddr_storage const *sa, socklen_t salen)
Convert sockaddr to our internal ip address representation.
Definition inet.c:1448
bool fr_hostname_lookups
hostname -> IP lookups?
Definition inet.c:52
int fr_inet_pton_port(fr_ipaddr_t *out, uint16_t *port_out, char const *value, ssize_t inlen, int af, bool resolve, bool mask)
Parses IPv4/6 address + port, to fr_ipaddr_t and integer (port)
Definition inet.c:944
char * fr_inet_ntop(char out[static FR_IPADDR_STRLEN], size_t outlen, fr_ipaddr_t const *addr)
Print the address portion of a fr_ipaddr_t.
Definition inet.c:1025
bool fr_reverse_lookups
IP -> hostname lookups?
Definition inet.c:51
#define FR_IPADDR_STRLEN
Like INET6_ADDRSTRLEN but includes space for the textual Zone ID.
Definition inet.h:89
int af
Address family.
Definition inet.h:64
IPv4/6 prefix.
rlm_rcode_t unlang_interpret(request_t *request, bool running)
Run the interpreter for a current request.
Definition interpret.c:1314
void unlang_interpret_set(request_t *request, unlang_interpret_t *intp)
Set a specific interpreter for a request.
Definition interpret.c:2771
void unlang_interpret_set_thread_default(unlang_interpret_t *intp)
Set the default interpreter for this thread.
Definition interpret.c:2802
unlang_interpret_t * unlang_interpret_init(TALLOC_CTX *ctx, fr_event_list_t *el, unlang_request_func_t *funcs, void *uctx)
Initialize a unlang compiler / interpret.
Definition interpret.c:2722
void unlang_interpret_signal(request_t *request, fr_signal_t action)
Send a signal (usually stop) to a request.
Definition interpret.c:1806
#define UNLANG_REQUEST_RESUME
Definition interpret.h:48
External functions provided by the owner of the interpret.
Definition interpret.h:116
el_self ties the lifetime of the event list to the interpreter
int server_init(CONF_SECTION *cs, char const *conf_dir, fr_dict_t *dict)
Initialize src/lib/server/.
Definition base.c:42
void server_free(void)
Free src/lib/server/.
Definition base.c:137
Describes a host allowed to send packets to the server.
Definition client.h:80
void vlog_request(fr_log_type_t type, fr_log_lvl_t lvl, request_t *request, char const *file, int line, char const *fmt, va_list ap, void *uctx)
Send a log message to its destination, possibly including fields from the request.
Definition log.c:293
#define PERROR(_fmt,...)
Definition log.h:233
#define DEBUG3(_fmt,...)
Definition log.h:271
#define RDEBUG3(fmt,...)
Definition log.h:360
#define RPEDEBUG(fmt,...)
Definition log.h:393
Definition log.h:70
int fr_packet_pairs_from_packet(TALLOC_CTX *ctx, fr_pair_list_t *list, fr_packet_t const *packet)
Allocate a "Net." struct with src/dst host and port.
Definition packet.c:91
int unlang_global_init(void)
Definition base.c:158
int fr_event_post_delete(fr_event_list_t *el, fr_event_post_cb_t callback, void *uctx)
Delete a post-event callback from the event list.
Definition event.c:2106
#define fr_time()
Definition event.c:61
unsigned int fr_event_list_reap_signal(fr_event_list_t *el, fr_time_delta_t timeout, int signal)
Send a signal to all the processes we have in our reap list, and reap them.
Definition event.c:1759
void fr_event_loop_exit(fr_event_list_t *el, int code)
Signal an event loop exit with the specified code.
Definition event.c:2463
int fr_event_fd_delete(fr_event_list_t *el, int fd, fr_event_filter_t filter)
Remove a file descriptor from the event loop.
Definition event.c:1244
int fr_event_loop(fr_event_list_t *el)
Run an event loop.
Definition event.c:2485
int fr_event_post_insert(fr_event_list_t *el, fr_event_post_cb_t callback, void *uctx)
Add a post-event callback to the event list.
Definition event.c:2083
A file descriptor/filter event.
Definition event.c:282
Stores all information relating to an event list.
Definition event.c:415
Callbacks for kevent() user events.
Definition event.c:363
int fr_unlink(char const *filename)
Remove a regular file from the filesystem.
Definition file.c:366
ssize_t fr_touch(int *fd_out, char const *filename, mode_t mode, bool mkdir, mode_t dir_mode)
Create an empty file.
Definition file.c:322
int fr_debug_lvl
Definition log.c:41
fr_log_t default_log
Definition log.c:308
@ L_DST_STDOUT
Log to stdout.
Definition log.h:75
fr_packet_t * fr_packet_alloc(TALLOC_CTX *ctx, bool new_vector)
Allocate a new fr_packet_t.
Definition packet.c:38
Minimal data structure to use the new code.
Definition listen.h:80
int main_config_free(main_config_t **config)
main_config_t * main_config_alloc(TALLOC_CTX *ctx)
Allocate a main_config_t struct, setting defaults.
void main_config_name_set_default(main_config_t *config, char const *name, bool overwrite_config)
Set the server name.
int main_config_init(main_config_t *config)
void main_config_confdir_set(main_config_t *config, char const *name)
Set the global radius config directory.
void main_config_dict_dir_set(main_config_t *config, char const *name)
Set the global dictionary directory.
Main server configuration.
Definition main_config.h:59
fr_event_list_t * main_loop_event_list(void)
Return the main loop event list.
Definition main_loop.c:173
int main_loop_init(void)
Initialise the main event loop, setting up signal handlers.
Definition main_loop.c:262
void main_loop_free(void)
Definition main_loop.c:198
unsigned short uint16_t
@ FR_TYPE_IPV4_ADDR
32 Bit IPv4 Address.
@ FR_TYPE_IPV6_ADDR
128 Bit IPv6 Address.
@ FR_TYPE_COMBO_IP_ADDR
IPv4 or IPv6 address depending on length.
unsigned int uint32_t
long int ssize_t
unsigned char uint8_t
unsigned long int size_t
fr_cmp_ret_t fr_pointer_cmp(void const *a, void const *b)
Compares two pointers.
Definition misc.c:449
int fr_nonblock(UNUSED int fd)
Definition misc.c:293
int fr_blocking(UNUSED int fd)
Definition misc.c:298
int modules_rlm_coord_attach(fr_event_list_t *el)
Runs the coord_attach method of all registered backend modules.
Definition module_rlm.c:992
int modules_rlm_free(void)
Cleanup all global structures.
int modules_rlm_coord_detach(void)
Runs the coord_detach method of all registered backend modules.
Definition module_rlm.c:999
int modules_rlm_init(void)
Initialise the module list structure.
char * fr_asprintf(TALLOC_CTX *ctx, char const *fmt,...)
Special version of asprintf which implements custom format specifiers.
Definition print.c:883
static const conf_parser_t config[]
Definition base.c:164
#define fr_assert(_expr)
Definition rad_assert.h:37
#define DEBUG2(fmt,...)
#define INFO(fmt,...)
Definition radict.c:67
#define WIFEXITED(stat_val)
Definition radiusd.c:66
#define WEXITSTATUS(stat_val)
Definition radiusd.c:63
static bool cleanup
Definition radsniff.c:59
static rs_t * conf
Definition radsniff.c:52
rlm_rcode_t
Return codes indicating the result of the module call.
Definition rcode.h:44
int request_global_init(void)
Definition request.c:614
int request_detach(request_t *child)
Unlink a subrequest from its parent.
Definition request.c:560
#define request_local_alloc_internal(_ctx, _args)
Allocate a new internal request outside of the request pool.
Definition request.h:344
@ REQUEST_ACTIVE
Request is active (running or runnable)
Definition request.h:89
void fr_schedule_worker_id_set(int id)
Explicitly set the worker id for the current thread.
Definition schedule.c:122
@ FR_SIGNAL_CANCEL
Request has been cancelled.
Definition signal.h:40
int fr_socket_server_tcp(fr_ipaddr_t const *src_ipaddr, uint16_t *src_port, char const *port_name, bool async)
Open an IPv4/IPv6 TCP socket.
Definition socket.c:943
int fr_socket_client_udp(char const *ifname, fr_ipaddr_t *src_ipaddr, uint16_t *src_port, fr_ipaddr_t const *dst_ipaddr, uint16_t dst_port, bool async)
Establish a connected UDP socket.
Definition socket.c:611
int fr_socket_server_udp(fr_ipaddr_t const *src_ipaddr, uint16_t *src_port, char const *port_name, bool async)
Open an IPv4/IPv6 unconnected UDP socket.
Definition socket.c:841
int fr_socket_client_tcp(char const *ifname, fr_ipaddr_t *src_ipaddr, fr_ipaddr_t const *dst_ipaddr, uint16_t dst_port, bool async)
Establish a connected TCP socket.
Definition socket.c:706
int fr_socket_bind(int sockfd, char const *ifname, fr_ipaddr_t *src_ipaddr, uint16_t *src_port)
Bind a UDP/TCP v4/v6 socket to a given ipaddr src port, and interface.
Definition socket.c:200
fr_client_t * client_afrom_cs(TALLOC_CTX *ctx, CONF_SECTION *cs, CONF_SECTION *server_cs, size_t extra)
Allocate a new client from a config section.
Definition client.c:735
void modules_init(char const *lib_dir)
Perform global initialisation for modules.
Definition module.c:1981
return count
Definition module.c:155
fr_log_dst_t dst
Log destination.
Definition log.h:94
int fd
File descriptor to write messages to.
Definition log.h:109
bool print_level
sometimes we don't want log levels printed
Definition log.h:103
char const * fr_syserror(int num)
Guaranteed to be thread-safe version of strerror.
Definition syserror.c:243
char * talloc_typed_asprintf(TALLOC_CTX *ctx, char const *fmt,...)
Call talloc vasprintf, setting the type on the new chunk correctly.
Definition talloc.c:621
static int talloc_const_free(void const *ptr)
Free const'd memory.
Definition talloc.h:289
#define talloc_autofree_context
The original function is deprecated, so replace it with our version.
Definition talloc.h:55
int fr_thread_instantiate(TALLOC_CTX *ctx, fr_event_list_t *el)
Instantiate thread-specific data for modules, virtual servers, xlats, unlang, and TLS.
Definition thread.c:177
static const char * names[8]
Definition time.c:618
int fr_time_start(void)
Initialize the local time.
Definition time.c:157
static fr_time_delta_t fr_time_delta_from_sec(int64_t sec)
Definition time.h:599
"server local" time.
Definition time.h:69
int fr_openssl_version_consistent(void)
Definition version.c:246
@ T_BARE_WORD
Definition token.h:118
@ T_OP_EQ
Definition token.h:81
@ T_DOUBLE_QUOTED_STRING
Definition token.h:119
static char const * receipt_file
static fr_event_list_t * el
static void _request_yield(request_t *request, void *uctx)
uint8_t * first
The datagram which named the peer, read from the listening socket before the connection's socket exis...
unit_test_tls_socket_t udp
The udp { ... } subsection.
static int tls_socket_accept(unit_test_tls_t *utt)
Wait for a connection, or for the command started by -e to exit without connecting.
unsigned int count
How many connections to run.
unit_test_tls_socket_t tcp
The tcp { ... } subsection.
static void _request_done_external(request_t *request, UNUSED rlm_rcode_t rcode, UNUSED void *uctx)
int main(int argc, char *argv[])
static void tls_command_wait(unit_test_tls_t *utt)
Wait for the command started by -e to exit, so its output is complete.
static void _tls_runnable(UNUSED fr_event_list_t *el, UNUSED fr_time_t now, void *uctx)
Drain the runnable heap once per pass of the event loop.
unit_test_tls_conf_t conf
Parsed "unit_test_tls" section.
static const conf_parser_t unit_test_tls_server_config[]
The rules for the server and client subsections.
static void _request_resume(request_t *request, UNUSED void *uctx)
static void _tls_socket_accept_start(fr_event_list_t *el, void *uctx)
Start waiting for a connection, from inside the event loop.
SSL_CTX * ssl_ctx
Context built from the "tls" section.
bool alert
Reject the peer with a TLS alert, see -A.
uint16_t port
Port of the listening socket, and the default port for -s.
static void _request_runnable(request_t *request, void *uctx)
bool abort_pending
Free the connection once the handshake succeeds, while store session is still queued,...
static fr_client_t * tls_client_alloc(TALLOC_CTX *ctx, fr_ipaddr_t const *ipaddr)
Build an internal client.
static int tls_connection_write_wait(unit_test_tls_t *utt, bool wait)
Start or stop waiting for the socket to have room for more records.
static void _request_done_internal(request_t *request, UNUSED rlm_rcode_t rcode, UNUSED void *uctx)
int fd
Accepted or connected socket.
fr_event_list_t * el
Event list everything runs on.
fr_event_fd_t * accept_ef
Read event for sockfd, while waiting in tls_socket_accept().
bool accepting
Waiting in tls_socket_accept().
static void _tls_connection_error(UNUSED fr_event_list_t *el, int fd, int flags, int fd_errno, void *uctx)
The connection failed at the socket level.
static bool _request_scheduled(request_t const *request, UNUSED void *uctx)
bool network_fail
Fail the session with a network error once the handshake succeeds, see -N.
static void _tls_connection_read(UNUSED fr_event_list_t *el, int fd, UNUSED int flags, void *uctx)
A record arrived on the connection, so hand the record to the connection.
static fr_dict_t const * dict_freeradius
static fr_dict_t const * dict_tls
static void tls_request_close(fr_tls_connection_t *conn)
Stop the event loop, recording why.
static void tls_request_failed(unit_test_tls_t *utt)
Record a failure this program cannot recover from, and stop.
bool invalid
Mark the session invalid mid-handshake, see -I.
bool command_waiting
Waiting in tls_command_wait().
char const * command
Command to run, see -e.
static void tls_runnable_insert(unit_test_tls_t *utt, request_t *request)
Schedule a request, once.
static void _request_detach(request_t *request, UNUSED void *uctx)
fr_ipaddr_t ipaddr
Address of the listening socket.
static void tls_connection_recv_resume(fr_tls_connection_t *conn)
OpenSSL has read from dirty_in, so start reading the socket again.
int yielded
How many requests are currently yielded.
uint16_t port
Port of the listening socket.
bool hold
Once connected, send nothing and stay connected, see -H.
static const conf_parser_t unit_test_tls_client_config[]
static fr_event_update_t const resume_write[]
fr_tls_connection_t * conn
State of the connection being run.
static int tls_command_start(unit_test_tls_t *utt, char const *command)
Start the command named by -e.
bool command_exited
The command has exited.
static void _tls_connection_start(fr_event_list_t *el, void *uctx)
Add the connection to the event loop, and get it moving.
static fr_event_update_t const pause_read[]
static request_t * tls_request_alloc(TALLOC_CTX *ctx, int fd, int socket_type)
Build the request the handshake runs under.
bool require_client_certificate
Whether the client has to present a certificate.
fr_ipaddr_t ipaddr
Address of the listening socket, copied from whichever subsection transport named.
static int * tls_alpn_ids(TALLOC_CTX *ctx, char const *names, size_t *num)
Turn a comma separated list of names into ids of the test table.
bool read_paused
True while the read event is suspended, because fr_tls_connection_recv_room() returned 0,...
fr_tls_conf_t * client
The client { ... } subsection, used with -s.
bool app_data
Send one byte of application data once the handshake is done, see -P.
fr_ipaddr_t server_ipaddr
Server named by -s.
static int tls_socket_connect(unit_test_tls_t *utt)
Connect to the server named by -s.
fr_dict_autoload_t unit_test_tls_dict[]
bool reject
Reject the session once the handshake succeeds, see -R.
static void tls_request_connected(fr_tls_connection_t *conn)
The connection is up, and can carry application data.
int ret
Exit status.
char const * radiusd_version
unlang_interpret_t * intp
Interpreter for the connection.
uint32_t datagrams
How many datagrams this connection has been asked to write, counting from one.
static void _tls_connection_write(UNUSED fr_event_list_t *el, UNUSED int fd, UNUSED int flags, void *uctx)
The socket is ready for writes.
bool nonblock
Put the connection socket in non-blocking mode, see -B.
static fr_event_update_t const resume_read[]
static void _tls_socket_error(fr_event_list_t *el, UNUSED int fd, UNUSED int flags, int fd_errno, UNUSED void *uctx)
Stop waiting for a connection if the listening socket fails.
fr_event_fd_t * ef
Read and write events for fd.
fr_heap_t * runnable
Requests the interpreter has marked runnable.
bool write_blocked
True while the socket has no room for a record and the write event is active, see tls_connection_writ...
char const * transport
"tcp" or "udp", naming the subsection below which holds the socket.
#define EXIT_WITH_FAILURE
fr_event_pid_t const * command_ev
Waits for the command to exit.
static void _tls_command_exit(fr_event_list_t *el, pid_t pid, int status, void *uctx)
Record that the command started by -e has exited.
bool alpn_required
Set by -l.
static int tls_socket_open(unit_test_tls_t *utt)
Open the listening socket described by the "unit_test_tls" section.
static void _tls_socket_accept(fr_event_list_t *el, UNUSED int fd, UNUSED int flags, void *uctx)
Accept the connection once the listening socket is readable.
int sockfd
Listening socket.
unsigned int connections
How many connections have been run so far.
static int tls_socket_accept_one(unit_test_tls_t *utt)
Accept a connection, if the listening socket has one queued.
static const conf_parser_t unit_test_tls_alpn_config[]
The alpn subsection has no rules of its own.
unit_test_tls_alpn_id_t
Protocols which the test program can negotiate.
@ UTT_ALPN_RADIUS_1_0
@ UTT_ALPN_RADIUS_1_1
@ UTT_ALPN_HTTP_1_1
unsigned char * alpn
Protocol list built by -L, in the wire format fr_tls_conf_t expects.
static ssize_t tls_connection_write(fr_tls_connection_t *conn, uint8_t const *data, size_t size)
Write whatever OpenSSL has produced out to the connection.
static void _request_done_detached(request_t *request, UNUSED rlm_rcode_t rcode, UNUSED void *uctx)
size_t first_len
Length of first.
bool done
Set once the connection has a result.
bool client
Act as the client and connect to a server, rather than accept a connection.
int socket_type
SOCK_STREAM or SOCK_DGRAM, from transport.
static const conf_parser_t unit_test_tls_socket_config[]
The socket items, parsed once per transport subsection.
static const conf_parser_t unit_test_tls_config[]
pid_t command_pid
Command started by -e, or 0.
fr_tls_conf_t * server
The server { ... } subsection.
static void _request_init_internal(request_t *request, void *uctx)
An internal request created by the interpreter has to run on ours.
uint32_t drop_datagram
Drop this datagram rather than sending it, counting from one.
static fr_event_update_t const pause_write[]
static int tls_connection_run(unit_test_tls_t *utt)
Run one connection from the first byte to the last.
uint16_t server_port
Port from -s, or from the configuration.
static unsigned char * tls_alpn_build(TALLOC_CTX *ctx, char const *names)
Turn a comma separated list of names into the wire format ALPN uses.
static fr_tls_alpn_t const unit_test_tls_alpn_table[]
The "unit_test_tls" section.
State of the test program.
#define FR_DICTIONARY_FILE
Definition conf.h:6
#define FR_DICTIONARY_INTERNAL_DIR
Definition conf.h:7
int type
SOCK_STREAM, SOCK_DGRAM, etc.
Definition socket.h:84
Holds information necessary for binding or connecting to a socket.
Definition socket.h:60
void fr_perror(char const *fmt,...)
Print the current error to stderr with a prefix.
Definition strerror.c:737
#define fr_strerror_const(_msg)
Definition strerror.h:223
int fr_check_lib_magic(uint64_t magic)
Check if the application linking to the library has the correct magic number.
Definition version.c:40
#define RADIUSD_VERSION_BUILD(_x)
Create a version string for a utility in the suite of FreeRADIUS utilities.
Definition version.h:58
#define RADIUSD_MAGIC_NUMBER
Definition version.h:81
#define fr_box_ipaddr(_val)
Definition value.h:348
static fr_slen_t data
Definition value.h:1366
static fr_sbuff_err_t char size_t * len
Definition value.h:1061
fr_dict_t const * virtual_server_dict_by_name(char const *virtual_server)
Return the namespace for the named virtual server.
virtual_server_t const * virtual_server_find(char const *name)
Return virtual server matching the specified name.
int virtual_servers_init(void)
Performs global initialisation for the virtual server code.
int virtual_servers_free(void)