internal PSObject AddFeature(Runspace runSpace, string hostName, string featureName, bool includeAllSubFeature = true, bool restart = false)
        {                       
            Command cmd = new Command("Add-WindowsFeature");
            cmd.Parameters.Add("Name", featureName);

            if (includeAllSubFeature)
            {
                cmd.Parameters.Add("IncludeAllSubFeature", "");
            }
            
            if (restart)
            {
                cmd.Parameters.Add("Restart", "");
            }

            return runSpace.ExecuteRemoteShellCommand(hostName, cmd, PrimaryDomainController).FirstOrDefault();            
        }
        internal void RemoveItemRemote(Runspace runSpace, string hostname, string path, params string[] imports)
        {
            Command rdRapCommand = new Command("Remove-Item");
            rdRapCommand.Parameters.Add("Path", string.Format("\"{0}\"", path));
            rdRapCommand.Parameters.Add("Force", "");
            rdRapCommand.Parameters.Add("Recurse", "");

            runSpace.ExecuteRemoteShellCommand(hostname, rdRapCommand, PrimaryDomainController, imports);
        }
        internal bool IsFeatureInstalled(string hostName, string featureName, Runspace runSpace)
        {
            bool isInstalled = false;            
            Command cmd = new Command("Get-WindowsFeature");
            cmd.Parameters.Add("Name", featureName);
            var feature = runSpace.ExecuteRemoteShellCommand(hostName, cmd, PrimaryDomainController).FirstOrDefault();
            
            if (feature != null)
            {
                isInstalled = (bool)RdsRunspaceExtensions.GetPSObjectProperty(feature, "Installed");
            }            

            return isInstalled;
        }
        internal void CreateRdRapForce(Runspace runSpace, string gatewayHost, string policyName, string collectionName, List<string> groups)
        {            
            //New-Item -Path "RDS:\GatewayServer\RAP" -Name "Allow Connections To Everywhere" -UserGroups "Administrators@." -ComputerGroupType 1
            //Set-Item -Path "RDS:\GatewayServer\RAP\Allow Connections To Everywhere\PortNumbers" -Value 3389,3390

            if (ItemExistsRemote(runSpace, gatewayHost, Path.Combine(RapPath, policyName)))
            {
                RemoveRdRap(runSpace, gatewayHost, policyName);
            }
            
            var userGroupParametr = string.Format("@({0})", string.Join(",", groups.Select(x => string.Format("\"{0}@{1}\"", x, RootDomain)).ToArray()));
            var computerGroupParametr = string.Format("\"{0}@{1}\"", GetComputersGroupName(collectionName), RootDomain);

            Command rdRapCommand = new Command("New-Item");
            rdRapCommand.Parameters.Add("Path", string.Format("\"{0}\"", RapPath));
            rdRapCommand.Parameters.Add("Name", string.Format("\"{0}\"", policyName));
            rdRapCommand.Parameters.Add("UserGroups", userGroupParametr);            
            rdRapCommand.Parameters.Add("ComputerGroupType", 1);
            rdRapCommand.Parameters.Add("ComputerGroup", computerGroupParametr);            

            object[] errors;

            for (int i = 0; i < 3; i++)
            {
                Log.WriteWarning(string.Format("Adding RD RAP ... {0}\r\nGateway Host\t{1}\r\nUser Group\t{2}\r\nComputer Group\t{3}", i + 1, gatewayHost, userGroupParametr, computerGroupParametr));
                runSpace.ExecuteRemoteShellCommand(gatewayHost, rdRapCommand, PrimaryDomainController, out errors, RdsModuleName);

                if (errors == null || !errors.Any())
                {
                    Log.WriteWarning("RD RAP Added Successfully");
                    break;
                }
                else
                {
                    Log.WriteWarning(string.Join("\r\n", errors.Select(e => e.ToString()).ToArray()));
                }
            }            
        }        
        private object[] ImportCertificate(Runspace runspace, string hostName, string password, string certificatePath, string thumbprint)
        {
            var scripts = new List<string>
            {                
                string.Format("$mypwd = ConvertTo-SecureString -String {0} -Force –AsPlainText", password),
                string.Format("Import-PfxCertificate –FilePath \"{0}\" cert:\\localMachine\\my -Password $mypwd", certificatePath),
                string.Format("$cert = Get-Item cert:\\LocalMachine\\My\\{0}", thumbprint),
                string.Format("$path = (Get-WmiObject -class \"Win32_TSGeneralSetting\" -Namespace root\\cimv2\\terminalservices -Filter \"TerminalName='RDP-tcp'\").__path"),
                string.Format("Set-WmiInstance -Path $path -argument @{0}", string.Format("{{SSLCertificateSHA1Hash=\"{0}\"}}", thumbprint))
            };

            object[] errors = null;
            runspace.ExecuteRemoteShellCommand(hostName, scripts, PrimaryDomainController, out errors);

            return errors;
        }
        internal void CreateCentralNpsPolicy(Runspace runSpace, string centralNpshost, string policyName, string collectionName, string organizationId)
        {
            var showCmd = new Command("netsh nps show np");

            var showResult = runSpace.ExecuteRemoteShellCommand(centralNpshost, showCmd, PrimaryDomainController);
            var processingOrders = showResult.Where(x => Convert.ToString(x).ToLower().Contains("processing order")).Select(x => Convert.ToString(x));
            var count = 0;

            foreach(var processingOrder in processingOrders)
            {
                var order = Convert.ToInt32(processingOrder.Remove(0, processingOrder.LastIndexOf("=") + 1).Replace(" ", ""));

                if (order > count)
                {
                    count = order;
                }
            }

            var userGroupAd = ActiveDirectoryUtils.GetADObject(GetUsersGroupPath(organizationId, collectionName));
            var userGroupSid = (byte[])ActiveDirectoryUtils.GetADObjectProperty(userGroupAd, "objectSid");
            var addCmdString = string.Format(AddNpsString, policyName.Replace(" ", "_"), count + 1, ConvertByteToStringSid(userGroupSid));
            Command addCmd = new Command(addCmdString);

            var result = runSpace.ExecuteRemoteShellCommand(centralNpshost, addCmd, PrimaryDomainController);
        }
        internal void CreateRdCapForce(Runspace runSpace, string gatewayHost, string policyName, string collectionName, List<string> groups)
        {
            //New-Item -Path "RDS:\GatewayServer\CAP" -Name "Allow Admins" -UserGroups "Administrators@." -AuthMethod 1
            //Set-Item -Path "RDS:\GatewayServer\CAP\Allow Admins\SessionTimeout" -Value 480 -SessionTimeoutAction 0

            if (ItemExistsRemote(runSpace, gatewayHost, Path.Combine(CapPath, policyName)))
            {
                RemoveRdCap(runSpace, gatewayHost, policyName);
            }

            var userGroupParametr = string.Format("@({0})",string.Join(",", groups.Select(x => string.Format("\"{0}@{1}\"", x, RootDomain)).ToArray()));

            Command rdCapCommand = new Command("New-Item");
            rdCapCommand.Parameters.Add("Path", string.Format("\"{0}\"", CapPath));
            rdCapCommand.Parameters.Add("Name", string.Format("\"{0}\"", policyName));
            rdCapCommand.Parameters.Add("UserGroups", userGroupParametr);
            rdCapCommand.Parameters.Add("AuthMethod", 1);

            runSpace.ExecuteRemoteShellCommand(gatewayHost, rdCapCommand, PrimaryDomainController, RdsModuleName);
        }
        private void SetPolicyPermissions(Runspace runspace, string gpoName, DirectoryEntry entry, DirectoryEntry collectionComputersEntry)
        {
            var scripts = new List<string>
            {
                string.Format("Set-GPPermissions -Name {0} -Replace -PermissionLevel None -TargetName 'Authenticated Users' -TargetType group", gpoName),
                string.Format("Set-GPPermissions -Name {0} -PermissionLevel gpoapply -TargetName {1} -TargetType group", gpoName, string.Format("'{0}'", ActiveDirectoryUtils.GetADObjectProperty(entry, "sAMAccountName").ToString())),
                string.Format("Set-GPPermissions -Name {0} -PermissionLevel gpoapply -TargetName {1} -TargetType group", gpoName, string.Format("'{0}'", ActiveDirectoryUtils.GetADObjectProperty(collectionComputersEntry, "sAMAccountName").ToString()))
            };

            object[] errors = null;
            runspace.ExecuteRemoteShellCommand(PrimaryDomainController, scripts, PrimaryDomainController, out errors);
        }
        private string CreateAndLinkPolicy(Runspace runspace, string gpoName, string organizationId, string collectionName)
        {
            string gpoId = null;

            try
            {
                var entry = new DirectoryEntry(GetOrganizationPath(organizationId));
                var distinguishedName = string.Format("\"{0}\"", ActiveDirectoryUtils.GetADObjectProperty(entry, "DistinguishedName"));

                Command cmd = new Command("New-GPO");
                cmd.Parameters.Add("Name", gpoName);

                Collection<PSObject> result = runspace.ExecuteRemoteShellCommand(PrimaryDomainController, cmd, PrimaryDomainController);

                if (result != null && result.Count > 0)
                {
                    PSObject gpo = result[0];
                    gpoId = ((Guid)RdsRunspaceExtensions.GetPSObjectProperty(gpo, "Id")).ToString("B");

                }

                cmd = new Command("New-GPLink");
                cmd.Parameters.Add("Name", gpoName);
                cmd.Parameters.Add("Target", distinguishedName);

                runspace.ExecuteRemoteShellCommand(PrimaryDomainController, cmd, PrimaryDomainController);
            }
            catch (Exception)
            {
                gpoId = null;
                throw;
            }

            return gpoId;
        }
Beispiel #10
0
        private void DeleteGpo(Runspace runspace, string gpoName)
        {
            Command cmd = new Command("Remove-GPO");
            cmd.Parameters.Add("Name", gpoName);

            Collection<PSObject> result = runspace.ExecuteRemoteShellCommand(PrimaryDomainController, cmd, PrimaryDomainController);
        }
Beispiel #11
0
        private void ExcludeAdminsFromUsersPolicy(Runspace runspace, string gpoId, string collectionName)
        {
            var scripts = new List<string>
            {
                string.Format("$adgpo = [ADSI]\"{0}\"", GetGpoPath(gpoId)),
                string.Format("$rule = New-Object System.DirectoryServices.ActiveDirectoryAccessRule([System.Security.Principal.NTAccount]\"{0}\\{1}\",\"ExtendedRight\",\"Deny\",[GUID]\"edacfd8f-ffb3-11d1-b41d-00a0c968f939\")",
                    RootDomain.Split('.').First(), GetLocalAdminsGroupName(collectionName)),
                string.Format("$acl = $adgpo.ObjectSecurity"),
                string.Format("$acl.AddAccessRule($rule)"),
                string.Format("$adgpo.CommitChanges()")
            };

            object[] errors = null;
            runspace.ExecuteRemoteShellCommand(PrimaryDomainController, scripts, PrimaryDomainController, out errors);
        }
Beispiel #12
0
        private void SetRegistryValue(Runspace runspace, string key, string gpoName, string value, string valueName, string type)
        {
            Command cmd = new Command("Set-GPRegistryValue");
            cmd.Parameters.Add("Name", gpoName);
            cmd.Parameters.Add("Key", string.Format("\"{0}\"", key));
            cmd.Parameters.Add("Value", value);
            cmd.Parameters.Add("ValueName", valueName);
            cmd.Parameters.Add("Type", type);

            Collection<PSObject> result = runspace.ExecuteRemoteShellCommand(PrimaryDomainController, cmd, PrimaryDomainController);
        }
Beispiel #13
0
        private void CheckPolicySecurityFiltering(Runspace runspace, string gpoName, DirectoryEntry collectionComputersEntry)
        {
            var scripts = new List<string>{
                string.Format("Get-GPPermissions -Name {0} -TargetName {1} -TargetType group", gpoName, string.Format("'{0}'", ActiveDirectoryUtils.GetADObjectProperty(collectionComputersEntry, "sAMAccountName").ToString()))
            };

            object[] errors = null;
            runspace.ExecuteRemoteShellCommand(PrimaryDomainController, scripts, PrimaryDomainController, out errors);

            if (errors != null && errors.Any())
            {
                scripts = new List<string>{
                    string.Format("Set-GPPermissions -Name {0} -PermissionLevel gpoapply -TargetName {1} -TargetType group", gpoName, string.Format("'{0}'", ActiveDirectoryUtils.GetADObjectProperty(collectionComputersEntry, "sAMAccountName").ToString()))
                };
            }

            runspace.ExecuteRemoteShellCommand(PrimaryDomainController, scripts, PrimaryDomainController, out errors);
        }
Beispiel #14
0
        private void RemoveGroupFromLocalAdmin(string fqdnName, string hostName, string groupName, Runspace runspace)
        {            
            var scripts = new List<string>
            {
                string.Format("$GroupObj = [ADSI]\"WinNT://{0}/{1}\"", hostName, LocalAdministratorsGroupName),
                string.Format("$GroupObj.Remove(\"WinNT://{0}/{1}\")", ServerSettings.ADRootDomain, RDSHelpDeskGroup),
                string.Format("$GroupObj.Remove(\"WinNT://{0}/{1}\")", ServerSettings.ADRootDomain, groupName)
            };

            object[] errors = null;
            runspace.ExecuteRemoteShellCommand(fqdnName, scripts, PrimaryDomainController, out errors);
        }
Beispiel #15
0
        internal bool ItemExistsRemote(Runspace runSpace, string hostname,string path)
        {
            Command testPathCommand = new Command("Test-Path");
            testPathCommand.Parameters.Add("Path", string.Format("\"{0}\"", path));

            var testPathResult = runSpace.ExecuteRemoteShellCommand(hostname, testPathCommand, PrimaryDomainController, RdsModuleName).First();

            var result = Convert.ToBoolean(testPathResult.ToString());

            return result;
        }
Beispiel #16
0
        private string GetPolicyId(Runspace runspace, string gpoName)
        {
            string gpoId = null;

            try
            {
                Command cmd = new Command("Get-GPO");
                cmd.Parameters.Add("Name", gpoName);

                Collection<PSObject> result = runspace.ExecuteRemoteShellCommand(PrimaryDomainController, cmd, PrimaryDomainController);

                if (result != null && result.Count > 0)
                {
                    PSObject gpo = result[0];
                    gpoId = ((Guid)RdsRunspaceExtensions.GetPSObjectProperty(gpo, "Id")).ToString("B");
                }
            }
            catch (Exception)
            {
                gpoId = null;

                throw;
            }

            return gpoId;
        }
Beispiel #17
0
        private bool CheckPendingReboot(Runspace runspace, string serverName, string registryPath, string registryKey)
        {
            Command cmd = new Command("Get-ItemProperty");
            cmd.Parameters.Add("Path", string.Format("\"{0}\"", registryPath));
            cmd.Parameters.Add("Name", registryKey);
            cmd.Parameters.Add("ErrorAction", "SilentlyContinue");

            var feature = runspace.ExecuteRemoteShellCommand(serverName, cmd, PrimaryDomainController).FirstOrDefault();

            if (feature != null)
            {
                return true;
            }

            return false;
        }
Beispiel #18
0
 private void AddAdGroupToLocalAdmins(Runspace runspace, string hostName, string samAccountName)
 {                                    
     var scripts = new List<string>
     {
         string.Format("$GroupObj = [ADSI]\"WinNT://{0}/{1}\"", hostName, LocalAdministratorsGroupName),
         string.Format("$GroupObj.Add(\"WinNT://{0}/{1}\")", ServerSettings.ADRootDomain, samAccountName)
     };
     
     object[] errors = null;
     runspace.ExecuteRemoteShellCommand(hostName, scripts, PrimaryDomainController, out errors);                 
 }
Beispiel #19
0
        internal void RemoveNpsPolicy(Runspace runSpace, string centralNpshost, string policyName)
        {
            var removeCmd = new Command(string.Format("netsh nps delete np {0}", policyName.Replace(" ", "_")));

            var removeResult = runSpace.ExecuteRemoteShellCommand(centralNpshost, removeCmd, PrimaryDomainController);
        }
Beispiel #20
0
        private void RemoveCertificate(Runspace runspace, string hostName, string thumbprint)
        {
            var scripts = new List<string>
            {
                string.Format("Remove-Item -Path cert:\\LocalMachine\\My\\{0}", thumbprint)
            };

            object[] errors = null;
            runspace.ExecuteRemoteShellCommand(hostName, scripts, PrimaryDomainController, out errors);
        }
Beispiel #21
0
        private void CreateHelpDeskRdCapForce(Runspace runSpace, string gatewayHost)
        {                        
            if (ItemExistsRemote(runSpace, gatewayHost, Path.Combine(CapPath, RDSHelpDeskRdCapPolicyName)))
            {
                return;
            }

            var userGroupParameter = string.Format("@({0})", string.Format("\"{0}@{1}\"", RDSHelpDeskGroup, RootDomain));

            Command rdCapCommand = new Command("New-Item");
            rdCapCommand.Parameters.Add("Path", string.Format("\"{0}\"", CapPath));
            rdCapCommand.Parameters.Add("Name", string.Format("\"{0}\"", RDSHelpDeskRdCapPolicyName));
            rdCapCommand.Parameters.Add("UserGroups", userGroupParameter);
            rdCapCommand.Parameters.Add("AuthMethod", 1);

            runSpace.ExecuteRemoteShellCommand(gatewayHost, rdCapCommand, PrimaryDomainController, RdsModuleName);
        }
Beispiel #22
0
        private void CreateHelpDeskRdRapForce(Runspace runSpace, string gatewayHost)
        {
            if (ItemExistsRemote(runSpace, gatewayHost, Path.Combine(RapPath, RDSHelpDeskRdRapPolicyName)))
            {
                return;
            }

            var userGroupParameter = string.Format("@({0})", string.Format("\"{0}@{1}\"", RDSHelpDeskGroup, RootDomain));
            var computerGroupParameter = string.Format("\"{0}@{1}\"", RDSHelpDeskComputerGroup, RootDomain);

            Command rdRapCommand = new Command("New-Item");
            rdRapCommand.Parameters.Add("Path", string.Format("\"{0}\"", RapPath));
            rdRapCommand.Parameters.Add("Name", string.Format("\"{0}\"", RDSHelpDeskRdRapPolicyName));
            rdRapCommand.Parameters.Add("UserGroups", userGroupParameter);
            rdRapCommand.Parameters.Add("ComputerGroupType", 1);
            rdRapCommand.Parameters.Add("ComputerGroup", computerGroupParameter);

            object[] errors;

            for (int i = 0; i < 3; i++)
            {                
                runSpace.ExecuteRemoteShellCommand(gatewayHost, rdRapCommand, PrimaryDomainController, out errors, RdsModuleName);

                if (errors == null || !errors.Any())
                {
                    Log.WriteWarning("RD RAP Added Successfully");
                    break;
                }
                else
                {
                    Log.WriteWarning(string.Join("\r\n", errors.Select(e => e.ToString()).ToArray()));
                }
            }
        }