ovl: Do not check for redirect if this is last layer
[linux-2.6-microblaze.git] / fs / overlayfs / namei.c
1 /*
2  * Copyright (C) 2011 Novell Inc.
3  * Copyright (C) 2016 Red Hat, Inc.
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 as published by
7  * the Free Software Foundation.
8  */
9
10 #include <linux/fs.h>
11 #include <linux/cred.h>
12 #include <linux/ctype.h>
13 #include <linux/namei.h>
14 #include <linux/xattr.h>
15 #include <linux/ratelimit.h>
16 #include <linux/mount.h>
17 #include <linux/exportfs.h>
18 #include "overlayfs.h"
19
20 struct ovl_lookup_data {
21         struct qstr name;
22         bool is_dir;
23         bool opaque;
24         bool stop;
25         bool last;
26         char *redirect;
27 };
28
29 static int ovl_check_redirect(struct dentry *dentry, struct ovl_lookup_data *d,
30                               size_t prelen, const char *post)
31 {
32         int res;
33         char *s, *next, *buf = NULL;
34
35         res = vfs_getxattr(dentry, OVL_XATTR_REDIRECT, NULL, 0);
36         if (res < 0) {
37                 if (res == -ENODATA || res == -EOPNOTSUPP)
38                         return 0;
39                 goto fail;
40         }
41         buf = kzalloc(prelen + res + strlen(post) + 1, GFP_KERNEL);
42         if (!buf)
43                 return -ENOMEM;
44
45         if (res == 0)
46                 goto invalid;
47
48         res = vfs_getxattr(dentry, OVL_XATTR_REDIRECT, buf, res);
49         if (res < 0)
50                 goto fail;
51         if (res == 0)
52                 goto invalid;
53         if (buf[0] == '/') {
54                 for (s = buf; *s++ == '/'; s = next) {
55                         next = strchrnul(s, '/');
56                         if (s == next)
57                                 goto invalid;
58                 }
59                 /*
60                  * One of the ancestor path elements in an absolute path
61                  * lookup in ovl_lookup_layer() could have been opaque and
62                  * that will stop further lookup in lower layers (d->stop=true)
63                  * But we have found an absolute redirect in decendant path
64                  * element and that should force continue lookup in lower
65                  * layers (reset d->stop).
66                  */
67                 d->stop = false;
68         } else {
69                 if (strchr(buf, '/') != NULL)
70                         goto invalid;
71
72                 memmove(buf + prelen, buf, res);
73                 memcpy(buf, d->name.name, prelen);
74         }
75
76         strcat(buf, post);
77         kfree(d->redirect);
78         d->redirect = buf;
79         d->name.name = d->redirect;
80         d->name.len = strlen(d->redirect);
81
82         return 0;
83
84 err_free:
85         kfree(buf);
86         return 0;
87 fail:
88         pr_warn_ratelimited("overlayfs: failed to get redirect (%i)\n", res);
89         goto err_free;
90 invalid:
91         pr_warn_ratelimited("overlayfs: invalid redirect (%s)\n", buf);
92         goto err_free;
93 }
94
95 static int ovl_acceptable(void *ctx, struct dentry *dentry)
96 {
97         /*
98          * A non-dir origin may be disconnected, which is fine, because
99          * we only need it for its unique inode number.
100          */
101         if (!d_is_dir(dentry))
102                 return 1;
103
104         /* Don't decode a deleted empty directory */
105         if (d_unhashed(dentry))
106                 return 0;
107
108         /* Check if directory belongs to the layer we are decoding from */
109         return is_subdir(dentry, ((struct vfsmount *)ctx)->mnt_root);
110 }
111
112 /*
113  * Check validity of an overlay file handle buffer.
114  *
115  * Return 0 for a valid file handle.
116  * Return -ENODATA for "origin unknown".
117  * Return <0 for an invalid file handle.
118  */
119 int ovl_check_fh_len(struct ovl_fh *fh, int fh_len)
120 {
121         if (fh_len < sizeof(struct ovl_fh) || fh_len < fh->len)
122                 return -EINVAL;
123
124         if (fh->magic != OVL_FH_MAGIC)
125                 return -EINVAL;
126
127         /* Treat larger version and unknown flags as "origin unknown" */
128         if (fh->version > OVL_FH_VERSION || fh->flags & ~OVL_FH_FLAG_ALL)
129                 return -ENODATA;
130
131         /* Treat endianness mismatch as "origin unknown" */
132         if (!(fh->flags & OVL_FH_FLAG_ANY_ENDIAN) &&
133             (fh->flags & OVL_FH_FLAG_BIG_ENDIAN) != OVL_FH_FLAG_CPU_ENDIAN)
134                 return -ENODATA;
135
136         return 0;
137 }
138
139 static struct ovl_fh *ovl_get_fh(struct dentry *dentry, const char *name)
140 {
141         int res, err;
142         struct ovl_fh *fh = NULL;
143
144         res = vfs_getxattr(dentry, name, NULL, 0);
145         if (res < 0) {
146                 if (res == -ENODATA || res == -EOPNOTSUPP)
147                         return NULL;
148                 goto fail;
149         }
150         /* Zero size value means "copied up but origin unknown" */
151         if (res == 0)
152                 return NULL;
153
154         fh = kzalloc(res, GFP_KERNEL);
155         if (!fh)
156                 return ERR_PTR(-ENOMEM);
157
158         res = vfs_getxattr(dentry, name, fh, res);
159         if (res < 0)
160                 goto fail;
161
162         err = ovl_check_fh_len(fh, res);
163         if (err < 0) {
164                 if (err == -ENODATA)
165                         goto out;
166                 goto invalid;
167         }
168
169         return fh;
170
171 out:
172         kfree(fh);
173         return NULL;
174
175 fail:
176         pr_warn_ratelimited("overlayfs: failed to get origin (%i)\n", res);
177         goto out;
178 invalid:
179         pr_warn_ratelimited("overlayfs: invalid origin (%*phN)\n", res, fh);
180         goto out;
181 }
182
183 struct dentry *ovl_decode_real_fh(struct ovl_fh *fh, struct vfsmount *mnt,
184                                   bool connected)
185 {
186         struct dentry *real;
187         int bytes;
188
189         /*
190          * Make sure that the stored uuid matches the uuid of the lower
191          * layer where file handle will be decoded.
192          */
193         if (!uuid_equal(&fh->uuid, &mnt->mnt_sb->s_uuid))
194                 return NULL;
195
196         bytes = (fh->len - offsetof(struct ovl_fh, fid));
197         real = exportfs_decode_fh(mnt, (struct fid *)fh->fid,
198                                   bytes >> 2, (int)fh->type,
199                                   connected ? ovl_acceptable : NULL, mnt);
200         if (IS_ERR(real)) {
201                 /*
202                  * Treat stale file handle to lower file as "origin unknown".
203                  * upper file handle could become stale when upper file is
204                  * unlinked and this information is needed to handle stale
205                  * index entries correctly.
206                  */
207                 if (real == ERR_PTR(-ESTALE) &&
208                     !(fh->flags & OVL_FH_FLAG_PATH_UPPER))
209                         real = NULL;
210                 return real;
211         }
212
213         if (ovl_dentry_weird(real)) {
214                 dput(real);
215                 return NULL;
216         }
217
218         return real;
219 }
220
221 static bool ovl_is_opaquedir(struct dentry *dentry)
222 {
223         return ovl_check_dir_xattr(dentry, OVL_XATTR_OPAQUE);
224 }
225
226 static int ovl_lookup_single(struct dentry *base, struct ovl_lookup_data *d,
227                              const char *name, unsigned int namelen,
228                              size_t prelen, const char *post,
229                              struct dentry **ret)
230 {
231         struct dentry *this;
232         int err;
233
234         this = lookup_one_len_unlocked(name, base, namelen);
235         if (IS_ERR(this)) {
236                 err = PTR_ERR(this);
237                 this = NULL;
238                 if (err == -ENOENT || err == -ENAMETOOLONG)
239                         goto out;
240                 goto out_err;
241         }
242         if (!this->d_inode)
243                 goto put_and_out;
244
245         if (ovl_dentry_weird(this)) {
246                 /* Don't support traversing automounts and other weirdness */
247                 err = -EREMOTE;
248                 goto out_err;
249         }
250         if (ovl_is_whiteout(this)) {
251                 d->stop = d->opaque = true;
252                 goto put_and_out;
253         }
254         if (!d_can_lookup(this)) {
255                 d->stop = true;
256                 if (d->is_dir)
257                         goto put_and_out;
258                 goto out;
259         }
260         d->is_dir = true;
261         if (d->last)
262                 goto out;
263
264         if (ovl_is_opaquedir(this)) {
265                 d->stop = d->opaque = true;
266                 goto out;
267         }
268         err = ovl_check_redirect(this, d, prelen, post);
269         if (err)
270                 goto out_err;
271 out:
272         *ret = this;
273         return 0;
274
275 put_and_out:
276         dput(this);
277         this = NULL;
278         goto out;
279
280 out_err:
281         dput(this);
282         return err;
283 }
284
285 static int ovl_lookup_layer(struct dentry *base, struct ovl_lookup_data *d,
286                             struct dentry **ret)
287 {
288         /* Counting down from the end, since the prefix can change */
289         size_t rem = d->name.len - 1;
290         struct dentry *dentry = NULL;
291         int err;
292
293         if (d->name.name[0] != '/')
294                 return ovl_lookup_single(base, d, d->name.name, d->name.len,
295                                          0, "", ret);
296
297         while (!IS_ERR_OR_NULL(base) && d_can_lookup(base)) {
298                 const char *s = d->name.name + d->name.len - rem;
299                 const char *next = strchrnul(s, '/');
300                 size_t thislen = next - s;
301                 bool end = !next[0];
302
303                 /* Verify we did not go off the rails */
304                 if (WARN_ON(s[-1] != '/'))
305                         return -EIO;
306
307                 err = ovl_lookup_single(base, d, s, thislen,
308                                         d->name.len - rem, next, &base);
309                 dput(dentry);
310                 if (err)
311                         return err;
312                 dentry = base;
313                 if (end)
314                         break;
315
316                 rem -= thislen + 1;
317
318                 if (WARN_ON(rem >= d->name.len))
319                         return -EIO;
320         }
321         *ret = dentry;
322         return 0;
323 }
324
325
326 int ovl_check_origin_fh(struct ovl_fs *ofs, struct ovl_fh *fh, bool connected,
327                         struct dentry *upperdentry, struct ovl_path **stackp)
328 {
329         struct dentry *origin = NULL;
330         int i;
331
332         for (i = 0; i < ofs->numlower; i++) {
333                 origin = ovl_decode_real_fh(fh, ofs->lower_layers[i].mnt,
334                                             connected);
335                 if (origin)
336                         break;
337         }
338
339         if (!origin)
340                 return -ESTALE;
341         else if (IS_ERR(origin))
342                 return PTR_ERR(origin);
343
344         if (upperdentry && !ovl_is_whiteout(upperdentry) &&
345             ((d_inode(origin)->i_mode ^ d_inode(upperdentry)->i_mode) & S_IFMT))
346                 goto invalid;
347
348         if (!*stackp)
349                 *stackp = kmalloc(sizeof(struct ovl_path), GFP_KERNEL);
350         if (!*stackp) {
351                 dput(origin);
352                 return -ENOMEM;
353         }
354         **stackp = (struct ovl_path){
355                 .dentry = origin,
356                 .layer = &ofs->lower_layers[i]
357         };
358
359         return 0;
360
361 invalid:
362         pr_warn_ratelimited("overlayfs: invalid origin (%pd2, ftype=%x, origin ftype=%x).\n",
363                             upperdentry, d_inode(upperdentry)->i_mode & S_IFMT,
364                             d_inode(origin)->i_mode & S_IFMT);
365         dput(origin);
366         return -EIO;
367 }
368
369 static int ovl_check_origin(struct ovl_fs *ofs, struct dentry *upperdentry,
370                             struct ovl_path **stackp, unsigned int *ctrp)
371 {
372         struct ovl_fh *fh = ovl_get_fh(upperdentry, OVL_XATTR_ORIGIN);
373         int err;
374
375         if (IS_ERR_OR_NULL(fh))
376                 return PTR_ERR(fh);
377
378         err = ovl_check_origin_fh(ofs, fh, false, upperdentry, stackp);
379         kfree(fh);
380
381         if (err) {
382                 if (err == -ESTALE)
383                         return 0;
384                 return err;
385         }
386
387         if (WARN_ON(*ctrp))
388                 return -EIO;
389
390         *ctrp = 1;
391         return 0;
392 }
393
394 /*
395  * Verify that @fh matches the file handle stored in xattr @name.
396  * Return 0 on match, -ESTALE on mismatch, < 0 on error.
397  */
398 static int ovl_verify_fh(struct dentry *dentry, const char *name,
399                          const struct ovl_fh *fh)
400 {
401         struct ovl_fh *ofh = ovl_get_fh(dentry, name);
402         int err = 0;
403
404         if (!ofh)
405                 return -ENODATA;
406
407         if (IS_ERR(ofh))
408                 return PTR_ERR(ofh);
409
410         if (fh->len != ofh->len || memcmp(fh, ofh, fh->len))
411                 err = -ESTALE;
412
413         kfree(ofh);
414         return err;
415 }
416
417 /*
418  * Verify that @real dentry matches the file handle stored in xattr @name.
419  *
420  * If @set is true and there is no stored file handle, encode @real and store
421  * file handle in xattr @name.
422  *
423  * Return 0 on match, -ESTALE on mismatch, -ENODATA on no xattr, < 0 on error.
424  */
425 int ovl_verify_set_fh(struct dentry *dentry, const char *name,
426                       struct dentry *real, bool is_upper, bool set)
427 {
428         struct inode *inode;
429         struct ovl_fh *fh;
430         int err;
431
432         fh = ovl_encode_real_fh(real, is_upper);
433         err = PTR_ERR(fh);
434         if (IS_ERR(fh))
435                 goto fail;
436
437         err = ovl_verify_fh(dentry, name, fh);
438         if (set && err == -ENODATA)
439                 err = ovl_do_setxattr(dentry, name, fh, fh->len, 0);
440         if (err)
441                 goto fail;
442
443 out:
444         kfree(fh);
445         return err;
446
447 fail:
448         inode = d_inode(real);
449         pr_warn_ratelimited("overlayfs: failed to verify %s (%pd2, ino=%lu, err=%i)\n",
450                             is_upper ? "upper" : "origin", real,
451                             inode ? inode->i_ino : 0, err);
452         goto out;
453 }
454
455 /* Get upper dentry from index */
456 struct dentry *ovl_index_upper(struct ovl_fs *ofs, struct dentry *index)
457 {
458         struct ovl_fh *fh;
459         struct dentry *upper;
460
461         if (!d_is_dir(index))
462                 return dget(index);
463
464         fh = ovl_get_fh(index, OVL_XATTR_UPPER);
465         if (IS_ERR_OR_NULL(fh))
466                 return ERR_CAST(fh);
467
468         upper = ovl_decode_real_fh(fh, ofs->upper_mnt, true);
469         kfree(fh);
470
471         if (IS_ERR_OR_NULL(upper))
472                 return upper ?: ERR_PTR(-ESTALE);
473
474         if (!d_is_dir(upper)) {
475                 pr_warn_ratelimited("overlayfs: invalid index upper (%pd2, upper=%pd2).\n",
476                                     index, upper);
477                 dput(upper);
478                 return ERR_PTR(-EIO);
479         }
480
481         return upper;
482 }
483
484 /* Is this a leftover from create/whiteout of directory index entry? */
485 static bool ovl_is_temp_index(struct dentry *index)
486 {
487         return index->d_name.name[0] == '#';
488 }
489
490 /*
491  * Verify that an index entry name matches the origin file handle stored in
492  * OVL_XATTR_ORIGIN and that origin file handle can be decoded to lower path.
493  * Return 0 on match, -ESTALE on mismatch or stale origin, < 0 on error.
494  */
495 int ovl_verify_index(struct ovl_fs *ofs, struct dentry *index)
496 {
497         struct ovl_fh *fh = NULL;
498         size_t len;
499         struct ovl_path origin = { };
500         struct ovl_path *stack = &origin;
501         struct dentry *upper = NULL;
502         int err;
503
504         if (!d_inode(index))
505                 return 0;
506
507         /* Cleanup leftover from index create/cleanup attempt */
508         err = -ESTALE;
509         if (ovl_is_temp_index(index))
510                 goto fail;
511
512         err = -EINVAL;
513         if (index->d_name.len < sizeof(struct ovl_fh)*2)
514                 goto fail;
515
516         err = -ENOMEM;
517         len = index->d_name.len / 2;
518         fh = kzalloc(len, GFP_KERNEL);
519         if (!fh)
520                 goto fail;
521
522         err = -EINVAL;
523         if (hex2bin((u8 *)fh, index->d_name.name, len))
524                 goto fail;
525
526         err = ovl_check_fh_len(fh, len);
527         if (err)
528                 goto fail;
529
530         /*
531          * Whiteout index entries are used as an indication that an exported
532          * overlay file handle should be treated as stale (i.e. after unlink
533          * of the overlay inode). These entries contain no origin xattr.
534          */
535         if (ovl_is_whiteout(index))
536                 goto out;
537
538         /*
539          * Verifying directory index entries are not stale is expensive, so
540          * only verify stale dir index if NFS export is enabled.
541          */
542         if (d_is_dir(index) && !ofs->config.nfs_export)
543                 goto out;
544
545         /*
546          * Directory index entries should have 'upper' xattr pointing to the
547          * real upper dir. Non-dir index entries are hardlinks to the upper
548          * real inode. For non-dir index, we can read the copy up origin xattr
549          * directly from the index dentry, but for dir index we first need to
550          * decode the upper directory.
551          */
552         upper = ovl_index_upper(ofs, index);
553         if (IS_ERR_OR_NULL(upper)) {
554                 err = PTR_ERR(upper);
555                 /*
556                  * Directory index entries with no 'upper' xattr need to be
557                  * removed. When dir index entry has a stale 'upper' xattr,
558                  * we assume that upper dir was removed and we treat the dir
559                  * index as orphan entry that needs to be whited out.
560                  */
561                 if (err == -ESTALE)
562                         goto orphan;
563                 else if (!err)
564                         err = -ESTALE;
565                 goto fail;
566         }
567
568         err = ovl_verify_fh(upper, OVL_XATTR_ORIGIN, fh);
569         dput(upper);
570         if (err)
571                 goto fail;
572
573         /* Check if non-dir index is orphan and don't warn before cleaning it */
574         if (!d_is_dir(index) && d_inode(index)->i_nlink == 1) {
575                 err = ovl_check_origin_fh(ofs, fh, false, index, &stack);
576                 if (err)
577                         goto fail;
578
579                 if (ovl_get_nlink(origin.dentry, index, 0) == 0)
580                         goto orphan;
581         }
582
583 out:
584         dput(origin.dentry);
585         kfree(fh);
586         return err;
587
588 fail:
589         pr_warn_ratelimited("overlayfs: failed to verify index (%pd2, ftype=%x, err=%i)\n",
590                             index, d_inode(index)->i_mode & S_IFMT, err);
591         goto out;
592
593 orphan:
594         pr_warn_ratelimited("overlayfs: orphan index entry (%pd2, ftype=%x, nlink=%u)\n",
595                             index, d_inode(index)->i_mode & S_IFMT,
596                             d_inode(index)->i_nlink);
597         err = -ENOENT;
598         goto out;
599 }
600
601 static int ovl_get_index_name_fh(struct ovl_fh *fh, struct qstr *name)
602 {
603         char *n, *s;
604
605         n = kzalloc(fh->len * 2, GFP_KERNEL);
606         if (!n)
607                 return -ENOMEM;
608
609         s  = bin2hex(n, fh, fh->len);
610         *name = (struct qstr) QSTR_INIT(n, s - n);
611
612         return 0;
613
614 }
615
616 /*
617  * Lookup in indexdir for the index entry of a lower real inode or a copy up
618  * origin inode. The index entry name is the hex representation of the lower
619  * inode file handle.
620  *
621  * If the index dentry in negative, then either no lower aliases have been
622  * copied up yet, or aliases have been copied up in older kernels and are
623  * not indexed.
624  *
625  * If the index dentry for a copy up origin inode is positive, but points
626  * to an inode different than the upper inode, then either the upper inode
627  * has been copied up and not indexed or it was indexed, but since then
628  * index dir was cleared. Either way, that index cannot be used to indentify
629  * the overlay inode.
630  */
631 int ovl_get_index_name(struct dentry *origin, struct qstr *name)
632 {
633         struct ovl_fh *fh;
634         int err;
635
636         fh = ovl_encode_real_fh(origin, false);
637         if (IS_ERR(fh))
638                 return PTR_ERR(fh);
639
640         err = ovl_get_index_name_fh(fh, name);
641
642         kfree(fh);
643         return err;
644 }
645
646 /* Lookup index by file handle for NFS export */
647 struct dentry *ovl_get_index_fh(struct ovl_fs *ofs, struct ovl_fh *fh)
648 {
649         struct dentry *index;
650         struct qstr name;
651         int err;
652
653         err = ovl_get_index_name_fh(fh, &name);
654         if (err)
655                 return ERR_PTR(err);
656
657         index = lookup_one_len_unlocked(name.name, ofs->indexdir, name.len);
658         kfree(name.name);
659         if (IS_ERR(index)) {
660                 if (PTR_ERR(index) == -ENOENT)
661                         index = NULL;
662                 return index;
663         }
664
665         if (d_is_negative(index))
666                 err = 0;
667         else if (ovl_is_whiteout(index))
668                 err = -ESTALE;
669         else if (ovl_dentry_weird(index))
670                 err = -EIO;
671         else
672                 return index;
673
674         dput(index);
675         return ERR_PTR(err);
676 }
677
678 struct dentry *ovl_lookup_index(struct ovl_fs *ofs, struct dentry *upper,
679                                 struct dentry *origin, bool verify)
680 {
681         struct dentry *index;
682         struct inode *inode;
683         struct qstr name;
684         bool is_dir = d_is_dir(origin);
685         int err;
686
687         err = ovl_get_index_name(origin, &name);
688         if (err)
689                 return ERR_PTR(err);
690
691         index = lookup_one_len_unlocked(name.name, ofs->indexdir, name.len);
692         if (IS_ERR(index)) {
693                 err = PTR_ERR(index);
694                 if (err == -ENOENT) {
695                         index = NULL;
696                         goto out;
697                 }
698                 pr_warn_ratelimited("overlayfs: failed inode index lookup (ino=%lu, key=%*s, err=%i);\n"
699                                     "overlayfs: mount with '-o index=off' to disable inodes index.\n",
700                                     d_inode(origin)->i_ino, name.len, name.name,
701                                     err);
702                 goto out;
703         }
704
705         inode = d_inode(index);
706         if (d_is_negative(index)) {
707                 goto out_dput;
708         } else if (ovl_is_whiteout(index) && !verify) {
709                 /*
710                  * When index lookup is called with !verify for decoding an
711                  * overlay file handle, a whiteout index implies that decode
712                  * should treat file handle as stale and no need to print a
713                  * warning about it.
714                  */
715                 dput(index);
716                 index = ERR_PTR(-ESTALE);
717                 goto out;
718         } else if (ovl_dentry_weird(index) || ovl_is_whiteout(index) ||
719                    ((inode->i_mode ^ d_inode(origin)->i_mode) & S_IFMT)) {
720                 /*
721                  * Index should always be of the same file type as origin
722                  * except for the case of a whiteout index. A whiteout
723                  * index should only exist if all lower aliases have been
724                  * unlinked, which means that finding a lower origin on lookup
725                  * whose index is a whiteout should be treated as an error.
726                  */
727                 pr_warn_ratelimited("overlayfs: bad index found (index=%pd2, ftype=%x, origin ftype=%x).\n",
728                                     index, d_inode(index)->i_mode & S_IFMT,
729                                     d_inode(origin)->i_mode & S_IFMT);
730                 goto fail;
731         } else if (is_dir && verify) {
732                 if (!upper) {
733                         pr_warn_ratelimited("overlayfs: suspected uncovered redirected dir found (origin=%pd2, index=%pd2).\n",
734                                             origin, index);
735                         goto fail;
736                 }
737
738                 /* Verify that dir index 'upper' xattr points to upper dir */
739                 err = ovl_verify_upper(index, upper, false);
740                 if (err) {
741                         if (err == -ESTALE) {
742                                 pr_warn_ratelimited("overlayfs: suspected multiply redirected dir found (upper=%pd2, origin=%pd2, index=%pd2).\n",
743                                                     upper, origin, index);
744                         }
745                         goto fail;
746                 }
747         } else if (upper && d_inode(upper) != inode) {
748                 goto out_dput;
749         }
750 out:
751         kfree(name.name);
752         return index;
753
754 out_dput:
755         dput(index);
756         index = NULL;
757         goto out;
758
759 fail:
760         dput(index);
761         index = ERR_PTR(-EIO);
762         goto out;
763 }
764
765 /*
766  * Returns next layer in stack starting from top.
767  * Returns -1 if this is the last layer.
768  */
769 int ovl_path_next(int idx, struct dentry *dentry, struct path *path)
770 {
771         struct ovl_entry *oe = dentry->d_fsdata;
772
773         BUG_ON(idx < 0);
774         if (idx == 0) {
775                 ovl_path_upper(dentry, path);
776                 if (path->dentry)
777                         return oe->numlower ? 1 : -1;
778                 idx++;
779         }
780         BUG_ON(idx > oe->numlower);
781         path->dentry = oe->lowerstack[idx - 1].dentry;
782         path->mnt = oe->lowerstack[idx - 1].layer->mnt;
783
784         return (idx < oe->numlower) ? idx + 1 : -1;
785 }
786
787 /* Fix missing 'origin' xattr */
788 static int ovl_fix_origin(struct dentry *dentry, struct dentry *lower,
789                           struct dentry *upper)
790 {
791         int err;
792
793         if (ovl_check_origin_xattr(upper))
794                 return 0;
795
796         err = ovl_want_write(dentry);
797         if (err)
798                 return err;
799
800         err = ovl_set_origin(dentry, lower, upper);
801         if (!err)
802                 err = ovl_set_impure(dentry->d_parent, upper->d_parent);
803
804         ovl_drop_write(dentry);
805         return err;
806 }
807
808 struct dentry *ovl_lookup(struct inode *dir, struct dentry *dentry,
809                           unsigned int flags)
810 {
811         struct ovl_entry *oe;
812         const struct cred *old_cred;
813         struct ovl_fs *ofs = dentry->d_sb->s_fs_info;
814         struct ovl_entry *poe = dentry->d_parent->d_fsdata;
815         struct ovl_entry *roe = dentry->d_sb->s_root->d_fsdata;
816         struct ovl_path *stack = NULL;
817         struct dentry *upperdir, *upperdentry = NULL;
818         struct dentry *origin = NULL;
819         struct dentry *index = NULL;
820         unsigned int ctr = 0;
821         struct inode *inode = NULL;
822         bool upperopaque = false;
823         char *upperredirect = NULL;
824         struct dentry *this;
825         unsigned int i;
826         int err;
827         struct ovl_lookup_data d = {
828                 .name = dentry->d_name,
829                 .is_dir = false,
830                 .opaque = false,
831                 .stop = false,
832                 .last = ofs->config.redirect_follow ? false : !poe->numlower,
833                 .redirect = NULL,
834         };
835
836         if (dentry->d_name.len > ofs->namelen)
837                 return ERR_PTR(-ENAMETOOLONG);
838
839         old_cred = ovl_override_creds(dentry->d_sb);
840         upperdir = ovl_dentry_upper(dentry->d_parent);
841         if (upperdir) {
842                 err = ovl_lookup_layer(upperdir, &d, &upperdentry);
843                 if (err)
844                         goto out;
845
846                 if (upperdentry && unlikely(ovl_dentry_remote(upperdentry))) {
847                         dput(upperdentry);
848                         err = -EREMOTE;
849                         goto out;
850                 }
851                 if (upperdentry && !d.is_dir) {
852                         BUG_ON(!d.stop || d.redirect);
853                         /*
854                          * Lookup copy up origin by decoding origin file handle.
855                          * We may get a disconnected dentry, which is fine,
856                          * because we only need to hold the origin inode in
857                          * cache and use its inode number.  We may even get a
858                          * connected dentry, that is not under any of the lower
859                          * layers root.  That is also fine for using it's inode
860                          * number - it's the same as if we held a reference
861                          * to a dentry in lower layer that was moved under us.
862                          */
863                         err = ovl_check_origin(ofs, upperdentry, &stack, &ctr);
864                         if (err)
865                                 goto out_put_upper;
866                 }
867
868                 if (d.redirect) {
869                         err = -ENOMEM;
870                         upperredirect = kstrdup(d.redirect, GFP_KERNEL);
871                         if (!upperredirect)
872                                 goto out_put_upper;
873                         if (d.redirect[0] == '/')
874                                 poe = roe;
875                 }
876                 upperopaque = d.opaque;
877         }
878
879         if (!d.stop && poe->numlower) {
880                 err = -ENOMEM;
881                 stack = kcalloc(ofs->numlower, sizeof(struct ovl_path),
882                                 GFP_KERNEL);
883                 if (!stack)
884                         goto out_put_upper;
885         }
886
887         for (i = 0; !d.stop && i < poe->numlower; i++) {
888                 struct ovl_path lower = poe->lowerstack[i];
889
890                 if (!ofs->config.redirect_follow)
891                         d.last = i == poe->numlower - 1;
892                 else
893                         d.last = lower.layer->idx == roe->numlower;
894
895                 err = ovl_lookup_layer(lower.dentry, &d, &this);
896                 if (err)
897                         goto out_put;
898
899                 if (!this)
900                         continue;
901
902                 /*
903                  * If no origin fh is stored in upper of a merge dir, store fh
904                  * of lower dir and set upper parent "impure".
905                  */
906                 if (upperdentry && !ctr && !ofs->noxattr) {
907                         err = ovl_fix_origin(dentry, this, upperdentry);
908                         if (err) {
909                                 dput(this);
910                                 goto out_put;
911                         }
912                 }
913
914                 /*
915                  * When "verify_lower" feature is enabled, do not merge with a
916                  * lower dir that does not match a stored origin xattr. In any
917                  * case, only verified origin is used for index lookup.
918                  */
919                 if (upperdentry && !ctr && ovl_verify_lower(dentry->d_sb)) {
920                         err = ovl_verify_origin(upperdentry, this, false);
921                         if (err) {
922                                 dput(this);
923                                 break;
924                         }
925
926                         /* Bless lower dir as verified origin */
927                         origin = this;
928                 }
929
930                 stack[ctr].dentry = this;
931                 stack[ctr].layer = lower.layer;
932                 ctr++;
933
934                 /*
935                  * Following redirects can have security consequences: it's like
936                  * a symlink into the lower layer without the permission checks.
937                  * This is only a problem if the upper layer is untrusted (e.g
938                  * comes from an USB drive).  This can allow a non-readable file
939                  * or directory to become readable.
940                  *
941                  * Only following redirects when redirects are enabled disables
942                  * this attack vector when not necessary.
943                  */
944                 err = -EPERM;
945                 if (d.redirect && !ofs->config.redirect_follow) {
946                         pr_warn_ratelimited("overlayfs: refusing to follow redirect for (%pd2)\n",
947                                             dentry);
948                         goto out_put;
949                 }
950
951                 if (d.stop)
952                         break;
953
954                 if (d.redirect && d.redirect[0] == '/' && poe != roe) {
955                         poe = roe;
956                         /* Find the current layer on the root dentry */
957                         i = lower.layer->idx - 1;
958                 }
959         }
960
961         /*
962          * Lookup index by lower inode and verify it matches upper inode.
963          * We only trust dir index if we verified that lower dir matches
964          * origin, otherwise dir index entries may be inconsistent and we
965          * ignore them. Always lookup index of non-dir and non-upper.
966          */
967         if (ctr && (!upperdentry || !d.is_dir))
968                 origin = stack[0].dentry;
969
970         if (origin && ovl_indexdir(dentry->d_sb) &&
971             (!d.is_dir || ovl_index_all(dentry->d_sb))) {
972                 index = ovl_lookup_index(ofs, upperdentry, origin, true);
973                 if (IS_ERR(index)) {
974                         err = PTR_ERR(index);
975                         index = NULL;
976                         goto out_put;
977                 }
978         }
979
980         oe = ovl_alloc_entry(ctr);
981         err = -ENOMEM;
982         if (!oe)
983                 goto out_put;
984
985         memcpy(oe->lowerstack, stack, sizeof(struct ovl_path) * ctr);
986         dentry->d_fsdata = oe;
987
988         if (upperopaque)
989                 ovl_dentry_set_opaque(dentry);
990
991         if (upperdentry)
992                 ovl_dentry_set_upper_alias(dentry);
993         else if (index)
994                 upperdentry = dget(index);
995
996         if (upperdentry || ctr) {
997                 if (ctr)
998                         origin = stack[0].dentry;
999                 inode = ovl_get_inode(dentry->d_sb, upperdentry, origin, index,
1000                                       ctr);
1001                 err = PTR_ERR(inode);
1002                 if (IS_ERR(inode))
1003                         goto out_free_oe;
1004
1005                 OVL_I(inode)->redirect = upperredirect;
1006                 if (index)
1007                         ovl_set_flag(OVL_INDEX, inode);
1008         }
1009
1010         revert_creds(old_cred);
1011         dput(index);
1012         kfree(stack);
1013         kfree(d.redirect);
1014         return d_splice_alias(inode, dentry);
1015
1016 out_free_oe:
1017         dentry->d_fsdata = NULL;
1018         kfree(oe);
1019 out_put:
1020         dput(index);
1021         for (i = 0; i < ctr; i++)
1022                 dput(stack[i].dentry);
1023         kfree(stack);
1024 out_put_upper:
1025         dput(upperdentry);
1026         kfree(upperredirect);
1027 out:
1028         kfree(d.redirect);
1029         revert_creds(old_cred);
1030         return ERR_PTR(err);
1031 }
1032
1033 bool ovl_lower_positive(struct dentry *dentry)
1034 {
1035         struct ovl_entry *poe = dentry->d_parent->d_fsdata;
1036         const struct qstr *name = &dentry->d_name;
1037         const struct cred *old_cred;
1038         unsigned int i;
1039         bool positive = false;
1040         bool done = false;
1041
1042         /*
1043          * If dentry is negative, then lower is positive iff this is a
1044          * whiteout.
1045          */
1046         if (!dentry->d_inode)
1047                 return ovl_dentry_is_opaque(dentry);
1048
1049         /* Negative upper -> positive lower */
1050         if (!ovl_dentry_upper(dentry))
1051                 return true;
1052
1053         old_cred = ovl_override_creds(dentry->d_sb);
1054         /* Positive upper -> have to look up lower to see whether it exists */
1055         for (i = 0; !done && !positive && i < poe->numlower; i++) {
1056                 struct dentry *this;
1057                 struct dentry *lowerdir = poe->lowerstack[i].dentry;
1058
1059                 this = lookup_one_len_unlocked(name->name, lowerdir,
1060                                                name->len);
1061                 if (IS_ERR(this)) {
1062                         switch (PTR_ERR(this)) {
1063                         case -ENOENT:
1064                         case -ENAMETOOLONG:
1065                                 break;
1066
1067                         default:
1068                                 /*
1069                                  * Assume something is there, we just couldn't
1070                                  * access it.
1071                                  */
1072                                 positive = true;
1073                                 break;
1074                         }
1075                 } else {
1076                         if (this->d_inode) {
1077                                 positive = !ovl_is_whiteout(this);
1078                                 done = true;
1079                         }
1080                         dput(this);
1081                 }
1082         }
1083         revert_creds(old_cred);
1084
1085         return positive;
1086 }