1 /*
2  * This file and its contents are supplied under the terms of the
3  * Common Development and Distribution License ("CDDL"), version 1.0.
4  * You may only use this file in accordance with the terms of version
5  * 1.0 of the CDDL.
6  *
7  * A full copy of the text of the CDDL should have accompanied this
8  * source.  A copy of the CDDL is also available via the Internet at
9  * http://www.illumos.org/license/CDDL.
10  */
11 
12 /*
13  * Copyright 2019 Nexenta Systems, Inc.  All rights reserved.
14  * Copyright 2022 RackTop Systems, Inc.
15  */
16 
17 /*
18  * Dispatch function for SMB2_NEGOTIATE
19  */
20 
21 #include <smbsrv/smb2_kproto.h>
22 #include <smbsrv/smb2.h>
23 #include <sys/random.h>
24 
25 /*
26  * Note from [MS-SMB2] Sec. 2.2.3:  Windows servers return
27  * invalid parameter if the dialect count is greater than 64
28  * This is here (and not in smb2.h) because this is technically
29  * an implementation detail, not protocol specification.
30  */
31 #define	SMB2_NEGOTIATE_MAX_DIALECTS	64
32 
33 static int smb2_negotiate_common(smb_request_t *, uint16_t);
34 
35 /* List of supported capabilities.  Can be patched for testing. */
36 uint32_t smb2srv_capabilities =
37 	SMB2_CAP_DFS |
38 	SMB2_CAP_LEASING |
39 	SMB2_CAP_LARGE_MTU |
40 	SMB2_CAP_PERSISTENT_HANDLES |
41 #ifndef	_FAKE_KERNEL
42 	SMB2_CAP_ENCRYPTION |
43 #endif
44 	0;
45 
46 /* These are the only capabilities defined for SMB2.X */
47 #define	SMB_2X_CAPS (SMB2_CAP_DFS | SMB2_CAP_LEASING | SMB2_CAP_LARGE_MTU)
48 
49 /*
50  * These are not intended as customer tunables, but dev. & test folks
51  * might want to adjust them (with caution).
52  *
53  * smb2_tcp_bufsize is the TCP buffer size, applied to the network socket
54  * with setsockopt SO_SNDBUF, SO_RCVBUF.  These set the TCP window size.
55  * This is also used as a "sanity limit" for internal send/reply message
56  * allocations.  Note that with compounding SMB2 messages may contain
57  * multiple requests/responses.  This size should be large enough for
58  * at least a few SMB2 requests, and at least 2X smb2_max_rwsize.
59  *
60  * smb2_max_rwsize is what we put in the SMB2 negotiate response to tell
61  * the client the largest read and write request size we'll support.
62  * For now, we're using contiguous allocations, so keep this at 64KB
63  * so that (even with message overhead) allocations stay below 128KB,
64  * avoiding kmem_alloc -> page_create_va thrashing.
65  *
66  * smb2_max_trans is the largest "transact" send or receive, which is
67  * used for directory listings and info set/get operations.
68  */
69 uint32_t smb2_tcp_bufsize = (1<<22);	/* 4MB */
70 uint32_t smb2_max_rwsize = (1<<16);	/* 64KB */
71 uint32_t smb2_max_trans  = (1<<16);	/* 64KB */
72 
73 /*
74  * With clients (e.g. HP scanners) that don't advertise SMB2_CAP_LARGE_MTU
75  * (including all clients using dialect < SMB 2.1), use a "conservative" value
76  * for max r/w size because some older clients misbehave with larger values.
77  * 64KB is recommended in the [MS-SMB2] spec.  (3.3.5.3.1 SMB 2.1 or SMB 3.x
78  * Support) as the minimum so we'll use that.
79  */
80 uint32_t smb2_old_rwsize = (1<<16);	/* 64KB */
81 
82 /*
83  * List of all SMB2 versions we implement.  Note that the
84  * versions we support may be limited by the
85  * _cfg.skc_max_protocol and min_protocol settings.
86  */
87 static uint16_t smb2_versions[] = {
88 	0x202,	/* SMB 2.002 */
89 	0x210,	/* SMB 2.1 */
90 	0x300,	/* SMB 3.0 */
91 	0x302,	/* SMB 3.02 */
92 	0x311,	/* SMB 3.11 */
93 };
94 static uint16_t smb2_nversions =
95     sizeof (smb2_versions) / sizeof (smb2_versions[0]);
96 
97 enum smb2_neg_ctx_type {
98 	SMB2_PREAUTH_INTEGRITY_CAPS		= 1,
99 	SMB2_ENCRYPTION_CAPS			= 2,
100 	SMB2_COMPRESSION_CAPS			= 3,	/* not imlemented */
101 	SMB2_NETNAME_NEGOTIATE_CONTEXT_ID	= 5	/* not imlemented */
102 };
103 
104 typedef struct smb2_negotiate_ctx {
105 	uint16_t	type;
106 	uint16_t	datalen;
107 } smb2_neg_ctx_t;
108 
109 #define	SMB31_PREAUTH_CTX_SALT_LEN	32
110 
111 /*
112  * SMB 3.1.1 originally specified a single hashing algorithm - SHA-512 - and
113  * two encryption ones - AES-128-CCM and AES-128-GCM.
114  * Windows Server 2022 and Windows 11 introduced two further encryption
115  * algorithms - AES-256-CCM and AES-256-GCM.
116  */
117 #define	MAX_HASHID_NUM	(1)
118 #define	MAX_CIPHER_NUM	(4)
119 
120 typedef struct smb2_preauth_integrity_caps {
121 	uint16_t	picap_hash_count;
122 	uint16_t	picap_salt_len;
123 	uint16_t	picap_hash_id;
124 	uint8_t		picap_salt[SMB31_PREAUTH_CTX_SALT_LEN];
125 } smb2_preauth_caps_t;
126 
127 typedef struct smb2_encryption_caps {
128 	uint16_t	encap_cipher_count;
129 	uint16_t	encap_cipher_ids[MAX_CIPHER_NUM];
130 } smb2_encrypt_caps_t;
131 
132 /*
133  * The contexts we support
134  */
135 typedef struct smb2_preauth_neg_ctx {
136 	smb2_neg_ctx_t		neg_ctx;
137 	smb2_preauth_caps_t	preauth_caps;
138 } smb2_preauth_neg_ctx_t;
139 
140 typedef struct smb2_encrypt_neg_ctx {
141 	smb2_neg_ctx_t		neg_ctx;
142 	smb2_encrypt_caps_t	encrypt_caps;
143 } smb2_encrypt_neg_ctx_t;
144 
145 typedef struct smb2_neg_ctxs {
146 	uint32_t		offset;
147 	uint16_t		count;
148 	smb2_preauth_neg_ctx_t	preauth_ctx;
149 	smb2_encrypt_neg_ctx_t	encrypt_ctx;
150 } smb2_neg_ctxs_t;
151 
152 #define	NEG_CTX_INFO_OFFSET	(SMB2_HDR_SIZE + 28)
153 #define	NEG_CTX_OFFSET_OFFSET	(SMB2_HDR_SIZE + 64)
154 #define	NEG_CTX_MAX_COUNT	(16)
155 #define	NEG_CTX_MAX_DATALEN	(256)
156 
157 #define	STATUS_SMB_NO_PREAUTH_INEGRITY_HASH_OVERLAP	(0xC05D0000)
158 
159 #define	STATUS_PREAUTH_HASH_OVERLAP \
160     STATUS_SMB_NO_PREAUTH_INEGRITY_HASH_OVERLAP
161 
162 #define	SMB3_CIPHER_ENABLED(c, f)	((c) <= SMB3_CIPHER_MAX && \
163     SMB3_CIPHER_BIT(c) & (f))
164 
165 typedef struct smb2_arg_negotiate {
166 	struct smb2_neg_ctxs	neg_in_ctxs;
167 	struct smb2_neg_ctxs	neg_out_ctxs;
168 	uint16_t		neg_dialect_cnt;
169 	uint16_t		neg_dialects[SMB2_NEGOTIATE_MAX_DIALECTS];
170 	uint16_t		neg_highest_dialect;
171 } smb2_arg_negotiate_t;
172 
173 
174 static boolean_t
175 smb2_supported_version(smb_session_t *s, uint16_t version)
176 {
177 	int i;
178 
179 	if (version > s->s_cfg.skc_max_protocol ||
180 	    version < s->s_cfg.skc_min_protocol)
181 		return (B_FALSE);
182 	for (i = 0; i < smb2_nversions; i++)
183 		if (version == smb2_versions[i])
184 			return (B_TRUE);
185 	return (B_FALSE);
186 }
187 
188 static uint16_t
189 smb2_find_best_dialect(smb_session_t *s, uint16_t cl_versions[],
190     uint16_t version_cnt)
191 {
192 	uint16_t best_version = 0;
193 	int i;
194 
195 	for (i = 0; i < version_cnt; i++)
196 		if (smb2_supported_version(s, cl_versions[i]) &&
197 		    best_version < cl_versions[i])
198 			best_version = cl_versions[i];
199 
200 	return (best_version);
201 }
202 
203 /*
204  * This function should be called only for dialect >= 0x311
205  * Negotiate context list should contain exactly one
206  * SMB2_PREAUTH_INTEGRITY_CAPS context.
207  * Otherwise STATUS_INVALID_PARAMETER.
208  * It should contain at least 1 hash algorith what server does support.
209  * Otehrwise STATUS_SMB_NO_PREAUTH_INEGRITY_HASH_OVERLAP.
210  */
211 static uint32_t
212 smb31_decode_neg_ctxs(smb_request_t *sr)
213 {
214 	smb_session_t *s = sr->session;
215 	smb2_arg_negotiate_t *nego = sr->arg.other;
216 	smb2_neg_ctxs_t *neg_ctxs = &nego->neg_in_ctxs;
217 	smb2_preauth_caps_t *picap = &neg_ctxs->preauth_ctx.preauth_caps;
218 	smb2_encrypt_caps_t *encap = &neg_ctxs->encrypt_ctx.encrypt_caps;
219 	boolean_t found_sha512 = B_FALSE;
220 	boolean_t found_cipher = B_FALSE;
221 	uint32_t ciphers = sr->sr_server->sv_cfg.skc_encrypt_ciphers;
222 	uint32_t status = 0;
223 	int32_t skip;
224 	int found_preauth_ctx = 0;
225 	int found_encrypt_ctx = 0;
226 	int cnt, i;
227 	int rc;
228 
229 	/*
230 	 * There should be exactly 1 SMB2_PREAUTH_INTEGRITY_CAPS negotiate ctx.
231 	 * SMB2_ENCRYPTION_CAPS is optional one.
232 	 * If there is no contexts or there are to many then stop parsing.
233 	 */
234 	cnt = neg_ctxs->count;
235 	if (cnt < 1 || cnt > NEG_CTX_MAX_COUNT) {
236 		status = NT_STATUS_INVALID_PARAMETER;
237 		goto errout;
238 	}
239 
240 	/*
241 	 * Cannot proceed parsing if the first context isn't aligned by 8.
242 	 */
243 	if (neg_ctxs->offset % 8 != 0) {
244 		status = NT_STATUS_INVALID_PARAMETER;
245 		goto errout;
246 	}
247 
248 	if ((skip = neg_ctxs->offset - sr->command.chain_offset) != 0 &&
249 	    smb_mbc_decodef(&sr->command, "#.", skip) != 0) {
250 		status = NT_STATUS_INVALID_PARAMETER;
251 		goto errout;
252 	}
253 
254 	/*
255 	 * Parse negotiate contexts. Ignore non-decoding errors to fill
256 	 * as much as possible data for dtrace probe.
257 	 */
258 	for (i = 0; i < cnt; i++) {
259 		smb2_neg_ctx_t neg_ctx;
260 		int32_t ctx_end_off;
261 		int32_t ctx_next_off;
262 
263 		if (i > 0) {
264 			if ((skip = ctx_next_off - ctx_end_off) != 0 &&
265 			    smb_mbc_decodef(&sr->command, "#.", skip) != 0) {
266 				status = NT_STATUS_INVALID_PARAMETER;
267 				goto errout;
268 			}
269 		}
270 
271 		rc = smb_mbc_decodef(
272 		    &sr->command, "ww4.",
273 		    &neg_ctx.type,	/* w */
274 		    &neg_ctx.datalen);	/* w */
275 		if (rc != 0) {
276 			status = NT_STATUS_INVALID_PARAMETER;
277 			goto errout;
278 		}
279 
280 		/*
281 		 * We got something crazy
282 		 */
283 		if (neg_ctx.datalen > NEG_CTX_MAX_DATALEN) {
284 			status = NT_STATUS_INVALID_PARAMETER;
285 			goto errout;
286 		}
287 
288 		ctx_end_off = sr->command.chain_offset + neg_ctx.datalen;
289 		ctx_next_off = P2ROUNDUP(ctx_end_off, 8);
290 
291 		switch (neg_ctx.type) {
292 		case SMB2_PREAUTH_INTEGRITY_CAPS:
293 			memcpy(&neg_ctxs->preauth_ctx.neg_ctx, &neg_ctx,
294 			    sizeof (neg_ctx));
295 
296 			if (found_preauth_ctx++ != 0) {
297 				status = NT_STATUS_INVALID_PARAMETER;
298 				continue;
299 			}
300 
301 			rc = smb_mbc_decodef(
302 			    &sr->command, "ww",
303 			    &picap->picap_hash_count,	/* w */
304 			    &picap->picap_salt_len);	/* w */
305 			if (rc != 0 || picap->picap_hash_count >
306 			    MAX_HASHID_NUM) {
307 				status = NT_STATUS_INVALID_PARAMETER;
308 				goto errout;
309 			}
310 
311 			/*
312 			 * Get hash id
313 			 */
314 			rc = smb_mbc_decodef(
315 			    &sr->command, "#w",
316 			    picap->picap_hash_count,
317 			    &picap->picap_hash_id);	/* w */
318 			if (rc != 0) {
319 				status = NT_STATUS_INVALID_PARAMETER;
320 				goto errout;
321 			}
322 
323 			/*
324 			 * Get salt
325 			 */
326 			rc = smb_mbc_decodef(
327 			    &sr->command, "#c",
328 			    sizeof (picap->picap_salt),
329 			    &picap->picap_salt[0]);	/* w */
330 			if (rc != 0) {
331 				status = NT_STATUS_INVALID_PARAMETER;
332 				goto errout;
333 			}
334 
335 			/*
336 			 * In SMB 0x311 there should be exactly 1 preauth
337 			 * negotiate context, and there should be exactly 1
338 			 * hash value in the list - SHA512.
339 			 */
340 			if (picap->picap_hash_count != 1) {
341 				status = NT_STATUS_INVALID_PARAMETER;
342 				continue;
343 			}
344 
345 			if (picap->picap_hash_id == SMB3_HASH_SHA512)
346 				found_sha512 = B_TRUE;
347 			break;
348 		case SMB2_ENCRYPTION_CAPS:
349 			memcpy(&neg_ctxs->preauth_ctx.neg_ctx, &neg_ctx,
350 			    sizeof (neg_ctx));
351 
352 			if (found_encrypt_ctx++ != 0) {
353 				status = NT_STATUS_INVALID_PARAMETER;
354 				continue;
355 			}
356 
357 			rc = smb_mbc_decodef(
358 			    &sr->command, "w",
359 			    &encap->encap_cipher_count);	/* w */
360 			if (rc != 0 || encap->encap_cipher_count >
361 			    MAX_CIPHER_NUM) {
362 				status = NT_STATUS_INVALID_PARAMETER;
363 				goto errout;
364 			}
365 
366 			/*
367 			 * Get cipher list
368 			 */
369 			rc = smb_mbc_decodef(
370 			    &sr->command, "#w",
371 			    encap->encap_cipher_count,
372 			    &encap->encap_cipher_ids[0]);	/* w */
373 			if (rc != 0) {
374 				status = NT_STATUS_INVALID_PARAMETER;
375 				goto errout;
376 			}
377 
378 			/*
379 			 * Select the first enabled cipher.
380 			 * Client should list more prioritized ciphers first.
381 			 */
382 			for (int k = 0; k < encap->encap_cipher_count; k++) {
383 				uint16_t c = encap->encap_cipher_ids[k];
384 
385 				if (SMB3_CIPHER_ENABLED(c, ciphers)) {
386 					s->smb31_enc_cipherid = c;
387 					found_cipher = B_TRUE;
388 					break;
389 				}
390 			}
391 			break;
392 		default:
393 			;
394 		}
395 	}
396 
397 	if (status)
398 		goto errout;
399 
400 	/* Not found mandatory SMB2_PREAUTH_INTEGRITY_CAPS ctx */
401 	if (found_preauth_ctx != 1 || found_encrypt_ctx > 1) {
402 		status = NT_STATUS_INVALID_PARAMETER;
403 		goto errout;
404 	}
405 
406 	if (!found_sha512) {
407 		status = STATUS_PREAUTH_HASH_OVERLAP;
408 		goto errout;
409 	}
410 
411 	s->smb31_preauth_hashid = SMB3_HASH_SHA512;
412 
413 	if (!found_cipher)
414 		s->smb31_enc_cipherid = 0;
415 
416 	/* Initialize out = in */
417 	nego->neg_out_ctxs = nego->neg_in_ctxs;
418 
419 errout:
420 	return (status);
421 }
422 
423 static int
424 smb31_encode_neg_ctxs(smb_request_t *sr)
425 {
426 	smb_session_t *s = sr->session;
427 	smb2_arg_negotiate_t *nego = sr->arg.other;
428 	smb2_neg_ctxs_t *neg_ctxs = &nego->neg_out_ctxs;
429 	smb2_preauth_caps_t *picap = &neg_ctxs->preauth_ctx.preauth_caps;
430 	smb2_encrypt_caps_t *encap = &neg_ctxs->encrypt_ctx.encrypt_caps;
431 	uint16_t salt_len = sizeof (picap->picap_salt);
432 	uint32_t preauth_ctx_len = 6 + salt_len;
433 	uint32_t enc_ctx_len = 4;
434 	uint32_t neg_ctx_off = NEG_CTX_OFFSET_OFFSET +
435 	    P2ROUNDUP(sr->sr_cfg->skc_negtok_len, 8);
436 	uint32_t rc;
437 
438 	if ((rc = smb_mbc_put_align(&sr->reply, 8)) != 0)
439 		return (rc);
440 
441 	ASSERT3S(neg_ctx_off, ==, sr->reply.chain_offset);
442 
443 	picap->picap_hash_id = s->smb31_preauth_hashid;
444 	picap->picap_salt_len = salt_len;
445 
446 	(void) random_get_pseudo_bytes(picap->picap_salt, salt_len);
447 
448 	rc = smb_mbc_encodef(
449 	    &sr->reply, "ww4.",
450 	    SMB2_PREAUTH_INTEGRITY_CAPS,
451 	    preauth_ctx_len
452 	    /* 4. */); /* reserved */
453 	if (rc != 0)
454 		return (rc);
455 
456 	rc = smb_mbc_encodef(
457 	    &sr->reply, "www#c",
458 	    1,				/* hash algo count */
459 	    salt_len,			/* salt length */
460 	    s->smb31_preauth_hashid,	/* hash id */
461 	    salt_len,			/* salt length */
462 	    picap->picap_salt);
463 	if (rc != 0)
464 		return (rc);
465 
466 	/*
467 	 * If we did not get SMB2_ENCRYPTION_CAPS, don't send one.
468 	 */
469 	if (encap->encap_cipher_count == 0)
470 		return (0);
471 
472 	/*
473 	 * Encode SMB2_ENCRYPTION_CAPS response.
474 	 */
475 	if ((rc = smb_mbc_put_align(&sr->reply, 8)) != 0)
476 		return (rc);
477 
478 	rc = smb_mbc_encodef(
479 	    &sr->reply, "ww4.",
480 	    SMB2_ENCRYPTION_CAPS,
481 	    enc_ctx_len
482 	    /* 4. */); /* reserved */
483 
484 	rc = smb_mbc_encodef(
485 	    &sr->reply, "ww",
486 	    1,				/* cipher count */
487 	    s->smb31_enc_cipherid);	/* encrypt. cipher id */
488 
489 	return (rc);
490 }
491 
492 /*
493  * Helper for the (SMB1) smb_com_negotiate().  This is the
494  * very unusual protocol interaction where an SMB1 negotiate
495  * gets an SMB2 negotiate response.  This is the normal way
496  * clients first find out if the server supports SMB2.
497  *
498  * Note: This sends an SMB2 reply _itself_ and then returns
499  * SDRC_NO_REPLY so the caller will not send an SMB1 reply.
500  * Also, this is called directly from the reader thread, so
501  * we know this is the only thread using this session.
502  * Otherwise, this is similar to smb2_newrq_negotiate().
503  *
504  * The caller frees this request.
505  */
506 smb_sdrc_t
507 smb1_negotiate_smb2(smb_request_t *sr)
508 {
509 	smb_session_t *s = sr->session;
510 	smb_arg_negotiate_t *negprot = sr->sr_negprot;
511 	uint16_t smb2_version;
512 
513 	/*
514 	 * Note: In the SMB1 negotiate command handler, we
515 	 * agreed with one of the SMB2 dialects.  If that
516 	 * dialect was "SMB 2.002", we'll respond here with
517 	 * version 0x202 and negotiation is done.  If that
518 	 * dialect was "SMB 2.???", we'll respond here with
519 	 * the "wildcard" version 0x2FF, and the client will
520 	 * come back with an SMB2 negotiate.
521 	 */
522 	switch (negprot->ni_dialect) {
523 	case DIALECT_SMB2002:	/* SMB 2.002 (a.k.a. SMB2.0) */
524 		smb2_version = SMB_VERS_2_002;
525 		s->dialect = smb2_version;
526 		s->s_state = SMB_SESSION_STATE_NEGOTIATED;
527 		/* Allow normal SMB2 requests now. */
528 		s->newrq_func = smb2sr_newrq;
529 		break;
530 	case DIALECT_SMB2XXX:	/* SMB 2.??? (wildcard vers) */
531 		/*
532 		 * Expecting an SMB2 negotiate next, so keep the
533 		 * initial s->newrq_func.
534 		 */
535 		smb2_version = 0x2FF;
536 		break;
537 	default:
538 		return (SDRC_DROP_VC);
539 	}
540 
541 	/*
542 	 * We did not decode an SMB2 header, so make sure
543 	 * the SMB2 header fields are initialized.
544 	 * (Most are zero from smb_request_alloc.)
545 	 * Also, the SMB1 common dispatch code reserved space
546 	 * for an SMB1 header, which we need to undo here.
547 	 */
548 	sr->smb2_reply_hdr = sr->reply.chain_offset = 0;
549 	sr->smb2_cmd_code = SMB2_NEGOTIATE;
550 	sr->smb2_hdr_flags = SMB2_FLAGS_SERVER_TO_REDIR;
551 
552 	/*
553 	 * Also setup SMB2 negotiate args (empty here).
554 	 * SMB1 args free'd by smb_srm_fini(sr)
555 	 */
556 	sr->arg.other = smb_srm_zalloc(sr, sizeof (smb2_arg_negotiate_t));
557 
558 	(void) smb2_encode_header(sr, B_FALSE);
559 	if (smb2_negotiate_common(sr, smb2_version) != 0)
560 		sr->smb2_status = NT_STATUS_INTERNAL_ERROR;
561 	if (sr->smb2_status != 0)
562 		smb2sr_put_error(sr, sr->smb2_status);
563 	(void) smb2_encode_header(sr, B_TRUE);
564 
565 	smb2_send_reply(sr);
566 
567 	/*
568 	 * We sent the reply, so tell the SMB1 dispatch
569 	 * it should NOT (also) send a reply.
570 	 */
571 	return (SDRC_NO_REPLY);
572 }
573 
574 /*
575  * SMB2 Negotiate gets special handling.  This is called directly by
576  * the reader thread (see smbsr_newrq_initial) with what _should_ be
577  * an SMB2 Negotiate.  Only the "\feSMB" header has been checked
578  * when this is called, so this needs to check the SMB command,
579  * if it's Negotiate execute it, then send the reply, etc.
580  *
581  * Since this is called directly from the reader thread, we
582  * know this is the only thread currently using this session.
583  * This has to duplicate some of what smb2sr_work does as a
584  * result of bypassing the normal dispatch mechanism.
585  *
586  * The caller always frees this request.
587  *
588  * Return value is 0 for success, and anything else will
589  * terminate the reader thread (drop the connection).
590  */
591 int
592 smb2_newrq_negotiate(smb_request_t *sr)
593 {
594 	smb_session_t *s = sr->session;
595 	smb2_arg_negotiate_t *nego;
596 	int rc;
597 	uint32_t nctx_status = 0;
598 	uint32_t status = 0;
599 	uint32_t neg_ctx_off;
600 	uint16_t neg_ctx_cnt;
601 	uint16_t struct_size;
602 	uint16_t dialect_cnt;
603 	uint16_t best_version;
604 
605 	nego = smb_srm_zalloc(sr, sizeof (smb2_arg_negotiate_t));
606 	sr->arg.other = nego;	// for dtrace
607 
608 	sr->smb2_cmd_hdr = sr->command.chain_offset;
609 	rc = smb2_decode_header(sr);
610 	if (rc != 0)
611 		return (rc);
612 
613 	if (sr->smb2_hdr_flags & SMB2_FLAGS_SERVER_TO_REDIR)
614 		return (-1);
615 
616 	if ((sr->smb2_cmd_code != SMB2_NEGOTIATE) ||
617 	    (sr->smb2_next_command != 0))
618 		return (-1);
619 
620 	/*
621 	 * Decode SMB2 Negotiate (fixed-size part)
622 	 */
623 	rc = smb_mbc_decodef(
624 	    &sr->command, "www..l16clw..",
625 	    &struct_size,	/* w */
626 	    &dialect_cnt,	/* w */
627 	    &s->cli_secmode,	/* w */
628 	    /* reserved		(..) */
629 	    &s->capabilities,	/* l */
630 	    s->clnt_uuid,	/* 16c */
631 	    &neg_ctx_off,	/* l */
632 	    &neg_ctx_cnt);	/* w */
633 	    /* reserverd	(..) */
634 	if (rc != 0)
635 		return (rc);
636 	if (struct_size != 36)
637 		return (-1);
638 
639 	/*
640 	 * Decode SMB2 Negotiate (variable part)
641 	 *
642 	 * Be somewhat tolerant while decoding the variable part
643 	 * so we can return errors instead of dropping the client.
644 	 * Will limit decoding to the size of cli_dialects here,
645 	 * and do error checks on the decoded dialect_cnt after the
646 	 * dtrace start probe.
647 	 */
648 	if (dialect_cnt > SMB2_NEGOTIATE_MAX_DIALECTS)
649 		nego->neg_dialect_cnt = SMB2_NEGOTIATE_MAX_DIALECTS;
650 	else
651 		nego->neg_dialect_cnt = dialect_cnt;
652 	if (nego->neg_dialect_cnt > 0) {
653 		rc = smb_mbc_decodef(&sr->command, "#w",
654 		    nego->neg_dialect_cnt,
655 		    nego->neg_dialects);
656 		if (rc != 0)
657 			return (rc);	// short msg
658 	}
659 
660 	best_version = smb2_find_best_dialect(s, nego->neg_dialects,
661 	    nego->neg_dialect_cnt);
662 
663 	if (best_version >= SMB_VERS_3_11) {
664 		nego->neg_in_ctxs.offset = neg_ctx_off;
665 		nego->neg_in_ctxs.count  = neg_ctx_cnt;
666 		nctx_status = smb31_decode_neg_ctxs(sr);
667 		/* check nctx_status below */
668 	}
669 
670 	DTRACE_SMB2_START(op__Negotiate, smb_request_t *, sr);
671 
672 	sr->smb2_credit_response = 1;
673 	sr->smb2_hdr_flags |= SMB2_FLAGS_SERVER_TO_REDIR;
674 	(void) smb2_encode_header(sr, B_FALSE);
675 
676 	/*
677 	 * NOW start validating things (NOT before here)
678 	 */
679 
680 	/*
681 	 * [MS-SMB2] 3.3.5.2.4 Verifying the Signature
682 	 * "If the SMB2 header of the SMB2 NEGOTIATE request has the
683 	 * SMB2_FLAGS_SIGNED bit set in the Flags field, the server
684 	 * MUST fail the request with STATUS_INVALID_PARAMETER."
685 	 */
686 	if ((sr->smb2_hdr_flags & SMB2_FLAGS_SIGNED) != 0) {
687 		sr->smb2_hdr_flags &= ~SMB2_FLAGS_SIGNED;
688 		status = NT_STATUS_INVALID_PARAMETER;
689 		goto errout;
690 	}
691 
692 	/*
693 	 * [MS-SMB2] 3.3.5.4 Receiving an SMB2 NEGOTIATE Request
694 	 * "If the DialectCount of the SMB2 NEGOTIATE Request is 0, the
695 	 * server MUST fail the request with STATUS_INVALID_PARAMETER."
696 	 * Checking the decoded value here, not the constrained one.
697 	 */
698 	if (dialect_cnt == 0 ||
699 	    dialect_cnt > SMB2_NEGOTIATE_MAX_DIALECTS) {
700 		status = NT_STATUS_INVALID_PARAMETER;
701 		goto errout;
702 	}
703 
704 	/*
705 	 * We decoded the offered dialects above, and
706 	 * determined which was the highest we support.
707 	 *
708 	 * [MS-SMB2] 3.3.5.4 Receiving an SMB2 NEGOTIATE Request
709 	 * "If a common dialect is not found, the server MUST fail
710 	 * the request with STATUS_NOT_SUPPORTED."
711 	 */
712 	if (best_version == 0) {
713 		status = NT_STATUS_NOT_SUPPORTED;
714 		goto errout;
715 	}
716 
717 	/*
718 	 * Check for problems with the negotiate contexts.
719 	 */
720 	if (nctx_status != 0) {
721 		status = nctx_status;
722 		goto errout;
723 	}
724 
725 	/* Allow normal SMB2 requests now. */
726 	s->dialect = best_version;
727 	s->s_state = SMB_SESSION_STATE_NEGOTIATED;
728 	s->newrq_func = smb2sr_newrq;
729 
730 	if (smb2_negotiate_common(sr, best_version) != 0)
731 		status = NT_STATUS_INTERNAL_ERROR;
732 
733 	if (s->dialect >= SMB_VERS_3_11 && status == 0) {
734 		if (smb31_encode_neg_ctxs(sr) != 0)
735 			status = NT_STATUS_INTERNAL_ERROR;
736 	}
737 
738 errout:
739 	sr->smb2_status = status;
740 	DTRACE_SMB2_DONE(op__Negotiate, smb_request_t *, sr);
741 
742 	if (sr->smb2_status != 0)
743 		smb2sr_put_error(sr, sr->smb2_status);
744 	(void) smb2_encode_header(sr, B_TRUE);
745 
746 	if (s->dialect >= SMB_VERS_3_11 && sr->smb2_status == 0) {
747 		ASSERT3U(s->smb31_preauth_hashid, !=, 0);
748 		if (smb31_preauth_sha512_calc(sr, &sr->reply,
749 		    s->smb31_preauth_hashval,
750 		    s->smb31_preauth_hashval) != 0)
751 			cmn_err(CE_WARN, "(1) Preauth hash calculation "
752 			    "failed");
753 	}
754 
755 	smb2_send_reply(sr);
756 
757 	return (rc);
758 }
759 
760 /*
761  * Common parts of SMB2 Negotiate, used for both the
762  * SMB1-to-SMB2 style, and straight SMB2 style.
763  * Do negotiation decisions and encode the reply.
764  * The caller does the network send.
765  *
766  * Return value is 0 for success, else error.
767  */
768 static int
769 smb2_negotiate_common(smb_request_t *sr, uint16_t version)
770 {
771 	timestruc_t boot_tv, now_tv;
772 	smb_session_t *s = sr->session;
773 	smb2_arg_negotiate_t *nego = sr->arg.other;
774 	int rc;
775 	uint32_t max_rwsize;
776 	uint16_t secmode;
777 	uint16_t neg_ctx_cnt = 0;
778 	uint32_t neg_ctx_off = 0;
779 
780 	/*
781 	 * Negotiation itself.  First the Security Mode.
782 	 */
783 	secmode = SMB2_NEGOTIATE_SIGNING_ENABLED;
784 	if (sr->sr_cfg->skc_signing_required)
785 		secmode |= SMB2_NEGOTIATE_SIGNING_REQUIRED;
786 	s->srv_secmode = secmode;
787 
788 	s->cmd_max_bytes = smb2_tcp_bufsize;
789 	s->reply_max_bytes = smb2_tcp_bufsize;
790 
791 	/*
792 	 * "The number of credits held by the client MUST be considered
793 	 * as 1 when the connection is established." [MS-SMB2]
794 	 * We leave credits at 1 until the first successful
795 	 * session setup is completed.
796 	 */
797 	s->s_cur_credits = s->s_max_credits = 1;
798 	sr->smb2_credit_response = 1;
799 
800 	boot_tv.tv_sec = smb_get_boottime();
801 	boot_tv.tv_nsec = 0;
802 	now_tv.tv_sec = gethrestime_sec();
803 	now_tv.tv_nsec = 0;
804 
805 	/*
806 	 * If the version is 0x2FF, we haven't completed negotiate.
807 	 * Don't initialize until we have our final request.
808 	 */
809 	if (version != 0x2FF)
810 		smb2_sign_init_mech(s);
811 	if (version >= 0x311)
812 		smb31_preauth_init_mech(s);
813 
814 	/*
815 	 * [MS-SMB2] 3.3.5.4 Receiving an SMB2 NEGOTIATE Request
816 	 *
817 	 * The SMB2.x capabilities are returned without regard for
818 	 * what capabilities the client provided in the request.
819 	 * The SMB3.x capabilities returned are the traditional
820 	 * logical AND of server and client capabilities, except
821 	 * for the SMB2.x capabilities which are what the server
822 	 * supports (regardless of the client capabilities).
823 	 *
824 	 * One additional check: If KCF is missing something we
825 	 * require for encryption, turn off that capability.
826 	 */
827 	if (s->dialect < SMB_VERS_2_1) {
828 		/* SMB 2.002 */
829 		s->srv_cap = smb2srv_capabilities & SMB2_CAP_DFS;
830 	} else if (s->dialect < SMB_VERS_3_0) {
831 		/* SMB 2.x */
832 		s->srv_cap = smb2srv_capabilities & SMB_2X_CAPS;
833 	} else {
834 		/* SMB 3.0 or later */
835 		s->srv_cap = smb2srv_capabilities &
836 		    (SMB_2X_CAPS | s->capabilities);
837 
838 		if (s->dialect < SMB_VERS_3_11)
839 			s->smb31_enc_cipherid = SMB3_CIPHER_AES128_CCM;
840 		/* else from negotiate context */
841 
842 		if ((s->srv_cap & SMB2_CAP_ENCRYPTION) != 0 &&
843 		    smb3_encrypt_init_mech(s) != 0) {
844 			s->srv_cap &= ~SMB2_CAP_ENCRYPTION;
845 		}
846 
847 		if (s->dialect >= SMB_VERS_3_11) {
848 			smb2_encrypt_caps_t *encap =
849 			    &nego->neg_in_ctxs.encrypt_ctx.encrypt_caps;
850 
851 			neg_ctx_cnt = 1; // always have preauth
852 
853 			if (encap->encap_cipher_count != 0)
854 				neg_ctx_cnt++;
855 
856 			neg_ctx_off = NEG_CTX_OFFSET_OFFSET +
857 			    P2ROUNDUP(sr->sr_cfg->skc_negtok_len, 8);
858 
859 			ASSERT3U(s->smb31_preauth_hashid, !=, 0);
860 
861 			if (smb31_preauth_sha512_calc(sr, &sr->command,
862 			    s->smb31_preauth_hashval,
863 			    s->smb31_preauth_hashval) != 0)
864 				cmn_err(CE_WARN, "(0) Preauth hash calculation "
865 				    "failed");
866 		}
867 	}
868 
869 	/*
870 	 * See notes above smb2_max_rwsize, smb2_old_rwsize
871 	 */
872 	if (s->capabilities & SMB2_CAP_LARGE_MTU)
873 		max_rwsize = smb2_max_rwsize;
874 	else
875 		max_rwsize = smb2_old_rwsize;
876 
877 	rc = smb_mbc_encodef(
878 	    &sr->reply,
879 	    "wwww#cllllTTwwl#c",
880 	    65,	/* StructSize */	/* w */
881 	    s->srv_secmode,		/* w */
882 	    version,			/* w */
883 	    neg_ctx_cnt,		/* w */
884 	    UUID_LEN,			/* # */
885 	    &s->s_cfg.skc_machine_uuid, /* c */
886 	    s->srv_cap,			/* l */
887 	    smb2_max_trans,		/* l */
888 	    max_rwsize,			/* l */
889 	    max_rwsize,			/* l */
890 	    &now_tv,			/* T */
891 	    &boot_tv,			/* T */
892 	    128, /* SecBufOff */	/* w */
893 	    sr->sr_cfg->skc_negtok_len,	/* w */
894 	    neg_ctx_off,		/* l */
895 	    sr->sr_cfg->skc_negtok_len,	/* # */
896 	    sr->sr_cfg->skc_negtok);	/* c */
897 
898 	/* Note: smb31_encode_neg_ctxs() follows in caller */
899 
900 	/* smb2_send_reply(sr); in caller */
901 
902 	(void) ksocket_setsockopt(s->sock, SOL_SOCKET,
903 	    SO_SNDBUF, (const void *)&smb2_tcp_bufsize,
904 	    sizeof (smb2_tcp_bufsize), CRED());
905 	(void) ksocket_setsockopt(s->sock, SOL_SOCKET,
906 	    SO_RCVBUF, (const void *)&smb2_tcp_bufsize,
907 	    sizeof (smb2_tcp_bufsize), CRED());
908 
909 	return (rc);
910 }
911 
912 /*
913  * SMB2 Dispatch table handler, which will run if we see an
914  * SMB2_NEGOTIATE after the initial negotiation is done.
915  * That would be a protocol error.
916  */
917 smb_sdrc_t
918 smb2_negotiate(smb_request_t *sr)
919 {
920 	sr->smb2_status = NT_STATUS_INVALID_PARAMETER;
921 	return (SDRC_ERROR);
922 }
923 
924 /*
925  * VALIDATE_NEGOTIATE_INFO [MS-SMB2] 2.2.32.6
926  */
927 uint32_t
928 smb2_nego_validate(smb_request_t *sr, smb_fsctl_t *fsctl)
929 {
930 	smb_session_t *s = sr->session;
931 	int rc;
932 
933 	/*
934 	 * The spec. says to parse the VALIDATE_NEGOTIATE_INFO here
935 	 * and verify that the original negotiate was not modified.
936 	 *
937 	 * One interesting requirement here is that we MUST reply
938 	 * with exactly the same information as we returned in our
939 	 * original reply to the SMB2 negotiate on this session.
940 	 * If we don't the client closes the connection.
941 	 */
942 
943 	uint32_t capabilities;
944 	uint16_t secmode;
945 	uint16_t num_dialects;
946 	uint16_t dialects[SMB2_NEGOTIATE_MAX_DIALECTS];
947 	uint8_t clnt_guid[16];
948 
949 	if (s->dialect >= SMB_VERS_3_11)
950 		goto drop;
951 
952 	/*
953 	 * [MS-SMB2] 3.3.5.2.4 Verifying the Signature
954 	 *
955 	 * If the dialect is SMB3 and the message was successfully
956 	 * decrypted we MUST skip processing of the signature.
957 	 */
958 	if (!sr->encrypted && (sr->smb2_hdr_flags & SMB2_FLAGS_SIGNED) == 0)
959 		goto drop;
960 
961 	if (fsctl->InputCount < 24)
962 		goto drop;
963 
964 	(void) smb_mbc_decodef(fsctl->in_mbc, "l16cww",
965 	    &capabilities, /* l */
966 	    &clnt_guid, /* 16c */
967 	    &secmode, /* w */
968 	    &num_dialects); /* w */
969 
970 	if (num_dialects == 0 || num_dialects > SMB2_NEGOTIATE_MAX_DIALECTS)
971 		goto drop;
972 	if (secmode != s->cli_secmode)
973 		goto drop;
974 	if (capabilities != s->capabilities)
975 		goto drop;
976 	if (memcmp(clnt_guid, s->clnt_uuid, sizeof (clnt_guid)) != 0)
977 		goto drop;
978 
979 	rc = smb_mbc_decodef(fsctl->in_mbc, "#w", num_dialects, dialects);
980 	if (rc != 0)
981 		goto drop;
982 
983 	/*
984 	 * MS-SMB2 says we should compare the dialects array with the
985 	 * one sent previously, but that appears to be unnecessary
986 	 * as long as we end up with the same dialect.
987 	 */
988 	if (smb2_find_best_dialect(s, dialects, num_dialects) != s->dialect)
989 		goto drop;
990 
991 	rc = smb_mbc_encodef(
992 	    fsctl->out_mbc, "l#cww",
993 	    s->srv_cap,			/* l */
994 	    UUID_LEN,			/* # */
995 	    &s->s_cfg.skc_machine_uuid, /* c */
996 	    s->srv_secmode,		/* w */
997 	    s->dialect);		/* w */
998 	if (rc == 0)
999 		return (rc);
1000 
1001 drop:
1002 	smb_session_disconnect(s);
1003 	return (NT_STATUS_ACCESS_DENIED);
1004 }
1005