WinBatch® Technical Support Forum

All Things WinBatch => WinBatch => Topic started by: stanl on March 23, 2021, 03:19:53 AM

Title: Scan Port 443
Post by: stanl on March 23, 2021, 03:19:53 AM
Just a general question. If I want to enumerate the Established IP connections to remote port 443 - can this be accomplished with WB's Winsock Extender or use something else?
Title: Re: Scan Port 443
Post by: td on March 23, 2021, 07:18:05 AM
Do you mean the connections made from one local computer to any remote computers over the 443 port or are you referring to all the 443 connections from all computers to a single remote computer?
Title: Re: Scan Port 443
Post by: td on March 23, 2021, 07:38:54 AM
Of course, there is the no-code technique of using the "netstat" command-line tool to get local connections.

netstat -an | find "443"
Title: Re: Scan Port 443
Post by: td on March 23, 2021, 09:28:51 AM
I suspect that you already know this but you can always use your favored PS. The cmdlet is Get-NetTCPConnection.

https://docs.microsoft.com/en-us/powershell/module/nettcpip/get-nettcpconnection?view=windowsserver2019-ps

Title: Re: Scan Port 443
Post by: stanl on March 24, 2021, 03:05:31 AM
Quote from: td on March 23, 2021, 09:28:51 AM
I suspect that you already know this but you can always use your favored PS. The cmdlet is Get-NetTCPConnection.

https://docs.microsoft.com/en-us/powershell/module/nettcpip/get-nettcpconnection?view=windowsserver2019-ps (https://docs.microsoft.com/en-us/powershell/module/nettcpip/get-nettcpconnection?view=windowsserver2019-ps)


Yes, I know and there is a script for that. This would have to be an additional menu option to an existing WB program I compiled in 2016. The PS script goes the extra mile of accessing https://ipinfo.io/[ip address(s) from port 443]/json - to get extended information and I have code for submitting ip addresses to that URL in place.
Title: Re: Scan Port 443
Post by: td on March 24, 2021, 08:41:05 AM
LLC normally uses the Registries of Intenet Numbers directly (along with blacklist services and malformed request detection) for detecting malicious actors on this board and on other sites. But the site you mentioned is handy because it is one place to look instead of five Registries.
Title: Re: Scan Port 443
Post by: stanl on March 24, 2021, 02:31:38 PM
Quote from: td on March 24, 2021, 08:41:05 AM
LLC normally uses the Registries of Intenet Numbers directly (along with blacklist services and malformed request detection) for detecting malicious actors on this board and on other sites. But the site you mentioned is handy because it is one place to look instead of five Registries.


Fine.. and below is PS Script... but the ask was could getting the IP's from 443 be accomplished in WB. The rest is already covered.


$process = @{
  Name = 'ProcessName'
  Expression = { (Get-Process -Id $_.OwningProcess).Name }
}

$darkAgent = @{
  Name = 'ExternalIdentity'
  Expression = {
    $ip = $_.RemoteAddress
    (Invoke-RestMethod -Uri "http://ipinfo.io/$ip/json" -UseBasicParsing -ErrorAction Ignore).org
 
  }
}
Get-NetTCPConnection -RemotePort 443 -State Established |
  Select-Object -Property RemoteAddress, OwningProcess, $process, $darkAgent
Title: Re: Scan Port 443
Post by: td on March 24, 2021, 03:11:31 PM
I would have mentioned a method if I knew a native WinBatch method. Though that was obvious from the response.  To be more acute there is a method that may work but it is a time-consuming task to script using DllCalls and I don't have the time to spend on it at the moment. You might want to check the  FCL for classes likely used by PS.
Title: Re: Scan Port 443
Post by: td on March 24, 2021, 04:00:47 PM
After thinking about it, it might make sense to add something along these lines to an extender like IPGrabber. Could mock it up in DllCall based script to verify that works. When time permits and if it works will post a script here.
Title: Re: Scan Port 443
Post by: stanl on March 25, 2021, 04:07:20 AM
Quote from: td on March 24, 2021, 04:00:47 PM
After thinking about it, it might make sense to add something along these lines to an extender like IPGrabber. Could mock it up in DllCall based script to verify that works. When time permits and if it works will post a script here.


While I could easily incorporate the PS code via the CLR the original exe I compiled was for a user who still has Win7, was worried after getting messages it was no longer supported and I'm not sure if the PS code would even work on his machine. Nothing critical, he will probably upgrade to Win 10.


[EDIT] and if anyone cares, this worked for me, no error processing and goes into Excel (used attached text file}
Code (WINBATCH) Select


;Winbatch 2020B - Query Remote Connections to Port 443
;============================================================================================
cFile = "C:\temp\443.csv"
If FileExist(cFile) Then FileDelete(cFile)


cData= Dirscript():"443.txt"
If ! FileExist(cData) Then Terminate(@TRUE,"PS Script Not Foud",cData)


cScript = FileGet(cData)
cScript = StrReplace(cScript,"|cFile|",cFile)


BoxOpen("Please Wait","Enumerating Port 443 Remote Connections")
oNoGo = ObjectType("BOOL",@FALSE)
ObjectClrOption("useany", "System.Management.Automation")
objAutoPs = ObjectClrNew("System.Management.Automation.PowerShell")
oPshell = objAutoPs.Create()
oScope = ObjectType("BOOL",@TRUE)
oPshell.AddScript(cScript,oScope)
objAsync = oPshell.BeginInvoke()


ctimeout=100
tries=0


While objAsync.IsCompleted == oNoGo
   TimeDelay(10)
   tries=tries+1
   If tries>ctimeout Then Break
EndWhile


oPShell.EndInvoke(objAsync) 
Boxtext("Script Finished... Starting Excel")


If FileExist(cFile)
cText = FileGet(cFile)
cText = StrReplace(cText,'"','')
cText = StrReplace(cText,',',@TAB)
ClipPut(cText)
oXL = CreateObject("Excel.Application")
oXL.Visible          = @TRUE  ; change this to @FALSE to run hidden
oXL.ScreenUpdating   = @TRUE  ; if running hidden, change this to @FALSE
oXL.UserControl      = @TRUE
oXL.DisplayAlerts    = @FALSE
oXL.WorkBooks.Add()
BoxShut()
oWS = oXL.ActiveWorkBook.Worksheets(1)
oWS.Activate()
oWS.Name = "443 Remote Connections"
oWS.Cells(1,1).Select()
oWS.Paste()
oWS.UsedRange.Select()
oXL.Selection.Font.Name = 'Tahoma'
oXL.Selection.Font.Size = 9
oXL.Selection.Font.Bold = @True
oWS.UsedRange.Columns.Autofit()
oWS.ListObjects.Add(:1,oWS.UsedRange, , 1).Name ="Table1"
oWS.Range("Table1[#All]").Select()
oWS.ListObjects("Table1").TableStyle = "TableStyleLight15"
oXL.ActiveWindow.DisplayGridlines = @False
oWS.Cells(1,1).Select()
oWS=0
oXL=0
Pause("Data Loaded Into Excel","Save or Close Workbook")


Endif


Exit


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


Title: Re: Scan Port 443
Post by: td on March 26, 2021, 08:05:17 AM
As it sometimes happens this script provided a convenient integration test for another project currently in the works. It is not production-ready by any stretch because it is lacking error handling, proper documentation, adherence to coding standards, and it could be rewritten to execute much more efficiently.  It also requires Windows Vista or newer and only reports IPV4 TCP connections; not IPV6 or UDP connections. Bugs are included at no extra charge...

Code (winbatch) Select
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; SDK data structures.
;;; GetTCPTable.wbt
;typedef enum {
;    TcpConnectionOffloadStateInHost,
;    TcpConnectionOffloadStateOffloading,
;    TcpConnectionOffloadStateOffloaded,
;    TcpConnectionOffloadStateUploading,
;    TcpConnectionOffloadStateMax
;} TCP_CONNECTION_OFFLOAD_STATE, *PTCP_CONNECTION_OFFLOAD_STATE;


;typedef struct _MIB_TCPROW2 {
;    DWORD dwState;
;    DWORD dwLocalAddr;
;    DWORD dwLocalPort;
;    DWORD dwRemoteAddr;
;    DWORD dwRemotePort;
;    DWORD dwOwningPid;
;    TCP_CONNECTION_OFFLOAD_STATE dwOffloadState;
;} MIB_TCPROW2, *PMIB_TCPROW2;


;typedef struct _MIB_TCPTABLE2 { 
;  DWORD dwNumEntries; 
;  MIB_TCPROW2 table[ANY_SIZE];
;} MIB_TCPTABLE2,  *PMIB_TCPTABLE2;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

; Need stuff.
bWin64 = WinMetrics(-3) == 5

;; Converts a network byte order ip address to a machine byte order string.
#DefineFunction Ipv4ToString(_ipv4)

   hAddr = BinaryAlloc(4)
   hStr  = BinaryAlloc(17)
   BinaryPoke4(hAddr, 0, _ipv4)
   DllCall('Ntdll.dll', lpstr:'RtlIpv4AddressToStringA', lpbinary:hAddr, lpbinary:hStr)
   BinaryEodSet(hStr, 17)
   strRet = BinaryPeekStr(hStr, 0, 17)
   BinaryFree(hAddr)
   BinaryFree(hStr)

   return strRet
#EndFunction

;; Converts a TCP network byte order port number to a machine byte order port number.
#DefineFunction PortOrderConvert( _port )
   return DllCall('Ws2_32.dll', word:'ntohs', word:_port)
#EndFunction

; SDK constants.
NO_ERROR = 0
ERROR_INSUFFICIENT_BUFFER = 122

nRowSize = 28

; Create the struct with a table array added.
hTcpTbl = BinaryAlloc(4+nRowSize)
if bWin64 then nBufSize = 8
else nBufSize = 4
hSize = BinaryAlloc(nBufSize)
pdwSize = IntControl(42, hSize, 0, 0, 0)

nRet = DllCall('Iphlpapi.dll', long:'GetTcpTable2', lpbinary:hTcpTbl, long_ptr:pdwSize, long:1)

if bWin64 then nTableSize = BinaryPeek8(hSize, 0)
else nTableSize = BinaryPeek4(hSize, 0)
terminate(nTableSize <= 0, 'GetTCPTable2 Table Size', 'No joy in Mudville.')

; Need room for more than one connection.
if nRet == ERROR_INSUFFICIENT_BUFFER
   BinaryFree(hTcpTbl)
   
   ; Create the a table and fill it with data.
   hTcpTbl = BinaryAlloc(4+nTableSize)
   
   if bWin64 then nTableSize = BinaryPoke8(hSize, 0, nTableSize)
   else nTableSize = BinaryPoke4(hSize, 0, nTableSize)
   
   ; Fetch the table.
   nRet = DllCall('Iphlpapi.dll', long:'GetTcpTable2', lpbinary:hTcpTbl, long_ptr:pdwSize, long:1)
   terminate(nRet != NO_ERROR, 'GetTCPTable2 Table Fetch', 'Well that did work very well. Did it?')
   
   BinaryEodSet(hTcpTbl, 4+nTableSize)
   BinaryFree(hSize)
else
   BinaryFree(hSize) 
endif
   
; Dimension an array to store the table.
nRows   = BinaryPeek4(hTcpTbl, 0)
aTable  = ArrDimension(nRows+1, 7) ; +1 for table header.
aTable[0,0] = 'State'
aTable[0,1] = 'Local Address'
aTable[0,2] = 'Local Port'
aTable[0,3] = 'Remote Address'
aTable[0,4] = 'Remote Port'
aTable[0,5] = 'Process ID'
aTable[0,6] = 'Load State'

nOffset = 4 ; Skip entry count.

;; Copy buffer to the array with conversions as needed.
for i = 1 to nRows
   for j = 0 to 6
      aTable[i,j] = BinaryPeek4(hTcpTbl, nOffset)
      nOffset += 4
      if j==1 || j==3 then aTable[i,j] = Ipv4ToString(aTable[i,j])
      else if j==2 || j==4 then aTable[i,j] = PortOrderConvert(aTable[i,j])
   next
next

BinaryFree(hTcpTbl)

TcpTabFormat=`WWWDLGED,6.2`

TcpTabCaption=`TCP Ipv4 Connections`
TcpTabX=1857
TcpTabY=208
TcpTabWidth=518
TcpTabHeight=324
TcpTabNumControls=003
TcpTabProcedure=`DEFAULT`
TcpTabFont=`DEFAULT`
TcpTabTextColor=`DEFAULT`
TcpTabBackground=`DEFAULT,DEFAULT`
TcpTabConfig=0
TcpTabDPI=`192,10,20`

TcpTab001=`138,300,050,016,PUSHBUTTON,"PushButton_OK",DEFAULT,"OK",1,10,@csDefButton,DEFAULT,DEFAULT,DEFAULT`
TcpTab002=`329,300,049,016,PUSHBUTTON,"PushButton_Cancel",DEFAULT,"Cancel",0,20,DEFAULT,DEFAULT,DEFAULT,DEFAULT`
TcpTab003=`012,014,488,268,REPORTVIEW,"ReportView_1",aTable,DEFAULT,DEFAULT,30,@csFirstHeader,DEFAULT,DEFAULT,DEFAULT`

ButtonPushed=Dialog("TcpTab")

exit
   


Title: Re: Scan Port 443
Post by: stanl on March 26, 2021, 12:14:22 PM
Quote from: td on March 26, 2021, 08:05:17 AM
As it sometimes happens this script provided a convenient integration test for another project currently in the works.


We aim to please. I have the .h files for the .dll's you referenced as part of Windows\Kits but can't find the .dlls
Title: Re: Scan Port 443
Post by: td on March 26, 2021, 01:12:33 PM
The DLLs are all part of the OS.  They are either in "System32", "SysWOW64", or one of the SXS directories. But you don't need to know that.  Since they are system DLLs, they will be located for you by WinBatch.
Title: Re: Scan Port 443
Post by: stanl on March 27, 2021, 03:28:16 AM
Quote from: td on March 26, 2021, 01:12:33 PM
The DLLs are all part of the OS.  They are either in "System32", "SysWOW64", or one of the SXS directories. But you don't need to know that.  Since they are system DLLs, they will be located for you by WinBatch.


I searched for Iphlpapi.dll in those folders. Maybe corrupted, destroyed.... if you search it on the web you get a lot of 'fixes' 'downloads' for dll not found. Anyway, ran your script... it does nothing on my laptop... so it's my problem.


[EDIT] ran sfc \scannow which helped.... then noticed  a endifendif in your script code. Adjusted and script ran fine.

[EDIT_2]: ran your script alongside the one I posted that calls PS from CLR.  Your script did not appear to pick up port 443.
Title: Re: Scan Port 443
Post by: td on March 27, 2021, 09:10:21 AM
The "endifendif" was a bit of sloppiness on my part. I modified the script on my system which works but tried to just alter the posted script instead of reposting it. 

Don't have any explanation for why your HTTPS port connects are missing other than because there aren't any or they are IPV6 (note that is possible to modify the script to collect IPV6 connections).  The HTTPS (443) connects show up on my system and are tied to the correct process. Also remember that connects change frequently on systems.
Title: Re: Scan Port 443
Post by: td on March 27, 2021, 09:52:12 AM
Out of an abundance of curiosity, I searched for the Iphlpapi.dll on my system found 11 copies in all the places I mentioned and a few more.  Places like restore point storage for updates e.t.c.
Title: Re: Scan Port 443
Post by: td on March 27, 2021, 10:54:32 AM
FWIW, a simple way to search for system files if you don't trust MSFT's Start menu search functionality is to use the OS's File Explorer search functionality. Open a File Explorer window on the root of the system drive and type the file name with extension into the search box on the right. You would likely need to enable the Show Hidden and System files option. If you are still using dark ages mechanical hard drives, you may need to take a lunch break or something as it could take a while. 
Title: Re: Scan Port 443
Post by: stanl on March 27, 2021, 11:26:40 AM
To put things in perspective and close this thread: