xref: /linux/fs/smb/client/sess.c (revision 3d0fe49454652117522f60bfbefb978ba0e5300b)
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 "cifspdu.h"
12 #include "cifsglob.h"
13 #include "cifsproto.h"
14 #include "cifs_unicode.h"
15 #include "cifs_debug.h"
16 #include "ntlmssp.h"
17 #include "nterr.h"
18 #include <linux/utsname.h>
19 #include <linux/slab.h>
20 #include <linux/version.h>
21 #include "cifsfs.h"
22 #include "cifs_spnego.h"
23 #include "smb2proto.h"
24 #include "fs_context.h"
25 
26 static int
27 cifs_ses_add_channel(struct cifs_ses *ses,
28 		     struct cifs_server_iface *iface);
29 
30 bool
31 is_server_using_iface(struct TCP_Server_Info *server,
32 		      struct cifs_server_iface *iface)
33 {
34 	struct sockaddr_in *i4 = (struct sockaddr_in *)&iface->sockaddr;
35 	struct sockaddr_in6 *i6 = (struct sockaddr_in6 *)&iface->sockaddr;
36 	struct sockaddr_in *s4 = (struct sockaddr_in *)&server->dstaddr;
37 	struct sockaddr_in6 *s6 = (struct sockaddr_in6 *)&server->dstaddr;
38 
39 	if (server->dstaddr.ss_family != iface->sockaddr.ss_family)
40 		return false;
41 	if (server->dstaddr.ss_family == AF_INET) {
42 		if (s4->sin_addr.s_addr != i4->sin_addr.s_addr)
43 			return false;
44 	} else if (server->dstaddr.ss_family == AF_INET6) {
45 		if (memcmp(&s6->sin6_addr, &i6->sin6_addr,
46 			   sizeof(i6->sin6_addr)) != 0)
47 			return false;
48 	} else {
49 		/* unknown family.. */
50 		return false;
51 	}
52 	return true;
53 }
54 
55 bool is_ses_using_iface(struct cifs_ses *ses, struct cifs_server_iface *iface)
56 {
57 	int i;
58 
59 	spin_lock(&ses->chan_lock);
60 	for (i = 0; i < ses->chan_count; i++) {
61 		if (ses->chans[i].iface == iface) {
62 			spin_unlock(&ses->chan_lock);
63 			return true;
64 		}
65 	}
66 	spin_unlock(&ses->chan_lock);
67 	return false;
68 }
69 
70 /* channel helper functions. assumed that chan_lock is held by caller. */
71 
72 int
73 cifs_ses_get_chan_index(struct cifs_ses *ses,
74 			struct TCP_Server_Info *server)
75 {
76 	unsigned int i;
77 
78 	for (i = 0; i < ses->chan_count; i++) {
79 		if (ses->chans[i].server == server)
80 			return i;
81 	}
82 
83 	/* If we didn't find the channel, it is likely a bug */
84 	if (server)
85 		cifs_dbg(VFS, "unable to get chan index for server: 0x%llx",
86 			 server->conn_id);
87 	WARN_ON(1);
88 	return CIFS_INVAL_CHAN_INDEX;
89 }
90 
91 void
92 cifs_chan_set_in_reconnect(struct cifs_ses *ses,
93 			     struct TCP_Server_Info *server)
94 {
95 	int chan_index = cifs_ses_get_chan_index(ses, server);
96 
97 	if (chan_index == CIFS_INVAL_CHAN_INDEX)
98 		return;
99 
100 	ses->chans[chan_index].in_reconnect = true;
101 }
102 
103 void
104 cifs_chan_clear_in_reconnect(struct cifs_ses *ses,
105 			     struct TCP_Server_Info *server)
106 {
107 	unsigned int chan_index = cifs_ses_get_chan_index(ses, server);
108 
109 	if (chan_index == CIFS_INVAL_CHAN_INDEX)
110 		return;
111 
112 	ses->chans[chan_index].in_reconnect = false;
113 }
114 
115 bool
116 cifs_chan_in_reconnect(struct cifs_ses *ses,
117 			  struct TCP_Server_Info *server)
118 {
119 	unsigned int chan_index = cifs_ses_get_chan_index(ses, server);
120 
121 	if (chan_index == CIFS_INVAL_CHAN_INDEX)
122 		return true;	/* err on the safer side */
123 
124 	return CIFS_CHAN_IN_RECONNECT(ses, chan_index);
125 }
126 
127 void
128 cifs_chan_set_need_reconnect(struct cifs_ses *ses,
129 			     struct TCP_Server_Info *server)
130 {
131 	unsigned int chan_index = cifs_ses_get_chan_index(ses, server);
132 
133 	if (chan_index == CIFS_INVAL_CHAN_INDEX)
134 		return;
135 
136 	set_bit(chan_index, &ses->chans_need_reconnect);
137 	cifs_dbg(FYI, "Set reconnect bitmask for chan %u; now 0x%lx\n",
138 		 chan_index, ses->chans_need_reconnect);
139 }
140 
141 void
142 cifs_chan_clear_need_reconnect(struct cifs_ses *ses,
143 			       struct TCP_Server_Info *server)
144 {
145 	unsigned int chan_index = cifs_ses_get_chan_index(ses, server);
146 
147 	if (chan_index == CIFS_INVAL_CHAN_INDEX)
148 		return;
149 
150 	clear_bit(chan_index, &ses->chans_need_reconnect);
151 	cifs_dbg(FYI, "Cleared reconnect bitmask for chan %u; now 0x%lx\n",
152 		 chan_index, ses->chans_need_reconnect);
153 }
154 
155 bool
156 cifs_chan_needs_reconnect(struct cifs_ses *ses,
157 			  struct TCP_Server_Info *server)
158 {
159 	unsigned int chan_index = cifs_ses_get_chan_index(ses, server);
160 
161 	if (chan_index == CIFS_INVAL_CHAN_INDEX)
162 		return true;	/* err on the safer side */
163 
164 	return CIFS_CHAN_NEEDS_RECONNECT(ses, chan_index);
165 }
166 
167 bool
168 cifs_chan_is_iface_active(struct cifs_ses *ses,
169 			  struct TCP_Server_Info *server)
170 {
171 	unsigned int chan_index = cifs_ses_get_chan_index(ses, server);
172 
173 	if (chan_index == CIFS_INVAL_CHAN_INDEX)
174 		return true;	/* err on the safer side */
175 
176 	return ses->chans[chan_index].iface &&
177 		ses->chans[chan_index].iface->is_active;
178 }
179 
180 /* returns number of channels added */
181 int cifs_try_adding_channels(struct cifs_ses *ses)
182 {
183 	struct TCP_Server_Info *server = ses->server;
184 	int old_chan_count, new_chan_count;
185 	int left;
186 	int rc = 0;
187 	int tries = 0;
188 	size_t iface_weight = 0, iface_min_speed = 0;
189 	struct cifs_server_iface *iface = NULL, *niface = NULL;
190 	struct cifs_server_iface *last_iface = NULL;
191 
192 	spin_lock(&ses->chan_lock);
193 
194 	new_chan_count = old_chan_count = ses->chan_count;
195 	left = ses->chan_max - ses->chan_count;
196 
197 	if (left <= 0) {
198 		spin_unlock(&ses->chan_lock);
199 		cifs_dbg(FYI,
200 			 "ses already at max_channels (%zu), nothing to open\n",
201 			 ses->chan_max);
202 		return 0;
203 	}
204 
205 	if (server->dialect < SMB30_PROT_ID) {
206 		spin_unlock(&ses->chan_lock);
207 		cifs_dbg(VFS, "multichannel is not supported on this protocol version, use 3.0 or above\n");
208 		return 0;
209 	}
210 
211 	if (!(server->capabilities & SMB2_GLOBAL_CAP_MULTI_CHANNEL)) {
212 		spin_unlock(&ses->chan_lock);
213 		cifs_server_dbg(VFS, "no multichannel support\n");
214 		return 0;
215 	}
216 	spin_unlock(&ses->chan_lock);
217 
218 	while (left > 0) {
219 
220 		tries++;
221 		if (tries > 3*ses->chan_max) {
222 			cifs_dbg(VFS, "too many channel open attempts (%d channels left to open)\n",
223 				 left);
224 			break;
225 		}
226 
227 		spin_lock(&ses->iface_lock);
228 		if (!ses->iface_count) {
229 			spin_unlock(&ses->iface_lock);
230 			cifs_dbg(VFS, "server %s does not advertise interfaces\n",
231 				      ses->server->hostname);
232 			break;
233 		}
234 
235 		if (!iface)
236 			iface = list_first_entry(&ses->iface_list, struct cifs_server_iface,
237 						 iface_head);
238 		last_iface = list_last_entry(&ses->iface_list, struct cifs_server_iface,
239 					     iface_head);
240 		iface_min_speed = last_iface->speed;
241 
242 		list_for_each_entry_safe_from(iface, niface, &ses->iface_list,
243 				    iface_head) {
244 			/* do not mix rdma and non-rdma interfaces */
245 			if (iface->rdma_capable != ses->server->rdma)
246 				continue;
247 
248 			/* skip ifaces that are unusable */
249 			if (!iface->is_active ||
250 			    (is_ses_using_iface(ses, iface) &&
251 			     !iface->rss_capable))
252 				continue;
253 
254 			/* check if we already allocated enough channels */
255 			iface_weight = iface->speed / iface_min_speed;
256 
257 			if (iface->weight_fulfilled >= iface_weight)
258 				continue;
259 
260 			/* take ref before unlock */
261 			kref_get(&iface->refcount);
262 
263 			spin_unlock(&ses->iface_lock);
264 			rc = cifs_ses_add_channel(ses, iface);
265 			spin_lock(&ses->iface_lock);
266 
267 			if (rc) {
268 				cifs_dbg(VFS, "failed to open extra channel on iface:%pIS rc=%d\n",
269 					 &iface->sockaddr,
270 					 rc);
271 				kref_put(&iface->refcount, release_iface);
272 				continue;
273 			}
274 
275 			iface->num_channels++;
276 			iface->weight_fulfilled++;
277 			cifs_dbg(VFS, "successfully opened new channel on iface:%pIS\n",
278 				 &iface->sockaddr);
279 			break;
280 		}
281 
282 		/* reached end of list. reset weight_fulfilled and start over */
283 		if (list_entry_is_head(iface, &ses->iface_list, iface_head)) {
284 			list_for_each_entry(iface, &ses->iface_list, iface_head)
285 				iface->weight_fulfilled = 0;
286 			spin_unlock(&ses->iface_lock);
287 			iface = NULL;
288 			continue;
289 		}
290 		spin_unlock(&ses->iface_lock);
291 
292 		left--;
293 		new_chan_count++;
294 	}
295 
296 	return new_chan_count - old_chan_count;
297 }
298 
299 /*
300  * called when multichannel is disabled by the server.
301  * this always gets called from smb2_reconnect
302  * and cannot get called in parallel threads.
303  */
304 void
305 cifs_disable_secondary_channels(struct cifs_ses *ses)
306 {
307 	int i, chan_count;
308 	struct TCP_Server_Info *server;
309 	struct cifs_server_iface *iface;
310 
311 	spin_lock(&ses->chan_lock);
312 	chan_count = ses->chan_count;
313 	if (chan_count == 1)
314 		goto done;
315 
316 	ses->chan_count = 1;
317 
318 	/* for all secondary channels reset the need reconnect bit */
319 	ses->chans_need_reconnect &= 1;
320 
321 	for (i = 1; i < chan_count; i++) {
322 		iface = ses->chans[i].iface;
323 		server = ses->chans[i].server;
324 
325 		if (iface) {
326 			spin_lock(&ses->iface_lock);
327 			kref_put(&iface->refcount, release_iface);
328 			ses->chans[i].iface = NULL;
329 			iface->num_channels--;
330 			if (iface->weight_fulfilled)
331 				iface->weight_fulfilled--;
332 			spin_unlock(&ses->iface_lock);
333 		}
334 
335 		spin_unlock(&ses->chan_lock);
336 		if (server && !server->terminate) {
337 			server->terminate = true;
338 			cifs_signal_cifsd_for_reconnect(server, false);
339 		}
340 		spin_lock(&ses->chan_lock);
341 
342 		if (server) {
343 			ses->chans[i].server = NULL;
344 			cifs_put_tcp_session(server, false);
345 		}
346 
347 	}
348 
349 done:
350 	spin_unlock(&ses->chan_lock);
351 }
352 
353 /*
354  * update the iface for the channel if necessary.
355  * will return 0 when iface is updated, 1 if removed, 2 otherwise
356  * Must be called with chan_lock held.
357  */
358 int
359 cifs_chan_update_iface(struct cifs_ses *ses, struct TCP_Server_Info *server)
360 {
361 	unsigned int chan_index;
362 	size_t iface_weight = 0, iface_min_speed = 0;
363 	struct cifs_server_iface *iface = NULL;
364 	struct cifs_server_iface *old_iface = NULL;
365 	struct cifs_server_iface *last_iface = NULL;
366 	struct sockaddr_storage ss;
367 	int rc = 0;
368 
369 	spin_lock(&ses->chan_lock);
370 	chan_index = cifs_ses_get_chan_index(ses, server);
371 	if (chan_index == CIFS_INVAL_CHAN_INDEX) {
372 		spin_unlock(&ses->chan_lock);
373 		return 0;
374 	}
375 
376 	if (ses->chans[chan_index].iface) {
377 		old_iface = ses->chans[chan_index].iface;
378 		if (old_iface->is_active) {
379 			spin_unlock(&ses->chan_lock);
380 			return 1;
381 		}
382 	}
383 	spin_unlock(&ses->chan_lock);
384 
385 	spin_lock(&server->srv_lock);
386 	ss = server->dstaddr;
387 	spin_unlock(&server->srv_lock);
388 
389 	spin_lock(&ses->iface_lock);
390 	if (!ses->iface_count) {
391 		spin_unlock(&ses->iface_lock);
392 		cifs_dbg(VFS, "server %s does not advertise interfaces\n", ses->server->hostname);
393 		return 0;
394 	}
395 
396 	last_iface = list_last_entry(&ses->iface_list, struct cifs_server_iface,
397 				     iface_head);
398 	iface_min_speed = last_iface->speed;
399 
400 	/* then look for a new one */
401 	list_for_each_entry(iface, &ses->iface_list, iface_head) {
402 		if (!chan_index) {
403 			/* if we're trying to get the updated iface for primary channel */
404 			if (!cifs_match_ipaddr((struct sockaddr *) &ss,
405 					       (struct sockaddr *) &iface->sockaddr))
406 				continue;
407 
408 			kref_get(&iface->refcount);
409 			break;
410 		}
411 
412 		/* do not mix rdma and non-rdma interfaces */
413 		if (iface->rdma_capable != server->rdma)
414 			continue;
415 
416 		if (!iface->is_active ||
417 		    (is_ses_using_iface(ses, iface) &&
418 		     !iface->rss_capable)) {
419 			continue;
420 		}
421 
422 		/* check if we already allocated enough channels */
423 		iface_weight = iface->speed / iface_min_speed;
424 
425 		if (iface->weight_fulfilled >= iface_weight)
426 			continue;
427 
428 		kref_get(&iface->refcount);
429 		break;
430 	}
431 
432 	if (list_entry_is_head(iface, &ses->iface_list, iface_head)) {
433 		rc = 1;
434 		iface = NULL;
435 		cifs_dbg(FYI, "unable to find a suitable iface\n");
436 	}
437 
438 	if (!chan_index && !iface) {
439 		cifs_dbg(FYI, "unable to get the interface matching: %pIS\n",
440 			 &ss);
441 		spin_unlock(&ses->iface_lock);
442 		return 0;
443 	}
444 
445 	/* now drop the ref to the current iface */
446 	if (old_iface && iface) {
447 		cifs_dbg(FYI, "replacing iface: %pIS with %pIS\n",
448 			 &old_iface->sockaddr,
449 			 &iface->sockaddr);
450 
451 		old_iface->num_channels--;
452 		if (old_iface->weight_fulfilled)
453 			old_iface->weight_fulfilled--;
454 		iface->num_channels++;
455 		iface->weight_fulfilled++;
456 
457 		kref_put(&old_iface->refcount, release_iface);
458 	} else if (old_iface) {
459 		cifs_dbg(FYI, "releasing ref to iface: %pIS\n",
460 			 &old_iface->sockaddr);
461 
462 		old_iface->num_channels--;
463 		if (old_iface->weight_fulfilled)
464 			old_iface->weight_fulfilled--;
465 
466 		kref_put(&old_iface->refcount, release_iface);
467 	} else if (!chan_index) {
468 		/* special case: update interface for primary channel */
469 		cifs_dbg(FYI, "referencing primary channel iface: %pIS\n",
470 			 &iface->sockaddr);
471 		iface->num_channels++;
472 		iface->weight_fulfilled++;
473 	} else {
474 		WARN_ON(!iface);
475 		cifs_dbg(FYI, "adding new iface: %pIS\n", &iface->sockaddr);
476 	}
477 	spin_unlock(&ses->iface_lock);
478 
479 	spin_lock(&ses->chan_lock);
480 	chan_index = cifs_ses_get_chan_index(ses, server);
481 	if (chan_index == CIFS_INVAL_CHAN_INDEX) {
482 		spin_unlock(&ses->chan_lock);
483 		return 0;
484 	}
485 
486 	ses->chans[chan_index].iface = iface;
487 
488 	/* No iface is found. if secondary chan, drop connection */
489 	if (!iface && SERVER_IS_CHAN(server))
490 		ses->chans[chan_index].server = NULL;
491 
492 	spin_unlock(&ses->chan_lock);
493 
494 	if (!iface && SERVER_IS_CHAN(server))
495 		cifs_put_tcp_session(server, false);
496 
497 	return rc;
498 }
499 
500 /*
501  * If server is a channel of ses, return the corresponding enclosing
502  * cifs_chan otherwise return NULL.
503  */
504 struct cifs_chan *
505 cifs_ses_find_chan(struct cifs_ses *ses, struct TCP_Server_Info *server)
506 {
507 	int i;
508 
509 	spin_lock(&ses->chan_lock);
510 	for (i = 0; i < ses->chan_count; i++) {
511 		if (ses->chans[i].server == server) {
512 			spin_unlock(&ses->chan_lock);
513 			return &ses->chans[i];
514 		}
515 	}
516 	spin_unlock(&ses->chan_lock);
517 	return NULL;
518 }
519 
520 static int
521 cifs_ses_add_channel(struct cifs_ses *ses,
522 		     struct cifs_server_iface *iface)
523 {
524 	struct TCP_Server_Info *chan_server;
525 	struct cifs_chan *chan;
526 	struct smb3_fs_context *ctx;
527 	static const char unc_fmt[] = "\\%s\\foo";
528 	struct sockaddr_in *ipv4 = (struct sockaddr_in *)&iface->sockaddr;
529 	struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)&iface->sockaddr;
530 	size_t len;
531 	int rc;
532 	unsigned int xid = get_xid();
533 
534 	if (iface->sockaddr.ss_family == AF_INET)
535 		cifs_dbg(FYI, "adding channel to ses %p (speed:%zu bps rdma:%s ip:%pI4)\n",
536 			 ses, iface->speed, iface->rdma_capable ? "yes" : "no",
537 			 &ipv4->sin_addr);
538 	else
539 		cifs_dbg(FYI, "adding channel to ses %p (speed:%zu bps rdma:%s ip:%pI6)\n",
540 			 ses, iface->speed, iface->rdma_capable ? "yes" : "no",
541 			 &ipv6->sin6_addr);
542 
543 	/*
544 	 * Setup a ctx with mostly the same info as the existing
545 	 * session and overwrite it with the requested iface data.
546 	 *
547 	 * We need to setup at least the fields used for negprot and
548 	 * sesssetup.
549 	 *
550 	 * We only need the ctx here, so we can reuse memory from
551 	 * the session and server without caring about memory
552 	 * management.
553 	 */
554 	ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
555 	if (!ctx) {
556 		rc = -ENOMEM;
557 		goto out_free_xid;
558 	}
559 
560 	/* Always make new connection for now (TODO?) */
561 	ctx->nosharesock = true;
562 
563 	/* Auth */
564 	ctx->domainauto = ses->domainAuto;
565 	ctx->domainname = ses->domainName;
566 
567 	/* no hostname for extra channels */
568 	ctx->server_hostname = "";
569 
570 	ctx->username = ses->user_name;
571 	ctx->password = ses->password;
572 	ctx->sectype = ses->sectype;
573 	ctx->sign = ses->sign;
574 
575 	/* UNC and paths */
576 	/* XXX: Use ses->server->hostname? */
577 	len = sizeof(unc_fmt) + SERVER_NAME_LEN_WITH_NULL;
578 	ctx->UNC = kzalloc(len, GFP_KERNEL);
579 	if (!ctx->UNC) {
580 		rc = -ENOMEM;
581 		goto out_free_ctx;
582 	}
583 	scnprintf(ctx->UNC, len, unc_fmt, ses->ip_addr);
584 	ctx->prepath = "";
585 
586 	/* Reuse same version as master connection */
587 	ctx->vals = ses->server->vals;
588 	ctx->ops = ses->server->ops;
589 
590 	ctx->noblocksnd = ses->server->noblocksnd;
591 	ctx->noautotune = ses->server->noautotune;
592 	ctx->sockopt_tcp_nodelay = ses->server->tcp_nodelay;
593 	ctx->echo_interval = ses->server->echo_interval / HZ;
594 	ctx->max_credits = ses->server->max_credits;
595 
596 	/*
597 	 * This will be used for encoding/decoding user/domain/pw
598 	 * during sess setup auth.
599 	 */
600 	ctx->local_nls = ses->local_nls;
601 
602 	/* Use RDMA if possible */
603 	ctx->rdma = iface->rdma_capable;
604 	memcpy(&ctx->dstaddr, &iface->sockaddr, sizeof(ctx->dstaddr));
605 
606 	/* reuse master con client guid */
607 	memcpy(&ctx->client_guid, ses->server->client_guid,
608 	       sizeof(ctx->client_guid));
609 	ctx->use_client_guid = true;
610 
611 	chan_server = cifs_get_tcp_session(ctx, ses->server);
612 
613 	spin_lock(&ses->chan_lock);
614 	chan = &ses->chans[ses->chan_count];
615 	chan->server = chan_server;
616 	if (IS_ERR(chan->server)) {
617 		rc = PTR_ERR(chan->server);
618 		chan->server = NULL;
619 		spin_unlock(&ses->chan_lock);
620 		goto out;
621 	}
622 	chan->iface = iface;
623 	ses->chan_count++;
624 	atomic_set(&ses->chan_seq, 0);
625 
626 	/* Mark this channel as needing connect/setup */
627 	cifs_chan_set_need_reconnect(ses, chan->server);
628 
629 	spin_unlock(&ses->chan_lock);
630 
631 	mutex_lock(&ses->session_mutex);
632 	/*
633 	 * We need to allocate the server crypto now as we will need
634 	 * to sign packets before we generate the channel signing key
635 	 * (we sign with the session key)
636 	 */
637 	rc = smb311_crypto_shash_allocate(chan->server);
638 	if (rc) {
639 		cifs_dbg(VFS, "%s: crypto alloc failed\n", __func__);
640 		mutex_unlock(&ses->session_mutex);
641 		goto out;
642 	}
643 
644 	rc = cifs_negotiate_protocol(xid, ses, chan->server);
645 	if (!rc)
646 		rc = cifs_setup_session(xid, ses, chan->server, ses->local_nls);
647 
648 	mutex_unlock(&ses->session_mutex);
649 
650 out:
651 	if (rc && chan->server) {
652 		cifs_put_tcp_session(chan->server, 0);
653 
654 		spin_lock(&ses->chan_lock);
655 
656 		/* we rely on all bits beyond chan_count to be clear */
657 		cifs_chan_clear_need_reconnect(ses, chan->server);
658 		ses->chan_count--;
659 		/*
660 		 * chan_count should never reach 0 as at least the primary
661 		 * channel is always allocated
662 		 */
663 		WARN_ON(ses->chan_count < 1);
664 		spin_unlock(&ses->chan_lock);
665 	}
666 
667 	kfree(ctx->UNC);
668 out_free_ctx:
669 	kfree(ctx);
670 out_free_xid:
671 	free_xid(xid);
672 	return rc;
673 }
674 
675 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
676 static __u32 cifs_ssetup_hdr(struct cifs_ses *ses,
677 			     struct TCP_Server_Info *server,
678 			     SESSION_SETUP_ANDX *pSMB)
679 {
680 	__u32 capabilities = 0;
681 
682 	/* init fields common to all four types of SessSetup */
683 	/* Note that offsets for first seven fields in req struct are same  */
684 	/*	in CIFS Specs so does not matter which of 3 forms of struct */
685 	/*	that we use in next few lines                               */
686 	/* Note that header is initialized to zero in header_assemble */
687 	pSMB->req.AndXCommand = 0xFF;
688 	pSMB->req.MaxBufferSize = cpu_to_le16(min_t(u32,
689 					CIFSMaxBufSize + MAX_CIFS_HDR_SIZE - 4,
690 					USHRT_MAX));
691 	pSMB->req.MaxMpxCount = cpu_to_le16(server->maxReq);
692 	pSMB->req.VcNumber = cpu_to_le16(1);
693 
694 	/* Now no need to set SMBFLG_CASELESS or obsolete CANONICAL PATH */
695 
696 	/* BB verify whether signing required on neg or just auth frame (and NTLM case) */
697 
698 	capabilities = CAP_LARGE_FILES | CAP_NT_SMBS | CAP_LEVEL_II_OPLOCKS |
699 			CAP_LARGE_WRITE_X | CAP_LARGE_READ_X;
700 
701 	if (server->sign)
702 		pSMB->req.hdr.Flags2 |= SMBFLG2_SECURITY_SIGNATURE;
703 
704 	if (ses->capabilities & CAP_UNICODE) {
705 		pSMB->req.hdr.Flags2 |= SMBFLG2_UNICODE;
706 		capabilities |= CAP_UNICODE;
707 	}
708 	if (ses->capabilities & CAP_STATUS32) {
709 		pSMB->req.hdr.Flags2 |= SMBFLG2_ERR_STATUS;
710 		capabilities |= CAP_STATUS32;
711 	}
712 	if (ses->capabilities & CAP_DFS) {
713 		pSMB->req.hdr.Flags2 |= SMBFLG2_DFS;
714 		capabilities |= CAP_DFS;
715 	}
716 	if (ses->capabilities & CAP_UNIX)
717 		capabilities |= CAP_UNIX;
718 
719 	return capabilities;
720 }
721 
722 static void
723 unicode_oslm_strings(char **pbcc_area, const struct nls_table *nls_cp)
724 {
725 	char *bcc_ptr = *pbcc_area;
726 	int bytes_ret = 0;
727 
728 	/* Copy OS version */
729 	bytes_ret = cifs_strtoUTF16((__le16 *)bcc_ptr, "Linux version ", 32,
730 				    nls_cp);
731 	bcc_ptr += 2 * bytes_ret;
732 	bytes_ret = cifs_strtoUTF16((__le16 *) bcc_ptr, init_utsname()->release,
733 				    32, nls_cp);
734 	bcc_ptr += 2 * bytes_ret;
735 	bcc_ptr += 2; /* trailing null */
736 
737 	bytes_ret = cifs_strtoUTF16((__le16 *) bcc_ptr, CIFS_NETWORK_OPSYS,
738 				    32, nls_cp);
739 	bcc_ptr += 2 * bytes_ret;
740 	bcc_ptr += 2; /* trailing null */
741 
742 	*pbcc_area = bcc_ptr;
743 }
744 
745 static void unicode_domain_string(char **pbcc_area, struct cifs_ses *ses,
746 				   const struct nls_table *nls_cp)
747 {
748 	char *bcc_ptr = *pbcc_area;
749 	int bytes_ret = 0;
750 
751 	/* copy domain */
752 	if (ses->domainName == NULL) {
753 		/*
754 		 * Sending null domain better than using a bogus domain name (as
755 		 * we did briefly in 2.6.18) since server will use its default
756 		 */
757 		*bcc_ptr = 0;
758 		*(bcc_ptr+1) = 0;
759 		bytes_ret = 0;
760 	} else
761 		bytes_ret = cifs_strtoUTF16((__le16 *) bcc_ptr, ses->domainName,
762 					    CIFS_MAX_DOMAINNAME_LEN, nls_cp);
763 	bcc_ptr += 2 * bytes_ret;
764 	bcc_ptr += 2;  /* account for null terminator */
765 
766 	*pbcc_area = bcc_ptr;
767 }
768 
769 static void unicode_ssetup_strings(char **pbcc_area, struct cifs_ses *ses,
770 				   const struct nls_table *nls_cp)
771 {
772 	char *bcc_ptr = *pbcc_area;
773 	int bytes_ret = 0;
774 
775 	/* BB FIXME add check that strings less than 335 or will need to send as arrays */
776 
777 	/* copy user */
778 	if (ses->user_name == NULL) {
779 		/* null user mount */
780 		*bcc_ptr = 0;
781 		*(bcc_ptr+1) = 0;
782 	} else {
783 		bytes_ret = cifs_strtoUTF16((__le16 *) bcc_ptr, ses->user_name,
784 					    CIFS_MAX_USERNAME_LEN, nls_cp);
785 	}
786 	bcc_ptr += 2 * bytes_ret;
787 	bcc_ptr += 2; /* account for null termination */
788 
789 	unicode_domain_string(&bcc_ptr, ses, nls_cp);
790 	unicode_oslm_strings(&bcc_ptr, nls_cp);
791 
792 	*pbcc_area = bcc_ptr;
793 }
794 
795 static void ascii_ssetup_strings(char **pbcc_area, struct cifs_ses *ses,
796 				 const struct nls_table *nls_cp)
797 {
798 	char *bcc_ptr = *pbcc_area;
799 	int len;
800 
801 	/* copy user */
802 	/* BB what about null user mounts - check that we do this BB */
803 	/* copy user */
804 	if (ses->user_name != NULL) {
805 		len = strscpy(bcc_ptr, ses->user_name, CIFS_MAX_USERNAME_LEN);
806 		if (WARN_ON_ONCE(len < 0))
807 			len = CIFS_MAX_USERNAME_LEN - 1;
808 		bcc_ptr += len;
809 	}
810 	/* else null user mount */
811 	*bcc_ptr = 0;
812 	bcc_ptr++; /* account for null termination */
813 
814 	/* copy domain */
815 	if (ses->domainName != NULL) {
816 		len = strscpy(bcc_ptr, ses->domainName, CIFS_MAX_DOMAINNAME_LEN);
817 		if (WARN_ON_ONCE(len < 0))
818 			len = CIFS_MAX_DOMAINNAME_LEN - 1;
819 		bcc_ptr += len;
820 	} /* else we send a null domain name so server will default to its own domain */
821 	*bcc_ptr = 0;
822 	bcc_ptr++;
823 
824 	/* BB check for overflow here */
825 
826 	strcpy(bcc_ptr, "Linux version ");
827 	bcc_ptr += strlen("Linux version ");
828 	strcpy(bcc_ptr, init_utsname()->release);
829 	bcc_ptr += strlen(init_utsname()->release) + 1;
830 
831 	strcpy(bcc_ptr, CIFS_NETWORK_OPSYS);
832 	bcc_ptr += strlen(CIFS_NETWORK_OPSYS) + 1;
833 
834 	*pbcc_area = bcc_ptr;
835 }
836 
837 static void
838 decode_unicode_ssetup(char **pbcc_area, int bleft, struct cifs_ses *ses,
839 		      const struct nls_table *nls_cp)
840 {
841 	int len;
842 	char *data = *pbcc_area;
843 
844 	cifs_dbg(FYI, "bleft %d\n", bleft);
845 
846 	kfree(ses->serverOS);
847 	ses->serverOS = cifs_strndup_from_utf16(data, bleft, true, nls_cp);
848 	cifs_dbg(FYI, "serverOS=%s\n", ses->serverOS);
849 	len = (UniStrnlen((wchar_t *) data, bleft / 2) * 2) + 2;
850 	data += len;
851 	bleft -= len;
852 	if (bleft <= 0)
853 		return;
854 
855 	kfree(ses->serverNOS);
856 	ses->serverNOS = cifs_strndup_from_utf16(data, bleft, true, nls_cp);
857 	cifs_dbg(FYI, "serverNOS=%s\n", ses->serverNOS);
858 	len = (UniStrnlen((wchar_t *) data, bleft / 2) * 2) + 2;
859 	data += len;
860 	bleft -= len;
861 	if (bleft <= 0)
862 		return;
863 
864 	kfree(ses->serverDomain);
865 	ses->serverDomain = cifs_strndup_from_utf16(data, bleft, true, nls_cp);
866 	cifs_dbg(FYI, "serverDomain=%s\n", ses->serverDomain);
867 
868 	return;
869 }
870 
871 static void decode_ascii_ssetup(char **pbcc_area, __u16 bleft,
872 				struct cifs_ses *ses,
873 				const struct nls_table *nls_cp)
874 {
875 	int len;
876 	char *bcc_ptr = *pbcc_area;
877 
878 	cifs_dbg(FYI, "decode sessetup ascii. bleft %d\n", bleft);
879 
880 	len = strnlen(bcc_ptr, bleft);
881 	if (len >= bleft)
882 		return;
883 
884 	kfree(ses->serverOS);
885 
886 	ses->serverOS = kmalloc(len + 1, GFP_KERNEL);
887 	if (ses->serverOS) {
888 		memcpy(ses->serverOS, bcc_ptr, len);
889 		ses->serverOS[len] = 0;
890 		if (strncmp(ses->serverOS, "OS/2", 4) == 0)
891 			cifs_dbg(FYI, "OS/2 server\n");
892 	}
893 
894 	bcc_ptr += len + 1;
895 	bleft -= len + 1;
896 
897 	len = strnlen(bcc_ptr, bleft);
898 	if (len >= bleft)
899 		return;
900 
901 	kfree(ses->serverNOS);
902 
903 	ses->serverNOS = kmalloc(len + 1, GFP_KERNEL);
904 	if (ses->serverNOS) {
905 		memcpy(ses->serverNOS, bcc_ptr, len);
906 		ses->serverNOS[len] = 0;
907 	}
908 
909 	bcc_ptr += len + 1;
910 	bleft -= len + 1;
911 
912 	len = strnlen(bcc_ptr, bleft);
913 	if (len > bleft)
914 		return;
915 
916 	/*
917 	 * No domain field in LANMAN case. Domain is
918 	 * returned by old servers in the SMB negprot response
919 	 *
920 	 * BB For newer servers which do not support Unicode,
921 	 * but thus do return domain here, we could add parsing
922 	 * for it later, but it is not very important
923 	 */
924 	cifs_dbg(FYI, "ascii: bytes left %d\n", bleft);
925 }
926 #endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
927 
928 int decode_ntlmssp_challenge(char *bcc_ptr, int blob_len,
929 				    struct cifs_ses *ses)
930 {
931 	unsigned int tioffset; /* challenge message target info area */
932 	unsigned int tilen; /* challenge message target info area length  */
933 	CHALLENGE_MESSAGE *pblob = (CHALLENGE_MESSAGE *)bcc_ptr;
934 	__u32 server_flags;
935 
936 	if (blob_len < sizeof(CHALLENGE_MESSAGE)) {
937 		cifs_dbg(VFS, "challenge blob len %d too small\n", blob_len);
938 		return -EINVAL;
939 	}
940 
941 	if (memcmp(pblob->Signature, "NTLMSSP", 8)) {
942 		cifs_dbg(VFS, "blob signature incorrect %s\n",
943 			 pblob->Signature);
944 		return -EINVAL;
945 	}
946 	if (pblob->MessageType != NtLmChallenge) {
947 		cifs_dbg(VFS, "Incorrect message type %d\n",
948 			 pblob->MessageType);
949 		return -EINVAL;
950 	}
951 
952 	server_flags = le32_to_cpu(pblob->NegotiateFlags);
953 	cifs_dbg(FYI, "%s: negotiate=0x%08x challenge=0x%08x\n", __func__,
954 		 ses->ntlmssp->client_flags, server_flags);
955 
956 	if ((ses->ntlmssp->client_flags & (NTLMSSP_NEGOTIATE_SEAL | NTLMSSP_NEGOTIATE_SIGN)) &&
957 	    (!(server_flags & NTLMSSP_NEGOTIATE_56) && !(server_flags & NTLMSSP_NEGOTIATE_128))) {
958 		cifs_dbg(VFS, "%s: requested signing/encryption but server did not return either 56-bit or 128-bit session key size\n",
959 			 __func__);
960 		return -EINVAL;
961 	}
962 	if (!(server_flags & NTLMSSP_NEGOTIATE_NTLM) && !(server_flags & NTLMSSP_NEGOTIATE_EXTENDED_SEC)) {
963 		cifs_dbg(VFS, "%s: server does not seem to support either NTLMv1 or NTLMv2\n", __func__);
964 		return -EINVAL;
965 	}
966 	if (ses->server->sign && !(server_flags & NTLMSSP_NEGOTIATE_SIGN)) {
967 		cifs_dbg(VFS, "%s: forced packet signing but server does not seem to support it\n",
968 			 __func__);
969 		return -EOPNOTSUPP;
970 	}
971 	if ((ses->ntlmssp->client_flags & NTLMSSP_NEGOTIATE_KEY_XCH) &&
972 	    !(server_flags & NTLMSSP_NEGOTIATE_KEY_XCH))
973 		pr_warn_once("%s: authentication has been weakened as server does not support key exchange\n",
974 			     __func__);
975 
976 	ses->ntlmssp->server_flags = server_flags;
977 
978 	memcpy(ses->ntlmssp->cryptkey, pblob->Challenge, CIFS_CRYPTO_KEY_SIZE);
979 	/*
980 	 * In particular we can examine sign flags
981 	 *
982 	 * BB spec says that if AvId field of MsvAvTimestamp is populated then
983 	 * we must set the MIC field of the AUTHENTICATE_MESSAGE
984 	 */
985 
986 	tioffset = le32_to_cpu(pblob->TargetInfoArray.BufferOffset);
987 	tilen = le16_to_cpu(pblob->TargetInfoArray.Length);
988 	if (tioffset > blob_len || tioffset + tilen > blob_len) {
989 		cifs_dbg(VFS, "tioffset + tilen too high %u + %u\n",
990 			 tioffset, tilen);
991 		return -EINVAL;
992 	}
993 	if (tilen) {
994 		kfree_sensitive(ses->auth_key.response);
995 		ses->auth_key.response = kmemdup(bcc_ptr + tioffset, tilen,
996 						 GFP_KERNEL);
997 		if (!ses->auth_key.response) {
998 			cifs_dbg(VFS, "Challenge target info alloc failure\n");
999 			return -ENOMEM;
1000 		}
1001 		ses->auth_key.len = tilen;
1002 	}
1003 
1004 	return 0;
1005 }
1006 
1007 static int size_of_ntlmssp_blob(struct cifs_ses *ses, int base_size)
1008 {
1009 	int sz = base_size + ses->auth_key.len
1010 		- CIFS_SESS_KEY_SIZE + CIFS_CPHTXT_SIZE + 2;
1011 
1012 	if (ses->domainName)
1013 		sz += sizeof(__le16) * strnlen(ses->domainName, CIFS_MAX_DOMAINNAME_LEN);
1014 	else
1015 		sz += sizeof(__le16);
1016 
1017 	if (ses->user_name)
1018 		sz += sizeof(__le16) * strnlen(ses->user_name, CIFS_MAX_USERNAME_LEN);
1019 	else
1020 		sz += sizeof(__le16);
1021 
1022 	if (ses->workstation_name[0])
1023 		sz += sizeof(__le16) * strnlen(ses->workstation_name,
1024 					       ntlmssp_workstation_name_size(ses));
1025 	else
1026 		sz += sizeof(__le16);
1027 
1028 	return sz;
1029 }
1030 
1031 static inline void cifs_security_buffer_from_str(SECURITY_BUFFER *pbuf,
1032 						 char *str_value,
1033 						 int str_length,
1034 						 unsigned char *pstart,
1035 						 unsigned char **pcur,
1036 						 const struct nls_table *nls_cp)
1037 {
1038 	unsigned char *tmp = pstart;
1039 	int len;
1040 
1041 	if (!pbuf)
1042 		return;
1043 
1044 	if (!pcur)
1045 		pcur = &tmp;
1046 
1047 	if (!str_value) {
1048 		pbuf->BufferOffset = cpu_to_le32(*pcur - pstart);
1049 		pbuf->Length = 0;
1050 		pbuf->MaximumLength = 0;
1051 		*pcur += sizeof(__le16);
1052 	} else {
1053 		len = cifs_strtoUTF16((__le16 *)*pcur,
1054 				      str_value,
1055 				      str_length,
1056 				      nls_cp);
1057 		len *= sizeof(__le16);
1058 		pbuf->BufferOffset = cpu_to_le32(*pcur - pstart);
1059 		pbuf->Length = cpu_to_le16(len);
1060 		pbuf->MaximumLength = cpu_to_le16(len);
1061 		*pcur += len;
1062 	}
1063 }
1064 
1065 /* BB Move to ntlmssp.c eventually */
1066 
1067 int build_ntlmssp_negotiate_blob(unsigned char **pbuffer,
1068 				 u16 *buflen,
1069 				 struct cifs_ses *ses,
1070 				 struct TCP_Server_Info *server,
1071 				 const struct nls_table *nls_cp)
1072 {
1073 	int rc = 0;
1074 	NEGOTIATE_MESSAGE *sec_blob;
1075 	__u32 flags;
1076 	unsigned char *tmp;
1077 	int len;
1078 
1079 	len = size_of_ntlmssp_blob(ses, sizeof(NEGOTIATE_MESSAGE));
1080 	*pbuffer = kmalloc(len, GFP_KERNEL);
1081 	if (!*pbuffer) {
1082 		rc = -ENOMEM;
1083 		cifs_dbg(VFS, "Error %d during NTLMSSP allocation\n", rc);
1084 		*buflen = 0;
1085 		goto setup_ntlm_neg_ret;
1086 	}
1087 	sec_blob = (NEGOTIATE_MESSAGE *)*pbuffer;
1088 
1089 	memset(*pbuffer, 0, sizeof(NEGOTIATE_MESSAGE));
1090 	memcpy(sec_blob->Signature, NTLMSSP_SIGNATURE, 8);
1091 	sec_blob->MessageType = NtLmNegotiate;
1092 
1093 	/* BB is NTLMV2 session security format easier to use here? */
1094 	flags = NTLMSSP_NEGOTIATE_56 |	NTLMSSP_REQUEST_TARGET |
1095 		NTLMSSP_NEGOTIATE_128 | NTLMSSP_NEGOTIATE_UNICODE |
1096 		NTLMSSP_NEGOTIATE_NTLM | NTLMSSP_NEGOTIATE_EXTENDED_SEC |
1097 		NTLMSSP_NEGOTIATE_ALWAYS_SIGN | NTLMSSP_NEGOTIATE_SEAL |
1098 		NTLMSSP_NEGOTIATE_SIGN;
1099 	if (!server->session_estab || ses->ntlmssp->sesskey_per_smbsess)
1100 		flags |= NTLMSSP_NEGOTIATE_KEY_XCH;
1101 
1102 	tmp = *pbuffer + sizeof(NEGOTIATE_MESSAGE);
1103 	ses->ntlmssp->client_flags = flags;
1104 	sec_blob->NegotiateFlags = cpu_to_le32(flags);
1105 
1106 	/* these fields should be null in negotiate phase MS-NLMP 3.1.5.1.1 */
1107 	cifs_security_buffer_from_str(&sec_blob->DomainName,
1108 				      NULL,
1109 				      CIFS_MAX_DOMAINNAME_LEN,
1110 				      *pbuffer, &tmp,
1111 				      nls_cp);
1112 
1113 	cifs_security_buffer_from_str(&sec_blob->WorkstationName,
1114 				      NULL,
1115 				      CIFS_MAX_WORKSTATION_LEN,
1116 				      *pbuffer, &tmp,
1117 				      nls_cp);
1118 
1119 	*buflen = tmp - *pbuffer;
1120 setup_ntlm_neg_ret:
1121 	return rc;
1122 }
1123 
1124 /*
1125  * Build ntlmssp blob with additional fields, such as version,
1126  * supported by modern servers. For safety limit to SMB3 or later
1127  * See notes in MS-NLMP Section 2.2.2.1 e.g.
1128  */
1129 int build_ntlmssp_smb3_negotiate_blob(unsigned char **pbuffer,
1130 				 u16 *buflen,
1131 				 struct cifs_ses *ses,
1132 				 struct TCP_Server_Info *server,
1133 				 const struct nls_table *nls_cp)
1134 {
1135 	int rc = 0;
1136 	struct negotiate_message *sec_blob;
1137 	__u32 flags;
1138 	unsigned char *tmp;
1139 	int len;
1140 
1141 	len = size_of_ntlmssp_blob(ses, sizeof(struct negotiate_message));
1142 	*pbuffer = kmalloc(len, GFP_KERNEL);
1143 	if (!*pbuffer) {
1144 		rc = -ENOMEM;
1145 		cifs_dbg(VFS, "Error %d during NTLMSSP allocation\n", rc);
1146 		*buflen = 0;
1147 		goto setup_ntlm_smb3_neg_ret;
1148 	}
1149 	sec_blob = (struct negotiate_message *)*pbuffer;
1150 
1151 	memset(*pbuffer, 0, sizeof(struct negotiate_message));
1152 	memcpy(sec_blob->Signature, NTLMSSP_SIGNATURE, 8);
1153 	sec_blob->MessageType = NtLmNegotiate;
1154 
1155 	/* BB is NTLMV2 session security format easier to use here? */
1156 	flags = NTLMSSP_NEGOTIATE_56 |	NTLMSSP_REQUEST_TARGET |
1157 		NTLMSSP_NEGOTIATE_128 | NTLMSSP_NEGOTIATE_UNICODE |
1158 		NTLMSSP_NEGOTIATE_NTLM | NTLMSSP_NEGOTIATE_EXTENDED_SEC |
1159 		NTLMSSP_NEGOTIATE_ALWAYS_SIGN | NTLMSSP_NEGOTIATE_SEAL |
1160 		NTLMSSP_NEGOTIATE_SIGN | NTLMSSP_NEGOTIATE_VERSION;
1161 	if (!server->session_estab || ses->ntlmssp->sesskey_per_smbsess)
1162 		flags |= NTLMSSP_NEGOTIATE_KEY_XCH;
1163 
1164 	sec_blob->Version.ProductMajorVersion = LINUX_VERSION_MAJOR;
1165 	sec_blob->Version.ProductMinorVersion = LINUX_VERSION_PATCHLEVEL;
1166 	sec_blob->Version.ProductBuild = cpu_to_le16(SMB3_PRODUCT_BUILD);
1167 	sec_blob->Version.NTLMRevisionCurrent = NTLMSSP_REVISION_W2K3;
1168 
1169 	tmp = *pbuffer + sizeof(struct negotiate_message);
1170 	ses->ntlmssp->client_flags = flags;
1171 	sec_blob->NegotiateFlags = cpu_to_le32(flags);
1172 
1173 	/* these fields should be null in negotiate phase MS-NLMP 3.1.5.1.1 */
1174 	cifs_security_buffer_from_str(&sec_blob->DomainName,
1175 				      NULL,
1176 				      CIFS_MAX_DOMAINNAME_LEN,
1177 				      *pbuffer, &tmp,
1178 				      nls_cp);
1179 
1180 	cifs_security_buffer_from_str(&sec_blob->WorkstationName,
1181 				      NULL,
1182 				      CIFS_MAX_WORKSTATION_LEN,
1183 				      *pbuffer, &tmp,
1184 				      nls_cp);
1185 
1186 	*buflen = tmp - *pbuffer;
1187 setup_ntlm_smb3_neg_ret:
1188 	return rc;
1189 }
1190 
1191 
1192 /* See MS-NLMP 2.2.1.3 */
1193 int build_ntlmssp_auth_blob(unsigned char **pbuffer,
1194 					u16 *buflen,
1195 				   struct cifs_ses *ses,
1196 				   struct TCP_Server_Info *server,
1197 				   const struct nls_table *nls_cp)
1198 {
1199 	int rc;
1200 	AUTHENTICATE_MESSAGE *sec_blob;
1201 	__u32 flags;
1202 	unsigned char *tmp;
1203 	int len;
1204 
1205 	rc = setup_ntlmv2_rsp(ses, nls_cp);
1206 	if (rc) {
1207 		cifs_dbg(VFS, "Error %d during NTLMSSP authentication\n", rc);
1208 		*buflen = 0;
1209 		goto setup_ntlmv2_ret;
1210 	}
1211 
1212 	len = size_of_ntlmssp_blob(ses, sizeof(AUTHENTICATE_MESSAGE));
1213 	*pbuffer = kmalloc(len, GFP_KERNEL);
1214 	if (!*pbuffer) {
1215 		rc = -ENOMEM;
1216 		cifs_dbg(VFS, "Error %d during NTLMSSP allocation\n", rc);
1217 		*buflen = 0;
1218 		goto setup_ntlmv2_ret;
1219 	}
1220 	sec_blob = (AUTHENTICATE_MESSAGE *)*pbuffer;
1221 
1222 	memcpy(sec_blob->Signature, NTLMSSP_SIGNATURE, 8);
1223 	sec_blob->MessageType = NtLmAuthenticate;
1224 
1225 	/* send version information in ntlmssp authenticate also */
1226 	flags = ses->ntlmssp->server_flags | NTLMSSP_REQUEST_TARGET |
1227 		NTLMSSP_NEGOTIATE_TARGET_INFO | NTLMSSP_NEGOTIATE_VERSION |
1228 		NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED;
1229 
1230 	sec_blob->Version.ProductMajorVersion = LINUX_VERSION_MAJOR;
1231 	sec_blob->Version.ProductMinorVersion = LINUX_VERSION_PATCHLEVEL;
1232 	sec_blob->Version.ProductBuild = cpu_to_le16(SMB3_PRODUCT_BUILD);
1233 	sec_blob->Version.NTLMRevisionCurrent = NTLMSSP_REVISION_W2K3;
1234 
1235 	tmp = *pbuffer + sizeof(AUTHENTICATE_MESSAGE);
1236 	sec_blob->NegotiateFlags = cpu_to_le32(flags);
1237 
1238 	sec_blob->LmChallengeResponse.BufferOffset =
1239 				cpu_to_le32(sizeof(AUTHENTICATE_MESSAGE));
1240 	sec_blob->LmChallengeResponse.Length = 0;
1241 	sec_blob->LmChallengeResponse.MaximumLength = 0;
1242 
1243 	sec_blob->NtChallengeResponse.BufferOffset =
1244 				cpu_to_le32(tmp - *pbuffer);
1245 	if (ses->user_name != NULL) {
1246 		memcpy(tmp, ses->auth_key.response + CIFS_SESS_KEY_SIZE,
1247 				ses->auth_key.len - CIFS_SESS_KEY_SIZE);
1248 		tmp += ses->auth_key.len - CIFS_SESS_KEY_SIZE;
1249 
1250 		sec_blob->NtChallengeResponse.Length =
1251 				cpu_to_le16(ses->auth_key.len - CIFS_SESS_KEY_SIZE);
1252 		sec_blob->NtChallengeResponse.MaximumLength =
1253 				cpu_to_le16(ses->auth_key.len - CIFS_SESS_KEY_SIZE);
1254 	} else {
1255 		/*
1256 		 * don't send an NT Response for anonymous access
1257 		 */
1258 		sec_blob->NtChallengeResponse.Length = 0;
1259 		sec_blob->NtChallengeResponse.MaximumLength = 0;
1260 	}
1261 
1262 	cifs_security_buffer_from_str(&sec_blob->DomainName,
1263 				      ses->domainName,
1264 				      CIFS_MAX_DOMAINNAME_LEN,
1265 				      *pbuffer, &tmp,
1266 				      nls_cp);
1267 
1268 	cifs_security_buffer_from_str(&sec_blob->UserName,
1269 				      ses->user_name,
1270 				      CIFS_MAX_USERNAME_LEN,
1271 				      *pbuffer, &tmp,
1272 				      nls_cp);
1273 
1274 	cifs_security_buffer_from_str(&sec_blob->WorkstationName,
1275 				      ses->workstation_name,
1276 				      ntlmssp_workstation_name_size(ses),
1277 				      *pbuffer, &tmp,
1278 				      nls_cp);
1279 
1280 	if ((ses->ntlmssp->server_flags & NTLMSSP_NEGOTIATE_KEY_XCH) &&
1281 	    (!ses->server->session_estab || ses->ntlmssp->sesskey_per_smbsess) &&
1282 	    !calc_seckey(ses)) {
1283 		memcpy(tmp, ses->ntlmssp->ciphertext, CIFS_CPHTXT_SIZE);
1284 		sec_blob->SessionKey.BufferOffset = cpu_to_le32(tmp - *pbuffer);
1285 		sec_blob->SessionKey.Length = cpu_to_le16(CIFS_CPHTXT_SIZE);
1286 		sec_blob->SessionKey.MaximumLength =
1287 				cpu_to_le16(CIFS_CPHTXT_SIZE);
1288 		tmp += CIFS_CPHTXT_SIZE;
1289 	} else {
1290 		sec_blob->SessionKey.BufferOffset = cpu_to_le32(tmp - *pbuffer);
1291 		sec_blob->SessionKey.Length = 0;
1292 		sec_blob->SessionKey.MaximumLength = 0;
1293 	}
1294 
1295 	*buflen = tmp - *pbuffer;
1296 setup_ntlmv2_ret:
1297 	return rc;
1298 }
1299 
1300 enum securityEnum
1301 cifs_select_sectype(struct TCP_Server_Info *server, enum securityEnum requested)
1302 {
1303 	switch (server->negflavor) {
1304 	case CIFS_NEGFLAVOR_EXTENDED:
1305 		switch (requested) {
1306 		case Kerberos:
1307 		case RawNTLMSSP:
1308 			return requested;
1309 		case Unspecified:
1310 			if (server->sec_ntlmssp &&
1311 			    (global_secflags & CIFSSEC_MAY_NTLMSSP))
1312 				return RawNTLMSSP;
1313 			if ((server->sec_kerberos || server->sec_mskerberos) &&
1314 			    (global_secflags & CIFSSEC_MAY_KRB5))
1315 				return Kerberos;
1316 			fallthrough;
1317 		default:
1318 			return Unspecified;
1319 		}
1320 	case CIFS_NEGFLAVOR_UNENCAP:
1321 		switch (requested) {
1322 		case NTLMv2:
1323 			return requested;
1324 		case Unspecified:
1325 			if (global_secflags & CIFSSEC_MAY_NTLMV2)
1326 				return NTLMv2;
1327 			break;
1328 		default:
1329 			break;
1330 		}
1331 		fallthrough;
1332 	default:
1333 		return Unspecified;
1334 	}
1335 }
1336 
1337 struct sess_data {
1338 	unsigned int xid;
1339 	struct cifs_ses *ses;
1340 	struct TCP_Server_Info *server;
1341 	struct nls_table *nls_cp;
1342 	void (*func)(struct sess_data *);
1343 	int result;
1344 
1345 	/* we will send the SMB in three pieces:
1346 	 * a fixed length beginning part, an optional
1347 	 * SPNEGO blob (which can be zero length), and a
1348 	 * last part which will include the strings
1349 	 * and rest of bcc area. This allows us to avoid
1350 	 * a large buffer 17K allocation
1351 	 */
1352 	int buf0_type;
1353 	struct kvec iov[3];
1354 };
1355 
1356 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
1357 static int
1358 sess_alloc_buffer(struct sess_data *sess_data, int wct)
1359 {
1360 	int rc;
1361 	struct cifs_ses *ses = sess_data->ses;
1362 	struct smb_hdr *smb_buf;
1363 
1364 	rc = small_smb_init_no_tc(SMB_COM_SESSION_SETUP_ANDX, wct, ses,
1365 				  (void **)&smb_buf);
1366 
1367 	if (rc)
1368 		return rc;
1369 
1370 	sess_data->iov[0].iov_base = (char *)smb_buf;
1371 	sess_data->iov[0].iov_len = be32_to_cpu(smb_buf->smb_buf_length) + 4;
1372 	/*
1373 	 * This variable will be used to clear the buffer
1374 	 * allocated above in case of any error in the calling function.
1375 	 */
1376 	sess_data->buf0_type = CIFS_SMALL_BUFFER;
1377 
1378 	/* 2000 big enough to fit max user, domain, NOS name etc. */
1379 	sess_data->iov[2].iov_base = kmalloc(2000, GFP_KERNEL);
1380 	if (!sess_data->iov[2].iov_base) {
1381 		rc = -ENOMEM;
1382 		goto out_free_smb_buf;
1383 	}
1384 
1385 	return 0;
1386 
1387 out_free_smb_buf:
1388 	cifs_small_buf_release(smb_buf);
1389 	sess_data->iov[0].iov_base = NULL;
1390 	sess_data->iov[0].iov_len = 0;
1391 	sess_data->buf0_type = CIFS_NO_BUFFER;
1392 	return rc;
1393 }
1394 
1395 static void
1396 sess_free_buffer(struct sess_data *sess_data)
1397 {
1398 	struct kvec *iov = sess_data->iov;
1399 
1400 	/*
1401 	 * Zero the session data before freeing, as it might contain sensitive info (keys, etc).
1402 	 * Note that iov[1] is already freed by caller.
1403 	 */
1404 	if (sess_data->buf0_type != CIFS_NO_BUFFER && iov[0].iov_base)
1405 		memzero_explicit(iov[0].iov_base, iov[0].iov_len);
1406 
1407 	free_rsp_buf(sess_data->buf0_type, iov[0].iov_base);
1408 	sess_data->buf0_type = CIFS_NO_BUFFER;
1409 	kfree_sensitive(iov[2].iov_base);
1410 }
1411 
1412 static int
1413 sess_establish_session(struct sess_data *sess_data)
1414 {
1415 	struct cifs_ses *ses = sess_data->ses;
1416 	struct TCP_Server_Info *server = sess_data->server;
1417 
1418 	cifs_server_lock(server);
1419 	if (!server->session_estab) {
1420 		if (server->sign) {
1421 			server->session_key.response =
1422 				kmemdup(ses->auth_key.response,
1423 				ses->auth_key.len, GFP_KERNEL);
1424 			if (!server->session_key.response) {
1425 				cifs_server_unlock(server);
1426 				return -ENOMEM;
1427 			}
1428 			server->session_key.len =
1429 						ses->auth_key.len;
1430 		}
1431 		server->sequence_number = 0x2;
1432 		server->session_estab = true;
1433 	}
1434 	cifs_server_unlock(server);
1435 
1436 	cifs_dbg(FYI, "CIFS session established successfully\n");
1437 	return 0;
1438 }
1439 
1440 static int
1441 sess_sendreceive(struct sess_data *sess_data)
1442 {
1443 	int rc;
1444 	struct smb_hdr *smb_buf = (struct smb_hdr *) sess_data->iov[0].iov_base;
1445 	__u16 count;
1446 	struct kvec rsp_iov = { NULL, 0 };
1447 
1448 	count = sess_data->iov[1].iov_len + sess_data->iov[2].iov_len;
1449 	be32_add_cpu(&smb_buf->smb_buf_length, count);
1450 	put_bcc(count, smb_buf);
1451 
1452 	rc = SendReceive2(sess_data->xid, sess_data->ses,
1453 			  sess_data->iov, 3 /* num_iovecs */,
1454 			  &sess_data->buf0_type,
1455 			  CIFS_LOG_ERROR, &rsp_iov);
1456 	cifs_small_buf_release(sess_data->iov[0].iov_base);
1457 	memcpy(&sess_data->iov[0], &rsp_iov, sizeof(struct kvec));
1458 
1459 	return rc;
1460 }
1461 
1462 static void
1463 sess_auth_ntlmv2(struct sess_data *sess_data)
1464 {
1465 	int rc = 0;
1466 	struct smb_hdr *smb_buf;
1467 	SESSION_SETUP_ANDX *pSMB;
1468 	char *bcc_ptr;
1469 	struct cifs_ses *ses = sess_data->ses;
1470 	struct TCP_Server_Info *server = sess_data->server;
1471 	__u32 capabilities;
1472 	__u16 bytes_remaining;
1473 
1474 	/* old style NTLM sessionsetup */
1475 	/* wct = 13 */
1476 	rc = sess_alloc_buffer(sess_data, 13);
1477 	if (rc)
1478 		goto out;
1479 
1480 	pSMB = (SESSION_SETUP_ANDX *)sess_data->iov[0].iov_base;
1481 	bcc_ptr = sess_data->iov[2].iov_base;
1482 	capabilities = cifs_ssetup_hdr(ses, server, pSMB);
1483 
1484 	pSMB->req_no_secext.Capabilities = cpu_to_le32(capabilities);
1485 
1486 	/* LM2 password would be here if we supported it */
1487 	pSMB->req_no_secext.CaseInsensitivePasswordLength = 0;
1488 
1489 	if (ses->user_name != NULL) {
1490 		/* calculate nlmv2 response and session key */
1491 		rc = setup_ntlmv2_rsp(ses, sess_data->nls_cp);
1492 		if (rc) {
1493 			cifs_dbg(VFS, "Error %d during NTLMv2 authentication\n", rc);
1494 			goto out;
1495 		}
1496 
1497 		memcpy(bcc_ptr, ses->auth_key.response + CIFS_SESS_KEY_SIZE,
1498 				ses->auth_key.len - CIFS_SESS_KEY_SIZE);
1499 		bcc_ptr += ses->auth_key.len - CIFS_SESS_KEY_SIZE;
1500 
1501 		/* set case sensitive password length after tilen may get
1502 		 * assigned, tilen is 0 otherwise.
1503 		 */
1504 		pSMB->req_no_secext.CaseSensitivePasswordLength =
1505 			cpu_to_le16(ses->auth_key.len - CIFS_SESS_KEY_SIZE);
1506 	} else {
1507 		pSMB->req_no_secext.CaseSensitivePasswordLength = 0;
1508 	}
1509 
1510 	if (ses->capabilities & CAP_UNICODE) {
1511 		if (!IS_ALIGNED(sess_data->iov[0].iov_len, 2)) {
1512 			*bcc_ptr = 0;
1513 			bcc_ptr++;
1514 		}
1515 		unicode_ssetup_strings(&bcc_ptr, ses, sess_data->nls_cp);
1516 	} else {
1517 		ascii_ssetup_strings(&bcc_ptr, ses, sess_data->nls_cp);
1518 	}
1519 
1520 
1521 	sess_data->iov[2].iov_len = (long) bcc_ptr -
1522 			(long) sess_data->iov[2].iov_base;
1523 
1524 	rc = sess_sendreceive(sess_data);
1525 	if (rc)
1526 		goto out;
1527 
1528 	pSMB = (SESSION_SETUP_ANDX *)sess_data->iov[0].iov_base;
1529 	smb_buf = (struct smb_hdr *)sess_data->iov[0].iov_base;
1530 
1531 	if (smb_buf->WordCount != 3) {
1532 		rc = -EIO;
1533 		cifs_dbg(VFS, "bad word count %d\n", smb_buf->WordCount);
1534 		goto out;
1535 	}
1536 
1537 	if (le16_to_cpu(pSMB->resp.Action) & GUEST_LOGIN)
1538 		cifs_dbg(FYI, "Guest login\n"); /* BB mark SesInfo struct? */
1539 
1540 	ses->Suid = smb_buf->Uid;   /* UID left in wire format (le) */
1541 	cifs_dbg(FYI, "UID = %llu\n", ses->Suid);
1542 
1543 	bytes_remaining = get_bcc(smb_buf);
1544 	bcc_ptr = pByteArea(smb_buf);
1545 
1546 	/* BB check if Unicode and decode strings */
1547 	if (bytes_remaining == 0) {
1548 		/* no string area to decode, do nothing */
1549 	} else if (smb_buf->Flags2 & SMBFLG2_UNICODE) {
1550 		/* unicode string area must be word-aligned */
1551 		if (!IS_ALIGNED((unsigned long)bcc_ptr - (unsigned long)smb_buf, 2)) {
1552 			++bcc_ptr;
1553 			--bytes_remaining;
1554 		}
1555 		decode_unicode_ssetup(&bcc_ptr, bytes_remaining, ses,
1556 				      sess_data->nls_cp);
1557 	} else {
1558 		decode_ascii_ssetup(&bcc_ptr, bytes_remaining, ses,
1559 				    sess_data->nls_cp);
1560 	}
1561 
1562 	rc = sess_establish_session(sess_data);
1563 out:
1564 	sess_data->result = rc;
1565 	sess_data->func = NULL;
1566 	sess_free_buffer(sess_data);
1567 	kfree_sensitive(ses->auth_key.response);
1568 	ses->auth_key.response = NULL;
1569 }
1570 
1571 #ifdef CONFIG_CIFS_UPCALL
1572 static void
1573 sess_auth_kerberos(struct sess_data *sess_data)
1574 {
1575 	int rc = 0;
1576 	struct smb_hdr *smb_buf;
1577 	SESSION_SETUP_ANDX *pSMB;
1578 	char *bcc_ptr;
1579 	struct cifs_ses *ses = sess_data->ses;
1580 	struct TCP_Server_Info *server = sess_data->server;
1581 	__u32 capabilities;
1582 	__u16 bytes_remaining;
1583 	struct key *spnego_key = NULL;
1584 	struct cifs_spnego_msg *msg;
1585 	u16 blob_len;
1586 
1587 	/* extended security */
1588 	/* wct = 12 */
1589 	rc = sess_alloc_buffer(sess_data, 12);
1590 	if (rc)
1591 		goto out;
1592 
1593 	pSMB = (SESSION_SETUP_ANDX *)sess_data->iov[0].iov_base;
1594 	bcc_ptr = sess_data->iov[2].iov_base;
1595 	capabilities = cifs_ssetup_hdr(ses, server, pSMB);
1596 
1597 	spnego_key = cifs_get_spnego_key(ses, server);
1598 	if (IS_ERR(spnego_key)) {
1599 		rc = PTR_ERR(spnego_key);
1600 		spnego_key = NULL;
1601 		goto out;
1602 	}
1603 
1604 	msg = spnego_key->payload.data[0];
1605 	/*
1606 	 * check version field to make sure that cifs.upcall is
1607 	 * sending us a response in an expected form
1608 	 */
1609 	if (msg->version != CIFS_SPNEGO_UPCALL_VERSION) {
1610 		cifs_dbg(VFS, "incorrect version of cifs.upcall (expected %d but got %d)\n",
1611 			 CIFS_SPNEGO_UPCALL_VERSION, msg->version);
1612 		rc = -EKEYREJECTED;
1613 		goto out_put_spnego_key;
1614 	}
1615 
1616 	kfree_sensitive(ses->auth_key.response);
1617 	ses->auth_key.response = kmemdup(msg->data, msg->sesskey_len,
1618 					 GFP_KERNEL);
1619 	if (!ses->auth_key.response) {
1620 		cifs_dbg(VFS, "Kerberos can't allocate (%u bytes) memory\n",
1621 			 msg->sesskey_len);
1622 		rc = -ENOMEM;
1623 		goto out_put_spnego_key;
1624 	}
1625 	ses->auth_key.len = msg->sesskey_len;
1626 
1627 	pSMB->req.hdr.Flags2 |= SMBFLG2_EXT_SEC;
1628 	capabilities |= CAP_EXTENDED_SECURITY;
1629 	pSMB->req.Capabilities = cpu_to_le32(capabilities);
1630 	sess_data->iov[1].iov_base = msg->data + msg->sesskey_len;
1631 	sess_data->iov[1].iov_len = msg->secblob_len;
1632 	pSMB->req.SecurityBlobLength = cpu_to_le16(sess_data->iov[1].iov_len);
1633 
1634 	if (ses->capabilities & CAP_UNICODE) {
1635 		/* unicode strings must be word aligned */
1636 		if (!IS_ALIGNED(sess_data->iov[0].iov_len + sess_data->iov[1].iov_len, 2)) {
1637 			*bcc_ptr = 0;
1638 			bcc_ptr++;
1639 		}
1640 		unicode_oslm_strings(&bcc_ptr, sess_data->nls_cp);
1641 		unicode_domain_string(&bcc_ptr, ses, sess_data->nls_cp);
1642 	} else {
1643 		/* BB: is this right? */
1644 		ascii_ssetup_strings(&bcc_ptr, ses, sess_data->nls_cp);
1645 	}
1646 
1647 	sess_data->iov[2].iov_len = (long) bcc_ptr -
1648 			(long) sess_data->iov[2].iov_base;
1649 
1650 	rc = sess_sendreceive(sess_data);
1651 	if (rc)
1652 		goto out_put_spnego_key;
1653 
1654 	pSMB = (SESSION_SETUP_ANDX *)sess_data->iov[0].iov_base;
1655 	smb_buf = (struct smb_hdr *)sess_data->iov[0].iov_base;
1656 
1657 	if (smb_buf->WordCount != 4) {
1658 		rc = -EIO;
1659 		cifs_dbg(VFS, "bad word count %d\n", smb_buf->WordCount);
1660 		goto out_put_spnego_key;
1661 	}
1662 
1663 	if (le16_to_cpu(pSMB->resp.Action) & GUEST_LOGIN)
1664 		cifs_dbg(FYI, "Guest login\n"); /* BB mark SesInfo struct? */
1665 
1666 	ses->Suid = smb_buf->Uid;   /* UID left in wire format (le) */
1667 	cifs_dbg(FYI, "UID = %llu\n", ses->Suid);
1668 
1669 	bytes_remaining = get_bcc(smb_buf);
1670 	bcc_ptr = pByteArea(smb_buf);
1671 
1672 	blob_len = le16_to_cpu(pSMB->resp.SecurityBlobLength);
1673 	if (blob_len > bytes_remaining) {
1674 		cifs_dbg(VFS, "bad security blob length %d\n",
1675 				blob_len);
1676 		rc = -EINVAL;
1677 		goto out_put_spnego_key;
1678 	}
1679 	bcc_ptr += blob_len;
1680 	bytes_remaining -= blob_len;
1681 
1682 	/* BB check if Unicode and decode strings */
1683 	if (bytes_remaining == 0) {
1684 		/* no string area to decode, do nothing */
1685 	} else if (smb_buf->Flags2 & SMBFLG2_UNICODE) {
1686 		/* unicode string area must be word-aligned */
1687 		if (!IS_ALIGNED((unsigned long)bcc_ptr - (unsigned long)smb_buf, 2)) {
1688 			++bcc_ptr;
1689 			--bytes_remaining;
1690 		}
1691 		decode_unicode_ssetup(&bcc_ptr, bytes_remaining, ses,
1692 				      sess_data->nls_cp);
1693 	} else {
1694 		decode_ascii_ssetup(&bcc_ptr, bytes_remaining, ses,
1695 				    sess_data->nls_cp);
1696 	}
1697 
1698 	rc = sess_establish_session(sess_data);
1699 out_put_spnego_key:
1700 	key_invalidate(spnego_key);
1701 	key_put(spnego_key);
1702 out:
1703 	sess_data->result = rc;
1704 	sess_data->func = NULL;
1705 	sess_free_buffer(sess_data);
1706 	kfree_sensitive(ses->auth_key.response);
1707 	ses->auth_key.response = NULL;
1708 }
1709 
1710 #endif /* ! CONFIG_CIFS_UPCALL */
1711 
1712 /*
1713  * The required kvec buffers have to be allocated before calling this
1714  * function.
1715  */
1716 static int
1717 _sess_auth_rawntlmssp_assemble_req(struct sess_data *sess_data)
1718 {
1719 	SESSION_SETUP_ANDX *pSMB;
1720 	struct cifs_ses *ses = sess_data->ses;
1721 	struct TCP_Server_Info *server = sess_data->server;
1722 	__u32 capabilities;
1723 	char *bcc_ptr;
1724 
1725 	pSMB = (SESSION_SETUP_ANDX *)sess_data->iov[0].iov_base;
1726 
1727 	capabilities = cifs_ssetup_hdr(ses, server, pSMB);
1728 	if ((pSMB->req.hdr.Flags2 & SMBFLG2_UNICODE) == 0) {
1729 		cifs_dbg(VFS, "NTLMSSP requires Unicode support\n");
1730 		return -ENOSYS;
1731 	}
1732 
1733 	pSMB->req.hdr.Flags2 |= SMBFLG2_EXT_SEC;
1734 	capabilities |= CAP_EXTENDED_SECURITY;
1735 	pSMB->req.Capabilities |= cpu_to_le32(capabilities);
1736 
1737 	bcc_ptr = sess_data->iov[2].iov_base;
1738 	/* unicode strings must be word aligned */
1739 	if (!IS_ALIGNED(sess_data->iov[0].iov_len + sess_data->iov[1].iov_len, 2)) {
1740 		*bcc_ptr = 0;
1741 		bcc_ptr++;
1742 	}
1743 	unicode_oslm_strings(&bcc_ptr, sess_data->nls_cp);
1744 
1745 	sess_data->iov[2].iov_len = (long) bcc_ptr -
1746 					(long) sess_data->iov[2].iov_base;
1747 
1748 	return 0;
1749 }
1750 
1751 static void
1752 sess_auth_rawntlmssp_authenticate(struct sess_data *sess_data);
1753 
1754 static void
1755 sess_auth_rawntlmssp_negotiate(struct sess_data *sess_data)
1756 {
1757 	int rc;
1758 	struct smb_hdr *smb_buf;
1759 	SESSION_SETUP_ANDX *pSMB;
1760 	struct cifs_ses *ses = sess_data->ses;
1761 	struct TCP_Server_Info *server = sess_data->server;
1762 	__u16 bytes_remaining;
1763 	char *bcc_ptr;
1764 	unsigned char *ntlmsspblob = NULL;
1765 	u16 blob_len;
1766 
1767 	cifs_dbg(FYI, "rawntlmssp session setup negotiate phase\n");
1768 
1769 	/*
1770 	 * if memory allocation is successful, caller of this function
1771 	 * frees it.
1772 	 */
1773 	ses->ntlmssp = kmalloc(sizeof(struct ntlmssp_auth), GFP_KERNEL);
1774 	if (!ses->ntlmssp) {
1775 		rc = -ENOMEM;
1776 		goto out;
1777 	}
1778 	ses->ntlmssp->sesskey_per_smbsess = false;
1779 
1780 	/* wct = 12 */
1781 	rc = sess_alloc_buffer(sess_data, 12);
1782 	if (rc)
1783 		goto out;
1784 
1785 	pSMB = (SESSION_SETUP_ANDX *)sess_data->iov[0].iov_base;
1786 
1787 	/* Build security blob before we assemble the request */
1788 	rc = build_ntlmssp_negotiate_blob(&ntlmsspblob,
1789 				     &blob_len, ses, server,
1790 				     sess_data->nls_cp);
1791 	if (rc)
1792 		goto out_free_ntlmsspblob;
1793 
1794 	sess_data->iov[1].iov_len = blob_len;
1795 	sess_data->iov[1].iov_base = ntlmsspblob;
1796 	pSMB->req.SecurityBlobLength = cpu_to_le16(blob_len);
1797 
1798 	rc = _sess_auth_rawntlmssp_assemble_req(sess_data);
1799 	if (rc)
1800 		goto out_free_ntlmsspblob;
1801 
1802 	rc = sess_sendreceive(sess_data);
1803 
1804 	pSMB = (SESSION_SETUP_ANDX *)sess_data->iov[0].iov_base;
1805 	smb_buf = (struct smb_hdr *)sess_data->iov[0].iov_base;
1806 
1807 	/* If true, rc here is expected and not an error */
1808 	if (sess_data->buf0_type != CIFS_NO_BUFFER &&
1809 	    smb_buf->Status.CifsError ==
1810 			cpu_to_le32(NT_STATUS_MORE_PROCESSING_REQUIRED))
1811 		rc = 0;
1812 
1813 	if (rc)
1814 		goto out_free_ntlmsspblob;
1815 
1816 	cifs_dbg(FYI, "rawntlmssp session setup challenge phase\n");
1817 
1818 	if (smb_buf->WordCount != 4) {
1819 		rc = -EIO;
1820 		cifs_dbg(VFS, "bad word count %d\n", smb_buf->WordCount);
1821 		goto out_free_ntlmsspblob;
1822 	}
1823 
1824 	ses->Suid = smb_buf->Uid;   /* UID left in wire format (le) */
1825 	cifs_dbg(FYI, "UID = %llu\n", ses->Suid);
1826 
1827 	bytes_remaining = get_bcc(smb_buf);
1828 	bcc_ptr = pByteArea(smb_buf);
1829 
1830 	blob_len = le16_to_cpu(pSMB->resp.SecurityBlobLength);
1831 	if (blob_len > bytes_remaining) {
1832 		cifs_dbg(VFS, "bad security blob length %d\n",
1833 				blob_len);
1834 		rc = -EINVAL;
1835 		goto out_free_ntlmsspblob;
1836 	}
1837 
1838 	rc = decode_ntlmssp_challenge(bcc_ptr, blob_len, ses);
1839 
1840 out_free_ntlmsspblob:
1841 	kfree_sensitive(ntlmsspblob);
1842 out:
1843 	sess_free_buffer(sess_data);
1844 
1845 	if (!rc) {
1846 		sess_data->func = sess_auth_rawntlmssp_authenticate;
1847 		return;
1848 	}
1849 
1850 	/* Else error. Cleanup */
1851 	kfree_sensitive(ses->auth_key.response);
1852 	ses->auth_key.response = NULL;
1853 	kfree_sensitive(ses->ntlmssp);
1854 	ses->ntlmssp = NULL;
1855 
1856 	sess_data->func = NULL;
1857 	sess_data->result = rc;
1858 }
1859 
1860 static void
1861 sess_auth_rawntlmssp_authenticate(struct sess_data *sess_data)
1862 {
1863 	int rc;
1864 	struct smb_hdr *smb_buf;
1865 	SESSION_SETUP_ANDX *pSMB;
1866 	struct cifs_ses *ses = sess_data->ses;
1867 	struct TCP_Server_Info *server = sess_data->server;
1868 	__u16 bytes_remaining;
1869 	char *bcc_ptr;
1870 	unsigned char *ntlmsspblob = NULL;
1871 	u16 blob_len;
1872 
1873 	cifs_dbg(FYI, "rawntlmssp session setup authenticate phase\n");
1874 
1875 	/* wct = 12 */
1876 	rc = sess_alloc_buffer(sess_data, 12);
1877 	if (rc)
1878 		goto out;
1879 
1880 	/* Build security blob before we assemble the request */
1881 	pSMB = (SESSION_SETUP_ANDX *)sess_data->iov[0].iov_base;
1882 	smb_buf = (struct smb_hdr *)pSMB;
1883 	rc = build_ntlmssp_auth_blob(&ntlmsspblob,
1884 					&blob_len, ses, server,
1885 					sess_data->nls_cp);
1886 	if (rc)
1887 		goto out_free_ntlmsspblob;
1888 	sess_data->iov[1].iov_len = blob_len;
1889 	sess_data->iov[1].iov_base = ntlmsspblob;
1890 	pSMB->req.SecurityBlobLength = cpu_to_le16(blob_len);
1891 	/*
1892 	 * Make sure that we tell the server that we are using
1893 	 * the uid that it just gave us back on the response
1894 	 * (challenge)
1895 	 */
1896 	smb_buf->Uid = ses->Suid;
1897 
1898 	rc = _sess_auth_rawntlmssp_assemble_req(sess_data);
1899 	if (rc)
1900 		goto out_free_ntlmsspblob;
1901 
1902 	rc = sess_sendreceive(sess_data);
1903 	if (rc)
1904 		goto out_free_ntlmsspblob;
1905 
1906 	pSMB = (SESSION_SETUP_ANDX *)sess_data->iov[0].iov_base;
1907 	smb_buf = (struct smb_hdr *)sess_data->iov[0].iov_base;
1908 	if (smb_buf->WordCount != 4) {
1909 		rc = -EIO;
1910 		cifs_dbg(VFS, "bad word count %d\n", smb_buf->WordCount);
1911 		goto out_free_ntlmsspblob;
1912 	}
1913 
1914 	if (le16_to_cpu(pSMB->resp.Action) & GUEST_LOGIN)
1915 		cifs_dbg(FYI, "Guest login\n"); /* BB mark SesInfo struct? */
1916 
1917 	if (ses->Suid != smb_buf->Uid) {
1918 		ses->Suid = smb_buf->Uid;
1919 		cifs_dbg(FYI, "UID changed! new UID = %llu\n", ses->Suid);
1920 	}
1921 
1922 	bytes_remaining = get_bcc(smb_buf);
1923 	bcc_ptr = pByteArea(smb_buf);
1924 	blob_len = le16_to_cpu(pSMB->resp.SecurityBlobLength);
1925 	if (blob_len > bytes_remaining) {
1926 		cifs_dbg(VFS, "bad security blob length %d\n",
1927 				blob_len);
1928 		rc = -EINVAL;
1929 		goto out_free_ntlmsspblob;
1930 	}
1931 	bcc_ptr += blob_len;
1932 	bytes_remaining -= blob_len;
1933 
1934 
1935 	/* BB check if Unicode and decode strings */
1936 	if (bytes_remaining == 0) {
1937 		/* no string area to decode, do nothing */
1938 	} else if (smb_buf->Flags2 & SMBFLG2_UNICODE) {
1939 		/* unicode string area must be word-aligned */
1940 		if (!IS_ALIGNED((unsigned long)bcc_ptr - (unsigned long)smb_buf, 2)) {
1941 			++bcc_ptr;
1942 			--bytes_remaining;
1943 		}
1944 		decode_unicode_ssetup(&bcc_ptr, bytes_remaining, ses,
1945 				      sess_data->nls_cp);
1946 	} else {
1947 		decode_ascii_ssetup(&bcc_ptr, bytes_remaining, ses,
1948 				    sess_data->nls_cp);
1949 	}
1950 
1951 out_free_ntlmsspblob:
1952 	kfree_sensitive(ntlmsspblob);
1953 out:
1954 	sess_free_buffer(sess_data);
1955 
1956 	if (!rc)
1957 		rc = sess_establish_session(sess_data);
1958 
1959 	/* Cleanup */
1960 	kfree_sensitive(ses->auth_key.response);
1961 	ses->auth_key.response = NULL;
1962 	kfree_sensitive(ses->ntlmssp);
1963 	ses->ntlmssp = NULL;
1964 
1965 	sess_data->func = NULL;
1966 	sess_data->result = rc;
1967 }
1968 
1969 static int select_sec(struct sess_data *sess_data)
1970 {
1971 	int type;
1972 	struct cifs_ses *ses = sess_data->ses;
1973 	struct TCP_Server_Info *server = sess_data->server;
1974 
1975 	type = cifs_select_sectype(server, ses->sectype);
1976 	cifs_dbg(FYI, "sess setup type %d\n", type);
1977 	if (type == Unspecified) {
1978 		cifs_dbg(VFS, "Unable to select appropriate authentication method!\n");
1979 		return -EINVAL;
1980 	}
1981 
1982 	switch (type) {
1983 	case NTLMv2:
1984 		sess_data->func = sess_auth_ntlmv2;
1985 		break;
1986 	case Kerberos:
1987 #ifdef CONFIG_CIFS_UPCALL
1988 		sess_data->func = sess_auth_kerberos;
1989 		break;
1990 #else
1991 		cifs_dbg(VFS, "Kerberos negotiated but upcall support disabled!\n");
1992 		return -ENOSYS;
1993 #endif /* CONFIG_CIFS_UPCALL */
1994 	case RawNTLMSSP:
1995 		sess_data->func = sess_auth_rawntlmssp_negotiate;
1996 		break;
1997 	default:
1998 		cifs_dbg(VFS, "secType %d not supported!\n", type);
1999 		return -ENOSYS;
2000 	}
2001 
2002 	return 0;
2003 }
2004 
2005 int CIFS_SessSetup(const unsigned int xid, struct cifs_ses *ses,
2006 		   struct TCP_Server_Info *server,
2007 		   const struct nls_table *nls_cp)
2008 {
2009 	int rc = 0;
2010 	struct sess_data *sess_data;
2011 
2012 	if (ses == NULL) {
2013 		WARN(1, "%s: ses == NULL!", __func__);
2014 		return -EINVAL;
2015 	}
2016 
2017 	sess_data = kzalloc(sizeof(struct sess_data), GFP_KERNEL);
2018 	if (!sess_data)
2019 		return -ENOMEM;
2020 
2021 	sess_data->xid = xid;
2022 	sess_data->ses = ses;
2023 	sess_data->server = server;
2024 	sess_data->buf0_type = CIFS_NO_BUFFER;
2025 	sess_data->nls_cp = (struct nls_table *) nls_cp;
2026 
2027 	rc = select_sec(sess_data);
2028 	if (rc)
2029 		goto out;
2030 
2031 	while (sess_data->func)
2032 		sess_data->func(sess_data);
2033 
2034 	/* Store result before we free sess_data */
2035 	rc = sess_data->result;
2036 
2037 out:
2038 	kfree_sensitive(sess_data);
2039 	return rc;
2040 }
2041 #endif /* CONFIG_CIFS_ALLOW_INSECURE_LEGACY */
2042