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