2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright 1998 Juniper Networks, Inc.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
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.
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
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
32 #include <sys/types.h>
33 #include <sys/socket.h>
35 #include <netinet/in.h>
36 #include <arpa/inet.h>
38 #include <openssl/hmac.h>
39 #include <openssl/md5.h>
40 #define MD5Init MD5_Init
41 #define MD5Update MD5_Update
42 #define MD5Final MD5_Final
44 #define MD5_DIGEST_LENGTH 16
50 /* We need the MPPE_KEY_LEN define */
51 #include <netgraph/ng_mppc.h>
62 #include "radlib_private.h"
64 static void clear_password(struct rad_handle *);
65 static void generr(struct rad_handle *, const char *, ...)
67 static void insert_scrambled_password(struct rad_handle *, int);
68 static void insert_request_authenticator(struct rad_handle *, int);
69 static void insert_message_authenticator(struct rad_handle *, int);
70 static int is_valid_response(struct rad_handle *, int,
71 const struct sockaddr_in *);
72 static int put_password_attr(struct rad_handle *, int,
73 const void *, size_t);
74 static int put_raw_attr(struct rad_handle *, int,
75 const void *, size_t);
76 static int split(char *, char *[], int, char *, size_t);
79 clear_password(struct rad_handle *h)
81 if (h->pass_len != 0) {
82 memset(h->pass, 0, h->pass_len);
89 generr(struct rad_handle *h, const char *format, ...)
94 vsnprintf(h->errmsg, ERRSIZE, format, ap);
99 insert_scrambled_password(struct rad_handle *h, int srv)
102 unsigned char md5[MD5_DIGEST_LENGTH];
103 const struct rad_server *srvp;
107 srvp = &h->servers[srv];
108 padded_len = h->pass_len == 0 ? 16 : (h->pass_len+15) & ~0xf;
110 memcpy(md5, &h->out[POS_AUTH], LEN_AUTH);
111 for (pos = 0; pos < padded_len; pos += 16) {
114 /* Calculate the new scrambler */
116 MD5Update(&ctx, srvp->secret, strlen(srvp->secret));
117 MD5Update(&ctx, md5, 16);
121 * Mix in the current chunk of the password, and copy
122 * the result into the right place in the request. Also
123 * modify the scrambler in place, since we will use this
124 * in calculating the scrambler for next time.
126 for (i = 0; i < 16; i++)
127 h->out[h->pass_pos + pos + i] =
128 md5[i] ^= h->pass[pos + i];
133 insert_request_authenticator(struct rad_handle *h, int resp)
136 const struct rad_server *srvp;
138 srvp = &h->servers[h->srv];
140 /* Create the request authenticator */
142 MD5Update(&ctx, &h->out[POS_CODE], POS_AUTH - POS_CODE);
144 MD5Update(&ctx, &h->in[POS_AUTH], LEN_AUTH);
146 MD5Update(&ctx, &h->out[POS_AUTH], LEN_AUTH);
147 MD5Update(&ctx, &h->out[POS_ATTRS], h->out_len - POS_ATTRS);
148 MD5Update(&ctx, srvp->secret, strlen(srvp->secret));
149 MD5Final(&h->out[POS_AUTH], &ctx);
153 insert_message_authenticator(struct rad_handle *h, int resp)
156 u_char md[EVP_MAX_MD_SIZE];
158 const struct rad_server *srvp;
160 srvp = &h->servers[h->srv];
162 if (h->authentic_pos != 0) {
164 HMAC_Init(&ctx, srvp->secret, strlen(srvp->secret), EVP_md5());
165 HMAC_Update(&ctx, &h->out[POS_CODE], POS_AUTH - POS_CODE);
167 HMAC_Update(&ctx, &h->in[POS_AUTH], LEN_AUTH);
169 HMAC_Update(&ctx, &h->out[POS_AUTH], LEN_AUTH);
170 HMAC_Update(&ctx, &h->out[POS_ATTRS],
171 h->out_len - POS_ATTRS);
172 HMAC_Final(&ctx, md, &md_len);
173 HMAC_CTX_cleanup(&ctx);
175 memcpy(&h->out[h->authentic_pos + 2], md, md_len);
181 * Return true if the current response is valid for a request to the
185 is_valid_response(struct rad_handle *h, int srv,
186 const struct sockaddr_in *from)
189 unsigned char md5[MD5_DIGEST_LENGTH];
190 const struct rad_server *srvp;
194 u_char resp[MSGSIZE], md[EVP_MAX_MD_SIZE];
199 srvp = &h->servers[srv];
201 /* Check the source address */
202 if (from->sin_family != srvp->addr.sin_family ||
203 from->sin_addr.s_addr != srvp->addr.sin_addr.s_addr ||
204 from->sin_port != srvp->addr.sin_port)
207 /* Check the message length */
208 if (h->in_len < POS_ATTRS)
210 len = h->in[POS_LENGTH] << 8 | h->in[POS_LENGTH+1];
214 /* Check the response authenticator */
216 MD5Update(&ctx, &h->in[POS_CODE], POS_AUTH - POS_CODE);
217 MD5Update(&ctx, &h->out[POS_AUTH], LEN_AUTH);
218 MD5Update(&ctx, &h->in[POS_ATTRS], len - POS_ATTRS);
219 MD5Update(&ctx, srvp->secret, strlen(srvp->secret));
221 if (memcmp(&h->in[POS_AUTH], md5, sizeof md5) != 0)
226 * For non accounting responses check the message authenticator,
229 if (h->in[POS_CODE] != RAD_ACCOUNTING_RESPONSE) {
231 memcpy(resp, h->in, MSGSIZE);
234 /* Search and verify the Message-Authenticator */
235 while (pos < len - 2) {
237 if (h->in[pos] == RAD_MESSAGE_AUTHENTIC) {
238 /* zero fill the Message-Authenticator */
239 memset(&resp[pos + 2], 0, MD5_DIGEST_LENGTH);
241 HMAC_CTX_init(&hctx);
242 HMAC_Init(&hctx, srvp->secret,
243 strlen(srvp->secret), EVP_md5());
244 HMAC_Update(&hctx, &h->in[POS_CODE],
245 POS_AUTH - POS_CODE);
246 HMAC_Update(&hctx, &h->out[POS_AUTH],
248 HMAC_Update(&hctx, &resp[POS_ATTRS],
249 h->in_len - POS_ATTRS);
250 HMAC_Final(&hctx, md, &md_len);
251 HMAC_CTX_cleanup(&hctx);
253 if (memcmp(md, &h->in[pos + 2],
254 MD5_DIGEST_LENGTH) != 0)
258 pos += h->in[pos + 1];
266 * Return true if the current request is valid for the specified server.
269 is_valid_request(struct rad_handle *h)
272 unsigned char md5[MD5_DIGEST_LENGTH];
273 const struct rad_server *srvp;
277 u_char resp[MSGSIZE], md[EVP_MAX_MD_SIZE];
282 srvp = &h->servers[h->srv];
284 /* Check the message length */
285 if (h->in_len < POS_ATTRS)
287 len = h->in[POS_LENGTH] << 8 | h->in[POS_LENGTH+1];
291 if (h->in[POS_CODE] != RAD_ACCESS_REQUEST) {
292 uint32_t zeroes[4] = { 0, 0, 0, 0 };
293 /* Check the request authenticator */
295 MD5Update(&ctx, &h->in[POS_CODE], POS_AUTH - POS_CODE);
296 MD5Update(&ctx, zeroes, LEN_AUTH);
297 MD5Update(&ctx, &h->in[POS_ATTRS], len - POS_ATTRS);
298 MD5Update(&ctx, srvp->secret, strlen(srvp->secret));
300 if (memcmp(&h->in[POS_AUTH], md5, sizeof md5) != 0)
305 /* Search and verify the Message-Authenticator */
307 while (pos < len - 2) {
308 if (h->in[pos] == RAD_MESSAGE_AUTHENTIC) {
309 memcpy(resp, h->in, MSGSIZE);
310 /* zero fill the Request-Authenticator */
311 if (h->in[POS_CODE] != RAD_ACCESS_REQUEST)
312 memset(&resp[POS_AUTH], 0, LEN_AUTH);
313 /* zero fill the Message-Authenticator */
314 memset(&resp[pos + 2], 0, MD5_DIGEST_LENGTH);
316 HMAC_CTX_init(&hctx);
317 HMAC_Init(&hctx, srvp->secret,
318 strlen(srvp->secret), EVP_md5());
319 HMAC_Update(&hctx, resp, h->in_len);
320 HMAC_Final(&hctx, md, &md_len);
321 HMAC_CTX_cleanup(&hctx);
323 if (memcmp(md, &h->in[pos + 2],
324 MD5_DIGEST_LENGTH) != 0)
328 pos += h->in[pos + 1];
335 put_password_attr(struct rad_handle *h, int type, const void *value, size_t len)
340 if (h->pass_pos != 0) {
341 generr(h, "Multiple User-Password attributes specified");
346 padded_len = len == 0 ? 16 : (len+15) & ~0xf;
347 pad_len = padded_len - len;
350 * Put in a place-holder attribute containing all zeros, and
351 * remember where it is so we can fill it in later.
354 put_raw_attr(h, type, h->pass, padded_len);
355 h->pass_pos = h->out_len - padded_len;
357 /* Save the cleartext password, padded as necessary */
358 memcpy(h->pass, value, len);
360 memset(h->pass + len, 0, pad_len);
365 put_raw_attr(struct rad_handle *h, int type, const void *value, size_t len)
368 generr(h, "Attribute too long");
371 if (h->out_len + 2 + len > MSGSIZE) {
372 generr(h, "Maximum message length exceeded");
375 h->out[h->out_len++] = type;
376 h->out[h->out_len++] = len + 2;
377 memcpy(&h->out[h->out_len], value, len);
383 rad_add_server(struct rad_handle *h, const char *host, int port,
384 const char *secret, int timeout, int tries)
386 struct in_addr bindto;
387 bindto.s_addr = INADDR_ANY;
389 return rad_add_server_ex(h, host, port, secret, timeout, tries,
394 rad_add_server_ex(struct rad_handle *h, const char *host, int port,
395 const char *secret, int timeout, int tries, int dead_time,
396 struct in_addr *bindto)
398 struct rad_server *srvp;
400 if (h->num_servers >= MAXSERVERS) {
401 generr(h, "Too many RADIUS servers specified");
404 srvp = &h->servers[h->num_servers];
406 memset(&srvp->addr, 0, sizeof srvp->addr);
407 srvp->addr.sin_len = sizeof srvp->addr;
408 srvp->addr.sin_family = AF_INET;
409 if (!inet_aton(host, &srvp->addr.sin_addr)) {
410 struct hostent *hent;
412 if ((hent = gethostbyname(host)) == NULL) {
413 generr(h, "%s: host not found", host);
416 memcpy(&srvp->addr.sin_addr, hent->h_addr,
417 sizeof srvp->addr.sin_addr);
420 srvp->addr.sin_port = htons((u_short)port);
422 struct servent *sent;
424 if (h->type == RADIUS_AUTH)
425 srvp->addr.sin_port =
426 (sent = getservbyname("radius", "udp")) != NULL ?
427 sent->s_port : htons(RADIUS_PORT);
429 srvp->addr.sin_port =
430 (sent = getservbyname("radacct", "udp")) != NULL ?
431 sent->s_port : htons(RADACCT_PORT);
433 if ((srvp->secret = strdup(secret)) == NULL) {
434 generr(h, "Out of memory");
437 srvp->timeout = timeout;
438 srvp->max_tries = tries;
441 srvp->dead_time = dead_time;
442 srvp->next_probe = 0;
443 srvp->bindto = bindto->s_addr;
449 rad_close(struct rad_handle *h)
455 for (srv = 0; srv < h->num_servers; srv++) {
456 memset(h->servers[srv].secret, 0,
457 strlen(h->servers[srv].secret));
458 free(h->servers[srv].secret);
465 rad_bind_to(struct rad_handle *h, in_addr_t addr)
472 rad_config(struct rad_handle *h, const char *path)
475 char buf[MAXCONFLINE];
480 path = PATH_RADIUS_CONF;
481 if ((fp = fopen(path, "r")) == NULL) {
482 generr(h, "Cannot open \"%s\": %s", path, strerror(errno));
487 while (fgets(buf, sizeof buf, fp) != NULL) {
489 char *fields[MAX_FIELDS];
502 unsigned long timeout;
503 unsigned long maxtries;
504 unsigned long dead_time;
506 struct in_addr bindto;
511 /* We know len > 0, else fgets would have returned NULL. */
512 if (buf[len - 1] != '\n') {
513 if (len == sizeof buf - 1)
514 generr(h, "%s:%d: line too long", path,
517 generr(h, "%s:%d: missing newline", path,
524 /* Extract the fields from the line. */
525 nfields = split(buf, fields, MAX_FIELDS, msg, sizeof msg);
527 generr(h, "%s:%d: %s", path, linenum, msg);
534 * The first field should contain "auth" or "acct" for
535 * authentication or accounting, respectively. But older
536 * versions of the file didn't have that field. Default
537 * it to "auth" for backward compatibility.
539 if (strcmp(fields[0], "auth") != 0 &&
540 strcmp(fields[0], "acct") != 0) {
541 if (nfields >= MAX_FIELDS) {
542 generr(h, "%s:%d: invalid service type", path,
548 for (i = nfields; --i > 0; )
549 fields[i] = fields[i - 1];
553 generr(h, "%s:%d: missing shared secret", path,
561 timeout_str = fields[3];
562 maxtries_str = fields[4];
563 dead_time_str = fields[5];
564 bindto_str = fields[6];
566 /* Ignore the line if it is for the wrong service type. */
567 wanttype = h->type == RADIUS_AUTH ? "auth" : "acct";
568 if (strcmp(type, wanttype) != 0)
571 /* Parse and validate the fields. */
573 host = strsep(&res, ":");
574 port_str = strsep(&res, ":");
575 if (port_str != NULL) {
576 port = strtoul(port_str, &end, 10);
578 generr(h, "%s:%d: invalid port", path,
585 if (timeout_str != NULL) {
586 timeout = strtoul(timeout_str, &end, 10);
588 generr(h, "%s:%d: invalid timeout", path,
595 if (maxtries_str != NULL) {
596 maxtries = strtoul(maxtries_str, &end, 10);
598 generr(h, "%s:%d: invalid maxtries", path,
606 if (dead_time_str != NULL) {
607 dead_time = strtoul(dead_time_str, &end, 10);
609 generr(h, "%s:%d: invalid dead_time", path,
615 dead_time = DEAD_TIME;
617 if (bindto_str != NULL) {
618 bindto.s_addr = inet_addr(bindto_str);
619 if (bindto.s_addr == INADDR_NONE) {
620 generr(h, "%s:%d: invalid bindto", path,
626 bindto.s_addr = INADDR_ANY;
628 if (rad_add_server_ex(h, host, port, secret, timeout, maxtries,
629 dead_time, &bindto) == -1) {
630 strcpy(msg, h->errmsg);
631 generr(h, "%s:%d: %s", path, linenum, msg);
636 /* Clear out the buffer to wipe a possible copy of a shared secret */
637 memset(buf, 0, sizeof buf);
643 * rad_init_send_request() must have previously been called.
645 * 0 The application should select on *fd with a timeout of tv before
646 * calling rad_continue_send_request again.
651 rad_continue_send_request(struct rad_handle *h, int selected, int *fd,
656 struct sockaddr_in sin;
658 if (h->type == RADIUS_SERVER) {
659 generr(h, "denied function call");
663 struct sockaddr_in from;
666 fromlen = sizeof from;
667 h->in_len = recvfrom(h->fd, h->in,
668 MSGSIZE, MSG_WAITALL, (struct sockaddr *)&from, &fromlen);
669 if (h->in_len == -1) {
670 generr(h, "recvfrom: %s", strerror(errno));
673 if (is_valid_response(h, h->srv, &from)) {
674 h->in_len = h->in[POS_LENGTH] << 8 |
676 h->in_pos = POS_ATTRS;
677 return h->in[POS_CODE];
682 * Scan round-robin to the next server that has some
683 * tries left. There is guaranteed to be one, or we
684 * would have exited this loop by now.
688 if (h->servers[h->srv].num_tries >= h->servers[h->srv].max_tries) {
689 /* Set next probe time for this server */
690 if (h->servers[h->srv].dead_time) {
691 h->servers[h->srv].is_dead = 1;
692 h->servers[h->srv].next_probe = now +
693 h->servers[h->srv].dead_time;
697 if (h->srv >= h->num_servers)
699 if (h->servers[h->srv].is_dead == 0)
701 if (h->servers[h->srv].dead_time &&
702 h->servers[h->srv].next_probe <= now) {
703 h->servers[h->srv].is_dead = 0;
704 h->servers[h->srv].num_tries = 0;
707 } while (h->srv != cur_srv);
709 if (h->srv == cur_srv) {
710 generr(h, "No valid RADIUS responses received");
716 if (h->bindto != h->servers[h->srv].bindto) {
717 h->bindto = h->servers[h->srv].bindto;
719 if ((h->fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
720 generr(h, "Cannot create socket: %s", strerror(errno));
723 memset(&sin, 0, sizeof sin);
724 sin.sin_len = sizeof sin;
725 sin.sin_family = AF_INET;
726 sin.sin_addr.s_addr = h->bindto;
728 if (bind(h->fd, (const struct sockaddr *)&sin,
730 generr(h, "bind: %s", strerror(errno));
737 if (h->out[POS_CODE] == RAD_ACCESS_REQUEST) {
738 /* Insert the scrambled password into the request */
739 if (h->pass_pos != 0)
740 insert_scrambled_password(h, h->srv);
742 insert_message_authenticator(h, 0);
744 if (h->out[POS_CODE] != RAD_ACCESS_REQUEST) {
745 /* Insert the request authenticator into the request */
746 memset(&h->out[POS_AUTH], 0, LEN_AUTH);
747 insert_request_authenticator(h, 0);
750 /* Send the request */
751 n = sendto(h->fd, h->out, h->out_len, 0,
752 (const struct sockaddr *)&h->servers[h->srv].addr,
753 sizeof h->servers[h->srv].addr);
755 tv->tv_sec = 1; /* Do not wait full timeout if send failed. */
757 tv->tv_sec = h->servers[h->srv].timeout;
758 h->servers[h->srv].num_tries++;
766 rad_receive_request(struct rad_handle *h)
768 struct sockaddr_in from;
772 if (h->type != RADIUS_SERVER) {
773 generr(h, "denied function call");
777 fromlen = sizeof(from);
778 h->in_len = recvfrom(h->fd, h->in,
779 MSGSIZE, MSG_WAITALL, (struct sockaddr *)&from, &fromlen);
780 if (h->in_len == -1) {
781 generr(h, "recvfrom: %s", strerror(errno));
784 for (n = 0; n < h->num_servers; n++) {
785 if (h->servers[n].addr.sin_addr.s_addr == from.sin_addr.s_addr) {
786 h->servers[n].addr.sin_port = from.sin_port;
793 if (is_valid_request(h)) {
794 h->in_len = h->in[POS_LENGTH] << 8 |
796 h->in_pos = POS_ATTRS;
797 return (h->in[POS_CODE]);
803 rad_send_response(struct rad_handle *h)
807 if (h->type != RADIUS_SERVER) {
808 generr(h, "denied function call");
811 /* Fill in the length field in the message */
812 h->out[POS_LENGTH] = h->out_len >> 8;
813 h->out[POS_LENGTH+1] = h->out_len;
815 insert_message_authenticator(h,
816 (h->in[POS_CODE] == RAD_ACCESS_REQUEST) ? 1 : 0);
817 insert_request_authenticator(h, 1);
819 /* Send the request */
820 n = sendto(h->fd, h->out, h->out_len, 0,
821 (const struct sockaddr *)&h->servers[h->srv].addr,
822 sizeof h->servers[h->srv].addr);
823 if (n != h->out_len) {
825 generr(h, "sendto: %s", strerror(errno));
827 generr(h, "sendto: short write");
835 rad_create_request(struct rad_handle *h, int code)
839 if (h->type == RADIUS_SERVER) {
840 generr(h, "denied function call");
843 if (h->num_servers == 0) {
844 generr(h, "No RADIUS servers specified");
847 h->out[POS_CODE] = code;
848 h->out[POS_IDENT] = ++h->ident;
849 if (code == RAD_ACCESS_REQUEST) {
850 /* Create a random authenticator */
851 for (i = 0; i < LEN_AUTH; i += 2) {
854 h->out[POS_AUTH+i] = (u_char)r;
855 h->out[POS_AUTH+i+1] = (u_char)(r >> 8);
858 memset(&h->out[POS_AUTH], 0, LEN_AUTH);
859 h->out_len = POS_ATTRS;
861 h->authentic_pos = 0;
867 rad_create_response(struct rad_handle *h, int code)
870 if (h->type != RADIUS_SERVER) {
871 generr(h, "denied function call");
874 h->out[POS_CODE] = code;
875 h->out[POS_IDENT] = h->in[POS_IDENT];
876 memset(&h->out[POS_AUTH], 0, LEN_AUTH);
877 h->out_len = POS_ATTRS;
879 h->authentic_pos = 0;
885 rad_cvt_addr(const void *data)
887 struct in_addr value;
889 memcpy(&value.s_addr, data, sizeof value.s_addr);
894 rad_cvt_addr6(const void *data)
896 struct in6_addr value;
898 memcpy(&value.s6_addr, data, sizeof value.s6_addr);
903 rad_cvt_int(const void *data)
907 memcpy(&value, data, sizeof value);
912 rad_cvt_string(const void *data, size_t len)
918 memcpy(s, data, len);
925 * Returns the attribute type. If none are left, returns 0. On failure,
929 rad_get_attr(struct rad_handle *h, const void **value, size_t *len)
933 if (h->in_pos >= h->in_len)
935 if (h->in_pos + 2 > h->in_len) {
936 generr(h, "Malformed attribute in response");
939 type = h->in[h->in_pos++];
940 *len = h->in[h->in_pos++] - 2;
941 if (h->in_pos + (int)*len > h->in_len) {
942 generr(h, "Malformed attribute in response");
945 *value = &h->in[h->in_pos];
951 * Returns -1 on error, 0 to indicate no event and >0 for success
954 rad_init_send_request(struct rad_handle *h, int *fd, struct timeval *tv)
958 struct sockaddr_in sin;
960 if (h->type == RADIUS_SERVER) {
961 generr(h, "denied function call");
964 /* Make sure we have a socket to use */
966 if ((h->fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
967 generr(h, "Cannot create socket: %s", strerror(errno));
970 memset(&sin, 0, sizeof sin);
971 sin.sin_len = sizeof sin;
972 sin.sin_family = AF_INET;
973 sin.sin_addr.s_addr = h->bindto;
974 sin.sin_port = htons(0);
975 if (bind(h->fd, (const struct sockaddr *)&sin,
977 generr(h, "bind: %s", strerror(errno));
984 if (h->out[POS_CODE] != RAD_ACCESS_REQUEST) {
985 /* Make sure no password given */
986 if (h->pass_pos || h->chap_pass) {
987 generr(h, "User or Chap Password"
988 " in accounting request");
992 if (h->eap_msg == 0) {
993 /* Make sure the user gave us a password */
994 if (h->pass_pos == 0 && !h->chap_pass) {
995 generr(h, "No User or Chap Password"
996 " attributes given");
999 if (h->pass_pos != 0 && h->chap_pass) {
1000 generr(h, "Both User and Chap Password"
1001 " attributes given");
1007 /* Fill in the length field in the message */
1008 h->out[POS_LENGTH] = h->out_len >> 8;
1009 h->out[POS_LENGTH+1] = h->out_len;
1013 for (srv = 0; srv < h->num_servers; srv++)
1014 h->servers[srv].num_tries = 0;
1015 /* Find a first good server. */
1016 for (srv = 0; srv < h->num_servers; srv++) {
1017 if (h->servers[srv].is_dead == 0)
1019 if (h->servers[srv].dead_time &&
1020 h->servers[srv].next_probe <= now) {
1021 h->servers[srv].is_dead = 0;
1027 /* If all servers was dead on the last probe, try from beginning */
1028 if (h->srv == h->num_servers) {
1029 for (srv = 0; srv < h->num_servers; srv++) {
1030 h->servers[srv].is_dead = 0;
1031 h->servers[srv].next_probe = 0;
1036 return rad_continue_send_request(h, 0, fd, tv);
1040 * Create and initialize a rad_handle structure, and return it to the
1041 * caller. Can fail only if the necessary memory cannot be allocated.
1042 * In that case, it returns NULL.
1047 struct rad_handle *h;
1049 h = (struct rad_handle *)malloc(sizeof(struct rad_handle));
1054 h->ident = random();
1055 h->errmsg[0] = '\0';
1056 memset(h->pass, 0, sizeof h->pass);
1060 h->authentic_pos = 0;
1061 h->type = RADIUS_AUTH;
1064 h->bindto = INADDR_ANY;
1072 struct rad_handle *h;
1076 h->type = RADIUS_ACCT;
1081 rad_server_open(int fd)
1083 struct rad_handle *h;
1087 h->type = RADIUS_SERVER;
1096 return rad_auth_open();
1100 rad_put_addr(struct rad_handle *h, int type, struct in_addr addr)
1102 return rad_put_attr(h, type, &addr.s_addr, sizeof addr.s_addr);
1106 rad_put_addr6(struct rad_handle *h, int type, struct in6_addr addr)
1109 return rad_put_attr(h, type, &addr.s6_addr, sizeof addr.s6_addr);
1113 rad_put_attr(struct rad_handle *h, int type, const void *value, size_t len)
1117 if (!h->out_created) {
1118 generr(h, "Please call rad_create_request()"
1119 " before putting attributes");
1123 if (h->out[POS_CODE] == RAD_ACCOUNTING_REQUEST) {
1124 if (type == RAD_EAP_MESSAGE) {
1125 generr(h, "EAP-Message attribute is not valid"
1126 " in accounting requests");
1132 * When proxying EAP Messages, the Message Authenticator
1133 * MUST be present; see RFC 3579.
1135 if (type == RAD_EAP_MESSAGE) {
1136 if (rad_put_message_authentic(h) == -1)
1140 if (type == RAD_USER_PASSWORD) {
1141 result = put_password_attr(h, type, value, len);
1142 } else if (type == RAD_MESSAGE_AUTHENTIC) {
1143 result = rad_put_message_authentic(h);
1145 result = put_raw_attr(h, type, value, len);
1147 if (type == RAD_CHAP_PASSWORD)
1149 else if (type == RAD_EAP_MESSAGE)
1158 rad_put_int(struct rad_handle *h, int type, u_int32_t value)
1162 nvalue = htonl(value);
1163 return rad_put_attr(h, type, &nvalue, sizeof nvalue);
1167 rad_put_string(struct rad_handle *h, int type, const char *str)
1169 return rad_put_attr(h, type, str, strlen(str));
1173 rad_put_message_authentic(struct rad_handle *h)
1176 u_char md_zero[MD5_DIGEST_LENGTH];
1178 if (h->out[POS_CODE] == RAD_ACCOUNTING_REQUEST) {
1179 generr(h, "Message-Authenticator is not valid"
1180 " in accounting requests");
1184 if (h->authentic_pos == 0) {
1185 h->authentic_pos = h->out_len;
1186 memset(md_zero, 0, sizeof(md_zero));
1187 return (put_raw_attr(h, RAD_MESSAGE_AUTHENTIC, md_zero,
1192 generr(h, "Message Authenticator not supported,"
1193 " please recompile libradius with SSL support");
1199 * Returns the response type code on success, or -1 on failure.
1202 rad_send_request(struct rad_handle *h)
1204 struct timeval timelimit;
1209 n = rad_init_send_request(h, &fd, &tv);
1214 gettimeofday(&timelimit, NULL);
1215 timeradd(&tv, &timelimit, &timelimit);
1221 FD_SET(fd, &readfds);
1223 n = select(fd + 1, &readfds, NULL, NULL, &tv);
1226 generr(h, "select: %s", strerror(errno));
1230 if (!FD_ISSET(fd, &readfds)) {
1231 /* Compute a new timeout */
1232 gettimeofday(&tv, NULL);
1233 timersub(&timelimit, &tv, &tv);
1234 if (tv.tv_sec > 0 || (tv.tv_sec == 0 && tv.tv_usec > 0))
1235 /* Continue the select */
1239 n = rad_continue_send_request(h, n, &fd, &tv);
1244 gettimeofday(&timelimit, NULL);
1245 timeradd(&tv, &timelimit, &timelimit);
1250 rad_strerror(struct rad_handle *h)
1256 * Destructively split a string into fields separated by white space.
1257 * `#' at the beginning of a field begins a comment that extends to the
1258 * end of the string. Fields may be quoted with `"'. Inside quoted
1259 * strings, the backslash escapes `\"' and `\\' are honored.
1261 * Pointers to up to the first maxfields fields are stored in the fields
1262 * array. Missing fields get NULL pointers.
1264 * The return value is the actual number of fields parsed, and is always
1267 * On a syntax error, places a message in the msg string, and returns -1.
1270 split(char *str, char *fields[], int maxfields, char *msg, size_t msglen)
1274 static const char ws[] = " \t";
1276 for (i = 0; i < maxfields; i++)
1280 while (*p != '\0') {
1282 if (*p == '#' || *p == '\0')
1284 if (i >= maxfields) {
1285 snprintf(msg, msglen, "line has too many fields");
1296 if (*p != '"' && *p != '\\' &&
1298 snprintf(msg, msglen,
1299 "invalid `\\' escape");
1304 snprintf(msg, msglen,
1305 "unterminated quoted string");
1312 if (*fields[i] == '\0') {
1313 snprintf(msg, msglen,
1314 "empty quoted string not permitted");
1317 if (*p != '\0' && strspn(p, ws) == 0) {
1318 snprintf(msg, msglen, "quoted string not"
1319 " followed by white space");
1324 p += strcspn(p, ws);
1334 rad_get_vendor_attr(u_int32_t *vendor, const void **data, size_t *len)
1336 struct vendor_attribute *attr;
1338 attr = (struct vendor_attribute *)*data;
1339 *vendor = ntohl(attr->vendor_value);
1340 *data = attr->attrib_data;
1341 *len = attr->attrib_len - 2;
1343 return (attr->attrib_type);
1347 rad_put_vendor_addr(struct rad_handle *h, int vendor, int type,
1348 struct in_addr addr)
1350 return (rad_put_vendor_attr(h, vendor, type, &addr.s_addr,
1351 sizeof addr.s_addr));
1355 rad_put_vendor_addr6(struct rad_handle *h, int vendor, int type,
1356 struct in6_addr addr)
1359 return (rad_put_vendor_attr(h, vendor, type, &addr.s6_addr,
1360 sizeof addr.s6_addr));
1364 rad_put_vendor_attr(struct rad_handle *h, int vendor, int type,
1365 const void *value, size_t len)
1367 struct vendor_attribute *attr;
1370 if (!h->out_created) {
1371 generr(h, "Please call rad_create_request()"
1372 " before putting attributes");
1376 if ((attr = malloc(len + 6)) == NULL) {
1377 generr(h, "malloc failure (%zu bytes)", len + 6);
1381 attr->vendor_value = htonl(vendor);
1382 attr->attrib_type = type;
1383 attr->attrib_len = len + 2;
1384 memcpy(attr->attrib_data, value, len);
1386 res = put_raw_attr(h, RAD_VENDOR_SPECIFIC, attr, len + 6);
1388 if (res == 0 && vendor == RAD_VENDOR_MICROSOFT
1389 && (type == RAD_MICROSOFT_MS_CHAP_RESPONSE
1390 || type == RAD_MICROSOFT_MS_CHAP2_RESPONSE)) {
1397 rad_put_vendor_int(struct rad_handle *h, int vendor, int type, u_int32_t i)
1402 return (rad_put_vendor_attr(h, vendor, type, &value, sizeof value));
1406 rad_put_vendor_string(struct rad_handle *h, int vendor, int type,
1409 return (rad_put_vendor_attr(h, vendor, type, str, strlen(str)));
1413 rad_request_authenticator(struct rad_handle *h, char *buf, size_t len)
1417 memcpy(buf, h->out + POS_AUTH, LEN_AUTH);
1419 buf[LEN_AUTH] = '\0';
1424 rad_demangle(struct rad_handle *h, const void *mangled, size_t mlen)
1430 u_char b[MD5_DIGEST_LENGTH], *C, *demangled;
1432 if ((mlen % 16 != 0) || mlen > 128) {
1433 generr(h, "Cannot interpret mangled data of length %lu",
1438 C = (u_char *)mangled;
1440 /* We need the shared secret as Salt */
1441 S = rad_server_secret(h);
1443 /* We need the request authenticator */
1444 if (rad_request_authenticator(h, R, sizeof R) != LEN_AUTH) {
1445 generr(h, "Cannot obtain the RADIUS request authenticator");
1449 demangled = malloc(mlen);
1454 MD5Update(&Context, S, strlen(S));
1455 MD5Update(&Context, R, LEN_AUTH);
1456 MD5Final(b, &Context);
1461 for (i = 0; i < 16; i++)
1462 demangled[Ppos++] = C[i] ^ b[i];
1466 MD5Update(&Context, S, strlen(S));
1467 MD5Update(&Context, C, 16);
1468 MD5Final(b, &Context);
1478 rad_demangle_mppe_key(struct rad_handle *h, const void *mangled,
1479 size_t mlen, size_t *len)
1481 char R[LEN_AUTH]; /* variable names as per rfc2548 */
1483 u_char b[MD5_DIGEST_LENGTH], *demangled;
1484 const u_char *A, *C;
1486 int Slen, i, Clen, Ppos;
1489 if (mlen % 16 != SALT_LEN) {
1490 generr(h, "Cannot interpret mangled data of length %lu",
1495 /* We need the RADIUS Request-Authenticator */
1496 if (rad_request_authenticator(h, R, sizeof R) != LEN_AUTH) {
1497 generr(h, "Cannot obtain the RADIUS request authenticator");
1501 A = (const u_char *)mangled; /* Salt comes first */
1502 C = (const u_char *)mangled + SALT_LEN; /* Then the ciphertext */
1503 Clen = mlen - SALT_LEN;
1504 S = rad_server_secret(h); /* We need the RADIUS secret */
1506 P = alloca(Clen); /* We derive our plaintext */
1509 MD5Update(&Context, S, Slen);
1510 MD5Update(&Context, R, LEN_AUTH);
1511 MD5Update(&Context, A, SALT_LEN);
1512 MD5Final(b, &Context);
1518 for (i = 0; i < 16; i++)
1519 P[Ppos++] = C[i] ^ b[i];
1523 MD5Update(&Context, S, Slen);
1524 MD5Update(&Context, C, 16);
1525 MD5Final(b, &Context);
1532 * The resulting plain text consists of a one-byte length, the text and
1533 * maybe some padding.
1536 if (*len > mlen - 1) {
1537 generr(h, "Mangled data seems to be garbage %zu %zu",
1542 if (*len > MPPE_KEY_LEN * 2) {
1543 generr(h, "Key to long (%zu) for me max. %d",
1544 *len, MPPE_KEY_LEN * 2);
1547 demangled = malloc(*len);
1551 memcpy(demangled, P + 1, *len);
1556 rad_server_secret(struct rad_handle *h)
1558 return (h->servers[h->srv].secret);