chap.c revision 43888
1/*
2 *			PPP CHAP Module
3 *
4 *	    Written by Toshiharu OHNO (tony-o@iij.ad.jp)
5 *
6 *   Copyright (C) 1993, Internet Initiative Japan, Inc. All rights reserverd.
7 *
8 * Redistribution and use in source and binary forms are permitted
9 * provided that the above copyright notice and this paragraph are
10 * duplicated in all such forms and that any documentation,
11 * advertising materials, and other materials related to such
12 * distribution and use acknowledge that the software was developed
13 * by the Internet Initiative Japan, Inc.  The name of the
14 * IIJ may not be used to endorse or promote products derived
15 * from this software without specific prior written permission.
16 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
17 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
18 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
19 *
20 * $Id: chap.c,v 1.42 1999/02/07 13:56:29 brian Exp $
21 *
22 *	TODO:
23 */
24#include <sys/param.h>
25#include <netinet/in.h>
26#include <netinet/in_systm.h>
27#include <netinet/ip.h>
28#include <sys/un.h>
29
30#include <errno.h>
31#include <fcntl.h>
32#ifdef HAVE_DES
33#include <md4.h>
34#include <string.h>
35#endif
36#include <md5.h>
37#include <paths.h>
38#include <signal.h>
39#include <stdlib.h>
40#include <sys/wait.h>
41#include <termios.h>
42#include <unistd.h>
43
44#include "mbuf.h"
45#include "log.h"
46#include "defs.h"
47#include "timer.h"
48#include "fsm.h"
49#include "lcpproto.h"
50#include "lcp.h"
51#include "lqr.h"
52#include "hdlc.h"
53#include "auth.h"
54#include "async.h"
55#include "throughput.h"
56#include "descriptor.h"
57#include "chap.h"
58#include "iplist.h"
59#include "slcompress.h"
60#include "ipcp.h"
61#include "filter.h"
62#include "ccp.h"
63#include "link.h"
64#include "physical.h"
65#include "mp.h"
66#ifndef NORADIUS
67#include "radius.h"
68#endif
69#include "bundle.h"
70#include "chat.h"
71#include "cbcp.h"
72#include "command.h"
73#include "datalink.h"
74#ifdef HAVE_DES
75#include "chap_ms.h"
76#endif
77
78static const char *chapcodes[] = {
79  "???", "CHALLENGE", "RESPONSE", "SUCCESS", "FAILURE"
80};
81#define MAXCHAPCODE (sizeof chapcodes / sizeof chapcodes[0] - 1)
82
83static void
84ChapOutput(struct physical *physical, u_int code, u_int id,
85	   const u_char *ptr, int count, const char *text)
86{
87  int plen;
88  struct fsmheader lh;
89  struct mbuf *bp;
90
91  plen = sizeof(struct fsmheader) + count;
92  lh.code = code;
93  lh.id = id;
94  lh.length = htons(plen);
95  bp = mbuf_Alloc(plen, MB_FSM);
96  memcpy(MBUF_CTOP(bp), &lh, sizeof(struct fsmheader));
97  if (count)
98    memcpy(MBUF_CTOP(bp) + sizeof(struct fsmheader), ptr, count);
99  log_DumpBp(LogDEBUG, "ChapOutput", bp);
100  if (text == NULL)
101    log_Printf(LogPHASE, "Chap Output: %s\n", chapcodes[code]);
102  else
103    log_Printf(LogPHASE, "Chap Output: %s (%s)\n", chapcodes[code], text);
104  hdlc_Output(&physical->link, PRI_LINK, PROTO_CHAP, bp);
105}
106
107static char *
108chap_BuildAnswer(char *name, char *key, u_char id, char *challenge, int MSChap)
109{
110  char *result, *digest;
111  size_t nlen, klen;
112
113  nlen = strlen(name);
114  klen = strlen(key);
115
116#ifdef HAVE_DES
117  if (MSChap) {
118    char expkey[AUTHLEN << 2];
119    MD4_CTX MD4context;
120    int f;
121
122    if ((result = malloc(1 + nlen + MS_CHAP_RESPONSE_LEN)) == NULL)
123      return result;
124
125    digest = result;				/* this is the response */
126    *digest++ = MS_CHAP_RESPONSE_LEN;		/* 49 */
127    memset(digest, '\0', 24);
128    digest += 24;
129
130    for (f = klen; f; f--) {
131      expkey[2*f-2] = key[f-1];
132      expkey[2*f-1] = 0;
133    }
134
135    /*
136     *           -----------
137     * answer = | k\0e\0y\0 |
138     *           -----------
139     */
140    MD4Init(&MD4context);
141    MD4Update(&MD4context, expkey, klen << 1);
142    MD4Final(digest, &MD4context);
143    memcpy(digest + 25, name, nlen);
144
145    /*
146     * ``result'' is:
147     *           ---- --------- -------------------- ------
148     * result = | 49 | 24 * \0 | digest (pad to 25) | name |
149     *           ---- --------- -------------------- ------
150     */
151    chap_MS(digest, challenge + 1, *challenge);
152
153    /*
154     *           ---- --------- ---------------- --- ----------
155     * result = | 49 | 24 * \0 | 24 byte digest | 1 | authname |
156     *           ---- --------- ---------------- --- ----------
157     */
158  } else
159#endif
160  if ((result = malloc(nlen + 17)) != NULL) {
161    /* Normal MD5 stuff */
162    MD5_CTX MD5context;
163
164    digest = result;
165    *digest++ = 16;				/* value size */
166
167    MD5Init(&MD5context);
168    MD5Update(&MD5context, &id, 1);
169    MD5Update(&MD5context, key, klen);
170    MD5Update(&MD5context, challenge + 1, *challenge);
171    MD5Final(digest, &MD5context);
172
173    memcpy(digest + 16, name, nlen);
174    /*
175     *           ---- -------- ------
176     * result = | 16 | digest | name |
177     *           ---- -------- ------
178     */
179  }
180
181  return result;
182}
183
184static void
185chap_StartChild(struct chap *chap, char *prog, const char *name)
186{
187  char *argv[MAXARGS], *nargv[MAXARGS];
188  int argc, fd;
189  int in[2], out[2];
190
191  if (chap->child.fd != -1) {
192    log_Printf(LogWARN, "Chap: %s: Program already running\n", prog);
193    return;
194  }
195
196  if (pipe(in) == -1) {
197    log_Printf(LogERROR, "Chap: pipe: %s\n", strerror(errno));
198    return;
199  }
200
201  if (pipe(out) == -1) {
202    log_Printf(LogERROR, "Chap: pipe: %s\n", strerror(errno));
203    close(in[0]);
204    close(in[1]);
205    return;
206  }
207
208  switch ((chap->child.pid = fork())) {
209    case -1:
210      log_Printf(LogERROR, "Chap: fork: %s\n", strerror(errno));
211      close(in[0]);
212      close(in[1]);
213      close(out[0]);
214      close(out[1]);
215      chap->child.pid = 0;
216      return;
217
218    case 0:
219      timer_TermService();
220      close(in[1]);
221      close(out[0]);
222      if (out[1] == STDIN_FILENO) {
223        fd = dup(out[1]);
224        close(out[1]);
225        out[1] = fd;
226      }
227      dup2(in[0], STDIN_FILENO);
228      dup2(out[1], STDOUT_FILENO);
229      if ((fd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
230        log_Printf(LogALERT, "Chap: Failed to open %s: %s\n",
231                  _PATH_DEVNULL, strerror(errno));
232        exit(1);
233      }
234      dup2(fd, STDERR_FILENO);
235      fcntl(3, F_SETFD, 1);		/* Set close-on-exec flag */
236
237      setuid(geteuid());
238      argc = command_Interpret(prog, strlen(prog), argv);
239      command_Expand(nargv, argc, (char const *const *)argv,
240                     chap->auth.physical->dl->bundle, 0);
241      execvp(nargv[0], nargv);
242
243      log_Printf(LogWARN, "exec() of %s failed: %s\n",
244                nargv[0], strerror(errno));
245      exit(255);
246
247    default:
248      close(in[0]);
249      close(out[1]);
250      chap->child.fd = out[0];
251      chap->child.buf.len = 0;
252      write(in[1], chap->auth.in.name, strlen(chap->auth.in.name));
253      write(in[1], "\n", 1);
254      write(in[1], chap->challenge + 1, *chap->challenge);
255      write(in[1], "\n", 1);
256      write(in[1], name, strlen(name));
257      write(in[1], "\n", 1);
258      close(in[1]);
259      break;
260  }
261}
262
263static void
264chap_Cleanup(struct chap *chap, int sig)
265{
266  if (chap->child.pid) {
267    int status;
268
269    close(chap->child.fd);
270    chap->child.fd = -1;
271    if (sig)
272      kill(chap->child.pid, SIGTERM);
273    chap->child.pid = 0;
274    chap->child.buf.len = 0;
275
276    if (wait(&status) == -1)
277      log_Printf(LogERROR, "Chap: wait: %s\n", strerror(errno));
278    else if (WIFSIGNALED(status))
279      log_Printf(LogWARN, "Chap: Child received signal %d\n", WTERMSIG(status));
280    else if (WIFEXITED(status) && WEXITSTATUS(status))
281      log_Printf(LogERROR, "Chap: Child exited %d\n", WEXITSTATUS(status));
282  }
283  *chap->challenge = 0;
284}
285
286static void
287chap_SendResponse(struct chap *chap, char *name, char *key)
288{
289  char *ans;
290
291  ans = chap_BuildAnswer(name, key, chap->auth.id, chap->challenge, 0);
292
293  if (ans) {
294    ChapOutput(chap->auth.physical, CHAP_RESPONSE, chap->auth.id,
295               ans, *ans + 1 + strlen(name), name);
296    free(ans);
297  } else
298    ChapOutput(chap->auth.physical, CHAP_FAILURE, chap->auth.id,
299               "Out of memory!", 14, NULL);
300}
301
302static int
303chap_UpdateSet(struct descriptor *d, fd_set *r, fd_set *w, fd_set *e, int *n)
304{
305  struct chap *chap = descriptor2chap(d);
306
307  if (r && chap && chap->child.fd != -1) {
308    FD_SET(chap->child.fd, r);
309    if (*n < chap->child.fd + 1)
310      *n = chap->child.fd + 1;
311    log_Printf(LogTIMER, "Chap: fdset(r) %d\n", chap->child.fd);
312    return 1;
313  }
314
315  return 0;
316}
317
318static int
319chap_IsSet(struct descriptor *d, const fd_set *fdset)
320{
321  struct chap *chap = descriptor2chap(d);
322
323  return chap && chap->child.fd != -1 && FD_ISSET(chap->child.fd, fdset);
324}
325
326static void
327chap_Read(struct descriptor *d, struct bundle *bundle, const fd_set *fdset)
328{
329  struct chap *chap = descriptor2chap(d);
330  int got;
331
332  got = read(chap->child.fd, chap->child.buf.ptr + chap->child.buf.len,
333             sizeof chap->child.buf.ptr - chap->child.buf.len - 1);
334  if (got == -1) {
335    log_Printf(LogERROR, "Chap: Read: %s\n", strerror(errno));
336    chap_Cleanup(chap, SIGTERM);
337  } else if (got == 0) {
338    log_Printf(LogWARN, "Chap: Read: Child terminated connection\n");
339    chap_Cleanup(chap, SIGTERM);
340  } else {
341    char *name, *key, *end;
342
343    chap->child.buf.len += got;
344    chap->child.buf.ptr[chap->child.buf.len] = '\0';
345    name = chap->child.buf.ptr;
346    name += strspn(name, " \t");
347    if ((key = strchr(name, '\n')) == NULL)
348      end = NULL;
349    else
350      end = strchr(++key, '\n');
351
352    if (end == NULL) {
353      if (chap->child.buf.len == sizeof chap->child.buf.ptr - 1) {
354        log_Printf(LogWARN, "Chap: Read: Input buffer overflow\n");
355        chap_Cleanup(chap, SIGTERM);
356      }
357    } else {
358      while (end >= name && strchr(" \t\r\n", *end))
359        *end-- = '\0';
360      end = key - 1;
361      while (end >= name && strchr(" \t\r\n", *end))
362        *end-- = '\0';
363      key += strspn(key, " \t");
364
365      chap_SendResponse(chap, name, key);
366      chap_Cleanup(chap, 0);
367    }
368  }
369}
370
371static int
372chap_Write(struct descriptor *d, struct bundle *bundle, const fd_set *fdset)
373{
374  /* We never want to write here ! */
375  log_Printf(LogALERT, "chap_Write: Internal error: Bad call !\n");
376  return 0;
377}
378
379static void
380chap_Challenge(struct authinfo *authp)
381{
382  struct chap *chap = auth2chap(authp);
383  int len, i;
384  char *cp;
385
386  len = strlen(authp->physical->dl->bundle->cfg.auth.name);
387
388  if (!*chap->challenge) {
389    randinit();
390    cp = chap->challenge;
391
392#ifndef NORADIUS
393    if (*authp->physical->dl->bundle->radius.cfg.file) {
394      /* For radius, our challenge is 16 readable NUL terminated bytes :*/
395      *cp++ = 16;
396      for (i = 0; i < 16; i++)
397        *cp++ = (random() % 10) + '0';
398    } else
399#endif
400    {
401      *cp++ = random() % (CHAPCHALLENGELEN-16) + 16;
402      for (i = 0; i < *chap->challenge; i++)
403        *cp++ = random() & 0xff;
404    }
405    memcpy(cp, authp->physical->dl->bundle->cfg.auth.name, len);
406  }
407  ChapOutput(authp->physical, CHAP_CHALLENGE, authp->id, chap->challenge,
408	     1 + *chap->challenge + len, NULL);
409}
410
411static void
412chap_Success(struct authinfo *authp)
413{
414  datalink_GotAuthname(authp->physical->dl, authp->in.name);
415  ChapOutput(authp->physical, CHAP_SUCCESS, authp->id, "Welcome!!", 10, NULL);
416  authp->physical->link.lcp.auth_ineed = 0;
417  if (Enabled(authp->physical->dl->bundle, OPT_UTMP))
418    physical_Login(authp->physical, authp->in.name);
419
420  if (authp->physical->link.lcp.auth_iwait == 0)
421    /*
422     * Either I didn't need to authenticate, or I've already been
423     * told that I got the answer right.
424     */
425    datalink_AuthOk(authp->physical->dl);
426}
427
428static void
429chap_Failure(struct authinfo *authp)
430{
431  ChapOutput(authp->physical, CHAP_FAILURE, authp->id, "Invalid!!", 9, NULL);
432  datalink_AuthNotOk(authp->physical->dl);
433}
434
435void
436chap_Init(struct chap *chap, struct physical *p)
437{
438  chap->desc.type = CHAP_DESCRIPTOR;
439  chap->desc.UpdateSet = chap_UpdateSet;
440  chap->desc.IsSet = chap_IsSet;
441  chap->desc.Read = chap_Read;
442  chap->desc.Write = chap_Write;
443  chap->child.pid = 0;
444  chap->child.fd = -1;
445  auth_Init(&chap->auth, p, chap_Challenge, chap_Success, chap_Failure);
446  *chap->challenge = 0;
447  chap->using_MSChap = 0;
448}
449
450void
451chap_ReInit(struct chap *chap)
452{
453  chap_Cleanup(chap, SIGTERM);
454}
455
456void
457chap_Input(struct physical *p, struct mbuf *bp)
458{
459  struct chap *chap = &p->dl->chap;
460  char *name, *key, *ans, *myans;
461  int len, nlen;
462  u_char alen;
463
464  if ((bp = auth_ReadHeader(&chap->auth, bp)) == NULL)
465    log_Printf(LogERROR, "Chap Input: Truncated header !\n");
466  else if (chap->auth.in.hdr.code == 0 || chap->auth.in.hdr.code > MAXCHAPCODE)
467    log_Printf(LogPHASE, "Chap Input: %d: Bad CHAP code !\n",
468               chap->auth.in.hdr.code);
469  else {
470    len = mbuf_Length(bp);
471    ans = NULL;
472
473    if (chap->auth.in.hdr.code != CHAP_CHALLENGE &&
474        chap->auth.id != chap->auth.in.hdr.id &&
475        Enabled(p->dl->bundle, OPT_IDCHECK)) {
476      /* Wrong conversation dude ! */
477      log_Printf(LogPHASE, "Chap Input: %s dropped (got id %d, not %d)\n",
478                 chapcodes[chap->auth.in.hdr.code], chap->auth.in.hdr.id,
479                 chap->auth.id);
480      mbuf_Free(bp);
481      return;
482    }
483    chap->auth.id = chap->auth.in.hdr.id;	/* We respond with this id */
484
485    switch (chap->auth.in.hdr.code) {
486      case CHAP_CHALLENGE:
487        bp = mbuf_Read(bp, chap->challenge, 1);
488        len -= *chap->challenge + 1;
489        if (len < 0) {
490          log_Printf(LogERROR, "Chap Input: Truncated challenge !\n");
491          mbuf_Free(bp);
492          return;
493        }
494        bp = mbuf_Read(bp, chap->challenge + 1, *chap->challenge);
495        bp = auth_ReadName(&chap->auth, bp, len);
496        break;
497
498      case CHAP_RESPONSE:
499        auth_StopTimer(&chap->auth);
500        bp = mbuf_Read(bp, &alen, 1);
501        len -= alen + 1;
502        if (len < 0) {
503          log_Printf(LogERROR, "Chap Input: Truncated response !\n");
504          mbuf_Free(bp);
505          return;
506        }
507        if ((ans = malloc(alen + 2)) == NULL) {
508          log_Printf(LogERROR, "Chap Input: Out of memory !\n");
509          mbuf_Free(bp);
510          return;
511        }
512        *ans = chap->auth.id;
513        bp = mbuf_Read(bp, ans + 1, alen);
514        ans[alen+1] = '\0';
515        bp = auth_ReadName(&chap->auth, bp, len);
516        break;
517
518      case CHAP_SUCCESS:
519      case CHAP_FAILURE:
520        /* chap->auth.in.name is already set up at CHALLENGE time */
521        if ((ans = malloc(len + 1)) == NULL) {
522          log_Printf(LogERROR, "Chap Input: Out of memory !\n");
523          mbuf_Free(bp);
524          return;
525        }
526        bp = mbuf_Read(bp, ans, len);
527        ans[len] = '\0';
528        break;
529    }
530
531    switch (chap->auth.in.hdr.code) {
532      case CHAP_CHALLENGE:
533      case CHAP_RESPONSE:
534        if (*chap->auth.in.name)
535          log_Printf(LogPHASE, "Chap Input: %s (from %s)\n",
536                     chapcodes[chap->auth.in.hdr.code], chap->auth.in.name);
537        else
538          log_Printf(LogPHASE, "Chap Input: %s\n",
539                     chapcodes[chap->auth.in.hdr.code]);
540        break;
541
542      case CHAP_SUCCESS:
543      case CHAP_FAILURE:
544        if (*ans)
545          log_Printf(LogPHASE, "Chap Input: %s (%s)\n",
546                     chapcodes[chap->auth.in.hdr.code], ans);
547        else
548          log_Printf(LogPHASE, "Chap Input: %s\n",
549                     chapcodes[chap->auth.in.hdr.code]);
550        break;
551    }
552
553    switch (chap->auth.in.hdr.code) {
554      case CHAP_CHALLENGE:
555        if (*p->dl->bundle->cfg.auth.key == '!')
556          chap_StartChild(chap, p->dl->bundle->cfg.auth.key + 1,
557                          p->dl->bundle->cfg.auth.name);
558        else
559          chap_SendResponse(chap, p->dl->bundle->cfg.auth.name,
560                            p->dl->bundle->cfg.auth.key);
561        break;
562
563      case CHAP_RESPONSE:
564        name = chap->auth.in.name;
565        nlen = strlen(name);
566#ifndef NORADIUS
567        if (*p->dl->bundle->radius.cfg.file) {
568          chap->challenge[*chap->challenge+1] = '\0';
569          radius_Authenticate(&p->dl->bundle->radius, &chap->auth,
570                              chap->auth.in.name, ans, chap->challenge + 1);
571        } else
572#endif
573        {
574          key = auth_GetSecret(p->dl->bundle, name, nlen, p);
575          if (key) {
576            myans = chap_BuildAnswer(name, key, chap->auth.id, chap->challenge,
577                                     chap->using_MSChap);
578            if (myans == NULL)
579              key = NULL;
580            else {
581              if (*myans != alen || memcmp(myans + 1, ans + 1, *myans))
582                key = NULL;
583              free(myans);
584            }
585          }
586
587          if (key)
588            chap_Success(&chap->auth);
589          else
590            chap_Failure(&chap->auth);
591        }
592
593        break;
594
595      case CHAP_SUCCESS:
596        if (p->link.lcp.auth_iwait == PROTO_CHAP) {
597          p->link.lcp.auth_iwait = 0;
598          if (p->link.lcp.auth_ineed == 0)
599            /*
600             * We've succeeded in our ``login''
601             * If we're not expecting  the peer to authenticate (or he already
602             * has), proceed to network phase.
603             */
604            datalink_AuthOk(p->dl);
605        }
606        break;
607
608      case CHAP_FAILURE:
609        datalink_AuthNotOk(p->dl);
610        break;
611    }
612    free(ans);
613  }
614
615  mbuf_Free(bp);
616}
617