]> git.ozlabs.org Git - ppp.git/blob - pppd/plugins/radius/radius.c
Simplified and cleaned up the radiusclient implementation, and
[ppp.git] / pppd / plugins / radius / radius.c
1 /***********************************************************************
2 *
3 * radius.c
4 *
5 * RADIUS plugin for pppd.  Performs PAP, CHAP, MS-CHAP, MS-CHAPv2
6 * authentication using RADIUS.
7 *
8 * Copyright (C) 2002 Roaring Penguin Software Inc.
9 *
10 * Based on a patch for ipppd, which is:
11 *    Copyright (C) 1996, Matjaz Godec <gody@elgo.si>
12 *    Copyright (C) 1996, Lars Fenneberg <in5y050@public.uni-hamburg.de>
13 *    Copyright (C) 1997, Miguel A.L. Paraz <map@iphil.net>
14 *
15 * Uses radiusclient library, which is:
16 *    Copyright (C) 1995,1996,1997,1998 Lars Fenneberg <lf@elemental.net>
17 *    Copyright (C) 2002 Roaring Penguin Software Inc.
18 *
19 * MPPE support is by Ralf Hofmann, <ralf.hofmann@elvido.net>, with
20 * modification from Frank Cusack, <frank@google.com>.
21 *
22 * This plugin may be distributed according to the terms of the GNU
23 * General Public License, version 2 or (at your option) any later version.
24 *
25 ***********************************************************************/
26 static char const RCSID[] =
27 "$Id: radius.c,v 1.27 2004/11/14 07:26:26 paulus Exp $";
28
29 #include "pppd.h"
30 #include "chap-new.h"
31 #ifdef CHAPMS
32 #include "chap_ms.h"
33 #ifdef MPPE
34 #include "md5.h"
35 #endif
36 #endif
37 #include "radiusclient.h"
38 #include "fsm.h"
39 #include "ipcp.h"
40 #include <syslog.h>
41 #include <sys/types.h>
42 #include <sys/time.h>
43 #include <string.h>
44 #include <netinet/in.h>
45 #include <stdlib.h>
46
47 #define BUF_LEN 1024
48
49 #define MD5_HASH_SIZE   16
50
51 static char *config_file = NULL;
52 static int add_avp(char **);
53 static struct avpopt {
54     char *vpstr;
55     struct avpopt *next;
56 } *avpopt = NULL;
57 static bool portnummap = 0;
58
59 static option_t Options[] = {
60     { "radius-config-file", o_string, &config_file },
61     { "avpair", o_special, add_avp },
62     { "map-to-ttyname", o_bool, &portnummap,
63         "Set Radius NAS-Port attribute value via libradiusclient library", OPT_PRIO | 1 },
64     { "map-to-ifname", o_bool, &portnummap,
65         "Set Radius NAS-Port attribute to number as in interface name (Default)", OPT_PRIOSUB | 0 },
66     { NULL }
67 };
68
69 static int radius_secret_check(void);
70 static int radius_pap_auth(char *user,
71                            char *passwd,
72                            char **msgp,
73                            struct wordlist **paddrs,
74                            struct wordlist **popts);
75 static int radius_chap_verify(char *user, char *ourname, int id,
76                               struct chap_digest_type *digest,
77                               unsigned char *challenge,
78                               unsigned char *response,
79                               char *message, int message_space);
80
81 static void radius_ip_up(void *opaque, int arg);
82 static void radius_ip_down(void *opaque, int arg);
83 static void make_username_realm(char *user);
84 static int radius_setparams(VALUE_PAIR *vp, char *msg, REQUEST_INFO *req_info,
85                             struct chap_digest_type *digest,
86                             unsigned char *challenge,
87                             char *message, int message_space);
88 static void radius_choose_ip(u_int32_t *addrp);
89 static int radius_init(char *msg);
90 static int get_client_port(char *ifname);
91 static int radius_allowed_address(u_int32_t addr);
92 static void radius_acct_interim(void *);
93 #ifdef MPPE
94 static int radius_setmppekeys(VALUE_PAIR *vp, REQUEST_INFO *req_info,
95                               unsigned char *);
96 static int radius_setmppekeys2(VALUE_PAIR *vp, REQUEST_INFO *req_info);
97 #endif
98
99 #ifndef MAXSESSIONID
100 #define MAXSESSIONID 32
101 #endif
102
103 #ifndef MAXCLASSLEN
104 #define MAXCLASSLEN 500
105 #endif
106
107 struct radius_state {
108     int accounting_started;
109     int initialized;
110     int client_port;
111     int choose_ip;
112     int any_ip_addr_ok;
113     int done_chap_once;
114     u_int32_t ip_addr;
115     char user[MAXNAMELEN];
116     char config_file[MAXPATHLEN];
117     char session_id[MAXSESSIONID + 1];
118     time_t start_time;
119     int acct_interim_interval;
120     SERVER *authserver;         /* Authentication server to use */
121     SERVER *acctserver;         /* Accounting server to use */
122     int class_len;
123     char class[MAXCLASSLEN];
124     VALUE_PAIR *avp;    /* Additional (user supplied) vp's to send to server */
125 };
126
127 void (*radius_attributes_hook)(VALUE_PAIR *) = NULL;
128
129 /* The pre_auth_hook MAY set authserver and acctserver if it wants.
130    In that case, they override the values in the radiusclient.conf file */
131 void (*radius_pre_auth_hook)(char const *user,
132                              SERVER **authserver,
133                              SERVER **acctserver) = NULL;
134
135 static struct radius_state rstate;
136
137 char pppd_version[] = VERSION;
138
139 /**********************************************************************
140 * %FUNCTION: plugin_init
141 * %ARGUMENTS:
142 *  None
143 * %RETURNS:
144 *  Nothing
145 * %DESCRIPTION:
146 *  Initializes RADIUS plugin.
147 ***********************************************************************/
148 void
149 plugin_init(void)
150 {
151     pap_check_hook = radius_secret_check;
152     pap_auth_hook = radius_pap_auth;
153
154     chap_check_hook = radius_secret_check;
155     chap_verify_hook = radius_chap_verify;
156
157     ip_choose_hook = radius_choose_ip;
158     allowed_address_hook = radius_allowed_address;
159
160     add_notifier(&ip_up_notifier, radius_ip_up, NULL);
161     add_notifier(&ip_down_notifier, radius_ip_down, NULL);
162
163     memset(&rstate, 0, sizeof(rstate));
164
165     strlcpy(rstate.config_file, "/etc/radiusclient/radiusclient.conf",
166             sizeof(rstate.config_file));
167
168     add_options(Options);
169
170     info("RADIUS plugin initialized.");
171 }
172
173 /**********************************************************************
174 * %FUNCTION: add_avp
175 * %ARGUMENTS:
176 *  argv -- the <attribute=value> pair to add
177 * %RETURNS:
178 *  1
179 * %DESCRIPTION:
180 *  Adds an av pair to be passed on to the RADIUS server on each request.
181 ***********************************************************************/
182 static int
183 add_avp(char **argv)
184 {
185     struct avpopt *p = malloc(sizeof(struct avpopt));
186
187     /* Append to a list of vp's for later parsing */
188     p->vpstr = strdup(*argv);
189     p->next = avpopt;
190     avpopt = p;
191
192     return 1;
193 }
194
195 /**********************************************************************
196 * %FUNCTION: radius_secret_check
197 * %ARGUMENTS:
198 *  None
199 * %RETURNS:
200 *  1 -- we are ALWAYS willing to supply a secret. :-)
201 * %DESCRIPTION:
202 * Tells pppd that we will try to authenticate the peer, and not to
203 * worry about looking in /etc/ppp/*-secrets
204 ***********************************************************************/
205 static int
206 radius_secret_check(void)
207 {
208     return 1;
209 }
210
211 /**********************************************************************
212 * %FUNCTION: radius_choose_ip
213 * %ARGUMENTS:
214 *  addrp -- where to store the IP address
215 * %RETURNS:
216 *  Nothing
217 * %DESCRIPTION:
218 *  If RADIUS server has specified an IP address, it is stored in *addrp.
219 ***********************************************************************/
220 static void
221 radius_choose_ip(u_int32_t *addrp)
222 {
223     if (rstate.choose_ip) {
224         *addrp = rstate.ip_addr;
225     }
226 }
227
228 /**********************************************************************
229 * %FUNCTION: radius_pap_auth
230 * %ARGUMENTS:
231 *  user -- user-name of peer
232 *  passwd -- password supplied by peer
233 *  msgp -- Message which will be sent in PAP response
234 *  paddrs -- set to a list of possible peer IP addresses
235 *  popts -- set to a list of additional pppd options
236 * %RETURNS:
237 *  1 if we can authenticate, -1 if we cannot.
238 * %DESCRIPTION:
239 * Performs PAP authentication using RADIUS
240 ***********************************************************************/
241 static int
242 radius_pap_auth(char *user,
243                 char *passwd,
244                 char **msgp,
245                 struct wordlist **paddrs,
246                 struct wordlist **popts)
247 {
248     VALUE_PAIR *send, *received;
249     UINT4 av_type;
250     int result;
251     static char radius_msg[BUF_LEN];
252
253     radius_msg[0] = 0;
254     *msgp = radius_msg;
255
256     if (radius_init(radius_msg) < 0) {
257         return 0;
258     }
259
260     /* Put user with potentially realm added in rstate.user */
261     make_username_realm(user);
262
263     if (radius_pre_auth_hook) {
264         radius_pre_auth_hook(rstate.user,
265                              &rstate.authserver,
266                              &rstate.acctserver);
267     }
268
269     send = NULL;
270     received = NULL;
271
272     /* Hack... the "port" is the ppp interface number.  Should really be
273        the tty */
274     rstate.client_port = get_client_port(portnummap ? devnam : ifname);
275
276     av_type = PW_FRAMED;
277     rc_avpair_add(&send, PW_SERVICE_TYPE, &av_type, 0, VENDOR_NONE);
278
279     av_type = PW_PPP;
280     rc_avpair_add(&send, PW_FRAMED_PROTOCOL, &av_type, 0, VENDOR_NONE);
281
282     rc_avpair_add(&send, PW_USER_NAME, rstate.user , 0, VENDOR_NONE);
283     rc_avpair_add(&send, PW_USER_PASSWORD, passwd, 0, VENDOR_NONE);
284     if (*remote_number) {
285         rc_avpair_add(&send, PW_CALLING_STATION_ID, remote_number, 0,
286                        VENDOR_NONE);
287     }
288
289     /* Add user specified vp's */
290     if (rstate.avp)
291         rc_avpair_insert(&send, NULL, rc_avpair_copy(rstate.avp));
292
293     if (rstate.authserver) {
294         result = rc_auth_using_server(rstate.authserver,
295                                       rstate.client_port, send,
296                                       &received, radius_msg, NULL);
297     } else {
298         result = rc_auth(rstate.client_port, send, &received, radius_msg, NULL);
299     }
300
301     if (result == OK_RC) {
302         if (radius_setparams(received, radius_msg, NULL, NULL, NULL, NULL, 0) < 0) {
303             result = ERROR_RC;
304         }
305     }
306
307     /* free value pairs */
308     rc_avpair_free(received);
309     rc_avpair_free(send);
310
311     return (result == OK_RC) ? 1 : 0;
312 }
313
314 /**********************************************************************
315 * %FUNCTION: radius_chap_verify
316 * %ARGUMENTS:
317 *  user -- name of the peer
318 *  ourname -- name for this machine
319 *  id -- the ID byte in the challenge
320 *  digest -- points to the structure representing the digest type
321 *  challenge -- the challenge string we sent (length in first byte)
322 *  response -- the response (hash) the peer sent back (length in 1st byte)
323 *  message -- space for a message to be returned to the peer
324 *  message_space -- number of bytes available at *message.
325 * %RETURNS:
326 *  1 if the response is good, 0 if it is bad
327 * %DESCRIPTION:
328 * Performs CHAP, MS-CHAP and MS-CHAPv2 authentication using RADIUS.
329 ***********************************************************************/
330 static int
331 radius_chap_verify(char *user, char *ourname, int id,
332                    struct chap_digest_type *digest,
333                    unsigned char *challenge, unsigned char *response,
334                    char *message, int message_space)
335 {
336     VALUE_PAIR *send, *received;
337     UINT4 av_type;
338     static char radius_msg[BUF_LEN];
339     int result;
340     int challenge_len, response_len;
341     u_char cpassword[MAX_RESPONSE_LEN + 1];
342 #ifdef MPPE
343     /* Need the RADIUS secret and Request Authenticator to decode MPPE */
344     REQUEST_INFO request_info, *req_info = &request_info;
345 #else
346     REQUEST_INFO *req_info = NULL;
347 #endif
348
349     challenge_len = *challenge++;
350     response_len = *response++;
351
352     radius_msg[0] = 0;
353
354     if (radius_init(radius_msg) < 0) {
355         error("%s", radius_msg);
356         return 0;
357     }
358
359     /* return error for types we can't handle */
360     if ((digest->code != CHAP_MD5)
361 #ifdef CHAPMS
362         && (digest->code != CHAP_MICROSOFT)
363         && (digest->code != CHAP_MICROSOFT_V2)
364 #endif
365         ) {
366         error("RADIUS: Challenge type %u unsupported", digest->code);
367         return 0;
368     }
369
370     /* Put user with potentially realm added in rstate.user */
371     if (!rstate.done_chap_once) {
372         make_username_realm(user);
373         rstate.client_port = get_client_port (portnummap ? devnam : ifname);
374         if (radius_pre_auth_hook) {
375             radius_pre_auth_hook(rstate.user,
376                                  &rstate.authserver,
377                                  &rstate.acctserver);
378         }
379     }
380
381     send = received = NULL;
382
383     av_type = PW_FRAMED;
384     rc_avpair_add (&send, PW_SERVICE_TYPE, &av_type, 0, VENDOR_NONE);
385
386     av_type = PW_PPP;
387     rc_avpair_add (&send, PW_FRAMED_PROTOCOL, &av_type, 0, VENDOR_NONE);
388
389     rc_avpair_add (&send, PW_USER_NAME, rstate.user , 0, VENDOR_NONE);
390
391     /*
392      * add the challenge and response fields
393      */
394     switch (digest->code) {
395     case CHAP_MD5:
396         /* CHAP-Challenge and CHAP-Password */
397         if (response_len != MD5_HASH_SIZE)
398             return 0;
399         cpassword[0] = id;
400         memcpy(&cpassword[1], response, MD5_HASH_SIZE);
401
402         rc_avpair_add(&send, PW_CHAP_CHALLENGE,
403                       challenge, challenge_len, VENDOR_NONE);
404         rc_avpair_add(&send, PW_CHAP_PASSWORD,
405                       cpassword, MD5_HASH_SIZE + 1, VENDOR_NONE);
406         break;
407
408 #ifdef CHAPMS
409     case CHAP_MICROSOFT:
410     {
411         /* MS-CHAP-Challenge and MS-CHAP-Response */
412         MS_ChapResponse *rmd = (MS_ChapResponse *) response;
413         u_char *p = cpassword;
414
415         if (response_len != MS_CHAP_RESPONSE_LEN)
416             return 0;
417         *p++ = id;
418         /* The idiots use a different field order in RADIUS than PPP */
419         memcpy(p, rmd->UseNT, sizeof(rmd->UseNT));
420         p += sizeof(rmd->UseNT);
421         memcpy(p, rmd->LANManResp, sizeof(rmd->LANManResp));
422         p += sizeof(rmd->LANManResp);
423         memcpy(p, rmd->NTResp, sizeof(rmd->NTResp));
424
425         rc_avpair_add(&send, PW_MS_CHAP_CHALLENGE,
426                       challenge, challenge_len, VENDOR_MICROSOFT);
427         rc_avpair_add(&send, PW_MS_CHAP_RESPONSE,
428                       cpassword, MS_CHAP_RESPONSE_LEN + 1, VENDOR_MICROSOFT);
429         break;
430     }
431
432     case CHAP_MICROSOFT_V2:
433     {
434         /* MS-CHAP-Challenge and MS-CHAP2-Response */
435         MS_Chap2Response *rmd = (MS_Chap2Response *) response;
436         u_char *p = cpassword;
437
438         if (response_len != MS_CHAP2_RESPONSE_LEN)
439             return 0;
440         *p++ = id;
441         /* The idiots use a different field order in RADIUS than PPP */
442         memcpy(p, rmd->Flags, sizeof(rmd->Flags));
443         p += sizeof(rmd->Flags);
444         memcpy(p, rmd->PeerChallenge, sizeof(rmd->PeerChallenge));
445         p += sizeof(rmd->PeerChallenge);
446         memcpy(p, rmd->Reserved, sizeof(rmd->Reserved));
447         p += sizeof(rmd->Reserved);
448         memcpy(p, rmd->NTResp, sizeof(rmd->NTResp));
449
450         rc_avpair_add(&send, PW_MS_CHAP_CHALLENGE,
451                       challenge, challenge_len, VENDOR_MICROSOFT);
452         rc_avpair_add(&send, PW_MS_CHAP2_RESPONSE,
453                       cpassword, MS_CHAP2_RESPONSE_LEN + 1, VENDOR_MICROSOFT);
454         break;
455     }
456 #endif
457     }
458
459     if (*remote_number) {
460         rc_avpair_add(&send, PW_CALLING_STATION_ID, remote_number, 0,
461                        VENDOR_NONE);
462     }
463
464     /* Add user specified vp's */
465     if (rstate.avp)
466         rc_avpair_insert(&send, NULL, rc_avpair_copy(rstate.avp));
467
468     /*
469      * make authentication with RADIUS server
470      */
471
472     if (rstate.authserver) {
473         result = rc_auth_using_server(rstate.authserver,
474                                       rstate.client_port, send,
475                                       &received, radius_msg, req_info);
476     } else {
477         result = rc_auth(rstate.client_port, send, &received, radius_msg,
478                          req_info);
479     }
480
481     if (result == OK_RC) {
482         if (!rstate.done_chap_once) {
483             if (radius_setparams(received, radius_msg, req_info, digest,
484                                  challenge, message, message_space) < 0) {
485                 error("%s", radius_msg);
486                 result = ERROR_RC;
487             } else {
488                 rstate.done_chap_once = 1;
489             }
490         }
491     }
492
493     rc_avpair_free(received);
494     rc_avpair_free (send);
495     return (result == OK_RC);
496 }
497
498 /**********************************************************************
499 * %FUNCTION: make_username_realm
500 * %ARGUMENTS:
501 *  user -- the user given to pppd
502 * %RETURNS:
503 *  Nothing
504 * %DESCRIPTION:
505 *  Copies user into rstate.user.  If it lacks a realm (no "@domain" part),
506 * then the default realm from the radiusclient config file is added.
507 ***********************************************************************/
508 static void
509 make_username_realm(char *user)
510 {
511     char *default_realm;
512
513     if ( user != NULL ) {
514         strlcpy(rstate.user, user, sizeof(rstate.user));
515     }  else {
516         rstate.user[0] = 0;
517     }
518
519     default_realm = rc_conf_str("default_realm");
520
521     if (!strchr(rstate.user, '@') &&
522         default_realm &&
523         (*default_realm != '\0')) {
524         strlcat(rstate.user, "@", sizeof(rstate.user));
525         strlcat(rstate.user, default_realm, sizeof(rstate.user));
526     }
527 }
528
529 /**********************************************************************
530 * %FUNCTION: radius_setparams
531 * %ARGUMENTS:
532 *  vp -- received value-pairs
533 *  msg -- buffer in which to place error message.  Holds up to BUF_LEN chars
534 * %RETURNS:
535 *  >= 0 on success; -1 on failure
536 * %DESCRIPTION:
537 *  Parses attributes sent by RADIUS server and sets them in pppd.
538 ***********************************************************************/
539 static int
540 radius_setparams(VALUE_PAIR *vp, char *msg, REQUEST_INFO *req_info,
541                  struct chap_digest_type *digest, unsigned char *challenge,
542                  char *message, int message_space)
543 {
544     u_int32_t remote;
545     int ms_chap2_success = 0;
546 #ifdef MPPE
547     int mppe_enc_keys = 0;      /* whether or not these were received */
548     int mppe_enc_policy = 0;
549     int mppe_enc_types = 0;
550 #endif
551
552     /* Send RADIUS attributes to anyone else who might be interested */
553     if (radius_attributes_hook) {
554         (*radius_attributes_hook)(vp);
555     }
556
557     /*
558      * service type (if not framed then quit),
559      * new IP address (RADIUS can define static IP for some users),
560      */
561
562     while (vp) {
563         if (vp->vendorcode == VENDOR_NONE) {
564             switch (vp->attribute) {
565             case PW_SERVICE_TYPE:
566                 /* check for service type       */
567                 /* if not FRAMED then exit      */
568                 if (vp->lvalue != PW_FRAMED) {
569                     slprintf(msg, BUF_LEN, "RADIUS: wrong service type %ld for %s",
570                              vp->lvalue, rstate.user);
571                     return -1;
572                 }
573                 break;
574
575             case PW_FRAMED_PROTOCOL:
576                 /* check for framed protocol type       */
577                 /* if not PPP then also exit            */
578                 if (vp->lvalue != PW_PPP) {
579                     slprintf(msg, BUF_LEN, "RADIUS: wrong framed protocol %ld for %s",
580                              vp->lvalue, rstate.user);
581                     return -1;
582                 }
583                 break;
584
585             case PW_SESSION_TIMEOUT:
586                 /* Session timeout */
587                 maxconnect = vp->lvalue;
588                 break;
589 #ifdef MAXOCTETS
590             case PW_SESSION_OCTETS_LIMIT:
591                 /* Session traffic limit */
592                 maxoctets = vp->lvalue;
593                 break;
594             case PW_OCTETS_DIRECTION:
595                 /* Session traffic limit direction check */
596                 maxoctets_dir = ( vp->lvalue > 4 ) ? 0 : vp->lvalue ;
597                 break;
598 #endif
599             case PW_ACCT_INTERIM_INTERVAL:
600                 /* Send accounting updates every few seconds */
601                 rstate.acct_interim_interval = vp->lvalue;
602                 /* RFC says it MUST NOT be less than 60 seconds */
603                 /* We use "0" to signify not sending updates */
604                 if (rstate.acct_interim_interval &&
605                     rstate.acct_interim_interval < 60) {
606                     rstate.acct_interim_interval = 60;
607                 }
608                 break;
609             case PW_FRAMED_IP_ADDRESS:
610                 /* seting up remote IP addresses */
611                 remote = vp->lvalue;
612                 if (remote == 0xffffffff) {
613                     /* 0xffffffff means user should be allowed to select one */
614                     rstate.any_ip_addr_ok = 1;
615                 } else if (remote != 0xfffffffe) {
616                     /* 0xfffffffe means NAS should select an ip address */
617                     remote = htonl(vp->lvalue);
618                     if (bad_ip_adrs (remote)) {
619                         slprintf(msg, BUF_LEN, "RADIUS: bad remote IP address %I for %s",
620                                  remote, rstate.user);
621                         return -1;
622                     }
623                     rstate.choose_ip = 1;
624                     rstate.ip_addr = remote;
625                 }
626                 break;
627             case PW_CLASS:
628                 /* Save Class attribute to pass it in accounting request */
629                 if (vp->lvalue <= MAXCLASSLEN) {
630                     rstate.class_len=vp->lvalue;
631                     memcpy(rstate.class, vp->strvalue, rstate.class_len);
632                 } /* else too big for our buffer - ignore it */
633                 break;
634             }
635
636
637 #ifdef CHAPMS
638         } else if (vp->vendorcode == VENDOR_MICROSOFT) {
639             switch (vp->attribute) {
640             case PW_MS_CHAP2_SUCCESS:
641                 if ((vp->lvalue != 43) || strncmp(vp->strvalue + 1, "S=", 2)) {
642                     slprintf(msg,BUF_LEN,"RADIUS: bad MS-CHAP2-Success packet");
643                     return -1;
644                 }
645                 if (message != NULL)
646                     strlcpy(message, vp->strvalue + 1, message_space);
647                 ms_chap2_success = 1;
648                 break;
649
650 #ifdef MPPE
651             case PW_MS_CHAP_MPPE_KEYS:
652                 if (radius_setmppekeys(vp, req_info, challenge) < 0) {
653                     slprintf(msg, BUF_LEN,
654                              "RADIUS: bad MS-CHAP-MPPE-Keys attribute");
655                     return -1;
656                 }
657                 mppe_enc_keys = 1;
658                 break;
659
660             case PW_MS_MPPE_SEND_KEY:
661             case PW_MS_MPPE_RECV_KEY:
662                 if (radius_setmppekeys2(vp, req_info) < 0) {
663                     slprintf(msg, BUF_LEN,
664                              "RADIUS: bad MS-MPPE-%s-Key attribute",
665                              (vp->attribute == PW_MS_MPPE_SEND_KEY)?
666                              "Send": "Recv");
667                     return -1;
668                 }
669                 mppe_enc_keys = 1;
670                 break;
671
672             case PW_MS_MPPE_ENCRYPTION_POLICY:
673                 mppe_enc_policy = vp->lvalue;   /* save for later */
674                 break;
675
676             case PW_MS_MPPE_ENCRYPTION_TYPES:
677                 mppe_enc_types = vp->lvalue;    /* save for later */
678                 break;
679
680 #endif /* MPPE */
681 #if 0
682             case PW_MS_PRIMARY_DNS_SERVER:
683             case PW_MS_SECONDARY_DNS_SERVER:
684             case PW_MS_PRIMARY_NBNS_SERVER:
685             case PW_MS_SECONDARY_NBNS_SERVER:
686                 break;
687 #endif
688             }
689 #endif /* CHAPMS */
690         }
691         vp = vp->next;
692     }
693
694     /* Require a valid MS-CHAP2-SUCCESS for MS-CHAPv2 auth */
695     if (digest && (digest->code == CHAP_MICROSOFT_V2) && !ms_chap2_success)
696         return -1;
697
698 #ifdef MPPE
699     /*
700      * Require both policy and key attributes to indicate a valid key.
701      * Note that if the policy value was '0' we don't set the key!
702      */
703     if (mppe_enc_policy && mppe_enc_keys) {
704         mppe_keys_set = 1;
705         /* Set/modify allowed encryption types. */
706         if (mppe_enc_types)
707             set_mppe_enc_types(mppe_enc_policy, mppe_enc_types);
708     }
709 #endif
710
711     return 0;
712 }
713
714 #ifdef MPPE
715 /**********************************************************************
716 * %FUNCTION: radius_setmppekeys
717 * %ARGUMENTS:
718 *  vp -- value pair holding MS-CHAP-MPPE-KEYS attribute
719 *  req_info -- radius request information used for encryption
720 * %RETURNS:
721 *  >= 0 on success; -1 on failure
722 * %DESCRIPTION:
723 *  Decrypt the "key" provided by the RADIUS server for MPPE encryption.
724 *  See RFC 2548.
725 ***********************************************************************/
726 static int
727 radius_setmppekeys(VALUE_PAIR *vp, REQUEST_INFO *req_info,
728                    unsigned char *challenge)
729 {
730     int i;
731     MD5_CTX Context;
732     u_char  plain[32];
733     u_char  buf[16];
734
735     if (vp->lvalue != 32) {
736         error("RADIUS: Incorrect attribute length (%d) for MS-CHAP-MPPE-Keys",
737               vp->lvalue);
738         return -1;
739     }
740
741     memcpy(plain, vp->strvalue, sizeof(plain));
742
743     MD5_Init(&Context);
744     MD5_Update(&Context, req_info->secret, strlen(req_info->secret));
745     MD5_Update(&Context, req_info->request_vector, AUTH_VECTOR_LEN);
746     MD5_Final(buf, &Context);
747
748     for (i = 0; i < 16; i++)
749         plain[i] ^= buf[i];
750
751     MD5_Init(&Context);
752     MD5_Update(&Context, req_info->secret, strlen(req_info->secret));
753     MD5_Update(&Context, vp->strvalue, 16);
754     MD5_Final(buf, &Context);
755
756     for(i = 0; i < 16; i++)
757         plain[i + 16] ^= buf[i];
758
759     /*
760      * Annoying.  The "key" returned is just the NTPasswordHashHash, which
761      * the NAS (us) doesn't need; we only need the start key.  So we have
762      * to generate the start key, sigh.  NB: We do not support the LM-Key.
763      */
764     mppe_set_keys(challenge, &plain[8]);
765
766     return 0;    
767 }
768
769 /**********************************************************************
770 * %FUNCTION: radius_setmppekeys2
771 * %ARGUMENTS:
772 *  vp -- value pair holding MS-MPPE-SEND-KEY or MS-MPPE-RECV-KEY attribute
773 *  req_info -- radius request information used for encryption
774 * %RETURNS:
775 *  >= 0 on success; -1 on failure
776 * %DESCRIPTION:
777 *  Decrypt the key provided by the RADIUS server for MPPE encryption.
778 *  See RFC 2548.
779 ***********************************************************************/
780 static int
781 radius_setmppekeys2(VALUE_PAIR *vp, REQUEST_INFO *req_info)
782 {
783     int i;
784     MD5_CTX Context;
785     u_char  *salt = vp->strvalue;
786     u_char  *crypt = vp->strvalue + 2;
787     u_char  plain[32];
788     u_char  buf[MD5_HASH_SIZE];
789     char    *type = "Send";
790
791     if (vp->attribute == PW_MS_MPPE_RECV_KEY)
792         type = "Recv";
793
794     if (vp->lvalue != 34) {
795         error("RADIUS: Incorrect attribute length (%d) for MS-MPPE-%s-Key",
796               vp->lvalue, type);
797         return -1;
798     }
799
800     if ((salt[0] & 0x80) == 0) {
801         error("RADIUS: Illegal salt value for MS-MPPE-%s-Key attribute", type);
802         return -1;
803     }
804
805     memcpy(plain, crypt, 32);
806
807     MD5_Init(&Context);
808     MD5_Update(&Context, req_info->secret, strlen(req_info->secret));
809     MD5_Update(&Context, req_info->request_vector, AUTH_VECTOR_LEN);
810     MD5_Update(&Context, salt, 2);
811     MD5_Final(buf, &Context);
812
813     for (i = 0; i < 16; i++)
814         plain[i] ^= buf[i];
815
816     if (plain[0] != sizeof(mppe_send_key) /* 16 */) {
817         error("RADIUS: Incorrect key length (%d) for MS-MPPE-%s-Key attribute",
818               (int) plain[0], type);
819         return -1;
820     }
821
822     MD5_Init(&Context);
823     MD5_Update(&Context, req_info->secret, strlen(req_info->secret));
824     MD5_Update(&Context, crypt, 16);
825     MD5_Final(buf, &Context);
826
827     plain[16] ^= buf[0]; /* only need the first byte */
828
829     if (vp->attribute == PW_MS_MPPE_SEND_KEY)
830         memcpy(mppe_send_key, plain + 1, 16);
831     else
832         memcpy(mppe_recv_key, plain + 1, 16);
833
834     return 0;
835 }
836 #endif /* MPPE */
837
838 /**********************************************************************
839 * %FUNCTION: radius_acct_start
840 * %ARGUMENTS:
841 *  None
842 * %RETURNS:
843 *  Nothing
844 * %DESCRIPTION:
845 *  Sends a "start" accounting message to the RADIUS server.
846 ***********************************************************************/
847 static void
848 radius_acct_start(void)
849 {
850     UINT4 av_type;
851     int result;
852     VALUE_PAIR *send = NULL;
853     ipcp_options *ho = &ipcp_hisoptions[0];
854     u_int32_t hisaddr;
855
856     if (!rstate.initialized) {
857         return;
858     }
859
860     rstate.start_time = time(NULL);
861
862     strncpy(rstate.session_id, rc_mksid(), sizeof(rstate.session_id));
863
864     rc_avpair_add(&send, PW_ACCT_SESSION_ID,
865                    rstate.session_id, 0, VENDOR_NONE);
866     rc_avpair_add(&send, PW_USER_NAME,
867                    rstate.user, 0, VENDOR_NONE);
868
869     if (rstate.class_len > 0)
870         rc_avpair_add(&send, PW_CLASS,
871                       rstate.class, rstate.class_len, VENDOR_NONE);
872
873     av_type = PW_STATUS_START;
874     rc_avpair_add(&send, PW_ACCT_STATUS_TYPE, &av_type, 0, VENDOR_NONE);
875
876     av_type = PW_FRAMED;
877     rc_avpair_add(&send, PW_SERVICE_TYPE, &av_type, 0, VENDOR_NONE);
878
879     av_type = PW_PPP;
880     rc_avpair_add(&send, PW_FRAMED_PROTOCOL, &av_type, 0, VENDOR_NONE);
881
882     if (*remote_number) {
883         rc_avpair_add(&send, PW_CALLING_STATION_ID,
884                        remote_number, 0, VENDOR_NONE);
885     }
886
887     av_type = PW_RADIUS;
888     rc_avpair_add(&send, PW_ACCT_AUTHENTIC, &av_type, 0, VENDOR_NONE);
889
890
891     av_type = ( using_pty ? PW_VIRTUAL : ( sync_serial ? PW_SYNC : PW_ASYNC ) );
892     rc_avpair_add(&send, PW_NAS_PORT_TYPE, &av_type, 0, VENDOR_NONE);
893
894     hisaddr = ho->hisaddr;
895     av_type = htonl(hisaddr);
896     rc_avpair_add(&send, PW_FRAMED_IP_ADDRESS , &av_type , 0, VENDOR_NONE);
897
898     /* Add user specified vp's */
899     if (rstate.avp)
900         rc_avpair_insert(&send, NULL, rc_avpair_copy(rstate.avp));
901
902     if (rstate.acctserver) {
903         result = rc_acct_using_server(rstate.acctserver,
904                                       rstate.client_port, send);
905     } else {
906         result = rc_acct(rstate.client_port, send);
907     }
908
909     rc_avpair_free(send);
910
911     if (result != OK_RC) {
912         /* RADIUS server could be down so make this a warning */
913         syslog(LOG_WARNING,
914                 "Accounting START failed for %s", rstate.user);
915     } else {
916         rstate.accounting_started = 1;
917         /* Kick off periodic accounting reports */
918         if (rstate.acct_interim_interval) {
919             TIMEOUT(radius_acct_interim, NULL, rstate.acct_interim_interval);
920         }
921     }
922 }
923
924 /**********************************************************************
925 * %FUNCTION: radius_acct_stop
926 * %ARGUMENTS:
927 *  None
928 * %RETURNS:
929 *  Nothing
930 * %DESCRIPTION:
931 *  Sends a "stop" accounting message to the RADIUS server.
932 ***********************************************************************/
933 static void
934 radius_acct_stop(void)
935 {
936     UINT4 av_type;
937     VALUE_PAIR *send = NULL;
938     ipcp_options *ho = &ipcp_hisoptions[0];
939     u_int32_t hisaddr;
940     int result;
941
942     if (!rstate.initialized) {
943         return;
944     }
945
946     if (!rstate.accounting_started) {
947         return;
948     }
949
950     rstate.accounting_started = 0;
951     rc_avpair_add(&send, PW_ACCT_SESSION_ID, rstate.session_id,
952                    0, VENDOR_NONE);
953
954     rc_avpair_add(&send, PW_USER_NAME, rstate.user, 0, VENDOR_NONE);
955
956     av_type = PW_STATUS_STOP;
957     rc_avpair_add(&send, PW_ACCT_STATUS_TYPE, &av_type, 0, VENDOR_NONE);
958
959     av_type = PW_FRAMED;
960     rc_avpair_add(&send, PW_SERVICE_TYPE, &av_type, 0, VENDOR_NONE);
961
962     av_type = PW_PPP;
963     rc_avpair_add(&send, PW_FRAMED_PROTOCOL, &av_type, 0, VENDOR_NONE);
964
965     av_type = PW_RADIUS;
966     rc_avpair_add(&send, PW_ACCT_AUTHENTIC, &av_type, 0, VENDOR_NONE);
967
968
969     if (link_stats_valid) {
970         av_type = link_connect_time;
971         rc_avpair_add(&send, PW_ACCT_SESSION_TIME, &av_type, 0, VENDOR_NONE);
972
973         av_type = link_stats.bytes_out;
974         rc_avpair_add(&send, PW_ACCT_OUTPUT_OCTETS, &av_type, 0, VENDOR_NONE);
975
976         av_type = link_stats.bytes_in;
977         rc_avpair_add(&send, PW_ACCT_INPUT_OCTETS, &av_type, 0, VENDOR_NONE);
978
979         av_type = link_stats.pkts_out;
980         rc_avpair_add(&send, PW_ACCT_OUTPUT_PACKETS, &av_type, 0, VENDOR_NONE);
981
982         av_type = link_stats.pkts_in;
983         rc_avpair_add(&send, PW_ACCT_INPUT_PACKETS, &av_type, 0, VENDOR_NONE);
984     }
985
986     if (*remote_number) {
987         rc_avpair_add(&send, PW_CALLING_STATION_ID,
988                        remote_number, 0, VENDOR_NONE);
989     }
990
991     av_type = ( using_pty ? PW_VIRTUAL : ( sync_serial ? PW_SYNC : PW_ASYNC ) );
992     rc_avpair_add(&send, PW_NAS_PORT_TYPE, &av_type, 0, VENDOR_NONE);
993
994     av_type = PW_NAS_ERROR;
995     switch( status ) {
996         case EXIT_OK:
997         case EXIT_USER_REQUEST:
998             av_type = PW_USER_REQUEST;
999             break;
1000
1001         case EXIT_HANGUP:
1002         case EXIT_PEER_DEAD:
1003         case EXIT_CONNECT_FAILED:
1004             av_type = PW_LOST_CARRIER;
1005             break;
1006
1007         case EXIT_INIT_FAILED:
1008         case EXIT_OPEN_FAILED:
1009         case EXIT_LOCK_FAILED:
1010         case EXIT_PTYCMD_FAILED:
1011             av_type = PW_PORT_ERROR;
1012             break;
1013
1014         case EXIT_PEER_AUTH_FAILED:
1015         case EXIT_AUTH_TOPEER_FAILED:
1016         case EXIT_NEGOTIATION_FAILED:
1017         case EXIT_CNID_AUTH_FAILED:
1018             av_type = PW_SERVICE_UNAVAILABLE;
1019             break;
1020
1021         case EXIT_IDLE_TIMEOUT:
1022             av_type = PW_ACCT_IDLE_TIMEOUT;
1023             break;
1024
1025         case EXIT_CONNECT_TIME:
1026             av_type = PW_ACCT_SESSION_TIMEOUT;
1027             break;
1028             
1029 #ifdef MAXOCTETS
1030         case EXIT_TRAFFIC_LIMIT:
1031             av_type = PW_NAS_REQUEST;
1032             break;
1033 #endif
1034
1035         default:
1036             av_type = PW_NAS_ERROR;
1037             break;
1038     }
1039     rc_avpair_add(&send, PW_ACCT_TERMINATE_CAUSE, &av_type, 0, VENDOR_NONE);
1040
1041     hisaddr = ho->hisaddr;
1042     av_type = htonl(hisaddr);
1043     rc_avpair_add(&send, PW_FRAMED_IP_ADDRESS , &av_type , 0, VENDOR_NONE);
1044
1045     /* Add user specified vp's */
1046     if (rstate.avp)
1047         rc_avpair_insert(&send, NULL, rc_avpair_copy(rstate.avp));
1048
1049     if (rstate.acctserver) {
1050         result = rc_acct_using_server(rstate.acctserver,
1051                                       rstate.client_port, send);
1052     } else {
1053         result = rc_acct(rstate.client_port, send);
1054     }
1055
1056     if (result != OK_RC) {
1057         /* RADIUS server could be down so make this a warning */
1058         syslog(LOG_WARNING,
1059                 "Accounting STOP failed for %s", rstate.user);
1060     }
1061     rc_avpair_free(send);
1062 }
1063
1064 /**********************************************************************
1065 * %FUNCTION: radius_acct_interim
1066 * %ARGUMENTS:
1067 *  None
1068 * %RETURNS:
1069 *  Nothing
1070 * %DESCRIPTION:
1071 *  Sends an interim accounting message to the RADIUS server
1072 ***********************************************************************/
1073 static void
1074 radius_acct_interim(void *ignored)
1075 {
1076     UINT4 av_type;
1077     VALUE_PAIR *send = NULL;
1078     ipcp_options *ho = &ipcp_hisoptions[0];
1079     u_int32_t hisaddr;
1080     int result;
1081
1082     if (!rstate.initialized) {
1083         return;
1084     }
1085
1086     if (!rstate.accounting_started) {
1087         return;
1088     }
1089
1090     rc_avpair_add(&send, PW_ACCT_SESSION_ID, rstate.session_id,
1091                    0, VENDOR_NONE);
1092
1093     rc_avpair_add(&send, PW_USER_NAME, rstate.user, 0, VENDOR_NONE);
1094
1095     av_type = PW_STATUS_ALIVE;
1096     rc_avpair_add(&send, PW_ACCT_STATUS_TYPE, &av_type, 0, VENDOR_NONE);
1097
1098     av_type = PW_FRAMED;
1099     rc_avpair_add(&send, PW_SERVICE_TYPE, &av_type, 0, VENDOR_NONE);
1100
1101     av_type = PW_PPP;
1102     rc_avpair_add(&send, PW_FRAMED_PROTOCOL, &av_type, 0, VENDOR_NONE);
1103
1104     av_type = PW_RADIUS;
1105     rc_avpair_add(&send, PW_ACCT_AUTHENTIC, &av_type, 0, VENDOR_NONE);
1106
1107     /* Update link stats */
1108     update_link_stats(0);
1109
1110     if (link_stats_valid) {
1111         link_stats_valid = 0; /* Force later code to update */
1112
1113         av_type = link_connect_time;
1114         rc_avpair_add(&send, PW_ACCT_SESSION_TIME, &av_type, 0, VENDOR_NONE);
1115
1116         av_type = link_stats.bytes_out;
1117         rc_avpair_add(&send, PW_ACCT_OUTPUT_OCTETS, &av_type, 0, VENDOR_NONE);
1118
1119         av_type = link_stats.bytes_in;
1120         rc_avpair_add(&send, PW_ACCT_INPUT_OCTETS, &av_type, 0, VENDOR_NONE);
1121
1122         av_type = link_stats.pkts_out;
1123         rc_avpair_add(&send, PW_ACCT_OUTPUT_PACKETS, &av_type, 0, VENDOR_NONE);
1124
1125         av_type = link_stats.pkts_in;
1126         rc_avpair_add(&send, PW_ACCT_INPUT_PACKETS, &av_type, 0, VENDOR_NONE);
1127     }
1128
1129     if (*remote_number) {
1130         rc_avpair_add(&send, PW_CALLING_STATION_ID,
1131                        remote_number, 0, VENDOR_NONE);
1132     }
1133
1134     av_type = ( using_pty ? PW_VIRTUAL : ( sync_serial ? PW_SYNC : PW_ASYNC ) );
1135     rc_avpair_add(&send, PW_NAS_PORT_TYPE, &av_type, 0, VENDOR_NONE);
1136
1137     hisaddr = ho->hisaddr;
1138     av_type = htonl(hisaddr);
1139     rc_avpair_add(&send, PW_FRAMED_IP_ADDRESS , &av_type , 0, VENDOR_NONE);
1140
1141     /* Add user specified vp's */
1142     if (rstate.avp)
1143         rc_avpair_insert(&send, NULL, rc_avpair_copy(rstate.avp));
1144
1145     if (rstate.acctserver) {
1146         result = rc_acct_using_server(rstate.acctserver,
1147                                       rstate.client_port, send);
1148     } else {
1149         result = rc_acct(rstate.client_port, send);
1150     }
1151
1152     if (result != OK_RC) {
1153         /* RADIUS server could be down so make this a warning */
1154         syslog(LOG_WARNING,
1155                 "Interim accounting failed for %s", rstate.user);
1156     }
1157     rc_avpair_free(send);
1158
1159     /* Schedule another one */
1160     TIMEOUT(radius_acct_interim, NULL, rstate.acct_interim_interval);
1161 }
1162
1163 /**********************************************************************
1164 * %FUNCTION: radius_ip_up
1165 * %ARGUMENTS:
1166 *  opaque -- ignored
1167 *  arg -- ignored
1168 * %RETURNS:
1169 *  Nothing
1170 * %DESCRIPTION:
1171 *  Called when IPCP is up.  We'll do a start-accounting record.
1172 ***********************************************************************/
1173 static void
1174 radius_ip_up(void *opaque, int arg)
1175 {
1176     radius_acct_start();
1177 }
1178
1179 /**********************************************************************
1180 * %FUNCTION: radius_ip_down
1181 * %ARGUMENTS:
1182 *  opaque -- ignored
1183 *  arg -- ignored
1184 * %RETURNS:
1185 *  Nothing
1186 * %DESCRIPTION:
1187 *  Called when IPCP is down.  We'll do a stop-accounting record.
1188 ***********************************************************************/
1189 static void
1190 radius_ip_down(void *opaque, int arg)
1191 {
1192     radius_acct_stop();
1193 }
1194
1195 /**********************************************************************
1196 * %FUNCTION: radius_init
1197 * %ARGUMENTS:
1198 *  msg -- buffer of size BUF_LEN for error message
1199 * %RETURNS:
1200 *  negative on failure; non-negative on success
1201 * %DESCRIPTION:
1202 *  Initializes radiusclient library
1203 ***********************************************************************/
1204 static int
1205 radius_init(char *msg)
1206 {
1207     if (rstate.initialized) {
1208         return 0;
1209     }
1210
1211     if (config_file && *config_file) {
1212         strlcpy(rstate.config_file, config_file, MAXPATHLEN-1);
1213     }
1214
1215     rstate.initialized = 1;
1216
1217     if (rc_read_config(rstate.config_file) != 0) {
1218         slprintf(msg, BUF_LEN, "RADIUS: Can't read config file %s",
1219                  rstate.config_file);
1220         return -1;
1221     }
1222
1223     if (rc_read_dictionary(rc_conf_str("dictionary")) != 0) {
1224         slprintf(msg, BUF_LEN, "RADIUS: Can't read dictionary file %s",
1225                  rc_conf_str("dictionary"));
1226         return -1;
1227     }
1228
1229     if (rc_read_mapfile(rc_conf_str("mapfile")) != 0)   {
1230         slprintf(msg, BUF_LEN, "RADIUS: Can't read map file %s",
1231                  rc_conf_str("mapfile"));
1232         return -1;
1233     }
1234
1235     /* Add av pairs saved during option parsing */
1236     while (avpopt) {
1237         struct avpopt *n = avpopt->next;
1238
1239         rc_avpair_parse(avpopt->vpstr, &rstate.avp);
1240         free(avpopt->vpstr);
1241         free(avpopt);
1242         avpopt = n;
1243     }
1244     return 0;
1245 }
1246
1247 /**********************************************************************
1248 * %FUNCTION: get_client_port
1249 * %ARGUMENTS:
1250 *  ifname -- PPP interface name (e.g. "ppp7")
1251 * %RETURNS:
1252 *  The NAS port number (e.g. 7)
1253 * %DESCRIPTION:
1254 *  Extracts the port number from the interface name
1255 ***********************************************************************/
1256 static int
1257 get_client_port(char *ifname)
1258 {
1259     int port;
1260     if (sscanf(ifname, "ppp%d", &port) == 1) {
1261         return port;
1262     }
1263     return rc_map2id(ifname);
1264 }
1265
1266 /**********************************************************************
1267 * %FUNCTION: radius_allowed_address
1268 * %ARGUMENTS:
1269 *  addr -- IP address
1270 * %RETURNS:
1271 *  1 if we're allowed to use that IP address; 0 if not; -1 if we do
1272 *  not know.
1273 ***********************************************************************/
1274 static int
1275 radius_allowed_address(u_int32_t addr)
1276 {
1277     ipcp_options *wo = &ipcp_wantoptions[0];
1278
1279     if (!rstate.choose_ip) {
1280         /* If RADIUS server said any address is OK, then fine... */
1281         if (rstate.any_ip_addr_ok) {
1282             return 1;
1283         }
1284
1285         /* Sigh... if an address was supplied for remote host in pppd
1286            options, it has to match that.  */
1287         if (wo->hisaddr != 0 && wo->hisaddr == addr) {
1288             return 1;
1289         }
1290
1291         return 0;
1292     }
1293     if (addr == rstate.ip_addr) return 1;
1294     return 0;
1295 }
1296
1297 /* Useful for other plugins */
1298 char *radius_logged_in_user(void)
1299 {
1300     return rstate.user;
1301 }