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