2 * Copyright 1998 Juniper Networks, Inc.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
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 memset(h->pass, 0, 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) {
162 HMAC_Init(&ctx, srvp->secret, strlen(srvp->secret), EVP_md5());
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);
171 HMAC_CTX_cleanup(&ctx);
173 memcpy(&h->out[h->authentic_pos + 2], md, md_len);
179 * Return true if the current response is valid for a request to the
183 is_valid_response(struct rad_handle *h, int srv,
184 const struct sockaddr_in *from)
187 unsigned char md5[MD5_DIGEST_LENGTH];
188 const struct rad_server *srvp;
192 u_char resp[MSGSIZE], md[EVP_MAX_MD_SIZE];
197 srvp = &h->servers[srv];
199 /* Check the source address */
200 if (from->sin_family != srvp->addr.sin_family ||
201 from->sin_addr.s_addr != srvp->addr.sin_addr.s_addr ||
202 from->sin_port != srvp->addr.sin_port)
205 /* Check the message length */
206 if (h->in_len < POS_ATTRS)
208 len = h->in[POS_LENGTH] << 8 | h->in[POS_LENGTH+1];
212 /* Check the response authenticator */
214 MD5Update(&ctx, &h->in[POS_CODE], POS_AUTH - POS_CODE);
215 MD5Update(&ctx, &h->out[POS_AUTH], LEN_AUTH);
216 MD5Update(&ctx, &h->in[POS_ATTRS], len - POS_ATTRS);
217 MD5Update(&ctx, srvp->secret, strlen(srvp->secret));
219 if (memcmp(&h->in[POS_AUTH], md5, sizeof md5) != 0)
224 * For non accounting responses check the message authenticator,
227 if (h->in[POS_CODE] != RAD_ACCOUNTING_RESPONSE) {
229 memcpy(resp, h->in, MSGSIZE);
232 /* Search and verify the Message-Authenticator */
233 while (pos < len - 2) {
235 if (h->in[pos] == RAD_MESSAGE_AUTHENTIC) {
236 /* zero fill the Message-Authenticator */
237 memset(&resp[pos + 2], 0, MD5_DIGEST_LENGTH);
239 HMAC_CTX_init(&hctx);
240 HMAC_Init(&hctx, srvp->secret,
241 strlen(srvp->secret), EVP_md5());
242 HMAC_Update(&hctx, &h->in[POS_CODE],
243 POS_AUTH - POS_CODE);
244 HMAC_Update(&hctx, &h->out[POS_AUTH],
246 HMAC_Update(&hctx, &resp[POS_ATTRS],
247 h->in_len - POS_ATTRS);
248 HMAC_Final(&hctx, md, &md_len);
249 HMAC_CTX_cleanup(&hctx);
251 if (memcmp(md, &h->in[pos + 2],
252 MD5_DIGEST_LENGTH) != 0)
256 pos += h->in[pos + 1];
264 * Return true if the current request is valid for the specified server.
267 is_valid_request(struct rad_handle *h)
270 unsigned char md5[MD5_DIGEST_LENGTH];
271 const struct rad_server *srvp;
275 u_char resp[MSGSIZE], md[EVP_MAX_MD_SIZE];
280 srvp = &h->servers[h->srv];
282 /* Check the message length */
283 if (h->in_len < POS_ATTRS)
285 len = h->in[POS_LENGTH] << 8 | h->in[POS_LENGTH+1];
289 if (h->in[POS_CODE] != RAD_ACCESS_REQUEST) {
290 uint32_t zeroes[4] = { 0, 0, 0, 0 };
291 /* Check the request authenticator */
293 MD5Update(&ctx, &h->in[POS_CODE], POS_AUTH - POS_CODE);
294 MD5Update(&ctx, zeroes, LEN_AUTH);
295 MD5Update(&ctx, &h->in[POS_ATTRS], len - POS_ATTRS);
296 MD5Update(&ctx, srvp->secret, strlen(srvp->secret));
298 if (memcmp(&h->in[POS_AUTH], md5, sizeof md5) != 0)
303 /* Search and verify the Message-Authenticator */
305 while (pos < len - 2) {
306 if (h->in[pos] == RAD_MESSAGE_AUTHENTIC) {
307 memcpy(resp, h->in, MSGSIZE);
308 /* zero fill the Request-Authenticator */
309 if (h->in[POS_CODE] != RAD_ACCESS_REQUEST)
310 memset(&resp[POS_AUTH], 0, LEN_AUTH);
311 /* zero fill the Message-Authenticator */
312 memset(&resp[pos + 2], 0, MD5_DIGEST_LENGTH);
314 HMAC_CTX_init(&hctx);
315 HMAC_Init(&hctx, srvp->secret,
316 strlen(srvp->secret), EVP_md5());
317 HMAC_Update(&hctx, resp, h->in_len);
318 HMAC_Final(&hctx, md, &md_len);
319 HMAC_CTX_cleanup(&hctx);
321 if (memcmp(md, &h->in[pos + 2],
322 MD5_DIGEST_LENGTH) != 0)
326 pos += h->in[pos + 1];
333 put_password_attr(struct rad_handle *h, int type, const void *value, size_t len)
338 if (h->pass_pos != 0) {
339 generr(h, "Multiple User-Password attributes specified");
344 padded_len = len == 0 ? 16 : (len+15) & ~0xf;
345 pad_len = padded_len - len;
348 * Put in a place-holder attribute containing all zeros, and
349 * remember where it is so we can fill it in later.
352 put_raw_attr(h, type, h->pass, padded_len);
353 h->pass_pos = h->out_len - padded_len;
355 /* Save the cleartext password, padded as necessary */
356 memcpy(h->pass, value, len);
358 memset(h->pass + len, 0, pad_len);
363 put_raw_attr(struct rad_handle *h, int type, const void *value, size_t len)
366 generr(h, "Attribute too long");
369 if (h->out_len + 2 + len > MSGSIZE) {
370 generr(h, "Maximum message length exceeded");
373 h->out[h->out_len++] = type;
374 h->out[h->out_len++] = len + 2;
375 memcpy(&h->out[h->out_len], value, len);
381 rad_add_server(struct rad_handle *h, const char *host, int port,
382 const char *secret, int timeout, int tries)
384 struct in_addr bindto;
385 bindto.s_addr = INADDR_ANY;
387 return rad_add_server_ex(h, host, port, secret, timeout, tries,
392 rad_add_server_ex(struct rad_handle *h, const char *host, int port,
393 const char *secret, int timeout, int tries, int dead_time,
394 struct in_addr *bindto)
396 struct rad_server *srvp;
398 if (h->num_servers >= MAXSERVERS) {
399 generr(h, "Too many RADIUS servers specified");
402 srvp = &h->servers[h->num_servers];
404 memset(&srvp->addr, 0, sizeof srvp->addr);
405 srvp->addr.sin_len = sizeof srvp->addr;
406 srvp->addr.sin_family = AF_INET;
407 if (!inet_aton(host, &srvp->addr.sin_addr)) {
408 struct hostent *hent;
410 if ((hent = gethostbyname(host)) == NULL) {
411 generr(h, "%s: host not found", host);
414 memcpy(&srvp->addr.sin_addr, hent->h_addr,
415 sizeof srvp->addr.sin_addr);
418 srvp->addr.sin_port = htons((u_short)port);
420 struct servent *sent;
422 if (h->type == RADIUS_AUTH)
423 srvp->addr.sin_port =
424 (sent = getservbyname("radius", "udp")) != NULL ?
425 sent->s_port : htons(RADIUS_PORT);
427 srvp->addr.sin_port =
428 (sent = getservbyname("radacct", "udp")) != NULL ?
429 sent->s_port : htons(RADACCT_PORT);
431 if ((srvp->secret = strdup(secret)) == NULL) {
432 generr(h, "Out of memory");
435 srvp->timeout = timeout;
436 srvp->max_tries = tries;
439 srvp->dead_time = dead_time;
440 srvp->next_probe = 0;
441 srvp->bindto = bindto->s_addr;
447 rad_close(struct rad_handle *h)
453 for (srv = 0; srv < h->num_servers; srv++) {
454 memset(h->servers[srv].secret, 0,
455 strlen(h->servers[srv].secret));
456 free(h->servers[srv].secret);
463 rad_bind_to(struct rad_handle *h, in_addr_t addr)
470 rad_config(struct rad_handle *h, const char *path)
473 char buf[MAXCONFLINE];
478 path = PATH_RADIUS_CONF;
479 if ((fp = fopen(path, "r")) == NULL) {
480 generr(h, "Cannot open \"%s\": %s", path, strerror(errno));
485 while (fgets(buf, sizeof buf, fp) != NULL) {
487 char *fields[MAX_FIELDS];
500 unsigned long timeout;
501 unsigned long maxtries;
502 unsigned long dead_time;
504 struct in_addr bindto;
509 /* We know len > 0, else fgets would have returned NULL. */
510 if (buf[len - 1] != '\n') {
511 if (len == sizeof buf - 1)
512 generr(h, "%s:%d: line too long", path,
515 generr(h, "%s:%d: missing newline", path,
522 /* Extract the fields from the line. */
523 nfields = split(buf, fields, MAX_FIELDS, msg, sizeof msg);
525 generr(h, "%s:%d: %s", path, linenum, msg);
532 * The first field should contain "auth" or "acct" for
533 * authentication or accounting, respectively. But older
534 * versions of the file didn't have that field. Default
535 * it to "auth" for backward compatibility.
537 if (strcmp(fields[0], "auth") != 0 &&
538 strcmp(fields[0], "acct") != 0) {
539 if (nfields >= MAX_FIELDS) {
540 generr(h, "%s:%d: invalid service type", path,
546 for (i = nfields; --i > 0; )
547 fields[i] = fields[i - 1];
551 generr(h, "%s:%d: missing shared secret", path,
559 timeout_str = fields[3];
560 maxtries_str = fields[4];
561 dead_time_str = fields[5];
562 bindto_str = fields[6];
564 /* Ignore the line if it is for the wrong service type. */
565 wanttype = h->type == RADIUS_AUTH ? "auth" : "acct";
566 if (strcmp(type, wanttype) != 0)
569 /* Parse and validate the fields. */
571 host = strsep(&res, ":");
572 port_str = strsep(&res, ":");
573 if (port_str != NULL) {
574 port = strtoul(port_str, &end, 10);
576 generr(h, "%s:%d: invalid port", path,
583 if (timeout_str != NULL) {
584 timeout = strtoul(timeout_str, &end, 10);
586 generr(h, "%s:%d: invalid timeout", path,
593 if (maxtries_str != NULL) {
594 maxtries = strtoul(maxtries_str, &end, 10);
596 generr(h, "%s:%d: invalid maxtries", path,
604 if (dead_time_str != NULL) {
605 dead_time = strtoul(dead_time_str, &end, 10);
607 generr(h, "%s:%d: invalid dead_time", path,
613 dead_time = DEAD_TIME;
615 if (bindto_str != NULL) {
616 bindto.s_addr = inet_addr(bindto_str);
617 if (bindto.s_addr == INADDR_NONE) {
618 generr(h, "%s:%d: invalid bindto", path,
624 bindto.s_addr = INADDR_ANY;
626 if (rad_add_server_ex(h, host, port, secret, timeout, maxtries,
627 dead_time, &bindto) == -1) {
628 strcpy(msg, h->errmsg);
629 generr(h, "%s:%d: %s", path, linenum, msg);
634 /* Clear out the buffer to wipe a possible copy of a shared secret */
635 memset(buf, 0, sizeof buf);
641 * rad_init_send_request() must have previously been called.
643 * 0 The application should select on *fd with a timeout of tv before
644 * calling rad_continue_send_request again.
649 rad_continue_send_request(struct rad_handle *h, int selected, int *fd,
654 struct sockaddr_in sin;
656 if (h->type == RADIUS_SERVER) {
657 generr(h, "denied function call");
661 struct sockaddr_in from;
664 fromlen = sizeof from;
665 h->in_len = recvfrom(h->fd, h->in,
666 MSGSIZE, MSG_WAITALL, (struct sockaddr *)&from, &fromlen);
667 if (h->in_len == -1) {
668 generr(h, "recvfrom: %s", strerror(errno));
671 if (is_valid_response(h, h->srv, &from)) {
672 h->in_len = h->in[POS_LENGTH] << 8 |
674 h->in_pos = POS_ATTRS;
675 return h->in[POS_CODE];
680 * Scan round-robin to the next server that has some
681 * tries left. There is guaranteed to be one, or we
682 * would have exited this loop by now.
686 if (h->servers[h->srv].num_tries >= h->servers[h->srv].max_tries) {
687 /* Set next probe time for this server */
688 if (h->servers[h->srv].dead_time) {
689 h->servers[h->srv].is_dead = 1;
690 h->servers[h->srv].next_probe = now +
691 h->servers[h->srv].dead_time;
695 if (h->srv >= h->num_servers)
697 if (h->servers[h->srv].is_dead == 0)
699 if (h->servers[h->srv].dead_time &&
700 h->servers[h->srv].next_probe <= now) {
701 h->servers[h->srv].is_dead = 0;
702 h->servers[h->srv].num_tries = 0;
705 } while (h->srv != cur_srv);
707 if (h->srv == cur_srv) {
708 generr(h, "No valid RADIUS responses received");
714 if (h->bindto != h->servers[h->srv].bindto) {
715 h->bindto = h->servers[h->srv].bindto;
717 if ((h->fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
718 generr(h, "Cannot create socket: %s", strerror(errno));
721 memset(&sin, 0, sizeof sin);
722 sin.sin_len = sizeof sin;
723 sin.sin_family = AF_INET;
724 sin.sin_addr.s_addr = h->bindto;
726 if (bind(h->fd, (const struct sockaddr *)&sin,
728 generr(h, "bind: %s", strerror(errno));
735 if (h->out[POS_CODE] == RAD_ACCESS_REQUEST) {
736 /* Insert the scrambled password into the request */
737 if (h->pass_pos != 0)
738 insert_scrambled_password(h, h->srv);
740 insert_message_authenticator(h, 0);
742 if (h->out[POS_CODE] != RAD_ACCESS_REQUEST) {
743 /* Insert the request authenticator into the request */
744 memset(&h->out[POS_AUTH], 0, LEN_AUTH);
745 insert_request_authenticator(h, 0);
748 /* Send the request */
749 n = sendto(h->fd, h->out, h->out_len, 0,
750 (const struct sockaddr *)&h->servers[h->srv].addr,
751 sizeof h->servers[h->srv].addr);
753 tv->tv_sec = 1; /* Do not wait full timeout if send failed. */
755 tv->tv_sec = h->servers[h->srv].timeout;
756 h->servers[h->srv].num_tries++;
764 rad_receive_request(struct rad_handle *h)
766 struct sockaddr_in from;
770 if (h->type != RADIUS_SERVER) {
771 generr(h, "denied function call");
775 fromlen = sizeof(from);
776 h->in_len = recvfrom(h->fd, h->in,
777 MSGSIZE, MSG_WAITALL, (struct sockaddr *)&from, &fromlen);
778 if (h->in_len == -1) {
779 generr(h, "recvfrom: %s", strerror(errno));
782 for (n = 0; n < h->num_servers; n++) {
783 if (h->servers[n].addr.sin_addr.s_addr == from.sin_addr.s_addr) {
784 h->servers[n].addr.sin_port = from.sin_port;
791 if (is_valid_request(h)) {
792 h->in_len = h->in[POS_LENGTH] << 8 |
794 h->in_pos = POS_ATTRS;
795 return (h->in[POS_CODE]);
801 rad_send_response(struct rad_handle *h)
805 if (h->type != RADIUS_SERVER) {
806 generr(h, "denied function call");
809 /* Fill in the length field in the message */
810 h->out[POS_LENGTH] = h->out_len >> 8;
811 h->out[POS_LENGTH+1] = h->out_len;
813 insert_message_authenticator(h,
814 (h->in[POS_CODE] == RAD_ACCESS_REQUEST) ? 1 : 0);
815 insert_request_authenticator(h, 1);
817 /* Send the request */
818 n = sendto(h->fd, h->out, h->out_len, 0,
819 (const struct sockaddr *)&h->servers[h->srv].addr,
820 sizeof h->servers[h->srv].addr);
821 if (n != h->out_len) {
823 generr(h, "sendto: %s", strerror(errno));
825 generr(h, "sendto: short write");
833 rad_create_request(struct rad_handle *h, int code)
837 if (h->type == RADIUS_SERVER) {
838 generr(h, "denied function call");
841 if (h->num_servers == 0) {
842 generr(h, "No RADIUS servers specified");
845 h->out[POS_CODE] = code;
846 h->out[POS_IDENT] = ++h->ident;
847 if (code == RAD_ACCESS_REQUEST) {
848 /* Create a random authenticator */
849 for (i = 0; i < LEN_AUTH; i += 2) {
852 h->out[POS_AUTH+i] = (u_char)r;
853 h->out[POS_AUTH+i+1] = (u_char)(r >> 8);
856 memset(&h->out[POS_AUTH], 0, LEN_AUTH);
857 h->out_len = POS_ATTRS;
859 h->authentic_pos = 0;
865 rad_create_response(struct rad_handle *h, int code)
868 if (h->type != RADIUS_SERVER) {
869 generr(h, "denied function call");
872 h->out[POS_CODE] = code;
873 h->out[POS_IDENT] = h->in[POS_IDENT];
874 memset(&h->out[POS_AUTH], 0, LEN_AUTH);
875 h->out_len = POS_ATTRS;
877 h->authentic_pos = 0;
883 rad_cvt_addr(const void *data)
885 struct in_addr value;
887 memcpy(&value.s_addr, data, sizeof value.s_addr);
892 rad_cvt_addr6(const void *data)
894 struct in6_addr value;
896 memcpy(&value.s6_addr, data, sizeof value.s6_addr);
901 rad_cvt_int(const void *data)
905 memcpy(&value, data, sizeof value);
910 rad_cvt_string(const void *data, size_t len)
916 memcpy(s, data, len);
923 * Returns the attribute type. If none are left, returns 0. On failure,
927 rad_get_attr(struct rad_handle *h, const void **value, size_t *len)
931 if (h->in_pos >= h->in_len)
933 if (h->in_pos + 2 > h->in_len) {
934 generr(h, "Malformed attribute in response");
937 type = h->in[h->in_pos++];
938 *len = h->in[h->in_pos++] - 2;
939 if (h->in_pos + (int)*len > h->in_len) {
940 generr(h, "Malformed attribute in response");
943 *value = &h->in[h->in_pos];
949 * Returns -1 on error, 0 to indicate no event and >0 for success
952 rad_init_send_request(struct rad_handle *h, int *fd, struct timeval *tv)
956 struct sockaddr_in sin;
958 if (h->type == RADIUS_SERVER) {
959 generr(h, "denied function call");
962 /* Make sure we have a socket to use */
964 if ((h->fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
965 generr(h, "Cannot create socket: %s", strerror(errno));
968 memset(&sin, 0, sizeof sin);
969 sin.sin_len = sizeof sin;
970 sin.sin_family = AF_INET;
971 sin.sin_addr.s_addr = h->bindto;
972 sin.sin_port = htons(0);
973 if (bind(h->fd, (const struct sockaddr *)&sin,
975 generr(h, "bind: %s", strerror(errno));
982 if (h->out[POS_CODE] != RAD_ACCESS_REQUEST) {
983 /* Make sure no password given */
984 if (h->pass_pos || h->chap_pass) {
985 generr(h, "User or Chap Password"
986 " in accounting request");
990 if (h->eap_msg == 0) {
991 /* Make sure the user gave us a password */
992 if (h->pass_pos == 0 && !h->chap_pass) {
993 generr(h, "No User or Chap Password"
994 " attributes given");
997 if (h->pass_pos != 0 && h->chap_pass) {
998 generr(h, "Both User and Chap Password"
999 " attributes given");
1005 /* Fill in the length field in the message */
1006 h->out[POS_LENGTH] = h->out_len >> 8;
1007 h->out[POS_LENGTH+1] = h->out_len;
1011 for (srv = 0; srv < h->num_servers; srv++)
1012 h->servers[srv].num_tries = 0;
1013 /* Find a first good server. */
1014 for (srv = 0; srv < h->num_servers; srv++) {
1015 if (h->servers[srv].is_dead == 0)
1017 if (h->servers[srv].dead_time &&
1018 h->servers[srv].next_probe <= now) {
1019 h->servers[srv].is_dead = 0;
1025 /* If all servers was dead on the last probe, try from beginning */
1026 if (h->srv == h->num_servers) {
1027 for (srv = 0; srv < h->num_servers; srv++) {
1028 h->servers[srv].is_dead = 0;
1029 h->servers[srv].next_probe = 0;
1034 return rad_continue_send_request(h, 0, fd, tv);
1038 * Create and initialize a rad_handle structure, and return it to the
1039 * caller. Can fail only if the necessary memory cannot be allocated.
1040 * In that case, it returns NULL.
1045 struct rad_handle *h;
1047 h = (struct rad_handle *)malloc(sizeof(struct rad_handle));
1052 h->ident = random();
1053 h->errmsg[0] = '\0';
1054 memset(h->pass, 0, sizeof h->pass);
1058 h->authentic_pos = 0;
1059 h->type = RADIUS_AUTH;
1062 h->bindto = INADDR_ANY;
1070 struct rad_handle *h;
1074 h->type = RADIUS_ACCT;
1079 rad_server_open(int fd)
1081 struct rad_handle *h;
1085 h->type = RADIUS_SERVER;
1094 return rad_auth_open();
1098 rad_put_addr(struct rad_handle *h, int type, struct in_addr addr)
1100 return rad_put_attr(h, type, &addr.s_addr, sizeof addr.s_addr);
1104 rad_put_addr6(struct rad_handle *h, int type, struct in6_addr addr)
1107 return rad_put_attr(h, type, &addr.s6_addr, sizeof addr.s6_addr);
1111 rad_put_attr(struct rad_handle *h, int type, const void *value, size_t len)
1115 if (!h->out_created) {
1116 generr(h, "Please call rad_create_request()"
1117 " before putting attributes");
1121 if (h->out[POS_CODE] == RAD_ACCOUNTING_REQUEST) {
1122 if (type == RAD_EAP_MESSAGE) {
1123 generr(h, "EAP-Message attribute is not valid"
1124 " in accounting requests");
1130 * When proxying EAP Messages, the Message Authenticator
1131 * MUST be present; see RFC 3579.
1133 if (type == RAD_EAP_MESSAGE) {
1134 if (rad_put_message_authentic(h) == -1)
1138 if (type == RAD_USER_PASSWORD) {
1139 result = put_password_attr(h, type, value, len);
1140 } else if (type == RAD_MESSAGE_AUTHENTIC) {
1141 result = rad_put_message_authentic(h);
1143 result = put_raw_attr(h, type, value, len);
1145 if (type == RAD_CHAP_PASSWORD)
1147 else if (type == RAD_EAP_MESSAGE)
1156 rad_put_int(struct rad_handle *h, int type, u_int32_t value)
1160 nvalue = htonl(value);
1161 return rad_put_attr(h, type, &nvalue, sizeof nvalue);
1165 rad_put_string(struct rad_handle *h, int type, const char *str)
1167 return rad_put_attr(h, type, str, strlen(str));
1171 rad_put_message_authentic(struct rad_handle *h)
1174 u_char md_zero[MD5_DIGEST_LENGTH];
1176 if (h->out[POS_CODE] == RAD_ACCOUNTING_REQUEST) {
1177 generr(h, "Message-Authenticator is not valid"
1178 " in accounting requests");
1182 if (h->authentic_pos == 0) {
1183 h->authentic_pos = h->out_len;
1184 memset(md_zero, 0, sizeof(md_zero));
1185 return (put_raw_attr(h, RAD_MESSAGE_AUTHENTIC, md_zero,
1190 generr(h, "Message Authenticator not supported,"
1191 " please recompile libradius with SSL support");
1197 * Returns the response type code on success, or -1 on failure.
1200 rad_send_request(struct rad_handle *h)
1202 struct timeval timelimit;
1207 n = rad_init_send_request(h, &fd, &tv);
1212 gettimeofday(&timelimit, NULL);
1213 timeradd(&tv, &timelimit, &timelimit);
1219 FD_SET(fd, &readfds);
1221 n = select(fd + 1, &readfds, NULL, NULL, &tv);
1224 generr(h, "select: %s", strerror(errno));
1228 if (!FD_ISSET(fd, &readfds)) {
1229 /* Compute a new timeout */
1230 gettimeofday(&tv, NULL);
1231 timersub(&timelimit, &tv, &tv);
1232 if (tv.tv_sec > 0 || (tv.tv_sec == 0 && tv.tv_usec > 0))
1233 /* Continue the select */
1237 n = rad_continue_send_request(h, n, &fd, &tv);
1242 gettimeofday(&timelimit, NULL);
1243 timeradd(&tv, &timelimit, &timelimit);
1248 rad_strerror(struct rad_handle *h)
1254 * Destructively split a string into fields separated by white space.
1255 * `#' at the beginning of a field begins a comment that extends to the
1256 * end of the string. Fields may be quoted with `"'. Inside quoted
1257 * strings, the backslash escapes `\"' and `\\' are honored.
1259 * Pointers to up to the first maxfields fields are stored in the fields
1260 * array. Missing fields get NULL pointers.
1262 * The return value is the actual number of fields parsed, and is always
1265 * On a syntax error, places a message in the msg string, and returns -1.
1268 split(char *str, char *fields[], int maxfields, char *msg, size_t msglen)
1272 static const char ws[] = " \t";
1274 for (i = 0; i < maxfields; i++)
1278 while (*p != '\0') {
1280 if (*p == '#' || *p == '\0')
1282 if (i >= maxfields) {
1283 snprintf(msg, msglen, "line has too many fields");
1294 if (*p != '"' && *p != '\\' &&
1296 snprintf(msg, msglen,
1297 "invalid `\\' escape");
1302 snprintf(msg, msglen,
1303 "unterminated quoted string");
1310 if (*fields[i] == '\0') {
1311 snprintf(msg, msglen,
1312 "empty quoted string not permitted");
1315 if (*p != '\0' && strspn(p, ws) == 0) {
1316 snprintf(msg, msglen, "quoted string not"
1317 " followed by white space");
1322 p += strcspn(p, ws);
1332 rad_get_vendor_attr(u_int32_t *vendor, const void **data, size_t *len)
1334 struct vendor_attribute *attr;
1336 attr = (struct vendor_attribute *)*data;
1337 *vendor = ntohl(attr->vendor_value);
1338 *data = attr->attrib_data;
1339 *len = attr->attrib_len - 2;
1341 return (attr->attrib_type);
1345 rad_put_vendor_addr(struct rad_handle *h, int vendor, int type,
1346 struct in_addr addr)
1348 return (rad_put_vendor_attr(h, vendor, type, &addr.s_addr,
1349 sizeof addr.s_addr));
1353 rad_put_vendor_addr6(struct rad_handle *h, int vendor, int type,
1354 struct in6_addr addr)
1357 return (rad_put_vendor_attr(h, vendor, type, &addr.s6_addr,
1358 sizeof addr.s6_addr));
1362 rad_put_vendor_attr(struct rad_handle *h, int vendor, int type,
1363 const void *value, size_t len)
1365 struct vendor_attribute *attr;
1368 if (!h->out_created) {
1369 generr(h, "Please call rad_create_request()"
1370 " before putting attributes");
1374 if ((attr = malloc(len + 6)) == NULL) {
1375 generr(h, "malloc failure (%zu bytes)", len + 6);
1379 attr->vendor_value = htonl(vendor);
1380 attr->attrib_type = type;
1381 attr->attrib_len = len + 2;
1382 memcpy(attr->attrib_data, value, len);
1384 res = put_raw_attr(h, RAD_VENDOR_SPECIFIC, attr, len + 6);
1386 if (res == 0 && vendor == RAD_VENDOR_MICROSOFT
1387 && (type == RAD_MICROSOFT_MS_CHAP_RESPONSE
1388 || type == RAD_MICROSOFT_MS_CHAP2_RESPONSE)) {
1395 rad_put_vendor_int(struct rad_handle *h, int vendor, int type, u_int32_t i)
1400 return (rad_put_vendor_attr(h, vendor, type, &value, sizeof value));
1404 rad_put_vendor_string(struct rad_handle *h, int vendor, int type,
1407 return (rad_put_vendor_attr(h, vendor, type, str, strlen(str)));
1411 rad_request_authenticator(struct rad_handle *h, char *buf, size_t len)
1415 memcpy(buf, h->out + POS_AUTH, LEN_AUTH);
1417 buf[LEN_AUTH] = '\0';
1422 rad_demangle(struct rad_handle *h, const void *mangled, size_t mlen)
1428 u_char b[MD5_DIGEST_LENGTH], *C, *demangled;
1430 if ((mlen % 16 != 0) || mlen > 128) {
1431 generr(h, "Cannot interpret mangled data of length %lu",
1436 C = (u_char *)mangled;
1438 /* We need the shared secret as Salt */
1439 S = rad_server_secret(h);
1441 /* We need the request authenticator */
1442 if (rad_request_authenticator(h, R, sizeof R) != LEN_AUTH) {
1443 generr(h, "Cannot obtain the RADIUS request authenticator");
1447 demangled = malloc(mlen);
1452 MD5Update(&Context, S, strlen(S));
1453 MD5Update(&Context, R, LEN_AUTH);
1454 MD5Final(b, &Context);
1459 for (i = 0; i < 16; i++)
1460 demangled[Ppos++] = C[i] ^ b[i];
1464 MD5Update(&Context, S, strlen(S));
1465 MD5Update(&Context, C, 16);
1466 MD5Final(b, &Context);
1476 rad_demangle_mppe_key(struct rad_handle *h, const void *mangled,
1477 size_t mlen, size_t *len)
1479 char R[LEN_AUTH]; /* variable names as per rfc2548 */
1481 u_char b[MD5_DIGEST_LENGTH], *demangled;
1482 const u_char *A, *C;
1484 int Slen, i, Clen, Ppos;
1487 if (mlen % 16 != SALT_LEN) {
1488 generr(h, "Cannot interpret mangled data of length %lu",
1493 /* We need the RADIUS Request-Authenticator */
1494 if (rad_request_authenticator(h, R, sizeof R) != LEN_AUTH) {
1495 generr(h, "Cannot obtain the RADIUS request authenticator");
1499 A = (const u_char *)mangled; /* Salt comes first */
1500 C = (const u_char *)mangled + SALT_LEN; /* Then the ciphertext */
1501 Clen = mlen - SALT_LEN;
1502 S = rad_server_secret(h); /* We need the RADIUS secret */
1504 P = alloca(Clen); /* We derive our plaintext */
1507 MD5Update(&Context, S, Slen);
1508 MD5Update(&Context, R, LEN_AUTH);
1509 MD5Update(&Context, A, SALT_LEN);
1510 MD5Final(b, &Context);
1516 for (i = 0; i < 16; i++)
1517 P[Ppos++] = C[i] ^ b[i];
1521 MD5Update(&Context, S, Slen);
1522 MD5Update(&Context, C, 16);
1523 MD5Final(b, &Context);
1530 * The resulting plain text consists of a one-byte length, the text and
1531 * maybe some padding.
1534 if (*len > mlen - 1) {
1535 generr(h, "Mangled data seems to be garbage %zu %zu",
1540 if (*len > MPPE_KEY_LEN * 2) {
1541 generr(h, "Key to long (%zu) for me max. %d",
1542 *len, MPPE_KEY_LEN * 2);
1545 demangled = malloc(*len);
1549 memcpy(demangled, P + 1, *len);
1554 rad_server_secret(struct rad_handle *h)
1556 return (h->servers[h->srv].secret);