Sign in to follow this  
Followers 0
Jimtags

Good example of TCPServer with basic security

2 posts in this topic

#1 ·  Posted (edited)

Hello this is my first started thread, I guess  :bye:

I coded this TCPServer script with the help from this topics

>Fast multi-client TCP Server

>Multiple connection TCP server

Ohh GOD wrong section.. my bad..

mod, please transfer this to Example section..

#include <ListViewConstants.au3>
#include <WindowsConstants.au3>
#include <ButtonConstants.au3>
#include <GUIConstantsEx.au3>
#include <EditConstants.au3>
#include <TabConstants.au3>
#include <GuiListView.au3>
#include <GUIListBox.au3>
#include <GuiMenu.au3>
#include <String.au3>
#include <Array.au3>
#include <Crypt.au3>
#include <File.au3>

TCPStartup() ;Start the TCP function
Opt("TCPTimeout", 0) ;We will make our own timeout
Opt("GUIOnEventMode", 1)
_Crypt_Startup() ;To optimized crypt function
OnAutoItExitRegister("Close") ;Call Close() function when script exit

#Region ;***User Setting***
Global $ServerBindToHost = IniRead("PXGWS.ini", "Server", "IP", "0.0.0.0") ;The IP will be used for TCP connections
Global $ServerBindToPort = IniRead("PXGWS.ini", "NetLib", "Port", 15998) ;The Port will be used for TCP connections
Global $PacketHeaderKey = BinaryToString("0x" & IniRead("PXGWS.ini", "Server", "HeaderXor", "FD2AC72E")) ;This is the packet header identifier
Global $PacketSecretKey = BinaryToString("0x" & IniRead("PXGWS.ini", "Server", "PacketXor", "B8E9ACD5")) ;This is the packet data encryption/decryption key
Global $PacketMaxSize = IniRead("PXGWS.ini", "NetLib", "MaxBufferSize", 2048) ;The packet data size to handle
Global $MaxClients = IniRead("PXGWS.ini", "NetLib", "MaxUserNum", 999) ;Total of connections to handle
Global $MaxTimeout = IniRead("PXGWS.ini", "NetLib", "ConnectTimeout", 65000) ;Maximum timeout of each connections
Global $XTrapDir = IniRead("PXGWS.ini", "Server", "XTrapDir", "XTrap") ;XTrap folder
Global $TimeFormat = IniRead("PXGWS.ini", "Server", "TimeFormat", 24) ;Time Format
Global $CabalMain = IniRead("PXGWS.ini", "Generator", "CabalMain", "CabalMain.exe")
Global $Parameter = IniRead("PXGWS.ini", "Generator", "Parameter", "husky")
Global $PXLibHost = IniRead("PXGWS.ini", "Generator", "PXLibHost", "127.0.0.1")
Global $CheckList = IniRead("PXGWS.ini", "Generator", "CheckList", "CabalOnline.ini")
#EndRegion ;***User Setting***

#Region ;***Data Identifiers
Global $REQ_DATA_SR = 100 ;Session request
Global $REQ_DATA_HB = 101 ;Heartbeart request
Global $REQ_DATA_XH = 102 ;XTrap Hash request
Global $CS2_DATA_XH = 103 ;XTrap Hash data
Global $S2C_DATA_ST = 200 ;Server Stopped
Global $S2C_DATA_SR = 201 ;Server Restarted
Global $S2C_DATA_SS = 202 ;Server Shutdown
Global $S2C_DATA_KC = 203 ;Terminate selected client connection
Global $S2C_DATA_KA = 204 ;Terminate all client connections
Global $C2S_DATA_DA = 300 ;Detected Application
Global $C2S_DATA_LO = 400 ;Client Logout
#EndRegion ;***Data Identifiers

#Region ;***Ignore if you don't know what you are doing***
Global $Listen = -1 ;The handle of TCPListen
Global $Client[1][20] ;[index][Socket,IP,Time,Data,List]
Global $Ws2_32 = DllOpen("Ws2_32.dll") ;Ws2_32.dll open handle
Global $NTDLL = DllOpen("ntdll.dll") ;ntdll.dll open handle
Global $Kernel32 = DllOpen("Kernel32.dll") ;kernel32.dll open handle
Global $InitialTime, $PacketCache, $UserBanList
Global $tmpList = FileRead("cl.tmp")
#EndRegion ;***Ignore if you don't know what you are doing***

#Region ### START Koda GUI section ### Form=C:\Program Files (x86)\AutoIt3\SciTE\Koda\Forms\Form2.kxf
Global $MAINGUI = GUICreate("PX2000 Game Watcher Server", 834, 384, 190, 113)
Global $LOGS = GUICtrlCreateList("", 8, 280, 817, 97, BitOR($LBS_NOTIFY, $LBS_NOINTEGRALHEIGHT, $LBS_NODATA, $WS_VSCROLL, $WS_BORDER), 0)
Global $TAB = GUICtrlCreateTab(8, 8, 817, 267, $TCS_FLATBUTTONS)
Global $TAB1 = GUICtrlCreateTabItem("Monitor")
Global $LIST = GUICtrlCreateListView("#|IP Address|Computer Name|Game Account|Status|LastUpdate", 19, 40, 649, 225)
Global $Group1 = GUICtrlCreateGroup("Server ", 676, 35, 137, 49, BitOR($GUI_SS_DEFAULT_GROUP, $BS_CENTER))
Global $SVRSTART = GUICtrlCreateButton("Start", 684, 51, 57, 25, $BS_FLAT)
Global $SVRSTOP = GUICtrlCreateButton("Stop", 748, 51, 57, 25, $BS_FLAT)
Global $Group2 = GUICtrlCreateGroup(" Control ", 677, 88, 137, 49, BitOR($GUI_SS_DEFAULT_GROUP, $BS_CENTER))
Global $KICKONE = GUICtrlCreateButton("Kick One", 685, 104, 57, 25, $BS_FLAT)
Global $KICKALL = GUICtrlCreateButton("Kick All", 749, 104, 57, 25, $BS_FLAT)
Global $Group3 = GUICtrlCreateGroup(" Setting ", 677, 142, 137, 124, BitOR($GUI_SS_DEFAULT_GROUP, $BS_CENTER))
Global $IP = GUICtrlCreateInput($ServerBindToHost, 688, 160, 113, 21, BitOR($GUI_SS_DEFAULT_INPUT, $ES_CENTER))
Global $PORT = GUICtrlCreateInput($ServerBindToPort, 688, 184, 56, 21, BitOR($GUI_SS_DEFAULT_INPUT, $ES_CENTER, $ES_NUMBER))
Global $MAXCLIENT = GUICtrlCreateInput($MaxClients, 747, 184, 54, 21, BitOR($GUI_SS_DEFAULT_INPUT, $ES_CENTER, $ES_NUMBER))
Global $MAXBUFFER = GUICtrlCreateInput($PacketMaxSize, 688, 208, 56, 21, BitOR($GUI_SS_DEFAULT_INPUT, $ES_CENTER, $ES_NUMBER))
Global $TIMEOUT = GUICtrlCreateInput($MaxTimeout, 747, 208, 54, 21, BitOR($GUI_SS_DEFAULT_INPUT, $ES_CENTER, $ES_NUMBER))
Global $SVRRELOAD = GUICtrlCreateButton("Apply and Restart", 688, 232, 113, 25, $BS_FLAT)
Global $TabSheet2 = GUICtrlCreateTabItem("Generator")
Global $Group4 = GUICtrlCreateGroup(" Param Generator ", 16, 34, 799, 231)
Global $Label1 = GUICtrlCreateLabel("CabalMain:", 24, 59, 57, 17)
Global $Input1 = GUICtrlCreateInput($CabalMain, 88, 56, 113, 21)
GUICtrlSetTip(-1, "Your CabalMain.exe")
Global $Label2 = GUICtrlCreateLabel("Parameter:", 208, 59, 55, 17)
Global $Input2 = GUICtrlCreateInput($Parameter, 272, 56, 113, 21)
GUICtrlSetTip(-1, "You CabalMain parameter")
Global $Label3 = GUICtrlCreateLabel("Server IP:", 24, 83, 51, 17)
Global $Input3 = GUICtrlCreateInput($ServerBindToHost, 88, 80, 113, 21)
GUICtrlSetTip(-1, "PXGW Server IP")
Global $Label4 = GUICtrlCreateLabel("Server Port:", 208, 83, 56, 17)
Global $Input4 = GUICtrlCreateInput($ServerBindToPort, 272, 80, 113, 21)
GUICtrlSetTip(-1, "PXGW Server Port")
Global $Label5 = GUICtrlCreateLabel("Check List:", 392, 83, 57, 17)
Global $Input5 = GUICtrlCreateInput($CheckList, 456, 80, 113, 21)
GUICtrlSetTip(-1, "List of trainers")
Global $Label6 = GUICtrlCreateLabel("URL: http://", 392, 59, 63, 17)
Global $Input6 = GUICtrlCreateInput($PXLibHost, 456, 56, 113, 21)
GUICtrlSetTip(-1, "URL to download PXLib32.dll and PXLib64.dll")
Global $Edit1 = GUICtrlCreateEdit("", 24, 104, 361, 153, BitOR($ES_AUTOVSCROLL, $ES_READONLY, $ES_WANTRETURN, $WS_VSCROLL))
GUICtrlSetData(-1, "Your PXGWC parameter will show here.")
Global $Button6 = GUICtrlCreateButton("Generate Parameter and Check List", 576, 80, 233, 20, $BS_FLAT)
Global $Label7 = GUICtrlCreateLabel("/PXLib32.dll and PXLib64.dll", 574, 59, 139, 17)
Global $Edit2 = GUICtrlCreateEdit("", 392, 104, 417, 153, BitOR($ES_AUTOVSCROLL, $ES_WANTRETURN, $WS_VSCROLL))
GUICtrlSetData(-1, $tmpList)
GUICtrlSetFont(-1, 9, 400, 0, "Lucida Console")
GUICtrlSetTip(-1, "#MD5 Hashes of application you want PXGWC to detect it.")
GUICtrlSetLimit($IP, 15)
GUICtrlSetTip($IP, "Server IP Address")
GUICtrlSetLimit($PORT, 5)
GUICtrlSetTip($PORT, "Server Port Address")
GUICtrlSetLimit($MAXCLIENT, 3)
GUICtrlSetTip($MAXCLIENT, "Maximum client connections")
GUICtrlSetLimit($MAXBUFFER, 4)
GUICtrlSetTip($MAXBUFFER, "Max buffer to accept")
GUICtrlSetLimit($TIMEOUT, 5)
GUICtrlSetTip($TIMEOUT, "Maximum connection timeout")
GUICtrlSendMsg($LIST, $LVM_SETCOLUMNWIDTH, 0, 35)
GUICtrlSendMsg($LIST, $LVM_SETCOLUMNWIDTH, 1, 100)
GUICtrlSendMsg($LIST, $LVM_SETCOLUMNWIDTH, 2, 120)
GUICtrlSendMsg($LIST, $LVM_SETCOLUMNWIDTH, 3, 110)
GUICtrlSendMsg($LIST, $LVM_SETCOLUMNWIDTH, 4, 175)
GUICtrlSendMsg($LIST, $LVM_SETCOLUMNWIDTH, 5, 105)
GUICtrlSendMsg($LOGS, $LVM_SETCOLUMNWIDTH, 0, 150)
GUICtrlSendMsg($LOGS, $LVM_SETCOLUMNWIDTH, 1, 663)
GUISetOnEvent($GUI_EVENT_CLOSE, "Close")
GUICtrlSetOnEvent($SVRSTART, "_ServerListenStart")
GUICtrlSetOnEvent($SVRSTOP, "_ServerListenStop")
GUICtrlSetOnEvent($KICKONE, "_ConnectionKill")
GUICtrlSetOnEvent($KICKALL, "_ConnectionKillAll")
GUICtrlSetOnEvent($SVRRELOAD, "_ServerReload")
GUICtrlSetOnEvent($Button6, "_Generate")
GUICtrlSetState($SVRSTOP, $GUI_DISABLE)
GUICtrlSetState($KICKONE, $GUI_DISABLE)
GUICtrlSetState($KICKALL, $GUI_DISABLE)
GUISetState(@SW_SHOW)
#EndRegion ### END Koda GUI section ###

CheckSetting()
_Main()

Func _Main()
    $Client[0][0] = 0
    AddLogView($LOGS, "PX2000 XTrap Auth Server", 0)
    AddLogView($LOGS, "Build Version " & StringTrimLeft(FileGetVersion(@AutoItExe), 4), 0)
    While 1
        _CheckNewConnections()
        _CheckNewPackets()
        _CheckBadConnection()
        NSleep(1000, $NTDLL)
    WEnd
EndFunc   ;==>_Main

Func _CheckNewConnections()
    Local $iSock = TCPAccept($Listen)
    If $iSock = -1 Then Return
    Local $iSize = UBound($Client, 1)
    If $iSize - 1 > $MaxClients And $MaxClients > 0 Then
        TCPCloseSocket($iSock)
        Return
    EndIf
    ReDim $Client[$iSize + 1][20]
    $Client[0][0] = $iSize
    $Client[$iSize][0] = $iSock
    $Client[$iSize][1] = SocketIP($iSock, $Ws2_32)
    $Client[$iSize][2] = TimerInit()
    $Client[$iSize][3] = "" ; Packet buffer
    $Client[$iSize][4] = "" ; Connection error buffer
    $Client[$iSize][5] = "" ; Identifier buffer
    $Client[$iSize][6] = "" ; Heartbeat count buffer
    $Client[$iSize][7] = "" ; Computer/Username buffer
    $Client[$iSize][8] = "" ; Unused buffer
    $Client[$iSize][9] = "" ; Unused buffer
    $Client[$iSize][10] = "" ; Unused buffer
    $Client[$iSize][11] = "" ; Unused buffer
    $Client[$iSize][12] = "" ; Unused buffer
    $Client[$iSize][13] = "" ; Unused buffer
    $Client[$iSize][14] = "" ; Unused buffer
    $Client[$iSize][15] = "" ; Unused buffer
    $Client[$iSize][16] = "" ; Unused buffer
    $Client[$iSize][17] = "" ; Unused buffer
    $Client[$iSize][18] = "" ; Unused buffer
    $Client[$iSize][19] = GUICtrlCreateListViewItem($iSize & "|" & $Client[$iSize][1] & "||N/A||" & $InitialTime, $LIST)
EndFunc   ;==>_CheckNewConnections

Func _CheckBadConnection()
    If $Client[0][0] < 1 Then Return
    Local $iNewSize = 0
    For $i = 1 To $Client[0][0]
        If $Client[$i][4] <> 1 Or Round(TimerDiff($Client[$i][2])) > $MaxTimeout Then
            TCPCloseSocket($Client[$i][0])
            GUICtrlDelete($Client[$i][19])
            $Client[$i][0] = ""
            $Client[$i][4] = ""
            $Client[$i][5] = ""
            $Client[$i][6] = ""
            $Client[$i][7] = ""
            $Client[$i][8] = ""
            $Client[$i][9] = ""
            $Client[$i][11] = ""
            $Client[$i][12] = ""
            $Client[$i][13] = ""
            $Client[$i][14] = ""
            $Client[$i][15] = ""
            $Client[$i][16] = ""
            $Client[$i][17] = ""
            $Client[$i][18] = ""
            ContinueLoop
        Else
            $iNewSize += 1
        EndIf
    Next
    If $iNewSize < $Client[0][0] Then
        Local $iSize = UBound($Client, 2) - 1
        Local $aTemp[$iNewSize + 1][$iSize + 1]
        Local $iCount = 1
        For $i = 1 To $Client[0][0]
            If $Client[$i][0] = "" Then ContinueLoop
            For $j = 0 To $iSize
                $aTemp[$iCount][$j] = $Client[$i][$j]
            Next
            $iCount += 1
        Next
        $aTemp[0][0] = $iNewSize
        $Client = $aTemp
        For $i = 1 To $Client[0][0]
            GUICtrlSetData($Client[$i][19], $i)
        Next
    EndIf
EndFunc   ;==>_CheckBadConnection

Func _CheckNewPackets()
    If $Client[0][0] < 1 Then Return ;No connections then return to _Main()
    Local $RecvPacket
    For $i = 1 To $Client[0][0]
        $RecvPacket = TCPRecv($Client[$i][0], $PacketMaxSize, 1) ; Attempt to receive data
        If $RecvPacket <> "" Then
            If CheckHeader($RecvPacket) = 0 Then
                AddLogView($LOGS, "Unknown Client from IP [" & $Client[$i][1] & "]")
                $Client[$i][4] = -1 ; The packet don't have the spicified packet header, let's set this as invalid one
                Return
            Else
                $Client[$i][3] &= $RecvPacket ; Add it to the packet buffer.
                ConsoleWrite(">> New Packet from " & SocketIP($Client[$i][0]) & @CRLF & "+> " & $RecvPacket & @CRLF & @CRLF) ; Let us know we got a packet in scite.
            EndIf
            Local $RawPackets = $Client[$i][3] ; Transfer all the data we have to a new variable.
            Local $StripHeader = StripHeader($RawPackets) ; Removing the packet header
            Local $DecryptData = PacketDec($StripHeader, $PacketSecretKey) ; Decrypting the data
            If $DecryptData <> "" Then
                Local $Calculator = Dec(StringMid($DecryptData, 1, 8))
                Local $PacketHash = StringMid($DecryptData, 9, $Calculator) ; Retrieving the packet hash
                Local $RequestType = Dec(StringMid($DecryptData, 9 + $Calculator, 8)) ; Retrieving the request type
                Local $RequestData = _HexToString(StringTrimLeft($DecryptData, 16 + $Calculator)) ; Retrieving the packet data
                $Client[$i][5] = $PacketHash ; Packet hash to avoid duplicated packet or packet resend
                $Client[$i][3] = StringTrimLeft($Client[$i][3], StringLen($RecvPacket)) ;We are done extracting the packet let's now empty the buffer
                ConsoleWrite(">> Full packet found!" & @CRLF)
                ConsoleWrite("+> Unpacked: " & $DecryptData & @CRLF)
                ConsoleWrite("+> Hash: " & $Client[$i][5] & @CRLF)
                ConsoleWrite("+> Type: " & $RequestType & @CRLF)
                ConsoleWrite("+> Data: " & $RequestData & @CRLF)
                ConsoleWrite("+> LeftOver: " & $Client[$i][3] & @CRLF)
                If StringInStr($PacketCache, $Client[$i][5]) <> 0 Then
                    AddLogView($LOGS, "Received duplicated packet from User IP [" & $Client[$i][1] & "]. This is malicious action!")
                    $Client[$i][4] = -1
                    ConsoleWrite(@CRLF)
                    Return
                Else
                    ConsoleWrite("+> PacketCache Current Size: " & StringLen($PacketCache) & @CRLF & @CRLF)
                    If StringLen($PacketCache) > 2048 Then $PacketCache = ""
                    $PacketCache &= $Client[$i][5] & @CRLF
                    _ProcessFullPacket($RequestData, $RequestType, $i)
                EndIf
            Else
                $Client[$i][4] = -1
            EndIf
        EndIf
    Next
EndFunc   ;==>_CheckNewPackets

Func _ProcessFullPacket($PacketData, $PacketType, $sID)
    Local $i = $sID
    Switch $PacketType
        Case $REQ_DATA_SR
            $Client[$i][4] = 1
            $Client[$i][7] = $PacketData
            GUICtrlSetData($Client[$i][19], "||" & $Client[$i][7] & "||Connection Established")
            AddLogView($LOGS, "Established connection from IP [" & $Client[$i][1] & "]")
        Case $REQ_DATA_HB
            Local $BeatCount = 1
            $Client[$i][2] = TimerInit()
            $Client[$i][6] += $BeatCount
            GUICtrlSetData($Client[$i][19], "||" & $Client[$i][7] & "||Heartbeat Count " & $Client[$i][6] & "|" & Hour($PacketData, $TimeFormat))
            AddLogView($LOGS, "Heartbeat is okey from IP [" & $Client[$i][1] & "]", 0)
        Case $REQ_DATA_XH
            If $PacketData <> XTrapHash() Then
                Local $Data = PacketEnc(Hex($CS2_DATA_XH) & _StringToHex(XTrapHash()))
                Local $Packet = $PacketHeaderKey & $Data
                TCPSend($Client[$i][0], BinaryToString($Packet))
                GUICtrlSetData($Client[$i][19], "||||XTrap Check Error")
                AddLogView($LOGS, "Client " & $Client[$i][7] & " has different XTrap version from the server")
                $Client[$i][4] = -1
            EndIf
        Case $C2S_DATA_DA
            AddLogView($LOGS, $PacketData & " is detected from client " & $Client[$i][7])
            $Client[$i][4] = -1
        Case $C2S_DATA_LO
            GUICtrlSetData($Client[$i][19], "||||User Logout|" & Hour($PacketData, $TimeFormat))
    EndSwitch
EndFunc   ;==>_ProcessFullPacket

Func Close()
    If $Client[0][0] >= 1 Then
        For $i = 1 To $Client[0][0]
            Sleep($Client[0][0] - $i)
            Local $Data = PacketEnc(Hex($S2C_DATA_SS) & _StringToHex("Server has been shutdown."))
            Local $Packet = $PacketHeaderKey & $Data
            TCPSend($Client[$i][0], BinaryToString($Packet))
            TCPCloseSocket($Client[$i][0])
        Next
    EndIf
    DllClose($Ws2_32)
    DllClose($NTDLL)
    DllClose($Kernel32)
    TCPShutdown()
    _Crypt_Shutdown()
    $PacketCache = ""
    Exit
EndFunc   ;==>Close

Func SocketIP($Sock, $hDLL = "Ws2_32.dll")
    Local $structName = DllStructCreate("short;ushort;uint;char[8]")
    Local $sRet = DllCall($hDLL, "int", "getpeername", "int", $Sock, "ptr", DllStructGetPtr($structName), "int*", DllStructGetSize($structName))
    If Not @error Then
        $sRet = DllCall($hDLL, "str", "inet_ntoa", "int", DllStructGetData($structName, 3))
        If Not @error Then Return $sRet[0]
    EndIf
    Return "0.0.0.0"
EndFunc   ;==>SocketIP

Func NSleep($nSleep, $hDLL = "ntdll.dll")
    Local $hStruct = DllStructCreate("int64")
    DllStructSetData($hStruct, 1, -1 * ($nSleep * 10))
    DllCall($hDLL, "dword", "ZwDelayExecution", "int", 0, "ptr", DllStructGetPtr($hStruct))
EndFunc   ;==>NSleep

Func PacketEnc($EncData, $EncKey = $PacketSecretKey)
    Local $EncOut0 = MD5Data(Random(11111111, 99999999, 1))
    Local $EncOut1 = Random(111111, 999999, 1) & Hex(StringLen($EncOut0)) & $EncOut0
    Local $EncOut2 = _Crypt_EncryptData($EncOut1 & $EncData, $EncKey, $CALG_AES_256)
    Return BinaryToString($EncOut2)
EndFunc   ;==>PacketEnc

Func PacketDec($DecData, $DecKey = $PacketSecretKey)
    Local $DecOut1 = _Crypt_DecryptData($DecData, $DecKey, $CALG_AES_256)
    Local $DecOut2 = BinaryToString($DecOut1)
    Return StringTrimLeft($DecOut2, 6)
EndFunc   ;==>PacketDec

Func CheckHeader($RawPacketData)
    Local $CheckHeader1 = StringTrimLeft($RawPacketData, 2)
    Local $CheckHeader2 = StringLen(StringTrimLeft(StringToBinary($PacketHeaderKey), 2))
    Local $CheckHeader3 = StringMid($CheckHeader1, 1, $CheckHeader2)
    Local $CheckHeader4 = StringTrimLeft(StringToBinary($PacketHeaderKey), 2)
    If $CheckHeader3 = $CheckHeader4 Then Return 1
EndFunc   ;==>CheckHeader

Func StripHeader($RawPacketData)
    Local $StripHeader1 = StringTrimLeft($RawPacketData, 2)
    Local $StripHeader2 = StringLen(StringTrimLeft(StringToBinary($PacketHeaderKey), 2))
    Local $StripHeader3 = StringTrimLeft($StripHeader1, $StripHeader2)
    Return BinaryToString("0x" & $StripHeader3)
EndFunc   ;==>StripHeader

Func XTrapHash($iDir = $XTrapDir)
    Local $XTemp1 = MD5File($iDir & "\psapi.dll")
    Local $XTemp2 = MD5File($iDir & "\XDataFI0.Xtp")
    Local $XTemp3 = MD5File($iDir & "\XTrap.xt")
    Local $XTemp4 = MD5File($iDir & "\XTrapExt.dll")
    Local $XTemp5 = MD5File($iDir & "\XTrapVa.dll")
    Return MD5Data($XTemp1 & $XTemp2 & $XTemp3 & $XTemp4 & $XTemp5)
EndFunc   ;==>XTrapHash

Func MD5File($iFile)
    Local $FileHash1 = _Crypt_HashFile($iFile, $CALG_MD5)
    Return StringTrimLeft($FileHash1, 2)
EndFunc   ;==>MD5File

Func MD5Data($iStr)
    Local $DataHash1 = _Crypt_HashData($iStr, $CALG_MD5)
    Return StringTrimLeft($DataHash1, 2)
EndFunc   ;==>MD5Data

Func _ServerListenStart()
    If $Listen <> -1 Then
        AddLogView($LOGS, "Socket already open")
        Return
    Else
        $Listen = TCPListen($ServerBindToHost, $ServerBindToPort, $MaxClients)
        If $Listen = -1 Then
            AddLogView($LOGS, "Unable to open socket")
            Return
        EndIf
    EndIf
    GUICtrlSetState($SVRSTART, $GUI_DISABLE)
    GUICtrlSetState($SVRSTOP, $GUI_ENABLE)
    GUICtrlSetState($KICKONE, $GUI_ENABLE)
    GUICtrlSetState($KICKALL, $GUI_ENABLE)
    AddLogView($LOGS, "Server started on " & $ServerBindToHost & ":" & $ServerBindToPort)
EndFunc   ;==>_ServerListenStart

Func _ServerListenStop()
    If $Listen = -1 Then
        AddLogView($LOGS, "Socket already closed")
        Return
    EndIf
    For $i = 1 To $Client[0][0]
        Sleep($Client[0][0] - $i)
        Local $Data = PacketEnc(Hex($S2C_DATA_ST) & _StringToHex("Server has been stopped."))
        Local $Packet = $PacketHeaderKey & $Data
        TCPSend($Client[$i][0], BinaryToString($Packet))
        $Client[$i][4] = -1
    Next
    GUICtrlSetState($SVRSTART, $GUI_ENABLE)
    GUICtrlSetState($SVRSTOP, $GUI_DISABLE)
    GUICtrlSetState($KICKONE, $GUI_DISABLE)
    GUICtrlSetState($KICKALL, $GUI_DISABLE)
    AddLogView($LOGS, "Server stopped, (" & $Client[0][0] & ") total clients has been disconnected")
    TCPCloseSocket($Listen)
    $Listen = -1
    $PacketCache = ""
EndFunc   ;==>_ServerListenStop

Func _ServerReload()
    GUICtrlSetState($SVRRELOAD, $GUI_DISABLE)
    GUICtrlSetData($SVRRELOAD, "Restarting...")
    GUICtrlSetState($SVRSTART, $GUI_ENABLE)
    GUICtrlSetState($SVRSTOP, $GUI_DISABLE)
    GUICtrlSetState($KICKONE, $GUI_DISABLE)
    GUICtrlSetState($KICKALL, $GUI_DISABLE)
    If Not $Listen = -1 Then
        If $Client[0][0] >= 1 Then
            For $i = 1 To $Client[0][0]
                Sleep($Client[0][0] - $i)
                Local $Data = PacketEnc(Hex($S2C_DATA_SR) & _StringToHex("Server has been restarted"))
                Local $Packet = $PacketHeaderKey & $Data
                TCPSend($Client[$i][0], BinaryToString($Packet))
                $Client[$i][4] = -1
            Next
            AddLogView($LOGS, "Server stopped for restart, (" & $Client[0][0] & ") total clients has been disconnected")
        EndIf
    EndIf
    TCPCloseSocket($Listen)
    $Listen = -1
    $PacketCache = ""
    IniWrite("PXGWS.ini", "Server", "IP", GUICtrlRead($IP))
    IniWrite("PXGWS.ini", "NetLib", "Port", GUICtrlRead($PORT))
    IniWrite("PXGWS.ini", "NetLib", "MaxBufferSize", GUICtrlRead($MAXBUFFER))
    IniWrite("PXGWS.ini", "NetLib", "MaxUserNum", GUICtrlRead($MAXCLIENT))
    IniWrite("PXGWS.ini", "NetLib", "ConnectTimeout", GUICtrlRead($TIMEOUT))
    $ServerBindToHost = GUICtrlRead($IP)
    $ServerBindToPort = GUICtrlRead($PORT)
    $PacketMaxSize = GUICtrlRead($MAXBUFFER)
    $MaxClients = GUICtrlRead($MAXCLIENT)
    $MaxTimeout = GUICtrlRead($TIMEOUT)
    TCPShutdown()
    TCPStartup()
    _ServerListenStart()
    GUICtrlSetData($SVRRELOAD, "Save/Restart")
    GUICtrlSetState($SVRRELOAD, $GUI_ENABLE)
EndFunc   ;==>_ServerReload

Func _ConnectionKill()
    Local $Selected = GUICtrlRead(GUICtrlRead($LIST))
    If Not $Selected <> "" Then
        AddLogView($LOGS, "Please select a connection to disconnect")
        Return
    EndIf
    Local $Data = PacketEnc(Hex($S2C_DATA_KC) & _StringToHex("You have been kicked from the server."))
    Local $Packet = $PacketHeaderKey & $Data
    Local $x = StringSplit($Selected, "|", 1)
    Local $i = $x[1]
    TCPSend($Client[$i][0], BinaryToString($Packet))
    AddLogView($LOGS, "Terminate client successful, client " & $Client[$i][7] & " has been disconnected")
    $Client[$i][4] = -1
EndFunc   ;==>_ConnectionKill

Func _ConnectionKillAll()
    If $Client[0][0] >= 1 Then
        For $i = 1 To $Client[0][0]
            If $Client[$i][0] > 0 Then
                Sleep($Client[0][0] - $i)
                Local $Data = PacketEnc(Hex($S2C_DATA_KA) & _StringToHex("All client's has been kicked from the server."))
                Local $Packet = $PacketHeaderKey & $Data
                TCPSend($Client[$i][0], BinaryToString($Packet))
                $Client[$i][4] = -1
            EndIf
        Next
    Else
        AddLogView($LOGS, "No connections to close")
        Return
    EndIf
    $PacketCache = ""
    AddLogView($LOGS, "Terminate all client successful, (" & $Client[0][0] & ") total clients has been disconnected")
EndFunc   ;==>_ConnectionKillAll

Func AddLogView($hListBox, $hListBoxMsg, $isLog = 1)
    If $isLog = 1 Then
        WriteLog($hListBoxMsg)
        _GUICtrlListBox_BeginUpdate($hListBox)
        _GUICtrlListBox_AddString($hListBox, "[" & @HOUR & ":" & @MIN & ":" & @SEC & ":" & @MSEC & "] > " & $hListBoxMsg)
        _GUICtrlListBox_SetTopIndex($hListBox, _GUICtrlListBox_GetListBoxInfo($hListBox) - 1)
        _GUICtrlListBox_UpdateHScroll($hListBox)
        _GUICtrlListBox_EndUpdate($hListBox)
    ElseIf $isLog = 0 Then
        _GUICtrlListBox_BeginUpdate($hListBox)
        _GUICtrlListBox_AddString($hListBox, "[" & @HOUR & ":" & @MIN & ":" & @SEC & ":" & @MSEC & "] > " & $hListBoxMsg)
        _GUICtrlListBox_SetTopIndex($hListBox, _GUICtrlListBox_GetListBoxInfo($hListBox) - 1)
        _GUICtrlListBox_UpdateHScroll($hListBox)
        _GUICtrlListBox_EndUpdate($hListBox)
    Else
        Return @error - 1
    EndIf
EndFunc   ;==>AddLogView

Func Hour($cTime, $iFormat = 24)
    Local $Time = StringSplit($cTime, "/")
    ConsoleWrite($Time & @CRLF)
    If Not $Time[0] = 7 Then
        Return @error - 1
    Else
        If $iFormat = 24 Then
            Return $Time[4] & ":" & $Time[5] & ":" & $Time[6] & ":" & $Time[7]
        ElseIf $iFormat = 12 Then
            Local $HOUR
            Local $AMPM
            If $Time[4] >= 01 And $Time[4] <= 11 Then
                If StringMid($Time[4], 1, 1) = 0 Then
                    $HOUR = StringTrimLeft($Time[4], 1)
                Else
                    $HOUR = $Time[4]
                EndIf
            ElseIf $Time[4] = 00 Or $Time[4] = 12 Then
                $HOUR = 12
            Else
                $HOUR = $Time[4] - 12
            EndIf
            If $Time[4] = 00 Or $Time[4] >= 01 And $Time[4] <= 11 Then
                $AMPM = "AM"
            Else
                $AMPM = "PM"
            EndIf
            Return $HOUR & ":" & $Time[5] & ":" & $Time[6] & " " & $AMPM
        Else
            Return @error - 2
        EndIf
    EndIf
EndFunc   ;==>Hour

Func WriteLog($lMsg)
    FileWrite(@ScriptDir & "\" & @YEAR & @MON & @MDAY & "_FatalLog.txt", @YEAR & "-" & @MON & "-" & @MDAY & @TAB & @HOUR & ":" & @MIN & ":" & @SEC & ":" & @MSEC & @TAB & $lMsg & @CRLF)
EndFunc   ;==>WriteLog

Func CheckSetting()
    Local $XPath = _FileListToArray(@ScriptDir, $XTrapDir, 2)
    If StringInStr($PacketHeaderKey, "0x") <> 0 Then
        GUIDelete($MAINGUI)
        MsgBox(16, "Error", "Header xor must be in hex.")
        Exit
    ElseIf StringLen($PacketHeaderKey) <> 4 Then
        GUIDelete($MAINGUI)
        MsgBox(16, "Error", "Header xor must be 8 bytes long.")
        Exit
    ElseIf StringInStr($PacketSecretKey, "0x") <> 0 Then
        GUIDelete($MAINGUI)
        MsgBox(16, "Error", "Packet xor must be in hex.")
        Exit
    ElseIf StringLen($PacketSecretKey) <> 4 Then
        GUIDelete($MAINGUI)
        MsgBox(16, "Error", "Packet xor must be 8 bytes long.")
        Exit
    ElseIf $PacketMaxSize > 2048 Then
        GUIDelete($MAINGUI)
        MsgBox(16, "Error", "Error Code: " & 1004)
        Exit
    ElseIf $MaxClients >= 1000 Then
        GUIDelete($MAINGUI)
        MsgBox(16, "Error", "Error Code: " & 1005)
        Exit
    ElseIf $MaxTimeout < 65000 Then
        GUIDelete($MAINGUI)
        MsgBox(16, "Error", "Error Code: " & 1006)
        Exit
    ElseIf $XPath = 0 Then
        GUIDelete($MAINGUI)
        MsgBox(16, "Error", "Error Code: " & 1007)
        Exit
    ElseIf $TimeFormat <> 12 And $TimeFormat <> 24 Then
        GUIDelete($MAINGUI)
        MsgBox(16, "Error", "Error Code: " & 1008)
        Exit
    EndIf
    If $TimeFormat = 12 Then
        $InitialTime = "--:--:-- --"
    Else
        $InitialTime = "--:--:--:---"
    EndIf
EndFunc   ;==>CheckSetting

Func PCrypt($1, $2, $3, $4, $5, $6)
    Local $CmdParam1 = _Crypt_EncryptData($1 & "|" & $2 & "|" & $3 & "|" & $4 & "|" & $5 & "|" & $6, $PacketSecretKey, $CALG_AES_256)
    Return StringTrimLeft($CmdParam1, 2)
EndFunc   ;==>PCrypt

Func _Generate()
    Local $gTimer = TimerInit()
    Local $main = GUICtrlRead($Input1)
    Local $parm = GUICtrlRead($Input2)
    Local $hsts = GUICtrlRead($Input3)
    Local $prts = GUICtrlRead($Input4)
    Local $lsts = GUICtrlRead($Input5)
    Local $link = GUICtrlRead($Input6)
    Local $pOut = PCrypt($main, $parm, $hsts, $prts, $lsts, $link)
    GUICtrlSetData($Edit1, "-Usage" & @CRLF & "PXGWC.exe EncryptedParam" & @CRLF & @CRLF & "-EncryptedParam" & @CRLF & $pOut & @CRLF & @CRLF & "Example: PXGWC.exe " & $pOut)
    If FileExists(GUICtrlRead($Input5)) Then FileDelete(GUICtrlRead($Input5))
    Local $iHash = MD5Data(GUICtrlRead($Edit2))
    Local $eData = _Crypt_EncryptData($iHash & GUICtrlRead($Edit2), $PacketSecretKey, $CALG_RC4)
    FileDelete("cl.tmp")
    FileDelete($CheckList)
    FileWrite("cl.tmp", GUICtrlRead($Edit2))
    FileWrite($lsts, BinaryToString($eData))
    IniWrite("PXGWS.ini", "Generator", "CabalMain", $main)
    IniWrite("PXGWS.ini", "Generator", "Parameter", $parm)
    IniWrite("PXGWS.ini", "Generator", "PXLibHost", $link)
    IniWrite("PXGWS.ini", "Generator", "CheckList", $lsts)
    Local $fTimer = Round(TimerDiff($gTimer))
    AddLogView($LOGS, "File created on " & @ScriptDir & "\" & $lsts)
    AddLogView($LOGS, "Generated in " & $fTimer & "ms.")
EndFunc   ;==>_Generate
Edited by Jimtags

Share this post


Link to post
Share on other sites



#2 ·  Posted (edited)

Are you asking for help with a problem? If not, this would be better suited for the Examples section, rather than Help and Support. If you do require assistance, please explain in detail what you're having a problem with.

Edited by JLogan3o13

When you're dead, you don't know you're dead - it's only difficult for those that know you. It's the same way when you're stupid...

My Scripts: SCCM UDFInclude Source with Compiled Script, Windows Firewall UDF

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  
Followers 0