xref: /linux/fs/smb/client/sess.c (revision bb29b957eaaa15be33243550d9ee576c2d601669)
1 // SPDX-License-Identifier: LGPL-2.1
2 /*
3  *
4  *   SMB/CIFS session setup handling routines
5  *
6  *   Copyright (c) International Business Machines  Corp., 2006, 2009
7  *   Author(s): Steve French (sfrench@us.ibm.com)
8  *
9  */
10 
11 #include "cifsglob.h"
12 #include "cifsproto.h"
13 #include "cifs_unicode.h"
14 #include "cifs_debug.h"
15 #include "ntlmssp.h"
16 #include "nterr.h"
17 #include <linux/utsname.h>
18 #include <linux/slab.h>
19 #include <linux/version.h>
20 #include "cifsfs.h"
21 #include "cifs_spnego.h"
22 #include "smb2proto.h"
23 #include "fs_context.h"
24 
25 static int
26 cifs_ses_add_channel(struct cifs_ses *ses,
27 		     struct cifs_server_iface *iface);
28 
29 bool is_ses_using_iface(struct cifs_ses *ses, struct cifs_server_iface *iface)
30 {
31 	int i;
32 
33 	spin_lock(&ses->chan_lock);
34 	for (i = 0; i < ses->chan_count; i++) {
35 		if (ses->chans[i].iface == iface) {
36 			spin_unlock(&ses->chan_lock);
37 			return true;
38 		}
39 	}
40 	spin_unlock(&ses->chan_lock);
41 	return false;
42 }
43 
44 /* channel helper functions. assumed that chan_lock is held by caller. */
45 
46 int
47 cifs_ses_get_chan_index(struct cifs_ses *ses,
48 			struct TCP_Server_Info *server)
49 {
50 	unsigned int i;
51 
52 	/* if the channel is waiting for termination */
53 	if (server && server->terminate)
54 		return CIFS_INVAL_CHAN_INDEX;
55 
56 	for (i = 0; i < ses->chan_count; i++) {
57 		if (ses->chans[i].server == server)
58 			return i;
59 	}
60 
61 	/* If we didn't find the channel, it is likely a bug */
62 	if (server)
63 		cifs_dbg(VFS, "unable to get chan index for server: 0x%llx",
64 			 server->conn_id);
65 	return CIFS_INVAL_CHAN_INDEX;
66 }
67 
68 void
69 cifs_chan_set_in_reconnect(struct cifs_ses *ses,
70 			     struct TCP_Server_Info *server)
71 {
72 	int chan_index = cifs_ses_get_chan_index(ses, server);
73 
74 	if (chan_index == CIFS_INVAL_CHAN_INDEX)
75 		return;
76 
77 	ses->chans[chan_index].in_reconnect = true;
78 }
79 
80 void
81 cifs_chan_clear_in_reconnect(struct cifs_ses *ses,
82 			     struct TCP_Server_Info *server)
83 {
84 	unsigned int chan_index = cifs_ses_get_chan_index(ses, server);
85 
86 	if (chan_index == CIFS_INVAL_CHAN_INDEX)
87 		return;
88 
89 	ses->chans[chan_index].in_reconnect = false;
90 }
91 
92 void
93 cifs_chan_set_need_reconnect(struct cifs_ses *ses,
94 			     struct TCP_Server_Info *server)
95 {
96 	unsigned int chan_index = cifs_ses_get_chan_index(ses, server);
97 
98 	if (chan_index == CIFS_INVAL_CHAN_INDEX)
99 		return;
100 
101 	set_bit(chan_index, &ses->chans_need_reconnect);
102 	cifs_dbg(FYI, "Set reconnect bitmask for chan %u; now 0x%lx\n",
103 		 chan_index, ses->chans_need_reconnect);
104 }
105 
106 void
107 cifs_chan_clear_need_reconnect(struct cifs_ses *ses,
108 			       struct TCP_Server_Info *server)
109 {
110 	unsigned int chan_index = cifs_ses_get_chan_index(ses, server);
111 
112 	if (chan_index == CIFS_INVAL_CHAN_INDEX)
113 		return;
114 
115 	clear_bit(chan_index, &ses->chans_need_reconnect);
116 	cifs_dbg(FYI, "Cleared reconnect bitmask for chan %u; now 0x%lx\n",
117 		 chan_index, ses->chans_need_reconnect);
118 }
119 
120 bool
121 cifs_chan_needs_reconnect(struct cifs_ses *ses,
122 			  struct TCP_Server_Info *server)
123 {
124 	unsigned int chan_index = cifs_ses_get_chan_index(ses, server);
125 
126 	if (chan_index == CIFS_INVAL_CHAN_INDEX)
127 		return true;	/* err on the safer side */
128 
129 	return CIFS_CHAN_NEEDS_RECONNECT(ses, chan_index);
130 }
131 
132 bool
133 cifs_chan_is_iface_active(struct cifs_ses *ses,
134 			  struct TCP_Server_Info *server)
135 {
136 	unsigned int chan_index = cifs_ses_get_chan_index(ses, server);
137 
138 	if (chan_index == CIFS_INVAL_CHAN_INDEX)
139 		return true;	/* err on the safer side */
140 
141 	return ses->chans[chan_index].iface &&
142 		ses->chans[chan_index].iface->is_active;
143 }
144 
145 /* returns number of channels added */
146 int cifs_try_adding_channels(struct cifs_ses *ses)
147 {
148 	struct TCP_Server_Info *server = ses->server;
149 	int old_chan_count, new_chan_count;
150 	int left;
151 	int rc = 0;
152 	int tries = 0, attempts;
153 	size_t iface_weight = 0, iface_min_speed = 0;
154 	struct cifs_server_iface *iface = NULL, *candidate = NULL;
155 	struct cifs_server_iface *last_iface = NULL;
156 
157 	spin_lock(&ses->chan_lock);
158 
159 	new_chan_count = old_chan_count = ses->chan_count;
160 	left = ses->chan_max - ses->chan_count;
161 
162 	if (left <= 0) {
163 		spin_unlock(&ses->chan_lock);
164 		cifs_dbg(FYI,
165 			 "ses already at max_channels (%zu), nothing to open\n",
166 			 ses->chan_max);
167 		return 0;
168 	}
169 
170 	if (server->dialect < SMB30_PROT_ID) {
171 		spin_unlock(&ses->chan_lock);
172 		cifs_dbg(VFS, "multichannel is not supported on this protocol version, use 3.0 or above\n");
173 		return 0;
174 	}
175 
176 	if (!(server->capabilities & SMB2_GLOBAL_CAP_MULTI_CHANNEL)) {
177 		spin_unlock(&ses->chan_lock);
178 		cifs_server_dbg(VFS, "no multichannel support\n");
179 		return 0;
180 	}
181 	spin_unlock(&ses->chan_lock);
182 
183 	while (left > 0) {
184 
185 		tries++;
186 		if (tries > 3*ses->chan_max) {
187 			cifs_dbg(VFS, "too many channel open attempts (%d channels left to open)\n",
188 				 left);
189 			break;
190 		}
191 
192 		spin_lock(&ses->iface_lock);
193 		if (!ses->iface_count) {
194 			spin_unlock(&ses->iface_lock);
195 			cifs_dbg(ONCE, "server %s does not advertise interfaces\n",
196 				      ses->server->hostname);
197 			break;
198 		}
199 
200 		last_iface = list_last_entry(&ses->iface_list, struct cifs_server_iface,
201 					     iface_head);
202 		iface_min_speed = last_iface->speed;
203 		spin_unlock(&ses->iface_lock);
204 
205 		attempts = 0;
206 		while (left > 0) {
207 			spin_lock(&ses->iface_lock);
208 
209 			/*
210 			 * iface_lock must be dropped while opening a channel,
211 			 * and a concurrent interface refresh may remove and
212 			 * free entries during that window, so no list entry
213 			 * may be kept across it without a reference.  Scan
214 			 * the list from the beginning each time and only pass
215 			 * a referenced candidate to cifs_ses_add_channel();
216 			 * weight_fulfilled tracks the progress so that no
217 			 * iface is selected beyond its weight.
218 			 */
219 			candidate = NULL;
220 			list_for_each_entry(iface, &ses->iface_list, iface_head) {
221 				/* do not mix rdma and non-rdma interfaces */
222 				if (iface->rdma_capable != ses->server->rdma)
223 					continue;
224 
225 				/* skip ifaces that are unusable */
226 				if (!iface->is_active ||
227 				    (is_ses_using_iface(ses, iface) &&
228 				     !iface->rss_capable))
229 					continue;
230 
231 				/* check if we already allocated enough channels */
232 				iface_weight = iface->speed / iface_min_speed;
233 
234 				if (iface->weight_fulfilled >= iface_weight)
235 					continue;
236 
237 				/* take ref before unlock */
238 				kref_get(&iface->refcount);
239 				candidate = iface;
240 				break;
241 			}
242 
243 			if (!candidate) {
244 				/* no usable iface. reset weight_fulfilled and start over */
245 				list_for_each_entry(iface, &ses->iface_list, iface_head)
246 					iface->weight_fulfilled = 0;
247 				spin_unlock(&ses->iface_lock);
248 				break;
249 			}
250 
251 			attempts++;
252 			if (attempts > 3 * ses->chan_max) {
253 				kref_put(&candidate->refcount, release_iface);
254 				spin_unlock(&ses->iface_lock);
255 				break;
256 			}
257 
258 			spin_unlock(&ses->iface_lock);
259 			rc = cifs_ses_add_channel(ses, candidate);
260 			spin_lock(&ses->iface_lock);
261 
262 			if (rc) {
263 				cifs_dbg(VFS, "failed to open extra channel on iface:%pIS rc=%d\n",
264 					 &candidate->sockaddr,
265 					 rc);
266 				/* failure to add chan should increase weight */
267 				candidate->weight_fulfilled++;
268 				kref_put(&candidate->refcount, release_iface);
269 				spin_unlock(&ses->iface_lock);
270 				continue;
271 			}
272 
273 			candidate->num_channels++;
274 			candidate->weight_fulfilled++;
275 			cifs_info("successfully opened new channel on iface:%pIS\n",
276 				 &candidate->sockaddr);
277 			spin_unlock(&ses->iface_lock);
278 
279 			left--;
280 			new_chan_count++;
281 			break;
282 		}
283 	}
284 
285 	return new_chan_count - old_chan_count;
286 }
287 
288 /*
289  * cifs_decrease_secondary_channels - Reduce the number of active secondary channels
290  * @ses: pointer to the CIFS session structure
291  * @disable_mchan: if true, reduce to a single channel; if false, reduce to chan_max
292  *
293  * This function disables and cleans up extra secondary channels for a CIFS session.
294  * If called during reconfiguration, it reduces the channel count to the new maximum (chan_max).
295  * Otherwise, it disables all but the primary channel.
296  */
297 void
298 cifs_decrease_secondary_channels(struct cifs_ses *ses, bool disable_mchan)
299 {
300 	int i, chan_count;
301 	struct TCP_Server_Info *server;
302 	struct cifs_server_iface *iface;
303 
304 	spin_lock(&ses->chan_lock);
305 	chan_count = ses->chan_count;
306 	if (chan_count == 1)
307 		goto done;
308 
309 	/* Update the chan_count to the new maximum */
310 	if (disable_mchan) {
311 		cifs_dbg(FYI, "server does not support multichannel anymore.\n");
312 		ses->chan_count = 1;
313 	} else {
314 		ses->chan_count = ses->chan_max;
315 	}
316 
317 	/* Disable all secondary channels beyond the new chan_count */
318 	for (i = ses->chan_count ; i < chan_count; i++) {
319 		iface = ses->chans[i].iface;
320 		server = ses->chans[i].server;
321 
322 		/*
323 		 * remove these references first, since we need to unlock
324 		 * the chan_lock here, since iface_lock is a higher lock
325 		 */
326 		ses->chans[i].iface = NULL;
327 		ses->chans[i].server = NULL;
328 		spin_unlock(&ses->chan_lock);
329 
330 		if (iface) {
331 			spin_lock(&ses->iface_lock);
332 			iface->num_channels--;
333 			if (iface->weight_fulfilled)
334 				iface->weight_fulfilled--;
335 			kref_put(&iface->refcount, release_iface);
336 			spin_unlock(&ses->iface_lock);
337 		}
338 
339 		if (server) {
340 			if (!server->terminate) {
341 				server->terminate = true;
342 				cifs_signal_cifsd_for_reconnect(server, false);
343 			}
344 			cifs_put_tcp_session(server, false);
345 		}
346 
347 		spin_lock(&ses->chan_lock);
348 	}
349 
350 	/* For extra secondary channels, reset the need reconnect bit */
351 	if (ses->chan_count == 1) {
352 		cifs_dbg(VFS, "Disable all secondary channels\n");
353 		ses->chans_need_reconnect &= 1;
354 	} else {
355 		cifs_dbg(VFS, "Disable extra secondary channels\n");
356 		ses->chans_need_reconnect &= ((1UL << ses->chan_max) - 1);
357 	}
358 
359 done:
360 	spin_unlock(&ses->chan_lock);
361 }
362 
363 /* update the iface for the channel if necessary. */
364 void
365 cifs_chan_update_iface(struct cifs_ses *ses, struct TCP_Server_Info *server)
366 {
367 	unsigned int chan_index;
368 	size_t iface_weight = 0, iface_min_speed = 0;
369 	struct cifs_server_iface *iface = NULL;
370 	struct cifs_server_iface *old_iface = NULL;
371 	struct cifs_server_iface *last_iface = NULL;
372 	struct sockaddr_storage ss;
373 	int retry = 0;
374 
375 	spin_lock(&ses->chan_lock);
376 	chan_index = cifs_ses_get_chan_index(ses, server);
377 	if (chan_index == CIFS_INVAL_CHAN_INDEX) {
378 		spin_unlock(&ses->chan_lock);
379 		return;
380 	}
381 
382 	if (ses->chans[chan_index].iface) {
383 		old_iface = ses->chans[chan_index].iface;
384 		if (old_iface->is_active) {
385 			spin_unlock(&ses->chan_lock);
386 			return;
387 		}
388 	}
389 	spin_unlock(&ses->chan_lock);
390 
391 	spin_lock(&server->srv_lock);
392 	ss = server->dstaddr;
393 	spin_unlock(&server->srv_lock);
394 
395 	spin_lock(&ses->iface_lock);
396 	if (!ses->iface_count) {
397 		spin_unlock(&ses->iface_lock);
398 		cifs_dbg(ONCE, "server %s does not advertise interfaces\n", ses->server->hostname);
399 		return;
400 	}
401 
402 try_again:
403 	last_iface = list_last_entry(&ses->iface_list, struct cifs_server_iface,
404 				     iface_head);
405 	iface_min_speed = last_iface->speed;
406 
407 	/* then look for a new one */
408 	list_for_each_entry(iface, &ses->iface_list, iface_head) {
409 		if (!chan_index) {
410 			/* if we're trying to get the updated iface for primary channel */
411 			if (!cifs_match_ipaddr((struct sockaddr *) &ss,
412 					       (struct sockaddr *) &iface->sockaddr))
413 				continue;
414 
415 			kref_get(&iface->refcount);
416 			break;
417 		}
418 
419 		/* do not mix rdma and non-rdma interfaces */
420 		if (iface->rdma_capable != server->rdma)
421 			continue;
422 
423 		if (!iface->is_active ||
424 		    (is_ses_using_iface(ses, iface) &&
425 		     !iface->rss_capable)) {
426 			continue;
427 		}
428 
429 		/* check if we already allocated enough channels */
430 		iface_weight = iface->speed / iface_min_speed;
431 
432 		if (iface->weight_fulfilled >= iface_weight)
433 			continue;
434 
435 		kref_get(&iface->refcount);
436 		break;
437 	}
438 
439 	if (list_entry_is_head(iface, &ses->iface_list, iface_head)) {
440 		list_for_each_entry(iface, &ses->iface_list, iface_head)
441 			iface->weight_fulfilled = 0;
442 
443 		/* see if it can be satisfied in second attempt */
444 		if (!retry++)
445 			goto try_again;
446 
447 		iface = NULL;
448 		cifs_dbg(FYI, "unable to find a suitable iface\n");
449 	}
450 
451 	if (!iface) {
452 		if (!chan_index)
453 			cifs_dbg(FYI, "unable to get the interface matching: %pIS\n",
454 				 &ss);
455 		else {
456 			cifs_dbg(FYI, "unable to find another interface to replace: %pIS\n",
457 				 &old_iface->sockaddr);
458 		}
459 
460 		spin_unlock(&ses->iface_lock);
461 		return;
462 	}
463 
464 	/* now drop the ref to the current iface */
465 	if (old_iface) {
466 		cifs_dbg(FYI, "replacing iface: %pIS with %pIS\n",
467 			 &old_iface->sockaddr,
468 			 &iface->sockaddr);
469 
470 		old_iface->num_channels--;
471 		if (old_iface->weight_fulfilled)
472 			old_iface->weight_fulfilled--;
473 		iface->num_channels++;
474 		iface->weight_fulfilled++;
475 
476 		kref_put(&old_iface->refcount, release_iface);
477 	} else if (!chan_index) {
478 		/* special case: update interface for primary channel */
479 		cifs_dbg(FYI, "referencing primary channel iface: %pIS\n",
480 			 &iface->sockaddr);
481 		iface->num_channels++;
482 		iface->weight_fulfilled++;
483 	}
484 	spin_unlock(&ses->iface_lock);
485 
486 	spin_lock(&ses->chan_lock);
487 	chan_index = cifs_ses_get_chan_index(ses, server);
488 	if (chan_index == CIFS_INVAL_CHAN_INDEX) {
489 		spin_unlock(&ses->chan_lock);
490 		return;
491 	}
492 
493 	ses->chans[chan_index].iface = iface;
494 	spin_unlock(&ses->chan_lock);
495 
496 	spin_lock(&server->srv_lock);
497 	memcpy(&server->dstaddr, &iface->sockaddr, sizeof(server->dstaddr));
498 	spin_unlock(&server->srv_lock);
499 }
500 
501 static int
502 cifs_ses_add_channel(struct cifs_ses *ses,
503 		     struct cifs_server_iface *iface)
504 {
505 	struct TCP_Server_Info *chan_server;
506 	struct cifs_chan *chan;
507 	struct smb3_fs_context *ctx;
508 	static const char unc_fmt[] = "\\%s\\foo";
509 	struct sockaddr_in *ipv4 = (struct sockaddr_in *)&iface->sockaddr;
510 	struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)&iface->sockaddr;
511 	size_t len;
512 	int rc;
513 	unsigned int xid = get_xid();
514 
515 	if (iface->sockaddr.ss_family == AF_INET)
516 		cifs_dbg(FYI, "adding channel to ses %p (speed:%zu bps rdma:%s ip:%pI4)\n",
517 			 ses, iface->speed, str_yes_no(iface->rdma_capable),
518 			 &ipv4->sin_addr);
519 	else
520 		cifs_dbg(FYI, "adding channel to ses %p (speed:%zu bps rdma:%s ip:%pI6)\n",
521 			 ses, iface->speed, str_yes_no(iface->rdma_capable),
522 			 &ipv6->sin6_addr);
523 
524 	/*
525 	 * Setup a ctx with mostly the same info as the existing
526 	 * session and overwrite it with the requested iface data.
527 	 *
528 	 * We need to setup at least the fields used for negprot and
529 	 * sesssetup.
530 	 *
531 	 * We only need the ctx here, so we can reuse memory from
532 	 * the session and server without caring about memory
533 	 * management.
534 	 */
535 	ctx = kzalloc_obj(*ctx);
536 	if (!ctx) {
537 		rc = -ENOMEM;
538 		goto out_free_xid;
539 	}
540 
541 	/* Always make new connection for now (TODO?) */
542 	ctx->nosharesock = true;
543 
544 	/* Auth */
545 	ctx->domainauto = ses->domainAuto;
546 	ctx->domainname = ses->domainName;
547 
548 	ctx->server_hostname = ses->server->hostname;
549 
550 	ctx->username = ses->user_name;
551 	ctx->password = ses->password;
552 	ctx->sectype = ses->sectype;
553 	ctx->sign = ses->sign;
554 	ctx->unicode = ses->unicode;
555 
556 	/* UNC and paths */
557 	/* XXX: Use ses->server->hostname? */
558 	len = sizeof(unc_fmt) + SERVER_NAME_LEN_WITH_NULL;
559 	ctx->UNC = kzalloc(len, GFP_KERNEL);
560 	if (!ctx->UNC) {
561 		rc = -ENOMEM;
562 		goto out_free_ctx;
563 	}
564 	scnprintf(ctx->UNC, len, unc_fmt, ses->ip_addr);
565 	ctx->prepath = "";
566 
567 	/* Reuse same version as master connection */
568 	ctx->vals = ses->server->vals;
569 	ctx->ops = ses->server->ops;
570 
571 	ctx->noblocksnd = ses->server->noblocksnd;
572 	ctx->noautotune = ses->server->noautotune;
573 	ctx->sockopt_tcp_nodelay = ses->server->tcp_nodelay;
574 	ctx->echo_interval = ses->server->echo_interval / HZ;
575 	ctx->max_credits = ses->server->max_credits;
576 	ctx->min_offload = ses->server->min_offload;
577 	ctx->compress = ses->server->compression.requested;
578 	ctx->dfs_conn = ses->server->dfs_conn;
579 	ctx->ignore_signature = ses->server->ignore_signature;
580 	ctx->leaf_fullpath = ses->server->leaf_fullpath;
581 	ctx->rootfs = ses->server->noblockcnt;
582 	ctx->retrans = ses->server->retrans;
583 
584 	/*
585 	 * This will be used for encoding/decoding user/domain/pw
586 	 * during sess setup auth.
587 	 */
588 	ctx->local_nls = ses->local_nls;
589 
590 	/* Use RDMA if possible */
591 	ctx->rdma = iface->rdma_capable;
592 	memcpy(&ctx->dstaddr, &iface->sockaddr, sizeof(ctx->dstaddr));
593 
594 	/* reuse master con client guid */
595 	memcpy(&ctx->client_guid, ses->server->client_guid,
596 	       sizeof(ctx->client_guid));
597 	ctx->use_client_guid = true;
598 
599 	chan_server = cifs_get_tcp_session(ctx, ses->server);
600 
601 	spin_lock(&ses->chan_lock);
602 	chan = &ses->chans[ses->chan_count];
603 	chan->server = chan_server;
604 	if (IS_ERR(chan->server)) {
605 		rc = PTR_ERR(chan->server);
606 		chan->server = NULL;
607 		spin_unlock(&ses->chan_lock);
608 		goto out;
609 	}
610 	chan->iface = iface;
611 	ses->chan_count++;
612 	atomic_set(&ses->chan_seq, 0);
613 
614 	/* Mark this channel as needing connect/setup */
615 	cifs_chan_set_need_reconnect(ses, chan->server);
616 
617 	spin_unlock(&ses->chan_lock);
618 
619 	mutex_lock(&ses->session_mutex);
620 
621 	rc = cifs_negotiate_protocol(xid, ses, chan->server);
622 	if (!rc)
623 		rc = cifs_setup_session(xid, ses, chan->server);
624 
625 	mutex_unlock(&ses->session_mutex);
626 
627 out:
628 	if (rc && chan->server) {
629 		struct TCP_Server_Info *pserver;
630 
631 		spin_lock(&ses->chan_lock);
632 		pserver = chan->server;
633 
634 		/* we rely on all bits beyond chan_count to be clear */
635 		cifs_chan_clear_need_reconnect(ses, pserver);
636 		ses->chan_count--;
637 		/*
638 		 * chan_count should never reach 0 as at least the primary
639 		 * channel is always allocated
640 		 */
641 		WARN_ON(ses->chan_count < 1);
642 		spin_unlock(&ses->chan_lock);
643 		cifs_put_tcp_session(pserver, 0);
644 	}
645 
646 	kfree(ctx->UNC);
647 out_free_ctx:
648 	kfree(ctx);
649 out_free_xid:
650 	free_xid(xid);
651 	return rc;
652 }
653 
654 
655 int decode_ntlmssp_challenge(char *bcc_ptr, int blob_len,
656 				    struct cifs_ses *ses)
657 {
658 	unsigned int tioffset; /* challenge message target info area */
659 	unsigned int tilen; /* challenge message target info area length  */
660 	CHALLENGE_MESSAGE *pblob = (CHALLENGE_MESSAGE *)bcc_ptr;
661 	__u32 server_flags;
662 
663 	if (blob_len < sizeof(CHALLENGE_MESSAGE)) {
664 		cifs_dbg(VFS, "challenge blob len %d too small\n", blob_len);
665 		return -EINVAL;
666 	}
667 
668 	if (memcmp(pblob->Signature, "NTLMSSP", 8)) {
669 		cifs_dbg(VFS, "blob signature incorrect %s\n",
670 			 pblob->Signature);
671 		return -EINVAL;
672 	}
673 	if (pblob->MessageType != NtLmChallenge) {
674 		cifs_dbg(VFS, "Incorrect message type %d\n",
675 			 pblob->MessageType);
676 		return -EINVAL;
677 	}
678 
679 	server_flags = le32_to_cpu(pblob->NegotiateFlags);
680 	cifs_dbg(FYI, "%s: negotiate=0x%08x challenge=0x%08x\n", __func__,
681 		 ses->ntlmssp->client_flags, server_flags);
682 
683 	if ((ses->ntlmssp->client_flags & (NTLMSSP_NEGOTIATE_SEAL | NTLMSSP_NEGOTIATE_SIGN)) &&
684 	    (!(server_flags & NTLMSSP_NEGOTIATE_56) && !(server_flags & NTLMSSP_NEGOTIATE_128))) {
685 		cifs_dbg(VFS, "%s: requested signing/encryption but server did not return either 56-bit or 128-bit session key size\n",
686 			 __func__);
687 		return -EINVAL;
688 	}
689 	if (!(server_flags & NTLMSSP_NEGOTIATE_NTLM) && !(server_flags & NTLMSSP_NEGOTIATE_EXTENDED_SEC)) {
690 		cifs_dbg(VFS, "%s: server does not seem to support either NTLMv1 or NTLMv2\n", __func__);
691 		return -EINVAL;
692 	}
693 	if (ses->server->sign && !(server_flags & NTLMSSP_NEGOTIATE_SIGN)) {
694 		cifs_dbg(VFS, "%s: forced packet signing but server does not seem to support it\n",
695 			 __func__);
696 		return -EOPNOTSUPP;
697 	}
698 	if ((ses->ntlmssp->client_flags & NTLMSSP_NEGOTIATE_KEY_XCH) &&
699 	    !(server_flags & NTLMSSP_NEGOTIATE_KEY_XCH))
700 		pr_warn_once("%s: authentication has been weakened as server does not support key exchange\n",
701 			     __func__);
702 
703 	ses->ntlmssp->server_flags = server_flags;
704 
705 	memcpy(ses->ntlmssp->cryptkey, pblob->Challenge, CIFS_CRYPTO_KEY_SIZE);
706 	/*
707 	 * In particular we can examine sign flags
708 	 *
709 	 * BB spec says that if AvId field of MsvAvTimestamp is populated then
710 	 * we must set the MIC field of the AUTHENTICATE_MESSAGE
711 	 */
712 
713 	tioffset = le32_to_cpu(pblob->TargetInfoArray.BufferOffset);
714 	tilen = le16_to_cpu(pblob->TargetInfoArray.Length);
715 	if (tioffset > blob_len || tioffset + tilen > blob_len) {
716 		cifs_dbg(VFS, "tioffset + tilen too high %u + %u\n",
717 			 tioffset, tilen);
718 		return -EINVAL;
719 	}
720 	if (tilen) {
721 		kfree_sensitive(ses->auth_key.response);
722 		ses->auth_key.response = kmemdup(bcc_ptr + tioffset, tilen,
723 						 GFP_KERNEL);
724 		if (!ses->auth_key.response) {
725 			cifs_dbg(VFS, "Challenge target info alloc failure\n");
726 			return -ENOMEM;
727 		}
728 		ses->auth_key.len = tilen;
729 	}
730 
731 	return 0;
732 }
733 
734 static int size_of_ntlmssp_blob(struct cifs_ses *ses, int base_size)
735 {
736 	int sz = base_size + ses->auth_key.len
737 		- CIFS_SESS_KEY_SIZE + CIFS_CPHTXT_SIZE + 2;
738 
739 	if (ses->domainName)
740 		sz += sizeof(__le16) * strnlen(ses->domainName, CIFS_MAX_DOMAINNAME_LEN);
741 	else
742 		sz += sizeof(__le16);
743 
744 	if (ses->user_name)
745 		sz += sizeof(__le16) * strnlen(ses->user_name, CIFS_MAX_USERNAME_LEN);
746 	else
747 		sz += sizeof(__le16);
748 
749 	if (ses->workstation_name[0])
750 		sz += sizeof(__le16) * strnlen(ses->workstation_name,
751 					       ntlmssp_workstation_name_size(ses));
752 	else
753 		sz += sizeof(__le16);
754 
755 	return sz;
756 }
757 
758 static inline void cifs_security_buffer_from_str(SECURITY_BUFFER *pbuf,
759 						 char *str_value,
760 						 int str_length,
761 						 unsigned char *pstart,
762 						 unsigned char **pcur,
763 						 const struct nls_table *nls_cp)
764 {
765 	unsigned char *tmp = pstart;
766 	int len;
767 
768 	if (!pbuf)
769 		return;
770 
771 	if (!pcur)
772 		pcur = &tmp;
773 
774 	if (!str_value) {
775 		pbuf->BufferOffset = cpu_to_le32(*pcur - pstart);
776 		pbuf->Length = 0;
777 		pbuf->MaximumLength = 0;
778 		*pcur += sizeof(__le16);
779 	} else {
780 		len = cifs_strtoUTF16((__le16 *)*pcur,
781 				      str_value,
782 				      str_length,
783 				      nls_cp);
784 		len *= sizeof(__le16);
785 		pbuf->BufferOffset = cpu_to_le32(*pcur - pstart);
786 		pbuf->Length = cpu_to_le16(len);
787 		pbuf->MaximumLength = cpu_to_le16(len);
788 		*pcur += len;
789 	}
790 }
791 
792 /* BB Move to ntlmssp.c eventually */
793 
794 int build_ntlmssp_negotiate_blob(unsigned char **pbuffer,
795 				 u16 *buflen,
796 				 struct cifs_ses *ses,
797 				 struct TCP_Server_Info *server)
798 {
799 	int rc = 0;
800 	NEGOTIATE_MESSAGE *sec_blob;
801 	__u32 flags;
802 	unsigned char *tmp;
803 	int len;
804 
805 	len = size_of_ntlmssp_blob(ses, sizeof(NEGOTIATE_MESSAGE));
806 	*pbuffer = kmalloc(len, GFP_KERNEL);
807 	if (!*pbuffer) {
808 		rc = -ENOMEM;
809 		cifs_dbg(VFS, "Error %d during NTLMSSP allocation\n", rc);
810 		*buflen = 0;
811 		goto setup_ntlm_neg_ret;
812 	}
813 	sec_blob = (NEGOTIATE_MESSAGE *)*pbuffer;
814 
815 	memset(*pbuffer, 0, sizeof(NEGOTIATE_MESSAGE));
816 	memcpy(sec_blob->Signature, NTLMSSP_SIGNATURE, 8);
817 	sec_blob->MessageType = NtLmNegotiate;
818 
819 	/* BB is NTLMV2 session security format easier to use here? */
820 	flags = NTLMSSP_NEGOTIATE_56 |	NTLMSSP_REQUEST_TARGET |
821 		NTLMSSP_NEGOTIATE_128 | NTLMSSP_NEGOTIATE_UNICODE |
822 		NTLMSSP_NEGOTIATE_NTLM | NTLMSSP_NEGOTIATE_EXTENDED_SEC |
823 		NTLMSSP_NEGOTIATE_ALWAYS_SIGN | NTLMSSP_NEGOTIATE_SEAL |
824 		NTLMSSP_NEGOTIATE_SIGN;
825 	if (!server->session_estab || ses->ntlmssp->sesskey_per_smbsess)
826 		flags |= NTLMSSP_NEGOTIATE_KEY_XCH;
827 
828 	tmp = *pbuffer + sizeof(NEGOTIATE_MESSAGE);
829 	ses->ntlmssp->client_flags = flags;
830 	sec_blob->NegotiateFlags = cpu_to_le32(flags);
831 
832 	/* these fields should be null in negotiate phase MS-NLMP 3.1.5.1.1 */
833 	cifs_security_buffer_from_str(&sec_blob->DomainName,
834 				      NULL,
835 				      CIFS_MAX_DOMAINNAME_LEN,
836 				      *pbuffer, &tmp,
837 				      ses->local_nls);
838 
839 	cifs_security_buffer_from_str(&sec_blob->WorkstationName,
840 				      NULL,
841 				      CIFS_MAX_WORKSTATION_LEN,
842 				      *pbuffer, &tmp,
843 				      ses->local_nls);
844 
845 	*buflen = tmp - *pbuffer;
846 setup_ntlm_neg_ret:
847 	return rc;
848 }
849 
850 /*
851  * Build ntlmssp blob with additional fields, such as version,
852  * supported by modern servers. For safety limit to SMB3 or later
853  * See notes in MS-NLMP Section 2.2.2.1 e.g.
854  */
855 int build_ntlmssp_smb3_negotiate_blob(unsigned char **pbuffer,
856 				 u16 *buflen,
857 				 struct cifs_ses *ses,
858 				 struct TCP_Server_Info *server)
859 {
860 	int rc = 0;
861 	struct negotiate_message *sec_blob;
862 	__u32 flags;
863 	unsigned char *tmp;
864 	int len;
865 
866 	len = size_of_ntlmssp_blob(ses, sizeof(struct negotiate_message));
867 	*pbuffer = kmalloc(len, GFP_KERNEL);
868 	if (!*pbuffer) {
869 		rc = -ENOMEM;
870 		cifs_dbg(VFS, "Error %d during NTLMSSP allocation\n", rc);
871 		*buflen = 0;
872 		goto setup_ntlm_smb3_neg_ret;
873 	}
874 	sec_blob = (struct negotiate_message *)*pbuffer;
875 
876 	memset(*pbuffer, 0, sizeof(struct negotiate_message));
877 	memcpy(sec_blob->Signature, NTLMSSP_SIGNATURE, 8);
878 	sec_blob->MessageType = NtLmNegotiate;
879 
880 	/* BB is NTLMV2 session security format easier to use here? */
881 	flags = NTLMSSP_NEGOTIATE_56 |	NTLMSSP_REQUEST_TARGET |
882 		NTLMSSP_NEGOTIATE_128 | NTLMSSP_NEGOTIATE_UNICODE |
883 		NTLMSSP_NEGOTIATE_NTLM | NTLMSSP_NEGOTIATE_EXTENDED_SEC |
884 		NTLMSSP_NEGOTIATE_ALWAYS_SIGN | NTLMSSP_NEGOTIATE_SEAL |
885 		NTLMSSP_NEGOTIATE_SIGN | NTLMSSP_NEGOTIATE_VERSION;
886 	if (!server->session_estab || ses->ntlmssp->sesskey_per_smbsess)
887 		flags |= NTLMSSP_NEGOTIATE_KEY_XCH;
888 
889 	sec_blob->Version.ProductMajorVersion = LINUX_VERSION_MAJOR;
890 	sec_blob->Version.ProductMinorVersion = LINUX_VERSION_PATCHLEVEL;
891 	sec_blob->Version.ProductBuild = cpu_to_le16(LINUX_VERSION_SUBLEVEL);
892 	sec_blob->Version.NTLMRevisionCurrent = NTLMSSP_REVISION_W2K3;
893 
894 	tmp = *pbuffer + sizeof(struct negotiate_message);
895 	ses->ntlmssp->client_flags = flags;
896 	sec_blob->NegotiateFlags = cpu_to_le32(flags);
897 
898 	/* these fields should be null in negotiate phase MS-NLMP 3.1.5.1.1 */
899 	cifs_security_buffer_from_str(&sec_blob->DomainName,
900 				      NULL,
901 				      CIFS_MAX_DOMAINNAME_LEN,
902 				      *pbuffer, &tmp,
903 				      ses->local_nls);
904 
905 	cifs_security_buffer_from_str(&sec_blob->WorkstationName,
906 				      NULL,
907 				      CIFS_MAX_WORKSTATION_LEN,
908 				      *pbuffer, &tmp,
909 				      ses->local_nls);
910 
911 	*buflen = tmp - *pbuffer;
912 setup_ntlm_smb3_neg_ret:
913 	return rc;
914 }
915 
916 
917 /* See MS-NLMP 2.2.1.3 */
918 int build_ntlmssp_auth_blob(unsigned char **pbuffer,
919 					u16 *buflen,
920 				   struct cifs_ses *ses,
921 				   struct TCP_Server_Info *server)
922 {
923 	int rc;
924 	AUTHENTICATE_MESSAGE *sec_blob;
925 	__u32 flags;
926 	unsigned char *tmp;
927 	int len;
928 
929 	rc = setup_ntlmv2_rsp(ses);
930 	if (rc) {
931 		cifs_dbg(VFS, "Error %d during NTLMSSP authentication\n", rc);
932 		*buflen = 0;
933 		goto setup_ntlmv2_ret;
934 	}
935 
936 	len = size_of_ntlmssp_blob(ses, sizeof(AUTHENTICATE_MESSAGE));
937 	*pbuffer = kmalloc(len, GFP_KERNEL);
938 	if (!*pbuffer) {
939 		rc = -ENOMEM;
940 		cifs_dbg(VFS, "Error %d during NTLMSSP allocation\n", rc);
941 		*buflen = 0;
942 		goto setup_ntlmv2_ret;
943 	}
944 	sec_blob = (AUTHENTICATE_MESSAGE *)*pbuffer;
945 
946 	memcpy(sec_blob->Signature, NTLMSSP_SIGNATURE, 8);
947 	sec_blob->MessageType = NtLmAuthenticate;
948 
949 	/* send version information in ntlmssp authenticate also */
950 	flags = ses->ntlmssp->server_flags | NTLMSSP_REQUEST_TARGET |
951 		NTLMSSP_NEGOTIATE_TARGET_INFO | NTLMSSP_NEGOTIATE_VERSION |
952 		NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED;
953 
954 	sec_blob->Version.ProductMajorVersion = LINUX_VERSION_MAJOR;
955 	sec_blob->Version.ProductMinorVersion = LINUX_VERSION_PATCHLEVEL;
956 	sec_blob->Version.ProductBuild = cpu_to_le16(LINUX_VERSION_SUBLEVEL);
957 	sec_blob->Version.NTLMRevisionCurrent = NTLMSSP_REVISION_W2K3;
958 
959 	tmp = *pbuffer + sizeof(AUTHENTICATE_MESSAGE);
960 	sec_blob->NegotiateFlags = cpu_to_le32(flags);
961 
962 	sec_blob->LmChallengeResponse.BufferOffset =
963 				cpu_to_le32(sizeof(AUTHENTICATE_MESSAGE));
964 	sec_blob->LmChallengeResponse.Length = 0;
965 	sec_blob->LmChallengeResponse.MaximumLength = 0;
966 
967 	sec_blob->NtChallengeResponse.BufferOffset =
968 				cpu_to_le32(tmp - *pbuffer);
969 	if (ses->user_name != NULL) {
970 		memcpy(tmp, ses->auth_key.response + CIFS_SESS_KEY_SIZE,
971 				ses->auth_key.len - CIFS_SESS_KEY_SIZE);
972 		tmp += ses->auth_key.len - CIFS_SESS_KEY_SIZE;
973 
974 		sec_blob->NtChallengeResponse.Length =
975 				cpu_to_le16(ses->auth_key.len - CIFS_SESS_KEY_SIZE);
976 		sec_blob->NtChallengeResponse.MaximumLength =
977 				cpu_to_le16(ses->auth_key.len - CIFS_SESS_KEY_SIZE);
978 	} else {
979 		/*
980 		 * don't send an NT Response for anonymous access
981 		 */
982 		sec_blob->NtChallengeResponse.Length = 0;
983 		sec_blob->NtChallengeResponse.MaximumLength = 0;
984 	}
985 
986 	cifs_security_buffer_from_str(&sec_blob->DomainName,
987 				      ses->domainName,
988 				      CIFS_MAX_DOMAINNAME_LEN,
989 				      *pbuffer, &tmp,
990 				      ses->local_nls);
991 
992 	cifs_security_buffer_from_str(&sec_blob->UserName,
993 				      ses->user_name,
994 				      CIFS_MAX_USERNAME_LEN,
995 				      *pbuffer, &tmp,
996 				      ses->local_nls);
997 
998 	cifs_security_buffer_from_str(&sec_blob->WorkstationName,
999 				      ses->workstation_name,
1000 				      ntlmssp_workstation_name_size(ses),
1001 				      *pbuffer, &tmp,
1002 				      ses->local_nls);
1003 
1004 	if ((ses->ntlmssp->server_flags & NTLMSSP_NEGOTIATE_KEY_XCH) &&
1005 	    (!ses->server->session_estab || ses->ntlmssp->sesskey_per_smbsess) &&
1006 	    !calc_seckey(ses)) {
1007 		memcpy(tmp, ses->ntlmssp->ciphertext, CIFS_CPHTXT_SIZE);
1008 		sec_blob->SessionKey.BufferOffset = cpu_to_le32(tmp - *pbuffer);
1009 		sec_blob->SessionKey.Length = cpu_to_le16(CIFS_CPHTXT_SIZE);
1010 		sec_blob->SessionKey.MaximumLength =
1011 				cpu_to_le16(CIFS_CPHTXT_SIZE);
1012 		tmp += CIFS_CPHTXT_SIZE;
1013 	} else {
1014 		sec_blob->SessionKey.BufferOffset = cpu_to_le32(tmp - *pbuffer);
1015 		sec_blob->SessionKey.Length = 0;
1016 		sec_blob->SessionKey.MaximumLength = 0;
1017 	}
1018 
1019 	*buflen = tmp - *pbuffer;
1020 setup_ntlmv2_ret:
1021 	return rc;
1022 }
1023 
1024 enum securityEnum
1025 cifs_select_sectype(struct TCP_Server_Info *server, enum securityEnum requested)
1026 {
1027 	switch (server->negflavor) {
1028 	case CIFS_NEGFLAVOR_EXTENDED:
1029 		switch (requested) {
1030 		case Kerberos:
1031 		case RawNTLMSSP:
1032 		case IAKerb:
1033 			return requested;
1034 		case Unspecified:
1035 			if (server->sec_ntlmssp &&
1036 			    (global_secflags & CIFSSEC_MAY_NTLMSSP))
1037 				return RawNTLMSSP;
1038 			if ((server->sec_kerberos || server->sec_mskerberos || server->sec_iakerb) &&
1039 			    (global_secflags & CIFSSEC_MAY_KRB5))
1040 				return Kerberos;
1041 			fallthrough;
1042 		default:
1043 			return Unspecified;
1044 		}
1045 	case CIFS_NEGFLAVOR_UNENCAP:
1046 		switch (requested) {
1047 		case NTLMv2:
1048 			return requested;
1049 		case Unspecified:
1050 			if (global_secflags & CIFSSEC_MAY_NTLMV2)
1051 				return NTLMv2;
1052 			break;
1053 		default:
1054 			break;
1055 		}
1056 		fallthrough;
1057 	default:
1058 		return Unspecified;
1059 	}
1060 }
1061