1 /*-
2  * Copyright 1998 Juniper Networks, Inc.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  *	$OpenBSD: radlib.c,v 1.8 2003/04/04 20:25:06 deraadt Exp $
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 
35 #include <errno.h>
36 #include <md5.h>
37 #include <netdb.h>
38 #include <stdarg.h>
39 #include <stddef.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <termios.h>
44 #include <unistd.h>
45 
46 #include "defs.h"
47 #include "radlib_private.h"
48 
49 __RCSID("$MirOS: src/usr.sbin/ppp/ppp/radlib.c,v 1.2 2014/03/13 00:52:16 tg Exp $");
50 
51 static void	 clear_password(struct rad_handle *);
52 static void	 generr(struct rad_handle *, const char *, ...);
53 static void	 insert_scrambled_password(struct rad_handle *, int);
54 static void	 insert_request_authenticator(struct rad_handle *, int);
55 static int	 is_valid_response(struct rad_handle *, int,
56 		    const struct sockaddr_in *);
57 static int	 put_password_attr(struct rad_handle *, int,
58 		    const void *, size_t);
59 static int	 put_raw_attr(struct rad_handle *, int,
60 		    const void *, size_t);
61 static int	 split(char *, char *[], int, char *, size_t);
62 
63 static void
clear_password(struct rad_handle * h)64 clear_password(struct rad_handle *h)
65 {
66 	if (h->pass_len != 0) {
67 		memset(h->pass, 0, h->pass_len);
68 		h->pass_len = 0;
69 	}
70 	h->pass_pos = 0;
71 }
72 
73 static void
generr(struct rad_handle * h,const char * format,...)74 generr(struct rad_handle *h, const char *format, ...)
75 {
76 	va_list		 ap;
77 
78 	va_start(ap, format);
79 	vsnprintf(h->errmsg, ERRSIZE, format, ap);
80 	va_end(ap);
81 }
82 
83 static void
insert_scrambled_password(struct rad_handle * h,int srv)84 insert_scrambled_password(struct rad_handle *h, int srv)
85 {
86 	MD5_CTX ctx;
87 	unsigned char md5[16];
88 	const struct rad_server *srvp;
89 	int padded_len;
90 	int pos;
91 
92 	srvp = &h->servers[srv];
93 	padded_len = h->pass_len == 0 ? 16 : (h->pass_len+15) & ~0xf;
94 
95 	memcpy(md5, &h->request[POS_AUTH], LEN_AUTH);
96 	for (pos = 0;  pos < padded_len;  pos += 16) {
97 		int i;
98 
99 		/* Calculate the new scrambler */
100 		MD5Init(&ctx);
101 		MD5Update(&ctx, srvp->secret, strlen(srvp->secret));
102 		MD5Update(&ctx, md5, 16);
103 		MD5Final(md5, &ctx);
104 
105 		/*
106 		 * Mix in the current chunk of the password, and copy
107 		 * the result into the right place in the request.  Also
108 		 * modify the scrambler in place, since we will use this
109 		 * in calculating the scrambler for next time.
110 		 */
111 		for (i = 0;  i < 16;  i++)
112 			h->request[h->pass_pos + pos + i] =
113 			    md5[i] ^= h->pass[pos + i];
114 	}
115 }
116 
117 static void
insert_request_authenticator(struct rad_handle * h,int srv)118 insert_request_authenticator(struct rad_handle *h, int srv)
119 {
120 	MD5_CTX ctx;
121 	const struct rad_server *srvp;
122 
123 	srvp = &h->servers[srv];
124 
125 	/* Create the request authenticator */
126 	MD5Init(&ctx);
127 	MD5Update(&ctx, &h->request[POS_CODE], POS_AUTH - POS_CODE);
128 	MD5Update(&ctx, memset(&h->request[POS_AUTH], 0, LEN_AUTH), LEN_AUTH);
129 	MD5Update(&ctx, &h->request[POS_ATTRS], h->req_len - POS_ATTRS);
130 	MD5Update(&ctx, srvp->secret, strlen(srvp->secret));
131 	MD5Final(&h->request[POS_AUTH], &ctx);
132 }
133 
134 /*
135  * Return true if the current response is valid for a request to the
136  * specified server.
137  */
138 static int
is_valid_response(struct rad_handle * h,int srv,const struct sockaddr_in * from)139 is_valid_response(struct rad_handle *h, int srv,
140     const struct sockaddr_in *from)
141 {
142 	MD5_CTX ctx;
143 	unsigned char md5[16];
144 	const struct rad_server *srvp;
145 	int len;
146 
147 	srvp = &h->servers[srv];
148 
149 	/* Check the source address */
150 	if (from->sin_family != srvp->addr.sin_family ||
151 	    from->sin_addr.s_addr != srvp->addr.sin_addr.s_addr ||
152 	    from->sin_port != srvp->addr.sin_port)
153 		return 0;
154 
155 	/* Check the message length */
156 	if (h->resp_len < POS_ATTRS)
157 		return 0;
158 	len = h->response[POS_LENGTH] << 8 | h->response[POS_LENGTH+1];
159 	if (len > h->resp_len)
160 		return 0;
161 
162 	/* Check the response authenticator */
163 	MD5Init(&ctx);
164 	MD5Update(&ctx, &h->response[POS_CODE], POS_AUTH - POS_CODE);
165 	MD5Update(&ctx, &h->request[POS_AUTH], LEN_AUTH);
166 	MD5Update(&ctx, &h->response[POS_ATTRS], len - POS_ATTRS);
167 	MD5Update(&ctx, srvp->secret, strlen(srvp->secret));
168 	MD5Final(md5, &ctx);
169 	if (memcmp(&h->response[POS_AUTH], md5, sizeof md5) != 0)
170 		return 0;
171 
172 	return 1;
173 }
174 
175 static int
put_password_attr(struct rad_handle * h,int type,const void * value,size_t len)176 put_password_attr(struct rad_handle *h, int type, const void *value, size_t len)
177 {
178 	int padded_len;
179 	int pad_len;
180 
181 	if (h->pass_pos != 0) {
182 		generr(h, "Multiple User-Password attributes specified");
183 		return -1;
184 	}
185 	if (len > PASSSIZE)
186 		len = PASSSIZE;
187 	padded_len = len == 0 ? 16 : (len+15) & ~0xf;
188 	pad_len = padded_len - len;
189 
190 	/*
191 	 * Put in a place-holder attribute containing all zeros, and
192 	 * remember where it is so we can fill it in later.
193 	 */
194 	clear_password(h);
195 	put_raw_attr(h, type, h->pass, padded_len);
196 	h->pass_pos = h->req_len - padded_len;
197 
198 	/* Save the cleartext password, padded as necessary */
199 	memcpy(h->pass, value, len);
200 	h->pass_len = len;
201 	memset(h->pass + len, 0, pad_len);
202 	return 0;
203 }
204 
205 static int
put_raw_attr(struct rad_handle * h,int type,const void * value,size_t len)206 put_raw_attr(struct rad_handle *h, int type, const void *value, size_t len)
207 {
208 	if (len > 253) {
209 		generr(h, "Attribute too long");
210 		return -1;
211 	}
212 	if (h->req_len + 2 + len > MSGSIZE) {
213 		generr(h, "Maximum message length exceeded");
214 		return -1;
215 	}
216 	h->request[h->req_len++] = type;
217 	h->request[h->req_len++] = len + 2;
218 	memcpy(&h->request[h->req_len], value, len);
219 	h->req_len += len;
220 	return 0;
221 }
222 
223 int
rad_add_server(struct rad_handle * h,const char * host,int port,const char * secret,int timeout,int tries)224 rad_add_server(struct rad_handle *h, const char *host, int port,
225     const char *secret, int timeout, int tries)
226 {
227 	struct rad_server *srvp;
228 
229 	if (h->num_servers >= MAXSERVERS) {
230 		generr(h, "Too many RADIUS servers specified");
231 		return -1;
232 	}
233 	srvp = &h->servers[h->num_servers];
234 
235 	memset(&srvp->addr, 0, sizeof srvp->addr);
236 	srvp->addr.sin_len = sizeof srvp->addr;
237 	srvp->addr.sin_family = AF_INET;
238 	if (!inet_aton(host, &srvp->addr.sin_addr)) {
239 		struct hostent *hent;
240 
241 		if ((hent = gethostbyname(host)) == NULL) {
242 			generr(h, "%s: host not found", host);
243 			return -1;
244 		}
245 		memcpy(&srvp->addr.sin_addr, hent->h_addr,
246 		    sizeof srvp->addr.sin_addr);
247 	}
248 	if (port != 0)
249 		srvp->addr.sin_port = htons(port);
250 	else {
251 		struct servent *sent;
252 
253 		if (h->type == RADIUS_AUTH)
254 			srvp->addr.sin_port =
255 			    (sent = getservbyname("radius", "udp")) != NULL ?
256 				sent->s_port : htons(RADIUS_PORT);
257 		else
258 			srvp->addr.sin_port =
259 			    (sent = getservbyname("radacct", "udp")) != NULL ?
260 				sent->s_port : htons(RADACCT_PORT);
261 	}
262 	if ((srvp->secret = strdup(secret)) == NULL) {
263 		generr(h, "Out of memory");
264 		return -1;
265 	}
266 	srvp->timeout = timeout;
267 	srvp->max_tries = tries;
268 	srvp->num_tries = 0;
269 	h->num_servers++;
270 	return 0;
271 }
272 
273 void
rad_close(struct rad_handle * h)274 rad_close(struct rad_handle *h)
275 {
276 	int srv;
277 
278 	if (h->fd != -1)
279 		close(h->fd);
280 	for (srv = 0;  srv < h->num_servers;  srv++) {
281 		memset(h->servers[srv].secret, 0,
282 		    strlen(h->servers[srv].secret));
283 		free(h->servers[srv].secret);
284 	}
285 	clear_password(h);
286 	free(h);
287 }
288 
289 int
rad_config(struct rad_handle * h,const char * path)290 rad_config(struct rad_handle *h, const char *path)
291 {
292 	FILE *fp;
293 	char buf[MAXCONFLINE];
294 	int linenum;
295 	int retval;
296 
297 	if (path == NULL)
298 		path = PATH_RADIUS_CONF;
299 	if ((fp = fopen(path, "r")) == NULL) {
300 		generr(h, "Cannot open \"%s\": %s", path, strerror(errno));
301 		return -1;
302 	}
303 	retval = 0;
304 	linenum = 0;
305 	while (fgets(buf, sizeof buf, fp) != NULL) {
306 		int len;
307 		char *fields[5];
308 		int nfields;
309 		char msg[ERRSIZE];
310 		char *type;
311 		char *host, *res;
312 		char *port_str;
313 		char *secret;
314 		char *timeout_str;
315 		char *maxtries_str;
316 		char *end;
317 		char *wanttype;
318 		unsigned long timeout;
319 		unsigned long maxtries;
320 		int port;
321 		int i;
322 
323 		linenum++;
324 		len = strlen(buf);
325 		/* We know len > 0, else fgets would have returned NULL. */
326 		if (buf[len - 1] != '\n') {
327 			if (len == sizeof buf - 1)
328 				generr(h, "%s:%d: line too long", path,
329 				    linenum);
330 			else
331 				generr(h, "%s:%d: missing newline", path,
332 				    linenum);
333 			retval = -1;
334 			break;
335 		}
336 		buf[len - 1] = '\0';
337 
338 		/* Extract the fields from the line. */
339 		nfields = split(buf, fields, 5, msg, sizeof msg);
340 		if (nfields == -1) {
341 			generr(h, "%s:%d: %s", path, linenum, msg);
342 			retval = -1;
343 			break;
344 		}
345 		if (nfields == 0)
346 			continue;
347 		/*
348 		 * The first field should contain "auth" or "acct" for
349 		 * authentication or accounting, respectively.  But older
350 		 * versions of the file didn't have that field.  Default
351 		 * it to "auth" for backward compatibility.
352 		 */
353 		if (strcmp(fields[0], "auth") != 0 &&
354 		    strcmp(fields[0], "acct") != 0) {
355 			if (nfields >= 5) {
356 				generr(h, "%s:%d: invalid service type", path,
357 				    linenum);
358 				retval = -1;
359 				break;
360 			}
361 			nfields++;
362 			for (i = nfields;  --i > 0;  )
363 				fields[i] = fields[i - 1];
364 			fields[0] = "auth";
365 		}
366 		if (nfields < 3) {
367 			generr(h, "%s:%d: missing shared secret", path,
368 			    linenum);
369 			retval = -1;
370 			break;
371 		}
372 		type = fields[0];
373 		host = fields[1];
374 		secret = fields[2];
375 		timeout_str = fields[3];
376 		maxtries_str = fields[4];
377 
378 		/* Ignore the line if it is for the wrong service type. */
379 		wanttype = h->type == RADIUS_AUTH ? "auth" : "acct";
380 		if (strcmp(type, wanttype) != 0)
381 			continue;
382 
383 		/* Parse and validate the fields. */
384 		res = host;
385 		host = strsep(&res, ":");
386 		port_str = strsep(&res, ":");
387 		if (port_str != NULL) {
388 			port = strtoul(port_str, &end, 10);
389 			if (*end != '\0') {
390 				generr(h, "%s:%d: invalid port", path,
391 				    linenum);
392 				retval = -1;
393 				break;
394 			}
395 		} else
396 			port = 0;
397 		if (timeout_str != NULL) {
398 			timeout = strtoul(timeout_str, &end, 10);
399 			if (*end != '\0') {
400 				generr(h, "%s:%d: invalid timeout", path,
401 				    linenum);
402 				retval = -1;
403 				break;
404 			}
405 		} else
406 			timeout = TIMEOUT;
407 		if (maxtries_str != NULL) {
408 			maxtries = strtoul(maxtries_str, &end, 10);
409 			if (*end != '\0') {
410 				generr(h, "%s:%d: invalid maxtries", path,
411 				    linenum);
412 				retval = -1;
413 				break;
414 			}
415 		} else
416 			maxtries = MAXTRIES;
417 
418 		if (rad_add_server(h, host, port, secret, timeout, maxtries) ==
419 		    -1) {
420 			strlcpy(msg, h->errmsg, sizeof msg);
421 			generr(h, "%s:%d: %s", path, linenum, msg);
422 			retval = -1;
423 			break;
424 		}
425 	}
426 	/* Clear out the buffer to wipe a possible copy of a shared secret */
427 	memset(buf, 0, sizeof buf);
428 	fclose(fp);
429 	return retval;
430 }
431 
432 /*
433  * rad_init_send_request() must have previously been called.
434  * Returns:
435  *   0     The application should select on *fd with a timeout of tv before
436  *         calling rad_continue_send_request again.
437  *   < 0   Failure
438  *   > 0   Success
439  */
440 int
rad_continue_send_request(struct rad_handle * h,int selected,int * fd,struct timeval * tv)441 rad_continue_send_request(struct rad_handle *h, int selected, int *fd,
442                           struct timeval *tv)
443 {
444 	int n;
445 
446 	if (selected) {
447 		struct sockaddr_in from;
448 		int fromlen;
449 
450 		fromlen = sizeof from;
451 		h->resp_len = recvfrom(h->fd, h->response,
452 		    MSGSIZE, MSG_WAITALL, (struct sockaddr *)&from, &fromlen);
453 		if (h->resp_len == -1) {
454 			generr(h, "recvfrom: %s", strerror(errno));
455 			return -1;
456 		}
457 		if (is_valid_response(h, h->srv, &from)) {
458 			h->resp_len = h->response[POS_LENGTH] << 8 |
459 			    h->response[POS_LENGTH+1];
460 			h->resp_pos = POS_ATTRS;
461 			return h->response[POS_CODE];
462 		}
463 	}
464 
465 	if (h->try == h->total_tries) {
466 		generr(h, "No valid RADIUS responses received");
467 		return -1;
468 	}
469 
470 	/*
471          * Scan round-robin to the next server that has some
472          * tries left.  There is guaranteed to be one, or we
473          * would have exited this loop by now.
474 	 */
475 	while (h->servers[h->srv].num_tries >= h->servers[h->srv].max_tries)
476 		if (++h->srv >= h->num_servers)
477 			h->srv = 0;
478 
479 	if (h->request[POS_CODE] == RAD_ACCOUNTING_REQUEST)
480 		/* Insert the request authenticator into the request */
481 		insert_request_authenticator(h, h->srv);
482 	else
483 		/* Insert the scrambled password into the request */
484 		if (h->pass_pos != 0)
485 			insert_scrambled_password(h, h->srv);
486 
487 	/* Send the request */
488 	n = sendto(h->fd, h->request, h->req_len, 0,
489 	    (const struct sockaddr *)&h->servers[h->srv].addr,
490 	    sizeof h->servers[h->srv].addr);
491 	if (n != h->req_len) {
492 		if (n == -1)
493 			generr(h, "sendto: %s", strerror(errno));
494 		else
495 			generr(h, "sendto: short write");
496 		return -1;
497 	}
498 
499 	h->try++;
500 	h->servers[h->srv].num_tries++;
501 	tv->tv_sec = h->servers[h->srv].timeout;
502 	tv->tv_usec = 0;
503 	*fd = h->fd;
504 
505 	return 0;
506 }
507 
508 int
rad_create_request(struct rad_handle * h,int code)509 rad_create_request(struct rad_handle *h, int code)
510 {
511 	int i;
512 
513 	h->request[POS_CODE] = code;
514 	h->request[POS_IDENT] = ++h->ident;
515 	/* Create a random authenticator */
516 	for (i = 0;  i < LEN_AUTH;  i += 2) {
517 		long r;
518 		r = arc4random();
519 		h->request[POS_AUTH+i] = r;
520 		h->request[POS_AUTH+i+1] = r >> 8;
521 	}
522 	h->req_len = POS_ATTRS;
523 	clear_password(h);
524 	return 0;
525 }
526 
527 struct in_addr
rad_cvt_addr(const void * data)528 rad_cvt_addr(const void *data)
529 {
530 	struct in_addr value;
531 
532 	memcpy(&value.s_addr, data, sizeof value.s_addr);
533 	return value;
534 }
535 
536 u_int32_t
rad_cvt_int(const void * data)537 rad_cvt_int(const void *data)
538 {
539 	u_int32_t value;
540 
541 	memcpy(&value, data, sizeof value);
542 	return ntohl(value);
543 }
544 
545 char *
rad_cvt_string(const void * data,size_t len)546 rad_cvt_string(const void *data, size_t len)
547 {
548 	char *s;
549 
550 	s = malloc(len + 1);
551 	if (s != NULL) {
552 		memcpy(s, data, len);
553 		s[len] = '\0';
554 	}
555 	return s;
556 }
557 
558 /*
559  * Returns the attribute type.  If none are left, returns 0.  On failure,
560  * returns -1.
561  */
562 int
rad_get_attr(struct rad_handle * h,const void ** value,size_t * len)563 rad_get_attr(struct rad_handle *h, const void **value, size_t *len)
564 {
565 	int type;
566 
567 	if (h->resp_pos >= h->resp_len)
568 		return 0;
569 	if (h->resp_pos + 2 > h->resp_len) {
570 		generr(h, "Malformed attribute in response");
571 		return -1;
572 	}
573 	type = h->response[h->resp_pos++];
574 	*len = h->response[h->resp_pos++] - 2;
575 	if (h->resp_pos + *len > h->resp_len) {
576 		generr(h, "Malformed attribute in response");
577 		return -1;
578 	}
579 	*value = &h->response[h->resp_pos];
580 	h->resp_pos += *len;
581 	return type;
582 }
583 
584 /*
585  * Returns -1 on error, 0 to indicate no event and >0 for success
586  */
587 int
rad_init_send_request(struct rad_handle * h,int * fd,struct timeval * tv)588 rad_init_send_request(struct rad_handle *h, int *fd, struct timeval *tv)
589 {
590 	int srv;
591 
592 	/* Make sure we have a socket to use */
593 	if (h->fd == -1) {
594 		struct sockaddr_in sin;
595 
596 		if ((h->fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
597 			generr(h, "Cannot create socket: %s", strerror(errno));
598 			return -1;
599 		}
600 		memset(&sin, 0, sizeof sin);
601 		sin.sin_len = sizeof sin;
602 		sin.sin_family = AF_INET;
603 		sin.sin_addr.s_addr = INADDR_ANY;
604 		sin.sin_port = htons(0);
605 		if (bind(h->fd, (const struct sockaddr *)&sin,
606 		    sizeof sin) == -1) {
607 			generr(h, "bind: %s", strerror(errno));
608 			close(h->fd);
609 			h->fd = -1;
610 			return -1;
611 		}
612 	}
613 
614 	if (h->request[POS_CODE] == RAD_ACCOUNTING_REQUEST) {
615 		/* Make sure no password given */
616 		if (h->pass_pos || h->chap_pass) {
617 			generr(h, "User or Chap Password in accounting request");
618 			return -1;
619 		}
620 	} else {
621 		/* Make sure the user gave us a password */
622 		if (h->pass_pos == 0 && !h->chap_pass) {
623 			generr(h, "No User or Chap Password attributes given");
624 			return -1;
625 		}
626 		if (h->pass_pos != 0 && h->chap_pass) {
627 			generr(h, "Both User and Chap Password attributes given");
628 			return -1;
629 		}
630 	}
631 
632 	/* Fill in the length field in the message */
633 	h->request[POS_LENGTH] = h->req_len >> 8;
634 	h->request[POS_LENGTH+1] = h->req_len;
635 
636 	/*
637 	 * Count the total number of tries we will make, and zero the
638 	 * counter for each server.
639 	 */
640 	h->total_tries = 0;
641 	for (srv = 0;  srv < h->num_servers;  srv++) {
642 		h->total_tries += h->servers[srv].max_tries;
643 		h->servers[srv].num_tries = 0;
644 	}
645 	if (h->total_tries == 0) {
646 		generr(h, "No RADIUS servers specified");
647 		return -1;
648 	}
649 
650 	h->try = h->srv = 0;
651 
652 	return rad_continue_send_request(h, 0, fd, tv);
653 }
654 
655 /*
656  * Create and initialize a rad_handle structure, and return it to the
657  * caller.  Can fail only if the necessary memory cannot be allocated.
658  * In that case, it returns NULL.
659  */
660 struct rad_handle *
rad_auth_open(void)661 rad_auth_open(void)
662 {
663 	struct rad_handle *h;
664 
665 	h = (struct rad_handle *)malloc(sizeof(struct rad_handle));
666 	if (h != NULL) {
667 		randinit();
668 		h->fd = -1;
669 		h->num_servers = 0;
670 		h->ident = arc4random();
671 		h->errmsg[0] = '\0';
672 		memset(h->pass, 0, sizeof h->pass);
673 		h->pass_len = 0;
674 		h->pass_pos = 0;
675 		h->chap_pass = 0;
676 		h->type = RADIUS_AUTH;
677 	}
678 	return h;
679 }
680 
681 struct rad_handle *
rad_acct_open(void)682 rad_acct_open(void)
683 {
684 	struct rad_handle *h;
685 
686 	h = rad_open();
687 	if (h != NULL)
688 	        h->type = RADIUS_ACCT;
689 	return h;
690 }
691 
692 struct rad_handle *
rad_open(void)693 rad_open(void)
694 {
695     return rad_auth_open();
696 }
697 
698 int
rad_put_addr(struct rad_handle * h,int type,struct in_addr addr)699 rad_put_addr(struct rad_handle *h, int type, struct in_addr addr)
700 {
701 	return rad_put_attr(h, type, &addr.s_addr, sizeof addr.s_addr);
702 }
703 
704 int
rad_put_attr(struct rad_handle * h,int type,const void * value,size_t len)705 rad_put_attr(struct rad_handle *h, int type, const void *value, size_t len)
706 {
707 	int result;
708 
709 	if (type == RAD_USER_PASSWORD)
710 		result = put_password_attr(h, type, value, len);
711 	else {
712 		result = put_raw_attr(h, type, value, len);
713 		if (result == 0 && type == RAD_CHAP_PASSWORD)
714 			h->chap_pass = 1;
715 	}
716 
717 	return result;
718 }
719 
720 int
rad_put_int(struct rad_handle * h,int type,u_int32_t value)721 rad_put_int(struct rad_handle *h, int type, u_int32_t value)
722 {
723 	u_int32_t nvalue;
724 
725 	nvalue = htonl(value);
726 	return rad_put_attr(h, type, &nvalue, sizeof nvalue);
727 }
728 
729 int
rad_put_string(struct rad_handle * h,int type,const char * str)730 rad_put_string(struct rad_handle *h, int type, const char *str)
731 {
732 	return rad_put_attr(h, type, str, strlen(str));
733 }
734 
735 /*
736  * Returns the response type code on success, or -1 on failure.
737  */
738 int
rad_send_request(struct rad_handle * h)739 rad_send_request(struct rad_handle *h)
740 {
741 	struct timeval timelimit;
742 	struct timeval tv;
743 	int fd;
744 	int n;
745 
746 	n = rad_init_send_request(h, &fd, &tv);
747 
748 	if (n != 0)
749 		return n;
750 
751 	gettimeofday(&timelimit, NULL);
752 	timeradd(&tv, &timelimit, &timelimit);
753 
754 	for ( ; ; ) {
755 		fd_set readfds;
756 
757 		FD_ZERO(&readfds);
758 		FD_SET(fd, &readfds);
759 
760 		n = select(fd + 1, &readfds, NULL, NULL, &tv);
761 
762 		if (n == -1) {
763 			generr(h, "select: %s", strerror(errno));
764 			return -1;
765 		}
766 
767 		if (!FD_ISSET(fd, &readfds)) {
768 			/* Compute a new timeout */
769 			gettimeofday(&tv, NULL);
770 			timersub(&timelimit, &tv, &tv);
771 			if (tv.tv_sec > 0 || (tv.tv_sec == 0 && tv.tv_usec > 0))
772 				/* Continue the select */
773 				continue;
774 		}
775 
776 		n = rad_continue_send_request(h, n, &fd, &tv);
777 
778 		if (n != 0)
779 			return n;
780 
781 		gettimeofday(&timelimit, NULL);
782 		timeradd(&tv, &timelimit, &timelimit);
783 	}
784 }
785 
786 const char *
rad_strerror(struct rad_handle * h)787 rad_strerror(struct rad_handle *h)
788 {
789 	return h->errmsg;
790 }
791 
792 /*
793  * Destructively split a string into fields separated by white space.
794  * `#' at the beginning of a field begins a comment that extends to the
795  * end of the string.  Fields may be quoted with `"'.  Inside quoted
796  * strings, the backslash escapes `\"' and `\\' are honored.
797  *
798  * Pointers to up to the first maxfields fields are stored in the fields
799  * array.  Missing fields get NULL pointers.
800  *
801  * The return value is the actual number of fields parsed, and is always
802  * <= maxfields.
803  *
804  * On a syntax error, places a message in the msg string, and returns -1.
805  */
806 static int
split(char * str,char * fields[],int maxfields,char * msg,size_t msglen)807 split(char *str, char *fields[], int maxfields, char *msg, size_t msglen)
808 {
809 	char *p;
810 	int i;
811 	static const char ws[] = " \t";
812 
813 	for (i = 0;  i < maxfields;  i++)
814 		fields[i] = NULL;
815 	p = str;
816 	i = 0;
817 	while (*p != '\0') {
818 		p += strspn(p, ws);
819 		if (*p == '#' || *p == '\0')
820 			break;
821 		if (i >= maxfields) {
822 			snprintf(msg, msglen, "line has too many fields");
823 			return -1;
824 		}
825 		if (*p == '"') {
826 			char *dst;
827 
828 			dst = ++p;
829 			fields[i] = dst;
830 			while (*p != '"') {
831 				if (*p == '\\') {
832 					p++;
833 					if (*p != '"' && *p != '\\' &&
834 					    *p != '\0') {
835 						snprintf(msg, msglen,
836 						    "invalid `\\' escape");
837 						return -1;
838 					}
839 				}
840 				if (*p == '\0') {
841 					snprintf(msg, msglen,
842 					    "unterminated quoted string");
843 					return -1;
844 				}
845 				*dst++ = *p++;
846 			}
847 			*dst = '\0';
848 			p++;
849 			if (*fields[i] == '\0') {
850 				snprintf(msg, msglen,
851 				    "empty quoted string not permitted");
852 				return -1;
853 			}
854 			if (*p != '\0' && strspn(p, ws) == 0) {
855 				snprintf(msg, msglen, "quoted string not"
856 				    " followed by white space");
857 				return -1;
858 			}
859 		} else {
860 			fields[i] = p;
861 			p += strcspn(p, ws);
862 			if (*p != '\0')
863 				*p++ = '\0';
864 		}
865 		i++;
866 	}
867 	return i;
868 }
869 
870 int
rad_get_vendor_attr(u_int32_t * vendor,const void ** data,size_t * len)871 rad_get_vendor_attr(u_int32_t *vendor, const void **data, size_t *len)
872 {
873 	struct vendor_attribute *attr;
874 
875 	attr = (struct vendor_attribute *)*data;
876 	*vendor = ntohl(attr->vendor_value);
877 	*data = attr->attrib_data;
878 	*len = attr->attrib_len - 2;
879 
880 	return (attr->attrib_type);
881 }
882 
883 int
rad_put_vendor_addr(struct rad_handle * h,int vendor,int type,struct in_addr addr)884 rad_put_vendor_addr(struct rad_handle *h, int vendor, int type,
885     struct in_addr addr)
886 {
887 	return (rad_put_vendor_attr(h, vendor, type, &addr.s_addr,
888 	    sizeof addr.s_addr));
889 }
890 
891 int
rad_put_vendor_attr(struct rad_handle * h,int vendor,int type,const void * value,size_t len)892 rad_put_vendor_attr(struct rad_handle *h, int vendor, int type,
893     const void *value, size_t len)
894 {
895 	struct vendor_attribute *attr;
896 	int res;
897 
898 	if ((attr = malloc(len + 6)) == NULL) {
899 		generr(h, "malloc failure (%d bytes)", len + 6);
900 		return -1;
901 	}
902 
903 	attr->vendor_value = htonl(vendor);
904 	attr->attrib_type = type;
905 	attr->attrib_len = len + 2;
906 	memcpy(attr->attrib_data, value, len);
907 
908 	res = put_raw_attr(h, RAD_VENDOR_SPECIFIC, attr, len + 6);
909 	free(attr);
910 	if (res == 0 && vendor == RAD_VENDOR_MICROSOFT
911 	    && (type == RAD_MICROSOFT_MS_CHAP_RESPONSE
912 	    || type == RAD_MICROSOFT_MS_CHAP2_RESPONSE)) {
913 		h->chap_pass = 1;
914 	}
915 	return (res);
916 }
917 
918 int
rad_put_vendor_int(struct rad_handle * h,int vendor,int type,u_int32_t i)919 rad_put_vendor_int(struct rad_handle *h, int vendor, int type, u_int32_t i)
920 {
921 	u_int32_t value;
922 
923 	value = htonl(i);
924 	return (rad_put_vendor_attr(h, vendor, type, &value, sizeof value));
925 }
926 
927 int
rad_put_vendor_string(struct rad_handle * h,int vendor,int type,const char * str)928 rad_put_vendor_string(struct rad_handle *h, int vendor, int type,
929     const char *str)
930 {
931 	return (rad_put_vendor_attr(h, vendor, type, str, strlen(str)));
932 }
933 
934 ssize_t
rad_request_authenticator(struct rad_handle * h,char * buf,size_t len)935 rad_request_authenticator(struct rad_handle *h, char *buf, size_t len)
936 {
937 	if (len < LEN_AUTH)
938 		return (-1);
939 	memcpy(buf, h->request + POS_AUTH, LEN_AUTH);
940 	if (len > LEN_AUTH)
941 		buf[LEN_AUTH] = '\0';
942 	return (LEN_AUTH);
943 }
944 
945 const char *
rad_server_secret(struct rad_handle * h)946 rad_server_secret(struct rad_handle *h)
947 {
948 	return (h->servers[h->srv].secret);
949 }
950