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