27702b9f4281027448bd1ac9351654fe7cae8731
[nivanova/samba-autobuild/.git] / source3 / libsmb / 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 "../lib/util/byteorder.h"
26
27 void SMBencrypt_hash(const uchar lm_hash[16], const uchar *c8, uchar p24[24])
28 {
29         uchar p21[21];
30
31         memset(p21,'\0',21);
32         memcpy(p21, lm_hash, 16);
33
34         SMBOWFencrypt(p21, c8, p24);
35
36 #ifdef DEBUG_PASSWORD
37         DEBUG(100,("SMBencrypt_hash: lm#, challenge, response\n"));
38         dump_data(100, p21, 16);
39         dump_data(100, c8, 8);
40         dump_data(100, p24, 24);
41 #endif
42 }
43
44 /*
45    This implements the X/Open SMB password encryption
46    It takes a password ('unix' string), a 8 byte "crypt key" 
47    and puts 24 bytes of encrypted password into p24 
48
49    Returns False if password must have been truncated to create LM hash
50 */
51
52 bool SMBencrypt(const char *passwd, const uchar *c8, uchar p24[24])
53 {
54         bool ret;
55         uchar lm_hash[16];
56
57         ret = E_deshash(passwd, lm_hash); 
58         SMBencrypt_hash(lm_hash, c8, p24);
59         return ret;
60 }
61
62 /**
63  * Creates the MD4 Hash of the users password in NT UNICODE.
64  * @param passwd password in 'unix' charset.
65  * @param p16 return password hashed with md4, caller allocated 16 byte buffer
66  */
67  
68 void E_md4hash(const char *passwd, uchar p16[16])
69 {
70         int len;
71         smb_ucs2_t wpwd[129];
72         
73         /* Password must be converted to NT unicode - null terminated. */
74         push_ucs2(NULL, wpwd, (const char *)passwd, 256, STR_UNICODE|STR_NOALIGN|STR_TERMINATE);
75         /* Calculate length in bytes */
76         len = strlen_w(wpwd) * sizeof(int16);
77
78         mdfour(p16, (unsigned char *)wpwd, len);
79         ZERO_STRUCT(wpwd);      
80 }
81
82 /**
83  * Creates the MD5 Hash of a combination of 16 byte salt and 16 byte NT hash.
84  * @param 16 byte salt.
85  * @param 16 byte NT hash.
86  * @param 16 byte return hashed with md5, caller allocated 16 byte buffer
87  */
88
89 void E_md5hash(const uchar salt[16], const uchar nthash[16], uchar hash_out[16])
90 {
91         struct MD5Context tctx;
92         uchar array[32];
93         
94         memset(hash_out, '\0', 16);
95         memcpy(array, salt, 16);
96         memcpy(&array[16], nthash, 16);
97         MD5Init(&tctx);
98         MD5Update(&tctx, array, 32);
99         MD5Final(hash_out, &tctx);
100 }
101
102 /**
103  * Creates the DES forward-only Hash of the users password in DOS ASCII charset
104  * @param passwd password in 'unix' charset.
105  * @param p16 return password hashed with DES, caller allocated 16 byte buffer
106  * @return False if password was > 14 characters, and therefore may be incorrect, otherwise True
107  * @note p16 is filled in regardless
108  */
109  
110 bool E_deshash(const char *passwd, uchar p16[16])
111 {
112         bool ret = True;
113         fstring dospwd; 
114         ZERO_STRUCT(dospwd);
115         
116         /* Password must be converted to DOS charset - null terminated, uppercase. */
117         push_ascii(dospwd, passwd, sizeof(dospwd), STR_UPPER|STR_TERMINATE);
118        
119         /* Only the fisrt 14 chars are considered, password need not be null terminated. */
120         E_P16((const unsigned char *)dospwd, p16);
121
122         if (strlen(dospwd) > 14) {
123                 ret = False;
124         }
125
126         ZERO_STRUCT(dospwd);    
127
128         return ret;
129 }
130
131 /**
132  * Creates the MD4 and DES (LM) Hash of the users password.  
133  * MD4 is of the NT Unicode, DES is of the DOS UPPERCASE password.
134  * @param passwd password in 'unix' charset.
135  * @param nt_p16 return password hashed with md4, caller allocated 16 byte buffer
136  * @param p16 return password hashed with des, caller allocated 16 byte buffer
137  */
138  
139 /* Does both the NT and LM owfs of a user's password */
140 void nt_lm_owf_gen(const char *pwd, uchar nt_p16[16], uchar p16[16])
141 {
142         /* Calculate the MD4 hash (NT compatible) of the password */
143         memset(nt_p16, '\0', 16);
144         E_md4hash(pwd, nt_p16);
145
146 #ifdef DEBUG_PASSWORD
147         DEBUG(100,("nt_lm_owf_gen: pwd, nt#\n"));
148         dump_data(120, (uint8 *)pwd, strlen(pwd));
149         dump_data(100, nt_p16, 16);
150 #endif
151
152         E_deshash(pwd, (uchar *)p16);
153
154 #ifdef DEBUG_PASSWORD
155         DEBUG(100,("nt_lm_owf_gen: pwd, lm#\n"));
156         dump_data(120, (uint8 *)pwd, strlen(pwd));
157         dump_data(100, p16, 16);
158 #endif
159 }
160
161 /* Does both the NTLMv2 owfs of a user's password */
162 bool ntv2_owf_gen(const uchar owf[16],
163                   const char *user_in, const char *domain_in,
164                   bool upper_case_domain, /* Transform the domain into UPPER case */
165                   uchar kr_buf[16])
166 {
167         smb_ucs2_t *user;
168         smb_ucs2_t *domain;
169         
170         size_t user_byte_len;
171         size_t domain_byte_len;
172
173         HMACMD5Context ctx;
174
175         if (!push_ucs2_talloc(NULL, &user, user_in, &user_byte_len)) {
176                 DEBUG(0, ("push_uss2_talloc() for user failed: %s\n",
177                           strerror(errno)));
178                 return False;
179         }
180
181         if (!push_ucs2_talloc(NULL, &domain, domain_in, &domain_byte_len)) {
182                 DEBUG(0, ("push_uss2_talloc() for domain failed: %s\n",
183                           strerror(errno)));
184                 TALLOC_FREE(user);
185                 return False;
186         }
187
188         strupper_w(user);
189
190         if (upper_case_domain)
191                 strupper_w(domain);
192
193         SMB_ASSERT(user_byte_len >= 2);
194         SMB_ASSERT(domain_byte_len >= 2);
195
196         /* We don't want null termination */
197         user_byte_len = user_byte_len - 2;
198         domain_byte_len = domain_byte_len - 2;
199         
200         hmac_md5_init_limK_to_64(owf, 16, &ctx);
201         hmac_md5_update((const unsigned char *)user, user_byte_len, &ctx);
202         hmac_md5_update((const unsigned char *)domain, domain_byte_len, &ctx);
203         hmac_md5_final(kr_buf, &ctx);
204
205 #ifdef DEBUG_PASSWORD
206         DEBUG(100, ("ntv2_owf_gen: user, domain, owfkey, kr\n"));
207         dump_data(100, (uint8 *)user, user_byte_len);
208         dump_data(100, (uint8 *)domain, domain_byte_len);
209         dump_data(100, (uint8 *)owf, 16);
210         dump_data(100, (uint8 *)kr_buf, 16);
211 #endif
212
213         TALLOC_FREE(user);
214         TALLOC_FREE(domain);
215         return True;
216 }
217
218 /* Does the des encryption from the NT or LM MD4 hash. */
219 void SMBOWFencrypt(const uchar passwd[16], const uchar *c8, uchar p24[24])
220 {
221         uchar p21[21];
222
223         ZERO_STRUCT(p21);
224  
225         memcpy(p21, passwd, 16);    
226         E_P24(p21, c8, p24);
227 }
228
229 /* Does the des encryption from the FIRST 8 BYTES of the NT or LM MD4 hash. */
230 void NTLMSSPOWFencrypt(const uchar passwd[8], const uchar *ntlmchalresp, uchar p24[24])
231 {
232         uchar p21[21];
233  
234         memset(p21,'\0',21);
235         memcpy(p21, passwd, 8);    
236         memset(p21 + 8, 0xbd, 8);    
237
238         E_P24(p21, ntlmchalresp, p24);
239 #ifdef DEBUG_PASSWORD
240         DEBUG(100,("NTLMSSPOWFencrypt: p21, c8, p24\n"));
241         dump_data(100, p21, 21);
242         dump_data(100, ntlmchalresp, 8);
243         dump_data(100, p24, 24);
244 #endif
245 }
246
247
248 /* Does the des encryption. */
249  
250 void SMBNTencrypt_hash(const uchar nt_hash[16], uchar *c8, uchar *p24)
251 {
252         uchar p21[21];
253  
254         memset(p21,'\0',21);
255         memcpy(p21, nt_hash, 16);
256         SMBOWFencrypt(p21, c8, p24);
257
258 #ifdef DEBUG_PASSWORD
259         DEBUG(100,("SMBNTencrypt: nt#, challenge, response\n"));
260         dump_data(100, p21, 16);
261         dump_data(100, c8, 8);
262         dump_data(100, p24, 24);
263 #endif
264 }
265
266 /* Does the NT MD4 hash then des encryption. Plaintext version of the above. */
267
268 void SMBNTencrypt(const char *passwd, uchar *c8, uchar *p24)
269 {
270         uchar nt_hash[16];
271         E_md4hash(passwd, nt_hash);    
272         SMBNTencrypt_hash(nt_hash, c8, p24);
273 }
274
275 /* Does the md5 encryption from the Key Response for NTLMv2. */
276 void SMBOWFencrypt_ntv2(const uchar kr[16],
277                         const DATA_BLOB *srv_chal,
278                         const DATA_BLOB *cli_chal,
279                         uchar resp_buf[16])
280 {
281         HMACMD5Context ctx;
282
283         hmac_md5_init_limK_to_64(kr, 16, &ctx);
284         hmac_md5_update(srv_chal->data, srv_chal->length, &ctx);
285         hmac_md5_update(cli_chal->data, cli_chal->length, &ctx);
286         hmac_md5_final(resp_buf, &ctx);
287
288 #ifdef DEBUG_PASSWORD
289         DEBUG(100, ("SMBOWFencrypt_ntv2: srv_chal, cli_chal, resp_buf\n"));
290         dump_data(100, srv_chal->data, srv_chal->length);
291         dump_data(100, cli_chal->data, cli_chal->length);
292         dump_data(100, resp_buf, 16);
293 #endif
294 }
295
296 void SMBsesskeygen_ntv2(const uchar kr[16],
297                         const uchar * nt_resp, uint8 sess_key[16])
298 {
299         /* a very nice, 128 bit, variable session key */
300         
301         HMACMD5Context ctx;
302
303         hmac_md5_init_limK_to_64(kr, 16, &ctx);
304         hmac_md5_update(nt_resp, 16, &ctx);
305         hmac_md5_final((unsigned char *)sess_key, &ctx);
306
307 #ifdef DEBUG_PASSWORD
308         DEBUG(100, ("SMBsesskeygen_ntv2:\n"));
309         dump_data(100, sess_key, 16);
310 #endif
311 }
312
313 void SMBsesskeygen_ntv1(const uchar kr[16],
314                         const uchar * nt_resp, uint8 sess_key[16])
315 {
316         /* yes, this session key does not change - yes, this 
317            is a problem - but it is 128 bits */
318         
319         mdfour((unsigned char *)sess_key, kr, 16);
320
321 #ifdef DEBUG_PASSWORD
322         DEBUG(100, ("SMBsesskeygen_ntv1:\n"));
323         dump_data(100, sess_key, 16);
324 #endif
325 }
326
327 void SMBsesskeygen_lm_sess_key(const uchar lm_hash[16],
328                         const uchar lm_resp[24], /* only uses 8 */ 
329                         uint8 sess_key[16])
330 {
331         uchar p24[24];
332         uchar partial_lm_hash[16];
333         
334         memcpy(partial_lm_hash, lm_hash, 8);
335         memset(partial_lm_hash + 8, 0xbd, 8);    
336
337         SMBOWFencrypt(partial_lm_hash, lm_resp, p24);
338         
339         memcpy(sess_key, p24, 16);
340
341 #ifdef DEBUG_PASSWORD
342         DEBUG(100, ("SMBsesskeygen_lmv1_jerry:\n"));
343         dump_data(100, sess_key, 16);
344 #endif
345 }
346
347 DATA_BLOB NTLMv2_generate_names_blob(const char *hostname, 
348                                      const char *domain)
349 {
350         DATA_BLOB names_blob = data_blob_null;
351         
352         msrpc_gen(&names_blob, "aaa", 
353                   NTLMSSP_NAME_TYPE_DOMAIN, domain,
354                   NTLMSSP_NAME_TYPE_SERVER, hostname,
355                   0, "");
356         return names_blob;
357 }
358
359 static DATA_BLOB NTLMv2_generate_client_data(const DATA_BLOB *names_blob) 
360 {
361         uchar client_chal[8];
362         DATA_BLOB response = data_blob_null;
363         char long_date[8];
364
365         generate_random_buffer(client_chal, sizeof(client_chal));
366
367         put_long_date(long_date, time(NULL));
368
369         /* See http://www.ubiqx.org/cifs/SMB.html#SMB.8.5 */
370
371         msrpc_gen(&response, "ddbbdb", 
372                   0x00000101,     /* Header  */
373                   0,              /* 'Reserved'  */
374                   long_date, 8,   /* Timestamp */
375                   client_chal, 8, /* client challenge */
376                   0,              /* Unknown */
377                   names_blob->data, names_blob->length);        /* End of name list */
378
379         return response;
380 }
381
382 static DATA_BLOB NTLMv2_generate_response(const uchar ntlm_v2_hash[16],
383                                           const DATA_BLOB *server_chal,
384                                           const DATA_BLOB *names_blob)
385 {
386         uchar ntlmv2_response[16];
387         DATA_BLOB ntlmv2_client_data;
388         DATA_BLOB final_response;
389         
390         /* NTLMv2 */
391         /* generate some data to pass into the response function - including
392            the hostname and domain name of the server */
393         ntlmv2_client_data = NTLMv2_generate_client_data(names_blob);
394
395         /* Given that data, and the challenge from the server, generate a response */
396         SMBOWFencrypt_ntv2(ntlm_v2_hash, server_chal, &ntlmv2_client_data, ntlmv2_response);
397         
398         final_response = data_blob(NULL, sizeof(ntlmv2_response) + ntlmv2_client_data.length);
399
400         memcpy(final_response.data, ntlmv2_response, sizeof(ntlmv2_response));
401
402         memcpy(final_response.data+sizeof(ntlmv2_response), 
403                ntlmv2_client_data.data, ntlmv2_client_data.length);
404
405         data_blob_free(&ntlmv2_client_data);
406
407         return final_response;
408 }
409
410 static DATA_BLOB LMv2_generate_response(const uchar ntlm_v2_hash[16],
411                                         const DATA_BLOB *server_chal)
412 {
413         uchar lmv2_response[16];
414         DATA_BLOB lmv2_client_data = data_blob(NULL, 8);
415         DATA_BLOB final_response = data_blob(NULL, 24);
416         
417         /* LMv2 */
418         /* client-supplied random data */
419         generate_random_buffer(lmv2_client_data.data, lmv2_client_data.length); 
420
421         /* Given that data, and the challenge from the server, generate a response */
422         SMBOWFencrypt_ntv2(ntlm_v2_hash, server_chal, &lmv2_client_data, lmv2_response);
423         memcpy(final_response.data, lmv2_response, sizeof(lmv2_response));
424
425         /* after the first 16 bytes is the random data we generated above, 
426            so the server can verify us with it */
427         memcpy(final_response.data+sizeof(lmv2_response), 
428                lmv2_client_data.data, lmv2_client_data.length);
429
430         data_blob_free(&lmv2_client_data);
431
432         return final_response;
433 }
434
435 bool SMBNTLMv2encrypt_hash(const char *user, const char *domain, const uchar nt_hash[16], 
436                       const DATA_BLOB *server_chal, 
437                       const DATA_BLOB *names_blob,
438                       DATA_BLOB *lm_response, DATA_BLOB *nt_response, 
439                       DATA_BLOB *user_session_key) 
440 {
441         uchar ntlm_v2_hash[16];
442
443         /* We don't use the NT# directly.  Instead we use it mashed up with
444            the username and domain.
445            This prevents username swapping during the auth exchange
446         */
447         if (!ntv2_owf_gen(nt_hash, user, domain, False, ntlm_v2_hash)) {
448                 return False;
449         }
450         
451         if (nt_response) {
452                 *nt_response = NTLMv2_generate_response(ntlm_v2_hash, server_chal,
453                                                         names_blob); 
454                 if (user_session_key) {
455                         *user_session_key = data_blob(NULL, 16);
456                         
457                         /* The NTLMv2 calculations also provide a session key, for signing etc later */
458                         /* use only the first 16 bytes of nt_response for session key */
459                         SMBsesskeygen_ntv2(ntlm_v2_hash, nt_response->data, user_session_key->data);
460                 }
461         }
462         
463         /* LMv2 */
464         
465         if (lm_response) {
466                 *lm_response = LMv2_generate_response(ntlm_v2_hash, server_chal);
467         }
468         
469         return True;
470 }
471
472 /* Plaintext version of the above. */
473
474 bool SMBNTLMv2encrypt(const char *user, const char *domain, const char *password, 
475                       const DATA_BLOB *server_chal, 
476                       const DATA_BLOB *names_blob,
477                       DATA_BLOB *lm_response, DATA_BLOB *nt_response, 
478                       DATA_BLOB *user_session_key) 
479 {
480         uchar nt_hash[16];
481         E_md4hash(password, nt_hash);
482
483         return SMBNTLMv2encrypt_hash(user, domain, nt_hash,
484                                 server_chal,
485                                 names_blob,
486                                 lm_response, nt_response,
487                                 user_session_key);
488 }
489
490 /***********************************************************
491  encode a password buffer with a unicode password.  The buffer
492  is filled with random data to make it harder to attack.
493 ************************************************************/
494 bool encode_pw_buffer(uint8 buffer[516], const char *password, int string_flags)
495 {
496         uchar new_pw[512];
497         size_t new_pw_len;
498
499         /* the incoming buffer can be any alignment. */
500         string_flags |= STR_NOALIGN;
501
502         new_pw_len = push_string_check(new_pw,
503                                        password, 
504                                        sizeof(new_pw), string_flags);
505         
506         memcpy(&buffer[512 - new_pw_len], new_pw, new_pw_len);
507
508         generate_random_buffer(buffer, 512 - new_pw_len);
509
510         /* 
511          * The length of the new password is in the last 4 bytes of
512          * the data buffer.
513          */
514         SIVAL(buffer, 512, new_pw_len);
515         ZERO_STRUCT(new_pw);
516         return True;
517 }
518
519
520 /***********************************************************
521  decode a password buffer
522  *new_pw_len is the length in bytes of the possibly mulitbyte
523  returned password including termination.
524 ************************************************************/
525
526 bool decode_pw_buffer(TALLOC_CTX *ctx,
527                         uint8 in_buffer[516],
528                         char **pp_new_pwrd,
529                         uint32 *new_pw_len,
530                         int string_flags)
531 {
532         int byte_len=0;
533
534         *pp_new_pwrd = NULL;
535         *new_pw_len = 0;
536
537         /* the incoming buffer can be any alignment. */
538         string_flags |= STR_NOALIGN;
539
540         /*
541           Warning !!! : This function is called from some rpc call.
542           The password IN the buffer may be a UNICODE string.
543           The password IN new_pwrd is an ASCII string
544           If you reuse that code somewhere else check first.
545         */
546
547         /* The length of the new password is in the last 4 bytes of the data buffer. */
548
549         byte_len = IVAL(in_buffer, 512);
550
551 #ifdef DEBUG_PASSWORD
552         dump_data(100, in_buffer, 516);
553 #endif
554
555         /* Password cannot be longer than the size of the password buffer */
556         if ( (byte_len < 0) || (byte_len > 512)) {
557                 DEBUG(0, ("decode_pw_buffer: incorrect password length (%d).\n", byte_len));
558                 DEBUG(0, ("decode_pw_buffer: check that 'encrypt passwords = yes'\n"));
559                 return false;
560         }
561
562         /* decode into the return buffer. */
563         *new_pw_len = pull_string_talloc(ctx,
564                                 NULL,
565                                 0,
566                                 pp_new_pwrd,
567                                 &in_buffer[512 - byte_len],
568                                 byte_len,
569                                 string_flags);
570
571         if (!*pp_new_pwrd || *new_pw_len == 0) {
572                 DEBUG(0, ("decode_pw_buffer: pull_string_talloc failed\n"));
573                 return false;
574         }
575
576 #ifdef DEBUG_PASSWORD
577         DEBUG(100,("decode_pw_buffer: new_pwrd: "));
578         dump_data(100, (uint8 *)*pp_new_pwrd, *new_pw_len);
579         DEBUG(100,("multibyte len:%d\n", *new_pw_len));
580         DEBUG(100,("original char len:%d\n", byte_len/2));
581 #endif
582
583         return true;
584 }
585
586 /***********************************************************
587  Decode an arc4 encrypted password change buffer.
588 ************************************************************/
589
590 void encode_or_decode_arc4_passwd_buffer(unsigned char pw_buf[532], const DATA_BLOB *psession_key)
591 {
592         struct MD5Context tctx;
593         unsigned char key_out[16];
594
595         /* Confounder is last 16 bytes. */
596
597         MD5Init(&tctx);
598         MD5Update(&tctx, &pw_buf[516], 16);
599         MD5Update(&tctx, psession_key->data, psession_key->length);
600         MD5Final(key_out, &tctx);
601         /* arc4 with key_out. */
602         SamOEMhash(pw_buf, key_out, 516);
603 }
604
605 /***********************************************************
606  Encrypt/Decrypt used for LSA secrets and trusted domain
607  passwords.
608 ************************************************************/
609
610 void sess_crypt_blob(DATA_BLOB *out, const DATA_BLOB *in, const DATA_BLOB *session_key, int forward)
611 {
612         int i, k;
613
614         for (i=0,k=0;
615              i<in->length;
616              i += 8, k += 7) {
617                 uint8 bin[8], bout[8], key[7];
618
619                 memset(bin, 0, 8);
620                 memcpy(bin,  &in->data[i], MIN(8, in->length-i));
621
622                 if (k + 7 > session_key->length) {
623                         k = (session_key->length - k);
624                 }
625                 memcpy(key, &session_key->data[k], 7);
626
627                 des_crypt56(bout, bin, key, forward?1:0);
628
629                 memcpy(&out->data[i], bout, MIN(8, in->length-i));
630         }
631 }
632
633 /* Decrypts password-blob with session-key
634  * @param nt_hash       NT hash for the session key
635  * @param data_in       DATA_BLOB encrypted password
636  *
637  * Returns cleartext password in CH_UNIX 
638  * Caller must free the returned string
639  */
640
641 char *decrypt_trustdom_secret(uint8_t nt_hash[16], DATA_BLOB *data_in)
642 {
643         DATA_BLOB data_out, sess_key;
644         uint32_t length;
645         uint32_t version;
646         fstring cleartextpwd;
647
648         if (!data_in || !nt_hash)
649                 return NULL;
650
651         /* hashed twice with md4 */
652         mdfour(nt_hash, nt_hash, 16);
653
654         /* 16-Byte session-key */
655         sess_key = data_blob(nt_hash, 16);
656         if (sess_key.data == NULL)
657                 return NULL;
658         
659         data_out = data_blob(NULL, data_in->length);
660         if (data_out.data == NULL)
661                 return NULL;
662         
663         /* decrypt with des3 */
664         sess_crypt_blob(&data_out, data_in, &sess_key, 0);
665
666         /* 4 Byte length, 4 Byte version */
667         length  = IVAL(data_out.data, 0);
668         version = IVAL(data_out.data, 4);
669
670         if (length > data_in->length - 8) {
671                 DEBUG(0,("decrypt_trustdom_secret: invalid length (%d)\n", length));
672                 return NULL;
673         }
674         
675         if (version != 1) {
676                 DEBUG(0,("decrypt_trustdom_secret: unknown version number (%d)\n", version));
677                 return NULL;
678         }
679         
680         rpcstr_pull(cleartextpwd, data_out.data + 8, sizeof(fstring), length, 0 );
681
682 #ifdef DEBUG_PASSWORD
683         DEBUG(100,("decrypt_trustdom_secret: length is: %d, version is: %d, password is: %s\n", 
684                                 length, version, cleartextpwd));
685 #endif
686
687         data_blob_free(&data_out);
688         data_blob_free(&sess_key);
689         
690         return SMB_STRDUP(cleartextpwd);
691
692 }
693
694 /* encode a wkssvc_PasswordBuffer:
695  *
696  * similar to samr_CryptPasswordEx. Different: 8byte confounder (instead of
697  * 16byte), confounder in front of the 516 byte buffer (instead of after that
698  * buffer), calling MD5Update() first with session_key and then with confounder
699  * (vice versa in samr) - Guenther */
700
701 void encode_wkssvc_join_password_buffer(TALLOC_CTX *mem_ctx,
702                                         const char *pwd,
703                                         DATA_BLOB *session_key,
704                                         struct wkssvc_PasswordBuffer **pwd_buf)
705 {
706         uint8_t buffer[516];
707         struct MD5Context ctx;
708         struct wkssvc_PasswordBuffer *my_pwd_buf = NULL;
709         DATA_BLOB confounded_session_key;
710         int confounder_len = 8;
711         uint8_t confounder[8];
712
713         my_pwd_buf = talloc_zero(mem_ctx, struct wkssvc_PasswordBuffer);
714         if (!my_pwd_buf) {
715                 return;
716         }
717
718         confounded_session_key = data_blob_talloc(mem_ctx, NULL, 16);
719
720         encode_pw_buffer(buffer, pwd, STR_UNICODE);
721
722         generate_random_buffer((uint8_t *)confounder, confounder_len);
723
724         MD5Init(&ctx);
725         MD5Update(&ctx, session_key->data, session_key->length);
726         MD5Update(&ctx, confounder, confounder_len);
727         MD5Final(confounded_session_key.data, &ctx);
728
729         SamOEMhashBlob(buffer, 516, &confounded_session_key);
730
731         memcpy(&my_pwd_buf->data[0], confounder, confounder_len);
732         memcpy(&my_pwd_buf->data[8], buffer, 516);
733
734         data_blob_free(&confounded_session_key);
735
736         *pwd_buf = my_pwd_buf;
737 }
738
739 WERROR decode_wkssvc_join_password_buffer(TALLOC_CTX *mem_ctx,
740                                           struct wkssvc_PasswordBuffer *pwd_buf,
741                                           DATA_BLOB *session_key,
742                                           char **pwd)
743 {
744         uint8_t buffer[516];
745         struct MD5Context ctx;
746         uint32_t pwd_len;
747
748         DATA_BLOB confounded_session_key;
749
750         int confounder_len = 8;
751         uint8_t confounder[8];
752
753         *pwd = NULL;
754
755         if (!pwd_buf) {
756                 return WERR_BAD_PASSWORD;
757         }
758
759         if (session_key->length != 16) {
760                 DEBUG(10,("invalid session key\n"));
761                 return WERR_BAD_PASSWORD;
762         }
763
764         confounded_session_key = data_blob_talloc(mem_ctx, NULL, 16);
765
766         memcpy(&confounder, &pwd_buf->data[0], confounder_len);
767         memcpy(&buffer, &pwd_buf->data[8], 516);
768
769         MD5Init(&ctx);
770         MD5Update(&ctx, session_key->data, session_key->length);
771         MD5Update(&ctx, confounder, confounder_len);
772         MD5Final(confounded_session_key.data, &ctx);
773
774         SamOEMhashBlob(buffer, 516, &confounded_session_key);
775
776         if (!decode_pw_buffer(mem_ctx, buffer, pwd, &pwd_len, STR_UNICODE)) {
777                 data_blob_free(&confounded_session_key);
778                 return WERR_BAD_PASSWORD;
779         }
780
781         data_blob_free(&confounded_session_key);
782
783         return WERR_OK;
784 }
785
786 DATA_BLOB decrypt_drsuapi_blob(TALLOC_CTX *mem_ctx,
787                                const DATA_BLOB *session_key,
788                                bool rcrypt,
789                                uint32_t rid,
790                                const DATA_BLOB *buffer)
791 {
792         DATA_BLOB confounder;
793         DATA_BLOB enc_buffer;
794
795         struct MD5Context md5;
796         uint8_t _enc_key[16];
797         DATA_BLOB enc_key;
798
799         DATA_BLOB dec_buffer;
800
801         uint32_t crc32_given;
802         uint32_t crc32_calc;
803         DATA_BLOB checked_buffer;
804
805         DATA_BLOB plain_buffer;
806
807         /*
808          * the combination "c[3] s[1] e[1] d[0]..."
809          * was successful!!!!!!!!!!!!!!!!!!!!!!!!!!
810          */
811
812         /*
813          * the first 16 bytes at the beginning are the confounder
814          * followed by the 4 byte crc32 checksum
815          */
816         if (buffer->length < 20) {
817                 return data_blob_const(NULL, 0);
818         }
819         confounder = data_blob_const(buffer->data, 16);
820         enc_buffer = data_blob_const(buffer->data + 16, buffer->length - 16);
821
822         /*
823          * build the encryption key md5 over the session key followed
824          * by the confounder
825          *
826          * here the gensec session key is used and
827          * not the dcerpc ncacn_ip_tcp "SystemLibraryDTC" key!
828          */
829         enc_key = data_blob_const(_enc_key, sizeof(_enc_key));
830         MD5Init(&md5);
831         MD5Update(&md5, session_key->data, session_key->length);
832         MD5Update(&md5, confounder.data, confounder.length);
833         MD5Final(enc_key.data, &md5);
834
835         /*
836          * copy the encrypted buffer part and
837          * decrypt it using the created encryption key using arcfour
838          */
839         dec_buffer = data_blob_talloc(mem_ctx, enc_buffer.data, enc_buffer.length);
840         if (!dec_buffer.data) {
841                 return data_blob_const(NULL, 0);
842         }
843         SamOEMhashBlob(dec_buffer.data, dec_buffer.length, &enc_key);
844
845         /*
846          * the first 4 byte are the crc32 checksum
847          * of the remaining bytes
848          */
849         crc32_given = IVAL(dec_buffer.data, 0);
850         crc32_calc = crc32_calc_buffer(dec_buffer.data + 4 , dec_buffer.length - 4);
851         if (crc32_given != crc32_calc) {
852                 DEBUG(1,("CRC32: given[0x%08X] calc[0x%08X]\n",
853                       crc32_given, crc32_calc));
854                 return data_blob_const(NULL, 0);
855         }
856         checked_buffer = data_blob_talloc(mem_ctx, dec_buffer.data + 4, dec_buffer.length - 4);
857         if (!checked_buffer.data) {
858                 return data_blob_const(NULL, 0);
859         }
860
861         /*
862          * some attributes seem to be in a usable form after this decryption
863          * (supplementalCredentials, priorValue, currentValue, trustAuthOutgoing,
864          *  trustAuthIncoming, initialAuthOutgoing, initialAuthIncoming)
865          * At least supplementalCredentials contains plaintext
866          * like "Primary:Kerberos" (in unicode form)
867          *
868          * some attributes seem to have some additional encryption
869          * dBCSPwd, unicodePwd, ntPwdHistory, lmPwdHistory
870          *
871          * it's the sam_rid_crypt() function, as the value is constant,
872          * so it doesn't depend on sessionkeys.
873          */
874         if (rcrypt) {
875                 uint32_t i, num_hashes;
876
877                 if ((checked_buffer.length % 16) != 0) {
878                         return data_blob_const(NULL, 0);
879                 }
880
881                 plain_buffer = data_blob_talloc(mem_ctx, checked_buffer.data, checked_buffer.length);
882                 if (!plain_buffer.data) {
883                         return data_blob_const(NULL, 0);
884                 }
885
886                 num_hashes = plain_buffer.length / 16;
887                 for (i = 0; i < num_hashes; i++) {
888                         uint32_t offset = i * 16;
889                         sam_pwd_hash(rid, checked_buffer.data + offset, plain_buffer.data + offset, 0);
890                 }
891         } else {
892                 plain_buffer = checked_buffer;
893         }
894
895         return plain_buffer;
896 }
897
898