Установка archlinux arm рядом с android без chroot

Содержание:

Create the chroot

To get started so you may build packages for Debian unstable, run the following.

sudo apt-get install sbuild schroot debootstrap
sudo sbuild-adduser $LOGNAME 
cp /usr/share/doc/sbuild/examples/example.sbuildrc $HOME/.sbuildrc # copy example config into your home as suggested
sudo apt install apt-cacher-ng
 ... *logout* and *re-login* or use `newgrp sbuild` in your current shell
sudo sbuild-createchroot --include=eatmydata,ccache,gnupg unstable /srv/chroot/unstable-amd64-sbuild http://127.0.0.1:3142/deb.debian.org/debian

Now for a brief explanation on what these commands do.

  1. Install sbuild onto the system.
  2. This will add your username so that it may use the sbuild command. Additional users may be added by running sudo sbuild-adduser USER1 USER2 .... sbuild-adduser will prompt you to copy the template sbuild configuration in /usr/share/doc/sbuild/examples/example.sbuildrc to each user’s ~/.sbuildrc, to be used as their user sbuild configuration. You can customize sbuild settings here, but you usually won’t need to customize anything. This should be done once per user.

  3. Copy the sbuild template configuration to your home folder.
  4. Install apt-cacher-ng, to cache packages needed in your sbuild usage
  5. Update the active user group set to include sbuild.
  6. Use sbuild-createchroot to create a chroot used by sbuild meant for building packages targeting Debian unstable main.

    The chroot is saved in /srv/chroot/unstable-amd64-sbuild. It installs the packages ccache and eatmydata in the chroot in case you want to use some of the enhancements detailed below. The apt repository used is the mirror service http://deb.debian.org/debian through apt-cacher-ng which will choose a suitable local mirror automatically. This can be changed to use a URL for a different mirror of the Debian archive. You can run this command once per distribution you want, and pass # —arch=i386 to create a chroot for a different architecture (the default is your host architecture).

    The command given above creates a type=directory chroot. If you are short of disc space, you can instead use the following command to create a chroot stored in a tarball at /srv/chroot/unstable-amd64-sbuild.tar.gz. This is not recommended unless you really can’t spare the disc space, because several of the enhancements below depend on using a type=directory chroot.

    sudo sbuild-createchroot —make-sbuild-tarball=/srv/chroot/unstable-amd64-sbuild.tar.gz unstable `mktemp -d` http://deb.debian.org/debian

Без прав суперпользователя

Chroot требует привелегий суперпользователя, что может быть нежелательно. Однако, есть несколько способов симулировать работу chroot, используя альтернативные реализации.

PRoot

PRoot может использоваться для изменения корневого раздела и использовать без привелегий суперпользователя. Это полезно для ограничивания доступа приложений до единственного каталога или запуска программ, собранных для другой архитектуры. Однако PRoot имеет ограничения, связанные с тем, что все файлы принадлежат пользователю на основной системе. PRoot предоставляет опцию , которая может быть использована в качестве обходного пути для этих ограничений, по тому же принципу (хотя и более ограниченно), что и в fakeroot.

Fakechroot

является небольшой прослойкой, которая перехватывает системные вызовы chroot и симулирует поведение системы, на самом деле не выполняя реальных вызовов (на которые все равно нет прав). Он может использоваться вместе с для создания видимости того, что chroot запускается суперпользователем.

# fakechroot fakeroot chroot ~/my-chroot bash

Montare pseudo filesystem

/proc

Se il sistema non è interamente funzionante controllare la presenza di /proc nel sistema chroot. A priori, dalla versione di debootstrap in Debian/Wheezy è integrato il montaggio di /proc e /sys nativamente.

proc on /proc type proc (rw)
sysfs on /sys sysfs kind (rw)

/dev/pts

È inoltre consigliato di fare un «bind» a /dev/pts. Questo previene messaggi di errore come Devo essere collegato ad un terminale o Impossibile accedere a ‘/dev/pts/0’: File o directory non esistente durante l’uso di screen.

In tal caso, dal sistema principale, eseguire il comando:

mount --bind /dev/pts /srv/chroot/stretch/dev/pts

Configurazioni predefinite

Generalmente il file /etc/fstab apparirà come segue:

# grep chroot /etc/fstab
/dev /srv/chroot/stretch/dev auto bind 0 0
/dev/pts /srv/chroot/stretch/dev/pts auto bind 0 0
/proc /srv/chroot/stretch/proc auto bind 0

Perciò «mount» dal sistema principale sarà:

# mount | grep chroot
/dev on /srv/chroot/stretch/dev -type none (rw, bind)
/dev/pts on /srv/chroot/stretch/dev/pts kind none (rw, bind)
/proc on /srv/chroot/stretch/proc type none (rw, bind)

Using piuparts

The use of piuparts with sbuild is another feature meant to enhance the quality of Debian packages built with sbuild. To use piuparts, edit your ~/.sbuildrc configuration file. Open ~/.sbuildrc with your favorite text editor and edit the lines with the following variables.

$run_piuparts = 1;
$piuparts_opts = ;

The $run_piuparts variable will enable running piuparts after a successful build with sbuild.

The $piuparts_opts variable is an array of options to pass to piuparts. Here the options instruct piuparts to use sbuild chroot ‘/srv/chroot/unstable-amd64-sbuild’ as the chroot used in its testing of packages.

Why Install Linux on Your Android Device?

So why might you want a Linux desktop environment installed on your Android phone or tablet?

You may wish to run an app that isn’t available on Android. But in most cases, you’ll simply want to gain access to some sort of desktop environment. Maybe you have a spare Android tablet you want to revitalize, and installing Linux on it is a good way to do this.

Current Android devices have ideal hardware for a PC-like experience, and installing Linux is a great way to enable this.

Of course, you may find that the tasks you want to perform in Linux also work in Android. The only hurdle holding you back might be simultaneous Android app multitasking. Fortunately, this is a feature that many modern Android devices support on the latest OS versions.

Running Linux running on an Android phone or tablet device isn’t easy. If you’re looking for improved multitasking, try upgrading to a recent version of Android instead.

Getting and installing debootstrap

For the least pain and gnashing of teeth, please get the Ubuntu binary packages manually by downloading from the following links with the ‘wget’ command which is demonstrated below:

  • http://archive.ubuntu.com/ubuntu/pool/main/d/debootstrap/debootstrap_1.0.7~dapper1_all.deb — If you want a dapper chroot

  • http://archive.ubuntu.com/ubuntu/pool/main/d/debootstrap/debootstrap_1.0.7~edgy1_all.deb — If you want a edgy chroot

  • http://archive.ubuntu.com/ubuntu/pool/main/d/debootstrap/debootstrap_1.0.7~feisty1_all.deb — If you want a feisty chroot

  • http://archive.ubuntu.com/ubuntu/pool/main/d/debootstrap/debootstrap_1.0.7~gutsy1_all.deb — If you want a gutsy chroot

  • http://archive.ubuntu.com/ubuntu/pool/main/d/debootstrap/debootstrap_1.0.9~hardy1_all.deb — If you want a hardy chroot (if that’s not available go to http://archive.ubuntu.com/ubuntu/pool/main/d/debootstrap/ and find the newest one)

Example: Terminal session wget-ing and installing the latest hardy debootstrap:

 wget http://archive.ubuntu.com/ubuntu/pool/main/d/debootstrap/debootstrap_1.0.9~hardy1_all.deb
 sudo dpkg --install debootstrap_1.0.9~hardy1_all.deb

Note that if you are going to develop the next in-development version on the current stable release (e.g. you want a Quantal chroot on your Precise system), you will need to install debootstrap from backports. Once you’ve enabled backports (e.g. precise-backports), you’ll need to explicitly install the new debootstrap in Ubuntu versions on or after 11.04. E.g.

 apt-get update
 apt-get install -t precise-backports debootstrap

Now you can easily build Quantal chroots.

Заполнение chroot-окружения

Теперь нужно установить систему в chroot; просто введите:

Флаг —variant задаёт тип chroot-окружения, которое нужно собрать. Опция build указывает, что нужно также установить инструменты сборки программ «из коробки», которые находятся в пакете build-essential. Узнать о доступных опциях больше можно при помощи команды:

Найдите описание –variant. Флаг —arch указывает архитектуру системы клиента. Если архитектура отличается от родительской архитектуры, нужно также использовать флаг —foreign. После этого нужно вызвать команду debootstrap во второй раз, чтобы завершить установку:

Эта команда выполняет установку, в то время как первая команда только загружает пакеты в случае архитектурных различий.

Примечание: Не забудьте флаг —foreign, если архитектура систем не совпадает.

Saucy в команде должно соответствовать имени, заданному в файле schroot.conf. Часть команды /test/ указывает целевой каталог, а URL задаёт адрес репозитория и загружает запрошенные файлы. На самом деле, формат данного файла очень похож на /etc/apt/sources.list. После этого можно просмотреть все файлы, которые были скачаны и установлены, проверив целевой каталог.

Как видите, выглядит как обыкновенная файловая система, только развёрнута она в нестандартном каталоге.

Tips and tricks

Write permissions

The path needs to be fully owned by , however files and/or subdirectories don’t have to be.
In the following example the user www-demo uses as the jail-directory:

# mkdir /srv/ssh/www/demo/public_html
# chown www-demo:sftponly /srv/ssh/www/demo/public_html
# chmod 755 /srv/ssh/www/demo/public_html

The user should now be able to create files/subdirectories inside this directory. See File permissions and attributes for more information.

Logging

The user will not be able to access . This can be seen by running on the process once the user connects and attempts to download a file.

Create sub directory

Create the sub-directory in the , for example:

# mkdir /usr/local/chroot/user/dev
# chmod 755 /usr/local/chroot/user/dev

Now you should create socket at which will be used by openssh. You may directly bind this socket to (or in case you’re using journald) or create using /.

Bind to journald

# touch /usr/local/chroot/user/dev/log
# mount --bind /run/systemd/journal/dev-log /usr/local/chroot/user/dev/log

Syslog-ng configuration

Add to a new source for the log and add the configuration, for example change the section:

source src {
  unix-dgram("/dev/log");
  internal();
  file("/proc/kmsg");
};

to:

source src {
  unix-dgram("/dev/log");
  internal();
  file("/proc/kmsg");
  unix-dgram("/usr/local/chroot/theuser/dev/log");
};

and append:

#sftp configuration
destination sftp { file("/var/log/sftp.log"); };
filter f_sftp { program("internal-sftp"); };
log { source(src); filter(f_sftp); destination(sftp); };

(Optional) If you would like to similarly log SSH messages to its own file:

#sshd configuration
destination ssh { file("/var/log/ssh.log"); };
filter f_ssh { program("sshd"); };
log { source(src); filter(f_ssh); destination(ssh); };

(From )

Notes

Some missing points are covered on this external article: http://ornellas.apanela.com/dokuwiki/pub:multiarch.

From unknown Sun Apr 17 05:43:14 +0100 2005 From: Date: Sun, 17 Apr 2005 05:43:14 +0100 Subject: Using symlinks for passwd, groups, shadow, etc..? Message-ID: <20050417054314+0100@https://www.ubuntulinux.org>

Wouldn’t it be possible to use symlinks for the files that get copied into the chroot? Like /etc/hosts? Would it work with /etc/passwd and the like?

  Re: You can link into, but not outof a chroot.
mv /etc/hosts /chroot/etc/hosts
ln -s ../chroot/etc/hosts /etc
... Using hardlinks is better.

From MichaelShigorin Sun Apr 17 13:42:38 +0100 2005 From: Michael Shigorin Date: Sun, 17 Apr 2005 13:42:38 +0100 Subject: nope Message-ID: <20050417134238+0100@https://www.ubuntulinux.org>

…but you can mount —bind them one be one.

From goofrider Thu May 12 19:26:45 +0100 2005 From: goofrider Date: Thu, 12 May 2005 19:26:45 +0100 Subject: chroot and symlinks Message-ID: <20050512192645+0100@https://www.ubuntulinux.org>

You can’t symlinks from inside the chroot to somewhere outside of it, because once you chroot into it, the new chroot will becomes , and all symlinks will be resolved relative to this new . Use mount --bind instead (though hard links should work too). —GoofRider 2005-05-12

From Sam Fri May 13 09:22:44 +0100 2005 From: Sam Date: Fri, 13 May 2005 09:22:44 +0100 Subject: mount -a Message-ID: <20050513092244+0100@www.ubuntulinux.org>

You can use $ sudo mount -a for mounting all the entries in fstab instead of mounting them one by one.

From LukaszStelmach Sun May 15 00:06:59 +0100 2005 From: Lukasz Stelmach Date: Sun, 15 May 2005 00:06:59 +0100 Subject: Using symlinks Message-ID: <20050515000659+0100@www.ubuntulinux.org>

You can make hardlink to files (but only when your chroot dir is on te same partition):

ln /etc/passwd /var/chroot/etc/

From: Elmo, 21.12.05 Does anyone know howto enable DRI from inside a 32bit chroot, ’cause if I mount —bind /dev/dri chroot/dev/dri I get the following error: «DDX driver parameter mismatch: got 848 bytes, but expected 840 bytes. libGL error: InitDriver failed» (glxinfo) I’d really like to get doom3 working on my amd64 install.

26.12.05, Elmo: I know, it should work natively, but I have problems with other games aswell, so getting dri working from a chroot would be great=)

26.12.05, Elmo: At debian-amd64 list(http://lists.debian.org/debian-amd64/2005/02/msg00807.html), around February 05, is said that it’s not possible at the moment. Got to find another way around my problem, will propably post to ubuntu forums.

10.06.06 Just a note from a person who ruined his system: After all this is done do not go and delete things from /var/chroot willy-nilly as it will delete the files from the linked directory as well. I found this out only after my entire /home directory was wiped out when I tried to free up some disk space by deleting the files from the chroot directory. Thanks to my foolishness I emptied root’s trash before I realized what I’d done. It’s been a while since my last backup so I lost everything from Documents, etc for the last year or so.

From: Murray Cumming 06.10.05: I had to do «apt-get install language-pack-en» to avoid the «Locale not supported by C library.» warnings. Even «sudo dpkg-reconfigure locales» gave a «perl: warning: Setting locale failed.» error until I did this. And that was even after I did a whole «sudo apt-get ubuntu-desktop» in the chroot.

Almost all the schroot config is unhelpful and irrelevant — Adding three lines to schroot.conf completely removes the need to copy anything from/to /etc:

run-setup-scripts=true
run-exec-scripts=true
type=directory

these will cause schroot itself to copy the latest versions of the required files every time, and do all required mounting to get /proc and /home working. Removes a LOT of effort and worry. And removes the risk of deleting your own home area due to stray bind mounts. — directhex, 2007-09-21

 Re: This is the best method.
I see there are a few things missing from these scripts, the rbind(bind) stuff, ect.  We should identify what is missing and try and get setup scripts to cover these areas.

The dchroot stuff here is practically obsolete. I found that it is completely possible to create a working schroot environment that does not make an individual root. Also the default setup appears to work. I tried it out when I messed up my ubuntu server install. Now my setup is relatively safe. None of the fstab stuff is required at all. I may actually create a wiki page to help out for schroot in non-root setups.

Configuration

Setup the filesystem

Note:

  • Readers may select a file access scheme on their own. For example, optionally create a subdirectory for an incoming (writable) space and/or a read-only space. This need not be done directly under — it can be accomplished on the live partition which will be mounted via a bind mount as well.
  • It is also possible chrooting into directory thus skipping the usage of bind, however the desired user home directory should be owned by root:
# chown root:root /home/<username>
# chmod 0755 /home/<username>

Bind mount the live filesystem to be shared to this directory. In this example, is to be used, owned by user and has octal permissions of :

# chown root:root /mnt/data/share
# chmod 755 /mnt/data/share
# mkdir -p /srv/ssh/jail
# mount -o bind /mnt/data/share /srv/ssh/jail

Add entries to fstab to make the bind mount survive on a reboot:

/mnt/data/share /srv/ssh/jail  none   bind   0   0

Create an unprivileged user

Note: You do not need to create a group, it is possible to use instead of .

Create the user group:

# groupadd sftponly 

Create a user that uses sftponly as main group and has shell login access denied:

# useradd -g sftponly -s /usr/bin/nologin -d /srv/ssh/jail username

Set a (complex) password to prevent error (may appear even with key authentication):

# passwd username

Configure OpenSSH

Note: You may want to use instead of as been given in the previous step.

/etc/ssh/sshd_config
Subsystem sftp /usr/lib/ssh/sftp-server

Match Group sftponly
  ChrootDirectory %h
  ForceCommand internal-sftp
  AllowTcpForwarding no
  X11Forwarding no
  PasswordAuthentication no

Restart to confirm the changes.

Fixing path for authorized_keys

Tip: Use the of OpenSSH on the client and server in case of error(s).

With the standard path of AuthorizedKeysFile, the SSH keys authentication will fail for chrooted-users. To fix this, append a root-owned directory on AuthorizedKeysFile to e.g. , as example:

/etc/ssh/sshd_config
AuthorizedKeysFile /etc/ssh/authorized_keys/%u .ssh/authorized_keys
PermitRootLogin no
PasswordAuthentication no
PermitEmptyPasswords no
Subsystem sftp /usr/lib/ssh/sftp-server

Create authorized_keys folder, generate a on the client, the contents of the key to (or any other preferred method) of the server and :

# mkdir /etc/ssh/authorized_keys
# chown root:root /etc/ssh/authorized_keys
# chmod 755 /etc/ssh/authorized_keys
# echo 'ssh-rsa <key> <username@host>' >> /etc/ssh/authorized_keys/username
# chmod 644 /etc/ssh/authorized_keys/username

Restart .

Управление идентификацией

$ cat ~/.ssh/config
StrictHostKeyChecking no

Парольная аутентификация

 # apt install sshpass

 # sshpass -p '123' ssh 172.16.1.13

server# sshpass -p cisco ssh switchN

server# sshpass -p cisco ssh switch1 sh int | grep line

Аутентификация с использованием ключей ssh

gate# cat /etc/ssh/sshd_config
...
PubkeyAuthentication yes
#AuthorizedKeysFile     %h/.ssh/authorized_keys
...

Генерация ключей

user1@client1:~$ ssh-keygen
...
Enter passphrase (empty for no passphrase): password1
...
user1@client1:~$ ls .ssh/

user1@client1:~$ chmod 755 .
user1@client1:~$ chmod 700 .ssh/
user1@client1:~$ chmod 600 .ssh/authorized_keys

Распространение публичных ключей

linux$ ssh-copy-id gate

freebsd$ ssh-copy-id -i .ssh/id_rsa.pub gate

вручную

user1@client1$ ssh gate "mkdir .ssh"

user1@client1$ scp .ssh/id_rsa.pub gate:.ssh/authorized_keys
или
user1@client1$ cat .ssh/id_rsa.pub | ssh gate "cat >> .ssh/authorized_keys"

Использование ssh_agent

user1@client1$ ssh-agent
SSH_AUTH_SOCK=/tmp/ssh-JaQgNr4492/agent.4492; export SSH_AUTH_SOCK;
SSH_AGENT_PID=4493; export SSH_AGENT_PID;
echo Agent pid 4493;

user1@client1$ SSH_AUTH_SOCK=/tmp/ssh-JaQgNr4492/agent.4492; export SSH_AUTH_SOCK;
user1@client1$ SSH_AGENT_PID=4493; export SSH_AGENT_PID;

или

user1@client1$ eval `ssh-agent -s`
user1@client1$ ssh-add
Enter passphrase for /root/.ssh/id_rsa:
...

gate# ssh-add -l
...

user1@client1$ ssh gate

Аутентификация с использованием протокола GSSAPI

Регистрация принципалов сервиса в KDC и перемещение ключа сервиса на сервер

Debian/Ubuntu (MIT)
root@server:~# kadmin.local
kadmin.local:  addprinc -randkey host/gate.corpX.un
...
kadmin.local:  listprincs

kadmin.local:  ktadd -k gatehost.keytab host/gate.corpX.un
...
kadmin.local:  quit
server# scp gatehost.keytab gate:
FreeBSD (Heimdal)
server# kadmin -l
kadmin> add -r host/gate.corpX.un
...
kadmin> list *

kadmin> ext -k gatehost.keytab host/gate.corpX.un
kadmin> quit
server# scp gatehost.keytab gate:
Microsoft Active Directory

Добавляем пользователя в AD

Login: gatehost
Password: Pa$$w0rd

Пароль не меняется и не устаревает

C:\>ktpass -princ host/gate.corpX.un@CORPX.UN -mapuser gatehost -pass 'Pa$$w0rd' -out gatehost.keytab

C:\>setspn -L -U gatehost

C:\>pscp gatehost.keytab gate:

Добавление ключа в системный keytab

Debian/Ubuntu (MIT)
root@gate:~# ktutil
ktutil: rkt /root/gatehost.keytab
ktutil: list
ktutil: wkt /etc/krb5.keytab
ktutil: quit

root@gate:~# klist -ek /etc/krb5.keytab
FreeBSD (Heimdal)
gate# ktutil copy /root/gatehost.keytab /etc/krb5.keytab
gate# touch /etc/srvtab

gate# ktutil list
...
gate# cat /etc/ssh/sshd_config
...
GSSAPIAuthentication yes
...
client1# cat /etc/ssh/ssh_config
...
GSSAPIAuthentication yes
...

Настройка windows клиента (Centrify putty) на использование GSSAPI

Hostname: gate.corpX.un
SSH->Auth
  Attempt "keyboard intractive": no
SSH->Kerberos 
  Attempt Kerberos Auth: yes
  User name portion of user principal name: yes
gate# kinit -V -k -t /etc/krb5.keytab host/gate.corpX.un@CORPX.UN

user1@client1$ kinit

user1@client1$ kinit -S host/gate.corpX.un@CORPX.UN
или
user1@client1$ kvno host/gate.corpX.un@CORPX.UN

user1@client1$ ssh -vv gate.corpX.un

gate# /usr/sbin/sshd -d

chroot command examples

In this example, build a mini-jail for testing purpose with bash and ls command only. First, set jail location using mkdir command: Create directories inside $J: Copy /bin/bash and /bin/ls into $J/bin/ location using cp command: Copy required libs in $J. Use ldd command to print shared library dependencies for bash: Sample outputs:

	linux-vdso.so.1 =>  (0x00007fff8d987000)
	libtinfo.so.5 => /lib64/libtinfo.so.5 (0x00000032f7a00000)
	libdl.so.2 => /lib64/libdl.so.2 (0x00000032f6e00000)
	libc.so.6 => /lib64/libc.so.6 (0x00000032f7200000)
	/lib64/ld-linux-x86-64.so.2 (0x00000032f6a00000)

Copy libs in $J correctly from the above output: Sample outputs:

`/lib64/libtinfo.so.5' -> `/home/vivek/jail/lib64/libtinfo.so.5'
`/lib64/libdl.so.2' -> `/home/vivek/jail/lib64/libdl.so.2'
`/lib64/libc.so.6' -> `/home/vivek/jail/lib64/libc.so.6'
`/lib64/ld-linux-x86-64.so.2' -> `/home/vivek/jail/lib64/ld-linux-x86-64.so.2'

Copy required libs in $J for ls command. Use ldd command to print shared library dependencies for ls command: Sample outputs:

	linux-vdso.so.1 =>  (0x00007fff68dff000)
	libselinux.so.1 => /lib64/libselinux.so.1 (0x00000032f8a00000)
	librt.so.1 => /lib64/librt.so.1 (0x00000032f7a00000)
	libcap.so.2 => /lib64/libcap.so.2 (0x00000032fda00000)
	libacl.so.1 => /lib64/libacl.so.1 (0x00000032fbe00000)
	libc.so.6 => /lib64/libc.so.6 (0x00000032f7200000)
	libdl.so.2 => /lib64/libdl.so.2 (0x00000032f6e00000)
	/lib64/ld-linux-x86-64.so.2 (0x00000032f6a00000)
	libpthread.so.0 => /lib64/libpthread.so.0 (0x00000032f7600000)
	libattr.so.1 => /lib64/libattr.so.1 (0x00000032f9600000)

You can copy libs one-by-one or try bash shell for loop as follows:

list="$(ldd /bin/ls | egrep -o '/lib.*\.')"
for i in $list; do cp  -v "$i" "${J}${i}"; done

Sample outputs:

`/lib64/libselinux.so.1' -> `/home/vivek/jail/lib64/libselinux.so.1'
`/lib64/librt.so.1' -> `/home/vivek/jail/lib64/librt.so.1'
`/lib64/libcap.so.2' -> `/home/vivek/jail/lib64/libcap.so.2'
`/lib64/libacl.so.1' -> `/home/vivek/jail/lib64/libacl.so.1'
`/lib64/libc.so.6' -> `/home/vivek/jail/lib64/libc.so.6'
`/lib64/libdl.so.2' -> `/home/vivek/jail/lib64/libdl.so.2'
`/lib64/ld-linux-x86-64.so.2' -> `/home/vivek/jail/lib64/ld-linux-x86-64.so.2'
`/lib64/libpthread.so.0' -> `/home/vivek/jail/lib64/libpthread.so.0'
`/lib64/libattr.so.1' -> `/home/vivek/jail/lib64/libattr.so.1'

Finally, chroot into your new jail: Try browsing /etc or /var: A chrooted bash and ls application is locked into a particular directory called $HOME/$J and unable to wander around the rest of the directory tree, and sees that directory as its “/” (root) directory. This is a tremendous boost to security if configured properly. I usually lock down the following applications using the same techniques:

  1. Apache – Red Hat / CentOS: Chroot Apache 2 Web Server
  2. Nginx – Linux nginx: Chroot (Jail) Setup
  3. Chroot Lighttpd web server on a Linux based system
  4. Chroot mail server.
  5. Chroot Bind DNS server and more.

Find out if service in chrooted jail or not

You can easily find out if Postfix mail server is chrooted or not using the following two commands:

pid=$(pidof -s master)
ls -ld proc$pidroot

Sample outputs from my Linux based server:

lrwxrwxrwx. 1 root root 0 Mar  9 11:16 /proc/8613/root -> /

The PID 8613 pointing out to / (root) i.e. the root directory for application is not changed or chrooted. This is a quick and dirty way to find out if application is chrooted or not without opening configuration files. Here is another example from chrooted nginx server:

pid=$(pidof -s master)
ls -ld proc$pidroot

Sample outputs:

lrwxrwxrwx 1 nginx nginx 0 Mar  9 11:17 /proc/4233/root -> /nginxjail

The root directory for application is changed to /nginxjail.

Когда не нужно использовать chroot?

Chroot-окружение Linux не стоит использовать в качестве средства защиты. В целом, окружения chroot могут быть использованы как дополнительный уровень безопасности, но они не достаточно изолированы, чтобы выступать в качестве полноценной защиты системы.

Конечно, chroot-окружения, создадут дополнительную работу для непривилегированного пользователя; однако их следует рассматривать как способ усиления безопасности сервера, а не как полноценную защиту, так как они способны только уменьшить количество векторов атаки, не обеспечивая полной безопасности. Для пользователей, которые нуждаются в полной изоляции, существуют боле надёжные решения (контейнеры Linux, Docker и т.п.).

Setting up a dchroot (non-root) environment

dchroot makes it possible to use your newly-built chroot even as a non-root user. Hence, you can configure your chroot environment in such a way that you can even use your existing /home as the chroot’s /home, thereby saving you some expensive moving in between homes, as well as making package building/testing a LOT more convenient.

To do this, first fix the user and root password:

 sudo cp /etc/passwd /var/chroot/hardy/etc/
 sudo sed 's/\(*\):*:/\1:*:/' /etc/shadow | sudo tee /var/chroot/hardy/etc/shadow
 sudo cp /etc/group /var/chroot/hardy/etc/
 sudo cp /etc/hosts /var/chroot/hardy/etc/ # avoid sudo warnings when it tries to resolve the chroot's hostname

For a debian chroot, I also had to do:

sudo sed 's/\(*\):*:/\1:*:/' /etc/gshadow | sudo tee /var/chroot/hardy/etc/gshadow

Then enable sudo and setup your passwords for root and the first sudo user in the admin group:

 sudo cp /etc/sudoers /var/chroot/hardy/etc/
 sudo chroot /var/chroot/hardy/
 dpkg-reconfigure passwd
 passwd <username of your first ubuntu user in the admin group>

Next, install the sudo package to be able to use it being in chroot:

 apt-get install sudo
 exit

Finish things up:

 sudo editor /etc/fstab

This is like the previous instructions, but different. Add these lines: (/media/cdrom is optional, of course, and you might have to create the dir in the chroot)

 /home           /var/chroot/hardy/home        none    bind            0       0
 /tmp            /var/chroot/hardy/tmp         none    bind            0       0
 /media/cdrom    /var/chroot/hardy/media/cdrom none    bind            0       0
 /dev            /var/chroot/hardy/dev         none    bind            0       0
 proc-chroot     /var/chroot/hardy/proc        proc    defaults        0       0
 devpts-chroot   /var/chroot/hardy/dev/pts     devpts  defaults        0       0

and delete these lines from before:

 /proc /var/chroot/hardy/proc none rbind 0 0 # Can just be mounted, comments?
 /dev /var/chroot/hardy/dev none rbind 0 0 # Good thing to do, but not secure.
 /sys /var/chroot/hardy/sys none rbind 0 0 # Same as proc?
 /tmp /var/chroot/hardy/tmp none rbind 0 0 # This opens a lot of doors, namly X sockets are here... DRI should work assuming bits match.
 /home /var/chroot/hardy/home none rbind 0 0 # This is optional.  As are the others, but this is more so.
 /media /var/chroot/hardy/media none rbind 0 0 # Your USB stick.
 /lib/modules /var/chroot/hardy/lib/modules none rbind 0 0 # You may need to load modules??  Think binfmt_misc.
 /var/run/dbus/ /var/chroot/hardy/var/run/dbus/ none rbind 0 0 # Gnome likes this.

Mount them:

sudo mount -a

The default bash path includes chroot information. To make this visible:

sudo chroot /var/chroot/hardy/
echo mychroot > etc/debian_chroot
exit

Set the chroot you just created in the dchroot.conf file

sudo editor /etc/dchroot.conf

Add the following to this file (if this is your first «dchroot» it will be a new, empty file; if there is more than one, the first item listed will be the default):

mychroot /var/chroot/hardy/

Now when you want to use your chroot (you may omit the -c mychroot if there’s only one, or you just want the first one in the file). The -d parameter means that your environment will be preserved, this is generally useful if you want chrooted applications to seamlessly use your X server, your session manager, etc.

 dchroot -c mychroot -d

Tada! Now you can switch to and from your main and /var/chroot/, without even becoming root!

Shortcuts / Usage

you can type dchroot -d «command» and it executes that command in the chroot.

I have this script do_chroot in /usr/local/bin:

/usr/bin/dchroot -d "`echo $0 | sed 's|^.*/||'` $*"

I had trouble with quoting in the above script. This one works better for me. ~JPKotta

args=""
for i in "$@" ; do
    args="$args '$i'"
    #echo $args
done

/usr/bin/dchroot -d -- "$0" $args

Then I create a symbolic link from that to the command I want to execute in the chroot, e.g.:

ln -s /usr/local/bin/do_chroot /usr/local/bin/firefox

which will execute firefox in the chroot environment when I launch it in my normal 64 bit environment. To launch my amd64 firefox I can type /usr/bin/firefox.

Instead if you want you can just create a script for launching the 32bit firefox e.g.:

dchroot -d "firefox"

put it in /usr/local/bin and add it to the gnome menu.

If you’re going to start a program that only works in 32bit, first type dchroot -d and you’ll be in the 32 bit environment.

Setting up your chroot with debootstrap

If you want a 32-bit chroot on amd64 add --arch i386 to this command line. If you use the chroot to build packages add --variant=buildd . Change hardy to according to your needs to dapper, edgy, feisty or leave as is for hardy chroot.

To actually install the base chroot, open a Terminal and do:

 sudo debootstrap --variant=buildd --arch i386 hardy /var/chroot/hardy http://archive.ubuntu.com/ubuntu/

debootstrap will then build a HardyHeron chroot in /var/chroot/, getting the base packages in http://archive.ubuntu.com/ubuntu/, and, depending on the given additional options (in square brackets,) debootstrap will build a chroot for the given architecture and variant.

If debootstrap finishes successfully, you’ll be left with a base chroot in /var/chroot, which is not suitable for nearly anything. To actually get our chroot to work and be able to, say, grab packages from the network, do the following right after debootstrap:

 sudo cp /etc/resolv.conf /var/chroot/hardy/etc/resolv.conf
 sudo cp /etc/apt/sources.list /var/chroot/hardy/etc/apt/
 sudo editor /var/chroot/hardy/etc/apt/sources.list

If your current distribution is different than your target distribution (i.e. you use Hardy and want a Gutsy chroot), change all of the occurrences of Hardy/Gutsy/Feisty/Edgy etc. to your target distribution.

 sudo chroot /var/chroot/hardy
 apt-get update
 apt-get --no-install-recommends install wget debconf devscripts gnupg nano  #For package-building
 apt-get update  #clean the gpg error message
 apt-get install locales dialog  #If you don't talk en_US
 locale-gen en_GB.UTF-8  # or your preferred locale
 tzselect; TZ='Continent/Country'; export TZ  #Configure and use our local time instead of UTC; save in .profile
 exit

If you dont want the locale warnings in your chroot, add this to your ~/.bashrc file.

export LANG=C 

You can stop here if you want a simple chroot that you use as root (sudo chroot /var/chroot). If you want to use your chroot as another user and have access to your normal /home and other directories inside the chroot, continue.

Note for Debian chroot on Ubuntu

If you want to build a Debian chroot on an Ubuntu system you need to point it at a Debian archive:

 sudo debootstrap --arch i386 sid sid/ http://ftp.uk.debian.org/debian/

A note about chrooting apps on a Linux or Unix-like systems

Should you use the chroot feature all the time? In the above example, the program is fairly simple but you may end up with several different kinds of problems such as:

  1. Missing libs in jail can result into broken jail.
  2. Complex program are difficult to chroot. I suggest you either try real jail such as provided by FreeBSD or use virtualization soultuon such as KVM on Linux.
  3. App running in jail can not run any other programs, can not alter any files, and can not assume another user’s identity. Loosen these restrictions, you have lessened your security, chroot or no chroot.

Also note that:

  1. Do not forgot, to updated chrooted apps when you upgrade apps locally.
  2. Not every app can or should be chrooted.
  3. Any app which has to assume root privileges to operate is pointless to attempt to chroot, as root can generally escape a chroot.
  4. Chroot is not a silver bullet. Learn how to secure and harden rest of the system too.

Apt package caching

To avoid downloading the same packages over and over again when building a package multiple times in a row, install the apt-cacher-ng package and use http://localhost:3142/debian as a proxy.

For an existing sbuild chroot, you can update your sources.list as follows:

sudo sbuild-shell source:unstable-$arch-sbuild
echo 'acquire::http::proxy "http://localhost:3142/debian";' >>  /etc/apt/apt.conf.d/proxy

For new schroot, you can use this:

sudo apt install apt-cacher-ng
sudo sbuild-createchroot --include=eatmydata,ccache,gnupg unstable /srv/chroot/unstable-amd64-sbuild http://127.0.0.1:3142/deb.debian.org/debian

See also AptCacherNg for more details on how to configure the proxy.

Unknown key B4C86482705A2CE1

Debian’s package system has a chronic problem of missing signing keys, and inability to update the system once installed (if it installs in the first place). You will experience the goodness with errors like Release signed by unknown key (key id B4C86482705A2CE1) and failures in Apt. If you find yourself fighting the Debian package system, you should (1) know you are not alone, and (2) visit bug reports like and .

According to the bug, you are supposed to be able to fix it with one of the following. We know for certain the suggestions do not work under Debian Hurd (i386). We don’t expect it to work in other places either, like Sparc64.

apt-get install --reinstall debian-archive-keyring

Or

apt-get install --reinstall debian-ports-archive-keyring

Or

dpkg --force-depends -P debian-archive-keyring
dpkg -i /var/cache/apt/archives/debian-archive-keyring*

Or

cd /
apt-get update

Or

cd ~
apt-get update

Running Apt with --no-check-gpg and --allow-unauthenticated does not work either.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector