EldoS | Feel safer!

Software components for data protection, secure storage and transfer

SSH public and private key - .Net C#

Also by EldoS: CallbackRegistry
A component to monitor and control Windows registry access and create virtual registry keys.
#9866
Posted: 04/29/2009 10:29:26
by Blue White (Basic support level)
Joined: 01/22/2009
Posts: 27

Hi,
I am trying to connect from .net application to an sftp server which im sure of its connection and all the

credentials (im able to connect to this SFTP server from FileZilla)

here's my code:

Code
public partial class Form2 : Form
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger

(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private SBSimpleSftp.TElSimpleSFTPClient SftpClient;

        private TElSSHMemoryKeyStorage KeyStorage;


   public Form2()
        {
            SftpClient = new TElSimpleSFTPClient();
            this.SftpClient.OnKeyValidate += new SBSSHCommon.TSSHKeyValidateEvent

(this.SftpClient_OnKeyValidate);
            XmlConfigurator.Configure();

            InitializeComponent();

          
            SBUtils.Unit.SetLicenseKey(SBUtils.Unit.BytesOfString("here goes my key"));

            KeyStorage = new TElSSHMemoryKeyStorage(this);
            SftpClient.KeyStorage = KeyStorage;        
        }


private void Connect()
        {

            log.Info("stepping inside Connect method");

            SftpClient.Username = "user";
            SftpClient.Password = "pass";
            SftpClient.Address = "ip.address.goes.here";
            SftpClient.Port = 22;


            KeyStorage.Clear();
            TElSSHKey key = new TElSSHKey();
            SftpClient.AuthenticationTypes = SBSSHConstants.Unit.SSH_AUTH_TYPE_PUBLICKEY;

            //int err1 = key.LoadPublicKey(@"C:\Keys\publickey", "");
            //if (err1 != 0)
            //{
            //    log.Error("Error in retrieving publickey file" + err1.ToString());
            //}

            string privateKeyFile = @"C:\Keys\privatekey.rsa";
            int err2 = key.LoadPrivateKey( privateKeyFile, "");
            if (err2 != 0)
            {
                log.Error("Error in retrieving privatekey file" + err2.ToString());
            }
            if (err2 == 0)
            {
                KeyStorage.Add(key);
            }

            try
            {
                SftpClient.Open();

            }
            catch (Exception e)
            {
                try
                {
                    SftpClient.Close(true);
                    label1.Visible = true;
                    label1.Text = "Failed to connect to SFTP server";
                    if (SftpClient.ServerSoftwareName.Length > 0)
                    {
                        label1.Text += "Server identified itself as: " +

SftpClient.ServerSoftwareName.ToString();
                    }
                    log.Error("Failed to connect to SFTP server");
                }
                catch
                {
                }
                return;
                //log.Error("Connection failed");
            }
            
            log.Info("Connected to SFTP Server");
            label1.Visible = true;
            label1.Text = "Connected to SFTP Server";

         }

  private void Upload()
        {
            string localPath = @"C:\SFTPuploadTest.txt";
            string remoteFile = @"C:\SFTPuploadTest.txt";
            try
            {
                SftpClient.UploadFile(localPath, remoteFile);
            }
            catch
            {
                log.Error("Error uploading file");

            }


        }


....



and here's my InitializeComponent() which is found in form2.Designer.cs

Code
private void InitializeComponent()
        {
            this.btnUpload = new System.Windows.Forms.Button();
            this.label1 = new System.Windows.Forms.Label();
            this.SuspendLayout();
            //
            // btnUpload
            //
            this.btnUpload.Location = new System.Drawing.Point(216, 250);
            this.btnUpload.Name = "btnUpload";
            this.btnUpload.Size = new System.Drawing.Size(75, 23);
            this.btnUpload.TabIndex = 0;
            this.btnUpload.Text = "Upload";
            this.btnUpload.UseVisualStyleBackColor = true;
            this.btnUpload.Click += new System.EventHandler(this.btnUpload_Click_1);
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(1, 9);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(35, 13);
            this.label1.TabIndex = 1;
            this.label1.Text = "label1";
            //
            // Form2
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(484, 485);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.btnUpload);
            this.Name = "Form2";
            this.Text = "Form2";
            this.ResumeLayout(false);
            this.PerformLayout();


            //
            // SftpClient
            //
            this.SftpClient.ClientHostname = "";
            this.SftpClient.ClientUsername = "";
            this.SftpClient.CompressionLevel = 6;
            this.SftpClient.ForceCompression = false;
            this.SftpClient.KeyStorage = null;
            this.SftpClient.Password = "";
            this.SftpClient.SFTPExt = null;
            this.SftpClient.SoftwareName = "EldoS.SFTPBlackbox.5";
            this.SftpClient.Username = "";
            this.SftpClient.Versions = ((short)(28));
            this.SftpClient.OnKeyValidate += new SBSSHCommon.TSSHKeyValidateEvent

(this.SftpClient_OnKeyValidate);
            //this.SftpClient.OnAuthenticationSuccess += new SBUtils.TNotifyEvent

(this.SftpClient_OnAuthenticationSuccess);
            //this.SftpClient.OnAuthenticationKeyboard += new SBSSHCommon.TSSHAuthenticationKeyboardEvent

(SftpClient_OnAuthenticationKeyboard);
            //this.SftpClient.OnCloseConnection += new SBSSHCommon.TSSHCloseConnectionEvent

(this.SftpClient_OnCloseConnection);
            //this.SftpClient.OnError += new SBSSHCommon.TSSHErrorEvent(this.SftpClient_OnError);
            //this.SftpClient.MessageLoop += new SBSftpCommon.TSBSftpMessageLoopEvent

(this.SftpClient_MessageLoop);
            //this.SftpClient.OnAuthenticationFailed += new SBSSHCommon.TSSHAuthenticationFailedEvent

(this.SftpClient_OnAuthenticationFailed);
            //this.SftpClient.OnProgress += new SBUtils.TSBProgressEvent(this.SftpClient_OnProgress);

        }


it's not able to connect, it's stopping on the catch after SftpClient.Open();

and the result for:

Code

if (SftpClient.ServerSoftwareName.Length > 0)
                    {
                        label1.Text += "Server identified itself as: " +

SftpClient.ServerSoftwareName.ToString();
                    }


is:

Server identified itself as: WeOnlyDo-wodFTPD 2.3.6.165

would you please help me on this error? why can't i be connected?
is it from my code?

Thanks
#9867
Posted: 04/29/2009 11:33:32
by Eugene Mayevski (EldoS Corp.)

Dealing with user code is done only on Standard support level, i.e. for registered users. I am sorry but we won't be able to help you until you purchase a license.


Sincerely yours
Eugene Mayevski
#9872
Posted: 04/30/2009 01:56:06
by Blue White (Basic support level)
Joined: 01/22/2009
Posts: 27

ok, ill be asking you general questions not directly related to code.

Thanks for your help.
#9976
Posted: 05/11/2009 10:26:47
by Blue White (Basic support level)
Joined: 01/22/2009
Posts: 27

Hi,

I went through the knowledge base and have read the following:
Public key authentication

Public key authentication method is the only method that each software (both client and server) is required to implement. This method expects each client to have a key pair (key pair is a pair of keys, properly generated using one of asymmetric encryption algorithms, either RSA or DSA). The client first sends a public key to the server. If the server finds the key in the list of allowed keys, the client encrypts certain data packet using private key and sends the packet to the server together with the public key.

In SSH/SFTP client components public key authentication is done using TElSSHMemoryKeyStorage class. This class is a storage for keys (represented by TElSSHKey class). The application should put a key (which contains both public and private parts) to the storage and attach KeyStorage to ElSSHClient or other SSH/SFTP component via this component's KeyStorage property.

but in the SimpleSftpDemo, I was not able to find anything that makes the client give the public key to the server. there's only loadprivatekeyfile method.
Also i have not found anything that makes the client take the public key of the server and authenticate it.

could you please show me if it's done in the simplesftpclientDemo.

and how can i make the client always trust the server?

thanks.
#9977
Posted: 05/11/2009 10:46:21
by Eugene Mayevski (EldoS Corp.)

Quote
Blue White wrote:
but in the SimpleSftpDemo, I was not able to find anything that makes the client give the public key to the server. there's only loadprivatekeyfile method.


You are misinterpreting the article: you can't authenticate the client to the server without having both private and public keys. Indeed only the public key is sent to the server, but the private key is used for computations during key exchange.

Quote
Blue White wrote:
Also i have not found anything that makes the client take the public key of the server and authenticate it.


OnKeyValidate event.


Sincerely yours
Eugene Mayevski
#9978
Posted: 05/11/2009 10:48:36
by Mykola Olshevsky (Basic support level)
Joined: 07/07/2005
Posts: 450

Hi.
To authenticate server's key, you should use OnKeyValidate event handler.
To authenticate client with public key, you should load his public key (or public and secret key) to ElSimpleSftpClient.KeyStorage, or you can also load client's private key in .OnPrivateKeyNeeded event handler.
#9982
Posted: 05/12/2009 01:33:55
by Blue White (Basic support level)
Joined: 01/22/2009
Posts: 27

Thanks for the explanation,

Eugene:

Quote
Indeed only the public key is sent to the server,



Mykola:
Quote
To authenticate client with public key, you should load his public key (or public and secret key) to ElSimpleSftpClient.KeyStorage.


but in SimpleSftpDemo_VS2008 sample which is found under EldoS\SecureBlackbox.NET\Samples, there is no use for LoadPublicKey method,
instead, there's only the use of LoadPrivateKey method. Then this key is added to the KeyStorage.

here's a copy of the SimpleSftpDemo_VS2008 code:

Code
if (dlg.txtPrivateKey.Text != "")
            {
               int err = Key.LoadPrivateKey(dlg.txtPrivateKey.Text, "");
               if (err == 0)
               {
                  KeyStorage.Add(Key);
                  SftpClient.AuthenticationTypes = SftpClient.AuthenticationTypes | SBSSHConstants.Unit.SSH_AUTH_TYPE_PUBLICKEY;
               }
               else
               {
                  SftpClient.AuthenticationTypes = SftpClient.AuthenticationTypes & (~SBSSHConstants.Unit.SSH_AUTH_TYPE_PUBLICKEY);
                  Log("Private key file could not be loaded due to error "  + err.ToString(), true);
               }
            }


in the above code, how is the public key sent to the server?i can only see the private key being sent.
#9983
Posted: 05/12/2009 04:34:22
by Mykola Olshevsky (Basic support level)
Joined: 07/07/2005
Posts: 450

Client doesn't need to load public key, since private key contains all data, required to be sent (i.e. SSH private key also contains public part).
#9988
Posted: 05/12/2009 07:49:38
by Blue White (Basic support level)
Joined: 01/22/2009
Posts: 27

Ok Thanks for the reply
#10004
Posted: 05/13/2009 02:25:03
by Blue White (Basic support level)
Joined: 01/22/2009
Posts: 27

Hi,

I am now able to connect to an SFTP server (FreeSSHd Trial Version which has an SFTP built in server), the problem is it only connects
1 time out of several times. I even tested your code samples, it only connects few times out of several connect trials.
when I am not connected i always get this 10058 error.

can I assume that this problem is totally related to the SFTP server?

Thanks
Also by EldoS: Callback File System
Create virtual file systems and disks, expose and manage remote data as if they were files on the local disk.

Reply

Statistics

Topic viewed 26304 times

Number of guests: 2, registered members: 0, in total hidden: 0




|

Back to top

As of July 15, 2016 EldoS Corporation will operate as a division of /n software inc. For more information, please read the announcement.

Got it!