libcli/smb Move cifs posix helper functions and headers in common
[ira/wip.git] / libcli / auth / smbencrypt.c
1 /*
2    Unix SMB/CIFS implementation.
3    SMB parameters and setup
4    Copyright (C) Andrew Tridgell 1992-1998
5    Modified by Jeremy Allison 1995.
6    Copyright (C) Jeremy Allison 1995-2000.
7    Copyright (C) Luke Kennethc Casson Leighton 1996-2000.
8    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2002-2003
9
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 3 of the License, or
13    (at your option) any later version.
14
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with this program.  If not, see <http://www.gnu.org/licenses/>.
22 */
23
24 #include "includes.h"
25 #include "system/time.h"
26 #include "../libcli/auth/msrpc_parse.h"
27 #include "../lib/crypto/crypto.h"
28 #include "../libcli/auth/libcli_auth.h"
29 #include "../librpc/gen_ndr/ntlmssp.h"
30
31 void SMBencrypt_hash(const uint8_t lm_hash[16], const uint8_t *c8, uint8_t p24[24])
32 {
33         uint8_t p21[21];
34
35         memset(p21,'\0',21);
36         memcpy(p21, lm_hash, 16);
37
38         SMBOWFencrypt(p21, c8, p24);
39
40 #ifdef DEBUG_PASSWORD
41         DEBUG(100,("SMBencrypt_hash: lm#, challenge, response\n"));
42         dump_data(100, p21, 16);
43         dump_data(100, c8, 8);
44         dump_data(100, p24, 24);
45 #endif
46 }
47
48 /*
49    This implements the X/Open SMB password encryption
50    It takes a password ('unix' string), a 8 byte "crypt key"
51    and puts 24 bytes of encrypted password into p24
52
53    Returns False if password must have been truncated to create LM hash
54 */
55
56 bool SMBencrypt(const char *passwd, const uint8_t *c8, uint8_t p24[24])
57 {
58         bool ret;
59         uint8_t lm_hash[16];
60
61         ret = E_deshash(passwd, lm_hash);
62         SMBencrypt_hash(lm_hash, c8, p24);
63         return ret;
64 }
65
66 /**
67  * Creates the MD4 Hash of the users password in NT UNICODE.
68  * @param passwd password in 'unix' charset.
69  * @param p16 return password hashed with md4, caller allocated 16 byte buffer
70  */
71
72 bool E_md4hash(const char *passwd, uint8_t p16[16])
73 {
74         size_t len;
75         smb_ucs2_t *wpwd;
76         bool ret;
77
78         ret = push_ucs2_talloc(NULL, &wpwd, passwd, &len);
79         if (!ret || len < 2) {
80                 /* We don't want to return fixed data, as most callers
81                  * don't check */
82                 mdfour(p16, (const uint8_t *)passwd, strlen(passwd));
83                 return false;
84         }
85
86         len -= 2;
87         mdfour(p16, (const uint8_t *)wpwd, len);
88
89         talloc_free(wpwd);
90         return true;
91 }
92
93 /**
94  * Creates the MD5 Hash of a combination of 16 byte salt and 16 byte NT hash.
95  * @param 16 byte salt.
96  * @param 16 byte NT hash.
97  * @param 16 byte return hashed with md5, caller allocated 16 byte buffer
98  */
99
100 void E_md5hash(const uint8_t salt[16], const uint8_t nthash[16], uint8_t hash_out[16])
101 {
102         struct MD5Context tctx;
103         MD5Init(&tctx);
104         MD5Update(&tctx, salt, 16);
105         MD5Update(&tctx, nthash, 16);
106         MD5Final(hash_out, &tctx);
107 }
108
109 /**
110  * Creates the DES forward-only Hash of the users password in DOS ASCII charset
111  * @param passwd password in 'unix' charset.
112  * @param p16 return password hashed with DES, caller allocated 16 byte buffer
113  * @return false if password was > 14 characters, and therefore may be incorrect, otherwise true
114  * @note p16 is filled in regardless
115  */
116
117 bool E_deshash(const char *passwd, uint8_t p16[16])
118 {
119         bool ret;
120         uint8_t dospwd[14];
121         TALLOC_CTX *mem_ctx;
122
123         size_t converted_size;
124
125         char *tmpbuf;
126
127         ZERO_STRUCT(dospwd);
128
129 #if _SAMBA_BUILD_ == 3
130         mem_ctx = talloc_tos();
131 #else
132         mem_ctx = NULL;
133 #endif
134         tmpbuf = strupper_talloc(mem_ctx, passwd);
135         if (tmpbuf == NULL) {
136                 /* Too many callers don't check this result, we need to fill in the buffer with something */
137                 strlcpy((char *)dospwd, passwd ? passwd : "", sizeof(dospwd));
138                 E_P16(dospwd, p16);
139                 return false;
140         }
141
142         ZERO_STRUCT(dospwd);
143
144         ret = convert_string_error(CH_UNIX, CH_DOS, tmpbuf, strlen(tmpbuf), dospwd, sizeof(dospwd), &converted_size);
145         talloc_free(tmpbuf);
146
147         /* Only the first 14 chars are considered, password need not
148          * be null terminated.  We do this in the error and success
149          * case to avoid returning a fixed 'password' buffer, but
150          * callers should not use it when E_deshash returns false */
151
152         E_P16((const uint8_t *)dospwd, p16);
153
154         ZERO_STRUCT(dospwd);
155
156         return ret;
157 }
158
159 /**
160  * Creates the MD4 and DES (LM) Hash of the users password.
161  * MD4 is of the NT Unicode, DES is of the DOS UPPERCASE password.
162  * @param passwd password in 'unix' charset.
163  * @param nt_p16 return password hashed with md4, caller allocated 16 byte buffer
164  * @param p16 return password hashed with des, caller allocated 16 byte buffer
165  */
166
167 /* Does both the NT and LM owfs of a user's password */
168 void nt_lm_owf_gen(const char *pwd, uint8_t nt_p16[16], uint8_t p16[16])
169 {
170         /* Calculate the MD4 hash (NT compatible) of the password */
171         memset(nt_p16, '\0', 16);
172         E_md4hash(pwd, nt_p16);
173
174 #ifdef DEBUG_PASSWORD
175         DEBUG(100,("nt_lm_owf_gen: pwd, nt#\n"));
176         dump_data(120, (const uint8_t *)pwd, strlen(pwd));
177         dump_data(100, nt_p16, 16);
178 #endif
179
180         E_deshash(pwd, (uint8_t *)p16);
181
182 #ifdef DEBUG_PASSWORD
183         DEBUG(100,("nt_lm_owf_gen: pwd, lm#\n"));
184         dump_data(120, (const uint8_t *)pwd, strlen(pwd));
185         dump_data(100, p16, 16);
186 #endif
187 }
188
189 /* Does both the NTLMv2 owfs of a user's password */
190 bool ntv2_owf_gen(const uint8_t owf[16],
191                   const char *user_in, const char *domain_in,
192                   bool upper_case_domain, /* Transform the domain into UPPER case */
193                   uint8_t kr_buf[16])
194 {
195         smb_ucs2_t *user;
196         smb_ucs2_t *domain;
197         size_t user_byte_len;
198         size_t domain_byte_len;
199         bool ret;
200
201         HMACMD5Context ctx;
202         TALLOC_CTX *mem_ctx = talloc_init("ntv2_owf_gen for %s\\%s", domain_in, user_in);
203
204         if (!mem_ctx) {
205                 return false;
206         }
207
208         if (!user_in) {
209                 user_in = "";
210         }
211
212         if (!domain_in) {
213                 domain_in = "";
214         }
215
216         user_in = strupper_talloc(mem_ctx, user_in);
217         if (user_in == NULL) {
218                 talloc_free(mem_ctx);
219                 return false;
220         }
221
222         if (upper_case_domain) {
223                 domain_in = strupper_talloc(mem_ctx, domain_in);
224                 if (domain_in == NULL) {
225                         talloc_free(mem_ctx);
226                         return false;
227                 }
228         }
229
230         ret = push_ucs2_talloc(mem_ctx, &user, user_in, &user_byte_len );
231         if (!ret) {
232                 DEBUG(0, ("push_uss2_talloc() for user failed)\n"));
233                 talloc_free(mem_ctx);
234                 return false;
235         }
236
237         ret = push_ucs2_talloc(mem_ctx, &domain, domain_in, &domain_byte_len);
238         if (!ret) {
239                 DEBUG(0, ("push_ucs2_talloc() for domain failed\n"));
240                 talloc_free(mem_ctx);
241                 return false;
242         }
243
244         SMB_ASSERT(user_byte_len >= 2);
245         SMB_ASSERT(domain_byte_len >= 2);
246
247         /* We don't want null termination */
248         user_byte_len = user_byte_len - 2;
249         domain_byte_len = domain_byte_len - 2;
250
251         hmac_md5_init_limK_to_64(owf, 16, &ctx);
252         hmac_md5_update((uint8_t *)user, user_byte_len, &ctx);
253         hmac_md5_update((uint8_t *)domain, domain_byte_len, &ctx);
254         hmac_md5_final(kr_buf, &ctx);
255
256 #ifdef DEBUG_PASSWORD
257         DEBUG(100, ("ntv2_owf_gen: user, domain, owfkey, kr\n"));
258         dump_data(100, (uint8_t *)user, user_byte_len);
259         dump_data(100, (uint8_t *)domain, domain_byte_len);
260         dump_data(100, owf, 16);
261         dump_data(100, kr_buf, 16);
262 #endif
263
264         talloc_free(mem_ctx);
265         return true;
266 }
267
268 /* Does the des encryption from the NT or LM MD4 hash. */
269 void SMBOWFencrypt(const uint8_t passwd[16], const uint8_t *c8, uint8_t p24[24])
270 {
271         uint8_t p21[21];
272
273         ZERO_STRUCT(p21);
274
275         memcpy(p21, passwd, 16);
276         E_P24(p21, c8, p24);
277 }
278
279 /* Does the des encryption. */
280
281 void SMBNTencrypt_hash(const uint8_t nt_hash[16], uint8_t *c8, uint8_t *p24)
282 {
283         uint8_t p21[21];
284
285         memset(p21,'\0',21);
286         memcpy(p21, nt_hash, 16);
287         SMBOWFencrypt(p21, c8, p24);
288
289 #ifdef DEBUG_PASSWORD
290         DEBUG(100,("SMBNTencrypt: nt#, challenge, response\n"));
291         dump_data(100, p21, 16);
292         dump_data(100, c8, 8);
293         dump_data(100, p24, 24);
294 #endif
295 }
296
297 /* Does the NT MD4 hash then des encryption. Plaintext version of the above. */
298
299 void SMBNTencrypt(const char *passwd, uint8_t *c8, uint8_t *p24)
300 {
301         uint8_t nt_hash[16];
302         E_md4hash(passwd, nt_hash);
303         SMBNTencrypt_hash(nt_hash, c8, p24);
304 }
305
306
307 /* Does the md5 encryption from the Key Response for NTLMv2. */
308 void SMBOWFencrypt_ntv2(const uint8_t kr[16],
309                         const DATA_BLOB *srv_chal,
310                         const DATA_BLOB *smbcli_chal,
311                         uint8_t resp_buf[16])
312 {
313         HMACMD5Context ctx;
314
315         hmac_md5_init_limK_to_64(kr, 16, &ctx);
316         hmac_md5_update(srv_chal->data, srv_chal->length, &ctx);
317         hmac_md5_update(smbcli_chal->data, smbcli_chal->length, &ctx);
318         hmac_md5_final(resp_buf, &ctx);
319
320 #ifdef DEBUG_PASSWORD
321         DEBUG(100, ("SMBOWFencrypt_ntv2: srv_chal, smbcli_chal, resp_buf\n"));
322         dump_data(100, srv_chal->data, srv_chal->length);
323         dump_data(100, smbcli_chal->data, smbcli_chal->length);
324         dump_data(100, resp_buf, 16);
325 #endif
326 }
327
328 void SMBsesskeygen_ntv2(const uint8_t kr[16],
329                         const uint8_t * nt_resp, uint8_t sess_key[16])
330 {
331         /* a very nice, 128 bit, variable session key */
332
333         HMACMD5Context ctx;
334
335         hmac_md5_init_limK_to_64(kr, 16, &ctx);
336         hmac_md5_update(nt_resp, 16, &ctx);
337         hmac_md5_final((uint8_t *)sess_key, &ctx);
338
339 #ifdef DEBUG_PASSWORD
340         DEBUG(100, ("SMBsesskeygen_ntv2:\n"));
341         dump_data(100, sess_key, 16);
342 #endif
343 }
344
345 void SMBsesskeygen_ntv1(const uint8_t kr[16], uint8_t sess_key[16])
346 {
347         /* yes, this session key does not change - yes, this
348            is a problem - but it is 128 bits */
349
350         mdfour((uint8_t *)sess_key, kr, 16);
351
352 #ifdef DEBUG_PASSWORD
353         DEBUG(100, ("SMBsesskeygen_ntv1:\n"));
354         dump_data(100, sess_key, 16);
355 #endif
356 }
357
358 void SMBsesskeygen_lm_sess_key(const uint8_t lm_hash[16],
359                                const uint8_t lm_resp[24], /* only uses 8 */
360                                uint8_t sess_key[16])
361 {
362         /* Calculate the LM session key (effective length 40 bits,
363            but changes with each session) */
364         uint8_t p24[24];
365         uint8_t partial_lm_hash[14];
366
367         memcpy(partial_lm_hash, lm_hash, 8);
368         memset(partial_lm_hash + 8, 0xbd, 6);
369
370         des_crypt56(p24,   lm_resp, partial_lm_hash,     1);
371         des_crypt56(p24+8, lm_resp, partial_lm_hash + 7, 1);
372
373         memcpy(sess_key, p24, 16);
374
375 #ifdef DEBUG_PASSWORD
376         DEBUG(100, ("SMBsesskeygen_lm_sess_key: \n"));
377         dump_data(100, sess_key, 16);
378 #endif
379 }
380
381 DATA_BLOB NTLMv2_generate_names_blob(TALLOC_CTX *mem_ctx,
382                                      const char *hostname,
383                                      const char *domain)
384 {
385         DATA_BLOB names_blob = data_blob_talloc(mem_ctx, NULL, 0);
386
387         /* Deliberately ignore return here.. */
388         if (hostname != NULL) {
389                 (void)msrpc_gen(mem_ctx, &names_blob,
390                           "aaa",
391                           MsvAvNbDomainName, domain,
392                           MsvAvNbComputerName, hostname,
393                           MsvAvEOL, "");
394         } else {
395                 (void)msrpc_gen(mem_ctx, &names_blob,
396                           "aa",
397                           MsvAvNbDomainName, domain,
398                           MsvAvEOL, "");
399         }
400         return names_blob;
401 }
402
403 static DATA_BLOB NTLMv2_generate_client_data(TALLOC_CTX *mem_ctx, const DATA_BLOB *names_blob)
404 {
405         uint8_t client_chal[8];
406         DATA_BLOB response = data_blob(NULL, 0);
407         uint8_t long_date[8];
408         NTTIME nttime;
409
410         unix_to_nt_time(&nttime, time(NULL));
411
412         generate_random_buffer(client_chal, sizeof(client_chal));
413
414         push_nttime(long_date, 0, nttime);
415
416         /* See http://www.ubiqx.org/cifs/SMB.html#SMB.8.5 */
417
418         /* Deliberately ignore return here.. */
419         (void)msrpc_gen(mem_ctx, &response, "ddbbdb",
420                   0x00000101,     /* Header  */
421                   0,              /* 'Reserved'  */
422                   long_date, 8,   /* Timestamp */
423                   client_chal, 8, /* client challenge */
424                   0,              /* Unknown */
425                   names_blob->data, names_blob->length);        /* End of name list */
426
427         return response;
428 }
429
430 static DATA_BLOB NTLMv2_generate_response(TALLOC_CTX *out_mem_ctx,
431                                           const uint8_t ntlm_v2_hash[16],
432                                           const DATA_BLOB *server_chal,
433                                           const DATA_BLOB *names_blob)
434 {
435         uint8_t ntlmv2_response[16];
436         DATA_BLOB ntlmv2_client_data;
437         DATA_BLOB final_response;
438
439         TALLOC_CTX *mem_ctx = talloc_named(out_mem_ctx, 0,
440                                            "NTLMv2_generate_response internal context");
441
442         if (!mem_ctx) {
443                 return data_blob(NULL, 0);
444         }
445
446         /* NTLMv2 */
447         /* generate some data to pass into the response function - including
448            the hostname and domain name of the server */
449         ntlmv2_client_data = NTLMv2_generate_client_data(mem_ctx, names_blob);
450
451         /* Given that data, and the challenge from the server, generate a response */
452         SMBOWFencrypt_ntv2(ntlm_v2_hash, server_chal, &ntlmv2_client_data, ntlmv2_response);
453
454         final_response = data_blob_talloc(out_mem_ctx, NULL, sizeof(ntlmv2_response) + ntlmv2_client_data.length);
455
456         memcpy(final_response.data, ntlmv2_response, sizeof(ntlmv2_response));
457
458         memcpy(final_response.data+sizeof(ntlmv2_response),
459                ntlmv2_client_data.data, ntlmv2_client_data.length);
460
461         talloc_free(mem_ctx);
462
463         return final_response;
464 }
465
466 static DATA_BLOB LMv2_generate_response(TALLOC_CTX *mem_ctx,
467                                         const uint8_t ntlm_v2_hash[16],
468                                         const DATA_BLOB *server_chal)
469 {
470         uint8_t lmv2_response[16];
471         DATA_BLOB lmv2_client_data = data_blob_talloc(mem_ctx, NULL, 8);
472         DATA_BLOB final_response = data_blob_talloc(mem_ctx, NULL,24);
473
474         /* LMv2 */
475         /* client-supplied random data */
476         generate_random_buffer(lmv2_client_data.data, lmv2_client_data.length);
477
478         /* Given that data, and the challenge from the server, generate a response */
479         SMBOWFencrypt_ntv2(ntlm_v2_hash, server_chal, &lmv2_client_data, lmv2_response);
480         memcpy(final_response.data, lmv2_response, sizeof(lmv2_response));
481
482         /* after the first 16 bytes is the random data we generated above,
483            so the server can verify us with it */
484         memcpy(final_response.data+sizeof(lmv2_response),
485                lmv2_client_data.data, lmv2_client_data.length);
486
487         data_blob_free(&lmv2_client_data);
488
489         return final_response;
490 }
491
492 bool SMBNTLMv2encrypt_hash(TALLOC_CTX *mem_ctx,
493                            const char *user, const char *domain, const uint8_t nt_hash[16],
494                            const DATA_BLOB *server_chal,
495                            const DATA_BLOB *names_blob,
496                            DATA_BLOB *lm_response, DATA_BLOB *nt_response,
497                            DATA_BLOB *lm_session_key, DATA_BLOB *user_session_key)
498 {
499         uint8_t ntlm_v2_hash[16];
500
501         /* We don't use the NT# directly.  Instead we use it mashed up with
502            the username and domain.
503            This prevents username swapping during the auth exchange
504         */
505         if (!ntv2_owf_gen(nt_hash, user, domain, true, ntlm_v2_hash)) {
506                 return false;
507         }
508
509         if (nt_response) {
510                 *nt_response = NTLMv2_generate_response(mem_ctx,
511                                                         ntlm_v2_hash, server_chal,
512                                                         names_blob);
513                 if (user_session_key) {
514                         *user_session_key = data_blob_talloc(mem_ctx, NULL, 16);
515
516                         /* The NTLMv2 calculations also provide a session key, for signing etc later */
517                         /* use only the first 16 bytes of nt_response for session key */
518                         SMBsesskeygen_ntv2(ntlm_v2_hash, nt_response->data, user_session_key->data);
519                 }
520         }
521
522         /* LMv2 */
523
524         if (lm_response) {
525                 *lm_response = LMv2_generate_response(mem_ctx,
526                                                       ntlm_v2_hash, server_chal);
527                 if (lm_session_key) {
528                         *lm_session_key = data_blob_talloc(mem_ctx, NULL, 16);
529
530                         /* The NTLMv2 calculations also provide a session key, for signing etc later */
531                         /* use only the first 16 bytes of lm_response for session key */
532                         SMBsesskeygen_ntv2(ntlm_v2_hash, lm_response->data, lm_session_key->data);
533                 }
534         }
535
536         return true;
537 }
538
539 bool SMBNTLMv2encrypt(TALLOC_CTX *mem_ctx,
540                       const char *user, const char *domain,
541                       const char *password,
542                       const DATA_BLOB *server_chal,
543                       const DATA_BLOB *names_blob,
544                       DATA_BLOB *lm_response, DATA_BLOB *nt_response,
545                       DATA_BLOB *lm_session_key, DATA_BLOB *user_session_key)
546 {
547         uint8_t nt_hash[16];
548         E_md4hash(password, nt_hash);
549
550         return SMBNTLMv2encrypt_hash(mem_ctx,
551                                      user, domain, nt_hash, server_chal, names_blob,
552                                      lm_response, nt_response, lm_session_key, user_session_key);
553 }
554
555 /***********************************************************
556  encode a password buffer with a unicode password.  The buffer
557  is filled with random data to make it harder to attack.
558 ************************************************************/
559 bool encode_pw_buffer(uint8_t buffer[516], const char *password, int string_flags)
560 {
561         uint8_t new_pw[512];
562         ssize_t new_pw_len;
563
564         /* the incoming buffer can be any alignment. */
565         string_flags |= STR_NOALIGN;
566
567         new_pw_len = push_string(new_pw,
568                                  password,
569                                  sizeof(new_pw), string_flags);
570         if (new_pw_len == -1) {
571                 return false;
572         }
573
574         memcpy(&buffer[512 - new_pw_len], new_pw, new_pw_len);
575
576         generate_random_buffer(buffer, 512 - new_pw_len);
577
578         /*
579          * The length of the new password is in the last 4 bytes of
580          * the data buffer.
581          */
582         SIVAL(buffer, 512, new_pw_len);
583         ZERO_STRUCT(new_pw);
584         return true;
585 }
586
587
588 /***********************************************************
589  decode a password buffer
590  *new_pw_len is the length in bytes of the possibly mulitbyte
591  returned password including termination.
592 ************************************************************/
593
594 bool decode_pw_buffer(TALLOC_CTX *ctx,
595                       uint8_t in_buffer[516],
596                       char **pp_new_pwrd,
597                       size_t *new_pw_len,
598                       charset_t string_charset)
599 {
600         int byte_len=0;
601
602         *pp_new_pwrd = NULL;
603         *new_pw_len = 0;
604
605         /*
606           Warning !!! : This function is called from some rpc call.
607           The password IN the buffer may be a UNICODE string.
608           The password IN new_pwrd is an ASCII string
609           If you reuse that code somewhere else check first.
610         */
611
612         /* The length of the new password is in the last 4 bytes of the data buffer. */
613
614         byte_len = IVAL(in_buffer, 512);
615
616 #ifdef DEBUG_PASSWORD
617         dump_data(100, in_buffer, 516);
618 #endif
619
620         /* Password cannot be longer than the size of the password buffer */
621         if ( (byte_len < 0) || (byte_len > 512)) {
622                 DEBUG(0, ("decode_pw_buffer: incorrect password length (%d).\n", byte_len));
623                 DEBUG(0, ("decode_pw_buffer: check that 'encrypt passwords = yes'\n"));
624                 return false;
625         }
626
627         /* decode into the return buffer. */
628         if (!convert_string_talloc(ctx, string_charset, CH_UNIX,
629                                    &in_buffer[512 - byte_len],
630                                    byte_len,
631                                    (void *)pp_new_pwrd,
632                                    new_pw_len)) {
633                 DEBUG(0, ("decode_pw_buffer: failed to convert incoming password\n"));
634                 return false;
635         }
636
637 #ifdef DEBUG_PASSWORD
638         DEBUG(100,("decode_pw_buffer: new_pwrd: "));
639         dump_data(100, (uint8_t *)*pp_new_pwrd, *new_pw_len);
640         DEBUG(100,("multibyte len:%lu\n", (unsigned long int)*new_pw_len));
641         DEBUG(100,("original char len:%d\n", byte_len/2));
642 #endif
643
644         return true;
645 }
646
647 /***********************************************************
648  Decode an arc4 encrypted password change buffer.
649 ************************************************************/
650
651 void encode_or_decode_arc4_passwd_buffer(unsigned char pw_buf[532], const DATA_BLOB *psession_key)
652 {
653         struct MD5Context tctx;
654         unsigned char key_out[16];
655
656         /* Confounder is last 16 bytes. */
657
658         MD5Init(&tctx);
659         MD5Update(&tctx, &pw_buf[516], 16);
660         MD5Update(&tctx, psession_key->data, psession_key->length);
661         MD5Final(key_out, &tctx);
662         /* arc4 with key_out. */
663         arcfour_crypt(pw_buf, key_out, 516);
664 }
665
666 /***********************************************************
667  encode a password buffer with an already unicode password.  The
668  rest of the buffer is filled with random data to make it harder to attack.
669 ************************************************************/
670 bool set_pw_in_buffer(uint8_t buffer[516], DATA_BLOB *password)
671 {
672         if (password->length > 512) {
673                 return false;
674         }
675
676         memcpy(&buffer[512 - password->length], password->data, password->length);
677
678         generate_random_buffer(buffer, 512 - password->length);
679
680         /*
681          * The length of the new password is in the last 4 bytes of
682          * the data buffer.
683          */
684         SIVAL(buffer, 512, password->length);
685         return true;
686 }
687
688 /***********************************************************
689  decode a password buffer
690  *new_pw_size is the length in bytes of the extracted unicode password
691 ************************************************************/
692 bool extract_pw_from_buffer(TALLOC_CTX *mem_ctx,
693                             uint8_t in_buffer[516], DATA_BLOB *new_pass)
694 {
695         int byte_len=0;
696
697         /* The length of the new password is in the last 4 bytes of the data buffer. */
698
699         byte_len = IVAL(in_buffer, 512);
700
701 #ifdef DEBUG_PASSWORD
702         dump_data(100, in_buffer, 516);
703 #endif
704
705         /* Password cannot be longer than the size of the password buffer */
706         if ( (byte_len < 0) || (byte_len > 512)) {
707                 return false;
708         }
709
710         *new_pass = data_blob_talloc(mem_ctx, &in_buffer[512 - byte_len], byte_len);
711
712         if (!new_pass->data) {
713                 return false;
714         }
715
716         return true;
717 }
718
719
720 /* encode a wkssvc_PasswordBuffer:
721  *
722  * similar to samr_CryptPasswordEx. Different: 8byte confounder (instead of
723  * 16byte), confounder in front of the 516 byte buffer (instead of after that
724  * buffer), calling MD5Update() first with session_key and then with confounder
725  * (vice versa in samr) - Guenther */
726
727 void encode_wkssvc_join_password_buffer(TALLOC_CTX *mem_ctx,
728                                         const char *pwd,
729                                         DATA_BLOB *session_key,
730                                         struct wkssvc_PasswordBuffer **pwd_buf)
731 {
732         uint8_t buffer[516];
733         struct MD5Context ctx;
734         struct wkssvc_PasswordBuffer *my_pwd_buf = NULL;
735         DATA_BLOB confounded_session_key;
736         int confounder_len = 8;
737         uint8_t confounder[8];
738
739         my_pwd_buf = talloc_zero(mem_ctx, struct wkssvc_PasswordBuffer);
740         if (!my_pwd_buf) {
741                 return;
742         }
743
744         confounded_session_key = data_blob_talloc(mem_ctx, NULL, 16);
745
746         encode_pw_buffer(buffer, pwd, STR_UNICODE);
747
748         generate_random_buffer((uint8_t *)confounder, confounder_len);
749
750         MD5Init(&ctx);
751         MD5Update(&ctx, session_key->data, session_key->length);
752         MD5Update(&ctx, confounder, confounder_len);
753         MD5Final(confounded_session_key.data, &ctx);
754
755         arcfour_crypt_blob(buffer, 516, &confounded_session_key);
756
757         memcpy(&my_pwd_buf->data[0], confounder, confounder_len);
758         memcpy(&my_pwd_buf->data[8], buffer, 516);
759
760         data_blob_free(&confounded_session_key);
761
762         *pwd_buf = my_pwd_buf;
763 }
764
765 WERROR decode_wkssvc_join_password_buffer(TALLOC_CTX *mem_ctx,
766                                           struct wkssvc_PasswordBuffer *pwd_buf,
767                                           DATA_BLOB *session_key,
768                                           char **pwd)
769 {
770         uint8_t buffer[516];
771         struct MD5Context ctx;
772         size_t pwd_len;
773
774         DATA_BLOB confounded_session_key;
775
776         int confounder_len = 8;
777         uint8_t confounder[8];
778
779         *pwd = NULL;
780
781         if (!pwd_buf) {
782                 return WERR_BAD_PASSWORD;
783         }
784
785         if (session_key->length != 16) {
786                 DEBUG(10,("invalid session key\n"));
787                 return WERR_BAD_PASSWORD;
788         }
789
790         confounded_session_key = data_blob_talloc(mem_ctx, NULL, 16);
791
792         memcpy(&confounder, &pwd_buf->data[0], confounder_len);
793         memcpy(&buffer, &pwd_buf->data[8], 516);
794
795         MD5Init(&ctx);
796         MD5Update(&ctx, session_key->data, session_key->length);
797         MD5Update(&ctx, confounder, confounder_len);
798         MD5Final(confounded_session_key.data, &ctx);
799
800         arcfour_crypt_blob(buffer, 516, &confounded_session_key);
801
802         if (!decode_pw_buffer(mem_ctx, buffer, pwd, &pwd_len, CH_UTF16)) {
803                 data_blob_free(&confounded_session_key);
804                 return WERR_BAD_PASSWORD;
805         }
806
807         data_blob_free(&confounded_session_key);
808
809         return WERR_OK;
810 }
811