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 explicit_bzero(h->pass, 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) {
163 ctx = HMAC_CTX_new();
164 HMAC_Init_ex(ctx, srvp->secret, strlen(srvp->secret), EVP_md5(), NULL);
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);
174 memcpy(&h->out[h->authentic_pos + 2], md, md_len);
180 * Return true if the current response is valid for a request to the
184 is_valid_response(struct rad_handle *h, int srv,
185 const struct sockaddr_in *from)
188 unsigned char md5[MD5_DIGEST_LENGTH];
189 const struct rad_server *srvp;
193 u_char resp[MSGSIZE], md[EVP_MAX_MD_SIZE];
198 srvp = &h->servers[srv];
200 /* Check the source address */
201 if (from->sin_family != srvp->addr.sin_family ||
202 from->sin_addr.s_addr != srvp->addr.sin_addr.s_addr ||
203 from->sin_port != srvp->addr.sin_port)
206 /* Check the message length */
207 if (h->in_len < POS_ATTRS)
209 len = h->in[POS_LENGTH] << 8 | h->in[POS_LENGTH+1];
213 /* Check the response authenticator */
215 MD5Update(&ctx, &h->in[POS_CODE], POS_AUTH - POS_CODE);
216 MD5Update(&ctx, &h->out[POS_AUTH], LEN_AUTH);
217 MD5Update(&ctx, &h->in[POS_ATTRS], len - POS_ATTRS);
218 MD5Update(&ctx, srvp->secret, strlen(srvp->secret));
220 if (memcmp(&h->in[POS_AUTH], md5, sizeof md5) != 0)
225 * For non accounting responses check the message authenticator,
228 if (h->in[POS_CODE] != RAD_ACCOUNTING_RESPONSE) {
230 memcpy(resp, h->in, MSGSIZE);
233 /* Search and verify the Message-Authenticator */
234 hctx = HMAC_CTX_new();
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_Init_ex(hctx, srvp->secret,
242 strlen(srvp->secret), EVP_md5(), NULL);
243 HMAC_Update(hctx, &h->in[POS_CODE],
244 POS_AUTH - POS_CODE);
245 HMAC_Update(hctx, &h->out[POS_AUTH],
247 HMAC_Update(hctx, &resp[POS_ATTRS],
248 h->in_len - POS_ATTRS);
249 HMAC_Final(hctx, md, &md_len);
250 HMAC_CTX_reset(hctx);
251 if (memcmp(md, &h->in[pos + 2],
252 MD5_DIGEST_LENGTH) != 0) {
258 pos += h->in[pos + 1];
267 * Return true if the current request is valid for the specified server.
270 is_valid_request(struct rad_handle *h)
273 unsigned char md5[MD5_DIGEST_LENGTH];
274 const struct rad_server *srvp;
278 u_char resp[MSGSIZE], md[EVP_MAX_MD_SIZE];
283 srvp = &h->servers[h->srv];
285 /* Check the message length */
286 if (h->in_len < POS_ATTRS)
288 len = h->in[POS_LENGTH] << 8 | h->in[POS_LENGTH+1];
292 if (h->in[POS_CODE] != RAD_ACCESS_REQUEST) {
293 uint32_t zeroes[4] = { 0, 0, 0, 0 };
294 /* Check the request authenticator */
296 MD5Update(&ctx, &h->in[POS_CODE], POS_AUTH - POS_CODE);
297 MD5Update(&ctx, zeroes, LEN_AUTH);
298 MD5Update(&ctx, &h->in[POS_ATTRS], len - POS_ATTRS);
299 MD5Update(&ctx, srvp->secret, strlen(srvp->secret));
301 if (memcmp(&h->in[POS_AUTH], md5, sizeof md5) != 0)
306 /* Search and verify the Message-Authenticator */
308 hctx = HMAC_CTX_new();
309 while (pos < len - 2) {
310 if (h->in[pos] == RAD_MESSAGE_AUTHENTIC) {
311 memcpy(resp, h->in, MSGSIZE);
312 /* zero fill the Request-Authenticator */
313 if (h->in[POS_CODE] != RAD_ACCESS_REQUEST)
314 memset(&resp[POS_AUTH], 0, LEN_AUTH);
315 /* zero fill the Message-Authenticator */
316 memset(&resp[pos + 2], 0, MD5_DIGEST_LENGTH);
318 HMAC_Init_ex(hctx, srvp->secret,
319 strlen(srvp->secret), EVP_md5(), NULL);
320 HMAC_Update(hctx, resp, h->in_len);
321 HMAC_Final(hctx, md, &md_len);
322 HMAC_CTX_reset(hctx);
323 if (memcmp(md, &h->in[pos + 2],
324 MD5_DIGEST_LENGTH) != 0) {
330 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 char *fields[MAX_FIELDS];
505 unsigned long timeout;
506 unsigned long maxtries;
507 unsigned long dead_time;
509 struct in_addr bindto;
514 /* We know len > 0, else fgets would have returned NULL. */
515 if (buf[len - 1] != '\n') {
516 if (len == sizeof buf - 1)
517 generr(h, "%s:%d: line too long", path,
520 generr(h, "%s:%d: missing newline", path,
527 /* Extract the fields from the line. */
528 nfields = split(buf, fields, MAX_FIELDS, msg, sizeof msg);
530 generr(h, "%s:%d: %s", path, linenum, msg);
537 * The first field should contain "auth" or "acct" for
538 * authentication or accounting, respectively. But older
539 * versions of the file didn't have that field. Default
540 * it to "auth" for backward compatibility.
542 if (strcmp(fields[0], "auth") != 0 &&
543 strcmp(fields[0], "acct") != 0) {
544 if (nfields >= MAX_FIELDS) {
545 generr(h, "%s:%d: invalid service type", path,
551 for (i = nfields; --i > 0; )
552 fields[i] = fields[i - 1];
556 generr(h, "%s:%d: missing shared secret", path,
564 timeout_str = fields[3];
565 maxtries_str = fields[4];
566 dead_time_str = fields[5];
567 bindto_str = fields[6];
569 /* Ignore the line if it is for the wrong service type. */
570 wanttype = h->type == RADIUS_AUTH ? "auth" : "acct";
571 if (strcmp(type, wanttype) != 0)
574 /* Parse and validate the fields. */
576 host = strsep(&res, ":");
577 port_str = strsep(&res, ":");
578 if (port_str != NULL) {
579 port = strtoul(port_str, &end, 10);
581 generr(h, "%s:%d: invalid port", path,
588 if (timeout_str != NULL) {
589 timeout = strtoul(timeout_str, &end, 10);
591 generr(h, "%s:%d: invalid timeout", path,
598 if (maxtries_str != NULL) {
599 maxtries = strtoul(maxtries_str, &end, 10);
601 generr(h, "%s:%d: invalid maxtries", path,
609 if (dead_time_str != NULL) {
610 dead_time = strtoul(dead_time_str, &end, 10);
612 generr(h, "%s:%d: invalid dead_time", path,
618 dead_time = DEAD_TIME;
620 if (bindto_str != NULL) {
621 bindto.s_addr = inet_addr(bindto_str);
622 if (bindto.s_addr == INADDR_NONE) {
623 generr(h, "%s:%d: invalid bindto", path,
629 bindto.s_addr = INADDR_ANY;
631 if (rad_add_server_ex(h, host, port, secret, timeout, maxtries,
632 dead_time, &bindto) == -1) {
633 strcpy(msg, h->errmsg);
634 generr(h, "%s:%d: %s", path, linenum, msg);
639 /* Clear out the buffer to wipe a possible copy of a shared secret */
640 memset(buf, 0, sizeof buf);
646 * rad_init_send_request() must have previously been called.
648 * 0 The application should select on *fd with a timeout of tv before
649 * calling rad_continue_send_request again.
654 rad_continue_send_request(struct rad_handle *h, int selected, int *fd,
659 struct sockaddr_in sin;
661 if (h->type == RADIUS_SERVER) {
662 generr(h, "denied function call");
666 struct sockaddr_in from;
669 fromlen = sizeof from;
670 h->in_len = recvfrom(h->fd, h->in,
671 MSGSIZE, MSG_WAITALL, (struct sockaddr *)&from, &fromlen);
672 if (h->in_len == -1) {
673 generr(h, "recvfrom: %s", strerror(errno));
676 if (is_valid_response(h, h->srv, &from)) {
677 h->in_len = h->in[POS_LENGTH] << 8 |
679 h->in_pos = POS_ATTRS;
680 return h->in[POS_CODE];
685 * Scan round-robin to the next server that has some
686 * tries left. There is guaranteed to be one, or we
687 * would have exited this loop by now.
691 if (h->servers[h->srv].num_tries >= h->servers[h->srv].max_tries) {
692 /* Set next probe time for this server */
693 if (h->servers[h->srv].dead_time) {
694 h->servers[h->srv].is_dead = 1;
695 h->servers[h->srv].next_probe = now +
696 h->servers[h->srv].dead_time;
700 if (h->srv >= h->num_servers)
702 if (h->servers[h->srv].is_dead == 0)
704 if (h->servers[h->srv].dead_time &&
705 h->servers[h->srv].next_probe <= now) {
706 h->servers[h->srv].is_dead = 0;
707 h->servers[h->srv].num_tries = 0;
710 } while (h->srv != cur_srv);
712 if (h->srv == cur_srv) {
713 generr(h, "No valid RADIUS responses received");
719 if (h->bindto != h->servers[h->srv].bindto) {
720 h->bindto = h->servers[h->srv].bindto;
722 if ((h->fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
723 generr(h, "Cannot create socket: %s", strerror(errno));
726 memset(&sin, 0, sizeof sin);
727 sin.sin_len = sizeof sin;
728 sin.sin_family = AF_INET;
729 sin.sin_addr.s_addr = h->bindto;
731 if (bind(h->fd, (const struct sockaddr *)&sin,
733 generr(h, "bind: %s", strerror(errno));
740 if (h->out[POS_CODE] == RAD_ACCESS_REQUEST) {
741 /* Insert the scrambled password into the request */
742 if (h->pass_pos != 0)
743 insert_scrambled_password(h, h->srv);
745 insert_message_authenticator(h, 0);
747 if (h->out[POS_CODE] != RAD_ACCESS_REQUEST) {
748 /* Insert the request authenticator into the request */
749 memset(&h->out[POS_AUTH], 0, LEN_AUTH);
750 insert_request_authenticator(h, 0);
753 /* Send the request */
754 n = sendto(h->fd, h->out, h->out_len, 0,
755 (const struct sockaddr *)&h->servers[h->srv].addr,
756 sizeof h->servers[h->srv].addr);
758 tv->tv_sec = 1; /* Do not wait full timeout if send failed. */
760 tv->tv_sec = h->servers[h->srv].timeout;
761 h->servers[h->srv].num_tries++;
769 rad_receive_request(struct rad_handle *h)
771 struct sockaddr_in from;
775 if (h->type != RADIUS_SERVER) {
776 generr(h, "denied function call");
780 fromlen = sizeof(from);
781 h->in_len = recvfrom(h->fd, h->in,
782 MSGSIZE, MSG_WAITALL, (struct sockaddr *)&from, &fromlen);
783 if (h->in_len == -1) {
784 generr(h, "recvfrom: %s", strerror(errno));
787 for (n = 0; n < h->num_servers; n++) {
788 if (h->servers[n].addr.sin_addr.s_addr == from.sin_addr.s_addr) {
789 h->servers[n].addr.sin_port = from.sin_port;
796 if (is_valid_request(h)) {
797 h->in_len = h->in[POS_LENGTH] << 8 |
799 h->in_pos = POS_ATTRS;
800 return (h->in[POS_CODE]);
806 rad_send_response(struct rad_handle *h)
810 if (h->type != RADIUS_SERVER) {
811 generr(h, "denied function call");
814 /* Fill in the length field in the message */
815 h->out[POS_LENGTH] = h->out_len >> 8;
816 h->out[POS_LENGTH+1] = h->out_len;
818 insert_message_authenticator(h,
819 (h->in[POS_CODE] == RAD_ACCESS_REQUEST) ? 1 : 0);
820 insert_request_authenticator(h, 1);
822 /* Send the request */
823 n = sendto(h->fd, h->out, h->out_len, 0,
824 (const struct sockaddr *)&h->servers[h->srv].addr,
825 sizeof h->servers[h->srv].addr);
826 if (n != h->out_len) {
828 generr(h, "sendto: %s", strerror(errno));
830 generr(h, "sendto: short write");
838 rad_create_request(struct rad_handle *h, int code)
842 if (h->type == RADIUS_SERVER) {
843 generr(h, "denied function call");
846 if (h->num_servers == 0) {
847 generr(h, "No RADIUS servers specified");
850 h->out[POS_CODE] = code;
851 h->out[POS_IDENT] = ++h->ident;
852 if (code == RAD_ACCESS_REQUEST) {
853 /* Create a random authenticator */
854 for (i = 0; i < LEN_AUTH; i += 2) {
857 h->out[POS_AUTH+i] = (u_char)r;
858 h->out[POS_AUTH+i+1] = (u_char)(r >> 8);
861 memset(&h->out[POS_AUTH], 0, LEN_AUTH);
862 h->out_len = POS_ATTRS;
864 h->authentic_pos = 0;
870 rad_create_response(struct rad_handle *h, int code)
873 if (h->type != RADIUS_SERVER) {
874 generr(h, "denied function call");
877 h->out[POS_CODE] = code;
878 h->out[POS_IDENT] = h->in[POS_IDENT];
879 memset(&h->out[POS_AUTH], 0, LEN_AUTH);
880 h->out_len = POS_ATTRS;
882 h->authentic_pos = 0;
888 rad_cvt_addr(const void *data)
890 struct in_addr value;
892 memcpy(&value.s_addr, data, sizeof value.s_addr);
897 rad_cvt_addr6(const void *data)
899 struct in6_addr value;
901 memcpy(&value.s6_addr, data, sizeof value.s6_addr);
906 rad_cvt_int(const void *data)
910 memcpy(&value, data, sizeof value);
915 rad_cvt_string(const void *data, size_t len)
921 memcpy(s, data, len);
928 * Returns the attribute type. If none are left, returns 0. On failure,
932 rad_get_attr(struct rad_handle *h, const void **value, size_t *len)
936 if (h->in_pos >= h->in_len)
938 if (h->in_pos + 2 > h->in_len) {
939 generr(h, "Malformed attribute in response");
942 type = h->in[h->in_pos++];
943 *len = h->in[h->in_pos++] - 2;
944 if (h->in_pos + (int)*len > h->in_len) {
945 generr(h, "Malformed attribute in response");
948 *value = &h->in[h->in_pos];
954 * Returns -1 on error, 0 to indicate no event and >0 for success
957 rad_init_send_request(struct rad_handle *h, int *fd, struct timeval *tv)
961 struct sockaddr_in sin;
963 if (h->type == RADIUS_SERVER) {
964 generr(h, "denied function call");
967 /* Make sure we have a socket to use */
969 if ((h->fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
970 generr(h, "Cannot create socket: %s", strerror(errno));
973 memset(&sin, 0, sizeof sin);
974 sin.sin_len = sizeof sin;
975 sin.sin_family = AF_INET;
976 sin.sin_addr.s_addr = h->bindto;
977 sin.sin_port = htons(0);
978 if (bind(h->fd, (const struct sockaddr *)&sin,
980 generr(h, "bind: %s", strerror(errno));
987 if (h->out[POS_CODE] != RAD_ACCESS_REQUEST) {
988 /* Make sure no password given */
989 if (h->pass_pos || h->chap_pass) {
990 generr(h, "User or Chap Password"
991 " in accounting request");
995 if (h->eap_msg == 0) {
996 /* Make sure the user gave us a password */
997 if (h->pass_pos == 0 && !h->chap_pass) {
998 generr(h, "No User or Chap Password"
999 " attributes given");
1002 if (h->pass_pos != 0 && h->chap_pass) {
1003 generr(h, "Both User and Chap Password"
1004 " attributes given");
1010 /* Fill in the length field in the message */
1011 h->out[POS_LENGTH] = h->out_len >> 8;
1012 h->out[POS_LENGTH+1] = h->out_len;
1016 for (srv = 0; srv < h->num_servers; srv++)
1017 h->servers[srv].num_tries = 0;
1018 /* Find a first good server. */
1019 for (srv = 0; srv < h->num_servers; srv++) {
1020 if (h->servers[srv].is_dead == 0)
1022 if (h->servers[srv].dead_time &&
1023 h->servers[srv].next_probe <= now) {
1024 h->servers[srv].is_dead = 0;
1030 /* If all servers was dead on the last probe, try from beginning */
1031 if (h->srv == h->num_servers) {
1032 for (srv = 0; srv < h->num_servers; srv++) {
1033 h->servers[srv].is_dead = 0;
1034 h->servers[srv].next_probe = 0;
1039 return rad_continue_send_request(h, 0, fd, tv);
1043 * Create and initialize a rad_handle structure, and return it to the
1044 * caller. Can fail only if the necessary memory cannot be allocated.
1045 * In that case, it returns NULL.
1050 struct rad_handle *h;
1052 h = (struct rad_handle *)malloc(sizeof(struct rad_handle));
1056 h->ident = arc4random();
1057 h->errmsg[0] = '\0';
1058 memset(h->pass, 0, sizeof h->pass);
1062 h->authentic_pos = 0;
1063 h->type = RADIUS_AUTH;
1066 h->bindto = INADDR_ANY;
1074 struct rad_handle *h;
1078 h->type = RADIUS_ACCT;
1083 rad_server_open(int fd)
1085 struct rad_handle *h;
1089 h->type = RADIUS_SERVER;
1098 return rad_auth_open();
1102 rad_put_addr(struct rad_handle *h, int type, struct in_addr addr)
1104 return rad_put_attr(h, type, &addr.s_addr, sizeof addr.s_addr);
1108 rad_put_addr6(struct rad_handle *h, int type, struct in6_addr addr)
1111 return rad_put_attr(h, type, &addr.s6_addr, sizeof addr.s6_addr);
1115 rad_put_attr(struct rad_handle *h, int type, const void *value, size_t len)
1119 if (!h->out_created) {
1120 generr(h, "Please call rad_create_request()"
1121 " before putting attributes");
1125 if (h->out[POS_CODE] == RAD_ACCOUNTING_REQUEST) {
1126 if (type == RAD_EAP_MESSAGE) {
1127 generr(h, "EAP-Message attribute is not valid"
1128 " in accounting requests");
1134 * When proxying EAP Messages, the Message Authenticator
1135 * MUST be present; see RFC 3579.
1137 if (type == RAD_EAP_MESSAGE) {
1138 if (rad_put_message_authentic(h) == -1)
1142 if (type == RAD_USER_PASSWORD) {
1143 result = put_password_attr(h, type, value, len);
1144 } else if (type == RAD_MESSAGE_AUTHENTIC) {
1145 result = rad_put_message_authentic(h);
1147 result = put_raw_attr(h, type, value, len);
1149 if (type == RAD_CHAP_PASSWORD)
1151 else if (type == RAD_EAP_MESSAGE)
1160 rad_put_int(struct rad_handle *h, int type, u_int32_t value)
1164 nvalue = htonl(value);
1165 return rad_put_attr(h, type, &nvalue, sizeof nvalue);
1169 rad_put_string(struct rad_handle *h, int type, const char *str)
1171 return rad_put_attr(h, type, str, strlen(str));
1175 rad_put_message_authentic(struct rad_handle *h)
1178 u_char md_zero[MD5_DIGEST_LENGTH];
1180 if (h->out[POS_CODE] == RAD_ACCOUNTING_REQUEST) {
1181 generr(h, "Message-Authenticator is not valid"
1182 " in accounting requests");
1186 if (h->authentic_pos == 0) {
1187 h->authentic_pos = h->out_len;
1188 memset(md_zero, 0, sizeof(md_zero));
1189 return (put_raw_attr(h, RAD_MESSAGE_AUTHENTIC, md_zero,
1194 generr(h, "Message Authenticator not supported,"
1195 " please recompile libradius with SSL support");
1201 * Returns the response type code on success, or -1 on failure.
1204 rad_send_request(struct rad_handle *h)
1206 struct timeval timelimit;
1211 n = rad_init_send_request(h, &fd, &tv);
1216 gettimeofday(&timelimit, NULL);
1217 timeradd(&tv, &timelimit, &timelimit);
1223 FD_SET(fd, &readfds);
1225 n = select(fd + 1, &readfds, NULL, NULL, &tv);
1228 generr(h, "select: %s", strerror(errno));
1232 if (!FD_ISSET(fd, &readfds)) {
1233 /* Compute a new timeout */
1234 gettimeofday(&tv, NULL);
1235 timersub(&timelimit, &tv, &tv);
1236 if (tv.tv_sec > 0 || (tv.tv_sec == 0 && tv.tv_usec > 0))
1237 /* Continue the select */
1241 n = rad_continue_send_request(h, n, &fd, &tv);
1246 gettimeofday(&timelimit, NULL);
1247 timeradd(&tv, &timelimit, &timelimit);
1252 rad_strerror(struct rad_handle *h)
1258 * Destructively split a string into fields separated by white space.
1259 * `#' at the beginning of a field begins a comment that extends to the
1260 * end of the string. Fields may be quoted with `"'. Inside quoted
1261 * strings, the backslash escapes `\"' and `\\' are honored.
1263 * Pointers to up to the first maxfields fields are stored in the fields
1264 * array. Missing fields get NULL pointers.
1266 * The return value is the actual number of fields parsed, and is always
1269 * On a syntax error, places a message in the msg string, and returns -1.
1272 split(char *str, char *fields[], int maxfields, char *msg, size_t msglen)
1276 static const char ws[] = " \t";
1278 for (i = 0; i < maxfields; i++)
1282 while (*p != '\0') {
1284 if (*p == '#' || *p == '\0')
1286 if (i >= maxfields) {
1287 snprintf(msg, msglen, "line has too many fields");
1298 if (*p != '"' && *p != '\\' &&
1300 snprintf(msg, msglen,
1301 "invalid `\\' escape");
1306 snprintf(msg, msglen,
1307 "unterminated quoted string");
1314 if (*fields[i] == '\0') {
1315 snprintf(msg, msglen,
1316 "empty quoted string not permitted");
1319 if (*p != '\0' && strspn(p, ws) == 0) {
1320 snprintf(msg, msglen, "quoted string not"
1321 " followed by white space");
1326 p += strcspn(p, ws);
1336 rad_get_vendor_attr(u_int32_t *vendor, const void **data, size_t *len)
1338 struct vendor_attribute *attr;
1340 attr = (struct vendor_attribute *)*data;
1341 *vendor = ntohl(attr->vendor_value);
1342 *data = attr->attrib_data;
1343 *len = attr->attrib_len - 2;
1345 return (attr->attrib_type);
1349 rad_put_vendor_addr(struct rad_handle *h, int vendor, int type,
1350 struct in_addr addr)
1352 return (rad_put_vendor_attr(h, vendor, type, &addr.s_addr,
1353 sizeof addr.s_addr));
1357 rad_put_vendor_addr6(struct rad_handle *h, int vendor, int type,
1358 struct in6_addr addr)
1361 return (rad_put_vendor_attr(h, vendor, type, &addr.s6_addr,
1362 sizeof addr.s6_addr));
1366 rad_put_vendor_attr(struct rad_handle *h, int vendor, int type,
1367 const void *value, size_t len)
1369 struct vendor_attribute *attr;
1372 if (!h->out_created) {
1373 generr(h, "Please call rad_create_request()"
1374 " before putting attributes");
1378 if ((attr = malloc(len + 6)) == NULL) {
1379 generr(h, "malloc failure (%zu bytes)", len + 6);
1383 attr->vendor_value = htonl(vendor);
1384 attr->attrib_type = type;
1385 attr->attrib_len = len + 2;
1386 memcpy(attr->attrib_data, value, len);
1388 res = put_raw_attr(h, RAD_VENDOR_SPECIFIC, attr, len + 6);
1390 if (res == 0 && vendor == RAD_VENDOR_MICROSOFT
1391 && (type == RAD_MICROSOFT_MS_CHAP_RESPONSE
1392 || type == RAD_MICROSOFT_MS_CHAP2_RESPONSE)) {
1399 rad_put_vendor_int(struct rad_handle *h, int vendor, int type, u_int32_t i)
1404 return (rad_put_vendor_attr(h, vendor, type, &value, sizeof value));
1408 rad_put_vendor_string(struct rad_handle *h, int vendor, int type,
1411 return (rad_put_vendor_attr(h, vendor, type, str, strlen(str)));
1415 rad_request_authenticator(struct rad_handle *h, char *buf, size_t len)
1419 memcpy(buf, h->out + POS_AUTH, LEN_AUTH);
1421 buf[LEN_AUTH] = '\0';
1426 rad_demangle(struct rad_handle *h, const void *mangled, size_t mlen)
1432 u_char b[MD5_DIGEST_LENGTH], *C, *demangled;
1434 if ((mlen % 16 != 0) || mlen > 128) {
1435 generr(h, "Cannot interpret mangled data of length %lu",
1440 C = (u_char *)mangled;
1442 /* We need the shared secret as Salt */
1443 S = rad_server_secret(h);
1445 /* We need the request authenticator */
1446 if (rad_request_authenticator(h, R, sizeof R) != LEN_AUTH) {
1447 generr(h, "Cannot obtain the RADIUS request authenticator");
1451 demangled = malloc(mlen);
1456 MD5Update(&Context, S, strlen(S));
1457 MD5Update(&Context, R, LEN_AUTH);
1458 MD5Final(b, &Context);
1463 for (i = 0; i < 16; i++)
1464 demangled[Ppos++] = C[i] ^ b[i];
1468 MD5Update(&Context, S, strlen(S));
1469 MD5Update(&Context, C, 16);
1470 MD5Final(b, &Context);
1480 rad_demangle_mppe_key(struct rad_handle *h, const void *mangled,
1481 size_t mlen, size_t *len)
1483 char R[LEN_AUTH]; /* variable names as per rfc2548 */
1485 u_char b[MD5_DIGEST_LENGTH], *demangled;
1486 const u_char *A, *C;
1488 int Slen, i, Clen, Ppos;
1491 if (mlen % 16 != SALT_LEN) {
1492 generr(h, "Cannot interpret mangled data of length %lu",
1497 /* We need the RADIUS Request-Authenticator */
1498 if (rad_request_authenticator(h, R, sizeof R) != LEN_AUTH) {
1499 generr(h, "Cannot obtain the RADIUS request authenticator");
1503 A = (const u_char *)mangled; /* Salt comes first */
1504 C = (const u_char *)mangled + SALT_LEN; /* Then the ciphertext */
1505 Clen = mlen - SALT_LEN;
1506 S = rad_server_secret(h); /* We need the RADIUS secret */
1508 P = alloca(Clen); /* We derive our plaintext */
1511 MD5Update(&Context, S, Slen);
1512 MD5Update(&Context, R, LEN_AUTH);
1513 MD5Update(&Context, A, SALT_LEN);
1514 MD5Final(b, &Context);
1520 for (i = 0; i < 16; i++)
1521 P[Ppos++] = C[i] ^ b[i];
1525 MD5Update(&Context, S, Slen);
1526 MD5Update(&Context, C, 16);
1527 MD5Final(b, &Context);
1534 * The resulting plain text consists of a one-byte length, the text and
1535 * maybe some padding.
1538 if (*len > mlen - 1) {
1539 generr(h, "Mangled data seems to be garbage %zu %zu",
1544 if (*len > MPPE_KEY_LEN * 2) {
1545 generr(h, "Key to long (%zu) for me max. %d",
1546 *len, MPPE_KEY_LEN * 2);
1549 demangled = malloc(*len);
1553 memcpy(demangled, P + 1, *len);
1558 rad_server_secret(struct rad_handle *h)
1560 return (h->servers[h->srv].secret);