This commit was manufactured by cvs2svn to create branch 'SAMBA_3_0'.(This used to...
[bbaumbach/samba-autobuild/.git] / source3 / libsmb / 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 "byteorder.h"
27
28 /*
29    This implements the X/Open SMB password encryption
30    It takes a password ('unix' string), a 8 byte "crypt key" 
31    and puts 24 bytes of encrypted password into p24 */
32 void SMBencrypt(const char *passwd, const uchar *c8, uchar p24[24])
33 {
34         uchar p21[21];
35
36         memset(p21,'\0',21);
37         E_deshash(passwd, p21); 
38
39         SMBOWFencrypt(p21, c8, p24);
40
41 #ifdef DEBUG_PASSWORD
42         DEBUG(100,("SMBencrypt: lm#, challenge, response\n"));
43         dump_data(100, (char *)p21, 16);
44         dump_data(100, (const char *)c8, 8);
45         dump_data(100, (char *)p24, 24);
46 #endif
47 }
48
49 /**
50  * Creates the MD4 Hash of the users password in NT UNICODE.
51  * @param passwd password in 'unix' charset.
52  * @param p16 return password hashed with md4, caller allocated 16 byte buffer
53  */
54  
55 void E_md4hash(const char *passwd, uchar p16[16])
56 {
57         int len;
58         smb_ucs2_t wpwd[129];
59         
60         /* Password must be converted to NT unicode - null terminated. */
61         push_ucs2(NULL, wpwd, (const char *)passwd, 256, STR_UNICODE|STR_NOALIGN|STR_TERMINATE);
62         /* Calculate length in bytes */
63         len = strlen_w(wpwd) * sizeof(int16);
64
65         mdfour(p16, (unsigned char *)wpwd, len);
66         ZERO_STRUCT(wpwd);      
67 }
68
69 /**
70  * Creates the DES forward-only Hash of the users password in DOS ASCII charset
71  * @param passwd password in 'unix' charset.
72  * @param p16 return password hashed with DES, caller allocated 16 byte buffer
73  */
74  
75 void E_deshash(const char *passwd, uchar p16[16])
76 {
77         fstring dospwd; 
78         ZERO_STRUCT(dospwd);
79         ZERO_STRUCTP(p16);
80         
81         /* Password must be converted to DOS charset - null terminated, uppercase. */
82         push_ascii(dospwd, (const char *)passwd, sizeof(dospwd), STR_UPPER|STR_TERMINATE);
83
84         /* Only the fisrt 14 chars are considered, password need not be null terminated. */
85         E_P16(dospwd, p16);
86
87         ZERO_STRUCT(dospwd);    
88 }
89
90 /**
91  * Creates the MD4 and DES (LM) Hash of the users password.  
92  * MD4 is of the NT Unicode, DES is of the DOS UPPERCASE password.
93  * @param passwd password in 'unix' charset.
94  * @param nt_p16 return password hashed with md4, caller allocated 16 byte buffer
95  * @param p16 return password hashed with des, caller allocated 16 byte buffer
96  */
97  
98 /* Does both the NT and LM owfs of a user's password */
99 void nt_lm_owf_gen(const char *pwd, uchar nt_p16[16], uchar p16[16])
100 {
101         /* Calculate the MD4 hash (NT compatible) of the password */
102         memset(nt_p16, '\0', 16);
103         E_md4hash(pwd, nt_p16);
104
105 #ifdef DEBUG_PASSWORD
106         DEBUG(100,("nt_lm_owf_gen: pwd, nt#\n"));
107         dump_data(120, pwd, strlen(pwd));
108         dump_data(100, (char *)nt_p16, 16);
109 #endif
110
111         E_deshash(pwd, (uchar *)p16);
112
113 #ifdef DEBUG_PASSWORD
114         DEBUG(100,("nt_lm_owf_gen: pwd, lm#\n"));
115         dump_data(120, pwd, strlen(pwd));
116         dump_data(100, (char *)p16, 16);
117 #endif
118 }
119
120 /* Does both the NTLMv2 owfs of a user's password */
121 BOOL ntv2_owf_gen(const uchar owf[16],
122                   const char *user_in, const char *domain_in, uchar kr_buf[16])
123 {
124         smb_ucs2_t *user;
125         smb_ucs2_t *domain;
126         
127         size_t user_byte_len;
128         size_t domain_byte_len;
129
130         HMACMD5Context ctx;
131
132         user_byte_len = push_ucs2_allocate(&user, user_in);
133         if (user_byte_len == (size_t)-1) {
134                 DEBUG(0, ("push_uss2_allocate() for user returned -1 (probably malloc() failure)\n"));
135                 return False;
136         }
137
138         domain_byte_len = push_ucs2_allocate(&domain, domain_in);
139         if (domain_byte_len == (size_t)-1) {
140                 DEBUG(0, ("push_uss2_allocate() for domain returned -1 (probably malloc() failure)\n"));
141                 return False;
142         }
143
144         strupper_w(user);
145         strupper_w(domain);
146
147         SMB_ASSERT(user_byte_len >= 2);
148         SMB_ASSERT(domain_byte_len >= 2);
149
150         /* We don't want null termination */
151         user_byte_len = user_byte_len - 2;
152         domain_byte_len = domain_byte_len - 2;
153         
154         hmac_md5_init_limK_to_64(owf, 16, &ctx);
155         hmac_md5_update((const unsigned char *)user, user_byte_len, &ctx);
156         hmac_md5_update((const unsigned char *)domain, domain_byte_len, &ctx);
157         hmac_md5_final(kr_buf, &ctx);
158
159 #ifdef DEBUG_PASSWORD
160         DEBUG(100, ("ntv2_owf_gen: user, domain, owfkey, kr\n"));
161         dump_data(100, (const char *)user, user_byte_len);
162         dump_data(100, (const char *)domain, domain_byte_len);
163         dump_data(100, owf, 16);
164         dump_data(100, kr_buf, 16);
165 #endif
166
167         SAFE_FREE(user);
168         SAFE_FREE(domain);
169         return True;
170 }
171
172 /* Does the des encryption from the NT or LM MD4 hash. */
173 void SMBOWFencrypt(const uchar passwd[16], const uchar *c8, uchar p24[24])
174 {
175         uchar p21[21];
176
177         ZERO_STRUCT(p21);
178  
179         memcpy(p21, passwd, 16);    
180         E_P24(p21, c8, p24);
181 }
182
183 /* Does the des encryption from the FIRST 8 BYTES of the NT or LM MD4 hash. */
184 void NTLMSSPOWFencrypt(const uchar passwd[8], const uchar *ntlmchalresp, uchar p24[24])
185 {
186         uchar p21[21];
187  
188         memset(p21,'\0',21);
189         memcpy(p21, passwd, 8);    
190         memset(p21 + 8, 0xbd, 8);    
191
192         E_P24(p21, ntlmchalresp, p24);
193 #ifdef DEBUG_PASSWORD
194         DEBUG(100,("NTLMSSPOWFencrypt: p21, c8, p24\n"));
195         dump_data(100, (char *)p21, 21);
196         dump_data(100, (const char *)ntlmchalresp, 8);
197         dump_data(100, (char *)p24, 24);
198 #endif
199 }
200
201
202 /* Does the NT MD4 hash then des encryption. */
203  
204 void SMBNTencrypt(const char *passwd, uchar *c8, uchar *p24)
205 {
206         uchar 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, (char *)p21, 16);
216         dump_data(100, (char *)c8, 8);
217         dump_data(100, (char *)p24, 24);
218 #endif
219 }
220
221 BOOL make_oem_passwd_hash(char data[516], const char *passwd, uchar old_pw_hash[16], BOOL unicode)
222 {
223         int new_pw_len = strlen(passwd) * (unicode ? 2 : 1);
224
225         if (new_pw_len > 512)
226         {
227                 DEBUG(0,("make_oem_passwd_hash: new password is too long.\n"));
228                 return False;
229         }
230
231         /*
232          * Now setup the data area.
233          * We need to generate a random fill
234          * for this area to make it harder to
235          * decrypt. JRA.
236          */
237         generate_random_buffer((unsigned char *)data, 516, False);
238         push_string(NULL, &data[512 - new_pw_len], passwd, new_pw_len, 
239                     STR_NOALIGN | (unicode?STR_UNICODE:STR_ASCII));
240         SIVAL(data, 512, new_pw_len);
241
242 #ifdef DEBUG_PASSWORD
243         DEBUG(100,("make_oem_passwd_hash\n"));
244         dump_data(100, data, 516);
245 #endif
246         SamOEMhash( (unsigned char *)data, (unsigned char *)old_pw_hash, 516);
247
248         return True;
249 }
250
251 /* Does the md5 encryption from the NT hash for NTLMv2. */
252 void SMBOWFencrypt_ntv2(const uchar kr[16],
253                         const DATA_BLOB srv_chal,
254                         const DATA_BLOB cli_chal,
255                         uchar resp_buf[16])
256 {
257         HMACMD5Context ctx;
258
259         hmac_md5_init_limK_to_64(kr, 16, &ctx);
260         hmac_md5_update(srv_chal.data, srv_chal.length, &ctx);
261         hmac_md5_update(cli_chal.data, cli_chal.length, &ctx);
262         hmac_md5_final(resp_buf, &ctx);
263
264 #ifdef DEBUG_PASSWORD
265         DEBUG(100, ("SMBOWFencrypt_ntv2: srv_chal, cli_chal, resp_buf\n"));
266         dump_data(100, srv_chal.data, srv_chal.length);
267         dump_data(100, cli_chal.data, cli_chal.length);
268         dump_data(100, resp_buf, 16);
269 #endif
270 }
271
272 void SMBsesskeygen_ntv2(const uchar kr[16],
273                         const uchar * nt_resp, uint8 sess_key[16])
274 {
275         HMACMD5Context ctx;
276
277         hmac_md5_init_limK_to_64(kr, 16, &ctx);
278         hmac_md5_update(nt_resp, 16, &ctx);
279         hmac_md5_final((unsigned char *)sess_key, &ctx);
280
281 #ifdef DEBUG_PASSWORD
282         DEBUG(100, ("SMBsesskeygen_ntv2:\n"));
283         dump_data(100, sess_key, 16);
284 #endif
285 }
286
287 void SMBsesskeygen_ntv1(const uchar kr[16],
288                         const uchar * nt_resp, uint8 sess_key[16])
289 {
290         mdfour((unsigned char *)sess_key, kr, 16);
291
292 #ifdef DEBUG_PASSWORD
293         DEBUG(100, ("SMBsesskeygen_ntv1:\n"));
294         dump_data(100, sess_key, 16);
295 #endif
296 }
297
298 DATA_BLOB NTLMv2_generate_response(uchar ntlm_v2_hash[16],
299                                    DATA_BLOB server_chal, size_t client_chal_length)
300 {
301         uchar ntlmv2_response[16];
302         DATA_BLOB ntlmv2_client_data;
303         DATA_BLOB final_response;
304         
305         /* NTLMv2 */
306
307         /* We also get to specify some random data */
308         ntlmv2_client_data = data_blob(NULL, client_chal_length);
309         generate_random_buffer(ntlmv2_client_data.data, ntlmv2_client_data.length, False);
310         
311         /* Given that data, and the challenge from the server, generate a response */
312         SMBOWFencrypt_ntv2(ntlm_v2_hash, server_chal, ntlmv2_client_data, ntlmv2_response);
313         
314         /* put it into nt_response, for the code below to put into the packet */
315         final_response = data_blob(NULL, ntlmv2_client_data.length + sizeof(ntlmv2_response));
316         memcpy(final_response.data, ntlmv2_response, sizeof(ntlmv2_response));
317         /* after the first 16 bytes is the random data we generated above, so the server can verify us with it */
318         memcpy(final_response.data + sizeof(ntlmv2_response), ntlmv2_client_data.data, ntlmv2_client_data.length);
319         data_blob_free(&ntlmv2_client_data);
320
321         return final_response;
322 }
323
324 BOOL SMBNTLMv2encrypt(const char *user, const char *domain, const char *password, 
325                       const DATA_BLOB server_chal, 
326                       DATA_BLOB *lm_response, DATA_BLOB *nt_response, 
327                       DATA_BLOB *session_key) 
328 {
329         uchar nt_hash[16];
330         uchar ntlm_v2_hash[16];
331         E_md4hash(password, nt_hash);
332
333         /* We don't use the NT# directly.  Instead we use it mashed up with
334            the username and domain.
335            This prevents username swapping during the auth exchange
336         */
337         if (!ntv2_owf_gen(nt_hash, user, domain, ntlm_v2_hash)) {
338                 return False;
339         }
340         
341         *nt_response = NTLMv2_generate_response(ntlm_v2_hash, server_chal, 64 /* pick a number, > 8 */);
342         
343         /* LMv2 */
344         
345         *lm_response = NTLMv2_generate_response(ntlm_v2_hash, server_chal, 8);
346         
347         *session_key = data_blob(NULL, 16);
348         
349         /* The NTLMv2 calculations also provide a session key, for signing etc later */
350         /* use only the first 16 bytes of nt_response for session key */
351         SMBsesskeygen_ntv2(ntlm_v2_hash, nt_response->data, session_key->data);
352
353         return True;
354 }
355
356 /***********************************************************
357  encode a password buffer.  The caller gets to figure out 
358  what to put in it.
359 ************************************************************/
360 BOOL encode_pw_buffer(char buffer[516], char *new_pw, int new_pw_length)
361 {
362         generate_random_buffer((unsigned char *)buffer, 516, True);
363
364         memcpy(&buffer[512 - new_pw_length], new_pw, new_pw_length);
365
366         /* 
367          * The length of the new password is in the last 4 bytes of
368          * the data buffer.
369          */
370         SIVAL(buffer, 512, new_pw_length);
371
372         return True;
373 }
374
375 /***********************************************************
376  decode a password buffer
377  *new_pw_len is the length in bytes of the possibly mulitbyte
378  returned password including termination.
379 ************************************************************/
380 BOOL decode_pw_buffer(char in_buffer[516], char *new_pwrd,
381                       int new_pwrd_size, uint32 *new_pw_len)
382 {
383         int byte_len=0;
384
385         /*
386           Warning !!! : This function is called from some rpc call.
387           The password IN the buffer is a UNICODE string.
388           The password IN new_pwrd is an ASCII string
389           If you reuse that code somewhere else check first.
390         */
391
392         /* The length of the new password is in the last 4 bytes of the data buffer. */
393
394         byte_len = IVAL(in_buffer, 512);
395
396 #ifdef DEBUG_PASSWORD
397         dump_data(100, in_buffer, 516);
398 #endif
399
400         /* Password cannot be longer than 128 characters */
401         if ( (byte_len < 0) || (byte_len > new_pwrd_size - 1)) {
402                 DEBUG(0, ("decode_pw_buffer: incorrect password length (%d).\n", byte_len));
403                 DEBUG(0, ("decode_pw_buffer: check that 'encrypt passwords = yes'\n"));
404                 return False;
405         }
406
407         /* decode into the return buffer.  Buffer must be a pstring */
408         *new_pw_len = pull_string(NULL, new_pwrd, &in_buffer[512 - byte_len], new_pwrd_size, byte_len, STR_UNICODE);
409
410 #ifdef DEBUG_PASSWORD
411         DEBUG(100,("decode_pw_buffer: new_pwrd: "));
412         dump_data(100, (char *)new_pwrd, *new_pw_len);
413         DEBUG(100,("multibyte len:%d\n", *new_pw_len));
414         DEBUG(100,("original char len:%d\n", byte_len/2));
415 #endif
416         
417         return True;
418 }
419
420 /***********************************************************
421  SMB signing - setup the MAC key.
422 ************************************************************/
423
424 void cli_calculate_mac_key(struct cli_state *cli, const uchar user_session_key[16], const DATA_BLOB response)
425 {
426         
427         memcpy(&cli->sign_info.mac_key[0], user_session_key, 16);
428         memcpy(&cli->sign_info.mac_key[16],response.data, MIN(response.length, 40 - 16));
429         cli->sign_info.mac_key_len = MIN(response.length + 16, 40);
430         cli->sign_info.use_smb_signing = True;
431
432         /* These calls are INCONPATIBLE with SMB signing */
433         cli->readbraw_supported = False;
434         cli->writebraw_supported = False;
435
436         /* Reset the sequence number in case we had a previous (aborted) attempt */
437         cli->sign_info.send_seq_num = 2;
438 }
439
440 /***********************************************************
441  SMB signing - calculate a MAC to send.
442 ************************************************************/
443
444 void cli_caclulate_sign_mac(struct cli_state *cli)
445 {
446         unsigned char calc_md5_mac[16];
447         struct MD5Context md5_ctx;
448
449         if (cli->sign_info.temp_smb_signing) {
450                 memcpy(&cli->outbuf[smb_ss_field], "SignRequest", 8);
451                 cli->sign_info.temp_smb_signing = False;
452                 return;
453         }
454
455         if (!cli->sign_info.use_smb_signing) {
456                 return;
457         }
458
459         /*
460          * Firstly put the sequence number into the first 4 bytes.
461          * and zero out the next 4 bytes.
462          */
463         SIVAL(cli->outbuf, smb_ss_field, cli->sign_info.send_seq_num);
464         SIVAL(cli->outbuf, smb_ss_field + 4, 0);
465
466         /* Calculate the 16 byte MAC and place first 8 bytes into the field. */
467         MD5Init(&md5_ctx);
468         MD5Update(&md5_ctx, cli->sign_info.mac_key, cli->sign_info.mac_key_len);
469         MD5Update(&md5_ctx, cli->outbuf + 4, smb_len(cli->outbuf));
470         MD5Final(calc_md5_mac, &md5_ctx);
471
472         memcpy(&cli->outbuf[smb_ss_field], calc_md5_mac, 8);
473
474 /*      cli->outbuf[smb_ss_field+2]=0; 
475         Uncomment this to test if the remote server actually verifies signitures...*/
476         cli->sign_info.send_seq_num++;
477         cli->sign_info.reply_seq_num = cli->sign_info.send_seq_num;
478         cli->sign_info.send_seq_num++;
479 }
480
481 /***********************************************************
482  SMB signing - check a MAC sent by server.
483 ************************************************************/
484
485 BOOL cli_check_sign_mac(struct cli_state *cli)
486 {
487         unsigned char calc_md5_mac[16];
488         unsigned char server_sent_mac[8];
489         struct MD5Context md5_ctx;
490
491         if (cli->sign_info.temp_smb_signing) {
492                 return True;
493         }
494
495         if (!cli->sign_info.use_smb_signing) {
496                 return True;
497         }
498
499         /*
500          * Firstly put the sequence number into the first 4 bytes.
501          * and zero out the next 4 bytes.
502          */
503
504         memcpy(server_sent_mac, &cli->inbuf[smb_ss_field], sizeof(server_sent_mac));
505
506         SIVAL(cli->inbuf, smb_ss_field, cli->sign_info.reply_seq_num);
507         SIVAL(cli->inbuf, smb_ss_field + 4, 0);
508
509         /* Calculate the 16 byte MAC and place first 8 bytes into the field. */
510         MD5Init(&md5_ctx);
511         MD5Update(&md5_ctx, cli->sign_info.mac_key, cli->sign_info.mac_key_len);
512         MD5Update(&md5_ctx, cli->inbuf + 4, smb_len(cli->inbuf));
513         MD5Final(calc_md5_mac, &md5_ctx);
514
515         return (memcmp(server_sent_mac, calc_md5_mac, 8) == 0);
516 }