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