]> git.ozlabs.org Git - ppp.git/blob - pppd/chap.c
Patches from Frank Cusack:
[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.32 2002/05/21 17:26:49 dfs 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         cstate->resp_length = MS_CHAP_RESPONSE_LEN;
504         break;
505
506     case CHAP_MICROSOFT_V2:
507         ChapMS2(cstate, rchallenge,
508                 mschap2_peer_challenge? mschap2_peer_challenge: NULL,
509                 cstate->resp_name, secret, secret_len,
510                 (MS_Chap2Response *) cstate->response, cstate->earesponse,
511                  MS_CHAP2_AUTHENTICATEE);
512         cstate->resp_length = MS_CHAP2_RESPONSE_LEN;
513         break;
514 #endif /* CHAPMS */
515
516     default:
517         CHAPDEBUG(("unknown digest type %d", cstate->resp_type));
518         return;
519     }
520
521     BZERO(secret, sizeof(secret));
522     ChapSendResponse(cstate);
523 }
524
525
526 /*
527  * ChapReceiveResponse - Receive and process response.
528  */
529 static void
530 ChapReceiveResponse(cstate, inp, id, len)
531     chap_state *cstate;
532     u_char *inp;
533     int id;
534     int len;
535 {
536     u_char *remmd, remmd_len;
537     int secret_len, old_state;
538     int code;
539     char rhostname[256];
540     MD5_CTX mdContext;
541     char secret[MAXSECRETLEN];
542     u_char hash[MD5_SIGNATURE_SIZE];
543
544     if (cstate->serverstate == CHAPSS_CLOSED ||
545         cstate->serverstate == CHAPSS_PENDING) {
546         CHAPDEBUG(("ChapReceiveResponse: in state %d", cstate->serverstate));
547         return;
548     }
549
550     if (id != cstate->chal_id)
551         return;                 /* doesn't match ID of last challenge */
552
553     /*
554      * If we have received a duplicate or bogus Response,
555      * we have to send the same answer (Success/Failure)
556      * as we did for the first Response we saw.
557      */
558     if (cstate->serverstate == CHAPSS_OPEN) {
559         ChapSendStatus(cstate, CHAP_SUCCESS);
560         return;
561     }
562     if (cstate->serverstate == CHAPSS_BADAUTH) {
563         ChapSendStatus(cstate, CHAP_FAILURE);
564         return;
565     }
566
567     if (len < 2) {
568         CHAPDEBUG(("ChapReceiveResponse: rcvd short packet."));
569         return;
570     }
571     GETCHAR(remmd_len, inp);            /* get length of MD */
572     remmd = inp;                        /* get pointer to MD */
573     INCPTR(remmd_len, inp);
574
575     len -= sizeof (u_char) + remmd_len;
576     if (len < 0) {
577         CHAPDEBUG(("ChapReceiveResponse: rcvd short packet."));
578         return;
579     }
580
581     UNTIMEOUT(ChapChallengeTimeout, cstate);
582
583     if (len >= sizeof(rhostname))
584         len = sizeof(rhostname) - 1;
585     BCOPY(inp, rhostname, len);
586     rhostname[len] = '\000';
587
588 #ifdef CHAPMS
589     /* copy the flags into cstate for use elsewhere */
590     if (cstate->chal_type == CHAP_MICROSOFT_V2)
591         cstate->resp_flags = ((MS_Chap2Response *) remmd)->Flags[0];
592 #endif /* CHAPMS */
593     /*
594      * Get secret for authenticating them with us,
595      * do the hash ourselves, and compare the result.
596      */
597     code = CHAP_FAILURE;
598
599     /* If a plugin will verify the response, let the plugin do it. */
600     if (chap_auth_hook) {
601         code = (*chap_auth_hook) ( (explicit_remote ? remote_name : rhostname),
602                                    remmd, (int) remmd_len,
603                                    cstate );
604     } else {
605         if (!get_secret(cstate->unit, (explicit_remote? remote_name: rhostname),
606                         cstate->chal_name, secret, &secret_len, 1)) {
607             warn("No CHAP secret found for authenticating %q", rhostname);
608         } else {
609
610             /*  generate MD based on negotiated type */
611             switch (cstate->chal_type) {
612
613             case CHAP_DIGEST_MD5:
614                 if (remmd_len != MD5_SIGNATURE_SIZE)
615                     break;                      /* not even the right length */
616                 MD5Init(&mdContext);
617                 MD5Update(&mdContext, &cstate->chal_id, 1);
618                 MD5Update(&mdContext, secret, secret_len);
619                 MD5Update(&mdContext, cstate->challenge, cstate->chal_len);
620                 MD5Final(hash, &mdContext);
621
622                 /* compare MDs and send the appropriate status */
623                 if (memcmp(hash, remmd, MD5_SIGNATURE_SIZE) == 0)
624                     code = CHAP_SUCCESS;        /* they are the same! */
625                 break;
626
627 #ifdef CHAPMS
628             case CHAP_MICROSOFT:
629             {
630                 int response_offset, response_size;
631                 MS_ChapResponse *rmd = (MS_ChapResponse *) remmd;
632                 MS_ChapResponse md;
633
634                 if (remmd_len != MS_CHAP_RESPONSE_LEN)
635                     break;                      /* not even the right length */
636
637                 /* Determine which part of response to verify against */
638                 if (rmd->UseNT[0]) {
639                     response_offset = offsetof(MS_ChapResponse, NTResp);
640                     response_size = sizeof(rmd->NTResp);
641                 } else {
642 #ifdef MSLANMAN
643                     response_offset = offsetof(MS_ChapResponse, LANManResp);
644                     response_size = sizeof(rmd->LANManResp);
645 #else
646                     /* Should really propagate this into the error packet. */
647                     notice("Peer request for LANMAN auth not supported");
648                     break;
649 #endif /* MSLANMAN */
650                 }
651
652                 /* Generate the expected response. */
653                 ChapMS(cstate, cstate->challenge, secret, secret_len, &md);
654
655                 /* compare MDs and send the appropriate status */
656                 if (memcmp((u_char *) &md + response_offset,
657                            (u_char *) remmd + response_offset,
658                            response_size) == 0)
659                     code = CHAP_SUCCESS;        /* they are the same! */
660                 break;
661             }
662
663             case CHAP_MICROSOFT_V2:
664             {
665                 MS_Chap2Response *rmd = (MS_Chap2Response *) remmd;
666                 MS_Chap2Response md;
667
668                 if (remmd_len != MS_CHAP2_RESPONSE_LEN)
669                     break;                      /* not even the right length */
670
671                 /* Generate the expected response and our mutual auth. */
672                 ChapMS2(cstate, cstate->challenge, rmd->PeerChallenge,
673                         (explicit_remote? remote_name: rhostname),
674                         secret, secret_len, &md,
675                         cstate->saresponse, MS_CHAP2_AUTHENTICATOR);
676
677                 /* compare MDs and send the appropriate status */
678                 if (memcmp(md.NTResp, rmd->NTResp, sizeof(md.NTResp)) == 0)
679                     code = CHAP_SUCCESS;        /* yay! */
680                 break;
681             }
682 #endif /* CHAPMS */
683
684             default:
685                 CHAPDEBUG(("unknown digest type %d", cstate->chal_type));
686             }
687         }
688
689         BZERO(secret, sizeof(secret));
690     }
691     ChapSendStatus(cstate, code);
692
693     if (code == CHAP_SUCCESS) {
694         old_state = cstate->serverstate;
695         cstate->serverstate = CHAPSS_OPEN;
696         if (old_state == CHAPSS_INITIAL_CHAL) {
697             auth_peer_success(cstate->unit, PPP_CHAP, cstate->chal_type,
698                               rhostname, len);
699         }
700         if (cstate->chal_interval != 0)
701             TIMEOUT(ChapRechallenge, cstate, cstate->chal_interval);
702         notice("CHAP peer authentication succeeded for %q", rhostname);
703
704     } else {
705         error("CHAP peer authentication failed for remote host %q", rhostname);
706         cstate->serverstate = CHAPSS_BADAUTH;
707         auth_peer_fail(cstate->unit, PPP_CHAP);
708     }
709 }
710
711 /*
712  * ChapReceiveSuccess - Receive Success
713  */
714 static void
715 ChapReceiveSuccess(cstate, inp, id, len)
716     chap_state *cstate;
717     u_char *inp;
718     u_char id;
719     int len;
720 {
721
722     if (cstate->clientstate == CHAPCS_OPEN)
723         /* presumably an answer to a duplicate response */
724         return;
725
726     if (cstate->clientstate != CHAPCS_RESPONSE) {
727         /* don't know what this is */
728         CHAPDEBUG(("ChapReceiveSuccess: in state %d\n", cstate->clientstate));
729         return;
730     }
731
732     UNTIMEOUT(ChapResponseTimeout, cstate);
733
734 #ifdef CHAPMS
735     /*
736      * For MS-CHAPv2, we must verify that the peer knows our secret.
737      */
738     if (cstate->resp_type == CHAP_MICROSOFT_V2) {
739         if ((len >= MS_AUTH_RESPONSE_LENGTH + 2) && !strncmp(inp, "S=", 2)) {
740             inp += 2; len -= 2;
741             if (!memcmp(inp, cstate->earesponse, MS_AUTH_RESPONSE_LENGTH)) {
742                 /* Authenticator Response matches. */
743                 inp += MS_AUTH_RESPONSE_LENGTH; /* Eat it */
744                 len -= MS_AUTH_RESPONSE_LENGTH;
745                 if ((len >= 3) && !strncmp(inp, " M=", 3)) {
746                     inp += 3; len -= 3; /* Eat the delimiter */
747                 } else if (len) {
748                     /* Packet has extra text which does not begin " M=" */
749                     error("MS-CHAPv2 Success packet is badly formed.");
750                     auth_withpeer_fail(cstate->unit, PPP_CHAP);
751                 }
752             } else {
753                 /* Authenticator Response did not match expected. */
754                 error("MS-CHAPv2 mutual authentication failed.");
755                 auth_withpeer_fail(cstate->unit, PPP_CHAP);
756             }
757         } else {
758             /* Packet does not start with "S=" */
759             error("MS-CHAPv2 Success packet is badly formed.");
760             auth_withpeer_fail(cstate->unit, PPP_CHAP);
761         }
762     }
763 #endif
764
765     /*
766      * Print message.
767      */
768     if (len > 0)
769         PRINTMSG(inp, len);
770
771     cstate->clientstate = CHAPCS_OPEN;
772
773     auth_withpeer_success(cstate->unit, PPP_CHAP, cstate->resp_type);
774 }
775
776
777 /*
778  * ChapReceiveFailure - Receive failure.
779  */
780 static void
781 ChapReceiveFailure(cstate, inp, id, len)
782     chap_state *cstate;
783     u_char *inp;
784     u_char id;
785     int len;
786 {
787     u_char *msg;
788     u_char *p = inp;
789
790     if (cstate->clientstate != CHAPCS_RESPONSE) {
791         /* don't know what this is */
792         CHAPDEBUG(("ChapReceiveFailure: in state %d\n", cstate->clientstate));
793         return;
794     }
795
796 #ifdef CHAPMS
797     /* We want a null-terminated string for strxxx(). */
798     msg = malloc(len + 1);
799     if (!msg) {
800         p = NULL;
801         notice("Out of memory in ChapReceiveFailure");
802         goto print_msg;
803     }
804     BCOPY(inp, msg, len);
805     p = msg + len; *p = '\0'; p = msg;
806 #endif
807
808     UNTIMEOUT(ChapResponseTimeout, cstate);
809
810 #ifdef CHAPMS
811     if ((cstate->resp_type == CHAP_MICROSOFT_V2) ||
812         (cstate->resp_type == CHAP_MICROSOFT)) {
813         int error;
814
815         /*
816          * Deal with MS-CHAP formatted failure messages; just print the
817          * M=<message> part (if any).  For MS-CHAP we're not really supposed
818          * to use M=<message>, but it shouldn't hurt.  See ChapSendStatus().
819          */
820         if (!strncmp(p, "E=", 2))
821             error = (int) strtol(p, NULL, 10); /* Remember the error code. */
822         else
823             goto print_msg; /* Message is badly formatted. */
824
825         if (len && ((p = strstr(p, " M=")) != NULL)) {
826             /* M=<message> field found. */
827             p += 3;
828         } else {
829             /* No M=<message>; use the error code. */
830             switch(error) {
831             case MS_CHAP_ERROR_RESTRICTED_LOGON_HOURS:
832                 p = "E=646 Restricted logon hours";
833                 break;
834
835             case MS_CHAP_ERROR_ACCT_DISABLED:
836                 p = "E=647 Account disabled";
837                 break;
838
839             case MS_CHAP_ERROR_PASSWD_EXPIRED:
840                 p = "E=648 Password expired";
841                 break;
842
843             case MS_CHAP_ERROR_NO_DIALIN_PERMISSION:
844                 p = "E=649 No dialin permission";
845                 break;
846
847             case MS_CHAP_ERROR_AUTHENTICATION_FAILURE:
848                 p = "E=691 Authentication failure";
849                 break;
850
851             case MS_CHAP_ERROR_CHANGING_PASSWORD:
852                 /* Should never see this, we don't support Change Password. */
853                 p = "E=709 Error changing password";
854                 break;
855
856             default:
857                 free(msg);
858                 p = msg = malloc(len + 33);
859                 if (!msg) {
860                     novm("ChapReceiveFailure");
861                     goto print_msg;
862                 }
863                 slprintf(p, len + 33, "Unknown authentication failure: %.*s",
864                          len, inp);
865                 break;
866             }
867         }
868         len = strlen(p);
869     }
870 #endif
871
872     /*
873      * Print message.
874      */
875 print_msg:
876     if (len > 0 && p != NULL)
877         PRINTMSG(p, len);
878
879     error("CHAP authentication failed");
880     auth_withpeer_fail(cstate->unit, PPP_CHAP);
881 #ifdef CHAPMS
882     if (msg) free(msg);
883 #endif
884 }
885
886
887 /*
888  * ChapSendChallenge - Send an Authenticate challenge.
889  */
890 static void
891 ChapSendChallenge(cstate)
892     chap_state *cstate;
893 {
894     u_char *outp;
895     int chal_len, name_len;
896     int outlen;
897
898     chal_len = cstate->chal_len;
899     name_len = strlen(cstate->chal_name);
900     outlen = CHAP_HEADERLEN + sizeof (u_char) + chal_len + name_len;
901     outp = outpacket_buf;
902
903     MAKEHEADER(outp, PPP_CHAP);         /* paste in a CHAP header */
904
905     PUTCHAR(CHAP_CHALLENGE, outp);
906     PUTCHAR(cstate->chal_id, outp);
907     PUTSHORT(outlen, outp);
908
909     PUTCHAR(chal_len, outp);            /* put length of challenge */
910     BCOPY(cstate->challenge, outp, chal_len);
911     INCPTR(chal_len, outp);
912
913     BCOPY(cstate->chal_name, outp, name_len);   /* append hostname */
914
915     output(cstate->unit, outpacket_buf, outlen + PPP_HDRLEN);
916
917     TIMEOUT(ChapChallengeTimeout, cstate, cstate->timeouttime);
918     ++cstate->chal_transmits;
919 }
920
921
922 /*
923  * ChapSendStatus - Send a status response (ack or nak).
924  * See RFC 2433 and RFC 2759 for MS-CHAP and MS-CHAPv2 message formats.
925  */
926 static void
927 ChapSendStatus(cstate, code)
928     chap_state *cstate;
929     int code;
930 {
931     u_char *outp;
932     int i, outlen, msglen;
933     char msg[256];
934     char *p, *q;
935
936     p = msg;
937     q = p + sizeof(msg); /* points 1 byte past msg */
938
939     if (code == CHAP_SUCCESS) {
940 #ifdef CHAPMS
941         if (cstate->chal_type == CHAP_MICROSOFT_V2) {
942             /*
943              * Per RFC 2759, success message must be formatted as
944              *     "S=<auth_string> M=<message>"
945              * where
946              *     <auth_string> is the Authenticator Response (mutual auth)
947              *     <message> is a text message
948              *
949              * However, some versions of Windows (win98 tested) do not know
950              * about the M=<message> part (required per RFC 2759) and flag
951              * it as an error (reported incorrectly as an encryption error
952              * to the user).  Since the RFC requires it, and it can be
953              * useful information, we supply it if the peer is a conforming
954              * system.  Luckily (?), win98 sets the Flags field to 0x04
955              * (contrary to RFC requirements) so we can use that to
956              * distinguish between conforming and non-conforming systems.
957              *
958              * Special thanks to Alex Swiridov <say@real.kharkov.ua> for
959              * help debugging this.
960              */
961             slprintf(p, q - p, "S=");
962             p += 2;
963             slprintf(p, q - p, "%s", cstate->saresponse);
964             p += strlen(cstate->saresponse);
965             if (cstate->resp_flags != 0)
966                 goto msgdone;
967             slprintf(p, q - p, " M=");
968             p += 3;
969         }
970 #endif /* CHAPMS */
971
972         slprintf(p, q - p, "Welcome to %s.", hostname);
973     } else {
974 #ifdef CHAPMS
975         if ((cstate->chal_type == CHAP_MICROSOFT_V2) ||
976             (cstate->chal_type == CHAP_MICROSOFT)) {
977             /*
978              * Failure message must be formatted as
979              *     "E=e R=r C=c V=v M=m"
980              * where
981              *     e = error code (we use 691, ERROR_AUTHENTICATION_FAILURE)
982              *     r = retry (we use 1, ok to retry)
983              *     c = challenge to use for next response, we reuse previous
984              *     v = Change Password version supported, we use 0
985              *     m = text message
986              *
987              * The M=m part is only for MS-CHAPv2, but MS-CHAP should ignore
988              * any extra text according to RFC 2433.  So we'll go the easy
989              * (read: lazy) route and include it always.  Neither win2k nor
990              * win98 (others untested) display the message to the user anyway.
991              * They also both ignore the E=e code.
992              *
993              * Note that it's safe to reuse the same challenge as we don't
994              * actually accept another response based on the error message
995              * (and no clients try to resend a response anyway).
996              *
997              * Basically, this whole bit is useless code, even the small
998              * implementation here is only because of overspecification.
999              */
1000             slprintf(p, q - p, "E=691 R=1 C=");
1001             p += 12;
1002             for (i = 0; i < cstate->chal_len; i++)
1003                 sprintf(p + i * 2, "%02X", cstate->challenge[i]);
1004             p += cstate->chal_len * 2;
1005             slprintf(p, q - p, " V=0 M=");
1006             p += 7;
1007         }
1008 #endif /* CHAPMS */
1009
1010         slprintf(p, q - p, "I don't like you.  Go 'way.");
1011     }
1012 msgdone:
1013     msglen = strlen(msg);
1014
1015     outlen = CHAP_HEADERLEN + msglen;
1016     outp = outpacket_buf;
1017
1018     MAKEHEADER(outp, PPP_CHAP); /* paste in a header */
1019
1020     PUTCHAR(code, outp);
1021     PUTCHAR(cstate->chal_id, outp);
1022     PUTSHORT(outlen, outp);
1023     BCOPY(msg, outp, msglen);
1024     output(cstate->unit, outpacket_buf, outlen + PPP_HDRLEN);
1025 }
1026
1027 /*
1028  * ChapGenChallenge is used to generate a pseudo-random challenge string of
1029  * a pseudo-random length between min_len and max_len.  The challenge
1030  * string and its length are stored in *cstate, and various other fields of
1031  * *cstate are initialized.
1032  */
1033
1034 static void
1035 ChapGenChallenge(cstate)
1036     chap_state *cstate;
1037 {
1038     int chal_len = 0; /* Avoid compiler warning */
1039     u_char *ptr = cstate->challenge;
1040     int i;
1041
1042     switch (cstate->chal_type) {
1043     case CHAP_DIGEST_MD5:
1044         /*
1045          * pick a random challenge length between MIN_CHALLENGE_LENGTH and
1046          * MAX_CHALLENGE_LENGTH
1047          */
1048         chal_len = (unsigned) ((drand48() *
1049                                 (MAX_CHALLENGE_LENGTH - MIN_CHALLENGE_LENGTH)) +
1050                                 MIN_CHALLENGE_LENGTH);
1051         break;
1052
1053 #ifdef CHAPMS
1054     case CHAP_MICROSOFT:
1055         /* MS-CHAP is fixed to an 8 octet challenge. */
1056         chal_len = 8;
1057         break;
1058
1059     case CHAP_MICROSOFT_V2:
1060         /* MS-CHAPv2 is fixed to a 16 octet challenge. */
1061         chal_len = 16;
1062         break;
1063 #endif
1064     default:
1065         fatal("ChapGenChallenge: Unsupported challenge type %d",
1066               (int) cstate->chal_type);
1067         break;
1068     }
1069
1070     cstate->chal_len = chal_len;
1071     cstate->chal_id = ++cstate->id;
1072     cstate->chal_transmits = 0;
1073
1074 #ifdef CHAPMS
1075     if (mschap_challenge)
1076         for (i = 0; i < chal_len; i++)
1077             *ptr++ = mschap_challenge[i];
1078     else
1079 #endif
1080         /* generate a random string */
1081         for (i = 0; i < chal_len; i++)
1082             *ptr++ = (char) (drand48() * 0xff);
1083 }
1084
1085 /*
1086  * ChapSendResponse - send a response packet with values as specified
1087  * in *cstate.
1088  */
1089 /* ARGSUSED */
1090 static void
1091 ChapSendResponse(cstate)
1092     chap_state *cstate;
1093 {
1094     u_char *outp;
1095     int outlen, md_len, name_len;
1096
1097     md_len = cstate->resp_length;
1098     name_len = strlen(cstate->resp_name);
1099     outlen = CHAP_HEADERLEN + sizeof (u_char) + md_len + name_len;
1100     outp = outpacket_buf;
1101
1102     MAKEHEADER(outp, PPP_CHAP);
1103
1104     PUTCHAR(CHAP_RESPONSE, outp);       /* we are a response */
1105     PUTCHAR(cstate->resp_id, outp);     /* copy id from challenge packet */
1106     PUTSHORT(outlen, outp);             /* packet length */
1107
1108     PUTCHAR(md_len, outp);              /* length of MD */
1109     BCOPY(cstate->response, outp, md_len);      /* copy MD to buffer */
1110     INCPTR(md_len, outp);
1111
1112     BCOPY(cstate->resp_name, outp, name_len); /* append our name */
1113
1114     /* send the packet */
1115     output(cstate->unit, outpacket_buf, outlen + PPP_HDRLEN);
1116
1117     cstate->clientstate = CHAPCS_RESPONSE;
1118     TIMEOUT(ChapResponseTimeout, cstate, cstate->timeouttime);
1119     ++cstate->resp_transmits;
1120 }
1121
1122 /*
1123  * ChapPrintPkt - print the contents of a CHAP packet.
1124  */
1125 static char *ChapCodenames[] = {
1126     "Challenge", "Response", "Success", "Failure"
1127 };
1128
1129 static int
1130 ChapPrintPkt(p, plen, printer, arg)
1131     u_char *p;
1132     int plen;
1133     void (*printer) __P((void *, char *, ...));
1134     void *arg;
1135 {
1136     int code, id, len;
1137     int clen, nlen;
1138     u_char x;
1139
1140     if (plen < CHAP_HEADERLEN)
1141         return 0;
1142     GETCHAR(code, p);
1143     GETCHAR(id, p);
1144     GETSHORT(len, p);
1145     if (len < CHAP_HEADERLEN || len > plen)
1146         return 0;
1147
1148     if (code >= 1 && code <= sizeof(ChapCodenames) / sizeof(char *))
1149         printer(arg, " %s", ChapCodenames[code-1]);
1150     else
1151         printer(arg, " code=0x%x", code);
1152     printer(arg, " id=0x%x", id);
1153     len -= CHAP_HEADERLEN;
1154     switch (code) {
1155     case CHAP_CHALLENGE:
1156     case CHAP_RESPONSE:
1157         if (len < 1)
1158             break;
1159         clen = p[0];
1160         if (len < clen + 1)
1161             break;
1162         ++p;
1163         nlen = len - clen - 1;
1164         printer(arg, " <");
1165         for (; clen > 0; --clen) {
1166             GETCHAR(x, p);
1167             printer(arg, "%.2x", x);
1168         }
1169         printer(arg, ">, name = ");
1170         print_string((char *)p, nlen, printer, arg);
1171         break;
1172     case CHAP_FAILURE:
1173     case CHAP_SUCCESS:
1174         printer(arg, " ");
1175         print_string((char *)p, len, printer, arg);
1176         break;
1177     default:
1178         for (clen = len; clen > 0; --clen) {
1179             GETCHAR(x, p);
1180             printer(arg, " %.2x", x);
1181         }
1182     }
1183
1184     return len + CHAP_HEADERLEN;
1185 }