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