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