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