2 * Copyright 1998 Juniper Networks, Inc.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * $FreeBSD: src/lib/libradius/radlib.c,v 1.15 2009/09/29 19:09:17 mav Exp $
29 #include <sys/cdefs.h>
31 #include <sys/types.h>
32 #include <sys/socket.h>
34 #include <netinet/in.h>
35 #include <arpa/inet.h>
37 #include <openssl/hmac.h>
38 #include <openssl/md5.h>
39 #define MD5Init MD5_Init
40 #define MD5Update MD5_Update
41 #define MD5Final MD5_Final
43 #define MD5_DIGEST_LENGTH 16
49 /* We need the MPPE_KEY_LEN define */
51 #include <netgraph7/mppc/ng_mppc.h>
53 #include <netgraph/mppc/ng_mppc.h>
65 #include "radlib_private.h"
67 static void clear_password(struct rad_handle *);
68 static void generr(struct rad_handle *, const char *, ...)
70 static void insert_scrambled_password(struct rad_handle *, int);
71 static void insert_request_authenticator(struct rad_handle *, int);
72 static void insert_message_authenticator(struct rad_handle *, int);
73 static int is_valid_response(struct rad_handle *, int,
74 const struct sockaddr_in *);
75 static int put_password_attr(struct rad_handle *, int,
76 const void *, size_t);
77 static int put_raw_attr(struct rad_handle *, int,
78 const void *, size_t);
79 static int split(char *, const char *[], int, char *, size_t);
82 clear_password(struct rad_handle *h)
84 if (h->pass_len != 0) {
85 memset(h->pass, 0, h->pass_len);
92 generr(struct rad_handle *h, const char *format, ...)
97 vsnprintf(h->errmsg, ERRSIZE, format, ap);
102 insert_scrambled_password(struct rad_handle *h, int srv)
105 unsigned char md5[MD5_DIGEST_LENGTH];
106 const struct rad_server *srvp;
110 srvp = &h->servers[srv];
111 padded_len = h->pass_len == 0 ? 16 : (h->pass_len+15) & ~0xf;
113 memcpy(md5, &h->out[POS_AUTH], LEN_AUTH);
114 for (pos = 0; pos < padded_len; pos += 16) {
117 /* Calculate the new scrambler */
119 MD5Update(&ctx, srvp->secret, strlen(srvp->secret));
120 MD5Update(&ctx, md5, 16);
124 * Mix in the current chunk of the password, and copy
125 * the result into the right place in the request. Also
126 * modify the scrambler in place, since we will use this
127 * in calculating the scrambler for next time.
129 for (i = 0; i < 16; i++)
130 h->out[h->pass_pos + pos + i] =
131 md5[i] ^= h->pass[pos + i];
136 insert_request_authenticator(struct rad_handle *h, int resp)
139 const struct rad_server *srvp;
141 srvp = &h->servers[h->srv];
143 /* Create the request authenticator */
145 MD5Update(&ctx, &h->out[POS_CODE], POS_AUTH - POS_CODE);
147 MD5Update(&ctx, &h->in[POS_AUTH], LEN_AUTH);
149 MD5Update(&ctx, &h->out[POS_AUTH], LEN_AUTH);
150 MD5Update(&ctx, &h->out[POS_ATTRS], h->out_len - POS_ATTRS);
151 MD5Update(&ctx, srvp->secret, strlen(srvp->secret));
152 MD5Final(&h->out[POS_AUTH], &ctx);
156 insert_message_authenticator(struct rad_handle *h, int resp)
159 u_char md[EVP_MAX_MD_SIZE];
161 const struct rad_server *srvp;
163 srvp = &h->servers[h->srv];
165 if (h->authentic_pos != 0) {
167 HMAC_Init(&ctx, srvp->secret, strlen(srvp->secret), EVP_md5());
168 HMAC_Update(&ctx, &h->out[POS_CODE], POS_AUTH - POS_CODE);
170 HMAC_Update(&ctx, &h->in[POS_AUTH], LEN_AUTH);
172 HMAC_Update(&ctx, &h->out[POS_AUTH], LEN_AUTH);
173 HMAC_Update(&ctx, &h->out[POS_ATTRS],
174 h->out_len - POS_ATTRS);
175 HMAC_Final(&ctx, md, &md_len);
176 HMAC_CTX_cleanup(&ctx);
178 memcpy(&h->out[h->authentic_pos + 2], md, md_len);
184 * Return true if the current response is valid for a request to the
188 is_valid_response(struct rad_handle *h, int srv,
189 const struct sockaddr_in *from)
192 unsigned char md5[MD5_DIGEST_LENGTH];
193 const struct rad_server *srvp;
197 u_char resp[MSGSIZE], md[EVP_MAX_MD_SIZE];
202 srvp = &h->servers[srv];
204 /* Check the source address */
205 if (from->sin_family != srvp->addr.sin_family ||
206 from->sin_addr.s_addr != srvp->addr.sin_addr.s_addr ||
207 from->sin_port != srvp->addr.sin_port)
210 /* Check the message length */
211 if (h->in_len < POS_ATTRS)
213 len = h->in[POS_LENGTH] << 8 | h->in[POS_LENGTH+1];
217 /* Check the response authenticator */
219 MD5Update(&ctx, &h->in[POS_CODE], POS_AUTH - POS_CODE);
220 MD5Update(&ctx, &h->out[POS_AUTH], LEN_AUTH);
221 MD5Update(&ctx, &h->in[POS_ATTRS], len - POS_ATTRS);
222 MD5Update(&ctx, srvp->secret, strlen(srvp->secret));
224 if (memcmp(&h->in[POS_AUTH], md5, sizeof md5) != 0)
229 * For non accounting responses check the message authenticator,
232 if (h->in[POS_CODE] != RAD_ACCOUNTING_RESPONSE) {
234 memcpy(resp, h->in, MSGSIZE);
237 /* Search and verify the Message-Authenticator */
238 while (pos < len - 2) {
240 if (h->in[pos] == RAD_MESSAGE_AUTHENTIC) {
241 /* zero fill the Message-Authenticator */
242 memset(&resp[pos + 2], 0, MD5_DIGEST_LENGTH);
244 HMAC_CTX_init(&hctx);
245 HMAC_Init(&hctx, srvp->secret,
246 strlen(srvp->secret), EVP_md5());
247 HMAC_Update(&hctx, &h->in[POS_CODE],
248 POS_AUTH - POS_CODE);
249 HMAC_Update(&hctx, &h->out[POS_AUTH],
251 HMAC_Update(&hctx, &resp[POS_ATTRS],
252 h->in_len - POS_ATTRS);
253 HMAC_Final(&hctx, md, &md_len);
254 HMAC_CTX_cleanup(&hctx);
256 if (memcmp(md, &h->in[pos + 2],
257 MD5_DIGEST_LENGTH) != 0)
261 pos += h->in[pos + 1];
269 * Return true if the current request is valid for the specified server.
272 is_valid_request(struct rad_handle *h)
275 unsigned char md5[MD5_DIGEST_LENGTH];
276 const struct rad_server *srvp;
280 u_char resp[MSGSIZE], md[EVP_MAX_MD_SIZE];
285 srvp = &h->servers[h->srv];
287 /* Check the message length */
288 if (h->in_len < POS_ATTRS)
290 len = h->in[POS_LENGTH] << 8 | h->in[POS_LENGTH+1];
294 if (h->in[POS_CODE] != RAD_ACCESS_REQUEST) {
295 uint32_t zeroes[4] = { 0, 0, 0, 0 };
296 /* Check the request authenticator */
298 MD5Update(&ctx, &h->in[POS_CODE], POS_AUTH - POS_CODE);
299 MD5Update(&ctx, zeroes, LEN_AUTH);
300 MD5Update(&ctx, &h->in[POS_ATTRS], len - POS_ATTRS);
301 MD5Update(&ctx, srvp->secret, strlen(srvp->secret));
303 if (memcmp(&h->in[POS_AUTH], md5, sizeof md5) != 0)
308 /* Search and verify the Message-Authenticator */
310 while (pos < len - 2) {
311 if (h->in[pos] == RAD_MESSAGE_AUTHENTIC) {
312 memcpy(resp, h->in, MSGSIZE);
313 /* zero fill the Request-Authenticator */
314 if (h->in[POS_CODE] != RAD_ACCESS_REQUEST)
315 memset(&resp[POS_AUTH], 0, LEN_AUTH);
316 /* zero fill the Message-Authenticator */
317 memset(&resp[pos + 2], 0, MD5_DIGEST_LENGTH);
319 HMAC_CTX_init(&hctx);
320 HMAC_Init(&hctx, srvp->secret,
321 strlen(srvp->secret), EVP_md5());
322 HMAC_Update(&hctx, resp, h->in_len);
323 HMAC_Final(&hctx, md, &md_len);
324 HMAC_CTX_cleanup(&hctx);
326 if (memcmp(md, &h->in[pos + 2],
327 MD5_DIGEST_LENGTH) != 0)
331 pos += h->in[pos + 1];
338 put_password_attr(struct rad_handle *h, int type, const void *value, size_t len)
343 if (h->pass_pos != 0) {
344 generr(h, "Multiple User-Password attributes specified");
349 padded_len = len == 0 ? 16 : (len+15) & ~0xf;
350 pad_len = padded_len - len;
353 * Put in a place-holder attribute containing all zeros, and
354 * remember where it is so we can fill it in later.
357 put_raw_attr(h, type, h->pass, padded_len);
358 h->pass_pos = h->out_len - padded_len;
360 /* Save the cleartext password, padded as necessary */
361 memcpy(h->pass, value, len);
363 memset(h->pass + len, 0, pad_len);
368 put_raw_attr(struct rad_handle *h, int type, const void *value, size_t len)
371 generr(h, "Attribute too long");
374 if (h->out_len + 2 + len > MSGSIZE) {
375 generr(h, "Maximum message length exceeded");
378 h->out[h->out_len++] = type;
379 h->out[h->out_len++] = len + 2;
380 memcpy(&h->out[h->out_len], value, len);
386 rad_add_server(struct rad_handle *h, const char *host, int port,
387 const char *secret, int timeout, int tries)
389 struct in_addr bindto;
390 bindto.s_addr = INADDR_ANY;
392 return rad_add_server_ex(h, host, port, secret, timeout, tries,
397 rad_add_server_ex(struct rad_handle *h, const char *host, int port,
398 const char *secret, int timeout, int tries, int dead_time,
399 struct in_addr *bindto)
401 struct rad_server *srvp;
403 if (h->num_servers >= MAXSERVERS) {
404 generr(h, "Too many RADIUS servers specified");
407 srvp = &h->servers[h->num_servers];
409 memset(&srvp->addr, 0, sizeof srvp->addr);
410 srvp->addr.sin_len = sizeof srvp->addr;
411 srvp->addr.sin_family = AF_INET;
412 if (!inet_aton(host, &srvp->addr.sin_addr)) {
413 struct hostent *hent;
415 if ((hent = gethostbyname(host)) == NULL) {
416 generr(h, "%s: host not found", host);
419 memcpy(&srvp->addr.sin_addr, hent->h_addr,
420 sizeof srvp->addr.sin_addr);
423 srvp->addr.sin_port = htons((u_short)port);
425 struct servent *sent;
427 if (h->type == RADIUS_AUTH)
428 srvp->addr.sin_port =
429 (sent = getservbyname("radius", "udp")) != NULL ?
430 sent->s_port : htons(RADIUS_PORT);
432 srvp->addr.sin_port =
433 (sent = getservbyname("radacct", "udp")) != NULL ?
434 sent->s_port : htons(RADACCT_PORT);
436 if ((srvp->secret = strdup(secret)) == NULL) {
437 generr(h, "Out of memory");
440 srvp->timeout = timeout;
441 srvp->max_tries = tries;
444 srvp->dead_time = dead_time;
445 srvp->next_probe = 0;
446 srvp->bindto = bindto->s_addr;
452 rad_close(struct rad_handle *h)
458 for (srv = 0; srv < h->num_servers; srv++) {
459 memset(h->servers[srv].secret, 0,
460 strlen(h->servers[srv].secret));
461 free(h->servers[srv].secret);
468 rad_bind_to(struct rad_handle *h, in_addr_t addr)
475 rad_config(struct rad_handle *h, const char *path)
478 char buf[MAXCONFLINE];
483 path = PATH_RADIUS_CONF;
484 if ((fp = fopen(path, "r")) == NULL) {
485 generr(h, "Cannot open \"%s\": %s", path, strerror(errno));
490 while (fgets(buf, sizeof buf, fp) != NULL) {
492 const char *fields[MAX_FIELDS];
497 const char *port_str;
499 const char *timeout_str;
500 const char *maxtries_str;
501 const char *dead_time_str;
502 const char *bindto_str;
503 char *res, *host_dup;
505 const char *wanttype;
506 unsigned long timeout;
507 unsigned long maxtries;
508 unsigned long dead_time;
510 struct in_addr bindto;
515 /* We know len > 0, else fgets would have returned NULL. */
516 if (buf[len - 1] != '\n') {
517 if (len == sizeof buf - 1)
518 generr(h, "%s:%d: line too long", path,
521 generr(h, "%s:%d: missing newline", path,
528 /* Extract the fields from the line. */
529 nfields = split(buf, fields, MAX_FIELDS, msg, sizeof msg);
531 generr(h, "%s:%d: %s", path, linenum, msg);
538 * The first field should contain "auth" or "acct" for
539 * authentication or accounting, respectively. But older
540 * versions of the file didn't have that field. Default
541 * it to "auth" for backward compatibility.
543 if (strcmp(fields[0], "auth") != 0 &&
544 strcmp(fields[0], "acct") != 0) {
545 if (nfields >= MAX_FIELDS) {
546 generr(h, "%s:%d: invalid service type", path,
552 for (i = nfields; --i > 0; )
553 fields[i] = fields[i - 1];
557 generr(h, "%s:%d: missing shared secret", path,
565 timeout_str = fields[3];
566 maxtries_str = fields[4];
567 dead_time_str = fields[5];
568 bindto_str = fields[6];
570 /* Ignore the line if it is for the wrong service type. */
571 wanttype = h->type == RADIUS_AUTH ? "auth" : "acct";
572 if (strcmp(type, wanttype) != 0)
575 /* Parse and validate the fields. */
576 if ((host_dup = strdup(host)) == NULL) {
577 generr(h, "%s:%d: malloc failed", path, linenum);
582 host = strsep(&res, ":");
583 port_str = strsep(&res, ":");
584 if (port_str != NULL) {
585 port = strtoul(port_str, &end, 10);
588 generr(h, "%s:%d: invalid port", path,
595 if (timeout_str != NULL) {
596 timeout = strtoul(timeout_str, &end, 10);
599 generr(h, "%s:%d: invalid timeout", path,
606 if (maxtries_str != NULL) {
607 maxtries = strtoul(maxtries_str, &end, 10);
610 generr(h, "%s:%d: invalid maxtries", path,
618 if (dead_time_str != NULL) {
619 dead_time = strtoul(dead_time_str, &end, 10);
622 generr(h, "%s:%d: invalid dead_time", path,
628 dead_time = DEAD_TIME;
630 if (bindto_str != NULL) {
631 bindto.s_addr = inet_addr(bindto_str);
632 if (bindto.s_addr == INADDR_NONE) {
634 generr(h, "%s:%d: invalid bindto", path,
640 bindto.s_addr = INADDR_ANY;
642 if (rad_add_server_ex(h, host, port, secret, timeout, maxtries,
643 dead_time, &bindto) == -1) {
645 strcpy(msg, h->errmsg);
646 generr(h, "%s:%d: %s", path, linenum, msg);
652 /* Clear out the buffer to wipe a possible copy of a shared secret */
653 memset(buf, 0, sizeof buf);
659 * rad_init_send_request() must have previously been called.
661 * 0 The application should select on *fd with a timeout of tv before
662 * calling rad_continue_send_request again.
667 rad_continue_send_request(struct rad_handle *h, int selected, int *fd,
672 struct sockaddr_in sin;
674 if (h->type == RADIUS_SERVER) {
675 generr(h, "denied function call");
679 struct sockaddr_in from;
682 fromlen = sizeof from;
683 h->in_len = recvfrom(h->fd, h->in,
684 MSGSIZE, MSG_WAITALL, (struct sockaddr *)&from, &fromlen);
685 if (h->in_len == -1) {
686 generr(h, "recvfrom: %s", strerror(errno));
689 if (is_valid_response(h, h->srv, &from)) {
690 h->in_len = h->in[POS_LENGTH] << 8 |
692 h->in_pos = POS_ATTRS;
693 return h->in[POS_CODE];
698 * Scan round-robin to the next server that has some
699 * tries left. There is guaranteed to be one, or we
700 * would have exited this loop by now.
704 if (h->servers[h->srv].num_tries >= h->servers[h->srv].max_tries) {
705 /* Set next probe time for this server */
706 if (h->servers[h->srv].dead_time) {
707 h->servers[h->srv].is_dead = 1;
708 h->servers[h->srv].next_probe = now +
709 h->servers[h->srv].dead_time;
713 if (h->srv >= h->num_servers)
715 if (h->servers[h->srv].is_dead == 0)
717 if (h->servers[h->srv].dead_time &&
718 h->servers[h->srv].next_probe <= now) {
719 h->servers[h->srv].is_dead = 0;
720 h->servers[h->srv].num_tries = 0;
723 } while (h->srv != cur_srv);
725 if (h->srv == cur_srv) {
726 generr(h, "No valid RADIUS responses received");
732 if (h->bindto != h->servers[h->srv].bindto) {
733 h->bindto = h->servers[h->srv].bindto;
735 if ((h->fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
736 generr(h, "Cannot create socket: %s", strerror(errno));
739 memset(&sin, 0, sizeof sin);
740 sin.sin_len = sizeof sin;
741 sin.sin_family = AF_INET;
742 sin.sin_addr.s_addr = h->bindto;
744 if (bind(h->fd, (const struct sockaddr *)&sin,
746 generr(h, "bind: %s", strerror(errno));
753 if (h->out[POS_CODE] == RAD_ACCESS_REQUEST) {
754 /* Insert the scrambled password into the request */
755 if (h->pass_pos != 0)
756 insert_scrambled_password(h, h->srv);
758 insert_message_authenticator(h, 0);
760 if (h->out[POS_CODE] != RAD_ACCESS_REQUEST) {
761 /* Insert the request authenticator into the request */
762 memset(&h->out[POS_AUTH], 0, LEN_AUTH);
763 insert_request_authenticator(h, 0);
766 /* Send the request */
767 n = sendto(h->fd, h->out, h->out_len, 0,
768 (const struct sockaddr *)&h->servers[h->srv].addr,
769 sizeof h->servers[h->srv].addr);
771 tv->tv_sec = 1; /* Do not wait full timeout if send failed. */
773 tv->tv_sec = h->servers[h->srv].timeout;
774 h->servers[h->srv].num_tries++;
782 rad_receive_request(struct rad_handle *h)
784 struct sockaddr_in from;
788 if (h->type != RADIUS_SERVER) {
789 generr(h, "denied function call");
793 fromlen = sizeof(from);
794 h->in_len = recvfrom(h->fd, h->in,
795 MSGSIZE, MSG_WAITALL, (struct sockaddr *)&from, &fromlen);
796 if (h->in_len == -1) {
797 generr(h, "recvfrom: %s", strerror(errno));
800 for (n = 0; n < h->num_servers; n++) {
801 if (h->servers[n].addr.sin_addr.s_addr == from.sin_addr.s_addr) {
802 h->servers[n].addr.sin_port = from.sin_port;
809 if (is_valid_request(h)) {
810 h->in_len = h->in[POS_LENGTH] << 8 |
812 h->in_pos = POS_ATTRS;
813 return (h->in[POS_CODE]);
819 rad_send_response(struct rad_handle *h)
823 if (h->type != RADIUS_SERVER) {
824 generr(h, "denied function call");
827 /* Fill in the length field in the message */
828 h->out[POS_LENGTH] = h->out_len >> 8;
829 h->out[POS_LENGTH+1] = h->out_len;
831 insert_message_authenticator(h,
832 (h->in[POS_CODE] == RAD_ACCESS_REQUEST) ? 1 : 0);
833 insert_request_authenticator(h, 1);
835 /* Send the request */
836 n = sendto(h->fd, h->out, h->out_len, 0,
837 (const struct sockaddr *)&h->servers[h->srv].addr,
838 sizeof h->servers[h->srv].addr);
839 if (n != h->out_len) {
841 generr(h, "sendto: %s", strerror(errno));
843 generr(h, "sendto: short write");
851 rad_create_request(struct rad_handle *h, int code)
855 if (h->type == RADIUS_SERVER) {
856 generr(h, "denied function call");
859 if (h->num_servers == 0) {
860 generr(h, "No RADIUS servers specified");
863 h->out[POS_CODE] = code;
864 h->out[POS_IDENT] = ++h->ident;
865 if (code == RAD_ACCESS_REQUEST) {
866 /* Create a random authenticator */
867 for (i = 0; i < LEN_AUTH; i += 2) {
870 h->out[POS_AUTH+i] = (u_char)r;
871 h->out[POS_AUTH+i+1] = (u_char)(r >> 8);
874 memset(&h->out[POS_AUTH], 0, LEN_AUTH);
875 h->out_len = POS_ATTRS;
877 h->authentic_pos = 0;
883 rad_create_response(struct rad_handle *h, int code)
886 if (h->type != RADIUS_SERVER) {
887 generr(h, "denied function call");
890 h->out[POS_CODE] = code;
891 h->out[POS_IDENT] = h->in[POS_IDENT];
892 memset(&h->out[POS_AUTH], 0, LEN_AUTH);
893 h->out_len = POS_ATTRS;
895 h->authentic_pos = 0;
901 rad_cvt_addr(const void *data)
903 struct in_addr value;
905 memcpy(&value.s_addr, data, sizeof value.s_addr);
910 rad_cvt_addr6(const void *data)
912 struct in6_addr value;
914 memcpy(&value.s6_addr, data, sizeof value.s6_addr);
919 rad_cvt_int(const void *data)
923 memcpy(&value, data, sizeof value);
928 rad_cvt_string(const void *data, size_t len)
934 memcpy(s, data, len);
941 * Returns the attribute type. If none are left, returns 0. On failure,
945 rad_get_attr(struct rad_handle *h, const void **value, size_t *len)
949 if (h->in_pos >= h->in_len)
951 if (h->in_pos + 2 > h->in_len) {
952 generr(h, "Malformed attribute in response");
955 type = h->in[h->in_pos++];
956 *len = h->in[h->in_pos++] - 2;
957 if (h->in_pos + (int)*len > h->in_len) {
958 generr(h, "Malformed attribute in response");
961 *value = &h->in[h->in_pos];
967 * Returns -1 on error, 0 to indicate no event and >0 for success
970 rad_init_send_request(struct rad_handle *h, int *fd, struct timeval *tv)
974 struct sockaddr_in sin;
976 if (h->type == RADIUS_SERVER) {
977 generr(h, "denied function call");
980 /* Make sure we have a socket to use */
982 if ((h->fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
983 generr(h, "Cannot create socket: %s", strerror(errno));
986 memset(&sin, 0, sizeof sin);
987 sin.sin_len = sizeof sin;
988 sin.sin_family = AF_INET;
989 sin.sin_addr.s_addr = h->bindto;
990 sin.sin_port = htons(0);
991 if (bind(h->fd, (const struct sockaddr *)&sin,
993 generr(h, "bind: %s", strerror(errno));
1000 if (h->out[POS_CODE] != RAD_ACCESS_REQUEST) {
1001 /* Make sure no password given */
1002 if (h->pass_pos || h->chap_pass) {
1003 generr(h, "User or Chap Password"
1004 " in accounting request");
1008 if (h->eap_msg == 0) {
1009 /* Make sure the user gave us a password */
1010 if (h->pass_pos == 0 && !h->chap_pass) {
1011 generr(h, "No User or Chap Password"
1012 " attributes given");
1015 if (h->pass_pos != 0 && h->chap_pass) {
1016 generr(h, "Both User and Chap Password"
1017 " attributes given");
1023 /* Fill in the length field in the message */
1024 h->out[POS_LENGTH] = h->out_len >> 8;
1025 h->out[POS_LENGTH+1] = h->out_len;
1029 for (srv = 0; srv < h->num_servers; srv++)
1030 h->servers[srv].num_tries = 0;
1031 /* Find a first good server. */
1032 for (srv = 0; srv < h->num_servers; srv++) {
1033 if (h->servers[srv].is_dead == 0)
1035 if (h->servers[srv].dead_time &&
1036 h->servers[srv].next_probe <= now) {
1037 h->servers[srv].is_dead = 0;
1043 /* If all servers was dead on the last probe, try from beginning */
1044 if (h->srv == h->num_servers) {
1045 for (srv = 0; srv < h->num_servers; srv++) {
1046 h->servers[srv].is_dead = 0;
1047 h->servers[srv].next_probe = 0;
1052 return rad_continue_send_request(h, 0, fd, tv);
1056 * Create and initialize a rad_handle structure, and return it to the
1057 * caller. Can fail only if the necessary memory cannot be allocated.
1058 * In that case, it returns NULL.
1063 struct rad_handle *h;
1065 h = (struct rad_handle *)malloc(sizeof(struct rad_handle));
1070 h->ident = random();
1071 h->errmsg[0] = '\0';
1072 memset(h->pass, 0, sizeof h->pass);
1076 h->authentic_pos = 0;
1077 h->type = RADIUS_AUTH;
1080 h->bindto = INADDR_ANY;
1088 struct rad_handle *h;
1092 h->type = RADIUS_ACCT;
1097 rad_server_open(int fd)
1099 struct rad_handle *h;
1103 h->type = RADIUS_SERVER;
1112 return rad_auth_open();
1116 rad_put_addr(struct rad_handle *h, int type, struct in_addr addr)
1118 return rad_put_attr(h, type, &addr.s_addr, sizeof addr.s_addr);
1122 rad_put_addr6(struct rad_handle *h, int type, struct in6_addr addr)
1125 return rad_put_attr(h, type, &addr.s6_addr, sizeof addr.s6_addr);
1129 rad_put_attr(struct rad_handle *h, int type, const void *value, size_t len)
1133 if (!h->out_created) {
1134 generr(h, "Please call rad_create_request()"
1135 " before putting attributes");
1139 if (h->out[POS_CODE] == RAD_ACCOUNTING_REQUEST) {
1140 if (type == RAD_EAP_MESSAGE) {
1141 generr(h, "EAP-Message attribute is not valid"
1142 " in accounting requests");
1148 * When proxying EAP Messages, the Message Authenticator
1149 * MUST be present; see RFC 3579.
1151 if (type == RAD_EAP_MESSAGE) {
1152 if (rad_put_message_authentic(h) == -1)
1156 if (type == RAD_USER_PASSWORD) {
1157 result = put_password_attr(h, type, value, len);
1158 } else if (type == RAD_MESSAGE_AUTHENTIC) {
1159 result = rad_put_message_authentic(h);
1161 result = put_raw_attr(h, type, value, len);
1163 if (type == RAD_CHAP_PASSWORD)
1165 else if (type == RAD_EAP_MESSAGE)
1174 rad_put_int(struct rad_handle *h, int type, u_int32_t value)
1178 nvalue = htonl(value);
1179 return rad_put_attr(h, type, &nvalue, sizeof nvalue);
1183 rad_put_string(struct rad_handle *h, int type, const char *str)
1185 return rad_put_attr(h, type, str, strlen(str));
1189 rad_put_message_authentic(struct rad_handle *h)
1192 u_char md_zero[MD5_DIGEST_LENGTH];
1194 if (h->out[POS_CODE] == RAD_ACCOUNTING_REQUEST) {
1195 generr(h, "Message-Authenticator is not valid"
1196 " in accounting requests");
1200 if (h->authentic_pos == 0) {
1201 h->authentic_pos = h->out_len;
1202 memset(md_zero, 0, sizeof(md_zero));
1203 return (put_raw_attr(h, RAD_MESSAGE_AUTHENTIC, md_zero,
1208 generr(h, "Message Authenticator not supported,"
1209 " please recompile libradius with SSL support");
1215 * Returns the response type code on success, or -1 on failure.
1218 rad_send_request(struct rad_handle *h)
1220 struct timeval timelimit;
1225 n = rad_init_send_request(h, &fd, &tv);
1230 gettimeofday(&timelimit, NULL);
1231 timeradd(&tv, &timelimit, &timelimit);
1237 FD_SET(fd, &readfds);
1239 n = select(fd + 1, &readfds, NULL, NULL, &tv);
1242 generr(h, "select: %s", strerror(errno));
1246 if (!FD_ISSET(fd, &readfds)) {
1247 /* Compute a new timeout */
1248 gettimeofday(&tv, NULL);
1249 timersub(&timelimit, &tv, &tv);
1250 if (tv.tv_sec > 0 || (tv.tv_sec == 0 && tv.tv_usec > 0))
1251 /* Continue the select */
1255 n = rad_continue_send_request(h, n, &fd, &tv);
1260 gettimeofday(&timelimit, NULL);
1261 timeradd(&tv, &timelimit, &timelimit);
1266 rad_strerror(struct rad_handle *h)
1272 * Destructively split a string into fields separated by white space.
1273 * `#' at the beginning of a field begins a comment that extends to the
1274 * end of the string. Fields may be quoted with `"'. Inside quoted
1275 * strings, the backslash escapes `\"' and `\\' are honored.
1277 * Pointers to up to the first maxfields fields are stored in the fields
1278 * array. Missing fields get NULL pointers.
1280 * The return value is the actual number of fields parsed, and is always
1283 * On a syntax error, places a message in the msg string, and returns -1.
1286 split(char *str, const char *fields[], int maxfields, char *msg, size_t msglen)
1290 static const char ws[] = " \t";
1292 for (i = 0; i < maxfields; i++)
1296 while (*p != '\0') {
1298 if (*p == '#' || *p == '\0')
1300 if (i >= maxfields) {
1301 snprintf(msg, msglen, "line has too many fields");
1312 if (*p != '"' && *p != '\\' &&
1314 snprintf(msg, msglen,
1315 "invalid `\\' escape");
1320 snprintf(msg, msglen,
1321 "unterminated quoted string");
1328 if (*fields[i] == '\0') {
1329 snprintf(msg, msglen,
1330 "empty quoted string not permitted");
1333 if (*p != '\0' && strspn(p, ws) == 0) {
1334 snprintf(msg, msglen, "quoted string not"
1335 " followed by white space");
1340 p += strcspn(p, ws);
1350 rad_get_vendor_attr(u_int32_t *vendor, const void **data, size_t *len)
1352 const struct vendor_attribute *attr;
1354 attr = (const struct vendor_attribute *)*data;
1355 *vendor = ntohl(attr->vendor_value);
1356 *data = attr->attrib_data;
1357 *len = attr->attrib_len - 2;
1359 return (attr->attrib_type);
1363 rad_put_vendor_addr(struct rad_handle *h, int vendor, int type,
1364 struct in_addr addr)
1366 return (rad_put_vendor_attr(h, vendor, type, &addr.s_addr,
1367 sizeof addr.s_addr));
1371 rad_put_vendor_addr6(struct rad_handle *h, int vendor, int type,
1372 struct in6_addr addr)
1375 return (rad_put_vendor_attr(h, vendor, type, &addr.s6_addr,
1376 sizeof addr.s6_addr));
1380 rad_put_vendor_attr(struct rad_handle *h, int vendor, int type,
1381 const void *value, size_t len)
1383 struct vendor_attribute *attr;
1386 if (!h->out_created) {
1387 generr(h, "Please call rad_create_request()"
1388 " before putting attributes");
1392 if ((attr = malloc(len + 6)) == NULL) {
1393 generr(h, "malloc failure (%zu bytes)", len + 6);
1397 attr->vendor_value = htonl(vendor);
1398 attr->attrib_type = type;
1399 attr->attrib_len = len + 2;
1400 memcpy(attr->attrib_data, value, len);
1402 res = put_raw_attr(h, RAD_VENDOR_SPECIFIC, attr, len + 6);
1404 if (res == 0 && vendor == RAD_VENDOR_MICROSOFT
1405 && (type == RAD_MICROSOFT_MS_CHAP_RESPONSE
1406 || type == RAD_MICROSOFT_MS_CHAP2_RESPONSE)) {
1413 rad_put_vendor_int(struct rad_handle *h, int vendor, int type, u_int32_t i)
1418 return (rad_put_vendor_attr(h, vendor, type, &value, sizeof value));
1422 rad_put_vendor_string(struct rad_handle *h, int vendor, int type,
1425 return (rad_put_vendor_attr(h, vendor, type, str, strlen(str)));
1429 rad_request_authenticator(struct rad_handle *h, char *buf, size_t len)
1433 memcpy(buf, h->out + POS_AUTH, LEN_AUTH);
1435 buf[LEN_AUTH] = '\0';
1440 rad_demangle(struct rad_handle *h, const void *mangled, size_t mlen)
1446 u_char b[MD5_DIGEST_LENGTH], *demangled;
1449 if ((mlen % 16 != 0) || mlen > 128) {
1450 generr(h, "Cannot interpret mangled data of length %lu",
1457 /* We need the shared secret as Salt */
1458 S = rad_server_secret(h);
1460 /* We need the request authenticator */
1461 if (rad_request_authenticator(h, R, sizeof R) != LEN_AUTH) {
1462 generr(h, "Cannot obtain the RADIUS request authenticator");
1466 demangled = malloc(mlen);
1471 MD5Update(&Context, S, strlen(S));
1472 MD5Update(&Context, R, LEN_AUTH);
1473 MD5Final(b, &Context);
1478 for (i = 0; i < 16; i++)
1479 demangled[Ppos++] = C[i] ^ b[i];
1483 MD5Update(&Context, S, strlen(S));
1484 MD5Update(&Context, C, 16);
1485 MD5Final(b, &Context);
1495 rad_demangle_mppe_key(struct rad_handle *h, const void *mangled,
1496 size_t mlen, size_t *len)
1498 char R[LEN_AUTH]; /* variable names as per rfc2548 */
1500 u_char b[MD5_DIGEST_LENGTH], *demangled;
1501 const u_char *A, *C;
1503 int Slen, i, Clen, Ppos;
1506 if (mlen % 16 != SALT_LEN) {
1507 generr(h, "Cannot interpret mangled data of length %lu",
1512 /* We need the RADIUS Request-Authenticator */
1513 if (rad_request_authenticator(h, R, sizeof R) != LEN_AUTH) {
1514 generr(h, "Cannot obtain the RADIUS request authenticator");
1518 A = (const u_char *)mangled; /* Salt comes first */
1519 C = (const u_char *)mangled + SALT_LEN; /* Then the ciphertext */
1520 Clen = mlen - SALT_LEN;
1521 S = rad_server_secret(h); /* We need the RADIUS secret */
1523 P = alloca(Clen); /* We derive our plaintext */
1526 MD5Update(&Context, S, Slen);
1527 MD5Update(&Context, R, LEN_AUTH);
1528 MD5Update(&Context, A, SALT_LEN);
1529 MD5Final(b, &Context);
1535 for (i = 0; i < 16; i++)
1536 P[Ppos++] = C[i] ^ b[i];
1540 MD5Update(&Context, S, Slen);
1541 MD5Update(&Context, C, 16);
1542 MD5Final(b, &Context);
1549 * The resulting plain text consists of a one-byte length, the text and
1550 * maybe some padding.
1553 if (*len > mlen - 1) {
1554 generr(h, "Mangled data seems to be garbage %zu %zu",
1559 if (*len > MPPE_KEY_LEN * 2) {
1560 generr(h, "Key to long (%zu) for me max. %d",
1561 *len, MPPE_KEY_LEN * 2);
1564 demangled = malloc(*len);
1568 memcpy(demangled, P + 1, *len);
1573 rad_server_secret(struct rad_handle *h)
1575 return (h->servers[h->srv].secret);