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