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