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];
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;
290 u_char resp[MSGSIZE], md[EVP_MAX_MD_SIZE];
295 srvp = &h->servers[h->srv];
297 /* Check the message length */
298 if (h->in_len < POS_ATTRS)
300 len = (h->in[POS_LENGTH] << 8) | h->in[POS_LENGTH + 1];
301 if (len < POS_ATTRS || len > h->in_len)
304 if (h->in[POS_CODE] != RAD_ACCESS_REQUEST) {
305 uint32_t zeroes[4] = { 0, 0, 0, 0 };
306 /* Check the request authenticator */
308 MD5Update(&ctx, &h->in[POS_CODE], POS_AUTH - POS_CODE);
309 MD5Update(&ctx, zeroes, LEN_AUTH);
310 MD5Update(&ctx, &h->in[POS_ATTRS], len - POS_ATTRS);
311 MD5Update(&ctx, srvp->secret, strlen(srvp->secret));
313 if (memcmp(&h->in[POS_AUTH], md5, sizeof md5) != 0)
318 /* Search and verify the Message-Authenticator */
320 hctx = HMAC_CTX_new();
321 while (pos < len - 2) {
322 alen = h->in[pos + 1];
325 if (h->in[pos] == RAD_MESSAGE_AUTHENTIC) {
326 if (len - pos < MD5_DIGEST_LENGTH + 2) {
330 if (alen < MD5_DIGEST_LENGTH + 2) {
334 memcpy(resp, h->in, MSGSIZE);
335 /* zero fill the Request-Authenticator */
336 if (h->in[POS_CODE] != RAD_ACCESS_REQUEST)
337 memset(&resp[POS_AUTH], 0, LEN_AUTH);
338 /* zero fill the Message-Authenticator */
339 memset(&resp[pos + 2], 0, MD5_DIGEST_LENGTH);
341 HMAC_Init_ex(hctx, srvp->secret,
342 strlen(srvp->secret), EVP_md5(), NULL);
343 HMAC_Update(hctx, resp, h->in_len);
344 HMAC_Final(hctx, md, &md_len);
345 HMAC_CTX_reset(hctx);
346 if (memcmp(md, &h->in[pos + 2],
347 MD5_DIGEST_LENGTH) != 0) {
361 put_password_attr(struct rad_handle *h, int type, const void *value, size_t len)
366 if (h->pass_pos != 0) {
367 generr(h, "Multiple User-Password attributes specified");
372 padded_len = len == 0 ? 16 : (len+15) & ~0xf;
373 pad_len = padded_len - len;
376 * Put in a place-holder attribute containing all zeros, and
377 * remember where it is so we can fill it in later.
380 put_raw_attr(h, type, h->pass, padded_len);
381 h->pass_pos = h->out_len - padded_len;
383 /* Save the cleartext password, padded as necessary */
384 memcpy(h->pass, value, len);
386 memset(h->pass + len, 0, pad_len);
391 put_raw_attr(struct rad_handle *h, int type, const void *value, size_t len)
394 generr(h, "Attribute too long");
397 if (h->out_len + 2 + len > MSGSIZE) {
398 generr(h, "Maximum message length exceeded");
401 h->out[h->out_len++] = type;
402 h->out[h->out_len++] = len + 2;
403 memcpy(&h->out[h->out_len], value, len);
409 rad_add_server(struct rad_handle *h, const char *host, int port,
410 const char *secret, int timeout, int tries)
412 struct in_addr bindto;
413 bindto.s_addr = INADDR_ANY;
415 return rad_add_server_ex(h, host, port, secret, timeout, tries,
420 rad_add_server_ex(struct rad_handle *h, const char *host, int port,
421 const char *secret, int timeout, int tries, int dead_time,
422 struct in_addr *bindto)
424 struct rad_server *srvp;
426 if (h->num_servers >= MAXSERVERS) {
427 generr(h, "Too many RADIUS servers specified");
430 srvp = &h->servers[h->num_servers];
432 memset(&srvp->addr, 0, sizeof srvp->addr);
433 srvp->addr.sin_len = sizeof srvp->addr;
434 srvp->addr.sin_family = AF_INET;
435 if (!inet_aton(host, &srvp->addr.sin_addr)) {
436 struct hostent *hent;
438 if ((hent = gethostbyname(host)) == NULL) {
439 generr(h, "%s: host not found", host);
442 memcpy(&srvp->addr.sin_addr, hent->h_addr,
443 sizeof srvp->addr.sin_addr);
446 srvp->addr.sin_port = htons((u_short)port);
448 struct servent *sent;
450 if (h->type == RADIUS_AUTH)
451 srvp->addr.sin_port =
452 (sent = getservbyname("radius", "udp")) != NULL ?
453 sent->s_port : htons(RADIUS_PORT);
455 srvp->addr.sin_port =
456 (sent = getservbyname("radacct", "udp")) != NULL ?
457 sent->s_port : htons(RADACCT_PORT);
459 if ((srvp->secret = strdup(secret)) == NULL) {
460 generr(h, "Out of memory");
463 srvp->timeout = timeout;
464 srvp->max_tries = tries;
467 srvp->dead_time = dead_time;
468 srvp->next_probe = 0;
469 srvp->bindto = bindto->s_addr;
475 rad_close(struct rad_handle *h)
481 for (srv = 0; srv < h->num_servers; srv++) {
482 memset(h->servers[srv].secret, 0,
483 strlen(h->servers[srv].secret));
484 free(h->servers[srv].secret);
491 rad_bind_to(struct rad_handle *h, in_addr_t addr)
498 rad_config(struct rad_handle *h, const char *path)
501 char buf[MAXCONFLINE];
506 path = PATH_RADIUS_CONF;
507 if ((fp = fopen(path, "r")) == NULL) {
508 generr(h, "Cannot open \"%s\": %s", path, strerror(errno));
513 while (fgets(buf, sizeof buf, fp) != NULL) {
515 char *fields[MAX_FIELDS];
528 unsigned long timeout;
529 unsigned long maxtries;
530 unsigned long dead_time;
532 struct in_addr bindto;
537 /* We know len > 0, else fgets would have returned NULL. */
538 if (buf[len - 1] != '\n') {
539 if (len == sizeof buf - 1)
540 generr(h, "%s:%d: line too long", path,
543 generr(h, "%s:%d: missing newline", path,
550 /* Extract the fields from the line. */
551 nfields = split(buf, fields, MAX_FIELDS, msg, sizeof msg);
553 generr(h, "%s:%d: %s", path, linenum, msg);
560 * The first field should contain "auth" or "acct" for
561 * authentication or accounting, respectively. But older
562 * versions of the file didn't have that field. Default
563 * it to "auth" for backward compatibility.
565 if (strcmp(fields[0], "auth") != 0 &&
566 strcmp(fields[0], "acct") != 0) {
567 if (nfields >= MAX_FIELDS) {
568 generr(h, "%s:%d: invalid service type", path,
574 for (i = nfields; --i > 0; )
575 fields[i] = fields[i - 1];
579 generr(h, "%s:%d: missing shared secret", path,
587 timeout_str = fields[3];
588 maxtries_str = fields[4];
589 dead_time_str = fields[5];
590 bindto_str = fields[6];
592 /* Ignore the line if it is for the wrong service type. */
593 wanttype = h->type == RADIUS_AUTH ? "auth" : "acct";
594 if (strcmp(type, wanttype) != 0)
597 /* Parse and validate the fields. */
599 host = strsep(&res, ":");
600 port_str = strsep(&res, ":");
601 if (port_str != NULL) {
602 port = strtoul(port_str, &end, 10);
604 generr(h, "%s:%d: invalid port", path,
611 if (timeout_str != NULL) {
612 timeout = strtoul(timeout_str, &end, 10);
614 generr(h, "%s:%d: invalid timeout", path,
621 if (maxtries_str != NULL) {
622 maxtries = strtoul(maxtries_str, &end, 10);
624 generr(h, "%s:%d: invalid maxtries", path,
632 if (dead_time_str != NULL) {
633 dead_time = strtoul(dead_time_str, &end, 10);
635 generr(h, "%s:%d: invalid dead_time", path,
641 dead_time = DEAD_TIME;
643 if (bindto_str != NULL) {
644 bindto.s_addr = inet_addr(bindto_str);
645 if (bindto.s_addr == INADDR_NONE) {
646 generr(h, "%s:%d: invalid bindto", path,
652 bindto.s_addr = INADDR_ANY;
654 if (rad_add_server_ex(h, host, port, secret, timeout, maxtries,
655 dead_time, &bindto) == -1) {
656 strcpy(msg, h->errmsg);
657 generr(h, "%s:%d: %s", path, linenum, msg);
662 /* Clear out the buffer to wipe a possible copy of a shared secret */
663 memset(buf, 0, sizeof buf);
669 * rad_init_send_request() must have previously been called.
671 * 0 The application should select on *fd with a timeout of tv before
672 * calling rad_continue_send_request again.
677 rad_continue_send_request(struct rad_handle *h, int selected, int *fd,
682 struct sockaddr_in sin;
684 if (h->type == RADIUS_SERVER) {
685 generr(h, "denied function call");
689 struct sockaddr_in from;
692 fromlen = sizeof from;
693 h->in_len = recvfrom(h->fd, h->in,
694 MSGSIZE, MSG_WAITALL, (struct sockaddr *)&from, &fromlen);
695 if (h->in_len == -1) {
696 generr(h, "recvfrom: %s", strerror(errno));
699 if (is_valid_response(h, h->srv, &from)) {
700 h->in_len = h->in[POS_LENGTH] << 8 |
702 h->in_pos = POS_ATTRS;
703 return h->in[POS_CODE];
708 * Scan round-robin to the next server that has some
709 * tries left. There is guaranteed to be one, or we
710 * would have exited this loop by now.
714 if (h->servers[h->srv].num_tries >= h->servers[h->srv].max_tries) {
715 /* Set next probe time for this server */
716 if (h->servers[h->srv].dead_time) {
717 h->servers[h->srv].is_dead = 1;
718 h->servers[h->srv].next_probe = now +
719 h->servers[h->srv].dead_time;
723 if (h->srv >= h->num_servers)
725 if (h->servers[h->srv].is_dead == 0)
727 if (h->servers[h->srv].dead_time &&
728 h->servers[h->srv].next_probe <= now) {
729 h->servers[h->srv].is_dead = 0;
730 h->servers[h->srv].num_tries = 0;
733 } while (h->srv != cur_srv);
735 if (h->srv == cur_srv) {
736 generr(h, "No valid RADIUS responses received");
742 if (h->bindto != h->servers[h->srv].bindto) {
743 h->bindto = h->servers[h->srv].bindto;
745 if ((h->fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
746 generr(h, "Cannot create socket: %s", strerror(errno));
749 memset(&sin, 0, sizeof sin);
750 sin.sin_len = sizeof sin;
751 sin.sin_family = AF_INET;
752 sin.sin_addr.s_addr = h->bindto;
754 if (bind(h->fd, (const struct sockaddr *)&sin,
756 generr(h, "bind: %s", strerror(errno));
763 if (h->out[POS_CODE] == RAD_ACCESS_REQUEST) {
764 /* Insert the scrambled password into the request */
765 if (h->pass_pos != 0)
766 insert_scrambled_password(h, h->srv);
768 insert_message_authenticator(h, 0);
770 if (h->out[POS_CODE] != RAD_ACCESS_REQUEST) {
771 /* Insert the request authenticator into the request */
772 memset(&h->out[POS_AUTH], 0, LEN_AUTH);
773 insert_request_authenticator(h, 0);
776 /* Send the request */
777 n = sendto(h->fd, h->out, h->out_len, 0,
778 (const struct sockaddr *)&h->servers[h->srv].addr,
779 sizeof h->servers[h->srv].addr);
781 tv->tv_sec = 1; /* Do not wait full timeout if send failed. */
783 tv->tv_sec = h->servers[h->srv].timeout;
784 h->servers[h->srv].num_tries++;
792 rad_receive_request(struct rad_handle *h)
794 struct sockaddr_in from;
798 if (h->type != RADIUS_SERVER) {
799 generr(h, "denied function call");
803 fromlen = sizeof(from);
804 h->in_len = recvfrom(h->fd, h->in,
805 MSGSIZE, MSG_WAITALL, (struct sockaddr *)&from, &fromlen);
806 if (h->in_len == -1) {
807 generr(h, "recvfrom: %s", strerror(errno));
810 for (n = 0; n < h->num_servers; n++) {
811 if (h->servers[n].addr.sin_addr.s_addr == from.sin_addr.s_addr) {
812 h->servers[n].addr.sin_port = from.sin_port;
819 if (is_valid_request(h)) {
820 h->in_len = h->in[POS_LENGTH] << 8 |
822 h->in_pos = POS_ATTRS;
823 return (h->in[POS_CODE]);
829 rad_send_response(struct rad_handle *h)
833 if (h->type != RADIUS_SERVER) {
834 generr(h, "denied function call");
837 /* Fill in the length field in the message */
838 h->out[POS_LENGTH] = h->out_len >> 8;
839 h->out[POS_LENGTH+1] = h->out_len;
841 insert_message_authenticator(h,
842 (h->in[POS_CODE] == RAD_ACCESS_REQUEST) ? 1 : 0);
843 insert_request_authenticator(h, 1);
845 /* Send the request */
846 n = sendto(h->fd, h->out, h->out_len, 0,
847 (const struct sockaddr *)&h->servers[h->srv].addr,
848 sizeof h->servers[h->srv].addr);
849 if (n != h->out_len) {
851 generr(h, "sendto: %s", strerror(errno));
853 generr(h, "sendto: short write");
861 rad_create_request(struct rad_handle *h, int code)
865 if (h->type == RADIUS_SERVER) {
866 generr(h, "denied function call");
869 if (h->num_servers == 0) {
870 generr(h, "No RADIUS servers specified");
873 h->out[POS_CODE] = code;
874 h->out[POS_IDENT] = ++h->ident;
875 if (code == RAD_ACCESS_REQUEST) {
876 /* Create a random authenticator */
877 for (i = 0; i < LEN_AUTH; i += 2) {
880 h->out[POS_AUTH+i] = (u_char)r;
881 h->out[POS_AUTH+i+1] = (u_char)(r >> 8);
884 memset(&h->out[POS_AUTH], 0, LEN_AUTH);
885 h->out_len = POS_ATTRS;
887 h->authentic_pos = 0;
893 rad_create_response(struct rad_handle *h, int code)
896 if (h->type != RADIUS_SERVER) {
897 generr(h, "denied function call");
900 h->out[POS_CODE] = code;
901 h->out[POS_IDENT] = h->in[POS_IDENT];
902 memset(&h->out[POS_AUTH], 0, LEN_AUTH);
903 h->out_len = POS_ATTRS;
905 h->authentic_pos = 0;
911 rad_cvt_addr(const void *data)
913 struct in_addr value;
915 memcpy(&value.s_addr, data, sizeof value.s_addr);
920 rad_cvt_addr6(const void *data)
922 struct in6_addr value;
924 memcpy(&value.s6_addr, data, sizeof value.s6_addr);
929 rad_cvt_int(const void *data)
933 memcpy(&value, data, sizeof value);
938 rad_cvt_string(const void *data, size_t len)
944 memcpy(s, data, len);
951 * Returns the attribute type. If none are left, returns 0. On failure,
955 rad_get_attr(struct rad_handle *h, const void **value, size_t *lenp)
959 if (h->in_pos >= h->in_len)
961 if (h->in_pos + 2 > h->in_len) {
962 generr(h, "Malformed attribute in response");
965 type = h->in[h->in_pos++];
966 len = h->in[h->in_pos++];
968 generr(h, "Malformed attribute in response");
972 if (h->in_pos + len > h->in_len) {
973 generr(h, "Malformed attribute in response");
977 *value = &h->in[h->in_pos];
983 * Returns -1 on error, 0 to indicate no event and >0 for success
986 rad_init_send_request(struct rad_handle *h, int *fd, struct timeval *tv)
990 struct sockaddr_in sin;
992 if (h->type == RADIUS_SERVER) {
993 generr(h, "denied function call");
996 /* Make sure we have a socket to use */
998 if ((h->fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
999 generr(h, "Cannot create socket: %s", strerror(errno));
1002 memset(&sin, 0, sizeof sin);
1003 sin.sin_len = sizeof sin;
1004 sin.sin_family = AF_INET;
1005 sin.sin_addr.s_addr = h->bindto;
1006 sin.sin_port = htons(0);
1007 if (bind(h->fd, (const struct sockaddr *)&sin,
1008 sizeof sin) == -1) {
1009 generr(h, "bind: %s", strerror(errno));
1016 if (h->out[POS_CODE] != RAD_ACCESS_REQUEST) {
1017 /* Make sure no password given */
1018 if (h->pass_pos || h->chap_pass) {
1019 generr(h, "User or Chap Password"
1020 " in accounting request");
1024 if (h->eap_msg == 0) {
1025 /* Make sure the user gave us a password */
1026 if (h->pass_pos == 0 && !h->chap_pass) {
1027 generr(h, "No User or Chap Password"
1028 " attributes given");
1031 if (h->pass_pos != 0 && h->chap_pass) {
1032 generr(h, "Both User and Chap Password"
1033 " attributes given");
1039 /* Fill in the length field in the message */
1040 h->out[POS_LENGTH] = h->out_len >> 8;
1041 h->out[POS_LENGTH+1] = h->out_len;
1045 for (srv = 0; srv < h->num_servers; srv++)
1046 h->servers[srv].num_tries = 0;
1047 /* Find a first good server. */
1048 for (srv = 0; srv < h->num_servers; srv++) {
1049 if (h->servers[srv].is_dead == 0)
1051 if (h->servers[srv].dead_time &&
1052 h->servers[srv].next_probe <= now) {
1053 h->servers[srv].is_dead = 0;
1059 /* If all servers was dead on the last probe, try from beginning */
1060 if (h->srv == h->num_servers) {
1061 for (srv = 0; srv < h->num_servers; srv++) {
1062 h->servers[srv].is_dead = 0;
1063 h->servers[srv].next_probe = 0;
1068 return rad_continue_send_request(h, 0, fd, tv);
1072 * Create and initialize a rad_handle structure, and return it to the
1073 * caller. Can fail only if the necessary memory cannot be allocated.
1074 * In that case, it returns NULL.
1079 struct rad_handle *h;
1081 h = (struct rad_handle *)malloc(sizeof(struct rad_handle));
1085 h->ident = arc4random();
1086 h->errmsg[0] = '\0';
1087 memset(h->pass, 0, sizeof h->pass);
1091 h->authentic_pos = 0;
1092 h->type = RADIUS_AUTH;
1095 h->bindto = INADDR_ANY;
1103 struct rad_handle *h;
1107 h->type = RADIUS_ACCT;
1112 rad_server_open(int fd)
1114 struct rad_handle *h;
1118 h->type = RADIUS_SERVER;
1127 return rad_auth_open();
1131 rad_put_addr(struct rad_handle *h, int type, struct in_addr addr)
1133 return rad_put_attr(h, type, &addr.s_addr, sizeof addr.s_addr);
1137 rad_put_addr6(struct rad_handle *h, int type, struct in6_addr addr)
1140 return rad_put_attr(h, type, &addr.s6_addr, sizeof addr.s6_addr);
1144 rad_put_attr(struct rad_handle *h, int type, const void *value, size_t len)
1148 if (!h->out_created) {
1149 generr(h, "Please call rad_create_request()"
1150 " before putting attributes");
1154 if (h->out[POS_CODE] == RAD_ACCOUNTING_REQUEST) {
1155 if (type == RAD_EAP_MESSAGE) {
1156 generr(h, "EAP-Message attribute is not valid"
1157 " in accounting requests");
1163 * When proxying EAP Messages, the Message Authenticator
1164 * MUST be present; see RFC 3579.
1166 if (type == RAD_EAP_MESSAGE) {
1167 if (rad_put_message_authentic(h) == -1)
1171 if (type == RAD_USER_PASSWORD) {
1172 result = put_password_attr(h, type, value, len);
1173 } else if (type == RAD_MESSAGE_AUTHENTIC) {
1174 result = rad_put_message_authentic(h);
1176 result = put_raw_attr(h, type, value, len);
1178 if (type == RAD_CHAP_PASSWORD)
1180 else if (type == RAD_EAP_MESSAGE)
1189 rad_put_int(struct rad_handle *h, int type, u_int32_t value)
1193 nvalue = htonl(value);
1194 return rad_put_attr(h, type, &nvalue, sizeof nvalue);
1198 rad_put_string(struct rad_handle *h, int type, const char *str)
1200 return rad_put_attr(h, type, str, strlen(str));
1204 rad_put_message_authentic(struct rad_handle *h)
1207 u_char md_zero[MD5_DIGEST_LENGTH];
1209 if (h->out[POS_CODE] == RAD_ACCOUNTING_REQUEST) {
1210 generr(h, "Message-Authenticator is not valid"
1211 " in accounting requests");
1215 if (h->authentic_pos == 0) {
1216 h->authentic_pos = h->out_len;
1217 memset(md_zero, 0, sizeof(md_zero));
1218 return (put_raw_attr(h, RAD_MESSAGE_AUTHENTIC, md_zero,
1223 generr(h, "Message Authenticator not supported,"
1224 " please recompile libradius with SSL support");
1230 * Returns the response type code on success, or -1 on failure.
1233 rad_send_request(struct rad_handle *h)
1235 struct timeval timelimit;
1240 n = rad_init_send_request(h, &fd, &tv);
1245 gettimeofday(&timelimit, NULL);
1246 timeradd(&tv, &timelimit, &timelimit);
1252 FD_SET(fd, &readfds);
1254 n = select(fd + 1, &readfds, NULL, NULL, &tv);
1257 generr(h, "select: %s", strerror(errno));
1261 if (!FD_ISSET(fd, &readfds)) {
1262 /* Compute a new timeout */
1263 gettimeofday(&tv, NULL);
1264 timersub(&timelimit, &tv, &tv);
1265 if (tv.tv_sec > 0 || (tv.tv_sec == 0 && tv.tv_usec > 0))
1266 /* Continue the select */
1270 n = rad_continue_send_request(h, n, &fd, &tv);
1275 gettimeofday(&timelimit, NULL);
1276 timeradd(&tv, &timelimit, &timelimit);
1281 rad_strerror(struct rad_handle *h)
1287 * Destructively split a string into fields separated by white space.
1288 * `#' at the beginning of a field begins a comment that extends to the
1289 * end of the string. Fields may be quoted with `"'. Inside quoted
1290 * strings, the backslash escapes `\"' and `\\' are honored.
1292 * Pointers to up to the first maxfields fields are stored in the fields
1293 * array. Missing fields get NULL pointers.
1295 * The return value is the actual number of fields parsed, and is always
1298 * On a syntax error, places a message in the msg string, and returns -1.
1301 split(char *str, char *fields[], int maxfields, char *msg, size_t msglen)
1305 static const char ws[] = " \t";
1307 for (i = 0; i < maxfields; i++)
1311 while (*p != '\0') {
1313 if (*p == '#' || *p == '\0')
1315 if (i >= maxfields) {
1316 snprintf(msg, msglen, "line has too many fields");
1327 if (*p != '"' && *p != '\\' &&
1329 snprintf(msg, msglen,
1330 "invalid `\\' escape");
1335 snprintf(msg, msglen,
1336 "unterminated quoted string");
1343 if (*fields[i] == '\0') {
1344 snprintf(msg, msglen,
1345 "empty quoted string not permitted");
1348 if (*p != '\0' && strspn(p, ws) == 0) {
1349 snprintf(msg, msglen, "quoted string not"
1350 " followed by white space");
1355 p += strcspn(p, ws);
1365 rad_get_vendor_attr(u_int32_t *vendor, const void **data, size_t *len)
1367 struct vendor_attribute *attr;
1369 attr = (struct vendor_attribute *)*data;
1370 *vendor = ntohl(attr->vendor_value);
1371 *data = attr->attrib_data;
1372 *len = attr->attrib_len - 2;
1374 return (attr->attrib_type);
1378 rad_put_vendor_addr(struct rad_handle *h, int vendor, int type,
1379 struct in_addr addr)
1381 return (rad_put_vendor_attr(h, vendor, type, &addr.s_addr,
1382 sizeof addr.s_addr));
1386 rad_put_vendor_addr6(struct rad_handle *h, int vendor, int type,
1387 struct in6_addr addr)
1390 return (rad_put_vendor_attr(h, vendor, type, &addr.s6_addr,
1391 sizeof addr.s6_addr));
1395 rad_put_vendor_attr(struct rad_handle *h, int vendor, int type,
1396 const void *value, size_t len)
1398 struct vendor_attribute *attr;
1401 if (!h->out_created) {
1402 generr(h, "Please call rad_create_request()"
1403 " before putting attributes");
1407 if ((attr = malloc(len + 6)) == NULL) {
1408 generr(h, "malloc failure (%zu bytes)", len + 6);
1412 attr->vendor_value = htonl(vendor);
1413 attr->attrib_type = type;
1414 attr->attrib_len = len + 2;
1415 memcpy(attr->attrib_data, value, len);
1417 res = put_raw_attr(h, RAD_VENDOR_SPECIFIC, attr, len + 6);
1419 if (res == 0 && vendor == RAD_VENDOR_MICROSOFT
1420 && (type == RAD_MICROSOFT_MS_CHAP_RESPONSE
1421 || type == RAD_MICROSOFT_MS_CHAP2_RESPONSE)) {
1428 rad_put_vendor_int(struct rad_handle *h, int vendor, int type, u_int32_t i)
1433 return (rad_put_vendor_attr(h, vendor, type, &value, sizeof value));
1437 rad_put_vendor_string(struct rad_handle *h, int vendor, int type,
1440 return (rad_put_vendor_attr(h, vendor, type, str, strlen(str)));
1444 rad_request_authenticator(struct rad_handle *h, char *buf, size_t len)
1448 memcpy(buf, h->out + POS_AUTH, LEN_AUTH);
1450 buf[LEN_AUTH] = '\0';
1455 rad_demangle(struct rad_handle *h, const void *mangled, size_t mlen)
1461 u_char b[MD5_DIGEST_LENGTH], *C, *demangled;
1463 if ((mlen % 16 != 0) || mlen > 128) {
1464 generr(h, "Cannot interpret mangled data of length %lu",
1469 C = (u_char *)mangled;
1471 /* We need the shared secret as Salt */
1472 S = rad_server_secret(h);
1474 /* We need the request authenticator */
1475 if (rad_request_authenticator(h, R, sizeof R) != LEN_AUTH) {
1476 generr(h, "Cannot obtain the RADIUS request authenticator");
1480 demangled = malloc(mlen);
1485 MD5Update(&Context, S, strlen(S));
1486 MD5Update(&Context, R, LEN_AUTH);
1487 MD5Final(b, &Context);
1492 for (i = 0; i < 16; i++)
1493 demangled[Ppos++] = C[i] ^ b[i];
1497 MD5Update(&Context, S, strlen(S));
1498 MD5Update(&Context, C, 16);
1499 MD5Final(b, &Context);
1509 rad_demangle_mppe_key(struct rad_handle *h, const void *mangled,
1510 size_t mlen, size_t *len)
1512 char R[LEN_AUTH]; /* variable names as per rfc2548 */
1514 u_char b[MD5_DIGEST_LENGTH], *demangled;
1515 const u_char *A, *C;
1517 int Slen, i, Clen, Ppos;
1520 if (mlen % 16 != SALT_LEN) {
1521 generr(h, "Cannot interpret mangled data of length %lu",
1526 /* We need the RADIUS Request-Authenticator */
1527 if (rad_request_authenticator(h, R, sizeof R) != LEN_AUTH) {
1528 generr(h, "Cannot obtain the RADIUS request authenticator");
1532 A = (const u_char *)mangled; /* Salt comes first */
1533 C = (const u_char *)mangled + SALT_LEN; /* Then the ciphertext */
1534 Clen = mlen - SALT_LEN;
1535 S = rad_server_secret(h); /* We need the RADIUS secret */
1537 P = alloca(Clen); /* We derive our plaintext */
1540 MD5Update(&Context, S, Slen);
1541 MD5Update(&Context, R, LEN_AUTH);
1542 MD5Update(&Context, A, SALT_LEN);
1543 MD5Final(b, &Context);
1549 for (i = 0; i < 16; i++)
1550 P[Ppos++] = C[i] ^ b[i];
1554 MD5Update(&Context, S, Slen);
1555 MD5Update(&Context, C, 16);
1556 MD5Final(b, &Context);
1563 * The resulting plain text consists of a one-byte length, the text and
1564 * maybe some padding.
1567 if (*len > mlen - 1) {
1568 generr(h, "Mangled data seems to be garbage %zu %zu",
1573 if (*len > MPPE_KEY_LEN * 2) {
1574 generr(h, "Key to long (%zu) for me max. %d",
1575 *len, MPPE_KEY_LEN * 2);
1578 demangled = malloc(*len);
1582 memcpy(demangled, P + 1, *len);
1587 rad_server_secret(struct rad_handle *h)
1589 return (h->servers[h->srv].secret);