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