chap.c revision 96582
131921Sbrian/*-
231921Sbrian * Copyright (c) 1996 - 2001 Brian Somers <brian@Awfulhak.org>
331921Sbrian *          based on work by Toshiharu OHNO <tony-o@iij.ad.jp>
431921Sbrian *                           Internet Initiative Japan, Inc (IIJ)
531921Sbrian * All rights reserved.
631921Sbrian *
731921Sbrian * Redistribution and use in source and binary forms, with or without
831921Sbrian * modification, are permitted provided that the following conditions
931921Sbrian * are met:
1031921Sbrian * 1. Redistributions of source code must retain the above copyright
1131921Sbrian *    notice, this list of conditions and the following disclaimer.
1231921Sbrian * 2. Redistributions in binary form must reproduce the above copyright
1331921Sbrian *    notice, this list of conditions and the following disclaimer in the
1431921Sbrian *    documentation and/or other materials provided with the distribution.
1531921Sbrian *
1631921Sbrian * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
1731921Sbrian * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
1831921Sbrian * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
1931921Sbrian * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
2031921Sbrian * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2131921Sbrian * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2231921Sbrian * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2331921Sbrian * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2431921Sbrian * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2531921Sbrian * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
2650479Speter * SUCH DAMAGE.
2731061Sbrian *
2831061Sbrian * $FreeBSD: head/usr.sbin/ppp/chap.c 96582 2002-05-14 12:55:39Z brian $
2964802Sbrian */
3033603Sbrian
3136285Sbrian#include <sys/param.h>
3233603Sbrian#include <netinet/in.h>
3331061Sbrian#include <netinet/in_systm.h>
3431061Sbrian#include <netinet/ip.h>
3531061Sbrian#include <sys/socket.h>
3631061Sbrian#include <sys/un.h>
3731061Sbrian
3831061Sbrian#include <errno.h>
3936285Sbrian#include <fcntl.h>
4032025Sbrian#ifndef NODES
4131061Sbrian#include <md4.h>
4236450Sbrian#endif
4331061Sbrian#include <md5.h>
4433603Sbrian#include <paths.h>
4552487Sbrian#include <signal.h>
4636285Sbrian#include <stdio.h>
4736285Sbrian#include <stdlib.h>
4836467Sbrian#include <string.h>
4953241Sbrian#include <sys/wait.h>
5051525Sbrian#include <termios.h>
5151525Sbrian#include <unistd.h>
5253535Sbrian
5353535Sbrian#include "layer.h"
5453535Sbrian#include "mbuf.h"
5564802Sbrian#include "log.h"
5664802Sbrian#include "defs.h"
5764802Sbrian#include "timer.h"
5864802Sbrian#include "fsm.h"
5964802Sbrian#include "proto.h"
6064802Sbrian#include "lqr.h"
6164802Sbrian#include "hdlc.h"
6264802Sbrian#include "lcp.h"
6364802Sbrian#include "auth.h"
6464802Sbrian#include "async.h"
6564802Sbrian#include "throughput.h"
6664802Sbrian#include "descriptor.h"
6764802Sbrian#include "chap.h"
6864802Sbrian#include "iplist.h"
6964802Sbrian#include "slcompress.h"
7064802Sbrian#include "ncpaddr.h"
7164802Sbrian#include "ipcp.h"
7264802Sbrian#include "filter.h"
7364802Sbrian#include "ccp.h"
7464802Sbrian#include "link.h"
7564802Sbrian#include "physical.h"
7664802Sbrian#include "mp.h"
7764802Sbrian#ifndef NORADIUS
7864802Sbrian#include "radius.h"
7964802Sbrian#endif
8064802Sbrian#include "ipv6cp.h"
8164802Sbrian#include "ncp.h"
8264802Sbrian#include "bundle.h"
8364802Sbrian#include "chat.h"
8464802Sbrian#include "cbcp.h"
8564802Sbrian#include "command.h"
86134885Smarcel#include "datalink.h"
87134885Smarcel#ifndef NODES
8864802Sbrian#include "chap_ms.h"
8964802Sbrian#include "mppe.h"
9064802Sbrian#endif
9164802Sbrian#include "id.h"
9264802Sbrian
9364802Sbrianstatic const char * const chapcodes[] = {
94  "???", "CHALLENGE", "RESPONSE", "SUCCESS", "FAILURE"
95};
96#define MAXCHAPCODE (sizeof chapcodes / sizeof chapcodes[0] - 1)
97
98static void
99ChapOutput(struct physical *physical, u_int code, u_int id,
100	   const u_char *ptr, int count, const char *text)
101{
102  int plen;
103  struct fsmheader lh;
104  struct mbuf *bp;
105
106  plen = sizeof(struct fsmheader) + count;
107  lh.code = code;
108  lh.id = id;
109  lh.length = htons(plen);
110  bp = m_get(plen, MB_CHAPOUT);
111  memcpy(MBUF_CTOP(bp), &lh, sizeof(struct fsmheader));
112  if (count)
113    memcpy(MBUF_CTOP(bp) + sizeof(struct fsmheader), ptr, count);
114  log_DumpBp(LogDEBUG, "ChapOutput", bp);
115  if (text == NULL)
116    log_Printf(LogPHASE, "Chap Output: %s\n", chapcodes[code]);
117  else
118    log_Printf(LogPHASE, "Chap Output: %s (%s)\n", chapcodes[code], text);
119  link_PushPacket(&physical->link, bp, physical->dl->bundle,
120                  LINK_QUEUES(&physical->link) - 1, PROTO_CHAP);
121}
122
123static char *
124chap_BuildAnswer(char *name, char *key, u_char id, char *challenge, u_char type
125#ifndef NODES
126                 , char *peerchallenge, char *authresponse, int lanman
127#endif
128                )
129{
130  char *result, *digest;
131  size_t nlen, klen;
132
133  nlen = strlen(name);
134  klen = strlen(key);
135
136#ifndef NODES
137  if (type == 0x80) {
138    char expkey[AUTHLEN << 2];
139    MD4_CTX MD4context;
140    int f;
141
142    if ((result = malloc(1 + nlen + MS_CHAP_RESPONSE_LEN)) == NULL)
143      return result;
144
145    digest = result;					/* the response */
146    *digest++ = MS_CHAP_RESPONSE_LEN;			/* 49 */
147    memcpy(digest + MS_CHAP_RESPONSE_LEN, name, nlen);
148    if (lanman) {
149      memset(digest + 24, '\0', 25);
150      mschap_LANMan(digest, challenge + 1, key);	/* LANMan response */
151    } else {
152      memset(digest, '\0', 25);
153      digest += 24;
154
155      for (f = 0; f < klen; f++) {
156        expkey[2*f] = key[f];
157        expkey[2*f+1] = '\0';
158      }
159      /*
160       *           -----------
161       * expkey = | k\0e\0y\0 |
162       *           -----------
163       */
164      MD4Init(&MD4context);
165      MD4Update(&MD4context, expkey, klen << 1);
166      MD4Final(digest, &MD4context);
167
168      /*
169       *           ---- -------- ---------------- ------- ------
170       * result = | 49 | LANMan | 16 byte digest | 9 * ? | name |
171       *           ---- -------- ---------------- ------- ------
172       */
173      mschap_NT(digest, challenge + 1);
174    }
175    /*
176     *           ---- -------- ------------- ----- ------
177     *          |    |  struct MS_ChapResponse24  |      |
178     * result = | 49 | LANMan  |  NT digest | 0/1 | name |
179     *           ---- -------- ------------- ----- ------
180     * where only one of LANMan & NT digest are set.
181     */
182  } else if (type == 0x81) {
183    char expkey[AUTHLEN << 2];
184    char pwdhash[CHAP81_HASH_LEN];
185    char pwdhashhash[CHAP81_HASH_LEN];
186    char *ntresponse;
187    int f;
188
189    if ((result = malloc(1 + nlen + CHAP81_RESPONSE_LEN)) == NULL)
190      return result;
191
192    memset(result, 0, 1 + nlen + CHAP81_RESPONSE_LEN);
193
194    digest = result;
195    *digest++ = CHAP81_RESPONSE_LEN;		/* value size */
196
197    /* Copy our challenge */
198    memcpy(digest, peerchallenge + 1, CHAP81_CHALLENGE_LEN);
199
200    /* Expand password to Unicode XXX */
201    for (f = 0; f < klen; f++) {
202      expkey[2*f] = key[f];
203      expkey[2*f+1] = '\0';
204    }
205
206    ntresponse = digest + CHAP81_NTRESPONSE_OFF;
207
208    /* Get some needed hashes */
209    NtPasswordHash(expkey, klen * 2, pwdhash);
210    HashNtPasswordHash(pwdhash, pwdhashhash);
211
212    /* Generate NTRESPONSE to respond on challenge call */
213    GenerateNTResponse(challenge + 1, peerchallenge + 1, name, nlen,
214                       expkey, klen * 2, ntresponse);
215
216    /* Generate MPPE MASTERKEY */
217    GetMasterKey(pwdhashhash, ntresponse, MPPE_MasterKey);    /* XXX Global ! */
218
219    /* Generate AUTHRESPONSE to verify on auth success */
220    GenerateAuthenticatorResponse(expkey, klen * 2, ntresponse,
221                                  peerchallenge + 1, challenge + 1, name, nlen,
222                                  authresponse);
223
224    authresponse[CHAP81_AUTHRESPONSE_LEN] = 0;
225
226    memcpy(digest + CHAP81_RESPONSE_LEN, name, nlen);
227  } else
228#endif
229  if ((result = malloc(nlen + 17)) != NULL) {
230    /* Normal MD5 stuff */
231    MD5_CTX MD5context;
232
233    digest = result;
234    *digest++ = 16;				/* value size */
235
236    MD5Init(&MD5context);
237    MD5Update(&MD5context, &id, 1);
238    MD5Update(&MD5context, key, klen);
239    MD5Update(&MD5context, challenge + 1, *challenge);
240    MD5Final(digest, &MD5context);
241
242    memcpy(digest + 16, name, nlen);
243    /*
244     *           ---- -------- ------
245     * result = | 16 | digest | name |
246     *           ---- -------- ------
247     */
248  }
249
250  return result;
251}
252
253static void
254chap_StartChild(struct chap *chap, char *prog, const char *name)
255{
256  char *argv[MAXARGS], *nargv[MAXARGS];
257  int argc, fd;
258  int in[2], out[2];
259  pid_t pid;
260
261  if (chap->child.fd != -1) {
262    log_Printf(LogWARN, "Chap: %s: Program already running\n", prog);
263    return;
264  }
265
266  if (pipe(in) == -1) {
267    log_Printf(LogERROR, "Chap: pipe: %s\n", strerror(errno));
268    return;
269  }
270
271  if (pipe(out) == -1) {
272    log_Printf(LogERROR, "Chap: pipe: %s\n", strerror(errno));
273    close(in[0]);
274    close(in[1]);
275    return;
276  }
277
278  pid = getpid();
279  switch ((chap->child.pid = fork())) {
280    case -1:
281      log_Printf(LogERROR, "Chap: fork: %s\n", strerror(errno));
282      close(in[0]);
283      close(in[1]);
284      close(out[0]);
285      close(out[1]);
286      chap->child.pid = 0;
287      return;
288
289    case 0:
290      timer_TermService();
291
292      if ((argc = command_Interpret(prog, strlen(prog), argv)) <= 0) {
293        if (argc < 0) {
294          log_Printf(LogWARN, "CHAP: Invalid command syntax\n");
295          _exit(255);
296        }
297        _exit(0);
298      }
299
300      close(in[1]);
301      close(out[0]);
302      if (out[1] == STDIN_FILENO)
303        out[1] = dup(out[1]);
304      dup2(in[0], STDIN_FILENO);
305      dup2(out[1], STDOUT_FILENO);
306      close(STDERR_FILENO);
307      if (open(_PATH_DEVNULL, O_RDWR) != STDERR_FILENO) {
308        log_Printf(LogALERT, "Chap: Failed to open %s: %s\n",
309                  _PATH_DEVNULL, strerror(errno));
310        exit(1);
311      }
312      for (fd = getdtablesize(); fd > STDERR_FILENO; fd--)
313        fcntl(fd, F_SETFD, 1);
314#ifndef NOSUID
315      setuid(ID0realuid());
316#endif
317      command_Expand(nargv, argc, (char const *const *)argv,
318                     chap->auth.physical->dl->bundle, 0, pid);
319      execvp(nargv[0], nargv);
320      printf("exec() of %s failed: %s\n", nargv[0], strerror(errno));
321      _exit(255);
322
323    default:
324      close(in[0]);
325      close(out[1]);
326      chap->child.fd = out[0];
327      chap->child.buf.len = 0;
328      write(in[1], chap->auth.in.name, strlen(chap->auth.in.name));
329      write(in[1], "\n", 1);
330      write(in[1], chap->challenge.peer + 1, *chap->challenge.peer);
331      write(in[1], "\n", 1);
332      write(in[1], name, strlen(name));
333      write(in[1], "\n", 1);
334      close(in[1]);
335      break;
336  }
337}
338
339static void
340chap_Cleanup(struct chap *chap, int sig)
341{
342  if (chap->child.pid) {
343    int status;
344
345    close(chap->child.fd);
346    chap->child.fd = -1;
347    if (sig)
348      kill(chap->child.pid, SIGTERM);
349    chap->child.pid = 0;
350    chap->child.buf.len = 0;
351
352    if (wait(&status) == -1)
353      log_Printf(LogERROR, "Chap: wait: %s\n", strerror(errno));
354    else if (WIFSIGNALED(status))
355      log_Printf(LogWARN, "Chap: Child received signal %d\n", WTERMSIG(status));
356    else if (WIFEXITED(status) && WEXITSTATUS(status))
357      log_Printf(LogERROR, "Chap: Child exited %d\n", WEXITSTATUS(status));
358  }
359  *chap->challenge.local = *chap->challenge.peer = '\0';
360#ifndef NODES
361  chap->peertries = 0;
362#endif
363}
364
365static void
366chap_Respond(struct chap *chap, char *name, char *key, u_char type
367#ifndef NODES
368             , int lm
369#endif
370            )
371{
372  u_char *ans;
373
374  ans = chap_BuildAnswer(name, key, chap->auth.id, chap->challenge.peer, type
375#ifndef NODES
376                         , chap->challenge.local, chap->authresponse, lm
377#endif
378                        );
379
380  if (ans) {
381    ChapOutput(chap->auth.physical, CHAP_RESPONSE, chap->auth.id,
382               ans, *ans + 1 + strlen(name), name);
383#ifndef NODES
384    chap->NTRespSent = !lm;
385    MPPE_IsServer = 0;		/* XXX Global ! */
386#endif
387    free(ans);
388  } else
389    ChapOutput(chap->auth.physical, CHAP_FAILURE, chap->auth.id,
390               "Out of memory!", 14, NULL);
391}
392
393static int
394chap_UpdateSet(struct fdescriptor *d, fd_set *r, fd_set *w, fd_set *e, int *n)
395{
396  struct chap *chap = descriptor2chap(d);
397
398  if (r && chap && chap->child.fd != -1) {
399    FD_SET(chap->child.fd, r);
400    if (*n < chap->child.fd + 1)
401      *n = chap->child.fd + 1;
402    log_Printf(LogTIMER, "Chap: fdset(r) %d\n", chap->child.fd);
403    return 1;
404  }
405
406  return 0;
407}
408
409static int
410chap_IsSet(struct fdescriptor *d, const fd_set *fdset)
411{
412  struct chap *chap = descriptor2chap(d);
413
414  return chap && chap->child.fd != -1 && FD_ISSET(chap->child.fd, fdset);
415}
416
417static void
418chap_Read(struct fdescriptor *d, struct bundle *bundle, const fd_set *fdset)
419{
420  struct chap *chap = descriptor2chap(d);
421  int got;
422
423  got = read(chap->child.fd, chap->child.buf.ptr + chap->child.buf.len,
424             sizeof chap->child.buf.ptr - chap->child.buf.len - 1);
425  if (got == -1) {
426    log_Printf(LogERROR, "Chap: Read: %s\n", strerror(errno));
427    chap_Cleanup(chap, SIGTERM);
428  } else if (got == 0) {
429    log_Printf(LogWARN, "Chap: Read: Child terminated connection\n");
430    chap_Cleanup(chap, SIGTERM);
431  } else {
432    char *name, *key, *end;
433
434    chap->child.buf.len += got;
435    chap->child.buf.ptr[chap->child.buf.len] = '\0';
436    name = chap->child.buf.ptr;
437    name += strspn(name, " \t");
438    if ((key = strchr(name, '\n')) == NULL)
439      end = NULL;
440    else
441      end = strchr(++key, '\n');
442
443    if (end == NULL) {
444      if (chap->child.buf.len == sizeof chap->child.buf.ptr - 1) {
445        log_Printf(LogWARN, "Chap: Read: Input buffer overflow\n");
446        chap_Cleanup(chap, SIGTERM);
447      }
448    } else {
449#ifndef NODES
450      int lanman = chap->auth.physical->link.lcp.his_authtype == 0x80 &&
451                   ((chap->NTRespSent &&
452                     IsAccepted(chap->auth.physical->link.lcp.cfg.chap80lm)) ||
453                    !IsAccepted(chap->auth.physical->link.lcp.cfg.chap80nt));
454#endif
455
456      while (end >= name && strchr(" \t\r\n", *end))
457        *end-- = '\0';
458      end = key - 1;
459      while (end >= name && strchr(" \t\r\n", *end))
460        *end-- = '\0';
461      key += strspn(key, " \t");
462
463      chap_Respond(chap, name, key, chap->auth.physical->link.lcp.his_authtype
464#ifndef NODES
465                   , lanman
466#endif
467                  );
468      chap_Cleanup(chap, 0);
469    }
470  }
471}
472
473static int
474chap_Write(struct fdescriptor *d, struct bundle *bundle, const fd_set *fdset)
475{
476  /* We never want to write here ! */
477  log_Printf(LogALERT, "chap_Write: Internal error: Bad call !\n");
478  return 0;
479}
480
481static void
482chap_ChallengeInit(struct authinfo *authp)
483{
484  struct chap *chap = auth2chap(authp);
485  int len, i;
486  char *cp;
487
488  len = strlen(authp->physical->dl->bundle->cfg.auth.name);
489
490  if (!*chap->challenge.local) {
491    randinit();
492    cp = chap->challenge.local;
493
494#ifndef NORADIUS
495    if (*authp->physical->dl->bundle->radius.cfg.file) {
496      /* For radius, our challenge is 16 readable NUL terminated bytes :*/
497      *cp++ = 16;
498      for (i = 0; i < 16; i++)
499        *cp++ = (random() % 10) + '0';
500    } else
501#endif
502    {
503#ifndef NODES
504      if (authp->physical->link.lcp.want_authtype == 0x80)
505        *cp++ = 8;	/* MS does 8 byte callenges :-/ */
506      else if (authp->physical->link.lcp.want_authtype == 0x81)
507        *cp++ = 16;	/* MS-CHAP-V2 does 16 bytes challenges */
508      else
509#endif
510        *cp++ = random() % (CHAPCHALLENGELEN-16) + 16;
511      for (i = 0; i < *chap->challenge.local; i++)
512        *cp++ = random() & 0xff;
513    }
514    memcpy(cp, authp->physical->dl->bundle->cfg.auth.name, len);
515  }
516}
517
518static void
519chap_Challenge(struct authinfo *authp)
520{
521  struct chap *chap = auth2chap(authp);
522  int len;
523
524  log_Printf(LogDEBUG, "CHAP%02X: Challenge\n",
525             authp->physical->link.lcp.want_authtype);
526
527  len = strlen(authp->physical->dl->bundle->cfg.auth.name);
528
529  /* Generate new local challenge value */
530  if (!*chap->challenge.local)
531    chap_ChallengeInit(authp);
532
533#ifndef NODES
534  if (authp->physical->link.lcp.want_authtype == 0x81)
535    ChapOutput(authp->physical, CHAP_CHALLENGE, authp->id,
536             chap->challenge.local, 1 + *chap->challenge.local, NULL);
537  else
538#endif
539    ChapOutput(authp->physical, CHAP_CHALLENGE, authp->id,
540             chap->challenge.local, 1 + *chap->challenge.local + len, NULL);
541}
542
543static void
544chap_Success(struct authinfo *authp)
545{
546  struct bundle *bundle = authp->physical->dl->bundle;
547  const char *msg;
548
549  datalink_GotAuthname(authp->physical->dl, authp->in.name);
550#ifndef NODES
551  if (authp->physical->link.lcp.want_authtype == 0x81) {
552    msg = auth2chap(authp)->authresponse;
553    MPPE_MasterKeyValid = 1;		/* XXX Global ! */
554  } else
555#endif
556#ifndef NORADIUS
557  if (*bundle->radius.cfg.file && bundle->radius.repstr)
558    msg = bundle->radius.repstr;
559  else
560#endif
561    msg = "Welcome!!";
562
563  ChapOutput(authp->physical, CHAP_SUCCESS, authp->id, msg, strlen(msg),
564             NULL);
565
566  authp->physical->link.lcp.auth_ineed = 0;
567  if (Enabled(bundle, OPT_UTMP))
568    physical_Login(authp->physical, authp->in.name);
569
570  if (authp->physical->link.lcp.auth_iwait == 0)
571    /*
572     * Either I didn't need to authenticate, or I've already been
573     * told that I got the answer right.
574     */
575    datalink_AuthOk(authp->physical->dl);
576}
577
578static void
579chap_Failure(struct authinfo *authp)
580{
581#ifndef NODES
582  char buf[1024], *ptr;
583#endif
584  const char *msg;
585
586#ifndef NORADIUS
587  struct bundle *bundle = authp->physical->link.lcp.fsm.bundle;
588  if (*bundle->radius.cfg.file && bundle->radius.errstr)
589    msg = bundle->radius.errstr;
590  else
591#endif
592#ifndef NODES
593  if (authp->physical->link.lcp.want_authtype == 0x80) {
594    sprintf(buf, "E=691 R=1 M=Invalid!");
595    msg = buf;
596  } else if (authp->physical->link.lcp.want_authtype == 0x81) {
597    int i;
598
599    ptr = buf;
600    ptr += sprintf(buf, "E=691 R=0 C=");
601    for (i=0; i<16; i++)
602      ptr += sprintf(ptr, "%02X", *(auth2chap(authp)->challenge.local+1+i));
603
604    sprintf(ptr, " V=3 M=Invalid!");
605    msg = buf;
606  } else
607#endif
608    msg = "Invalid!!";
609
610  ChapOutput(authp->physical, CHAP_FAILURE, authp->id, msg, strlen(msg) + 1,
611             NULL);
612  datalink_AuthNotOk(authp->physical->dl);
613}
614
615static int
616chap_Cmp(u_char type, char *myans, int mylen, char *hisans, int hislen
617#ifndef NODES
618         , int lm
619#endif
620        )
621{
622  if (mylen != hislen)
623    return 0;
624#ifndef NODES
625  else if (type == 0x80) {
626    int off = lm ? 0 : 24;
627
628    if (memcmp(myans + off, hisans + off, 24))
629      return 0;
630  }
631#endif
632  else if (memcmp(myans, hisans, mylen))
633    return 0;
634
635  return 1;
636}
637
638#ifndef NODES
639static int
640chap_HaveAnotherGo(struct chap *chap)
641{
642  if (++chap->peertries < 3) {
643    /* Give the peer another shot */
644    *chap->challenge.local = '\0';
645    chap_Challenge(&chap->auth);
646    return 1;
647  }
648
649  return 0;
650}
651#endif
652
653void
654chap_Init(struct chap *chap, struct physical *p)
655{
656  chap->desc.type = CHAP_DESCRIPTOR;
657  chap->desc.UpdateSet = chap_UpdateSet;
658  chap->desc.IsSet = chap_IsSet;
659  chap->desc.Read = chap_Read;
660  chap->desc.Write = chap_Write;
661  chap->child.pid = 0;
662  chap->child.fd = -1;
663  auth_Init(&chap->auth, p, chap_Challenge, chap_Success, chap_Failure);
664  *chap->challenge.local = *chap->challenge.peer = '\0';
665#ifndef NODES
666  chap->NTRespSent = 0;
667  chap->peertries = 0;
668#endif
669}
670
671void
672chap_ReInit(struct chap *chap)
673{
674  chap_Cleanup(chap, SIGTERM);
675}
676
677struct mbuf *
678chap_Input(struct bundle *bundle, struct link *l, struct mbuf *bp)
679{
680  struct physical *p = link2physical(l);
681  struct chap *chap = &p->dl->chap;
682  char *name, *key, *ans;
683  int len, nlen;
684  u_char alen;
685#ifndef NODES
686  int lanman;
687#endif
688
689  if (p == NULL) {
690    log_Printf(LogERROR, "chap_Input: Not a physical link - dropped\n");
691    m_freem(bp);
692    return NULL;
693  }
694
695  if (bundle_Phase(bundle) != PHASE_NETWORK &&
696      bundle_Phase(bundle) != PHASE_AUTHENTICATE) {
697    log_Printf(LogPHASE, "Unexpected chap input - dropped !\n");
698    m_freem(bp);
699    return NULL;
700  }
701
702  m_settype(bp, MB_CHAPIN);
703  if ((bp = auth_ReadHeader(&chap->auth, bp)) == NULL &&
704      ntohs(chap->auth.in.hdr.length) == 0)
705    log_Printf(LogWARN, "Chap Input: Truncated header !\n");
706  else if (chap->auth.in.hdr.code == 0 || chap->auth.in.hdr.code > MAXCHAPCODE)
707    log_Printf(LogPHASE, "Chap Input: %d: Bad CHAP code !\n",
708               chap->auth.in.hdr.code);
709  else {
710    len = m_length(bp);
711    ans = NULL;
712
713    if (chap->auth.in.hdr.code != CHAP_CHALLENGE &&
714        chap->auth.id != chap->auth.in.hdr.id &&
715        Enabled(bundle, OPT_IDCHECK)) {
716      /* Wrong conversation dude ! */
717      log_Printf(LogPHASE, "Chap Input: %s dropped (got id %d, not %d)\n",
718                 chapcodes[chap->auth.in.hdr.code], chap->auth.in.hdr.id,
719                 chap->auth.id);
720      m_freem(bp);
721      return NULL;
722    }
723    chap->auth.id = chap->auth.in.hdr.id;	/* We respond with this id */
724
725#ifndef NODES
726    lanman = 0;
727#endif
728    switch (chap->auth.in.hdr.code) {
729      case CHAP_CHALLENGE:
730        bp = mbuf_Read(bp, &alen, 1);
731        len -= alen + 1;
732        if (len < 0) {
733          log_Printf(LogERROR, "Chap Input: Truncated challenge !\n");
734          m_freem(bp);
735          return NULL;
736        }
737        *chap->challenge.peer = alen;
738        bp = mbuf_Read(bp, chap->challenge.peer + 1, alen);
739        bp = auth_ReadName(&chap->auth, bp, len);
740#ifndef NODES
741        lanman = p->link.lcp.his_authtype == 0x80 &&
742                 ((chap->NTRespSent && IsAccepted(p->link.lcp.cfg.chap80lm)) ||
743                  !IsAccepted(p->link.lcp.cfg.chap80nt));
744
745        /* Generate local challenge value */
746        chap_ChallengeInit(&chap->auth);
747#endif
748        break;
749
750      case CHAP_RESPONSE:
751        auth_StopTimer(&chap->auth);
752        bp = mbuf_Read(bp, &alen, 1);
753        len -= alen + 1;
754        if (len < 0) {
755          log_Printf(LogERROR, "Chap Input: Truncated response !\n");
756          m_freem(bp);
757          return NULL;
758        }
759        if ((ans = malloc(alen + 2)) == NULL) {
760          log_Printf(LogERROR, "Chap Input: Out of memory !\n");
761          m_freem(bp);
762          return NULL;
763        }
764        *ans = chap->auth.id;
765        bp = mbuf_Read(bp, ans + 1, alen);
766        if (p->link.lcp.want_authtype == 0x81 && ans[alen] != '\0') {
767          log_Printf(LogWARN, "%s: Compensating for corrupt (Win98/WinME?) "
768                     "CHAP81 RESPONSE\n", l->name);
769          ans[alen] = '\0';
770        }
771        ans[alen+1] = '\0';
772        bp = auth_ReadName(&chap->auth, bp, len);
773#ifndef NODES
774        lanman = p->link.lcp.want_authtype == 0x80 &&
775                 alen == 49 && ans[alen] == 0;
776#endif
777        break;
778
779      case CHAP_SUCCESS:
780      case CHAP_FAILURE:
781        /* chap->auth.in.name is already set up at CHALLENGE time */
782        if ((ans = malloc(len + 1)) == NULL) {
783          log_Printf(LogERROR, "Chap Input: Out of memory !\n");
784          m_freem(bp);
785          return NULL;
786        }
787        bp = mbuf_Read(bp, ans, len);
788        ans[len] = '\0';
789        break;
790    }
791
792    switch (chap->auth.in.hdr.code) {
793      case CHAP_CHALLENGE:
794      case CHAP_RESPONSE:
795        if (*chap->auth.in.name)
796          log_Printf(LogPHASE, "Chap Input: %s (%d bytes from %s%s)\n",
797                     chapcodes[chap->auth.in.hdr.code], alen,
798                     chap->auth.in.name,
799#ifndef NODES
800                     lanman && chap->auth.in.hdr.code == CHAP_RESPONSE ?
801                     " - lanman" :
802#endif
803                     "");
804        else
805          log_Printf(LogPHASE, "Chap Input: %s (%d bytes%s)\n",
806                     chapcodes[chap->auth.in.hdr.code], alen,
807#ifndef NODES
808                     lanman && chap->auth.in.hdr.code == CHAP_RESPONSE ?
809                     " - lanman" :
810#endif
811                     "");
812        break;
813
814      case CHAP_SUCCESS:
815      case CHAP_FAILURE:
816        if (*ans)
817          log_Printf(LogPHASE, "Chap Input: %s (%s)\n",
818                     chapcodes[chap->auth.in.hdr.code], ans);
819        else
820          log_Printf(LogPHASE, "Chap Input: %s\n",
821                     chapcodes[chap->auth.in.hdr.code]);
822        break;
823    }
824
825    switch (chap->auth.in.hdr.code) {
826      case CHAP_CHALLENGE:
827        if (*bundle->cfg.auth.key == '!' && bundle->cfg.auth.key[1] != '!')
828          chap_StartChild(chap, bundle->cfg.auth.key + 1,
829                          bundle->cfg.auth.name);
830        else
831          chap_Respond(chap, bundle->cfg.auth.name, bundle->cfg.auth.key +
832                       (*bundle->cfg.auth.key == '!' ? 1 : 0),
833                       p->link.lcp.his_authtype
834#ifndef NODES
835                       , lanman
836#endif
837                      );
838        break;
839
840      case CHAP_RESPONSE:
841        name = chap->auth.in.name;
842        nlen = strlen(name);
843#ifndef NORADIUS
844        if (*bundle->radius.cfg.file)
845          radius_Authenticate(&bundle->radius, &chap->auth,
846                              chap->auth.in.name, ans, alen + 1,
847                              chap->challenge.local + 1,
848                              *chap->challenge.local);
849        else
850#endif
851        {
852          key = auth_GetSecret(bundle, name, nlen, p);
853          if (key) {
854            char *myans;
855#ifndef NODES
856            if (p->link.lcp.want_authtype == 0x80 &&
857                lanman && !IsEnabled(p->link.lcp.cfg.chap80lm)) {
858              log_Printf(LogPHASE, "Auth failure: LANMan not enabled\n");
859              if (chap_HaveAnotherGo(chap))
860                break;
861              key = NULL;
862            } else if (p->link.lcp.want_authtype == 0x80 &&
863                !lanman && !IsEnabled(p->link.lcp.cfg.chap80nt)) {
864              log_Printf(LogPHASE, "Auth failure: mschap not enabled\n");
865              if (chap_HaveAnotherGo(chap))
866                break;
867              key = NULL;
868            } else if (p->link.lcp.want_authtype == 0x81 &&
869                !IsEnabled(p->link.lcp.cfg.chap81)) {
870              log_Printf(LogPHASE, "Auth failure: CHAP81 not enabled\n");
871              key = NULL;
872            } else
873#endif
874            {
875#ifndef NODES
876              /* Get peer's challenge */
877              if (p->link.lcp.want_authtype == 0x81) {
878                chap->challenge.peer[0] = CHAP81_CHALLENGE_LEN;
879                memcpy(chap->challenge.peer + 1, ans + 1, CHAP81_CHALLENGE_LEN);
880              }
881#endif
882
883              myans = chap_BuildAnswer(name, key, chap->auth.id,
884                                       chap->challenge.local,
885                                       p->link.lcp.want_authtype
886#ifndef NODES
887                                       , chap->challenge.peer,
888                                       chap->authresponse, lanman);
889              MPPE_IsServer = 1;		/* XXX Global ! */
890#else
891                                      );
892#endif
893              if (myans == NULL)
894                key = NULL;
895              else {
896                if (!chap_Cmp(p->link.lcp.want_authtype, myans + 1, *myans,
897                              ans + 1, alen
898#ifndef NODES
899                              , lanman
900#endif
901                             ))
902                  key = NULL;
903                free(myans);
904              }
905            }
906          }
907
908          if (key)
909            chap_Success(&chap->auth);
910          else
911            chap_Failure(&chap->auth);
912        }
913
914        break;
915
916      case CHAP_SUCCESS:
917        if (p->link.lcp.auth_iwait == PROTO_CHAP) {
918          p->link.lcp.auth_iwait = 0;
919          if (p->link.lcp.auth_ineed == 0) {
920#ifndef NODES
921            if (p->link.lcp.his_authtype == 0x81) {
922              if (strncmp(ans, chap->authresponse, 42)) {
923                datalink_AuthNotOk(p->dl);
924	        log_Printf(LogWARN, "CHAP81: AuthenticatorResponse: (%.42s)"
925                           " != ans: (%.42s)\n", chap->authresponse, ans);
926
927              } else {
928                /* Successful login */
929                MPPE_MasterKeyValid = 1;		/* XXX Global ! */
930                datalink_AuthOk(p->dl);
931              }
932            } else
933#endif
934            /*
935             * We've succeeded in our ``login''
936             * If we're not expecting  the peer to authenticate (or he already
937             * has), proceed to network phase.
938             */
939            datalink_AuthOk(p->dl);
940          }
941        }
942        break;
943
944      case CHAP_FAILURE:
945        datalink_AuthNotOk(p->dl);
946        break;
947    }
948    free(ans);
949  }
950
951  m_freem(bp);
952  return NULL;
953}
954