Пример #1
0
        static void do_service(string ipaddress, string private_key)
        {
            PrivateKeyFile private_key_file = new PrivateKeyFile(private_key);
            ConnectionInfo connect_info     = new ConnectionInfo(ipaddress, 22, "usi_engine",
                                                                 new AuthenticationMethod[] { new PrivateKeyAuthenticationMethod("usi_engine",
                                                                                                                                 new PrivateKeyFile[] { private_key_file }) });

            connect_info.Timeout = TimeSpan.FromMinutes(30);

            int read_timeout = checked (60 * 60 * 5);

            using (var client = new SshClient(connect_info))
            {
                client.KeepAliveInterval = TimeSpan.FromSeconds(30);
                client.Connect();
                using (ShellStream stream = client.CreateShellStream("usi_engine", 80, 24, 800, 600, 1024))
                {
                    var reader = new StreamReader(stream);
                    var writer = new StreamWriter(stream);
                    writer.AutoFlush = true;

                    read_stream_async(reader, read_timeout);
                    while (sync_flg_)
                    {
                        var str = Console.ReadLine();
                        write_stream(str.TrimEnd(), writer, stream);
                        if (str.Equals("quit"))
                        {
                            break;
                        }
                    }
                }
            }
        }
Пример #2
0
        public void PrivateKeyFileConstructorTest3()
        {
            Stream         privateKey = null; // TODO: Initialize to an appropriate value
            PrivateKeyFile target     = new PrivateKeyFile(privateKey);

            Assert.Inconclusive("TODO: Implement code to verify target");
        }
Пример #3
0
        static Keys()
        {
            string basePath = Path.Combine(Path.GetDirectoryName(new Uri(typeof(Keys).Assembly.CodeBase).LocalPath), "TestData");

            PublicKeys = SshRsaModule.loadPublicKeys(Path.Combine(basePath, "authorized_keys"));
            PrivateKey = new PrivateKeyFile(Path.Combine(basePath, "test_rsa"), "test");
        }
Пример #4
0
 public FtpInfoModel(string localPath, string hostUri, string usuario, string privateKeyPath, string privateKeyPassword)
 {
     LocalPath  = localPath;
     PrivateKey = new PrivateKeyFile(privateKeyPath, privateKeyPassword);
     HostURI    = hostUri;
     Usuario    = usuario;
 }
        public async Task <IActionResult> OnPostAsync()
        {
            LodgerUser = await _userManager.GetUserAsync(User);

            VirusReport vr = await ScanForVirus(PrivateKeyFile);

            if (vr.Positives > 0)
            {
                ModelState.AddModelError("PrivateKeyFileFailedVirusCheck", "ProfilePicture failed virus scan!");
                ModelState.AddModelError("PrivateKeyFileReportLink", vr.ReportLink);
                return(Page());
            }
            using (var ms = new MemoryStream())
            {
                PrivateKeyFile.CopyTo(ms);
                byte[] PrivateKeyFileBytes = ms.ToArray();
                SHA512 sha512 = SHA512.Create();
                byte[] HashedPrivateKeyFileBytes  = sha512.ComputeHash(PrivateKeyFileBytes);
                string HashedPrivateKeyFileString = Encoding.UTF8.GetString(HashedPrivateKeyFileBytes);
                LodgerUser.secretFileVerificationHash = HashedPrivateKeyFileString;
                await _context.SaveChangesAsync();

                AlertMessage = "Success! You can now login to your account by uploading this file at the login page!";
            }
            return(Page());
        }
Пример #6
0
        public SSHclient(string ip, int port, string user, string pw)
        {
            try
            {
                PrivateKeyFile pkf = new PrivateKeyFile(@"C:\Users\lotte_test\Desktop\개인 프로젝트\GoogleSoft\Compute Service\Login Keys\스타2\aa", pw);
                PrivateKeyAuthenticationMethod pam = new PrivateKeyAuthenticationMethod(user, pkf);
                ConnectionInfo connInfo            = new ConnectionInfo(ip, port, user, pam);

                client = new SshClient(connInfo);
                client.Connect();

                if (client.IsConnected)
                {
                    MessageBox.Show("연결 성공");
                }
                else
                {
                    MessageBox.Show("연결 실패");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
Пример #7
0
        public SshManager(Config.Config config)
        {
            try
            {
                KeyFile    = config.UserKeyFilePath;
                Passphrase = config.UserFingerprint;
                UserName   = config.UserLogin;
                Host       = config.ClusterHost;
                Port       = config.ClusterPort;

                _privateKeyFile = new PrivateKeyFile(KeyFile, Cryptor.Decrypt(Passphrase, "abc123"));

                var keyFiles = new[] { _privateKeyFile };
                var username = UserName;

                var methods = new List <AuthenticationMethod>();
                methods.Add(new PrivateKeyAuthenticationMethod(username, keyFiles));

                _connectionInfo = new ConnectionInfo(Host, Port, username, methods.ToArray())
                {
                    Timeout = TimeSpan.FromSeconds(60)
                };

                _compilerConnectionInfo = new ConnectionInfo("compiler." + Host, Port, username, methods.ToArray())
                {
                    Timeout = TimeSpan.FromSeconds(60)
                };
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Пример #8
0
        public SshClient Connect(string host, int port, string user, string password, string pkey)
        {
            SshClient ssh = null;

            try
            {
                if (password != null)
                {
                    ssh = new SshClient(host, port, user, password);
                    ssh.ConnectionInfo.Timeout = TimeSpan.FromSeconds(5);
                }
                else
                {
                    var pk       = new PrivateKeyFile(pkey);
                    var keyFiles = new[] { pk };
                    ssh = new SshClient(host, port, user, keyFiles);
                    ssh.ConnectionInfo.Timeout = TimeSpan.FromSeconds(5);
                }
                ssh.Connect();
            }
            catch (Renci.SshNet.Common.SshAuthenticationException ex)
            {
                // bad key
                Error = ex.Message;
            }
            catch (Exception ex)
            {
                Error = ex.Message;
            }
            return(ssh);
        }
Пример #9
0
        public string ExecuteCommand(string command)
        {
            string host     = _config.GetValue <string>("ESXI:host");
            string username = _config.GetValue <string>("ESXI:username");
            string keyPath  = _config.GetValue <string>("ESXI:privateKeyPath");
            int    port     = _config.GetValue <int>("ESXI:port");

            var pk       = new PrivateKeyFile(keyPath);
            var keyFiles = new[] { pk };

            var methods = new List <AuthenticationMethod>();

            methods.Add(new PrivateKeyAuthenticationMethod(username, keyFiles));

            var connectionInfo = new ConnectionInfo(host, port, username, methods.ToArray());

            using (var client = new SshClient(connectionInfo))
            {
                client.Connect();
                var cmd    = client.CreateCommand(command);
                var result = cmd.Execute();

                client.Disconnect();
                return(cmd.Result);
            }
        }
Пример #10
0
        /// <summary>
        ///     GetSshClient
        /// </summary>
        /// <param name="host"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="ppkFilename"></param>
        /// <returns></returns>
        public static SshClient GetSshClient(string host, string username, string password, string ppkFilename)
        {
            var ppkFile = new PrivateKeyFile(ppkFilename);
            var client  = new SshClient(host, username, ppkFile);

            return(client);
        }
Пример #11
0
 public void PrivateKeyFileConstructorTest1()
 {
     string fileName = string.Empty; // TODO: Initialize to an appropriate value
     string passPhrase = string.Empty; // TODO: Initialize to an appropriate value
     PrivateKeyFile target = new PrivateKeyFile(fileName, passPhrase);
     Assert.Inconclusive("TODO: Implement code to verify target");
 }
Пример #12
0
 public SftpUploader(AppConfig conf)
 {
     this.config = conf;
     if (config.sftpEnabled)
     {
         AuthenticationMethod[] auths = new AuthenticationMethod[1];
         if (String.IsNullOrWhiteSpace(config.sftpPrivateKeyPath))
         {
             auths[0] = new PasswordAuthenticationMethod(config.sftpUsername, Utils.GetBytes(config.sftpPassword));
         }
         else
         {
             try
             {
                 PrivateKeyFile pkf = null;
                 if (string.IsNullOrEmpty(config.sftpPassword))
                 {
                     pkf = new PrivateKeyFile(config.sftpPrivateKeyPath);
                 }
                 else
                 {
                     pkf = new PrivateKeyFile(config.sftpPrivateKeyPath, config.sftpPassword);
                 }
                 auths[0] = new PrivateKeyAuthenticationMethod(config.sftpUsername, pkf);
             }
             catch (IOException)
             {
                 Log.Error("Unable to read private key file: " + config.sftpPrivateKeyPath);
                 return;
             }
         }
         connInfo = new ConnectionInfo(config.sftpRemoteServer, config.sftpUsername, auths);
     }
 }
Пример #13
0
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="host">sftp服务器名或IP</param>
        /// <param name="port">端口,默认22</param>
        /// <param name="user">用户名</param>
        /// <param name="privateKey">私钥</param>
        /// <param name="passPhrase">通行短语</param>
        public SFtpRSAHelper(string host, int?port, string user, string privateKey, string passPhrase)
        {
            PrivateKeyFile keyFile = null;

            if (string.IsNullOrEmpty(passPhrase))
            {
                keyFile = new PrivateKeyFile(privateKey);
            }
            else
            {
                keyFile = new PrivateKeyFile(privateKey, passPhrase);
            }

            if (port.HasValue)
            {
                sftp = new SftpClient(host, port.Value, user, keyFile);
            }
            else
            {
                sftp = new SftpClient(host, user, keyFile);
            }


            if (sftp != null)
            {
                sftp.ConnectionInfo.RetryAttempts = 5;
                sftp.ConnectionInfo.Timeout       = new TimeSpan(0, 3, 0);
            }
        }
Пример #14
0
        public static void SshAuthenticateWithPK(BotData data, string host, int port = 22, string username = "******",
                                                 string keyFile = "rsa.key", string keyFilePassword        = "", int timeoutMilliseconds = 30000,
                                                 int channelTimeoutMilliseconds = 1000, int retryAttempts  = 10)
        {
            data.Logger.LogHeader();

            ConnectionInfo info;
            var            pk       = new PrivateKeyFile(keyFile, keyFilePassword);
            var            keyFiles = new[] { pk };

            if (data.UseProxy && data.Proxy is not null)
            {
                info = new ConnectionInfo(host, port, username, TranslateProxyType(data.Proxy.Type), data.Proxy.Host,
                                          data.Proxy.Port, data.Proxy.Username, data.Proxy.Password,
                                          new PrivateKeyAuthenticationMethod(username, keyFiles));
            }
            else
            {
                info = new ConnectionInfo(host, port, username,
                                          new PrivateKeyAuthenticationMethod(username, keyFiles));
            }

            info.Timeout             = TimeSpan.FromMilliseconds(timeoutMilliseconds);
            info.ChannelCloseTimeout = TimeSpan.FromMilliseconds(channelTimeoutMilliseconds);
            info.RetryAttempts       = retryAttempts;

            var client = new SshClient(info);

            client.Connect();

            data.SetObject("sshClient", client);

            data.Logger.Log($"Connected to {host} on port {port} as {username}", "#526ab4");
        }
Пример #15
0
        private static AuthenticationMethod[] privateKeyObject(string username, string publicKeyPath)
        {
            PrivateKeyFile privateKeyFile = new PrivateKeyFile(publicKeyPath);
            PrivateKeyAuthenticationMethod privateKeyAuthenticationMethod = new PrivateKeyAuthenticationMethod(username, privateKeyFile);

            return(new AuthenticationMethod[] { privateKeyAuthenticationMethod });
        }
Пример #16
0
        public bool Connect()
        {
            this.authorition = this.Authorition as SshConnectionAuthorition;

            var authentications = new List <AuthenticationMethod>();

            if (!string.IsNullOrEmpty(this.authorition.KeyFilePath))
            {
                var privateKeyFile = new PrivateKeyFile(this.authorition.KeyFilePath, this.authorition.KeyFilePassphrase);
                authentications.Add(new PrivateKeyAuthenticationMethod(this.authorition.UserName, privateKeyFile));
            }
            authentications.Add(new PasswordAuthenticationMethod(this.authorition.UserName, this.authorition.Password));
            ConnectionInfo connectionInfo = new ConnectionInfo(this.authorition.ServerAddress, this.authorition.ServerPort, this.authorition.UserName, authentications.ToArray());

            //this.parser = new AnsiEscapeSequencesParser();

            try
            {
                this.sshClient = new SshClient(connectionInfo);
                this.sshClient.Connect();
                this.sshClient.KeepAliveInterval = TimeSpan.FromSeconds(20);
                this.shellStream = this.sshClient.CreateShellStream(this.authorition.TerminalName, this.authorition.TerminalColumns, this.authorition.TerminalRows, 0, 0, 1000);
                this.shellStream.DataReceived += this.ShellStream_DataReceived;
                this.writer = new BinaryWriter(this.shellStream, Encoding.UTF8);
            }
            catch (Exception ex)
            {
                logger.Error("初始化SshConnection异常", ex);
                return(false);
            }

            return(true);
        }
Пример #17
0
        public void PrivateKeyFileConstructorTest2()
        {
            string         fileName = string.Empty; // TODO: Initialize to an appropriate value
            PrivateKeyFile target   = new PrivateKeyFile(fileName);

            Assert.Inconclusive("TODO: Implement code to verify target");
        }
 public DeployServiceConfiguration(PrivateKeyFile pemKey, string ip, int port, string username)
 {
     PemKey   = pemKey;
     Ip       = ip;
     Port     = port;
     Username = username;
 }
Пример #19
0
 public void DisposeTest()
 {
     Stream privateKey = null; // TODO: Initialize to an appropriate value
     PrivateKeyFile target = new PrivateKeyFile(privateKey); // TODO: Initialize to an appropriate value
     target.Dispose();
     Assert.Inconclusive("A method that does not return a value cannot be verified.");
 }
        /// <summary>
        /// Occurs when the import button is clicked.
        /// </summary>
        /// <param name="sender">The object where the event handler is attached.</param>
        /// <param name="e">The event data.</param>
        private async void importButton_Click(object sender, RoutedEventArgs e)
        {
            FileOpenPicker openPicker = new FileOpenPicker();

            openPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            openPicker.ViewMode         = PickerViewMode.List;
            openPicker.CommitButtonText = "Import";

            // Filter to include a sample subset of file types.
            openPicker.FileTypeFilter.Clear();
            //openPicker.FileTypeFilter.Add(".pfx");
            openPicker.FileTypeFilter.Add(".pem");
            openPicker.FileTypeFilter.Add(".key");
            openPicker.FileTypeFilter.Add(".ssh");

            // Open the file picker.
            var files = await openPicker.PickMultipleFilesAsync();

            // files is null if user cancels the file picker.
            if (files == null || files.Count == 0)
            {
                return;
            }

            var privateKeysDataSource = App.Current.Resources["privateKeysDataSource"] as PrivateKeysDataSource;

            if (privateKeysDataSource == null)
            {
                return;
            }

            foreach (var file in files)
            {
                var buffer = await FileIO.ReadBufferAsync(file);

                using (var stream = new MemoryStream(buffer.ToArray()))
                {
                    PrivateKeyFile.Validate(stream);
                }

                var privateKeysFolder = await PrivateKeysDataSource.GetPrivateKeysFolder();

                var privateKeyFile = await file.CopyAsync(privateKeysFolder, file.Name, NameCollisionOption.GenerateUniqueName);

                var privateKeyData = new PrivateKeyData()
                {
                    FileName = privateKeyFile.Name,
                    Data     = (await FileIO.ReadBufferAsync(privateKeyFile)).ToArray(),
                };

                privateKeysDataSource.PrivateKeys.Remove(PrivateKeysDataSource.GetPrivateKey(privateKeyData.FileName));
                privateKeysDataSource.PrivateKeys.Add(privateKeyData);
            }

            var items = new ObservableCollection <PrivateKeyData>(privateKeysDataSource.PrivateKeys.OrderBy(f => f.FileName));

            this.DefaultViewModel["Items"] = items;
            this.emptyHint.Visibility      = this.itemGridView.Items.Count == 0 ? Visibility.Visible : Visibility.Collapsed;
        }
Пример #21
0
        public void DisposeTest()
        {
            Stream         privateKey = null;                           // TODO: Initialize to an appropriate value
            PrivateKeyFile target     = new PrivateKeyFile(privateKey); // TODO: Initialize to an appropriate value

            target.Dispose();
            Assert.Inconclusive("A method that does not return a value cannot be verified.");
        }
Пример #22
0
 public void ConstructorWithStream()
 {
     using (var stream = GetData("Key.RSA.txt"))
     {
         var privateKeyFile = new PrivateKeyFile(stream);
         Assert.IsNotNull(privateKeyFile.HostKey);
     }
 }
Пример #23
0
 public void DisposeTest()
 {
     using (var privateKeyStream = GetData("Key.RSA.txt"))
     {
         var target = new PrivateKeyFile(privateKeyStream);
         target.Dispose();
     }
 }
Пример #24
0
 public void ConstructorWithStreamAndPassphrase()
 {
     using (var stream = GetData("Key.RSA.Encrypted.Aes.128.CBC.12345.txt"))
     {
         var privateKeyFile = new PrivateKeyFile(stream, "12345");
         Assert.IsNotNull(privateKeyFile.HostKey);
     }
 }
Пример #25
0
        private ConnectionInfo GetConnectionInfo(SSHLogin loginInfo)
        {
            var privateKeyFile = new PrivateKeyFile(loginInfo.PrivateKeyFilePath);

            var connection = new ConnectionInfo(loginInfo.IPOrHostFQDN, loginInfo.User,
                                                new PrivateKeyAuthenticationMethod(loginInfo.User, privateKeyFile));

            return(connection);
        }
Пример #26
0
        public VippsService(VippsSettings settings)
        {
            _settings = settings;

            var privateKeyBytes = Convert.FromBase64String(_settings.SftpPrivateKey);
            var privateKey      = new PrivateKeyFile(new MemoryStream(privateKeyBytes));

            _connectionInfo = new ConnectionInfo("sftp.vipps.no", "test", new PrivateKeyAuthenticationMethod("test", privateKey));
        }
Пример #27
0
        public static void Run()
        {
            var pfFile         = new PrivateKeyFile(@"mykey.pem");
            var connectionInfo = new PrivateKeyConnectionInfo("54.252.90.204", "ubuntu", pfFile);

            CopyScript(connectionInfo);

            //RunRefreshShell(connectionInfo);
        }
Пример #28
0
 private void openFileDialog_FileOk(object sender, CancelEventArgs e)
 {
     //don't check larger files
     if (new FileInfo(openFileDialog.FileName).Length > 4 * 4 * 1024 || !PrivateKeyFile.IsValid(openFileDialog.FileName))
     {
         MessageBox.Show(this,
                         "File doesn't seem to be a valid private key file", Text);
         e.Cancel = true;
     }
 }
Пример #29
0
 /// <summary>
 /// Save a key to the key ring
 /// </summary>
 public static PrivateKey Save(this PrivateKey key)
 {
     if (!Directory.Exists(KeyRingPath))
     {
         Directory.CreateDirectory(KeyRingPath);
     }
     PrivateKeyFile.Save(GetPath(key.Id), key);
     AliasFile.Save(GetPath(AliasFilename), key.Alias);
     return(key);
 }
        private static KeyHostAlgorithm GetKeyHostAlgorithm()
        {
            var executingAssembly = Assembly.GetExecutingAssembly();

            using (var s = executingAssembly.GetManifestResourceStream(string.Format("Renci.SshNet.Tests.Data.{0}", "Key.RSA.txt")))
            {
                var privateKey = new PrivateKeyFile(s);
                return((KeyHostAlgorithm)privateKey.HostKey);
            }
        }
        public void TestPrivateKeyFile()
        {
            const string path = @"C:\Temp\PKFile.dat";

            PrivateKeyFile.Save(path, _key);

            var key = PrivateKeyFile.Load(path);

            Assert.AreEqual(key, _key);
        }
Пример #32
0
        /// <summary>
        /// 파일명 지정해서 upolad
        /// </summary>
        /// <param name="remoteFileName"></param>
        public void UploadFile(string remoteFileName, string localdir)
        {
            string host     = @"13.209.113.71";
            string username = "******";

            string pathRemote = "/ftp/bnk_b/uploads/";

            pathLocalPut = localdir;
            if (!Directory.Exists(pathLocalPut))
            {
                Directory.CreateDirectory(pathLocalPut);
            }


            string pathRemoteFile = Path.Combine(pathRemote, remoteFileName);
            string pathLocalFile  = Path.Combine(pathLocalPut, remoteFileName);


            PrivateKeyFile keyFile  = new PrivateKeyFile(@"./bnk_sftp.pem");
            var            keyFiles = new[] { keyFile };

            var methods = new List <AuthenticationMethod>();

            methods.Add(new PrivateKeyAuthenticationMethod(username, keyFiles));

            ConnectionInfo con = new ConnectionInfo(host, 10021, username, methods.ToArray());

            if (!File.Exists(pathLocalFile))
            {
                Console.WriteLine("File Not Found {0}", pathLocalFile);
                return;
            }

            using (SftpClient sftp = new SftpClient(con))
            {
                try
                {
                    sftp.Connect();


                    Console.WriteLine("Uploading {0}", pathLocalFile);

                    using (Stream fileStream = File.OpenRead(pathLocalFile))
                    {
                        sftp.UploadFile(fileStream, pathRemoteFile);
                    }

                    sftp.Disconnect();
                }
                catch (Exception er)
                {
                    Console.WriteLine("An exception has been caught " + er.ToString());
                }
            }
        }
 public void Test_PrivateKeyFile_StreamIsNull()
 {
     Stream stream = null;
     var keyFile = new PrivateKeyFile(stream);
 }
Пример #34
0
        public void ConstructorWithFileNameAndPassPhraseShouldBeAbleToReadFileThatIsSharedForReadAccess()
        {
            using (var stream = GetData("Key.RSA.Encrypted.Aes.128.CBC.12345.txt"))
            {
                SaveStreamToFile(stream, _temporaryFile);
            }

            using (var fs = File.Open(_temporaryFile, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                var privateKeyFile = new PrivateKeyFile(_temporaryFile, "12345");
                Assert.IsNotNull(privateKeyFile.HostKey);

                fs.Close();
            }
        }
Пример #35
0
 public void ConstructorWithStream()
 {
     using (var stream = GetData("Key.RSA.txt"))
     {
         var privateKeyFile = new PrivateKeyFile(stream);
         Assert.IsNotNull(privateKeyFile.HostKey);
     }
 }
Пример #36
0
        public void ConstructorWithFileName()
        {
            using (var stream = GetData("Key.RSA.Encrypted.Aes.128.CBC.12345.txt"))
            {
                SaveStreamToFile(stream, _temporaryFile);
            }

            var privateKeyFile = new PrivateKeyFile(_temporaryFile, "12345");
            Assert.IsNotNull(privateKeyFile.HostKey);
        }
Пример #37
0
 public void ConstructorWithStreamAndPassphrase()
 {
     using (var stream = GetData("Key.RSA.Encrypted.Aes.128.CBC.12345.txt"))
     {
         var privateKeyFile = new PrivateKeyFile(stream, "12345");
         Assert.IsNotNull(privateKeyFile.HostKey);
     }
 }
Пример #38
0
 public void DisposeTest()
 {
     using (var privateKeyStream = GetData("Key.RSA.txt"))
     {
         var target = new PrivateKeyFile(privateKeyStream);
         target.Dispose();
     }
 }
Пример #39
0
 public void PrivateKeyFileConstructorTest3()
 {
     Stream privateKey = null; // TODO: Initialize to an appropriate value
     PrivateKeyFile target = new PrivateKeyFile(privateKey);
     Assert.Inconclusive("TODO: Implement code to verify target");
 }
 public void Test_PrivateKeyFile_EmptyFileName()
 {
     string fileName = string.Empty;
     var keyFile = new PrivateKeyFile(fileName);
 }