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