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