public void Test_Vagrant_Connect() { SshConnectionInfo input = UserInput; SshShell shell = new SshShell(input.Host, input.User); if (input.Pass != null) { shell.Password = input.Pass; } if (input.IdentityFile != null) { shell.AddIdentityFile(input.IdentityFile); } //This statement must be prior to connecting shell.RedirectToConsole(); Console.Write("Connecting..."); shell.Connect(); Console.WriteLine("OK"); // SSH-2.0-OpenSSH_6.6.1p1 Ubuntu-2ubuntu2 Console.WriteLine("server=" + shell.ServerVersion); SshExec shellExec = null; if (shell.ShellOpened) { // shell.Close(); shellExec = SshExec.Clone(shell); // new SshExec(shell.Host, shell.Username, shell.Password); shellExec.Connect(); } if (shellExec != null && shellExec.Connected) { var session = shellExec.Session; var channel = shellExec.Channel; Console.WriteLine(session); Console.WriteLine(channel); var stream = shellExec.RunCommandEx("ls -l", true); // = shell.StreamASCII(); while (stream.MoveNext()) { Console.WriteLine(stream.Current); } System.Threading.Thread.Sleep(500); } Console.Write("Disconnecting..."); if (shellExec != null) { shellExec.Close(); } Console.WriteLine("OK"); }
public void Connect() { try { shell.Connect(); while (!shell.Connected) { Thread.Sleep(1); } while (!shell.ShellOpened) { Thread.Sleep(1); } while (!shell.ShellConnected) { Thread.Sleep(1); } sshStream = shell.GetStream(); thr.Start(); } catch (Exception ee) { Console.WriteLine(ee.Message); } }
protected override void BeginProcessing() { SshShell sshShell = null; switch (this.ParameterSetName) { case "PasswordAuthentication": sshShell = new SshShell(this.SshHost, this.User, this.Port); sshShell.SetPasswordAuthentication(this.Password); break; case "PrivateKeyAuthentication": sshShell = new SshShell(this.SshHost, this.User, this.Port); sshShell.SetPrivateKeyAuthentication(this.PrivateKeyFile, this.Passphrase); break; case "CredentialAuthentication": sshShell = new SshShell(this.SshHost, this.Credential.UserName, this.Port); sshShell.SetPasswordAuthentication(this.Credential.GetNetworkCredential().Password); break; } sshShell.ConnectionTimeout = this.ConnectionTimeout; sshShell.Connect(); this.WriteObject(sshShell); }
public bool Connect() { bool _result = false; try { if (m_Shell != null) { try { m_Shell.Close(); } catch { } } m_Shell = new SshShell(FileManager.Configuration.Options.SSHOptions.SSHHost, FileManager.Configuration.Options.SSHOptions.SSHUser, FileManager.Configuration.Options.SSHOptions.SSHPass); int _port = 22; try { _port = Int32.Parse(FileManager.Configuration.Options.SSHOptions.SSHPort); } catch { } m_Shell.Connect(_port); _result = m_Shell.Connected; } catch (Exception ex) { Loggy.Logger.DebugException("SSH Connect: ", ex); } return(_result); }
public static void RunExample() { try { SshConnectionInfo input = Util.GetInput(); SshShell shell = new SshShell(input.Host, input.User); if (input.Pass != null) { shell.Password = input.Pass; } if (input.IdentityFile != null) { shell.AddIdentityFile(input.IdentityFile); } //This statement must be prior to connecting shell.RedirectToConsole(); Console.Write("Connecting..."); shell.Connect(); Console.WriteLine("OK"); while (shell.ShellOpened) { System.Threading.Thread.Sleep(500); } Console.Write("Disconnecting..."); shell.Close(); Console.WriteLine("OK"); } catch (Exception e) { Console.WriteLine(e.Message); } }
/// <summary> /// Open a Connection /// </summary> /// <param name="username"></param> /// <param name="password"></param> public override void OnOpenConnection(string username, SecureString password) { try { if (_sessionWindow == null) { throw new ProtocolException(beRemoteExInfoPackage.MajorInformationPackage, "SSH not initialized!"); } if (SessionWindow.IsSendInputRegistered == false) { SessionWindow.SendInput += SessionWindowSendInput; } //Load the configuration _sshTimeout = Convert.ToInt32(GetSessionSettings()["ssh.timeout"].GetProtocolSettingValue().GetValue()); try { //Create SSH Connection SshConnectionInfo input; input.Host = GetSessionServer().GetRemoteIP().ToString(); input.User = username; input.Pass = password == null ? null : Helper.ConvertToUnsecureString(password); //if (input.IdentityFile != null) shell.AddIdentityFile(input.IdentityFile); _sshConnection = new SshShell(input.Host, input.User); _readerStream = new MemoryStream(); if (input.Pass != null) { _sshConnection.Password = input.Pass; } //if (input.IdentityFile != null) shell.AddIdentityFile(input.IdentityFile); //This statement must be prior to connecting //_SshConnection.RedirectToConsole(); WriteDisplayText("Connecting..."); _sshConnection.Connect(); WriteDisplayText(_sshConnection.Expect()); } catch (Exception ea) { Logger.Log(LogEntryType.Warning, "Cannot connect to SSH-Server.", ea); WriteDisplayText(Environment.NewLine + "***Cannot connect to SSH-Server."); WriteDisplayText(Environment.NewLine + ea.Message); return; } WaitForSessionClose(); CloseConnection(); } catch (Exception ea) { Logger.Log(LogEntryType.Warning, "An unknown error occures on starting SSH-session", ea); } }
public string GetMacAddress(string _host, int _boot_groupid, int _environment, Log oLog, string _name, string _serial) { oLog.AddEvent(_name, _serial, "Starting MAC Address lookup...", LoggingType.Debug); string strMAC = ""; if (_boot_groupid > 0) { Models oModel = new Models(0, dsn); string strUsername = oModel.GetBootGroup(_boot_groupid, "username"); string strPassword = oModel.GetBootGroup(_boot_groupid, "password"); string strExpects = oModel.GetBootGroup(_boot_groupid, "regular"); string strCommand = oModel.GetBootGroup(_boot_groupid, "mac_query_command"); string strStart = oModel.GetBootGroup(_boot_groupid, "mac_query_substring_start"); oLog.AddEvent(_name, _serial, "Connecting...", LoggingType.Debug); SshShell oSSHshell = new SshShell(_host, strUsername, strPassword); oSSHshell.RemoveTerminalEmulationCharacters = true; oSSHshell.Connect(); string[] strExpect = strExpects.Split(new char[] { '|' }); if (oSSHshell.Connected == true && oSSHshell.ShellOpened == true) { // Wait for prompt string strBanner = oSSHshell.Expect(strExpects); oLog.AddEvent(_name, _serial, "Received banner prompt = " + strBanner, LoggingType.Debug); if (IsInOutput(strBanner, strExpect) == false) { oLog.AddEvent(_name, _serial, "Did not recieve all the output...trying again # 1...", LoggingType.Debug); strBanner = oSSHshell.Expect(strExpects); oLog.AddEvent(_name, _serial, "Received banner prompt # 1 = " + strBanner, LoggingType.Debug); } if (IsInOutput(strBanner, strExpect) == false) { oLog.AddEvent(_name, _serial, "Did not recieve all the output...trying again # 2...", LoggingType.Debug); strBanner = oSSHshell.Expect(strExpects); oLog.AddEvent(_name, _serial, "Received banner prompt # 2 = " + strBanner, LoggingType.Debug); } if (IsInOutput(strBanner, strExpect) == false) { oLog.AddEvent(_name, _serial, "Did not recieve all the output...trying again # 3...", LoggingType.Debug); strBanner = oSSHshell.Expect(strExpects); oLog.AddEvent(_name, _serial, "Received banner prompt # 3 = " + strBanner, LoggingType.Debug); } if (IsInOutput(strBanner, strExpect) == true) { oLog.AddEvent(_name, _serial, "Writing command = " + strCommand, LoggingType.Debug); // Send Command to get MAC Address oSSHshell.WriteLine(strCommand); // Wait for prompt strMAC = oSSHshell.Expect(strExpects); oLog.AddEvent(_name, _serial, "Received Response = " + strMAC, LoggingType.Debug); oLog.AddEvent(_name, _serial, "Parsing using " + strStart, LoggingType.Debug); strMAC = ParseOutput(strMAC, strStart, Environment.NewLine); } } oSSHshell.Close(); } return(strMAC); }
private void ConfigureNexus() { try { Ping oPing = new Ping(); string strPingStatus = ""; try { PingReply oReply = oPing.Send(strSwitch); strPingStatus = oReply.Status.ToString().ToUpper(); } catch { } if (strPingStatus == "SUCCESS") { // Switch the port of strSwitchA, strInterfaceA oSSHshell = new SshShell(strSwitch, oVariable.NexusUsername(), oVariable.NexusPassword()); oSSHshell.RemoveTerminalEmulationCharacters = true; oSSHshell.Connect(); string strLogin = oAsset.GetDellSwitchportOutput(oSSHshell); if (strLogin != "**INVALID**") { oLog.AddEvent(intAnswer, strName, strSerial, "Successfully logged into Switch (" + strSwitch + ")...Setting " + (oMode == DellBladeSwitchportMode.Trunk ? "TRUNK" : "ACCESS") + " Switchport (" + strInterface + ") to " + strVlan + " (override = " + (boolOverride ? "true" : "false") + ")", LoggingType.Information); string strResult = oAsset.ChangeDellSwitchport(oSSHshell, strInterface, oMode, strVlan, strNative, strDescription, boolOverride, intAsset); if (strResult == "") { oLog.AddEvent(intAnswer, strName, strSerial, "Successfully changed switchport " + strInterface + " on " + strSwitch, LoggingType.Information); Complete = true; // Done Configuring Switchports } else { Error = "There was a problem configuring the Dell Blade Switchport ~ Switch: " + strSwitch + ", Interface: " + strInterface + ", Error: " + strResult; oLog.AddEvent(intAnswer, strName, strSerial, Error, LoggingType.Error); } if (oSSHshell.ShellConnected == true && oSSHshell.ShellOpened == true) { oSSHshell.Close(); } } else { Error = "There was a problem logging into the Dell Blade Switch ~ Switch: " + strSwitch; oLog.AddEvent(intAnswer, strName, strSerial, Error, LoggingType.Error); } } else { Error = "There was a problem pinging the Dell Blade Switch ~ Switch: " + strSwitch + ", Status: " + strPingStatus; oLog.AddEvent(intAnswer, strName, strSerial, Error, LoggingType.Error); } } catch (Exception ex) { Error = "Physical Service (NexusThread - ConfigureNexus): " + "(Error Message: " + ex.Message + ") (Source: " + ex.Source + ") (Stack Trace: " + ex.StackTrace + ") [" + System.Environment.UserName + "]"; } }
public static void RunExample() { try { SshConnectionInfo input = Util.GetInput(); SshShell ssh = new SshShell(input.Host, input.User); if (input.Pass != null) { ssh.Password = input.Pass; } if (input.IdentityFile != null) { ssh.AddIdentityFile(input.IdentityFile); } Console.Write("Connecting..."); ssh.Connect(); Console.WriteLine("OK"); Console.Write("Enter a pattern to expect in response [e.g. '#', '$', C:\\\\.*>, etc...]: "); string pattern = Console.ReadLine(); ssh.ExpectPattern = pattern; ssh.RemoveTerminalEmulationCharacters = true; Console.WriteLine(); Console.WriteLine(ssh.Expect(pattern)); while (ssh.ShellOpened) { Console.WriteLine(); Console.Write("Enter some data to write ['Enter' to cancel]: "); string data = Console.ReadLine(); if (data == "") { break; } ssh.WriteLine(data); string output = ssh.Expect(pattern); Console.WriteLine(output); } Console.Write("Disconnecting..."); ssh.Close(); Console.WriteLine("OK"); } catch (Exception e) { Console.WriteLine(e.Message); } }
static void Main(string[] args) { SshShell lol = new SshShell("10.10.99.2", "admin"); lol.Password = "******"; lol.RedirectToConsole(); lol.Connect(); while (lol.ShellOpened) { System.Threading.Thread.Sleep(500); } lol.Close(); }
public void Begin() { datStart = DateTime.Now; arProcessing = new int[4] { 45, 47, 92, 124 }; // 92 = \, 124 = |, 47 = /, 45 = - strSSH = ""; oModel = new Models(0, dsn); oModelsProperties = new ModelsProperties(0, dsn); oServer = new Servers(0, dsn); oSetting = new Settings(0, dsn); oOnDemand = new OnDemand(0, dsn); oSolaris = new Solaris(0, dsn); oEventLog = new Log(0, dsn); oFunction = new Functions(0, dsn, intEnvironment); strTo = oFunction.GetGetEmailAlertsEmailIds("EMAILGRP_PROVISIONING_SUPPORT"); intModel = Int32.Parse(oServer.Get(intServer, "modelid")); if (intModel > 0) { strModel = oModelsProperties.Get(intModel, "name"); Int32.TryParse(oModelsProperties.Get(intModel, "modelid"), out intModelParent); if (intModelParent > 0) { Int32.TryParse(oModel.Get(intModelParent, "boot_groupid"), out intModelBootGroup); } } if (intModelBootGroup > 0) { string strUsername = oModel.GetBootGroup(intModelBootGroup, "username"); string strPassword = oModel.GetBootGroup(intModelBootGroup, "password"); strReturnToALOM = oModel.GetBootGroup(intModelBootGroup, "return_to_alom"); oEventLog.AddEvent(strName, strSerial, "Connecting to " + strILO + "... (U:" + strUsername + ", P:****)", LoggingType.Information); oSSHshell = new SshShell(strILO, strUsername, strPassword); oSSHshell.RemoveTerminalEmulationCharacters = true; oSSHshell.Connect(); oEventLog.AddEvent(strName, strSerial, "Connected to " + strILO + "...sending commands...", LoggingType.Information); ThreadStart oReadingDoneSSH = new ThreadStart(ReadingDoneSSH); Thread oJobReadingDoneSSH = new Thread(oReadingDoneSSH); oJobReadingDoneSSH.Start(); ReadingSSH(); } else { AddResult("The boot group of the model has not been configured ~ (ModelPropertyID = " + intModel.ToString() + ") (ModelID = " + intModelParent.ToString() + ") (ModelBootGroupID = " + intModelBootGroup.ToString() + ")"); } }
public bool ExecutionDeviceConnect() { try { sshShell.Connect(); sshShell.Expect(); isConnect = true; } catch (Exception ex) { ErrorLog.PutInLog(ex); isConnect = false; } return(isConnect); }
private string runStatusCommand(SshShell shell, SshExec exec, string command) { string stdout = ""; string stderr = ""; shell.Connect(); shell.RedirectToConsole(); exec.Connect(); int ret = exec.RunCommand(command, ref stdout, ref stderr); exec.Close(); shell.Close(); return(stdout); }
public void runCommand(string command, string stdout = "", string stderr = "") { _shell.Connect(); _shell.RedirectToConsole(); _exec.Connect(); int ret = _exec.RunCommand(command, ref stdout, ref stderr); if (ret != 0) { System.Diagnostics.Debugger.Break(); } _exec.Close(); _shell.Close(); }
public void RunShellTest() { try { shell.Connect(); } catch (Exception ex) { Console.WriteLine(ex.Message); } shell.ExpectPattern = "#"; Console.WriteLine(shell.Expect()); shell.WriteLine(@"ls"); Console.WriteLine(shell.Expect()); shell.WriteLine(@"ll"); Console.WriteLine(shell.Expect()); shell.WriteLine(@"cd /usr/local"); Console.WriteLine(shell.Expect()); shell.WriteLine(@"ll"); Console.WriteLine(shell.Expect()); shell.WriteLine(@"topp"); Console.WriteLine(shell.Expect()); shell.Close(); Console.WriteLine("----------------------------------------------"); exec.Connect(); string strRrr = ""; string strOut = ""; exec.RunCommand("ls", ref strOut, ref strRrr); System.Threading.Thread.Sleep(1000); Console.WriteLine(strOut); Console.WriteLine(strRrr); exec.RunCommand(@"cd /usr/local", ref strOut, ref strRrr); Console.WriteLine(strOut); Console.WriteLine(strRrr); Console.WriteLine(exec.RunCommand(@"ll")); Console.WriteLine(exec.RunCommand(@"cd /usr/local")); exec.Close(); }
//TODO //https://isc.sans.edu/ipinfo.html?ip= static SshShell connect() { port = 22; address = "192.168.1.2"; //TODO Hardcoded username = "******"; password = "******"; SshShell sshShell; sshShell = new SshShell(address, username, password); sshShell.RemoveTerminalEmulationCharacters = true; //string prompt; //prompt = "root@backtrack:~#"; //exec.Connect(address); //exec.Login(username, password); try { sshShell.Connect(port); string stdout = sshShell.Expect(prompt); //Utils.Helper_Trace("XORCISM PROVIDER XINFO", "stdoutconnect: " + stdout); } catch (Exception ex) { Utils.Helper_Trace("XORCISM PROVIDER XINFO", "Error in sshconnect to " + address + " " + ex.Message + " " + ex.InnerException); } Console.WriteLine("connected"); string cmd1 = "cd /home/root/tools/metasploitsvn"; //TODO Hardcoded sshShell.WriteLine(cmd1); //prompt1 = prompt + "~/tools/metasploitsvn" + promptend; prompt1 = "/tools/metasploitsvn"; //HARDCODED sshShell.Expect(prompt1); //============================================== cmd1 = "svn update"; //Hardcoded sshShell.WriteLine(cmd1); Thread.Sleep(60000); sshShell.Expect(prompt1); return(sshShell); }
static void Main(string[] args) { var serconfigPaht = AppDomain.CurrentDomain.BaseDirectory + "/config/server.config.json"; var configPath = AppDomain.CurrentDomain.BaseDirectory + "/config/dbCluster.config.cnf"; var configStr = File.ReadAllText(configPath); var serverConfigStr = File.ReadAllTextAsync(serconfigPaht).Result; var serverConfigJson = JObject.Parse(serverConfigStr); var taskList = new List <Task>(); foreach (var host in serverConfigJson["host"]) { var taskResult = Task.Run(() => { var shell = new SshShell(host.ToString(), "root", "Adminqwer!@#$"); shell.Connect(); foreach (var cmd in serverConfigJson["cmd"]) { var cmdTxt = cmd.ToString(); //Console.WriteLine(cmdTxt); switch (cmdTxt) { case "[writeConfig]": shell.WriteLine($"echo '{configStr}' > /var/lib/mysql-cluster/config.ini"); break; default: shell.WriteLine(cmdTxt); break; } //shell. } //shell.WriteLine("rm -rf ./*"); }); taskList.Add(taskResult); } Task.WaitAll(taskList.ToArray()); Console.Read(); }
static void Main(string[] args) { testScp(); try { string host = "192.168.0.3"; string user = "******"; string pass = "******"; Console.WriteLine("主机地址: {0}", host); Console.WriteLine("登陆用户: {0}", user); Console.WriteLine("登录密码: {0}", pass); SshShell shell = new SshShell(host, user); shell.Password = pass; shell.RedirectToConsole(); Console.Write("正在连接..."); shell.Connect(); Console.WriteLine("连接完毕!"); Console.WriteLine("========="); while (shell.ShellOpened) { System.Threading.Thread.Sleep(500); } Console.WriteLine("========="); Console.WriteLine("断开连接中..."); shell.Close(); Console.WriteLine("断开完毕"); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.Write("按任意键继续..."); Console.ReadKey(); Console.WriteLine("\b"); Environment.Exit(0); }
protected void Page_Load(object sender, EventArgs e) { string strUsername = "******"; string strPassword = "******"; //string strExpects = "sc>|[y/n]|} ok|return to ALOM"; string strExpects = "#"; SshShell oSSHshell = new SshShell("10.49.254.229", strUsername, strPassword); oSSHshell.RemoveTerminalEmulationCharacters = true; oSSHshell.Connect(); CombinedStream oSSHstream = (CombinedStream)(oSSHshell.GetStream()); if (oSSHshell.Connected == true && oSSHshell.ShellOpened == true) { //int bt = oSSHstream.ReadByte(); string strOutput = oSSHshell.Expect(strExpects); Response.Write(strOutput); } oSSHshell.Close(); }
public void Connect() { shell = new SshShell(user.Host, user.UserName, YSEncrypt.DecryptB(user.Password, KeysUtil.PassKey)); shell.Connect(user.Port); m_Channel = shell.getChannel(); session = shell.getSession(); sftpChannel = (ChannelSftp)session.openChannel("sftp"); sftpChannel.connect(); ThreadPool.QueueUserWorkItem((a) => { string line = null; while (RUN_CUT && shell.ShellOpened) { success = true; logger.Debug("Successed..."); sftpForm.HideTool(); System.Threading.Thread.Sleep(100); while ((line = m_Channel.GetMessage()) != null) { Console.WriteLine(line); } } logger.Debug("Disconnecting..."); Disconnection(); logger.Debug("OK"); }); dir = sftpChannel.getHome(); text_adress.Text = dir; LoadDirFilesToListView(dir); SetContentMenuItem(true); }
private void button1_Click(object sender, EventArgs e) { try { string host = tb_host.Text; string acc = tb_acc.Text; string pwd = tb_pwd.Text; shell = new SshShell(host, acc, pwd); //shell.RedirectToConsole(); shell.Connect(22); m_Channel = shell.getChannel(); string line = null; ThreadPool.QueueUserWorkItem((a) => { while (shell.ShellOpened) { System.Threading.Thread.Sleep(100); while ((line = m_Channel.GetMessage()) != null) { ShowLogger(line); } } Console.Write("Disconnecting..."); shell.Close(); Console.WriteLine("OK"); }); } catch (Exception ex) { Console.WriteLine(ex); } }
static void Main(string[] args) { //SshConnectionInfo input = Util.GetInput(); SshShell shell = new SshShell("101.132.130.133", "root"); shell.Password = "******"; //This statement must be prior to connecting shell.RedirectToConsole(); Console.Write("Connecting..."); shell.Connect(); Console.WriteLine("OK"); while (shell.ShellOpened) { System.Threading.Thread.Sleep(500); } Console.Write("Disconnecting..."); shell.Close(); Console.WriteLine("OK"); Console.ReadKey(); }
public bool Parse() { Assembly a; a = Assembly.GetExecutingAssembly(); Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", "Assembly location = " + a.Location); XmlDocument doc = new XmlDocument(); #region WITH OPENVAS (VERSION 1) /* * string folder; * folder = string.Format("result_{0}_{1}", DateTime.Now.Ticks, this.GetHashCode()); * Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", "FolderName is ="+folder); * //_SaintSettings settings = _SaintSettings.getInstance(); * * //Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", "Connecting to remote server by SSH" + settings.SaintIP); * * // SshStream sshStream = new SshStream(settings.SaintIP, settings.SaintLogin, settings.SaintPassword); * //string saintIP = ConfigurationManager.AppSettings["SAINT_IP"]; * //string saintLogin = ConfigurationManager.AppSettings["SAINT_LOGIN"]; * //string saintPassword = ConfigurationManager.AppSettings["SAINT_PASSWORD"]; * * // SshStream sshStream = new SshStream(saintIP, saintLogin, saintPassword); * * // Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", string.Format("saintIP={0},saintLogin={1},saintPassword={2}", saintIP, saintLogin, saintPassword)); * * SshStream sshStream = new SshStream("1.2.3.4", "saint", "OPENVAS!!!"); * * //SshExec exec; * //exec = new SshExec("1.2.3.4", "saint"); * //exec.Password = "******"; * * //exec.Connect(); * * //Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", "Successfully connected to remote server"); * * string cmd1; * string cmd2; * //string output; * * //cmd = string.Format("cd /usr/share/saint"); * //output = exec.RunCommand(cmd); * * //cmd = string.Format("ls -al"); * //output = exec.RunCommand(cmd); * * * * // cmd = string.Format("sudo ./saint -i -a 3 -Q -d {0} -L smb:root%7MyMP8qt {1}", folder, m_target); * cmd1 = string.Format("sudo ./mysaint.sh {0} {1}", folder, m_target); * cmd2 = string.Format("sudo ./mysaint2.sh {0} ", folder); * //string sdout=string.Empty; * //string serror=string.Empty; * * //output = exec.RunCommand(cmd,ref sdout,ref serror).ToString(); * * //cmd = string.Format("sudo ./mysaint2.sh {0}", folder); * //cmd = string.Format("sudo ./bin/saintwriter -c full.cf -d {0} -f 7", folder); * //output = exec.RunCommand(cmd, ref sdout, ref serror).ToString(); * * * StreamWriter sw = new StreamWriter(sshStream); * StreamReader sr = new StreamReader(sshStream); * sw.AutoFlush = true; * * //sw.WriteLine("cd /usr/share/saint"); * * //sw.WriteLine(string.Format("sudo ./saint -i -a 3 -Q -d {0} -L smb:root%7MyMP8qt {1}", folder, m_target)); * sw.WriteLine(cmd1); * sw.Flush(); * * // Thread.Sleep(10000); * // sw.WriteLine("OPENVAS!!!"); * // Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", "Password = OPENVAS!!!"); * // Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", "Executing OPENVAS Query:" + sw.ToString()); * * sw.WriteLine(cmd2); * sw.Flush(); * * //Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", "Sleep 10000 : BEGIN"); * ////Thread.Sleep(10000); * //Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", "Sleep 10000 : END"); * //sw.WriteLine(string.Format("sudo ./bin/saintwriter -c full.cf -d {0} -f 7", folder)); * * bool finished = false; * * string s = string.Empty; * string VulnerabilityXml = string.Empty; * * try * { * char[] buffer = new char[2048];//1024 * * StringBuilder sb; * sb = new StringBuilder(); * * while (finished == false) * { * * int n; * n = sr.Read(buffer, 0, 1024); * * sb.Append(buffer, 0, n); * * StringBuilder sb2; * sb2 = new StringBuilder(); * sb2.Append(buffer, 0, n); * Debug.WriteLine(sb2.ToString()); * * if (sb.ToString().Contains("udp_scan: no response from" + m_target + "; host is offline or UDP is filtered")) * { * throw new Exception("udp_scan: no response from" + m_target + "; host is offline or UDP is filtered"); * * } * * if (sb.ToString().Contains("</report>")) * { * Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", "XmlReport Found"); * finished = true; * int startIndex = sb.ToString().IndexOf("<report>"); * int endIndex = sb.ToString().IndexOf("</report>"); * VulnerabilityXml = sb.ToString().Substring(startIndex, endIndex - startIndex); * VulnerabilityXml += "</report>"; * } * * } * * Debug.WriteLine(sb.ToString()); * } * catch (Exception ex) * { * Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", "Exception = " + ex.Message); * } * * Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", "Parsing Saint Result into Xml"); * * doc.LoadXml(VulnerabilityXml); */ #endregion #region WITH OPENVAS (VERSION 2) long ticks; ticks = DateTime.Now.Ticks; string inputfile; inputfile = string.Format("{0}_{1}_input", ticks, this.GetHashCode()); string outputfile; outputfile = string.Format("{0}_{1}_output", ticks, this.GetHashCode()); Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", string.Format("JobID:" + m_jobId + " Input file = [{0}]", inputfile)); Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", string.Format("JobID:" + m_jobId + " Output file = [{0}]", outputfile)); int port; string address, username, password; /* * port = 22222; * address = "1.2.3.4"; * username = "******"; * password = "******"; */ port = 22; address = "111.222.333.444"; username = "******"; password = "******"; Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", string.Format("Connecting to OPENVAS server at {0} on port {1}", address, port)); string prompt; //prompt = "openvas@linux-jnx2:~>"; prompt = "root@xmachine:~#"; SshShell sshShell; sshShell = new SshShell(address, username, password); sshShell.RemoveTerminalEmulationCharacters = true; sshShell.Connect(port); sshShell.Expect(prompt); Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", string.Format("Successfully connected to OPENVAS server")); //string output; string stdout = ""; //string stderr = ""; // ========= // Command 0 (test) // ========= string cmd; cmd = string.Format("cd /home"); //Hardcoded sshShell.WriteLine(cmd); prompt = "root@xmachine:/home#"; stdout = sshShell.Expect(prompt); //Update openvas plugins: //openvas-nvt-sync cmd = string.Format("openvas-nvt-sync"); //Hardcoded Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", string.Format("JobID:" + m_jobId + " Executing command [{0}]", cmd)); sshShell.WriteLine(cmd); stdout = sshShell.Expect(prompt); Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", string.Format("START DUMP STDOUT")); Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", stdout); Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", string.Format("END DUMP STDOUT")); // ========= // Command 1 : Generate the input file // ========= cmd = string.Format("echo \"{0}\" > {1}", m_target, inputfile); Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", string.Format("Executing command [{0}]", cmd)); sshShell.WriteLine(cmd); stdout = sshShell.Expect(prompt); Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", string.Format("START DUMP STDOUT")); Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", stdout); Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", string.Format("END DUMP STDOUT")); // ========= // Command 2 : Scan // ========= cmd = string.Format("openvas-client --output-type=xml -x --batch-mode=localhost 9391 openvas tcurstantv {0} {1}", inputfile, outputfile); //Hardcoded //cmd = string.Format("RunOpenVAS.sh {0} {1}", inputfile, outputfile); Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", string.Format("JobID:" + m_jobId + " Executing command [{0}]", cmd)); sshShell.WriteLine(cmd); stdout = sshShell.Expect(prompt); Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", string.Format("START DUMP STDOUT")); Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", stdout); //OpenVAS-Client : Could not open a connection to localhost //==> we should launch openvasd Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", string.Format("END DUMP STDOUT")); if (stdout.Contains("Could not open a connection to localhost")) { Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", string.Format("Executing command [openvassd]")); sshShell.WriteLine("openvassd"); stdout = sshShell.Expect(prompt); //Relaunching the scan Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", string.Format("Executing command [{0}]", cmd)); sshShell.WriteLine(cmd); stdout = sshShell.Expect(prompt); } /* * string[] tab; * tab = stdout.Split(new char[] { '\n' }); * * int pid; * pid = Convert.ToInt32(tab[1]); * * Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", string.Format("PID = [{0}]", pid)); * * // ========= * // Command 3 : Wait for completion * // ========= * * while (true) * { * Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", "Checking for completion..."); * * // cmd = string.Format("ps ax | grep {0} | cut -f1 -d\" \"", pid); * cmd = string.Format("ps ax | grep {0}", pid); * * sshShell.WriteLine(cmd); * stdout = sshShell.Expect(prompt); * * stdout = stdout.Replace("\r", ""); * * tab = stdout.Split(new char[] { '\n' }); * * bool bFound = false; * foreach (string dummy in tab) * { * Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", string.Format(" Line [{0}]", dummy.Trim())); * * string[] tt; * tt = dummy.Trim().Split(new char[] { ' ' }); * * if (tt[0] == pid.ToString()) * bFound = true; * } * * if(bFound == false) * break; * * Thread.Sleep(10000); * } * * Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", "Scan has completed"); */ // ========= // Command 4 : Get results // ========= string localOutputFile; localOutputFile = Path.GetTempFileName(); // HACK : // outputfile = "634244542240861588_39608125_output"; Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", string.Format("Downloading results via SFTP to [{0}]", localOutputFile)); try { Sftp ftp; ftp = new Sftp(address, username, password); ftp.OnTransferStart += new FileTransferEvent(ftp_OnTransferStart); ftp.OnTransferProgress += new FileTransferEvent(ftp_OnTransferProgress); ftp.OnTransferEnd += new FileTransferEvent(ftp_OnTransferEnd); ftp.Connect(port); ftp.Get(outputfile, localOutputFile); ftp.Close(); } catch (Exception ex) { Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", string.Format("Exception = {0} / {1}", ex.Message, ex.InnerException == null ? "" : ex.InnerException.Message)); return(false); } Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", "Loading the xml document"); // HACK // string localOutputFile = @"C:\Users\Jerome\AppData\Local\Temp\tmpCEA4.tmp"; try { doc.XmlResolver = null; doc.Load(localOutputFile); } catch (Exception ex) { Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", string.Format("Exception = {0} / {1}", ex.Message, ex.InnerException == null ? "" : ex.InnerException.Message)); return(false); } #endregion #region WITH OPENVAS (VERSION 3) /* * string folder; * folder = string.Format("result_{0}_{1}", DateTime.Now.Ticks, this.GetHashCode()); * * Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", string.Format("Results will be stored in folder [{0}]", folder)); * * string address, username, password; * * address = "111.222.333.444"; * username = "******"; * password = "******"; * * // address = "1.2.3.4"; * // username = "******"; * // password = "******"; * * Ssh exec; * exec = new Ssh(); * exec.Timeout = -1; * * Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", string.Format("Connecting to OPENVAS server at {0}", address)); * * exec.Connect(address); * exec.Login(username, password); * * Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", string.Format("Successfully connected to OPENVAS server")); * * string output; * string stdout = ""; * string stderr = ""; * * // ========= * // Command 0 (test) * // ========= * * string cmd0; * * cmd0 = string.Format("sudo ls -al"); * * Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", string.Format("Executing command [{0}]", cmd0)); * * stdout = exec.RunCommand(cmd0); * * Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", string.Format("START DUMP STDOUT")); * Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", stdout); * Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", string.Format("END DUMP STDOUT")); * * Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", string.Format("START DUMP STDERR")); * Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", stderr); * Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", string.Format("END DUMP STDERR")); * * // ========= * // Command 1 * // ========= * * string cmd1; * * string commande = string.Empty; * * var Provider = from o in m_model.JOB * where o.JobID == m_jobId * select o.PROVIDER; * * PROVIDER CurrentProvider = Provider.FirstOrDefault(); * * Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", string.Format("Strategy = {0} - Policy = {1} - Provider = {2}", m_strategy, m_policy, CurrentProvider.Title)); * * var cmd = from o in m_model.PARAMETERSFORPROVIDER * where o.Policy == m_policy && * o.Strategy == m_strategy && * o.ProviderID == CurrentProvider.ProviderID * select o.Parameters; * * string CommandeToUse = cmd.FirstOrDefault(); * * // HACK * // CommandeToUse = "\"" + "-i -a 3 -Q -d" + "\""; * // m_target = "www.target.com"; * * // cmd1 = string.Format("sudo ./mysaint1.sh {0} {1} {2}", folder, m_target, CommandeToUse); * // cmd1 = string.Format("sudo ./mysaint1.sh {0} {1}", folder, m_target); * * cmd1 = string.Format("sudo sh -c \"cd /usr/share/saint ; ./saint {0} -d {1} -L smb:root%MyMP8qt {2}\"", CommandeToUse, folder, m_target); * * Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", string.Format("Executing command [{0}]", cmd1)); * * stdout = exec.RunCommand(cmd1); * * Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", string.Format("START DUMP STDOUT")); * Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", stdout); * Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", string.Format("END DUMP STDOUT")); * * Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", string.Format("START DUMP STDERR")); * Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", stderr); * Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", string.Format("END DUMP STDERR")); * * // if (sb.ToString().Contains("udp_scan: no response from" + m_target + "; host is offline or UDP is filtered")) * // throw new Exception("udp_scan: no response from" + m_target + "; host is offline or UDP is filtered"); * * // ========= * // Command 1 bis * // ========= * * string cmd11; * * cmd11 = string.Format("sudo sh -c \"cd /usr/share/saint ; chmod -R a+r results\""); * * Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", string.Format("Executing command [{0}]", cmd11)); * * stdout = exec.RunCommand(cmd11); * * Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", string.Format("START DUMP STDOUT")); * Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", stdout); * Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", string.Format("END DUMP STDOUT")); * * Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", string.Format("START DUMP STDERR")); * Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", stderr); * Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", string.Format("END DUMP STDERR")); * * // ========= * // Command 2 * // ========= * * string cmd2; * cmd2 = string.Format("sudo ./mysaint2.sh {0} ", folder); * * cmd2 = string.Format("sudo sh -c \"cd /usr/share/saint ; ./bin/saintwriter -c full.cf -d {0} -f 7\"", folder); * * Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", string.Format("Executing command [{0}]", cmd2)); * * stdout = exec.RunCommand(cmd2); * * Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", string.Format("START DUMP STDOUT")); * Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", stdout); * Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", string.Format("END DUMP STDOUT")); * * Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", string.Format("START DUMP STDERR")); * Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", stderr); * Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", string.Format("END DUMP STDERR")); * * int index; * index = stdout.IndexOf("<?xml version="); * if (index == -1) * { * Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", string.Format("Report does not contain XML data")); * return false; * } * * stdout = stdout.Substring(index); * * try * { * Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", "Loading the xml document"); * * doc.LoadXml(stdout); * } * catch (Exception ex) * { * Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", string.Format("Exception = {0} / {1}", ex.Message, ex.InnerException == null ? "" : ex.InnerException.Message)); * return false; * } */ #endregion #region WITHOUT OPENVAS //string filename; //filename = @"D:\Resultats_OpenVAS.xml"; //Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", string.Format("Using file '{0}'", filename)); //doc.Load(filename); #endregion try { Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", "Getting vulnerabilities"); Helper_GetVulnerabilities(doc, m_target); } catch (Exception ex) { Utils.Helper_Trace("XORCISM PROVIDER OPENVAS", string.Format("Exception = {0} / {1}", ex.Message, ex.InnerException == null ? "" : ex.InnerException.Message)); return(false); } // Finshed return(true); }
protected override void RunWithSession(ref Session session) { string toDirectory = "/tmp"; Status = Messages.IN_PROGRESS; log.InfoFormat("{0} Upgrade...", Host.address); int sshdstate = 1; int sshport = 22; Dictionary <string, string> _servicearguments = new Dictionary <string, string>(); _servicearguments.Add("servicename", "sshd"); try { string rsvalue = XenAPI.Host.call_plugin(Host.Connection.Session, Host.opaque_ref, "serviceinfo.py", "getserviceinfo", _servicearguments); rsvalue = rsvalue.Replace("[", "").Replace("]", "").Replace("'", "").Replace("\\n", ""); string[] rsvalues = rsvalue.Split(','); if (rsvalues.Length > 1 && "0".Equals(rsvalues[1].Trim())) { log.InfoFormat("{0} sshd is running ...", Host.address); } if (rsvalues.Length > 1 && "3".Equals(rsvalues[1].Trim())) { log.InfoFormat("{0} sshd is stop, start sshd ...", Host.address); rsvalue = XenAPI.Host.call_plugin(Host.Connection.Session, Host.opaque_ref, "serviceinfo.py", "startserviceinfo", _servicearguments); rsvalue = rsvalue.Replace("[", "").Replace("]", "").Replace("'", "").Replace("\\n", ""); rsvalues = rsvalue.Split(','); if (rsvalues.Length > 1 && "0".Equals(rsvalues[1].Trim())) { sshdstate = 0; } else { throw new Exception(Messages.START_SSH_FAILED); } } //sshport = 7443; }catch (Exception) {} FileStream file = new FileStream(_fileName, FileMode.Open); string topfilename = Path.GetFileNameWithoutExtension(_fileName); System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] retVal = md5.ComputeHash(file); file.Close(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < retVal.Length; i++) { sb.Append(retVal[i].ToString("x2")); } log.InfoFormat("md5.......{0}", sb); SshTransferProtocolBase sshCp; //sshCp = new Sftp(Host.address, Host.Connection.Username); sshCp = new Scp(Host.address, Host.Connection.Username); sshCp.Password = Host.Connection.Password; log.InfoFormat("sshCp Connecting..."); sshCp.Connect(sshport); log.InfoFormat("sshCp Connecting OK ......."); String Programurl = Program.AssemblyDir; sshCp.Put(_fileName, toDirectory + "/" + Path.GetFileName(_fileName)); log.InfoFormat("cp Installation package ok......"); sshCp.Put(Programurl + "\\halsign_host_upgrade.py", "/etc/xapi.d/plugins/halsign_host_upgrade.py"); log.InfoFormat("cp halsign_host_upgrade.py ok......"); SshShell ssh = new SshShell(Host.address, Host.Connection.Username); ssh.Password = Host.Connection.Password; string productVersion = Host.ProductVersion; log.InfoFormat("sshshell Connecting..."); ssh.Connect(sshport); log.InfoFormat("sshshell Connecting ok..."); ssh.ExpectPattern = "#"; ssh.RemoveTerminalEmulationCharacters = true; //System.Console.WriteLine(); //Thread.Sleep(1000); //ssh.WriteLine("chmod 777 /etc/xapi.d/plugins/halsign_host_upgrade.py;echo $?"); //string output = ssh.Expect("#"); //log.InfoFormat(output); while (true) { ssh.WriteLine("chmod 777 /etc/xapi.d/plugins/halsign_host_upgrade.py;echo $?"); string output = ssh.Expect("#"); log.InfoFormat(output); if (output.IndexOf("rwxrwxrwx") > -1) { break; } ssh.WriteLine("ls -ld /etc/xapi.d/plugins/halsign_host_upgrade.py |awk '{print $1}'|sed 's/^[a-zA-Z-]//'"); output = ssh.Expect("#"); log.InfoFormat(output); if (output.IndexOf("rwxrwxrwx") > -1) { break; } } ssh.WriteLine("exit"); ssh.Close(); log.InfoFormat("sshshell Disconnecting OK....."); sshCp.Close(); log.InfoFormat("sshCp Disconnecting OK....."); if (sshdstate == 0) { XenAPI.Host.call_plugin(Host.Connection.Session, Host.opaque_ref, "serviceinfo.py", "stopserviceinfo", _servicearguments); } _arguments = new Dictionary <string, string>(); _arguments.Add("md5", sb.ToString()); _arguments.Add("filename", topfilename); _arguments.Add("toDirectory", toDirectory); Status = Messages.PLAN_ACTION_STATUS_HOST_UPGRADED; string value = XenAPI.Host.call_plugin(session, Host.opaque_ref, "halsign_host_upgrade.py", "main", _arguments); if (value.ToLower() == "true") { //base.RunWithSession(ref session); Status = Messages.PLAN_ACTION_STATUS_HOST_UPGRADED; } else if (",1,2,5,6,7,10,11,12,13,1001,1002,1003,1004,1005,1006,".IndexOf("," + value + ",") > -1) { value = value == "2" ? "1" : value; string Ms = "PATCH_UPGRADE_" + value; if (value.Equals("1")) { //Status = (string)XenAdmin.Messages.ResourceManager.GetString(Ms, resourceCulture); throw new Exception("PATCHOK_" + (string)XenAdmin.Messages.ResourceManager.GetString(Ms)); } else { throw new Exception((string)XenAdmin.Messages.ResourceManager.GetString(Ms)); } } else { throw new Exception(Messages.ERROR + ":" + value); } }
protected void Page_Load(object sender, EventArgs e) { Models oModel = new Models(0, dsn); Solaris oSolaris = new Solaris(0, dsn); Variables oVariables = new Variables((int)CurrentEnvironment.PNCNT_QA); string strMAC = ""; string strUsername = oVariables.NexusUsername(); string strPassword = oVariables.NexusPassword(); string strExpects = "#"; string strLine = "show int eth 102/1/24 br"; //SshShell oSSHshell = new SshShell("P-PRDC-ZA08A-1", strUsername, strPassword); //oSSHshell.RemoveTerminalEmulationCharacters = true; //oSSHshell.Connect(); //if (oSSHshell.Connected == true && oSSHshell.ShellOpened == true) //{ // // Wait for "sc>" // string strBanner = oSSHshell.Expect(strExpects); // // Send Command : showsc sys_enetaddr // oSSHshell.WriteLine(strLine); // //WriteLine(oSSHshell, strLine); // // Wait for "sc>" // strMAC = oSSHshell.Expect(strExpects); // //strMAC = oSolaris.ParseOutput(strMAC, "macaddress = ", Environment.NewLine); //} //oSSHshell.Close(); //Response.Write("<p>" + strMAC + "</p>"); //SshExec oSSH = new SshExec("P-PRDC-ZA08A-1", strUsername, strPassword); //oSSH.Connect(); //string strMAC2 = oSSH.RunCommand(strLine); //oSSH.Close(); //Response.Write("<p>" + strMAC2 + "</p>"); //SshExec oSSHa = new SshExec("10.49.254.229", "admin", "nccSAN03"); //oSSHa.Connect(); //string strResult = oSSHa.RunCommand("config t"); //Response.Write(strResult); ////Response.Write(ExecuteSSH("config t", oSSHa)); //oSSHa.Close(); string strName = "HEALYTEST"; StringBuilder strSAN = new StringBuilder(); SshShell oSSHshellb = new SshShell("10.49.254.230", "admin", "nccSAN03"); oSSHshellb.RemoveTerminalEmulationCharacters = true; oSSHshellb.Connect(); if (oSSHshellb.Connected == true && oSSHshellb.ShellOpened == true) { string strBanner = oSSHshellb.Expect("#"); strSAN.Append("10.49.254.230..."); strSAN.Append(ExecuteSSH("config t", oSSHshellb)); strSAN.Append(ExecuteSSH("device-alias database", oSSHshellb)); strSAN.Append(ExecuteSSH("device-alias name " + strName + "b pwwn 50:06:0b:00:00:c3:5a:36", oSSHshellb)); strSAN.Append(ExecuteSSH("exit", oSSHshellb)); strSAN.Append(ExecuteSSH("device-alias commit", oSSHshellb)); System.Threading.Thread.Sleep(20000); // wait 20 seconds strSAN.Append(ExecuteSSH("zoneset name eng_cert vsan 1101", oSSHshellb)); strSAN.Append(ExecuteSSH("zone name " + strName + "b_vmax0425_01h1", oSSHshellb)); strSAN.Append(ExecuteSSH("member device-alias " + strName + "b", oSSHshellb)); strSAN.Append(ExecuteSSH("member device-alias vmax0425_01h1", oSSHshellb)); strSAN.Append(ExecuteSSH("exit", oSSHshellb)); strSAN.Append(ExecuteSSH("member " + strName + "b_vmax0425_01h1", oSSHshellb)); strSAN.Append(ExecuteSSH("exit", oSSHshellb)); strSAN.Append(ExecuteSSH("zoneset activate name eng_cert vsan 1101", oSSHshellb)); System.Threading.Thread.Sleep(10000); // wait 10 seconds strSAN.Append(ExecuteSSH("zone commit vsan 1101", oSSHshellb)); System.Threading.Thread.Sleep(20000); // wait 20 seconds strSAN.Append(ExecuteSSH("end", oSSHshellb)); strSAN.Append(ExecuteSSH("exit", oSSHshellb)); } oSSHshellb.Close(); Response.Write("<p>" + strSAN + "</p>"); }
public void Run(string target, int jobID, string policy, string Strategy) { Utils.Helper_Trace("XORCISM PROVIDER VOIPSCANNER", "Entering Run()"); Utils.Helper_Trace("XORCISM PROVIDER VOIPSCANNER", string.Format("Target = {0} , JobID = {1} , Policy = {2}", target, jobID, policy)); Assembly a; a = Assembly.GetExecutingAssembly(); Utils.Helper_Trace("XORCISM PROVIDER VOIPSCANNER", "Assembly location = " + a.Location); // ============== // Launch the job // ============== #region With VoIPScanner const string username = "******"; //TODO Hardcoded //string username = ConfigurationManager.AppSettings["VOIPSCANNER_USERNAME"]; const string key = "1943e197-0zae-4bxc-xd18-12345"; //string key = ConfigurationManager.AppSettings["VOIPSCANNER_KEY"]; // const string baseurl = "https://voipscanner.com/voipscanner/voipscannerxmlrpc/handle"; Utils.Helper_Trace("XORCISM PROVIDER VOIPSCANNER", string.Format("UserName = {0} , Key = {1}", username, key)); XmlRpcStruct Xtarget = new XmlRpcStruct(); XORCISMEntities model; model = new XORCISMEntities(); Dictionary <string, object> parameters; var q = from x in model.JOB where x.JobID == jobID select x.Parameters; try { byte[] buffer; buffer = q.First(); Utils.Helper_Trace("XORCISM PROVIDER VOIPSCANNER", string.Format("Size of parameters = {0} bytes", buffer.Length)); MemoryStream ms; ms = new MemoryStream(buffer); BinaryFormatter bf; bf = new BinaryFormatter(); parameters = (Dictionary <string, object>)bf.Deserialize(ms); } catch (Exception ex) { Utils.Helper_Trace("XORCISM PROVIDER VOIPSCANNER", string.Format("Error while deserializing parameters : Exception = {0}", ex.Message)); return; } string Sip; Sip = (string)parameters["SIP"]; string Extrange; Extrange = (string)parameters["EXTRANGE"]; try { Xtarget.Add("hostname", target); if (string.IsNullOrEmpty(Sip) == false) { Xtarget.Add("sipport", Sip); } if (string.IsNullOrEmpty(Extrange) == false) { Xtarget.Add("extrange", Extrange); } } catch (Exception ex) { Utils.Helper_Trace("XORCISM PROVIDER VOIPSCANNER", string.Format("Exception = {0}", ex.Message)); // Que faire ? } Utils.Helper_Trace("XORCISM PROVIDER VOIPSCANNER", string.Format("Target = {0}", target)); IToto proxy = XmlRpcProxyGen.Create <IToto>(); Utils.Helper_Trace("XORCISM PROVIDER VOIPSCANNER", string.Format("Proxy = {0}", proxy)); Tracer tracer = new Tracer(); tracer.Attach(proxy); Utils.Helper_Trace("XORCISM PROVIDER VOIPSCANNER", "Param Okay"); string[] res = null; try { res = proxy.scan(username, key, Xtarget); } catch (XmlRpcFaultException fex) { Utils.Helper_Trace("XORCISM PROVIDER VOIPSCANNER", string.Format("Fault Response: {0} {1}", fex.FaultCode, fex.FaultString)); } string scanuid = string.Empty; if (res[0] == "Success") { Utils.Helper_Trace("XORCISM PROVIDER VOIPSCANNER", "Success 1"); scanuid = res[1]; } else { Utils.Helper_Trace("XORCISM PROVIDER VOIPSCANNER", string.Format("Fail 1: {0}", res[0])); } // =================== // Wait for completion // =================== XmlRpcStruct scanparams = new XmlRpcStruct(); scanparams.Add("scanuid", scanuid); scanparams.Add("pretty", true); scanparams.Add("documented", true); // target.Add("upperBound", 139); bool finished = false; string xml = string.Empty; Utils.Helper_Trace("XORCISM PROVIDER VOIPSCANNER", "Waiting 45 seconds..."); Thread.Sleep(45000); //Hardcoded while (finished == false) { try { Utils.Helper_Trace("XORCISM PROVIDER VOIPSCANNER", "Trying to get results"); res = proxy.getresultsxml(username, key, scanparams); } catch (XmlRpcFaultException fex) { Utils.Helper_Trace("XORCISM PROVIDER VOIPSCANNER", string.Format("Fault Response: {0} {1}", fex.FaultCode, fex.FaultString)); } if (res[0] == "Success") { Utils.Helper_Trace("XORCISM PROVIDER VOIPSCANNER", "Success 2"); xml = res[1]; Utils.Helper_Trace("XORCISM PROVIDER VOIPSCANNER", "res=" + xml); finished = true; } else { //Wait Utils.Helper_Trace("XORCISM PROVIDER VOIPSCANNER", string.Format("Fail 2: {0}", res[0])); // return null; Thread.Sleep(30000); } } Utils.Helper_Trace("XORCISM PROVIDER VOIPSCANNER", "Results successfully downloaded"); XmlDocument doc; doc = new XmlDocument(); try { //TODO XML Validation doc.LoadXml(xml); } catch (Exception ex) { Utils.Helper_Trace("XORCISM PROVIDER VOIPSCANNER", string.Format("LoadXmlException = {0}", ex.Message)); // Que faire ? } #endregion #region Without VoIPScanner /* * XmlDocument doc = new XmlDocument(); * doc.Load(@"c:\VoIPScanner.xml"); */ #endregion Utils.Helper_Trace("XORCISM PROVIDER VOIPSCANNER", "Parsing the results"); VoIPScannerParser parser = new VoIPScannerParser(doc, jobID); parser.parse(); Utils.Helper_Trace("XORCISM PROVIDER VOIPSCANNER", "Using svmap.py from sipvicious"); string address = "111.222.333.444"; //TODO Hardcoded //string username = "******"; string password = "******"; string prompt = "root"; SshShell sshShell; sshShell = new SshShell(address, "root", password); sshShell.RemoveTerminalEmulationCharacters = true; Utils.Helper_Trace("XORCISM PROVIDER SIPVICIOUS", string.Format("JobID: {0} Connecting to SIPVICIOUS server at {1}", jobID, address)); try { sshShell.Connect(22); //sshShell.Expect(prompt+"~#"); sshShell.Expect(prompt);// + "~$"); } catch (Exception ex) { Utils.Helper_Trace("XORCISM PROVIDER SIPVICIOUS", string.Format("JobID: {0} ConnectingERROR to SIPVICIOUS server at {1} : " + ex.Message + " " + ex.InnerException, jobID, address)); } string cmd1 = "cd /home/root/tools/sipvicious/"; //Hardcoded sshShell.WriteLine(cmd1); Thread.Sleep(1000); //Hardcoded string stdout = sshShell.Expect(prompt); Utils.Helper_Trace("XORCISM PROVIDER SIPVICIOUS", string.Format("JobID: {0} START DUMP STDOUT01", jobID)); Utils.Helper_Trace("XORCISM PROVIDER SIPVICIOUS", stdout); Thread.Sleep(1000); sshShell.WriteLine("./svmap.py " + target); //Hardcoded Thread.Sleep(30000); //Hardcoded stdout = sshShell.Expect(prompt); Utils.Helper_Trace("XORCISM PROVIDER SIPVICIOUS", string.Format("JobID: {0} START DUMP STDOUT02", jobID)); Utils.Helper_Trace("XORCISM PROVIDER SIPVICIOUS", stdout); //TODO /* * INFORMATION myInformation = new INFORMATION(); * //VulnerabilityFound vulnerabilityFound = new VulnerabilityFound(); * myInformation.EndPointID = theEndPointID; * myInformation.JobID = m_jobId; * //vulnerabilityFound.ListItem = Helper_GetCVE(n); * //vulnerabilityFound.ListReference = Helper_GetREFERENCE(n); //TODO: Helper_GetCVE and Helper_GetREFERENCE could be mixed for only 1 parsing * //vulnerabilityFound.InnerXml = n.OuterXml; * * myInformation.Description = HelperGetChildInnerText(n, "DIAGNOSIS"); * myInformation.Solution = HelperGetChildInnerText(n, "SOLUTION"); * myInformation.Severity = n.Attributes["severity"].Value; * myInformation.Consequence = HelperGetChildInnerText(n, "CONSEQUENCE"); * myInformation.Result = HelperGetChildInnerText(n, "RESULT"); * myInformation.ModifiedDate = DateTime.Parse(HelperGetChildInnerText(n, "LAST_UPDATE")); * if (HelperGetChildInnerText(n, "PCI_FLAG") == "1") * { * myInformation.PCI_FLAG = true; * } * myInformation.Title = ""; * * model.AddToINFORMATION(myInformation); * model.SaveChanges(); */ Utils.Helper_Trace("XORCISM PROVIDER VOIPSCANNER", "Update job status to FINISHED"); var j = from xJob in model.JOB where xJob.JobID == jobID select xJob; JOB J = j.FirstOrDefault(); J.Status = XCommon.STATUS.FINISHED.ToString(); model.SaveChanges(); //FREE MEMORY parser = null; J = null; model.Dispose(); Utils.Helper_Trace("XORCISM PROVIDER VOIPSCANNER", string.Format("Leaving Run()")); }
protected void Page_Load(object sender, EventArgs e) { string strSSH = ""; string strILO = "10.249.237.148"; if (Request.QueryString["ilo"] != null) { strILO = "10.249.237.144"; } Variables oVariable = new Variables(intEnvironment); int intLogging = 0; byte[] byt; string str; Models oModel = new Models(0, dsn); ModelsProperties oModelsProperties = new ModelsProperties(0, dsn); Servers oServer = new Servers(0, dsn); Settings oSetting = new Settings(0, dsn); OnDemand oOnDemand = new OnDemand(0, dsn); Log oEventLog = new Log(0, dsn); SshShell oSSHshell = new SshShell(strILO, oVariable.SolarisUsername(), oVariable.SolarisPassword()); oSSHshell.RemoveTerminalEmulationCharacters = true; oSSHshell.Connect(); Response.Write("Connected to " + strILO + "...sending commands..." + "<br/>"); CombinedStream oSSHstream = (CombinedStream)(oSSHshell.GetStream()); int intStep = 1; if (Request.QueryString["none"] == null) { byt = new byte[100]; str = "" + strSSH_Carriage; byt = System.Text.ASCIIEncoding.ASCII.GetBytes(str); if (oSSHshell.Connected == true && oSSHshell.ShellOpened == true) { oSSHstream.Write(byt); } } int bt = 0; int intMinutePrevious = 0; bool boolProcessing = false; while (bt != -1 && oSSHshell.Connected == true && oSSHshell.ShellOpened == true) { bt = oSSHstream.ReadByte(); // Strip the processing cursor -\|/-\|/ from the output if (bt == 8) // 8 = backspace { // Check to see if previous characters were a processing character as well char chrSSH = strSSH[strSSH.Length - 1]; int intSymbol = (int)chrSSH; while (IsGarbageChar(intSymbol) == true) { if (intLogging > 1) { Response.Write("The symbol [" + chrSSH.ToString() + "] is a garbage character and must be removed" + "<br/>"); } strSSH = strSSH.Substring(0, strSSH.Length - 1); chrSSH = strSSH[strSSH.Length - 1]; intSymbol = (int)chrSSH; } // Set processing to true to exclude future characters boolProcessing = true; } if (boolProcessing == true && IsGarbageChar(bt) == false) { boolProcessing = false; } if (boolProcessing == false) { strSSH += (char)bt; } string strReadSSH = ""; string strWriteSSH = ""; switch (intStep) { case 1: strReadSSH = "-sc>"; strWriteSSH = "poweron"; break; case 2: strReadSSH = "-sc>"; strWriteSSH = "showpower"; break; case 3: strReadSSH = "-sc>"; break; } if (strReadSSH != "" && strSSH.EndsWith(strReadSSH) == true) { try { Response.Write("SSH output ends with [" + strReadSSH + "] : " + strSSH + "<br/>"); } catch { } if (intStep == 3) { break; } // Execute next command byt = new byte[100]; str = strWriteSSH + strSSH_Carriage; byt = System.Text.ASCIIEncoding.ASCII.GetBytes(str); if (oSSHshell.Connected == true && oSSHshell.ShellOpened == true) { try { Response.Write("Sending command [" + strWriteSSH + "] : " + strSSH + "<br/>"); } catch { } oSSHstream.Write(byt); } intStep++; } else { } } Response.Write(strSSH); oSSHstream.Close(); oSSHshell.Close(); }
public bool Parse() { Assembly a; a = Assembly.GetExecutingAssembly(); Utils.Helper_Trace("XORCISM PROVIDER WHATWEB", "WHATWEB Assembly location = " + a.Location); /* Name of XML result */ string file; file = string.Format("result_{0}_{1}.xml", DateTime.Now.Ticks, this.GetHashCode()); Utils.Helper_Trace("XORCISM PROVIDER WHATWEB", string.Format("JobID: {0} Results will be stored in file [{1}]", m_jobId, file)); /* SSH instructions & declarations */ int port = 22; string address, username, password; string prompt; /* * address = "192.168.79.129"; //111.222.333.444 * username = "******"; //jerome * password = "******"; //jerome * //prompt = "root@ubuntu:~#"; */ /* * //OVH * address = "111.222.333.444"; * username = "******"; * password = "******"; * prompt = "root@xmachine:"; */ address = "111.222.333.444"; username = "******"; password = "******"; prompt = "root"; //@backtrack:"; SshShell sshShell; sshShell = new SshShell(address, username, password); sshShell.RemoveTerminalEmulationCharacters = true; Utils.Helper_Trace("XORCISM PROVIDER WHATWEB", string.Format("JobID: {0} Connecting to WHATWEB server at {1}", m_jobId, address)); try { sshShell.Connect(port); //sshShell.Expect(prompt+"~#"); sshShell.Expect(prompt);// + "~$"); } catch (Exception ex) { Utils.Helper_Trace("XORCISM PROVIDER WHATWEB", string.Format("JobID: {0} ConnectingERROR to WHATWEB server at {1} : " + ex.Message + " " + ex.InnerException, m_jobId, address)); address = "111.222.333.444"; username = "******"; password = "******"; //prompt = "root@backtrack:"; sshShell = new SshShell(address, username, password); sshShell.RemoveTerminalEmulationCharacters = true; Utils.Helper_Trace("XORCISM PROVIDER WHATWEB", string.Format("JobID: {0} Connecting to WHATWEB server at {1}", m_jobId, address)); try { sshShell.Connect(port); sshShell.Expect(prompt);// + "~$"); } catch (Exception ex2) { Utils.Helper_Trace("XORCISM PROVIDER WHATWEB", string.Format("JobID: {0} ConnectingERROR to WHATWEB server at {1} : " + ex2.Message + " " + ex2.InnerException, m_jobId, address)); } } Utils.Helper_Trace("XORCISM PROVIDER WHATWEB", string.Format("JobID: {0} Successfully connected to WHATWEB server", m_jobId)); //string output; string stdout = ""; //string stderr = ""; /* Command 1 */ string cmd1; //cmd1 = "cd /home/tools/whatweb-0.4.7"; cmd1 = "cd /home/root/tools/whatweb-0.4.7/"; sshShell.WriteLine(cmd1); //prompt = prompt+"/home/tools/whatweb-0.4.7#"; //prompt = "root";//@backtrack:~/tools/whatweb-0.4.7$"; //prompt = "tools/whatweb-0.4.7"; stdout = sshShell.Expect(prompt); Utils.Helper_Trace("XORCISM PROVIDER WHATWEB", string.Format("JobID: {0} START DUMP STDOUT01", m_jobId)); Utils.Helper_Trace("XORCISM PROVIDER WHATWEB", stdout); cmd1 = "sudo /usr/local/rvm/bin/rvm use 1.8.7"; sshShell.WriteLine(cmd1); Thread.Sleep(2000); stdout = sshShell.Expect(prompt); Utils.Helper_Trace("XORCISM PROVIDER WHATWEB", string.Format("JobID: {0} START DUMP STDOUT02", m_jobId)); Utils.Helper_Trace("XORCISM PROVIDER WHATWEB", stdout); sshShell.WriteLine(password); Thread.Sleep(2000); stdout = sshShell.Expect(prompt); Utils.Helper_Trace("XORCISM PROVIDER WHATWEB", string.Format("JobID: {0} START DUMP STDOUT03", m_jobId)); Utils.Helper_Trace("XORCISM PROVIDER WHATWEB", stdout); /* See for provider m_model */ /* For an URL */ /* * AGGRESSION LEVELS: * --aggression, -a=LEVEL The aggression level controls the trade-off between * speed/stealth and reliability. Default: 1 * Aggression levels are: * 1 (Passive) Make one HTTP request per target. Except for redirects. * 2 (Polite) Reserved for future use * 3 (Aggressive) Triggers aggressive plugin functions only when a * plugin matches passively. * 4 (Heavy) Trigger aggressive functions for all plugins. Guess a * lot of URLs like Nikto. */ string agressionlevel = "1"; if (m_policy == "Moderate") { agressionlevel = "3"; } if (m_policy == "Intrusive") { agressionlevel = "4"; } if (m_policy == "PCI DSS") { agressionlevel = "3"; } cmd1 = string.Format("sudo ./whatweb -r -a {0} {1} --log-xml={2}", agressionlevel, m_target, file); Utils.Helper_Trace("XORCISM PROVIDER WHATWEB", string.Format("JobID: {0} Executing command [{1}]", m_jobId, cmd1)); sshShell.WriteLine(cmd1); Thread.Sleep(2000); stdout = ""; string localOutputFile; localOutputFile = Path.GetTempFileName(); //ON ATTEND PLUS LE PROMPT CAR DES FOIS CA VIENT PAS - DEBUG A VOIR Thread.Sleep(60000); /* * stdout = sshShell.Expect(prompt); * * Utils.Helper_Trace("XORCISM PROVIDER WHATWEB", string.Format("JobID: {0} START DUMP STDOUT04", m_jobId)); * Utils.Helper_Trace("XORCISM PROVIDER WHATWEB", stdout); * //whatweb: command not found * //http://www.marocannonces.com/ ERROR: Timed out execution expired * * // HACK : * // outputfile = "634244542240861588_39608125_output"; * * if (stdout.Contains("bson_ext gem is in your load path")) * { * Utils.Helper_Trace("XORCISM PROVIDER WHATWEB", string.Format("JobID: {0} ExecutingAGAIN command [{1}]", m_jobId, cmd1)); * //We were not root? * sshShell.WriteLine(cmd1); * Thread.Sleep(2000); * stdout = sshShell.Expect(prompt); * * Utils.Helper_Trace("XORCISM PROVIDER WHATWEB", string.Format("JobID: {0} START DUMP STDOUT05", m_jobId)); * Utils.Helper_Trace("XORCISM PROVIDER WHATWEB", stdout); * } */ if (stdout.Contains("bson_ext gem is in your load path")) { //TODO: voir cette erreur } else { whatweb_get_result(m_jobId, file, localOutputFile, 1); } // aff_list(); // Pause Console.ReadLine(); sshShell.Close(); sshShell = null; return(true); }
public bool Parse() { Assembly a; /* A way for loading XMLfile */ a = Assembly.GetExecutingAssembly(); Utils.Helper_Trace("XORCISM PROVIDER NIKTO", "NIKTO Assembly location = " + a.Location); /* Name of XML result */ string file; file = string.Format("result_{0}_{1}.xml", DateTime.Now.Ticks, this.GetHashCode()); Utils.Helper_Trace("XORCISM PROVIDER NIKTO", string.Format("JobID: {0} Results will be stored in file [{1}]", m_jobId, file)); /* SSH instructions & declarations */ int port = 22; string address, username, password; string prompt; /* * address = "111.222.333.444"; * username = "******"; * password = "******"; * prompt = "root@xmachine:"; */ //HARDCODED address = "111.222.333.444"; username = "******"; password = "******"; prompt = "root"; //@backtrack: SshShell sshShell; sshShell = new SshShell(address, username, password); // sshShell.RemoveTerminalEmulationCharacters = true; Utils.Helper_Trace("XORCISM PROVIDER NIKTO", string.Format("JobID: {0} Connecting to NIKTO server at {1}", m_jobId, address)); try { sshShell.Connect(port); //sshShell.Expect(prompt+"~#"); sshShell.Expect(prompt);// + "~$"); } catch (Exception ex) { Utils.Helper_Trace("XORCISM PROVIDER NIKTO", "Error in sshconnection to " + address + " " + ex.Message + " " + ex.InnerException); } // if ssh connection if (sshShell.Connected) { Utils.Helper_Trace("XORCISM PROVIDER NIKTO", string.Format("JobID: {0} Successfully connected to NIKTO server", m_jobId)); //string output; string stdout = ""; /* Command 1 */ string cmd1; //cmd1 = "cd /home/tools/nikto-2.1.4"; cmd1 = "cd /home/root/tools/nikto-2.1.4"; //HARDCODED sshShell.WriteLine(cmd1); //prompt = prompt+"/home/tools/nikto-2.1.4#"; //prompt = "tools/nikto-2.1.4$"; stdout = sshShell.Expect(prompt); /* See for provider m_model */ /* For an URL */ /* * @ -T => tunning or strategy * @ -C all => to force check all possible dirs */ //cmd1 = string.Format("nikto -Format XML -o {2} -host {1} -T {3} -C all", m_policy, m_target, file, m_strategy); //-g -e 6 cmd1 = string.Format("./nikto.pl -Format XML -o {2} -host {1} -C all", m_policy, m_target, file); //-g -e 6 //HARDCODED Utils.Helper_Trace("XORCISM PROVIDER NIKTO", string.Format("JobID: {0} Executing command [{1}]", m_jobId, cmd1)); sshShell.WriteLine(cmd1); stdout = sshShell.Expect(prompt); Utils.Helper_Trace("XORCISM PROVIDER NIKTO", string.Format("JobID: {0} START DUMP STDOUT01", m_jobId)); Utils.Helper_Trace("XORCISM PROVIDER NIKTO", stdout); string localOutputFile; localOutputFile = Path.GetTempFileName(); Utils.Helper_Trace("XORCISM PROVIDER NIKTO", string.Format("Downloading results via SFTP to [{0}]", localOutputFile)); nikto_get_result(file, localOutputFile); Utils.Helper_Trace("XORCISM PROVIDER NIKTO", string.Format("JobID: {0} XML PARSE successfull for file : [{1}] ", m_jobId, file)); //aff_list(); // Pause Console.ReadLine(); sshShell.Close(); sshShell = null; return(true); } else { Utils.Helper_Trace("XORCISM PROVIDER NIKTO", string.Format("JobID: {0} Connection failed to NIKTO server", m_jobId)); return(false); } }
public bool Parse() { Utils.Helper_Trace("XORCISM PROVIDER ARACHNI", "Parse()"); Assembly a; /* A way for loading XMLfile */ XPathNavigator nav; XPathNavigator nav1; XPathDocument docNav; XPathNodeIterator NodeIter1; String strExpression1; a = Assembly.GetExecutingAssembly(); Utils.Helper_Trace("XORCISM PROVIDER ARACHNI", "ARACHNI Assembly location = " + a.Location); /* Name of XML result */ string file; file = string.Format("result_{0}_{1}.xml", DateTime.Now.Ticks, this.GetHashCode()); Utils.Helper_Trace("XORCISM PROVIDER ARACHNI", string.Format("JobID: {0} Results will be stored in file [{1}]", m_jobId, file)); /* SSH instructions & declarations */ //HARDCODED int port = 22; string address, username, password; string prompt; address = "192.168.1.2"; //TODO Hardcoded username = "******"; password = "******"; prompt = "root"; //@backtrack:"; //Kali... SshShell sshShell; sshShell = new SshShell(address, username, password); sshShell.RemoveTerminalEmulationCharacters = true; Utils.Helper_Trace("XORCISM PROVIDER ARACHNI", string.Format("JobID: {0} Connecting to ARACHNI server at {1}", m_jobId, address)); try{ sshShell.Connect(port); //sshShell.Expect(prompt+"~#"); sshShell.Expect(prompt);// + "~$"); } catch (Exception ex) { Utils.Helper_Trace("XORCISM PROVIDER ARACHNI", string.Format("JobID: {0} ConnectingERROR to ARACHNI server at {1} : " + ex.Message + " " + ex.InnerException, m_jobId, address)); address = "192.168.1.2"; //TODO hardcoded username = "******"; password = "******"; prompt = "root";//@backtrack:"; sshShell = new SshShell(address, username, password); sshShell.RemoveTerminalEmulationCharacters = true; Utils.Helper_Trace("XORCISM PROVIDER ARACHNI", string.Format("JobID: {0} Connecting to ARACHNI server at {1}", m_jobId, address)); try { sshShell.Connect(port); sshShell.Expect(prompt);// + "~$"); } catch (Exception ex2) { Utils.Helper_Trace("XORCISM PROVIDER ARACHNI", string.Format("JobID: {0} ConnectingERROR to ARACHNI server at {1} : " + ex2.Message + " " + ex2.InnerException, m_jobId, address)); } } Utils.Helper_Trace("XORCISM PROVIDER ARACHNI", string.Format("JobID: {0} Successfully connected to ARACHNI server", m_jobId)); //string output; string stdout = ""; //string stderr = ""; /* Command 1 */ string cmd1; /* See for provider m_model */ /* For an URL */ cmd1 = string.Format("arachni {1} --report='xml:outfile={2}'", m_policy, m_target, file); Utils.Helper_Trace("XORCISM PROVIDER ARACHNI", string.Format("JobID: {0} Executing command [{1}]", m_jobId, cmd1)); sshShell.WriteLine(cmd1); stdout = sshShell.Expect(prompt); Utils.Helper_Trace("XORCISM PROVIDER ARACHNI", string.Format("JobID: {0} START DUMP STDOUT01", m_jobId)); Utils.Helper_Trace("XORCISM PROVIDER ARACHNI", stdout); string localOutputFile; localOutputFile = Path.GetTempFileName(); // HACK : // outputfile = "634244542240861588_39608125_output"; Utils.Helper_Trace("XORCISM PROVIDER ARACHNI", string.Format("Downloading results via SFTP to [{0}]", localOutputFile)); try { Sftp ftp; ftp = new Sftp(address, username, password); ftp.OnTransferStart += new FileTransferEvent(ftp_OnTransferStart); ftp.OnTransferProgress += new FileTransferEvent(ftp_OnTransferProgress); ftp.OnTransferEnd += new FileTransferEvent(ftp_OnTransferEnd); ftp.Connect(port); ftp.Get("/" + file, localOutputFile); ftp.Close(); } catch (Exception ex) { Utils.Helper_Trace("XORCISM PROVIDER ARACHNI", string.Format("Exception = {0} / {1}", ex.Message, ex.InnerException == null ? "" : ex.InnerException.Message)); return(false); } Utils.Helper_Trace("XORCISM PROVIDER ARACHNI", "Loading the xml document"); /* SAMPLE of XML structure * * <?xml version=" * <arachni_report> * <title>...</title> * <generated_on>...</generated_on> * <report_false_positives>http://github.com/Zapotek/arachni/issues</report_false_positives> * <system> * <version...</version> * <revision>...</revision> * <start_datetime>...</start_datetime> * <finish_datetime>...</finish_datetime> * <delta_time>...</delta_time> * <url>...</url> * <user_agent>...</user_agent> * <audited_elements> * <element>...</element> * </audited_elements> * <modules> * <module name="..."/> * </modules> * <filters> * <exclude> * </exclude> * <include> * <regexp>...</regexp> * </include> * <redundant> * </redundant> * </filters> * <cookies> * <cookie name="..." value="..." /> * </cookies> * </system> * <issues> * <issue> * <name>...</name> * <url>...</url> * <element>...</element> * <method>...</method> * <tags> * <tag name="..." /> * </tags> * <variable>..</variable> * <description>...</description> * <manual_verification...</manual_verification> * <references> * <reference name="..." url="..." /> * </references> * <variations> * <variation> * <url>...</url> * <injected>...</injected> * <regexp_match>...</regexp_match> * <headers> * <request> * <field name="..." value="..." /> * </request> * <response> * <field name="..." value="..." /> * </response> * </headers> * <html>...</html> * <variation> * <variations> * ... * </arachni_report> */ try { docNav = new XPathDocument(localOutputFile); // for test : result_634521969362210000_41014879.xml || URL file : file nav = docNav.CreateNavigator(); nav1 = docNav.CreateNavigator(); // If all is OK! Utils.Helper_Trace("XORCISM PROVIDER ARACHNI", string.Format("JobID: {0} Successfully loaded XML file : [{1}] ", m_jobId, file)); // Go to parse try { // For read all plugin's strExpression1 = "/arachni_report/title | /arachni_report/generated_on | /arachni_report/report_false_positives | /arachni_report/system/start_datetime | /arachni_report/system/finish_datetime | /arachni_report/system/delta_time | /arachni_report/system/url | /arachni_report/system/audited_elements/element | /arachni_report/issues/issue/name | /arachni_report/issues/issue/url | /arachni_report/issues/issue/element | /arachni_report/issues/issue/method | /arachni_report/issues/issue/tags/tag/@name | /arachni_report/issues/issue/variable | /arachni_report/issues/issue/description | /arachni_report/issues/issue/manual_verification | /arachni_report/issues/issue/references/reference/@name | /arachni_report/issues/issue/references/reference/@url | /arachni_report/issues/issue/variations/variation/url | /arachni_report/issues/issue/variations/variation/injected | /arachni_report/issues/issue/variations/variation/regexp_match | /arachni_report/issues/issue/variations/variation/headers/request/field/@name | /arachni_report/issues/issue/variations/variation/headers/request/field/@value | /arachni_report/issues/issue/variations/variation/headers/response/field/@value | /arachni_report/issues/issue/variations/variation/headers/response/field/@name | /arachni_report/issues/issue/variations/variation/html"; NodeIter1 = nav1.Select(strExpression1); while (NodeIter1.MoveNext()) { switch ((string)NodeIter1.Current.Name) { case "title": Utils.Helper_Trace("XORCISM PROVIDER ARACHNI", string.Format("JobID: {0} XML PARSE - TITLE : [{1}] ", m_jobId, NodeIter1.Current.Value)); break; case "generated_on": Utils.Helper_Trace("XORCISM PROVIDER ARACHNI", string.Format("JobID: {0} XML PARSE - GENERATED-TIME : [{1}] ", m_jobId, NodeIter1.Current.Value)); break; case "report_false_positives": Utils.Helper_Trace("XORCISM PROVIDER ARACHNI", string.Format("JobID: {0} XML PARSE - REPORT : [{1}] ", m_jobId, NodeIter1.Current.Value)); break; case "start_datetime": Utils.Helper_Trace("XORCISM PROVIDER ARACHNI", string.Format("JobID: {0} XML PARSE - START-TIME : [{1}] ", m_jobId, NodeIter1.Current.Value)); break; case "finish_datetime": Utils.Helper_Trace("XORCISM PROVIDER ARACHNI", string.Format("JobID: {0} XML PARSE - FINISH-TIME : [{1}] ", m_jobId, NodeIter1.Current.Value)); break; case "delta_time": Utils.Helper_Trace("XORCISM PROVIDER ARACHNI", string.Format("JobID: {0} XML PARSE - DELTA-TIME : [{1}] ", m_jobId, NodeIter1.Current.Value)); break; case "element": Utils.Helper_Trace("XORCISM PROVIDER ARACHNI", string.Format("JobID: {0} XML PARSE - ELEMENT : [{1}] ", m_jobId, NodeIter1.Current.Value)); break; case "name": Utils.Helper_Trace("XORCISM PROVIDER ARACHNI", string.Format("JobID: {0} XML PARSE - ISSUE-NAME : [{1}] ", m_jobId, NodeIter1.Current.Value)); break; case "url": Utils.Helper_Trace("XORCISM PROVIDER ARACHNI", string.Format("JobID: {0} XML PARSE - ISSUE-URL : [{1}] ", m_jobId, NodeIter1.Current.Value)); break; case "method": Utils.Helper_Trace("XORCISM PROVIDER ARACHNI", string.Format("JobID: {0} XML PARSE - ISSUE-METHOD : [{1}] ", m_jobId, NodeIter1.Current.Value)); break; case "modules": Utils.Helper_Trace("XORCISM PROVIDER ARACHNI", string.Format("JobID: {0} XML PARSE - MODULE : [{1}] ", m_jobId, NodeIter1.Current.Value)); break; } list_parse.Add((string)NodeIter1.Current.Value); } ; } catch (System.Exception ex) { Utils.Helper_Trace("XORCISM PROVIDER ARACHNI", "JobID:" + m_jobId + "Exception Parsing XML PLUGIN'S = " + ex.Message + " " + ex.InnerException); } } catch (System.Exception ex) { Utils.Helper_Trace("XORCISM PROVIDER ARACHNI", "JobID:" + m_jobId + "Exception LOADING XML = " + ex.Message + " " + ex.InnerException); } Utils.Helper_Trace("XORCISM PROVIDER ARACHNI", string.Format("JobID: {0} XML PARSE successfull for file : [{1}] ", m_jobId, file)); aff_list(); // Pause Console.ReadLine(); sshShell.Close(); sshShell = null; return(true); }