Reverse SSH Port Forwarding in C# - c#

I came across this article when trying to put together a reverse SSH solution in visual studio C#:
.NET SSH Port Forwarding
Using his code works up until the point where I actually start the port (port.Start()), then it throws an exception. Doing a reverse tunnel with PuTTY works just fine, so I believe the server is set up correctly. Am I doing something wrong in regards to implementing this SSH.NET library?
using Renci.SshNet;
using Renci.SshNet.Messages;
using Renci.SshNet.Common;
using System;
using System.Net;
using System.Threading;
namespace rSSHTunnelerSSHNET
{
public class Program
{
public static void Main(String[] arg)
{
String Host = "testserver.remote";
String Username = "testuser";
String Password = "password";
using (var client = new SshClient(Host, Username, Password))
{
client.Connect();
if (client.IsConnected)
{
Console.WriteLine("connected");
var port = new ForwardedPortRemote("targetserver.local", 80, "testserver.remote", 8080);
client.AddForwardedPort(port);
port.Exception += delegate(object sender, ExceptionEventArgs e)
{
Console.WriteLine(e.Exception.ToString());
};
port.Start();
}
else
{
Console.WriteLine("failed to connect.");
Console.ReadLine();
}
}
}
}
}

Related

Display complete SSH shell output including login message and prompt in C#

I'm trying to create a simple SSH client in C#. This is my code now:
using Renci.SshNet;
public static void Main(string[] args)
{
AuthenticationMethod method = new PasswordAuthenticationMethod("pi", "raspberry");
ConnectionInfo connection = new ConnectionInfo("192.168.91.134", "pi", method);
SshClient client = new SshClient(connection);
if (!client.IsConnected)
{
Console.WriteLine("Not Connected...");
client.Connect();
}
while (true)
{
string command = Console.ReadLine();
SshCommand response = client.RunCommand(command);
Console.WriteLine(response.Result);
}
}
Problem:
like this, it shows just the response of the command sent. I would like the entire output, also with the user and the current directory (like a classic SSH shell).
if I want to launch the sudo su command giving the password it doesn't work...
(in the future I want to add the output to a listbox and take the input from a texbox in a winForms app)
Thank you in advance for your help
This is my implementation:
using System;
using System.Threading;
using Renci.SshNet;
public class Program
{
public static void Main(string[] args)
{
SshClient sshClient = new SshClient("192.168.91.134", 22, "pi", "raspberry");
sshClient.ConnectionInfo.Timeout = TimeSpan.FromSeconds(120);
sshClient.Connect();
ShellStream shellStreamSSH = sshClient.CreateShellStream("vt-100", 80, 60, 800, 600, 65536);
Thread thread = new Thread(() => recvSSHData(shellStreamSSH));
thread.Start();
while (true)
{
string command = Console.ReadLine();
shellStreamSSH.Write(command + "\n");
shellStreamSSH.Flush();
}
}
public static void recvSSHData(ShellStream shellStreamSSH)
{
while (true)
{
try
{
if (shellStreamSSH != null && shellStreamSSH.DataAvailable)
{
string strData = shellStreamSSH.Read();
Console.WriteLine(strData);
}
}
catch
{
}
System.Threading.Thread.Sleep(200);
}
}
}
In you want to implement an SSH terminal client (like PuTTY), you need to use SSH "shell" channel.
In SSH.NET, use SshClient.CreateShell or SshClient.CreateShellStream, not SshClient.RunCommand.

Receiving UDP packets from Wireless IMU application in Unity

I have a project where I have a wireless IMU application on my android phone. Based on the app description, it sends out accel/gyro data in csv format over UDP to a target IP address and port.
Currently I am trying to code a UDPListener in Unity that receives this data.
using UnityEngine;
using UnityEngine.Networking;
using System;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Collections.Generic;
using System.Linq;
public class UDPReceiver1 : MonoBehaviour
{
Thread udpListeningThread;
public int portNumberReceive;
UdpClient receivingUdpClient;
string[] delimiters = { ", ", "," };
string[] data;
void Start()
{
initListenerThread();
}
void initListenerThread()
{
Debug.Log("Started on : " + portNumberReceive.ToString());
udpListeningThread = new Thread(new ThreadStart(UdpListener));
// Run in background
udpListeningThread.IsBackground = true;
udpListeningThread.Start();
}
public void UdpListener()
{
receivingUdpClient = new UdpClient(portNumberReceive);
while (true)
{
//Listening
try
{
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
// Blocks until a message returns on this socket from a remote host.
byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint);
if (receiveBytes != null)
{
string returnData = Encoding.UTF8.GetString(receiveBytes);
Debug.Log("Message Received" + returnData.ToString());
Debug.Log("Address IP Sender" + RemoteIpEndPoint.Address.ToString());
Debug.Log("Port Number Sender" + RemoteIpEndPoint.Port.ToString());
data = returnData.Split(delimiters, StringSplitOptions.None);
Debug.Log(data);
}
}
catch (Exception e)
{
Debug.Log(e.ToString());
}
}
}
void OnDisable()
{
if (udpListeningThread != null && udpListeningThread.IsAlive)
{
udpListeningThread.Abort();
}
receivingUdpClient.Close();
}
}
As of now this code does not work at all, and I have been very perplexed as to why it isnt working. Many forums seem to follow the same structure and the code seems logical.
When I tested the connection, what i did was to attach this script to a gameobject, set an arbitrary port number, e.g. "12345", and Play. Meanwhile I ran the application on my android phone, with the target IP address being the computer's Ip address and the target port number being the same port number I used earlier.
I would really appreciate it if any kind soul can help, as I have been stuck here for close to 2 weeks;(

C# SSH Connection

I'm trying to run SSH commands as part of a C# app. My code is as follows:
using System;
using Renci.SshNet;
namespace SSHconsole
{
class MainClass
{
public static void Main (string[] args)
{
//Connection information
string user = "sshuser";
string pass = "********";
string host = "127.0.0.1";
//Set up the SSH connection
using (var client = new SshClient (host, user, pass))
{
//Start the connection
client.Connect ();
var output = client.RunCommand ("echo test");
client.Disconnect();
Console.WriteLine (output.ToString());
}
}
}
}
From what I've read about SSH.NET, this should output the result of the command which I believe should be 'test'. However, when I run the program, the output I get is:
Renci.SshNet.SshCommand
Press any key to continue...
I don't understand why I'm getting this output (regardless of the command) and any input would be greatly appreciated.
Thanks,
Jake
Use output.Result instead of output.ToString().
using System;
using Renci.SshNet;
namespace SSHconsole
{
class MainClass
{
public static void Main (string[] args)
{
//Connection information
string user = "sshuser";
string pass = "********";
string host = "127.0.0.1";
//Set up the SSH connection
using (var client = new SshClient(host, user, pass))
{
//Start the connection
client.Connect();
var output = client.RunCommand("echo test");
client.Disconnect();
Console.WriteLine(output.Result);
}
}
}
}

OpenPop.Mime don't find plaintext

i need to recover all my message from my Outlook box. I use the OpenPop open source, but i can't recover the plain text (the value is null) and i don't understand why because when i check up my mail the plain text exist. When i try with the html version it works but i don't need this one in my project. Thanks to anyone who can help me.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Globalization;
using System.IO;
using System.Net.Security;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;
using OpenPop.Mime;
using OpenPop.Pop3;
namespace EmailGmail
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string hostname = ***;
int port = **;
bool useSsl = true;
string username = ***;
string password = ***;
List<OpenPop.Mime.Message> allaEmail = FetchAllMessages(hostname, port, useSsl, username, password);
foreach (OpenPop.Mime.Message message in allaEmail)
{
OpenPop.Mime.MessagePart plainText = message.FindFirstPlainTextVersion();
OpenPop.Mime.MessagePart html = message.FindFirstHtmlVersion();
}
}
public static List<OpenPop.Mime.Message> FetchAllMessages(string hostname, int port, bool useSsl, string username, string password)
{
// The client disconnects from the server when being disposed
using (Pop3Client client = new Pop3Client())
{
try
{
// Connect to the server
client.Connect(hostname, port, useSsl);
// Authenticate ourselves towards the server
client.Authenticate(username, password);
// Get the number of messages in the inbox
int messageCount = client.GetMessageCount();
// We want to download all messages
List<OpenPop.Mime.Message> allMessages = new List<OpenPop.Mime.Message>(messageCount);
// Messages are numbered in the interval: [1, messageCount]
// Ergo: message numbers are 1-based.
// Most servers give the latest message the highest number
for (int i = messageCount; i > 0; i--)
{
allMessages.Add(client.GetMessage(i));
}
// Now return the fetched messages
return allMessages;
}
catch (Exception ex)
{
return null;
}
}
}
}
}
I had the same problem. I solved by going to pick the raw data of the body and using a method to convert its bytes to readable text (string).
string Body = msgList[0].MessagePart.MessageParts[0].GetBodyAsText();
Here is what you gets the body text.
msgList is the result of calling FetchAllMe messages, which gives you an array of messages. Every message has its MessagePart which contain the body text. Use GetBodyAsText to retrieve the body text. GetBodyAsText is already included in OpenPop library, so it's not a method of mine.
Hope this clears your doubts.
private void button7_Click(object sender, EventArgs e)
{
List<OpenPop.Mime.Message> allaEmail = FetchAllMessages(...);
StringBuilder builder = new StringBuilder();
foreach(OpenPop.Mime.Message message in allaEmail)
{
OpenPop.Mime.MessagePart plainText = message.FindFirstPlainTextVersion();
if(plainText != null)
{
// We found some plaintext!
builder.Append(plainText.GetBodyAsText());
} else
{
// Might include a part holding html instead
OpenPop.Mime.MessagePart html = message.FindFirstHtmlVersion();
if(html != null)
{
// We found some html!
builder.Append(html.GetBodyAsText());
}
}
}
MessageBox.Show(builder.ToString());
}

Is it bad Ju-ju that the port is still being listened to after my app shuts down?

My app listens on a certain port for socket messages. I can see that it is LISTENING via "netstat -a" at the command line.
When I shut the app down, the machine is still listening on that port when I re-run "netstat -a"
Is this a problem?
It seems like maybe it is, as when I subsequently start the app again, it crashes ignominiously.
How can I cause the listening to cease?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Diagnostics;
namespace testSocketSendAndReceive_Nutshell
{
public partial class Form1 : Form
{
string sJerrysIPAddr = "10.24.93.110";
string sMyIPAddr = "10.24.93.128";
string sThisAppFileName = string.Empty;
bool bThisInstanceFunctionsAsServer = false;
internal static Form1 MainSocketPairForm = null;
public Form1()
{
InitializeComponent();
MainSocketPairForm = this;
}
private void Form1_Load(object sender, EventArgs e)
{
sThisAppFileName = System.Diagnostics.Process.GetCurrentProcess().ProcessName; // This provides just the app name, appending ".vshost" but NOT ".exe" (testSocketSendAndReceive_Nutshell.vshost)
lblFileName.Text = sThisAppFileName;
// Client and Server code are here combined in one app; however, we want each instance to run as
// just one or the other, so (the .exe functioning as a Server should be renamed with the subString
// "Server" somewhere in the filename):
bThisInstanceFunctionsAsServer = sThisAppFileName.Contains("Server");
if (bThisInstanceFunctionsAsServer)
{
new Thread(Server).Start(); // Run server method concurrently.
Thread.Sleep(500); // Give server time to start.
}
btnSendMsg.Visible = !bThisInstanceFunctionsAsServer;
textBox1.Visible = !bThisInstanceFunctionsAsServer;
}
static void Client()
{
using (TcpClient client = new TcpClient(Form1.MainSocketPairForm.sJerrysIPAddr, 51111)) // err here second time around
using (NetworkStream n = client.GetStream())
{
BinaryWriter w = new BinaryWriter(n);
w.Write(Form1.MainSocketPairForm.textBox1.Text.ToString());
w.Flush();
Form1.MainSocketPairForm.label1.Text = new BinaryReader(n).ReadString();
}
}
static void Server()
{
TcpListener listener = new TcpListener(IPAddress.Any, 51111);
listener.Start();
var shouldExit = false;
while (!shouldExit)
using (TcpClient c = listener.AcceptTcpClient())
{
using (NetworkStream n = c.GetStream())
{
string msg = new BinaryReader(n).ReadString();
if (msg == "exit")
// Client told us to exit...
shouldExit = true;
BinaryWriter w = new BinaryWriter(n);
w.Write(msg + " back atcha!");
w.Flush(); // Must call Flush because we're not disposing the writer.
}
}
}
private void button1_Click(object sender, EventArgs e)
{
Client();
}
private void button2_Click(object sender, EventArgs e)
{
Close();
}
}
}
Your application is probably not actually exiting (check task manager "Processes" tab for your .exe).
You are probably trying to close the application by just closing the command window. Because your Server thread is not a background thread, it will just keep running. Try this guy in Form_Load:
if (bThisInstanceFunctionsAsServer)
{
var serverThread = new Thread(Server);
serverThread.IsBackground = true; // Make sure the server thread doesn't keep the app running in the background
serverThread.Start(); // Run server method concurrently.
Thread.Sleep(500); // Give server time to start.
}

Categories