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