xref: /netbsd-src/lib/libradius/radlib.c (revision b1c86f5f087524e68db12794ee9c3e3da1ab17a0)
1 /* $NetBSD: radlib.c,v 1.11 2009/01/19 09:43:11 jmmv Exp $ */
2 
3 /*-
4  * Copyright 1998 Juniper Networks, Inc.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include <sys/cdefs.h>
30 #ifdef __FreeBSD__
31 __FBSDID("$FreeBSD: /repoman/r/ncvs/src/lib/libradius/radlib.c,v 1.12 2004/06/14 20:55:30 stefanf Exp $");
32 #else
33 __RCSID("$NetBSD: radlib.c,v 1.11 2009/01/19 09:43:11 jmmv Exp $");
34 #endif
35 
36 #include <sys/types.h>
37 #include <sys/socket.h>
38 #include <sys/time.h>
39 #include <netinet/in.h>
40 #include <arpa/inet.h>
41 #ifdef WITH_SSL
42 #include <openssl/hmac.h>
43 #include <openssl/md5.h>
44 #define MD5Init MD5_Init
45 #define MD5Update MD5_Update
46 #define MD5Final MD5_Final
47 #define MD5Len size_t
48 #define MD5Buf const void *
49 #else
50 #define MD5_DIGEST_LENGTH 16
51 #define MD5Len unsigned int
52 #define MD5Buf const unsigned char *
53 #include <md5.h>
54 #endif
55 
56 /* We need the MPPE_KEY_LEN define */
57 #ifdef __FreeBSD__
58 #include <netgraph/ng_mppc.h>
59 #else
60 #define MPPE_KEY_LEN 16
61 #endif
62 
63 #include <errno.h>
64 #include <netdb.h>
65 #include <stdarg.h>
66 #include <stddef.h>
67 #include <stdio.h>
68 #include <stdlib.h>
69 #include <string.h>
70 #include <unistd.h>
71 
72 #include "radlib_private.h"
73 #if !defined(__printflike)
74 #define __printflike(fmtarg, firstvararg)				\
75 	__attribute__((__format__ (__printf__, fmtarg, firstvararg)))
76 #endif
77 
78 #ifdef __NetBSD__
79 #define srandomdev(x)
80 #define random arc4random
81 #endif
82 
83 static void	 clear_password(struct rad_handle *);
84 static void	 generr(struct rad_handle *, const char *, ...)
85 		    __printflike(2, 3);
86 static void	 insert_scrambled_password(struct rad_handle *, size_t);
87 static void	 insert_request_authenticator(struct rad_handle *, size_t);
88 static void	 insert_message_authenticator(struct rad_handle *, size_t);
89 static int	 is_valid_response(struct rad_handle *, size_t,
90 		    const struct sockaddr_in *);
91 static int	 put_password_attr(struct rad_handle *, int,
92 		    const void *, size_t);
93 static int	 put_raw_attr(struct rad_handle *, int,
94 		    const void *, size_t);
95 static size_t	 split(char *, const char *[], size_t, char *, size_t);
96 
97 static void
98 clear_password(struct rad_handle *h)
99 {
100 	if (h->pass_len != 0) {
101 		(void)memset(h->pass, 0, h->pass_len);
102 		h->pass_len = 0;
103 	}
104 	h->pass_pos = 0;
105 }
106 
107 static void
108 generr(struct rad_handle *h, const char *format, ...)
109 {
110 	va_list		 ap;
111 
112 	va_start(ap, format);
113 	vsnprintf(h->errmsg, (size_t)ERRSIZE, format, ap);
114 	va_end(ap);
115 }
116 
117 static void
118 insert_scrambled_password(struct rad_handle *h, size_t srv)
119 {
120 	MD5_CTX ctx;
121 	unsigned char md5[MD5_DIGEST_LENGTH];
122 	const struct rad_server *srvp;
123 	size_t padded_len, pos;
124 
125 	srvp = &h->servers[srv];
126 	padded_len = h->pass_len == 0 ? (size_t)16 : (h->pass_len+15) & ~0xf;
127 
128 	(void)memcpy(md5, &h->request[POS_AUTH], (size_t)LEN_AUTH);
129 	for (pos = 0;  pos < padded_len;  pos += 16) {
130 		int i;
131 
132 		/* Calculate the new scrambler */
133 		MD5Init(&ctx);
134 		MD5Update(&ctx, (MD5Buf)srvp->secret,
135 		    (MD5Len)strlen(srvp->secret));
136 		MD5Update(&ctx, md5, (MD5Len)16);
137 		MD5Final(md5, &ctx);
138 
139 		/*
140 		 * Mix in the current chunk of the password, and copy
141 		 * the result into the right place in the request.  Also
142 		 * modify the scrambler in place, since we will use this
143 		 * in calculating the scrambler for next time.
144 		 */
145 		for (i = 0;  i < 16;  i++)
146 			h->request[h->pass_pos + pos + i] =
147 			    md5[i] ^= h->pass[pos + i];
148 	}
149 }
150 
151 static void
152 insert_request_authenticator(struct rad_handle *h, size_t srv)
153 {
154 	MD5_CTX ctx;
155 	const struct rad_server *srvp;
156 
157 	srvp = &h->servers[srv];
158 
159 	/* Create the request authenticator */
160 	MD5Init(&ctx);
161 	MD5Update(&ctx, &h->request[POS_CODE],
162 	    (MD5Len)(POS_AUTH - POS_CODE));
163 	MD5Update(&ctx, memset(&h->request[POS_AUTH], 0, (size_t)LEN_AUTH),
164 	    (MD5Len)LEN_AUTH);
165 	MD5Update(&ctx, &h->request[POS_ATTRS],
166 	    (MD5Len)(h->req_len - POS_ATTRS));
167 	MD5Update(&ctx, (MD5Buf)srvp->secret,
168 	    (MD5Len)strlen(srvp->secret));
169 	MD5Final(&h->request[POS_AUTH], &ctx);
170 }
171 
172 static void
173 /*ARGSUSED*/
174 insert_message_authenticator(struct rad_handle *h, size_t srv)
175 {
176 #ifdef WITH_SSL
177 	u_char md[EVP_MAX_MD_SIZE];
178 	u_int md_len;
179 	const struct rad_server *srvp;
180 	HMAC_CTX ctx;
181 	srvp = &h->servers[srv];
182 
183 	if (h->authentic_pos != 0) {
184 		HMAC_CTX_init(&ctx);
185 		HMAC_Init(&ctx, srvp->secret,
186 		    (int)strlen(srvp->secret), EVP_md5());
187 		HMAC_Update(&ctx, &h->request[POS_CODE], (size_t)(POS_AUTH - POS_CODE));
188 		HMAC_Update(&ctx, &h->request[POS_AUTH], (size_t)LEN_AUTH);
189 		HMAC_Update(&ctx, &h->request[POS_ATTRS],
190 		    (size_t)(h->req_len - POS_ATTRS));
191 		HMAC_Final(&ctx, md, &md_len);
192 		HMAC_CTX_cleanup(&ctx);
193 		HMAC_cleanup(&ctx);
194 		(void)memcpy(&h->request[h->authentic_pos + 2], md,
195 		    (size_t)md_len);
196 	}
197 #endif
198 }
199 
200 /*
201  * Return true if the current response is valid for a request to the
202  * specified server.
203  */
204 static int
205 is_valid_response(struct rad_handle *h, size_t srv,
206     const struct sockaddr_in *from)
207 {
208 	MD5_CTX ctx;
209 	unsigned char md5[MD5_DIGEST_LENGTH];
210 	const struct rad_server *srvp;
211 	size_t len;
212 #ifdef WITH_SSL
213 	HMAC_CTX hctx;
214 	u_char resp[MSGSIZE], md[EVP_MAX_MD_SIZE];
215 	size_t pos;
216 	u_int md_len;
217 #endif
218 
219 	srvp = &h->servers[srv];
220 
221 	/* Check the source address */
222 	if (from->sin_family != srvp->addr.sin_family ||
223 	    from->sin_addr.s_addr != srvp->addr.sin_addr.s_addr ||
224 	    from->sin_port != srvp->addr.sin_port)
225 		return 0;
226 
227 	/* Check the message length */
228 	if (h->resp_len < POS_ATTRS)
229 		return 0;
230 	len = h->response[POS_LENGTH] << 8 | h->response[POS_LENGTH+1];
231 	if (len > h->resp_len)
232 		return 0;
233 
234 	/* Check the response authenticator */
235 	MD5Init(&ctx);
236 	MD5Update(&ctx, &h->response[POS_CODE],
237 	    (MD5Len)(POS_AUTH - POS_CODE));
238 	MD5Update(&ctx, &h->request[POS_AUTH],
239 	    (MD5Len)LEN_AUTH);
240 	MD5Update(&ctx, &h->response[POS_ATTRS],
241 	    (MD5Len)(len - POS_ATTRS));
242 	MD5Update(&ctx, (MD5Buf)srvp->secret,
243 	    (MD5Len)strlen(srvp->secret));
244 	MD5Final(md5, &ctx);
245 	if (memcmp(&h->response[POS_AUTH], md5, sizeof md5) != 0)
246 		return 0;
247 
248 #ifdef WITH_SSL
249 	/*
250 	 * For non accounting responses check the message authenticator,
251 	 * if any.
252 	 */
253 	if (h->response[POS_CODE] != RAD_ACCOUNTING_RESPONSE) {
254 
255 		(void)memcpy(resp, h->response, (size_t)MSGSIZE);
256 		pos = POS_ATTRS;
257 
258 		/* Search and verify the Message-Authenticator */
259 		while (pos < len - 2) {
260 
261 			if (h->response[pos] == RAD_MESSAGE_AUTHENTIC) {
262 				/* zero fill the Message-Authenticator */
263 				(void)memset(&resp[pos + 2], 0,
264 				    (size_t)MD5_DIGEST_LENGTH);
265 
266 				HMAC_CTX_init(&hctx);
267 				HMAC_Init(&hctx, srvp->secret,
268 				    (int)strlen(srvp->secret), EVP_md5());
269 				HMAC_Update(&hctx, &h->response[POS_CODE],
270 				    (size_t)(POS_AUTH - POS_CODE));
271 				HMAC_Update(&hctx, &h->request[POS_AUTH],
272 				    (size_t)LEN_AUTH);
273 				HMAC_Update(&hctx, &resp[POS_ATTRS],
274 				    (size_t)(h->resp_len - POS_ATTRS));
275 				HMAC_Final(&hctx, md, &md_len);
276 				HMAC_CTX_cleanup(&hctx);
277 				HMAC_cleanup(&hctx);
278 				if (memcmp(md, &h->response[pos + 2],
279 				    (size_t)MD5_DIGEST_LENGTH) != 0)
280 					return 0;
281 				break;
282 			}
283 			pos += h->response[pos + 1];
284 		}
285 	}
286 #endif
287 	return 1;
288 }
289 
290 static int
291 put_password_attr(struct rad_handle *h, int type, const void *value, size_t len)
292 {
293 	size_t padded_len;
294 	size_t pad_len;
295 
296 	if (h->pass_pos != 0) {
297 		generr(h, "Multiple User-Password attributes specified");
298 		return -1;
299 	}
300 	if (len > PASSSIZE)
301 		len = PASSSIZE;
302 	padded_len = len == 0 ? 16 : (len + 15) & ~0xf;
303 	pad_len = padded_len - len;
304 
305 	/*
306 	 * Put in a place-holder attribute containing all zeros, and
307 	 * remember where it is so we can fill it in later.
308 	 */
309 	clear_password(h);
310 	put_raw_attr(h, type, h->pass, padded_len);
311 	h->pass_pos = (int)(h->req_len - padded_len);
312 
313 	/* Save the cleartext password, padded as necessary */
314 	(void)memcpy(h->pass, value, len);
315 	h->pass_len = len;
316 	(void)memset(h->pass + len, 0, pad_len);
317 	return 0;
318 }
319 
320 static int
321 put_raw_attr(struct rad_handle *h, int type, const void *value, size_t len)
322 {
323 	if (len > 253) {
324 		generr(h, "Attribute too long");
325 		return -1;
326 	}
327 	if (h->req_len + 2 + len > MSGSIZE) {
328 		generr(h, "Maximum message length exceeded");
329 		return -1;
330 	}
331 	h->request[h->req_len++] = type;
332 	h->request[h->req_len++] = (unsigned char)(len + 2);
333 	(void)memcpy(&h->request[h->req_len], value, len);
334 	h->req_len += len;
335 	return 0;
336 }
337 
338 int
339 rad_add_server(struct rad_handle *h, const char *host, int port,
340     const char *secret, int timeout, int tries)
341 {
342 	struct rad_server *srvp;
343 
344 	if (h->num_servers >= MAXSERVERS) {
345 		generr(h, "Too many RADIUS servers specified");
346 		return -1;
347 	}
348 	srvp = &h->servers[h->num_servers];
349 
350 	(void)memset(&srvp->addr, 0, sizeof srvp->addr);
351 	srvp->addr.sin_len = sizeof srvp->addr;
352 	srvp->addr.sin_family = AF_INET;
353 	if (!inet_aton(host, &srvp->addr.sin_addr)) {
354 		struct hostent *hent;
355 
356 		if ((hent = gethostbyname(host)) == NULL) {
357 			generr(h, "%s: host not found", host);
358 			return -1;
359 		}
360 		(void)memcpy(&srvp->addr.sin_addr, hent->h_addr,
361 		    sizeof srvp->addr.sin_addr);
362 	}
363 	if (port != 0)
364 		srvp->addr.sin_port = htons((u_short)port);
365 	else {
366 		struct servent *sent;
367 
368 		if (h->type == RADIUS_AUTH)
369 			srvp->addr.sin_port =
370 			    (sent = getservbyname("radius", "udp")) != NULL ?
371 				sent->s_port : htons(RADIUS_PORT);
372 		else
373 			srvp->addr.sin_port =
374 			    (sent = getservbyname("radacct", "udp")) != NULL ?
375 				sent->s_port : htons(RADACCT_PORT);
376 	}
377 	if ((srvp->secret = strdup(secret)) == NULL) {
378 		generr(h, "Out of memory");
379 		return -1;
380 	}
381 	srvp->timeout = timeout;
382 	srvp->max_tries = tries;
383 	srvp->num_tries = 0;
384 	h->num_servers++;
385 	return 0;
386 }
387 
388 void
389 rad_close(struct rad_handle *h)
390 {
391 	size_t srv;
392 
393 	if (h->fd != -1)
394 		close(h->fd);
395 	for (srv = 0;  srv < h->num_servers;  srv++) {
396 		(void)memset(h->servers[srv].secret, 0,
397 		    strlen(h->servers[srv].secret));
398 		free(h->servers[srv].secret);
399 	}
400 	clear_password(h);
401 	free(h);
402 }
403 
404 int
405 rad_config(struct rad_handle *h, const char *path)
406 {
407 	FILE *fp;
408 	char buf[MAXCONFLINE];
409 	int linenum;
410 	int retval;
411 
412 	if (path == NULL)
413 		path = PATH_RADIUS_CONF;
414 	if ((fp = fopen(path, "r")) == NULL) {
415 		generr(h, "Cannot open \"%s\": %s", path, strerror(errno));
416 		return -1;
417 	}
418 	retval = 0;
419 	linenum = 0;
420 	while (fgets(buf, (int)sizeof buf, fp) != NULL) {
421 		size_t len;
422 		const char *fields[5];
423 		size_t nfields;
424 		char msg[ERRSIZE];
425 		const char *type;
426 		const char *host;
427 		char *res;
428 		const char *port_str;
429 		const char *secret;
430 		const char *timeout_str;
431 		const char *maxtries_str;
432 		char *end;
433 		const char *wanttype;
434 		unsigned long timeout;
435 		unsigned long maxtries;
436 		int port;
437 		size_t i;
438 
439 		linenum++;
440 		len = strlen(buf);
441 		/* We know len > 0, else fgets would have returned NULL. */
442 		if (buf[len - 1] != '\n') {
443 			if (len == sizeof buf - 1)
444 				generr(h, "%s:%d: line too long", path,
445 				    linenum);
446 			else
447 				generr(h, "%s:%d: missing newline", path,
448 				    linenum);
449 			retval = -1;
450 			break;
451 		}
452 		buf[len - 1] = '\0';
453 
454 		/* Extract the fields from the line. */
455 		msg[0] = '\0';
456 		nfields = split(buf, fields, sizeof(fields) / sizeof(fields[0]),
457 		    msg, sizeof msg);
458 		if (msg[0] != '\0') {
459 			generr(h, "%s:%d: %s", path, linenum, msg);
460 			retval = -1;
461 			break;
462 		}
463 		if (nfields == 0)
464 			continue;
465 		/*
466 		 * The first field should contain "auth" or "acct" for
467 		 * authentication or accounting, respectively.  But older
468 		 * versions of the file didn't have that field.  Default
469 		 * it to "auth" for backward compatibility.
470 		 */
471 		if (strcmp(fields[0], "auth") != 0 &&
472 		    strcmp(fields[0], "acct") != 0) {
473 			if (nfields >= 5) {
474 				generr(h, "%s:%d: invalid service type", path,
475 				    linenum);
476 				retval = -1;
477 				break;
478 			}
479 			nfields++;
480 			for (i = nfields;  --i > 0;  )
481 				fields[i] = fields[i - 1];
482 			fields[0] = "auth";
483 		}
484 		if (nfields < 3) {
485 			generr(h, "%s:%d: missing shared secret", path,
486 			    linenum);
487 			retval = -1;
488 			break;
489 		}
490 		type = fields[0];
491 		host = fields[1];
492 		secret = fields[2];
493 		timeout_str = fields[3];
494 		maxtries_str = fields[4];
495 
496 		/* Ignore the line if it is for the wrong service type. */
497 		wanttype = h->type == RADIUS_AUTH ? "auth" : "acct";
498 		if (strcmp(type, wanttype) != 0)
499 			continue;
500 
501 		/* Parse and validate the fields. */
502 		res = __UNCONST(host);
503 		host = strsep(&res, ":");
504 		port_str = strsep(&res, ":");
505 		if (port_str != NULL) {
506 			port = (int)strtoul(port_str, &end, 10);
507 			if (*end != '\0') {
508 				generr(h, "%s:%d: invalid port", path,
509 				    linenum);
510 				retval = -1;
511 				break;
512 			}
513 		} else
514 			port = 0;
515 		if (timeout_str != NULL) {
516 			timeout = strtoul(timeout_str, &end, 10);
517 			if (*end != '\0') {
518 				generr(h, "%s:%d: invalid timeout", path,
519 				    linenum);
520 				retval = -1;
521 				break;
522 			}
523 		} else
524 			timeout = TIMEOUT;
525 		if (maxtries_str != NULL) {
526 			maxtries = strtoul(maxtries_str, &end, 10);
527 			if (*end != '\0') {
528 				generr(h, "%s:%d: invalid maxtries", path,
529 				    linenum);
530 				retval = -1;
531 				break;
532 			}
533 		} else
534 			maxtries = MAXTRIES;
535 
536 		if (rad_add_server(h, host, port, secret, (int)timeout,
537 		    (int)maxtries) == -1) {
538 			(void)strcpy(msg, h->errmsg);
539 			generr(h, "%s:%d: %s", path, linenum, msg);
540 			retval = -1;
541 			break;
542 		}
543 	}
544 	/* Clear out the buffer to wipe a possible copy of a shared secret */
545 	(void)memset(buf, 0, sizeof buf);
546 	fclose(fp);
547 	return retval;
548 }
549 
550 /*
551  * rad_init_send_request() must have previously been called.
552  * Returns:
553  *   0     The application should select on *fd with a timeout of tv before
554  *         calling rad_continue_send_request again.
555  *   < 0   Failure
556  *   > 0   Success
557  */
558 int
559 rad_continue_send_request(struct rad_handle *h, int selected, int *fd,
560                           struct timeval *tv)
561 {
562 	ssize_t n;
563 
564 	if (selected) {
565 		struct sockaddr_in from;
566 		socklen_t fromlen;
567 		ssize_t rv;
568 
569 		fromlen = sizeof from;
570 		rv = recvfrom(h->fd, h->response, (size_t)MSGSIZE,
571 		    MSG_WAITALL, (struct sockaddr *)(void *)&from, &fromlen);
572 		if (rv == -1) {
573 			generr(h, "recvfrom: %s", strerror(errno));
574 			return -1;
575 		}
576 		h->resp_len = rv;
577 		if (is_valid_response(h, h->srv, &from)) {
578 			h->resp_len = h->response[POS_LENGTH] << 8 |
579 			    h->response[POS_LENGTH+1];
580 			h->resp_pos = POS_ATTRS;
581 			return h->response[POS_CODE];
582 		}
583 	}
584 
585 	if (h->try == h->total_tries) {
586 		generr(h, "No valid RADIUS responses received");
587 		return -1;
588 	}
589 
590 	/*
591          * Scan round-robin to the next server that has some
592          * tries left.  There is guaranteed to be one, or we
593          * would have exited this loop by now.
594 	 */
595 	while (h->servers[h->srv].num_tries >= h->servers[h->srv].max_tries)
596 		if (++h->srv >= h->num_servers)
597 			h->srv = 0;
598 
599 	if (h->request[POS_CODE] == RAD_ACCOUNTING_REQUEST)
600 		/* Insert the request authenticator into the request */
601 		insert_request_authenticator(h, h->srv);
602 	else
603 		/* Insert the scrambled password into the request */
604 		if (h->pass_pos != 0)
605 			insert_scrambled_password(h, h->srv);
606 
607 	insert_message_authenticator(h, h->srv);
608 
609 	/* Send the request */
610 	n = sendto(h->fd, h->request, h->req_len, 0,
611 	    (const struct sockaddr *)(void *)&h->servers[h->srv].addr,
612 	    (socklen_t)sizeof h->servers[h->srv].addr);
613 	if (n != (ssize_t)h->req_len) {
614 		if (n == -1)
615 			generr(h, "sendto: %s", strerror(errno));
616 		else
617 			generr(h, "sendto: short write");
618 		return -1;
619 	}
620 
621 	h->try++;
622 	h->servers[h->srv].num_tries++;
623 	tv->tv_sec = h->servers[h->srv].timeout;
624 	tv->tv_usec = 0;
625 	*fd = h->fd;
626 
627 	return 0;
628 }
629 
630 int
631 rad_create_request(struct rad_handle *h, int code)
632 {
633 	int i;
634 
635 	h->request[POS_CODE] = code;
636 	h->request[POS_IDENT] = ++h->ident;
637 	/* Create a random authenticator */
638 	for (i = 0;  i < LEN_AUTH;  i += 2) {
639 		uint32_t r;
640 		r = (uint32_t)random();
641 		h->request[POS_AUTH+i] = (u_char)r;
642 		h->request[POS_AUTH+i+1] = (u_char)(r >> 8);
643 	}
644 	h->req_len = POS_ATTRS;
645 	clear_password(h);
646 	h->request_created = 1;
647 	return 0;
648 }
649 
650 struct in_addr
651 rad_cvt_addr(const void *data)
652 {
653 	struct in_addr value;
654 
655 	(void)memcpy(&value.s_addr, data, sizeof value.s_addr);
656 	return value;
657 }
658 
659 u_int32_t
660 rad_cvt_int(const void *data)
661 {
662 	u_int32_t value;
663 
664 	(void)memcpy(&value, data, sizeof value);
665 	return ntohl(value);
666 }
667 
668 char *
669 rad_cvt_string(const void *data, size_t len)
670 {
671 	char *s;
672 
673 	s = malloc(len + 1);
674 	if (s != NULL) {
675 		(void)memcpy(s, data, len);
676 		s[len] = '\0';
677 	}
678 	return s;
679 }
680 
681 /*
682  * Returns the attribute type.  If none are left, returns 0.  On failure,
683  * returns -1.
684  */
685 int
686 rad_get_attr(struct rad_handle *h, const void **value, size_t *len)
687 {
688 	int type;
689 
690 	if (h->resp_pos >= h->resp_len)
691 		return 0;
692 	if (h->resp_pos + 2 > h->resp_len) {
693 		generr(h, "Malformed attribute in response");
694 		return -1;
695 	}
696 	type = h->response[h->resp_pos++];
697 	*len = h->response[h->resp_pos++] - 2;
698 	if (h->resp_pos + (int)*len > h->resp_len) {
699 		generr(h, "Malformed attribute in response");
700 		return -1;
701 	}
702 	*value = &h->response[h->resp_pos];
703 	h->resp_pos += (int)*len;
704 	return type;
705 }
706 
707 /*
708  * Returns -1 on error, 0 to indicate no event and >0 for success
709  */
710 int
711 rad_init_send_request(struct rad_handle *h, int *fd, struct timeval *tv)
712 {
713 	size_t srv;
714 
715 	/* Make sure we have a socket to use */
716 	if (h->fd == -1) {
717 		struct sockaddr_in saddr;
718 
719 		if ((h->fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
720 			generr(h, "Cannot create socket: %s", strerror(errno));
721 			return -1;
722 		}
723 		(void)memset(&saddr, 0, sizeof saddr);
724 		saddr.sin_len = sizeof saddr;
725 		saddr.sin_family = AF_INET;
726 		saddr.sin_addr.s_addr = INADDR_ANY;
727 		saddr.sin_port = htons(0);
728 		if (bind(h->fd, (const struct sockaddr *)(void *)&saddr,
729 		    (socklen_t)sizeof saddr) == -1) {
730 			generr(h, "bind: %s", strerror(errno));
731 			close(h->fd);
732 			h->fd = -1;
733 			return -1;
734 		}
735 	}
736 
737 	if (h->request[POS_CODE] == RAD_ACCOUNTING_REQUEST) {
738 		/* Make sure no password given */
739 		if (h->pass_pos || h->chap_pass) {
740 			generr(h, "User or Chap Password"
741 			    " in accounting request");
742 			return -1;
743 		}
744 	} else {
745 		if (h->eap_msg == 0) {
746 			/* Make sure the user gave us a password */
747 			if (h->pass_pos == 0 && !h->chap_pass) {
748 				generr(h, "No User or Chap Password"
749 				    " attributes given");
750 				return -1;
751 			}
752 			if (h->pass_pos != 0 && h->chap_pass) {
753 				generr(h, "Both User and Chap Password"
754 				    " attributes given");
755 				return -1;
756 			}
757 		}
758 	}
759 
760 	/* Fill in the length field in the message */
761 	h->request[POS_LENGTH] = (unsigned char)(h->req_len >> 8);
762 	h->request[POS_LENGTH+1] = (unsigned char)h->req_len;
763 
764 	/*
765 	 * Count the total number of tries we will make, and zero the
766 	 * counter for each server.
767 	 */
768 	h->total_tries = 0;
769 	for (srv = 0;  srv < h->num_servers;  srv++) {
770 		h->total_tries += h->servers[srv].max_tries;
771 		h->servers[srv].num_tries = 0;
772 	}
773 	if (h->total_tries == 0) {
774 		generr(h, "No RADIUS servers specified");
775 		return -1;
776 	}
777 
778 	h->try = h->srv = 0;
779 
780 	return rad_continue_send_request(h, 0, fd, tv);
781 }
782 
783 /*
784  * Create and initialize a rad_handle structure, and return it to the
785  * caller.  Can fail only if the necessary memory cannot be allocated.
786  * In that case, it returns NULL.
787  */
788 struct rad_handle *
789 rad_auth_open(void)
790 {
791 	struct rad_handle *h;
792 
793 	h = (struct rad_handle *)malloc(sizeof(struct rad_handle));
794 	if (h != NULL) {
795 		srandomdev(0);
796 		h->fd = -1;
797 		h->num_servers = 0;
798 		h->ident = random();
799 		h->errmsg[0] = '\0';
800 		(void)memset(h->pass, 0, sizeof h->pass);
801 		h->pass_len = 0;
802 		h->pass_pos = 0;
803 		h->chap_pass = 0;
804 		h->authentic_pos = 0;
805 		h->type = RADIUS_AUTH;
806 		h->request_created = 0;
807 		h->eap_msg = 0;
808 	}
809 	return h;
810 }
811 
812 struct rad_handle *
813 rad_acct_open(void)
814 {
815 	struct rad_handle *h;
816 
817 	h = rad_open();
818 	if (h != NULL)
819 	        h->type = RADIUS_ACCT;
820 	return h;
821 }
822 
823 struct rad_handle *
824 rad_open(void)
825 {
826     return rad_auth_open();
827 }
828 
829 int
830 rad_put_addr(struct rad_handle *h, int type, struct in_addr addr)
831 {
832 	return rad_put_attr(h, type, &addr.s_addr, sizeof addr.s_addr);
833 }
834 
835 int
836 rad_put_attr(struct rad_handle *h, int type, const void *value, size_t len)
837 {
838 	int result;
839 
840 	if (!h->request_created) {
841 		generr(h, "Please call rad_create_request()"
842 		    " before putting attributes");
843 		return -1;
844 	}
845 
846 	if (h->request[POS_CODE] == RAD_ACCOUNTING_REQUEST) {
847 		if (type == RAD_EAP_MESSAGE) {
848 			generr(h, "EAP-Message attribute is not valid"
849 			    " in accounting requests");
850 			return -1;
851 		}
852 	}
853 
854 	/*
855 	 * When proxying EAP Messages, the Message Authenticator
856 	 * MUST be present; see RFC 3579.
857 	 */
858 	if (type == RAD_EAP_MESSAGE) {
859 		if (rad_put_message_authentic(h) == -1)
860 			return -1;
861 	}
862 
863 	if (type == RAD_USER_PASSWORD) {
864 		result = put_password_attr(h, type, value, len);
865 	} else if (type == RAD_MESSAGE_AUTHENTIC) {
866 		result = rad_put_message_authentic(h);
867 	} else {
868 		result = put_raw_attr(h, type, value, len);
869 		if (result == 0) {
870 			if (type == RAD_CHAP_PASSWORD)
871 				h->chap_pass = 1;
872 			else if (type == RAD_EAP_MESSAGE)
873 				h->eap_msg = 1;
874 		}
875 	}
876 
877 	return result;
878 }
879 
880 int
881 rad_put_int(struct rad_handle *h, int type, u_int32_t value)
882 {
883 	u_int32_t nvalue;
884 
885 	nvalue = htonl(value);
886 	return rad_put_attr(h, type, &nvalue, sizeof nvalue);
887 }
888 
889 int
890 rad_put_string(struct rad_handle *h, int type, const char *str)
891 {
892 	return rad_put_attr(h, type, str, strlen(str));
893 }
894 
895 int
896 rad_put_message_authentic(struct rad_handle *h)
897 {
898 #ifdef WITH_SSL
899 	u_char md_zero[MD5_DIGEST_LENGTH];
900 
901 	if (h->request[POS_CODE] == RAD_ACCOUNTING_REQUEST) {
902 		generr(h, "Message-Authenticator is not valid"
903 		    " in accounting requests");
904 		return -1;
905 	}
906 
907 	if (h->authentic_pos == 0) {
908 		h->authentic_pos = (int)h->req_len;
909 		(void)memset(md_zero, 0, sizeof(md_zero));
910 		return (put_raw_attr(h, RAD_MESSAGE_AUTHENTIC, md_zero,
911 		    sizeof(md_zero)));
912 	}
913 	return 0;
914 #else
915 	generr(h, "Message Authenticator not supported,"
916 	    " please recompile libradius with SSL support");
917 	return -1;
918 #endif
919 }
920 
921 /*
922  * Returns the response type code on success, or -1 on failure.
923  */
924 int
925 rad_send_request(struct rad_handle *h)
926 {
927 	struct timeval timelimit;
928 	struct timeval tv;
929 	int fd;
930 	int n;
931 
932 	n = rad_init_send_request(h, &fd, &tv);
933 
934 	if (n != 0)
935 		return n;
936 
937 	gettimeofday(&timelimit, NULL);
938 	timeradd(&tv, &timelimit, &timelimit);
939 
940 	for ( ; ; ) {
941 		fd_set readfds;
942 
943 		FD_ZERO(&readfds);
944 		FD_SET(fd, &readfds);
945 
946 		n = select(fd + 1, &readfds, NULL, NULL, &tv);
947 
948 		if (n == -1) {
949 			generr(h, "select: %s", strerror(errno));
950 			return -1;
951 		}
952 
953 		if (!FD_ISSET(fd, &readfds)) {
954 			/* Compute a new timeout */
955 			gettimeofday(&tv, NULL);
956 			timersub(&timelimit, &tv, &tv);
957 			if (tv.tv_sec > 0 || (tv.tv_sec == 0 && tv.tv_usec > 0))
958 				/* Continue the select */
959 				continue;
960 		}
961 
962 		n = rad_continue_send_request(h, n, &fd, &tv);
963 
964 		if (n != 0)
965 			return n;
966 
967 		gettimeofday(&timelimit, NULL);
968 		timeradd(&tv, &timelimit, &timelimit);
969 	}
970 }
971 
972 const char *
973 rad_strerror(struct rad_handle *h)
974 {
975 	return h->errmsg;
976 }
977 
978 /*
979  * Destructively split a string into fields separated by white space.
980  * `#' at the beginning of a field begins a comment that extends to the
981  * end of the string.  Fields may be quoted with `"'.  Inside quoted
982  * strings, the backslash escapes `\"' and `\\' are honored.
983  *
984  * Pointers to up to the first maxfields fields are stored in the fields
985  * array.  Missing fields get NULL pointers.
986  *
987  * The return value is the actual number of fields parsed, and is always
988  * <= maxfields.
989  *
990  * On a syntax error, places a message in the msg string, and returns
991  * SIZE_MAX.
992  */
993 static size_t
994 split(char *str, const char *fields[], size_t maxfields, char *msg,
995     size_t msglen)
996 {
997 	char *p;
998 	size_t i;
999 	static const char ws[] = " \t";
1000 
1001 	for (i = 0;  i < maxfields;  i++)
1002 		fields[i] = NULL;
1003 	p = str;
1004 	i = 0;
1005 	while (*p != '\0') {
1006 		p += strspn(p, ws);
1007 		if (*p == '#' || *p == '\0')
1008 			break;
1009 		if (i >= maxfields) {
1010 			snprintf(msg, msglen, "line has too many fields");
1011 			return SIZE_MAX;
1012 		}
1013 		if (*p == '"') {
1014 			char *dst;
1015 
1016 			dst = ++p;
1017 			fields[i] = dst;
1018 			while (*p != '"') {
1019 				if (*p == '\\') {
1020 					p++;
1021 					if (*p != '"' && *p != '\\' &&
1022 					    *p != '\0') {
1023 						snprintf(msg, msglen,
1024 						    "invalid `\\' escape");
1025 						return SIZE_MAX;
1026 					}
1027 				}
1028 				if (*p == '\0') {
1029 					snprintf(msg, msglen,
1030 					    "unterminated quoted string");
1031 					return SIZE_MAX;
1032 				}
1033 				*dst++ = *p++;
1034 			}
1035 			*dst = '\0';
1036 			p++;
1037 			if (*fields[i] == '\0') {
1038 				snprintf(msg, msglen,
1039 				    "empty quoted string not permitted");
1040 				return SIZE_MAX;
1041 			}
1042 			if (*p != '\0' && strspn(p, ws) == 0) {
1043 				snprintf(msg, msglen, "quoted string not"
1044 				    " followed by white space");
1045 				return SIZE_MAX;
1046 			}
1047 		} else {
1048 			fields[i] = p;
1049 			p += strcspn(p, ws);
1050 			if (*p != '\0')
1051 				*p++ = '\0';
1052 		}
1053 		i++;
1054 	}
1055 	return i;
1056 }
1057 
1058 int
1059 rad_get_vendor_attr(u_int32_t *vendor, const void **data, size_t *len)
1060 {
1061 	const struct vendor_attribute *attr;
1062 
1063 	attr = (const struct vendor_attribute *)*data;
1064 	*vendor = ntohl(attr->vendor_value);
1065 	*data = attr->attrib_data;
1066 	*len = attr->attrib_len - 2;
1067 
1068 	return (attr->attrib_type);
1069 }
1070 
1071 int
1072 rad_put_vendor_addr(struct rad_handle *h, int vendor, int type,
1073     struct in_addr addr)
1074 {
1075 	return (rad_put_vendor_attr(h, vendor, type, &addr.s_addr,
1076 	    sizeof addr.s_addr));
1077 }
1078 
1079 int
1080 rad_put_vendor_attr(struct rad_handle *h, int vendor, int type,
1081     const void *value, size_t len)
1082 {
1083 	struct vendor_attribute *attr;
1084 	int res;
1085 
1086 	if (!h->request_created) {
1087 		generr(h, "Please call rad_create_request()"
1088 		    " before putting attributes");
1089 		return -1;
1090 	}
1091 
1092 	if ((attr = malloc(len + 6)) == NULL) {
1093 		generr(h, "malloc failure (%zu bytes)", len + 6);
1094 		return -1;
1095 	}
1096 
1097 	attr->vendor_value = htonl((uint32_t)vendor);
1098 	attr->attrib_type = type;
1099 	attr->attrib_len = (unsigned char)(len + 2);
1100 	(void)memcpy(attr->attrib_data, value, len);
1101 
1102 	res = put_raw_attr(h, RAD_VENDOR_SPECIFIC, attr, len + 6);
1103 	free(attr);
1104 	if (res == 0 && vendor == RAD_VENDOR_MICROSOFT
1105 	    && (type == RAD_MICROSOFT_MS_CHAP_RESPONSE
1106 	    || type == RAD_MICROSOFT_MS_CHAP2_RESPONSE)) {
1107 		h->chap_pass = 1;
1108 	}
1109 	return (res);
1110 }
1111 
1112 int
1113 rad_put_vendor_int(struct rad_handle *h, int vendor, int type, u_int32_t i)
1114 {
1115 	u_int32_t value;
1116 
1117 	value = htonl(i);
1118 	return (rad_put_vendor_attr(h, vendor, type, &value, sizeof value));
1119 }
1120 
1121 int
1122 rad_put_vendor_string(struct rad_handle *h, int vendor, int type,
1123     const char *str)
1124 {
1125 	return (rad_put_vendor_attr(h, vendor, type, str, strlen(str)));
1126 }
1127 
1128 ssize_t
1129 rad_request_authenticator(struct rad_handle *h, char *buf, size_t len)
1130 {
1131 	if (len < LEN_AUTH)
1132 		return (-1);
1133 	(void)memcpy(buf, h->request + POS_AUTH, (size_t)LEN_AUTH);
1134 	if (len > LEN_AUTH)
1135 		buf[LEN_AUTH] = '\0';
1136 	return (LEN_AUTH);
1137 }
1138 
1139 u_char *
1140 rad_demangle(struct rad_handle *h, const void *mangled, size_t mlen)
1141 {
1142 	char R[LEN_AUTH];
1143 	const char *S;
1144 	int i, Ppos;
1145 	MD5_CTX Context;
1146 	u_char b[MD5_DIGEST_LENGTH], *demangled;
1147 	const u_char *C;
1148 
1149 	if ((mlen % 16 != 0) || mlen > 128) {
1150 		generr(h, "Cannot interpret mangled data of length %lu",
1151 		    (u_long)mlen);
1152 		return NULL;
1153 	}
1154 
1155 	C = (const u_char *)mangled;
1156 
1157 	/* We need the shared secret as Salt */
1158 	S = rad_server_secret(h);
1159 
1160 	/* We need the request authenticator */
1161 	if (rad_request_authenticator(h, R, sizeof R) != LEN_AUTH) {
1162 		generr(h, "Cannot obtain the RADIUS request authenticator");
1163 		return NULL;
1164 	}
1165 
1166 	demangled = malloc(mlen);
1167 	if (!demangled)
1168 		return NULL;
1169 
1170 	MD5Init(&Context);
1171 	MD5Update(&Context, (MD5Buf)S, (MD5Len)strlen(S));
1172 	MD5Update(&Context, (MD5Buf)R, (MD5Len)LEN_AUTH);
1173 	MD5Final(b, &Context);
1174 	Ppos = 0;
1175 	while (mlen) {
1176 
1177 		mlen -= 16;
1178 		for (i = 0; i < 16; i++)
1179 			demangled[Ppos++] = C[i] ^ b[i];
1180 
1181 		if (mlen) {
1182 			MD5Init(&Context);
1183 			MD5Update(&Context, (MD5Buf)S, (MD5Len)strlen(S));
1184 			MD5Update(&Context, (MD5Buf)C, (MD5Len)16);
1185 			MD5Final(b, &Context);
1186 		}
1187 
1188 		C += 16;
1189 	}
1190 
1191 	return demangled;
1192 }
1193 
1194 u_char *
1195 rad_demangle_mppe_key(struct rad_handle *h, const void *mangled,
1196     size_t mlen, size_t *len)
1197 {
1198 	char R[LEN_AUTH];    /* variable names as per rfc2548 */
1199 	const char *S;
1200 	u_char b[MD5_DIGEST_LENGTH], *demangled = NULL;
1201 	const u_char *A, *C;
1202 	MD5_CTX Context;
1203 	size_t Slen, Clen, i, Ppos;
1204 	u_char *P;
1205 
1206 	if (mlen % 16 != SALT_LEN) {
1207 		generr(h, "Cannot interpret mangled data of length %lu",
1208 		    (u_long)mlen);
1209 		return NULL;
1210 	}
1211 
1212 	/* We need the RADIUS Request-Authenticator */
1213 	if (rad_request_authenticator(h, R, sizeof R) != LEN_AUTH) {
1214 		generr(h, "Cannot obtain the RADIUS request authenticator");
1215 		return NULL;
1216 	}
1217 
1218 	A = (const u_char *)mangled;      /* Salt comes first */
1219 	C = (const u_char *)mangled + SALT_LEN;  /* Then the ciphertext */
1220 	Clen = mlen - SALT_LEN;
1221 	S = rad_server_secret(h);    /* We need the RADIUS secret */
1222 	Slen = strlen(S);
1223 	P = malloc(Clen);        /* We derive our plaintext */
1224 
1225 	MD5Init(&Context);
1226 	MD5Update(&Context, (MD5Buf)S, (MD5Len)Slen);
1227 	MD5Update(&Context, (MD5Buf)R, (MD5Len)LEN_AUTH);
1228 	MD5Update(&Context, (MD5Buf)A, (MD5Len)SALT_LEN);
1229 	MD5Final(b, &Context);
1230 	Ppos = 0;
1231 
1232 	while (Clen) {
1233 		Clen -= 16;
1234 
1235 		for (i = 0; i < 16; i++)
1236 		    P[Ppos++] = C[i] ^ b[i];
1237 
1238 		if (Clen) {
1239 			MD5Init(&Context);
1240 			MD5Update(&Context, (MD5Buf)S, (MD5Len)Slen);
1241 			MD5Update(&Context, (MD5Buf)C, (MD5Len)16);
1242 			MD5Final(b, &Context);
1243 		}
1244 
1245 		C += 16;
1246 	}
1247 
1248 	/*
1249 	* The resulting plain text consists of a one-byte length, the text and
1250 	* maybe some padding.
1251 	*/
1252 	*len = *P;
1253 	if (*len > mlen - 1) {
1254 		generr(h, "Mangled data seems to be garbage %zu %zu",
1255 		    *len, mlen-1);
1256 		goto out;
1257 	}
1258 
1259 	if (*len > MPPE_KEY_LEN * 2) {
1260 		generr(h, "Key to long (%zu) for me max. %d",
1261 		    *len, MPPE_KEY_LEN * 2);
1262 		goto out;
1263 	}
1264 	demangled = malloc(*len);
1265 	if (!demangled)
1266 		goto out;
1267 
1268 	(void)memcpy(demangled, P + 1, *len);
1269 out:
1270 	free(P);
1271 	return demangled;
1272 }
1273 
1274 const char *
1275 rad_server_secret(struct rad_handle *h)
1276 {
1277 	return (h->servers[h->srv].secret);
1278 }
1279