Basic, Secure, Remote, & unmanaged Remote Server Setup

Ubuntu Logo

Ubuntu Logo

Introduction

Setting up an unmanaged instance of Ubuntu Linux is not difficult.  You just need to know what to do.  A bit rhetorical, but that’s the truth of the matter.  If you search or Google for solutions, you’ll find multiple tutorials describing the process.  You have to be careful though, some authors leave out key steps (not sure why).  Also, you have to ensure that you are following the correct version.  Following the tutorial  for alternate software versions is a recipe for disaster and a doorway to countless hours spent debugging non-existent problems.  In this tutorial, we provide a complete guide to set up an unmanaged Ubuntu Linux.  Version 16.04.

Deployment

If you have your server hardware in house, you have less to worry about.  If you lock yourself out, you have console access.  If you have leased or rented a Linux distro from Linode or similar service, you’ll need to be a bit more careful.  Locking yourself out of a remote instance with no physical access, can be more difficult to deal with.  Some providers provide console access remotely, an excellent feature.  If you find yourself locked out remotely for any reason, be sure to check if the provider has remote console access.  I know Joe’s Datacenter provides this capability, I’m certain others do as well.  Below, we walk through each step and provide detailed information on each step and what to do in the event something goes wrong.

SSH Connection

This tutorial assumes that Ubuntu has been set up and exists on a network ready to accept SSH connections.  This network can be the internet or a local area network.  If you purchased a Ubuntu instance from a provider, they will give you the SSH username/password and IP address.  If you have installed Ubuntu on a LAN, you will need to know the local IP address.  Once you have the IP address, username, and password.  You are ready to connect to your server.

Connection Software: Putty

You are free to use any SSH/Telnet client available.  For this tutorial, Putty will be our choice, download it here.  Once you have installed the client, follow the below instuctions which reference the provided screenshot.  The numbers reflect the arrows in the screenshot.

  1.   Your IP Address goes here
  2. The port number.  The default is 22, we will change this later to help mitigate lazy attacks.
  3. SSH is the protocol we will use.  It encrypts traffic using a self signed certificate initially.
  4. Provide a name for your session.  Anything you want
  5. Click save so that you can load the settings later.  Easy to forget.

putty

Putty Categories

You will notice that Putty has a ton of categorial screens for various customization options.  We do not need to worry about these at all,  we only need to worry about the session screen. We do not need to alter any settings elsewhere.

Unable to connect?

Make sure that port 22 is open.  Network administrators or ISP’s could disable them.  If they are disabled, you will not be able to connect.  Also, check that you have entered the connection criteria correctly.

Login

Once you have established a connection you will move through the following phases.

  • Enter Connection settings or load previously saved settings
  • Click yes on the security prompt
  • Login with username and password
  • congratulations, you should be logged into the server.

Security Alert (Perfectly fine, select yes)

Putty Security Alert

Login Prompt (Enter your username and password )

Login Prompt

Logged In (Your login may or may not mention updates)

logged in screenshot

Are you getting the error below?  Putty login should be easy, however,  There are two primary reasons this could occur.

  • Incorrect settings.  Ensure you have the correct IP address and port number.
  • Blocked Port.  Network administrators or ISP’s could block the required port.
    • Check with your network administrator or your ISP website. example.
  • If you are at the login prompt, but login is failing, you are not entering the correct username/password.
Putty Error

Sudo User: root

Congratulations on successfully logging in.  Now, firstly, we will check for updates.  However, you must have sudo(admin rights) to accomplish this.  If your provider gave you the username “root”, they have provided you the super account by default and you will be able to just run commands.  We will change this later, however, it is best practice to avoid using the root account by default.  If you are not the root user,  there are two approaches.  First, you can enter “sudo” before every command.  The server will prompt you for the password, this is a temporary elevation to the root level just for the command.

kparker@ubuntu-Server-Demo:~$ sudo apt-get udpate
[sudo] password for kparker:

Secondly, not recommended, but fine if you are comfortable.  You can use sudo -s to enter a root level session.  This will allow you to run commands as the root user so that you do not need to enter sudo before every command. There are other ways to accomplish this, but for now, we are starting with the simplest method.

kparker@ubuntu-Server-Demo:~$ sudo -s
[sudo] password for kparker:
root@ubuntu-Server-Demo:~#

 

Update Often

The first thing to do is run updates.  You will need to run “apt-get update” and apt-get upgrade using the sudo method of choice.  The below example uses the “sudo -s method”  Either command may prompt you to confirm update installation with a “Y/N” prompt, be sure to hit “Y”. You will likely see a large amount of scrolling text, some text may even read “warning”, a normal occurrence during updates.

root@ubuntu-Server-Demo:~# apt-get update
Hit:1 http://us.archive.ubuntu.com/ubuntu xenial InRelease
Get:2 http://us.archive.ubuntu.com/ubuntu xenial-updates InRelease [102 kB]
Get:3 http://security.ubuntu.com/ubuntu xenial-security InRelease [102 kB]
Get:4 http://us.archive.ubuntu.com/ubuntu xenial-backports InRelease [102 kB]
Fetched 306 kB in 0s (528 kB/s)
Reading package lists… Done
root@ubuntu-Server-Demo:~#
root@ubuntu-Server-Demo:~# apt-get upgrade
Reading package lists… Done
Building dependency tree
Reading state information… Done
Calculating upgrade… Done
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
root@ubuntu-Server-Demo:~#

UFW vs. IP Tables

If you are new, you want to implement network security using the UFW application.  Its simple and accomplishes the same task with a fraction of the difficulty.  If you are an expert or have a deep interest, go ahead and implement your own rules using IP Tables.  IP Tables are complex and warrant their own chapter/tutorial.  UFW is easy and will reach a acceptable level of security by any standard, in fact, many experts prefer standard software solutions.  It is  more likely an individual, even an expert, accidentally left a hole in the firewall.  If you are using a standard solution, I know that is much less likely to have occurred.  This tutorial will be using the UFW application to enforce standard network security principles.

UFW Setup

First, before enabling UFW, ensure that your SSH port is open.  This is 22 by default. run the command “ufw allow 22”

root@ubuntu-Server-Demo:~# ufw allow 22
Rules updated
Rules updated (v6)

Then, check results with “ufw show added”.  This command shows the rules even while the application is disabled.  This will help you avoid locking yourself out.  UFW blocks all ports by default, thus, if you enable with no implemented rules, you will lose remote access to your system.

root@ubuntu-Server-Demo:~# ufw show added
Added user rules (see ‘ufw status’ for running firewall):
ufw allow 22

Once you have confirmed the correct port is added, enable ufw with the “ufw enable” command.  This command will also cause UFW to configure with auto-start.  UFW will be enabled automatically on system restarts.

root@ubuntu-Server-Demo:~# ufw enable
Command may disrupt existing ssh connections. Proceed with operation (y|n)? y
Firewall is active and enabled on system startup

Now check that UFW is working correctly and that the expected port rules exist.  The command is “UFW status”

root@ubuntu-Server-Demo:~# ufw status
Status: active
To Action From
--- ------ ----
22 ALLOW Anywhere
22 (v6) ALLOW Anywhere (v6)
root@ubuntu-Server-Demo:~#

Now, before you do anything else, check and ensure that your server is still accepting connections.  Open Putt again, while your current session is open and attempt to start a new session.  If you are unable to, disable the UFW application with the “ufw disable” command.  Then try again, if the connection works, your UFW settings are incorrect.  Verify UFW settings with the previously mentioned commands and try again.

root@ubuntu-Server-Demo:~# ufw disable
Firewall stopped and disabled on system startup
root@ubuntu-Server-Demo:~#

Disable Remote Root Connections

Create a new User

If the provider gave you the username “root”, we need to disable its use for remote access.  The Root username is half the key, if you have a custom username, that is two pieces of information needed for system access.  First, create a new user with the command ” adduser username

root@ubuntu-Server-Demo:~# adduser testuser
Adding user `testuser’ …
Adding new group `testuser’ (1001) …
Adding new user `testuser’ (1001) with group `testuser’ …
Creating home directory `/home/testuser’ …
Copying files from `/etc/skel’ …
Enter new UNIX password:
Retype new UNIX password:
passwd: password updated successfully
Changing the user information for testuser
Enter the new value, or press ENTER for the default
Full Name []: test user
Room Number []: 999
Work Phone []: 123-456-7890
Home Phone []: 123-456-7890
Other []: kewl guy
Is the information correct? [Y/n] y

Add the User to the SUDO group

Now we need to add the new user to the SUDO group so that it can run commands at the administrator level.  Complete this action by running the following command.  “usermod -aG sudo username

root@ubuntu-Server-Demo:~# usermod -aG sudo testuser

Test the User

Run the command “su – username“.  This command switches to the new user account, a test drive in this case.  Once switched to the new account, run a test command.  “sudo ls -la /root”,  In this example we list the contents of the “root” directory, this requires root level access to accomplish.  If the command is successful, congratulations, you now have a new user capable of root level permissions.  Also, open a new Putty session and connect as the new user to confirm remote connectivity.

testuser@ubuntu-Server-Demo:~$ root@ubuntu-Server-Demo:~# su -- testuser
See “man sudo_root” for details.
testuser@ubuntu-Server-Demo:~$ sudo ls -la /root
[sudo] password for testuser:
total 16
drwx------ 2 root root 4096 Nov 27 14:43 .
drwxr-xr-x 23 root root 4096 Nov 28 06:56 ..
-rw-r--r-- 1 root root 3106 Oct 22 2015 .bashrc
-rw-r--r-- 1 root root 148 Aug 17 2015 .profile
testuser@ubuntu-Server-Demo:~$
Update Gear

Root Session

Entering a root session is often frowned upon by experts.  However, right now, focus on getting the server up and secured.

 

 

apt-get update

updates the list of available packages and their versions, but it does not install or upgrade any packages.

apt-get upgrade

Installs newer versions of packages available on running system. After updating the lists, the package manager knows about available updates for installed software.    You will want to run apt-get update followed by apt-get upgrade.

 

 

 

 

 

 

 

Uncomplicated Firewall (UFW)

The Uncomplicated Firewall (ufw) is a frontend for iptables and is particularly well-suited for host-based firewalls.  Key point here, using UWF uses iptables to accomplish its goal.  Trick question, why did you use UFW instead of iptables?

IPTables

Iptables is used to set up, maintain, and inspect the tables of IP packet filter rules in the Linux kernel. Several different tables may be defined. Each table contains a number of built-in chains and may also contain user-defined chains.

Port Open for Docking!

Make sure to add your SSH port prior to enabling UFW.  Failure to open a access port will result in your computer blocking all remote access attempts, thus, a lock out.  You will need console access to remedy.

UFW: Opening Ports

You can open ports between 0 to 65535, however, some programs use certain ports by default and you should avoid the use of such numbers with custom software or setups.  For example, avoid using port 25 for SSH, this port is used for SMTP email service.  Using the same port for multiple services can cause a lot of unnecessary heartache, a quick google search will let you know if the port number you are interested in is for use with another service.

 

 

 

 

 

 

 

 

 

 

Usernames

When adding a user, feel free to choose any name you like.  When dealing with a large userbase, you will want to use a naming scheme such as {lastname}{first initial}{index}.  Also, feel free to leave any of the questions blank, they are optional.  Just make sure to choose a strong password, especially if your server is on the internet.

Weak Password

Weak passwords are a serious vulnerability on the internet.  Most often, people imagine a hooded figure manually attempting to guess passwords.  The, reality is,  a rogue program will discover your servers door and will begin to automatically cycle through passwords.  Programs can do this quickly, 1000 attempts a second is reasonable for even a slow computer.  If the program is successful, server details will be exposed and sent back to the programmer who will then decide what he wants to do.

 

 

Sudo

Sudo stands for either “substitute user do” or “super user do”.  When you add a user to the sudo group, the username is added to a configuration file permitting root level privileges.  If the user is not added to the group, the user will be unable to complete any action that requires enhanced privileges.

Disable Root SSH access/Change Port Number

To disable root and change the port number, we need to access the SSH settings file.  This is located at  “/etc/ssh/sshd_config”.  Access the file using the “nano” text editor program.  This program is simple to use, if you are new, avoid the VI/Vim editor.  Access the file using the following command.  “/etc/ssh/sshd_config”.  If you are not in a root session, be sure to append sudo to the beginning, otherwise, you wont be able to save the settings.

root@ubuntu-Server-Demo:~# nano /etc/ssh/sshd_config
`# Package generated configuration file
`# See the sshd_config(5) manpage for details
`# What ports, IPs and protocols we listen for
Port 22
`# Use these options to restrict which interfaces/protocols sshd will bind to
`#ListenAddress ::
`#ListenAddress 0.0.0.0
Protocol 2
`# HostKeys for protocol version 2
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_dsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key
`#Privilege Separation is turned on for security
UsePrivilegeSeparation yes
`# Lifetime and size of ephemeral version 1 server key
KeyRegenerationInterval 3600
ServerKeyBits 1024
`# Logging
SyslogFacility AUTH
LogLevel INFO
`# Authentication:
LoginGraceTime 120
PermitRootLogin prohibit-password
StrictModes yes
RSAAuthentication yes
PubkeyAuthentication yes
`#AuthorizedKeysFile %h/.ssh/authorized_keys
`# Don’t read the user’s ~/.rhosts and ~/.shosts files
IgnoreRhosts yes
`# For this to work you will also need host keys in /etc/ssh_known_hosts
RhostsRSAAuthentication no
`# similar for protocol version 2
HostbasedAuthentication no
`#Uncomment if you don’t trust ~/.ssh/known_hosts for RhostsRSAAuthentication
[ Read 88 lines ]
^G Get Help ^O Write Out ^W Where Is ^K Cut Text ^J Justify ^C Cur Pos ^Y Prev Page
^X Exit ^R Read File ^\ Replace ^U Uncut Text ^T To Spell ^_ Go To Line ^V Next Page
`# Package generated configuration file
`# See the sshd_config(5) manpage for details
`# What ports, IPs and protocols we listen for
Port 54474
`# Use these options to restrict which interfaces/protocols sshd will bind to
`#ListenAddress ::
`#ListenAddress 0.0.0.0
Protocol 2
`# HostKeys for protocol version 2
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_dsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key
`#Privilege Separation is turned on for security
UsePrivilegeSeparation yes
`# Lifetime and size of ephemeral version 1 server key
KeyRegenerationInterval 3600
ServerKeyBits 1024
`# Logging
SyslogFacility AUTH
LogLevel INFO
`# Authentication:
LoginGraceTime 120
PermitRootLogin no
StrictModes yes
RSAAuthentication yes
PubkeyAuthentication yes
`#AuthorizedKeysFile %h/.ssh/authorized_keys
`# Don’t read the user’s ~/.rhosts and ~/.shosts files
IgnoreRhosts yes
`# For this to work you will also need host keys in /etc/ssh_known_hosts
RhostsRSAAuthentication no
`# similar for protocol version 2
HostbasedAuthentication no
`#Uncomment if you don’t trust ~/.ssh/known_hosts for RhostsRSAAuthentication
[ Read 88 lines ]
^G Get Help ^O Write Out ^W Where Is ^K Cut Text ^J Justify ^C Cur Pos ^Y Prev Page
^X Exit ^R Read File ^\ Replace ^U Uncut Text ^T To Spell ^_ Go To Line ^V Next Page
File Name to Write: /etc/ssh/sshd_config
^G Get Help M-D DOS Format M-A Append M-B Backup File
^C Cancel M-M Mac Format M-P Prepend ^T To Files
[ Wrote 88 lines ]
^G Get Help ^O Write Out ^W Where Is ^K Cut Text ^J Justify ^C Cur Pos ^Y Prev Page
^X Exit ^R Read File ^\ Replace ^U Uncut Text ^T To Spell ^_ Go To Line ^V Next Page
root@ubuntu-Server-Demo:~# ufw allow 54474
Rule added
Rule added (v6)
root@ubuntu-Server-Demo:~#
root@ubuntu-Server-Demo:~# ufw status
Status: active
To Action From
--- ------ ----
22 ALLOW Anywhere
54474 ALLOW Anywhere
22 (v6) ALLOW Anywhere (v6)
54474 (v6) ALLOW Anywhere (v6)
root@ubuntu-Server-Demo:~#
root@ubuntu-Server-Demo:~# service ssh reload
root@ubuntu-Server-Demo:~#

Now test your settings by opening another Putty Session.  You do not need to close you current running session, in fact I recommend leaving it running.  In some cases, you could put the wrong setting in place and your running session will give you an opportunity to fix it.

Putty Setting Updated

To change the port number, find the line with labeled “Port 22”.  In this example, we will change the port to 54474.  Feel free to use a different number if desired, just make sure its not a port commonly used for other services.  Next change the the line  “PermitRootLogin prohibit-password” to “PermitRootLogin no”  Once you have accomplished this, save the file and add the correct port number using the “UFW allow” command.  To perform nano commands, ^o  = “ctrl+o”.  Save is titled “Write Out”, run “Ctril+o” with the file open to save.

Add UFW port and reload SSH

Once you have saved the file, add the port number to the UFW rule list.  Once you have done that, reload the SSH service with the “service ssh reload” command.  Now connect to the new port number with a new Putty session.  If the connection is successful, deny port 22 with a “ufw deny 22” command.  Check the status again, you see that 22 is denied.  You do not need to worry that other ports are not shown, if its not mentioned, it is blocked.

Why Nano?

Don’t get me wrong here, Vi/VIM is an awesome editor with a huge number of capabilities that nano lacks.  However, VI has a steep learning curve and has been known to scare new people away.  VI is complicated enough to warrant its own tutorial, for this tutorial, we are keeping it simple with nano.

what’s with the ‘`’ character?

My plugin for displaying terminal output changed the “#” to a “$”, I prevented this with the “`” character.  Pay it no mind.

Careful Now

You will need to edit two lines, the first is the line with “PermitRootLogin ” and the second is the Port number.  If you make a mistake here, such as not entering a port number or forgetting the number, you could lock yourself out.

UFW Port

Make sure to open the port number you chose.  If you restart the SSH service and forgot to establish the UFW port rule, you will lose system access.  Again, you’ll need console access to remedy.

Nano Commands

the “^” character represents “ctrl” by default in Putty.  To save the file after making changes, press “ctrl+o” and select “y” when Prompted.  Also “ctrl+w” allows you to search for text in large documents.  If you did not open the file with root privileges, you will not be able to save the file.

Why Change the port?

Security through obscurity.  By changing the port number, any rogue programs will need to scan for available ports and attempt to find the service.  This can still be done, but its discouraging, if someone has changed the port number, they probably have other security in place too.  Better to find a new target.  Of course, if you are running a Wells Fargo server, the attacker might hang around and really dig for vulnerabilities. In any case, you want to keep a standard level of security in place when out on the internet.

Improved Security

Authorized keys

Security is an important concept, it is central to the protection of your information and any consumers you serve.  Take the login security a step further, disable password login and enforce token login only.  This creates an even more difficult scenario for hackers to overcome if they take a particular interest in your server.   First, generate a key pair with the command “ssh-keygen -t ecdsa”.

You may put the key in any directory.  However, make sure you generate the key as the target user and not root.  Permission errors can cause the process to fail.  Make sure that if you create new directories, that these are created with the target users permission as well.  This is easily accomplished in the users home directory at /home/$username/

testuser@ubuntu-Server-Demo:~$ ssh-keygen -t ecdsa
Generating public/private ecdsa key pair.
Enter file in which to save the key (/home/testuser/.ssh/id_ecdsa): /home/testuser/id_ecdsa
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/testuser/id_ecdsa.
Your public key has been saved in /home/testuser/id_ecdsa.pub.
The key fingerprint is:
SHA256:kmx1cPUB+afEx9gu33sbQCmrqjsXIIR/y4SpPxrc3jU testuser@ubuntu-Server-Demo
The key’s randomart image is:
+---[ECDSA 256]---+
|         . . ..oo. |
|        . . o …. |
|      o o . .. =.+ |
|      = = o . + = =|
|     . = B S . o = |
|      … + o . + .|
|         o.. E.. +.|
|          oo….o =|
|         ….+=. o+|
+----[SHA256]-----+

Now that you have generated the key, you must know inform the SSH application that this key is acceptable.  If you forget to do this, the key will not work.  Also, be sure to include the port number we changed earlier.

My command: “ssh-copy-id -p 54474 testuser@ubuntu-Server-Demo

testuser@ubuntu-Server-Demo:~/.ssh$ ssh-copy-id -p 54474 testuser@ubuntu-Server-Demo
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: “/home/testuser/.ssh/id_ecdsa. pub”
The authenticity of host ‘[ubuntu-server-demo]:54474 ([66.85.77.117]:54474)’ can’t be establ ished.
ED25519 key fingerprint is SHA256:PbFM8UXnLf31fm8f3XPE9V6H2E3MYtqOmPnhWTkEtxQ.
Are you sure you want to continue connecting (yes/no)? yes
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed --- if you are prompted now it is to install the new keys
testuser@ubuntu-server-demo’s password:
Number of key(s) added: 1
Now try logging into the machine, with: “ssh -p ‘54474’ ‘testuser@ubuntu-Server-Demo'”
and check to make sure that only the key(s) you wanted were added.
testuser@ubuntu-Server-Demo:~/.ssh$

To set this up with Putty and make the process easy, we need to install some additional tools.  We need to install putty tools on our server.  Furthermore, we will use the Puttygen program that installs with the Putty program.  You should not need to install anything extra to use it.

testuser@ubuntu-Server-Demo:~$ sudo apt install putty-tools

PuttyGen

Permissions

Permission problems will cause the most trouble for new users of Linux.  Be sure to check this with the “ls -l” command.  Also, many people save SSH keys in the “/home/username/.ssh/”.  If you do this, make sure you create this directory with the target user and not root.  When you log in, the SSH application will attempt to use the requested users permission, if it belongs to root, this will fail.

Port Number

Don’t forget you changed your port number.  Anytime an application performs some action, it will assume the default setting.  Many applications have a “switch” that allows you to provide the new port number.  If you forget to do this, the application probably wont tell you.  The application will likely inform you that the connection timed out.

This is a demo store for testing purposes — no orders shall be fulfilled. Dismiss

%d bloggers like this: