libcli:auth: Return NTSTATUS for encode_or_decode_arc4_passwd_buffer()
[garming/samba-autobuild/.git] / 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 "../libcli/auth/msrpc_parse.h"
27 #include "../lib/crypto/crypto.h"
28 #include "../libcli/auth/libcli_auth.h"
29 #include "../librpc/gen_ndr/ndr_ntlmssp.h"
30
31 #include "lib/crypto/gnutls_helpers.h"
32 #include <gnutls/gnutls.h>
33 #include <gnutls/crypto.h>
34
35 void SMBencrypt_hash(const uint8_t lm_hash[16], const uint8_t *c8, uint8_t p24[24])
36 {
37         uint8_t p21[21];
38
39         memset(p21,'\0',21);
40         memcpy(p21, lm_hash, 16);
41
42         SMBOWFencrypt(p21, c8, p24);
43
44 #ifdef DEBUG_PASSWORD
45         DEBUG(100,("SMBencrypt_hash: lm#, challenge, response\n"));
46         dump_data(100, p21, 16);
47         dump_data(100, c8, 8);
48         dump_data(100, p24, 24);
49 #endif
50 }
51
52 /*
53    This implements the X/Open SMB password encryption
54    It takes a password ('unix' string), a 8 byte "crypt key"
55    and puts 24 bytes of encrypted password into p24
56
57    Returns False if password must have been truncated to create LM hash
58 */
59
60 bool SMBencrypt(const char *passwd, const uint8_t *c8, uint8_t p24[24])
61 {
62         bool ret;
63         uint8_t lm_hash[16];
64
65         ret = E_deshash(passwd, lm_hash);
66         SMBencrypt_hash(lm_hash, c8, p24);
67         return ret;
68 }
69
70 /**
71  * Creates the MD4 Hash of the users password in NT UNICODE.
72  * @param passwd password in 'unix' charset.
73  * @param p16 return password hashed with md4, caller allocated 16 byte buffer
74  */
75
76 bool E_md4hash(const char *passwd, uint8_t p16[16])
77 {
78         size_t len;
79         smb_ucs2_t *wpwd;
80         bool ret;
81
82         ret = push_ucs2_talloc(NULL, &wpwd, passwd, &len);
83         if (!ret || len < 2) {
84                 /* We don't want to return fixed data, as most callers
85                  * don't check */
86                 mdfour(p16, (const uint8_t *)passwd, strlen(passwd));
87                 return false;
88         }
89
90         len -= 2;
91         mdfour(p16, (const uint8_t *)wpwd, len);
92
93         talloc_free(wpwd);
94         return true;
95 }
96
97 /**
98  * Creates the MD5 Hash of a combination of 16 byte salt and 16 byte NT hash.
99  * @param 16 byte salt.
100  * @param 16 byte NT hash.
101  * @param 16 byte return hashed with md5, caller allocated 16 byte buffer
102  */
103
104 void E_md5hash(const uint8_t salt[16], const uint8_t nthash[16], uint8_t hash_out[16])
105 {
106         gnutls_hash_hd_t hash_hnd = NULL;
107         int rc;
108
109         rc = gnutls_hash_init(&hash_hnd, GNUTLS_DIG_MD5);
110         if (rc < 0) {
111                 goto out;
112         }
113
114         rc = gnutls_hash(hash_hnd, salt, 16);
115         if (rc < 0) {
116                 gnutls_hash_deinit(hash_hnd, NULL);
117                 goto out;
118         }
119         rc = gnutls_hash(hash_hnd, nthash, 16);
120         if (rc < 0) {
121                 gnutls_hash_deinit(hash_hnd, NULL);
122                 goto out;
123         }
124         gnutls_hash_deinit(hash_hnd, hash_out);
125
126 out:
127         return;
128 }
129
130 /**
131  * Creates the DES forward-only Hash of the users password in DOS ASCII charset
132  * @param passwd password in 'unix' charset.
133  * @param p16 return password hashed with DES, caller allocated 16 byte buffer
134  * @return false if password was > 14 characters, and therefore may be incorrect, otherwise true
135  * @note p16 is filled in regardless
136  */
137
138 bool E_deshash(const char *passwd, uint8_t p16[16])
139 {
140         bool ret;
141         uint8_t dospwd[14];
142         TALLOC_CTX *frame = talloc_stackframe();
143
144         size_t converted_size;
145
146         char *tmpbuf;
147
148         ZERO_STRUCT(dospwd);
149
150         tmpbuf = strupper_talloc(frame, passwd);
151         if (tmpbuf == NULL) {
152                 /* Too many callers don't check this result, we need to fill in the buffer with something */
153                 strlcpy((char *)dospwd, passwd ? passwd : "", sizeof(dospwd));
154                 E_P16(dospwd, p16);
155                 talloc_free(frame);
156                 return false;
157         }
158
159         ZERO_STRUCT(dospwd);
160
161         ret = convert_string_error(CH_UNIX, CH_DOS, tmpbuf, strlen(tmpbuf), dospwd, sizeof(dospwd), &converted_size);
162         talloc_free(frame);
163
164         /* Only the first 14 chars are considered, password need not
165          * be null terminated.  We do this in the error and success
166          * case to avoid returning a fixed 'password' buffer, but
167          * callers should not use it when E_deshash returns false */
168
169         E_P16((const uint8_t *)dospwd, p16);
170
171         ZERO_STRUCT(dospwd);
172
173         return ret;
174 }
175
176 /**
177  * Creates the MD4 and DES (LM) Hash of the users password.
178  * MD4 is of the NT Unicode, DES is of the DOS UPPERCASE password.
179  * @param passwd password in 'unix' charset.
180  * @param nt_p16 return password hashed with md4, caller allocated 16 byte buffer
181  * @param p16 return password hashed with des, caller allocated 16 byte buffer
182  */
183
184 /* Does both the NT and LM owfs of a user's password */
185 void nt_lm_owf_gen(const char *pwd, uint8_t nt_p16[16], uint8_t p16[16])
186 {
187         /* Calculate the MD4 hash (NT compatible) of the password */
188         memset(nt_p16, '\0', 16);
189         E_md4hash(pwd, nt_p16);
190
191 #ifdef DEBUG_PASSWORD
192         DEBUG(100,("nt_lm_owf_gen: pwd, nt#\n"));
193         dump_data(120, (const uint8_t *)pwd, strlen(pwd));
194         dump_data(100, nt_p16, 16);
195 #endif
196
197         E_deshash(pwd, (uint8_t *)p16);
198
199 #ifdef DEBUG_PASSWORD
200         DEBUG(100,("nt_lm_owf_gen: pwd, lm#\n"));
201         dump_data(120, (const uint8_t *)pwd, strlen(pwd));
202         dump_data(100, p16, 16);
203 #endif
204 }
205
206 /* Does both the NTLMv2 owfs of a user's password */
207 bool ntv2_owf_gen(const uint8_t owf[16],
208                   const char *user_in, const char *domain_in,
209                   uint8_t kr_buf[16])
210 {
211         smb_ucs2_t *user;
212         smb_ucs2_t *domain;
213         size_t user_byte_len;
214         size_t domain_byte_len;
215         gnutls_hmac_hd_t hmac_hnd = NULL;
216         int rc;
217         bool ok = false;
218         TALLOC_CTX *mem_ctx = talloc_init("ntv2_owf_gen for %s\\%s", domain_in, user_in);
219
220         if (!mem_ctx) {
221                 return false;
222         }
223
224         if (!user_in) {
225                 user_in = "";
226         }
227
228         if (!domain_in) {
229                 domain_in = "";
230         }
231
232         user_in = strupper_talloc(mem_ctx, user_in);
233         if (user_in == NULL) {
234                 talloc_free(mem_ctx);
235                 return false;
236         }
237
238         ok = push_ucs2_talloc(mem_ctx, &user, user_in, &user_byte_len );
239         if (!ok) {
240                 DEBUG(0, ("push_uss2_talloc() for user failed)\n"));
241                 talloc_free(mem_ctx);
242                 return false;
243         }
244
245         ok = push_ucs2_talloc(mem_ctx, &domain, domain_in, &domain_byte_len);
246         if (!ok) {
247                 DEBUG(0, ("push_ucs2_talloc() for domain failed\n"));
248                 talloc_free(mem_ctx);
249                 return false;
250         }
251
252         SMB_ASSERT(user_byte_len >= 2);
253         SMB_ASSERT(domain_byte_len >= 2);
254
255         /* We don't want null termination */
256         user_byte_len = user_byte_len - 2;
257         domain_byte_len = domain_byte_len - 2;
258
259         rc = gnutls_hmac_init(&hmac_hnd,
260                               GNUTLS_MAC_MD5,
261                               owf,
262                               16);
263         if (rc < 0) {
264                 ok = false;
265                 goto out;
266         }
267
268         rc = gnutls_hmac(hmac_hnd, user, user_byte_len);
269         if (rc < 0) {
270                 gnutls_hmac_deinit(hmac_hnd, NULL);
271                 ok = false;
272                 goto out;
273         }
274         rc = gnutls_hmac(hmac_hnd, domain, domain_byte_len);
275         if (rc < 0) {
276                 gnutls_hmac_deinit(hmac_hnd, NULL);
277                 ok = false;
278                 goto out;
279         }
280
281         gnutls_hmac_deinit(hmac_hnd, kr_buf);
282
283 #ifdef DEBUG_PASSWORD
284         DEBUG(100, ("ntv2_owf_gen: user, domain, owfkey, kr\n"));
285         dump_data(100, (uint8_t *)user, user_byte_len);
286         dump_data(100, (uint8_t *)domain, domain_byte_len);
287         dump_data(100, owf, 16);
288         dump_data(100, kr_buf, 16);
289 #endif
290
291         ok = true;
292 out:
293         talloc_free(mem_ctx);
294         return ok;
295 }
296
297 /* Does the des encryption from the NT or LM MD4 hash. */
298 void SMBOWFencrypt(const uint8_t passwd[16], const uint8_t *c8, uint8_t p24[24])
299 {
300         uint8_t p21[21];
301
302         ZERO_STRUCT(p21);
303
304         memcpy(p21, passwd, 16);
305         E_P24(p21, c8, p24);
306 }
307
308 /* Does the des encryption. */
309
310 void SMBNTencrypt_hash(const uint8_t nt_hash[16], const uint8_t *c8, uint8_t *p24)
311 {
312         uint8_t p21[21];
313
314         memset(p21,'\0',21);
315         memcpy(p21, nt_hash, 16);
316         SMBOWFencrypt(p21, c8, p24);
317
318 #ifdef DEBUG_PASSWORD
319         DEBUG(100,("SMBNTencrypt: nt#, challenge, response\n"));
320         dump_data(100, p21, 16);
321         dump_data(100, c8, 8);
322         dump_data(100, p24, 24);
323 #endif
324 }
325
326 /* Does the NT MD4 hash then des encryption. Plaintext version of the above. */
327
328 void SMBNTencrypt(const char *passwd, const uint8_t *c8, uint8_t *p24)
329 {
330         uint8_t nt_hash[16];
331         E_md4hash(passwd, nt_hash);
332         SMBNTencrypt_hash(nt_hash, c8, p24);
333 }
334
335
336 /* Does the md5 encryption from the Key Response for NTLMv2. */
337 void SMBOWFencrypt_ntv2(const uint8_t kr[16],
338                         const DATA_BLOB *srv_chal,
339                         const DATA_BLOB *smbcli_chal,
340                         uint8_t resp_buf[16])
341 {
342         gnutls_hmac_hd_t hmac_hnd = NULL;
343         int rc;
344
345         rc = gnutls_hmac_init(&hmac_hnd,
346                               GNUTLS_MAC_MD5,
347                               kr,
348                               16);
349         if (rc < 0) {
350                 return;
351         }
352
353         rc = gnutls_hmac(hmac_hnd, srv_chal->data, srv_chal->length);
354         if (rc < 0) {
355                 return;
356         }
357         rc = gnutls_hmac(hmac_hnd, smbcli_chal->data, smbcli_chal->length);
358         if (rc < 0) {
359                 gnutls_hmac_deinit(hmac_hnd, NULL);
360                 return;
361         }
362
363         gnutls_hmac_deinit(hmac_hnd, resp_buf);
364
365 #ifdef DEBUG_PASSWORD
366         DEBUG(100, ("SMBOWFencrypt_ntv2: srv_chal, smbcli_chal, resp_buf\n"));
367         dump_data(100, srv_chal->data, srv_chal->length);
368         dump_data(100, smbcli_chal->data, smbcli_chal->length);
369         dump_data(100, resp_buf, 16);
370 #endif
371 }
372
373 void SMBsesskeygen_ntv2(const uint8_t kr[16],
374                         const uint8_t * nt_resp, uint8_t sess_key[16])
375 {
376         /* a very nice, 128 bit, variable session key */
377         gnutls_hmac_fast(GNUTLS_MAC_MD5,
378                          kr,
379                          16,
380                          nt_resp,
381                          16,
382                          sess_key);
383
384 #ifdef DEBUG_PASSWORD
385         DEBUG(100, ("SMBsesskeygen_ntv2:\n"));
386         dump_data(100, sess_key, 16);
387 #endif
388 }
389
390 void SMBsesskeygen_ntv1(const uint8_t kr[16], uint8_t sess_key[16])
391 {
392         /* yes, this session key does not change - yes, this
393            is a problem - but it is 128 bits */
394
395         mdfour((uint8_t *)sess_key, kr, 16);
396
397 #ifdef DEBUG_PASSWORD
398         DEBUG(100, ("SMBsesskeygen_ntv1:\n"));
399         dump_data(100, sess_key, 16);
400 #endif
401 }
402
403 void SMBsesskeygen_lm_sess_key(const uint8_t lm_hash[16],
404                                const uint8_t lm_resp[24], /* only uses 8 */
405                                uint8_t sess_key[16])
406 {
407         /* Calculate the LM session key (effective length 40 bits,
408            but changes with each session) */
409         uint8_t p24[24];
410         uint8_t partial_lm_hash[14];
411
412         memcpy(partial_lm_hash, lm_hash, 8);
413         memset(partial_lm_hash + 8, 0xbd, 6);
414
415         des_crypt56(p24,   lm_resp, partial_lm_hash,     1);
416         des_crypt56(p24+8, lm_resp, partial_lm_hash + 7, 1);
417
418         memcpy(sess_key, p24, 16);
419
420 #ifdef DEBUG_PASSWORD
421         DEBUG(100, ("SMBsesskeygen_lm_sess_key: \n"));
422         dump_data(100, sess_key, 16);
423 #endif
424 }
425
426 DATA_BLOB NTLMv2_generate_names_blob(TALLOC_CTX *mem_ctx,
427                                      const char *hostname,
428                                      const char *domain)
429 {
430         DATA_BLOB names_blob = data_blob_talloc(mem_ctx, NULL, 0);
431
432         /* Deliberately ignore return here.. */
433         if (hostname != NULL) {
434                 (void)msrpc_gen(mem_ctx, &names_blob,
435                           "aaa",
436                           MsvAvNbDomainName, domain,
437                           MsvAvNbComputerName, hostname,
438                           MsvAvEOL, "");
439         } else {
440                 (void)msrpc_gen(mem_ctx, &names_blob,
441                           "aa",
442                           MsvAvNbDomainName, domain,
443                           MsvAvEOL, "");
444         }
445         return names_blob;
446 }
447
448 static DATA_BLOB NTLMv2_generate_client_data(TALLOC_CTX *mem_ctx,
449                                              NTTIME nttime,
450                                              const DATA_BLOB *names_blob)
451 {
452         uint8_t client_chal[8];
453         DATA_BLOB response = data_blob(NULL, 0);
454         uint8_t long_date[8];
455
456         generate_random_buffer(client_chal, sizeof(client_chal));
457
458         push_nttime(long_date, 0, nttime);
459
460         /* See http://www.ubiqx.org/cifs/SMB.html#SMB.8.5 */
461
462         /* Deliberately ignore return here.. */
463         (void)msrpc_gen(mem_ctx, &response, "ddbbdb",
464                   0x00000101,     /* Header  */
465                   0,              /* 'Reserved'  */
466                   long_date, 8,   /* Timestamp */
467                   client_chal, 8, /* client challenge */
468                   0,              /* Unknown */
469                   names_blob->data, names_blob->length);        /* End of name list */
470
471         return response;
472 }
473
474 static DATA_BLOB NTLMv2_generate_response(TALLOC_CTX *out_mem_ctx,
475                                           const uint8_t ntlm_v2_hash[16],
476                                           const DATA_BLOB *server_chal,
477                                           NTTIME nttime,
478                                           const DATA_BLOB *names_blob)
479 {
480         uint8_t ntlmv2_response[16];
481         DATA_BLOB ntlmv2_client_data;
482         DATA_BLOB final_response;
483
484         TALLOC_CTX *mem_ctx = talloc_named(out_mem_ctx, 0,
485                                            "NTLMv2_generate_response internal context");
486
487         if (!mem_ctx) {
488                 return data_blob(NULL, 0);
489         }
490
491         /* NTLMv2 */
492         /* generate some data to pass into the response function - including
493            the hostname and domain name of the server */
494         ntlmv2_client_data = NTLMv2_generate_client_data(mem_ctx, nttime, names_blob);
495
496         /* Given that data, and the challenge from the server, generate a response */
497         SMBOWFencrypt_ntv2(ntlm_v2_hash, server_chal, &ntlmv2_client_data, ntlmv2_response);
498
499         final_response = data_blob_talloc(out_mem_ctx, NULL, sizeof(ntlmv2_response) + ntlmv2_client_data.length);
500
501         memcpy(final_response.data, ntlmv2_response, sizeof(ntlmv2_response));
502
503         memcpy(final_response.data+sizeof(ntlmv2_response),
504                ntlmv2_client_data.data, ntlmv2_client_data.length);
505
506         talloc_free(mem_ctx);
507
508         return final_response;
509 }
510
511 static DATA_BLOB LMv2_generate_response(TALLOC_CTX *mem_ctx,
512                                         const uint8_t ntlm_v2_hash[16],
513                                         const DATA_BLOB *server_chal)
514 {
515         uint8_t lmv2_response[16];
516         DATA_BLOB lmv2_client_data = data_blob_talloc(mem_ctx, NULL, 8);
517         DATA_BLOB final_response = data_blob_talloc(mem_ctx, NULL,24);
518
519         /* LMv2 */
520         /* client-supplied random data */
521         generate_random_buffer(lmv2_client_data.data, lmv2_client_data.length);
522
523         /* Given that data, and the challenge from the server, generate a response */
524         SMBOWFencrypt_ntv2(ntlm_v2_hash, server_chal, &lmv2_client_data, lmv2_response);
525         memcpy(final_response.data, lmv2_response, sizeof(lmv2_response));
526
527         /* after the first 16 bytes is the random data we generated above,
528            so the server can verify us with it */
529         memcpy(final_response.data+sizeof(lmv2_response),
530                lmv2_client_data.data, lmv2_client_data.length);
531
532         data_blob_free(&lmv2_client_data);
533
534         return final_response;
535 }
536
537 bool SMBNTLMv2encrypt_hash(TALLOC_CTX *mem_ctx,
538                            const char *user, const char *domain, const uint8_t nt_hash[16],
539                            const DATA_BLOB *server_chal,
540                            const NTTIME *server_timestamp,
541                            const DATA_BLOB *names_blob,
542                            DATA_BLOB *lm_response, DATA_BLOB *nt_response,
543                            DATA_BLOB *lm_session_key, DATA_BLOB *user_session_key)
544 {
545         uint8_t ntlm_v2_hash[16];
546
547         /* We don't use the NT# directly.  Instead we use it mashed up with
548            the username and domain.
549            This prevents username swapping during the auth exchange
550         */
551         if (!ntv2_owf_gen(nt_hash, user, domain, ntlm_v2_hash)) {
552                 return false;
553         }
554
555         if (nt_response) {
556                 const NTTIME *nttime = server_timestamp;
557                 NTTIME _now = 0;
558
559                 if (nttime == NULL) {
560                         struct timeval tv_now = timeval_current();
561                         _now = timeval_to_nttime(&tv_now);
562                         nttime = &_now;
563                 }
564
565                 *nt_response = NTLMv2_generate_response(mem_ctx,
566                                                         ntlm_v2_hash,
567                                                         server_chal,
568                                                         *nttime,
569                                                         names_blob);
570                 if (user_session_key) {
571                         *user_session_key = data_blob_talloc(mem_ctx, NULL, 16);
572
573                         /* The NTLMv2 calculations also provide a session key, for signing etc later */
574                         /* use only the first 16 bytes of nt_response for session key */
575                         SMBsesskeygen_ntv2(ntlm_v2_hash, nt_response->data, user_session_key->data);
576                 }
577         }
578
579         /* LMv2 */
580
581         if (lm_response) {
582                 if (server_timestamp != NULL) {
583                         *lm_response = data_blob_talloc_zero(mem_ctx, 24);
584                 } else {
585                         *lm_response = LMv2_generate_response(mem_ctx,
586                                                               ntlm_v2_hash,
587                                                               server_chal);
588                 }
589                 if (lm_session_key) {
590                         *lm_session_key = data_blob_talloc(mem_ctx, NULL, 16);
591
592                         /* The NTLMv2 calculations also provide a session key, for signing etc later */
593                         /* use only the first 16 bytes of lm_response for session key */
594                         SMBsesskeygen_ntv2(ntlm_v2_hash, lm_response->data, lm_session_key->data);
595                 }
596         }
597
598         return true;
599 }
600
601 bool SMBNTLMv2encrypt(TALLOC_CTX *mem_ctx,
602                       const char *user, const char *domain,
603                       const char *password,
604                       const DATA_BLOB *server_chal,
605                       const DATA_BLOB *names_blob,
606                       DATA_BLOB *lm_response, DATA_BLOB *nt_response,
607                       DATA_BLOB *lm_session_key, DATA_BLOB *user_session_key)
608 {
609         uint8_t nt_hash[16];
610         E_md4hash(password, nt_hash);
611
612         return SMBNTLMv2encrypt_hash(mem_ctx,
613                                      user, domain, nt_hash,
614                                      server_chal, NULL, names_blob,
615                                      lm_response, nt_response, lm_session_key, user_session_key);
616 }
617
618 NTSTATUS NTLMv2_RESPONSE_verify_netlogon_creds(const char *account_name,
619                         const char *account_domain,
620                         const DATA_BLOB response,
621                         const struct netlogon_creds_CredentialState *creds,
622                         const char *workgroup)
623 {
624         TALLOC_CTX *frame = NULL;
625         /* RespType + HiRespType */
626         static const char *magic = "\x01\x01";
627         int cmp;
628         struct NTLMv2_RESPONSE v2_resp;
629         enum ndr_err_code err;
630         const struct AV_PAIR *av_nb_cn = NULL;
631         const struct AV_PAIR *av_nb_dn = NULL;
632
633         if (response.length < 48) {
634                 /*
635                  * NTLMv2_RESPONSE has at least 48 bytes.
636                  */
637                 return NT_STATUS_OK;
638         }
639
640         cmp = memcmp(response.data + 16, magic, 2);
641         if (cmp != 0) {
642                 /*
643                  * It doesn't look like a valid NTLMv2_RESPONSE
644                  */
645                 return NT_STATUS_OK;
646         }
647
648         frame = talloc_stackframe();
649
650         err = ndr_pull_struct_blob(&response, frame, &v2_resp,
651                 (ndr_pull_flags_fn_t)ndr_pull_NTLMv2_RESPONSE);
652         if (!NDR_ERR_CODE_IS_SUCCESS(err)) {
653                 NTSTATUS status;
654                 status = ndr_map_error2ntstatus(err);
655                 DEBUG(2,("Failed to parse NTLMv2_RESPONSE "
656                          "length %u - %s - %s\n",
657                          (unsigned)response.length,
658                          ndr_map_error2string(err),
659                          nt_errstr(status)));
660                 dump_data(2, response.data, response.length);
661                 TALLOC_FREE(frame);
662                 return status;
663         }
664
665         if (DEBUGLVL(10)) {
666                 NDR_PRINT_DEBUG(NTLMv2_RESPONSE, &v2_resp);
667         }
668
669         /*
670          * Make sure the netbios computer name in the
671          * NTLMv2_RESPONSE matches the computer name
672          * in the secure channel credentials for workstation
673          * trusts.
674          *
675          * And the netbios domain name matches our
676          * workgroup.
677          *
678          * This prevents workstations from requesting
679          * the session key of NTLMSSP sessions of clients
680          * to other hosts.
681          */
682         if (creds->secure_channel_type == SEC_CHAN_WKSTA) {
683                 av_nb_cn = ndr_ntlmssp_find_av(&v2_resp.Challenge.AvPairs,
684                                                MsvAvNbComputerName);
685                 av_nb_dn = ndr_ntlmssp_find_av(&v2_resp.Challenge.AvPairs,
686                                                MsvAvNbDomainName);
687         }
688
689         if (av_nb_cn != NULL) {
690                 const char *v = NULL;
691                 char *a = NULL;
692                 size_t len;
693
694                 v = av_nb_cn->Value.AvNbComputerName;
695
696                 a = talloc_strdup(frame, creds->account_name);
697                 if (a == NULL) {
698                         TALLOC_FREE(frame);
699                         return NT_STATUS_NO_MEMORY;
700                 }
701                 len = strlen(a);
702                 if (len > 0 && a[len - 1] == '$') {
703                         a[len - 1] = '\0';
704                 }
705
706                 cmp = strcasecmp_m(a, v);
707                 if (cmp != 0) {
708                         DEBUG(2,("%s: NTLMv2_RESPONSE with "
709                                  "NbComputerName[%s] rejected "
710                                  "for user[%s\\%s] "
711                                  "against SEC_CHAN_WKSTA[%s/%s] "
712                                  "in workgroup[%s]\n",
713                                  __func__, v,
714                                  account_domain,
715                                  account_name,
716                                  creds->computer_name,
717                                  creds->account_name,
718                                  workgroup));
719                         TALLOC_FREE(frame);
720                         return NT_STATUS_LOGON_FAILURE;
721                 }
722         }
723         if (av_nb_dn != NULL) {
724                 const char *v = NULL;
725
726                 v = av_nb_dn->Value.AvNbDomainName;
727
728                 cmp = strcasecmp_m(workgroup, v);
729                 if (cmp != 0) {
730                         DEBUG(2,("%s: NTLMv2_RESPONSE with "
731                                  "NbDomainName[%s] rejected "
732                                  "for user[%s\\%s] "
733                                  "against SEC_CHAN_WKSTA[%s/%s] "
734                                  "in workgroup[%s]\n",
735                                  __func__, v,
736                                  account_domain,
737                                  account_name,
738                                  creds->computer_name,
739                                  creds->account_name,
740                                  workgroup));
741                         TALLOC_FREE(frame);
742                         return NT_STATUS_LOGON_FAILURE;
743                 }
744         }
745
746         TALLOC_FREE(frame);
747         return NT_STATUS_OK;
748 }
749
750 /***********************************************************
751  encode a password buffer with a unicode password.  The buffer
752  is filled with random data to make it harder to attack.
753 ************************************************************/
754 bool encode_pw_buffer(uint8_t buffer[516], const char *password, int string_flags)
755 {
756         uint8_t new_pw[512];
757         ssize_t new_pw_len;
758
759         /* the incoming buffer can be any alignment. */
760         string_flags |= STR_NOALIGN;
761
762         new_pw_len = push_string(new_pw,
763                                  password,
764                                  sizeof(new_pw), string_flags);
765         if (new_pw_len == -1) {
766                 return false;
767         }
768
769         memcpy(&buffer[512 - new_pw_len], new_pw, new_pw_len);
770
771         generate_random_buffer(buffer, 512 - new_pw_len);
772
773         /*
774          * The length of the new password is in the last 4 bytes of
775          * the data buffer.
776          */
777         SIVAL(buffer, 512, new_pw_len);
778         ZERO_STRUCT(new_pw);
779         return true;
780 }
781
782
783 /***********************************************************
784  decode a password buffer
785  *new_pw_len is the length in bytes of the possibly mulitbyte
786  returned password including termination.
787 ************************************************************/
788
789 bool decode_pw_buffer(TALLOC_CTX *ctx,
790                       uint8_t in_buffer[516],
791                       char **pp_new_pwrd,
792                       size_t *new_pw_len,
793                       charset_t string_charset)
794 {
795         int byte_len=0;
796
797         *pp_new_pwrd = NULL;
798         *new_pw_len = 0;
799
800         /*
801           Warning !!! : This function is called from some rpc call.
802           The password IN the buffer may be a UNICODE string.
803           The password IN new_pwrd is an ASCII string
804           If you reuse that code somewhere else check first.
805         */
806
807         /* The length of the new password is in the last 4 bytes of the data buffer. */
808
809         byte_len = IVAL(in_buffer, 512);
810
811 #ifdef DEBUG_PASSWORD
812         dump_data(100, in_buffer, 516);
813 #endif
814
815         /* Password cannot be longer than the size of the password buffer */
816         if ( (byte_len < 0) || (byte_len > 512)) {
817                 DEBUG(0, ("decode_pw_buffer: incorrect password length (%d).\n", byte_len));
818                 DEBUG(0, ("decode_pw_buffer: check that 'encrypt passwords = yes'\n"));
819                 return false;
820         }
821
822         /* decode into the return buffer. */
823         if (!convert_string_talloc(ctx, string_charset, CH_UNIX,
824                                    &in_buffer[512 - byte_len],
825                                    byte_len,
826                                    (void *)pp_new_pwrd,
827                                    new_pw_len)) {
828                 DEBUG(0, ("decode_pw_buffer: failed to convert incoming password\n"));
829                 return false;
830         }
831
832 #ifdef DEBUG_PASSWORD
833         DEBUG(100,("decode_pw_buffer: new_pwrd: "));
834         dump_data(100, (uint8_t *)*pp_new_pwrd, *new_pw_len);
835         DEBUG(100,("multibyte len:%lu\n", (unsigned long int)*new_pw_len));
836         DEBUG(100,("original char len:%d\n", byte_len/2));
837 #endif
838
839         return true;
840 }
841
842 /***********************************************************
843  Decode an arc4 encrypted password change buffer.
844 ************************************************************/
845
846 NTSTATUS encode_or_decode_arc4_passwd_buffer(unsigned char pw_buf[532],
847                                              const DATA_BLOB *psession_key)
848 {
849         gnutls_hash_hd_t hash_hnd = NULL;
850         unsigned char key_out[16];
851         NTSTATUS status;
852         int rc;
853
854         /* Confounder is last 16 bytes. */
855
856         rc = gnutls_hash_init(&hash_hnd, GNUTLS_DIG_MD5);
857         if (rc < 0) {
858                 status = gnutls_error_to_ntstatus(rc, NT_STATUS_HASH_NOT_SUPPORTED);
859                 goto out;
860         }
861
862         rc = gnutls_hash(hash_hnd, &pw_buf[516], 16);
863         if (rc < 0) {
864                 gnutls_hash_deinit(hash_hnd, NULL);
865                 status = gnutls_error_to_ntstatus(rc, NT_STATUS_HASH_NOT_SUPPORTED);
866                 goto out;
867         }
868         rc = gnutls_hash(hash_hnd, psession_key->data, psession_key->length);
869         if (rc < 0) {
870                 gnutls_hash_deinit(hash_hnd, NULL);
871                 status = gnutls_error_to_ntstatus(rc, NT_STATUS_HASH_NOT_SUPPORTED);
872                 goto out;
873         }
874         gnutls_hash_deinit(hash_hnd, key_out);
875
876         /* arc4 with key_out. */
877         arcfour_crypt(pw_buf, key_out, 516);
878
879         ZERO_ARRAY(key_out);
880
881         status = NT_STATUS_OK;
882 out:
883         return status;
884 }
885
886 /***********************************************************
887  encode a password buffer with an already unicode password.  The
888  rest of the buffer is filled with random data to make it harder to attack.
889 ************************************************************/
890 bool set_pw_in_buffer(uint8_t buffer[516], const DATA_BLOB *password)
891 {
892         if (password->length > 512) {
893                 return false;
894         }
895
896         memcpy(&buffer[512 - password->length], password->data, password->length);
897
898         generate_random_buffer(buffer, 512 - password->length);
899
900         /*
901          * The length of the new password is in the last 4 bytes of
902          * the data buffer.
903          */
904         SIVAL(buffer, 512, password->length);
905         return true;
906 }
907
908 /***********************************************************
909  decode a password buffer
910  *new_pw_size is the length in bytes of the extracted unicode password
911 ************************************************************/
912 bool extract_pw_from_buffer(TALLOC_CTX *mem_ctx,
913                             uint8_t in_buffer[516], DATA_BLOB *new_pass)
914 {
915         int byte_len=0;
916
917         /* The length of the new password is in the last 4 bytes of the data buffer. */
918
919         byte_len = IVAL(in_buffer, 512);
920
921 #ifdef DEBUG_PASSWORD
922         dump_data(100, in_buffer, 516);
923 #endif
924
925         /* Password cannot be longer than the size of the password buffer */
926         if ( (byte_len < 0) || (byte_len > 512)) {
927                 return false;
928         }
929
930         *new_pass = data_blob_talloc(mem_ctx, &in_buffer[512 - byte_len], byte_len);
931
932         if (!new_pass->data) {
933                 return false;
934         }
935
936         return true;
937 }
938
939
940 /* encode a wkssvc_PasswordBuffer:
941  *
942  * similar to samr_CryptPasswordEx. Different: 8byte confounder (instead of
943  * 16byte), confounder in front of the 516 byte buffer (instead of after that
944  * buffer), calling MD5Update() first with session_key and then with confounder
945  * (vice versa in samr) - Guenther */
946
947 void encode_wkssvc_join_password_buffer(TALLOC_CTX *mem_ctx,
948                                         const char *pwd,
949                                         DATA_BLOB *session_key,
950                                         struct wkssvc_PasswordBuffer **pwd_buf)
951 {
952         uint8_t buffer[516];
953         gnutls_hash_hd_t hash_hnd = NULL;
954         struct wkssvc_PasswordBuffer *my_pwd_buf = NULL;
955         DATA_BLOB confounded_session_key;
956         int confounder_len = 8;
957         uint8_t confounder[8];
958         int rc;
959
960         my_pwd_buf = talloc_zero(mem_ctx, struct wkssvc_PasswordBuffer);
961         if (!my_pwd_buf) {
962                 return;
963         }
964
965         confounded_session_key = data_blob_talloc(mem_ctx, NULL, 16);
966
967         encode_pw_buffer(buffer, pwd, STR_UNICODE);
968
969         generate_random_buffer((uint8_t *)confounder, confounder_len);
970
971         rc = gnutls_hash_init(&hash_hnd, GNUTLS_DIG_MD5);
972         if (rc < 0) {
973                 goto out;
974         }
975
976         rc = gnutls_hash(hash_hnd, session_key->data, session_key->length);
977         if (rc < 0) {
978                 gnutls_hash_deinit(hash_hnd, NULL);
979                 goto out;
980         }
981         rc = gnutls_hash(hash_hnd, confounder, confounder_len);
982         if (rc < 0) {
983                 gnutls_hash_deinit(hash_hnd, NULL);
984                 goto out;
985         }
986         gnutls_hash_deinit(hash_hnd, confounded_session_key.data);
987
988         arcfour_crypt_blob(buffer, 516, &confounded_session_key);
989
990         memcpy(&my_pwd_buf->data[0], confounder, confounder_len);
991         ZERO_ARRAY(confounder);
992         memcpy(&my_pwd_buf->data[8], buffer, 516);
993         ZERO_ARRAY(buffer);
994
995         data_blob_clear_free(&confounded_session_key);
996
997         *pwd_buf = my_pwd_buf;
998
999 out:
1000         return;
1001 }
1002
1003 WERROR decode_wkssvc_join_password_buffer(TALLOC_CTX *mem_ctx,
1004                                           struct wkssvc_PasswordBuffer *pwd_buf,
1005                                           DATA_BLOB *session_key,
1006                                           char **pwd)
1007 {
1008         gnutls_hash_hd_t hash_hnd = NULL;
1009         uint8_t buffer[516];
1010         size_t pwd_len;
1011         WERROR result;
1012         bool ok;
1013         int rc;
1014
1015         DATA_BLOB confounded_session_key;
1016
1017         int confounder_len = 8;
1018         uint8_t confounder[8];
1019
1020         *pwd = NULL;
1021
1022         if (!pwd_buf) {
1023                 return WERR_INVALID_PASSWORD;
1024         }
1025
1026         if (session_key->length != 16) {
1027                 DEBUG(10,("invalid session key\n"));
1028                 return WERR_INVALID_PASSWORD;
1029         }
1030
1031         confounded_session_key = data_blob_talloc(mem_ctx, NULL, 16);
1032
1033         memcpy(&confounder, &pwd_buf->data[0], confounder_len);
1034         memcpy(&buffer, &pwd_buf->data[8], 516);
1035
1036         rc = gnutls_hash_init(&hash_hnd, GNUTLS_DIG_MD5);
1037         if (rc < 0) {
1038                 result = gnutls_error_to_werror(rc, WERR_CONTENT_BLOCKED);
1039                 goto out;
1040         }
1041
1042         rc = gnutls_hash(hash_hnd, session_key->data, session_key->length);
1043         if (rc < 0) {
1044                 gnutls_hash_deinit(hash_hnd, NULL);
1045                 result = gnutls_error_to_werror(rc, WERR_CONTENT_BLOCKED);
1046                 goto out;
1047         }
1048         rc = gnutls_hash(hash_hnd, confounder, confounder_len);
1049         if (rc < 0) {
1050                 gnutls_hash_deinit(hash_hnd, NULL);
1051                 result = gnutls_error_to_werror(rc, WERR_CONTENT_BLOCKED);
1052                 goto out;
1053         }
1054         gnutls_hash_deinit(hash_hnd, confounded_session_key.data);
1055
1056         arcfour_crypt_blob(buffer, 516, &confounded_session_key);
1057
1058         ok = decode_pw_buffer(mem_ctx, buffer, pwd, &pwd_len, CH_UTF16);
1059
1060         ZERO_ARRAY(confounder);
1061         ZERO_ARRAY(buffer);
1062
1063         data_blob_clear_free(&confounded_session_key);
1064
1065         if (!ok) {
1066                 result = WERR_INVALID_PASSWORD;
1067                 goto out;
1068         }
1069
1070         result = WERR_OK;
1071 out:
1072         return result;
1073 }
1074