private bool AskUserReliability(ISSHLoginParameter param, SSHConnectionInfo info, string keystr, string message_text_id) { //比較結果に基づく処理 IPoderosaForm form = UsabilityPlugin.Instance.WindowManager.ActiveWindow; Debug.Assert(form.AsForm().InvokeRequired); //別スレッドで実行しているはず //fingerprint StringBuilder bld = new StringBuilder(); byte[] fingerprint = info.HostKeyMD5FingerPrint(); for (int i = 0; i < fingerprint.Length; i++) { if (bld.Length > 0) { bld.Append(':'); } bld.Append(fingerprint[i].ToString("x2")); } string message = String.Format("ssh hostkey fingerprint {0}\n\n{1}", bld.ToString(), UsabilityPlugin.Strings.GetString(message_text_id)); if (form.AskUserYesNo(message) == DialogResult.Yes) { Update(param, keystr, true); return(true); } else { return(false); } }
public async Task Load() { IsLoading.Value = true; try { await DbBackup.Execute(); } catch (Exception ex) { MyLogger.Log("Exception occured on DB backup.", ex); } MyLogger.Log("Data loading..."); DbContext = new AppDbContext(); var cacheLoading = PortNumberCache.Load(); var dbLoading = Task.Run(async() => { await SSHConnectionInfo.RefreshAll(DbContext); SSHConnectionInfo.All .ForEach(x => App.Current.Dispatcher.Invoke(() => SSHConnectionInfos.Items.Add(x))); DbContext.RDPConnectionInfos.ToList() .ForEach(x => App.Current.Dispatcher.Invoke(() => RDPConnectionInfos.Items.Add(x))); DbContext.InitSecurePasswords(); }); await Task.WhenAll(new[] { cacheLoading, dbLoading, }); MyLogger.Log("Data loaded."); IsLoading.Value = false; InitConnectionInvokeTimer(); }
public bool Verify(ISSHLoginParameter param, SSHConnectionInfo info) { if (!_loaded) { try { Load(); } catch (Exception ex) { //ロード中のエラーのときは鍵は拒否。安全側に! RuntimeUtil.ReportException(ex); return(false); } } string keystr = info.DumpHostKeyInKnownHostsStyle(); string local = param.Method == SSHProtocol.SSH1 ? _dataForSSH1[ToKeyString(param)] : _dataForSSH2[ToKeyString(param)]; if (local == null) { return(AskUserReliability(param, info, keystr, "Message.HostKeyChecker.AskHostKeyRegister")); } else if (keystr != local) { return(AskUserReliability(param, info, keystr, "Message.HostKeyChecker.AskHostKeyRenew")); } else { return(true); } }
public void Connect(Socket s) { this._params.WindowSize = 0x1000; this._conn = SSHConnection.Connect(this._params, this, s); this._pf = this._conn.OpenShell(this); SSHConnectionInfo ci = this._conn.ConnectionInfo; }
public void start() { try { SSHConnectionParameter f = new SSHConnectionParameter(); f.UserName = userName; f.Password = passwordWord; f.Protocol = SSHProtocol.SSH2; f.AuthenticationType = AuthenticationType.Password; f.WindowSize = 0x1000; _objTmp = new Dictionary <TextBox, StringBuilder>(); Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //s.Blocking = false; s.Connect(new IPEndPoint(IPAddress.Parse(ip), _port)); _conn = SSHConnection.Connect(f, this, s); this._conn = _conn; SSHChannel ch = _conn.OpenShell(this); this._pf = ch; _linePool = new List <string>(); SSHConnectionInfo ci = _conn.ConnectionInfo; } catch (Exception e1) { SetText(_objTmp, form.consoleBox, e1.Message); } }
public bool CheckHostKeyCallback(SSHConnectionInfo ci) { /* * string keystr = ci.DumpHostKeyInKnownHostsStyle(); * KeyCheckResult r = GEnv.SSHKnownHosts.Check(_tryingParam, keystr); * if(r==KeyCheckResult.NotExists) { * if(GEnv.InterThreadUIService.AskUserYesNo(GEnv.Strings.GetString("Message.HostKeyChecker.AskHostKeyRegister"))==DialogResult.Yes) { * GEnv.SSHKnownHosts.Update(_tryingParam, keystr); * return true; * } * else * return false; * } * else if(r==KeyCheckResult.Different) { * if(GEnv.InterThreadUIService.AskUserYesNo(GEnv.Strings.GetString("Message.HostKeyChecker.AskHostKeyRenew"))==DialogResult.Yes) { * GEnv.SSHKnownHosts.Update(_tryingParam, keystr); * return true; * } * else * return false; * } * else * return true; */ return(true); }
protected void PrepareRequiredConnection(SSHConnectionInfo requiredConnectionInfo) { if (requiredConnectionInfo == null) { return; } var additionalPF = new PortForwarding { Type = "Local", RemoteHost = ConnectionInfo.Host, RemotePort = ConnectionInfo.Port, }; // Try to re-use recently used port. var recentlyUsedPort = ConnectionInfo.GetAvailableCachedPort(); if (recentlyUsedPort > 0) { additionalPF.LocalPort = recentlyUsedPort; } var conn = new SSHConnectionViewModel(requiredConnectionInfo, false, additionalPF) { Parent = this }; conn.IsRoot.Value = false; RequiredConnection = conn; Children.Add(conn); }
private void button2_Click(object sender, EventArgs e) { SSHConnectionParameter f = new SSHConnectionParameter(); f.UserName = "******"; f.Password = "******"; f.Protocol = SSHProtocol.SSH2; f.AuthenticationType = AuthenticationType.Password; Reader reader = new Reader(); Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); s.Connect(new IPEndPoint(IPAddress.Parse("192.168.10.131"), 22)); _conn = SSHConnection.Connect(f, reader, s); reader._conn = _conn; SSHChannel ch = _conn.OpenShell(reader); reader._pf = ch; SSHConnectionInfo ci = _conn.ConnectionInfo; Thread.Sleep(1000); byte[] b = new byte[1]; string cmd = "ls"; byte[] data = (new UnicodeEncoding()).GetBytes(cmd); reader._pf.Transmit(data); Thread.Sleep(5000); string x = reader.SessionLog; //reader.OnData += }
public void Connect(Socket s) { _params.WindowSize = 0x1000; _params.IdentityFile = SSH2PrivateKeyFile; _conn = SSHConnection.Connect(_params, this, s); _pf = _conn.OpenShell(this); SSHConnectionInfo ci = _conn.ConnectionInfo; }
public void OpenConnect() { f.UserName = username; f.Password = password; f.Protocol = SSHProtocol.SSH2; f.AuthenticationType = AuthenticationType.Password; f.WindowSize = 0x1000; s.Connect(new IPEndPoint(IPAddress.Parse(host), port)); _conn = SSHConnection.Connect(f, this, s); this._pf = _conn.OpenShell(this); SSHConnectionInfo ci = _conn.ConnectionInfo; }
private async Task Invoke(SSHConnectionInfo info) { try { Model.Invoke(info); } catch (Exception) { await MainWindow.ShowMessageDialog( Resources.ExternalProgramDefinition_Dialog_Invoke_Failed_Message, Resources.ExternalProgramDefinition_Dialog_Invoke_Title); } }
public bool Vefiry(ISSHLoginParameter param, SSHConnectionInfo info) { if (_verifier == null) { _verifier = FindHostKeyVerifier(); } if (_verifier == null) { return(true); //•’ÊKnownHosts‚‚ç‚¢‚Í‚ ‚邾‚낤BƒGƒ‰[‚É‚·‚ׂ«‚©‚à‚µ‚ê‚È‚¢‚ª } else { return(_verifier.Verify(param, info)); } }
public PNetPowerShell(string hostName, string userName, string keyFile) { if (string.IsNullOrEmpty(hostName)) { throw new ArgumentNullException(nameof(hostName)); } if (string.IsNullOrEmpty(userName)) { throw new ArgumentNullException(nameof(userName)); } var conInfo = new SSHConnectionInfo(userName, hostName, keyFile); _pool = new PNetRunspacePool(conInfo); }
public bool Vefiry(ISSHLoginParameter param, SSHConnectionInfo info) { if (_verifier == null) { _verifier = FindHostKeyVerifier(); } if (_verifier == null) { return(true); //普通KnownHostsくらいはあるだろう。エラーにすべきかもしれないが } else { return(_verifier.Verify(param, info)); } }
/// <summary> /// Method to connect to the Wabis machine /// </summary> /// <returns>true if connected else false</returns> public bool Connect() { connParameter.Protocol = Routrek.SSHC.SSHProtocol.SSH2; connParameter.AuthenticationType = AuthenticationType.Password; connParameter.WindowSize = 0x1000; Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp); try { s.Connect(new IPEndPoint(_ipAddress, 22)); } catch { s.Close(); return(false); } try { _conn = SSHConnection.Connect(connParameter, reader, s); reader.connection = _conn; Routrek.SSHC.SSHChannel ch = _conn.OpenShell(reader); reader.Channel = ch; SSHConnectionInfo ci = _conn.ConnectionInfo; reader.notify += new RcvdData(PrintResult); if (_conn.AuthenticationResult.ToString() == "Success") { return(true); } else { return(false); } } catch (Exception connectionException) { Framework.Logger.LogError("Fail to connect to SSH Server, error: " + connectionException.Message); throw connectionException; } }
/// <summary> /// Returns the prompt used in remote sessions: "[machine]: basePrompt" /// </summary> internal static string GetRemotePrompt(RemoteRunspace runspace, string basePrompt, bool configuredSession = false) { if (configuredSession || runspace.ConnectionInfo is NamedPipeConnectionInfo || runspace.ConnectionInfo is VMConnectionInfo || runspace.ConnectionInfo is ContainerConnectionInfo) { return(basePrompt); } SSHConnectionInfo sshConnectionInfo = runspace.ConnectionInfo as SSHConnectionInfo; // Usernames are case-sensitive on Unix systems if (sshConnectionInfo != null && !string.IsNullOrEmpty(sshConnectionInfo.UserName) && !System.Environment.UserName.Equals(sshConnectionInfo.UserName, StringComparison.Ordinal)) { return(string.Format(CultureInfo.InvariantCulture, "[{0}@{1}]: {2}", sshConnectionInfo.UserName, sshConnectionInfo.ComputerName, basePrompt)); } return(string.Format(CultureInfo.InvariantCulture, "[{0}]: {1}", runspace.ConnectionInfo.ComputerName, basePrompt)); }
public async Task RemoteExitCode() { //hack for remote connection if (Runspace.DefaultRunspace == null) { var defaultRunspace = RunspaceFactory.CreateRunspace(); defaultRunspace.Open(); Runspace.DefaultRunspace = defaultRunspace; } var localRs = RunspaceFactory.CreateRunspace(); var localPipe = localRs.CreatePipeline("pwsh -c 'exit 123'"); localRs.Open(); var localResult = localPipe.Invoke(); Assert.True(localPipe.HadErrors); Assert.Empty(localResult); localRs.Close(); var connectionInfo = new SSHConnectionInfo("root", "lnx1513", null); var remoteRS = RunspaceFactory.CreateRunspace(connectionInfo); var remotePipe = remoteRS.CreatePipeline("pwsh -c 'exit 123'"); remoteRS.Open(); var remoteResult = remotePipe.Invoke(); Assert.True(remotePipe.HadErrors); Assert.Empty(remoteResult); remoteRS.Close(); }
static void Main(string[] args) { /* * string cn = System.Threading.Thread.CurrentThread.CurrentUICulture.Name; * string t1 = Routrek.SSHC.Strings.GetString("NotSSHServer"); * System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("ja"); * Routrek.SSHC.Strings.Reload(); * string t2 = Routrek.SSHC.Strings.GetString("NotSSHServer"); */ #if false //RSA keygen //RSA KEY GENERATION TEST byte[] testdata = Encoding.ASCII.GetBytes("CHRISTIAN VIERI"); RSAKeyPair kp = RSAKeyPair.GenerateNew(2048, new Random()); byte[] sig = kp.Sign(testdata); kp.Verify(sig, testdata); new SSH2UserAuthKey(kp).WritePublicPartInOpenSSHStyle(new FileStream("C:\\IOPort\\newrsakey", FileMode.Create)); //SSH2UserAuthKey newpk = SSH2PrivateKey.FromSECSHStyleFile("C:\\IOPort\\newrsakey", "nedved"); #endif #if false //DSA keygen //DSA KEY GENERATION TEST byte[] testdata = Encoding.ASCII.GetBytes("CHRISTIAN VIERI 0000"); DSAKeyPair kp = DSAKeyPair.GenerateNew(2048, new Random()); byte[] sig = kp.Sign(testdata); kp.Verify(sig, testdata); new SSH2UserAuthKey(kp).WritePublicPartInOpenSSHStyle(new FileStream("C:\\IOPort\\newdsakey", FileMode.Create)); //SSH2PrivateKey newpk = SSH2PrivateKey.FromSECSHStyleFile("C:\\IOPort\\newdsakey", "nedved"); #endif SSHConnectionParameter f = new SSHConnectionParameter(); f.UserName = "******"; #if false //SSH1 //SSH1 f.Password = ""; f.Protocol = SSHProtocol.SSH2; f.AuthenticationType = AuthenticationType.Password; f.PreferableCipherAlgorithms = new CipherAlgorithm[] { CipherAlgorithm.Blowfish, CipherAlgorithm.TripleDES }; #else //SSH2 f.Password = ""; f.Protocol = SSHProtocol.SSH2; f.AuthenticationType = AuthenticationType.Password; f.WindowSize = 0x1000; #endif Reader reader = new Reader(); Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //s.Blocking = false; s.Connect(new IPEndPoint(IPAddress.Parse("192.168.1.1"), 22)); _conn = SSHConnection.Connect(f, reader, s); reader._conn = _conn; #if false //Remote->Local _conn.ListenForwardedPort("0.0.0.0", 29472); #elif false //Local->Remote SSHChannel ch = _conn.ForwardPort(reader, "www.yahoo.co.jp", 80, "localhost", 0); reader._pf = ch; while (!reader._ready) { System.Threading.Thread.Sleep(100); } reader._pf.Transmit(Encoding.ASCII.GetBytes("GET / HTTP/1.0\r\n\r\n")); #elif false //SSH over SSH f.Password = "******"; SSHConnection con2 = _conn.OpenPortForwardedAnotherConnection(f, reader, "kuromatsu", 22); reader._conn = con2; SSHChannel ch = con2.OpenShell(reader); reader._pf = ch; #else //normal shell SSHChannel ch = _conn.OpenShell(reader); reader._pf = ch; #endif //Debug.WriteLine(_conn.ConnectionInfo.DumpHostKeyInKnownHostsStyle()); SSHConnectionInfo ci = _conn.ConnectionInfo; Thread.Sleep(1000); //((SSH2Connection)_conn).ReexchangeKeys(); byte[] b = new byte[1]; while (true) { int input = System.Console.Read(); b[0] = (byte)input; //Debug.WriteLine(input); reader._pf.Transmit(b); } }
private bool CheckKey(SSHConnectionInfo ci) { SetIgnoreTimeout(); return(_keycheck(ci)); }
}// CreateHelpersForSpecifiedComputerNames /// <summary> /// Creates helper objects for host names for PSRP over SSH /// remoting. /// </summary> protected void CreateHelpersForSpecifiedHostNames() { var sshConnectionInfo = new SSHConnectionInfo(this.UserName, this.HostName, this.KeyFilePath); var typeTable = TypeTable.LoadDefaultTypeFiles(); var remoteRunspace = RunspaceFactory.CreateRunspace(sshConnectionInfo, this.Host, typeTable) as RemoteRunspace; var pipeline = CreatePipeline(remoteRunspace); var operation = new ExecutionCmdletHelperComputerName(remoteRunspace, pipeline); Operations.Add(operation); }
private bool CheckKey(SSHConnectionInfo ci) { return(_keycheck.Vefiry(_destination, ci)); }
//ISSHHostKeyVerifier public bool Verify(ISSHLoginParameter param, SSHConnectionInfo info) { return(_acceptsHostKey); }
/// <summary> /// Create remote runspace for SSH session /// </summary> private RemoteRunspace GetRunspaceForSSHSession() { var sshConnectionInfo = new SSHConnectionInfo(this.UserName, this.HostName, this.KeyFilePath); var typeTable = TypeTable.LoadDefaultTypeFiles(); var remoteRunspace = RunspaceFactory.CreateRunspace(sshConnectionInfo, this.Host, typeTable) as RemoteRunspace; remoteRunspace.Open(); remoteRunspace.ShouldCloseOnPop = true; return remoteRunspace; }
}// CreateRunspacesWhenContainerParameterSpecified /// <summary> /// CreateRunspacesForSSHHostParameterSet /// </summary> /// <returns></returns> private List<RemoteRunspace> CreateRunspacesForSSHHostParameterSet() { var remoteRunspaces = new List<RemoteRunspace>(); var sshConnectionInfo = new SSHConnectionInfo( this.UserName, this.HostName, this.KeyPath); var typeTable = TypeTable.LoadDefaultTypeFiles(); remoteRunspaces.Add(RunspaceFactory.CreateRunspace(sshConnectionInfo, this.Host, typeTable) as RemoteRunspace); return remoteRunspaces; }
/// <summary> /// This constructor will be used to created a remote runspace info /// object with a auto generated name /// </summary> /// <param name="remoteRunspace">Remote runspace object for which /// the info object need to be created</param> internal PSSession(RemoteRunspace remoteRunspace) { _remoteRunspace = remoteRunspace; // Use passed in session Id, if available. if (remoteRunspace.PSSessionId != -1) { Id = remoteRunspace.PSSessionId; } else { Id = System.Threading.Interlocked.Increment(ref s_seed); remoteRunspace.PSSessionId = Id; } // Use passed in friendly name, if available. if (!string.IsNullOrEmpty(remoteRunspace.PSSessionName)) { Name = remoteRunspace.PSSessionName; } else { Name = "Runspace" + Id; remoteRunspace.PSSessionName = Name; } // WSMan session if (remoteRunspace.ConnectionInfo is WSManConnectionInfo) { ComputerType = TargetMachineType.RemoteMachine; string fullShellName = WSManConnectionInfo.ExtractPropertyAsWsManConnectionInfo <string>( remoteRunspace.ConnectionInfo, "ShellUri", string.Empty); ConfigurationName = GetDisplayShellName(fullShellName); return; } // VM session VMConnectionInfo vmConnectionInfo = remoteRunspace.ConnectionInfo as VMConnectionInfo; if (vmConnectionInfo != null) { ComputerType = TargetMachineType.VirtualMachine; ConfigurationName = vmConnectionInfo.ConfigurationName; return; } // Container session ContainerConnectionInfo containerConnectionInfo = remoteRunspace.ConnectionInfo as ContainerConnectionInfo; if (containerConnectionInfo != null) { ComputerType = TargetMachineType.Container; ConfigurationName = containerConnectionInfo.ContainerProc.ConfigurationName; return; } // SSH session SSHConnectionInfo sshConnectionInfo = remoteRunspace.ConnectionInfo as SSHConnectionInfo; if (sshConnectionInfo != null) { ComputerType = TargetMachineType.RemoteMachine; ConfigurationName = "DefaultShell"; return; } // We only support WSMan/VM/Container sessions now. Dbg.Assert(false, "Invalid Runspace"); }
private bool CheckKey(SSHConnectionInfo ci) { SetIgnoreTimeout(); //これが呼ばれるということは途中までSSHのネゴシエートができているのでタイムアウトはしないようにする return(_keycheck(ci)); }
//Tutorial: Connecting to a host and opening a shell private static void ConnectAndOpenShell() { SSHConnectionParameter f = new SSHConnectionParameter(); f.EventTracer = new Tracer(); //to receive detailed events, set ISSHEventTracer Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); f.Protocol = SSHProtocol.SSH2; //this sample works on both SSH1 and SSH2 string host_ip = "172.22.1.15"; //<--!!! [TO USERS OF Granados] f.UserName = "******"; //<--!!! if you try this sample, edit these values for your environment! string password = "******"; s.Connect(new IPEndPoint(IPAddress.Parse(host_ip), 22)); //22 is the default SSH port //former algorithm is given priority in the algorithm negotiation f.PreferableHostKeyAlgorithms = new PublicKeyAlgorithm[] { PublicKeyAlgorithm.RSA, PublicKeyAlgorithm.DSA }; f.PreferableCipherAlgorithms = new CipherAlgorithm[] { CipherAlgorithm.Blowfish, CipherAlgorithm.TripleDES }; f.WindowSize = 0x1000; //this option is ignored with SSH1 Reader reader = new Reader(); //simple event receiver AuthenticationType at = AuthenticationType.PublicKey; f.AuthenticationType = at; if (at == AuthenticationType.KeyboardInteractive) { //Creating a new SSH connection over the underlying socket _conn = SSHConnection.Connect(f, reader, s); reader._conn = _conn; Debug.Assert(_conn.AuthenticationResult == AuthenticationResult.Prompt); AuthenticationResult r = ((SSH2Connection)_conn).DoKeyboardInteractiveAuth(new string[] { password }); Debug.Assert(r == AuthenticationResult.Success); } else { //NOTE: if you use public-key authentication, follow this sample instead of the line above: //f.AuthenticationType = AuthenticationType.PublicKey; f.IdentityFile = "C:\\P4\\tools\\keys\\aaa"; f.Password = password; f.KeyCheck = delegate(SSHConnectionInfo info) { byte[] h = info.HostKeyMD5FingerPrint(); foreach (byte b in h) { Debug.Write(String.Format("{0:x2} ", b)); } return(true); }; //Creating a new SSH connection over the underlying socket _conn = SSHConnection.Connect(f, reader, s); reader._conn = _conn; } //Opening a shell SSHChannel ch = _conn.OpenShell(reader); reader._pf = ch; //you can get the detailed connection information in this way: SSHConnectionInfo ci = _conn.ConnectionInfo; //Go to sample shell SampleShell(reader); }
internal SSHClientSessionTransportManager( SSHConnectionInfo connectionInfo, Guid runspaceId, PSRemotingCryptoHelper cryptoHelper) : base(runspaceId, cryptoHelper) { if (connectionInfo == null) { throw new PSArgumentException("connectionInfo"); } _connectionInfo = connectionInfo; }