r7031: Added encrypt/decrypt function for LSA secrets and trusted
[bbaumbach/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 2 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, write to the Free Software
22    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23 */
24
25 #include "includes.h"
26 #include "byteorder.h"
27
28 /*
29    This implements the X/Open SMB password encryption
30    It takes a password ('unix' string), a 8 byte "crypt key" 
31    and puts 24 bytes of encrypted password into p24 
32
33    Returns False if password must have been truncated to create LM hash
34 */
35 BOOL SMBencrypt(const char *passwd, const uchar *c8, uchar p24[24])
36 {
37         BOOL ret;
38         uchar p21[21];
39
40         memset(p21,'\0',21);
41         ret = E_deshash(passwd, p21); 
42
43         SMBOWFencrypt(p21, c8, p24);
44
45 #ifdef DEBUG_PASSWORD
46         DEBUG(100,("SMBencrypt: lm#, challenge, response\n"));
47         dump_data(100, (char *)p21, 16);
48         dump_data(100, (const char *)c8, 8);
49         dump_data(100, (char *)p24, 24);
50 #endif
51
52         return ret;
53 }
54
55 /**
56  * Creates the MD4 Hash of the users password in NT UNICODE.
57  * @param passwd password in 'unix' charset.
58  * @param p16 return password hashed with md4, caller allocated 16 byte buffer
59  */
60  
61 void E_md4hash(const char *passwd, uchar p16[16])
62 {
63         int len;
64         smb_ucs2_t wpwd[129];
65         
66         /* Password must be converted to NT unicode - null terminated. */
67         push_ucs2(NULL, wpwd, (const char *)passwd, 256, STR_UNICODE|STR_NOALIGN|STR_TERMINATE);
68         /* Calculate length in bytes */
69         len = strlen_w(wpwd) * sizeof(int16);
70
71         mdfour(p16, (unsigned char *)wpwd, len);
72         ZERO_STRUCT(wpwd);      
73 }
74
75 /**
76  * Creates the MD5 Hash of a combination of 16 byte salt and 16 byte NT hash.
77  * @param 16 byte salt.
78  * @param 16 byte NT hash.
79  * @param 16 byte return hashed with md5, caller allocated 16 byte buffer
80  */
81
82 void E_md5hash(const uchar salt[16], const uchar nthash[16], uchar hash_out[16])
83 {
84         struct MD5Context tctx;
85         uchar array[32];
86         
87         memset(hash_out, '\0', 16);
88         memcpy(array, salt, 16);
89         memcpy(&array[16], nthash, 16);
90         MD5Init(&tctx);
91         MD5Update(&tctx, array, 32);
92         MD5Final(hash_out, &tctx);
93 }
94
95 /**
96  * Creates the DES forward-only Hash of the users password in DOS ASCII charset
97  * @param passwd password in 'unix' charset.
98  * @param p16 return password hashed with DES, caller allocated 16 byte buffer
99  * @return False if password was > 14 characters, and therefore may be incorrect, otherwise True
100  * @note p16 is filled in regardless
101  */
102  
103 BOOL E_deshash(const char *passwd, uchar p16[16])
104 {
105         BOOL ret = True;
106         fstring dospwd; 
107         ZERO_STRUCT(dospwd);
108         
109         /* Password must be converted to DOS charset - null terminated, uppercase. */
110         push_ascii(dospwd, passwd, sizeof(dospwd), STR_UPPER|STR_TERMINATE);
111        
112         /* Only the fisrt 14 chars are considered, password need not be null terminated. */
113         E_P16((const unsigned char *)dospwd, p16);
114
115         if (strlen(dospwd) > 14) {
116                 ret = False;
117         }
118
119         ZERO_STRUCT(dospwd);    
120
121         return ret;
122 }
123
124 /**
125  * Creates the MD4 and DES (LM) Hash of the users password.  
126  * MD4 is of the NT Unicode, DES is of the DOS UPPERCASE password.
127  * @param passwd password in 'unix' charset.
128  * @param nt_p16 return password hashed with md4, caller allocated 16 byte buffer
129  * @param p16 return password hashed with des, caller allocated 16 byte buffer
130  */
131  
132 /* Does both the NT and LM owfs of a user's password */
133 void nt_lm_owf_gen(const char *pwd, uchar nt_p16[16], uchar p16[16])
134 {
135         /* Calculate the MD4 hash (NT compatible) of the password */
136         memset(nt_p16, '\0', 16);
137         E_md4hash(pwd, nt_p16);
138
139 #ifdef DEBUG_PASSWORD
140         DEBUG(100,("nt_lm_owf_gen: pwd, nt#\n"));
141         dump_data(120, pwd, strlen(pwd));
142         dump_data(100, (char *)nt_p16, 16);
143 #endif
144
145         E_deshash(pwd, (uchar *)p16);
146
147 #ifdef DEBUG_PASSWORD
148         DEBUG(100,("nt_lm_owf_gen: pwd, lm#\n"));
149         dump_data(120, pwd, strlen(pwd));
150         dump_data(100, (char *)p16, 16);
151 #endif
152 }
153
154 /* Does both the NTLMv2 owfs of a user's password */
155 BOOL ntv2_owf_gen(const uchar owf[16],
156                   const char *user_in, const char *domain_in,
157                   BOOL upper_case_domain, /* Transform the domain into UPPER case */
158                   uchar kr_buf[16])
159 {
160         smb_ucs2_t *user;
161         smb_ucs2_t *domain;
162         
163         size_t user_byte_len;
164         size_t domain_byte_len;
165
166         HMACMD5Context ctx;
167
168         user_byte_len = push_ucs2_allocate(&user, user_in);
169         if (user_byte_len == (size_t)-1) {
170                 DEBUG(0, ("push_uss2_allocate() for user returned -1 (probably malloc() failure)\n"));
171                 return False;
172         }
173
174         domain_byte_len = push_ucs2_allocate(&domain, domain_in);
175         if (domain_byte_len == (size_t)-1) {
176                 DEBUG(0, ("push_uss2_allocate() for domain returned -1 (probably malloc() failure)\n"));
177                 return False;
178         }
179
180         strupper_w(user);
181
182         if (upper_case_domain)
183                 strupper_w(domain);
184
185         SMB_ASSERT(user_byte_len >= 2);
186         SMB_ASSERT(domain_byte_len >= 2);
187
188         /* We don't want null termination */
189         user_byte_len = user_byte_len - 2;
190         domain_byte_len = domain_byte_len - 2;
191         
192         hmac_md5_init_limK_to_64(owf, 16, &ctx);
193         hmac_md5_update((const unsigned char *)user, user_byte_len, &ctx);
194         hmac_md5_update((const unsigned char *)domain, domain_byte_len, &ctx);
195         hmac_md5_final(kr_buf, &ctx);
196
197 #ifdef DEBUG_PASSWORD
198         DEBUG(100, ("ntv2_owf_gen: user, domain, owfkey, kr\n"));
199         dump_data(100, (const char *)user, user_byte_len);
200         dump_data(100, (const char *)domain, domain_byte_len);
201         dump_data(100, owf, 16);
202         dump_data(100, kr_buf, 16);
203 #endif
204
205         SAFE_FREE(user);
206         SAFE_FREE(domain);
207         return True;
208 }
209
210 /* Does the des encryption from the NT or LM MD4 hash. */
211 void SMBOWFencrypt(const uchar passwd[16], const uchar *c8, uchar p24[24])
212 {
213         uchar p21[21];
214
215         ZERO_STRUCT(p21);
216  
217         memcpy(p21, passwd, 16);    
218         E_P24(p21, c8, p24);
219 }
220
221 /* Does the des encryption from the FIRST 8 BYTES of the NT or LM MD4 hash. */
222 void NTLMSSPOWFencrypt(const uchar passwd[8], const uchar *ntlmchalresp, uchar p24[24])
223 {
224         uchar p21[21];
225  
226         memset(p21,'\0',21);
227         memcpy(p21, passwd, 8);    
228         memset(p21 + 8, 0xbd, 8);    
229
230         E_P24(p21, ntlmchalresp, p24);
231 #ifdef DEBUG_PASSWORD
232         DEBUG(100,("NTLMSSPOWFencrypt: p21, c8, p24\n"));
233         dump_data(100, (char *)p21, 21);
234         dump_data(100, (const char *)ntlmchalresp, 8);
235         dump_data(100, (char *)p24, 24);
236 #endif
237 }
238
239
240 /* Does the NT MD4 hash then des encryption. */
241  
242 void SMBNTencrypt(const char *passwd, uchar *c8, uchar *p24)
243 {
244         uchar p21[21];
245  
246         memset(p21,'\0',21);
247  
248         E_md4hash(passwd, p21);    
249         SMBOWFencrypt(p21, c8, p24);
250
251 #ifdef DEBUG_PASSWORD
252         DEBUG(100,("SMBNTencrypt: nt#, challenge, response\n"));
253         dump_data(100, (char *)p21, 16);
254         dump_data(100, (char *)c8, 8);
255         dump_data(100, (char *)p24, 24);
256 #endif
257 }
258
259 /* Does the md5 encryption from the Key Response for NTLMv2. */
260 void SMBOWFencrypt_ntv2(const uchar kr[16],
261                         const DATA_BLOB *srv_chal,
262                         const DATA_BLOB *cli_chal,
263                         uchar resp_buf[16])
264 {
265         HMACMD5Context ctx;
266
267         hmac_md5_init_limK_to_64(kr, 16, &ctx);
268         hmac_md5_update(srv_chal->data, srv_chal->length, &ctx);
269         hmac_md5_update(cli_chal->data, cli_chal->length, &ctx);
270         hmac_md5_final(resp_buf, &ctx);
271
272 #ifdef DEBUG_PASSWORD
273         DEBUG(100, ("SMBOWFencrypt_ntv2: srv_chal, cli_chal, resp_buf\n"));
274         dump_data(100, srv_chal->data, srv_chal->length);
275         dump_data(100, cli_chal->data, cli_chal->length);
276         dump_data(100, resp_buf, 16);
277 #endif
278 }
279
280 void SMBsesskeygen_ntv2(const uchar kr[16],
281                         const uchar * nt_resp, uint8 sess_key[16])
282 {
283         /* a very nice, 128 bit, variable session key */
284         
285         HMACMD5Context ctx;
286
287         hmac_md5_init_limK_to_64(kr, 16, &ctx);
288         hmac_md5_update(nt_resp, 16, &ctx);
289         hmac_md5_final((unsigned char *)sess_key, &ctx);
290
291 #ifdef DEBUG_PASSWORD
292         DEBUG(100, ("SMBsesskeygen_ntv2:\n"));
293         dump_data(100, sess_key, 16);
294 #endif
295 }
296
297 void SMBsesskeygen_ntv1(const uchar kr[16],
298                         const uchar * nt_resp, uint8 sess_key[16])
299 {
300         /* yes, this session key does not change - yes, this 
301            is a problem - but it is 128 bits */
302         
303         mdfour((unsigned char *)sess_key, kr, 16);
304
305 #ifdef DEBUG_PASSWORD
306         DEBUG(100, ("SMBsesskeygen_ntv1:\n"));
307         dump_data(100, sess_key, 16);
308 #endif
309 }
310
311 void SMBsesskeygen_lmv1(const uchar lm_hash[16],
312                         const uchar lm_resp[24], /* only uses 8 */ 
313                         uint8 sess_key[16])
314 {
315         /* Calculate the LM session key (effective length 40 bits,
316            but changes with each session) */
317
318         uchar p24[24];
319         uchar partial_lm_hash[16];
320         
321         memcpy(partial_lm_hash, lm_hash, 8);
322         memset(partial_lm_hash + 8, 0xbd, 8);    
323
324         SMBOWFencrypt(lm_hash, lm_resp, p24);
325         
326         memcpy(sess_key, p24, 16);
327         sess_key[5] = 0xe5;
328         sess_key[6] = 0x38;
329         sess_key[7] = 0xb0;
330
331 #ifdef DEBUG_PASSWORD
332         DEBUG(100, ("SMBsesskeygen_lmv1:\n"));
333         dump_data(100, sess_key, 16);
334 #endif
335 }
336
337 void SMBsesskeygen_lm_sess_key(const uchar lm_hash[16],
338                         const uchar lm_resp[24], /* only uses 8 */ 
339                         uint8 sess_key[16])
340 {
341         uchar p24[24];
342         uchar partial_lm_hash[16];
343         
344         memcpy(partial_lm_hash, lm_hash, 8);
345         memset(partial_lm_hash + 8, 0xbd, 8);    
346
347         SMBOWFencrypt(partial_lm_hash, lm_resp, p24);
348         
349         memcpy(sess_key, p24, 16);
350
351 #ifdef DEBUG_PASSWORD
352         DEBUG(100, ("SMBsesskeygen_lmv1_jerry:\n"));
353         dump_data(100, sess_key, 16);
354 #endif
355 }
356
357 DATA_BLOB NTLMv2_generate_names_blob(const char *hostname, 
358                                      const char *domain)
359 {
360         DATA_BLOB names_blob = data_blob(NULL, 0);
361         
362         msrpc_gen(&names_blob, "aaa", 
363                   NTLMSSP_NAME_TYPE_DOMAIN, domain,
364                   NTLMSSP_NAME_TYPE_SERVER, hostname,
365                   0, "");
366         return names_blob;
367 }
368
369 static DATA_BLOB NTLMv2_generate_client_data(const DATA_BLOB *names_blob) 
370 {
371         uchar client_chal[8];
372         DATA_BLOB response = data_blob(NULL, 0);
373         char long_date[8];
374
375         generate_random_buffer(client_chal, sizeof(client_chal));
376
377         put_long_date(long_date, time(NULL));
378
379         /* See http://www.ubiqx.org/cifs/SMB.html#SMB.8.5 */
380
381         msrpc_gen(&response, "ddbbdb", 
382                   0x00000101,     /* Header  */
383                   0,              /* 'Reserved'  */
384                   long_date, 8,   /* Timestamp */
385                   client_chal, 8, /* client challenge */
386                   0,              /* Unknown */
387                   names_blob->data, names_blob->length);        /* End of name list */
388
389         return response;
390 }
391
392 static DATA_BLOB NTLMv2_generate_response(const uchar ntlm_v2_hash[16],
393                                           const DATA_BLOB *server_chal,
394                                           const DATA_BLOB *names_blob)
395 {
396         uchar ntlmv2_response[16];
397         DATA_BLOB ntlmv2_client_data;
398         DATA_BLOB final_response;
399         
400         /* NTLMv2 */
401         /* generate some data to pass into the response function - including
402            the hostname and domain name of the server */
403         ntlmv2_client_data = NTLMv2_generate_client_data(names_blob);
404
405         /* Given that data, and the challenge from the server, generate a response */
406         SMBOWFencrypt_ntv2(ntlm_v2_hash, server_chal, &ntlmv2_client_data, ntlmv2_response);
407         
408         final_response = data_blob(NULL, sizeof(ntlmv2_response) + ntlmv2_client_data.length);
409
410         memcpy(final_response.data, ntlmv2_response, sizeof(ntlmv2_response));
411
412         memcpy(final_response.data+sizeof(ntlmv2_response), 
413                ntlmv2_client_data.data, ntlmv2_client_data.length);
414
415         data_blob_free(&ntlmv2_client_data);
416
417         return final_response;
418 }
419
420 static DATA_BLOB LMv2_generate_response(const uchar ntlm_v2_hash[16],
421                                         const DATA_BLOB *server_chal)
422 {
423         uchar lmv2_response[16];
424         DATA_BLOB lmv2_client_data = data_blob(NULL, 8);
425         DATA_BLOB final_response = data_blob(NULL, 24);
426         
427         /* LMv2 */
428         /* client-supplied random data */
429         generate_random_buffer(lmv2_client_data.data, lmv2_client_data.length); 
430
431         /* Given that data, and the challenge from the server, generate a response */
432         SMBOWFencrypt_ntv2(ntlm_v2_hash, server_chal, &lmv2_client_data, lmv2_response);
433         memcpy(final_response.data, lmv2_response, sizeof(lmv2_response));
434
435         /* after the first 16 bytes is the random data we generated above, 
436            so the server can verify us with it */
437         memcpy(final_response.data+sizeof(lmv2_response), 
438                lmv2_client_data.data, lmv2_client_data.length);
439
440         data_blob_free(&lmv2_client_data);
441
442         return final_response;
443 }
444
445 BOOL SMBNTLMv2encrypt(const char *user, const char *domain, const char *password, 
446                       const DATA_BLOB *server_chal, 
447                       const DATA_BLOB *names_blob,
448                       DATA_BLOB *lm_response, DATA_BLOB *nt_response, 
449                       DATA_BLOB *user_session_key) 
450 {
451         uchar nt_hash[16];
452         uchar ntlm_v2_hash[16];
453         E_md4hash(password, nt_hash);
454
455         /* We don't use the NT# directly.  Instead we use it mashed up with
456            the username and domain.
457            This prevents username swapping during the auth exchange
458         */
459         if (!ntv2_owf_gen(nt_hash, user, domain, True, ntlm_v2_hash)) {
460                 return False;
461         }
462         
463         if (nt_response) {
464                 *nt_response = NTLMv2_generate_response(ntlm_v2_hash, server_chal,
465                                                         names_blob); 
466                 if (user_session_key) {
467                         *user_session_key = data_blob(NULL, 16);
468                         
469                         /* The NTLMv2 calculations also provide a session key, for signing etc later */
470                         /* use only the first 16 bytes of nt_response for session key */
471                         SMBsesskeygen_ntv2(ntlm_v2_hash, nt_response->data, user_session_key->data);
472                 }
473         }
474         
475         /* LMv2 */
476         
477         if (lm_response) {
478                 *lm_response = LMv2_generate_response(ntlm_v2_hash, server_chal);
479         }
480         
481         return True;
482 }
483
484 /***********************************************************
485  encode a password buffer with a unicode password.  The buffer
486  is filled with random data to make it harder to attack.
487 ************************************************************/
488 BOOL encode_pw_buffer(char buffer[516], const char *password, int string_flags)
489 {
490         uchar new_pw[512];
491         size_t new_pw_len;
492
493         new_pw_len = push_string(NULL, new_pw,
494                                  password, 
495                                  sizeof(new_pw), string_flags);
496         
497         memcpy(&buffer[512 - new_pw_len], new_pw, new_pw_len);
498
499         generate_random_buffer((unsigned char *)buffer, 512 - new_pw_len);
500
501         /* 
502          * The length of the new password is in the last 4 bytes of
503          * the data buffer.
504          */
505         SIVAL(buffer, 512, new_pw_len);
506         ZERO_STRUCT(new_pw);
507         return True;
508 }
509
510
511 /***********************************************************
512  decode a password buffer
513  *new_pw_len is the length in bytes of the possibly mulitbyte
514  returned password including termination.
515 ************************************************************/
516
517 BOOL decode_pw_buffer(uint8 in_buffer[516], char *new_pwrd,
518                       int new_pwrd_size, uint32 *new_pw_len,
519                       int string_flags)
520 {
521         int byte_len=0;
522
523         /*
524           Warning !!! : This function is called from some rpc call.
525           The password IN the buffer may be a UNICODE string.
526           The password IN new_pwrd is an ASCII string
527           If you reuse that code somewhere else check first.
528         */
529
530         /* The length of the new password is in the last 4 bytes of the data buffer. */
531
532         byte_len = IVAL(in_buffer, 512);
533
534 #ifdef DEBUG_PASSWORD
535         dump_data(100, in_buffer, 516);
536 #endif
537
538         /* Password cannot be longer than the size of the password buffer */
539         if ( (byte_len < 0) || (byte_len > 512)) {
540                 DEBUG(0, ("decode_pw_buffer: incorrect password length (%d).\n", byte_len));
541                 DEBUG(0, ("decode_pw_buffer: check that 'encrypt passwords = yes'\n"));
542                 return False;
543         }
544
545         /* decode into the return buffer.  Buffer length supplied */
546         *new_pw_len = pull_string(NULL, new_pwrd, &in_buffer[512 - byte_len], new_pwrd_size, 
547                                   byte_len, string_flags);
548
549 #ifdef DEBUG_PASSWORD
550         DEBUG(100,("decode_pw_buffer: new_pwrd: "));
551         dump_data(100, (char *)new_pwrd, *new_pw_len);
552         DEBUG(100,("multibyte len:%d\n", *new_pw_len));
553         DEBUG(100,("original char len:%d\n", byte_len/2));
554 #endif
555         
556         return True;
557 }
558
559 /***********************************************************
560  Encrypt/Decrypt used for LSA secrets and trusted domain
561  passwords.
562 ************************************************************/
563
564 void sess_crypt_blob(DATA_BLOB *out, const DATA_BLOB *in, const DATA_BLOB *session_key, int forward)
565 {
566         int i, k;
567
568         for (i=0,k=0;
569              i<in->length;
570              i += 8, k += 7) {
571                 uint8_t bin[8], bout[8], key[7];
572
573                 memset(bin, 0, 8);
574                 memcpy(bin,  &in->data[i], MIN(8, in->length-i));
575
576                 if (k + 7 > session_key->length) {
577                         k = (session_key->length - k);
578                 }
579                 memcpy(key, &session_key->data[k], 7);
580
581                 smbhash(bout, bin, key, forward?1:0);
582
583                 memcpy(&out->data[i], bout, MIN(8, in->length-i));
584         }
585 }