user_namespace.c 33.3 KB
Newer Older
1 2 3 4 5 6 7
/*
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU General Public License as
 *  published by the Free Software Foundation, version 2 of the
 *  License.
 */

8
#include <linux/export.h>
9
#include <linux/nsproxy.h>
10
#include <linux/slab.h>
11
#include <linux/sched/signal.h>
12
#include <linux/user_namespace.h>
13
#include <linux/proc_ns.h>
14
#include <linux/highuid.h>
15
#include <linux/cred.h>
16
#include <linux/securebits.h>
17 18 19 20 21 22 23
#include <linux/keyctl.h>
#include <linux/key-type.h>
#include <keys/user-type.h>
#include <linux/seq_file.h>
#include <linux/fs.h>
#include <linux/uaccess.h>
#include <linux/ctype.h>
24
#include <linux/projid.h>
25
#include <linux/fs_struct.h>
26 27
#include <linux/bsearch.h>
#include <linux/sort.h>
28

29
static struct kmem_cache *user_ns_cachep __read_mostly;
30
static DEFINE_MUTEX(userns_state_mutex);
31

32 33
static bool new_idmap_permitted(const struct file *file,
				struct user_namespace *ns, int cap_setid,
34
				struct uid_gid_map *map);
35
static void free_user_ns(struct work_struct *work);
36

37 38 39 40 41 42 43 44 45 46
static struct ucounts *inc_user_namespaces(struct user_namespace *ns, kuid_t uid)
{
	return inc_ucount(ns, uid, UCOUNT_USER_NAMESPACES);
}

static void dec_user_namespaces(struct ucounts *ucounts)
{
	return dec_ucount(ucounts, UCOUNT_USER_NAMESPACES);
}

47 48 49 50 51 52 53 54 55
static void set_cred_user_ns(struct cred *cred, struct user_namespace *user_ns)
{
	/* Start with the same capabilities as init but useless for doing
	 * anything as the capabilities are bound to the new user namespace.
	 */
	cred->securebits = SECUREBITS_DEFAULT;
	cred->cap_inheritable = CAP_EMPTY_SET;
	cred->cap_permitted = CAP_FULL_SET;
	cred->cap_effective = CAP_FULL_SET;
56
	cred->cap_ambient = CAP_EMPTY_SET;
57 58 59 60 61 62 63 64 65
	cred->cap_bset = CAP_FULL_SET;
#ifdef CONFIG_KEYS
	key_put(cred->request_key_auth);
	cred->request_key_auth = NULL;
#endif
	/* tgcred will be cleared in our caller bc CLONE_THREAD won't be set */
	cred->user_ns = user_ns;
}

S
Serge E. Hallyn 已提交
66
/*
67 68 69 70 71 72
 * Create a new user namespace, deriving the creator from the user in the
 * passed credentials, and replacing that user with the new root user for the
 * new namespace.
 *
 * This is called by copy_creds(), which will finish setting the target task's
 * credentials.
S
Serge E. Hallyn 已提交
73
 */
74
int create_user_ns(struct cred *new)
S
Serge E. Hallyn 已提交
75
{
76
	struct user_namespace *ns, *parent_ns = new->user_ns;
77 78
	kuid_t owner = new->euid;
	kgid_t group = new->egid;
79
	struct ucounts *ucounts;
80
	int ret, i;
81

82
	ret = -ENOSPC;
83
	if (parent_ns->level > 32)
84 85
		goto fail;

86 87
	ucounts = inc_user_namespaces(parent_ns, owner);
	if (!ucounts)
88
		goto fail;
89

90 91 92 93 94 95
	/*
	 * Verify that we can not violate the policy of which files
	 * may be accessed that is specified by the root directory,
	 * by verifing that the root directory is at the root of the
	 * mount namespace which allows all files to be accessed.
	 */
96
	ret = -EPERM;
97
	if (current_chrooted())
98
		goto fail_dec;
99

100 101 102 103
	/* The creator needs a mapping in the parent user namespace
	 * or else we won't be able to reasonably tell userspace who
	 * created a user_namespace.
	 */
104
	ret = -EPERM;
105 106
	if (!kuid_has_mapping(parent_ns, owner) ||
	    !kgid_has_mapping(parent_ns, group))
107
		goto fail_dec;
S
Serge E. Hallyn 已提交
108

109
	ret = -ENOMEM;
110
	ns = kmem_cache_zalloc(user_ns_cachep, GFP_KERNEL);
S
Serge E. Hallyn 已提交
111
	if (!ns)
112
		goto fail_dec;
S
Serge E. Hallyn 已提交
113

A
Al Viro 已提交
114
	ret = ns_alloc_inum(&ns->ns);
115 116
	if (ret)
		goto fail_free;
117
	ns->ns.ops = &userns_operations;
118

119
	atomic_set(&ns->count, 1);
120
	/* Leave the new->user_ns reference with the new user namespace. */
121
	ns->parent = parent_ns;
122
	ns->level = parent_ns->level + 1;
123 124
	ns->owner = owner;
	ns->group = group;
125
	INIT_WORK(&ns->work, free_user_ns);
126 127 128
	for (i = 0; i < UCOUNT_COUNTS; i++) {
		ns->ucount_max[i] = INT_MAX;
	}
129
	ns->ucounts = ucounts;
130

131 132 133 134 135
	/* Inherit USERNS_SETGROUPS_ALLOWED from our parent */
	mutex_lock(&userns_state_mutex);
	ns->flags = parent_ns->flags;
	mutex_unlock(&userns_state_mutex);

136 137 138
#ifdef CONFIG_PERSISTENT_KEYRINGS
	init_rwsem(&ns->persistent_keyring_register_sem);
#endif
139 140 141 142 143
	ret = -ENOMEM;
	if (!setup_userns_sysctls(ns))
		goto fail_keyring;

	set_cred_user_ns(new, ns);
144
	return 0;
145 146 147 148 149
fail_keyring:
#ifdef CONFIG_PERSISTENT_KEYRINGS
	key_put(ns->persistent_keyring_register);
#endif
	ns_free_inum(&ns->ns);
150
fail_free:
151
	kmem_cache_free(user_ns_cachep, ns);
152
fail_dec:
153
	dec_user_namespaces(ucounts);
154
fail:
155
	return ret;
156 157
}

158 159 160
int unshare_userns(unsigned long unshare_flags, struct cred **new_cred)
{
	struct cred *cred;
161
	int err = -ENOMEM;
162 163 164 165 166

	if (!(unshare_flags & CLONE_NEWUSER))
		return 0;

	cred = prepare_creds();
167 168 169 170 171 172 173
	if (cred) {
		err = create_user_ns(cred);
		if (err)
			put_cred(cred);
		else
			*new_cred = cred;
	}
174

175
	return err;
176 177
}

178
static void free_user_ns(struct work_struct *work)
179
{
180 181
	struct user_namespace *parent, *ns =
		container_of(work, struct user_namespace, work);
182

183
	do {
184
		struct ucounts *ucounts = ns->ucounts;
185
		parent = ns->parent;
186 187 188 189 190 191 192 193 194 195 196 197
		if (ns->gid_map.nr_extents > UID_GID_MAP_MAX_BASE_EXTENTS) {
			kfree(ns->gid_map.forward);
			kfree(ns->gid_map.reverse);
		}
		if (ns->uid_map.nr_extents > UID_GID_MAP_MAX_BASE_EXTENTS) {
			kfree(ns->uid_map.forward);
			kfree(ns->uid_map.reverse);
		}
		if (ns->projid_map.nr_extents > UID_GID_MAP_MAX_BASE_EXTENTS) {
			kfree(ns->projid_map.forward);
			kfree(ns->projid_map.reverse);
		}
198
		retire_userns_sysctls(ns);
199 200 201
#ifdef CONFIG_PERSISTENT_KEYRINGS
		key_put(ns->persistent_keyring_register);
#endif
A
Al Viro 已提交
202
		ns_free_inum(&ns->ns);
203
		kmem_cache_free(user_ns_cachep, ns);
204
		dec_user_namespaces(ucounts);
205 206
		ns = parent;
	} while (atomic_dec_and_test(&parent->count));
207
}
208 209 210 211 212 213

void __put_user_ns(struct user_namespace *ns)
{
	schedule_work(&ns->work);
}
EXPORT_SYMBOL(__put_user_ns);
214

215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
/**
 * idmap_key struct holds the information necessary to find an idmapping in a
 * sorted idmap array. It is passed to cmp_map_id() as first argument.
 */
struct idmap_key {
	bool map_up; /* true  -> id from kid; false -> kid from id */
	u32 id; /* id to find */
	u32 count; /* == 0 unless used with map_id_range_down() */
};

/**
 * cmp_map_id - Function to be passed to bsearch() to find the requested
 * idmapping. Expects struct idmap_key to be passed via @k.
 */
static int cmp_map_id(const void *k, const void *e)
{
	u32 first, last, id2;
	const struct idmap_key *key = k;
	const struct uid_gid_extent *el = e;

235
	id2 = key->id + key->count - 1;
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258

	/* handle map_id_{down,up}() */
	if (key->map_up)
		first = el->lower_first;
	else
		first = el->first;

	last = first + el->count - 1;

	if (key->id >= first && key->id <= last &&
	    (id2 >= first && id2 <= last))
		return 0;

	if (key->id < first || id2 < first)
		return -1;

	return 1;
}

/**
 * map_id_range_down_max - Find idmap via binary search in ordered idmap array.
 * Can only be called if number of mappings exceeds UID_GID_MAP_MAX_BASE_EXTENTS.
 */
259 260
static struct uid_gid_extent *
map_id_range_down_max(unsigned extents, struct uid_gid_map *map, u32 id, u32 count)
261
{
262 263 264 265 266 267
	struct idmap_key key;

	key.map_up = false;
	key.count = count;
	key.id = id;

268 269
	return bsearch(&key, map->forward, extents,
		       sizeof(struct uid_gid_extent), cmp_map_id);
270 271 272 273 274 275 276
}

/**
 * map_id_range_down_base - Find idmap via binary search in static extent array.
 * Can only be called if number of mappings is equal or less than
 * UID_GID_MAP_MAX_BASE_EXTENTS.
 */
277 278
static struct uid_gid_extent *
map_id_range_down_base(unsigned extents, struct uid_gid_map *map, u32 id, u32 count)
279
{
280
	unsigned idx;
281
	u32 first, last, id2;
282

283
	id2 = id + count - 1;
284

285 286 287 288 289 290
	/* Find the matching extent */
	for (idx = 0; idx < extents; idx++) {
		first = map->extent[idx].first;
		last = first + map->extent[idx].count - 1;
		if (id >= first && id <= last &&
		    (id2 >= first && id2 <= last))
291
			return &map->extent[idx];
292
	}
293
	return NULL;
294 295
}

296 297
static u32 map_id_range_down(struct uid_gid_map *map, u32 id, u32 count)
{
298 299
	struct uid_gid_extent *extent;
	unsigned extents = map->nr_extents;
300 301 302
	smp_rmb();

	if (extents <= UID_GID_MAP_MAX_BASE_EXTENTS)
303 304 305 306
		extent = map_id_range_down_base(extents, map, id, count);
	else
		extent = map_id_range_down_max(extents, map, id, count);

307
	/* Map the id or note failure */
308 309
	if (extent)
		id = (id - extent->first) + extent->lower_first;
310 311 312 313 314 315 316 317
	else
		id = (u32) -1;

	return id;
}

static u32 map_id_down(struct uid_gid_map *map, u32 id)
{
318
	return map_id_range_down(map, id, 1);
319 320 321 322 323 324 325
}

/**
 * map_id_up_base - Find idmap via binary search in static extent array.
 * Can only be called if number of mappings is equal or less than
 * UID_GID_MAP_MAX_BASE_EXTENTS.
 */
326 327
static struct uid_gid_extent *
map_id_up_base(unsigned extents, struct uid_gid_map *map, u32 id)
328
{
329
	unsigned idx;
330 331 332 333 334 335 336
	u32 first, last;

	/* Find the matching extent */
	for (idx = 0; idx < extents; idx++) {
		first = map->extent[idx].lower_first;
		last = first + map->extent[idx].count - 1;
		if (id >= first && id <= last)
337
			return &map->extent[idx];
338
	}
339
	return NULL;
340 341
}

342 343 344 345
/**
 * map_id_up_max - Find idmap via binary search in ordered idmap array.
 * Can only be called if number of mappings exceeds UID_GID_MAP_MAX_BASE_EXTENTS.
 */
346 347
static struct uid_gid_extent *
map_id_up_max(unsigned extents, struct uid_gid_map *map, u32 id)
348 349 350 351
{
	struct idmap_key key;

	key.map_up = true;
352
	key.count = 1;
353 354
	key.id = id;

355 356
	return bsearch(&key, map->reverse, extents,
		       sizeof(struct uid_gid_extent), cmp_map_id);
357 358 359 360
}

static u32 map_id_up(struct uid_gid_map *map, u32 id)
{
361 362
	struct uid_gid_extent *extent;
	unsigned extents = map->nr_extents;
363
	smp_rmb();
364

365 366 367 368 369
	if (extents <= UID_GID_MAP_MAX_BASE_EXTENTS)
		extent = map_id_up_base(extents, map, id);
	else
		extent = map_id_up_max(extents, map, id);

370
	/* Map the id or note failure */
371 372
	if (extent)
		id = (id - extent->lower_first) + extent->first;
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
	else
		id = (u32) -1;

	return id;
}

/**
 *	make_kuid - Map a user-namespace uid pair into a kuid.
 *	@ns:  User namespace that the uid is in
 *	@uid: User identifier
 *
 *	Maps a user-namespace uid pair into a kernel internal kuid,
 *	and returns that kuid.
 *
 *	When there is no mapping defined for the user-namespace uid
 *	pair INVALID_UID is returned.  Callers are expected to test
389
 *	for and handle INVALID_UID being returned.  INVALID_UID
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
 *	may be tested for using uid_valid().
 */
kuid_t make_kuid(struct user_namespace *ns, uid_t uid)
{
	/* Map the uid to a global kernel uid */
	return KUIDT_INIT(map_id_down(&ns->uid_map, uid));
}
EXPORT_SYMBOL(make_kuid);

/**
 *	from_kuid - Create a uid from a kuid user-namespace pair.
 *	@targ: The user namespace we want a uid in.
 *	@kuid: The kernel internal uid to start with.
 *
 *	Map @kuid into the user-namespace specified by @targ and
 *	return the resulting uid.
 *
 *	There is always a mapping into the initial user_namespace.
 *
 *	If @kuid has no mapping in @targ (uid_t)-1 is returned.
 */
uid_t from_kuid(struct user_namespace *targ, kuid_t kuid)
{
	/* Map the uid from a global kernel uid */
	return map_id_up(&targ->uid_map, __kuid_val(kuid));
}
EXPORT_SYMBOL(from_kuid);

/**
 *	from_kuid_munged - Create a uid from a kuid user-namespace pair.
 *	@targ: The user namespace we want a uid in.
 *	@kuid: The kernel internal uid to start with.
 *
 *	Map @kuid into the user-namespace specified by @targ and
 *	return the resulting uid.
 *
 *	There is always a mapping into the initial user_namespace.
 *
 *	Unlike from_kuid from_kuid_munged never fails and always
 *	returns a valid uid.  This makes from_kuid_munged appropriate
 *	for use in syscalls like stat and getuid where failing the
 *	system call and failing to provide a valid uid are not an
 *	options.
 *
 *	If @kuid has no mapping in @targ overflowuid is returned.
 */
uid_t from_kuid_munged(struct user_namespace *targ, kuid_t kuid)
{
	uid_t uid;
	uid = from_kuid(targ, kuid);

	if (uid == (uid_t) -1)
		uid = overflowuid;
	return uid;
}
EXPORT_SYMBOL(from_kuid_munged);

/**
 *	make_kgid - Map a user-namespace gid pair into a kgid.
 *	@ns:  User namespace that the gid is in
450
 *	@gid: group identifier
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
 *
 *	Maps a user-namespace gid pair into a kernel internal kgid,
 *	and returns that kgid.
 *
 *	When there is no mapping defined for the user-namespace gid
 *	pair INVALID_GID is returned.  Callers are expected to test
 *	for and handle INVALID_GID being returned.  INVALID_GID may be
 *	tested for using gid_valid().
 */
kgid_t make_kgid(struct user_namespace *ns, gid_t gid)
{
	/* Map the gid to a global kernel gid */
	return KGIDT_INIT(map_id_down(&ns->gid_map, gid));
}
EXPORT_SYMBOL(make_kgid);

/**
 *	from_kgid - Create a gid from a kgid user-namespace pair.
 *	@targ: The user namespace we want a gid in.
 *	@kgid: The kernel internal gid to start with.
 *
 *	Map @kgid into the user-namespace specified by @targ and
 *	return the resulting gid.
 *
 *	There is always a mapping into the initial user_namespace.
 *
 *	If @kgid has no mapping in @targ (gid_t)-1 is returned.
 */
gid_t from_kgid(struct user_namespace *targ, kgid_t kgid)
{
	/* Map the gid from a global kernel gid */
	return map_id_up(&targ->gid_map, __kgid_val(kgid));
}
EXPORT_SYMBOL(from_kgid);

/**
 *	from_kgid_munged - Create a gid from a kgid user-namespace pair.
 *	@targ: The user namespace we want a gid in.
 *	@kgid: The kernel internal gid to start with.
 *
 *	Map @kgid into the user-namespace specified by @targ and
 *	return the resulting gid.
 *
 *	There is always a mapping into the initial user_namespace.
 *
 *	Unlike from_kgid from_kgid_munged never fails and always
 *	returns a valid gid.  This makes from_kgid_munged appropriate
 *	for use in syscalls like stat and getgid where failing the
 *	system call and failing to provide a valid gid are not options.
 *
 *	If @kgid has no mapping in @targ overflowgid is returned.
 */
gid_t from_kgid_munged(struct user_namespace *targ, kgid_t kgid)
{
	gid_t gid;
	gid = from_kgid(targ, kgid);

	if (gid == (gid_t) -1)
		gid = overflowgid;
	return gid;
}
EXPORT_SYMBOL(from_kgid_munged);

514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
/**
 *	make_kprojid - Map a user-namespace projid pair into a kprojid.
 *	@ns:  User namespace that the projid is in
 *	@projid: Project identifier
 *
 *	Maps a user-namespace uid pair into a kernel internal kuid,
 *	and returns that kuid.
 *
 *	When there is no mapping defined for the user-namespace projid
 *	pair INVALID_PROJID is returned.  Callers are expected to test
 *	for and handle handle INVALID_PROJID being returned.  INVALID_PROJID
 *	may be tested for using projid_valid().
 */
kprojid_t make_kprojid(struct user_namespace *ns, projid_t projid)
{
	/* Map the uid to a global kernel uid */
	return KPROJIDT_INIT(map_id_down(&ns->projid_map, projid));
}
EXPORT_SYMBOL(make_kprojid);

/**
 *	from_kprojid - Create a projid from a kprojid user-namespace pair.
 *	@targ: The user namespace we want a projid in.
 *	@kprojid: The kernel internal project identifier to start with.
 *
 *	Map @kprojid into the user-namespace specified by @targ and
 *	return the resulting projid.
 *
 *	There is always a mapping into the initial user_namespace.
 *
 *	If @kprojid has no mapping in @targ (projid_t)-1 is returned.
 */
projid_t from_kprojid(struct user_namespace *targ, kprojid_t kprojid)
{
	/* Map the uid from a global kernel uid */
	return map_id_up(&targ->projid_map, __kprojid_val(kprojid));
}
EXPORT_SYMBOL(from_kprojid);

/**
 *	from_kprojid_munged - Create a projiid from a kprojid user-namespace pair.
 *	@targ: The user namespace we want a projid in.
 *	@kprojid: The kernel internal projid to start with.
 *
 *	Map @kprojid into the user-namespace specified by @targ and
 *	return the resulting projid.
 *
 *	There is always a mapping into the initial user_namespace.
 *
 *	Unlike from_kprojid from_kprojid_munged never fails and always
 *	returns a valid projid.  This makes from_kprojid_munged
 *	appropriate for use in syscalls like stat and where
 *	failing the system call and failing to provide a valid projid are
 *	not an options.
 *
 *	If @kprojid has no mapping in @targ OVERFLOW_PROJID is returned.
 */
projid_t from_kprojid_munged(struct user_namespace *targ, kprojid_t kprojid)
{
	projid_t projid;
	projid = from_kprojid(targ, kprojid);

	if (projid == (projid_t) -1)
		projid = OVERFLOW_PROJID;
	return projid;
}
EXPORT_SYMBOL(from_kprojid_munged);


583 584 585 586 587 588
static int uid_m_show(struct seq_file *seq, void *v)
{
	struct user_namespace *ns = seq->private;
	struct uid_gid_extent *extent = v;
	struct user_namespace *lower_ns;
	uid_t lower;
589

590
	lower_ns = seq_user_ns(seq);
591 592 593 594 595 596 597 598 599 600 601
	if ((lower_ns == ns) && lower_ns->parent)
		lower_ns = lower_ns->parent;

	lower = from_kuid(lower_ns, KUIDT_INIT(extent->lower_first));

	seq_printf(seq, "%10u %10u %10u\n",
		extent->first,
		lower,
		extent->count);

	return 0;
602 603
}

604
static int gid_m_show(struct seq_file *seq, void *v)
605
{
606 607 608 609
	struct user_namespace *ns = seq->private;
	struct uid_gid_extent *extent = v;
	struct user_namespace *lower_ns;
	gid_t lower;
610

611
	lower_ns = seq_user_ns(seq);
612 613
	if ((lower_ns == ns) && lower_ns->parent)
		lower_ns = lower_ns->parent;
614

615 616 617 618 619 620 621 622 623 624
	lower = from_kgid(lower_ns, KGIDT_INIT(extent->lower_first));

	seq_printf(seq, "%10u %10u %10u\n",
		extent->first,
		lower,
		extent->count);

	return 0;
}

625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645
static int projid_m_show(struct seq_file *seq, void *v)
{
	struct user_namespace *ns = seq->private;
	struct uid_gid_extent *extent = v;
	struct user_namespace *lower_ns;
	projid_t lower;

	lower_ns = seq_user_ns(seq);
	if ((lower_ns == ns) && lower_ns->parent)
		lower_ns = lower_ns->parent;

	lower = from_kprojid(lower_ns, KPROJIDT_INIT(extent->lower_first));

	seq_printf(seq, "%10u %10u %10u\n",
		extent->first,
		lower,
		extent->count);

	return 0;
}

646 647
static void *m_start(struct seq_file *seq, loff_t *ppos,
		     struct uid_gid_map *map)
648 649
{
	loff_t pos = *ppos;
650 651
	unsigned extents = map->nr_extents;
	smp_rmb();
652

653
	if (pos >= extents)
654
		return NULL;
655

656
	if (extents <= UID_GID_MAP_MAX_BASE_EXTENTS)
657
		return &map->extent[pos];
658

659
	return &map->forward[pos];
660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
}

static void *uid_m_start(struct seq_file *seq, loff_t *ppos)
{
	struct user_namespace *ns = seq->private;

	return m_start(seq, ppos, &ns->uid_map);
}

static void *gid_m_start(struct seq_file *seq, loff_t *ppos)
{
	struct user_namespace *ns = seq->private;

	return m_start(seq, ppos, &ns->gid_map);
}

676 677 678 679 680 681 682
static void *projid_m_start(struct seq_file *seq, loff_t *ppos)
{
	struct user_namespace *ns = seq->private;

	return m_start(seq, ppos, &ns->projid_map);
}

683 684 685 686 687 688 689 690 691 692 693
static void *m_next(struct seq_file *seq, void *v, loff_t *pos)
{
	(*pos)++;
	return seq->op->start(seq, pos);
}

static void m_stop(struct seq_file *seq, void *v)
{
	return;
}

F
Fabian Frederick 已提交
694
const struct seq_operations proc_uid_seq_operations = {
695 696 697 698 699 700
	.start = uid_m_start,
	.stop = m_stop,
	.next = m_next,
	.show = uid_m_show,
};

F
Fabian Frederick 已提交
701
const struct seq_operations proc_gid_seq_operations = {
702 703 704 705 706 707
	.start = gid_m_start,
	.stop = m_stop,
	.next = m_next,
	.show = gid_m_show,
};

F
Fabian Frederick 已提交
708
const struct seq_operations proc_projid_seq_operations = {
709 710 711 712 713 714
	.start = projid_m_start,
	.stop = m_stop,
	.next = m_next,
	.show = projid_m_show,
};

715 716
static bool mappings_overlap(struct uid_gid_map *new_map,
			     struct uid_gid_extent *extent)
717 718 719 720 721 722 723 724 725 726 727 728 729 730
{
	u32 upper_first, lower_first, upper_last, lower_last;
	unsigned idx;

	upper_first = extent->first;
	lower_first = extent->lower_first;
	upper_last = upper_first + extent->count - 1;
	lower_last = lower_first + extent->count - 1;

	for (idx = 0; idx < new_map->nr_extents; idx++) {
		u32 prev_upper_first, prev_lower_first;
		u32 prev_upper_last, prev_lower_last;
		struct uid_gid_extent *prev;

731 732 733 734
		if (new_map->nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS)
			prev = &new_map->extent[idx];
		else
			prev = &new_map->forward[idx];
735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753

		prev_upper_first = prev->first;
		prev_lower_first = prev->lower_first;
		prev_upper_last = prev_upper_first + prev->count - 1;
		prev_lower_last = prev_lower_first + prev->count - 1;

		/* Does the upper range intersect a previous extent? */
		if ((prev_upper_first <= upper_last) &&
		    (prev_upper_last >= upper_first))
			return true;

		/* Does the lower range intersect a previous extent? */
		if ((prev_lower_first <= lower_last) &&
		    (prev_lower_last >= lower_first))
			return true;
	}
	return false;
}

754 755 756 757 758 759 760
/**
 * insert_extent - Safely insert a new idmap extent into struct uid_gid_map.
 * Takes care to allocate a 4K block of memory if the number of mappings exceeds
 * UID_GID_MAP_MAX_BASE_EXTENTS.
 */
static int insert_extent(struct uid_gid_map *map, struct uid_gid_extent *extent)
{
E
Eric W. Biederman 已提交
761
	struct uid_gid_extent *dest;
762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781

	if (map->nr_extents == UID_GID_MAP_MAX_BASE_EXTENTS) {
		struct uid_gid_extent *forward;

		/* Allocate memory for 340 mappings. */
		forward = kmalloc(sizeof(struct uid_gid_extent) *
				 UID_GID_MAP_MAX_EXTENTS, GFP_KERNEL);
		if (!forward)
			return -ENOMEM;

		/* Copy over memory. Only set up memory for the forward pointer.
		 * Defer the memory setup for the reverse pointer.
		 */
		memcpy(forward, map->extent,
		       map->nr_extents * sizeof(map->extent[0]));

		map->forward = forward;
		map->reverse = NULL;
	}

E
Eric W. Biederman 已提交
782 783 784 785 786 787 788
	if (map->nr_extents < UID_GID_MAP_MAX_BASE_EXTENTS)
		dest = &map->extent[map->nr_extents];
	else
		dest = &map->forward[map->nr_extents];

	*dest = *extent;
	map->nr_extents++;
789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848
	return 0;
}

/* cmp function to sort() forward mappings */
static int cmp_extents_forward(const void *a, const void *b)
{
	const struct uid_gid_extent *e1 = a;
	const struct uid_gid_extent *e2 = b;

	if (e1->first < e2->first)
		return -1;

	if (e1->first > e2->first)
		return 1;

	return 0;
}

/* cmp function to sort() reverse mappings */
static int cmp_extents_reverse(const void *a, const void *b)
{
	const struct uid_gid_extent *e1 = a;
	const struct uid_gid_extent *e2 = b;

	if (e1->lower_first < e2->lower_first)
		return -1;

	if (e1->lower_first > e2->lower_first)
		return 1;

	return 0;
}

/**
 * sort_idmaps - Sorts an array of idmap entries.
 * Can only be called if number of mappings exceeds UID_GID_MAP_MAX_BASE_EXTENTS.
 */
static int sort_idmaps(struct uid_gid_map *map)
{
	if (map->nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS)
		return 0;

	/* Sort forward array. */
	sort(map->forward, map->nr_extents, sizeof(struct uid_gid_extent),
	     cmp_extents_forward, NULL);

	/* Only copy the memory from forward we actually need. */
	map->reverse = kmemdup(map->forward,
			       map->nr_extents * sizeof(struct uid_gid_extent),
			       GFP_KERNEL);
	if (!map->reverse)
		return -ENOMEM;

	/* Sort reverse array. */
	sort(map->reverse, map->nr_extents, sizeof(struct uid_gid_extent),
	     cmp_extents_reverse, NULL);

	return 0;
}

849 850 851 852 853 854 855 856 857 858
static ssize_t map_write(struct file *file, const char __user *buf,
			 size_t count, loff_t *ppos,
			 int cap_setid,
			 struct uid_gid_map *map,
			 struct uid_gid_map *parent_map)
{
	struct seq_file *seq = file->private_data;
	struct user_namespace *ns = seq->private;
	struct uid_gid_map new_map;
	unsigned idx;
859
	struct uid_gid_extent extent;
A
Al Viro 已提交
860
	char *kbuf = NULL, *pos, *next_line;
861 862 863
	ssize_t ret = -EINVAL;

	/*
864
	 * The userns_state_mutex serializes all writes to any given map.
865 866 867 868 869 870 871 872 873 874 875 876 877 878
	 *
	 * Any map is only ever written once.
	 *
	 * An id map fits within 1 cache line on most architectures.
	 *
	 * On read nothing needs to be done unless you are on an
	 * architecture with a crazy cache coherency model like alpha.
	 *
	 * There is a one time data dependency between reading the
	 * count of the extents and the values of the extents.  The
	 * desired behavior is to see the values of the extents that
	 * were written before the count of the extents.
	 *
	 * To achieve this smp_wmb() is used on guarantee the write
879 880
	 * order and smp_rmb() is guaranteed that we don't have crazy
	 * architectures returning stale data.
881
	 */
882
	mutex_lock(&userns_state_mutex);
883

884 885
	memset(&new_map, 0, sizeof(struct uid_gid_map));

886 887 888 889 890
	ret = -EPERM;
	/* Only allow one successful write to the map */
	if (map->nr_extents != 0)
		goto out;

891 892
	/*
	 * Adjusting namespace settings requires capabilities on the target.
893
	 */
894
	if (cap_valid(cap_setid) && !file_ns_capable(file, ns, CAP_SYS_ADMIN))
895 896
		goto out;

897
	/* Only allow < page size writes at the beginning of the file */
898 899 900 901 902
	ret = -EINVAL;
	if ((*ppos != 0) || (count >= PAGE_SIZE))
		goto out;

	/* Slurp in the user data */
A
Al Viro 已提交
903 904 905 906
	kbuf = memdup_user_nul(buf, count);
	if (IS_ERR(kbuf)) {
		ret = PTR_ERR(kbuf);
		kbuf = NULL;
907
		goto out;
A
Al Viro 已提交
908
	}
909 910 911 912

	/* Parse the user data */
	ret = -EINVAL;
	pos = kbuf;
913
	for (; pos; pos = next_line) {
914 915 916 917 918 919 920 921

		/* Find the end of line and ensure I don't look past it */
		next_line = strchr(pos, '\n');
		if (next_line) {
			*next_line = '\0';
			next_line++;
			if (*next_line == '\0')
				next_line = NULL;
922
		}
923 924

		pos = skip_spaces(pos);
925
		extent.first = simple_strtoul(pos, &pos, 10);
926 927 928 929
		if (!isspace(*pos))
			goto out;

		pos = skip_spaces(pos);
930
		extent.lower_first = simple_strtoul(pos, &pos, 10);
931 932 933 934
		if (!isspace(*pos))
			goto out;

		pos = skip_spaces(pos);
935
		extent.count = simple_strtoul(pos, &pos, 10);
936 937 938 939 940 941 942 943 944
		if (*pos && !isspace(*pos))
			goto out;

		/* Verify there is not trailing junk on the line */
		pos = skip_spaces(pos);
		if (*pos != '\0')
			goto out;

		/* Verify we have been given valid starting values */
945 946
		if ((extent.first == (u32) -1) ||
		    (extent.lower_first == (u32) -1))
947 948
			goto out;

949 950 951
		/* Verify count is not zero and does not cause the
		 * extent to wrap
		 */
952
		if ((extent.first + extent.count) <= extent.first)
953
			goto out;
954 955
		if ((extent.lower_first + extent.count) <=
		     extent.lower_first)
956 957
			goto out;

958
		/* Do the ranges in extent overlap any previous extents? */
959
		if (mappings_overlap(&new_map, &extent))
960 961
			goto out;

962
		if ((new_map.nr_extents + 1) == UID_GID_MAP_MAX_EXTENTS &&
963 964
		    (next_line != NULL))
			goto out;
965 966 967 968 969

		ret = insert_extent(&new_map, &extent);
		if (ret < 0)
			goto out;
		ret = -EINVAL;
970
	}
971 972 973 974 975 976
	/* Be very certaint the new map actually exists */
	if (new_map.nr_extents == 0)
		goto out;

	ret = -EPERM;
	/* Validate the user is allowed to use user id's mapped to. */
977
	if (!new_idmap_permitted(file, ns, cap_setid, &new_map))
978 979
		goto out;

980 981 982 983 984
	ret = sort_idmaps(&new_map);
	if (ret < 0)
		goto out;

	ret = -EPERM;
985 986 987 988
	/* Map the lower ids from the parent user namespace to the
	 * kernel global id space.
	 */
	for (idx = 0; idx < new_map.nr_extents; idx++) {
989
		struct uid_gid_extent *e;
990
		u32 lower_first;
991 992 993 994 995

		if (new_map.nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS)
			e = &new_map.extent[idx];
		else
			e = &new_map.forward[idx];
996 997

		lower_first = map_id_range_down(parent_map,
998 999
						e->lower_first,
						e->count);
1000 1001 1002 1003 1004 1005 1006

		/* Fail if we can not map the specified extent to
		 * the kernel global id space.
		 */
		if (lower_first == (u32) -1)
			goto out;

1007
		e->lower_first = lower_first;
1008 1009 1010
	}

	/* Install the map */
1011 1012 1013 1014 1015 1016 1017
	if (new_map.nr_extents <= UID_GID_MAP_MAX_BASE_EXTENTS) {
		memcpy(map->extent, new_map.extent,
		       new_map.nr_extents * sizeof(new_map.extent[0]));
	} else {
		map->forward = new_map.forward;
		map->reverse = new_map.reverse;
	}
1018 1019 1020 1021 1022 1023
	smp_wmb();
	map->nr_extents = new_map.nr_extents;

	*ppos = count;
	ret = count;
out:
1024 1025 1026 1027 1028 1029 1030 1031
	if (ret < 0 && new_map.nr_extents > UID_GID_MAP_MAX_BASE_EXTENTS) {
		kfree(new_map.forward);
		kfree(new_map.reverse);
		map->forward = NULL;
		map->reverse = NULL;
		map->nr_extents = 0;
	}

1032
	mutex_unlock(&userns_state_mutex);
A
Al Viro 已提交
1033
	kfree(kbuf);
1034 1035 1036
	return ret;
}

1037 1038
ssize_t proc_uid_map_write(struct file *file, const char __user *buf,
			   size_t size, loff_t *ppos)
1039 1040 1041
{
	struct seq_file *seq = file->private_data;
	struct user_namespace *ns = seq->private;
1042
	struct user_namespace *seq_ns = seq_user_ns(seq);
1043 1044 1045 1046

	if (!ns->parent)
		return -EPERM;

1047 1048 1049
	if ((seq_ns != ns) && (seq_ns != ns->parent))
		return -EPERM;

1050 1051 1052 1053
	return map_write(file, buf, size, ppos, CAP_SETUID,
			 &ns->uid_map, &ns->parent->uid_map);
}

1054 1055
ssize_t proc_gid_map_write(struct file *file, const char __user *buf,
			   size_t size, loff_t *ppos)
1056 1057 1058
{
	struct seq_file *seq = file->private_data;
	struct user_namespace *ns = seq->private;
1059
	struct user_namespace *seq_ns = seq_user_ns(seq);
1060 1061 1062 1063

	if (!ns->parent)
		return -EPERM;

1064 1065 1066
	if ((seq_ns != ns) && (seq_ns != ns->parent))
		return -EPERM;

1067 1068 1069 1070
	return map_write(file, buf, size, ppos, CAP_SETGID,
			 &ns->gid_map, &ns->parent->gid_map);
}

1071 1072
ssize_t proc_projid_map_write(struct file *file, const char __user *buf,
			      size_t size, loff_t *ppos)
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
{
	struct seq_file *seq = file->private_data;
	struct user_namespace *ns = seq->private;
	struct user_namespace *seq_ns = seq_user_ns(seq);

	if (!ns->parent)
		return -EPERM;

	if ((seq_ns != ns) && (seq_ns != ns->parent))
		return -EPERM;

	/* Anyone can set any valid project id no capability needed */
	return map_write(file, buf, size, ppos, -1,
			 &ns->projid_map, &ns->parent->projid_map);
}

1089
static bool new_idmap_permitted(const struct file *file,
1090
				struct user_namespace *ns, int cap_setid,
1091 1092
				struct uid_gid_map *new_map)
{
1093
	const struct cred *cred = file->f_cred;
1094 1095 1096
	/* Don't allow mappings that would allow anything that wouldn't
	 * be allowed without the establishment of unprivileged mappings.
	 */
1097 1098
	if ((new_map->nr_extents == 1) && (new_map->extent[0].count == 1) &&
	    uid_eq(ns->owner, cred->euid)) {
1099 1100 1101
		u32 id = new_map->extent[0].lower_first;
		if (cap_setid == CAP_SETUID) {
			kuid_t uid = make_kuid(ns->parent, id);
1102
			if (uid_eq(uid, cred->euid))
1103
				return true;
1104
		} else if (cap_setid == CAP_SETGID) {
1105
			kgid_t gid = make_kgid(ns->parent, id);
1106 1107
			if (!(ns->flags & USERNS_SETGROUPS_ALLOWED) &&
			    gid_eq(gid, cred->egid))
1108 1109 1110 1111
				return true;
		}
	}

1112 1113 1114 1115
	/* Allow anyone to set a mapping that doesn't require privilege */
	if (!cap_valid(cap_setid))
		return true;

1116 1117
	/* Allow the specified ids if we have the appropriate capability
	 * (CAP_SETUID or CAP_SETGID) over the parent user namespace.
1118
	 * And the opener of the id file also had the approprpiate capability.
1119
	 */
1120 1121
	if (ns_capable(ns->parent, cap_setid) &&
	    file_ns_capable(file, ns->parent, cap_setid))
1122
		return true;
1123

1124
	return false;
1125
}
1126

1127 1128 1129
int proc_setgroups_show(struct seq_file *seq, void *v)
{
	struct user_namespace *ns = seq->private;
1130
	unsigned long userns_flags = READ_ONCE(ns->flags);
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204

	seq_printf(seq, "%s\n",
		   (userns_flags & USERNS_SETGROUPS_ALLOWED) ?
		   "allow" : "deny");
	return 0;
}

ssize_t proc_setgroups_write(struct file *file, const char __user *buf,
			     size_t count, loff_t *ppos)
{
	struct seq_file *seq = file->private_data;
	struct user_namespace *ns = seq->private;
	char kbuf[8], *pos;
	bool setgroups_allowed;
	ssize_t ret;

	/* Only allow a very narrow range of strings to be written */
	ret = -EINVAL;
	if ((*ppos != 0) || (count >= sizeof(kbuf)))
		goto out;

	/* What was written? */
	ret = -EFAULT;
	if (copy_from_user(kbuf, buf, count))
		goto out;
	kbuf[count] = '\0';
	pos = kbuf;

	/* What is being requested? */
	ret = -EINVAL;
	if (strncmp(pos, "allow", 5) == 0) {
		pos += 5;
		setgroups_allowed = true;
	}
	else if (strncmp(pos, "deny", 4) == 0) {
		pos += 4;
		setgroups_allowed = false;
	}
	else
		goto out;

	/* Verify there is not trailing junk on the line */
	pos = skip_spaces(pos);
	if (*pos != '\0')
		goto out;

	ret = -EPERM;
	mutex_lock(&userns_state_mutex);
	if (setgroups_allowed) {
		/* Enabling setgroups after setgroups has been disabled
		 * is not allowed.
		 */
		if (!(ns->flags & USERNS_SETGROUPS_ALLOWED))
			goto out_unlock;
	} else {
		/* Permanently disabling setgroups after setgroups has
		 * been enabled by writing the gid_map is not allowed.
		 */
		if (ns->gid_map.nr_extents != 0)
			goto out_unlock;
		ns->flags &= ~USERNS_SETGROUPS_ALLOWED;
	}
	mutex_unlock(&userns_state_mutex);

	/* Report a successful write */
	*ppos = count;
	ret = count;
out:
	return ret;
out_unlock:
	mutex_unlock(&userns_state_mutex);
	goto out;
}

1205 1206 1207 1208
bool userns_may_setgroups(const struct user_namespace *ns)
{
	bool allowed;

1209
	mutex_lock(&userns_state_mutex);
1210 1211 1212 1213
	/* It is not safe to use setgroups until a gid mapping in
	 * the user namespace has been established.
	 */
	allowed = ns->gid_map.nr_extents != 0;
1214 1215
	/* Is setgroups allowed? */
	allowed = allowed && (ns->flags & USERNS_SETGROUPS_ALLOWED);
1216
	mutex_unlock(&userns_state_mutex);
1217 1218 1219 1220

	return allowed;
}

1221
/*
1222 1223
 * Returns true if @child is the same namespace or a descendant of
 * @ancestor.
1224
 */
1225 1226 1227 1228 1229 1230 1231 1232 1233
bool in_userns(const struct user_namespace *ancestor,
	       const struct user_namespace *child)
{
	const struct user_namespace *ns;
	for (ns = child; ns->level > ancestor->level; ns = ns->parent)
		;
	return (ns == ancestor);
}

1234 1235
bool current_in_userns(const struct user_namespace *target_ns)
{
1236
	return in_userns(target_ns, current_user_ns());
1237 1238
}

1239 1240 1241 1242 1243
static inline struct user_namespace *to_user_ns(struct ns_common *ns)
{
	return container_of(ns, struct user_namespace, ns);
}

1244
static struct ns_common *userns_get(struct task_struct *task)
1245 1246 1247 1248 1249 1250 1251
{
	struct user_namespace *user_ns;

	rcu_read_lock();
	user_ns = get_user_ns(__task_cred(task)->user_ns);
	rcu_read_unlock();

1252
	return user_ns ? &user_ns->ns : NULL;
1253 1254
}

1255
static void userns_put(struct ns_common *ns)
1256
{
1257
	put_user_ns(to_user_ns(ns));
1258 1259
}

1260
static int userns_install(struct nsproxy *nsproxy, struct ns_common *ns)
1261
{
1262
	struct user_namespace *user_ns = to_user_ns(ns);
1263 1264 1265 1266 1267 1268 1269 1270
	struct cred *cred;

	/* Don't allow gaining capabilities by reentering
	 * the same user namespace.
	 */
	if (user_ns == current_user_ns())
		return -EINVAL;

1271 1272
	/* Tasks that share a thread group must share a user namespace */
	if (!thread_group_empty(current))
1273 1274
		return -EINVAL;

1275 1276 1277
	if (current->fs->users != 1)
		return -EINVAL;

1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290
	if (!ns_capable(user_ns, CAP_SYS_ADMIN))
		return -EPERM;

	cred = prepare_creds();
	if (!cred)
		return -ENOMEM;

	put_user_ns(cred->user_ns);
	set_cred_user_ns(cred, get_user_ns(user_ns));

	return commit_creds(cred);
}

1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313
struct ns_common *ns_get_owner(struct ns_common *ns)
{
	struct user_namespace *my_user_ns = current_user_ns();
	struct user_namespace *owner, *p;

	/* See if the owner is in the current user namespace */
	owner = p = ns->ops->owner(ns);
	for (;;) {
		if (!p)
			return ERR_PTR(-EPERM);
		if (p == my_user_ns)
			break;
		p = p->parent;
	}

	return &get_user_ns(owner)->ns;
}

static struct user_namespace *userns_owner(struct ns_common *ns)
{
	return to_user_ns(ns)->parent;
}

1314 1315 1316 1317 1318 1319
const struct proc_ns_operations userns_operations = {
	.name		= "user",
	.type		= CLONE_NEWUSER,
	.get		= userns_get,
	.put		= userns_put,
	.install	= userns_install,
1320
	.owner		= userns_owner,
1321
	.get_parent	= ns_get_owner,
1322 1323
};

1324 1325 1326 1327 1328
static __init int user_namespaces_init(void)
{
	user_ns_cachep = KMEM_CACHE(user_namespace, SLAB_PANIC);
	return 0;
}
1329
subsys_initcall(user_namespaces_init);