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