Jump to content
Sign in to follow this  
FireFox

Winpcap filter and TCP/UDP packet splitter

Recommended Posts

FireFox

Hi,

I have worked on a project for a friend and it needed to retreive some data in UDP packets, it was a challenge because I didn't know anything about that packets, and after few days of work I have managed to do what I wanted.

The hardest part was to set a very strict filter for the cpu usage and for the script optimisation, so here is one :

;use filters with _PcapStartCapture
;retreive only tcp packets containing AABBCCDD, at the start of 8 and with a length of 4; like the StringMid func.
tcp[8:4] == 0xAABBCCDD ;8th byte from the beginning of the tcp DATA, 4bytes length; always include the 0x to specify you are dealing with hex.

And some funcs to split the different data from packets :

;$hCapture is the handle returned by _PcapStartCapture
; #FUNCTION# ====================================================================================================================
; Name...........: _TCP_Recv
; Description ...: Retreives a TCP Packet and returns its data splitted
; Syntax.........: _TCP_Recv($hCapture, $iInstance = 0, $iTimeOut = 3000)
; Parameters ....: $hCapture    - Capture handle
;                   $iInstance    - Instance of the packet to retreive
;                   $iTimeOut    - Timeout
; Return values .: Success    - Array containing the packet data
;                   Failure    - -1 (timedout)
; Author ........: FireFox (d3mon)
; Modified.......:
; Remarks .......:
; Related .......: _UDP_Recv
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func _TCP_Recv($hCapture, $iInstance = 0, $iTimeOut = 3000)
    Local $blPacketCaptured = False, $iTimer_Capture, $aPacket, $iPacket

    $iTimer_Capture = TimerInit()

    While (TimerDiff($iTimer_Capture) < $iTimeOut Or $iTimeOut = -1)
        $aPacket = _PcapGetPacket($hCapture)

        If IsArray($aPacket) Then
            If $iPacket = $iInstance Then
                Local $aTCPPacket[21]

                $aTCPPacket[0] = StringMid($aPacket[3], 3, 12) ;Destination Mac Address
                $aTCPPacket[1] = StringMid($aPacket[3], 15, 12) ;Source Mac Address
                $aTCPPacket[2] = StringMid($aPacket[3], 27, 4) ;Type
                $aTCPPacket[3] = StringMid($aPacket[3], 31, 2) ;Version & Header length
                $aTCPPacket[4] = StringMid($aPacket[3], 33, 2) ;Differientiated Services Field
                $aTCPPacket[5] = StringMid($aPacket[3], 35, 4) ;Total Length
                $aTCPPacket[6] = StringMid($aPacket[3], 39, 4) ;Identification
                $aTCPPacket[7] = StringMid($aPacket[3], 43, 4) ;Fragment offset
                $aTCPPacket[8] = StringMid($aPacket[3], 47, 2) ;Time to live
                $aTCPPacket[9] = StringMid($aPacket[3], 49, 2) ;Protocol
                $aTCPPacket[10] = StringMid($aPacket[3], 51, 4) ;Header checksum
                $aTCPPacket[11] = StringMid($aPacket[3], 55, 8) ;Source IP Address
                $aTCPPacket[12] = StringMid($aPacket[3], 63, 8) ;Destination IP Address
                $aTCPPacket[13] = StringMid($aPacket[3], 71, 4) ;Source port
                $aTCPPacket[14] = StringMid($aPacket[3], 75, 4) ;Destination port
                $aTCPPacket[15] = StringMid($aPacket[3], 79, 8) ;Sequence number
                $aTCPPacket[16] = StringMid($aPacket[3], 87, 8) ;Acknowledgment number
                $aTCPPacket[17] = StringMid($aPacket[3], 95, 4) ;Flags
                $aTCPPacket[18] = StringMid($aPacket[3], 99, 4) ;Window size value
                $aTCPPacket[19] = StringMid($aPacket[3], 103, 4) ;Checksum
                ;107 to 110 = NULL data
                $aTCPPacket[20] = StringTrimLeft($aPacket[3], 110) ;Data

                Return $aTCPPacket
            EndIf
            $iPacket += 1
        EndIf

        Sleep(50)
    WEnd

    Return -1
EndFunc   ;==>_TCP_Recv

; #FUNCTION# ====================================================================================================================
; Name...........: _UDP_Recv
; Description ...: Retreives an UDP Packet and returns its data splitted
; Syntax.........: _UDP_Recv($hCapture, $iInstance = 0, $iTimeOut = 3000)
; Parameters ....: $hCapture    - Capture handle
;                   $iInstance    - Instance of the packet to retreive
;                   $iTimeOut    - Timeout
; Return values .: Success    - Array containing the packet data
;                   Failure    - -1 (timedout)
; Author ........: FireFox (d3mon)
; Modified.......:
; Remarks .......:
; Related .......: _TCP_Recv
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func _UDP_Recv($hCapture, $iInstance = 0, $iTimeOut = 3000)
    Local $blPacketCaptured = False, $iTimer_Capture, $aPacket, $iPacket

    $iTimer_Capture = TimerInit()

    While (TimerDiff($iTimer_Capture) < $iTimeOut Or $iTimeOut = -1)
        $aPacket = _PcapGetPacket($hCapture)

        If IsArray($aPacket) Then
            If $iPacket = $iInstance Then
                Local $aUDPPacket[18]

                $aUDPPacket[0] = StringMid($aPacket[3], 3, 12) ;Source Mac Address
                $aUDPPacket[1] = StringMid($aPacket[3], 15, 12) ;Destination Mac Address
                $aUDPPacket[2] = StringMid($aPacket[3], 27, 4) ;Type
                $aUDPPacket[3] = StringMid($aPacket[3], 31, 2) ;Version & Header length
                $aUDPPacket[4] = StringMid($aPacket[3], 33, 2) ;Differientiated Services Field
                $aUDPPacket[5] = StringMid($aPacket[3], 35, 4) ;Total Length
                $aUDPPacket[6] = StringMid($aPacket[3], 39, 4) ;Identification
                $aUDPPacket[7] = StringMid($aPacket[3], 43, 4) ;Fragment offset
                $aUDPPacket[8] = StringMid($aPacket[3], 47, 2) ;Time to live
                $aUDPPacket[9] = StringMid($aPacket[3], 49, 2) ;Protocol
                $aUDPPacket[10] = StringMid($aPacket[3], 51, 4) ;Header checksum
                $aUDPPacket[11] = StringMid($aPacket[3], 55, 8) ;Source IP Address
                $aUDPPacket[12] = StringMid($aPacket[3], 63, 8) ;Destination IP Address
                $aUDPPacket[13] = StringMid($aPacket[3], 71, 4) ;Source port
                $aUDPPacket[14] = StringMid($aPacket[3], 75, 4) ;Destination port
                $aUDPPacket[15] = StringMid($aPacket[3], 79, 4) ;Length
                $aUDPPacket[16] = StringMid($aPacket[3], 83, 4) ;Checksum
                $aUDPPacket[17] = StringTrimLeft($aPacket[3], 86) ;Data

                Return $aUDPPacket
            EndIf
            $iPacket += 1
        EndIf

        Sleep(50)
    WEnd

    Return -1
EndFunc   ;==>_UDP_Recv

;for example convert the packet's source/dest IP Address to text
; #FUNCTION# ====================================================================================================================
; Name...........: _HexIPAddressToText
; Description ...: Converts Hex IP Adress to text
; Syntax.........: _HexIPAddressToText($vhexIPAddress)
; Parameters ....: $vIPAddress    - IP Address v4 (string, int)
; Return values .: Success    - Converted IP Address
; Author ........: FireFox (d3mon)
; Modified.......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func _HexIPAddressToText($vhexIPAddress)
    Local $sIPAddress

    For $iOffset = 1 To 8 Step 2
        $sIPAddress &= Dec(StringMid($vhexIPAddress, $iOffset, 2)) & "."
    Next

    Return StringTrimRight($sIPAddress, 1)
EndFunc   ;==>_UDP_DecodeIPAddress

Ops, almost forgot the Winpcap UDF available here : http://opensource.grisambre.net/pcapau3/

PS : If you find this helpful, please "like"/rate this post.

Enjoy :guitar:

Edited by FireFox
  • Like 3

 

OS : Win XP SP2 (32 bits) / Win 7 SP1 (64 bits) / Win 8 (64 bits) | Autoit version: latest stable / beta.
Hardware : Intel(R) Core(TM) i5-2400 CPU @ 3.10Ghz / 8 GiB RAM DDR3.

My UDFs : Skype UDF | TrayIconEx UDF | GUI Panel UDF | Excel XML UDF | Is_Pressed_UDF

My Projects : YouTube Multi-downloader | FTP Easy-UP | Lock'n | WinKill | AVICapture | Skype TM | Tap Maker | ShellNew | Scriptner | Const Replacer | FT_Pocket | Chrome theme maker

My Examples : Capture toolIP Camera | Crosshair | Draw Captured Region | Picture Screensaver | Jscreenfix | Drivetemp | Picture viewer

My Snippets : Basic TCP | Systray_GetIconIndex | Intercept End task | Winpcap various | Advanced HotKeySet | Transparent Edit control

 

Share this post


Link to post
Share on other sites
Ontosy

How do I get uri of HTTP packet with winpcap?

Share this post


Link to post
Share on other sites
FireFox

@Ontosy

Here you go :

#include <String.au3>
...
Global $aPacket = _TCP_Recv(...)

If Dec($aPacket[13]) = 80 Then ;Source port = 80
$sPacketText = _HexToString($aTCPPacket[20])

... ;process
EndIf

In the $sPacketText you will have the request header where you will be able to retreive the URI.

Br, FireFox.

Edited by FireFox
  • Like 1

 

OS : Win XP SP2 (32 bits) / Win 7 SP1 (64 bits) / Win 8 (64 bits) | Autoit version: latest stable / beta.
Hardware : Intel(R) Core(TM) i5-2400 CPU @ 3.10Ghz / 8 GiB RAM DDR3.

My UDFs : Skype UDF | TrayIconEx UDF | GUI Panel UDF | Excel XML UDF | Is_Pressed_UDF

My Projects : YouTube Multi-downloader | FTP Easy-UP | Lock'n | WinKill | AVICapture | Skype TM | Tap Maker | ShellNew | Scriptner | Const Replacer | FT_Pocket | Chrome theme maker

My Examples : Capture toolIP Camera | Crosshair | Draw Captured Region | Picture Screensaver | Jscreenfix | Drivetemp | Picture viewer

My Snippets : Basic TCP | Systray_GetIconIndex | Intercept End task | Winpcap various | Advanced HotKeySet | Transparent Edit control

 

Share this post


Link to post
Share on other sites
Ontosy

ty

Edited by Ontosy

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

  • Similar Content

    • Jefrey
      By Jefrey
      Needed a way to store global temporary & permanent information and came up with this.
      This is inspired by NodeJS's store and store2 packages, as well as W3 specs' localStorage and sessionStorage, offering multiple ways of usage.
      This is not related to any browser's storage, nor will allow you to access or modify browsers storage - although this is possible and not a hard task, this is not what this UDF is intended to do.
      This UDF offers functions for temporary storage (that gets cleaned up once the application is shutdown) that is kept on memory using ScriptingDictionary, as well as for permanent storage, that is saved on the harddisk as an encrypted file.
      sessionStorage (temporary storage)
      It's useful to keep application state and temporary settings accessible by any part of your script (although it could also be done with a global variable, I still prefer this method).
      You have multiple ways, at your choice, to:
      ; add or modify a key sessionStorage("foo", "bar") store("foo", "bar") sessionStorage_set("foo", "bar") sessionStorage_setItem("foo", "bar") ; read a key (returns false if key does not exist) $read = sessionStorage("foo") $read = store("foo") $read = sessionStorage_get("foo") $read = sessionStorage_getItem("foo") ; delete a key sessionStorage_remove("foo") ; delete all keys sessionStorage_clear() sessionStorage_clearAll() localStorage (permanent storage)
      It's useful to store user-defined settings.
      ; initialize ; this is optional, but allows you to control ; how things are going to be saved localStorage_startup([file where you want the settings to be saved], [crypt password]) ; by default, if not supplied, if supplied the "Default" keyword (or if you dont initialize), ; the file will be a random-named file (based on @ScriptFullPath) at user's %APPDATA% ; and the password will also be based on @ScriptFullPath ; you can set only the crypt password if you want: ; localStorage_startup(Default, "mypassword") ; the usage is the same as sessionStorage ; add or modify a key localStorage("foo", "bar") store2("foo", "bar") ; notice the '2' localStorage_set("foo", "bar") localStorage_setItem("foo", "bar") ; read a key (returns false if key does not exist) $read = localStorage("foo") $read = store2("foo") $read = localStorage_get("foo") $read = localStorage_getItem("foo") ; delete a key localStorage_remove("foo") ; delete all keys localStorage_clear() localStorage_clearAll() Download
    • ripdad
      By ripdad
      I have had several people ask for this, so I decided to work the algorithm for it and this is the result.
      What is it?
      A Gateway Proxy Sends and Receives Data Unmodified.
      https://en.wikipedia.org/wiki/Proxy_server
      What is it used for?
      You can use it as a gateway, relay or router between two known static IP addresses.
      More information is in the header of the script.
      Download: LocalGatewayProxy.au3
      You will need WSA_NBTCP.au3 from here:
      https://www.autoitscript.com/forum/topic/191954-wsa_nbtcp-v100-udf/
      If you have any questions or problems, let me know.
       
    • ripdad
      By ripdad

      This script is based on algorithm code from EnrMa.
      Updated: January 22, 2018
      Made improvements. Changes are in the script header.
      Known Issues: AutoIt x64 does not work properly with this script.
      Download: LocalProxyServer_v1.00.zip
       
    • ripdad
      By ripdad
      WSA_NBTCP.au3  (Windows Sockets API - Non-Blocking Transmission Control Protocol)
      Version: 1.00
      Type: UDF
      This is an accumulation of WSA code from many sources and modified to suit myself.
      These functions have been thoroughly tested using a Local Proxy Server, which
      is about the most strenuous test you can use.
      Includes my rendition of how a TCPRecv Timeout should work. Also includes a
      timewait/timeout using Select for TCP Send, which works great for that function.
      You will need a loop to use _WSA_TCPRecv(). An example will be forthcoming in a second post.
      Functions:
      #CURRENT_USER_FUNCTIONS
      _WSA_Cleanup
      _WSA_FormatMessage
      _WSA_GetLastError
      _WSA_TCPAccept
      _WSA_TCPCloseSocket
      _WSA_TCPConnect
      _WSA_TCPListen
      _WSA_TCPRecv
      _WSA_TCPSend

      #INTERNAL_FUNCTIONS
      __TimeoutManager
      __TimeoutReset

      #EXTRA_FUNCTIONS
      _WSA_GetAddrInfo
      _WSA_GetHostByAddr
      _WSAAsyncGetHostByName
      _WSAAsyncGetHostByName_Callback
      _WSA_GetNameInfo
       
      Requirements:
      - AutoIt Versions: 3.3.8.1 thru 3.3.15.0 (32Bit only).
      - TCPStartup() at beginning of script on startup.
      - TCPShutDown() and _WSA_Cleanup() on exit.
      Download UDF: WSA_NBTCP.au3
       
    • tarretarretarre
      By tarretarretarre
      AutoIt-SocketIo
      Yep yep, this is pretty much an attempt to port the existing project's concept https://socket.io/ to AutoIt's Codebase. So i will not go in to so much detail.
      This is how the communication is done http://i.imgur.com/0mMfsBD.png Each client is isolated to the server http://i.imgur.com/rVO2LFb.png Features
      Easy API VarType Translation (Example: If the server sends an int, the client will receive an int and vice versa) Fully featured examples Data encryption (Using Autoit's UDF Crypt.au3) Limitations / Drawbacks
      It is not possible to Broadcast/Emit objects Only 1D-arrays are allowed to be Broadcasted/Emitted (2D arrays will probably never be supported) Changelog
      Version 1.5.0 (This update DOES NOT break scripts)
      Added AutoIt like docs under Docs\. The docs are generated so its a 1 to 1 reflection of the UDF headers. Print of documentation Added a production ready server example. Added a new method: _Io_DevDebug which will display useful information when debugging. Added a new method: _Io_SetMaxRecvPackageSize which defaults to whatever _Io_setRecvPackageSize is set to. Added a new method: _Io_setOnPrefix which defaults to _On_ Added a new default client & server event called flood. Flood occurs when exceeding the $__g_io_nMaxPacketSize. $__g_io_nMaxPacketSize is set by _Io_SetMaxRecvPackageSize Fixed the 16 parameter limit when sending data with _Io_Emit, _Io_Broadcast, _Io_BroadcastToAll and _Io_BroadcastToRoom. This works on the same premise that AutoIt's Call Does Fixed a TRUNCATION problem when receiving packages which could cause crashes! Fixed a programming error which caused $__g_ionPacketSize to reset to default 4096 if _Io_Connect or _Io_listenwere called after _Io_setRecvPackageSize Fixed _Io_setEventPreScript and _Io_setEventPostScript They didnt work. Lol. Changed how events are fired so the client cannot crash the server by sending the wrong number of parameters (This also allows for optional parameters on callbacks) Changed _Io_On. The second parameter $fCallback can now be set to null. Doing this, the function assumes that the callback is: _On_<eventName>.  
      Changelog History
      Api methods
      Please see the docs provided
      Default events
      Server events
      connection Client events
      banned Server and Client events
      disconnect flood View source on github
       
      Autoit-Socket-IO-1.0.0.zip (OLD!)
      Autoit-Socket-IO-1.1.0.zip (OLD)
      Autoit-Socket-IO-1.3.0.zip (OLD)
      Autoit-Socket-IO-1.4.0.zip (OLD)
      Autoit-Socket-IO-1.5.0.zip (NEWEST 2017-12-20)
×