Network retstart
# service netif restart
Routing restart
# service routing restart
Network retstart
# service netif restart
Routing restart
# service routing restart
Монтируем / и подключаем /usr
# mountroot> ufs:/dev/ada0p2 # mount /dev/ada0p5 /usr # mount -u / # ee /etc/fstab # reboot
# fsck -y /dev/ada0p1 # mount /dev/ada0p1 /usr # vi /etc/fstab (change ada0 to ada1) # reboot
В продолжение темы.
Меняем батареи и подключаем через родной APC COM-кабель переходником COM to USB к PC.
Скачиваем ApcFix и запускаем, выставляем галочку SMART-UPS AUTO Fix
Дожидаемся когда параметр “0” устаканится
Закрываем программу.
Скачиваем Power Chut Bisnes Edition v9.5.0/9.5.1, запускаем, не забыв записать Login и Password и заходим через браузер:
https://localhost:6547/logon
Запускаем калибровку. Желательно, что бы батареи простояли на зарядке 12 часов.
В этой же программе можно изменить дату установки батарей. Если у вас несколько бесперебойников, то установка программы понадобится каждый раз.
Утро началось не с кофе. Просматривая логи, обнаружил, что на web сервере аномальная нагрузка. Причем, ping еще шел, а по ssh я уже не мог достучаться. Соответственно все сайты лежали. Идем на шлюз и смотрим кто мешает.
# tcpdump -i bge0 host 19x.xxx.xxx.xx4
....
10:58:29.348293 IP site.com.ua.49864 > 130.0.237.242.https: Flags [S], seq 142297589, win 29200, options [mss 1460,sackOK,TS val 95348608 ecr 0,nop,wscale 7], length 0
10:58:29.348303 IP site.com.ua.49888 > 130.0.237.242.https: Flags [S], seq 3563334456, win 29200, options [mss 1460,sackOK,TS val 95348608 ecr 0,nop,wscale 7], length 0
10:58:29.348313 IP site.com.ua.49880 > 130.0.237.242.https: Flags [S], seq 1828917869, win 29200, options [mss 1460,sackOK,TS val 95348608 ecr 0,nop,wscale 7], length 0
10:58:29.348324 IP site.com.ua.49878 > 130.0.237.242.https: Flags [S], seq 1635255414, win 29200, options [mss 1460,sackOK,TS val 95348608 ecr 0,nop,wscale 7], length 0
10:58:29.348333 IP site.com.ua.49876 > 130.0.237.242.https: Flags [S], seq 3432924249, win 29200, options [mss 1460,sackOK,TS val 95348608 ecr 0,nop,wscale 7], length 0
....
Здесь все понятно. Блокируем IP, сразу падает нагрузка, и идем подкручивать WEB сервер.
Здесь стоит nginx. Редактируем конфиг. В секции http {…} вставляем строку:
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
10m is size of zone. 1MB can hold 16000 states. I think this means 16000 unique IP addresses. In case you have way too many sites or very high traffic sites, you may want to increase it to 20MB or 100MB.
1r/s means 1 request per second is allowed. You cannot specify fractions. If you want to slowdown further, means less requests per second try 30r/m which means 30 requests per min, effectively 1 request per 2 second.
location ~ \.php$ { limit_req zone=one burst=1 nodelay; }
You can limit the number of connections that can be opened by a single client IP address,
Here we tweak the limit_conn_zone and limit_conn directives to limit the number of connections per IP address.
limit_conn_zone $binary_remote_addr zone=two:1m; server { location / { limit_conn two 10; } }
Slow connections can represent an attempt to keep connections open for a long time. As a result, the server can’t accept new connections.
server { client_body_timeout 5s; client_header_timeout 5s; }
Теперь подправим iptables, добавив вверх правила:
### DDOS PROTECTION ### ### 1: Limit connections per source IP ### /sbin/iptables -A INPUT -p tcp -m connlimit --connlimit-above 111 -j REJECT --reject-with tcp-reset ### 2: Limit RST packets ### /sbin/iptables -A INPUT -p tcp --tcp-flags RST RST -m limit --limit 2/s --limit-burst 2 -j ACCEPT /sbin/iptables -A INPUT -p tcp --tcp-flags RST RST -j DROP ### 3: Limit new TCP connections per second per source IP ### /sbin/iptables -A INPUT -p tcp -m conntrack --ctstate NEW -m limit --limit 60/s --limit-burst 20 -j ACCEPT /sbin/iptables -A INPUT -p tcp -m conntrack --ctstate NEW -j DROP
https://gist.github.com/mattia-beta/bd5b1c68e3d51db933181d8a3dc0ba64
https://inmediatum.com/en/blog/engineering/ddos-attacks-prevention-nginx/
https://cryptoworld.su/ddos-ataka-kak-ee-ustroit-i-zashhita-ot-nee/
https://mozgovoy.in.ua/centos-7/103-nastrojka-yadra-linux-dlya-tyazhelykh-proektov-i-zashchity-ot-ddos
В продолжение темы. Нужно настроить почту для сайта только на отправку.
Устанавливаем
# yum install certbot # yum install cyrus-sasl-plain # service postfix restart
Порт 25 заблокирован хостером, поэтому настроим на 587.
# mkdir /etc/postfix/sasl # cat sasl_passwd [smtp.gmail.com]:587 user_gmail@gmail.com:__PASSWORD__ # postmap /etc/postfix/sasl/sasl_passwd
# chmod 600 sasl_passwd
Редактируем main.cf
myhostname = aws.tst-amo.net.ua inet_protocols = ipv4 mydestination = $myhostname, localhost.$mydomain, localhost mynetworks = 127.0.0.0/8 relayhost = [smtp.gmail.com]:587 # Enables SASL authentication for postfix smtp_sasl_auth_enable = yes # Disallow methods that allow anonymous authentication smtp_sasl_security_options = noanonymous # Location of sasl_passwd we saved smtp_sasl_password_maps = hash:/etc/postfix/sasl/sasl_passwd # Enable STARTTLS encryption for SMTP smtp_tls_security_level = encrypt # Location of CA certificates for TLS smtp_tls_CAfile = /etc/ssl/certs/ca-bundle.crt smtp_sasl_security_options = noanonymous # TLS parameters smtpd_tls_cert_file=/etc/letsencrypt/live/aws.tst-amo.net.ua/fullchain.pem smtpd_tls_key_file=/etc/letsencrypt/live/aws.tst-amo.net.ua/privkey.pem smtp_use_tls=yes smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
В master.cf раскоментировать строку (включаем 587 порт)
submission inet n - n - - smtpd
Проверяем
# echo "Test Postfix Gmail https://example.com" | mail -s "Postfix Gmail" to_user@domen.com
https://medium.com/yavar/send-mail-using-postfix-server-bbb08331d39d
https://www.digitalocean.com/community/tutorials/how-to-install-and-configure-postfix-as-a-send-only-smtp-server-on-ubuntu-22-04
После установки на AWS LAMP (Centos 7, apache24, php7.4, mariadb10) выяснилось, что некоторые скрипты некоректно отрабатывают. Поэтому нужно понизить версию php.
Смотрим все установленные пакеты:
# rpm -qa | grep php php74-php-pecl-mysql-1.0.0-0.23.20190415.d7643af.el7.remi.x86_64 php-cli-7.4.33-6.el7.remi.x86_64 php-mysqlnd-7.4.33-6.el7.remi.x86_64 php-mbstring-7.4.33-6.el7.remi.x86_64 php74-php-common-7.4.33-6.el7.remi.x86_64 gd3php-2.3.3-7.el7.remi.x86_64 php74-php-pecl-mcrypt-1.0.6-1.el7.remi.x86_64 php-json-7.4.33-6.el7.remi.x86_64 php-7.4.33-6.el7.remi.x86_64 php74-php-json-7.4.33-6.el7.remi.x86_64 php74-php-cli-7.4.33-6.el7.remi.x86_64 php74-php-pdo-7.4.33-6.el7.remi.x86_64 php-pdo-7.4.33-6.el7.remi.x86_64 oniguruma5php-6.9.8-1.el7.remi.x86_64 php74-php-gd-7.4.33-6.el7.remi.x86_64 php-common-7.4.33-6.el7.remi.x86_64 php-sodium-7.4.33-6.el7.remi.x86_64 php74-runtime-7.4-3.el7.remi.x86_64 php74-7.4-3.el7.remi.x86_64 php74-php-mysqlnd-7.4.33-6.el7.remi.x86_64
Удаляем PHP 7.4 packages вместе с зависимостями:
# yum remove php-*
Устанавливаем PHP 7.2 packages:
# yum-config-manager --disable remi-php74 # yum-config-manager --enable remi-php72 # yum install php php-common php-cli php-mysqlnd php-mbstring php-pecl-mcrypt php-json php-pdo php-gd
Еще нужно переустановить модули apache24 и phpmyadmin ???
# timedatectl list-timezones # timedatectl set-timezone Europe/Kyiv
# yum install update
# yum -y install https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm # yum -y install https://rpms.remirepo.net/enterprise/remi-release-7.rpm # yum -y install yum-utils # yum-config-manager --enable remi-php72 # yum update # yum install wget zip unzip # yum install httpd
# yum install mariadb-server mariadb # mysql_secure_installation
And answer to questions in wizard:
# yum install php php-common php-mcrypt php-cli php-gd php-curl php-mysql php-xml php-mbstring php-sodium php-pecl-mysql
# yum install gcc php-devel php-pear # yum install ImageMagick ImageMagick-devel # pecl install imagick You should add "extension=imagick.so" to php.ini или создать файлик в # vi /etc/php.d/imagick.so extension=imagick.so
https://tst-amo.net.ua/blog/?p=2937 # yum install proftpd
mount -o bind /var/www/html /home/aws/html
# httpd -M # yum install mod_ssl openssh # apachectl restart # httpd -t # systemctl status httpd
# cat httpd.conf | egrep "^[^#]" ServerRoot "/etc/httpd" ServerTokens ProductOnly ServerSignature Off Listen 0.0.0.0:80 Include conf.modules.d/*.conf User apache Group apache ServerAdmin root@localhost ServerName aws.tst-amo.net.ua:80 <Directory /> AllowOverride none Require all denied </Directory> DocumentRoot "/var/www/" # Relax access to content within /var/www <Directory "/var/www"> AllowOverride All #Allow open access: Require all granted #Require all denied </Directory> # Further relax access to the default document root <Directory "/var/www/html"> Options -Indexes +FollowSymLinks AllowOverride All Require all granted </Directory> <Directory "/var/www/cgi-bin"> AllowOverride None Options None Require all granted </Directory> <IfModule mime_module> TypesConfig /etc/mime.types AddType application/x-compress .Z AddType application/x-gzip .gz .tgz AddType text/html .shtml AddOutputFilter INCLUDES .shtml </IfModule> <IfModule dir_module> DirectoryIndex index.php index.html index.htm index.shtml </IfModule> <Files ".ht*"> Require all denied </Files> ErrorLog "logs/error_log" LogLevel warn <IfModule log_config_module> LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined LogFormat "%h %l %u %t \"%r\" %>s %b" common <IfModule logio_module> # You need to enable mod_logio.c to use %I and %O LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio </IfModule> CustomLog "logs/access_log" combined </IfModule> <IfModule alias_module> ScriptAlias /cgi-bin/ "/var/www/cgi-bin/" </IfModule>
<IfModule mime_magic_module> MIMEMagicFile conf/magic </IfModule> EnableSendfile on IncludeOptional conf.d/*.conf
Запускаем сайт на протоколе http
# vi /etc/httpd/conf.d/aws.conf <VirtualHost 0.0.0.0:80> ServerName aws.tst-amo.net.ua ServerAlias www.aws.tst-amo.net.ua ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog /var/log/httpd/error.log CustomLog /var/log/httpd/access.log combined Redirect permanent / https://aws.tst-amo.net.ua/ </VirtualHost>
# wget https://files.phpmyadmin.net/phpMyAdmin/4.9.11/phpMyAdmin-4.9.11-all-languages.zip
Правим конфиг:
# cp config.sample.inc.php config.inc.php # vi config.inc.php $cfg['blowfish_secret'] = '12345678901234273190123456789012' /** * Directories for saving/loading files from server */ $cfg['TempDir'] = '/tmp';
# yum install certbot # certbot certonly -n --standalone -m user@gmail.com --agree-tos -d aws.tst-amo.net.ua # ss -tlpn | grep -E ":(80|443)" # systemctl stop httpd # certbot certonly -n --standalone -m user@gmail.com --agree-tos -d aws.tst-amo.net.ua # systemctl start httpd
Продление сертификатов:
# vi /etc/cron.daily/certbot-renew #!/bin/sh if certbot renew > /var/log/letsencrypt/renew.log 2>&1 ; then /usr/sbin/service httpd reload >> /var/log/letsencrypt/renew.log fi exit
# crontab -e 07 02,18 * * * /etc/cron.daily/certbot-renew
Подключим SSL в apache, создаем конф файл
# vi /etc/httpd/conf.d/aws-ssl.conf
<VirtualHost 0.0.0.0:443> ServerName aws.tst-amo.net.ua ServerAlias www.aws.tst-amo.net.ua ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog /var/log/httpd/error.log CustomLog /var/log/httpd/access.log combined SSLEngine on SSLProtocol all -SSLv2 -SSLv3 -TLSv1 -TLSv1.1 SSLCipherSuite "EECDH+ECDSA+AESGCM EECDH+aRSA+AESGCM EECDH+ECDSA+SHA384 EECDH+ECDSA+SHA256 EECDH+aRSA+SHA384 EECDH+aRSA+SHA256 EECDH+aRSA+RC4 EECDH EDH+aRSA RC4 !aNULL SSLHonorCipherOrder on SSLCompression off Header always set Strict-Transport-Security "max-age=15552000; includeSubDomains; preload" SSLCertificateFile /etc/letsencrypt/live/aws.tst-amo.net.ua/cert.pem SSLCertificateChainFile /etc/letsencrypt/live/aws.tst-amo.net.ua/chain.pem SSLCertificateKeyFile /etc/letsencrypt/live/aws.tst-amo.net.ua/privkey.pem </VirtualHost>
Проверяем на сайте ssllabs.com и радуемся рейтингу A+.
Доустановим немобходимый механизм и консольный почтовик для проверки:
# yum install cyrus-sasl-plain # yum install mailx
Postfix будет настроен как релей, используя google учетку:
# vi /etc/postfix/main.cf relayhost = [smtp.gmail.com]:587 # Enables SASL authentication for postfix smtp_sasl_auth_enable = yes # Disallow methods that allow anonymous authentication smtp_sasl_security_options = noanonymous # Location of sasl_passwd we saved smtp_sasl_password_maps = hash:/etc/postfix/sasl/sasl_passwd # Enable STARTTLS encryption for SMTP smtp_tls_security_level = encrypt # Location of CA certificates for TLS smtp_tls_CAfile = /etc/ssl/certs/ca-bundle.crt smtp_sasl_security_options = noanonymous # TLS parameters smtpd_tls_cert_file=/etc/letsencrypt/live/aws.tst-amo.net.ua/fullchain.pem smtpd_tls_key_file=/etc/letsencrypt/live/aws.tst-amo.net.ua/privkey.pem smtp_use_tls=yes #smtpd_tls_mandatory_protocols=!SSLv2, !SSLv3 smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
# vi /etc/postfix/master.cf submission inet n - n - - smtpd
# vi /etc/postfix/aliases postmaster: postmaster@aws.tst-amo.net.ua root: no_reply_dataverse@aws.tst-amo.net.ua
# postmap aliases
# vi /etc/aliases
# Basic system aliases -- these MUST be present.
mailer-daemon: postmaster
postmaster: root
root: user@gmail.com
# newaliases
# vi /etc/postfix/sasl/sasl_passwd [smtp.gmail.com]:587 user@mail.com:your_password
# postmap /etc/postfix/sasl/sasl_passwd # chown root:root /etc/postfix/sasl/sasl_passwd /etc/postfix/sasl/sasl_passwd.db # chmod 600 /etc/postfix/sasl/sasl_passwd /etc/postfix/sasl/sasl_passwd.db
# yum install ca-certificates # systemctl restart postfix
Проверка:
# echo "Test Postfix Gmail https://example.com" | mail -s "Postfix Gmail" to_user@domen.ua
Заблокировать доступ к устройству на 14 дней
/ip firewall filter add action=drop chain=input comment="Drop - port scanners" src-address-list=\ Port-Scanners add action=drop chain=forward comment="Drop - port scanners" \ src-address-list=Port-Scanners add action=add-src-to-address-list address-list=Port-Scanners \ address-list-timeout=2w chain=input comment="Scan - Scan Ports" protocol=\ tcp psd=21,3s,3,1 add action=add-src-to-address-list address-list=Port-Scanners \ address-list-timeout=2w chain=input comment=\ "Scan - NMAP FIN Stealth scan" protocol=tcp tcp-flags=\ fin,!syn,!rst,!psh,!ack,!urg add action=add-src-to-address-list address-list=Port-Scanners \ address-list-timeout=2w chain=input comment="Scan - SYN/FIN scan" \ protocol=tcp tcp-flags=fin,syn add action=add-src-to-address-list address-list=Port-Scanners \ address-list-timeout=2w chain=input comment="Scan - SYN/RST scan" \ protocol=tcp tcp-flags=syn,rst add action=add-src-to-address-list address-list=Port-Scanners \ address-list-timeout=2w chain=input comment="Scan - FIN/PSH/URG scan" \ protocol=tcp tcp-flags=fin,psh,urg,!syn,!rst,!ack add action=add-src-to-address-list address-list=Port-Scanners \ address-list-timeout=2w chain=input comment="Scan - ALL/ALL scan" \ protocol=tcp tcp-flags=fin,syn,rst,psh,ack,urg add action=add-src-to-address-list address-list=Port-Scanners \ address-list-timeout=2w chain=input comment="Scan - NMAP NULL scan" \ protocol=tcp tcp-flags=!fin,!syn,!rst,!psh,!ack,!urg
значения Timeout:
По результатам работы сканера создаются записи в Address Lists, которым запрещен доступ в цепочке input на 14 дней.