# apt update -y && apt upgrade -y
!!!# apt-get install mc nano wget -y
# apt-get install mc -y
Отключим службу ondemand
(для разгона cpu)
# cat /proc/cpuinfo | grep MHz
# systemctl status ondemand
# systemctl stop ondemand
# systemctl disable ondemand
# nano /etc/sysctl.conf
В конец
!!!vm.swappiness=0
!!!vm.vfs_cache_pressure = 100
net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.default.disable_ipv6 = 1
net.ipv6.conf.lo.disable_ipv6 = 1
Сохранить.
Применить сразу:
# sysctl -p
Включить журналирование (предыдущих загрузок)
# nano /etc/systemd/journald.conf
...
[Journal]
#Storage=auto
Storage=persistent
Сохранить
Обратить внимание на имя nic!!!!
nano /etc/network/interfaces
Пример:
# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).
#source /etc/network/interfaces.d/*
# The loopback network interface
auto lo
iface lo inet loopback
# The primary network interface
#auto enp3s0
#iface enp3s0 inet dhcp
iface enp3s0 inet static
address 192.168.1.46
netmask 255.255.255.0
gateway 192.168.1.1
dns-nameservers 192.168.1.1
auto enp3s0
Сохранить.
Перезагрузка
# reboot
# apt install apache2 mariadb-server libapache2-mod-php -y
# apt install php-gd php-json php-mysql php-curl php-zip php-bz2
libxml2-dev php-dom php-xmlwriter php-xmlreader php-xml php-mbstring
php-ldap -y
# apt install php-intl php-mcrypt php-imagick -y
!!# apt install unzip -y
# cd /var/www
# wget https://download.nextcloud.com/server/releases/latest.zip
# unzip latest.zip
!!!# chown -R www-data:www-data /var/www/html/nextcloud
# nano /tmp/nextcloud.sh
#!/bin/bash
ocpath='/var/www/nextcloud'
htuser='www-data'
htgroup='www-data'
rootuser='root'
printf "Creating possible missing Directories\n"
mkdir -p $ocpath/data
mkdir -p $ocpath/assets
mkdir -p $ocpath/updater
printf "chmod Files and Directories\n"
find ${ocpath}/ -type f -print0 | xargs -0 chmod 0640
find ${ocpath}/ -type d -print0 | xargs -0 chmod 0750
chmod 755 ${ocpath}
printf "chown Directories\n"
chown -R ${rootuser}:${htgroup} ${ocpath}/
chown -R ${htuser}:${htgroup} ${ocpath}/apps/
chown -R ${htuser}:${htgroup} ${ocpath}/assets/
chown -R ${htuser}:${htgroup} ${ocpath}/config/
chown -R ${htuser}:${htgroup} ${ocpath}/data/
chown -R ${htuser}:${htgroup} ${ocpath}/themes/
chown -R ${htuser}:${htgroup} ${ocpath}/updater/
chmod +x ${ocpath}/occ
printf "chmod/chown .htaccess\n"
if [ -f ${ocpath}/.htaccess ]
then
chmod 0644 ${ocpath}/.htaccess
chown ${rootuser}:${htgroup} ${ocpath}/.htaccess
fi
if [ -f ${ocpath}/data/.htaccess ]
then
chmod 0644 ${ocpath}/data/.htaccess
chown ${rootuser}:${htgroup} ${ocpath}/data/.htaccess
fi
Сохранить.
# bash /tmp/nextcloud.sh
# nano /etc/apache2/sites-available/nextcloud.conf
<IfModule mod_ssl.c>
<VirtualHost _default_:443>
ServerAdmin admin@local
ServerName nextcloud
DocumentRoot /var/www/html
Alias /nextcloud "/var/www/nextcloud/"
<Directory /var/www/nextcloud/>
Options +FollowSymlinks
AllowOverride All
<IfModule mod_dav.c>
Dav off
</IfModule>
SetEnv HOME /var/www/html
SetEnv HTTP_HOME /var/www/html
</Directory>
<IfModule mod_headers.c>
Header always set Strict-Transport-Security "max-age=15768000; preload"
</IfModule>
SSLEngine on
SSLCertificateFile /etc/ssl/certs/ssl-cert-snakeoil.pem
SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key
</VirtualHost>
</IfModule>
Сохранить.
# nano /etc/apache2/sites-available/nc-redir.conf
<VirtualHost *:80>
ServerName nc-redir
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}$1 [R=301,L]
</VirtualHost>
# a2dissite 000-default.conf
# a2ensite nextcloud
# a2ensite nc-redir
# a2enmod rewrite
# a2enmod headers env dir mime
# a2enmod setenvif
# nano /etc/php/7.0/apache2/php.ini
Закоментировать:
;upload_max_filesize = 2M;max_file_uploads = 20
Добавить в конец:
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
Сохранить.
!!!# service apache2 restart
http://192.168.0.115/nextcloud/
# a2enmod ssl
# a2dissite default-ssl.conf
# service apache2 restart
https://192.168.0.223/nextcloud
# mysql_secure_installation
На пароль Enter
Вводим новый пароль, подтверждаем.
На все Y по умолчанию!
# mysql -u root -p
Enter password:
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 50
Server version: 10.0.29-MariaDB-0ubuntu0.16.04.1 Ubuntu 16.04
Copyright (c) 2000, 2016, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MariaDB [(none)]> CREATE DATABASE nextcloud;
Query OK, 1 row affected (0.00 sec)
MariaDB [(none)]> GRANT ALL ON nextcloud.* to 'nextcloud'@'localhost' IDENTIFIED BY 'password';
Query OK, 0 rows affected (0.00 sec)
MariaDB [(none)]> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.00 sec)
MariaDB [(none)]> quit
Bye
# mkdir /data
# chown -R www-data:www-data /data
!!!# chown -R www-data:www-data /mnt/data
https://192.168.0.223/nextcloud
Запускаем браузер и вводим http://ip-server/nextcloud
Задаем логин — Администратора NextCloud сервера
Вводим пароль администратора NextCloud сервера
Указываем место хранения данных, можно оставить по умолчанию и потом изменить.
Пользователь базы данных — nextcloud
Пароль пользователя базы данных (тот, что мы задавали выше при настройке базы данных)
Далее — Завершить установку
# apt install php-memcached memcached -y
# netstat -tap | grep memcached
tcp 0 0 localhost:11211 *:* LISTEN 17009/memcached
# ps ax | grep memcached
17009 ? Ssl 0:00 /usr/bin/memcached -m 64 -p 11211 -u memcache -l 127.0.0.1
17176 pts/4 S+ 0:00 grep --color=auto memcached
# nano /var/www/nextcloud/config/config.php
Вставить перед конечной );
'logtimezone' => 'Europe/Moscow',
'log_type' => 'owncloud',
'logfile' => 'nextcloud.log',
'memcache.distributed' => '\OC\Memcache\Memcached',
'memcache.local' => '\OC\Memcache\Memcached',
'memcached_servers' => array(
array('localhost', 11211),
),
'memcached_options' => array(
\Memcached::OPT_CONNECT_TIMEOUT => 50,
\Memcached::OPT_RETRY_TIMEOUT => 50,
\Memcached::OPT_SEND_TIMEOUT => 50,
\Memcached::OPT_RECV_TIMEOUT => 50,
\Memcached::OPT_POLL_TIMEOUT => 50,
// Enable compression
\Memcached::OPT_COMPRESSION => true,
// Turn on consistent hashing
\Memcached::OPT_LIBKETAMA_COMPATIBLE => true,
// Enable Binary Protocol
\Memcached::OPT_BINARY_PROTOCOL => true,
),
Сохранить.
# service apache2 restart
# apt install fail2ban
# nano /etc/fail2ban/filter.d/nextcloud.conf
Добавим:
[INCLUDES]
before = common.conf
[Definition]
failregex = Login failed.*Remote IP.*'<HOST>'
ignoreregex =
Сохранить.
# nano /etc/fail2ban/jail.d/nextcloud.conf
Добавить.
[nextcloud]
enabled = true
port = http,https
filter = nextcloud
# maxretry = 3
# bantime = 3600
# findtime = 36000
#logpath = /var/www/nextcloud/nextcloud.log
logpath = /data/nextcloud.log
Сохранить.
По умолчанию банит на 4 раз, на 600 с.
# service fail2ban restart
nextсloud Защита от подбора пароля с помощью FAIL2BAN
nextcloud-fail2ban
# fail2ban-client status nextcloud
Status for the jail: nextcloud
|- Filter
| |- Currently failed: 1
| |- Total failed: 6
| `- File list: /data/nextcloud.log
`- Actions
|- Currently banned: 1
|- Total banned: 1
`- Banned IP list: 192.168.1.246
How to Integrate OnlyOffice with NextCloud
# fail2ban-client set nextcloud unbanip <Banned IP>
Настройка firewall
# apt install ufw -y
# ip6tables -P INPUT DROP && ip6tables -P OUTPUT DROP && ip6tables -P FORWARD DROP
# ip6tables -L
# cp /etc/default/ufw /etc/default/ufw.bak
# nano /etc/default/ufw
Изменить:
IPV6=no
# ufw disable
# ufw default deny incoming
# ufw default allow outgoing
# ufw default deny forward
!!!# ufw allow ssh
# ufw allow 443
# ufw allow from 192.168.0.0/24
# ufw allow from 192.168.1.0/24 to any port 22
# ufw allow from x.x.x.x to any port 22
# ufw enable
# ufw status numbered
Состояние: активен
В Действие Из
- -------- --
[ 1] 443 ALLOW IN Anywhere
[ 2] 22 ALLOW IN XXX.XXX.XXX.XXX
[ 3] 22 ALLOW IN 192.168.1.0/24
[ 4] 22 ALLOW IN 192.168.0.0/24
# iptables -L
Удаление правила:
# ufw status numbered
Состояние: активен
В Действие Из
- -------- --
[ 1] 22 ALLOW IN Anywhere
[ 2] 443 ALLOW IN Anywhere
[ 3] Anywhere ALLOW IN 192.168.0.0/24
[ 4] Anywhere ALLOW IN 192.168.1.0/24
# ufw delete 1
Удаление:
allow 22
При смене ip адресов (доменов)
# nano /var/www/nextcloud/config/config.php
array (
0 => '192.168.0.X',
1 => '192.168.1.X',
2 => 'domen.example.com/',
),
Сохранить.
, отключить:
# service apache2 restart
# ufw disable
Ubuntu 16.04 LTS – How To Configure FireWall/IpTables and Fail2Ban
Fail2Ban 0.9.x в Ubuntu 16.04
Настройка Ubuntu для работы с ИБП от APC
# lsusb
Bus 001 Device 003: ID 051d:0002 American Power Conversion Uninterruptible Power Supply
# apt-get install apcupsd -y
# nano /etc/apcupsd/apcupsd.conf
#UPSCABLE smart
UPSCABLE usb
......
#UPSTYPE apcsmart
UPSTYPE usb
#DEVICE /dev/ttyS0
# Для проверки можно 30 (потом убрать )
TIMEOUT 0
Сохранить.
Настроим /etc/default/apcupsd
Заменяем ISCONFIGURED=no на ISCONFIGURED=yes , сохраняем, закрываем. Отныне apcupsd будет знать, что мы не забыли его настроить.
# nano /etc/default/apcupsd
#ISCONFIGURED=no
ISCONFIGURED=yes
Сохранить.
Теперь достаточно запустить apcupsd:
# /etc/init.d/apcupsd start
Starting UPS power management: apcupsd.
# /etc/init.d/apcupsd status
# apt install nmap -y
# nmap -v -sT localhost
Starting Nmap 7.01 ( https://nmap.org ) at 2017-06-08 22:12 MSK
Initiating Connect Scan at 22:12
Scanning localhost (127.0.0.1) [1000 ports]
Discovered open port 80/tcp on 127.0.0.1
Discovered open port 443/tcp on 127.0.0.1
Discovered open port 22/tcp on 127.0.0.1
Discovered open port 3306/tcp on 127.0.0.1
Discovered open port 139/tcp on 127.0.0.1
Discovered open port 445/tcp on 127.0.0.1
Discovered open port 3551/tcp on 127.0.0.1
Completed Connect Scan at 22:12, 0.04s elapsed (1000 total ports)
Nmap scan report for localhost (127.0.0.1)
Host is up (0.00024s latency).
Other addresses for localhost (not scanned): ::1
Not shown: 993 closed ports
PORT STATE SERVICE
22/tcp open ssh
80/tcp open http
139/tcp open netbios-ssn
443/tcp open https
445/tcp open microsoft-ds
3306/tcp open mysql
3551/tcp open apcupsd
Read data files from: /usr/bin/../share/nmap
Nmap done: 1 IP address (1 host up) scanned in 0.15 seconds
Raw packets sent: 0 (0B) | Rcvd: 0 (0B)
-----------------------------------------------------------------------------------------------------------------------
Решил дополнить сервер OpenVPN сервером
для подключения web сервера с 1с, а также TightVNC
Как настроить сервер OpenVPN в Ubuntu 17.10
Зайдем на сервер с nextcloud:
$ sudo -i
# nano /etc/sysctl.conf
Раскоментировать:
net.ipv4.ip_forward=1
Сохранить.
# sysctl -p
# ufw disable
# apt install openvpn easy-rsa -y
!!!# cp -R /root/files/openvpn /etc/openvpn
# cp -R /home/user/openvpn /etc/openvpn
Для ubuntu 16.04/2
# nano /etc/openvpn/server.conf
Закоментировать:
# Сообщите клиенту, что когда сервер перезагружается, так что
# Может автоматически повторно подключаться.
;explicit-exit-notify 1
------------------------------------------------------------------------------------------------------------------
port 1194
proto tcp
dev tun
ca ca.crt
cert server.crt
key server.key # This file should be kept secret
dh dh2048.pem
topology subnet
server 10.8.0.0 255.255.255.0
;ifconfig-pool-persist ipp.txt
client-config-dir /etc/openvpn/ccd/
client-to-client
keepalive 10 120
tls-auth ta.key 0 # This file is secret
key-direction 0
cipher AES-256-CBC
auth SHA256
user nobody
group nogroup
persist-key
persist-tun
status openvpn-status.log
verb 3
------------------------------------------------------------------------------------------------------------------
Сохранить.
# make-cadir ~/openvpn-ca
# cd ~/openvpn-ca
# source vars
# ./clean-all
# ./build-ca
# ./build-key-server server
# ./build-dh
# openvpn --genkey --secret keys/ta.key
Генерация ключей для клиента
# cd ~/openvpn-ca
# source vars
# ./build-key client1
...............................
# ./build-key client9
Скопируем ключи:
# cd ~/openvpn-ca/keys
# cp ca.crt ca.key server.crt server.key ta.key dh2048.pem /etc/openvpn
!!!# gunzip -c /usr/share/doc/openvpn/examples/sample-config-files/server.conf.gz | tee /etc/openvpn/server.conf
!!!# cp /etc/openvpn/server.conf /etc/openvpn/server.conf.bak
# nano /etc/openvpn/server.conf
Создать или заменить:
;local a.b.c.d
;proto tcp
proto udp
;dev tap
dev tun
;dev-node MyTap
ca ca.crt
cert server.crt
key server.key # This file should be kept secret
dh dh2048.pem
topology subnet
server 10.8.0.0 255.255.255.0
;ifconfig-pool-persist ipp.txt
;server-bridge 10.8.0.4 255.255.255.0 10.8.0.50 10.8.0.100
;server-bridge
;push "route 192.168.10.0 255.255.255.0"
;push "route 192.168.20.0 255.255.255.0"
;client-config-dir ccd
;route 192.168.40.128 255.255.255.248
client-config-dir /etc/openvpn/ccd/
;route 10.9.0.0 255.255.255.252
;learn-address ./script
;push "redirect-gateway def1 bypass-dhcp"
;push "dhcp-option DNS 208.67.222.222"
;push "dhcp-option DNS 208.67.220.220"
client-to-client
;duplicate-cn
keepalive 10 120
tls-auth ta.key 0 # This file is secret
key-direction 0
cipher AES-256-CBC
auth SHA256
;compress lz4-v2
;push "compress lz4-v2"
;comp-lzo
;max-clients 100
user nobody
group nogroup
persist-key
persist-tun
status openvpn-status.log
;log openvpn.log
;log-append openvpn.log
verb 3
;mute 20
;explicit-exit-notify 1
Сохранить.
!!!# systemctl restart openvpn@server
# systemctl start openvpn@server
# systemctl enable openvpn@server
# systemctl status openvpn@server
# mkdir -p ~/client-configs/files
# chmod 700 ~/client-configs/files
# cp /usr/share/doc/openvpn/examples/sample-config-files/client.conf ~/client-configs/base.conf
# cp ~/client-configs/base.conf ~/client-configs/base.conf.bak
# nano ~/client-configs/base.conf
Создать:
client
;dev tap
dev tun
;dev-node MyTap
proto tcp
;proto udp
# Указать свой ниже:
remote XXX.XXX.XXX.XXX 1194
;remote my-server-2 1194
;remote-random
resolv-retry infinite
nobind
user nobody
group nogroup
persist-key
persist-tun
;http-proxy-retry # retry on connection failures
;http-proxy [proxy server] [proxy port #]
;mute-replay-warnings
#ca ca.crt
#cert client.crt
#key client.key
remote-cert-tls server
tls-auth ta.key 1
key-direction 1
cipher AES-256-CBC
auth SHA256
#comp-lzo
verb 3
;mute 20
# script-security 2
# up /etc/openvpn/update-resolv-conf
# down /etc/openvpn/update-resolv-conf
Сохранить.
# nano ~/client-configs/make_config.sh
Добавить:
#!/bin/bash
# First argument: Client identifier
KEY_DIR=~/openvpn-ca/keys
OUTPUT_DIR=~/client-configs/files
BASE_CONFIG=~/client-configs/base.conf
cat ${BASE_CONFIG} \
<(echo -e '<ca>') \
${KEY_DIR}/ca.crt \
<(echo -e '</ca>\n<cert>') \
${KEY_DIR}/${1}.crt \
<(echo -e '</cert>\n<key>') \
${KEY_DIR}/${1}.key \
<(echo -e '</key>\n<tls-auth>') \
${KEY_DIR}/ta.key \
<(echo -e '</tls-auth>') \
> ${OUTPUT_DIR}/${1}.ovpn
Сохранить.
# chmod 700 ~/client-configs/make_config.sh
# cd ~/client-configs
# ./make_config.sh client1
.........................................
# ./make_config.sh client9
!!! Внимание проверить имена nic!!!
# ufw reset
# ufw status
# ufw disable
# ufw default deny incoming
# ufw default deny outgoing
# ufw default deny forward
# ufw allow out on tun0
# ufw allow in on tun0
# ufw allow 1194/udp
# ufw allow 443/tcp
# ufw allow from 192.168.1.0/24 proto tcp to any port 22
# ufw allow from x.x.x.x proto tcp to any port 21
# ufw allow out on enp3s0 to 192.168.1.0/24
# ufw allow in on enp3s0 to 192.168.1.0/24
# ufw enable# ufw status
# ufw status
Состояние: активен
В Действие Из
- -------- --
Anywhere on tun0 ALLOW Anywhere
1194/udp ALLOW Anywhere
443 ALLOW Anywhere
22 ALLOW xxx.xxx.xxx.xxx
192.168.1.0/24 on enp0s3 ALLOW Anywhere
Anywhere ALLOW OUT Anywhere on tun0
192.168.1.0/24 ALLOW OUT Anywhere on enp0s3
------------------------------------------------------------------------------------------
Установка и настройка Pure-FTPD (Pure FTP)
Установка и настройка Pure-FTPd в Ubuntu
# ufw disable
# apt install pure-ftpd
# groupadd ftpgroup
# useradd -g ftpgroup -d /dev/null -s /etc ftpuser
# passwd ftpuser
# mkdir /home/ftpuser/
# chown -R ftpuser:ftpgroup /home/ftpuser
# ln -s /etc/pure-ftpd/conf/PureDB /etc/pure-ftpd/auth/50pure
# mkdir /home/ftpuser/test
# chown -R ftpuser:ftpgroup /home/ftpuser/test
# mkdir /home/ftpuser/test/client
# chown -R ftpuser:ftpgroup /home/ftpuser/test/client
# pure-pw useradd test -u ftpuser -d /home/ftpuser/test
FTP, порты пассивного режима (иначе случайные):
указать два порта на одного клиента.
# echo "50000 50010" > /etc/pure-ftpd/conf/PassivePortRange
Порты открываются независимо от ufw! (и iptables? )
Работаем только по ip4
# echo "yes" > /etc/pure-ftpd/conf/IPV4Only
"Человеческий лог"(более детальный, после настройки убрать - удалить файл)
!!!# echo "yes" > /etc/pure-ftpd/conf/VerboseLog
В логе ip адреса вместо имен.
# echo yes > /etc/pure-ftpd/conf/DontResolve
# pure-pw mkdb
# service pure-ftpd restart
# netstat -ln | grep :21
tcp 0 0 0.0.0.0:21 0.0.0.0:* LISTEN
# ufw allow from 192.168.1.0/24 to any port 22
# ufw allow 21/tcp
# ufwreload
# ufw status
Защита Pure-ftpd от брутфорса с помощью Fail2Ban
Идеальный сервер - Ubuntu 14.04, nginx, BIND, MySQL, PHP, Postfix, Dovecot и ISPConfig 3 (страница 3)
# echo yes > /etc/pure-ftpd/conf/DontResolve
# pure-pw mkdb
# service pure-ftpd restart
# nano /etc/fail2ban/jail.d/pureftpd.conf
Вставить:
[pureftpd]
enabled = true
port = ftp
filter = pureftpd
logpath = /var/log/syslog
maxretry = 3
Сохранить.
# nano /etc/fail2ban/filter.d/pureftpd.conf
Вставить:
[Definition]
failregex = .*pure-ftpd: \(.*@<HOST>\) \[WARNING\] Authentication failed for user.*
ignoreregex =
Сохранить.
# service fail2ban restart
# iptables -L -n
# fail2ban-client status pureftpd
# fail2ban-client set pureftpd
unbanip <Banned IP>
# netstat -t
Активные соединения с интернетом (w/o servers)
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 192.168.1.46:ftp x.x.x.x:64087 ESTABLISHED
tcp 0 0 192.168.1.46:50002 x.x.x.x:64129 ESTABLISHED
Активные соединения с интернетом (servers and established) можно посмотреть:
# netstat -pant
---------------------------------------------------------------------------------------------------------
Настройка ufw
# apt purge snapd
Окончательный вариант:
# ufw reset
# ufw status
# ufw enable
# ufw default deny incoming
# ufw default deny outgoing
# ufw default deny forward
# ufw allow out on tun0
# ufw allow in on tun0
# ufw allow 443/tcp
# ufw allow from 192.168.1.0/24 proto tcp to any port 22
# ufw allow out on enp3s0 proto udp to 192.168.1.1 port 53
# ufw allow out on enp3s0 proto udp to any port 123
# ufw allow in on enp3s0 from 192.168.1.1 to 224.0.0.1
# ufw allow from 192.168.1.0/24 proto tcp to any port 1194
# ufw allow from X.X.X.X proto tcp to any port 1194
# ufw allow from Y1.Y1.Y1.Y1/21 proto tcp to any port 1194
# ufw allow from Y2.Y2.Y2.Y2/21 proto tcp to any port 1194
# ufw allow from Z.Z.Z.Z proto tcp to any port 1194
# ufw disable
# ufw enable