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