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