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