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