Provides connection information when password authentication method is used
Inheritance: ConnectionInfo, IDisposable
 public bool UploadFile(string filePath)
 {
     ConnectionInfo connectionInfo = new PasswordConnectionInfo(_address, ConstFields.SFTP_PORT, _username, _password);
     try
     {
         using (var sftp = new SftpClient(connectionInfo))
         {
             sftp.Connect();
             using (var file = File.OpenRead(filePath))
             {
                 if (!sftp.Exists(ConstFields.TEMP_PRINT_DIRECTORY))
                 {
                     sftp.CreateDirectory(ConstFields.TEMP_PRINT_DIRECTORY);
                 }
                 sftp.ChangeDirectory(ConstFields.TEMP_PRINT_DIRECTORY);
                 string filename = Path.GetFileName(filePath);
                 sftp.UploadFile(file, filename);
             }
             sftp.Disconnect();
         }
     }
     catch (Renci.SshNet.Common.SshConnectionException)
     {
         Console.WriteLine("Cannot connect to the server.");
         return false;
     }
     catch (System.Net.Sockets.SocketException)
     {
         Console.WriteLine("Unable to establish the socket.");
         return false;
     }
     catch (Renci.SshNet.Common.SshAuthenticationException)
     {
         Console.WriteLine("Authentication of SSH session failed.");
         return false;
     }
     return true;
 }
Exemplo n.º 2
1
        private void LocalVmToolStripMenuItemClick(object sender, EventArgs e)
        {
            var connectionInfo = new PasswordConnectionInfo(host, 22, username, password);
            connectionInfo.AuthenticationBanner += ConnectionInfoAuthenticationBanner;
            connectionInfo.PasswordExpired += ConnectionInfoPasswordExpired;
            sshClient = new SshClient(connectionInfo);
            sshClient.ErrorOccurred += SshClientErrorOccurred;
            Log(string.Format("Connecting to {0}:{1} as {2}", connectionInfo.Host, connectionInfo.Port, connectionInfo.Username));

            try
            {
                sshClient.Connect();
                var tunnel = sshClient.AddForwardedPort<ForwardedPortLocal>("localhost", 20080, "www.google.com", 80);
                tunnel.Start();

            }
            catch (Exception ex)
            {
                Log(ex.ToString());
            }
            finally
            {
                sshClient.Dispose();
            }
            Log("Connected");
            sshClient.ForwardedPorts.ToList().ForEach(p => Log(string.Format("SSH tunnel: {0}:{1} --> {2}:{3}", p.BoundHost, p.BoundPort, p.Host, p.Port) ));
        }
Exemplo n.º 3
0
 public CrackProcess()
 {
     xml = Brake.Container.getContainer();
     InitializeComponent();
     queue = new Queue<IPAInfo>();
     connectionInfo = new PasswordConnectionInfo(xml.Config.host, xml.Config.port, "root", xml.Config.Password);
 }
        public void Execute(IJobExecutionContext context)
        {
            try
            {
                using (new UnitOfWork())
                {
                    var dataMap = context.JobDetail.JobDataMap;
                    var ftphost = dataMap.GetString("FtpHost");
                    var userId = dataMap.GetString("UserId");
                    var password = dataMap.GetString("Password");

                    if (!(string.IsNullOrEmpty(ftphost)
                        && string.IsNullOrEmpty(userId) && string.IsNullOrEmpty(password)))
                    {
                        var connectionInfo = new PasswordConnectionInfo(ftphost, userId, password);

                        // {
                            // Timeout = TimeSpan.FromSeconds(60)
                       // };
                        var achFilesToUpload = this.Manager.AchFilesToUpload();
                        this.Uploadfiles(connectionInfo, achFilesToUpload);
                    }
                }
            }
            catch (Exception ex)
            {
                throw new JobExecutionException(ex);
            }
        }
Exemplo n.º 5
0
        public void beginCracking()
        {
            log("beginning cracking process..");
            var connectionInfo = new PasswordConnectionInfo (xml.Config.host, xml.Config.port, "root", xml.Config.Password);
            using (var sftp = new SftpClient(connectionInfo))
            {
                using (var ssh = new SshClient(connectionInfo))
                {
                    PercentStatus("Establishing SSH connection", 5);
                    ssh.Connect();
                    PercentStatus("Establishing SFTP connection", 10);
                    sftp.Connect();

                    log("Cracking " + ipaInfo.AppName);
                    PercentStatus("Preparing IPA", 25);
                    String ipalocation = AppHelper.extractIPA(ipaInfo);
                    using (var file = File.OpenRead(ipalocation))
                    {
                        log("Uploading IPA to device..");
                        PercentStatus("Uploading IPA", 40);
                        sftp.UploadFile(file, "Upload.ipa");

                    }
                    log("Cracking! (This might take a while)");
                    PercentStatus("Cracking", 50);
                    String binaryLocation = ipaInfo.BinaryLocation.Replace("Payload/", "");
                    String TempDownloadBinary = Path.Combine(AppHelper.GetTemporaryDirectory(), "crackedBinary");
                    var crack = ssh.RunCommand("Clutch -i 'Upload.ipa' " + binaryLocation + " /tmp/crackedBinary");
                    log("Clutch -i 'Upload.ipa' " + binaryLocation + " /tmp/crackedBinary");
                    log("cracking output: " + crack.Result);

                    using (var file = File.OpenWrite(TempDownloadBinary))
                    {
                        log("Downloading cracked binary..");
                        PercentStatus("Downloading cracked binary", 80);
                        try
                        {
                            sftp.DownloadFile("/tmp/crackedBinary", file);
                        }
                        catch (SftpPathNotFoundException e)
                        {
                            log("Could not find file, help!!!!!");
                            return;
                        }
                    }

                    PercentStatus("Repacking IPA", 90);
                    String repack = AppHelper.repack(ipaInfo, TempDownloadBinary);
                    PercentStatus("Done!", 100);

                    log("Cracking completed, file at " + repack);
                }
            }
        }
Exemplo n.º 6
0
 public static bool TestCredentials(PasswordConnectionInfo connectionInfo)
 {
     bool connected = false;
     using (SshClient ssh = new SshClient(connectionInfo))
     {
         try
         {
             ssh.Connect();
             connected = ssh.IsConnected;
         }
         catch (SshAuthenticationException) { connected = false; }
     }
     return connected;
 }
Exemplo n.º 7
0
        public void sftp_upload(string filename)
        {
            // 폴더가 없을경우 no such file
            // 폴더 있는데 업로드 할경우 권한 에러

            var connectionInfo_pw = new Renci.SshNet.PasswordConnectionInfo("l.bsks.ac.kr", "p201606010", "pp201606010");
            var client            = new SftpClient(connectionInfo_pw);

            client.Connect();
            string serverPath = string.Format(@"/home/p201606010/public_html/hero_php/img/" + db_name + "/" + filename);
            Stream stream     = new MemoryStream(File.ReadAllBytes(filename));

            client.UploadFile(stream, serverPath);
            client.Disconnect();
        }
Exemplo n.º 8
0
        private void Button_Click_3(object sender, RoutedEventArgs e)
        {
            Instellingen inst = new Instellingen();
            ConnectionInfo connectionInfo = new PasswordConnectionInfo(inst.ip, "pi", "idpgroep5");
             ssh = new SshClient(connectionInfo);

                ssh.Connect();
                var cmd = ssh.CreateCommand("./startSpinOS.sh");   //  very long list
                var asynch = cmd.BeginExecute();
                System.Threading.Thread.Sleep(20000);
                ssh.Disconnect();

            /*SshStream ssh = new SshStream("192.168.10.1", "pi", "idpgroep5");
            //Set the end of response matcher character
            ssh.Prompt = "#";
            //Remove terminal emulation characters
            ssh.RemoveTerminalEmulationCharacters = true;
            //Writing to the SSH channel
            ssh.Write("./startSpinOS.sh");*/
        }
Exemplo n.º 9
0
        private void DataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            int asd = int.Parse(e.RowIndex.ToString());

            if (asd < 0)
            {
                return;
            }
            numberbox.Text = dataGridView1.Rows[e.RowIndex].Cells[0].FormattedValue.ToString();
            namebox.Text   = dataGridView1.Rows[e.RowIndex].Cells[1].FormattedValue.ToString();
            birthbox.Text  = dataGridView1.Rows[e.RowIndex].Cells[2].FormattedValue.ToString();
            if (sexbox.Text == "1")
            {
                man.Checked = true;
            }
            else
            {
                girl.Checked = true;
            }
            sexbox.Text   = dataGridView1.Rows[e.RowIndex].Cells[3].FormattedValue.ToString();
            phonebox.Text = dataGridView1.Rows[e.RowIndex].Cells[4].FormattedValue.ToString();
            mailbox.Text  = dataGridView1.Rows[e.RowIndex].Cells[5].FormattedValue.ToString();
            addrbox.Text  = dataGridView1.Rows[e.RowIndex].Cells[6].FormattedValue.ToString();
            pickbox.Text  = dataGridView1.Rows[e.RowIndex].Cells[7].FormattedValue.ToString();

            // ftp 주소로 불러와서 로컬에 다운로드 후 불러오는건데
            // 비효율적인거 같음 바로 불러올수는 없나? sftp에서

            var connectionInfo_pw = new Renci.SshNet.PasswordConnectionInfo("l.bsks.ac.kr", "p201606010", "pp201606010");
            var client            = new SftpClient(connectionInfo_pw);

            client.Connect();
            string serverPath = string.Format(@"/home/p201606010/public_html/hero_php/img/" + db_name + "/" + pickbox.Text);

            using (var file = File.OpenWrite(pickbox.Text))
            {
                client.DownloadFile(serverPath, file);
            }

            pictureBox1.Image = System.Drawing.Image.FromFile(pickbox.Text);
        }
Exemplo n.º 10
0
 public bool Connect()
 {
     System.Diagnostics.Debug.WriteLineIf(DEBUG, "ssh: connecting ....");
     try
     {
         ConnectionInfo info = new PasswordConnectionInfo(_host,_port, _user, _pw);
         _client = new SshClient(info);
         _client.ErrorOccurred += SSHError;
         _client.Connect();
         _stream = _client.CreateShellStream("xterm", 80, 24, 800, 600, 1024);
         System.Diagnostics.Debug.WriteLineIf(DEBUG, "ssh: connected");
         return true;
     }
     catch (System.Exception e)
     {
         System.Diagnostics.Debug.WriteLineIf(DEBUG, "ssh: error while connecting:");
         System.Diagnostics.Debug.WriteLine(e.Message);
         System.Diagnostics.Debug.WriteLine(e.InnerException);
         return false;
     }
 }
Exemplo n.º 11
0
        /// <summary>
        /// Establishes the connection to the server, using the specified <paramref name="terminal"/> for connection initialization (authentication, etc.).
        /// </summary>
        /// <param name="terminal">The terminal to use for connection initialization.</param>
        /// <returns>A value indicating whether the connection was successfully established.</returns>
        /// <exception cref="ObjectDisposedException">The connection object is already disposed.</exception>
        /// <exception cref="InvalidOperationException">The connection object is currently connected.</exception>
        public async Task<bool> ConnectAsync(IConnectionInitializingTerminal terminal)
        {
            this.CheckDisposed();
            this.MustBeConnected(false);

            Lazy<string> username = new Lazy<string>(() =>
            {
                if (string.IsNullOrEmpty(this.connectionData.Username))
                {
                    return terminal.ReadLineAsync("Username: "******"Username: "******"Password: "******"Password expired for user " + e.Username);
                                do
                                {
                                    var readNewPassword1Task = terminal.ReadLineAsync("New password: "******"Repeat new password: "******"Performing keyboard-interactive authentication.");
                                }

                                if (!string.IsNullOrEmpty(e.Instruction))
                                {
                                    terminal.WriteLine(e.Instruction);
                                }

                                foreach (var prompt in e.Prompts)
                                {
                                    var readLineTask = terminal.ReadLineAsync(prompt.Request, echo: prompt.IsEchoed);
                                    readLineTask.Wait();
                                    prompt.Response = readLineTask.Result;
                                }
                            };
                            connectionInfo = keyboardInteractiveConnectionInfo;
                            break;
                        case Model.AuthenticationType.PrivateKey:
                            if (this.privateKeyData == null)
                            {
                                throw new Exception("Private Key '" + connectionData.PrivateKeyName + "' not found. Please correct the authentication details of the connection.");
                            }

                            PrivateKeyFile privateKey;

                            try
                            {
                                using (var privateKeyStream = new MemoryStream(privateKeyData.Data))
                                {
                                    privateKey = new PrivateKeyFile(privateKeyStream);
                                }
                            }
                            catch (SshPassPhraseNullOrEmptyException)
                            {
                                privateKey = null;
                            }

                            // In the normal PrivateKey authentication there is only a connection-local PrivateKeyAgent.
                            var localPprivateKeyAgent = new Lazy<PrivateKeyAgent>(() =>
                            {
                                terminal.WriteLine("Performing authentication with Private Key '" + connectionData.PrivateKeyName + "'.");

                                if (privateKey == null)
                                {
                                    string privateKeyPassword = terminal.ReadLineAsync("Private Key password: "******"Wrong Private Key password, please try again.", ex);
                                        }
                                    }
                                }

                                var pka = new PrivateKeyAgent();
                                pka.AddSsh2(privateKey.HostKey, connectionData.PrivateKeyName);
                                return pka;
                            });

                            var privateKeyConnectionInfo = new PrivateKeyConnectionInfo(this.connectionData.Host, this.connectionData.Port, username, localPprivateKeyAgent);
                            connectionInfo = privateKeyConnectionInfo;

                            break;
                        case AuthenticationType.PrivateKeyAgent:
                            if (PrivateKeyAgentManager.PrivateKeyAgent.ListSsh2().Count == 0)
                            {
                                throw new SshAuthenticationException("The private key agent doesn't contain any private keys.");
                            }

                            var globalPrivateKeyAgent = new Lazy<PrivateKeyAgent>(() =>
                            {
                                var pka = PrivateKeyAgentManager.PrivateKeyAgent;
                                terminal.WriteLine("Performing private key agent authentication.");
                                return pka;
                            });

                            var privateKeyAgentConnectionInfo = new PrivateKeyConnectionInfo(this.connectionData.Host, this.connectionData.Port, username, globalPrivateKeyAgent);
                            connectionInfo = privateKeyAgentConnectionInfo;
                            if (connectionData.PrivateKeyAgentForwarding == true)
                            {
                                forwardedPrivateKeyAgent = globalPrivateKeyAgent;
                                terminal.WriteLine("Agent forwarding is enabled.");
                            }

                            break;
                        default:
                            throw new NotImplementedException("Authentication method '" + this.connectionData.Authentication + "' not implemented.");
                    }

                    connectionInfo.AuthenticationBanner += (sender, e) =>
                    {
                        terminal.WriteLine(e.BannerMessage.Replace("\n", "\r\n"));
                    };

                    this.client = new SshClient(connectionInfo);
                    this.client.HostKeyReceived += (s, e) =>
                    {
                        string fingerprint = string.Join(":", e.FingerPrint.Select(b => b.ToString("x2")));

                        bool trustHostKey = true;
                        bool storeHostKey = false;

                        string newHostKey = string.Join(null, e.HostKey.Select(b => b.ToString("x2")));
                        if (oldHostKey == null)
                        {
                            terminal.WriteLine("Remote Terminal has not yet cached a host key for this server.");
                            terminal.WriteLine("Host key's fingerprint: " + fingerprint);
                            terminal.WriteLine("Please make sure the fingerprint matches the server's actual host key.");
                            trustHostKey = QueryYesNo(terminal, "Do you want to continue connecting to the host?");
                            if (trustHostKey)
                            {
                                storeHostKey = QueryYesNo(terminal, "Do you want to store this host key in the cache?");
                            }
                        }
                        else if (oldHostKey != newHostKey)
                        {
                            terminal.WriteLine("POSSIBLE SECURITY BREACH DETECTED!");
                            terminal.WriteLine("Remote Terminal has cached another host key for this server.");
                            terminal.WriteLine("This could mean one of two things:");
                            terminal.WriteLine(" * the server's host key was changed by an administrator");
                            terminal.WriteLine(" * another computer is trying to intercept your connection");
                            terminal.WriteLine("Host key's new fingerprint: " + fingerprint);
                            trustHostKey = QueryYesNo(terminal, "Do you want to continue connecting to the host?");
                            if (trustHostKey)
                            {
                                storeHostKey = QueryYesNo(terminal, "Do you want to update the cache with the new host key?");
                            }
                        }

                        e.CanTrust = trustHostKey;
                        if (trustHostKey)
                        {
                            oldHostKey = newHostKey;
                        }

                        if (storeHostKey)
                        {
                            HostKeysDataSource.AddOrUpdate(this.connectionData.Host, this.connectionData.Port, newHostKey);
                        }
                    };

                    this.client.ConnectionInfo.Timeout = new TimeSpan(0, 15, 0);
                    await Task.Run(() => { this.client.Connect(); });
                    this.client.ConnectionInfo.Timeout = new TimeSpan(0, 1, 0);

                    var terminalModes = new Dictionary<TerminalModes, uint>();
                    terminalModes[TerminalModes.TTY_OP_ISPEED] = 0x00009600;
                    terminalModes[TerminalModes.TTY_OP_OSPEED] = 0x00009600;
                    this.stream = this.client.CreateShellStream(terminal.TerminalName, (uint)terminal.Columns, (uint)terminal.Rows, 0, 0, 1024, forwardedPrivateKeyAgent.Value, terminalModes.ToArray());

                    this.reader = new StreamReader(this.stream);
                    this.writer = new StreamWriter(this.stream);
                    this.writer.AutoFlush = true;
                    return true;
                }
                catch (SshConnectionException ex)
                {
                    terminal.WriteLine(ex.Message);
                    retry = false;
                }
                catch (SshAuthenticationException ex)
                {
                    terminal.WriteLine(ex.Message);
                    if (connectionData.Authentication == AuthenticationType.PrivateKeyAgent)
                    {
                        terminal.WriteLine("Please load the necessary private key(s) into the private key agent.");
                        retry = false;
                    }
                    else
                    {
                        retry = true;
                    }
                }
                catch (Exception ex)
                {
                    terminal.WriteLine(ex.Message);
                    retry = false;
                }

                if (!retry || numRetries++ > 5)
                {
                    return false;
                }
            }
            while (true);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Connect to the remote servers, with the details from Profile
        /// </summary>
        /// <param name="reconnecting">True if this is an attempt to re-establish a closed connection</param>
        public void Connect(bool reconnecting = false)
        {
            Notifications.ChangeTrayText(reconnecting ? MessageType.Reconnecting : MessageType.Connecting);
            Log.Write(l.Debug, "{0} client...", reconnecting ? "Reconnecting" : "Connecting");

            if (FTP)
            {
                _ftpc = new FtpClient { Host = controller.Account.Host, Port = controller.Account.Port };

                // Add accepted certificates
                _ftpc.ClientCertificates.AddRange(Certificates);

                if (controller.Account.Protocol == FtpProtocol.FTPS)
                {
                    _ftpc.ValidateCertificate += (sender, x) =>
                    {
                        var fingerPrint = new X509Certificate2(x.Certificate).Thumbprint;

                        if (_ftpc.ClientCertificates.Count <= 0 && x.PolicyErrors != SslPolicyErrors.None)
                        {
                            Certificates.Add(x.Certificate);
                            x.Accept = false;
                            return;
                        }

                        // if ValidateCertificate handler isn't set, accept the certificate and move on
                        if (ValidateCertificate == null || Settings.TrustedCertificates.Contains(fingerPrint))
                        {
                            Log.Write(l.Client, "Trusted: {0}", fingerPrint);
                            x.Accept = true;
                            return;
                        }

                        var e = new ValidateCertificateEventArgs
                        {
                            Fingerprint = fingerPrint,
                            SerialNumber = x.Certificate.GetSerialNumberString(),
                            Algorithm = x.Certificate.GetKeyAlgorithmParametersString(),
                            ValidFrom = x.Certificate.GetEffectiveDateString(),
                            ValidTo = x.Certificate.GetExpirationDateString(),
                            Issuer = x.Certificate.Issuer
                        };
                        // Prompt user to validate
                        ValidateCertificate(null, e);
                        x.Accept = e.IsTrusted;
                    };

                    // Change Security Protocol
                    if (controller.Account.FtpsMethod == FtpsMethod.Explicit)
                        _ftpc.EncryptionMode = FtpEncryptionMode.Explicit;
                    else if (controller.Account.FtpsMethod == FtpsMethod.Implicit)
                        _ftpc.EncryptionMode = FtpEncryptionMode.Implicit;
                }

                _ftpc.Credentials = new NetworkCredential(controller.Account.Username, controller.Account.Password);

                try
                {
                    _ftpc.Connect();
                }
                catch (Exception exc)
                {
                    // Since the ClientCertificates are added when accepted in ValidateCertificate, the first
                    // attempt to connect will fail with an AuthenticationException. If this is the case, a
                    // re-connect is attempted, this time with the certificates properly set.
                    // This is a workaround to avoid storing Certificate files locally...
                    if (exc is System.Security.Authentication.AuthenticationException
                        && _ftpc.ClientCertificates.Count <= 0)
                        Connect();
                    else
                        throw;
                }
            }
            else // SFTP
            {
                ConnectionInfo connectionInfo;
                if (controller.isPrivateKeyValid)
                    connectionInfo = new PrivateKeyConnectionInfo(controller.Account.Host, controller.Account.Port, controller.Account.Username, new PrivateKeyFile(controller.Account.PrivateKeyFile, controller.Account.Password));
                else
                    connectionInfo = new PasswordConnectionInfo(controller.Account.Host, controller.Account.Port, controller.Account.Username, controller.Account.Password);

                _sftpc = new SftpClient(connectionInfo);
                _sftpc.ConnectionInfo.AuthenticationBanner += (o, x) => Log.Write(l.Warning, x.BannerMessage);

                _sftpc.HostKeyReceived += (o, x) =>
                {
                    var fingerPrint = x.FingerPrint.GetCertificateData();

                    // if ValidateCertificate handler isn't set, accept the certificate and move on
                    if (ValidateCertificate == null || Settings.TrustedCertificates.Contains(fingerPrint))
                    {
                        Log.Write(l.Client, "Trusted: {0}", fingerPrint);
                        x.CanTrust = true;
                        return;
                    }

                    var e = new ValidateCertificateEventArgs
                    {
                        Fingerprint = fingerPrint,
                        Key = x.HostKeyName,
                        KeySize = x.KeyLength.ToString()
                    };
                    // Prompt user to validate
                    ValidateCertificate(null, e);
                    x.CanTrust = e.IsTrusted;
                };

                _sftpc.Connect();

                _sftpc.ErrorOccurred += (o, e) =>
                {
                    if (!isConnected) Notifications.ChangeTrayText(MessageType.Nothing);
                    if (ConnectionClosed != null) ConnectionClosed(null, new ConnectionClosedEventArgs { Text = e.Exception.Message });

                    if (e.Exception is Renci.SshNet.Common.SftpPermissionDeniedException)
                        Log.Write(l.Warning, "Permission denied error occured");
                    if (e.Exception is Renci.SshNet.Common.SshConnectionException)
                        Reconnect();
                };
            }

            controller.HomePath = WorkingDirectory;

            if (isConnected)
                if (!string.IsNullOrWhiteSpace(controller.Paths.Remote) && !controller.Paths.Remote.Equals("/"))
                    WorkingDirectory = controller.Paths.Remote;

            Log.Write(l.Debug, "Client connected sucessfully");
            Notifications.ChangeTrayText(MessageType.Ready);

            if (Settings.IsDebugMode)
                LogServerInfo();

            // Periodically send NOOP (KeepAlive) to server if a non-zero interval is set
            SetKeepAlive();
        }
Exemplo n.º 13
0
        public static void Main(string[] args)
        {
            Console.WriteLine ("Welcome to Brake!");
            Console.WriteLine ("Current version: Brake-0.0.4");
            Container xml = Container.getContainer ();
            if (xml.Config.host == null) {
                xml.Config = new Configuration ();
                Console.Write ("IP address of your iDevice: ");
                xml.Config.host = Console.ReadLine ();
                Console.Write ("SSH Port: ");
                string portString = "22";
                portString = Console.ReadLine ();
                int.TryParse (portString, out xml.Config.port);
                Console.Write ("Root Password: "******"== Is this correct? Y/N ==");
                Console.WriteLine ("Host: " + xml.Config.host);
                Console.WriteLine ("Root Password: "******"y") {
                    return;
                }
                xml.SaveXML ();
            }
            AppHelper appHelper = new AppHelper ();

            //COMING SOON PORT VERIFICATION
            //var ping = new Ping();
            //var reply = ping.Send(host); // 1 minute time out (in ms)
            //if (reply.Status == IPStatus.Success)
            //{
            //    Console.WriteLine("IP Address Valid");
            //}
            //else
            //{
            //    Console.WriteLine("Unable to SSH to IP");
            //}

            Console.WriteLine ("Establishing SSH connection");
            var connectionInfo = new PasswordConnectionInfo (xml.Config.host, xml.Config.port, "root", xml.Config.Password);
            using (var sftp = new SftpClient(connectionInfo)) {
                using (var ssh = new SshClient(connectionInfo)) {
                    ssh.Connect ();
                    sftp.Connect ();
                    var whoami = ssh.RunCommand ("Clutch -b");
                    long b;
                    long.TryParse (whoami.Result, out b);
                    /*if (b < 13104)
                    {
                        Console.WriteLine("You're using an old version of Clutch, please update to 1.3.1!");
                        //COMING SOON download Clutch to device for you
                        //Console.WriteLine("Would you like to download the latest version to your iDevice?");
                        //string dlyn = Console.ReadLine();
                        //if (dlyn == "y")
                        //{
                            //ssh.RunCommand("apt-get install wget");
                            //ssh.RunCommand("wget --no-check-certificate -O Clutch https://github.com/CrackEngine/Clutch/releases/download/1.3.1/Clutch");
                            //ssh.RunCommand("mv Clutch /usr/bin/Clutch");
                            //ssh.RunCommand("chown root:wheel /usr/bin/Clutch");
                            //ssh.RunCommand("chmod 755 /usr/bin/Clutch");
                        //}
                        //else if (dlyn == "Y")
                        //{
                            //ssh.RunCommand("apt-get install wget");
                            //ssh.RunCommand("wget --no-check-certificate -O Clutch https://github.com/CrackEngine/Clutch/releases/download/1.3.1/Clutch");
                            //ssh.RunCommand("mv Clutch /usr/bin/Clutch");
                            //ssh.RunCommand("chown root:wheel /usr/bin/Clutch");
                            //ssh.RunCommand("chmod 755 /usr/bin/Clutch");
                        //}
                        //else
                        //{
                            return;
                        //}
                    }*/
                    Console.WriteLine ("reply: " + whoami.Result);

                    //return;
                    string location;
                    switch (RunningPlatform ()) {
                    case Platform.Mac:
                        {
                            location = Environment.GetEnvironmentVariable ("HOME") + "/Music/iTunes/iTunes Media/Mobile Applications";
                            break;
                        }
                    case Platform.Windows:
                        {
                            string location2 = Environment.GetFolderPath (Environment.SpecialFolder.MyMusic);
                            location = Path.Combine (location2, "iTunes\\iTunes Media\\Mobile Applications");
                            break;
                        }
                    default:
                        {
                            Console.WriteLine ("Unknown operating system!");
                            return;
                        }
                    }
                    appHelper.getIPAs (location);
                    int i = 1;
                    int a;
                    while (true) {
                        foreach (IPAInfo ipaInfo in xml.IPAItems) {
                            Console.WriteLine (i + ". >> " + ipaInfo.AppName + " (" + ipaInfo.AppVersion + ")");
                            i++;
                        }
                        Console.WriteLine ("");
                        Console.Write ("Please enter your selection:  ");
                        if (int.TryParse (Console.ReadLine (), out a)) {
                            try {
                                IPAInfo ipaInfo = xml.IPAItems [a - 1];
                                Console.WriteLine ("Cracking " + ipaInfo.AppName);
                                String ipalocation = appHelper.extractIPA (ipaInfo);

                                using (var file = File.OpenRead(ipalocation)) {
                                    Console.WriteLine ("Uploading IPA to device..");
                                    sftp.UploadFile (file, "Upload.ipa");

                                }

                                Console.WriteLine ("Cracking! (This might take a while)");
                                String binaryLocation = ipaInfo.BinaryLocation.Replace ("Payload/", "");
                                String TempDownloadBinary = Path.Combine (AppHelper.GetTemporaryDirectory (), "crackedBinary");
                                var crack = ssh.RunCommand ("Clutch -i 'Upload.ipa' " + binaryLocation + " /tmp/crackedBinary");
                                Console.WriteLine ("Clutch -i 'Upload.ipa' " + binaryLocation + " /tmp/crackedBinary");
                                Console.WriteLine ("cracking output: " + crack.Result);

                                using (var file = File.OpenWrite(TempDownloadBinary)) {
                                    Console.WriteLine ("Downloading cracked binary..");
                                    sftp.DownloadFile ("/tmp/crackedBinary", file);
                                }

                                String repack = appHelper.repack (ipaInfo, TempDownloadBinary);
                                Console.WriteLine ("Cracking completed, file at " + repack);
                            } catch (IndexOutOfRangeException) {
                                Console.WriteLine ("Invalid input, out of range");
                                return;
                            }
                        } else {
                            Console.WriteLine ("Invalid input");
                            return;
                        }

                        AppHelper.DeleteDirectory (AppHelper.GetTemporaryDirectory ());
                        sftp.Disconnect ();
                    }
                }
            }
        }
Exemplo n.º 14
0
        private string MikrotikExportCompact(string MikrotikIP, int MikrotikSSHPort, string MikrotikUser, string MikrotikPassword)
        {
            ConnectionInfo sLogin = new PasswordConnectionInfo(MikrotikIP, MikrotikSSHPort, MikrotikUser, MikrotikPassword);
            SshClient sClient = new SshClient(sLogin);
            sClient.Connect();

            SshCommand appStatCmd = sClient.CreateCommand("export compact");
            appStatCmd.Execute();

            sClient.Disconnect();
            sClient.Dispose();

            return appStatCmd.Result;
        }
        public void CreateSSHClient()
        {
            if (String.IsNullOrEmpty(Ssh.HostName) || String.IsNullOrEmpty(Ssh.UserName) || String.IsNullOrEmpty(Ssh.Password))
                return;

            if (Networking.IP.checkValidIP(Ssh.HostName) == false) { throw new Exception(Ssh.HostName + "is not a valid IP address"); }

            PasswordConnectionInfo cinfo = new PasswordConnectionInfo(Ssh.HostName, Ssh.Port, Ssh.UserName, Ssh.Password);
            Ssh.ClientSSH = new SshClient(cinfo);
        }
Exemplo n.º 16
0
        /// <summary>
        /// An event handler called when connecting to the SSH server.
        /// </summary>
        /// <param name="sender">The sender object.</param>
        /// <param name="e">The event arguments.</param>
        private void OnConnect(object sender, EventArgs e)
        {
            // If the username is empty, show a message and return.
            if (string.IsNullOrWhiteSpace(this.textBoxUsername.Text))
            {
                MessageBox.Show("The user name cannot be empty.", "Cannot Connect", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            // The connection info.
            ConnectionInfo connectionInfo = null;

            try
            {
                // Create a new connection info.
                if (this.radioPasswordAuthentication.Checked)
                {
                    // Create a password connection info.
                    connectionInfo = new PasswordConnectionInfo(this.textBoxServer.Text, this.textBoxUsername.Text, this.secureTextBoxPassword.SecureText.ConvertToUnsecureString());
                }
                else if (this.radioKeyAuthentication.Checked)
                {
                    // If the private key is null, show a message and return.
                    if (null == this.sshKey)
                    {
                        MessageBox.Show("The key cannot be empty for the selected authentication method.", "Cannot Connect", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    // Create a memory stream with the key data.
                    using (MemoryStream memoryStream = new MemoryStream(this.sshKey))
                    {
                        // Create the private key file.
                        using (PrivateKeyFile keyFile = new PrivateKeyFile(memoryStream))
                        {
                            // Create a key connection info.
                            connectionInfo = new PrivateKeyConnectionInfo(this.textBoxServer.Text, this.textBoxUsername.Text, keyFile);
                        }
                    }
                }
                else
                {
                    // If no authentication type is selected, do nothing.
                    MessageBox.Show("You must select a method of authentication.", "Cannot Connect", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }
            catch (Exception exception)
            {
                // Show an error dialog if an exception is thrown.
                MessageBox.Show("Cannot connect to the SSH server. {0}".FormatWith(exception.Message), "Cannot Connect", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            try
            {
                // Connect to the SSH server.
                this.Connect(connectionInfo);
            }
            catch (SshException exception)
            {
                // Show an error dialog if an exception is thrown.
                MessageBox.Show("Cannot connect to the SSH server. {0}".FormatWith(exception.Message), "Cannot Connect", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
        }
Exemplo n.º 17
0
        /// <summary>
        /// Connect to the remote servers, with the details from Profile
        /// </summary>
        /// <param name="reconnecting">True if this is an attempt to re-establish a closed connection</param>
        public void Connect(bool reconnecting = false)
        {
            Notifications.ChangeTrayText(reconnecting ? MessageType.Reconnecting : MessageType.Connecting);
            Log.Write(l.Debug, "{0} client...", reconnecting ? "Reconnecting" : "Connecting");

            if (FTP)
            {
                _ftpc = new FtpClient(controller.Account.Host, controller.Account.Port);
                _ftpc.ConnectionClosed += (o, e) =>
                {
                    Notifications.ChangeTrayText(MessageType.Nothing);
                    if (ConnectionClosed != null) ConnectionClosed(null, new ConnectionClosedEventArgs { Text = _ftpc.LastResponse.Text });
                    Reconnect();
                };

                if (controller.Account.Protocol == FtpProtocol.FTPS)
                {
                    _ftpc.ValidateServerCertificate += (sender, x) =>
                    {
                        // if ValidateCertificate handler isn't set, accept the certificate and move on
                        if (ValidateCertificate == null || Settings.TrustedCertificates.Contains(x.Certificate.Thumbprint))
                        {
                            Log.Write(l.Client, "Trusted: {0}", x.Certificate.Thumbprint);
                            x.IsCertificateValid = true;
                            return;
                        }

                        var e = new ValidateCertificateEventArgs
                        {
                            Fingerprint = x.Certificate.Thumbprint,
                            SerialNumber = x.Certificate.SerialNumber,
                            Algorithm = x.Certificate.SignatureAlgorithm.FriendlyName,
                            ValidFrom = x.Certificate.NotBefore.ToString("MM/dd/yy"),
                            ValidTo = x.Certificate.NotAfter.ToString("MM/dd/yy"),
                            Issuer = x.Certificate.IssuerName.Name
                        };

                        ValidateCertificate(null, e);
                        x.IsCertificateValid = e.IsTrusted;
                    };

                    // Change Security Protocol
                    if (controller.Account.FtpsMethod == FtpsMethod.Explicit)
                        _ftpc.SecurityProtocol = FtpSecurityProtocol.Tls1OrSsl3Explicit;
                    else if (controller.Account.FtpsMethod == FtpsMethod.Implicit)
                        _ftpc.SecurityProtocol = FtpSecurityProtocol.Tls1OrSsl3Implicit;
                }

                try
                {
                    _ftpc.Open(controller.Account.Username, controller.Account.Password);
                }
                catch (Exception)
                {
                    if (controller.Account.FtpsMethod == FtpsMethod.None)
                        throw;
                    bool connected = false;
                    // Try connecting with the other available Security Protocols
                    foreach (FtpSecurityProtocol p in Enum.GetValues(typeof(FtpSecurityProtocol)))
                    {
                        if ((controller.Account.FtpsMethod == FtpsMethod.Explicit && p.ToString().Contains("Explicit"))
                            || (controller.Account.FtpsMethod == FtpsMethod.Implicit && p.ToString().Contains("Implicit")))
                        {
                            Log.Write(l.Debug, "Testing with {0}", p.ToString());

                            try {
                                _ftpc.Close();
                                _ftpc.SecurityProtocol = p;
                                _ftpc.Open(controller.Account.Username, controller.Account.Password);
                            }
                            catch (Exception exe){
                                Log.Write(l.Warning, "Unable to connect: {0}", exe.GetType().ToString());
                                continue;
                            }
                            connected = true;
                            controller.Account.FtpSecurityProtocol = p;
                            break;
                        }
                    }

                    if (!connected)
                    {
                        Notifications.ChangeTrayText(MessageType.Nothing);
                        throw;
                    }
                }
            }
            else // SFTP
            {
                ConnectionInfo connectionInfo;
                if (controller.isPrivateKeyValid)
                    connectionInfo = new PrivateKeyConnectionInfo(controller.Account.Host, controller.Account.Port, controller.Account.Username, new PrivateKeyFile(controller.Account.PrivateKeyFile, controller.Account.Password));
                else
                    connectionInfo = new PasswordConnectionInfo(controller.Account.Host, controller.Account.Port, controller.Account.Username, controller.Account.Password);

                _sftpc = new SftpClient(connectionInfo);
                _sftpc.ConnectionInfo.AuthenticationBanner += (o, x) => Log.Write(l.Warning, x.BannerMessage);

                _sftpc.HostKeyReceived += (o, x) =>
                {
                    var fingerPrint = x.FingerPrint.GetCertificateData();

                    // if ValidateCertificate handler isn't set, accept the certificate and move on
                    if (ValidateCertificate == null || Settings.TrustedCertificates.Contains(fingerPrint))
                    {
                        Log.Write(l.Client, "Trusted: {0}", fingerPrint);
                        x.CanTrust = true;
                        return;
                    }

                    var e = new ValidateCertificateEventArgs
                    {
                        Fingerprint = fingerPrint,
                        Key = x.HostKeyName,
                        KeySize = x.KeyLength.ToString()
                    };
                    ValidateCertificate(null, e);
                    x.CanTrust = e.IsTrusted;
                };

                _sftpc.Connect();

                _sftpc.ErrorOccurred += (o, e) =>
                {
                    if (!isConnected) Notifications.ChangeTrayText(MessageType.Nothing);
                    if (ConnectionClosed != null) ConnectionClosed(null, new ConnectionClosedEventArgs { Text = e.Exception.Message });

                    if (e.Exception is Renci.SshNet.Common.SftpPermissionDeniedException)
                        Log.Write(l.Warning, "Permission denied error occured");
                    if (e.Exception is Renci.SshNet.Common.SshConnectionException)
                        Reconnect();
                };
            }

            controller.HomePath = WorkingDirectory;

            if (isConnected)
                if (!string.IsNullOrWhiteSpace(controller.Paths.Remote) && !controller.Paths.Remote.Equals("/"))
                    WorkingDirectory = controller.Paths.Remote;

            Log.Write(l.Debug, "Client connected sucessfully");
            Notifications.ChangeTrayText(MessageType.Ready);

            if (Settings.IsDebugMode)
                LogServerInfo();

            // Periodically send NOOP (KeepAlive) to server if a non-zero interval is set
            SetKeepAlive();
        }
		private static void CopyTheLatestSourceFiles()
		{
			string currentDirectory = Directory.GetCurrentDirectory();
			IEnumerable<string> directoryInfo =
				Directory.GetFiles(currentDirectory, "BuildIndicatron*.*", SearchOption.AllDirectories)
				         .Union(Directory.GetFiles(currentDirectory, "*.html", SearchOption.AllDirectories));
			ConnectionInfo connectionInfo = new PasswordConnectionInfo(Host, UserName, Password);
            
			var scpClient = new ScpClient(connectionInfo);
			scpClient.Connect();
			_log.Info(string.Format("Copy {0} files", directoryInfo.Count()));
			foreach (string source in directoryInfo.Where(x => !x.Contains(".Test.dll")))
			{
				string sourceName = source.Replace(currentDirectory + "\\", "");
				string remoteFileName = Path.Combine(_homePiBuildindicatronServer, sourceName.Replace("\\", "/"));
				_log.Info(string.Format("Upload:{0} to {1}", sourceName, remoteFileName));
				scpClient.Upload(new FileInfo(source), remoteFileName);
			}
			scpClient.Disconnect();
		}
Exemplo n.º 19
0
        private void SetupFilesystem()
        {
            Debug.WriteLine("SetupFilesystem {0},{1},{2},{3}",Host,Port,Username,ConnectionType.ToString());

            ProxyTypes pt = ProxyTypes.None;
            switch (ProxyType) {
              case 1: pt = ProxyTypes.Http; break;
              case 2: pt = ProxyTypes.Socks4; break;
              case 3: pt = ProxyTypes.Socks5; break;
            }
            int ProxyPort = 8080;
            var Proxy = ProxyHost;
            if (ProxyHost != null)
            {
                var s = ProxyHost.Split(':');
                if (s.Length > 1)
                {
                    Int32.TryParse(s[1], out ProxyPort);
                    Proxy = s[0];
                }
            }

            ConnectionInfo info;
            switch (ConnectionType)
            {
                case ConnectionType.Pageant:
                    var agent = new PageantProtocol();
                    if (pt == ProxyTypes.None) {
                      info = new AgentConnectionInfo(Host, Port, Username, agent);
                    }
                    else if (ProxyUser.Length>0) {
                      info = new AgentConnectionInfo(Host, Port, Username, pt, Proxy, ProxyPort, ProxyUser, ProxyPass, agent);
                    }
                    else {
                      info = new AgentConnectionInfo(Host, Port, Username, pt, Proxy, ProxyPort, agent);
                    }
                    break;
                case ConnectionType.PrivateKey:
                    if (pt == ProxyTypes.None) {
                      info = new PrivateKeyConnectionInfo(Host, Port, Username, new PrivateKeyFile(PrivateKey, Passphrase));
                    }
                    else if (ProxyUser.Length > 0) {
                      info = new PrivateKeyConnectionInfo(Host, Port, Username, pt, Proxy, ProxyPort, ProxyUser, ProxyPass, new PrivateKeyFile(PrivateKey, Passphrase));
                    }
                    else {
                      info = new PrivateKeyConnectionInfo(Host, Port, Username, pt, Proxy, ProxyPort, new PrivateKeyFile(PrivateKey, Passphrase));
                    }
                    break;
                default:
                    if (pt == ProxyTypes.None) {
                      info = new PasswordConnectionInfo(Host, Port, Username, Password);
                    }
                    else if (ProxyUser.Length > 0) {
                      info = new PasswordConnectionInfo(Host, Username, Password, pt, Proxy, ProxyPort, ProxyUser, ProxyPass);
                    }
                    else {
                      info = new PasswordConnectionInfo(Host, Port, Username, Password, pt, Proxy, ProxyPort);
                    }
                    break;
            }

            _connection = Settings.Default.UseNetworkDrive ? String.Format("\\\\{0}\\{1}\\{2}", info.Host, Root, info.Username) : Name;

            _filesystem = new SftpFilesystem(info, Root,_connection,Settings.Default.UseOfflineAttribute,false, (int) Settings.Default.AttributeCacheTimeout,  (int) Settings.Default.DirContentCacheTimeout);
            Debug.WriteLine("Connecting...");
            _filesystem.KeepAliveInterval = new TimeSpan(0, 0, 60);
            _filesystem.Connect();
        }
Exemplo n.º 20
-47
        private void Uploadfiles(PasswordConnectionInfo connectionInfo, IEnumerable<AchFileEntity> achFilesToUpload)
        {
            using (var sftp = new SftpClient(connectionInfo))
            {          
                try
                {
                    sftp.Connect();

                    foreach (var achfile in achFilesToUpload)
                    {
                        using (var stream = new MemoryStream())
                        {
                            var fileName = achfile.Name + ".ach";

                            var writer = new StreamWriter(stream);
                           // writer.Write(achfile.AchFileBody);
                            writer.Flush();
                            stream.Position = 0;

                            sftp.UploadFile(stream, fileName);
                            this.Manager.ChangeAchFilesStatus(achfile, AchFileStatus.Uploaded);
                            this.Manager.UnLock(achfile);
                        }
                    }
                }
                finally
                {
                    sftp.Disconnect();
                }
            }
        }