Move-RuleFromTAtoAS.ps1 87 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626
  1. <#
  2. .DESCRIPTION
  3. Ñêðèïò ìèãðàöèè ïðàâèë ñåòåâîãî ýêðàíà Trust Access â Secret Net Studio. Çàïóñêàåòñÿ ïîä ïîëüçîâàòåëåì èìåþùèì ïðàâà àäìèíèñòðàòîðà íà ñåðâåðå áåçîïàñíîñòè SNS. Äëÿ ðàáîòû ñêðèïòà íåîáõîäèìî, ÷òîáû íà äîìåí êîíòðîëëåðå è ñåðâåðå áåçîïàñíîñòè Secret Net Studio áûëà äîñòóïíà ñëæáà WinRM.
  4. .PARAMETER AuthXMLpath
  5. Ïóòü ê ôàéëó ñ êîíôèãóðàöèåé Auth.xml èç TrustAccess.
  6. .PARAMETER SSSNSName
  7. Èìÿ èëè IP àäðåññ ñåðâåðà áåçîïàñíîñòè SNS êóäà èìïîðòèðóþòñÿ ïðàâèëà.
  8. .PARAMETER GroupMappingFile
  9. Ïóòü ê TXT ôàéëó â êîòîðîì ïåðå÷èñëåííî ñîîòâåòñòâèå ãðóïï TrustAccess ãðóïïàì â AD.
  10. Ïðèìåð:
  11. Taadmins,SNSadmins
  12. TAUsers,SNSlUsers
  13. TAVIP,SNSHUsers
  14. User TrustAccess,SNS Users S
  15. .PARAMETER DC
  16. Èìÿ èëè IP àäðåññ äîìåí êîíòðîëëåðà èñïîëüçóåòñÿ äëÿ ïîèñêà ãðóïï TrustAccess â AD è ïåðåìåùåíèÿ èõ â SNS.
  17. .PARAMETER FallBackGroup
  18. Èìÿ ãðóïïû êîòîðàÿ èñïîëüçóåòñÿ äëÿ çàäàíèÿ â ïðàâèëàõ ó êîòîðûõ íå óäàëîñü íàéòè ñîîòâåòñòâèå ãðóïïû â TrustAccess ãðóïïå â AD.
  19. .PARAMETER RunAs
  20. Ïàðàìåòð ïåðåäàâàåìûé åñëè äëÿ äîñòóïà ê AD è äîñòóïó ê Ñåðâåðó Áåçîïàñíîñòè SNS òðåáóåòñÿ èñïîëüçîâàòü ó÷åòíóþ çàïèñü ïîëüçîâàòåëÿ îòëè÷íóþ îò òåêóùåãî.
  21. .PARAMETER OnlyCurrentComputer
  22. Èñïîëüçóåòñÿ äëÿ àâòîíîìíîé âåðñèè Secret Net Studio, èç ôàéëà êîíôèãóðàöèè TrustAccess çàãðóæàþòñÿ òîëüêî ïðàâèëà äëÿ ýòîãî êîìïüþòåðà.
  23. .PARAMETER EnableProtectionEveryone
  24. Ïàðàìåòð äëÿ çàäàíèÿ ïîëèòèêè "Çàùèòà ñîåäèíåíèé äëÿ ãðóïïû everyone" äëÿ âñåõ àãåíòîâ.
  25. .PARAMETER OnlyViewRule
  26. Èñïîëüçóåòñÿ äëÿ òåñòâîãî çàïóñêà ñêðèïòà, èìïîðòèðîâàííûå ïðàâèëà íå çàãðóçàþòñÿ íà ñåðâåð áåçîïàñíîñòè, à òîëüêî âûâîäÿòñÿ íà ýêðàí.
  27. .EXAMPLE
  28. Move-RuleFromTAtoAS.ps1 -AuthXMLpath D:\AuthWithUser.xml -SSSNSName lse2016-3.some.local -DC PDC.SOME.LOCAL -FallBackGroup snsadmins -RunAs -OnlyViewRule -GroupMappingFile D:\grouplist.txt
  29.  ýòîì ïðèìåðå ñêðèïò çàïóñêàåòñÿ íà ÑÁ lse2016-3.some.local, ãðóïïà ïî-óìîë÷àíèþ snsadmins, äëÿ ãðóïï Òrust Access êîòîðûì íå óäàëîñü íàéòè ñîîòâåòñòâèå â ôàéëå ñîîòâåòñòâèÿ èëè Active Directory. Ïðàâèëà áóäóò âûâåäåíû íà ýêðàí, íî íå áóäóò çàãðóæåíû íà ñåðâåð.
  30. .EXAMPLE
  31. Move-RuleFromTAtoAS.ps1 -AuthXMLpath D:\AuthWithUser.xml -SSSNSName lse2016-3.some.local -OnlyViewRule -GroupMappingFile D:\grouplist.txt
  32. Â ýòîì ïðèìåðå ñêðèïò çàïóñêàåòñÿ íà ÑÁ lse2016-3.some.local, óêàçàí ôàéë ñîîòâåòñòâèÿ ãðóïï Trust Access ãðóïïàì â Active Directory. Ïðàâèëà áóäóò âûâåäåíû íà ýêðàí, íî íå áóäóò çàãðóæåíû íà ñåðâåð.
  33. .EXAMPLE
  34. Move-RuleFromTAtoAS.ps1 -AuthXMLpath D:\AuthWithUser.xml -RunAs -OnlyViewRule -OnlyCurrentComputer
  35. Ñêðèïò çàïóñêàåòñÿ ëîêàëüíî íà àãåíòå SNS (ëîêàëüíàÿ âåðñèÿ), áóäóò èìïîðòèðîâàíû ïðàâèëà äëÿ ýòîãî àãåíòà. Â ëîêàëüíîì ðåæèìå èãíîðèðóþòñÿ ãðóïïû è âñå ïðâèëà ïîñëå èìïîðòà áóäóò ñîîñòâåòñòâîâàòü ãðóïïå everyone.
  36. #>
  37. #Requires -Version 2
  38. [CmdletBinding(DefaultParameterSetName = 'Remote')]
  39. Param(
  40. [Parameter(Mandatory = $True, ParameterSetName = 'Local')]
  41. [Parameter(Mandatory = $True, ParameterSetName='Remote')]
  42. [ValidateScript( {(Test-Path -Path $_ -Type Leaf)} )]
  43. [String]$AuthXMLpath,
  44. [Parameter(Mandatory = $false, ParameterSetName = 'Remote')]
  45. [String] $SSSNSName = $env:COMPUTERNAME,
  46. [Parameter(Mandatory = $false, ParameterSetName = 'Local')]
  47. [Parameter(Mandatory = $false, ParameterSetName='Remote')]
  48. [ValidateScript( {(Test-Path -Path $_ -Type Leaf)} )]
  49. [String] $GroupMappingFile,
  50. [Parameter(Mandatory = $false, ParameterSetName = 'Local')]
  51. [Parameter(Mandatory = $false, ParameterSetName='Remote')]
  52. [String] $DC = ('{0}.{1}' -f (($env:LOGONSERVER).replace('\\','')), $env:USERDNSDOMAIN),
  53. [Parameter(Mandatory = $false, ParameterSetName='Remote')]
  54. [String] $FallBackGroup = "Everyone",
  55. [Parameter(Mandatory = $false, ParameterSetName = 'Local')]
  56. [Parameter(Mandatory = $false, ParameterSetName='Remote')]
  57. [Switch] $RunAs = $false,
  58. [Parameter(Mandatory = $true, ParameterSetName = 'Local')]
  59. [Switch] $OnlyCurrentComputer = $false,
  60. [Parameter(Mandatory = $false, ParameterSetName = 'Local')]
  61. [Parameter(Mandatory = $false, ParameterSetName='Remote')]
  62. [Switch] $EnableProtectionEveryone = $false,
  63. [Parameter(Mandatory = $false, ParameterSetName = 'Local')]
  64. [Parameter(Mandatory = $false, ParameterSetName='Remote')]
  65. [Switch] $OnlyViewRule = $false
  66. )
  67. BEGIN {
  68. Set-StrictMode -Version 2.0
  69. $ErrorActionPreference = 'Stop'
  70. [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Management.Automation")
  71. #### V A R I A B L E ####
  72. ##### SCRIPT #####
  73. New-Variable -Name CREDENTIALS -Scope Script -Value $null -Force
  74. New-Variable -Name SSSESSION -Scope Script -Value $null -Force
  75. New-Variable -Name DCSESSION -Scope Script -Value $null -Force
  76. New-Variable -Name GROUPMAPPING -Scope Script -Value (New-Object System.Collections.Hashtable) -Force
  77. New-Variable -Name AUTHXML -Scope Script -Value (New-Object System.Collections.Hashtable) -Force
  78. ##### SCRIPT #####
  79. $LogsPath = 'C:\Logs'
  80. $LogFile = (Join-Path -Path $LogsPath -ChildPath 'Move-RuleFromTAtoAS.log')
  81. $NGFWREGPATH = "HKLM:\SOFTWARE\Security Code\Secret Net Studio\Client\Network Protection"
  82. $AUTHSRVREGPATH = "HKLM:\SOFTWARE\Security Code\Secret Net Studio\Server\Authentication Server"
  83. $ORDERRAGE = @{
  84. 'network-transport-rules' = 101000
  85. 'network-layer-rules' = 100000
  86. 'network-transport-with-auth-rules' = 110000
  87. 'pipe-rules' = 121000
  88. 'smb-folder-rules' = 120000
  89. }
  90. $GROUPSNAME = @{
  91. '{00000001-0000-0000-0000-000000000000}' = 'Everyone'
  92. '{00000002-0000-0000-0000-000000000000}' = 'Anonymous'
  93. '{00000003-0000-0000-0000-000000000000}' = 'Authenticated'
  94. '{00000004-0000-0000-0000-000000000000}' = 'Computers'
  95. '{00000005-0000-0000-0000-000000000000}' = 'Users'
  96. }
  97. [String]$ScSrvConfig = $null
  98. [String[]]$ScSrvConfigArg = $null
  99. $AUTHMODCFGPATH = '\auth-mod-cfg\'
  100. $SERVERSPATH = (Join-Path -Path $AUTHMODCFGPATH -ChildPath '\servers\')
  101. $AGENTSPATH = (Join-Path -Path $AUTHMODCFGPATH -ChildPath '\agents\')
  102. $GROUPSPATH = '\groups\'
  103. $USERSPATH = '\users\'
  104. $SYSGROUPSPATH = '\system_groups\'
  105. $Everyone = 'Everyone'
  106. $ACCESSRULESPATH = (Join-Path -Path $AuthModCfgPath -ChildPath '\accessrules\')
  107. $ALLPRINCIPAL = 'principal'
  108. $PSMODULES = @('ActiveDirectory')
  109. $CRYPTOFNNAME = @('Get-PassFromCredential', 'ConvertTo-CredentialsAsEncryptedStringWinthPSK', 'ConvertFrom-CredentialsAsEncryptedStringWinthPSK', 'Get-CredentialBySecretString')
  110. $PSK = (-join ((65..90) + (97..122) | Get-Random -Count 5 | ForEach-Object {[char]$_}) ) # Ïðåäâàðèòåëüíûé îáùèé êëþ÷, èñïîëüçóåòñÿ äëÿ îáìåíà ïàðîëåì ïîëüçîâàòåëÿ.
  111. $COMMONFN = @('Trace-Message', 'Trace-VerboseMessage', 'Trace-ErrorMessage')
  112. $RemoteGlobalVar = @{
  113. LogFile = $LogFile
  114. NGFWREGPATH = $NGFWREGPATH
  115. AUTHSRVREGPATH = $AUTHSRVREGPATH
  116. }
  117. try {[NGFRRule]} catch [Management.Automation.RuntimeException] {
  118. $code = @"
  119. using System;
  120. using System.Collections;
  121. using System.Collections.Generic;
  122. public enum ON_OFF_STATUS : int {
  123. OFF = 0,
  124. ON = 1
  125. }
  126. public static class ProtocolType {
  127. private static readonly Dictionary<string, string> PotocolNameDict = new Dictionary<string, string>();
  128. static ProtocolType (){
  129. PotocolNameDict.Add( "1", "ICMP" );
  130. PotocolNameDict.Add( "2", "IGMP" );
  131. PotocolNameDict.Add( "6", "TCP" );
  132. PotocolNameDict.Add( "8", "EGP" );
  133. PotocolNameDict.Add( "17", "UDP" );
  134. PotocolNameDict.Add( "20", "HMP" );
  135. PotocolNameDict.Add( "22", "XNS" );
  136. PotocolNameDict.Add( "27", "RDP" );
  137. PotocolNameDict.Add( "66", "RVD" );
  138. PotocolNameDict.Add( "*", "ALL" );
  139. }
  140. public static string GetProtocolType(string propname){
  141. string result;
  142. if (PotocolNameDict.TryGetValue(propname, out result))
  143. {
  144. return result;
  145. }
  146. else
  147. {
  148. return null;
  149. }
  150. }
  151. }
  152. public static class SmbService {
  153. private static readonly Dictionary<string, string> ServicesNameDict = new Dictionary<string, string>();
  154. static SmbService () {
  155. ServicesNameDict.Add( "smb-folder", "Shared folders" );
  156. ServicesNameDict.Add( "pipes", "Named pipes" );
  157. }
  158. public static string GetService(string propname){
  159. string result;
  160. if (ServicesNameDict.TryGetValue(propname, out result))
  161. {
  162. return result;
  163. }
  164. else
  165. {
  166. return null;
  167. }
  168. }
  169. }
  170. public static class GroupsName {
  171. private static readonly Dictionary<string, string> ServicesNameDict = new Dictionary<string, string>();
  172. static GroupsName() {
  173. ServicesNameDict.Add( "{00000001-0000-0000-0000-000000000000}", "Everyone" );
  174. ServicesNameDict.Add( "{00000002-0000-0000-0000-000000000000}", "Anonymous" );
  175. ServicesNameDict.Add( "{00000003-0000-0000-0000-000000000000}", "Authenticated" );
  176. ServicesNameDict.Add( "{00000004-0000-0000-0000-000000000000}", "Computers" );
  177. ServicesNameDict.Add( "{00000005-0000-0000-0000-000000000000}", "Users" );
  178. }
  179. public static string GetGroup(string propname){
  180. string result;
  181. if (ServicesNameDict.TryGetValue(propname, out result))
  182. {
  183. return result;
  184. }
  185. else
  186. {
  187. return null;
  188. }
  189. }
  190. }
  191. public class NGFWRule {
  192. public NGFWRule (Hashtable rule){
  193. this.Status = (ON_OFF_STATUS)Enum.Parse(typeof(ON_OFF_STATUS), (string)(rule["enabled"]));
  194. this.Audit = (ON_OFF_STATUS)Enum.Parse(typeof(ON_OFF_STATUS), (string)rule["audit-enabled"]);
  195. this.Accesstype = (string)rule["accesstype"];
  196. this.Remoteaddress = (string)rule["remote-addrs"];
  197. }
  198. private ON_OFF_STATUS _Status;
  199. public ON_OFF_STATUS Status{ get{return _Status;} set {_Status = value;}}
  200. private ON_OFF_STATUS _Audit;
  201. public ON_OFF_STATUS Audit {get{return _Audit;} set {_Audit = value;}}
  202. private string _Accesstype;
  203. public string Accesstype {get{return _Accesstype;} set {_Accesstype = value;}}
  204. private string _Remoteaddress;
  205. public string Remoteaddress {get{return _Remoteaddress;} set {_Remoteaddress = value;}}
  206. }
  207. public class NGFWNetworkTransportRule : NGFWRule {
  208. public NGFWNetworkTransportRule (Hashtable rule) : base(rule){
  209. this.Protocol = ProtocolType.GetProtocolType((string)rule["protocol"]);
  210. }
  211. private string _Protocol;
  212. public string Protocol {get{return _Protocol;} set {_Protocol = value;}}
  213. }
  214. public class NGFWPipeRule : NGFWRule {
  215. public NGFWPipeRule (Hashtable rule) : base(rule){
  216. this.Subject = GroupsName.GetGroup((string)rule["groups"]) + (string)rule["external-subjects"];
  217. this.service = SmbService.GetService((string)rule["service"]);
  218. this.accessobject = (string)rule["pipe-name"];
  219. }
  220. private string _Subject;
  221. public string Subject {get{return _Subject;} set {_Subject = value;}}
  222. private string _service;
  223. public string service {get{return _service;} set {_service = value;}}
  224. private string _accessobject;
  225. public string accessobject {get{return _accessobject;} set {_accessobject = value;}}
  226. }
  227. public class NGFWSMBRule : NGFWRule {
  228. public NGFWSMBRule (Hashtable rule) : base(rule){
  229. string resSubj = GroupsName.GetGroup((string)rule["groups"]) + (string)rule["external-subjects"];
  230. this.Subject = resSubj;
  231. this.service = SmbService.GetService((string)rule["service"]);
  232. this.accessobject = (string)rule["folder-path-mask"];
  233. }
  234. private string _Subject;
  235. public string Subject {get{return _Subject;} set {_Subject = value;}}
  236. private string _service;
  237. public string service {get{return _service;} set {_service = value;}}
  238. private string _accessobject;
  239. public string accessobject {get{return _accessobject;} set {_accessobject = value;}}
  240. }
  241. public class NGFWNetworkWithAuthRule : NGFWRule {
  242. public NGFWNetworkWithAuthRule (Hashtable rule) : base(rule){
  243. this.Direction = (string)rule["rule-direction-type"];
  244. this.Protocol = ProtocolType.GetProtocolType((string)rule["protocol"]);
  245. this.Subject = GroupsName.GetGroup((string)rule["groups"]) + (string)rule["external-subjects"];
  246. this.Remoteports = (string)rule["remote-ports"];
  247. this.Localaddress = (string)rule["local-addrs"];
  248. this.Localports = (string)rule["local-ports"];
  249. this.Application = (string)rule["processes-to-include"];
  250. }
  251. private string _Direction;
  252. public string Direction {get{return _Direction;} set {_Direction = value;}}
  253. private string _Protocol;
  254. public string Protocol {get{return _Protocol;} set {_Protocol = value;}}
  255. private string _Subject;
  256. public string Subject {get{return _Subject;} set {_Subject = value;}}
  257. private string _Remoteports;
  258. public string Remoteports {get{return _Remoteports;} set {_Remoteports = value;}}
  259. private string _Localaddress;
  260. public string Localaddress {get{return _Localaddress;} set {_Localaddress = value;}}
  261. private string _Localports;
  262. public string Localports {get{return _Localports;} set {_Localports = value;}}
  263. private string _Application;
  264. public string Application {get{return _Application;} set {_Application = value;}}
  265. }
  266. "@
  267. Add-Type -TypeDefinition $code -PassThru -WarningAction SilentlyContinue | Out-Null
  268. }
  269. #### V A R I A B L E ####
  270. [String]$DefaultTemplateName = 'Default'
  271. if($RunAs){
  272. $Script:CREDENTIALS = $Host.ui.PromptForCredential("Enter credential", "Please enter your user name and password.", "", "Domain User")
  273. } else {
  274. $Script:CREDENTIALS = $Host.ui.PromptForCredential("Enter credential", "Please enter current user password.", ($([System.Security.Principal.WindowsIdentity]::GetCurrent().Name)), "Domain User")
  275. }
  276. }
  277. Process {
  278. Trap {
  279. $LastErr = $Error[0]
  280. $Msg =@(
  281. $LastErr.Exception.Message
  282. $LastErr.Exception.StackTrace
  283. )
  284. Trace-ErrorMessage -Msg $Msg
  285. Remove-ScriptVariable
  286. break
  287. }
  288. function Trace-Message {
  289. [CmdletBinding()]
  290. Param(
  291. [Parameter(ValueFromPipeline=$true)]
  292. [String[]]$Msg = ""
  293. )
  294. Begin {[String]$FormattedMsg = $null}
  295. Process {
  296. $FormattedMsg = ("{0:yyyy}/{0:MM}/{0:dd}-{0:HH}:{0:mm}:{0:ss}: " -f (Get-Date)) + $Msg
  297. Write-Verbose -Msg $FormattedMsg
  298. if ($null -ne $Script:LogFile) {
  299. try {
  300. $FormattedMsg | Out-File -FilePath $Script:LogFile -Append -Encoding bigendianunicode -Force
  301. }
  302. Catch [System.IO.DirectoryNotFoundException] {
  303. New-Item -Path (Split-path $Script:LogFile -Parent) -ItemType Directory
  304. }
  305. }
  306. }
  307. }
  308. function Trace-ErrorMessage {
  309. Param(
  310. [Parameter(ValueFromPipeline=$true)]
  311. [String[]]$Msg = ""
  312. )
  313. PROCESS {
  314. Trace-Message -Msg $Msg
  315. Write-Error -Message ([String]$Msg)
  316. }
  317. }
  318. function Trace-VerboseMessage {
  319. Param(
  320. [Parameter(ValueFromPipeline=$true)]
  321. [String[]]$Msg = ""
  322. )
  323. PROCESS {
  324. if( $Script:PSBoundParameters.ContainsKey('Verbose') ){
  325. Trace-Message -Msg $Msg
  326. }
  327. }
  328. }
  329. function Remove-ScriptVariable {
  330. Remove-Variable -Name CREDENTIALS -Scope Script -ErrorAction SilentlyContinue
  331. if($Script:SSSESSION){
  332. Remove-PSSession -Session $Script:SSSESSION -ErrorAction SilentlyContinue
  333. }
  334. Remove-Variable -Name SSSESSION -Scope Script -ErrorAction SilentlyContinue
  335. if($Script:DCSESSION){
  336. Remove-PSSession -Session $Script:DCSESSION -ErrorAction SilentlyContinue
  337. }
  338. Remove-Variable -Name DCSESSION -Scope Script -ErrorAction SilentlyContinue
  339. Remove-Variable -Name GROUPMAPPING -Scope Script -ErrorAction SilentlyContinue
  340. Remove-Variable -Name AUTHXML -Scope Script -ErrorAction SilentlyContinue
  341. }
  342. function Invoke-FnRemote {
  343. Param(
  344. [Parameter(Mandatory=$false)]
  345. [String[]]$InitializationScript = $null,
  346. [Parameter(Mandatory=$true)]
  347. [ValidateNotNullOrEmpty()]
  348. [String]$FunctionName,
  349. [Parameter(Mandatory=$true)]
  350. [ValidateNotNullOrEmpty()]
  351. [System.Management.Automation.Runspaces.PSSession]$PSsession,
  352. [Parameter(Mandatory=$false)]
  353. [Hashtable[]]$ArgList = $null
  354. )
  355. Begin {
  356. $StartBlock = 'Param([Hashtable]$param);.{'
  357. $sb = $null
  358. }
  359. Process {
  360. if ($null -ne $InitializationScript) {
  361. $InitializationScript |ForEach-Object{
  362. $ScriptFunctionName = $_
  363. Trace-VerboseMessage ('Add function: {0}' -f $ScriptFunctionName)
  364. try {
  365. $sb = [scriptblock]::create( "$sb function $ScriptFunctionName{$((Get-Item ('Function:\{0}' -f $ScriptFunctionName)).ScriptBlock)}`r`n")
  366. }
  367. Catch [Management.Automation.ItemNotFoundException] {
  368. Throw ('Could not find an implementation for function: {0}' -f $ScriptFunctionName)
  369. }
  370. Catch {
  371. Throw $_
  372. }
  373. Trace-VerboseMessage ('Result {0}' -f $sb)
  374. }
  375. } else {
  376. Trace-VerboseMessage "No InitializationScript"
  377. }
  378. }
  379. End {
  380. $sb = [scriptblock]::create("$StartBlock $sb function $FunctionName{$((Get-Item ('Function:\{0}' -f $FunctionName)).ScriptBlock)} }; $FunctionName @param")
  381. $res = Invoke-Command -Session $PSsession -ScriptBlock $sb -ArgumentList $ArgList
  382. return $res
  383. }
  384. }
  385. function ConvertTo-Scriptblock {
  386. <#
  387. .SYNOPSIS
  388. Function to Convert a String into a Script Block
  389. #>
  390. Param(
  391. [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
  392. [string]$string
  393. )
  394. $scriptBlock = [scriptblock]::Create($string)
  395. return $scriptBlock
  396. }
  397. function Get-PassFromCredential {
  398. <#
  399. .SYNOPSIS
  400. Extract user password from credential.
  401. #>
  402. Param(
  403. [Parameter(Mandatory=$True)]
  404. [System.Management.Automation.PSCredential]$Credential
  405. )
  406. $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Credential.Password)
  407. return [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
  408. }
  409. function Invoke-RemoteWithArguments {
  410. <#
  411. .SYNOPSIS
  412. Invoke function on remote server.
  413. #>
  414. Param(
  415. [Parameter(Mandatory=$false)]
  416. [Hashtable] $Param,
  417. [Parameter(Mandatory=$true)]
  418. [String] $InvokeExpression,
  419. [Parameter(Mandatory=$false)]
  420. [switch] $Force = $false,
  421. [Parameter(Mandatory = $false)] [ValidateSet('Global', 'Local', 'Script')]
  422. [String] $Scope = 'Local'
  423. )
  424. if($Param -ne $null) {
  425. $Param.GetEnumerator() |ForEach-Object{
  426. New-Variable -Name $_.Key -Value $_.Value -scope $Scope -Force:$Force
  427. }
  428. if ($Param['PSBoundParameters']){
  429. $script:PSBoundParameters = $Param['PSBoundParameters']
  430. }
  431. }
  432. Invoke-Expression $InvokeExpression
  433. }
  434. function Invoke-FnRemoteCommonWrapper{
  435. <#
  436. .SYNOPSIS
  437. Wrapper on Invoke-FnRemote function, invoke only functions that meet the requirements verb naming rules Windows Powershell.
  438. #>
  439. Param(
  440. [Parameter(Mandatory=$True)]
  441. [ValidateNotNullOrEmpty()]
  442. [System.Management.Automation.Runspaces.PSSession] $PSsession,
  443. [Parameter(Mandatory=$True)]
  444. [String] $InvokeExpression,
  445. [Parameter(Mandatory=$False)]
  446. [Hashtable] $Parameters = $null,
  447. [Parameter(Mandatory=$false)]
  448. [String[]] $AdditionalDependencies,
  449. [Parameter(Mandatory=$false)]
  450. [Switch] $Force = $false
  451. )
  452. [String]$InvokeFunction = $InvokeExpression |Select-String -Pattern '(\w+-\w+)(?:\s.+|$)' |ForEach-Object{$_.Matches|ForEach-Object{$_.groups[1].Value}}
  453. [String[]]$FunctionDep = Get-DependentFunctions -FunctionName $InvokeFunction
  454. if (-not $InvokeFunction) {throw 'Attempting to call a function whose name does not meet the requirements functions verb naming rules Windows PowerShell.'}
  455. $res = Invoke-FnRemote -PSSession $PSsession -InitializationScript (@($Script:COMMONFN + $FunctionDep + $AdditionalDependencies + $InvokeFunction)|Select-Object -Unique) -FunctionName 'Invoke-RemoteWithArguments' -ArgList @{
  456. Param = $Parameters
  457. InvokeExpression = $InvokeExpression
  458. Force = $Force
  459. Scope = 'Local'
  460. }
  461. return $res
  462. }
  463. function Get-DependentFunctions{
  464. <#
  465. .SYNOPSIS
  466. Returns the dependencies of a function from its description.
  467. #>
  468. [OutputType([System.Collections.ArrayList])]
  469. Param(
  470. [Parameter(Mandatory=$true)]
  471. [ValidateNotNullOrEmpty()]
  472. [String] $functionName
  473. )
  474. $fnHelpTemplate = 'RequiredFunction<(?<function>.*?)\>'
  475. $DependentFunctions = New-Object System.Collections.ArrayList
  476. try {
  477. [String[]]$RequiredFunction = (get-help $functionName).alertSet.alert[0].text -split "\n" |Where-Object{$_ -match $fnHelpTemplate }
  478. }
  479. Catch {
  480. Trace-VerboseMessage -Msg 'No function dependency description was found.'
  481. return $null
  482. }
  483. if($RequiredFunction -ne $null){
  484. if($RequiredFunction.Length -le 0) {
  485. Trace-VerboseMessage "Function not contains dependent functions or there is no description of them."
  486. } else {
  487. $DependentFunctions = $RequiredFunction |Select-String -Pattern $fnHelpTemplate -AllMatches |ForEach-Object{$_.Matches|ForEach-Object{$_.Groups['function'].Value}}
  488. }
  489. }
  490. return $DependentFunctions
  491. }
  492. function Get-NodePropByName {
  493. # extract group property
  494. [OutputType([Hashtable])]
  495. Param(
  496. [Parameter(Mandatory=$True)][System.Xml.XmlDocument]$Xml,
  497. [Parameter(Mandatory=$True)][String]$Path
  498. )
  499. $query = "Nodes/Node[@path='$Path']"
  500. $Node = New-Object System.Collections.Hashtable
  501. ($xml | Select-Xml -XPath $query) |%{$_.Node.ChildNodes} |ForEach-Object{
  502. $Node.Add($_.name,$_.value)
  503. }
  504. return $Node
  505. }
  506. function Get-ChildNodesMapByPath {
  507. # External groups from TrustAccess config xml
  508. [OutputType([Hashtable])]
  509. Param(
  510. [Parameter(Mandatory=$True)][System.Xml.XmlDocument]$Xml,
  511. [Parameter(Mandatory=$True)][String]$Path
  512. )
  513. $query = "Nodes/Node[starts-with(@path,'$Path')][a]"
  514. $Nodes = New-Object System.Collections.Hashtable
  515. $Path | Trace-Message
  516. try {
  517. ($xml | Select-Xml -XPath $query) |%{$_.Node.Path} |Where-Object{$_ -ne "$Path"} |ForEach-Object{
  518. $Nodes.Add($_.replace("$Path",'').trim('\'), (Get-NodePropByName -Xml $Xml -Path $_) )
  519. }
  520. }
  521. Catch{
  522. "Not found ChildNodes from Root Node $Path" | Trace-Message
  523. }
  524. return $Nodes
  525. }
  526. function Get-NodesMapByPath {
  527. # Extract root node from Auth.xml
  528. Param(
  529. [Parameter(Mandatory=$True)][System.Xml.XmlDocument]$Xml,
  530. [Parameter(Mandatory=$True)][String]$Path
  531. )
  532. $Nodes = New-Object System.Collections.Hashtable
  533. (Get-RootNodesByPath -Xml $xml -Path $Path) |ForEach-Object{
  534. $Nodes.Add($_, (Get-ChildNodesMapByPath -Xml $Xml -Path $_) ) # ìîæåò óáðàòü óäàëåíèå ñëåøåé íà êîíöàõ
  535. }
  536. return $Nodes
  537. }
  538. function Get-RootNodesByPath {
  539. # Extract root node from Auth.xml
  540. [OutputType([Hashtable])]
  541. Param(
  542. [Parameter(Mandatory=$True)][System.Xml.XmlDocument]$Xml,
  543. [Parameter(Mandatory=$True)][String]$Path
  544. )
  545. $res = @()
  546. ($xml | Select-Xml -XPath "Nodes/Node[not(a)][@path='$path']")|ForEach-Object{
  547. $res += $_.Node.Path
  548. }
  549. return $res
  550. }
  551. function Get-TAusers {
  552. # return users list from Auth.xml rules
  553. [OutputType([String[]])]
  554. Param(
  555. [Parameter(Mandatory=$True)]
  556. [ValidateNotNullOrEmpty()]
  557. [System.Xml.XmlDocument]$Xml
  558. )
  559. $res = @()
  560. ($Xml | Select-Xml -XPath "Nodes/Node/a[@name='principals' and @value != '']")|ForEach-Object{
  561. $res += $_.Node.Value
  562. }
  563. return $res
  564. }
  565. function Get-GroupNodeByRoot {
  566. # group by the first element in hashtable
  567. Param(
  568. [Parameter(Mandatory=$True)][System.Collections.Hashtable]$Nodes
  569. )
  570. $Servers = New-Object System.Collections.Hashtable
  571. $Nodes.Clone().GetEnumerator()|Where-Object{$_.key -notmatch '\\'}|ForEach-Object{
  572. $root = $_
  573. $Servers.Add($Root.Key,$Root.Value)
  574. $Nodes.GetEnumerator()|Where-Object{$_.key -match "$($root.key)\\*"}|ForEach-Object{
  575. $Servers[$Root.Key].Add($_.key.replace($root.key,''),$_.Value)
  576. }
  577. }
  578. return $Servers
  579. }
  580. function Get-AuthXmlConfiguration {
  581. <#
  582. .SYNOPSIS
  583. Extracts parameters from the Auth.xml
  584. #>
  585. [OutputType([Hashtable])]
  586. Param(
  587. [Parameter(Mandatory=$True)][String]$AuthXMLPath
  588. )
  589. $Authxml = New-Object System.Collections.Hashtable
  590. $xml = New-Object System.Xml.XmlDocument
  591. $xml.Load($AuthXMLPath)
  592. $Authxml.add($GROUPSPATH, (Get-TAConfigNode -Xml $xml -Path $GROUPSPATH) )
  593. $Authxml.add($SYSGROUPSPATH, (Get-TAConfigNode -Xml $xml -Path $SYSGROUPSPATH) )
  594. $Authxml.add($SERVERSPATH , (Get-TAConfigNode -Xml $xml -Path $SERVERSPATH) )
  595. $Authxml.add($AGENTSPATH, (Get-TAConfigNode -Xml $xml -Path $AGENTSPATH) )
  596. $Authxml.add($ACCESSRULESPATH, (Get-TAConfigNode -Xml $xml -Path $ACCESSRULESPATH) )
  597. $Authxml.add($USERSPATH, (Get-TAusers -Xml $xml))
  598. return $Authxml
  599. }
  600. function Get-TAConfigNode {
  601. # Extract servers from Auth.xml
  602. Param(
  603. [Parameter(Mandatory=$True)][System.Xml.XmlDocument]$Xml,
  604. [Parameter(Mandatory=$True)][String]$Path
  605. )
  606. $AuthModCfg = Get-NodesMapByPath -Xml $xml -Path $Path
  607. Get-GroupNodeByRoot -Nodes $AuthModCfg[$Path]
  608. }
  609. function Get-AuthServerQueryArguments {
  610. <#
  611. .SYNOPSIS
  612. Prepare arguments to execute queries on the SNS Security Server.
  613. .NOTES
  614. RequiredFunction<Get-PassFromCredential>
  615. RequiredFunction<Test-isAdmin>
  616. #>
  617. [CmdletBinding(DefaultParameterSetName = 'Credentials')]
  618. Param(
  619. [Parameter(Mandatory = $True, ParameterSetName = 'builtinAdmin')]
  620. [String]$SettingskstPath = 'C:\Settings.kst',
  621. [Parameter(Mandatory = $True, ParameterSetName = 'Credentials')]
  622. [ValidateNotNullOrEmpty()]
  623. [System.Management.Automation.PSCredential]$Credential
  624. )
  625. $ScSrvConfig = (Get-ItemProperty $Script:AUTHSRVREGPATH).ProductInstallPath + 'ScAuthSrvConfig.exe'
  626. $Realm = (Get-ItemProperty $Script:AUTHSRVREGPATH).KRBREALM
  627. if(-not (Test-Path -Path $ScSrvConfig -PathType Leaf) ){throw 'Not found ScAuthSrvConfig.exe util'}
  628. if($PsCmdlet.ParameterSetName -eq 'builtinAdmin'){
  629. Try {
  630. $builtinAdmin = (Get-Content $SettingskstPath -ErrorAction Stop)[1]
  631. }
  632. Catch [Management.Automation.ItemNotFoundException] {
  633. Trace-Message -Msg 'Settings.kst file not found!'
  634. throw $_
  635. }
  636. $ScSrvConfigArg = @('&',"'$ScSrvConfig'", $Realm, '/p', "'$builtinAdmin'")
  637. } else {
  638. $ScSrvConfigArg = @('&',"'$ScSrvConfig'", $Realm, '/a', "'$($env:USERNAME)'" ,'/p', "'$(Get-PassFromCredential -Credential $Credential)'")
  639. }
  640. return ($ScSrvConfigArg -join ' ')
  641. }
  642. function Get-LocalServerQueryArguments {
  643. <#
  644. .SYNOPSIS
  645. Extracts parameters from the Auth.xml
  646. #>
  647. [OutputType([Hashtable])]
  648. Param(
  649. [System.Management.Automation.PSCredential]$Credentials
  650. )
  651. $ScSrvConfig = (Get-ItemProperty $Script:NGFWREGPATH ).ProductInstallPath + 'ScLocalSrvConfig.exe'
  652. if(-not (Test-Path -Path $ScSrvConfig -PathType Leaf) ) {throw 'Not found ScLocalSrvConfig.exe util'}
  653. $ScSrvConfigArg = @('&',"'$ScSrvConfig'")
  654. return ($ScSrvConfigArg -join ' ')
  655. }
  656. function Get-PassFromCredential {
  657. Param(
  658. [Parameter(Mandatory=$True)][System.Management.Automation.PSCredential]$Credentials
  659. )
  660. $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Credentials.Password)
  661. return [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
  662. }
  663. function Test-AgentsOnSecurityServer {
  664. Param(
  665. [ValidateNotNullOrEmpty()]
  666. [Parameter(Mandatory=$True)] [String[]]$TAagents,
  667. [Parameter(Mandatory=$false)] [String[]]$TAagentsFromRule,
  668. [ValidateNotNullOrEmpty()]
  669. [Parameter(Mandatory=$True)] [String[]]$AuthSrvAgents
  670. )
  671. $TAagents = $TAagents |ForEach-Object{$_.ToUpper()}
  672. $AuthSrvAgents = $AuthSrvAgents |ForEach-Object{$_.ToUpper()}
  673. if ($null -ne $TAagentsFromRule){
  674. $TAagentsFromRule = $TAagentsFromRule |ForEach-Object{$_.ToUpper()}
  675. $TAagentsFromRule |Where-Object{$AuthSrvAgents -notcontains $_}|ForEach-Object{
  676. Write-Warning ("Íå óäàëîñü íàéòè ó÷åòíóþ çàïèñü êîìïüþòåðà {0} èç ïðàâèëà Trust Access â ñïèñêå àãåíòîâ Secret Net Studio. Ïðè ïðîäîëæåíèè òåêóùåå çíà÷åíèå â ïðàâèëå íå áóäåò èçìåíåíî ïðè èìïîðòå." -f $_) -WarningAction Inquire
  677. }
  678. }
  679. if( ($TAagents |Where-Object{$AuthSrvAgents -notcontains $_}) -eq $null ){
  680. Trace-VerboseMessage -Msg "Íàéäåíû âñå àãåíòû èç êîíôèãóðàöèè TrustAccess íà Ñåðâåðå áåçîïàñíîñòè Secret Net Studio."
  681. } else {
  682. throw "Imported accounts from TrustAccess weren’t found in the Security Server"
  683. }
  684. }
  685. function Test-TAUsersFromRulesInAD {
  686. <#
  687. checking users from the rules in active directory.
  688. #>
  689. # check fallback group
  690. $res = Get-ObjectOnAD -TAGroups $Script:FallBackGroup -DCSession $Script:DCSESSION
  691. if ($Script:FallBackGroup -ne $Everyone -and ($null -eq $res -or (($res |Where-Object{$_.ObjectClass -eq 'group'}) -eq $null)) ) {Throw 'Çàäàííàÿ ãðóïïà ïî óìîë÷àíèþ îòñóòñòâóåò â AD.'}
  692. # users from rules
  693. $TAusersFromRule = Get-TAItem -AuthXml $Script:AUTHXML -Path $script:USERSPATH
  694. # computers form rules
  695. $TApcFromRule = $TAusersFromRule |Where-Object{$_ -match '.+\$@.+'}|ForEach-Object{($_ -split '$')[0]}
  696. # Groups TA add up with users from the rules.
  697. $TAgoups = ( (Get-TAItem -AuthXml $Script:AUTHXML -Path $script:GROUPSPATH) + ($TAusersFromRule |Where-Object{$_ -notmatch '.+\$@.+'} |ForEach-Object{($_ -split '@')[0]}) |Select-Object -Unique )
  698. $TAgoups = $TAgoups |%{$_.ToUpper()}
  699. # Check the groups mapping from the groups mapping file
  700. if ($Script:GroupMappingFile){
  701. $GroupMappingFromFile = New-Object System.Collections.Hashtable
  702. try {
  703. $GMFileContent = Get-Content -Path $Script:GroupMappingFile -ErrorAction Stop
  704. }
  705. Catch {
  706. throw 'Íå óäàëîñü ïðî÷èòàòü ôàéë ñîîòâåòñòâèÿ ãðóïï TrustAccess ãðóïïàì â AD.'
  707. }
  708. $GMFileContent |ForEach-Object{
  709. $item = $_ -split ','
  710. $GroupMappingFromFile.Add($item[0].toUpper(), $item[1].toUpper())
  711. }
  712. # Check group from group mapping file on AD
  713. $TAgoups |Where-Object {$GroupMappingFromFile.Keys -contains $_} |Where-Object {$Script:AUTHXML[$SYSGROUPSPATH].Keys -notcontains $_ }|ForEach-Object {
  714. $MappedGroup = $GroupMappingFromFile[$_]
  715. if(Test-ObjectOnAD -TAGroups $MappedGroup -DCSession $Script:DCSESSION){
  716. Trace-Message -Msg ('User {0} from user mapping file found in Acrive Directory. Trust Access user {1}' -f $MappedGroup, $_)
  717. $Script:GROUPMAPPING.Add($_, $MappedGroup)
  718. } else {
  719. Write-Warning ("Óêàçàííîå â ôàéëå ñîîòâåòñòâèå ïîëüçîâàòåëÿ èëè ãðóïïû TA íå íàéäåíî â Active Directory. Ïðè ïðîäîëæåíèè òåêóùåå çíà÷åíèå {0} áóäåò çàìåíåíî íà ãðóïïó ïî óìîë÷àíèþ {1}." -f $_, $Script:FallBackGroup) -WarningAction Inquire
  720. Trace-Message -Msg ('User {0} from user mapping file not found in Acrive Directory, replace to default user {1}' -f $_, $Script:FallBackGroup)
  721. $Script:GROUPMAPPING.Add($_, $Script:FallBackGroup)
  722. }
  723. }
  724. # For users not found from groupmapping file set the fallback group.
  725. [String[]]$notMappedUser = $TAgoups |Where-Object {$GroupMappingFromFile.Keys -notcontains $_}
  726. if ($notMappedUser.Length -ge 1){
  727. Trace-Message -Msg ("The groups from Trust Access missing in the mapping file are found: `r`n{0}" -f ($notMappedUser -join "`r`n") )
  728. $notMappedUser |ForEach-Object{
  729. if(Test-ObjectOnAD -TAGroups $_ -DCSession $Script:DCSESSION){
  730. Trace-Message -Msg ('User {0} from rule Trust Access found in Acrive Directory.' -f $_)
  731. $Script:GROUPMAPPING.Add($_, $_)
  732. } else {
  733. Write-Warning ("Íå óäàëîñü íàéòè ïîëüçîâàòåëÿ èëè ãðóïïó â ôàéëå ñîîòâåòñòâèÿ è AD. Ïðè ïðîäîëæåíèè òåêóùåå çíà÷åíèå {0} áóäåò çàìåíåíî íà ãðóïïó ïî óìîë÷àíèþ {1}." -f $_, $Script:FallBackGroup) -WarningAction Inquire
  734. Trace-Message -Msg ("Replace user {0} from Trust Access to default user {0}." -f $_, $Script:FallBackGroup)
  735. $Script:GROUPMAPPING.Add($_, $Script:FallBackGroup)
  736. }
  737. }
  738. } else {
  739. Trace-Message -Msg 'All users found in the user mapping file.'
  740. }
  741. } else {
  742. # not net groupmapping file
  743. $TAgoups |ForEach-Object{
  744. if(Test-ObjectOnAD -TAGroups $_ -DCSession $Script:DCSESSION){
  745. Trace-Message -Msg ('User {0} from rule Trust Access found in Acrive Directory.' -f $_)
  746. $Script:GROUPMAPPING.Add($_, $_)
  747. } else {
  748. Write-Warning ("Íå óäàëîñü íàéòè ïîëüçîâàòåëÿ èëè ãðóïïó Trust Access â Active Directory. Ïðè ïðîäîëæåíèè òåêóùåå çíà÷åíèå {0} áóäåò çàìåíåíî íà ãðóïïó ïî óìîë÷àíèþ {1}." -f $_, $Script:FallBackGroup) -WarningAction Inquire
  749. Trace-Message -Msg ("Replace user {0} from Trust Access to default user {0}." -f $_, $Script:FallBackGroup)
  750. $Script:GROUPMAPPING.Add($_, $Script:FallBackGroup)
  751. }
  752. }
  753. }
  754. }
  755. function Test-ObjectOnAD {
  756. Param(
  757. [ValidateNotNullOrEmpty()]
  758. [Parameter(Mandatory=$True, ValueFromPipeline=$true)]
  759. [String[]] $TAgroups,
  760. [ValidateNotNullOrEmpty()]
  761. [Parameter(Mandatory=$True)]
  762. [System.Management.Automation.Runspaces.PSSession] $DCSession,
  763. [Parameter(Mandatory=$false)]
  764. [String] $DC = ($DCSession.ComputerName)
  765. )
  766. Process {
  767. $TAgroups |ForEach-Object{
  768. $res = Get-ObjectOnAD -TAgroups $_ -DCSession $DCSession -DC $DC
  769. return ($null -ne $res)
  770. }
  771. }
  772. }
  773. function Get-ObjectOnAD {
  774. Param(
  775. [ValidateNotNullOrEmpty()]
  776. [Parameter(Mandatory=$True, ValueFromPipeline=$true)]
  777. [String[]] $TAgroups,
  778. [ValidateNotNullOrEmpty()]
  779. [Parameter(Mandatory=$True)]
  780. [System.Management.Automation.Runspaces.PSSession] $DCSession,
  781. [Parameter(Mandatory=$false)]
  782. [String] $DC = $DCSession.ComputerName
  783. )
  784. Process {
  785. $TAgroups |ForEach-Object{
  786. $user = $_
  787. $ErrorActionPreferencePrev = $ErrorActionPreference
  788. for ($attempt = 0; $attempt -lt 33; $attempt++ ) {
  789. try {
  790. $ErrorActionPreference = 'Stop'
  791. $res = Invoke-Command -Session $DCSession -ScriptBlock {Get-ADObject -Filter "Name -eq '$($args[0])'" -Server $args[1]} -ArgumentList @($user,$DC)
  792. if($null -ne $res){
  793. switch ($res.ObjectClass){
  794. 'user'{
  795. $res = Invoke-Command -Session $DCSession -ScriptBlock {Get-ADUser -Filter "Name -eq '$($args[0])'" -Server $args[1]} -ArgumentList @($user,$DC)
  796. }
  797. 'computer'{
  798. $res = Invoke-Command -Session $DCSession -ScriptBlock {Get-ADComputer -Filter "Name -eq '$($args[0])'" -Server $args[1]} -ArgumentList @($user,$DC)
  799. }
  800. 'group' {
  801. $res = Invoke-Command -Session $DCSession -ScriptBlock {Get-ADGroup -Filter "Name -eq '$($args[0])'" -Server $args[1]} -ArgumentList @($user,$DC)
  802. }
  803. default {}
  804. }
  805. }
  806. return $res
  807. }
  808. Catch [System.Management.Automation.Remoting.PSRemotingTransportException] {
  809. $ErrorActionPreference='SilentlyContinue'
  810. Trace-VerboseMessage 'Retry invoke command '
  811. Start-Sleep -Seconds 1
  812. }
  813. }
  814. $ErrorActionPreference = $ErrorActionPreferencePrev
  815. throw 'Årror checking an object in AD.'
  816. }
  817. }
  818. }
  819. function Test-isAdmin {
  820. <#
  821. .SYNOPSIS
  822. Checks administrator rights.
  823. .EXAMPLE
  824. Test-isAdmin -Credentials $PSSession.Runspace.OriginalConnectionInfo.Credential
  825. #>
  826. Param(
  827. [System.Management.Automation.PSCredential]$Credentials = $null
  828. )
  829. if($null -ne $Credentials){
  830. $User = New-Object System.Security.Principal.WindowsIdentity($Credentials.UserName)
  831. } else {
  832. $User = [Security.Principal.WindowsIdentity]::GetCurrent()
  833. }
  834. if (-not ([Security.Principal.WindowsPrincipal] $User).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
  835. {
  836. 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!"
  837. return $false
  838. } else {
  839. return $true
  840. }
  841. }
  842. function Initialize-Requirements {
  843. $isAdmin = $false
  844. switch ($PsCmdlet.ParameterSetName){
  845. 'Remote'{
  846. }
  847. 'Local' {
  848. $Script:SSSNSName = $env:COMPUTERNAME
  849. }
  850. default {}
  851. }
  852. $Script:AuthXMLpath = (Resolve-Path $Script:AuthXMLpath).Path
  853. $Script:AUTHXML = Get-AuthXmlConfiguration -AuthXMLPath $Script:AuthXMLpath
  854. $Script:SSsession = Get-SessionByCredentials -ComputerName $Script:SSSNSName -Credential $Script:CREDENTIALS
  855. $Script:DCSESSION = Get-SessionByCredentials -ComputerName $Script:DC -Credential $Script:CREDENTIALS
  856. Invoke-FnRemote -PSSession $Script:SSsession -FunctionName 'Invoke-RemoteWithArguments' -ArgList @{
  857. Param = $Script:RemoteGlobalVar
  858. InvokeExpression = 'Write-Verbose "Set global variable."'
  859. Force = $true
  860. Scope = 'Global'
  861. }
  862. Invoke-FnRemote -PSSession $Script:DCSESSION -FunctionName 'Invoke-RemoteWithArguments' -ArgList @{
  863. Param = $Script:RemoteGlobalVar
  864. InvokeExpression = 'Write-Verbose "Set global variable."'
  865. Force = $true
  866. Scope = 'Global'
  867. }
  868. $isAdmin = Invoke-FnRemoteCommonWrapper -PSsession $Script:SSsession -InvokeExpression 'Test-isAdmin'
  869. if(-not $isAdmin){throw 'Äëÿ çàãðóçêè ïðàâèë íà ñåðâåð áåçîïàñíîñòè òðåáóþòñÿ ïðàâà àäìèíèñòðàòîðà.'}
  870. try {
  871. Invoke-FnRemoteCommonWrapper -PSsession $Script:DCSESSION -InvokeExpression 'Import-RequiredADmodule -PSmodules $PSmodules' -Parameters @{'PSmodules' = $Script:PSmodules} |Trace-VerboseMessage
  872. }
  873. Catch [System.IO.FileNotFoundException] {
  874. throw 'Íå óäàëîñü çàãðóçèòü òðåáóåìûå ìîäóëè íà êîíòðîëëåðå äîìåíà.'
  875. exit
  876. }
  877. Catch {
  878. throw $_
  879. }
  880. }
  881. function Import-RequiredADmodule {
  882. <#
  883. .SYNOPSIS
  884. Checking for the presence of necessary modules.
  885. #>
  886. Param(
  887. $PSmodules
  888. )
  889. Trace-Message -Msg "Loading the module into the session."
  890. $PSmodules |ForEach-Object {
  891. if (Get-Module -ListAvailable -Name $_) {
  892. Trace-Message -Msg ("{0} module exists." -f $_)
  893. } else {
  894. Try {
  895. Trace-Message -Msg ("Try import module {0}" -f $_)
  896. Import-Module -Name $_
  897. } Catch {
  898. throw ("Module {0} not exist." -f $_)
  899. }
  900. }
  901. }
  902. }
  903. function Get-SessionByCredentials {
  904. Param(
  905. [String]$ComputerName,
  906. [System.Management.Automation.PSCredential]$Credential
  907. )
  908. Try {
  909. $session = New-PSSession -ComputerName $ComputerName -Credential $Credential -ErrorAction Stop
  910. }
  911. Catch [System.Management.Automation.Remoting.PSRemotingTransportException] {
  912. throw ("Îïåðàöèÿ íå ìîæåò áûòü âûïîëíåíà - îøèáêà äîñòóïà ê ñåðâåðó {0}.`r`n{1}" -f $ComputerName, $_)
  913. exit
  914. }
  915. Catch {
  916. throw $_
  917. }
  918. return $session
  919. }
  920. function Get-AgentList {
  921. Param(
  922. [ValidateNotNullOrEmpty()]
  923. [Parameter(Mandatory=$True)][String]$ScSrvConfigArg
  924. )
  925. [String[]]$output = Invoke-Expression ($ScSrvConfigArg + '/q', '"show computers"')
  926. if($LASTEXITCODE -ne 0){
  927. Trace-Message ('Exit code ScAuthSrvConfig: {0}' -f $LASTEXITCODE)
  928. Trace-Message ( 'ScSrvConfig error: {0}' -f $output)
  929. throw ('ScSrvConfig error:{0}' -f $LASTEXITCODE)
  930. }
  931. Trace-Message 'Get SNS computers.'
  932. $output |Trace-Message
  933. if($null -ne $output){
  934. $index = 0
  935. $output |%{$i = 0}{if($_ -like '*computer(s)*'){$index = $i}else{$i++} }
  936. $Computers = $output[0..($index -2)]|ForEach-Object{($_ -split '\s+')[0].trim()}
  937. } else {
  938. throw 'Íå óäàëîñü ïîëó÷èòü ñïèñîê àãåíòîâ Secret Net Studio.'
  939. }
  940. return $Computers
  941. }
  942. function Get-TAitem {
  943. [OutputType([String[]])]
  944. Param(
  945. [Parameter(Mandatory=$True)][Hashtable]$AuthXml,
  946. [Parameter(Mandatory=$True)][String]$Path
  947. )
  948. $TAitem = New-Object System.Collections.ArrayList
  949. if($AuthXml[$Path] -is [hashtable]){
  950. $TAitem = $AuthXml[$Path].GetEnumerator()|ForEach-Object{$_.key |Where-Object{$_ -notmatch '/'}}
  951. } elseif ($AuthXml[$Path] -is [System.Array]) {
  952. $TAitem = $AuthXml[$Path]
  953. }
  954. return $TAitem
  955. }
  956. function Get-AuthSrvConfiguration {
  957. <#
  958. .SYNOPSIS
  959. Get configuration from Auth Server.
  960. .NOTES
  961. RequiredFunction<Get-XMLbyPath>
  962. #>
  963. Param(
  964. [ValidateNotNullOrEmpty()]
  965. [Parameter(Mandatory=$True)][String[]]$AgentNameList,
  966. [ValidateNotNullOrEmpty()]
  967. [Parameter(Mandatory=$True)][String]$ScSrvConfigArg
  968. )
  969. $tmpdir = new-item -Path (Join-Path ($env:TEMP) ([System.IO.Path]::GetRandomFileName()) ) -type Directory -ErrorAction Stop
  970. $AgentsRules = New-Object System.Collections.Hashtable
  971. Trace-Message -Msg "Create temp directory $tmpdir"
  972. try{
  973. $AgentNameList |ForEach-Object {
  974. $AgentrulesXML = "$($tmpdir.FullName)\$_"
  975. Trace-Message -Msg ("Create temp config agent file {0}" -f $AgentrulesXML)
  976. Invoke-Expression ( $ScSrvConfigArg + '/q', ('"show raw_configuration /path ""\auth-mod-cfg\servers\{0}\rules"" /file {1} "') -f $_, $AgentrulesXML) |Trace-Message
  977. if($LASTEXITCODE -ne 0){
  978. Trace-Message ('Exit code ScAuthSrvConfig: {0}' -f $LASTEXITCODE)
  979. throw ('ScSrvConfig error:{0}' -f $LASTEXITCODE)
  980. }
  981. if(Test-Path -Path $AgentrulesXML -PathType leaf ){
  982. $AgentsRules.Add($_, (Get-XMLbyPath -XmlPath $AgentrulesXML) )
  983. } else {
  984. throw 'Âðåìåííûé ôàéë êîíôèãóðàöèè àãåíòà íå íàéäåí.'
  985. }
  986. }
  987. } Catch {
  988. Remove-item -Path $tmpdir -Recurse
  989. throw
  990. }
  991. Trace-Message -Msg "Remove temp directory $tmpdir"
  992. $AgentsRules.Keys |Trace-Message
  993. Remove-item -Path $tmpdir -Recurse
  994. return $AgentsRules
  995. }
  996. function Set-TAUsersAsEveryone{
  997. <#
  998. Set all users from rule Trust Access as everyone.
  999. #>
  1000. Param(
  1001. [Hashtable]$AuthXml
  1002. )
  1003. # users from rules
  1004. $TAusersFromRule = Get-TAItem -AuthXml $Script:AUTHXML -Path $script:USERSPATH
  1005. # computers from rules
  1006. $TApcFromRule = $TAusersFromRule |Where-Object{$_ -match '.+\$@.+'}|ForEach-Object{($_ -split '$')[0]}
  1007. $TAgoups = ( (Get-TAItem -AuthXml $Script:AUTHXML -Path $script:GROUPSPATH) + ($TAusersFromRule |Where-Object{$_ -notmatch '.+\$@.+'} |ForEach-Object{($_ -split '@')[0]}) |Select-Object -Unique )
  1008. $TAgoups = $TAgoups|%{$_.ToUpper()}
  1009. $TAgoups |Where-Object {$Script:AUTHXML[$SYSGROUPSPATH] -notcontains $_}|ForEach-Object {
  1010. $Script:GROUPMAPPING.Add($_, $Everyone)
  1011. }
  1012. $AuthXml[$Script:ACCESSRULESPATH].GetEnumerator()|%{$_.value['groups'] = '1';$_.value['principals'] = ""}
  1013. }
  1014. function Set-AuthSrvConfiguration {
  1015. <#
  1016. .SYNOPSIS
  1017. Set configuration from Auth Server.
  1018. #>
  1019. Param(
  1020. [ValidateNotNullOrEmpty()]
  1021. [Parameter(Mandatory=$True)][Hashtable]$AgentsConfigXML,
  1022. [ValidateNotNullOrEmpty()]
  1023. [Parameter(Mandatory=$True)][String]$ScSrvConfigArg
  1024. )
  1025. $tmpdir = new-item -Path (Join-Path ($env:TEMP) ([System.IO.Path]::GetRandomFileName()) ) -type Directory -ErrorAction Stop
  1026. Trace-Message -Msg "Create temp directory $tmpdir"
  1027. try{
  1028. $AgentsConfigXML.GetEnumerator() |ForEach-Object {
  1029. $AgentName = $_.Key
  1030. $AgentrulesXML = "{0}\{1}.xml" -f $tmpdir.FullName, $AgentName
  1031. Trace-Message -Msg ("Create temp config agent file {0}" -f $AgentrulesXML)
  1032. $_.Value.Save($AgentrulesXML)
  1033. Invoke-Expression ( $ScSrvConfigArg + '/q', ('"set raw_configuration {0} "' -f $AgentrulesXML)) |Trace-Message
  1034. if($LASTEXITCODE -ne 0){
  1035. Trace-Message ('Exit code ScAuthSrvConfig: {0}' -f $LASTEXITCODE)
  1036. throw ('ScSrvConfig error:{0}' -f $LASTEXITCODE)
  1037. }
  1038. }
  1039. } Catch {
  1040. Trace-Message -Msg "Remove temp directory $tmpdir"
  1041. Remove-item -Path $tmpdir -Recurse
  1042. throw $_
  1043. }
  1044. Trace-Message -Msg "Remove temp directory $tmpdir"
  1045. Remove-item -Path $tmpdir -Recurse
  1046. }
  1047. function Set-AuthSrvPolicyConfiguration {
  1048. <#
  1049. .SYNOPSIS
  1050. Set configuration from Auth Server.
  1051. #>
  1052. Param(
  1053. [ValidateNotNullOrEmpty()]
  1054. [Parameter(Mandatory=$True)][String[]]$Agents,
  1055. [ValidateNotNullOrEmpty()]
  1056. [Parameter(Mandatory=$True)][String]$ScSrvConfigArg,
  1057. [ValidateNotNullOrEmpty()]
  1058. [Parameter(Mandatory=$True)][Hashtable]$AuthPolicy
  1059. )
  1060. $Agents|%{
  1061. $agent = $_
  1062. Trace-Message -Msg ("Set policy agent {0}" -f $agent)
  1063. $AuthPolicy.GetEnumerator() |ForEach-Object {
  1064. Trace-Message -Msg ("Set auth-policy {0} value {1} for agent {2}" -f $_.Key, $_.Value, $agent)
  1065. Invoke-Expression ( $ScSrvConfigArg + '/q', ('"set cp {0} /{1} {2}"' -f $agent, $_.Key, $_.Value)) |Trace-Message
  1066. if($LASTEXITCODE -ne 0){
  1067. Trace-Message ('Exit code ScAuthSrvConfig: {0}' -f $LASTEXITCODE)
  1068. throw ('ScSrvConfig error:{0}' -f $LASTEXITCODE)
  1069. }
  1070. }
  1071. }
  1072. }
  1073. function Get-XMLbyPath {
  1074. Param(
  1075. [ValidateNotNullOrEmpty()]
  1076. [Parameter(Mandatory=$True)][String]$XmlPath
  1077. )
  1078. $xml = New-Object System.Xml.XmlDocument
  1079. Trace-Message -Msg ('Load XML {0}' -f $XmlPath)
  1080. $xml.Load($XmlPath)
  1081. return $xml
  1082. }
  1083. function Import-TARules {
  1084. Param(
  1085. [Hashtable]$AuthXml,
  1086. [String]$ScSrvConfigArg
  1087. )
  1088. $ImportedRules = New-Object System.Collections.Hashtable
  1089. $UsedGuid = New-Object System.Collections.ArrayList
  1090. $AgentsRuleMsgBuff = New-Object System.Collections.Hashtable
  1091. [String[]]$TAagents = Get-TAitem -AuthXml $Authxml -Path $SCript:AGENTSPATH
  1092. [Hashtable]$AgentsConfigXML = Invoke-FnRemoteCommonWrapper -PSsession $Script:SSsession -InvokeExpression 'Get-AuthSrvConfiguration -AgentNameList $AgentNameList -ScSrvConfigArg $ScSrvConfigArg' -Parameters @{
  1093. ScSrvConfigArg = $ScSrvConfigArg
  1094. AgentNameList = $TAagents
  1095. }
  1096. $TAagents|ForEach-Object{
  1097. $agent = $_.ToUpper()
  1098. $RuleMsgBuff = New-Object System.Collections.Hashtable
  1099. $AgentsRuleMsgBuff.Add($agent, (New-Object System.Collections.Hashtable))
  1100. $RawAgentRules = ($AuthXml[$Script:SERVERSPATH].GetEnumerator()|?{$_.Value.'server-name' -eq $agent}).Value.GetEnumerator()|?{$_.Name -match '\\rules\\*'}
  1101. $agentRules = New-Object System.Collections.Hashtable
  1102. $RawAgentRules.GetEnumerator()|ForEach-Object{
  1103. $agentrule = $_
  1104. $agentrule.Name |Select-String -Pattern '\\rules\\(?<type>.+)\\(?<guid>.+)' |ForEach-Object{
  1105. $agentRules[$_.Matches[0].Groups['type'].Value] += @{$agentrule.Value['order'] = (($agentrule.Value['ruleid']|Select-string -Pattern '\\auth-mod-cfg\\accessrules\\(?<guid>.+)\\').Matches[0].Groups['guid'].Value)}
  1106. }
  1107. }
  1108. $ImportedRules[$agent] += $agentRules
  1109. $ImportedRules[$agent].GetEnumerator()|ForEach-Object{
  1110. $Rule = $null
  1111. $type = $_.Name
  1112. $RuleMsgBuff.Add($type, (New-Object System.Collections.ArrayList)) |Out-Null
  1113. if ($type -eq 'network-layer-rules'){return} # skip network layer rules
  1114. [bool]$icmpProtectOn = $false
  1115. [Microsoft.PowerShell.Commands.SelectXmlInfo]$currSNSRuleBlock = $AgentsConfigXML[$agent] | Select-Xml -XPath ("//Node[@path='{0}']" -f $type)
  1116. if( -not $currSNSRuleBlock){
  1117. $xmlElement = $AgentsConfigXML[$agent] | Select-Xml -XPath "//Node[@path='rules']"
  1118. $xmlElement |%{$_.Node.AppendChild( (New-XmlNode -XmlDoc $AgentsConfigXML[$agent] -Type "Node" -Attribute "path" -AttributeName $type) )}
  1119. [Microsoft.PowerShell.Commands.SelectXmlInfo]$currSNSRuleBlock = $AgentsConfigXML[$agent] | Select-Xml -XPath ("//Node[@path='{0}']" -f $type)
  1120. }
  1121. [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']"
  1122. $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')]]")
  1123. if ($null -ne $icmpRules){
  1124. $icmpProtectOn = $true
  1125. }
  1126. if($null -ne $order){
  1127. [int]$order = ($order|%{$_.Node.Value} |Measure-Object -Maximum).Maximum + 1
  1128. } else {
  1129. [int]$order = $Script:ORDERRAGE[$type]
  1130. }
  1131. [String[]]$UsedGuid = 0
  1132. $currSNSRuleBlock |%{$_.Node.ChildNodes} | ForEach-Object{
  1133. $rule = $_
  1134. $UsedGuid += $_.path
  1135. }
  1136. ($ImportedRules[$agent][$type].GetEnumerator() |Sort-Object -Property name) |%{$_.Value} |ForEach-Object{$i = 0}{
  1137. $ruleGUID = $_
  1138. Trace-VerboseMessage -Msg ('Add rule TA guid:{0}' -f $ruleGUID)
  1139. if($AuthXml[$ACCESSRULESPATH].$ruleGUID['protocol'] -eq '1' -and ($AuthXml[$ACCESSRULESPATH].$ruleGUID['hidden-rule'] -eq '1')){ # îïðåäåëÿþ ñèñòåìíûå ïðàâèëà Icmp
  1140. if($icmpProtectOn){
  1141. Trace-VerboseMessage -Msg 'ICMP rules already exist for this agent on the Auth Server, removed rule from the imported.'
  1142. $ImportedRules[$agent][$type].Remove( ($ImportedRules[$agent][$type].GetEnumerator()|?{$_.Value -eq $ruleGUID}).Key )
  1143. $AuthXml[$ACCESSRULESPATH].Remove($ruleGUID)
  1144. return
  1145. } else {
  1146. $AuthXml[$ACCESSRULESPATH].$ruleGUID['create-auth-rule'] = "0"
  1147. $AuthXml[$ACCESSRULESPATH].$ruleGUID['flags'] = "1"
  1148. $order += 990
  1149. }
  1150. } else {
  1151. $AuthXml[$ACCESSRULESPATH].$ruleGUID['create-auth-rule'] = "1"
  1152. $AuthXml[$ACCESSRULESPATH].$ruleGUID['flags'] = "0"
  1153. }
  1154. $AuthXml[$ACCESSRULESPATH].$ruleGUID['order'] = ($order + $i)
  1155. $AuthXml[$ACCESSRULESPATH].$ruleGUID['owner'] = $agent
  1156. switch -regex ($AuthXml[$ACCESSRULESPATH].$ruleGUID['groups']) { # replacing groups in a rule
  1157. '^\d{1}$' {
  1158. $gNum = $AuthXml[$ACCESSRULESPATH].$ruleGUID['groups']
  1159. $AuthXml[$ACCESSRULESPATH].$ruleGUID['groups'] = ""
  1160. Trace-VerboseMessage -Msg ('System group in the rule: {0}' -f $gNum)
  1161. $AuthXml[$ACCESSRULESPATH].$ruleGUID['groups'] = '{0000000#-0000-0000-0000-000000000000}'.Replace('#', $gNum)
  1162. }
  1163. '^\d{4}$' {
  1164. $gNum = $AuthXml[$ACCESSRULESPATH].$ruleGUID['groups']
  1165. $AuthXml[$ACCESSRULESPATH].$ruleGUID['groups'] = ""
  1166. $ADgroup = $Script:GROUPMAPPING[(($AuthXml[$script:GROUPSPATH].GetEnumerator()|?{$_.Value['SID'] -eq $gNum}).Name).toUpper()]
  1167. if($ADgroup -eq $Everyone) {
  1168. $AuthXml[$ACCESSRULESPATH].$ruleGUID['groups'] = ($Script:GROUPSNAME.GetEnumerator()|?{$_.Value -eq $Everyone}).Name
  1169. } else {
  1170. $ADobj = Get-ObjectOnAD -TAGroups $ADgroup -DCSession $Script:DCSESSION |Where-Object{$_.ObjectClass -eq 'group'}
  1171. if($null -eq $ADobj){throw ('Íå óäàëîñü íàéòè ãðóïïó {0} â Active Directory.' -f $ADgroup)}
  1172. $sid = $ADobj.SID
  1173. Trace-VerboseMessage -Msg ('External group in the rule sid: {0} SID AD: {1}' -f $gNum, $sid)
  1174. $AuthXml[$ACCESSRULESPATH].$ruleGUID['external-subjects'] = $sid
  1175. }
  1176. }
  1177. ''{
  1178. Trace-VerboseMessage -Msg ('No goups')
  1179. }
  1180. Default {
  1181. throw "Unexpected group id."
  1182. }
  1183. }
  1184. switch -regex ($AuthXml[$ACCESSRULESPATH].$ruleGUID['principals']) { # Replacing users and computer accounts in a rule
  1185. '' {
  1186. Trace-VerboseMessage -Msg 'No principal in the rule.'
  1187. }
  1188. '(.+)\$@.+' {
  1189. $AuthXml[$ACCESSRULESPATH].$ruleGUID['principals'] = ""
  1190. $pc = $matches[1].toUpper()
  1191. $ADobj = (Get-ObjectOnAD -TAGroups $pc -DCSession $Script:DCSESSION |Where-Object{$_.ObjectClass -eq 'computer'})
  1192. if($null -eq $ADobj){throw ('Íå óäàëîñü íàéòè êîìïüþòåð {0} â Active Directory.' -f $pc)}
  1193. $pcSID = $ADobj.SID
  1194. Trace-VerboseMessage -Msg ('Computer account in the rule. SID:{0}' -f $pcSID)
  1195. $AuthXml[$ACCESSRULESPATH].$ruleGUID['external-subjects'] = $pcSID
  1196. }
  1197. '(.[^\$]+)@.+' {
  1198. $AuthXml[$ACCESSRULESPATH].$ruleGUID['principals'] = ""
  1199. $ADuser = $Script:GROUPMAPPING[($matches[1].toUpper())]
  1200. if($ADuser -eq $Everyone) {
  1201. $AuthXml[$ACCESSRULESPATH].$ruleGUID['groups'] = ($Script:GROUPSNAME.GetEnumerator()|?{$_.Value -eq $Everyone}).Name
  1202. } else {
  1203. $ADobj = Get-ObjectOnAD -TAGroups $ADuser -DCSession $Script:DCSESSION
  1204. if($null -eq $ADobj){throw ('Íå óäàëîñü íàéòè ïîëüçîâàòåëÿ {0} â Active Directory.' -f $ADuser)}
  1205. $userSID = $ADobj.SID
  1206. Trace-VerboseMessage -Msg ('User account in the rule. SID:{0}' -f $userSID)
  1207. $AuthXml[$ACCESSRULESPATH].$ruleGUID['external-subjects'] = $userSID
  1208. }
  1209. }
  1210. Default {}
  1211. }
  1212. Set-RuleNode -Xml $AgentsConfigXML[$agent] -TARule $AuthXml[$ACCESSRULESPATH].$ruleGUID -result ([ref]$Rule) -Type $type -UsedGuid $UsedGuid
  1213. $i++
  1214. $currSNSRuleBlock |%{$_.Node.AppendChild($Rule)} |Out-Null
  1215. }
  1216. if ($Script:OnlyViewRule){
  1217. ($ImportedRules[$agent][$type].GetEnumerator() |Sort-Object -Property name) |%{$_.Value} |ForEach-Object{
  1218. $RuleMsgBuff[$type].Add((Get-ngfwrule -TARule $AuthXml[$ACCESSRULESPATH].$_ -Type $type)) |Out-Null
  1219. }
  1220. }
  1221. }
  1222. $AgentsRuleMsgBuff[$agent] += $RuleMsgBuff
  1223. }
  1224. if ($Script:OnlyViewRule) {
  1225. Trace-Message ('Íà íà ñåðâåð áåçîïàñòíîñòè Secret Net Studio {0} áóäóò èìïîðòèðîâàíû ñëåäóþùèå ïðàâèëà:' -f $Script:SSsession.ComputerName )
  1226. $AgentsRuleMsgBuff.GetEnumerator()|ForEach-Object{
  1227. ('Add rule for agent:{0}' -f $_.key)
  1228. $_.Value.GetEnumerator()|ForEach-Object{
  1229. ('Type:{0}' -f $_.key)
  1230. ('Count:{0}' -f $_.Value.Count)
  1231. $_.Value |Format-Table * -AutoSize |Out-String
  1232. }
  1233. }
  1234. } else {
  1235. Trace-Message -Msg 'Set configuration.'
  1236. Invoke-FnRemoteCommonWrapper -PSsession $Script:SSsession -InvokeExpression 'Set-AuthSrvConfiguration -AgentsConfigXML $AgentsConfigXML -ScSrvConfigArg $ScSrvConfigArg' -Parameters @{
  1237. ScSrvConfigArg = $ScSrvConfigArg
  1238. AgentsConfigXML = $AgentsConfigXML
  1239. }
  1240. if($EnableProtectionEveryone){
  1241. Trace-Message -Msg 'Set everyone policy.'
  1242. Invoke-FnRemoteCommonWrapper -PSsession $Script:SSsession -InvokeExpression 'Set-AuthSrvPolicyConfiguration -Agents $Agents -AuthPolicy $AuthPolicy -ScSrvConfigArg $ScSrvConfigArg' -Parameters @{
  1243. ScSrvConfigArg = $ScSrvConfigArg
  1244. Agents = $AgentsConfigXML.Keys
  1245. AuthPolicy = @{
  1246. 'auth_rule_gen_skip_everyone' = 0
  1247. }
  1248. }
  1249. }
  1250. }
  1251. }
  1252. function Get-ngfwrule {
  1253. Param(
  1254. [hashtable]$TARule,
  1255. [String]$type
  1256. )
  1257. switch ($type) {
  1258. 'network-transport-with-auth-rules' {
  1259. New-Object -TypeName NGFWNetworkWithAuthRule($TARule)
  1260. }
  1261. 'network-transport-rules' {
  1262. New-Object -TypeName NGFWNetworkTransportRule($TArule)
  1263. }
  1264. 'smb-folder-rules'{
  1265. New-Object -TypeName NGFWSMBRule($TArule)
  1266. }
  1267. 'pipe-rules' {
  1268. New-Object -TypeName NGFWPipeRule($TArule)
  1269. }
  1270. Default {throw ('Òèï ïðàâèë {0} íå ñóùåñòâóåò.' -f $type) }
  1271. }
  1272. }
  1273. function CreateRuleNode{
  1274. Param(
  1275. [Parameter(Mandatory=$True)]
  1276. [System.Xml.XmlDocument]$XmlDoc,
  1277. [String]$Name,
  1278. [String]$Value
  1279. )
  1280. $Field = New-XmlNode -XmlDoc $XmlDoc -Type "a" -Attribute "name" -AttributeName $Name -AttributeValue $Value
  1281. return $Field
  1282. }
  1283. function New-XmlNode {
  1284. Param(
  1285. [Parameter(Mandatory=$True)]
  1286. [System.Xml.XmlDocument]$XmlDoc,
  1287. [Parameter(Mandatory=$True)]
  1288. [String]$Type,
  1289. [Parameter(Mandatory=$True)]
  1290. [String]$Attribute,
  1291. [Parameter(Mandatory=$True)]
  1292. [String]$AttributeName,
  1293. [Parameter(Mandatory=$false)]
  1294. [String]$AttributeValue
  1295. )
  1296. $Field = $XmlDoc.CreateElement($type)
  1297. $Field.SetAttribute($Attribute, $AttributeName)
  1298. $Field.SetAttribute("value",$AttributeValue)
  1299. return $Field
  1300. }
  1301. function Set-RuleNode {
  1302. Param(
  1303. [Parameter(Mandatory=$True)][System.Xml.XmlDocument]$Xml,
  1304. [Parameter(Mandatory=$True)][hashtable]$TARule,
  1305. [Parameter(Mandatory=$True)][String[]]$UsedGuid,
  1306. [Parameter(Mandatory=$True)][String]$Type,
  1307. [Parameter(Mandatory=$True)][ref]$result
  1308. )
  1309. $Rule = $xml.CreateElement("Node")
  1310. do
  1311. {
  1312. $guid = "{$([guid]::NewGuid().guid)}"
  1313. } while($UsedGuid -icontains $guid)
  1314. $Rule.SetAttribute("path", $guid)
  1315. switch ($Type) {
  1316. 'network-layer-rules' {
  1317. Set-NetworkLayerRuleNode -Rule $Rule -TArule $TArule
  1318. }
  1319. 'network-transport-with-auth-rules' {
  1320. Set-TransportWithAuthRuleNode -Rule $Rule -TArule $TArule
  1321. }
  1322. 'network-transport-rules' {
  1323. Set-TransportRuleNode -Rule $Rule -TArule $TArule
  1324. }
  1325. 'smb-folder-rules'{
  1326. Set-SmbRuleNode -Rule $Rule -TArule $TArule
  1327. }
  1328. 'pipe-rules' {
  1329. Set-PipeRuleNode -Rule $Rule -TArule $TArule
  1330. }
  1331. Default {throw ('Òèï ïðàâèë {0} íå ñóùåñòâóåò.' -f $Type) }
  1332. }
  1333. $result.Value = $rule
  1334. }
  1335. function Set-TransportWithAuthRuleNode {
  1336. Param(
  1337. [System.Xml.XmlElement]$Rule,
  1338. [hashtable]$TArule
  1339. )
  1340. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "order" -Value ("{0}" -f $TArule["order"]) )) |Out-Null
  1341. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "enabled" -Value ("{0}" -f $TArule["enabled"]) )) |Out-Null
  1342. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "ruletype" -Value ("{0}" -f $TArule["ruletype"]) )) |Out-Null
  1343. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "service" -Value ("{0}" -f $TArule["service"]) )) |Out-Null
  1344. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "accesstype" -Value ("{0}" -f $TArule["accesstype"]) )) |Out-Null
  1345. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "audit-enabled" -Value ("{0}" -f $TArule["audit-enabled"]) )) |Out-Null
  1346. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "local-ports" -Value ("{0}" -f $TArule["local-ports"]) )) |Out-Null
  1347. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "remote-ports" -Value ("{0}" -f $TArule["remote-ports"]) )) |Out-Null
  1348. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "protocol" -Value ("{0}" -f $TArule["protocol"]) )) |Out-Null
  1349. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "local-addrs" -Value ("{0}" -f $TArule["local-addrs"]) )) |Out-Null
  1350. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "remote-addrs" -Value ("{0}" -f $TArule["remote-addrs"]) )) |Out-Null
  1351. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "rule-direction-type" -Value ("{0}" -f $TArule["rule-direction-type"]) )) |Out-Null
  1352. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "flags" -Value ("{0}" -f $TArule["flags"]) )) |Out-Null
  1353. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "groups" -Value ("{0}" -f $TArule["groups"]) )) |Out-Null
  1354. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "create-auth-rule" -Value ("{0}" -f $TArule["create-auth-rule"]) )) |Out-Null
  1355. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "owner" -Value ("{0}" -f $TArule["owner"]) )) |Out-Null
  1356. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "description" -Value "" )) |Out-Null
  1357. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "guid" -Value "" )) |Out-Null
  1358. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "rule-activate-times" -Value ("{0}" -f $TArule["rule-activate-times"]) )) |Out-Null
  1359. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd" -Value ("{0}" -f $TArule["on-rule-action-cmd"]) )) |Out-Null
  1360. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd-folder" -Value "" )) |Out-Null
  1361. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd-start-type" -Value "system" )) |Out-Null
  1362. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd-token-type" -Value "user" )) |Out-Null
  1363. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd-beep" -Value ("{0}" -f $TArule["on-rule-action-cmd-beep"]) )) |Out-Null
  1364. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "accessmask" -Value ("{0}" -f $TArule["accessmask"]) )) |Out-Null
  1365. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "reply-on-reject" -Value ("{0}" -f $TArule["reply-on-reject"]) )) |Out-Null
  1366. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "adapters-to-include" -Value ("{0}" -f $TArule["adapters-to-include"]) )) |Out-Null
  1367. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "adapters-to-exclude" -Value ("{0}" -f $TArule["adapters-to-exclude"]) )) |Out-Null
  1368. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "adapters-match" -Value ("{0}" -f $TArule["adapters-match"]) )) |Out-Null
  1369. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "rule-activate-regexp" -Value ("{0}" -f $TArule["rule-activate-regexp"]) )) |Out-Null
  1370. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "principals" -Value ("{0}" -f $TArule["principals"]) )) |Out-Null
  1371. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "external-subjects" -Value ("{0}" -f $TArule["external-subjects"]) )) |Out-Null
  1372. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "restricted-process-sids" -Value "" )) |Out-Null
  1373. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "is-emergency-rule" -Value ("{0}" -f $TArule["is-emergency-rule"]) )) |Out-Null
  1374. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "network-level" -Value ("{0}" -f $TArule["network-level"]) )) |Out-Null
  1375. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "rule-scope" -Value ("{0}" -f $TArule["rule-scope"]) )) |Out-Null
  1376. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "out-channel-protection-enabled" -Value ("{0}" -f $TArule["out-channel-protection-enabled"]) )) |Out-Null
  1377. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "processes-to-include" -Value ("{0}" -f $TArule["processes-to-include"]) )) |Out-Null
  1378. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "processes-to-exclude" -Value ("{0}" -f $TArule["processes-to-exclude"]) )) |Out-Null
  1379. }
  1380. function Set-TransportRuleNode {
  1381. Param(
  1382. [System.Xml.XmlElement]$Rule,
  1383. [hashtable]$TArule
  1384. )
  1385. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "order" -Value ("{0}" -f $TArule["order"]) )) |Out-Null
  1386. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "enabled" -Value ("{0}" -f $TArule["enabled"]) )) |Out-Null |Out-Null
  1387. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "ruletype" -Value ("{0}" -f $TArule["ruletype"]) )) |Out-Null
  1388. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "service" -Value ("{0}" -f $TArule["service"]) )) |Out-Null
  1389. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "accesstype" -Value ("{0}" -f $TArule["accesstype"]) )) |Out-Null
  1390. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "audit-enabled" -Value ("{0}" -f $TArule["audit-enabled"]) )) |Out-Null
  1391. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "local-ports" -Value "" )) |Out-Null
  1392. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "remote-ports" -Value "" )) |Out-Null
  1393. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "protocol" -Value ("{0}" -f $TArule["protocol"]) )) |Out-Null
  1394. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "local-addrs" -Value ("{0}" -f $TArule["local-addrs"]) )) |Out-Null
  1395. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "remote-addrs" -Value ("{0}" -f $TArule["remote-addrs"]) )) |Out-Null
  1396. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "rule-direction-type" -Value ("{0}" -f $TArule["rule-direction-type"]) )) |Out-Null
  1397. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "flags" -Value ("{0}" -f $TArule["flags"]) )) |Out-Null
  1398. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "rule-condition" -Value ("{0}" -f $TArule["rule-condition"]) )) |Out-Null
  1399. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "description" -Value "" )) |Out-Null
  1400. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "create-auth-rule" -Value ("{0}" -f $TArule["create-auth-rule"]) )) |Out-Null
  1401. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "guid" -Value "" )) |Out-Null
  1402. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "owner" -Value ("{0}" -f $TArule["owner"]) )) |Out-Null
  1403. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "rule-activate-times" -Value ("{0}" -f $TArule["rule-activate-times"]) )) |Out-Null
  1404. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd" -Value ("{0}" -f $TArule["on-rule-action-cmd"]) )) |Out-Null
  1405. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd-folder" -Value "" )) |Out-Null
  1406. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd-start-type" -Value "system" )) |Out-Null
  1407. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd-token-type" -Value "user" )) |Out-Null
  1408. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd-beep" -Value ("{0}" -f $TArule["on-rule-action-cmd-beep"]) )) |Out-Null
  1409. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "accessmask" -Value ("{0}" -f $TArule["accessmask"]) )) |Out-Null
  1410. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "reply-on-reject" -Value ("{0}" -f $TArule["reply-on-reject"]) )) |Out-Null
  1411. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "adapters-to-include" -Value ("{0}" -f $TArule["adapters-to-include"]) )) |Out-Null
  1412. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "adapters-to-exclude" -Value ("{0}" -f $TArule["adapters-to-exclude"]) )) |Out-Null
  1413. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "adapters-match" -Value ("{0}" -f $TArule["adapters-match"]) )) |Out-Null
  1414. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "rule-activate-regexp" -Value ("{0}" -f $TArule["rule-activate-regexp"]) )) |Out-Null
  1415. }
  1416. function Set-NetworkLayerRuleNode {
  1417. Param(
  1418. [System.Xml.XmlElement]$Rule,
  1419. [hashtable]$TArule
  1420. )
  1421. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "order" -Value ("{0}" -f $TArule["order"]) )) |Out-Null
  1422. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "enabled" -Value ("{0}" -f $TArule["enabled"]) )) |Out-Null
  1423. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "ruletype" -Value ("{0}" -f $TArule["ruletype"]) )) |Out-Null
  1424. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "service" -Value ("{0}" -f $TArule["service"]) )) |Out-Null
  1425. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "accesstype" -Value ("{0}" -f $TArule["accesstype"]) )) |Out-Null
  1426. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "audit-enabled" -Value ("{0}" -f $TArule["audit-enabled"]) )) |Out-Null
  1427. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "datalink-protocol" -Value ("{0}" -f $TArule["datalink-protocol"]) )) |Out-Null
  1428. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "network-protocol" -Value ("{0}" -f $TArule["network-protocol"]) )) |Out-Null
  1429. }
  1430. function Set-PipeRuleNode {
  1431. Param(
  1432. [System.Xml.XmlElement]$Rule,
  1433. [hashtable]$TArule
  1434. )
  1435. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "order" -Value ("{0}" -f $TArule["order"]) )) |Out-Null
  1436. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "enabled" -Value ("{0}" -f $TArule["enabled"]) )) |Out-Null
  1437. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "ruletype" -Value ("{0}" -f $TArule["ruletype"]) )) |Out-Null
  1438. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "service" -Value ("{0}" -f $TArule["service"]) )) |Out-Null
  1439. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "accesstype" -Value ("{0}" -f $TArule["accesstype"]) )) |Out-Null
  1440. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "audit-enabled" -Value ("{0}" -f $TArule["audit-enabled"]) )) |Out-Null
  1441. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "local-ports" -Value "*" )) |Out-Null
  1442. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "remote-ports" -Value "*" )) |Out-Null
  1443. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "local-addrs" -Value ("{0}" -f $TArule["local-addrs"]) )) |Out-Null
  1444. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "remote-addrs" -Value ("{0}" -f $TArule["remote-addrs"]) )) |Out-Null
  1445. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "rule-direction-type" -Value "in" )) |Out-Null
  1446. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "flags" -Value ("{0}" -f $TArule["flags"]) )) |Out-Null
  1447. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "description" -Value ("{0}" -f $TArule["description"]) )) |Out-Null
  1448. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "create-auth-rule" -Value "1" )) |Out-Null
  1449. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "guid" -Value "" )) |Out-Null
  1450. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "owner" -Value ("{0}" -f $TArule["owner"]) )) |Out-Null
  1451. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "rule-activate-times" -Value ("{0}" -f $TArule["rule-activate-times"]) )) |Out-Null
  1452. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd" -Value ("{0}" -f $TArule["on-rule-action-cmd"]) )) |Out-Null
  1453. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd-folder" -Value "" )) |Out-Null
  1454. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd-start-type" -Value "system" )) |Out-Null
  1455. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd-token-type" -Value "user" )) |Out-Null
  1456. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd-beep" -Value ("{0}" -f $TArule["on-rule-action-cmd-beep"]) )) |Out-Null
  1457. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "accessmask" -Value ("{0}" -f $TArule["accessmask"]) )) |Out-Null
  1458. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "reply-on-reject" -Value ("{0}" -f $TArule["reply-on-reject"]) )) |Out-Null
  1459. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "adapters-to-include" -Value ("{0}" -f $TArule["adapters-to-include"]) )) |Out-Null
  1460. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "adapters-to-exclude" -Value ("{0}" -f $TArule["adapters-to-exclude"]) )) |Out-Null
  1461. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "adapters-match" -Value ("{0}" -f $TArule["adapters-match"]) )) |Out-Null
  1462. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "groups" -Value ("{0}" -f $TArule["groups"]) )) |Out-Null
  1463. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "principals" -Value ("{0}" -f $TArule["principals"]) )) |Out-Null
  1464. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "external-subjects" -Value ("{0}" -f $TArule["external-subjects"]) )) |Out-Null
  1465. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "restricted-process-sids" -Value "" )) |Out-Null
  1466. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "is-emergency-rule" -Value "0" )) |Out-Null
  1467. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "pipe-name" -Value ("{0}" -f $TArule["pipe-name"]) )) |Out-Null
  1468. }
  1469. function Set-SmbRuleNode {
  1470. Param(
  1471. [System.Xml.XmlElement]$Rule,
  1472. [hashtable]$TArule
  1473. )
  1474. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "order" -Value ("{0}" -f $TArule["order"]) )) |Out-Null
  1475. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "enabled" -Value ("{0}" -f $TArule["enabled"]) )) |Out-Null
  1476. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "ruletype" -Value ("{0}" -f $TArule["ruletype"]) )) |Out-Null
  1477. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "service" -Value ("{0}" -f $TArule["service"]) )) |Out-Null
  1478. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "accesstype" -Value ("{0}" -f $TArule["accesstype"]) )) |Out-Null
  1479. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "audit-enabled" -Value ("{0}" -f $TArule["audit-enabled"]) )) |Out-Null
  1480. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "local-ports" -Value "" )) |Out-Null
  1481. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "remote-ports" -Value "" )) |Out-Null
  1482. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "local-addrs" -Value ("{0}" -f $TArule["local-addrs"]) )) |Out-Null
  1483. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "remote-addrs" -Value ("{0}" -f $TArule["remote-addrs"]) )) |Out-Null
  1484. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "rule-direction-type" -Value "in" )) |Out-Null
  1485. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "flags" -Value ("{0}" -f $TArule["flags"]) )) |Out-Null
  1486. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "description" -Value "" )) |Out-Null
  1487. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "create-auth-rule" -Value "1" )) |Out-Null
  1488. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "guid" -Value "" )) |Out-Null
  1489. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "owner" -Value ("{0}" -f $TArule["owner"]) )) |Out-Null
  1490. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "rule-activate-times" -Value ("{0}" -f $TArule["rule-activate-times"]) )) |Out-Null
  1491. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd" -Value ("{0}" -f $TArule["on-rule-action-cmd"]) )) |Out-Null
  1492. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd-folder" -Value "" )) |Out-Null
  1493. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd-start-type" -Value "system" )) |Out-Null
  1494. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd-token-type" -Value "user" )) |Out-Null
  1495. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd-beep" -Value ("{0}" -f $TArule["on-rule-action-cmd-beep"]) )) |Out-Null
  1496. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "accessmask" -Value ("{0}" -f $TArule["accessmask"]) )) |Out-Null
  1497. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "reply-on-reject" -Value ("{0}" -f $TArule["reply-on-reject"]) )) |Out-Null
  1498. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "adapters-to-include" -Value ("{0}" -f $TArule["adapters-to-include"]) )) |Out-Null
  1499. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "adapters-to-exclude" -Value ("{0}" -f $TArule["adapters-to-exclude"]) )) |Out-Null
  1500. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "adapters-match" -Value ("{0}" -f $TArule["adapters-match"]) )) |Out-Null
  1501. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "groups" -Value ("{0}" -f $TArule["groups"]) )) |Out-Null
  1502. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "principals" -Value ("{0}" -f $TArule["principals"]) )) |Out-Null
  1503. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "external-subjects" -Value ("{0}" -f $TArule["external-subjects"]) )) |Out-Null
  1504. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "restricted-process-sids" -Value "" )) |Out-Null
  1505. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "is-emergency-rule" -Value "0" )) |Out-Null
  1506. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "folder-path-mask" -Value ("{0}" -f $TArule["folder-path-mask"]) )) |Out-Null
  1507. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "include-subfolders" -Value ("{0}" -f $TArule["include-subfolders"]) )) |Out-Null
  1508. $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "file-name-masks" -Value ("{0}" -f $TArule["file-name-masks"]) )) |Out-Null
  1509. }
  1510. Initialize-Requirements
  1511. if ($PSBoundParameters['OnlyCurrentComputer']) {
  1512. $Script:ScSrvConfigArg = Get-LocalServerQueryArguments
  1513. if( (Get-TAItem -AuthXml $Script:AUTHXML -Path $script:AGENTSPATH|?{$_.ToUpper() -eq $env:COMPUTERNAME}) -ne $null){
  1514. $item = $AUTHXML[$AGENTSPATH].GetEnumerator()|?{$_.Key -eq $env:COMPUTERNAME}
  1515. $AUTHXML[$AGENTSPATH] = @{$item.Key = $item.Value}
  1516. Set-TAUsersAsEveryone -AuthXML $AuthXml
  1517. } else {
  1518. throw 'Íå óäàëîñü íàéòè òåêóùåå èìÿ êîìïüþòåðà â ñïèñêå àãåíòîâ êîíôèãóðàöèè Trust Access.'
  1519. }
  1520. } else {
  1521. $Script:ScSrvConfigArg = Invoke-FnRemoteCommonWrapper -PSsession $Script:SSsession -InvokeExpression 'Get-AuthServerQueryArguments -credential $Credential' -Parameters @{
  1522. Credential = $Script:CREDENTIALS
  1523. }
  1524. $SNSagents = Invoke-FnRemoteCommonWrapper -PSsession $Script:SSsession -InvokeExpression 'Get-AgentList -ScSrvConfigArg $ScSrvConfigArg' -Parameters @{
  1525. ScSrvConfigArg = $ScSrvConfigArg
  1526. }
  1527. $TApcFromRule = (Get-TAItem -AuthXml $Script:AUTHXML -Path $script:USERSPATH) |Where-Object{$_ -match '.+\$@.+'}|ForEach-Object{($_ -split '\$')[0]}
  1528. Test-TAUsersFromRulesInAD
  1529. Test-AgentsOnSecurityServer -TAagents (Get-TAItem -AuthXml $Authxml -Path $script:AGENTSPATH) -AuthSrvAgents $SNSagents -TAagentsFromRule $TApcFromRule
  1530. }
  1531. Import-TARules -AuthXML $AuthXml -ScSrvConfigArg $ScSrvConfigArg
  1532. Trace-message -Msg 'End.'
  1533. }
  1534. End {
  1535. Remove-ScriptVariable
  1536. }