]> git.ozlabs.org Git - ppp.git/blob - pppd/chap.c
fix typo reported by Thomas Klausner.
[ppp.git] / pppd / chap.c
1 /*
2  * chap.c - Challenge Handshake Authentication Protocol.
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. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in
15  *    the documentation and/or other materials provided with the
16  *    distribution.
17  *
18  * 3. The name(s) of the authors of this software must not be used to
19  *    endorse or promote products derived from this software without
20  *    prior written permission.
21  *
22  * 4. Redistributions of any form whatsoever must retain the following
23  *    acknowledgment:
24  *    "This product includes software developed by Paul Mackerras
25  *     <paulus@samba.org>".
26  *
27  * THE AUTHORS OF THIS SOFTWARE DISCLAIM ALL WARRANTIES WITH REGARD TO
28  * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
29  * AND FITNESS, IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
30  * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
31  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
32  * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
33  * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
34  *
35  * Copyright (c) 1991 Gregory M. Christy.
36  * All rights reserved.
37  *
38  * Redistribution and use in source and binary forms are permitted
39  * provided that the above copyright notice and this paragraph are
40  * duplicated in all such forms and that any documentation,
41  * advertising materials, and other materials related to such
42  * distribution and use acknowledge that the software was developed
43  * by Gregory M. Christy.  The name of the author may not be used to
44  * endorse or promote products derived from this software without
45  * specific prior written permission.
46  *
47  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
48  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
49  * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
50  */
51
52 #define RCSID   "$Id: chap.c,v 1.39 2003/02/16 22:32:14 paulus Exp $"
53
54 /*
55  * TODO:
56  */
57
58 #include <stdio.h>
59 #include <stdlib.h>
60 #include <string.h>
61 #include <sys/types.h>
62 #include <sys/time.h>
63
64 #include "pppd.h"
65 #include "chap.h"
66 #include "md5.h"
67 #ifdef CHAPMS
68 #include "chap_ms.h"
69 #endif
70
71 /* Hook for a plugin to say if we can possibly authenticate a peer using CHAP */
72 int (*chap_check_hook) __P((void)) = NULL;
73
74 /* Hook for a plugin to get the CHAP password for authenticating us */
75 int (*chap_passwd_hook) __P((char *user, char *passwd)) = NULL;
76
77 /* Hook for a plugin to validate CHAP challenge */
78 int (*chap_auth_hook) __P((char *user,
79                            u_char *remmd,
80                            int remmd_len,
81                            chap_state *cstate)) = NULL;
82
83 static const char rcsid[] = RCSID;
84
85 #ifdef CHAPMS
86 /* For MPPE debug */
87 /* Use "[]|}{?/><,`!2&&(" (sans quotes) for RFC 3079 MS-CHAPv2 test value */
88 static char *mschap_challenge = NULL;
89 /* Use "!@\#$%^&*()_+:3|~" (sans quotes, backslash is to escape #) for ... */
90 static char *mschap2_peer_challenge = NULL;
91 #endif
92
93 /*
94  * Command-line options.
95  */
96 static option_t chap_option_list[] = {
97     { "chap-restart", o_int, &chap[0].timeouttime,
98       "Set timeout for CHAP", OPT_PRIO },
99     { "chap-max-challenge", o_int, &chap[0].max_transmits,
100       "Set max #xmits for challenge", OPT_PRIO },
101     { "chap-interval", o_int, &chap[0].chal_interval,
102       "Set interval for rechallenge", OPT_PRIO },
103 #ifdef MSCHAP
104 #ifdef MSLANMAN
105     { "ms-lanman", o_bool, &ms_lanman,
106       "Use LanMan passwd when using MS-CHAP", 1 },
107 #endif
108 #ifdef DEBUGMPPEKEY
109     { "mschap-challenge", o_string, &mschap_challenge,
110       "specify CHAP challenge" },
111     { "mschap2-peer-challenge", o_string, &mschap2_peer_challenge,
112       "specify CHAP peer challenge" },
113 #endif
114 #endif
115     { NULL }
116 };
117
118 /*
119  * Protocol entry points.
120  */
121 static void ChapInit __P((int));
122 static void ChapLowerUp __P((int));
123 static void ChapLowerDown __P((int));
124 static void ChapInput __P((int, u_char *, int));
125 static void ChapProtocolReject __P((int));
126 static int  ChapPrintPkt __P((u_char *, int,
127                               void (*) __P((void *, char *, ...)), void *));
128
129 struct protent chap_protent = {
130     PPP_CHAP,
131     ChapInit,
132     ChapInput,
133     ChapProtocolReject,
134     ChapLowerUp,
135     ChapLowerDown,
136     NULL,
137     NULL,
138     ChapPrintPkt,
139     NULL,
140     1,
141     "CHAP",
142     NULL,
143     chap_option_list,
144     NULL,
145     NULL,
146     NULL
147 };
148
149 chap_state chap[NUM_PPP];               /* CHAP state; one for each unit */
150
151 static void ChapChallengeTimeout __P((void *));
152 static void ChapResponseTimeout __P((void *));
153 static void ChapReceiveChallenge __P((chap_state *, u_char *, int, int));
154 static void ChapRechallenge __P((void *));
155 static void ChapReceiveResponse __P((chap_state *, u_char *, int, int));
156 static void ChapReceiveSuccess __P((chap_state *, u_char *, int, int));
157 static void ChapReceiveFailure __P((chap_state *, u_char *, int, int));
158 static void ChapSendStatus __P((chap_state *, int));
159 static void ChapSendChallenge __P((chap_state *));
160 static void ChapSendResponse __P((chap_state *));
161 static void ChapGenChallenge __P((chap_state *));
162
163 extern double drand48 __P((void));
164 extern void srand48 __P((long));
165
166 /*
167  * ChapInit - Initialize a CHAP unit.
168  */
169 static void
170 ChapInit(unit)
171     int unit;
172 {
173     chap_state *cstate = &chap[unit];
174
175     BZERO(cstate, sizeof(*cstate));
176     cstate->unit = unit;
177     cstate->clientstate = CHAPCS_INITIAL;
178     cstate->serverstate = CHAPSS_INITIAL;
179     cstate->timeouttime = CHAP_DEFTIMEOUT;
180     cstate->max_transmits = CHAP_DEFTRANSMITS;
181     /* random number generator is initialized in magic_init */
182 }
183
184
185 /*
186  * ChapAuthWithPeer - Authenticate us with our peer (start client).
187  *
188  */
189 void
190 ChapAuthWithPeer(unit, our_name, digest)
191     int unit;
192     char *our_name;
193     int digest;
194 {
195     chap_state *cstate = &chap[unit];
196
197     cstate->resp_name = our_name;
198     cstate->resp_type = digest;
199
200     if (cstate->clientstate == CHAPCS_INITIAL ||
201         cstate->clientstate == CHAPCS_PENDING) {
202         /* lower layer isn't up - wait until later */
203         cstate->clientstate = CHAPCS_PENDING;
204         return;
205     }
206
207     /*
208      * We get here as a result of LCP coming up.
209      * So even if CHAP was open before, we will
210      * have to re-authenticate ourselves.
211      */
212     cstate->clientstate = CHAPCS_LISTEN;
213 }
214
215
216 /*
217  * ChapAuthPeer - Authenticate our peer (start server).
218  */
219 void
220 ChapAuthPeer(unit, our_name, digest)
221     int unit;
222     char *our_name;
223     int digest;
224 {
225     chap_state *cstate = &chap[unit];
226
227     cstate->chal_name = our_name;
228     cstate->chal_type = digest;
229
230     if (cstate->serverstate == CHAPSS_INITIAL ||
231         cstate->serverstate == CHAPSS_PENDING) {
232         /* lower layer isn't up - wait until later */
233         cstate->serverstate = CHAPSS_PENDING;
234         return;
235     }
236
237     ChapGenChallenge(cstate);
238     ChapSendChallenge(cstate);          /* crank it up dude! */
239     cstate->serverstate = CHAPSS_INITIAL_CHAL;
240 }
241
242
243 /*
244  * ChapChallengeTimeout - Timeout expired on sending challenge.
245  */
246 static void
247 ChapChallengeTimeout(arg)
248     void *arg;
249 {
250     chap_state *cstate = (chap_state *) arg;
251
252     /* if we aren't sending challenges, don't worry.  then again we */
253     /* probably shouldn't be here either */
254     if (cstate->serverstate != CHAPSS_INITIAL_CHAL &&
255         cstate->serverstate != CHAPSS_RECHALLENGE)
256         return;
257
258     if (cstate->chal_transmits >= cstate->max_transmits) {
259         /* give up on peer */
260         error("Peer failed to respond to CHAP challenge");
261         cstate->serverstate = CHAPSS_BADAUTH;
262         auth_peer_fail(cstate->unit, PPP_CHAP);
263         return;
264     }
265
266     ChapSendChallenge(cstate);          /* Re-send challenge */
267 }
268
269
270 /*
271  * ChapResponseTimeout - Timeout expired on sending response.
272  */
273 static void
274 ChapResponseTimeout(arg)
275     void *arg;
276 {
277     chap_state *cstate = (chap_state *) arg;
278
279     /* if we aren't sending a response, don't worry. */
280     if (cstate->clientstate != CHAPCS_RESPONSE)
281         return;
282
283     ChapSendResponse(cstate);           /* re-send response */
284 }
285
286
287 /*
288  * ChapRechallenge - Time to challenge the peer again.
289  */
290 static void
291 ChapRechallenge(arg)
292     void *arg;
293 {
294     chap_state *cstate = (chap_state *) arg;
295
296     /* if we aren't sending a response, don't worry. */
297     if (cstate->serverstate != CHAPSS_OPEN)
298         return;
299
300     ChapGenChallenge(cstate);
301     ChapSendChallenge(cstate);
302     cstate->serverstate = CHAPSS_RECHALLENGE;
303 }
304
305
306 /*
307  * ChapLowerUp - The lower layer is up.
308  *
309  * Start up if we have pending requests.
310  */
311 static void
312 ChapLowerUp(unit)
313     int unit;
314 {
315     chap_state *cstate = &chap[unit];
316
317     if (cstate->clientstate == CHAPCS_INITIAL)
318         cstate->clientstate = CHAPCS_CLOSED;
319     else if (cstate->clientstate == CHAPCS_PENDING)
320         cstate->clientstate = CHAPCS_LISTEN;
321
322     if (cstate->serverstate == CHAPSS_INITIAL)
323         cstate->serverstate = CHAPSS_CLOSED;
324     else if (cstate->serverstate == CHAPSS_PENDING) {
325         ChapGenChallenge(cstate);
326         ChapSendChallenge(cstate);
327         cstate->serverstate = CHAPSS_INITIAL_CHAL;
328     }
329 }
330
331
332 /*
333  * ChapLowerDown - The lower layer is down.
334  *
335  * Cancel all timeouts.
336  */
337 static void
338 ChapLowerDown(unit)
339     int unit;
340 {
341     chap_state *cstate = &chap[unit];
342
343     /* Timeout(s) pending?  Cancel if so. */
344     if (cstate->serverstate == CHAPSS_INITIAL_CHAL ||
345         cstate->serverstate == CHAPSS_RECHALLENGE)
346         UNTIMEOUT(ChapChallengeTimeout, cstate);
347     else if (cstate->serverstate == CHAPSS_OPEN
348              && cstate->chal_interval != 0)
349         UNTIMEOUT(ChapRechallenge, cstate);
350     if (cstate->clientstate == CHAPCS_RESPONSE)
351         UNTIMEOUT(ChapResponseTimeout, cstate);
352
353     cstate->clientstate = CHAPCS_INITIAL;
354     cstate->serverstate = CHAPSS_INITIAL;
355 }
356
357
358 /*
359  * ChapProtocolReject - Peer doesn't grok CHAP.
360  */
361 static void
362 ChapProtocolReject(unit)
363     int unit;
364 {
365     chap_state *cstate = &chap[unit];
366
367     if (cstate->serverstate != CHAPSS_INITIAL &&
368         cstate->serverstate != CHAPSS_CLOSED)
369         auth_peer_fail(unit, PPP_CHAP);
370     if (cstate->clientstate != CHAPCS_INITIAL &&
371         cstate->clientstate != CHAPCS_CLOSED)
372         auth_withpeer_fail(unit, PPP_CHAP);
373     ChapLowerDown(unit);                /* shutdown chap */
374 }
375
376
377 /*
378  * ChapInput - Input CHAP packet.
379  */
380 static void
381 ChapInput(unit, inpacket, packet_len)
382     int unit;
383     u_char *inpacket;
384     int packet_len;
385 {
386     chap_state *cstate = &chap[unit];
387     u_char *inp;
388     u_char code, id;
389     int len;
390
391     /*
392      * Parse header (code, id and length).
393      * If packet too short, drop it.
394      */
395     inp = inpacket;
396     if (packet_len < CHAP_HEADERLEN) {
397         CHAPDEBUG(("ChapInput: rcvd short header."));
398         return;
399     }
400     GETCHAR(code, inp);
401     GETCHAR(id, inp);
402     GETSHORT(len, inp);
403     if (len < CHAP_HEADERLEN) {
404         CHAPDEBUG(("ChapInput: rcvd illegal length."));
405         return;
406     }
407     if (len > packet_len) {
408         CHAPDEBUG(("ChapInput: rcvd short packet."));
409         return;
410     }
411     len -= CHAP_HEADERLEN;
412
413     /*
414      * Action depends on code (as in fact it usually does :-).
415      */
416     switch (code) {
417     case CHAP_CHALLENGE:
418         ChapReceiveChallenge(cstate, inp, id, len);
419         break;
420
421     case CHAP_RESPONSE:
422         ChapReceiveResponse(cstate, inp, id, len);
423         break;
424
425     case CHAP_FAILURE:
426         ChapReceiveFailure(cstate, inp, id, len);
427         break;
428
429     case CHAP_SUCCESS:
430         ChapReceiveSuccess(cstate, inp, id, len);
431         break;
432
433     default:                            /* Need code reject? */
434         warn("Unknown CHAP code (%d) received.", code);
435         break;
436     }
437 }
438
439
440 /*
441  * ChapReceiveChallenge - Receive Challenge and send Response.
442  */
443 static void
444 ChapReceiveChallenge(cstate, inp, id, len)
445     chap_state *cstate;
446     u_char *inp;
447     int id;
448     int len;
449 {
450     int rchallenge_len;
451     u_char *rchallenge;
452     int secret_len;
453     char secret[MAXSECRETLEN];
454     char rhostname[256];
455     MD5_CTX mdContext;
456     u_char hash[MD5_SIGNATURE_SIZE];
457
458     if (cstate->clientstate == CHAPCS_CLOSED ||
459         cstate->clientstate == CHAPCS_PENDING) {
460         CHAPDEBUG(("ChapReceiveChallenge: in state %d", cstate->clientstate));
461         return;
462     }
463
464     if (len < 2) {
465         CHAPDEBUG(("ChapReceiveChallenge: rcvd short packet."));
466         return;
467     }
468
469     GETCHAR(rchallenge_len, inp);
470     len -= sizeof (u_char) + rchallenge_len;    /* now name field length */
471     if (len < 0) {
472         CHAPDEBUG(("ChapReceiveChallenge: rcvd short packet."));
473         return;
474     }
475     rchallenge = inp;
476     INCPTR(rchallenge_len, inp);
477
478     /* Null terminate and clean remote name. */
479     slprintf(rhostname, sizeof(rhostname), "%.*v", len, inp);
480
481     /* Microsoft doesn't send their name back in the PPP packet */
482     if (explicit_remote || (remote_name[0] != 0 && rhostname[0] == 0)) {
483         strlcpy(rhostname, remote_name, sizeof(rhostname));
484         CHAPDEBUG(("ChapReceiveChallenge: using '%q' as remote name",
485                    rhostname));
486     }
487
488     /* get secret for authenticating ourselves with the specified host */
489     if (!get_secret(cstate->unit, cstate->resp_name, rhostname,
490                     secret, &secret_len, 0)) {
491         secret_len = 0;         /* assume null secret if can't find one */
492         warn("No CHAP secret found for authenticating us to %q", rhostname);
493     }
494
495     /* cancel response send timeout if necessary */
496     if (cstate->clientstate == CHAPCS_RESPONSE)
497         UNTIMEOUT(ChapResponseTimeout, cstate);
498
499     cstate->resp_id = id;
500     cstate->resp_transmits = 0;
501
502     /*  generate MD based on negotiated type */
503     switch (cstate->resp_type) {
504
505     case CHAP_DIGEST_MD5:
506         MD5Init(&mdContext);
507         MD5Update(&mdContext, &cstate->resp_id, 1);
508         MD5Update(&mdContext, secret, secret_len);
509         MD5Update(&mdContext, rchallenge, rchallenge_len);
510         MD5Final(hash, &mdContext);
511         BCOPY(hash, cstate->response, MD5_SIGNATURE_SIZE);
512         cstate->resp_length = MD5_SIGNATURE_SIZE;
513         break;
514
515 #ifdef CHAPMS
516     case CHAP_MICROSOFT:
517         ChapMS(cstate, rchallenge, secret, secret_len,
518                (MS_ChapResponse *) cstate->response);
519         break;
520
521     case CHAP_MICROSOFT_V2:
522         ChapMS2(cstate, rchallenge,
523                 mschap2_peer_challenge? mschap2_peer_challenge: NULL,
524                 cstate->resp_name, secret, secret_len,
525                 (MS_Chap2Response *) cstate->response, cstate->earesponse,
526                  MS_CHAP2_AUTHENTICATEE);
527         break;
528 #endif /* CHAPMS */
529
530     default:
531         CHAPDEBUG(("unknown digest type %d", cstate->resp_type));
532         return;
533     }
534
535     BZERO(secret, sizeof(secret));
536     ChapSendResponse(cstate);
537 }
538
539
540 /*
541  * ChapReceiveResponse - Receive and process response.
542  */
543 static void
544 ChapReceiveResponse(cstate, inp, id, len)
545     chap_state *cstate;
546     u_char *inp;
547     int id;
548     int len;
549 {
550     u_char *remmd, remmd_len;
551     int secret_len, old_state;
552     int code;
553     char rhostname[256];
554     MD5_CTX mdContext;
555     char secret[MAXSECRETLEN];
556     u_char hash[MD5_SIGNATURE_SIZE];
557
558     if (cstate->serverstate == CHAPSS_CLOSED ||
559         cstate->serverstate == CHAPSS_PENDING) {
560         CHAPDEBUG(("ChapReceiveResponse: in state %d", cstate->serverstate));
561         return;
562     }
563
564     if (id != cstate->chal_id)
565         return;                 /* doesn't match ID of last challenge */
566
567     /*
568      * If we have received a duplicate or bogus Response,
569      * we have to send the same answer (Success/Failure)
570      * as we did for the first Response we saw.
571      */
572     if (cstate->serverstate == CHAPSS_OPEN) {
573         ChapSendStatus(cstate, CHAP_SUCCESS);
574         return;
575     }
576     if (cstate->serverstate == CHAPSS_BADAUTH) {
577         ChapSendStatus(cstate, CHAP_FAILURE);
578         return;
579     }
580
581     if (len < 2) {
582         CHAPDEBUG(("ChapReceiveResponse: rcvd short packet."));
583         return;
584     }
585     GETCHAR(remmd_len, inp);            /* get length of MD */
586     remmd = inp;                        /* get pointer to MD */
587     INCPTR(remmd_len, inp);
588
589     len -= sizeof (u_char) + remmd_len;
590     if (len < 0) {
591         CHAPDEBUG(("ChapReceiveResponse: rcvd short packet."));
592         return;
593     }
594
595     UNTIMEOUT(ChapChallengeTimeout, cstate);
596
597     /* Null terminate and clean remote name. */
598     slprintf(rhostname, sizeof(rhostname), "%.*v", len, inp);
599
600 #ifdef CHAPMS
601     /* copy the flags into cstate for use elsewhere */
602     if (cstate->chal_type == CHAP_MICROSOFT_V2)
603         cstate->resp_flags = ((MS_Chap2Response *) remmd)->Flags[0];
604 #endif /* CHAPMS */
605     /*
606      * Get secret for authenticating them with us,
607      * do the hash ourselves, and compare the result.
608      */
609     code = CHAP_FAILURE;
610
611     /* If a plugin will verify the response, let the plugin do it. */
612     if (chap_auth_hook) {
613         code = (*chap_auth_hook) ( (explicit_remote ? remote_name : rhostname),
614                                    remmd, (int) remmd_len,
615                                    cstate );
616         /*
617          * Check remote number authorization.  A plugin may have filled in
618          * the remote number or added an allowed number, and rather than
619          * return an authenticate failure, is leaving it for us to verify.
620          */
621         if (code == CHAP_SUCCESS) {
622             if (!auth_number()) {
623                 /* We do not want to leak info about the chap result. */
624                 code = CHAP_FAILURE; /* XXX exit value will be "wrong" */
625                 warn("calling number %q is not authorized", remote_number);
626             }
627         }
628
629     } else {
630         if (!get_secret(cstate->unit, (explicit_remote? remote_name: rhostname),
631                         cstate->chal_name, secret, &secret_len, 1)) {
632             warn("No CHAP secret found for authenticating %q", rhostname);
633         } else {
634
635             /*  generate MD based on negotiated type */
636             switch (cstate->chal_type) {
637
638             case CHAP_DIGEST_MD5:
639                 if (remmd_len != MD5_SIGNATURE_SIZE)
640                     break;                      /* not even the right length */
641                 MD5Init(&mdContext);
642                 MD5Update(&mdContext, &cstate->chal_id, 1);
643                 MD5Update(&mdContext, secret, secret_len);
644                 MD5Update(&mdContext, cstate->challenge, cstate->chal_len);
645                 MD5Final(hash, &mdContext);
646
647                 /* compare MDs and send the appropriate status */
648                 if (memcmp(hash, remmd, MD5_SIGNATURE_SIZE) == 0)
649                     code = CHAP_SUCCESS;        /* they are the same! */
650                 break;
651
652 #ifdef CHAPMS
653             case CHAP_MICROSOFT:
654             {
655                 int response_offset, response_size;
656                 MS_ChapResponse *rmd = (MS_ChapResponse *) remmd;
657                 MS_ChapResponse md;
658
659                 if (remmd_len != MS_CHAP_RESPONSE_LEN)
660                     break;                      /* not even the right length */
661
662                 /* Determine which part of response to verify against */
663                 if (rmd->UseNT[0]) {
664                     response_offset = offsetof(MS_ChapResponse, NTResp);
665                     response_size = sizeof(rmd->NTResp);
666                 } else {
667 #ifdef MSLANMAN
668                     response_offset = offsetof(MS_ChapResponse, LANManResp);
669                     response_size = sizeof(rmd->LANManResp);
670 #else
671                     /* Should really propagate this into the error packet. */
672                     notice("Peer request for LANMAN auth not supported");
673                     break;
674 #endif /* MSLANMAN */
675                 }
676
677                 /* Generate the expected response. */
678                 ChapMS(cstate, cstate->challenge, secret, secret_len, &md);
679
680                 /* compare MDs and send the appropriate status */
681                 if (memcmp((u_char *) &md + response_offset,
682                            (u_char *) remmd + response_offset,
683                            response_size) == 0)
684                     code = CHAP_SUCCESS;        /* they are the same! */
685                 break;
686             }
687
688             case CHAP_MICROSOFT_V2:
689             {
690                 MS_Chap2Response *rmd = (MS_Chap2Response *) remmd;
691                 MS_Chap2Response md;
692
693                 if (remmd_len != MS_CHAP2_RESPONSE_LEN)
694                     break;                      /* not even the right length */
695
696                 /* Generate the expected response and our mutual auth. */
697                 ChapMS2(cstate, cstate->challenge, rmd->PeerChallenge,
698                         (explicit_remote? remote_name: rhostname),
699                         secret, secret_len, &md,
700                         cstate->saresponse, MS_CHAP2_AUTHENTICATOR);
701
702                 /* compare MDs and send the appropriate status */
703                 if (memcmp(md.NTResp, rmd->NTResp, sizeof(md.NTResp)) == 0)
704                     code = CHAP_SUCCESS;        /* yay! */
705                 break;
706             }
707 #endif /* CHAPMS */
708
709             default:
710                 CHAPDEBUG(("unknown digest type %d", cstate->chal_type));
711             }
712         }
713
714         BZERO(secret, sizeof(secret));
715     }
716     ChapSendStatus(cstate, code);
717
718     if (code == CHAP_SUCCESS) {
719         old_state = cstate->serverstate;
720         cstate->serverstate = CHAPSS_OPEN;
721         if (old_state == CHAPSS_INITIAL_CHAL) {
722             auth_peer_success(cstate->unit, PPP_CHAP, cstate->chal_type,
723                               rhostname, len);
724         }
725         if (cstate->chal_interval != 0)
726             TIMEOUT(ChapRechallenge, cstate, cstate->chal_interval);
727         notice("CHAP peer authentication succeeded for %q", rhostname);
728
729     } else {
730         warn("CHAP peer authentication failed for %q", rhostname);
731         cstate->serverstate = CHAPSS_BADAUTH;
732         auth_peer_fail(cstate->unit, PPP_CHAP);
733     }
734 }
735
736 /*
737  * ChapReceiveSuccess - Receive Success
738  */
739 static void
740 ChapReceiveSuccess(cstate, inp, id, len)
741     chap_state *cstate;
742     u_char *inp;
743     u_char id;
744     int len;
745 {
746
747     if (cstate->clientstate == CHAPCS_OPEN)
748         /* presumably an answer to a duplicate response */
749         return;
750
751     if (cstate->clientstate != CHAPCS_RESPONSE) {
752         /* don't know what this is */
753         CHAPDEBUG(("ChapReceiveSuccess: in state %d\n", cstate->clientstate));
754         return;
755     }
756
757     UNTIMEOUT(ChapResponseTimeout, cstate);
758
759 #ifdef CHAPMS
760     /*
761      * For MS-CHAPv2, we must verify that the peer knows our secret.
762      */
763     if (cstate->resp_type == CHAP_MICROSOFT_V2) {
764         if ((len >= MS_AUTH_RESPONSE_LENGTH + 2) && !strncmp(inp, "S=", 2)) {
765             inp += 2; len -= 2;
766             if (!memcmp(inp, cstate->earesponse, MS_AUTH_RESPONSE_LENGTH)) {
767                 /* Authenticator Response matches. */
768                 inp += MS_AUTH_RESPONSE_LENGTH; /* Eat it */
769                 len -= MS_AUTH_RESPONSE_LENGTH;
770                 if ((len >= 3) && !strncmp(inp, " M=", 3)) {
771                     inp += 3; len -= 3; /* Eat the delimiter */
772                 } else if (len) {
773                     /* Packet has extra text which does not begin " M=" */
774                     error("MS-CHAPv2 Success packet is badly formed.");
775                     auth_withpeer_fail(cstate->unit, PPP_CHAP);
776                 }
777             } else {
778                 /* Authenticator Response did not match expected. */
779                 error("MS-CHAPv2 mutual authentication failed.");
780                 auth_withpeer_fail(cstate->unit, PPP_CHAP);
781             }
782         } else {
783             /* Packet does not start with "S=" */
784             error("MS-CHAPv2 Success packet is badly formed.");
785             auth_withpeer_fail(cstate->unit, PPP_CHAP);
786         }
787     }
788 #endif
789
790     /*
791      * Print message.
792      */
793     if (len > 0)
794         PRINTMSG(inp, len);
795
796     cstate->clientstate = CHAPCS_OPEN;
797
798     notice("CHAP authentication succeeded");
799     auth_withpeer_success(cstate->unit, PPP_CHAP, cstate->resp_type);
800 }
801
802
803 /*
804  * ChapReceiveFailure - Receive failure.
805  */
806 static void
807 ChapReceiveFailure(cstate, inp, id, len)
808     chap_state *cstate;
809     u_char *inp;
810     u_char id;
811     int len;
812 {
813     u_char *msg;
814     u_char *p = inp;
815
816     if (cstate->clientstate != CHAPCS_RESPONSE) {
817         /* don't know what this is */
818         CHAPDEBUG(("ChapReceiveFailure: in state %d\n", cstate->clientstate));
819         return;
820     }
821
822 #ifdef CHAPMS
823     /* We want a null-terminated string for strxxx(). */
824     msg = malloc(len + 1);
825     if (!msg) {
826         p = NULL;
827         notice("Out of memory in ChapReceiveFailure");
828         goto print_msg;
829     }
830     BCOPY(inp, msg, len);
831     p = msg + len; *p = '\0'; p = msg;
832 #endif
833
834     UNTIMEOUT(ChapResponseTimeout, cstate);
835
836 #ifdef CHAPMS
837     if ((cstate->resp_type == CHAP_MICROSOFT_V2) ||
838         (cstate->resp_type == CHAP_MICROSOFT)) {
839         int error;
840
841         /*
842          * Deal with MS-CHAP formatted failure messages; just print the
843          * M=<message> part (if any).  For MS-CHAP we're not really supposed
844          * to use M=<message>, but it shouldn't hurt.  See ChapSendStatus().
845          */
846         if (!strncmp(p, "E=", 2))
847             error = (int) strtol(p, NULL, 10); /* Remember the error code. */
848         else
849             goto print_msg; /* Message is badly formatted. */
850
851         if (len && ((p = strstr(p, " M=")) != NULL)) {
852             /* M=<message> field found. */
853             p += 3;
854         } else {
855             /* No M=<message>; use the error code. */
856             switch(error) {
857             case MS_CHAP_ERROR_RESTRICTED_LOGON_HOURS:
858                 p = "E=646 Restricted logon hours";
859                 break;
860
861             case MS_CHAP_ERROR_ACCT_DISABLED:
862                 p = "E=647 Account disabled";
863                 break;
864
865             case MS_CHAP_ERROR_PASSWD_EXPIRED:
866                 p = "E=648 Password expired";
867                 break;
868
869             case MS_CHAP_ERROR_NO_DIALIN_PERMISSION:
870                 p = "E=649 No dialin permission";
871                 break;
872
873             case MS_CHAP_ERROR_AUTHENTICATION_FAILURE:
874                 p = "E=691 Authentication failure";
875                 break;
876
877             case MS_CHAP_ERROR_CHANGING_PASSWORD:
878                 /* Should never see this, we don't support Change Password. */
879                 p = "E=709 Error changing password";
880                 break;
881
882             default:
883                 free(msg);
884                 p = msg = malloc(len + 33);
885                 if (!msg) {
886                     novm("ChapReceiveFailure");
887                     goto print_msg;
888                 }
889                 slprintf(p, len + 33, "Unknown authentication failure: %.*s",
890                          len, inp);
891                 break;
892             }
893         }
894         len = strlen(p);
895     }
896 #endif
897
898     /*
899      * Print message.
900      */
901 print_msg:
902     if (len > 0 && p != NULL)
903         PRINTMSG(p, len);
904
905     error("CHAP authentication failed");
906     auth_withpeer_fail(cstate->unit, PPP_CHAP);
907 #ifdef CHAPMS
908     if (msg) free(msg);
909 #endif
910 }
911
912
913 /*
914  * ChapSendChallenge - Send an Authenticate challenge.
915  */
916 static void
917 ChapSendChallenge(cstate)
918     chap_state *cstate;
919 {
920     u_char *outp;
921     int chal_len, name_len;
922     int outlen;
923
924     chal_len = cstate->chal_len;
925     name_len = strlen(cstate->chal_name);
926     outlen = CHAP_HEADERLEN + sizeof (u_char) + chal_len + name_len;
927     outp = outpacket_buf;
928
929     MAKEHEADER(outp, PPP_CHAP);         /* paste in a CHAP header */
930
931     PUTCHAR(CHAP_CHALLENGE, outp);
932     PUTCHAR(cstate->chal_id, outp);
933     PUTSHORT(outlen, outp);
934
935     PUTCHAR(chal_len, outp);            /* put length of challenge */
936     BCOPY(cstate->challenge, outp, chal_len);
937     INCPTR(chal_len, outp);
938
939     BCOPY(cstate->chal_name, outp, name_len);   /* append hostname */
940
941     output(cstate->unit, outpacket_buf, outlen + PPP_HDRLEN);
942
943     TIMEOUT(ChapChallengeTimeout, cstate, cstate->timeouttime);
944     ++cstate->chal_transmits;
945 }
946
947
948 /*
949  * ChapSendStatus - Send a status response (ack or nak).
950  * See RFC 2433 and RFC 2759 for MS-CHAP and MS-CHAPv2 message formats.
951  */
952 static void
953 ChapSendStatus(cstate, code)
954     chap_state *cstate;
955     int code;
956 {
957     u_char *outp;
958     int i, outlen, msglen;
959     char msg[256];
960     char *p, *q;
961
962     p = msg;
963     q = p + sizeof(msg); /* points 1 byte past msg */
964
965     if (code == CHAP_SUCCESS) {
966 #ifdef CHAPMS
967         if (cstate->chal_type == CHAP_MICROSOFT_V2) {
968             /*
969              * Per RFC 2759, success message must be formatted as
970              *     "S=<auth_string> M=<message>"
971              * where
972              *     <auth_string> is the Authenticator Response (mutual auth)
973              *     <message> is a text message
974              *
975              * However, some versions of Windows (win98 tested) do not know
976              * about the M=<message> part (required per RFC 2759) and flag
977              * it as an error (reported incorrectly as an encryption error
978              * to the user).  Since the RFC requires it, and it can be
979              * useful information, we supply it if the peer is a conforming
980              * system.  Luckily (?), win98 sets the Flags field to 0x04
981              * (contrary to RFC requirements) so we can use that to
982              * distinguish between conforming and non-conforming systems.
983              *
984              * Special thanks to Alex Swiridov <say@real.kharkov.ua> for
985              * help debugging this.
986              */
987             slprintf(p, q - p, "S=");
988             p += 2;
989             slprintf(p, q - p, "%s", cstate->saresponse);
990             p += strlen(cstate->saresponse);
991             if (cstate->resp_flags != 0)
992                 goto msgdone;
993             slprintf(p, q - p, " M=");
994             p += 3;
995         }
996 #endif /* CHAPMS */
997
998         slprintf(p, q - p, "Welcome to %s.", hostname);
999     } else {
1000 #ifdef CHAPMS
1001         if ((cstate->chal_type == CHAP_MICROSOFT_V2) ||
1002             (cstate->chal_type == CHAP_MICROSOFT)) {
1003             /*
1004              * Failure message must be formatted as
1005              *     "E=e R=r C=c V=v M=m"
1006              * where
1007              *     e = error code (we use 691, ERROR_AUTHENTICATION_FAILURE)
1008              *     r = retry (we use 1, ok to retry)
1009              *     c = challenge to use for next response, we reuse previous
1010              *     v = Change Password version supported, we use 0
1011              *     m = text message
1012              *
1013              * The M=m part is only for MS-CHAPv2, but MS-CHAP should ignore
1014              * any extra text according to RFC 2433.  So we'll go the easy
1015              * (read: lazy) route and include it always.  Neither win2k nor
1016              * win98 (others untested) display the message to the user anyway.
1017              * They also both ignore the E=e code.
1018              *
1019              * Note that it's safe to reuse the same challenge as we don't
1020              * actually accept another response based on the error message
1021              * (and no clients try to resend a response anyway).
1022              *
1023              * Basically, this whole bit is useless code, even the small
1024              * implementation here is only because of overspecification.
1025              */
1026             slprintf(p, q - p, "E=691 R=1 C=");
1027             p += 12;
1028             for (i = 0; i < cstate->chal_len; i++)
1029                 sprintf(p + i * 2, "%02X", cstate->challenge[i]);
1030             p += cstate->chal_len * 2;
1031             slprintf(p, q - p, " V=0 M=");
1032             p += 7;
1033         }
1034 #endif /* CHAPMS */
1035
1036         slprintf(p, q - p, "I don't like you.  Go 'way.");
1037     }
1038 msgdone:
1039     msglen = strlen(msg);
1040
1041     outlen = CHAP_HEADERLEN + msglen;
1042     outp = outpacket_buf;
1043
1044     MAKEHEADER(outp, PPP_CHAP); /* paste in a header */
1045
1046     PUTCHAR(code, outp);
1047     PUTCHAR(cstate->chal_id, outp);
1048     PUTSHORT(outlen, outp);
1049     BCOPY(msg, outp, msglen);
1050     output(cstate->unit, outpacket_buf, outlen + PPP_HDRLEN);
1051 }
1052
1053 /*
1054  * ChapGenChallenge is used to generate a pseudo-random challenge string of
1055  * a pseudo-random length between min_len and max_len.  The challenge
1056  * string and its length are stored in *cstate, and various other fields of
1057  * *cstate are initialized.
1058  */
1059
1060 static void
1061 ChapGenChallenge(cstate)
1062     chap_state *cstate;
1063 {
1064     int chal_len = 0; /* Avoid compiler warning */
1065     u_char *ptr = cstate->challenge;
1066     int i;
1067
1068     switch (cstate->chal_type) {
1069     case CHAP_DIGEST_MD5:
1070         /*
1071          * pick a random challenge length between MIN_CHALLENGE_LENGTH and
1072          * MAX_CHALLENGE_LENGTH
1073          */
1074         chal_len = (unsigned) ((drand48() *
1075                                 (MAX_CHALLENGE_LENGTH - MIN_CHALLENGE_LENGTH)) +
1076                                 MIN_CHALLENGE_LENGTH);
1077         break;
1078
1079 #ifdef CHAPMS
1080     case CHAP_MICROSOFT:
1081         /* MS-CHAP is fixed to an 8 octet challenge. */
1082         chal_len = 8;
1083         break;
1084
1085     case CHAP_MICROSOFT_V2:
1086         /* MS-CHAPv2 is fixed to a 16 octet challenge. */
1087         chal_len = 16;
1088         break;
1089 #endif
1090     default:
1091         fatal("ChapGenChallenge: Unsupported challenge type %d",
1092               (int) cstate->chal_type);
1093         break;
1094     }
1095
1096     cstate->chal_len = chal_len;
1097     cstate->chal_id = ++cstate->id;
1098     cstate->chal_transmits = 0;
1099
1100 #ifdef CHAPMS
1101     if (mschap_challenge)
1102         for (i = 0; i < chal_len; i++)
1103             *ptr++ = mschap_challenge[i];
1104     else
1105 #endif
1106         /* generate a random string */
1107         for (i = 0; i < chal_len; i++)
1108             *ptr++ = (char) (drand48() * 0xff);
1109 }
1110
1111 /*
1112  * ChapSendResponse - send a response packet with values as specified
1113  * in *cstate.
1114  */
1115 /* ARGSUSED */
1116 static void
1117 ChapSendResponse(cstate)
1118     chap_state *cstate;
1119 {
1120     u_char *outp;
1121     int outlen, md_len, name_len;
1122
1123     md_len = cstate->resp_length;
1124     name_len = strlen(cstate->resp_name);
1125     outlen = CHAP_HEADERLEN + sizeof (u_char) + md_len + name_len;
1126     outp = outpacket_buf;
1127
1128     MAKEHEADER(outp, PPP_CHAP);
1129
1130     PUTCHAR(CHAP_RESPONSE, outp);       /* we are a response */
1131     PUTCHAR(cstate->resp_id, outp);     /* copy id from challenge packet */
1132     PUTSHORT(outlen, outp);             /* packet length */
1133
1134     PUTCHAR(md_len, outp);              /* length of MD */
1135     BCOPY(cstate->response, outp, md_len);      /* copy MD to buffer */
1136     INCPTR(md_len, outp);
1137
1138     BCOPY(cstate->resp_name, outp, name_len); /* append our name */
1139
1140     /* send the packet */
1141     output(cstate->unit, outpacket_buf, outlen + PPP_HDRLEN);
1142
1143     cstate->clientstate = CHAPCS_RESPONSE;
1144     TIMEOUT(ChapResponseTimeout, cstate, cstate->timeouttime);
1145     ++cstate->resp_transmits;
1146 }
1147
1148 /*
1149  * ChapPrintPkt - print the contents of a CHAP packet.
1150  */
1151 static char *ChapCodenames[] = {
1152     "Challenge", "Response", "Success", "Failure"
1153 };
1154
1155 static int
1156 ChapPrintPkt(p, plen, printer, arg)
1157     u_char *p;
1158     int plen;
1159     void (*printer) __P((void *, char *, ...));
1160     void *arg;
1161 {
1162     int code, id, len;
1163     int clen, nlen;
1164     u_char x;
1165
1166     if (plen < CHAP_HEADERLEN)
1167         return 0;
1168     GETCHAR(code, p);
1169     GETCHAR(id, p);
1170     GETSHORT(len, p);
1171     if (len < CHAP_HEADERLEN || len > plen)
1172         return 0;
1173
1174     if (code >= 1 && code <= sizeof(ChapCodenames) / sizeof(char *))
1175         printer(arg, " %s", ChapCodenames[code-1]);
1176     else
1177         printer(arg, " code=0x%x", code);
1178     printer(arg, " id=0x%x", id);
1179     len -= CHAP_HEADERLEN;
1180     switch (code) {
1181     case CHAP_CHALLENGE:
1182     case CHAP_RESPONSE:
1183         if (len < 1)
1184             break;
1185         clen = p[0];
1186         if (len < clen + 1)
1187             break;
1188         ++p;
1189         nlen = len - clen - 1;
1190         printer(arg, " <");
1191         for (; clen > 0; --clen) {
1192             GETCHAR(x, p);
1193             printer(arg, "%.2x", x);
1194         }
1195         printer(arg, ">, name = ");
1196         print_string((char *)p, nlen, printer, arg);
1197         break;
1198     case CHAP_FAILURE:
1199     case CHAP_SUCCESS:
1200         printer(arg, " ");
1201         print_string((char *)p, len, printer, arg);
1202         break;
1203     default:
1204         for (clen = len; clen > 0; --clen) {
1205             GETCHAR(x, p);
1206             printer(arg, " %.2x", x);
1207         }
1208     }
1209
1210     return len + CHAP_HEADERLEN;
1211 }