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