1 // SPDX-License-Identifier: LGPL-2.1
2 /*
3  *
4  *   Copyright (C) International Business Machines  Corp., 2009, 2013
5  *                 Etersoft, 2012
6  *   Author(s): Steve French (sfrench@us.ibm.com)
7  *              Pavel Shilovsky (pshilovsky@samba.org) 2012
8  *
9  *   Contains the routines for constructing the SMB2 PDUs themselves
10  *
11  */
12 
13  /* SMB2 PDU handling routines here - except for leftovers (eg session setup) */
14  /* Note that there are handle based routines which must be		      */
15  /* treated slightly differently for reconnection purposes since we never     */
16  /* want to reuse a stale file handle and only the caller knows the file info */
17 
18 #include <linux/fs.h>
19 #include <linux/kernel.h>
20 #include <linux/vfs.h>
21 #include <linux/task_io_accounting_ops.h>
22 #include <linux/uaccess.h>
23 #include <linux/uuid.h>
24 #include <linux/pagemap.h>
25 #include <linux/xattr.h>
26 #include "cifsglob.h"
27 #include "cifsacl.h"
28 #include "cifsproto.h"
29 #include "smb2proto.h"
30 #include "cifs_unicode.h"
31 #include "cifs_debug.h"
32 #include "ntlmssp.h"
33 #include "smb2status.h"
34 #include "smb2glob.h"
35 #include "cifspdu.h"
36 #include "cifs_spnego.h"
37 #include "smbdirect.h"
38 #include "trace.h"
39 #ifdef CONFIG_CIFS_DFS_UPCALL
40 #include "dfs_cache.h"
41 #endif
42 
43 /*
44  *  The following table defines the expected "StructureSize" of SMB2 requests
45  *  in order by SMB2 command.  This is similar to "wct" in SMB/CIFS requests.
46  *
47  *  Note that commands are defined in smb2pdu.h in le16 but the array below is
48  *  indexed by command in host byte order.
49  */
50 static const int smb2_req_struct_sizes[NUMBER_OF_SMB2_COMMANDS] = {
51 	/* SMB2_NEGOTIATE */ 36,
52 	/* SMB2_SESSION_SETUP */ 25,
53 	/* SMB2_LOGOFF */ 4,
54 	/* SMB2_TREE_CONNECT */	9,
55 	/* SMB2_TREE_DISCONNECT */ 4,
56 	/* SMB2_CREATE */ 57,
57 	/* SMB2_CLOSE */ 24,
58 	/* SMB2_FLUSH */ 24,
59 	/* SMB2_READ */	49,
60 	/* SMB2_WRITE */ 49,
61 	/* SMB2_LOCK */	48,
62 	/* SMB2_IOCTL */ 57,
63 	/* SMB2_CANCEL */ 4,
64 	/* SMB2_ECHO */ 4,
65 	/* SMB2_QUERY_DIRECTORY */ 33,
66 	/* SMB2_CHANGE_NOTIFY */ 32,
67 	/* SMB2_QUERY_INFO */ 41,
68 	/* SMB2_SET_INFO */ 33,
69 	/* SMB2_OPLOCK_BREAK */ 24 /* BB this is 36 for LEASE_BREAK variant */
70 };
71 
smb3_encryption_required(const struct cifs_tcon * tcon)72 int smb3_encryption_required(const struct cifs_tcon *tcon)
73 {
74 	if (!tcon || !tcon->ses)
75 		return 0;
76 	if ((tcon->ses->session_flags & SMB2_SESSION_FLAG_ENCRYPT_DATA) ||
77 	    (tcon->share_flags & SHI1005_FLAGS_ENCRYPT_DATA))
78 		return 1;
79 	if (tcon->seal &&
80 	    (tcon->ses->server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION))
81 		return 1;
82 	return 0;
83 }
84 
85 static void
smb2_hdr_assemble(struct smb2_hdr * shdr,__le16 smb2_cmd,const struct cifs_tcon * tcon,struct TCP_Server_Info * server)86 smb2_hdr_assemble(struct smb2_hdr *shdr, __le16 smb2_cmd,
87 		  const struct cifs_tcon *tcon,
88 		  struct TCP_Server_Info *server)
89 {
90 	shdr->ProtocolId = SMB2_PROTO_NUMBER;
91 	shdr->StructureSize = cpu_to_le16(64);
92 	shdr->Command = smb2_cmd;
93 	if (server) {
94 		spin_lock(&server->req_lock);
95 		/* Request up to 10 credits but don't go over the limit. */
96 		if (server->credits >= server->max_credits)
97 			shdr->CreditRequest = cpu_to_le16(0);
98 		else
99 			shdr->CreditRequest = cpu_to_le16(
100 				min_t(int, server->max_credits -
101 						server->credits, 10));
102 		spin_unlock(&server->req_lock);
103 	} else {
104 		shdr->CreditRequest = cpu_to_le16(2);
105 	}
106 	shdr->Id.SyncId.ProcessId = cpu_to_le32((__u16)current->tgid);
107 
108 	if (!tcon)
109 		goto out;
110 
111 	/* GLOBAL_CAP_LARGE_MTU will only be set if dialect > SMB2.02 */
112 	/* See sections 2.2.4 and 3.2.4.1.5 of MS-SMB2 */
113 	if (server && (server->capabilities & SMB2_GLOBAL_CAP_LARGE_MTU))
114 		shdr->CreditCharge = cpu_to_le16(1);
115 	/* else CreditCharge MBZ */
116 
117 	shdr->Id.SyncId.TreeId = cpu_to_le32(tcon->tid);
118 	/* Uid is not converted */
119 	if (tcon->ses)
120 		shdr->SessionId = cpu_to_le64(tcon->ses->Suid);
121 
122 	/*
123 	 * If we would set SMB2_FLAGS_DFS_OPERATIONS on open we also would have
124 	 * to pass the path on the Open SMB prefixed by \\server\share.
125 	 * Not sure when we would need to do the augmented path (if ever) and
126 	 * setting this flag breaks the SMB2 open operation since it is
127 	 * illegal to send an empty path name (without \\server\share prefix)
128 	 * when the DFS flag is set in the SMB open header. We could
129 	 * consider setting the flag on all operations other than open
130 	 * but it is safer to net set it for now.
131 	 */
132 /*	if (tcon->share_flags & SHI1005_FLAGS_DFS)
133 		shdr->Flags |= SMB2_FLAGS_DFS_OPERATIONS; */
134 
135 	if (server && server->sign && !smb3_encryption_required(tcon))
136 		shdr->Flags |= SMB2_FLAGS_SIGNED;
137 out:
138 	return;
139 }
140 
141 static int
smb2_reconnect(__le16 smb2_command,struct cifs_tcon * tcon,struct TCP_Server_Info * server)142 smb2_reconnect(__le16 smb2_command, struct cifs_tcon *tcon,
143 	       struct TCP_Server_Info *server)
144 {
145 	int rc = 0;
146 	struct nls_table *nls_codepage;
147 	struct cifs_ses *ses;
148 	int retries;
149 
150 	/*
151 	 * SMB2s NegProt, SessSetup, Logoff do not have tcon yet so
152 	 * check for tcp and smb session status done differently
153 	 * for those three - in the calling routine.
154 	 */
155 	if (tcon == NULL)
156 		return 0;
157 
158 	/*
159 	 * Need to also skip SMB2_IOCTL because it is used for checking nested dfs links in
160 	 * cifs_tree_connect().
161 	 */
162 	if (smb2_command == SMB2_TREE_CONNECT || smb2_command == SMB2_IOCTL)
163 		return 0;
164 
165 	spin_lock(&cifs_tcp_ses_lock);
166 	if (tcon->status == TID_EXITING) {
167 		/*
168 		 * only tree disconnect, open, and write,
169 		 * (and ulogoff which does not have tcon)
170 		 * are allowed as we start force umount.
171 		 */
172 		if ((smb2_command != SMB2_WRITE) &&
173 		   (smb2_command != SMB2_CREATE) &&
174 		   (smb2_command != SMB2_TREE_DISCONNECT)) {
175 			spin_unlock(&cifs_tcp_ses_lock);
176 			cifs_dbg(FYI, "can not send cmd %d while umounting\n",
177 				 smb2_command);
178 			return -ENODEV;
179 		}
180 	}
181 	spin_unlock(&cifs_tcp_ses_lock);
182 	if ((!tcon->ses) || (tcon->ses->ses_status == SES_EXITING) ||
183 	    (!tcon->ses->server) || !server)
184 		return -EIO;
185 
186 	ses = tcon->ses;
187 	retries = server->nr_targets;
188 
189 	/*
190 	 * Give demultiplex thread up to 10 seconds to each target available for
191 	 * reconnect -- should be greater than cifs socket timeout which is 7
192 	 * seconds.
193 	 */
194 	while (server->tcpStatus == CifsNeedReconnect) {
195 		/*
196 		 * Return to caller for TREE_DISCONNECT and LOGOFF and CLOSE
197 		 * here since they are implicitly done when session drops.
198 		 */
199 		switch (smb2_command) {
200 		/*
201 		 * BB Should we keep oplock break and add flush to exceptions?
202 		 */
203 		case SMB2_TREE_DISCONNECT:
204 		case SMB2_CANCEL:
205 		case SMB2_CLOSE:
206 		case SMB2_OPLOCK_BREAK:
207 			return -EAGAIN;
208 		}
209 
210 		rc = wait_event_interruptible_timeout(server->response_q,
211 						      (server->tcpStatus != CifsNeedReconnect),
212 						      10 * HZ);
213 		if (rc < 0) {
214 			cifs_dbg(FYI, "%s: aborting reconnect due to a received signal by the process\n",
215 				 __func__);
216 			return -ERESTARTSYS;
217 		}
218 
219 		/* are we still trying to reconnect? */
220 		spin_lock(&cifs_tcp_ses_lock);
221 		if (server->tcpStatus != CifsNeedReconnect) {
222 			spin_unlock(&cifs_tcp_ses_lock);
223 			break;
224 		}
225 		spin_unlock(&cifs_tcp_ses_lock);
226 
227 		if (retries && --retries)
228 			continue;
229 
230 		/*
231 		 * on "soft" mounts we wait once. Hard mounts keep
232 		 * retrying until process is killed or server comes
233 		 * back on-line
234 		 */
235 		if (!tcon->retry) {
236 			cifs_dbg(FYI, "gave up waiting on reconnect in smb_init\n");
237 			return -EHOSTDOWN;
238 		}
239 		retries = server->nr_targets;
240 	}
241 
242 	spin_lock(&ses->chan_lock);
243 	if (!cifs_chan_needs_reconnect(ses, server) && !tcon->need_reconnect) {
244 		spin_unlock(&ses->chan_lock);
245 		return 0;
246 	}
247 	spin_unlock(&ses->chan_lock);
248 	cifs_dbg(FYI, "sess reconnect mask: 0x%lx, tcon reconnect: %d",
249 		 tcon->ses->chans_need_reconnect,
250 		 tcon->need_reconnect);
251 
252 	nls_codepage = load_nls_default();
253 
254 	/*
255 	 * Recheck after acquire mutex. If another thread is negotiating
256 	 * and the server never sends an answer the socket will be closed
257 	 * and tcpStatus set to reconnect.
258 	 */
259 	spin_lock(&cifs_tcp_ses_lock);
260 	if (server->tcpStatus == CifsNeedReconnect) {
261 		spin_unlock(&cifs_tcp_ses_lock);
262 		rc = -EHOSTDOWN;
263 		goto out;
264 	}
265 	spin_unlock(&cifs_tcp_ses_lock);
266 
267 	/*
268 	 * need to prevent multiple threads trying to simultaneously
269 	 * reconnect the same SMB session
270 	 */
271 	spin_lock(&ses->chan_lock);
272 	if (!cifs_chan_needs_reconnect(ses, server)) {
273 		spin_unlock(&ses->chan_lock);
274 
275 		/* this means that we only need to tree connect */
276 		if (tcon->need_reconnect)
277 			goto skip_sess_setup;
278 
279 		goto out;
280 	}
281 	spin_unlock(&ses->chan_lock);
282 
283 	mutex_lock(&ses->session_mutex);
284 	rc = cifs_negotiate_protocol(0, ses, server);
285 	if (!rc) {
286 		rc = cifs_setup_session(0, ses, server, nls_codepage);
287 		if ((rc == -EACCES) && !tcon->retry) {
288 			mutex_unlock(&ses->session_mutex);
289 			rc = -EHOSTDOWN;
290 			goto failed;
291 		} else if (rc) {
292 			mutex_unlock(&ses->session_mutex);
293 			goto out;
294 		}
295 	} else {
296 		mutex_unlock(&ses->session_mutex);
297 		goto out;
298 	}
299 	mutex_unlock(&ses->session_mutex);
300 
301 skip_sess_setup:
302 	mutex_lock(&ses->session_mutex);
303 	if (!tcon->need_reconnect) {
304 		mutex_unlock(&ses->session_mutex);
305 		goto out;
306 	}
307 	cifs_mark_open_files_invalid(tcon);
308 	if (tcon->use_persistent)
309 		tcon->need_reopen_files = true;
310 
311 	rc = cifs_tree_connect(0, tcon, nls_codepage);
312 	mutex_unlock(&ses->session_mutex);
313 
314 	cifs_dbg(FYI, "reconnect tcon rc = %d\n", rc);
315 	if (rc) {
316 		/* If sess reconnected but tcon didn't, something strange ... */
317 		pr_warn_once("reconnect tcon failed rc = %d\n", rc);
318 		goto out;
319 	}
320 
321 	if (smb2_command != SMB2_INTERNAL_CMD)
322 		mod_delayed_work(cifsiod_wq, &server->reconnect, 0);
323 
324 	atomic_inc(&tconInfoReconnectCount);
325 out:
326 	/*
327 	 * Check if handle based operation so we know whether we can continue
328 	 * or not without returning to caller to reset file handle.
329 	 */
330 	/*
331 	 * BB Is flush done by server on drop of tcp session? Should we special
332 	 * case it and skip above?
333 	 */
334 	switch (smb2_command) {
335 	case SMB2_FLUSH:
336 	case SMB2_READ:
337 	case SMB2_WRITE:
338 	case SMB2_LOCK:
339 	case SMB2_IOCTL:
340 	case SMB2_QUERY_DIRECTORY:
341 	case SMB2_CHANGE_NOTIFY:
342 	case SMB2_QUERY_INFO:
343 	case SMB2_SET_INFO:
344 		rc = -EAGAIN;
345 	}
346 failed:
347 	unload_nls(nls_codepage);
348 	return rc;
349 }
350 
351 static void
fill_small_buf(__le16 smb2_command,struct cifs_tcon * tcon,struct TCP_Server_Info * server,void * buf,unsigned int * total_len)352 fill_small_buf(__le16 smb2_command, struct cifs_tcon *tcon,
353 	       struct TCP_Server_Info *server,
354 	       void *buf,
355 	       unsigned int *total_len)
356 {
357 	struct smb2_pdu *spdu = (struct smb2_pdu *)buf;
358 	/* lookup word count ie StructureSize from table */
359 	__u16 parmsize = smb2_req_struct_sizes[le16_to_cpu(smb2_command)];
360 
361 	/*
362 	 * smaller than SMALL_BUFFER_SIZE but bigger than fixed area of
363 	 * largest operations (Create)
364 	 */
365 	memset(buf, 0, 256);
366 
367 	smb2_hdr_assemble(&spdu->hdr, smb2_command, tcon, server);
368 	spdu->StructureSize2 = cpu_to_le16(parmsize);
369 
370 	*total_len = parmsize + sizeof(struct smb2_hdr);
371 }
372 
373 /*
374  * Allocate and return pointer to an SMB request hdr, and set basic
375  * SMB information in the SMB header. If the return code is zero, this
376  * function must have filled in request_buf pointer.
377  */
__smb2_plain_req_init(__le16 smb2_command,struct cifs_tcon * tcon,struct TCP_Server_Info * server,void ** request_buf,unsigned int * total_len)378 static int __smb2_plain_req_init(__le16 smb2_command, struct cifs_tcon *tcon,
379 				 struct TCP_Server_Info *server,
380 				 void **request_buf, unsigned int *total_len)
381 {
382 	/* BB eventually switch this to SMB2 specific small buf size */
383 	if (smb2_command == SMB2_SET_INFO)
384 		*request_buf = cifs_buf_get();
385 	else
386 		*request_buf = cifs_small_buf_get();
387 	if (*request_buf == NULL) {
388 		/* BB should we add a retry in here if not a writepage? */
389 		return -ENOMEM;
390 	}
391 
392 	fill_small_buf(smb2_command, tcon, server,
393 		       (struct smb2_hdr *)(*request_buf),
394 		       total_len);
395 
396 	if (tcon != NULL) {
397 		uint16_t com_code = le16_to_cpu(smb2_command);
398 		cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_sent[com_code]);
399 		cifs_stats_inc(&tcon->num_smbs_sent);
400 	}
401 
402 	return 0;
403 }
404 
smb2_plain_req_init(__le16 smb2_command,struct cifs_tcon * tcon,struct TCP_Server_Info * server,void ** request_buf,unsigned int * total_len)405 static int smb2_plain_req_init(__le16 smb2_command, struct cifs_tcon *tcon,
406 			       struct TCP_Server_Info *server,
407 			       void **request_buf, unsigned int *total_len)
408 {
409 	int rc;
410 
411 	rc = smb2_reconnect(smb2_command, tcon, server);
412 	if (rc)
413 		return rc;
414 
415 	return __smb2_plain_req_init(smb2_command, tcon, server, request_buf,
416 				     total_len);
417 }
418 
smb2_ioctl_req_init(u32 opcode,struct cifs_tcon * tcon,struct TCP_Server_Info * server,void ** request_buf,unsigned int * total_len)419 static int smb2_ioctl_req_init(u32 opcode, struct cifs_tcon *tcon,
420 			       struct TCP_Server_Info *server,
421 			       void **request_buf, unsigned int *total_len)
422 {
423 	/* Skip reconnect only for FSCTL_VALIDATE_NEGOTIATE_INFO IOCTLs */
424 	if (opcode == FSCTL_VALIDATE_NEGOTIATE_INFO) {
425 		return __smb2_plain_req_init(SMB2_IOCTL, tcon, server,
426 					     request_buf, total_len);
427 	}
428 	return smb2_plain_req_init(SMB2_IOCTL, tcon, server,
429 				   request_buf, total_len);
430 }
431 
432 /* For explanation of negotiate contexts see MS-SMB2 section 2.2.3.1 */
433 
434 static void
build_preauth_ctxt(struct smb2_preauth_neg_context * pneg_ctxt)435 build_preauth_ctxt(struct smb2_preauth_neg_context *pneg_ctxt)
436 {
437 	pneg_ctxt->ContextType = SMB2_PREAUTH_INTEGRITY_CAPABILITIES;
438 	pneg_ctxt->DataLength = cpu_to_le16(38);
439 	pneg_ctxt->HashAlgorithmCount = cpu_to_le16(1);
440 	pneg_ctxt->SaltLength = cpu_to_le16(SMB311_SALT_SIZE);
441 	get_random_bytes(pneg_ctxt->Salt, SMB311_SALT_SIZE);
442 	pneg_ctxt->HashAlgorithms = SMB2_PREAUTH_INTEGRITY_SHA512;
443 }
444 
445 static void
build_compression_ctxt(struct smb2_compression_capabilities_context * pneg_ctxt)446 build_compression_ctxt(struct smb2_compression_capabilities_context *pneg_ctxt)
447 {
448 	pneg_ctxt->ContextType = SMB2_COMPRESSION_CAPABILITIES;
449 	pneg_ctxt->DataLength =
450 		cpu_to_le16(sizeof(struct smb2_compression_capabilities_context)
451 			  - sizeof(struct smb2_neg_context));
452 	pneg_ctxt->CompressionAlgorithmCount = cpu_to_le16(3);
453 	pneg_ctxt->CompressionAlgorithms[0] = SMB3_COMPRESS_LZ77;
454 	pneg_ctxt->CompressionAlgorithms[1] = SMB3_COMPRESS_LZ77_HUFF;
455 	pneg_ctxt->CompressionAlgorithms[2] = SMB3_COMPRESS_LZNT1;
456 }
457 
458 static unsigned int
build_signing_ctxt(struct smb2_signing_capabilities * pneg_ctxt)459 build_signing_ctxt(struct smb2_signing_capabilities *pneg_ctxt)
460 {
461 	unsigned int ctxt_len = sizeof(struct smb2_signing_capabilities);
462 	unsigned short num_algs = 1; /* number of signing algorithms sent */
463 
464 	pneg_ctxt->ContextType = SMB2_SIGNING_CAPABILITIES;
465 	/*
466 	 * Context Data length must be rounded to multiple of 8 for some servers
467 	 */
468 	pneg_ctxt->DataLength = cpu_to_le16(DIV_ROUND_UP(
469 				sizeof(struct smb2_signing_capabilities) -
470 				sizeof(struct smb2_neg_context) +
471 				(num_algs * 2 /* sizeof u16 */), 8) * 8);
472 	pneg_ctxt->SigningAlgorithmCount = cpu_to_le16(num_algs);
473 	pneg_ctxt->SigningAlgorithms[0] = cpu_to_le16(SIGNING_ALG_AES_CMAC);
474 
475 	ctxt_len += 2 /* sizeof le16 */ * num_algs;
476 	ctxt_len = DIV_ROUND_UP(ctxt_len, 8) * 8;
477 	return ctxt_len;
478 	/* TBD add SIGNING_ALG_AES_GMAC and/or SIGNING_ALG_HMAC_SHA256 */
479 }
480 
481 static void
build_encrypt_ctxt(struct smb2_encryption_neg_context * pneg_ctxt)482 build_encrypt_ctxt(struct smb2_encryption_neg_context *pneg_ctxt)
483 {
484 	pneg_ctxt->ContextType = SMB2_ENCRYPTION_CAPABILITIES;
485 	if (require_gcm_256) {
486 		pneg_ctxt->DataLength = cpu_to_le16(4); /* Cipher Count + 1 cipher */
487 		pneg_ctxt->CipherCount = cpu_to_le16(1);
488 		pneg_ctxt->Ciphers[0] = SMB2_ENCRYPTION_AES256_GCM;
489 	} else if (enable_gcm_256) {
490 		pneg_ctxt->DataLength = cpu_to_le16(8); /* Cipher Count + 3 ciphers */
491 		pneg_ctxt->CipherCount = cpu_to_le16(3);
492 		pneg_ctxt->Ciphers[0] = SMB2_ENCRYPTION_AES128_GCM;
493 		pneg_ctxt->Ciphers[1] = SMB2_ENCRYPTION_AES256_GCM;
494 		pneg_ctxt->Ciphers[2] = SMB2_ENCRYPTION_AES128_CCM;
495 	} else {
496 		pneg_ctxt->DataLength = cpu_to_le16(6); /* Cipher Count + 2 ciphers */
497 		pneg_ctxt->CipherCount = cpu_to_le16(2);
498 		pneg_ctxt->Ciphers[0] = SMB2_ENCRYPTION_AES128_GCM;
499 		pneg_ctxt->Ciphers[1] = SMB2_ENCRYPTION_AES128_CCM;
500 	}
501 }
502 
503 static unsigned int
build_netname_ctxt(struct smb2_netname_neg_context * pneg_ctxt,char * hostname)504 build_netname_ctxt(struct smb2_netname_neg_context *pneg_ctxt, char *hostname)
505 {
506 	struct nls_table *cp = load_nls_default();
507 
508 	pneg_ctxt->ContextType = SMB2_NETNAME_NEGOTIATE_CONTEXT_ID;
509 
510 	/* copy up to max of first 100 bytes of server name to NetName field */
511 	pneg_ctxt->DataLength = cpu_to_le16(2 * cifs_strtoUTF16(pneg_ctxt->NetName, hostname, 100, cp));
512 	/* context size is DataLength + minimal smb2_neg_context */
513 	return DIV_ROUND_UP(le16_to_cpu(pneg_ctxt->DataLength) +
514 			sizeof(struct smb2_neg_context), 8) * 8;
515 }
516 
517 static void
build_posix_ctxt(struct smb2_posix_neg_context * pneg_ctxt)518 build_posix_ctxt(struct smb2_posix_neg_context *pneg_ctxt)
519 {
520 	pneg_ctxt->ContextType = SMB2_POSIX_EXTENSIONS_AVAILABLE;
521 	pneg_ctxt->DataLength = cpu_to_le16(POSIX_CTXT_DATA_LEN);
522 	/* SMB2_CREATE_TAG_POSIX is "0x93AD25509CB411E7B42383DE968BCD7C" */
523 	pneg_ctxt->Name[0] = 0x93;
524 	pneg_ctxt->Name[1] = 0xAD;
525 	pneg_ctxt->Name[2] = 0x25;
526 	pneg_ctxt->Name[3] = 0x50;
527 	pneg_ctxt->Name[4] = 0x9C;
528 	pneg_ctxt->Name[5] = 0xB4;
529 	pneg_ctxt->Name[6] = 0x11;
530 	pneg_ctxt->Name[7] = 0xE7;
531 	pneg_ctxt->Name[8] = 0xB4;
532 	pneg_ctxt->Name[9] = 0x23;
533 	pneg_ctxt->Name[10] = 0x83;
534 	pneg_ctxt->Name[11] = 0xDE;
535 	pneg_ctxt->Name[12] = 0x96;
536 	pneg_ctxt->Name[13] = 0x8B;
537 	pneg_ctxt->Name[14] = 0xCD;
538 	pneg_ctxt->Name[15] = 0x7C;
539 }
540 
541 static void
assemble_neg_contexts(struct smb2_negotiate_req * req,struct TCP_Server_Info * server,unsigned int * total_len)542 assemble_neg_contexts(struct smb2_negotiate_req *req,
543 		      struct TCP_Server_Info *server, unsigned int *total_len)
544 {
545 	char *pneg_ctxt;
546 	char *hostname = NULL;
547 	unsigned int ctxt_len, neg_context_count;
548 
549 	if (*total_len > 200) {
550 		/* In case length corrupted don't want to overrun smb buffer */
551 		cifs_server_dbg(VFS, "Bad frame length assembling neg contexts\n");
552 		return;
553 	}
554 
555 	/*
556 	 * round up total_len of fixed part of SMB3 negotiate request to 8
557 	 * byte boundary before adding negotiate contexts
558 	 */
559 	*total_len = roundup(*total_len, 8);
560 
561 	pneg_ctxt = (*total_len) + (char *)req;
562 	req->NegotiateContextOffset = cpu_to_le32(*total_len);
563 
564 	build_preauth_ctxt((struct smb2_preauth_neg_context *)pneg_ctxt);
565 	ctxt_len = DIV_ROUND_UP(sizeof(struct smb2_preauth_neg_context), 8) * 8;
566 	*total_len += ctxt_len;
567 	pneg_ctxt += ctxt_len;
568 
569 	build_encrypt_ctxt((struct smb2_encryption_neg_context *)pneg_ctxt);
570 	ctxt_len = DIV_ROUND_UP(sizeof(struct smb2_encryption_neg_context), 8) * 8;
571 	*total_len += ctxt_len;
572 	pneg_ctxt += ctxt_len;
573 
574 	/*
575 	 * secondary channels don't have the hostname field populated
576 	 * use the hostname field in the primary channel instead
577 	 */
578 	hostname = CIFS_SERVER_IS_CHAN(server) ?
579 		server->primary_server->hostname : server->hostname;
580 	if (hostname && (hostname[0] != 0)) {
581 		ctxt_len = build_netname_ctxt((struct smb2_netname_neg_context *)pneg_ctxt,
582 					      hostname);
583 		*total_len += ctxt_len;
584 		pneg_ctxt += ctxt_len;
585 		neg_context_count = 3;
586 	} else
587 		neg_context_count = 2;
588 
589 	build_posix_ctxt((struct smb2_posix_neg_context *)pneg_ctxt);
590 	*total_len += sizeof(struct smb2_posix_neg_context);
591 	pneg_ctxt += sizeof(struct smb2_posix_neg_context);
592 	neg_context_count++;
593 
594 	if (server->compress_algorithm) {
595 		build_compression_ctxt((struct smb2_compression_capabilities_context *)
596 				pneg_ctxt);
597 		ctxt_len = DIV_ROUND_UP(
598 			sizeof(struct smb2_compression_capabilities_context),
599 				8) * 8;
600 		*total_len += ctxt_len;
601 		pneg_ctxt += ctxt_len;
602 		neg_context_count++;
603 	}
604 
605 	if (enable_negotiate_signing) {
606 		ctxt_len = build_signing_ctxt((struct smb2_signing_capabilities *)
607 				pneg_ctxt);
608 		*total_len += ctxt_len;
609 		pneg_ctxt += ctxt_len;
610 		neg_context_count++;
611 	}
612 
613 	/* check for and add transport_capabilities and signing capabilities */
614 	req->NegotiateContextCount = cpu_to_le16(neg_context_count);
615 
616 }
617 
decode_preauth_context(struct smb2_preauth_neg_context * ctxt)618 static void decode_preauth_context(struct smb2_preauth_neg_context *ctxt)
619 {
620 	unsigned int len = le16_to_cpu(ctxt->DataLength);
621 
622 	/* If invalid preauth context warn but use what we requested, SHA-512 */
623 	if (len < MIN_PREAUTH_CTXT_DATA_LEN) {
624 		pr_warn_once("server sent bad preauth context\n");
625 		return;
626 	} else if (len < MIN_PREAUTH_CTXT_DATA_LEN + le16_to_cpu(ctxt->SaltLength)) {
627 		pr_warn_once("server sent invalid SaltLength\n");
628 		return;
629 	}
630 	if (le16_to_cpu(ctxt->HashAlgorithmCount) != 1)
631 		pr_warn_once("Invalid SMB3 hash algorithm count\n");
632 	if (ctxt->HashAlgorithms != SMB2_PREAUTH_INTEGRITY_SHA512)
633 		pr_warn_once("unknown SMB3 hash algorithm\n");
634 }
635 
decode_compress_ctx(struct TCP_Server_Info * server,struct smb2_compression_capabilities_context * ctxt)636 static void decode_compress_ctx(struct TCP_Server_Info *server,
637 			 struct smb2_compression_capabilities_context *ctxt)
638 {
639 	unsigned int len = le16_to_cpu(ctxt->DataLength);
640 
641 	/* sizeof compress context is a one element compression capbility struct */
642 	if (len < 10) {
643 		pr_warn_once("server sent bad compression cntxt\n");
644 		return;
645 	}
646 	if (le16_to_cpu(ctxt->CompressionAlgorithmCount) != 1) {
647 		pr_warn_once("Invalid SMB3 compress algorithm count\n");
648 		return;
649 	}
650 	if (le16_to_cpu(ctxt->CompressionAlgorithms[0]) > 3) {
651 		pr_warn_once("unknown compression algorithm\n");
652 		return;
653 	}
654 	server->compress_algorithm = ctxt->CompressionAlgorithms[0];
655 }
656 
decode_encrypt_ctx(struct TCP_Server_Info * server,struct smb2_encryption_neg_context * ctxt)657 static int decode_encrypt_ctx(struct TCP_Server_Info *server,
658 			      struct smb2_encryption_neg_context *ctxt)
659 {
660 	unsigned int len = le16_to_cpu(ctxt->DataLength);
661 
662 	cifs_dbg(FYI, "decode SMB3.11 encryption neg context of len %d\n", len);
663 	if (len < MIN_ENCRYPT_CTXT_DATA_LEN) {
664 		pr_warn_once("server sent bad crypto ctxt len\n");
665 		return -EINVAL;
666 	}
667 
668 	if (le16_to_cpu(ctxt->CipherCount) != 1) {
669 		pr_warn_once("Invalid SMB3.11 cipher count\n");
670 		return -EINVAL;
671 	}
672 	cifs_dbg(FYI, "SMB311 cipher type:%d\n", le16_to_cpu(ctxt->Ciphers[0]));
673 	if (require_gcm_256) {
674 		if (ctxt->Ciphers[0] != SMB2_ENCRYPTION_AES256_GCM) {
675 			cifs_dbg(VFS, "Server does not support requested encryption type (AES256 GCM)\n");
676 			return -EOPNOTSUPP;
677 		}
678 	} else if (ctxt->Ciphers[0] == 0) {
679 		/*
680 		 * e.g. if server only supported AES256_CCM (very unlikely)
681 		 * or server supported no encryption types or had all disabled.
682 		 * Since GLOBAL_CAP_ENCRYPTION will be not set, in the case
683 		 * in which mount requested encryption ("seal") checks later
684 		 * on during tree connection will return proper rc, but if
685 		 * seal not requested by client, since server is allowed to
686 		 * return 0 to indicate no supported cipher, we can't fail here
687 		 */
688 		server->cipher_type = 0;
689 		server->capabilities &= ~SMB2_GLOBAL_CAP_ENCRYPTION;
690 		pr_warn_once("Server does not support requested encryption types\n");
691 		return 0;
692 	} else if ((ctxt->Ciphers[0] != SMB2_ENCRYPTION_AES128_CCM) &&
693 		   (ctxt->Ciphers[0] != SMB2_ENCRYPTION_AES128_GCM) &&
694 		   (ctxt->Ciphers[0] != SMB2_ENCRYPTION_AES256_GCM)) {
695 		/* server returned a cipher we didn't ask for */
696 		pr_warn_once("Invalid SMB3.11 cipher returned\n");
697 		return -EINVAL;
698 	}
699 	server->cipher_type = ctxt->Ciphers[0];
700 	server->capabilities |= SMB2_GLOBAL_CAP_ENCRYPTION;
701 	return 0;
702 }
703 
decode_signing_ctx(struct TCP_Server_Info * server,struct smb2_signing_capabilities * pctxt)704 static void decode_signing_ctx(struct TCP_Server_Info *server,
705 			       struct smb2_signing_capabilities *pctxt)
706 {
707 	unsigned int len = le16_to_cpu(pctxt->DataLength);
708 
709 	if ((len < 4) || (len > 16)) {
710 		pr_warn_once("server sent bad signing negcontext\n");
711 		return;
712 	}
713 	if (le16_to_cpu(pctxt->SigningAlgorithmCount) != 1) {
714 		pr_warn_once("Invalid signing algorithm count\n");
715 		return;
716 	}
717 	if (le16_to_cpu(pctxt->SigningAlgorithms[0]) > 2) {
718 		pr_warn_once("unknown signing algorithm\n");
719 		return;
720 	}
721 
722 	server->signing_negotiated = true;
723 	server->signing_algorithm = le16_to_cpu(pctxt->SigningAlgorithms[0]);
724 	cifs_dbg(FYI, "signing algorithm %d chosen\n",
725 		     server->signing_algorithm);
726 }
727 
728 
smb311_decode_neg_context(struct smb2_negotiate_rsp * rsp,struct TCP_Server_Info * server,unsigned int len_of_smb)729 static int smb311_decode_neg_context(struct smb2_negotiate_rsp *rsp,
730 				     struct TCP_Server_Info *server,
731 				     unsigned int len_of_smb)
732 {
733 	struct smb2_neg_context *pctx;
734 	unsigned int offset = le32_to_cpu(rsp->NegotiateContextOffset);
735 	unsigned int ctxt_cnt = le16_to_cpu(rsp->NegotiateContextCount);
736 	unsigned int len_of_ctxts, i;
737 	int rc = 0;
738 
739 	cifs_dbg(FYI, "decoding %d negotiate contexts\n", ctxt_cnt);
740 	if (len_of_smb <= offset) {
741 		cifs_server_dbg(VFS, "Invalid response: negotiate context offset\n");
742 		return -EINVAL;
743 	}
744 
745 	len_of_ctxts = len_of_smb - offset;
746 
747 	for (i = 0; i < ctxt_cnt; i++) {
748 		int clen;
749 		/* check that offset is not beyond end of SMB */
750 		if (len_of_ctxts == 0)
751 			break;
752 
753 		if (len_of_ctxts < sizeof(struct smb2_neg_context))
754 			break;
755 
756 		pctx = (struct smb2_neg_context *)(offset + (char *)rsp);
757 		clen = le16_to_cpu(pctx->DataLength);
758 		if (clen > len_of_ctxts)
759 			break;
760 
761 		if (pctx->ContextType == SMB2_PREAUTH_INTEGRITY_CAPABILITIES)
762 			decode_preauth_context(
763 				(struct smb2_preauth_neg_context *)pctx);
764 		else if (pctx->ContextType == SMB2_ENCRYPTION_CAPABILITIES)
765 			rc = decode_encrypt_ctx(server,
766 				(struct smb2_encryption_neg_context *)pctx);
767 		else if (pctx->ContextType == SMB2_COMPRESSION_CAPABILITIES)
768 			decode_compress_ctx(server,
769 				(struct smb2_compression_capabilities_context *)pctx);
770 		else if (pctx->ContextType == SMB2_POSIX_EXTENSIONS_AVAILABLE)
771 			server->posix_ext_supported = true;
772 		else if (pctx->ContextType == SMB2_SIGNING_CAPABILITIES)
773 			decode_signing_ctx(server,
774 				(struct smb2_signing_capabilities *)pctx);
775 		else
776 			cifs_server_dbg(VFS, "unknown negcontext of type %d ignored\n",
777 				le16_to_cpu(pctx->ContextType));
778 
779 		if (rc)
780 			break;
781 		/* offsets must be 8 byte aligned */
782 		clen = (clen + 7) & ~0x7;
783 		offset += clen + sizeof(struct smb2_neg_context);
784 		len_of_ctxts -= clen;
785 	}
786 	return rc;
787 }
788 
789 static struct create_posix *
create_posix_buf(umode_t mode)790 create_posix_buf(umode_t mode)
791 {
792 	struct create_posix *buf;
793 
794 	buf = kzalloc(sizeof(struct create_posix),
795 			GFP_KERNEL);
796 	if (!buf)
797 		return NULL;
798 
799 	buf->ccontext.DataOffset =
800 		cpu_to_le16(offsetof(struct create_posix, Mode));
801 	buf->ccontext.DataLength = cpu_to_le32(4);
802 	buf->ccontext.NameOffset =
803 		cpu_to_le16(offsetof(struct create_posix, Name));
804 	buf->ccontext.NameLength = cpu_to_le16(16);
805 
806 	/* SMB2_CREATE_TAG_POSIX is "0x93AD25509CB411E7B42383DE968BCD7C" */
807 	buf->Name[0] = 0x93;
808 	buf->Name[1] = 0xAD;
809 	buf->Name[2] = 0x25;
810 	buf->Name[3] = 0x50;
811 	buf->Name[4] = 0x9C;
812 	buf->Name[5] = 0xB4;
813 	buf->Name[6] = 0x11;
814 	buf->Name[7] = 0xE7;
815 	buf->Name[8] = 0xB4;
816 	buf->Name[9] = 0x23;
817 	buf->Name[10] = 0x83;
818 	buf->Name[11] = 0xDE;
819 	buf->Name[12] = 0x96;
820 	buf->Name[13] = 0x8B;
821 	buf->Name[14] = 0xCD;
822 	buf->Name[15] = 0x7C;
823 	buf->Mode = cpu_to_le32(mode);
824 	cifs_dbg(FYI, "mode on posix create 0%o\n", mode);
825 	return buf;
826 }
827 
828 static int
add_posix_context(struct kvec * iov,unsigned int * num_iovec,umode_t mode)829 add_posix_context(struct kvec *iov, unsigned int *num_iovec, umode_t mode)
830 {
831 	struct smb2_create_req *req = iov[0].iov_base;
832 	unsigned int num = *num_iovec;
833 
834 	iov[num].iov_base = create_posix_buf(mode);
835 	if (mode == ACL_NO_MODE)
836 		cifs_dbg(FYI, "Invalid mode\n");
837 	if (iov[num].iov_base == NULL)
838 		return -ENOMEM;
839 	iov[num].iov_len = sizeof(struct create_posix);
840 	if (!req->CreateContextsOffset)
841 		req->CreateContextsOffset = cpu_to_le32(
842 				sizeof(struct smb2_create_req) +
843 				iov[num - 1].iov_len);
844 	le32_add_cpu(&req->CreateContextsLength, sizeof(struct create_posix));
845 	*num_iovec = num + 1;
846 	return 0;
847 }
848 
849 
850 /*
851  *
852  *	SMB2 Worker functions follow:
853  *
854  *	The general structure of the worker functions is:
855  *	1) Call smb2_init (assembles SMB2 header)
856  *	2) Initialize SMB2 command specific fields in fixed length area of SMB
857  *	3) Call smb_sendrcv2 (sends request on socket and waits for response)
858  *	4) Decode SMB2 command specific fields in the fixed length area
859  *	5) Decode variable length data area (if any for this SMB2 command type)
860  *	6) Call free smb buffer
861  *	7) return
862  *
863  */
864 
865 int
SMB2_negotiate(const unsigned int xid,struct cifs_ses * ses,struct TCP_Server_Info * server)866 SMB2_negotiate(const unsigned int xid,
867 	       struct cifs_ses *ses,
868 	       struct TCP_Server_Info *server)
869 {
870 	struct smb_rqst rqst;
871 	struct smb2_negotiate_req *req;
872 	struct smb2_negotiate_rsp *rsp;
873 	struct kvec iov[1];
874 	struct kvec rsp_iov;
875 	int rc = 0;
876 	int resp_buftype;
877 	int blob_offset, blob_length;
878 	char *security_blob;
879 	int flags = CIFS_NEG_OP;
880 	unsigned int total_len;
881 
882 	cifs_dbg(FYI, "Negotiate protocol\n");
883 
884 	if (!server) {
885 		WARN(1, "%s: server is NULL!\n", __func__);
886 		return -EIO;
887 	}
888 
889 	rc = smb2_plain_req_init(SMB2_NEGOTIATE, NULL, server,
890 				 (void **) &req, &total_len);
891 	if (rc)
892 		return rc;
893 
894 	req->hdr.SessionId = 0;
895 
896 	memset(server->preauth_sha_hash, 0, SMB2_PREAUTH_HASH_SIZE);
897 	memset(ses->preauth_sha_hash, 0, SMB2_PREAUTH_HASH_SIZE);
898 
899 	if (strcmp(server->vals->version_string,
900 		   SMB3ANY_VERSION_STRING) == 0) {
901 		req->Dialects[0] = cpu_to_le16(SMB30_PROT_ID);
902 		req->Dialects[1] = cpu_to_le16(SMB302_PROT_ID);
903 		req->Dialects[2] = cpu_to_le16(SMB311_PROT_ID);
904 		req->DialectCount = cpu_to_le16(3);
905 		total_len += 6;
906 	} else if (strcmp(server->vals->version_string,
907 		   SMBDEFAULT_VERSION_STRING) == 0) {
908 		req->Dialects[0] = cpu_to_le16(SMB21_PROT_ID);
909 		req->Dialects[1] = cpu_to_le16(SMB30_PROT_ID);
910 		req->Dialects[2] = cpu_to_le16(SMB302_PROT_ID);
911 		req->Dialects[3] = cpu_to_le16(SMB311_PROT_ID);
912 		req->DialectCount = cpu_to_le16(4);
913 		total_len += 8;
914 	} else {
915 		/* otherwise send specific dialect */
916 		req->Dialects[0] = cpu_to_le16(server->vals->protocol_id);
917 		req->DialectCount = cpu_to_le16(1);
918 		total_len += 2;
919 	}
920 
921 	/* only one of SMB2 signing flags may be set in SMB2 request */
922 	if (ses->sign)
923 		req->SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_REQUIRED);
924 	else if (global_secflags & CIFSSEC_MAY_SIGN)
925 		req->SecurityMode = cpu_to_le16(SMB2_NEGOTIATE_SIGNING_ENABLED);
926 	else
927 		req->SecurityMode = 0;
928 
929 	req->Capabilities = cpu_to_le32(server->vals->req_capabilities);
930 	if (ses->chan_max > 1)
931 		req->Capabilities |= cpu_to_le32(SMB2_GLOBAL_CAP_MULTI_CHANNEL);
932 
933 	/* ClientGUID must be zero for SMB2.02 dialect */
934 	if (server->vals->protocol_id == SMB20_PROT_ID)
935 		memset(req->ClientGUID, 0, SMB2_CLIENT_GUID_SIZE);
936 	else {
937 		memcpy(req->ClientGUID, server->client_guid,
938 			SMB2_CLIENT_GUID_SIZE);
939 		if ((server->vals->protocol_id == SMB311_PROT_ID) ||
940 		    (strcmp(server->vals->version_string,
941 		     SMB3ANY_VERSION_STRING) == 0) ||
942 		    (strcmp(server->vals->version_string,
943 		     SMBDEFAULT_VERSION_STRING) == 0))
944 			assemble_neg_contexts(req, server, &total_len);
945 	}
946 	iov[0].iov_base = (char *)req;
947 	iov[0].iov_len = total_len;
948 
949 	memset(&rqst, 0, sizeof(struct smb_rqst));
950 	rqst.rq_iov = iov;
951 	rqst.rq_nvec = 1;
952 
953 	rc = cifs_send_recv(xid, ses, server,
954 			    &rqst, &resp_buftype, flags, &rsp_iov);
955 	cifs_small_buf_release(req);
956 	rsp = (struct smb2_negotiate_rsp *)rsp_iov.iov_base;
957 	/*
958 	 * No tcon so can't do
959 	 * cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_fail[SMB2...]);
960 	 */
961 	if (rc == -EOPNOTSUPP) {
962 		cifs_server_dbg(VFS, "Dialect not supported by server. Consider  specifying vers=1.0 or vers=2.0 on mount for accessing older servers\n");
963 		goto neg_exit;
964 	} else if (rc != 0)
965 		goto neg_exit;
966 
967 	rc = -EIO;
968 	if (strcmp(server->vals->version_string,
969 		   SMB3ANY_VERSION_STRING) == 0) {
970 		if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID)) {
971 			cifs_server_dbg(VFS,
972 				"SMB2 dialect returned but not requested\n");
973 			goto neg_exit;
974 		} else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID)) {
975 			cifs_server_dbg(VFS,
976 				"SMB2.1 dialect returned but not requested\n");
977 			goto neg_exit;
978 		} else if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID)) {
979 			/* ops set to 3.0 by default for default so update */
980 			server->ops = &smb311_operations;
981 			server->vals = &smb311_values;
982 		}
983 	} else if (strcmp(server->vals->version_string,
984 		   SMBDEFAULT_VERSION_STRING) == 0) {
985 		if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID)) {
986 			cifs_server_dbg(VFS,
987 				"SMB2 dialect returned but not requested\n");
988 			goto neg_exit;
989 		} else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID)) {
990 			/* ops set to 3.0 by default for default so update */
991 			server->ops = &smb21_operations;
992 			server->vals = &smb21_values;
993 		} else if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID)) {
994 			server->ops = &smb311_operations;
995 			server->vals = &smb311_values;
996 		}
997 	} else if (le16_to_cpu(rsp->DialectRevision) !=
998 				server->vals->protocol_id) {
999 		/* if requested single dialect ensure returned dialect matched */
1000 		cifs_server_dbg(VFS, "Invalid 0x%x dialect returned: not requested\n",
1001 				le16_to_cpu(rsp->DialectRevision));
1002 		goto neg_exit;
1003 	}
1004 
1005 	cifs_dbg(FYI, "mode 0x%x\n", rsp->SecurityMode);
1006 
1007 	if (rsp->DialectRevision == cpu_to_le16(SMB20_PROT_ID))
1008 		cifs_dbg(FYI, "negotiated smb2.0 dialect\n");
1009 	else if (rsp->DialectRevision == cpu_to_le16(SMB21_PROT_ID))
1010 		cifs_dbg(FYI, "negotiated smb2.1 dialect\n");
1011 	else if (rsp->DialectRevision == cpu_to_le16(SMB30_PROT_ID))
1012 		cifs_dbg(FYI, "negotiated smb3.0 dialect\n");
1013 	else if (rsp->DialectRevision == cpu_to_le16(SMB302_PROT_ID))
1014 		cifs_dbg(FYI, "negotiated smb3.02 dialect\n");
1015 	else if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID))
1016 		cifs_dbg(FYI, "negotiated smb3.1.1 dialect\n");
1017 	else {
1018 		cifs_server_dbg(VFS, "Invalid dialect returned by server 0x%x\n",
1019 				le16_to_cpu(rsp->DialectRevision));
1020 		goto neg_exit;
1021 	}
1022 
1023 	rc = 0;
1024 	server->dialect = le16_to_cpu(rsp->DialectRevision);
1025 
1026 	/*
1027 	 * Keep a copy of the hash after negprot. This hash will be
1028 	 * the starting hash value for all sessions made from this
1029 	 * server.
1030 	 */
1031 	memcpy(server->preauth_sha_hash, ses->preauth_sha_hash,
1032 	       SMB2_PREAUTH_HASH_SIZE);
1033 
1034 	/* SMB2 only has an extended negflavor */
1035 	server->negflavor = CIFS_NEGFLAVOR_EXTENDED;
1036 	/* set it to the maximum buffer size value we can send with 1 credit */
1037 	server->maxBuf = min_t(unsigned int, le32_to_cpu(rsp->MaxTransactSize),
1038 			       SMB2_MAX_BUFFER_SIZE);
1039 	server->max_read = le32_to_cpu(rsp->MaxReadSize);
1040 	server->max_write = le32_to_cpu(rsp->MaxWriteSize);
1041 	server->sec_mode = le16_to_cpu(rsp->SecurityMode);
1042 	if ((server->sec_mode & SMB2_SEC_MODE_FLAGS_ALL) != server->sec_mode)
1043 		cifs_dbg(FYI, "Server returned unexpected security mode 0x%x\n",
1044 				server->sec_mode);
1045 	server->capabilities = le32_to_cpu(rsp->Capabilities);
1046 	/* Internal types */
1047 	server->capabilities |= SMB2_NT_FIND | SMB2_LARGE_FILES;
1048 
1049 	/*
1050 	 * SMB3.0 supports only 1 cipher and doesn't have a encryption neg context
1051 	 * Set the cipher type manually.
1052 	 */
1053 	if (server->dialect == SMB30_PROT_ID && (server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION))
1054 		server->cipher_type = SMB2_ENCRYPTION_AES128_CCM;
1055 
1056 	security_blob = smb2_get_data_area_len(&blob_offset, &blob_length,
1057 					       (struct smb2_hdr *)rsp);
1058 	/*
1059 	 * See MS-SMB2 section 2.2.4: if no blob, client picks default which
1060 	 * for us will be
1061 	 *	ses->sectype = RawNTLMSSP;
1062 	 * but for time being this is our only auth choice so doesn't matter.
1063 	 * We just found a server which sets blob length to zero expecting raw.
1064 	 */
1065 	if (blob_length == 0) {
1066 		cifs_dbg(FYI, "missing security blob on negprot\n");
1067 		server->sec_ntlmssp = true;
1068 	}
1069 
1070 	rc = cifs_enable_signing(server, ses->sign);
1071 	if (rc)
1072 		goto neg_exit;
1073 	if (blob_length) {
1074 		rc = decode_negTokenInit(security_blob, blob_length, server);
1075 		if (rc == 1)
1076 			rc = 0;
1077 		else if (rc == 0)
1078 			rc = -EIO;
1079 	}
1080 
1081 	if (rsp->DialectRevision == cpu_to_le16(SMB311_PROT_ID)) {
1082 		if (rsp->NegotiateContextCount)
1083 			rc = smb311_decode_neg_context(rsp, server,
1084 						       rsp_iov.iov_len);
1085 		else
1086 			cifs_server_dbg(VFS, "Missing expected negotiate contexts\n");
1087 	}
1088 neg_exit:
1089 	free_rsp_buf(resp_buftype, rsp);
1090 	return rc;
1091 }
1092 
smb3_validate_negotiate(const unsigned int xid,struct cifs_tcon * tcon)1093 int smb3_validate_negotiate(const unsigned int xid, struct cifs_tcon *tcon)
1094 {
1095 	int rc;
1096 	struct validate_negotiate_info_req *pneg_inbuf;
1097 	struct validate_negotiate_info_rsp *pneg_rsp = NULL;
1098 	u32 rsplen;
1099 	u32 inbuflen; /* max of 4 dialects */
1100 	struct TCP_Server_Info *server = tcon->ses->server;
1101 
1102 	cifs_dbg(FYI, "validate negotiate\n");
1103 
1104 	/* In SMB3.11 preauth integrity supersedes validate negotiate */
1105 	if (server->dialect == SMB311_PROT_ID)
1106 		return 0;
1107 
1108 	/*
1109 	 * validation ioctl must be signed, so no point sending this if we
1110 	 * can not sign it (ie are not known user).  Even if signing is not
1111 	 * required (enabled but not negotiated), in those cases we selectively
1112 	 * sign just this, the first and only signed request on a connection.
1113 	 * Having validation of negotiate info  helps reduce attack vectors.
1114 	 */
1115 	if (tcon->ses->session_flags & SMB2_SESSION_FLAG_IS_GUEST)
1116 		return 0; /* validation requires signing */
1117 
1118 	if (tcon->ses->user_name == NULL) {
1119 		cifs_dbg(FYI, "Can't validate negotiate: null user mount\n");
1120 		return 0; /* validation requires signing */
1121 	}
1122 
1123 	if (tcon->ses->session_flags & SMB2_SESSION_FLAG_IS_NULL)
1124 		cifs_tcon_dbg(VFS, "Unexpected null user (anonymous) auth flag sent by server\n");
1125 
1126 	pneg_inbuf = kmalloc(sizeof(*pneg_inbuf), GFP_NOFS);
1127 	if (!pneg_inbuf)
1128 		return -ENOMEM;
1129 
1130 	pneg_inbuf->Capabilities =
1131 			cpu_to_le32(server->vals->req_capabilities);
1132 	if (tcon->ses->chan_max > 1)
1133 		pneg_inbuf->Capabilities |= cpu_to_le32(SMB2_GLOBAL_CAP_MULTI_CHANNEL);
1134 
1135 	memcpy(pneg_inbuf->Guid, server->client_guid,
1136 					SMB2_CLIENT_GUID_SIZE);
1137 
1138 	if (tcon->ses->sign)
1139 		pneg_inbuf->SecurityMode =
1140 			cpu_to_le16(SMB2_NEGOTIATE_SIGNING_REQUIRED);
1141 	else if (global_secflags & CIFSSEC_MAY_SIGN)
1142 		pneg_inbuf->SecurityMode =
1143 			cpu_to_le16(SMB2_NEGOTIATE_SIGNING_ENABLED);
1144 	else
1145 		pneg_inbuf->SecurityMode = 0;
1146 
1147 
1148 	if (strcmp(server->vals->version_string,
1149 		SMB3ANY_VERSION_STRING) == 0) {
1150 		pneg_inbuf->Dialects[0] = cpu_to_le16(SMB30_PROT_ID);
1151 		pneg_inbuf->Dialects[1] = cpu_to_le16(SMB302_PROT_ID);
1152 		pneg_inbuf->Dialects[2] = cpu_to_le16(SMB311_PROT_ID);
1153 		pneg_inbuf->DialectCount = cpu_to_le16(3);
1154 		/* SMB 2.1 not included so subtract one dialect from len */
1155 		inbuflen = sizeof(*pneg_inbuf) -
1156 				(sizeof(pneg_inbuf->Dialects[0]));
1157 	} else if (strcmp(server->vals->version_string,
1158 		SMBDEFAULT_VERSION_STRING) == 0) {
1159 		pneg_inbuf->Dialects[0] = cpu_to_le16(SMB21_PROT_ID);
1160 		pneg_inbuf->Dialects[1] = cpu_to_le16(SMB30_PROT_ID);
1161 		pneg_inbuf->Dialects[2] = cpu_to_le16(SMB302_PROT_ID);
1162 		pneg_inbuf->Dialects[3] = cpu_to_le16(SMB311_PROT_ID);
1163 		pneg_inbuf->DialectCount = cpu_to_le16(4);
1164 		/* structure is big enough for 4 dialects */
1165 		inbuflen = sizeof(*pneg_inbuf);
1166 	} else {
1167 		/* otherwise specific dialect was requested */
1168 		pneg_inbuf->Dialects[0] =
1169 			cpu_to_le16(server->vals->protocol_id);
1170 		pneg_inbuf->DialectCount = cpu_to_le16(1);
1171 		/* structure is big enough for 3 dialects, sending only 1 */
1172 		inbuflen = sizeof(*pneg_inbuf) -
1173 				sizeof(pneg_inbuf->Dialects[0]) * 2;
1174 	}
1175 
1176 	rc = SMB2_ioctl(xid, tcon, NO_FILE_ID, NO_FILE_ID,
1177 		FSCTL_VALIDATE_NEGOTIATE_INFO,
1178 		(char *)pneg_inbuf, inbuflen, CIFSMaxBufSize,
1179 		(char **)&pneg_rsp, &rsplen);
1180 	if (rc == -EOPNOTSUPP) {
1181 		/*
1182 		 * Old Windows versions or Netapp SMB server can return
1183 		 * not supported error. Client should accept it.
1184 		 */
1185 		cifs_tcon_dbg(VFS, "Server does not support validate negotiate\n");
1186 		rc = 0;
1187 		goto out_free_inbuf;
1188 	} else if (rc != 0) {
1189 		cifs_tcon_dbg(VFS, "validate protocol negotiate failed: %d\n",
1190 			      rc);
1191 		rc = -EIO;
1192 		goto out_free_inbuf;
1193 	}
1194 
1195 	rc = -EIO;
1196 	if (rsplen != sizeof(*pneg_rsp)) {
1197 		cifs_tcon_dbg(VFS, "Invalid protocol negotiate response size: %d\n",
1198 			      rsplen);
1199 
1200 		/* relax check since Mac returns max bufsize allowed on ioctl */
1201 		if (rsplen > CIFSMaxBufSize || rsplen < sizeof(*pneg_rsp))
1202 			goto out_free_rsp;
1203 	}
1204 
1205 	/* check validate negotiate info response matches what we got earlier */
1206 	if (pneg_rsp->Dialect != cpu_to_le16(server->dialect))
1207 		goto vneg_out;
1208 
1209 	if (pneg_rsp->SecurityMode != cpu_to_le16(server->sec_mode))
1210 		goto vneg_out;
1211 
1212 	/* do not validate server guid because not saved at negprot time yet */
1213 
1214 	if ((le32_to_cpu(pneg_rsp->Capabilities) | SMB2_NT_FIND |
1215 	      SMB2_LARGE_FILES) != server->capabilities)
1216 		goto vneg_out;
1217 
1218 	/* validate negotiate successful */
1219 	rc = 0;
1220 	cifs_dbg(FYI, "validate negotiate info successful\n");
1221 	goto out_free_rsp;
1222 
1223 vneg_out:
1224 	cifs_tcon_dbg(VFS, "protocol revalidation - security settings mismatch\n");
1225 out_free_rsp:
1226 	kfree(pneg_rsp);
1227 out_free_inbuf:
1228 	kfree(pneg_inbuf);
1229 	return rc;
1230 }
1231 
1232 enum securityEnum
smb2_select_sectype(struct TCP_Server_Info * server,enum securityEnum requested)1233 smb2_select_sectype(struct TCP_Server_Info *server, enum securityEnum requested)
1234 {
1235 	switch (requested) {
1236 	case Kerberos:
1237 	case RawNTLMSSP:
1238 		return requested;
1239 	case NTLMv2:
1240 		return RawNTLMSSP;
1241 	case Unspecified:
1242 		if (server->sec_ntlmssp &&
1243 			(global_secflags & CIFSSEC_MAY_NTLMSSP))
1244 			return RawNTLMSSP;
1245 		if ((server->sec_kerberos || server->sec_mskerberos) &&
1246 			(global_secflags & CIFSSEC_MAY_KRB5))
1247 			return Kerberos;
1248 		fallthrough;
1249 	default:
1250 		return Unspecified;
1251 	}
1252 }
1253 
1254 struct SMB2_sess_data {
1255 	unsigned int xid;
1256 	struct cifs_ses *ses;
1257 	struct TCP_Server_Info *server;
1258 	struct nls_table *nls_cp;
1259 	void (*func)(struct SMB2_sess_data *);
1260 	int result;
1261 	u64 previous_session;
1262 
1263 	/* we will send the SMB in three pieces:
1264 	 * a fixed length beginning part, an optional
1265 	 * SPNEGO blob (which can be zero length), and a
1266 	 * last part which will include the strings
1267 	 * and rest of bcc area. This allows us to avoid
1268 	 * a large buffer 17K allocation
1269 	 */
1270 	int buf0_type;
1271 	struct kvec iov[2];
1272 };
1273 
1274 static int
SMB2_sess_alloc_buffer(struct SMB2_sess_data * sess_data)1275 SMB2_sess_alloc_buffer(struct SMB2_sess_data *sess_data)
1276 {
1277 	int rc;
1278 	struct cifs_ses *ses = sess_data->ses;
1279 	struct TCP_Server_Info *server = sess_data->server;
1280 	struct smb2_sess_setup_req *req;
1281 	unsigned int total_len;
1282 	bool is_binding = false;
1283 
1284 	rc = smb2_plain_req_init(SMB2_SESSION_SETUP, NULL, server,
1285 				 (void **) &req,
1286 				 &total_len);
1287 	if (rc)
1288 		return rc;
1289 
1290 	spin_lock(&ses->chan_lock);
1291 	is_binding = !CIFS_ALL_CHANS_NEED_RECONNECT(ses);
1292 	spin_unlock(&ses->chan_lock);
1293 
1294 	if (is_binding) {
1295 		req->hdr.SessionId = cpu_to_le64(ses->Suid);
1296 		req->hdr.Flags |= SMB2_FLAGS_SIGNED;
1297 		req->PreviousSessionId = 0;
1298 		req->Flags = SMB2_SESSION_REQ_FLAG_BINDING;
1299 		cifs_dbg(FYI, "Binding to sess id: %llx\n", ses->Suid);
1300 	} else {
1301 		/* First session, not a reauthenticate */
1302 		req->hdr.SessionId = 0;
1303 		/*
1304 		 * if reconnect, we need to send previous sess id
1305 		 * otherwise it is 0
1306 		 */
1307 		req->PreviousSessionId = cpu_to_le64(sess_data->previous_session);
1308 		req->Flags = 0; /* MBZ */
1309 		cifs_dbg(FYI, "Fresh session. Previous: %llx\n",
1310 			 sess_data->previous_session);
1311 	}
1312 
1313 	/* enough to enable echos and oplocks and one max size write */
1314 	req->hdr.CreditRequest = cpu_to_le16(130);
1315 
1316 	/* only one of SMB2 signing flags may be set in SMB2 request */
1317 	if (server->sign)
1318 		req->SecurityMode = SMB2_NEGOTIATE_SIGNING_REQUIRED;
1319 	else if (global_secflags & CIFSSEC_MAY_SIGN) /* one flag unlike MUST_ */
1320 		req->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED;
1321 	else
1322 		req->SecurityMode = 0;
1323 
1324 #ifdef CONFIG_CIFS_DFS_UPCALL
1325 	req->Capabilities = cpu_to_le32(SMB2_GLOBAL_CAP_DFS);
1326 #else
1327 	req->Capabilities = 0;
1328 #endif /* DFS_UPCALL */
1329 
1330 	req->Channel = 0; /* MBZ */
1331 
1332 	sess_data->iov[0].iov_base = (char *)req;
1333 	/* 1 for pad */
1334 	sess_data->iov[0].iov_len = total_len - 1;
1335 	/*
1336 	 * This variable will be used to clear the buffer
1337 	 * allocated above in case of any error in the calling function.
1338 	 */
1339 	sess_data->buf0_type = CIFS_SMALL_BUFFER;
1340 
1341 	return 0;
1342 }
1343 
1344 static void
SMB2_sess_free_buffer(struct SMB2_sess_data * sess_data)1345 SMB2_sess_free_buffer(struct SMB2_sess_data *sess_data)
1346 {
1347 	free_rsp_buf(sess_data->buf0_type, sess_data->iov[0].iov_base);
1348 	sess_data->buf0_type = CIFS_NO_BUFFER;
1349 }
1350 
1351 static int
SMB2_sess_sendreceive(struct SMB2_sess_data * sess_data)1352 SMB2_sess_sendreceive(struct SMB2_sess_data *sess_data)
1353 {
1354 	int rc;
1355 	struct smb_rqst rqst;
1356 	struct smb2_sess_setup_req *req = sess_data->iov[0].iov_base;
1357 	struct kvec rsp_iov = { NULL, 0 };
1358 
1359 	/* Testing shows that buffer offset must be at location of Buffer[0] */
1360 	req->SecurityBufferOffset =
1361 		cpu_to_le16(sizeof(struct smb2_sess_setup_req) - 1 /* pad */);
1362 	req->SecurityBufferLength = cpu_to_le16(sess_data->iov[1].iov_len);
1363 
1364 	memset(&rqst, 0, sizeof(struct smb_rqst));
1365 	rqst.rq_iov = sess_data->iov;
1366 	rqst.rq_nvec = 2;
1367 
1368 	/* BB add code to build os and lm fields */
1369 	rc = cifs_send_recv(sess_data->xid, sess_data->ses,
1370 			    sess_data->server,
1371 			    &rqst,
1372 			    &sess_data->buf0_type,
1373 			    CIFS_LOG_ERROR | CIFS_SESS_OP, &rsp_iov);
1374 	cifs_small_buf_release(sess_data->iov[0].iov_base);
1375 	memcpy(&sess_data->iov[0], &rsp_iov, sizeof(struct kvec));
1376 
1377 	return rc;
1378 }
1379 
1380 static int
SMB2_sess_establish_session(struct SMB2_sess_data * sess_data)1381 SMB2_sess_establish_session(struct SMB2_sess_data *sess_data)
1382 {
1383 	int rc = 0;
1384 	struct cifs_ses *ses = sess_data->ses;
1385 	struct TCP_Server_Info *server = sess_data->server;
1386 
1387 	cifs_server_lock(server);
1388 	if (server->ops->generate_signingkey) {
1389 		rc = server->ops->generate_signingkey(ses, server);
1390 		if (rc) {
1391 			cifs_dbg(FYI,
1392 				"SMB3 session key generation failed\n");
1393 			cifs_server_unlock(server);
1394 			return rc;
1395 		}
1396 	}
1397 	if (!server->session_estab) {
1398 		server->sequence_number = 0x2;
1399 		server->session_estab = true;
1400 	}
1401 	cifs_server_unlock(server);
1402 
1403 	cifs_dbg(FYI, "SMB2/3 session established successfully\n");
1404 	return rc;
1405 }
1406 
1407 #ifdef CONFIG_CIFS_UPCALL
1408 static void
SMB2_auth_kerberos(struct SMB2_sess_data * sess_data)1409 SMB2_auth_kerberos(struct SMB2_sess_data *sess_data)
1410 {
1411 	int rc;
1412 	struct cifs_ses *ses = sess_data->ses;
1413 	struct TCP_Server_Info *server = sess_data->server;
1414 	struct cifs_spnego_msg *msg;
1415 	struct key *spnego_key = NULL;
1416 	struct smb2_sess_setup_rsp *rsp = NULL;
1417 	bool is_binding = false;
1418 
1419 	rc = SMB2_sess_alloc_buffer(sess_data);
1420 	if (rc)
1421 		goto out;
1422 
1423 	spnego_key = cifs_get_spnego_key(ses, server);
1424 	if (IS_ERR(spnego_key)) {
1425 		rc = PTR_ERR(spnego_key);
1426 		if (rc == -ENOKEY)
1427 			cifs_dbg(VFS, "Verify user has a krb5 ticket and keyutils is installed\n");
1428 		spnego_key = NULL;
1429 		goto out;
1430 	}
1431 
1432 	msg = spnego_key->payload.data[0];
1433 	/*
1434 	 * check version field to make sure that cifs.upcall is
1435 	 * sending us a response in an expected form
1436 	 */
1437 	if (msg->version != CIFS_SPNEGO_UPCALL_VERSION) {
1438 		cifs_dbg(VFS, "bad cifs.upcall version. Expected %d got %d\n",
1439 			 CIFS_SPNEGO_UPCALL_VERSION, msg->version);
1440 		rc = -EKEYREJECTED;
1441 		goto out_put_spnego_key;
1442 	}
1443 
1444 	spin_lock(&ses->chan_lock);
1445 	is_binding = !CIFS_ALL_CHANS_NEED_RECONNECT(ses);
1446 	spin_unlock(&ses->chan_lock);
1447 
1448 	/* keep session key if binding */
1449 	if (!is_binding) {
1450 		ses->auth_key.response = kmemdup(msg->data, msg->sesskey_len,
1451 						 GFP_KERNEL);
1452 		if (!ses->auth_key.response) {
1453 			cifs_dbg(VFS, "Kerberos can't allocate (%u bytes) memory\n",
1454 				 msg->sesskey_len);
1455 			rc = -ENOMEM;
1456 			goto out_put_spnego_key;
1457 		}
1458 		ses->auth_key.len = msg->sesskey_len;
1459 	}
1460 
1461 	sess_data->iov[1].iov_base = msg->data + msg->sesskey_len;
1462 	sess_data->iov[1].iov_len = msg->secblob_len;
1463 
1464 	rc = SMB2_sess_sendreceive(sess_data);
1465 	if (rc)
1466 		goto out_put_spnego_key;
1467 
1468 	rsp = (struct smb2_sess_setup_rsp *)sess_data->iov[0].iov_base;
1469 	/* keep session id and flags if binding */
1470 	if (!is_binding) {
1471 		ses->Suid = le64_to_cpu(rsp->hdr.SessionId);
1472 		ses->session_flags = le16_to_cpu(rsp->SessionFlags);
1473 	}
1474 
1475 	rc = SMB2_sess_establish_session(sess_data);
1476 out_put_spnego_key:
1477 	key_invalidate(spnego_key);
1478 	key_put(spnego_key);
1479 out:
1480 	sess_data->result = rc;
1481 	sess_data->func = NULL;
1482 	SMB2_sess_free_buffer(sess_data);
1483 }
1484 #else
1485 static void
SMB2_auth_kerberos(struct SMB2_sess_data * sess_data)1486 SMB2_auth_kerberos(struct SMB2_sess_data *sess_data)
1487 {
1488 	cifs_dbg(VFS, "Kerberos negotiated but upcall support disabled!\n");
1489 	sess_data->result = -EOPNOTSUPP;
1490 	sess_data->func = NULL;
1491 }
1492 #endif
1493 
1494 static void
1495 SMB2_sess_auth_rawntlmssp_authenticate(struct SMB2_sess_data *sess_data);
1496 
1497 static void
SMB2_sess_auth_rawntlmssp_negotiate(struct SMB2_sess_data * sess_data)1498 SMB2_sess_auth_rawntlmssp_negotiate(struct SMB2_sess_data *sess_data)
1499 {
1500 	int rc;
1501 	struct cifs_ses *ses = sess_data->ses;
1502 	struct TCP_Server_Info *server = sess_data->server;
1503 	struct smb2_sess_setup_rsp *rsp = NULL;
1504 	unsigned char *ntlmssp_blob = NULL;
1505 	bool use_spnego = false; /* else use raw ntlmssp */
1506 	u16 blob_length = 0;
1507 	bool is_binding = false;
1508 
1509 	/*
1510 	 * If memory allocation is successful, caller of this function
1511 	 * frees it.
1512 	 */
1513 	ses->ntlmssp = kmalloc(sizeof(struct ntlmssp_auth), GFP_KERNEL);
1514 	if (!ses->ntlmssp) {
1515 		rc = -ENOMEM;
1516 		goto out_err;
1517 	}
1518 	ses->ntlmssp->sesskey_per_smbsess = true;
1519 
1520 	rc = SMB2_sess_alloc_buffer(sess_data);
1521 	if (rc)
1522 		goto out_err;
1523 
1524 	rc = build_ntlmssp_smb3_negotiate_blob(&ntlmssp_blob,
1525 					  &blob_length, ses, server,
1526 					  sess_data->nls_cp);
1527 	if (rc)
1528 		goto out_err;
1529 
1530 	if (use_spnego) {
1531 		/* BB eventually need to add this */
1532 		cifs_dbg(VFS, "spnego not supported for SMB2 yet\n");
1533 		rc = -EOPNOTSUPP;
1534 		goto out;
1535 	}
1536 	sess_data->iov[1].iov_base = ntlmssp_blob;
1537 	sess_data->iov[1].iov_len = blob_length;
1538 
1539 	rc = SMB2_sess_sendreceive(sess_data);
1540 	rsp = (struct smb2_sess_setup_rsp *)sess_data->iov[0].iov_base;
1541 
1542 	/* If true, rc here is expected and not an error */
1543 	if (sess_data->buf0_type != CIFS_NO_BUFFER &&
1544 		rsp->hdr.Status == STATUS_MORE_PROCESSING_REQUIRED)
1545 		rc = 0;
1546 
1547 	if (rc)
1548 		goto out;
1549 
1550 	if (offsetof(struct smb2_sess_setup_rsp, Buffer) !=
1551 			le16_to_cpu(rsp->SecurityBufferOffset)) {
1552 		cifs_dbg(VFS, "Invalid security buffer offset %d\n",
1553 			le16_to_cpu(rsp->SecurityBufferOffset));
1554 		rc = -EIO;
1555 		goto out;
1556 	}
1557 	rc = decode_ntlmssp_challenge(rsp->Buffer,
1558 			le16_to_cpu(rsp->SecurityBufferLength), ses);
1559 	if (rc)
1560 		goto out;
1561 
1562 	cifs_dbg(FYI, "rawntlmssp session setup challenge phase\n");
1563 
1564 	spin_lock(&ses->chan_lock);
1565 	is_binding = !CIFS_ALL_CHANS_NEED_RECONNECT(ses);
1566 	spin_unlock(&ses->chan_lock);
1567 
1568 	/* keep existing ses id and flags if binding */
1569 	if (!is_binding) {
1570 		ses->Suid = le64_to_cpu(rsp->hdr.SessionId);
1571 		ses->session_flags = le16_to_cpu(rsp->SessionFlags);
1572 	}
1573 
1574 out:
1575 	kfree(ntlmssp_blob);
1576 	SMB2_sess_free_buffer(sess_data);
1577 	if (!rc) {
1578 		sess_data->result = 0;
1579 		sess_data->func = SMB2_sess_auth_rawntlmssp_authenticate;
1580 		return;
1581 	}
1582 out_err:
1583 	kfree(ses->ntlmssp);
1584 	ses->ntlmssp = NULL;
1585 	sess_data->result = rc;
1586 	sess_data->func = NULL;
1587 }
1588 
1589 static void
SMB2_sess_auth_rawntlmssp_authenticate(struct SMB2_sess_data * sess_data)1590 SMB2_sess_auth_rawntlmssp_authenticate(struct SMB2_sess_data *sess_data)
1591 {
1592 	int rc;
1593 	struct cifs_ses *ses = sess_data->ses;
1594 	struct TCP_Server_Info *server = sess_data->server;
1595 	struct smb2_sess_setup_req *req;
1596 	struct smb2_sess_setup_rsp *rsp = NULL;
1597 	unsigned char *ntlmssp_blob = NULL;
1598 	bool use_spnego = false; /* else use raw ntlmssp */
1599 	u16 blob_length = 0;
1600 	bool is_binding = false;
1601 
1602 	rc = SMB2_sess_alloc_buffer(sess_data);
1603 	if (rc)
1604 		goto out;
1605 
1606 	req = (struct smb2_sess_setup_req *) sess_data->iov[0].iov_base;
1607 	req->hdr.SessionId = cpu_to_le64(ses->Suid);
1608 
1609 	rc = build_ntlmssp_auth_blob(&ntlmssp_blob, &blob_length,
1610 				     ses, server,
1611 				     sess_data->nls_cp);
1612 	if (rc) {
1613 		cifs_dbg(FYI, "build_ntlmssp_auth_blob failed %d\n", rc);
1614 		goto out;
1615 	}
1616 
1617 	if (use_spnego) {
1618 		/* BB eventually need to add this */
1619 		cifs_dbg(VFS, "spnego not supported for SMB2 yet\n");
1620 		rc = -EOPNOTSUPP;
1621 		goto out;
1622 	}
1623 	sess_data->iov[1].iov_base = ntlmssp_blob;
1624 	sess_data->iov[1].iov_len = blob_length;
1625 
1626 	rc = SMB2_sess_sendreceive(sess_data);
1627 	if (rc)
1628 		goto out;
1629 
1630 	rsp = (struct smb2_sess_setup_rsp *)sess_data->iov[0].iov_base;
1631 
1632 	spin_lock(&ses->chan_lock);
1633 	is_binding = !CIFS_ALL_CHANS_NEED_RECONNECT(ses);
1634 	spin_unlock(&ses->chan_lock);
1635 
1636 	/* keep existing ses id and flags if binding */
1637 	if (!is_binding) {
1638 		ses->Suid = le64_to_cpu(rsp->hdr.SessionId);
1639 		ses->session_flags = le16_to_cpu(rsp->SessionFlags);
1640 	}
1641 
1642 	rc = SMB2_sess_establish_session(sess_data);
1643 #ifdef CONFIG_CIFS_DEBUG_DUMP_KEYS
1644 	if (ses->server->dialect < SMB30_PROT_ID) {
1645 		cifs_dbg(VFS, "%s: dumping generated SMB2 session keys\n", __func__);
1646 		/*
1647 		 * The session id is opaque in terms of endianness, so we can't
1648 		 * print it as a long long. we dump it as we got it on the wire
1649 		 */
1650 		cifs_dbg(VFS, "Session Id    %*ph\n", (int)sizeof(ses->Suid),
1651 			 &ses->Suid);
1652 		cifs_dbg(VFS, "Session Key   %*ph\n",
1653 			 SMB2_NTLMV2_SESSKEY_SIZE, ses->auth_key.response);
1654 		cifs_dbg(VFS, "Signing Key   %*ph\n",
1655 			 SMB3_SIGN_KEY_SIZE, ses->auth_key.response);
1656 	}
1657 #endif
1658 out:
1659 	kfree(ntlmssp_blob);
1660 	SMB2_sess_free_buffer(sess_data);
1661 	kfree(ses->ntlmssp);
1662 	ses->ntlmssp = NULL;
1663 	sess_data->result = rc;
1664 	sess_data->func = NULL;
1665 }
1666 
1667 static int
SMB2_select_sec(struct SMB2_sess_data * sess_data)1668 SMB2_select_sec(struct SMB2_sess_data *sess_data)
1669 {
1670 	int type;
1671 	struct cifs_ses *ses = sess_data->ses;
1672 	struct TCP_Server_Info *server = sess_data->server;
1673 
1674 	type = smb2_select_sectype(server, ses->sectype);
1675 	cifs_dbg(FYI, "sess setup type %d\n", type);
1676 	if (type == Unspecified) {
1677 		cifs_dbg(VFS, "Unable to select appropriate authentication method!\n");
1678 		return -EINVAL;
1679 	}
1680 
1681 	switch (type) {
1682 	case Kerberos:
1683 		sess_data->func = SMB2_auth_kerberos;
1684 		break;
1685 	case RawNTLMSSP:
1686 		sess_data->func = SMB2_sess_auth_rawntlmssp_negotiate;
1687 		break;
1688 	default:
1689 		cifs_dbg(VFS, "secType %d not supported!\n", type);
1690 		return -EOPNOTSUPP;
1691 	}
1692 
1693 	return 0;
1694 }
1695 
1696 int
SMB2_sess_setup(const unsigned int xid,struct cifs_ses * ses,struct TCP_Server_Info * server,const struct nls_table * nls_cp)1697 SMB2_sess_setup(const unsigned int xid, struct cifs_ses *ses,
1698 		struct TCP_Server_Info *server,
1699 		const struct nls_table *nls_cp)
1700 {
1701 	int rc = 0;
1702 	struct SMB2_sess_data *sess_data;
1703 
1704 	cifs_dbg(FYI, "Session Setup\n");
1705 
1706 	if (!server) {
1707 		WARN(1, "%s: server is NULL!\n", __func__);
1708 		return -EIO;
1709 	}
1710 
1711 	sess_data = kzalloc(sizeof(struct SMB2_sess_data), GFP_KERNEL);
1712 	if (!sess_data)
1713 		return -ENOMEM;
1714 
1715 	sess_data->xid = xid;
1716 	sess_data->ses = ses;
1717 	sess_data->server = server;
1718 	sess_data->buf0_type = CIFS_NO_BUFFER;
1719 	sess_data->nls_cp = (struct nls_table *) nls_cp;
1720 	sess_data->previous_session = ses->Suid;
1721 
1722 	rc = SMB2_select_sec(sess_data);
1723 	if (rc)
1724 		goto out;
1725 
1726 	/*
1727 	 * Initialize the session hash with the server one.
1728 	 */
1729 	memcpy(ses->preauth_sha_hash, server->preauth_sha_hash,
1730 	       SMB2_PREAUTH_HASH_SIZE);
1731 
1732 	while (sess_data->func)
1733 		sess_data->func(sess_data);
1734 
1735 	if ((ses->session_flags & SMB2_SESSION_FLAG_IS_GUEST) && (ses->sign))
1736 		cifs_server_dbg(VFS, "signing requested but authenticated as guest\n");
1737 	rc = sess_data->result;
1738 out:
1739 	kfree(sess_data);
1740 	return rc;
1741 }
1742 
1743 int
SMB2_logoff(const unsigned int xid,struct cifs_ses * ses)1744 SMB2_logoff(const unsigned int xid, struct cifs_ses *ses)
1745 {
1746 	struct smb_rqst rqst;
1747 	struct smb2_logoff_req *req; /* response is also trivial struct */
1748 	int rc = 0;
1749 	struct TCP_Server_Info *server;
1750 	int flags = 0;
1751 	unsigned int total_len;
1752 	struct kvec iov[1];
1753 	struct kvec rsp_iov;
1754 	int resp_buf_type;
1755 
1756 	cifs_dbg(FYI, "disconnect session %p\n", ses);
1757 
1758 	if (ses && (ses->server))
1759 		server = ses->server;
1760 	else
1761 		return -EIO;
1762 
1763 	/* no need to send SMB logoff if uid already closed due to reconnect */
1764 	spin_lock(&ses->chan_lock);
1765 	if (CIFS_ALL_CHANS_NEED_RECONNECT(ses)) {
1766 		spin_unlock(&ses->chan_lock);
1767 		goto smb2_session_already_dead;
1768 	}
1769 	spin_unlock(&ses->chan_lock);
1770 
1771 	rc = smb2_plain_req_init(SMB2_LOGOFF, NULL, ses->server,
1772 				 (void **) &req, &total_len);
1773 	if (rc)
1774 		return rc;
1775 
1776 	 /* since no tcon, smb2_init can not do this, so do here */
1777 	req->hdr.SessionId = cpu_to_le64(ses->Suid);
1778 
1779 	if (ses->session_flags & SMB2_SESSION_FLAG_ENCRYPT_DATA)
1780 		flags |= CIFS_TRANSFORM_REQ;
1781 	else if (server->sign)
1782 		req->hdr.Flags |= SMB2_FLAGS_SIGNED;
1783 
1784 	flags |= CIFS_NO_RSP_BUF;
1785 
1786 	iov[0].iov_base = (char *)req;
1787 	iov[0].iov_len = total_len;
1788 
1789 	memset(&rqst, 0, sizeof(struct smb_rqst));
1790 	rqst.rq_iov = iov;
1791 	rqst.rq_nvec = 1;
1792 
1793 	rc = cifs_send_recv(xid, ses, ses->server,
1794 			    &rqst, &resp_buf_type, flags, &rsp_iov);
1795 	cifs_small_buf_release(req);
1796 	/*
1797 	 * No tcon so can't do
1798 	 * cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_fail[SMB2...]);
1799 	 */
1800 
1801 smb2_session_already_dead:
1802 	return rc;
1803 }
1804 
cifs_stats_fail_inc(struct cifs_tcon * tcon,uint16_t code)1805 static inline void cifs_stats_fail_inc(struct cifs_tcon *tcon, uint16_t code)
1806 {
1807 	cifs_stats_inc(&tcon->stats.smb2_stats.smb2_com_failed[code]);
1808 }
1809 
1810 #define MAX_SHARENAME_LENGTH (255 /* server */ + 80 /* share */ + 1 /* NULL */)
1811 
1812 /* These are similar values to what Windows uses */
init_copy_chunk_defaults(struct cifs_tcon * tcon)1813 static inline void init_copy_chunk_defaults(struct cifs_tcon *tcon)
1814 {
1815 	tcon->max_chunks = 256;
1816 	tcon->max_bytes_chunk = 1048576;
1817 	tcon->max_bytes_copy = 16777216;
1818 }
1819 
1820 int
SMB2_tcon(const unsigned int xid,struct cifs_ses * ses,const char * tree,struct cifs_tcon * tcon,const struct nls_table * cp)1821 SMB2_tcon(const unsigned int xid, struct cifs_ses *ses, const char *tree,
1822 	  struct cifs_tcon *tcon, const struct nls_table *cp)
1823 {
1824 	struct smb_rqst rqst;
1825 	struct smb2_tree_connect_req *req;
1826 	struct smb2_tree_connect_rsp *rsp = NULL;
1827 	struct kvec iov[2];
1828 	struct kvec rsp_iov = { NULL, 0 };
1829 	int rc = 0;
1830 	int resp_buftype;
1831 	int unc_path_len;
1832 	__le16 *unc_path = NULL;
1833 	int flags = 0;
1834 	unsigned int total_len;
1835 	struct TCP_Server_Info *server;
1836 
1837 	/* always use master channel */
1838 	server = ses->server;
1839 
1840 	cifs_dbg(FYI, "TCON\n");
1841 
1842 	if (!server || !tree)
1843 		return -EIO;
1844 
1845 	unc_path = kmalloc(MAX_SHARENAME_LENGTH * 2, GFP_KERNEL);
1846 	if (unc_path == NULL)
1847 		return -ENOMEM;
1848 
1849 	unc_path_len = cifs_strtoUTF16(unc_path, tree, strlen(tree), cp) + 1;
1850 	unc_path_len *= 2;
1851 	if (unc_path_len < 2) {
1852 		kfree(unc_path);
1853 		return -EINVAL;
1854 	}
1855 
1856 	/* SMB2 TREE_CONNECT request must be called with TreeId == 0 */
1857 	tcon->tid = 0;
1858 	atomic_set(&tcon->num_remote_opens, 0);
1859 	rc = smb2_plain_req_init(SMB2_TREE_CONNECT, tcon, server,
1860 				 (void **) &req, &total_len);
1861 	if (rc) {
1862 		kfree(unc_path);
1863 		return rc;
1864 	}
1865 
1866 	if (smb3_encryption_required(tcon))
1867 		flags |= CIFS_TRANSFORM_REQ;
1868 
1869 	iov[0].iov_base = (char *)req;
1870 	/* 1 for pad */
1871 	iov[0].iov_len = total_len - 1;
1872 
1873 	/* Testing shows that buffer offset must be at location of Buffer[0] */
1874 	req->PathOffset = cpu_to_le16(sizeof(struct smb2_tree_connect_req)
1875 			- 1 /* pad */);
1876 	req->PathLength = cpu_to_le16(unc_path_len - 2);
1877 	iov[1].iov_base = unc_path;
1878 	iov[1].iov_len = unc_path_len;
1879 
1880 	/*
1881 	 * 3.11 tcon req must be signed if not encrypted. See MS-SMB2 3.2.4.1.1
1882 	 * unless it is guest or anonymous user. See MS-SMB2 3.2.5.3.1
1883 	 * (Samba servers don't always set the flag so also check if null user)
1884 	 */
1885 	if ((server->dialect == SMB311_PROT_ID) &&
1886 	    !smb3_encryption_required(tcon) &&
1887 	    !(ses->session_flags &
1888 		    (SMB2_SESSION_FLAG_IS_GUEST|SMB2_SESSION_FLAG_IS_NULL)) &&
1889 	    ((ses->user_name != NULL) || (ses->sectype == Kerberos)))
1890 		req->hdr.Flags |= SMB2_FLAGS_SIGNED;
1891 
1892 	memset(&rqst, 0, sizeof(struct smb_rqst));
1893 	rqst.rq_iov = iov;
1894 	rqst.rq_nvec = 2;
1895 
1896 	/* Need 64 for max size write so ask for more in case not there yet */
1897 	req->hdr.CreditRequest = cpu_to_le16(64);
1898 
1899 	rc = cifs_send_recv(xid, ses, server,
1900 			    &rqst, &resp_buftype, flags, &rsp_iov);
1901 	cifs_small_buf_release(req);
1902 	rsp = (struct smb2_tree_connect_rsp *)rsp_iov.iov_base;
1903 	trace_smb3_tcon(xid, tcon->tid, ses->Suid, tree, rc);
1904 	if ((rc != 0) || (rsp == NULL)) {
1905 		cifs_stats_fail_inc(tcon, SMB2_TREE_CONNECT_HE);
1906 		tcon->need_reconnect = true;
1907 		goto tcon_error_exit;
1908 	}
1909 
1910 	switch (rsp->ShareType) {
1911 	case SMB2_SHARE_TYPE_DISK:
1912 		cifs_dbg(FYI, "connection to disk share\n");
1913 		break;
1914 	case SMB2_SHARE_TYPE_PIPE:
1915 		tcon->pipe = true;
1916 		cifs_dbg(FYI, "connection to pipe share\n");
1917 		break;
1918 	case SMB2_SHARE_TYPE_PRINT:
1919 		tcon->print = true;
1920 		cifs_dbg(FYI, "connection to printer\n");
1921 		break;
1922 	default:
1923 		cifs_server_dbg(VFS, "unknown share type %d\n", rsp->ShareType);
1924 		rc = -EOPNOTSUPP;
1925 		goto tcon_error_exit;
1926 	}
1927 
1928 	tcon->share_flags = le32_to_cpu(rsp->ShareFlags);
1929 	tcon->capabilities = rsp->Capabilities; /* we keep caps little endian */
1930 	tcon->maximal_access = le32_to_cpu(rsp->MaximalAccess);
1931 	tcon->tid = le32_to_cpu(rsp->hdr.Id.SyncId.TreeId);
1932 	strlcpy(tcon->treeName, tree, sizeof(tcon->treeName));
1933 
1934 	if ((rsp->Capabilities & SMB2_SHARE_CAP_DFS) &&
1935 	    ((tcon->share_flags & SHI1005_FLAGS_DFS) == 0))
1936 		cifs_tcon_dbg(VFS, "DFS capability contradicts DFS flag\n");
1937 
1938 	if (tcon->seal &&
1939 	    !(server->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION))
1940 		cifs_tcon_dbg(VFS, "Encryption is requested but not supported\n");
1941 
1942 	init_copy_chunk_defaults(tcon);
1943 	if (server->ops->validate_negotiate)
1944 		rc = server->ops->validate_negotiate(xid, tcon);
1945 tcon_exit:
1946 
1947 	free_rsp_buf(resp_buftype, rsp);
1948 	kfree(unc_path);
1949 	return rc;
1950 
1951 tcon_error_exit:
1952 	if (rsp && rsp->hdr.Status == STATUS_BAD_NETWORK_NAME)
1953 		cifs_tcon_dbg(VFS, "BAD_NETWORK_NAME: %s\n", tree);
1954 	goto tcon_exit;
1955 }
1956 
1957 int
SMB2_tdis(const unsigned int xid,struct cifs_tcon * tcon)1958 SMB2_tdis(const unsigned int xid, struct cifs_tcon *tcon)
1959 {
1960 	struct smb_rqst rqst;
1961 	struct smb2_tree_disconnect_req *req; /* response is trivial */
1962 	int rc = 0;
1963 	struct cifs_ses *ses = tcon->ses;
1964 	int flags = 0;
1965 	unsigned int total_len;
1966 	struct kvec iov[1];
1967 	struct kvec rsp_iov;
1968 	int resp_buf_type;
1969 
1970 	cifs_dbg(FYI, "Tree Disconnect\n");
1971 
1972 	if (!ses || !(ses->server))
1973 		return -EIO;
1974 
1975 	spin_lock(&ses->chan_lock);
1976 	if ((tcon->need_reconnect) ||
1977 	    (CIFS_ALL_CHANS_NEED_RECONNECT(tcon->ses))) {
1978 		spin_unlock(&ses->chan_lock);
1979 		return 0;
1980 	}
1981 	spin_unlock(&ses->chan_lock);
1982 
1983 	close_cached_dir_lease(&tcon->crfid);
1984 
1985 	rc = smb2_plain_req_init(SMB2_TREE_DISCONNECT, tcon, ses->server,
1986 				 (void **) &req,
1987 				 &total_len);
1988 	if (rc)
1989 		return rc;
1990 
1991 	if (smb3_encryption_required(tcon))
1992 		flags |= CIFS_TRANSFORM_REQ;
1993 
1994 	flags |= CIFS_NO_RSP_BUF;
1995 
1996 	iov[0].iov_base = (char *)req;
1997 	iov[0].iov_len = total_len;
1998 
1999 	memset(&rqst, 0, sizeof(struct smb_rqst));
2000 	rqst.rq_iov = iov;
2001 	rqst.rq_nvec = 1;
2002 
2003 	rc = cifs_send_recv(xid, ses, ses->server,
2004 			    &rqst, &resp_buf_type, flags, &rsp_iov);
2005 	cifs_small_buf_release(req);
2006 	if (rc)
2007 		cifs_stats_fail_inc(tcon, SMB2_TREE_DISCONNECT_HE);
2008 
2009 	return rc;
2010 }
2011 
2012 
2013 static struct create_durable *
create_durable_buf(void)2014 create_durable_buf(void)
2015 {
2016 	struct create_durable *buf;
2017 
2018 	buf = kzalloc(sizeof(struct create_durable), GFP_KERNEL);
2019 	if (!buf)
2020 		return NULL;
2021 
2022 	buf->ccontext.DataOffset = cpu_to_le16(offsetof
2023 					(struct create_durable, Data));
2024 	buf->ccontext.DataLength = cpu_to_le32(16);
2025 	buf->ccontext.NameOffset = cpu_to_le16(offsetof
2026 				(struct create_durable, Name));
2027 	buf->ccontext.NameLength = cpu_to_le16(4);
2028 	/* SMB2_CREATE_DURABLE_HANDLE_REQUEST is "DHnQ" */
2029 	buf->Name[0] = 'D';
2030 	buf->Name[1] = 'H';
2031 	buf->Name[2] = 'n';
2032 	buf->Name[3] = 'Q';
2033 	return buf;
2034 }
2035 
2036 static struct create_durable *
create_reconnect_durable_buf(struct cifs_fid * fid)2037 create_reconnect_durable_buf(struct cifs_fid *fid)
2038 {
2039 	struct create_durable *buf;
2040 
2041 	buf = kzalloc(sizeof(struct create_durable), GFP_KERNEL);
2042 	if (!buf)
2043 		return NULL;
2044 
2045 	buf->ccontext.DataOffset = cpu_to_le16(offsetof
2046 					(struct create_durable, Data));
2047 	buf->ccontext.DataLength = cpu_to_le32(16);
2048 	buf->ccontext.NameOffset = cpu_to_le16(offsetof
2049 				(struct create_durable, Name));
2050 	buf->ccontext.NameLength = cpu_to_le16(4);
2051 	buf->Data.Fid.PersistentFileId = fid->persistent_fid;
2052 	buf->Data.Fid.VolatileFileId = fid->volatile_fid;
2053 	/* SMB2_CREATE_DURABLE_HANDLE_RECONNECT is "DHnC" */
2054 	buf->Name[0] = 'D';
2055 	buf->Name[1] = 'H';
2056 	buf->Name[2] = 'n';
2057 	buf->Name[3] = 'C';
2058 	return buf;
2059 }
2060 
2061 static void
parse_query_id_ctxt(struct create_context * cc,struct smb2_file_all_info * buf)2062 parse_query_id_ctxt(struct create_context *cc, struct smb2_file_all_info *buf)
2063 {
2064 	struct create_on_disk_id *pdisk_id = (struct create_on_disk_id *)cc;
2065 
2066 	cifs_dbg(FYI, "parse query id context 0x%llx 0x%llx\n",
2067 		pdisk_id->DiskFileId, pdisk_id->VolumeId);
2068 	buf->IndexNumber = pdisk_id->DiskFileId;
2069 }
2070 
2071 static void
parse_posix_ctxt(struct create_context * cc,struct smb2_file_all_info * info,struct create_posix_rsp * posix)2072 parse_posix_ctxt(struct create_context *cc, struct smb2_file_all_info *info,
2073 		 struct create_posix_rsp *posix)
2074 {
2075 	int sid_len;
2076 	u8 *beg = (u8 *)cc + le16_to_cpu(cc->DataOffset);
2077 	u8 *end = beg + le32_to_cpu(cc->DataLength);
2078 	u8 *sid;
2079 
2080 	memset(posix, 0, sizeof(*posix));
2081 
2082 	posix->nlink = le32_to_cpu(*(__le32 *)(beg + 0));
2083 	posix->reparse_tag = le32_to_cpu(*(__le32 *)(beg + 4));
2084 	posix->mode = le32_to_cpu(*(__le32 *)(beg + 8));
2085 
2086 	sid = beg + 12;
2087 	sid_len = posix_info_sid_size(sid, end);
2088 	if (sid_len < 0) {
2089 		cifs_dbg(VFS, "bad owner sid in posix create response\n");
2090 		return;
2091 	}
2092 	memcpy(&posix->owner, sid, sid_len);
2093 
2094 	sid = sid + sid_len;
2095 	sid_len = posix_info_sid_size(sid, end);
2096 	if (sid_len < 0) {
2097 		cifs_dbg(VFS, "bad group sid in posix create response\n");
2098 		return;
2099 	}
2100 	memcpy(&posix->group, sid, sid_len);
2101 
2102 	cifs_dbg(FYI, "nlink=%d mode=%o reparse_tag=%x\n",
2103 		 posix->nlink, posix->mode, posix->reparse_tag);
2104 }
2105 
2106 void
smb2_parse_contexts(struct TCP_Server_Info * server,struct smb2_create_rsp * rsp,unsigned int * epoch,char * lease_key,__u8 * oplock,struct smb2_file_all_info * buf,struct create_posix_rsp * posix)2107 smb2_parse_contexts(struct TCP_Server_Info *server,
2108 		    struct smb2_create_rsp *rsp,
2109 		    unsigned int *epoch, char *lease_key, __u8 *oplock,
2110 		    struct smb2_file_all_info *buf,
2111 		    struct create_posix_rsp *posix)
2112 {
2113 	char *data_offset;
2114 	struct create_context *cc;
2115 	unsigned int next;
2116 	unsigned int remaining;
2117 	char *name;
2118 	static const char smb3_create_tag_posix[] = {
2119 		0x93, 0xAD, 0x25, 0x50, 0x9C,
2120 		0xB4, 0x11, 0xE7, 0xB4, 0x23, 0x83,
2121 		0xDE, 0x96, 0x8B, 0xCD, 0x7C
2122 	};
2123 
2124 	*oplock = 0;
2125 	data_offset = (char *)rsp + le32_to_cpu(rsp->CreateContextsOffset);
2126 	remaining = le32_to_cpu(rsp->CreateContextsLength);
2127 	cc = (struct create_context *)data_offset;
2128 
2129 	/* Initialize inode number to 0 in case no valid data in qfid context */
2130 	if (buf)
2131 		buf->IndexNumber = 0;
2132 
2133 	while (remaining >= sizeof(struct create_context)) {
2134 		name = le16_to_cpu(cc->NameOffset) + (char *)cc;
2135 		if (le16_to_cpu(cc->NameLength) == 4 &&
2136 		    strncmp(name, SMB2_CREATE_REQUEST_LEASE, 4) == 0)
2137 			*oplock = server->ops->parse_lease_buf(cc, epoch,
2138 							   lease_key);
2139 		else if (buf && (le16_to_cpu(cc->NameLength) == 4) &&
2140 		    strncmp(name, SMB2_CREATE_QUERY_ON_DISK_ID, 4) == 0)
2141 			parse_query_id_ctxt(cc, buf);
2142 		else if ((le16_to_cpu(cc->NameLength) == 16)) {
2143 			if (posix &&
2144 			    memcmp(name, smb3_create_tag_posix, 16) == 0)
2145 				parse_posix_ctxt(cc, buf, posix);
2146 		}
2147 		/* else {
2148 			cifs_dbg(FYI, "Context not matched with len %d\n",
2149 				le16_to_cpu(cc->NameLength));
2150 			cifs_dump_mem("Cctxt name: ", name, 4);
2151 		} */
2152 
2153 		next = le32_to_cpu(cc->Next);
2154 		if (!next)
2155 			break;
2156 		remaining -= next;
2157 		cc = (struct create_context *)((char *)cc + next);
2158 	}
2159 
2160 	if (rsp->OplockLevel != SMB2_OPLOCK_LEVEL_LEASE)
2161 		*oplock = rsp->OplockLevel;
2162 
2163 	return;
2164 }
2165 
2166 static int
add_lease_context(struct TCP_Server_Info * server,struct kvec * iov,unsigned int * num_iovec,u8 * lease_key,__u8 * oplock)2167 add_lease_context(struct TCP_Server_Info *server, struct kvec *iov,
2168 		  unsigned int *num_iovec, u8 *lease_key, __u8 *oplock)
2169 {
2170 	struct smb2_create_req *req = iov[0].iov_base;
2171 	unsigned int num = *num_iovec;
2172 
2173 	iov[num].iov_base = server->ops->create_lease_buf(lease_key, *oplock);
2174 	if (iov[num].iov_base == NULL)
2175 		return -ENOMEM;
2176 	iov[num].iov_len = server->vals->create_lease_size;
2177 	req->RequestedOplockLevel = SMB2_OPLOCK_LEVEL_LEASE;
2178 	if (!req->CreateContextsOffset)
2179 		req->CreateContextsOffset = cpu_to_le32(
2180 				sizeof(struct smb2_create_req) +
2181 				iov[num - 1].iov_len);
2182 	le32_add_cpu(&req->CreateContextsLength,
2183 		     server->vals->create_lease_size);
2184 	*num_iovec = num + 1;
2185 	return 0;
2186 }
2187 
2188 static struct create_durable_v2 *
create_durable_v2_buf(struct cifs_open_parms * oparms)2189 create_durable_v2_buf(struct cifs_open_parms *oparms)
2190 {
2191 	struct cifs_fid *pfid = oparms->fid;
2192 	struct create_durable_v2 *buf;
2193 
2194 	buf = kzalloc(sizeof(struct create_durable_v2), GFP_KERNEL);
2195 	if (!buf)
2196 		return NULL;
2197 
2198 	buf->ccontext.DataOffset = cpu_to_le16(offsetof
2199 					(struct create_durable_v2, dcontext));
2200 	buf->ccontext.DataLength = cpu_to_le32(sizeof(struct durable_context_v2));
2201 	buf->ccontext.NameOffset = cpu_to_le16(offsetof
2202 				(struct create_durable_v2, Name));
2203 	buf->ccontext.NameLength = cpu_to_le16(4);
2204 
2205 	/*
2206 	 * NB: Handle timeout defaults to 0, which allows server to choose
2207 	 * (most servers default to 120 seconds) and most clients default to 0.
2208 	 * This can be overridden at mount ("handletimeout=") if the user wants
2209 	 * a different persistent (or resilient) handle timeout for all opens
2210 	 * opens on a particular SMB3 mount.
2211 	 */
2212 	buf->dcontext.Timeout = cpu_to_le32(oparms->tcon->handle_timeout);
2213 	buf->dcontext.Flags = cpu_to_le32(SMB2_DHANDLE_FLAG_PERSISTENT);
2214 	generate_random_uuid(buf->dcontext.CreateGuid);
2215 	memcpy(pfid->create_guid, buf->dcontext.CreateGuid, 16);
2216 
2217 	/* SMB2_CREATE_DURABLE_HANDLE_REQUEST is "DH2Q" */
2218 	buf->Name[0] = 'D';
2219 	buf->Name[1] = 'H';
2220 	buf->Name[2] = '2';
2221 	buf->Name[3] = 'Q';
2222 	return buf;
2223 }
2224 
2225 static struct create_durable_handle_reconnect_v2 *
create_reconnect_durable_v2_buf(struct cifs_fid * fid)2226 create_reconnect_durable_v2_buf(struct cifs_fid *fid)
2227 {
2228 	struct create_durable_handle_reconnect_v2 *buf;
2229 
2230 	buf = kzalloc(sizeof(struct create_durable_handle_reconnect_v2),
2231 			GFP_KERNEL);
2232 	if (!buf)
2233 		return NULL;
2234 
2235 	buf->ccontext.DataOffset =
2236 		cpu_to_le16(offsetof(struct create_durable_handle_reconnect_v2,
2237 				     dcontext));
2238 	buf->ccontext.DataLength =
2239 		cpu_to_le32(sizeof(struct durable_reconnect_context_v2));
2240 	buf->ccontext.NameOffset =
2241 		cpu_to_le16(offsetof(struct create_durable_handle_reconnect_v2,
2242 			    Name));
2243 	buf->ccontext.NameLength = cpu_to_le16(4);
2244 
2245 	buf->dcontext.Fid.PersistentFileId = fid->persistent_fid;
2246 	buf->dcontext.Fid.VolatileFileId = fid->volatile_fid;
2247 	buf->dcontext.Flags = cpu_to_le32(SMB2_DHANDLE_FLAG_PERSISTENT);
2248 	memcpy(buf->dcontext.CreateGuid, fid->create_guid, 16);
2249 
2250 	/* SMB2_CREATE_DURABLE_HANDLE_RECONNECT_V2 is "DH2C" */
2251 	buf->Name[0] = 'D';
2252 	buf->Name[1] = 'H';
2253 	buf->Name[2] = '2';
2254 	buf->Name[3] = 'C';
2255 	return buf;
2256 }
2257 
2258 static int
add_durable_v2_context(struct kvec * iov,unsigned int * num_iovec,struct cifs_open_parms * oparms)2259 add_durable_v2_context(struct kvec *iov, unsigned int *num_iovec,
2260 		    struct cifs_open_parms *oparms)
2261 {
2262 	struct smb2_create_req *req = iov[0].iov_base;
2263 	unsigned int num = *num_iovec;
2264 
2265 	iov[num].iov_base = create_durable_v2_buf(oparms);
2266 	if (iov[num].iov_base == NULL)
2267 		return -ENOMEM;
2268 	iov[num].iov_len = sizeof(struct create_durable_v2);
2269 	if (!req->CreateContextsOffset)
2270 		req->CreateContextsOffset =
2271 			cpu_to_le32(sizeof(struct smb2_create_req) +
2272 								iov[1].iov_len);
2273 	le32_add_cpu(&req->CreateContextsLength, sizeof(struct create_durable_v2));
2274 	*num_iovec = num + 1;
2275 	return 0;
2276 }
2277 
2278 static int
add_durable_reconnect_v2_context(struct kvec * iov,unsigned int * num_iovec,struct cifs_open_parms * oparms)2279 add_durable_reconnect_v2_context(struct kvec *iov, unsigned int *num_iovec,
2280 		    struct cifs_open_parms *oparms)
2281 {
2282 	struct smb2_create_req *req = iov[0].iov_base;
2283 	unsigned int num = *num_iovec;
2284 
2285 	/* indicate that we don't need to relock the file */
2286 	oparms->reconnect = false;
2287 
2288 	iov[num].iov_base = create_reconnect_durable_v2_buf(oparms->fid);
2289 	if (iov[num].iov_base == NULL)
2290 		return -ENOMEM;
2291 	iov[num].iov_len = sizeof(struct create_durable_handle_reconnect_v2);
2292 	if (!req->CreateContextsOffset)
2293 		req->CreateContextsOffset =
2294 			cpu_to_le32(sizeof(struct smb2_create_req) +
2295 								iov[1].iov_len);
2296 	le32_add_cpu(&req->CreateContextsLength,
2297 			sizeof(struct create_durable_handle_reconnect_v2));
2298 	*num_iovec = num + 1;
2299 	return 0;
2300 }
2301 
2302 static int
add_durable_context(struct kvec * iov,unsigned int * num_iovec,struct cifs_open_parms * oparms,bool use_persistent)2303 add_durable_context(struct kvec *iov, unsigned int *num_iovec,
2304 		    struct cifs_open_parms *oparms, bool use_persistent)
2305 {
2306 	struct smb2_create_req *req = iov[0].iov_base;
2307 	unsigned int num = *num_iovec;
2308 
2309 	if (use_persistent) {
2310 		if (oparms->reconnect)
2311 			return add_durable_reconnect_v2_context(iov, num_iovec,
2312 								oparms);
2313 		else
2314 			return add_durable_v2_context(iov, num_iovec, oparms);
2315 	}
2316 
2317 	if (oparms->reconnect) {
2318 		iov[num].iov_base = create_reconnect_durable_buf(oparms->fid);
2319 		/* indicate that we don't need to relock the file */
2320 		oparms->reconnect = false;
2321 	} else
2322 		iov[num].iov_base = create_durable_buf();
2323 	if (iov[num].iov_base == NULL)
2324 		return -ENOMEM;
2325 	iov[num].iov_len = sizeof(struct create_durable);
2326 	if (!req->CreateContextsOffset)
2327 		req->CreateContextsOffset =
2328 			cpu_to_le32(sizeof(struct smb2_create_req) +
2329 								iov[1].iov_len);
2330 	le32_add_cpu(&req->CreateContextsLength, sizeof(struct create_durable));
2331 	*num_iovec = num + 1;
2332 	return 0;
2333 }
2334 
2335 /* See MS-SMB2 2.2.13.2.7 */
2336 static struct crt_twarp_ctxt *
create_twarp_buf(__u64 timewarp)2337 create_twarp_buf(__u64 timewarp)
2338 {
2339 	struct crt_twarp_ctxt *buf;
2340 
2341 	buf = kzalloc(sizeof(struct crt_twarp_ctxt), GFP_KERNEL);
2342 	if (!buf)
2343 		return NULL;
2344 
2345 	buf->ccontext.DataOffset = cpu_to_le16(offsetof
2346 					(struct crt_twarp_ctxt, Timestamp));
2347 	buf->ccontext.DataLength = cpu_to_le32(8);
2348 	buf->ccontext.NameOffset = cpu_to_le16(offsetof
2349 				(struct crt_twarp_ctxt, Name));
2350 	buf->ccontext.NameLength = cpu_to_le16(4);
2351 	/* SMB2_CREATE_TIMEWARP_TOKEN is "TWrp" */
2352 	buf->Name[0] = 'T';
2353 	buf->Name[1] = 'W';
2354 	buf->Name[2] = 'r';
2355 	buf->Name[3] = 'p';
2356 	buf->Timestamp = cpu_to_le64(timewarp);
2357 	return buf;
2358 }
2359 
2360 /* See MS-SMB2 2.2.13.2.7 */
2361 static int
add_twarp_context(struct kvec * iov,unsigned int * num_iovec,__u64 timewarp)2362 add_twarp_context(struct kvec *iov, unsigned int *num_iovec, __u64 timewarp)
2363 {
2364 	struct smb2_create_req *req = iov[0].iov_base;
2365 	unsigned int num = *num_iovec;
2366 
2367 	iov[num].iov_base = create_twarp_buf(timewarp);
2368 	if (iov[num].iov_base == NULL)
2369 		return -ENOMEM;
2370 	iov[num].iov_len = sizeof(struct crt_twarp_ctxt);
2371 	if (!req->CreateContextsOffset)
2372 		req->CreateContextsOffset = cpu_to_le32(
2373 				sizeof(struct smb2_create_req) +
2374 				iov[num - 1].iov_len);
2375 	le32_add_cpu(&req->CreateContextsLength, sizeof(struct crt_twarp_ctxt));
2376 	*num_iovec = num + 1;
2377 	return 0;
2378 }
2379 
2380 /* See See http://technet.microsoft.com/en-us/library/hh509017(v=ws.10).aspx */
setup_owner_group_sids(char * buf)2381 static void setup_owner_group_sids(char *buf)
2382 {
2383 	struct owner_group_sids *sids = (struct owner_group_sids *)buf;
2384 
2385 	/* Populate the user ownership fields S-1-5-88-1 */
2386 	sids->owner.Revision = 1;
2387 	sids->owner.NumAuth = 3;
2388 	sids->owner.Authority[5] = 5;
2389 	sids->owner.SubAuthorities[0] = cpu_to_le32(88);
2390 	sids->owner.SubAuthorities[1] = cpu_to_le32(1);
2391 	sids->owner.SubAuthorities[2] = cpu_to_le32(current_fsuid().val);
2392 
2393 	/* Populate the group ownership fields S-1-5-88-2 */
2394 	sids->group.Revision = 1;
2395 	sids->group.NumAuth = 3;
2396 	sids->group.Authority[5] = 5;
2397 	sids->group.SubAuthorities[0] = cpu_to_le32(88);
2398 	sids->group.SubAuthorities[1] = cpu_to_le32(2);
2399 	sids->group.SubAuthorities[2] = cpu_to_le32(current_fsgid().val);
2400 
2401 	cifs_dbg(FYI, "owner S-1-5-88-1-%d, group S-1-5-88-2-%d\n", current_fsuid().val, current_fsgid().val);
2402 }
2403 
2404 /* See MS-SMB2 2.2.13.2.2 and MS-DTYP 2.4.6 */
2405 static struct crt_sd_ctxt *
create_sd_buf(umode_t mode,bool set_owner,unsigned int * len)2406 create_sd_buf(umode_t mode, bool set_owner, unsigned int *len)
2407 {
2408 	struct crt_sd_ctxt *buf;
2409 	__u8 *ptr, *aclptr;
2410 	unsigned int acelen, acl_size, ace_count;
2411 	unsigned int owner_offset = 0;
2412 	unsigned int group_offset = 0;
2413 	struct smb3_acl acl;
2414 
2415 	*len = roundup(sizeof(struct crt_sd_ctxt) + (sizeof(struct cifs_ace) * 4), 8);
2416 
2417 	if (set_owner) {
2418 		/* sizeof(struct owner_group_sids) is already multiple of 8 so no need to round */
2419 		*len += sizeof(struct owner_group_sids);
2420 	}
2421 
2422 	buf = kzalloc(*len, GFP_KERNEL);
2423 	if (buf == NULL)
2424 		return buf;
2425 
2426 	ptr = (__u8 *)&buf[1];
2427 	if (set_owner) {
2428 		/* offset fields are from beginning of security descriptor not of create context */
2429 		owner_offset = ptr - (__u8 *)&buf->sd;
2430 		buf->sd.OffsetOwner = cpu_to_le32(owner_offset);
2431 		group_offset = owner_offset + offsetof(struct owner_group_sids, group);
2432 		buf->sd.OffsetGroup = cpu_to_le32(group_offset);
2433 
2434 		setup_owner_group_sids(ptr);
2435 		ptr += sizeof(struct owner_group_sids);
2436 	} else {
2437 		buf->sd.OffsetOwner = 0;
2438 		buf->sd.OffsetGroup = 0;
2439 	}
2440 
2441 	buf->ccontext.DataOffset = cpu_to_le16(offsetof(struct crt_sd_ctxt, sd));
2442 	buf->ccontext.NameOffset = cpu_to_le16(offsetof(struct crt_sd_ctxt, Name));
2443 	buf->ccontext.NameLength = cpu_to_le16(4);
2444 	/* SMB2_CREATE_SD_BUFFER_TOKEN is "SecD" */
2445 	buf->Name[0] = 'S';
2446 	buf->Name[1] = 'e';
2447 	buf->Name[2] = 'c';
2448 	buf->Name[3] = 'D';
2449 	buf->sd.Revision = 1;  /* Must be one see MS-DTYP 2.4.6 */
2450 
2451 	/*
2452 	 * ACL is "self relative" ie ACL is stored in contiguous block of memory
2453 	 * and "DP" ie the DACL is present
2454 	 */
2455 	buf->sd.Control = cpu_to_le16(ACL_CONTROL_SR | ACL_CONTROL_DP);
2456 
2457 	/* offset owner, group and Sbz1 and SACL are all zero */
2458 	buf->sd.OffsetDacl = cpu_to_le32(ptr - (__u8 *)&buf->sd);
2459 	/* Ship the ACL for now. we will copy it into buf later. */
2460 	aclptr = ptr;
2461 	ptr += sizeof(struct smb3_acl);
2462 
2463 	/* create one ACE to hold the mode embedded in reserved special SID */
2464 	acelen = setup_special_mode_ACE((struct cifs_ace *)ptr, (__u64)mode);
2465 	ptr += acelen;
2466 	acl_size = acelen + sizeof(struct smb3_acl);
2467 	ace_count = 1;
2468 
2469 	if (set_owner) {
2470 		/* we do not need to reallocate buffer to add the two more ACEs. plenty of space */
2471 		acelen = setup_special_user_owner_ACE((struct cifs_ace *)ptr);
2472 		ptr += acelen;
2473 		acl_size += acelen;
2474 		ace_count += 1;
2475 	}
2476 
2477 	/* and one more ACE to allow access for authenticated users */
2478 	acelen = setup_authusers_ACE((struct cifs_ace *)ptr);
2479 	ptr += acelen;
2480 	acl_size += acelen;
2481 	ace_count += 1;
2482 
2483 	acl.AclRevision = ACL_REVISION; /* See 2.4.4.1 of MS-DTYP */
2484 	acl.AclSize = cpu_to_le16(acl_size);
2485 	acl.AceCount = cpu_to_le16(ace_count);
2486 	memcpy(aclptr, &acl, sizeof(struct smb3_acl));
2487 
2488 	buf->ccontext.DataLength = cpu_to_le32(ptr - (__u8 *)&buf->sd);
2489 	*len = roundup(ptr - (__u8 *)buf, 8);
2490 
2491 	return buf;
2492 }
2493 
2494 static int
add_sd_context(struct kvec * iov,unsigned int * num_iovec,umode_t mode,bool set_owner)2495 add_sd_context(struct kvec *iov, unsigned int *num_iovec, umode_t mode, bool set_owner)
2496 {
2497 	struct smb2_create_req *req = iov[0].iov_base;
2498 	unsigned int num = *num_iovec;
2499 	unsigned int len = 0;
2500 
2501 	iov[num].iov_base = create_sd_buf(mode, set_owner, &len);
2502 	if (iov[num].iov_base == NULL)
2503 		return -ENOMEM;
2504 	iov[num].iov_len = len;
2505 	if (!req->CreateContextsOffset)
2506 		req->CreateContextsOffset = cpu_to_le32(
2507 				sizeof(struct smb2_create_req) +
2508 				iov[num - 1].iov_len);
2509 	le32_add_cpu(&req->CreateContextsLength, len);
2510 	*num_iovec = num + 1;
2511 	return 0;
2512 }
2513 
2514 static struct crt_query_id_ctxt *
create_query_id_buf(void)2515 create_query_id_buf(void)
2516 {
2517 	struct crt_query_id_ctxt *buf;
2518 
2519 	buf = kzalloc(sizeof(struct crt_query_id_ctxt), GFP_KERNEL);
2520 	if (!buf)
2521 		return NULL;
2522 
2523 	buf->ccontext.DataOffset = cpu_to_le16(0);
2524 	buf->ccontext.DataLength = cpu_to_le32(0);
2525 	buf->ccontext.NameOffset = cpu_to_le16(offsetof
2526 				(struct crt_query_id_ctxt, Name));
2527 	buf->ccontext.NameLength = cpu_to_le16(4);
2528 	/* SMB2_CREATE_QUERY_ON_DISK_ID is "QFid" */
2529 	buf->Name[0] = 'Q';
2530 	buf->Name[1] = 'F';
2531 	buf->Name[2] = 'i';
2532 	buf->Name[3] = 'd';
2533 	return buf;
2534 }
2535 
2536 /* See MS-SMB2 2.2.13.2.9 */
2537 static int
add_query_id_context(struct kvec * iov,unsigned int * num_iovec)2538 add_query_id_context(struct kvec *iov, unsigned int *num_iovec)
2539 {
2540 	struct smb2_create_req *req = iov[0].iov_base;
2541 	unsigned int num = *num_iovec;
2542 
2543 	iov[num].iov_base = create_query_id_buf();
2544 	if (iov[num].iov_base == NULL)
2545 		return -ENOMEM;
2546 	iov[num].iov_len = sizeof(struct crt_query_id_ctxt);
2547 	if (!req->CreateContextsOffset)
2548 		req->CreateContextsOffset = cpu_to_le32(
2549 				sizeof(struct smb2_create_req) +
2550 				iov[num - 1].iov_len);
2551 	le32_add_cpu(&req->CreateContextsLength, sizeof(struct crt_query_id_ctxt));
2552 	*num_iovec = num + 1;
2553 	return 0;
2554 }
2555 
2556 static int
alloc_path_with_tree_prefix(__le16 ** out_path,int * out_size,int * out_len,const char * treename,const __le16 * path)2557 alloc_path_with_tree_prefix(__le16 **out_path, int *out_size, int *out_len,
2558 			    const char *treename, const __le16 *path)
2559 {
2560 	int treename_len, path_len;
2561 	struct nls_table *cp;
2562 	const __le16 sep[] = {cpu_to_le16('\\'), cpu_to_le16(0x0000)};
2563 
2564 	/*
2565 	 * skip leading "\\"
2566 	 */
2567 	treename_len = strlen(treename);
2568 	if (treename_len < 2 || !(treename[0] == '\\' && treename[1] == '\\'))
2569 		return -EINVAL;
2570 
2571 	treename += 2;
2572 	treename_len -= 2;
2573 
2574 	path_len = UniStrnlen((wchar_t *)path, PATH_MAX);
2575 
2576 	/* make room for one path separator only if @path isn't empty */
2577 	*out_len = treename_len + (path[0] ? 1 : 0) + path_len;
2578 
2579 	/*
2580 	 * final path needs to be 8-byte aligned as specified in
2581 	 * MS-SMB2 2.2.13 SMB2 CREATE Request.
2582 	 */
2583 	*out_size = roundup(*out_len * sizeof(__le16), 8);
2584 	*out_path = kzalloc(*out_size + sizeof(__le16) /* null */, GFP_KERNEL);
2585 	if (!*out_path)
2586 		return -ENOMEM;
2587 
2588 	cp = load_nls_default();
2589 	cifs_strtoUTF16(*out_path, treename, treename_len, cp);
2590 
2591 	/* Do not append the separator if the path is empty */
2592 	if (path[0] != cpu_to_le16(0x0000)) {
2593 		UniStrcat(*out_path, sep);
2594 		UniStrcat(*out_path, path);
2595 	}
2596 
2597 	unload_nls(cp);
2598 
2599 	return 0;
2600 }
2601 
smb311_posix_mkdir(const unsigned int xid,struct inode * inode,umode_t mode,struct cifs_tcon * tcon,const char * full_path,struct cifs_sb_info * cifs_sb)2602 int smb311_posix_mkdir(const unsigned int xid, struct inode *inode,
2603 			       umode_t mode, struct cifs_tcon *tcon,
2604 			       const char *full_path,
2605 			       struct cifs_sb_info *cifs_sb)
2606 {
2607 	struct smb_rqst rqst;
2608 	struct smb2_create_req *req;
2609 	struct smb2_create_rsp *rsp = NULL;
2610 	struct cifs_ses *ses = tcon->ses;
2611 	struct kvec iov[3]; /* make sure at least one for each open context */
2612 	struct kvec rsp_iov = {NULL, 0};
2613 	int resp_buftype;
2614 	int uni_path_len;
2615 	__le16 *copy_path = NULL;
2616 	int copy_size;
2617 	int rc = 0;
2618 	unsigned int n_iov = 2;
2619 	__u32 file_attributes = 0;
2620 	char *pc_buf = NULL;
2621 	int flags = 0;
2622 	unsigned int total_len;
2623 	__le16 *utf16_path = NULL;
2624 	struct TCP_Server_Info *server = cifs_pick_channel(ses);
2625 
2626 	cifs_dbg(FYI, "mkdir\n");
2627 
2628 	/* resource #1: path allocation */
2629 	utf16_path = cifs_convert_path_to_utf16(full_path, cifs_sb);
2630 	if (!utf16_path)
2631 		return -ENOMEM;
2632 
2633 	if (!ses || !server) {
2634 		rc = -EIO;
2635 		goto err_free_path;
2636 	}
2637 
2638 	/* resource #2: request */
2639 	rc = smb2_plain_req_init(SMB2_CREATE, tcon, server,
2640 				 (void **) &req, &total_len);
2641 	if (rc)
2642 		goto err_free_path;
2643 
2644 
2645 	if (smb3_encryption_required(tcon))
2646 		flags |= CIFS_TRANSFORM_REQ;
2647 
2648 	req->ImpersonationLevel = IL_IMPERSONATION;
2649 	req->DesiredAccess = cpu_to_le32(FILE_WRITE_ATTRIBUTES);
2650 	/* File attributes ignored on open (used in create though) */
2651 	req->FileAttributes = cpu_to_le32(file_attributes);
2652 	req->ShareAccess = FILE_SHARE_ALL_LE;
2653 	req->CreateDisposition = cpu_to_le32(FILE_CREATE);
2654 	req->CreateOptions = cpu_to_le32(CREATE_NOT_FILE);
2655 
2656 	iov[0].iov_base = (char *)req;
2657 	/* -1 since last byte is buf[0] which is sent below (path) */
2658 	iov[0].iov_len = total_len - 1;
2659 
2660 	req->NameOffset = cpu_to_le16(sizeof(struct smb2_create_req));
2661 
2662 	/* [MS-SMB2] 2.2.13 NameOffset:
2663 	 * If SMB2_FLAGS_DFS_OPERATIONS is set in the Flags field of
2664 	 * the SMB2 header, the file name includes a prefix that will
2665 	 * be processed during DFS name normalization as specified in
2666 	 * section 3.3.5.9. Otherwise, the file name is relative to
2667 	 * the share that is identified by the TreeId in the SMB2
2668 	 * header.
2669 	 */
2670 	if (tcon->share_flags & SHI1005_FLAGS_DFS) {
2671 		int name_len;
2672 
2673 		req->hdr.Flags |= SMB2_FLAGS_DFS_OPERATIONS;
2674 		rc = alloc_path_with_tree_prefix(&copy_path, &copy_size,
2675 						 &name_len,
2676 						 tcon->treeName, utf16_path);
2677 		if (rc)
2678 			goto err_free_req;
2679 
2680 		req->NameLength = cpu_to_le16(name_len * 2);
2681 		uni_path_len = copy_size;
2682 		/* free before overwriting resource */
2683 		kfree(utf16_path);
2684 		utf16_path = copy_path;
2685 	} else {
2686 		uni_path_len = (2 * UniStrnlen((wchar_t *)utf16_path, PATH_MAX)) + 2;
2687 		/* MUST set path len (NameLength) to 0 opening root of share */
2688 		req->NameLength = cpu_to_le16(uni_path_len - 2);
2689 		if (uni_path_len % 8 != 0) {
2690 			copy_size = roundup(uni_path_len, 8);
2691 			copy_path = kzalloc(copy_size, GFP_KERNEL);
2692 			if (!copy_path) {
2693 				rc = -ENOMEM;
2694 				goto err_free_req;
2695 			}
2696 			memcpy((char *)copy_path, (const char *)utf16_path,
2697 			       uni_path_len);
2698 			uni_path_len = copy_size;
2699 			/* free before overwriting resource */
2700 			kfree(utf16_path);
2701 			utf16_path = copy_path;
2702 		}
2703 	}
2704 
2705 	iov[1].iov_len = uni_path_len;
2706 	iov[1].iov_base = utf16_path;
2707 	req->RequestedOplockLevel = SMB2_OPLOCK_LEVEL_NONE;
2708 
2709 	if (tcon->posix_extensions) {
2710 		/* resource #3: posix buf */
2711 		rc = add_posix_context(iov, &n_iov, mode);
2712 		if (rc)
2713 			goto err_free_req;
2714 		pc_buf = iov[n_iov-1].iov_base;
2715 	}
2716 
2717 
2718 	memset(&rqst, 0, sizeof(struct smb_rqst));
2719 	rqst.rq_iov = iov;
2720 	rqst.rq_nvec = n_iov;
2721 
2722 	/* no need to inc num_remote_opens because we close it just below */
2723 	trace_smb3_posix_mkdir_enter(xid, tcon->tid, ses->Suid, CREATE_NOT_FILE,
2724 				    FILE_WRITE_ATTRIBUTES);
2725 	/* resource #4: response buffer */
2726 	rc = cifs_send_recv(xid, ses, server,
2727 			    &rqst, &resp_buftype, flags, &rsp_iov);
2728 	if (rc) {
2729 		cifs_stats_fail_inc(tcon, SMB2_CREATE_HE);
2730 		trace_smb3_posix_mkdir_err(xid, tcon->tid, ses->Suid,
2731 					   CREATE_NOT_FILE,
2732 					   FILE_WRITE_ATTRIBUTES, rc);
2733 		goto err_free_rsp_buf;
2734 	}
2735 
2736 	/*
2737 	 * Although unlikely to be possible for rsp to be null and rc not set,
2738 	 * adding check below is slightly safer long term (and quiets Coverity
2739 	 * warning)
2740 	 */
2741 	rsp = (struct smb2_create_rsp *)rsp_iov.iov_base;
2742 	if (rsp == NULL) {
2743 		rc = -EIO;
2744 		kfree(pc_buf);
2745 		goto err_free_req;
2746 	}
2747 
2748 	trace_smb3_posix_mkdir_done(xid, rsp->PersistentFileId, tcon->tid, ses->Suid,
2749 				    CREATE_NOT_FILE, FILE_WRITE_ATTRIBUTES);
2750 
2751 	SMB2_close(xid, tcon, rsp->PersistentFileId, rsp->VolatileFileId);
2752 
2753 	/* Eventually save off posix specific response info and timestaps */
2754 
2755 err_free_rsp_buf:
2756 	free_rsp_buf(resp_buftype, rsp);
2757 	kfree(pc_buf);
2758 err_free_req:
2759 	cifs_small_buf_release(req);
2760 err_free_path:
2761 	kfree(utf16_path);
2762 	return rc;
2763 }
2764 
2765 int
SMB2_open_init(struct cifs_tcon * tcon,struct TCP_Server_Info * server,struct smb_rqst * rqst,__u8 * oplock,struct cifs_open_parms * oparms,__le16 * path)2766 SMB2_open_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
2767 	       struct smb_rqst *rqst, __u8 *oplock,
2768 	       struct cifs_open_parms *oparms, __le16 *path)
2769 {
2770 	struct smb2_create_req *req;
2771 	unsigned int n_iov = 2;
2772 	__u32 file_attributes = 0;
2773 	int copy_size;
2774 	int uni_path_len;
2775 	unsigned int total_len;
2776 	struct kvec *iov = rqst->rq_iov;
2777 	__le16 *copy_path;
2778 	int rc;
2779 
2780 	rc = smb2_plain_req_init(SMB2_CREATE, tcon, server,
2781 				 (void **) &req, &total_len);
2782 	if (rc)
2783 		return rc;
2784 
2785 	iov[0].iov_base = (char *)req;
2786 	/* -1 since last byte is buf[0] which is sent below (path) */
2787 	iov[0].iov_len = total_len - 1;
2788 
2789 	if (oparms->create_options & CREATE_OPTION_READONLY)
2790 		file_attributes |= ATTR_READONLY;
2791 	if (oparms->create_options & CREATE_OPTION_SPECIAL)
2792 		file_attributes |= ATTR_SYSTEM;
2793 
2794 	req->ImpersonationLevel = IL_IMPERSONATION;
2795 	req->DesiredAccess = cpu_to_le32(oparms->desired_access);
2796 	/* File attributes ignored on open (used in create though) */
2797 	req->FileAttributes = cpu_to_le32(file_attributes);
2798 	req->ShareAccess = FILE_SHARE_ALL_LE;
2799 
2800 	req->CreateDisposition = cpu_to_le32(oparms->disposition);
2801 	req->CreateOptions = cpu_to_le32(oparms->create_options & CREATE_OPTIONS_MASK);
2802 	req->NameOffset = cpu_to_le16(sizeof(struct smb2_create_req));
2803 
2804 	/* [MS-SMB2] 2.2.13 NameOffset:
2805 	 * If SMB2_FLAGS_DFS_OPERATIONS is set in the Flags field of
2806 	 * the SMB2 header, the file name includes a prefix that will
2807 	 * be processed during DFS name normalization as specified in
2808 	 * section 3.3.5.9. Otherwise, the file name is relative to
2809 	 * the share that is identified by the TreeId in the SMB2
2810 	 * header.
2811 	 */
2812 	if (tcon->share_flags & SHI1005_FLAGS_DFS) {
2813 		int name_len;
2814 
2815 		req->hdr.Flags |= SMB2_FLAGS_DFS_OPERATIONS;
2816 		rc = alloc_path_with_tree_prefix(&copy_path, &copy_size,
2817 						 &name_len,
2818 						 tcon->treeName, path);
2819 		if (rc)
2820 			return rc;
2821 		req->NameLength = cpu_to_le16(name_len * 2);
2822 		uni_path_len = copy_size;
2823 		path = copy_path;
2824 	} else {
2825 		uni_path_len = (2 * UniStrnlen((wchar_t *)path, PATH_MAX)) + 2;
2826 		/* MUST set path len (NameLength) to 0 opening root of share */
2827 		req->NameLength = cpu_to_le16(uni_path_len - 2);
2828 		copy_size = uni_path_len;
2829 		if (copy_size % 8 != 0)
2830 			copy_size = roundup(copy_size, 8);
2831 		copy_path = kzalloc(copy_size, GFP_KERNEL);
2832 		if (!copy_path)
2833 			return -ENOMEM;
2834 		memcpy((char *)copy_path, (const char *)path,
2835 		       uni_path_len);
2836 		uni_path_len = copy_size;
2837 		path = copy_path;
2838 	}
2839 
2840 	iov[1].iov_len = uni_path_len;
2841 	iov[1].iov_base = path;
2842 
2843 	if ((!server->oplocks) || (tcon->no_lease))
2844 		*oplock = SMB2_OPLOCK_LEVEL_NONE;
2845 
2846 	if (!(server->capabilities & SMB2_GLOBAL_CAP_LEASING) ||
2847 	    *oplock == SMB2_OPLOCK_LEVEL_NONE)
2848 		req->RequestedOplockLevel = *oplock;
2849 	else if (!(server->capabilities & SMB2_GLOBAL_CAP_DIRECTORY_LEASING) &&
2850 		  (oparms->create_options & CREATE_NOT_FILE))
2851 		req->RequestedOplockLevel = *oplock; /* no srv lease support */
2852 	else {
2853 		rc = add_lease_context(server, iov, &n_iov,
2854 				       oparms->fid->lease_key, oplock);
2855 		if (rc)
2856 			return rc;
2857 	}
2858 
2859 	if (*oplock == SMB2_OPLOCK_LEVEL_BATCH) {
2860 		/* need to set Next field of lease context if we request it */
2861 		if (server->capabilities & SMB2_GLOBAL_CAP_LEASING) {
2862 			struct create_context *ccontext =
2863 			    (struct create_context *)iov[n_iov-1].iov_base;
2864 			ccontext->Next =
2865 				cpu_to_le32(server->vals->create_lease_size);
2866 		}
2867 
2868 		rc = add_durable_context(iov, &n_iov, oparms,
2869 					tcon->use_persistent);
2870 		if (rc)
2871 			return rc;
2872 	}
2873 
2874 	if (tcon->posix_extensions) {
2875 		if (n_iov > 2) {
2876 			struct create_context *ccontext =
2877 			    (struct create_context *)iov[n_iov-1].iov_base;
2878 			ccontext->Next =
2879 				cpu_to_le32(iov[n_iov-1].iov_len);
2880 		}
2881 
2882 		rc = add_posix_context(iov, &n_iov, oparms->mode);
2883 		if (rc)
2884 			return rc;
2885 	}
2886 
2887 	if (tcon->snapshot_time) {
2888 		cifs_dbg(FYI, "adding snapshot context\n");
2889 		if (n_iov > 2) {
2890 			struct create_context *ccontext =
2891 			    (struct create_context *)iov[n_iov-1].iov_base;
2892 			ccontext->Next =
2893 				cpu_to_le32(iov[n_iov-1].iov_len);
2894 		}
2895 
2896 		rc = add_twarp_context(iov, &n_iov, tcon->snapshot_time);
2897 		if (rc)
2898 			return rc;
2899 	}
2900 
2901 	if ((oparms->disposition != FILE_OPEN) && (oparms->cifs_sb)) {
2902 		bool set_mode;
2903 		bool set_owner;
2904 
2905 		if ((oparms->cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MODE_FROM_SID) &&
2906 		    (oparms->mode != ACL_NO_MODE))
2907 			set_mode = true;
2908 		else {
2909 			set_mode = false;
2910 			oparms->mode = ACL_NO_MODE;
2911 		}
2912 
2913 		if (oparms->cifs_sb->mnt_cifs_flags & CIFS_MOUNT_UID_FROM_ACL)
2914 			set_owner = true;
2915 		else
2916 			set_owner = false;
2917 
2918 		if (set_owner | set_mode) {
2919 			if (n_iov > 2) {
2920 				struct create_context *ccontext =
2921 				    (struct create_context *)iov[n_iov-1].iov_base;
2922 				ccontext->Next = cpu_to_le32(iov[n_iov-1].iov_len);
2923 			}
2924 
2925 			cifs_dbg(FYI, "add sd with mode 0x%x\n", oparms->mode);
2926 			rc = add_sd_context(iov, &n_iov, oparms->mode, set_owner);
2927 			if (rc)
2928 				return rc;
2929 		}
2930 	}
2931 
2932 	if (n_iov > 2) {
2933 		struct create_context *ccontext =
2934 			(struct create_context *)iov[n_iov-1].iov_base;
2935 		ccontext->Next = cpu_to_le32(iov[n_iov-1].iov_len);
2936 	}
2937 	add_query_id_context(iov, &n_iov);
2938 
2939 	rqst->rq_nvec = n_iov;
2940 	return 0;
2941 }
2942 
2943 /* rq_iov[0] is the request and is released by cifs_small_buf_release().
2944  * All other vectors are freed by kfree().
2945  */
2946 void
SMB2_open_free(struct smb_rqst * rqst)2947 SMB2_open_free(struct smb_rqst *rqst)
2948 {
2949 	int i;
2950 
2951 	if (rqst && rqst->rq_iov) {
2952 		cifs_small_buf_release(rqst->rq_iov[0].iov_base);
2953 		for (i = 1; i < rqst->rq_nvec; i++)
2954 			if (rqst->rq_iov[i].iov_base != smb2_padding)
2955 				kfree(rqst->rq_iov[i].iov_base);
2956 	}
2957 }
2958 
2959 int
SMB2_open(const unsigned int xid,struct cifs_open_parms * oparms,__le16 * path,__u8 * oplock,struct smb2_file_all_info * buf,struct create_posix_rsp * posix,struct kvec * err_iov,int * buftype)2960 SMB2_open(const unsigned int xid, struct cifs_open_parms *oparms, __le16 *path,
2961 	  __u8 *oplock, struct smb2_file_all_info *buf,
2962 	  struct create_posix_rsp *posix,
2963 	  struct kvec *err_iov, int *buftype)
2964 {
2965 	struct smb_rqst rqst;
2966 	struct smb2_create_rsp *rsp = NULL;
2967 	struct cifs_tcon *tcon = oparms->tcon;
2968 	struct cifs_ses *ses = tcon->ses;
2969 	struct TCP_Server_Info *server = cifs_pick_channel(ses);
2970 	struct kvec iov[SMB2_CREATE_IOV_SIZE];
2971 	struct kvec rsp_iov = {NULL, 0};
2972 	int resp_buftype = CIFS_NO_BUFFER;
2973 	int rc = 0;
2974 	int flags = 0;
2975 
2976 	cifs_dbg(FYI, "create/open\n");
2977 	if (!ses || !server)
2978 		return -EIO;
2979 
2980 	if (smb3_encryption_required(tcon))
2981 		flags |= CIFS_TRANSFORM_REQ;
2982 
2983 	memset(&rqst, 0, sizeof(struct smb_rqst));
2984 	memset(&iov, 0, sizeof(iov));
2985 	rqst.rq_iov = iov;
2986 	rqst.rq_nvec = SMB2_CREATE_IOV_SIZE;
2987 
2988 	rc = SMB2_open_init(tcon, server,
2989 			    &rqst, oplock, oparms, path);
2990 	if (rc)
2991 		goto creat_exit;
2992 
2993 	trace_smb3_open_enter(xid, tcon->tid, tcon->ses->Suid,
2994 		oparms->create_options, oparms->desired_access);
2995 
2996 	rc = cifs_send_recv(xid, ses, server,
2997 			    &rqst, &resp_buftype, flags,
2998 			    &rsp_iov);
2999 	rsp = (struct smb2_create_rsp *)rsp_iov.iov_base;
3000 
3001 	if (rc != 0) {
3002 		cifs_stats_fail_inc(tcon, SMB2_CREATE_HE);
3003 		if (err_iov && rsp) {
3004 			*err_iov = rsp_iov;
3005 			*buftype = resp_buftype;
3006 			resp_buftype = CIFS_NO_BUFFER;
3007 			rsp = NULL;
3008 		}
3009 		trace_smb3_open_err(xid, tcon->tid, ses->Suid,
3010 				    oparms->create_options, oparms->desired_access, rc);
3011 		if (rc == -EREMCHG) {
3012 			pr_warn_once("server share %s deleted\n",
3013 				     tcon->treeName);
3014 			tcon->need_reconnect = true;
3015 		}
3016 		goto creat_exit;
3017 	} else if (rsp == NULL) /* unlikely to happen, but safer to check */
3018 		goto creat_exit;
3019 	else
3020 		trace_smb3_open_done(xid, rsp->PersistentFileId, tcon->tid, ses->Suid,
3021 				     oparms->create_options, oparms->desired_access);
3022 
3023 	atomic_inc(&tcon->num_remote_opens);
3024 	oparms->fid->persistent_fid = rsp->PersistentFileId;
3025 	oparms->fid->volatile_fid = rsp->VolatileFileId;
3026 	oparms->fid->access = oparms->desired_access;
3027 #ifdef CONFIG_CIFS_DEBUG2
3028 	oparms->fid->mid = le64_to_cpu(rsp->hdr.MessageId);
3029 #endif /* CIFS_DEBUG2 */
3030 
3031 	if (buf) {
3032 		buf->CreationTime = rsp->CreationTime;
3033 		buf->LastAccessTime = rsp->LastAccessTime;
3034 		buf->LastWriteTime = rsp->LastWriteTime;
3035 		buf->ChangeTime = rsp->ChangeTime;
3036 		buf->AllocationSize = rsp->AllocationSize;
3037 		buf->EndOfFile = rsp->EndofFile;
3038 		buf->Attributes = rsp->FileAttributes;
3039 		buf->NumberOfLinks = cpu_to_le32(1);
3040 		buf->DeletePending = 0;
3041 	}
3042 
3043 
3044 	smb2_parse_contexts(server, rsp, &oparms->fid->epoch,
3045 			    oparms->fid->lease_key, oplock, buf, posix);
3046 creat_exit:
3047 	SMB2_open_free(&rqst);
3048 	free_rsp_buf(resp_buftype, rsp);
3049 	return rc;
3050 }
3051 
3052 int
SMB2_ioctl_init(struct cifs_tcon * tcon,struct TCP_Server_Info * server,struct smb_rqst * rqst,u64 persistent_fid,u64 volatile_fid,u32 opcode,char * in_data,u32 indatalen,__u32 max_response_size)3053 SMB2_ioctl_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
3054 		struct smb_rqst *rqst,
3055 		u64 persistent_fid, u64 volatile_fid, u32 opcode,
3056 		char *in_data, u32 indatalen,
3057 		__u32 max_response_size)
3058 {
3059 	struct smb2_ioctl_req *req;
3060 	struct kvec *iov = rqst->rq_iov;
3061 	unsigned int total_len;
3062 	int rc;
3063 	char *in_data_buf;
3064 
3065 	rc = smb2_ioctl_req_init(opcode, tcon, server,
3066 				 (void **) &req, &total_len);
3067 	if (rc)
3068 		return rc;
3069 
3070 	if (indatalen) {
3071 		/*
3072 		 * indatalen is usually small at a couple of bytes max, so
3073 		 * just allocate through generic pool
3074 		 */
3075 		in_data_buf = kmemdup(in_data, indatalen, GFP_NOFS);
3076 		if (!in_data_buf) {
3077 			cifs_small_buf_release(req);
3078 			return -ENOMEM;
3079 		}
3080 	}
3081 
3082 	req->CtlCode = cpu_to_le32(opcode);
3083 	req->PersistentFileId = persistent_fid;
3084 	req->VolatileFileId = volatile_fid;
3085 
3086 	iov[0].iov_base = (char *)req;
3087 	/*
3088 	 * If no input data, the size of ioctl struct in
3089 	 * protocol spec still includes a 1 byte data buffer,
3090 	 * but if input data passed to ioctl, we do not
3091 	 * want to double count this, so we do not send
3092 	 * the dummy one byte of data in iovec[0] if sending
3093 	 * input data (in iovec[1]).
3094 	 */
3095 	if (indatalen) {
3096 		req->InputCount = cpu_to_le32(indatalen);
3097 		/* do not set InputOffset if no input data */
3098 		req->InputOffset =
3099 		       cpu_to_le32(offsetof(struct smb2_ioctl_req, Buffer));
3100 		rqst->rq_nvec = 2;
3101 		iov[0].iov_len = total_len - 1;
3102 		iov[1].iov_base = in_data_buf;
3103 		iov[1].iov_len = indatalen;
3104 	} else {
3105 		rqst->rq_nvec = 1;
3106 		iov[0].iov_len = total_len;
3107 	}
3108 
3109 	req->OutputOffset = 0;
3110 	req->OutputCount = 0; /* MBZ */
3111 
3112 	/*
3113 	 * In most cases max_response_size is set to 16K (CIFSMaxBufSize)
3114 	 * We Could increase default MaxOutputResponse, but that could require
3115 	 * more credits. Windows typically sets this smaller, but for some
3116 	 * ioctls it may be useful to allow server to send more. No point
3117 	 * limiting what the server can send as long as fits in one credit
3118 	 * We can not handle more than CIFS_MAX_BUF_SIZE yet but may want
3119 	 * to increase this limit up in the future.
3120 	 * Note that for snapshot queries that servers like Azure expect that
3121 	 * the first query be minimal size (and just used to get the number/size
3122 	 * of previous versions) so response size must be specified as EXACTLY
3123 	 * sizeof(struct snapshot_array) which is 16 when rounded up to multiple
3124 	 * of eight bytes.  Currently that is the only case where we set max
3125 	 * response size smaller.
3126 	 */
3127 	req->MaxOutputResponse = cpu_to_le32(max_response_size);
3128 	req->hdr.CreditCharge =
3129 		cpu_to_le16(DIV_ROUND_UP(max(indatalen, max_response_size),
3130 					 SMB2_MAX_BUFFER_SIZE));
3131 	/* always an FSCTL (for now) */
3132 	req->Flags = cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL);
3133 
3134 	/* validate negotiate request must be signed - see MS-SMB2 3.2.5.5 */
3135 	if (opcode == FSCTL_VALIDATE_NEGOTIATE_INFO)
3136 		req->hdr.Flags |= SMB2_FLAGS_SIGNED;
3137 
3138 	return 0;
3139 }
3140 
3141 void
SMB2_ioctl_free(struct smb_rqst * rqst)3142 SMB2_ioctl_free(struct smb_rqst *rqst)
3143 {
3144 	int i;
3145 	if (rqst && rqst->rq_iov) {
3146 		cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
3147 		for (i = 1; i < rqst->rq_nvec; i++)
3148 			if (rqst->rq_iov[i].iov_base != smb2_padding)
3149 				kfree(rqst->rq_iov[i].iov_base);
3150 	}
3151 }
3152 
3153 
3154 /*
3155  *	SMB2 IOCTL is used for both IOCTLs and FSCTLs
3156  */
3157 int
SMB2_ioctl(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,u32 opcode,char * in_data,u32 indatalen,u32 max_out_data_len,char ** out_data,u32 * plen)3158 SMB2_ioctl(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
3159 	   u64 volatile_fid, u32 opcode, char *in_data, u32 indatalen,
3160 	   u32 max_out_data_len, char **out_data,
3161 	   u32 *plen /* returned data len */)
3162 {
3163 	struct smb_rqst rqst;
3164 	struct smb2_ioctl_rsp *rsp = NULL;
3165 	struct cifs_ses *ses;
3166 	struct TCP_Server_Info *server;
3167 	struct kvec iov[SMB2_IOCTL_IOV_SIZE];
3168 	struct kvec rsp_iov = {NULL, 0};
3169 	int resp_buftype = CIFS_NO_BUFFER;
3170 	int rc = 0;
3171 	int flags = 0;
3172 
3173 	cifs_dbg(FYI, "SMB2 IOCTL\n");
3174 
3175 	if (out_data != NULL)
3176 		*out_data = NULL;
3177 
3178 	/* zero out returned data len, in case of error */
3179 	if (plen)
3180 		*plen = 0;
3181 
3182 	if (!tcon)
3183 		return -EIO;
3184 
3185 	ses = tcon->ses;
3186 	if (!ses)
3187 		return -EIO;
3188 
3189 	server = cifs_pick_channel(ses);
3190 	if (!server)
3191 		return -EIO;
3192 
3193 	if (smb3_encryption_required(tcon))
3194 		flags |= CIFS_TRANSFORM_REQ;
3195 
3196 	memset(&rqst, 0, sizeof(struct smb_rqst));
3197 	memset(&iov, 0, sizeof(iov));
3198 	rqst.rq_iov = iov;
3199 	rqst.rq_nvec = SMB2_IOCTL_IOV_SIZE;
3200 
3201 	rc = SMB2_ioctl_init(tcon, server,
3202 			     &rqst, persistent_fid, volatile_fid, opcode,
3203 			     in_data, indatalen, max_out_data_len);
3204 	if (rc)
3205 		goto ioctl_exit;
3206 
3207 	rc = cifs_send_recv(xid, ses, server,
3208 			    &rqst, &resp_buftype, flags,
3209 			    &rsp_iov);
3210 	rsp = (struct smb2_ioctl_rsp *)rsp_iov.iov_base;
3211 
3212 	if (rc != 0)
3213 		trace_smb3_fsctl_err(xid, persistent_fid, tcon->tid,
3214 				ses->Suid, 0, opcode, rc);
3215 
3216 	if ((rc != 0) && (rc != -EINVAL) && (rc != -E2BIG)) {
3217 		cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
3218 		goto ioctl_exit;
3219 	} else if (rc == -EINVAL) {
3220 		if ((opcode != FSCTL_SRV_COPYCHUNK_WRITE) &&
3221 		    (opcode != FSCTL_SRV_COPYCHUNK)) {
3222 			cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
3223 			goto ioctl_exit;
3224 		}
3225 	} else if (rc == -E2BIG) {
3226 		if (opcode != FSCTL_QUERY_ALLOCATED_RANGES) {
3227 			cifs_stats_fail_inc(tcon, SMB2_IOCTL_HE);
3228 			goto ioctl_exit;
3229 		}
3230 	}
3231 
3232 	/* check if caller wants to look at return data or just return rc */
3233 	if ((plen == NULL) || (out_data == NULL))
3234 		goto ioctl_exit;
3235 
3236 	/*
3237 	 * Although unlikely to be possible for rsp to be null and rc not set,
3238 	 * adding check below is slightly safer long term (and quiets Coverity
3239 	 * warning)
3240 	 */
3241 	if (rsp == NULL) {
3242 		rc = -EIO;
3243 		goto ioctl_exit;
3244 	}
3245 
3246 	*plen = le32_to_cpu(rsp->OutputCount);
3247 
3248 	/* We check for obvious errors in the output buffer length and offset */
3249 	if (*plen == 0)
3250 		goto ioctl_exit; /* server returned no data */
3251 	else if (*plen > rsp_iov.iov_len || *plen > 0xFF00) {
3252 		cifs_tcon_dbg(VFS, "srv returned invalid ioctl length: %d\n", *plen);
3253 		*plen = 0;
3254 		rc = -EIO;
3255 		goto ioctl_exit;
3256 	}
3257 
3258 	if (rsp_iov.iov_len - *plen < le32_to_cpu(rsp->OutputOffset)) {
3259 		cifs_tcon_dbg(VFS, "Malformed ioctl resp: len %d offset %d\n", *plen,
3260 			le32_to_cpu(rsp->OutputOffset));
3261 		*plen = 0;
3262 		rc = -EIO;
3263 		goto ioctl_exit;
3264 	}
3265 
3266 	*out_data = kmemdup((char *)rsp + le32_to_cpu(rsp->OutputOffset),
3267 			    *plen, GFP_KERNEL);
3268 	if (*out_data == NULL) {
3269 		rc = -ENOMEM;
3270 		goto ioctl_exit;
3271 	}
3272 
3273 ioctl_exit:
3274 	SMB2_ioctl_free(&rqst);
3275 	free_rsp_buf(resp_buftype, rsp);
3276 	return rc;
3277 }
3278 
3279 /*
3280  *   Individual callers to ioctl worker function follow
3281  */
3282 
3283 int
SMB2_set_compression(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid)3284 SMB2_set_compression(const unsigned int xid, struct cifs_tcon *tcon,
3285 		     u64 persistent_fid, u64 volatile_fid)
3286 {
3287 	int rc;
3288 	struct  compress_ioctl fsctl_input;
3289 	char *ret_data = NULL;
3290 
3291 	fsctl_input.CompressionState =
3292 			cpu_to_le16(COMPRESSION_FORMAT_DEFAULT);
3293 
3294 	rc = SMB2_ioctl(xid, tcon, persistent_fid, volatile_fid,
3295 			FSCTL_SET_COMPRESSION,
3296 			(char *)&fsctl_input /* data input */,
3297 			2 /* in data len */, CIFSMaxBufSize /* max out data */,
3298 			&ret_data /* out data */, NULL);
3299 
3300 	cifs_dbg(FYI, "set compression rc %d\n", rc);
3301 
3302 	return rc;
3303 }
3304 
3305 int
SMB2_close_init(struct cifs_tcon * tcon,struct TCP_Server_Info * server,struct smb_rqst * rqst,u64 persistent_fid,u64 volatile_fid,bool query_attrs)3306 SMB2_close_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
3307 		struct smb_rqst *rqst,
3308 		u64 persistent_fid, u64 volatile_fid, bool query_attrs)
3309 {
3310 	struct smb2_close_req *req;
3311 	struct kvec *iov = rqst->rq_iov;
3312 	unsigned int total_len;
3313 	int rc;
3314 
3315 	rc = smb2_plain_req_init(SMB2_CLOSE, tcon, server,
3316 				 (void **) &req, &total_len);
3317 	if (rc)
3318 		return rc;
3319 
3320 	req->PersistentFileId = persistent_fid;
3321 	req->VolatileFileId = volatile_fid;
3322 	if (query_attrs)
3323 		req->Flags = SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB;
3324 	else
3325 		req->Flags = 0;
3326 	iov[0].iov_base = (char *)req;
3327 	iov[0].iov_len = total_len;
3328 
3329 	return 0;
3330 }
3331 
3332 void
SMB2_close_free(struct smb_rqst * rqst)3333 SMB2_close_free(struct smb_rqst *rqst)
3334 {
3335 	if (rqst && rqst->rq_iov)
3336 		cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
3337 }
3338 
3339 int
__SMB2_close(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,struct smb2_file_network_open_info * pbuf)3340 __SMB2_close(const unsigned int xid, struct cifs_tcon *tcon,
3341 	     u64 persistent_fid, u64 volatile_fid,
3342 	     struct smb2_file_network_open_info *pbuf)
3343 {
3344 	struct smb_rqst rqst;
3345 	struct smb2_close_rsp *rsp = NULL;
3346 	struct cifs_ses *ses = tcon->ses;
3347 	struct TCP_Server_Info *server = cifs_pick_channel(ses);
3348 	struct kvec iov[1];
3349 	struct kvec rsp_iov;
3350 	int resp_buftype = CIFS_NO_BUFFER;
3351 	int rc = 0;
3352 	int flags = 0;
3353 	bool query_attrs = false;
3354 
3355 	cifs_dbg(FYI, "Close\n");
3356 
3357 	if (!ses || !server)
3358 		return -EIO;
3359 
3360 	if (smb3_encryption_required(tcon))
3361 		flags |= CIFS_TRANSFORM_REQ;
3362 
3363 	memset(&rqst, 0, sizeof(struct smb_rqst));
3364 	memset(&iov, 0, sizeof(iov));
3365 	rqst.rq_iov = iov;
3366 	rqst.rq_nvec = 1;
3367 
3368 	/* check if need to ask server to return timestamps in close response */
3369 	if (pbuf)
3370 		query_attrs = true;
3371 
3372 	trace_smb3_close_enter(xid, persistent_fid, tcon->tid, ses->Suid);
3373 	rc = SMB2_close_init(tcon, server,
3374 			     &rqst, persistent_fid, volatile_fid,
3375 			     query_attrs);
3376 	if (rc)
3377 		goto close_exit;
3378 
3379 	rc = cifs_send_recv(xid, ses, server,
3380 			    &rqst, &resp_buftype, flags, &rsp_iov);
3381 	rsp = (struct smb2_close_rsp *)rsp_iov.iov_base;
3382 
3383 	if (rc != 0) {
3384 		cifs_stats_fail_inc(tcon, SMB2_CLOSE_HE);
3385 		trace_smb3_close_err(xid, persistent_fid, tcon->tid, ses->Suid,
3386 				     rc);
3387 		goto close_exit;
3388 	} else {
3389 		trace_smb3_close_done(xid, persistent_fid, tcon->tid,
3390 				      ses->Suid);
3391 		/*
3392 		 * Note that have to subtract 4 since struct network_open_info
3393 		 * has a final 4 byte pad that close response does not have
3394 		 */
3395 		if (pbuf)
3396 			memcpy(pbuf, (char *)&rsp->CreationTime, sizeof(*pbuf) - 4);
3397 	}
3398 
3399 	atomic_dec(&tcon->num_remote_opens);
3400 close_exit:
3401 	SMB2_close_free(&rqst);
3402 	free_rsp_buf(resp_buftype, rsp);
3403 
3404 	/* retry close in a worker thread if this one is interrupted */
3405 	if (is_interrupt_error(rc)) {
3406 		int tmp_rc;
3407 
3408 		tmp_rc = smb2_handle_cancelled_close(tcon, persistent_fid,
3409 						     volatile_fid);
3410 		if (tmp_rc)
3411 			cifs_dbg(VFS, "handle cancelled close fid 0x%llx returned error %d\n",
3412 				 persistent_fid, tmp_rc);
3413 	}
3414 	return rc;
3415 }
3416 
3417 int
SMB2_close(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid)3418 SMB2_close(const unsigned int xid, struct cifs_tcon *tcon,
3419 		u64 persistent_fid, u64 volatile_fid)
3420 {
3421 	return __SMB2_close(xid, tcon, persistent_fid, volatile_fid, NULL);
3422 }
3423 
3424 int
smb2_validate_iov(unsigned int offset,unsigned int buffer_length,struct kvec * iov,unsigned int min_buf_size)3425 smb2_validate_iov(unsigned int offset, unsigned int buffer_length,
3426 		  struct kvec *iov, unsigned int min_buf_size)
3427 {
3428 	unsigned int smb_len = iov->iov_len;
3429 	char *end_of_smb = smb_len + (char *)iov->iov_base;
3430 	char *begin_of_buf = offset + (char *)iov->iov_base;
3431 	char *end_of_buf = begin_of_buf + buffer_length;
3432 
3433 
3434 	if (buffer_length < min_buf_size) {
3435 		cifs_dbg(VFS, "buffer length %d smaller than minimum size %d\n",
3436 			 buffer_length, min_buf_size);
3437 		return -EINVAL;
3438 	}
3439 
3440 	/* check if beyond RFC1001 maximum length */
3441 	if ((smb_len > 0x7FFFFF) || (buffer_length > 0x7FFFFF)) {
3442 		cifs_dbg(VFS, "buffer length %d or smb length %d too large\n",
3443 			 buffer_length, smb_len);
3444 		return -EINVAL;
3445 	}
3446 
3447 	if ((begin_of_buf > end_of_smb) || (end_of_buf > end_of_smb)) {
3448 		cifs_dbg(VFS, "Invalid server response, bad offset to data\n");
3449 		return -EINVAL;
3450 	}
3451 
3452 	return 0;
3453 }
3454 
3455 /*
3456  * If SMB buffer fields are valid, copy into temporary buffer to hold result.
3457  * Caller must free buffer.
3458  */
3459 int
smb2_validate_and_copy_iov(unsigned int offset,unsigned int buffer_length,struct kvec * iov,unsigned int minbufsize,char * data)3460 smb2_validate_and_copy_iov(unsigned int offset, unsigned int buffer_length,
3461 			   struct kvec *iov, unsigned int minbufsize,
3462 			   char *data)
3463 {
3464 	char *begin_of_buf = offset + (char *)iov->iov_base;
3465 	int rc;
3466 
3467 	if (!data)
3468 		return -EINVAL;
3469 
3470 	rc = smb2_validate_iov(offset, buffer_length, iov, minbufsize);
3471 	if (rc)
3472 		return rc;
3473 
3474 	memcpy(data, begin_of_buf, buffer_length);
3475 
3476 	return 0;
3477 }
3478 
3479 int
SMB2_query_info_init(struct cifs_tcon * tcon,struct TCP_Server_Info * server,struct smb_rqst * rqst,u64 persistent_fid,u64 volatile_fid,u8 info_class,u8 info_type,u32 additional_info,size_t output_len,size_t input_len,void * input)3480 SMB2_query_info_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
3481 		     struct smb_rqst *rqst,
3482 		     u64 persistent_fid, u64 volatile_fid,
3483 		     u8 info_class, u8 info_type, u32 additional_info,
3484 		     size_t output_len, size_t input_len, void *input)
3485 {
3486 	struct smb2_query_info_req *req;
3487 	struct kvec *iov = rqst->rq_iov;
3488 	unsigned int total_len;
3489 	int rc;
3490 
3491 	rc = smb2_plain_req_init(SMB2_QUERY_INFO, tcon, server,
3492 				 (void **) &req, &total_len);
3493 	if (rc)
3494 		return rc;
3495 
3496 	req->InfoType = info_type;
3497 	req->FileInfoClass = info_class;
3498 	req->PersistentFileId = persistent_fid;
3499 	req->VolatileFileId = volatile_fid;
3500 	req->AdditionalInformation = cpu_to_le32(additional_info);
3501 
3502 	req->OutputBufferLength = cpu_to_le32(output_len);
3503 	if (input_len) {
3504 		req->InputBufferLength = cpu_to_le32(input_len);
3505 		/* total_len for smb query request never close to le16 max */
3506 		req->InputBufferOffset = cpu_to_le16(total_len - 1);
3507 		memcpy(req->Buffer, input, input_len);
3508 	}
3509 
3510 	iov[0].iov_base = (char *)req;
3511 	/* 1 for Buffer */
3512 	iov[0].iov_len = total_len - 1 + input_len;
3513 	return 0;
3514 }
3515 
3516 void
SMB2_query_info_free(struct smb_rqst * rqst)3517 SMB2_query_info_free(struct smb_rqst *rqst)
3518 {
3519 	if (rqst && rqst->rq_iov)
3520 		cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
3521 }
3522 
3523 static int
query_info(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,u8 info_class,u8 info_type,u32 additional_info,size_t output_len,size_t min_len,void ** data,u32 * dlen)3524 query_info(const unsigned int xid, struct cifs_tcon *tcon,
3525 	   u64 persistent_fid, u64 volatile_fid, u8 info_class, u8 info_type,
3526 	   u32 additional_info, size_t output_len, size_t min_len, void **data,
3527 		u32 *dlen)
3528 {
3529 	struct smb_rqst rqst;
3530 	struct smb2_query_info_rsp *rsp = NULL;
3531 	struct kvec iov[1];
3532 	struct kvec rsp_iov;
3533 	int rc = 0;
3534 	int resp_buftype = CIFS_NO_BUFFER;
3535 	struct cifs_ses *ses = tcon->ses;
3536 	struct TCP_Server_Info *server;
3537 	int flags = 0;
3538 	bool allocated = false;
3539 
3540 	cifs_dbg(FYI, "Query Info\n");
3541 
3542 	if (!ses)
3543 		return -EIO;
3544 	server = cifs_pick_channel(ses);
3545 	if (!server)
3546 		return -EIO;
3547 
3548 	if (smb3_encryption_required(tcon))
3549 		flags |= CIFS_TRANSFORM_REQ;
3550 
3551 	memset(&rqst, 0, sizeof(struct smb_rqst));
3552 	memset(&iov, 0, sizeof(iov));
3553 	rqst.rq_iov = iov;
3554 	rqst.rq_nvec = 1;
3555 
3556 	rc = SMB2_query_info_init(tcon, server,
3557 				  &rqst, persistent_fid, volatile_fid,
3558 				  info_class, info_type, additional_info,
3559 				  output_len, 0, NULL);
3560 	if (rc)
3561 		goto qinf_exit;
3562 
3563 	trace_smb3_query_info_enter(xid, persistent_fid, tcon->tid,
3564 				    ses->Suid, info_class, (__u32)info_type);
3565 
3566 	rc = cifs_send_recv(xid, ses, server,
3567 			    &rqst, &resp_buftype, flags, &rsp_iov);
3568 	rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
3569 
3570 	if (rc) {
3571 		cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
3572 		trace_smb3_query_info_err(xid, persistent_fid, tcon->tid,
3573 				ses->Suid, info_class, (__u32)info_type, rc);
3574 		goto qinf_exit;
3575 	}
3576 
3577 	trace_smb3_query_info_done(xid, persistent_fid, tcon->tid,
3578 				ses->Suid, info_class, (__u32)info_type);
3579 
3580 	if (dlen) {
3581 		*dlen = le32_to_cpu(rsp->OutputBufferLength);
3582 		if (!*data) {
3583 			*data = kmalloc(*dlen, GFP_KERNEL);
3584 			if (!*data) {
3585 				cifs_tcon_dbg(VFS,
3586 					"Error %d allocating memory for acl\n",
3587 					rc);
3588 				*dlen = 0;
3589 				rc = -ENOMEM;
3590 				goto qinf_exit;
3591 			}
3592 			allocated = true;
3593 		}
3594 	}
3595 
3596 	rc = smb2_validate_and_copy_iov(le16_to_cpu(rsp->OutputBufferOffset),
3597 					le32_to_cpu(rsp->OutputBufferLength),
3598 					&rsp_iov, min_len, *data);
3599 	if (rc && allocated) {
3600 		kfree(*data);
3601 		*data = NULL;
3602 		*dlen = 0;
3603 	}
3604 
3605 qinf_exit:
3606 	SMB2_query_info_free(&rqst);
3607 	free_rsp_buf(resp_buftype, rsp);
3608 	return rc;
3609 }
3610 
SMB2_query_info(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,struct smb2_file_all_info * data)3611 int SMB2_query_info(const unsigned int xid, struct cifs_tcon *tcon,
3612 	u64 persistent_fid, u64 volatile_fid, struct smb2_file_all_info *data)
3613 {
3614 	return query_info(xid, tcon, persistent_fid, volatile_fid,
3615 			  FILE_ALL_INFORMATION, SMB2_O_INFO_FILE, 0,
3616 			  sizeof(struct smb2_file_all_info) + PATH_MAX * 2,
3617 			  sizeof(struct smb2_file_all_info), (void **)&data,
3618 			  NULL);
3619 }
3620 
3621 #if 0
3622 /* currently unused, as now we are doing compounding instead (see smb311_posix_query_path_info) */
3623 int
3624 SMB311_posix_query_info(const unsigned int xid, struct cifs_tcon *tcon,
3625 		u64 persistent_fid, u64 volatile_fid, struct smb311_posix_qinfo *data, u32 *plen)
3626 {
3627 	size_t output_len = sizeof(struct smb311_posix_qinfo *) +
3628 			(sizeof(struct cifs_sid) * 2) + (PATH_MAX * 2);
3629 	*plen = 0;
3630 
3631 	return query_info(xid, tcon, persistent_fid, volatile_fid,
3632 			  SMB_FIND_FILE_POSIX_INFO, SMB2_O_INFO_FILE, 0,
3633 			  output_len, sizeof(struct smb311_posix_qinfo), (void **)&data, plen);
3634 	/* Note caller must free "data" (passed in above). It may be allocated in query_info call */
3635 }
3636 #endif
3637 
3638 int
SMB2_query_acl(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,void ** data,u32 * plen,u32 extra_info)3639 SMB2_query_acl(const unsigned int xid, struct cifs_tcon *tcon,
3640 	       u64 persistent_fid, u64 volatile_fid,
3641 	       void **data, u32 *plen, u32 extra_info)
3642 {
3643 	__u32 additional_info = OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO |
3644 				extra_info;
3645 	*plen = 0;
3646 
3647 	return query_info(xid, tcon, persistent_fid, volatile_fid,
3648 			  0, SMB2_O_INFO_SECURITY, additional_info,
3649 			  SMB2_MAX_BUFFER_SIZE, MIN_SEC_DESC_LEN, data, plen);
3650 }
3651 
3652 int
SMB2_get_srv_num(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,__le64 * uniqueid)3653 SMB2_get_srv_num(const unsigned int xid, struct cifs_tcon *tcon,
3654 		 u64 persistent_fid, u64 volatile_fid, __le64 *uniqueid)
3655 {
3656 	return query_info(xid, tcon, persistent_fid, volatile_fid,
3657 			  FILE_INTERNAL_INFORMATION, SMB2_O_INFO_FILE, 0,
3658 			  sizeof(struct smb2_file_internal_info),
3659 			  sizeof(struct smb2_file_internal_info),
3660 			  (void **)&uniqueid, NULL);
3661 }
3662 
3663 /*
3664  * CHANGE_NOTIFY Request is sent to get notifications on changes to a directory
3665  * See MS-SMB2 2.2.35 and 2.2.36
3666  */
3667 
3668 static int
SMB2_notify_init(const unsigned int xid,struct smb_rqst * rqst,struct cifs_tcon * tcon,struct TCP_Server_Info * server,u64 persistent_fid,u64 volatile_fid,u32 completion_filter,bool watch_tree)3669 SMB2_notify_init(const unsigned int xid, struct smb_rqst *rqst,
3670 		 struct cifs_tcon *tcon, struct TCP_Server_Info *server,
3671 		 u64 persistent_fid, u64 volatile_fid,
3672 		 u32 completion_filter, bool watch_tree)
3673 {
3674 	struct smb2_change_notify_req *req;
3675 	struct kvec *iov = rqst->rq_iov;
3676 	unsigned int total_len;
3677 	int rc;
3678 
3679 	rc = smb2_plain_req_init(SMB2_CHANGE_NOTIFY, tcon, server,
3680 				 (void **) &req, &total_len);
3681 	if (rc)
3682 		return rc;
3683 
3684 	req->PersistentFileId = persistent_fid;
3685 	req->VolatileFileId = volatile_fid;
3686 	/* See note 354 of MS-SMB2, 64K max */
3687 	req->OutputBufferLength =
3688 		cpu_to_le32(SMB2_MAX_BUFFER_SIZE - MAX_SMB2_HDR_SIZE);
3689 	req->CompletionFilter = cpu_to_le32(completion_filter);
3690 	if (watch_tree)
3691 		req->Flags = cpu_to_le16(SMB2_WATCH_TREE);
3692 	else
3693 		req->Flags = 0;
3694 
3695 	iov[0].iov_base = (char *)req;
3696 	iov[0].iov_len = total_len;
3697 
3698 	return 0;
3699 }
3700 
3701 int
SMB2_change_notify(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,bool watch_tree,u32 completion_filter)3702 SMB2_change_notify(const unsigned int xid, struct cifs_tcon *tcon,
3703 		u64 persistent_fid, u64 volatile_fid, bool watch_tree,
3704 		u32 completion_filter)
3705 {
3706 	struct cifs_ses *ses = tcon->ses;
3707 	struct TCP_Server_Info *server = cifs_pick_channel(ses);
3708 	struct smb_rqst rqst;
3709 	struct kvec iov[1];
3710 	struct kvec rsp_iov = {NULL, 0};
3711 	int resp_buftype = CIFS_NO_BUFFER;
3712 	int flags = 0;
3713 	int rc = 0;
3714 
3715 	cifs_dbg(FYI, "change notify\n");
3716 	if (!ses || !server)
3717 		return -EIO;
3718 
3719 	if (smb3_encryption_required(tcon))
3720 		flags |= CIFS_TRANSFORM_REQ;
3721 
3722 	memset(&rqst, 0, sizeof(struct smb_rqst));
3723 	memset(&iov, 0, sizeof(iov));
3724 	rqst.rq_iov = iov;
3725 	rqst.rq_nvec = 1;
3726 
3727 	rc = SMB2_notify_init(xid, &rqst, tcon, server,
3728 			      persistent_fid, volatile_fid,
3729 			      completion_filter, watch_tree);
3730 	if (rc)
3731 		goto cnotify_exit;
3732 
3733 	trace_smb3_notify_enter(xid, persistent_fid, tcon->tid, ses->Suid,
3734 				(u8)watch_tree, completion_filter);
3735 	rc = cifs_send_recv(xid, ses, server,
3736 			    &rqst, &resp_buftype, flags, &rsp_iov);
3737 
3738 	if (rc != 0) {
3739 		cifs_stats_fail_inc(tcon, SMB2_CHANGE_NOTIFY_HE);
3740 		trace_smb3_notify_err(xid, persistent_fid, tcon->tid, ses->Suid,
3741 				(u8)watch_tree, completion_filter, rc);
3742 	} else
3743 		trace_smb3_notify_done(xid, persistent_fid, tcon->tid,
3744 				ses->Suid, (u8)watch_tree, completion_filter);
3745 
3746  cnotify_exit:
3747 	if (rqst.rq_iov)
3748 		cifs_small_buf_release(rqst.rq_iov[0].iov_base); /* request */
3749 	free_rsp_buf(resp_buftype, rsp_iov.iov_base);
3750 	return rc;
3751 }
3752 
3753 
3754 
3755 /*
3756  * This is a no-op for now. We're not really interested in the reply, but
3757  * rather in the fact that the server sent one and that server->lstrp
3758  * gets updated.
3759  *
3760  * FIXME: maybe we should consider checking that the reply matches request?
3761  */
3762 static void
smb2_echo_callback(struct mid_q_entry * mid)3763 smb2_echo_callback(struct mid_q_entry *mid)
3764 {
3765 	struct TCP_Server_Info *server = mid->callback_data;
3766 	struct smb2_echo_rsp *rsp = (struct smb2_echo_rsp *)mid->resp_buf;
3767 	struct cifs_credits credits = { .value = 0, .instance = 0 };
3768 
3769 	if (mid->mid_state == MID_RESPONSE_RECEIVED
3770 	    || mid->mid_state == MID_RESPONSE_MALFORMED) {
3771 		credits.value = le16_to_cpu(rsp->hdr.CreditRequest);
3772 		credits.instance = server->reconnect_instance;
3773 	}
3774 
3775 	DeleteMidQEntry(mid);
3776 	add_credits(server, &credits, CIFS_ECHO_OP);
3777 }
3778 
smb2_reconnect_server(struct work_struct * work)3779 void smb2_reconnect_server(struct work_struct *work)
3780 {
3781 	struct TCP_Server_Info *server = container_of(work,
3782 					struct TCP_Server_Info, reconnect.work);
3783 	struct TCP_Server_Info *pserver;
3784 	struct cifs_ses *ses, *ses2;
3785 	struct cifs_tcon *tcon, *tcon2;
3786 	struct list_head tmp_list, tmp_ses_list;
3787 	bool tcon_exist = false, ses_exist = false;
3788 	bool tcon_selected = false;
3789 	int rc;
3790 	bool resched = false;
3791 
3792 	/* If server is a channel, select the primary channel */
3793 	pserver = CIFS_SERVER_IS_CHAN(server) ? server->primary_server : server;
3794 
3795 	/* Prevent simultaneous reconnects that can corrupt tcon->rlist list */
3796 	mutex_lock(&pserver->reconnect_mutex);
3797 
3798 	INIT_LIST_HEAD(&tmp_list);
3799 	INIT_LIST_HEAD(&tmp_ses_list);
3800 	cifs_dbg(FYI, "Reconnecting tcons and channels\n");
3801 
3802 	spin_lock(&cifs_tcp_ses_lock);
3803 	list_for_each_entry(ses, &pserver->smb_ses_list, smb_ses_list) {
3804 
3805 		tcon_selected = false;
3806 
3807 		list_for_each_entry(tcon, &ses->tcon_list, tcon_list) {
3808 			if (tcon->need_reconnect || tcon->need_reopen_files) {
3809 				tcon->tc_count++;
3810 				list_add_tail(&tcon->rlist, &tmp_list);
3811 				tcon_selected = tcon_exist = true;
3812 			}
3813 		}
3814 		/*
3815 		 * IPC has the same lifetime as its session and uses its
3816 		 * refcount.
3817 		 */
3818 		if (ses->tcon_ipc && ses->tcon_ipc->need_reconnect) {
3819 			list_add_tail(&ses->tcon_ipc->rlist, &tmp_list);
3820 			tcon_selected = tcon_exist = true;
3821 			ses->ses_count++;
3822 		}
3823 		/*
3824 		 * handle the case where channel needs to reconnect
3825 		 * binding session, but tcon is healthy (some other channel
3826 		 * is active)
3827 		 */
3828 		spin_lock(&ses->chan_lock);
3829 		if (!tcon_selected && cifs_chan_needs_reconnect(ses, server)) {
3830 			list_add_tail(&ses->rlist, &tmp_ses_list);
3831 			ses_exist = true;
3832 			ses->ses_count++;
3833 		}
3834 		spin_unlock(&ses->chan_lock);
3835 	}
3836 	/*
3837 	 * Get the reference to server struct to be sure that the last call of
3838 	 * cifs_put_tcon() in the loop below won't release the server pointer.
3839 	 */
3840 	if (tcon_exist || ses_exist)
3841 		server->srv_count++;
3842 
3843 	spin_unlock(&cifs_tcp_ses_lock);
3844 
3845 	list_for_each_entry_safe(tcon, tcon2, &tmp_list, rlist) {
3846 		rc = smb2_reconnect(SMB2_INTERNAL_CMD, tcon, server);
3847 		if (!rc)
3848 			cifs_reopen_persistent_handles(tcon);
3849 		else
3850 			resched = true;
3851 		list_del_init(&tcon->rlist);
3852 		if (tcon->ipc)
3853 			cifs_put_smb_ses(tcon->ses);
3854 		else
3855 			cifs_put_tcon(tcon);
3856 	}
3857 
3858 	if (!ses_exist)
3859 		goto done;
3860 
3861 	/* allocate a dummy tcon struct used for reconnect */
3862 	tcon = kzalloc(sizeof(struct cifs_tcon), GFP_KERNEL);
3863 	if (!tcon) {
3864 		resched = true;
3865 		list_for_each_entry_safe(ses, ses2, &tmp_ses_list, rlist) {
3866 			list_del_init(&ses->rlist);
3867 			cifs_put_smb_ses(ses);
3868 		}
3869 		goto done;
3870 	}
3871 
3872 	tcon->status = TID_GOOD;
3873 	tcon->retry = false;
3874 	tcon->need_reconnect = false;
3875 
3876 	/* now reconnect sessions for necessary channels */
3877 	list_for_each_entry_safe(ses, ses2, &tmp_ses_list, rlist) {
3878 		tcon->ses = ses;
3879 		rc = smb2_reconnect(SMB2_INTERNAL_CMD, tcon, server);
3880 		if (rc)
3881 			resched = true;
3882 		list_del_init(&ses->rlist);
3883 		cifs_put_smb_ses(ses);
3884 	}
3885 	kfree(tcon);
3886 
3887 done:
3888 	cifs_dbg(FYI, "Reconnecting tcons and channels finished\n");
3889 	if (resched)
3890 		queue_delayed_work(cifsiod_wq, &server->reconnect, 2 * HZ);
3891 	mutex_unlock(&pserver->reconnect_mutex);
3892 
3893 	/* now we can safely release srv struct */
3894 	if (tcon_exist || ses_exist)
3895 		cifs_put_tcp_session(server, 1);
3896 }
3897 
3898 int
SMB2_echo(struct TCP_Server_Info * server)3899 SMB2_echo(struct TCP_Server_Info *server)
3900 {
3901 	struct smb2_echo_req *req;
3902 	int rc = 0;
3903 	struct kvec iov[1];
3904 	struct smb_rqst rqst = { .rq_iov = iov,
3905 				 .rq_nvec = 1 };
3906 	unsigned int total_len;
3907 
3908 	cifs_dbg(FYI, "In echo request for conn_id %lld\n", server->conn_id);
3909 
3910 	spin_lock(&cifs_tcp_ses_lock);
3911 	if (server->ops->need_neg &&
3912 	    server->ops->need_neg(server)) {
3913 		spin_unlock(&cifs_tcp_ses_lock);
3914 		/* No need to send echo on newly established connections */
3915 		mod_delayed_work(cifsiod_wq, &server->reconnect, 0);
3916 		return rc;
3917 	}
3918 	spin_unlock(&cifs_tcp_ses_lock);
3919 
3920 	rc = smb2_plain_req_init(SMB2_ECHO, NULL, server,
3921 				 (void **)&req, &total_len);
3922 	if (rc)
3923 		return rc;
3924 
3925 	req->hdr.CreditRequest = cpu_to_le16(1);
3926 
3927 	iov[0].iov_len = total_len;
3928 	iov[0].iov_base = (char *)req;
3929 
3930 	rc = cifs_call_async(server, &rqst, NULL, smb2_echo_callback, NULL,
3931 			     server, CIFS_ECHO_OP, NULL);
3932 	if (rc)
3933 		cifs_dbg(FYI, "Echo request failed: %d\n", rc);
3934 
3935 	cifs_small_buf_release(req);
3936 	return rc;
3937 }
3938 
3939 void
SMB2_flush_free(struct smb_rqst * rqst)3940 SMB2_flush_free(struct smb_rqst *rqst)
3941 {
3942 	if (rqst && rqst->rq_iov)
3943 		cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
3944 }
3945 
3946 int
SMB2_flush_init(const unsigned int xid,struct smb_rqst * rqst,struct cifs_tcon * tcon,struct TCP_Server_Info * server,u64 persistent_fid,u64 volatile_fid)3947 SMB2_flush_init(const unsigned int xid, struct smb_rqst *rqst,
3948 		struct cifs_tcon *tcon, struct TCP_Server_Info *server,
3949 		u64 persistent_fid, u64 volatile_fid)
3950 {
3951 	struct smb2_flush_req *req;
3952 	struct kvec *iov = rqst->rq_iov;
3953 	unsigned int total_len;
3954 	int rc;
3955 
3956 	rc = smb2_plain_req_init(SMB2_FLUSH, tcon, server,
3957 				 (void **) &req, &total_len);
3958 	if (rc)
3959 		return rc;
3960 
3961 	req->PersistentFileId = persistent_fid;
3962 	req->VolatileFileId = volatile_fid;
3963 
3964 	iov[0].iov_base = (char *)req;
3965 	iov[0].iov_len = total_len;
3966 
3967 	return 0;
3968 }
3969 
3970 int
SMB2_flush(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid)3971 SMB2_flush(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
3972 	   u64 volatile_fid)
3973 {
3974 	struct cifs_ses *ses = tcon->ses;
3975 	struct smb_rqst rqst;
3976 	struct kvec iov[1];
3977 	struct kvec rsp_iov = {NULL, 0};
3978 	struct TCP_Server_Info *server = cifs_pick_channel(ses);
3979 	int resp_buftype = CIFS_NO_BUFFER;
3980 	int flags = 0;
3981 	int rc = 0;
3982 
3983 	cifs_dbg(FYI, "flush\n");
3984 	if (!ses || !(ses->server))
3985 		return -EIO;
3986 
3987 	if (smb3_encryption_required(tcon))
3988 		flags |= CIFS_TRANSFORM_REQ;
3989 
3990 	memset(&rqst, 0, sizeof(struct smb_rqst));
3991 	memset(&iov, 0, sizeof(iov));
3992 	rqst.rq_iov = iov;
3993 	rqst.rq_nvec = 1;
3994 
3995 	rc = SMB2_flush_init(xid, &rqst, tcon, server,
3996 			     persistent_fid, volatile_fid);
3997 	if (rc)
3998 		goto flush_exit;
3999 
4000 	trace_smb3_flush_enter(xid, persistent_fid, tcon->tid, ses->Suid);
4001 	rc = cifs_send_recv(xid, ses, server,
4002 			    &rqst, &resp_buftype, flags, &rsp_iov);
4003 
4004 	if (rc != 0) {
4005 		cifs_stats_fail_inc(tcon, SMB2_FLUSH_HE);
4006 		trace_smb3_flush_err(xid, persistent_fid, tcon->tid, ses->Suid,
4007 				     rc);
4008 	} else
4009 		trace_smb3_flush_done(xid, persistent_fid, tcon->tid,
4010 				      ses->Suid);
4011 
4012  flush_exit:
4013 	SMB2_flush_free(&rqst);
4014 	free_rsp_buf(resp_buftype, rsp_iov.iov_base);
4015 	return rc;
4016 }
4017 
4018 /*
4019  * To form a chain of read requests, any read requests after the first should
4020  * have the end_of_chain boolean set to true.
4021  */
4022 static int
smb2_new_read_req(void ** buf,unsigned int * total_len,struct cifs_io_parms * io_parms,struct cifs_readdata * rdata,unsigned int remaining_bytes,int request_type)4023 smb2_new_read_req(void **buf, unsigned int *total_len,
4024 	struct cifs_io_parms *io_parms, struct cifs_readdata *rdata,
4025 	unsigned int remaining_bytes, int request_type)
4026 {
4027 	int rc = -EACCES;
4028 	struct smb2_read_req *req = NULL;
4029 	struct smb2_hdr *shdr;
4030 	struct TCP_Server_Info *server = io_parms->server;
4031 
4032 	rc = smb2_plain_req_init(SMB2_READ, io_parms->tcon, server,
4033 				 (void **) &req, total_len);
4034 	if (rc)
4035 		return rc;
4036 
4037 	if (server == NULL)
4038 		return -ECONNABORTED;
4039 
4040 	shdr = &req->hdr;
4041 	shdr->Id.SyncId.ProcessId = cpu_to_le32(io_parms->pid);
4042 
4043 	req->PersistentFileId = io_parms->persistent_fid;
4044 	req->VolatileFileId = io_parms->volatile_fid;
4045 	req->ReadChannelInfoOffset = 0; /* reserved */
4046 	req->ReadChannelInfoLength = 0; /* reserved */
4047 	req->Channel = 0; /* reserved */
4048 	req->MinimumCount = 0;
4049 	req->Length = cpu_to_le32(io_parms->length);
4050 	req->Offset = cpu_to_le64(io_parms->offset);
4051 
4052 	trace_smb3_read_enter(0 /* xid */,
4053 			io_parms->persistent_fid,
4054 			io_parms->tcon->tid, io_parms->tcon->ses->Suid,
4055 			io_parms->offset, io_parms->length);
4056 #ifdef CONFIG_CIFS_SMB_DIRECT
4057 	/*
4058 	 * If we want to do a RDMA write, fill in and append
4059 	 * smbd_buffer_descriptor_v1 to the end of read request
4060 	 */
4061 	if (server->rdma && rdata && !server->sign &&
4062 		rdata->bytes >= server->smbd_conn->rdma_readwrite_threshold) {
4063 
4064 		struct smbd_buffer_descriptor_v1 *v1;
4065 		bool need_invalidate = server->dialect == SMB30_PROT_ID;
4066 
4067 		rdata->mr = smbd_register_mr(
4068 				server->smbd_conn, rdata->pages,
4069 				rdata->nr_pages, rdata->page_offset,
4070 				rdata->tailsz, true, need_invalidate);
4071 		if (!rdata->mr)
4072 			return -EAGAIN;
4073 
4074 		req->Channel = SMB2_CHANNEL_RDMA_V1_INVALIDATE;
4075 		if (need_invalidate)
4076 			req->Channel = SMB2_CHANNEL_RDMA_V1;
4077 		req->ReadChannelInfoOffset =
4078 			cpu_to_le16(offsetof(struct smb2_read_req, Buffer));
4079 		req->ReadChannelInfoLength =
4080 			cpu_to_le16(sizeof(struct smbd_buffer_descriptor_v1));
4081 		v1 = (struct smbd_buffer_descriptor_v1 *) &req->Buffer[0];
4082 		v1->offset = cpu_to_le64(rdata->mr->mr->iova);
4083 		v1->token = cpu_to_le32(rdata->mr->mr->rkey);
4084 		v1->length = cpu_to_le32(rdata->mr->mr->length);
4085 
4086 		*total_len += sizeof(*v1) - 1;
4087 	}
4088 #endif
4089 	if (request_type & CHAINED_REQUEST) {
4090 		if (!(request_type & END_OF_CHAIN)) {
4091 			/* next 8-byte aligned request */
4092 			*total_len = DIV_ROUND_UP(*total_len, 8) * 8;
4093 			shdr->NextCommand = cpu_to_le32(*total_len);
4094 		} else /* END_OF_CHAIN */
4095 			shdr->NextCommand = 0;
4096 		if (request_type & RELATED_REQUEST) {
4097 			shdr->Flags |= SMB2_FLAGS_RELATED_OPERATIONS;
4098 			/*
4099 			 * Related requests use info from previous read request
4100 			 * in chain.
4101 			 */
4102 			shdr->SessionId = cpu_to_le64(0xFFFFFFFFFFFFFFFF);
4103 			shdr->Id.SyncId.TreeId = cpu_to_le32(0xFFFFFFFF);
4104 			req->PersistentFileId = (u64)-1;
4105 			req->VolatileFileId = (u64)-1;
4106 		}
4107 	}
4108 	if (remaining_bytes > io_parms->length)
4109 		req->RemainingBytes = cpu_to_le32(remaining_bytes);
4110 	else
4111 		req->RemainingBytes = 0;
4112 
4113 	*buf = req;
4114 	return rc;
4115 }
4116 
4117 static void
smb2_readv_callback(struct mid_q_entry * mid)4118 smb2_readv_callback(struct mid_q_entry *mid)
4119 {
4120 	struct cifs_readdata *rdata = mid->callback_data;
4121 	struct cifs_tcon *tcon = tlink_tcon(rdata->cfile->tlink);
4122 	struct TCP_Server_Info *server = rdata->server;
4123 	struct smb2_hdr *shdr =
4124 				(struct smb2_hdr *)rdata->iov[0].iov_base;
4125 	struct cifs_credits credits = { .value = 0, .instance = 0 };
4126 	struct smb_rqst rqst = { .rq_iov = &rdata->iov[1],
4127 				 .rq_nvec = 1,
4128 				 .rq_pages = rdata->pages,
4129 				 .rq_offset = rdata->page_offset,
4130 				 .rq_npages = rdata->nr_pages,
4131 				 .rq_pagesz = rdata->pagesz,
4132 				 .rq_tailsz = rdata->tailsz };
4133 
4134 	WARN_ONCE(rdata->server != mid->server,
4135 		  "rdata server %p != mid server %p",
4136 		  rdata->server, mid->server);
4137 
4138 	cifs_dbg(FYI, "%s: mid=%llu state=%d result=%d bytes=%u\n",
4139 		 __func__, mid->mid, mid->mid_state, rdata->result,
4140 		 rdata->bytes);
4141 
4142 	switch (mid->mid_state) {
4143 	case MID_RESPONSE_RECEIVED:
4144 		credits.value = le16_to_cpu(shdr->CreditRequest);
4145 		credits.instance = server->reconnect_instance;
4146 		/* result already set, check signature */
4147 		if (server->sign && !mid->decrypted) {
4148 			int rc;
4149 
4150 			rc = smb2_verify_signature(&rqst, server);
4151 			if (rc)
4152 				cifs_tcon_dbg(VFS, "SMB signature verification returned error = %d\n",
4153 					 rc);
4154 		}
4155 		/* FIXME: should this be counted toward the initiating task? */
4156 		task_io_account_read(rdata->got_bytes);
4157 		cifs_stats_bytes_read(tcon, rdata->got_bytes);
4158 		break;
4159 	case MID_REQUEST_SUBMITTED:
4160 	case MID_RETRY_NEEDED:
4161 		rdata->result = -EAGAIN;
4162 		if (server->sign && rdata->got_bytes)
4163 			/* reset bytes number since we can not check a sign */
4164 			rdata->got_bytes = 0;
4165 		/* FIXME: should this be counted toward the initiating task? */
4166 		task_io_account_read(rdata->got_bytes);
4167 		cifs_stats_bytes_read(tcon, rdata->got_bytes);
4168 		break;
4169 	case MID_RESPONSE_MALFORMED:
4170 		credits.value = le16_to_cpu(shdr->CreditRequest);
4171 		credits.instance = server->reconnect_instance;
4172 		fallthrough;
4173 	default:
4174 		rdata->result = -EIO;
4175 	}
4176 #ifdef CONFIG_CIFS_SMB_DIRECT
4177 	/*
4178 	 * If this rdata has a memmory registered, the MR can be freed
4179 	 * MR needs to be freed as soon as I/O finishes to prevent deadlock
4180 	 * because they have limited number and are used for future I/Os
4181 	 */
4182 	if (rdata->mr) {
4183 		smbd_deregister_mr(rdata->mr);
4184 		rdata->mr = NULL;
4185 	}
4186 #endif
4187 	if (rdata->result && rdata->result != -ENODATA) {
4188 		cifs_stats_fail_inc(tcon, SMB2_READ_HE);
4189 		trace_smb3_read_err(0 /* xid */,
4190 				    rdata->cfile->fid.persistent_fid,
4191 				    tcon->tid, tcon->ses->Suid, rdata->offset,
4192 				    rdata->bytes, rdata->result);
4193 	} else
4194 		trace_smb3_read_done(0 /* xid */,
4195 				     rdata->cfile->fid.persistent_fid,
4196 				     tcon->tid, tcon->ses->Suid,
4197 				     rdata->offset, rdata->got_bytes);
4198 
4199 	queue_work(cifsiod_wq, &rdata->work);
4200 	DeleteMidQEntry(mid);
4201 	add_credits(server, &credits, 0);
4202 }
4203 
4204 /* smb2_async_readv - send an async read, and set up mid to handle result */
4205 int
smb2_async_readv(struct cifs_readdata * rdata)4206 smb2_async_readv(struct cifs_readdata *rdata)
4207 {
4208 	int rc, flags = 0;
4209 	char *buf;
4210 	struct smb2_hdr *shdr;
4211 	struct cifs_io_parms io_parms;
4212 	struct smb_rqst rqst = { .rq_iov = rdata->iov,
4213 				 .rq_nvec = 1 };
4214 	struct TCP_Server_Info *server;
4215 	struct cifs_tcon *tcon = tlink_tcon(rdata->cfile->tlink);
4216 	unsigned int total_len;
4217 
4218 	cifs_dbg(FYI, "%s: offset=%llu bytes=%u\n",
4219 		 __func__, rdata->offset, rdata->bytes);
4220 
4221 	if (!rdata->server)
4222 		rdata->server = cifs_pick_channel(tcon->ses);
4223 
4224 	io_parms.tcon = tlink_tcon(rdata->cfile->tlink);
4225 	io_parms.server = server = rdata->server;
4226 	io_parms.offset = rdata->offset;
4227 	io_parms.length = rdata->bytes;
4228 	io_parms.persistent_fid = rdata->cfile->fid.persistent_fid;
4229 	io_parms.volatile_fid = rdata->cfile->fid.volatile_fid;
4230 	io_parms.pid = rdata->pid;
4231 
4232 	rc = smb2_new_read_req(
4233 		(void **) &buf, &total_len, &io_parms, rdata, 0, 0);
4234 	if (rc)
4235 		return rc;
4236 
4237 	if (smb3_encryption_required(io_parms.tcon))
4238 		flags |= CIFS_TRANSFORM_REQ;
4239 
4240 	rdata->iov[0].iov_base = buf;
4241 	rdata->iov[0].iov_len = total_len;
4242 
4243 	shdr = (struct smb2_hdr *)buf;
4244 
4245 	if (rdata->credits.value > 0) {
4246 		shdr->CreditCharge = cpu_to_le16(DIV_ROUND_UP(rdata->bytes,
4247 						SMB2_MAX_BUFFER_SIZE));
4248 		shdr->CreditRequest = cpu_to_le16(le16_to_cpu(shdr->CreditCharge) + 8);
4249 
4250 		rc = adjust_credits(server, &rdata->credits, rdata->bytes);
4251 		if (rc)
4252 			goto async_readv_out;
4253 
4254 		flags |= CIFS_HAS_CREDITS;
4255 	}
4256 
4257 	kref_get(&rdata->refcount);
4258 	rc = cifs_call_async(server, &rqst,
4259 			     cifs_readv_receive, smb2_readv_callback,
4260 			     smb3_handle_read_data, rdata, flags,
4261 			     &rdata->credits);
4262 	if (rc) {
4263 		kref_put(&rdata->refcount, cifs_readdata_release);
4264 		cifs_stats_fail_inc(io_parms.tcon, SMB2_READ_HE);
4265 		trace_smb3_read_err(0 /* xid */, io_parms.persistent_fid,
4266 				    io_parms.tcon->tid,
4267 				    io_parms.tcon->ses->Suid,
4268 				    io_parms.offset, io_parms.length, rc);
4269 	}
4270 
4271 async_readv_out:
4272 	cifs_small_buf_release(buf);
4273 	return rc;
4274 }
4275 
4276 int
SMB2_read(const unsigned int xid,struct cifs_io_parms * io_parms,unsigned int * nbytes,char ** buf,int * buf_type)4277 SMB2_read(const unsigned int xid, struct cifs_io_parms *io_parms,
4278 	  unsigned int *nbytes, char **buf, int *buf_type)
4279 {
4280 	struct smb_rqst rqst;
4281 	int resp_buftype, rc;
4282 	struct smb2_read_req *req = NULL;
4283 	struct smb2_read_rsp *rsp = NULL;
4284 	struct kvec iov[1];
4285 	struct kvec rsp_iov;
4286 	unsigned int total_len;
4287 	int flags = CIFS_LOG_ERROR;
4288 	struct cifs_ses *ses = io_parms->tcon->ses;
4289 
4290 	if (!io_parms->server)
4291 		io_parms->server = cifs_pick_channel(io_parms->tcon->ses);
4292 
4293 	*nbytes = 0;
4294 	rc = smb2_new_read_req((void **)&req, &total_len, io_parms, NULL, 0, 0);
4295 	if (rc)
4296 		return rc;
4297 
4298 	if (smb3_encryption_required(io_parms->tcon))
4299 		flags |= CIFS_TRANSFORM_REQ;
4300 
4301 	iov[0].iov_base = (char *)req;
4302 	iov[0].iov_len = total_len;
4303 
4304 	memset(&rqst, 0, sizeof(struct smb_rqst));
4305 	rqst.rq_iov = iov;
4306 	rqst.rq_nvec = 1;
4307 
4308 	rc = cifs_send_recv(xid, ses, io_parms->server,
4309 			    &rqst, &resp_buftype, flags, &rsp_iov);
4310 	rsp = (struct smb2_read_rsp *)rsp_iov.iov_base;
4311 
4312 	if (rc) {
4313 		if (rc != -ENODATA) {
4314 			cifs_stats_fail_inc(io_parms->tcon, SMB2_READ_HE);
4315 			cifs_dbg(VFS, "Send error in read = %d\n", rc);
4316 			trace_smb3_read_err(xid,
4317 					    req->PersistentFileId,
4318 					    io_parms->tcon->tid, ses->Suid,
4319 					    io_parms->offset, io_parms->length,
4320 					    rc);
4321 		} else
4322 			trace_smb3_read_done(xid, req->PersistentFileId, io_parms->tcon->tid,
4323 					     ses->Suid, io_parms->offset, 0);
4324 		free_rsp_buf(resp_buftype, rsp_iov.iov_base);
4325 		cifs_small_buf_release(req);
4326 		return rc == -ENODATA ? 0 : rc;
4327 	} else
4328 		trace_smb3_read_done(xid,
4329 				    req->PersistentFileId,
4330 				    io_parms->tcon->tid, ses->Suid,
4331 				    io_parms->offset, io_parms->length);
4332 
4333 	cifs_small_buf_release(req);
4334 
4335 	*nbytes = le32_to_cpu(rsp->DataLength);
4336 	if ((*nbytes > CIFS_MAX_MSGSIZE) ||
4337 	    (*nbytes > io_parms->length)) {
4338 		cifs_dbg(FYI, "bad length %d for count %d\n",
4339 			 *nbytes, io_parms->length);
4340 		rc = -EIO;
4341 		*nbytes = 0;
4342 	}
4343 
4344 	if (*buf) {
4345 		memcpy(*buf, (char *)rsp + rsp->DataOffset, *nbytes);
4346 		free_rsp_buf(resp_buftype, rsp_iov.iov_base);
4347 	} else if (resp_buftype != CIFS_NO_BUFFER) {
4348 		*buf = rsp_iov.iov_base;
4349 		if (resp_buftype == CIFS_SMALL_BUFFER)
4350 			*buf_type = CIFS_SMALL_BUFFER;
4351 		else if (resp_buftype == CIFS_LARGE_BUFFER)
4352 			*buf_type = CIFS_LARGE_BUFFER;
4353 	}
4354 	return rc;
4355 }
4356 
4357 /*
4358  * Check the mid_state and signature on received buffer (if any), and queue the
4359  * workqueue completion task.
4360  */
4361 static void
smb2_writev_callback(struct mid_q_entry * mid)4362 smb2_writev_callback(struct mid_q_entry *mid)
4363 {
4364 	struct cifs_writedata *wdata = mid->callback_data;
4365 	struct cifs_tcon *tcon = tlink_tcon(wdata->cfile->tlink);
4366 	struct TCP_Server_Info *server = wdata->server;
4367 	unsigned int written;
4368 	struct smb2_write_rsp *rsp = (struct smb2_write_rsp *)mid->resp_buf;
4369 	struct cifs_credits credits = { .value = 0, .instance = 0 };
4370 
4371 	WARN_ONCE(wdata->server != mid->server,
4372 		  "wdata server %p != mid server %p",
4373 		  wdata->server, mid->server);
4374 
4375 	switch (mid->mid_state) {
4376 	case MID_RESPONSE_RECEIVED:
4377 		credits.value = le16_to_cpu(rsp->hdr.CreditRequest);
4378 		credits.instance = server->reconnect_instance;
4379 		wdata->result = smb2_check_receive(mid, server, 0);
4380 		if (wdata->result != 0)
4381 			break;
4382 
4383 		written = le32_to_cpu(rsp->DataLength);
4384 		/*
4385 		 * Mask off high 16 bits when bytes written as returned
4386 		 * by the server is greater than bytes requested by the
4387 		 * client. OS/2 servers are known to set incorrect
4388 		 * CountHigh values.
4389 		 */
4390 		if (written > wdata->bytes)
4391 			written &= 0xFFFF;
4392 
4393 		if (written < wdata->bytes)
4394 			wdata->result = -ENOSPC;
4395 		else
4396 			wdata->bytes = written;
4397 		break;
4398 	case MID_REQUEST_SUBMITTED:
4399 	case MID_RETRY_NEEDED:
4400 		wdata->result = -EAGAIN;
4401 		break;
4402 	case MID_RESPONSE_MALFORMED:
4403 		credits.value = le16_to_cpu(rsp->hdr.CreditRequest);
4404 		credits.instance = server->reconnect_instance;
4405 		fallthrough;
4406 	default:
4407 		wdata->result = -EIO;
4408 		break;
4409 	}
4410 #ifdef CONFIG_CIFS_SMB_DIRECT
4411 	/*
4412 	 * If this wdata has a memory registered, the MR can be freed
4413 	 * The number of MRs available is limited, it's important to recover
4414 	 * used MR as soon as I/O is finished. Hold MR longer in the later
4415 	 * I/O process can possibly result in I/O deadlock due to lack of MR
4416 	 * to send request on I/O retry
4417 	 */
4418 	if (wdata->mr) {
4419 		smbd_deregister_mr(wdata->mr);
4420 		wdata->mr = NULL;
4421 	}
4422 #endif
4423 	if (wdata->result) {
4424 		cifs_stats_fail_inc(tcon, SMB2_WRITE_HE);
4425 		trace_smb3_write_err(0 /* no xid */,
4426 				     wdata->cfile->fid.persistent_fid,
4427 				     tcon->tid, tcon->ses->Suid, wdata->offset,
4428 				     wdata->bytes, wdata->result);
4429 		if (wdata->result == -ENOSPC)
4430 			pr_warn_once("Out of space writing to %s\n",
4431 				     tcon->treeName);
4432 	} else
4433 		trace_smb3_write_done(0 /* no xid */,
4434 				      wdata->cfile->fid.persistent_fid,
4435 				      tcon->tid, tcon->ses->Suid,
4436 				      wdata->offset, wdata->bytes);
4437 
4438 	queue_work(cifsiod_wq, &wdata->work);
4439 	DeleteMidQEntry(mid);
4440 	add_credits(server, &credits, 0);
4441 }
4442 
4443 /* smb2_async_writev - send an async write, and set up mid to handle result */
4444 int
smb2_async_writev(struct cifs_writedata * wdata,void (* release)(struct kref * kref))4445 smb2_async_writev(struct cifs_writedata *wdata,
4446 		  void (*release)(struct kref *kref))
4447 {
4448 	int rc = -EACCES, flags = 0;
4449 	struct smb2_write_req *req = NULL;
4450 	struct smb2_hdr *shdr;
4451 	struct cifs_tcon *tcon = tlink_tcon(wdata->cfile->tlink);
4452 	struct TCP_Server_Info *server = wdata->server;
4453 	struct kvec iov[1];
4454 	struct smb_rqst rqst = { };
4455 	unsigned int total_len;
4456 
4457 	if (!wdata->server)
4458 		server = wdata->server = cifs_pick_channel(tcon->ses);
4459 
4460 	rc = smb2_plain_req_init(SMB2_WRITE, tcon, server,
4461 				 (void **) &req, &total_len);
4462 	if (rc)
4463 		return rc;
4464 
4465 	if (smb3_encryption_required(tcon))
4466 		flags |= CIFS_TRANSFORM_REQ;
4467 
4468 	shdr = (struct smb2_hdr *)req;
4469 	shdr->Id.SyncId.ProcessId = cpu_to_le32(wdata->cfile->pid);
4470 
4471 	req->PersistentFileId = wdata->cfile->fid.persistent_fid;
4472 	req->VolatileFileId = wdata->cfile->fid.volatile_fid;
4473 	req->WriteChannelInfoOffset = 0;
4474 	req->WriteChannelInfoLength = 0;
4475 	req->Channel = 0;
4476 	req->Offset = cpu_to_le64(wdata->offset);
4477 	req->DataOffset = cpu_to_le16(
4478 				offsetof(struct smb2_write_req, Buffer));
4479 	req->RemainingBytes = 0;
4480 
4481 	trace_smb3_write_enter(0 /* xid */, wdata->cfile->fid.persistent_fid,
4482 		tcon->tid, tcon->ses->Suid, wdata->offset, wdata->bytes);
4483 #ifdef CONFIG_CIFS_SMB_DIRECT
4484 	/*
4485 	 * If we want to do a server RDMA read, fill in and append
4486 	 * smbd_buffer_descriptor_v1 to the end of write request
4487 	 */
4488 	if (server->rdma && !server->sign && wdata->bytes >=
4489 		server->smbd_conn->rdma_readwrite_threshold) {
4490 
4491 		struct smbd_buffer_descriptor_v1 *v1;
4492 		bool need_invalidate = server->dialect == SMB30_PROT_ID;
4493 
4494 		wdata->mr = smbd_register_mr(
4495 				server->smbd_conn, wdata->pages,
4496 				wdata->nr_pages, wdata->page_offset,
4497 				wdata->tailsz, false, need_invalidate);
4498 		if (!wdata->mr) {
4499 			rc = -EAGAIN;
4500 			goto async_writev_out;
4501 		}
4502 		req->Length = 0;
4503 		req->DataOffset = 0;
4504 		if (wdata->nr_pages > 1)
4505 			req->RemainingBytes =
4506 				cpu_to_le32(
4507 					(wdata->nr_pages - 1) * wdata->pagesz -
4508 					wdata->page_offset + wdata->tailsz
4509 				);
4510 		else
4511 			req->RemainingBytes = cpu_to_le32(wdata->tailsz);
4512 		req->Channel = SMB2_CHANNEL_RDMA_V1_INVALIDATE;
4513 		if (need_invalidate)
4514 			req->Channel = SMB2_CHANNEL_RDMA_V1;
4515 		req->WriteChannelInfoOffset =
4516 			cpu_to_le16(offsetof(struct smb2_write_req, Buffer));
4517 		req->WriteChannelInfoLength =
4518 			cpu_to_le16(sizeof(struct smbd_buffer_descriptor_v1));
4519 		v1 = (struct smbd_buffer_descriptor_v1 *) &req->Buffer[0];
4520 		v1->offset = cpu_to_le64(wdata->mr->mr->iova);
4521 		v1->token = cpu_to_le32(wdata->mr->mr->rkey);
4522 		v1->length = cpu_to_le32(wdata->mr->mr->length);
4523 	}
4524 #endif
4525 	iov[0].iov_len = total_len - 1;
4526 	iov[0].iov_base = (char *)req;
4527 
4528 	rqst.rq_iov = iov;
4529 	rqst.rq_nvec = 1;
4530 	rqst.rq_pages = wdata->pages;
4531 	rqst.rq_offset = wdata->page_offset;
4532 	rqst.rq_npages = wdata->nr_pages;
4533 	rqst.rq_pagesz = wdata->pagesz;
4534 	rqst.rq_tailsz = wdata->tailsz;
4535 #ifdef CONFIG_CIFS_SMB_DIRECT
4536 	if (wdata->mr) {
4537 		iov[0].iov_len += sizeof(struct smbd_buffer_descriptor_v1);
4538 		rqst.rq_npages = 0;
4539 	}
4540 #endif
4541 	cifs_dbg(FYI, "async write at %llu %u bytes\n",
4542 		 wdata->offset, wdata->bytes);
4543 
4544 #ifdef CONFIG_CIFS_SMB_DIRECT
4545 	/* For RDMA read, I/O size is in RemainingBytes not in Length */
4546 	if (!wdata->mr)
4547 		req->Length = cpu_to_le32(wdata->bytes);
4548 #else
4549 	req->Length = cpu_to_le32(wdata->bytes);
4550 #endif
4551 
4552 	if (wdata->credits.value > 0) {
4553 		shdr->CreditCharge = cpu_to_le16(DIV_ROUND_UP(wdata->bytes,
4554 						    SMB2_MAX_BUFFER_SIZE));
4555 		shdr->CreditRequest = cpu_to_le16(le16_to_cpu(shdr->CreditCharge) + 8);
4556 
4557 		rc = adjust_credits(server, &wdata->credits, wdata->bytes);
4558 		if (rc)
4559 			goto async_writev_out;
4560 
4561 		flags |= CIFS_HAS_CREDITS;
4562 	}
4563 
4564 	kref_get(&wdata->refcount);
4565 	rc = cifs_call_async(server, &rqst, NULL, smb2_writev_callback, NULL,
4566 			     wdata, flags, &wdata->credits);
4567 
4568 	if (rc) {
4569 		trace_smb3_write_err(0 /* no xid */,
4570 				     req->PersistentFileId,
4571 				     tcon->tid, tcon->ses->Suid, wdata->offset,
4572 				     wdata->bytes, rc);
4573 		kref_put(&wdata->refcount, release);
4574 		cifs_stats_fail_inc(tcon, SMB2_WRITE_HE);
4575 	}
4576 
4577 async_writev_out:
4578 	cifs_small_buf_release(req);
4579 	return rc;
4580 }
4581 
4582 /*
4583  * SMB2_write function gets iov pointer to kvec array with n_vec as a length.
4584  * The length field from io_parms must be at least 1 and indicates a number of
4585  * elements with data to write that begins with position 1 in iov array. All
4586  * data length is specified by count.
4587  */
4588 int
SMB2_write(const unsigned int xid,struct cifs_io_parms * io_parms,unsigned int * nbytes,struct kvec * iov,int n_vec)4589 SMB2_write(const unsigned int xid, struct cifs_io_parms *io_parms,
4590 	   unsigned int *nbytes, struct kvec *iov, int n_vec)
4591 {
4592 	struct smb_rqst rqst;
4593 	int rc = 0;
4594 	struct smb2_write_req *req = NULL;
4595 	struct smb2_write_rsp *rsp = NULL;
4596 	int resp_buftype;
4597 	struct kvec rsp_iov;
4598 	int flags = 0;
4599 	unsigned int total_len;
4600 	struct TCP_Server_Info *server;
4601 
4602 	*nbytes = 0;
4603 
4604 	if (n_vec < 1)
4605 		return rc;
4606 
4607 	if (!io_parms->server)
4608 		io_parms->server = cifs_pick_channel(io_parms->tcon->ses);
4609 	server = io_parms->server;
4610 	if (server == NULL)
4611 		return -ECONNABORTED;
4612 
4613 	rc = smb2_plain_req_init(SMB2_WRITE, io_parms->tcon, server,
4614 				 (void **) &req, &total_len);
4615 	if (rc)
4616 		return rc;
4617 
4618 	if (smb3_encryption_required(io_parms->tcon))
4619 		flags |= CIFS_TRANSFORM_REQ;
4620 
4621 	req->hdr.Id.SyncId.ProcessId = cpu_to_le32(io_parms->pid);
4622 
4623 	req->PersistentFileId = io_parms->persistent_fid;
4624 	req->VolatileFileId = io_parms->volatile_fid;
4625 	req->WriteChannelInfoOffset = 0;
4626 	req->WriteChannelInfoLength = 0;
4627 	req->Channel = 0;
4628 	req->Length = cpu_to_le32(io_parms->length);
4629 	req->Offset = cpu_to_le64(io_parms->offset);
4630 	req->DataOffset = cpu_to_le16(
4631 				offsetof(struct smb2_write_req, Buffer));
4632 	req->RemainingBytes = 0;
4633 
4634 	trace_smb3_write_enter(xid, io_parms->persistent_fid,
4635 		io_parms->tcon->tid, io_parms->tcon->ses->Suid,
4636 		io_parms->offset, io_parms->length);
4637 
4638 	iov[0].iov_base = (char *)req;
4639 	/* 1 for Buffer */
4640 	iov[0].iov_len = total_len - 1;
4641 
4642 	memset(&rqst, 0, sizeof(struct smb_rqst));
4643 	rqst.rq_iov = iov;
4644 	rqst.rq_nvec = n_vec + 1;
4645 
4646 	rc = cifs_send_recv(xid, io_parms->tcon->ses, server,
4647 			    &rqst,
4648 			    &resp_buftype, flags, &rsp_iov);
4649 	rsp = (struct smb2_write_rsp *)rsp_iov.iov_base;
4650 
4651 	if (rc) {
4652 		trace_smb3_write_err(xid,
4653 				     req->PersistentFileId,
4654 				     io_parms->tcon->tid,
4655 				     io_parms->tcon->ses->Suid,
4656 				     io_parms->offset, io_parms->length, rc);
4657 		cifs_stats_fail_inc(io_parms->tcon, SMB2_WRITE_HE);
4658 		cifs_dbg(VFS, "Send error in write = %d\n", rc);
4659 	} else {
4660 		*nbytes = le32_to_cpu(rsp->DataLength);
4661 		trace_smb3_write_done(xid,
4662 				      req->PersistentFileId,
4663 				      io_parms->tcon->tid,
4664 				      io_parms->tcon->ses->Suid,
4665 				      io_parms->offset, *nbytes);
4666 	}
4667 
4668 	cifs_small_buf_release(req);
4669 	free_rsp_buf(resp_buftype, rsp);
4670 	return rc;
4671 }
4672 
posix_info_sid_size(const void * beg,const void * end)4673 int posix_info_sid_size(const void *beg, const void *end)
4674 {
4675 	size_t subauth;
4676 	int total;
4677 
4678 	if (beg + 1 > end)
4679 		return -1;
4680 
4681 	subauth = *(u8 *)(beg+1);
4682 	if (subauth < 1 || subauth > 15)
4683 		return -1;
4684 
4685 	total = 1 + 1 + 6 + 4*subauth;
4686 	if (beg + total > end)
4687 		return -1;
4688 
4689 	return total;
4690 }
4691 
posix_info_parse(const void * beg,const void * end,struct smb2_posix_info_parsed * out)4692 int posix_info_parse(const void *beg, const void *end,
4693 		     struct smb2_posix_info_parsed *out)
4694 
4695 {
4696 	int total_len = 0;
4697 	int owner_len, group_len;
4698 	int name_len;
4699 	const void *owner_sid;
4700 	const void *group_sid;
4701 	const void *name;
4702 
4703 	/* if no end bound given, assume payload to be correct */
4704 	if (!end) {
4705 		const struct smb2_posix_info *p = beg;
4706 
4707 		end = beg + le32_to_cpu(p->NextEntryOffset);
4708 		/* last element will have a 0 offset, pick a sensible bound */
4709 		if (end == beg)
4710 			end += 0xFFFF;
4711 	}
4712 
4713 	/* check base buf */
4714 	if (beg + sizeof(struct smb2_posix_info) > end)
4715 		return -1;
4716 	total_len = sizeof(struct smb2_posix_info);
4717 
4718 	/* check owner sid */
4719 	owner_sid = beg + total_len;
4720 	owner_len = posix_info_sid_size(owner_sid, end);
4721 	if (owner_len < 0)
4722 		return -1;
4723 	total_len += owner_len;
4724 
4725 	/* check group sid */
4726 	group_sid = beg + total_len;
4727 	group_len = posix_info_sid_size(group_sid, end);
4728 	if (group_len < 0)
4729 		return -1;
4730 	total_len += group_len;
4731 
4732 	/* check name len */
4733 	if (beg + total_len + 4 > end)
4734 		return -1;
4735 	name_len = le32_to_cpu(*(__le32 *)(beg + total_len));
4736 	if (name_len < 1 || name_len > 0xFFFF)
4737 		return -1;
4738 	total_len += 4;
4739 
4740 	/* check name */
4741 	name = beg + total_len;
4742 	if (name + name_len > end)
4743 		return -1;
4744 	total_len += name_len;
4745 
4746 	if (out) {
4747 		out->base = beg;
4748 		out->size = total_len;
4749 		out->name_len = name_len;
4750 		out->name = name;
4751 		memcpy(&out->owner, owner_sid, owner_len);
4752 		memcpy(&out->group, group_sid, group_len);
4753 	}
4754 	return total_len;
4755 }
4756 
posix_info_extra_size(const void * beg,const void * end)4757 static int posix_info_extra_size(const void *beg, const void *end)
4758 {
4759 	int len = posix_info_parse(beg, end, NULL);
4760 
4761 	if (len < 0)
4762 		return -1;
4763 	return len - sizeof(struct smb2_posix_info);
4764 }
4765 
4766 static unsigned int
num_entries(int infotype,char * bufstart,char * end_of_buf,char ** lastentry,size_t size)4767 num_entries(int infotype, char *bufstart, char *end_of_buf, char **lastentry,
4768 	    size_t size)
4769 {
4770 	int len;
4771 	unsigned int entrycount = 0;
4772 	unsigned int next_offset = 0;
4773 	char *entryptr;
4774 	FILE_DIRECTORY_INFO *dir_info;
4775 
4776 	if (bufstart == NULL)
4777 		return 0;
4778 
4779 	entryptr = bufstart;
4780 
4781 	while (1) {
4782 		if (entryptr + next_offset < entryptr ||
4783 		    entryptr + next_offset > end_of_buf ||
4784 		    entryptr + next_offset + size > end_of_buf) {
4785 			cifs_dbg(VFS, "malformed search entry would overflow\n");
4786 			break;
4787 		}
4788 
4789 		entryptr = entryptr + next_offset;
4790 		dir_info = (FILE_DIRECTORY_INFO *)entryptr;
4791 
4792 		if (infotype == SMB_FIND_FILE_POSIX_INFO)
4793 			len = posix_info_extra_size(entryptr, end_of_buf);
4794 		else
4795 			len = le32_to_cpu(dir_info->FileNameLength);
4796 
4797 		if (len < 0 ||
4798 		    entryptr + len < entryptr ||
4799 		    entryptr + len > end_of_buf ||
4800 		    entryptr + len + size > end_of_buf) {
4801 			cifs_dbg(VFS, "directory entry name would overflow frame end of buf %p\n",
4802 				 end_of_buf);
4803 			break;
4804 		}
4805 
4806 		*lastentry = entryptr;
4807 		entrycount++;
4808 
4809 		next_offset = le32_to_cpu(dir_info->NextEntryOffset);
4810 		if (!next_offset)
4811 			break;
4812 	}
4813 
4814 	return entrycount;
4815 }
4816 
4817 /*
4818  * Readdir/FindFirst
4819  */
SMB2_query_directory_init(const unsigned int xid,struct cifs_tcon * tcon,struct TCP_Server_Info * server,struct smb_rqst * rqst,u64 persistent_fid,u64 volatile_fid,int index,int info_level)4820 int SMB2_query_directory_init(const unsigned int xid,
4821 			      struct cifs_tcon *tcon,
4822 			      struct TCP_Server_Info *server,
4823 			      struct smb_rqst *rqst,
4824 			      u64 persistent_fid, u64 volatile_fid,
4825 			      int index, int info_level)
4826 {
4827 	struct smb2_query_directory_req *req;
4828 	unsigned char *bufptr;
4829 	__le16 asteriks = cpu_to_le16('*');
4830 	unsigned int output_size = CIFSMaxBufSize -
4831 		MAX_SMB2_CREATE_RESPONSE_SIZE -
4832 		MAX_SMB2_CLOSE_RESPONSE_SIZE;
4833 	unsigned int total_len;
4834 	struct kvec *iov = rqst->rq_iov;
4835 	int len, rc;
4836 
4837 	rc = smb2_plain_req_init(SMB2_QUERY_DIRECTORY, tcon, server,
4838 				 (void **) &req, &total_len);
4839 	if (rc)
4840 		return rc;
4841 
4842 	switch (info_level) {
4843 	case SMB_FIND_FILE_DIRECTORY_INFO:
4844 		req->FileInformationClass = FILE_DIRECTORY_INFORMATION;
4845 		break;
4846 	case SMB_FIND_FILE_ID_FULL_DIR_INFO:
4847 		req->FileInformationClass = FILEID_FULL_DIRECTORY_INFORMATION;
4848 		break;
4849 	case SMB_FIND_FILE_POSIX_INFO:
4850 		req->FileInformationClass = SMB_FIND_FILE_POSIX_INFO;
4851 		break;
4852 	default:
4853 		cifs_tcon_dbg(VFS, "info level %u isn't supported\n",
4854 			info_level);
4855 		return -EINVAL;
4856 	}
4857 
4858 	req->FileIndex = cpu_to_le32(index);
4859 	req->PersistentFileId = persistent_fid;
4860 	req->VolatileFileId = volatile_fid;
4861 
4862 	len = 0x2;
4863 	bufptr = req->Buffer;
4864 	memcpy(bufptr, &asteriks, len);
4865 
4866 	req->FileNameOffset =
4867 		cpu_to_le16(sizeof(struct smb2_query_directory_req) - 1);
4868 	req->FileNameLength = cpu_to_le16(len);
4869 	/*
4870 	 * BB could be 30 bytes or so longer if we used SMB2 specific
4871 	 * buffer lengths, but this is safe and close enough.
4872 	 */
4873 	output_size = min_t(unsigned int, output_size, server->maxBuf);
4874 	output_size = min_t(unsigned int, output_size, 2 << 15);
4875 	req->OutputBufferLength = cpu_to_le32(output_size);
4876 
4877 	iov[0].iov_base = (char *)req;
4878 	/* 1 for Buffer */
4879 	iov[0].iov_len = total_len - 1;
4880 
4881 	iov[1].iov_base = (char *)(req->Buffer);
4882 	iov[1].iov_len = len;
4883 
4884 	trace_smb3_query_dir_enter(xid, persistent_fid, tcon->tid,
4885 			tcon->ses->Suid, index, output_size);
4886 
4887 	return 0;
4888 }
4889 
SMB2_query_directory_free(struct smb_rqst * rqst)4890 void SMB2_query_directory_free(struct smb_rqst *rqst)
4891 {
4892 	if (rqst && rqst->rq_iov) {
4893 		cifs_small_buf_release(rqst->rq_iov[0].iov_base); /* request */
4894 	}
4895 }
4896 
4897 int
smb2_parse_query_directory(struct cifs_tcon * tcon,struct kvec * rsp_iov,int resp_buftype,struct cifs_search_info * srch_inf)4898 smb2_parse_query_directory(struct cifs_tcon *tcon,
4899 			   struct kvec *rsp_iov,
4900 			   int resp_buftype,
4901 			   struct cifs_search_info *srch_inf)
4902 {
4903 	struct smb2_query_directory_rsp *rsp;
4904 	size_t info_buf_size;
4905 	char *end_of_smb;
4906 	int rc;
4907 
4908 	rsp = (struct smb2_query_directory_rsp *)rsp_iov->iov_base;
4909 
4910 	switch (srch_inf->info_level) {
4911 	case SMB_FIND_FILE_DIRECTORY_INFO:
4912 		info_buf_size = sizeof(FILE_DIRECTORY_INFO) - 1;
4913 		break;
4914 	case SMB_FIND_FILE_ID_FULL_DIR_INFO:
4915 		info_buf_size = sizeof(SEARCH_ID_FULL_DIR_INFO) - 1;
4916 		break;
4917 	case SMB_FIND_FILE_POSIX_INFO:
4918 		/* note that posix payload are variable size */
4919 		info_buf_size = sizeof(struct smb2_posix_info);
4920 		break;
4921 	default:
4922 		cifs_tcon_dbg(VFS, "info level %u isn't supported\n",
4923 			 srch_inf->info_level);
4924 		return -EINVAL;
4925 	}
4926 
4927 	rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset),
4928 			       le32_to_cpu(rsp->OutputBufferLength), rsp_iov,
4929 			       info_buf_size);
4930 	if (rc) {
4931 		cifs_tcon_dbg(VFS, "bad info payload");
4932 		return rc;
4933 	}
4934 
4935 	srch_inf->unicode = true;
4936 
4937 	if (srch_inf->ntwrk_buf_start) {
4938 		if (srch_inf->smallBuf)
4939 			cifs_small_buf_release(srch_inf->ntwrk_buf_start);
4940 		else
4941 			cifs_buf_release(srch_inf->ntwrk_buf_start);
4942 	}
4943 	srch_inf->ntwrk_buf_start = (char *)rsp;
4944 	srch_inf->srch_entries_start = srch_inf->last_entry =
4945 		(char *)rsp + le16_to_cpu(rsp->OutputBufferOffset);
4946 	end_of_smb = rsp_iov->iov_len + (char *)rsp;
4947 
4948 	srch_inf->entries_in_buffer = num_entries(
4949 		srch_inf->info_level,
4950 		srch_inf->srch_entries_start,
4951 		end_of_smb,
4952 		&srch_inf->last_entry,
4953 		info_buf_size);
4954 
4955 	srch_inf->index_of_last_entry += srch_inf->entries_in_buffer;
4956 	cifs_dbg(FYI, "num entries %d last_index %lld srch start %p srch end %p\n",
4957 		 srch_inf->entries_in_buffer, srch_inf->index_of_last_entry,
4958 		 srch_inf->srch_entries_start, srch_inf->last_entry);
4959 	if (resp_buftype == CIFS_LARGE_BUFFER)
4960 		srch_inf->smallBuf = false;
4961 	else if (resp_buftype == CIFS_SMALL_BUFFER)
4962 		srch_inf->smallBuf = true;
4963 	else
4964 		cifs_tcon_dbg(VFS, "Invalid search buffer type\n");
4965 
4966 	return 0;
4967 }
4968 
4969 int
SMB2_query_directory(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,int index,struct cifs_search_info * srch_inf)4970 SMB2_query_directory(const unsigned int xid, struct cifs_tcon *tcon,
4971 		     u64 persistent_fid, u64 volatile_fid, int index,
4972 		     struct cifs_search_info *srch_inf)
4973 {
4974 	struct smb_rqst rqst;
4975 	struct kvec iov[SMB2_QUERY_DIRECTORY_IOV_SIZE];
4976 	struct smb2_query_directory_rsp *rsp = NULL;
4977 	int resp_buftype = CIFS_NO_BUFFER;
4978 	struct kvec rsp_iov;
4979 	int rc = 0;
4980 	struct cifs_ses *ses = tcon->ses;
4981 	struct TCP_Server_Info *server = cifs_pick_channel(ses);
4982 	int flags = 0;
4983 
4984 	if (!ses || !(ses->server))
4985 		return -EIO;
4986 
4987 	if (smb3_encryption_required(tcon))
4988 		flags |= CIFS_TRANSFORM_REQ;
4989 
4990 	memset(&rqst, 0, sizeof(struct smb_rqst));
4991 	memset(&iov, 0, sizeof(iov));
4992 	rqst.rq_iov = iov;
4993 	rqst.rq_nvec = SMB2_QUERY_DIRECTORY_IOV_SIZE;
4994 
4995 	rc = SMB2_query_directory_init(xid, tcon, server,
4996 				       &rqst, persistent_fid,
4997 				       volatile_fid, index,
4998 				       srch_inf->info_level);
4999 	if (rc)
5000 		goto qdir_exit;
5001 
5002 	rc = cifs_send_recv(xid, ses, server,
5003 			    &rqst, &resp_buftype, flags, &rsp_iov);
5004 	rsp = (struct smb2_query_directory_rsp *)rsp_iov.iov_base;
5005 
5006 	if (rc) {
5007 		if (rc == -ENODATA &&
5008 		    rsp->hdr.Status == STATUS_NO_MORE_FILES) {
5009 			trace_smb3_query_dir_done(xid, persistent_fid,
5010 				tcon->tid, tcon->ses->Suid, index, 0);
5011 			srch_inf->endOfSearch = true;
5012 			rc = 0;
5013 		} else {
5014 			trace_smb3_query_dir_err(xid, persistent_fid, tcon->tid,
5015 				tcon->ses->Suid, index, 0, rc);
5016 			cifs_stats_fail_inc(tcon, SMB2_QUERY_DIRECTORY_HE);
5017 		}
5018 		goto qdir_exit;
5019 	}
5020 
5021 	rc = smb2_parse_query_directory(tcon, &rsp_iov,	resp_buftype,
5022 					srch_inf);
5023 	if (rc) {
5024 		trace_smb3_query_dir_err(xid, persistent_fid, tcon->tid,
5025 			tcon->ses->Suid, index, 0, rc);
5026 		goto qdir_exit;
5027 	}
5028 	resp_buftype = CIFS_NO_BUFFER;
5029 
5030 	trace_smb3_query_dir_done(xid, persistent_fid, tcon->tid,
5031 			tcon->ses->Suid, index, srch_inf->entries_in_buffer);
5032 
5033 qdir_exit:
5034 	SMB2_query_directory_free(&rqst);
5035 	free_rsp_buf(resp_buftype, rsp);
5036 	return rc;
5037 }
5038 
5039 int
SMB2_set_info_init(struct cifs_tcon * tcon,struct TCP_Server_Info * server,struct smb_rqst * rqst,u64 persistent_fid,u64 volatile_fid,u32 pid,u8 info_class,u8 info_type,u32 additional_info,void ** data,unsigned int * size)5040 SMB2_set_info_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server,
5041 		   struct smb_rqst *rqst,
5042 		   u64 persistent_fid, u64 volatile_fid, u32 pid,
5043 		   u8 info_class, u8 info_type, u32 additional_info,
5044 		   void **data, unsigned int *size)
5045 {
5046 	struct smb2_set_info_req *req;
5047 	struct kvec *iov = rqst->rq_iov;
5048 	unsigned int i, total_len;
5049 	int rc;
5050 
5051 	rc = smb2_plain_req_init(SMB2_SET_INFO, tcon, server,
5052 				 (void **) &req, &total_len);
5053 	if (rc)
5054 		return rc;
5055 
5056 	req->hdr.Id.SyncId.ProcessId = cpu_to_le32(pid);
5057 	req->InfoType = info_type;
5058 	req->FileInfoClass = info_class;
5059 	req->PersistentFileId = persistent_fid;
5060 	req->VolatileFileId = volatile_fid;
5061 	req->AdditionalInformation = cpu_to_le32(additional_info);
5062 
5063 	req->BufferOffset =
5064 			cpu_to_le16(sizeof(struct smb2_set_info_req) - 1);
5065 	req->BufferLength = cpu_to_le32(*size);
5066 
5067 	memcpy(req->Buffer, *data, *size);
5068 	total_len += *size;
5069 
5070 	iov[0].iov_base = (char *)req;
5071 	/* 1 for Buffer */
5072 	iov[0].iov_len = total_len - 1;
5073 
5074 	for (i = 1; i < rqst->rq_nvec; i++) {
5075 		le32_add_cpu(&req->BufferLength, size[i]);
5076 		iov[i].iov_base = (char *)data[i];
5077 		iov[i].iov_len = size[i];
5078 	}
5079 
5080 	return 0;
5081 }
5082 
5083 void
SMB2_set_info_free(struct smb_rqst * rqst)5084 SMB2_set_info_free(struct smb_rqst *rqst)
5085 {
5086 	if (rqst && rqst->rq_iov)
5087 		cifs_buf_release(rqst->rq_iov[0].iov_base); /* request */
5088 }
5089 
5090 static int
send_set_info(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,u32 pid,u8 info_class,u8 info_type,u32 additional_info,unsigned int num,void ** data,unsigned int * size)5091 send_set_info(const unsigned int xid, struct cifs_tcon *tcon,
5092 	       u64 persistent_fid, u64 volatile_fid, u32 pid, u8 info_class,
5093 	       u8 info_type, u32 additional_info, unsigned int num,
5094 		void **data, unsigned int *size)
5095 {
5096 	struct smb_rqst rqst;
5097 	struct smb2_set_info_rsp *rsp = NULL;
5098 	struct kvec *iov;
5099 	struct kvec rsp_iov;
5100 	int rc = 0;
5101 	int resp_buftype;
5102 	struct cifs_ses *ses = tcon->ses;
5103 	struct TCP_Server_Info *server = cifs_pick_channel(ses);
5104 	int flags = 0;
5105 
5106 	if (!ses || !server)
5107 		return -EIO;
5108 
5109 	if (!num)
5110 		return -EINVAL;
5111 
5112 	if (smb3_encryption_required(tcon))
5113 		flags |= CIFS_TRANSFORM_REQ;
5114 
5115 	iov = kmalloc_array(num, sizeof(struct kvec), GFP_KERNEL);
5116 	if (!iov)
5117 		return -ENOMEM;
5118 
5119 	memset(&rqst, 0, sizeof(struct smb_rqst));
5120 	rqst.rq_iov = iov;
5121 	rqst.rq_nvec = num;
5122 
5123 	rc = SMB2_set_info_init(tcon, server,
5124 				&rqst, persistent_fid, volatile_fid, pid,
5125 				info_class, info_type, additional_info,
5126 				data, size);
5127 	if (rc) {
5128 		kfree(iov);
5129 		return rc;
5130 	}
5131 
5132 
5133 	rc = cifs_send_recv(xid, ses, server,
5134 			    &rqst, &resp_buftype, flags,
5135 			    &rsp_iov);
5136 	SMB2_set_info_free(&rqst);
5137 	rsp = (struct smb2_set_info_rsp *)rsp_iov.iov_base;
5138 
5139 	if (rc != 0) {
5140 		cifs_stats_fail_inc(tcon, SMB2_SET_INFO_HE);
5141 		trace_smb3_set_info_err(xid, persistent_fid, tcon->tid,
5142 				ses->Suid, info_class, (__u32)info_type, rc);
5143 	}
5144 
5145 	free_rsp_buf(resp_buftype, rsp);
5146 	kfree(iov);
5147 	return rc;
5148 }
5149 
5150 int
SMB2_set_eof(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,u32 pid,__le64 * eof)5151 SMB2_set_eof(const unsigned int xid, struct cifs_tcon *tcon, u64 persistent_fid,
5152 	     u64 volatile_fid, u32 pid, __le64 *eof)
5153 {
5154 	struct smb2_file_eof_info info;
5155 	void *data;
5156 	unsigned int size;
5157 
5158 	info.EndOfFile = *eof;
5159 
5160 	data = &info;
5161 	size = sizeof(struct smb2_file_eof_info);
5162 
5163 	trace_smb3_set_eof(xid, persistent_fid, tcon->tid, tcon->ses->Suid, le64_to_cpu(*eof));
5164 
5165 	return send_set_info(xid, tcon, persistent_fid, volatile_fid,
5166 			pid, FILE_END_OF_FILE_INFORMATION, SMB2_O_INFO_FILE,
5167 			0, 1, &data, &size);
5168 }
5169 
5170 int
SMB2_set_acl(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,struct cifs_ntsd * pnntsd,int pacllen,int aclflag)5171 SMB2_set_acl(const unsigned int xid, struct cifs_tcon *tcon,
5172 		u64 persistent_fid, u64 volatile_fid,
5173 		struct cifs_ntsd *pnntsd, int pacllen, int aclflag)
5174 {
5175 	return send_set_info(xid, tcon, persistent_fid, volatile_fid,
5176 			current->tgid, 0, SMB2_O_INFO_SECURITY, aclflag,
5177 			1, (void **)&pnntsd, &pacllen);
5178 }
5179 
5180 int
SMB2_set_ea(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,struct smb2_file_full_ea_info * buf,int len)5181 SMB2_set_ea(const unsigned int xid, struct cifs_tcon *tcon,
5182 	    u64 persistent_fid, u64 volatile_fid,
5183 	    struct smb2_file_full_ea_info *buf, int len)
5184 {
5185 	return send_set_info(xid, tcon, persistent_fid, volatile_fid,
5186 		current->tgid, FILE_FULL_EA_INFORMATION, SMB2_O_INFO_FILE,
5187 		0, 1, (void **)&buf, &len);
5188 }
5189 
5190 int
SMB2_oplock_break(const unsigned int xid,struct cifs_tcon * tcon,const u64 persistent_fid,const u64 volatile_fid,__u8 oplock_level)5191 SMB2_oplock_break(const unsigned int xid, struct cifs_tcon *tcon,
5192 		  const u64 persistent_fid, const u64 volatile_fid,
5193 		  __u8 oplock_level)
5194 {
5195 	struct smb_rqst rqst;
5196 	int rc;
5197 	struct smb2_oplock_break *req = NULL;
5198 	struct cifs_ses *ses = tcon->ses;
5199 	struct TCP_Server_Info *server = cifs_pick_channel(ses);
5200 	int flags = CIFS_OBREAK_OP;
5201 	unsigned int total_len;
5202 	struct kvec iov[1];
5203 	struct kvec rsp_iov;
5204 	int resp_buf_type;
5205 
5206 	cifs_dbg(FYI, "SMB2_oplock_break\n");
5207 	rc = smb2_plain_req_init(SMB2_OPLOCK_BREAK, tcon, server,
5208 				 (void **) &req, &total_len);
5209 	if (rc)
5210 		return rc;
5211 
5212 	if (smb3_encryption_required(tcon))
5213 		flags |= CIFS_TRANSFORM_REQ;
5214 
5215 	req->VolatileFid = volatile_fid;
5216 	req->PersistentFid = persistent_fid;
5217 	req->OplockLevel = oplock_level;
5218 	req->hdr.CreditRequest = cpu_to_le16(1);
5219 
5220 	flags |= CIFS_NO_RSP_BUF;
5221 
5222 	iov[0].iov_base = (char *)req;
5223 	iov[0].iov_len = total_len;
5224 
5225 	memset(&rqst, 0, sizeof(struct smb_rqst));
5226 	rqst.rq_iov = iov;
5227 	rqst.rq_nvec = 1;
5228 
5229 	rc = cifs_send_recv(xid, ses, server,
5230 			    &rqst, &resp_buf_type, flags, &rsp_iov);
5231 	cifs_small_buf_release(req);
5232 
5233 	if (rc) {
5234 		cifs_stats_fail_inc(tcon, SMB2_OPLOCK_BREAK_HE);
5235 		cifs_dbg(FYI, "Send error in Oplock Break = %d\n", rc);
5236 	}
5237 
5238 	return rc;
5239 }
5240 
5241 void
smb2_copy_fs_info_to_kstatfs(struct smb2_fs_full_size_info * pfs_inf,struct kstatfs * kst)5242 smb2_copy_fs_info_to_kstatfs(struct smb2_fs_full_size_info *pfs_inf,
5243 			     struct kstatfs *kst)
5244 {
5245 	kst->f_bsize = le32_to_cpu(pfs_inf->BytesPerSector) *
5246 			  le32_to_cpu(pfs_inf->SectorsPerAllocationUnit);
5247 	kst->f_blocks = le64_to_cpu(pfs_inf->TotalAllocationUnits);
5248 	kst->f_bfree  = kst->f_bavail =
5249 			le64_to_cpu(pfs_inf->CallerAvailableAllocationUnits);
5250 	return;
5251 }
5252 
5253 static void
copy_posix_fs_info_to_kstatfs(FILE_SYSTEM_POSIX_INFO * response_data,struct kstatfs * kst)5254 copy_posix_fs_info_to_kstatfs(FILE_SYSTEM_POSIX_INFO *response_data,
5255 			struct kstatfs *kst)
5256 {
5257 	kst->f_bsize = le32_to_cpu(response_data->BlockSize);
5258 	kst->f_blocks = le64_to_cpu(response_data->TotalBlocks);
5259 	kst->f_bfree =  le64_to_cpu(response_data->BlocksAvail);
5260 	if (response_data->UserBlocksAvail == cpu_to_le64(-1))
5261 		kst->f_bavail = kst->f_bfree;
5262 	else
5263 		kst->f_bavail = le64_to_cpu(response_data->UserBlocksAvail);
5264 	if (response_data->TotalFileNodes != cpu_to_le64(-1))
5265 		kst->f_files = le64_to_cpu(response_data->TotalFileNodes);
5266 	if (response_data->FreeFileNodes != cpu_to_le64(-1))
5267 		kst->f_ffree = le64_to_cpu(response_data->FreeFileNodes);
5268 
5269 	return;
5270 }
5271 
5272 static int
build_qfs_info_req(struct kvec * iov,struct cifs_tcon * tcon,struct TCP_Server_Info * server,int level,int outbuf_len,u64 persistent_fid,u64 volatile_fid)5273 build_qfs_info_req(struct kvec *iov, struct cifs_tcon *tcon,
5274 		   struct TCP_Server_Info *server,
5275 		   int level, int outbuf_len, u64 persistent_fid,
5276 		   u64 volatile_fid)
5277 {
5278 	int rc;
5279 	struct smb2_query_info_req *req;
5280 	unsigned int total_len;
5281 
5282 	cifs_dbg(FYI, "Query FSInfo level %d\n", level);
5283 
5284 	if ((tcon->ses == NULL) || server == NULL)
5285 		return -EIO;
5286 
5287 	rc = smb2_plain_req_init(SMB2_QUERY_INFO, tcon, server,
5288 				 (void **) &req, &total_len);
5289 	if (rc)
5290 		return rc;
5291 
5292 	req->InfoType = SMB2_O_INFO_FILESYSTEM;
5293 	req->FileInfoClass = level;
5294 	req->PersistentFileId = persistent_fid;
5295 	req->VolatileFileId = volatile_fid;
5296 	/* 1 for pad */
5297 	req->InputBufferOffset =
5298 			cpu_to_le16(sizeof(struct smb2_query_info_req) - 1);
5299 	req->OutputBufferLength = cpu_to_le32(
5300 		outbuf_len + sizeof(struct smb2_query_info_rsp) - 1);
5301 
5302 	iov->iov_base = (char *)req;
5303 	iov->iov_len = total_len;
5304 	return 0;
5305 }
5306 
5307 int
SMB311_posix_qfs_info(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,struct kstatfs * fsdata)5308 SMB311_posix_qfs_info(const unsigned int xid, struct cifs_tcon *tcon,
5309 	      u64 persistent_fid, u64 volatile_fid, struct kstatfs *fsdata)
5310 {
5311 	struct smb_rqst rqst;
5312 	struct smb2_query_info_rsp *rsp = NULL;
5313 	struct kvec iov;
5314 	struct kvec rsp_iov;
5315 	int rc = 0;
5316 	int resp_buftype;
5317 	struct cifs_ses *ses = tcon->ses;
5318 	struct TCP_Server_Info *server = cifs_pick_channel(ses);
5319 	FILE_SYSTEM_POSIX_INFO *info = NULL;
5320 	int flags = 0;
5321 
5322 	rc = build_qfs_info_req(&iov, tcon, server,
5323 				FS_POSIX_INFORMATION,
5324 				sizeof(FILE_SYSTEM_POSIX_INFO),
5325 				persistent_fid, volatile_fid);
5326 	if (rc)
5327 		return rc;
5328 
5329 	if (smb3_encryption_required(tcon))
5330 		flags |= CIFS_TRANSFORM_REQ;
5331 
5332 	memset(&rqst, 0, sizeof(struct smb_rqst));
5333 	rqst.rq_iov = &iov;
5334 	rqst.rq_nvec = 1;
5335 
5336 	rc = cifs_send_recv(xid, ses, server,
5337 			    &rqst, &resp_buftype, flags, &rsp_iov);
5338 	cifs_small_buf_release(iov.iov_base);
5339 	if (rc) {
5340 		cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
5341 		goto posix_qfsinf_exit;
5342 	}
5343 	rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
5344 
5345 	info = (FILE_SYSTEM_POSIX_INFO *)(
5346 		le16_to_cpu(rsp->OutputBufferOffset) + (char *)rsp);
5347 	rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset),
5348 			       le32_to_cpu(rsp->OutputBufferLength), &rsp_iov,
5349 			       sizeof(FILE_SYSTEM_POSIX_INFO));
5350 	if (!rc)
5351 		copy_posix_fs_info_to_kstatfs(info, fsdata);
5352 
5353 posix_qfsinf_exit:
5354 	free_rsp_buf(resp_buftype, rsp_iov.iov_base);
5355 	return rc;
5356 }
5357 
5358 int
SMB2_QFS_info(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,struct kstatfs * fsdata)5359 SMB2_QFS_info(const unsigned int xid, struct cifs_tcon *tcon,
5360 	      u64 persistent_fid, u64 volatile_fid, struct kstatfs *fsdata)
5361 {
5362 	struct smb_rqst rqst;
5363 	struct smb2_query_info_rsp *rsp = NULL;
5364 	struct kvec iov;
5365 	struct kvec rsp_iov;
5366 	int rc = 0;
5367 	int resp_buftype;
5368 	struct cifs_ses *ses = tcon->ses;
5369 	struct TCP_Server_Info *server = cifs_pick_channel(ses);
5370 	struct smb2_fs_full_size_info *info = NULL;
5371 	int flags = 0;
5372 
5373 	rc = build_qfs_info_req(&iov, tcon, server,
5374 				FS_FULL_SIZE_INFORMATION,
5375 				sizeof(struct smb2_fs_full_size_info),
5376 				persistent_fid, volatile_fid);
5377 	if (rc)
5378 		return rc;
5379 
5380 	if (smb3_encryption_required(tcon))
5381 		flags |= CIFS_TRANSFORM_REQ;
5382 
5383 	memset(&rqst, 0, sizeof(struct smb_rqst));
5384 	rqst.rq_iov = &iov;
5385 	rqst.rq_nvec = 1;
5386 
5387 	rc = cifs_send_recv(xid, ses, server,
5388 			    &rqst, &resp_buftype, flags, &rsp_iov);
5389 	cifs_small_buf_release(iov.iov_base);
5390 	if (rc) {
5391 		cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
5392 		goto qfsinf_exit;
5393 	}
5394 	rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
5395 
5396 	info = (struct smb2_fs_full_size_info *)(
5397 		le16_to_cpu(rsp->OutputBufferOffset) + (char *)rsp);
5398 	rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset),
5399 			       le32_to_cpu(rsp->OutputBufferLength), &rsp_iov,
5400 			       sizeof(struct smb2_fs_full_size_info));
5401 	if (!rc)
5402 		smb2_copy_fs_info_to_kstatfs(info, fsdata);
5403 
5404 qfsinf_exit:
5405 	free_rsp_buf(resp_buftype, rsp_iov.iov_base);
5406 	return rc;
5407 }
5408 
5409 int
SMB2_QFS_attr(const unsigned int xid,struct cifs_tcon * tcon,u64 persistent_fid,u64 volatile_fid,int level)5410 SMB2_QFS_attr(const unsigned int xid, struct cifs_tcon *tcon,
5411 	      u64 persistent_fid, u64 volatile_fid, int level)
5412 {
5413 	struct smb_rqst rqst;
5414 	struct smb2_query_info_rsp *rsp = NULL;
5415 	struct kvec iov;
5416 	struct kvec rsp_iov;
5417 	int rc = 0;
5418 	int resp_buftype, max_len, min_len;
5419 	struct cifs_ses *ses = tcon->ses;
5420 	struct TCP_Server_Info *server = cifs_pick_channel(ses);
5421 	unsigned int rsp_len, offset;
5422 	int flags = 0;
5423 
5424 	if (level == FS_DEVICE_INFORMATION) {
5425 		max_len = sizeof(FILE_SYSTEM_DEVICE_INFO);
5426 		min_len = sizeof(FILE_SYSTEM_DEVICE_INFO);
5427 	} else if (level == FS_ATTRIBUTE_INFORMATION) {
5428 		max_len = sizeof(FILE_SYSTEM_ATTRIBUTE_INFO);
5429 		min_len = MIN_FS_ATTR_INFO_SIZE;
5430 	} else if (level == FS_SECTOR_SIZE_INFORMATION) {
5431 		max_len = sizeof(struct smb3_fs_ss_info);
5432 		min_len = sizeof(struct smb3_fs_ss_info);
5433 	} else if (level == FS_VOLUME_INFORMATION) {
5434 		max_len = sizeof(struct smb3_fs_vol_info) + MAX_VOL_LABEL_LEN;
5435 		min_len = sizeof(struct smb3_fs_vol_info);
5436 	} else {
5437 		cifs_dbg(FYI, "Invalid qfsinfo level %d\n", level);
5438 		return -EINVAL;
5439 	}
5440 
5441 	rc = build_qfs_info_req(&iov, tcon, server,
5442 				level, max_len,
5443 				persistent_fid, volatile_fid);
5444 	if (rc)
5445 		return rc;
5446 
5447 	if (smb3_encryption_required(tcon))
5448 		flags |= CIFS_TRANSFORM_REQ;
5449 
5450 	memset(&rqst, 0, sizeof(struct smb_rqst));
5451 	rqst.rq_iov = &iov;
5452 	rqst.rq_nvec = 1;
5453 
5454 	rc = cifs_send_recv(xid, ses, server,
5455 			    &rqst, &resp_buftype, flags, &rsp_iov);
5456 	cifs_small_buf_release(iov.iov_base);
5457 	if (rc) {
5458 		cifs_stats_fail_inc(tcon, SMB2_QUERY_INFO_HE);
5459 		goto qfsattr_exit;
5460 	}
5461 	rsp = (struct smb2_query_info_rsp *)rsp_iov.iov_base;
5462 
5463 	rsp_len = le32_to_cpu(rsp->OutputBufferLength);
5464 	offset = le16_to_cpu(rsp->OutputBufferOffset);
5465 	rc = smb2_validate_iov(offset, rsp_len, &rsp_iov, min_len);
5466 	if (rc)
5467 		goto qfsattr_exit;
5468 
5469 	if (level == FS_ATTRIBUTE_INFORMATION)
5470 		memcpy(&tcon->fsAttrInfo, offset
5471 			+ (char *)rsp, min_t(unsigned int,
5472 			rsp_len, max_len));
5473 	else if (level == FS_DEVICE_INFORMATION)
5474 		memcpy(&tcon->fsDevInfo, offset
5475 			+ (char *)rsp, sizeof(FILE_SYSTEM_DEVICE_INFO));
5476 	else if (level == FS_SECTOR_SIZE_INFORMATION) {
5477 		struct smb3_fs_ss_info *ss_info = (struct smb3_fs_ss_info *)
5478 			(offset + (char *)rsp);
5479 		tcon->ss_flags = le32_to_cpu(ss_info->Flags);
5480 		tcon->perf_sector_size =
5481 			le32_to_cpu(ss_info->PhysicalBytesPerSectorForPerf);
5482 	} else if (level == FS_VOLUME_INFORMATION) {
5483 		struct smb3_fs_vol_info *vol_info = (struct smb3_fs_vol_info *)
5484 			(offset + (char *)rsp);
5485 		tcon->vol_serial_number = vol_info->VolumeSerialNumber;
5486 		tcon->vol_create_time = vol_info->VolumeCreationTime;
5487 	}
5488 
5489 qfsattr_exit:
5490 	free_rsp_buf(resp_buftype, rsp_iov.iov_base);
5491 	return rc;
5492 }
5493 
5494 int
smb2_lockv(const unsigned int xid,struct cifs_tcon * tcon,const __u64 persist_fid,const __u64 volatile_fid,const __u32 pid,const __u32 num_lock,struct smb2_lock_element * buf)5495 smb2_lockv(const unsigned int xid, struct cifs_tcon *tcon,
5496 	   const __u64 persist_fid, const __u64 volatile_fid, const __u32 pid,
5497 	   const __u32 num_lock, struct smb2_lock_element *buf)
5498 {
5499 	struct smb_rqst rqst;
5500 	int rc = 0;
5501 	struct smb2_lock_req *req = NULL;
5502 	struct kvec iov[2];
5503 	struct kvec rsp_iov;
5504 	int resp_buf_type;
5505 	unsigned int count;
5506 	int flags = CIFS_NO_RSP_BUF;
5507 	unsigned int total_len;
5508 	struct TCP_Server_Info *server = cifs_pick_channel(tcon->ses);
5509 
5510 	cifs_dbg(FYI, "smb2_lockv num lock %d\n", num_lock);
5511 
5512 	rc = smb2_plain_req_init(SMB2_LOCK, tcon, server,
5513 				 (void **) &req, &total_len);
5514 	if (rc)
5515 		return rc;
5516 
5517 	if (smb3_encryption_required(tcon))
5518 		flags |= CIFS_TRANSFORM_REQ;
5519 
5520 	req->hdr.Id.SyncId.ProcessId = cpu_to_le32(pid);
5521 	req->LockCount = cpu_to_le16(num_lock);
5522 
5523 	req->PersistentFileId = persist_fid;
5524 	req->VolatileFileId = volatile_fid;
5525 
5526 	count = num_lock * sizeof(struct smb2_lock_element);
5527 
5528 	iov[0].iov_base = (char *)req;
5529 	iov[0].iov_len = total_len - sizeof(struct smb2_lock_element);
5530 	iov[1].iov_base = (char *)buf;
5531 	iov[1].iov_len = count;
5532 
5533 	cifs_stats_inc(&tcon->stats.cifs_stats.num_locks);
5534 
5535 	memset(&rqst, 0, sizeof(struct smb_rqst));
5536 	rqst.rq_iov = iov;
5537 	rqst.rq_nvec = 2;
5538 
5539 	rc = cifs_send_recv(xid, tcon->ses, server,
5540 			    &rqst, &resp_buf_type, flags,
5541 			    &rsp_iov);
5542 	cifs_small_buf_release(req);
5543 	if (rc) {
5544 		cifs_dbg(FYI, "Send error in smb2_lockv = %d\n", rc);
5545 		cifs_stats_fail_inc(tcon, SMB2_LOCK_HE);
5546 		trace_smb3_lock_err(xid, persist_fid, tcon->tid,
5547 				    tcon->ses->Suid, rc);
5548 	}
5549 
5550 	return rc;
5551 }
5552 
5553 int
SMB2_lock(const unsigned int xid,struct cifs_tcon * tcon,const __u64 persist_fid,const __u64 volatile_fid,const __u32 pid,const __u64 length,const __u64 offset,const __u32 lock_flags,const bool wait)5554 SMB2_lock(const unsigned int xid, struct cifs_tcon *tcon,
5555 	  const __u64 persist_fid, const __u64 volatile_fid, const __u32 pid,
5556 	  const __u64 length, const __u64 offset, const __u32 lock_flags,
5557 	  const bool wait)
5558 {
5559 	struct smb2_lock_element lock;
5560 
5561 	lock.Offset = cpu_to_le64(offset);
5562 	lock.Length = cpu_to_le64(length);
5563 	lock.Flags = cpu_to_le32(lock_flags);
5564 	if (!wait && lock_flags != SMB2_LOCKFLAG_UNLOCK)
5565 		lock.Flags |= cpu_to_le32(SMB2_LOCKFLAG_FAIL_IMMEDIATELY);
5566 
5567 	return smb2_lockv(xid, tcon, persist_fid, volatile_fid, pid, 1, &lock);
5568 }
5569 
5570 int
SMB2_lease_break(const unsigned int xid,struct cifs_tcon * tcon,__u8 * lease_key,const __le32 lease_state)5571 SMB2_lease_break(const unsigned int xid, struct cifs_tcon *tcon,
5572 		 __u8 *lease_key, const __le32 lease_state)
5573 {
5574 	struct smb_rqst rqst;
5575 	int rc;
5576 	struct smb2_lease_ack *req = NULL;
5577 	struct cifs_ses *ses = tcon->ses;
5578 	int flags = CIFS_OBREAK_OP;
5579 	unsigned int total_len;
5580 	struct kvec iov[1];
5581 	struct kvec rsp_iov;
5582 	int resp_buf_type;
5583 	__u64 *please_key_high;
5584 	__u64 *please_key_low;
5585 	struct TCP_Server_Info *server = cifs_pick_channel(tcon->ses);
5586 
5587 	cifs_dbg(FYI, "SMB2_lease_break\n");
5588 	rc = smb2_plain_req_init(SMB2_OPLOCK_BREAK, tcon, server,
5589 				 (void **) &req, &total_len);
5590 	if (rc)
5591 		return rc;
5592 
5593 	if (smb3_encryption_required(tcon))
5594 		flags |= CIFS_TRANSFORM_REQ;
5595 
5596 	req->hdr.CreditRequest = cpu_to_le16(1);
5597 	req->StructureSize = cpu_to_le16(36);
5598 	total_len += 12;
5599 
5600 	memcpy(req->LeaseKey, lease_key, 16);
5601 	req->LeaseState = lease_state;
5602 
5603 	flags |= CIFS_NO_RSP_BUF;
5604 
5605 	iov[0].iov_base = (char *)req;
5606 	iov[0].iov_len = total_len;
5607 
5608 	memset(&rqst, 0, sizeof(struct smb_rqst));
5609 	rqst.rq_iov = iov;
5610 	rqst.rq_nvec = 1;
5611 
5612 	rc = cifs_send_recv(xid, ses, server,
5613 			    &rqst, &resp_buf_type, flags, &rsp_iov);
5614 	cifs_small_buf_release(req);
5615 
5616 	please_key_low = (__u64 *)lease_key;
5617 	please_key_high = (__u64 *)(lease_key+8);
5618 	if (rc) {
5619 		cifs_stats_fail_inc(tcon, SMB2_OPLOCK_BREAK_HE);
5620 		trace_smb3_lease_err(le32_to_cpu(lease_state), tcon->tid,
5621 			ses->Suid, *please_key_low, *please_key_high, rc);
5622 		cifs_dbg(FYI, "Send error in Lease Break = %d\n", rc);
5623 	} else
5624 		trace_smb3_lease_done(le32_to_cpu(lease_state), tcon->tid,
5625 			ses->Suid, *please_key_low, *please_key_high);
5626 
5627 	return rc;
5628 }
5629