2 * SPDX-License-Identifier: BSD-2-Clause
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 #include <sys/types.h>
31 #include <sys/socket.h>
33 #include <netinet/in.h>
34 #include <arpa/inet.h>
36 #include <openssl/hmac.h>
37 #include <openssl/md5.h>
38 #define MD5Init MD5_Init
39 #define MD5Update MD5_Update
40 #define MD5Final MD5_Final
42 #define MD5_DIGEST_LENGTH 16
48 /* We need the MPPE_KEY_LEN define */
49 #include <netgraph/ng_mppc.h>
60 #include "radlib_private.h"
62 static void clear_password(struct rad_handle *);
63 static void generr(struct rad_handle *, const char *, ...)
65 static void insert_scrambled_password(struct rad_handle *, int);
66 static void insert_request_authenticator(struct rad_handle *, int);
67 static void insert_message_authenticator(struct rad_handle *, int);
68 static int is_valid_response(struct rad_handle *, int,
69 const struct sockaddr_in *);
70 static int put_password_attr(struct rad_handle *, int,
71 const void *, size_t);
72 static int put_raw_attr(struct rad_handle *, int,
73 const void *, size_t);
74 static int split(char *, char *[], int, char *, size_t);
77 clear_password(struct rad_handle *h)
79 if (h->pass_len != 0) {
80 explicit_bzero(h->pass, h->pass_len);
87 generr(struct rad_handle *h, const char *format, ...)
92 vsnprintf(h->errmsg, ERRSIZE, format, ap);
97 insert_scrambled_password(struct rad_handle *h, int srv)
100 unsigned char md5[MD5_DIGEST_LENGTH];
101 const struct rad_server *srvp;
105 srvp = &h->servers[srv];
106 padded_len = h->pass_len == 0 ? 16 : (h->pass_len+15) & ~0xf;
108 memcpy(md5, &h->out[POS_AUTH], LEN_AUTH);
109 for (pos = 0; pos < padded_len; pos += 16) {
112 /* Calculate the new scrambler */
114 MD5Update(&ctx, srvp->secret, strlen(srvp->secret));
115 MD5Update(&ctx, md5, 16);
119 * Mix in the current chunk of the password, and copy
120 * the result into the right place in the request. Also
121 * modify the scrambler in place, since we will use this
122 * in calculating the scrambler for next time.
124 for (i = 0; i < 16; i++)
125 h->out[h->pass_pos + pos + i] =
126 md5[i] ^= h->pass[pos + i];
131 insert_request_authenticator(struct rad_handle *h, int resp)
134 const struct rad_server *srvp;
136 srvp = &h->servers[h->srv];
138 /* Create the request authenticator */
140 MD5Update(&ctx, &h->out[POS_CODE], POS_AUTH - POS_CODE);
142 MD5Update(&ctx, &h->in[POS_AUTH], LEN_AUTH);
144 MD5Update(&ctx, &h->out[POS_AUTH], LEN_AUTH);
145 MD5Update(&ctx, &h->out[POS_ATTRS], h->out_len - POS_ATTRS);
146 MD5Update(&ctx, srvp->secret, strlen(srvp->secret));
147 MD5Final(&h->out[POS_AUTH], &ctx);
151 insert_message_authenticator(struct rad_handle *h, int resp)
154 u_char md[EVP_MAX_MD_SIZE];
156 const struct rad_server *srvp;
158 srvp = &h->servers[h->srv];
160 if (h->authentic_pos != 0) {
161 ctx = HMAC_CTX_new();
162 HMAC_Init_ex(ctx, srvp->secret, strlen(srvp->secret), EVP_md5(), NULL);
163 HMAC_Update(ctx, &h->out[POS_CODE], POS_AUTH - POS_CODE);
165 HMAC_Update(ctx, &h->in[POS_AUTH], LEN_AUTH);
167 HMAC_Update(ctx, &h->out[POS_AUTH], LEN_AUTH);
168 HMAC_Update(ctx, &h->out[POS_ATTRS],
169 h->out_len - POS_ATTRS);
170 HMAC_Final(ctx, md, &md_len);
172 memcpy(&h->out[h->authentic_pos + 2], md, md_len);
178 * Return true if the current response is valid for a request to the
182 is_valid_response(struct rad_handle *h, int srv,
183 const struct sockaddr_in *from)
186 unsigned char md5[MD5_DIGEST_LENGTH];
187 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];
210 if (len < POS_ATTRS || len > h->in_len)
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) {
236 if (h->in[pos] == RAD_MESSAGE_AUTHENTIC) {
237 if (h->in[pos + 1] != MD5_DIGEST_LENGTH + 2) {
241 if (len - pos < MD5_DIGEST_LENGTH + 2) {
246 memset(&resp[pos + 2], 0, MD5_DIGEST_LENGTH);
248 HMAC_Init_ex(hctx, srvp->secret,
249 strlen(srvp->secret), EVP_md5(), NULL);
250 HMAC_Update(hctx, &h->in[POS_CODE],
251 POS_AUTH - POS_CODE);
252 HMAC_Update(hctx, &h->out[POS_AUTH],
254 HMAC_Update(hctx, &resp[POS_ATTRS],
255 h->in_len - POS_ATTRS);
256 HMAC_Final(hctx, md, &md_len);
257 HMAC_CTX_reset(hctx);
258 if (memcmp(md, &h->in[pos + 2],
259 MD5_DIGEST_LENGTH) != 0) {
265 alen = h->in[pos + 1];
279 * Return true if the current request is valid for the specified server.
282 is_valid_request(struct rad_handle *h)
285 unsigned char md5[MD5_DIGEST_LENGTH];
286 const struct rad_server *srvp;
291 u_char resp[MSGSIZE], md[EVP_MAX_MD_SIZE];
296 srvp = &h->servers[h->srv];
298 /* Check the message length */
299 if (h->in_len < POS_ATTRS)
301 len = (h->in[POS_LENGTH] << 8) | h->in[POS_LENGTH + 1];
302 if (len < POS_ATTRS || len > h->in_len)
305 if (h->in[POS_CODE] != RAD_ACCESS_REQUEST) {
306 uint32_t zeroes[4] = { 0, 0, 0, 0 };
307 /* Check the request authenticator */
309 MD5Update(&ctx, &h->in[POS_CODE], POS_AUTH - POS_CODE);
310 MD5Update(&ctx, zeroes, LEN_AUTH);
311 MD5Update(&ctx, &h->in[POS_ATTRS], len - POS_ATTRS);
312 MD5Update(&ctx, srvp->secret, strlen(srvp->secret));
314 if (memcmp(&h->in[POS_AUTH], md5, sizeof md5) != 0)
319 /* Search and verify the Message-Authenticator */
321 hctx = HMAC_CTX_new();
322 while (pos < len - 2) {
323 alen = h->in[pos + 1];
326 if (h->in[pos] == RAD_MESSAGE_AUTHENTIC) {
327 if (len - pos < MD5_DIGEST_LENGTH + 2) {
331 if (alen < MD5_DIGEST_LENGTH + 2) {
335 memcpy(resp, h->in, MSGSIZE);
336 /* zero fill the Request-Authenticator */
337 if (h->in[POS_CODE] != RAD_ACCESS_REQUEST)
338 memset(&resp[POS_AUTH], 0, LEN_AUTH);
339 /* zero fill the Message-Authenticator */
340 memset(&resp[pos + 2], 0, MD5_DIGEST_LENGTH);
342 HMAC_Init_ex(hctx, srvp->secret,
343 strlen(srvp->secret), EVP_md5(), NULL);
344 HMAC_Update(hctx, resp, h->in_len);
345 HMAC_Final(hctx, md, &md_len);
346 HMAC_CTX_reset(hctx);
347 if (memcmp(md, &h->in[pos + 2],
348 MD5_DIGEST_LENGTH) != 0) {
362 put_password_attr(struct rad_handle *h, int type, const void *value, size_t len)
367 if (h->pass_pos != 0) {
368 generr(h, "Multiple User-Password attributes specified");
373 padded_len = len == 0 ? 16 : (len+15) & ~0xf;
374 pad_len = padded_len - len;
377 * Put in a place-holder attribute containing all zeros, and
378 * remember where it is so we can fill it in later.
381 put_raw_attr(h, type, h->pass, padded_len);
382 h->pass_pos = h->out_len - padded_len;
384 /* Save the cleartext password, padded as necessary */
385 memcpy(h->pass, value, len);
387 memset(h->pass + len, 0, pad_len);
392 put_raw_attr(struct rad_handle *h, int type, const void *value, size_t len)
395 generr(h, "Attribute too long");
398 if (h->out_len + 2 + len > MSGSIZE) {
399 generr(h, "Maximum message length exceeded");
402 h->out[h->out_len++] = type;
403 h->out[h->out_len++] = len + 2;
404 memcpy(&h->out[h->out_len], value, len);
410 rad_add_server(struct rad_handle *h, const char *host, int port,
411 const char *secret, int timeout, int tries)
413 struct in_addr bindto;
414 bindto.s_addr = INADDR_ANY;
416 return rad_add_server_ex(h, host, port, secret, timeout, tries,
421 rad_add_server_ex(struct rad_handle *h, const char *host, int port,
422 const char *secret, int timeout, int tries, int dead_time,
423 struct in_addr *bindto)
425 struct rad_server *srvp;
427 if (h->num_servers >= MAXSERVERS) {
428 generr(h, "Too many RADIUS servers specified");
431 srvp = &h->servers[h->num_servers];
433 memset(&srvp->addr, 0, sizeof srvp->addr);
434 srvp->addr.sin_len = sizeof srvp->addr;
435 srvp->addr.sin_family = AF_INET;
436 if (!inet_aton(host, &srvp->addr.sin_addr)) {
437 struct hostent *hent;
439 if ((hent = gethostbyname(host)) == NULL) {
440 generr(h, "%s: host not found", host);
443 memcpy(&srvp->addr.sin_addr, hent->h_addr,
444 sizeof srvp->addr.sin_addr);
447 srvp->addr.sin_port = htons((u_short)port);
449 struct servent *sent;
451 if (h->type == RADIUS_AUTH)
452 srvp->addr.sin_port =
453 (sent = getservbyname("radius", "udp")) != NULL ?
454 sent->s_port : htons(RADIUS_PORT);
456 srvp->addr.sin_port =
457 (sent = getservbyname("radacct", "udp")) != NULL ?
458 sent->s_port : htons(RADACCT_PORT);
460 if ((srvp->secret = strdup(secret)) == NULL) {
461 generr(h, "Out of memory");
464 srvp->timeout = timeout;
465 srvp->max_tries = tries;
468 srvp->dead_time = dead_time;
469 srvp->next_probe = 0;
470 srvp->bindto = bindto->s_addr;
476 rad_close(struct rad_handle *h)
482 for (srv = 0; srv < h->num_servers; srv++) {
483 memset(h->servers[srv].secret, 0,
484 strlen(h->servers[srv].secret));
485 free(h->servers[srv].secret);
492 rad_bind_to(struct rad_handle *h, in_addr_t addr)
499 rad_config(struct rad_handle *h, const char *path)
502 char buf[MAXCONFLINE];
507 path = PATH_RADIUS_CONF;
508 if ((fp = fopen(path, "r")) == NULL) {
509 generr(h, "Cannot open \"%s\": %s", path, strerror(errno));
514 while (fgets(buf, sizeof buf, fp) != NULL) {
516 char *fields[MAX_FIELDS];
529 unsigned long timeout;
530 unsigned long maxtries;
531 unsigned long dead_time;
533 struct in_addr bindto;
538 /* We know len > 0, else fgets would have returned NULL. */
539 if (buf[len - 1] != '\n') {
540 if (len == sizeof buf - 1)
541 generr(h, "%s:%d: line too long", path,
544 generr(h, "%s:%d: missing newline", path,
551 /* Extract the fields from the line. */
552 nfields = split(buf, fields, MAX_FIELDS, msg, sizeof msg);
554 generr(h, "%s:%d: %s", path, linenum, msg);
561 * The first field should contain "auth" or "acct" for
562 * authentication or accounting, respectively. But older
563 * versions of the file didn't have that field. Default
564 * it to "auth" for backward compatibility.
566 if (strcmp(fields[0], "auth") != 0 &&
567 strcmp(fields[0], "acct") != 0) {
568 if (nfields >= MAX_FIELDS) {
569 generr(h, "%s:%d: invalid service type", path,
575 for (i = nfields; --i > 0; )
576 fields[i] = fields[i - 1];
580 generr(h, "%s:%d: missing shared secret", path,
588 timeout_str = fields[3];
589 maxtries_str = fields[4];
590 dead_time_str = fields[5];
591 bindto_str = fields[6];
593 /* Ignore the line if it is for the wrong service type. */
594 wanttype = h->type == RADIUS_AUTH ? "auth" : "acct";
595 if (strcmp(type, wanttype) != 0)
598 /* Parse and validate the fields. */
600 host = strsep(&res, ":");
601 port_str = strsep(&res, ":");
602 if (port_str != NULL) {
603 port = strtoul(port_str, &end, 10);
605 generr(h, "%s:%d: invalid port", path,
612 if (timeout_str != NULL) {
613 timeout = strtoul(timeout_str, &end, 10);
615 generr(h, "%s:%d: invalid timeout", path,
622 if (maxtries_str != NULL) {
623 maxtries = strtoul(maxtries_str, &end, 10);
625 generr(h, "%s:%d: invalid maxtries", path,
633 if (dead_time_str != NULL) {
634 dead_time = strtoul(dead_time_str, &end, 10);
636 generr(h, "%s:%d: invalid dead_time", path,
642 dead_time = DEAD_TIME;
644 if (bindto_str != NULL) {
645 bindto.s_addr = inet_addr(bindto_str);
646 if (bindto.s_addr == INADDR_NONE) {
647 generr(h, "%s:%d: invalid bindto", path,
653 bindto.s_addr = INADDR_ANY;
655 if (rad_add_server_ex(h, host, port, secret, timeout, maxtries,
656 dead_time, &bindto) == -1) {
657 strcpy(msg, h->errmsg);
658 generr(h, "%s:%d: %s", path, linenum, msg);
663 /* Clear out the buffer to wipe a possible copy of a shared secret */
664 memset(buf, 0, sizeof buf);
670 * rad_init_send_request() must have previously been called.
672 * 0 The application should select on *fd with a timeout of tv before
673 * calling rad_continue_send_request again.
678 rad_continue_send_request(struct rad_handle *h, int selected, int *fd,
683 struct sockaddr_in sin;
685 if (h->type == RADIUS_SERVER) {
686 generr(h, "denied function call");
690 struct sockaddr_in from;
693 fromlen = sizeof from;
694 h->in_len = recvfrom(h->fd, h->in,
695 MSGSIZE, MSG_WAITALL, (struct sockaddr *)&from, &fromlen);
696 if (h->in_len == -1) {
697 generr(h, "recvfrom: %s", strerror(errno));
700 if (is_valid_response(h, h->srv, &from)) {
701 h->in_len = h->in[POS_LENGTH] << 8 |
703 h->in_pos = POS_ATTRS;
704 return h->in[POS_CODE];
709 * Scan round-robin to the next server that has some
710 * tries left. There is guaranteed to be one, or we
711 * would have exited this loop by now.
715 if (h->servers[h->srv].num_tries >= h->servers[h->srv].max_tries) {
716 /* Set next probe time for this server */
717 if (h->servers[h->srv].dead_time) {
718 h->servers[h->srv].is_dead = 1;
719 h->servers[h->srv].next_probe = now +
720 h->servers[h->srv].dead_time;
724 if (h->srv >= h->num_servers)
726 if (h->servers[h->srv].is_dead == 0)
728 if (h->servers[h->srv].dead_time &&
729 h->servers[h->srv].next_probe <= now) {
730 h->servers[h->srv].is_dead = 0;
731 h->servers[h->srv].num_tries = 0;
734 } while (h->srv != cur_srv);
736 if (h->srv == cur_srv) {
737 generr(h, "No valid RADIUS responses received");
743 if (h->bindto != h->servers[h->srv].bindto) {
744 h->bindto = h->servers[h->srv].bindto;
746 if ((h->fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
747 generr(h, "Cannot create socket: %s", strerror(errno));
750 memset(&sin, 0, sizeof sin);
751 sin.sin_len = sizeof sin;
752 sin.sin_family = AF_INET;
753 sin.sin_addr.s_addr = h->bindto;
755 if (bind(h->fd, (const struct sockaddr *)&sin,
757 generr(h, "bind: %s", strerror(errno));
764 if (h->out[POS_CODE] == RAD_ACCESS_REQUEST) {
765 /* Insert the scrambled password into the request */
766 if (h->pass_pos != 0)
767 insert_scrambled_password(h, h->srv);
769 insert_message_authenticator(h, 0);
771 if (h->out[POS_CODE] != RAD_ACCESS_REQUEST) {
772 /* Insert the request authenticator into the request */
773 memset(&h->out[POS_AUTH], 0, LEN_AUTH);
774 insert_request_authenticator(h, 0);
777 /* Send the request */
778 n = sendto(h->fd, h->out, h->out_len, 0,
779 (const struct sockaddr *)&h->servers[h->srv].addr,
780 sizeof h->servers[h->srv].addr);
782 tv->tv_sec = 1; /* Do not wait full timeout if send failed. */
784 tv->tv_sec = h->servers[h->srv].timeout;
785 h->servers[h->srv].num_tries++;
793 rad_receive_request(struct rad_handle *h)
795 struct sockaddr_in from;
799 if (h->type != RADIUS_SERVER) {
800 generr(h, "denied function call");
804 fromlen = sizeof(from);
805 h->in_len = recvfrom(h->fd, h->in,
806 MSGSIZE, MSG_WAITALL, (struct sockaddr *)&from, &fromlen);
807 if (h->in_len == -1) {
808 generr(h, "recvfrom: %s", strerror(errno));
811 for (n = 0; n < h->num_servers; n++) {
812 if (h->servers[n].addr.sin_addr.s_addr == from.sin_addr.s_addr) {
813 h->servers[n].addr.sin_port = from.sin_port;
820 if (is_valid_request(h)) {
821 h->in_len = h->in[POS_LENGTH] << 8 |
823 h->in_pos = POS_ATTRS;
824 return (h->in[POS_CODE]);
830 rad_send_response(struct rad_handle *h)
834 if (h->type != RADIUS_SERVER) {
835 generr(h, "denied function call");
838 /* Fill in the length field in the message */
839 h->out[POS_LENGTH] = h->out_len >> 8;
840 h->out[POS_LENGTH+1] = h->out_len;
842 insert_message_authenticator(h,
843 (h->in[POS_CODE] == RAD_ACCESS_REQUEST) ? 1 : 0);
844 insert_request_authenticator(h, 1);
846 /* Send the request */
847 n = sendto(h->fd, h->out, h->out_len, 0,
848 (const struct sockaddr *)&h->servers[h->srv].addr,
849 sizeof h->servers[h->srv].addr);
850 if (n != h->out_len) {
852 generr(h, "sendto: %s", strerror(errno));
854 generr(h, "sendto: short write");
862 rad_create_request(struct rad_handle *h, int code)
866 if (h->type == RADIUS_SERVER) {
867 generr(h, "denied function call");
870 if (h->num_servers == 0) {
871 generr(h, "No RADIUS servers specified");
874 h->out[POS_CODE] = code;
875 h->out[POS_IDENT] = ++h->ident;
876 if (code == RAD_ACCESS_REQUEST) {
877 /* Create a random authenticator */
878 for (i = 0; i < LEN_AUTH; i += 2) {
881 h->out[POS_AUTH+i] = (u_char)r;
882 h->out[POS_AUTH+i+1] = (u_char)(r >> 8);
885 memset(&h->out[POS_AUTH], 0, LEN_AUTH);
886 h->out_len = POS_ATTRS;
888 h->authentic_pos = 0;
894 rad_create_response(struct rad_handle *h, int code)
897 if (h->type != RADIUS_SERVER) {
898 generr(h, "denied function call");
901 h->out[POS_CODE] = code;
902 h->out[POS_IDENT] = h->in[POS_IDENT];
903 memset(&h->out[POS_AUTH], 0, LEN_AUTH);
904 h->out_len = POS_ATTRS;
906 h->authentic_pos = 0;
912 rad_cvt_addr(const void *data)
914 struct in_addr value;
916 memcpy(&value.s_addr, data, sizeof value.s_addr);
921 rad_cvt_addr6(const void *data)
923 struct in6_addr value;
925 memcpy(&value.s6_addr, data, sizeof value.s6_addr);
930 rad_cvt_int(const void *data)
934 memcpy(&value, data, sizeof value);
939 rad_cvt_string(const void *data, size_t len)
945 memcpy(s, data, len);
952 * Returns the attribute type. If none are left, returns 0. On failure,
956 rad_get_attr(struct rad_handle *h, const void **value, size_t *lenp)
960 if (h->in_pos >= h->in_len)
962 if (h->in_pos + 2 > h->in_len) {
963 generr(h, "Malformed attribute in response");
966 type = h->in[h->in_pos++];
967 len = h->in[h->in_pos++];
969 generr(h, "Malformed attribute in response");
973 if (h->in_pos + len > h->in_len) {
974 generr(h, "Malformed attribute in response");
978 *value = &h->in[h->in_pos];
984 * Returns -1 on error, 0 to indicate no event and >0 for success
987 rad_init_send_request(struct rad_handle *h, int *fd, struct timeval *tv)
991 struct sockaddr_in sin;
993 if (h->type == RADIUS_SERVER) {
994 generr(h, "denied function call");
997 /* Make sure we have a socket to use */
999 if ((h->fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
1000 generr(h, "Cannot create socket: %s", strerror(errno));
1003 memset(&sin, 0, sizeof sin);
1004 sin.sin_len = sizeof sin;
1005 sin.sin_family = AF_INET;
1006 sin.sin_addr.s_addr = h->bindto;
1007 sin.sin_port = htons(0);
1008 if (bind(h->fd, (const struct sockaddr *)&sin,
1009 sizeof sin) == -1) {
1010 generr(h, "bind: %s", strerror(errno));
1017 if (h->out[POS_CODE] != RAD_ACCESS_REQUEST) {
1018 /* Make sure no password given */
1019 if (h->pass_pos || h->chap_pass) {
1020 generr(h, "User or Chap Password"
1021 " in accounting request");
1025 if (h->eap_msg == 0) {
1026 /* Make sure the user gave us a password */
1027 if (h->pass_pos == 0 && !h->chap_pass) {
1028 generr(h, "No User or Chap Password"
1029 " attributes given");
1032 if (h->pass_pos != 0 && h->chap_pass) {
1033 generr(h, "Both User and Chap Password"
1034 " attributes given");
1040 /* Fill in the length field in the message */
1041 h->out[POS_LENGTH] = h->out_len >> 8;
1042 h->out[POS_LENGTH+1] = h->out_len;
1046 for (srv = 0; srv < h->num_servers; srv++)
1047 h->servers[srv].num_tries = 0;
1048 /* Find a first good server. */
1049 for (srv = 0; srv < h->num_servers; srv++) {
1050 if (h->servers[srv].is_dead == 0)
1052 if (h->servers[srv].dead_time &&
1053 h->servers[srv].next_probe <= now) {
1054 h->servers[srv].is_dead = 0;
1060 /* If all servers was dead on the last probe, try from beginning */
1061 if (h->srv == h->num_servers) {
1062 for (srv = 0; srv < h->num_servers; srv++) {
1063 h->servers[srv].is_dead = 0;
1064 h->servers[srv].next_probe = 0;
1069 return rad_continue_send_request(h, 0, fd, tv);
1073 * Create and initialize a rad_handle structure, and return it to the
1074 * caller. Can fail only if the necessary memory cannot be allocated.
1075 * In that case, it returns NULL.
1080 struct rad_handle *h;
1082 h = (struct rad_handle *)malloc(sizeof(struct rad_handle));
1086 h->ident = arc4random();
1087 h->errmsg[0] = '\0';
1088 memset(h->pass, 0, sizeof h->pass);
1092 h->authentic_pos = 0;
1093 h->type = RADIUS_AUTH;
1096 h->bindto = INADDR_ANY;
1104 struct rad_handle *h;
1108 h->type = RADIUS_ACCT;
1113 rad_server_open(int fd)
1115 struct rad_handle *h;
1119 h->type = RADIUS_SERVER;
1128 return rad_auth_open();
1132 rad_put_addr(struct rad_handle *h, int type, struct in_addr addr)
1134 return rad_put_attr(h, type, &addr.s_addr, sizeof addr.s_addr);
1138 rad_put_addr6(struct rad_handle *h, int type, struct in6_addr addr)
1141 return rad_put_attr(h, type, &addr.s6_addr, sizeof addr.s6_addr);
1145 rad_put_attr(struct rad_handle *h, int type, const void *value, size_t len)
1149 if (!h->out_created) {
1150 generr(h, "Please call rad_create_request()"
1151 " before putting attributes");
1155 if (h->out[POS_CODE] == RAD_ACCOUNTING_REQUEST) {
1156 if (type == RAD_EAP_MESSAGE) {
1157 generr(h, "EAP-Message attribute is not valid"
1158 " in accounting requests");
1164 * When proxying EAP Messages, the Message Authenticator
1165 * MUST be present; see RFC 3579.
1167 if (type == RAD_EAP_MESSAGE) {
1168 if (rad_put_message_authentic(h) == -1)
1172 if (type == RAD_USER_PASSWORD) {
1173 result = put_password_attr(h, type, value, len);
1174 } else if (type == RAD_MESSAGE_AUTHENTIC) {
1175 result = rad_put_message_authentic(h);
1177 result = put_raw_attr(h, type, value, len);
1179 if (type == RAD_CHAP_PASSWORD)
1181 else if (type == RAD_EAP_MESSAGE)
1190 rad_put_int(struct rad_handle *h, int type, u_int32_t value)
1194 nvalue = htonl(value);
1195 return rad_put_attr(h, type, &nvalue, sizeof nvalue);
1199 rad_put_string(struct rad_handle *h, int type, const char *str)
1201 return rad_put_attr(h, type, str, strlen(str));
1205 rad_put_message_authentic(struct rad_handle *h)
1208 u_char md_zero[MD5_DIGEST_LENGTH];
1210 if (h->out[POS_CODE] == RAD_ACCOUNTING_REQUEST) {
1211 generr(h, "Message-Authenticator is not valid"
1212 " in accounting requests");
1216 if (h->authentic_pos == 0) {
1217 h->authentic_pos = h->out_len;
1218 memset(md_zero, 0, sizeof(md_zero));
1219 return (put_raw_attr(h, RAD_MESSAGE_AUTHENTIC, md_zero,
1224 generr(h, "Message Authenticator not supported,"
1225 " please recompile libradius with SSL support");
1231 * Returns the response type code on success, or -1 on failure.
1234 rad_send_request(struct rad_handle *h)
1236 struct timeval timelimit;
1241 n = rad_init_send_request(h, &fd, &tv);
1246 gettimeofday(&timelimit, NULL);
1247 timeradd(&tv, &timelimit, &timelimit);
1253 FD_SET(fd, &readfds);
1255 n = select(fd + 1, &readfds, NULL, NULL, &tv);
1258 generr(h, "select: %s", strerror(errno));
1262 if (!FD_ISSET(fd, &readfds)) {
1263 /* Compute a new timeout */
1264 gettimeofday(&tv, NULL);
1265 timersub(&timelimit, &tv, &tv);
1266 if (tv.tv_sec > 0 || (tv.tv_sec == 0 && tv.tv_usec > 0))
1267 /* Continue the select */
1271 n = rad_continue_send_request(h, n, &fd, &tv);
1276 gettimeofday(&timelimit, NULL);
1277 timeradd(&tv, &timelimit, &timelimit);
1282 rad_strerror(struct rad_handle *h)
1288 * Destructively split a string into fields separated by white space.
1289 * `#' at the beginning of a field begins a comment that extends to the
1290 * end of the string. Fields may be quoted with `"'. Inside quoted
1291 * strings, the backslash escapes `\"' and `\\' are honored.
1293 * Pointers to up to the first maxfields fields are stored in the fields
1294 * array. Missing fields get NULL pointers.
1296 * The return value is the actual number of fields parsed, and is always
1299 * On a syntax error, places a message in the msg string, and returns -1.
1302 split(char *str, char *fields[], int maxfields, char *msg, size_t msglen)
1306 static const char ws[] = " \t";
1308 for (i = 0; i < maxfields; i++)
1312 while (*p != '\0') {
1314 if (*p == '#' || *p == '\0')
1316 if (i >= maxfields) {
1317 snprintf(msg, msglen, "line has too many fields");
1328 if (*p != '"' && *p != '\\' &&
1330 snprintf(msg, msglen,
1331 "invalid `\\' escape");
1336 snprintf(msg, msglen,
1337 "unterminated quoted string");
1344 if (*fields[i] == '\0') {
1345 snprintf(msg, msglen,
1346 "empty quoted string not permitted");
1349 if (*p != '\0' && strspn(p, ws) == 0) {
1350 snprintf(msg, msglen, "quoted string not"
1351 " followed by white space");
1356 p += strcspn(p, ws);
1366 rad_get_vendor_attr(u_int32_t *vendor, const void **data, size_t *len)
1368 struct vendor_attribute *attr;
1370 attr = (struct vendor_attribute *)*data;
1371 *vendor = ntohl(attr->vendor_value);
1372 *data = attr->attrib_data;
1373 *len = attr->attrib_len - 2;
1375 return (attr->attrib_type);
1379 rad_put_vendor_addr(struct rad_handle *h, int vendor, int type,
1380 struct in_addr addr)
1382 return (rad_put_vendor_attr(h, vendor, type, &addr.s_addr,
1383 sizeof addr.s_addr));
1387 rad_put_vendor_addr6(struct rad_handle *h, int vendor, int type,
1388 struct in6_addr addr)
1391 return (rad_put_vendor_attr(h, vendor, type, &addr.s6_addr,
1392 sizeof addr.s6_addr));
1396 rad_put_vendor_attr(struct rad_handle *h, int vendor, int type,
1397 const void *value, size_t len)
1399 struct vendor_attribute *attr;
1402 if (!h->out_created) {
1403 generr(h, "Please call rad_create_request()"
1404 " before putting attributes");
1408 if ((attr = malloc(len + 6)) == NULL) {
1409 generr(h, "malloc failure (%zu bytes)", len + 6);
1413 attr->vendor_value = htonl(vendor);
1414 attr->attrib_type = type;
1415 attr->attrib_len = len + 2;
1416 memcpy(attr->attrib_data, value, len);
1418 res = put_raw_attr(h, RAD_VENDOR_SPECIFIC, attr, len + 6);
1420 if (res == 0 && vendor == RAD_VENDOR_MICROSOFT
1421 && (type == RAD_MICROSOFT_MS_CHAP_RESPONSE
1422 || type == RAD_MICROSOFT_MS_CHAP2_RESPONSE)) {
1429 rad_put_vendor_int(struct rad_handle *h, int vendor, int type, u_int32_t i)
1434 return (rad_put_vendor_attr(h, vendor, type, &value, sizeof value));
1438 rad_put_vendor_string(struct rad_handle *h, int vendor, int type,
1441 return (rad_put_vendor_attr(h, vendor, type, str, strlen(str)));
1445 rad_request_authenticator(struct rad_handle *h, char *buf, size_t len)
1449 memcpy(buf, h->out + POS_AUTH, LEN_AUTH);
1451 buf[LEN_AUTH] = '\0';
1456 rad_demangle(struct rad_handle *h, const void *mangled, size_t mlen)
1462 u_char b[MD5_DIGEST_LENGTH], *C, *demangled;
1464 if ((mlen % 16 != 0) || mlen > 128) {
1465 generr(h, "Cannot interpret mangled data of length %lu",
1470 C = (u_char *)mangled;
1472 /* We need the shared secret as Salt */
1473 S = rad_server_secret(h);
1475 /* We need the request authenticator */
1476 if (rad_request_authenticator(h, R, sizeof R) != LEN_AUTH) {
1477 generr(h, "Cannot obtain the RADIUS request authenticator");
1481 demangled = malloc(mlen);
1486 MD5Update(&Context, S, strlen(S));
1487 MD5Update(&Context, R, LEN_AUTH);
1488 MD5Final(b, &Context);
1493 for (i = 0; i < 16; i++)
1494 demangled[Ppos++] = C[i] ^ b[i];
1498 MD5Update(&Context, S, strlen(S));
1499 MD5Update(&Context, C, 16);
1500 MD5Final(b, &Context);
1510 rad_demangle_mppe_key(struct rad_handle *h, const void *mangled,
1511 size_t mlen, size_t *len)
1513 char R[LEN_AUTH]; /* variable names as per rfc2548 */
1515 u_char b[MD5_DIGEST_LENGTH], *demangled;
1516 const u_char *A, *C;
1518 int Slen, i, Clen, Ppos;
1521 if (mlen % 16 != SALT_LEN) {
1522 generr(h, "Cannot interpret mangled data of length %lu",
1527 /* We need the RADIUS Request-Authenticator */
1528 if (rad_request_authenticator(h, R, sizeof R) != LEN_AUTH) {
1529 generr(h, "Cannot obtain the RADIUS request authenticator");
1533 A = (const u_char *)mangled; /* Salt comes first */
1534 C = (const u_char *)mangled + SALT_LEN; /* Then the ciphertext */
1535 Clen = mlen - SALT_LEN;
1536 S = rad_server_secret(h); /* We need the RADIUS secret */
1538 P = alloca(Clen); /* We derive our plaintext */
1541 MD5Update(&Context, S, Slen);
1542 MD5Update(&Context, R, LEN_AUTH);
1543 MD5Update(&Context, A, SALT_LEN);
1544 MD5Final(b, &Context);
1550 for (i = 0; i < 16; i++)
1551 P[Ppos++] = C[i] ^ b[i];
1555 MD5Update(&Context, S, Slen);
1556 MD5Update(&Context, C, 16);
1557 MD5Final(b, &Context);
1564 * The resulting plain text consists of a one-byte length, the text and
1565 * maybe some padding.
1568 if (*len > mlen - 1) {
1569 generr(h, "Mangled data seems to be garbage %zu %zu",
1574 if (*len > MPPE_KEY_LEN * 2) {
1575 generr(h, "Key to long (%zu) for me max. %d",
1576 *len, MPPE_KEY_LEN * 2);
1579 demangled = malloc(*len);
1583 memcpy(demangled, P + 1, *len);
1588 rad_server_secret(struct rad_handle *h)
1590 return (h->servers[h->srv].secret);