<?xml version="1.0" ?>
<package>
  <comment>
    '===============================================================================
    ' *** Microsoft Solution Accelerators: Security and Compliance
    ' *** 
    ' *** --------------------------------------------------------------------------
    ' *** Filename   :  LocalGPO.wsf
    ' *** --------------------------------------------------------------------------
    ' *** Description:  Applies the contents of a backup GPO to the local policy of 
    ' ***               a Windows computer, or exports the Local Policy to a backup GPO
    ' *** --------------------------------------------------------------------------
    ' *** Version    :  2.0
    ' *** Notes      :	Send questions and feedback to secwish@microsoft.com	
    ' *** --------------------------------------------------------------------------
    ' *** Copyright (C) Microsoft Corporation 2011, All Rights Reserved
    ' *** --------------------------------------------------------------------------
    ' ***
    '===============================================================================
  </comment>
  <job>
    <runtime>
      <description>Apply a backed up GPO to local policy</description>
      <named name="Path"  required="false"  many="false"  
             helpstring="Applies GPO backup to local policy." />
      <named name="ConfigSCE"   required="false"  many="false"  
             helpstring="Configures SCE to display MSS settings." />	
      <named name="ResetSCE"    required="false"  many="false"  
             helpstring="Restores SCE to default settings." />	
      <named name="Export"     required="false"  many="false"  
             helpstring="Exports Local Policy to backup GPO." />		
      <named name="Restore"     required="false"  many="false"  
             helpstring="Restores Local Policy to defaults." />		
      <named name="GPOPack"     required="false"  many="false"  
             helpstring="Creates GPOPack." />
      <named name="MLGPO"     required="false"  many="false"  
             helpstring="Configures MLGPO." />
      <example>Example: LocalGPO.wsf /Path:C:\GPObackups\TestGPO</example>
		
      <usage>
LocalGPO - Configures various aspects of a computer's Local Policy

Usage: LocalGPO.wsf {/Path:path to GPO Backup} [/Export] {[/GPOPack:name]}
       LocalGPO.wsf {/ConfigSCE | /ResetSCE | /Restore}

Options:

/Path:{path}     : Applies the contents of a GPO Backup to the local policy
                   of a Windows computer.

/Export          : Exports Local Policy to a GPO Backup.	

/GPOPack:{name}  : Creates a GPO backup that contains all components required 
                   for it to apply itself to the local security policy of a
                   computer. Specifying a name is optional.

/MLGPO:{name}    : Applies user settings from a GPO Backup to the specified 
		   MLGPO of a Windows computer. Must specify Administrators, 
                   Users(Non-Administrators), or a valid account name.

/Restore         : Restores Local Policy to the default configuration.

/ConfigSCE       : Configures Security Configuration Editor (SCE) to display
                   MSS settings.

/ResetSCE        : Restores SCE to default settings.

Examples:

	cscript LocalGPO.wsf /Path:C:\GPObackups\{GPO Backup GUID}
	- Applies the contents of the GPO Backup stored in the specified
	  path to the Local Policy of a Windows computer.

	cscript LocalGPO.wsf /Path:C:\GPObackups /Export
	- Exports a GPO Backup based on the Local Policy configuration
	  to a folder in the specified path.  

	cscript LocalGPO.wsf /Path:C:\GPObackups /Export /GPOPack
	- Creates a GPOPack and stores it in the specified path. GPOPacks
	  can be copied to other computers, and applied by double-clicking
	  GPOPack.wsf. 	

	cscript LocalGPO.wsf /Path:C:\GPObackups\{GPO Backup GUID} /MLGPO:Users
	- Applies the contents of the GPO Backup stored in the specified
	  path to the specified Multiple Local Group Policy Obect (MLGPO).

	cscript LocalGPO.wsf /Restore
	- Restores the entire Local Policy to its default configuration.

      </usage>		
    </runtime>
    <script language="VBScript">
    <![CDATA[
    
' ~~~ 
' ~~~ Force variables to be declared 
' ~~~ 
      Option Explicit
      
'=============================================================================
' Initialization of Error and Progress Message Constants for Localization
'=============================================================================
      
        Const conLABEL_CODE002 = "00002"
        Const conLABEL_CODE004 = "00004"
        Const conLABEL_CODE007 = "00007"
        Const conLABEL_CODE008 = "00008"
        Const conLABEL_CODE014 = "00014"
        Const conLABEL_CODE019 = "00019"
        Const conLABEL_CODE020 = "00020"
        Const conLABEL_CODE021 = "00021"
        Const conLABEL_CODE022 = "00022"
        Const conLABEL_CODE023 = "00023"
        Const conLABEL_CODE028 = "00028"
        Const conLABEL_CODE030 = "00030"
        Const conLABEL_CODE031 = "00031"
        Const conLABEL_CODE032 = "00032"
        Const conLABEL_CODE033 = "00033"
        Const conLABEL_CODE034 = "00034"
        Const conLABEL_CODE035 = "00035"
        Const conLABEL_CODE036 = "00036"
        Const conLABEL_CODE037 = "00037"
        Const conLABEL_CODE039 = "00039"
        Const conLABEL_CODE040 = "00040"
        Const conLABEL_CODE041 = "00041"
        Const conLABEL_CODE042 = "00042"
        Const conLABEL_CODE043 = "00043"
        Const conLABEL_CODE044 = "00044"
        Const conLABEL_CODE102 = "10002"
        Const conLABEL_CODE101 = "10001"
        Const conLABEL_CODE103 = "10003"
        Const conLABEL_CODE104 = "10004"
        Const conLABEL_CODE105 = "10005"
        Const conLABEL_CODE106 = "10006"
        Const conLABEL_CODE107 = "10007"
        Const conLABEL_CODE108 = "10008"
        Const conLABEL_CODE109 = "10009"
        Const conLABEL_CODE110 = "10010"
        Const conLABEL_CODE111 = "10011"
        Const conLABEL_CODE206 = "20006"
        Const conLABEL_CODE207 = "20007"
        Const conLABEL_CODE208 = "20008"
        Const conLABEL_CODE209 = "20009"
        Const conLABEL_CODE210 = "20010"
        Const conLABEL_CODE211 = "20011"
        Const conLABEL_CODE212 = "20012"
        Const conLABEL_CODE217 = "20017"
        Const conLABEL_CODE218 = "20018"
        Const conLABEL_CODE219 = "20019"
        Const conLABEL_CODE220 = "20020"
        

'=============================================================================
' Constants and Variables Declaration Section
'=============================================================================
        Const ForReading = 1
        Const ForWriting = 2
        Const HKLM = &H80000002

        Dim blnOK
        Dim objArgs, objFSO, objGroupDict, objFile, objEnv
        Dim objShell, objWMIReg, objWMIReg2, objWMIService 
        Dim objXMLDoc, objXMLGetElement ,objXMLErr
        Dim objNetwork
        Dim strArg, strArgValue
        Dim strWinDir, strConfigFile, strComputerRole, strCMDPath
        Dim strAbsoluteConfigPath 
        Dim strAbsoluteSCEUpdate
        Dim strAbsoluteSecurityTemplates, strAbsoluteXMLPath
        Dim strBackupGPOPath	
        Dim strMachinePOLPath, strUserPOLPath
        Dim strInfPath, strCsvPath
        Dim strDefaultSdbPath,strLocalSdbPath
        Dim strDefaultInfPath, strLocalInfPath
        Dim strDefaultAuditPath
        Dim strEnvironment, strErrCode
        Dim strMessage, strMessage1, strMessage2, strMessage3
        Dim strOpSys, strOpVer, strSPMinorVer, strSPMajorVer, strOS 
        Dim strSCEUpdate, strSecurityTemplates
        Dim strTitle    
        Dim strPath, strProduct, strScePath, strText 
        Dim strRegKey, strRegValue
        Dim strUserName, strUserDomain 
        Dim strXMLPath
	Dim strGUID

        Dim intUserChoice
        Dim strFileName
        Dim strSceOrigFile, strSceOldFile
        Dim strWin7SceRegvl, strVistaSceRegvl, strXPSP2SceRegvl, strW2K3SP1SceRegvl, strW2K8SP1SceRegvl

        Dim intRegFlg,intStringFlg
        Dim intMSSRegStartLn, intMSSRegEndLn
        Dim objTempFolder, objF
        Dim strMSSRegistryFile, strMSSStringFile
        Dim strMSSRegistryPatrn, strMSSStringPatrn
        Dim strSceOutFile

        Dim objReg, subkey
        Dim strKeyPath
        Dim SubKeysArray(500)

        Set objFSO = CreateObject("Scripting.FileSystemObject")
        Set objShell = WScript.CreateObject("WScript.Shell")
        CheckError 532,Err.Number,Err.Description

        Set objWMIService = GetObject("winmgmts:"& _
            "{impersonationLevel=impersonate}!\\"& _
            "." & "\root\cimv2")

        Set objWMIReg = GetObject("winmgmts:"& _
            "{impersonationLevel=impersonate}!\\"& _
            "." & "\root\default:StdRegProv")


        Set objNetwork = WScript.CreateObject("WScript.Network")

        Set objXMLDoc = CreateObject("Microsoft.XMLDOM")

        Set objArgs = WScript.Arguments

        Set objEnv = objShell.Environment("Process")
        CheckError 109,Err.Number,Err.Description

        strKeyPath = "Software\Microsoft\Windows NT\CurrentVersion\SeCEdit\Reg Values"

        strConfigFile = ".\Localization.ini"             
        strTitle = "LocalGPO Tool"			
        strSCEUpdate = ".\SCE Update"
        strSecurityTemplates = ".\Security Templates"	
        strXMLPath = ".\Path.xml"
        strRegKey = "HKLM\SOFTWARE\Microsoft\MMC\SnapIns\"& _
        "{E12BBB5D-D59D-4E61-947A-301D25AE8C23}\NameString"

        strUserName = objNetwork.UserName
        strUserDomain = objNetwork.UserDomain
        strAbsoluteConfigPath = objFSO.GetAbsolutePathName(strConfigFile)
        strAbsoluteXMLPath = objFSO.GetAbsolutePathName(strXMLPath)
        strAbsoluteSCEUpdate = objFSO.GetAbsolutePathName(strSCEUpdate)
        strAbsoluteSecurityTemplates = objFSO.GetAbsolutePathName(strSecurityTemplates)

        strWindir=objShell.ExpandEnvironmentStrings("%WinDir%")

        strScePath = objEnv("SYSTEMROOT") & "\inf\"

        strXPSP2SceRegvl = "sceregvl_XPSP2.inf.txt"
        strW2K3SP1SceRegvl = "sceregvl_W2K3_SP1.inf.txt"
        strVistaSceRegvl = "sceregvl_Vista.inf.txt"
        strW2K8SP1SceRegvl = "sceregvl_W2K8_SP1.inf.txt"
        strWin7SceRegvl = "sceregvl_Win7.inf.txt"
        strSceOrigFile = strScePath & "sceregvl.inf"
        strSceOldFile = "sceregvl_old.inf"


'=============================================================================
'                                     Main
'=============================================================================

        Call ChkAdmin

        Call RemoveBlankLines
                                   
        Call ChkOSVersion    

        Call ChkProperUsage

        If WScript.Arguments.Named.Exists("ConfigSCE") or _
        WScript.Arguments.Named.Exists("ResetSCE") Then
            Call ConfigureSCE
        ElseIf WScript.Arguments.Named.Exists("Restore") Then
            Call RestoreLocalPolicy
        ElseIf WScript.Arguments.Named.Exists("Export") and _
        WScript.Arguments.Named.Exists("Path") Then
            Call ExportLocalPolicy
        ElseIf WScript.Arguments.Named.Exists("MLGPO") and _
	WScript.Arguments.Named.Exists("Path") Then
            Call ConfigureMLGPO
        ElseIf WScript.Arguments.Named.Exists("Path") Then
            Call ConfigureLocalPolicy
        Else
            WScript.Arguments.ShowUsage
        End If	

        Set objXMLDoc = Nothing			
        Set objShell = Nothing
        Set objWMIService = Nothing
        Set objWMIReg = Nothing
        Set objNetwork = Nothing
        Set objFSO = Nothing
        Set objArgs = Nothing
        Set objEnv = Nothing
        
        
'*****************************************************************************
' 
' Routine Name:
'
'   RemoveBlankLines
' 
' Description :
'    
'   This routine removes the spaces, blank lines from the configuration
'   (.INI) file.
'        
' Inputs:
'   
'   None.
'
' Outputs:
' 
'   None.
'*****************************************************************************
    Sub RemoveBlankLines

        Dim objFile
        Dim StrLine
        Dim strNewContents           

        Set objFile = objFSO.OpenTextFile(strAbsoluteConfigPath, ForReading)
        Do Until objFile.AtEndOfStream
          strLine = objFile.Readline
          strLine = Trim(strLine)
          If Len(strLine) > 0 Then
            strNewContents = strNewContents & strLine & vbCrLf
          End If
        Loop
        objFile.Close

        Set objFile = objFSO.OpenTextFile(strAbsoluteConfigPath, ForWriting)
        objFile.Write strNewContents
        objFile.Close

    End Sub 
      			
      
'*****************************************************************************
' 
' Function Name:
'
'   DisplayMessage
' 
' Description :
'    
'   This function fetches the corresponding error message for the error 
'   code from the configuration (.INI) file.
'
' Inputs:
'   
'   String containing error code
'
' Outputs:
' 
'   Return value is string containing error message for the corresponding
'   error code
'*****************************************************************************
    Function DisplayMessage(strErrCode)

        Dim arrErrValues 
        Dim strLine        
        Dim objFile
        Dim strMessage2

        Set objFSO = CreateObject("Scripting.FileSystemObject")
        
        Set objFile = objFSO.OpenTextFile(strAbsoluteConfigPath, ForReading)        
        Do Until objFile.AtEndOfStream
          strLine = objFile.Readline
          arrErrValues = Split(strLine, ":", -1, 1)
          If(strErrCode = arrErrValues(0)) Then
            strMessage2 = arrErrValues(1)      
          End If 
        Loop
        
        DisplayMessage = strMessage2
        objFile.Close

    End Function      
      
      
'*****************************************************************************
' 
' Routine Name:
'
'   ChkOSVersion
' 
' Description :
'    
'   This routine gets the Operating System's caption,version and Service
'   Pack information on the host
'
' Inputs:
'   
'   None.
'
' Outputs:
' 
'   None.
'*****************************************************************************     
    Sub ChkOSVersion
    		
        Dim colOperatingSystems, objOperatingSystem
        Dim colComputers, objComputer, strProductType

        Set colOperatingSystems = objWMIService.ExecQuery _
          ("Select * from Win32_OperatingSystem")

        For Each objOperatingSystem in colOperatingSystems
          strOpSys=objOperatingSystem.Caption
          strOpVer=objOperatingSystem.Version
          strSPMinorVer=objOperatingSystem.ServicePackMinorVersion
          strSPMajorVer=objOperatingSystem.ServicePackMajorVersion
          strProductType=objOperatingSystem.ProductType
        Next

        strComputerRole = NULL

        Set colComputers = objWMIService.ExecQuery _
          ("Select DomainRole from Win32_ComputerSystem")
        For Each objComputer in colComputers
          Select Case objComputer.DomainRole 
            Case 0 
              strComputerRole = "Standalone"
            Case 1        
              strComputerRole = "Member"
            Case 2 
              strComputerRole = "Standalone"
            Case 3        
              strComputerRole = "Member"
          End Select
        Next	

        'Checks whether the operating system is Windows XP or _
        'Windows Server 2003 or Windows Vista or Windows Server 2008 or _
        'Windows 7 or Windows Server 2008 R2

        If(Left(strOpVer,3) = "6.1") and (strProductType <> "1") then 
	   strOS = "WS08R2"
        ElseIf(Left(strOpVer,3) = "6.1") and (strProductType = "1") then 
	   strOS = "Win7"
        ElseIf(Left(strOpVer,3) = "6.0") and (strProductType <> "1") then 
	   strOS = "WS08"
	ElseIf(Left(strOpVer,3) = "6.2") and (strProductType <> "1") then 
	   strOS = "WS08"
	ElseIf(Left(strOpVer,3) = "6.3") and (strProductType <> "1") then 
	   strOS = "WS08"
	ElseIf(Left(strOpVer,3) = "6.0") and (strProductType = "1") then 
	   strOS = "VISTA"
        ElseIf(Left(strOpVer,3) = "5.2") and (strProductType <> "1") then
	   strOS = "WS03"
        ElseIf(Left(strOpVer,3) = "5.2") and (strProductType = "1") then 
	   strOS = "XP"
        ElseIf(Left(strOpVer,3) = "5.1") and (strProductType = "1") then 
	   strOS = "XP"
        Else
          strMessage = DisplayMessage(conLABEL_CODE002)
          Call MsgBox(strMessage, vbOKOnly + vbCritical, strTitle)
          WScript.Quit(1)
        End If

    End Sub      
      
      
'*****************************************************************************
' 
' Routine Name:
'
'   ChkAdmin
' 
' Description :
'    
'   This routine checks if the user is a local administrator         
'
' Inputs:
'   
'   None.
'
' Outputs:
' 
'   None.
'*****************************************************************************      
    Sub ChkAdmin

        Dim strKeyPath, bIsAdmin

        CONST KEY_SET_VALUE = &H0002
        CONST HKEY_LOCAL_MACHINE = &H80000002

        strKeyPath = "SYSTEM\CurrentControlSet"

        objWMIReg.CheckAccess HKEY_LOCAL_MACHINE, strKeyPath, KEY_SET_VALUE, _
          bIsAdmin

        If Not(bIsAdmin) Then
          strMessage = "You must use the 'Run as Administrator' option to use this tool."
          Call MsgBox(strMessage, vbOKOnly + vbCritical, strTitle)
          WScript.Quit(1)
        End If 

    End Sub
      
            
'*****************************************************************************
' 
' Routine Name:
'
'   ChkProperUsage
' 
' Description :
'    
'   This routine does simple checks for incorrect usage.        
'
' Inputs:
'   
'   None.
'
' Outputs:
' 
'   None.
'*****************************************************************************            
    Sub ChkProperUsage

        blnOK = True

        ' ~~~ Simple checks for incorrect usage

        If WScript.Arguments.Named.Count = 0 or _
          WScript.Arguments.Named.Count > 3 Then
          blnOK = False
        End If

        If WScript.Arguments.Named.Count = 1 and _
          Not(WScript.Arguments.Named.Exists("Path")) and _
          Not(WScript.Arguments.Named.Exists("Restore")) and _
          Not(WScript.Arguments.Named.Exists("ConfigSCE")) and _
          Not(WScript.Arguments.Named.Exists("ResetSCE")) Then          
          blnOK = False
        End If  

        If WScript.Arguments.Named.Count = 2 Then
		blnOK = False
		If (WScript.Arguments.Named.Exists("Path")) and (WScript.Arguments.Named.Exists("Export")) Then
			blnOK = True
		ElseIF (WScript.Arguments.Named.Exists("Path")) and (WScript.Arguments.Named.Exists("MLGPO")) Then

			blnOK = True
		end If
	end If

        If WScript.Arguments.Named.Count = 3 Then
		blnOK = False
		If (WScript.Arguments.Named.Exists("Path")) and (WScript.Arguments.Named.Exists("Export")) and (WScript.Arguments.Named.Exists("GPOPACK")) Then
			blnOK = True
		end If
	end If

        ' ~~~ If incorrect usage display message and quit
        If Not(blnOK) Then
          WScript.Arguments.ShowUsage
          WScript.Quit
        End If

    End Sub

'===================================================================================
'	Feature #1 - Apply of a GPO Backup to the Local Policy of a computer
'	-------
'	
'===================================================================================
  
'*****************************************************************************
' 
' Routine Name:
'
'   ConfigureLocalPolicy
' 
' Description :
'    
'   This routine applies a GPO backup to the local policy of a computer.          
'
' Inputs:
'   
'   None.
'
' Outputs:
' 
'   None.
'*****************************************************************************  
    Sub ConfigureLocalPolicy

        dim strTempdir, objFileCopy

        Call ReadPathFromXML

        blnOK = False

        objShell.CurrentDirectory = strAbsoluteSecurityTemplates
        strBackupGPOPath = WScript.Arguments.named("PATH")
        
        If objFSO.FolderExists(strBackupGPOPath) Then 

            strInfPath = strBackupGPOPath & "\DomainSysvol\GPO\Machine\microsoft\windows nt\SecEdit\GptTmpl.inf"
            strMachinePOLPath = strBackupGPOPath & "\DomainSysvol\GPO\Machine\registry.pol"
            strUserPOLPath = strBackupGPOPath & "\DomainSysvol\GPO\User\registry.pol"
            strCsvPath = strBackupGPOPath & "\DomainSysvol\GPO\Machine\microsoft\windows nt\Audit\Audit.csv"

            strMessage = DisplayMessage(conLABEL_CODE020)
            WScript.echo
            WScript.echo strMessage
            WScript.echo 

            If (strOS = "Win7") or (strOS = "Vista") or (strOS = "WS08R2") or (strOS = "WS08") Then
              Call objShell.Run("ICACLS " & chr(34) & strDefaultSdbPath & _
                chr(34) & " /GRANT:R *S-1-5-32-544:F", 0, True)
              Call objShell.Run("ICACLS " & chr(34) & strLocalSdbPath & _
                chr(34) & " /GRANT:R *S-1-5-32-544:F", 0, True)
            End If

            If objFSO.FileExists(strInfPath) Then
            blnOK = True
              If (strOS = "XP") or (strOS = "WS03") Then
                Call objShell.Run("SECEDIT.EXE /configure /db " & chr(34) & _
                  strLocalSdbPath & chr(34) & " /cfg " & chr(34) & _
                  strInfPath & chr(34), 0, True)
                Call objShell.Run("REG DELETE" & chr(34) & _
                  "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer"& _
                  "\MyComputer\NameSpace\DelegateFolders\"& _
                  "{59031a47-3f72-44a7-89c5-5595fe6b30ee}" & chr(34) & "/f ", 0, _
                  True)      
              Else
                Call objShell.Run("SECEDIT.EXE /configure /db " & chr(34) & _
                  strLocalSdbPath & chr(34) & " /cfg " & chr(34) & _
                  strInfPath & chr(34) & " /Overwrite /quiet", 0, True)
              End If
              strMessage = DisplayMessage(conLABEL_CODE030)
              WScript.echo strMessage & " " & strBackupGPOPath
            Else
              strMessage = DisplayMessage(conLABEL_CODE031)
              WScript.echo strMessage & " " & strBackupGPOPath
            End If

            If objFSO.FileExists(strMachinePOLPath) Then
	          blnOK = True
              Call objShell.Run("LocalPol.EXE -f " & chr(34) & _
                strMachinePolPath & chr(34) & " -m", 0, True)
              strMessage = DisplayMessage(conLABEL_CODE032)
              WScript.echo strMessage & " " & strBackupGPOPath
            Else
              strMessage = DisplayMessage(conLABEL_CODE033)
              WScript.echo strMessage & " " & strBackupGPOPath
            End If

            If objFSO.FileExists(strUserPOLPath) Then
	          blnOK = True
              Call objShell.Run("LocalPol.EXE -f " & chr(34) & _
                strUserPolPath & chr(34) & " -u", 0, True) 		
              strMessage = DisplayMessage(conLABEL_CODE034)
              WScript.echo strMessage & " " & strBackupGPOPath
            Else
              strMessage = DisplayMessage(conLABEL_CODE035)
              WScript.echo strMessage & " " & strBackupGPOPath
            End If
            		
            If (strOS <> "XP") and (strOS <> "WS03") Then
              If objFSO.FileExists(strCsvPath) Then
                blnOK = True
                Set objFileCopy = objFSO.GetFile(strCsvPath)

                If (strOS = "Win7") or (strOS = "WS08R2") Then
                    Dim arrDirs, i, strGPOAuditDir, strDirBuild

                    strGPOAuditDir = objFSO.GetAbsolutePathName( strWindir & "\System32\GroupPolicy\Machine\microsoft\windows nt\Audit" )
                    arrDirs = Split( strGPOAuditDir, "\" )

                    For i = 1 to Ubound( arrDirs )
                      strDirBuild = objFSO.BuildPath( strDirBuild, arrDirs(i) )
                        If Not objFSO.FolderExists( left(strWinDir,3) & strDirBuild ) Then 
                          objFSO.CreateFolder (left(strWinDir,3) & strDirBuild)
                        End If
                    Next


		    If objFSO.FileExists (strGPOAuditDir & "\Audit.csv") Then
        	         Call objFSO.DeleteFile(strGPOAuditDir & "\Audit.csv",True)
	  	    End If
	
	            objFileCopy.Copy(strGPOAuditDir & "\Audit.csv")

		    If objFSO.FileExists (strGPOAuditDir & "\Audit.csv") Then
                       If (objFSO.GetFile(strGPOAuditDir & "\Audit.csv").Attributes mod 2 = 1) Then  
        	    	   objFSO.GetFile(strGPOAuditDir & "\Audit.csv").Attributes = objFSO.GetFile(strGPOAuditDir & "\Audit.csv").Attributes-1
                       End If
	  	    End If

                End If

                strTempdir=objShell.ExpandEnvironmentStrings("%TEMP%")

		If objFSO.FileExists (strTempdir & "\Audit.csv") Then
        	     Call objFSO.DeleteFile(strTempdir & "\Audit.csv",True)
	  	End If

                objFileCopy.Copy(strTempdir & "\Audit.csv")

                Call Replacetxt(",System,", "PC,System,",strTempdir & "\Audit.csv")
                Call Replacetxt(",,", "PC,,",strTempdir & "\Audit.csv")
                Call objShell.Run("AUDITPOL /RESTORE /FILE:" & chr(34) & strTempdir & "\Audit.csv" & chr(34), 0, True)

		If objFSO.FileExists (strTempdir & "\Audit.csv") Then
        	     Call objFSO.DeleteFile(strTempdir & "\Audit.csv",True)
	  	End If

                strMessage = DisplayMessage(conLABEL_CODE036)
                WScript.echo strMessage & " " & strBackupGPOPath
              Else
                strMessage = DisplayMessage(conLABEL_CODE037)
                WScript.echo strMessage & " " & strBackupGPOPath
              End If   
            End If

	        If blnOK then
                  strMessage = DisplayMessage(conLABEL_CODE022)
                  WScript.echo
                  WScript.echo strMessage
                  WScript.echo

                  strMessage = DisplayMessage(conLABEL_CODE023)
                  WScript.echo
                  WScript.echo strMessage
                  WScript.echo
	        Else	
                  strMessage = DisplayMessage(conLABEL_CODE039)
                  WScript.echo
                  WScript.echo strMessage & " " & strBackupGPOPath
                  WScript.echo

                  strMessage = DisplayMessage(conLABEL_CODE040)
                  WScript.echo
                  WScript.echo strMessage
                  WScript.echo
	        End If
	    Else
            strMessage = DisplayMessage(conLABEL_CODE220)
            WScript.echo
            WScript.echo strMessage
            WScript.echo
        End If

    End Sub

'===================================================================================
'	Feature #1b - Apply a GPO Backup to MLGPO
'	-------
'	
'===================================================================================
  
'*****************************************************************************
' 
' Routine Name:
'
'   ConfigureMLGPO
' 
' Description :
'    
'   This routine applies a GPO backup to the MLGPO of a computer
'
' Inputs:
'   
'   None.
'
' Outputs:
' 
'   None.
'*****************************************************************************  
    Sub ConfigureMLGPO

        Dim strSID, colLocalAccounts, objLocalAccount, strAccount, blnGroup
        Dim arrDirs, i, strMLGPODir, strDirBuild, objFileCopy

        strBackupGPOPath = WScript.Arguments.named("PATH")

	strAccount = WScript.Arguments.named("MLGPO")
	strSID = ""

	Set colLocalAccounts = objWMIService.ExecQuery _
		("Select * from Win32_Account Where LocalAccount = True")
	For Each objLocalAccount in colLocalAccounts
		If UCase(objLocalAccount.Name) = Ucase(strAccount) Then
			strSID = objLocalAccount.SID
		End If
	Next

	Set colLocalAccounts = objWMIService.ExecQuery _
		("Select * from Win32_Group Where LocalAccount = True")
	For Each objLocalAccount in colLocalAccounts
		If UCase(objLocalAccount.Name) = Ucase(strAccount) Then
			blnGroup = True
		End If
	Next


	If UCase(strAccount) = UCase("Non-Administrators") Then
		strSID = "S-1-5-32-545"
	End If	

	If strSID = "" Then
		strMessage = "Local Account: " & strAccount & " not found!"
            	WScript.echo
       	    	WScript.echo strMessage
		WScript.echo "Please specify a valid local account, or one of the"
		WScript.echo "following local groups: Administrators or Users"
      		WScript.echo 
		WScript.Quit(1)
	End If	


	If (strSID <> "S-1-5-32-544") and (strSID <> "S-1-5-32-545") and (blnGroup = True) Then
		strMessage = "Local Group: " & strAccount & " is not supported!"
            	WScript.echo
       	    	WScript.echo strMessage
		WScript.echo "MLGPO only supports Administrators and Non-Administrators(Users)"
		WScript.echo "You must specify Administrators, Non-Administrators, or Users"
      		WScript.echo 
		WScript.Quit(1)
	End If	


        If (strOS = "Win7") or (strOS = "Vista") or (strOS = "WS08R2") or (strOS = "WS08") Then

		If objFSO.FileExists(strBackupGPOPath & "\DomainSysvol\GPO\User\registry.pol") Then 

	           	Set objFileCopy = objFSO.GetFile(strBackupGPOPath & "\DomainSysvol\GPO\User\registry.pol")

	           	strMLGPODir = objFSO.GetAbsolutePathName(strWindir & "\System32\GroupPolicyUsers\" & strSID)
              	 	arrDirs = Split( strMLGPODir & "\User", "\" )

	           	For i = 1 to Ubound( arrDirs )
              	   		strDirBuild = objFSO.BuildPath( strDirBuild, arrDirs(i) )
				If Not objFSO.FolderExists( left(strWinDir,3) & strDirBuild ) Then 
					objFSO.CreateFolder (left(strWinDir,3) & strDirBuild)
                   		End If
                 	Next

		        If objFSO.FileExists(strMLGPODir & "\User\registry.pol") Then		
		          Call objFSO.DeleteFile(strMLGPODir & "\User\registry.pol",True)
		        End If	
			call objFileCopy.Copy(strMLGPODir & "\User\registry.pol")

			If objFSO.FileExists (strMLGPODir & "\User\registry.pol") Then
				If (objFSO.GetFile(strMLGPODir & "\User\registry.pol").Attributes mod 2 = 1) Then  
					objFSO.GetFile(strMLGPODir & "\User\registry.pol").Attributes = objFSO.GetFile(strMLGPODir & "\User\registry.pol").Attributes-1
	                        End If
	  	        End If

			If Not objFSO.FolderExists(strMLGPODir & "\User\Scripts") Then
				objFSO.CreateFolder(strMLGPODir & "\User\Scripts")
			End If
			If Not objFSO.FolderExists(strMLGPODir & "\User\Scripts\Logoff") Then
				objFSO.CreateFolder(strMLGPODir & "\User\Scripts\Logoff")
			End If
			If Not objFSO.FolderExists(strMLGPODir & "\User\Scripts\Logon") Then
				objFSO.CreateFolder(strMLGPODir & "\User\Scripts\Logon")
			End If
        	    	objFSO.GetFolder(strMLGPODir).attributes = 2	

		        If strSID = "S-1-5-32-544" then
              			Call objShell.Run("ICACLS " & chr(34) & strMLGPODir  & _
		                  chr(34) & " /inheritance:r /GRANT:R *S-1-5-18:(OI)(CI)F /GRANT:R *S-1-5-32-544:(OI)(CI)F", 0, True)

		        else
		        	Call objShell.Run("ICACLS " & chr(34) & strMLGPODir & _
                		  chr(34) & " /inheritance:r /GRANT:R *S-1-5-18:(OI)(CI)F /GRANT:R *S-1-5-32-544:(OI)(CI)F /GRANT:R *" & strSID & ":(OI)(CI)RX", 0, True)

		        End If

			strMessage = strAccount &" MLGPO... Modified!"
	            	WScript.echo
       		    	WScript.echo strMessage
			WScript.echo 

	                Call objShell.Run("ICACLS " & chr(34) & strMLGPODir & "\*" & _
                         chr(34) & " /inheritance:e", 0, True)
			
			objFSO.CreateTextFile(strMLGPODir & "\gpt.ini")			
			set objFile = objFSO.OpenTextFile(strMLGPODir & "\gpt.ini", ForWriting)
			objFile.Writeline "[General]"
			objFile.Writeline "gPCFunctionalityVersion=2"
			objFile.Writeline "gPCUserExtensionNames=[{35378EAC-683F-11D2-A89A-00C04FBBCFA2}{D02B1F73-3407-48AE-BA88-E8213C6761F1}]"
			objFile.Writeline "Version=65536"
			objFile.Close	

		Else
			strMessage = "GPO Backup in " & strBackupGPOPath & " contains no User settings!"
	            	WScript.echo
        	    	WScript.echo strMessage
           		WScript.echo
		End If
       Else

            strMessage = "Windows XP and Windows Server 2003 do not support MLGPO!!"
            WScript.echo
            WScript.echo strMessage
            WScript.echo 

       End If

   End Sub
    
'===================================================================================
'	Feature #1a - Export the Local Policy of a computer to a GPO backup
'	-------
'	
'===================================================================================

'*****************************************************************************
' 
' Routine Name:
'
'   ExportLocalPolicy
' 
' Description :
'    
'   This routine exports the Local Policy of computers to a GPO backup        
'
' Inputs:
'   
'   None.
'
' Outputs:
' 
'   None.
'*****************************************************************************  
    Sub ExportLocalPolicy

        dim strComputer, strTempdir, objFileCopy
        
        dim colOperatingSystems, objOperatingSystem
        dim strHour, strMinutes, strSeconds
        dim strYear, strMonth, strDay

        Call ReadPathFromXML

        blnOK = False
    
        objShell.CurrentDirectory = strAbsoluteSecurityTemplates
        strBackupGPOPath = WScript.Arguments.named("PATH")
    
        If objFSO.FolderExists(strBackupGPOPath) Then 
        
            If objFSO.FileExists(".\GPO\Backup.XML") and objFSO.FileExists(".\GPO\bkupInfo.XML") and objFSO.FileExists(".\GPO\Registry.pol") Then

                strMessage = DisplayMessage(conLABEL_CODE019)
                WScript.echo
                WScript.echo strMessage
                WScript.echo     

                If  (WScript.Arguments.Named.Exists("GPOPack")) and (WScript.Arguments.Named("GPOPack") <> "") Then
		    strGUID = WScript.Arguments.Named("GPOPack")
		Else
		    strGUID = left(createobject("Scriptlet.Typelib").guid,38)
		End If
        
                objFSO.CreateFolder(strBackupGPOPath & "\" & strGUID)
                objFSO.CreateFolder(strBackupGPOPath & "\" & strGUID & "\DomainSysvol")
                objFSO.CreateFolder(strBackupGPOPath & "\" & strGUID & "\DomainSysvol\GPO")
                objFSO.CreateFolder(strBackupGPOPath & "\" & strGUID & "\DomainSysvol\GPO\User")
                objFSO.CreateFolder(strBackupGPOPath & "\" & strGUID & "\DomainSysvol\GPO\Machine")
                objFSO.CreateFolder(strBackupGPOPath & "\" & strGUID & "\DomainSysvol\GPO\Machine\microsoft")
                objFSO.CreateFolder(strBackupGPOPath & "\" & strGUID & "\DomainSysvol\GPO\Machine\microsoft\windows nt")
                objFSO.CreateFolder(strBackupGPOPath & "\" & strGUID & "\DomainSysvol\GPO\Machine\microsoft\windows nt\SecEdit")
                objFSO.CreateFolder(strBackupGPOPath & "\" & strGUID & "\DomainSysvol\GPO\Machine\microsoft\windows nt\Audit")

                strInfPath = strBackupGPOPath & "\" & strGUID & "\DomainSysvol\GPO\Machine\microsoft\windows nt\SecEdit\GptTmpl.inf"
                strMachinePOLPath = strBackupGPOPath & "\" & strGUID & "\DomainSysvol\GPO\Machine\registry.pol"
                strUserPOLPath = strBackupGPOPath & "\" & strGUID & "\DomainSysvol\GPO\User\registry.pol"
                strCsvPath = strBackupGPOPath & "\" & strGUID & "\DomainSysvol\GPO\Machine\microsoft\windows nt\Audit\audit.csv"

                Call objFSO.CopyFile(".\GPO\Backup.XML",strBackupGPOPath & "\" & strGUID & "\Backup.XML")
                Call objFSO.CopyFile(".\GPO\bkupInfo.XML",strBackupGPOPath & "\" & strGUID & "\bkupInfo.XML")
                
                Call objFSO.CopyFile(".\GPO\Registry.pol",strMachinePOLPath)
                Call objFSO.CopyFile(".\GPO\Registry.pol",strUserPOLPath)
                Call objFSO.CreateTextFile(strInfPath,True)
                Call objFSO.CreateTextFile(strCsvPath,True)
                
                Set colOperatingSystems = objWMIService.ExecQuery _
                 ("Select * from Win32_UTCTime")
                For Each objOperatingSystem in colOperatingSystems
                  strHour=objOperatingSystem.Hour
                  strMinutes=objOperatingSystem.Minute
                  strSeconds=objOperatingSystem.Second
                  strYear=objOperatingSystem.Year
                  strMonth=objOperatingSystem.Month
                  strDay=objOperatingSystem.Day
                Next

                Call Replacetxt("[CDATA[2010-01-01T12:00:00]]","[CDATA[" & strYear & "-" & strMonth & "-" & strDay & "T" & strHour & ":" & strMinutes & ":" & strSeconds & "]]",strBackupGPOPath & "\" & strGUID & "\bkupInfo.XML")

                If objFSO.FileExists(strWindir & "\System32\GroupPolicy\Machine\registry.pol") Then		
                  Call objFSO.CopyFile(strWindir & "\System32\GroupPolicy\Machine\registry.pol",strMachinePOLPath)
                End If	

                If objFSO.FileExists(strWindir & "\System32\GroupPolicy\User\registry.pol") Then		
                  Call objFSO.CopyFile(strWindir & "\System32\GroupPolicy\User\Registry.pol",strUserPOLPath)
                End If	

                Call objShell.Run("SECEDIT.EXE /export /cfg " & chr(34) & strInfPath & chr(34), 0, True)
     
                If (strOS <> "XP") and (strOS <> "WS03") Then
                    objFSO.DeleteFile(strCsvPath)
                    Call objShell.Run("AUDITPOL.EXE /BACKUP /FILE:" & chr(34) & strCSVPath & chr(34), 0, True)
		    If objFSO.FileExists(strCSVPath) = False Then
		    	Call objFSO.CreateTextFile(strCsvPath,True)
		    End If	 	
                    strComputer=objShell.ExpandEnvironmentStrings("%COMPUTERNAME%")
                    Call Replacetxt(strComputer & ",System,", ",System,",strCSVPath)
                    Call Replacetxt(strComputer & ",,", ",,",strCSVPath)
                End If

		If WScript.Arguments.Named.Exists("GPOPack") Then
                    Call objFSO.CopyFile(".\GPOPack.wsf",strBackupGPOPath & "\" & strGUID & "\GPOPack.wsf")
                    Call objFSO.CopyFile(".\LocalPol.exe",strBackupGPOPath & "\" & strGUID & "\LocalPol.exe")
                    Call objFSO.CopyFile(".\LocalSecurityDB.sdb",strBackupGPOPath & "\" & strGUID & "\LocalSecurityDB.sdb")
                End If	

                strMessage = DisplayMessage(conLABEL_CODE218) & " " & strBackupGPOPath & "\" & strGUID
                WScript.echo
                WScript.echo strMessage
                WScript.echo     
            Else
                strMessage = DisplayMessage(conLABEL_CODE219)
                WScript.echo
                WScript.echo strMessage
                WScript.echo
            End If       
        Else
            strMessage = DisplayMessage(conLABEL_CODE220)
            WScript.echo
            WScript.echo strBackupGPOPath
            WScript.echo
            WScript.echo strMessage
            WScript.echo
        End If

    End Sub
    
'*****************************************************************************
' 
' Function Name:
'
'   ReplaceTxt
' 
' Description :
'    
'   This routine reads a text file, and replaces text with specified text.
'
' Inputs:
'   
'   Filename, string to replace, replacement text
'
' Outputs:
' 
'   Modified file with replaced text
'*****************************************************************************        
    Function ReplaceTxt(Find, ReplaceWith, FileName)

        dim FileContents, dFileContents
                
        'Read source text file
        FileContents = GetFile(FileName)

        'replace all string In the source file
        dFileContents = replace(FileContents, Find, ReplaceWith, 1, -1, 1)

        'Compare source And result
        if dFileContents <> FileContents Then
          'write result If different
          WriteFile FileName, dFileContents
        End If

        End Function

        'Read text file
        function GetFile(FileName)

        If FileName<>"" Then
          Dim FS, FileStream
          Set FS = CreateObject("Scripting.FileSystemObject")
          on error resume Next
          Set FileStream = FS.OpenTextFile(FileName)
          GetFile = FileStream.ReadAll
        End If

        End Function

        'Write string As a text file.
        function WriteFile(FileName, Contents)
        Dim OutStream, FS

        on error resume Next
        Set FS = CreateObject("Scripting.FileSystemObject")
        Set OutStream = FS.OpenTextFile(FileName, 2, True)
        OutStream.Write Contents
        
    End Function


      
'===================================================================================
'	Feature #2 - Restore Local Policy to Default Configuration
'	-------
'	
'===================================================================================

'*****************************************************************************
' 
' Routine Name:
'
'   RestoreLocalPolicy
' 
' Description :
'    
'   This routine applies security templates to standalone computers.          
'
' Inputs:
'   
'   None.
'
' Outputs:
' 
'   None.
'*****************************************************************************  
    Sub RestoreLocalPolicy

	dim objMLGPOFolder, objMLGPOFiles, objMLGPOFolders, objFile, objSubFolder

        Call ReadPathFromXML

        objShell.CurrentDirectory = strAbsoluteSecurityTemplates

        If (strOS = "Win7") or (strOS = "Vista") or (strOS = "WS08R2") or (strOS = "WS08") Then
	        Call objShell.Run("ICACLS " & chr(34) & strDefaultSdbPath & _
                chr(34) & " /GRANT:R *S-1-5-32-544:F", 0, True)
                Call objShell.Run("ICACLS " & chr(34) & strLocalSdbPath & _
                chr(34) & " /GRANT:R *S-1-5-32-544:F", 0, True)
        End If


        strMessage = DisplayMessage(conLABEL_CODE020)
        WScript.echo
        WScript.echo strMessage
        WScript.echo

        
        strMessage = DisplayMessage(conLABEL_CODE041)
        WScript.echo strMessage
        Call objShell.Run("SECEDIT.EXE /configure /db " & chr(34) & _
        strDefaultSdbPath & chr(34) & " /cfg " & chr(34) & _
        strDefaultInfPath & chr(34), 0, True)

        Call objShell.Run(chr(34) & strCMDPath & chr(34), 0, True)

        strMessage = DisplayMessage(conLABEL_CODE042)
        WScript.echo strMessage
        If objFSO.FileExists(strWindir & "\System32\GroupPolicy\Machine\registry.pol") Then		
          Call objFSO.DeleteFile(strWindir & "\System32\GroupPolicy\Machine\registry.pol")
        End If	

        If objFSO.FileExists(strWindir & "\System32\GroupPolicy\User\registry.pol") Then		
          Call objFSO.DeleteFile(strWindir & "\System32\GroupPolicy\User\registry.pol")
        End If	

        If (strOS <> "XP") and (strOS <> "WS03")Then
 
            If objFSO.FileExists(strWindir & "\System32\GroupPolicy\Machine\microsoft\windows nt\Audit\Audit.csv") Then		
                Call objFSO.DeleteFile(strWindir & "\System32\GroupPolicy\Machine\microsoft\windows nt\Audit\Audit.csv")
            End If	

            strMessage = DisplayMessage(conLABEL_CODE043)
            WScript.echo strMessage
            Call objShell.Run("AUDITPOL /RESTORE /FILE:" & chr(34) & strDefaultAuditPath & chr(34), 0, True)

	    Set objMLGPOFolder = objFSO.GetFolder(strWindir & "\System32\GroupPolicyUsers")
	    Set objMLGPOFiles = objMLGPOFolder.Files
	    Set objMLGPOFolders = objMLGPOFolder.SubFolders

	    WScript.echo "Restoring MLGPO..."

	    For Each objFile In objMLGPOFiles
	      objFile.Delete(True)
	    Next

	    For Each objSubFolder In objMLGPOFolders
	      objSubFolder.Delete(True)
	    Next

            strMessage = DisplayMessage(conLABEL_CODE044)
            WScript.echo strMessage

	End If
          
        strMessage = DisplayMessage(conLABEL_CODE021)
        WScript.echo
        WScript.echo strMessage
        WScript.echo

        strMessage = DisplayMessage(conLABEL_CODE023)
        WScript.echo
        WScript.echo strMessage
        WScript.echo

    End Sub

      
'*****************************************************************************
' 
' Routine Name:
'
'   ReadPathFromXML
' 
' Description :
'    
'   This routine reads the XML file and stores the path values of 
'   Security Templates (.inf and .sdb files) and GPMC backup files
'
' Inputs:
'   
'   None.
'
' Outputs:
' 
'   None.
'*****************************************************************************            
    Sub ReadPathFromXML      

        Dim objPathNode , objSecurityTemplateNode

        objXMLDoc.async = false
        objXMLDoc.load(strAbsoluteXMLPath)

        If (objXMLDoc.parseError.errorCode <> 0) Then
          Set objXMLErr = objXMLDoc.parseError
          Call Msgbox (DisplayMessage(conLABEL_CODE028), vbOKOnly + vbCritical, strTitle)
          WScript.Quit(1)
        End If        

        Set objXMLGetElement = objXMLDoc.getElementsbyTagName("Path")

        'Enters the Path element in the XML file and fetches the corresponding _ 
        'path values in variables.
        For Each objPathNode in objXMLGetElement
          If strOS = objPathNode.getAttribute("Product") Then
            strDefaultSdbPath = objPathNode.getAttribute("DefaultSdbPath")      
            strLocalSdbPath = objPathNode.getAttribute("LocalSdbPath")
            strDefaultInfPath = objPathNode.getAttribute("DefaultInfPath") 
          End If        
        Next   

        Set objXMLGetElement = objXMLDoc.getElementsbyTagName("SecurityTemplate")

        For Each objSecurityTemplateNode in objXMLGetElement 
          If strOS = objSecurityTemplateNode.getAttribute("Product") Then
            strCMDPath = objSecurityTemplateNode.getAttribute("LocalCMDPath")
            If (strOS <> "XP") and (strOS <> "WS03")Then
              strDefaultAuditPath = objSecurityTemplateNode.getAttribute("DefaultAuditPath")
            End If
          End If
        Next

    End Sub  


'===================================================================================
'	Feature #3 - Modify Security Configuraton Editor(SCE)
'	-------
'	
'===================================================================================

'*****************************************************************************
' 
' Routine Name:
'
'   ConfigureSCE
' 
' Description :
'    
'   This routine calls appropriate Security Configuration Editor 
'   modification that update SCE to include MSSC prescribed settings      
'
' Inputs:
'   
'   None.
'
' Outputs:
' 
'   None.
'***************************************************************************** 
    Sub ConfigureSCE

        Dim strTargetText1, strTargetText2, strTargetText3, strTargetText4 

        objShell.CurrentDirectory = strAbsoluteSCEUpdate

        If WScript.Arguments.Named.Exists("ResetSCE") Then
          Restore_SCE_to_Default
        Else

          Const ForReading = 1

          Set objEnv = objShell.Environment("Process")

          strScePath = objEnv("SYSTEMROOT") & "\inf\"

          Set objFile = objFSO.OpenTextFile(strScePath & "SCERegVL.inf", ForReading)

          strText = objFile.ReadAll
          objFile.Close

          strTargetText1 = ";========= Start of MSS Registry Values ========="
          strTargetText2 = ";========= End of MSS Registry Values ========="
          strTargetText3 = ";========= Start of MSS Strings Values ========="
          strTargetText4 = ";========= End of MSS Strings Values ========="

          If (InStr(strText,strTargetText1) = 0) or _
           (InStr(strText,strTargetText2) = 0) or _ 
           (InStr(strText,strTargetText3) = 0) or _
           (InStr(strText,strTargetText4) = 0) Then
             Update_SCE_with_MSS_Regkeys
          Else
            strMessage = DisplayMessage(conLABEL_CODE014)
            WScript.echo 
            WScript.echo strMessage
            WScript.echo
          End If

        End If

    End Sub


'*****************************************************************************
' 
' Routine Name:
'
'   Restore_SCE_to_Default
' 
' Description :
'    
'   Modifies the Security Configuration Editor to include 
'   only default "out of the box" settings
'
' Inputs:
'   
'   None.
'
' Outputs:
' 
'   None.
'*****************************************************************************    

    Sub Restore_SCE_to_Default

        Set objXMLDoc = CreateObject("Microsoft.XMLDOM")

        Set objArgs = WScript.Arguments

        strUserName = objNetwork.UserName
        strUserDomain = objNetwork.UserDomain
        strAbsoluteXMLPath = objFSO.GetAbsolutePathName(strXMLPath)
        strAbsoluteSCEUpdate = objFSO.GetAbsolutePathName(strSCEUpdate)
        strAbsoluteSecurityTemplates = objFSO.GetAbsolutePathName(strSecurityTemplates)

        If (RegExpTest("Microsoft Windows XP Professional",strOpSys) = 1) Then
          If strSPMajorVer >= 2 Then
              strMessage3 = DisplayMessage(conLABEL_CODE206)
              WScript.echo
              WScript.echo strMessage3
              WScript.echo
              OverwriteSceregvl strXPSP2SceRegvl
          Else
              strMessage3 = DisplayMessage(conLABEL_CODE206)
              WScript.echo
              WScript.echo strMessage3
              WScript.echo
              OverwriteSceregvl strXPSP2SceRegvl
          End If
        End If

        If (RegExpTest("Microsoft\(R\) Windows\(R\) Server 2003",strOpSys) = 1) Then
          If strSPMajorVer >= 1 Then    
              strMessage3 = DisplayMessage(conLABEL_CODE206)
              WScript.echo
              WScript.echo strMessage3
              WScript.echo
              OverwriteSceregvl strW2K3SP1SceRegvl
          Else
              strMessage3 = DisplayMessage(conLABEL_CODE206)
              WScript.echo
              WScript.echo strMessage3
              WScript.echo
              OverwriteSceregvl strW2K3SP1SceRegvl
          End If
        End If

        If (strOS = "Vista") Then
          If strSPMajorVer >= 0 Then  
              strMessage3 = DisplayMessage(conLABEL_CODE206)
              WScript.echo
              WScript.echo strMessage3
              WScript.echo
              OverwriteSceregvl strVistaSceRegvl
          Else
              strMessage3 = DisplayMessage(conLABEL_CODE206)
              WScript.echo
              WScript.echo strMessage3
              WScript.echo
              OverwriteSceregvl strVistaSceRegvl
          End If  
        End If

        If (strOS = "Win7") then
          If strSPMajorVer >= 0 Then  
              strMessage3 = DisplayMessage(conLABEL_CODE206)
              WScript.echo
              WScript.echo strMessage3
              WScript.echo
              OverwriteSceregvl strWin7SceRegvl
          Else
              strMessage3 = DisplayMessage(conLABEL_CODE206)
              WScript.echo
              WScript.echo strMessage3
              WScript.echo
              OverwriteSceregvl strWin7SceRegvl
          End If  
        End If

        If (strOS = "WS08R2") or (strOS = "WS08") then
          If strSPMajorVer = 1 Then  
              WScript.echo
              WScript.echo strMessage3
              WScript.echo
              OverwriteSceregvl strW2K8SP1SceRegvl
          Else
              strMessage3 = DisplayMessage(conLABEL_CODE206)
              WScript.echo
              WScript.echo strMessage3
              WScript.echo
              OverwriteSceregvl strW2K8SP1SceRegvl
          End If
        End If

        Set objReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" &_ 
          "." & "\root\default:StdRegProv")
        CheckError 535, Err.Number, Err.Description

        ReadSubKeysFromPath(strKeyPath)         'Enumerating the Subkeys

        DeleteSubKeysFromPath                   'Deleting the Subkeys

        strMessage = DisplayMessage(conLABEL_CODE111)
        Wscript.Echo strMessage
        ReRegisterSceCli                        'Re-registering SceCli.dll 

        strMessage1 = DisplayMessage(conLABEL_CODE102)
        Wscript.Echo
        Wscript.Echo strMessage1
        Wscript.Echo

    End Sub


'*****************************************************************************
' 
' Routine Name:
'
'   Update_SCE_with_MSS_Regkeys
' 
' Description :
'    
'   Modifies the Security Configuration Editor to include 
'   MSS settings
'
' Inputs:
'   
'   None.
'
' Outputs:
' 
'   None.
'*****************************************************************************    
    Sub Update_SCE_with_MSS_Regkeys

        Set objTempFolder = objFSO.GetSpecialFolder(2) '2 - User's Temp Folder
        CheckError 98,Err.Number,Err.Description

        strSceOrigFile = strScePath & "sceregvl.inf"
        strSceOutFile = objTempFolder & "\" & "sceregvl.inf.txt"
        strMSSRegistryFile = ".\" & "Values-sceregvl.txt"
        strMSSStringFile = ".\" & "Strings-sceregvl.txt"
        strMSSRegistryPatrn = "\[Register Registry Values\]"
        strMSSStringPatrn = "\[Strings\]"
        intRegFlg = 0
        intStringFlg = 0
        intMSSRegStartLn = 0
        intMSSRegEndLn = 0

        Dim strWindowsDir, colFolders, objFolder
        Dim colOperatingSystems, objOperatingSystem

        strWindowsDir = objEnv("SYSTEMROOT")
        strWindowsDir = "'" & left(strWindowsDir,3) & "\" & _
          Right(strWindowsDir,len(strWindowsDir) - 3) & "\\inf\\sceregvl.inf" & "'"

        Set objWMIService = GetObject _
          ("winmgmts:{impersonationLevel=impersonate,(Security,TakeOwnerShip)}!\\.\root\cimv2")
        Set colFolders = objWMIService.ExecQuery _
          ("Select * From CIM_DataFile Where Name = " & strWindowsDir)
        For Each objFolder in colFolders
          objFolder.TakeOwnershipEx
        Next


        If (strOS = "Win7") or (strOS = "Vista") or (strOS = "WS08R2") or (strOS = "WS08") Then
          Call objShell.Run _
            ("ICACLS %Systemroot%\inf\sceregvl.inf /GRANT:R *S-1-5-32-544:F", 0, True)
        End If

        strMessage = DisplayMessage(conLABEL_CODE007)
        Wscript.Echo
        Wscript.Echo strMessage
        Wscript.Echo

        If objFSO.FileExists(strSceOutFile) Then
          Set objF = objFSO.GetFile(strSceOutFile)
          objF.delete
        End If

        GetRegValLineNos

        UpdateSCEwithMSSValues

        CleanupFiles

        strMessage = DisplayMessage(conLABEL_CODE101)
        Wscript.Echo strScePath & strMessage
                     
        strMessage = DisplayMessage(conLABEL_CODE111)
        Wscript.Echo strMessage
        ReRegisterSceCli
         
        strMessage = DisplayMessage(conLABEL_CODE102)
        Wscript.Echo
        Wscript.Echo strMessage
        Wscript.Echo

    End Sub

'====================================================================
'Functions and Procedures related to Feature #3
'====================================================================

'***********************************************************************************
' 
' Routine Name:
'
'   OverwriteSceregvl
' 
' Description :
'    
'   This routine does file manipulation as defined in the header description
'
' Inputs:
'   
'   String containing XP SP2 inf file or WS2K3 SP1 inf file or Vista inf file.
'
' Outputs:
' 
'   None.
'***********************************************************************************
    Sub OverwriteSceregvl (SceregvlStr)
      Dim objFile

      'First check if the default SCE template is present
      CheckFilePresent(SceregvlStr)   
      
      If objFSO.FileExists(strScePath & strSceOldFile) Then
        Set objFile = objFSO.GetFile(strScePath & strSceOldFile)
        CheckError 366,Err.Number,Err.Description
        objFile.Delete                      'Deleting existing sceregvl_old.inf
        If Err.Number = 70 Then
          strMessage1 = DisplayMessage(conLABEL_CODE104)
          strMessage3 = DisplayMessage(conLABEL_CODE105)
          WScript.Echo strMessage1 &" "& strScePath & strSceOldFile & strMessage3      
          WScript.Quit(1)
        ElseIf Err.Number <> 0 Then
          CheckError 368, Err.Number, Err.Description
        End If	  
      End if

      Set objFile = objFSO.GetFile(strSceOrigFile)
      CheckError 379,Err.Number,Err.Description
    		
      'Rename sceregvl.inf to sceregvl_old.inf otherwise throw an error
      objFile.Name = strSceOldFile
      CheckError 383,Err.Number,Err.Description
      
      'Copy the default template file to sceregvl.inf 		
      objFSO.Copyfile SceregvlStr, strSceOrigFile   
      CheckError 387,Err.Number,Err.Description

      ' Clean up
      Set objFile = Nothing 
      Set objFSO = Nothing

    End Sub

'***********************************************************************************
' 
' Function Name:
'
'   RegExpTest
' 
' Description :
'    
'   This function takes input of pattern string and the string in which
'   pattern is to be searched.
'
' Inputs:
'   
'   Pattern string, String in which pattern is to be searched.
'
' Outputs:
' 
'   Return value is 1 if pattern is matched else returns 0.
'***********************************************************************************
    Function RegExpTest(patrn, strng)

      Dim regEx, Match, Matches             ' Create variable.
      Dim RetStr
      Set regEx = New RegExp                ' Create a regular expression.
      regEx.Pattern = patrn                 ' Set pattern.
      regEx.IgnoreCase = False              ' Set case insensitivity.
      regEx.Global = True                   ' Set global applicability.
      Set Matches = regEx.Execute(strng)    ' Execute search.
      RetStr = 0
      For Each Match in Matches             ' Iterate Matches collection.
        RetStr = 1  
      Next
    	
      RegExpTest = RetStr                   'Return back the result 0 or 1

    End Function

'***********************************************************************************
' 
' Routine Name:
'
'   CheckFilePresent
' 
' Description :
'    
'   This routine checks if that particular file exists or not.
'
' Inputs:
'   
'   File to be checked for.
'
' Outputs:
' 
'   None.
'***********************************************************************************
    Sub CheckFilePresent(strFileName)

      If Not objFSO.FileExists(strFileName) Then
        strMessage1 = DisplayMessage(conLABEL_CODE106)
        strMessage = strFileName &" "& strMessage1
        WScript.Echo
        WScript.Echo strMessage
        WScript.Echo
        WScript.Quit(1)
      End If
      
    End Sub
  
'***********************************************************************************
' 
' Routine Name:
'
'   CheckError
' 
' Description :
'    
'   This routine is used for error handling purpose.
'
' Inputs:
'   
'   1. Line number where error is checked for.
'   2. Error Number 
'   3. Error Description. 
'
' Outputs:
' 
'   None.
'***********************************************************************************
    Sub CheckError(Loc,ErrNum,ErrDesc)

      If ErrNum <> 0 then
        strMessage1 = DisplayMessage(conLABEL_CODE107)
        strMessage3 = DisplayMessage(conLABEL_CODE108)
        strMessage = strMessage1 &" "& Loc &" "&strMessage3 &" "& CStr(ErrNum) & _
          ", " & ErrDesc
        WScript.Echo
        WScript.Echo strMessage
        WScript.Echo
        WScript.Quit(1)
      End If
      
    End Sub

'***********************************************************************************
' 
' Routine Name:
'
'   ReadSubKeysFromPath
' 
' Description :
'    
'   This routine enumerates and reads the SCE registry subkeys
'
' Inputs:
'   
'   String containing Registry Key path. 
'
' Outputs:
' 
'   None.
'***********************************************************************************
    Sub ReadSubKeysFromPath(RegKeyPath)

      Dim arrSubKeys, intCount
      objReg.EnumKey HKLM, RegKeyPath, arrSubKeys

      intCount = 0	
      For Each subkey In arrSubKeys
        SubKeysArray(intCount)=RegKeyPath & "\" & subkey    
        intCount = intCount + 1
      Next
      strMessage1 = DisplayMessage(conLABEL_CODE217)
      Wscript.Echo strMessage1
      strMessage1 = DisplayMessage(conLABEL_CODE207)
      Wscript.Echo intCount &" "&strMessage1
    End Sub

'***********************************************************************************
' 
' Routine Name:
'
'   DeleteSubKeysFromPath
' 
' Description :
'    
'   This routine deletes the sub keys from the Registry key path.
'
' Inputs:
'   
'   None. 
'
' Outputs:
' 
'   None.
'***********************************************************************************
    Sub DeleteSubKeysFromPath
      
      Dim intResult
      Dim intCount
      intCount = 0
      While (SubKeysArray(intCount) <> "")
        intResult = objReg.DeleteKey(HKLM, SubKeysArray(intCount))    
        If (intResult = 0) And (Err.Number = 0) Then    
        
        Else
         strMessage = DisplayMessage(conLABEL_CODE210)
         strMessage1 = DisplayMessage(conLABEL_CODE211)
         strMessage3 = DisplayMessage(conLABEL_CODE212)
         Wscript.Echo strMessage &" "& SubKeysArray(intCount) &" "&strMessage1& _
           " "&Err.Number&" "&strMessage3&" "& Err.Description
         WScript.Quit(1)
        End If		
        intCount = intCount + 1
      Wend
      
      strMessage1 = DisplayMessage(conLABEL_CODE208)
      Wscript.Echo strMessage1 

      If (strOS = "Win7") or (strOS = "Vista") or (strOS = "WS08R2") or (strOS = "WS08") Then
	    If (strOS = "Win7") or (strOS = "WS08R2") Then
	      Call objShell.run("REG IMPORT sceWin7.reg",0,True)
	    Else
	      Call objShell.run("REG IMPORT sceVista.reg",0,True)
	    End If
        strMessage3 = DisplayMessage(conLABEL_CODE209)
        WScript.Echo strMessage3 
      End If  
      
    End Sub

'***********************************************************************************
' 
' Routine Name:
'
'   ReRegisterSceCli
' 
' Description :
'    
'   This routine re-registers the SceCli.dll after deleting all the sub keys
'
' Inputs:
'
'   None.
'
' Outputs:
' 
'   None.
'***********************************************************************************
    Sub ReRegisterSceCli

      Dim intRegSvrResult
      intRegSvrResult = objShell.Run ("regsvr32 /s Scecli.dll",,1)
      If (intRegSvrResult = 0) And (Err.Number = 0) Then
        strMessage1 = DisplayMessage(conLABEL_CODE008)
        WScript.Echo
        WScript.Echo strMessage1
        WScript.Echo
      Else
        strMessage1 = DisplayMessage(conLABEL_CODE109)
        strMessage3 = DisplayMessage(conLABEL_CODE110)  
        WScript.Echo        
        WScript.Echo strMessage1 &" "& Err.Description &" " & strMessage3 &" " & _
          Err.Number    
      End If
      
    End Sub

'***********************************************************************************
' 
' Routine Name:
'
'   GetRegValLineNos
' 
' Description :
'    
'   This routine will find the line number in the existing sceregvl.inf where 
'   the section [Register Registry Values] ends
'
' Inputs:
'   
'   None.
'
' Outputs:
' 
'   None.
'***********************************************************************************
    Sub GetRegValLineNos

      Dim objInputInfFile, strText, intCounter
    	
      Set objInputInfFile = objFSO.OpenTextFile(strSceOrigFile)
      If Err.Number = 70 Then
        strMessage = DisplayMessage(conLABEL_CODE103)
        strMessage1 = DisplayMessage(conLABEL_CODE105)
        WScript.Echo strMessage &" "& strSceOrigFile & strMessage1
        Wscript.Quit(1)
      Elseif Err.Number <> 0 Then
        CheckError 202,Err.Number,Err.Description
      End If
    	
      intCounter = 0
      Do While Not (objInputInfFile.atEndOfStream)
        intCounter = intCounter + 1
        strText = objInputInfFile.ReadLine  'Read line
    			
        If (RegExpTest(strMSSRegistryPatrn,strText) = 1) Then
          intMSSRegStartLn = intCounter      
        End If

        If intMSSRegStartLn <> 0 and (RegExpTest(strMSSStringPatrn,strText) = 1) _
          Then
          intMSSRegEndLn = intCounter - 1   
          'This is where [Register Registry Values] ends     
        End If
      Loop
      objInputInfFile.Close
      
    End Sub

'***********************************************************************************
' 
' Routine Name:
'
'   UpdatedSCEwithMSSValues
' 
' Description :
'    
'   This routine create a new file sceregvl.inf.txt where it will copy the 
'   contents of your existing sceregvl.inf, sequentially line by line. While
'   parsing through the sceregvl.inf, once it comes across the header 
'   "[Register Registry Values]", it will next open the Values-sceregvl.txt
'   file included with the guide and append its content to sceregvl.inf.txt.
'   When it comes across the mark "[Strings]", it will open the text file
'   Strings-sceregvl.txt included with the guide and append its content 
'   to sceregvl.inf.txt.
'
' Inputs:
'   
'   None.
'
' Outputs:
' 
'   None.
'***********************************************************************************
    Sub UpdateSCEwithMSSValues

      Dim intCounter
      Dim objInputFile, objOutputFile, objRegistryFile, objStringFile
      Dim strText, strText1
    	
      Set objInputFile = objFSO.OpenTextFile(strSceOrigFile) 
      ' C:\windows\inf\sceregvl.inf
      CheckError 262,Err.Number,Err.Description

      Set objOutputFile = objFSO.OpenTextFile(strSceOutFile,ForWriting,True) 
      'objTempFolder\sceregvl.inf.txt
      CheckError 266,Err.Number,Err.Description  

      CheckFilePresent(strMSSRegistryFile)  
      'Check if Values-sceregvl.txt is present
      Set objRegistryFile = objFSO.OpenTextFile(strMSSRegistryFile)
      CheckError 272,Err.Number,Err.Description

      CheckFilePresent(strMSSStringFile)    
      'Check if Strings-sceregvl.txt is present
      Set objStringFile = objFSO.OpenTextFile(strMSSStringFile)
      CheckError 277,Err.Number,Err.Description

      intCounter = 0
      Do While Not (objInputFile.atEndOfStream)
        intCounter = intCounter + 1
        strText = objInputFile.ReadLine     'Read line
        objOutputFile.WriteLine strText     'Write to strSceOutFile
    		
        If (RegExpTest(strMSSRegistryPatrn,strText) = 1) Then
          intRegFlg = 1      
        End If
    		
        If (intRegFlg = 1 and intCounter = intMSSRegEndLn) Then      
          Do While Not (objRegistryFile.atEndofStream)
            strText1 = objRegistryFile.ReadLine
            objOutputFile.WriteLine strText1
          Loop
          intRegFlg = 0
          objOutputFile.WriteLine vbCrlf    'Write a blank line as well
        End If
    			
        If (RegExpTest(strMSSStringPatrn,strText) = 1) Then
          Do while Not (objStringFile.atEndofStream)
            strText1 = objStringFile.ReadLine
            objOutputFile.WriteLine strText1
          Loop
        End If	
      Loop
    	
      objInputFile.Close
      objOutputFile.Close
      objRegistryFile.Close
      objStringFile.Close
      
    End Sub

'***********************************************************************************
' 
' Routine Name:
'
'   CleanupFiles
' 
' Description :
'    
'   This routine deletes sceregvl.inf and then renames the other file 
'   sceregvl.inf.txt to sceregvl.inf.
'
' Inputs:
'   
'   None.
'
' Outputs:
' 
'   None.
'***********************************************************************************
    Sub CleanupFiles

      Dim objF1,objF2
      Set objF2 = objFSO.GetFile(strSceOrigFile)
      CheckError 377,Err.Number,Err.Description

      objF2.Delete                          'Deleting sceregvl.inf
      If Err.Number = 70 Then
        strMessage = DisplayMessage(conLABEL_CODE104)
        strMessage1 = DisplayMessage(conLABEL_CODE105)
        WScript.Echo strMessage &" "& strSceOrigFile & strMessage1
        WScript.Quit(1)
      Elseif Err.Number <> 0 Then
        CheckError 380,Err.Number,Err.Description
      End If
      
      Set objF2 = Nothing

      objFSO.MoveFile strSceOutFile, strScePath
      set objF1 = objFSO.GetFile(strScePath & "sceregvl.inf.txt")
      objF1.Name = "sceregvl.inf"
      CheckError 394,Err.Number,Err.Description
      
      Set objF1 = Nothing
      
    End Sub


    ]]> 
    </script>
  </job>
</package>