]> git.ozlabs.org Git - ppp.git/blob - pppd/auth.c
Patch from Frank Cusack to make RADIUS plugin support MS-CHAP authentication.
[ppp.git] / pppd / auth.c
1 /*
2  * auth.c - PPP authentication and phase control.
3  *
4  * Copyright (c) 1993 The Australian National University.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms are permitted
8  * provided that the above copyright notice and this paragraph are
9  * duplicated in all such forms and that any documentation,
10  * advertising materials, and other materials related to such
11  * distribution and use acknowledge that the software was developed
12  * by the Australian National University.  The name of the University
13  * may not be used to endorse or promote products derived from this
14  * software without specific prior written permission.
15  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
17  * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
18  *
19  * Copyright (c) 1989 Carnegie Mellon University.
20  * All rights reserved.
21  *
22  * Redistribution and use in source and binary forms are permitted
23  * provided that the above copyright notice and this paragraph are
24  * duplicated in all such forms and that any documentation,
25  * advertising materials, and other materials related to such
26  * distribution and use acknowledge that the software was developed
27  * by Carnegie Mellon University.  The name of the
28  * University may not be used to endorse or promote products derived
29  * from this software without specific prior written permission.
30  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
31  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
32  * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
33  */
34
35 #define RCSID   "$Id: auth.c,v 1.74 2002/03/01 14:39:18 dfs Exp $"
36
37 #include <stdio.h>
38 #include <stddef.h>
39 #include <stdlib.h>
40 #include <unistd.h>
41 #include <pwd.h>
42 #include <grp.h>
43 #include <string.h>
44 #include <sys/types.h>
45 #include <sys/stat.h>
46 #include <sys/socket.h>
47 #include <utmp.h>
48 #include <fcntl.h>
49 #if defined(_PATH_LASTLOG) && defined(_linux_)
50 #include <lastlog.h>
51 #endif
52
53 #include <netdb.h>
54 #include <netinet/in.h>
55 #include <arpa/inet.h>
56
57 #ifdef USE_PAM
58 #include <security/pam_appl.h>
59 #endif
60
61 #ifdef HAS_SHADOW
62 #include <shadow.h>
63 #ifndef PW_PPP
64 #define PW_PPP PW_LOGIN
65 #endif
66 #endif
67 #include <time.h>
68
69 #include "pppd.h"
70 #include "fsm.h"
71 #include "lcp.h"
72 #include "ipcp.h"
73 #include "upap.h"
74 #include "chap.h"
75 #ifdef CBCP_SUPPORT
76 #include "cbcp.h"
77 #endif
78 #include "pathnames.h"
79
80 static const char rcsid[] = RCSID;
81
82 /* Bits in scan_authfile return value */
83 #define NONWILD_SERVER  1
84 #define NONWILD_CLIENT  2
85
86 #define ISWILD(word)    (word[0] == '*' && word[1] == 0)
87
88 /* The name by which the peer authenticated itself to us. */
89 char peer_authname[MAXNAMELEN];
90
91 /* Records which authentication operations haven't completed yet. */
92 static int auth_pending[NUM_PPP];
93
94 /* Set if we have successfully called plogin() */
95 static int logged_in;
96
97 /* List of addresses which the peer may use. */
98 static struct permitted_ip *addresses[NUM_PPP];
99
100 /* Wordlist giving addresses which the peer may use
101    without authenticating itself. */
102 static struct wordlist *noauth_addrs;
103
104 /* Extra options to apply, from the secrets file entry for the peer. */
105 static struct wordlist *extra_options;
106
107 /* Number of network protocols which we have opened. */
108 static int num_np_open;
109
110 /* Number of network protocols which have come up. */
111 static int num_np_up;
112
113 /* Set if we got the contents of passwd[] from the pap-secrets file. */
114 static int passwd_from_file;
115
116 /* Set if we require authentication only because we have a default route. */
117 static bool default_auth;
118
119 /* Hook to enable a plugin to control the idle time limit */
120 int (*idle_time_hook) __P((struct ppp_idle *)) = NULL;
121
122 /* Hook for a plugin to say whether we can possibly authenticate any peer */
123 int (*pap_check_hook) __P((void)) = NULL;
124
125 /* Hook for a plugin to check the PAP user and password */
126 int (*pap_auth_hook) __P((char *user, char *passwd, char **msgp,
127                           struct wordlist **paddrs,
128                           struct wordlist **popts)) = NULL;
129
130 /* Hook for a plugin to know about the PAP user logout */
131 void (*pap_logout_hook) __P((void)) = NULL;
132
133 /* Hook for a plugin to get the PAP password for authenticating us */
134 int (*pap_passwd_hook) __P((char *user, char *passwd)) = NULL;
135
136 /* Hook for a plugin to say whether it is OK if the peer
137    refuses to authenticate. */
138 int (*null_auth_hook) __P((struct wordlist **paddrs,
139                            struct wordlist **popts)) = NULL;
140
141 int (*allowed_address_hook) __P((u_int32_t addr)) = NULL;
142
143 /* A notifier for when the peer has authenticated itself,
144    and we are proceeding to the network phase. */
145 struct notifier *auth_up_notifier = NULL;
146
147 /* A notifier for when the link goes down. */
148 struct notifier *link_down_notifier = NULL;
149
150 /*
151  * This is used to ensure that we don't start an auth-up/down
152  * script while one is already running.
153  */
154 enum script_state {
155     s_down,
156     s_up
157 };
158
159 static enum script_state auth_state = s_down;
160 static enum script_state auth_script_state = s_down;
161 static pid_t auth_script_pid = 0;
162
163 static int used_login;          /* peer authenticated against login database */
164
165 /*
166  * Option variables.
167  */
168 bool uselogin = 0;              /* Use /etc/passwd for checking PAP */
169 bool cryptpap = 0;              /* Passwords in pap-secrets are encrypted */
170 bool refuse_pap = 0;            /* Don't wanna auth. ourselves with PAP */
171 bool refuse_chap = 0;           /* Don't wanna auth. ourselves with CHAP */
172 #ifdef CHAPMS
173 bool refuse_mschap = 0;         /* Don't wanna auth. ourselves with MS-CHAP */
174 #else
175 bool refuse_mschap = 1;         /* Don't wanna auth. ourselves with MS-CHAP */
176 #endif
177 bool usehostname = 0;           /* Use hostname for our_name */
178 bool auth_required = 0;         /* Always require authentication from peer */
179 bool allow_any_ip = 0;          /* Allow peer to use any IP address */
180 bool explicit_remote = 0;       /* User specified explicit remote name */
181 char remote_name[MAXNAMELEN];   /* Peer's name for authentication */
182
183 static char *uafname;           /* name of most recent +ua file */
184
185 /* Bits in auth_pending[] */
186 #define PAP_WITHPEER    1
187 #define PAP_PEER        2
188 #define CHAP_WITHPEER   4
189 #define CHAP_PEER       8
190
191 extern char *crypt __P((const char *, const char *));
192
193 /* Prototypes for procedures local to this file. */
194
195 static void network_phase __P((int));
196 static void check_idle __P((void *));
197 static void connect_time_expired __P((void *));
198 static int  plogin __P((char *, char *, char **));
199 static void plogout __P((void));
200 static int  null_login __P((int));
201 static int  get_pap_passwd __P((char *));
202 static int  have_pap_secret __P((int *));
203 static int  have_chap_secret __P((char *, char *, int, int *));
204 static int  ip_addr_check __P((u_int32_t, struct permitted_ip *));
205 static int  scan_authfile __P((FILE *, char *, char *, char *,
206                                struct wordlist **, struct wordlist **,
207                                char *));
208 static void free_wordlist __P((struct wordlist *));
209 static void auth_script __P((char *));
210 static void auth_script_done __P((void *));
211 static void set_allowed_addrs __P((int, struct wordlist *, struct wordlist *));
212 static int  some_ip_ok __P((struct wordlist *));
213 static int  setupapfile __P((char **));
214 static int  privgroup __P((char **));
215 static int  set_noauth_addr __P((char **));
216 static void check_access __P((FILE *, char *));
217 static int  wordlist_count __P((struct wordlist *));
218
219 /*
220  * Authentication-related options.
221  */
222 option_t auth_options[] = {
223     { "auth", o_bool, &auth_required,
224       "Require authentication from peer", OPT_PRIO | 1 },
225     { "noauth", o_bool, &auth_required,
226       "Don't require peer to authenticate", OPT_PRIOSUB | OPT_PRIV | OPT_A2COPY,
227       &allow_any_ip },
228     { "require-pap", o_bool, &lcp_wantoptions[0].neg_upap,
229       "Require PAP authentication from peer",
230       OPT_PRIOSUB | OPT_A2COPY | 1, &auth_required },
231     { "+pap", o_bool, &lcp_wantoptions[0].neg_upap,
232       "Require PAP authentication from peer",
233       OPT_ALIAS | OPT_PRIOSUB | OPT_A2COPY | 1, &auth_required },
234     { "require-chap", o_bool, &lcp_wantoptions[0].neg_chap,
235       "Require CHAP authentication from peer",
236       OPT_PRIOSUB | OPT_A2COPY | OPT_A3OR | MDTYPE_MD5,
237       &auth_required, 0, 0, NULL, 0, 0, &lcp_wantoptions[0].chap_mdtype },
238     { "+chap", o_bool, &lcp_wantoptions[0].neg_chap,
239       "Require CHAP authentication from peer",
240       OPT_ALIAS | OPT_PRIOSUB | OPT_A2COPY | OPT_A3OR | MDTYPE_MD5,
241       &auth_required, 0, 0, NULL, 0, 0, &lcp_wantoptions[0].chap_mdtype },
242 #ifdef CHAPMS
243     { "require-mschap", o_bool, &lcp_wantoptions[0].neg_chap,
244       "Require MS-CHAP authentication from peer",
245       OPT_PRIOSUB | OPT_A2COPY | OPT_A3OR | MDTYPE_MICROSOFT,
246       &auth_required, 0, 0, NULL, 0, 0, &lcp_wantoptions[0].chap_mdtype },
247     { "+mschap", o_bool, &lcp_wantoptions[0].neg_chap,
248       "Require MS-CHAP authentication from peer",
249       OPT_ALIAS | OPT_PRIOSUB | OPT_A2COPY | OPT_A3OR | MDTYPE_MICROSOFT,
250       &auth_required, 0, 0, NULL, 0, 0, &lcp_wantoptions[0].chap_mdtype },
251 #endif
252
253     { "refuse-pap", o_bool, &refuse_pap,
254       "Don't agree to auth to peer with PAP", 1 },
255     { "-pap", o_bool, &refuse_pap,
256       "Don't allow PAP authentication with peer", OPT_ALIAS | 1 },
257     { "refuse-chap", o_bool, &refuse_chap,
258       "Don't agree to auth to peer with CHAP", OPT_A2CLRB | MDTYPE_MD5,
259       &lcp_allowoptions[0].chap_mdtype },
260     { "-chap", o_bool, &refuse_chap,
261       "Don't allow CHAP authentication with peer",
262       OPT_ALIAS | OPT_A2CLRB | MDTYPE_MD5,
263       &lcp_allowoptions[0].chap_mdtype },
264 #ifdef CHAPMS
265     { "refuse-mschap", o_bool, &refuse_mschap,
266       "Don't agree to auth to peer with MS-CHAP", OPT_A2CLRB | MDTYPE_MICROSOFT,
267       &lcp_allowoptions[0].chap_mdtype },
268     { "-mschap", o_bool, &refuse_mschap,
269       "Don't allow MS-CHAP authentication with peer",
270       OPT_ALIAS | OPT_A2CLRB | MDTYPE_MICROSOFT,
271       &lcp_allowoptions[0].chap_mdtype },
272 #endif
273
274     { "name", o_string, our_name,
275       "Set local name for authentication",
276       OPT_PRIO | OPT_PRIV | OPT_STATIC, NULL, MAXNAMELEN },
277
278     { "+ua", o_special, (void *)setupapfile,
279       "Get PAP user and password from file",
280       OPT_PRIO | OPT_A2STRVAL, &uafname },
281
282     { "user", o_string, user,
283       "Set name for auth with peer", OPT_PRIO | OPT_STATIC, NULL, MAXNAMELEN },
284
285     { "password", o_string, passwd,
286       "Password for authenticating us to the peer",
287       OPT_PRIO | OPT_STATIC | OPT_HIDE, NULL, MAXSECRETLEN },
288
289     { "usehostname", o_bool, &usehostname,
290       "Must use hostname for authentication", 1 },
291
292     { "remotename", o_string, remote_name,
293       "Set remote name for authentication", OPT_PRIO | OPT_STATIC,
294       &explicit_remote, MAXNAMELEN },
295
296     { "login", o_bool, &uselogin,
297       "Use system password database for PAP", 1 },
298
299     { "papcrypt", o_bool, &cryptpap,
300       "PAP passwords are encrypted", 1 },
301
302     { "privgroup", o_special, (void *)privgroup,
303       "Allow group members to use privileged options", OPT_PRIV | OPT_A2LIST },
304
305     { "allow-ip", o_special, (void *)set_noauth_addr,
306       "Set IP address(es) which can be used without authentication",
307       OPT_PRIV | OPT_A2LIST },
308
309     { NULL }
310 };
311
312 /*
313  * setupapfile - specifies UPAP info for authenticating with peer.
314  */
315 static int
316 setupapfile(argv)
317     char **argv;
318 {
319     FILE *ufile;
320     int l;
321     char u[MAXNAMELEN], p[MAXSECRETLEN];
322     char *fname;
323
324     lcp_allowoptions[0].neg_upap = 1;
325
326     /* open user info file */
327     fname = strdup(*argv);
328     if (fname == NULL)
329         novm("+ua file name");
330     seteuid(getuid());
331     ufile = fopen(fname, "r");
332     seteuid(0);
333     if (ufile == NULL) {
334         option_error("unable to open user login data file %s", fname);
335         return 0;
336     }
337     check_access(ufile, fname);
338     uafname = fname;
339
340     /* get username */
341     if (fgets(u, MAXNAMELEN - 1, ufile) == NULL
342         || fgets(p, MAXSECRETLEN - 1, ufile) == NULL){
343         option_error("unable to read user login data file %s", fname);
344         return 0;
345     }
346     fclose(ufile);
347
348     /* get rid of newlines */
349     l = strlen(u);
350     if (l > 0 && u[l-1] == '\n')
351         u[l-1] = 0;
352     l = strlen(p);
353     if (l > 0 && p[l-1] == '\n')
354         p[l-1] = 0;
355
356     if (override_value("user", option_priority, fname))
357         strlcpy(user, u, sizeof(user));
358     if (override_value("passwd", option_priority, fname))
359         strlcpy(passwd, p, sizeof(passwd));
360
361     return (1);
362 }
363
364
365 /*
366  * privgroup - allow members of the group to have privileged access.
367  */
368 static int
369 privgroup(argv)
370     char **argv;
371 {
372     struct group *g;
373     int i;
374
375     g = getgrnam(*argv);
376     if (g == 0) {
377         option_error("group %s is unknown", *argv);
378         return 0;
379     }
380     for (i = 0; i < ngroups; ++i) {
381         if (groups[i] == g->gr_gid) {
382             privileged = 1;
383             break;
384         }
385     }
386     return 1;
387 }
388
389
390 /*
391  * set_noauth_addr - set address(es) that can be used without authentication.
392  * Equivalent to specifying an entry like `"" * "" addr' in pap-secrets.
393  */
394 static int
395 set_noauth_addr(argv)
396     char **argv;
397 {
398     char *addr = *argv;
399     int l = strlen(addr) + 1;
400     struct wordlist *wp;
401
402     wp = (struct wordlist *) malloc(sizeof(struct wordlist) + l);
403     if (wp == NULL)
404         novm("allow-ip argument");
405     wp->word = (char *) (wp + 1);
406     wp->next = noauth_addrs;
407     BCOPY(addr, wp->word, l);
408     noauth_addrs = wp;
409     return 1;
410 }
411
412
413 /*
414  * An Open on LCP has requested a change from Dead to Establish phase.
415  * Do what's necessary to bring the physical layer up.
416  */
417 void
418 link_required(unit)
419     int unit;
420 {
421 }
422
423 /*
424  * LCP has terminated the link; go to the Dead phase and take the
425  * physical layer down.
426  */
427 void
428 link_terminated(unit)
429     int unit;
430 {
431     if (phase == PHASE_DEAD)
432         return;
433     if (pap_logout_hook) {
434         pap_logout_hook();
435     } else {
436         if (logged_in)
437             plogout();
438     }
439     new_phase(PHASE_DEAD);
440     notice("Connection terminated.");
441 }
442
443 /*
444  * LCP has gone down; it will either die or try to re-establish.
445  */
446 void
447 link_down(unit)
448     int unit;
449 {
450     int i;
451     struct protent *protp;
452
453     notify(link_down_notifier, 0);
454     auth_state = s_down;
455     if (auth_script_state == s_up && auth_script_pid == 0) {
456         update_link_stats(unit);
457         auth_script_state = s_down;
458         auth_script(_PATH_AUTHDOWN);
459     }
460     for (i = 0; (protp = protocols[i]) != NULL; ++i) {
461         if (!protp->enabled_flag)
462             continue;
463         if (protp->protocol != PPP_LCP && protp->lowerdown != NULL)
464             (*protp->lowerdown)(unit);
465         if (protp->protocol < 0xC000 && protp->close != NULL)
466             (*protp->close)(unit, "LCP down");
467     }
468     num_np_open = 0;
469     num_np_up = 0;
470     if (phase != PHASE_DEAD)
471         new_phase(PHASE_ESTABLISH);
472 }
473
474 /*
475  * The link is established.
476  * Proceed to the Dead, Authenticate or Network phase as appropriate.
477  */
478 void
479 link_established(unit)
480     int unit;
481 {
482     int auth;
483     lcp_options *wo = &lcp_wantoptions[unit];
484     lcp_options *go = &lcp_gotoptions[unit];
485     lcp_options *ho = &lcp_hisoptions[unit];
486     int i;
487     struct protent *protp;
488
489     /*
490      * Tell higher-level protocols that LCP is up.
491      */
492     for (i = 0; (protp = protocols[i]) != NULL; ++i)
493         if (protp->protocol != PPP_LCP && protp->enabled_flag
494             && protp->lowerup != NULL)
495             (*protp->lowerup)(unit);
496
497     if (auth_required && !(go->neg_upap || go->neg_chap)) {
498         /*
499          * We wanted the peer to authenticate itself, and it refused:
500          * if we have some address(es) it can use without auth, fine,
501          * otherwise treat it as though it authenticated with PAP using
502          * a username of "" and a password of "".  If that's not OK,
503          * boot it out.
504          */
505         if (noauth_addrs != NULL) {
506             set_allowed_addrs(unit, NULL, NULL);
507         } else if (!wo->neg_upap || uselogin || !null_login(unit)) {
508             warn("peer refused to authenticate: terminating link");
509             lcp_close(unit, "peer refused to authenticate");
510             status = EXIT_PEER_AUTH_FAILED;
511             return;
512         }
513     }
514
515     new_phase(PHASE_AUTHENTICATE);
516     used_login = 0;
517     auth = 0;
518     if (go->neg_chap) {
519         ChapAuthPeer(unit, our_name, CHAP_DIGEST(go->chap_mdtype));
520         auth |= CHAP_PEER;
521     } else if (go->neg_upap) {
522         upap_authpeer(unit);
523         auth |= PAP_PEER;
524     }
525     if (ho->neg_chap) {
526         ChapAuthWithPeer(unit, user, CHAP_DIGEST(ho->chap_mdtype));
527         auth |= CHAP_WITHPEER;
528     } else if (ho->neg_upap) {
529         if (passwd[0] == 0) {
530             passwd_from_file = 1;
531             if (!get_pap_passwd(passwd))
532                 error("No secret found for PAP login");
533         }
534         upap_authwithpeer(unit, user, passwd);
535         auth |= PAP_WITHPEER;
536     }
537     auth_pending[unit] = auth;
538
539     if (!auth)
540         network_phase(unit);
541 }
542
543 /*
544  * Proceed to the network phase.
545  */
546 static void
547 network_phase(unit)
548     int unit;
549 {
550     lcp_options *go = &lcp_gotoptions[unit];
551
552     /*
553      * If the peer had to authenticate, run the auth-up script now.
554      */
555     if (go->neg_chap || go->neg_upap) {
556         notify(auth_up_notifier, 0);
557         auth_state = s_up;
558         if (auth_script_state == s_down && auth_script_pid == 0) {
559             auth_script_state = s_up;
560             auth_script(_PATH_AUTHUP);
561         }
562     }
563
564 #ifdef CBCP_SUPPORT
565     /*
566      * If we negotiated callback, do it now.
567      */
568     if (go->neg_cbcp) {
569         new_phase(PHASE_CALLBACK);
570         (*cbcp_protent.open)(unit);
571         return;
572     }
573 #endif
574
575     /*
576      * Process extra options from the secrets file
577      */
578     if (extra_options) {
579         options_from_list(extra_options, 1);
580         free_wordlist(extra_options);
581         extra_options = 0;
582     }
583     start_networks();
584 }
585
586 void
587 start_networks()
588 {
589     int i;
590     struct protent *protp;
591
592     new_phase(PHASE_NETWORK);
593
594 #ifdef HAVE_MULTILINK
595     if (multilink) {
596         if (mp_join_bundle()) {
597             if (updetach && !nodetach)
598                 detach();
599             return;
600         }
601     }
602 #endif /* HAVE_MULTILINK */
603
604 #ifdef PPP_FILTER
605     if (!demand)
606         set_filters(&pass_filter, &active_filter);
607 #endif
608     for (i = 0; (protp = protocols[i]) != NULL; ++i)
609         if (protp->protocol < 0xC000 && protp->enabled_flag
610             && protp->open != NULL) {
611             (*protp->open)(0);
612             if (protp->protocol != PPP_CCP)
613                 ++num_np_open;
614         }
615
616     if (num_np_open == 0)
617         /* nothing to do */
618         lcp_close(0, "No network protocols running");
619 }
620
621 /*
622  * The peer has failed to authenticate himself using `protocol'.
623  */
624 void
625 auth_peer_fail(unit, protocol)
626     int unit, protocol;
627 {
628     /*
629      * Authentication failure: take the link down
630      */
631     lcp_close(unit, "Authentication failed");
632     status = EXIT_PEER_AUTH_FAILED;
633 }
634
635 /*
636  * The peer has been successfully authenticated using `protocol'.
637  */
638 void
639 auth_peer_success(unit, protocol, name, namelen)
640     int unit, protocol;
641     char *name;
642     int namelen;
643 {
644     int bit;
645
646     switch (protocol) {
647     case PPP_CHAP:
648         bit = CHAP_PEER;
649         break;
650     case PPP_PAP:
651         bit = PAP_PEER;
652         break;
653     default:
654         warn("auth_peer_success: unknown protocol %x", protocol);
655         return;
656     }
657
658     /*
659      * Save the authenticated name of the peer for later.
660      */
661     if (namelen > sizeof(peer_authname) - 1)
662         namelen = sizeof(peer_authname) - 1;
663     BCOPY(name, peer_authname, namelen);
664     peer_authname[namelen] = 0;
665     script_setenv("PEERNAME", peer_authname, 0);
666
667     /*
668      * If there is no more authentication still to be done,
669      * proceed to the network (or callback) phase.
670      */
671     if ((auth_pending[unit] &= ~bit) == 0)
672         network_phase(unit);
673 }
674
675 /*
676  * We have failed to authenticate ourselves to the peer using `protocol'.
677  */
678 void
679 auth_withpeer_fail(unit, protocol)
680     int unit, protocol;
681 {
682     if (passwd_from_file)
683         BZERO(passwd, MAXSECRETLEN);
684     /*
685      * We've failed to authenticate ourselves to our peer.
686      * Some servers keep sending CHAP challenges, but there
687      * is no point in persisting without any way to get updated
688      * authentication secrets.
689      */
690     lcp_close(unit, "Failed to authenticate ourselves to peer");
691     status = EXIT_AUTH_TOPEER_FAILED;
692 }
693
694 /*
695  * We have successfully authenticated ourselves with the peer using `protocol'.
696  */
697 void
698 auth_withpeer_success(unit, protocol)
699     int unit, protocol;
700 {
701     int bit;
702
703     switch (protocol) {
704     case PPP_CHAP:
705         bit = CHAP_WITHPEER;
706         break;
707     case PPP_PAP:
708         if (passwd_from_file)
709             BZERO(passwd, MAXSECRETLEN);
710         bit = PAP_WITHPEER;
711         break;
712     default:
713         warn("auth_withpeer_success: unknown protocol %x", protocol);
714         bit = 0;
715     }
716
717     /*
718      * If there is no more authentication still being done,
719      * proceed to the network (or callback) phase.
720      */
721     if ((auth_pending[unit] &= ~bit) == 0)
722         network_phase(unit);
723 }
724
725
726 /*
727  * np_up - a network protocol has come up.
728  */
729 void
730 np_up(unit, proto)
731     int unit, proto;
732 {
733     int tlim;
734
735     if (num_np_up == 0) {
736         /*
737          * At this point we consider that the link has come up successfully.
738          */
739         status = EXIT_OK;
740         unsuccess = 0;
741         new_phase(PHASE_RUNNING);
742
743         if (idle_time_hook != 0)
744             tlim = (*idle_time_hook)(NULL);
745         else
746             tlim = idle_time_limit;
747         if (tlim > 0)
748             TIMEOUT(check_idle, NULL, tlim);
749
750         /*
751          * Set a timeout to close the connection once the maximum
752          * connect time has expired.
753          */
754         if (maxconnect > 0)
755             TIMEOUT(connect_time_expired, 0, maxconnect);
756
757         /*
758          * Detach now, if the updetach option was given.
759          */
760         if (updetach && !nodetach)
761             detach();
762     }
763     ++num_np_up;
764 }
765
766 /*
767  * np_down - a network protocol has gone down.
768  */
769 void
770 np_down(unit, proto)
771     int unit, proto;
772 {
773     if (--num_np_up == 0) {
774         UNTIMEOUT(check_idle, NULL);
775         UNTIMEOUT(connect_time_expired, NULL);
776         new_phase(PHASE_NETWORK);
777     }
778 }
779
780 /*
781  * np_finished - a network protocol has finished using the link.
782  */
783 void
784 np_finished(unit, proto)
785     int unit, proto;
786 {
787     if (--num_np_open <= 0) {
788         /* no further use for the link: shut up shop. */
789         lcp_close(0, "No network protocols running");
790     }
791 }
792
793 /*
794  * check_idle - check whether the link has been idle for long
795  * enough that we can shut it down.
796  */
797 static void
798 check_idle(arg)
799     void *arg;
800 {
801     struct ppp_idle idle;
802     time_t itime;
803     int tlim;
804
805     if (!get_idle_time(0, &idle))
806         return;
807     if (idle_time_hook != 0) {
808         tlim = idle_time_hook(&idle);
809     } else {
810         itime = MIN(idle.xmit_idle, idle.recv_idle);
811         tlim = idle_time_limit - itime;
812     }
813     if (tlim <= 0) {
814         /* link is idle: shut it down. */
815         notice("Terminating connection due to lack of activity.");
816         lcp_close(0, "Link inactive");
817         need_holdoff = 0;
818         status = EXIT_IDLE_TIMEOUT;
819     } else {
820         TIMEOUT(check_idle, NULL, tlim);
821     }
822 }
823
824 /*
825  * connect_time_expired - log a message and close the connection.
826  */
827 static void
828 connect_time_expired(arg)
829     void *arg;
830 {
831     info("Connect time expired");
832     lcp_close(0, "Connect time expired");       /* Close connection */
833     status = EXIT_CONNECT_TIME;
834 }
835
836 /*
837  * auth_check_options - called to check authentication options.
838  */
839 void
840 auth_check_options()
841 {
842     lcp_options *wo = &lcp_wantoptions[0];
843     int can_auth;
844     int lacks_ip;
845
846     /* Default our_name to hostname, and user to our_name */
847     if (our_name[0] == 0 || usehostname)
848         strlcpy(our_name, hostname, sizeof(our_name));
849     if (user[0] == 0)
850         strlcpy(user, our_name, sizeof(user));
851
852     /*
853      * If we have a default route, require the peer to authenticate
854      * unless the noauth option was given or the real user is root.
855      */
856     if (!auth_required && !allow_any_ip && have_route_to(0) && !privileged) {
857         auth_required = 1;
858         default_auth = 1;
859     }
860
861     /* If authentication is required, ask peer for CHAP or PAP. */
862     if (auth_required) {
863         allow_any_ip = 0;
864         if (!wo->neg_chap && !wo->neg_upap) {
865             wo->neg_chap = 1; wo->chap_mdtype = MDTYPE_ALL;
866             wo->neg_upap = 1;
867         }
868     } else {
869         wo->neg_chap = 0; wo->chap_mdtype = MDTYPE_NONE;
870         wo->neg_upap = 0;
871     }
872
873     /*
874      * Check whether we have appropriate secrets to use
875      * to authenticate the peer.
876      */
877     lacks_ip = 0;
878     can_auth = wo->neg_upap && (uselogin || have_pap_secret(&lacks_ip));
879     if (!can_auth && (wo->neg_chap)) {
880         can_auth = have_chap_secret((explicit_remote? remote_name: NULL),
881                                     our_name, 1, &lacks_ip);
882     }
883
884     if (auth_required && !can_auth && noauth_addrs == NULL) {
885         if (default_auth) {
886             option_error(
887 "By default the remote system is required to authenticate itself");
888             option_error(
889 "(because this system has a default route to the internet)");
890         } else if (explicit_remote)
891             option_error(
892 "The remote system (%s) is required to authenticate itself",
893                          remote_name);
894         else
895             option_error(
896 "The remote system is required to authenticate itself");
897         option_error(
898 "but I couldn't find any suitable secret (password) for it to use to do so.");
899         if (lacks_ip)
900             option_error(
901 "(None of the available passwords would let it use an IP address.)");
902
903         exit(1);
904     }
905 }
906
907 /*
908  * auth_reset - called when LCP is starting negotiations to recheck
909  * authentication options, i.e. whether we have appropriate secrets
910  * to use for authenticating ourselves and/or the peer.
911  */
912 void
913 auth_reset(unit)
914     int unit;
915 {
916     lcp_options *go = &lcp_gotoptions[unit];
917     lcp_options *ao = &lcp_allowoptions[0];
918
919     ao->neg_upap = !refuse_pap && (passwd[0] != 0 || get_pap_passwd(NULL));
920     ao->neg_chap = (!refuse_chap || !refuse_mschap)
921         && (passwd[0] != 0
922             || have_chap_secret(user, (explicit_remote? remote_name: NULL),
923                                 0, NULL));
924
925     if (go->neg_upap && !uselogin && !have_pap_secret(NULL))
926         go->neg_upap = 0;
927     if (go->neg_chap) {
928         if (!have_chap_secret((explicit_remote? remote_name: NULL),
929                               our_name, 1, NULL))
930             go->neg_chap = 0;
931     }
932 }
933
934
935 /*
936  * check_passwd - Check the user name and passwd against the PAP secrets
937  * file.  If requested, also check against the system password database,
938  * and login the user if OK.
939  *
940  * returns:
941  *      UPAP_AUTHNAK: Authentication failed.
942  *      UPAP_AUTHACK: Authentication succeeded.
943  * In either case, msg points to an appropriate message.
944  */
945 int
946 check_passwd(unit, auser, userlen, apasswd, passwdlen, msg)
947     int unit;
948     char *auser;
949     int userlen;
950     char *apasswd;
951     int passwdlen;
952     char **msg;
953 {
954     int ret;
955     char *filename;
956     FILE *f;
957     struct wordlist *addrs = NULL, *opts = NULL;
958     char passwd[256], user[256];
959     char secret[MAXWORDLEN];
960     static int attempts = 0;
961
962     /*
963      * Make copies of apasswd and auser, then null-terminate them.
964      * If there are unprintable characters in the password, make
965      * them visible.
966      */
967     slprintf(passwd, sizeof(passwd), "%.*v", passwdlen, apasswd);
968     slprintf(user, sizeof(user), "%.*v", userlen, auser);
969     *msg = "";
970
971     /*
972      * Check if a plugin wants to handle this.
973      */
974     if (pap_auth_hook) {
975         ret = (*pap_auth_hook)(user, passwd, msg, &addrs, &opts);
976         if (ret >= 0) {
977             if (ret)
978                 set_allowed_addrs(unit, addrs, opts);
979             BZERO(passwd, sizeof(passwd));
980             if (addrs != 0)
981                 free_wordlist(addrs);
982             if (opts != 0) {
983                 free_wordlist(opts);
984             }
985             return ret? UPAP_AUTHACK: UPAP_AUTHNAK;
986         }
987     }
988
989     /*
990      * Open the file of pap secrets and scan for a suitable secret
991      * for authenticating this user.
992      */
993     filename = _PATH_UPAPFILE;
994     addrs = opts = NULL;
995     ret = UPAP_AUTHNAK;
996     f = fopen(filename, "r");
997     if (f == NULL) {
998         error("Can't open PAP password file %s: %m", filename);
999
1000     } else {
1001         check_access(f, filename);
1002         if (scan_authfile(f, user, our_name, secret, &addrs, &opts, filename) < 0) {
1003             warn("no PAP secret found for %s", user);
1004         } else {
1005             /*
1006              * If the secret is "@login", it means to check
1007              * the password against the login database.
1008              */
1009             int login_secret = strcmp(secret, "@login") == 0;
1010             ret = UPAP_AUTHACK;
1011             if (uselogin || login_secret) {
1012                 /* login option or secret is @login */
1013                 ret = plogin(user, passwd, msg);
1014                 if (ret == UPAP_AUTHNAK)
1015                     warn("PAP login failure for %s", user);
1016                 else
1017                     used_login = 1;
1018             }
1019             if (secret[0] != 0 && !login_secret) {
1020                 /* password given in pap-secrets - must match */
1021                 if ((cryptpap || strcmp(passwd, secret) != 0)
1022                     && strcmp(crypt(passwd, secret), secret) != 0) {
1023                     ret = UPAP_AUTHNAK;
1024                     warn("PAP authentication failure for %s", user);
1025                 }
1026             }
1027         }
1028         fclose(f);
1029     }
1030
1031     if (ret == UPAP_AUTHNAK) {
1032         if (**msg == 0)
1033             *msg = "Login incorrect";
1034         /*
1035          * XXX can we ever get here more than once??
1036          * Frustrate passwd stealer programs.
1037          * Allow 10 tries, but start backing off after 3 (stolen from login).
1038          * On 10'th, drop the connection.
1039          */
1040         if (attempts++ >= 10) {
1041             warn("%d LOGIN FAILURES ON %s, %s", attempts, devnam, user);
1042             lcp_close(unit, "login failed");
1043         }
1044         if (attempts > 3)
1045             sleep((u_int) (attempts - 3) * 5);
1046         if (opts != NULL)
1047             free_wordlist(opts);
1048
1049     } else {
1050         attempts = 0;                   /* Reset count */
1051         if (**msg == 0)
1052             *msg = "Login ok";
1053         set_allowed_addrs(unit, addrs, opts);
1054     }
1055
1056     if (addrs != NULL)
1057         free_wordlist(addrs);
1058     BZERO(passwd, sizeof(passwd));
1059     BZERO(secret, sizeof(secret));
1060
1061     return ret;
1062 }
1063
1064 /*
1065  * This function is needed for PAM.
1066  */
1067
1068 #ifdef USE_PAM
1069 /* Static variables used to communicate between the conversation function
1070  * and the server_login function 
1071  */
1072 static char *PAM_username;
1073 static char *PAM_password;
1074 static int PAM_error = 0;
1075 static pam_handle_t *pamh = NULL;
1076
1077 /* PAM conversation function
1078  * Here we assume (for now, at least) that echo on means login name, and
1079  * echo off means password.
1080  */
1081
1082 static int PAM_conv (int num_msg, const struct pam_message **msg,
1083                     struct pam_response **resp, void *appdata_ptr)
1084 {
1085     int replies = 0;
1086     struct pam_response *reply = NULL;
1087
1088 #define COPY_STRING(s) (s) ? strdup(s) : NULL
1089
1090     reply = malloc(sizeof(struct pam_response) * num_msg);
1091     if (!reply) return PAM_CONV_ERR;
1092
1093     for (replies = 0; replies < num_msg; replies++) {
1094         switch (msg[replies]->msg_style) {
1095             case PAM_PROMPT_ECHO_ON:
1096                 reply[replies].resp_retcode = PAM_SUCCESS;
1097                 reply[replies].resp = COPY_STRING(PAM_username);
1098                 /* PAM frees resp */
1099                 break;
1100             case PAM_PROMPT_ECHO_OFF:
1101                 reply[replies].resp_retcode = PAM_SUCCESS;
1102                 reply[replies].resp = COPY_STRING(PAM_password);
1103                 /* PAM frees resp */
1104                 break;
1105             case PAM_TEXT_INFO:
1106                 /* fall through */
1107             case PAM_ERROR_MSG:
1108                 /* ignore it, but pam still wants a NULL response... */
1109                 reply[replies].resp_retcode = PAM_SUCCESS;
1110                 reply[replies].resp = NULL;
1111                 break;
1112             default:       
1113                 /* Must be an error of some sort... */
1114                 free (reply);
1115                 PAM_error = 1;
1116                 return PAM_CONV_ERR;
1117         }
1118     }
1119     *resp = reply;     
1120     return PAM_SUCCESS;
1121 }
1122
1123 static struct pam_conv PAM_conversation = {
1124     &PAM_conv,
1125     NULL
1126 };
1127 #endif  /* USE_PAM */
1128
1129 /*
1130  * plogin - Check the user name and password against the system
1131  * password database, and login the user if OK.
1132  *
1133  * returns:
1134  *      UPAP_AUTHNAK: Login failed.
1135  *      UPAP_AUTHACK: Login succeeded.
1136  * In either case, msg points to an appropriate message.
1137  */
1138
1139 static int
1140 plogin(user, passwd, msg)
1141     char *user;
1142     char *passwd;
1143     char **msg;
1144 {
1145     char *tty;
1146
1147 #ifdef USE_PAM
1148     int pam_error;
1149
1150     pam_error = pam_start ("ppp", user, &PAM_conversation, &pamh);
1151     if (pam_error != PAM_SUCCESS) {
1152         *msg = (char *) pam_strerror (pamh, pam_error);
1153         reopen_log();
1154         return UPAP_AUTHNAK;
1155     }
1156     /*
1157      * Define the fields for the credential validation
1158      */
1159      
1160     PAM_username = user;
1161     PAM_password = passwd;
1162     PAM_error = 0;
1163     pam_set_item (pamh, PAM_TTY, devnam); /* this might be useful to some modules */
1164
1165     /*
1166      * Validate the user
1167      */
1168     pam_error = pam_authenticate (pamh, PAM_SILENT);
1169     if (pam_error == PAM_SUCCESS && !PAM_error) {    
1170         pam_error = pam_acct_mgmt (pamh, PAM_SILENT);
1171         if (pam_error == PAM_SUCCESS)
1172             pam_error = pam_open_session (pamh, PAM_SILENT);
1173     }
1174
1175     *msg = (char *) pam_strerror (pamh, pam_error);
1176
1177     /*
1178      * Clean up the mess
1179      */
1180     reopen_log();       /* apparently the PAM stuff does closelog() */
1181     PAM_username = NULL;
1182     PAM_password = NULL;
1183     if (pam_error != PAM_SUCCESS)
1184         return UPAP_AUTHNAK;
1185 #else /* #ifdef USE_PAM */
1186
1187 /*
1188  * Use the non-PAM methods directly
1189  */
1190
1191 #ifdef HAS_SHADOW
1192     struct spwd *spwd;
1193     struct spwd *getspnam();
1194 #endif
1195     struct passwd *pw = getpwnam(user);
1196
1197     endpwent();
1198     if (pw == NULL)
1199         return (UPAP_AUTHNAK);
1200
1201 #ifdef HAS_SHADOW
1202     spwd = getspnam(user);
1203     endspent();
1204     if (spwd) {
1205         /* check the age of the password entry */
1206         long now = time(NULL) / 86400L;
1207
1208         if ((spwd->sp_expire > 0 && now >= spwd->sp_expire)
1209             || ((spwd->sp_max >= 0 && spwd->sp_max < 10000)
1210                 && spwd->sp_lstchg >= 0
1211                 && now >= spwd->sp_lstchg + spwd->sp_max)) {
1212             warn("Password for %s has expired", user);
1213             return (UPAP_AUTHNAK);
1214         }
1215         pw->pw_passwd = spwd->sp_pwdp;
1216     }
1217 #endif
1218
1219     /*
1220      * If no passwd, don't let them login.
1221      */
1222     if (pw->pw_passwd == NULL || strlen(pw->pw_passwd) < 2
1223         || strcmp(crypt(passwd, pw->pw_passwd), pw->pw_passwd) != 0)
1224         return (UPAP_AUTHNAK);
1225
1226 #endif /* #ifdef USE_PAM */
1227
1228     /*
1229      * Write a wtmp entry for this user.
1230      */
1231
1232     tty = devnam;
1233     if (strncmp(tty, "/dev/", 5) == 0)
1234         tty += 5;
1235     logwtmp(tty, user, remote_name);            /* Add wtmp login entry */
1236
1237 #if defined(_PATH_LASTLOG) && !defined(USE_PAM)
1238     if (pw != (struct passwd *)NULL) {
1239             struct lastlog ll;
1240             int fd;
1241
1242             if ((fd = open(_PATH_LASTLOG, O_RDWR, 0)) >= 0) {
1243                 (void)lseek(fd, (off_t)(pw->pw_uid * sizeof(ll)), SEEK_SET);
1244                 memset((void *)&ll, 0, sizeof(ll));
1245                 (void)time(&ll.ll_time);
1246                 (void)strncpy(ll.ll_line, tty, sizeof(ll.ll_line));
1247                 (void)write(fd, (char *)&ll, sizeof(ll));
1248                 (void)close(fd);
1249             }
1250     }
1251 #endif /* _PATH_LASTLOG and not USE_PAM */
1252
1253     info("user %s logged in", user);
1254     logged_in = 1;
1255
1256     return (UPAP_AUTHACK);
1257 }
1258
1259 /*
1260  * plogout - Logout the user.
1261  */
1262 static void
1263 plogout()
1264 {
1265 #ifdef USE_PAM
1266     int pam_error;
1267
1268     if (pamh != NULL) {
1269         pam_error = pam_close_session (pamh, PAM_SILENT);
1270         pam_end (pamh, pam_error);
1271         pamh = NULL;
1272     }
1273     /* Apparently the pam stuff does closelog(). */
1274     reopen_log();
1275 #else /* ! USE_PAM */   
1276     char *tty;
1277
1278     tty = devnam;
1279     if (strncmp(tty, "/dev/", 5) == 0)
1280         tty += 5;
1281     logwtmp(tty, "", "");               /* Wipe out utmp logout entry */
1282 #endif /* ! USE_PAM */
1283     logged_in = 0;
1284 }
1285
1286
1287 /*
1288  * null_login - Check if a username of "" and a password of "" are
1289  * acceptable, and iff so, set the list of acceptable IP addresses
1290  * and return 1.
1291  */
1292 static int
1293 null_login(unit)
1294     int unit;
1295 {
1296     char *filename;
1297     FILE *f;
1298     int i, ret;
1299     struct wordlist *addrs, *opts;
1300     char secret[MAXWORDLEN];
1301
1302     /*
1303      * Check if a plugin wants to handle this.
1304      */
1305     ret = -1;
1306     if (null_auth_hook)
1307         ret = (*null_auth_hook)(&addrs, &opts);
1308
1309     /*
1310      * Open the file of pap secrets and scan for a suitable secret.
1311      */
1312     if (ret <= 0) {
1313         filename = _PATH_UPAPFILE;
1314         addrs = NULL;
1315         f = fopen(filename, "r");
1316         if (f == NULL)
1317             return 0;
1318         check_access(f, filename);
1319
1320         i = scan_authfile(f, "", our_name, secret, &addrs, &opts, filename);
1321         ret = i >= 0 && secret[0] == 0;
1322         BZERO(secret, sizeof(secret));
1323         fclose(f);
1324     }
1325
1326     if (ret)
1327         set_allowed_addrs(unit, addrs, opts);
1328     else if (opts != 0)
1329         free_wordlist(opts);
1330     if (addrs != 0)
1331         free_wordlist(addrs);
1332
1333     return ret;
1334 }
1335
1336
1337 /*
1338  * get_pap_passwd - get a password for authenticating ourselves with
1339  * our peer using PAP.  Returns 1 on success, 0 if no suitable password
1340  * could be found.
1341  * Assumes passwd points to MAXSECRETLEN bytes of space (if non-null).
1342  */
1343 static int
1344 get_pap_passwd(passwd)
1345     char *passwd;
1346 {
1347     char *filename;
1348     FILE *f;
1349     int ret;
1350     char secret[MAXWORDLEN];
1351
1352     /*
1353      * Check whether a plugin wants to supply this.
1354      */
1355     if (pap_passwd_hook) {
1356         ret = (*pap_passwd_hook)(user, passwd);
1357         if (ret >= 0)
1358             return ret;
1359     }
1360
1361     filename = _PATH_UPAPFILE;
1362     f = fopen(filename, "r");
1363     if (f == NULL)
1364         return 0;
1365     check_access(f, filename);
1366     ret = scan_authfile(f, user,
1367                         (remote_name[0]? remote_name: NULL),
1368                         secret, NULL, NULL, filename);
1369     fclose(f);
1370     if (ret < 0)
1371         return 0;
1372     if (passwd != NULL)
1373         strlcpy(passwd, secret, MAXSECRETLEN);
1374     BZERO(secret, sizeof(secret));
1375     return 1;
1376 }
1377
1378
1379 /*
1380  * have_pap_secret - check whether we have a PAP file with any
1381  * secrets that we could possibly use for authenticating the peer.
1382  */
1383 static int
1384 have_pap_secret(lacks_ipp)
1385     int *lacks_ipp;
1386 {
1387     FILE *f;
1388     int ret;
1389     char *filename;
1390     struct wordlist *addrs;
1391
1392     /* let the plugin decide, if there is one */
1393     if (pap_check_hook) {
1394         ret = (*pap_check_hook)();
1395         if (ret >= 0)
1396             return ret;
1397     }
1398
1399     filename = _PATH_UPAPFILE;
1400     f = fopen(filename, "r");
1401     if (f == NULL)
1402         return 0;
1403
1404     ret = scan_authfile(f, (explicit_remote? remote_name: NULL), our_name,
1405                         NULL, &addrs, NULL, filename);
1406     fclose(f);
1407     if (ret >= 0 && !some_ip_ok(addrs)) {
1408         if (lacks_ipp != 0)
1409             *lacks_ipp = 1;
1410         ret = -1;
1411     }
1412     if (addrs != 0)
1413         free_wordlist(addrs);
1414
1415     return ret >= 0;
1416 }
1417
1418
1419 /*
1420  * have_chap_secret - check whether we have a CHAP file with a
1421  * secret that we could possibly use for authenticating `client'
1422  * on `server'.  Either can be the null string, meaning we don't
1423  * know the identity yet.
1424  */
1425 static int
1426 have_chap_secret(client, server, need_ip, lacks_ipp)
1427     char *client;
1428     char *server;
1429     int need_ip;
1430     int *lacks_ipp;
1431 {
1432     FILE *f;
1433     int ret;
1434     char *filename;
1435     struct wordlist *addrs;
1436
1437     if (chap_check_hook) {
1438         ret = (*chap_check_hook)();
1439         if (ret >= 0) {
1440             return ret;
1441         }
1442     }
1443
1444     filename = _PATH_CHAPFILE;
1445     f = fopen(filename, "r");
1446     if (f == NULL)
1447         return 0;
1448
1449     if (client != NULL && client[0] == 0)
1450         client = NULL;
1451     else if (server != NULL && server[0] == 0)
1452         server = NULL;
1453
1454     ret = scan_authfile(f, client, server, NULL, &addrs, NULL, filename);
1455     fclose(f);
1456     if (ret >= 0 && need_ip && !some_ip_ok(addrs)) {
1457         if (lacks_ipp != 0)
1458             *lacks_ipp = 1;
1459         ret = -1;
1460     }
1461     if (addrs != 0)
1462         free_wordlist(addrs);
1463
1464     return ret >= 0;
1465 }
1466
1467
1468 /*
1469  * get_secret - open the CHAP secret file and return the secret
1470  * for authenticating the given client on the given server.
1471  * (We could be either client or server).
1472  */
1473 int
1474 get_secret(unit, client, server, secret, secret_len, am_server)
1475     int unit;
1476     char *client;
1477     char *server;
1478     char *secret;
1479     int *secret_len;
1480     int am_server;
1481 {
1482     FILE *f;
1483     int ret, len;
1484     char *filename;
1485     struct wordlist *addrs, *opts;
1486     char secbuf[MAXWORDLEN];
1487
1488     if (!am_server && passwd[0] != 0) {
1489         strlcpy(secbuf, passwd, sizeof(secbuf));
1490     } else if (!am_server && chap_passwd_hook) {
1491         if ( (*chap_passwd_hook)(client, secbuf) < 0) {
1492             error("Unable to obtain CHAP password for %s on %s from plugin",
1493                   client, server);
1494             return 0;
1495         }
1496     } else {
1497         filename = _PATH_CHAPFILE;
1498         addrs = NULL;
1499         secbuf[0] = 0;
1500
1501         f = fopen(filename, "r");
1502         if (f == NULL) {
1503             error("Can't open chap secret file %s: %m", filename);
1504             return 0;
1505         }
1506         check_access(f, filename);
1507
1508         ret = scan_authfile(f, client, server, secbuf, &addrs, &opts, filename);
1509         fclose(f);
1510         if (ret < 0)
1511             return 0;
1512
1513         if (am_server)
1514             set_allowed_addrs(unit, addrs, opts);
1515         else if (opts != 0)
1516             free_wordlist(opts);
1517         if (addrs != 0)
1518             free_wordlist(addrs);
1519     }
1520
1521     len = strlen(secbuf);
1522     if (len > MAXSECRETLEN) {
1523         error("Secret for %s on %s is too long", client, server);
1524         len = MAXSECRETLEN;
1525     }
1526     BCOPY(secbuf, secret, len);
1527     BZERO(secbuf, sizeof(secbuf));
1528     *secret_len = len;
1529
1530     return 1;
1531 }
1532
1533 /*
1534  * set_allowed_addrs() - set the list of allowed addresses.
1535  * Also looks for `--' indicating options to apply for this peer
1536  * and leaves the following words in extra_options.
1537  */
1538 static void
1539 set_allowed_addrs(unit, addrs, opts)
1540     int unit;
1541     struct wordlist *addrs;
1542     struct wordlist *opts;
1543 {
1544     int n;
1545     struct wordlist *ap, **plink;
1546     struct permitted_ip *ip;
1547     char *ptr_word, *ptr_mask;
1548     struct hostent *hp;
1549     struct netent *np;
1550     u_int32_t a, mask, ah, offset;
1551     struct ipcp_options *wo = &ipcp_wantoptions[unit];
1552     u_int32_t suggested_ip = 0;
1553
1554     if (addresses[unit] != NULL)
1555         free(addresses[unit]);
1556     addresses[unit] = NULL;
1557     if (extra_options != NULL)
1558         free_wordlist(extra_options);
1559     extra_options = opts;
1560
1561     /*
1562      * Count the number of IP addresses given.
1563      */
1564     n = wordlist_count(addrs) + wordlist_count(noauth_addrs);
1565     if (n == 0)
1566         return;
1567     ip = (struct permitted_ip *) malloc((n + 1) * sizeof(struct permitted_ip));
1568     if (ip == 0)
1569         return;
1570
1571     /* temporarily append the noauth_addrs list to addrs */
1572     for (plink = &addrs; *plink != NULL; plink = &(*plink)->next)
1573         ;
1574     *plink = noauth_addrs;
1575
1576     n = 0;
1577     for (ap = addrs; ap != NULL; ap = ap->next) {
1578         /* "-" means no addresses authorized, "*" means any address allowed */
1579         ptr_word = ap->word;
1580         if (strcmp(ptr_word, "-") == 0)
1581             break;
1582         if (strcmp(ptr_word, "*") == 0) {
1583             ip[n].permit = 1;
1584             ip[n].base = ip[n].mask = 0;
1585             ++n;
1586             break;
1587         }
1588
1589         ip[n].permit = 1;
1590         if (*ptr_word == '!') {
1591             ip[n].permit = 0;
1592             ++ptr_word;
1593         }
1594
1595         mask = ~ (u_int32_t) 0;
1596         offset = 0;
1597         ptr_mask = strchr (ptr_word, '/');
1598         if (ptr_mask != NULL) {
1599             int bit_count;
1600             char *endp;
1601
1602             bit_count = (int) strtol (ptr_mask+1, &endp, 10);
1603             if (bit_count <= 0 || bit_count > 32) {
1604                 warn("invalid address length %v in auth. address list",
1605                      ptr_mask+1);
1606                 continue;
1607             }
1608             bit_count = 32 - bit_count; /* # bits in host part */
1609             if (*endp == '+') {
1610                 offset = ifunit + 1;
1611                 ++endp;
1612             }
1613             if (*endp != 0) {
1614                 warn("invalid address length syntax: %v", ptr_mask+1);
1615                 continue;
1616             }
1617             *ptr_mask = '\0';
1618             mask <<= bit_count;
1619         }
1620
1621         hp = gethostbyname(ptr_word);
1622         if (hp != NULL && hp->h_addrtype == AF_INET) {
1623             a = *(u_int32_t *)hp->h_addr;
1624         } else {
1625             np = getnetbyname (ptr_word);
1626             if (np != NULL && np->n_addrtype == AF_INET) {
1627                 a = htonl (*(u_int32_t *)np->n_net);
1628                 if (ptr_mask == NULL) {
1629                     /* calculate appropriate mask for net */
1630                     ah = ntohl(a);
1631                     if (IN_CLASSA(ah))
1632                         mask = IN_CLASSA_NET;
1633                     else if (IN_CLASSB(ah))
1634                         mask = IN_CLASSB_NET;
1635                     else if (IN_CLASSC(ah))
1636                         mask = IN_CLASSC_NET;
1637                 }
1638             } else {
1639                 a = inet_addr (ptr_word);
1640             }
1641         }
1642
1643         if (ptr_mask != NULL)
1644             *ptr_mask = '/';
1645
1646         if (a == (u_int32_t)-1L) {
1647             warn("unknown host %s in auth. address list", ap->word);
1648             continue;
1649         }
1650         if (offset != 0) {
1651             if (offset >= ~mask) {
1652                 warn("interface unit %d too large for subnet %v",
1653                      ifunit, ptr_word);
1654                 continue;
1655             }
1656             a = htonl((ntohl(a) & mask) + offset);
1657             mask = ~(u_int32_t)0;
1658         }
1659         ip[n].mask = htonl(mask);
1660         ip[n].base = a & ip[n].mask;
1661         ++n;
1662         if (~mask == 0 && suggested_ip == 0)
1663             suggested_ip = a;
1664     }
1665     *plink = NULL;
1666
1667     ip[n].permit = 0;           /* make the last entry forbid all addresses */
1668     ip[n].base = 0;             /* to terminate the list */
1669     ip[n].mask = 0;
1670
1671     addresses[unit] = ip;
1672
1673     /*
1674      * If the address given for the peer isn't authorized, or if
1675      * the user hasn't given one, AND there is an authorized address
1676      * which is a single host, then use that if we find one.
1677      */
1678     if (suggested_ip != 0
1679         && (wo->hisaddr == 0 || !auth_ip_addr(unit, wo->hisaddr))) {
1680         wo->hisaddr = suggested_ip;
1681         /*
1682          * Do we insist on this address?  No, if there are other
1683          * addresses authorized than the suggested one.
1684          */
1685         if (n > 1)
1686             wo->accept_remote = 1;
1687     }
1688 }
1689
1690 /*
1691  * auth_ip_addr - check whether the peer is authorized to use
1692  * a given IP address.  Returns 1 if authorized, 0 otherwise.
1693  */
1694 int
1695 auth_ip_addr(unit, addr)
1696     int unit;
1697     u_int32_t addr;
1698 {
1699     int ok;
1700
1701     /* don't allow loopback or multicast address */
1702     if (bad_ip_adrs(addr))
1703         return 0;
1704
1705     if (allowed_address_hook) {
1706         ok = allowed_address_hook(addr);
1707         if (ok >= 0) return ok;
1708     }
1709
1710     if (addresses[unit] != NULL) {
1711         ok = ip_addr_check(addr, addresses[unit]);
1712         if (ok >= 0)
1713             return ok;
1714     }
1715
1716     if (auth_required)
1717         return 0;               /* no addresses authorized */
1718     return allow_any_ip || privileged || !have_route_to(addr);
1719 }
1720
1721 static int
1722 ip_addr_check(addr, addrs)
1723     u_int32_t addr;
1724     struct permitted_ip *addrs;
1725 {
1726     for (; ; ++addrs)
1727         if ((addr & addrs->mask) == addrs->base)
1728             return addrs->permit;
1729 }
1730
1731 /*
1732  * bad_ip_adrs - return 1 if the IP address is one we don't want
1733  * to use, such as an address in the loopback net or a multicast address.
1734  * addr is in network byte order.
1735  */
1736 int
1737 bad_ip_adrs(addr)
1738     u_int32_t addr;
1739 {
1740     addr = ntohl(addr);
1741     return (addr >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET
1742         || IN_MULTICAST(addr) || IN_BADCLASS(addr);
1743 }
1744
1745 /*
1746  * some_ip_ok - check a wordlist to see if it authorizes any
1747  * IP address(es).
1748  */
1749 static int
1750 some_ip_ok(addrs)
1751     struct wordlist *addrs;
1752 {
1753     for (; addrs != 0; addrs = addrs->next) {
1754         if (addrs->word[0] == '-')
1755             break;
1756         if (addrs->word[0] != '!')
1757             return 1;           /* some IP address is allowed */
1758     }
1759     return 0;
1760 }
1761
1762 /*
1763  * check_access - complain if a secret file has too-liberal permissions.
1764  */
1765 static void
1766 check_access(f, filename)
1767     FILE *f;
1768     char *filename;
1769 {
1770     struct stat sbuf;
1771
1772     if (fstat(fileno(f), &sbuf) < 0) {
1773         warn("cannot stat secret file %s: %m", filename);
1774     } else if ((sbuf.st_mode & (S_IRWXG | S_IRWXO)) != 0) {
1775         warn("Warning - secret file %s has world and/or group access",
1776              filename);
1777     }
1778 }
1779
1780
1781 /*
1782  * scan_authfile - Scan an authorization file for a secret suitable
1783  * for authenticating `client' on `server'.  The return value is -1
1784  * if no secret is found, otherwise >= 0.  The return value has
1785  * NONWILD_CLIENT set if the secret didn't have "*" for the client, and
1786  * NONWILD_SERVER set if the secret didn't have "*" for the server.
1787  * Any following words on the line up to a "--" (i.e. address authorization
1788  * info) are placed in a wordlist and returned in *addrs.  Any
1789  * following words (extra options) are placed in a wordlist and
1790  * returned in *opts.
1791  * We assume secret is NULL or points to MAXWORDLEN bytes of space.
1792  */
1793 static int
1794 scan_authfile(f, client, server, secret, addrs, opts, filename)
1795     FILE *f;
1796     char *client;
1797     char *server;
1798     char *secret;
1799     struct wordlist **addrs;
1800     struct wordlist **opts;
1801     char *filename;
1802 {
1803     int newline, xxx;
1804     int got_flag, best_flag;
1805     FILE *sf;
1806     struct wordlist *ap, *addr_list, *alist, **app;
1807     char word[MAXWORDLEN];
1808     char atfile[MAXWORDLEN];
1809     char lsecret[MAXWORDLEN];
1810
1811     if (addrs != NULL)
1812         *addrs = NULL;
1813     if (opts != NULL)
1814         *opts = NULL;
1815     addr_list = NULL;
1816     if (!getword(f, word, &newline, filename))
1817         return -1;              /* file is empty??? */
1818     newline = 1;
1819     best_flag = -1;
1820     for (;;) {
1821         /*
1822          * Skip until we find a word at the start of a line.
1823          */
1824         while (!newline && getword(f, word, &newline, filename))
1825             ;
1826         if (!newline)
1827             break;              /* got to end of file */
1828
1829         /*
1830          * Got a client - check if it's a match or a wildcard.
1831          */
1832         got_flag = 0;
1833         if (client != NULL && strcmp(word, client) != 0 && !ISWILD(word)) {
1834             newline = 0;
1835             continue;
1836         }
1837         if (!ISWILD(word))
1838             got_flag = NONWILD_CLIENT;
1839
1840         /*
1841          * Now get a server and check if it matches.
1842          */
1843         if (!getword(f, word, &newline, filename))
1844             break;
1845         if (newline)
1846             continue;
1847         if (!ISWILD(word)) {
1848             if (server != NULL && strcmp(word, server) != 0)
1849                 continue;
1850             got_flag |= NONWILD_SERVER;
1851         }
1852
1853         /*
1854          * Got some sort of a match - see if it's better than what
1855          * we have already.
1856          */
1857         if (got_flag <= best_flag)
1858             continue;
1859
1860         /*
1861          * Get the secret.
1862          */
1863         if (!getword(f, word, &newline, filename))
1864             break;
1865         if (newline)
1866             continue;
1867
1868         if (secret != NULL) {
1869             /*
1870              * Special syntax: @/pathname means read secret from file.
1871              */
1872             if (word[0] == '@' && word[1] == '/') {
1873                 strlcpy(atfile, word+1, sizeof(atfile));
1874                 if ((sf = fopen(atfile, "r")) == NULL) {
1875                     warn("can't open indirect secret file %s", atfile);
1876                     continue;
1877                 }
1878                 check_access(sf, atfile);
1879                 if (!getword(sf, word, &xxx, atfile)) {
1880                     warn("no secret in indirect secret file %s", atfile);
1881                     fclose(sf);
1882                     continue;
1883                 }
1884                 fclose(sf);
1885             }
1886             strlcpy(lsecret, word, sizeof(lsecret));
1887         }
1888
1889         /*
1890          * Now read address authorization info and make a wordlist.
1891          */
1892         app = &alist;
1893         for (;;) {
1894             if (!getword(f, word, &newline, filename) || newline)
1895                 break;
1896             ap = (struct wordlist *)
1897                     malloc(sizeof(struct wordlist) + strlen(word) + 1);
1898             if (ap == NULL)
1899                 novm("authorized addresses");
1900             ap->word = (char *) (ap + 1);
1901             strcpy(ap->word, word);
1902             *app = ap;
1903             app = &ap->next;
1904         }
1905         *app = NULL;
1906
1907         /*
1908          * This is the best so far; remember it.
1909          */
1910         best_flag = got_flag;
1911         if (addr_list)
1912             free_wordlist(addr_list);
1913         addr_list = alist;
1914         if (secret != NULL)
1915             strlcpy(secret, lsecret, MAXWORDLEN);
1916
1917         if (!newline)
1918             break;
1919     }
1920
1921     /* scan for a -- word indicating the start of options */
1922     for (app = &addr_list; (ap = *app) != NULL; app = &ap->next)
1923         if (strcmp(ap->word, "--") == 0)
1924             break;
1925     /* ap = start of options */
1926     if (ap != NULL) {
1927         ap = ap->next;          /* first option */
1928         free(*app);                     /* free the "--" word */
1929         *app = NULL;            /* terminate addr list */
1930     }
1931     if (opts != NULL)
1932         *opts = ap;
1933     else if (ap != NULL)
1934         free_wordlist(ap);
1935     if (addrs != NULL)
1936         *addrs = addr_list;
1937     else if (addr_list != NULL)
1938         free_wordlist(addr_list);
1939
1940     return best_flag;
1941 }
1942
1943 /*
1944  * wordlist_count - return the number of items in a wordlist
1945  */
1946 static int
1947 wordlist_count(wp)
1948     struct wordlist *wp;
1949 {
1950     int n;
1951
1952     for (n = 0; wp != NULL; wp = wp->next)
1953         ++n;
1954     return n;
1955 }
1956
1957 /*
1958  * free_wordlist - release memory allocated for a wordlist.
1959  */
1960 static void
1961 free_wordlist(wp)
1962     struct wordlist *wp;
1963 {
1964     struct wordlist *next;
1965
1966     while (wp != NULL) {
1967         next = wp->next;
1968         free(wp);
1969         wp = next;
1970     }
1971 }
1972
1973 /*
1974  * auth_script_done - called when the auth-up or auth-down script
1975  * has finished.
1976  */
1977 static void
1978 auth_script_done(arg)
1979     void *arg;
1980 {
1981     auth_script_pid = 0;
1982     switch (auth_script_state) {
1983     case s_up:
1984         if (auth_state == s_down) {
1985             auth_script_state = s_down;
1986             auth_script(_PATH_AUTHDOWN);
1987         }
1988         break;
1989     case s_down:
1990         if (auth_state == s_up) {
1991             auth_script_state = s_up;
1992             auth_script(_PATH_AUTHUP);
1993         }
1994         break;
1995     }
1996 }
1997
1998 /*
1999  * auth_script - execute a script with arguments
2000  * interface-name peer-name real-user tty speed
2001  */
2002 static void
2003 auth_script(script)
2004     char *script;
2005 {
2006     char strspeed[32];
2007     struct passwd *pw;
2008     char struid[32];
2009     char *user_name;
2010     char *argv[8];
2011
2012     if ((pw = getpwuid(getuid())) != NULL && pw->pw_name != NULL)
2013         user_name = pw->pw_name;
2014     else {
2015         slprintf(struid, sizeof(struid), "%d", getuid());
2016         user_name = struid;
2017     }
2018     slprintf(strspeed, sizeof(strspeed), "%d", baud_rate);
2019
2020     argv[0] = script;
2021     argv[1] = ifname;
2022     argv[2] = peer_authname;
2023     argv[3] = user_name;
2024     argv[4] = devnam;
2025     argv[5] = strspeed;
2026     argv[6] = NULL;
2027
2028     auth_script_pid = run_program(script, argv, 0, auth_script_done, NULL);
2029 }