Initialize VPS UNPM Server

From UNPM.org Wiki
Jump to navigation Jump to search

Now that the server is booted and running, it is time to log in and initialize it for use as a web server. Although this guide assumes the user is using Windows, a user on any platform could use these steps to initialize the server. This article is written with no assumption of experience, though it is more likely that more experienced users will not need it or will only need parts of it. However, all articles in this wiki assume the server is configured as described in this article.

Create users and groups

The server will require at least one administrative user account that will be a member of several additional groups.

Log into the server

If using PuTTY, open PuTTY and enter the server's IPv4 address in the 'Host Name (or IP address)' field. Enter the name of the server in the 'Saved Sessions' field, click 'Save', then 'Open'. PuTTY should connect to the server and display a message stating that the public fingerprint for the RSA key of the server is not in its cache. This message should only appear when connecting to a newly built server (e.g. new or restored image, but same IP address or domain), a server it has never connected to, or connecting to a server in a new way, such as different subdomain or different port. If this message is displayed when no changes have been made to the server (such as rebuild or restore from image) and the fingerprint is expected to be stored in the cache, then the connection may not be trustworthy. PuTTY may not be connecting to the intended server and the user may be the target of a man-in-the-middle attack.

Select 'Yes' to continue. Log in as user root (as with nearly everything else in Linux, user names are case-sensitive), then paste in the password the VPS provider assigned by right-clicking anywhere in the PuTTY window. When entering passwords, Linux will not move the cursor, so press enter after right-clicking in PuTTY.

Ubuntu will list the system status, also available with the command landscape-sysinfo and may state that updates are available, which will be addressed in a later step.

Raise the firewall

The firewall is disabled on the default server install. Uncomplicated Firewall (UFW) is a reasonably secure tool for managing firewalls and comes installed with every version Ubuntu.

For the server's initial setup, it is best to enable a complete firewall. However, if the SSH session is interrupted before setup spteps below are completed, then it may not be possible to reestablish the connection. In the unlikely event that this happens, it will be necessary to log in through the provider's terminal to complete the remaining steps, or start all over again by reinstalling the server.

root@servername:~# ufw enable

Ubuntu will ask to verify that ufw is to be enabled because it may disrupt the existing SSH session. In the case of this server, enabling UFW will not disrupt the session, but it will not be possible to establish a new session until the ufw settings are changed in a later step.

Create new user and add to groups

It is very insecure to log in as root, so a new user should be created, then added to appropriate groups. The user may use any name desired, keeping in mind that the name is case-sensitive. It is also important to consider that the user's password is used to gain root access, and may be entered many times in a session, but will not be used for logging into the server via SSH.

The new user will need to be a member of several groups. The command used to create the user can also be used to add the user to a group.

root@servername:~# adduser username
root@servername:~# adduser username sudo
root@servername:~# adduser username adm

When using the adduser command to create a user, a home folder will be created for the user at /home/username/, a group will be created called username, and the user will be assigned to the group. The sudo group is only for users requiring root level permissions. The adm group is still used by some legacy applications.

Change login method

Logging in with passwords is very insecure as it is susceptible to brute force attacks. Logging in with key pairs effectively prevents this from ever being successful. As an additional measure, a non-default port will be enabled in the firewall to allow access to SSH while the default port is disabled, reducing log noise.

Add user public key

Adding a public key to a user's authorized_keys file allows the user to log in using that key. Create the .ssh directory in the user's home folder. Opening a file that does not exist with nano will also create the file:

root@servername:~# mkdir /home/username/.ssh/
root@servername:~# nano /home/username/.ssh/authorized_keys

In the authorized_keys file, paste in the device's public key from the OpenSSH Public Key file on the local device, then save the file (ctrl+o) and exit (ctrl+x). Additional device keys may be added to the authorized_keys file. Simply place each key on its own line to allow multiple devices to log in using the same user account.

The user will not be able to log in by key authentication if it is not the owner of the ~/.ssh/ directory and the authorized_keys file. It is also not necessary for any other user to access this user's home directory, so permissions can be set for this:

root@servername:~# chown -R username:username /home/username/
root@servername:~# chmod 750 /home/username/
root@servername:~# chmod 600 /home/username/.ssh/authorized_keys

Set up SSH

The config file for SSH should be edited to prevent the root user from logging in, prevent password login, allow only specified users to login, and tell SSH to use a non-standard port. Though it is first a good idea to make a backup of the original file.

The following commands will improve the quality of encryption:

root@servername:~# rm /etc/ssh/ssh_host_*key*
root@servername:~# ssh-keygen -t ed25519 -f /etc/ssh/ssh_host_ed25519_key -N "" < /dev/null
root@servername:~# ssh-keygen -t rsa -b 4096 -f /etc/ssh/ssh_host_rsa_key -N "" < /dev/null
root@servername:~# awk '$5 > 2000' /etc/ssh/moduli > "${HOME}/moduli"
root@servername:~# wc -l "${HOME}/moduli"
root@servername:~# mv "${HOME}/moduli" /etc/ssh/moduli
root@servername:~# mv /etc/ssh/sshd_config /etc/ssh/original.sshd_config
root@servername:~# nano /etc/ssh/sshd_config

Add:

# Package generated configuration file
# See the sshd_config(5) manpage for details

# What ports, IPs and protocols we listen for
Port randomunassignedportnumber
# Use these options to restrict which interfaces/protocols sshd will bind to
#ListenAddress ::
#ListenAddress 0.0.0.0
KexAlgorithms curve25519-sha256@libssh.org,diffie-hellman-group-exchange-sha256
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
 
# Logging
SyslogFacility AUTH
LogLevel INFO

# Authentication:
LoginGraceTime 120
PermitRootLogin no
StrictModes yes

Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com,aes256-ctr,aes192-ctr,aes128-ctr

MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-512,hmac-sha2-256,umac-128@openssh.com

PubkeyAuthentication yes
#AuthorizedKeysFile     %h/.ssh/authorized_keys

# Don't read the user's ~/.rhosts and ~/.shosts files
IgnoreRhosts yes
# similar for protocol version 2
HostbasedAuthentication no
# Uncomment if you don't trust ~/.ssh/known_hosts for RhostsRSAAuthentication
#IgnoreUserKnownHosts yes

# To enable empty passwords, change to yes (NOT RECOMMENDED)
PermitEmptyPasswords no

# Change to yes to enable challenge-response passwords (beware issues with
# some PAM modules and threads)
ChallengeResponseAuthentication no

# Change to no to disable tunnelled clear text passwords
PasswordAuthentication no

# Kerberos options
#KerberosAuthentication no
#KerberosGetAFSToken no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes

# GSSAPI options
#GSSAPIAuthentication no
#GSSAPICleanupCredentials yes

X11Forwarding yes
X11DisplayOffset 10
PrintMotd no
PrintLastLog yes
TCPKeepAlive yes
#UseLogin no

#MaxStartups 10:30:60
#Banner /etc/issue.net

# Allow client to pass locale environment variables
AcceptEnv LANG LC_*

Subsystem sftp /usr/lib/openssh/sftp-server

# Set this to 'yes' to enable PAM authentication, account processing,
# and session processing. If this is enabled, PAM authentication will
# be allowed through the ChallengeResponseAuthentication and
# PasswordAuthentication.  Depending on your PAM configuration,
# PAM authentication via ChallengeResponseAuthentication may bypass
# the setting of "PermitRootLogin yes
# If you just want the PAM account and session checks to run without
# PAM authentication, then enable this but set PasswordAuthentication
UsePAM yes

AllowUsers username

Generally, when using instructions such as this wiki, the text will be exactly what should be in the file, with obvious exceptions such as username, servername, example.com, and occasional unique, yet still fairly obvious variables such as randomeunassignedportnumber from the above example. Also of note, if the existing text in the file being edited is commented out, but the comment symbol isn't displayed in the change, then remove the comment tag (and associated closing tags, as with HTML and PHP, when present). However, if there appears a misspelling or incorrect punctuation, case, etc., it may be wise to do a quick web search and verify that the guide being used is correct as guides are generally human-generated.

To find an unassigned port number, the Wikipedia article containing the list is a bit easier to read than the official IANA list. Whatever port number is used, it will have to be used for all clients using SSH and related services, such as SFTP.

Restart the SSH service to implement the changes:

root@servername:~# service ssh restart

Configure the firewall for new SSH port

UFW can be used to allow specific ports, protocols, and installed applications. Here are some useful UFW command options and their outputs with the current configuration:

root@servername:~# ufw status
Status: active
root@servername:~# ufw app list
Available applications:
 OpenSSH

The OpenSSH application settings, though available, will not be used for this server setup because the server is using a non-standard SSH port. Allow the port entered into the sshd_config file:

root@servername:~# ufw limit randomunassignedportnumber/tcp

Using the limit rule reduces the impace of brute force attacks hitting the server.

Verify new SSH settings

In the following steps it is important to keep track of the PuTTY window that contains the initial root session, as additional SSH sessions are created and closed in new PuTTY windows, do not to accidentally close the root session.

Use PuTTY to create a new SSH session without closing the current one. A quick way to do this is to use the drop-down menu available in the top left corner of the PuTTY window. To test if a session can be created that is identical to the current session, click 'Duplicate Session'. This will open a new PuTTY session window which should time out as the firewall rules will not acknowledge anything on port 22.

Create a new session by clicking 'New Session...' from the drop-down menu. Select the saved session from the previous step, but change to the randomunassignedportnumber entered into sshd_config, and click 'Save' to save current settings to the 'Saved Session'. Click 'Open' and attempt to login as username. Note that PuTTY will find a new key fingerprint with the new port. The server should reject the login attempt and state that a public key is required for login.

Create another new session. Load the saved session, and in the menu in the left column, navigate to Connection -> SSH -> Auth. Under ‘Private key file for authentication’ click ‘Browse’ and select the private key associated with the public key on the server (note that the file used for PuTTY and most Windows applications is a .ppk file, which is a different format from an OpenSSH file - what Linux uses). Click ‘Session’ at the top of the left sidebar and save the settings, then 'Open'. Attempt to log in as root. The server should deny the attempt and close the session. 'Restart Session' using the drop-down menu and enter username. The server should accept the credentials and open a session with username.

username@servername:~$

Verify the new user is a member of the sudo group by creating a test file using the sudo command.

username@servername:~$ sudo touch test
[sudo] password for username:

Entering the password should create the new file test. Use the ll command to verify the new file is owned by root and then remove it using rm:

username@servername:~$ ll test
-rw-r--r--  1 root root     5 Aug 14 21:55 test
username@servername:~$ sudo rm test
If the server did not allow login

If the server did not allow the session to be created, first verify that the username is spelled correctly in PuTTY when logging in, then check that the path to /home/username/.ssh/authorized_keys is correctly spelled and has correct ownership and permissions (easily done using the ll command):

root@servername:~# ll /home/username/
root@servername:~# ll /home/username/.ssh/

Next verify that the public key has been entered without error into authorized_keys. Everything needs to be precisely as PuTTY created it, and it should all be on one line. Note that nano will indicate a line is longer than the screen can display by placing a $ at the end of the line. To review the contents of the line, it can be more convenient to press enter just before the $, and do this until all of the key is displayed on several lines. Do not save the file in this configuration, just use it to verify the key is completely entered and accurate.

If that all checks out, go back into /etc/ssh/sshd_config and verify all settings were changed correctly.

If none of that works, check everything again (and possibly yet again), or restore the backup made of the original sshd_config file and edit the settings as per above again, as it is possible a different setting was accidentally changed.

root@servername:~# mv /etc/ssh/sshd_config /etc/ssh/suspect.sshd_config
root@servername:~# cp /etc/ssh/original.sshd_config /etc/ssh/sshd_config
root@servername:~# nano /etc/ssh/sshd_config
root@servername:~# service ssh restart

Create and configure swap

Servers running on small amounts of RAM, such as the 512 MB and, depending on use case, 1 GB, may not have enough swap space or probably no swap configured at all. This can cause problems if applications are requiring more memory than the system provides, which typically results in system crash.

To check if there is any swap, type the following:

root@servername:~# swapon --show
root@servername:~#

If nothing is displayed before the new command prompt, then swap has not been configured (as demonstrated in the above example), as can also be verified with the free command:

root@servername:~# free -h
              total        used        free      shared  buff/cache   available
Mem:           487M        194M         36M         10M        256M        245M
Swap:            0B          0B          0B

Verify that ample space exists in storage to support a swap partition:

root@servername:~# df -h
Filesystem      Size  Used Avail Use% Mounted on
udev            234M     0  234M   0% /dev
tmpfs            49M  5.5M   43M  12% /run
/dev/xvda1       20G  2.2G   18G  11% /
tmpfs           242M     0  242M   0% /dev/shm
tmpfs           5.0M     0  5.0M   0% /run/lock
tmpfs           242M     0  242M   0% /sys/fs/cgroup
tmpfs            49M     0   49M   0% /run/user/1001

Create a swap file that will use 1GB of space:

root@servername:~# fallocate -l 1G /swapfile
root@servername:~# chmod 600 /swapfile
root@servername:~# mkswap /swapfile
root@servername:~# swapon /swapfile
root@servername:~# swapon --show
NAME      TYPE  SIZE USED PRIO
/swapfile file 1024M   0B   -1
root@servername:~# free -h
              total        used        free      shared  buff/cache   available
Mem:           487M        194M         36M         10M        256M        245M
Swap:          1.0G          0B        1.0G

Configure swapiness and cach-pressure

The swapiness and cache-pressure can be adjusted to improve overall web server performance.

To see the current settings:

root@servername:~# cat /proc/sys/vm/swappiness
60
root@servername:~# 

Improve performance by adjusting swappiness and cache pressure settings:

root@servername:~# sysctl vm.swappiness=10
root@servername:~# sysctl vm.vfs_cache_pressure=50

Make the changes permanent:

root@servername:~# cp /etc/fstab /etc/fstab.bak
root@servername:~# echo '/swapfile none swap sw 0 0' | tee -a /etc/fstab
root@servername:~# nano /etc/sysctl.conf

Add these two lines to the bottom of the file:

vm.swappiness=10
vm.vfs_cache_pressure=50

Log out of root

After the SSH settings have been verified, username has logged in and verified sudo membership, it is no longer necessary to log in as root ever again.

root@servername:~# logout

Next step

Now that the VPS is initialized, it's time to configure and learn about Ubuntu 18.04.

External links

Secure Secure Shell

How To Add Swap Space on Ubuntu 16.04 | DigitalOcean