radius.c revision 99418
1/*
2 * Copyright 1999 Internet Business Solutions Ltd., Switzerland
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 * $FreeBSD: head/usr.sbin/ppp/radius.c 99418 2002-07-04 23:33:35Z brian $
27 *
28 */
29
30#include <sys/param.h>
31
32#include <sys/socket.h>
33#include <netinet/in_systm.h>
34#include <netinet/in.h>
35#include <netinet/ip.h>
36#include <arpa/inet.h>
37#include <sys/un.h>
38#include <net/route.h>
39
40#ifdef LOCALRAD
41#include "radlib.h"
42#include "radlib_vs.h"
43#else
44#include <radlib.h>
45#include <radlib_vs.h>
46#endif
47
48#include <errno.h>
49#ifndef NODES
50#include <md5.h>
51#endif
52#include <stdio.h>
53#include <stdlib.h>
54#include <string.h>
55#include <sys/time.h>
56#include <termios.h>
57#include <unistd.h>
58#include <netdb.h>
59
60#include "layer.h"
61#include "defs.h"
62#include "log.h"
63#include "descriptor.h"
64#include "prompt.h"
65#include "timer.h"
66#include "fsm.h"
67#include "iplist.h"
68#include "slcompress.h"
69#include "throughput.h"
70#include "lqr.h"
71#include "hdlc.h"
72#include "mbuf.h"
73#include "ncpaddr.h"
74#include "ip.h"
75#include "ipcp.h"
76#include "ipv6cp.h"
77#include "route.h"
78#include "command.h"
79#include "filter.h"
80#include "lcp.h"
81#include "ccp.h"
82#include "link.h"
83#include "mp.h"
84#include "radius.h"
85#include "auth.h"
86#include "async.h"
87#include "physical.h"
88#include "chat.h"
89#include "cbcp.h"
90#include "chap.h"
91#include "datalink.h"
92#include "ncp.h"
93#include "bundle.h"
94#include "proto.h"
95
96#ifndef NODES
97struct mschap_response {
98  u_char ident;
99  u_char flags;
100  u_char lm_response[24];
101  u_char nt_response[24];
102};
103
104struct mschap2_response {
105  u_char ident;
106  u_char flags;
107  u_char pchallenge[16];
108  u_char reserved[8];
109  u_char response[24];
110};
111
112#define	AUTH_LEN	16
113#define	SALT_LEN	2
114#endif
115
116static const char *
117radius_policyname(int policy)
118{
119  switch(policy) {
120  case MPPE_POLICY_ALLOWED:
121    return "Allowed";
122  case MPPE_POLICY_REQUIRED:
123    return "Required";
124  }
125  return NumStr(policy, NULL, 0);
126}
127
128static const char *
129radius_typesname(int types)
130{
131  switch(types) {
132  case MPPE_TYPE_40BIT:
133    return "40 bit";
134  case MPPE_TYPE_128BIT:
135    return "128 bit";
136  case MPPE_TYPE_40BIT|MPPE_TYPE_128BIT:
137    return "40 or 128 bit";
138  }
139  return NumStr(types, NULL, 0);
140}
141
142#ifndef NODES
143static void
144demangle(struct radius *r, const void *mangled, size_t mlen,
145         char **buf, size_t *len)
146{
147  char R[AUTH_LEN];		/* variable names as per rfc2548 */
148  const char *S;
149  u_char b[16];
150  const u_char *A, *C;
151  MD5_CTX Context;
152  int Slen, i, Clen, Ppos;
153  u_char *P;
154
155  if (mlen % 16 != SALT_LEN) {
156    log_Printf(LogWARN, "Cannot interpret mangled data of length %ld\n",
157               (u_long)mlen);
158    *buf = NULL;
159    *len = 0;
160    return;
161  }
162
163  /* We need the RADIUS Request-Authenticator */
164  if (rad_request_authenticator(r->cx.rad, R, sizeof R) != AUTH_LEN) {
165    log_Printf(LogWARN, "Cannot obtain the RADIUS request authenticator\n");
166    *buf = NULL;
167    *len = 0;
168    return;
169  }
170
171  A = (const u_char *)mangled;			/* Salt comes first */
172  C = (const u_char *)mangled + SALT_LEN;	/* Then the ciphertext */
173  Clen = mlen - SALT_LEN;
174  S = rad_server_secret(r->cx.rad);		/* We need the RADIUS secret */
175  Slen = strlen(S);
176  P = alloca(Clen);				/* We derive our plaintext */
177
178  MD5Init(&Context);
179  MD5Update(&Context, S, Slen);
180  MD5Update(&Context, R, AUTH_LEN);
181  MD5Update(&Context, A, SALT_LEN);
182  MD5Final(b, &Context);
183  Ppos = 0;
184
185  while (Clen) {
186    Clen -= 16;
187
188    for (i = 0; i < 16; i++)
189      P[Ppos++] = C[i] ^ b[i];
190
191    if (Clen) {
192      MD5Init(&Context);
193      MD5Update(&Context, S, Slen);
194      MD5Update(&Context, C, 16);
195      MD5Final(b, &Context);
196    }
197
198    C += 16;
199  }
200
201  /*
202   * The resulting plain text consists of a one-byte length, the text and
203   * maybe some padding.
204   */
205  *len = *P;
206  if (*len > mlen - 1) {
207    log_Printf(LogWARN, "Mangled data seems to be garbage\n");
208    *buf = NULL;
209    *len = 0;
210    return;
211  }
212
213  *buf = malloc(*len);
214  memcpy(*buf, P + 1, *len);
215}
216#endif
217
218/*
219 * rad_continue_send_request() has given us `got' (non-zero).  Deal with it.
220 */
221static void
222radius_Process(struct radius *r, int got)
223{
224  char *argv[MAXARGS], *nuke;
225  struct bundle *bundle;
226  int argc, addrs, res, width;
227  size_t len;
228  struct ncprange dest;
229  struct ncpaddr gw;
230  const void *data;
231  const char *stype;
232  u_int32_t ipaddr, vendor;
233  struct in_addr ip;
234
235  r->cx.fd = -1;		/* Stop select()ing */
236  stype = r->cx.auth ? "auth" : "acct";
237
238  switch (got) {
239    case RAD_ACCESS_ACCEPT:
240      log_Printf(LogPHASE, "Radius(%s): ACCEPT received\n", stype);
241      if (!r->cx.auth) {
242        rad_close(r->cx.rad);
243        return;
244      }
245      break;
246
247    case RAD_ACCESS_REJECT:
248      log_Printf(LogPHASE, "Radius(%s): REJECT received\n", stype);
249      if (!r->cx.auth) {
250        rad_close(r->cx.rad);
251        return;
252      }
253      break;
254
255    case RAD_ACCESS_CHALLENGE:
256      /* we can't deal with this (for now) ! */
257      log_Printf(LogPHASE, "Radius: CHALLENGE received (can't handle yet)\n");
258      if (r->cx.auth)
259        auth_Failure(r->cx.auth);
260      rad_close(r->cx.rad);
261      return;
262
263    case RAD_ACCOUNTING_RESPONSE:
264      log_Printf(LogPHASE, "Radius(%s): Accounting response received\n", stype);
265      if (r->cx.auth)
266        auth_Failure(r->cx.auth);		/* unexpected !!! */
267
268      /* No further processing for accounting requests, please */
269      rad_close(r->cx.rad);
270      return;
271
272    case -1:
273      log_Printf(LogPHASE, "radius(%s): %s\n", stype, rad_strerror(r->cx.rad));
274      if (r->cx.auth)
275        auth_Failure(r->cx.auth);
276      rad_close(r->cx.rad);
277      return;
278
279    default:
280      log_Printf(LogERROR, "rad_send_request(%s): Failed %d: %s\n", stype,
281                 got, rad_strerror(r->cx.rad));
282      if (r->cx.auth)
283        auth_Failure(r->cx.auth);
284      rad_close(r->cx.rad);
285      return;
286  }
287
288  /* Let's see what we've got in our reply */
289  r->ip.s_addr = r->mask.s_addr = INADDR_NONE;
290  r->mtu = 0;
291  r->vj = 0;
292  while ((res = rad_get_attr(r->cx.rad, &data, &len)) > 0) {
293    switch (res) {
294      case RAD_FRAMED_IP_ADDRESS:
295        r->ip = rad_cvt_addr(data);
296        log_Printf(LogPHASE, " IP %s\n", inet_ntoa(r->ip));
297        break;
298
299      case RAD_FILTER_ID:
300        free(r->filterid);
301        if ((r->filterid = rad_cvt_string(data, len)) == NULL) {
302          log_Printf(LogERROR, "rad_cvt_string: %s\n", rad_strerror(r->cx.rad));
303          auth_Failure(r->cx.auth);
304          rad_close(r->cx.rad);
305          return;
306        }
307        log_Printf(LogPHASE, " Filter \"%s\"\n", r->filterid);
308        break;
309
310      case RAD_SESSION_TIMEOUT:
311        r->sessiontime = rad_cvt_int(data);
312        log_Printf(LogPHASE, " Session-Timeout %lu\n", r->sessiontime);
313        break;
314
315      case RAD_FRAMED_IP_NETMASK:
316        r->mask = rad_cvt_addr(data);
317        log_Printf(LogPHASE, " Netmask %s\n", inet_ntoa(r->mask));
318        break;
319
320      case RAD_FRAMED_MTU:
321        r->mtu = rad_cvt_int(data);
322        log_Printf(LogPHASE, " MTU %lu\n", r->mtu);
323        break;
324
325      case RAD_FRAMED_ROUTING:
326        /* Disabled for now - should we automatically set up some filters ? */
327        /* rad_cvt_int(data); */
328        /* bit 1 = Send routing packets */
329        /* bit 2 = Receive routing packets */
330        break;
331
332      case RAD_FRAMED_COMPRESSION:
333        r->vj = rad_cvt_int(data) == 1 ? 1 : 0;
334        log_Printf(LogPHASE, " VJ %sabled\n", r->vj ? "en" : "dis");
335        break;
336
337      case RAD_FRAMED_ROUTE:
338        /*
339         * We expect a string of the format ``dest[/bits] gw [metrics]''
340         * Any specified metrics are ignored.  MYADDR and HISADDR are
341         * understood for ``dest'' and ``gw'' and ``0.0.0.0'' is the same
342         * as ``HISADDR''.
343         */
344
345        if ((nuke = rad_cvt_string(data, len)) == NULL) {
346          log_Printf(LogERROR, "rad_cvt_string: %s\n", rad_strerror(r->cx.rad));
347          auth_Failure(r->cx.auth);
348          rad_close(r->cx.rad);
349          return;
350        }
351
352        log_Printf(LogPHASE, " Route: %s\n", nuke);
353        bundle = r->cx.auth->physical->dl->bundle;
354        ip.s_addr = INADDR_ANY;
355        ncprange_setip4host(&dest, ip);
356        argc = command_Interpret(nuke, strlen(nuke), argv);
357        if (argc < 0)
358          log_Printf(LogWARN, "radius: %s: Syntax error\n",
359                     argc == 1 ? argv[0] : "\"\"");
360        else if (argc < 2)
361          log_Printf(LogWARN, "radius: %s: Invalid route\n",
362                     argc == 1 ? argv[0] : "\"\"");
363        else if ((strcasecmp(argv[0], "default") != 0 &&
364                  !ncprange_aton(&dest, &bundle->ncp, argv[0])) ||
365                 !ncpaddr_aton(&gw, &bundle->ncp, argv[1]))
366          log_Printf(LogWARN, "radius: %s %s: Invalid route\n",
367                     argv[0], argv[1]);
368        else {
369          ncprange_getwidth(&dest, &width);
370          if (width == 32 && strchr(argv[0], '/') == NULL) {
371            /* No mask specified - use the natural mask */
372            ncprange_getip4addr(&dest, &ip);
373            ncprange_setip4mask(&dest, addr2mask(ip));
374          }
375          addrs = 0;
376
377          if (!strncasecmp(argv[0], "HISADDR", 7))
378            addrs = ROUTE_DSTHISADDR;
379          else if (!strncasecmp(argv[0], "MYADDR", 6))
380            addrs = ROUTE_DSTMYADDR;
381
382          if (ncpaddr_getip4addr(&gw, &ipaddr) && ipaddr == INADDR_ANY) {
383            addrs |= ROUTE_GWHISADDR;
384            ncpaddr_setip4(&gw, bundle->ncp.ipcp.peer_ip);
385          } else if (strcasecmp(argv[1], "HISADDR") == 0)
386            addrs |= ROUTE_GWHISADDR;
387
388          route_Add(&r->routes, addrs, &dest, &gw);
389        }
390        free(nuke);
391        break;
392
393      case RAD_REPLY_MESSAGE:
394        free(r->repstr);
395        if ((r->repstr = rad_cvt_string(data, len)) == NULL) {
396          log_Printf(LogERROR, "rad_cvt_string: %s\n", rad_strerror(r->cx.rad));
397          auth_Failure(r->cx.auth);
398          rad_close(r->cx.rad);
399          return;
400        }
401        log_Printf(LogPHASE, " Reply-Message \"%s\"\n", r->repstr);
402        break;
403
404      case RAD_VENDOR_SPECIFIC:
405        if ((res = rad_get_vendor_attr(&vendor, &data, &len)) <= 0) {
406          log_Printf(LogERROR, "rad_get_vendor_attr: %s (failing!)\n",
407                     rad_strerror(r->cx.rad));
408          auth_Failure(r->cx.auth);
409          rad_close(r->cx.rad);
410          return;
411        }
412
413	switch (vendor) {
414          case RAD_VENDOR_MICROSOFT:
415            switch (res) {
416#ifndef NODES
417              case RAD_MICROSOFT_MS_CHAP_ERROR:
418                free(r->errstr);
419                if (len == 0)
420                  r->errstr = NULL;
421                else {
422                  if (len < 3 || ((const char *)data)[1] != '=') {
423                    /*
424                     * Only point at the String field if we don't think the
425                     * peer has misformatted the response.
426                     */
427                    ((const char *)data)++;
428                    len--;
429                  } else
430                    log_Printf(LogWARN, "Warning: The MS-CHAP-Error "
431                               "attribute is mis-formatted.  Compensating\n");
432                  if ((r->errstr = rad_cvt_string((const char *)data,
433                                                  len)) == NULL) {
434                    log_Printf(LogERROR, "rad_cvt_string: %s\n",
435                               rad_strerror(r->cx.rad));
436                    auth_Failure(r->cx.auth);
437                    rad_close(r->cx.rad);
438                    return;
439                  }
440                  log_Printf(LogPHASE, " MS-CHAP-Error \"%s\"\n", r->errstr);
441                }
442                break;
443
444              case RAD_MICROSOFT_MS_CHAP2_SUCCESS:
445                free(r->msrepstr);
446                if (len == 0)
447                  r->msrepstr = NULL;
448                else {
449                  if (len < 3 || ((const char *)data)[1] != '=') {
450                    /*
451                     * Only point at the String field if we don't think the
452                     * peer has misformatted the response.
453                     */
454                    ((const char *)data)++;
455                    len--;
456                  } else
457                    log_Printf(LogWARN, "Warning: The MS-CHAP2-Success "
458                               "attribute is mis-formatted.  Compensating\n");
459                  if ((r->msrepstr = rad_cvt_string((const char *)data,
460                                                    len)) == NULL) {
461                    log_Printf(LogERROR, "rad_cvt_string: %s\n",
462                               rad_strerror(r->cx.rad));
463                    auth_Failure(r->cx.auth);
464                    rad_close(r->cx.rad);
465                    return;
466                  }
467                  log_Printf(LogPHASE, " MS-CHAP2-Success \"%s\"\n",
468                             r->msrepstr);
469                }
470                break;
471
472              case RAD_MICROSOFT_MS_MPPE_ENCRYPTION_POLICY:
473                r->mppe.policy = rad_cvt_int(data);
474                log_Printf(LogPHASE, " MS-MPPE-Encryption-Policy %s\n",
475                           radius_policyname(r->mppe.policy));
476                break;
477
478              case RAD_MICROSOFT_MS_MPPE_ENCRYPTION_TYPES:
479                r->mppe.types = rad_cvt_int(data);
480                log_Printf(LogPHASE, " MS-MPPE-Encryption-Types %s\n",
481                           radius_typesname(r->mppe.types));
482                break;
483
484              case RAD_MICROSOFT_MS_MPPE_RECV_KEY:
485                free(r->mppe.recvkey);
486		demangle(r, data, len, &r->mppe.recvkey, &r->mppe.recvkeylen);
487                log_Printf(LogPHASE, " MS-MPPE-Recv-Key ********\n");
488                break;
489
490              case RAD_MICROSOFT_MS_MPPE_SEND_KEY:
491		demangle(r, data, len, &r->mppe.sendkey, &r->mppe.sendkeylen);
492                log_Printf(LogPHASE, " MS-MPPE-Send-Key ********\n");
493                break;
494#endif
495
496              default:
497                log_Printf(LogDEBUG, "Dropping MICROSOFT vendor specific "
498                           "RADIUS attribute %d\n", res);
499                break;
500            }
501            break;
502
503          default:
504            log_Printf(LogDEBUG, "Dropping vendor %lu RADIUS attribute %d\n",
505                       (unsigned long)vendor, res);
506            break;
507        }
508        break;
509
510      default:
511        log_Printf(LogDEBUG, "Dropping RADIUS attribute %d\n", res);
512        break;
513    }
514  }
515
516  if (res == -1) {
517    log_Printf(LogERROR, "rad_get_attr: %s (failing!)\n",
518               rad_strerror(r->cx.rad));
519    auth_Failure(r->cx.auth);
520  } else if (got == RAD_ACCESS_REJECT)
521    auth_Failure(r->cx.auth);
522  else {
523    r->valid = 1;
524    auth_Success(r->cx.auth);
525  }
526  rad_close(r->cx.rad);
527}
528
529/*
530 * We've either timed out or select()ed on the read descriptor
531 */
532static void
533radius_Continue(struct radius *r, int sel)
534{
535  struct timeval tv;
536  int got;
537
538  timer_Stop(&r->cx.timer);
539  if ((got = rad_continue_send_request(r->cx.rad, sel, &r->cx.fd, &tv)) == 0) {
540    log_Printf(LogPHASE, "Radius: Request re-sent\n");
541    r->cx.timer.load = tv.tv_usec / TICKUNIT + tv.tv_sec * SECTICKS;
542    timer_Start(&r->cx.timer);
543    return;
544  }
545
546  radius_Process(r, got);
547}
548
549/*
550 * Time to call rad_continue_send_request() - timed out.
551 */
552static void
553radius_Timeout(void *v)
554{
555  radius_Continue((struct radius *)v, 0);
556}
557
558/*
559 * Time to call rad_continue_send_request() - something to read.
560 */
561static void
562radius_Read(struct fdescriptor *d, struct bundle *bundle, const fd_set *fdset)
563{
564  radius_Continue(descriptor2radius(d), 1);
565}
566
567/*
568 * Behave as a struct fdescriptor (descriptor.h)
569 */
570static int
571radius_UpdateSet(struct fdescriptor *d, fd_set *r, fd_set *w, fd_set *e, int *n)
572{
573  struct radius *rad = descriptor2radius(d);
574
575  if (r && rad->cx.fd != -1) {
576    FD_SET(rad->cx.fd, r);
577    if (*n < rad->cx.fd + 1)
578      *n = rad->cx.fd + 1;
579    log_Printf(LogTIMER, "Radius: fdset(r) %d\n", rad->cx.fd);
580    return 1;
581  }
582
583  return 0;
584}
585
586/*
587 * Behave as a struct fdescriptor (descriptor.h)
588 */
589static int
590radius_IsSet(struct fdescriptor *d, const fd_set *fdset)
591{
592  struct radius *r = descriptor2radius(d);
593
594  return r && r->cx.fd != -1 && FD_ISSET(r->cx.fd, fdset);
595}
596
597/*
598 * Behave as a struct fdescriptor (descriptor.h)
599 */
600static int
601radius_Write(struct fdescriptor *d, struct bundle *bundle, const fd_set *fdset)
602{
603  /* We never want to write here ! */
604  log_Printf(LogALERT, "radius_Write: Internal error: Bad call !\n");
605  return 0;
606}
607
608/*
609 * Initialise ourselves
610 */
611void
612radius_Init(struct radius *r)
613{
614  r->desc.type = RADIUS_DESCRIPTOR;
615  r->desc.UpdateSet = radius_UpdateSet;
616  r->desc.IsSet = radius_IsSet;
617  r->desc.Read = radius_Read;
618  r->desc.Write = radius_Write;
619  r->cx.fd = -1;
620  r->cx.rad = NULL;
621  memset(&r->cx.timer, '\0', sizeof r->cx.timer);
622  r->cx.auth = NULL;
623  r->valid = 0;
624  r->vj = 0;
625  r->ip.s_addr = INADDR_ANY;
626  r->mask.s_addr = INADDR_NONE;
627  r->routes = NULL;
628  r->mtu = DEF_MTU;
629  r->msrepstr = NULL;
630  r->repstr = NULL;
631  r->errstr = NULL;
632  r->mppe.policy = 0;
633  r->mppe.types = 0;
634  r->mppe.recvkey = NULL;
635  r->mppe.recvkeylen = 0;
636  r->mppe.sendkey = NULL;
637  r->mppe.sendkeylen = 0;
638  *r->cfg.file = '\0';;
639  log_Printf(LogDEBUG, "Radius: radius_Init\n");
640}
641
642/*
643 * Forget everything and go back to initialised state.
644 */
645void
646radius_Destroy(struct radius *r)
647{
648  r->valid = 0;
649  log_Printf(LogDEBUG, "Radius: radius_Destroy\n");
650  timer_Stop(&r->cx.timer);
651  route_DeleteAll(&r->routes);
652  free(r->filterid);
653  r->filterid = NULL;
654  free(r->msrepstr);
655  r->msrepstr = NULL;
656  free(r->repstr);
657  r->repstr = NULL;
658  free(r->errstr);
659  r->errstr = NULL;
660  free(r->mppe.recvkey);
661  r->mppe.recvkey = NULL;
662  r->mppe.recvkeylen = 0;
663  free(r->mppe.sendkey);
664  r->mppe.sendkey = NULL;
665  r->mppe.sendkeylen = 0;
666  if (r->cx.fd != -1) {
667    r->cx.fd = -1;
668    rad_close(r->cx.rad);
669  }
670}
671
672static int
673radius_put_physical_details(struct rad_handle *rad, struct physical *p)
674{
675  int slot, type;
676
677  type = RAD_VIRTUAL;
678  if (p->handler)
679    switch (p->handler->type) {
680      case I4B_DEVICE:
681        type = RAD_ISDN_SYNC;
682        break;
683
684      case TTY_DEVICE:
685        type = RAD_ASYNC;
686        break;
687
688      case ETHER_DEVICE:
689        type = RAD_ETHERNET;
690        break;
691
692      case TCP_DEVICE:
693      case UDP_DEVICE:
694      case EXEC_DEVICE:
695      case ATM_DEVICE:
696      case NG_DEVICE:
697        type = RAD_VIRTUAL;
698        break;
699    }
700
701  if (rad_put_int(rad, RAD_NAS_PORT_TYPE, type) != 0) {
702    log_Printf(LogERROR, "rad_put: rad_put_int: %s\n", rad_strerror(rad));
703    rad_close(rad);
704    return 0;
705  }
706
707  if ((slot = physical_Slot(p)) >= 0)
708    if (rad_put_int(rad, RAD_NAS_PORT, slot) != 0) {
709      log_Printf(LogERROR, "rad_put: rad_put_int: %s\n", rad_strerror(rad));
710      rad_close(rad);
711      return 0;
712    }
713
714  return 1;
715}
716
717/*
718 * Start an authentication request to the RADIUS server.
719 */
720int
721radius_Authenticate(struct radius *r, struct authinfo *authp, const char *name,
722                    const char *key, int klen, const char *nchallenge,
723                    int nclen)
724{
725  struct timeval tv;
726  int got;
727  char hostname[MAXHOSTNAMELEN];
728#if 0
729  struct hostent *hp;
730  struct in_addr hostaddr;
731#endif
732#ifndef NODES
733  struct mschap_response msresp;
734  struct mschap2_response msresp2;
735  const struct MSCHAPv2_resp *keyv2;
736#endif
737
738  if (!*r->cfg.file)
739    return 0;
740
741  if (r->cx.fd != -1)
742    /*
743     * We assume that our name/key/challenge is the same as last time,
744     * and just continue to wait for the RADIUS server(s).
745     */
746    return 1;
747
748  radius_Destroy(r);
749
750  if ((r->cx.rad = rad_auth_open()) == NULL) {
751    log_Printf(LogERROR, "rad_auth_open: %s\n", strerror(errno));
752    return 0;
753  }
754
755  if (rad_config(r->cx.rad, r->cfg.file) != 0) {
756    log_Printf(LogERROR, "rad_config: %s\n", rad_strerror(r->cx.rad));
757    rad_close(r->cx.rad);
758    return 0;
759  }
760
761  if (rad_create_request(r->cx.rad, RAD_ACCESS_REQUEST) != 0) {
762    log_Printf(LogERROR, "rad_create_request: %s\n", rad_strerror(r->cx.rad));
763    rad_close(r->cx.rad);
764    return 0;
765  }
766
767  if (rad_put_string(r->cx.rad, RAD_USER_NAME, name) != 0 ||
768      rad_put_int(r->cx.rad, RAD_SERVICE_TYPE, RAD_FRAMED) != 0 ||
769      rad_put_int(r->cx.rad, RAD_FRAMED_PROTOCOL, RAD_PPP) != 0) {
770    log_Printf(LogERROR, "rad_put: %s\n", rad_strerror(r->cx.rad));
771    rad_close(r->cx.rad);
772    return 0;
773  }
774
775  switch (authp->physical->link.lcp.want_auth) {
776  case PROTO_PAP:
777    /* We're talking PAP */
778    if (rad_put_attr(r->cx.rad, RAD_USER_PASSWORD, key, klen) != 0) {
779      log_Printf(LogERROR, "PAP: rad_put_string: %s\n",
780                 rad_strerror(r->cx.rad));
781      rad_close(r->cx.rad);
782      return 0;
783    }
784    break;
785
786  case PROTO_CHAP:
787    switch (authp->physical->link.lcp.want_authtype) {
788    case 0x5:
789      if (rad_put_attr(r->cx.rad, RAD_CHAP_PASSWORD, key, klen) != 0 ||
790          rad_put_attr(r->cx.rad, RAD_CHAP_CHALLENGE, nchallenge, nclen) != 0) {
791        log_Printf(LogERROR, "CHAP: rad_put_string: %s\n",
792                   rad_strerror(r->cx.rad));
793        rad_close(r->cx.rad);
794        return 0;
795      }
796      break;
797
798#ifndef NODES
799    case 0x80:
800      if (klen != 50) {
801        log_Printf(LogERROR, "CHAP80: Unrecognised key length %d\n", klen);
802        rad_close(r->cx.rad);
803        return 0;
804      }
805
806      rad_put_vendor_attr(r->cx.rad, RAD_VENDOR_MICROSOFT,
807                          RAD_MICROSOFT_MS_CHAP_CHALLENGE, nchallenge, nclen);
808      msresp.ident = *key;
809      msresp.flags = 0x01;
810      memcpy(msresp.lm_response, key + 1, 24);
811      memcpy(msresp.nt_response, key + 25, 24);
812      rad_put_vendor_attr(r->cx.rad, RAD_VENDOR_MICROSOFT,
813                          RAD_MICROSOFT_MS_CHAP_RESPONSE, &msresp,
814                          sizeof msresp);
815      break;
816
817    case 0x81:
818      if (klen != sizeof(*keyv2) + 1) {
819        log_Printf(LogERROR, "CHAP81: Unrecognised key length %d\n", klen);
820        rad_close(r->cx.rad);
821        return 0;
822      }
823
824      keyv2 = (const struct MSCHAPv2_resp *)(key + 1);
825      rad_put_vendor_attr(r->cx.rad, RAD_VENDOR_MICROSOFT,
826                          RAD_MICROSOFT_MS_CHAP_CHALLENGE, nchallenge, nclen);
827      msresp2.ident = *key;
828      msresp2.flags = keyv2->Flags;
829      memcpy(msresp2.response, keyv2->NTResponse, sizeof msresp2.response);
830      memset(msresp2.reserved, '\0', sizeof msresp2.reserved);
831      memcpy(msresp2.pchallenge, keyv2->PeerChallenge,
832             sizeof msresp2.pchallenge);
833      rad_put_vendor_attr(r->cx.rad, RAD_VENDOR_MICROSOFT,
834                          RAD_MICROSOFT_MS_CHAP2_RESPONSE, &msresp2,
835                          sizeof msresp2);
836      break;
837#endif
838    default:
839      log_Printf(LogERROR, "CHAP: Unrecognised type 0x%02x\n",
840                 authp->physical->link.lcp.want_authtype);
841      rad_close(r->cx.rad);
842      return 0;
843    }
844  }
845
846  if (gethostname(hostname, sizeof hostname) != 0)
847    log_Printf(LogERROR, "rad_put: gethostname(): %s\n", strerror(errno));
848  else {
849#if 0
850    if ((hp = gethostbyname(hostname)) != NULL) {
851      hostaddr.s_addr = *(u_long *)hp->h_addr;
852      if (rad_put_addr(r->cx.rad, RAD_NAS_IP_ADDRESS, hostaddr) != 0) {
853        log_Printf(LogERROR, "rad_put: rad_put_string: %s\n",
854                   rad_strerror(r->cx.rad));
855        rad_close(r->cx.rad);
856        return 0;
857      }
858    }
859#endif
860    if (rad_put_string(r->cx.rad, RAD_NAS_IDENTIFIER, hostname) != 0) {
861      log_Printf(LogERROR, "rad_put: rad_put_string: %s\n",
862                 rad_strerror(r->cx.rad));
863      rad_close(r->cx.rad);
864      return 0;
865    }
866  }
867
868  radius_put_physical_details(r->cx.rad, authp->physical);
869
870  r->cx.auth = authp;
871  if ((got = rad_init_send_request(r->cx.rad, &r->cx.fd, &tv)))
872    radius_Process(r, got);
873  else {
874    log_Printf(LogPHASE, "Radius: Request sent\n");
875    log_Printf(LogDEBUG, "Using radius_Timeout [%p]\n", radius_Timeout);
876    r->cx.timer.load = tv.tv_usec / TICKUNIT + tv.tv_sec * SECTICKS;
877    r->cx.timer.func = radius_Timeout;
878    r->cx.timer.name = "radius auth";
879    r->cx.timer.arg = r;
880    timer_Start(&r->cx.timer);
881  }
882
883  return 1;
884}
885
886/*
887 * Send an accounting request to the RADIUS server
888 */
889void
890radius_Account(struct radius *r, struct radacct *ac, struct datalink *dl,
891               int acct_type, struct in_addr *peer_ip, struct in_addr *netmask,
892               struct pppThroughput *stats)
893{
894  struct timeval tv;
895  int got;
896  char hostname[MAXHOSTNAMELEN];
897#if 0
898  struct hostent *hp;
899  struct in_addr hostaddr;
900#endif
901
902  if (!*r->cfg.file)
903    return;
904
905  if (r->cx.fd != -1)
906    /*
907     * We assume that our name/key/challenge is the same as last time,
908     * and just continue to wait for the RADIUS server(s).
909     */
910    return;
911
912  timer_Stop(&r->cx.timer);
913
914  if ((r->cx.rad = rad_acct_open()) == NULL) {
915    log_Printf(LogERROR, "rad_auth_open: %s\n", strerror(errno));
916    return;
917  }
918
919  if (rad_config(r->cx.rad, r->cfg.file) != 0) {
920    log_Printf(LogERROR, "rad_config: %s\n", rad_strerror(r->cx.rad));
921    rad_close(r->cx.rad);
922    return;
923  }
924
925  if (rad_create_request(r->cx.rad, RAD_ACCOUNTING_REQUEST) != 0) {
926    log_Printf(LogERROR, "rad_create_request: %s\n", rad_strerror(r->cx.rad));
927    rad_close(r->cx.rad);
928    return;
929  }
930
931  /* Grab some accounting data and initialize structure */
932  if (acct_type == RAD_START) {
933    ac->rad_parent = r;
934    /* Fetch username from datalink */
935    strncpy(ac->user_name, dl->peer.authname, sizeof ac->user_name);
936    ac->user_name[AUTHLEN-1] = '\0';
937
938    ac->authentic = 2;		/* Assume RADIUS verified auth data */
939
940    /* Generate a session ID */
941    snprintf(ac->session_id, sizeof ac->session_id, "%s%ld-%s%lu",
942             dl->bundle->cfg.auth.name, (long)getpid(),
943             dl->peer.authname, (unsigned long)stats->uptime);
944
945    /* And grab our MP socket name */
946    snprintf(ac->multi_session_id, sizeof ac->multi_session_id, "%s",
947             dl->bundle->ncp.mp.active ?
948             dl->bundle->ncp.mp.server.socket.sun_path : "");
949
950    /* Fetch IP, netmask from IPCP */
951    memcpy(&ac->ip, peer_ip, sizeof(ac->ip));
952    memcpy(&ac->mask, netmask, sizeof(ac->mask));
953  };
954
955  if (rad_put_string(r->cx.rad, RAD_USER_NAME, ac->user_name) != 0 ||
956      rad_put_int(r->cx.rad, RAD_SERVICE_TYPE, RAD_FRAMED) != 0 ||
957      rad_put_int(r->cx.rad, RAD_FRAMED_PROTOCOL, RAD_PPP) != 0 ||
958      rad_put_addr(r->cx.rad, RAD_FRAMED_IP_ADDRESS, ac->ip) != 0 ||
959      rad_put_addr(r->cx.rad, RAD_FRAMED_IP_NETMASK, ac->mask) != 0) {
960    log_Printf(LogERROR, "rad_put: %s\n", rad_strerror(r->cx.rad));
961    rad_close(r->cx.rad);
962    return;
963  }
964
965  if (gethostname(hostname, sizeof hostname) != 0)
966    log_Printf(LogERROR, "rad_put: gethostname(): %s\n", strerror(errno));
967  else {
968#if 0
969    if ((hp = gethostbyname(hostname)) != NULL) {
970      hostaddr.s_addr = *(u_long *)hp->h_addr;
971      if (rad_put_addr(r->cx.rad, RAD_NAS_IP_ADDRESS, hostaddr) != 0) {
972        log_Printf(LogERROR, "rad_put: rad_put_string: %s\n",
973                   rad_strerror(r->cx.rad));
974        rad_close(r->cx.rad);
975        return;
976      }
977    }
978#endif
979    if (rad_put_string(r->cx.rad, RAD_NAS_IDENTIFIER, hostname) != 0) {
980      log_Printf(LogERROR, "rad_put: rad_put_string: %s\n",
981                 rad_strerror(r->cx.rad));
982      rad_close(r->cx.rad);
983      return;
984    }
985  }
986
987  radius_put_physical_details(r->cx.rad, dl->physical);
988
989  if (rad_put_int(r->cx.rad, RAD_ACCT_STATUS_TYPE, acct_type) != 0 ||
990      rad_put_string(r->cx.rad, RAD_ACCT_SESSION_ID, ac->session_id) != 0 ||
991      rad_put_string(r->cx.rad, RAD_ACCT_MULTI_SESSION_ID,
992                     ac->multi_session_id) != 0 ||
993      rad_put_int(r->cx.rad, RAD_ACCT_DELAY_TIME, 0) != 0) {
994/* XXX ACCT_DELAY_TIME should be increased each time a packet is waiting */
995    log_Printf(LogERROR, "rad_put: %s\n", rad_strerror(r->cx.rad));
996    rad_close(r->cx.rad);
997    return;
998  }
999
1000  if (acct_type == RAD_STOP)
1001  /* Show some statistics */
1002    if (rad_put_int(r->cx.rad, RAD_ACCT_INPUT_OCTETS, stats->OctetsIn) != 0 ||
1003        rad_put_int(r->cx.rad, RAD_ACCT_INPUT_PACKETS, stats->PacketsIn) != 0 ||
1004        rad_put_int(r->cx.rad, RAD_ACCT_OUTPUT_OCTETS, stats->OctetsOut) != 0 ||
1005        rad_put_int(r->cx.rad, RAD_ACCT_OUTPUT_PACKETS, stats->PacketsOut)
1006        != 0 ||
1007        rad_put_int(r->cx.rad, RAD_ACCT_SESSION_TIME, throughput_uptime(stats))
1008        != 0) {
1009      log_Printf(LogERROR, "rad_put: %s\n", rad_strerror(r->cx.rad));
1010      rad_close(r->cx.rad);
1011      return;
1012    }
1013
1014  r->cx.auth = NULL;			/* Not valid for accounting requests */
1015  if ((got = rad_init_send_request(r->cx.rad, &r->cx.fd, &tv)))
1016    radius_Process(r, got);
1017  else {
1018    log_Printf(LogDEBUG, "Using radius_Timeout [%p]\n", radius_Timeout);
1019    r->cx.timer.load = tv.tv_usec / TICKUNIT + tv.tv_sec * SECTICKS;
1020    r->cx.timer.func = radius_Timeout;
1021    r->cx.timer.name = "radius acct";
1022    r->cx.timer.arg = r;
1023    timer_Start(&r->cx.timer);
1024  }
1025}
1026
1027/*
1028 * How do things look at the moment ?
1029 */
1030void
1031radius_Show(struct radius *r, struct prompt *p)
1032{
1033  prompt_Printf(p, " Radius config:     %s",
1034                *r->cfg.file ? r->cfg.file : "none");
1035  if (r->valid) {
1036    prompt_Printf(p, "\n                IP: %s\n", inet_ntoa(r->ip));
1037    prompt_Printf(p, "           Netmask: %s\n", inet_ntoa(r->mask));
1038    prompt_Printf(p, "               MTU: %lu\n", r->mtu);
1039    prompt_Printf(p, "                VJ: %sabled\n", r->vj ? "en" : "dis");
1040    prompt_Printf(p, "           Message: %s\n", r->repstr ? r->repstr : "");
1041    prompt_Printf(p, "   MPPE Enc Policy: %s\n",
1042                  radius_policyname(r->mppe.policy));
1043    prompt_Printf(p, "    MPPE Enc Types: %s\n",
1044                  radius_typesname(r->mppe.types));
1045    prompt_Printf(p, "     MPPE Recv Key: %seceived\n",
1046                  r->mppe.recvkey ? "R" : "Not r");
1047    prompt_Printf(p, "     MPPE Send Key: %seceived\n",
1048                  r->mppe.sendkey ? "R" : "Not r");
1049    prompt_Printf(p, " MS-CHAP2-Response: %s\n",
1050                  r->msrepstr ? r->msrepstr : "");
1051    prompt_Printf(p, "     Error Message: %s\n", r->errstr ? r->errstr : "");
1052    if (r->routes)
1053      route_ShowSticky(p, r->routes, "            Routes", 16);
1054  } else
1055    prompt_Printf(p, " (not authenticated)\n");
1056}
1057