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