📜 ⬆️ ⬇️

Bleeding debian / ubuntu servers for small

Hello. Recently there was a need to raise VPS on debian 7 for modest money.
About dances with a bell, I would like to describe here in detail.
Everything in this post was collected on the Internet, refined, chewed and thrown into one article.


The choice fell on https://account.nt-vps.ru/register/ due to low prices and good stability for this money (although there were serious problems with the network for 2 days). VPS was taken for 5 rubles per day (or for 150r per month) with small configurations of RAM 128mb and 10GB on disk.

In automatic mode, Debian 7.0 x86-64 Wheezy was installed and the VPS was ready to go.
64 bit system was chosen only for my personal needs, and I advise you, on this VPS, to install x86.
')


Start


After the creation of the server, you should receive a letter of the following type on the e-mail address that you registered during registration:
Good day!

Virtual server: vps3456
Configuration: 1xAMD-Opteron / 128Mb / 10Gb / 1xIPv4 @ 100
Operating system: Debian 7.0 x86-64 Wheezy

Access to the server using ssh2 protocol:
IP: 93.189.xx.xx
port: 22
user: root
Password: xxxxxxxxxxx

Use the putty program to connect to the server.
via ssh2 protocol https://www.putty.org/

Respectfully,
technical support

If you have windows, humbly obey instructions in the letter and follow the link https://www.putty.org/ for further instructions, if you have Linux (Debian / Ubuntu, etc.) connect to the server like this:
$ ssh root@93.189.xx.xx -p 22 

What we get the key security dialogue:
 The authenticity of host '[93.189.xx.xx]:22 ([93.189.xx.xx]:22)' can't be established. ECDSA key fingerprint is xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx. Are you sure you want to continue connecting (yes/no)? 

We agree and write yes.
Congratulations, you are in the system.
Let's update:
 # apt-get update && apt-get dist-upgrade -y 


Do not sit as root!


By default, we are prompted to sit as root, which is not very good for security reasons.

1. create a user under which we will work (the easiest way):
 # adduser user 

where user is the username
Next we will see a dialog something like:
   «user» ...    «user» (1001) ...    «user» (1001)   «user» ...    «/home/user» ...    «/etc/skel» ...    UNIX:     UNIX: passwd:        user      ENTER        []:   []:   []:   []:  []:   ? [Y/n] Y 

We write a complex password (which you will not forget!) And fill in the data we consider necessary, or simply press enter.

2. Allow user to execute sudo
Add user to a special group sudo:
 # usermod -a -G sudo user 

where user is the username.
Everything, we can leave and logs in under user
 $ ssh user@93.189.xx.xx -p 22 

and use sudo later if you need root privileges

Secure SSH a bit


Almost immediately after starting the server I noticed a suspicious activity in anu .. on port 22. Apparently, the Chinese porn scanners sniffed out and began to crack passwords.
The easiest way out is to change the ssh port from 22 to any other.
1. To do this, open the ssh server configuration file:
 $ sudo nano /etc/ssh/sshd_config 

We are looking for the string "Port 22" and replace it with "Port 354" where 354 is any number in the range from 1 to 65535
Just in case, let's see the open ports:
 netstat -tupln | grep LISTEN 

and choose any one not from this list.
I have to say right away that ports 80, 443, 3306, 22, 21, 8080 - I advise you not to use.
2. Next, we restrict the type of addresses to connect (IPv6 or IPv4). If your server is not using IPv6, then append the file / etc / ssh / sshd_config:
 AddressFamily inet 

3. Forbid authorization as root, look for the PermitRootLogin file and set no. If this parameter is not present, we add:
 PermitRootLogin no 

4. We allow connecting only by certain logins, appending the file / etc / ssh / sshd_config:
 AllowUsers user 

where the list of users is written through a space.

5. Forbid the attempt to log in with an empty password. We are looking for PermitEmptyPasswords and set no
 PermitEmptyPasswords no 

6. Save and restart ssh daemon:
 $ sudo /etc/init.d/ssh restart 

First of all, we can log in with new parameters ($ ssh user@93.189.xx.xx-p 354), later in the article we will return to the issue of security.

SWAP installation


As it turned out in the automatic mode, the swap was not set, and with such a memory size - this is critical.
Attention! This is my particular case, check if there is a swap like this:
 $ sudo swapon -s 


Create, using dd, the file of the required size for the swap area, where / swap is the name and path of the file, and count = 1024K is its size, in this case 512 MB
(the usual formula is swap = OZU * 1.5, but this is not our case):
 $ sudo dd if=/dev/zero of=/swap bs=1024 count=512K 


Next, we write to the beginning of the file the system information that will be used by the system kernel to work with the paging file:
 $ sudo mkswap /swap 


After the end of the operation, something like this will appear on the screen:
      1,  = 536868   , UUID=54c60583-e61a-483a-a15c-2f1be966db85 


The next step is to activate the newly created SWAP file:
 $ sudo swapon /swap 


Next, you need to edit the fstab file to connect the swap during the next system boot:
 $ sudo echo "/swap swap swap defaults 0 0" | sudo tee -a /etc/fstab 

That's it, the swap is ready.
Check with the command:
 $ free 

and should get:
  total used free shared buffers cached Mem: 510116 502320 7796 4380 1212 452548 -/+ buffers/cache: 48560 461556 Swap: 524284 0 524284 


Installation and advanced setup NGINX


As a frontend (Frontend), we will use the well-known nginx.
If you will not use the server for web applications, you can skip this part.

In the standard repository, of course, there is already nginx, but I would like a fresher version and no dancing.
1. Modify the /etc/apt/sources.list file:
 $ sudo nano /etc/apt/sources.list 

and append to the bottom:
 deb http://nginx.org/packages/debian/ wheezy nginx deb-src http://nginx.org/packages/debian/ wheezy nginx 

If you have a debian other than 7, then instead of wheezy we write its code name.

2. Update package sources and install nginx:
 $ sudo apt-get update && sudo apt-get install nginx 

3. Add new parameters to the beginning of the nginx.conf file
 timer_resolution 100ms; #      ,        worker_rlimit_nofile 8192; #       (RLIMIT_NOFILE)    worker_priority -5;#       

4. We are looking for worker_processes and set the number according to the number of processor cores, in our case 1.
 worker_processes 1; 

5. We are looking for the events directive and we bring it to the form:
 events { worker_connections 2048; use epoll; } 

6. Edit the http directive by modifying or appending the following parameters:
 sendfile on; #      #     gzip on; gzip_min_length 1100; gzip_buffers 64 8k; gzip_comp_level 3; gzip_http_version 1.1; gzip_proxied any; gzip_types text/plain application/xml application/x-javascript text/css; #       client_body_timeout 10; #       client_header_timeout 10; # ,    keep-alive          keepalive_timeout 5 5; #      send_timeout 10; 

7. Edit /etc/nginx/conf.d/sitename.conf or (ubuntu) /etc/nginx/sites-available/sitename.conf where sitename will be the name of your site:
 $ sudo nano /etc/nginx/conf.d/sitename.conf 

We lead to this form:
 #     limit_conn_zone $binary_remote_addr zone=perip:10m; limit_conn_zone $server_name zone=perserver:10m; server { listen 80; #    server_name sitename.net www.sitename.net; #         client_body_buffer_size 1K; #         client_header_buffer_size 1k; #     ,    Content-Length .      ,     client_max_body_size 1k; #           large_client_header_buffers 2 1k; #    if ($request_method !~ ^(GET|HEAD|POST)$ ) { return 444; } #  access_log /var/log/nginx/sitename.access.log main; #    error_log /var/log/nginx/sitename.error.log main; #     charset utf-8; location / { #   (slimits),      .   1     32000 ,      5  limit_conn perip 10; limit_conn perserver 100; #        #    ( )   ! if ($http_user_agent ~* LWP::Simple|BBBike|wget|curl|msnbot|scrapbot) { return 403; } #  referer . (     )       if ( $http_referer ~* (babes|forsale|girl|jewelry|love|nudit|organic|poker|porn|sex|teen|pron|money|free|jwh|speed|test|cash|xxx) ) { return 403; } #     location /   } } 

Later in the article we will return to these settings.

We pick system variables, defend against certain types of attacks.


These parameters give some oil and oiliness and in some cases increase the load.
Editing /etc/sysctl.conf
 $ sudo nano /etc/sysctl.conf 

Append to the end
 #   smurf- net.ipv4.icmp_echo_ignore_broadcasts = 1 #    ICMP- net.ipv4.icmp_ignore_bogus_error_responses = 1 #   SYN- net.ipv4.tcp_syncookies = 1 #     net.ipv4.conf.all.accept_source_route = 0 net.ipv4.conf.default.accept_source_route = 0 #    net.ipv4.conf.all.rp_filter = 1 net.ipv4.conf.default.rp_filter = 1 #   ,     net.ipv4.ip_forward = 0 net.ipv4.conf.all.send_redirects = 0 net.ipv4.conf.default.send_redirects = 0 #  ExecShield          kernel.exec-shield = 1 kernel.randomize_va_space = 1 #     net.ipv4.ip_local_port_range = 2000 65000 #    TCP- net.ipv4.tcp_rmem = 4096 87380 8388608 net.ipv4.tcp_wmem = 4096 87380 8388608 net.core.rmem_max = 8388608 net.core.wmem_max = 8388608 net.core.netdev_max_backlog = 5000 net.ipv4.tcp_window_scaling = 1 #  (. "   ") vm.swappiness=10 

Now you can reboot

We accelerate the overall work of the system


Prelink and Preload. Prelink for creating static library addresses, Preload is a small application that keeps track of the files of the most frequently used applications and loads them into memory when the system is idle.
1. Prelink installation:
 $ sudo apt-get -y install prelink 

Editing the / etc / default / prelink file:
 $ sudo nano /etc/default/prelink 

Change the line from PRELINKING = unknown to PRELINKING = yes
Run:
 $ sudo /etc/cron.daily/prelink 

2. Install Preload:
 $ sudo apt-get -y install preload 

Anything more is required

Configure the firewall (firewall)


Further there will be very doubtful configurations. We configure the number of connections from one IP address.
Rescues with some types of DOS attacks and brute force.

We carry out:
 $ sudo iptables -A INPUT -p tcp --dport 80 -i eth0 \ -m state --state NEW -m recent --set 

Further:
 $ sudo iptables -A INPUT -p tcp --dport 80 -i eth0 \ -m state --state NEW -m recent --update \ --seconds 15 --hitcount 20 -j DROP 

This rule limits more than 20 connection to port 80 (web) in 15 seconds from 1 ip address.
(by the way, the similar rule is already established at the level of nginx, but eats a huge amount of resources)

 $ sudo iptables -A INPUT -p tcp --dport 354 -i eth0 \ -m state --state NEW -m recent --set 


 $ sudo iptables -A INPUT -p tcp --dport 354 -i eth0 \ -m state --state NEW -m recent --update \ --seconds 60 --hitcount 4 -j DROP 

Where 354 port of your ssh server. The rule limits the number of connections, no more than 4 connections in 1 minute. In fact, I could not authorize more than 1 time per minute.
Further you can further adapt this rule for yourself and other services.

After the restart of the system, all the rules will be reset, so we do the following:
create and edit the /etc/network/if-up.d/00-iptables file
 $ sudo nano -w /etc/network/if-up.d/00-iptables 

We write to it:
 #!/bin/sh iptables-restore < /etc/firewall.conf 

save and make the file executable:
 $ sudo chmod +x /etc/network/if-up.d/00-iptables 

Save the rules to a file:
 $ sudo iptables-save | sudo tee /etc/firewall.conf 

Everything, rules are configured and will remain after system reboot.

At this the first part ends, it came out free time.

In the next part, I will tell nginx proxying to node.js, install and configure node.js, install and connect php-fpm to nginx. + Some tips on speed and safety without any extra dancing.

PS This is my first post on Habré and one of the first experiences of debian advanced setup. I will be glad to hear criticism and corrections.

upd: Thank you for the criticism, amendments, tips and responsiveness of habra people. The following article will supplement your advice.
upd 04/19/16: I did some research on the article, corrected errors and in some places supplemented it. Checked on debian 8.1 - it works. New article is postponed for the n-th time ...

upd 12/10/2018: The service is divided. Links in the article updated

Source: https://habr.com/ru/post/186362/


All Articles