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