user_namespace.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. #include <linux/cred.h>
  12. /*
  13. * Create a new user namespace, deriving the creator from the user in the
  14. * passed credentials, and replacing that user with the new root user for the
  15. * new namespace.
  16. *
  17. * This is called by copy_creds(), which will finish setting the target task's
  18. * credentials.
  19. */
  20. int create_user_ns(struct cred *new)
  21. {
  22. struct user_namespace *ns;
  23. struct user_struct *root_user;
  24. int n;
  25. ns = kmalloc(sizeof(struct user_namespace), GFP_KERNEL);
  26. if (!ns)
  27. return -ENOMEM;
  28. kref_init(&ns->kref);
  29. for (n = 0; n < UIDHASH_SZ; ++n)
  30. INIT_HLIST_HEAD(ns->uidhash_table + n);
  31. /* Alloc new root user. */
  32. root_user = alloc_uid(ns, 0);
  33. if (!root_user) {
  34. kfree(ns);
  35. return -ENOMEM;
  36. }
  37. /* set the new root user in the credentials under preparation */
  38. ns->creator = new->user;
  39. new->user = root_user;
  40. new->uid = new->euid = new->suid = new->fsuid = 0;
  41. new->gid = new->egid = new->sgid = new->fsgid = 0;
  42. put_group_info(new->group_info);
  43. new->group_info = get_group_info(&init_groups);
  44. #ifdef CONFIG_KEYS
  45. key_put(new->request_key_auth);
  46. new->request_key_auth = NULL;
  47. #endif
  48. /* tgcred will be cleared in our caller bc CLONE_THREAD won't be set */
  49. /* alloc_uid() incremented the userns refcount. Just set it to 1 */
  50. kref_set(&ns->kref, 1);
  51. return 0;
  52. }
  53. /*
  54. * Deferred destructor for a user namespace. This is required because
  55. * free_user_ns() may be called with uidhash_lock held, but we need to call
  56. * back to free_uid() which will want to take the lock again.
  57. */
  58. static void free_user_ns_work(struct work_struct *work)
  59. {
  60. struct user_namespace *ns =
  61. container_of(work, struct user_namespace, destroyer);
  62. free_uid(ns->creator);
  63. kfree(ns);
  64. }
  65. void free_user_ns(struct kref *kref)
  66. {
  67. struct user_namespace *ns =
  68. container_of(kref, struct user_namespace, kref);
  69. INIT_WORK(&ns->destroyer, free_user_ns_work);
  70. schedule_work(&ns->destroyer);
  71. }
  72. EXPORT_SYMBOL(free_user_ns);