Quantcast
Channel: SSH.NET Library
Viewing all 2955 articles
Browse latest View live

New Post: Configure for plain FTP

$
0
0
Hi,

Is it possible to configure the SFTP client for plain FTP? My code needs to support both options, so instead of writing two different implementations, it would be very interesting to "turn a switch on or off" :-)

Patch Uploaded: #14626

$
0
0

boric has uploaded a patch.

Description:
Fixes bug where Session.Connect() throws an exception when it doesn't receive the SSH version number in the server reply. Instead, it recognizes the end of the reply and continues without it.

New Post: SSH Tunnel / Port Forwarding

$
0
0
where you able to get it to connect, because i'm having the same problem using C#, trying to connect to mysql database after connecting to the server but no success

by the way i have the same connection setup in the MYSQL workbench and its working fine

for the below code the server is using the host "data" not "localhost", don't know why, but that's how they set it up.

the error i get is "Unable to connect to any of the specified MySQL hosts."
 Console.WriteLine("Ssh connection sucessful");
                            uint sqlPort = 3307;
                            var portFwd = new ForwardedPortLocal("127.0.0.1", sqlPort, "data", sqlPort);
                            client.AddForwardedPort(portFwd);
                            portFwd.Start();
                            if (portFwd.IsStarted)
                            {
                                Console.WriteLine("Port Forwarding has started.");
                            }
                            else
                            {
                                Console.WriteLine("Port Forwarding has failed.");
                            }

                            string connStr = "server=data;database=db_name;uid=my_sql_username;pwd=my_sql_server_password;"; 
                                                        
                            MySqlConnection mysqlConn = new MySqlConnection(connStr); 

                            try
                            {
                                Console.WriteLine("Connecting to MySQL...");
                                mysqlConn.Open();
                                Console.WriteLine("MySql database connection activated");
                                string query = "select * from table_t1";  
                                MySqlCommand cmd = new MySqlCommand(query, mysqlConn);
                                cmd.ExecuteNonQuery();
                                MySqlDataAdapter da = new MySqlDataAdapter(cmd);
                                DataTable data = new DataTable();

                                da.Fill(data);

                                dataGridView1.DataSource = data;

                                Console.WriteLine("Query Successful");

                            }
                            catch (SocketException ex)
                            {
                                Console.WriteLine(ex.ToString());
                            }
                            finally
                            {
                                mysqlConn.Close();
                            }

                        }
                        else
                        {
                            Console.WriteLine("Ssh connection failed");
                        }
any help would be great

thanks alot

New Post: Code to download SFTP files.

New Post: Port-Forwardings crashes when unable to ship data

$
0
0
Hi,

I discovered a huge problem in the current implementation of the SSH.Net PortForwarding.

To show the problem I created following test-program:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Renci.SshNet;

namespace SshTestConsole
{
    class Program
    {
        static void Main(string[] args)
        {

            SshClient _sshclient = new SshClient($host, $user, $password);
            _sshclient.ErrorOccurred += _sshclient_ErrorOccurred;
            _sshclient.HostKeyReceived += _sshclient_HostKeyReceived;

            ForwardedPortLocal forwarding = new ForwardedPortLocal("127.0.0.1", 22223, "127.0.0.1", 80);
            forwarding.Exception += forwarding_Exception;
            forwarding.RequestReceived += forwarding_RequestReceived;
            _sshclient.Connect();
            _sshclient.AddForwardedPort(forwarding);
            forwarding.Start();
            Console.WriteLine("Enter to exit...");
            Console.ReadLine();
        }

        static void forwarding_RequestReceived(object sender, Renci.SshNet.Common.PortForwardEventArgs e)
        {
            Console.WriteLine("forwarding_RequestReceived: '{0}:{1}'", e.OriginatorHost, e.OriginatorPort); 
        }

        static void forwarding_Exception(object sender, Renci.SshNet.Common.ExceptionEventArgs e)
        {
            Console.WriteLine("forwarding_Exception: {0}\n{1}", e.Exception.Message, e.Exception.StackTrace);
        }

        static void _sshclient_HostKeyReceived(object sender, Renci.SshNet.Common.HostKeyEventArgs e)
        {
            Console.WriteLine("_sshclient_HostKeyReceived: {0}, {1}, {2}, {3}, {4}", e.CanTrust, e.FingerPrint, e.HostKey, e.HostKeyName, e.KeyLength); 
        }

        static void _sshclient_ErrorOccurred(object sender, Renci.SshNet.Common.ExceptionEventArgs e)
        {
            Console.WriteLine("_sshclient_ErrorOccurred: {0}\n{1}", e.Exception.Message, e.Exception.StackTrace);
        }
    }
}
The forwarding works. But when you do some quick reloads (Shift+F5) of the webpage the
forwarding crashes and stops working.
_sshclient_HostKeyReceived: True, System.Byte[], System.Byte[], ssh-rsa, 2048
Enter to exit...
forwarding_RequestReceived: '127.0.0.1:64230'
forwarding_RequestReceived: '127.0.0.1:64231'
_sshclient_ErrorOccurred: Eine bestehende Verbindung wurde softwaregesteuert
durch den Hostcomputer abgebrochen
bei System.Net.Sockets.Socket.Send(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
bei Renci.SshNet.Channels.ChannelDirectTcpip.InternalSocketSend(Byte[] data) in c:\Users\srinkes\Documents\Visual Studio 2012\Projects\Project\Renci.SshNet\Channels\ChannelDirectTcpip.NET40.cs:Zeile
bei Renci.SshNet.Channels.ChannelDirectTcpip.OnData(Byte[] data) in c:\Users\srinkes\Documents\Visual Studio 2012\Projects\Project\Renci.SshNet\Channels\ChannelDirectTcpip.cs:Zeile 157.
bei Renci.SshNet.Channels.Channel.OnChannelData(Object sender, MessageEventArgs1 e) in c:\Users\srinkes\Documents\Visual Studio 2012\Projects\Project\Renci.SshNet\Channels\Channel.cs:Zeile 590.
bei System.EventHandler
1.Invoke(Object sender, TEventArgs e)
bei Renci.SshNet.Session.OnChannelDataReceived(ChannelDataMessage message) in c:\Users\srinkes\Documents\Visual Studio 2012\Projects\Project\Renci.SshNet\Session.cs:Zeile 1392.
bei Renci.SshNet.Session.HandleMessage(ChannelDataMessage message) in c:\Users\srinkes\Documents\Visual Studio 2012\Projects\Project\Renci.SshNet\Session.cs:Zeile 1034.
bei CallSite.Target(Closure , CallSite , Session , Object )
bei Renci.SshNet.Session.HandleMessageCore(Message message) in c:\Users\srinkes\Documents\Visual Studio 2012\Projects\Project\Renci.SshNet\Session.NET40.cs:Zeile 20.
bei Renci.SshNet.Session.MessageListener() in c:\Users\srinkes\Documents\Visual Studio 2012\Projects\Project\Renci.SshNet\Session.cs:Zeile 1589.
forwarding_RequestReceived: '127.0.0.1:64232'
forwarding_Exception: Eine bestehende Verbindung wurde softwaregesteuert
durch den Hostcomputer abgebrochen
bei Renci.SshNet.Session.WaitHandle(WaitHandle waitHandle) in c:\Users\srinkes\Documents\Visual Studio 2012\Projects\Project\Renci.SshNet\Session.cs:Zeile 642.
forwarding_Exception: Eine bestehende Verbindung wurde softwaregesteuert
durch den Hostcomputer abgebrochen
bei Renci.SshNet.Session.WaitHandle(WaitHandle waitHandle) in c:\Users\srinkes\Documents\Visual Studio 2012\Projects\Project\Renci.SshNet\Session.cs:Zeile 642.
forwarding_Exception: Eine bestehende Verbindung wurde softwaregesteuert
durch den Hostcomputer abgebrochen
bei Renci.SshNet.Session.WaitHandle(WaitHandle waitHandle) in c:\Users\srinkes\Documents\Visual Studio 2012\Projects\Project\Renci.SshNet\Session.cs:Zeile 642.
bei Renci.SshNet.Channels.Channel.Close(Boolean wait) in c:\Users\srinkes\Documents\Visual Studio 2012\Projects\Project\Renci.SshNet\Channels\Channel.cs:Zeile 518.
bei Renci.SshNet.Channels.Channel.Close() in c:\Users\srinkes\Documents\Visual Studio 2012\Projects\Project\Renci.SshNet\Channels\Channel.cs:Zeile 223.
bei Renci.SshNet.Channels.ChannelDirectTcpip.Close() in c:\Users\srinkes\Documents\Visual Studio 2012\Projects\Project\Renci.SshNet\Channels\ChannelDirectTcpip.cs:Zeile 146.
bei Renci.SshNet.ForwardedPortLocal.<>c__DisplayClass3.<InternalStart>b__2() in c:\Users\srinkes\Documents\Visual Studio 2012\Projects\Project\Renci.SshNet\ForwardedPortLocal.NET.cs:Zeile 62.
IMHO it's OK to throw an Exception (for logging purpose), but it's not OK that the whole
forwarding stops working. Also the IsStarted property is still true :(
I will take some time to investigate for a fix, but hints/ideas are very welcome.

Greetz

New Post: Port-Forwardings crashes when unable to ship data

$
0
0
I followed the stacktrace to Renci.SshNet.Channels.ChannelDirectTcpip.InternalSocketSend

And change it from:
        partial void InternalSocketSend(byte[] data)
        {
                this._socket.Send(data, 0, data.Length, SocketFlags.None);
        }
to
        partial void InternalSocketSend(byte[] data)
        {
            try
            {
                this._socket.Send(data, 0, data.Length, SocketFlags.None);
            }
            catch (Exception exp)
            {
                Console.WriteLine("InternalSocketSend Exception: " + exp.Message + "\n" + exp.StackTrace);
            }
        }
Now the forwardings do not crash anymore in my use case.

Reopened Issue: Orphaned threads when port forwarding [1522]

$
0
0
I'm not sure if this is the same issue as [here](http://sshnet.codeplex.com/workitem/1436).

In the situation where a port forward has been established and actively used, therefore a listener thread has been created, if the network is disconnected (by pulling out the cable) and reconnected sometime later then the internal thread will remain there even after everything else has been disposed properly. This causes problems, especially when trying to exit the application since it will hang.

With a fair amount of Console.WriteLineing it was established that the internal listener thread, consisting mostly of the Bind function in ChannelDirectTcpip, eventually exits its main loop correctly but then stalls at this point forever (well at least until a kill -9 is issued):

```
System.Threading.WaitHandle.WaitAny(new WaitHandle[] { this._channelEof });
```

I do not know much about the inner workings of SSH.NET and therefore do not know the best solution to the problem, but a workaround that seems to do the job for us is to simply allow that wait to timeout:

```
System.Threading.WaitHandle.WaitAny(new WaitHandle[] { this._channelEof }, 5000);
```

After that, the inner thread exits properly and no more hangs on exit.

Reopened Issue: Process terminated due to unhandled exception in Finalize / Destructor [1514]

$
0
0
__My application encountered the following unhandled exception that caused the process to exit:__

Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: Renci.SshNet.Common.SshConnectionException
Stack:
at Renci.SshNet.Session.SendMessage(Renci.SshNet.Messages.Message)
at Renci.SshNet.Channels.Channel.SendMessage(Renci.SshNet.Messages.Connection.ChannelCloseMessage)
at Renci.SshNet.Channels.Channel.Close(Boolean)
at Renci.SshNet.Channels.ChannelSession.Close(Boolean)
at Renci.SshNet.Channels.Channel.Dispose(Boolean)
at Renci.SshNet.Channels.ChannelSession.Dispose(Boolean)
at Renci.SshNet.Sftp.SubsystemSession.Dispose(Boolean)
at Renci.SshNet.Sftp.SftpSession.Dispose(Boolean)
at Renci.SshNet.Sftp.SubsystemSession.Finalize()

__This occurred just over 60 seconds _after_ the Dispose method on SftpClient was called which generated a very similar exception (handled and logged by my code):__

2013-02-16 15:41:32.9693 Error SftpFileTransfer Renci.SshNet.Common.SshConnectionException,Client not connected., at Renci.SshNet.Session.SendMessage(Message message)
at Renci.SshNet.Channels.Channel.SendMessage(ChannelCloseMessage message)
at Renci.SshNet.Channels.Channel.Close(Boolean wait)
at Renci.SshNet.Channels.ChannelSession.Close(Boolean wait)
at Renci.SshNet.Channels.Channel.Dispose(Boolean disposing)
at Renci.SshNet.Channels.ChannelSession.Dispose(Boolean disposing)
at Renci.SshNet.Sftp.SubsystemSession.Dispose(Boolean disposing)
at Renci.SshNet.Sftp.SftpSession.Dispose(Boolean disposing)
at Renci.SshNet.SftpClient.Dispose(Boolean disposing)
at Renci.SshNet.BaseClient.Dispose()
at BusinessObjects.SftpFileTransfer.DownloadFiles()


__It looks like ~SubsystemSession() is causing an attempt to send a message over the channel(!) due to the chaining of calls to the various Dispose() methods.__

Reopened Issue: SCP Can't Upload Rooted Directories [1511]

$
0
0
As per the discussion [here](http://sshnet.codeplex.com/discussions/284021), SCP doesn't currently work when uploading rooted folders.

Reopened Issue: Invalid handling of http proxy server response [1509]

$
0
0
Hi,

I did find a problem when testing the assembly with our squid 3.0 proxy. I receive the message, that Result cannot be called on a failed match. Therefore I've extended the code in Session.cs a little bit:

if (statusCode == 200 && string.IsNullOrEmpty(response))
{
// Once all HTTP header information is read, exit
break;
}
else
{
string reasonPhrase = string.Empty;

try
{
if (match.Success)
reasonPhrase = match.Result("${reasonPhrase}");
}
catch (Exception ex)
{
reasonPhrase = string.Empty;
}

Now the following line

throw new ProxyException(string.Format("HTTP: Status code {0}, Reason \"{1}\"", statusCode, reasonPhrase));

Does at least return the error code (not yet the fault reason; in this case ERR_ACCESS_DENIED)

In fact the code received a 403 status code from the proxy:

SshNet.Logging Verbose: 1 : Initiating connect to 'yyy.xxx.zzz.ww:22'.

HTTP/1.0 403 Forbidden
Server: squid/3.0.STABLE16-RC1
Mime-Version: 1.0
Date: Wed, 13 Feb 2013 14:15:06 GMT
Content-Type: text/html
Content-Length: 1008
Expires: Wed, 13 Feb 2013 14:15:06 GMT
X-Squid-Error: ERR_ACCESS_DENIED 0
X-Cache: MISS from app-proxy-3.xxxx.xxx
Via: 1.0 app-proxy-3.xxxx.xxx (squid/3.0.STABLE16-RC1)
Proxy-Connection: close

The thread 0xa2c has exited with code 0 (0x0).

Kind regards

Johannes

Reopened Issue: Dispose() should not leave running threads behind! [1436]

$
0
0
Hi. I have found a really hard to find bug that is very consistently repeatable. Before getting into the details, I think it should be noted that this issue will be resolved if the Renci.SshNet.SshClient.Dispose() and the Renci.SshNet.ForwardedPortLocal.Dispose() (and anything else) actually and honestly dispose everything. But the problem is that after calling those, there are still threads hanging around doing stuff and sometimes they get stuck badly. It looks like someone went crazy with anonymous methods and launching Thread Tasks without leaving a handle to the Thread for management by the parents to kill them when disposed. And I found in Session.NET40.cs this line: Task.Factory.StartNew(action, TaskCreationOptions.LongRunning);which I changed to: Task.Factory.StartNew(action, TaskCreationOptions.AttachedToParent);but it had no positive impact.I have seen posts on this site about Disconnect doing funny stuff and also about the Timeouts not seeming to disconnect things, and some other things like that. I bet they are related to getting over your head in multi-threading or events.The result is that sometimes I still have the process listening on the local port way after the Dispose() is called. And also the Connection is sitting there too. Usually this happens when eliminating both the Forwards and the Connection, but sometimes even just the Forwards. The call to the Forward's Disconnect() and Dispose() when the problem happens will take a much longer time, but then sadly continue going after seemingly giving up.When I pause I can see 2 Renci threads hanging around and stuck at these points:ForwardedPortLocal.NET.cs line 34: var socket = this._listener.AcceptSocket();Session.cs line 1575: var message = this.ReceiveMessage();I have tested this A LOT!!! trying to find ways around it. It happens in the code base (pulled today 12/5/12), it happens in .Net 4.0 DLL from a month ago, and it happens from .Net 3.5 DLL pulled today also. Another result is that sometimes the situation causes the app to die a horrible death with:System.AggregateException was unhandled Message=A Task's exception(s) were not observed either by Waiting on the Task or accessing its Exception property. As a result, the unobserved exception was rethrown by the finalizer thread. Source=mscorlib StackTrace: at System.Threading.Tasks.TaskExceptionHolder.Finalize() InnerException: System.NullReferenceException Message=Object reference not set to an instance of an object. Source=Renci.SshNet StackTrace: at Renci.SshNet.ForwardedPortLocal.b__0() at System.Threading.Tasks.Task.InnerInvoke() at System.Threading.Tasks.Task.Execute()WHEN DOES THIS HAPPEN:Here is the kicker. I wrote an app to manage SSH tunnels. And when I first was having problems with Renci, I made it so I can implement other libraries and other means. Via a config file I can add and remove tunnels and have multiple connections. The process reads the config file periodically and applies the changes found. So I can have a connection using Renci, another using Chilkat, another using Plink, Tunnelier, and that's all I finished implementing so far.If I have all Renci connections, it seems that I can add and remove tunnels and connections a bunch of times and not have an issue. (however usually there is a Connection (SshClient) that hangs around in CLOSE_WAIT state). If I bring say Chilkat into the mix, things still are OK.. and I can replace all active connections to one of the other implementations.The problems start happening when I bring in Plink or Tunnelier. They are launched using System.Process. They close themselves properly from what I see in memory and via TCP connections and SSH server. When I have a Renci and Plink (let's say) connection, it is then that if I start removing tunnels from Renci I might have issues. If I start removing the Connection, I almost always have an issue.The issue is that when Renci is told to close up shop, it stalls for a while, and then the code moves on while leaving the listeners in place (though of course not working). And they stay there it seems indefinitely. And I'm also using System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners() to look at the listeners and it's there. It's because there are those silly Renci threads that are hanging around for some reason trying to read from the socket.And I have verified that the Connection replacement (like Plink) is not actually opening up that tunnel. I have my app now specifically checks for the Active listeners before moving tunnels to another connection.This may be a very complicated specific bug to find, but I think the real root of the problem and the much easier one to fix, is that when you Dispose(), it really should be DISPOSED, leaving no threads behind. I have also verified that calling SshClient.Dispose() does not DISCONNECT, so you have to call both. I think also similar thing with the Forward.. if you don't call Stop().This is how I stop the connections and port forwards: foreach (ForwardedPort forward in this.sshConnection.ForwardedPorts.ToList()) { this.sshConnection.RemoveForwardedPort(forward); Console.WriteLine("just finished removing tunnel"); } this.sshConnection.Disconnect(); Console.WriteLine("just finished conn Disconnect()"); this.sshConnection.Dispose(); Console.WriteLine("just finished conn Dispose()"); public void Dispose() { if (this.localForward != null) { this.localForward.Stop(); Console.WriteLine("just finished tunnel Stop()"); this.localForward.Dispose(); Console.WriteLine("just finished tunnel Disconnect()"); //System.Threading.Thread.Sleep(2000); } }

Reopened Issue: SCP : Missing files when using DirectoryUpload [1382]

$
0
0
Hi,I have the following environment:- Win7 / 64- .NET 3.5- MPC-Target :OpenSSH_6.0p1, OpenSSL 1.0.0j 10 May 2012- SSH.NET commit 19813I want to upload a directory structure (recursive, depth = 2) from the PC to a MPC basedLinux remote system. The total amount of data is about 8MB with 23 files from55 bytes to 4MB.Calling mScp.Upload(new DirectoryInfo(localDir), remoteDir) does not result anyerror and the Uploading event shoes uploading all files. But after Upload() returnedThere are a random number of missing files on the target (between 1 and 5).It tried the same with a PC based Linux as target what resulted in the same behaviour(OpenSSH_5.8p1 Debian-7ubuntu1, OpenSSL 1.0.0e 6 Sep 2011). It seems theproblem is caused anywhere within SSH.NET.Does anyone have a solution?Extension:I tried to workaround by replacing Upload(new DirectoryInfo(...)) by several singlecalls of Upload(new FileInfo(...)). This worked but is too slow for my application.

Reopened Feature: File Transfer Progress [1324]

$
0
0
** Added Issue as status PROPOSED type FEATURE **This is a discussion thread. Is there any interest in including a way to expose current transfer progress to an application? For example, imagine a user wanting to upload a file could pass in an implementation of:    public interface IFileTransferHandler{ ulong BytesRead { get; }  void IncrementBytesRead(ulong bytes);  void TransferCompleted();}    Whenever the callback for Write returns confirming that the bytes were written, IncrementReadBytes would be called and whenever the file is fully uploaded TransferCompleted gets called. Since we're passing in streams, there's no objective way to determine the file size so that would have to be provided in the implementation, if at all. All you really need to do is add a field for that interface in SftpFileStream and then pass it to all calls to RequestWrite and then create some new constructors so that the interface can be passed along from the publicly exposed methods (I've managed to build a sample implementation for sftp upload, so this method works). The only issue is if the handler throws an exception. Since it's asynchronous the debugger displays the stack trace in the wrong place and could confuse developers.

Reopened Issue: Unobserved exception rethrown by finalizer thread [1298]

$
0
0
Hi, There is an unhandled System.AggregateException in a worker thread within SSH.NET version 18974 that causes the container application to crash. The exception should be caught and rethrown to the caller. This error occurs when the connection between the SHH client and server is flaky, i.e. it comes on and off. I added an AppDomain unhandled exception handler to log the exception. Here is the stack trace of the exception: ERROR: SubsystemSession.cs(128): Object reference not set to an instance of an object.ERROR: SubsystemSession.cs(169): Renci.SshNet.Sftp.SubsystemSession.Session_ErrorOccured(Object sender, ExceptionEventArgs e) failed.ERROR: System.EventHandler`1.Invoke(Object sender, TEventArgs e) failed.ERROR: Session.cs(1929): Renci.SshNet.Session.RaiseError(Exception exp) failed.ERROR: Session.cs(1592): Renci.SshNet.Session.MessageListener() failed.ERROR: Session.cs(522): Renci.SshNet.Session.b__14() failed.ERROR: System.Threading.Tasks.Task.InnerInvoke() failed.ERROR: System.Threading.Tasks.Task.Execute() failed.ERROR: A Task's exception(s) were not observed either by Waiting on the Task or accessing its Exception property. As a result, the unobserved exception was rethrown by the finalizer thread.ERROR: Application domain unhandled exception. I am not too familar with Tasks, but I suspect the error could be fixed by adding a catch block to the try block at Session.cs, line 520, and rethrow the exception. I am posting this while I am trying to fix the issue in case someone else can help. Thanks, Robert

New Post: Calling SSH from Sharepoint

$
0
0
I've wrapped SSH.Net in a web service so that I can call it from SharePoint. I'm using SSH.Net to make calls from a windows server to a Unix server. On my local laptop the web service is working fine and my SSH.Net calls are working great. I then released the code to our development web server. I created a test app to ensure web service is working on the dev web server. I'm running the test app on my local laptop but it calls out to the DEV web server and that also works perfectly. Unfortunately when I call the web services from our SharePoint Server I get a the "No suitable authentication method found to complete authentication." error. In all my test scenarios regardless of what method initiates the web service call the SSH.Net code is calling the same Unix server.

I don't understand why I'm getting the error because I've added logging to the SSH.Net code and password authentication is one of the allowed authentication methods. I've also confirmed that the web service is using the proper username and password in all cases.

I'm at a loss as to why I'm getting this error. Any help or suggestions would be greatly appreciated.

Created Unassigned: Incorrect check for timeout vallues [1620]

$
0
0
In ShellStream.cs we see this four times:

> if (timeout != null)
> {...}

Well, _timeout_ is a value type and it will never be "null", meaning in the above expression it wall always evaluate to true.

I fixed it locally by replacing the above with:

> if (timeout.Ticks > 0)
> {...}

Source code checked in, #28763

Edited Issue: Wrong PKCS7 padding in DES algorithm [1580]

$
0
0
public class PKCS7Padding : CipherPadding
{
/// <summary>
/// Transforms the specified input.
/// </summary>
/// <param name="blockSize">Size of the block.</param>
/// <param name="input">The input.</param>
/// <returns>
/// Padded data array.
/// </returns>
public override byte[] Pad(int blockSize, byte[] input)
{
var numOfPaddedBytes = blockSize - (input.Length % blockSize);

var output = new byte[input.Length + numOfPaddedBytes];
Buffer.BlockCopy(input, 0, output, 0, input.Length);
for (int i = 0; i < numOfPaddedBytes; i++)
{
//Wrong
//output[input.Length + i] = output[input.Length - 1];

//Should be like this
output[input.Length + i] = (byte)numOfPaddedBytes;
}

return output;
}
}

Source code checked in, #28764

$
0
0
Fix "OverflowException on empty server response" for silverlight

Edited Issue: OverflowException on empty server response [1562]

$
0
0
Hello,

I'm trying to connect to OS X Mountain Lion from a Windows Phone 7.5 application using a SFTP client implemented using your library (version 2013.4.7), and upon sftpclient.connect, after a few seconds of it apparently waiting for something, it crashes with OverflowException. Debugging in the source code the OverflowException is thrown in line 88 of Session.SilverlightShared.cs:
```
response = encoding.GetString(buffer.ToArray(), 0, buffer.Count - 1);
```

At this point buffer.Count = 0, so buffer.Count -1 is actually -1.

Looking up it did break at:
```
// If zero bytes received then exit
if (args.BytesTransferred == 0)
break;
```

However in the subsequent tests that case doesn't seem handled:
```
if (buffer.Count > 0 && buffer[buffer.Count - 1] == 0x00)
{
response = string.Empty;
}
else if (buffer.Count > 1 && buffer[buffer.Count - 2] == 0x0D)
response = encoding.GetString(buffer.ToArray(), 0, buffer.Count - 2);
else
response = encoding.GetString(buffer.ToArray(), 0, buffer.Count - 1);
```

So I added a simple line as follows and now I do get the "Server string is null or empty" exception as expected:

```
if (buffer.Count > 0 && buffer[buffer.Count - 1] == 0x00)
{
response = string.Empty;
}
else if (buffer.Count == 0) response = string.Empty; // <-- this line right here
else if (buffer.Count > 1 && buffer[buffer.Count - 2] == 0x0D)
response = encoding.GetString(buffer.ToArray(), 0, buffer.Count - 2);
else
response = encoding.GetString(buffer.ToArray(), 0, buffer.Count - 1);
```
Viewing all 2955 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>