···53535454MS_BIND = 0x1000
5555MS_REC = 0x4000
5656+MS_SLAVE = 0x80000
5657$mount = make_fcall 'mount', [Fiddle::TYPE_VOIDP,
5758 Fiddle::TYPE_VOIDP,
5859 Fiddle::TYPE_VOIDP,
···9293# we don't use threads at all.
9394$cpid = $fork.call
9495if $cpid == 0
9595- # Save user UID and GID
9696- uid = Process.uid
9797- gid = Process.gid
9696+ # If we are root, no need to create new user namespace.
9797+ if Process.uid == 0
9898+ $unshare.call CLONE_NEWNS
9999+ # Mark all mounted filesystems as slave so changes
100100+ # don't propagate to the parent mount namespace.
101101+ $mount.call nil, '/', nil, MS_REC | MS_SLAVE, nil
102102+ else
103103+ # Save user UID and GID
104104+ uid = Process.uid
105105+ gid = Process.gid
981069999- # Create new mount and user namespaces
100100- # CLONE_NEWUSER requires a program to be non-threaded, hence
101101- # native fork above.
102102- $unshare.call CLONE_NEWNS | CLONE_NEWUSER
107107+ # Create new mount and user namespaces
108108+ # CLONE_NEWUSER requires a program to be non-threaded, hence
109109+ # native fork above.
110110+ $unshare.call CLONE_NEWNS | CLONE_NEWUSER
103111104104- # Map users and groups to the parent namespace
105105- begin
106106- # setgroups is only available since Linux 3.19
107107- write_file '/proc/self/setgroups', 'deny'
108108- rescue
112112+ # Map users and groups to the parent namespace
113113+ begin
114114+ # setgroups is only available since Linux 3.19
115115+ write_file '/proc/self/setgroups', 'deny'
116116+ rescue
117117+ end
118118+ write_file '/proc/self/uid_map', "#{uid} #{uid} 1"
119119+ write_file '/proc/self/gid_map', "#{gid} #{gid} 1"
109120 end
110110- write_file '/proc/self/uid_map', "#{uid} #{uid} 1"
111111- write_file '/proc/self/gid_map', "#{gid} #{gid} 1"
112121113122 # Do rbind mounts.
114123 mounts.each do |from, rto|
···117126 $mount.call from, to, nil, MS_BIND | MS_REC, nil
118127 end
119128129129+ # Don't make root private so privilege drops inside chroot are possible
130130+ File.chmod(0755, root)
120131 # Chroot!
121132 Dir.chroot root
122133 Dir.chdir '/'