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