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