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