d2a7161e94c3f6d560ef67c0078fd87067825670
[pandora-kernel.git] / fs / ecryptfs / miscdev.c
1 /**
2  * eCryptfs: Linux filesystem encryption layer
3  *
4  * Copyright (C) 2008 International Business Machines Corp.
5  *   Author(s): Michael A. Halcrow <mhalcrow@us.ibm.com>
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License version
9  * 2 as published by the Free Software Foundation.
10  *
11  * This program is distributed in the hope that it will be useful, but
12  * WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
19  * 02111-1307, USA.
20  */
21
22 #include <linux/fs.h>
23 #include <linux/hash.h>
24 #include <linux/random.h>
25 #include <linux/miscdevice.h>
26 #include <linux/poll.h>
27 #include <linux/slab.h>
28 #include <linux/wait.h>
29 #include <linux/module.h>
30 #include "ecryptfs_kernel.h"
31
32 static atomic_t ecryptfs_num_miscdev_opens;
33
34 /**
35  * ecryptfs_miscdev_poll
36  * @file: dev file (ignored)
37  * @pt: dev poll table (ignored)
38  *
39  * Returns the poll mask
40  */
41 static unsigned int
42 ecryptfs_miscdev_poll(struct file *file, poll_table *pt)
43 {
44         struct ecryptfs_daemon *daemon;
45         unsigned int mask = 0;
46         uid_t euid = current_euid();
47         int rc;
48
49         mutex_lock(&ecryptfs_daemon_hash_mux);
50         /* TODO: Just use file->private_data? */
51         rc = ecryptfs_find_daemon_by_euid(&daemon, euid, current_user_ns());
52         if (rc || !daemon) {
53                 mutex_unlock(&ecryptfs_daemon_hash_mux);
54                 return -EINVAL;
55         }
56         mutex_lock(&daemon->mux);
57         mutex_unlock(&ecryptfs_daemon_hash_mux);
58         if (daemon->flags & ECRYPTFS_DAEMON_ZOMBIE) {
59                 printk(KERN_WARNING "%s: Attempt to poll on zombified "
60                        "daemon\n", __func__);
61                 goto out_unlock_daemon;
62         }
63         if (daemon->flags & ECRYPTFS_DAEMON_IN_READ)
64                 goto out_unlock_daemon;
65         if (daemon->flags & ECRYPTFS_DAEMON_IN_POLL)
66                 goto out_unlock_daemon;
67         daemon->flags |= ECRYPTFS_DAEMON_IN_POLL;
68         mutex_unlock(&daemon->mux);
69         poll_wait(file, &daemon->wait, pt);
70         mutex_lock(&daemon->mux);
71         if (!list_empty(&daemon->msg_ctx_out_queue))
72                 mask |= POLLIN | POLLRDNORM;
73 out_unlock_daemon:
74         daemon->flags &= ~ECRYPTFS_DAEMON_IN_POLL;
75         mutex_unlock(&daemon->mux);
76         return mask;
77 }
78
79 /**
80  * ecryptfs_miscdev_open
81  * @inode: inode of miscdev handle (ignored)
82  * @file: file for miscdev handle (ignored)
83  *
84  * Returns zero on success; non-zero otherwise
85  */
86 static int
87 ecryptfs_miscdev_open(struct inode *inode, struct file *file)
88 {
89         struct ecryptfs_daemon *daemon = NULL;
90         uid_t euid = current_euid();
91         int rc;
92
93         mutex_lock(&ecryptfs_daemon_hash_mux);
94         rc = try_module_get(THIS_MODULE);
95         if (rc == 0) {
96                 rc = -EIO;
97                 printk(KERN_ERR "%s: Error attempting to increment module use "
98                        "count; rc = [%d]\n", __func__, rc);
99                 goto out_unlock_daemon_list;
100         }
101         rc = ecryptfs_find_daemon_by_euid(&daemon, euid, current_user_ns());
102         if (rc || !daemon) {
103                 rc = ecryptfs_spawn_daemon(&daemon, euid, current_user_ns(),
104                                            task_pid(current));
105                 if (rc) {
106                         printk(KERN_ERR "%s: Error attempting to spawn daemon; "
107                                "rc = [%d]\n", __func__, rc);
108                         goto out_module_put_unlock_daemon_list;
109                 }
110         }
111         mutex_lock(&daemon->mux);
112         if (daemon->pid != task_pid(current)) {
113                 rc = -EINVAL;
114                 printk(KERN_ERR "%s: pid [0x%p] has registered with euid [%d], "
115                        "but pid [0x%p] has attempted to open the handle "
116                        "instead\n", __func__, daemon->pid, daemon->euid,
117                        task_pid(current));
118                 goto out_unlock_daemon;
119         }
120         if (daemon->flags & ECRYPTFS_DAEMON_MISCDEV_OPEN) {
121                 rc = -EBUSY;
122                 printk(KERN_ERR "%s: Miscellaneous device handle may only be "
123                        "opened once per daemon; pid [0x%p] already has this "
124                        "handle open\n", __func__, daemon->pid);
125                 goto out_unlock_daemon;
126         }
127         daemon->flags |= ECRYPTFS_DAEMON_MISCDEV_OPEN;
128         file->private_data = daemon;
129         atomic_inc(&ecryptfs_num_miscdev_opens);
130 out_unlock_daemon:
131         mutex_unlock(&daemon->mux);
132 out_module_put_unlock_daemon_list:
133         if (rc)
134                 module_put(THIS_MODULE);
135 out_unlock_daemon_list:
136         mutex_unlock(&ecryptfs_daemon_hash_mux);
137         return rc;
138 }
139
140 /**
141  * ecryptfs_miscdev_release
142  * @inode: inode of fs/ecryptfs/euid handle (ignored)
143  * @file: file for fs/ecryptfs/euid handle (ignored)
144  *
145  * This keeps the daemon registered until the daemon sends another
146  * ioctl to fs/ecryptfs/ctl or until the kernel module unregisters.
147  *
148  * Returns zero on success; non-zero otherwise
149  */
150 static int
151 ecryptfs_miscdev_release(struct inode *inode, struct file *file)
152 {
153         struct ecryptfs_daemon *daemon = NULL;
154         uid_t euid = current_euid();
155         int rc;
156
157         mutex_lock(&ecryptfs_daemon_hash_mux);
158         rc = ecryptfs_find_daemon_by_euid(&daemon, euid, current_user_ns());
159         if (rc || !daemon)
160                 daemon = file->private_data;
161         mutex_lock(&daemon->mux);
162         BUG_ON(!(daemon->flags & ECRYPTFS_DAEMON_MISCDEV_OPEN));
163         daemon->flags &= ~ECRYPTFS_DAEMON_MISCDEV_OPEN;
164         atomic_dec(&ecryptfs_num_miscdev_opens);
165         mutex_unlock(&daemon->mux);
166         rc = ecryptfs_exorcise_daemon(daemon);
167         if (rc) {
168                 printk(KERN_CRIT "%s: Fatal error whilst attempting to "
169                        "shut down daemon; rc = [%d]. Please report this "
170                        "bug.\n", __func__, rc);
171                 BUG();
172         }
173         module_put(THIS_MODULE);
174         mutex_unlock(&ecryptfs_daemon_hash_mux);
175         return rc;
176 }
177
178 /**
179  * ecryptfs_send_miscdev
180  * @data: Data to send to daemon; may be NULL
181  * @data_size: Amount of data to send to daemon
182  * @msg_ctx: Message context, which is used to handle the reply. If
183  *           this is NULL, then we do not expect a reply.
184  * @msg_type: Type of message
185  * @msg_flags: Flags for message
186  * @daemon: eCryptfs daemon object
187  *
188  * Add msg_ctx to queue and then, if it exists, notify the blocked
189  * miscdevess about the data being available. Must be called with
190  * ecryptfs_daemon_hash_mux held.
191  *
192  * Returns zero on success; non-zero otherwise
193  */
194 int ecryptfs_send_miscdev(char *data, size_t data_size,
195                           struct ecryptfs_msg_ctx *msg_ctx, u8 msg_type,
196                           u16 msg_flags, struct ecryptfs_daemon *daemon)
197 {
198         struct ecryptfs_message *msg;
199
200         msg = kmalloc((sizeof(*msg) + data_size), GFP_KERNEL);
201         if (!msg) {
202                 printk(KERN_ERR "%s: Out of memory whilst attempting "
203                        "to kmalloc(%zd, GFP_KERNEL)\n", __func__,
204                        (sizeof(*msg) + data_size));
205                 return -ENOMEM;
206         }
207
208         mutex_lock(&msg_ctx->mux);
209         msg_ctx->msg = msg;
210         msg_ctx->msg->index = msg_ctx->index;
211         msg_ctx->msg->data_len = data_size;
212         msg_ctx->type = msg_type;
213         memcpy(msg_ctx->msg->data, data, data_size);
214         msg_ctx->msg_size = (sizeof(*msg_ctx->msg) + data_size);
215         list_add_tail(&msg_ctx->daemon_out_list, &daemon->msg_ctx_out_queue);
216         mutex_unlock(&msg_ctx->mux);
217
218         mutex_lock(&daemon->mux);
219         daemon->num_queued_msg_ctx++;
220         wake_up_interruptible(&daemon->wait);
221         mutex_unlock(&daemon->mux);
222
223         return 0;
224 }
225
226 /**
227  * ecryptfs_miscdev_read - format and send message from queue
228  * @file: fs/ecryptfs/euid miscdevfs handle (ignored)
229  * @buf: User buffer into which to copy the next message on the daemon queue
230  * @count: Amount of space available in @buf
231  * @ppos: Offset in file (ignored)
232  *
233  * Pulls the most recent message from the daemon queue, formats it for
234  * being sent via a miscdevfs handle, and copies it into @buf
235  *
236  * Returns the number of bytes copied into the user buffer
237  */
238 static ssize_t
239 ecryptfs_miscdev_read(struct file *file, char __user *buf, size_t count,
240                       loff_t *ppos)
241 {
242         struct ecryptfs_daemon *daemon;
243         struct ecryptfs_msg_ctx *msg_ctx;
244         size_t packet_length_size;
245         char packet_length[3];
246         size_t i;
247         size_t total_length;
248         uid_t euid = current_euid();
249         int rc;
250
251         mutex_lock(&ecryptfs_daemon_hash_mux);
252         /* TODO: Just use file->private_data? */
253         rc = ecryptfs_find_daemon_by_euid(&daemon, euid, current_user_ns());
254         if (rc || !daemon) {
255                 mutex_unlock(&ecryptfs_daemon_hash_mux);
256                 return -EINVAL;
257         }
258         mutex_lock(&daemon->mux);
259         if (task_pid(current) != daemon->pid) {
260                 mutex_unlock(&daemon->mux);
261                 mutex_unlock(&ecryptfs_daemon_hash_mux);
262                 return -EPERM;
263         }
264         if (daemon->flags & ECRYPTFS_DAEMON_ZOMBIE) {
265                 rc = 0;
266                 mutex_unlock(&ecryptfs_daemon_hash_mux);
267                 printk(KERN_WARNING "%s: Attempt to read from zombified "
268                        "daemon\n", __func__);
269                 goto out_unlock_daemon;
270         }
271         if (daemon->flags & ECRYPTFS_DAEMON_IN_READ) {
272                 rc = 0;
273                 mutex_unlock(&ecryptfs_daemon_hash_mux);
274                 goto out_unlock_daemon;
275         }
276         /* This daemon will not go away so long as this flag is set */
277         daemon->flags |= ECRYPTFS_DAEMON_IN_READ;
278         mutex_unlock(&ecryptfs_daemon_hash_mux);
279 check_list:
280         if (list_empty(&daemon->msg_ctx_out_queue)) {
281                 mutex_unlock(&daemon->mux);
282                 rc = wait_event_interruptible(
283                         daemon->wait, !list_empty(&daemon->msg_ctx_out_queue));
284                 mutex_lock(&daemon->mux);
285                 if (rc < 0) {
286                         rc = 0;
287                         goto out_unlock_daemon;
288                 }
289         }
290         if (daemon->flags & ECRYPTFS_DAEMON_ZOMBIE) {
291                 rc = 0;
292                 goto out_unlock_daemon;
293         }
294         if (list_empty(&daemon->msg_ctx_out_queue)) {
295                 /* Something else jumped in since the
296                  * wait_event_interruptable() and removed the
297                  * message from the queue; try again */
298                 goto check_list;
299         }
300         msg_ctx = list_first_entry(&daemon->msg_ctx_out_queue,
301                                    struct ecryptfs_msg_ctx, daemon_out_list);
302         BUG_ON(!msg_ctx);
303         mutex_lock(&msg_ctx->mux);
304         if (msg_ctx->msg) {
305                 rc = ecryptfs_write_packet_length(packet_length,
306                                                   msg_ctx->msg_size,
307                                                   &packet_length_size);
308                 if (rc) {
309                         rc = 0;
310                         printk(KERN_WARNING "%s: Error writing packet length; "
311                                "rc = [%d]\n", __func__, rc);
312                         goto out_unlock_msg_ctx;
313                 }
314         } else {
315                 packet_length_size = 0;
316                 msg_ctx->msg_size = 0;
317         }
318         /* miscdevfs packet format:
319          *  Octet 0: Type
320          *  Octets 1-4: network byte order msg_ctx->counter
321          *  Octets 5-N0: Size of struct ecryptfs_message to follow
322          *  Octets N0-N1: struct ecryptfs_message (including data)
323          *
324          *  Octets 5-N1 not written if the packet type does not
325          *  include a message */
326         total_length = (1 + 4 + packet_length_size + msg_ctx->msg_size);
327         if (count < total_length) {
328                 rc = 0;
329                 printk(KERN_WARNING "%s: Only given user buffer of "
330                        "size [%zd], but we need [%zd] to read the "
331                        "pending message\n", __func__, count, total_length);
332                 goto out_unlock_msg_ctx;
333         }
334         rc = -EFAULT;
335         if (put_user(msg_ctx->type, buf))
336                 goto out_unlock_msg_ctx;
337         if (put_user(cpu_to_be32(msg_ctx->counter), (__be32 __user *)(buf + 1)))
338                 goto out_unlock_msg_ctx;
339         i = 5;
340         if (msg_ctx->msg) {
341                 if (copy_to_user(&buf[i], packet_length, packet_length_size))
342                         goto out_unlock_msg_ctx;
343                 i += packet_length_size;
344                 if (copy_to_user(&buf[i], msg_ctx->msg, msg_ctx->msg_size))
345                         goto out_unlock_msg_ctx;
346                 i += msg_ctx->msg_size;
347         }
348         rc = i;
349         list_del(&msg_ctx->daemon_out_list);
350         kfree(msg_ctx->msg);
351         msg_ctx->msg = NULL;
352         /* We do not expect a reply from the userspace daemon for any
353          * message type other than ECRYPTFS_MSG_REQUEST */
354         if (msg_ctx->type != ECRYPTFS_MSG_REQUEST)
355                 ecryptfs_msg_ctx_alloc_to_free(msg_ctx);
356 out_unlock_msg_ctx:
357         mutex_unlock(&msg_ctx->mux);
358 out_unlock_daemon:
359         daemon->flags &= ~ECRYPTFS_DAEMON_IN_READ;
360         mutex_unlock(&daemon->mux);
361         return rc;
362 }
363
364 /**
365  * ecryptfs_miscdev_response - miscdevess response to message previously sent to daemon
366  * @data: Bytes comprising struct ecryptfs_message
367  * @data_size: sizeof(struct ecryptfs_message) + data len
368  * @euid: Effective user id of miscdevess sending the miscdev response
369  * @user_ns: The namespace in which @euid applies
370  * @pid: Miscdevess id of miscdevess sending the miscdev response
371  * @seq: Sequence number for miscdev response packet
372  *
373  * Returns zero on success; non-zero otherwise
374  */
375 static int ecryptfs_miscdev_response(char *data, size_t data_size,
376                                      uid_t euid, struct user_namespace *user_ns,
377                                      struct pid *pid, u32 seq)
378 {
379         struct ecryptfs_message *msg = (struct ecryptfs_message *)data;
380         int rc;
381
382         if ((sizeof(*msg) + msg->data_len) != data_size) {
383                 printk(KERN_WARNING "%s: (sizeof(*msg) + msg->data_len) = "
384                        "[%zd]; data_size = [%zd]. Invalid packet.\n", __func__,
385                        (sizeof(*msg) + msg->data_len), data_size);
386                 rc = -EINVAL;
387                 goto out;
388         }
389         rc = ecryptfs_process_response(msg, euid, user_ns, pid, seq);
390         if (rc)
391                 printk(KERN_ERR
392                        "Error processing response message; rc = [%d]\n", rc);
393 out:
394         return rc;
395 }
396
397 /**
398  * ecryptfs_miscdev_write - handle write to daemon miscdev handle
399  * @file: File for misc dev handle (ignored)
400  * @buf: Buffer containing user data
401  * @count: Amount of data in @buf
402  * @ppos: Pointer to offset in file (ignored)
403  *
404  * miscdevfs packet format:
405  *  Octet 0: Type
406  *  Octets 1-4: network byte order msg_ctx->counter (0's for non-response)
407  *  Octets 5-N0: Size of struct ecryptfs_message to follow
408  *  Octets N0-N1: struct ecryptfs_message (including data)
409  *
410  * Returns the number of bytes read from @buf
411  */
412 static ssize_t
413 ecryptfs_miscdev_write(struct file *file, const char __user *buf,
414                        size_t count, loff_t *ppos)
415 {
416         __be32 counter_nbo;
417         u32 seq;
418         size_t packet_size, packet_size_length, i;
419         char *data;
420         uid_t euid = current_euid();
421         unsigned char packet_size_peek[3];
422         ssize_t rc;
423
424         if (count == 0) {
425                 return 0;
426         } else if (count == (1 + 4)) {
427                 /* Likely a harmless MSG_HELO or MSG_QUIT - no packet length */
428                 goto memdup;
429         } else if (count < (1 + 4 + 1)
430                    || count > (1 + 4 + 2 + sizeof(struct ecryptfs_message) + 4
431                                + ECRYPTFS_MAX_ENCRYPTED_KEY_BYTES)) {
432                 printk(KERN_WARNING "%s: Acceptable packet size range is "
433                        "[%d-%lu], but amount of data written is [%zu].",
434                        __func__, (1 + 4 + 1),
435                        (1 + 4 + 2 + sizeof(struct ecryptfs_message) + 4
436                         + ECRYPTFS_MAX_ENCRYPTED_KEY_BYTES), count);
437                 return -EINVAL;
438         }
439
440         if (copy_from_user(packet_size_peek, (buf + 1 + 4),
441                            sizeof(packet_size_peek))) {
442                 printk(KERN_WARNING "%s: Error while inspecting packet size\n",
443                        __func__);
444                 return -EFAULT;
445         }
446
447         rc = ecryptfs_parse_packet_length(packet_size_peek, &packet_size,
448                                           &packet_size_length);
449         if (rc) {
450                 printk(KERN_WARNING "%s: Error parsing packet length; "
451                        "rc = [%zd]\n", __func__, rc);
452                 return rc;
453         }
454
455         if ((1 + 4 + packet_size_length + packet_size) != count) {
456                 printk(KERN_WARNING "%s: Invalid packet size [%zu]\n", __func__,
457                        packet_size);
458                 return -EINVAL;
459         }
460
461 memdup:
462         data = memdup_user(buf, count);
463         if (IS_ERR(data)) {
464                 printk(KERN_ERR "%s: memdup_user returned error [%ld]\n",
465                        __func__, PTR_ERR(data));
466                 return PTR_ERR(data);
467         }
468         i = 0;
469         switch (data[i++]) {
470         case ECRYPTFS_MSG_RESPONSE:
471                 if (count < (1 + 4 + 1 + sizeof(struct ecryptfs_message))) {
472                         printk(KERN_WARNING "%s: Minimum acceptable packet "
473                                "size is [%zd], but amount of data written is "
474                                "only [%zd]. Discarding response packet.\n",
475                                __func__,
476                                (1 + 4 + 1 + sizeof(struct ecryptfs_message)),
477                                count);
478                         rc = -EINVAL;
479                         goto out_free;
480                 }
481                 memcpy(&counter_nbo, &data[i], 4);
482                 seq = be32_to_cpu(counter_nbo);
483                 i += 4 + packet_size_length;
484                 rc = ecryptfs_miscdev_response(&data[i], packet_size,
485                                                euid, current_user_ns(),
486                                                task_pid(current), seq);
487                 if (rc) {
488                         printk(KERN_WARNING "%s: Failed to deliver miscdev "
489                                "response to requesting operation; rc = [%zd]\n",
490                                __func__, rc);
491                         goto out_free;
492                 }
493                 break;
494         case ECRYPTFS_MSG_HELO:
495         case ECRYPTFS_MSG_QUIT:
496                 break;
497         default:
498                 ecryptfs_printk(KERN_WARNING, "Dropping miscdev "
499                                 "message of unrecognized type [%d]\n",
500                                 data[0]);
501                 rc = -EINVAL;
502                 goto out_free;
503         }
504         rc = count;
505 out_free:
506         kfree(data);
507         return rc;
508 }
509
510
511 static const struct file_operations ecryptfs_miscdev_fops = {
512         .open    = ecryptfs_miscdev_open,
513         .poll    = ecryptfs_miscdev_poll,
514         .read    = ecryptfs_miscdev_read,
515         .write   = ecryptfs_miscdev_write,
516         .release = ecryptfs_miscdev_release,
517         .llseek  = noop_llseek,
518 };
519
520 static struct miscdevice ecryptfs_miscdev = {
521         .minor = MISC_DYNAMIC_MINOR,
522         .name  = "ecryptfs",
523         .fops  = &ecryptfs_miscdev_fops
524 };
525
526 /**
527  * ecryptfs_init_ecryptfs_miscdev
528  *
529  * Messages sent to the userspace daemon from the kernel are placed on
530  * a queue associated with the daemon. The next read against the
531  * miscdev handle by that daemon will return the oldest message placed
532  * on the message queue for the daemon.
533  *
534  * Returns zero on success; non-zero otherwise
535  */
536 int __init ecryptfs_init_ecryptfs_miscdev(void)
537 {
538         int rc;
539
540         atomic_set(&ecryptfs_num_miscdev_opens, 0);
541         rc = misc_register(&ecryptfs_miscdev);
542         if (rc)
543                 printk(KERN_ERR "%s: Failed to register miscellaneous device "
544                        "for communications with userspace daemons; rc = [%d]\n",
545                        __func__, rc);
546         return rc;
547 }
548
549 /**
550  * ecryptfs_destroy_ecryptfs_miscdev
551  *
552  * All of the daemons must be exorcised prior to calling this
553  * function.
554  */
555 void ecryptfs_destroy_ecryptfs_miscdev(void)
556 {
557         BUG_ON(atomic_read(&ecryptfs_num_miscdev_opens) != 0);
558         misc_deregister(&ecryptfs_miscdev);
559 }