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