Fritzbox Capture Stream speichern

Stelle Fragen zur Programmierung mit Autohotkey

Moderator: jNizM

User avatar
haichen
Posts: 631
Joined: 09 Feb 2014, 08:24

Fritzbox Capture Stream speichern

11 Feb 2017, 10:33

Ich bin soweit gekommen, dass ich mich in meiner Fritzbox anmelden und verschiedene Seiten aufrufen kann.
Jetzt wollte ich den IP-Verkehr mitschneiden. Das kann man auf http://fritz.box/html/capture.html händisch starten und stoppen.
Beim start geht dann ein standardspeichern Fenster auf wo man eine Dateiname vorgeben ist. Danach muss man noch stopp drücken. Das wars.

Für start und stopp werden diese urls aufgerufen:

Code: Select all

URL_start=http://fritz.box/cgi-bin/capture_notimeout?sid=a6c17e36dc939f17&capture=Start&snaplen=1600&ifaceorminor=2-1
URL_stop=http://fritz.box/cgi-bin/capture_notimeout?iface=internet,voip&minor=1&type=2&capture=Stop&sid=a6c17e36dc939f17&xhr=1&t1486464763454=nocache
(die sid ist bei jeder Sitzung anders)
Kopiert man die in die Adresszeile des Browsers kann man das Verhalten von Start und Stopp auslösen.

Ich hab versucht das im Programm mit GET auszulösen und dann zu speichern

Leider klappt das nicht, aber vielleicht hat ja jemand eine idee.

Code: Select all

global password
password := "XXXX"
HttpObj := ComObjCreate("WinHttp.WinHttpRequest.5.1")

;==============
Fritzbox Login
;==============
loginURL := "http://fritz.box/login.lua"

loginBody := "uiPass=" password 

HttpObj.Open("POST",loginURL)
gosub, header
HttpObj.SetRequestHeader("Content-Type","application/x-www-form-urlencoded")
HttpObj.Send(loginBody)
HttpObj.WaitForResponse()

; sucht etwas wie g_challenge = "f3c2d520"
pattern=im)g_challenge = "(\w+)"
FoundPos := RegExMatch(HttpObj.ResponseText, pattern, SubPat)
challenge:=SubPat1
;Berechnet aus Passwort und Challenge ein Response was zum Login genutzt wird
response:=FB_CalculateResponse(challenge)


loginBody := "response=" response 
HttpObj.Send(loginBody)
HttpObj.WaitForResponse()

; findet eine sid die für die ganze Sitzung konstant ist, und mit der man die verschieden Seiten aufrufen kann
pattern=im)lua\?sid=(\w+)"
FoundPos := RegExMatch(HttpObj.ResponseText, pattern, SubPat)
sid:=SubPat1

URL=http://fritz.box/login.lua?page=/capture.lua&sid=%sid%
HttpObj.Open("get",URL)
HttpObj.Send()
HttpObj.WaitForResponse()

; ================
; versuche den IP stream mitzuschneiden
; ================
; capture start
; beim Kopieren in die Adresszeile (bei korrekter sid) wird capture gestartet, Dabei wird das zuerst ein speichermenü für die Datei aufgerufen
URL_start=http://fritz.box/cgi-bin/capture_notimeout?sid=%sid%&capture=Start&snaplen=1600&ifaceorminor=2-1

;HttpObj.Open("trace",URL_start,true)
HttpObj.Open("GET",URL_start,true)
HttpObj.SetRequestHeader("Upgrade-Insecure-Requests","1") ;https ?
HttpObj.Send()
;msgbox, % HttpObj.ResponseText

; stoppt beim kopieren in die Adresszeile sofort die Aufzeichnung des IP-Streams
URL_stop=http://fritz.box/cgi-bin/capture_notimeout?iface=internet,voip&minor=1&type=2&capture=Stop&sid=%sid%&xhr=1&t1486464763654=nocache
HttpObj.Open("GET",URL_stop,false)
HttpObj.Send()
HttpObj.WaitForResponse(5)

vStream := HttpObj.ResponseStream
;Streamobjekt speichern
msgbox, % HttpObj.ResponseText ; "Der Paketmitschnitt wurde gestoppt.." ansonsten leer

;https://autohotkey.com/board/topic/71528-com-winhttprequest-responsestream/page-2
if (ComObjType(vStream) = 0xD) { ;VT_UNKNOWN = 0xD
 pIStream := ComObjQuery(vStream, "{0000000c-0000-0000-C000-000000000046}") ;defined in ObjIdl.h
 oFile := FileOpen( A_ScriptDIr "\testcapture.txt", "w")

 Loop { 
 VarSetCapacity(Buffer, 1600)  ;8192
 hResult := DllCall(NumGet(NumGet(pIStream + 0) + 3 * A_PtrSize) ; IStream::Read 
 , "ptr", pIStream 
 , "ptr", &Buffer ;pv [out] A pointer to the buffer which the stream data is read into.
 , "uint", 1600 ;cb [in] The number of bytes of data to read from the stream object.
 , "ptr*", cbRead) ;pcbRead [out] A pointer to a ULONG variable that receives the actual number of bytes read from the stream object. 
 oFile.RawWrite(&Buffer, cbRead)
 } Until (cbRead = 0)
 ObjRelease(pIStream) 
 oFile.Close() 
}
exitapp
return


FB_makeDots(str){
Loop, Parse, str 
  s .= asc(A_LoopField)>255 ? "." : A_LoopField
return s
}

FB_StringToBinary(str){
Loop, Parse, str 
  s .= Format("{1:X}00", asc(A_LoopField)) 
return "0x" s
}

FB_CalculateResponse(challenge){
response:=challenge "-" FB_makeDots(password)
response:=challenge "-" bcrypt_md5(response, "UTF-16")
return response
}

; https://github.com/jNizM/AHK_CNG
; https://autohotkey.com/boards/viewtopic.php?p=130356#p130356
bcrypt_md5(string, encoding = "UTF-8")
{
static BCRYPT_MD5_ALGORITHM := "MD5"
static BCRYPT_HASH_LENGTH := "HashDigestLength"
If encoding not in CP0,UTF-8,UTF-16
Return ""
ts := (encoding = "UTF-16") ? 2 : 1
if !(hBCRYPT := DllCall("LoadLibrary", "str", "bcrypt.dll", "ptr"))
throw Exception("Failed to load bcrypt.dll", -1)
if (NT_STATUS := DllCall("bcrypt\BCryptOpenAlgorithmProvider", "ptr*", hAlgo, "ptr", &BCRYPT_MD5_ALGORITHM, "ptr", 0, "uint", 0) != 0)
throw Exception("BCryptOpenAlgorithmProvider: " NT_STATUS, -1)
if (NT_STATUS := DllCall("bcrypt\BCryptGetProperty", "ptr", hAlgo, "ptr", &BCRYPT_HASH_LENGTH, "uint*", cbHash, "uint", 4, "uint*", cbResult, "uint", 0) != 0)
throw Exception("BCryptGetProperty: " NT_STATUS, -1)
VarSetCapacity(pbInput, cbInput := (StrPut(string, encoding) - 1) * ts, 0), StrPut(string, &pbInput, encoding), VarSetCapacity(pbHash, cbHash, 0)
if (NT_STATUS := DllCall("bcrypt\BCryptHash", "ptr", hAlgo, "ptr", 0, "uint", 0, "ptr", &pbInput, "uint", cbInput, "ptr", &pbHash, "uint", cbHash) != 0)
throw Exception("BCryptHash: " NT_STATUS, -1)
loop % cbHash
hash .= Format("{:02x}", NumGet(pbHash, A_Index - 1, "uchar"))
DllCall("bcrypt\BCryptCloseAlgorithmProvider", "ptr", hAlgo, "uint", 0)
DllCall("FreeLibrary", "ptr", hBCRYPT)
return hash
}

Header:
host:="fritz.box"
useragent:="Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:51.0) Gecko/20100101 Firefox/51.0"
Accept:="text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
AcceptLanguage:="de,en-US;q=0.7,en;q=0.3"
AcceptEncoding:="gzip, deflate"
Referer:="http://fritz.box/home/home.lua?sid=" sid
Connection:="keep-alive"
HttpObj.SetRequestHeader("host",host)
HttpObj.SetRequestHeader("User-Agent",useragent)
HttpObj.SetRequestHeader("Accept",Accept)
HttpObj.SetRequestHeader("Accept-Encoding",AcceptEncoding)
HttpObj.SetRequestHeader("Accept-Language",AcceptLanguage)
HttpObj.SetRequestHeader("Referer",referer)
HttpObj.SetRequestHeader("Connection",Connection)
return
Das hier konnte ich mit dem Firefox addon Tamper herausfinden:

Code: Select all

14:59:17.618[13655ms][total 13655ms] Status: 200[OK]
GET http://fritz.box/cgi-bin/capture_notimeout?sid=a6c17e36dc939f17&capture=Start&snaplen=1600&ifaceorminor=2-1 Load Flags[LOAD_DOCUMENT_URI  ] Größe des Inhalts[-1] Mime Type[application/octet-stream]
   Request Header:
      Host[fritz.box]
      User-Agent[Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:51.0) Gecko/20100101 Firefox/51.0]
      Accept[text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8]
      Accept-Language[de,en-US;q=0.7,en;q=0.3]
      Accept-Encoding[gzip, deflate]
      Referer[http://fritz.box/capture.lua?sid=a6c17e36dc939f17]
      Connection[keep-alive]
      Upgrade-Insecure-Requests[1]
   Response Header:
      Connection[Keep-Alive]
      Transfer-Encoding[chunked]
      Content-Type[application/octet-stream]
      Keep-Alive[timeout=60, max=300]
      Content-Disposition[attachment; filename=fritzbox-vcc0_11.02.17_1459.eth]

14:59:45.057[53ms][total 53ms] Status: 200[OK]
GET http://fritz.box/cgi-bin/capture_notimeout?iface=internet,voip&minor=1&type=2&capture=Stop&sid=a6c17e36dc939f17&xhr=1&t1486821585050=nocache Load Flags[LOAD_BACKGROUND  LOAD_BYPASS_LOCAL_CACHE_IF_BUSY ] Größe des Inhalts[-1] Mime Type[text/plain]
   Request Header:
      Host[fritz.box]
      User-Agent[Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:51.0) Gecko/20100101 Firefox/51.0]
      Accept[*/*]
      Accept-Language[de,en-US;q=0.7,en;q=0.3]
      Accept-Encoding[gzip, deflate]
      Referer[http://fritz.box/capture.lua?sid=a6c17e36dc939f17]
      Connection[keep-alive]
   Response Header:
      Connection[Keep-Alive]
      Transfer-Encoding[chunked]
      Content-Type[text/plain]
      Keep-Alive[timeout=60, max=300]
      refresh[5; url=/cgi-bin/webcm?getpage=../html/capture_frame.html&sid=a6c17e36dc939f17]
Guest

Re: Fritzbox Capture Stream speichern

28 Jul 2017, 12:40

Hallo,

ich bin auch nach einer Lösung interessiert. z.B per cron die lan capture zu starten. (iad-if-lan_datum_zeit.eth
z.B startet die fritzbox jede Nacht um 3uhr nachts > per cron sollte dann jedes mal ab 4uhr download erneut gestartet werden.
ahk_0909
Posts: 1
Joined: 28 Jul 2017, 12:37

Re: Fritzbox Capture Stream speichern

28 Jul 2017, 12:43

ich wäre auch an einer Lösung interessiert. zb per cron download um 2uhr nachts stoppen (fritz box startet neu) und ab 3uhr wieder fortfahren. Somit z.b für jeden tag eine iad-if_datum_zeit.eth Datei zu speichern.
Guest

Re: Fritzbox Capture Stream speichern

01 Aug 2017, 08:32

Weiß jemand wie ich bei dem script bei "wireshark" den Datennamen zb auf lan_*heutigesdatum-zeitpunkt* einfüge?
tcl ist die Sprache oder nicht?

Code: Select all

wstrace open
set fbpwd password
set fbtrace 1
sid
fbgetr "http://fritz.box/cgi-bin/capture_notimeout?capture=Start&snaplen=1600&ifaceorminor=1-lan" > wireshark &
Last edited by tank on 01 Aug 2017, 12:23, edited 1 time in total.
Reason: Edit at OP request
BoBo
Posts: 6564
Joined: 13 May 2014, 17:15

Re: Fritzbox Capture Stream speichern

01 Aug 2017, 09:46

Code: Select all

FileAppend, 
(LTrim
wstrace open
set fbpwd l33tl33t
set fbtrace 1
sid
fbgetr "http://fritz.box/cgi-bin/capture_notimeout?capture=Start&snaplen=1600&ifaceorminor=1-lan" > wireshark & lan_%A_Now%.log
), myScript.tcl
Wenn ich das richtig interpretiere wird hier über wireshark der traffic konvertiert, und du möchtest ihn dann in echtzeit in ein logfile pipen?
Ob der dateiname an der position syntaktisch richtig platziert ist solltest du besser wissen (oder noch recherchieren). Und ja, NAT32 arbeitet wohl mit tcl-script.
Good luck :)
User avatar
haichen
Posts: 631
Joined: 09 Feb 2014, 08:24

Re: Fritzbox Capture Stream speichern

26 Oct 2019, 03:43

Hi, nach einiger Zeit hab ich mir noch mal das Skript zum aufnehmen des Internetverkehrs vorgenommen.

Das Response-Challenge Verfahren um die SID zu erhalten funktioniert jetzt.
Aufnahme starten und beenden klappt auch.

Das ganze hat aber noch eine, nicht so schöne Aktion. So wie es jetzt läuft, wird eine Datei im IE Cache angelegt und während der Aufnahme befüllt. Beim beenden der Aufnahme wird die Datei aber gelöscht. Ich behelfe mir damit, die Datei vorher aus dem Cache zu kopieren.

Ich würde das ganze aber gerne korrekt speichern und beenden. Für den Download von Dateien wird im Forum der adobe.stream verwendet. Das bekomme ich aber nicht zum laufen (Funktion ist unten im Skript). Vielleicht hat ja jemand eine Idee. Ansonsten läuft das Skript bei mir gut.

Ich habe das Skript auch nur mit "Msxml2.XMLHTTP" statt mit "WinHttp.WinHttpRequest.5.1" zum laufen gebracht. Der Unterschied der beiden ist mir nicht klar.

Code: Select all

#NoEnv  ; Recommended for performance and compatibility with future AutoHotkey releases.
; #Warn  ; Enable warnings to assist with detecting common errors.
SendMode Input  ; Recommended for new scripts due to its superior speed and reliability.
SetWorkingDir %A_ScriptDir%  ; Ensures a consistent starting directory.

;DetectHiddenWindows,On
SetTitleMatchMode, 2
SetTitleMatchMode, slow
global headers
;startDebugview()

;;  mit ":" wird die Zeile nicht in das Array headers aufgenommen
; das Skript funktioniert auch ohne die headers zu setzen: die Nutzung habe ich in 
; startCapture() auskommentiert
hstr:="
(
:X-XSS-Protection: 1; mode=block
:X-Content-Type-Options: nosniff
:Keep-Alive: timeout=60, max=300
:X-Frame-Options: SAMEORIGIN
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-type: application/octet-stream
Content-Disposition: attachment; filename=rainersfritzbox-vcc0_24.10.19_1240.eth
:Range: bytes=0-1023
)"

headers:={}
loop, parse, hstr, `n
{
	h:=StrSplit(a_loopfield,":"," `t" ,2)
	if (h[1]<>"")
		headers[h[1]]:=h[2]
}


pwd:="geheim"
Gui Add, Button, x104 y56 w136 h89 gCapture vcc, Capture
Gui Add, Button, x304 y56 w136 h90 gstop vsc, Stop
GuiControl, Disable, sc

Gui Show, w569 h195, Window
Return

GuiEscape:
GuiClose:
;stopDebugview()
ExitApp


capture:
gui,submit,nohide
ch:=  getChallenge(whr)
rsp:= ch . "-" . getResponse(ch,pwd)
sid:= getSID(whr,rsp)
startCapture(whr,sid)
GuiControl, Enable, sc
GuiControl, Disable, cc
OutputDebug, % "challenge: |" ch "|`n"
. "response: |" rsp "|`n"
. "sid: |"      sid "|"
return


stop:
gui,submit,nohide
MoveFileFromIECacheToScripDir()
stopCapture(whr,sid)
GuiControl, Enable, cc
GuiControl, Disable, sc


return

;===============================
; Challenge response authorization
;===============================

getChallenge(ByRef whr){
	whr := ComObjCreate("Msxml2.XMLHTTP")
	whr.Open("GET", "http://fritz.box/login_sid.lua", false)
	whr.Send()
	Array := StrSplit(whr.ResponseText , ["<Challenge>","</Challenge>"])
	OutputDebug, % "challenge Status: " Array[2] "`n"
	return Array[2]
}


getResponse(challenge,pwd){
	ch:=challenge . "-" . pwd
	len:=strpututf16raw(ch,string)
	return MD5FromAddr(&string,len)
}



getSID(ByRef whr,rstr){
	whr.Open("GET", "http://fritz.box/login_sid.lua?username=&response=" . rstr, false)
	whr.Send()
	Array := StrSplit(whr.ResponseText , ["<SID>","</SID>"])
	OutputDebug, % "getSID Status: " Array[2] "`n"
	return Array[2]
}



;===============================
;===============================

startCapture(ByRef whr,sid){
	url:="http://fritz.box/cgi-bin/capture_notimeout?sid=" . sid . "&capture=Start&snaplen=1600&ifaceorminor=2-1"
	whr.Open("GET", url, true) ;  true   false
	;For header, value in headers
	;	whr.SetRequestHeader(header,value)
	whr.Send()
	return
}


stopCapture(ByRef whr,sid){
	;url := "http://fritz.box/cgi-bin/capture_notimeout?iface=stopall&capture=Stop&sid=" . sid
	url := "http://fritz.box/cgi-bin/capture_notimeout?iface=internet,voip&minor=1&type=2&capture=Stop&sid=" . sid . "&useajax=1&xhr=1&"
	whr.Open("GET", url, false)
	whr.Send()
	return
}


MoveFileFromIECacheToScripDir(){
	iecachePath := "C:\Users\" . a_username . "\AppData\Local\Microsoft\Windows\INetCache\IE"
	FileList := ""
	Loop, Files, %iecachePath%\*.eth ,FR
		FileList .= A_LoopFilePath . "`n"
	
	Loop, Parse, FileList, `n
		FileMove, %A_LoopField%, %A_ScriptDir%
	return
}

;===============================
;===============================



StrPutUTF16RAW(Str,byref Var,zeroterminated=1)
{ ;https://autohotkey.com/board/topic/90962-wie-erzeuge-ich-eine-bytefolge-der-utf-16le-codierung/ ;nnnik
	zeroterminated:=zeroterminated?2:0
	VarSetCapacity(Var,(var2:=(strlen(str)-1)*2)+zeroterminated,0)
	loop,% var2
	{
		NumPut(Asc(str),Var,(A_Index-1)*2,"UShort")
		StringTrimLeft,str,str,1
	}
	return var2+zeroterminated
}


MD5FromAddr(addr, len)
{
	return HashFromAddr(addr, len, 0x8003)
}


HashFromAddr(pData, len, algid, key=0)
{ ;https://autohotkey.com/board/topic/90962-wie-erzeuge-ich-eine-bytefolge-der-utf-16le-codierung/ ;nnnik
	ptr := (A_PtrSize) ? "ptr" : "uint"
	aw := (A_IsUnicode) ? "W" : "A"
	if (DllCall("advapi32\CryptAcquireContext" aw, ptr "*", hProv, ptr, 0, ptr, 0, "uint", 1, "uint", 0xF0000000))
	{
		if (DllCall("advapi32\CryptCreateHash", ptr, hProv, "uint", algid, "uint", key, "uint", 0, ptr "*", hHash))
		{
			if (DllCall("advapi32\CryptHashData", ptr, hHash, ptr, pData, "uint", len, "uint", 0))
			{
				if (DllCall("advapi32\CryptGetHashParam", ptr, hHash, "uint", 2, ptr, 0, "uint*", size, "uint", 0))
				{
					VarSetCapacity(bhash, size, 0)
					DllCall("advapi32\CryptGetHashParam", ptr, hHash, "uint", 2, ptr, &bhash, "uint*", size, "uint", 0)
				}
			}
			DllCall("advapi32\CryptDestroyHash", ptr, hHash)
		}
		DllCall("advapi32\CryptReleaseContext", ptr, hProv, "uint", 0)
	}
	int := A_FormatInteger
	SetFormat, Integer, h
	Loop, % size
	{
		v := substr(NumGet(bhash, A_Index-1, "uchar") "", 3)
		while (strlen(v)<2)
			v := "0" v
		hash .= v
	}
	SetFormat, Integer, % int
	return hash
}

stopDebugview(){
	WinActivate,DebugView++
	send,{Alt down}fx{Alt up}
	return
}

startDebugview(){
	if !(WinExist("DebugView++"))
		run DebugView++
	else
		WinActivate
	return
}

SaveResponseBody(ByRef whr, SavePath) {
	;https://www.autohotkey.com/boards/viewtopic.php?p=84867&sid=eace2819507b480cf967e2ab115768d8#p84867
	ado := ComObjCreate("adodb.stream")
	ado.Type := 1 ; adTypeBinary = 1
	ado.Open()
	ado.Write( whr.ResponseBody )
	ado.SaveToFile( SavePath, 2 ) ; adSaveCreateOverWrite = 2
	ado.Close()
	return
}

Return to “Ich brauche Hilfe”

Who is online

Users browsing this forum: No registered users and 25 guests