<# .DESCRIPTION Скрипт миграции правил сетевого экрана Trust Access в Secret Net Studio. Запускается под пользователем имеющим права администратора на сервере безопасности SNS. Для работы скрипта необходимо, чтобы на домен контроллере и сервере безопасности Secret Net Studio была доступна слжба WinRM. .PARAMETER AuthXMLpath Путь к файлу с конфигурацией Auth.xml из TrustAccess. .PARAMETER SSSNSName Имя или IP адресс сервера безопасности SNS куда импортируются правила. .PARAMETER GroupMappingFile Путь к TXT файлу в котором перечисленно соответствие групп TrustAccess группам в AD. Пример: Taadmins,SNSadmins TAUsers,SNSlUsers TAVIP,SNSHUsers User TrustAccess,SNS Users S .PARAMETER DC Имя или IP адресс домен контроллера используется для поиска групп TrustAccess в AD и перемещения их в SNS. .PARAMETER FallBackGroup Имя группы которая используется для задания в правилах у которых не удалось найти соответствие группы в TrustAccess группе в AD. .PARAMETER RunAs Параметр передаваемый если для доступа к AD и доступу к Серверу Безопасности SNS требуется использовать учетную запись пользователя отличную от текущего. .PARAMETER OnlyCurrentComputer Используется для автономной версии Secret Net Studio, из файла конфигурации TrustAccess загружаются только правила для этого компьютера. .PARAMETER EnableProtectionEveryone Параметр для задания политики "Защита соединений для группы everyone" для всех агентов. .PARAMETER OnlyViewRule Используется для тествого запуска скрипта, импортированные правила не загрузаются на сервер безопасности, а только выводятся на экран. .EXAMPLE Move-RuleFromTAtoAS.ps1 -AuthXMLpath D:\AuthWithUser.xml -SSSNSName lse2016-3.some.local -DC PDC.SOME.LOCAL -FallBackGroup snsadmins -RunAs -OnlyViewRule -GroupMappingFile D:\grouplist.txt В этом примере скрипт запускается на СБ lse2016-3.some.local, группа по-умолчанию snsadmins, для групп Тrust Access которым не удалось найти соответствие в файле соответствия или Active Directory. Правила будут выведены на экран, но не будут загружены на сервер. .EXAMPLE Move-RuleFromTAtoAS.ps1 -AuthXMLpath D:\AuthWithUser.xml -SSSNSName lse2016-3.some.local -OnlyViewRule -GroupMappingFile D:\grouplist.txt В этом примере скрипт запускается на СБ lse2016-3.some.local, указан файл соответствия групп Trust Access группам в Active Directory. Правила будут выведены на экран, но не будут загружены на сервер. .EXAMPLE Move-RuleFromTAtoAS.ps1 -AuthXMLpath D:\AuthWithUser.xml -RunAs -OnlyViewRule -OnlyCurrentComputer Скрипт запускается локально на агенте SNS (локальная версия), будут импортированы правила для этого агента. В локальном режиме игнорируются группы и все првила после импорта будут соостветствовать группе everyone. #> #Requires -Version 2 [CmdletBinding(DefaultParameterSetName = 'Remote')] Param( [Parameter(Mandatory = $True, ParameterSetName = 'Local')] [Parameter(Mandatory = $True, ParameterSetName='Remote')] [ValidateScript( {(Test-Path -Path $_ -Type Leaf)} )] [String]$AuthXMLpath, [Parameter(Mandatory = $false, ParameterSetName = 'Remote')] [String] $SSSNSName = $env:COMPUTERNAME, [Parameter(Mandatory = $false, ParameterSetName = 'Local')] [Parameter(Mandatory = $false, ParameterSetName='Remote')] [ValidateScript( {(Test-Path -Path $_ -Type Leaf)} )] [String] $GroupMappingFile, [Parameter(Mandatory = $false, ParameterSetName = 'Local')] [Parameter(Mandatory = $false, ParameterSetName='Remote')] [String] $DC = ('{0}.{1}' -f (($env:LOGONSERVER).replace('\\','')), $env:USERDNSDOMAIN), [Parameter(Mandatory = $false, ParameterSetName='Remote')] [String] $FallBackGroup = "Everyone", [Parameter(Mandatory = $false, ParameterSetName = 'Local')] [Parameter(Mandatory = $false, ParameterSetName='Remote')] [Switch] $RunAs = $false, [Parameter(Mandatory = $true, ParameterSetName = 'Local')] [Switch] $OnlyCurrentComputer = $false, [Parameter(Mandatory = $false, ParameterSetName = 'Local')] [Parameter(Mandatory = $false, ParameterSetName='Remote')] [Switch] $EnableProtectionEveryone = $false, [Parameter(Mandatory = $false, ParameterSetName = 'Local')] [Parameter(Mandatory = $false, ParameterSetName='Remote')] [Switch] $OnlyViewRule = $false ) BEGIN { Set-StrictMode -Version 2.0 $ErrorActionPreference = 'Stop' [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Management.Automation") #### V A R I A B L E #### ##### SCRIPT ##### New-Variable -Name CREDENTIALS -Scope Script -Value $null -Force New-Variable -Name SSSESSION -Scope Script -Value $null -Force New-Variable -Name DCSESSION -Scope Script -Value $null -Force New-Variable -Name GROUPMAPPING -Scope Script -Value (New-Object System.Collections.Hashtable) -Force New-Variable -Name AUTHXML -Scope Script -Value (New-Object System.Collections.Hashtable) -Force ##### SCRIPT ##### $LogsPath = 'C:\Logs' $LogFile = (Join-Path -Path $LogsPath -ChildPath 'Move-RuleFromTAtoAS.log') $NGFWREGPATH = "HKLM:\SOFTWARE\Security Code\Secret Net Studio\Client\Network Protection" $AUTHSRVREGPATH = "HKLM:\SOFTWARE\Security Code\Secret Net Studio\Server\Authentication Server" $ORDERRAGE = @{ 'network-transport-rules' = 101000 'network-layer-rules' = 100000 'network-transport-with-auth-rules' = 110000 'pipe-rules' = 121000 'smb-folder-rules' = 120000 } $GROUPSNAME = @{ '{00000001-0000-0000-0000-000000000000}' = 'Everyone' '{00000002-0000-0000-0000-000000000000}' = 'Anonymous' '{00000003-0000-0000-0000-000000000000}' = 'Authenticated' '{00000004-0000-0000-0000-000000000000}' = 'Computers' '{00000005-0000-0000-0000-000000000000}' = 'Users' } [String]$ScSrvConfig = $null [String[]]$ScSrvConfigArg = $null $AUTHMODCFGPATH = '\auth-mod-cfg\' $SERVERSPATH = (Join-Path -Path $AUTHMODCFGPATH -ChildPath '\servers\') $AGENTSPATH = (Join-Path -Path $AUTHMODCFGPATH -ChildPath '\agents\') $GROUPSPATH = '\groups\' $USERSPATH = '\users\' $SYSGROUPSPATH = '\system_groups\' $Everyone = 'Everyone' $ACCESSRULESPATH = (Join-Path -Path $AuthModCfgPath -ChildPath '\accessrules\') $ALLPRINCIPAL = 'principal' $PSMODULES = @('ActiveDirectory') $CRYPTOFNNAME = @('Get-PassFromCredential', 'ConvertTo-CredentialsAsEncryptedStringWinthPSK', 'ConvertFrom-CredentialsAsEncryptedStringWinthPSK', 'Get-CredentialBySecretString') $PSK = (-join ((65..90) + (97..122) | Get-Random -Count 5 | ForEach-Object {[char]$_}) ) # Предварительный общий ключ, используется для обмена паролем пользователя. $COMMONFN = @('Trace-Message', 'Trace-VerboseMessage', 'Trace-ErrorMessage') $RemoteGlobalVar = @{ LogFile = $LogFile NGFWREGPATH = $NGFWREGPATH AUTHSRVREGPATH = $AUTHSRVREGPATH } try {[NGFRRule]} catch [Management.Automation.RuntimeException] { $code = @" using System; using System.Collections; using System.Collections.Generic; public enum ON_OFF_STATUS : int { OFF = 0, ON = 1 } public static class ProtocolType { private static readonly Dictionary PotocolNameDict = new Dictionary(); static ProtocolType (){ PotocolNameDict.Add( "1", "ICMP" ); PotocolNameDict.Add( "2", "IGMP" ); PotocolNameDict.Add( "6", "TCP" ); PotocolNameDict.Add( "8", "EGP" ); PotocolNameDict.Add( "17", "UDP" ); PotocolNameDict.Add( "20", "HMP" ); PotocolNameDict.Add( "22", "XNS" ); PotocolNameDict.Add( "27", "RDP" ); PotocolNameDict.Add( "66", "RVD" ); PotocolNameDict.Add( "*", "ALL" ); } public static string GetProtocolType(string propname){ string result; if (PotocolNameDict.TryGetValue(propname, out result)) { return result; } else { return null; } } } public static class SmbService { private static readonly Dictionary ServicesNameDict = new Dictionary(); static SmbService () { ServicesNameDict.Add( "smb-folder", "Shared folders" ); ServicesNameDict.Add( "pipes", "Named pipes" ); } public static string GetService(string propname){ string result; if (ServicesNameDict.TryGetValue(propname, out result)) { return result; } else { return null; } } } public static class GroupsName { private static readonly Dictionary ServicesNameDict = new Dictionary(); static GroupsName() { ServicesNameDict.Add( "{00000001-0000-0000-0000-000000000000}", "Everyone" ); ServicesNameDict.Add( "{00000002-0000-0000-0000-000000000000}", "Anonymous" ); ServicesNameDict.Add( "{00000003-0000-0000-0000-000000000000}", "Authenticated" ); ServicesNameDict.Add( "{00000004-0000-0000-0000-000000000000}", "Computers" ); ServicesNameDict.Add( "{00000005-0000-0000-0000-000000000000}", "Users" ); } public static string GetGroup(string propname){ string result; if (ServicesNameDict.TryGetValue(propname, out result)) { return result; } else { return null; } } } public class NGFWRule { public NGFWRule (Hashtable rule){ this.Status = (ON_OFF_STATUS)Enum.Parse(typeof(ON_OFF_STATUS), (string)(rule["enabled"])); this.Audit = (ON_OFF_STATUS)Enum.Parse(typeof(ON_OFF_STATUS), (string)rule["audit-enabled"]); this.Accesstype = (string)rule["accesstype"]; this.Remoteaddress = (string)rule["remote-addrs"]; } private ON_OFF_STATUS _Status; public ON_OFF_STATUS Status{ get{return _Status;} set {_Status = value;}} private ON_OFF_STATUS _Audit; public ON_OFF_STATUS Audit {get{return _Audit;} set {_Audit = value;}} private string _Accesstype; public string Accesstype {get{return _Accesstype;} set {_Accesstype = value;}} private string _Remoteaddress; public string Remoteaddress {get{return _Remoteaddress;} set {_Remoteaddress = value;}} } public class NGFWNetworkTransportRule : NGFWRule { public NGFWNetworkTransportRule (Hashtable rule) : base(rule){ this.Protocol = ProtocolType.GetProtocolType((string)rule["protocol"]); } private string _Protocol; public string Protocol {get{return _Protocol;} set {_Protocol = value;}} } public class NGFWPipeRule : NGFWRule { public NGFWPipeRule (Hashtable rule) : base(rule){ this.Subject = GroupsName.GetGroup((string)rule["groups"]) + (string)rule["external-subjects"]; this.service = SmbService.GetService((string)rule["service"]); this.accessobject = (string)rule["pipe-name"]; } private string _Subject; public string Subject {get{return _Subject;} set {_Subject = value;}} private string _service; public string service {get{return _service;} set {_service = value;}} private string _accessobject; public string accessobject {get{return _accessobject;} set {_accessobject = value;}} } public class NGFWSMBRule : NGFWRule { public NGFWSMBRule (Hashtable rule) : base(rule){ string resSubj = GroupsName.GetGroup((string)rule["groups"]) + (string)rule["external-subjects"]; this.Subject = resSubj; this.service = SmbService.GetService((string)rule["service"]); this.accessobject = (string)rule["folder-path-mask"]; } private string _Subject; public string Subject {get{return _Subject;} set {_Subject = value;}} private string _service; public string service {get{return _service;} set {_service = value;}} private string _accessobject; public string accessobject {get{return _accessobject;} set {_accessobject = value;}} } public class NGFWNetworkWithAuthRule : NGFWRule { public NGFWNetworkWithAuthRule (Hashtable rule) : base(rule){ this.Direction = (string)rule["rule-direction-type"]; this.Protocol = ProtocolType.GetProtocolType((string)rule["protocol"]); this.Subject = GroupsName.GetGroup((string)rule["groups"]) + (string)rule["external-subjects"]; this.Remoteports = (string)rule["remote-ports"]; this.Localaddress = (string)rule["local-addrs"]; this.Localports = (string)rule["local-ports"]; this.Application = (string)rule["processes-to-include"]; } private string _Direction; public string Direction {get{return _Direction;} set {_Direction = value;}} private string _Protocol; public string Protocol {get{return _Protocol;} set {_Protocol = value;}} private string _Subject; public string Subject {get{return _Subject;} set {_Subject = value;}} private string _Remoteports; public string Remoteports {get{return _Remoteports;} set {_Remoteports = value;}} private string _Localaddress; public string Localaddress {get{return _Localaddress;} set {_Localaddress = value;}} private string _Localports; public string Localports {get{return _Localports;} set {_Localports = value;}} private string _Application; public string Application {get{return _Application;} set {_Application = value;}} } "@ Add-Type -TypeDefinition $code -PassThru -WarningAction SilentlyContinue | Out-Null } #### V A R I A B L E #### [String]$DefaultTemplateName = 'Default' if($RunAs){ $Script:CREDENTIALS = $Host.ui.PromptForCredential("Enter credential", "Please enter your user name and password.", "", "Domain User") } else { $Script:CREDENTIALS = $Host.ui.PromptForCredential("Enter credential", "Please enter current user password.", ($([System.Security.Principal.WindowsIdentity]::GetCurrent().Name)), "Domain User") } } Process { Trap { $LastErr = $Error[0] $Msg =@( $LastErr.Exception.Message $LastErr.Exception.StackTrace ) Trace-ErrorMessage -Msg $Msg Remove-ScriptVariable break } function Trace-Message { [CmdletBinding()] Param( [Parameter(ValueFromPipeline=$true)] [String[]]$Msg = "" ) Begin {[String]$FormattedMsg = $null} Process { $FormattedMsg = ("{0:yyyy}/{0:MM}/{0:dd}-{0:HH}:{0:mm}:{0:ss}: " -f (Get-Date)) + $Msg Write-Verbose -Msg $FormattedMsg if ($null -ne $Script:LogFile) { try { $FormattedMsg | Out-File -FilePath $Script:LogFile -Append -Encoding bigendianunicode -Force } Catch [System.IO.DirectoryNotFoundException] { New-Item -Path (Split-path $Script:LogFile -Parent) -ItemType Directory } } } } function Trace-ErrorMessage { Param( [Parameter(ValueFromPipeline=$true)] [String[]]$Msg = "" ) PROCESS { Trace-Message -Msg $Msg Write-Error -Message ([String]$Msg) } } function Trace-VerboseMessage { Param( [Parameter(ValueFromPipeline=$true)] [String[]]$Msg = "" ) PROCESS { if( $Script:PSBoundParameters.ContainsKey('Verbose') ){ Trace-Message -Msg $Msg } } } function Remove-ScriptVariable { Remove-Variable -Name CREDENTIALS -Scope Script -ErrorAction SilentlyContinue if($Script:SSSESSION){ Remove-PSSession -Session $Script:SSSESSION -ErrorAction SilentlyContinue } Remove-Variable -Name SSSESSION -Scope Script -ErrorAction SilentlyContinue if($Script:DCSESSION){ Remove-PSSession -Session $Script:DCSESSION -ErrorAction SilentlyContinue } Remove-Variable -Name DCSESSION -Scope Script -ErrorAction SilentlyContinue Remove-Variable -Name GROUPMAPPING -Scope Script -ErrorAction SilentlyContinue Remove-Variable -Name AUTHXML -Scope Script -ErrorAction SilentlyContinue } function Invoke-FnRemote { Param( [Parameter(Mandatory=$false)] [String[]]$InitializationScript = $null, [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$FunctionName, [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [System.Management.Automation.Runspaces.PSSession]$PSsession, [Parameter(Mandatory=$false)] [Hashtable[]]$ArgList = $null ) Begin { $StartBlock = 'Param([Hashtable]$param);.{' $sb = $null } Process { if ($null -ne $InitializationScript) { $InitializationScript |ForEach-Object{ $ScriptFunctionName = $_ Trace-VerboseMessage ('Add function: {0}' -f $ScriptFunctionName) try { $sb = [scriptblock]::create( "$sb function $ScriptFunctionName{$((Get-Item ('Function:\{0}' -f $ScriptFunctionName)).ScriptBlock)}`r`n") } Catch [Management.Automation.ItemNotFoundException] { Throw ('Could not find an implementation for function: {0}' -f $ScriptFunctionName) } Catch { Throw $_ } Trace-VerboseMessage ('Result {0}' -f $sb) } } else { Trace-VerboseMessage "No InitializationScript" } } End { $sb = [scriptblock]::create("$StartBlock $sb function $FunctionName{$((Get-Item ('Function:\{0}' -f $FunctionName)).ScriptBlock)} }; $FunctionName @param") $res = Invoke-Command -Session $PSsession -ScriptBlock $sb -ArgumentList $ArgList return $res } } function ConvertTo-Scriptblock { <# .SYNOPSIS Function to Convert a String into a Script Block #> Param( [Parameter(Mandatory = $true, ValueFromPipeline = $true)] [string]$string ) $scriptBlock = [scriptblock]::Create($string) return $scriptBlock } function Get-PassFromCredential { <# .SYNOPSIS Extract user password from credential. #> Param( [Parameter(Mandatory=$True)] [System.Management.Automation.PSCredential]$Credential ) $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Credential.Password) return [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR) } function Invoke-RemoteWithArguments { <# .SYNOPSIS Invoke function on remote server. #> Param( [Parameter(Mandatory=$false)] [Hashtable] $Param, [Parameter(Mandatory=$true)] [String] $InvokeExpression, [Parameter(Mandatory=$false)] [switch] $Force = $false, [Parameter(Mandatory = $false)] [ValidateSet('Global', 'Local', 'Script')] [String] $Scope = 'Local' ) if($Param -ne $null) { $Param.GetEnumerator() |ForEach-Object{ New-Variable -Name $_.Key -Value $_.Value -scope $Scope -Force:$Force } if ($Param['PSBoundParameters']){ $script:PSBoundParameters = $Param['PSBoundParameters'] } } Invoke-Expression $InvokeExpression } function Invoke-FnRemoteCommonWrapper{ <# .SYNOPSIS Wrapper on Invoke-FnRemote function, invoke only functions that meet the requirements verb naming rules Windows Powershell. #> Param( [Parameter(Mandatory=$True)] [ValidateNotNullOrEmpty()] [System.Management.Automation.Runspaces.PSSession] $PSsession, [Parameter(Mandatory=$True)] [String] $InvokeExpression, [Parameter(Mandatory=$False)] [Hashtable] $Parameters = $null, [Parameter(Mandatory=$false)] [String[]] $AdditionalDependencies, [Parameter(Mandatory=$false)] [Switch] $Force = $false ) [String]$InvokeFunction = $InvokeExpression |Select-String -Pattern '(\w+-\w+)(?:\s.+|$)' |ForEach-Object{$_.Matches|ForEach-Object{$_.groups[1].Value}} [String[]]$FunctionDep = Get-DependentFunctions -FunctionName $InvokeFunction if (-not $InvokeFunction) {throw 'Attempting to call a function whose name does not meet the requirements functions verb naming rules Windows PowerShell.'} $res = Invoke-FnRemote -PSSession $PSsession -InitializationScript (@($Script:COMMONFN + $FunctionDep + $AdditionalDependencies + $InvokeFunction)|Select-Object -Unique) -FunctionName 'Invoke-RemoteWithArguments' -ArgList @{ Param = $Parameters InvokeExpression = $InvokeExpression Force = $Force Scope = 'Local' } return $res } function Get-DependentFunctions{ <# .SYNOPSIS Returns the dependencies of a function from its description. #> [OutputType([System.Collections.ArrayList])] Param( [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [String] $functionName ) $fnHelpTemplate = 'RequiredFunction<(?.*?)\>' $DependentFunctions = New-Object System.Collections.ArrayList try { [String[]]$RequiredFunction = (get-help $functionName).alertSet.alert[0].text -split "\n" |Where-Object{$_ -match $fnHelpTemplate } } Catch { Trace-VerboseMessage -Msg 'No function dependency description was found.' return $null } if($RequiredFunction -ne $null){ if($RequiredFunction.Length -le 0) { Trace-VerboseMessage "Function not contains dependent functions or there is no description of them." } else { $DependentFunctions = $RequiredFunction |Select-String -Pattern $fnHelpTemplate -AllMatches |ForEach-Object{$_.Matches|ForEach-Object{$_.Groups['function'].Value}} } } return $DependentFunctions } function Get-NodePropByName { # extract group property [OutputType([Hashtable])] Param( [Parameter(Mandatory=$True)][System.Xml.XmlDocument]$Xml, [Parameter(Mandatory=$True)][String]$Path ) $query = "Nodes/Node[@path='$Path']" $Node = New-Object System.Collections.Hashtable ($xml | Select-Xml -XPath $query) |%{$_.Node.ChildNodes} |ForEach-Object{ $Node.Add($_.name,$_.value) } return $Node } function Get-ChildNodesMapByPath { # External groups from TrustAccess config xml [OutputType([Hashtable])] Param( [Parameter(Mandatory=$True)][System.Xml.XmlDocument]$Xml, [Parameter(Mandatory=$True)][String]$Path ) $query = "Nodes/Node[starts-with(@path,'$Path')][a]" $Nodes = New-Object System.Collections.Hashtable $Path | Trace-Message try { ($xml | Select-Xml -XPath $query) |%{$_.Node.Path} |Where-Object{$_ -ne "$Path"} |ForEach-Object{ $Nodes.Add($_.replace("$Path",'').trim('\'), (Get-NodePropByName -Xml $Xml -Path $_) ) } } Catch{ "Not found ChildNodes from Root Node $Path" | Trace-Message } return $Nodes } function Get-NodesMapByPath { # Extract root node from Auth.xml Param( [Parameter(Mandatory=$True)][System.Xml.XmlDocument]$Xml, [Parameter(Mandatory=$True)][String]$Path ) $Nodes = New-Object System.Collections.Hashtable (Get-RootNodesByPath -Xml $xml -Path $Path) |ForEach-Object{ $Nodes.Add($_, (Get-ChildNodesMapByPath -Xml $Xml -Path $_) ) # может убрать удаление слешей на концах } return $Nodes } function Get-RootNodesByPath { # Extract root node from Auth.xml [OutputType([Hashtable])] Param( [Parameter(Mandatory=$True)][System.Xml.XmlDocument]$Xml, [Parameter(Mandatory=$True)][String]$Path ) $res = @() ($xml | Select-Xml -XPath "Nodes/Node[not(a)][@path='$path']")|ForEach-Object{ $res += $_.Node.Path } return $res } function Get-TAusers { # return users list from Auth.xml rules [OutputType([String[]])] Param( [Parameter(Mandatory=$True)] [ValidateNotNullOrEmpty()] [System.Xml.XmlDocument]$Xml ) $res = @() ($Xml | Select-Xml -XPath "Nodes/Node/a[@name='principals' and @value != '']")|ForEach-Object{ $res += $_.Node.Value } return $res } function Get-GroupNodeByRoot { # group by the first element in hashtable Param( [Parameter(Mandatory=$True)][System.Collections.Hashtable]$Nodes ) $Servers = New-Object System.Collections.Hashtable $Nodes.Clone().GetEnumerator()|Where-Object{$_.key -notmatch '\\'}|ForEach-Object{ $root = $_ $Servers.Add($Root.Key,$Root.Value) $Nodes.GetEnumerator()|Where-Object{$_.key -match "$($root.key)\\*"}|ForEach-Object{ $Servers[$Root.Key].Add($_.key.replace($root.key,''),$_.Value) } } return $Servers } function Get-AuthXmlConfiguration { <# .SYNOPSIS Extracts parameters from the Auth.xml #> [OutputType([Hashtable])] Param( [Parameter(Mandatory=$True)][String]$AuthXMLPath ) $Authxml = New-Object System.Collections.Hashtable $xml = New-Object System.Xml.XmlDocument $xml.Load($AuthXMLPath) $Authxml.add($GROUPSPATH, (Get-TAConfigNode -Xml $xml -Path $GROUPSPATH) ) $Authxml.add($SYSGROUPSPATH, (Get-TAConfigNode -Xml $xml -Path $SYSGROUPSPATH) ) $Authxml.add($SERVERSPATH , (Get-TAConfigNode -Xml $xml -Path $SERVERSPATH) ) $Authxml.add($AGENTSPATH, (Get-TAConfigNode -Xml $xml -Path $AGENTSPATH) ) $Authxml.add($ACCESSRULESPATH, (Get-TAConfigNode -Xml $xml -Path $ACCESSRULESPATH) ) $Authxml.add($USERSPATH, (Get-TAusers -Xml $xml)) return $Authxml } function Get-TAConfigNode { # Extract servers from Auth.xml Param( [Parameter(Mandatory=$True)][System.Xml.XmlDocument]$Xml, [Parameter(Mandatory=$True)][String]$Path ) $AuthModCfg = Get-NodesMapByPath -Xml $xml -Path $Path Get-GroupNodeByRoot -Nodes $AuthModCfg[$Path] } function Get-AuthServerQueryArguments { <# .SYNOPSIS Prepare arguments to execute queries on the SNS Security Server. .NOTES RequiredFunction RequiredFunction #> [CmdletBinding(DefaultParameterSetName = 'Credentials')] Param( [Parameter(Mandatory = $True, ParameterSetName = 'builtinAdmin')] [String]$SettingskstPath = 'C:\Settings.kst', [Parameter(Mandatory = $True, ParameterSetName = 'Credentials')] [ValidateNotNullOrEmpty()] [System.Management.Automation.PSCredential]$Credential ) $ScSrvConfig = (Get-ItemProperty $Script:AUTHSRVREGPATH).ProductInstallPath + 'ScAuthSrvConfig.exe' $Realm = (Get-ItemProperty $Script:AUTHSRVREGPATH).KRBREALM if(-not (Test-Path -Path $ScSrvConfig -PathType Leaf) ){throw 'Not found ScAuthSrvConfig.exe util'} if($PsCmdlet.ParameterSetName -eq 'builtinAdmin'){ Try { $builtinAdmin = (Get-Content $SettingskstPath -ErrorAction Stop)[1] } Catch [Management.Automation.ItemNotFoundException] { Trace-Message -Msg 'Settings.kst file not found!' throw $_ } $ScSrvConfigArg = @('&',"'$ScSrvConfig'", $Realm, '/p', "'$builtinAdmin'") } else { $ScSrvConfigArg = @('&',"'$ScSrvConfig'", $Realm, '/a', "'$($env:USERNAME)'" ,'/p', "'$(Get-PassFromCredential -Credential $Credential)'") } return ($ScSrvConfigArg -join ' ') } function Get-LocalServerQueryArguments { <# .SYNOPSIS Extracts parameters from the Auth.xml #> [OutputType([Hashtable])] Param( [System.Management.Automation.PSCredential]$Credentials ) $ScSrvConfig = (Get-ItemProperty $Script:NGFWREGPATH ).ProductInstallPath + 'ScLocalSrvConfig.exe' if(-not (Test-Path -Path $ScSrvConfig -PathType Leaf) ) {throw 'Not found ScLocalSrvConfig.exe util'} $ScSrvConfigArg = @('&',"'$ScSrvConfig'") return ($ScSrvConfigArg -join ' ') } function Get-PassFromCredential { Param( [Parameter(Mandatory=$True)][System.Management.Automation.PSCredential]$Credentials ) $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Credentials.Password) return [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR) } function Test-AgentsOnSecurityServer { Param( [ValidateNotNullOrEmpty()] [Parameter(Mandatory=$True)] [String[]]$TAagents, [Parameter(Mandatory=$false)] [String[]]$TAagentsFromRule, [ValidateNotNullOrEmpty()] [Parameter(Mandatory=$True)] [String[]]$AuthSrvAgents ) $TAagents = $TAagents |ForEach-Object{$_.ToUpper()} $AuthSrvAgents = $AuthSrvAgents |ForEach-Object{$_.ToUpper()} if ($null -ne $TAagentsFromRule){ $TAagentsFromRule = $TAagentsFromRule |ForEach-Object{$_.ToUpper()} $TAagentsFromRule |Where-Object{$AuthSrvAgents -notcontains $_}|ForEach-Object{ Write-Warning ("Не удалось найти учетную запись компьютера {0} из правила Trust Access в списке агентов Secret Net Studio. При продолжении текущее значение в правиле не будет изменено при импорте." -f $_) -WarningAction Inquire } } if( ($TAagents |Where-Object{$AuthSrvAgents -notcontains $_}) -eq $null ){ Trace-VerboseMessage -Msg "Найдены все агенты из конфигурации TrustAccess на Сервере безопасности Secret Net Studio." } else { throw "Imported accounts from TrustAccess weren’t found in the Security Server" } } function Test-TAUsersFromRulesInAD { <# checking users from the rules in active directory. #> # check fallback group $res = Get-ObjectOnAD -TAGroups $Script:FallBackGroup -DCSession $Script:DCSESSION if ($Script:FallBackGroup -ne $Everyone -and ($null -eq $res -or (($res |Where-Object{$_.ObjectClass -eq 'group'}) -eq $null)) ) {Throw 'Заданная группа по умолчанию отсутствует в AD.'} # users from rules $TAusersFromRule = Get-TAItem -AuthXml $Script:AUTHXML -Path $script:USERSPATH # computers form rules $TApcFromRule = $TAusersFromRule |Where-Object{$_ -match '.+\$@.+'}|ForEach-Object{($_ -split '$')[0]} # Groups TA add up with users from the rules. $TAgoups = ( (Get-TAItem -AuthXml $Script:AUTHXML -Path $script:GROUPSPATH) + ($TAusersFromRule |Where-Object{$_ -notmatch '.+\$@.+'} |ForEach-Object{($_ -split '@')[0]}) |Select-Object -Unique ) $TAgoups = $TAgoups |%{$_.ToUpper()} # Check the groups mapping from the groups mapping file if ($Script:GroupMappingFile){ $GroupMappingFromFile = New-Object System.Collections.Hashtable try { $GMFileContent = Get-Content -Path $Script:GroupMappingFile -ErrorAction Stop } Catch { throw 'Не удалось прочитать файл соответствия групп TrustAccess группам в AD.' } $GMFileContent |ForEach-Object{ $item = $_ -split ',' $GroupMappingFromFile.Add($item[0].toUpper(), $item[1].toUpper()) } # Check group from group mapping file on AD $TAgoups |Where-Object {$GroupMappingFromFile.Keys -contains $_} |Where-Object {$Script:AUTHXML[$SYSGROUPSPATH].Keys -notcontains $_ }|ForEach-Object { $MappedGroup = $GroupMappingFromFile[$_] if(Test-ObjectOnAD -TAGroups $MappedGroup -DCSession $Script:DCSESSION){ Trace-Message -Msg ('User {0} from user mapping file found in Acrive Directory. Trust Access user {1}' -f $MappedGroup, $_) $Script:GROUPMAPPING.Add($_, $MappedGroup) } else { Write-Warning ("Указанное в файле соответствие пользователя или группы TA не найдено в Active Directory. При продолжении текущее значение {0} будет заменено на группу по умолчанию {1}." -f $_, $Script:FallBackGroup) -WarningAction Inquire Trace-Message -Msg ('User {0} from user mapping file not found in Acrive Directory, replace to default user {1}' -f $_, $Script:FallBackGroup) $Script:GROUPMAPPING.Add($_, $Script:FallBackGroup) } } # For users not found from groupmapping file set the fallback group. [String[]]$notMappedUser = $TAgoups |Where-Object {$GroupMappingFromFile.Keys -notcontains $_} if ($notMappedUser.Length -ge 1){ Trace-Message -Msg ("The groups from Trust Access missing in the mapping file are found: `r`n{0}" -f ($notMappedUser -join "`r`n") ) $notMappedUser |ForEach-Object{ if(Test-ObjectOnAD -TAGroups $_ -DCSession $Script:DCSESSION){ Trace-Message -Msg ('User {0} from rule Trust Access found in Acrive Directory.' -f $_) $Script:GROUPMAPPING.Add($_, $_) } else { Write-Warning ("Не удалось найти пользователя или группу в файле соответствия и AD. При продолжении текущее значение {0} будет заменено на группу по умолчанию {1}." -f $_, $Script:FallBackGroup) -WarningAction Inquire Trace-Message -Msg ("Replace user {0} from Trust Access to default user {0}." -f $_, $Script:FallBackGroup) $Script:GROUPMAPPING.Add($_, $Script:FallBackGroup) } } } else { Trace-Message -Msg 'All users found in the user mapping file.' } } else { # not net groupmapping file $TAgoups |ForEach-Object{ if(Test-ObjectOnAD -TAGroups $_ -DCSession $Script:DCSESSION){ Trace-Message -Msg ('User {0} from rule Trust Access found in Acrive Directory.' -f $_) $Script:GROUPMAPPING.Add($_, $_) } else { Write-Warning ("Не удалось найти пользователя или группу Trust Access в Active Directory. При продолжении текущее значение {0} будет заменено на группу по умолчанию {1}." -f $_, $Script:FallBackGroup) -WarningAction Inquire Trace-Message -Msg ("Replace user {0} from Trust Access to default user {0}." -f $_, $Script:FallBackGroup) $Script:GROUPMAPPING.Add($_, $Script:FallBackGroup) } } } } function Test-ObjectOnAD { Param( [ValidateNotNullOrEmpty()] [Parameter(Mandatory=$True, ValueFromPipeline=$true)] [String[]] $TAgroups, [ValidateNotNullOrEmpty()] [Parameter(Mandatory=$True)] [System.Management.Automation.Runspaces.PSSession] $DCSession, [Parameter(Mandatory=$false)] [String] $DC = ($DCSession.ComputerName) ) Process { $TAgroups |ForEach-Object{ $res = Get-ObjectOnAD -TAgroups $_ -DCSession $DCSession -DC $DC return ($null -ne $res) } } } function Get-ObjectOnAD { Param( [ValidateNotNullOrEmpty()] [Parameter(Mandatory=$True, ValueFromPipeline=$true)] [String[]] $TAgroups, [ValidateNotNullOrEmpty()] [Parameter(Mandatory=$True)] [System.Management.Automation.Runspaces.PSSession] $DCSession, [Parameter(Mandatory=$false)] [String] $DC = $DCSession.ComputerName ) Process { $TAgroups |ForEach-Object{ $user = $_ $ErrorActionPreferencePrev = $ErrorActionPreference for ($attempt = 0; $attempt -lt 33; $attempt++ ) { try { $ErrorActionPreference = 'Stop' $res = Invoke-Command -Session $DCSession -ScriptBlock {Get-ADObject -Filter "Name -eq '$($args[0])'" -Server $args[1]} -ArgumentList @($user,$DC) if($null -ne $res){ switch ($res.ObjectClass){ 'user'{ $res = Invoke-Command -Session $DCSession -ScriptBlock {Get-ADUser -Filter "Name -eq '$($args[0])'" -Server $args[1]} -ArgumentList @($user,$DC) } 'computer'{ $res = Invoke-Command -Session $DCSession -ScriptBlock {Get-ADComputer -Filter "Name -eq '$($args[0])'" -Server $args[1]} -ArgumentList @($user,$DC) } 'group' { $res = Invoke-Command -Session $DCSession -ScriptBlock {Get-ADGroup -Filter "Name -eq '$($args[0])'" -Server $args[1]} -ArgumentList @($user,$DC) } default {} } } return $res } Catch [System.Management.Automation.Remoting.PSRemotingTransportException] { $ErrorActionPreference='SilentlyContinue' Trace-VerboseMessage 'Retry invoke command ' Start-Sleep -Seconds 1 } } $ErrorActionPreference = $ErrorActionPreferencePrev throw 'Еrror checking an object in AD.' } } } function Test-isAdmin { <# .SYNOPSIS Checks administrator rights. .EXAMPLE Test-isAdmin -Credentials $PSSession.Runspace.OriginalConnectionInfo.Credential #> Param( [System.Management.Automation.PSCredential]$Credentials = $null ) if($null -ne $Credentials){ $User = New-Object System.Security.Principal.WindowsIdentity($Credentials.UserName) } else { $User = [Security.Principal.WindowsIdentity]::GetCurrent() } if (-not ([Security.Principal.WindowsPrincipal] $User).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { Trace-ErrorMessage -Msg "You do not have Administrator rights to run this script on the Security Server!`nPlease re-run this script as an Administrator or use -RunAs parameter!" return $false } else { return $true } } function Initialize-Requirements { $isAdmin = $false switch ($PsCmdlet.ParameterSetName){ 'Remote'{ } 'Local' { $Script:SSSNSName = $env:COMPUTERNAME } default {} } $Script:AuthXMLpath = (Resolve-Path $Script:AuthXMLpath).Path $Script:AUTHXML = Get-AuthXmlConfiguration -AuthXMLPath $Script:AuthXMLpath $Script:SSsession = Get-SessionByCredentials -ComputerName $Script:SSSNSName -Credential $Script:CREDENTIALS $Script:DCSESSION = Get-SessionByCredentials -ComputerName $Script:DC -Credential $Script:CREDENTIALS Invoke-FnRemote -PSSession $Script:SSsession -FunctionName 'Invoke-RemoteWithArguments' -ArgList @{ Param = $Script:RemoteGlobalVar InvokeExpression = 'Write-Verbose "Set global variable."' Force = $true Scope = 'Global' } Invoke-FnRemote -PSSession $Script:DCSESSION -FunctionName 'Invoke-RemoteWithArguments' -ArgList @{ Param = $Script:RemoteGlobalVar InvokeExpression = 'Write-Verbose "Set global variable."' Force = $true Scope = 'Global' } $isAdmin = Invoke-FnRemoteCommonWrapper -PSsession $Script:SSsession -InvokeExpression 'Test-isAdmin' if(-not $isAdmin){throw 'Для загрузки правил на сервер безопасности требуются права администратора.'} try { Invoke-FnRemoteCommonWrapper -PSsession $Script:DCSESSION -InvokeExpression 'Import-RequiredADmodule -PSmodules $PSmodules' -Parameters @{'PSmodules' = $Script:PSmodules} |Trace-VerboseMessage } Catch [System.IO.FileNotFoundException] { throw 'Не удалось загрузить требуемые модули на контроллере домена.' exit } Catch { throw $_ } } function Import-RequiredADmodule { <# .SYNOPSIS Checking for the presence of necessary modules. #> Param( $PSmodules ) Trace-Message -Msg "Loading the module into the session." $PSmodules |ForEach-Object { if (Get-Module -ListAvailable -Name $_) { Trace-Message -Msg ("{0} module exists." -f $_) } else { Try { Trace-Message -Msg ("Try import module {0}" -f $_) Import-Module -Name $_ } Catch { throw ("Module {0} not exist." -f $_) } } } } function Get-SessionByCredentials { Param( [String]$ComputerName, [System.Management.Automation.PSCredential]$Credential ) Try { $session = New-PSSession -ComputerName $ComputerName -Credential $Credential -ErrorAction Stop } Catch [System.Management.Automation.Remoting.PSRemotingTransportException] { throw ("Операция не может быть выполнена - ошибка доступа к серверу {0}.`r`n{1}" -f $ComputerName, $_) exit } Catch { throw $_ } return $session } function Get-AgentList { Param( [ValidateNotNullOrEmpty()] [Parameter(Mandatory=$True)][String]$ScSrvConfigArg ) [String[]]$output = Invoke-Expression ($ScSrvConfigArg + '/q', '"show computers"') if($LASTEXITCODE -ne 0){ Trace-Message ('Exit code ScAuthSrvConfig: {0}' -f $LASTEXITCODE) Trace-Message ( 'ScSrvConfig error: {0}' -f $output) throw ('ScSrvConfig error:{0}' -f $LASTEXITCODE) } Trace-Message 'Get SNS computers.' $output |Trace-Message if($null -ne $output){ $index = 0 $output |%{$i = 0}{if($_ -like '*computer(s)*'){$index = $i}else{$i++} } $Computers = $output[0..($index -2)]|ForEach-Object{($_ -split '\s+')[0].trim()} } else { throw 'Не удалось получить список агентов Secret Net Studio.' } return $Computers } function Get-TAitem { [OutputType([String[]])] Param( [Parameter(Mandatory=$True)][Hashtable]$AuthXml, [Parameter(Mandatory=$True)][String]$Path ) $TAitem = New-Object System.Collections.ArrayList if($AuthXml[$Path] -is [hashtable]){ $TAitem = $AuthXml[$Path].GetEnumerator()|ForEach-Object{$_.key |Where-Object{$_ -notmatch '/'}} } elseif ($AuthXml[$Path] -is [System.Array]) { $TAitem = $AuthXml[$Path] } return $TAitem } function Get-AuthSrvConfiguration { <# .SYNOPSIS Get configuration from Auth Server. .NOTES RequiredFunction #> Param( [ValidateNotNullOrEmpty()] [Parameter(Mandatory=$True)][String[]]$AgentNameList, [ValidateNotNullOrEmpty()] [Parameter(Mandatory=$True)][String]$ScSrvConfigArg ) $tmpdir = new-item -Path (Join-Path ($env:TEMP) ([System.IO.Path]::GetRandomFileName()) ) -type Directory -ErrorAction Stop $AgentsRules = New-Object System.Collections.Hashtable Trace-Message -Msg "Create temp directory $tmpdir" try{ $AgentNameList |ForEach-Object { $AgentrulesXML = "$($tmpdir.FullName)\$_" Trace-Message -Msg ("Create temp config agent file {0}" -f $AgentrulesXML) Invoke-Expression ( $ScSrvConfigArg + '/q', ('"show raw_configuration /path ""\auth-mod-cfg\servers\{0}\rules"" /file {1} "') -f $_, $AgentrulesXML) |Trace-Message if($LASTEXITCODE -ne 0){ Trace-Message ('Exit code ScAuthSrvConfig: {0}' -f $LASTEXITCODE) throw ('ScSrvConfig error:{0}' -f $LASTEXITCODE) } if(Test-Path -Path $AgentrulesXML -PathType leaf ){ $AgentsRules.Add($_, (Get-XMLbyPath -XmlPath $AgentrulesXML) ) } else { throw 'Временный файл конфигурации агента не найден.' } } } Catch { Remove-item -Path $tmpdir -Recurse throw } Trace-Message -Msg "Remove temp directory $tmpdir" $AgentsRules.Keys |Trace-Message Remove-item -Path $tmpdir -Recurse return $AgentsRules } function Set-TAUsersAsEveryone{ <# Set all users from rule Trust Access as everyone. #> Param( [Hashtable]$AuthXml ) # users from rules $TAusersFromRule = Get-TAItem -AuthXml $Script:AUTHXML -Path $script:USERSPATH # computers from rules $TApcFromRule = $TAusersFromRule |Where-Object{$_ -match '.+\$@.+'}|ForEach-Object{($_ -split '$')[0]} $TAgoups = ( (Get-TAItem -AuthXml $Script:AUTHXML -Path $script:GROUPSPATH) + ($TAusersFromRule |Where-Object{$_ -notmatch '.+\$@.+'} |ForEach-Object{($_ -split '@')[0]}) |Select-Object -Unique ) $TAgoups = $TAgoups|%{$_.ToUpper()} $TAgoups |Where-Object {$Script:AUTHXML[$SYSGROUPSPATH] -notcontains $_}|ForEach-Object { $Script:GROUPMAPPING.Add($_, $Everyone) } $AuthXml[$Script:ACCESSRULESPATH].GetEnumerator()|%{$_.value['groups'] = '1';$_.value['principals'] = ""} } function Set-AuthSrvConfiguration { <# .SYNOPSIS Set configuration from Auth Server. #> Param( [ValidateNotNullOrEmpty()] [Parameter(Mandatory=$True)][Hashtable]$AgentsConfigXML, [ValidateNotNullOrEmpty()] [Parameter(Mandatory=$True)][String]$ScSrvConfigArg ) $tmpdir = new-item -Path (Join-Path ($env:TEMP) ([System.IO.Path]::GetRandomFileName()) ) -type Directory -ErrorAction Stop Trace-Message -Msg "Create temp directory $tmpdir" try{ $AgentsConfigXML.GetEnumerator() |ForEach-Object { $AgentName = $_.Key $AgentrulesXML = "{0}\{1}.xml" -f $tmpdir.FullName, $AgentName Trace-Message -Msg ("Create temp config agent file {0}" -f $AgentrulesXML) $_.Value.Save($AgentrulesXML) Invoke-Expression ( $ScSrvConfigArg + '/q', ('"set raw_configuration {0} "' -f $AgentrulesXML)) |Trace-Message if($LASTEXITCODE -ne 0){ Trace-Message ('Exit code ScAuthSrvConfig: {0}' -f $LASTEXITCODE) throw ('ScSrvConfig error:{0}' -f $LASTEXITCODE) } } } Catch { Trace-Message -Msg "Remove temp directory $tmpdir" Remove-item -Path $tmpdir -Recurse throw $_ } Trace-Message -Msg "Remove temp directory $tmpdir" Remove-item -Path $tmpdir -Recurse } function Set-AuthSrvPolicyConfiguration { <# .SYNOPSIS Set configuration from Auth Server. #> Param( [ValidateNotNullOrEmpty()] [Parameter(Mandatory=$True)][String[]]$Agents, [ValidateNotNullOrEmpty()] [Parameter(Mandatory=$True)][String]$ScSrvConfigArg, [ValidateNotNullOrEmpty()] [Parameter(Mandatory=$True)][Hashtable]$AuthPolicy ) $Agents|%{ $agent = $_ Trace-Message -Msg ("Set policy agent {0}" -f $agent) $AuthPolicy.GetEnumerator() |ForEach-Object { Trace-Message -Msg ("Set auth-policy {0} value {1} for agent {2}" -f $_.Key, $_.Value, $agent) Invoke-Expression ( $ScSrvConfigArg + '/q', ('"set cp {0} /{1} {2}"' -f $agent, $_.Key, $_.Value)) |Trace-Message if($LASTEXITCODE -ne 0){ Trace-Message ('Exit code ScAuthSrvConfig: {0}' -f $LASTEXITCODE) throw ('ScSrvConfig error:{0}' -f $LASTEXITCODE) } } } } function Get-XMLbyPath { Param( [ValidateNotNullOrEmpty()] [Parameter(Mandatory=$True)][String]$XmlPath ) $xml = New-Object System.Xml.XmlDocument Trace-Message -Msg ('Load XML {0}' -f $XmlPath) $xml.Load($XmlPath) return $xml } function Import-TARules { Param( [Hashtable]$AuthXml, [String]$ScSrvConfigArg ) $ImportedRules = New-Object System.Collections.Hashtable $UsedGuid = New-Object System.Collections.ArrayList $AgentsRuleMsgBuff = New-Object System.Collections.Hashtable [String[]]$TAagents = Get-TAitem -AuthXml $Authxml -Path $SCript:AGENTSPATH [Hashtable]$AgentsConfigXML = Invoke-FnRemoteCommonWrapper -PSsession $Script:SSsession -InvokeExpression 'Get-AuthSrvConfiguration -AgentNameList $AgentNameList -ScSrvConfigArg $ScSrvConfigArg' -Parameters @{ ScSrvConfigArg = $ScSrvConfigArg AgentNameList = $TAagents } $TAagents|ForEach-Object{ $agent = $_.ToUpper() $RuleMsgBuff = New-Object System.Collections.Hashtable $AgentsRuleMsgBuff.Add($agent, (New-Object System.Collections.Hashtable)) $RawAgentRules = ($AuthXml[$Script:SERVERSPATH].GetEnumerator()|?{$_.Value.'server-name' -eq $agent}).Value.GetEnumerator()|?{$_.Name -match '\\rules\\*'} $agentRules = New-Object System.Collections.Hashtable $RawAgentRules.GetEnumerator()|ForEach-Object{ $agentrule = $_ $agentrule.Name |Select-String -Pattern '\\rules\\(?.+)\\(?.+)' |ForEach-Object{ $agentRules[$_.Matches[0].Groups['type'].Value] += @{$agentrule.Value['order'] = (($agentrule.Value['ruleid']|Select-string -Pattern '\\auth-mod-cfg\\accessrules\\(?.+)\\').Matches[0].Groups['guid'].Value)} } } $ImportedRules[$agent] += $agentRules $ImportedRules[$agent].GetEnumerator()|ForEach-Object{ $Rule = $null $type = $_.Name $RuleMsgBuff.Add($type, (New-Object System.Collections.ArrayList)) |Out-Null if ($type -eq 'network-layer-rules'){return} # skip network layer rules [bool]$icmpProtectOn = $false [Microsoft.PowerShell.Commands.SelectXmlInfo]$currSNSRuleBlock = $AgentsConfigXML[$agent] | Select-Xml -XPath ("//Node[@path='{0}']" -f $type) if( -not $currSNSRuleBlock){ $xmlElement = $AgentsConfigXML[$agent] | Select-Xml -XPath "//Node[@path='rules']" $xmlElement |%{$_.Node.AppendChild( (New-XmlNode -XmlDoc $AgentsConfigXML[$agent] -Type "Node" -Attribute "path" -AttributeName $type) )} [Microsoft.PowerShell.Commands.SelectXmlInfo]$currSNSRuleBlock = $AgentsConfigXML[$agent] | Select-Xml -XPath ("//Node[@path='{0}']" -f $type) } [Microsoft.PowerShell.Commands.SelectXmlInfo[]]$order = $currSNSRuleBlock |Select-Xml -XPath "Node[not((a[@name='order' and @value >= 101990] and a[@name='order' and @value <= 101995]) and a[not(@name = 'protocol' and @value = '1')])]/a[@name='order']" $icmpRules = ($currSNSRuleBlock |Select-Xml -XPath "Node[(a[@name='order' and @value >= 101990] and a[@name='order' and @value <= 101995]) and a[not(@name = 'protocol' and @value = '1')]]") if ($null -ne $icmpRules){ $icmpProtectOn = $true } if($null -ne $order){ [int]$order = ($order|%{$_.Node.Value} |Measure-Object -Maximum).Maximum + 1 } else { [int]$order = $Script:ORDERRAGE[$type] } [String[]]$UsedGuid = 0 $currSNSRuleBlock |%{$_.Node.ChildNodes} | ForEach-Object{ $rule = $_ $UsedGuid += $_.path } ($ImportedRules[$agent][$type].GetEnumerator() |Sort-Object -Property name) |%{$_.Value} |ForEach-Object{$i = 0}{ $ruleGUID = $_ Trace-VerboseMessage -Msg ('Add rule TA guid:{0}' -f $ruleGUID) if($AuthXml[$ACCESSRULESPATH].$ruleGUID['protocol'] -eq '1' -and ($AuthXml[$ACCESSRULESPATH].$ruleGUID['hidden-rule'] -eq '1')){ # определяю системные правила Icmp if($icmpProtectOn){ Trace-VerboseMessage -Msg 'ICMP rules already exist for this agent on the Auth Server, removed rule from the imported.' $ImportedRules[$agent][$type].Remove( ($ImportedRules[$agent][$type].GetEnumerator()|?{$_.Value -eq $ruleGUID}).Key ) $AuthXml[$ACCESSRULESPATH].Remove($ruleGUID) return } else { $AuthXml[$ACCESSRULESPATH].$ruleGUID['create-auth-rule'] = "0" $AuthXml[$ACCESSRULESPATH].$ruleGUID['flags'] = "1" $order += 990 } } else { $AuthXml[$ACCESSRULESPATH].$ruleGUID['create-auth-rule'] = "1" $AuthXml[$ACCESSRULESPATH].$ruleGUID['flags'] = "0" } $AuthXml[$ACCESSRULESPATH].$ruleGUID['order'] = ($order + $i) $AuthXml[$ACCESSRULESPATH].$ruleGUID['owner'] = $agent switch -regex ($AuthXml[$ACCESSRULESPATH].$ruleGUID['groups']) { # replacing groups in a rule '^\d{1}$' { $gNum = $AuthXml[$ACCESSRULESPATH].$ruleGUID['groups'] $AuthXml[$ACCESSRULESPATH].$ruleGUID['groups'] = "" Trace-VerboseMessage -Msg ('System group in the rule: {0}' -f $gNum) $AuthXml[$ACCESSRULESPATH].$ruleGUID['groups'] = '{0000000#-0000-0000-0000-000000000000}'.Replace('#', $gNum) } '^\d{4}$' { $gNum = $AuthXml[$ACCESSRULESPATH].$ruleGUID['groups'] $AuthXml[$ACCESSRULESPATH].$ruleGUID['groups'] = "" $ADgroup = $Script:GROUPMAPPING[(($AuthXml[$script:GROUPSPATH].GetEnumerator()|?{$_.Value['SID'] -eq $gNum}).Name).toUpper()] if($ADgroup -eq $Everyone) { $AuthXml[$ACCESSRULESPATH].$ruleGUID['groups'] = ($Script:GROUPSNAME.GetEnumerator()|?{$_.Value -eq $Everyone}).Name } else { $ADobj = Get-ObjectOnAD -TAGroups $ADgroup -DCSession $Script:DCSESSION |Where-Object{$_.ObjectClass -eq 'group'} if($null -eq $ADobj){throw ('Не удалось найти группу {0} в Active Directory.' -f $ADgroup)} $sid = $ADobj.SID Trace-VerboseMessage -Msg ('External group in the rule sid: {0} SID AD: {1}' -f $gNum, $sid) $AuthXml[$ACCESSRULESPATH].$ruleGUID['external-subjects'] = $sid } } ''{ Trace-VerboseMessage -Msg ('No goups') } Default { throw "Unexpected group id." } } switch -regex ($AuthXml[$ACCESSRULESPATH].$ruleGUID['principals']) { # Replacing users and computer accounts in a rule '' { Trace-VerboseMessage -Msg 'No principal in the rule.' } '(.+)\$@.+' { $AuthXml[$ACCESSRULESPATH].$ruleGUID['principals'] = "" $pc = $matches[1].toUpper() $ADobj = (Get-ObjectOnAD -TAGroups $pc -DCSession $Script:DCSESSION |Where-Object{$_.ObjectClass -eq 'computer'}) if($null -eq $ADobj){throw ('Не удалось найти компьютер {0} в Active Directory.' -f $pc)} $pcSID = $ADobj.SID Trace-VerboseMessage -Msg ('Computer account in the rule. SID:{0}' -f $pcSID) $AuthXml[$ACCESSRULESPATH].$ruleGUID['external-subjects'] = $pcSID } '(.[^\$]+)@.+' { $AuthXml[$ACCESSRULESPATH].$ruleGUID['principals'] = "" $ADuser = $Script:GROUPMAPPING[($matches[1].toUpper())] if($ADuser -eq $Everyone) { $AuthXml[$ACCESSRULESPATH].$ruleGUID['groups'] = ($Script:GROUPSNAME.GetEnumerator()|?{$_.Value -eq $Everyone}).Name } else { $ADobj = Get-ObjectOnAD -TAGroups $ADuser -DCSession $Script:DCSESSION if($null -eq $ADobj){throw ('Не удалось найти пользователя {0} в Active Directory.' -f $ADuser)} $userSID = $ADobj.SID Trace-VerboseMessage -Msg ('User account in the rule. SID:{0}' -f $userSID) $AuthXml[$ACCESSRULESPATH].$ruleGUID['external-subjects'] = $userSID } } Default {} } Set-RuleNode -Xml $AgentsConfigXML[$agent] -TARule $AuthXml[$ACCESSRULESPATH].$ruleGUID -result ([ref]$Rule) -Type $type -UsedGuid $UsedGuid $i++ $currSNSRuleBlock |%{$_.Node.AppendChild($Rule)} |Out-Null } if ($Script:OnlyViewRule){ ($ImportedRules[$agent][$type].GetEnumerator() |Sort-Object -Property name) |%{$_.Value} |ForEach-Object{ $RuleMsgBuff[$type].Add((Get-ngfwrule -TARule $AuthXml[$ACCESSRULESPATH].$_ -Type $type)) |Out-Null } } } $AgentsRuleMsgBuff[$agent] += $RuleMsgBuff } if ($Script:OnlyViewRule) { Trace-Message ('На на сервер безопастности Secret Net Studio {0} будут импортированы следующие правила:' -f $Script:SSsession.ComputerName ) $AgentsRuleMsgBuff.GetEnumerator()|ForEach-Object{ ('Add rule for agent:{0}' -f $_.key) $_.Value.GetEnumerator()|ForEach-Object{ ('Type:{0}' -f $_.key) ('Count:{0}' -f $_.Value.Count) $_.Value |Format-Table * -AutoSize |Out-String } } } else { Trace-Message -Msg 'Set configuration.' Invoke-FnRemoteCommonWrapper -PSsession $Script:SSsession -InvokeExpression 'Set-AuthSrvConfiguration -AgentsConfigXML $AgentsConfigXML -ScSrvConfigArg $ScSrvConfigArg' -Parameters @{ ScSrvConfigArg = $ScSrvConfigArg AgentsConfigXML = $AgentsConfigXML } if($EnableProtectionEveryone){ Trace-Message -Msg 'Set everyone policy.' Invoke-FnRemoteCommonWrapper -PSsession $Script:SSsession -InvokeExpression 'Set-AuthSrvPolicyConfiguration -Agents $Agents -AuthPolicy $AuthPolicy -ScSrvConfigArg $ScSrvConfigArg' -Parameters @{ ScSrvConfigArg = $ScSrvConfigArg Agents = $AgentsConfigXML.Keys AuthPolicy = @{ 'auth_rule_gen_skip_everyone' = 0 } } } } } function Get-ngfwrule { Param( [hashtable]$TARule, [String]$type ) switch ($type) { 'network-transport-with-auth-rules' { New-Object -TypeName NGFWNetworkWithAuthRule($TARule) } 'network-transport-rules' { New-Object -TypeName NGFWNetworkTransportRule($TArule) } 'smb-folder-rules'{ New-Object -TypeName NGFWSMBRule($TArule) } 'pipe-rules' { New-Object -TypeName NGFWPipeRule($TArule) } Default {throw ('Тип правил {0} не существует.' -f $type) } } } function CreateRuleNode{ Param( [Parameter(Mandatory=$True)] [System.Xml.XmlDocument]$XmlDoc, [String]$Name, [String]$Value ) $Field = New-XmlNode -XmlDoc $XmlDoc -Type "a" -Attribute "name" -AttributeName $Name -AttributeValue $Value return $Field } function New-XmlNode { Param( [Parameter(Mandatory=$True)] [System.Xml.XmlDocument]$XmlDoc, [Parameter(Mandatory=$True)] [String]$Type, [Parameter(Mandatory=$True)] [String]$Attribute, [Parameter(Mandatory=$True)] [String]$AttributeName, [Parameter(Mandatory=$false)] [String]$AttributeValue ) $Field = $XmlDoc.CreateElement($type) $Field.SetAttribute($Attribute, $AttributeName) $Field.SetAttribute("value",$AttributeValue) return $Field } function Set-RuleNode { Param( [Parameter(Mandatory=$True)][System.Xml.XmlDocument]$Xml, [Parameter(Mandatory=$True)][hashtable]$TARule, [Parameter(Mandatory=$True)][String[]]$UsedGuid, [Parameter(Mandatory=$True)][String]$Type, [Parameter(Mandatory=$True)][ref]$result ) $Rule = $xml.CreateElement("Node") do { $guid = "{$([guid]::NewGuid().guid)}" } while($UsedGuid -icontains $guid) $Rule.SetAttribute("path", $guid) switch ($Type) { 'network-layer-rules' { Set-NetworkLayerRuleNode -Rule $Rule -TArule $TArule } 'network-transport-with-auth-rules' { Set-TransportWithAuthRuleNode -Rule $Rule -TArule $TArule } 'network-transport-rules' { Set-TransportRuleNode -Rule $Rule -TArule $TArule } 'smb-folder-rules'{ Set-SmbRuleNode -Rule $Rule -TArule $TArule } 'pipe-rules' { Set-PipeRuleNode -Rule $Rule -TArule $TArule } Default {throw ('Тип правил {0} не существует.' -f $Type) } } $result.Value = $rule } function Set-TransportWithAuthRuleNode { Param( [System.Xml.XmlElement]$Rule, [hashtable]$TArule ) $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "order" -Value ("{0}" -f $TArule["order"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "enabled" -Value ("{0}" -f $TArule["enabled"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "ruletype" -Value ("{0}" -f $TArule["ruletype"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "service" -Value ("{0}" -f $TArule["service"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "accesstype" -Value ("{0}" -f $TArule["accesstype"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "audit-enabled" -Value ("{0}" -f $TArule["audit-enabled"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "local-ports" -Value ("{0}" -f $TArule["local-ports"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "remote-ports" -Value ("{0}" -f $TArule["remote-ports"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "protocol" -Value ("{0}" -f $TArule["protocol"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "local-addrs" -Value ("{0}" -f $TArule["local-addrs"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "remote-addrs" -Value ("{0}" -f $TArule["remote-addrs"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "rule-direction-type" -Value ("{0}" -f $TArule["rule-direction-type"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "flags" -Value ("{0}" -f $TArule["flags"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "groups" -Value ("{0}" -f $TArule["groups"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "create-auth-rule" -Value ("{0}" -f $TArule["create-auth-rule"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "owner" -Value ("{0}" -f $TArule["owner"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "description" -Value "" )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "guid" -Value "" )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "rule-activate-times" -Value ("{0}" -f $TArule["rule-activate-times"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd" -Value ("{0}" -f $TArule["on-rule-action-cmd"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd-folder" -Value "" )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd-start-type" -Value "system" )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd-token-type" -Value "user" )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd-beep" -Value ("{0}" -f $TArule["on-rule-action-cmd-beep"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "accessmask" -Value ("{0}" -f $TArule["accessmask"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "reply-on-reject" -Value ("{0}" -f $TArule["reply-on-reject"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "adapters-to-include" -Value ("{0}" -f $TArule["adapters-to-include"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "adapters-to-exclude" -Value ("{0}" -f $TArule["adapters-to-exclude"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "adapters-match" -Value ("{0}" -f $TArule["adapters-match"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "rule-activate-regexp" -Value ("{0}" -f $TArule["rule-activate-regexp"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "principals" -Value ("{0}" -f $TArule["principals"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "external-subjects" -Value ("{0}" -f $TArule["external-subjects"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "restricted-process-sids" -Value "" )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "is-emergency-rule" -Value ("{0}" -f $TArule["is-emergency-rule"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "network-level" -Value ("{0}" -f $TArule["network-level"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "rule-scope" -Value ("{0}" -f $TArule["rule-scope"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "out-channel-protection-enabled" -Value ("{0}" -f $TArule["out-channel-protection-enabled"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "processes-to-include" -Value ("{0}" -f $TArule["processes-to-include"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "processes-to-exclude" -Value ("{0}" -f $TArule["processes-to-exclude"]) )) |Out-Null } function Set-TransportRuleNode { Param( [System.Xml.XmlElement]$Rule, [hashtable]$TArule ) $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "order" -Value ("{0}" -f $TArule["order"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "enabled" -Value ("{0}" -f $TArule["enabled"]) )) |Out-Null |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "ruletype" -Value ("{0}" -f $TArule["ruletype"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "service" -Value ("{0}" -f $TArule["service"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "accesstype" -Value ("{0}" -f $TArule["accesstype"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "audit-enabled" -Value ("{0}" -f $TArule["audit-enabled"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "local-ports" -Value "" )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "remote-ports" -Value "" )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "protocol" -Value ("{0}" -f $TArule["protocol"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "local-addrs" -Value ("{0}" -f $TArule["local-addrs"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "remote-addrs" -Value ("{0}" -f $TArule["remote-addrs"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "rule-direction-type" -Value ("{0}" -f $TArule["rule-direction-type"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "flags" -Value ("{0}" -f $TArule["flags"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "rule-condition" -Value ("{0}" -f $TArule["rule-condition"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "description" -Value "" )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "create-auth-rule" -Value ("{0}" -f $TArule["create-auth-rule"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "guid" -Value "" )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "owner" -Value ("{0}" -f $TArule["owner"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "rule-activate-times" -Value ("{0}" -f $TArule["rule-activate-times"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd" -Value ("{0}" -f $TArule["on-rule-action-cmd"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd-folder" -Value "" )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd-start-type" -Value "system" )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd-token-type" -Value "user" )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd-beep" -Value ("{0}" -f $TArule["on-rule-action-cmd-beep"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "accessmask" -Value ("{0}" -f $TArule["accessmask"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "reply-on-reject" -Value ("{0}" -f $TArule["reply-on-reject"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "adapters-to-include" -Value ("{0}" -f $TArule["adapters-to-include"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "adapters-to-exclude" -Value ("{0}" -f $TArule["adapters-to-exclude"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "adapters-match" -Value ("{0}" -f $TArule["adapters-match"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "rule-activate-regexp" -Value ("{0}" -f $TArule["rule-activate-regexp"]) )) |Out-Null } function Set-NetworkLayerRuleNode { Param( [System.Xml.XmlElement]$Rule, [hashtable]$TArule ) $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "order" -Value ("{0}" -f $TArule["order"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "enabled" -Value ("{0}" -f $TArule["enabled"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "ruletype" -Value ("{0}" -f $TArule["ruletype"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "service" -Value ("{0}" -f $TArule["service"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "accesstype" -Value ("{0}" -f $TArule["accesstype"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "audit-enabled" -Value ("{0}" -f $TArule["audit-enabled"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "datalink-protocol" -Value ("{0}" -f $TArule["datalink-protocol"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "network-protocol" -Value ("{0}" -f $TArule["network-protocol"]) )) |Out-Null } function Set-PipeRuleNode { Param( [System.Xml.XmlElement]$Rule, [hashtable]$TArule ) $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "order" -Value ("{0}" -f $TArule["order"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "enabled" -Value ("{0}" -f $TArule["enabled"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "ruletype" -Value ("{0}" -f $TArule["ruletype"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "service" -Value ("{0}" -f $TArule["service"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "accesstype" -Value ("{0}" -f $TArule["accesstype"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "audit-enabled" -Value ("{0}" -f $TArule["audit-enabled"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "local-ports" -Value "*" )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "remote-ports" -Value "*" )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "local-addrs" -Value ("{0}" -f $TArule["local-addrs"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "remote-addrs" -Value ("{0}" -f $TArule["remote-addrs"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "rule-direction-type" -Value "in" )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "flags" -Value ("{0}" -f $TArule["flags"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "description" -Value ("{0}" -f $TArule["description"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "create-auth-rule" -Value "1" )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "guid" -Value "" )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "owner" -Value ("{0}" -f $TArule["owner"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "rule-activate-times" -Value ("{0}" -f $TArule["rule-activate-times"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd" -Value ("{0}" -f $TArule["on-rule-action-cmd"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd-folder" -Value "" )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd-start-type" -Value "system" )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd-token-type" -Value "user" )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd-beep" -Value ("{0}" -f $TArule["on-rule-action-cmd-beep"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "accessmask" -Value ("{0}" -f $TArule["accessmask"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "reply-on-reject" -Value ("{0}" -f $TArule["reply-on-reject"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "adapters-to-include" -Value ("{0}" -f $TArule["adapters-to-include"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "adapters-to-exclude" -Value ("{0}" -f $TArule["adapters-to-exclude"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "adapters-match" -Value ("{0}" -f $TArule["adapters-match"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "groups" -Value ("{0}" -f $TArule["groups"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "principals" -Value ("{0}" -f $TArule["principals"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "external-subjects" -Value ("{0}" -f $TArule["external-subjects"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "restricted-process-sids" -Value "" )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "is-emergency-rule" -Value "0" )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "pipe-name" -Value ("{0}" -f $TArule["pipe-name"]) )) |Out-Null } function Set-SmbRuleNode { Param( [System.Xml.XmlElement]$Rule, [hashtable]$TArule ) $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "order" -Value ("{0}" -f $TArule["order"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "enabled" -Value ("{0}" -f $TArule["enabled"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "ruletype" -Value ("{0}" -f $TArule["ruletype"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "service" -Value ("{0}" -f $TArule["service"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "accesstype" -Value ("{0}" -f $TArule["accesstype"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "audit-enabled" -Value ("{0}" -f $TArule["audit-enabled"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "local-ports" -Value "" )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "remote-ports" -Value "" )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "local-addrs" -Value ("{0}" -f $TArule["local-addrs"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "remote-addrs" -Value ("{0}" -f $TArule["remote-addrs"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "rule-direction-type" -Value "in" )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "flags" -Value ("{0}" -f $TArule["flags"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "description" -Value "" )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "create-auth-rule" -Value "1" )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "guid" -Value "" )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "owner" -Value ("{0}" -f $TArule["owner"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "rule-activate-times" -Value ("{0}" -f $TArule["rule-activate-times"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd" -Value ("{0}" -f $TArule["on-rule-action-cmd"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd-folder" -Value "" )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd-start-type" -Value "system" )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd-token-type" -Value "user" )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd-beep" -Value ("{0}" -f $TArule["on-rule-action-cmd-beep"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "accessmask" -Value ("{0}" -f $TArule["accessmask"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "reply-on-reject" -Value ("{0}" -f $TArule["reply-on-reject"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "adapters-to-include" -Value ("{0}" -f $TArule["adapters-to-include"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "adapters-to-exclude" -Value ("{0}" -f $TArule["adapters-to-exclude"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "adapters-match" -Value ("{0}" -f $TArule["adapters-match"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "groups" -Value ("{0}" -f $TArule["groups"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "principals" -Value ("{0}" -f $TArule["principals"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "external-subjects" -Value ("{0}" -f $TArule["external-subjects"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "restricted-process-sids" -Value "" )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "is-emergency-rule" -Value "0" )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "folder-path-mask" -Value ("{0}" -f $TArule["folder-path-mask"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "include-subfolders" -Value ("{0}" -f $TArule["include-subfolders"]) )) |Out-Null $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "file-name-masks" -Value ("{0}" -f $TArule["file-name-masks"]) )) |Out-Null } Initialize-Requirements if ($PSBoundParameters['OnlyCurrentComputer']) { $Script:ScSrvConfigArg = Get-LocalServerQueryArguments if( (Get-TAItem -AuthXml $Script:AUTHXML -Path $script:AGENTSPATH|?{$_.ToUpper() -eq $env:COMPUTERNAME}) -ne $null){ $item = $AUTHXML[$AGENTSPATH].GetEnumerator()|?{$_.Key -eq $env:COMPUTERNAME} $AUTHXML[$AGENTSPATH] = @{$item.Key = $item.Value} Set-TAUsersAsEveryone -AuthXML $AuthXml } else { throw 'Не удалось найти текущее имя компьютера в списке агентов конфигурации Trust Access.' } } else { $Script:ScSrvConfigArg = Invoke-FnRemoteCommonWrapper -PSsession $Script:SSsession -InvokeExpression 'Get-AuthServerQueryArguments -credential $Credential' -Parameters @{ Credential = $Script:CREDENTIALS } $SNSagents = Invoke-FnRemoteCommonWrapper -PSsession $Script:SSsession -InvokeExpression 'Get-AgentList -ScSrvConfigArg $ScSrvConfigArg' -Parameters @{ ScSrvConfigArg = $ScSrvConfigArg } $TApcFromRule = (Get-TAItem -AuthXml $Script:AUTHXML -Path $script:USERSPATH) |Where-Object{$_ -match '.+\$@.+'}|ForEach-Object{($_ -split '\$')[0]} Test-TAUsersFromRulesInAD Test-AgentsOnSecurityServer -TAagents (Get-TAItem -AuthXml $Authxml -Path $script:AGENTSPATH) -AuthSrvAgents $SNSagents -TAagentsFromRule $TApcFromRule } Import-TARules -AuthXML $AuthXml -ScSrvConfigArg $ScSrvConfigArg Trace-message -Msg 'End.' } End { Remove-ScriptVariable }