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