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