xref: /freebsd/lib/libradius/radlib.c (revision 72143e89bb430c3b1406b399b810806904f6c882)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
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 __FBSDID("$FreeBSD$");
31 
32 #include <sys/types.h>
33 #include <sys/socket.h>
34 #include <sys/time.h>
35 #include <netinet/in.h>
36 #include <arpa/inet.h>
37 #ifdef WITH_SSL
38 #include <openssl/hmac.h>
39 #include <openssl/md5.h>
40 #define MD5Init MD5_Init
41 #define MD5Update MD5_Update
42 #define MD5Final MD5_Final
43 #else
44 #define MD5_DIGEST_LENGTH 16
45 #include <md5.h>
46 #endif
47 
48 #define	MAX_FIELDS	7
49 
50 /* We need the MPPE_KEY_LEN define */
51 #include <netgraph/ng_mppc.h>
52 
53 #include <errno.h>
54 #include <netdb.h>
55 #include <stdarg.h>
56 #include <stddef.h>
57 #include <stdio.h>
58 #include <stdlib.h>
59 #include <string.h>
60 #include <unistd.h>
61 
62 #include "radlib_private.h"
63 
64 static void	 clear_password(struct rad_handle *);
65 static void	 generr(struct rad_handle *, const char *, ...)
66 		    __printflike(2, 3);
67 static void	 insert_scrambled_password(struct rad_handle *, int);
68 static void	 insert_request_authenticator(struct rad_handle *, int);
69 static void	 insert_message_authenticator(struct rad_handle *, int);
70 static int	 is_valid_response(struct rad_handle *, int,
71 		    const struct sockaddr_in *);
72 static int	 put_password_attr(struct rad_handle *, int,
73 		    const void *, size_t);
74 static int	 put_raw_attr(struct rad_handle *, int,
75 		    const void *, size_t);
76 static int	 split(char *, char *[], int, char *, size_t);
77 
78 static void
79 clear_password(struct rad_handle *h)
80 {
81 	if (h->pass_len != 0) {
82 		explicit_bzero(h->pass, h->pass_len);
83 		h->pass_len = 0;
84 	}
85 	h->pass_pos = 0;
86 }
87 
88 static void
89 generr(struct rad_handle *h, const char *format, ...)
90 {
91 	va_list		 ap;
92 
93 	va_start(ap, format);
94 	vsnprintf(h->errmsg, ERRSIZE, format, ap);
95 	va_end(ap);
96 }
97 
98 static void
99 insert_scrambled_password(struct rad_handle *h, int srv)
100 {
101 	MD5_CTX ctx;
102 	unsigned char md5[MD5_DIGEST_LENGTH];
103 	const struct rad_server *srvp;
104 	int padded_len;
105 	int pos;
106 
107 	srvp = &h->servers[srv];
108 	padded_len = h->pass_len == 0 ? 16 : (h->pass_len+15) & ~0xf;
109 
110 	memcpy(md5, &h->out[POS_AUTH], LEN_AUTH);
111 	for (pos = 0;  pos < padded_len;  pos += 16) {
112 		int i;
113 
114 		/* Calculate the new scrambler */
115 		MD5Init(&ctx);
116 		MD5Update(&ctx, srvp->secret, strlen(srvp->secret));
117 		MD5Update(&ctx, md5, 16);
118 		MD5Final(md5, &ctx);
119 
120 		/*
121 		 * Mix in the current chunk of the password, and copy
122 		 * the result into the right place in the request.  Also
123 		 * modify the scrambler in place, since we will use this
124 		 * in calculating the scrambler for next time.
125 		 */
126 		for (i = 0;  i < 16;  i++)
127 			h->out[h->pass_pos + pos + i] =
128 			    md5[i] ^= h->pass[pos + i];
129 	}
130 }
131 
132 static void
133 insert_request_authenticator(struct rad_handle *h, int resp)
134 {
135 	MD5_CTX ctx;
136 	const struct rad_server *srvp;
137 
138 	srvp = &h->servers[h->srv];
139 
140 	/* Create the request authenticator */
141 	MD5Init(&ctx);
142 	MD5Update(&ctx, &h->out[POS_CODE], POS_AUTH - POS_CODE);
143 	if (resp)
144 	    MD5Update(&ctx, &h->in[POS_AUTH], LEN_AUTH);
145 	else
146 	    MD5Update(&ctx, &h->out[POS_AUTH], LEN_AUTH);
147 	MD5Update(&ctx, &h->out[POS_ATTRS], h->out_len - POS_ATTRS);
148 	MD5Update(&ctx, srvp->secret, strlen(srvp->secret));
149 	MD5Final(&h->out[POS_AUTH], &ctx);
150 }
151 
152 static void
153 insert_message_authenticator(struct rad_handle *h, int resp)
154 {
155 #ifdef WITH_SSL
156 	u_char md[EVP_MAX_MD_SIZE];
157 	u_int md_len;
158 	const struct rad_server *srvp;
159 	HMAC_CTX *ctx;
160 	srvp = &h->servers[h->srv];
161 
162 	if (h->authentic_pos != 0) {
163 		ctx = HMAC_CTX_new();
164 		HMAC_Init_ex(ctx, srvp->secret, strlen(srvp->secret), EVP_md5(), NULL);
165 		HMAC_Update(ctx, &h->out[POS_CODE], POS_AUTH - POS_CODE);
166 		if (resp)
167 		    HMAC_Update(ctx, &h->in[POS_AUTH], LEN_AUTH);
168 		else
169 		    HMAC_Update(ctx, &h->out[POS_AUTH], LEN_AUTH);
170 		HMAC_Update(ctx, &h->out[POS_ATTRS],
171 		    h->out_len - POS_ATTRS);
172 		HMAC_Final(ctx, md, &md_len);
173 		HMAC_CTX_free(ctx);
174 		memcpy(&h->out[h->authentic_pos + 2], md, md_len);
175 	}
176 #endif
177 }
178 
179 /*
180  * Return true if the current response is valid for a request to the
181  * specified server.
182  */
183 static int
184 is_valid_response(struct rad_handle *h, int srv,
185     const struct sockaddr_in *from)
186 {
187 	MD5_CTX ctx;
188 	unsigned char md5[MD5_DIGEST_LENGTH];
189 	const struct rad_server *srvp;
190 	int len;
191 #ifdef WITH_SSL
192 	HMAC_CTX *hctx;
193 	u_char resp[MSGSIZE], md[EVP_MAX_MD_SIZE];
194 	u_int md_len;
195 	int pos;
196 #endif
197 
198 	srvp = &h->servers[srv];
199 
200 	/* Check the source address */
201 	if (from->sin_family != srvp->addr.sin_family ||
202 	    from->sin_addr.s_addr != srvp->addr.sin_addr.s_addr ||
203 	    from->sin_port != srvp->addr.sin_port)
204 		return 0;
205 
206 	/* Check the message length */
207 	if (h->in_len < POS_ATTRS)
208 		return 0;
209 	len = h->in[POS_LENGTH] << 8 | h->in[POS_LENGTH+1];
210 	if (len > h->in_len)
211 		return 0;
212 
213 	/* Check the response authenticator */
214 	MD5Init(&ctx);
215 	MD5Update(&ctx, &h->in[POS_CODE], POS_AUTH - POS_CODE);
216 	MD5Update(&ctx, &h->out[POS_AUTH], LEN_AUTH);
217 	MD5Update(&ctx, &h->in[POS_ATTRS], len - POS_ATTRS);
218 	MD5Update(&ctx, srvp->secret, strlen(srvp->secret));
219 	MD5Final(md5, &ctx);
220 	if (memcmp(&h->in[POS_AUTH], md5, sizeof md5) != 0)
221 		return 0;
222 
223 #ifdef WITH_SSL
224 	/*
225 	 * For non accounting responses check the message authenticator,
226 	 * if any.
227 	 */
228 	if (h->in[POS_CODE] != RAD_ACCOUNTING_RESPONSE) {
229 
230 		memcpy(resp, h->in, MSGSIZE);
231 		pos = POS_ATTRS;
232 
233 		/* Search and verify the Message-Authenticator */
234 		hctx = HMAC_CTX_new();
235 		while (pos < len - 2) {
236 
237 			if (h->in[pos] == RAD_MESSAGE_AUTHENTIC) {
238 				/* zero fill the Message-Authenticator */
239 				memset(&resp[pos + 2], 0, MD5_DIGEST_LENGTH);
240 
241 				HMAC_Init_ex(hctx, srvp->secret,
242 				    strlen(srvp->secret), EVP_md5(), NULL);
243 				HMAC_Update(hctx, &h->in[POS_CODE],
244 				    POS_AUTH - POS_CODE);
245 				HMAC_Update(hctx, &h->out[POS_AUTH],
246 				    LEN_AUTH);
247 				HMAC_Update(hctx, &resp[POS_ATTRS],
248 				    h->in_len - POS_ATTRS);
249 				HMAC_Final(hctx, md, &md_len);
250 				HMAC_CTX_reset(hctx);
251 				if (memcmp(md, &h->in[pos + 2],
252 				    MD5_DIGEST_LENGTH) != 0) {
253 					HMAC_CTX_free(hctx);
254 					return 0;
255 				}
256 				break;
257 			}
258 			pos += h->in[pos + 1];
259 		}
260 		HMAC_CTX_free(hctx);
261 	}
262 #endif
263 	return 1;
264 }
265 
266 /*
267  * Return true if the current request is valid for the specified server.
268  */
269 static int
270 is_valid_request(struct rad_handle *h)
271 {
272 	MD5_CTX ctx;
273 	unsigned char md5[MD5_DIGEST_LENGTH];
274 	const struct rad_server *srvp;
275 	int len;
276 #ifdef WITH_SSL
277 	HMAC_CTX *hctx;
278 	u_char resp[MSGSIZE], md[EVP_MAX_MD_SIZE];
279 	u_int md_len;
280 	int pos;
281 #endif
282 
283 	srvp = &h->servers[h->srv];
284 
285 	/* Check the message length */
286 	if (h->in_len < POS_ATTRS)
287 		return (0);
288 	len = h->in[POS_LENGTH] << 8 | h->in[POS_LENGTH+1];
289 	if (len > h->in_len)
290 		return (0);
291 
292 	if (h->in[POS_CODE] != RAD_ACCESS_REQUEST) {
293 		uint32_t zeroes[4] = { 0, 0, 0, 0 };
294 		/* Check the request authenticator */
295 		MD5Init(&ctx);
296 		MD5Update(&ctx, &h->in[POS_CODE], POS_AUTH - POS_CODE);
297 		MD5Update(&ctx, zeroes, LEN_AUTH);
298 		MD5Update(&ctx, &h->in[POS_ATTRS], len - POS_ATTRS);
299 		MD5Update(&ctx, srvp->secret, strlen(srvp->secret));
300 		MD5Final(md5, &ctx);
301 		if (memcmp(&h->in[POS_AUTH], md5, sizeof md5) != 0)
302 			return (0);
303 	}
304 
305 #ifdef WITH_SSL
306 	/* Search and verify the Message-Authenticator */
307 	pos = POS_ATTRS;
308 	hctx = HMAC_CTX_new();
309 	while (pos < len - 2) {
310 		if (h->in[pos] == RAD_MESSAGE_AUTHENTIC) {
311 			memcpy(resp, h->in, MSGSIZE);
312 			/* zero fill the Request-Authenticator */
313 			if (h->in[POS_CODE] != RAD_ACCESS_REQUEST)
314 				memset(&resp[POS_AUTH], 0, LEN_AUTH);
315 			/* zero fill the Message-Authenticator */
316 			memset(&resp[pos + 2], 0, MD5_DIGEST_LENGTH);
317 
318 			HMAC_Init_ex(hctx, srvp->secret,
319 			    strlen(srvp->secret), EVP_md5(), NULL);
320 			HMAC_Update(hctx, resp, h->in_len);
321 			HMAC_Final(hctx, md, &md_len);
322 			HMAC_CTX_reset(hctx);
323 			if (memcmp(md, &h->in[pos + 2],
324 			    MD5_DIGEST_LENGTH) != 0) {
325 				HMAC_CTX_free(hctx);
326 				return (0);
327 			}
328 			break;
329 		}
330 		pos += h->in[pos + 1];
331 	}
332 	HMAC_CTX_free(hctx);
333 #endif
334 	return (1);
335 }
336 
337 static int
338 put_password_attr(struct rad_handle *h, int type, const void *value, size_t len)
339 {
340 	int padded_len;
341 	int pad_len;
342 
343 	if (h->pass_pos != 0) {
344 		generr(h, "Multiple User-Password attributes specified");
345 		return -1;
346 	}
347 	if (len > PASSSIZE)
348 		len = PASSSIZE;
349 	padded_len = len == 0 ? 16 : (len+15) & ~0xf;
350 	pad_len = padded_len - len;
351 
352 	/*
353 	 * Put in a place-holder attribute containing all zeros, and
354 	 * remember where it is so we can fill it in later.
355 	 */
356 	clear_password(h);
357 	put_raw_attr(h, type, h->pass, padded_len);
358 	h->pass_pos = h->out_len - padded_len;
359 
360 	/* Save the cleartext password, padded as necessary */
361 	memcpy(h->pass, value, len);
362 	h->pass_len = len;
363 	memset(h->pass + len, 0, pad_len);
364 	return 0;
365 }
366 
367 static int
368 put_raw_attr(struct rad_handle *h, int type, const void *value, size_t len)
369 {
370 	if (len > 253) {
371 		generr(h, "Attribute too long");
372 		return -1;
373 	}
374 	if (h->out_len + 2 + len > MSGSIZE) {
375 		generr(h, "Maximum message length exceeded");
376 		return -1;
377 	}
378 	h->out[h->out_len++] = type;
379 	h->out[h->out_len++] = len + 2;
380 	memcpy(&h->out[h->out_len], value, len);
381 	h->out_len += len;
382 	return 0;
383 }
384 
385 int
386 rad_add_server(struct rad_handle *h, const char *host, int port,
387     const char *secret, int timeout, int tries)
388 {
389     	struct in_addr bindto;
390 	bindto.s_addr = INADDR_ANY;
391 
392 	return rad_add_server_ex(h, host, port, secret, timeout, tries,
393 		DEAD_TIME, &bindto);
394 }
395 
396 int
397 rad_add_server_ex(struct rad_handle *h, const char *host, int port,
398     const char *secret, int timeout, int tries, int dead_time,
399     struct in_addr *bindto)
400 {
401 	struct rad_server *srvp;
402 
403 	if (h->num_servers >= MAXSERVERS) {
404 		generr(h, "Too many RADIUS servers specified");
405 		return -1;
406 	}
407 	srvp = &h->servers[h->num_servers];
408 
409 	memset(&srvp->addr, 0, sizeof srvp->addr);
410 	srvp->addr.sin_len = sizeof srvp->addr;
411 	srvp->addr.sin_family = AF_INET;
412 	if (!inet_aton(host, &srvp->addr.sin_addr)) {
413 		struct hostent *hent;
414 
415 		if ((hent = gethostbyname(host)) == NULL) {
416 			generr(h, "%s: host not found", host);
417 			return -1;
418 		}
419 		memcpy(&srvp->addr.sin_addr, hent->h_addr,
420 		    sizeof srvp->addr.sin_addr);
421 	}
422 	if (port != 0)
423 		srvp->addr.sin_port = htons((u_short)port);
424 	else {
425 		struct servent *sent;
426 
427 		if (h->type == RADIUS_AUTH)
428 			srvp->addr.sin_port =
429 			    (sent = getservbyname("radius", "udp")) != NULL ?
430 				sent->s_port : htons(RADIUS_PORT);
431 		else
432 			srvp->addr.sin_port =
433 			    (sent = getservbyname("radacct", "udp")) != NULL ?
434 				sent->s_port : htons(RADACCT_PORT);
435 	}
436 	if ((srvp->secret = strdup(secret)) == NULL) {
437 		generr(h, "Out of memory");
438 		return -1;
439 	}
440 	srvp->timeout = timeout;
441 	srvp->max_tries = tries;
442 	srvp->num_tries = 0;
443 	srvp->is_dead = 0;
444 	srvp->dead_time = dead_time;
445 	srvp->next_probe = 0;
446 	srvp->bindto = bindto->s_addr;
447 	h->num_servers++;
448 	return 0;
449 }
450 
451 void
452 rad_close(struct rad_handle *h)
453 {
454 	int srv;
455 
456 	if (h->fd != -1)
457 		close(h->fd);
458 	for (srv = 0;  srv < h->num_servers;  srv++) {
459 		memset(h->servers[srv].secret, 0,
460 		    strlen(h->servers[srv].secret));
461 		free(h->servers[srv].secret);
462 	}
463 	clear_password(h);
464 	free(h);
465 }
466 
467 void
468 rad_bind_to(struct rad_handle *h, in_addr_t addr)
469 {
470 
471 	h->bindto = addr;
472 }
473 
474 int
475 rad_config(struct rad_handle *h, const char *path)
476 {
477 	FILE *fp;
478 	char buf[MAXCONFLINE];
479 	int linenum;
480 	int retval;
481 
482 	if (path == NULL)
483 		path = PATH_RADIUS_CONF;
484 	if ((fp = fopen(path, "r")) == NULL) {
485 		generr(h, "Cannot open \"%s\": %s", path, strerror(errno));
486 		return -1;
487 	}
488 	retval = 0;
489 	linenum = 0;
490 	while (fgets(buf, sizeof buf, fp) != NULL) {
491 		int len;
492 		char *fields[MAX_FIELDS];
493 		int nfields;
494 		char msg[ERRSIZE];
495 		char *type;
496 		char *host, *res;
497 		char *port_str;
498 		char *secret;
499 		char *timeout_str;
500 		char *maxtries_str;
501 		char *dead_time_str;
502 		char *bindto_str;
503 		char *end;
504 		char *wanttype;
505 		unsigned long timeout;
506 		unsigned long maxtries;
507 		unsigned long dead_time;
508 		int port;
509 		struct in_addr bindto;
510 		int i;
511 
512 		linenum++;
513 		len = strlen(buf);
514 		/* We know len > 0, else fgets would have returned NULL. */
515 		if (buf[len - 1] != '\n') {
516 			if (len == sizeof buf - 1)
517 				generr(h, "%s:%d: line too long", path,
518 				    linenum);
519 			else
520 				generr(h, "%s:%d: missing newline", path,
521 				    linenum);
522 			retval = -1;
523 			break;
524 		}
525 		buf[len - 1] = '\0';
526 
527 		/* Extract the fields from the line. */
528 		nfields = split(buf, fields, MAX_FIELDS, msg, sizeof msg);
529 		if (nfields == -1) {
530 			generr(h, "%s:%d: %s", path, linenum, msg);
531 			retval = -1;
532 			break;
533 		}
534 		if (nfields == 0)
535 			continue;
536 		/*
537 		 * The first field should contain "auth" or "acct" for
538 		 * authentication or accounting, respectively.  But older
539 		 * versions of the file didn't have that field.  Default
540 		 * it to "auth" for backward compatibility.
541 		 */
542 		if (strcmp(fields[0], "auth") != 0 &&
543 		    strcmp(fields[0], "acct") != 0) {
544 			if (nfields >= MAX_FIELDS) {
545 				generr(h, "%s:%d: invalid service type", path,
546 				    linenum);
547 				retval = -1;
548 				break;
549 			}
550 			nfields++;
551 			for (i = nfields;  --i > 0;  )
552 				fields[i] = fields[i - 1];
553 			fields[0] = "auth";
554 		}
555 		if (nfields < 3) {
556 			generr(h, "%s:%d: missing shared secret", path,
557 			    linenum);
558 			retval = -1;
559 			break;
560 		}
561 		type = fields[0];
562 		host = fields[1];
563 		secret = fields[2];
564 		timeout_str = fields[3];
565 		maxtries_str = fields[4];
566 		dead_time_str = fields[5];
567 		bindto_str = fields[6];
568 
569 		/* Ignore the line if it is for the wrong service type. */
570 		wanttype = h->type == RADIUS_AUTH ? "auth" : "acct";
571 		if (strcmp(type, wanttype) != 0)
572 			continue;
573 
574 		/* Parse and validate the fields. */
575 		res = host;
576 		host = strsep(&res, ":");
577 		port_str = strsep(&res, ":");
578 		if (port_str != NULL) {
579 			port = strtoul(port_str, &end, 10);
580 			if (*end != '\0') {
581 				generr(h, "%s:%d: invalid port", path,
582 				    linenum);
583 				retval = -1;
584 				break;
585 			}
586 		} else
587 			port = 0;
588 		if (timeout_str != NULL) {
589 			timeout = strtoul(timeout_str, &end, 10);
590 			if (*end != '\0') {
591 				generr(h, "%s:%d: invalid timeout", path,
592 				    linenum);
593 				retval = -1;
594 				break;
595 			}
596 		} else
597 			timeout = TIMEOUT;
598 		if (maxtries_str != NULL) {
599 			maxtries = strtoul(maxtries_str, &end, 10);
600 			if (*end != '\0') {
601 				generr(h, "%s:%d: invalid maxtries", path,
602 				    linenum);
603 				retval = -1;
604 				break;
605 			}
606 		} else
607 			maxtries = MAXTRIES;
608 
609 		if (dead_time_str != NULL) {
610 			dead_time = strtoul(dead_time_str, &end, 10);
611 			if (*end != '\0') {
612 				generr(h, "%s:%d: invalid dead_time", path,
613 				    linenum);
614 				retval = -1;
615 				break;
616 			}
617 		} else
618 		    	dead_time = DEAD_TIME;
619 
620 		if (bindto_str != NULL) {
621 		    	bindto.s_addr = inet_addr(bindto_str);
622 			if (bindto.s_addr == INADDR_NONE) {
623 				generr(h, "%s:%d: invalid bindto", path,
624 				    linenum);
625 				retval = -1;
626 				break;
627 			}
628 		} else
629 		    	bindto.s_addr = INADDR_ANY;
630 
631 		if (rad_add_server_ex(h, host, port, secret, timeout, maxtries,
632 			    dead_time, &bindto) == -1) {
633 			strcpy(msg, h->errmsg);
634 			generr(h, "%s:%d: %s", path, linenum, msg);
635 			retval = -1;
636 			break;
637 		}
638 	}
639 	/* Clear out the buffer to wipe a possible copy of a shared secret */
640 	memset(buf, 0, sizeof buf);
641 	fclose(fp);
642 	return retval;
643 }
644 
645 /*
646  * rad_init_send_request() must have previously been called.
647  * Returns:
648  *   0     The application should select on *fd with a timeout of tv before
649  *         calling rad_continue_send_request again.
650  *   < 0   Failure
651  *   > 0   Success
652  */
653 int
654 rad_continue_send_request(struct rad_handle *h, int selected, int *fd,
655                           struct timeval *tv)
656 {
657 	int n, cur_srv;
658 	time_t now;
659 	struct sockaddr_in sin;
660 
661 	if (h->type == RADIUS_SERVER) {
662 		generr(h, "denied function call");
663 		return (-1);
664 	}
665 	if (selected) {
666 		struct sockaddr_in from;
667 		socklen_t fromlen;
668 
669 		fromlen = sizeof from;
670 		h->in_len = recvfrom(h->fd, h->in,
671 		    MSGSIZE, MSG_WAITALL, (struct sockaddr *)&from, &fromlen);
672 		if (h->in_len == -1) {
673 			generr(h, "recvfrom: %s", strerror(errno));
674 			return -1;
675 		}
676 		if (is_valid_response(h, h->srv, &from)) {
677 			h->in_len = h->in[POS_LENGTH] << 8 |
678 			    h->in[POS_LENGTH+1];
679 			h->in_pos = POS_ATTRS;
680 			return h->in[POS_CODE];
681 		}
682 	}
683 
684 	/*
685          * Scan round-robin to the next server that has some
686          * tries left.  There is guaranteed to be one, or we
687          * would have exited this loop by now.
688 	 */
689 	cur_srv = h->srv;
690 	now = time(NULL);
691 	if (h->servers[h->srv].num_tries >= h->servers[h->srv].max_tries) {
692 		/* Set next probe time for this server */
693 		if (h->servers[h->srv].dead_time) {
694 			h->servers[h->srv].is_dead = 1;
695 			h->servers[h->srv].next_probe = now +
696 			    h->servers[h->srv].dead_time;
697 		}
698 		do {
699 		    	h->srv++;
700 			if (h->srv >= h->num_servers)
701 				h->srv = 0;
702 			if (h->servers[h->srv].is_dead == 0)
703 			    	break;
704 			if (h->servers[h->srv].dead_time &&
705 			    h->servers[h->srv].next_probe <= now) {
706 			    	h->servers[h->srv].is_dead = 0;
707 				h->servers[h->srv].num_tries = 0;
708 				break;
709 			}
710 		} while (h->srv != cur_srv);
711 
712 		if (h->srv == cur_srv) {
713 			generr(h, "No valid RADIUS responses received");
714 			return (-1);
715 		}
716 	}
717 
718 	/* Rebind */
719 	if (h->bindto != h->servers[h->srv].bindto) {
720 	    	h->bindto = h->servers[h->srv].bindto;
721 		close(h->fd);
722 		if ((h->fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
723 			generr(h, "Cannot create socket: %s", strerror(errno));
724 			return -1;
725 		}
726 		memset(&sin, 0, sizeof sin);
727 		sin.sin_len = sizeof sin;
728 		sin.sin_family = AF_INET;
729 		sin.sin_addr.s_addr = h->bindto;
730 		sin.sin_port = 0;
731 		if (bind(h->fd, (const struct sockaddr *)&sin,
732 		    sizeof sin) == -1) {
733 			generr(h, "bind: %s", strerror(errno));
734 			close(h->fd);
735 			h->fd = -1;
736 			return (-1);
737 		}
738 	}
739 
740 	if (h->out[POS_CODE] == RAD_ACCESS_REQUEST) {
741 		/* Insert the scrambled password into the request */
742 		if (h->pass_pos != 0)
743 			insert_scrambled_password(h, h->srv);
744 	}
745 	insert_message_authenticator(h, 0);
746 
747 	if (h->out[POS_CODE] != RAD_ACCESS_REQUEST) {
748 		/* Insert the request authenticator into the request */
749 		memset(&h->out[POS_AUTH], 0, LEN_AUTH);
750 		insert_request_authenticator(h, 0);
751 	}
752 
753 	/* Send the request */
754 	n = sendto(h->fd, h->out, h->out_len, 0,
755 	    (const struct sockaddr *)&h->servers[h->srv].addr,
756 	    sizeof h->servers[h->srv].addr);
757 	if (n != h->out_len)
758 		tv->tv_sec = 1; /* Do not wait full timeout if send failed. */
759 	else
760 		tv->tv_sec = h->servers[h->srv].timeout;
761 	h->servers[h->srv].num_tries++;
762 	tv->tv_usec = 0;
763 	*fd = h->fd;
764 
765 	return 0;
766 }
767 
768 int
769 rad_receive_request(struct rad_handle *h)
770 {
771 	struct sockaddr_in from;
772 	socklen_t fromlen;
773 	int n;
774 
775 	if (h->type != RADIUS_SERVER) {
776 		generr(h, "denied function call");
777 		return (-1);
778 	}
779 	h->srv = -1;
780 	fromlen = sizeof(from);
781 	h->in_len = recvfrom(h->fd, h->in,
782 	    MSGSIZE, MSG_WAITALL, (struct sockaddr *)&from, &fromlen);
783 	if (h->in_len == -1) {
784 		generr(h, "recvfrom: %s", strerror(errno));
785 		return (-1);
786 	}
787 	for (n = 0; n < h->num_servers; n++) {
788 		if (h->servers[n].addr.sin_addr.s_addr == from.sin_addr.s_addr) {
789 			h->servers[n].addr.sin_port = from.sin_port;
790 			h->srv = n;
791 			break;
792 		}
793 	}
794 	if (h->srv == -1)
795 		return (-2);
796 	if (is_valid_request(h)) {
797 		h->in_len = h->in[POS_LENGTH] << 8 |
798 		    h->in[POS_LENGTH+1];
799 		h->in_pos = POS_ATTRS;
800 		return (h->in[POS_CODE]);
801 	}
802 	return (-3);
803 }
804 
805 int
806 rad_send_response(struct rad_handle *h)
807 {
808 	int n;
809 
810 	if (h->type != RADIUS_SERVER) {
811 		generr(h, "denied function call");
812 		return (-1);
813 	}
814 	/* Fill in the length field in the message */
815 	h->out[POS_LENGTH] = h->out_len >> 8;
816 	h->out[POS_LENGTH+1] = h->out_len;
817 
818 	insert_message_authenticator(h,
819 	    (h->in[POS_CODE] == RAD_ACCESS_REQUEST) ? 1 : 0);
820 	insert_request_authenticator(h, 1);
821 
822 	/* Send the request */
823 	n = sendto(h->fd, h->out, h->out_len, 0,
824 	    (const struct sockaddr *)&h->servers[h->srv].addr,
825 	    sizeof h->servers[h->srv].addr);
826 	if (n != h->out_len) {
827 		if (n == -1)
828 			generr(h, "sendto: %s", strerror(errno));
829 		else
830 			generr(h, "sendto: short write");
831 		return -1;
832 	}
833 
834 	return 0;
835 }
836 
837 int
838 rad_create_request(struct rad_handle *h, int code)
839 {
840 	int i;
841 
842 	if (h->type == RADIUS_SERVER) {
843 		generr(h, "denied function call");
844 		return (-1);
845 	}
846 	if (h->num_servers == 0) {
847 	    	generr(h, "No RADIUS servers specified");
848 		return (-1);
849 	}
850 	h->out[POS_CODE] = code;
851 	h->out[POS_IDENT] = ++h->ident;
852 	if (code == RAD_ACCESS_REQUEST) {
853 		/* Create a random authenticator */
854 		for (i = 0;  i < LEN_AUTH;  i += 2) {
855 			uint32_t r;
856 			r = arc4random();
857 			h->out[POS_AUTH+i] = (u_char)r;
858 			h->out[POS_AUTH+i+1] = (u_char)(r >> 8);
859 		}
860 	} else
861 		memset(&h->out[POS_AUTH], 0, LEN_AUTH);
862 	h->out_len = POS_ATTRS;
863 	clear_password(h);
864 	h->authentic_pos = 0;
865 	h->out_created = 1;
866 	return 0;
867 }
868 
869 int
870 rad_create_response(struct rad_handle *h, int code)
871 {
872 
873 	if (h->type != RADIUS_SERVER) {
874 		generr(h, "denied function call");
875 		return (-1);
876 	}
877 	h->out[POS_CODE] = code;
878 	h->out[POS_IDENT] = h->in[POS_IDENT];
879 	memset(&h->out[POS_AUTH], 0, LEN_AUTH);
880 	h->out_len = POS_ATTRS;
881 	clear_password(h);
882 	h->authentic_pos = 0;
883 	h->out_created = 1;
884 	return 0;
885 }
886 
887 struct in_addr
888 rad_cvt_addr(const void *data)
889 {
890 	struct in_addr value;
891 
892 	memcpy(&value.s_addr, data, sizeof value.s_addr);
893 	return value;
894 }
895 
896 struct in6_addr
897 rad_cvt_addr6(const void *data)
898 {
899 	struct in6_addr value;
900 
901 	memcpy(&value.s6_addr, data, sizeof value.s6_addr);
902 	return value;
903 }
904 
905 u_int32_t
906 rad_cvt_int(const void *data)
907 {
908 	u_int32_t value;
909 
910 	memcpy(&value, data, sizeof value);
911 	return ntohl(value);
912 }
913 
914 char *
915 rad_cvt_string(const void *data, size_t len)
916 {
917 	char *s;
918 
919 	s = malloc(len + 1);
920 	if (s != NULL) {
921 		memcpy(s, data, len);
922 		s[len] = '\0';
923 	}
924 	return s;
925 }
926 
927 /*
928  * Returns the attribute type.  If none are left, returns 0.  On failure,
929  * returns -1.
930  */
931 int
932 rad_get_attr(struct rad_handle *h, const void **value, size_t *len)
933 {
934 	int type;
935 
936 	if (h->in_pos >= h->in_len)
937 		return 0;
938 	if (h->in_pos + 2 > h->in_len) {
939 		generr(h, "Malformed attribute in response");
940 		return -1;
941 	}
942 	type = h->in[h->in_pos++];
943 	*len = h->in[h->in_pos++] - 2;
944 	if (h->in_pos + (int)*len > h->in_len) {
945 		generr(h, "Malformed attribute in response");
946 		return -1;
947 	}
948 	*value = &h->in[h->in_pos];
949 	h->in_pos += *len;
950 	return type;
951 }
952 
953 /*
954  * Returns -1 on error, 0 to indicate no event and >0 for success
955  */
956 int
957 rad_init_send_request(struct rad_handle *h, int *fd, struct timeval *tv)
958 {
959 	int srv;
960 	time_t now;
961 	struct sockaddr_in sin;
962 
963 	if (h->type == RADIUS_SERVER) {
964 		generr(h, "denied function call");
965 		return (-1);
966 	}
967 	/* Make sure we have a socket to use */
968 	if (h->fd == -1) {
969 		if ((h->fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
970 			generr(h, "Cannot create socket: %s", strerror(errno));
971 			return -1;
972 		}
973 		memset(&sin, 0, sizeof sin);
974 		sin.sin_len = sizeof sin;
975 		sin.sin_family = AF_INET;
976 		sin.sin_addr.s_addr = h->bindto;
977 		sin.sin_port = htons(0);
978 		if (bind(h->fd, (const struct sockaddr *)&sin,
979 		    sizeof sin) == -1) {
980 			generr(h, "bind: %s", strerror(errno));
981 			close(h->fd);
982 			h->fd = -1;
983 			return -1;
984 		}
985 	}
986 
987 	if (h->out[POS_CODE] != RAD_ACCESS_REQUEST) {
988 		/* Make sure no password given */
989 		if (h->pass_pos || h->chap_pass) {
990 			generr(h, "User or Chap Password"
991 			    " in accounting request");
992 			return -1;
993 		}
994 	} else {
995 		if (h->eap_msg == 0) {
996 			/* Make sure the user gave us a password */
997 			if (h->pass_pos == 0 && !h->chap_pass) {
998 				generr(h, "No User or Chap Password"
999 				    " attributes given");
1000 				return -1;
1001 			}
1002 			if (h->pass_pos != 0 && h->chap_pass) {
1003 				generr(h, "Both User and Chap Password"
1004 				    " attributes given");
1005 				return -1;
1006 			}
1007 		}
1008 	}
1009 
1010 	/* Fill in the length field in the message */
1011 	h->out[POS_LENGTH] = h->out_len >> 8;
1012 	h->out[POS_LENGTH+1] = h->out_len;
1013 
1014 	h->srv = 0;
1015 	now = time(NULL);
1016 	for (srv = 0;  srv < h->num_servers;  srv++)
1017 		h->servers[srv].num_tries = 0;
1018 	/* Find a first good server. */
1019 	for (srv = 0;  srv < h->num_servers;  srv++) {
1020 		if (h->servers[srv].is_dead == 0)
1021 			break;
1022 		if (h->servers[srv].dead_time &&
1023 		    h->servers[srv].next_probe <= now) {
1024 		    	h->servers[srv].is_dead = 0;
1025 			break;
1026 		}
1027 		h->srv++;
1028 	}
1029 
1030 	/* If all servers was dead on the last probe, try from beginning */
1031 	if (h->srv == h->num_servers) {
1032 		for (srv = 0;  srv < h->num_servers;  srv++) {
1033 		    	h->servers[srv].is_dead = 0;
1034 			h->servers[srv].next_probe = 0;
1035 		}
1036 		h->srv = 0;
1037 	}
1038 
1039 	return rad_continue_send_request(h, 0, fd, tv);
1040 }
1041 
1042 /*
1043  * Create and initialize a rad_handle structure, and return it to the
1044  * caller.  Can fail only if the necessary memory cannot be allocated.
1045  * In that case, it returns NULL.
1046  */
1047 struct rad_handle *
1048 rad_auth_open(void)
1049 {
1050 	struct rad_handle *h;
1051 
1052 	h = (struct rad_handle *)malloc(sizeof(struct rad_handle));
1053 	if (h != NULL) {
1054 		h->fd = -1;
1055 		h->num_servers = 0;
1056 		h->ident = arc4random();
1057 		h->errmsg[0] = '\0';
1058 		memset(h->pass, 0, sizeof h->pass);
1059 		h->pass_len = 0;
1060 		h->pass_pos = 0;
1061 		h->chap_pass = 0;
1062 		h->authentic_pos = 0;
1063 		h->type = RADIUS_AUTH;
1064 		h->out_created = 0;
1065 		h->eap_msg = 0;
1066 		h->bindto = INADDR_ANY;
1067 	}
1068 	return h;
1069 }
1070 
1071 struct rad_handle *
1072 rad_acct_open(void)
1073 {
1074 	struct rad_handle *h;
1075 
1076 	h = rad_open();
1077 	if (h != NULL)
1078 	        h->type = RADIUS_ACCT;
1079 	return h;
1080 }
1081 
1082 struct rad_handle *
1083 rad_server_open(int fd)
1084 {
1085 	struct rad_handle *h;
1086 
1087 	h = rad_open();
1088 	if (h != NULL) {
1089 	        h->type = RADIUS_SERVER;
1090 	        h->fd = fd;
1091 	}
1092 	return h;
1093 }
1094 
1095 struct rad_handle *
1096 rad_open(void)
1097 {
1098     return rad_auth_open();
1099 }
1100 
1101 int
1102 rad_put_addr(struct rad_handle *h, int type, struct in_addr addr)
1103 {
1104 	return rad_put_attr(h, type, &addr.s_addr, sizeof addr.s_addr);
1105 }
1106 
1107 int
1108 rad_put_addr6(struct rad_handle *h, int type, struct in6_addr addr)
1109 {
1110 
1111 	return rad_put_attr(h, type, &addr.s6_addr, sizeof addr.s6_addr);
1112 }
1113 
1114 int
1115 rad_put_attr(struct rad_handle *h, int type, const void *value, size_t len)
1116 {
1117 	int result;
1118 
1119 	if (!h->out_created) {
1120 		generr(h, "Please call rad_create_request()"
1121 		    " before putting attributes");
1122 		return -1;
1123 	}
1124 
1125 	if (h->out[POS_CODE] == RAD_ACCOUNTING_REQUEST) {
1126 		if (type == RAD_EAP_MESSAGE) {
1127 			generr(h, "EAP-Message attribute is not valid"
1128 			    " in accounting requests");
1129 			return -1;
1130 		}
1131 	}
1132 
1133 	/*
1134 	 * When proxying EAP Messages, the Message Authenticator
1135 	 * MUST be present; see RFC 3579.
1136 	 */
1137 	if (type == RAD_EAP_MESSAGE) {
1138 		if (rad_put_message_authentic(h) == -1)
1139 			return -1;
1140 	}
1141 
1142 	if (type == RAD_USER_PASSWORD) {
1143 		result = put_password_attr(h, type, value, len);
1144 	} else if (type == RAD_MESSAGE_AUTHENTIC) {
1145 		result = rad_put_message_authentic(h);
1146 	} else {
1147 		result = put_raw_attr(h, type, value, len);
1148 		if (result == 0) {
1149 			if (type == RAD_CHAP_PASSWORD)
1150 				h->chap_pass = 1;
1151 			else if (type == RAD_EAP_MESSAGE)
1152 				h->eap_msg = 1;
1153 		}
1154 	}
1155 
1156 	return result;
1157 }
1158 
1159 int
1160 rad_put_int(struct rad_handle *h, int type, u_int32_t value)
1161 {
1162 	u_int32_t nvalue;
1163 
1164 	nvalue = htonl(value);
1165 	return rad_put_attr(h, type, &nvalue, sizeof nvalue);
1166 }
1167 
1168 int
1169 rad_put_string(struct rad_handle *h, int type, const char *str)
1170 {
1171 	return rad_put_attr(h, type, str, strlen(str));
1172 }
1173 
1174 int
1175 rad_put_message_authentic(struct rad_handle *h)
1176 {
1177 #ifdef WITH_SSL
1178 	u_char md_zero[MD5_DIGEST_LENGTH];
1179 
1180 	if (h->out[POS_CODE] == RAD_ACCOUNTING_REQUEST) {
1181 		generr(h, "Message-Authenticator is not valid"
1182 		    " in accounting requests");
1183 		return -1;
1184 	}
1185 
1186 	if (h->authentic_pos == 0) {
1187 		h->authentic_pos = h->out_len;
1188 		memset(md_zero, 0, sizeof(md_zero));
1189 		return (put_raw_attr(h, RAD_MESSAGE_AUTHENTIC, md_zero,
1190 		    sizeof(md_zero)));
1191 	}
1192 	return 0;
1193 #else
1194 	generr(h, "Message Authenticator not supported,"
1195 	    " please recompile libradius with SSL support");
1196 	return -1;
1197 #endif
1198 }
1199 
1200 /*
1201  * Returns the response type code on success, or -1 on failure.
1202  */
1203 int
1204 rad_send_request(struct rad_handle *h)
1205 {
1206 	struct timeval timelimit;
1207 	struct timeval tv;
1208 	int fd;
1209 	int n;
1210 
1211 	n = rad_init_send_request(h, &fd, &tv);
1212 
1213 	if (n != 0)
1214 		return n;
1215 
1216 	gettimeofday(&timelimit, NULL);
1217 	timeradd(&tv, &timelimit, &timelimit);
1218 
1219 	for ( ; ; ) {
1220 		fd_set readfds;
1221 
1222 		FD_ZERO(&readfds);
1223 		FD_SET(fd, &readfds);
1224 
1225 		n = select(fd + 1, &readfds, NULL, NULL, &tv);
1226 
1227 		if (n == -1) {
1228 			generr(h, "select: %s", strerror(errno));
1229 			return -1;
1230 		}
1231 
1232 		if (!FD_ISSET(fd, &readfds)) {
1233 			/* Compute a new timeout */
1234 			gettimeofday(&tv, NULL);
1235 			timersub(&timelimit, &tv, &tv);
1236 			if (tv.tv_sec > 0 || (tv.tv_sec == 0 && tv.tv_usec > 0))
1237 				/* Continue the select */
1238 				continue;
1239 		}
1240 
1241 		n = rad_continue_send_request(h, n, &fd, &tv);
1242 
1243 		if (n != 0)
1244 			return n;
1245 
1246 		gettimeofday(&timelimit, NULL);
1247 		timeradd(&tv, &timelimit, &timelimit);
1248 	}
1249 }
1250 
1251 const char *
1252 rad_strerror(struct rad_handle *h)
1253 {
1254 	return h->errmsg;
1255 }
1256 
1257 /*
1258  * Destructively split a string into fields separated by white space.
1259  * `#' at the beginning of a field begins a comment that extends to the
1260  * end of the string.  Fields may be quoted with `"'.  Inside quoted
1261  * strings, the backslash escapes `\"' and `\\' are honored.
1262  *
1263  * Pointers to up to the first maxfields fields are stored in the fields
1264  * array.  Missing fields get NULL pointers.
1265  *
1266  * The return value is the actual number of fields parsed, and is always
1267  * <= maxfields.
1268  *
1269  * On a syntax error, places a message in the msg string, and returns -1.
1270  */
1271 static int
1272 split(char *str, char *fields[], int maxfields, char *msg, size_t msglen)
1273 {
1274 	char *p;
1275 	int i;
1276 	static const char ws[] = " \t";
1277 
1278 	for (i = 0;  i < maxfields;  i++)
1279 		fields[i] = NULL;
1280 	p = str;
1281 	i = 0;
1282 	while (*p != '\0') {
1283 		p += strspn(p, ws);
1284 		if (*p == '#' || *p == '\0')
1285 			break;
1286 		if (i >= maxfields) {
1287 			snprintf(msg, msglen, "line has too many fields");
1288 			return -1;
1289 		}
1290 		if (*p == '"') {
1291 			char *dst;
1292 
1293 			dst = ++p;
1294 			fields[i] = dst;
1295 			while (*p != '"') {
1296 				if (*p == '\\') {
1297 					p++;
1298 					if (*p != '"' && *p != '\\' &&
1299 					    *p != '\0') {
1300 						snprintf(msg, msglen,
1301 						    "invalid `\\' escape");
1302 						return -1;
1303 					}
1304 				}
1305 				if (*p == '\0') {
1306 					snprintf(msg, msglen,
1307 					    "unterminated quoted string");
1308 					return -1;
1309 				}
1310 				*dst++ = *p++;
1311 			}
1312 			*dst = '\0';
1313 			p++;
1314 			if (*fields[i] == '\0') {
1315 				snprintf(msg, msglen,
1316 				    "empty quoted string not permitted");
1317 				return -1;
1318 			}
1319 			if (*p != '\0' && strspn(p, ws) == 0) {
1320 				snprintf(msg, msglen, "quoted string not"
1321 				    " followed by white space");
1322 				return -1;
1323 			}
1324 		} else {
1325 			fields[i] = p;
1326 			p += strcspn(p, ws);
1327 			if (*p != '\0')
1328 				*p++ = '\0';
1329 		}
1330 		i++;
1331 	}
1332 	return i;
1333 }
1334 
1335 int
1336 rad_get_vendor_attr(u_int32_t *vendor, const void **data, size_t *len)
1337 {
1338 	struct vendor_attribute *attr;
1339 
1340 	attr = (struct vendor_attribute *)*data;
1341 	*vendor = ntohl(attr->vendor_value);
1342 	*data = attr->attrib_data;
1343 	*len = attr->attrib_len - 2;
1344 
1345 	return (attr->attrib_type);
1346 }
1347 
1348 int
1349 rad_put_vendor_addr(struct rad_handle *h, int vendor, int type,
1350     struct in_addr addr)
1351 {
1352 	return (rad_put_vendor_attr(h, vendor, type, &addr.s_addr,
1353 	    sizeof addr.s_addr));
1354 }
1355 
1356 int
1357 rad_put_vendor_addr6(struct rad_handle *h, int vendor, int type,
1358     struct in6_addr addr)
1359 {
1360 
1361 	return (rad_put_vendor_attr(h, vendor, type, &addr.s6_addr,
1362 	    sizeof addr.s6_addr));
1363 }
1364 
1365 int
1366 rad_put_vendor_attr(struct rad_handle *h, int vendor, int type,
1367     const void *value, size_t len)
1368 {
1369 	struct vendor_attribute *attr;
1370 	int res;
1371 
1372 	if (!h->out_created) {
1373 		generr(h, "Please call rad_create_request()"
1374 		    " before putting attributes");
1375 		return -1;
1376 	}
1377 
1378 	if ((attr = malloc(len + 6)) == NULL) {
1379 		generr(h, "malloc failure (%zu bytes)", len + 6);
1380 		return -1;
1381 	}
1382 
1383 	attr->vendor_value = htonl(vendor);
1384 	attr->attrib_type = type;
1385 	attr->attrib_len = len + 2;
1386 	memcpy(attr->attrib_data, value, len);
1387 
1388 	res = put_raw_attr(h, RAD_VENDOR_SPECIFIC, attr, len + 6);
1389 	free(attr);
1390 	if (res == 0 && vendor == RAD_VENDOR_MICROSOFT
1391 	    && (type == RAD_MICROSOFT_MS_CHAP_RESPONSE
1392 	    || type == RAD_MICROSOFT_MS_CHAP2_RESPONSE)) {
1393 		h->chap_pass = 1;
1394 	}
1395 	return (res);
1396 }
1397 
1398 int
1399 rad_put_vendor_int(struct rad_handle *h, int vendor, int type, u_int32_t i)
1400 {
1401 	u_int32_t value;
1402 
1403 	value = htonl(i);
1404 	return (rad_put_vendor_attr(h, vendor, type, &value, sizeof value));
1405 }
1406 
1407 int
1408 rad_put_vendor_string(struct rad_handle *h, int vendor, int type,
1409     const char *str)
1410 {
1411 	return (rad_put_vendor_attr(h, vendor, type, str, strlen(str)));
1412 }
1413 
1414 ssize_t
1415 rad_request_authenticator(struct rad_handle *h, char *buf, size_t len)
1416 {
1417 	if (len < LEN_AUTH)
1418 		return (-1);
1419 	memcpy(buf, h->out + POS_AUTH, LEN_AUTH);
1420 	if (len > LEN_AUTH)
1421 		buf[LEN_AUTH] = '\0';
1422 	return (LEN_AUTH);
1423 }
1424 
1425 u_char *
1426 rad_demangle(struct rad_handle *h, const void *mangled, size_t mlen)
1427 {
1428 	char R[LEN_AUTH];
1429 	const char *S;
1430 	int i, Ppos;
1431 	MD5_CTX Context;
1432 	u_char b[MD5_DIGEST_LENGTH], *C, *demangled;
1433 
1434 	if ((mlen % 16 != 0) || mlen > 128) {
1435 		generr(h, "Cannot interpret mangled data of length %lu",
1436 		    (u_long)mlen);
1437 		return NULL;
1438 	}
1439 
1440 	C = (u_char *)mangled;
1441 
1442 	/* We need the shared secret as Salt */
1443 	S = rad_server_secret(h);
1444 
1445 	/* We need the request authenticator */
1446 	if (rad_request_authenticator(h, R, sizeof R) != LEN_AUTH) {
1447 		generr(h, "Cannot obtain the RADIUS request authenticator");
1448 		return NULL;
1449 	}
1450 
1451 	demangled = malloc(mlen);
1452 	if (!demangled)
1453 		return NULL;
1454 
1455 	MD5Init(&Context);
1456 	MD5Update(&Context, S, strlen(S));
1457 	MD5Update(&Context, R, LEN_AUTH);
1458 	MD5Final(b, &Context);
1459 	Ppos = 0;
1460 	while (mlen) {
1461 
1462 		mlen -= 16;
1463 		for (i = 0; i < 16; i++)
1464 			demangled[Ppos++] = C[i] ^ b[i];
1465 
1466 		if (mlen) {
1467 			MD5Init(&Context);
1468 			MD5Update(&Context, S, strlen(S));
1469 			MD5Update(&Context, C, 16);
1470 			MD5Final(b, &Context);
1471 		}
1472 
1473 		C += 16;
1474 	}
1475 
1476 	return demangled;
1477 }
1478 
1479 u_char *
1480 rad_demangle_mppe_key(struct rad_handle *h, const void *mangled,
1481     size_t mlen, size_t *len)
1482 {
1483 	char R[LEN_AUTH];    /* variable names as per rfc2548 */
1484 	const char *S;
1485 	u_char b[MD5_DIGEST_LENGTH], *demangled;
1486 	const u_char *A, *C;
1487 	MD5_CTX Context;
1488 	int Slen, i, Clen, Ppos;
1489 	u_char *P;
1490 
1491 	if (mlen % 16 != SALT_LEN) {
1492 		generr(h, "Cannot interpret mangled data of length %lu",
1493 		    (u_long)mlen);
1494 		return NULL;
1495 	}
1496 
1497 	/* We need the RADIUS Request-Authenticator */
1498 	if (rad_request_authenticator(h, R, sizeof R) != LEN_AUTH) {
1499 		generr(h, "Cannot obtain the RADIUS request authenticator");
1500 		return NULL;
1501 	}
1502 
1503 	A = (const u_char *)mangled;      /* Salt comes first */
1504 	C = (const u_char *)mangled + SALT_LEN;  /* Then the ciphertext */
1505 	Clen = mlen - SALT_LEN;
1506 	S = rad_server_secret(h);    /* We need the RADIUS secret */
1507 	Slen = strlen(S);
1508 	P = alloca(Clen);        /* We derive our plaintext */
1509 
1510 	MD5Init(&Context);
1511 	MD5Update(&Context, S, Slen);
1512 	MD5Update(&Context, R, LEN_AUTH);
1513 	MD5Update(&Context, A, SALT_LEN);
1514 	MD5Final(b, &Context);
1515 	Ppos = 0;
1516 
1517 	while (Clen) {
1518 		Clen -= 16;
1519 
1520 		for (i = 0; i < 16; i++)
1521 		    P[Ppos++] = C[i] ^ b[i];
1522 
1523 		if (Clen) {
1524 			MD5Init(&Context);
1525 			MD5Update(&Context, S, Slen);
1526 			MD5Update(&Context, C, 16);
1527 			MD5Final(b, &Context);
1528 		}
1529 
1530 		C += 16;
1531 	}
1532 
1533 	/*
1534 	* The resulting plain text consists of a one-byte length, the text and
1535 	* maybe some padding.
1536 	*/
1537 	*len = *P;
1538 	if (*len > mlen - 1) {
1539 		generr(h, "Mangled data seems to be garbage %zu %zu",
1540 		    *len, mlen-1);
1541 		return NULL;
1542 	}
1543 
1544 	if (*len > MPPE_KEY_LEN * 2) {
1545 		generr(h, "Key to long (%zu) for me max. %d",
1546 		    *len, MPPE_KEY_LEN * 2);
1547 		return NULL;
1548 	}
1549 	demangled = malloc(*len);
1550 	if (!demangled)
1551 		return NULL;
1552 
1553 	memcpy(demangled, P + 1, *len);
1554 	return demangled;
1555 }
1556 
1557 const char *
1558 rad_server_secret(struct rad_handle *h)
1559 {
1560 	return (h->servers[h->srv].secret);
1561 }
1562