user_namespace.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. struct cred *new;
  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. /* Install the new user */
  42. new = prepare_creds();
  43. if (!new) {
  44. free_uid(new_user);
  45. free_uid(ns->root_user);
  46. kfree(ns);
  47. }
  48. free_uid(new->user);
  49. new->user = new_user;
  50. commit_creds(new);
  51. return ns;
  52. }
  53. struct user_namespace * copy_user_ns(int flags, struct user_namespace *old_ns)
  54. {
  55. struct user_namespace *new_ns;
  56. BUG_ON(!old_ns);
  57. get_user_ns(old_ns);
  58. if (!(flags & CLONE_NEWUSER))
  59. return old_ns;
  60. new_ns = clone_user_ns(old_ns);
  61. put_user_ns(old_ns);
  62. return new_ns;
  63. }
  64. void free_user_ns(struct kref *kref)
  65. {
  66. struct user_namespace *ns;
  67. ns = container_of(kref, struct user_namespace, kref);
  68. release_uids(ns);
  69. kfree(ns);
  70. }
  71. EXPORT_SYMBOL(free_user_ns);