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