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