Zugriffe TCP/IP

01/11/2009 - 09:19 von Ruediger Roesler | Report spam
Moin,

da hier eh nix mehr los ist, habe ich beschlossen, eine kleine Anregung
zu vermitteln. Unter Windows XP ist eine Protokollierung der
Port-Zugriffe über das TCP/IP-Protokoll standardmàßig nicht vorgesehen.
Mit dem folgenden kleinen Skript können zumindest die meisten dieser
Zugriffe in einer Datei protokolliert werden.

Das Skript fragt die Ports etwa zweimal pro Sekunde ab. Dazu wird ein
externes Programm benötigt, wenn es auf dem lokalen System nicht
vorhanden ist, wird es aus dem Internet heruntergeladen. Mit der Anzahl
der offenen Verbindungen steigt natürlich die Prozessorbelastung an.
Dieses Skript eignet sich daher nicht dazu, stàndig im Hintergrund
mitzulaufen. Ab etwa 1000 Verbindungen sollte das Skript auf einem
aktuellem Standardsystem besser beendet werden.

Dieses Skript dient zur Systemanalyse, um etwa nicht autorisierte
Zugriffe auf das Internet zu entlarven. Es werden jedoch unter Umstànden
nicht alle Zugriffe protokolliert, zum Beispiel NTP-Abfragen oder
DNS-Zugriffe. Beim Aufruf muss eine Protokolldatei angegeben werden,
etwa so:
TCPIPLog.wsf %temp%\TCPIPView.log

Mit einem Textbearbeitungsprogramm, das die gelesenen Daten stàndig
aktualisiert, kann dann der Verlauf der Verbindungsaufnahme verfolgt
werden. Um die Protokollierung wieder zu beenden, genügt es, das Skript
ohne jedes Argument aufzurufen:
TCPIPLog.wsf

Unter Windows 7 làuft dieses Skript nicht, es wurde nur unter Windows XP
getestet.

Schönen Sonntag

<!--######################## TCPIPLog.wsf #############################
von h.r.roesler -->
<package>
<job id="Log">
<?job error="true" debug="true" ?>
<runtime>
<description>
Monitor port activity on TCP/IP to a specified log file.

To show this message, enter:
TCPIPLog.wsf /?

To cancel a formerly started instance, start another instance
without any arguments. Then all instances will be terminated.

To execute this script, the command line application
TCPVCON.exe from www.sysinternals.com is required in the path
of your system. If it is not found on the local system, it is
downloaded from the internet.
</description>
<unnamed name="[[drive:][\path\]]filename"
helpstring="File to receive the output of logging results."
many="false" required="false"/>
<example>TCPIPLog.wsf %temp%\TCPIPView.log</example>
</runtime>
<object id="wmiLoc" progid="WbemScripting.SWbemLocator"
reference="true"/>
<object id="fso" progid="Scripting.FileSystemObject"
reference="true"/>
<object id="wshShell" progid="WScript.Shell" reference="true"/>
<object id="xpShell" progid="Shell.Application"/>
<object id="xmlHttpReq" progid="MSXML2.XMLHTTP.3.0"/>
<object id="adoStream" progid="ADODB.Stream" reference="true"/>
<resource id="URL">
http://download.sysinternals.com/Fi...source>
<script language="JScript">
function logDatTime() {
var dtm = new Date(); var str = new String();
var zeroup = function(value, length) {
if (!length) length = 2;
value = String(value);
while (value.length < length)
value = "0" + value;
return(value);
}

str += dtm.getFullYear() + "-";
str += zeroup(dtm.getMonth() + 1) + "-";
str += zeroup(dtm.getDate()) + " ";
str += zeroup(dtm.getHours()) + ":";
str += zeroup(dtm.getMinutes()) + ":";
str += zeroup(dtm.getSeconds()) + ".";
str += zeroup(dtm.getMilliseconds(), 3) + " ";

return(str);
}
</script>

<script language="VBScript">
Option Explicit
Private Const HIDE = "HIDE", MSEC = 500, TCPV = "tcpvcon.exe"
Private Const HKCU = &H80000001, HKLM = &H80000002

Public strLog, blnShut, blnXC, dtime
Private X

Set X = New TCPLog

Sub ShutDown_OnObjectReady(wmiEvt, wmiAsyncContext)
If blnXC Then blnXC = False: dtime = Now
strLog = strLog & vbCRLF & logDatTime()
If wmiEvt.Path_.Class = "__InstanceCreationEvent" Then
With wmiEvt.TargetInstance
strLog = strLog & .User & vbCRLF & .SourceName & _
vbCRLF & .EventCode & vbCRLF & .Message & vbCRLF
If .EventCode = 513 Then blnShut = True
End With
Else'If wmiEvt.Path_.Class = "Win32_ComputerShutDownEvent" Then
strLog = strLog & wmiEvt.Path_.Class & " " & wmiEvt.MachineName
Select Case wmiEvt.Type
Case 0: strLog = strLog & ": Log off" & vbCRLF
Case 1: strLog = strLog & ": Shutdown or Reboot" & vbCRLF
End Select
blnShut = True
End If
End Sub

Class TCPLog
Private wmiSink, wmi, wshVEnv, strCtrl, oArg, fsoStrm, strErr, strMe

Private Sub Class_Initialize
blnXC = True ' execute applications allowed
wmiSink = "ShutDown_"
Set wmi = CreateNotification(wmiSink)
Set wshVEnv = wshShell.Environment("VOLATILE")
strCtrl = fso.GetBaseName(WScript.ScriptName)
strMe = WScript.ScriptFullName
Set oArg = WScript.Arguments.Unnamed
If oArg.Count > 0 Then strErr = CheckValid(oArg(0))
If oArg.Count > 1 Then
If oArg(1) <> HIDE Then strErr = oArg(1): Err.Raise 449
Call Log(Search4(TCPV), oArg(0))
Else
Call Control(strErr)
End If
End Sub

Private Sub Class_Terminate
wmiSink.Cancel
Set wmiSink = Nothing
If Not(IsEmpty(fsoStrm)) Then
fsoStrm.Write strLog
fsoStrm.Close
End If
If Len(wshVEnv(strCtrl)) > 0 Then wshVEnv.Remove strCtrl
If Err Then
MsgBox Err.Description & vbCRLF & strErr, vbSystemModal, _
strCtrl & ": " & Err.Source & " " & Err.Number
End If
End Sub

Private Sub Log(strCmd, strFile)
Dim dtm, strNew, strOld, strTime

strLog = vbCRLF & "#" & strCtrl & " session started [Local" & _
" Time]: " & logDatTime() & vbCRLF & "#Software: '" & _
strCmd & "'." & vbCRLF
Call Shrink(strFile, 2^20): Set fsoStrm = CreateStream(strFile)
wshVEnv(strCtrl) = "1": dtm = Timer
Do
strNew = Capture(strCmd, "-a -c -n", strTime)
If strNew <> strOld Then '^^^^^^^^ don't resolve DNS!
strLog = strLog & Compare(strNew, strOld, strTime)
If Len(strLog) > 0 Then
fsoStrm.Write strLog: strLog = ""
End If
strOld = strNew
End If
If Not(blnShut) Then
If Not(blnXC) Then ' Shutdown cancelled?
If DateDiff("s", dtime, Now) > 61 Then blnXC = True
End If
If Shrink(strFile, 2^20) Then
Set fsoStrm = CreateStream(strFile)
End If
If (Timer > dtm) And ((Timer - dtm)*1000 < MSEC) Then
WScript.Sleep Abs(MSEC - Int((Timer - dtm)*1000)-15)
End If
End If
dtm = Timer
Loop While (wshVEnv(strCtrl) = "1") Xor blnShut
strLog = strLog & vbCRLF & "#" & strCtrl & _
" session terminated at: " & logDatTime() & vbCRLF
End Sub

Private Function Capture(ByRef strCmd, ByRef strArgs, ByRef strTime)
Dim strOut

If blnXC Then
strTime = logDatTime()
With wshShell.Exec(strCmd & " " & strArgs)
Do
strOut = strOut & .StdOut.ReadAll
Loop Until .StdOut.AtEndOfStream
End With
End If

Capture = strOut
End Function

Private Function Compare(ByRef strCap, ByRef strCmp, ByRef strTime)
Dim str, str0, str1, blnFound

If blnXC Then
For Each str0 In Split(strCap, vbNewLine)
If Len(str0) > 0 Then
blnFound = False
For Each str1 In Split(strCmp, vbNewLine)
If str0 = str1 Then blnFound = True: Exit For
Next
If Not(blnFound) Then
str = str & strTime & str0 & vbNewLine
End If
End If
Next
End If

Compare = str
End Function

Private Function Shrink(strFile, lngSize)
Dim strOld, bln

If fso.FileExists(strFile) Then
With fso.GetFile(strFile)
If .Size >= lngSize Then
strOld = fso.BuildPath(.ParentFolder, _
fso.GetBaseName(.Name) & ".old." & _
fso.GetExtensionName(.Name))
If fso.FileExists(strOld) Then ThrowAway strOld
If IsObject(fsoStrm) Then fsoStrm.Close: bln = True
.Move strOld
End If
End With
End If

Shrink = bln
End Function

Private Function CreateStream(ByRef strFile)
strLog = strLog & vbCRLF & "#Fields: date time: protocol, " & _
"application, pid, state, src-ip:src-port, dst-ip" & _
":dst-port" & vbCRLF
With fso.OpenTextFile(strFile, ForAppending, True)
.Write strLog: strLog = ""
.Close
End With
wmi.Get("CIM_Datafile='" & strFile & "'").Compress

Set CreateStream = fso.OpenTextFile(strFile, ForAppending, True)
End Function

Private Sub ThrowAway(strFile)
Const ssfBITBUCKET = &Ha, FOF_NOCONFIRMATION = &H10

With xpShell.NameSpace(ssfBITBUCKET)
.MoveHere strFile, FOF_NOCONFIRMATION
Do While fso.FileExists(strFile) And wshVEnv(strCtrl) = "1"
WScript.Sleep 50 'before the folder object is destroyed
Loop 'assure moving operation has finished
End With
End Sub

Private Sub Control(strFileName)
Dim i, str

If Len(wshVEnv(strCtrl)) > 0 And wshVEnv(strCtrl) <> "0" Then
wshVEnv(strCtrl) = "0" ' cancel former instances
For i = 0 To 9 ' Wait for termination
WScript.Sleep MSEC \ 5
If Len(wshVEnv(strCtrl)) = 0 Then
WScript.Echo vbCRLF & "All instances are canceled."
Exit For
End If
Next
End If
If Not(IsEmpty(strFileName)) And blnXC Then
WScript.Echo vbCRLF & "Creating new log in: " & strFileName
str = "CScript.exe """ & strMe & """ """ & strFileName
wshShell.Run str & """ " & HIDE, wshHide
'str = wshShell.RegRead("HKCR\" & wshShell.RegRead("HKCR" &_
' "\.txt\") & "\shell\open\command\")
'wshShell.Run str & " """ & strFileName & """"
ElseIf IsEmpty(i) Then
WScript.Arguments.ShowUsage
End If
End Sub

Private Function CreateNotification(ByRef wmiSink)
Const CURVER = "SOFTWARE\Microsoft\Windows\CurrentVersion"
Const SHUTDOWNREASON = "\Reliability\ShutdownReasonUI"
Const SN = "WbemScripting.SWbemSink", PV = "SeSecurityPrivilege"
Dim wql

Call CompRegVal(HKLM, CURVER & SHUTDOWNREASON, 1, "REG_DWORD")
wmiLoc.Security_.ImpersonationLevel = _
wbemImpersonationLevelImpersonate
wmiLoc.Security_.Privileges.AddAsString PV, True
Set wmi = wmiLoc.ConnectServer(".", "root/cimv2")
Set wmiSink = WScript.CreateObject(SN, wmiSink)
wql = "Select * from Win32_ComputerShutDownEvent"
wmi.ExecNotificationQueryAsync wmiSink, wql
wql = "Select * from __InstanceCreationEvent within 1 " & _
"where TargetInstance isa 'Win32_NTLogEvent' and " & _
"((TargetInstance.LogFile = 'Security' and " & _
"TargetInstance.SourceName = 'Security' and " & _
"(TargetInstance.EventCode = '513' or " & _
"TargetInstance.EventCode = '551')) or " & _
"(TargetInstance.LogFile = 'System' and " & _
"TargetInstance.SourceName = 'USER32' and " & _
"TargetInstance.EventCode = '1074'))"
wmi.ExecNotificationQueryAsync wmiSink, wql

Set CreateNotification = wmi
End Function

Private Function Search4(strAppl)
Const TCPV = "Software\Sysinternals\TCPView\EulaAccepted"
Dim strFldr, strPath

strPath = wshShell.CurrentDirectory & ";" & _
fso.GetParentFolderName(strMe) & ";" & _
wshShell.Environment("PROCESS")("PATH")

For Each strFldr In Split(strPath, ";")
If Len(strFldr) > 0 Then
If fso.FileExists(fso.BuildPath(strFldr, strAppl)) Then
strAppl = fso.BuildPath(strFldr, strAppl)
Exit For
End If
End If
Next
If Not(fso.FileExists(strAppl)) Then strAppl = GetAppl(strAppl)
If CompRegVal(HKCU, TCPV, "", "") <> 1 Then
wshShell.Run strAppl, wshHide, True
If CompRegVal(HKCU, TCPV, "", "") <> 1 Then WScript.Quit
End If

Search4 = strAppl
End Function

Private Function GetAppl(strProg)
Dim str

str = wshShell.Environment("USER")("TEMP")
str = wshShell.ExpandEnvironmentStrings(str)
str = fso.BuildPath(str, fso.GetFileName(getResource("URL")))
If fso.FileExists(str) Then
str = Unzip(str, fso.GetParentFolderName(strMe), strProg)
Else
Select Case wshShell.PopUp(strProg & " wasn't found. Do" & _
" you want it to download now?" , 60, strCtrl & _
": Download", vbYesNo Or vbQuestion Or vbSystemModal)
Case vbNo
Err.Raise vbObjectError + 2, , "Application " & _
"was not found: " & strProg
Case Else
If Download(Trim(getResource("URL")), str) Then
str = GetAppl(strProg)
End If
End Select
End If

GetAppl = str
End Function

Private Function Unzip(strZipFldr, strDestFldr, strFile)
Dim xpFolder(2): Const ZIP = 0, DST = 1

Set xpFolder(ZIP) = xpShell.NameSpace(strZipFldr)
Set xpFolder(DST) = xpShell.NameSpace(strDestFldr)
xpFolder(DST).CopyHere xpFolder(ZIP).ParseName(strFile)
Do Until fso.FileExists(fso.BuildPath(strDestFldr, strFile))
WScript.Sleep 50
Loop

Unzip = xpFolder(DST).ParseName(strFile).Path
End Function

Private Function Download(strURL, strDstPath)
Const CURV = "Software\Microsoft\Windows\CurrentVersion\"
Const OFF = "Internet Settings\GlobalUserOffline", COMPLETED = 4
Dim intOffline

If Not(fso.FileExists(strDstPath)) Then
intOffline = CompRegVal(HKCU, CURV & OFF, 0, "REG_DWORD")
xmlHttpReq.Open "GET", strURL, False
xmlHttpReq.Send
Do
WScript.Sleep 100
Loop Until xmlHttpReq.ReadyState = COMPLETED
With adoStream
.Mode = adModeReadWrite
.Type = adTypeBinary
.Open
.Write xmlHttpReq.ResponseBody
.SaveToFile strDstPath, adSaveCreateNotExist
.Close
End With
Call CompRegVal(HKCU, CURV & OFF, intOffline, "REG_DWORD")
End If

Download = fso.FileExists(strDstPath)
End Function

Private Function CheckValid(strPath)
Dim str, fsoFolder

Set fsoFolder = fso.GetFolder(fso.GetParentFolderName(strPath))
str = fso.BuildPath(fsoFolder.Path, fso.GetFileName(strPath))
If StrComp(strPath, str, vbTextCompare) <> 0 Then
Err.Raise vbObjectError + 1, ,"Invalid Path: " & strPath
End If

CheckValid = str
End Function

Private Function CompRegVal(intBranch, strKey, vtValue, strTyp)
Const KEY_QUERY_VALUE = &H0001, KEY_SET_VALUE = &H0002
Dim vtVal, reg, blnAccess, strBK

Set reg = wmiLoc.ConnectServer(".", "root/default")
Set reg = reg.Get("StdRegProv")

Select Case intBranch
Case HKCU: strBK = "HKCU\" & strKey
Case HKLM: strBK = "HKLM\" & strKey
End Select
strKey = Left(strKey, InStrRev(strKey, "\"))
reg.CheckAccess intBranch, strKey, KEY_QUERY_VALUE, blnAccess
If blnAccess Then
On Error Resume Next
vtVal = wshShell.RegRead(strBK)
On Error GoTo 0
End If

If Len(strTyp) > 0 And vtVal <> vtValue Then
reg.CheckAccess intBranch, strKey, KEY_SET_VALUE, blnAccess
If blnAccess Then wshShell.RegWrite strBK, vtValue, strTyp
End If

CompRegVal = vtVal
End Function
End Class
</script>
</job>
</package>
<!--######################## TCPIPLog.wsf ##########################-->

ЯR
 

Lesen sie die antworten

#1 Ruediger Roesler
02/11/2009 - 08:55 | Warnen spam
Ruediger Roesler typed:

Call Shrink(strFile, 2^20): Set fsoStrm = CreateStream(strFile)
wshVEnv(strCtrl) = "1": dtm = Timer



Diese beiden Zeilen sollten miteinander vertauscht werden:
wshVEnv(strCtrl) = "1": dtm = Timer
Call Shrink(strFile, 2^20): Set fsoStrm = CreateStream(strFile)

ЯR

Ähnliche fragen