Code Monkey home page Code Monkey logo

fxssh's Introduction

FxSsh

FxSsh is a lightweight SSH server side application as SSH reinforcement of GitCandy.


Nuget

NuGet version

PM> Install-Package FxSsh

Sample code

static int windowWidth, windowHeight;

static void Main(string[] args)
{
    var server = new SshServer();
    server.AddHostKey("ssh-rsa", "BwIAAACkAABSU0EyAAQAAAEAAQADKjiW5UyIad8ITutLjcdtejF4wPA1dk1JFHesDMEhU9pGUUs+HPTmSn67ar3UvVj/1t/+YK01FzMtgq4GHKzQHHl2+N+onWK4qbIAMgC6vIcs8u3d38f3NFUfX+lMnngeyxzbYITtDeVVXcLnFd7NgaOcouQyGzYrHBPbyEivswsnqcnF4JpUTln29E1mqt0a49GL8kZtDfNrdRSt/opeexhCuzSjLPuwzTPc6fKgMc6q4MBDBk53vrFY2LtGALrpg3tuydh3RbMLcrVyTNT+7st37goubQ2xWGgkLvo+TZqu3yutxr1oLSaPMSmf9bTACMi5QDicB3CaWNe9eU73MzhXaFLpNpBpLfIuhUaZ3COlMazs7H9LCJMXEL95V6ydnATf7tyO0O+jQp7hgYJdRLR3kNAKT0HU8enE9ZbQEXG88hSCbpf1PvFUytb1QBcotDy6bQ6vTtEAZV+XwnUGwFRexERWuu9XD6eVkYjA4Y3PGtSXbsvhwgH0mTlBOuH4soy8MV4dxGkxM8fIMM0NISTYrPvCeyozSq+NDkekXztFau7zdVEYmhCqIjeMNmRGuiEo8ppJYj4CvR1hc8xScUIw7N4OnLISeAdptm97ADxZqWWFZHno7j7rbNsq5ysdx08OtplghFPx4vNHlS09LwdStumtUel5oIEVMYv+yWBYSPPZBcVY5YFyZFJzd0AOkVtUbEbLuzRs5AtKZG01Ip/8+pZQvJvdbBMLT1BUvHTrccuRbY03SHIaUM3cTUc=");
    server.AddHostKey("ssh-dss", "BwIAAAAiAABEU1MyAAQAAG+6KQWB+crih2Ivb6CZsMe/7NHLimiTl0ap97KyBoBOs1amqXB8IRwI2h9A10R/v0BHmdyjwe0c0lPsegqDuBUfD2VmsDgrZ/i78t7EJ6Sb6m2lVQfTT0w7FYgVk3J1Deygh7UcbIbDoQ+refeRNM7CjSKtdR+/zIwO3Qub2qH+p6iol2iAlh0LP+cw+XlH0LW5YKPqOXOLgMIiO+48HZjvV67pn5LDubxru3ZQLvjOcDY0pqi5g7AJ3wkLq5dezzDOOun72E42uUHTXOzo+Ct6OZXFP53ZzOfjNw0SiL66353c9igBiRMTGn2gZ+au0jMeIaSsQNjQmWD+Lnri39n0gSCXurDaPkec+uaufGSG9tWgGnBdJhUDqwab8P/Ipvo5lS5p6PlzAQAAACqx1Nid0Ea0YAuYPhg+YolsJ/ce");
    server.ConnectionAccepted += server_ConnectionAccepted;

    server.Start();

    Task.Delay(-1).Wait();
}

static void server_ConnectionAccepted(object sender, Session e)
{
    Console.WriteLine("Accepted a client.");

    e.ServiceRegistered += e_ServiceRegistered;
    e.KeysExchanged += e_KeysExchanged;
}

private static void e_KeysExchanged(object sender, KeyExchangeArgs e)
{
    foreach (var keyExchangeAlg in e.KeyExchangeAlgorithms)
    {
        Console.WriteLine("Key exchange algorithm: {0}", keyExchangeAlg);
    }
}

static void e_ServiceRegistered(object sender, SshService e)
{
    var session = (Session)sender;
    Console.WriteLine("Session {0} requesting {1}.",
        BitConverter.ToString(session.SessionId).Replace("-", ""), e.GetType().Name);

    if (e is UserauthService)
    {
        var service = (UserauthService)e;
        service.Userauth += service_Userauth;
    }
    else if (e is ConnectionService)
    {
        var service = (ConnectionService)e;
        service.CommandOpened += service_CommandOpened;
        service.EnvReceived += service_EnvReceived;
        service.PtyReceived += service_PtyReceived;
        service.TcpForwardRequest += service_TcpForwardRequest;
        service.WindowChange += Service_WindowChange;
    }
}

static void Service_WindowChange(object sender, WindowChangeArgs e)
{
    // DEMO MiniTerm not support change window size
}

static void service_TcpForwardRequest(object sender, TcpRequestArgs e)
{
    Console.WriteLine("Received a request to forward data to {0}:{1}", e.Host, e.Port);

    var allow = true;  // func(e.Host, e.Port, e.AttachedUserauthArgs);

    if (!allow)
        return;

    var tcp = new TcpForwardService(e.Host, e.Port, e.OriginatorIP, e.OriginatorPort);
    e.Channel.DataReceived += (ss, ee) => tcp.OnData(ee);
    e.Channel.CloseReceived += (ss, ee) => tcp.OnClose();
    tcp.DataReceived += (ss, ee) => e.Channel.SendData(ee);
    tcp.CloseReceived += (ss, ee) => e.Channel.SendClose();
    tcp.Start();
}

static void service_PtyReceived(object sender, PtyArgs e)
{
    Console.WriteLine("Request to create a PTY received for terminal type {0}", e.Terminal);
    windowWidth = (int)e.WidthChars;
    windowHeight = (int)e.HeightRows;
}

static void service_EnvReceived(object sender, EnvironmentArgs e)
{
    Console.WriteLine("Received environment variable {0}:{1}", e.Name, e.Value);
}

static void service_Userauth(object sender, UserauthArgs e)
{
    Console.WriteLine("Client {0} fingerprint: {1}.", e.KeyAlgorithm, e.Fingerprint);

    e.Result = true;
}

static void service_CommandOpened(object sender, CommandRequestedArgs e)
{
    Console.WriteLine($"Channel {e.Channel.ServerChannelId} runs {e.ShellType}: \"{e.CommandText}\".");

    var allow = true;  // func(e.ShellType, e.CommandText, e.AttachedUserauthArgs);

    if (!allow)
        return;

    if (e.ShellType == "shell")
    {
        // requirements: Windows 10 RedStone 5, 1809
        // also, you can call powershell.exe
        var terminal = new Terminal("cmd.exe", windowWidth, windowHeight);

        e.Channel.DataReceived += (ss, ee) => terminal.OnInput(ee);
        e.Channel.CloseReceived += (ss, ee) => terminal.OnClose();
        terminal.DataReceived += (ss, ee) => e.Channel.SendData(ee);
        terminal.CloseReceived += (ss, ee) => e.Channel.SendClose(ee);

        terminal.Run();
    }
    else if (e.ShellType == "exec")
    {
        var parser = new Regex(@"(?<cmd>git-receive-pack|git-upload-pack|git-upload-archive) \'/?(?<proj>.+)\.git\'");
        var match = parser.Match(e.CommandText);
        var command = match.Groups["cmd"].Value;
        var project = match.Groups["proj"].Value;

        var git = new GitService(command, project);

        e.Channel.DataReceived += (ss, ee) => git.OnData(ee);
        e.Channel.CloseReceived += (ss, ee) => git.OnClose();
        git.DataReceived += (ss, ee) => e.Channel.SendData(ee);
        git.CloseReceived += (ss, ee) => e.Channel.SendClose(ee);

        git.Start();
    }
    else if (e.ShellType == "subsystem")
    {
        // do something more
    }
}

License

The MIT license

fxssh's People

Contributors

aimeast avatar cocowalla avatar dcnick3 avatar robeving avatar thatwileyguy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

fxssh's Issues

Session gets closed very quickly

Hi,

I tried to implement a SFTP Subsystem beneath FxSsh. It works as expected but I noticed that the timeout for read seems to be 30 seconds. I couldn't find anything about timeouts in the RFC and all the SFTP Clients I tried (FileZilla, WinScp and even putty) are reporting that the server unexpectedly closed the connection when it's idle for 30 seconds.

"Socket operation has timed out after 30000 milliseconds."

It would be great if this timeout can be made configurable or even be disabled.

Or maybe I'm just missing something?

Channel always forces close when sending SSH_MSG_CHANNEL_CLOSE

As per ssh documentation

The close message can be non-violently to return exit-statuses and acknowledgement of commands.

" When the command running at the other end terminates, the following
message can be sent to return the exit status of the command.
Returning the status is RECOMMENDED. No acknowledgement is sent for
this message. The channel needs to be closed with
SSH_MSG_CHANNEL_CLOSE after this message.

The client MAY ignore these messages.

  byte      SSH_MSG_CHANNEL_REQUEST
  uint32    recipient channel
  string    "exit-status"
  boolean   FALSE
  uint32    exit_status

The remote command may also terminate violently due to a signal.
Such a condition can be indicated by the following message. A zero
'exit_status' usually means that the command terminated successfully.
"

Suggested fix is to allow for optional parameter in SendClose(uint? exitCode = null) in Channel.cs that dictates whether to "CheckBothClosed()" which will default to true to prevent any breaking change for other projects.

        public void SendClose(uint? exitCode = null, bool forceClose = true)
        {
            if (ServerClosed)
                return;

            ServerClosed = true;
            if (exitCode.HasValue)
                _connectionService._session.SendMessage(new ExitStatusMessage { RecipientChannel = ClientChannelId, ExitStatus = exitCode.Value });
            _connectionService._session.SendMessage(new ChannelCloseMessage { RecipientChannel = ClientChannelId });

            if (forceClose)
            {
                CheckBothClosed();
            }
        }

I will submit a PR with the suggested fix.

Putty support error

First, the server can not use the .ppk public key generated by puttygen.
Second, I use the key in the example and use putty connect to it, but I met this error:
Unknown request type: pty-req.

It seems the method 'HandleMessage' in file ConnectionService.cs not process pty-req:
private void HandleMessage(ChannelRequestMessage message) { switch (message.RequestType) { case "exec": var msg = Message.LoadFrom<CommandRequestMessage>(message); HandleMessage(msg); break; default: if (message.WantReply) _session.SendMessage(new ChannelFailureMessage { RecipientChannel = FindChannelByServerId<Channel>(message.RecipientChannel).ClientChannelId }); throw new SshConnectionException(string.Format("Unknown request type: {0}.", message.RequestType)); } }

Connection closes

Hello, I'm using a connection with OpenSSH Pty console type.
Running version 1.1.1 from NuGet
I don't know if this is related to a idle timeout, as the disconnect seems to happen when there is no activity, not so sure. May be this diagnostics (-vvv) makes more sense to someone else than me.

debug3: send packet: type 1
debug1: channel 0: free: client-session, nchannels 1
debug3: channel 0: status: The following connections are open:
  #0 client-session (t4 r0 i0/0 o0/0 fd 4/5 cc -1)

Connection to localhost closed by remote host.
Connection to localhost closed.
Transferred: sent 8584, received 56784 bytes, in 114.3 seconds
Bytes per second: sent 75.1, received 496.6
debug1: Exit status -1

also Session.Disconnected event is fired on the server.

Elliptic Curve cryptography

Hello,

Nice lib, but it really needs upgrade in compatibility (ECC)!!
And when you guys do implement it, please use bouncy castle lib not a CNG from net core as CNG is not available on linux only on windows platform. i don't mind little dependency as long as it works on every platform :)

What the host key xml format?

I try use RSACryptoServiceProvider ToXmlString, its no work.
I try use PuTTY Key Generator and copy private key, its no work too.
How can i generate my own host key?

Feature under subsystem

Hi, do you plan to add any feature under subsystem? at least an echo service? to act as a honeypot or similar functionality?

Cheers, loved it so far

Requirements for PR

Hi,

I'd like to make some contributions to FxSsh, do you have any requirements for PRs?

Kind Regards,
Chris

Automated tests

Would be great to add some automated tests to the project, for example, spinning up an SSH server and then using SSH.NET as a client to interact with it.

Reverse tunneling

Hello,
can I use this project to implement a reverse tunneling to my client?
Reading this instructions: https://www.howtoforge.com/reverse-ssh-tunneling , I can connect to the FxSsh server using from my "remote client":

ssh -R 10000:localhost:22 michele@publicIP

But when I connect from to my PublicIP at port 10000 there is no channel opened.

I saw from the sources the service_TcpForwardRequest function, but I cannot figure out how to make it execute from a ssh client...

Can you pls help?

Thanks,
Michele

Unable to negotiate

Unable to negotiate with 127.0.0.1 port 9999: no matching key exchange method found. Their offer: diffie-hellman-group14-sha1,diffie-hellman-group1-sha1

Publish version 1.1.2 to NuGet

Any interest in publishing a new version to pick up the dev branch changes submitted after 1.1.1 was released to nuget? There are some good changes that are of interest to us in the handful of changes made after Jan 19, 2019.

Sending data that is greater then 1Mb causes permanent wait

Sending data greater then 1024 event cumulatively will cause a unlimited wait.

 public void SendData(byte[] data)
        {
            Contract.Requires(data != null);

            if (data.Length == 0)
            {
                return;
            }

            var msg = new ChannelDataMessage();
            msg.RecipientChannel = ClientChannelId;

            var total = (uint)data.Length;
            var offset = 0L;
            byte[] buf = null;
            do
            {
                var packetSize = Math.Min(Math.Min(ClientWindowSize, ClientMaxPacketSize), total);
// This waits forever?                
if (packetSize == 0)
                {
                    _sendingWindowWaitHandle.WaitOne();
                    continue;
                }

                if (buf == null || packetSize != buf.Length)
                    buf = new byte[packetSize];
                Array.Copy(data, offset, buf, 0, packetSize);

                msg.Data = buf;
                _connectionService._session.SendMessage(msg);

                ClientWindowSize -= packetSize;
                total -= packetSize;
                offset += packetSize;
            } while (total > 0);
        }

When terminal windows resize, outputs are weird

My SSH client is PuTTY.
When window width added, the output content still wrap line by old width.
When window height added, after output the cursor is no followed to bottom of window, scroll are broken.

Critical security issue

Result of signature verification in public key auth is ignored. Because of that server will accept any signature effectively removing need of private key for auth. This allows user to auth using ONLY trusted public key.

Not working dot net core linux

in Session.SetSocketOptions
in _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true); The following exception is thrown:
System.Net.Sockets.SocketException (95): Operation not supported

I got it working by commenting out this line.

dotnet --version gives: 2.1.401

Seems to be a know dotnet issue
https://github.com/dotnet/corefx/issues/28305

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.