xref: /freebsd/lib/libradius/radlib.c (revision 6829dae12bb055451fa467da4589c43bd03b1e64)
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 		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 			long r;
856 			r = random();
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 		srandomdev();
1055 		h->fd = -1;
1056 		h->num_servers = 0;
1057 		h->ident = random();
1058 		h->errmsg[0] = '\0';
1059 		memset(h->pass, 0, sizeof h->pass);
1060 		h->pass_len = 0;
1061 		h->pass_pos = 0;
1062 		h->chap_pass = 0;
1063 		h->authentic_pos = 0;
1064 		h->type = RADIUS_AUTH;
1065 		h->out_created = 0;
1066 		h->eap_msg = 0;
1067 		h->bindto = INADDR_ANY;
1068 	}
1069 	return h;
1070 }
1071 
1072 struct rad_handle *
1073 rad_acct_open(void)
1074 {
1075 	struct rad_handle *h;
1076 
1077 	h = rad_open();
1078 	if (h != NULL)
1079 	        h->type = RADIUS_ACCT;
1080 	return h;
1081 }
1082 
1083 struct rad_handle *
1084 rad_server_open(int fd)
1085 {
1086 	struct rad_handle *h;
1087 
1088 	h = rad_open();
1089 	if (h != NULL) {
1090 	        h->type = RADIUS_SERVER;
1091 	        h->fd = fd;
1092 	}
1093 	return h;
1094 }
1095 
1096 struct rad_handle *
1097 rad_open(void)
1098 {
1099     return rad_auth_open();
1100 }
1101 
1102 int
1103 rad_put_addr(struct rad_handle *h, int type, struct in_addr addr)
1104 {
1105 	return rad_put_attr(h, type, &addr.s_addr, sizeof addr.s_addr);
1106 }
1107 
1108 int
1109 rad_put_addr6(struct rad_handle *h, int type, struct in6_addr addr)
1110 {
1111 
1112 	return rad_put_attr(h, type, &addr.s6_addr, sizeof addr.s6_addr);
1113 }
1114 
1115 int
1116 rad_put_attr(struct rad_handle *h, int type, const void *value, size_t len)
1117 {
1118 	int result;
1119 
1120 	if (!h->out_created) {
1121 		generr(h, "Please call rad_create_request()"
1122 		    " before putting attributes");
1123 		return -1;
1124 	}
1125 
1126 	if (h->out[POS_CODE] == RAD_ACCOUNTING_REQUEST) {
1127 		if (type == RAD_EAP_MESSAGE) {
1128 			generr(h, "EAP-Message attribute is not valid"
1129 			    " in accounting requests");
1130 			return -1;
1131 		}
1132 	}
1133 
1134 	/*
1135 	 * When proxying EAP Messages, the Message Authenticator
1136 	 * MUST be present; see RFC 3579.
1137 	 */
1138 	if (type == RAD_EAP_MESSAGE) {
1139 		if (rad_put_message_authentic(h) == -1)
1140 			return -1;
1141 	}
1142 
1143 	if (type == RAD_USER_PASSWORD) {
1144 		result = put_password_attr(h, type, value, len);
1145 	} else if (type == RAD_MESSAGE_AUTHENTIC) {
1146 		result = rad_put_message_authentic(h);
1147 	} else {
1148 		result = put_raw_attr(h, type, value, len);
1149 		if (result == 0) {
1150 			if (type == RAD_CHAP_PASSWORD)
1151 				h->chap_pass = 1;
1152 			else if (type == RAD_EAP_MESSAGE)
1153 				h->eap_msg = 1;
1154 		}
1155 	}
1156 
1157 	return result;
1158 }
1159 
1160 int
1161 rad_put_int(struct rad_handle *h, int type, u_int32_t value)
1162 {
1163 	u_int32_t nvalue;
1164 
1165 	nvalue = htonl(value);
1166 	return rad_put_attr(h, type, &nvalue, sizeof nvalue);
1167 }
1168 
1169 int
1170 rad_put_string(struct rad_handle *h, int type, const char *str)
1171 {
1172 	return rad_put_attr(h, type, str, strlen(str));
1173 }
1174 
1175 int
1176 rad_put_message_authentic(struct rad_handle *h)
1177 {
1178 #ifdef WITH_SSL
1179 	u_char md_zero[MD5_DIGEST_LENGTH];
1180 
1181 	if (h->out[POS_CODE] == RAD_ACCOUNTING_REQUEST) {
1182 		generr(h, "Message-Authenticator is not valid"
1183 		    " in accounting requests");
1184 		return -1;
1185 	}
1186 
1187 	if (h->authentic_pos == 0) {
1188 		h->authentic_pos = h->out_len;
1189 		memset(md_zero, 0, sizeof(md_zero));
1190 		return (put_raw_attr(h, RAD_MESSAGE_AUTHENTIC, md_zero,
1191 		    sizeof(md_zero)));
1192 	}
1193 	return 0;
1194 #else
1195 	generr(h, "Message Authenticator not supported,"
1196 	    " please recompile libradius with SSL support");
1197 	return -1;
1198 #endif
1199 }
1200 
1201 /*
1202  * Returns the response type code on success, or -1 on failure.
1203  */
1204 int
1205 rad_send_request(struct rad_handle *h)
1206 {
1207 	struct timeval timelimit;
1208 	struct timeval tv;
1209 	int fd;
1210 	int n;
1211 
1212 	n = rad_init_send_request(h, &fd, &tv);
1213 
1214 	if (n != 0)
1215 		return n;
1216 
1217 	gettimeofday(&timelimit, NULL);
1218 	timeradd(&tv, &timelimit, &timelimit);
1219 
1220 	for ( ; ; ) {
1221 		fd_set readfds;
1222 
1223 		FD_ZERO(&readfds);
1224 		FD_SET(fd, &readfds);
1225 
1226 		n = select(fd + 1, &readfds, NULL, NULL, &tv);
1227 
1228 		if (n == -1) {
1229 			generr(h, "select: %s", strerror(errno));
1230 			return -1;
1231 		}
1232 
1233 		if (!FD_ISSET(fd, &readfds)) {
1234 			/* Compute a new timeout */
1235 			gettimeofday(&tv, NULL);
1236 			timersub(&timelimit, &tv, &tv);
1237 			if (tv.tv_sec > 0 || (tv.tv_sec == 0 && tv.tv_usec > 0))
1238 				/* Continue the select */
1239 				continue;
1240 		}
1241 
1242 		n = rad_continue_send_request(h, n, &fd, &tv);
1243 
1244 		if (n != 0)
1245 			return n;
1246 
1247 		gettimeofday(&timelimit, NULL);
1248 		timeradd(&tv, &timelimit, &timelimit);
1249 	}
1250 }
1251 
1252 const char *
1253 rad_strerror(struct rad_handle *h)
1254 {
1255 	return h->errmsg;
1256 }
1257 
1258 /*
1259  * Destructively split a string into fields separated by white space.
1260  * `#' at the beginning of a field begins a comment that extends to the
1261  * end of the string.  Fields may be quoted with `"'.  Inside quoted
1262  * strings, the backslash escapes `\"' and `\\' are honored.
1263  *
1264  * Pointers to up to the first maxfields fields are stored in the fields
1265  * array.  Missing fields get NULL pointers.
1266  *
1267  * The return value is the actual number of fields parsed, and is always
1268  * <= maxfields.
1269  *
1270  * On a syntax error, places a message in the msg string, and returns -1.
1271  */
1272 static int
1273 split(char *str, char *fields[], int maxfields, char *msg, size_t msglen)
1274 {
1275 	char *p;
1276 	int i;
1277 	static const char ws[] = " \t";
1278 
1279 	for (i = 0;  i < maxfields;  i++)
1280 		fields[i] = NULL;
1281 	p = str;
1282 	i = 0;
1283 	while (*p != '\0') {
1284 		p += strspn(p, ws);
1285 		if (*p == '#' || *p == '\0')
1286 			break;
1287 		if (i >= maxfields) {
1288 			snprintf(msg, msglen, "line has too many fields");
1289 			return -1;
1290 		}
1291 		if (*p == '"') {
1292 			char *dst;
1293 
1294 			dst = ++p;
1295 			fields[i] = dst;
1296 			while (*p != '"') {
1297 				if (*p == '\\') {
1298 					p++;
1299 					if (*p != '"' && *p != '\\' &&
1300 					    *p != '\0') {
1301 						snprintf(msg, msglen,
1302 						    "invalid `\\' escape");
1303 						return -1;
1304 					}
1305 				}
1306 				if (*p == '\0') {
1307 					snprintf(msg, msglen,
1308 					    "unterminated quoted string");
1309 					return -1;
1310 				}
1311 				*dst++ = *p++;
1312 			}
1313 			*dst = '\0';
1314 			p++;
1315 			if (*fields[i] == '\0') {
1316 				snprintf(msg, msglen,
1317 				    "empty quoted string not permitted");
1318 				return -1;
1319 			}
1320 			if (*p != '\0' && strspn(p, ws) == 0) {
1321 				snprintf(msg, msglen, "quoted string not"
1322 				    " followed by white space");
1323 				return -1;
1324 			}
1325 		} else {
1326 			fields[i] = p;
1327 			p += strcspn(p, ws);
1328 			if (*p != '\0')
1329 				*p++ = '\0';
1330 		}
1331 		i++;
1332 	}
1333 	return i;
1334 }
1335 
1336 int
1337 rad_get_vendor_attr(u_int32_t *vendor, const void **data, size_t *len)
1338 {
1339 	struct vendor_attribute *attr;
1340 
1341 	attr = (struct vendor_attribute *)*data;
1342 	*vendor = ntohl(attr->vendor_value);
1343 	*data = attr->attrib_data;
1344 	*len = attr->attrib_len - 2;
1345 
1346 	return (attr->attrib_type);
1347 }
1348 
1349 int
1350 rad_put_vendor_addr(struct rad_handle *h, int vendor, int type,
1351     struct in_addr addr)
1352 {
1353 	return (rad_put_vendor_attr(h, vendor, type, &addr.s_addr,
1354 	    sizeof addr.s_addr));
1355 }
1356 
1357 int
1358 rad_put_vendor_addr6(struct rad_handle *h, int vendor, int type,
1359     struct in6_addr addr)
1360 {
1361 
1362 	return (rad_put_vendor_attr(h, vendor, type, &addr.s6_addr,
1363 	    sizeof addr.s6_addr));
1364 }
1365 
1366 int
1367 rad_put_vendor_attr(struct rad_handle *h, int vendor, int type,
1368     const void *value, size_t len)
1369 {
1370 	struct vendor_attribute *attr;
1371 	int res;
1372 
1373 	if (!h->out_created) {
1374 		generr(h, "Please call rad_create_request()"
1375 		    " before putting attributes");
1376 		return -1;
1377 	}
1378 
1379 	if ((attr = malloc(len + 6)) == NULL) {
1380 		generr(h, "malloc failure (%zu bytes)", len + 6);
1381 		return -1;
1382 	}
1383 
1384 	attr->vendor_value = htonl(vendor);
1385 	attr->attrib_type = type;
1386 	attr->attrib_len = len + 2;
1387 	memcpy(attr->attrib_data, value, len);
1388 
1389 	res = put_raw_attr(h, RAD_VENDOR_SPECIFIC, attr, len + 6);
1390 	free(attr);
1391 	if (res == 0 && vendor == RAD_VENDOR_MICROSOFT
1392 	    && (type == RAD_MICROSOFT_MS_CHAP_RESPONSE
1393 	    || type == RAD_MICROSOFT_MS_CHAP2_RESPONSE)) {
1394 		h->chap_pass = 1;
1395 	}
1396 	return (res);
1397 }
1398 
1399 int
1400 rad_put_vendor_int(struct rad_handle *h, int vendor, int type, u_int32_t i)
1401 {
1402 	u_int32_t value;
1403 
1404 	value = htonl(i);
1405 	return (rad_put_vendor_attr(h, vendor, type, &value, sizeof value));
1406 }
1407 
1408 int
1409 rad_put_vendor_string(struct rad_handle *h, int vendor, int type,
1410     const char *str)
1411 {
1412 	return (rad_put_vendor_attr(h, vendor, type, str, strlen(str)));
1413 }
1414 
1415 ssize_t
1416 rad_request_authenticator(struct rad_handle *h, char *buf, size_t len)
1417 {
1418 	if (len < LEN_AUTH)
1419 		return (-1);
1420 	memcpy(buf, h->out + POS_AUTH, LEN_AUTH);
1421 	if (len > LEN_AUTH)
1422 		buf[LEN_AUTH] = '\0';
1423 	return (LEN_AUTH);
1424 }
1425 
1426 u_char *
1427 rad_demangle(struct rad_handle *h, const void *mangled, size_t mlen)
1428 {
1429 	char R[LEN_AUTH];
1430 	const char *S;
1431 	int i, Ppos;
1432 	MD5_CTX Context;
1433 	u_char b[MD5_DIGEST_LENGTH], *C, *demangled;
1434 
1435 	if ((mlen % 16 != 0) || mlen > 128) {
1436 		generr(h, "Cannot interpret mangled data of length %lu",
1437 		    (u_long)mlen);
1438 		return NULL;
1439 	}
1440 
1441 	C = (u_char *)mangled;
1442 
1443 	/* We need the shared secret as Salt */
1444 	S = rad_server_secret(h);
1445 
1446 	/* We need the request authenticator */
1447 	if (rad_request_authenticator(h, R, sizeof R) != LEN_AUTH) {
1448 		generr(h, "Cannot obtain the RADIUS request authenticator");
1449 		return NULL;
1450 	}
1451 
1452 	demangled = malloc(mlen);
1453 	if (!demangled)
1454 		return NULL;
1455 
1456 	MD5Init(&Context);
1457 	MD5Update(&Context, S, strlen(S));
1458 	MD5Update(&Context, R, LEN_AUTH);
1459 	MD5Final(b, &Context);
1460 	Ppos = 0;
1461 	while (mlen) {
1462 
1463 		mlen -= 16;
1464 		for (i = 0; i < 16; i++)
1465 			demangled[Ppos++] = C[i] ^ b[i];
1466 
1467 		if (mlen) {
1468 			MD5Init(&Context);
1469 			MD5Update(&Context, S, strlen(S));
1470 			MD5Update(&Context, C, 16);
1471 			MD5Final(b, &Context);
1472 		}
1473 
1474 		C += 16;
1475 	}
1476 
1477 	return demangled;
1478 }
1479 
1480 u_char *
1481 rad_demangle_mppe_key(struct rad_handle *h, const void *mangled,
1482     size_t mlen, size_t *len)
1483 {
1484 	char R[LEN_AUTH];    /* variable names as per rfc2548 */
1485 	const char *S;
1486 	u_char b[MD5_DIGEST_LENGTH], *demangled;
1487 	const u_char *A, *C;
1488 	MD5_CTX Context;
1489 	int Slen, i, Clen, Ppos;
1490 	u_char *P;
1491 
1492 	if (mlen % 16 != SALT_LEN) {
1493 		generr(h, "Cannot interpret mangled data of length %lu",
1494 		    (u_long)mlen);
1495 		return NULL;
1496 	}
1497 
1498 	/* We need the RADIUS Request-Authenticator */
1499 	if (rad_request_authenticator(h, R, sizeof R) != LEN_AUTH) {
1500 		generr(h, "Cannot obtain the RADIUS request authenticator");
1501 		return NULL;
1502 	}
1503 
1504 	A = (const u_char *)mangled;      /* Salt comes first */
1505 	C = (const u_char *)mangled + SALT_LEN;  /* Then the ciphertext */
1506 	Clen = mlen - SALT_LEN;
1507 	S = rad_server_secret(h);    /* We need the RADIUS secret */
1508 	Slen = strlen(S);
1509 	P = alloca(Clen);        /* We derive our plaintext */
1510 
1511 	MD5Init(&Context);
1512 	MD5Update(&Context, S, Slen);
1513 	MD5Update(&Context, R, LEN_AUTH);
1514 	MD5Update(&Context, A, SALT_LEN);
1515 	MD5Final(b, &Context);
1516 	Ppos = 0;
1517 
1518 	while (Clen) {
1519 		Clen -= 16;
1520 
1521 		for (i = 0; i < 16; i++)
1522 		    P[Ppos++] = C[i] ^ b[i];
1523 
1524 		if (Clen) {
1525 			MD5Init(&Context);
1526 			MD5Update(&Context, S, Slen);
1527 			MD5Update(&Context, C, 16);
1528 			MD5Final(b, &Context);
1529 		}
1530 
1531 		C += 16;
1532 	}
1533 
1534 	/*
1535 	* The resulting plain text consists of a one-byte length, the text and
1536 	* maybe some padding.
1537 	*/
1538 	*len = *P;
1539 	if (*len > mlen - 1) {
1540 		generr(h, "Mangled data seems to be garbage %zu %zu",
1541 		    *len, mlen-1);
1542 		return NULL;
1543 	}
1544 
1545 	if (*len > MPPE_KEY_LEN * 2) {
1546 		generr(h, "Key to long (%zu) for me max. %d",
1547 		    *len, MPPE_KEY_LEN * 2);
1548 		return NULL;
1549 	}
1550 	demangled = malloc(*len);
1551 	if (!demangled)
1552 		return NULL;
1553 
1554 	memcpy(demangled, P + 1, *len);
1555 	return demangled;
1556 }
1557 
1558 const char *
1559 rad_server_secret(struct rad_handle *h)
1560 {
1561 	return (h->servers[h->srv].secret);
1562 }
1563