Заметки сисадмина

Заметки сисадмина о интересных вещах из мира IT, инструкции и рецензии. Настраиваем Компьютеры/Сервера/1С/SIP-телефонию в Москве



Как быстро понять, что тормозит подключение по SSH?

2025-04-21 · Posted in Linux

Когда SSH «висит» на 5–10 секунд перед вводом пароля — виноват чаще всего Reverse DNS lookup на стороне сервера.

Решение: отключаем проверку DNS у sshd

Добавьте (или раскомментируйте и установите) строку:

Перезапустите службу:

Дополнительно: отключите GSSAPI-аутентификацию

Иногда медленно работает GSSAPI (Kerberos и пр.), особенно в хостах без домена:

Когда применять?
Если SSH подключение к серверу с «белым» IP идёт с задержкой — проверь DNS и GSSAPI. Особенно актуально для серверов в DMZ или без настроенного rDNS.

служба Windows Update на стартует

2025-04-16 · Posted in Windows Server 2016/2019

Cлужба Windows Update на одном из серверов Windows Server 2019 просто отказалась стартовать. Перезапуск, reset компонентов — ничего не помогло.

Оказалось, что виноват битый файл базы данных обновлений. Решение оказалось простым, но мало кто его делает вручную:

Вот PowerShell-скрипт, который полностью сбрасывает Windows Update, включая очистку базы данных:

После этого сервер спокойно начал тянуть апдейты. Главное — не забудьте перезапустить сервисы, а лучше сразу проверить доступность обновлений:

(если стоит PSWindowsUpdate модуль)

если хотите автоматизировать это на нескольких машинах — добавьте Invoke-Command и в путь!

pfSense: setup WireGuard Site-to-Site Tunnel

This guide will walk you through setting up a WireGuard site to site  tunnel on pfsense 2.7.2.

For this guide we assume

  • Site A with a network subnet of 192.168.1.0/24,
  • Site B with a network subnet of 192.168.24.0/24 and a
  • Tunnel Subnet of 10.10.12.0/30.

Obviously adjust these settings to your specific needs.
Ensure that the Tunnel Subnet you choose does NOT overlap with any other network subnets currently in use in your network environment.

Install WireGuard Package on Both Sites

On BOTH site pfsense installations, install the WireGuard package from System —> Package Manager —> Available Packages. Enter Wireguard in the Search term field, click search and then click on the Install button next to WireGuard package.

image.png

Create Tunnel on Site A

On Site A, refresh the pfsense web GUI and navigate to VPN —> Wireguard, click on the Tunnels tab and then click on Add Tunnel button.

image.png

In the Tunnel Configuration fill/set in the following fields:

  • Enable: Checked
  • Description: Optionally, describe the purpose of this tunnel (Ex: Tunnel to Site B)
  • Listen Port: Leave blank to use port UDP/51820 or enter a specific port number you with to use
  • Interface Keys: click the Generate button to create a new Private/Public key pair and copy the Public Key that’s generated in order to enter it in the Public Key field on Site B.
  • Click the Save Tunnel button

image.png

Create Tunnel on Site B

On Site B, refresh the pfsense web GUI and navigate to VPN —> Wireguard, click on the Tunnels tab and then click on Add Tunnel button.

In the Tunnel Configuration fill/set in the following fields:

  • Enable: Checked
  • Description: Optionally, describe the purpose of this tunnel(Ex: Tunnel to Site A)
  • Listen Port: Leave blank to use port UDP/51820 or enter a specific port number you with to use
  • Interface Keys: click the Generate button to create a new Private/Public key pair and copy the Public Key that’s generated in order to enter it in the Public Key field on Site B.
  • Click the Save Tunnel button

image.png

Enable WireGuard on Both Sites

On BOTH sites, navigate to VPN —> WireGuard, click on the Settings tab and click on the Enable WireGuard checkbox, select Only Unassigned Tunnels on the Interface Group Membership drop-down and then click on the Save button.

image.png

Add Peer on Site A

On Site A, navigate to VPN —> WireGuard, click on the Peers tab and then click on the Add Peer button.

image.png

In the Peer Configuration fill/set in the following fields:

  • Enable: Checked
  • Tunnel: Select the Tunnel previously configured from the drop-down list
  • Description: Optionally, describe the purpose of this Peer (Ex: Peer to Site B)
  • Dynamic Endpoint: Unchecked
  • Endpoint: Fill in the Internet IP or Hostname as well as the port number for Site B
  • Public Key: Paste the previously copied Public Key from the Tunnel on Site B
  • Pre-shared Key: Click the Generate button to generate a new pre-shared key and copy it in order to paste in the Peer configuration of Site B
  • Allowed IPs: Enter an UNUSED Network address (Example: 10.10.12.0) with a CIDR of 30 (For a total of two IPs) in the first field, click the Add Allowed IP and then enter the Network Address and corresponding CIDR of the subnet for Site B
  • Click the Save Peer button

image.png

Add Peer on Site B

On Site B, navigate to VPN —> WireGuard, click on the Peers tab and then click on the Add Peer button.

In the Peer Configuration fill/set in the following fields:

  • Enable: Checked
  • Tunnel: Select the Tunnel previously configured from the drop-down list
  • Description: Optionally, describe the purpose of this Peer (Ex: Peer to Site A)
  • Dynamic Endpoint: Unchecked
  • Endpoint: Fill in the Internet IP or Hostname as well as the port number for Site A
  • Public Key: Paste the previously copied Public Key from the Tunnel on Site A
  • Pre-shared Key:  Paste the previously copied Pre-Shared key from the Peer on Site A
  • Allowed IPs: Enter the SAME Tunnel Subnet Network address and CIDR you set on the Peer on Site A, click the Add Allowed IP and then enter the Network Address and corresponding CIDR of the subnet for Site A
  • Click the Save Peer button

Configure Interface for Site A

On Site A, navigate to Interfaces —> Assignments and under Available network ports drop-down select the WireGuard tunnel you previously created and click the Add button.

image.png

Click on the new OPT(X) interface that was just created.

image.png

In the General Configuration page fill/set the following fields:

  • Enable: Checked
  • Description: Optionally, describe the purpose of this Interface (Ex: Tunnel to Site B)
  • IPv4 Configuration Type: Static IPv4
  • IPv4 Address: Enter an IP address for Site A. The IP address you enter here will be one of two possible IP addresses you can use from the /30 Tunnel Subnet you chose earlier. For this example, we used the Subnet Tunnel of 10.10.12.0/30 which gives us 10.10.12.1 and 10.10.12.2 as the only two usable IPs for this subnet. So, for this example we will use 10.10.12.1 for Site A.
  • Click the Save button and then click the Apply Changes button.

image.png

Configure Interface for Site B

On Site B, navigate to Interfaces —> Assignments and under Available network ports drop-down select the WireGuard tunnel you previously created and click the Add button.

Click on the new OPT(X) interface that was just created.

In the General Configuration page fill/set the following fields:

  • Enable: Checked
  • Description: Optionally, describe the purpose of this Interface (Ex: Tunnel to Site A)
  • IPv4 Configuration Type: Static IPv4
  • IPv4 Address: Enter an IP address for Site B. The IP address you enter here will be one of two possible IP addresses you can use from the /30 Tunnel Subnet you chose earlier. For this example, we used the Subnet Tunnel of 10.10.12.0/30 which gives us 10.10.12.1 and 10.10.12.2 as the only two usable IPs for this subnet. So, for this example we will use 10.10.12.2 for Site B.
  • Click the Save button and then click the Apply Changes button.

image.png

Create Gateway and Route on Site A

On Site A navigate to System —> Routing and under the Gateways tab click the Add button.

image.png

In the Edit Gateway page fill/set the following fields:

  • Disabled: Unchecked
  • Interface: Select the interface for Site A you created earlier
  • Name: Enter a name for this gateway (Ex: WG_GW_Site_B)
  • Gateway: Enter the Tunnel Subnet IP address for Site B. For this example we used 10.10.12.2 for Site B.
  • Description: Optionally, enter a description (Ex: Wireguard Gateway to Site B)
  • Click the Save button and then click the Apply Changes button.

image.png

Next, on Site A navigate to System —> Routing and under the Static Routes tab click the Add button.

image.png

In the Edit Route Entry page, fill/set the following fields:

  • Destination network: Enter the network subnet for Site B (NOT the tunnel subnet). In this example, the network subnet we used for Site B was 192.168.24.0/24.
  • Gateway: Select the Gateway to Site B you created earlier
  • Description: Optionally, enter a description (Ex: Route to Site B)
  • Click the Save button and then click the Apply Changes button.

image.png

Create Gateway and Route on Site B

On Site B navigate to System —> Routing and under the Gateways tab click the Add button.

In the Edit Gateway page fill/set the following fields:

  • Disabled: Unchecked
  • Interface: Select the interface for Site A you created earlier
  • Name: Enter a name for this gateway (Ex: WG_GW_Site_A)
  • Gateway: Enter the Tunnel Subnet IP address for Site A. For this example we used 10.10.12.1 for Site A.
  • Description: Optionally, enter a description (Ex: Wireguard Gateway to Site A)
  • Click the Save button and then click the Apply Changes button.

image.png

Next, on Site B navigate to System —> Routing and under the Static Routes tab click the Add button.

In the Edit Route Entry page, fill/set the following fields:

  • Destination network: Enter the network subnet for Site A (NOT the tunnel subnet). In this example, the network subnet we used for Site A was 192.168.1.0/24.
  • Gateway: Select the Gateway to Site A you created earlier
  • Description: Optionally, enter a description (Ex: Route to Site A)
  • Click the Save button and then click the Apply Changes button.

image.png

Add Firewall Rules on BOTH Firewalls

On BOTH firewalls, navigate to Firewall —> Rules and under the WAN tab, click the Add button. In the Edit Firewall Rule page, fill/set the following fields.

  • Action: Pass
  • Interface: WAN
  • Address Family: IPv4
  • Protocol: UDP
  • Source: Any
  • Destination: WAN address
  • Destination Port Range: (other) 51820 to (other) 51820
  • Log: Optionally, check to Log packets that are handled by this rule
  • Description: Optionally, enter a description (Ex: Wireguard Site A and Site B)
  • Click the Save button and then click the Apply Changes button.

image.png
On BOTH firewalls, navigate to Firewall —> Rules and under the TUNNELTOSITE(X) tab, click the Add button. In the Edit Firewall Rule page, fill/set the following fields.

  • Action: Pass
  • Interface: Ensure the interface you created earlier for each site is already selected
  • Address Family: IPv4
  • Protocol: Any (Start with Any and then you can tighten the rules further after you ensure tunnel is working properly)
  • Source: Any (Start with Any and then you can tighten the rules further after you ensure tunnel is working properly)
  • Destination: Any (Start with Any and then you can tighten the rules further after you ensure tunnel is working properly)
  • Destination Port Range: Any (Start with Any and then you can tighten the rules further after you ensure tunnel is working properly)
  • Log: Optionally, check to Log packets that are handled by this rule
  • Description: Optionally, enter a description (Ex: Wireguard Traffic Site A and Site B)
  • Click the Save button and then click the Apply Changes button.

Check the Wireguard Status

On BOTH firewalls navigate to Status —> Wireguard, locate the WireGuard tunnel you created, expand it and ensure the Peers are connected on BOTH firewalls.

image.png

Additionally, ensure you can ping and access resources on each remote network from the corresponding site.

pfSense Disable IPv6

However, there are cases where disabling IPv6 becomes necessary. For instance, like simplifying network management or addressing specific issues.

Today, we are going to take a look at how to disable IPv6 on pfSense.

1)First, we have to head to System -> Advanced -> Networking.

2)Then, we have to uncheck the “Allow IPv6” checkbox.

3)Next, it is time to turn on Logging for PFsense Default Blocks. We can do this by heading to Rules under Firewalls.

4)Now, click the icon to view the logs in the top right corner.

5)Then, click Settings and check the boxes next to “Log firewall default blocks.”

This will give us access to IPv6 traffic in our logs.

6)Next, we have to make sure DHCPv6 Relay is disabled. We do this by heading to Services -> DHCPv6 Relay and unchecking “Enable.”

7)Then, save and apply the settings.

8)Furthermore, we have to disable IPv6 on each Interface individually.

  • First, head to Interfaces and review the list of interfaces on the firewall.
  • Then, start with the WAN interface and click it.
  • After that, we have to set the configuration type for each interface to “None.”
  • Next, save and apply our changes.
  • We have to repeat this process for all other interfaces.

9)Finally, head to Routing under System and set “Default gateway IPv6” to “none.” Then click Save.

10)Additionally, we can create firewall rules to block IPv6 to help identify potential misconfigurations or issues. This step is optional but can be useful for monitoring.

After the above steps, we will no longer see IPv6 traffic in our logs.

PfSense: Настройка Site-to-Site

Для начала, думаю, стоит объяснить что такое pfSense и Site-to-Site VPN и в чем его преимущества. Затем перейдем к реализации.

pfSense – это дистрибутив межсетевого экрана основанный на операционной системе FreeBSD. Дистрибутив позволяет реализовать такие механизмы, как NAT, CARP, VPN (в т.ч. PPTP, IPsec, OpenVPN), Captive portal. Кроме этого выполняет функционал классического файрволла, динамического DNS, DHCP и прокси сервера. Прост в развертывании.

Почему Site-to-Site?

Site-to-Site позволяет сконфигурировать только шлюзы в удаленных подсетях, при этом отпадает необходимость конфигурирования самих узлов сети. Говоря простым языком, способ Site-to-Site соединяет два офиса в единую сеть, а Point-to-Site – удаленных сотрудников с офисом. В статье рассмотрим пример соединения двух уже существующих сетей – физической и виртуальной.

Процесс настройки условно разделим на два этапа:
  1. Настройка pfSense и конфигурирование частных сетей;
  2. Реализация Site-to-Site.

Приступаем.

Настройка pfSense

Сперва настроим внутреннюю локальную сеть и интерфейс шлюза. Для этого, в браузере, переходим по IP-адресу сервера или доменному имени, если такое имеется. Вводим логин и пароль и попадаем на Главный экран (Dashboard). В меню программы переходим в раздел интерфейсов (Interfaces) -> Назначение (Assignments). В нашем примере только два интерфейса и уже распределены – оставляем как есть. Если у Вас несколько интерфейсов, следует выбрать необходимый интерфейс по mac-адресу и нажать кнопку добавить (Add).

Назначаем IP-адрес интерфейсу “смотрящему” в локальную сеть. В меню программы переходим в раздел интерфейсов (Interfaces) -> LAN. По окончании настройки нажимаем кнопку Сохранить (Save).

Для всех серверов в локальной сети, в качестве шлюза по умолчанию, устанавливаем IP-адрес, указанный в LAN.

Важно! Если вы используете облачные сервисы, то объединять узлы сети необходимо из панели администрирования облачного сервиса через “Виртуальные сети”.

Настраиваем Firewall для локальных соединений.

В меню программы выбираем Firewall -> Правила (Rules) -> LAN. Наживаем кнопку Добавить (Add).

На новой странице проверяем параметры:

  • Настраиваемый интерфейс (Interface) – LAN;
  • Протокол (Protocol) – TCP, но можно и Any;
  • Источник (Source) – Any;
  • Назначение (Destination)- Any.
  • Настройки сохраняем кликнув по клавише Сохранить (Save).

Следует обратить внимание, что эти же настройки надо сделать на всех удаленных серверах pfSense, соединяемых в единую сеть.

Приступаем к настройке туннеля Site-to-Site.

В начале настраиваем OpenVPN. В главном меню выбираем VPN -> OpenVPN и кликаем по кнопке Добавить (Add).

На новой странице выбираем пункты (их конкретное расположение показано на скриншоте ниже):

  • Режим работы сервера (Server mode) – Peer to Peer (Shared Key);
  • Протокол (Protocol) – UDP on IPv4 only;
  • Device mode – tun – Layer 3 Tunnel Mode;
  • Интерфейс (Interface) – WAN;
  • Порт (Local port) – 1194;
  • Shared key – Устанавливаем галку напротив Automatically generate a shared key;
  • Алгоритм шифрования (Encryption algorithm) – оставляем по умолчанию;
  • Аппаратное шифрование (Hardware Crypto) – No hardware crypto acceleration;
  • IPv4 Tunnel Network: 10.0.10.0/24 – указываем адреса используемые в туннеле;
  • IPv4 Remote networks: 10.0.1.0/24 – указываем адрес сети находящийся за удаленным шлюзом pfSense.

Сохраняем настройки и не забываем кликнуть по зеленой кнопке Применить изменения (Apply Changes).

Настроим Firewall для нового интерфейса.

В главном меню выбираем Firewall -> Правила (Rules). Выбираем пункт OpenVPN и кликаем по кнопке Добавить (Add).

На обновленной странице проверяем параметры:

Интерфейс (Interface) – OpenVPN;

Протокол – TCP, но лучше Any;

Источник (Source) и назначение (Destination) – Any.

По окончании кликаем по кнопке Сохранить (Save). Не забываем кликнуть по зеленой кнопке Применить изменения (Apply Changes)

Настроим Firewall для интерфейса WAN.

В главном меню выбираем Firewall -> Правила (Rules). Выбираем пункт OpenVPN и кликаем по кнопке Добавить (Add).

  • Интерфейс (Interface) – WAN;
  • Протокол (Protocol) – UDP;

Диапазон портов назначения (Destination port range) в обоих выпадающих списках (From и To) выбираем OpenVPN (1194).

Сохраняем настройки. Не забываем кликнуть по зеленой кнопке Применить изменения (Apply Changes).

Теперь копируем сгенерированный ключ, для передачи его на удаленный маршрутизатор. В главном меню выбираем VPN -> OpenVPN. Кликаем по значку “Карандаш” (редактировать). На обновленной странице из пункта Shared Key копируем всё содержимое поля в текстовый редактор, например, Блокнот.

Осталось настроить удаленный pfSense-шлюз в качестве клиента.

В главном меню выбираем VPN -> OpenVPN и кликаем по пункту Clients, затем по кнопке Добавить (Add).

На открывшейся странице проверяем параметры (их конкретное расположение показано на скриншоте ниже):

  • Режим работы сервера (Server mode) – Peer to Peer (Shared Key);
  • Протокол (Protocol) – UDP on IPv4 only;
  • Device mode – tun – Layer 3 Tunnel Mode;
  • Интерфейс (Interface) – WAN;
  • Адрес сервера (Server host address) – указывается именно WAN интерфейс сервера, который настраивали ранее;
  • Порт (Local port) – 1194;
  • Shared key – Снимаем галку напротив Automatically generate a shared key;
  • Алгоритм шифрования (Encryption algorithm) – оставляем по умолчанию;
  • Аппаратное шифрование (Hardware Crypto) – No hardware crypto acceleration;
  • IPv4 Tunnel Network: 10.0.10.0/24 – указываем адреса используемые в туннеле;
  • IPv4 Remote networks: указываем адрес сети находящийся за удаленным сервером – шлюзом pfSense.

Кликаем Сохранить (Save). Затем по зеленой кнопке Применить изменения (Apply Changes).

Поздравляем! На этом настройка окончена.