Поиск по этому блогу

четверг, 22 октября 2015 г.

Exchange 2013 Spam Protection

В этой статье мы поговорим об особенностях работы и настройке RBL фильтров в Exchange 2013. Вкратце напомним о том, что такое RBL. Упрощенно RBL (Realtime Blackhole List) представляет собой сервис, хранящий базу данных, содержащую  список ip-адресов почтовых серверов, замеченных в рассылке спама. Чаще всего доступ к RBL осуществляется по протоколу DNS, поэтому такие сервисы называют также DNSBL (DNS Block Lists).
Почтовый сервер при получении письма от неизвестного отправителя может автоматически сверятся с такими списками и блокировать почту с ip адресов, перечисленных в базе. При обнаружении совпадения адреса отправителя со значением одного из RBL списков, в ответ на команду RCPT TO сервер выдает SMTP сообщение об ошибке 550 5.x.x, а отправитель получат соответствующий отбойник.
За функционал блокировки соединений на основе списков IP адресов в Exchange 2013 отвечает агент фильтрация подключений (Connection Filtering). Агент Connection Filtering включает в себя:
  • IP Block Lists – черный список IP адресов, почта с которых не принимается (запрещенные отправители)
  • IP Allow Lists — белый список IP адресов (разрешенные отправители)
  • RBL Providers – список провайдеров RBL
Первые два списка являются статическими и ведутся вручную администратором Exchang. В списке RBL провайдеров указывается список сторонних источников данных RBL, с которыми необходимо сверится при получении письма.
В Exchange 2007/2010 антиспам фильтрация включалась с помощью скрипта install-AntispamAgents.ps1, причем оба агента фильтрации (Connection Filtering и Content Filtering) устанавливались на одном сервере с ролью Hub Transport. В Exchange 2013 транспортная роль разбита на 2 составляющие: Front End Transport и Back End Transport, а функционал антиспам фильтрации разделен на 2 части. На сервере Front End выполняется фильтрация подключений (Connection Filtering), а на Back End – фильтрация содержимого (включает в себя IMF-фильтр — Exchange Intelligent Message Filter и агент обнаружения вирусов — Malware Agent).
В Exchange 2013, если роли CAS и Mailbox установлены на одном сервере, скрипт Install-AntispamAgents.ps1 устанавливает только агент контентной фильтрации. Это означает, что функционал RBL-фильтрации будет не доступен. Чтобы установить агент Connection Filtering, нужно воспользоваться командлетом Install-TransportAgent:
Install-TransportAgent -Name "Connection Filtering Agent" -TransportService FrontEnd -TransportAgentFactory "Microsoft.Exchange.Transport.Agent.ConnectionFiltering.ConnectionFilteringAgentFactory" -AssemblyPath "C:\Program Files\Microsoft\Exchange Server\V15\TransportRoles\agents\Hygiene\Microsoft.Exchange.Transport.Agent.Hygiene.dll"
Установка агента фильтрации подключений в Exchange 2013
После установки агента, его нужно включить и перезапустить службу Front End Transport:
Enable-TransportAgent -TransportService FrontEnd -Identity "Connection Filtering Agent"
Restart-Service MSExchangeFrontEndTransport

Включить агент фильтрации командой Enable-TransportAgent
Проверить, что агент фильтрации подключений установлен и работает можно так:
Get-TransportAgent -TransportService FrontEnd
Агент фильтрации Exchange 2013, реализующий RBL фильтрацию
Далее нужно задать используемых RBL провайдеров.
Примечание. Самыми популярными RBL провайдерами на данный момент являются Spamhaus и SpamCop.
Add-IPBlockListProvider -Name zen.spamhaus.org -LookupDomain zen.spamhaus.org -AnyMatch $true -Enabled $True
Чтобы изменить текст отбойника, возвращаемого отправителю, воспользуемся такой командой:
Set-IPBlockListProvider zen.spamhaus.org -RejectionResponse "Your IP address is listed by Spamhaus Zen. You can delete it on page http://www.spamhaus.org/lookup/”
Можно добавить сразу несколько RBL провайдеров, предварительно ознакомившись с их особенностями и политикой коммерческого использования.
Список используемых RBL можно вывести так:
Get-IPBlockListProvider

Get-IPBlockListProvider - список используемых RBL сервисов
Проверить наличие конкретного IP адреса на предмет присутствия в RBL списке можно так:
Test-IPBlockListProvider -Identity zen.spamhaus.org -IPAddress x.x.x.x
Логи агента Connection Filter по умолчанию сохраняются в каталог
C:\Program Files\Microsoft\Exchange Server\V15\TransportRoles\Logs\FrontEnd\AgentLog
После накопления первичной информации (зависит от объема почтового трафика, в среднем два – три дня), статистику результатов работы RBL фильтрации можно посмотреть с помощью командлета Get-AntispamTopRBLProviders.ps1
.\get-AntispamTopRBLProviders.ps1 -location "C:\Program Files\Microsoft\Exchange Server\V15\TransportRoles\Logs\FrontEnd\AgentLog"
get-AntispamTopRBLProviders.ps1 - статистика работы RBL фильтров
После начала использования RBL-фильтрации нужно внимательно изучить логи фильтрации на предмет  ложных срабатываний.
Списки RBL являются достаточно эффективным средством борьбы с нежелательной коррекспонденцией, но в большинстве случаем  для полноценной антиспам защиты нужно использовать их совместно с другими способами борьбы со спамом.

Просмотреть список компьютеров в Whitelist
Get-IPAllowListEntry
Добавить в White list
Add-IPAllowListEntry

To configure the spam confidence level (SCL) thresholds and actions, run the following command:

Set-ContentFilterConfig -SCLDeleteEnabled $true -SCLDeleteThreshold 7 -SCLRejectEnabled $false -SCLRejectThreshold 7 -SCLQuarantineEnabled $true -SCLQuarantineThreshold 6

If you set the SCL thresholds too high, you may not reduce the spam that enters your organization. If you set the SCL thresholds too low, the risk is that you will filter messages from legitimate users.

You can enable and set each SCL threshold action to a value between 0 and 9, where 0 is considered less likely to be spam, and 9 is considered more likely to be spam.

You enable and set the SCL thresholds and corresponding actions as follows:
  • Delete messages that have a SCL rating greater than or equal to   This option deletes the message but does not inform the sending server of the deletion. In fact, the computer that has the Edge Transport server role installed sends a fake "OK" Simple Mail Transfer Protocol (SMTP) command to the sending server and then deletes the message. Because the sending server assumes that the message was sent, the sending server does not retry to send the message in the same session.
  • Reject messages that have a SCL rating greater than or equal to   This option rejects the message and sends an SMTP error response to the sending server.
  • Quarantine messages that have a SCL rating greater than or equal to   This option quarantines the message and sends it to the spam quarantine mailbox that you specified. For more information about how to configure the spam quarantine mailbox, see How to Specify a Spam Quarantine Mailbox.

    Set-ContentFilterConfig -QuarantineMailbox spamQ@contoso.com

source1

source2

source3 

четверг, 26 февраля 2015 г.

Usefull AD commands

How to lock computers not logged in for last 4 weeks

dsquery computer -inactive 4 -limit 500 | dsmod computer -disabled yes

How to get a list of users in the OU with PowerShell

Get-ADUser -Filter * -SearchBase "ou=filial, dc=domain, dc=local"

How to get only names:

Get-ADUser -Filter * -SearchBase "ou=filial, dc=domain, dc=local" | fl Name

To write it into a file "d:\OUuserlist.txt":

Get-ADUser -Filter * -SearchBase "ou=filial, dc=domain, dc=local"  > d:\OUuserlist.txt

How many users are in certain OU
(Get-ADUser -SearchBase "ou=APK,ou=Users,ou=Offices,dc=local,dc=my,dc=ru" -ResultSetSize $null -LDAPFilter "(&(objectClass=user))").count

Get list with all computers in AD
Get-ADComputer -Filter * -Property * | Select-Object Name,OperatingSystem,Description | Export-CSV d:\AllWindows.csv -NoTypeInformation -Encoding UTF8

useful link