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