1/**
2 * eCryptfs: Linux filesystem encryption layer
3 *
4 * Copyright (C) 2004-2008 International Business Machines Corp.
5 *   Author(s): Michael A. Halcrow <mhalcrow@us.ibm.com>
6 *		Tyler Hicks <tyhicks@ou.edu>
7 *
8 * This program is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU General Public License version
10 * 2 as published by the Free Software Foundation.
11 *
12 * This program is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 * General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
20 * 02111-1307, USA.
21 */
22#include <linux/sched.h>
23#include <linux/slab.h>
24#include <linux/user_namespace.h>
25#include <linux/nsproxy.h>
26#include "ecryptfs_kernel.h"
27
28static LIST_HEAD(ecryptfs_msg_ctx_free_list);
29static LIST_HEAD(ecryptfs_msg_ctx_alloc_list);
30static struct mutex ecryptfs_msg_ctx_lists_mux;
31
32static struct hlist_head *ecryptfs_daemon_hash;
33struct mutex ecryptfs_daemon_hash_mux;
34static int ecryptfs_hash_bits;
35#define ecryptfs_current_euid_hash(uid) \
36	hash_long((unsigned long)from_kuid(&init_user_ns, current_euid()), ecryptfs_hash_bits)
37
38static u32 ecryptfs_msg_counter;
39static struct ecryptfs_msg_ctx *ecryptfs_msg_ctx_arr;
40
41/**
42 * ecryptfs_acquire_free_msg_ctx
43 * @msg_ctx: The context that was acquired from the free list
44 *
45 * Acquires a context element from the free list and locks the mutex
46 * on the context.  Sets the msg_ctx task to current.  Returns zero on
47 * success; non-zero on error or upon failure to acquire a free
48 * context element.  Must be called with ecryptfs_msg_ctx_lists_mux
49 * held.
50 */
51static int ecryptfs_acquire_free_msg_ctx(struct ecryptfs_msg_ctx **msg_ctx)
52{
53	struct list_head *p;
54	int rc;
55
56	if (list_empty(&ecryptfs_msg_ctx_free_list)) {
57		printk(KERN_WARNING "%s: The eCryptfs free "
58		       "context list is empty.  It may be helpful to "
59		       "specify the ecryptfs_message_buf_len "
60		       "parameter to be greater than the current "
61		       "value of [%d]\n", __func__, ecryptfs_message_buf_len);
62		rc = -ENOMEM;
63		goto out;
64	}
65	list_for_each(p, &ecryptfs_msg_ctx_free_list) {
66		*msg_ctx = list_entry(p, struct ecryptfs_msg_ctx, node);
67		if (mutex_trylock(&(*msg_ctx)->mux)) {
68			(*msg_ctx)->task = current;
69			rc = 0;
70			goto out;
71		}
72	}
73	rc = -ENOMEM;
74out:
75	return rc;
76}
77
78/**
79 * ecryptfs_msg_ctx_free_to_alloc
80 * @msg_ctx: The context to move from the free list to the alloc list
81 *
82 * Must be called with ecryptfs_msg_ctx_lists_mux held.
83 */
84static void ecryptfs_msg_ctx_free_to_alloc(struct ecryptfs_msg_ctx *msg_ctx)
85{
86	list_move(&msg_ctx->node, &ecryptfs_msg_ctx_alloc_list);
87	msg_ctx->state = ECRYPTFS_MSG_CTX_STATE_PENDING;
88	msg_ctx->counter = ++ecryptfs_msg_counter;
89}
90
91/**
92 * ecryptfs_msg_ctx_alloc_to_free
93 * @msg_ctx: The context to move from the alloc list to the free list
94 *
95 * Must be called with ecryptfs_msg_ctx_lists_mux held.
96 */
97void ecryptfs_msg_ctx_alloc_to_free(struct ecryptfs_msg_ctx *msg_ctx)
98{
99	list_move(&(msg_ctx->node), &ecryptfs_msg_ctx_free_list);
100	kfree(msg_ctx->msg);
101	msg_ctx->msg = NULL;
102	msg_ctx->state = ECRYPTFS_MSG_CTX_STATE_FREE;
103}
104
105/**
106 * ecryptfs_find_daemon_by_euid
107 * @daemon: If return value is zero, points to the desired daemon pointer
108 *
109 * Must be called with ecryptfs_daemon_hash_mux held.
110 *
111 * Search the hash list for the current effective user id.
112 *
113 * Returns zero if the user id exists in the list; non-zero otherwise.
114 */
115int ecryptfs_find_daemon_by_euid(struct ecryptfs_daemon **daemon)
116{
117	int rc;
118
119	hlist_for_each_entry(*daemon,
120			    &ecryptfs_daemon_hash[ecryptfs_current_euid_hash()],
121			    euid_chain) {
122		if (uid_eq((*daemon)->file->f_cred->euid, current_euid())) {
123			rc = 0;
124			goto out;
125		}
126	}
127	rc = -EINVAL;
128out:
129	return rc;
130}
131
132/**
133 * ecryptfs_spawn_daemon - Create and initialize a new daemon struct
134 * @daemon: Pointer to set to newly allocated daemon struct
135 * @file: File used when opening /dev/ecryptfs
136 *
137 * Must be called ceremoniously while in possession of
138 * ecryptfs_sacred_daemon_hash_mux
139 *
140 * Returns zero on success; non-zero otherwise
141 */
142int
143ecryptfs_spawn_daemon(struct ecryptfs_daemon **daemon, struct file *file)
144{
145	int rc = 0;
146
147	(*daemon) = kzalloc(sizeof(**daemon), GFP_KERNEL);
148	if (!(*daemon)) {
149		rc = -ENOMEM;
150		printk(KERN_ERR "%s: Failed to allocate [%zd] bytes of "
151		       "GFP_KERNEL memory\n", __func__, sizeof(**daemon));
152		goto out;
153	}
154	(*daemon)->file = file;
155	mutex_init(&(*daemon)->mux);
156	INIT_LIST_HEAD(&(*daemon)->msg_ctx_out_queue);
157	init_waitqueue_head(&(*daemon)->wait);
158	(*daemon)->num_queued_msg_ctx = 0;
159	hlist_add_head(&(*daemon)->euid_chain,
160		       &ecryptfs_daemon_hash[ecryptfs_current_euid_hash()]);
161out:
162	return rc;
163}
164
165/**
166 * ecryptfs_exorcise_daemon - Destroy the daemon struct
167 *
168 * Must be called ceremoniously while in possession of
169 * ecryptfs_daemon_hash_mux and the daemon's own mux.
170 */
171int ecryptfs_exorcise_daemon(struct ecryptfs_daemon *daemon)
172{
173	struct ecryptfs_msg_ctx *msg_ctx, *msg_ctx_tmp;
174	int rc = 0;
175
176	mutex_lock(&daemon->mux);
177	if ((daemon->flags & ECRYPTFS_DAEMON_IN_READ)
178	    || (daemon->flags & ECRYPTFS_DAEMON_IN_POLL)) {
179		rc = -EBUSY;
180		mutex_unlock(&daemon->mux);
181		goto out;
182	}
183	list_for_each_entry_safe(msg_ctx, msg_ctx_tmp,
184				 &daemon->msg_ctx_out_queue, daemon_out_list) {
185		list_del(&msg_ctx->daemon_out_list);
186		daemon->num_queued_msg_ctx--;
187		printk(KERN_WARNING "%s: Warning: dropping message that is in "
188		       "the out queue of a dying daemon\n", __func__);
189		ecryptfs_msg_ctx_alloc_to_free(msg_ctx);
190	}
191	hlist_del(&daemon->euid_chain);
192	mutex_unlock(&daemon->mux);
193	kzfree(daemon);
194out:
195	return rc;
196}
197
198/**
199 * ecryptfs_process_reponse
200 * @msg: The ecryptfs message received; the caller should sanity check
201 *       msg->data_len and free the memory
202 * @seq: The sequence number of the message; must match the sequence
203 *       number for the existing message context waiting for this
204 *       response
205 *
206 * Processes a response message after sending an operation request to
207 * userspace. Some other process is awaiting this response. Before
208 * sending out its first communications, the other process allocated a
209 * msg_ctx from the ecryptfs_msg_ctx_arr at a particular index. The
210 * response message contains this index so that we can copy over the
211 * response message into the msg_ctx that the process holds a
212 * reference to. The other process is going to wake up, check to see
213 * that msg_ctx->state == ECRYPTFS_MSG_CTX_STATE_DONE, and then
214 * proceed to read off and process the response message. Returns zero
215 * upon delivery to desired context element; non-zero upon delivery
216 * failure or error.
217 *
218 * Returns zero on success; non-zero otherwise
219 */
220int ecryptfs_process_response(struct ecryptfs_daemon *daemon,
221			      struct ecryptfs_message *msg, u32 seq)
222{
223	struct ecryptfs_msg_ctx *msg_ctx;
224	size_t msg_size;
225	int rc;
226
227	if (msg->index >= ecryptfs_message_buf_len) {
228		rc = -EINVAL;
229		printk(KERN_ERR "%s: Attempt to reference "
230		       "context buffer at index [%d]; maximum "
231		       "allowable is [%d]\n", __func__, msg->index,
232		       (ecryptfs_message_buf_len - 1));
233		goto out;
234	}
235	msg_ctx = &ecryptfs_msg_ctx_arr[msg->index];
236	mutex_lock(&msg_ctx->mux);
237	if (msg_ctx->state != ECRYPTFS_MSG_CTX_STATE_PENDING) {
238		rc = -EINVAL;
239		printk(KERN_WARNING "%s: Desired context element is not "
240		       "pending a response\n", __func__);
241		goto unlock;
242	} else if (msg_ctx->counter != seq) {
243		rc = -EINVAL;
244		printk(KERN_WARNING "%s: Invalid message sequence; "
245		       "expected [%d]; received [%d]\n", __func__,
246		       msg_ctx->counter, seq);
247		goto unlock;
248	}
249	msg_size = (sizeof(*msg) + msg->data_len);
250	msg_ctx->msg = kmemdup(msg, msg_size, GFP_KERNEL);
251	if (!msg_ctx->msg) {
252		rc = -ENOMEM;
253		printk(KERN_ERR "%s: Failed to allocate [%zd] bytes of "
254		       "GFP_KERNEL memory\n", __func__, msg_size);
255		goto unlock;
256	}
257	msg_ctx->state = ECRYPTFS_MSG_CTX_STATE_DONE;
258	wake_up_process(msg_ctx->task);
259	rc = 0;
260unlock:
261	mutex_unlock(&msg_ctx->mux);
262out:
263	return rc;
264}
265
266/**
267 * ecryptfs_send_message_locked
268 * @data: The data to send
269 * @data_len: The length of data
270 * @msg_ctx: The message context allocated for the send
271 *
272 * Must be called with ecryptfs_daemon_hash_mux held.
273 *
274 * Returns zero on success; non-zero otherwise
275 */
276static int
277ecryptfs_send_message_locked(char *data, int data_len, u8 msg_type,
278			     struct ecryptfs_msg_ctx **msg_ctx)
279{
280	struct ecryptfs_daemon *daemon;
281	int rc;
282
283	rc = ecryptfs_find_daemon_by_euid(&daemon);
284	if (rc) {
285		rc = -ENOTCONN;
286		goto out;
287	}
288	mutex_lock(&ecryptfs_msg_ctx_lists_mux);
289	rc = ecryptfs_acquire_free_msg_ctx(msg_ctx);
290	if (rc) {
291		mutex_unlock(&ecryptfs_msg_ctx_lists_mux);
292		printk(KERN_WARNING "%s: Could not claim a free "
293		       "context element\n", __func__);
294		goto out;
295	}
296	ecryptfs_msg_ctx_free_to_alloc(*msg_ctx);
297	mutex_unlock(&(*msg_ctx)->mux);
298	mutex_unlock(&ecryptfs_msg_ctx_lists_mux);
299	rc = ecryptfs_send_miscdev(data, data_len, *msg_ctx, msg_type, 0,
300				   daemon);
301	if (rc)
302		printk(KERN_ERR "%s: Error attempting to send message to "
303		       "userspace daemon; rc = [%d]\n", __func__, rc);
304out:
305	return rc;
306}
307
308/**
309 * ecryptfs_send_message
310 * @data: The data to send
311 * @data_len: The length of data
312 * @msg_ctx: The message context allocated for the send
313 *
314 * Grabs ecryptfs_daemon_hash_mux.
315 *
316 * Returns zero on success; non-zero otherwise
317 */
318int ecryptfs_send_message(char *data, int data_len,
319			  struct ecryptfs_msg_ctx **msg_ctx)
320{
321	int rc;
322
323	mutex_lock(&ecryptfs_daemon_hash_mux);
324	rc = ecryptfs_send_message_locked(data, data_len, ECRYPTFS_MSG_REQUEST,
325					  msg_ctx);
326	mutex_unlock(&ecryptfs_daemon_hash_mux);
327	return rc;
328}
329
330/**
331 * ecryptfs_wait_for_response
332 * @msg_ctx: The context that was assigned when sending a message
333 * @msg: The incoming message from userspace; not set if rc != 0
334 *
335 * Sleeps until awaken by ecryptfs_receive_message or until the amount
336 * of time exceeds ecryptfs_message_wait_timeout.  If zero is
337 * returned, msg will point to a valid message from userspace; a
338 * non-zero value is returned upon failure to receive a message or an
339 * error occurs. Callee must free @msg on success.
340 */
341int ecryptfs_wait_for_response(struct ecryptfs_msg_ctx *msg_ctx,
342			       struct ecryptfs_message **msg)
343{
344	signed long timeout = ecryptfs_message_wait_timeout * HZ;
345	int rc = 0;
346
347sleep:
348	timeout = schedule_timeout_interruptible(timeout);
349	mutex_lock(&ecryptfs_msg_ctx_lists_mux);
350	mutex_lock(&msg_ctx->mux);
351	if (msg_ctx->state != ECRYPTFS_MSG_CTX_STATE_DONE) {
352		if (timeout) {
353			mutex_unlock(&msg_ctx->mux);
354			mutex_unlock(&ecryptfs_msg_ctx_lists_mux);
355			goto sleep;
356		}
357		rc = -ENOMSG;
358	} else {
359		*msg = msg_ctx->msg;
360		msg_ctx->msg = NULL;
361	}
362	ecryptfs_msg_ctx_alloc_to_free(msg_ctx);
363	mutex_unlock(&msg_ctx->mux);
364	mutex_unlock(&ecryptfs_msg_ctx_lists_mux);
365	return rc;
366}
367
368int __init ecryptfs_init_messaging(void)
369{
370	int i;
371	int rc = 0;
372
373	if (ecryptfs_number_of_users > ECRYPTFS_MAX_NUM_USERS) {
374		ecryptfs_number_of_users = ECRYPTFS_MAX_NUM_USERS;
375		printk(KERN_WARNING "%s: Specified number of users is "
376		       "too large, defaulting to [%d] users\n", __func__,
377		       ecryptfs_number_of_users);
378	}
379	mutex_init(&ecryptfs_daemon_hash_mux);
380	mutex_lock(&ecryptfs_daemon_hash_mux);
381	ecryptfs_hash_bits = 1;
382	while (ecryptfs_number_of_users >> ecryptfs_hash_bits)
383		ecryptfs_hash_bits++;
384	ecryptfs_daemon_hash = kmalloc((sizeof(struct hlist_head)
385					* (1 << ecryptfs_hash_bits)),
386				       GFP_KERNEL);
387	if (!ecryptfs_daemon_hash) {
388		rc = -ENOMEM;
389		printk(KERN_ERR "%s: Failed to allocate memory\n", __func__);
390		mutex_unlock(&ecryptfs_daemon_hash_mux);
391		goto out;
392	}
393	for (i = 0; i < (1 << ecryptfs_hash_bits); i++)
394		INIT_HLIST_HEAD(&ecryptfs_daemon_hash[i]);
395	mutex_unlock(&ecryptfs_daemon_hash_mux);
396	ecryptfs_msg_ctx_arr = kmalloc((sizeof(struct ecryptfs_msg_ctx)
397					* ecryptfs_message_buf_len),
398				       GFP_KERNEL);
399	if (!ecryptfs_msg_ctx_arr) {
400		rc = -ENOMEM;
401		printk(KERN_ERR "%s: Failed to allocate memory\n", __func__);
402		goto out;
403	}
404	mutex_init(&ecryptfs_msg_ctx_lists_mux);
405	mutex_lock(&ecryptfs_msg_ctx_lists_mux);
406	ecryptfs_msg_counter = 0;
407	for (i = 0; i < ecryptfs_message_buf_len; i++) {
408		INIT_LIST_HEAD(&ecryptfs_msg_ctx_arr[i].node);
409		INIT_LIST_HEAD(&ecryptfs_msg_ctx_arr[i].daemon_out_list);
410		mutex_init(&ecryptfs_msg_ctx_arr[i].mux);
411		mutex_lock(&ecryptfs_msg_ctx_arr[i].mux);
412		ecryptfs_msg_ctx_arr[i].index = i;
413		ecryptfs_msg_ctx_arr[i].state = ECRYPTFS_MSG_CTX_STATE_FREE;
414		ecryptfs_msg_ctx_arr[i].counter = 0;
415		ecryptfs_msg_ctx_arr[i].task = NULL;
416		ecryptfs_msg_ctx_arr[i].msg = NULL;
417		list_add_tail(&ecryptfs_msg_ctx_arr[i].node,
418			      &ecryptfs_msg_ctx_free_list);
419		mutex_unlock(&ecryptfs_msg_ctx_arr[i].mux);
420	}
421	mutex_unlock(&ecryptfs_msg_ctx_lists_mux);
422	rc = ecryptfs_init_ecryptfs_miscdev();
423	if (rc)
424		ecryptfs_release_messaging();
425out:
426	return rc;
427}
428
429void ecryptfs_release_messaging(void)
430{
431	if (ecryptfs_msg_ctx_arr) {
432		int i;
433
434		mutex_lock(&ecryptfs_msg_ctx_lists_mux);
435		for (i = 0; i < ecryptfs_message_buf_len; i++) {
436			mutex_lock(&ecryptfs_msg_ctx_arr[i].mux);
437			kfree(ecryptfs_msg_ctx_arr[i].msg);
438			mutex_unlock(&ecryptfs_msg_ctx_arr[i].mux);
439		}
440		kfree(ecryptfs_msg_ctx_arr);
441		mutex_unlock(&ecryptfs_msg_ctx_lists_mux);
442	}
443	if (ecryptfs_daemon_hash) {
444		struct ecryptfs_daemon *daemon;
445		int i;
446
447		mutex_lock(&ecryptfs_daemon_hash_mux);
448		for (i = 0; i < (1 << ecryptfs_hash_bits); i++) {
449			int rc;
450
451			hlist_for_each_entry(daemon,
452					     &ecryptfs_daemon_hash[i],
453					     euid_chain) {
454				rc = ecryptfs_exorcise_daemon(daemon);
455				if (rc)
456					printk(KERN_ERR "%s: Error whilst "
457					       "attempting to destroy daemon; "
458					       "rc = [%d]. Dazed and confused, "
459					       "but trying to continue.\n",
460					       __func__, rc);
461			}
462		}
463		kfree(ecryptfs_daemon_hash);
464		mutex_unlock(&ecryptfs_daemon_hash_mux);
465	}
466	ecryptfs_destroy_ecryptfs_miscdev();
467	return;
468}
469