user_namespace.c 1.8 KB

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