summaryrefslogtreecommitdiff
path: root/usr.sbin/radiusd/radiusd_radius.c
blob: a2f03d1a547e38478783a3397c7c7845c02e1f7b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
/*	$OpenBSD: radiusd_radius.c,v 1.5 2015/07/30 09:16:30 yasuoka Exp $	*/

/*
 * Copyright (c) 2013 Internet Initiative Japan Inc.
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <sys/types.h>
#include <sys/queue.h>
#include <sys/socket.h>
#include <netinet/in.h>

#include <err.h>
#include <event.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <syslog.h>
#include <unistd.h>

#include <radius.h>

#include "radiusd.h"
#include "radiusd_module.h"
#include "util.h"
#include "log.h"

struct radius_server {
	struct module_radius		*module;
	int				 sock;
	union {
		struct sockaddr_in6	 sin6;
		struct sockaddr_in	 sin4;
	}				 addr;
	union {
		struct sockaddr_in6	 sin6;
		struct sockaddr_in	 sin4;
	}				 local;
	struct event			 ev;
	u_char				 req_id_seq;
};

struct module_radius {
	struct module_base		*base;
	struct radius_server		 server[4];
	char				 secret[RADIUSD_SECRET_MAX];
	u_int				 nserver;
	u_int				 curr_server;
	u_int				 req_timeout;
	u_int				 max_tries;
	u_int				 max_failovers;
	u_int				 nfailover;
	TAILQ_HEAD(,module_radius_req)	 req;
};

struct module_radius_req {
	struct module_radius		*module;
	struct radius_server		*server;
	u_int				 q_id;
	RADIUS_PACKET			*q_pkt;
	u_int				 ntry;
	u_int				 nfailover;
	u_char				 req_id;
	struct event			 ev;
	TAILQ_ENTRY(module_radius_req)	 next;
};

static void	 module_radius_init(struct module_radius *);
static void	 module_radius_config_set(void *, const char *, int,
		    char * const *);
static void	 module_radius_start(void *);
static void	 module_radius_stop(void *);
static void	 module_radius_access_request(void *, u_int, const u_char *,
		    size_t);
static int	 radius_server_start(struct radius_server *);
static void	 radius_server_stop(struct radius_server *);
static void	 radius_server_on_event(int, short, void *);
static void	 radius_server_on_fail(struct radius_server *, const char *);
static void	 module_radius_req_send(struct module_radius_req *);
static int	 module_radius_req_reset_event(struct module_radius_req *);
static void	 module_radius_req_on_timeout(int, short, void *);
static void	 module_radius_req_on_success(struct module_radius_req *,
		    const u_char *, size_t);
static void	 module_radius_req_on_failure(struct module_radius_req *);

static void	 module_radius_req_free(struct module_radius_req *);
static void	 module_radius_req_select_server(struct module_radius_req *);

static void	 module_radius_req_reset_msgauth(struct module_radius_req *);
static void	 module_radius_log(struct module_radius *, int, const char *, ...);

static struct module_handlers module_radius_handlers = {
	.config_set = module_radius_config_set,
	.start = module_radius_start,
	.stop = module_radius_stop,
	.access_request = module_radius_access_request
};

#ifndef nitems
#define nitems(_x)    (sizeof((_x)) / sizeof((_x)[0]))
#endif

int
main(int argc, char *argv[])
{
	static struct module_radius module_radius;

	module_radius_init(&module_radius);
	openlog(NULL, LOG_PID, LOG_DAEMON);

	if ((module_radius.base = module_create(
	    STDIN_FILENO, &module_radius, &module_radius_handlers)) == NULL)
		err(1, "Could not create a module instance");
	module_drop_privilege(module_radius.base);
	setproctitle("[main]");

	module_load(module_radius.base);
	log_init(1);
	event_init();
	module_start(module_radius.base);
	event_loop(0);

	exit(EXIT_SUCCESS);
}

static void
module_radius_init(struct module_radius *module)
{
	memset(module, 0, sizeof(struct module_radius));
	TAILQ_INIT(&module->req);
}

static void
module_radius_config_set(void *ctx, const char *paramname, int paramvalc,
    char * const * paramvalv)
{
	const char		*errmsg = NULL;
	struct addrinfo		*res;
	struct module_radius	*module = ctx;

	if (strcmp(paramname, "server") == 0) {
		SYNTAX_ASSERT(paramvalc == 1,
		    "`server' must have just one argument");
		SYNTAX_ASSERT(module->nserver < (int)nitems(module->server),
		    "number of server reached limit");

		if (addrport_parse(paramvalv[0], IPPROTO_UDP, &res) != 0)
			SYNTAX_ASSERT(0, "could not parse address and port");
		memcpy(&module->server[module->nserver].addr, res->ai_addr,
		    res->ai_addrlen);

		if (ntohs(module->server[module->nserver].addr.sin4.sin_port)
		    == 0)
			module->server[module->nserver].addr.sin4.sin_port
			    = htons(RADIUS_DEFAULT_PORT);

		module->server[module->nserver].sock = -1;
		module->nserver++;
		freeaddrinfo(res);
	} else if (strcmp(paramname, "request-timeout") == 0) {
		SYNTAX_ASSERT(paramvalc == 1,
		    "`request-timeout' must have just one argument");
		module->req_timeout = (int)strtonum(paramvalv[0], 0,
		    UINT16_MAX, &errmsg);
		if (module->req_timeout == 0 && errmsg != NULL) {
			module_send_message(module->base, IMSG_NG,
			    "`request-timeout must be 0-%d", UINT16_MAX);
			return;
		}
	} else if (strcmp(paramname, "max-tries") == 0) {
		SYNTAX_ASSERT(paramvalc == 1,
		    "`max-tries' must have just one argument");
		module->max_tries = (int)strtonum(paramvalv[0], 0,
		    UINT16_MAX, &errmsg);
		if (module->max_tries == 0 && errmsg != NULL) {
			module_send_message(module->base, IMSG_NG,
			    "`max-tries must be 0-%d", UINT16_MAX);
			return;
		}

	} else if (strcmp(paramname, "max-failovers") == 0) {
		SYNTAX_ASSERT(paramvalc == 1,
		    "`max-failovers' must have just one argument");
		module->max_failovers = (int)strtonum(paramvalv[0], 0,
		    UINT16_MAX, &errmsg);
		if (module->max_failovers == 0 && errmsg != NULL) {
			module_send_message(module->base, IMSG_NG,
			    "`max-failovers' must be 0-%d", UINT16_MAX);
			return;
		}
	} else if (strcmp(paramname, "secret") == 0) {
		SYNTAX_ASSERT(paramvalc == 1,
		    "`secret' must have just one argument");
		if (strlcpy(module->secret, paramvalv[0],
		    sizeof(module->secret)) >= sizeof(module->secret)) {
			module_send_message(module->base, IMSG_NG,
			    "`secret' length must be 0-%lu",
			    (u_long) sizeof(module->secret) - 1);
			return;
		}
	} else {
		module_send_message(module->base, IMSG_NG,
		    "Unknown config parameter name `%s'", paramname);
		return;
	}
	module_send_message(module->base, IMSG_OK, NULL);

	return;
syntax_error:
	module_send_message(module->base, IMSG_NG, "%s", errmsg);
}

static void
module_radius_start(void *ctx)
{
	u_int			 i;
	struct module_radius	*module = ctx;

	if (module->nserver <= 0) {
		module_send_message(module->base, IMSG_NG,
			"module `radius' needs one `server' at least");
		return;
	}

	for (i = 0; i < module->nserver; i++) {
		module->server[i].module = module;
		if (radius_server_start(&module->server[i]) != 0) {
			module_send_message(module->base, IMSG_NG,
				"module `radius' failed to start one of "
				"the servers");
			return;
		}
	}
	module_send_message(module->base, IMSG_OK, NULL);

	if (module->secret[0] != '\0')
		module_notify_secret(module->base, module->secret);
}

static void
module_radius_stop(void *ctx)
{
	u_int				 i;
	struct module_radius_req	*req, *treq;
	struct module_radius		*module = ctx;

	TAILQ_FOREACH_SAFE(req, &module->req, next, treq) {
		module_radius_req_on_failure(req);
		TAILQ_REMOVE(&module->req, req, next);
	}

	for (i = 0; i < module->nserver; i++)
		radius_server_stop(&module->server[i]);
}

static void
module_radius_access_request(void *ctx, u_int q_id, const u_char *pkt,
    size_t pktlen)
{
	struct module_radius		*module = ctx;
	struct module_radius_req	*req;
	u_char				 attrbuf[256];
	ssize_t				 attrlen;

	req = malloc(sizeof(struct module_radius_req));
	if (req == NULL) {
		module_radius_log(module, LOG_WARNING,
		    "%s: Out of memory: %m", __func__);
		goto on_fail;
	}

	req->ntry = 0;
	req->module = module;
	req->q_id = q_id;
	if ((req->q_pkt = radius_convert_packet(pkt, pktlen)) == NULL) {
		module_radius_log(module, LOG_WARNING,
		    "%s: radius_convert_packet() failed: %m", __func__);
		goto on_fail;
	}
	evtimer_set(&req->ev, module_radius_req_on_timeout, req);
	TAILQ_INSERT_TAIL(&req->module->req, req, next);

	/*
	 * radiusd decrypt User-Password attribute.  crypt it again with our
	 * secret.
	 */
	attrlen = sizeof(attrbuf);
	if (module->secret[0] != '\0' &&
	    radius_get_raw_attr(req->q_pkt, RADIUS_TYPE_USER_PASSWORD,
		    attrbuf, &attrlen) == 0) {
		attrbuf[attrlen] = '\0';
		radius_del_attr_all(req->q_pkt, RADIUS_TYPE_USER_PASSWORD);
		radius_put_user_password_attr(req->q_pkt, attrbuf,
		    module->secret);
	}

	/* select current server */
	module_radius_req_select_server(req);

	module_radius_req_send(req);

	return;

on_fail:
	free(req);
	module_accsreq_aborted(module->base, q_id);
}

/*
 * radius_server
 */
static int
radius_server_start(struct radius_server *module)
{
	socklen_t	 locallen;
	char		 buf0[NI_MAXHOST + NI_MAXSERV + 32];
	char		 buf1[NI_MAXHOST + NI_MAXSERV + 32];

	if ((module->sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
		log_warn("%s: socket() failed", __func__);
		goto on_error;
	}
	if (connect(module->sock, (struct sockaddr *)&module->addr,
		module->addr.sin4.sin_len) != 0) {
		log_warn("%s: connect to %s failed", __func__,
		    addrport_tostring((struct sockaddr *)&module->addr,
			module->addr.sin4.sin_len, buf1, sizeof(buf1)));
		goto on_error;
	}
	locallen = sizeof(module->local);
	if (getsockname(module->sock, (struct sockaddr *)&module->local,
	    &locallen) != 0) {
		log_warn("%s: getsockanme() failed", __func__);
		goto on_error;
	}
	module_radius_log(module->module, LOG_INFO,
	    "Use %s to send requests for %s",
	    addrport_tostring((struct sockaddr *)&module->local,
		    locallen, buf0, sizeof(buf0)),
	    addrport_tostring((struct sockaddr *)&module->addr,
		    module->addr.sin4.sin_len, buf1, sizeof(buf1)));

	event_set(&module->ev, module->sock, EV_READ | EV_PERSIST,
	    radius_server_on_event, module);
	if (event_add(&module->ev, NULL)) {
		log_warn("%s: event_add() failed", __func__);
		goto on_error;
	}

	return (0);
on_error:
	if (module->sock >= 0)
		close(module->sock);
	module->sock = -1;
	return (-1);
}

static void
radius_server_stop(struct radius_server *server)
{
	event_del(&server->ev);
	if (server->sock >= 0)
		close(server->sock);
	server->sock = -1;
}

static void
radius_server_on_event(int fd, short evmask, void *ctx)
{
	int				 sz, res_id;
	u_char				 pkt[65535];
	char				 buf[NI_MAXHOST + NI_MAXSERV + 32];
	struct radius_server		*server = ctx;
	RADIUS_PACKET			*radpkt = NULL;
	struct module_radius_req	*req;
	struct sockaddr			*peer;

	peer = (struct sockaddr *)&server->addr;
	if ((sz = recv(server->sock, pkt, sizeof(pkt), 0)) <= 0) {
		module_radius_log(server->module, LOG_WARNING,
		    "server=%s recv() failed: %m",
		    addrport_tostring(peer, peer->sa_len, buf, sizeof(buf)));
		return;
	}
	if ((radpkt = radius_convert_packet(pkt, sz)) == NULL) {
		module_radius_log(server->module, LOG_WARNING,
		    "server=%s could not convert the received message to a "
		    "RADIUS packet object: %m",
		    addrport_tostring(peer, peer->sa_len, buf, sizeof(buf)));
		return;
	}
	res_id = radius_get_id(radpkt);
	TAILQ_FOREACH(req, &server->module->req, next) {
		if (req->server == server && req->req_id == res_id)
			break;
	}
	if (req == NULL) {
		module_radius_log(server->module, LOG_WARNING,
		    "server=%s Received radius message has unknown id=%d",
		    addrport_tostring(peer, peer->sa_len, buf, sizeof(buf)),
		    res_id);
		goto out;
	}
	radius_set_request_packet(radpkt, req->q_pkt);

	if (server->module->secret[0] != '\0') {
		if (radius_check_response_authenticator(radpkt,
		    server->module->secret) != 0) {
			module_radius_log(server->module, LOG_WARNING,
			    "server=%s Received radius message(id=%d) has bad "
			    "authenticator",
			    addrport_tostring(peer, peer->sa_len, buf,
			    sizeof(buf)), res_id);
			goto out;
		}
		if (radius_has_attr(radpkt,
		    RADIUS_TYPE_MESSAGE_AUTHENTICATOR) &&
		    radius_check_message_authenticator(radpkt,
			    server->module->secret) != 0) {
			module_radius_log(server->module, LOG_WARNING,
			    "server=%s Received radius message(id=%d) has bad "
			    "message authenticator",
			    addrport_tostring(peer, peer->sa_len, buf,
			    sizeof(buf)), res_id);
			goto out;
		}
	}

	module_radius_log(server->module, LOG_INFO,
	    "q=%u received a response from server %s", req->q_id,
	    addrport_tostring(peer, peer->sa_len, buf, sizeof(buf)));

	module_radius_req_on_success(req, radius_get_data(radpkt),
	    radius_get_length(radpkt));
out:
	if (radpkt != NULL)
		radius_delete_packet(radpkt);
}

static void
radius_server_on_fail(struct radius_server *server, const char *failmsg)
{
	char		 buf0[NI_MAXHOST + NI_MAXSERV + 32];
	char		 buf1[NI_MAXHOST + NI_MAXSERV + 32];
	struct sockaddr	*caddr, *naddr;

	caddr = (struct sockaddr *)&server->addr;
	if (server->module->nserver <= 1) {
		module_radius_log(server->module, LOG_WARNING,
		    "Server %s failed: %s",
		    addrport_tostring(caddr, caddr->sa_len, buf0, sizeof(buf0)),
		    failmsg);
		return;
	}
	server->module->curr_server++;
	server->module->curr_server %= server->module->nserver;
	naddr = (struct sockaddr *)
	    &server->module->server[server->module->curr_server].addr;

	module_radius_log(server->module, LOG_WARNING,
	    "Server %s failed: %s  Fail over to %s",
	    addrport_tostring(caddr, caddr->sa_len, buf0, sizeof(buf0)),
	    failmsg,
	    addrport_tostring(naddr, naddr->sa_len, buf1, sizeof(buf1)));
}

/* module_radius_req */

static void
module_radius_req_send(struct module_radius_req *req)
{
	int		 sz;
	struct sockaddr	*peer;
	char		 msg[BUFSIZ];

	peer = (struct sockaddr *)&req->server->addr;
	if ((sz = send(req->server->sock, radius_get_data(req->q_pkt),
	    radius_get_length(req->q_pkt), 0)) < 0) {
		module_radius_log(req->module, LOG_WARNING,
		    "Sending RADIUS query q=%u to %s failed: %m",
		    req->q_id,
		    addrport_tostring(peer, peer->sa_len, msg, sizeof(msg)));
		/* retry anyway */
	}
	module_radius_log(req->module, LOG_INFO,
	    "Send RADIUS query q=%u id=%d to %s successfully",
	    req->q_id, req->req_id,
	    addrport_tostring(peer, peer->sa_len, msg, sizeof(msg)));
	if (module_radius_req_reset_event(req) != -1)
		req->ntry++;
}

static int
module_radius_req_reset_event(struct module_radius_req *req)
{
	struct timeval	 tv;
	static int	 timeouts[] = { 2, 4, 8 };

	tv.tv_usec = 0;
	if (req->module->req_timeout != 0)
		tv.tv_sec = req->module->req_timeout;
	else {
		if (req->ntry < nitems(timeouts))
			tv.tv_sec = timeouts[req->ntry];
		else
			tv.tv_sec = timeouts[nitems(timeouts) - 1];
	}
	if (evtimer_add(&req->ev, &tv) != 0) {
		module_radius_log(req->module, LOG_WARNING,
		    "Cannot proccess the request for q=%u: "
		    "evtimer_add() failed: %m", req->q_id);
		module_radius_req_on_failure(req);
		return (-1);
	}
	return (0);
}

static void
module_radius_req_on_timeout(int fd, short evmask, void *ctx)
{
	struct module_radius_req	*req = ctx;
	char				 msg[BUFSIZ];


	if (req->module->max_tries <= req->ntry) {
		snprintf(msg, sizeof(msg), "q=%u didn't response RADIUS query "
		    "%d time%s", req->q_id, req->ntry,
		    (req->ntry > 0)? "s" : "");
		radius_server_on_fail(req->server, msg);
		if (++req->nfailover >= req->module->max_failovers) {
			module_radius_log(req->module,
			    LOG_WARNING, "RADIUS query q=%u time out",
			    req->q_id);
			module_radius_req_on_failure(req);
			return;
		}
		/* select the next server */
		module_radius_req_select_server(req);
	}
	module_radius_req_send(req);
}

static void
module_radius_req_on_success(struct module_radius_req *req,
    const u_char *pkt, size_t pktlen)
{
	module_accsreq_answer(req->module->base, req->q_id, 1, pkt, pktlen);
	module_radius_req_free(req);
}

static void
module_radius_req_on_failure(struct module_radius_req *req)
{
	module_accsreq_aborted(req->module->base, req->q_id);
	module_radius_req_free(req);
}


static void
module_radius_req_free(struct module_radius_req *req)
{
	evtimer_del(&req->ev);
	TAILQ_REMOVE(&req->module->req, req, next);
	if (req->q_pkt != NULL)
		radius_delete_packet(req->q_pkt);
	free(req);
}

static void
module_radius_req_select_server(struct module_radius_req *req)
{
	req->server = &req->module->server[req->module->curr_server];
	req->ntry = 0;
	req->req_id = req->server->req_id_seq++;
	radius_set_id(req->q_pkt, req->req_id);
	module_radius_req_reset_msgauth(req);
}

static void
module_radius_req_reset_msgauth(struct module_radius_req *req)
{
	if (radius_has_attr(req->q_pkt, RADIUS_TYPE_MESSAGE_AUTHENTICATOR))
		radius_del_attr_all(req->q_pkt,
		    RADIUS_TYPE_MESSAGE_AUTHENTICATOR);
	if (req->module->secret[0] != '\0')
		radius_put_message_authenticator(req->q_pkt,
		    req->module->secret);
}

static void
module_radius_log(struct module_radius *module, int pri, const char *fmt, ...)
{
	char		fmt0[BUFSIZ];
	va_list		va;

	snprintf(fmt0, sizeof(fmt0), "radius: %s", fmt);
	va_start(va, fmt);
	vlog(pri, fmt0, va);
	va_end(va);
}