xref: /illumos-gate/usr/src/uts/common/fs/smbsrv/smb_session.c (revision 422fa9b925a472d76f14397640602fa82fdece3f)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
23  * Copyright 2011-2021 Tintri by DDN, Inc. All rights reserved.
24  * Copyright 2021-2023 RackTop Systems, Inc.
25  */
26 
27 #include <sys/atomic.h>
28 #include <sys/synch.h>
29 #include <sys/types.h>
30 #include <sys/sdt.h>
31 #include <sys/random.h>
32 #include <smbsrv/netbios.h>
33 #include <smbsrv/smb2_kproto.h>
34 #include <smbsrv/string.h>
35 #include <netinet/tcp.h>
36 
37 #define	SMB_NEW_KID()	atomic_inc_64_nv(&smb_kids)
38 
39 static volatile uint64_t smb_kids;
40 
41 /*
42  * We track the keepalive in minutes, but this constant
43  * specifies it in seconds, so convert to minutes.
44  */
45 uint32_t smb_keep_alive = SMB_PI_KEEP_ALIVE_MIN / 60;
46 
47 /*
48  * This is the maximum time we'll allow a "session" to exist with no
49  * authenticated smb_user_t objects on it.  This allows a client to
50  * logoff their "one and only" user session and then logon as some
51  * different user.  (There are some tests that do that.)  The same
52  * timeout mechanism also reduces the impact of clients that might
53  * open TCP connections but never authenticate.
54  */
55 int smb_session_auth_tmo = 30; /* sec. */
56 
57 /*
58  * There are many smbtorture test cases that send
59  * racing requests, and where the tests fail if we
60  * don't execute them in exactly the order sent.
61  * These are test bugs.  The protocol makes no
62  * guarantees about execution order of requests
63  * that are concurrently active.
64  *
65  * Nonetheless, smbtorture has many useful tests,
66  * so we have this work-around we can enable to
67  * basically force sequential execution.  When
68  * enabled, insert a delay after each request is
69  * issued a taskq job.  Enable this with mdb by
70  * setting smb_reader_delay to 10.  Don't make it
71  * more than 500 or so or the server will appear
72  * to be so slow that tests may time out.
73  */
74 int smb_reader_delay = 0;  /* mSec. */
75 
76 static int  smbsr_newrq_initial(smb_request_t *);
77 
78 static void smb_session_cancel(smb_session_t *);
79 static int smb_session_reader(smb_session_t *);
80 static int smb_session_xprt_puthdr(smb_session_t *,
81     uint8_t msg_type, uint32_t msg_len,
82     uint8_t *dst, size_t dstlen);
83 static void smb_session_disconnect_trees(smb_session_t	*);
84 static void smb_session_genkey(smb_session_t *);
85 
86 /*
87  * This (legacy) code is in support of an "idle timeout" feature,
88  * which is apparently incomplete.  To complete it, we should:
89  * when the keep_alive timer expires, check whether the client
90  * has any open files, and if not then kill their session.
91  * Right now the timers are there, but nothing happens when
92  * a timer expires.
93  *
94  * Todo: complete logic to kill idle sessions.
95  *
96  * Only called when sv_cfg.skc_keepalive != 0
97  */
98 void
smb_session_timers(smb_server_t * sv)99 smb_session_timers(smb_server_t *sv)
100 {
101 	smb_session_t	*session;
102 	smb_llist_t	*ll;
103 
104 	ll = &sv->sv_session_list;
105 	smb_llist_enter(ll, RW_READER);
106 	session = smb_llist_head(ll);
107 	while (session != NULL) {
108 		/*
109 		 * Walk through the table and decrement each keep_alive
110 		 * timer that has not timed out yet. (keepalive > 0)
111 		 */
112 		SMB_SESSION_VALID(session);
113 		if (session->keep_alive &&
114 		    (session->keep_alive != (uint32_t)-1))
115 			session->keep_alive--;
116 
117 		session = smb_llist_next(ll, session);
118 	}
119 	smb_llist_exit(ll);
120 }
121 
122 /*
123  * Send a session message - supports SMB-over-NBT and SMB-over-TCP.
124  * If an mbuf chain is provided (optional), it will be freed and
125  * set to NULL -- unconditionally!  (error or not)
126  *
127  * Prepends the 4-byte NBT header before sending.
128  */
129 int
smb_session_send(smb_session_t * session,uint8_t nbt_type,mbuf_chain_t * mbc)130 smb_session_send(smb_session_t *session, uint8_t nbt_type, mbuf_chain_t *mbc)
131 {
132 	mbuf_t		*m = NULL;
133 	uint32_t	nbt_len;
134 	int		rc;
135 
136 	switch (session->s_state) {
137 	case SMB_SESSION_STATE_DISCONNECTED:
138 	case SMB_SESSION_STATE_TERMINATED:
139 		rc = ENOTCONN;
140 		goto out;
141 	default:
142 		break;
143 	}
144 
145 	/*
146 	 * Prepend the NBT header (NetBIOS or SMB/TCP)
147 	 * and fill it in.
148 	 *
149 	 * After this, we "own" the mbuf chain (m) and must
150 	 * either consume it (via send) or free it.
151 	 */
152 	if (mbc != NULL && (m = mbc->chain) != NULL) {
153 		nbt_len = MBC_LENGTH(mbc);
154 		m = m_prepend(mbc->chain, NETBIOS_HDR_SZ, M_WAIT);
155 		mbc->chain = NULL;
156 	} else {
157 		nbt_len = 0;
158 		MGET(m, M_WAIT, MT_DATA);
159 		m->m_len = NETBIOS_HDR_SZ;
160 	}
161 	ASSERT(m->m_len >= NETBIOS_HDR_SZ);
162 	rc = smb_session_xprt_puthdr(session, nbt_type, nbt_len,
163 	    mtod(m, uint8_t *), NETBIOS_HDR_SZ);
164 	if (rc != 0)
165 		goto out;
166 
167 	/* Send "consumes" m unconditionally */
168 	rc = smb_net_send_mbufs(session, m);
169 	if (rc == 0) {
170 		smb_server_add_txb(session->s_server,
171 		    nbt_len + NETBIOS_HDR_SZ);
172 	}
173 	m = NULL; // consumed
174 
175 out:
176 	if (m != NULL)
177 		m_freem(m);
178 	if (mbc != NULL && mbc->chain != NULL) {
179 		m_freem(mbc->chain);
180 		mbc->chain = NULL;
181 	}
182 
183 	return (rc);
184 }
185 
186 /*
187  * Read, process and respond to a NetBIOS session request.
188  *
189  * A NetBIOS session must be established for SMB-over-NetBIOS.  Validate
190  * the calling and called name format and save the client NetBIOS name,
191  * which is used when a NetBIOS session is established to check for and
192  * cleanup leftover state from a previous session.
193  *
194  * Session requests are not valid for SMB-over-TCP, which is unfortunate
195  * because without the client name leftover state cannot be cleaned up
196  * if the client is behind a NAT server.
197  */
198 static int
smb_netbios_session_request(struct smb_session * session)199 smb_netbios_session_request(struct smb_session *session)
200 {
201 	int			rc;
202 	char			*calling_name;
203 	char			*called_name;
204 	char			client_name[NETBIOS_NAME_SZ];
205 	struct mbuf_chain	mbc;
206 	char			*names = NULL;
207 	smb_wchar_t		*wbuf = NULL;
208 	smb_xprt_t		hdr;
209 	char *p;
210 	int rc1, rc2;
211 
212 	session->keep_alive = smb_keep_alive;
213 
214 	if ((rc = smb_session_xprt_gethdr(session, &hdr)) != 0)
215 		return (rc);
216 
217 	DTRACE_PROBE2(receive__session__req__xprthdr, struct session *, session,
218 	    smb_xprt_t *, &hdr);
219 
220 	if ((hdr.xh_type != SESSION_REQUEST) ||
221 	    (hdr.xh_length != NETBIOS_SESSION_REQUEST_DATA_LENGTH)) {
222 		DTRACE_PROBE1(receive__session__req__failed,
223 		    struct session *, session);
224 		return (EINVAL);
225 	}
226 
227 	names = kmem_alloc(hdr.xh_length, KM_SLEEP);
228 
229 	if ((rc = smb_sorecv(session->sock, names, hdr.xh_length)) != 0) {
230 		kmem_free(names, hdr.xh_length);
231 		DTRACE_PROBE1(receive__session__req__failed,
232 		    struct session *, session);
233 		return (rc);
234 	}
235 
236 	DTRACE_PROBE3(receive__session__req__data, struct session *, session,
237 	    char *, names, uint32_t, hdr.xh_length);
238 
239 	called_name = &names[0];
240 	calling_name = &names[NETBIOS_ENCODED_NAME_SZ + 2];
241 
242 	rc1 = netbios_name_isvalid(called_name, 0);
243 	rc2 = netbios_name_isvalid(calling_name, client_name);
244 
245 	if (rc1 == 0 || rc2 == 0) {
246 
247 		DTRACE_PROBE3(receive__invalid__session__req,
248 		    struct session *, session, char *, names,
249 		    uint32_t, hdr.xh_length);
250 
251 		kmem_free(names, hdr.xh_length);
252 		MBC_INIT(&mbc, MAX_DATAGRAM_LENGTH);
253 		(void) smb_mbc_encodef(&mbc, "b",
254 		    DATAGRAM_INVALID_SOURCE_NAME_FORMAT);
255 		(void) smb_session_send(session, NEGATIVE_SESSION_RESPONSE,
256 		    &mbc);
257 		return (EINVAL);
258 	}
259 
260 	DTRACE_PROBE3(receive__session__req__calling__decoded,
261 	    struct session *, session,
262 	    char *, calling_name, char *, client_name);
263 
264 	/*
265 	 * The client NetBIOS name is in oem codepage format.
266 	 * We need to convert it to unicode and store it in
267 	 * multi-byte format.  We also need to strip off any
268 	 * spaces added as part of the NetBIOS name encoding.
269 	 */
270 	wbuf = kmem_alloc((SMB_PI_MAX_HOST * sizeof (smb_wchar_t)), KM_SLEEP);
271 	(void) oemtoucs(wbuf, client_name, SMB_PI_MAX_HOST, OEM_CPG_850);
272 	(void) smb_wcstombs(session->workstation, wbuf, SMB_PI_MAX_HOST);
273 	kmem_free(wbuf, (SMB_PI_MAX_HOST * sizeof (smb_wchar_t)));
274 
275 	if ((p = strchr(session->workstation, ' ')) != 0)
276 		*p = '\0';
277 
278 	kmem_free(names, hdr.xh_length);
279 	return (smb_session_send(session, POSITIVE_SESSION_RESPONSE, NULL));
280 }
281 
282 /*
283  * Read 4-byte header from the session socket and build an in-memory
284  * session transport header.  See smb_xprt_t definition for header
285  * format information.
286  *
287  * Direct hosted NetBIOS-less SMB (SMB-over-TCP) uses port 445.  The
288  * first byte of the four-byte header must be 0 and the next three
289  * bytes contain the length of the remaining data.
290  */
291 int
smb_session_xprt_gethdr(smb_session_t * session,smb_xprt_t * ret_hdr)292 smb_session_xprt_gethdr(smb_session_t *session, smb_xprt_t *ret_hdr)
293 {
294 	int		rc;
295 	unsigned char	buf[NETBIOS_HDR_SZ];
296 
297 	if ((rc = smb_sorecv(session->sock, buf, NETBIOS_HDR_SZ)) != 0)
298 		return (rc);
299 
300 	switch (session->s_local_port) {
301 	case IPPORT_NETBIOS_SSN:
302 		ret_hdr->xh_type = buf[0];
303 		ret_hdr->xh_length = (((uint32_t)buf[1] & 1) << 16) |
304 		    ((uint32_t)buf[2] << 8) |
305 		    ((uint32_t)buf[3]);
306 		break;
307 
308 	case IPPORT_SMB:
309 		ret_hdr->xh_type = buf[0];
310 
311 		if (ret_hdr->xh_type != 0) {
312 			cmn_err(CE_WARN, "invalid NBT type (%u) from %s",
313 			    ret_hdr->xh_type, session->ip_addr_str);
314 			return (EPROTO);
315 		}
316 
317 		ret_hdr->xh_length = ((uint32_t)buf[1] << 16) |
318 		    ((uint32_t)buf[2] << 8) |
319 		    ((uint32_t)buf[3]);
320 		break;
321 
322 	default:
323 		cmn_err(CE_WARN, "invalid port %u", session->s_local_port);
324 		return (EPROTO);
325 	}
326 
327 	return (0);
328 }
329 
330 /*
331  * Encode a transport session packet header into a 4-byte buffer.
332  */
333 static int
smb_session_xprt_puthdr(smb_session_t * session,uint8_t msg_type,uint32_t msg_length,uint8_t * buf,size_t buflen)334 smb_session_xprt_puthdr(smb_session_t *session,
335     uint8_t msg_type, uint32_t msg_length,
336     uint8_t *buf, size_t buflen)
337 {
338 	if (buf == NULL || buflen < NETBIOS_HDR_SZ) {
339 		return (-1);
340 	}
341 
342 	switch (session->s_local_port) {
343 	case IPPORT_NETBIOS_SSN:
344 		/* Per RFC 1001, 1002: msg. len < 128KB */
345 		if (msg_length >= (1 << 17))
346 			return (-1);
347 		buf[0] = msg_type;
348 		buf[1] = ((msg_length >> 16) & 1);
349 		buf[2] = (msg_length >> 8) & 0xff;
350 		buf[3] = msg_length & 0xff;
351 		break;
352 
353 	case IPPORT_SMB:
354 		/*
355 		 * SMB over TCP is like NetBIOS but the one byte
356 		 * message type is always zero, and the length
357 		 * part is three bytes.  It could actually use
358 		 * longer messages, but this is conservative.
359 		 */
360 		if (msg_length >= (1 << 24))
361 			return (-1);
362 		buf[0] = msg_type;
363 		buf[1] = (msg_length >> 16) & 0xff;
364 		buf[2] = (msg_length >> 8) & 0xff;
365 		buf[3] = msg_length & 0xff;
366 		break;
367 
368 	default:
369 		cmn_err(CE_WARN, "invalid port %u", session->s_local_port);
370 		return (-1);
371 	}
372 
373 	return (0);
374 }
375 
376 static int
smb_request_recv(smb_request_t * sr,uint32_t len)377 smb_request_recv(smb_request_t *sr, uint32_t len)
378 {
379 	mbuf_t *mhead = NULL;
380 	int rc;
381 
382 	rc = smb_net_recv_mbufs(sr->session, &mhead, len);
383 	if (rc != 0)
384 		return (rc);
385 
386 	/*
387 	 * Setup command mbuf chain received.
388 	 */
389 	MBC_ATTACH_MBUF(&sr->command, mhead);
390 	sr->command.max_bytes = len;
391 
392 	return (0);
393 }
394 
395 /*
396  * smb_request_cancel
397  *
398  * Handle a cancel for a request properly depending on the current request
399  * state.
400  */
401 void
smb_request_cancel(smb_request_t * sr)402 smb_request_cancel(smb_request_t *sr)
403 {
404 	void (*cancel_method)(smb_request_t *) = NULL;
405 
406 	mutex_enter(&sr->sr_mutex);
407 	switch (sr->sr_state) {
408 
409 	case SMB_REQ_STATE_INITIALIZING:
410 	case SMB_REQ_STATE_SUBMITTED:
411 	case SMB_REQ_STATE_ACTIVE:
412 	case SMB_REQ_STATE_CLEANED_UP:
413 		sr->sr_state = SMB_REQ_STATE_CANCELLED;
414 		break;
415 
416 	case SMB_REQ_STATE_WAITING_AUTH:
417 	case SMB_REQ_STATE_WAITING_FCN1:
418 	case SMB_REQ_STATE_WAITING_LOCK:
419 	case SMB_REQ_STATE_WAITING_PIPE:
420 	case SMB_REQ_STATE_WAITING_OLBRK:
421 		/*
422 		 * These are states that have a cancel_method.
423 		 * Make the state change now, to ensure that
424 		 * we call cancel_method exactly once.
425 		 *
426 		 * Do the method call with sr_mutex not held.
427 		 * When the cancelled request thread resumes,
428 		 * it should re-take sr_mutex and wait for
429 		 * sr_state != CANCEL_PENDING, ensuring that
430 		 * the cancel method has completed.
431 		 */
432 		sr->sr_state = SMB_REQ_STATE_CANCEL_PENDING;
433 		cancel_method = sr->cancel_method;
434 		VERIFY(cancel_method != NULL);
435 		mutex_exit(&sr->sr_mutex);
436 		cancel_method(sr);
437 		mutex_enter(&sr->sr_mutex);
438 		if (sr->sr_state == SMB_REQ_STATE_CANCEL_PENDING)
439 			sr->sr_state = SMB_REQ_STATE_CANCELLED;
440 		cv_broadcast(&sr->sr_st_cv);
441 		break;
442 
443 	case SMB_REQ_STATE_WAITING_FCN2:
444 	case SMB_REQ_STATE_COMPLETED:
445 	case SMB_REQ_STATE_CANCEL_PENDING:
446 	case SMB_REQ_STATE_CANCELLED:
447 		/*
448 		 * No action required for these states since the request
449 		 * is completing.
450 		 */
451 		break;
452 
453 	case SMB_REQ_STATE_FREE:
454 	default:
455 		SMB_PANIC();
456 	}
457 	mutex_exit(&sr->sr_mutex);
458 }
459 
460 /*
461  * smb_session_receiver
462  *
463  * Receives request from the network and dispatches them to a worker.
464  *
465  * When we receive a disconnect here, it _could_ be due to the server
466  * having initiated disconnect, in which case the session state will be
467  * SMB_SESSION_STATE_TERMINATED and we want to keep that state so later
468  * tear-down logic will know which side initiated.
469  */
470 void
smb_session_receiver(smb_session_t * session)471 smb_session_receiver(smb_session_t *session)
472 {
473 	int	rc = 0;
474 	timeout_id_t tmo = NULL;
475 
476 	SMB_SESSION_VALID(session);
477 
478 	session->s_thread = curthread;
479 
480 	if (session->s_local_port == IPPORT_NETBIOS_SSN) {
481 		rc = smb_netbios_session_request(session);
482 		if (rc != 0) {
483 			smb_rwx_rwenter(&session->s_lock, RW_WRITER);
484 			if (session->s_state != SMB_SESSION_STATE_TERMINATED)
485 				session->s_state =
486 				    SMB_SESSION_STATE_DISCONNECTED;
487 			smb_rwx_rwexit(&session->s_lock);
488 			return;
489 		}
490 	}
491 
492 	smb_rwx_rwenter(&session->s_lock, RW_WRITER);
493 	session->s_state = SMB_SESSION_STATE_ESTABLISHED;
494 	session->s_auth_tmo = timeout((tmo_func_t)smb_session_disconnect,
495 	    session, SEC_TO_TICK(smb_session_auth_tmo));
496 	smb_rwx_rwexit(&session->s_lock);
497 
498 	(void) smb_session_reader(session);
499 
500 	smb_rwx_rwenter(&session->s_lock, RW_WRITER);
501 	if (session->s_state != SMB_SESSION_STATE_TERMINATED)
502 		session->s_state = SMB_SESSION_STATE_DISCONNECTED;
503 	tmo = session->s_auth_tmo;
504 	session->s_auth_tmo = NULL;
505 	smb_rwx_rwexit(&session->s_lock);
506 
507 	/* Timeout callback takes s_lock. See untimeout(9f) */
508 	if (tmo != NULL)
509 		(void) untimeout(tmo);
510 
511 	smb_soshutdown(session->sock);
512 
513 	DTRACE_PROBE2(session__drop, struct session *, session, int, rc);
514 
515 	smb_session_cancel(session);
516 	/*
517 	 * At this point everything related to the session should have been
518 	 * cleaned up and we expect that nothing will attempt to use the
519 	 * socket.
520 	 */
521 }
522 
523 /*
524  * smb_session_disconnect
525  *
526  * Server-initiated disconnect (i.e. server shutdown)
527  */
528 void
smb_session_disconnect(smb_session_t * session)529 smb_session_disconnect(smb_session_t *session)
530 {
531 	SMB_SESSION_VALID(session);
532 
533 	smb_rwx_rwenter(&session->s_lock, RW_WRITER);
534 	switch (session->s_state) {
535 	case SMB_SESSION_STATE_INITIALIZED:
536 	case SMB_SESSION_STATE_CONNECTED:
537 	case SMB_SESSION_STATE_ESTABLISHED:
538 	case SMB_SESSION_STATE_NEGOTIATED:
539 		smb_soshutdown(session->sock);
540 		session->s_state = SMB_SESSION_STATE_TERMINATED;
541 		break;
542 	case SMB_SESSION_STATE_DISCONNECTED:
543 	case SMB_SESSION_STATE_TERMINATED:
544 		break;
545 	}
546 	smb_rwx_rwexit(&session->s_lock);
547 }
548 
549 /*
550  * Read and process SMB requests.
551  *
552  * Returns:
553  *	0	Success
554  *	1	Unable to read transport header
555  *	2	Invalid transport header type
556  *	3	Invalid SMB length (too small)
557  *	4	Unable to read SMB header
558  *	5	Invalid SMB header (bad magic number)
559  *	6	Unable to read SMB data
560  */
561 static int
smb_session_reader(smb_session_t * session)562 smb_session_reader(smb_session_t *session)
563 {
564 	smb_server_t	*sv;
565 	smb_request_t	*sr = NULL;
566 	smb_xprt_t	hdr;
567 	int		rc;
568 
569 	sv = session->s_server;
570 
571 	for (;;) {
572 
573 		rc = smb_session_xprt_gethdr(session, &hdr);
574 		if (rc)
575 			return (rc);
576 
577 		DTRACE_PROBE2(session__receive__xprthdr, session_t *, session,
578 		    smb_xprt_t *, &hdr);
579 
580 		if (hdr.xh_type != SESSION_MESSAGE) {
581 			/*
582 			 * Anything other than SESSION_MESSAGE or
583 			 * SESSION_KEEP_ALIVE is an error.  A SESSION_REQUEST
584 			 * may indicate a new session request but we need to
585 			 * close this session and we can treat it as an error
586 			 * here.
587 			 */
588 			if (hdr.xh_type == SESSION_KEEP_ALIVE) {
589 				session->keep_alive = smb_keep_alive;
590 				continue;
591 			}
592 			return (EPROTO);
593 		}
594 
595 		if (hdr.xh_length == 0) {
596 			/* zero length is another form of keep alive */
597 			session->keep_alive = smb_keep_alive;
598 			continue;
599 		}
600 
601 		if (hdr.xh_length < SMB_HEADER_LEN)
602 			return (EPROTO);
603 		if (hdr.xh_length > session->cmd_max_bytes)
604 			return (EPROTO);
605 
606 		session->keep_alive = smb_keep_alive;
607 
608 		/*
609 		 * Allocate a request context, read the whole message.
610 		 * If the request alloc fails, we've disconnected
611 		 * and won't be able to send the reply anyway, so bail now.
612 		 */
613 		if ((sr = smb_request_alloc(session, hdr.xh_length)) == NULL)
614 			break;
615 		if ((rc = smb_request_recv(sr, hdr.xh_length)) != 0) {
616 			smb_request_free(sr);
617 			break;
618 		}
619 
620 		/* accounting: received bytes */
621 		smb_server_add_rxb(sv,
622 		    (int64_t)(hdr.xh_length + NETBIOS_HDR_SZ));
623 
624 		DTRACE_PROBE1(session__receive__smb, smb_request_t *, sr);
625 
626 		rc = session->newrq_func(sr);
627 		sr = NULL;	/* enqueued or freed */
628 		if (rc != 0)
629 			break;
630 
631 		/* See notes where this is defined (above). */
632 		if (smb_reader_delay) {
633 			delay(MSEC_TO_TICK(smb_reader_delay));
634 		}
635 	}
636 	return (rc);
637 }
638 
639 /*
640  * This is the initial handler for new smb requests, called from
641  * from smb_session_reader when we have not yet seen any requests.
642  * The first SMB request must be "negotiate", which determines
643  * which protocol and dialect we'll be using.  That's the ONLY
644  * request type handled here, because with all later requests,
645  * we know the protocol and handle those with either the SMB1 or
646  * SMB2 handlers:  smb1sr_post() or smb2sr_post().
647  * Those do NOT allow SMB negotiate, because that's only allowed
648  * as the first request on new session.
649  *
650  * This and other "post a request" handlers must either enqueue
651  * the new request for the session taskq, or smb_request_free it
652  * (in case we've decided to drop this connection).  In this
653  * (special) new request handler, we always free the request.
654  *
655  * Return value is 0 for success, and anything else will
656  * terminate the reader thread (drop the connection).
657  */
658 static int
smbsr_newrq_initial(smb_request_t * sr)659 smbsr_newrq_initial(smb_request_t *sr)
660 {
661 	uint32_t magic;
662 	int rc;
663 
664 	mutex_enter(&sr->sr_mutex);
665 	sr->sr_state = SMB_REQ_STATE_ACTIVE;
666 	mutex_exit(&sr->sr_mutex);
667 
668 	if ((rc = smb_mbc_peek(&sr->command, 0, "l", &magic)) != 0)
669 		goto done;
670 
671 	switch (magic) {
672 	case SMB_PROTOCOL_MAGIC:
673 		rc = smb1_newrq_negotiate(sr);
674 		break;
675 	case SMB2_PROTOCOL_MAGIC:
676 		rc = smb2_newrq_negotiate(sr);
677 		break;
678 	default:
679 		rc = EPROTO;
680 	}
681 
682 done:
683 	mutex_enter(&sr->sr_mutex);
684 	sr->sr_state = SMB_REQ_STATE_COMPLETED;
685 	mutex_exit(&sr->sr_mutex);
686 
687 	smb_request_free(sr);
688 	return (rc);
689 }
690 
691 /*
692  * Port will be IPPORT_NETBIOS_SSN or IPPORT_SMB.
693  */
694 smb_session_t *
smb_session_create(ksocket_t new_so,uint16_t port,smb_server_t * sv,int family)695 smb_session_create(ksocket_t new_so, uint16_t port, smb_server_t *sv,
696     int family)
697 {
698 	struct sockaddr_in	sin;
699 	socklen_t		slen;
700 	struct sockaddr_in6	sin6;
701 	smb_session_t		*session;
702 	int64_t			now;
703 	uint16_t		rport;
704 
705 	session = kmem_cache_alloc(smb_cache_session, KM_SLEEP);
706 	bzero(session, sizeof (smb_session_t));
707 
708 	if (smb_idpool_constructor(&session->s_uid_pool)) {
709 		kmem_cache_free(smb_cache_session, session);
710 		return (NULL);
711 	}
712 	if (smb_idpool_constructor(&session->s_tid_pool)) {
713 		smb_idpool_destructor(&session->s_uid_pool);
714 		kmem_cache_free(smb_cache_session, session);
715 		return (NULL);
716 	}
717 
718 	now = ddi_get_lbolt64();
719 
720 	session->s_server = sv;
721 	session->s_kid = SMB_NEW_KID();
722 	session->s_state = SMB_SESSION_STATE_INITIALIZED;
723 	session->native_os = NATIVE_OS_UNKNOWN;
724 	session->opentime = now;
725 	session->keep_alive = smb_keep_alive;
726 	session->activity_timestamp = now;
727 	smb_session_genkey(session);
728 
729 	mutex_init(&session->s_credits_mutex, NULL, MUTEX_DEFAULT, NULL);
730 
731 	smb_slist_constructor(&session->s_req_list, sizeof (smb_request_t),
732 	    offsetof(smb_request_t, sr_session_lnd));
733 
734 	smb_llist_constructor(&session->s_user_list, sizeof (smb_user_t),
735 	    offsetof(smb_user_t, u_lnd));
736 
737 	smb_llist_constructor(&session->s_tree_list, sizeof (smb_tree_t),
738 	    offsetof(smb_tree_t, t_lnd));
739 
740 	smb_llist_constructor(&session->s_xa_list, sizeof (smb_xa_t),
741 	    offsetof(smb_xa_t, xa_lnd));
742 
743 	smb_net_txl_constructor(&session->s_txlst);
744 
745 	smb_rwx_init(&session->s_lock);
746 
747 	session->s_srqueue = &sv->sv_srqueue;
748 	smb_server_get_cfg(sv, &session->s_cfg);
749 
750 	if (new_so == NULL) {
751 		/*
752 		 * This call is creating the special "server" session,
753 		 * used for kshare export, oplock breaks, CA import.
754 		 * CA import creates temporary trees on this session
755 		 * and those should never get map/unmap up-calls, so
756 		 * force the map/unmap flags zero on this session.
757 		 * Set a "modern" dialect for CA import too, so
758 		 * pathname parse doesn't do OS/2 stuff, etc.
759 		 */
760 		session->s_cfg.skc_execflags = 0;
761 		session->dialect = session->s_cfg.skc_max_protocol;
762 	} else {
763 		if (family == AF_INET) {
764 			slen = sizeof (sin);
765 			(void) ksocket_getsockname(new_so,
766 			    (struct sockaddr *)&sin, &slen, CRED());
767 			bcopy(&sin.sin_addr,
768 			    &session->local_ipaddr.au_addr.au_ipv4,
769 			    sizeof (in_addr_t));
770 			slen = sizeof (sin);
771 			(void) ksocket_getpeername(new_so,
772 			    (struct sockaddr *)&sin, &slen, CRED());
773 			bcopy(&sin.sin_addr,
774 			    &session->ipaddr.au_addr.au_ipv4,
775 			    sizeof (in_addr_t));
776 			rport = sin.sin_port;
777 		} else {
778 			slen = sizeof (sin6);
779 			(void) ksocket_getsockname(new_so,
780 			    (struct sockaddr *)&sin6, &slen, CRED());
781 			bcopy(&sin6.sin6_addr,
782 			    &session->local_ipaddr.au_addr.au_ipv6,
783 			    sizeof (in6_addr_t));
784 			slen = sizeof (sin6);
785 			(void) ksocket_getpeername(new_so,
786 			    (struct sockaddr *)&sin6, &slen, CRED());
787 			bcopy(&sin6.sin6_addr,
788 			    &session->ipaddr.au_addr.au_ipv6,
789 			    sizeof (in6_addr_t));
790 			rport = sin6.sin6_port;
791 		}
792 		session->ipaddr.a_family = family;
793 		session->local_ipaddr.a_family = family;
794 		session->s_local_port = port;
795 		session->s_remote_port = ntohs(rport);
796 		session->sock = new_so;
797 		(void) smb_inet_ntop(&session->ipaddr,
798 		    session->ip_addr_str, INET6_ADDRSTRLEN);
799 		if (port == IPPORT_NETBIOS_SSN)
800 			smb_server_inc_nbt_sess(sv);
801 		else
802 			smb_server_inc_tcp_sess(sv);
803 	}
804 
805 	/*
806 	 * The initial new request handler is special,
807 	 * and only accepts negotiation requests.
808 	 */
809 	session->newrq_func = smbsr_newrq_initial;
810 
811 	/* These may increase in SMB2 negotiate. */
812 	session->cmd_max_bytes = SMB_REQ_MAX_SIZE;
813 	session->reply_max_bytes = SMB_REQ_MAX_SIZE;
814 
815 	session->s_magic = SMB_SESSION_MAGIC;
816 	return (session);
817 }
818 
819 void
smb_session_delete(smb_session_t * session)820 smb_session_delete(smb_session_t *session)
821 {
822 
823 	ASSERT(session->s_magic == SMB_SESSION_MAGIC);
824 
825 	if (session->enc_mech != NULL)
826 		smb3_encrypt_ssn_fini(session);
827 
828 	if (session->sign_fini != NULL)
829 		session->sign_fini(session);
830 
831 	if (session->signing.mackey != NULL) {
832 		kmem_free(session->signing.mackey,
833 		    session->signing.mackey_len);
834 	}
835 
836 	if (session->preauth_mech != NULL)
837 		smb31_preauth_fini(session);
838 
839 	session->s_magic = 0;
840 
841 	smb_rwx_destroy(&session->s_lock);
842 	smb_net_txl_destructor(&session->s_txlst);
843 
844 	mutex_destroy(&session->s_credits_mutex);
845 
846 	smb_slist_destructor(&session->s_req_list);
847 	smb_llist_destructor(&session->s_tree_list);
848 	smb_llist_destructor(&session->s_user_list);
849 	smb_llist_destructor(&session->s_xa_list);
850 
851 	ASSERT(session->s_tree_cnt == 0);
852 	ASSERT(session->s_file_cnt == 0);
853 	ASSERT(session->s_dir_cnt == 0);
854 
855 	smb_idpool_destructor(&session->s_tid_pool);
856 	smb_idpool_destructor(&session->s_uid_pool);
857 	if (session->sock != NULL) {
858 		if (session->s_local_port == IPPORT_NETBIOS_SSN)
859 			smb_server_dec_nbt_sess(session->s_server);
860 		else
861 			smb_server_dec_tcp_sess(session->s_server);
862 		smb_sodestroy(session->sock);
863 	}
864 	kmem_cache_free(smb_cache_session, session);
865 }
866 
867 static void
smb_session_cancel(smb_session_t * session)868 smb_session_cancel(smb_session_t *session)
869 {
870 	smb_xa_t	*xa, *nextxa;
871 
872 	/* All the request currently being treated must be canceled. */
873 	smb_session_cancel_requests(session, NULL, NULL);
874 
875 	/*
876 	 * Work around limitations on cancellation of pipe_read.
877 	 */
878 	smb_session_disconnect_share(session, "IPC$");
879 
880 	/*
881 	 * We wait for the completion of all the requests associated with
882 	 * this session.
883 	 */
884 	smb_slist_wait_for_empty(&session->s_req_list);
885 
886 	/*
887 	 * Cleanup transact state objects
888 	 */
889 	xa = smb_llist_head(&session->s_xa_list);
890 	while (xa) {
891 		nextxa = smb_llist_next(&session->s_xa_list, xa);
892 		smb_xa_close(xa);
893 		xa = nextxa;
894 	}
895 
896 	/*
897 	 * At this point the reference count of the files and directories
898 	 * should be zero. It should be possible to destroy them without
899 	 * any problem, which should trigger the destruction of other objects.
900 	 */
901 	smb_session_logoff(session);
902 }
903 
904 /*
905  * Cancel requests.  If a non-null tree is specified, only requests specific
906  * to that tree will be cancelled.  If a non-null sr is specified, that sr
907  * will be not be cancelled - this would typically be the caller's sr.
908  */
909 void
smb_session_cancel_requests(smb_session_t * session,smb_tree_t * tree,smb_request_t * exclude_sr)910 smb_session_cancel_requests(
911     smb_session_t	*session,
912     smb_tree_t		*tree,
913     smb_request_t	*exclude_sr)
914 {
915 	smb_request_t	*sr;
916 
917 	smb_slist_enter(&session->s_req_list);
918 	sr = smb_slist_head(&session->s_req_list);
919 
920 	while (sr) {
921 		ASSERT(sr->sr_magic == SMB_REQ_MAGIC);
922 		if ((sr != exclude_sr) &&
923 		    (tree == NULL || sr->tid_tree == tree))
924 			smb_request_cancel(sr);
925 
926 		sr = smb_slist_next(&session->s_req_list, sr);
927 	}
928 
929 	smb_slist_exit(&session->s_req_list);
930 }
931 
932 /*
933  * Find a user on the specified session by SMB UID.
934  */
935 smb_user_t *
smb_session_lookup_uid(smb_session_t * session,uint16_t uid)936 smb_session_lookup_uid(smb_session_t *session, uint16_t uid)
937 {
938 	return (smb_session_lookup_uid_st(session, 0, uid,
939 	    SMB_USER_STATE_LOGGED_ON));
940 }
941 
942 /*
943  * Find a user on the specified session by SMB2 SSNID.
944  */
945 smb_user_t *
smb_session_lookup_ssnid(smb_session_t * session,uint64_t ssnid)946 smb_session_lookup_ssnid(smb_session_t *session, uint64_t ssnid)
947 {
948 	return (smb_session_lookup_uid_st(session, ssnid, 0,
949 	    SMB_USER_STATE_LOGGED_ON));
950 }
951 
952 smb_user_t *
smb_session_lookup_uid_st(smb_session_t * session,uint64_t ssnid,uint16_t uid,smb_user_state_t st)953 smb_session_lookup_uid_st(smb_session_t *session, uint64_t ssnid,
954     uint16_t uid, smb_user_state_t st)
955 {
956 	smb_user_t	*user;
957 	smb_llist_t	*user_list;
958 
959 	SMB_SESSION_VALID(session);
960 
961 	user_list = &session->s_user_list;
962 	smb_llist_enter(user_list, RW_READER);
963 
964 	for (user = smb_llist_head(user_list);
965 	    user != NULL;
966 	    user = smb_llist_next(user_list, user)) {
967 
968 		SMB_USER_VALID(user);
969 		ASSERT(user->u_session == session);
970 
971 		if (user->u_ssnid != ssnid && user->u_uid != uid)
972 			continue;
973 
974 		mutex_enter(&user->u_mutex);
975 		if (user->u_state == st) {
976 			// smb_user_hold_internal(user);
977 			user->u_refcnt++;
978 			mutex_exit(&user->u_mutex);
979 			break;
980 		}
981 		mutex_exit(&user->u_mutex);
982 	}
983 
984 	smb_llist_exit(user_list);
985 	return (user);
986 }
987 
988 /*
989  * Find a tree by tree-id.
990  */
991 smb_tree_t *
smb_session_lookup_tree(smb_session_t * session,uint16_t tid)992 smb_session_lookup_tree(
993     smb_session_t	*session,
994     uint16_t		tid)
995 {
996 	smb_tree_t	*tree;
997 
998 	SMB_SESSION_VALID(session);
999 
1000 	smb_llist_enter(&session->s_tree_list, RW_READER);
1001 	tree = smb_llist_head(&session->s_tree_list);
1002 
1003 	while (tree) {
1004 		ASSERT3U(tree->t_magic, ==, SMB_TREE_MAGIC);
1005 		ASSERT(tree->t_session == session);
1006 
1007 		if (tree->t_tid == tid) {
1008 			if (smb_tree_hold(tree)) {
1009 				smb_llist_exit(&session->s_tree_list);
1010 				return (tree);
1011 			} else {
1012 				smb_llist_exit(&session->s_tree_list);
1013 				return (NULL);
1014 			}
1015 		}
1016 
1017 		tree = smb_llist_next(&session->s_tree_list, tree);
1018 	}
1019 
1020 	smb_llist_exit(&session->s_tree_list);
1021 	return (NULL);
1022 }
1023 
1024 /*
1025  * Disconnect all trees that match the specified client process-id.
1026  * Used by the SMB1 "process exit" request.
1027  */
1028 void
smb_session_close_pid(smb_session_t * session,uint32_t pid)1029 smb_session_close_pid(
1030     smb_session_t	*session,
1031     uint32_t		pid)
1032 {
1033 	smb_llist_t	*tree_list = &session->s_tree_list;
1034 	smb_tree_t	*tree;
1035 
1036 	smb_llist_enter(tree_list, RW_READER);
1037 
1038 	tree = smb_llist_head(tree_list);
1039 	while (tree) {
1040 		if (smb_tree_hold(tree)) {
1041 			smb_tree_close_pid(tree, pid);
1042 			smb_tree_release(tree);
1043 		}
1044 		tree = smb_llist_next(tree_list, tree);
1045 	}
1046 
1047 	smb_llist_exit(tree_list);
1048 }
1049 
1050 static void
smb_session_tree_dtor(void * arg)1051 smb_session_tree_dtor(void *arg)
1052 {
1053 	smb_tree_t	*tree = arg;
1054 
1055 	smb_tree_disconnect(tree, B_TRUE);
1056 	/* release the ref acquired during the traversal loop */
1057 	smb_tree_release(tree);
1058 }
1059 
1060 
1061 /*
1062  * Disconnect all trees that this user has connected.
1063  */
1064 void
smb_session_disconnect_owned_trees(smb_session_t * session,smb_user_t * owner)1065 smb_session_disconnect_owned_trees(
1066     smb_session_t	*session,
1067     smb_user_t		*owner)
1068 {
1069 	smb_tree_t	*tree;
1070 	smb_llist_t	*tree_list = &session->s_tree_list;
1071 
1072 	SMB_SESSION_VALID(session);
1073 	SMB_USER_VALID(owner);
1074 
1075 	smb_llist_enter(tree_list, RW_READER);
1076 
1077 	tree = smb_llist_head(tree_list);
1078 	while (tree) {
1079 		if ((tree->t_owner == owner) &&
1080 		    smb_tree_hold(tree)) {
1081 			/*
1082 			 * smb_tree_hold() succeeded, hence we are in state
1083 			 * SMB_TREE_STATE_CONNECTED; schedule this tree
1084 			 * for disconnect after smb_llist_exit because
1085 			 * the "unmap exec" up-call can block, and we'd
1086 			 * rather not block with the tree list locked.
1087 			 */
1088 			smb_llist_post(tree_list, tree, smb_session_tree_dtor);
1089 		}
1090 		tree = smb_llist_next(tree_list, tree);
1091 	}
1092 
1093 	/* drop the lock and flush the dtor queue */
1094 	smb_llist_exit(tree_list);
1095 }
1096 
1097 /*
1098  * Disconnect all trees that this user has connected.
1099  */
1100 static void
smb_session_disconnect_trees(smb_session_t * session)1101 smb_session_disconnect_trees(
1102     smb_session_t	*session)
1103 {
1104 	smb_llist_t	*tree_list = &session->s_tree_list;
1105 	smb_tree_t	*tree;
1106 
1107 	smb_llist_enter(tree_list, RW_READER);
1108 
1109 	tree = smb_llist_head(tree_list);
1110 	while (tree) {
1111 		if (smb_tree_hold(tree)) {
1112 			smb_llist_post(tree_list, tree,
1113 			    smb_session_tree_dtor);
1114 		}
1115 		tree = smb_llist_next(tree_list, tree);
1116 	}
1117 
1118 	/* drop the lock and flush the dtor queue */
1119 	smb_llist_exit(tree_list);
1120 }
1121 
1122 /*
1123  * Variant of smb_session_tree_dtor that also
1124  * cancels requests using this tree.
1125  */
1126 static void
smb_session_tree_kill(void * arg)1127 smb_session_tree_kill(void *arg)
1128 {
1129 	smb_tree_t	*tree = arg;
1130 
1131 	SMB_TREE_VALID(tree);
1132 
1133 	smb_tree_disconnect(tree, B_TRUE);
1134 	smb_session_cancel_requests(tree->t_session, tree, NULL);
1135 
1136 	/* release the ref acquired during the traversal loop */
1137 	smb_tree_release(tree);
1138 }
1139 
1140 /*
1141  * Disconnect all trees that match the specified share name,
1142  * and kill requests using those trees.
1143  */
1144 void
smb_session_disconnect_share(smb_session_t * session,const char * sharename)1145 smb_session_disconnect_share(
1146     smb_session_t	*session,
1147     const char		*sharename)
1148 {
1149 	smb_llist_t	*ll;
1150 	smb_tree_t	*tree;
1151 
1152 	SMB_SESSION_VALID(session);
1153 
1154 	ll = &session->s_tree_list;
1155 	smb_llist_enter(ll, RW_READER);
1156 
1157 	for (tree = smb_llist_head(ll);
1158 	    tree != NULL;
1159 	    tree = smb_llist_next(ll, tree)) {
1160 
1161 		SMB_TREE_VALID(tree);
1162 		ASSERT(tree->t_session == session);
1163 
1164 		if (smb_strcasecmp(tree->t_sharename, sharename, 0) != 0)
1165 			continue;
1166 
1167 		if (smb_tree_hold(tree)) {
1168 			smb_llist_post(ll, tree,
1169 			    smb_session_tree_kill);
1170 		}
1171 	}
1172 
1173 	smb_llist_exit(ll);
1174 }
1175 
1176 int smb_session_logoff_maxwait = 5;	/* seconds */
1177 
1178 /*
1179  * Logoff all users associated with the specified session.
1180  *
1181  * This is called for both server-initiated disconnect
1182  * (SMB_SESSION_STATE_TERMINATED) and client-initiated
1183  * disconnect (SMB_SESSION_STATE_DISCONNECTED).
1184  * If client-initiated, save durable handles.
1185  * All requests on this session have finished.
1186  */
1187 void
smb_session_logoff(smb_session_t * session)1188 smb_session_logoff(smb_session_t *session)
1189 {
1190 	smb_llist_t	*ulist;
1191 	smb_user_t	*user;
1192 	int		count;
1193 	int		timeleft = SEC_TO_TICK(smb_session_logoff_maxwait);
1194 
1195 	SMB_SESSION_VALID(session);
1196 
1197 top:
1198 	ulist = &session->s_user_list;
1199 	smb_llist_enter(ulist, RW_READER);
1200 
1201 	user = smb_llist_head(ulist);
1202 	while (user) {
1203 		SMB_USER_VALID(user);
1204 		ASSERT(user->u_session == session);
1205 
1206 		mutex_enter(&user->u_mutex);
1207 		switch (user->u_state) {
1208 		case SMB_USER_STATE_LOGGING_ON:
1209 		case SMB_USER_STATE_LOGGED_ON:
1210 			// smb_user_hold_internal(user);
1211 			user->u_refcnt++;
1212 			mutex_exit(&user->u_mutex);
1213 			smb_user_logoff(user);
1214 			smb_user_release(user);
1215 			break;
1216 
1217 		case SMB_USER_STATE_LOGGED_OFF:
1218 		case SMB_USER_STATE_LOGGING_OFF:
1219 			mutex_exit(&user->u_mutex);
1220 			break;
1221 
1222 		default:
1223 			mutex_exit(&user->u_mutex);
1224 			ASSERT(0);
1225 			break;
1226 		}
1227 
1228 		user = smb_llist_next(ulist, user);
1229 	}
1230 
1231 	count = smb_llist_get_count(ulist);
1232 
1233 	/* drop the lock and flush the dtor queue */
1234 	smb_llist_exit(ulist);
1235 
1236 	/*
1237 	 * Wait (briefly) for user objects to go away.
1238 	 * They might linger, eg. if some ofile ref has been
1239 	 * forgotten, which holds, a tree and a user.
1240 	 * See smb_session_destroy.
1241 	 */
1242 	if (count == 0) {
1243 		/* User list is empty. */
1244 		smb_rwx_rwenter(&session->s_lock, RW_WRITER);
1245 		session->s_state = SMB_SESSION_STATE_SHUTDOWN;
1246 		smb_rwx_rwexit(&session->s_lock);
1247 	} else {
1248 		smb_rwx_rwenter(&session->s_lock, RW_READER);
1249 		if (session->s_state != SMB_SESSION_STATE_SHUTDOWN &&
1250 		    timeleft > 0) {
1251 			/* May be signaled in smb_user_delete */
1252 			(void) smb_rwx_cvwait(&session->s_lock,
1253 			    MSEC_TO_TICK(200));
1254 			timeleft -= 200;
1255 			smb_rwx_rwexit(&session->s_lock);
1256 			goto top;
1257 		}
1258 		smb_rwx_rwexit(&session->s_lock);
1259 
1260 		cmn_err(CE_NOTE, "!session logoff waited %d seconds"
1261 		    " with %d logons remaining",
1262 		    smb_session_logoff_maxwait, count);
1263 		DTRACE_PROBE1(max__wait, smb_session_t *, session);
1264 	}
1265 
1266 	/*
1267 	 * User list should be empty now, but might not be if we
1268 	 * timed out waiting for smb_user objects to go away.
1269 	 * Checked in smb_server_destroy_session
1270 	 *
1271 	 * User logoff happens first so we'll set preserve_opens
1272 	 * for client-initiated disconnect.  When that's done
1273 	 * there should be no trees left, but check anyway.
1274 	 */
1275 	smb_session_disconnect_trees(session);
1276 }
1277 
1278 /*
1279  * Copy the session workstation/client name to buf.  If the workstation
1280  * is an empty string (which it will be on TCP connections), use the
1281  * client IP address.
1282  */
1283 void
smb_session_getclient(smb_session_t * sn,char * buf,size_t buflen)1284 smb_session_getclient(smb_session_t *sn, char *buf, size_t buflen)
1285 {
1286 
1287 	*buf = '\0';
1288 
1289 	if (sn->workstation[0] != '\0') {
1290 		(void) strlcpy(buf, sn->workstation, buflen);
1291 		return;
1292 	}
1293 
1294 	(void) strlcpy(buf, sn->ip_addr_str, buflen);
1295 }
1296 
1297 /*
1298  * Check whether or not the specified client name is the client of this
1299  * session.  The name may be in UNC format (\\CLIENT).
1300  *
1301  * A workstation/client name is setup on NBT connections as part of the
1302  * NetBIOS session request but that isn't available on TCP connections.
1303  * If the session doesn't have a client name we typically return the
1304  * client IP address as the workstation name on MSRPC requests.  So we
1305  * check for the IP address here in addition to the workstation name.
1306  */
1307 boolean_t
smb_session_isclient(smb_session_t * sn,const char * client)1308 smb_session_isclient(smb_session_t *sn, const char *client)
1309 {
1310 
1311 	client += strspn(client, "\\");
1312 
1313 	if (smb_strcasecmp(client, sn->workstation, 0) == 0)
1314 		return (B_TRUE);
1315 
1316 	if (smb_strcasecmp(client, sn->ip_addr_str, 0) == 0)
1317 		return (B_TRUE);
1318 
1319 	return (B_FALSE);
1320 }
1321 
1322 /*
1323  * smb_request_alloc
1324  *
1325  * Allocate an smb_request_t structure from the kmem_cache.  Partially
1326  * initialize the found/new request.
1327  *
1328  * Returns pointer to a request, or NULL if the session state is
1329  * one in which new requests are no longer allowed.
1330  */
1331 smb_request_t *
smb_request_alloc(smb_session_t * session,int req_length)1332 smb_request_alloc(smb_session_t *session, int req_length)
1333 {
1334 	smb_request_t	*sr;
1335 
1336 	ASSERT(session->s_magic == SMB_SESSION_MAGIC);
1337 	ASSERT(req_length <= session->cmd_max_bytes);
1338 
1339 	sr = kmem_cache_alloc(smb_cache_request, KM_SLEEP);
1340 
1341 	/*
1342 	 * Future:  Use constructor to pre-initialize some fields.  For now
1343 	 * there are so many fields that it is easiest just to zero the
1344 	 * whole thing and start over.
1345 	 */
1346 	bzero(sr, sizeof (smb_request_t));
1347 
1348 	mutex_init(&sr->sr_mutex, NULL, MUTEX_DEFAULT, NULL);
1349 	cv_init(&sr->sr_st_cv, NULL, CV_DEFAULT, NULL);
1350 	smb_srm_init(sr);
1351 	sr->session = session;
1352 	sr->sr_server = session->s_server;
1353 	sr->sr_gmtoff = session->s_server->si_gmtoff;
1354 	sr->sr_cfg = &session->s_cfg;
1355 	sr->reply.max_bytes = session->reply_max_bytes;
1356 
1357 	sr->sr_magic = SMB_REQ_MAGIC;
1358 	sr->sr_state = SMB_REQ_STATE_INITIALIZING;
1359 
1360 	/*
1361 	 * Only allow new SMB requests in some states.
1362 	 */
1363 	smb_rwx_rwenter(&session->s_lock, RW_WRITER);
1364 	switch (session->s_state) {
1365 	case SMB_SESSION_STATE_CONNECTED:
1366 	case SMB_SESSION_STATE_INITIALIZED:
1367 	case SMB_SESSION_STATE_ESTABLISHED:
1368 	case SMB_SESSION_STATE_NEGOTIATED:
1369 		smb_slist_insert_tail(&session->s_req_list, sr);
1370 		break;
1371 
1372 	default:
1373 		ASSERT(0);
1374 		/* FALLTHROUGH */
1375 	case SMB_SESSION_STATE_DISCONNECTED:
1376 	case SMB_SESSION_STATE_SHUTDOWN:
1377 	case SMB_SESSION_STATE_TERMINATED:
1378 		/* Disallow new requests in these states. */
1379 		sr->session = NULL;
1380 		sr->sr_magic = 0;
1381 		cv_destroy(&sr->sr_st_cv);
1382 		mutex_destroy(&sr->sr_mutex);
1383 		kmem_cache_free(smb_cache_request, sr);
1384 		sr = NULL;
1385 		break;
1386 	}
1387 	smb_rwx_rwexit(&session->s_lock);
1388 
1389 	return (sr);
1390 }
1391 
1392 /*
1393  * smb_request_free
1394  *
1395  * release the memories which have been allocated for a smb request.
1396  */
1397 void
smb_request_free(smb_request_t * sr)1398 smb_request_free(smb_request_t *sr)
1399 {
1400 	ASSERT(sr->sr_magic == SMB_REQ_MAGIC);
1401 	ASSERT(sr->session);
1402 	ASSERT(sr->r_xa == NULL);
1403 
1404 	if (sr->fid_ofile != NULL) {
1405 		smb_ofile_release(sr->fid_ofile);
1406 	}
1407 
1408 	if (sr->tid_tree != NULL)
1409 		smb_tree_release(sr->tid_tree);
1410 
1411 	if (sr->uid_user != NULL)
1412 		smb_user_release(sr->uid_user);
1413 
1414 	if (sr->th_sid_user != NULL)
1415 		smb_user_release(sr->th_sid_user);
1416 
1417 	/*
1418 	 * The above may have left work on the delete queues
1419 	 */
1420 	smb_llist_flush(&sr->session->s_tree_list);
1421 	smb_llist_flush(&sr->session->s_user_list);
1422 
1423 	smb_slist_remove(&sr->session->s_req_list, sr);
1424 
1425 	sr->session = NULL;
1426 
1427 	smb_srm_fini(sr);
1428 
1429 	if (sr->command.chain)
1430 		m_freem(sr->command.chain);
1431 	if (sr->reply.chain)
1432 		m_freem(sr->reply.chain);
1433 	if (sr->raw_data.chain)
1434 		m_freem(sr->raw_data.chain);
1435 
1436 	sr->sr_magic = 0;
1437 	mutex_destroy(&sr->sr_mutex);
1438 	kmem_cache_free(smb_cache_request, sr);
1439 }
1440 
1441 boolean_t
smb_session_oplocks_enable(smb_session_t * session)1442 smb_session_oplocks_enable(smb_session_t *session)
1443 {
1444 	SMB_SESSION_VALID(session);
1445 	if (session->s_cfg.skc_oplock_enable == 0)
1446 		return (B_FALSE);
1447 	else
1448 		return (B_TRUE);
1449 }
1450 
1451 boolean_t
smb_session_levelII_oplocks(smb_session_t * session)1452 smb_session_levelII_oplocks(smb_session_t *session)
1453 {
1454 	SMB_SESSION_VALID(session);
1455 
1456 	/* Older clients only do Level II oplocks if negotiated. */
1457 	if ((session->capabilities & CAP_LEVEL_II_OPLOCKS) != 0)
1458 		return (B_TRUE);
1459 
1460 	return (B_FALSE);
1461 }
1462 
1463 static void
smb_session_genkey(smb_session_t * session)1464 smb_session_genkey(smb_session_t *session)
1465 {
1466 	uint8_t		tmp_key[SMB_CHALLENGE_SZ];
1467 
1468 	(void) random_get_pseudo_bytes(tmp_key, SMB_CHALLENGE_SZ);
1469 	bcopy(tmp_key, &session->challenge_key, SMB_CHALLENGE_SZ);
1470 	session->challenge_len = SMB_CHALLENGE_SZ;
1471 
1472 	(void) random_get_pseudo_bytes(tmp_key, 4);
1473 	session->sesskey = tmp_key[0] | tmp_key[1] << 8 |
1474 	    tmp_key[2] << 16 | tmp_key[3] << 24;
1475 }
1476