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