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