	
'RMS ReInit
option explicit
on error resume next
const HKEY_LOCAL_MACHINE = &H80000002
const ROUTER_SERVICE     = "Sophos Message Router"
const AGENT_SERVICE      = "Sophos Agent"
const REINIT_EXE_FILE    = "ClientMRInit.exe"
const WOW_KEY            = "Wow6432Node"
dim strLogPath, strMRInitLog, strFilePathCac, strFilePathMrInit, strCac
dim strMrinit, objArgs, strArg, intForceRun, strRouterCertIdentityKey
intForceRun = 0
Set objArgs = WScript.Arguments
For Each strArg in objArgs
    if lcase(strArg) = "-force" then
      intForceRun = 1
    end if	
Next 

strCac = ""&_
"-----BEGIN CERTIFICATE-----" &vbcrlf &_ 
"MIIDFzCCAf+gAwIBAgIBATANBgkqhkiG9w0BAQQFADARMQ8wDQYDVQQDFAZFTTJf" &vbcrlf &_ 
"Q0EwHhcNMTAwMTE3MDkxODAxWhcNMzAwMTEzMDkxODAxWjARMQ8wDQYDVQQDFAZF" &vbcrlf &_ 
"TTJfQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCy0jp7CApAujSV" &vbcrlf &_ 
"Mqb3mPFTas7NcRiWzGEwP4rANIwhcUQzG+FtUiOTAN3ufNFCs7olA9l3YPsR9DUa" &vbcrlf &_ 
"JQYerCHj8VNHUrTBR69ytdTUQcbexjaULKiv8y5DntSCGnkcMxp3Gzrh1Q72kICB" &vbcrlf &_ 
"Th4O44edDhAXpf0LX2QuvBCwo8isvQpxMdr7bYC9dV/8HiSvr90q6k/IqLxjWXE3" &vbcrlf &_ 
"Ih9gSk0SSP/5Lnkcw6Y24kBfSIBAAH3HdR5KSUrAdcnAqCI4EHJMp8l6uKmzWqXC" &vbcrlf &_ 
"2Ob88gEWb7AcjSpef0U/GlKJSk6CKggbTVnAxwhISm0lO2LHoid5Tv+gLUu66NCS" &vbcrlf &_ 
"QT9HvcjhAgMBAAGjejB4MB0GA1UdDgQWBBQrz1GPzq7oJci4uQpWl0SlGgYGcTA5" &vbcrlf &_ 
"BgNVHSMEMjAwgBQrz1GPzq7oJci4uQpWl0SlGgYGcaEVpBMwETEPMA0GA1UEAxQG" &vbcrlf &_ 
"RU0yX0NBggEBMAwGA1UdEwQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3" &vbcrlf &_ 
"DQEBBAUAA4IBAQAv/aHy9rbBHyeVex0FMg30uFHi+J6HLegGsBfmK5SR4/oJljn7" &vbcrlf &_ 
"jh0FhuHbXYu7VfQCppDDbeLPn58sqxdB+kfJBIANEewT/bkbgKZep/r9guizvWZn" &vbcrlf &_ 
"gaFqpioDwhlMQWl9O8jVjqz2fKyGA3JdNOxbgQizv0xZwR4nMXjKizVeetmTYDQm" &vbcrlf &_ 
"t4VM/BHNWNZP2jm3mU/ZCOl9iKfYKbYHRwgFcVykh1WUJiUpqXvl51whDlASGqK7" &vbcrlf &_ 
"4lbIZirWy1YkPyDxad3O5aNEzf/kFh1lhhLuNl2mPamsSDSO4d5yhIz1hbCbNDt+" &vbcrlf &_ 
"Xj1DyCjynQmC2iG1/wJKYM+QB1IaioCyQq70" &vbcrlf &_ 
"-----END CERTIFICATE-----" &vbcrlf &_ 
"" 
strLogPath ="C:\windows\temp\Reinit.txt"
strMRInitLog ="C:\windows\temp"
strMrinit = ""&_
"[Config] " &vbcrlf &_ 
"""NotifyRouterUpdate""=""EM""" &vbcrlf &_ 
"""ClientIIOPPort""=dword:00002001" &vbcrlf &_ 
"""ClientSSLPort""=dword:00002002" &vbcrlf &_ 
"""ClientIORPort""=dword:00002000" &vbcrlf &_ 
"""IORSenderPort""=dword:00002000" &vbcrlf &_ 
"""DelegatedManagerCertIdentityKey""=""qirQZJxYA3LMu3I6dMHxh6FMMNk=""" &vbcrlf &_ 
"""ManagedAppCertIdentityKey""=""sSrLRwALJ7vPO167549sjk3F4ZU=""" &vbcrlf &_ 
"""RouterCertIdentityKey""=""hz55ioniT6rLohRETcH66KPrKYM=""" &vbcrlf &_ 
"""ServiceArgs""=""""" &vbcrlf &_ 
"""MRParentAddress""=""134.176.3.116,wuso.hrz.uni-giessen.de,wuso""" &vbcrlf &_ 
"""ParentRouterAddress""=""134.176.3.116,wuso.hrz.uni-giessen.de,wuso""" &vbcrlf &_ 
"" 
strRouterCertIdentityKey="hz55ioniT6rLohRETcH66KPrKYM="
dim objFSO, objFile, strRMSPath, strWow6432Node,intPauseForServiceInSeconds
strWow6432Node   = "\"
intPauseForServiceInSeconds = 10
set objFSO = CreateObject("Scripting.FileSystemObject")
set objFile = objFSO.CreateTextFile(strLogPath, true)
WriteToLog 0, "Starting Script"
if Is64() then
    strWow6432Node = "\" & WOW_KEY & "\"
else
    strWow6432Node = "\"
end if
if intForceRun = 0 then
	if RouterIdentityIsOK then
		WriteToLog 0, "End of script"
        CloseLog()
        wscript.quit(1)
	end if
    if MarkerFound() then
        WriteToLog 0, "End of script"
        CloseLog()
        wscript.quit(1)
    end if
	if ServerClassRouter() then
        WriteToLog 0, "End of script"
        CloseLog()
        wscript.quit(1)
    end if
else
	WriteToLog 0, "Running in Force mode (-force)"
end if
strRMSPath = GetRMSPath()
CreateFile strCac, strRMSPath, "cac.pem"
CreateFile strMrinit, strRMSPath, "mrinit.conf"
DeleteOrig(strRMSPath)
StopService(AGENT_SERVICE)
StopService(ROUTER_SERVICE)
DeleteKey HKEY_LOCAL_MACHINE, "SOFTWARE" & strWow6432Node & "Sophos\Messaging System", "cac", "."
DeleteKey HKEY_LOCAL_MACHINE, "SOFTWARE" & strWow6432Node & "Sophos\Messaging System\CertificationIdentityKeys", "CertificationIdentityKey", "."
DeleteKey HKEY_LOCAL_MACHINE, "SOFTWARE" & strWow6432Node & "Sophos\Messaging System\Router\Private", "pkc", "."
DeleteKey HKEY_LOCAL_MACHINE, "SOFTWARE" & strWow6432Node & "Sophos\Messaging System\Router\Private", "pkp", "."
DeleteKey HKEY_LOCAL_MACHINE, "SOFTWARE" & strWow6432Node & "Sophos\Remote Management System\CertificationIdentityKeys", "ManagedApplication", "."
DeleteKey HKEY_LOCAL_MACHINE, "SOFTWARE" & strWow6432Node & "Sophos\Remote Management System\ManagementAgent\Private", "CertificationIdentityKey", "."
DeleteKey HKEY_LOCAL_MACHINE, "SOFTWARE" & strWow6432Node & "Sophos\Remote Management System\ManagementAgent\Private", "pkc", "."
DeleteKey HKEY_LOCAL_MACHINE, "SOFTWARE" & strWow6432Node & "Sophos\Remote Management System\ManagementAgent\Private", "pkp", "."
'Only create marker if ClientMrinit.exe returned ok
if RunClientMRInit(strRMSPath) = 0 then
  CreateMarker()
end if
StartService(ROUTER_SERVICE)
StartService(AGENT_SERVICE)
WriteToLog 0, "Ending Script"
CloseLog()
Set objFSO = nothing
Set objArgs = nothing

Function CreateFile (strContents, strLocation, strFileName)
    WriteToLog 0, "--> CreateFile()"
    dim objFileCreate
	WriteToLog 0, "--> Creating file " & strFileName & " in " & strLocation
    Set objFileCreate = objFSO.CreateTextFile(strLocation & "\" & strFileName, true, false)
	objFileCreate.Write strContents
	objFileCreate.close
	Set objFileCreate = nothing
    WriteToLog 0, "<-- CreateFile()"
End Function
Function RouterIdentityIsOK()
   WriteToLog 0, "--> RouterIdentityIsOK()"	
   on error resume next
   dim oReg, strValue
   err.clear
   Set oReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\default:StdRegProv")
   if err.number <> 0 then
	    WriteToLog 1, "Error Number: " &_
    	err.number & " Error Description: " & err.description
	    CloseLog()
        wscript.quit(1)
   end if
   oReg.GetStringValue HKEY_LOCAL_MACHINE,"SOFTWARE" &_
    	strWow6432Node & "Sophos\Messaging System\CertificationIdentityKeys" ,"CertificationIdentityKey", strValue
   if strValue = strRouterCertIdentityKey then
        WriteToLog 0, "Router identity key in script is the same as the client: " & strValue
        RouterIdentityIsOK = true
   else
        WriteToLog 0, "Router identity key in script is different from the client: " & strValue
        RouterIdentityIsOK = false
   end if
   Set oReg = nothing
   WriteToLog 0, "--> RouterIdentityIsOK()"	
End Function
Function WriteToLog (strSev, strLogLine)
    dim strToWrite
    strToWrite = ""
    select case strSev
        case 0
	        strToWrite = "INFO: "
        case 1
	        strToWrite = "ERROR: "
        case else
	        strToWrite = "UNKNOWN: "
    end select
    objFile.WriteLine Date() & " " & Time() & " " & strToWrite & " " & strLogLine
End Function
Function CloseLog()
    WriteToLog 0, "--> CloseLog() - No Function Exit Logged"
    objFile.Close
    set objFile = nothing
End Function
Function CreateMarker()
    WriteToLog 0, "--> CreateMarker()"	
    on error resume next
    dim oReg, intRetValue
    err.clear
    Set oReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\default:StdRegProv")
    if err.number <> 0 then
	    WriteToLog 1, "Error Number: " & err.number & " Error Description: " & err.description
	    CloseLog()
       wscript.quit(1)
    end if
    intRetValue = oReg.SetStringValue (HKEY_LOCAL_MACHINE, "SOFTWARE" & strWow6432Node & "Sophos" ,"ReInit", "1")
    if intRetValue = 0 then
        WriteToLog 0, "Created marker key." 
    else
        WriteToLog 1, "Failed to create marker.  Error code " & intRetValue
    end if
    Set oReg = nothing
    WriteToLog 0, "<-- CreateMarker()"	
End Function
Function ServerClassRouter()
    WriteToLog 0, "--> ServerClassRouter()"	
    on error resume next
    dim oReg, intValue
    err.clear
    Set oReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\default:StdRegProv")
    if err.number <> 0 then
	    WriteToLog 1, "Error Number: " &_
    		err.number & " Error Description: " & err.description
	    CloseLog()
       wscript.quit(1)
    end if
    oReg.GetDWORDValue HKEY_LOCAL_MACHINE,"SOFTWARE" &_
    	strWow6432Node & "Sophos\Messaging System\Router" ,"ConnectionCache", intValue
    if intValue = 10 then
        WriteToLog 0, "Router is a client, ok to run"
        ServerClassRouter = false
    else
        WriteToLog 1, "Router is a server router, will exit "
        ServerClassRouter = true
    end if
    Set oReg = nothing
    WriteToLog 0, "<-- ServerClassRouter()"
End Function
Function MarkerFound()
    WriteToLog 0, "--> MarkerFound()"	
    on error resume next
    dim oReg, strValue
    err.clear
    Set oReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\default:StdRegProv")
    if err.number <> 0 then
	    WriteToLog 1, "Error Number: " &_
    		err.number & " Error Description: " & err.description
			
	    CloseLog()
       wscript.quit(1)
    end if
    oReg.GetStringValue HKEY_LOCAL_MACHINE,"SOFTWARE" &_
    	strWow6432Node & "Sophos" ,"ReInit", strValue
    if strValue = "1" then
        WriteToLog 0, "Script already run, will exit."
        MarkerFound = true
    else
        WriteToLog 0, "Script not already run."
        MarkerFound = false
    end if
    Set oReg = nothing
    WriteToLog 0, "<-- MarkerFound()"
End Function
Function DeleteKey (strTopLevel, strKey, strName, strMachineName)
    WriteToLog 0,"--> DeleteKey()"	
	on error resume next
    dim oReg, intReturn
    err.clear
    Set oReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" &_
    	strMachineName & "\root\default:StdRegProv")
    if err.number <> 0 then
	    WriteToLog 1, "Error Number: " &_
    		err.number & " Error Description: " & err.description
	    CloseLog()
       wscript.quit(1)
    end if
    WriteToLog 0, "Attemping to delete key: " &_
    	strMachineName & "\" & strTopLevel & "\" & strKey & "\" & strName
    intReturn = oReg.DeleteValue( HKEY_LOCAL_MACHINE, strKey, strName )
    if intReturn <> 0 then
        DeleteKey = intReturn
        WriteToLog 1, "Failed to delete Key: " & intReturn
    else  
        WriteToLog 0, "Deleted Key: " & intReturn
        DeleteKey = intReturn
    end if
    Set oReg = nothing
    WriteToLog 0, "<-- DeleteKey()"
End Function
Function StopService(strServiceName)
    WriteToLog 0, "--> StopService()"
    on error resume next
    dim objWMIService, colServices, objService, intReturn
    Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
    Set colServices = objWMIService.ExecQuery ("Select * from win32_Service where name='" & strServiceName & "'")
    For each objService in colServices 
        intReturn = objService.StopService()
    Next
    wscript.sleep (intPauseForServiceInSeconds * 1000)
    WriteToLog 0, "Return code for stopping service: " & strServiceName & " : " & intReturn
    StopService = intReturn
    Set objWMIService = nothing
    Set colServices = nothing
    WriteToLog 0, "<-- StopService()"
End function
Function StartService(strServiceName)
    WriteToLog 0, "--> StartService()"
    on error resume next
    dim objWMIService, objService, colServices, intReturn
    Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
    Set colServices = objWMIService.ExecQuery ("Select * from win32_Service where name='" & strServiceName & "'")
    For each objService in colServices 
        intReturn = objService.StartService()
    Next
    WriteToLog 0, "Return code for starting service: " & strServiceName & " : " & intReturn
    StartService = intReturn
    Set objWMIService = nothing
    Set colServices = nothing
    WriteToLog 0, "<-- StartService()"
End function
Function RunClientMRInit(strPathToExe)
    WriteToLog 0, "--> RunClientMRInit()"
    on error resume next
    dim intReturn, oShell, strSwitches, strCommand
    WriteToLog 0, "Running command: " & strPathToExe & REINIT_EXE_FILE 
    Set oShell = WScript.CreateObject("WScript.Shell")
    if err.number <> 0 then
        WriteToLog 1, "Error Number: " & err.number & " Error Description: " & err.description
	    CloseLog()
       wscript.quit(1)
    end if
    strSwitches = " -logpath " & strMRInitLog
    strSwitches = strSwitches & " -filepath" & " " & """" &  strPathToExe & """"
    strCommand  = """" & strPathToExe & REINIT_EXE_FILE & """" & strSwitches
    intReturn = oShell.Run(strCommand, 0, true)
    if intReturn <> 0 then
        WriteToLog 1, strPathToExe & REINIT_EXE_FILE &_
			strSwitches & " Failed.  Exit code " & intReturn
    else
        WriteToLog 0, strPathToExe & REINIT_EXE_FILE &_
    		strSwitches & " Completed OK.  Exit code " & intReturn
    end if
    RunClientMRInit = intReturn
    set oShell = nothing
    WriteToLog 0, "--> RunClientMRInit()"
End Function
Function GetRMSPath()
    WriteToLog 0, "--> GetRMSPath()"
    on error resume next
    dim oReg, strValue, intReturn
    err.clear
    Set oReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\default:StdRegProv")
    if err.number <> 0 then
	    WriteToLog 1, "Error Number: " & err.number & " Error Description: " & err.description
	    CloseLog()
       wscript.quit(1)
    end if
    intReturn = oReg.GetStringValue (HKEY_LOCAL_MACHINE, "SOFTWARE" &_
		strWow6432Node & "Sophos\Messaging System\Router", "ServiceHomeDir", strValue)
    If strValue <> "" then
        WriteToLog 0, "RMS Path is " & strValue
        GetRMSPath = strValue
    else
        WriteToLog 1, "Return code " & intReturn
        CloseLog()
        wscript.quit(1)
    end if	
    set oReg = nothing
    WriteToLog 0, "<-- GetRMSPath()"
End Function
Function DeleteOrig(strFilePath)
    WriteToLog 0, "--> DeleteOrig()"
    on error resume next
    err.clear
    dim oFS, intReturn, strOrigPath
	strOrigPath = strFilePath & "mrinit.conf.orig"
    set oFS = CreateObject("Scripting.FileSystemObject")
    If oFS.FileExists(strOrigPath) Then
        WriteToLog 0, strOrigPath & " Exists"
        intReturn = oFS.DeleteFile(strOrigPath,  true)
        if intReturn = 0 then
             WriteToLog 0, strOrigPath & " deleted."
         else
             WriteToLog 1, strOrigPath & " Not deleted: Return code: " & intReturn
        end if
    else
        WriteToLog 0, strOrigPath & " does not exist, carrying on."
    End If
    set oFS = nothing
    WriteToLog 0, "<-- DeleteOrig()"
End Function
Function Is64()
    WriteToLog 0, "--> Is64()"
    on error resume next
    err.clear
    
	dim objWMIService, objColSettings, strDesc, objProcessor
	
	Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
	Set objColSettings = objWMIService.ExecQuery ("SELECT * FROM Win32_Processor") 
	
    if err.number <> 0 then
	    WriteToLog 1, "Error Number: " & err.number & " Error Description: " & err.description
	    CloseLog()
       wscript.quit(1)
    end if
    
	For Each objProcessor In objColSettings 
		strDesc = objProcessor.AddressWidth 
	Next 
	
    if strDesc = "32" then
        WriteToLog 0, "Platform is 32-Bit"
        Is64 = false
    end if
    if strDesc = "64" then
        WriteToLog 0, "Platform is 64-Bit"
        Is64 = true
    end if
	
    Set objWMIService = nothing
	set objColSettings = nothing
	
    WriteToLog 0, "<-- Is64()"
End Function

