C# Web Traffic Listener - c#

I am trying to write a simple c# console application which shows the accessed websites (sort of proxy server) . I understood that the right approach would be using .Net Sockets and TCP Listeners. However, I tried some code samples and I can get working none of them.
Any suggestions would be great!

You can use FiddlerCore
public class HttpProxy : IDisposable
{
public HttpProxy()
{
Fiddler.FiddlerApplication.BeforeRequest += FiddlerApplication_BeforeRequest;
Fiddler.FiddlerApplication.Startup(8888, true, true);
}
void FiddlerApplication_BeforeRequest(Fiddler.Session oSession)
{
Console.WriteLine(String.Format("REQ: {0}", oSession.url));
}
public void Dispose()
{
Fiddler.FiddlerApplication.Shutdown();
}
}
static void Main(string[] Args)
{
var p = new HttpProxy();
Console.ReadLine();
p.Dispose();
}

Related

Websocket sharp , reading server variable from onmessage

Hello I am new on web sockets so was wondering what am I doing wrong here, I have a server and client
code looks something like this
public class SampleSocketService: WebSocketBehavior
{
private int globalvar = 1;
protected override void OnMessage(MessageEventArgs e)
{
if(...somecondition)
{
while(...loopcondition)
globalvar++;
}
if(...anothercondition)
{
this.Send(globalvar);
}
}
}
problem is when I am sending to client the globalvar it is always = 1
Any ideas?

Remove RoleInstance from data sent to Azure Application Insights from WPF

I'm trying to add Application Insights to a WPF app using this documentation: https://learn.microsoft.com/en-us/azure/azure-monitor/app/windows-desktop. The basic integration is working. I am now trying to remove the RoleInstance property from the submitted data, as described in the documentation, as this contains the user's computer name (personally identifiable information). Here's my code, based on the documentation above:
Telemetry.cs
public static class Telemetry
{
public static TelemetryClient Client;
public static void Close()
{
if (Client != null)
{
Client.Flush();
System.Threading.Thread.Sleep(1000);
}
}
public static void Initialize()
{
TelemetryConfiguration.Active.InstrumentationKey = "xxxxxxxx";
TelemetryConfiguration.Active.TelemetryInitializers.Add(new MyTelemetryInitializer());
Client = new TelemetryClient(TelemetryConfiguration.Active);
Client.Context.Session.Id = Guid.NewGuid().ToString();
Client.Context.Device.OperatingSystem = Environment.OSVersion.ToString();
}
private class MyTelemetryInitializer : ITelemetryInitializer
{
public void Initialize(ITelemetry telemetry)
{
if (string.IsNullOrEmpty(telemetry.Context.Cloud.RoleName))
{
telemetry.Context.Cloud.RoleInstance = null;
}
}
}
}
App.xaml.cs
public partial class App : Application
{
protected override void OnExit(ExitEventArgs e)
{
Telemetry.Close();
base.OnExit(e);
}
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
Telemetry.Initialize();
}
}
When I call Telemetry.Client.TrackEvent(), Telemetry.Initialize() runs, and RoleInstance is null from the start. But, the data sent to AI contains my computer name as the RoleInstance. Not sure how to debug further.
Note: the documentation describes integration into WinForms, and I'm in WPF, so I've guessed at using App.OnStartup instead of Main.
I just found something interesting, if you set a dummy value for RoleInstance, it really takes effect. Maybe the null/empty value will be checked and replaced by the real RoleInstance in the backend. As a workaround, you can just specify a dummy value instead of null/empty value.
Here is my test result with a dummy value:
in azure portal:

AfterSessionComplete event not firing in Window Service(Debugging in Console). Fiddercore

My application is not firing the event AfterSessionComplete. Code Below
fiddler.cs
namespace proj
{
public static class Fiddler
{
public static void start()
{
startProxy();
}
public static void startProxy()
{
FiddlerApplication.AfterSessionComplete += FiddlerApplication_AfterSessionComplete;
FiddlerApplication.Startup(8888, true, true, true);
}
public static void FiddlerApplication_AfterSessionComplete(Session sess)
{
//Working aftersessioncomplete
}
}
}
Service1.cs
namespace Proj
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
Fiddler.start();
}
protected override void OnStop()
{
}
internal void TestStartupAndStop(string[] args)
{
this.OnStart(args); //use to debug
//For commandLine
}
}
}
program.cs
namespace Proj
{
static class Program
{
static void Main(string[] args)
{
if (Environment.UserInteractive)
{
Service1 service1 = new Service1();
service1.TestStartupAndStop(args);
}
else
{
}
}
}
}
I'm creating a windows service but I was facing a debugging issue, that's why I use the console application debug to check my code working or not.
I added break point at aftersessioncomplete event when I get to know that FiddlerApplication.AfterSessionComplete is not firing. It stops the application without going on public static void FiddlerApplication_AfterSessionComplete(Session sess)
Anyone can help? or faced same issue?
After Session cannot fire in window service because of the Certificate popup the certificate as for GUI which windows service cannot provide so the code stuck at certificate installation and not firing after session events.
To work out with this one keep in mind to use console app and hide console app after installation of certificate

Connecting Anonymous Pipe across processes gives Invalid Handle Error, I'm using System.Io.Pipes

I'm trying to put together a class to handle Ipc between processes using anonymous pipes provided by System.Io.Pipes.
The problem I'm having is that when I test the class using a single process the pipes set up correctly and I can send data between client and server without a problem. However, when I split the client and server into separate processes ( on the same machine ), the client is unable to connect to the end of the server pipe.
The error System.Io.Exception Invalid pipe handle is raised when call
_outboundPipeServerStream = new AnonymousPipeClientStream(PipeDirection.Out, serverHandle);
The full code of the class is pasted below.
Essentially its work like this;
Server Process. Create anonymous pipe set for inbound data - call this Pipe A
Server Process. Starts Client process and passes PipeHandle via command argument
Client Process. Connects to end of Pipe A
Client Process. Create anonymous pipe set for inbound data (Pipe B)
5 Client process. Passes pipe handle back to Server using Pipe A
Server Process. Connects to end of Pipe B
So now we have two anonymous pipes, pointing in opposite directions between Server and Client.
Here is the full code of my IPC class
public class MessageReceivedEventArgs : EventArgs
{
public string Message { get; set; }
}
public class IpcChannel : IDisposable
{
private AnonymousPipeServerStream _inboundPipeServerStream;
private StreamReader _inboundMessageReader;
private string _inboundPipeHandle;
private AnonymousPipeClientStream _outboundPipeServerStream;
private StreamWriter _outboundMessageWriter;
public delegate void MessageReceivedHandler(object sender, MessageReceivedEventArgs e);
public event MessageReceivedHandler MessageReceived;
private Thread _clientListenerThread;
private bool _disposing = false;
public IpcChannel()
{
SetupServerChannel();
}
public IpcChannel(string serverHandle)
{
SetupServerChannel();
// this is the client end of the connection
// create an outbound connection to the server
System.Diagnostics.Trace.TraceInformation("Connecting client stream to server : {0}", serverHandle);
SetupClientChannel(serverHandle);
IntroduceToServer();
}
private void SetupClientChannel(string serverHandle)
{
_outboundPipeServerStream = new AnonymousPipeClientStream(PipeDirection.Out, serverHandle);
_outboundMessageWriter = new StreamWriter(_outboundPipeServerStream)
{
AutoFlush = true
};
}
private void SetupServerChannel()
{
_inboundPipeServerStream = new AnonymousPipeServerStream(PipeDirection.In);
_inboundMessageReader = new StreamReader(_inboundPipeServerStream);
_inboundPipeHandle = _inboundPipeServerStream.GetClientHandleAsString();
_inboundPipeServerStream.DisposeLocalCopyOfClientHandle();
System.Diagnostics.Trace.TraceInformation("Created server stream " + _inboundPipeServerStream.GetClientHandleAsString());
_clientListenerThread = new Thread(ClientListener)
{
IsBackground = true
};
_clientListenerThread.Start();
}
public void SendMessage(string message)
{
System.Diagnostics.Trace.TraceInformation("Sending message {0} chars", message.Length);
_outboundMessageWriter.WriteLine("M" + message);
}
private void IntroduceToServer()
{
System.Diagnostics.Trace.TraceInformation("Telling server callback channel is : " + _inboundPipeServerStream.GetClientHandleAsString());
_outboundMessageWriter.WriteLine("CI" + _inboundPipeServerStream.GetClientHandleAsString());
}
public string ServerHandle
{
get
{
return _inboundPipeHandle;
}
}
private void ProcessControlMessage(string message)
{
if (message.StartsWith("CI"))
{
ConnectResponseChannel(message.Substring(2));
}
}
private void ConnectResponseChannel(string channelHandle)
{
System.Diagnostics.Trace.TraceInformation("Connecting response (OUT) channel to : {0}", channelHandle);
_outboundPipeServerStream = new AnonymousPipeClientStream(PipeDirection.Out, channelHandle);
_outboundMessageWriter = new StreamWriter(_outboundPipeServerStream);
_outboundMessageWriter.AutoFlush = true;
}
private void ClientListener()
{
System.Diagnostics.Trace.TraceInformation("ClientListener started on thread {0}", Thread.CurrentThread.ManagedThreadId);
try
{
while (!_disposing)
{
var message = _inboundMessageReader.ReadLine();
if (message != null)
{
if (message.StartsWith("C"))
{
ProcessControlMessage(message);
}
else if (MessageReceived != null)
MessageReceived(this, new MessageReceivedEventArgs()
{
Message = message.Substring(1)
});
}
}
}
catch (ThreadAbortException)
{
}
finally
{
}
}
public void Dispose()
{
_disposing = true;
_clientListenerThread.Abort();
_outboundMessageWriter.Flush();
_outboundMessageWriter.Close();
_outboundPipeServerStream.Close();
_outboundPipeServerStream.Dispose();
_inboundMessageReader.Close();
_inboundMessageReader.Dispose();
_inboundPipeServerStream.DisposeLocalCopyOfClientHandle();
_inboundPipeServerStream.Close();
_inboundPipeServerStream.Dispose();
}
}
In a single process, it can be used like this;
class Program
{
private static IpcChannel _server;
private static IpcChannel _client;
static void Main(string[] args)
{
_server = new IpcChannel();
_server.MessageReceived += (s, e) => Console.WriteLine("Server Received : " + e.Message);
_client = new IpcChannel(_server.ServerHandle);
_client.MessageReceived += (s, e) => Console.WriteLine("Client Received : " + e.Message);
Console.ReadLine();
_server.SendMessage("This is the server sending to the client");
Console.ReadLine();
_client.SendMessage("This is the client sending to the server");
Console.ReadLine();
_client.Dispose();
_server.Dispose();
}
Thanks in advance for any suggestions.
You didn't post the server code, but anyway. In the server:
You need to specify that the client's pipe handle is inheritable when you create it.
When you launch the client you need to specify that inheritable handles will be inherited.
If you miss either of these steps then the pipe handle will be invalid in the client process.
Also, your step 4 won't work. If you create a pipe handle in the client it won't mean anything to the server when you pass it back. You can make this work using the DuplicateHandle function, but it's much easier to create all the handles in the server and inherit them in the client.
The key point is that handles are per-process, not system-wide.
Starting child process do not forget to set UseShellExecute = false or the handle will not be inherited.

Handling Server-side RtmpConnection.Invoke() when connecting with NetConnection as a client using FluorineFx

I am trying to create a basic console app in order to stress test our FluorineFx based flash remoting server.
I can connect fine but the server method I am calling invokes this client-side function:
connection.Invoke("onServerDataPush", new string[] { "someParam", "anotherParam" });
I am struggling to find out how I can expose this method to the connection. The NetConnection.Call() method allow you to pass in a callback but the result of this is always null and the NetConnection call fails with the following error:
Could not find a suitable method with name onServerDataPush
Here is my client-side code:
class Program
{
private NetConnection _netConnection;
static void Main(string[] args)
{
var program = new Program();
program.Connect();
Console.ReadLine();
}
public void Connect()
{
_netConnection = new NetConnection();
_netConnection.ObjectEncoding = ObjectEncoding.AMF3;
_netConnection.OnConnect += netConnection_OnConnect;
_netConnection.NetStatus += netConnection_NetStatus;
_netConnection.Connect("rtmp://localhost:1935/MyApplication");
}
void netConnection_OnConnect(object sender, EventArgs e)
{
var responder = new Responder<object>(x =>
{
var test = x;
});
//The NetConnection object is connected now
_netConnection.Call("MyServerMethod", responder, "someParameter");
}
void netConnection_NetStatus(object sender, NetStatusEventArgs e)
{
string level = e.Info["level"] as string;
}
}
Debugging through RtmpClient line 308 finally allowed me to solve this.
You must set the NetConnection.Client property to the class that contains a method of the same signature as the one being invoked by the server (in my case this as the method is in the Program class).
public void onServerDataPush(string type, string json)
{
}
FluorineFx then calls the method using reflection.

Categories