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