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