]> CyberLeo.Net >> Repos - FreeBSD/releng/8.1.git/blob - lib/libradius/radlib.c
Copy stable/8 to releng/8.1 in preparation for 8.1-RC1.
[FreeBSD/releng/8.1.git] / lib / libradius / radlib.c
1 /*-
2  * Copyright 1998 Juniper Networks, Inc.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
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.
13  *
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
24  * SUCH DAMAGE.
25  */
26
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29
30 #include <sys/types.h>
31 #include <sys/socket.h>
32 #include <sys/time.h>
33 #include <netinet/in.h>
34 #include <arpa/inet.h>
35 #ifdef WITH_SSL
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
41 #else
42 #define MD5_DIGEST_LENGTH 16
43 #include <md5.h>
44 #endif
45
46 /* We need the MPPE_KEY_LEN define */
47 #include <netgraph/ng_mppc.h>
48
49 #include <errno.h>
50 #include <netdb.h>
51 #include <stdarg.h>
52 #include <stddef.h>
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <string.h>
56 #include <unistd.h>
57
58 #include "radlib_private.h"
59
60 static void      clear_password(struct rad_handle *);
61 static void      generr(struct rad_handle *, const char *, ...)
62                     __printflike(2, 3);
63 static void      insert_scrambled_password(struct rad_handle *, int);
64 static void      insert_request_authenticator(struct rad_handle *, int);
65 static void      insert_message_authenticator(struct rad_handle *, int);
66 static int       is_valid_response(struct rad_handle *, int,
67                     const struct sockaddr_in *);
68 static int       put_password_attr(struct rad_handle *, int,
69                     const void *, size_t);
70 static int       put_raw_attr(struct rad_handle *, int,
71                     const void *, size_t);
72 static int       split(char *, char *[], int, char *, size_t);
73
74 static void
75 clear_password(struct rad_handle *h)
76 {
77         if (h->pass_len != 0) {
78                 memset(h->pass, 0, h->pass_len);
79                 h->pass_len = 0;
80         }
81         h->pass_pos = 0;
82 }
83
84 static void
85 generr(struct rad_handle *h, const char *format, ...)
86 {
87         va_list          ap;
88
89         va_start(ap, format);
90         vsnprintf(h->errmsg, ERRSIZE, format, ap);
91         va_end(ap);
92 }
93
94 static void
95 insert_scrambled_password(struct rad_handle *h, int srv)
96 {
97         MD5_CTX ctx;
98         unsigned char md5[MD5_DIGEST_LENGTH];
99         const struct rad_server *srvp;
100         int padded_len;
101         int pos;
102
103         srvp = &h->servers[srv];
104         padded_len = h->pass_len == 0 ? 16 : (h->pass_len+15) & ~0xf;
105
106         memcpy(md5, &h->out[POS_AUTH], LEN_AUTH);
107         for (pos = 0;  pos < padded_len;  pos += 16) {
108                 int i;
109
110                 /* Calculate the new scrambler */
111                 MD5Init(&ctx);
112                 MD5Update(&ctx, srvp->secret, strlen(srvp->secret));
113                 MD5Update(&ctx, md5, 16);
114                 MD5Final(md5, &ctx);
115
116                 /*
117                  * Mix in the current chunk of the password, and copy
118                  * the result into the right place in the request.  Also
119                  * modify the scrambler in place, since we will use this
120                  * in calculating the scrambler for next time.
121                  */
122                 for (i = 0;  i < 16;  i++)
123                         h->out[h->pass_pos + pos + i] =
124                             md5[i] ^= h->pass[pos + i];
125         }
126 }
127
128 static void
129 insert_request_authenticator(struct rad_handle *h, int resp)
130 {
131         MD5_CTX ctx;
132         const struct rad_server *srvp;
133
134         srvp = &h->servers[h->srv];
135
136         /* Create the request authenticator */
137         MD5Init(&ctx);
138         MD5Update(&ctx, &h->out[POS_CODE], POS_AUTH - POS_CODE);
139         if (resp)
140             MD5Update(&ctx, &h->in[POS_AUTH], LEN_AUTH);
141         else
142             MD5Update(&ctx, &h->out[POS_AUTH], LEN_AUTH);
143         MD5Update(&ctx, &h->out[POS_ATTRS], h->out_len - POS_ATTRS);
144         MD5Update(&ctx, srvp->secret, strlen(srvp->secret));
145         MD5Final(&h->out[POS_AUTH], &ctx);
146 }
147
148 static void
149 insert_message_authenticator(struct rad_handle *h, int resp)
150 {
151 #ifdef WITH_SSL
152         u_char md[EVP_MAX_MD_SIZE];
153         u_int md_len;
154         const struct rad_server *srvp;
155         HMAC_CTX ctx;
156         srvp = &h->servers[h->srv];
157
158         if (h->authentic_pos != 0) {
159                 HMAC_CTX_init(&ctx);
160                 HMAC_Init(&ctx, srvp->secret, strlen(srvp->secret), EVP_md5());
161                 HMAC_Update(&ctx, &h->out[POS_CODE], POS_AUTH - POS_CODE);
162                 if (resp)
163                     HMAC_Update(&ctx, &h->in[POS_AUTH], LEN_AUTH);
164                 else
165                     HMAC_Update(&ctx, &h->out[POS_AUTH], LEN_AUTH);
166                 HMAC_Update(&ctx, &h->out[POS_ATTRS],
167                     h->out_len - POS_ATTRS);
168                 HMAC_Final(&ctx, md, &md_len);
169                 HMAC_CTX_cleanup(&ctx);
170                 HMAC_cleanup(&ctx);
171                 memcpy(&h->out[h->authentic_pos + 2], md, md_len);
172         }
173 #endif
174 }
175
176 /*
177  * Return true if the current response is valid for a request to the
178  * specified server.
179  */
180 static int
181 is_valid_response(struct rad_handle *h, int srv,
182     const struct sockaddr_in *from)
183 {
184         MD5_CTX ctx;
185         unsigned char md5[MD5_DIGEST_LENGTH];
186         const struct rad_server *srvp;
187         int len;
188 #ifdef WITH_SSL
189         HMAC_CTX hctx;
190         u_char resp[MSGSIZE], md[EVP_MAX_MD_SIZE];
191         u_int md_len;
192         int pos;
193 #endif
194
195         srvp = &h->servers[srv];
196
197         /* Check the source address */
198         if (from->sin_family != srvp->addr.sin_family ||
199             from->sin_addr.s_addr != srvp->addr.sin_addr.s_addr ||
200             from->sin_port != srvp->addr.sin_port)
201                 return 0;
202
203         /* Check the message length */
204         if (h->in_len < POS_ATTRS)
205                 return 0;
206         len = h->in[POS_LENGTH] << 8 | h->in[POS_LENGTH+1];
207         if (len > h->in_len)
208                 return 0;
209
210         /* Check the response authenticator */
211         MD5Init(&ctx);
212         MD5Update(&ctx, &h->in[POS_CODE], POS_AUTH - POS_CODE);
213         MD5Update(&ctx, &h->out[POS_AUTH], LEN_AUTH);
214         MD5Update(&ctx, &h->in[POS_ATTRS], len - POS_ATTRS);
215         MD5Update(&ctx, srvp->secret, strlen(srvp->secret));
216         MD5Final(md5, &ctx);
217         if (memcmp(&h->in[POS_AUTH], md5, sizeof md5) != 0)
218                 return 0;
219
220 #ifdef WITH_SSL
221         /*
222          * For non accounting responses check the message authenticator,
223          * if any.
224          */
225         if (h->in[POS_CODE] != RAD_ACCOUNTING_RESPONSE) {
226
227                 memcpy(resp, h->in, MSGSIZE);
228                 pos = POS_ATTRS;
229
230                 /* Search and verify the Message-Authenticator */
231                 while (pos < len - 2) {
232
233                         if (h->in[pos] == RAD_MESSAGE_AUTHENTIC) {
234                                 /* zero fill the Message-Authenticator */
235                                 memset(&resp[pos + 2], 0, MD5_DIGEST_LENGTH);
236
237                                 HMAC_CTX_init(&hctx);
238                                 HMAC_Init(&hctx, srvp->secret,
239                                     strlen(srvp->secret), EVP_md5());
240                                 HMAC_Update(&hctx, &h->in[POS_CODE],
241                                     POS_AUTH - POS_CODE);
242                                 HMAC_Update(&hctx, &h->out[POS_AUTH],
243                                     LEN_AUTH);
244                                 HMAC_Update(&hctx, &resp[POS_ATTRS],
245                                     h->in_len - POS_ATTRS);
246                                 HMAC_Final(&hctx, md, &md_len);
247                                 HMAC_CTX_cleanup(&hctx);
248                                 HMAC_cleanup(&hctx);
249                                 if (memcmp(md, &h->in[pos + 2],
250                                     MD5_DIGEST_LENGTH) != 0)
251                                         return 0;
252                                 break;
253                         }
254                         pos += h->in[pos + 1];
255                 }
256         }
257 #endif
258         return 1;
259 }
260
261 /*
262  * Return true if the current request is valid for the specified server.
263  */
264 static int
265 is_valid_request(struct rad_handle *h)
266 {
267         MD5_CTX ctx;
268         unsigned char md5[MD5_DIGEST_LENGTH];
269         const struct rad_server *srvp;
270         int len;
271 #ifdef WITH_SSL
272         HMAC_CTX hctx;
273         u_char resp[MSGSIZE], md[EVP_MAX_MD_SIZE];
274         u_int md_len;
275         int pos;
276 #endif
277
278         srvp = &h->servers[h->srv];
279
280         /* Check the message length */
281         if (h->in_len < POS_ATTRS)
282                 return (0);
283         len = h->in[POS_LENGTH] << 8 | h->in[POS_LENGTH+1];
284         if (len > h->in_len)
285                 return (0);
286
287         if (h->in[POS_CODE] != RAD_ACCESS_REQUEST) {
288                 uint32_t zeroes[4] = { 0, 0, 0, 0 };
289                 /* Check the request authenticator */
290                 MD5Init(&ctx);
291                 MD5Update(&ctx, &h->in[POS_CODE], POS_AUTH - POS_CODE);
292                 MD5Update(&ctx, zeroes, LEN_AUTH);
293                 MD5Update(&ctx, &h->in[POS_ATTRS], len - POS_ATTRS);
294                 MD5Update(&ctx, srvp->secret, strlen(srvp->secret));
295                 MD5Final(md5, &ctx);
296                 if (memcmp(&h->in[POS_AUTH], md5, sizeof md5) != 0)
297                         return (0);
298         }
299
300 #ifdef WITH_SSL
301         /* Search and verify the Message-Authenticator */
302         pos = POS_ATTRS;
303         while (pos < len - 2) {
304                 if (h->in[pos] == RAD_MESSAGE_AUTHENTIC) {
305                         memcpy(resp, h->in, MSGSIZE);
306                         /* zero fill the Request-Authenticator */
307                         if (h->in[POS_CODE] != RAD_ACCESS_REQUEST)
308                                 memset(&resp[POS_AUTH], 0, LEN_AUTH);
309                         /* zero fill the Message-Authenticator */
310                         memset(&resp[pos + 2], 0, MD5_DIGEST_LENGTH);
311
312                         HMAC_CTX_init(&hctx);
313                         HMAC_Init(&hctx, srvp->secret,
314                             strlen(srvp->secret), EVP_md5());
315                         HMAC_Update(&hctx, resp, h->in_len);
316                         HMAC_Final(&hctx, md, &md_len);
317                         HMAC_CTX_cleanup(&hctx);
318                         HMAC_cleanup(&hctx);
319                         if (memcmp(md, &h->in[pos + 2],
320                             MD5_DIGEST_LENGTH) != 0)
321                                 return (0);
322                         break;
323                 }
324                 pos += h->in[pos + 1];
325         }
326 #endif
327         return (1);
328 }
329
330 static int
331 put_password_attr(struct rad_handle *h, int type, const void *value, size_t len)
332 {
333         int padded_len;
334         int pad_len;
335
336         if (h->pass_pos != 0) {
337                 generr(h, "Multiple User-Password attributes specified");
338                 return -1;
339         }
340         if (len > PASSSIZE)
341                 len = PASSSIZE;
342         padded_len = len == 0 ? 16 : (len+15) & ~0xf;
343         pad_len = padded_len - len;
344
345         /*
346          * Put in a place-holder attribute containing all zeros, and
347          * remember where it is so we can fill it in later.
348          */
349         clear_password(h);
350         put_raw_attr(h, type, h->pass, padded_len);
351         h->pass_pos = h->out_len - padded_len;
352
353         /* Save the cleartext password, padded as necessary */
354         memcpy(h->pass, value, len);
355         h->pass_len = len;
356         memset(h->pass + len, 0, pad_len);
357         return 0;
358 }
359
360 static int
361 put_raw_attr(struct rad_handle *h, int type, const void *value, size_t len)
362 {
363         if (len > 253) {
364                 generr(h, "Attribute too long");
365                 return -1;
366         }
367         if (h->out_len + 2 + len > MSGSIZE) {
368                 generr(h, "Maximum message length exceeded");
369                 return -1;
370         }
371         h->out[h->out_len++] = type;
372         h->out[h->out_len++] = len + 2;
373         memcpy(&h->out[h->out_len], value, len);
374         h->out_len += len;
375         return 0;
376 }
377
378 int
379 rad_add_server(struct rad_handle *h, const char *host, int port,
380     const char *secret, int timeout, int tries)
381 {
382         struct rad_server *srvp;
383
384         if (h->num_servers >= MAXSERVERS) {
385                 generr(h, "Too many RADIUS servers specified");
386                 return -1;
387         }
388         srvp = &h->servers[h->num_servers];
389
390         memset(&srvp->addr, 0, sizeof srvp->addr);
391         srvp->addr.sin_len = sizeof srvp->addr;
392         srvp->addr.sin_family = AF_INET;
393         if (!inet_aton(host, &srvp->addr.sin_addr)) {
394                 struct hostent *hent;
395
396                 if ((hent = gethostbyname(host)) == NULL) {
397                         generr(h, "%s: host not found", host);
398                         return -1;
399                 }
400                 memcpy(&srvp->addr.sin_addr, hent->h_addr,
401                     sizeof srvp->addr.sin_addr);
402         }
403         if (port != 0)
404                 srvp->addr.sin_port = htons((u_short)port);
405         else {
406                 struct servent *sent;
407
408                 if (h->type == RADIUS_AUTH)
409                         srvp->addr.sin_port =
410                             (sent = getservbyname("radius", "udp")) != NULL ?
411                                 sent->s_port : htons(RADIUS_PORT);
412                 else
413                         srvp->addr.sin_port =
414                             (sent = getservbyname("radacct", "udp")) != NULL ?
415                                 sent->s_port : htons(RADACCT_PORT);
416         }
417         if ((srvp->secret = strdup(secret)) == NULL) {
418                 generr(h, "Out of memory");
419                 return -1;
420         }
421         srvp->timeout = timeout;
422         srvp->max_tries = tries;
423         srvp->num_tries = 0;
424         h->num_servers++;
425         return 0;
426 }
427
428 void
429 rad_close(struct rad_handle *h)
430 {
431         int srv;
432
433         if (h->fd != -1)
434                 close(h->fd);
435         for (srv = 0;  srv < h->num_servers;  srv++) {
436                 memset(h->servers[srv].secret, 0,
437                     strlen(h->servers[srv].secret));
438                 free(h->servers[srv].secret);
439         }
440         clear_password(h);
441         free(h);
442 }
443
444 int
445 rad_config(struct rad_handle *h, const char *path)
446 {
447         FILE *fp;
448         char buf[MAXCONFLINE];
449         int linenum;
450         int retval;
451
452         if (path == NULL)
453                 path = PATH_RADIUS_CONF;
454         if ((fp = fopen(path, "r")) == NULL) {
455                 generr(h, "Cannot open \"%s\": %s", path, strerror(errno));
456                 return -1;
457         }
458         retval = 0;
459         linenum = 0;
460         while (fgets(buf, sizeof buf, fp) != NULL) {
461                 int len;
462                 char *fields[5];
463                 int nfields;
464                 char msg[ERRSIZE];
465                 char *type;
466                 char *host, *res;
467                 char *port_str;
468                 char *secret;
469                 char *timeout_str;
470                 char *maxtries_str;
471                 char *end;
472                 char *wanttype;
473                 unsigned long timeout;
474                 unsigned long maxtries;
475                 int port;
476                 int i;
477
478                 linenum++;
479                 len = strlen(buf);
480                 /* We know len > 0, else fgets would have returned NULL. */
481                 if (buf[len - 1] != '\n') {
482                         if (len == sizeof buf - 1)
483                                 generr(h, "%s:%d: line too long", path,
484                                     linenum);
485                         else
486                                 generr(h, "%s:%d: missing newline", path,
487                                     linenum);
488                         retval = -1;
489                         break;
490                 }
491                 buf[len - 1] = '\0';
492
493                 /* Extract the fields from the line. */
494                 nfields = split(buf, fields, 5, msg, sizeof msg);
495                 if (nfields == -1) {
496                         generr(h, "%s:%d: %s", path, linenum, msg);
497                         retval = -1;
498                         break;
499                 }
500                 if (nfields == 0)
501                         continue;
502                 /*
503                  * The first field should contain "auth" or "acct" for
504                  * authentication or accounting, respectively.  But older
505                  * versions of the file didn't have that field.  Default
506                  * it to "auth" for backward compatibility.
507                  */
508                 if (strcmp(fields[0], "auth") != 0 &&
509                     strcmp(fields[0], "acct") != 0) {
510                         if (nfields >= 5) {
511                                 generr(h, "%s:%d: invalid service type", path,
512                                     linenum);
513                                 retval = -1;
514                                 break;
515                         }
516                         nfields++;
517                         for (i = nfields;  --i > 0;  )
518                                 fields[i] = fields[i - 1];
519                         fields[0] = "auth";
520                 }
521                 if (nfields < 3) {
522                         generr(h, "%s:%d: missing shared secret", path,
523                             linenum);
524                         retval = -1;
525                         break;
526                 }
527                 type = fields[0];
528                 host = fields[1];
529                 secret = fields[2];
530                 timeout_str = fields[3];
531                 maxtries_str = fields[4];
532
533                 /* Ignore the line if it is for the wrong service type. */
534                 wanttype = h->type == RADIUS_AUTH ? "auth" : "acct";
535                 if (strcmp(type, wanttype) != 0)
536                         continue;
537
538                 /* Parse and validate the fields. */
539                 res = host;
540                 host = strsep(&res, ":");
541                 port_str = strsep(&res, ":");
542                 if (port_str != NULL) {
543                         port = strtoul(port_str, &end, 10);
544                         if (*end != '\0') {
545                                 generr(h, "%s:%d: invalid port", path,
546                                     linenum);
547                                 retval = -1;
548                                 break;
549                         }
550                 } else
551                         port = 0;
552                 if (timeout_str != NULL) {
553                         timeout = strtoul(timeout_str, &end, 10);
554                         if (*end != '\0') {
555                                 generr(h, "%s:%d: invalid timeout", path,
556                                     linenum);
557                                 retval = -1;
558                                 break;
559                         }
560                 } else
561                         timeout = TIMEOUT;
562                 if (maxtries_str != NULL) {
563                         maxtries = strtoul(maxtries_str, &end, 10);
564                         if (*end != '\0') {
565                                 generr(h, "%s:%d: invalid maxtries", path,
566                                     linenum);
567                                 retval = -1;
568                                 break;
569                         }
570                 } else
571                         maxtries = MAXTRIES;
572
573                 if (rad_add_server(h, host, port, secret, timeout, maxtries) ==
574                     -1) {
575                         strcpy(msg, h->errmsg);
576                         generr(h, "%s:%d: %s", path, linenum, msg);
577                         retval = -1;
578                         break;
579                 }
580         }
581         /* Clear out the buffer to wipe a possible copy of a shared secret */
582         memset(buf, 0, sizeof buf);
583         fclose(fp);
584         return retval;
585 }
586
587 /*
588  * rad_init_send_request() must have previously been called.
589  * Returns:
590  *   0     The application should select on *fd with a timeout of tv before
591  *         calling rad_continue_send_request again.
592  *   < 0   Failure
593  *   > 0   Success
594  */
595 int
596 rad_continue_send_request(struct rad_handle *h, int selected, int *fd,
597                           struct timeval *tv)
598 {
599         int n;
600
601         if (h->type == RADIUS_SERVER) {
602                 generr(h, "denied function call");
603                 return (-1);
604         }
605         if (selected) {
606                 struct sockaddr_in from;
607                 socklen_t fromlen;
608
609                 fromlen = sizeof from;
610                 h->in_len = recvfrom(h->fd, h->in,
611                     MSGSIZE, MSG_WAITALL, (struct sockaddr *)&from, &fromlen);
612                 if (h->in_len == -1) {
613                         generr(h, "recvfrom: %s", strerror(errno));
614                         return -1;
615                 }
616                 if (is_valid_response(h, h->srv, &from)) {
617                         h->in_len = h->in[POS_LENGTH] << 8 |
618                             h->in[POS_LENGTH+1];
619                         h->in_pos = POS_ATTRS;
620                         return h->in[POS_CODE];
621                 }
622         }
623
624         if (h->try == h->total_tries) {
625                 generr(h, "No valid RADIUS responses received");
626                 return -1;
627         }
628
629         /*
630          * Scan round-robin to the next server that has some
631          * tries left.  There is guaranteed to be one, or we
632          * would have exited this loop by now.
633          */
634         while (h->servers[h->srv].num_tries >= h->servers[h->srv].max_tries)
635                 if (++h->srv >= h->num_servers)
636                         h->srv = 0;
637
638         if (h->out[POS_CODE] == RAD_ACCESS_REQUEST) {
639                 /* Insert the scrambled password into the request */
640                 if (h->pass_pos != 0)
641                         insert_scrambled_password(h, h->srv);
642         }
643         insert_message_authenticator(h, 0);
644         if (h->out[POS_CODE] != RAD_ACCESS_REQUEST) {
645                 /* Insert the request authenticator into the request */
646                 insert_request_authenticator(h, h->srv);
647         }
648
649         /* Send the request */
650         n = sendto(h->fd, h->out, h->out_len, 0,
651             (const struct sockaddr *)&h->servers[h->srv].addr,
652             sizeof h->servers[h->srv].addr);
653         if (n != h->out_len)
654                 tv->tv_sec = 1; /* Do not wait full timeout if send failed. */
655         else
656                 tv->tv_sec = h->servers[h->srv].timeout;
657         h->try++;
658         h->servers[h->srv].num_tries++;
659         tv->tv_usec = 0;
660         *fd = h->fd;
661
662         return 0;
663 }
664
665 int
666 rad_receive_request(struct rad_handle *h)
667 {
668         struct sockaddr_in from;
669         socklen_t fromlen;
670         int n;
671
672         if (h->type != RADIUS_SERVER) {
673                 generr(h, "denied function call");
674                 return (-1);
675         }
676         h->srv = -1;
677         fromlen = sizeof(from);
678         h->in_len = recvfrom(h->fd, h->in,
679             MSGSIZE, MSG_WAITALL, (struct sockaddr *)&from, &fromlen);
680         if (h->in_len == -1) {
681                 generr(h, "recvfrom: %s", strerror(errno));
682                 return (-1);
683         }
684         for (n = 0; n < h->num_servers; n++) {
685                 if (h->servers[n].addr.sin_addr.s_addr == from.sin_addr.s_addr) {
686                         h->servers[n].addr.sin_port = from.sin_port;
687                         h->srv = n;
688                         break;
689                 }
690         }
691         if (h->srv == -1)
692                 return (-2);
693         if (is_valid_request(h)) {
694                 h->in_len = h->in[POS_LENGTH] << 8 |
695                     h->in[POS_LENGTH+1];
696                 h->in_pos = POS_ATTRS;
697                 return (h->in[POS_CODE]);
698         }
699         return (-3);
700 }
701
702 int
703 rad_send_response(struct rad_handle *h)
704 {
705         int n;
706
707         if (h->type != RADIUS_SERVER) {
708                 generr(h, "denied function call");
709                 return (-1);
710         }
711         /* Fill in the length field in the message */
712         h->out[POS_LENGTH] = h->out_len >> 8;
713         h->out[POS_LENGTH+1] = h->out_len;
714
715         insert_message_authenticator(h,
716             (h->in[POS_CODE] == RAD_ACCESS_REQUEST) ? 1 : 0);
717         insert_request_authenticator(h, 1);
718
719         /* Send the request */
720         n = sendto(h->fd, h->out, h->out_len, 0,
721             (const struct sockaddr *)&h->servers[h->srv].addr,
722             sizeof h->servers[h->srv].addr);
723         if (n != h->out_len) {
724                 if (n == -1)
725                         generr(h, "sendto: %s", strerror(errno));
726                 else
727                         generr(h, "sendto: short write");
728                 return -1;
729         }
730
731         return 0;
732 }
733
734 int
735 rad_create_request(struct rad_handle *h, int code)
736 {
737         int i;
738
739         if (h->type == RADIUS_SERVER) {
740                 generr(h, "denied function call");
741                 return (-1);
742         }
743         h->out[POS_CODE] = code;
744         h->out[POS_IDENT] = ++h->ident;
745         if (code == RAD_ACCESS_REQUEST) {
746                 /* Create a random authenticator */
747                 for (i = 0;  i < LEN_AUTH;  i += 2) {
748                         long r;
749                         r = random();
750                         h->out[POS_AUTH+i] = (u_char)r;
751                         h->out[POS_AUTH+i+1] = (u_char)(r >> 8);
752                 }
753         } else
754                 memset(&h->out[POS_AUTH], 0, LEN_AUTH);
755         h->out_len = POS_ATTRS;
756         clear_password(h);
757         h->authentic_pos = 0;
758         h->out_created = 1;
759         return 0;
760 }
761
762 int
763 rad_create_response(struct rad_handle *h, int code)
764 {
765
766         if (h->type != RADIUS_SERVER) {
767                 generr(h, "denied function call");
768                 return (-1);
769         }
770         h->out[POS_CODE] = code;
771         h->out[POS_IDENT] = h->in[POS_IDENT];
772         memset(&h->out[POS_AUTH], 0, LEN_AUTH);
773         h->out_len = POS_ATTRS;
774         clear_password(h);
775         h->authentic_pos = 0;
776         h->out_created = 1;
777         return 0;
778 }
779
780 struct in_addr
781 rad_cvt_addr(const void *data)
782 {
783         struct in_addr value;
784
785         memcpy(&value.s_addr, data, sizeof value.s_addr);
786         return value;
787 }
788
789 u_int32_t
790 rad_cvt_int(const void *data)
791 {
792         u_int32_t value;
793
794         memcpy(&value, data, sizeof value);
795         return ntohl(value);
796 }
797
798 char *
799 rad_cvt_string(const void *data, size_t len)
800 {
801         char *s;
802
803         s = malloc(len + 1);
804         if (s != NULL) {
805                 memcpy(s, data, len);
806                 s[len] = '\0';
807         }
808         return s;
809 }
810
811 /*
812  * Returns the attribute type.  If none are left, returns 0.  On failure,
813  * returns -1.
814  */
815 int
816 rad_get_attr(struct rad_handle *h, const void **value, size_t *len)
817 {
818         int type;
819
820         if (h->in_pos >= h->in_len)
821                 return 0;
822         if (h->in_pos + 2 > h->in_len) {
823                 generr(h, "Malformed attribute in response");
824                 return -1;
825         }
826         type = h->in[h->in_pos++];
827         *len = h->in[h->in_pos++] - 2;
828         if (h->in_pos + (int)*len > h->in_len) {
829                 generr(h, "Malformed attribute in response");
830                 return -1;
831         }
832         *value = &h->in[h->in_pos];
833         h->in_pos += *len;
834         return type;
835 }
836
837 /*
838  * Returns -1 on error, 0 to indicate no event and >0 for success
839  */
840 int
841 rad_init_send_request(struct rad_handle *h, int *fd, struct timeval *tv)
842 {
843         int srv;
844
845         if (h->type == RADIUS_SERVER) {
846                 generr(h, "denied function call");
847                 return (-1);
848         }
849         /* Make sure we have a socket to use */
850         if (h->fd == -1) {
851                 struct sockaddr_in sin;
852
853                 if ((h->fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
854                         generr(h, "Cannot create socket: %s", strerror(errno));
855                         return -1;
856                 }
857                 memset(&sin, 0, sizeof sin);
858                 sin.sin_len = sizeof sin;
859                 sin.sin_family = AF_INET;
860                 sin.sin_addr.s_addr = INADDR_ANY;
861                 sin.sin_port = htons(0);
862                 if (bind(h->fd, (const struct sockaddr *)&sin,
863                     sizeof sin) == -1) {
864                         generr(h, "bind: %s", strerror(errno));
865                         close(h->fd);
866                         h->fd = -1;
867                         return -1;
868                 }
869         }
870
871         if (h->out[POS_CODE] != RAD_ACCESS_REQUEST) {
872                 /* Make sure no password given */
873                 if (h->pass_pos || h->chap_pass) {
874                         generr(h, "User or Chap Password"
875                             " in accounting request");
876                         return -1;
877                 }
878         } else {
879                 if (h->eap_msg == 0) {
880                         /* Make sure the user gave us a password */
881                         if (h->pass_pos == 0 && !h->chap_pass) {
882                                 generr(h, "No User or Chap Password"
883                                     " attributes given");
884                                 return -1;
885                         }
886                         if (h->pass_pos != 0 && h->chap_pass) {
887                                 generr(h, "Both User and Chap Password"
888                                     " attributes given");
889                                 return -1;
890                         }
891                 }
892         }
893
894         /* Fill in the length field in the message */
895         h->out[POS_LENGTH] = h->out_len >> 8;
896         h->out[POS_LENGTH+1] = h->out_len;
897
898         /*
899          * Count the total number of tries we will make, and zero the
900          * counter for each server.
901          */
902         h->total_tries = 0;
903         for (srv = 0;  srv < h->num_servers;  srv++) {
904                 h->total_tries += h->servers[srv].max_tries;
905                 h->servers[srv].num_tries = 0;
906         }
907         if (h->total_tries == 0) {
908                 generr(h, "No RADIUS servers specified");
909                 return -1;
910         }
911
912         h->try = h->srv = 0;
913
914         return rad_continue_send_request(h, 0, fd, tv);
915 }
916
917 /*
918  * Create and initialize a rad_handle structure, and return it to the
919  * caller.  Can fail only if the necessary memory cannot be allocated.
920  * In that case, it returns NULL.
921  */
922 struct rad_handle *
923 rad_auth_open(void)
924 {
925         struct rad_handle *h;
926
927         h = (struct rad_handle *)malloc(sizeof(struct rad_handle));
928         if (h != NULL) {
929                 srandomdev();
930                 h->fd = -1;
931                 h->num_servers = 0;
932                 h->ident = random();
933                 h->errmsg[0] = '\0';
934                 memset(h->pass, 0, sizeof h->pass);
935                 h->pass_len = 0;
936                 h->pass_pos = 0;
937                 h->chap_pass = 0;
938                 h->authentic_pos = 0;
939                 h->type = RADIUS_AUTH;
940                 h->out_created = 0;
941                 h->eap_msg = 0;
942         }
943         return h;
944 }
945
946 struct rad_handle *
947 rad_acct_open(void)
948 {
949         struct rad_handle *h;
950
951         h = rad_open();
952         if (h != NULL)
953                 h->type = RADIUS_ACCT;
954         return h;
955 }
956
957 struct rad_handle *
958 rad_server_open(int fd)
959 {
960         struct rad_handle *h;
961
962         h = rad_open();
963         if (h != NULL) {
964                 h->type = RADIUS_SERVER;
965                 h->fd = fd;
966         }
967         return h;
968 }
969
970 struct rad_handle *
971 rad_open(void)
972 {
973     return rad_auth_open();
974 }
975
976 int
977 rad_put_addr(struct rad_handle *h, int type, struct in_addr addr)
978 {
979         return rad_put_attr(h, type, &addr.s_addr, sizeof addr.s_addr);
980 }
981
982 int
983 rad_put_attr(struct rad_handle *h, int type, const void *value, size_t len)
984 {
985         int result;
986
987         if (!h->out_created) {
988                 generr(h, "Please call rad_create_request()"
989                     " before putting attributes");
990                 return -1;
991         }
992
993         if (h->out[POS_CODE] == RAD_ACCOUNTING_REQUEST) {
994                 if (type == RAD_EAP_MESSAGE) {
995                         generr(h, "EAP-Message attribute is not valid"
996                             " in accounting requests");
997                         return -1;
998                 }
999         }
1000
1001         /*
1002          * When proxying EAP Messages, the Message Authenticator
1003          * MUST be present; see RFC 3579.
1004          */
1005         if (type == RAD_EAP_MESSAGE) {
1006                 if (rad_put_message_authentic(h) == -1)
1007                         return -1;
1008         }
1009
1010         if (type == RAD_USER_PASSWORD) {
1011                 result = put_password_attr(h, type, value, len);
1012         } else if (type == RAD_MESSAGE_AUTHENTIC) {
1013                 result = rad_put_message_authentic(h);
1014         } else {
1015                 result = put_raw_attr(h, type, value, len);
1016                 if (result == 0) {
1017                         if (type == RAD_CHAP_PASSWORD)
1018                                 h->chap_pass = 1;
1019                         else if (type == RAD_EAP_MESSAGE)
1020                                 h->eap_msg = 1;
1021                 }
1022         }
1023
1024         return result;
1025 }
1026
1027 int
1028 rad_put_int(struct rad_handle *h, int type, u_int32_t value)
1029 {
1030         u_int32_t nvalue;
1031
1032         nvalue = htonl(value);
1033         return rad_put_attr(h, type, &nvalue, sizeof nvalue);
1034 }
1035
1036 int
1037 rad_put_string(struct rad_handle *h, int type, const char *str)
1038 {
1039         return rad_put_attr(h, type, str, strlen(str));
1040 }
1041
1042 int
1043 rad_put_message_authentic(struct rad_handle *h)
1044 {
1045 #ifdef WITH_SSL
1046         u_char md_zero[MD5_DIGEST_LENGTH];
1047
1048         if (h->out[POS_CODE] == RAD_ACCOUNTING_REQUEST) {
1049                 generr(h, "Message-Authenticator is not valid"
1050                     " in accounting requests");
1051                 return -1;
1052         }
1053
1054         if (h->authentic_pos == 0) {
1055                 h->authentic_pos = h->out_len;
1056                 memset(md_zero, 0, sizeof(md_zero));
1057                 return (put_raw_attr(h, RAD_MESSAGE_AUTHENTIC, md_zero,
1058                     sizeof(md_zero)));
1059         }
1060         return 0;
1061 #else
1062         generr(h, "Message Authenticator not supported,"
1063             " please recompile libradius with SSL support");
1064         return -1;
1065 #endif
1066 }
1067
1068 /*
1069  * Returns the response type code on success, or -1 on failure.
1070  */
1071 int
1072 rad_send_request(struct rad_handle *h)
1073 {
1074         struct timeval timelimit;
1075         struct timeval tv;
1076         int fd;
1077         int n;
1078
1079         n = rad_init_send_request(h, &fd, &tv);
1080
1081         if (n != 0)
1082                 return n;
1083
1084         gettimeofday(&timelimit, NULL);
1085         timeradd(&tv, &timelimit, &timelimit);
1086
1087         for ( ; ; ) {
1088                 fd_set readfds;
1089
1090                 FD_ZERO(&readfds);
1091                 FD_SET(fd, &readfds);
1092
1093                 n = select(fd + 1, &readfds, NULL, NULL, &tv);
1094
1095                 if (n == -1) {
1096                         generr(h, "select: %s", strerror(errno));
1097                         return -1;
1098                 }
1099
1100                 if (!FD_ISSET(fd, &readfds)) {
1101                         /* Compute a new timeout */
1102                         gettimeofday(&tv, NULL);
1103                         timersub(&timelimit, &tv, &tv);
1104                         if (tv.tv_sec > 0 || (tv.tv_sec == 0 && tv.tv_usec > 0))
1105                                 /* Continue the select */
1106                                 continue;
1107                 }
1108
1109                 n = rad_continue_send_request(h, n, &fd, &tv);
1110
1111                 if (n != 0)
1112                         return n;
1113
1114                 gettimeofday(&timelimit, NULL);
1115                 timeradd(&tv, &timelimit, &timelimit);
1116         }
1117 }
1118
1119 const char *
1120 rad_strerror(struct rad_handle *h)
1121 {
1122         return h->errmsg;
1123 }
1124
1125 /*
1126  * Destructively split a string into fields separated by white space.
1127  * `#' at the beginning of a field begins a comment that extends to the
1128  * end of the string.  Fields may be quoted with `"'.  Inside quoted
1129  * strings, the backslash escapes `\"' and `\\' are honored.
1130  *
1131  * Pointers to up to the first maxfields fields are stored in the fields
1132  * array.  Missing fields get NULL pointers.
1133  *
1134  * The return value is the actual number of fields parsed, and is always
1135  * <= maxfields.
1136  *
1137  * On a syntax error, places a message in the msg string, and returns -1.
1138  */
1139 static int
1140 split(char *str, char *fields[], int maxfields, char *msg, size_t msglen)
1141 {
1142         char *p;
1143         int i;
1144         static const char ws[] = " \t";
1145
1146         for (i = 0;  i < maxfields;  i++)
1147                 fields[i] = NULL;
1148         p = str;
1149         i = 0;
1150         while (*p != '\0') {
1151                 p += strspn(p, ws);
1152                 if (*p == '#' || *p == '\0')
1153                         break;
1154                 if (i >= maxfields) {
1155                         snprintf(msg, msglen, "line has too many fields");
1156                         return -1;
1157                 }
1158                 if (*p == '"') {
1159                         char *dst;
1160
1161                         dst = ++p;
1162                         fields[i] = dst;
1163                         while (*p != '"') {
1164                                 if (*p == '\\') {
1165                                         p++;
1166                                         if (*p != '"' && *p != '\\' &&
1167                                             *p != '\0') {
1168                                                 snprintf(msg, msglen,
1169                                                     "invalid `\\' escape");
1170                                                 return -1;
1171                                         }
1172                                 }
1173                                 if (*p == '\0') {
1174                                         snprintf(msg, msglen,
1175                                             "unterminated quoted string");
1176                                         return -1;
1177                                 }
1178                                 *dst++ = *p++;
1179                         }
1180                         *dst = '\0';
1181                         p++;
1182                         if (*fields[i] == '\0') {
1183                                 snprintf(msg, msglen,
1184                                     "empty quoted string not permitted");
1185                                 return -1;
1186                         }
1187                         if (*p != '\0' && strspn(p, ws) == 0) {
1188                                 snprintf(msg, msglen, "quoted string not"
1189                                     " followed by white space");
1190                                 return -1;
1191                         }
1192                 } else {
1193                         fields[i] = p;
1194                         p += strcspn(p, ws);
1195                         if (*p != '\0')
1196                                 *p++ = '\0';
1197                 }
1198                 i++;
1199         }
1200         return i;
1201 }
1202
1203 int
1204 rad_get_vendor_attr(u_int32_t *vendor, const void **data, size_t *len)
1205 {
1206         struct vendor_attribute *attr;
1207
1208         attr = (struct vendor_attribute *)*data;
1209         *vendor = ntohl(attr->vendor_value);
1210         *data = attr->attrib_data;
1211         *len = attr->attrib_len - 2;
1212
1213         return (attr->attrib_type);
1214 }
1215
1216 int
1217 rad_put_vendor_addr(struct rad_handle *h, int vendor, int type,
1218     struct in_addr addr)
1219 {
1220         return (rad_put_vendor_attr(h, vendor, type, &addr.s_addr,
1221             sizeof addr.s_addr));
1222 }
1223
1224 int
1225 rad_put_vendor_attr(struct rad_handle *h, int vendor, int type,
1226     const void *value, size_t len)
1227 {
1228         struct vendor_attribute *attr;
1229         int res;
1230
1231         if (!h->out_created) {
1232                 generr(h, "Please call rad_create_request()"
1233                     " before putting attributes");
1234                 return -1;
1235         }
1236
1237         if ((attr = malloc(len + 6)) == NULL) {
1238                 generr(h, "malloc failure (%zu bytes)", len + 6);
1239                 return -1;
1240         }
1241
1242         attr->vendor_value = htonl(vendor);
1243         attr->attrib_type = type;
1244         attr->attrib_len = len + 2;
1245         memcpy(attr->attrib_data, value, len);
1246
1247         res = put_raw_attr(h, RAD_VENDOR_SPECIFIC, attr, len + 6);
1248         free(attr);
1249         if (res == 0 && vendor == RAD_VENDOR_MICROSOFT
1250             && (type == RAD_MICROSOFT_MS_CHAP_RESPONSE
1251             || type == RAD_MICROSOFT_MS_CHAP2_RESPONSE)) {
1252                 h->chap_pass = 1;
1253         }
1254         return (res);
1255 }
1256
1257 int
1258 rad_put_vendor_int(struct rad_handle *h, int vendor, int type, u_int32_t i)
1259 {
1260         u_int32_t value;
1261
1262         value = htonl(i);
1263         return (rad_put_vendor_attr(h, vendor, type, &value, sizeof value));
1264 }
1265
1266 int
1267 rad_put_vendor_string(struct rad_handle *h, int vendor, int type,
1268     const char *str)
1269 {
1270         return (rad_put_vendor_attr(h, vendor, type, str, strlen(str)));
1271 }
1272
1273 ssize_t
1274 rad_request_authenticator(struct rad_handle *h, char *buf, size_t len)
1275 {
1276         if (len < LEN_AUTH)
1277                 return (-1);
1278         memcpy(buf, h->out + POS_AUTH, LEN_AUTH);
1279         if (len > LEN_AUTH)
1280                 buf[LEN_AUTH] = '\0';
1281         return (LEN_AUTH);
1282 }
1283
1284 u_char *
1285 rad_demangle(struct rad_handle *h, const void *mangled, size_t mlen)
1286 {
1287         char R[LEN_AUTH];
1288         const char *S;
1289         int i, Ppos;
1290         MD5_CTX Context;
1291         u_char b[MD5_DIGEST_LENGTH], *C, *demangled;
1292
1293         if ((mlen % 16 != 0) || mlen > 128) {
1294                 generr(h, "Cannot interpret mangled data of length %lu",
1295                     (u_long)mlen);
1296                 return NULL;
1297         }
1298
1299         C = (u_char *)mangled;
1300
1301         /* We need the shared secret as Salt */
1302         S = rad_server_secret(h);
1303
1304         /* We need the request authenticator */
1305         if (rad_request_authenticator(h, R, sizeof R) != LEN_AUTH) {
1306                 generr(h, "Cannot obtain the RADIUS request authenticator");
1307                 return NULL;
1308         }
1309
1310         demangled = malloc(mlen);
1311         if (!demangled)
1312                 return NULL;
1313
1314         MD5Init(&Context);
1315         MD5Update(&Context, S, strlen(S));
1316         MD5Update(&Context, R, LEN_AUTH);
1317         MD5Final(b, &Context);
1318         Ppos = 0;
1319         while (mlen) {
1320
1321                 mlen -= 16;
1322                 for (i = 0; i < 16; i++)
1323                         demangled[Ppos++] = C[i] ^ b[i];
1324
1325                 if (mlen) {
1326                         MD5Init(&Context);
1327                         MD5Update(&Context, S, strlen(S));
1328                         MD5Update(&Context, C, 16);
1329                         MD5Final(b, &Context);
1330                 }
1331
1332                 C += 16;
1333         }
1334
1335         return demangled;
1336 }
1337
1338 u_char *
1339 rad_demangle_mppe_key(struct rad_handle *h, const void *mangled,
1340     size_t mlen, size_t *len)
1341 {
1342         char R[LEN_AUTH];    /* variable names as per rfc2548 */
1343         const char *S;
1344         u_char b[MD5_DIGEST_LENGTH], *demangled;
1345         const u_char *A, *C;
1346         MD5_CTX Context;
1347         int Slen, i, Clen, Ppos;
1348         u_char *P;
1349
1350         if (mlen % 16 != SALT_LEN) {
1351                 generr(h, "Cannot interpret mangled data of length %lu",
1352                     (u_long)mlen);
1353                 return NULL;
1354         }
1355
1356         /* We need the RADIUS Request-Authenticator */
1357         if (rad_request_authenticator(h, R, sizeof R) != LEN_AUTH) {
1358                 generr(h, "Cannot obtain the RADIUS request authenticator");
1359                 return NULL;
1360         }
1361
1362         A = (const u_char *)mangled;      /* Salt comes first */
1363         C = (const u_char *)mangled + SALT_LEN;  /* Then the ciphertext */
1364         Clen = mlen - SALT_LEN;
1365         S = rad_server_secret(h);    /* We need the RADIUS secret */
1366         Slen = strlen(S);
1367         P = alloca(Clen);        /* We derive our plaintext */
1368
1369         MD5Init(&Context);
1370         MD5Update(&Context, S, Slen);
1371         MD5Update(&Context, R, LEN_AUTH);
1372         MD5Update(&Context, A, SALT_LEN);
1373         MD5Final(b, &Context);
1374         Ppos = 0;
1375
1376         while (Clen) {
1377                 Clen -= 16;
1378
1379                 for (i = 0; i < 16; i++)
1380                     P[Ppos++] = C[i] ^ b[i];
1381
1382                 if (Clen) {
1383                         MD5Init(&Context);
1384                         MD5Update(&Context, S, Slen);
1385                         MD5Update(&Context, C, 16);
1386                         MD5Final(b, &Context);
1387                 }
1388
1389                 C += 16;
1390         }
1391
1392         /*
1393         * The resulting plain text consists of a one-byte length, the text and
1394         * maybe some padding.
1395         */
1396         *len = *P;
1397         if (*len > mlen - 1) {
1398                 generr(h, "Mangled data seems to be garbage %zu %zu",
1399                     *len, mlen-1);
1400                 return NULL;
1401         }
1402
1403         if (*len > MPPE_KEY_LEN * 2) {
1404                 generr(h, "Key to long (%zu) for me max. %d",
1405                     *len, MPPE_KEY_LEN * 2);
1406                 return NULL;
1407         }
1408         demangled = malloc(*len);
1409         if (!demangled)
1410                 return NULL;
1411
1412         memcpy(demangled, P + 1, *len);
1413         return demangled;
1414 }
1415
1416 const char *
1417 rad_server_secret(struct rad_handle *h)
1418 {
1419         return (h->servers[h->srv].secret);
1420 }