Merge pull request #11779 from abbradar/fhs-root

chroot-user: don't create new user namespace if we are root

+31 -15
+6 -1
pkgs/build-support/build-fhs-chrootenv/env.nix
··· 56 56 export PS1='${name}-chrootenv:\u@\h:\w\$ ' 57 57 export LOCALE_ARCHIVE='/usr/lib/locale/locale-archive' 58 58 export LD_LIBRARY_PATH='/run/opengl-driver/lib:/run/opengl-driver-32/lib:/usr/lib:/usr/lib32' 59 - export PATH='/usr/bin:/usr/sbin' 59 + export PATH='/var/setuid-wrappers:/usr/bin:/usr/sbin' 60 60 ${profile} 61 61 ''; 62 62 ··· 80 80 ln -s /host-etc/hosts hosts 81 81 ln -s /host-etc/resolv.conf resolv.conf 82 82 ln -s /host-etc/nsswitch.conf nsswitch.conf 83 + 84 + # symlink sudo and su stuff 85 + ln -s /host-etc/login.defs login.defs 86 + ln -s /host-etc/sudoers sudoers 87 + ln -s /host-etc/sudoers.d sudoers.d 83 88 84 89 # symlink other core stuff 85 90 ln -s /host-etc/localtime localtime
+25 -14
pkgs/build-support/build-fhs-userenv/chroot-user.rb
··· 53 53 54 54 MS_BIND = 0x1000 55 55 MS_REC = 0x4000 56 + MS_SLAVE = 0x80000 56 57 $mount = make_fcall 'mount', [Fiddle::TYPE_VOIDP, 57 58 Fiddle::TYPE_VOIDP, 58 59 Fiddle::TYPE_VOIDP, ··· 92 93 # we don't use threads at all. 93 94 $cpid = $fork.call 94 95 if $cpid == 0 95 - # Save user UID and GID 96 - uid = Process.uid 97 - gid = Process.gid 96 + # If we are root, no need to create new user namespace. 97 + if Process.uid == 0 98 + $unshare.call CLONE_NEWNS 99 + # Mark all mounted filesystems as slave so changes 100 + # don't propagate to the parent mount namespace. 101 + $mount.call nil, '/', nil, MS_REC | MS_SLAVE, nil 102 + else 103 + # Save user UID and GID 104 + uid = Process.uid 105 + gid = Process.gid 98 106 99 - # Create new mount and user namespaces 100 - # CLONE_NEWUSER requires a program to be non-threaded, hence 101 - # native fork above. 102 - $unshare.call CLONE_NEWNS | CLONE_NEWUSER 107 + # Create new mount and user namespaces 108 + # CLONE_NEWUSER requires a program to be non-threaded, hence 109 + # native fork above. 110 + $unshare.call CLONE_NEWNS | CLONE_NEWUSER 103 111 104 - # Map users and groups to the parent namespace 105 - begin 106 - # setgroups is only available since Linux 3.19 107 - write_file '/proc/self/setgroups', 'deny' 108 - rescue 112 + # Map users and groups to the parent namespace 113 + begin 114 + # setgroups is only available since Linux 3.19 115 + write_file '/proc/self/setgroups', 'deny' 116 + rescue 117 + end 118 + write_file '/proc/self/uid_map', "#{uid} #{uid} 1" 119 + write_file '/proc/self/gid_map', "#{gid} #{gid} 1" 109 120 end 110 - write_file '/proc/self/uid_map', "#{uid} #{uid} 1" 111 - write_file '/proc/self/gid_map', "#{gid} #{gid} 1" 112 121 113 122 # Do rbind mounts. 114 123 mounts.each do |from, rto| ··· 117 126 $mount.call from, to, nil, MS_BIND | MS_REC, nil 118 127 end 119 128 129 + # Don't make root private so privilege drops inside chroot are possible 130 + File.chmod(0755, root) 120 131 # Chroot! 121 132 Dir.chroot root 122 133 Dir.chdir '/'