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