Перейти из форума на сайт.

НовостиФайловые архивы
ПоискАктивные темыТоп лист
ПравилаКто в on-line?
Вход Забыли пароль? Первый раз на этом сайте? Регистрация
Компьютерный форум Ru.Board » Компьютеры » В помощь системному администратору » Брутфорс по RDP и скрипт для блокировки

Модерирует : lynx, Crash_Master, dg, emx, ShriEkeR

 Версия для печати • ПодписатьсяДобавить в закладки

Открыть новую тему     Написать ответ в эту тему

dekstero4eg

Full Member
Редактировать | Профиль | Сообщение | Цитировать | Сообщить модератору
Добрый день. Есть несколько VDS на Windows 2008R2, которые с недавних пор начали брутфорсить на предмет подбора пароля администратора. В логах постоянно записи вида

Код:
 
Учетной записи не удалось выполнить вход в систему.
Субъект:
    ИД безопасности:        NULL SID
    Имя учетной записи:        -
    Домен учетной записи:        -
    Код входа:        0x0
 
Тип входа:            3
 
Учетная запись, которой не удалось выполнить вход:
    ИД безопасности:        NULL SID
    Имя учетной записи:        administrator
    Домен учетной записи:        
 
Сведения об ошибке:
    Причина ошибки:        Неизвестное имя пользователя или неверный пароль.
    Состояние:            0xc000006d
    Подсостояние:        0xc000006a
 
Сведения о процессе:
    Идентификатор процесса вызывающей стороны:    0x0
    Имя процесса вызывающей стороны:    -
 
Сведения о сети:
    Имя рабочей станции:    
    Сетевой адрес источника:    116.206.157.244
    Порт источника:        9625
 

Отсекать на сетевом оборудовании таких взломщиков нет возможности, блокировать учётную запись, как видите, тоже. Поблокировал немного руками IP-адреса с помощью файрвола Windows, IP-адреса примерно через час обновляются и всё по новой.  
Попробовал это дело заскриптовать с помощью PowerShell, нашёл в сети скрипт, для Win2008. Содержание следующее:

Код:
 #Dong Xie, March 2012
 #my simple code to monitor attack and deal with it
 #Windows Server 2008 Logon Type
 #10: RemoteInteractive, i.e. RDP
 
 $tick = 0;
 "Start to run at: " + (get-date);
 
 $regex1 = [regex] "1\.1\.1\.1:3389\s+(\d+\.\d+\.\d+\.\d+)";
 $regex2 = [regex] "Source Network Address:\t(\d+\.\d+\.\d+\.\d+)";
 
 while($True) {
  $blacklist = @();
 
  "Running... (tick:" + $tick + ")"; $tick+=1;
 
 #Port 3389
 $a = @()
 netstat -no | Select-String ":3389" | ? { $m = $regex1.Match($_); `
   $ip = $m.Groups[1].Value; if ($m.Success -and $ip -ne "10.0.0.1") {$a = $a + $ip;} }
 
 if ($a.count -gt 0) {
   $ips = get-eventlog Security -Newest 1000 | Where-Object {$_.EventID -eq 4625 -and $_.Message -match "Logon Type:\s+10"} | foreach { `
     $m = $regex2.Match($_.Message); $ip = $m.Groups[1].Value; $ip; } | Sort-Object | Tee-Object -Variable list | Get-Unique
 
   foreach ($ip in $a) { if ($ips -contains $ip) {
     if (-not ($blacklist -contains $ip)) {
       $attack_count = ($list | Select-String $ip -SimpleMatch | Measure-Object).count;
       "Found attacking IP on 3389: " + $ip + ", with count: " + $attack_count;
       if ($attack_count -ge 20) {$blacklist = $blacklist + $ip;}
     }  
    }
   }
 }
   
 #Firewall change
 
 foreach ($ip in $blacklist) {
 
   $fw=New-object –comObject HNetCfg.FwPolicy2;
   $myrule = $fw.Rules | where {$_.Name -eq "MY BLACKLIST"} | select -First 1; # Potential bug here?
 
   if (-not ($myrule.RemoteAddresses -match $ip) -and -not ($ip -like "10.0.0.*"))
     {
       "Adding this IP into firewall blocklist: " + $ip;  
       $myrule.RemoteAddresses+=("," + $ip);
     }
 }
 
 Wait-Event -Timeout 30 #pause 30 secs
 
 }    
 
При попытке запустить вылазят следующие ошибки

Код:
 
В строке, начинающейся с:
C:\scr2.ps1:46 знак:33
+        $myrule.RemoteAddresses+=(", <<<< " + $ip);,
 отсутствует терминатор: ".
C:\scr2.ps1:52 знак:6
+  }             <<<<
    + CategoryInfo          : ParserError: ( + $ip);
     ... secs
 
 }            :String) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : TerminatorExpectedAtEndOfString
 

Может кто-то помочь с этими ошибками? Проблема в том, что скрипт написан под 2008, а у меня 2008R2? Ну или если у кого есть рабочий скрипт для подобных целей на 2008R2, то буду очень благодарен.

Всего записей: 441 | Зарегистр. 29-06-2009 | Отправлено: 12:57 04-11-2019
alexnov66



Advanced Member
Редактировать | Профиль | Сообщение | Цитировать | Сообщить модератору
dekstero4eg
Уже есть тема по этому вопросу

Всего записей: 1195 | Зарегистр. 29-08-2005 | Отправлено: 17:33 04-11-2019
dekstero4eg

Full Member
Редактировать | Профиль | Сообщение | Цитировать | Сообщить модератору
alexnov66
Тему эту я читал, история там совсем другая. В моём случае не подойдёт блокировка учётной записи, нет возможности ловить всё это на сетевом оборудовании, ибо VDS. Смена порта не помогает, брут начинается уже через минуту после рестарта службы. И единственный вариант - это скриптом помещать проблемные IP-адреса в правила файрвола. Об этом и тема, и соответствующей помощи я и прошу.

Всего записей: 441 | Зарегистр. 29-06-2009 | Отправлено: 19:38 04-11-2019
Paromshick



Silver Member
Редактировать | Профиль | Сообщение | Цитировать | Сообщить модератору
dekstero4eg
Вы предлагаете не помощь, а рецепт.
Вообще, принято писать в одной теме. собирая все рецепты воедино.
И в той теме есть "рецепт" http://forum.ru-board.com/topic.cgi?forum=35&topic=52788#1

----------
Скучно

Всего записей: 3019 | Зарегистр. 12-04-2013 | Отправлено: 20:50 04-11-2019
dekstero4eg

Full Member
Редактировать | Профиль | Сообщение | Цитировать | Сообщить модератору
Paromshick
За ссылку спасибо, есть интересные варианты со сторонним ПО. Но я в итоге взял за основу другой скрипт и другой алгоритм отлова, проблему с атаками решил. Если кому понадобится - вот отсюда взят скрипт https://social.technet.microsoft.com/Forums/ru-RU/6cb49bf6-1cdc-46ac-bc27-0c5b62ce0a59/-powershell?forum=ws2008r2ru  
Несмотря на заголовок темы, всё в планировщике нормально отрабатывает

Всего записей: 441 | Зарегистр. 29-06-2009 | Отправлено: 18:42 05-11-2019 | Исправлено: dekstero4eg, 18:43 05-11-2019
Yura12

Member
Редактировать | Профиль | Сообщение | ICQ | Цитировать | Сообщить модератору
 
А так ведь можно же во встроенном брандмауэре наоборот, сделать разрешение на подключение к рабочему столу только с заданных сетей.
 

Всего записей: 253 | Зарегистр. 06-01-2010 | Отправлено: 13:22 06-11-2019
fscpsd



Advanced Member
Редактировать | Профиль | Сообщение | Цитировать | Сообщить модератору
Если по каким-то причинам встроенный брандмауэр не работает, можно воспользоваться сторонним, к примеру winipfw. У меня из-за кривого наследования политик домена тоже не работал толком брандмауэр на винсервере, и winipfw отлично решил проблему.

Всего записей: 1731 | Зарегистр. 16-09-2010 | Отправлено: 08:07 10-11-2019
dimakdv

Newbie
Редактировать | Профиль | Сообщение | Цитировать | Сообщить модератору
Есть еще такой скриптик (допиливал под себя). Создает правило и добавляет в него IP с которых была атака.
Должен работать на 2008 , 2016 и 2019. на 2012 не работает из-за другой политики записи в журнал безопасности.
Вешаете скрипт на событие 4625 в журнале безопасности.
 

Код:
 
 
 
# Set number of failed login attempts after which an IP address will be blocked
$int_block_limit = 5
 
# Time window during which to check the Security log, which is currently set to check only the last 24 hours
$dat_time_window = [DateTime]::Now.AddDays(-1)
 
# Select from the Security log all IP addresses that have more than $int_block_limit audit failures (event 4625) within $dat_time_window
$arr_new_bad_ips_security_log = @()
$arr_new_bad_ips_security_log = Get-EventLog -LogName 'Security' -InstanceId 4625 -After $dat_time_window |
    Select-Object @{n='IpAddress';e={$_.ReplacementStrings[-2]}} |
    Group-Object -property IpAddress |
    Where {$_.Count -ge $int_block_limit} |
    Select -property Name
 
# Get current time UTC to figure out filename for current FTP log
$current_date_utc = (Get-Date).ToUniversalTime()
 
# Set path to today's FTP log file
#$str_log_file_name = "C:\inetpub\logs\LogFiles\FTPSVC2\u_ex" + $current_date_utc.ToString("yyMMdd") + ".log"
 
# Search today's FTP log file for "530 1326" to find lines that contain IPs of systems that failed to log in,
# get just the IP from each line, group the IPs by IP to count the attempts from each one, and select only the
# IPs that have $int_block_limit or more bad logins today
#$arr_new_bad_ips_ftp = @()
#$arr_new_bad_ips_ftp = Select-String $str_log_file_name -pattern "530 1326" |
#    ForEach-Object {$_.Line.Substring(20,15) -replace " .*", ""} |
#    Group |
#    Where {$_.Count -ge $int_block_limit} |
#    Select -property Name
 
# Concatenate the two arrays of IPs (one from Security log, one from FTP log)
$arr_new_bad_ips_all = @()
# $arr_new_bad_ips_all = @($arr_new_bad_ips_security_log) + @($arr_new_bad_ips_ftp_over_limit)
$arr_new_bad_ips_all = @($arr_new_bad_ips_security_log) + @($arr_new_bad_ips_ftp)
 
# Sort the array, selecting only unique IPs (in case one IP shows up in both the Security and FTP logs)
$arr_new_bad_ips_all_sorted = @()
$arr_new_bad_ips_all_sorted = $arr_new_bad_ips_all |
    Foreach-Object { [string]$_.Name } |
    Select-Object -unique
 
# Get firewall object
$firewall = New-Object -comobject hnetcfg.fwpolicy2
 
# Get all firewall rules matching "BlockAttackers*"
$arr_firewall_rules = $firewall.Rules | Where {$_.Name -like 'BlockAttackers*'}
 
# If no "BlockAttackers*" firewall rule exists yet, create one and set it to a variable
if ($arr_firewall_rules -eq $null) {
    $str_new_rule_name = "BlockAttackers (Created " + $current_date_utc.ToString("yyyy-MM-dd HH:mm:ss") + " UTC)"
    netsh advfirewall firewall add rule dir=in action=block name=$str_new_rule_name description="Rule automatically created by BlockAttackers Powershell script written by Kevin Micke." enable=yes remoteip="0.0.0.0" | Out-Null
    $arr_firewall_rules = $firewall.Rules | Where {$_.Name -like 'BlockAttackers*'}
}
 
# Split the existing IPs from current "BlockAttackers*" firewall rule(s) into an array so we can easily search them
$arr_existing_bad_ips = @()
foreach ($rule in $arr_firewall_rules) {
    $arr_existing_bad_ips += $rule.RemoteAddresses -split(',')
}
 
# Clean subnet masks off of IPs that are currently blocked by the firewall rule(s)
$arr_existing_bad_ips_without_masks = @()
$arr_existing_bad_ips_without_masks = $arr_existing_bad_ips | ForEach-Object {$_ -replace "/.*", ""}
 
# Select IP addresses to add to the firewall, but only ones that...
$arr_new_bad_ips_for_firewall = @()
$arr_new_bad_ips_for_firewall = $arr_new_bad_ips_all_sorted | Where {
    # contain an IP address (i.e. aren't blank or a dash, which the Security log has for systems that failed FTP logins)
    $_.Length -gt 6 -and
    # aren't already in the firewall rule(s)
    !($arr_existing_bad_ips_without_masks -contains $_) -and
    # aren't the local loopback
    !($_.StartsWith('127.0.0.1')) -and
    # aren't part of the local subnet
    !($_.StartsWith('192.168.')) -and
    !($_.StartsWith('10.0.'))    
}
 
# If there are IPs to block, do the following...
if ($arr_new_bad_ips_for_firewall -ne $null) {
    # Write date and time to script-specific log file
    [DateTime]::Now | Out-File -Append -Encoding utf8 C:\blockattackers.txt
    # Write newly-blocked IP addresses to log file
    $arr_new_bad_ips_for_firewall | Out-File -Append -Encoding utf8 C:\blockattackers.txt
    $arr_new_bad_ips_for_firewall | Out-File -Append -Encoding utf8 C:\block-IP.txt
    # Boolean to make sure the new IPs are only added on one rule
    $bln_added_to_rule = 0
 
    # Array to hold bad IPs from each rule one at a time, so we can count to make sure adding the new ones won't exceed 1000 IPs
    $arr_existing_bad_ips_current_rule = @()
 
    # For each "BlockAttackers*" rule in the firewall, do the following...
    foreach ($rule in $arr_firewall_rules) {
        if ($bln_added_to_rule -ne 1) {
            # Split the existing IPs from the current rule into an array so we can easily count them
            $arr_existing_bad_ips_current_rule = $rule.RemoteAddresses -split(',')
 
            # If the number of IPs to add is less than 1000 minus the current number of IPs in the rule, add them to this rule
            if ($arr_new_bad_ips_for_firewall.Count -le (1000 - $arr_existing_bad_ips_current_rule.Count)) {
                # Add new IPs to firewall rule
                $arr_new_bad_ips_for_firewall | %{$rule.RemoteAddresses += ',' + $_}
 
                # Write which rule the IPs were added to to log file
                echo "New IP addresses above added to Windows Firewall rule:" $rule.Name | Out-File -Append -Encoding utf8 C:\blockattackers.txt
 
                # Set boolean so any other rules are skipped when adding IPs
                $bln_added_to_rule = 1
            }
        }
    }
 
    # If there wasn't room in any other "BlockAttackers*" firewall rule, create a new one and add the IPs to it
    if ($bln_added_to_rule -ne 1) {
        $str_new_rule_name = "BlockAttackers (Created " + $current_date_utc.ToString("yyyy-MM-dd HH:mm:ss") + " UTC)"
        netsh advfirewall firewall add rule dir=in action=block name=$str_new_rule_name description="Rule automatically created by BlockAttackers Powershell script written by Kevin Micke." enable=yes remoteip="0.0.0.0" | Out-Null
        $new_rule = $firewall.rules | Where {$_.Name -eq $str_new_rule_name}
 
        # Add new IPs to firewall rule
        $arr_new_bad_ips_for_firewall | %{$new_rule.RemoteAddresses += ',' + $_}
 
        # Write which rule the IPs were added to to log file
        echo "New IP addresses above added to newly created Windows Firewall rule:" $new_rule.Name | Out-File -Append -Encoding utf8 C:\blockattackers.txt
    }
}
 

Всего записей: 3 | Зарегистр. 25-03-2014 | Отправлено: 14:57 05-12-2019 | Исправлено: dimakdv, 15:09 05-12-2019
Paromshick



Silver Member
Редактировать | Профиль | Сообщение | Цитировать | Сообщить модератору
Любой дурак должен понять, что скрипт безусловно на языке скриптовом, а уж как его вешать - это к палачу вопросы.
Как палач палачу, можете сказать: у вас ботинки какого размера?
 
Добавлено:
Причём закломентирваны в общем-то не комментарии.
К стеночке станьте лицом на минуточку.

----------
Скучно

Всего записей: 3019 | Зарегистр. 12-04-2013 | Отправлено: 20:41 06-12-2019
Открыть новую тему     Написать ответ в эту тему

Компьютерный форум Ru.Board » Компьютеры » В помощь системному администратору » Брутфорс по RDP и скрипт для блокировки


Реклама на форуме Ru.Board.

Powered by Ikonboard "v2.1.7b" © 2000 Ikonboard.com
Modified by Ru.B0ard
© Ru.B0ard 2000-2024

BitCoin: 1NGG1chHtUvrtEqjeerQCKDMUi6S6CG4iC

Рейтинг.ru