Chroot

From Gentoo Wiki
Jump to:navigation Jump to:search
This page is a translated version of the page Chroot and the translation is 21% complete.
Outdated translations are marked like this.
Resources

Chroot (Change root) es una utilidad del sistema Unix que se emplea para cambiar el directorio raíz aparente de modo que se pueda crear un nuevo entorno separado lógicamente del directorio raíz del sistema principal. Este nuevo entorno se conoce como una "jaula chroot". Un usuario que opere dentro de la jaula no puede ver ni acceder ficheros fuera del entorno en el que se le ha confinado.

Uno de los usos principales usos del enjaulamiento es crear un sistema Linux independiente encima del actual para realizar pruebas o compatibilidad del software. Chroot se ve a menudo como una alternativa ligera a la virtualización, ya que se puede correr sin la sobrecarga de un supervisor.

Requisitos previos

Configurar el entorno

Cuando se crea una nueva configuración de chroot, lo primero que se necesita es un directorio para que resida chroot. Por ejemplo, se podría crear un chroot en /mnt/mijaula:

user $mkdir /mnt/mijaula
user $cd /mnt/mijaula

Para montar una instalación ya existente desde una partición, se puede lanzar la siguiente orden. Asegúrese de reemplazar la cadena <DISPOSITIVO> en el ejemplo de abajo por el disco y partición de la instalación existente:

user $mkdir /mnt/mijaula
user $mount /dev/DISPOSITIVO /mnt/mijaula

Si ya se ha creado una instalación previamente en un subdirectorio del sistema de ficheros raíz actual, se pueden omitir los pasos indicados arriba.

Desempaquetar los ficheros de sistema y el árbol Portage (nuevas instalaciones)

Cuando se está construyendo una nueva instalación, el siguiente paso es descargar el stage3 y los ficheros tarball de Portage para colocarlos en la localización chroot. Para obtener más información sobre este proceso, por favor, lea Descargar el stage comprimido (tarball) y Extraer el stage comprimido del manual de Gentoo.

root #links http://distfiles.gentoo.org/releases/amd64/autobuilds/
root #tar xvjpf stage3-*.tar.bz2 -C /mnt/mychroot

Configuración

Antes de introducirse en la jaula se necesita montar algunos directorios:

root #mount --rbind /dev /mnt/mijaula/dev
root #mount --make-rslave /mnt/mijaula/dev
root #mount -t proc /proc /mnt/mijaula/proc
root #mount --rbind /sys /mnt/mijaula/sys
root #mount --make-rslave /mnt/mijaula/sys
root #mount --rbind /tmp /mnt/mijaula/tmp

Se necesitarán copiar algunos ficheros de configuración básica desde el anfitrión, no sobrescriba make.conf cuando se esté utilizando una instalación ya existente.

user $cp /etc/portage/make.conf /mnt/mijaula/etc/portage # Si está usando una instalación ya existente, no lance esta orden.
user $cp /etc/resolv.conf /mnt/mijaula/etc

Utilización

Una vez hecho esto, nos podemos introducir en el entorno jaula lanzando las siguientes órdenes:

root #chroot /mnt/mychroot /bin/bash
root #env-update && . /etc/profile
root #export PS1="(chroot) $PS1"

Cuándo se esté realizando una instalación nueva, se debería sincronizar Portage para asegurarse de que todo está actualizado.

(chroot) root #emerge-webrsync
(chroot) root #emerge --sync

El sistema es preparado. Se puede ahora instalar software, jugar un poco, probar paquetes y configuraciones experimentales sin que ello tenga ningún efecto en el sistema principal. Para abandonar la jaula, teclee simplemente exit o pulse Ctrl + d. Al hacer esto, se devolverá la consola a su entorno normal. No olvide desmontar (umount) los directorios que se han montado.

systemd-nspawn

If the system uses systemd, systemd-nspawn can be used, which can automatically handle much of the boilerplate required in administering chroots. For example, to enter a chroot via systemd-nspawn with the same configuration as specified in the Configuration section, simply run:

root #cp /etc/portage/make.conf /mnt/mychroot/etc/portage
root #systemd-nspawn -D /mnt/mychroot --bind=/tmp --resolv-conf=/etc/resolv.conf

Guiones de inicio

Si se van a poner en marcha jaulas chroot a menudo, es posible acelerar el montaje de los directorios utilizando un guión de inicio. Se podría añadir el guión al nivel de ejecución por defecto y por tanto se configuraría de forma automática en el inicio:

ARCHIVO /etc/init.d/mijaula
#!/sbin/openrc-run
 
depend() {
   need localmount
   need bootmisc
}
 
start() {
     ebegin "Montando los directorios de la jaula"
     mount -o rbind /dev /mnt/mijaula/dev > /dev/null &
     mount -t proc none /mnt/mijaula/proc > /dev/null &
     mount -o bind /sys /mnt/mijaula/sys > /dev/null &
     mount -o bind /tmp /mnt/mijaula/tmp > /dev/null &
     eend $? "Ocurrió un error mientras se montaban los directorios de la jaula"
}
 
stop() {
     ebegin "Desmontando los directorios de la jaula"
     umount -f /mnt/mijaula/dev > /dev/null &
     umount -f /mnt/mijaula/proc > /dev/null &
     umount -f /mnt/mijaula/sys > /dev/null &
     umount -f /mnt/mijaula/tmp > /dev/null &
     eend $? "Ocurrió un error mientras se desmontaban los directorios de la jaula"
}

Cuando se utiliza un directorio o partición diferentes, añada las órdenes de montaje necesarias en la función start() y cambie /mnt/jaula al nombre apropiado.

Sound and graphics

The software running inside the chroot will by default not have access to the system sound- and display-server. Fixing this is done by either sharing a socket, or by running the communication with TCP over localhost.

Wayland

Wayland uses a socket to connect clients with the compositor. This socket needs to be shared with the chroot to make graphical applications work. The general procedure for finding this socket is:[1]

  1. If WAYLAND_SOCKET is set, interpret it as a file descriptor number on which the connection is already established, assuming that the parent process configured the connection for us.
  2. If WAYLAND_DISPLAY is set, concat with XDG_RUNTIME_DIR to form the path to the Unix socket.
  3. Assume the socket name is wayland-0 and concat with XDG_RUNTIME_DIR to form the path to the Unix socket.

Using WAYLAND_DISPLAY and XDG_RUNTIME_DIR is fine in most cases and will be used here. By default XDG_RUNTIME_DIR is set to /run/user/$(uid). This directory will not be available in the chroot because the #Configuration instructions bind mounts /run non-recursively. Assuming the user's uid is 1000, this can be solved by either bind-mounting /run/user/1000 with:

root #mkdir -p /mnt/mychroot/run/user/1000
root #mount --bind /run/user/1000 /mnt/mychroot/run/user/1000

or by simply recursively bind mounting /run with:

root #mount --rbind /run /mnt/mychroot/run

The Wayland library dev-libs/wayland uses the same procedure for finding out the socket as listed above. So to share the socket with the chroot, the only thing that's needed to do is defining XDG_RUNTIME_DIR and WAYLAND_DISPLAY. Here it is assumed that the Wayland socket name WAYLAND_DISPLAY is wayland-0.

(chroot) root #useradd -m user
(chroot) root #su -l user
(chroot) user $export XDG_RUNTIME_DIR=/run/user/1000
(chroot) user $export WAYLAND_DISPLAY=wayland-0
(chroot) user $MOZ_ENABLE_WAYLAND=1 firefox-bin

Permission errors will occur if the user in the chroot does not have permissions to access the Wayland socket. This can be solved by using user namespace remapping or ACLs. The easiest solution is to just make sure that the user ids match. The useradd -u, --uid UID option can be used when creating a user.

PipeWire

Like Wayland, PipeWire uses a socket to connect clients to the PipeWire daemon.

Applications assume that the PipeWire socket will be located in ${XDG_RUNTIME_DIR}/pipewire-0, so the only thing that's needed to get PipeWire clients to connect to the host's daemon is to expose XDG_RUNTIME_DIR to the chroot. This process is identical to the one described in #Wayland. To expose XDG_RUNTIME_DIR, often /run/user/$(uid), the following commands are used:

root #mkdir -p /mnt/mychroot/run/user/1000
root #mount --bind /run/user/1000 /mnt/mychroot/run/user/1000

XDG_RUNTIME_DIR will not be set when logging in inside the chroot, therefore XDG_RUNTIME_DIR needs to exported so the PipeWire client can find the socket:

(chroot) user $export XDG_RUNTIME_DIR=/run/user/1000
(chroot) user $pw-cli

Xorg

Xorg by default listens on a socket located in /tmp/.X11-unix/X${DISPLAY}, as well as on localhost TCP port 6000 + ${DISPLAY}[2]. The instructions in #Configuration bind mounts /tmp, and therefore no additional configuration is needed except setting the DISPLAY variable before running a graphical application:

(chroot) user $DISPLAY=:0 firefox-bin

If the uid of the user inside the chroot does not match the uid outside the chroot, then setting permissions with xhost will be needed. To allow all local connections, run outside the chroot:

user $xhost +local:

Vea también

External resources

References

  1. https://wayland-book.com/protocol-design/wire-protocol.html
  2. So if DISPLAY=:12, then Xorg will listen on localhost TCP port 6012