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