2014년 2월 5일 수요일

윈도우 리부팅 되었던 날짜 확인.

Windows NT 4.0 서비스 팩 4를 설치하면 시스템 시작 시간과 종료 시간이 기록되고 아래와 같은 이벤트 ID와 함께 이벤트 로그에도 이들 시간이 기록됩니다.

  • 이벤트 6005는 이벤트 로그 서비스가 시작되었음을 알리기 위해 부팅할 때 기록됩니다.

  • 이벤트 6006은 정상 종료(Clean Shutdown) 시 기록됩니다.

  • 이벤트 6008은 비정상 종료(Dirty Shutdown) 시 기록됩니다.

  • 이벤트 6009는 부팅할 때마다 기록되며 운영 체제 버전, 빌드 번호, 서비스 팩 수준 및 기타 시스템 관련 정보를 표시합니다.


이들 이벤트 ID는 정보 제공 목적으로만 기록됩니다.

http://support.microsoft.com/kb/196452/ko

http://blogs.technet.com/b/sankim/archive/2008/02/12/eventlog-6008.aspx

----------------------------------------------------------------------------

참고

이벤트 ID : 41

원본 : Kernel-Power

메시지 : 시스템이 비정상적으로 종료된 후 다시 부팅되었습니다. 이 오류는 시스템이 응답을 멈추었거나 손상되었거나 예기치 않게 전원 공급이 중단되면 발생할 수 있습니다.

 

내용을 보면 기본적으로  오버클록킹, 메모리, 전원, 과열 문제를 확인 하라고 한다. 내가 발생한 상황은 위의 경우에 해당하지 않고, 어플리케이션 문제로 보인다.

 

컴퓨터가 이벤트 ID 41에 보고되지 않은 BugcheckCode 값을 포함하는 중지 오류를 생상하는 경우 컴퓨터의 다시 시작 동작을 수정하십시오. 이렇게 하려면 다음과 같이 하십시오.

  1. 내 컴퓨터를 마우스 오른쪽 단추로 클릭한 다음 속성을 클릭합니다.

  2. 고급 시스템 설정을 클릭합니다.

  3. 고급 탭을 클릭합니다.

  4. 시작 및 복구 섹션에서 설정을 클릭합니다.

  5. 자동 시작 확인란의 선택을 취소합니다.

2014년 1월 28일 화요일

원격데스크탑 ctrl+alt+del ( 컨트롤 알트 델)

원격데스크탑을 실행하는 경우, 예기치 못한 상황에 의해 explorer가 pending에 빠지는 경우가 있다..

이 경우 taskbar등이 살아 있다면 task manager를 쉽게 띄울 수 있겠지만, explorer가 이상이 생기는 경우 대부분은 taskbar도 제어불능 상태에 빠진다.

이 때 ctrl+alt+del을 누르면 로컬 PC의 Taskmgr이 뜨게 되므로 제어가 불가능해 진다.

이 때는 ctrl+alt+end 를 누르면 원격데스크탑의 taskmgr을 실행할 수 있게 된다.


[출처] 원격 컨트롤 알트 델|작성자 위더

found SPF/SPF record but no SPF/TXT record found, add matching type TXT record

bind 를 9.9.3-P1 로 업그레이드 하면 서 이런 에러가 발생

found SPF/SPF record but no SPF/TXT record found, add matching type TXT record

검색해보니 zone 파일에서 spf 설정이 조금 변경 됬다. 기존의 TXT 외에 SPF 로도 설정 해 주어야 한다.
@ IN TXT "v=spf1 ip4:111.222.333.444 ip4:111.222.333.555 -all"
@ IN SPF "v=spf1 ip4:111.222.333.444 ip4:111.222.333.555 -all"



출처

원격데스크탑,MSSQL 공격 자동 차단 스크립트

원격데스크탑 과 mssql 의 기본 포트를 바꾸지 않는 이상, BRUTE FORCE 공격이 지속적으로 들어온다.

해당 포트를 바꾸는 게 가장 최선이지만, 사정상 바꾸기 힘든 경우는 이벤트로그를 보고 해당 IP를 차단하는 방법 밖에 없다.

리눅스 같은 경우 fail2ban 이라는 훌륭한 오픈소스가 존재하여 사용가능 하나 윈도우 같은 경우 그런 프로그램이 없다.

소스포지에서 검색 해보면 비슷한 프로그램들이 나오나, 동작도 제대로 안 되고 에러 투성이 프로그램들만 있어서 사용할 수 있는 게 없다.

물론 상용프로램은 제외.

RDP 공격 같은 경우 EvlWatcher 라는 프로그램이 있는데, 아주 잘 동작 된다.

주의 할점은 관리자 권한으로 설치 해야 서비스 등록 및 방화벽 룰 셋팅이 제대로 설정 된다.

그러나 MSSQL BRUTE FORCE 공격은 따로 막아 주지 않아 조금 아쉽다.

ps.2014.05.21 윈도우2012에서는 동작을 안한다.

-------------------------------------------------------------------------------------

그러다 파워셀 스크립트로 해당 기능을 수행 할 수 있지 않을 까 해서 검색 해 보니, 역시 있었다.

해당 스크립트를 약간 변형 하여 mssql 도 막을 수 있게끔 처리 하였다.

이 스크립트는 이벤트 로그 기록을 참조하여 현재 접속 중인 아이피만 확인 한다.
#$regex1,$regex2값을 서버 아이피로 변경한다.
#예를 들어 서버 아이피가 222.222.222.222 이면
# $regex1 = [regex] "222\.222\.222\.(?:222|51):3389\s+(\d+\.\d+\.\d+\.\d+)";
#제일 마지막은 or 연산이기 때문에 신경 안써도 된다. 한개만 들어가도 됨.

###################### Config ######################
$regex1 = [regex] "111\.222\.333\.(?:140|51):3389\s+(\d+\.\d+\.\d+\.\d+)";
$regex2 = [regex] "원본 네트워크 주소:\t(\d+\.\d+\.\d+\.\d+)";

$regex1_mssql = [regex] "111\.222\.333\.(?:140|51):1433\s+(\d+\.\d+\.\d+\.\d+)";
$regex2_mssql = [regex] "클라이언트: (\d+\.\d+\.\d+\.\d+)";

$MyIp = "123.123.123.123"; #현재 내가 접속한 IP 차단하지 않는다.
$deny_count = 5; #임계값
$loop_time = 30; #loop_time 마다 재 실행.(초)
###################### Config ######################

$tick = 0;
"Start to run at: " + (get-date);

while($True) {
$blacklist = @();

#Port 3389 RDP
"Running... (tick:" + $tick + ")"; $tick+=1;

$a = @()
netstat -no | Select-String ":3389" | ? { $m = $regex1.Match($_);
$ip = $m.Groups[1].Value; if ($m.Success -and $ip -ne $MyIp) {$a = $a + $ip;} }

if ($a.count -gt 0) {
$ips = get-eventlog Security -Newest 1000 | Where-Object {$_.EventID -eq 4625 } | 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 RDP attacking IP on 3389: " + $ip + ", with count: " + $attack_count;
if ($attack_count -ge $deny_count) {$blacklist = $blacklist + $ip;}
}
}
}
}

#Port 1433 MSSQL

$a = @()
netstat -no | Select-String ":1433" | ? { $m = $regex1_mssql.Match($_);
$ip = $m.Groups[1].Value;
if ($m.Success -and $ip -ne $MyIp) {$a = $a + $ip;} }

if ($a.count -gt 0) {
$ips = get-eventlog Application -Newest 1000 | Where-Object {$_.EventID -eq 18456 -and ($_.Message -like "*sa*" ) } | foreach {
$m = $regex2_mssql.Match($_.Message); $ip = $m.Groups[1].Value; $ip; echo $m; } | 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 MSSQL attacking IP on 1433: " + $ip + ", with count: " + $attack_count;
if ($attack_count -ge $deny_count) {$blacklist = $blacklist + $ip;}
}
}
}
}

<# 주석처리. 사용안함. 미 테스트
#FTP
$MyFtpLogFile1 = "";
$now = (Get-Date).AddMinutes(-5); #check only last 5 mins.
#Get-EventLog has built-in switch for EventID, Message, Time, etc. but using any of these it will be VERY slow.
$count = (Get-EventLog Security -Newest 1000 | Where-Object {$_.EventID -eq 4625 -and $_.Message -match "Logon Type:\s+8" -and
$_.TimeGenerated.CompareTo($now) -gt 0} | Measure-Object).count;
if ($count -gt 50) #threshold
{
$ips = @();
$ips1 = dir "C:\inetpub\logs\LogFiles\FPTSVC2" | Sort-Object -Property LastWriteTime -Descending
| select -First 1 | gc | select -Last 200 | where {$_ -match "An\+error\+occured\+during\+the\+authentication\+process."}
| Select-String -Pattern "(\d+\.\d+\.\d+\.\d+)" | select -ExpandProperty Matches | select -ExpandProperty value | Group-Object
| where {$_.Count -ge 10} | select -ExpandProperty Name;

$ips2 = dir "C:\inetpub\logs\LogFiles\FTPSVC3" | Sort-Object -Property LastWriteTime -Descending
| select -First 1 | gc | select -Last 200 | where {$_ -match "An\+error\+occured\+during\+the\+authentication\+process."}
| Select-String -Pattern "(\d+\.\d+\.\d+\.\d+)" | select -ExpandProperty Matches | select -ExpandProperty value | Group-Object
| where {$_.Count -ge 10} | select -ExpandProperty Name;
$ips += $ips1; $ips += $ips2; $ips = $ips | where {$_ -ne "10.0.0.1"} | Sort-Object | Get-Unique;

foreach ($ip in $ips) {
if (-not ($blacklist -contains $ip)) {
"Found attacking IP on FTP: " + $ip;
$blacklist = $blacklist + $ip;
}
}
}
#>

#Firewall change

<# $current = (netsh advfirewall firewall show rule name="MY BLACKLIST" | where {$_ -match "RemoteIP"}).replace("RemoteIP:", "").replace(" ","").replace("/255.255.255.255",""); #inside $current there is no \r or \n need remove. foreach ($ip in $blacklist) { if (-not ($current -match $ip) -and -not ($ip -like "10.0.0.*")) {"Adding this IP into firewall blocklist: " + $ip; $c= 'netsh advfirewall firewall set rule name="MY BLACKLIST" new RemoteIP="{0},{1}"' -f $ip, $current; Invoke-Expression $c; } } #>

foreach ($ip in $blacklist) {

$fw=New-object -comObject HNetCfg.FwPolicy2; # http://blogs.technet.com/b/jamesone/archive/2009/02/18/how-to-manage-the-windows-firewall-settings-with-powershell.aspx
$myrule = $fw.Rules | where {$_.Name -eq "MY BLACKLIST"} | select -First 1; # Potential bug here?

if (-not ($myrule.RemoteAddresses -match $ip) -and -not ($ip -like "123.123.123.*"))
{"Adding this IP into firewall blocklist: " + $ip;
$myrule.RemoteAddresses+=(","+$ip);
#echo $ip > C:\BlackListIP.txt
}
}

"__________________________________________________________________________________"
Wait-Event -Timeout $loop_time #pause 30 secs

} # end of top while loop.

해당 코드를 Windows PowerShell ISE 실행하여 붙여넣고 실행하면 된다.
실행하기 전에 자기에게 맡게 IP,포트번호 등의 셋팅을 해야 하며, 윈도우 방화벽 규칙(MY BLACKLIST)이 추가 되어 있어야 한다.

 

#등록된 IP 전부를 deny 시키는 방화벽 룰 생성.
netsh advfirewall firewall add rule name="MY BLACKLIST" dir=in action=block localip=any remoteip=107.160.158.70

 107.160.158.70 아이피는 미국 어태커 IP.

 

1. 2008에서만 검증 확인. 2012에서도 가능 할 것으로 보임
2. 2003이하에서는 방화벽 동작 방식이 아예 달라서 사용 할 수 가 없다.
3. MY BLACKLIST 이름으로 차단 규칙 추가해야 한다.
4. FTP 스크립트는 테스트 안 해봄
5. 이벤트 로그가 있어야 하며, 현재 사용자가 계속 공격을 시도하고 있어야지 차단목록에 등록된다.
6. 공격자가 접속을 시도하는 상황에서만 차단 동작을 한다.

해당 스크립트를 저장하여 사용할 경우

오류: 이 시스템에서 스크립트를 실행할 수 없으므로 <Script name> 파일을 로드할 수 없습니다.  라는 메시지가 나타난다.

이럴 경우 파워셀을 관리자 권한으로 실행 후 아래의 명령어를 실행하면 된다.

Set-ExecutionPolicy RemoteSigned

출처

auto_blocking.ps1

2014년 1월 10일 금요일

리눅스 snmpd 설치 및 설정

//설치
yum install net-snmp

//부팅시 실행
chkconfig snmpd on

//부팅시 실행 확인
chkconfig --list | grep snmpd

//snmpd 실행
service snmpd start

기존것은 snmpd.conf.org로 변경해놓고
vim /etc/snmp/snmpd.conf


#community name 설정. localhost는 public
#111.222.333.444 IP와 111.111.111.0/24 대역은 community name을 password 라고 지정.
com2sec local_id localhost public
com2sec reno_id 111.222.333.444 password
com2sec reno_id 111.111.111.0/24 password

####
#위에서 설정한 local_id와 reno_id를 각각 local_group와 reno_group로 그룹에 매핑.
#securityModel은 v1과 v2c를 사용. v3는 생략
# groupName securityModel securityName
group local_group v1 local_id
group local_group v2c local_id
group reno_group v1 reno_id
group reno_group v2c reno_id

####
# snmpd의 권한설정. 다 필요없고 전부 준다. (.1)
# Third, create a view for us to let the group have rights to:
# Make at least snmpwalk -v 1 localhost -c public system fast again.
# name incl/excl subtree mask(optional)
view all included .1
#view systemview included .1V
#view systemview included .1.3.6.1.2.1.25.1.1

####
# Finally, grant the group read-only access to the systemview view.
# group context sec.model sec.level prefix read write notif
access local_group "" any noauth exact all none none
access reno_group "" any noauth exact all none none

방화벽에서 snmp:tcp, snmp:udp 둘다 열어주자