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