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