Broots Posted September 26, 2006 Posted September 26, 2006 Hi, I am trying to write a little app that disables other network adaptors on the local machine if a 'internally' definded network is detected on any network interface. For the most part the logic seems to work, but I am trying to write function in AutoIT which uses WMI to monitor for two two events: network connection and disconnection. When a connection is detected run Step A and when a disconnect is detected to run step B. Note: Disabling of devices will be done by the devcon utility. This is a portion of the code that I am having trouble with. Func F_TrayTip($TrayMsg, $TrayTime, $TrayIcon) TrayTip("clears previous tray tip", "", 0) TrayTip($APP, $TrayMsg, $TrayMsg, $TrayIcon) EndFunc ;==>F_TrayTip Func F_MonitorNICConnect() $wbemFlagReturnImmediately = 0x10 $wbemFlagForwardOnly = 0x20 $colItems = "" $strComputer = "localhost" $objNicMonitorService = ObjGet("winmgmts:\\" & $strComputer & "\root\WMI") ; **** QUERY FOR NIC CONNECT EVENTS ***** $colNicConnect = $objNicMonitorService.ExecNotificationQuery ("Select * from MSNdis_StatusMediaConnect") $ColNicDisconnect = $objNicMonitorService.ExecNotificationQuery ("SELECT * FROM MSNdis_StatusMediaDisconnect") While 1 ; Monitor Nics for event change If $colNicConnect.NextEvent Then $Output = "A network connection has been made:" F_TrayTip($Output & @CRLF & "Verifying Network Configuration", 2,1) $NicEvent = "Connect" F_VerifyConnection($NicEvent) ElseIf $ColNicDisconnect.NextEvent Then $Output = "A network connection has been lost:" F_TrayTip($Output & @CRLF & "Verifying Network Configuration", 2,1) $NicEvent = "Disconnect" F_VerifyConnection($NicEvent) EndIf Sleep(5000) WEnd EndFunc ;==>F_MonitorNICConnect When the events are written as different functions, ie, function just for Connect and another for Disconnect, it sort of works as expected if i call them manually. But once the one function is called and it starts polling, I don't know how to break out that function to also monitor for a disconnect state. I tried to amalgamate the two functions as one, which is listed above, but now it doesn't work. Any tips or pointers would really be appreciated on using a WHILE process to monitor for two events via WMI. Once I get this working, I will post the code to forums for peer review and hopefully to help other people like me. Thanks for all your advice in advance! M
lod3n Posted September 26, 2006 Posted September 26, 2006 Try this:Func F_TrayTip($TrayMsg, $TrayTime, $TrayIcon) TrayTip("clears previous tray tip", "", 0) TrayTip($APP, $TrayMsg, $TrayMsg, $TrayIcon) EndFunc ;==>F_TrayTip Func F_MonitorNICConnect() $wbemFlagReturnImmediately = 0x10 $wbemFlagForwardOnly = 0x20 $colItems = "" $strComputer = "localhost" $objNicMonitorService = ObjGet("winmgmts:\\" & $strComputer & "\root\WMI") $objNicMonitorService2 = ObjGet("winmgmts:\\" & $strComputer & "\root\WMI") ; **** QUERY FOR NIC CONNECT EVENTS ***** $colNicConnect = $objNicMonitorService.ExecNotificationQuery ("Select * from MSNdis_StatusMediaConnect") $ColNicDisconnect = $objNicMonitorService2.ExecNotificationQuery ("SELECT * FROM MSNdis_StatusMediaDisconnect") While 1 ; Monitor Nics for event change If $colNicConnect.NextEvent Then $Output = "A network connection has been made:" F_TrayTip($Output & @CRLF & "Verifying Network Configuration", 2,1) $NicEvent = "Connect" F_VerifyConnection($NicEvent) ElseIf $ColNicDisconnect.NextEvent Then $Output = "A network connection has been lost:" F_TrayTip($Output & @CRLF & "Verifying Network Configuration", 2,1) $NicEvent = "Disconnect" F_VerifyConnection($NicEvent) EndIf Sleep(5000) WEnd EndFunc ;==>F_MonitorNICConnect [font="Fixedsys"][list][*]All of my AutoIt Example Scripts[*]http://saneasylum.com[/list][/font]
PsaltyDS Posted September 26, 2006 Posted September 26, 2006 (edited) Hi, I am trying to write a little app that disables other network adaptors on the local machine if a 'internally' definded network is detected on any network interface. For the most part the logic seems to work, but I am trying to write function in AutoIT which uses WMI to monitor for two two events: network connection and disconnection. When a connection is detected run Step A and when a disconnect is detected to run step B. Note: Disabling of devices will be done by the devcon utility. This is a portion of the code that I am having trouble with. Func F_TrayTip($TrayMsg, $TrayTime, $TrayIcon) TrayTip("clears previous tray tip", "", 0) TrayTip($APP, $TrayMsg, $TrayMsg, $TrayIcon) EndFunc ;==>F_TrayTip Func F_MonitorNICConnect() $wbemFlagReturnImmediately = 0x10 $wbemFlagForwardOnly = 0x20 $colItems = "" $strComputer = "localhost" $objNicMonitorService = ObjGet("winmgmts:\\" & $strComputer & "\root\WMI") ; **** QUERY FOR NIC CONNECT EVENTS ***** $colNicConnect = $objNicMonitorService.ExecNotificationQuery ("Select * from MSNdis_StatusMediaConnect") $ColNicDisconnect = $objNicMonitorService.ExecNotificationQuery ("SELECT * FROM MSNdis_StatusMediaDisconnect") While 1 ; Monitor Nics for event change If $colNicConnect.NextEvent Then $Output = "A network connection has been made:" F_TrayTip($Output & @CRLF & "Verifying Network Configuration", 2,1) $NicEvent = "Connect" F_VerifyConnection($NicEvent) ElseIf $ColNicDisconnect.NextEvent Then $Output = "A network connection has been lost:" F_TrayTip($Output & @CRLF & "Verifying Network Configuration", 2,1) $NicEvent = "Disconnect" F_VerifyConnection($NicEvent) EndIf Sleep(5000) WEnd EndFunc ;==>F_MonitorNICConnect When the events are written as different functions, ie, function just for Connect and another for Disconnect, it sort of works as expected if i call them manually. But once the one function is called and it starts polling, I don't know how to break out that function to also monitor for a disconnect state. I tried to amalgamate the two functions as one, which is listed above, but now it doesn't work. Any tips or pointers would really be appreciated on using a WHILE process to monitor for two events via WMI. Once I get this working, I will post the code to forums for peer review and hopefully to help other people like me. Thanks for all your advice in advance! M According to "Scripting Guy!", that call to WMI hangs and returns nothing until the event occurs. So your script is paused indefinitely every time it hits $colNicConnect.NextEvent or $colNicDisconnect.NextEvent. Your script looks like an assumption that an immediate value is returned, and that's not what I see in that reference (which is all I know about, so YMMV). You may need entirely seperate scripts that monitor each of these events and fire some kind of trigger (like a registry value) that the monitoring script is looking for. Edited September 26, 2006 by PsaltyDS Valuater's AutoIt 1-2-3, Class... Is now in Session!For those who want somebody to write the script for them: RentACoder"Any technology distinguishable from magic is insufficiently advanced." -- Geek's corollary to Clarke's law
lod3n Posted September 26, 2006 Posted September 26, 2006 I think NextEvent has a parameter, the number of miliseconds to wait. If you take out your Sleep(5000), and change your NextEvents like this; $colNicConnect.NextEvent(2500), it should check each one every 2 and a half seconds. I think this has the potential to drop events on the event monitor you're not currently monitoring. If your testing reveals that, you don't have much choice but to do this with three exes, one for each monitor, and one to handle the F_VerifyConnections, triggered by the monitor exes. Good luck, sounds interesting. [font="Fixedsys"][list][*]All of my AutoIt Example Scripts[*]http://saneasylum.com[/list][/font]
lod3n Posted September 26, 2006 Posted September 26, 2006 There's also the WITHIN keyword that you can place in your SQL query. "select blah blah blah within 10". That will make it check for events every 10 seconds. More research is required... [font="Fixedsys"][list][*]All of my AutoIt Example Scripts[*]http://saneasylum.com[/list][/font]
Broots Posted September 27, 2006 Author Posted September 27, 2006 Thanks for the info and pointers. I was sitting on the train on my way to the Arsenal game last night and also wondered that I could miss some events if the app was polling for a disconnect at the time a connect is made. I will test, and hopefully post the code up sometime soon!
ChrisL Posted September 27, 2006 Posted September 27, 2006 (edited) My Suggestion *edit added trayiconhide to the lost and connect scripts expandcollapse popupHotkeySet ("{ESC}","Quit") Global $proc[3] $Lost = 'Opt("TrayIconHide",1)' & @crlf & _ '$strComputer = "." '& @crlf & _ '$objWMIService = ObjGet("winmgmts:\\" & $strComputer & "\root\wmi")' & @crlf & _ '$colMonitoredEvents = $objWMIService.ExecNotificationQuery ("Select * from MSNdis_StatusMediaDisconnect")' & @crlf & _ 'While True' & @crlf & _ '$strLatestEvent = $colMonitoredEvents.NextEvent '& @crlf & _ ' ConsoleWrite("A network connection has been lost: "& $strLatestEvent.InstanceName) '& @crlf & _ 'Wend' $connect = 'Opt("TrayIconHide",1)' & @crlf & _ '$strComputer = "." '& @crlf & _ '$objWMIService = Objget("winmgmts:\\" & $strComputer & "\root\wmi") '& @crlf & _ '$colMonitoredEvents = $objWMIService.ExecNotificationQuery ("Select * from MSNdis_StatusMediaConnect")' & @crlf & _ 'While True' & @crlf & _ ' $strLatestEvent = $colMonitoredEvents.NextEvent' & @crlf & _ ' ConsoleWrite("A network connection has been made: "& $strLatestEvent.InstanceName)' & @crlf & _ 'Wend' FileWrite ("Lost.au3",$lost) FileWrite ("Connect.au3",$connect) $Proc[1] = Run(@AutoItExe & ' /AutoIt3ExecuteScript Lost.au3' ,@scriptdir, @SW_show, 7) $Proc[2] = Run(@AutoItExe & ' /AutoIt3ExecuteScript Connect.au3' ,@scriptdir, @SW_show, 7) While 1 For $i = 1 to Ubound ($Proc) -1 If @error then exitloop $line = StdoutRead($Proc[$i],"",true) If $Line <> 0 then $line = StdoutRead($Proc[$i]) MsgBox(0, "STDOUT read:", $line, 2) EndIf Next Sleep (1000) Wend Func Quit() ProcessClose ($Proc[1]) ProcessClose($Proc[2]) FileDelete("Lost.au3") FileDelete("Connect.au3") Exit Endfunc Edited September 27, 2006 by ChrisL [u]Scripts[/u]Minimize gui to systray _ Fail safe source recoveryMsgbox UDF _ _procwatch() Stop your app from being closedLicensed/Trial software system _ Buffering Hotkeys_SQL.au3 ADODB.Connection _ Search 2d Arrays_SplashTextWithGraphicOn() _ Adjust Screen GammaTransparent Controls _ Eventlogs without the crap_GuiCtrlCreateFlash() _ Simple Interscript communication[u]Websites[/u]Curious Campers VW Hightops Lambert Plant Hire
Broots Posted September 27, 2006 Author Posted September 27, 2006 My Suggestion *edit added trayiconhide to the lost and connect scripts expandcollapse popupHotkeySet ("{ESC}","Quit") Global $proc[3] $Lost = 'Opt("TrayIconHide",1)' & @crlf & _ '$strComputer = "." '& @crlf & _ '$objWMIService = ObjGet("winmgmts:\\" & $strComputer & "\root\wmi")' & @crlf & _ '$colMonitoredEvents = $objWMIService.ExecNotificationQuery ("Select * from MSNdis_StatusMediaDisconnect")' & @crlf & _ 'While True' & @crlf & _ '$strLatestEvent = $colMonitoredEvents.NextEvent '& @crlf & _ ' ConsoleWrite("A network connection has been lost: "& $strLatestEvent.InstanceName) '& @crlf & _ 'Wend' $connect = 'Opt("TrayIconHide",1)' & @crlf & _ '$strComputer = "." '& @crlf & _ '$objWMIService = Objget("winmgmts:\\" & $strComputer & "\root\wmi") '& @crlf & _ '$colMonitoredEvents = $objWMIService.ExecNotificationQuery ("Select * from MSNdis_StatusMediaConnect")' & @crlf & _ 'While True' & @crlf & _ ' $strLatestEvent = $colMonitoredEvents.NextEvent' & @crlf & _ ' ConsoleWrite("A network connection has been made: "& $strLatestEvent.InstanceName)' & @crlf & _ 'Wend' FileWrite ("Lost.au3",$lost) FileWrite ("Connect.au3",$connect) $Proc[1] = Run(@AutoItExe & ' /AutoIt3ExecuteScript Lost.au3' ,@scriptdir, @SW_show, 7) $Proc[2] = Run(@AutoItExe & ' /AutoIt3ExecuteScript Connect.au3' ,@scriptdir, @SW_show, 7) While 1 For $i = 1 to Ubound ($Proc) -1 If @error then exitloop $line = StdoutRead($Proc[$i],"",true) If $Line <> 0 then $line = StdoutRead($Proc[$i]) MsgBox(0, "STDOUT read:", $line, 2) EndIf Next Sleep (1000) Wend Func Quit() ProcessClose ($Proc[1]) ProcessClose($Proc[2]) FileDelete("Lost.au3") FileDelete("Connect.au3") Exit Endfunc You, Sir, are a GENIUS! I'm still trying to understand the method of your absolutely glorius logic!
ChrisL Posted September 27, 2006 Posted September 27, 2006 It's simple! You generate 2 au3 files and run them with the std flag, you then poll both of them for data (peek) when peek isn't 0 you read the stream. [u]Scripts[/u]Minimize gui to systray _ Fail safe source recoveryMsgbox UDF _ _procwatch() Stop your app from being closedLicensed/Trial software system _ Buffering Hotkeys_SQL.au3 ADODB.Connection _ Search 2d Arrays_SplashTextWithGraphicOn() _ Adjust Screen GammaTransparent Controls _ Eventlogs without the crap_GuiCtrlCreateFlash() _ Simple Interscript communication[u]Websites[/u]Curious Campers VW Hightops Lambert Plant Hire
Broots Posted September 27, 2006 Author Posted September 27, 2006 It's simple!You generate 2 au3 files and run them with the std flag, you then poll both of them for data (peek) when peek isn't 0 you read the stream.Way too complicated for my bird brain ... but I'm getting there ... hopefully I can get it all working by Friday!Thank you once again!
Broots Posted November 24, 2006 Author Posted November 24, 2006 At long last, please find my working code. I was too busy to finish this project. I finally got a prototype I am happy with and that doesn't crash or stall the system and works as planned.Please note:----------1) This is my first app using WMI. Would like to thank ChrisL for the code snippet spawning the processes. I have no other experience of programming.2) I have run the compiled exe (with resource files) on separate computers and it has worked first time with no problem. The program is only tested with Windows 2000 Service Pack 4 machines. Don't know what results on XP will be like but can't think it could be much different, unless the WMI returns are slightly different!3) Other Executables:The exes in the resource folder are all Microsoft executables1.dc.ex_ is Devcon.exe (used to enable / disable devices - THIS FILE IS IMPORTANT!)2.instsrv.ex_ is Instrv.exe (to install the netsentry.exe as a service)3.srvany.ex_ is srvany.exe (to install the netsentry.exe as a service)The most damage this software can do is disable all network cards and modems!What it does is monitors network connects / disconnects and takes action as a result thereof. It does not act on soft connects like a VPN connection, etc.All application settings and actions are written to key HKLM\Software\Netsentry.-------------------------------What I would like to do in the future1) Have a GUI (accessible via admin mode) where all detected NICS and MODEMS and ACTIONS are listed (but I just use the registry for this!)2) Have the ability to exclude a specific NIC / Modems from the enable / disable process. This is easily achieved by putting a exclude Reg key for the NIC or Modem and having the software use that key as a criteria for it's enable disable/options. I still haven't implemented.3) Have a way to use less memory. The application spawns two processes that wait for disconnect or connect events. This program when running normally uses about 15Mb of memory!Would appreciate your comments on this and any advice on how to make it better.------------------Here is the code.expandcollapse popup; ---------------------------------------------------------------------------- ; ; AutoIt Version: 3.1.0 ; Author: M.Hira <secureair@gmail.com> ; ; Script Function: ; Template AutoIt script. ; ; ---------------------------------------------------------------------------- ; Script Start #include <GUIConstants.au3> #include <INet.au3> #Include <date.au3> #NoTrayIcon Opt("WinWaitDelay", 100) Opt("WinTitleMatchMode", 2) Opt("WinDetectHiddenText", 1) Opt("MouseCoordMode", 0) Opt("TrayIconDebug", 0) ;0=no info, 1=debug line info ;Opt("TrayAutoPause", 0) ; Should be 0 in final release Opt("TrayMenuMode", 1) ; Do not show Pause / exit options Opt("OnExitFunc", "F_AutoITExit") Opt("RunErrorsFatal", 0) ; 0= Don't crash script on error ; ============================================================= ; ****** START: Define Global Parameters ****** ; ============================================================= Global $SecureLAN, $SecureLANNotFound Global $proc[3] Global $wp $APP = "Network Sentry" $VER = "0.50" $APPVER = $APP & " (" & $VER & ")" $REG = "HKEY_LOCAL_MACHINE\SOFTWARE\NetSentry" $RES = @ScriptDir & "\Resource\" $wp = "password" ; the password for closing application ; ============================================================= ; Define Protected Networks ; Settings here will ensure that if settings match the network will be ; considered a secure network and all other other network cards will be ; disabled. ; These are the networks we will consider to be secure. If this ; information is not found, network and modem interfaces will be enabled ; if they were previously disables ; Local Network Settings 1 ; LAN 1 parameters ... will be used by GUI in future versions to allow ; changes instead of being hardcoded $DefinedDHCPServer1 = "10.225.200.101" $DefineDNSSuffix1 = "gb.corpnet.net" ; Local Network Setting 2 ; LAN 2 parameters ... will be used by GUI in future versions to allow ; changes instead of being hardcoded $DefinedDHCPServer2 = "10.225.1.101" $DefineDNSSuffix2 = "us.corpnet.net" ; Subsidiary Network Settings ; Will be used by GUI in future versions to allow changes instead of ; being hardcoded $GlobalDNSSuffix1 = "corpnet.net" $GlobalDNSSuffix2 = "corpnet.com" ; ============================================================= ; ****** END: Define Global Parameters ****** ; ============================================================= ; ============================================================= ; ****** START: Defining Functions ****** ; ============================================================= Func F_AutoITExit() ;kill the processes you spawn ;delete the files you create ProcessClose($proc[1]) ProcessClose($proc[2]) FileDelete("Disconnect.au3") FileDelete("Connect.au3") Exit EndFunc ;==>F_AutoITExit ; ============================================================= Func F_TrayTip($TrayMsg, $TrayTime, $TrayIcon) ; This function is used by the application to bring up the traytip ; dialog box when called TrayTip("Clear Previous tray tip", "", 0) TrayTip($APP, $TrayMsg, $TrayMsg, $TrayIcon) EndFunc ;==>F_TrayTip ; ============================================================= Func F_Debug($DebugMsg) ; Used for debugging, just throws up a msgbox with whatever ; we call it with MsgBox(64, $APP & "-Debug Window", $DebugMsg, 4) EndFunc ;==>F_Debug ; ============================================================= Func F_Startup() ; Is used for the general application when it starts up, to ; enable housekeeping to be performed and to ensure that the ; application dependencies are found, etc. ; ***** Define Initialization Steps ***** F_TrayTip("Network Sentry is intializing", 2, 1) TraySetIcon($RES & "mib.ico") ; Delete list of settings since last run so that program can repopulate RegDelete($REG & "\ACTION\", "SecureNetworkOnNICIndex") RegDelete($REG & "\ACTION\", "SecureNetworkDetectedAt") RegDelete($REG & "\ACTION\", "SecureNetworkStatus") RegDelete($REG & "\ACTION\", "SecureNetworkLostAt") ; Delete these scripts, as we will automatically create it again. If FileExists(@ScriptDir & "\connect.au3") Then FileDelete(@ScriptDir & "\connect.au3") If FileExists(@ScriptDir & "\disconnect.au3") Then FileDelete(@ScriptDir & "\disconnect.au3") Sleep(10000) ; Before we begin let's verify if the application's components can be found ; Check to see if you can find Devcon Utility which is used to control hardware ; devices. Vista will make devcon obsolete as we will be able to use WMI to ; to enable/disable devices :-) F_TrayTip("Verifying Application Settings", 2, 1) If FileExists(@SystemDir & "\devcon.exe") Then ; Do nothing! Else ; If you can't find it, try to copy it from Source folder F_TrayTip("Device controller cannot be found. Trying to repair", 2, 2) FileCopy($RES & "dc.ex_", @SystemDir, 1) ;Rename the source file If FileMove(@SystemDir & "\dc.ex_", @SystemDir & "\Devcon.exe", 1) = 1 Then F_TrayTip("Device controller functionality restored", 1, 1) Else F_TrayTip("Device controller cannot be found!", 2, 2) ; Throw up message box as some devices could be in a disabled state ; from the last time the application ran! MsgBox(64, $APP, "There is a problem with device controller." & @CRLF & _ "You may not have full network functionality" & @CRLF & "Please call IT") EndIf EndIf EndFunc ;==>F_Startup ; ============================================================= Func F_ServiceCheck() ; This checks if NetSentry is installed as a service. If not, it will ; automatically install the application as a service If RegRead($REG, "SvcInstalled") = "Yes" Then ; Do nothing, service is installed Else FileCopy($RES & "*.ex_", @SystemDir, 1) FileMove(@SystemDir & "\dc.ex_", @SystemDir & "\Devcon.exe", 1) FileMove(@SystemDir & "\instsrv.ex_", @SystemDir & "\instsrv.exe", 1) FileMove(@SystemDir & "\srvany.ex_", @SystemDir & "\srvany.exe", 1) If MsgBox(68, $APP, "It looks like " & $APP & " is not installed as a service" & @CRLF & "Would you like to install it?") = 6 Then ;Install Application as service $CMD = @SystemDir & "\instsrv.exe" & " NetSentry " & @SystemDir & "\srvany.exe" F_Debug("Command is: " & $CMD) RunWait(@ComSpec & " /c " & $CMD) $REGSVC = "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\NetSentry" $REGSVC1 = "HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Services\NetSentry" ;Modify Service Parameters RegWrite($REGSVC1 & "\Parameters") RegWrite($REGSVC1 & "\Parameters", "Application", "REG_SZ", @ScriptFullPath) RegWrite($REGSVC1 & "\Parameters", "Application", "REG_SZ", @ScriptFullPath) RegWrite($REGSVC, "Display Name", "REG_SZ", "Network Sentry") RegWrite($REGSVC, "Description", "REG_SZ", "Network Sentry - Monitors Network Connections and controls interfaces") RegWrite($REGSVC, "FailureActions", "REG_BINARY", "00000000000000000000000003000000f8f310000100000060ea00000100000060ea00000000000060ea0000") RegWrite($REGSVC, "Type", "REG_DWORD", "272") RegWrite($REGSVC1, "Display Name", "REG_SZ", "Network Sentry") RegWrite($REGSVC1, "Description", "REG_SZ", "Network Sentry - Monitors Network Connections and controls interfaces") RegWrite($REGSVC1, "FailureActions", "REG_BINARY", "00000000000000000000000003000000f8f310000100000060ea00000100000060ea00000000000060ea0000") RegWrite($REGSVC1, "Type", "REG_DWORD", "272") RegWrite($REG, "SvcInstalled", "REG_SZ", "Yes") Else ; Do Nothing, user said service should not be installed EndIf EndIf EndFunc ;==>F_ServiceCheck ; ============================================================= Func F_GetNetDevices($NicEvent) ; where event = Startup; Connect; Disconnect ; Builds a list of all network adaptors on the local machine ; Depending on what function calls it, it could do slightly different things. ; On application startup,once a Nic is added to a machine and is populated in the ; registry via this script, it does not get deleted. The reason for this is bcos if ; the device is disabled, the WMI script will not pick it up and we will not be able ; to get a PnPID Value it. In the future will try to get around this problem, but ; it is not major.. If $NicEvent = "Startup" Then F_TrayTip("Building list of connectivity adapters", 3, 1) ; If there is a connect/disconnect we clear the secure network settings, as the ; connectivity checks will update the value if a secure or subsidiary network is found If $NicEvent <> "StartUp" Then $SecureLAN = "" RegDelete($REG & "\ACTION\", "SecureNetworkOnNICIndex") RegDelete($REG & "\ACTION\", "SecureNetworkDetectedAt") RegDelete($REG & "\ACTION\", "SecureNetworkStatus") RegDelete($REG & "\ACTION\", "SecureNetworkLostAt") EndIf ; Start the WMI Queries $wbemFlagReturnImmediately = 0x10 $wbemFlagForwardOnly = 0x20 $colNetAdapter = "" $strComputer = "localhost" $objWMIService = ObjGet("winmgmts:\\" & $strComputer & "\root\CIMV2") $colNetAdapterConfig = $objWMIService.ExecQuery ("SELECT * FROM Win32_NetworkAdapterConfiguration Where IPEnabled=True", _ "WQL", $wbemFlagReturnImmediately + $wbemFlagForwardOnly) If IsObj($colNetAdapterConfig) Then For $objItem In $colNetAdapterConfig ; Populate NIC Key itself with MAC addresses and name of Network Card RegWrite($REG & "\NIC\", $ObjItem.MacAddress, "REG_SZ", $ObjItem.Description) ; For Each Network Card, create a key and get settings related to it! RegWrite($REG & "\NIC\" & $ObjItem.MacAddress, "ServiceName", "REG_SZ", $ObjItem.ServiceName) RegWrite($REG & "\NIC\" & $ObjItem.MacAddress, "MacAddress", "REG_SZ", $ObjItem.MacAddress) RegWrite($REG & "\NIC\" & $ObjItem.MacAddress, "Description", "REG_SZ", $ObjItem.Description) RegWrite($REG & "\NIC\" & $ObjItem.MacAddress, "Index", "REG_SZ", $ObjItem.Index) RegWrite($REG & "\NIC\" & $ObjItem.MacAddress, "ServiceName", "REG_SZ", $ObjItem.ServiceName) RegWrite($REG & "\NIC\" & $ObjItem.MacAddress, "DHCPServer", "REG_SZ", $ObjItem.DHCPServer) RegWrite($REG & "\NIC\" & $ObjItem.MacAddress, "DNSDomain", "REG_SZ", $ObjItem.DNSDomain) RegWrite($REG & "\NIC\" & $ObjItem.MacAddress, "IPAddress1", "REG_SZ", $ObjItem.IPAddress (0)) RegWrite($REG & "\NIC\" & $ObjItem.MacAddress, "IPAddress1Enabled", "REG_SZ", $ObjItem.IPEnabled) RegWrite($REG & "\NIC\" & $ObjItem.MacAddress, "IPAddress1SNMask", "REG_SZ", $ObjItem.IPSubnet (0)) RegWrite($REG & "\NIC\" & $ObjItem.MacAddress, "IPAddress1Gateway", "REG_SZ", $ObjItem.DefaultIPGateWay (0)) RegWrite($REG & "\NIC\" & $ObjItem.MacAddress, "SettingID", "REG_SZ", $ObjItem.SettingID) RegWrite($REG & "\NIC\" & $ObjItem.MacAddress, "LastUpdated", "REG_SZ", _Now()) ; Find Matching Device in Registry and see what connection is assigned to it $ConnectionNameRead = RegRead("HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Network\" & _ "{4D36E972-E325-11CE-BFC1-08002BE10318}\" & $ObjItem.SettingID & "\Connection\", "Name") RegWrite($REG & "\NIC\" & $ObjItem.MacAddress, "ConnectionName", "REG_SZ", $ConnectionNameRead) $PnPDeviceIDRead = RegRead("HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Network\" & _ "{4D36E972-E325-11CE-BFC1-08002BE10318}\" & $ObjItem.SettingID & "\Connection\", "PnpInstanceID") RegWrite($REG & "\NIC\" & $ObjItem.MacAddress, "HardwareID", "REG_SZ", $PnPDeviceIDRead) ; If you find that there is no Network Adapter name in Registry for a NIC, ; delete the section as it is not needed ; The section will be re-added when an IP address is found for it! If RegRead($REG & "\NIC\" & $ObjItem.MacAddress, "ConnectionName") = "" Then RegDelete($REG & "\NIC\" & $ObjItem.MacAddress) EndIf ; Check to see if the Domain Suffix for the local area connections are statically inputted ; If it matches - go and delete them, Do this once - when application is starting up. ; Note: Domain is the statically inputted connection suffix. When DHCP assigns a suffix, it appears in the ; same regtree as DHCPDomain. When querying for DNS suffix via WMI, Domain overides DHCPDomain but if ; no Domain value is listed, WMI will return the DHCPDomain Value when querying for DNSDomain. If $NicEvent = "Startup" Then If RegRead("HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\" & _ $ObjItem.SettingID & "\", "Domain") = $DefineDNSSuffix1 Or _ RegRead("HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\" & _ $ObjItem.SettingID & "\", "Domain") = $DefineDNSSuffix2 Then RegDelete("HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\" & _ $ObjItem.SettingID & "\", "Domain") EndIf EndIf Next EndIf ; Using Servicename Generated in the original query to get the Hardware ID from another WMI Query $colNetAdapter = $objWMIService.ExecQuery ("SELECT * FROM Win32_NetworkAdapter", "WQL", _ $wbemFlagReturnImmediately + $wbemFlagForwardOnly) If IsObj($colNetAdapter) Then For $objItem In $colNetAdapter If $ObjItem.Index = RegRead($REG & "\NIC\" & $ObjItem.MacAddress, "Index") Then RegWrite($REG & "\NIC\" & $ObjItem.MacAddress, "FriendlyName", "REG_SZ", $ObjItem.ProductName) RegWrite($REG & "\NIC\" & $ObjItem.MacAddress, "DeviceState", "REG_SZ", $ObjItem.ConfigManagerErrorCode) ; where Errorcode 22=Disabled ; 0=Enabled EndIf ;Clean up this section since the query may write some junk that is not needed! ; If RegRead($REG & "\NIC\" & $ObjItem.MacAddress, "ConnectionName") = "" Then ; RegDelete($REG & "\NIC\" & $ObjItem.MacAddress) ; EndIf Next EndIf ; Get List of Modems in System $colModems = $objWMIService.ExecQuery ("SELECT * FROM Win32_POTSModem", _ "WQL", $wbemFlagReturnImmediately + $wbemFlagForwardOnly) If IsObj($colModems) Then For $objItem In $colModems ; Populate Modem List RegWrite($REG & "\MODEM\", $ObjItem.AttachedTo, "REG_SZ", $ObjItem.Caption) ; For Each Modem, get some more details! RegWrite($REG & "\MODEM\" & $ObjItem.Caption, "FriendlyName", "REG_SZ", $ObjItem.Caption) RegWrite($REG & "\MODEM\" & $ObjItem.Caption, "HardwareID", "REG_SZ", $ObjItem.DeviceID) RegWrite($REG & "\MODEM\" & $ObjItem.Caption, "ModemType", "REG_SZ", $ObjItem.DeviceType) RegWrite($REG & "\MODEM\" & $ObjItem.Caption, "DeviceState", "REG_SZ", $ObjItem.ConfigManagerErrorCode) RegWrite($REG & "\MODEM\" & $ObjItem.Caption, "LastUpdated", "REG_SZ", _Now()) Next EndIf ;EndIf EndFunc ;==>F_GetNetDevices ; ============================================================= Func F_MonitorNics() $MonDisconnect = 'Opt("TrayIconHide",1)' & @CRLF & _ '$strComputer = "." ' & @CRLF & _ '$objWMIService = ObjGet("winmgmts:\\" & $strComputer & "\root\wmi")' & @CRLF & _ '$colMonitoredEvents = $objWMIService.ExecNotificationQuery ("Select * from MSNdis_StatusMediaDisconnect")' & @CRLF & _ 'While True' & @CRLF & _ '$strLatestEvent = $colMonitoredEvents.NextEvent ' & @CRLF & _ 'Sleep(1500) ' & @CRLF & _ 'ConsoleWrite("Disconnect")' & @CRLF & _ 'Wend' $MonConnect = 'Opt("TrayIconHide",1)' & @CRLF & _ '$strComputer = "." ' & @CRLF & _ '$objWMIService = Objget("winmgmts:\\" & $strComputer & "\root\wmi") ' & @CRLF & _ '$colMonitoredEvents = $objWMIService.ExecNotificationQuery ("Select * from MSNdis_StatusMediaConnect")' & @CRLF & _ 'While True' & @CRLF & _ '$strLatestEvent = $colMonitoredEvents.NextEvent' & @CRLF & _ 'Sleep(1500) ' & @CRLF & _ 'ConsoleWrite("Connect")' & @CRLF & _ 'Wend' FileWrite(@ScriptDir & "\Disconnect.au3", $MonDisconnect) FileWrite(@ScriptDir & "\Connect.au3", $MonConnect) $proc[1] = Run(@AutoItExe & ' /AutoIt3ExecuteScript Disconnect.au3', @ScriptDir, @SW_SHOW, 7) $proc[2] = Run(@AutoItExe & ' /AutoIt3ExecuteScript Connect.au3', @ScriptDir, @SW_SHOW, 7) ;=-=-=- $retestitem = TrayCreateItem("Re-test") TrayCreateItem("") $aboutitem = TrayCreateItem("About") $closeitem = TrayCreateItem("Close") ;=-=-=- TraySetState() While 1 $msg = TrayGetMsg() Select Case $msg = 0 For $i = 1 To UBound($proc) - 1 If @error Then ExitLoop $line = StdoutRead($proc[$i], "", True) If $line <> 0 Then $line = StdoutRead($proc[$i]) ;Pipe The Output of the SubProcesses so that we can use it to perform an action ;based on the subprocess, we are looking for an output of "Connect or "Disconnect" $NicEvent = $line F_VerifyConnection($NicEvent) EndIf Next Sleep(1500) ContinueLoop Case $msg = $retestitem F_VerifyConnection("Retest") Case $msg = $aboutitem MsgBox(64, $APPVER, "Network Sentry" & @CRLF & "Version:" & $VER) Case $msg = $closeitem If InputBox($APPVER, "Enter password to close application", "", "*") = $wp Then ; Correct Password given. Close program MsgBox(64, $APPVER, "Note: Some network interfaces and" & @CRLF & "modems may still be disabled!") ExitLoop Else ;Do Nothing!! MsgBox (48, $APPVER, "Wrong Password!") EndIf EndSelect WEnd EndFunc ;==>F_MonitorNics ; ============================================================= Func F_VerifyConnection($NicEvent) ; Based on whether a Connect/Disconnect Signal has been received, Verify Network Settings ; and disable or enable interfaces as needed TraySetIcon($RES & "mib.ico") $wbemFlagReturnImmediately = 0x10 $wbemFlagForwardOnly = 0x20 $colNetAdapter = "" $strComputer = "localhost" $objWMIService = ObjGet("winmgmts:\\" & $strComputer & "\root\CIMV2"); $colNetAdapterConfig = $objWMIService.ExecQuery ("SELECT * FROM Win32_NetworkAdapterConfiguration", _ "WQL", $wbemFlagReturnImmediately + $wbemFlagForwardOnly) $colNetAdapterServices = $objWMIService.ExecQuery ("SELECT * FROM Win32_SystemDriver", _ "WQL", $wbemFlagReturnImmediately + $wbemFlagForwardOnly) $colModems = $objWMIService.ExecQuery ("SELECT * FROM Win32_POTSModem", "WQL", _ $wbemFlagReturnImmediately + $wbemFlagForwardOnly) $colNetAdapter = $objWMIService.ExecQuery ("SELECT * FROM Win32_NetworkAdapter", "WQL", _ $wbemFlagReturnImmediately + $wbemFlagForwardOnly) ; Wait for network info to be collected before you verify connections again. If $NicEvent = "Startup" Then Sleep(15000) If $NicEvent = "Connect" Or $NicEvent = "Disconnect" Then Sleep(10000) If $NicEvent = "Retest" Then F_TrayTip("Re-testing network", 2, 1) TraySetState(4); let the tray icon flash ; Update the list of networks and modems on system ... F_GetNetDevices($NicEvent) ; Only Check for network connections that are connected at the time! ; Look for any interface that is connected to your defined 'secure' network If IsObj($colNetAdapterConfig) Then For $objItem In $colNetAdapterConfig ; We are using the DHCPServer Value as our primary criteria for determining ; if we are on the Local Secure LAN. ; Whether we are on the Local Secure LAN or a Subsidiary Secure LAN, ; the effect will be the same, but if you wanted a slightly different action, ; you could use this to diffrentiate between them. ; Using DHCPServer as parameter to decide if the network is our local internal one! ; Since the DHCPServer info is stored until the interface is connected to ; another network that overwrites it's settings, we ping the $DefindedDHCPServers ; to verify that we are on the network. ; NOTE: When not on a defined network as decided by the Checkpoint Firewall the ; Checkpoint firewall will not allow pings to be made which is fine .. as it is ; another safety check in our favour which means we can allow all interfaces to ; be enabled If $ObjItem.DHCPServer = $DefinedDHCPServer1 Or _ $ObjItem.DHCPServer = $DefinedDHCPServer2 And _ StringInStr($ObjItem.DNSDomain, $DefineDNSSuffix1) >= 1 Or _ StringInStr($ObjItem.DNSDomain, $DefineDNSSuffix2) >= 1 Then If Ping($ObjItem.DHCPServer, 250) = 1 And _ $ObjItem.IPAddress (0) <> "" Then ; ensure interface does have an IP Address! ; Mark this interface as the Local Secure LAN interface $SecureLAN = $ObjItem.Index ;F_TrayTip("Secure Network Detected", 4, 1) ;F_Debug("SecureLocal Network found on:" & $ObjItem.Index & @CRLF & $objItem.IPAddress (0)) RegWrite($REG & "\ACTION\", "SecureNetworkOnNICIndex", "REG_SZ", $SecureLAN) RegWrite($REG & "\ACTION\", "SecureNetworkDetectedAt", "REG_SZ", _Now()) RegWrite($REG & "\ACTION\", "SecureNetworkStatus", "REG_SZ", "LocalSecure") ; Write that the network type is SecureLocal RegDelete($REG & "\ACTION\", "SecureNetworkLostAt") EndIf EndIf ; If the secure network isn't detected we could could be on a subsidiary LAN, ; so we check the DNS Suffix for the connection. If it it matches, still run ; the rule to disable the other interfaces. ; Get the DNSDomain Setting (since it is or will be set by the DHCP Server). ; This will be used to query for a Corpnet Subsidiary network if the primary ; network criterion is not met If $SecureLAN = "" Then ;Check to see if you plugged into a subsidiary network by checking DNS settings If StringInStr($ObjItem.DNSDomain, $GlobalDNSSuffix1) >= 1 Or StringInStr($ObjItem.DNSDomain, $GlobalDNSSuffix2) >= 1 And _ Ping($ObjItem.IPAddress (0), 1000) = 1 Then ; Ensure that Interface has IP Address $SecureLAN = $ObjItem.Index RegWrite($REG & "\ACTION\", "SecureNetworkOnNICIndex", "REG_SZ", $SecureLAN) RegWrite($REG & "\ACTION\", "SecureNetworkDetectedAt", "REG_SZ", _Now()) RegWrite($REG & "\ACTION\", "SecureNetworkStatus", "REG_SZ", "Subsidiary") ; Write that the network type is a subsidiary Lan RegDelete($REG & "\ACTION\", "SecureNetworkLostAt") EndIf EndIf ; If the Local Secure or Subsidiary network is not detected, it means we need ; to enable all the interfaces. ; Try to Ping Secure Network Criterion ; If 0 = then there is no ping response so secure network is not connected ; Enable all cards that you have disabled or are disabled! ; Only run this portion if the local secure/subsidiary is not detected If $SecureLAN <= 0 Then ; Check for response from DHCPServers If Ping($DefinedDHCPServer1, 250) = 0 Or Ping($DefinedDHCPServer2, 250) = 0 Or _ StringInStr($ObjItem.DNSDomain, $GlobalDNSSuffix1) < 1 Or _ StringInStr($ObjItem.DNSDomain, $GlobalDNSSuffix2) < 1 Then ; Or Check to see if an interface has a DNS suffix meeting the criteria ;F_Debug("Secure/Subsidiary Lan Not Detected on " & @CRLF & $ObjItem.Description & "Index:" & $ObjItem.Index) RegWrite($REG & "\ACTION\", "SecureNetworkStatus", "REG_SZ", "NotDetected") RegWrite($REG & "\ACTION\", "SecureNetworkLostAt", "REG_SZ", _Now()) RegDelete($REG & "\ACTION\", "SecureNetworkDetectedAt") RegDelete($REG & "\ACTION\", "SecureNetworkOnNICIndex") EndIf EndIf Next EndIf ; Depending on what you found above, act on it .. If Secure or Subsidiary Network is detected ; enable/disable all other interfaces If RegRead($REG & "\ACTION\", "SecureNetworkOnNICIndex") <> "" Then For $objItem In $colNetAdapter $SecureLAN = RegRead($REG & "\ACTION\", "SecureNetworkOnNICIndex") TraySetIcon($RES & "redlock.ico") TraySetToolTip("PHYSICALLY connected to CorpNet Network" & @CRLF & "Note: Some interfaces have been disabled") If $ObjItem.Index <> $SecureLAN And _ RegRead($REG & "\NIC\" & $ObjItem.MacAddress, "Index") = $ObjItem.Index Then $HardwareID = RegRead($REG & "\NIC\" & $ObjItem.MacAddress, "HardwareID") $DeviceName = RegRead($REG & "\NIC\" & $ObjItem.MacAddress, "FriendlyName") RegWrite($REG & "\NIC\" & $ObjItem.MacAddress, "DeviceState", "REG_SZ", _ $ObjItem.ConfigManagerErrorCode) ; 22=Disabled 0=Enabled $DeviceState = RegRead($REG & "\NIC\" & $ObjItem.MacAddress, "DeviceState") $Action = "Disable" ;Send Disable Command If $ObjItem.ConfigManagerErrorCode = 0 Then F_ControlDevice($HardwareID, $DeviceName, $Action) ;Get the device status again after the action has been peformed on it. RegWrite($REG & "\NIC\" & $ObjItem.MacAddress, "DeviceState", "REG_SZ", _ $ObjItem.ConfigManagerErrorCode) ; 22=Disabled 0=Enabled Sleep(1000) EndIf Next For $objItem In $colModems $HardwareID = RegRead($REG & "\MODEM\" & $ObjItem.Caption, "HardwareID") $DeviceName = RegRead($REG & "\MODEM\" & $ObjItem.Caption, "FriendlyName") RegWrite($REG & "\MODEM\" & $ObjItem.Caption, "DeviceState", "REG_SZ", _ $ObjItem.ConfigManagerErrorCode) ; 22=Disabled 0=Enabled $DeviceState = RegRead($REG & "\MODEM\" & $ObjItem.Caption, "DeviceState") $Action = "Disable" ;Send Disable Command If EventCode picked up from WMI = 0 and needs to be 22 If $ObjItem.ConfigManagerErrorCode = 0 Then F_ControlDevice($HardwareID, $DeviceName, $Action) ;Get the device status again after the action has been peformed on it. RegWrite($REG & "\MODEM\" & $ObjItem.Caption, "DeviceState", "REG_SZ", _ $ObjItem.ConfigManagerErrorCode) ; 22=Disabled 0=Enabled Next ElseIf RegRead($REG & "\ACTION\", "SecureNetworkStatus") = "NotDetected" Then For $objItem In $colNetAdapter $SecureLAN = RegRead($REG & "\ACTION\", "SecureNetworkOnNICIndex") TraySetIcon($RES & "greenlock.ico") TraySetToolTip("NOT directly connected to CorpNet Network" & @CRLF & "Note: All interfaces are enabled") If $ObjItem.Index <> $SecureLAN And RegRead($REG & "\ACTION\" & _ $ObjItem.Description, "NetSentryLastAction") = "Disable" Then $HardwareID = $ObjItem.PnPDeviceID $DeviceName = $ObjItem.Name RegWrite($REG & "\NIC\" & $ObjItem.MacAddress, "DeviceState", "REG_SZ", _ $ObjItem.ConfigManagerErrorCode) ; 22=Disabled 0=Enabled $DeviceState = RegRead($REG & "\NIC\" & $ObjItem.MacAddress, "DeviceState") $Action = "Enable" ;Send Enable Command If $ObjItem.ConfigManagerErrorCode = 22 Then _ F_ControlDevice($HardwareID, $DeviceName, $Action) ;Get the device status again after the action has been peformed on it. RegWrite($REG & "\NIC\" & $ObjItem.MacAddress, "DeviceState", "REG_SZ", _ $ObjItem.ConfigManagerErrorCode) ; 22=Disabled 0=Enabled Sleep(1000) EndIf Next For $objItem In $colModems $HardwareID = RegRead($REG & "\MODEM\" & $ObjItem.Caption, "HardwareID") $DeviceName = RegRead($REG & "\MODEM\" & $ObjItem.Caption, "FriendlyName") RegWrite($REG & "\MODEM\" & $ObjItem.Caption, "DeviceState", "REG_SZ", _ $ObjItem.ConfigManagerErrorCode) ; 22=Disabled 0=Enabled $Action = "Enable" ;Send Enable Command If $ObjItem.ConfigManagerErrorCode = 22 Then _ F_ControlDevice($HardwareID, $DeviceName, $Action) ;Get the device status again after the action has been peformed on it. RegWrite($REG & "\MODEM\" & $ObjItem.Caption, "DeviceState", "REG_SZ", _ $ObjItem.ConfigManagerErrorCode) ; 22=Disabled 0=Enabled Next EndIf TraySetState(8); stop the tray icon flashing EndFunc ;==>F_VerifyConnection ; ============================================================= Func F_ControlDevice($HardwareID, $DeviceName, $Action) ; where $Hardware = PnPDeviceID, $DeviceName = Friendly Name, $Action = Enable or Disable ; Enables or disables interfaces based on Function that calls it.. If $Action = "Disable" Then F_TrayTip("Secure Network not detected:-" & @CRLF & "Unsecuring interfaces", 1, 1) ; Generic display box ; If Action = Enable If $Action = "Enable" Then F_TrayTip("Secure Network Detected:-" & @CRLF & "Securing interfaces", 1, 1) F_TrayTip("Network & modem " & @CRLF & "changes are being made", 1, 1) RegWrite($REG & "\ACTION\" & $DeviceName, "NetSentryLastAction", "REG_SZ", $Action) RegWrite($REG & "\ACTION\" & $DeviceName, "ActionTime", "REG_SZ", _Now()) $CMD = @SystemDir & "\devcon.exe -" & $Action & " ""@" & $HardwareID & """" RunWait(@ComSpec & " /c " & $CMD, "", @SW_HIDE) EndFunc ;==>F_ControlDevice ; ============================================================= Func F_Test() EndFunc ;==>F_Test ; ============================================================= ; ****** END: Define Functions ****** ; ============================================================= ; ============================================================= ; ****** START: Application Process ****** ; ============================================================= F_Startup() F_ServiceCheck() F_GetNetDevices("Startup") F_VerifyConnection("Startup") F_MonitorNics() ; ============================================================= ; ****** End: Application Process ****** ; =============================================================This is the zip file containing the EXEs and the uncompiled code!http://rapidshare.com/files/4651813/NetSentry.zip.html
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now