user_namespace.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. * This program is free software; you can redistribute it and/or
  3. * modify it under the terms of the GNU General Public License as
  4. * published by the Free Software Foundation, version 2 of the
  5. * License.
  6. */
  7. #include <linux/module.h>
  8. #include <linux/nsproxy.h>
  9. #include <linux/slab.h>
  10. #include <linux/user_namespace.h>
  11. /*
  12. * Clone a new ns copying an original user ns, setting refcount to 1
  13. * @old_ns: namespace to clone
  14. * Return NULL on error (failure to kmalloc), new ns otherwise
  15. */
  16. static struct user_namespace *clone_user_ns(struct user_namespace *old_ns)
  17. {
  18. struct user_namespace *ns;
  19. struct user_struct *new_user;
  20. int n;
  21. ns = kmalloc(sizeof(struct user_namespace), GFP_KERNEL);
  22. if (!ns)
  23. return ERR_PTR(-ENOMEM);
  24. kref_init(&ns->kref);
  25. for (n = 0; n < UIDHASH_SZ; ++n)
  26. INIT_HLIST_HEAD(ns->uidhash_table + n);
  27. /* Insert new root user. */
  28. ns->root_user = alloc_uid(ns, 0);
  29. if (!ns->root_user) {
  30. kfree(ns);
  31. return ERR_PTR(-ENOMEM);
  32. }
  33. /* Reset current->user with a new one */
  34. new_user = alloc_uid(ns, current->uid);
  35. if (!new_user) {
  36. free_uid(ns->root_user);
  37. kfree(ns);
  38. return ERR_PTR(-ENOMEM);
  39. }
  40. switch_uid(new_user);
  41. return ns;
  42. }
  43. struct user_namespace * copy_user_ns(int flags, struct user_namespace *old_ns)
  44. {
  45. struct user_namespace *new_ns;
  46. BUG_ON(!old_ns);
  47. get_user_ns(old_ns);
  48. if (!(flags & CLONE_NEWUSER))
  49. return old_ns;
  50. new_ns = clone_user_ns(old_ns);
  51. put_user_ns(old_ns);
  52. return new_ns;
  53. }
  54. void free_user_ns(struct kref *kref)
  55. {
  56. struct user_namespace *ns;
  57. ns = container_of(kref, struct user_namespace, kref);
  58. release_uids(ns);
  59. kfree(ns);
  60. }
  61. EXPORT_SYMBOL(free_user_ns);