2 * chap.c - Challenge Handshake Authentication Protocol.
4 * Copyright (c) 1993-2002 Paul Mackerras. All rights reserved.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
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
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.
22 * 4. Redistributions of any form whatsoever must retain the following
24 * "This product includes software developed by Paul Mackerras
25 * <paulus@samba.org>".
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.
35 * Copyright (c) 1991 Gregory M. Christy.
36 * All rights reserved.
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.
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.
52 #define RCSID "$Id: chap.c,v 1.41 2003/07/28 12:25:41 carlsonj Exp $"
61 #include <sys/types.h>
71 /* Hook for a plugin to validate CHAP challenge */
72 int (*chap_auth_hook) __P((char *user,
75 chap_state *cstate)) = NULL;
77 static const char rcsid[] = RCSID;
81 /* Use "[]|}{?/><,`!2&&(" (sans quotes) for RFC 3079 MS-CHAPv2 test value */
82 static char *mschap_challenge = NULL;
83 /* Use "!@\#$%^&*()_+:3|~" (sans quotes, backslash is to escape #) for ... */
84 static char *mschap2_peer_challenge = NULL;
88 * Command-line options.
90 static option_t chap_option_list[] = {
91 { "chap-restart", o_int, &chap[0].timeouttime,
92 "Set timeout for CHAP", OPT_PRIO },
93 { "chap-max-challenge", o_int, &chap[0].max_transmits,
94 "Set max #xmits for challenge", OPT_PRIO },
95 { "chap-interval", o_int, &chap[0].chal_interval,
96 "Set interval for rechallenge", OPT_PRIO },
99 { "ms-lanman", o_bool, &ms_lanman,
100 "Use LanMan passwd when using MS-CHAP", 1 },
103 { "mschap-challenge", o_string, &mschap_challenge,
104 "specify CHAP challenge" },
105 { "mschap2-peer-challenge", o_string, &mschap2_peer_challenge,
106 "specify CHAP peer challenge" },
113 * Protocol entry points.
115 static void ChapInit __P((int));
116 static void ChapLowerUp __P((int));
117 static void ChapLowerDown __P((int));
118 static void ChapInput __P((int, u_char *, int));
119 static void ChapProtocolReject __P((int));
120 static int ChapPrintPkt __P((u_char *, int,
121 void (*) __P((void *, char *, ...)), void *));
123 struct protent chap_protent = {
143 chap_state chap[NUM_PPP]; /* CHAP state; one for each unit */
145 static void ChapChallengeTimeout __P((void *));
146 static void ChapResponseTimeout __P((void *));
147 static void ChapReceiveChallenge __P((chap_state *, u_char *, int, int));
148 static void ChapRechallenge __P((void *));
149 static void ChapReceiveResponse __P((chap_state *, u_char *, int, int));
150 static void ChapReceiveSuccess __P((chap_state *, u_char *, int, int));
151 static void ChapReceiveFailure __P((chap_state *, u_char *, int, int));
152 static void ChapSendStatus __P((chap_state *, int));
153 static void ChapSendChallenge __P((chap_state *));
154 static void ChapSendResponse __P((chap_state *));
155 static void ChapGenChallenge __P((chap_state *));
157 extern double drand48 __P((void));
158 extern void srand48 __P((long));
161 * ChapInit - Initialize a CHAP unit.
167 chap_state *cstate = &chap[unit];
169 BZERO(cstate, sizeof(*cstate));
171 cstate->clientstate = CHAPCS_INITIAL;
172 cstate->serverstate = CHAPSS_INITIAL;
173 cstate->timeouttime = CHAP_DEFTIMEOUT;
174 cstate->max_transmits = CHAP_DEFTRANSMITS;
175 /* random number generator is initialized in magic_init */
180 * chap_auth_with_peer - Authenticate us with our peer (start client).
184 chap_auth_with_peer(int unit, char *our_name, int digest)
186 chap_state *cstate = &chap[unit];
188 cstate->resp_name = our_name;
189 cstate->resp_type = digest;
191 if (cstate->clientstate == CHAPCS_INITIAL ||
192 cstate->clientstate == CHAPCS_PENDING) {
193 /* lower layer isn't up - wait until later */
194 cstate->clientstate = CHAPCS_PENDING;
199 * We get here as a result of LCP coming up.
200 * So even if CHAP was open before, we will
201 * have to re-authenticate ourselves.
203 cstate->clientstate = CHAPCS_LISTEN;
208 * chap_auth_peer - Authenticate our peer (start server).
211 chap_auth_peer(int unit, char *our_name, int digest)
213 chap_state *cstate = &chap[unit];
215 cstate->chal_name = our_name;
216 cstate->chal_type = digest;
218 if (cstate->serverstate == CHAPSS_INITIAL ||
219 cstate->serverstate == CHAPSS_PENDING) {
220 /* lower layer isn't up - wait until later */
221 cstate->serverstate = CHAPSS_PENDING;
225 ChapGenChallenge(cstate);
226 ChapSendChallenge(cstate); /* crank it up dude! */
227 cstate->serverstate = CHAPSS_INITIAL_CHAL;
232 * ChapChallengeTimeout - Timeout expired on sending challenge.
235 ChapChallengeTimeout(arg)
238 chap_state *cstate = (chap_state *) arg;
240 /* if we aren't sending challenges, don't worry. then again we */
241 /* probably shouldn't be here either */
242 if (cstate->serverstate != CHAPSS_INITIAL_CHAL &&
243 cstate->serverstate != CHAPSS_RECHALLENGE)
246 if (cstate->chal_transmits >= cstate->max_transmits) {
247 /* give up on peer */
248 error("Peer failed to respond to CHAP challenge");
249 cstate->serverstate = CHAPSS_BADAUTH;
250 auth_peer_fail(cstate->unit, PPP_CHAP);
254 ChapSendChallenge(cstate); /* Re-send challenge */
259 * ChapResponseTimeout - Timeout expired on sending response.
262 ChapResponseTimeout(arg)
265 chap_state *cstate = (chap_state *) arg;
267 /* if we aren't sending a response, don't worry. */
268 if (cstate->clientstate != CHAPCS_RESPONSE)
271 ChapSendResponse(cstate); /* re-send response */
276 * ChapRechallenge - Time to challenge the peer again.
282 chap_state *cstate = (chap_state *) arg;
284 /* if we aren't sending a response, don't worry. */
285 if (cstate->serverstate != CHAPSS_OPEN)
288 ChapGenChallenge(cstate);
289 ChapSendChallenge(cstate);
290 cstate->serverstate = CHAPSS_RECHALLENGE;
295 * ChapLowerUp - The lower layer is up.
297 * Start up if we have pending requests.
303 chap_state *cstate = &chap[unit];
305 if (cstate->clientstate == CHAPCS_INITIAL)
306 cstate->clientstate = CHAPCS_CLOSED;
307 else if (cstate->clientstate == CHAPCS_PENDING)
308 cstate->clientstate = CHAPCS_LISTEN;
310 if (cstate->serverstate == CHAPSS_INITIAL)
311 cstate->serverstate = CHAPSS_CLOSED;
312 else if (cstate->serverstate == CHAPSS_PENDING) {
313 ChapGenChallenge(cstate);
314 ChapSendChallenge(cstate);
315 cstate->serverstate = CHAPSS_INITIAL_CHAL;
321 * ChapLowerDown - The lower layer is down.
323 * Cancel all timeouts.
329 chap_state *cstate = &chap[unit];
331 /* Timeout(s) pending? Cancel if so. */
332 if (cstate->serverstate == CHAPSS_INITIAL_CHAL ||
333 cstate->serverstate == CHAPSS_RECHALLENGE)
334 UNTIMEOUT(ChapChallengeTimeout, cstate);
335 else if (cstate->serverstate == CHAPSS_OPEN
336 && cstate->chal_interval != 0)
337 UNTIMEOUT(ChapRechallenge, cstate);
338 if (cstate->clientstate == CHAPCS_RESPONSE)
339 UNTIMEOUT(ChapResponseTimeout, cstate);
341 cstate->clientstate = CHAPCS_INITIAL;
342 cstate->serverstate = CHAPSS_INITIAL;
347 * ChapProtocolReject - Peer doesn't grok CHAP.
350 ChapProtocolReject(unit)
353 chap_state *cstate = &chap[unit];
355 if (cstate->serverstate != CHAPSS_INITIAL &&
356 cstate->serverstate != CHAPSS_CLOSED)
357 auth_peer_fail(unit, PPP_CHAP);
358 if (cstate->clientstate != CHAPCS_INITIAL &&
359 cstate->clientstate != CHAPCS_CLOSED)
360 auth_withpeer_fail(unit, PPP_CHAP);
361 ChapLowerDown(unit); /* shutdown chap */
366 * ChapInput - Input CHAP packet.
369 ChapInput(unit, inpacket, packet_len)
374 chap_state *cstate = &chap[unit];
380 * Parse header (code, id and length).
381 * If packet too short, drop it.
384 if (packet_len < CHAP_HEADERLEN) {
385 CHAPDEBUG(("ChapInput: rcvd short header."));
391 if (len < CHAP_HEADERLEN) {
392 CHAPDEBUG(("ChapInput: rcvd illegal length."));
395 if (len > packet_len) {
396 CHAPDEBUG(("ChapInput: rcvd short packet."));
399 len -= CHAP_HEADERLEN;
402 * Action depends on code (as in fact it usually does :-).
406 ChapReceiveChallenge(cstate, inp, id, len);
410 ChapReceiveResponse(cstate, inp, id, len);
414 ChapReceiveFailure(cstate, inp, id, len);
418 ChapReceiveSuccess(cstate, inp, id, len);
421 default: /* Need code reject? */
422 warn("Unknown CHAP code (%d) received.", code);
429 * ChapReceiveChallenge - Receive Challenge and send Response.
432 ChapReceiveChallenge(cstate, inp, id, len)
441 char secret[MAXSECRETLEN];
444 u_char hash[MD5_SIGNATURE_SIZE];
446 if (cstate->clientstate == CHAPCS_CLOSED ||
447 cstate->clientstate == CHAPCS_PENDING) {
448 CHAPDEBUG(("ChapReceiveChallenge: in state %d", cstate->clientstate));
453 CHAPDEBUG(("ChapReceiveChallenge: rcvd short packet."));
457 GETCHAR(rchallenge_len, inp);
458 len -= sizeof (u_char) + rchallenge_len; /* now name field length */
460 CHAPDEBUG(("ChapReceiveChallenge: rcvd short packet."));
464 INCPTR(rchallenge_len, inp);
466 /* Null terminate and clean remote name. */
467 slprintf(rhostname, sizeof(rhostname), "%.*v", len, inp);
469 /* Microsoft doesn't send their name back in the PPP packet */
470 if (explicit_remote || (remote_name[0] != 0 && rhostname[0] == 0)) {
471 strlcpy(rhostname, remote_name, sizeof(rhostname));
472 CHAPDEBUG(("ChapReceiveChallenge: using '%q' as remote name",
476 /* get secret for authenticating ourselves with the specified host */
477 if (!get_secret(cstate->unit, cstate->resp_name, rhostname,
478 secret, &secret_len, 0)) {
479 secret_len = 0; /* assume null secret if can't find one */
480 warn("No CHAP secret found for authenticating us to %q", rhostname);
483 /* cancel response send timeout if necessary */
484 if (cstate->clientstate == CHAPCS_RESPONSE)
485 UNTIMEOUT(ChapResponseTimeout, cstate);
487 cstate->resp_id = id;
488 cstate->resp_transmits = 0;
490 /* generate MD based on negotiated type */
491 switch (cstate->resp_type) {
493 case CHAP_DIGEST_MD5:
495 MD5Update(&mdContext, &cstate->resp_id, 1);
496 MD5Update(&mdContext, secret, secret_len);
497 MD5Update(&mdContext, rchallenge, rchallenge_len);
498 MD5Final(hash, &mdContext);
499 BCOPY(hash, cstate->response, MD5_SIGNATURE_SIZE);
500 cstate->resp_length = MD5_SIGNATURE_SIZE;
505 ChapMS(cstate, rchallenge, secret, secret_len,
506 (MS_ChapResponse *) cstate->response);
509 case CHAP_MICROSOFT_V2:
510 ChapMS2(cstate, rchallenge,
511 mschap2_peer_challenge? mschap2_peer_challenge: NULL,
512 cstate->resp_name, secret, secret_len,
513 (MS_Chap2Response *) cstate->response, cstate->earesponse,
514 MS_CHAP2_AUTHENTICATEE);
519 CHAPDEBUG(("unknown digest type %d", cstate->resp_type));
523 BZERO(secret, sizeof(secret));
524 ChapSendResponse(cstate);
529 * ChapReceiveResponse - Receive and process response.
532 ChapReceiveResponse(cstate, inp, id, len)
538 u_char *remmd, remmd_len;
539 int secret_len, old_state;
543 char secret[MAXSECRETLEN];
544 u_char hash[MD5_SIGNATURE_SIZE];
546 if (cstate->serverstate == CHAPSS_CLOSED ||
547 cstate->serverstate == CHAPSS_PENDING) {
548 CHAPDEBUG(("ChapReceiveResponse: in state %d", cstate->serverstate));
552 if (id != cstate->chal_id)
553 return; /* doesn't match ID of last challenge */
556 * If we have received a duplicate or bogus Response,
557 * we have to send the same answer (Success/Failure)
558 * as we did for the first Response we saw.
560 if (cstate->serverstate == CHAPSS_OPEN) {
561 ChapSendStatus(cstate, CHAP_SUCCESS);
564 if (cstate->serverstate == CHAPSS_BADAUTH) {
565 ChapSendStatus(cstate, CHAP_FAILURE);
570 CHAPDEBUG(("ChapReceiveResponse: rcvd short packet."));
573 GETCHAR(remmd_len, inp); /* get length of MD */
574 remmd = inp; /* get pointer to MD */
575 INCPTR(remmd_len, inp);
577 len -= sizeof (u_char) + remmd_len;
579 CHAPDEBUG(("ChapReceiveResponse: rcvd short packet."));
583 UNTIMEOUT(ChapChallengeTimeout, cstate);
585 /* Null terminate and clean remote name. */
586 slprintf(rhostname, sizeof(rhostname), "%.*v", len, inp);
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];
594 * Get secret for authenticating them with us,
595 * do the hash ourselves, and compare the result.
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,
605 * Check remote number authorization. A plugin may have filled in
606 * the remote number or added an allowed number, and rather than
607 * return an authenticate failure, is leaving it for us to verify.
609 if (code == CHAP_SUCCESS) {
610 if (!auth_number()) {
611 /* We do not want to leak info about the chap result. */
612 code = CHAP_FAILURE; /* XXX exit value will be "wrong" */
613 warn("calling number %q is not authorized", remote_number);
618 if (!get_secret(cstate->unit, (explicit_remote? remote_name: rhostname),
619 cstate->chal_name, secret, &secret_len, 1)) {
620 warn("No CHAP secret found for authenticating %q", rhostname);
623 /* generate MD based on negotiated type */
624 switch (cstate->chal_type) {
626 case CHAP_DIGEST_MD5:
627 if (remmd_len != MD5_SIGNATURE_SIZE)
628 break; /* not even the right length */
630 MD5Update(&mdContext, &cstate->chal_id, 1);
631 MD5Update(&mdContext, secret, secret_len);
632 MD5Update(&mdContext, cstate->challenge, cstate->chal_len);
633 MD5Final(hash, &mdContext);
635 /* compare MDs and send the appropriate status */
636 if (memcmp(hash, remmd, MD5_SIGNATURE_SIZE) == 0)
637 code = CHAP_SUCCESS; /* they are the same! */
643 int response_offset, response_size;
644 MS_ChapResponse *rmd = (MS_ChapResponse *) remmd;
647 if (remmd_len != MS_CHAP_RESPONSE_LEN)
648 break; /* not even the right length */
650 /* Determine which part of response to verify against */
652 response_offset = offsetof(MS_ChapResponse, NTResp);
653 response_size = sizeof(rmd->NTResp);
656 response_offset = offsetof(MS_ChapResponse, LANManResp);
657 response_size = sizeof(rmd->LANManResp);
659 /* Should really propagate this into the error packet. */
660 notice("Peer request for LANMAN auth not supported");
662 #endif /* MSLANMAN */
665 /* Generate the expected response. */
666 ChapMS(cstate, cstate->challenge, secret, secret_len, &md);
668 /* compare MDs and send the appropriate status */
669 if (memcmp((u_char *) &md + response_offset,
670 (u_char *) remmd + response_offset,
672 code = CHAP_SUCCESS; /* they are the same! */
676 case CHAP_MICROSOFT_V2:
678 MS_Chap2Response *rmd = (MS_Chap2Response *) remmd;
681 if (remmd_len != MS_CHAP2_RESPONSE_LEN)
682 break; /* not even the right length */
684 /* Generate the expected response and our mutual auth. */
685 ChapMS2(cstate, cstate->challenge, rmd->PeerChallenge,
686 (explicit_remote? remote_name: rhostname),
687 secret, secret_len, &md,
688 cstate->saresponse, MS_CHAP2_AUTHENTICATOR);
690 /* compare MDs and send the appropriate status */
691 if (memcmp(md.NTResp, rmd->NTResp, sizeof(md.NTResp)) == 0)
692 code = CHAP_SUCCESS; /* yay! */
698 CHAPDEBUG(("unknown digest type %d", cstate->chal_type));
702 BZERO(secret, sizeof(secret));
704 ChapSendStatus(cstate, code);
706 if (code == CHAP_SUCCESS) {
707 old_state = cstate->serverstate;
708 cstate->serverstate = CHAPSS_OPEN;
709 if (old_state == CHAPSS_INITIAL_CHAL) {
710 auth_peer_success(cstate->unit, PPP_CHAP, cstate->chal_type,
713 if (cstate->chal_interval != 0)
714 TIMEOUT(ChapRechallenge, cstate, cstate->chal_interval);
715 notice("CHAP peer authentication succeeded for %q", rhostname);
718 warn("CHAP peer authentication failed for %q", rhostname);
719 cstate->serverstate = CHAPSS_BADAUTH;
720 auth_peer_fail(cstate->unit, PPP_CHAP);
725 * ChapReceiveSuccess - Receive Success
728 ChapReceiveSuccess(cstate, inp, id, len)
735 if (cstate->clientstate == CHAPCS_OPEN)
736 /* presumably an answer to a duplicate response */
739 if (cstate->clientstate != CHAPCS_RESPONSE) {
740 /* don't know what this is */
741 CHAPDEBUG(("ChapReceiveSuccess: in state %d\n", cstate->clientstate));
745 UNTIMEOUT(ChapResponseTimeout, cstate);
749 * For MS-CHAPv2, we must verify that the peer knows our secret.
751 if (cstate->resp_type == CHAP_MICROSOFT_V2) {
752 if ((len >= MS_AUTH_RESPONSE_LENGTH + 2) && !strncmp(inp, "S=", 2)) {
754 if (!memcmp(inp, cstate->earesponse, MS_AUTH_RESPONSE_LENGTH)) {
755 /* Authenticator Response matches. */
756 inp += MS_AUTH_RESPONSE_LENGTH; /* Eat it */
757 len -= MS_AUTH_RESPONSE_LENGTH;
758 if ((len >= 3) && !strncmp(inp, " M=", 3)) {
759 inp += 3; len -= 3; /* Eat the delimiter */
761 /* Packet has extra text which does not begin " M=" */
762 error("MS-CHAPv2 Success packet is badly formed.");
763 auth_withpeer_fail(cstate->unit, PPP_CHAP);
766 /* Authenticator Response did not match expected. */
767 error("MS-CHAPv2 mutual authentication failed.");
768 auth_withpeer_fail(cstate->unit, PPP_CHAP);
771 /* Packet does not start with "S=" */
772 error("MS-CHAPv2 Success packet is badly formed.");
773 auth_withpeer_fail(cstate->unit, PPP_CHAP);
784 cstate->clientstate = CHAPCS_OPEN;
786 notice("CHAP authentication succeeded");
787 auth_withpeer_success(cstate->unit, PPP_CHAP, cstate->resp_type);
792 * ChapReceiveFailure - Receive failure.
795 ChapReceiveFailure(cstate, inp, id, len)
806 if (cstate->clientstate != CHAPCS_RESPONSE) {
807 /* don't know what this is */
808 CHAPDEBUG(("ChapReceiveFailure: in state %d\n", cstate->clientstate));
813 /* We want a null-terminated string for strxxx(). */
814 msg = malloc(len + 1);
817 notice("Out of memory in ChapReceiveFailure");
820 BCOPY(inp, msg, len);
821 p = msg + len; *p = '\0'; p = msg;
824 UNTIMEOUT(ChapResponseTimeout, cstate);
827 if ((cstate->resp_type == CHAP_MICROSOFT_V2) ||
828 (cstate->resp_type == CHAP_MICROSOFT)) {
832 * Deal with MS-CHAP formatted failure messages; just print the
833 * M=<message> part (if any). For MS-CHAP we're not really supposed
834 * to use M=<message>, but it shouldn't hurt. See ChapSendStatus().
836 if (!strncmp(p, "E=", 2))
837 error = (int) strtol(p, NULL, 10); /* Remember the error code. */
839 goto print_msg; /* Message is badly formatted. */
841 if (len && ((p = strstr(p, " M=")) != NULL)) {
842 /* M=<message> field found. */
845 /* No M=<message>; use the error code. */
847 case MS_CHAP_ERROR_RESTRICTED_LOGON_HOURS:
848 p = "E=646 Restricted logon hours";
851 case MS_CHAP_ERROR_ACCT_DISABLED:
852 p = "E=647 Account disabled";
855 case MS_CHAP_ERROR_PASSWD_EXPIRED:
856 p = "E=648 Password expired";
859 case MS_CHAP_ERROR_NO_DIALIN_PERMISSION:
860 p = "E=649 No dialin permission";
863 case MS_CHAP_ERROR_AUTHENTICATION_FAILURE:
864 p = "E=691 Authentication failure";
867 case MS_CHAP_ERROR_CHANGING_PASSWORD:
868 /* Should never see this, we don't support Change Password. */
869 p = "E=709 Error changing password";
874 p = msg = malloc(len + 33);
876 novm("ChapReceiveFailure");
879 slprintf(p, len + 33, "Unknown authentication failure: %.*s",
894 if (len > 0 && p != NULL)
897 error("CHAP authentication failed");
898 auth_withpeer_fail(cstate->unit, PPP_CHAP);
906 * ChapSendChallenge - Send an Authenticate challenge.
909 ChapSendChallenge(cstate)
913 int chal_len, name_len;
916 chal_len = cstate->chal_len;
917 name_len = strlen(cstate->chal_name);
918 outlen = CHAP_HEADERLEN + sizeof (u_char) + chal_len + name_len;
919 outp = outpacket_buf;
921 MAKEHEADER(outp, PPP_CHAP); /* paste in a CHAP header */
923 PUTCHAR(CHAP_CHALLENGE, outp);
924 PUTCHAR(cstate->chal_id, outp);
925 PUTSHORT(outlen, outp);
927 PUTCHAR(chal_len, outp); /* put length of challenge */
928 BCOPY(cstate->challenge, outp, chal_len);
929 INCPTR(chal_len, outp);
931 BCOPY(cstate->chal_name, outp, name_len); /* append hostname */
933 output(cstate->unit, outpacket_buf, outlen + PPP_HDRLEN);
935 TIMEOUT(ChapChallengeTimeout, cstate, cstate->timeouttime);
936 ++cstate->chal_transmits;
941 * ChapSendStatus - Send a status response (ack or nak).
942 * See RFC 2433 and RFC 2759 for MS-CHAP and MS-CHAPv2 message formats.
945 ChapSendStatus(cstate, code)
955 q = p + sizeof(msg); /* points 1 byte past msg */
957 if (code == CHAP_SUCCESS) {
959 if (cstate->chal_type == CHAP_MICROSOFT_V2) {
961 * Per RFC 2759, success message must be formatted as
962 * "S=<auth_string> M=<message>"
964 * <auth_string> is the Authenticator Response (mutual auth)
965 * <message> is a text message
967 * However, some versions of Windows (win98 tested) do not know
968 * about the M=<message> part (required per RFC 2759) and flag
969 * it as an error (reported incorrectly as an encryption error
970 * to the user). Since the RFC requires it, and it can be
971 * useful information, we supply it if the peer is a conforming
972 * system. Luckily (?), win98 sets the Flags field to 0x04
973 * (contrary to RFC requirements) so we can use that to
974 * distinguish between conforming and non-conforming systems.
976 * Special thanks to Alex Swiridov <say@real.kharkov.ua> for
977 * help debugging this.
979 slprintf(p, q - p, "S=");
981 slprintf(p, q - p, "%s", cstate->saresponse);
982 p += strlen(cstate->saresponse);
983 if (cstate->resp_flags != 0)
985 slprintf(p, q - p, " M=");
990 slprintf(p, q - p, "Welcome to %s.", hostname);
993 if ((cstate->chal_type == CHAP_MICROSOFT_V2) ||
994 (cstate->chal_type == CHAP_MICROSOFT)) {
996 * Failure message must be formatted as
997 * "E=e R=r C=c V=v M=m"
999 * e = error code (we use 691, ERROR_AUTHENTICATION_FAILURE)
1000 * r = retry (we use 1, ok to retry)
1001 * c = challenge to use for next response, we reuse previous
1002 * v = Change Password version supported, we use 0
1005 * The M=m part is only for MS-CHAPv2, but MS-CHAP should ignore
1006 * any extra text according to RFC 2433. So we'll go the easy
1007 * (read: lazy) route and include it always. Neither win2k nor
1008 * win98 (others untested) display the message to the user anyway.
1009 * They also both ignore the E=e code.
1011 * Note that it's safe to reuse the same challenge as we don't
1012 * actually accept another response based on the error message
1013 * (and no clients try to resend a response anyway).
1015 * Basically, this whole bit is useless code, even the small
1016 * implementation here is only because of overspecification.
1020 slprintf(p, q - p, "E=691 R=1 C=");
1022 for (i = 0; i < cstate->chal_len; i++)
1023 sprintf(p + i * 2, "%02X", cstate->challenge[i]);
1024 p += cstate->chal_len * 2;
1025 slprintf(p, q - p, " V=0 M=");
1030 slprintf(p, q - p, "I don't like you. Go 'way.");
1035 msglen = strlen(msg);
1037 outlen = CHAP_HEADERLEN + msglen;
1038 outp = outpacket_buf;
1040 MAKEHEADER(outp, PPP_CHAP); /* paste in a header */
1042 PUTCHAR(code, outp);
1043 PUTCHAR(cstate->chal_id, outp);
1044 PUTSHORT(outlen, outp);
1045 BCOPY(msg, outp, msglen);
1046 output(cstate->unit, outpacket_buf, outlen + PPP_HDRLEN);
1050 * ChapGenChallenge is used to generate a pseudo-random challenge string of
1051 * a pseudo-random length between min_len and max_len. The challenge
1052 * string and its length are stored in *cstate, and various other fields of
1053 * *cstate are initialized.
1057 ChapGenChallenge(cstate)
1060 int chal_len = 0; /* Avoid compiler warning */
1061 u_char *ptr = cstate->challenge;
1064 switch (cstate->chal_type) {
1065 case CHAP_DIGEST_MD5:
1067 * pick a random challenge length between MIN_CHALLENGE_LENGTH and
1068 * MAX_CHALLENGE_LENGTH
1070 chal_len = (unsigned) ((drand48() *
1071 (MAX_CHALLENGE_LENGTH - MIN_CHALLENGE_LENGTH)) +
1072 MIN_CHALLENGE_LENGTH);
1076 case CHAP_MICROSOFT:
1077 /* MS-CHAP is fixed to an 8 octet challenge. */
1081 case CHAP_MICROSOFT_V2:
1082 /* MS-CHAPv2 is fixed to a 16 octet challenge. */
1087 fatal("ChapGenChallenge: Unsupported challenge type %d",
1088 (int) cstate->chal_type);
1092 cstate->chal_len = chal_len;
1093 cstate->chal_id = ++cstate->id;
1094 cstate->chal_transmits = 0;
1097 if (mschap_challenge)
1098 for (i = 0; i < chal_len; i++)
1099 *ptr++ = mschap_challenge[i];
1102 /* generate a random string */
1103 for (i = 0; i < chal_len; i++)
1104 *ptr++ = (char) (drand48() * 0xff);
1108 * ChapSendResponse - send a response packet with values as specified
1113 ChapSendResponse(cstate)
1117 int outlen, md_len, name_len;
1119 md_len = cstate->resp_length;
1120 name_len = strlen(cstate->resp_name);
1121 outlen = CHAP_HEADERLEN + sizeof (u_char) + md_len + name_len;
1122 outp = outpacket_buf;
1124 MAKEHEADER(outp, PPP_CHAP);
1126 PUTCHAR(CHAP_RESPONSE, outp); /* we are a response */
1127 PUTCHAR(cstate->resp_id, outp); /* copy id from challenge packet */
1128 PUTSHORT(outlen, outp); /* packet length */
1130 PUTCHAR(md_len, outp); /* length of MD */
1131 BCOPY(cstate->response, outp, md_len); /* copy MD to buffer */
1132 INCPTR(md_len, outp);
1134 BCOPY(cstate->resp_name, outp, name_len); /* append our name */
1136 /* send the packet */
1137 output(cstate->unit, outpacket_buf, outlen + PPP_HDRLEN);
1139 cstate->clientstate = CHAPCS_RESPONSE;
1140 TIMEOUT(ChapResponseTimeout, cstate, cstate->timeouttime);
1141 ++cstate->resp_transmits;
1145 * ChapPrintPkt - print the contents of a CHAP packet.
1147 static char *ChapCodenames[] = {
1148 "Challenge", "Response", "Success", "Failure"
1152 ChapPrintPkt(p, plen, printer, arg)
1155 void (*printer) __P((void *, char *, ...));
1162 if (plen < CHAP_HEADERLEN)
1167 if (len < CHAP_HEADERLEN || len > plen)
1170 if (code >= 1 && code <= sizeof(ChapCodenames) / sizeof(char *))
1171 printer(arg, " %s", ChapCodenames[code-1]);
1173 printer(arg, " code=0x%x", code);
1174 printer(arg, " id=0x%x", id);
1175 len -= CHAP_HEADERLEN;
1177 case CHAP_CHALLENGE:
1185 nlen = len - clen - 1;
1187 for (; clen > 0; --clen) {
1189 printer(arg, "%.2x", x);
1191 printer(arg, ">, name = ");
1192 print_string((char *)p, nlen, printer, arg);
1197 print_string((char *)p, len, printer, arg);
1200 for (clen = len; clen > 0; --clen) {
1202 printer(arg, " %.2x", x);
1206 return len + CHAP_HEADERLEN;