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