]> git.ozlabs.org Git - ppp.git/blob - pppd/auth.c
pppd man page: Update header to refer to pppd 2.5.x
[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@ozlabs.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 = 0;
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 #if defined(SYSTEM_CA_PATH) && (defined(PPP_WITH_EAPTLS) || defined(PPP_WITH_PEAP))
1338     /* Use system default for CA Path if not specified */
1339     if (!ca_path) {
1340         ca_path = SYSTEM_CA_PATH;
1341     }
1342 #endif
1343
1344     /*
1345      * If we have a default route, require the peer to authenticate
1346      * unless the noauth option was given or the real user is root.
1347      */
1348     if (!auth_required && !allow_any_ip && have_route_to(0) && !privileged) {
1349         auth_required = 1;
1350         default_auth = 1;
1351     }
1352
1353     /* If we selected any CHAP flavors, we should probably negotiate it. :-) */
1354     if (wo->chap_mdtype)
1355         wo->neg_chap = 1;
1356
1357     /* If authentication is required, ask peer for CHAP, PAP, or EAP. */
1358     if (auth_required) {
1359         allow_any_ip = 0;
1360         if (!wo->neg_chap && !wo->neg_upap && !wo->neg_eap) {
1361             wo->neg_chap = chap_mdtype_all != MDTYPE_NONE;
1362             wo->chap_mdtype = chap_mdtype_all;
1363             wo->neg_upap = 1;
1364             wo->neg_eap = 1;
1365         }
1366     } else {
1367         wo->neg_chap = 0;
1368         wo->chap_mdtype = MDTYPE_NONE;
1369         wo->neg_upap = 0;
1370         wo->neg_eap = 0;
1371     }
1372
1373     /*
1374      * Check whether we have appropriate secrets to use
1375      * to authenticate the peer.  Note that EAP can authenticate by way
1376      * of a CHAP-like exchanges as well as SRP.
1377      */
1378     lacks_ip = 0;
1379     can_auth = wo->neg_upap && (uselogin || have_pap_secret(&lacks_ip));
1380     if (!can_auth && (wo->neg_chap || wo->neg_eap)) {
1381         can_auth = have_chap_secret((explicit_remote? remote_name: NULL),
1382                                     our_name, 1, &lacks_ip);
1383     }
1384     if (!can_auth && wo->neg_eap) {
1385         can_auth = have_srp_secret((explicit_remote? remote_name: NULL),
1386                                     our_name, 1, &lacks_ip);
1387     }
1388
1389 #ifdef PPP_WITH_EAPTLS
1390     if (!can_auth && wo->neg_eap) {
1391         can_auth =
1392             have_eaptls_secret_server((explicit_remote ? remote_name :
1393                                        NULL), our_name, 1, &lacks_ip);
1394
1395     }
1396 #endif
1397
1398     if (auth_required && !can_auth && noauth_addrs == NULL) {
1399         if (default_auth) {
1400             ppp_option_error(
1401 "By default the remote system is required to authenticate itself");
1402             ppp_option_error(
1403 "(because this system has a default route to the internet)");
1404         } else if (explicit_remote)
1405             ppp_option_error(
1406 "The remote system (%s) is required to authenticate itself",
1407                          remote_name);
1408         else
1409             ppp_option_error(
1410 "The remote system is required to authenticate itself");
1411         ppp_option_error(
1412 "but I couldn't find any suitable secret (password) for it to use to do so.");
1413         if (lacks_ip)
1414             ppp_option_error(
1415 "(None of the available passwords would let it use an IP address.)");
1416
1417         exit(1);
1418     }
1419
1420     /*
1421      * Early check for remote number authorization.
1422      */
1423     if (!auth_number()) {
1424         warn("calling number %q is not authorized", remote_number);
1425         exit(EXIT_CNID_AUTH_FAILED);
1426     }
1427 }
1428
1429 /*
1430  * auth_reset - called when LCP is starting negotiations to recheck
1431  * authentication options, i.e. whether we have appropriate secrets
1432  * to use for authenticating ourselves and/or the peer.
1433  */
1434 void
1435 auth_reset(int unit)
1436 {
1437     lcp_options *go = &lcp_gotoptions[unit];
1438     lcp_options *ao = &lcp_allowoptions[unit];
1439     int hadchap;
1440
1441     hadchap = -1;
1442     ao->neg_upap = !refuse_pap && (passwd[0] != 0 || get_pap_passwd(NULL));
1443     ao->neg_chap = (!refuse_chap || !refuse_mschap || !refuse_mschap_v2)
1444         && ((passwd[0] != 0 || explicit_passwd) ||
1445             (hadchap = have_chap_secret(user, (explicit_remote? remote_name:
1446                                                NULL), 0, NULL)));
1447     ao->neg_eap = !refuse_eap && (
1448         passwd[0] != 0 ||
1449         (hadchap == 1 || (hadchap == -1 && have_chap_secret(user,
1450             (explicit_remote? remote_name: NULL), 0, NULL))) ||
1451         have_srp_secret(user, (explicit_remote? remote_name: NULL), 0, NULL)
1452 #ifdef PPP_WITH_EAPTLS
1453                 || have_eaptls_secret_client(user, (explicit_remote? remote_name: NULL))
1454 #endif
1455         );
1456
1457     hadchap = -1;
1458     if (go->neg_upap && !uselogin && !have_pap_secret(NULL))
1459         go->neg_upap = 0;
1460     if (go->neg_chap) {
1461         if (!(hadchap = have_chap_secret((explicit_remote? remote_name: NULL),
1462                               our_name, 1, NULL)))
1463             go->neg_chap = 0;
1464     }
1465     if (go->neg_eap &&
1466         (hadchap == 0 || (hadchap == -1 &&
1467             !have_chap_secret((explicit_remote? remote_name: NULL), our_name,
1468                 1, NULL))) &&
1469         !have_srp_secret((explicit_remote? remote_name: NULL), our_name, 1,
1470             NULL)
1471 #ifdef PPP_WITH_EAPTLS
1472          && !have_eaptls_secret_server((explicit_remote? remote_name: NULL),
1473                                    our_name, 1, NULL)
1474 #endif
1475                 )
1476         go->neg_eap = 0;
1477 }
1478
1479
1480 /*
1481  * check_passwd - Check the user name and passwd against the PAP secrets
1482  * file.  If requested, also check against the system password database,
1483  * and login the user if OK.
1484  *
1485  * returns:
1486  *      UPAP_AUTHNAK: Authentication failed.
1487  *      UPAP_AUTHACK: Authentication succeeded.
1488  * In either case, msg points to an appropriate message.
1489  */
1490 int
1491 check_passwd(int unit,
1492              char *auser, int userlen,
1493              char *apasswd, int passwdlen, char **msg)
1494 {
1495     int ret;
1496     char *filename;
1497     FILE *f;
1498     struct wordlist *addrs = NULL, *opts = NULL;
1499     char passwd[256], user[256];
1500     char secret[MAXWORDLEN];
1501     static int attempts = 0;
1502
1503     /*
1504      * Make copies of apasswd and auser, then null-terminate them.
1505      * If there are unprintable characters in the password, make
1506      * them visible.
1507      */
1508     slprintf(passwd, sizeof(passwd), "%.*v", passwdlen, apasswd);
1509     slprintf(user, sizeof(user), "%.*v", userlen, auser);
1510     *msg = "";
1511
1512     /*
1513      * Check if a plugin wants to handle this.
1514      */
1515     if (pap_auth_hook) {
1516         ret = (*pap_auth_hook)(user, passwd, msg, &addrs, &opts);
1517         if (ret >= 0) {
1518             /* note: set_allowed_addrs() saves opts (but not addrs):
1519                don't free it! */
1520             if (ret)
1521                 set_allowed_addrs(unit, addrs, opts);
1522             else if (opts != 0)
1523                 free_wordlist(opts);
1524             if (addrs != 0)
1525                 free_wordlist(addrs);
1526             BZERO(passwd, sizeof(passwd));
1527             return ret? UPAP_AUTHACK: UPAP_AUTHNAK;
1528         }
1529     }
1530
1531     /*
1532      * Open the file of pap secrets and scan for a suitable secret
1533      * for authenticating this user.
1534      */
1535     filename = PPP_PATH_UPAPFILE;
1536     addrs = opts = NULL;
1537     ret = UPAP_AUTHNAK;
1538     f = fopen(filename, "r");
1539     if (f == NULL) {
1540         error("Can't open PAP password file %s: %m", filename);
1541
1542     } else {
1543         check_access(f, filename);
1544         if (scan_authfile(f, user, our_name, secret, &addrs, &opts, filename, 0) < 0) {
1545             warn("no PAP secret found for %s", user);
1546         } else {
1547             /*
1548              * If the secret is "@login", it means to check
1549              * the password against the login database.
1550              */
1551             int login_secret = strcmp(secret, "@login") == 0;
1552             ret = UPAP_AUTHACK;
1553             if (uselogin || login_secret) {
1554                 /* login option or secret is @login */
1555                 if (session_full(user, passwd, devnam, msg) == 0) {
1556                     ret = UPAP_AUTHNAK;
1557                 }
1558             } else if (session_mgmt) {
1559                 if (session_check(user, NULL, devnam, NULL) == 0) {
1560                     warn("Peer %q failed PAP Session verification", user);
1561                     ret = UPAP_AUTHNAK;
1562                 }
1563             }
1564             if (secret[0] != 0 && !login_secret) {
1565                 /* password given in pap-secrets - must match */
1566                 if (cryptpap || strcmp(passwd, secret) != 0) {
1567 #ifdef HAVE_CRYPT_H
1568                     char *cbuf = crypt(passwd, secret);
1569                     if (!cbuf || strcmp(cbuf, secret) != 0)
1570 #endif
1571                         ret = UPAP_AUTHNAK;
1572                 }
1573             }
1574         }
1575         fclose(f);
1576     }
1577
1578     if (ret == UPAP_AUTHNAK) {
1579         if (**msg == 0)
1580             *msg = "Login incorrect";
1581         /*
1582          * XXX can we ever get here more than once??
1583          * Frustrate passwd stealer programs.
1584          * Allow 10 tries, but start backing off after 3 (stolen from login).
1585          * On 10'th, drop the connection.
1586          */
1587         if (attempts++ >= 10) {
1588             warn("%d LOGIN FAILURES ON %s, %s", attempts, devnam, user);
1589             lcp_close(unit, "login failed");
1590         }
1591         if (attempts > 3)
1592             sleep((u_int) (attempts - 3) * 5);
1593         if (opts != NULL)
1594             free_wordlist(opts);
1595
1596     } else {
1597         attempts = 0;                   /* Reset count */
1598         if (**msg == 0)
1599             *msg = "Login ok";
1600         set_allowed_addrs(unit, addrs, opts);
1601     }
1602
1603     if (addrs != NULL)
1604         free_wordlist(addrs);
1605     BZERO(passwd, sizeof(passwd));
1606     BZERO(secret, sizeof(secret));
1607
1608     return ret;
1609 }
1610
1611 /*
1612  * null_login - Check if a username of "" and a password of "" are
1613  * acceptable, and iff so, set the list of acceptable IP addresses
1614  * and return 1.
1615  */
1616 static int
1617 null_login(int unit)
1618 {
1619     char *filename;
1620     FILE *f;
1621     int i, ret;
1622     struct wordlist *addrs, *opts;
1623     char secret[MAXWORDLEN];
1624
1625     /*
1626      * Check if a plugin wants to handle this.
1627      */
1628     ret = -1;
1629     if (null_auth_hook)
1630         ret = (*null_auth_hook)(&addrs, &opts);
1631
1632     /*
1633      * Open the file of pap secrets and scan for a suitable secret.
1634      */
1635     if (ret <= 0) {
1636         filename = PPP_PATH_UPAPFILE;
1637         addrs = NULL;
1638         f = fopen(filename, "r");
1639         if (f == NULL)
1640             return 0;
1641         check_access(f, filename);
1642
1643         i = scan_authfile(f, "", our_name, secret, &addrs, &opts, filename, 0);
1644         ret = i >= 0 && secret[0] == 0;
1645         BZERO(secret, sizeof(secret));
1646         fclose(f);
1647     }
1648
1649     if (ret)
1650         set_allowed_addrs(unit, addrs, opts);
1651     else if (opts != 0)
1652         free_wordlist(opts);
1653     if (addrs != 0)
1654         free_wordlist(addrs);
1655
1656     return ret;
1657 }
1658
1659
1660 /*
1661  * get_pap_passwd - get a password for authenticating ourselves with
1662  * our peer using PAP.  Returns 1 on success, 0 if no suitable password
1663  * could be found.
1664  * Assumes passwd points to MAXSECRETLEN bytes of space (if non-null).
1665  */
1666 static int
1667 get_pap_passwd(char *passwd)
1668 {
1669     char *filename;
1670     FILE *f;
1671     int ret;
1672     char secret[MAXWORDLEN];
1673
1674     /*
1675      * Check whether a plugin wants to supply this.
1676      */
1677     if (pap_passwd_hook) {
1678         ret = (*pap_passwd_hook)(user, passwd);
1679         if (ret >= 0)
1680             return ret;
1681     }
1682
1683     filename = PPP_PATH_UPAPFILE;
1684     f = fopen(filename, "r");
1685     if (f == NULL)
1686         return 0;
1687     check_access(f, filename);
1688     ret = scan_authfile(f, user,
1689                         (remote_name[0]? remote_name: NULL),
1690                         secret, NULL, NULL, filename, 0);
1691     fclose(f);
1692     if (ret < 0)
1693         return 0;
1694     if (passwd != NULL)
1695         strlcpy(passwd, secret, MAXSECRETLEN);
1696     BZERO(secret, sizeof(secret));
1697     return 1;
1698 }
1699
1700
1701 /*
1702  * have_pap_secret - check whether we have a PAP file with any
1703  * secrets that we could possibly use for authenticating the peer.
1704  */
1705 static int
1706 have_pap_secret(int *lacks_ipp)
1707 {
1708     FILE *f;
1709     int ret;
1710     char *filename;
1711     struct wordlist *addrs;
1712
1713     /* let the plugin decide, if there is one */
1714     if (pap_check_hook) {
1715         ret = (*pap_check_hook)();
1716         if (ret >= 0)
1717             return ret;
1718     }
1719
1720     filename = PPP_PATH_UPAPFILE;
1721     f = fopen(filename, "r");
1722     if (f == NULL)
1723         return 0;
1724
1725     ret = scan_authfile(f, (explicit_remote? remote_name: NULL), our_name,
1726                         NULL, &addrs, NULL, filename, 0);
1727     fclose(f);
1728     if (ret >= 0 && !some_ip_ok(addrs)) {
1729         if (lacks_ipp != 0)
1730             *lacks_ipp = 1;
1731         ret = -1;
1732     }
1733     if (addrs != 0)
1734         free_wordlist(addrs);
1735
1736     return ret >= 0;
1737 }
1738
1739
1740 /*
1741  * have_chap_secret - check whether we have a CHAP file with a
1742  * secret that we could possibly use for authenticating `client'
1743  * on `server'.  Either can be the null string, meaning we don't
1744  * know the identity yet.
1745  */
1746 static int
1747 have_chap_secret(char *client, char *server,
1748                  int need_ip, int *lacks_ipp)
1749 {
1750     FILE *f;
1751     int ret;
1752     char *filename;
1753     struct wordlist *addrs;
1754
1755     if (chap_check_hook) {
1756         ret = (*chap_check_hook)();
1757         if (ret >= 0) {
1758             return ret;
1759         }
1760     }
1761
1762     filename = PPP_PATH_CHAPFILE;
1763     f = fopen(filename, "r");
1764     if (f == NULL)
1765         return 0;
1766
1767     if (client != NULL && client[0] == 0)
1768         client = NULL;
1769     else if (server != NULL && server[0] == 0)
1770         server = NULL;
1771
1772     ret = scan_authfile(f, client, server, NULL, &addrs, NULL, filename, 0);
1773     fclose(f);
1774     if (ret >= 0 && need_ip && !some_ip_ok(addrs)) {
1775         if (lacks_ipp != 0)
1776             *lacks_ipp = 1;
1777         ret = -1;
1778     }
1779     if (addrs != 0)
1780         free_wordlist(addrs);
1781
1782     return ret >= 0;
1783 }
1784
1785
1786 /*
1787  * have_srp_secret - check whether we have a SRP file with a
1788  * secret that we could possibly use for authenticating `client'
1789  * on `server'.  Either can be the null string, meaning we don't
1790  * know the identity yet.
1791  */
1792 static int
1793 have_srp_secret(char *client, char *server, int need_ip, int *lacks_ipp)
1794 {
1795     FILE *f;
1796     int ret;
1797     char *filename;
1798     struct wordlist *addrs;
1799
1800     filename = PPP_PATH_SRPFILE;
1801     f = fopen(filename, "r");
1802     if (f == NULL)
1803         return 0;
1804
1805     if (client != NULL && client[0] == 0)
1806         client = NULL;
1807     else if (server != NULL && server[0] == 0)
1808         server = NULL;
1809
1810     ret = scan_authfile(f, client, server, NULL, &addrs, NULL, filename, 0);
1811     fclose(f);
1812     if (ret >= 0 && need_ip && !some_ip_ok(addrs)) {
1813         if (lacks_ipp != 0)
1814             *lacks_ipp = 1;
1815         ret = -1;
1816     }
1817     if (addrs != 0)
1818         free_wordlist(addrs);
1819
1820     return ret >= 0;
1821 }
1822
1823
1824 /*
1825  * get_secret - open the CHAP secret file and return the secret
1826  * for authenticating the given client on the given server.
1827  * (We could be either client or server).
1828  */
1829 int
1830 get_secret(int unit, char *client, char *server,
1831            char *secret, int *secret_len, int am_server)
1832 {
1833     FILE *f;
1834     int ret, len;
1835     char *filename;
1836     struct wordlist *addrs, *opts;
1837     char secbuf[MAXWORDLEN];
1838
1839     if (!am_server && passwd[0] != 0) {
1840         strlcpy(secbuf, passwd, sizeof(secbuf));
1841     } else if (!am_server && chap_passwd_hook) {
1842         if ( (*chap_passwd_hook)(client, secbuf) < 0) {
1843             error("Unable to obtain CHAP password for %s on %s from plugin",
1844                   client, server);
1845             return 0;
1846         }
1847     } else {
1848         filename = PPP_PATH_CHAPFILE;
1849         addrs = NULL;
1850         secbuf[0] = 0;
1851
1852         f = fopen(filename, "r");
1853         if (f == NULL) {
1854             error("Can't open chap secret file %s: %m", filename);
1855             return 0;
1856         }
1857         check_access(f, filename);
1858
1859         ret = scan_authfile(f, client, server, secbuf, &addrs, &opts, filename, 0);
1860         fclose(f);
1861         if (ret < 0)
1862             return 0;
1863
1864         if (am_server)
1865             set_allowed_addrs(unit, addrs, opts);
1866         else if (opts != 0)
1867             free_wordlist(opts);
1868         if (addrs != 0)
1869             free_wordlist(addrs);
1870     }
1871
1872     len = strlen(secbuf);
1873     if (len > MAXSECRETLEN) {
1874         error("Secret for %s on %s is too long", client, server);
1875         len = MAXSECRETLEN;
1876     }
1877     BCOPY(secbuf, secret, len);
1878     BZERO(secbuf, sizeof(secbuf));
1879     *secret_len = len;
1880
1881     return 1;
1882 }
1883
1884
1885 /*
1886  * get_srp_secret - open the SRP secret file and return the secret
1887  * for authenticating the given client on the given server.
1888  * (We could be either client or server).
1889  */
1890 int
1891 get_srp_secret(int unit, char *client, char *server,
1892                char *secret, int am_server)
1893 {
1894     FILE *fp;
1895     int ret;
1896     char *filename;
1897     struct wordlist *addrs, *opts;
1898
1899     if (!am_server && passwd[0] != '\0') {
1900         strlcpy(secret, passwd, MAXWORDLEN);
1901     } else {
1902         filename = PPP_PATH_SRPFILE;
1903         addrs = NULL;
1904
1905         fp = fopen(filename, "r");
1906         if (fp == NULL) {
1907             error("Can't open srp secret file %s: %m", filename);
1908             return 0;
1909         }
1910         check_access(fp, filename);
1911
1912         secret[0] = '\0';
1913         ret = scan_authfile(fp, client, server, secret, &addrs, &opts,
1914             filename, am_server);
1915         fclose(fp);
1916         if (ret < 0)
1917             return 0;
1918
1919         if (am_server)
1920             set_allowed_addrs(unit, addrs, opts);
1921         else if (opts != NULL)
1922             free_wordlist(opts);
1923         if (addrs != NULL)
1924             free_wordlist(addrs);
1925     }
1926
1927     return 1;
1928 }
1929
1930 /*
1931  * set_allowed_addrs() - set the list of allowed addresses.
1932  * Also looks for `--' indicating options to apply for this peer
1933  * and leaves the following words in extra_options.
1934  */
1935 static void
1936 set_allowed_addrs(int unit, struct wordlist *addrs,
1937                   struct wordlist *opts)
1938 {
1939     int n;
1940     struct wordlist *ap, **plink;
1941     struct permitted_ip *ip;
1942     char *ptr_word, *ptr_mask;
1943     struct hostent *hp;
1944     struct netent *np;
1945     u_int32_t a, mask, ah, offset;
1946     struct ipcp_options *wo = &ipcp_wantoptions[unit];
1947     u_int32_t suggested_ip = 0;
1948
1949     if (addresses[unit] != NULL)
1950         free(addresses[unit]);
1951     addresses[unit] = NULL;
1952     if (extra_options != NULL)
1953         free_wordlist(extra_options);
1954     extra_options = opts;
1955
1956     /*
1957      * Count the number of IP addresses given.
1958      */
1959     n = wordlist_count(addrs) + wordlist_count(noauth_addrs);
1960     if (n == 0)
1961         return;
1962     ip = (struct permitted_ip *) malloc((n + 1) * sizeof(struct permitted_ip));
1963     if (ip == 0)
1964         return;
1965
1966     /* temporarily append the noauth_addrs list to addrs */
1967     for (plink = &addrs; *plink != NULL; plink = &(*plink)->next)
1968         ;
1969     *plink = noauth_addrs;
1970
1971     n = 0;
1972     for (ap = addrs; ap != NULL; ap = ap->next) {
1973         /* "-" means no addresses authorized, "*" means any address allowed */
1974         ptr_word = ap->word;
1975         if (strcmp(ptr_word, "-") == 0)
1976             break;
1977         if (strcmp(ptr_word, "*") == 0) {
1978             ip[n].permit = 1;
1979             ip[n].base = ip[n].mask = 0;
1980             ++n;
1981             break;
1982         }
1983
1984         ip[n].permit = 1;
1985         if (*ptr_word == '!') {
1986             ip[n].permit = 0;
1987             ++ptr_word;
1988         }
1989
1990         mask = ~ (u_int32_t) 0;
1991         offset = 0;
1992         ptr_mask = strchr (ptr_word, '/');
1993         if (ptr_mask != NULL) {
1994             int bit_count;
1995             char *endp;
1996
1997             bit_count = (int) strtol (ptr_mask+1, &endp, 10);
1998             if (bit_count <= 0 || bit_count > 32) {
1999                 warn("invalid address length %v in auth. address list",
2000                      ptr_mask+1);
2001                 continue;
2002             }
2003             bit_count = 32 - bit_count; /* # bits in host part */
2004             if (*endp == '+') {
2005                 offset = ifunit + 1;
2006                 ++endp;
2007             }
2008             if (*endp != 0) {
2009                 warn("invalid address length syntax: %v", ptr_mask+1);
2010                 continue;
2011             }
2012             *ptr_mask = '\0';
2013             mask <<= bit_count;
2014         }
2015
2016         hp = gethostbyname(ptr_word);
2017         if (hp != NULL && hp->h_addrtype == AF_INET) {
2018             a = *(u_int32_t *)hp->h_addr;
2019         } else {
2020             np = getnetbyname (ptr_word);
2021             if (np != NULL && np->n_addrtype == AF_INET) {
2022                 a = htonl ((u_int32_t)np->n_net);
2023                 if (ptr_mask == NULL) {
2024                     /* calculate appropriate mask for net */
2025                     ah = ntohl(a);
2026                     if (IN_CLASSA(ah))
2027                         mask = IN_CLASSA_NET;
2028                     else if (IN_CLASSB(ah))
2029                         mask = IN_CLASSB_NET;
2030                     else if (IN_CLASSC(ah))
2031                         mask = IN_CLASSC_NET;
2032                 }
2033             } else {
2034                 a = inet_addr (ptr_word);
2035             }
2036         }
2037
2038         if (ptr_mask != NULL)
2039             *ptr_mask = '/';
2040
2041         if (a == (u_int32_t)-1L) {
2042             warn("unknown host %s in auth. address list", ap->word);
2043             continue;
2044         }
2045         if (offset != 0) {
2046             if (offset >= ~mask) {
2047                 warn("interface unit %d too large for subnet %v",
2048                      ifunit, ptr_word);
2049                 continue;
2050             }
2051             a = htonl((ntohl(a) & mask) + offset);
2052             mask = ~(u_int32_t)0;
2053         }
2054         ip[n].mask = htonl(mask);
2055         ip[n].base = a & ip[n].mask;
2056         ++n;
2057         if (~mask == 0 && suggested_ip == 0)
2058             suggested_ip = a;
2059     }
2060     *plink = NULL;
2061
2062     ip[n].permit = 0;           /* make the last entry forbid all addresses */
2063     ip[n].base = 0;             /* to terminate the list */
2064     ip[n].mask = 0;
2065
2066     addresses[unit] = ip;
2067
2068     /*
2069      * If the address given for the peer isn't authorized, or if
2070      * the user hasn't given one, AND there is an authorized address
2071      * which is a single host, then use that if we find one.
2072      */
2073     if (suggested_ip != 0
2074         && (wo->hisaddr == 0 || !auth_ip_addr(unit, wo->hisaddr))) {
2075         wo->hisaddr = suggested_ip;
2076         /*
2077          * Do we insist on this address?  No, if there are other
2078          * addresses authorized than the suggested one.
2079          */
2080         if (n > 1)
2081             wo->accept_remote = 1;
2082     }
2083 }
2084
2085 /*
2086  * auth_ip_addr - check whether the peer is authorized to use
2087  * a given IP address.  Returns 1 if authorized, 0 otherwise.
2088  */
2089 int
2090 auth_ip_addr(int unit, u_int32_t addr)
2091 {
2092     int ok;
2093
2094     /* don't allow loopback or multicast address */
2095     if (ppp_bad_ip_addr(addr))
2096         return 0;
2097
2098     if (allowed_address_hook) {
2099         ok = allowed_address_hook(addr);
2100         if (ok >= 0) return ok;
2101     }
2102
2103     if (addresses[unit] != NULL) {
2104         ok = ip_addr_check(addr, addresses[unit]);
2105         if (ok >= 0)
2106             return ok;
2107     }
2108
2109     if (auth_required)
2110         return 0;               /* no addresses authorized */
2111     return allow_any_ip || privileged || !have_route_to(addr);
2112 }
2113
2114 static int
2115 ip_addr_check(u_int32_t addr, struct permitted_ip *addrs)
2116 {
2117     for (; ; ++addrs)
2118         if ((addr & addrs->mask) == addrs->base)
2119             return addrs->permit;
2120 }
2121
2122 /*
2123  * Check if given addr in network byte order is in the looback network, or a multicast address.
2124  */
2125 bool
2126 ppp_bad_ip_addr(u_int32_t addr)
2127 {
2128     addr = ntohl(addr);
2129     return (addr >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET
2130         || IN_MULTICAST(addr) || IN_BADCLASS(addr);
2131 }
2132
2133 /*
2134  * some_ip_ok - check a wordlist to see if it authorizes any
2135  * IP address(es).
2136  */
2137 static int
2138 some_ip_ok(struct wordlist *addrs)
2139 {
2140     for (; addrs != 0; addrs = addrs->next) {
2141         if (addrs->word[0] == '-')
2142             break;
2143         if (addrs->word[0] != '!')
2144             return 1;           /* some IP address is allowed */
2145     }
2146     return 0;
2147 }
2148
2149 /*
2150  * auth_number - check whether the remote number is allowed to connect.
2151  * Returns 1 if authorized, 0 otherwise.
2152  */
2153 int
2154 auth_number(void)
2155 {
2156     struct wordlist *wp = permitted_numbers;
2157     int l;
2158
2159     /* Allow all if no authorization list. */
2160     if (!wp)
2161         return 1;
2162
2163     /* Allow if we have a match in the authorization list. */
2164     while (wp) {
2165         /* trailing '*' wildcard */
2166         l = strlen(wp->word);
2167         if ((wp->word)[l - 1] == '*')
2168             l--;
2169         if (!strncasecmp(wp->word, remote_number, l))
2170             return 1;
2171         wp = wp->next;
2172     }
2173
2174     return 0;
2175 }
2176
2177 /*
2178  * check_access - complain if a secret file has too-liberal permissions.
2179  */
2180 static void
2181 check_access(FILE *f, char *filename)
2182 {
2183     struct stat sbuf;
2184
2185     if (fstat(fileno(f), &sbuf) < 0) {
2186         warn("cannot stat secret file %s: %m", filename);
2187     } else if ((sbuf.st_mode & (S_IRWXG | S_IRWXO)) != 0) {
2188         warn("Warning - secret file %s has world and/or group access",
2189              filename);
2190     }
2191 }
2192
2193
2194 /*
2195  * scan_authfile - Scan an authorization file for a secret suitable
2196  * for authenticating `client' on `server'.  The return value is -1
2197  * if no secret is found, otherwise >= 0.  The return value has
2198  * NONWILD_CLIENT set if the secret didn't have "*" for the client, and
2199  * NONWILD_SERVER set if the secret didn't have "*" for the server.
2200  * Any following words on the line up to a "--" (i.e. address authorization
2201  * info) are placed in a wordlist and returned in *addrs.  Any
2202  * following words (extra options) are placed in a wordlist and
2203  * returned in *opts.
2204  * We assume secret is NULL or points to MAXWORDLEN bytes of space.
2205  * Flags are non-zero if we need two colons in the secret in order to
2206  * match.
2207  */
2208 static int
2209 scan_authfile(FILE *f, char *client, char *server,
2210               char *secret, struct wordlist **addrs,
2211               struct wordlist **opts, char *filename,
2212               int flags)
2213 {
2214     int newline, xxx;
2215     int got_flag, best_flag;
2216     FILE *sf;
2217     struct wordlist *ap, *addr_list, *alist, **app;
2218     char word[MAXWORDLEN];
2219     char atfile[MAXWORDLEN];
2220     char lsecret[MAXWORDLEN];
2221     char *cp;
2222
2223     if (addrs != NULL)
2224         *addrs = NULL;
2225     if (opts != NULL)
2226         *opts = NULL;
2227     addr_list = NULL;
2228     if (!getword(f, word, &newline, filename))
2229         return -1;              /* file is empty??? */
2230     newline = 1;
2231     best_flag = -1;
2232     for (;;) {
2233         /*
2234          * Skip until we find a word at the start of a line.
2235          */
2236         while (!newline && getword(f, word, &newline, filename))
2237             ;
2238         if (!newline)
2239             break;              /* got to end of file */
2240
2241         /*
2242          * Got a client - check if it's a match or a wildcard.
2243          */
2244         got_flag = 0;
2245         if (client != NULL && strcmp(word, client) != 0 && !ISWILD(word)) {
2246             newline = 0;
2247             continue;
2248         }
2249         if (!ISWILD(word))
2250             got_flag = NONWILD_CLIENT;
2251
2252         /*
2253          * Now get a server and check if it matches.
2254          */
2255         if (!getword(f, word, &newline, filename))
2256             break;
2257         if (newline)
2258             continue;
2259         if (!ISWILD(word)) {
2260             if (server != NULL && strcmp(word, server) != 0)
2261                 continue;
2262             got_flag |= NONWILD_SERVER;
2263         }
2264
2265         /*
2266          * Got some sort of a match - see if it's better than what
2267          * we have already.
2268          */
2269         if (got_flag <= best_flag)
2270             continue;
2271
2272         /*
2273          * Get the secret.
2274          */
2275         if (!getword(f, word, &newline, filename))
2276             break;
2277         if (newline)
2278             continue;
2279
2280         /*
2281          * SRP-SHA1 authenticator should never be reading secrets from
2282          * a file.  (Authenticatee may, though.)
2283          */
2284         if (flags && ((cp = strchr(word, ':')) == NULL ||
2285             strchr(cp + 1, ':') == NULL))
2286             continue;
2287
2288         if (secret != NULL) {
2289             /*
2290              * Special syntax: @/pathname means read secret from file.
2291              */
2292             if (word[0] == '@' && word[1] == '/') {
2293                 strlcpy(atfile, word+1, sizeof(atfile));
2294                 if ((sf = fopen(atfile, "r")) == NULL) {
2295                     warn("can't open indirect secret file %s", atfile);
2296                     continue;
2297                 }
2298                 check_access(sf, atfile);
2299                 if (!getword(sf, word, &xxx, atfile)) {
2300                     warn("no secret in indirect secret file %s", atfile);
2301                     fclose(sf);
2302                     continue;
2303                 }
2304                 fclose(sf);
2305             }
2306             strlcpy(lsecret, word, sizeof(lsecret));
2307         }
2308
2309         /*
2310          * Now read address authorization info and make a wordlist.
2311          */
2312         app = &alist;
2313         for (;;) {
2314             if (!getword(f, word, &newline, filename) || newline)
2315                 break;
2316             ap = (struct wordlist *)
2317                     malloc(sizeof(struct wordlist) + strlen(word) + 1);
2318             if (ap == NULL)
2319                 novm("authorized addresses");
2320             ap->word = (char *) (ap + 1);
2321             strcpy(ap->word, word);
2322             *app = ap;
2323             app = &ap->next;
2324         }
2325         *app = NULL;
2326
2327         /*
2328          * This is the best so far; remember it.
2329          */
2330         best_flag = got_flag;
2331         if (addr_list)
2332             free_wordlist(addr_list);
2333         addr_list = alist;
2334         if (secret != NULL)
2335             strlcpy(secret, lsecret, MAXWORDLEN);
2336
2337         if (!newline)
2338             break;
2339     }
2340
2341     /* scan for a -- word indicating the start of options */
2342     for (app = &addr_list; (ap = *app) != NULL; app = &ap->next)
2343         if (strcmp(ap->word, "--") == 0)
2344             break;
2345     /* ap = start of options */
2346     if (ap != NULL) {
2347         ap = ap->next;          /* first option */
2348         free(*app);                     /* free the "--" word */
2349         *app = NULL;            /* terminate addr list */
2350     }
2351     if (opts != NULL)
2352         *opts = ap;
2353     else if (ap != NULL)
2354         free_wordlist(ap);
2355     if (addrs != NULL)
2356         *addrs = addr_list;
2357     else if (addr_list != NULL)
2358         free_wordlist(addr_list);
2359
2360     return best_flag;
2361 }
2362
2363 /*
2364  * wordlist_count - return the number of items in a wordlist
2365  */
2366 static int
2367 wordlist_count(struct wordlist *wp)
2368 {
2369     int n;
2370
2371     for (n = 0; wp != NULL; wp = wp->next)
2372         ++n;
2373     return n;
2374 }
2375
2376 /*
2377  * free_wordlist - release memory allocated for a wordlist.
2378  */
2379 static void
2380 free_wordlist(struct wordlist *wp)
2381 {
2382     struct wordlist *next;
2383
2384     while (wp != NULL) {
2385         next = wp->next;
2386         free(wp);
2387         wp = next;
2388     }
2389 }
2390
2391 /*
2392  * auth_script_done - called when the auth-up or auth-down script
2393  * has finished.
2394  */
2395 static void
2396 auth_script_done(void *arg)
2397 {
2398     auth_script_pid = 0;
2399     switch (auth_script_state) {
2400     case s_up:
2401         if (auth_state == s_down) {
2402             auth_script_state = s_down;
2403             auth_script(PPP_PATH_AUTHDOWN);
2404         }
2405         break;
2406     case s_down:
2407         if (auth_state == s_up) {
2408             auth_script_state = s_up;
2409             auth_script(PPP_PATH_AUTHUP);
2410         }
2411         break;
2412     }
2413 }
2414
2415 /*
2416  * auth_script - execute a script with arguments
2417  * interface-name peer-name real-user tty speed
2418  */
2419 static void
2420 auth_script(char *script)
2421 {
2422     char strspeed[32];
2423     struct passwd *pw;
2424     char struid[32];
2425     char *user_name;
2426     char *argv[8];
2427
2428     if ((pw = getpwuid(getuid())) != NULL && pw->pw_name != NULL)
2429         user_name = pw->pw_name;
2430     else {
2431         slprintf(struid, sizeof(struid), "%d", getuid());
2432         user_name = struid;
2433     }
2434     slprintf(strspeed, sizeof(strspeed), "%d", baud_rate);
2435
2436     argv[0] = script;
2437     argv[1] = ifname;
2438     argv[2] = peer_authname;
2439     argv[3] = user_name;
2440     argv[4] = devnam;
2441     argv[5] = strspeed;
2442     argv[6] = ipparam;
2443     argv[7] = NULL;
2444
2445     auth_script_pid = run_program(script, argv, 0, auth_script_done, NULL, 0);
2446 }
2447
2448
2449 #ifdef PPP_WITH_EAPTLS
2450 static int
2451 have_eaptls_secret_server(char *client, char *server,
2452                           int need_ip, int *lacks_ipp)
2453 {
2454     FILE *f;
2455     int ret;
2456     char *filename;
2457     struct wordlist *addrs;
2458     char servcertfile[MAXWORDLEN];
2459     char clicertfile[MAXWORDLEN];
2460     char cacertfile[MAXWORDLEN];
2461     char pkfile[MAXWORDLEN];
2462
2463     filename = PPP_PATH_EAPTLSSERVFILE;
2464     f = fopen(filename, "r");
2465     if (f == NULL)
2466                 return 0;
2467
2468     if (client != NULL && client[0] == 0)
2469                 client = NULL;
2470     else if (server != NULL && server[0] == 0)
2471                 server = NULL;
2472
2473     ret =
2474         scan_authfile_eaptls(f, client, server, clicertfile, servcertfile,
2475                              cacertfile, pkfile, &addrs, NULL, filename,
2476                              0);
2477
2478     fclose(f);
2479
2480 /*
2481     if (ret >= 0 && !eaptls_init_ssl(1, cacertfile, servcertfile,
2482                                 clicertfile, pkfile))
2483                 ret = -1;
2484 */
2485
2486         if (ret >= 0 && need_ip && !some_ip_ok(addrs)) {
2487                 if (lacks_ipp != 0)
2488                         *lacks_ipp = 1;
2489                 ret = -1;
2490     }
2491     if (addrs != 0)
2492                 free_wordlist(addrs);
2493
2494     return ret >= 0;
2495 }
2496
2497
2498 static int
2499 have_eaptls_secret_client(char *client, char *server)
2500 {
2501     FILE *f;
2502     int ret;
2503     char *filename;
2504     struct wordlist *addrs = NULL;
2505     char servcertfile[MAXWORDLEN];
2506     char clicertfile[MAXWORDLEN];
2507     char cacertfile[MAXWORDLEN];
2508     char pkfile[MAXWORDLEN];
2509
2510     if (client != NULL && client[0] == 0)
2511                 client = NULL;
2512     else if (server != NULL && server[0] == 0)
2513                 server = NULL;
2514
2515         if ((cacert_file || ca_path) && cert_file && privkey_file)
2516                 return 1;
2517         if (pkcs12_file)
2518                 return 1;
2519
2520     filename = PPP_PATH_EAPTLSCLIFILE;
2521     f = fopen(filename, "r");
2522     if (f == NULL)
2523                 return 0;
2524
2525     ret =
2526         scan_authfile_eaptls(f, client, server, clicertfile, servcertfile,
2527                              cacertfile, pkfile, &addrs, NULL, filename,
2528                              0);
2529     fclose(f);
2530
2531 /*
2532     if (ret >= 0 && !eaptls_init_ssl(0, cacertfile, clicertfile,
2533                                 servcertfile, pkfile))
2534                 ret = -1;
2535 */
2536
2537     if (addrs != 0)
2538                 free_wordlist(addrs);
2539
2540     return ret >= 0;
2541 }
2542
2543
2544 static int
2545 scan_authfile_eaptls(FILE *f, char *client, char *server,
2546                      char *cli_cert, char *serv_cert, char *ca_cert,
2547                      char *pk, struct wordlist **addrs,
2548                      struct wordlist **opts,
2549                      char *filename, int flags)
2550 {
2551     int newline;
2552     int got_flag, best_flag;
2553     struct wordlist *ap, *addr_list, *alist, **app;
2554     char word[MAXWORDLEN];
2555
2556     if (addrs != NULL)
2557         *addrs = NULL;
2558     if (opts != NULL)
2559         *opts = NULL;
2560     addr_list = NULL;
2561     if (!getword(f, word, &newline, filename))
2562         return -1;              /* file is empty??? */
2563     newline = 1;
2564     best_flag = -1;
2565     for (;;) {
2566         /*
2567          * Skip until we find a word at the start of a line.
2568          */
2569         while (!newline && getword(f, word, &newline, filename));
2570         if (!newline)
2571             break;              /* got to end of file */
2572
2573         /*
2574          * Got a client - check if it's a match or a wildcard.
2575          */
2576         got_flag = 0;
2577         if (client != NULL && strcmp(word, client) != 0 && !ISWILD(word)) {
2578             newline = 0;
2579             continue;
2580         }
2581         if (!ISWILD(word))
2582             got_flag = NONWILD_CLIENT;
2583
2584         /*
2585          * Now get a server and check if it matches.
2586          */
2587         if (!getword(f, word, &newline, filename))
2588             break;
2589         if (newline)
2590             continue;
2591         if (!ISWILD(word)) {
2592             if (server != NULL && strcmp(word, server) != 0)
2593                 continue;
2594             got_flag |= NONWILD_SERVER;
2595         }
2596
2597         /*
2598          * Got some sort of a match - see if it's better than what
2599          * we have already.
2600          */
2601         if (got_flag <= best_flag)
2602             continue;
2603
2604         /*
2605          * Get the cli_cert
2606          */
2607         if (!getword(f, word, &newline, filename))
2608             break;
2609         if (newline)
2610             continue;
2611         if (strcmp(word, "-") != 0) {
2612             strlcpy(cli_cert, word, MAXWORDLEN);
2613         } else
2614             cli_cert[0] = 0;
2615
2616         /*
2617          * Get serv_cert
2618          */
2619         if (!getword(f, word, &newline, filename))
2620             break;
2621         if (newline)
2622             continue;
2623         if (strcmp(word, "-") != 0) {
2624             strlcpy(serv_cert, word, MAXWORDLEN);
2625         } else
2626             serv_cert[0] = 0;
2627
2628         /*
2629          * Get ca_cert
2630          */
2631         if (!getword(f, word, &newline, filename))
2632             break;
2633         if (newline)
2634             continue;
2635         strlcpy(ca_cert, word, MAXWORDLEN);
2636
2637         /*
2638          * Get pk
2639          */
2640         if (!getword(f, word, &newline, filename))
2641             break;
2642         if (newline)
2643             continue;
2644         strlcpy(pk, word, MAXWORDLEN);
2645
2646
2647         /*
2648          * Now read address authorization info and make a wordlist.
2649          */
2650         app = &alist;
2651         for (;;) {
2652             if (!getword(f, word, &newline, filename) || newline)
2653                 break;
2654             ap = (struct wordlist *)
2655                 malloc(sizeof(struct wordlist) + strlen(word) + 1);
2656             if (ap == NULL)
2657                 novm("authorized addresses");
2658             ap->word = (char *) (ap + 1);
2659             strcpy(ap->word, word);
2660             *app = ap;
2661             app = &ap->next;
2662         }
2663         *app = NULL;
2664         /*
2665          * This is the best so far; remember it.
2666          */
2667         best_flag = got_flag;
2668         if (addr_list)
2669             free_wordlist(addr_list);
2670         addr_list = alist;
2671
2672         if (!newline)
2673             break;
2674     }
2675
2676     /* scan for a -- word indicating the start of options */
2677     for (app = &addr_list; (ap = *app) != NULL; app = &ap->next)
2678         if (strcmp(ap->word, "--") == 0)
2679             break;
2680     /* ap = start of options */
2681     if (ap != NULL) {
2682         ap = ap->next;          /* first option */
2683         free(*app);             /* free the "--" word */
2684         *app = NULL;            /* terminate addr list */
2685     }
2686     if (opts != NULL)
2687         *opts = ap;
2688     else if (ap != NULL)
2689         free_wordlist(ap);
2690     if (addrs != NULL)
2691         *addrs = addr_list;
2692     else if (addr_list != NULL)
2693         free_wordlist(addr_list);
2694
2695     return best_flag;
2696 }
2697
2698
2699 int
2700 get_eaptls_secret(int unit, char *client, char *server,
2701                   char *clicertfile, char *servcertfile, char *cacertfile,
2702                   char *capath, char *pkfile, char *pkcs12, int am_server)
2703 {
2704     FILE *fp;
2705     int ret;
2706     char *filename         = NULL;
2707     struct wordlist *addrs = NULL;
2708     struct wordlist *opts  = NULL;
2709
2710         /* maybe overkill, but it eases debugging */
2711         bzero(clicertfile, MAXWORDLEN);
2712         bzero(servcertfile, MAXWORDLEN);
2713         bzero(cacertfile, MAXWORDLEN);
2714         bzero(capath, MAXWORDLEN);
2715         bzero(pkfile, MAXWORDLEN);
2716         bzero(pkcs12, MAXWORDLEN);
2717
2718         /* the ca+cert+privkey can also be specified as options */
2719         if (!am_server && (cacert_file || ca_path) && cert_file && privkey_file )
2720         {
2721                 strlcpy( clicertfile, cert_file, MAXWORDLEN );
2722                 if (cacert_file)
2723                         strlcpy( cacertfile, cacert_file, MAXWORDLEN );
2724                 if (ca_path)
2725                         strlcpy( capath, ca_path, MAXWORDLEN );
2726                 strlcpy( pkfile, privkey_file, MAXWORDLEN );
2727         }
2728     else if (!am_server && pkcs12_file)
2729         {
2730                 strlcpy( pkcs12, pkcs12_file, MAXWORDLEN );
2731                 if (cacert_file)
2732                         strlcpy( cacertfile, cacert_file, MAXWORDLEN );
2733                 if (ca_path)
2734                         strlcpy( capath, ca_path, MAXWORDLEN );
2735         }
2736         else
2737         {
2738                 filename = (am_server ? PPP_PATH_EAPTLSSERVFILE : PPP_PATH_EAPTLSCLIFILE);
2739                 addrs = NULL;
2740
2741                 fp = fopen(filename, "r");
2742                 if (fp == NULL)
2743                 {
2744                         error("Can't open eap-tls secret file %s: %m", filename);
2745                         return 0;
2746                 }
2747
2748                 check_access(fp, filename);
2749
2750                 ret = scan_authfile_eaptls(fp, client, server, clicertfile, servcertfile,
2751                                 cacertfile, pkfile, &addrs, &opts, filename, 0);
2752
2753                 fclose(fp);
2754
2755                 if (ret < 0) return 0;
2756         }
2757
2758     if (eaptls_passwd_hook)
2759     {
2760                 dbglog( "Calling eaptls password hook" );
2761                 if ( (*eaptls_passwd_hook)(pkfile, passwd) < 0)
2762                 {
2763                          error("Unable to obtain EAP-TLS password for %s (%s) from plugin",
2764                                 client, pkfile);
2765                     return 0;
2766                 }
2767         }
2768     if (am_server)
2769                 set_allowed_addrs(unit, addrs, opts);
2770     else if (opts != NULL)
2771                 free_wordlist(opts);
2772     if (addrs != NULL)
2773                 free_wordlist(addrs);
2774
2775     return 1;
2776 }
2777 #endif