Creating a virtual Linux in Debian using user-mode-linux

English version below.
O programa user-mode-linux (aqui abreviado para uml) deixa você rodar um sistema Linux virtual dentro de outro sistema Linux, que pode ser ligada sistema real através de interfaces de rede virtuais, usando as interfaces de rede ‘tap’. O kernel do sistema virtual roda como se fosse mais um processo dentro do seu sistema, e os processos rodados por este kernel aparecem como subprocessos dele.
The program user-mode-linux (uml for short) lets you run a Linux virtual system inside another Linux, that can be connected to the real system through virtual network adapters, using the network interfaces ‘tap’. The virtual system’s kernel will run as another process in your system, and the processes runned by this kernel will be their subprocesses.

Instalando o user-mode-linux no Debian

O pacote user-mode-linux ainda está na release unstable; se estiver usando outra, siga as instruções abaixo.
Faça login como root e adicione esta linha no seu /etc/apt/sources.list :
deb ftp://ftp.debian.org/debian unstable main contrib non-free
Crie um arquivo chamado /etc/apt/apt.conf.d/00default e dentro dele digite:
APT::Default-Release "stable";
Este arquivo servirá para informar que, apesar de ter no sources.list mais de um release configurado, o padrão usado quando da instalação será sempre stable. Se ao invés de stable estiver usando testing, mude de acordo.
Agora digite os comandos abaixo para instalar o uml:
# apt-get update
# apt-get -t unstable install user-mode-linux

Configurando a interface de rede

A conexão usando interfaces tap não é obrigatória; você pode rodar seu sistema virtual sem interface de rede alguma. O uml te dá a possibilidade de, ao rodar, abrir três telas de terminal conectadas ao sistema virtual (as telas são abertas dentro do ambiente gráfico, usando o xterm ou o emulador de terminal gráfico padrão do seu Debian).
Ainda, existem outras formas de criar uma rede entre os sistemas virtual e real; consulte a documentação do user-mode-linux. Aqui, vou dar o exemplo usando uma interface tap.
Primeiro, você precisa garantir que seu kernel tem suporte às interfaces tap (também chamadas de tun/tap). A maioria dos kernels 2.6.x pré-compilados já deve possuir este módulo compilado. Para testar, digite os comandos a seguir, como root:
# modprobe tun
# ifconfig tap0 192.168.0.1 up

Se nenhuma mensagem de erro for emitida e uma interface de rede chamada ‘tap0’ aparecer (consulte com o comando ‘ifconfig’) é porque você tem o suporte necessário no seu kernel. Se a interface não aparecer, você pode precisar instalar um kernel mais recente, ou compilar um novo kernel com suporte a dispositivos tun/tap (se quiser tentar, a opção no kernel é em Device drivers -> Network device support -> Universal TUN/TAP device support).
Agora você pode configurar a interface tap0 como outra interface de rede qualquer. No Debian, sugiro editar o arquivo /etc/network/interfaces e adicionar as linhas abaixo:
iface tap0 inet static
address 192.168.0.1
netmask 255.255.255.0
tunctl_user arkanoid

Note a última linha; ela serve para dar ao usuário arkanoid direitos de escrita à interface tap0. Se você for rodar seu sistema virtual como root, esta linha não é necessária, caso contrário adicione aqui o usuário que você irá usar.
Além disso, se você quiser que esta interface seja configurada automaticamente na inicialização do sistema, não esqueça de adicionar a linha ‘auto tap0’.

Criando uma imagem de disco para o sistema virtual

Você irá precisar de um arquivo com uma imagem de um sistema de arquivos que será usada pelo uml como a partição de disco do sistema virtual. Na página do projeto há várias imagens para download (root filesystems). Você também pode criar a sua própria imagem; a seguir mostrarei como criar uma imagem de um sistema Debian.
Primeiro, crie um arquivo com tamanho suficiente para o seu sistema virtual (aqui criaremos um arquivo chamado duck com 500 MB). Digite o comando a seguir:
dd if=/dev/zero of=duck bs=1M count=500
Agora, formate o arquivo com o sistema de arquivos ext2:
mke2fs duck

Baixando e instalado um sistema Debian com debootstrap

Instale o pacote debootstrap, se não estiver instalado.
Agora, monte o filesystem recém-criado:
# mkdir /tmp/mduck
# mount -o loop duck /tmp/mduck

Rode o debootstrap conforme abaixo. Ele irá baixar e instalar os pacotes no diretório indicado. Pode-se usar um release diferente do que se está usando no sistema atual, no exemplo abaixo estou usando o sarge para o novo sistema. Além disso, pode-se usar as chaves –include e –exclude para respectivamente incluir ou excluir pacotes do novo sistema, além dos instalados no sistema básico.
# deboostrap --include=apache sarge /tmp/mduck
Agora será necessário criar alguns arquivos com a configuração básica do novo sistema. Segue abaixo uma lista de arquivos que você deve editar e as linhas a serem adicionadas/editadas em cada arquivo:
Arquivo /tmp/mduck/etc/fstab : acrescente as linhas abaixo:
proc /proc proc defaults 0 0
/dev/ubd0 / ext2 defaults 0 1

Arquivo /tmp/mduck/etc/hostname : mude o nome do novo sistema para um nome diferente do seu sistema hospedeiro. Neste exemplo, usarei o nome duck:
# echo duck > /tmp/mduck/etc/hostname
Arquivo /tmp/mduck/etc/hosts : crie este arquivo com o comando abaixo (troque ‘duck’ pelo nome do seu novo sistema):
# echo 127.0.0.1 localhost localhost.localdomain duck duck.localdomain > /tmp/mduck/etc/hosts
Arquivo /tmp/mduck/etc/network/interfaces : adicione as linhas abaixo:
auto lo
iface lo inet loopback

Estas linhas são o mínimo necessário para o sistema funcionar. É uma boa idéia configurar também a interface de rede virtual, que permitirá a comunicação entre o sistema virtual e o real. Para tanto, acrescente ainda as demais linhas neste arquivo:
auto eth0
iface eth0 inet static
address 192.168.0.2
netmask 255.255.255.0

Arquivo /tmp/mduck/etc/inittab : abra este arquivo com um editor de texto e localize o grupo de linhas abaixo:
1:2345:respawn:/sbin/getty 38400 tty1
2:23:respawn:/sbin/getty 38400 tty2
3:23:respawn:/sbin/getty 38400 tty3
4:23:respawn:/sbin/getty 38400 tty4
5:23:respawn:/sbin/getty 38400 tty5
6:23:respawn:/sbin/getty 38400 tty6

Edite estas linhas conforme abaixo. Note que na primeira linha mudamos tty1 para tty0:
1:2345:respawn:/sbin/getty 38400 tty0
#2:23:respawn:/sbin/getty 38400 tty2
#3:23:respawn:/sbin/getty 38400 tty3
#4:23:respawn:/sbin/getty 38400 tty4
#5:23:respawn:/sbin/getty 38400 tty5
#6:23:respawn:/sbin/getty 38400 tty6

Arquivo /tmp/mduck/etc/securetty : adicione as linhas abaixo:
tty0
tty/0

Agora você deve criar uma senha para o usuário root. Para tanto, iremos entrar no novo sistema com chroot:
# mount -t proc proc /tmp/mduck/proc
# chroot /tmp/mduck

A partir deste ponto qualquer comando afetará o sistema virtual e não o real. Mude a senha do root:
# passwd
E saia do chroot, voltando ao seu sistema hospedeiro:
# exit
Finalmente, desmonte o sistema de arquivos. Lembre que montamos um sistema de arquivos proc dentro do sistema virtual, então ele deve ser desmontado primeiro:
# umount /tmp/mduck/proc
# umount /tmp/mduck

Rodando o sistema virtual

Você poderá agora rodar o novo sistema como um usuário comum (o mesmo usuário a quem você deu permissão de acesso à interface tap0).
linux ubd0=duck eth0=tuntap,tap0
Você deve ser capaz de logar como root no novo sistema, e a interface de rede eth0 deve estar ativada. Você também deve ser capaz de acessar o sistema real do virtual e vice-versa – teste com o comando ping e o IP da interface tap0 no sistema real.
Para desligar o sistema virtual, naturalmente, use o comando halt.


Installing user-mode-linux on Debian

The package user-mode-linux still is in the unstable release; if you’re using another one, follow these instructions:
Log in as root and add this line to your /etc/apt/sources.list :
deb ftp://ftp.debian.org/debian unstable main contrib non-free
Create a file called /etc/apt/apt.conf.d/00default and put this line in this:
APT::Default-Release "stable";
This file informs apt-get to always get the stable version of a package, even if we have more than one release configured in our sources.list. If you’re using another relase, change the word “stable” in the file.
Now type the following commands to install uml:
# apt-get update
# apt-get -t unstable install user-mode-linux

Setting up the network interface

The network connection through tap interfaces isn’t really necessary; you can run your virtual system without any network connection at all. User-mode-linux gives you the option of opening three terminal screens connected to the virtual system (the terminals are opened inside the graphical environment, using xterm or the default terminal emulator defined in your Debian).
Also there are another ways of creating a network connection between your virtual and real systems; consult user-mode-linux documentation for details. Here I’ll give an example of setting up a virtual machine using the tap interface.
First, you need to check if your kernel has support to the tap interfaces (also called tun/tap). To check it, type the following commands as root:
# modprobe tun
# ifconfig tap0 192.168.0.1 up

If no error message is printed and a new network interface called ‘tap’ pops up (check with the command ‘ifconfig’), then your kernel supports the tun/tap interfaces. If the new interface doesn’t appear, you may need to install a newer kernel, or then recompile yours with tun/tap support (if you want to try, the option inside the kernel configuration is Device drivers -> Network device support -> Universal TUN/TAP device support).
Now you can set up the tap0 interface as any other network interface. On Debian, I’d suggest to edit the file /etc/network/interfaces and add the following lines:
iface tap0 inet static
address 192.168.0.1
netmask 255.255.255.0
tunctl_user arkanoid

Please note the last line; it gives the user arkanoid writing access to the tap0 interface. If you’re going to run your virtual system as root, you don’t need to add this line, otherwise add here the user you’ll use.
Also, if you want that this interface to be activated during the system startup, don’t forget to add the line ‘auto tap0’.

Creating a disk image to the virtual system

You will need a file with a filesystem image that will be used by uml as the disk partition of the virtual system. At the project page there are several root filesystem images for download. You can create your own; here I will show how to create a Debian image.
First, create a file with enough size for your virtual system (here we will create a 500 MB file called duck). Type the following command:
dd if=/dev/zero of=duck bs=1M count=500
Now, format the file with the ext2 filesystem:
mke2fs duck

Downloading and installing a Debian system with debootstrap

Install the package debootstrap, if it isn’t already installed.
Now, mount the filesystem:
# mkdir /tmp/mduck
# mount -o loop duck /tmp/mduck

Run debootstrap as indicated below. It will download and install all the required packages in the indicated directory. You can use a different release than the one in the current system, in this example we are using the sarge release for the new system. Also, you can use –include and –exclude to respectively include and exclude packages in the new system, besides the ones already installed in the base system.
# deboostrap --include=apache sarge /tmp/mduck
Now we must create some files with the basic configuration in the new system. Following is a list of files you must edit and the lines to be added/edited in each file:
File /tmp/mduck/etc/fstab : add the following lines:
proc /proc proc defaults 0 0
/dev/ubd0 / ext2 defaults 0 1

File /tmp/mduck/etc/hostname : change the new system’s name for something different from your host system. In this example, I will use the name duck:
# echo duck > /tmp/mduck/etc/hostname
File /tmp/mduck/etc/hosts : create this file with the following line (change ‘duck’ for the name of your new system):
# echo 127.0.0.1 localhost localhost.localdomain duck duck.localdomain > /tmp/mduck/etc/hosts
File /tmp/mduck/etc/network/interfaces : add the following lines:
auto lo
iface lo inet loopback

These lines are the minimum configuration needed for the system to work. It is a good idea to configure also the virtual network interface, through which the virtual system can communicate with the real one and vice versa. So, add the following lines to this file:
auto eth0
iface eth0 inet static
address 192.168.0.2
netmask 255.255.255.0

File /tmp/mduck/etc/inittab : open this file with a text editor and locate the following lines in it:
1:2345:respawn:/sbin/getty 38400 tty1
2:23:respawn:/sbin/getty 38400 tty2
3:23:respawn:/sbin/getty 38400 tty3
4:23:respawn:/sbin/getty 38400 tty4
5:23:respawn:/sbin/getty 38400 tty5
6:23:respawn:/sbin/getty 38400 tty6

Edit these lines as below. Note that in the first line tty1 was changed to tty0:
1:2345:respawn:/sbin/getty 38400 tty0
#2:23:respawn:/sbin/getty 38400 tty2
#3:23:respawn:/sbin/getty 38400 tty3
#4:23:respawn:/sbin/getty 38400 tty4
#5:23:respawn:/sbin/getty 38400 tty5
#6:23:respawn:/sbin/getty 38400 tty6

File /tmp/mduck/etc/securetty : add the following lines:
tty0
tty/0

Now you must create a password for the user root. To this end, we will enter in the new system with chroot:
# mount -t proc proc /tmp/mduck/proc
# chroot /tmp/mduck

From now on any command will affect the virtual system and not the real one. Change the root password:
# passwd
And leave the chroot environment, returning to your host system:
# exit
Finally, unmount the filesystem. Remember that we mounted a proc filesystem inside the virtual system, then it must be unmounted first:
# umount /tmp/mduck/proc
# umount /tmp/mduck

Running the virtual system

You can now run the new system as a normal user (the same user you granted access to the tap0 interface).
linux ubd0=duck eth0=tuntap,tap0
You must be able to log on as root in the new system, and the network interface eth0 must be working. You must also be able to access the virtual system from the real one and vice-versa – teste with the command ping and the IP of the host system tap0 interface.
To shutdown the virtual system, naturally, use the halt command.

2 pensou em “Creating a virtual Linux in Debian using user-mode-linux

  1. Dailson Fernandes

    Oi André
    Paz!
    Gostaria de saber se posso fazer testes com o HLBR utilizando este tutorial. Pois estou com um problema sério de máquinas… Toda vez que vou testar algo tenho que montar um verdadeiro “Maracatu” (gíria de pernambucano) pra fazer os testes.
    Posso rodar o HLBR em uma VM pra fazer testes??? usando o uml????
    Dailson

    Responder

Deixe um comentário para Dailson Fernandes Cancelar resposta

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *