Exemplo n.º 1
0
        //profに対応したSSHConnectionを返す。接続がなければparentを親に認証ダイアログを出して認証する
        public SSHConnection GetOrCreateConnection(ChannelProfile prof, Form parent)
        {
            //ホスト名とアカウントのペアからコネクションを共有する仕組みがあるとよいかも
            SSHConnection c = (SSHConnection)_profileToConnection[prof];

            if (c != null)
            {
                return(c);
            }

            SSHShortcutLoginDialog dlg = new SSHShortcutLoginDialog(prof);

            if (dlg.ShowDialog(parent) == DialogResult.OK)
            {
                c = dlg.Result.Connection;
                try {
                    dlg.Result.WaitRequest();
                }
                catch (Exception ex) {
                    Debug.WriteLine(ex.StackTrace);
                    Util.Warning(parent, ex.Message);
                    c.Close();
                    return(null);
                }
                _profileToConnection[prof] = c;
                Env.MainForm.RefreshProfileStatus(prof);
            }

            return(c);
        }
Exemplo n.º 2
0
        public CommandResult InternalExecute(ICommandTarget target, params IAdaptable[] args)
        {
            SSHConnection sshConnection = GetSSHConnection(target);

            // Note: Currently, SCPClient supports only SSH2.
            if (!(sshConnection is SSH2Connection))
            {
                return(CommandResult.Ignored);
            }

            string connectionName = GetTerminalName(target);

            if (connectionName == null)
            {
                connectionName = SFTPPlugin.Instance.StringResource.GetString("Common.UnknownPeer");
            }

            Form ownerForm = GetForm(target);

            if (!ConfirmToUse(ownerForm, "SCP"))
            {
                return(CommandResult.Cancelled);
            }

            SCPClient scp = new SCPClient(sshConnection);

            SCPForm form = new SCPForm(ownerForm, scp, connectionName);

            form.Show();    // Note: don't specify owner to avoid fixed z-order.

            return(CommandResult.Succeeded);
        }
Exemplo n.º 3
0
        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 +=
        }
Exemplo n.º 4
0
 public SSH1Channel(SSHConnection con, ChannelType type, int local_id)
 {
     con.RegisterChannel(local_id, this);
     _connection = con;
     _type       = type;
     _localID    = local_id;
 }
Exemplo n.º 5
0
 private void DoAuth()
 {
     DoSaveSettings(EditPassword.text, FCookie);
     DoShowLogin(true);
     SSHConnection.DebugServer = TestServer.isOn;
     SSHConnection.ServerConnect();
 }
Exemplo n.º 6
0
        public void ReadBackWithPrompt()
        {
            var info = util.GetUsernameAndPassword();

            using (var s = new SSHConnection(info.Item1, info.Item2))
            {
                Console.WriteLine("Before we do anything here is the environment:");
                s.ExecuteCommand("set", l => Console.WriteLine(" set: " + l));
                Console.WriteLine();
                Console.WriteLine();
                Console.WriteLine();

                bool valueSet  = false;
                bool sawPrompt = false;
                s.ExecuteCommand("prompt=\"what is up: \"");
                s.ExecuteCommand("read -p \"$prompt\" bogusvalue", l =>
                {
                    sawPrompt = sawPrompt || l.Contains("what is up");
                    Console.WriteLine("==> " + l);
                }, seeAndRespond: new Dictionary <string, string>()
                {
                    { "up:", "this freak me out is a test" }
                })
                .ExecuteCommand("set", l => Console.WriteLine(" set: " + l))
                .ExecuteCommand("echo bogusvalue $bogusvalue", l =>
                {
                    valueSet = valueSet || l.Contains("this");
                    Console.WriteLine("--> " + l);
                });

                // THis guy isn't working yet because we don't seem to read in any input.
                Assert.IsTrue(sawPrompt);
                Assert.IsTrue(valueSet);
            }
        }
Exemplo n.º 7
0
        public void CopyTwice()
        {
            var info = util.GetUsernameAndPassword();

            using (var s = new SSHConnection(info.Item1, info.Item2))
            {
                // Create a "complex" directory structure on the remote machine
                s
                .ExecuteCommand("mkdir -p /tmp/usergwatts/data")
                .ExecuteCommand("mkdir -p /tmp/usergwatts/data/d1")
                .ExecuteCommand("mkdir -p /tmp/usergwatts/data/d2")
                .ExecuteCommand("echo hi1 > /tmp/usergwatts/data/f1")
                .ExecuteCommand("echo hi2 > /tmp/usergwatts/data/d1/f2")
                .ExecuteCommand("echo hi3 > /tmp/usergwatts/data/d2/f3")
                .ExecuteCommand("echo hi4 > /tmp/usergwatts/data/d2/f4");

                // Remove everything local
                var d = new DirectoryInfo("./data");
                if (d.Exists)
                {
                    d.Delete(true);
                    d.Refresh();
                }
                d.Create();

                // Do the copy
                s.CopyRemoteDirectoryLocally("/tmp/usergwatts/data", d);
                s.CopyRemoteDirectoryLocally("/tmp/usergwatts/data", d);
            }
        }
Exemplo n.º 8
0
        //終了のハンドリング 非同期に別スレッドから呼ばれるので注意
        public void ConnectionClosed(SSHConnection connection)
        {
            IDictionaryEnumerator e = _profileToConnection.GetEnumerator();

            while (e.MoveNext())
            {
                if (connection == e.Value)
                {
                    ChannelProfile prof = (ChannelProfile)e.Key;
                    _profileToConnection.Remove(e.Key);
                    bool manual = false;
                    lock (this) {
                        manual = _manualClosingConnections.Contains(connection);
                        if (manual)
                        {
                            _manualClosingConnections.Remove(connection);
                        }
                    }

                    if (!manual)
                    {
                        Util.InterThreadWarning(Env.Strings.GetString("Message.ConnectionManager.Disconnected"));
                    }

                    Env.MainForm.Invoke(new RefreshProfileStatusDelegate(Env.MainForm.RefreshProfileStatus), prof);

                    break;
                }
            }
        }
Exemplo n.º 9
0
        private static SSHConnection ConnectMain(SSHConnectionParameter param, ISSHConnectionEventReceiver receiver, ProtocolNegotiationHandler pnh, AbstractSocket s)
        {
            pnh.Wait();

            if (pnh.State != ReceiverState.Ready)
            {
                throw new Exception(pnh.ErrorMessage);
            }

            string sv = pnh.ServerVersion;

            SSHConnection con = null;

            //if (param.Protocol == SSHProtocol.SSH1)
            con = new SSH1Connection(param, receiver, sv, SSHUtil.ClientVersionString(param.Protocol));
            //else
            //    con = new SSH2Connection(param, receiver, sv, SSHUtil.ClientVersionString(param.Protocol));

            s.SetHandler(con.PacketBuilder());
            SendMyVersion(s, param);

            if (con.DoConnect(s) != GranadosRT.Routrek.SSHC.AuthenticationResult.Failure)
            {
                return(con);
            }
            else
            {
                s.Close();
                return(null);
            }
        }
Exemplo n.º 10
0
 // Выгрузка принятых комманд
 protected void DoReadQueue(SSHSocketReader AReader)
 {
     // Обработаем сообщение из очереди
     while (SSHConnection.Dequeue(out FData))
     {
         AReader.Read(FData.Command, FData.Buffer);
     }
 }
Exemplo n.º 11
0
 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;
 }
Exemplo n.º 12
0
        public List <ProcessInfoState> GetStates()
        {
            List <ProcessInfoState> processEntries = new List <ProcessInfoState>();

            Renci.SshNet.SshClient sshClient = SSHConnection.GetConnection();

            LinuxProcessSubEntry globalAlertDef = new LinuxProcessSubEntry();

            globalAlertDef.CPUPercWarningValue = CPUPercWarningValue;
            globalAlertDef.CPUPercErrorValue   = CPUPercErrorValue;
            globalAlertDef.MemPercWarningValue = MemPercWarningValue;
            globalAlertDef.MemPercErrorValue   = MemPercErrorValue;

            List <ProcessInfo> runningProcesses = ProcessInfo.FromPsAux(sshClient);

            if (ProcessCheckOption == ProcessCheckOption.TopXByCPU)
            {
                foreach (ProcessInfo p in (from p in runningProcesses
                                           orderby p.percCPU descending
                                           select p).Take(TopProcessCount))
                {
                    processEntries.Add(new ProcessInfoState()
                    {
                        ProcessInfo = p, AlertDefinition = globalAlertDef
                    });
                }
            }
            else if (ProcessCheckOption == ProcessCheckOption.TopXByMem)
            {
                foreach (ProcessInfo p in (from p in runningProcesses
                                           orderby p.percMEM descending
                                           select p).Take(TopProcessCount))
                {
                    processEntries.Add(new ProcessInfoState()
                    {
                        ProcessInfo = p, AlertDefinition = globalAlertDef
                    });
                }
            }
            else
            {
                foreach (ProcessInfo p in runningProcesses)
                {
                    LinuxProcessSubEntry se = (from LinuxProcessSubEntry sdef in SubItems
                                               where FileNameMatch(p.ProcessName, sdef.ProcessName)
                                               select sdef).FirstOrDefault();
                    if (se != null)
                    {
                        processEntries.Add(new ProcessInfoState()
                        {
                            ProcessInfo = p, AlertDefinition = se
                        });
                    }
                }
            }
            SSHConnection.CloseConnection();
            return(processEntries);
        }
Exemplo n.º 13
0
        public bool Connect(string host, string username, string password)
        {
            if (IsConnected)
            {
                return(false);
            }

            try
            {
                m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                // send TCP keep-alive packets after 10 seconds of inactivity, then every 5 seconds
                SocketUtil.SetKeepAliveValues(m_socket, true, 10 * 1000, 5 * 1000);

                m_socket.Connect(host, 22);

                SSHConnectionParameter f = new SSHConnectionParameter();

                f.UserName           = username;
                f.Password           = password;
                f.Protocol           = SSHProtocol.SSH2;
                f.AuthenticationType = AuthenticationType.Password;
                f.WindowSize         = 0x1000;

                NullReader r = new NullReader();

                if (m_timer != null)
                {
                    m_timer.Stop();
                    m_timer.Dispose();
                }

                m_conn = (SSH2Connection)SSHConnection.Connect(f, r, m_socket);

                m_timer = new Timer();
                // check connection every 10 milliseconds
                m_timer.Interval = 10;

                m_timer.Tick += new EventHandler(OnTimerTick);
            }
            catch (Exception e)
            {
                if (e.Message == "User authentication failed")
                {
                    MessageBox.Show("This username and/or password were not accepted.  Check them and try again",
                                    "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else
                {
                    MessageBox.Show("SSH connection exception: " + e.Message);
                }

                return(false);
            }

            return(true);
        }
Exemplo n.º 14
0
        public MemInfo GetMemoryInfo()
        {
            MemInfo mi = new MemInfo();

            Renci.SshNet.SshClient sshClient = SSHConnection.GetConnection();
            mi = MemInfo.FromCatProcMeminfo(sshClient);
            SSHConnection.CloseConnection();
            return(mi);
        }
Exemplo n.º 15
0
        //Tutorial: Connecting to a host and opening a shell
        private static void ConnectAndOpenShell()
        {
            SampleKeyboardInteractiveAuthenticationHandler authHandler = null;
            SSHConnectionParameter f = new SSHConnectionParameter("172.22.1.15", 22, SSHProtocol.SSH2, AuthenticationType.PublicKey, "okajima", "aaa");

            //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
            f.KeyboardInteractiveAuthenticationHandlerCreator =
                (connection) => {
                return(authHandler = new SampleKeyboardInteractiveAuthenticationHandler("aaa"));
            };

            Tracer tracer = new Tracer();

            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            s.Connect(new IPEndPoint(IPAddress.Parse(f.HostName), f.PortNumber)); //22 is the default SSH port

            ISSHConnection conn;

            if (f.AuthenticationType == AuthenticationType.KeyboardInteractive)
            {
                //Creating a new SSH connection over the underlying socket
                conn = SSHConnection.Connect(s, f, c => new Reader(c), c => new Tracer());
                bool result = authHandler.GetResult();
                Debug.Assert(result == true);
            }
            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.VerifySSHHostKey = (info) => {
                    byte[] h = info.HostKeyFingerPrint;
                    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(s, f, c => new Reader(c), null);
            }

            //Opening a shell
            var ch = conn.OpenShell(channelOperator => new ChannelHandler(channelOperator));

            //you can get the detailed connection information in this way:
            //SSHConnectionInfo ci = _conn.ConnectionInfo;

            //Go to sample shell
            SampleShell(ch);
        }
Exemplo n.º 16
0
        /// <summary>
        /// Process a single dataset and fetch the info about it.
        /// </summary>
        protected override void ProcessRecord()
        {
            var trimmedDSName = DatasetName.Trim();

            if (_resultsCache.Value[trimmedDSName] is PSGRIDDatasetInfo cHit)
            {
                WriteObject(cHit);
            }
            else
            {
                // Setup for verbosity if we need it.
                var listener = new PSListener(this);
                Trace.Listeners.Add(listener);
                try
                {
                    // Where are we going to be doing query on - we need a machine.
                    var sm = JobParser.GetSubmissionMachine();

                    // Get the remove environment configured if it needs to be
                    if (_connection == null)
                    {
                        _connection = new SSHConnection(sm.MachineName, sm.UserName);
                        _connection
                        .Apply(() => DisplayStatus("Setting up ATLAS"))
                        .setupATLAS()
                        .Apply(() => DisplayStatus("Setting up Rucio"))
                        .setupRucio(_gridCredentials.Username)
                        .Apply(() => DisplayStatus("Acquiring GRID credentials"))
                        .VomsProxyInit("atlas", failNow: () => Stopping);
                    }

                    // Great - get the info on this dataset.
                    var fileInfo = _connection
                                   .Apply(() => DisplayStatus($"Checking for info on {trimmedDSName}."))
                                   .FileInfoFromGRID(trimmedDSName, failNow: () => Stopping);

                    // Next, build the resulting thingy.
                    var r = new PSGRIDDatasetInfo()
                    {
                        DatasetName = trimmedDSName,
                        nFiles      = fileInfo.Count,
                        TotalSizeMB = (int)fileInfo.Sum(fi => fi.size),
                        FileInfo    = fileInfo.ToArray()
                    };
                    _resultsCache.Value[trimmedDSName] = r;
                    using (var pp = listener.PauseListening())
                    {
                        WriteObject(r);
                    }
                }
                finally
                {
                    Trace.Listeners.Remove(listener);
                }
            }
        }
Exemplo n.º 17
0
        public void KnownGenericNodeTest()
        {
            // Use a set of credentials that use something like "username" and "machine001.domain.edu" but have "machine.domain.edu" as the credential.
            // This makes sure that the fallback password finder works properly.
            var info = util.GetUsernameAndPassword(credentialKey: "AtlasSSHTestGenericMachine");

            using (var s = new SSHConnection(info.Item1, info.Item2)) {
                s.ExecuteCommand("ls -a", l => Console.WriteLine(l));
            }
        }
Exemplo n.º 18
0
 protected IConnection GetConnection()
 {
     if (this.sshConnection == null)
     {
         if (this.connectionInfo != null)
         {
             this.sshConnection = SSHHelper.CreateSSHConnectionFromConnectionInfo(connectionInfo);
         }
     }
     return(this.sshConnection);
 }
Exemplo n.º 19
0
 protected IConnection GetConnection()
 {
     ThreadHelper.ThrowIfNotOnUIThread();
     if (this.sshConnection == null)
     {
         if (this.connectionInfo != null)
         {
             this.sshConnection = SSHHelper.CreateSSHConnectionFromConnectionInfo(connectionInfo);
         }
     }
     return(this.sshConnection);
 }
Exemplo n.º 20
0
        /// <summary>
        /// Opens channel.
        /// </summary>
        /// <param name="connection">SSH connection object</param>
        /// <param name="command">Remote command</param>
        /// <param name="millisecondsTimeout">timeout in milliseconds</param>
        /// <exception cref="SCPClientInvalidStatusException">Channel has been already opened or already closed.</exception>
        /// <exception cref="SCPClientTimeoutException">Timeout has occurred while waiting for READY status.</exception>
        public void Open(SSHConnection connection, string command, int millisecondsTimeout)
        {
            if (_status != StreamStatus.NotOpened)
            {
                throw new SCPClientInvalidStatusException();
            }

            SCPClientChannelEventReceiver channelReceiver =
                new SCPClientChannelEventReceiver(
                    new DataReceivedDelegate(OnDataReceived),
                    new ChannelStatusChangedDelegate(OnChannelStatusChanged)
                    );

            SSHChannel channel;

            /* FIXME: SSH1's executing command is not implemented !!
             * if (connection is SSH1Connection) {
             *  channel = ((SSH1Connection)connection).DoExecCommand(channelReceiver, command);
             * }
             * else
             */
            if (connection is SSH2Connection)
            {
                channel = ((SSH2Connection)connection).DoExecCommand(channelReceiver, command);
            }
            else
            {
                // FIXME:
                //throw new ArgumentException("connection must be SSH1Connection or SSH2Connection.");
                throw new ArgumentException("connection must be SSH2Connection.");
            }

            _channelReceiver = channelReceiver;
            _channel         = channel;

            lock (_channelReceiver.StatusChangeNotifier) {
                while (_channelReceiver.ChannelStatus != SCPChannelStatus.READY)
                {
                    bool signaled = Monitor.Wait(_channelReceiver.StatusChangeNotifier, millisecondsTimeout);
                    if (!signaled)
                    {
                        throw new SCPClientTimeoutException();
                    }
                }
            }

            lock (_statusSync) {
                if (_status == StreamStatus.NotOpened)
                {
                    _status = StreamStatus.Opened;
                }
            }
        }
Exemplo n.º 21
0
 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;
 }
        public void CheckConnection()
        {
            if (sshConnection == null)
            {
                sshConnection = new SSHConnection();
            }

            if (!sshConnection.IsConnected())
            {
                sshConnection.Connect();
            }
        }
Exemplo n.º 23
0
        public void ListDirectoryWithNoOutput()
        {
            var info = util.GetUsernameAndPassword();
            var l    = new List <string>();

            using (var s = new SSHConnection(info.Item1, info.Item2))
            {
                s.ExecuteCommand("ls -a | cat", output: ln => l.Add(ln));
            }
            // Make sure we got a few things back.
            Assert.AreNotEqual(0, l.Count);
        }
Exemplo n.º 24
0
 private static void AddSSHConnection(object parameter)
 {
     if (parameter is ContainerPickerViewModel vm && vm.AddSSHConnectionCommand.CanExecute(parameter))
     {
         SSHConnection connection = ConnectionManager.GetSSHConnection(string.Empty) as SSHConnection;
         if (connection != null)
         {
             SSHConnectionViewModel sshConnection = new SSHConnectionViewModel(connection);
             vm.SupportedConnections.Add(sshConnection);
             vm.SelectedConnection = sshConnection;
         }
     }
Exemplo n.º 25
0
        public override MonitorState GetCurrentState()
        {
            MonitorState currentState = new MonitorState()
            {
                ForAgent         = Description,
                State            = CollectorState.NotAvailable,
                CurrentValueUnit = "%"
            };

            try
            {
                MemInfo mi = new MemInfo();
                Renci.SshNet.SshClient sshClient = SSHConnection.GetConnection();
                mi = MemInfo.FromCatProcMeminfo(sshClient);
                SSHConnection.CloseConnection();
                double outputValue = 0;
                if (MemoryType == LinuxMemoryType.MemAvailable)
                {
                    outputValue = mi.AvailablePerc;
                    if (outputValue == 0 && mi.TotalKB > 0)
                    {
                        outputValue = (mi.FreeKB + mi.Buffers + mi.Cached) / mi.TotalKB;
                    }
                }
                else if (MemoryType == LinuxMemoryType.MemFree)
                {
                    outputValue = mi.FreePerc;
                }
                else
                {
                    outputValue = mi.SwapFreePerc;
                }
                currentState.CurrentValue = outputValue.ToString("0.0");
                if (ErrorValue >= outputValue)
                {
                    currentState.State = CollectorState.Error;
                }
                else if (WarningValue >= outputValue)
                {
                    currentState.State = CollectorState.Warning;
                }
                else
                {
                    currentState.State = CollectorState.Good;
                }
            }
            catch (Exception ex)
            {
                currentState.State      = CollectorState.Error;
                currentState.RawDetails = ex.Message;
            }
            return(currentState);
        }
Exemplo n.º 26
0
 public void AttachTransmissionSide(SSHConnection con)
 {
     _sshSocket.SetSSHConnection(con);
     if (con.AuthenticationResult == AuthenticationResult.Success)
     {
         SSHSocket ss = (SSHSocket)_sshSocket; //Keyboard-Interactive‚ª‚ç‚Ý‚Å‚¿‚å‚Á‚Æ•sŽ©‘R‚É‚È‚Á‚Ä‚é‚È
         //ISSHSubsystemParameter subsystem = (ISSHSubsystemParameter)_sshLoginParameter;  //.GetAdapter(typeof(ISSHSubsystemParameter));
         //if(subsystem!=null)
         //    ss.OpenSubsystem(subsystem.SubsystemName);
         //else //‚ӂ‚¤‚̃VƒFƒ‹
         ss.OpenShell();
     }
 }
Exemplo n.º 27
0
        protected override void Negotiate()
        {
            ITerminalParameter term = (ITerminalParameter)_destination.GetAdapter(typeof(ITerminalParameter));
            ITCPParameter      tcp  = (ITCPParameter)_destination.GetAdapter(typeof(ITCPParameter));

            SSHConnectionParameter con = new SSHConnectionParameter();

#if DEBUG
            // con.EventTracer = new SSHDebugTracer();
#endif
            con.Protocol                    = _destination.Method;
            con.CheckMACError               = PEnv.Options.SSHCheckMAC;
            con.UserName                    = _destination.Account;
            con.Password                    = _destination.PasswordOrPassphrase;
            con.AuthenticationType          = _destination.AuthenticationType;
            con.IdentityFile                = _destination.IdentityFileName;
            con.TerminalWidth               = term.InitialWidth;
            con.TerminalHeight              = term.InitialHeight;
            con.TerminalName                = term.TerminalType;
            con.WindowSize                  = PEnv.Options.SSHWindowSize;
            con.PreferableCipherAlgorithms  = LocalSSHUtil.ParseCipherAlgorithm(PEnv.Options.CipherAlgorithmOrder);
            con.PreferableHostKeyAlgorithms = LocalSSHUtil.ParsePublicKeyAlgorithm(PEnv.Options.HostKeyAlgorithmOrder);
            con.AgentForward                = _destination.AgentForward;
            if (ProtocolsPlugin.Instance.ProtocolOptions.LogSSHEvents)
            {
                con.EventTracer = new SSHEventTracer(tcp.Destination);
            }
            if (_keycheck != null)
            {
                con.KeyCheck += new HostKeyCheckCallback(this.CheckKey);
            }


            SSHTerminalConnection r   = new SSHTerminalConnection(_destination);
            SSHConnection         ssh = SSHConnection.Connect(con, r.ConnectionEventReceiver, _socket);
            if (ssh != null)
            {
                if (PEnv.Options.RetainsPassphrase && _destination.AuthenticationType != AuthenticationType.KeyboardInteractive)
                {
                    ProtocolsPlugin.Instance.PassphraseCache.Add(tcp.Destination, _destination.Account, _destination.PasswordOrPassphrase);                     //接続成功時のみセット
                }
                //_destination.PasswordOrPassphrase = ""; 接続の複製のためにここで消さずに残しておく
                r.AttachTransmissionSide(ssh);
                r.UsingSocks = _socks != null;
                _result      = r;
            }
            else
            {
                throw new IOException(PEnv.Strings.GetString("Message.SSHConnector.Cancelled"));
            }
        }
Exemplo n.º 28
0
        //Tutorial: port forwarding
        private static void ConnectSSH2AndPortforwarding()
        {
            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.SSH1;                           //this sample works on both SSH1 and SSH2
            string host_ip = "10.10.9.8";                            //<--!!! [TO USERS OF Granados]

            f.UserName = "******";                                     //<--!!! if you try this sample, edit these values for your environment!
            f.Password = "";                                         //<--!!!
            s.Connect(new IPEndPoint(IPAddress.Parse(host_ip), 22)); //22 is the default SSH port

            f.Protocol = SSHProtocol.SSH2;

            f.AuthenticationType = AuthenticationType.Password;
            //NOTE: if you use public-key authentication, follow this sample instead of the line above:
            //  f.AuthenticationType = AuthenticationType.PublicKey;
            //  f.IdentityFile = "privatekey.bin";
            //  f.Password = "******";

            //former algorithm is given priority in the algorithm negotiation
            f.PreferableHostKeyAlgorithms = new PublicKeyAlgorithm[] { 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

            //Creating a new SSH connection over the underlying socket
            _conn        = SSHConnection.Connect(f, reader, s);
            reader._conn = _conn;

            //Local->Remote port forwarding
            SSHChannel ch = _conn.ForwardPort(reader, "www.google.co.jp", 80, "localhost", 0);

            reader._pf = ch;
            while (!reader._ready)
            {
                System.Threading.Thread.Sleep(100);                                 //wait response
            }
            reader._pf.Transmit(Encoding.ASCII.GetBytes("GET / HTTP/1.0\r\n\r\n")); //get the toppage

            //Remote->Local
            // if you want to listen to a port on the SSH server, follow this line:
            //_conn.ListenForwardedPort("0.0.0.0", 10000);

            //NOTE: if you use SSH2, dynamic key exchange feature is supported.
            //((SSH2Connection)_conn).ReexchangeKeys();
        }
Exemplo n.º 29
0
        /*
         * private static Socks CreateSocksParam(string dest_host, int dest_port) {
         *  Socks s = new Socks();
         *  s.DestName = dest_host;
         *  s.DestPort = (short)dest_port;
         *  s.Account = Env.Options.SocksAccount;
         *  s.Password = Env.Options.SocksPassword;
         *  s.ServerName = Env.Options.SocksServer;
         *  s.ServerPort = (short)Env.Options.SocksPort;
         *  s.ExcludingNetworks = Env.Options.SocksNANetworks;
         *  return s;
         * }
         */
        public void ManualClose(ChannelProfile prof)
        {
            if (!IsConnected(prof))
            {
                Debug.WriteLine("ManualClose - Not connected");
                return;
            }

            lock (this) {
                SSHConnection c = (SSHConnection)_profileToConnection[prof];
                _manualClosingConnections.Add(c);
                c.Disconnect("");
            }
        }
Exemplo n.º 30
0
        /// <summary>
        /// Make a long connection to a remote host. This is to help with debugging
        /// broken connections.
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            if (args.Length != 2)
            {
                throw new InvalidOperationException("Usage <prog> host username");
            }
            var c = new SSHConnection(args[0], args[1]);

            Console.WriteLine("Sending a ls command");
            c.ExecuteLinuxCommand("ls -l", s => Console.WriteLine(s));
            Console.WriteLine("Sleeping for 5 minutes");
            c.ExecuteLinuxCommand($"sleep {60 * 5}", s => Console.WriteLine(s));
            Console.WriteLine("Done!");
        }
Exemplo n.º 31
0
 public SSH2Channel(SSHConnection con, ChannelType type, int local_id)
 {
     con.RegisterChannel(local_id, this);
     _connection = con;
     _type = type;
     _localID = local_id;
     _windowSize = _leftWindowSize = con.Param().WindowSize;
     _negotiationStatus = type==ChannelType.Shell? 3 : type==ChannelType.ForwardedLocalToRemote? 1 : type==ChannelType.Session? 1 : 0;
 }
Exemplo n.º 32
0
 public SynchronizedPacketReceiver(SSHConnection c)
     : base(c.UnderlyingStream) {
     _connection = c;
 }
Exemplo n.º 33
0
 public SSH2Channel(SSHConnection con, ChannelType type, int local_id, int remote_id, int maxpacketsize)
 {
     con.RegisterChannel(local_id, this);
     _connection = con;
     _type = type;
     _localID = local_id;
     _remoteID = remote_id;
     _windowSize = _leftWindowSize = con.Param().WindowSize;
     Debug.Assert(type==ChannelType.ForwardedRemoteToLocal);
     _remoteID = remote_id;
     _serverMaxPacketSize = maxpacketsize;
     _negotiationStatus = 0;
 }
Exemplo n.º 34
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="connection">connection object</param>
 public SynchronizedPacketReceiver(SSHConnection connection)
     : this(connection.UnderlyingStream)
 {
 }
Exemplo n.º 35
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="connection">SSH connection. Currently only SSH2 connection is accepted.</param>
 public SCPClient(SSHConnection connection) {
     this._connection = connection;
 }
Exemplo n.º 36
0
        //Tutorial: Connecting to a host and opening a shell
        private static void ConnectAndOpenShell()
        {
            SSHConnectionParameter f = new SSHConnectionParameter("172.22.1.15", 22, SSHProtocol.SSH2, AuthenticationType.PublicKey, "okajima", "aaa");
            f.EventTracer = new Tracer(); //to receive detailed events, set ISSHEventTracer
            //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

            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            s.Connect(new IPEndPoint(IPAddress.Parse(f.HostName), f.PortNumber)); //22 is the default SSH port

            if (f.AuthenticationType == 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[] { f.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.VerifySSHHostKey = (info) => {
                    byte[] h = info.HostKeyFingerPrint;
                    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);
        }
Exemplo n.º 37
0
        private static void AgentForward()
        {
            SSHConnectionParameter f = new SSHConnectionParameter("172.22.1.15", 22, SSHProtocol.SSH2, AuthenticationType.Password, "root", "");
            f.EventTracer = new Tracer(); //to receive detailed events, set ISSHEventTracer
            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            s.Connect(new IPEndPoint(IPAddress.Parse(f.HostName), f.PortNumber)); //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
            f.AgentForward = new AgentForwardClient();
            Reader reader = new Reader(); //simple event receiver

            //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;

            while (!reader._ready)
                Thread.Sleep(100);

            Thread.Sleep(1000);
            ch.Transmit(Encoding.Default.GetBytes("ssh -A -l okajima localhost\r"));

            //Go to sample shell
            SampleShell(reader);
        }
Exemplo n.º 38
0
        private static void AgentForward()
        {
            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
            f.AgentForward = new AgentForwardClient();
            Reader reader = new Reader(); //simple event receiver

            AuthenticationType at = AuthenticationType.Password;
            f.AuthenticationType = at;
            f.Password = password;

            //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;

            while (!reader._ready)
                Thread.Sleep(100);

            Thread.Sleep(1000);
            ch.Transmit(Encoding.Default.GetBytes("ssh -A -l okajima localhost\r"));

            //Go to sample shell
            SampleShell(reader);
        }
Exemplo n.º 39
0
 private DummySSHChannel(SSHConnection conn)
     : base(conn, ChannelType. ExecCommand, 0)
 {
 }
Exemplo n.º 40
0
        //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);
        }
Exemplo n.º 41
0
        //Tutorial: port forwarding
        private static void ConnectSSH2AndPortforwarding()
        {
            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.SSH1; //this sample works on both SSH1 and SSH2
            string host_ip = "10.10.9.8"; //<--!!! [TO USERS OF Granados]
            f.UserName = "******";          //<--!!! if you try this sample, edit these values for your environment!
            f.Password = "";              //<--!!!
            s.Connect(new IPEndPoint(IPAddress.Parse(host_ip), 22)); //22 is the default SSH port

            f.Protocol = SSHProtocol.SSH2;

            f.AuthenticationType = AuthenticationType.Password;
            //NOTE: if you use public-key authentication, follow this sample instead of the line above:
            //  f.AuthenticationType = AuthenticationType.PublicKey;
            //  f.IdentityFile = "privatekey.bin";
            //  f.Password = "******";

            //former algorithm is given priority in the algorithm negotiation
            f.PreferableHostKeyAlgorithms = new PublicKeyAlgorithm[] { 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

            //Creating a new SSH connection over the underlying socket
            _conn = SSHConnection.Connect(f, reader, s);
            reader._conn = _conn;

            //Local->Remote port forwarding
            SSHChannel ch = _conn.ForwardPort(reader, "www.google.co.jp", 80, "localhost", 0);
            reader._pf = ch;
            while (!reader._ready)
                System.Threading.Thread.Sleep(100); //wait response
            reader._pf.Transmit(Encoding.ASCII.GetBytes("GET / HTTP/1.0\r\n\r\n")); //get the toppage

            //Remote->Local
            // if you want to listen to a port on the SSH server, follow this line:
            //_conn.ListenForwardedPort("0.0.0.0", 10000);

            //NOTE: if you use SSH2, dynamic key exchange feature is supported.
            //((SSH2Connection)_conn).ReexchangeKeys();
        }
Exemplo n.º 42
0
        /// <summary>
        /// Opens channel.
        /// </summary>
        /// <param name="connection">SSH connection object</param>
        /// <param name="command">Remote command</param>
        /// <param name="millisecondsTimeout">timeout in milliseconds</param>
        /// <exception cref="SCPClientInvalidStatusException">Channel has been already opened or already closed.</exception>
        /// <exception cref="SCPClientTimeoutException">Timeout has occurred while waiting for READY status.</exception>
        public void Open(SSHConnection connection, string command, int millisecondsTimeout)
        {
            if (_status != StreamStatus.NotOpened)
                throw new SCPClientInvalidStatusException();

            SCPClientChannelEventReceiver channelReceiver =
                new SCPClientChannelEventReceiver(
                    new DataReceivedDelegate(OnDataReceived),
                    new ChannelStatusChangedDelegate(OnChannelStatusChanged)
                );

            SSHChannel channel;
            /* FIXME: SSH1's executing command is not implemented !!
            if (connection is SSH1Connection) {
                channel = ((SSH1Connection)connection).DoExecCommand(channelReceiver, command);
            }
            else
            */
            if (connection is SSH2Connection) {
                channel = ((SSH2Connection)connection).DoExecCommand(channelReceiver, command);
            }
            else {
                // FIXME:
                //throw new ArgumentException("connection must be SSH1Connection or SSH2Connection.");
                throw new ArgumentException("connection must be SSH2Connection.");
            }

            _channelReceiver = channelReceiver;
            _channel = channel;

            lock (_channelReceiver.StatusChangeNotifier) {
                while (_channelReceiver.ChannelStatus != SCPChannelStatus.READY) {
                    bool signaled = Monitor.Wait(_channelReceiver.StatusChangeNotifier, millisecondsTimeout);
                    if (!signaled) {
                        throw new SCPClientTimeoutException();
                    }
                }
            }

            lock(_statusSync) {
                if (_status == StreamStatus.NotOpened) {
                    _status = StreamStatus.Opened;
                }
            }
        }
Exemplo n.º 43
0
 public SSH1Channel(SSHConnection con, ChannelType type, int local_id, int remote_id)
 {
     con.RegisterChannel(local_id, this);
     _connection = con;
     _type = type;
     _localID = local_id;
     _remoteID = remote_id;
 }