Merge tag 'erofs-for-5.15-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/xiang...
[linux-2.6-microblaze.git] / fs / ksmbd / smb_common.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *   Copyright (C) 2018 Samsung Electronics Co., Ltd.
4  *   Copyright (C) 2018 Namjae Jeon <linkinjeon@kernel.org>
5  */
6
7 #include "smb_common.h"
8 #include "server.h"
9 #include "misc.h"
10 #include "smbstatus.h"
11 #include "connection.h"
12 #include "ksmbd_work.h"
13 #include "mgmt/user_session.h"
14 #include "mgmt/user_config.h"
15 #include "mgmt/tree_connect.h"
16 #include "mgmt/share_config.h"
17
18 /*for shortname implementation */
19 static const char basechars[43] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_-!@#$%";
20 #define MANGLE_BASE (sizeof(basechars) / sizeof(char) - 1)
21 #define MAGIC_CHAR '~'
22 #define PERIOD '.'
23 #define mangle(V) ((char)(basechars[(V) % MANGLE_BASE]))
24 #define KSMBD_MIN_SUPPORTED_HEADER_SIZE (sizeof(struct smb2_hdr))
25
26 struct smb_protocol {
27         int             index;
28         char            *name;
29         char            *prot;
30         __u16           prot_id;
31 };
32
33 static struct smb_protocol smb1_protos[] = {
34         {
35                 SMB21_PROT,
36                 "\2SMB 2.1",
37                 "SMB2_10",
38                 SMB21_PROT_ID
39         },
40         {
41                 SMB2X_PROT,
42                 "\2SMB 2.???",
43                 "SMB2_22",
44                 SMB2X_PROT_ID
45         },
46 };
47
48 static struct smb_protocol smb2_protos[] = {
49         {
50                 SMB21_PROT,
51                 "\2SMB 2.1",
52                 "SMB2_10",
53                 SMB21_PROT_ID
54         },
55         {
56                 SMB30_PROT,
57                 "\2SMB 3.0",
58                 "SMB3_00",
59                 SMB30_PROT_ID
60         },
61         {
62                 SMB302_PROT,
63                 "\2SMB 3.02",
64                 "SMB3_02",
65                 SMB302_PROT_ID
66         },
67         {
68                 SMB311_PROT,
69                 "\2SMB 3.1.1",
70                 "SMB3_11",
71                 SMB311_PROT_ID
72         },
73 };
74
75 unsigned int ksmbd_server_side_copy_max_chunk_count(void)
76 {
77         return 256;
78 }
79
80 unsigned int ksmbd_server_side_copy_max_chunk_size(void)
81 {
82         return (2U << 30) - 1;
83 }
84
85 unsigned int ksmbd_server_side_copy_max_total_size(void)
86 {
87         return (2U << 30) - 1;
88 }
89
90 inline int ksmbd_min_protocol(void)
91 {
92         return SMB2_PROT;
93 }
94
95 inline int ksmbd_max_protocol(void)
96 {
97         return SMB311_PROT;
98 }
99
100 int ksmbd_lookup_protocol_idx(char *str)
101 {
102         int offt = ARRAY_SIZE(smb1_protos) - 1;
103         int len = strlen(str);
104
105         while (offt >= 0) {
106                 if (!strncmp(str, smb1_protos[offt].prot, len)) {
107                         ksmbd_debug(SMB, "selected %s dialect idx = %d\n",
108                                     smb1_protos[offt].prot, offt);
109                         return smb1_protos[offt].index;
110                 }
111                 offt--;
112         }
113
114         offt = ARRAY_SIZE(smb2_protos) - 1;
115         while (offt >= 0) {
116                 if (!strncmp(str, smb2_protos[offt].prot, len)) {
117                         ksmbd_debug(SMB, "selected %s dialect idx = %d\n",
118                                     smb2_protos[offt].prot, offt);
119                         return smb2_protos[offt].index;
120                 }
121                 offt--;
122         }
123         return -1;
124 }
125
126 /**
127  * ksmbd_verify_smb_message() - check for valid smb2 request header
128  * @work:       smb work
129  *
130  * check for valid smb signature and packet direction(request/response)
131  *
132  * Return:      0 on success, otherwise 1
133  */
134 int ksmbd_verify_smb_message(struct ksmbd_work *work)
135 {
136         struct smb2_hdr *smb2_hdr = work->request_buf;
137
138         if (smb2_hdr->ProtocolId == SMB2_PROTO_NUMBER)
139                 return ksmbd_smb2_check_message(work);
140
141         return 0;
142 }
143
144 /**
145  * ksmbd_smb_request() - check for valid smb request type
146  * @conn:       connection instance
147  *
148  * Return:      true on success, otherwise false
149  */
150 bool ksmbd_smb_request(struct ksmbd_conn *conn)
151 {
152         int type = *(char *)conn->request_buf;
153
154         switch (type) {
155         case RFC1002_SESSION_MESSAGE:
156                 /* Regular SMB request */
157                 return true;
158         case RFC1002_SESSION_KEEP_ALIVE:
159                 ksmbd_debug(SMB, "RFC 1002 session keep alive\n");
160                 break;
161         default:
162                 ksmbd_debug(SMB, "RFC 1002 unknown request type 0x%x\n", type);
163         }
164
165         return false;
166 }
167
168 static bool supported_protocol(int idx)
169 {
170         if (idx == SMB2X_PROT &&
171             (server_conf.min_protocol >= SMB21_PROT ||
172              server_conf.max_protocol <= SMB311_PROT))
173                 return true;
174
175         return (server_conf.min_protocol <= idx &&
176                 idx <= server_conf.max_protocol);
177 }
178
179 static char *next_dialect(char *dialect, int *next_off)
180 {
181         dialect = dialect + *next_off;
182         *next_off = strlen(dialect);
183         return dialect;
184 }
185
186 static int ksmbd_lookup_dialect_by_name(char *cli_dialects, __le16 byte_count)
187 {
188         int i, seq_num, bcount, next;
189         char *dialect;
190
191         for (i = ARRAY_SIZE(smb1_protos) - 1; i >= 0; i--) {
192                 seq_num = 0;
193                 next = 0;
194                 dialect = cli_dialects;
195                 bcount = le16_to_cpu(byte_count);
196                 do {
197                         dialect = next_dialect(dialect, &next);
198                         ksmbd_debug(SMB, "client requested dialect %s\n",
199                                     dialect);
200                         if (!strcmp(dialect, smb1_protos[i].name)) {
201                                 if (supported_protocol(smb1_protos[i].index)) {
202                                         ksmbd_debug(SMB,
203                                                     "selected %s dialect\n",
204                                                     smb1_protos[i].name);
205                                         if (smb1_protos[i].index == SMB1_PROT)
206                                                 return seq_num;
207                                         return smb1_protos[i].prot_id;
208                                 }
209                         }
210                         seq_num++;
211                         bcount -= (++next);
212                 } while (bcount > 0);
213         }
214
215         return BAD_PROT_ID;
216 }
217
218 int ksmbd_lookup_dialect_by_id(__le16 *cli_dialects, __le16 dialects_count)
219 {
220         int i;
221         int count;
222
223         for (i = ARRAY_SIZE(smb2_protos) - 1; i >= 0; i--) {
224                 count = le16_to_cpu(dialects_count);
225                 while (--count >= 0) {
226                         ksmbd_debug(SMB, "client requested dialect 0x%x\n",
227                                     le16_to_cpu(cli_dialects[count]));
228                         if (le16_to_cpu(cli_dialects[count]) !=
229                                         smb2_protos[i].prot_id)
230                                 continue;
231
232                         if (supported_protocol(smb2_protos[i].index)) {
233                                 ksmbd_debug(SMB, "selected %s dialect\n",
234                                             smb2_protos[i].name);
235                                 return smb2_protos[i].prot_id;
236                         }
237                 }
238         }
239
240         return BAD_PROT_ID;
241 }
242
243 static int ksmbd_negotiate_smb_dialect(void *buf)
244 {
245         __le32 proto;
246
247         proto = ((struct smb2_hdr *)buf)->ProtocolId;
248         if (proto == SMB2_PROTO_NUMBER) {
249                 struct smb2_negotiate_req *req;
250
251                 req = (struct smb2_negotiate_req *)buf;
252                 return ksmbd_lookup_dialect_by_id(req->Dialects,
253                                                   req->DialectCount);
254         }
255
256         proto = *(__le32 *)((struct smb_hdr *)buf)->Protocol;
257         if (proto == SMB1_PROTO_NUMBER) {
258                 struct smb_negotiate_req *req;
259
260                 req = (struct smb_negotiate_req *)buf;
261                 return ksmbd_lookup_dialect_by_name(req->DialectsArray,
262                                                     req->ByteCount);
263         }
264
265         return BAD_PROT_ID;
266 }
267
268 #define SMB_COM_NEGOTIATE       0x72
269 int ksmbd_init_smb_server(struct ksmbd_work *work)
270 {
271         struct ksmbd_conn *conn = work->conn;
272
273         if (conn->need_neg == false)
274                 return 0;
275
276         init_smb3_11_server(conn);
277
278         if (conn->ops->get_cmd_val(work) != SMB_COM_NEGOTIATE)
279                 conn->need_neg = false;
280         return 0;
281 }
282
283 bool ksmbd_pdu_size_has_room(unsigned int pdu)
284 {
285         return (pdu >= KSMBD_MIN_SUPPORTED_HEADER_SIZE - 4);
286 }
287
288 int ksmbd_populate_dot_dotdot_entries(struct ksmbd_work *work, int info_level,
289                                       struct ksmbd_file *dir,
290                                       struct ksmbd_dir_info *d_info,
291                                       char *search_pattern,
292                                       int (*fn)(struct ksmbd_conn *, int,
293                                                 struct ksmbd_dir_info *,
294                                                 struct user_namespace *,
295                                                 struct ksmbd_kstat *))
296 {
297         int i, rc = 0;
298         struct ksmbd_conn *conn = work->conn;
299         struct user_namespace *user_ns = file_mnt_user_ns(dir->filp);
300
301         for (i = 0; i < 2; i++) {
302                 struct kstat kstat;
303                 struct ksmbd_kstat ksmbd_kstat;
304
305                 if (!dir->dot_dotdot[i]) { /* fill dot entry info */
306                         if (i == 0) {
307                                 d_info->name = ".";
308                                 d_info->name_len = 1;
309                         } else {
310                                 d_info->name = "..";
311                                 d_info->name_len = 2;
312                         }
313
314                         if (!match_pattern(d_info->name, d_info->name_len,
315                                            search_pattern)) {
316                                 dir->dot_dotdot[i] = 1;
317                                 continue;
318                         }
319
320                         ksmbd_kstat.kstat = &kstat;
321                         ksmbd_vfs_fill_dentry_attrs(work,
322                                                     user_ns,
323                                                     dir->filp->f_path.dentry->d_parent,
324                                                     &ksmbd_kstat);
325                         rc = fn(conn, info_level, d_info,
326                                 user_ns, &ksmbd_kstat);
327                         if (rc)
328                                 break;
329                         if (d_info->out_buf_len <= 0)
330                                 break;
331
332                         dir->dot_dotdot[i] = 1;
333                         if (d_info->flags & SMB2_RETURN_SINGLE_ENTRY) {
334                                 d_info->out_buf_len = 0;
335                                 break;
336                         }
337                 }
338         }
339
340         return rc;
341 }
342
343 /**
344  * ksmbd_extract_shortname() - get shortname from long filename
345  * @conn:       connection instance
346  * @longname:   source long filename
347  * @shortname:  destination short filename
348  *
349  * Return:      shortname length or 0 when source long name is '.' or '..'
350  * TODO: Though this function comforms the restriction of 8.3 Filename spec,
351  * but the result is different with Windows 7's one. need to check.
352  */
353 int ksmbd_extract_shortname(struct ksmbd_conn *conn, const char *longname,
354                             char *shortname)
355 {
356         const char *p;
357         char base[9], extension[4];
358         char out[13] = {0};
359         int baselen = 0;
360         int extlen = 0, len = 0;
361         unsigned int csum = 0;
362         const unsigned char *ptr;
363         bool dot_present = true;
364
365         p = longname;
366         if ((*p == '.') || (!(strcmp(p, "..")))) {
367                 /*no mangling required */
368                 return 0;
369         }
370
371         p = strrchr(longname, '.');
372         if (p == longname) { /*name starts with a dot*/
373                 strscpy(extension, "___", strlen("___"));
374         } else {
375                 if (p) {
376                         p++;
377                         while (*p && extlen < 3) {
378                                 if (*p != '.')
379                                         extension[extlen++] = toupper(*p);
380                                 p++;
381                         }
382                         extension[extlen] = '\0';
383                 } else {
384                         dot_present = false;
385                 }
386         }
387
388         p = longname;
389         if (*p == '.') {
390                 p++;
391                 longname++;
392         }
393         while (*p && (baselen < 5)) {
394                 if (*p != '.')
395                         base[baselen++] = toupper(*p);
396                 p++;
397         }
398
399         base[baselen] = MAGIC_CHAR;
400         memcpy(out, base, baselen + 1);
401
402         ptr = longname;
403         len = strlen(longname);
404         for (; len > 0; len--, ptr++)
405                 csum += *ptr;
406
407         csum = csum % (MANGLE_BASE * MANGLE_BASE);
408         out[baselen + 1] = mangle(csum / MANGLE_BASE);
409         out[baselen + 2] = mangle(csum);
410         out[baselen + 3] = PERIOD;
411
412         if (dot_present)
413                 memcpy(&out[baselen + 4], extension, 4);
414         else
415                 out[baselen + 4] = '\0';
416         smbConvertToUTF16((__le16 *)shortname, out, PATH_MAX,
417                           conn->local_nls, 0);
418         len = strlen(out) * 2;
419         return len;
420 }
421
422 static int __smb2_negotiate(struct ksmbd_conn *conn)
423 {
424         return (conn->dialect >= SMB20_PROT_ID &&
425                 conn->dialect <= SMB311_PROT_ID);
426 }
427
428 static int smb_handle_negotiate(struct ksmbd_work *work)
429 {
430         struct smb_negotiate_rsp *neg_rsp = work->response_buf;
431
432         ksmbd_debug(SMB, "Unsupported SMB protocol\n");
433         neg_rsp->hdr.Status.CifsError = STATUS_INVALID_LOGON_TYPE;
434         return -EINVAL;
435 }
436
437 int ksmbd_smb_negotiate_common(struct ksmbd_work *work, unsigned int command)
438 {
439         struct ksmbd_conn *conn = work->conn;
440         int ret;
441
442         conn->dialect = ksmbd_negotiate_smb_dialect(work->request_buf);
443         ksmbd_debug(SMB, "conn->dialect 0x%x\n", conn->dialect);
444
445         if (command == SMB2_NEGOTIATE_HE) {
446                 struct smb2_hdr *smb2_hdr = work->request_buf;
447
448                 if (smb2_hdr->ProtocolId != SMB2_PROTO_NUMBER) {
449                         ksmbd_debug(SMB, "Downgrade to SMB1 negotiation\n");
450                         command = SMB_COM_NEGOTIATE;
451                 }
452         }
453
454         if (command == SMB2_NEGOTIATE_HE) {
455                 ret = smb2_handle_negotiate(work);
456                 init_smb2_neg_rsp(work);
457                 return ret;
458         }
459
460         if (command == SMB_COM_NEGOTIATE) {
461                 if (__smb2_negotiate(conn)) {
462                         conn->need_neg = true;
463                         init_smb3_11_server(conn);
464                         init_smb2_neg_rsp(work);
465                         ksmbd_debug(SMB, "Upgrade to SMB2 negotiation\n");
466                         return 0;
467                 }
468                 return smb_handle_negotiate(work);
469         }
470
471         pr_err("Unknown SMB negotiation command: %u\n", command);
472         return -EINVAL;
473 }
474
475 enum SHARED_MODE_ERRORS {
476         SHARE_DELETE_ERROR,
477         SHARE_READ_ERROR,
478         SHARE_WRITE_ERROR,
479         FILE_READ_ERROR,
480         FILE_WRITE_ERROR,
481         FILE_DELETE_ERROR,
482 };
483
484 static const char * const shared_mode_errors[] = {
485         "Current access mode does not permit SHARE_DELETE",
486         "Current access mode does not permit SHARE_READ",
487         "Current access mode does not permit SHARE_WRITE",
488         "Desired access mode does not permit FILE_READ",
489         "Desired access mode does not permit FILE_WRITE",
490         "Desired access mode does not permit FILE_DELETE",
491 };
492
493 static void smb_shared_mode_error(int error, struct ksmbd_file *prev_fp,
494                                   struct ksmbd_file *curr_fp)
495 {
496         ksmbd_debug(SMB, "%s\n", shared_mode_errors[error]);
497         ksmbd_debug(SMB, "Current mode: 0x%x Desired mode: 0x%x\n",
498                     prev_fp->saccess, curr_fp->daccess);
499 }
500
501 int ksmbd_smb_check_shared_mode(struct file *filp, struct ksmbd_file *curr_fp)
502 {
503         int rc = 0;
504         struct ksmbd_file *prev_fp;
505
506         /*
507          * Lookup fp in master fp list, and check desired access and
508          * shared mode between previous open and current open.
509          */
510         read_lock(&curr_fp->f_ci->m_lock);
511         list_for_each_entry(prev_fp, &curr_fp->f_ci->m_fp_list, node) {
512                 if (file_inode(filp) != file_inode(prev_fp->filp))
513                         continue;
514
515                 if (filp == prev_fp->filp)
516                         continue;
517
518                 if (ksmbd_stream_fd(prev_fp) && ksmbd_stream_fd(curr_fp))
519                         if (strcmp(prev_fp->stream.name, curr_fp->stream.name))
520                                 continue;
521
522                 if (prev_fp->attrib_only != curr_fp->attrib_only)
523                         continue;
524
525                 if (!(prev_fp->saccess & FILE_SHARE_DELETE_LE) &&
526                     curr_fp->daccess & FILE_DELETE_LE) {
527                         smb_shared_mode_error(SHARE_DELETE_ERROR,
528                                               prev_fp,
529                                               curr_fp);
530                         rc = -EPERM;
531                         break;
532                 }
533
534                 /*
535                  * Only check FILE_SHARE_DELETE if stream opened and
536                  * normal file opened.
537                  */
538                 if (ksmbd_stream_fd(prev_fp) && !ksmbd_stream_fd(curr_fp))
539                         continue;
540
541                 if (!(prev_fp->saccess & FILE_SHARE_READ_LE) &&
542                     curr_fp->daccess & (FILE_EXECUTE_LE | FILE_READ_DATA_LE)) {
543                         smb_shared_mode_error(SHARE_READ_ERROR,
544                                               prev_fp,
545                                               curr_fp);
546                         rc = -EPERM;
547                         break;
548                 }
549
550                 if (!(prev_fp->saccess & FILE_SHARE_WRITE_LE) &&
551                     curr_fp->daccess & (FILE_WRITE_DATA_LE | FILE_APPEND_DATA_LE)) {
552                         smb_shared_mode_error(SHARE_WRITE_ERROR,
553                                               prev_fp,
554                                               curr_fp);
555                         rc = -EPERM;
556                         break;
557                 }
558
559                 if (prev_fp->daccess & (FILE_EXECUTE_LE | FILE_READ_DATA_LE) &&
560                     !(curr_fp->saccess & FILE_SHARE_READ_LE)) {
561                         smb_shared_mode_error(FILE_READ_ERROR,
562                                               prev_fp,
563                                               curr_fp);
564                         rc = -EPERM;
565                         break;
566                 }
567
568                 if (prev_fp->daccess & (FILE_WRITE_DATA_LE | FILE_APPEND_DATA_LE) &&
569                     !(curr_fp->saccess & FILE_SHARE_WRITE_LE)) {
570                         smb_shared_mode_error(FILE_WRITE_ERROR,
571                                               prev_fp,
572                                               curr_fp);
573                         rc = -EPERM;
574                         break;
575                 }
576
577                 if (prev_fp->daccess & FILE_DELETE_LE &&
578                     !(curr_fp->saccess & FILE_SHARE_DELETE_LE)) {
579                         smb_shared_mode_error(FILE_DELETE_ERROR,
580                                               prev_fp,
581                                               curr_fp);
582                         rc = -EPERM;
583                         break;
584                 }
585         }
586         read_unlock(&curr_fp->f_ci->m_lock);
587
588         return rc;
589 }
590
591 bool is_asterisk(char *p)
592 {
593         return p && p[0] == '*';
594 }
595
596 int ksmbd_override_fsids(struct ksmbd_work *work)
597 {
598         struct ksmbd_session *sess = work->sess;
599         struct ksmbd_share_config *share = work->tcon->share_conf;
600         struct cred *cred;
601         struct group_info *gi;
602         unsigned int uid;
603         unsigned int gid;
604
605         uid = user_uid(sess->user);
606         gid = user_gid(sess->user);
607         if (share->force_uid != KSMBD_SHARE_INVALID_UID)
608                 uid = share->force_uid;
609         if (share->force_gid != KSMBD_SHARE_INVALID_GID)
610                 gid = share->force_gid;
611
612         cred = prepare_kernel_cred(NULL);
613         if (!cred)
614                 return -ENOMEM;
615
616         cred->fsuid = make_kuid(current_user_ns(), uid);
617         cred->fsgid = make_kgid(current_user_ns(), gid);
618
619         gi = groups_alloc(0);
620         if (!gi) {
621                 abort_creds(cred);
622                 return -ENOMEM;
623         }
624         set_groups(cred, gi);
625         put_group_info(gi);
626
627         if (!uid_eq(cred->fsuid, GLOBAL_ROOT_UID))
628                 cred->cap_effective = cap_drop_fs_set(cred->cap_effective);
629
630         WARN_ON(work->saved_cred);
631         work->saved_cred = override_creds(cred);
632         if (!work->saved_cred) {
633                 abort_creds(cred);
634                 return -EINVAL;
635         }
636         return 0;
637 }
638
639 void ksmbd_revert_fsids(struct ksmbd_work *work)
640 {
641         const struct cred *cred;
642
643         WARN_ON(!work->saved_cred);
644
645         cred = current_cred();
646         revert_creds(work->saved_cred);
647         put_cred(cred);
648         work->saved_cred = NULL;
649 }
650
651 __le32 smb_map_generic_desired_access(__le32 daccess)
652 {
653         if (daccess & FILE_GENERIC_READ_LE) {
654                 daccess |= cpu_to_le32(GENERIC_READ_FLAGS);
655                 daccess &= ~FILE_GENERIC_READ_LE;
656         }
657
658         if (daccess & FILE_GENERIC_WRITE_LE) {
659                 daccess |= cpu_to_le32(GENERIC_WRITE_FLAGS);
660                 daccess &= ~FILE_GENERIC_WRITE_LE;
661         }
662
663         if (daccess & FILE_GENERIC_EXECUTE_LE) {
664                 daccess |= cpu_to_le32(GENERIC_EXECUTE_FLAGS);
665                 daccess &= ~FILE_GENERIC_EXECUTE_LE;
666         }
667
668         if (daccess & FILE_GENERIC_ALL_LE) {
669                 daccess |= cpu_to_le32(GENERIC_ALL_FLAGS);
670                 daccess &= ~FILE_GENERIC_ALL_LE;
671         }
672
673         return daccess;
674 }