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;
293 u_char resp[MSGSIZE], md[EVP_MAX_MD_SIZE];
298 srvp = &h->servers[h->srv];
300 /* Check the message length */
301 if (h->in_len < POS_ATTRS)
303 len = (h->in[POS_LENGTH] << 8) | h->in[POS_LENGTH + 1];
304 if (len < POS_ATTRS || len > h->in_len)
307 if (h->in[POS_CODE] != RAD_ACCESS_REQUEST) {
308 uint32_t zeroes[4] = { 0, 0, 0, 0 };
309 /* Check the request authenticator */
311 MD5Update(&ctx, &h->in[POS_CODE], POS_AUTH - POS_CODE);
312 MD5Update(&ctx, zeroes, LEN_AUTH);
313 MD5Update(&ctx, &h->in[POS_ATTRS], len - POS_ATTRS);
314 MD5Update(&ctx, srvp->secret, strlen(srvp->secret));
316 if (memcmp(&h->in[POS_AUTH], md5, sizeof md5) != 0)
321 /* Search and verify the Message-Authenticator */
323 hctx = HMAC_CTX_new();
324 while (pos < len - 2) {
325 alen = h->in[pos + 1];
328 if (h->in[pos] == RAD_MESSAGE_AUTHENTIC) {
329 if (len - pos < MD5_DIGEST_LENGTH + 2) {
333 if (alen < MD5_DIGEST_LENGTH + 2) {
337 memcpy(resp, h->in, MSGSIZE);
338 /* zero fill the Request-Authenticator */
339 if (h->in[POS_CODE] != RAD_ACCESS_REQUEST)
340 memset(&resp[POS_AUTH], 0, LEN_AUTH);
341 /* zero fill the Message-Authenticator */
342 memset(&resp[pos + 2], 0, MD5_DIGEST_LENGTH);
344 HMAC_Init_ex(hctx, srvp->secret,
345 strlen(srvp->secret), EVP_md5(), NULL);
346 HMAC_Update(hctx, resp, h->in_len);
347 HMAC_Final(hctx, md, &md_len);
348 HMAC_CTX_reset(hctx);
349 if (memcmp(md, &h->in[pos + 2],
350 MD5_DIGEST_LENGTH) != 0) {
364 put_password_attr(struct rad_handle *h, int type, const void *value, size_t len)
369 if (h->pass_pos != 0) {
370 generr(h, "Multiple User-Password attributes specified");
375 padded_len = len == 0 ? 16 : (len+15) & ~0xf;
376 pad_len = padded_len - len;
379 * Put in a place-holder attribute containing all zeros, and
380 * remember where it is so we can fill it in later.
383 put_raw_attr(h, type, h->pass, padded_len);
384 h->pass_pos = h->out_len - padded_len;
386 /* Save the cleartext password, padded as necessary */
387 memcpy(h->pass, value, len);
389 memset(h->pass + len, 0, pad_len);
394 put_raw_attr(struct rad_handle *h, int type, const void *value, size_t len)
397 generr(h, "Attribute too long");
400 if (h->out_len + 2 + len > MSGSIZE) {
401 generr(h, "Maximum message length exceeded");
404 h->out[h->out_len++] = type;
405 h->out[h->out_len++] = len + 2;
406 memcpy(&h->out[h->out_len], value, len);
412 rad_add_server(struct rad_handle *h, const char *host, int port,
413 const char *secret, int timeout, int tries)
415 struct in_addr bindto;
416 bindto.s_addr = INADDR_ANY;
418 return rad_add_server_ex(h, host, port, secret, timeout, tries,
423 rad_add_server_ex(struct rad_handle *h, const char *host, int port,
424 const char *secret, int timeout, int tries, int dead_time,
425 struct in_addr *bindto)
427 struct rad_server *srvp;
429 if (h->num_servers >= MAXSERVERS) {
430 generr(h, "Too many RADIUS servers specified");
433 srvp = &h->servers[h->num_servers];
435 memset(&srvp->addr, 0, sizeof srvp->addr);
436 srvp->addr.sin_len = sizeof srvp->addr;
437 srvp->addr.sin_family = AF_INET;
438 if (!inet_aton(host, &srvp->addr.sin_addr)) {
439 struct hostent *hent;
441 if ((hent = gethostbyname(host)) == NULL) {
442 generr(h, "%s: host not found", host);
445 memcpy(&srvp->addr.sin_addr, hent->h_addr,
446 sizeof srvp->addr.sin_addr);
449 srvp->addr.sin_port = htons((u_short)port);
451 struct servent *sent;
453 if (h->type == RADIUS_AUTH)
454 srvp->addr.sin_port =
455 (sent = getservbyname("radius", "udp")) != NULL ?
456 sent->s_port : htons(RADIUS_PORT);
458 srvp->addr.sin_port =
459 (sent = getservbyname("radacct", "udp")) != NULL ?
460 sent->s_port : htons(RADACCT_PORT);
462 if ((srvp->secret = strdup(secret)) == NULL) {
463 generr(h, "Out of memory");
466 srvp->timeout = timeout;
467 srvp->max_tries = tries;
470 srvp->dead_time = dead_time;
471 srvp->next_probe = 0;
472 srvp->bindto = bindto->s_addr;
478 rad_close(struct rad_handle *h)
484 for (srv = 0; srv < h->num_servers; srv++) {
485 memset(h->servers[srv].secret, 0,
486 strlen(h->servers[srv].secret));
487 free(h->servers[srv].secret);
494 rad_bind_to(struct rad_handle *h, in_addr_t addr)
501 rad_config(struct rad_handle *h, const char *path)
504 char buf[MAXCONFLINE];
509 path = PATH_RADIUS_CONF;
510 if ((fp = fopen(path, "r")) == NULL) {
511 generr(h, "Cannot open \"%s\": %s", path, strerror(errno));
516 while (fgets(buf, sizeof buf, fp) != NULL) {
518 char *fields[MAX_FIELDS];
531 unsigned long timeout;
532 unsigned long maxtries;
533 unsigned long dead_time;
535 struct in_addr bindto;
540 /* We know len > 0, else fgets would have returned NULL. */
541 if (buf[len - 1] != '\n') {
542 if (len == sizeof buf - 1)
543 generr(h, "%s:%d: line too long", path,
546 generr(h, "%s:%d: missing newline", path,
553 /* Extract the fields from the line. */
554 nfields = split(buf, fields, MAX_FIELDS, msg, sizeof msg);
556 generr(h, "%s:%d: %s", path, linenum, msg);
563 * The first field should contain "auth" or "acct" for
564 * authentication or accounting, respectively. But older
565 * versions of the file didn't have that field. Default
566 * it to "auth" for backward compatibility.
568 if (strcmp(fields[0], "auth") != 0 &&
569 strcmp(fields[0], "acct") != 0) {
570 if (nfields >= MAX_FIELDS) {
571 generr(h, "%s:%d: invalid service type", path,
577 for (i = nfields; --i > 0; )
578 fields[i] = fields[i - 1];
582 generr(h, "%s:%d: missing shared secret", path,
590 timeout_str = fields[3];
591 maxtries_str = fields[4];
592 dead_time_str = fields[5];
593 bindto_str = fields[6];
595 /* Ignore the line if it is for the wrong service type. */
596 wanttype = h->type == RADIUS_AUTH ? "auth" : "acct";
597 if (strcmp(type, wanttype) != 0)
600 /* Parse and validate the fields. */
602 host = strsep(&res, ":");
603 port_str = strsep(&res, ":");
604 if (port_str != NULL) {
605 port = strtoul(port_str, &end, 10);
607 generr(h, "%s:%d: invalid port", path,
614 if (timeout_str != NULL) {
615 timeout = strtoul(timeout_str, &end, 10);
617 generr(h, "%s:%d: invalid timeout", path,
624 if (maxtries_str != NULL) {
625 maxtries = strtoul(maxtries_str, &end, 10);
627 generr(h, "%s:%d: invalid maxtries", path,
635 if (dead_time_str != NULL) {
636 dead_time = strtoul(dead_time_str, &end, 10);
638 generr(h, "%s:%d: invalid dead_time", path,
644 dead_time = DEAD_TIME;
646 if (bindto_str != NULL) {
647 bindto.s_addr = inet_addr(bindto_str);
648 if (bindto.s_addr == INADDR_NONE) {
649 generr(h, "%s:%d: invalid bindto", path,
655 bindto.s_addr = INADDR_ANY;
657 if (rad_add_server_ex(h, host, port, secret, timeout, maxtries,
658 dead_time, &bindto) == -1) {
659 strcpy(msg, h->errmsg);
660 generr(h, "%s:%d: %s", path, linenum, msg);
665 /* Clear out the buffer to wipe a possible copy of a shared secret */
666 memset(buf, 0, sizeof buf);
672 * rad_init_send_request() must have previously been called.
674 * 0 The application should select on *fd with a timeout of tv before
675 * calling rad_continue_send_request again.
680 rad_continue_send_request(struct rad_handle *h, int selected, int *fd,
685 struct sockaddr_in sin;
687 if (h->type == RADIUS_SERVER) {
688 generr(h, "denied function call");
692 struct sockaddr_in from;
695 fromlen = sizeof from;
696 h->in_len = recvfrom(h->fd, h->in,
697 MSGSIZE, MSG_WAITALL, (struct sockaddr *)&from, &fromlen);
698 if (h->in_len == -1) {
699 generr(h, "recvfrom: %s", strerror(errno));
702 if (is_valid_response(h, h->srv, &from)) {
703 h->in_len = h->in[POS_LENGTH] << 8 |
705 h->in_pos = POS_ATTRS;
706 return h->in[POS_CODE];
711 * Scan round-robin to the next server that has some
712 * tries left. There is guaranteed to be one, or we
713 * would have exited this loop by now.
717 if (h->servers[h->srv].num_tries >= h->servers[h->srv].max_tries) {
718 /* Set next probe time for this server */
719 if (h->servers[h->srv].dead_time) {
720 h->servers[h->srv].is_dead = 1;
721 h->servers[h->srv].next_probe = now +
722 h->servers[h->srv].dead_time;
726 if (h->srv >= h->num_servers)
728 if (h->servers[h->srv].is_dead == 0)
730 if (h->servers[h->srv].dead_time &&
731 h->servers[h->srv].next_probe <= now) {
732 h->servers[h->srv].is_dead = 0;
733 h->servers[h->srv].num_tries = 0;
736 } while (h->srv != cur_srv);
738 if (h->srv == cur_srv) {
739 generr(h, "No valid RADIUS responses received");
745 if (h->bindto != h->servers[h->srv].bindto) {
746 h->bindto = h->servers[h->srv].bindto;
748 if ((h->fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
749 generr(h, "Cannot create socket: %s", strerror(errno));
752 memset(&sin, 0, sizeof sin);
753 sin.sin_len = sizeof sin;
754 sin.sin_family = AF_INET;
755 sin.sin_addr.s_addr = h->bindto;
757 if (bind(h->fd, (const struct sockaddr *)&sin,
759 generr(h, "bind: %s", strerror(errno));
766 if (h->out[POS_CODE] == RAD_ACCESS_REQUEST) {
767 /* Insert the scrambled password into the request */
768 if (h->pass_pos != 0)
769 insert_scrambled_password(h, h->srv);
771 insert_message_authenticator(h, 0);
773 if (h->out[POS_CODE] != RAD_ACCESS_REQUEST) {
774 /* Insert the request authenticator into the request */
775 memset(&h->out[POS_AUTH], 0, LEN_AUTH);
776 insert_request_authenticator(h, 0);
779 /* Send the request */
780 n = sendto(h->fd, h->out, h->out_len, 0,
781 (const struct sockaddr *)&h->servers[h->srv].addr,
782 sizeof h->servers[h->srv].addr);
784 tv->tv_sec = 1; /* Do not wait full timeout if send failed. */
786 tv->tv_sec = h->servers[h->srv].timeout;
787 h->servers[h->srv].num_tries++;
795 rad_receive_request(struct rad_handle *h)
797 struct sockaddr_in from;
801 if (h->type != RADIUS_SERVER) {
802 generr(h, "denied function call");
806 fromlen = sizeof(from);
807 h->in_len = recvfrom(h->fd, h->in,
808 MSGSIZE, MSG_WAITALL, (struct sockaddr *)&from, &fromlen);
809 if (h->in_len == -1) {
810 generr(h, "recvfrom: %s", strerror(errno));
813 for (n = 0; n < h->num_servers; n++) {
814 if (h->servers[n].addr.sin_addr.s_addr == from.sin_addr.s_addr) {
815 h->servers[n].addr.sin_port = from.sin_port;
822 if (is_valid_request(h)) {
823 h->in_len = h->in[POS_LENGTH] << 8 |
825 h->in_pos = POS_ATTRS;
826 return (h->in[POS_CODE]);
832 rad_send_response(struct rad_handle *h)
836 if (h->type != RADIUS_SERVER) {
837 generr(h, "denied function call");
840 /* Fill in the length field in the message */
841 h->out[POS_LENGTH] = h->out_len >> 8;
842 h->out[POS_LENGTH+1] = h->out_len;
844 insert_message_authenticator(h,
845 (h->in[POS_CODE] == RAD_ACCESS_REQUEST) ? 1 : 0);
846 insert_request_authenticator(h, 1);
848 /* Send the request */
849 n = sendto(h->fd, h->out, h->out_len, 0,
850 (const struct sockaddr *)&h->servers[h->srv].addr,
851 sizeof h->servers[h->srv].addr);
852 if (n != h->out_len) {
854 generr(h, "sendto: %s", strerror(errno));
856 generr(h, "sendto: short write");
864 rad_create_request(struct rad_handle *h, int code)
868 if (h->type == RADIUS_SERVER) {
869 generr(h, "denied function call");
872 if (h->num_servers == 0) {
873 generr(h, "No RADIUS servers specified");
876 h->out[POS_CODE] = code;
877 h->out[POS_IDENT] = ++h->ident;
878 if (code == RAD_ACCESS_REQUEST) {
879 /* Create a random authenticator */
880 for (i = 0; i < LEN_AUTH; i += 2) {
883 h->out[POS_AUTH+i] = (u_char)r;
884 h->out[POS_AUTH+i+1] = (u_char)(r >> 8);
887 memset(&h->out[POS_AUTH], 0, LEN_AUTH);
888 h->out_len = POS_ATTRS;
890 h->authentic_pos = 0;
896 rad_create_response(struct rad_handle *h, int code)
899 if (h->type != RADIUS_SERVER) {
900 generr(h, "denied function call");
903 h->out[POS_CODE] = code;
904 h->out[POS_IDENT] = h->in[POS_IDENT];
905 memset(&h->out[POS_AUTH], 0, LEN_AUTH);
906 h->out_len = POS_ATTRS;
908 h->authentic_pos = 0;
914 rad_cvt_addr(const void *data)
916 struct in_addr value;
918 memcpy(&value.s_addr, data, sizeof value.s_addr);
923 rad_cvt_addr6(const void *data)
925 struct in6_addr value;
927 memcpy(&value.s6_addr, data, sizeof value.s6_addr);
932 rad_cvt_int(const void *data)
936 memcpy(&value, data, sizeof value);
941 rad_cvt_string(const void *data, size_t len)
947 memcpy(s, data, len);
954 * Returns the attribute type. If none are left, returns 0. On failure,
958 rad_get_attr(struct rad_handle *h, const void **value, size_t *lenp)
962 if (h->in_pos >= h->in_len)
964 if (h->in_pos + 2 > h->in_len) {
965 generr(h, "Malformed attribute in response");
968 type = h->in[h->in_pos++];
969 len = h->in[h->in_pos++];
971 generr(h, "Malformed attribute in response");
975 if (h->in_pos + len > h->in_len) {
976 generr(h, "Malformed attribute in response");
980 *value = &h->in[h->in_pos];
986 * Returns -1 on error, 0 to indicate no event and >0 for success
989 rad_init_send_request(struct rad_handle *h, int *fd, struct timeval *tv)
993 struct sockaddr_in sin;
995 if (h->type == RADIUS_SERVER) {
996 generr(h, "denied function call");
999 /* Make sure we have a socket to use */
1001 if ((h->fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
1002 generr(h, "Cannot create socket: %s", strerror(errno));
1005 memset(&sin, 0, sizeof sin);
1006 sin.sin_len = sizeof sin;
1007 sin.sin_family = AF_INET;
1008 sin.sin_addr.s_addr = h->bindto;
1009 sin.sin_port = htons(0);
1010 if (bind(h->fd, (const struct sockaddr *)&sin,
1011 sizeof sin) == -1) {
1012 generr(h, "bind: %s", strerror(errno));
1019 if (h->out[POS_CODE] != RAD_ACCESS_REQUEST) {
1020 /* Make sure no password given */
1021 if (h->pass_pos || h->chap_pass) {
1022 generr(h, "User or Chap Password"
1023 " in accounting request");
1027 if (h->eap_msg == 0) {
1028 /* Make sure the user gave us a password */
1029 if (h->pass_pos == 0 && !h->chap_pass) {
1030 generr(h, "No User or Chap Password"
1031 " attributes given");
1034 if (h->pass_pos != 0 && h->chap_pass) {
1035 generr(h, "Both User and Chap Password"
1036 " attributes given");
1042 /* Fill in the length field in the message */
1043 h->out[POS_LENGTH] = h->out_len >> 8;
1044 h->out[POS_LENGTH+1] = h->out_len;
1048 for (srv = 0; srv < h->num_servers; srv++)
1049 h->servers[srv].num_tries = 0;
1050 /* Find a first good server. */
1051 for (srv = 0; srv < h->num_servers; srv++) {
1052 if (h->servers[srv].is_dead == 0)
1054 if (h->servers[srv].dead_time &&
1055 h->servers[srv].next_probe <= now) {
1056 h->servers[srv].is_dead = 0;
1062 /* If all servers was dead on the last probe, try from beginning */
1063 if (h->srv == h->num_servers) {
1064 for (srv = 0; srv < h->num_servers; srv++) {
1065 h->servers[srv].is_dead = 0;
1066 h->servers[srv].next_probe = 0;
1071 return rad_continue_send_request(h, 0, fd, tv);
1075 * Create and initialize a rad_handle structure, and return it to the
1076 * caller. Can fail only if the necessary memory cannot be allocated.
1077 * In that case, it returns NULL.
1082 struct rad_handle *h;
1084 h = (struct rad_handle *)malloc(sizeof(struct rad_handle));
1088 h->ident = arc4random();
1089 h->errmsg[0] = '\0';
1090 memset(h->pass, 0, sizeof h->pass);
1094 h->authentic_pos = 0;
1095 h->type = RADIUS_AUTH;
1098 h->bindto = INADDR_ANY;
1106 struct rad_handle *h;
1110 h->type = RADIUS_ACCT;
1115 rad_server_open(int fd)
1117 struct rad_handle *h;
1121 h->type = RADIUS_SERVER;
1130 return rad_auth_open();
1134 rad_put_addr(struct rad_handle *h, int type, struct in_addr addr)
1136 return rad_put_attr(h, type, &addr.s_addr, sizeof addr.s_addr);
1140 rad_put_addr6(struct rad_handle *h, int type, struct in6_addr addr)
1143 return rad_put_attr(h, type, &addr.s6_addr, sizeof addr.s6_addr);
1147 rad_put_attr(struct rad_handle *h, int type, const void *value, size_t len)
1151 if (!h->out_created) {
1152 generr(h, "Please call rad_create_request()"
1153 " before putting attributes");
1157 if (h->out[POS_CODE] == RAD_ACCOUNTING_REQUEST) {
1158 if (type == RAD_EAP_MESSAGE) {
1159 generr(h, "EAP-Message attribute is not valid"
1160 " in accounting requests");
1166 * When proxying EAP Messages, the Message Authenticator
1167 * MUST be present; see RFC 3579.
1169 if (type == RAD_EAP_MESSAGE) {
1170 if (rad_put_message_authentic(h) == -1)
1174 if (type == RAD_USER_PASSWORD) {
1175 result = put_password_attr(h, type, value, len);
1176 } else if (type == RAD_MESSAGE_AUTHENTIC) {
1177 result = rad_put_message_authentic(h);
1179 result = put_raw_attr(h, type, value, len);
1181 if (type == RAD_CHAP_PASSWORD)
1183 else if (type == RAD_EAP_MESSAGE)
1192 rad_put_int(struct rad_handle *h, int type, u_int32_t value)
1196 nvalue = htonl(value);
1197 return rad_put_attr(h, type, &nvalue, sizeof nvalue);
1201 rad_put_string(struct rad_handle *h, int type, const char *str)
1203 return rad_put_attr(h, type, str, strlen(str));
1207 rad_put_message_authentic(struct rad_handle *h)
1210 u_char md_zero[MD5_DIGEST_LENGTH];
1212 if (h->out[POS_CODE] == RAD_ACCOUNTING_REQUEST) {
1213 generr(h, "Message-Authenticator is not valid"
1214 " in accounting requests");
1218 if (h->authentic_pos == 0) {
1219 h->authentic_pos = h->out_len;
1220 memset(md_zero, 0, sizeof(md_zero));
1221 return (put_raw_attr(h, RAD_MESSAGE_AUTHENTIC, md_zero,
1226 generr(h, "Message Authenticator not supported,"
1227 " please recompile libradius with SSL support");
1233 * Returns the response type code on success, or -1 on failure.
1236 rad_send_request(struct rad_handle *h)
1238 struct timeval timelimit;
1243 n = rad_init_send_request(h, &fd, &tv);
1248 gettimeofday(&timelimit, NULL);
1249 timeradd(&tv, &timelimit, &timelimit);
1255 FD_SET(fd, &readfds);
1257 n = select(fd + 1, &readfds, NULL, NULL, &tv);
1260 generr(h, "select: %s", strerror(errno));
1264 if (!FD_ISSET(fd, &readfds)) {
1265 /* Compute a new timeout */
1266 gettimeofday(&tv, NULL);
1267 timersub(&timelimit, &tv, &tv);
1268 if (tv.tv_sec > 0 || (tv.tv_sec == 0 && tv.tv_usec > 0))
1269 /* Continue the select */
1273 n = rad_continue_send_request(h, n, &fd, &tv);
1278 gettimeofday(&timelimit, NULL);
1279 timeradd(&tv, &timelimit, &timelimit);
1284 rad_strerror(struct rad_handle *h)
1290 * Destructively split a string into fields separated by white space.
1291 * `#' at the beginning of a field begins a comment that extends to the
1292 * end of the string. Fields may be quoted with `"'. Inside quoted
1293 * strings, the backslash escapes `\"' and `\\' are honored.
1295 * Pointers to up to the first maxfields fields are stored in the fields
1296 * array. Missing fields get NULL pointers.
1298 * The return value is the actual number of fields parsed, and is always
1301 * On a syntax error, places a message in the msg string, and returns -1.
1304 split(char *str, char *fields[], int maxfields, char *msg, size_t msglen)
1308 static const char ws[] = " \t";
1310 for (i = 0; i < maxfields; i++)
1314 while (*p != '\0') {
1316 if (*p == '#' || *p == '\0')
1318 if (i >= maxfields) {
1319 snprintf(msg, msglen, "line has too many fields");
1330 if (*p != '"' && *p != '\\' &&
1332 snprintf(msg, msglen,
1333 "invalid `\\' escape");
1338 snprintf(msg, msglen,
1339 "unterminated quoted string");
1346 if (*fields[i] == '\0') {
1347 snprintf(msg, msglen,
1348 "empty quoted string not permitted");
1351 if (*p != '\0' && strspn(p, ws) == 0) {
1352 snprintf(msg, msglen, "quoted string not"
1353 " followed by white space");
1358 p += strcspn(p, ws);
1368 rad_get_vendor_attr(u_int32_t *vendor, const void **data, size_t *len)
1370 struct vendor_attribute *attr;
1372 attr = (struct vendor_attribute *)*data;
1373 *vendor = ntohl(attr->vendor_value);
1374 *data = attr->attrib_data;
1375 *len = attr->attrib_len - 2;
1377 return (attr->attrib_type);
1381 rad_put_vendor_addr(struct rad_handle *h, int vendor, int type,
1382 struct in_addr addr)
1384 return (rad_put_vendor_attr(h, vendor, type, &addr.s_addr,
1385 sizeof addr.s_addr));
1389 rad_put_vendor_addr6(struct rad_handle *h, int vendor, int type,
1390 struct in6_addr addr)
1393 return (rad_put_vendor_attr(h, vendor, type, &addr.s6_addr,
1394 sizeof addr.s6_addr));
1398 rad_put_vendor_attr(struct rad_handle *h, int vendor, int type,
1399 const void *value, size_t len)
1401 struct vendor_attribute *attr;
1404 if (!h->out_created) {
1405 generr(h, "Please call rad_create_request()"
1406 " before putting attributes");
1410 if ((attr = malloc(len + 6)) == NULL) {
1411 generr(h, "malloc failure (%zu bytes)", len + 6);
1415 attr->vendor_value = htonl(vendor);
1416 attr->attrib_type = type;
1417 attr->attrib_len = len + 2;
1418 memcpy(attr->attrib_data, value, len);
1420 res = put_raw_attr(h, RAD_VENDOR_SPECIFIC, attr, len + 6);
1422 if (res == 0 && vendor == RAD_VENDOR_MICROSOFT
1423 && (type == RAD_MICROSOFT_MS_CHAP_RESPONSE
1424 || type == RAD_MICROSOFT_MS_CHAP2_RESPONSE)) {
1431 rad_put_vendor_int(struct rad_handle *h, int vendor, int type, u_int32_t i)
1436 return (rad_put_vendor_attr(h, vendor, type, &value, sizeof value));
1440 rad_put_vendor_string(struct rad_handle *h, int vendor, int type,
1443 return (rad_put_vendor_attr(h, vendor, type, str, strlen(str)));
1447 rad_request_authenticator(struct rad_handle *h, char *buf, size_t len)
1451 memcpy(buf, h->out + POS_AUTH, LEN_AUTH);
1453 buf[LEN_AUTH] = '\0';
1458 rad_demangle(struct rad_handle *h, const void *mangled, size_t mlen)
1464 u_char b[MD5_DIGEST_LENGTH], *C, *demangled;
1466 if ((mlen % 16 != 0) || mlen > 128) {
1467 generr(h, "Cannot interpret mangled data of length %lu",
1472 C = (u_char *)mangled;
1474 /* We need the shared secret as Salt */
1475 S = rad_server_secret(h);
1477 /* We need the request authenticator */
1478 if (rad_request_authenticator(h, R, sizeof R) != LEN_AUTH) {
1479 generr(h, "Cannot obtain the RADIUS request authenticator");
1483 demangled = malloc(mlen);
1488 MD5Update(&Context, S, strlen(S));
1489 MD5Update(&Context, R, LEN_AUTH);
1490 MD5Final(b, &Context);
1495 for (i = 0; i < 16; i++)
1496 demangled[Ppos++] = C[i] ^ b[i];
1500 MD5Update(&Context, S, strlen(S));
1501 MD5Update(&Context, C, 16);
1502 MD5Final(b, &Context);
1512 rad_demangle_mppe_key(struct rad_handle *h, const void *mangled,
1513 size_t mlen, size_t *len)
1515 char R[LEN_AUTH]; /* variable names as per rfc2548 */
1517 u_char b[MD5_DIGEST_LENGTH], *demangled;
1518 const u_char *A, *C;
1520 int Slen, i, Clen, Ppos;
1523 if (mlen % 16 != SALT_LEN) {
1524 generr(h, "Cannot interpret mangled data of length %lu",
1529 /* We need the RADIUS Request-Authenticator */
1530 if (rad_request_authenticator(h, R, sizeof R) != LEN_AUTH) {
1531 generr(h, "Cannot obtain the RADIUS request authenticator");
1535 A = (const u_char *)mangled; /* Salt comes first */
1536 C = (const u_char *)mangled + SALT_LEN; /* Then the ciphertext */
1537 Clen = mlen - SALT_LEN;
1538 S = rad_server_secret(h); /* We need the RADIUS secret */
1540 P = alloca(Clen); /* We derive our plaintext */
1543 MD5Update(&Context, S, Slen);
1544 MD5Update(&Context, R, LEN_AUTH);
1545 MD5Update(&Context, A, SALT_LEN);
1546 MD5Final(b, &Context);
1552 for (i = 0; i < 16; i++)
1553 P[Ppos++] = C[i] ^ b[i];
1557 MD5Update(&Context, S, Slen);
1558 MD5Update(&Context, C, 16);
1559 MD5Final(b, &Context);
1566 * The resulting plain text consists of a one-byte length, the text and
1567 * maybe some padding.
1570 if (*len > mlen - 1) {
1571 generr(h, "Mangled data seems to be garbage %zu %zu",
1576 if (*len > MPPE_KEY_LEN * 2) {
1577 generr(h, "Key to long (%zu) for me max. %d",
1578 *len, MPPE_KEY_LEN * 2);
1581 demangled = malloc(*len);
1585 memcpy(demangled, P + 1, *len);
1590 rad_server_secret(struct rad_handle *h)
1592 return (h->servers[h->srv].secret);