xref: /kernel/linux/linux-5.10/fs/cifs/sess.c (revision 8c2ecf20)
1/*
2 *   fs/cifs/sess.c
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 *   This library is free software; you can redistribute it and/or modify
10 *   it under the terms of the GNU Lesser General Public License as published
11 *   by the Free Software Foundation; either version 2.1 of the License, or
12 *   (at your option) any later version.
13 *
14 *   This library is distributed in the hope that it will be useful,
15 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
16 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See
17 *   the GNU Lesser General Public License for more details.
18 *
19 *   You should have received a copy of the GNU Lesser General Public License
20 *   along with this library; if not, write to the Free Software
21 *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22 */
23
24#include "cifspdu.h"
25#include "cifsglob.h"
26#include "cifsproto.h"
27#include "cifs_unicode.h"
28#include "cifs_debug.h"
29#include "ntlmssp.h"
30#include "nterr.h"
31#include <linux/utsname.h>
32#include <linux/slab.h>
33#include "cifs_spnego.h"
34#include "smb2proto.h"
35
36bool
37is_server_using_iface(struct TCP_Server_Info *server,
38		      struct cifs_server_iface *iface)
39{
40	struct sockaddr_in *i4 = (struct sockaddr_in *)&iface->sockaddr;
41	struct sockaddr_in6 *i6 = (struct sockaddr_in6 *)&iface->sockaddr;
42	struct sockaddr_in *s4 = (struct sockaddr_in *)&server->dstaddr;
43	struct sockaddr_in6 *s6 = (struct sockaddr_in6 *)&server->dstaddr;
44
45	if (server->dstaddr.ss_family != iface->sockaddr.ss_family)
46		return false;
47	if (server->dstaddr.ss_family == AF_INET) {
48		if (s4->sin_addr.s_addr != i4->sin_addr.s_addr)
49			return false;
50	} else if (server->dstaddr.ss_family == AF_INET6) {
51		if (memcmp(&s6->sin6_addr, &i6->sin6_addr,
52			   sizeof(i6->sin6_addr)) != 0)
53			return false;
54	} else {
55		/* unknown family.. */
56		return false;
57	}
58	return true;
59}
60
61bool is_ses_using_iface(struct cifs_ses *ses, struct cifs_server_iface *iface)
62{
63	int i;
64
65	for (i = 0; i < ses->chan_count; i++) {
66		if (is_server_using_iface(ses->chans[i].server, iface))
67			return true;
68	}
69	return false;
70}
71
72/* returns number of channels added */
73int cifs_try_adding_channels(struct cifs_ses *ses)
74{
75	int old_chan_count = ses->chan_count;
76	int left = ses->chan_max - ses->chan_count;
77	int i = 0;
78	int rc = 0;
79	int tries = 0;
80	struct cifs_server_iface *ifaces = NULL;
81	size_t iface_count;
82
83	if (left <= 0) {
84		cifs_dbg(FYI,
85			 "ses already at max_channels (%zu), nothing to open\n",
86			 ses->chan_max);
87		return 0;
88	}
89
90	if (ses->server->dialect < SMB30_PROT_ID) {
91		cifs_dbg(VFS, "multichannel is not supported on this protocol version, use 3.0 or above\n");
92		return 0;
93	}
94
95	if (!(ses->server->capabilities & SMB2_GLOBAL_CAP_MULTI_CHANNEL)) {
96		cifs_dbg(VFS, "server %s does not support multichannel\n", ses->server->hostname);
97		ses->chan_max = 1;
98		return 0;
99	}
100
101	/*
102	 * Make a copy of the iface list at the time and use that
103	 * instead so as to not hold the iface spinlock for opening
104	 * channels
105	 */
106	spin_lock(&ses->iface_lock);
107	iface_count = ses->iface_count;
108	if (iface_count <= 0) {
109		spin_unlock(&ses->iface_lock);
110		cifs_dbg(VFS, "no iface list available to open channels\n");
111		return 0;
112	}
113	ifaces = kmemdup(ses->iface_list, iface_count*sizeof(*ifaces),
114			 GFP_ATOMIC);
115	if (!ifaces) {
116		spin_unlock(&ses->iface_lock);
117		return 0;
118	}
119	spin_unlock(&ses->iface_lock);
120
121	/*
122	 * Keep connecting to same, fastest, iface for all channels as
123	 * long as its RSS. Try next fastest one if not RSS or channel
124	 * creation fails.
125	 */
126	while (left > 0) {
127		struct cifs_server_iface *iface;
128
129		tries++;
130		if (tries > 3*ses->chan_max) {
131			cifs_dbg(FYI, "too many channel open attempts (%d channels left to open)\n",
132				 left);
133			break;
134		}
135
136		iface = &ifaces[i];
137		if (is_ses_using_iface(ses, iface) && !iface->rss_capable) {
138			i = (i+1) % iface_count;
139			continue;
140		}
141
142		rc = cifs_ses_add_channel(ses, iface);
143		if (rc) {
144			cifs_dbg(FYI, "failed to open extra channel on iface#%d rc=%d\n",
145				 i, rc);
146			i = (i+1) % iface_count;
147			continue;
148		}
149
150		cifs_dbg(FYI, "successfully opened new channel on iface#%d\n",
151			 i);
152		left--;
153	}
154
155	kfree(ifaces);
156	return ses->chan_count - old_chan_count;
157}
158
159/*
160 * If server is a channel of ses, return the corresponding enclosing
161 * cifs_chan otherwise return NULL.
162 */
163struct cifs_chan *
164cifs_ses_find_chan(struct cifs_ses *ses, struct TCP_Server_Info *server)
165{
166	int i;
167
168	for (i = 0; i < ses->chan_count; i++) {
169		if (ses->chans[i].server == server)
170			return &ses->chans[i];
171	}
172	return NULL;
173}
174
175int
176cifs_ses_add_channel(struct cifs_ses *ses, struct cifs_server_iface *iface)
177{
178	struct cifs_chan *chan;
179	struct smb_vol vol = {NULL};
180	static const char unc_fmt[] = "\\%s\\foo";
181	char unc[sizeof(unc_fmt)+SERVER_NAME_LEN_WITH_NULL] = {0};
182	struct sockaddr_in *ipv4 = (struct sockaddr_in *)&iface->sockaddr;
183	struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)&iface->sockaddr;
184	int rc;
185	unsigned int xid = get_xid();
186
187	if (iface->sockaddr.ss_family == AF_INET)
188		cifs_dbg(FYI, "adding channel to ses %p (speed:%zu bps rdma:%s ip:%pI4)\n",
189			 ses, iface->speed, iface->rdma_capable ? "yes" : "no",
190			 &ipv4->sin_addr);
191	else
192		cifs_dbg(FYI, "adding channel to ses %p (speed:%zu bps rdma:%s ip:%pI4)\n",
193			 ses, iface->speed, iface->rdma_capable ? "yes" : "no",
194			 &ipv6->sin6_addr);
195
196	/*
197	 * Setup a smb_vol with mostly the same info as the existing
198	 * session and overwrite it with the requested iface data.
199	 *
200	 * We need to setup at least the fields used for negprot and
201	 * sesssetup.
202	 *
203	 * We only need the volume here, so we can reuse memory from
204	 * the session and server without caring about memory
205	 * management.
206	 */
207
208	/* Always make new connection for now (TODO?) */
209	vol.nosharesock = true;
210
211	/* Auth */
212	vol.domainauto = ses->domainAuto;
213	vol.domainname = ses->domainName;
214	vol.username = ses->user_name;
215	vol.password = ses->password;
216	vol.sectype = ses->sectype;
217	vol.sign = ses->sign;
218
219	/* UNC and paths */
220	/* XXX: Use ses->server->hostname? */
221	sprintf(unc, unc_fmt, ses->serverName);
222	vol.UNC = unc;
223	vol.prepath = "";
224
225	/* Reuse same version as master connection */
226	vol.vals = ses->server->vals;
227	vol.ops = ses->server->ops;
228
229	vol.noblocksnd = ses->server->noblocksnd;
230	vol.noautotune = ses->server->noautotune;
231	vol.sockopt_tcp_nodelay = ses->server->tcp_nodelay;
232	vol.echo_interval = ses->server->echo_interval / HZ;
233	vol.max_credits = ses->server->max_credits;
234
235	/*
236	 * This will be used for encoding/decoding user/domain/pw
237	 * during sess setup auth.
238	 *
239	 * XXX: We use the default for simplicity but the proper way
240	 * would be to use the one that ses used, which is not
241	 * stored. This might break when dealing with non-ascii
242	 * strings.
243	 */
244	vol.local_nls = load_nls_default();
245
246	/* Use RDMA if possible */
247	vol.rdma = iface->rdma_capable;
248	memcpy(&vol.dstaddr, &iface->sockaddr, sizeof(struct sockaddr_storage));
249
250	/* reuse master con client guid */
251	memcpy(&vol.client_guid, ses->server->client_guid,
252	       SMB2_CLIENT_GUID_SIZE);
253	vol.use_client_guid = true;
254
255	mutex_lock(&ses->session_mutex);
256
257	chan = ses->binding_chan = &ses->chans[ses->chan_count];
258	chan->server = cifs_get_tcp_session(&vol);
259	if (IS_ERR(chan->server)) {
260		rc = PTR_ERR(chan->server);
261		chan->server = NULL;
262		goto out;
263	}
264	spin_lock(&cifs_tcp_ses_lock);
265	chan->server->is_channel = true;
266	spin_unlock(&cifs_tcp_ses_lock);
267
268	/*
269	 * We need to allocate the server crypto now as we will need
270	 * to sign packets before we generate the channel signing key
271	 * (we sign with the session key)
272	 */
273	rc = smb311_crypto_shash_allocate(chan->server);
274	if (rc) {
275		cifs_dbg(VFS, "%s: crypto alloc failed\n", __func__);
276		goto out;
277	}
278
279	ses->binding = true;
280	rc = cifs_negotiate_protocol(xid, ses);
281	if (rc)
282		goto out;
283
284	rc = cifs_setup_session(xid, ses, vol.local_nls);
285	if (rc)
286		goto out;
287
288	/* success, put it on the list
289	 * XXX: sharing ses between 2 tcp servers is not possible, the
290	 * way "internal" linked lists works in linux makes element
291	 * only able to belong to one list
292	 *
293	 * the binding session is already established so the rest of
294	 * the code should be able to look it up, no need to add the
295	 * ses to the new server.
296	 */
297
298	ses->chan_count++;
299	atomic_set(&ses->chan_seq, 0);
300out:
301	ses->binding = false;
302	ses->binding_chan = NULL;
303	mutex_unlock(&ses->session_mutex);
304
305	if (rc && chan->server)
306		cifs_put_tcp_session(chan->server, 0);
307	unload_nls(vol.local_nls);
308
309	free_xid(xid);
310	return rc;
311}
312
313static __u32 cifs_ssetup_hdr(struct cifs_ses *ses, SESSION_SETUP_ANDX *pSMB)
314{
315	__u32 capabilities = 0;
316
317	/* init fields common to all four types of SessSetup */
318	/* Note that offsets for first seven fields in req struct are same  */
319	/*	in CIFS Specs so does not matter which of 3 forms of struct */
320	/*	that we use in next few lines                               */
321	/* Note that header is initialized to zero in header_assemble */
322	pSMB->req.AndXCommand = 0xFF;
323	pSMB->req.MaxBufferSize = cpu_to_le16(min_t(u32,
324					CIFSMaxBufSize + MAX_CIFS_HDR_SIZE - 4,
325					USHRT_MAX));
326	pSMB->req.MaxMpxCount = cpu_to_le16(ses->server->maxReq);
327	pSMB->req.VcNumber = cpu_to_le16(1);
328
329	/* Now no need to set SMBFLG_CASELESS or obsolete CANONICAL PATH */
330
331	/* BB verify whether signing required on neg or just on auth frame
332	   (and NTLM case) */
333
334	capabilities = CAP_LARGE_FILES | CAP_NT_SMBS | CAP_LEVEL_II_OPLOCKS |
335			CAP_LARGE_WRITE_X | CAP_LARGE_READ_X;
336
337	if (ses->server->sign)
338		pSMB->req.hdr.Flags2 |= SMBFLG2_SECURITY_SIGNATURE;
339
340	if (ses->capabilities & CAP_UNICODE) {
341		pSMB->req.hdr.Flags2 |= SMBFLG2_UNICODE;
342		capabilities |= CAP_UNICODE;
343	}
344	if (ses->capabilities & CAP_STATUS32) {
345		pSMB->req.hdr.Flags2 |= SMBFLG2_ERR_STATUS;
346		capabilities |= CAP_STATUS32;
347	}
348	if (ses->capabilities & CAP_DFS) {
349		pSMB->req.hdr.Flags2 |= SMBFLG2_DFS;
350		capabilities |= CAP_DFS;
351	}
352	if (ses->capabilities & CAP_UNIX)
353		capabilities |= CAP_UNIX;
354
355	return capabilities;
356}
357
358static void
359unicode_oslm_strings(char **pbcc_area, const struct nls_table *nls_cp)
360{
361	char *bcc_ptr = *pbcc_area;
362	int bytes_ret = 0;
363
364	/* Copy OS version */
365	bytes_ret = cifs_strtoUTF16((__le16 *)bcc_ptr, "Linux version ", 32,
366				    nls_cp);
367	bcc_ptr += 2 * bytes_ret;
368	bytes_ret = cifs_strtoUTF16((__le16 *) bcc_ptr, init_utsname()->release,
369				    32, nls_cp);
370	bcc_ptr += 2 * bytes_ret;
371	bcc_ptr += 2; /* trailing null */
372
373	bytes_ret = cifs_strtoUTF16((__le16 *) bcc_ptr, CIFS_NETWORK_OPSYS,
374				    32, nls_cp);
375	bcc_ptr += 2 * bytes_ret;
376	bcc_ptr += 2; /* trailing null */
377
378	*pbcc_area = bcc_ptr;
379}
380
381static void unicode_domain_string(char **pbcc_area, struct cifs_ses *ses,
382				   const struct nls_table *nls_cp)
383{
384	char *bcc_ptr = *pbcc_area;
385	int bytes_ret = 0;
386
387	/* copy domain */
388	if (ses->domainName == NULL) {
389		/* Sending null domain better than using a bogus domain name (as
390		we did briefly in 2.6.18) since server will use its default */
391		*bcc_ptr = 0;
392		*(bcc_ptr+1) = 0;
393		bytes_ret = 0;
394	} else
395		bytes_ret = cifs_strtoUTF16((__le16 *) bcc_ptr, ses->domainName,
396					    CIFS_MAX_DOMAINNAME_LEN, nls_cp);
397	bcc_ptr += 2 * bytes_ret;
398	bcc_ptr += 2;  /* account for null terminator */
399
400	*pbcc_area = bcc_ptr;
401}
402
403
404static void unicode_ssetup_strings(char **pbcc_area, struct cifs_ses *ses,
405				   const struct nls_table *nls_cp)
406{
407	char *bcc_ptr = *pbcc_area;
408	int bytes_ret = 0;
409
410	/* BB FIXME add check that strings total less
411	than 335 or will need to send them as arrays */
412
413	/* unicode strings, must be word aligned before the call */
414/*	if ((long) bcc_ptr % 2)	{
415		*bcc_ptr = 0;
416		bcc_ptr++;
417	} */
418	/* copy user */
419	if (ses->user_name == NULL) {
420		/* null user mount */
421		*bcc_ptr = 0;
422		*(bcc_ptr+1) = 0;
423	} else {
424		bytes_ret = cifs_strtoUTF16((__le16 *) bcc_ptr, ses->user_name,
425					    CIFS_MAX_USERNAME_LEN, nls_cp);
426	}
427	bcc_ptr += 2 * bytes_ret;
428	bcc_ptr += 2; /* account for null termination */
429
430	unicode_domain_string(&bcc_ptr, ses, nls_cp);
431	unicode_oslm_strings(&bcc_ptr, nls_cp);
432
433	*pbcc_area = bcc_ptr;
434}
435
436static void ascii_ssetup_strings(char **pbcc_area, struct cifs_ses *ses,
437				 const struct nls_table *nls_cp)
438{
439	char *bcc_ptr = *pbcc_area;
440	int len;
441
442	/* copy user */
443	/* BB what about null user mounts - check that we do this BB */
444	/* copy user */
445	if (ses->user_name != NULL) {
446		len = strscpy(bcc_ptr, ses->user_name, CIFS_MAX_USERNAME_LEN);
447		if (WARN_ON_ONCE(len < 0))
448			len = CIFS_MAX_USERNAME_LEN - 1;
449		bcc_ptr += len;
450	}
451	/* else null user mount */
452	*bcc_ptr = 0;
453	bcc_ptr++; /* account for null termination */
454
455	/* copy domain */
456	if (ses->domainName != NULL) {
457		len = strscpy(bcc_ptr, ses->domainName, CIFS_MAX_DOMAINNAME_LEN);
458		if (WARN_ON_ONCE(len < 0))
459			len = CIFS_MAX_DOMAINNAME_LEN - 1;
460		bcc_ptr += len;
461	} /* else we will send a null domain name
462	     so the server will default to its own domain */
463	*bcc_ptr = 0;
464	bcc_ptr++;
465
466	/* BB check for overflow here */
467
468	strcpy(bcc_ptr, "Linux version ");
469	bcc_ptr += strlen("Linux version ");
470	strcpy(bcc_ptr, init_utsname()->release);
471	bcc_ptr += strlen(init_utsname()->release) + 1;
472
473	strcpy(bcc_ptr, CIFS_NETWORK_OPSYS);
474	bcc_ptr += strlen(CIFS_NETWORK_OPSYS) + 1;
475
476	*pbcc_area = bcc_ptr;
477}
478
479static void
480decode_unicode_ssetup(char **pbcc_area, int bleft, struct cifs_ses *ses,
481		      const struct nls_table *nls_cp)
482{
483	int len;
484	char *data = *pbcc_area;
485
486	cifs_dbg(FYI, "bleft %d\n", bleft);
487
488	kfree(ses->serverOS);
489	ses->serverOS = cifs_strndup_from_utf16(data, bleft, true, nls_cp);
490	cifs_dbg(FYI, "serverOS=%s\n", ses->serverOS);
491	len = (UniStrnlen((wchar_t *) data, bleft / 2) * 2) + 2;
492	data += len;
493	bleft -= len;
494	if (bleft <= 0)
495		return;
496
497	kfree(ses->serverNOS);
498	ses->serverNOS = cifs_strndup_from_utf16(data, bleft, true, nls_cp);
499	cifs_dbg(FYI, "serverNOS=%s\n", ses->serverNOS);
500	len = (UniStrnlen((wchar_t *) data, bleft / 2) * 2) + 2;
501	data += len;
502	bleft -= len;
503	if (bleft <= 0)
504		return;
505
506	kfree(ses->serverDomain);
507	ses->serverDomain = cifs_strndup_from_utf16(data, bleft, true, nls_cp);
508	cifs_dbg(FYI, "serverDomain=%s\n", ses->serverDomain);
509
510	return;
511}
512
513static void decode_ascii_ssetup(char **pbcc_area, __u16 bleft,
514				struct cifs_ses *ses,
515				const struct nls_table *nls_cp)
516{
517	int len;
518	char *bcc_ptr = *pbcc_area;
519
520	cifs_dbg(FYI, "decode sessetup ascii. bleft %d\n", bleft);
521
522	len = strnlen(bcc_ptr, bleft);
523	if (len >= bleft)
524		return;
525
526	kfree(ses->serverOS);
527
528	ses->serverOS = kmalloc(len + 1, GFP_KERNEL);
529	if (ses->serverOS) {
530		memcpy(ses->serverOS, bcc_ptr, len);
531		ses->serverOS[len] = 0;
532		if (strncmp(ses->serverOS, "OS/2", 4) == 0)
533			cifs_dbg(FYI, "OS/2 server\n");
534	}
535
536	bcc_ptr += len + 1;
537	bleft -= len + 1;
538
539	len = strnlen(bcc_ptr, bleft);
540	if (len >= bleft)
541		return;
542
543	kfree(ses->serverNOS);
544
545	ses->serverNOS = kmalloc(len + 1, GFP_KERNEL);
546	if (ses->serverNOS) {
547		memcpy(ses->serverNOS, bcc_ptr, len);
548		ses->serverNOS[len] = 0;
549	}
550
551	bcc_ptr += len + 1;
552	bleft -= len + 1;
553
554	len = strnlen(bcc_ptr, bleft);
555	if (len > bleft)
556		return;
557
558	/* No domain field in LANMAN case. Domain is
559	   returned by old servers in the SMB negprot response */
560	/* BB For newer servers which do not support Unicode,
561	   but thus do return domain here we could add parsing
562	   for it later, but it is not very important */
563	cifs_dbg(FYI, "ascii: bytes left %d\n", bleft);
564}
565
566int decode_ntlmssp_challenge(char *bcc_ptr, int blob_len,
567				    struct cifs_ses *ses)
568{
569	unsigned int tioffset; /* challenge message target info area */
570	unsigned int tilen; /* challenge message target info area length  */
571
572	CHALLENGE_MESSAGE *pblob = (CHALLENGE_MESSAGE *)bcc_ptr;
573
574	if (blob_len < sizeof(CHALLENGE_MESSAGE)) {
575		cifs_dbg(VFS, "challenge blob len %d too small\n", blob_len);
576		return -EINVAL;
577	}
578
579	if (memcmp(pblob->Signature, "NTLMSSP", 8)) {
580		cifs_dbg(VFS, "blob signature incorrect %s\n",
581			 pblob->Signature);
582		return -EINVAL;
583	}
584	if (pblob->MessageType != NtLmChallenge) {
585		cifs_dbg(VFS, "Incorrect message type %d\n",
586			 pblob->MessageType);
587		return -EINVAL;
588	}
589
590	memcpy(ses->ntlmssp->cryptkey, pblob->Challenge, CIFS_CRYPTO_KEY_SIZE);
591	/* BB we could decode pblob->NegotiateFlags; some may be useful */
592	/* In particular we can examine sign flags */
593	/* BB spec says that if AvId field of MsvAvTimestamp is populated then
594		we must set the MIC field of the AUTHENTICATE_MESSAGE */
595	ses->ntlmssp->server_flags = le32_to_cpu(pblob->NegotiateFlags);
596	tioffset = le32_to_cpu(pblob->TargetInfoArray.BufferOffset);
597	tilen = le16_to_cpu(pblob->TargetInfoArray.Length);
598	if (tioffset > blob_len || tioffset + tilen > blob_len) {
599		cifs_dbg(VFS, "tioffset + tilen too high %u + %u\n",
600			 tioffset, tilen);
601		return -EINVAL;
602	}
603	if (tilen) {
604		ses->auth_key.response = kmemdup(bcc_ptr + tioffset, tilen,
605						 GFP_KERNEL);
606		if (!ses->auth_key.response) {
607			cifs_dbg(VFS, "Challenge target info alloc failure\n");
608			return -ENOMEM;
609		}
610		ses->auth_key.len = tilen;
611	}
612
613	return 0;
614}
615
616/* BB Move to ntlmssp.c eventually */
617
618/* We do not malloc the blob, it is passed in pbuffer, because
619   it is fixed size, and small, making this approach cleaner */
620void build_ntlmssp_negotiate_blob(unsigned char *pbuffer,
621					 struct cifs_ses *ses)
622{
623	struct TCP_Server_Info *server = cifs_ses_server(ses);
624	NEGOTIATE_MESSAGE *sec_blob = (NEGOTIATE_MESSAGE *)pbuffer;
625	__u32 flags;
626
627	memset(pbuffer, 0, sizeof(NEGOTIATE_MESSAGE));
628	memcpy(sec_blob->Signature, NTLMSSP_SIGNATURE, 8);
629	sec_blob->MessageType = NtLmNegotiate;
630
631	/* BB is NTLMV2 session security format easier to use here? */
632	flags = NTLMSSP_NEGOTIATE_56 |	NTLMSSP_REQUEST_TARGET |
633		NTLMSSP_NEGOTIATE_128 | NTLMSSP_NEGOTIATE_UNICODE |
634		NTLMSSP_NEGOTIATE_NTLM | NTLMSSP_NEGOTIATE_EXTENDED_SEC |
635		NTLMSSP_NEGOTIATE_SEAL;
636	if (server->sign)
637		flags |= NTLMSSP_NEGOTIATE_SIGN;
638	if (!server->session_estab || ses->ntlmssp->sesskey_per_smbsess)
639		flags |= NTLMSSP_NEGOTIATE_KEY_XCH;
640
641	sec_blob->NegotiateFlags = cpu_to_le32(flags);
642
643	sec_blob->WorkstationName.BufferOffset = 0;
644	sec_blob->WorkstationName.Length = 0;
645	sec_blob->WorkstationName.MaximumLength = 0;
646
647	/* Domain name is sent on the Challenge not Negotiate NTLMSSP request */
648	sec_blob->DomainName.BufferOffset = 0;
649	sec_blob->DomainName.Length = 0;
650	sec_blob->DomainName.MaximumLength = 0;
651}
652
653static int size_of_ntlmssp_blob(struct cifs_ses *ses)
654{
655	int sz = sizeof(AUTHENTICATE_MESSAGE) + ses->auth_key.len
656		- CIFS_SESS_KEY_SIZE + CIFS_CPHTXT_SIZE + 2;
657
658	if (ses->domainName)
659		sz += 2 * strnlen(ses->domainName, CIFS_MAX_DOMAINNAME_LEN);
660	else
661		sz += 2;
662
663	if (ses->user_name)
664		sz += 2 * strnlen(ses->user_name, CIFS_MAX_USERNAME_LEN);
665	else
666		sz += 2;
667
668	return sz;
669}
670
671int build_ntlmssp_auth_blob(unsigned char **pbuffer,
672					u16 *buflen,
673				   struct cifs_ses *ses,
674				   const struct nls_table *nls_cp)
675{
676	int rc;
677	AUTHENTICATE_MESSAGE *sec_blob;
678	__u32 flags;
679	unsigned char *tmp;
680
681	rc = setup_ntlmv2_rsp(ses, nls_cp);
682	if (rc) {
683		cifs_dbg(VFS, "Error %d during NTLMSSP authentication\n", rc);
684		*buflen = 0;
685		goto setup_ntlmv2_ret;
686	}
687	*pbuffer = kmalloc(size_of_ntlmssp_blob(ses), GFP_KERNEL);
688	if (!*pbuffer) {
689		rc = -ENOMEM;
690		cifs_dbg(VFS, "Error %d during NTLMSSP allocation\n", rc);
691		*buflen = 0;
692		goto setup_ntlmv2_ret;
693	}
694	sec_blob = (AUTHENTICATE_MESSAGE *)*pbuffer;
695
696	memcpy(sec_blob->Signature, NTLMSSP_SIGNATURE, 8);
697	sec_blob->MessageType = NtLmAuthenticate;
698
699	flags = NTLMSSP_NEGOTIATE_56 |
700		NTLMSSP_REQUEST_TARGET | NTLMSSP_NEGOTIATE_TARGET_INFO |
701		NTLMSSP_NEGOTIATE_128 | NTLMSSP_NEGOTIATE_UNICODE |
702		NTLMSSP_NEGOTIATE_NTLM | NTLMSSP_NEGOTIATE_EXTENDED_SEC |
703		NTLMSSP_NEGOTIATE_SEAL;
704	if (ses->server->sign)
705		flags |= NTLMSSP_NEGOTIATE_SIGN;
706	if (!ses->server->session_estab || ses->ntlmssp->sesskey_per_smbsess)
707		flags |= NTLMSSP_NEGOTIATE_KEY_XCH;
708
709	tmp = *pbuffer + sizeof(AUTHENTICATE_MESSAGE);
710	sec_blob->NegotiateFlags = cpu_to_le32(flags);
711
712	sec_blob->LmChallengeResponse.BufferOffset =
713				cpu_to_le32(sizeof(AUTHENTICATE_MESSAGE));
714	sec_blob->LmChallengeResponse.Length = 0;
715	sec_blob->LmChallengeResponse.MaximumLength = 0;
716
717	sec_blob->NtChallengeResponse.BufferOffset =
718				cpu_to_le32(tmp - *pbuffer);
719	if (ses->user_name != NULL) {
720		memcpy(tmp, ses->auth_key.response + CIFS_SESS_KEY_SIZE,
721				ses->auth_key.len - CIFS_SESS_KEY_SIZE);
722		tmp += ses->auth_key.len - CIFS_SESS_KEY_SIZE;
723
724		sec_blob->NtChallengeResponse.Length =
725				cpu_to_le16(ses->auth_key.len - CIFS_SESS_KEY_SIZE);
726		sec_blob->NtChallengeResponse.MaximumLength =
727				cpu_to_le16(ses->auth_key.len - CIFS_SESS_KEY_SIZE);
728	} else {
729		/*
730		 * don't send an NT Response for anonymous access
731		 */
732		sec_blob->NtChallengeResponse.Length = 0;
733		sec_blob->NtChallengeResponse.MaximumLength = 0;
734	}
735
736	if (ses->domainName == NULL) {
737		sec_blob->DomainName.BufferOffset = cpu_to_le32(tmp - *pbuffer);
738		sec_blob->DomainName.Length = 0;
739		sec_blob->DomainName.MaximumLength = 0;
740		tmp += 2;
741	} else {
742		int len;
743		len = cifs_strtoUTF16((__le16 *)tmp, ses->domainName,
744				      CIFS_MAX_DOMAINNAME_LEN, nls_cp);
745		len *= 2; /* unicode is 2 bytes each */
746		sec_blob->DomainName.BufferOffset = cpu_to_le32(tmp - *pbuffer);
747		sec_blob->DomainName.Length = cpu_to_le16(len);
748		sec_blob->DomainName.MaximumLength = cpu_to_le16(len);
749		tmp += len;
750	}
751
752	if (ses->user_name == NULL) {
753		sec_blob->UserName.BufferOffset = cpu_to_le32(tmp - *pbuffer);
754		sec_blob->UserName.Length = 0;
755		sec_blob->UserName.MaximumLength = 0;
756		tmp += 2;
757	} else {
758		int len;
759		len = cifs_strtoUTF16((__le16 *)tmp, ses->user_name,
760				      CIFS_MAX_USERNAME_LEN, nls_cp);
761		len *= 2; /* unicode is 2 bytes each */
762		sec_blob->UserName.BufferOffset = cpu_to_le32(tmp - *pbuffer);
763		sec_blob->UserName.Length = cpu_to_le16(len);
764		sec_blob->UserName.MaximumLength = cpu_to_le16(len);
765		tmp += len;
766	}
767
768	sec_blob->WorkstationName.BufferOffset = cpu_to_le32(tmp - *pbuffer);
769	sec_blob->WorkstationName.Length = 0;
770	sec_blob->WorkstationName.MaximumLength = 0;
771	tmp += 2;
772
773	if (((ses->ntlmssp->server_flags & NTLMSSP_NEGOTIATE_KEY_XCH) ||
774		(ses->ntlmssp->server_flags & NTLMSSP_NEGOTIATE_EXTENDED_SEC))
775			&& !calc_seckey(ses)) {
776		memcpy(tmp, ses->ntlmssp->ciphertext, CIFS_CPHTXT_SIZE);
777		sec_blob->SessionKey.BufferOffset = cpu_to_le32(tmp - *pbuffer);
778		sec_blob->SessionKey.Length = cpu_to_le16(CIFS_CPHTXT_SIZE);
779		sec_blob->SessionKey.MaximumLength =
780				cpu_to_le16(CIFS_CPHTXT_SIZE);
781		tmp += CIFS_CPHTXT_SIZE;
782	} else {
783		sec_blob->SessionKey.BufferOffset = cpu_to_le32(tmp - *pbuffer);
784		sec_blob->SessionKey.Length = 0;
785		sec_blob->SessionKey.MaximumLength = 0;
786	}
787
788	*buflen = tmp - *pbuffer;
789setup_ntlmv2_ret:
790	return rc;
791}
792
793enum securityEnum
794cifs_select_sectype(struct TCP_Server_Info *server, enum securityEnum requested)
795{
796	switch (server->negflavor) {
797	case CIFS_NEGFLAVOR_EXTENDED:
798		switch (requested) {
799		case Kerberos:
800		case RawNTLMSSP:
801			return requested;
802		case Unspecified:
803			if (server->sec_ntlmssp &&
804			    (global_secflags & CIFSSEC_MAY_NTLMSSP))
805				return RawNTLMSSP;
806			if ((server->sec_kerberos || server->sec_mskerberos) &&
807			    (global_secflags & CIFSSEC_MAY_KRB5))
808				return Kerberos;
809			fallthrough;
810		default:
811			return Unspecified;
812		}
813	case CIFS_NEGFLAVOR_UNENCAP:
814		switch (requested) {
815		case NTLM:
816		case NTLMv2:
817			return requested;
818		case Unspecified:
819			if (global_secflags & CIFSSEC_MAY_NTLMV2)
820				return NTLMv2;
821			if (global_secflags & CIFSSEC_MAY_NTLM)
822				return NTLM;
823		default:
824			break;
825		}
826		fallthrough;	/* to attempt LANMAN authentication next */
827	case CIFS_NEGFLAVOR_LANMAN:
828		switch (requested) {
829		case LANMAN:
830			return requested;
831		case Unspecified:
832			if (global_secflags & CIFSSEC_MAY_LANMAN)
833				return LANMAN;
834			fallthrough;
835		default:
836			return Unspecified;
837		}
838	default:
839		return Unspecified;
840	}
841}
842
843struct sess_data {
844	unsigned int xid;
845	struct cifs_ses *ses;
846	struct nls_table *nls_cp;
847	void (*func)(struct sess_data *);
848	int result;
849
850	/* we will send the SMB in three pieces:
851	 * a fixed length beginning part, an optional
852	 * SPNEGO blob (which can be zero length), and a
853	 * last part which will include the strings
854	 * and rest of bcc area. This allows us to avoid
855	 * a large buffer 17K allocation
856	 */
857	int buf0_type;
858	struct kvec iov[3];
859};
860
861static int
862sess_alloc_buffer(struct sess_data *sess_data, int wct)
863{
864	int rc;
865	struct cifs_ses *ses = sess_data->ses;
866	struct smb_hdr *smb_buf;
867
868	rc = small_smb_init_no_tc(SMB_COM_SESSION_SETUP_ANDX, wct, ses,
869				  (void **)&smb_buf);
870
871	if (rc)
872		return rc;
873
874	sess_data->iov[0].iov_base = (char *)smb_buf;
875	sess_data->iov[0].iov_len = be32_to_cpu(smb_buf->smb_buf_length) + 4;
876	/*
877	 * This variable will be used to clear the buffer
878	 * allocated above in case of any error in the calling function.
879	 */
880	sess_data->buf0_type = CIFS_SMALL_BUFFER;
881
882	/* 2000 big enough to fit max user, domain, NOS name etc. */
883	sess_data->iov[2].iov_base = kmalloc(2000, GFP_KERNEL);
884	if (!sess_data->iov[2].iov_base) {
885		rc = -ENOMEM;
886		goto out_free_smb_buf;
887	}
888
889	return 0;
890
891out_free_smb_buf:
892	cifs_small_buf_release(smb_buf);
893	sess_data->iov[0].iov_base = NULL;
894	sess_data->iov[0].iov_len = 0;
895	sess_data->buf0_type = CIFS_NO_BUFFER;
896	return rc;
897}
898
899static void
900sess_free_buffer(struct sess_data *sess_data)
901{
902
903	free_rsp_buf(sess_data->buf0_type, sess_data->iov[0].iov_base);
904	sess_data->buf0_type = CIFS_NO_BUFFER;
905	kfree(sess_data->iov[2].iov_base);
906}
907
908static int
909sess_establish_session(struct sess_data *sess_data)
910{
911	struct cifs_ses *ses = sess_data->ses;
912
913	mutex_lock(&ses->server->srv_mutex);
914	if (!ses->server->session_estab) {
915		if (ses->server->sign) {
916			ses->server->session_key.response =
917				kmemdup(ses->auth_key.response,
918				ses->auth_key.len, GFP_KERNEL);
919			if (!ses->server->session_key.response) {
920				mutex_unlock(&ses->server->srv_mutex);
921				return -ENOMEM;
922			}
923			ses->server->session_key.len =
924						ses->auth_key.len;
925		}
926		ses->server->sequence_number = 0x2;
927		ses->server->session_estab = true;
928	}
929	mutex_unlock(&ses->server->srv_mutex);
930
931	cifs_dbg(FYI, "CIFS session established successfully\n");
932	spin_lock(&GlobalMid_Lock);
933	ses->status = CifsGood;
934	ses->need_reconnect = false;
935	spin_unlock(&GlobalMid_Lock);
936
937	return 0;
938}
939
940static int
941sess_sendreceive(struct sess_data *sess_data)
942{
943	int rc;
944	struct smb_hdr *smb_buf = (struct smb_hdr *) sess_data->iov[0].iov_base;
945	__u16 count;
946	struct kvec rsp_iov = { NULL, 0 };
947
948	count = sess_data->iov[1].iov_len + sess_data->iov[2].iov_len;
949	be32_add_cpu(&smb_buf->smb_buf_length, count);
950	put_bcc(count, smb_buf);
951
952	rc = SendReceive2(sess_data->xid, sess_data->ses,
953			  sess_data->iov, 3 /* num_iovecs */,
954			  &sess_data->buf0_type,
955			  CIFS_LOG_ERROR, &rsp_iov);
956	cifs_small_buf_release(sess_data->iov[0].iov_base);
957	memcpy(&sess_data->iov[0], &rsp_iov, sizeof(struct kvec));
958
959	return rc;
960}
961
962/*
963 * LANMAN and plaintext are less secure and off by default.
964 * So we make this explicitly be turned on in kconfig (in the
965 * build) and turned on at runtime (changed from the default)
966 * in proc/fs/cifs or via mount parm.  Unfortunately this is
967 * needed for old Win (e.g. Win95), some obscure NAS and OS/2
968 */
969#ifdef CONFIG_CIFS_WEAK_PW_HASH
970static void
971sess_auth_lanman(struct sess_data *sess_data)
972{
973	int rc = 0;
974	struct smb_hdr *smb_buf;
975	SESSION_SETUP_ANDX *pSMB;
976	char *bcc_ptr;
977	struct cifs_ses *ses = sess_data->ses;
978	char lnm_session_key[CIFS_AUTH_RESP_SIZE];
979	__u16 bytes_remaining;
980
981	/* lanman 2 style sessionsetup */
982	/* wct = 10 */
983	rc = sess_alloc_buffer(sess_data, 10);
984	if (rc)
985		goto out;
986
987	pSMB = (SESSION_SETUP_ANDX *)sess_data->iov[0].iov_base;
988	bcc_ptr = sess_data->iov[2].iov_base;
989	(void)cifs_ssetup_hdr(ses, pSMB);
990
991	pSMB->req.hdr.Flags2 &= ~SMBFLG2_UNICODE;
992
993	if (ses->user_name != NULL) {
994		/* no capabilities flags in old lanman negotiation */
995		pSMB->old_req.PasswordLength = cpu_to_le16(CIFS_AUTH_RESP_SIZE);
996
997		/* Calculate hash with password and copy into bcc_ptr.
998		 * Encryption Key (stored as in cryptkey) gets used if the
999		 * security mode bit in Negotiate Protocol response states
1000		 * to use challenge/response method (i.e. Password bit is 1).
1001		 */
1002		rc = calc_lanman_hash(ses->password, ses->server->cryptkey,
1003				      ses->server->sec_mode & SECMODE_PW_ENCRYPT ?
1004				      true : false, lnm_session_key);
1005		if (rc)
1006			goto out;
1007
1008		memcpy(bcc_ptr, (char *)lnm_session_key, CIFS_AUTH_RESP_SIZE);
1009		bcc_ptr += CIFS_AUTH_RESP_SIZE;
1010	} else {
1011		pSMB->old_req.PasswordLength = 0;
1012	}
1013
1014	/*
1015	 * can not sign if LANMAN negotiated so no need
1016	 * to calculate signing key? but what if server
1017	 * changed to do higher than lanman dialect and
1018	 * we reconnected would we ever calc signing_key?
1019	 */
1020
1021	cifs_dbg(FYI, "Negotiating LANMAN setting up strings\n");
1022	/* Unicode not allowed for LANMAN dialects */
1023	ascii_ssetup_strings(&bcc_ptr, ses, sess_data->nls_cp);
1024
1025	sess_data->iov[2].iov_len = (long) bcc_ptr -
1026			(long) sess_data->iov[2].iov_base;
1027
1028	rc = sess_sendreceive(sess_data);
1029	if (rc)
1030		goto out;
1031
1032	pSMB = (SESSION_SETUP_ANDX *)sess_data->iov[0].iov_base;
1033	smb_buf = (struct smb_hdr *)sess_data->iov[0].iov_base;
1034
1035	/* lanman response has a word count of 3 */
1036	if (smb_buf->WordCount != 3) {
1037		rc = -EIO;
1038		cifs_dbg(VFS, "bad word count %d\n", smb_buf->WordCount);
1039		goto out;
1040	}
1041
1042	if (le16_to_cpu(pSMB->resp.Action) & GUEST_LOGIN)
1043		cifs_dbg(FYI, "Guest login\n"); /* BB mark SesInfo struct? */
1044
1045	ses->Suid = smb_buf->Uid;   /* UID left in wire format (le) */
1046	cifs_dbg(FYI, "UID = %llu\n", ses->Suid);
1047
1048	bytes_remaining = get_bcc(smb_buf);
1049	bcc_ptr = pByteArea(smb_buf);
1050
1051	/* BB check if Unicode and decode strings */
1052	if (bytes_remaining == 0) {
1053		/* no string area to decode, do nothing */
1054	} else if (smb_buf->Flags2 & SMBFLG2_UNICODE) {
1055		/* unicode string area must be word-aligned */
1056		if (((unsigned long) bcc_ptr - (unsigned long) smb_buf) % 2) {
1057			++bcc_ptr;
1058			--bytes_remaining;
1059		}
1060		decode_unicode_ssetup(&bcc_ptr, bytes_remaining, ses,
1061				      sess_data->nls_cp);
1062	} else {
1063		decode_ascii_ssetup(&bcc_ptr, bytes_remaining, ses,
1064				    sess_data->nls_cp);
1065	}
1066
1067	rc = sess_establish_session(sess_data);
1068out:
1069	sess_data->result = rc;
1070	sess_data->func = NULL;
1071	sess_free_buffer(sess_data);
1072}
1073
1074#endif
1075
1076static void
1077sess_auth_ntlm(struct sess_data *sess_data)
1078{
1079	int rc = 0;
1080	struct smb_hdr *smb_buf;
1081	SESSION_SETUP_ANDX *pSMB;
1082	char *bcc_ptr;
1083	struct cifs_ses *ses = sess_data->ses;
1084	__u32 capabilities;
1085	__u16 bytes_remaining;
1086
1087	/* old style NTLM sessionsetup */
1088	/* wct = 13 */
1089	rc = sess_alloc_buffer(sess_data, 13);
1090	if (rc)
1091		goto out;
1092
1093	pSMB = (SESSION_SETUP_ANDX *)sess_data->iov[0].iov_base;
1094	bcc_ptr = sess_data->iov[2].iov_base;
1095	capabilities = cifs_ssetup_hdr(ses, pSMB);
1096
1097	pSMB->req_no_secext.Capabilities = cpu_to_le32(capabilities);
1098	if (ses->user_name != NULL) {
1099		pSMB->req_no_secext.CaseInsensitivePasswordLength =
1100				cpu_to_le16(CIFS_AUTH_RESP_SIZE);
1101		pSMB->req_no_secext.CaseSensitivePasswordLength =
1102				cpu_to_le16(CIFS_AUTH_RESP_SIZE);
1103
1104		/* calculate ntlm response and session key */
1105		rc = setup_ntlm_response(ses, sess_data->nls_cp);
1106		if (rc) {
1107			cifs_dbg(VFS, "Error %d during NTLM authentication\n",
1108					 rc);
1109			goto out;
1110		}
1111
1112		/* copy ntlm response */
1113		memcpy(bcc_ptr, ses->auth_key.response + CIFS_SESS_KEY_SIZE,
1114				CIFS_AUTH_RESP_SIZE);
1115		bcc_ptr += CIFS_AUTH_RESP_SIZE;
1116		memcpy(bcc_ptr, ses->auth_key.response + CIFS_SESS_KEY_SIZE,
1117				CIFS_AUTH_RESP_SIZE);
1118		bcc_ptr += CIFS_AUTH_RESP_SIZE;
1119	} else {
1120		pSMB->req_no_secext.CaseInsensitivePasswordLength = 0;
1121		pSMB->req_no_secext.CaseSensitivePasswordLength = 0;
1122	}
1123
1124	if (ses->capabilities & CAP_UNICODE) {
1125		/* unicode strings must be word aligned */
1126		if (sess_data->iov[0].iov_len % 2) {
1127			*bcc_ptr = 0;
1128			bcc_ptr++;
1129		}
1130		unicode_ssetup_strings(&bcc_ptr, ses, sess_data->nls_cp);
1131	} else {
1132		ascii_ssetup_strings(&bcc_ptr, ses, sess_data->nls_cp);
1133	}
1134
1135
1136	sess_data->iov[2].iov_len = (long) bcc_ptr -
1137			(long) sess_data->iov[2].iov_base;
1138
1139	rc = sess_sendreceive(sess_data);
1140	if (rc)
1141		goto out;
1142
1143	pSMB = (SESSION_SETUP_ANDX *)sess_data->iov[0].iov_base;
1144	smb_buf = (struct smb_hdr *)sess_data->iov[0].iov_base;
1145
1146	if (smb_buf->WordCount != 3) {
1147		rc = -EIO;
1148		cifs_dbg(VFS, "bad word count %d\n", smb_buf->WordCount);
1149		goto out;
1150	}
1151
1152	if (le16_to_cpu(pSMB->resp.Action) & GUEST_LOGIN)
1153		cifs_dbg(FYI, "Guest login\n"); /* BB mark SesInfo struct? */
1154
1155	ses->Suid = smb_buf->Uid;   /* UID left in wire format (le) */
1156	cifs_dbg(FYI, "UID = %llu\n", ses->Suid);
1157
1158	bytes_remaining = get_bcc(smb_buf);
1159	bcc_ptr = pByteArea(smb_buf);
1160
1161	/* BB check if Unicode and decode strings */
1162	if (bytes_remaining == 0) {
1163		/* no string area to decode, do nothing */
1164	} else if (smb_buf->Flags2 & SMBFLG2_UNICODE) {
1165		/* unicode string area must be word-aligned */
1166		if (((unsigned long) bcc_ptr - (unsigned long) smb_buf) % 2) {
1167			++bcc_ptr;
1168			--bytes_remaining;
1169		}
1170		decode_unicode_ssetup(&bcc_ptr, bytes_remaining, ses,
1171				      sess_data->nls_cp);
1172	} else {
1173		decode_ascii_ssetup(&bcc_ptr, bytes_remaining, ses,
1174				    sess_data->nls_cp);
1175	}
1176
1177	rc = sess_establish_session(sess_data);
1178out:
1179	sess_data->result = rc;
1180	sess_data->func = NULL;
1181	sess_free_buffer(sess_data);
1182	kfree(ses->auth_key.response);
1183	ses->auth_key.response = NULL;
1184}
1185
1186static void
1187sess_auth_ntlmv2(struct sess_data *sess_data)
1188{
1189	int rc = 0;
1190	struct smb_hdr *smb_buf;
1191	SESSION_SETUP_ANDX *pSMB;
1192	char *bcc_ptr;
1193	struct cifs_ses *ses = sess_data->ses;
1194	__u32 capabilities;
1195	__u16 bytes_remaining;
1196
1197	/* old style NTLM sessionsetup */
1198	/* wct = 13 */
1199	rc = sess_alloc_buffer(sess_data, 13);
1200	if (rc)
1201		goto out;
1202
1203	pSMB = (SESSION_SETUP_ANDX *)sess_data->iov[0].iov_base;
1204	bcc_ptr = sess_data->iov[2].iov_base;
1205	capabilities = cifs_ssetup_hdr(ses, pSMB);
1206
1207	pSMB->req_no_secext.Capabilities = cpu_to_le32(capabilities);
1208
1209	/* LM2 password would be here if we supported it */
1210	pSMB->req_no_secext.CaseInsensitivePasswordLength = 0;
1211
1212	if (ses->user_name != NULL) {
1213		/* calculate nlmv2 response and session key */
1214		rc = setup_ntlmv2_rsp(ses, sess_data->nls_cp);
1215		if (rc) {
1216			cifs_dbg(VFS, "Error %d during NTLMv2 authentication\n", rc);
1217			goto out;
1218		}
1219
1220		memcpy(bcc_ptr, ses->auth_key.response + CIFS_SESS_KEY_SIZE,
1221				ses->auth_key.len - CIFS_SESS_KEY_SIZE);
1222		bcc_ptr += ses->auth_key.len - CIFS_SESS_KEY_SIZE;
1223
1224		/* set case sensitive password length after tilen may get
1225		 * assigned, tilen is 0 otherwise.
1226		 */
1227		pSMB->req_no_secext.CaseSensitivePasswordLength =
1228			cpu_to_le16(ses->auth_key.len - CIFS_SESS_KEY_SIZE);
1229	} else {
1230		pSMB->req_no_secext.CaseSensitivePasswordLength = 0;
1231	}
1232
1233	if (ses->capabilities & CAP_UNICODE) {
1234		if (sess_data->iov[0].iov_len % 2) {
1235			*bcc_ptr = 0;
1236			bcc_ptr++;
1237		}
1238		unicode_ssetup_strings(&bcc_ptr, ses, sess_data->nls_cp);
1239	} else {
1240		ascii_ssetup_strings(&bcc_ptr, ses, sess_data->nls_cp);
1241	}
1242
1243
1244	sess_data->iov[2].iov_len = (long) bcc_ptr -
1245			(long) sess_data->iov[2].iov_base;
1246
1247	rc = sess_sendreceive(sess_data);
1248	if (rc)
1249		goto out;
1250
1251	pSMB = (SESSION_SETUP_ANDX *)sess_data->iov[0].iov_base;
1252	smb_buf = (struct smb_hdr *)sess_data->iov[0].iov_base;
1253
1254	if (smb_buf->WordCount != 3) {
1255		rc = -EIO;
1256		cifs_dbg(VFS, "bad word count %d\n", smb_buf->WordCount);
1257		goto out;
1258	}
1259
1260	if (le16_to_cpu(pSMB->resp.Action) & GUEST_LOGIN)
1261		cifs_dbg(FYI, "Guest login\n"); /* BB mark SesInfo struct? */
1262
1263	ses->Suid = smb_buf->Uid;   /* UID left in wire format (le) */
1264	cifs_dbg(FYI, "UID = %llu\n", ses->Suid);
1265
1266	bytes_remaining = get_bcc(smb_buf);
1267	bcc_ptr = pByteArea(smb_buf);
1268
1269	/* BB check if Unicode and decode strings */
1270	if (bytes_remaining == 0) {
1271		/* no string area to decode, do nothing */
1272	} else if (smb_buf->Flags2 & SMBFLG2_UNICODE) {
1273		/* unicode string area must be word-aligned */
1274		if (((unsigned long) bcc_ptr - (unsigned long) smb_buf) % 2) {
1275			++bcc_ptr;
1276			--bytes_remaining;
1277		}
1278		decode_unicode_ssetup(&bcc_ptr, bytes_remaining, ses,
1279				      sess_data->nls_cp);
1280	} else {
1281		decode_ascii_ssetup(&bcc_ptr, bytes_remaining, ses,
1282				    sess_data->nls_cp);
1283	}
1284
1285	rc = sess_establish_session(sess_data);
1286out:
1287	sess_data->result = rc;
1288	sess_data->func = NULL;
1289	sess_free_buffer(sess_data);
1290	kfree(ses->auth_key.response);
1291	ses->auth_key.response = NULL;
1292}
1293
1294#ifdef CONFIG_CIFS_UPCALL
1295static void
1296sess_auth_kerberos(struct sess_data *sess_data)
1297{
1298	int rc = 0;
1299	struct smb_hdr *smb_buf;
1300	SESSION_SETUP_ANDX *pSMB;
1301	char *bcc_ptr;
1302	struct cifs_ses *ses = sess_data->ses;
1303	__u32 capabilities;
1304	__u16 bytes_remaining;
1305	struct key *spnego_key = NULL;
1306	struct cifs_spnego_msg *msg;
1307	u16 blob_len;
1308
1309	/* extended security */
1310	/* wct = 12 */
1311	rc = sess_alloc_buffer(sess_data, 12);
1312	if (rc)
1313		goto out;
1314
1315	pSMB = (SESSION_SETUP_ANDX *)sess_data->iov[0].iov_base;
1316	bcc_ptr = sess_data->iov[2].iov_base;
1317	capabilities = cifs_ssetup_hdr(ses, pSMB);
1318
1319	spnego_key = cifs_get_spnego_key(ses);
1320	if (IS_ERR(spnego_key)) {
1321		rc = PTR_ERR(spnego_key);
1322		spnego_key = NULL;
1323		goto out;
1324	}
1325
1326	msg = spnego_key->payload.data[0];
1327	/*
1328	 * check version field to make sure that cifs.upcall is
1329	 * sending us a response in an expected form
1330	 */
1331	if (msg->version != CIFS_SPNEGO_UPCALL_VERSION) {
1332		cifs_dbg(VFS, "incorrect version of cifs.upcall (expected %d but got %d)\n",
1333			 CIFS_SPNEGO_UPCALL_VERSION, msg->version);
1334		rc = -EKEYREJECTED;
1335		goto out_put_spnego_key;
1336	}
1337
1338	ses->auth_key.response = kmemdup(msg->data, msg->sesskey_len,
1339					 GFP_KERNEL);
1340	if (!ses->auth_key.response) {
1341		cifs_dbg(VFS, "Kerberos can't allocate (%u bytes) memory\n",
1342			 msg->sesskey_len);
1343		rc = -ENOMEM;
1344		goto out_put_spnego_key;
1345	}
1346	ses->auth_key.len = msg->sesskey_len;
1347
1348	pSMB->req.hdr.Flags2 |= SMBFLG2_EXT_SEC;
1349	capabilities |= CAP_EXTENDED_SECURITY;
1350	pSMB->req.Capabilities = cpu_to_le32(capabilities);
1351	sess_data->iov[1].iov_base = msg->data + msg->sesskey_len;
1352	sess_data->iov[1].iov_len = msg->secblob_len;
1353	pSMB->req.SecurityBlobLength = cpu_to_le16(sess_data->iov[1].iov_len);
1354
1355	if (ses->capabilities & CAP_UNICODE) {
1356		/* unicode strings must be word aligned */
1357		if ((sess_data->iov[0].iov_len
1358			+ sess_data->iov[1].iov_len) % 2) {
1359			*bcc_ptr = 0;
1360			bcc_ptr++;
1361		}
1362		unicode_oslm_strings(&bcc_ptr, sess_data->nls_cp);
1363		unicode_domain_string(&bcc_ptr, ses, sess_data->nls_cp);
1364	} else {
1365		/* BB: is this right? */
1366		ascii_ssetup_strings(&bcc_ptr, ses, sess_data->nls_cp);
1367	}
1368
1369	sess_data->iov[2].iov_len = (long) bcc_ptr -
1370			(long) sess_data->iov[2].iov_base;
1371
1372	rc = sess_sendreceive(sess_data);
1373	if (rc)
1374		goto out_put_spnego_key;
1375
1376	pSMB = (SESSION_SETUP_ANDX *)sess_data->iov[0].iov_base;
1377	smb_buf = (struct smb_hdr *)sess_data->iov[0].iov_base;
1378
1379	if (smb_buf->WordCount != 4) {
1380		rc = -EIO;
1381		cifs_dbg(VFS, "bad word count %d\n", smb_buf->WordCount);
1382		goto out_put_spnego_key;
1383	}
1384
1385	if (le16_to_cpu(pSMB->resp.Action) & GUEST_LOGIN)
1386		cifs_dbg(FYI, "Guest login\n"); /* BB mark SesInfo struct? */
1387
1388	ses->Suid = smb_buf->Uid;   /* UID left in wire format (le) */
1389	cifs_dbg(FYI, "UID = %llu\n", ses->Suid);
1390
1391	bytes_remaining = get_bcc(smb_buf);
1392	bcc_ptr = pByteArea(smb_buf);
1393
1394	blob_len = le16_to_cpu(pSMB->resp.SecurityBlobLength);
1395	if (blob_len > bytes_remaining) {
1396		cifs_dbg(VFS, "bad security blob length %d\n",
1397				blob_len);
1398		rc = -EINVAL;
1399		goto out_put_spnego_key;
1400	}
1401	bcc_ptr += blob_len;
1402	bytes_remaining -= blob_len;
1403
1404	/* BB check if Unicode and decode strings */
1405	if (bytes_remaining == 0) {
1406		/* no string area to decode, do nothing */
1407	} else if (smb_buf->Flags2 & SMBFLG2_UNICODE) {
1408		/* unicode string area must be word-aligned */
1409		if (((unsigned long) bcc_ptr - (unsigned long) smb_buf) % 2) {
1410			++bcc_ptr;
1411			--bytes_remaining;
1412		}
1413		decode_unicode_ssetup(&bcc_ptr, bytes_remaining, ses,
1414				      sess_data->nls_cp);
1415	} else {
1416		decode_ascii_ssetup(&bcc_ptr, bytes_remaining, ses,
1417				    sess_data->nls_cp);
1418	}
1419
1420	rc = sess_establish_session(sess_data);
1421out_put_spnego_key:
1422	key_invalidate(spnego_key);
1423	key_put(spnego_key);
1424out:
1425	sess_data->result = rc;
1426	sess_data->func = NULL;
1427	sess_free_buffer(sess_data);
1428	kfree(ses->auth_key.response);
1429	ses->auth_key.response = NULL;
1430}
1431
1432#endif /* ! CONFIG_CIFS_UPCALL */
1433
1434/*
1435 * The required kvec buffers have to be allocated before calling this
1436 * function.
1437 */
1438static int
1439_sess_auth_rawntlmssp_assemble_req(struct sess_data *sess_data)
1440{
1441	SESSION_SETUP_ANDX *pSMB;
1442	struct cifs_ses *ses = sess_data->ses;
1443	__u32 capabilities;
1444	char *bcc_ptr;
1445
1446	pSMB = (SESSION_SETUP_ANDX *)sess_data->iov[0].iov_base;
1447
1448	capabilities = cifs_ssetup_hdr(ses, pSMB);
1449	if ((pSMB->req.hdr.Flags2 & SMBFLG2_UNICODE) == 0) {
1450		cifs_dbg(VFS, "NTLMSSP requires Unicode support\n");
1451		return -ENOSYS;
1452	}
1453
1454	pSMB->req.hdr.Flags2 |= SMBFLG2_EXT_SEC;
1455	capabilities |= CAP_EXTENDED_SECURITY;
1456	pSMB->req.Capabilities |= cpu_to_le32(capabilities);
1457
1458	bcc_ptr = sess_data->iov[2].iov_base;
1459	/* unicode strings must be word aligned */
1460	if ((sess_data->iov[0].iov_len + sess_data->iov[1].iov_len) % 2) {
1461		*bcc_ptr = 0;
1462		bcc_ptr++;
1463	}
1464	unicode_oslm_strings(&bcc_ptr, sess_data->nls_cp);
1465
1466	sess_data->iov[2].iov_len = (long) bcc_ptr -
1467					(long) sess_data->iov[2].iov_base;
1468
1469	return 0;
1470}
1471
1472static void
1473sess_auth_rawntlmssp_authenticate(struct sess_data *sess_data);
1474
1475static void
1476sess_auth_rawntlmssp_negotiate(struct sess_data *sess_data)
1477{
1478	int rc;
1479	struct smb_hdr *smb_buf;
1480	SESSION_SETUP_ANDX *pSMB;
1481	struct cifs_ses *ses = sess_data->ses;
1482	__u16 bytes_remaining;
1483	char *bcc_ptr;
1484	u16 blob_len;
1485
1486	cifs_dbg(FYI, "rawntlmssp session setup negotiate phase\n");
1487
1488	/*
1489	 * if memory allocation is successful, caller of this function
1490	 * frees it.
1491	 */
1492	ses->ntlmssp = kmalloc(sizeof(struct ntlmssp_auth), GFP_KERNEL);
1493	if (!ses->ntlmssp) {
1494		rc = -ENOMEM;
1495		goto out;
1496	}
1497	ses->ntlmssp->sesskey_per_smbsess = false;
1498
1499	/* wct = 12 */
1500	rc = sess_alloc_buffer(sess_data, 12);
1501	if (rc)
1502		goto out;
1503
1504	pSMB = (SESSION_SETUP_ANDX *)sess_data->iov[0].iov_base;
1505
1506	/* Build security blob before we assemble the request */
1507	build_ntlmssp_negotiate_blob(pSMB->req.SecurityBlob, ses);
1508	sess_data->iov[1].iov_len = sizeof(NEGOTIATE_MESSAGE);
1509	sess_data->iov[1].iov_base = pSMB->req.SecurityBlob;
1510	pSMB->req.SecurityBlobLength = cpu_to_le16(sizeof(NEGOTIATE_MESSAGE));
1511
1512	rc = _sess_auth_rawntlmssp_assemble_req(sess_data);
1513	if (rc)
1514		goto out;
1515
1516	rc = sess_sendreceive(sess_data);
1517
1518	pSMB = (SESSION_SETUP_ANDX *)sess_data->iov[0].iov_base;
1519	smb_buf = (struct smb_hdr *)sess_data->iov[0].iov_base;
1520
1521	/* If true, rc here is expected and not an error */
1522	if (sess_data->buf0_type != CIFS_NO_BUFFER &&
1523	    smb_buf->Status.CifsError ==
1524			cpu_to_le32(NT_STATUS_MORE_PROCESSING_REQUIRED))
1525		rc = 0;
1526
1527	if (rc)
1528		goto out;
1529
1530	cifs_dbg(FYI, "rawntlmssp session setup challenge phase\n");
1531
1532	if (smb_buf->WordCount != 4) {
1533		rc = -EIO;
1534		cifs_dbg(VFS, "bad word count %d\n", smb_buf->WordCount);
1535		goto out;
1536	}
1537
1538	ses->Suid = smb_buf->Uid;   /* UID left in wire format (le) */
1539	cifs_dbg(FYI, "UID = %llu\n", ses->Suid);
1540
1541	bytes_remaining = get_bcc(smb_buf);
1542	bcc_ptr = pByteArea(smb_buf);
1543
1544	blob_len = le16_to_cpu(pSMB->resp.SecurityBlobLength);
1545	if (blob_len > bytes_remaining) {
1546		cifs_dbg(VFS, "bad security blob length %d\n",
1547				blob_len);
1548		rc = -EINVAL;
1549		goto out;
1550	}
1551
1552	rc = decode_ntlmssp_challenge(bcc_ptr, blob_len, ses);
1553out:
1554	sess_free_buffer(sess_data);
1555
1556	if (!rc) {
1557		sess_data->func = sess_auth_rawntlmssp_authenticate;
1558		return;
1559	}
1560
1561	/* Else error. Cleanup */
1562	kfree(ses->auth_key.response);
1563	ses->auth_key.response = NULL;
1564	kfree(ses->ntlmssp);
1565	ses->ntlmssp = NULL;
1566
1567	sess_data->func = NULL;
1568	sess_data->result = rc;
1569}
1570
1571static void
1572sess_auth_rawntlmssp_authenticate(struct sess_data *sess_data)
1573{
1574	int rc;
1575	struct smb_hdr *smb_buf;
1576	SESSION_SETUP_ANDX *pSMB;
1577	struct cifs_ses *ses = sess_data->ses;
1578	__u16 bytes_remaining;
1579	char *bcc_ptr;
1580	unsigned char *ntlmsspblob = NULL;
1581	u16 blob_len;
1582
1583	cifs_dbg(FYI, "rawntlmssp session setup authenticate phase\n");
1584
1585	/* wct = 12 */
1586	rc = sess_alloc_buffer(sess_data, 12);
1587	if (rc)
1588		goto out;
1589
1590	/* Build security blob before we assemble the request */
1591	pSMB = (SESSION_SETUP_ANDX *)sess_data->iov[0].iov_base;
1592	smb_buf = (struct smb_hdr *)pSMB;
1593	rc = build_ntlmssp_auth_blob(&ntlmsspblob,
1594					&blob_len, ses, sess_data->nls_cp);
1595	if (rc)
1596		goto out_free_ntlmsspblob;
1597	sess_data->iov[1].iov_len = blob_len;
1598	sess_data->iov[1].iov_base = ntlmsspblob;
1599	pSMB->req.SecurityBlobLength = cpu_to_le16(blob_len);
1600	/*
1601	 * Make sure that we tell the server that we are using
1602	 * the uid that it just gave us back on the response
1603	 * (challenge)
1604	 */
1605	smb_buf->Uid = ses->Suid;
1606
1607	rc = _sess_auth_rawntlmssp_assemble_req(sess_data);
1608	if (rc)
1609		goto out_free_ntlmsspblob;
1610
1611	rc = sess_sendreceive(sess_data);
1612	if (rc)
1613		goto out_free_ntlmsspblob;
1614
1615	pSMB = (SESSION_SETUP_ANDX *)sess_data->iov[0].iov_base;
1616	smb_buf = (struct smb_hdr *)sess_data->iov[0].iov_base;
1617	if (smb_buf->WordCount != 4) {
1618		rc = -EIO;
1619		cifs_dbg(VFS, "bad word count %d\n", smb_buf->WordCount);
1620		goto out_free_ntlmsspblob;
1621	}
1622
1623	if (le16_to_cpu(pSMB->resp.Action) & GUEST_LOGIN)
1624		cifs_dbg(FYI, "Guest login\n"); /* BB mark SesInfo struct? */
1625
1626	if (ses->Suid != smb_buf->Uid) {
1627		ses->Suid = smb_buf->Uid;
1628		cifs_dbg(FYI, "UID changed! new UID = %llu\n", ses->Suid);
1629	}
1630
1631	bytes_remaining = get_bcc(smb_buf);
1632	bcc_ptr = pByteArea(smb_buf);
1633	blob_len = le16_to_cpu(pSMB->resp.SecurityBlobLength);
1634	if (blob_len > bytes_remaining) {
1635		cifs_dbg(VFS, "bad security blob length %d\n",
1636				blob_len);
1637		rc = -EINVAL;
1638		goto out_free_ntlmsspblob;
1639	}
1640	bcc_ptr += blob_len;
1641	bytes_remaining -= blob_len;
1642
1643
1644	/* BB check if Unicode and decode strings */
1645	if (bytes_remaining == 0) {
1646		/* no string area to decode, do nothing */
1647	} else if (smb_buf->Flags2 & SMBFLG2_UNICODE) {
1648		/* unicode string area must be word-aligned */
1649		if (((unsigned long) bcc_ptr - (unsigned long) smb_buf) % 2) {
1650			++bcc_ptr;
1651			--bytes_remaining;
1652		}
1653		decode_unicode_ssetup(&bcc_ptr, bytes_remaining, ses,
1654				      sess_data->nls_cp);
1655	} else {
1656		decode_ascii_ssetup(&bcc_ptr, bytes_remaining, ses,
1657				    sess_data->nls_cp);
1658	}
1659
1660out_free_ntlmsspblob:
1661	kfree(ntlmsspblob);
1662out:
1663	sess_free_buffer(sess_data);
1664
1665	 if (!rc)
1666		rc = sess_establish_session(sess_data);
1667
1668	/* Cleanup */
1669	kfree(ses->auth_key.response);
1670	ses->auth_key.response = NULL;
1671	kfree(ses->ntlmssp);
1672	ses->ntlmssp = NULL;
1673
1674	sess_data->func = NULL;
1675	sess_data->result = rc;
1676}
1677
1678static int select_sec(struct cifs_ses *ses, struct sess_data *sess_data)
1679{
1680	int type;
1681
1682	type = cifs_select_sectype(ses->server, ses->sectype);
1683	cifs_dbg(FYI, "sess setup type %d\n", type);
1684	if (type == Unspecified) {
1685		cifs_dbg(VFS, "Unable to select appropriate authentication method!\n");
1686		return -EINVAL;
1687	}
1688
1689	switch (type) {
1690	case LANMAN:
1691		/* LANMAN and plaintext are less secure and off by default.
1692		 * So we make this explicitly be turned on in kconfig (in the
1693		 * build) and turned on at runtime (changed from the default)
1694		 * in proc/fs/cifs or via mount parm.  Unfortunately this is
1695		 * needed for old Win (e.g. Win95), some obscure NAS and OS/2 */
1696#ifdef CONFIG_CIFS_WEAK_PW_HASH
1697		sess_data->func = sess_auth_lanman;
1698		break;
1699#else
1700		return -EOPNOTSUPP;
1701#endif
1702	case NTLM:
1703		sess_data->func = sess_auth_ntlm;
1704		break;
1705	case NTLMv2:
1706		sess_data->func = sess_auth_ntlmv2;
1707		break;
1708	case Kerberos:
1709#ifdef CONFIG_CIFS_UPCALL
1710		sess_data->func = sess_auth_kerberos;
1711		break;
1712#else
1713		cifs_dbg(VFS, "Kerberos negotiated but upcall support disabled!\n");
1714		return -ENOSYS;
1715#endif /* CONFIG_CIFS_UPCALL */
1716	case RawNTLMSSP:
1717		sess_data->func = sess_auth_rawntlmssp_negotiate;
1718		break;
1719	default:
1720		cifs_dbg(VFS, "secType %d not supported!\n", type);
1721		return -ENOSYS;
1722	}
1723
1724	return 0;
1725}
1726
1727int CIFS_SessSetup(const unsigned int xid, struct cifs_ses *ses,
1728		    const struct nls_table *nls_cp)
1729{
1730	int rc = 0;
1731	struct sess_data *sess_data;
1732
1733	if (ses == NULL) {
1734		WARN(1, "%s: ses == NULL!", __func__);
1735		return -EINVAL;
1736	}
1737
1738	sess_data = kzalloc(sizeof(struct sess_data), GFP_KERNEL);
1739	if (!sess_data)
1740		return -ENOMEM;
1741
1742	rc = select_sec(ses, sess_data);
1743	if (rc)
1744		goto out;
1745
1746	sess_data->xid = xid;
1747	sess_data->ses = ses;
1748	sess_data->buf0_type = CIFS_NO_BUFFER;
1749	sess_data->nls_cp = (struct nls_table *) nls_cp;
1750
1751	while (sess_data->func)
1752		sess_data->func(sess_data);
1753
1754	/* Store result before we free sess_data */
1755	rc = sess_data->result;
1756
1757out:
1758	kfree(sess_data);
1759	return rc;
1760}
1761