Are you planning of moving away from your current Shared Web Hosting Company? Or perhaps, your website is getting lots of traffic now and thus, hogging most of the resources shared on your server and that you urgently need to create your own private server for your busy website.
Jump Links
Use these short-cut links to go to a specific part of this post:
- Purpose
- About VPS
- About Cloud VPS
- Requirements
- VPS Setup & Configurations
- TCP Wrapper Configuration
- Setup Basic Firewall
- Installing Fail2ban
- Point Your Domain Name To Your VPS
Not only that, maybe you’re a student or self-learner like myself who is fond of learning things on their own.
Whatever your reasons are in setting up your own VPS (Virtual Private Server), you could follow this step-by-step guide. I’ve written this guide in a very noob-friendly way so beginners and self-learners like myself could easily setup and configure their own server on any VPS hosts they like.
Purpose
This easy-to-follow tutorial teaches you (in a noob friendly way) how you would install Ubuntu 14.04 Server – TrustyTahr on a newly purchased VPS hosting account. This is a self-managed VPS or other term for it is Un-managed VPS. Others calls it Do-it-yourself or Self-managed VPS.
I’m not an expert when it comes to provisioning these kind of servers, but I do have lots of experiences in installing and configuring Ubuntu Servers on my Lab Computer and Development Servers like this one. I learned this stuff by myself and I am now promoted from Ubuntu Server Noob to Ubuntu Server Semi-Noob.
If you own a VPS or Cloud VPS, you have a dedicated resources for your hosting account. Resources like; bandwidth, memory, and storage.
With VPS, you have your own server resource and your own server. Unlike with shared hosting, where thousand of hosting accounts and web sites are hosted under one server, and shares all the server resources.
So if you follow and use this guide, you will learn how to build a virtual private server from scratch to finish, which you could use to host several web sites and CMS you’d like. Furthermore, you could also install many applications and open source software like OpenVPN Access Server
About Virtual Private Servers
VPS are virtual machines configured as servers.
If you have used VirtualBox or VMWare, then you should know what a virtual machine is. But those are just for Desktop Computers, not for server
VPS, like virtual machines or VMs runs on a dedicated machines loaded with HyperVisor.
The Hypervisor, which is also a software installed on bare-metals or on top of OS (i.e. Linux & Windows) runs those virtual machines and present it as guest machines.
Example of an Hypervisor is VirtualBox and VMWare, only thing is, those software are classified as Type-2 Hypervisors. Which means, they are installed on top of an Operating System, like Linux – Ubuntu Servers / Desktops.
Example of Type-1 Hypervisors are; VMWare ESXi & Microsoft Hyper-V.
Virtual Private Servers are sold by hosting companies as a Service. You are billed monthly, quarterly, semi-annual or annually for hosting your Virtual Machines under one of their hypervisor on their infrastructure.
Comparing it from a VPS, with Shared Hosting, you are billed for hosting your websites on the Web Host’s servers.
How About Cloud VPS
To the best of my knowledge, a cloud VPS is just like any other VPS that is hosted on a remote location or infrastructure. The VPS host provides you the means to connect to your server and configure it.
Unlike ordinary physical server or bare-metal, Cloud VPS’s storage is separate from the physical machine where your VPS is hosted on. It’s not like you have a virtual machine inside your VirtualBox (or VMWare) where its virtual hard drive is stored in the host’s physically attached hard disks.
With Cloud VPS, your storage or hard drive space is actually on another server called Storage Servers, these type of servers are dedicated to serve storage spaces or virtual hard drives for virtual machines or VPSs. For a cloud hosting company, one Storage Server would not be enough, so they build several and thousands of Storage Servers and then connect them to a network. They call them SAN or Storage Area Network.
Cloud VPS is scalable which means, you could adjust (scale up) your server resources like memory limit, storage limit or bandwidth limit whenever you feel necessary, with just a button click or set it to auto-scale upon traffic spikes without rebooting. You could also scale it down whenever you feels like to. You could do this using the hosting company’s web-based control panel.
If you have something more to tell about Cloud VPS Hosting, feel free to post your comments on the commenting area of this post.
Requirements
Before you start of with this instruction, make sure you already have or done the following:
- VPS Hosting Account (like these: 1, 2, 3)
- A Registered Domain Name from NameCheap.com or Register.com (Optional)
- Created an SSH Key Pairs
- Terminal App, if on Linux or Mac
- Putty, if on Windows
- Any text editor of your choice (Gedit, Notepad++, SublimeText 3)
- A working Internet Connection
Setup & Configuration
Here’s now the interesting part, the set up guide and configuration.
With this guide, I’ll be using this VPS provider since I have a current subscription from their service. You could use any Cloud VPS Provider you want, the process is just similar anyways.
Create A New VPS
- Step 1: Login to your VPS Control Panel or Web GUI.
Step 2: Create a new VPS (or Droplet).
Click on the
Create Droplet
button and enter a name for your VPS Host Name. I suggest that you enter the name in this format:name.your-domain-name.com
or
myvps.chubbable.com
Select Size of your VPS – You may choose from different combos like how many virtual CPUs, SSD Disk, and bandwidth allowance.
Reference Image:
Select Region – scroll down a bit and choose the location of your server that should be hosted at. I suggest that you choose the closest region or country to your target audience. If you want to target UK audiences or user, then choose UK server.
Reference Image:
Select Image – Select the Linux Distro that should be use with your VPS. The Create Droplet wizard will install the software for you.
Add SSH Keys – You really should use an SSH connection with your VPS for a more secure connection. It lets you connect to your server securely without entering a password.
Copy the contents of your ssh key (i.e. chubbable.pub) and paste it in the text area, name your key and click Add SSH button.
To learn how to create your SSH keys in Windows, watch this YouTube video.
Create Droplet – if everything is according to your liking, click on Create Droplet button to initiate the build.
Sucess!!! – After a successful a VPS creation, you should see a page like this one.
Reference Image:
Create A New User
You need to create a new user account with SUDO
privileges, it’s a user that belong to sudo
group or sudoers.
You need to have this type of user account, so you could administer your server.
sudo stands for super do. It’s a program built-in to Unix-like operating system, which gives privileges to a user to make any changes to the system.
Step 1: Connect to your Server.
In this step, you need to login to your newly build virtual private server, using SSH connection.
Fire-up your Terminal app if you’re on Linux or Mac, PuTTy if you’re on Windows-based machine.
SSH your way in, by typing this in the command line:
ssh [email protected]
Once logged in, your command line environment will change. It should look similar like this one:
root@myvps:~#
Note: Your VPS IP address can be found on your web-based control panel.
Reference Image:
The
#
character in your command line tells you that the login nameroot
is asuper user
, which means you have all the privileges to make changes to your system without being ask for a password. This is dangerous when it comes to public facing servers, because if the server got compromised and someone had break in to your server and got logged in asroot
user, then s/he could do whatever s/he desires to the system.So you need to have another user account and disable the
root
user login as a precautionary measure in case someone has broken in to your server.If in case someone broke in, s/he still needs to know what’s your sudo user password is, before s/he could do any changes to your system.
Let’s do the necessary configurations to set the basic SSH security for your VPS.
See Step 2 below.
Step 2: Create the new admin user account.
Make the user account so you don’t have to use the
root
account when you need to do some changes.Ok let’s do this, type this in your command-line:
adduser you-desired-username
Example:
adduser chubbable
Press
Enter
key and then you should see outputs similar with this one:Adding user `chubbable' ... Adding new group `chubbable' (1004) ... Adding new user `chubbable' (1004) with group `chubbable' ... Creating home directory `/home/chubbable' ... Copying files from `/etc/skel' ... Enter new UNIX password:
Now enter your desired password then hit
Enter
key.Note: When you type in your password, it will not show on your screen.
Next, enter other details for your user account. Just follow what the prompt says.
Step 3: Add the user name to the sudoer group.
Go back to your command-line enter the following:
usermod -aG sudo chubbable
Substitue
chubbable
with your own username.The command
usermod -aG
adds the user namechubbable
to thesudo
group, that makes userchubabble
a sudoer, a user that can make changes to the system, provided s/he enters his/her password and execute every command withsudo
prefix.Step 4: Copy the
authorized_keys
file.Note: Your
home
folder path is located at;/home/your-user-name
, While root’s home folder is located at/root
.In addition to that, when logged-in and you see this in your command prompt, this indicates that you are currently at your
home
folder path:`youruser-name@vps-host-name:~$`
The
~
character means that, you’re currently at yourhome
folder. Prior of moving the file, you need to create the.ssh
folder/directory first.authorized_keys
file is currently located in your VPS at:/root/.ssh/authorized_keys
You have to move it inside your server’s home folder, specifically inside:
/home/your-user-name/.ssh/
So it would look like this:
/home/your-user-name/.ssh/authorized_keys
You need to create the
.ssh
directory, prior to moving theauthorized_keys
file.To do that, type in:
mkdir ~/.ssh/
Note: mkdir in Unix-like OS means make directory or create directory/folder.
Then type in the following command:
sudo mv /root/.ssh/authorized_keys ~/.ssh/
mv command executes to move the
authorized_keys
file to your designated path.Note: In Unix-like OS, any file or folder name that begins with
.
ordot
, is a hidden file/folder.Set ownership for the
authorized_keys
file, since it is currently owned byroot
user. To do this, type the following and pressEnter
key.sudo chown your-username:your-username ~/.ssh/authorized_keys
Change folder permission for the folder and file accordingly:
chmod 700 ~/.ssh/ && chmod 600 ~/.ssh/authorized_keys
And… done! Proceed to next step below.
Step 5: Test your SSH connection.
Now that you have a sudoer user account, it’s time to use it and logout from the
root
user account and at the same time logout from your server.To do just that, type in
exit
and hitEnter
key in your command-line.Now, you should be back to your local command-line.
Log back to your server using your new user account.
Follow the instruction below.
To log back in to your VPS, go back to your command-line and type:
ssh your-new-username@your-vps-ipaddress
If you got in, then congratulations! You followed the instruction correctly and you had set a password-less SSH authentication.
Now continue setting up your basic SSH security and follow the steps below.
Set Basic SSH Security
Let’s do the following procedures for basic SSH Hardening .
Step 1: Disable
root
user login from SSHD config.To do that, log back to your server using SSH.
But this time, instead of typing
ssh root@your-vps-ipaddress
…You should type in…
ssh [email protected]
Example:
ssh [email protected]
After logging in successfully edit this file:
/etc/ssh/sshd_config
Type this in your command-line:
sudo nano -c /etc/ssh/sshd_config
Note: nano is a command-line text editor program for Unix-like operating system. i.e; Ubuntu, Debian and Linux Mint.
Scroll down around line
line 28
.You should see this config:
PermitRootLogin without-password
You need to change the
without-password
value tono
.Setting it to
no
prohibits it to login to the system.So what is PermitRootLogin without-password means? The
without-password
config lets theroot
account to login without a password, just like what it did when you logged in to your VPS for the first time.After editing the file, save the changes you did by typing…
ctrl + o + enter
o
is lettero
– as in omega, not zero.Then press
ctrl + x
to exit from the nano text editor.Now you have to restart the SSH Daemon to load the changes to the system.
To do that, type this in your command-line:
sudo service ssh restart
Note: Restart command stops and start the SSH Daemon regardless of whether it is already running or not.
Step 3: Continue editing the
/etc/ssh/sshd_config
file and set other SSH security configs.Type this in your command-line:
sudo nano -c /etc/ssh/sshd_config
Then scroll down around
line 52
and change this:#PasswordAuthentication yes
To:
PasswordAuthentication no
This disables clear text password authentication when logging-in to your server using SSH. After setting this up, you can only get in to your server using your SSH Keys.
Other configs you need to change, it should reflect the following configuration:
X11Forwarding no UsePAM no UseDNS no AllowUsers your-user-name
Then save the changes.
You probably know by now how to save a file opened by nano text editor. I mentioned in above. Step 1 of Set Basic SSH Security.
TCP Wrapper Configuration
For additional SSH security, set this up so SSH Daemon should only listen and allow connection from a range of IP addresses or specific IP address.
Basically, what TCP wrapper does is, it determines if a client machine is permitted to connect to a service. In our case, the service
is the SSH Daemon.
It gets its reference from two files, commonly referred to as hosts access files.
These files are; hosts.allow
and hosts.deny
and located at:
- hosts.deny –
/etc/hosts.deny
- hosts.allow –
/etc/hosts.allow
Setting TCP Wrappers up on Ubuntu:
To configure TCP Wrapper, you need to edit the files. So you need to launch nano` text editor in your ubuntu server command-line and start editing the two files.
Step 1 – Edit
hosts.allow
file first.Type in:
sudo nano /etc/hosts.allow
You should see similar output like this:
# /etc/hosts.allow: list of hosts that are allowed to access the system. # See the manual pages hosts_access(5) and hosts_options(5). # # Example: ALL: LOCAL @some_netgroup # ALL: .foobar.edu EXCEPT terminalserver.foobar.edu # # If you're going to protect the portmapper use the name "rpcbind" for the # daemon name. See rpcbind(8) and rpc.mountd(8) for further information. #
Now, enter the necessary configuration to add security to your SSH server.
Enter the configs like so:
sshd: 123.456. sshd: 124.456. sshd: 125.456. sshd: 126.456.
Explanation:
Notice that I entered 4 entries with the same service name
sshd
but different IP address pattern (IPv4 addresses).What this mean is, you’re allowing connection to the
sshd
service from any client with an IP address range of123.456.xxx.xxx
. Any host or client machine that matches this IP address range shall be allowed to connect. That is the same with124.456.
and also with the rest.So if you have an Internet Connection with dynamic IP addresses, you need to know all the IP address range used by your ISP. In my case, I did a Google search to find all IP address pool used by my ISP and entered it in my
hosts.allow
file.If you have a Static Public IP Address, then you should enter that entry like so:
sshd: xxx.xxx.xxx.xxx
I learned and studied about TCP Wrapper from this page
Step 2 – Edit
hosts.deny
file.Type in:
sudo nano /etc/hosts.deny
And create a new entry like so:
sshd: ALL
Then save and exit the editor.
And that was it! You’ve configured TCP Wrappers on your Ubuntu VPS.
You don’t need to reload or restart anything. It takes effect after saving the file.
Note: If in case you messed up and cannot login to your server. You may use your hosting control panel by logging in to your Web GUI and access the
Web Console
menu. You can access your VPs from thereon, by logging in using your username and password.
Setup Basic Firewall
It is necessary to setup right away, a basic firewall for your VPS. With this guide, we’ll use UFW or Uncomplicated Fire Wall, which is shipped with Ubuntu Server 14.04. It’s actually a front-end app for IP Tables.
UFW is the noob-friendly way of configuring a firewall for your virtual private server.
Here are the simple steps to configure it.
Procedure:
- Step 1 – SSH into your VPS.
Step 2 – Enable
UFW
using command-line.sudo ufw enable
Step 3 – Set firewall rule.
Port 22 Firewall Rule:
sudo ufw allow from any to port 22
Port 80 Firewall Rule:
sudo ufw allow from any to port 80
Port 443 (https) Firewall Rule:
sudo ufw allow from any to port 443
And that’s it!
But if you wanted to configure yourself, a more complicated firewall rules, I suggest you use IP TAbles.
Install Fail2ban
Perhaps you would ask What the hell is Fail2ban?
Ugh… Well, to the best of my knowledge, Fail2ban is a software that rejects IP addresses of a host for a specified period of time, it creates a firewall rule to ban a spceciic IP address due to failed attempt to make a brute-force entry to certain services.
It reads the log files and search for failed entry attempts from a hosts IP Address and then bans than IP address by creating a firewall rule that drops the connection.
This is very helpful in protecting your SSHD port from being brute-forced. As all *nix users know, that Port 22
is the default port for SSH server.
Note: You could actually change your SSHD listening port to a non-standard port. Port numbers higher than 1024.
Installing Fail2ban is easy, so let’s start of with the first step below.
Procedures:
Step 1 – Update the system’s local package index before installing it.
Type in the following command. It should install postfix and fail2ban in one command:
sudo apt-get update && sudo apt-get install fail2ban postfix
See that? Not that hard right?
Note: You need Postfix to send email to your desired email address.
Step 2 – Configure Fail2ban with your SSH service settings.
Fail2ban stores its configuration files in the following path:
/etc/fail2ban/jail.conf
That file contains the default configuration. You shouldn’t touch that ile. You need to copy and name it to
jail.local
. see reference image below.To copy the file and rename it at the same time, do this:
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
Once copied, open the file for editing. Type the following and press Enter key:
sudo nano /etc/fail2ban/jail.local
Fail2ban Configuration
The following should be configured, for a basic Ubuntu VPS.
Edit
/etc/fail2ban/jail.local
and configure the following:- ignoreip
- bantime
- findtime
- maxretry
- destemail
- sendername
- banaction
- mta
- action
- [ssh] section
Fail2ban Sample Configurations
Under
[DEFAULT]
Section:[DEFAULT] ignoreip = 127.0.0.1/8 bantime = 600 findtime = 600 maxretry = 3 backend = auto usedns = warn
Under
action
:change from:
action = %(action_)s
to:
action = %(action_mwl)s
Under
[SSH]
Section:enabled = true port = ssh bantime = 8600 filter = sshd logpath = /var/log/auth.log maxretry = 3
Note: I’ve overridden the default
bantime
of600
seconds to8600
seconds or 24hours. This setting is only applied toSSH
. You can change it to a shorter period like 60 seconds if you want to make some tests.Save your changes and exit the editor. Then restart
Fail2ban
service by typing the following:sudo service fail2ban restart
Fail2ban Parameters: Brief Explanation
These are the most important parameters to setup Fail2ban to secure your server. In this guide, we’ll only tackle protecting your SSH server.
The configs that you see under
[DEFAULT]
section shall be applied to all services enabled for Fail2ban. Except those configs that are service-specific, which means[DEFAULT]
settings shall apply unless they are overridden in in a specific service name (sshd
).1. Ignore IP – First config you should see under the
[DEFAULT]
section isignoreip
. You could skip this for now and leave the default value. What this parameter does is, NOT to ban a host or client machine that matches the IP address specified.If you have a Static Public IP Address, then just enter it here. But this is a bit trickier to setup if you’re on a Dynamic Public IP Address, especially if your ISP uses several IP Address Pools.
2. Ban Time – The
bantime
parameter sets how long that a client will be banned when they have failed to authenticate correctly. This is measured in seconds. By default, this is set to 600 seconds, or 10 minutes.3. Find Time & Max Retry – These two parameters works in tandem.
maxretry parameter sets the number of attempt a host or client machine has to authenticate within a time period (defined by findtime), before being banned.
What this means is… from the first time a client fails to authenticate, s/he still has 2 more attempt to authenticate within 10 minutes or 600 seconds. Countdown starts from the very first authentication failure.
4. DesteMail / SenderName / MTA – These parameters are for email alerts. If you wish to receive emails whenever Fail2ban bans someone, then you should configure these.
destemail
parameter sets the email address that should receive email alerts, if banning incidents happens . Thesendername
is the name that should appear in From field of an email. Themta
parameter configures what mail software to use to send email. It’s eithersendmail
ormail
.5. Action – This parameter configures fail2ban and tells what
action
it should take when it needs to make a ban.The value
action_
within theaction = %(action_)s
config is actually defined inside thejail.conf
file. Notice the lines after# Action shortcuts.
action_ =
action_mw =
action_mwl =
The default action is to simply ban the offending host, which is
action_
.6. [SSH] section.
You need to enable this parameter to configure it with Fail2ban. The deault value is disabled, so change it to
enable
to turn it on.max retry – You could set this to lower number if you want, let’s say
3
tries.Leave the other sections for now (i.e. apache, dropbear, nginx-http-auth). Since we only need to setup a basic VPS for now.
Fail2ban Testing
I know you’d ask How will I know If Fail2ban is working?
So I’ve included the following information so you could know if Fail2ban is working or not. Take note that in this guide, we only configured Fail2ban with SSH access.
So this is what you should do if Fail2ban is working with your SSH access.
Procedure:
Step 1 – Edit
/etc/fail2ban/jail.local
.Go to
destemail
and set it like so:destemail = root@localhost, [email protected]
Of course you need to enter your real email address instead of:
[email protected]
Next, go to
action =
and edit the line to reflect like the following:action = %(action_mwl)s
Next, go to
[SSH]
section and set parameter value like so:enabled = true port = ssh bantime = 60 filter = sshd logpath = /var/log/auth.log maxretry = 2
Save the file and exit the editor, then restart
Fail2ban
:sudo service fail2ban restart
Step 2 – Exit from your SSH session.
Login again using SSH, and this time you need to use a false user information.
You could do so like entering the following:
ssh wrong-username@your-vps-ipaddress
You should get a connection error for using the working login credential.
You should see error like this one:
Permission denied (publickey).
Note that you only have 2 maxretries, you should get banned for he 2nd unsuccessul login.
For the third login retry, you should see error like this one:
ssh: connect to host xxx.xxx.xxx.xxx port 22: Connection refused
That indicates that your host’s IP address has been already banned from accessing SSH.
You should now receive an email coming from your VPS, with the following email subject:
[Fail2Ban] ssh: banned xxx.xxx.xxx.xxxx from hostname.domain.tld
Reference Image:
If you receive the email, then you successfully configured Fail2ban with your SSH server.
Another method to know if Fail2ban is working is by checking the log file. Login to your VPS and check
fail2ban.log
file.You can check that out by entering this command:
sudo cat /var/log/fail2ban.log
You should see similar outputs like these:
fail2ban.jail : INFO Jail 'ssh' started fail2ban.actions: WARNING [ssh] Ban xxx.xxx.xxx.xxx The IP xxx.xxx.xxx.xxx has just been banned by Fail2Ban after 2 attempts against ssh.\n\n Here are more information about 1xxx.xxx.xxx.xxx:\n /usr/bin/whois 112.198.64.70 \n\n Lines containing IP:xxx.xxx.xxx.xxx in /var/log/auth.log\n `grep '\<xxx.xxx.xxx.xxx\>' /var/log/auth.log`\n\n Regards,\n
Reference Image:
And that’s it! That answers your question “How to know if Fail2ban is working?”
Pointing Your Domain Name To Your VPS
Now I’ve got myself a new VPS, but… How am I supposed to direct my domain name to my VPS?
For a VPS-noob like me, I’ve asked the same question before. And the answer to that question is to configure your DNS settings from your Domain Name Registrars’s Control Panel and Nameservers from your VPS host’s Control Panel.
So how do we point a domain name to a Virtual Private Server?
Follow the general steps below, it would generally work for most Domain Name Registrars and VPS Hosts.
Procedure:
- Step 1 – Login to your Domain Name Registrar’s control panel.
Step 2 – Find your DNS settings menu.
Modify the settings that has something to do with name servers. Find for labels like NS1 or DNS1.
You should modify 3 fields; ns1 or dns1, ns2 or dns2 and ns3 or dns3
Step 3 – Get Name Server information from your VPS Host.
If you’re on a VPS Host like this one, you can get the info from this link.
Step 4 – Enter the NameServer details in your control panel (Domain Registrar’s side), and save your changes.
Step 5 – Login to your VPS Host account.
Go to your DNS settings menu and create the following record types:
A Record – You need to create 2 records of this type.
A Record 1 – Enter your VPS name and it’s IP address. A Record 2 – Enter character
@
and your VPS IP address.CNAME Record
Enter
*
for the name andmysite.dev.
for the hostname.NS Record – Enter your VPS host’s name servers.
Example:
ns1.vpshost.com. ns2.vpshost.com. ns3.vpshost.com.
Note: Make sure you include those trailing dots (
.
).Step 6 – Save your settings.
Wait for a few minutes before trying to access your domain name (if your already have a webserver up and running). It may take some time for the new settings to propagate.
To test your settings without a web-server yet, search for DNS checker tools on the Internet or use an online tool like this one.
It’s a Wrap
If you followed this guide carefully, then you should now have a VPS. But if it’s not the case, feel free to ask for help by posting your comments below.
In case you’re an expert on this topic, and stumpled upon this post, I encourage you to post some tips and talk about your experiences virtual server provisioning and set-up.
If you have questions, sugestions, and clarifications, please post them in the comment section below. I will try my best to read and answer them.
I hope this post answered your question “How To Setup My Own VPS Using Ubuntu Server 14.04?”