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