Use correct value for inst->auth_type
[freeradius.git] / src / modules / rlm_mschap / rlm_mschap.c
1 /*
2  * rlm_mschap.c
3  *
4  * Version:     $Id$
5  *
6  *   This program is free software; you can redistribute it and/or modify
7  *   it under the terms of the GNU General Public License as published by
8  *   the Free Software Foundation; either version 2 of the License, or
9  *   (at your option) any later version.
10  *
11  *   This program is distributed in the hope that it will be useful,
12  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *   GNU General Public License for more details.
15  *
16  *   You should have received a copy of the GNU General Public License
17  *   along with this program; if not, write to the Free Software
18  *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  * Copyright 2000,2001  The FreeRADIUS server project
21  */
22
23
24 /*
25  *  mschap.c    MS-CHAP module
26  *
27  *  This implements MS-CHAP, as described in RFC 2548
28  *
29  *  http://www.freeradius.org/rfc/rfc2548.txt
30  *
31  */
32
33 /*
34  *  If you have any questions on NTLM (Samba) passwords
35  *  support, LM authentication and MS-CHAP v2 support
36  *  please contact
37  *
38  *  Vladimir Dubrovin   vlad@sandy.ru
39  *  aka
40  *  ZARAZA              3APA3A@security.nnov.ru
41  */
42
43 /*  MPPE support from Takahiro Wagatsuma <waga@sic.shibaura-it.ac.jp> */
44
45 #include        "autoconf.h"
46 #include        "libradius.h"
47
48 #include        <stdio.h>
49 #include        <stdlib.h>
50 #include        <string.h>
51 #include        <ctype.h>
52
53 #include        "radiusd.h"
54 #include        "modules.h"
55
56 #include        "md4.h"
57 #include        "md5.h"
58 #include        "sha1.h"
59 #include        "rad_assert.h"
60
61 #include        "smbdes.h"
62
63 static const char rcsid[] = "$Id$";
64
65 static const char *letters = "0123456789ABCDEF";
66
67 /*
68  *      hex2bin converts hexadecimal strings into binary
69  */
70 static int hex2bin (const char *szHex, unsigned char* szBin, int len)
71 {
72         char * c1, * c2;
73         int i;
74
75         for (i = 0; i < len; i++) {
76                 if( !(c1 = memchr(letters, toupper((int) szHex[i << 1]), 16)) ||
77                     !(c2 = memchr(letters, toupper((int) szHex[(i << 1) + 1]), 16)))
78                      break;
79                  szBin[i] = ((c1-letters)<<4) + (c2-letters);
80         }
81         return i;
82 }
83
84 /*
85  *      bin2hex creates hexadecimal presentation
86  *      of binary data
87  */
88 static void bin2hex (const unsigned char *szBin, char *szHex, int len)
89 {
90         int i;
91         for (i = 0; i < len; i++) {
92                 szHex[i<<1] = letters[szBin[i] >> 4];
93                 szHex[(i<<1) + 1] = letters[szBin[i] & 0x0F];
94         }
95 }
96
97
98 /* Allowable account control bits */
99 #define ACB_DISABLED   0x0001  /* 1 = User account disabled */
100 #define ACB_HOMDIRREQ  0x0002  /* 1 = Home directory required */
101 #define ACB_PWNOTREQ   0x0004  /* 1 = User password not required */
102 #define ACB_TEMPDUP    0x0008  /* 1 = Temporary duplicate account */
103 #define ACB_NORMAL     0x0010  /* 1 = Normal user account */
104 #define ACB_MNS        0x0020  /* 1 = MNS logon user account */
105 #define ACB_DOMTRUST   0x0040  /* 1 = Interdomain trust account */
106 #define ACB_WSTRUST    0x0080  /* 1 = Workstation trust account */
107 #define ACB_SVRTRUST   0x0100  /* 1 = Server trust account */
108 #define ACB_PWNOEXP    0x0200  /* 1 = User password does not expire */
109 #define ACB_AUTOLOCK   0x0400  /* 1 = Account auto locked */
110
111 static int pdb_decode_acct_ctrl(const char *p)
112 {
113         int acct_ctrl = 0;
114         int finished = 0;
115
116         /*
117          * Check if the account type bits have been encoded after the
118          * NT password (in the form [NDHTUWSLXI]).
119          */
120
121         if (*p != '[') return 0;
122
123         for (p++; *p && !finished; p++) {
124                 switch (*p) {
125                         case 'N': /* 'N'o password. */
126                           acct_ctrl |= ACB_PWNOTREQ;
127                           break;
128
129                         case 'D':  /* 'D'isabled. */
130                           acct_ctrl |= ACB_DISABLED ;
131                           break;
132
133                         case 'H':  /* 'H'omedir required. */
134                           acct_ctrl |= ACB_HOMDIRREQ;
135                           break;
136
137                         case 'T': /* 'T'emp account. */
138                           acct_ctrl |= ACB_TEMPDUP;
139                           break;
140
141                         case 'U': /* 'U'ser account (normal). */
142                           acct_ctrl |= ACB_NORMAL;
143                           break;
144
145                         case 'M': /* 'M'NS logon user account. What is this? */
146                           acct_ctrl |= ACB_MNS;
147                           break;
148
149                         case 'W': /* 'W'orkstation account. */
150                           acct_ctrl |= ACB_WSTRUST;
151                           break;
152
153                         case 'S': /* 'S'erver account. */
154                           acct_ctrl |= ACB_SVRTRUST;
155                           break;
156
157                         case 'L': /* 'L'ocked account. */
158                           acct_ctrl |= ACB_AUTOLOCK;
159                           break;
160
161                         case 'X': /* No 'X'piry on password */
162                           acct_ctrl |= ACB_PWNOEXP;
163                           break;
164
165                         case 'I': /* 'I'nterdomain trust account. */
166                           acct_ctrl |= ACB_DOMTRUST;
167                           break;
168
169                         case ' ': /* ignore spaces */
170                           break;
171
172                         case ':':
173                         case '\n':
174                         case '\0':
175                         case ']':
176                         default:
177                           finished = 1;
178                           break;
179                 }
180         }
181
182         return acct_ctrl;
183 }
184
185
186 /*
187  *      ntpwdhash converts Unicode password to 16-byte NT hash
188  *      with MD4
189  */
190 static void ntpwdhash (unsigned char *szHash, const char *szPassword)
191 {
192         char szUnicodePass[513];
193         int nPasswordLen;
194         int i;
195
196         /*
197          *      NT passwords are unicode.  Convert plain text password
198          *      to unicode by inserting a zero every other byte
199          */
200         nPasswordLen = strlen(szPassword);
201         for (i = 0; i < nPasswordLen; i++) {
202                 szUnicodePass[i << 1] = szPassword[i];
203                 szUnicodePass[(i << 1) + 1] = 0;
204         }
205
206         /* Encrypt Unicode password to a 16-byte MD4 hash */
207         md4_calc(szHash, szUnicodePass, (nPasswordLen<<1) );
208 }
209
210
211 /*
212  *      challenge_hash() is used by mschap2() and auth_response()
213  *      implements RFC2759 ChallengeHash()
214  *      generates 64 bit challenge
215  */
216 static void challenge_hash( const char *peer_challenge,
217                             const char *auth_challenge,
218                             const char *user_name, char *challenge )
219 {
220         SHA1_CTX Context;
221         unsigned char hash[20];
222
223         SHA1Init(&Context);
224         SHA1Update(&Context, peer_challenge, 16);
225         SHA1Update(&Context, auth_challenge, 16);
226         SHA1Update(&Context, user_name, strlen(user_name));
227         SHA1Final(hash, &Context);
228         memcpy(challenge, hash, 8);
229 }
230
231 /*
232  *      auth_response() generates MS-CHAP v2 SUCCESS response
233  *      according to RFC 2759 GenerateAuthenticatorResponse()
234  *      returns 42-octet response string
235  */
236 static void auth_response(const char *username,
237                           const unsigned char *nt_hash_hash,
238                           unsigned char *ntresponse,
239                           char *peer_challenge, char *auth_challenge,
240                           char *response)
241 {
242         SHA1_CTX Context;
243         const unsigned char magic1[39] =
244         {0x4D, 0x61, 0x67, 0x69, 0x63, 0x20, 0x73, 0x65, 0x72, 0x76,
245          0x65, 0x72, 0x20, 0x74, 0x6F, 0x20, 0x63, 0x6C, 0x69, 0x65,
246          0x6E, 0x74, 0x20, 0x73, 0x69, 0x67, 0x6E, 0x69, 0x6E, 0x67,
247          0x20, 0x63, 0x6F, 0x6E, 0x73, 0x74, 0x61, 0x6E, 0x74};
248
249         const unsigned char magic2[41] =
250         {0x50, 0x61, 0x64, 0x20, 0x74, 0x6F, 0x20, 0x6D, 0x61, 0x6B,
251          0x65, 0x20, 0x69, 0x74, 0x20, 0x64, 0x6F, 0x20, 0x6D, 0x6F,
252          0x72, 0x65, 0x20, 0x74, 0x68, 0x61, 0x6E, 0x20, 0x6F, 0x6E,
253          0x65, 0x20, 0x69, 0x74, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6F,
254          0x6E};
255
256         char challenge[8];
257         unsigned char digest[20];
258
259         SHA1Init(&Context);
260         SHA1Update(&Context, nt_hash_hash, 16);
261         SHA1Update(&Context, ntresponse, 24);
262         SHA1Update(&Context, magic1, 39);
263         SHA1Final(digest, &Context);
264         challenge_hash(peer_challenge, auth_challenge, username, challenge);
265         SHA1Init(&Context);
266         SHA1Update(&Context, digest, 20);
267         SHA1Update(&Context, challenge, 8);
268         SHA1Update(&Context, magic2, 41);
269         SHA1Final(digest, &Context);
270
271         /*
272          *      Encode the value of 'Digest' as "S=" followed by
273          *      40 ASCII hexadecimal digits and return it in
274          *      AuthenticatorResponse.
275          *      For example,
276          *      "S=0123456789ABCDEF0123456789ABCDEF01234567"
277          */
278         response[0] = 'S';
279         response[1] = '=';
280         bin2hex(digest, response + 2, 20);
281 }
282
283
284 typedef struct rlm_mschap_t {
285         int use_mppe;
286         int require_encryption;
287         int require_strong;
288         int with_ntdomain_hack; /* this should be in another module */
289         char *passwd_file;
290         char *xlat_name;
291         char *ntlm_auth;
292         char *auth_type;
293 } rlm_mschap_t;
294
295
296 /*
297  *      Does dynamic translation of strings.
298  *
299  *      Pulls NT-Response, LM-Response, or Challenge from MSCHAP
300  *      attributes.
301  */
302 static int mschap_xlat(void *instance, REQUEST *request,
303                        char *fmt, char *out, size_t outlen,
304                        RADIUS_ESCAPE_STRING func)
305 {
306         int             i, data_len;
307         uint8_t         *data = NULL;
308         uint8_t         buffer[32];
309         VALUE_PAIR      *user_name;
310         VALUE_PAIR      *chap_challenge, *response;
311         rlm_mschap_t    *inst = instance;
312
313         chap_challenge = response = NULL;
314
315         func = func;            /* -Wunused */
316
317         /*
318          *      Challenge means MS-CHAPv1 challenge, or
319          *      hash of MS-CHAPv2 challenge, and peer challenge.
320          */
321         if (strcasecmp(fmt, "Challenge") == 0) {
322                 chap_challenge = pairfind(request->packet->vps,
323                                           PW_MSCHAP_CHALLENGE);
324                 if (!chap_challenge) {
325                         DEBUG2("  rlm_mschap: No MS-CHAP-Challenge in the request.");
326                         return 0;
327                 }
328
329                 /*
330                  *      MS-CHAP-Challenges are 8 octets,
331                  *      for MS-CHAPv2
332                  */
333                 if (chap_challenge->length == 8) {
334                         DEBUG2(" mschap1: %02x", chap_challenge->strvalue[0]);
335                         data = chap_challenge->strvalue;
336                         data_len = 8;
337
338                         /*
339                          *      MS-CHAP-Challenges are 16 octets,
340                          *      for MS-CHAPv2.
341                          */
342                 } else if (chap_challenge->length == 16) {
343                         char *username_string;
344
345                         DEBUG2(" mschap2: %02x", chap_challenge->strvalue[0]);
346                         response = pairfind(request->packet->vps,
347                                             PW_MSCHAP2_RESPONSE);
348                         if (!response) {
349                                 DEBUG2("  rlm_mschap: MS-CHAP2-Response is required to calculate MS-CHAPv1 challenge.");
350                                 return 0;
351                         }
352
353                         /*
354                          *      Responses are 50 octets.
355                          */
356                         if (response->length < 50) {
357                                 radlog(L_AUTH, "rlm_mschap: MS-CHAP-Response has the wrong format.");
358                                 return 0;
359                         }
360
361                         user_name = pairfind(request->packet->vps,
362                                              PW_USER_NAME);
363                         if (!user_name) {
364                                 DEBUG2("  rlm_mschap: User-Name is required to calculateMS-CHAPv1 Challenge.");
365                                 return 0;
366                         }
367
368                         /*
369                          *      with_ntdomain_hack moved here, too.
370                          */
371                         if ((username_string = strchr(user_name->strvalue, '\\')) != NULL) {
372                                 if (inst->with_ntdomain_hack) {
373                                         username_string++;
374                                 } else {
375                                         DEBUG2("  rlm_mschap: NT Domain delimeter found, should we have enabled with_ntdomain_hack?");
376                                         username_string = user_name->strvalue;
377                                 }
378                         } else {
379                                 username_string = user_name->strvalue;
380                         }
381
382                         /*
383                          *      Get the MS-CHAPv1 challenge
384                          *      from the MS-CHAPv2 peer challenge,
385                          *      our challenge, and the user name.
386                          */
387                         challenge_hash(response->strvalue + 2,
388                                        chap_challenge->strvalue,
389                                        username_string, buffer);
390                         data = buffer;
391                         data_len = 8;
392                 } else {
393                         DEBUG2("  rlm_mschap: Invalid MS-CHAP challenge length");
394                         return 0;
395                 }
396                 
397                 /*
398                  *      Get the MS-CHAPv1 response, or the MS-CHAPv2
399                  *      response.
400                  */
401         } else if (strcasecmp(fmt, "NT-Response") == 0) {
402                 response = pairfind(request->packet->vps,
403                                     PW_MSCHAP_RESPONSE);
404                 if (!response) response = pairfind(request->packet->vps,
405                                                    PW_MSCHAP2_RESPONSE);
406                 if (!response) {
407                         DEBUG2("  rlm_mschap: No MS-CHAP-Response or MS-CHAP2-Response was found in the request.");
408                         return 0;
409                 }
410
411                 /*
412                  *      For MS-CHAPv1, the NT-Response exists only
413                  *      if the second octet says so.
414                  */
415                 if ((response->attribute == PW_MSCHAP_RESPONSE) &&
416                     ((response->strvalue[1] & 0x01) == 0)) {
417                         DEBUG2("  rlm_mschap: No NT-Response in MS-CHAP-Response");
418                         return 0;
419                 }
420
421                 /*
422                  *      MS-CHAP-Response and MS-CHAP2-Response have
423                  *      the NT-Response at the same offset, and are
424                  *      the same length.
425                  */
426                 data = response->strvalue + 26;
427                 data_len = 24;
428                 
429                 /*
430                  *      LM-Response is deprecated, and exists only
431                  *      in MS-CHAPv1, and not often there.
432                  */
433         } else if (strcasecmp(fmt, "LM-Response") == 0) {
434                 response = pairfind(request->packet->vps,
435                                     PW_MSCHAP_RESPONSE);
436                 if (!response) {
437                         DEBUG2("  rlm_mschap: No MS-CHAP-Response was found in the request.");
438                         return 0;
439                 }
440
441                 /*
442                  *      For MS-CHAPv1, the NT-Response exists only
443                  *      if the second octet says so.
444                  */
445                 if ((response->strvalue[1] & 0x01) != 0) {
446                         DEBUG2("  rlm_mschap: No LM-Response in MS-CHAP-Response");
447                         return 0;
448                 }
449                 data = response->strvalue + 2;
450                 data_len = 24;
451
452                 /*
453                  *      Pull the NT-Domain out of the User-Name, if it exists.
454                  */
455         } else if (strcasecmp(fmt, "NT-Domain") == 0) {
456                 char *p, *q;
457
458                 user_name = pairfind(request->packet->vps, PW_USER_NAME);
459                 if (!user_name) {
460                         DEBUG2("  rlm_mschap: No User-Name was found in the request.");
461                         return 0;
462                 }
463                 
464                 /*
465                  *      First check to see if this is a host/ style User-Name
466                  *      (a la Kerberos host principal)
467                  */
468                 if (strncmp(user_name->strvalue, "host/", 5) == 0) {
469                         /*
470                          *      If we're getting a User-Name formatted in this way,
471                          *      it's likely due to PEAP.  The Windows Domain will be
472                          *      the first domain component following the hostname,
473                          *      or the machine name itself if only a hostname is supplied
474                          */
475                         p = strchr(user_name->strvalue, '.');
476                         if (!p) {
477                                 DEBUG2("  rlm_mschap: setting NT-Domain to same as machine name");
478                                 strNcpy(out, user_name->strvalue + 5, outlen);
479                         } else {
480                                 p++;    /* skip the period */
481                                 q = strchr(p, '.');
482                                 /*
483                                  * use the same hack as below
484                                  * only if another period was found
485                                  */
486                                 if (q) *q = '\0';
487                                 strNcpy(out, p, outlen);
488                                 if (q) *q = '.';
489                         }
490                 } else {
491                         p = strchr(user_name->strvalue, '\\');
492                         if (!p) {
493                                 DEBUG2("  rlm_mschap: No NT-Domain was found in the User-Name.");
494                                 return 0;
495                         }
496
497                         /*
498                          *      Hack.  This is simpler than the alternatives.
499                          */
500                         *p = '\0';
501                         strNcpy(out, user_name->strvalue, outlen);
502                         *p = '\\';
503                 }
504
505                 return strlen(out);
506
507                 /*
508                  *      Pull the User-Name out of the User-Name...
509                  */
510         } else if (strcasecmp(fmt, "User-Name") == 0) {
511                 char *p;
512
513                 user_name = pairfind(request->packet->vps, PW_USER_NAME);
514                 if (!user_name) {
515                         DEBUG2("  rlm_mschap: No User-Name was found in the request.");
516                         return 0;
517                 }
518                 
519                 /*
520                  *      First check to see if this is a host/ style User-Name
521                  *      (a la Kerberos host principal)
522                  */
523                 if (strncmp(user_name->strvalue, "host/", 5) == 0) {
524                         /*
525                          *      If we're getting a User-Name formatted in this way,
526                          *      it's likely due to PEAP.  When authenticating this against
527                          *      a Domain, Windows will expect the User-Name to be in the
528                          *      format of hostname$, the SAM version of the name, so we
529                          *      have to convert it to that here.  We do so by stripping
530                          *      off the first 5 characters (host/), and copying everything
531                          *      from that point to the first period into a string and appending
532                          *      a $ to the end.
533                          */
534                         p = strchr(user_name->strvalue, '.');
535                         /*
536                          * use the same hack as above
537                          * only if a period was found
538                          */
539                         if (p) *p = '\0';
540                         snprintf(out, outlen, "%s$", user_name->strvalue + 5);
541                         if (p) *p = '.';
542                 } else {
543                         p = strchr(user_name->strvalue, '\\');
544                         if (p) {
545                                 p++;    /* skip the backslash */
546                         } else {
547                                 p = user_name->strvalue; /* use the whole User-Name */
548                         }
549                         strNcpy(out, p, outlen);
550                 }
551
552                 return strlen(out);
553
554                 /*
555                  * Return the NT-Hash of the passed string
556                  */
557         } else if (strncasecmp(fmt, "NT-Hash ", 8) == 0) {
558                 char *p;
559
560                 p = fmt + 8;    /* 7 is the length of 'NT-Hash' */
561                 if ((p == '\0')  || (outlen <= 32))
562                         return 0;
563                 DEBUG("rlm_mschap: NT-Hash: %s",p);
564                 ntpwdhash(buffer,p);
565
566                 lrad_bin2hex(buffer, out, 16);
567                 out[32] = '\0';
568                 DEBUG("rlm_mschap: NT-Hash: Result: %s",out);
569                 return 32;
570
571                 /*
572                  * Return the LM-Hash of the passed string
573                  */
574         } else if (strncasecmp(fmt, "LM-Hash ", 8) == 0) {
575                 char *p;
576
577                 p = fmt + 8;    /* 7 is the length of 'LM-Hash' */
578                 if ((p == '\0') || (outlen <= 32))
579                         return 0;
580                         
581                 DEBUG("rlm_mschap: LM-Hash: %s",p);
582                 smbdes_lmpwdhash(p,buffer);
583                 lrad_bin2hex(buffer, out, 16);
584                 out[32] = '\0';
585                 DEBUG("rlm_mschap: LM-Hash: Result: %s",out);
586                 return 32;
587         } else {
588                 DEBUG2("  rlm_mschap: Unknown expansion string \"%s\"",
589                        fmt);
590                 return 0;
591         }
592
593         if (outlen == 0) return 0; /* nowhere to go, don't do anything */
594
595         /*
596          *      Didn't set anything: this is bad.
597          */
598         if (!data) {
599                 DEBUG2("  rlm_mschap: Failed to do anything intelligent");
600                 return 0;
601         }
602
603         /*
604          *      Check the output length.
605          */
606         if (outlen < ((data_len * 2) + 1)) {
607                 data_len = (outlen - 1) / 2;
608         }
609
610         /*
611          *      
612          */
613         for (i = 0; i < data_len; i++) {
614                 sprintf(out + (2 * i), "%02x", data[i]);
615         }
616         out[data_len * 2] = '\0';
617         
618         return data_len * 2;
619 }
620
621
622 static CONF_PARSER module_config[] = {
623         /*
624          *      Cache the password by default.
625          */
626         { "use_mppe",    PW_TYPE_BOOLEAN,
627           offsetof(rlm_mschap_t,use_mppe), NULL, "yes" },
628         { "require_encryption",    PW_TYPE_BOOLEAN,
629           offsetof(rlm_mschap_t,require_encryption), NULL, "no" },
630         { "require_strong",    PW_TYPE_BOOLEAN,
631           offsetof(rlm_mschap_t,require_strong), NULL, "no" },
632         { "with_ntdomain_hack",     PW_TYPE_BOOLEAN,
633           offsetof(rlm_mschap_t,with_ntdomain_hack), NULL, "no" },
634         { "passwd",   PW_TYPE_STRING_PTR,
635           offsetof(rlm_mschap_t, passwd_file), NULL,  NULL },
636         { "ntlm_auth",   PW_TYPE_STRING_PTR,
637           offsetof(rlm_mschap_t, ntlm_auth), NULL,  NULL },
638
639         { NULL, -1, 0, NULL, NULL }             /* end the list */
640 };
641
642 /*
643  *      deinstantiate module, free all memory allocated during
644  *      mschap_instantiate()
645  */
646 static int mschap_detach(void *instance){
647 #define inst ((rlm_mschap_t *)instance)
648         free(inst->passwd_file);
649         free(inst->ntlm_auth);
650         if (inst->xlat_name) {
651                 xlat_unregister(inst->xlat_name, mschap_xlat);
652         }
653         free(instance);
654         return 0;
655 #undef inst
656 }
657
658 /*
659  *      Create instance for our module. Allocate space for
660  *      instance structure and read configuration parameters
661  */
662 static int mschap_instantiate(CONF_SECTION *conf, void **instance)
663 {
664         rlm_mschap_t *inst;
665
666         inst = *instance = rad_malloc(sizeof(*inst));
667         if (!inst) {
668                 return -1;
669         }
670         memset(inst, 0, sizeof(*inst));
671
672         if (cf_section_parse(conf, inst, module_config) < 0) {
673                 free(inst);
674                 return -1;
675         }
676
677         /*
678          *      This module used to support SMB Password files, but it
679          *      made it too complicated.  If the user tries to
680          *      configure an SMB Password file, then die, with an
681          *      error message.
682          */
683         if (inst->passwd_file) {
684                 radlog(L_ERR, "rlm_mschap: SMB password file is no longer supported in this module.  Use rlm_passwd module instead");
685                 mschap_detach(inst);
686                 return -1;
687         }
688
689         /*
690          *      Create the dynamic translation.
691          */
692         inst->xlat_name = cf_section_name2(conf);
693         if (!inst->xlat_name) inst->xlat_name = cf_section_name1(conf);
694         xlat_register(inst->xlat_name, mschap_xlat, inst);
695
696         /*
697          *      For backwards compatibility
698          */
699         if (!dict_valbyname(PW_AUTH_TYPE, inst->xlat_name)) {
700                 inst->auth_type = "MS-CHAP";
701         } else {
702                 inst->auth_type = inst->xlat_name;
703         }
704
705         return 0;
706 }
707
708 /*
709  *      add_reply() adds either MS-CHAP2-Success or MS-CHAP-Error
710  *      attribute to reply packet
711  */
712 static void add_reply(VALUE_PAIR** vp, unsigned char ident,
713                       const char* name, const char* value, int len)
714 {
715         VALUE_PAIR *reply_attr;
716         reply_attr = pairmake(name, "", T_OP_EQ);
717         if (!reply_attr) {
718                 DEBUG("  rlm_mschap: Failed to create attribute %s: %s\n", name, librad_errstr);
719                 return;
720         }
721
722         reply_attr->strvalue[0] = ident;
723         memcpy(reply_attr->strvalue + 1, value, len);
724         reply_attr->length = len + 1;
725         pairadd(vp, reply_attr);
726 }
727
728 /*
729  *      Add MPPE attributes to the reply.
730  */
731 static void mppe_add_reply(VALUE_PAIR **vp,
732                            const char* name, const char* value, int len)
733 {
734        VALUE_PAIR *reply_attr;
735        reply_attr = pairmake(name, "", T_OP_EQ);
736        if (!reply_attr) {
737                DEBUG("rlm_mschap: mppe_add_reply failed to create attribute %s: %s\n", name, librad_errstr);
738                return;
739        }
740
741        memcpy(reply_attr->strvalue, value, len);
742        reply_attr->length = len;
743        pairadd(vp, reply_attr);
744 }
745
746
747 /*
748  *      Do the MS-CHAP stuff.
749  *
750  *      This function is here so that all of the MS-CHAP related
751  *      authentication is in one place, and we can perhaps later replace
752  *      it with code to call winbindd, or something similar.
753  */
754 static int do_mschap(rlm_mschap_t *inst,
755                      REQUEST *request, VALUE_PAIR *password,
756                      uint8_t *challenge, uint8_t *response,
757                      uint8_t *nthashhash)
758 {
759         int             do_ntlm_auth = 0;
760         uint8_t         calculated[24];
761         VALUE_PAIR      *vp = NULL;
762
763         /*
764          *      If we have ntlm_auth configured, use it unless told
765          *      otherwise
766          */
767         if (inst->ntlm_auth) do_ntlm_auth = 1;
768
769         /*
770          *      If we have an ntlm_auth configuration, then we may
771          *      want to use it.
772          */
773         vp = pairfind(request->config_items,
774                       PW_MS_CHAP_USE_NTLM_AUTH);
775         if (vp) do_ntlm_auth = vp->lvalue;
776
777         /*
778          *      No ntlm_auth configured, attribute to tell us to
779          *      use it exists, and we're told to use it.  We don't
780          *      know what to do...
781          */
782         if (!inst->ntlm_auth && do_ntlm_auth) {
783                 DEBUG2("  rlm_mschap: Asked to use ntlm_auth, but it was not configured in the mschap{} section.");
784                 return -1;
785         }
786
787         /*
788          *      Do normal authentication.
789          */
790         if (!do_ntlm_auth) {
791                 /*
792                  *      No password: can't do authentication.
793                  */
794                 if (!password) {
795                         DEBUG2("  rlm_mschap: FAILED: No NT/LM-Password.  Cannot perform authentication.");
796                         return -1;
797                 }
798                 
799                 smbdes_mschap(password->strvalue, challenge, calculated);
800                 if (memcmp(response, calculated, 24) != 0) {
801                         return -1;
802                 }
803                 
804                 /*
805                  *      If the password exists, and is an NT-Password,
806                  *      then calculate the hash of the NT hash.  Doing this
807                  *      here minimizes work for later.
808                  */
809                 if (password && (password->attribute == PW_NT_PASSWORD)) {
810                         md4_calc(nthashhash, password->strvalue, 16);
811                 } else {
812                         memset(nthashhash, 0, 16);
813                 }
814         } else {                /* run ntlm_auth */
815                 int     result;
816                 char    buffer[256];
817
818                 memset(nthashhash, 0, 16);
819
820                 /*
821                  *      Run the program, and expect that we get 16 
822                  */
823                 result = radius_exec_program(inst->ntlm_auth, request,
824                                              TRUE, /* wait */
825                                              buffer, sizeof(buffer),
826                                              NULL, NULL);
827                 if (result != 0) {
828                         char *p;
829                         
830                         DEBUG2("  rlm_mschap: External script failed.");
831
832                         vp = pairmake("Module-Failure-Message", "", T_OP_EQ);
833                         if (!vp) {
834                                 radlog(L_ERR, "No memory");
835                                 return -1;
836                         }
837
838                         p = strchr(buffer, '\n');
839                         if (p) *p = '\0';
840                         snprintf(vp->strvalue, sizeof(vp->strvalue), 
841                                  "rlm_mschap: %s", buffer);
842                         vp->length = strlen(vp->strvalue);
843                         pairadd(&request->packet->vps, vp);
844                         return -1;
845                 }
846
847                 /*
848                  *      Parse the answer as an nthashhash.
849                  *
850                  *      ntlm_auth currently returns:
851                  *      NT_KEY: 000102030405060708090a0b0c0d0e0f
852                  */
853                 if (memcmp(buffer, "NT_KEY: ", 8) != 0) {
854                         DEBUG2("  rlm_mschap: Invalid output from ntlm_auth: expecting NT_KEY");
855                         return -1;
856                 }
857
858                 /*
859                  *      Check the length.  It should be at least 32,
860                  *      with an LF at the end.
861                  */
862                 if (strlen(buffer + 8) < 32) {
863                         DEBUG2("  rlm_mschap: Invalid output from ntlm_auth: NT_KEY has unexpected length");
864                         return -1;
865                 }
866
867                 /*
868                  *      Update the NT hash hash, from the NT key.
869                  */
870                 if (hex2bin(buffer + 8, nthashhash, 16) != 16) {
871                         DEBUG2("  rlm_mschap: Invalid output from ntlm_auth: NT_KEY has non-hex values");
872                         return -1;
873                 }
874         }
875
876         return 0;
877 }
878
879
880 /*
881  *      Data for the hashes.
882  */
883 static const uint8_t SHSpad1[40] =
884                { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
885                  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
886                  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
887                  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
888
889 static const uint8_t SHSpad2[40] =
890                { 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2,
891                  0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2,
892                  0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2,
893                  0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2 };
894
895 static const uint8_t magic1[27] =
896                { 0x54, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x74,
897                  0x68, 0x65, 0x20, 0x4d, 0x50, 0x50, 0x45, 0x20, 0x4d,
898                  0x61, 0x73, 0x74, 0x65, 0x72, 0x20, 0x4b, 0x65, 0x79 };
899
900 static const uint8_t magic2[84] =
901                { 0x4f, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20, 0x63, 0x6c, 0x69,
902                  0x65, 0x6e, 0x74, 0x20, 0x73, 0x69, 0x64, 0x65, 0x2c, 0x20,
903                  0x74, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x74, 0x68,
904                  0x65, 0x20, 0x73, 0x65, 0x6e, 0x64, 0x20, 0x6b, 0x65, 0x79,
905                  0x3b, 0x20, 0x6f, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20, 0x73,
906                  0x65, 0x72, 0x76, 0x65, 0x72, 0x20, 0x73, 0x69, 0x64, 0x65,
907                  0x2c, 0x20, 0x69, 0x74, 0x20, 0x69, 0x73, 0x20, 0x74, 0x68,
908                  0x65, 0x20, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x20,
909                  0x6b, 0x65, 0x79, 0x2e };
910
911 static const uint8_t magic3[84] =
912                { 0x4f, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20, 0x63, 0x6c, 0x69,
913                  0x65, 0x6e, 0x74, 0x20, 0x73, 0x69, 0x64, 0x65, 0x2c, 0x20,
914                  0x74, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x74, 0x68,
915                  0x65, 0x20, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x20,
916                  0x6b, 0x65, 0x79, 0x3b, 0x20, 0x6f, 0x6e, 0x20, 0x74, 0x68,
917                  0x65, 0x20, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x20, 0x73,
918                  0x69, 0x64, 0x65, 0x2c, 0x20, 0x69, 0x74, 0x20, 0x69, 0x73,
919                  0x20, 0x74, 0x68, 0x65, 0x20, 0x73, 0x65, 0x6e, 0x64, 0x20,
920                  0x6b, 0x65, 0x79, 0x2e };
921
922
923 static void mppe_GetMasterKey(uint8_t *nt_hashhash,uint8_t *nt_response,
924                               uint8_t *masterkey)
925 {
926        uint8_t digest[20];
927        SHA1_CTX Context;
928
929        SHA1Init(&Context);
930        SHA1Update(&Context,nt_hashhash,16);
931        SHA1Update(&Context,nt_response,24);
932        SHA1Update(&Context,magic1,27);
933        SHA1Final(digest,&Context);
934
935        memcpy(masterkey,digest,16);
936 }
937
938
939 static void mppe_GetAsymmetricStartKey(uint8_t *masterkey,uint8_t *sesskey,
940                                        int keylen,int issend)
941 {
942        uint8_t digest[20];
943        const uint8_t *s;
944        SHA1_CTX Context;
945
946        memset(digest,0,20);
947
948        if(issend) {
949                s = magic3;
950        } else {
951                s = magic2;
952        }
953
954        SHA1Init(&Context);
955        SHA1Update(&Context,masterkey,16);
956        SHA1Update(&Context,SHSpad1,40);
957        SHA1Update(&Context,s,84);
958        SHA1Update(&Context,SHSpad2,40);
959        SHA1Final(digest,&Context);
960
961        memcpy(sesskey,digest,keylen);
962 }
963
964
965 static void mppe_chap2_get_keys128(uint8_t *nt_hashhash,uint8_t *nt_response,
966                                    uint8_t *sendkey,uint8_t *recvkey)
967 {
968        uint8_t masterkey[16];
969
970        mppe_GetMasterKey(nt_hashhash,nt_response,masterkey);
971
972        mppe_GetAsymmetricStartKey(masterkey,sendkey,16,1);
973        mppe_GetAsymmetricStartKey(masterkey,recvkey,16,0);
974 }
975
976 /*
977  *      Generate MPPE keys.
978  */
979 static void mppe_chap2_gen_keys128(uint8_t *nt_hashhash,uint8_t *response,
980                                    uint8_t *sendkey,uint8_t *recvkey)
981 {
982         uint8_t enckey1[16];
983         uint8_t enckey2[16];
984
985         mppe_chap2_get_keys128(nt_hashhash,response,enckey1,enckey2);
986
987         /*
988          *      dictionary.microsoft defines these attributes as
989          *      'encrypt=2'.  The functions in src/lib/radius.c will
990          *      take care of encrypting/decrypting them as appropriate,
991          *      so that we don't have to.
992          */
993         memcpy (sendkey, enckey1, 16);
994         memcpy (recvkey, enckey2, 16);
995 }
996
997
998 /*
999  *      mschap_authorize() - authorize user if we can authenticate
1000  *      it later. Add Auth-Type attribute if present in module
1001  *      configuration (usually Auth-Type must be "MS-CHAP")
1002  */
1003 static int mschap_authorize(void * instance, REQUEST *request)
1004 {
1005 #define inst ((rlm_mschap_t *)instance)
1006         VALUE_PAIR *challenge = NULL;
1007         VALUE_PAIR *response = NULL;
1008         VALUE_PAIR *vp;
1009
1010         challenge = pairfind(request->packet->vps, PW_MSCHAP_CHALLENGE);
1011         if (!challenge) {
1012                 return RLM_MODULE_NOOP;
1013         }
1014
1015         response = pairfind(request->packet->vps, PW_MSCHAP_RESPONSE);
1016         if (!response)
1017                 response = pairfind(request->packet->vps, PW_MSCHAP2_RESPONSE);
1018
1019         /*
1020          *      Nothing we recognize.  Don't do anything.
1021          */
1022         if (!response) {
1023                 DEBUG2("  rlm_mschap: Found MS-CHAP-Challenge, but no MS-CHAP-Response.");
1024                 return RLM_MODULE_NOOP;
1025         }
1026
1027         DEBUG2("  rlm_mschap: Found MS-CHAP attributes.  Setting 'Auth-Type  = %s'", inst->xlat_name);
1028
1029         /*
1030          *      Set Auth-Type to MS-CHAP.  The authentication code
1031          *      will take care of turning clear-text passwords into
1032          *      NT/LM passwords.
1033          */
1034         vp = pairmake("Auth-Type", inst->auth_type, T_OP_EQ);
1035         if (!vp) return RLM_MODULE_FAIL;
1036         pairmove(&request->config_items, &vp);
1037         pairfree(&vp);          /* may be NULL */
1038
1039         return RLM_MODULE_OK;
1040 #undef inst
1041 }
1042
1043 /*
1044  *      mschap_authenticate() - authenticate user based on given
1045  *      attributes and configuration.
1046  *      We will try to find out password in configuration
1047  *      or in configured passwd file.
1048  *      If one is found we will check paraneters given by NAS.
1049  *
1050  *      If PW_SMB_ACCOUNT_CTRL is not set to ACB_PWNOTREQ we must have
1051  *      one of:
1052  *              PAP:      PW_PASSWORD or
1053  *              MS-CHAP:  PW_MSCHAP_CHALLENGE and PW_MSCHAP_RESPONSE or
1054  *              MS-CHAP2: PW_MSCHAP_CHALLENGE and PW_MSCHAP2_RESPONSE
1055  *      In case of password mismatch or locked account we MAY return
1056  *      PW_MSCHAP_ERROR for MS-CHAP or MS-CHAP v2
1057  *      If MS-CHAP2 succeeds we MUST return
1058  *      PW_MSCHAP2_SUCCESS
1059  */
1060 static int mschap_authenticate(void * instance, REQUEST *request)
1061 {
1062 #define inst ((rlm_mschap_t *)instance)
1063         VALUE_PAIR *challenge = NULL;
1064         VALUE_PAIR *response = NULL;
1065         VALUE_PAIR *password = NULL;
1066         VALUE_PAIR *lm_password, *nt_password, *smb_ctrl;
1067         VALUE_PAIR *username;
1068         VALUE_PAIR *reply_attr;
1069         uint8_t nthashhash[16];
1070         uint8_t msch2resp[42];
1071         char *username_string;
1072         int chap = 0;
1073
1074         /*
1075          *      Find the SMB-Account-Ctrl attribute, or the
1076          *      SMB-Account-Ctrl-Text attribute.
1077          */
1078         smb_ctrl = pairfind(request->config_items, PW_SMB_ACCOUNT_CTRL);
1079         if (!smb_ctrl) {
1080                 password = pairfind(request->config_items,
1081                                     PW_SMB_ACCOUNT_CTRL_TEXT);
1082                 if (password) {
1083                         smb_ctrl = pairmake("SMB-Account-CTRL", "0", T_OP_SET);
1084                         pairadd(&request->config_items, smb_ctrl);
1085                         smb_ctrl->lvalue = pdb_decode_acct_ctrl(password->strvalue);
1086                 }
1087         }
1088
1089         /*
1090          *      We're configured to do MS-CHAP authentication.
1091          *      and account control information exists.  Enforce it.
1092          */
1093         if (smb_ctrl) {
1094                 /*
1095                  *      Password is not required.
1096                  */
1097                 if ((smb_ctrl->lvalue & ACB_PWNOTREQ) != 0) {
1098                         DEBUG2("  rlm_mschap: SMB-Account-Ctrl says no password is required.");
1099                         return RLM_MODULE_OK;
1100                 }
1101         }
1102
1103         /*
1104          *      Decide how to get the passwords.
1105          */
1106         password = pairfind(request->config_items, PW_PASSWORD);
1107
1108         /*
1109          *      We need an LM-Password.
1110          */
1111         lm_password = pairfind(request->config_items, PW_LM_PASSWORD);
1112         if (lm_password) {
1113                 /*
1114                  *      Allow raw octets.
1115                  */
1116                 if ((lm_password->length == 16) ||
1117                     ((lm_password->length == 32) &&
1118                      (hex2bin(lm_password->strvalue,
1119                               lm_password->strvalue, 16) == 16))) {
1120                         DEBUG2("  rlm_mschap: Found LM-Password");
1121                         lm_password->length = 16;
1122
1123                 } else {
1124                         radlog(L_ERR, "rlm_mschap: Invalid LM-Password");
1125                         lm_password = NULL;
1126                 }
1127
1128         } else if (!password) {
1129                 DEBUG2("  rlm_mschap: No User-Password configured.  Cannot create LM-Password.");
1130
1131         } else {                /* there is a configured User-Password */
1132                 lm_password = pairmake("LM-Password", "", T_OP_EQ);
1133                 if (!lm_password) {
1134                         radlog(L_ERR, "No memory");
1135                 } else {
1136                         smbdes_lmpwdhash(password->strvalue,
1137                                        lm_password->strvalue);
1138                         lm_password->length = 16;
1139                         pairadd(&request->config_items, lm_password);
1140                 }
1141         }
1142
1143         /*
1144          *      We need an NT-Password.
1145          */
1146         nt_password = pairfind(request->config_items, PW_NT_PASSWORD);
1147         if (nt_password) {
1148                 if ((nt_password->length == 16) ||
1149                     ((nt_password->length == 32) &&
1150                      (hex2bin(nt_password->strvalue,
1151                               nt_password->strvalue, 16) == 16))) {
1152                         DEBUG2("  rlm_mschap: Found NT-Password");
1153                         nt_password->length = 16;
1154
1155                 } else {
1156                         radlog(L_ERR, "rlm_mschap: Invalid NT-Password");
1157                         nt_password = NULL;
1158                 }
1159         } else if (!password) {
1160                 DEBUG2("  rlm_mschap: No User-Password configured.  Cannot create NT-Password.");
1161
1162         } else {                /* there is a configured User-Password */
1163                 nt_password = pairmake("NT-Password", "", T_OP_EQ);
1164                 if (!nt_password) {
1165                         radlog(L_ERR, "No memory");
1166                         return RLM_MODULE_FAIL;
1167                 } else {
1168                         ntpwdhash(nt_password->strvalue, password->strvalue);
1169                         nt_password->length = 16;
1170                         pairadd(&request->config_items, nt_password);
1171                 }
1172         }
1173
1174         challenge = pairfind(request->packet->vps, PW_MSCHAP_CHALLENGE);
1175         if (!challenge) {
1176                 DEBUG2("  rlm_mschap: No MS-CHAP-Challenge in the request");
1177                 return RLM_MODULE_REJECT;
1178         }
1179
1180         /*
1181          *      We also require an MS-CHAP-Response.
1182          */
1183         response = pairfind(request->packet->vps, PW_MSCHAP_RESPONSE);
1184
1185         /*
1186          *      MS-CHAP-Response, means MS-CHAPv1
1187          */
1188         if (response) {
1189                 int offset;
1190
1191                 /*
1192                  *      MS-CHAPv1 challenges are 8 octets.
1193                  */
1194                 if (challenge->length < 8) {
1195                         radlog(L_AUTH, "rlm_mschap: MS-CHAP-Challenge has the wrong format.");
1196                         return RLM_MODULE_INVALID;
1197                 }
1198
1199                 /*
1200                  *      Responses are 50 octets.
1201                  */
1202                 if (response->length < 50) {
1203                         radlog(L_AUTH, "rlm_mschap: MS-CHAP-Response has the wrong format.");
1204                         return RLM_MODULE_INVALID;
1205                 }
1206
1207                 /*
1208                  *      We are doing MS-CHAP.  Calculate the MS-CHAP
1209                  *      response
1210                  */
1211                 if (response->strvalue[1] & 0x01) {
1212                         DEBUG2("  rlm_mschap: Told to do MS-CHAPv1 with NT-Password");
1213                         password = nt_password;
1214                         offset = 26;
1215                 } else {
1216                         DEBUG2("  rlm_mschap: Told to do MS-CHAPv1 with LM-Password");
1217                         password = lm_password;
1218                         offset = 2;
1219                 }
1220
1221                 /*
1222                  *      Do the MS-CHAP authentication.
1223                  */
1224                 if (do_mschap(inst, request, password, challenge->strvalue,
1225                               response->strvalue + offset, nthashhash) < 0) {
1226                         DEBUG2("  rlm_mschap: MS-CHAP-Response is incorrect.");
1227                         add_reply(&request->reply->vps, *response->strvalue,
1228                                   "MS-CHAP-Error", "E=691 R=1", 9);
1229                         return RLM_MODULE_REJECT;
1230                 }
1231
1232                 chap = 1;
1233
1234         } else if ((response = pairfind(request->packet->vps, PW_MSCHAP2_RESPONSE)) != NULL) {
1235                 uint8_t mschapv1_challenge[16];
1236
1237                 /*
1238                  *      MS-CHAPv2 challenges are 16 octets.
1239                  */
1240                 if (challenge->length < 16) {
1241                         radlog(L_AUTH, "rlm_mschap: MS-CHAP-Challenge has the wrong format.");
1242                         return RLM_MODULE_INVALID;
1243                 }
1244
1245                 /*
1246                  *      Responses are 50 octets.
1247                  */
1248                 if (response->length < 50) {
1249                         radlog(L_AUTH, "rlm_mschap: MS-CHAP-Response has the wrong format.");
1250                         return RLM_MODULE_INVALID;
1251                 }
1252
1253                 /*
1254                  *      We also require a User-Name
1255                  */
1256                 username = pairfind(request->packet->vps, PW_USER_NAME);
1257                 if (!username) {
1258                         radlog(L_AUTH, "rlm_mschap: We require a User-Name for MS-CHAPv2");
1259                         return RLM_MODULE_INVALID;
1260                 }
1261
1262
1263                 /*
1264                  *      with_ntdomain_hack moved here
1265                  */
1266                 if ((username_string = strchr(username->strvalue, '\\')) != NULL) {
1267                         if (inst->with_ntdomain_hack) {
1268                                 username_string++;
1269                         } else {
1270                                 DEBUG2("  rlm_mschap: NT Domain delimeter found, should we have enabled with_ntdomain_hack?");
1271                                 username_string = username->strvalue;
1272                         }
1273                 } else {
1274                         username_string = username->strvalue;
1275                 }
1276
1277                 /*
1278                  *      The old "mschapv2" function has been moved to
1279                  *      here.
1280                  *
1281                  *      MS-CHAPv2 takes some additional data to create an
1282                  *      MS-CHAPv1 challenge, and then does MS-CHAPv1.
1283                  */
1284                 challenge_hash(response->strvalue + 2, /* peer challenge */
1285                                challenge->strvalue, /* our challenge */
1286                                username_string, /* user name */
1287                                mschapv1_challenge); /* resulting challenge */
1288                 
1289                 DEBUG2("  rlm_mschap: Told to do MS-CHAPv2 for %s with NT-Password",
1290                        username_string);
1291
1292                 if (do_mschap(inst, request, nt_password, mschapv1_challenge,
1293                               response->strvalue + 26, nthashhash) < 0) {
1294                         DEBUG2("  rlm_mschap: FAILED: MS-CHAP2-Response is incorrect");
1295                         add_reply(&request->reply->vps, *response->strvalue,
1296                                   "MS-CHAP-Error", "E=691 R=1", 9);
1297                         return RLM_MODULE_REJECT;
1298                 }
1299
1300                 /*
1301                  *      Get the NT-hash-hash, if necessary
1302                  */
1303                 if (nt_password) {
1304                 }
1305
1306                 auth_response(username_string, /* without the domain */
1307                               nthashhash, /* nt-hash-hash */
1308                               response->strvalue + 26, /* peer response */
1309                               response->strvalue + 2, /* peer challenge */
1310                               challenge->strvalue, /* our challenge */
1311                               msch2resp); /* calculated MPPE key */
1312                 add_reply( &request->reply->vps, *response->strvalue,
1313                            "MS-CHAP2-Success", msch2resp, 42);
1314                 chap = 2;
1315
1316         } else {                /* Neither CHAPv1 or CHAPv2 response: die */
1317                 radlog(L_AUTH, "rlm_mschap: No MS-CHAP response found");
1318                 return RLM_MODULE_INVALID;
1319         }
1320
1321         /*
1322          *      We have a CHAP response, but the account may be
1323          *      disabled.  Reject the user with the same error code
1324          *      we use when their password is invalid.
1325          */
1326         if (smb_ctrl) {
1327                 /*
1328                  *      Account is disabled.
1329                  *
1330                  *      They're found, but they don't exist, so we
1331                  *      return 'not found'.
1332                  */
1333                 if (((smb_ctrl->lvalue & ACB_DISABLED) != 0) ||
1334                     ((smb_ctrl->lvalue & ACB_NORMAL) == 0)) {
1335                         DEBUG2("  rlm_mschap: SMB-Account-Ctrl says that the account is disabled, or is not a normal account.");
1336                         add_reply( &request->reply->vps, *response->strvalue,
1337                                    "MS-CHAP-Error", "E=691 R=1", 9);
1338                         return RLM_MODULE_NOTFOUND;
1339                 }
1340
1341                 /*
1342                  *      User is locked out.
1343                  */
1344                 if ((smb_ctrl->lvalue & ACB_AUTOLOCK) != 0) {
1345                         DEBUG2("  rlm_mschap: SMB-Account-Ctrl says that the account is locked out.");
1346                         add_reply( &request->reply->vps, *response->strvalue,
1347                                    "MS-CHAP-Error", "E=647 R=0", 9);
1348                         return RLM_MODULE_USERLOCK;
1349                 }
1350         }
1351
1352         /* now create MPPE attributes */
1353         if (inst->use_mppe) {
1354                 uint8_t mppe_sendkey[34];
1355                 uint8_t mppe_recvkey[34];
1356
1357                 if (chap == 1){
1358                         DEBUG2("rlm_mschap: adding MS-CHAPv1 MPPE keys");
1359                         memset(mppe_sendkey, 0, 32);
1360                         if (lm_password) {
1361                                 memcpy(mppe_sendkey, lm_password->strvalue, 8);
1362                         }
1363
1364                         /*
1365                          *      According to RFC 2548 we
1366                          *      should send NT hash.  But in
1367                          *      practice it doesn't work.
1368                          *      Instead, we should send nthashhash
1369                          *
1370                          *      This is an error on RFC 2548.
1371                          */
1372                         /*
1373                          *      do_mschap cares to zero nthashhash if NT hash
1374                          *      is not available.
1375                          */
1376                         memcpy(mppe_sendkey + 8,
1377                                nthashhash, 16);
1378                         mppe_add_reply(&request->reply->vps,
1379                                        "MS-CHAP-MPPE-Keys",
1380                                        mppe_sendkey, 32);
1381                 } else if (chap == 2) {
1382                         DEBUG2("rlm_mschap: adding MS-CHAPv2 MPPE keys");
1383                         mppe_chap2_gen_keys128(nthashhash,
1384                                                response->strvalue + 26,
1385                                                mppe_sendkey, mppe_recvkey);
1386                         
1387                         mppe_add_reply(&request->reply->vps,
1388                                        "MS-MPPE-Recv-Key",
1389                                        mppe_recvkey, 16);
1390                         mppe_add_reply(&request->reply->vps,
1391                                        "MS-MPPE-Send-Key",
1392                                        mppe_sendkey, 16);
1393
1394                 }
1395                 reply_attr = pairmake("MS-MPPE-Encryption-Policy",
1396                                       (inst->require_encryption)? "0x00000002":"0x00000001",
1397                                       T_OP_EQ);
1398                 rad_assert(reply_attr != NULL);
1399                 pairadd(&request->reply->vps, reply_attr);
1400                 reply_attr = pairmake("MS-MPPE-Encryption-Types",
1401                                       (inst->require_strong)? "0x00000004":"0x00000006",
1402                                       T_OP_EQ);
1403                 rad_assert(reply_attr != NULL);
1404                 pairadd(&request->reply->vps, reply_attr);
1405
1406         } /* else we weren't asked to use MPPE */
1407
1408         return RLM_MODULE_OK;
1409 #undef inst
1410 }
1411
1412 module_t rlm_mschap = {
1413   "MS-CHAP",
1414   RLM_TYPE_THREAD_SAFE,         /* type */
1415   NULL,                         /* initialize */
1416   mschap_instantiate,           /* instantiation */
1417   {
1418           mschap_authenticate,  /* authenticate */
1419           mschap_authorize,     /* authorize */
1420           NULL,                 /* pre-accounting */
1421           NULL,                 /* accounting */
1422           NULL,                 /* checksimul */
1423           NULL,                 /* pre-proxy */
1424           NULL,                 /* post-proxy */
1425           NULL                  /* post-auth */
1426   },
1427   mschap_detach,                /* detach */
1428   NULL,                         /* destroy */
1429 };