SSH and SFTP Chroot Jail

Let’s get Jailed!

Step 1: Create your chroot directories

I’ve seen a few strategies for this including placing the chroot directory under /var/chroot.

In this case all of the clients on this server have a public_html subdirectory structure under their home directories. To make it easy to see who’s been jailed we’ll put our chroot jail in /home.

#Create our directories
sudo mkdir -p /home/jail/{dev,etc,lib,lib64,usr,bin,home}
sudo mkdir -p /home/jail/usr/bin

#Set owner
sudo chown root:root /home/jail

#Needed for the OpenSSH ChrootDirectory directive to work
sudo chmod go-w /home/jail

Step 1: Choose your commands

We’ll offer a limited set of userspace applications. For these to work you need to copy the binary into its corresponding directory in the jail, as well as copy over any linked dependencies.

Allan Field pointed me to a handy script that can be used for bringing binary dependencies over for a given executable (as opposed to manually – via ldd and copying the results.)

The script can be found here…

We’re going to offer bash, cp, ls, clear, and mkdir to our jailed users (for starters).

#First the binaries
cd /home/jail/bin
sudo cp /bin/bash .
sudo cp /bin/ls .
sudo cp /bin/cp .
sudo cp /bin/mv .
sudo cp /bin/mkdir .

#Now our l2chroot script to bring over dependencies
sudo /bin/bash
sudo /bin/ls
sudo /bin/cp
sudo /bin/mv
sudo /bin/mkdir

(This should really be wrapped up into a single bash script that takes both the binary and its dependencies).

The clear command requires terminal definitions…

# clear command
cd /home/jail/usr/bin
sudo cp /usr/bin/clear .
sudo /usr/bin/clear
#Add terminal info files - so that clear, and other terminal aware commands will work.
cd /home/jail/lib
sudo cp -r /lib/terminfo .

Step 2: Create your user and jail group

Create the jail group sudo groupadd jail

You can either create a new user using sudo adduser --home /home/jail/home/username username, or copy (and then later remove) the home directory of an existing user into the home/jail/home directory.

If you create a new user using sudo adduser --home /home/jail/home/username username – the home directory will be created in the jail, but the user’s home directory in /etc/passwd will need to be edited to return it to /home/username – since the jail root will put home at the root again once the user is logged in.

Now add the user to the jail group sudo addgroup username jail

Step 3: Update sshd_config

We’re going to edit the sshd_config file, removing theForceCommand internal-sftp directive – since we don’t want to limit our users to SFTP (you could maintain a second group and configuration for this).

Match Group jail
    ChrootDirectory /home/jail
    X11Forwarding no
    AllowTcpForwarding no

We’ve chrooted to /home/jail – and both SFTP and SSH logins will default to the user’s home directory below the jail.

Restart the sshd daemon, and you’re ready to go sudo /etc/init.d/ssh restart or service ssh restart

Try logging in via SSH or SFTP, and your jailed user will be dropped into their home directory under /home/jail/home, with a limited set of userspace applications, and no access to the parent environment.

Step 4: Bonus marks – give the user MySQL access

I’d like users to be able to upload and configure a site, including be able to perform mysql dumps and restores. Here’s how to give them a MySQL prompt.

#Binaries for MySQL Client
sudo mkdir /home/jail/usr/local/mysql/bin
cd /home/jail/usr/local/mysql/bin
sudo cp /usr/local/mysql/bin/mysql .
sudo /usr/local/mysql/bin/mysql
cd /home/jail/lib/x86_64-linux-gnu
sudo cp /lib/x86_64-linux-gnu/ .

Note the ‘undiscovered’ dependancy on

Wrapping Up!

This is a nice and simple solution that works thanks to OpenSSH’s built in ChrootDirectory directive. It doesn’t require any modification to the passwd file, and could fairly easily be wrapped up into a consolidated shell scrip for creating, updating and adding applications to the jail.


How To Set Up GitLab As Your Very Own Private GitHub Clone


Git and GitHub are awesome tools that make managing and administering lots of Git repositories and their associated permissions a breeze. This is wonderful if you’re writing open source software, but when writing closed source software you may not want to trust your code to a third party server. So how can you get the control, flexibility and ease of use of something like Github or BitBucket without hosting your git repositories on servers outside of your control?

Enter GitLab. GitLab provides a simple but powerful web based interface to your Git repositories a la GitHub, only you can host it on your own cloud server, control access as you see fit, and repo size is limited only by how much storage space your server has. This tutorial will walk you through setting up a DigitalOcean VPS as a GitLab server.

It assumes you’re using a brand new Ubuntu 12.04 VPS. We’ll be installing all the necessary software needed to make GitLab work. If you are using an existing VPS (droplet) or a different Linux distro you may have issues, especially with incompatible Python and Ruby versions. Make sure you have Ruby 2.0 and Python 2.7 installed before beginning.

The first step is to install some required packages:

sudo apt-get update
sudo apt-get install -y build-essential zlib1g-dev libyaml-dev libssl-dev libgdbm-dev libreadline-dev libncurses5-dev libffi-dev curl git-core openssh-server redis-server checkinstall libxml2-dev libxslt-dev libcurl4-openssl-dev libicu-dev

Make sure you don’t have Ruby 1.8 installed (on a default Ubuntu 12.04 VPS it won’t be).

Install Ruby 2.0 (this will take a while):

mkdir /tmp/ruby && cd /tmp/ruby
curl --progress | tar xz
cd ruby-2.0.0-p247
sudo make install

When it’s finished you can check to make sure that you have Ruby 2 (not 1.8) installed by doing a:

ruby --version

If the output looks like the below then you’re good:

ruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-linux]

Now we need to install the Bundler gem:

sudo gem install bundler --no-ri --no-rdoc

And create a git user for GitLab to use:

sudo adduser --disabled-login --gecos 'GitLab' git

Installing the GitLab Shell

Download the GitLab shell with the following commands:

cd /home/git
sudo -u git -H git clone
cd gitlab-shell
sudo -u git -H git checkout v1.7.0
sudo -u git -H cp config.yml.example config.yml

You now have a copy of GitLab Shell 1.7.0, and the example config.yml is ready to go.

If you have a domain name pointed at this VPS, then you should take the time to editconfig.yml to use this domain.

nano config.yml

Near the top there will be a line that looks like:

gitlab_url: "http://localhost/"

Change the http://localhost/ portion to match your domain name. So if your domain is the line should look like this:

gitlab_url: ""

Now you can run the GitLab shell installer:

sudo -u git -H ./bin/install

Database Setup

We’ll set up GitLab to use a MySQL backend. The first step is to install MySQL with the below command. During the install process it will ask you to set a MySQL root password. Set it to whatever you like, but note it down as you will need it for the next steps.

sudo apt-get install -y mysql-server mysql-client libmysqlclient-dev

MySQL is now installed and the root password is set to the value you chose in the last step. We now need to create a MySQL user for GitLab to use. To do this we’ll first save the necessary SQL queries to a temporary file. Type:

nano tempfile


Paste in the following, changing the $password on the first line to a real password. Keep track of this password as this will be your GitLab’s database password.

CREATE USER 'gitlab'@'localhost' IDENTIFIED BY '$password';
CREATE DATABASE IF NOT EXISTS `gitlabhq_production` DEFAULT CHARACTER SET `utf8` COLLATE `utf8_unicode_ci`;
GRANT SELECT, LOCK TABLES, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER ON `gitlabhq_production`.* TO 'gitlab'@'localhost';

Now save the file and execute the following command (entering your MySQL root password from the first step at the prompt) to have MySQL execute your queries:

cat tempfile | mysql -u root -p

To make sure your new MySQL user was created successfully let’s log in to mysql using thegitlab user:

mysql -u gitlab -p

If you see some text followed by a:


line then everything worked successfully. Go ahead and type:



at the mysql> prompt to exit MySQL, and delete the tempfile file since it contains a password:

rm tempfile


At this point we have everything configured to install GitLab successfully, so let’s proceed with the installation:

cd /home/git
sudo -u git -H git clone gitlab
cd /home/git/gitlab
sudo -u git -H git checkout 6-0-stable
sudo -u git -H cp config/gitlab.yml.example config/gitlab.yml


Just like we did with the GitLab shell set up, if you have a domain configured for your VPS we need to edit the config.yml to use that domain.

sudo -u git -H nano config/gitlab.yml


Near the top of the file you should a text block that looks like the following:

## Web server settings
host: localhost
port: 80
https: false


Change the host: entry to match your domain name. If your domain is, then it should look like this:

## Web server settings
port: 80
https: false


Let’s also set some linux file permissions, configure the git user’s Git config, and set up some GitLab config and directories for the git user:

cd /home/git/gitlab
sudo chown -R git log/
sudo chown -R git tmp/
sudo chmod -R u+rwX  log/
sudo chmod -R u+rwX  tmp/
sudo -u git -H mkdir /home/git/gitlab-satellites
sudo -u git -H mkdir tmp/pids/
sudo -u git -H mkdir tmp/sockets/
sudo chmod -R u+rwX  tmp/pids/
sudo chmod -R u+rwX  tmp/sockets/
sudo -u git -H mkdir public/uploads
sudo chmod -R u+rwX  public/uploads
sudo -u git -H cp config/unicorn.rb.example config/unicorn.rb
sudo -u git -H git config --global "GitLab"
sudo -u git -H git config --global "gitlab@localhost"
sudo -u git -H git config --global core.autocrlf input
sudo -u git cp config/database.yml.mysql config/database.yml


Now we need to tell GitLab to use the gitlab MySQL user we set up earlier. To do this, edit the config/database.yml file:

sudo -u git -H nano config/database.yml


Near the top there will be a section called production: which will contain username andpassword entries. By default it looks like this:

  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: gitlabhq_production
  pool: 10
  username: root
  password: "secure password"


Change the username and password entries to match the GitLab database user we set up earlier. So if the password you used for your GitLab MySQL user was $password the edited file should look like this:

  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: gitlabhq_production
  pool: 10
  username: gitlab
  password: "$password"


Save the file, and we’ll secure it so that other users of the server can’t see the password:

sudo -u git -H chmod o-rwx config/database.yml


Let’s install a few more needed gems (this step may take awhile):

cd /home/git/gitlab
sudo gem install charlock_holmes --version ''
sudo -u git -H bundle install --deployment --without development test postgres aws


And run some final setup (type yes when it asks if you want to continue):

sudo -u git -H bundle exec rake gitlab:setup RAILS_ENV=production


After this finishes it will print a lot of information onscreen and at the end will showAdministrator account created and give you your administrator credentials. It should look something like the below:

Administrator account created:


Now let’s set GitLab to start up whenever your server boots:

sudo cp lib/support/init.d/gitlab /etc/init.d/gitlab
sudo chmod +x /etc/init.d/gitlab
sudo update-rc.d gitlab defaults 21


Run the following to make sure everything is working:

sudo -u git -H bundle exec rake gitlab:env:info RAILS_ENV=production


If there are no error messages and the data outputted by that command looks right then your GitLab install is working. Almost finished! Start up GitLab with this command:

sudo service gitlab start

Setting Up NGINX

GitLab works with the nginx web server by default. If you already have your own web server such as Apache set up then these steps don’t apply. Check out these recipes for info on how to configure GitLab with other web servers. Otherwise follow these directions to install and configure nginx to work with GitLab:

sudo apt-get -y install nginx
cd /home/git/gitlab
sudo cp lib/support/nginx/gitlab /etc/nginx/sites-available/gitlab
sudo ln -s /etc/nginx/sites-available/gitlab /etc/nginx/sites-enabled/gitlab


Edit /etc/nginx/sites-available/gitlab to use your domain name:

sudo nano /etc/nginx/sites-available/gitlab


A little ways from the top of the file you will see an entry server_name which is set toYOUR_SERVER_FQDN. As in the previous steps, replace the YOUR_SERVER_FQDN with your domain name. The original file looks like this:

server {
  listen *:80 default_server;     # e.g., listen; In most cases *:80 is a good idea
  server_name YOUR_SERVER_FQDN;       #


If your domain is then you should change it to look like this:

server {
  listen *:80 default_server;         # e.g., listen; In most cases *:80 is a good idea
  server_name;     #


And restart nginx:

sudo service nginx restart


Voila! You’re done. Connect to GitLab via your web browser using the Admin login and password from above (default user:, pass: 5iveL!fe) and enjoy GitLab.

If you are using a 512MB VPS then due to GitLab’s memory requirements it’s quite likely you will run into a 502 Bad Gateway error. If that’s the case, read on…


502 Bad Gateway Error

In a perfect world GitLab would now be running perfectly. Unfortunately, GitLab has surprisingly high memory requirements, so on 512MB VPSs it often chokes on the first sign in. This is because GitLab uses a lot of memory on the very first login. Since the Ubuntu 12.04 VPS has no swap space when the memory is exceeded parts of GitLab get terminated. Needless to say GitLab does not run well when parts of it are being unexpectedly terminated.

The easiest solution is just to allocate more memory to your VPS, at least for the first sign in. If you don’t want to do that, another option is to increase swap space. DigitalOcean already has a full tutorial on how to do this available here (although I would recommend adding more than just 512MB of swap). The quick fix is to run the following:

sudo dd if=/dev/zero of=/swapfile bs=1024 count=1024k
sudo mkswap /swapfile
sudo swapon /swapfile


Your swapfile is now running and active, but to set it so that it’s activated on each boot we need to edit /etc/fstab:

sudo nano /etc/fstab


Paste the following onto the bottom of the file:

/swapfile       none    swap    sw      0       0 


Now restart your VPS:

sudo restart


Wait a minute or two for your VPS to reboot, and then try GitLab again. If it doesn’t work the first time, refresh the Bad Gateway page a couple of times, and you should soon see the GitLab login page.

How To Create a SSL Certificate on nginx

ABout Self-Signed Certificates

A SSL certificate is a way to encrypt a site’s information and create a more secure connection. Additionally, the certificate can show the virtual private erver’s identification information to site visitors. Certificate Authorities can issue SSL certificates that verify the server’s details while a self-signed certificate has no 3rd party corroboration.

Set Up

You need to have nginx already installed and running on your VPS.
If this is not the case, you can download it with this command:

sudo apt-get install nginx

Step One—Create a Directory for the Certificate

The SSL certificate has 2 parts main parts: the certificate itself and the public key. To make all of the relevant files easy to access, we should create a directory to store them in:

 sudo mkdir /etc/nginx/ssl

We will perform the next few steps within the directory:

 cd /etc/nginx/ssl

Step Two—Create the Server Key and Certificate Signing Request

Start by creating the private server key. During this process, you will be asked to enter a specific passphrase. Be sure to note this phrase carefully, if you forget it or lose it, you will not be able to access the certificate.

sudo openssl genrsa -des3 -out server.key 1024

Follow up by creating a certificate signing request:

sudo openssl req -new -key server.key -out server.csr

This command will prompt terminal to display a lists of fields that need to be filled in.

The most important line is “Common Name”. Enter your official domain name here or, if you don’t have one yet, your site’s IP address. Leave the challenge password and optional company name blank.

You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
Country Name (2 letter code) [AU]:US
State or Province Name (full name) [Some-State]:Texas
Locality Name (eg, city) []:Dallas
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Awesome Inc
Organizational Unit Name (eg, section) []:Dept of Merriment
Common Name (e.g. server FQDN or YOUR name) []                  
Email Address []

Step Three—Remove the Passphrase

We are almost finished creating the certificate. However, it would serve us to remove the passphrase. Although having the passphrase in place does provide heightened security, the issue starts when one tries to reload nginx. In the event that nginx crashes or needs to reboot, you will always have to re-enter your passphrase to get your entire web server back online.

Use this command to remove the password:

sudo cp server.key
sudo openssl rsa -in -out server.key

Step Four— Sign your SSL Certificate

Your certificate is all but done, and you just have to sign it.

Keep in mind that you can specify how long the certificate should remain valid by changing the 365 to the number of days you prefer. As it stands this certificate will expire after one year.

 sudo openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

You are now done making your certificate.

Step Five—Set Up the Certificate

Now we have all of the required components of the finished certificate.The next thing to do is to set up the virtual hosts to display the new certificate.

Let’s create new file with the same default text and layout as the standard virtual host file. You can replace “example” in the command with whatever name you prefer:

sudo cp /etc/nginx/sites-available/default /etc/nginx/sites-available/example

Then go ahead and open up that new file:

 sudo nano /etc/nginx/sites-available/example

Scroll down to the bottom of the file and find the section that begins with this:

# HTTPS server

server {
        listen 443;

        root /usr/share/nginx/www;
        index index.html index.htm;

        ssl on;
        ssl_certificate /etc/nginx/ssl/server.crt;
        ssl_certificate_key /etc/nginx/ssl/server.key; 

Uncomment within the section under the line HTTPS Server. Match your config to the information above, replacing the in the “server_name” line with your domain name or IP address. Subsequently, add in the correct directory for your site (the above configuration includes the default nginx page).

Additionally, make sure that both of these lines are commented out in the line toward the beginning of the file that says:

# Make site accessible from http://localhost/
# server_name localhost;

Step Six—Activate the Virtual Host

The last step is to activate the host by creating a symbolic link between the sites-available directory and the sites-enabled directory.

 sudo ln -s /etc/nginx/sites-available/example /etc/nginx/sites-enabled/example

Then restart nginx:

 sudo service nginx restart

Visit https://youraddress You will see your self-signed certificate on that page!