chap.c revision 98311
18281Sjkh/*-
28281Sjkh * Copyright (c) 1996 - 2001 Brian Somers <brian@Awfulhak.org>
38281Sjkh *          based on work by Toshiharu OHNO <tony-o@iij.ad.jp>
48281Sjkh *                           Internet Initiative Japan, Inc (IIJ)
58281Sjkh * All rights reserved.
68281Sjkh *
78281Sjkh * Redistribution and use in source and binary forms, with or without
88281Sjkh * modification, are permitted provided that the following conditions
98281Sjkh * are met:
108281Sjkh * 1. Redistributions of source code must retain the above copyright
118281Sjkh *    notice, this list of conditions and the following disclaimer.
128281Sjkh * 2. Redistributions in binary form must reproduce the above copyright
138281Sjkh *    notice, this list of conditions and the following disclaimer in the
148281Sjkh *    documentation and/or other materials provided with the distribution.
158281Sjkh *
168281Sjkh * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
178281Sjkh * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
188281Sjkh * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
198281Sjkh * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
208281Sjkh * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
218281Sjkh * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
228281Sjkh * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
238281Sjkh * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
248281Sjkh * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
258281Sjkh * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
268281Sjkh * SUCH DAMAGE.
278281Sjkh *
288281Sjkh * $FreeBSD: head/usr.sbin/ppp/chap.c 98311 2002-06-17 01:12:38Z brian $
298281Sjkh */
308281Sjkh
318281Sjkh#include <sys/param.h>
328281Sjkh#include <netinet/in.h>
338281Sjkh#include <netinet/in_systm.h>
348281Sjkh#include <netinet/ip.h>
358281Sjkh#include <sys/socket.h>
368281Sjkh#include <sys/un.h>
378281Sjkh
388281Sjkh#include <errno.h>
398281Sjkh#include <fcntl.h>
408281Sjkh#ifndef NODES
418281Sjkh#include <md4.h>
428281Sjkh#endif
438281Sjkh#include <md5.h>
448281Sjkh#include <paths.h>
458281Sjkh#include <signal.h>
468281Sjkh#include <stdio.h>
478281Sjkh#include <stdlib.h>
488281Sjkh#include <string.h>
498281Sjkh#include <sys/wait.h>
508281Sjkh#include <termios.h>
518281Sjkh#include <unistd.h>
528281Sjkh
538281Sjkh#include "layer.h"
548281Sjkh#include "mbuf.h"
558281Sjkh#include "log.h"
568281Sjkh#include "defs.h"
578281Sjkh#include "timer.h"
588281Sjkh#include "fsm.h"
598281Sjkh#include "proto.h"
608281Sjkh#include "lqr.h"
618281Sjkh#include "hdlc.h"
628281Sjkh#include "lcp.h"
638281Sjkh#include "auth.h"
648281Sjkh#include "async.h"
658281Sjkh#include "throughput.h"
668281Sjkh#include "descriptor.h"
678281Sjkh#include "chap.h"
688281Sjkh#include "iplist.h"
698281Sjkh#include "slcompress.h"
708281Sjkh#include "ncpaddr.h"
718281Sjkh#include "ipcp.h"
728281Sjkh#include "filter.h"
738281Sjkh#include "ccp.h"
748281Sjkh#include "link.h"
758281Sjkh#include "physical.h"
768281Sjkh#include "mp.h"
778281Sjkh#ifndef NORADIUS
788281Sjkh#include "radius.h"
798281Sjkh#endif
808281Sjkh#include "ipv6cp.h"
818281Sjkh#include "ncp.h"
828281Sjkh#include "bundle.h"
838281Sjkh#include "chat.h"
848281Sjkh#include "cbcp.h"
858281Sjkh#include "command.h"
868281Sjkh#include "datalink.h"
878281Sjkh#ifndef NODES
888281Sjkh#include "chap_ms.h"
898281Sjkh#include "mppe.h"
908281Sjkh#endif
918281Sjkh#include "id.h"
928281Sjkh
938281Sjkhstatic const char * const chapcodes[] = {
948281Sjkh  "???", "CHALLENGE", "RESPONSE", "SUCCESS", "FAILURE"
958281Sjkh};
968281Sjkh#define MAXCHAPCODE (sizeof chapcodes / sizeof chapcodes[0] - 1)
978281Sjkh
988281Sjkhstatic void
998281SjkhChapOutput(struct physical *physical, u_int code, u_int id,
1008281Sjkh	   const u_char *ptr, int count, const char *text)
1018281Sjkh{
1028281Sjkh  int plen;
1038281Sjkh  struct fsmheader lh;
1048281Sjkh  struct mbuf *bp;
1058281Sjkh
1068281Sjkh  plen = sizeof(struct fsmheader) + count;
1078281Sjkh  lh.code = code;
1088281Sjkh  lh.id = id;
1098281Sjkh  lh.length = htons(plen);
1108281Sjkh  bp = m_get(plen, MB_CHAPOUT);
1118281Sjkh  memcpy(MBUF_CTOP(bp), &lh, sizeof(struct fsmheader));
1128281Sjkh  if (count)
1138281Sjkh    memcpy(MBUF_CTOP(bp) + sizeof(struct fsmheader), ptr, count);
1148281Sjkh  log_DumpBp(LogDEBUG, "ChapOutput", bp);
1158281Sjkh  if (text == NULL)
1168281Sjkh    log_Printf(LogPHASE, "Chap Output: %s\n", chapcodes[code]);
1178281Sjkh  else
1188281Sjkh    log_Printf(LogPHASE, "Chap Output: %s (%s)\n", chapcodes[code], text);
1198281Sjkh  link_PushPacket(&physical->link, bp, physical->dl->bundle,
1208281Sjkh                  LINK_QUEUES(&physical->link) - 1, PROTO_CHAP);
1218281Sjkh}
1228281Sjkh
1238281Sjkhstatic char *
1248281Sjkhchap_BuildAnswer(char *name, char *key, u_char id, char *challenge, u_char type
1258281Sjkh#ifndef NODES
1268281Sjkh                 , char *peerchallenge, char *authresponse, int lanman
1278281Sjkh#endif
1288281Sjkh                )
1298281Sjkh{
1308281Sjkh  char *result, *digest;
1318281Sjkh  size_t nlen, klen;
1328281Sjkh
1338281Sjkh  nlen = strlen(name);
1348281Sjkh  klen = strlen(key);
1358281Sjkh
1368281Sjkh#ifndef NODES
1378281Sjkh  if (type == 0x80) {
1388281Sjkh    char expkey[AUTHLEN << 2];
1398281Sjkh    MD4_CTX MD4context;
1408281Sjkh    int f;
1418281Sjkh
1428281Sjkh    if ((result = malloc(1 + nlen + MS_CHAP_RESPONSE_LEN)) == NULL)
1438281Sjkh      return result;
1448281Sjkh
1458281Sjkh    digest = result;					/* the response */
1468281Sjkh    *digest++ = MS_CHAP_RESPONSE_LEN;			/* 49 */
1478281Sjkh    memcpy(digest + MS_CHAP_RESPONSE_LEN, name, nlen);
1488281Sjkh    if (lanman) {
1498281Sjkh      memset(digest + 24, '\0', 25);
1508281Sjkh      mschap_LANMan(digest, challenge + 1, key);	/* LANMan response */
1518281Sjkh    } else {
1528281Sjkh      memset(digest, '\0', 25);
1538281Sjkh      digest += 24;
1548281Sjkh
1558281Sjkh      for (f = 0; f < klen; f++) {
1568281Sjkh        expkey[2*f] = key[f];
1578281Sjkh        expkey[2*f+1] = '\0';
1588281Sjkh      }
1598281Sjkh      /*
1608281Sjkh       *           -----------
1618281Sjkh       * expkey = | k\0e\0y\0 |
1628281Sjkh       *           -----------
1638281Sjkh       */
1648281Sjkh      MD4Init(&MD4context);
1658281Sjkh      MD4Update(&MD4context, expkey, klen << 1);
1668281Sjkh      MD4Final(digest, &MD4context);
1678281Sjkh
1688281Sjkh      /*
1698281Sjkh       *           ---- -------- ---------------- ------- ------
1708281Sjkh       * result = | 49 | LANMan | 16 byte digest | 9 * ? | name |
1718281Sjkh       *           ---- -------- ---------------- ------- ------
1728281Sjkh       */
1738281Sjkh      mschap_NT(digest, challenge + 1);
1748281Sjkh    }
1758281Sjkh    /*
1768281Sjkh     *           ---- -------- ------------- ----- ------
1778281Sjkh     *          |    |  struct MS_ChapResponse24  |      |
1788281Sjkh     * result = | 49 | LANMan  |  NT digest | 0/1 | name |
1798281Sjkh     *           ---- -------- ------------- ----- ------
1808281Sjkh     * where only one of LANMan & NT digest are set.
1818281Sjkh     */
1828281Sjkh  } else if (type == 0x81) {
1838281Sjkh    char expkey[AUTHLEN << 2];
1848281Sjkh    char pwdhash[CHAP81_HASH_LEN];
1858281Sjkh    char pwdhashhash[CHAP81_HASH_LEN];
1868281Sjkh    char *ntresponse;
1878281Sjkh    int f;
1888281Sjkh
1898281Sjkh    if ((result = malloc(1 + nlen + CHAP81_RESPONSE_LEN)) == NULL)
1908281Sjkh      return result;
1918281Sjkh
1928281Sjkh    memset(result, 0, 1 + nlen + CHAP81_RESPONSE_LEN);
1938281Sjkh
1948281Sjkh    digest = result;
1958281Sjkh    *digest++ = CHAP81_RESPONSE_LEN;		/* value size */
1968281Sjkh
1978281Sjkh    /* Copy our challenge */
1988281Sjkh    memcpy(digest, peerchallenge + 1, CHAP81_CHALLENGE_LEN);
1998281Sjkh
2008281Sjkh    /* Expand password to Unicode XXX */
2018281Sjkh    for (f = 0; f < klen; f++) {
2028281Sjkh      expkey[2*f] = key[f];
2038281Sjkh      expkey[2*f+1] = '\0';
2048281Sjkh    }
2058281Sjkh
2068281Sjkh    ntresponse = digest + CHAP81_NTRESPONSE_OFF;
2078281Sjkh
2088281Sjkh    /* Get some needed hashes */
2098281Sjkh    NtPasswordHash(expkey, klen * 2, pwdhash);
2108281Sjkh    HashNtPasswordHash(pwdhash, pwdhashhash);
2118281Sjkh
2128281Sjkh    /* Generate NTRESPONSE to respond on challenge call */
2138281Sjkh    GenerateNTResponse(challenge + 1, peerchallenge + 1, name, nlen,
2148281Sjkh                       expkey, klen * 2, ntresponse);
2158281Sjkh
2168281Sjkh    /* Generate MPPE MASTERKEY */
2178281Sjkh    GetMasterKey(pwdhashhash, ntresponse, MPPE_MasterKey);    /* XXX Global ! */
2188281Sjkh
2198281Sjkh    /* Generate AUTHRESPONSE to verify on auth success */
2208281Sjkh    GenerateAuthenticatorResponse(expkey, klen * 2, ntresponse,
2218281Sjkh                                  peerchallenge + 1, challenge + 1, name, nlen,
2228281Sjkh                                  authresponse);
2238281Sjkh
2248281Sjkh    authresponse[CHAP81_AUTHRESPONSE_LEN] = 0;
2258281Sjkh
2268281Sjkh    memcpy(digest + CHAP81_RESPONSE_LEN, name, nlen);
2278281Sjkh  } else
2288281Sjkh#endif
2298281Sjkh  if ((result = malloc(nlen + 17)) != NULL) {
2308281Sjkh    /* Normal MD5 stuff */
2318281Sjkh    MD5_CTX MD5context;
2328281Sjkh
2338281Sjkh    digest = result;
2348281Sjkh    *digest++ = 16;				/* value size */
2358281Sjkh
2368281Sjkh    MD5Init(&MD5context);
2378281Sjkh    MD5Update(&MD5context, &id, 1);
2388281Sjkh    MD5Update(&MD5context, key, klen);
2398281Sjkh    MD5Update(&MD5context, challenge + 1, *challenge);
2408281Sjkh    MD5Final(digest, &MD5context);
2418281Sjkh
2428281Sjkh    memcpy(digest + 16, name, nlen);
2438281Sjkh    /*
2448281Sjkh     *           ---- -------- ------
2458281Sjkh     * result = | 16 | digest | name |
2468281Sjkh     *           ---- -------- ------
2478281Sjkh     */
2488281Sjkh  }
2498281Sjkh
2508281Sjkh  return result;
2518281Sjkh}
2528281Sjkh
2538281Sjkhstatic void
2548281Sjkhchap_StartChild(struct chap *chap, char *prog, const char *name)
2558281Sjkh{
2568281Sjkh  char *argv[MAXARGS], *nargv[MAXARGS];
2578281Sjkh  int argc, fd;
2588281Sjkh  int in[2], out[2];
2598281Sjkh  pid_t pid;
2608281Sjkh
2618281Sjkh  if (chap->child.fd != -1) {
2628281Sjkh    log_Printf(LogWARN, "Chap: %s: Program already running\n", prog);
2638281Sjkh    return;
2648281Sjkh  }
2658281Sjkh
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#ifndef NORADIUS
553    if (*bundle->radius.cfg.file && bundle->radius.msrepstr)
554      msg = bundle->radius.msrepstr;
555    else
556#endif
557      msg = auth2chap(authp)->authresponse;
558    MPPE_MasterKeyValid = 1;		/* XXX Global ! */
559  } else
560#endif
561#ifndef NORADIUS
562  if (*bundle->radius.cfg.file && bundle->radius.repstr)
563    msg = bundle->radius.repstr;
564  else
565#endif
566    msg = "Welcome!!";
567
568  ChapOutput(authp->physical, CHAP_SUCCESS, authp->id, msg, strlen(msg),
569             NULL);
570
571  authp->physical->link.lcp.auth_ineed = 0;
572  if (Enabled(bundle, OPT_UTMP))
573    physical_Login(authp->physical, authp->in.name);
574
575  if (authp->physical->link.lcp.auth_iwait == 0)
576    /*
577     * Either I didn't need to authenticate, or I've already been
578     * told that I got the answer right.
579     */
580    datalink_AuthOk(authp->physical->dl);
581}
582
583static void
584chap_Failure(struct authinfo *authp)
585{
586#ifndef NODES
587  char buf[1024], *ptr;
588#endif
589  const char *msg;
590
591#ifndef NORADIUS
592  struct bundle *bundle = authp->physical->link.lcp.fsm.bundle;
593  if (*bundle->radius.cfg.file && bundle->radius.errstr)
594    msg = bundle->radius.errstr;
595  else
596#endif
597#ifndef NODES
598  if (authp->physical->link.lcp.want_authtype == 0x80) {
599    sprintf(buf, "E=691 R=1 M=Invalid!");
600    msg = buf;
601  } else if (authp->physical->link.lcp.want_authtype == 0x81) {
602    int i;
603
604    ptr = buf;
605    ptr += sprintf(buf, "E=691 R=0 C=");
606    for (i=0; i<16; i++)
607      ptr += sprintf(ptr, "%02X", *(auth2chap(authp)->challenge.local+1+i));
608
609    sprintf(ptr, " V=3 M=Invalid!");
610    msg = buf;
611  } else
612#endif
613    msg = "Invalid!!";
614
615  ChapOutput(authp->physical, CHAP_FAILURE, authp->id, msg, strlen(msg) + 1,
616             NULL);
617  datalink_AuthNotOk(authp->physical->dl);
618}
619
620static int
621chap_Cmp(u_char type, char *myans, int mylen, char *hisans, int hislen
622#ifndef NODES
623         , int lm
624#endif
625        )
626{
627  if (mylen != hislen)
628    return 0;
629#ifndef NODES
630  else if (type == 0x80) {
631    int off = lm ? 0 : 24;
632
633    if (memcmp(myans + off, hisans + off, 24))
634      return 0;
635  }
636#endif
637  else if (memcmp(myans, hisans, mylen))
638    return 0;
639
640  return 1;
641}
642
643#ifndef NODES
644static int
645chap_HaveAnotherGo(struct chap *chap)
646{
647  if (++chap->peertries < 3) {
648    /* Give the peer another shot */
649    *chap->challenge.local = '\0';
650    chap_Challenge(&chap->auth);
651    return 1;
652  }
653
654  return 0;
655}
656#endif
657
658void
659chap_Init(struct chap *chap, struct physical *p)
660{
661  chap->desc.type = CHAP_DESCRIPTOR;
662  chap->desc.UpdateSet = chap_UpdateSet;
663  chap->desc.IsSet = chap_IsSet;
664  chap->desc.Read = chap_Read;
665  chap->desc.Write = chap_Write;
666  chap->child.pid = 0;
667  chap->child.fd = -1;
668  auth_Init(&chap->auth, p, chap_Challenge, chap_Success, chap_Failure);
669  *chap->challenge.local = *chap->challenge.peer = '\0';
670#ifndef NODES
671  chap->NTRespSent = 0;
672  chap->peertries = 0;
673#endif
674}
675
676void
677chap_ReInit(struct chap *chap)
678{
679  chap_Cleanup(chap, SIGTERM);
680}
681
682struct mbuf *
683chap_Input(struct bundle *bundle, struct link *l, struct mbuf *bp)
684{
685  struct physical *p = link2physical(l);
686  struct chap *chap = &p->dl->chap;
687  char *name, *key, *ans;
688  int len, nlen;
689  u_char alen;
690#ifndef NODES
691  int lanman;
692#endif
693
694  if (p == NULL) {
695    log_Printf(LogERROR, "chap_Input: Not a physical link - dropped\n");
696    m_freem(bp);
697    return NULL;
698  }
699
700  if (bundle_Phase(bundle) != PHASE_NETWORK &&
701      bundle_Phase(bundle) != PHASE_AUTHENTICATE) {
702    log_Printf(LogPHASE, "Unexpected chap input - dropped !\n");
703    m_freem(bp);
704    return NULL;
705  }
706
707  m_settype(bp, MB_CHAPIN);
708  if ((bp = auth_ReadHeader(&chap->auth, bp)) == NULL &&
709      ntohs(chap->auth.in.hdr.length) == 0)
710    log_Printf(LogWARN, "Chap Input: Truncated header !\n");
711  else if (chap->auth.in.hdr.code == 0 || chap->auth.in.hdr.code > MAXCHAPCODE)
712    log_Printf(LogPHASE, "Chap Input: %d: Bad CHAP code !\n",
713               chap->auth.in.hdr.code);
714  else {
715    len = m_length(bp);
716    ans = NULL;
717
718    if (chap->auth.in.hdr.code != CHAP_CHALLENGE &&
719        chap->auth.id != chap->auth.in.hdr.id &&
720        Enabled(bundle, OPT_IDCHECK)) {
721      /* Wrong conversation dude ! */
722      log_Printf(LogPHASE, "Chap Input: %s dropped (got id %d, not %d)\n",
723                 chapcodes[chap->auth.in.hdr.code], chap->auth.in.hdr.id,
724                 chap->auth.id);
725      m_freem(bp);
726      return NULL;
727    }
728    chap->auth.id = chap->auth.in.hdr.id;	/* We respond with this id */
729
730#ifndef NODES
731    lanman = 0;
732#endif
733    switch (chap->auth.in.hdr.code) {
734      case CHAP_CHALLENGE:
735        bp = mbuf_Read(bp, &alen, 1);
736        len -= alen + 1;
737        if (len < 0) {
738          log_Printf(LogERROR, "Chap Input: Truncated challenge !\n");
739          m_freem(bp);
740          return NULL;
741        }
742        *chap->challenge.peer = alen;
743        bp = mbuf_Read(bp, chap->challenge.peer + 1, alen);
744        bp = auth_ReadName(&chap->auth, bp, len);
745#ifndef NODES
746        lanman = p->link.lcp.his_authtype == 0x80 &&
747                 ((chap->NTRespSent && IsAccepted(p->link.lcp.cfg.chap80lm)) ||
748                  !IsAccepted(p->link.lcp.cfg.chap80nt));
749
750        /* Generate local challenge value */
751        chap_ChallengeInit(&chap->auth);
752#endif
753        break;
754
755      case CHAP_RESPONSE:
756        auth_StopTimer(&chap->auth);
757        bp = mbuf_Read(bp, &alen, 1);
758        len -= alen + 1;
759        if (len < 0) {
760          log_Printf(LogERROR, "Chap Input: Truncated response !\n");
761          m_freem(bp);
762          return NULL;
763        }
764        if ((ans = malloc(alen + 1)) == NULL) {
765          log_Printf(LogERROR, "Chap Input: Out of memory !\n");
766          m_freem(bp);
767          return NULL;
768        }
769        *ans = chap->auth.id;
770        bp = mbuf_Read(bp, ans + 1, alen);
771        bp = auth_ReadName(&chap->auth, bp, len);
772#ifndef NODES
773        lanman = p->link.lcp.want_authtype == 0x80 &&
774                 alen == 49 && ans[alen] == 0;
775#endif
776        break;
777
778      case CHAP_SUCCESS:
779      case CHAP_FAILURE:
780        /* chap->auth.in.name is already set up at CHALLENGE time */
781        if ((ans = malloc(len + 1)) == NULL) {
782          log_Printf(LogERROR, "Chap Input: Out of memory !\n");
783          m_freem(bp);
784          return NULL;
785        }
786        bp = mbuf_Read(bp, ans, len);
787        ans[len] = '\0';
788        break;
789    }
790
791    switch (chap->auth.in.hdr.code) {
792      case CHAP_CHALLENGE:
793      case CHAP_RESPONSE:
794        if (*chap->auth.in.name)
795          log_Printf(LogPHASE, "Chap Input: %s (%d bytes from %s%s)\n",
796                     chapcodes[chap->auth.in.hdr.code], alen,
797                     chap->auth.in.name,
798#ifndef NODES
799                     lanman && chap->auth.in.hdr.code == CHAP_RESPONSE ?
800                     " - lanman" :
801#endif
802                     "");
803        else
804          log_Printf(LogPHASE, "Chap Input: %s (%d bytes%s)\n",
805                     chapcodes[chap->auth.in.hdr.code], alen,
806#ifndef NODES
807                     lanman && chap->auth.in.hdr.code == CHAP_RESPONSE ?
808                     " - lanman" :
809#endif
810                     "");
811        break;
812
813      case CHAP_SUCCESS:
814      case CHAP_FAILURE:
815        if (*ans)
816          log_Printf(LogPHASE, "Chap Input: %s (%s)\n",
817                     chapcodes[chap->auth.in.hdr.code], ans);
818        else
819          log_Printf(LogPHASE, "Chap Input: %s\n",
820                     chapcodes[chap->auth.in.hdr.code]);
821        break;
822    }
823
824    switch (chap->auth.in.hdr.code) {
825      case CHAP_CHALLENGE:
826        if (*bundle->cfg.auth.key == '!' && bundle->cfg.auth.key[1] != '!')
827          chap_StartChild(chap, bundle->cfg.auth.key + 1,
828                          bundle->cfg.auth.name);
829        else
830          chap_Respond(chap, bundle->cfg.auth.name, bundle->cfg.auth.key +
831                       (*bundle->cfg.auth.key == '!' ? 1 : 0),
832                       p->link.lcp.his_authtype
833#ifndef NODES
834                       , lanman
835#endif
836                      );
837        break;
838
839      case CHAP_RESPONSE:
840        name = chap->auth.in.name;
841        nlen = strlen(name);
842#ifndef NODES
843        if (p->link.lcp.want_authtype == 0x81) {
844          struct MSCHAPv2_resp *resp = (struct MSCHAPv2_resp *)(ans + 1);
845
846          chap->challenge.peer[0] = sizeof resp->PeerChallenge;
847          memcpy(chap->challenge.peer + 1, resp->PeerChallenge,
848                 sizeof resp->PeerChallenge);
849        }
850#endif
851
852#ifndef NORADIUS
853        if (*bundle->radius.cfg.file) {
854          if (!radius_Authenticate(&bundle->radius, &chap->auth,
855                                   chap->auth.in.name, ans, alen + 1,
856                                   chap->challenge.local + 1,
857                                   *chap->challenge.local))
858            chap_Failure(&chap->auth);
859        } else
860#endif
861        {
862          if (p->link.lcp.want_authtype == 0x81 && ans[alen] != '\0' &&
863              alen == sizeof(struct MSCHAPv2_resp)) {
864            struct MSCHAPv2_resp *resp = (struct MSCHAPv2_resp *)(ans + 1);
865
866            log_Printf(LogWARN, "%s: Compensating for corrupt (Win98/WinME?) "
867                       "CHAP81 RESPONSE\n", l->name);
868            resp->Flags = '\0';	/* rfc2759 says it *MUST* be zero */
869          }
870          key = auth_GetSecret(bundle, name, nlen, p);
871          if (key) {
872#ifndef NODES
873            if (p->link.lcp.want_authtype == 0x80 &&
874                lanman && !IsEnabled(p->link.lcp.cfg.chap80lm)) {
875              log_Printf(LogPHASE, "Auth failure: LANMan not enabled\n");
876              if (chap_HaveAnotherGo(chap))
877                break;
878              key = NULL;
879            } else if (p->link.lcp.want_authtype == 0x80 &&
880                !lanman && !IsEnabled(p->link.lcp.cfg.chap80nt)) {
881              log_Printf(LogPHASE, "Auth failure: mschap not enabled\n");
882              if (chap_HaveAnotherGo(chap))
883                break;
884              key = NULL;
885            } else if (p->link.lcp.want_authtype == 0x81 &&
886                !IsEnabled(p->link.lcp.cfg.chap81)) {
887              log_Printf(LogPHASE, "Auth failure: CHAP81 not enabled\n");
888              key = NULL;
889            } else
890#endif
891            {
892              char *myans = chap_BuildAnswer(name, key, chap->auth.id,
893                                             chap->challenge.local,
894                                       p->link.lcp.want_authtype
895#ifndef NODES
896                                       , chap->challenge.peer,
897                                       chap->authresponse, lanman);
898              MPPE_IsServer = 1;		/* XXX Global ! */
899#else
900                                      );
901#endif
902              if (myans == NULL)
903                key = NULL;
904              else {
905                if (!chap_Cmp(p->link.lcp.want_authtype, myans + 1, *myans,
906                              ans + 1, alen
907#ifndef NODES
908                              , lanman
909#endif
910                             ))
911                  key = NULL;
912                free(myans);
913              }
914            }
915          }
916
917          if (key)
918            chap_Success(&chap->auth);
919          else
920            chap_Failure(&chap->auth);
921        }
922
923        break;
924
925      case CHAP_SUCCESS:
926        if (p->link.lcp.auth_iwait == PROTO_CHAP) {
927          p->link.lcp.auth_iwait = 0;
928          if (p->link.lcp.auth_ineed == 0) {
929#ifndef NODES
930            if (p->link.lcp.his_authtype == 0x81) {
931              if (strncmp(ans, chap->authresponse, 42)) {
932                datalink_AuthNotOk(p->dl);
933	        log_Printf(LogWARN, "CHAP81: AuthenticatorResponse: (%.42s)"
934                           " != ans: (%.42s)\n", chap->authresponse, ans);
935
936              } else {
937                /* Successful login */
938                MPPE_MasterKeyValid = 1;		/* XXX Global ! */
939                datalink_AuthOk(p->dl);
940              }
941            } else
942#endif
943            /*
944             * We've succeeded in our ``login''
945             * If we're not expecting  the peer to authenticate (or he already
946             * has), proceed to network phase.
947             */
948            datalink_AuthOk(p->dl);
949          }
950        }
951        break;
952
953      case CHAP_FAILURE:
954        datalink_AuthNotOk(p->dl);
955        break;
956    }
957    free(ans);
958  }
959
960  m_freem(bp);
961  return NULL;
962}
963