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;
195 u_char resp[MSGSIZE], md[EVP_MAX_MD_SIZE];
200 srvp = &h->servers[srv];
202 /* Check the source address */
203 if (from->sin_family != srvp->addr.sin_family ||
204 from->sin_addr.s_addr != srvp->addr.sin_addr.s_addr ||
205 from->sin_port != srvp->addr.sin_port)
208 /* Check the message length */
209 if (h->in_len < POS_ATTRS)
211 len = (h->in[POS_LENGTH] << 8) | h->in[POS_LENGTH + 1];
212 if (len < POS_ATTRS || len > h->in_len)
215 /* Check the response authenticator */
217 MD5Update(&ctx, &h->in[POS_CODE], POS_AUTH - POS_CODE);
218 MD5Update(&ctx, &h->out[POS_AUTH], LEN_AUTH);
219 MD5Update(&ctx, &h->in[POS_ATTRS], len - POS_ATTRS);
220 MD5Update(&ctx, srvp->secret, strlen(srvp->secret));
222 if (memcmp(&h->in[POS_AUTH], md5, sizeof md5) != 0)
227 * For non accounting responses check the message authenticator,
230 if (h->in[POS_CODE] != RAD_ACCOUNTING_RESPONSE) {
232 memcpy(resp, h->in, MSGSIZE);
235 /* Search and verify the Message-Authenticator */
236 hctx = HMAC_CTX_new();
237 while (pos < len - 2) {
238 if (h->in[pos] == RAD_MESSAGE_AUTHENTIC) {
239 if (h->in[pos + 1] != MD5_DIGEST_LENGTH + 2) {
243 if (len - pos < MD5_DIGEST_LENGTH + 2) {
248 memset(&resp[pos + 2], 0, MD5_DIGEST_LENGTH);
250 HMAC_Init_ex(hctx, srvp->secret,
251 strlen(srvp->secret), EVP_md5(), NULL);
252 HMAC_Update(hctx, &h->in[POS_CODE],
253 POS_AUTH - POS_CODE);
254 HMAC_Update(hctx, &h->out[POS_AUTH],
256 HMAC_Update(hctx, &resp[POS_ATTRS],
257 h->in_len - POS_ATTRS);
258 HMAC_Final(hctx, md, &md_len);
259 HMAC_CTX_reset(hctx);
260 if (memcmp(md, &h->in[pos + 2],
261 MD5_DIGEST_LENGTH) != 0) {
267 alen = h->in[pos + 1];
281 * Return true if the current request is valid for the specified server.
284 is_valid_request(struct rad_handle *h)
287 unsigned char md5[MD5_DIGEST_LENGTH];
288 const struct rad_server *srvp;
292 u_char resp[MSGSIZE], md[EVP_MAX_MD_SIZE];
297 srvp = &h->servers[h->srv];
299 /* Check the message length */
300 if (h->in_len < POS_ATTRS)
302 len = (h->in[POS_LENGTH] << 8) | h->in[POS_LENGTH + 1];
303 if (len < POS_ATTRS || len > h->in_len)
306 if (h->in[POS_CODE] != RAD_ACCESS_REQUEST) {
307 uint32_t zeroes[4] = { 0, 0, 0, 0 };
308 /* Check the request authenticator */
310 MD5Update(&ctx, &h->in[POS_CODE], POS_AUTH - POS_CODE);
311 MD5Update(&ctx, zeroes, LEN_AUTH);
312 MD5Update(&ctx, &h->in[POS_ATTRS], len - POS_ATTRS);
313 MD5Update(&ctx, srvp->secret, strlen(srvp->secret));
315 if (memcmp(&h->in[POS_AUTH], md5, sizeof md5) != 0)
320 /* Search and verify the Message-Authenticator */
322 hctx = HMAC_CTX_new();
323 while (pos < len - 2) {
324 alen = h->in[pos + 1];
327 if (h->in[pos] == RAD_MESSAGE_AUTHENTIC) {
328 if (len - pos < MD5_DIGEST_LENGTH + 2) {
332 if (alen < MD5_DIGEST_LENGTH + 2) {
336 memcpy(resp, h->in, MSGSIZE);
337 /* zero fill the Request-Authenticator */
338 if (h->in[POS_CODE] != RAD_ACCESS_REQUEST)
339 memset(&resp[POS_AUTH], 0, LEN_AUTH);
340 /* zero fill the Message-Authenticator */
341 memset(&resp[pos + 2], 0, MD5_DIGEST_LENGTH);
343 HMAC_Init_ex(hctx, srvp->secret,
344 strlen(srvp->secret), EVP_md5(), NULL);
345 HMAC_Update(hctx, resp, h->in_len);
346 HMAC_Final(hctx, md, &md_len);
347 HMAC_CTX_reset(hctx);
348 if (memcmp(md, &h->in[pos + 2],
349 MD5_DIGEST_LENGTH) != 0) {
363 put_password_attr(struct rad_handle *h, int type, const void *value, size_t len)
368 if (h->pass_pos != 0) {
369 generr(h, "Multiple User-Password attributes specified");
374 padded_len = len == 0 ? 16 : (len+15) & ~0xf;
375 pad_len = padded_len - len;
378 * Put in a place-holder attribute containing all zeros, and
379 * remember where it is so we can fill it in later.
382 put_raw_attr(h, type, h->pass, padded_len);
383 h->pass_pos = h->out_len - padded_len;
385 /* Save the cleartext password, padded as necessary */
386 memcpy(h->pass, value, len);
388 memset(h->pass + len, 0, pad_len);
393 put_raw_attr(struct rad_handle *h, int type, const void *value, size_t len)
396 generr(h, "Attribute too long");
399 if (h->out_len + 2 + len > MSGSIZE) {
400 generr(h, "Maximum message length exceeded");
403 h->out[h->out_len++] = type;
404 h->out[h->out_len++] = len + 2;
405 memcpy(&h->out[h->out_len], value, len);
411 rad_add_server(struct rad_handle *h, const char *host, int port,
412 const char *secret, int timeout, int tries)
414 struct in_addr bindto;
415 bindto.s_addr = INADDR_ANY;
417 return rad_add_server_ex(h, host, port, secret, timeout, tries,
422 rad_add_server_ex(struct rad_handle *h, const char *host, int port,
423 const char *secret, int timeout, int tries, int dead_time,
424 struct in_addr *bindto)
426 struct rad_server *srvp;
428 if (h->num_servers >= MAXSERVERS) {
429 generr(h, "Too many RADIUS servers specified");
432 srvp = &h->servers[h->num_servers];
434 memset(&srvp->addr, 0, sizeof srvp->addr);
435 srvp->addr.sin_len = sizeof srvp->addr;
436 srvp->addr.sin_family = AF_INET;
437 if (!inet_aton(host, &srvp->addr.sin_addr)) {
438 struct hostent *hent;
440 if ((hent = gethostbyname(host)) == NULL) {
441 generr(h, "%s: host not found", host);
444 memcpy(&srvp->addr.sin_addr, hent->h_addr,
445 sizeof srvp->addr.sin_addr);
448 srvp->addr.sin_port = htons((u_short)port);
450 struct servent *sent;
452 if (h->type == RADIUS_AUTH)
453 srvp->addr.sin_port =
454 (sent = getservbyname("radius", "udp")) != NULL ?
455 sent->s_port : htons(RADIUS_PORT);
457 srvp->addr.sin_port =
458 (sent = getservbyname("radacct", "udp")) != NULL ?
459 sent->s_port : htons(RADACCT_PORT);
461 if ((srvp->secret = strdup(secret)) == NULL) {
462 generr(h, "Out of memory");
465 srvp->timeout = timeout;
466 srvp->max_tries = tries;
469 srvp->dead_time = dead_time;
470 srvp->next_probe = 0;
471 srvp->bindto = bindto->s_addr;
477 rad_close(struct rad_handle *h)
483 for (srv = 0; srv < h->num_servers; srv++) {
484 memset(h->servers[srv].secret, 0,
485 strlen(h->servers[srv].secret));
486 free(h->servers[srv].secret);
493 rad_bind_to(struct rad_handle *h, in_addr_t addr)
500 rad_config(struct rad_handle *h, const char *path)
503 char buf[MAXCONFLINE];
508 path = PATH_RADIUS_CONF;
509 if ((fp = fopen(path, "r")) == NULL) {
510 generr(h, "Cannot open \"%s\": %s", path, strerror(errno));
515 while (fgets(buf, sizeof buf, fp) != NULL) {
517 char *fields[MAX_FIELDS];
530 unsigned long timeout;
531 unsigned long maxtries;
532 unsigned long dead_time;
534 struct in_addr bindto;
539 /* We know len > 0, else fgets would have returned NULL. */
540 if (buf[len - 1] != '\n') {
541 if (len == sizeof buf - 1)
542 generr(h, "%s:%d: line too long", path,
545 generr(h, "%s:%d: missing newline", path,
552 /* Extract the fields from the line. */
553 nfields = split(buf, fields, MAX_FIELDS, msg, sizeof msg);
555 generr(h, "%s:%d: %s", path, linenum, msg);
562 * The first field should contain "auth" or "acct" for
563 * authentication or accounting, respectively. But older
564 * versions of the file didn't have that field. Default
565 * it to "auth" for backward compatibility.
567 if (strcmp(fields[0], "auth") != 0 &&
568 strcmp(fields[0], "acct") != 0) {
569 if (nfields >= MAX_FIELDS) {
570 generr(h, "%s:%d: invalid service type", path,
576 for (i = nfields; --i > 0; )
577 fields[i] = fields[i - 1];
581 generr(h, "%s:%d: missing shared secret", path,
589 timeout_str = fields[3];
590 maxtries_str = fields[4];
591 dead_time_str = fields[5];
592 bindto_str = fields[6];
594 /* Ignore the line if it is for the wrong service type. */
595 wanttype = h->type == RADIUS_AUTH ? "auth" : "acct";
596 if (strcmp(type, wanttype) != 0)
599 /* Parse and validate the fields. */
601 host = strsep(&res, ":");
602 port_str = strsep(&res, ":");
603 if (port_str != NULL) {
604 port = strtoul(port_str, &end, 10);
606 generr(h, "%s:%d: invalid port", path,
613 if (timeout_str != NULL) {
614 timeout = strtoul(timeout_str, &end, 10);
616 generr(h, "%s:%d: invalid timeout", path,
623 if (maxtries_str != NULL) {
624 maxtries = strtoul(maxtries_str, &end, 10);
626 generr(h, "%s:%d: invalid maxtries", path,
634 if (dead_time_str != NULL) {
635 dead_time = strtoul(dead_time_str, &end, 10);
637 generr(h, "%s:%d: invalid dead_time", path,
643 dead_time = DEAD_TIME;
645 if (bindto_str != NULL) {
646 bindto.s_addr = inet_addr(bindto_str);
647 if (bindto.s_addr == INADDR_NONE) {
648 generr(h, "%s:%d: invalid bindto", path,
654 bindto.s_addr = INADDR_ANY;
656 if (rad_add_server_ex(h, host, port, secret, timeout, maxtries,
657 dead_time, &bindto) == -1) {
658 strcpy(msg, h->errmsg);
659 generr(h, "%s:%d: %s", path, linenum, msg);
664 /* Clear out the buffer to wipe a possible copy of a shared secret */
665 memset(buf, 0, sizeof buf);
671 * rad_init_send_request() must have previously been called.
673 * 0 The application should select on *fd with a timeout of tv before
674 * calling rad_continue_send_request again.
679 rad_continue_send_request(struct rad_handle *h, int selected, int *fd,
684 struct sockaddr_in sin;
686 if (h->type == RADIUS_SERVER) {
687 generr(h, "denied function call");
691 struct sockaddr_in from;
694 fromlen = sizeof from;
695 h->in_len = recvfrom(h->fd, h->in,
696 MSGSIZE, MSG_WAITALL, (struct sockaddr *)&from, &fromlen);
697 if (h->in_len == -1) {
698 generr(h, "recvfrom: %s", strerror(errno));
701 if (is_valid_response(h, h->srv, &from)) {
702 h->in_len = h->in[POS_LENGTH] << 8 |
704 h->in_pos = POS_ATTRS;
705 return h->in[POS_CODE];
710 * Scan round-robin to the next server that has some
711 * tries left. There is guaranteed to be one, or we
712 * would have exited this loop by now.
716 if (h->servers[h->srv].num_tries >= h->servers[h->srv].max_tries) {
717 /* Set next probe time for this server */
718 if (h->servers[h->srv].dead_time) {
719 h->servers[h->srv].is_dead = 1;
720 h->servers[h->srv].next_probe = now +
721 h->servers[h->srv].dead_time;
725 if (h->srv >= h->num_servers)
727 if (h->servers[h->srv].is_dead == 0)
729 if (h->servers[h->srv].dead_time &&
730 h->servers[h->srv].next_probe <= now) {
731 h->servers[h->srv].is_dead = 0;
732 h->servers[h->srv].num_tries = 0;
735 } while (h->srv != cur_srv);
737 if (h->srv == cur_srv) {
738 generr(h, "No valid RADIUS responses received");
744 if (h->bindto != h->servers[h->srv].bindto) {
745 h->bindto = h->servers[h->srv].bindto;
747 if ((h->fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
748 generr(h, "Cannot create socket: %s", strerror(errno));
751 memset(&sin, 0, sizeof sin);
752 sin.sin_len = sizeof sin;
753 sin.sin_family = AF_INET;
754 sin.sin_addr.s_addr = h->bindto;
756 if (bind(h->fd, (const struct sockaddr *)&sin,
758 generr(h, "bind: %s", strerror(errno));
765 if (h->out[POS_CODE] == RAD_ACCESS_REQUEST) {
766 /* Insert the scrambled password into the request */
767 if (h->pass_pos != 0)
768 insert_scrambled_password(h, h->srv);
770 insert_message_authenticator(h, 0);
772 if (h->out[POS_CODE] != RAD_ACCESS_REQUEST) {
773 /* Insert the request authenticator into the request */
774 memset(&h->out[POS_AUTH], 0, LEN_AUTH);
775 insert_request_authenticator(h, 0);
778 /* Send the request */
779 n = sendto(h->fd, h->out, h->out_len, 0,
780 (const struct sockaddr *)&h->servers[h->srv].addr,
781 sizeof h->servers[h->srv].addr);
783 tv->tv_sec = 1; /* Do not wait full timeout if send failed. */
785 tv->tv_sec = h->servers[h->srv].timeout;
786 h->servers[h->srv].num_tries++;
794 rad_receive_request(struct rad_handle *h)
796 struct sockaddr_in from;
800 if (h->type != RADIUS_SERVER) {
801 generr(h, "denied function call");
805 fromlen = sizeof(from);
806 h->in_len = recvfrom(h->fd, h->in,
807 MSGSIZE, MSG_WAITALL, (struct sockaddr *)&from, &fromlen);
808 if (h->in_len == -1) {
809 generr(h, "recvfrom: %s", strerror(errno));
812 for (n = 0; n < h->num_servers; n++) {
813 if (h->servers[n].addr.sin_addr.s_addr == from.sin_addr.s_addr) {
814 h->servers[n].addr.sin_port = from.sin_port;
821 if (is_valid_request(h)) {
822 h->in_len = h->in[POS_LENGTH] << 8 |
824 h->in_pos = POS_ATTRS;
825 return (h->in[POS_CODE]);
831 rad_send_response(struct rad_handle *h)
835 if (h->type != RADIUS_SERVER) {
836 generr(h, "denied function call");
839 /* Fill in the length field in the message */
840 h->out[POS_LENGTH] = h->out_len >> 8;
841 h->out[POS_LENGTH+1] = h->out_len;
843 insert_message_authenticator(h,
844 (h->in[POS_CODE] == RAD_ACCESS_REQUEST) ? 1 : 0);
845 insert_request_authenticator(h, 1);
847 /* Send the request */
848 n = sendto(h->fd, h->out, h->out_len, 0,
849 (const struct sockaddr *)&h->servers[h->srv].addr,
850 sizeof h->servers[h->srv].addr);
851 if (n != h->out_len) {
853 generr(h, "sendto: %s", strerror(errno));
855 generr(h, "sendto: short write");
863 rad_create_request(struct rad_handle *h, int code)
867 if (h->type == RADIUS_SERVER) {
868 generr(h, "denied function call");
871 if (h->num_servers == 0) {
872 generr(h, "No RADIUS servers specified");
875 h->out[POS_CODE] = code;
876 h->out[POS_IDENT] = ++h->ident;
877 if (code == RAD_ACCESS_REQUEST) {
878 /* Create a random authenticator */
879 for (i = 0; i < LEN_AUTH; i += 2) {
882 h->out[POS_AUTH+i] = (u_char)r;
883 h->out[POS_AUTH+i+1] = (u_char)(r >> 8);
886 memset(&h->out[POS_AUTH], 0, LEN_AUTH);
887 h->out_len = POS_ATTRS;
889 h->authentic_pos = 0;
895 rad_create_response(struct rad_handle *h, int code)
898 if (h->type != RADIUS_SERVER) {
899 generr(h, "denied function call");
902 h->out[POS_CODE] = code;
903 h->out[POS_IDENT] = h->in[POS_IDENT];
904 memset(&h->out[POS_AUTH], 0, LEN_AUTH);
905 h->out_len = POS_ATTRS;
907 h->authentic_pos = 0;
913 rad_cvt_addr(const void *data)
915 struct in_addr value;
917 memcpy(&value.s_addr, data, sizeof value.s_addr);
922 rad_cvt_addr6(const void *data)
924 struct in6_addr value;
926 memcpy(&value.s6_addr, data, sizeof value.s6_addr);
931 rad_cvt_int(const void *data)
935 memcpy(&value, data, sizeof value);
940 rad_cvt_string(const void *data, size_t len)
946 memcpy(s, data, len);
953 * Returns the attribute type. If none are left, returns 0. On failure,
957 rad_get_attr(struct rad_handle *h, const void **value, size_t *lenp)
961 if (h->in_pos >= h->in_len)
963 if (h->in_pos + 2 > h->in_len) {
964 generr(h, "Malformed attribute in response");
967 type = h->in[h->in_pos++];
968 len = h->in[h->in_pos++];
970 generr(h, "Malformed attribute in response");
974 if (h->in_pos + len > h->in_len) {
975 generr(h, "Malformed attribute in response");
979 *value = &h->in[h->in_pos];
985 * Returns -1 on error, 0 to indicate no event and >0 for success
988 rad_init_send_request(struct rad_handle *h, int *fd, struct timeval *tv)
992 struct sockaddr_in sin;
994 if (h->type == RADIUS_SERVER) {
995 generr(h, "denied function call");
998 /* Make sure we have a socket to use */
1000 if ((h->fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
1001 generr(h, "Cannot create socket: %s", strerror(errno));
1004 memset(&sin, 0, sizeof sin);
1005 sin.sin_len = sizeof sin;
1006 sin.sin_family = AF_INET;
1007 sin.sin_addr.s_addr = h->bindto;
1008 sin.sin_port = htons(0);
1009 if (bind(h->fd, (const struct sockaddr *)&sin,
1010 sizeof sin) == -1) {
1011 generr(h, "bind: %s", strerror(errno));
1018 if (h->out[POS_CODE] != RAD_ACCESS_REQUEST) {
1019 /* Make sure no password given */
1020 if (h->pass_pos || h->chap_pass) {
1021 generr(h, "User or Chap Password"
1022 " in accounting request");
1026 if (h->eap_msg == 0) {
1027 /* Make sure the user gave us a password */
1028 if (h->pass_pos == 0 && !h->chap_pass) {
1029 generr(h, "No User or Chap Password"
1030 " attributes given");
1033 if (h->pass_pos != 0 && h->chap_pass) {
1034 generr(h, "Both User and Chap Password"
1035 " attributes given");
1041 /* Fill in the length field in the message */
1042 h->out[POS_LENGTH] = h->out_len >> 8;
1043 h->out[POS_LENGTH+1] = h->out_len;
1047 for (srv = 0; srv < h->num_servers; srv++)
1048 h->servers[srv].num_tries = 0;
1049 /* Find a first good server. */
1050 for (srv = 0; srv < h->num_servers; srv++) {
1051 if (h->servers[srv].is_dead == 0)
1053 if (h->servers[srv].dead_time &&
1054 h->servers[srv].next_probe <= now) {
1055 h->servers[srv].is_dead = 0;
1061 /* If all servers was dead on the last probe, try from beginning */
1062 if (h->srv == h->num_servers) {
1063 for (srv = 0; srv < h->num_servers; srv++) {
1064 h->servers[srv].is_dead = 0;
1065 h->servers[srv].next_probe = 0;
1070 return rad_continue_send_request(h, 0, fd, tv);
1074 * Create and initialize a rad_handle structure, and return it to the
1075 * caller. Can fail only if the necessary memory cannot be allocated.
1076 * In that case, it returns NULL.
1081 struct rad_handle *h;
1083 h = (struct rad_handle *)malloc(sizeof(struct rad_handle));
1087 h->ident = arc4random();
1088 h->errmsg[0] = '\0';
1089 memset(h->pass, 0, sizeof h->pass);
1093 h->authentic_pos = 0;
1094 h->type = RADIUS_AUTH;
1097 h->bindto = INADDR_ANY;
1105 struct rad_handle *h;
1109 h->type = RADIUS_ACCT;
1114 rad_server_open(int fd)
1116 struct rad_handle *h;
1120 h->type = RADIUS_SERVER;
1129 return rad_auth_open();
1133 rad_put_addr(struct rad_handle *h, int type, struct in_addr addr)
1135 return rad_put_attr(h, type, &addr.s_addr, sizeof addr.s_addr);
1139 rad_put_addr6(struct rad_handle *h, int type, struct in6_addr addr)
1142 return rad_put_attr(h, type, &addr.s6_addr, sizeof addr.s6_addr);
1146 rad_put_attr(struct rad_handle *h, int type, const void *value, size_t len)
1150 if (!h->out_created) {
1151 generr(h, "Please call rad_create_request()"
1152 " before putting attributes");
1156 if (h->out[POS_CODE] == RAD_ACCOUNTING_REQUEST) {
1157 if (type == RAD_EAP_MESSAGE) {
1158 generr(h, "EAP-Message attribute is not valid"
1159 " in accounting requests");
1165 * When proxying EAP Messages, the Message Authenticator
1166 * MUST be present; see RFC 3579.
1168 if (type == RAD_EAP_MESSAGE) {
1169 if (rad_put_message_authentic(h) == -1)
1173 if (type == RAD_USER_PASSWORD) {
1174 result = put_password_attr(h, type, value, len);
1175 } else if (type == RAD_MESSAGE_AUTHENTIC) {
1176 result = rad_put_message_authentic(h);
1178 result = put_raw_attr(h, type, value, len);
1180 if (type == RAD_CHAP_PASSWORD)
1182 else if (type == RAD_EAP_MESSAGE)
1191 rad_put_int(struct rad_handle *h, int type, u_int32_t value)
1195 nvalue = htonl(value);
1196 return rad_put_attr(h, type, &nvalue, sizeof nvalue);
1200 rad_put_string(struct rad_handle *h, int type, const char *str)
1202 return rad_put_attr(h, type, str, strlen(str));
1206 rad_put_message_authentic(struct rad_handle *h)
1209 u_char md_zero[MD5_DIGEST_LENGTH];
1211 if (h->out[POS_CODE] == RAD_ACCOUNTING_REQUEST) {
1212 generr(h, "Message-Authenticator is not valid"
1213 " in accounting requests");
1217 if (h->authentic_pos == 0) {
1218 h->authentic_pos = h->out_len;
1219 memset(md_zero, 0, sizeof(md_zero));
1220 return (put_raw_attr(h, RAD_MESSAGE_AUTHENTIC, md_zero,
1225 generr(h, "Message Authenticator not supported,"
1226 " please recompile libradius with SSL support");
1232 * Returns the response type code on success, or -1 on failure.
1235 rad_send_request(struct rad_handle *h)
1237 struct timeval timelimit;
1242 n = rad_init_send_request(h, &fd, &tv);
1247 gettimeofday(&timelimit, NULL);
1248 timeradd(&tv, &timelimit, &timelimit);
1254 FD_SET(fd, &readfds);
1256 n = select(fd + 1, &readfds, NULL, NULL, &tv);
1259 generr(h, "select: %s", strerror(errno));
1263 if (!FD_ISSET(fd, &readfds)) {
1264 /* Compute a new timeout */
1265 gettimeofday(&tv, NULL);
1266 timersub(&timelimit, &tv, &tv);
1267 if (tv.tv_sec > 0 || (tv.tv_sec == 0 && tv.tv_usec > 0))
1268 /* Continue the select */
1272 n = rad_continue_send_request(h, n, &fd, &tv);
1277 gettimeofday(&timelimit, NULL);
1278 timeradd(&tv, &timelimit, &timelimit);
1283 rad_strerror(struct rad_handle *h)
1289 * Destructively split a string into fields separated by white space.
1290 * `#' at the beginning of a field begins a comment that extends to the
1291 * end of the string. Fields may be quoted with `"'. Inside quoted
1292 * strings, the backslash escapes `\"' and `\\' are honored.
1294 * Pointers to up to the first maxfields fields are stored in the fields
1295 * array. Missing fields get NULL pointers.
1297 * The return value is the actual number of fields parsed, and is always
1300 * On a syntax error, places a message in the msg string, and returns -1.
1303 split(char *str, char *fields[], int maxfields, char *msg, size_t msglen)
1307 static const char ws[] = " \t";
1309 for (i = 0; i < maxfields; i++)
1313 while (*p != '\0') {
1315 if (*p == '#' || *p == '\0')
1317 if (i >= maxfields) {
1318 snprintf(msg, msglen, "line has too many fields");
1329 if (*p != '"' && *p != '\\' &&
1331 snprintf(msg, msglen,
1332 "invalid `\\' escape");
1337 snprintf(msg, msglen,
1338 "unterminated quoted string");
1345 if (*fields[i] == '\0') {
1346 snprintf(msg, msglen,
1347 "empty quoted string not permitted");
1350 if (*p != '\0' && strspn(p, ws) == 0) {
1351 snprintf(msg, msglen, "quoted string not"
1352 " followed by white space");
1357 p += strcspn(p, ws);
1367 rad_get_vendor_attr(u_int32_t *vendor, const void **data, size_t *len)
1369 struct vendor_attribute *attr;
1371 attr = (struct vendor_attribute *)*data;
1372 *vendor = ntohl(attr->vendor_value);
1373 *data = attr->attrib_data;
1374 *len = attr->attrib_len - 2;
1376 return (attr->attrib_type);
1380 rad_put_vendor_addr(struct rad_handle *h, int vendor, int type,
1381 struct in_addr addr)
1383 return (rad_put_vendor_attr(h, vendor, type, &addr.s_addr,
1384 sizeof addr.s_addr));
1388 rad_put_vendor_addr6(struct rad_handle *h, int vendor, int type,
1389 struct in6_addr addr)
1392 return (rad_put_vendor_attr(h, vendor, type, &addr.s6_addr,
1393 sizeof addr.s6_addr));
1397 rad_put_vendor_attr(struct rad_handle *h, int vendor, int type,
1398 const void *value, size_t len)
1400 struct vendor_attribute *attr;
1403 if (!h->out_created) {
1404 generr(h, "Please call rad_create_request()"
1405 " before putting attributes");
1409 if ((attr = malloc(len + 6)) == NULL) {
1410 generr(h, "malloc failure (%zu bytes)", len + 6);
1414 attr->vendor_value = htonl(vendor);
1415 attr->attrib_type = type;
1416 attr->attrib_len = len + 2;
1417 memcpy(attr->attrib_data, value, len);
1419 res = put_raw_attr(h, RAD_VENDOR_SPECIFIC, attr, len + 6);
1421 if (res == 0 && vendor == RAD_VENDOR_MICROSOFT
1422 && (type == RAD_MICROSOFT_MS_CHAP_RESPONSE
1423 || type == RAD_MICROSOFT_MS_CHAP2_RESPONSE)) {
1430 rad_put_vendor_int(struct rad_handle *h, int vendor, int type, u_int32_t i)
1435 return (rad_put_vendor_attr(h, vendor, type, &value, sizeof value));
1439 rad_put_vendor_string(struct rad_handle *h, int vendor, int type,
1442 return (rad_put_vendor_attr(h, vendor, type, str, strlen(str)));
1446 rad_request_authenticator(struct rad_handle *h, char *buf, size_t len)
1450 memcpy(buf, h->out + POS_AUTH, LEN_AUTH);
1452 buf[LEN_AUTH] = '\0';
1457 rad_demangle(struct rad_handle *h, const void *mangled, size_t mlen)
1463 u_char b[MD5_DIGEST_LENGTH], *C, *demangled;
1465 if ((mlen % 16 != 0) || mlen > 128) {
1466 generr(h, "Cannot interpret mangled data of length %lu",
1471 C = (u_char *)mangled;
1473 /* We need the shared secret as Salt */
1474 S = rad_server_secret(h);
1476 /* We need the request authenticator */
1477 if (rad_request_authenticator(h, R, sizeof R) != LEN_AUTH) {
1478 generr(h, "Cannot obtain the RADIUS request authenticator");
1482 demangled = malloc(mlen);
1487 MD5Update(&Context, S, strlen(S));
1488 MD5Update(&Context, R, LEN_AUTH);
1489 MD5Final(b, &Context);
1494 for (i = 0; i < 16; i++)
1495 demangled[Ppos++] = C[i] ^ b[i];
1499 MD5Update(&Context, S, strlen(S));
1500 MD5Update(&Context, C, 16);
1501 MD5Final(b, &Context);
1511 rad_demangle_mppe_key(struct rad_handle *h, const void *mangled,
1512 size_t mlen, size_t *len)
1514 char R[LEN_AUTH]; /* variable names as per rfc2548 */
1516 u_char b[MD5_DIGEST_LENGTH], *demangled;
1517 const u_char *A, *C;
1519 int Slen, i, Clen, Ppos;
1522 if (mlen % 16 != SALT_LEN) {
1523 generr(h, "Cannot interpret mangled data of length %lu",
1528 /* We need the RADIUS Request-Authenticator */
1529 if (rad_request_authenticator(h, R, sizeof R) != LEN_AUTH) {
1530 generr(h, "Cannot obtain the RADIUS request authenticator");
1534 A = (const u_char *)mangled; /* Salt comes first */
1535 C = (const u_char *)mangled + SALT_LEN; /* Then the ciphertext */
1536 Clen = mlen - SALT_LEN;
1537 S = rad_server_secret(h); /* We need the RADIUS secret */
1539 P = alloca(Clen); /* We derive our plaintext */
1542 MD5Update(&Context, S, Slen);
1543 MD5Update(&Context, R, LEN_AUTH);
1544 MD5Update(&Context, A, SALT_LEN);
1545 MD5Final(b, &Context);
1551 for (i = 0; i < 16; i++)
1552 P[Ppos++] = C[i] ^ b[i];
1556 MD5Update(&Context, S, Slen);
1557 MD5Update(&Context, C, 16);
1558 MD5Final(b, &Context);
1565 * The resulting plain text consists of a one-byte length, the text and
1566 * maybe some padding.
1569 if (*len > mlen - 1) {
1570 generr(h, "Mangled data seems to be garbage %zu %zu",
1575 if (*len > MPPE_KEY_LEN * 2) {
1576 generr(h, "Key to long (%zu) for me max. %d",
1577 *len, MPPE_KEY_LEN * 2);
1580 demangled = malloc(*len);
1584 memcpy(demangled, P + 1, *len);
1589 rad_server_secret(struct rad_handle *h)
1591 return (h->servers[h->srv].secret);