user_namespace.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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/version.h>
  9. #include <linux/nsproxy.h>
  10. #include <linux/slab.h>
  11. #include <linux/user_namespace.h>
  12. /*
  13. * Clone a new ns copying an original user ns, setting refcount to 1
  14. * @old_ns: namespace to clone
  15. * Return NULL on error (failure to kmalloc), new ns otherwise
  16. */
  17. static struct user_namespace *clone_user_ns(struct user_namespace *old_ns)
  18. {
  19. struct user_namespace *ns;
  20. struct user_struct *new_user;
  21. int n;
  22. ns = kmalloc(sizeof(struct user_namespace), GFP_KERNEL);
  23. if (!ns)
  24. return ERR_PTR(-ENOMEM);
  25. kref_init(&ns->kref);
  26. for (n = 0; n < UIDHASH_SZ; ++n)
  27. INIT_HLIST_HEAD(ns->uidhash_table + n);
  28. /* Insert new root user. */
  29. ns->root_user = alloc_uid(ns, 0);
  30. if (!ns->root_user) {
  31. kfree(ns);
  32. return ERR_PTR(-ENOMEM);
  33. }
  34. /* Reset current->user with a new one */
  35. new_user = alloc_uid(ns, current->uid);
  36. if (!new_user) {
  37. free_uid(ns->root_user);
  38. kfree(ns);
  39. return ERR_PTR(-ENOMEM);
  40. }
  41. switch_uid(new_user);
  42. return ns;
  43. }
  44. struct user_namespace * copy_user_ns(int flags, struct user_namespace *old_ns)
  45. {
  46. struct user_namespace *new_ns;
  47. BUG_ON(!old_ns);
  48. get_user_ns(old_ns);
  49. if (!(flags & CLONE_NEWUSER))
  50. return old_ns;
  51. new_ns = clone_user_ns(old_ns);
  52. put_user_ns(old_ns);
  53. return new_ns;
  54. }
  55. void free_user_ns(struct kref *kref)
  56. {
  57. struct user_namespace *ns;
  58. ns = container_of(kref, struct user_namespace, kref);
  59. release_uids(ns);
  60. kfree(ns);
  61. }
  62. EXPORT_SYMBOL(free_user_ns);