Linux Chroot Command Tutorial with Examples
Linux provides different mechanisms for practical and security reasons.
chroot is one of them. Processes in linux can access to the file system or root by default. Linux kernel also provides
chroot mechanism to restrict access to the whole filesystem in Linux.
The chroot syntax is like below.
chroot OPTION NEWROOT COMMAND
OPTIONis chroot option
NEWROOTis the new root directory
COMMANDis the command we want to run in the chrooted directory
Chroot Jail or Jailed Directory
We can create a jailed directory or chroot jail just using
chroot command with the path we want to use as jail. After the chroot the new root will be the given path. In this example we will chroot to the
/home/ismail/ . After chroot all contents of the
/home/ismail will be served as
/ root directory.
$ chroot /home/ismail /bin/bash
But keep in mind that before chrooting we need two things.
- We need root privileges to run
- We should provide command and required libraries we want to run in chrooted environment
Specify User and User ID
We can specify the user we want to use in chrooted environment as process owner. We will use
--userspec and the user id or name. In this example we will use user named
$ chroot --userspec=ismail /home/ismail /bin/bash
OR we will use user id
$ chroot --userspec=1001 /home/ismail /bin/bash
Specify Group and Group ID
We can also specify the group name or group ID we want to use for the chrooted process. We will use
--groups option. We can specify multiple groups by separating the group ids or names with comma. In this example we will use group
$ chroot --groups=ismail /home/ismail /bin/bash
OR we can use group ID like below
$ chroot --groups=1001 /home/ismail /bin/bash
Do Not Change Working Directory
We can also skip changing current working directory of the chrooted process to the
/ root. We will us
--skip-chdir . We will use current root as chrooted root.
$ chroot --skip-chdir / /bin/bash