powershell -command "& {[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force}; Install-Module -Name PSWindowsUpdate -Force"
Get-WindowsUpdate
powershell -command "& {Install-WindowsUpdate -AcceptAll -AutoReboot}"
Install-WindowsUpdate -MicrosoftUpdate -AcceptAll -AutoReboot
Configuring Automated Security Updates on Debian
Updated Thursday, March 9, 2023, by HackerSploit
This guide was written for Debian. Other distributions are available:
Debian
Create a Linode account to try this guide with a $100 credit.
This credit will be applied to any valid services used during your first 60 days.Sign Up
Keeping your system up-to-date with the latest packages and security updates can be a tedious task. Most users forget to do it, leaving them vulnerable to countless threats. Automate security (and other package) updates with the utility Unattended Upgrades on Debian.
Before You Begin
- Complete the Getting Started guide.
- Follow the Setting Up and Securing a Compute Instance guide to create a standard user account, and harden SSH access.
- Log into your Linode via SSH and update and upgrade.
sudo apt update && sudo apt upgrade
Note
This guide is written for a non-root user. Commands that require elevated privileges are prefixed with sudo
. If you’re not familiar with the sudo
command, see our Users and Groups guide.
Install Unattended Upgrades
You can set up automated security updates on Debian by installing a helpful utility called unattended-upgrades
.
- Install it running the following command:
sudo apt install unattended-upgrades
- After the installation completes, you can enable and start the
unattended-upgrades
service by running the following commands:sudo systemctl enable unattended-upgrades
sudo systemctl start unattended-upgrades
This ensures that the service runs on system startup and is persistent throughout. - You now need to make changes to the configuration file. The default configuration file can be found here at
/etc/apt/apt.conf.d/50unattended-upgrades
. Open it with the text editor of your choice.
Note
The unattended-upgrades package ignores lines that start with //
, as that line is considered to be a comment. Therefore, if you want a repository to update automatically, you need to remove //
from that line.
- In our example, remove
//
from the “security” line if it’s there,"origin=Debian,codename=${distro_codename},label=Debian-Security";
. This section should look like the following:
...
Unattended-Upgrade::Origins-Pattern {
// Codename based matching:
// This will follow the migration of a release through different
// archives (e.g. from testing to stable and later oldstable).
// Software will be the latest available for the named release,
// but the Debian release itself will not be automatically upgraded.
// "origin=Debian,codename=${distro_codename}-updates";
// "origin=Debian,codename=${distro_codename}-proposed-updates";
"origin=Debian,codename=${distro_codename},label=Debian";
"origin=Debian,codename=${distro_codename},label=Debian-Security";
// Archive or Suite based matching:
// Note that this will silently match a different release after
// migration to the specified archive (e.g. testing becomes the
// new stable).
// "o=Debian,a=stable";
// "o=Debian,a=stable-updates";
// "o=Debian,a=proposed-updates";
// "o=Debian Backports,a=${distro_codename}-backports,l=Debian Backports";
};
...
Enabling Automatic Upgrades
To enable automatic updates create a new auto-upgrades file: /etc/apt/apt.conf.d/20auto-upgrades
using text editor of your choice.
This file allows you to define how often the auto updates take place.File: /etc/apt/apt.conf.d/20auto-upgrades
APT::Periodic::Update-Package-Lists "1"; APT::Periodic::Unattended-Upgrade "1"; APT::Periodic::AutocleanInterval "7"; |
- Update-Package-Lists:
1
enables auto-update,0
disables. - Unattended-Upgrade:
1
enables auto-upgrade,0
disables. - AutocleanInterval: Enables auto clean packages for
X
days. The above configuration displays 7 days- For example, APT::Periodic::AutocleanInterval “7”; means that the system clears the download archive every seven days.
Testing The Configuration
You can perform a dry run to test the configuration. The dry run command runs a test update but no actual changes take place.
You can run the dry run test by using the command:
sudo unattended-upgrades --dry-run --debug
This page was originally published on Thursday, October 22, 2020.
Модуль PSWindowsUpdate
WinITPro.ru / PowerShell / Windows 10 / Windows 11 / Windows Server 2019 / Модуль PSWindowsUpdate: управление обновлениями Windows из PowerShell
Модуль PSWindowsUpdate: управление обновлениями Windows из PowerShell
21.02.2022
PowerShell, Windows 10, Windows 11, Windows Server 2019
Вы можете использовать PowerShell модуль PSWindowsUpdate для управления обновлениями Windows из командной строки. Модуль PSWindowsUpdate не встроен в Windows и доступен для установки из репозитория PowerShell Gallery. PSWindowsUpdate позволяет администраторам удаленно проверять, устанавливать, удалять и скрывать обновления на рабочих станциях и серверах Windows. Модуль PSWindowsUpdate особо ценен при использовании для управления обновлениями в Core редакциях Windows Server (в которых отсутствуют графический интерфейс), а также при настройке образа Windows в режиме аудита.
Содержание:
- Установка модуля управления обновлениями PSWindowsUpdate
- Обзор команд модуля PSWindowsUpdate
- Управление обновлениями Windows на удаленных компьютерах через PowerShell
- Получить список доступных обновлений Windows из PowerShell
- Установка обновлений Windows с помощью Install-WindowsUpdate
- Просмотр истории установленных обновлений Windows (Get-WUHistory)
- Удаление обновлений в Windows с помощью Remove-WindowsUpdate
- Как скрыть ненужные обновления Windows с помощью PowerShell (Hide-WindowsUpdate)?
Установка модуля управления обновлениями PSWindowsUpdate
Если вы используете Windows 10/11 или Windows Server 2022/2019/2016, вы можете установить (обновить) модуль PSWindowsUpdate из онлайн репозитория через менеджер пакетов PackageManagement всего одной командой:
Install-Module -Name PSWindowsUpdate
После окончания установки нужно проверить наличие пакета:
Get-Package -Name PSWindowsUpdate

В старых версиях Windows 2012R2/Windows 8.1 и ниже при установке PowerShell модуля может появится ошибка:
Install-Module: Unable to download from URI.Unable to download the list of available providers. Check your internet connection.
Для установки модуля нужно использовать для подключения протокол TLS 1.2. Включите его:[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Если у вас установлена более старая версия Windows (Windows 7/8.1/ Windows Server 2008 R2/ 2012 R2) или отсутствует прямой доступ в Интернет, вы можете установить модуль PSWindowsUpdate вручную (см. полную инструкцию по офлайн установке модулей PowerShell).
- Скачайте модуль PSWindowsUpdate на любой онлайн компьютер:
Save-Module –Name PSWindowsUpdate –Path C:\ps\
; - Скопируйте модуль на целевой компьютер, и поместите его в каталог
%WINDIR%\System32\WindowsPowerShell\v1.0\Modules
(при постоянном использовании модуля это лучший вариант); - Разрешите выполнение PowerShell скриптов:
Set-ExecutionPolicy –ExecutionPolicy RemoteSigned -force
- Теперь вы можете импортировать модуль в свою сессию PowerShell:
Import-Module PSWindowsUpdate
Примечание. В Windows 7 / Server 2008 R2 при импорте модуля PSWindowsUpdate вы можете столкнутся с ошибкой вида: Имя "Unblock-File" не распознано как имя командлета
. Дело в том, что в модуле используются некоторые функции, которые появились только в PowerShell 3.0. Для использования этих функций вам придется обновить PowerShell, либо вручную удалить строку | Unblock-File из файла PSWindowsUpdate.psm1.
После установки модуля PSWindowsUpdate на своем компьютере вы можете удаленно установить его на другие компьютеры или сервера с помощью командлета Update-WUModule. Например, чтобы скопировать PSWindowsUpdate модуль с вашего компьютера на два удаленных сервера, выполните команды (нужен доступ к удаленным серверам по протоколу WinRM):
$Targets = "Server1", "Server2"
Update-WUModule -ComputerName $Targets -local
Чтобы сохранить модуль в сетевой каталог для дальнейшего импорта модуля на других компьютерах, выполните:
Save-Module -Name PSWindowsUpdate –Path \\fs01\ps\
Обзор команд модуля PSWindowsUpdate
Список доступных командлетов модуля можно вывести так:
get-command -module PSWindowsUpdate
Вкратце опишем назначение команд модуля:
- Clear-WUJob – использовать Get-WUJob для вызова задания WUJob в планировщике;
- Download-WindowsUpdate (алиас для Get-WindowsUpdate –Download) — получить список обновлений и скачать их;
- Get-WUInstall, Install-WindowsUpdate (алиас для Get-WindowsUpdate –Install) – установить обвновления;
- Hide-WindowsUpdate (алиас для Get-WindowsUpdate -Hide:$false) – скрыть обновление;
- Uninstall-WindowsUpdate -удалить обновление с помощью Remove-WindowsUpdate;
- Add-WUServiceManager – регистрация сервера обновления (Windows Update Service Manager) на компьютере;
- Enable-WURemoting — включить правила Windows Defender файервола, разрешающие удаленное использование командлета PSWindowsUpdate;
- Get-WindowsUpdate (Get-WUList) — выводит список обновлений, соответствующим указанным критериям, позволяет найти и установить нужное обновление. Это основной командлет модуля PSWindowsUpdate. Позволяет скачать и установить обновления с сервера WSUS или Microsoft Update. Позволяет выбрать категории обновлений, конкретные обновления и указать правила перезагрузки компьютера при установке обновлений;
- Get-WUApiVersion – получить версию агента Windows Update Agent на компьютере;
- Get-WUHistory – вывести список установленных обновлений (история обновлений);
- Get-WUInstallerStatus — проверка состояния службы Windows Installer;
- Get-WUJob – запуска заданий обновления WUJob в Task Scheduler;
- Get-WULastResults — даты последнего поиска и установки обновлений (LastSearchSuccessDate и LastInstallationSuccessDate);
- Get-WURebootStatus — позволяет проверить, нужна ли перезагрузка для применения конкретного обновления;
- Get-WUServiceManager – вывод источников обновлений;
- Get-WUSettings – получить настройки клиента Windows Update;
- Invoke-WUJob – удаленное вызов заданий WUJobs в Task Schduler для немедленного выполнения заданий PSWindowsUpdate.
- Remove-WindowsUpdate – удалить обновление;
- Remove-WUServiceManager – отключить Windows Update Service Manager;
- Set-PSWUSettings – сохранить настройки модуля PSWindowsUpdate в XML файл;
- Set-WUSettings – настройка параметров клиента Windows Update;
- Update-WUModule – обновить модуль PSWindowsUpdate (можно обновить модуль на удаленном компьютере, скопировав его с текущего, или обновить из PSGallery);
- Reset-WUComponents – позволяет сбросить настройка агента Windows Update на компьютере к настройкам по-умолчанию.

Чтобы проверить текущие настройки клиента Windows Update, выполните команду:
Get-WUSettings
ComputerName : WKS22122 WUServer : http://MS-WSUS:8530 WUStatusServer : http://MS-WSUS:8530 AcceptTrustedPublisherCerts : 1 ElevateNonAdmins : 1 DoNotConnectToWindowsUpdateInternetLocations : 1 TargetGroupEnabled : 1 TargetGroup : WorkstationsProd NoAutoUpdate : 0 AUOptions : 3 - Notify before installation ScheduledInstallDay : 0 - Every Day ScheduledInstallTime : 3 UseWUServer : 1 AutoInstallMinorUpdates : 0 AlwaysAutoRebootAtScheduledTime : 0 DetectionFrequencyEnabled : 1 DetectionFrequency : 4
В данном примере клиент Windows Update на компьютере настроен с помощью GPO на получение обновлений с локального сервера WSUS.
Команда Reset-WUComponents –Verbose
позволяет сбросить все настройки агента Windows Update, перерегистрировать библиотеки и восстановить исходное состояние службы wususerv.

Управление обновлениями Windows на удаленных компьютерах через PowerShell
Практически все командлеты модуля PSWindowsUpdate позволяют управлять установкой обновлений на удаленных компьютерах. Для этого используется атрибут -Computername Host1, Host2, Host3
. На удаленных компьютерах должен быть включен и настроен WinRM (вручную или через GPO).
Установите модуль PSWindowsUpdate на удаленных компьютерах и разрешите в файерволе доступ по динамическим RPC портам к процессу dllhost.exe. Можно использовать Invoke-Command для настройки модуля PSWindowsUpdate на удаленных компьютерах:
Invoke-Command -ComputerName $computer -ScriptBlock {Set-ExecutionPolicy RemoteSigned -force }
Invoke-Command -ComputerName $computer -ScriptBlock {Import-Module PSWindowsUpdate; Enable-WURemoting}
Модуль PSWindowsUpdate можно использовать для удаленного управлений обновлениями Windows как на компьютерах в домене AD, так и в рабочей группе (потребует определенной настройки PowerShell Remoting)
Для удаленного управления обновлениями компьютерах, нужно добавить имена компьютеров доверенных хостов winrm, или настроить удаленное управление PSRemoting через WinRM HTTPS:
winrm set winrm/config/client ‘@{TrustedHosts="HOST1,HOST2,…"}’
Или с помощью PowerShell:Set-Item wsman:\localhost\client\TrustedHosts -Value wsk-w10BO1 -Force
Получить список доступных обновлений Windows из PowerShell
Вывести список обновлений, доступных для данного компьютера на сервере обновлений можно с помощью команд Get-WindowsUpdate или Get-WUList.

Чтобы проверить список доступных обновлений на удаленном компьютере, выполните:
Get-WUList –ComputerName server2
Вы можете проверить, откуда должна получать обновления ваша ОС Windows. Выполните команду:
Get-WUServiceManager
ServiceID IsManaged IsDefault Name --------- --------- --------- ---- 8b24b027-1dee-babb-9a95-3517dfb9c552 False False DCat Flighting Prod 855e8a7c-ecb4-4ca3-b045-1dfa50104289 False False Windows Store (DCat Prod) 3da21691-e39d-4da6-8a4b-b43877bcb1b7 True True Windows Server Update Service 9482f4b4-e343-43b6-b170-9a65bc822c77 False False Windows Update

Как вы видите, компьютер настроен на получение обновлений с локального сервера WSUS (Windows Server Update Service = True). В этом случае вы должны увидеть список обновлений, одобренных для вашего компьютера на WSUS.
Если вы хотите просканировать ваш компьютер на серверах Microsoft Update (кроме обновлений Windows на этих серверах содержатся обновления Office и других продуктов) в Интернете, выполните команду:
Get-WUlist -MicrosoftUpdate
Вы получаете предупреждение:
Get-WUlist : Service Windows Update was not found on computer
Чтобы разрешить сканирование на Microsoft Update, выполните команду:
Add-WUServiceManager -ServiceID "7971f918-a847-4430-9279-4a52d1efe18d" -AddServiceFlag 7
Теперь можете выполнить сканирование на Microsoft Update. Как вы видите, в данном случае были найдены дополнительные обновления для Microsoft Visual C++ 2008 и Microsoft Silverlight.

Чтобы проверить версию агента Windows Update на компьютере, выполните команду:
Get-WUApiVersion
ComputerName PSWindowsUpdate PSWUModuleDll ApiVersion WuapiDllVersion ------------ --------------- ------------- ---------- --------------- FS01 2.2.0.2 2.2.0.2 8.0 10.0.19041.1320

Чтобы убрать определенные продукты или конкретные KB из списка обновлений, которые получает ваш компьютер, вы их можете исключить по:
- Категории (-NotCategory);
- Названию (-NotTitle);
- Номеру обновления (-NotKBArticleID).
Например, исключим из списка обновления драйверов, OneDrive и одну конкретную KB:
Get-WUlist -NotCategory "Drivers" -NotTitle OneDrive -NotKBArticleID KB4533002
Установка обновлений Windows с помощью Install-WindowsUpdate
Чтобы автоматически загрузить и установить все доступные обновления для вашей версии Windows с серверов Windows Update (вместо локального WSUS), выполните:
Install-WindowsUpdate -MicrosoftUpdate -AcceptAll -AutoReboot
Ключ AcceptAll включает одобрение установки для всех пакетов, а AutoReboot разрешает автоматическую перезагрузку Windows после установки обновлений.
Также можно использовать следующе параметры:
- IgnoreReboot – запретить автоматическую перезагрузку;
- ScheduleReboot – задать точное время перезагрузки компьютера.
Можете сохранить историю установки обновлений в лог файл (можно использовать вместо WindowsUpdate.log).
Install-WindowsUpdate -AcceptAll -Install -AutoReboot | Out-File "c:\$(get-date -f yyyy-MM-dd)-WindowsUpdate.log" -force
Можно установить только конкретные обновления по номерам KB:
Get-WindowsUpdate -KBArticleID KB2267602, KB4533002 -Install

В данном случае нужно подтверждать установку каждого обновления вручную.
Если вы хотите исключить некоторые обновления из списка на установку, выполните:
Install-WindowsUpdate -NotCategory "Drivers" -NotTitle OneDrive -NotKBArticleID KB4011670 -AcceptAll -IgnoreReboot
Модуль позволяет удаленно запустить установку обновлений сразу на нескольких компьютерах или серверах (на компьютерах должен присутствовать модуль PSWindowsUpdate). Это особенно удобно, так как позволяет администратору не заходить вручную на все сервера во время плановой установки обновлений. Следующая команда установит все доступные обновление на трех удаленных серверах:
ServerNames = “server1, server2, server3”
Invoke-WUJob -ComputerName $ServerNames -Script {ipmo PSWindowsUpdate; Install-WindowsUpdate -AcceptAll | Out-File C:\Windows\PSWindowsUpdate.log } -RunNow -Confirm:$false -Verbose -ErrorAction Ignore
Командлет Invoke-WUJob (ранее командлет назывался Invoke-WUInstall) создаст на удаленном компьютере задание планировщика, запускаемое от SYSTEM. Можно указать точное время для установки обновлений Windows:
Invoke-WUJob -ComputerName $ServerNames -Script {ipmo PSWindowsUpdate; Install-WindowsUpdate –AcceptAll -AutoReboot | Out-File C:\Windows\PSWindowsUpdate.log } -Confirm:$false -TriggerDate (Get-Date -Hour 20 -Minute 0 -Second 0)
Можно установить обновления на удаленном компьютере и отправить email отчет администратору:
Install-WindowsUpdate -ComputerName server1 -MicrosoftUpdate -AcceptAll - IgnoreReboot -SendReport –PSWUSettings @{SmtpServer="smtp.winitpro.ru";From="wualert@winitpro.ru";To="wuadmin@winitpro.ru";Port=25} -Verbose
Проверить статус задания установки обновления можно с помощью Get-WUJob:
Get-WUJob -ComputerName $ServerNames
Если команда вернет пустой список, значит задача установки на всех компьютерах выполнена.
Просмотр истории установленных обновлений Windows (Get-WUHistory)
С помощью команды Get-WUHistory вы можете получить список обновлений, установленных на компьютере ранее автоматически или вручную.

Можно получить информацию о дате установки конкретного обновления:
Get-WUHistory| Where-Object {$_.Title -match "KB4517389"} | Select-Object *|ft

Чтобы получить информацию об наличии установленного обновления на нескольких удаленных компьютерах, можно воспользоваться таким кодом:
"server1","server2" | Get-WUHistory| Where-Object {$_.Title -match "KB4011634"} | Select-Object *|ft
Проверить, нужна ли перезагрузка компьютеру после установки обновления:
Get-WURebootStatus –ComputerName WKS80JT

Проверьте значение атрибутов RebootRequired
и RebootScheduled
.
Получить дату последней установки обновлений на всех компьютерах в домене можно с помощью командлета Get-ADComputer из модуля AD PowerShell:
$Computers=Get-ADComputer -Filter {enabled -eq "true" -and OperatingSystem -Like '*Windows*' }
Foreach ($Computer in $Computers)
{
Get-WULastResults -ComputerName $Computer.Name|select ComputerName, LastSearchSuccessDate, LastInstallationSuccessDate
}
По аналогии можно найти компьютеры, которые не устаналивали обновления более 40 дней и вывести результат в графическую таблицу Out-GridView:
$result=@()
Foreach ($Computer in $Computers) {
$result+= Get-WULastResults -ComputerName $Computer.Name
}
$result| Where-Object { $_.LastInstallationSuccessDate -lt ((Get-Date).AddDays(-30)) }| Out-GridView
Удаление обновлений в Windows с помощью Remove-WindowsUpdate
Для корректного удаления обновлений используется командлет Remove-WindowsUpdate. Вам достаточно указать номер KB в качестве аргумента параметра KBArticleID. Чтобы отложить автоматическую перезагрузку компьютера можно добавить ключ –NoRestart
:
Remove-WindowsUpdate -KBArticleID KB4011634 -NoRestart
Как скрыть ненужные обновления Windows с помощью PowerShell (Hide-WindowsUpdate)?
Вы можете скрыть определенные обновления, чтобы они никогда не устанавливались службой обновлений Windows Update на вашем компьютер (чаще всего скрывают обновления драйверов). Например, чтобы скрыть обновления KB2538243 и KB4524570, выполните такие команды:
$HideList = "KB2538243", "KB4524570"
Get-WindowsUpdate -KBArticleID $HideList -Hide
или используйте alias:
Hide-WindowsUpdate -KBArticleID $HideList -Verbose

Теперь при следующем сканировании обновлений с помощью команды Get-WUlist
скрытые обновления не будут отображаться в списке доступных для установки патчей.
Вывести список обновлений, которые скрыты на данном компьютере можно так:
Get-WindowsUpdate –IsHidden
Обратите внимание, что в колонке Status у скрытых обновлений появился атрибут H (Hidden).

Отменить скрытие некоторых обновлений можно так:
Get-WindowsUpdate -KBArticleID $HideList -WithHidden -Hide:$false
или так:
Show-WindowsUpdate -KBArticleID $HideList
Для тех, кто себя некомфортно чувствует в консоли PowerShell, для управления обновлениями Windows 10 могу порекомендовать графическую утилиту Windows Update MiniTool.
PMG 7/Debian 11 with fail2ban
apt-get install fail2ban -y
nano /etc/fail2ban/jail.d/defaults-debian.conf
[DEFAULT]
banaction = nftables-multiport
banaction_allports = nftables-allports
nano /etc/fail2ban/jail.d/pmg-web-auth.conf
[pmg-web-auth]
enabled = true
port = https,http,8006
filter = pmg-web-auth
logpath = /var/log/daemon.log
maxretry = 2
# 1 hour
bantime = 3600
nano /etc/fail2ban/filter.d/pmg-web-auth.conf
[Definition]
failregex = pmgdaemon\[.*authentication failure; rhost=<HOST> user=.* msg=.*
ignoreregex =
systemctl restart fail2ban
systemctl enable fail2ban
fail2ban-client status pmg-web-auth
systemctl status fail2ban
fail2ban-regex /var/log/daemon.log /etc/fail2ban/filter.d/pmg-web-auth.conf
Configuring Fail2Ban on Zimbra
Configuring Fail2Ban on Zimbra
by Barry De Graaff on August 24, 2022 in Product News, Community, Open Source, Security & Privacy
This article is a how-to guide on installing Fail2Ban to block attacking hosts using a null route or blackhole routes. This can help mitigate brute force attacks on Zimbra. Especially brute force attacks on SMTP are very common.
Prerequisite:
Fail2ban has been tested in combination with netfilter-persistent and iptables. If you use ufw or firewalld you may see errors when trying to ban/unban such as ERROR Failed to execute ban jail … action ‘route’. This article has been validated using a set-up installed using https://github.com/Zimbra/zinstaller which you can use to test fail2ban before applying to your production environment.
It is required the OIP configuration must be done before configuring
Fail2Ban service.
For a Single-Server Setup:
If you are running nginx on the same node as the mailstore, you will
need to add both 127.0.0.1 and the real IP address of that node:
sudo -u zimbra –
zmprov mcf +zimbraMailTrustedIP 127.0.0.1 +zimbraMailTrustedIP {IP of Server}
zmcontrol restart
For a Multi-Server Setup:
sudo -u zimbra –
zmprov mcf +zimbraHttpThrottleSafeIPs {IP of Mailbox-1}
zmprov mcf +zimbraHttpThrottleSafeIPs {IP of Mailbox-2}
zmprov mcf +zimbraMailTrustedIP {IP of Proxy-1}
zmprov mcf +zimbraMailTrustedIP {IP of Proxy-2}
zmcontrol restart
Installation and Configuration of Fail2Ban
1) Install Fail2Ban Package
On RHEL/CentOS 7/8:
yum install epel-release -y
yum install fail2ban -y
On Ubuntu 18/20:
apt-get clean all ; apt-get update
apt-get install fail2ban -y
2) Create a file /etc/fail2ban/jail.local and it will
override the default conf file /etc/fail2ban/jail.conf.
Add the local IP address of the Zimbra server in ignoreip =. You
can also add other IP addresses to ignore from Fail2Ban checking.
On a multi-server setup, add all server’s IP in ignoreip list.
nano /etc/fail2ban/jail.local
[DEFAULT]
"ignoreip" can be a list of IP addresses, CIDR masks or DNS hosts.
Fail2ban will not ban a host which matches an address in this list.
Several addresses can be defined using space (and/or comma) separator.
ignoreip = 127.0.0.1/8 ::1 10.137.26.29/32
ignoreip = 127.0.0.1/8 IP-ADDRESS-OF-ZIMBRA-SERVER/32
banaction = route
3) Create a jail file for Zimbra services.
nano /etc/fail2ban/jail.d/zimbra.local
[zimbra-smtp]
enabled = true
filter = zimbra-smtp
port = 25,465,587
logpath = /var/log/zimbra.log
maxretry = 3
findtime = 86400
bantime = 86400
action = route
[zimbra-web]
enabled = true
filter = zimbra-web
port = 80,443,7071,9071
logpath = /opt/zimbra/log/mailbox.log
maxretry = 5
findtime = 86400
bantime = 86400
action = route
Update: This article uses a regular expression that should work on most Zimbra deployments. To avoid double banning/unbanning which may lead to unpredictable results and errors this article combines the WebUI and Admin WebUI into a single jail called zimbra-web. This does mean that for most deployments a failed login will be counted double. So maxretry = 5 actually means you can try 3 times before being banned.
PROPERTY DESCRIPTION
ignoreip
This parameter identifies IP address that should be ignored by the banning system. By default, this is just set to ignore traffic coming from the machine itself, which is a pretty good setting to have.
banaction
This sets the action that will be used when the threshold is reached. There is actually the name of a file located in ’`/etc/fail2ban/action.d/’’ which calls the configured action using the .conf file. Here we configured route which calls route.conf to handle the routing table manipulation to ban an IP address.
findtime
This parameter sets the window that fail2ban will pay attention to when looking for repeated failed authentication attempts. The default is set to 600 seconds (10 minutes again), which means that the software will count the number of failed attempts in the last 10 minutes.
bantime
This parameter sets the length of a ban, in seconds.
maxretry
This sets the number of failed attempts that will be tolerated within the findtime window before a ban is instituted.
4) [Optional]
If you want to apply Fail2Ban for SSH then create jail file
sshd.local.
(No need to create filter rules for SSH, Fail2ban by default shipped
with filter rules for SSH)
On Ubuntu systems, SSH jail is by default enabled within the jail file
“/etc/fail2ban/jail.d/defaults-debian.conf”.
nano /etc/fail2ban/jail.d/sshd.local
[sshd]
enabled = true
port = 22
maxretry = 3
findtime = 600
bantime = 3600
5) Create filters for Zimbra services.
nano /etc/fail2ban/filter.d/zimbra-web.conf
[Definition]
failregex = .ip=;.authentication failed for .*$
ignoreregex =
nano /etc/fail2ban/filter.d/zimbra-smtp.conf
[Definition]
failregex = postfix\/submission\/smtpd[\d+]: warning: .[]: SASL \w+ authentication failed: authentication failure$ postfix\/smtps\/smtpd[\d+]: warning: .[]: SASL \w+ authentication failed: authentication failure$
ignoreregex =
6) Restart the Fail2ban service and enable it to start after system
reboot.
systemctl restart fail2ban
systemctl status fail2ban
systemctl enable fail2ban
7) Check the status of the Fail2Ban jails.
fail2ban-client status
The result should be similar to this:
[root@centos8 ~]# fail2ban-client status
Status
|- Number of jail: 3- Jail list: sshd, zimbra-smtp, zimbra-web [root@centos8 ~]# [root@centos8 ~]# fail2ban-client status sshd Status for the jail: sshd |- Filter | |- Currently failed: 0 | |- Total failed: 14 |
– Journal matches: _SYSTEMD_UNIT=sshd.service + _COMM=sshd- Actions |- Currently banned: 1 |- Total banned: 2
– Banned IP list: 10.137.26.29
8) Check banned IP in routing table.
ip r
route -n
The result should be similar to this:
[root@centos8 ~]# ip r
default via 10.0.10.1 dev ens3
10.0.10.0/24 dev ens3 proto kernel scope link src 10.0.10.67
unreachable 10.137.26.29
[root@centos8 ~]#
[root@centos8 ~]# route -n
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
0.0.0.0 10.0.10.1 0.0.0.0 UG 0 0 0 ens3
10.0.10.0 0.0.0.0 255.255.255.0 U 0 0 0 ens3
10.137.26.29 – 255.255.255.255 !H 0 – 0 –
[root@centos8 ~]#
9) Ban and unban an IP manually.
Ban an IP address.
fail2ban-client set “Jail-Name” banip “IP-Address”
Example:
fail2ban-client set sshd banip 10.137.26.29
Unban an IP address.
fail2ban-client set “Jail-Name” unbanip “Banned IP-Address”
Example:
[root@centos8 ~]# fail2ban-client set sshd unbanip 10.137.26.29
Unban everyone.
Can be useful when something goes wrong with creating new RegEx filter:
fail2ban-client unban –all
Debugging of Fail2Ban:
The loglevel and target are configured in
/etc/fail2ban/fail2ban.conf you can also obtain the log level
and log target by running:
fail2ban-client get loglevel
fail2ban-client get logtarget
To watch the log for debugging purpose you can run:
tail -f $(fail2ban-client get logtarget | grep “`” | awk ‘{ print $2; }’)
Fail2ban works by parsing log files using regular expressions, you can test the regular expression by using fail2ban-regex like this:
fail2ban-regex /opt/zimbra/log/mailbox.log /etc/fail2ban/filter.d/zimbra-web.conf
Multi server and centralized syslog
Fail2ban is designed to work on the local server. So it does it’s ban actions on the same server where it reads the logs. This can be a problem if you run Zimbra in a multi server scenario, where you can read the logs on the mailbox server, but want to apply the ban on the proxy server.
In addition you may want to use a centralized logging server and if you decide to ban a bad actor, deny access to all servers in your environment.
To do this you would need to create a custom fail2ban action. And set up SSH public key authentication so the server where you run fail2ban can connect to the server where the ban action needs to be applied. This article is not meant to cover all possible scenarios, but to get you started here is a basic example:
Create a new action by copying the default route action:
cp /etc/fail2ban/action.d/route.conf /etc/fail2ban/action.d/remote-route.conf
Next replace the local ip route command with an SSH command to run remotely, from this:
[Definition]
actionban = ip route add
actionunban = ip route del
actioncheck =
actionstart =
actionstop =
[Init]
Option: blocktype
Note: Type can be blackhole, unreachable and prohibit. Unreachable and prohibit correspond to the ICMP reject messages.
Values: STRING
blocktype = unreachable
To this:
[Definition]
actionban = ssh root@remote-server -C ip route add
actionunban = ssh root@remote-server -C ip route del
actioncheck =
actionstart =
actionstop =
[Init]
blocktype = unreachable
Then configure fail2ban to use the new action, in /etc/fail2ban/jail.local and /etc/fail2ban/jail.d/zimbra.local change
banaction = route
…
action = route
to:
banaction = remote-route
…
action = remote-route
Please note that this is meant to be a simple example to get you started, it is probably best NOT to use the root account on the remote server. But for testing this is the easiest. Once you have an idea of how it works, you will probably want to wrap the remote banaction into a script and use sudo on an account with limited access.
Which would lead to something like:
[Definition]
actionban = /usr/local/sbin/my-banaction-script
actionunban = /usr/local/sbin/my-unbanaction-script
…
Then in /usr/local/sbin/my-banaction-script you could run the banaction to any number over servers over SSH, something like:
!/bin/bash
ssh banuser@remote-proxy1 -C sudo ip route del $1 $2 &
ssh banuser@remote-proxy2 -C sudo ip route del $1 $2 &
…etc
Zimbra after 8.8.XX Update
No html email body content fix:
zmlocalconfig -e zimbra_use_owasp_html_sanitizer=FALSE
zmmailboxdctl restart
RDS 2019 – default printer changes after reconnect
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Print\Providers\Client Side Rendering Print Provider
REG_DWORD: RemovePrintersAtLogoff
VALUE: 0
This will basically prevent the printers being removed each time the users log off/disconnect which will subsequently prevent the corruptions.
Reset Windows Update components manually
net stop bits
net stop wuauserv
net stop cryptsvc
Del “%ALLUSERSPROFILE%\Application Data\Microsoft\Network\Downloader\qmgr*.dat”
%Systemroot%\SoftwareDistribution\DataStore
%Systemroot%\SoftwareDistribution\Download
%Systemroot%\System32\catroot2
sc.exe sdset bits D:(A;CI;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;IU)(A;;CCLCSWLOCRRC;;;SU)
sc.exe sdset wuauserv D:(A;;CCLCSWRPLORC;;;AU)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;SY)
cd /d %windir%\system32
regsvr32.exe atl.dll
regsvr32.exe urlmon.dll
regsvr32.exe mshtml.dll
regsvr32.exe shdocvw.dll
regsvr32.exe browseui.dll
regsvr32.exe jscript.dll
regsvr32.exe vbscript.dll
regsvr32.exe scrrun.dll
regsvr32.exe msxml.dll
regsvr32.exe msxml3.dll
regsvr32.exe msxml6.dll
regsvr32.exe actxprxy.dll
regsvr32.exe softpub.dll
regsvr32.exe wintrust.dll
regsvr32.exe dssenh.dll
regsvr32.exe rsaenh.dll
regsvr32.exe gpkcsp.dll
regsvr32.exe sccbase.dll
regsvr32.exe slbcsp.dll
regsvr32.exe cryptdlg.dll
regsvr32.exe oleaut32.dll
regsvr32.exe ole32.dll
regsvr32.exe shell32.dll
regsvr32.exe initpki.dll
regsvr32.exe wuapi.dll
regsvr32.exe wuaueng.dll
regsvr32.exe wuaueng1.dll
regsvr32.exe wucltui.dll
regsvr32.exe wups.dll
regsvr32.exe wups2.dll
regsvr32.exe wuweb.dll
regsvr32.exe qmgr.dll
regsvr32.exe qmgrprxy.dll
regsvr32.exe wucltux.dll
regsvr32.exe muweb.dll
regsvr32.exe wuwebv.dll
netsh winsock reset
net start bits
net start wuauserv
net start cryptsvc
Openvas installation log
apt-get upgrade
sudo apt install openvas
gvm-setup
systemctl enable gvmd.service
systemctl enable redis-server
systemctl enable gsad
systemctl enable ospd-openvas
cd /lib/systemd/system
nano gsad.service
##replace 127.0.0.1 to 0.0.0.0
reboot
sudo runuser -u _gvm — gvmd –user=admin –new-password=newstrongpassword
sudo runuser -u _gvm — greenbone-nvt-sync