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