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