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