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