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