Guest User

Untitled

a guest
Feb 25th, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. # please run: mkdir /tmp/img ; docker export $(docker create centos) | tar -C /tmp/img/ -xvf -
  2. # before this script
  3.  
  4. import os
  5. import ctypes
  6.  
  7. from multiprocessing import Process
  8.  
  9. CLONE_NEWUSER = 0x10000000
  10. CLONE_NEWPID = 0x20000000
  11. CLONE_NEWNET = 0x40000000
  12. CLONE_NEWNS = 0x00020000
  13.  
  14.  
  15. MS_PRIVATE = 0x40000
  16. MS_REC = 0x4000
  17. MS_NODEV = 0x4
  18. MS_NOEXEC = 0x8
  19. MS_NOSUID = 0x2
  20. MS_SLAVE = 0x80000
  21. MS_BIND = 4096
  22.  
  23. libc = ctypes.CDLL(None)
  24.  
  25. get_errno_loc = libc.__errno_location
  26. get_errno_loc.restype = ctypes.POINTER(ctypes.c_int)
  27.  
  28.  
  29. def unshare(flags):
  30. rc = libc.unshare(flags)
  31. if rc == -1:
  32. raise Exception(os.strerror(get_errno_loc()[0]))
  33.  
  34.  
  35. def mount(special_file, target, fs_type, flags, data):
  36. rc = libc.mount(special_file,
  37. target,
  38. fs_type,
  39. flags,
  40. data)
  41. if rc == -1:
  42. raise Exception(os.strerror(get_errno_loc()[0]))
  43.  
  44.  
  45. def unshare_user():
  46. print("I'm %s" % os.getuid())
  47. unshare(CLONE_NEWUSER)
  48. with open('/proc/self/uid_map', 'w') as file_:
  49. file_.write('0 1000 1')
  50. print("I'm %s" % os.getuid())
  51.  
  52.  
  53. def containerize():
  54. unshare_user()
  55. unshare(CLONE_NEWNET ^ CLONE_NEWPID ^ CLONE_NEWNS)
  56. process = Process(target=cmd)
  57. process.start()
  58.  
  59.  
  60. def cmd():
  61. root = ('/tmp/img')
  62. host = os.path.join(root, 'host')
  63. if not os.path.exists(host):
  64. os.makedirs(host)
  65. mount('none', '/', None, MS_REC ^ MS_PRIVATE, None)
  66. mount(root, root, None, MS_REC ^ MS_BIND, None)
  67. os.chdir(root)
  68. pivot_root('.', 'host')
  69. mount_proc()
  70. os.execve('/bin/bash', ['/bin/bash'], {'PATH': os.getenv('PATH')})
  71.  
  72.  
  73. def mount_proc():
  74. if not os.path.exists('/proc'):
  75. os.makedirs('/proc')
  76. mount('proc', '/proc', 'proc',
  77. MS_NODEV ^ MS_NOEXEC ^ MS_NOSUID, None)
  78.  
  79.  
  80. def pivot_root(new, old):
  81. rc = libc.pivot_root(new, old)
  82. if rc == -1:
  83. raise Exception(os.strerror(get_errno_loc()[0]))
  84.  
  85.  
  86. containerize()
Add Comment
Please, Sign In to add comment