Difference between revisions of "Install a new server"

From Organic Design wiki
m (Installing packages)
m (Web-server and PHP)
 
(2 intermediate revisions by the same user not shown)
Line 39: Line 39:
  
 
'''Note:''' If you want mail from the ''root'' account sent to something other that ''root@yourdomain'' then, set the address in ''/root/.forward''.
 
'''Note:''' If you want mail from the ''root'' account sent to something other that ''root@yourdomain'' then, set the address in ''/root/.forward''.
 +
 +
=== Hostname ===
 +
Use ''hostnamectl'' to set the hostname, or without any arguments to check it's current state. Also edit ''/etc/hosts'' to ensure that the local domains are set to the external IP of the server. If it's a desktop machine, then instead set the hostname to point to 127.0.1.1.
 +
<source>
 +
hostnamectl set-hostname {!PRIMARY DOMAIN!}
 +
</source>
  
 
=== Timezone ===
 
=== Timezone ===
Line 223: Line 229:
 
First install the packages:
 
First install the packages:
 
<source lang="bash">
 
<source lang="bash">
apt install nginx php-fpm php-cli composer php-mysql php-gd php-intl php-curl php-mbstring php-bcmath php-imagick php-zip php-xml php-gmp
+
apt install nginx python3-certbot-nginx php-fpm php-cli composer php-mysql php-redis php-gd php-intl php-curl php-mbstring php-bcmath php-imagick php-zip php-xml php-gmp php-apcu
 
</source>
 
</source>
  

Latest revision as of 20:16, 29 August 2023

Procedure.svg Install a new server
Organic Design procedure

Choose a hosting provider

First an appropriate hosting provider needs to be found, or if running a server in-house, see the Configure LAN procedure. Some possible points to check out when looking for a server hosting service apart from just the cost are:

  • Ease of hardware upgrading - can you upgrade disk/memory/cpu without reinstalling the system?
  • Contention rate (how many concurrent clients share the hardware if its a VPS)
  • Control panel usefulness (the most important features are rebooting and virtual console access)
  • OS choices available (up to date Debian or Ubuntu are most important for us)
  • Historical downtime statistics
  • What jurisdiction are they hosting in and what laws apply? for example can your run hidden services, i2p/tor routers or torrent daemons?
  • Do they accept Bitcoin or other crypto-currencies for payment?
  • What kind of data backup options do they provide?

Get reverse DNS set up

Any site that sends emails should have reverse DNS correctly configured. Having a reverse DNS correctly set up will help to prevent the site's mails being trashed as spam. Many mail-servers will do a reverse lookup on the sending IP address and ensure it matches the senders specified domain.

This is not done by the domain registrar, it's done by the company hosting the server (the IP address owner), sometimes they include the ability to set it in the server management interface. If not, raise a support ticket asking them if they can set up a PTR record for the server's IP pointing to your naked domain.

You can check the reverse DNS for a domain at DNSstuff in their IP section, and you can find out more about what reverse DNS is and why it's important here.

Set up a caching DNS server

Setting up a local caching non-forwarding DNS server is a good idea to ensure that DNS requests return quickly (especially useful if you have sites that make requests before returning the pages). It's also essential if you're running spam assassin because the domain black-lists (DNSBL) services operate over DNS and will often block requests made from large ISP's DNS servers. See Configure DNS for installation details.

Download and install Debian or Ubuntu

If the server has no OS then download and install Debian/Ubuntu first. Depending on the kind of access you have to the server and the kind of media it can accept, the following links may be of interest.

Setting up the OS environment

First, bring the system up to date.

apt update
apt upgrade

Give the server's root account (and any other accounts that send mail) a friendly name so it looks better in the inbox when it sends mail. Do this by replacing the name "root" in the full-name field in /etc/passwd as follows:

root:x:0:0:Organic Design server:/root:/bin/bash

Note: If you want mail from the root account sent to something other that root@yourdomain then, set the address in /root/.forward.

Hostname

Use hostnamectl to set the hostname, or without any arguments to check it's current state. Also edit /etc/hosts to ensure that the local domains are set to the external IP of the server. If it's a desktop machine, then instead set the hostname to point to 127.0.1.1.

hostnamectl set-hostname PRIMARY DOMAIN

Timezone

It's best for a server to run on UTC timezone,

sudo timedatectl set-timezone UTC


Getting the following warning plus a bunch of others whenever Perl scripts run?

perl: warning: Falling back to the standard locale ("C").


Configure the locales and tick the time zones you'd like to have available on the system, make sure that en_US.8859-1 and en_US.UTF-8 are selected because it seems that some programs expect them to exist. Also make sure that all locales ate included that were mentioned anywhere within the warning messages.

dpkg-reconfigure locales


If you're still getting the problem, you can explicitly set the associated variables to one of the locales you made available by appending entries to your ~/.bashrc as in the following example, you may need to log out and back in for these changes to take effect.

echo "export LC_ALL=en_US.UTF-8" >> /home/foo/.bashrc

Security

By default the server login is the root user with a password, so the first thing I did was to set up another user for myself, add the user to /etc/sudoers with full privileges and no password requirement. Note that you need to use the sudo or visudo utility to modify, not the usual vi or nano utilities. If the default editor that visudo uses is not to your taste, you can change it as follows:

sudo update-alternatives --config editor


The www-data line allows git repositories to be automatically updated in response to WebHooks events sent by Guthub in response to push events.

fred     ALL=(ALL) NOPASSWD : ALL
www-data ALL=(ALL) NOPASSWD : /usr/bin/git pull --no-edit


Then we want to disable passwords for SSH access and use RSA keys as typing passwords is insecure. Check or add these settings in /etc/ssh/sshd_config:

AllowUsers fred bob sam
PermitRootLogin no
PubkeyAuthentication yes
PasswordAuthentication no
ChallengeResponseAuthentication no

ClientAliveInterval 30
ClientAliveCountMax 2


And don't forget to add your public RSA key to '~/.ssh/authorized_keys. Note that you'll probably need to create the directory since the account has just been created, and the owner and mode is important.

mkdir /home/USER/.ssh
echo "RSA_KEY" > /home/USER/.ssh/authorized_keys
chown USER:USER -R /home/USER/.ssh
chmod 644 /home/USER/.ssh/authorized_keys

Restart the SSH server and test that you can login from another terminal window before exiting the current session. You now login as your own user, not the root user, and then use sudo bash to gain a root shell.

service ssh restart

See also protecting SSH with fail2ban if you'd like more control over blocking IPs after failed login attempts.

Fail2Ban

Fail2ban allows the blocking of repeated login attempts to the server. Install it with apt install fail2ban and then add the following basic configuration to /etc/fail2ban/jail.local:

[DEFAULT]
destemail = your@email.here
sendername = Fail2Ban

[sshd]
enabled = true
port = 22

[sshd-ddos]
enabled = true
port = 22

Rootkit Hunter

Install The Rootkit Hunter with apt-get install rkhunter and uncomment the following lines as these files are normal on Debian systems and should not be considered as attacks. Also have a look at the Debian README file with zcat /usr/share/doc/rkhunter/README.Debian.gz.

ALLOWHIDDENDIR=/dev/.udev
ALLOWHIDDENDIR=/dev/.static
ALLOWHIDDENDIR=/dev/.initramfs
ALLOWHIDDENDIR=/dev/.mdadm
...
RTKT_FILE_WHITELIST="/etc/init.d/hdparm /etc/init.d/.depend.boot"
...
USER_FILEPROP_FILES_DIRS="/etc/init.d/.depend.boot"


Then run a properties update on it since we've added some custom files to the whitelist and need notification if they change, and then run a local test to see if there are any warnings.

rkhunter --propupd
rkhunter -c

Monitoring filesystem events

A good idea, especially if you suspect any kind of remote code execution (RCE) bugs in webapps etc is to monitor for changes in the filesystem. Here's a simple method using FSWatch. first download the latest release and unpack it, then install it:

./configure
make
sudo make install
sudo ldconfig

I used the following command format to log what I'm interested in. I'm, using the inefficient poll-monitor here because I for some reason the default inotify-monitor wouldn't return events for files in sub-directories, I added the l 30 option to specify a latency of 30 seconds to save CPU resource. I'm piping the output through egrep -v so I can specify a pattern to filter out of the log.

fswatch --monitor=poll_monitor -trxl 30 /var/www | egrep -v "(gitlist-cache|\.log$)" >> /var/log/fswatch.log &

I added the command to the @reboot event in the crontab along with a second item to mail me the last 20 items in the log each day.

@reboot     root   fswatch --monitor=poll_monitor -trxl 30 /var/www | egrep -v "(gitlist-cache|\.log$)" >> /var/log/fswatch.log
0 0 * * *   root   tail -n 20 /var/log/fswatch.log | mail -s "Daily FS changes" "foo@bar.baz"

Installing packages

Then begin installing the necessary packages,

apt install sudo fail2ban host net-tools screen cpulimit htop tree build-essential python-dev ntp p7zip-full bzip2 unzip git poppler-utils encfs curl htmldoc librsvg2-bin imagemagick redis-server


The following if you're going to be using email on the server:

apt install exim4-daemon-heavy dovecot-common dovecot-imapd spamassassin spamc maildirsync


The following Perl packages and utilites:

apt install libwww-perl libio-socket-ssl-perl libjson-perl libxml-simple-perl libexpect-perl libterm-readpassword-perl libtimedate-perl libmath-random-secure-perl libclass-dbi-mysql-perl  
cpan HTML::Entities Archive::Zip Net::DNS Perl::Version Email::MIME Email::Sender::Simple


Math markup: We've always used Latex for this, but the installation can be complicated and it requires over a GB (yes a Gigabyte!) of packages to be installed that we don't use for anything else. But now client side rendering is possible, or server-side via the new Mathoid node.js service both of which are vastly preferable. See MW:Extension:Math for more detail about installation options. For a fully client-side rendering solution with no server-side installation at all and no configuration, the simplest method is just to install the SimpleMathJax extension.

NodeJS

Many services depend on NodeJS these days, so it's a good idea to have the latest long term service release installed. For Debian installation instructions check here.

MariaDB

Either install the mysql-server package with apt-get, or go through this procedure for installing MariaDB instead which is a truly open source drop-in replacement for MySQL forked from the original by the creators.

Here's some settings for /etc/mysql/mariadb.conf.d/50-server.cnf that we've found to be a good idea:

bind-address=127.0.0.1    # Ensure the database is not open to external connections (already default in Debian 10)
max_statement_time=0.5    # Don't allow long executing SQL statements that clog the machine up

One issue that can occur after moving server for both MySQL and MariaDB is the following error produced every day:

/etc/cron.daily/logrotate:
error: error running shared postrotate script for '/var/log/mysql.log /var/log/mysql/mysql.log /var/log/mysql/mysql-slow.log '
run-parts: /etc/cron.daily/logrotate exited with return code 1

This is due to the debian-sys-maint user not having permission to access mysqladmin to rotate the logs either due to the MySQL user missing, or having the wrong password (thanks to Lornajane for her solution in this post). Get the password from the /etc/mysql/debian.cnf configuration file and then either update the password if the user exists, or create the user with the correct password if not.

USE mysql
UPDATE user SET Password = PASSWORD('**************') WHERE User = 'debian-sys-maint' && Host = 'localhost';
FLUSH PRIVILEGES
or
GRANT RELOAD, SHUTDOWN, PROCESS, SHOW DATABASES, SUPER, LOCK TABLES ON *.* TO 'debian-sys-maint'@'localhost' IDENTIFIED BY PASSWORD '**************';
FLUSH PRIVILEGES

You can check if the maintenance user has its access correctly configured with the following command:

mysqladmin --defaults-file=/etc/mysql/debian.cnf ping

Open files limits: After installing a lot of Joomla's all using table prefixes in shared databases, each using about 140 tables, I started getting "too many open files" errors, so I've doubled the open-files-limit and innodb_open_files values.

Web-server and PHP

First install the packages:

apt install nginx python3-certbot-nginx php-fpm php-cli composer php-mysql php-redis php-gd php-intl php-curl php-mbstring php-bcmath php-imagick php-zip php-xml php-gmp php-apcu

The differences to the default php.ini file in our servers are as follows:

post_max_size = 100M
    ︙
upload_max_filesize = 100M
    ︙
[opcache]
opcache.enable=1
opcache.enable_cli=1
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=10000
opcache.memory_consumption=128
opcache.save_comments=1
opcache.revalidate_freq=1

Un-comment the env entries towards the end of www.conf in the pool.d sub-directory as well:

;env[HOSTNAME] = $HOSTNAME
;env[PATH] = /usr/local/bin:/usr/bin:/bin
;env[TMP] = /tmp
;env[TMPDIR] = /tmp
;env[TEMP] = /tmp

Setting up SSL

See SSL

Domain names

Adjust the names of the symlinks in the /var/www/domains directory to local domain names and ensure that those names are added to the /etc/hosts file.

  • Note: If you're installing your wikia structure on a local machine, then you must ensure that your domains such as foo.localhost are set in /etc/hosts as aliases for 127.0.0.1
  • DNS: if you need to set up a DNS server or Dymamic DNS system, see Configure DNS

Extracting Databases from a Backup

Extract the most recent database backup (this may overwrite existing databases of the same names)

7za x all-yyyy-mm-dd.sql.7z
mysql -u root -p < all.sql
mysqladmin -u root -p flush-privileges

Setting up SFTP access

The OpenSSH server comes with good SFTP support built in and allows users to be set up that have only SFTP access and can be restricted to specified sub-directories. The configuration is done from /etc/ssh/sshd_config (it must be the OpenSSH server), first enable the SFTP subsystem by un-commenting or adding the following directive:

Subsystem sftp internal-sftp


Next add a section like the following example for each user requiring access,

Match User foo
ChrootDirectory /var/www
ForceCommand internal-sftp
X11Forwarding no
AllowTcpForwarding no


You can check for problems in the /var/log/auth.log file. The most common issue will be to do with permissions. The root folder that is given access to the SFTP subsystem must be owned by root and be in the root group. It must be writable only by root, but readable by the SFTP user. The connecting clients use a path relative to the chroot directory given to them in their matching configuration section.

SFTP windows clients

Windows users can use the FileZilla FTP client to connect to the server over SFTP using key-based logins.

First you need to import your private key by going into edit/settings and then SFTP in the treeview and click the Add Key button. This will then allow you to convert the key to the windows ppk format and save it in its list.

You can then set up a new site entry using protocol SFTP, and authentication type Interactive.

Setting up FTP access

Some clients may require standard FTP access which although not very secure, can have some restrictions put on it to make it a little safer such as restricting users to their home directories and using a non standard port. We use the GPL proFTPD server in standalone mode.

apt-get install proftpd


Edit the /etc/proftpd/proftpd.conf file and change the port to something other than 21 and add the following directive to restrict users to their home directories (or set it to a shared FTP directory).

DefaultRoot ~

Following Symlinks

Note that following symlinks is not supported if the DefaultRoot directive is used because the directive creates a "jail" preventing access to any directories outside of it. Some administrators have said that mount --bind can be used to achieve this but it hasn't worked for us as that seems to just create a normal symlink as well.

Next steps

See also