mountroot: ee not found

Первый вариант

Монтируем / и подключаем /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
image_pdfimage_print

Create a Google application

 

  1. Sign in to the Google Developers Console with your Google account credentials.
  2. Accept the terms of service if you’re prompted to do so.
  3. In the upper-left corner of the page, select the project list, and then select New Project.
  4. Enter a Project Name, for example DataverseUA, and select Create.
  5. Make sure you’re using the new project by selecting the project drop-down in the top-left of the screen. Select your project by name, then select Open.
  6. Under the Quick access, or in the left menu, select APIs & services and then OAuth consent screen.
  7. For the User Type, select External and then select Create.
  8. On the OAuth consent screen, under App information
    1. Enter a Name for your application.
    2. Select a User support email address.
  9. Under the Authorized domains section, select Add domain, and then add dataverse.tst-amo.net.ua and www.dataverse.tst-amo.net.ua.
  10. In the Developer contact information section, enter comma separated emails for Google to notify you about any changes to your project.
  11. Select Save and Continue.
  12. From the left menu, select Credentials
  13. Select Create credentials, and then OAuth client ID.
  14. Under Application type, select Web application.
    1. Enter a suitable Name for your application, such as “DataverseUA for customers.”
    2. In Valid OAuth redirect URIs, enter the following URIs
      • https://dataverse.tst-amo.net.ua/oauth2/callback.xhtml
      • https://www.dataverse.tst-amo.net.ua/oauth2/callback.xhtml
  15. Select Create.
  16. Copy the values of Client ID and Client secret. You need both values to configure Google as an identity provider in your tenant. Client secret is an important security credential.

 

how-to-google-federation-customers

image_pdfimage_print

Калибровка APC Smart-UPS 750 / 1500

В продолжение темы.

Меняем батареи и подключаем через родной 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 часов.

В этой же программе можно изменить дату установки батарей. Если у вас несколько бесперебойников, то установка программы понадобится каждый раз.

image_pdfimage_print

DDOS на WEB сервер

Утро началось не с кофе. Просматривая логи, обнаружил, что на web сервере аномальная нагрузка. Причем, ping еще шел, а по ssh я уже не мог достучаться. Соответственно все сайты лежали. Идем на шлюз и смотрим кто мешает.

GATE

# 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 сервер.

WEB SERVER NGINX

Здесь стоит 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;
}

Limiting number of connections

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;
    }
}

Timeout parameters

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;
}

WEB SERVER IPTABLES

Теперь подправим 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

Block wp-login.php bruteforce attack

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

 

image_pdfimage_print

Postfix только на отправку (relayhost = smtp.gmail.com)

В продолжение темы. Нужно настроить почту для сайта только на отправку.

Устанавливаем

# 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

image_pdfimage_print

Downgrade php74 to php72

После установки на 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 ???

image_pdfimage_print

LAMP Centos 7 на AWS Lightsail

# 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

MariaDB

# yum install mariadb-server mariadb
# mysql_secure_installation

And answer to questions in wizard:

  • Switch to unix_socket authentication [Y/n] Y
  • Change the root password? [Y/n] Y
  • New password: ******
  • Re-enter new password: ******
  • Remove anonymous users? [Y/n] Y
  • Disallow root login remotely? [Y/n] Y
  • Remove test database and access to it? [Y/n] Y
  • Reload privilege tables now? [Y/n] Y

PhP

# 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

ProFTP

https://tst-amo.net.ua/blog/?p=2937
# yum install proftpd
mount -o bind /var/www/html /home/aws/html

Apache

# 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>

PhpMyAdmin

# 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';

Certbot

# 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

Apache HTTPS

Подключим 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+.

Postfix

Доустановим немобходимый механизм и консольный почтовик для проверки:

# 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
image_pdfimage_print

Блокировка сканера портов

Заблокировать доступ к устройству на 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:

  • 14d 00:00:00;
  • none dynamic – будет находиться в address list до перезагрузки роутера;
  • none static – постоянная запись(сохраняется в конфигурации).

По результатам работы сканера создаются записи в Address Lists, которым запрещен доступ в цепочке input на 14 дней.

image_pdfimage_print