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