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