util.c 22.9 KB
Newer Older
1
// SPDX-License-Identifier: GPL-2.0
Linus Torvalds's avatar
Linus Torvalds committed
2 3 4 5 6 7 8 9 10
/*
 * linux/ipc/util.c
 * Copyright (C) 1992 Krishna Balasubramanian
 *
 * Sep 1997 - Call suser() last after "normal" permission checks so we
 *            get BSD style process accounting right.
 *            Occurs in several places in the IPC code.
 *            Chris Evans, <chris@ferret.lmh.ox.ac.uk>
 * Nov 1999 - ipc helper functions, unified SMP locking
11
 *	      Manfred Spraul <manfred@colorfullife.com>
Linus Torvalds's avatar
Linus Torvalds committed
12 13
 * Oct 2002 - One lock per IPC id. RCU ipc_free for lock-free grow_ary().
 *            Mingming Cao <cmm@us.ibm.com>
Steve Grubb's avatar
Steve Grubb committed
14 15
 * Mar 2006 - support for audit of ipc object properties
 *            Dustin Kirkland <dustin.kirkland@us.ibm.com>
16 17 18
 * Jun 2006 - namespaces ssupport
 *            OpenVZ, SWsoft Inc.
 *            Pavel Emelianov <xemul@openvz.org>
19 20
 *
 * General sysv ipc locking scheme:
21 22 23 24 25
 *	rcu_read_lock()
 *          obtain the ipc object (kern_ipc_perm) by looking up the id in an idr
 *	    tree.
 *	    - perform initial checks (capabilities, auditing and permission,
 *	      etc).
26 27
 *	    - perform read-only operations, such as INFO command, that
 *	      do not demand atomicity
28 29
 *	      acquire the ipc lock (kern_ipc_perm.lock) through
 *	      ipc_lock_object()
30 31
 *		- perform read-only operations that demand atomicity,
 *		  such as STAT command.
32 33 34 35 36 37 38 39 40 41 42 43 44
 *		- perform data updates, such as SET, RMID commands and
 *		  mechanism-specific operations (semop/semtimedop,
 *		  msgsnd/msgrcv, shmat/shmdt).
 *	    drop the ipc lock, through ipc_unlock_object().
 *	rcu_read_unlock()
 *
 *  The ids->rwsem must be taken when:
 *	- creating, removing and iterating the existing entries in ipc
 *	  identifier sets.
 *	- iterating through files under /proc/sysvipc/
 *
 *  Note that sems have a special fast path that avoids kern_ipc_perm.lock -
 *  see sem_lock().
Linus Torvalds's avatar
Linus Torvalds committed
45 46 47 48 49 50 51 52
 */

#include <linux/mm.h>
#include <linux/shm.h>
#include <linux/init.h>
#include <linux/msg.h>
#include <linux/vmalloc.h>
#include <linux/slab.h>
53
#include <linux/notifier.h>
54
#include <linux/capability.h>
Linus Torvalds's avatar
Linus Torvalds committed
55 56 57 58
#include <linux/highuid.h>
#include <linux/security.h>
#include <linux/rcupdate.h>
#include <linux/workqueue.h>
59 60
#include <linux/seq_file.h>
#include <linux/proc_fs.h>
Steve Grubb's avatar
Steve Grubb committed
61
#include <linux/audit.h>
62
#include <linux/nsproxy.h>
Nadia Derbey's avatar
Nadia Derbey committed
63
#include <linux/rwsem.h>
64
#include <linux/memory.h>
65
#include <linux/ipc_namespace.h>
NeilBrown's avatar
NeilBrown committed
66
#include <linux/rhashtable.h>
Linus Torvalds's avatar
Linus Torvalds committed
67 68 69 70 71

#include <asm/unistd.h>

#include "util.h"

72 73 74
struct ipc_proc_iface {
	const char *path;
	const char *header;
75
	int ids;
76 77 78
	int (*show)(struct seq_file *, void *);
};

Linus Torvalds's avatar
Linus Torvalds committed
79
/**
80
 * ipc_init - initialise ipc subsystem
Linus Torvalds's avatar
Linus Torvalds committed
81
 *
82 83 84 85 86 87
 * The various sysv ipc resources (semaphores, messages and shared
 * memory) are initialised.
 *
 * A callback routine is registered into the memory hotplug notifier
 * chain: since msgmni scales to lowmem this callback routine will be
 * called upon successful memory add / remove to recompute msmgni.
Linus Torvalds's avatar
Linus Torvalds committed
88 89 90
 */
static int __init ipc_init(void)
{
91
	proc_mkdir("sysvipc", NULL);
92 93
	sem_init();
	msg_init();
Linus Torvalds's avatar
Linus Torvalds committed
94
	shm_init();
95

96
	return 0;
Linus Torvalds's avatar
Linus Torvalds committed
97
}
Davidlohr Bueso's avatar
Davidlohr Bueso committed
98
device_initcall(ipc_init);
Linus Torvalds's avatar
Linus Torvalds committed
99

100 101 102
static const struct rhashtable_params ipc_kht_params = {
	.head_offset		= offsetof(struct kern_ipc_perm, khtnode),
	.key_offset		= offsetof(struct kern_ipc_perm, key),
103
	.key_len		= sizeof_field(struct kern_ipc_perm, key),
104 105 106
	.automatic_shrinking	= true,
};

Linus Torvalds's avatar
Linus Torvalds committed
107
/**
108 109
 * ipc_init_ids	- initialise ipc identifiers
 * @ids: ipc identifier set
Linus Torvalds's avatar
Linus Torvalds committed
110
 *
111
 * Set up the sequence range to use for the ipc identifier range (limited
112
 * below ipc_mni) then initialise the keys hashtable and ids idr.
Linus Torvalds's avatar
Linus Torvalds committed
113
 */
114
void ipc_init_ids(struct ipc_ids *ids)
Linus Torvalds's avatar
Linus Torvalds committed
115 116 117
{
	ids->in_use = 0;
	ids->seq = 0;
118
	init_rwsem(&ids->rwsem);
119
	rhashtable_init(&ids->key_ht, &ipc_kht_params);
Nadia Derbey's avatar
Nadia Derbey committed
120
	idr_init(&ids->ipcs_idr);
121
	ids->max_idx = -1;
122
	ids->last_idx = -1;
123 124 125
#ifdef CONFIG_CHECKPOINT_RESTORE
	ids->next_id = -1;
#endif
Linus Torvalds's avatar
Linus Torvalds committed
126 127
}

128
#ifdef CONFIG_PROC_FS
129
static const struct proc_ops sysvipc_proc_ops;
130
/**
131 132 133 134 135
 * ipc_init_proc_interface -  create a proc interface for sysipc types using a seq_file interface.
 * @path: Path in procfs
 * @header: Banner to be printed at the beginning of the file.
 * @ids: ipc id table to iterate.
 * @show: show routine.
136 137
 */
void __init ipc_init_proc_interface(const char *path, const char *header,
138
		int ids, int (*show)(struct seq_file *, void *))
139 140 141 142 143 144 145 146 147 148 149 150
{
	struct proc_dir_entry *pde;
	struct ipc_proc_iface *iface;

	iface = kmalloc(sizeof(*iface), GFP_KERNEL);
	if (!iface)
		return;
	iface->path	= path;
	iface->header	= header;
	iface->ids	= ids;
	iface->show	= show;

151 152 153
	pde = proc_create_data(path,
			       S_IRUGO,        /* world readable */
			       NULL,           /* parent dir */
154
			       &sysvipc_proc_ops,
155
			       iface);
156
	if (!pde)
157 158 159 160
		kfree(iface);
}
#endif

Linus Torvalds's avatar
Linus Torvalds committed
161
/**
162 163 164
 * ipc_findkey	- find a key in an ipc identifier set
 * @ids: ipc identifier set
 * @key: key to find
Paul McQuade's avatar
Paul McQuade committed
165
 *
166 167 168
 * Returns the locked pointer to the ipc structure if found or NULL
 * otherwise. If key is found ipc points to the owning ipc structure
 *
169
 * Called with writer ipc_ids.rwsem held.
Linus Torvalds's avatar
Linus Torvalds committed
170
 */
Nadia Derbey's avatar
Nadia Derbey committed
171
static struct kern_ipc_perm *ipc_findkey(struct ipc_ids *ids, key_t key)
Linus Torvalds's avatar
Linus Torvalds committed
172
{
173
	struct kern_ipc_perm *ipcp;
Nadia Derbey's avatar
Nadia Derbey committed
174

175
	ipcp = rhashtable_lookup_fast(&ids->key_ht, &key,
176
					      ipc_kht_params);
177 178
	if (!ipcp)
		return NULL;
Nadia Derbey's avatar
Nadia Derbey committed
179

180 181 182
	rcu_read_lock();
	ipc_lock_object(ipcp);
	return ipcp;
Linus Torvalds's avatar
Linus Torvalds committed
183 184
}

185
/*
186 187 188 189 190 191 192 193 194 195
 * Insert new IPC object into idr tree, and set sequence number and id
 * in the correct order.
 * Especially:
 * - the sequence number must be set before inserting the object into the idr,
 *   because the sequence number is accessed without a lock.
 * - the id can/must be set after inserting the object into the idr.
 *   All accesses must be done after getting kern_ipc_perm.lock.
 *
 * The caller must own kern_ipc_perm.lock.of the new object.
 * On error, the function returns a (negative) error code.
196 197 198 199
 *
 * To conserve sequence number space, especially with extended ipc_mni,
 * the sequence number is incremented only when the returned ID is less than
 * the last one.
200
 */
201
static inline int ipc_idr_alloc(struct ipc_ids *ids, struct kern_ipc_perm *new)
202
{
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
	int idx, next_id = -1;

#ifdef CONFIG_CHECKPOINT_RESTORE
	next_id = ids->next_id;
	ids->next_id = -1;
#endif

	/*
	 * As soon as a new object is inserted into the idr,
	 * ipc_obtain_object_idr() or ipc_obtain_object_check() can find it,
	 * and the lockless preparations for ipc operations can start.
	 * This means especially: permission checks, audit calls, allocation
	 * of undo structures, ...
	 *
	 * Thus the object must be fully initialized, and if something fails,
	 * then the full tear-down sequence must be followed.
	 * (i.e.: set new->deleted, reduce refcount, call_rcu())
	 */

	if (next_id < 0) { /* !CHECKPOINT_RESTORE or next_id is unset */
223 224 225 226
		int max_idx;

		max_idx = max(ids->in_use*3/2, ipc_min_cycle);
		max_idx = min(max_idx, ipc_mni);
227 228

		/* allocate the idx, with a NULL struct kern_ipc_perm */
229 230
		idx = idr_alloc_cyclic(&ids->ipcs_idr, NULL, 0, max_idx,
					GFP_NOWAIT);
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251

		if (idx >= 0) {
			/*
			 * idx got allocated successfully.
			 * Now calculate the sequence number and set the
			 * pointer for real.
			 */
			if (idx <= ids->last_idx) {
				ids->seq++;
				if (ids->seq >= ipcid_seq_max())
					ids->seq = 0;
			}
			ids->last_idx = idx;

			new->seq = ids->seq;
			/* no need for smp_wmb(), this is done
			 * inside idr_replace, as part of
			 * rcu_assign_pointer
			 */
			idr_replace(&ids->ipcs_idr, new, idx);
		}
252
	} else {
253 254 255
		new->seq = ipcid_to_seqx(next_id);
		idx = idr_alloc(&ids->ipcs_idr, new, ipcid_to_idx(next_id),
				0, GFP_NOWAIT);
256
	}
257
	if (idx >= 0)
258
		new->id = (new->seq << ipcmni_seq_shift()) + idx;
259
	return idx;
260 261
}

Linus Torvalds's avatar
Linus Torvalds committed
262
/**
263 264 265
 * ipc_addid - add an ipc identifier
 * @ids: ipc identifier set
 * @new: new ipc permission set
266
 * @limit: limit for the number of used ids
Linus Torvalds's avatar
Linus Torvalds committed
267
 *
268
 * Add an entry 'new' to the ipc ids idr. The permissions object is
269
 * initialised and the first free entry is set up and the index assigned
270
 * is returned. The 'new' entry is returned in a locked state on success.
271
 *
272
 * On failure the entry is not locked and a negative err-code is returned.
273
 * The caller must use ipc_rcu_putref() to free the identifier.
Linus Torvalds's avatar
Linus Torvalds committed
274
 *
275
 * Called with writer ipc_ids.rwsem held.
Linus Torvalds's avatar
Linus Torvalds committed
276
 */
277
int ipc_addid(struct ipc_ids *ids, struct kern_ipc_perm *new, int limit)
Linus Torvalds's avatar
Linus Torvalds committed
278
{
279 280
	kuid_t euid;
	kgid_t egid;
281
	int idx, err;
Linus Torvalds's avatar
Linus Torvalds committed
282

283 284 285
	/* 1) Initialize the refcount so that ipc_rcu_putref works */
	refcount_set(&new->refcount, 1);

286 287
	if (limit > ipc_mni)
		limit = ipc_mni;
Nadia Derbey's avatar
Nadia Derbey committed
288

289
	if (ids->in_use >= limit)
290
		return -ENOSPC;
Nadia Derbey's avatar
Nadia Derbey committed
291

Tejun Heo's avatar
Tejun Heo committed
292 293
	idr_preload(GFP_KERNEL);

294 295 296 297
	spin_lock_init(&new->lock);
	rcu_read_lock();
	spin_lock(&new->lock);

298 299 300 301
	current_euid_egid(&euid, &egid);
	new->cuid = new->uid = euid;
	new->gid = new->cgid = egid;

302 303
	new->deleted = false;

304
	idx = ipc_idr_alloc(ids, new);
Tejun Heo's avatar
Tejun Heo committed
305
	idr_preload_end();
306

307
	if (idx >= 0 && new->key != IPC_PRIVATE) {
308 309 310
		err = rhashtable_insert_fast(&ids->key_ht, &new->khtnode,
					     ipc_kht_params);
		if (err < 0) {
311 312
			idr_remove(&ids->ipcs_idr, idx);
			idx = err;
313 314
		}
	}
315
	if (idx < 0) {
316
		new->deleted = true;
317 318
		spin_unlock(&new->lock);
		rcu_read_unlock();
319
		return idx;
320
	}
Nadia Derbey's avatar
Nadia Derbey committed
321

Linus Torvalds's avatar
Linus Torvalds committed
322
	ids->in_use++;
323 324
	if (idx > ids->max_idx)
		ids->max_idx = idx;
325
	return idx;
Linus Torvalds's avatar
Linus Torvalds committed
326 327
}

Nadia Derbey's avatar
Nadia Derbey committed
328
/**
329 330
 * ipcget_new -	create a new ipc object
 * @ns: ipc namespace
331
 * @ids: ipc identifier set
332 333 334 335 336
 * @ops: the actual creation routine to call
 * @params: its parameters
 *
 * This routine is called by sys_msgget, sys_semget() and sys_shmget()
 * when the key is IPC_PRIVATE.
Nadia Derbey's avatar
Nadia Derbey committed
337
 */
338
static int ipcget_new(struct ipc_namespace *ns, struct ipc_ids *ids,
Mathias Krause's avatar
Mathias Krause committed
339
		const struct ipc_ops *ops, struct ipc_params *params)
Nadia Derbey's avatar
Nadia Derbey committed
340 341 342
{
	int err;

Davidlohr Bueso's avatar
Davidlohr Bueso committed
343
	down_write(&ids->rwsem);
Nadia Derbey's avatar
Nadia Derbey committed
344
	err = ops->getnew(ns, params);
Davidlohr Bueso's avatar
Davidlohr Bueso committed
345
	up_write(&ids->rwsem);
Nadia Derbey's avatar
Nadia Derbey committed
346 347 348 349
	return err;
}

/**
350 351 352 353 354
 * ipc_check_perms - check security and permissions for an ipc object
 * @ns: ipc namespace
 * @ipcp: ipc permission set
 * @ops: the actual security routine to call
 * @params: its parameters
Nadia Derbey's avatar
Nadia Derbey committed
355
 *
356 357 358
 * This routine is called by sys_msgget(), sys_semget() and sys_shmget()
 * when the key is not IPC_PRIVATE and that key already exists in the
 * ds IDR.
Nadia Derbey's avatar
Nadia Derbey committed
359
 *
360
 * On success, the ipc id is returned.
Nadia Derbey's avatar
Nadia Derbey committed
361
 *
362
 * It is called with ipc_ids.rwsem and ipcp->lock held.
Nadia Derbey's avatar
Nadia Derbey committed
363
 */
364 365
static int ipc_check_perms(struct ipc_namespace *ns,
			   struct kern_ipc_perm *ipcp,
Mathias Krause's avatar
Mathias Krause committed
366
			   const struct ipc_ops *ops,
367
			   struct ipc_params *params)
Nadia Derbey's avatar
Nadia Derbey committed
368 369 370
{
	int err;

371
	if (ipcperms(ns, ipcp, params->flg))
Nadia Derbey's avatar
Nadia Derbey committed
372 373 374 375 376 377 378 379 380 381 382
		err = -EACCES;
	else {
		err = ops->associate(ipcp, params->flg);
		if (!err)
			err = ipcp->id;
	}

	return err;
}

/**
383 384
 * ipcget_public - get an ipc object or create a new one
 * @ns: ipc namespace
385
 * @ids: ipc identifier set
386 387 388 389 390 391 392 393 394
 * @ops: the actual creation routine to call
 * @params: its parameters
 *
 * This routine is called by sys_msgget, sys_semget() and sys_shmget()
 * when the key is not IPC_PRIVATE.
 * It adds a new entry if the key is not found and does some permission
 * / security checkings if the key is found.
 *
 * On success, the ipc id is returned.
Nadia Derbey's avatar
Nadia Derbey committed
395
 */
396
static int ipcget_public(struct ipc_namespace *ns, struct ipc_ids *ids,
Mathias Krause's avatar
Mathias Krause committed
397
		const struct ipc_ops *ops, struct ipc_params *params)
Nadia Derbey's avatar
Nadia Derbey committed
398 399 400 401 402
{
	struct kern_ipc_perm *ipcp;
	int flg = params->flg;
	int err;

Nadia Derbey's avatar
Nadia Derbey committed
403 404 405 406
	/*
	 * Take the lock as a writer since we are potentially going to add
	 * a new entry + read locks are not "upgradable"
	 */
Davidlohr Bueso's avatar
Davidlohr Bueso committed
407
	down_write(&ids->rwsem);
Nadia Derbey's avatar
Nadia Derbey committed
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
	ipcp = ipc_findkey(ids, params->key);
	if (ipcp == NULL) {
		/* key not used */
		if (!(flg & IPC_CREAT))
			err = -ENOENT;
		else
			err = ops->getnew(ns, params);
	} else {
		/* ipc object has been locked by ipc_findkey() */

		if (flg & IPC_CREAT && flg & IPC_EXCL)
			err = -EEXIST;
		else {
			err = 0;
			if (ops->more_checks)
				err = ops->more_checks(ipcp, params);
			if (!err)
Nadia Derbey's avatar
Nadia Derbey committed
425 426 427 428
				/*
				 * ipc_check_perms returns the IPC id on
				 * success
				 */
429
				err = ipc_check_perms(ns, ipcp, ops, params);
Nadia Derbey's avatar
Nadia Derbey committed
430 431 432
		}
		ipc_unlock(ipcp);
	}
Davidlohr Bueso's avatar
Davidlohr Bueso committed
433
	up_write(&ids->rwsem);
Nadia Derbey's avatar
Nadia Derbey committed
434 435 436 437

	return err;
}

438 439 440 441 442 443 444 445 446 447 448 449 450 451
/**
 * ipc_kht_remove - remove an ipc from the key hashtable
 * @ids: ipc identifier set
 * @ipcp: ipc perm structure containing the key to remove
 *
 * ipc_ids.rwsem (as a writer) and the spinlock for this ID are held
 * before this function is called, and remain locked on the exit.
 */
static void ipc_kht_remove(struct ipc_ids *ids, struct kern_ipc_perm *ipcp)
{
	if (ipcp->key != IPC_PRIVATE)
		rhashtable_remove_fast(&ids->key_ht, &ipcp->khtnode,
				       ipc_kht_params);
}
Nadia Derbey's avatar
Nadia Derbey committed
452

Linus Torvalds's avatar
Linus Torvalds committed
453
/**
454 455 456
 * ipc_rmid - remove an ipc identifier
 * @ids: ipc identifier set
 * @ipcp: ipc perm structure containing the identifier to remove
Linus Torvalds's avatar
Linus Torvalds committed
457
 *
458 459
 * ipc_ids.rwsem (as a writer) and the spinlock for this ID are held
 * before this function is called, and remain locked on the exit.
Linus Torvalds's avatar
Linus Torvalds committed
460
 */
Nadia Derbey's avatar
Nadia Derbey committed
461
void ipc_rmid(struct ipc_ids *ids, struct kern_ipc_perm *ipcp)
Linus Torvalds's avatar
Linus Torvalds committed
462
{
463
	int idx = ipcid_to_idx(ipcp->id);
Nadia Derbey's avatar
Nadia Derbey committed
464

465
	idr_remove(&ids->ipcs_idr, idx);
466
	ipc_kht_remove(ids, ipcp);
Linus Torvalds's avatar
Linus Torvalds committed
467
	ids->in_use--;
468
	ipcp->deleted = true;
469

470
	if (unlikely(idx == ids->max_idx)) {
471
		do {
472 473
			idx--;
			if (idx == -1)
474
				break;
475 476
		} while (!idr_find(&ids->ipcs_idr, idx));
		ids->max_idx = idx;
477
	}
Linus Torvalds's avatar
Linus Torvalds committed
478 479
}

480 481 482 483 484 485 486 487 488 489 490 491 492 493
/**
 * ipc_set_key_private - switch the key of an existing ipc to IPC_PRIVATE
 * @ids: ipc identifier set
 * @ipcp: ipc perm structure containing the key to modify
 *
 * ipc_ids.rwsem (as a writer) and the spinlock for this ID are held
 * before this function is called, and remain locked on the exit.
 */
void ipc_set_key_private(struct ipc_ids *ids, struct kern_ipc_perm *ipcp)
{
	ipc_kht_remove(ids, ipcp);
	ipcp->key = IPC_PRIVATE;
}

494
bool ipc_rcu_getref(struct kern_ipc_perm *ptr)
Linus Torvalds's avatar
Linus Torvalds committed
495
{
496
	return refcount_inc_not_zero(&ptr->refcount);
497 498
}

499 500
void ipc_rcu_putref(struct kern_ipc_perm *ptr,
			void (*func)(struct rcu_head *head))
Linus Torvalds's avatar
Linus Torvalds committed
501
{
502
	if (!refcount_dec_and_test(&ptr->refcount))
Linus Torvalds's avatar
Linus Torvalds committed
503 504
		return;

505
	call_rcu(&ptr->rcu, func);
Davidlohr Bueso's avatar
Davidlohr Bueso committed
506 507
}

Linus Torvalds's avatar
Linus Torvalds committed
508
/**
509 510 511 512
 * ipcperms - check ipc permissions
 * @ns: ipc namespace
 * @ipcp: ipc permission set
 * @flag: desired permission set
Linus Torvalds's avatar
Linus Torvalds committed
513
 *
514 515
 * Check user, group, other permissions for access
 * to ipc resources. return 0 if allowed
516
 *
517
 * @flag will most probably be 0 or ``S_...UGO`` from <linux/stat.h>
Linus Torvalds's avatar
Linus Torvalds committed
518
 */
519 520
int ipcperms(struct ipc_namespace *ns, struct kern_ipc_perm *ipcp, short flag)
{
521
	kuid_t euid = current_euid();
Al Viro's avatar
Al Viro committed
522
	int requested_mode, granted_mode;
Linus Torvalds's avatar
Linus Torvalds committed
523

Al Viro's avatar
Al Viro committed
524
	audit_ipc_obj(ipcp);
Linus Torvalds's avatar
Linus Torvalds committed
525 526
	requested_mode = (flag >> 6) | (flag >> 3) | flag;
	granted_mode = ipcp->mode;
527 528
	if (uid_eq(euid, ipcp->cuid) ||
	    uid_eq(euid, ipcp->uid))
Linus Torvalds's avatar
Linus Torvalds committed
529 530 531 532
		granted_mode >>= 6;
	else if (in_group_p(ipcp->cgid) || in_group_p(ipcp->gid))
		granted_mode >>= 3;
	/* is there some bit set in requested_mode but not in granted_mode? */
Paul McQuade's avatar
Paul McQuade committed
533
	if ((requested_mode & ~granted_mode & 0007) &&
534
	    !ns_capable(ns->user_ns, CAP_IPC_OWNER))
Linus Torvalds's avatar
Linus Torvalds committed
535 536 537 538 539 540 541 542 543 544 545
		return -1;

	return security_ipc_permission(ipcp, flag);
}

/*
 * Functions to convert between the kern_ipc_perm structure and the
 * old/new ipc_perm structures
 */

/**
546 547 548
 * kernel_to_ipc64_perm	- convert kernel ipc permissions to user
 * @in: kernel permissions
 * @out: new style ipc permissions
Linus Torvalds's avatar
Linus Torvalds committed
549
 *
550 551
 * Turn the kernel object @in into a set of permissions descriptions
 * for returning to userspace (@out).
Linus Torvalds's avatar
Linus Torvalds committed
552
 */
Manfred Spraul's avatar
Manfred Spraul committed
553
void kernel_to_ipc64_perm(struct kern_ipc_perm *in, struct ipc64_perm *out)
Linus Torvalds's avatar
Linus Torvalds committed
554 555
{
	out->key	= in->key;
556 557 558 559
	out->uid	= from_kuid_munged(current_user_ns(), in->uid);
	out->gid	= from_kgid_munged(current_user_ns(), in->gid);
	out->cuid	= from_kuid_munged(current_user_ns(), in->cuid);
	out->cgid	= from_kgid_munged(current_user_ns(), in->cgid);
Linus Torvalds's avatar
Linus Torvalds committed
560 561 562 563 564
	out->mode	= in->mode;
	out->seq	= in->seq;
}

/**
565 566 567
 * ipc64_perm_to_ipc_perm - convert new ipc permissions to old
 * @in: new style ipc permissions
 * @out: old style ipc permissions
Linus Torvalds's avatar
Linus Torvalds committed
568
 *
569 570
 * Turn the new style permissions object @in into a compatibility
 * object and store it into the @out pointer.
Linus Torvalds's avatar
Linus Torvalds committed
571
 */
Manfred Spraul's avatar
Manfred Spraul committed
572
void ipc64_perm_to_ipc_perm(struct ipc64_perm *in, struct ipc_perm *out)
Linus Torvalds's avatar
Linus Torvalds committed
573 574 575 576 577 578 579 580 581 582
{
	out->key	= in->key;
	SET_UID(out->uid, in->uid);
	SET_GID(out->gid, in->gid);
	SET_UID(out->cuid, in->cuid);
	SET_GID(out->cgid, in->cgid);
	out->mode	= in->mode;
	out->seq	= in->seq;
}

583
/**
584
 * ipc_obtain_object_idr
585 586 587 588 589 590 591 592
 * @ids: ipc identifier set
 * @id: ipc id to look for
 *
 * Look for an id in the ipc ids idr and return associated ipc object.
 *
 * Call inside the RCU critical section.
 * The ipc object is *not* locked on exit.
 */
593
struct kern_ipc_perm *ipc_obtain_object_idr(struct ipc_ids *ids, int id)
594 595
{
	struct kern_ipc_perm *out;
596
	int idx = ipcid_to_idx(id);
597

598
	out = idr_find(&ids->ipcs_idr, idx);
599 600 601 602 603 604 605 606 607 608 609
	if (!out)
		return ERR_PTR(-EINVAL);

	return out;
}

/**
 * ipc_obtain_object_check
 * @ids: ipc identifier set
 * @id: ipc id to look for
 *
610 611
 * Similar to ipc_obtain_object_idr() but also checks the ipc object
 * sequence number.
612 613 614 615 616 617
 *
 * Call inside the RCU critical section.
 * The ipc object is *not* locked on exit.
 */
struct kern_ipc_perm *ipc_obtain_object_check(struct ipc_ids *ids, int id)
{
618
	struct kern_ipc_perm *out = ipc_obtain_object_idr(ids, id);
619 620 621 622 623

	if (IS_ERR(out))
		goto out;

	if (ipc_checkid(out, id))
624
		return ERR_PTR(-EINVAL);
625
out:
Linus Torvalds's avatar
Linus Torvalds committed
626 627 628
	return out;
}

629 630
/**
 * ipcget - Common sys_*get() code
631
 * @ns: namespace
632 633 634 635
 * @ids: ipc identifier set
 * @ops: operations to be called on ipc object creation, permission checks
 *       and further checks
 * @params: the parameters needed by the previous operations.
636 637 638 639
 *
 * Common routine called by sys_msgget(), sys_semget() and sys_shmget().
 */
int ipcget(struct ipc_namespace *ns, struct ipc_ids *ids,
Mathias Krause's avatar
Mathias Krause committed
640
			const struct ipc_ops *ops, struct ipc_params *params)
641 642 643 644 645 646 647
{
	if (params->key == IPC_PRIVATE)
		return ipcget_new(ns, ids, ops, params);
	else
		return ipcget_public(ns, ids, ops, params);
}

648
/**
649
 * ipc_update_perm - update the permissions of an ipc object
650 651 652
 * @in:  the permission given as input.
 * @out: the permission of the ipc to set.
 */
653
int ipc_update_perm(struct ipc64_perm *in, struct kern_ipc_perm *out)
654
{
655 656 657 658 659 660 661
	kuid_t uid = make_kuid(current_user_ns(), in->uid);
	kgid_t gid = make_kgid(current_user_ns(), in->gid);
	if (!uid_valid(uid) || !gid_valid(gid))
		return -EINVAL;

	out->uid = uid;
	out->gid = gid;
662 663
	out->mode = (out->mode & ~S_IRWXUGO)
		| (in->mode & S_IRWXUGO);
664 665

	return 0;
666 667
}

668
/**
669
 * ipcctl_obtain_check - retrieve an ipc object and check permissions
670
 * @ns:  ipc namespace
671 672 673 674 675 676 677 678
 * @ids:  the table of ids where to look for the ipc
 * @id:   the id of the ipc to retrieve
 * @cmd:  the cmd to check
 * @perm: the permission to set
 * @extra_perm: one extra permission parameter used by msq
 *
 * This function does some common audit and permissions check for some IPC_XXX
 * cmd and is called from semctl_down, shmctl_down and msgctl_down.
679
 *
680 681
 * It:
 *   - retrieves the ipc object with the given id in the given table.
682 683 684
 *   - performs some audit and permission check, depending on the given cmd
 *   - returns a pointer to the ipc object or otherwise, the corresponding
 *     error.
685
 *
Davidlohr Bueso's avatar
Davidlohr Bueso committed
686
 * Call holding the both the rwsem and the rcu read lock.
687
 */
688
struct kern_ipc_perm *ipcctl_obtain_check(struct ipc_namespace *ns,
Davidlohr Bueso's avatar
Davidlohr Bueso committed
689 690
					struct ipc_ids *ids, int id, int cmd,
					struct ipc64_perm *perm, int extra_perm)
691
{
692
	kuid_t euid;
693 694
	int err = -EPERM;
	struct kern_ipc_perm *ipcp;
695

696
	ipcp = ipc_obtain_object_check(ids, id);
697 698
	if (IS_ERR(ipcp)) {
		err = PTR_ERR(ipcp);
699
		goto err;
700 701
	}

Al Viro's avatar
Al Viro committed
702
	audit_ipc_obj(ipcp);
Al Viro's avatar
Al Viro committed
703 704
	if (cmd == IPC_SET)
		audit_ipc_set_perm(extra_perm, perm->uid,
705
				   perm->gid, perm->mode);
706 707

	euid = current_euid();
708
	if (uid_eq(euid, ipcp->cuid) || uid_eq(euid, ipcp->uid)  ||
709
	    ns_capable(ns->user_ns, CAP_SYS_ADMIN))
710 711
		return ipcp; /* successful lookup */
err:
712 713 714
	return ERR_PTR(err);
}

715
#ifdef CONFIG_ARCH_WANT_IPC_PARSE_VERSION
Linus Torvalds's avatar
Linus Torvalds committed
716 717 718


/**
719 720
 * ipc_parse_version - ipc call version
 * @cmd: pointer to command
Linus Torvalds's avatar
Linus Torvalds committed
721
 *
722 723 724
 * Return IPC_64 for new style IPC and IPC_OLD for old style IPC.
 * The @cmd value is turned from an encoding command and version into
 * just the command code.
Linus Torvalds's avatar
Linus Torvalds committed
725
 */
Manfred Spraul's avatar
Manfred Spraul committed
726
int ipc_parse_version(int *cmd)
Linus Torvalds's avatar
Linus Torvalds committed
727 728 729 730 731 732 733 734 735
{
	if (*cmd & IPC_64) {
		*cmd ^= IPC_64;
		return IPC_64;
	} else {
		return IPC_OLD;
	}
}

736
#endif /* CONFIG_ARCH_WANT_IPC_PARSE_VERSION */
737 738

#ifdef CONFIG_PROC_FS
739 740
struct ipc_proc_iter {
	struct ipc_namespace *ns;
741
	struct pid_namespace *pid_ns;
742 743 744
	struct ipc_proc_iface *iface;
};

745 746 747 748 749 750
struct pid_namespace *ipc_seq_pid_ns(struct seq_file *s)
{
	struct ipc_proc_iter *iter = s->private;
	return iter->pid_ns;
}

Nadia Derbey's avatar
Nadia Derbey committed
751 752 753
/*
 * This routine locks the ipc structure found at least at position pos.
 */
754 755
static struct kern_ipc_perm *sysvipc_find_ipc(struct ipc_ids *ids, loff_t pos,
					      loff_t *new_pos)
756
{
Nadia Derbey's avatar
Nadia Derbey committed
757 758
	struct kern_ipc_perm *ipc;
	int total, id;
759

Nadia Derbey's avatar
Nadia Derbey committed
760 761 762 763 764 765
	total = 0;
	for (id = 0; id < pos && total < ids->in_use; id++) {
		ipc = idr_find(&ids->ipcs_idr, id);
		if (ipc != NULL)
			total++;
	}
766

767
	*new_pos = pos + 1;
Nadia Derbey's avatar
Nadia Derbey committed
768 769
	if (total >= ids->in_use)
		return NULL;
770

771
	for (; pos < ipc_mni; pos++) {
Nadia Derbey's avatar
Nadia Derbey committed
772 773
		ipc = idr_find(&ids->ipcs_idr, pos);
		if (ipc != NULL) {
Davidlohr Bueso's avatar
Davidlohr Bueso committed
774 775
			rcu_read_lock();
			ipc_lock_object(ipc);
776 777 778 779 780 781 782 783
			return ipc;
		}
	}

	/* Out of range - return NULL to terminate iteration */
	return NULL;
}

Nadia Derbey's avatar
Nadia Derbey committed
784 785 786 787 788 789 790 791 792 793
static void *sysvipc_proc_next(struct seq_file *s, void *it, loff_t *pos)
{
	struct ipc_proc_iter *iter = s->private;
	struct ipc_proc_iface *iface = iter->iface;
	struct kern_ipc_perm *ipc = it;

	/* If we had an ipc id locked before, unlock it */
	if (ipc && ipc != SEQ_START_TOKEN)
		ipc_unlock(ipc);

794
	return sysvipc_find_ipc(&iter->ns->ids[iface->ids], *pos, pos);
Nadia Derbey's avatar
Nadia Derbey committed
795 796
}

797
/*
Nadia Derbey's avatar
Nadia Derbey committed
798 799
 * File positions: pos 0 -> header, pos n -> ipc id = n - 1.
 * SeqFile iterator: iterator value locked ipc pointer or SEQ_TOKEN_START.
800 801 802
 */
static void *sysvipc_proc_start(struct seq_file *s, loff_t *pos)
{
803 804
	struct ipc_proc_iter *iter = s->private;
	struct ipc_proc_iface *iface = iter->iface;
805 806
	struct ipc_ids *ids;

807
	ids = &iter->ns->ids[iface->ids];
808 809 810 811 812

	/*
	 * Take the lock - this will be released by the corresponding
	 * call to stop().
	 */
Davidlohr Bueso's avatar
Davidlohr Bueso committed
813
	down_read(&ids->rwsem);
814 815 816 817 818 819 820 821 822 823

	/* pos < 0 is invalid */
	if (*pos < 0)
		return NULL;

	/* pos == 0 means header */
	if (*pos == 0)
		return SEQ_START_TOKEN;

	/* Find the (pos-1)th ipc */
Nadia Derbey's avatar
Nadia Derbey committed
824
	return sysvipc_find_ipc(ids, *pos - 1, pos);
825 826 827 828 829
}

static void sysvipc_proc_stop(struct seq_file *s, void *it)
{
	struct kern_ipc_perm *ipc = it;
830 831
	struct ipc_proc_iter *iter = s->private;
	struct ipc_proc_iface *iface = iter->iface;
832
	struct ipc_ids *ids;
833

Nadia Derbey's avatar
Nadia Derbey committed
834
	/* If we had a locked structure, release it */
835 836 837
	if (ipc && ipc != SEQ_START_TOKEN)
		ipc_unlock(ipc);

838
	ids = &iter->ns->ids[iface->ids];
839
	/* Release the lock we took in start() */
Davidlohr Bueso's avatar
Davidlohr Bueso committed
840
	up_read(&ids->rwsem);
841 842 843 844
}

static int sysvipc_proc_show(struct seq_file *s, void *it)
{
845 846
	struct ipc_proc_iter *iter = s->private;
	struct ipc_proc_iface *iface = iter->iface;
847

848 849 850 851
	if (it == SEQ_START_TOKEN) {
		seq_puts(s, iface->header);
		return 0;
	}
852 853 854 855

	return iface->show(s, it);
}

856
static const struct seq_operations sysvipc_proc_seqops = {
857 858 859 860 861 862
	.start = sysvipc_proc_start,
	.stop  = sysvipc_proc_stop,
	.next  = sysvipc_proc_next,
	.show  = sysvipc_proc_show,
};

863 864 865 866
static int sysvipc_proc_open(struct inode *inode, struct file *file)
{
	struct ipc_proc_iter *iter;

867
	iter = __seq_open_private(file, &sysvipc_proc_seqops, sizeof(*iter));
868
	if (!iter)
869
		return -ENOMEM;
870

Al Viro's avatar
Al Viro committed
871
	iter->iface = PDE_DATA(inode);
872
	iter->ns    = get_ipc_ns(current->nsproxy->ipc_ns);
873
	iter->pid_ns = get_pid_ns(task_active_pid_ns(current));
874 875

	return 0;
876 877 878 879 880 881 882
}

static int sysvipc_proc_release(struct inode *inode, struct file *file)
{
	struct seq_file *seq = file->private_data;
	struct ipc_proc_iter *iter = seq->private;
	put_ipc_ns(iter->ns);
883
	put_pid_ns(iter->pid_ns);
884
	return seq_release_private(inode, file);
885 886
}

887
static const struct proc_ops sysvipc_proc_ops = {
888
	.proc_flags	= PROC_ENTRY_PERMANENT,
889 890 891 892
	.proc_open	= sysvipc_proc_open,
	.proc_read	= seq_read,
	.proc_lseek	= seq_lseek,
	.proc_release	= sysvipc_proc_release,
893 894
};
#endif /* CONFIG_PROC_FS */