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