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