Esempio n. 1
0
        private void PublishFile(byte[] srcBytes, string dstPath, ServerConfig server)
        {
            const string publishScript = @"Param([string]$path, $data)
    $path = $ExecutionContext.InvokeCommand.ExpandString($path)
    $dir = Split-Path $path

    $dirInfo = [IO.Directory]::CreateDirectory($dir)
    if(Test-Path $path) {
        [IO.File]::Delete($path)
    }

    [IO.FileStream]$filestream = [IO.File]::OpenWrite( $path )
    $filestream.Write( $data, 0, $data.Length )
    $filestream.Close()
    write-host ""File $path created""
";

            var scriptParameters = new List <CommandParameter>
            {
                new CommandParameter("path", dstPath),
                new CommandParameter("data", srcBytes)
            };
            var scriptExecutor = new PowerShellExecutor(server)
            {
                LoadConDepModule = false
            };

            scriptExecutor.Execute(publishScript, parameters: scriptParameters, logOutput: false);
        }
Esempio n. 2
0
        private void EnableClientCredSSP()
        {
            var localPsExecutor = new PowerShellExecutor();
            var result          = localPsExecutor.ExecuteLocal(_server, @"get-item -Path wsman:\localhost\Client\Auth\CredSSP",
                                                               mod => mod.LoadConDepModule = false).ToList();

            if (result.Count != 1)
            {
                throw new ConDepCredSSPException();
            }

            bool credSspEnabled;

            if (!bool.TryParse(result.First().Value, out credSspEnabled))
            {
                throw new ConDepCredSSPException("Unable to retreive CredSSP value for this client.");
            }

            if (!credSspEnabled)
            {
                Logger.Verbose("CredSSP for client not enabled. Temporarly enabling now for this execution.");
                localPsExecutor.ExecuteLocal(_server, @"set-item -path wsman:\localhost\Client\Auth\CredSSP -value 'true'",
                                             mod => mod.LoadConDepModule = false);

                _cleanupFunctions.Add(() => localPsExecutor.ExecuteLocal(_server,
                                                                         @"set-item -path wsman:\localhost\Client\Auth\CredSSP -value 'false'", mod => mod.LoadConDepModule = false));
            }

            EnableFreshCredentials(REG_KEY_ALLOW_FRESH_CREDENTIALS);
            if (!IsDomainUser())
            {
                EnableFreshCredentials(REG_KEY_ALLOW_FRESH_CREDENTIALS_WHEN_NTLM_ONLY);
            }
        }
Esempio n. 3
0
        private void EnableServerCredSSP()
        {
            var executor = new PowerShellExecutor();
            var result   = executor.Execute(_server, @"get-item -path wsman:\localhost\Service\Auth\CredSSP",
                                            mod => mod.LoadConDepModule = false, logOutput: false).ToList();

            if (result.Count != 1)
            {
                throw new ConDepCredSSPException();
            }

            bool credSspEnabled;

            if (!bool.TryParse(result.First().Value, out credSspEnabled))
            {
                throw new ConDepCredSSPException("Unable to retreive CredSSP value from server.");
            }

            if (!credSspEnabled)
            {
                Logger.Verbose("CredSSP for server not enabled. Temporarly enabling now for this execution.");
                executor.Execute(_server, @"set-item -path wsman:\localhost\Service\Auth\CredSSP -value ""true"" -force",
                                 mod => mod.LoadConDepModule = false, logOutput: false);
                _cleanupFunctions.Add(() => executor.Execute(_server,
                                                             @"set-item -path wsman:\localhost\Service\Auth\CredSSP -value ""false"" -force",
                                                             mod => mod.LoadConDepModule = false, logOutput: false));
            }
        }
Esempio n. 4
0
        private void EnableClientCredSSP()
        {
            var localPsExecutor = new PowerShellExecutor();
            var result = localPsExecutor.ExecuteLocal(_server, @"get-item -Path wsman:\localhost\Client\Auth\CredSSP", mod => mod.LoadConDepModule = false).ToList();

            if (result.Count != 1) throw new ConDepCredSSPException();

            bool credSspEnabled;
            if (!Boolean.TryParse(result.First().Value, out credSspEnabled))
            {
                throw new ConDepCredSSPException("Unable to retreive CredSSP value for this client.");
            }

            if (!credSspEnabled)
            {
                Logger.Verbose("CredSSP for client not enabled. Temporarly enabling now for this execution.");
                localPsExecutor.ExecuteLocal(_server, @"set-item -path wsman:\localhost\Client\Auth\CredSSP -value 'true'", mod => mod.LoadConDepModule = false);

                _cleanupFunctions.Add(() => localPsExecutor.ExecuteLocal(_server, @"set-item -path wsman:\localhost\Client\Auth\CredSSP -value 'false'", mod => mod.LoadConDepModule = false));
            }

            EnableFreshCredentials(REG_KEY_ALLOW_FRESH_CREDENTIALS);
            if(!IsDomainUser())
            {
                EnableFreshCredentials(REG_KEY_ALLOW_FRESH_CREDENTIALS_WHEN_NTLM_ONLY);
            }
        }
Esempio n. 5
0
        public static void StartNode(ServerConfig server)
        {
            var startServiceExecutor = new PowerShellExecutor(server)
            {
                LoadConDepNodeModule = true, LoadConDepModule = false
            };

            startServiceExecutor.Execute("Start-ConDepNode", logOutput: false);
        }
        public ConDepNodePublisher(string srcPath, string destPath, ConDepNodeUrl url, PowerShellExecutor psExecutor)
        {
            _srcPath = srcPath;
            _destPath = destPath;
            _url = url;
            _psExecutor = psExecutor;

            //_psExecutor.LoadConDepNodeModule = true;
            //_psExecutor.LoadConDepModule = false;
        }
        public override void Execute(ServerConfig server, IReportStatus status, ConDepSettings settings, CancellationToken token)
        {
            var createFolderScript = string.Format(@"
            if(!(Test-Path ""{0}""))
            {{
            New-Item -ItemType directory -Path ""{0}""
            }}
            ", _path);

            var psExecutor = new PowerShellExecutor();
            psExecutor.Execute(server, createFolderScript);
        }
 private bool ConditionFulfilled(ServerConfig server)
 {
     if (string.IsNullOrEmpty(_conditionScript))
     {
         return _condition(server.GetServerInfo()) == _expectedConditionResult;
     }
     else
     {
         var psExecutor = new PowerShellExecutor();
         var result = psExecutor.Execute(server, _conditionScript);
         return result.First().ToString() == "True";
     }
 }
Esempio n. 9
0
        private dynamic GetNodeState(ServerConfig server)
        {
            var nodeCheckExecutor = new PowerShellExecutor(server)
            {
                LoadConDepModule = false, LoadConDepNodeModule = true
            };
            var nodeCheckResult =
                nodeCheckExecutor.Execute(
                    string.Format("Get-ConDepNodeState \"{0}\" \"{1}\"", _destPath, FileHashGenerator.GetFileHash(_srcPath)),
                    logOutput: true);

            return(nodeCheckResult.Single(psObject => psObject.ConDepResult != null).ConDepResult);
        }
Esempio n. 10
0
        public void TestThat_Something()
        {
            ConDep.Dsl.Logging.Logger.Initialize(CreateMemoryLogger());

            var executor = new PowerShellExecutor();
            var result = executor.ExecuteLocal(new ServerConfig(), "$psVersionTable.PSVersion.Major", load => load.LoadConDepModule = false);

            //var versionResult = GetExecutionResult();

            ////---------------------------
            var version = result.First();
            //dynamic version = ((Collection<PSObject>)versionResult).First();
            Assert.That(version >= 3);
        }
Esempio n. 11
0
        public override Result Execute(IOfferRemoteOperations remote, ServerConfig server, ConDepSettings settings, CancellationToken token)
        {
            token.ThrowIfCancellationRequested();

            Logger.WithLogSection(string.Format("Stopping ConDepNode on server {0}", server.Name), () =>
            {
                var executor = new PowerShellExecutor();
                executor.Execute(server, "Stop-ConDepNode", mod =>
                {
                    mod.LoadConDepModule = false;
                    mod.LoadConDepNodeModule = true;
                }, logOutput: false);
            });

            return Result.SuccessUnChanged();
        }
Esempio n. 12
0
 private bool ValidatePowerShellVersion(ServerConfig currentServer)
 {
     return(Logger.WithLogSection("Validating remote PowerShell version (must be 3.0 or higher)", () =>
     {
         var executor = new PowerShellExecutor(currentServer)
         {
             LoadConDepModule = false
         };
         var versionResult = executor.Execute("$psVersionTable.PSVersion.Major", logOutput: false);
         if (versionResult == null)
         {
             Logger.Error("Unable to get remote PowerShell version.");
             return false;
         }
         var version = versionResult.First();
         Logger.Info(string.Format("Remote PowerShell version is {0}", version));
         return version >= 3;
     }));
 }
Esempio n. 13
0
        private void DeployNode(ServerConfig server)
        {
            var byteArray  = File.ReadAllBytes(_srcPath);
            var parameters = new List <CommandParameter>
            {
                new CommandParameter("path", _destPath),
                new CommandParameter("data", byteArray),
                new CommandParameter("url", _url.ListenUrl),
                new CommandParameter("port", _url.Port),
            };

            var executor = new PowerShellExecutor(server)
            {
                LoadConDepNodeModule = true, LoadConDepModule = false
            };

            executor.Execute("Param([string]$path, $data, $url, $port)\n  Add-ConDepNode $path $data $url $port", parameters: parameters,
                             logOutput: false);
        }
        public override void Execute(ServerConfig server, IReportStatus status, ConDepSettings settings, CancellationToken token)
        {
            var canPingServer = CanPingServer(server);
            var startNodeOperation = new StartConDepNodeOperation();

            Logger.Verbose(string.Format("Can {0}use ping for validation", canPingServer ? "" : "NOT "));

            Logger.WithLogSection("Restarting", () =>
            {
                Logger.Info(string.Format("Executing restart command on server {0}", server.Name));
                var powershellExecutor = new PowerShellExecutor();
                powershellExecutor.Execute(server, string.Format("cmd /c \"shutdown /r /t {0}\"", _delayInSeconds));

                if (canPingServer)
                {
                    Logger.Verbose("Waiting for ping to fail");
                    Logger.Info("Waiting for server to stop responding");
                    WaitForPing(WaitForStatus.Failure, server);
                    Logger.Info("Server stopped responding");
                    Logger.Verbose("Waiting for ping to Succeed");
                    Logger.Info("Waiting for server to respond again");
                    WaitForPing(WaitForStatus.Success, server);
                    Logger.Info("Server started to respond");
                }
                else
                {
                    Logger.Verbose("Waiting for WinRM to fail");
                    Logger.Info("Waiting for server to stop responding");
                    WaitForWinRm(WaitForStatus.Failure, server);
                    Logger.Info("Server stopped responding");
                }
                Logger.Verbose("Waiting for WinRM to succeed");
                Logger.Info("Waiting for server to respond to PowerShell commands");
                WaitForWinRm(WaitForStatus.Success, server);
                Logger.Info("Serve successfully responds to PowerShell commands");
                Logger.Info("Computer successfully restarted");
                Logger.WithLogSection("Starting ConDepNode", () => startNodeOperation.Execute(server, status, settings, token));
            });
        }
        private dynamic GetNodeState(ServerConfig server)
        {
            var nodeCheckExecutor = new PowerShellExecutor();
            var nodeCheckResult =
                nodeCheckExecutor.Execute(server,
                    string.Format("Get-ConDepNodeState \"{0}\" \"{1}\"", _destPath, FileHashGenerator.GetFileHash(_srcPath)),
                    mod =>
                    {
                        mod.LoadConDepModule = false;
                        mod.LoadConDepNodeModule = true;
                    },
                    logOutput: true);

            return nodeCheckResult.Single(psObject => psObject.ConDepResult != null).ConDepResult;
        }
Esempio n. 16
0
        private bool NeedToDeployScript(ServerConfig server, string localFile)
        {
            const string script         = @"Param($fileWithHash, $dir)
$dir = $ExecutionContext.InvokeCommand.ExpandString($dir)

$conDepReturnValues = New-Object PSObject -Property @{         
    ConDepResult    = New-Object PSObject -Property @{
		Files = $null
    }                 
}                  

function Get-ConDepFileHash($path) {
    if(Test-Path $path) {
        $md5 = [System.Security.Cryptography.MD5]::Create()
        $hash = [System.BitConverter]::ToString($md5.ComputeHash([System.IO.File]::ReadAllBytes($path)))
        return $hash.Replace(""-"", """")
    }
    else {
        return """"
    }
}

$returnValues = @()

$hash = Get-ConDepFileHash (Join-Path -path $dir -childpath $($fileWithHash.Item1))
$returnValues += @{
	FileName = $fileWithHash.Item1
	IsEqual = ($hash -eq $fileWithHash.Item2)
}

$conDepReturnValues.ConDepResult.Files = $returnValues
return $conDepReturnValues
";
            var          scriptExecutor = new PowerShellExecutor(server)
            {
                LoadConDepModule = false
            };

            var scriptParameters = new List <CommandParameter>
            {
                new CommandParameter("fileWithHash", new Tuple <string, string>(Path.GetFileName(localFile), FileHashGenerator.GetFileHash(localFile))),
                new CommandParameter("dir", server.GetServerInfo().ConDepNodeScriptsFolder)
            };

            var scriptResult = scriptExecutor.Execute(script, logOutput: false, parameters: scriptParameters);

            foreach (var psObject in scriptResult)
            {
                if (psObject.ConDepResult == null || psObject.ConDepResult.Files == null)
                {
                    continue;
                }

                var remoteFilesArray = ((PSObject)psObject.ConDepResult.Files).BaseObject as ArrayList;
                var remoteFiles      = remoteFilesArray.Cast <dynamic>().Select(remoteFile => remoteFile);

                return(remoteFiles.Any(remoteFile => !remoteFile.IsEqual && remoteFile.FileName == Path.GetFileName(localFile)));
            }

            return(false);
        }
 public DotNetFrameworkHarvester(PowerShellExecutor executor)
 {
     _executor = executor;
 }
 public DotNetFrameworkHarvester()
 {
     _executor = new PowerShellExecutor();
 }
Esempio n. 19
0
 protected RemoteCodeOperation(IPublishFiles filePublisher, PowerShellExecutor psExecutor)
 {
     _filePublisher = filePublisher;
     _psExecutor = psExecutor;
 }
 public override void Execute(ServerConfig server, IReportStatus status, ConDepSettings settings, CancellationToken token)
 {
     var psExecutor = new PowerShellExecutor();
     psExecutor.Execute(server, string.Format("[Environment]::SetEnvironmentVariable(\"{0}\", \"{1}\", \"{2}\")", _name, _value, _target));
 }
 private void ExecuteCommand(string cmd, ServerConfig server)
 {
     var psExec = new PowerShellExecutor();
     if (_values != null)
     {
         if (_values.UseCredSSP) psExec.UseCredSSP = true;
     }
     psExec.Execute(server, cmd, mod =>
     {
         mod.LoadConDepDotNetLibrary = _values == null || _values.RequireRemoteLib;
     });
 }
Esempio n. 22
0
 public NetworkHarvester(PowerShellExecutor executor)
 {
     _executor = executor;
 }
Esempio n. 23
0
 public NetworkHarvester()
 {
     _executor = new PowerShellExecutor();
 }
 public RemoteServerValidator(IEnumerable<ServerConfig> servers, ServerInfoHarvester serverInfoHarvester, PowerShellExecutor psExecutor)
 {
     _servers = servers;
     _serverInfoHarvester = serverInfoHarvester;
     _psExecutor = psExecutor;
 }
 public OperatingSystemHarvester()
 {
     _executor = new PowerShellExecutor();
 }
Esempio n. 26
0
        private void EnableServerCredSSP()
        {
            var executor = new PowerShellExecutor();
            var result = executor.Execute(_server, @"get-item -path wsman:\localhost\Service\Auth\CredSSP", mod => mod.LoadConDepModule = false, logOutput: false).ToList();

            if (result.Count != 1) throw new ConDepCredSSPException();

            bool credSspEnabled;
            if (!Boolean.TryParse(result.First().Value, out credSspEnabled))
            {
                throw new ConDepCredSSPException("Unable to retreive CredSSP value from server.");
            }

            if (!credSspEnabled)
            {
                Logger.Verbose("CredSSP for server not enabled. Temporarly enabling now for this execution.");
                executor.Execute(_server, @"set-item -path wsman:\localhost\Service\Auth\CredSSP -value ""true"" -force", mod => mod.LoadConDepModule = false, logOutput: false);
                _cleanupFunctions.Add(() => executor.Execute(_server, @"set-item -path wsman:\localhost\Service\Auth\CredSSP -value ""false"" -force", mod => mod.LoadConDepModule = false, logOutput: false));
            }
        }
 public OperatingSystemHarvester(PowerShellExecutor executor)
 {
     _executor = executor;
 }
Esempio n. 28
0
        private void ConfigureSsl(ServerConfig server)
        {
            var resource = PfxInstallerResource.PfxInstallerScript;
            var script   = ConDepResourceFiles.GetResourceText(GetType().Assembly, resource);

            var dstPathDos = Path.Combine(server.GetServerInfo().TempFolderDos, "node.con-dep.net.pfx");
            var dstPathPs  = Path.Combine(server.GetServerInfo().TempFolderPowerShell, "node.con-dep.net.pfx");

            var certBytes = ConDepResourceFiles.GetResourceBytes(GetType().Assembly,
                                                                 new ConDepResource
            {
                Resource  = "node.con-dep.net.pfx",
                Namespace = typeof(ConDepResourceFiles).Namespace
            });

            var executor = new PowerShellExecutor(server)
            {
                LoadConDepModule = false
            };

            var scriptResult = executor.Execute(string.Format(@"
$conDepReturnValues = New-Object PSObject -Property @{{         
    ConDepResult    = $false 
}}     

$cert = Get-ChildItem Cert:\LocalMachine\My\{0} -ErrorAction SilentlyContinue
$conDepReturnValues.ConDepResult = !($cert -eq $null)
return $conDepReturnValues
", CERT_THUMBPRINT), logOutput: false);

            var certExist = false;

            foreach (var psObject in scriptResult)
            {
                if (psObject.ConDepResult == null)
                {
                    continue;
                }

                if (psObject.ConDepResult)
                {
                    certExist = true;
                }
            }

            if (!certExist)
            {
                Logger.Info("No SSL cert for ConDepNode found. Publishing now.");
                PublishFile(certBytes, dstPathPs, server);

                executor.Execute(script, new List <CommandParameter>
                {
                    new CommandParameter("filePath", dstPathDos),
                    new CommandParameter("password", CERT_PASS),
                });
                var cmd = string.Format(@"
$certThumbprint = ""{1}""
$appId = ""{2}""
netsh http add sslcert ipport=0.0.0.0:{0} certhash=$certThumbprint appid=$appId", _url.Port, CERT_THUMBPRINT, APP_ID);
                executor.Execute(cmd, logOutput: false);
                Logger.Info("SSL cert for ConDepNode published.");
            }
        }
Esempio n. 29
0
 public PreRemoteOps(PowerShellExecutor psExecutor)
 {
     _psExecutor = psExecutor;
 }