arch-chroot (8726B)
1 #!/bin/bash 2 # SPDX-License-Identifier: GPL-2.0-only 3 4 shopt -s extglob 5 6 use_systemd=0 7 unshare=0 8 keepresolvconf=0 9 10 #!/hint/bash 11 # SPDX-License-Identifier: GPL-2.0-only 12 # shellcheck disable=SC2059 # $1 and $2 can contain the printf modifiers 13 14 out() { printf "$1 $2\n" "${@:3}"; } 15 error() { out "==> ERROR:" "$@"; } >&2 16 warning() { out "==> WARNING:" "$@"; } >&2 17 msg() { out "==>" "$@"; } 18 die() { error "$@"; exit 1; } 19 20 ignore_error() { 21 "$@" 2>/dev/null 22 return 0 23 } 24 25 chroot_add_mount() { 26 mount "$@" && CHROOT_ACTIVE_MOUNTS=("$2" "${CHROOT_ACTIVE_MOUNTS[@]}") 27 } 28 29 chroot_maybe_add_mount() { 30 local cond=$1; shift 31 if eval "$cond"; then 32 chroot_add_mount "$@" 33 fi 34 } 35 36 chroot_init() { 37 CHROOT_ACTIVE_MOUNTS=() 38 CHROOT_ACTIVE_LAZY=() 39 CHROOT_ACTIVE_FILES=() 40 [[ $(trap -p EXIT) ]] && die '(BUG): attempting to overwrite existing EXIT trap' 41 trap 'chroot_teardown' EXIT 42 } 43 44 chroot_teardown() { 45 if (( ${#CHROOT_ACTIVE_MOUNTS[@]} )); then 46 umount "${CHROOT_ACTIVE_MOUNTS[@]}" 47 fi 48 unset CHROOT_ACTIVE_MOUNTS 49 50 if (( ${#CHROOT_ACTIVE_LAZY[@]} )); then 51 umount --lazy "${CHROOT_ACTIVE_LAZY[@]}" 52 fi 53 unset CHROOT_ACTIVE_LAZY 54 55 if (( ${#CHROOT_ACTIVE_FILES[@]} )); then 56 rm "${CHROOT_ACTIVE_FILES[@]}" 57 fi 58 unset CHROOT_ACTIVE_FILES 59 } 60 61 chroot_setup() { 62 chroot_add_mount proc "$1/proc" -t proc -o nosuid,noexec,nodev && 63 chroot_add_mount sys "$1/sys" -t sysfs -o nosuid,noexec,nodev,ro && 64 ignore_error chroot_maybe_add_mount "[[ -d '$1/sys/firmware/efi/efivars' ]]" \ 65 efivarfs "$1/sys/firmware/efi/efivars" -t efivarfs -o nosuid,noexec,nodev && 66 chroot_add_mount udev "$1/dev" -t devtmpfs -o mode=0755,nosuid && 67 chroot_add_mount devpts "$1/dev/pts" -t devpts -o mode=0620,gid=5,nosuid,noexec && 68 chroot_add_mount shm "$1/dev/shm" -t tmpfs -o mode=1777,nosuid,nodev && 69 chroot_add_mount /run "$1/run" --bind --make-private && 70 chroot_add_mount tmp "$1/tmp" -t tmpfs -o mode=1777,strictatime,nodev,nosuid 71 } 72 73 chroot_add_mount_lazy() { 74 mount "$@" && CHROOT_ACTIVE_LAZY=("$2" "${CHROOT_ACTIVE_LAZY[@]}") 75 } 76 77 chroot_bind_device() { 78 touch "$2" && CHROOT_ACTIVE_FILES=("$2" "${CHROOT_ACTIVE_FILES[@]}") 79 chroot_add_mount "$1" "$2" --bind 80 } 81 82 chroot_add_link() { 83 ln -sf "$1" "$2" && CHROOT_ACTIVE_FILES=("$2" "${CHROOT_ACTIVE_FILES[@]}") 84 } 85 86 unshare_setup() { 87 chroot_add_mount_lazy "$1" "$1" --bind && 88 chroot_add_mount proc "$1/proc" -t proc -o nosuid,noexec,nodev && 89 chroot_add_mount_lazy /sys "$1/sys" --rbind && 90 chroot_add_link /proc/self/fd "$1/dev/fd" && 91 chroot_add_link /proc/self/fd/0 "$1/dev/stdin" && 92 chroot_add_link /proc/self/fd/1 "$1/dev/stdout" && 93 chroot_add_link /proc/self/fd/2 "$1/dev/stderr" && 94 chroot_bind_device /dev/full "$1/dev/full" && 95 chroot_bind_device /dev/null "$1/dev/null" && 96 chroot_bind_device /dev/random "$1/dev/random" && 97 chroot_bind_device /dev/tty "$1/dev/tty" && 98 chroot_bind_device /dev/urandom "$1/dev/urandom" && 99 chroot_bind_device /dev/zero "$1/dev/zero" && 100 chroot_add_mount run "$1/run" -t tmpfs -o nosuid,nodev,mode=0755 && 101 chroot_add_mount tmp "$1/tmp" -t tmpfs -o mode=1777,strictatime,nodev,nosuid 102 } 103 104 pid_unshare="unshare --fork --pid" 105 mount_unshare="$pid_unshare --mount --map-auto --map-root-user --setuid 0 --setgid 0" 106 107 # This outputs code for declaring all variables to stdout. For example, if 108 # FOO=BAR, then running 109 # declare -p FOO 110 # will result in the output 111 # declare -- FOO="bar" 112 # This function may be used to re-declare all currently used variables and 113 # functions in a new shell. 114 declare_all() { 115 # Remove read-only variables to avoid warnings. Unfortunately, declare +r -p 116 # doesn't work like it looks like it should (declaring only read-write 117 # variables). However, declare -rp will print out read-only variables, which 118 # we can then use to remove those definitions. 119 declare -p | grep -Fvf <(declare -rp) 120 # Then declare functions 121 declare -pf 122 } 123 124 125 usage() { 126 cat <<EOF 127 usage: ${0##*/} chroot-dir [command] [arguments...] 128 129 -h Print this help message 130 -S Perform chroot using systemd-run 131 -N Run in unshare mode as a regular user 132 -u <user>[:group] Specify non-root user and optional group to use 133 -r Do not change the resolv.conf within the chroot 134 135 If 'command' is unspecified, ${0##*/} will launch /bin/bash. 136 137 Note that when using arch-chroot, the target chroot directory *should* be a 138 mountpoint. This ensures that tools such as pacman(8) or findmnt(8) have an 139 accurate hierarchy of the mounted filesystems within the chroot. 140 141 If your chroot target is not a mountpoint, you can bind mount the directory on 142 itself to make it a mountpoint, i.e. 'mount --bind /your/chroot /your/chroot'. 143 144 EOF 145 } 146 147 chroot_add_resolv_conf() { 148 local dest="$chrootdir/etc/resolv.conf" 149 150 # If we don't have a source resolv.conf file, there's nothing useful we can do. 151 [[ -e /etc/resolv.conf ]] || return 0 152 153 if [[ ! -e "$dest" && ! -L "$dest" ]]; then 154 # There may be no resolv.conf in the chroot. In this case, we'll just exit. 155 # The chroot environment must not be concerned with DNS resolution. 156 return 0 157 fi 158 159 chroot_add_mount /etc/resolv.conf "$dest" --bind -o X-mount.nocanonicalize=target 160 } 161 162 systemd_sanity_check() { 163 local systemd_ver 164 165 command -v systemd-run &>/dev/null || die 'systemd-run is not available' 166 167 IFS=' .-~^' read -r _ systemd_ver _ < <(SYSTEMD_COLORS=0 systemd-run --version) 168 (( systemd_ver >= 257 )) || die 'Unsupported systemd version: %s (requires >= 257)' "$systemd_ver" 169 170 [[ -d /run/systemd/system ]] || die 'System is not booted with systemd' 171 } 172 173 systemd_mode() { 174 local user=root group="" sd_args 175 176 systemd_sanity_check 177 178 # NB: we always have systemd spawn the service main process as root 179 # and call into setpriv later. The reason is two-fold: 180 # systemd resolves users using the host's passwd/groups database, 181 # while we want to resolve inside the chroot. Plus, setpriv 182 # does us a favor of clearing extraneous envvars from systemd, 183 # notably SYSTEMD_EXEC_PID which might confuse some programs. 184 185 if [[ $userspec ]]; then 186 IFS=':' read -r user group <<< "$userspec" 187 [[ $user ]] || die 'Invalid -u argument: %s' "$userspec" 188 fi 189 190 sd_args=(systemd-run --unit="arch-chroot-$$_$(systemd-escape --path "$chrootdir")" 191 --description="[arch-chroot] $chrootdir (as $user)" 192 --service-type=exec --collect 193 --pty --pipe --send-sighup 194 --expand-environment=no 195 -p RootDirectory="$chrootdir" 196 -p MountAPIVFS=yes 197 -p ProtectControlGroupsEx=private 198 -p BindLogSockets=no 199 -p BindReadOnlyPaths=/run/udev # https://github.com/archlinux/arch-install-scripts/pull/52 200 -p TemporaryFileSystem=/tmp 201 -p IgnoreSIGPIPE=no) 202 203 if ! [[ -t 0 && -t 1 ]]; then 204 sd_args+=(--quiet) 205 fi 206 207 sd_args+=(setpriv --reset-env --reuid="$user" --regid="${group:-"$user"}" --init-groups) 208 209 if [[ ! -v args ]]; then 210 args=(/bin/bash -i) 211 fi 212 213 "${sd_args[@]}" -- "${args[@]}" 214 } 215 216 offline_mode() { 217 local chroot_args=() 218 219 $setup "$chrootdir" || die "failed to setup chroot %s" "$chrootdir" 220 221 [[ $userspec ]] && chroot_args+=(--userspec "$userspec") 222 223 SHELL=/bin/bash SYSTEMD_IN_CHROOT=1 $pid_unshare chroot "${chroot_args[@]}" "$chrootdir" "${args[@]}" 224 } 225 226 arch-chroot() { 227 (( EUID == 0 )) || die 'This script must be run with root privileges' 228 229 [[ -d $chrootdir ]] || die "Can't create chroot on non-directory %s" "$chrootdir" 230 231 if ! mountpoint -q "$chrootdir"; then 232 warning "$chrootdir is not a mountpoint. This may have undesirable side effects." 233 fi 234 235 chroot_init 236 if (( ! keepresolvconf )); then 237 chroot_add_resolv_conf || die "failed to setup resolv.conf" 238 fi 239 240 if (( use_systemd )); then 241 systemd_mode 242 else 243 offline_mode 244 fi 245 } 246 247 while getopts ':hSNu:r' flag; do 248 case $flag in 249 h) 250 usage 251 exit 0 252 ;; 253 S) 254 use_systemd=1 255 ;; 256 N) 257 unshare=1 258 ;; 259 u) 260 userspec=$OPTARG 261 ;; 262 r) 263 keepresolvconf=1 264 ;; 265 :) 266 die '%s: option requires an argument -- '\''%s'\' "${0##*/}" "$OPTARG" 267 ;; 268 ?) 269 die '%s: invalid option -- '\''%s'\' "${0##*/}" "$OPTARG" 270 ;; 271 esac 272 done 273 shift $(( OPTIND - 1 )) 274 275 (( $# )) || die 'No chroot directory specified' 276 chrootdir=$1 277 shift 278 279 args=("$@") 280 if (( unshare )); then 281 if (( use_systemd )); then 282 die 'systemd mode (-S) cannot be used in conjunction with unshare (-N)' 283 fi 284 285 setup=unshare_setup 286 $mount_unshare bash -c "$(declare_all); arch-chroot" 287 else 288 setup=chroot_setup 289 arch-chroot 290 fi