Home | History | Annotate | Line # | Download | only in libradius
radlib.c revision 1.2
      1 /* $NetBSD: radlib.c,v 1.2 2005/02/20 00:28:20 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.2 2005/02/20 00:28:20 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 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 *[], int, char *, size_t);
     94 
     95 static void
     96 clear_password(struct rad_handle *h)
     97 {
     98 	if (h->pass_len != 0) {
     99 		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, 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 	int padded_len;
    122 	int pos;
    123 
    124 	srvp = &h->servers[srv];
    125 	padded_len = h->pass_len == 0 ? 16 : (h->pass_len+15) & ~0xf;
    126 
    127 	memcpy(md5, &h->request[POS_AUTH], LEN_AUTH);
    128 	for (pos = 0;  pos < padded_len;  pos += 16) {
    129 		int i;
    130 
    131 		/* Calculate the new scrambler */
    132 		MD5Init(&ctx);
    133 		MD5Update(&ctx, srvp->secret,
    134 		    (MD5Len)strlen(srvp->secret));
    135 		MD5Update(&ctx, md5, (MD5Len)16);
    136 		MD5Final(md5, &ctx);
    137 
    138 		/*
    139 		 * Mix in the current chunk of the password, and copy
    140 		 * the result into the right place in the request.  Also
    141 		 * modify the scrambler in place, since we will use this
    142 		 * in calculating the scrambler for next time.
    143 		 */
    144 		for (i = 0;  i < 16;  i++)
    145 			h->request[h->pass_pos + pos + i] =
    146 			    md5[i] ^= h->pass[pos + i];
    147 	}
    148 }
    149 
    150 static void
    151 insert_request_authenticator(struct rad_handle *h, int srv)
    152 {
    153 	MD5_CTX ctx;
    154 	const struct rad_server *srvp;
    155 
    156 	srvp = &h->servers[srv];
    157 
    158 	/* Create the request authenticator */
    159 	MD5Init(&ctx);
    160 	MD5Update(&ctx, &h->request[POS_CODE],
    161 	    (MD5Len)(POS_AUTH - POS_CODE));
    162 	MD5Update(&ctx, memset(&h->request[POS_AUTH], 0, (size_t)LEN_AUTH),
    163 	    (MD5Len)LEN_AUTH);
    164 	MD5Update(&ctx, &h->request[POS_ATTRS],
    165 	    (MD5Len)(h->req_len - POS_ATTRS));
    166 	MD5Update(&ctx, srvp->secret,
    167 	    (MD5Len)strlen(srvp->secret));
    168 	MD5Final(&h->request[POS_AUTH], &ctx);
    169 }
    170 
    171 static void
    172 insert_message_authenticator(struct rad_handle *h, int srv)
    173 {
    174 #ifdef WITH_SSL
    175 	u_char md[EVP_MAX_MD_SIZE];
    176 	u_int md_len;
    177 	const struct rad_server *srvp;
    178 	HMAC_CTX ctx;
    179 	srvp = &h->servers[srv];
    180 
    181 	if (h->authentic_pos != 0) {
    182 		HMAC_CTX_init(&ctx);
    183 		HMAC_Init(&ctx, srvp->secret,
    184 		    (int)strlen(srvp->secret), EVP_md5());
    185 		HMAC_Update(&ctx, &h->request[POS_CODE], POS_AUTH - POS_CODE);
    186 		HMAC_Update(&ctx, &h->request[POS_AUTH], LEN_AUTH);
    187 		HMAC_Update(&ctx, &h->request[POS_ATTRS],
    188 		    (int)(h->req_len - POS_ATTRS));
    189 		HMAC_Final(&ctx, md, &md_len);
    190 		HMAC_CTX_cleanup(&ctx);
    191 		HMAC_cleanup(&ctx);
    192 		memcpy(&h->request[h->authentic_pos + 2], md, 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 		memcpy(resp, h->response, 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 				memset(&resp[pos + 2], 0, MD5_DIGEST_LENGTH);
    261 
    262 				HMAC_CTX_init(&hctx);
    263 				HMAC_Init(&hctx, srvp->secret,
    264 				    (int)strlen(srvp->secret), EVP_md5());
    265 				HMAC_Update(&hctx, &h->response[POS_CODE],
    266 				    POS_AUTH - POS_CODE);
    267 				HMAC_Update(&hctx, &h->request[POS_AUTH],
    268 				    LEN_AUTH);
    269 				HMAC_Update(&hctx, &resp[POS_ATTRS],
    270 				    (int)(h->resp_len - POS_ATTRS));
    271 				HMAC_Final(&hctx, md, &md_len);
    272 				HMAC_CTX_cleanup(&hctx);
    273 				HMAC_cleanup(&hctx);
    274 				if (memcmp(md, &h->response[pos + 2],
    275 				    MD5_DIGEST_LENGTH) != 0)
    276 					return 0;
    277 				break;
    278 			}
    279 			pos += h->response[pos + 1];
    280 		}
    281 	}
    282 #endif
    283 	return 1;
    284 }
    285 
    286 static int
    287 put_password_attr(struct rad_handle *h, int type, const void *value, size_t len)
    288 {
    289 	size_t padded_len;
    290 	size_t pad_len;
    291 
    292 	if (h->pass_pos != 0) {
    293 		generr(h, "Multiple User-Password attributes specified");
    294 		return -1;
    295 	}
    296 	if (len > PASSSIZE)
    297 		len = PASSSIZE;
    298 	padded_len = len == 0 ? 16 : (len + 15) & ~0xf;
    299 	pad_len = padded_len - len;
    300 
    301 	/*
    302 	 * Put in a place-holder attribute containing all zeros, and
    303 	 * remember where it is so we can fill it in later.
    304 	 */
    305 	clear_password(h);
    306 	put_raw_attr(h, type, h->pass, padded_len);
    307 	h->pass_pos = h->req_len - padded_len;
    308 
    309 	/* Save the cleartext password, padded as necessary */
    310 	(void)memcpy(h->pass, value, len);
    311 	h->pass_len = len;
    312 	(void)memset(h->pass + len, 0, pad_len);
    313 	return 0;
    314 }
    315 
    316 static int
    317 put_raw_attr(struct rad_handle *h, int type, const void *value, size_t len)
    318 {
    319 	if (len > 253) {
    320 		generr(h, "Attribute too long");
    321 		return -1;
    322 	}
    323 	if (h->req_len + 2 + len > MSGSIZE) {
    324 		generr(h, "Maximum message length exceeded");
    325 		return -1;
    326 	}
    327 	h->request[h->req_len++] = type;
    328 	h->request[h->req_len++] = len + 2;
    329 	(void)memcpy(&h->request[h->req_len], value, len);
    330 	h->req_len += len;
    331 	return 0;
    332 }
    333 
    334 int
    335 rad_add_server(struct rad_handle *h, const char *host, int port,
    336     const char *secret, int timeout, int tries)
    337 {
    338 	struct rad_server *srvp;
    339 
    340 	if (h->num_servers >= MAXSERVERS) {
    341 		generr(h, "Too many RADIUS servers specified");
    342 		return -1;
    343 	}
    344 	srvp = &h->servers[h->num_servers];
    345 
    346 	memset(&srvp->addr, 0, sizeof srvp->addr);
    347 	srvp->addr.sin_len = sizeof srvp->addr;
    348 	srvp->addr.sin_family = AF_INET;
    349 	if (!inet_aton(host, &srvp->addr.sin_addr)) {
    350 		struct hostent *hent;
    351 
    352 		if ((hent = gethostbyname(host)) == NULL) {
    353 			generr(h, "%s: host not found", host);
    354 			return -1;
    355 		}
    356 		memcpy(&srvp->addr.sin_addr, hent->h_addr,
    357 		    sizeof srvp->addr.sin_addr);
    358 	}
    359 	if (port != 0)
    360 		srvp->addr.sin_port = htons((u_short)port);
    361 	else {
    362 		struct servent *sent;
    363 
    364 		if (h->type == RADIUS_AUTH)
    365 			srvp->addr.sin_port =
    366 			    (sent = getservbyname("radius", "udp")) != NULL ?
    367 				sent->s_port : htons(RADIUS_PORT);
    368 		else
    369 			srvp->addr.sin_port =
    370 			    (sent = getservbyname("radacct", "udp")) != NULL ?
    371 				sent->s_port : htons(RADACCT_PORT);
    372 	}
    373 	if ((srvp->secret = strdup(secret)) == NULL) {
    374 		generr(h, "Out of memory");
    375 		return -1;
    376 	}
    377 	srvp->timeout = timeout;
    378 	srvp->max_tries = tries;
    379 	srvp->num_tries = 0;
    380 	h->num_servers++;
    381 	return 0;
    382 }
    383 
    384 void
    385 rad_close(struct rad_handle *h)
    386 {
    387 	int srv;
    388 
    389 	if (h->fd != -1)
    390 		close(h->fd);
    391 	for (srv = 0;  srv < h->num_servers;  srv++) {
    392 		memset(h->servers[srv].secret, 0,
    393 		    strlen(h->servers[srv].secret));
    394 		free(h->servers[srv].secret);
    395 	}
    396 	clear_password(h);
    397 	free(h);
    398 }
    399 
    400 int
    401 rad_config(struct rad_handle *h, const char *path)
    402 {
    403 	FILE *fp;
    404 	char buf[MAXCONFLINE];
    405 	int linenum;
    406 	int retval;
    407 
    408 	if (path == NULL)
    409 		path = PATH_RADIUS_CONF;
    410 	if ((fp = fopen(path, "r")) == NULL) {
    411 		generr(h, "Cannot open \"%s\": %s", path, strerror(errno));
    412 		return -1;
    413 	}
    414 	retval = 0;
    415 	linenum = 0;
    416 	while (fgets(buf, sizeof buf, fp) != NULL) {
    417 		int len;
    418 		const char *fields[5];
    419 		int nfields;
    420 		char msg[ERRSIZE];
    421 		const char *type;
    422 		const char *host;
    423 		char *res;
    424 		const char *port_str;
    425 		const char *secret;
    426 		const char *timeout_str;
    427 		const char *maxtries_str;
    428 		char *end;
    429 		const char *wanttype;
    430 		unsigned long timeout;
    431 		unsigned long maxtries;
    432 		int port;
    433 		int i;
    434 
    435 		linenum++;
    436 		len = strlen(buf);
    437 		/* We know len > 0, else fgets would have returned NULL. */
    438 		if (buf[len - 1] != '\n') {
    439 			if (len == sizeof buf - 1)
    440 				generr(h, "%s:%d: line too long", path,
    441 				    linenum);
    442 			else
    443 				generr(h, "%s:%d: missing newline", path,
    444 				    linenum);
    445 			retval = -1;
    446 			break;
    447 		}
    448 		buf[len - 1] = '\0';
    449 
    450 		/* Extract the fields from the line. */
    451 		nfields = split(buf, fields, sizeof(fields) / sizeof(fields[0]),
    452 		    msg, sizeof msg);
    453 		if (nfields == -1) {
    454 			generr(h, "%s:%d: %s", path, linenum, msg);
    455 			retval = -1;
    456 			break;
    457 		}
    458 		if (nfields == 0)
    459 			continue;
    460 		/*
    461 		 * The first field should contain "auth" or "acct" for
    462 		 * authentication or accounting, respectively.  But older
    463 		 * versions of the file didn't have that field.  Default
    464 		 * it to "auth" for backward compatibility.
    465 		 */
    466 		if (strcmp(fields[0], "auth") != 0 &&
    467 		    strcmp(fields[0], "acct") != 0) {
    468 			if (nfields >= 5) {
    469 				generr(h, "%s:%d: invalid service type", path,
    470 				    linenum);
    471 				retval = -1;
    472 				break;
    473 			}
    474 			nfields++;
    475 			for (i = nfields;  --i > 0;  )
    476 				fields[i] = fields[i - 1];
    477 			fields[0] = "auth";
    478 		}
    479 		if (nfields < 3) {
    480 			generr(h, "%s:%d: missing shared secret", path,
    481 			    linenum);
    482 			retval = -1;
    483 			break;
    484 		}
    485 		type = fields[0];
    486 		host = fields[1];
    487 		secret = fields[2];
    488 		timeout_str = fields[3];
    489 		maxtries_str = fields[4];
    490 
    491 		/* Ignore the line if it is for the wrong service type. */
    492 		wanttype = h->type == RADIUS_AUTH ? "auth" : "acct";
    493 		if (strcmp(type, wanttype) != 0)
    494 			continue;
    495 
    496 		/* Parse and validate the fields. */
    497 		res = __UNCONST(host);
    498 		host = strsep(&res, ":");
    499 		port_str = strsep(&res, ":");
    500 		if (port_str != NULL) {
    501 			port = strtoul(port_str, &end, 10);
    502 			if (*end != '\0') {
    503 				generr(h, "%s:%d: invalid port", path,
    504 				    linenum);
    505 				retval = -1;
    506 				break;
    507 			}
    508 		} else
    509 			port = 0;
    510 		if (timeout_str != NULL) {
    511 			timeout = strtoul(timeout_str, &end, 10);
    512 			if (*end != '\0') {
    513 				generr(h, "%s:%d: invalid timeout", path,
    514 				    linenum);
    515 				retval = -1;
    516 				break;
    517 			}
    518 		} else
    519 			timeout = TIMEOUT;
    520 		if (maxtries_str != NULL) {
    521 			maxtries = strtoul(maxtries_str, &end, 10);
    522 			if (*end != '\0') {
    523 				generr(h, "%s:%d: invalid maxtries", path,
    524 				    linenum);
    525 				retval = -1;
    526 				break;
    527 			}
    528 		} else
    529 			maxtries = MAXTRIES;
    530 
    531 		if (rad_add_server(h, host, port, secret, (int)timeout,
    532 		    (int)maxtries) == -1) {
    533 			(void)strcpy(msg, h->errmsg);
    534 			generr(h, "%s:%d: %s", path, linenum, msg);
    535 			retval = -1;
    536 			break;
    537 		}
    538 	}
    539 	/* Clear out the buffer to wipe a possible copy of a shared secret */
    540 	memset(buf, 0, sizeof buf);
    541 	fclose(fp);
    542 	return retval;
    543 }
    544 
    545 /*
    546  * rad_init_send_request() must have previously been called.
    547  * Returns:
    548  *   0     The application should select on *fd with a timeout of tv before
    549  *         calling rad_continue_send_request again.
    550  *   < 0   Failure
    551  *   > 0   Success
    552  */
    553 int
    554 rad_continue_send_request(struct rad_handle *h, int selected, int *fd,
    555                           struct timeval *tv)
    556 {
    557 	int n;
    558 
    559 	if (selected) {
    560 		struct sockaddr_in from;
    561 		socklen_t fromlen;
    562 		ssize_t rv;
    563 
    564 		fromlen = sizeof from;
    565 		rv = recvfrom(h->fd, h->response,
    566 		    MSGSIZE, MSG_WAITALL, (struct sockaddr *)(void *)&from,
    567 		    &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 != 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 	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 	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 		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 += *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 		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 		    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] = h->req_len >> 8;
    758 	h->request[POS_LENGTH+1] = 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();
    792 		h->fd = -1;
    793 		h->num_servers = 0;
    794 		h->ident = random();
    795 		h->errmsg[0] = '\0';
    796 		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 = h->req_len;
    905 		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[], int maxfields, char *msg, size_t msglen)
    990 {
    991 	char *p;
    992 	int i;
    993 	static const char ws[] = " \t";
    994 
    995 	for (i = 0;  i < maxfields;  i++)
    996 		fields[i] = NULL;
    997 	p = str;
    998 	i = 0;
    999 	while (*p != '\0') {
   1000 		p += strspn(p, ws);
   1001 		if (*p == '#' || *p == '\0')
   1002 			break;
   1003 		if (i >= maxfields) {
   1004 			snprintf(msg, msglen, "line has too many fields");
   1005 			return -1;
   1006 		}
   1007 		if (*p == '"') {
   1008 			char *dst;
   1009 
   1010 			dst = ++p;
   1011 			fields[i] = dst;
   1012 			while (*p != '"') {
   1013 				if (*p == '\\') {
   1014 					p++;
   1015 					if (*p != '"' && *p != '\\' &&
   1016 					    *p != '\0') {
   1017 						snprintf(msg, msglen,
   1018 						    "invalid `\\' escape");
   1019 						return -1;
   1020 					}
   1021 				}
   1022 				if (*p == '\0') {
   1023 					snprintf(msg, msglen,
   1024 					    "unterminated quoted string");
   1025 					return -1;
   1026 				}
   1027 				*dst++ = *p++;
   1028 			}
   1029 			*dst = '\0';
   1030 			p++;
   1031 			if (*fields[i] == '\0') {
   1032 				snprintf(msg, msglen,
   1033 				    "empty quoted string not permitted");
   1034 				return -1;
   1035 			}
   1036 			if (*p != '\0' && strspn(p, ws) == 0) {
   1037 				snprintf(msg, msglen, "quoted string not"
   1038 				    " followed by white space");
   1039 				return -1;
   1040 			}
   1041 		} else {
   1042 			fields[i] = p;
   1043 			p += strcspn(p, ws);
   1044 			if (*p != '\0')
   1045 				*p++ = '\0';
   1046 		}
   1047 		i++;
   1048 	}
   1049 	return i;
   1050 }
   1051 
   1052 int
   1053 rad_get_vendor_attr(u_int32_t *vendor, const void **data, size_t *len)
   1054 {
   1055 	const struct vendor_attribute *attr;
   1056 
   1057 	attr = (const struct vendor_attribute *)*data;
   1058 	*vendor = ntohl(attr->vendor_value);
   1059 	*data = attr->attrib_data;
   1060 	*len = attr->attrib_len - 2;
   1061 
   1062 	return (attr->attrib_type);
   1063 }
   1064 
   1065 int
   1066 rad_put_vendor_addr(struct rad_handle *h, int vendor, int type,
   1067     struct in_addr addr)
   1068 {
   1069 	return (rad_put_vendor_attr(h, vendor, type, &addr.s_addr,
   1070 	    sizeof addr.s_addr));
   1071 }
   1072 
   1073 int
   1074 rad_put_vendor_attr(struct rad_handle *h, int vendor, int type,
   1075     const void *value, size_t len)
   1076 {
   1077 	struct vendor_attribute *attr;
   1078 	int res;
   1079 
   1080 	if (!h->request_created) {
   1081 		generr(h, "Please call rad_create_request()"
   1082 		    " before putting attributes");
   1083 		return -1;
   1084 	}
   1085 
   1086 	if ((attr = malloc(len + 6)) == NULL) {
   1087 		generr(h, "malloc failure (%zu bytes)", len + 6);
   1088 		return -1;
   1089 	}
   1090 
   1091 	attr->vendor_value = htonl((uint32_t)vendor);
   1092 	attr->attrib_type = type;
   1093 	attr->attrib_len = len + 2;
   1094 	memcpy(attr->attrib_data, value, len);
   1095 
   1096 	res = put_raw_attr(h, RAD_VENDOR_SPECIFIC, attr, len + 6);
   1097 	free(attr);
   1098 	if (res == 0 && vendor == RAD_VENDOR_MICROSOFT
   1099 	    && (type == RAD_MICROSOFT_MS_CHAP_RESPONSE
   1100 	    || type == RAD_MICROSOFT_MS_CHAP2_RESPONSE)) {
   1101 		h->chap_pass = 1;
   1102 	}
   1103 	return (res);
   1104 }
   1105 
   1106 int
   1107 rad_put_vendor_int(struct rad_handle *h, int vendor, int type, u_int32_t i)
   1108 {
   1109 	u_int32_t value;
   1110 
   1111 	value = htonl(i);
   1112 	return (rad_put_vendor_attr(h, vendor, type, &value, sizeof value));
   1113 }
   1114 
   1115 int
   1116 rad_put_vendor_string(struct rad_handle *h, int vendor, int type,
   1117     const char *str)
   1118 {
   1119 	return (rad_put_vendor_attr(h, vendor, type, str, strlen(str)));
   1120 }
   1121 
   1122 ssize_t
   1123 rad_request_authenticator(struct rad_handle *h, char *buf, size_t len)
   1124 {
   1125 	if (len < LEN_AUTH)
   1126 		return (-1);
   1127 	memcpy(buf, h->request + POS_AUTH, LEN_AUTH);
   1128 	if (len > LEN_AUTH)
   1129 		buf[LEN_AUTH] = '\0';
   1130 	return (LEN_AUTH);
   1131 }
   1132 
   1133 u_char *
   1134 rad_demangle(struct rad_handle *h, const void *mangled, size_t mlen)
   1135 {
   1136 	char R[LEN_AUTH];
   1137 	const char *S;
   1138 	int i, Ppos;
   1139 	MD5_CTX Context;
   1140 	u_char b[MD5_DIGEST_LENGTH], *demangled;
   1141 	const u_char *C;
   1142 
   1143 	if ((mlen % 16 != 0) || mlen > 128) {
   1144 		generr(h, "Cannot interpret mangled data of length %lu",
   1145 		    (u_long)mlen);
   1146 		return NULL;
   1147 	}
   1148 
   1149 	C = (const u_char *)mangled;
   1150 
   1151 	/* We need the shared secret as Salt */
   1152 	S = rad_server_secret(h);
   1153 
   1154 	/* We need the request authenticator */
   1155 	if (rad_request_authenticator(h, R, sizeof R) != LEN_AUTH) {
   1156 		generr(h, "Cannot obtain the RADIUS request authenticator");
   1157 		return NULL;
   1158 	}
   1159 
   1160 	demangled = malloc(mlen);
   1161 	if (!demangled)
   1162 		return NULL;
   1163 
   1164 	MD5Init(&Context);
   1165 	MD5Update(&Context, S, (MD5Len)strlen(S));
   1166 	MD5Update(&Context, R, (MD5Len)LEN_AUTH);
   1167 	MD5Final(b, &Context);
   1168 	Ppos = 0;
   1169 	while (mlen) {
   1170 
   1171 		mlen -= 16;
   1172 		for (i = 0; i < 16; i++)
   1173 			demangled[Ppos++] = C[i] ^ b[i];
   1174 
   1175 		if (mlen) {
   1176 			MD5Init(&Context);
   1177 			MD5Update(&Context, S, (MD5Len)strlen(S));
   1178 			MD5Update(&Context, C, (MD5Len)16);
   1179 			MD5Final(b, &Context);
   1180 		}
   1181 
   1182 		C += 16;
   1183 	}
   1184 
   1185 	return demangled;
   1186 }
   1187 
   1188 u_char *
   1189 rad_demangle_mppe_key(struct rad_handle *h, const void *mangled,
   1190     size_t mlen, size_t *len)
   1191 {
   1192 	char R[LEN_AUTH];    /* variable names as per rfc2548 */
   1193 	const char *S;
   1194 	u_char b[MD5_DIGEST_LENGTH], *demangled;
   1195 	const u_char *A, *C;
   1196 	MD5_CTX Context;
   1197 	size_t Slen, Clen, i, Ppos;
   1198 	u_char *P;
   1199 
   1200 	if (mlen % 16 != SALT_LEN) {
   1201 		generr(h, "Cannot interpret mangled data of length %lu",
   1202 		    (u_long)mlen);
   1203 		return NULL;
   1204 	}
   1205 
   1206 	/* We need the RADIUS Request-Authenticator */
   1207 	if (rad_request_authenticator(h, R, sizeof R) != LEN_AUTH) {
   1208 		generr(h, "Cannot obtain the RADIUS request authenticator");
   1209 		return NULL;
   1210 	}
   1211 
   1212 	A = (const u_char *)mangled;      /* Salt comes first */
   1213 	C = (const u_char *)mangled + SALT_LEN;  /* Then the ciphertext */
   1214 	Clen = mlen - SALT_LEN;
   1215 	S = rad_server_secret(h);    /* We need the RADIUS secret */
   1216 	Slen = strlen(S);
   1217 	P = alloca(Clen);        /* We derive our plaintext */
   1218 
   1219 	MD5Init(&Context);
   1220 	MD5Update(&Context, S, (MD5Len)Slen);
   1221 	MD5Update(&Context, R, (MD5Len)LEN_AUTH);
   1222 	MD5Update(&Context, A, (MD5Len)SALT_LEN);
   1223 	MD5Final(b, &Context);
   1224 	Ppos = 0;
   1225 
   1226 	while (Clen) {
   1227 		Clen -= 16;
   1228 
   1229 		for (i = 0; i < 16; i++)
   1230 		    P[Ppos++] = C[i] ^ b[i];
   1231 
   1232 		if (Clen) {
   1233 			MD5Init(&Context);
   1234 			MD5Update(&Context, S, (MD5Len)Slen);
   1235 			MD5Update(&Context, C, (MD5Len)16);
   1236 			MD5Final(b, &Context);
   1237 		}
   1238 
   1239 		C += 16;
   1240 	}
   1241 
   1242 	/*
   1243 	* The resulting plain text consists of a one-byte length, the text and
   1244 	* maybe some padding.
   1245 	*/
   1246 	*len = *P;
   1247 	if (*len > mlen - 1) {
   1248 		generr(h, "Mangled data seems to be garbage %zu %zu",
   1249 		    *len, mlen-1);
   1250 		return NULL;
   1251 	}
   1252 
   1253 	if (*len > MPPE_KEY_LEN * 2) {
   1254 		generr(h, "Key to long (%zu) for me max. %d",
   1255 		    *len, MPPE_KEY_LEN * 2);
   1256 		return NULL;
   1257 	}
   1258 	demangled = malloc(*len);
   1259 	if (!demangled)
   1260 		return NULL;
   1261 
   1262 	memcpy(demangled, P + 1, *len);
   1263 	return demangled;
   1264 }
   1265 
   1266 const char *
   1267 rad_server_secret(struct rad_handle *h)
   1268 {
   1269 	return (h->servers[h->srv].secret);
   1270 }
   1271