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