How to create a simple c# http monitor/blocker? - c#

I was reading that question (How to create a simple proxy in C#?) that is near of my wishes.
I simply want develop a c# app that, by example, monitors Firefox, IE, etc and logs all navigated pages. Depending of the visited page, I want to block the site (like a parental filter).
Code snippets/samples are good, but if you can just tell me some direction of that classes to use I will be grateful. :-)

I’ll answer appropriate for a parent: ala "Parental Controls"
You can start out with a proxy server when the kids are less than about 10 years old. After that, they will figure out how to get around the proxy (or run their own client applications that bypass the proxy). In the early teen years, you can use raw sockets.
Type this program into Visual Studio (C#).
class Program
{
static void Main(string[] args)
{
try
{
byte[] input = BitConverter.GetBytes(1);
byte[] buffer = new byte[4096];
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
s.Bind(new IPEndPoint(IPAddress.Parse("192.168.1.91"), 0));
s.IOControl(IOControlCode.ReceiveAll, input, null);
int bytes = 0;
do
{
bytes = s.Receive(buffer);
if (bytes > 0)
{
Console.WriteLine(Encoding.ASCII.GetString(buffer, 0, bytes));
}
} while (bytes > 0);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
Note that this is just a “snippet”, lacking appropriate design and error checking. [Please do not use 'as-is' - you did request just a head start] Change the IP address to your machine. Run the program AS Administrator (use “runas” on the command line, or right-click “Run as Administrator”). Only administrators can create and use raw sockets on modern versions of windows. Sit back and watch the show.
All network traffic is delivered to your code (displayed on the screen, which will not look nice, with this program).
Your next step is to create some protocol filters. Learn about the various internet application protocols (assuming you don't already know), modify the program to examine the packets. Look for HTTP protocol, and save the appropriate data (like GET requests).
I personally have setup filters for AIM (AOL Instant Messenger), HTTP, MSN messenger (Windows Live Messenger), POP, and SMTP. Today, HTTP gets just about everything since the kids prefer the facebook wall to AIM nowadays.
As the kids reach their early-to-mid teenage years, you will want to back-off on the monitoring. Some say this is to enable the kids to “grow up”, but the real reason is that “you don’t wanna know”. I backed off to just collecting URLs of get requests, and username/passwords (for emergency situations) that are in clear text (pop, basic auth, etc.).
I don't know what happens in late teen years; I cannot image things getting much worse, but I am told that "I have not seen anything yet".
Like someone earlier said, this only works when run on the target machine (I run a copy on all of the machines in the house). Otherwise, for simple monitoring check your router - mine has some nice logging features.
My final comment is that this application should be written in C/C++ against the Win32 API directly, and installed as a service running with administrative rights on the machine. I don't think this type of code is appropriate for managed c#. You can attach a UI in C# for monitoring and control. You have to engineer the code so as to have zero noticeable effect on the system.

Your approach will depend on whether or not you are installing this application on the same box you are using to browse or on a separate proxy server.
If you are doing this on a separate server it will be easier to accomplish this in C# / managed code, as you will be simply writing a C# proxy server that client pc's will have point to. System.Net.Sockets namespace TcpListener and TcpClient will be your friend.
If, however, you are installing this on the same machine then take a look WinPcap and and SharpPCap and perhaps Fiddler for some ideas.
Hope that helps.

Related

Creating a COM port out of a ttyUSB port in Ubuntu

The Question
I'm having to work with a rather awkward API at the moment which insists on me giving the address of a device, linked via USB port, in the form COM*. However, on the Ubuntu machine on which I'm working, and have to use, if I plug in this device it will automatically be assigned an address in the form /dev/ttyUSB*.
Given that I can't modify the source code of the API - which I would dearly like to do! - what is the least painful way getting the API to talk to said device?
Extra Detail
An example of how to use the API from the manual:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using com.caen.RFIDLibrary;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
CAENRFIDReader MyReader = new CAENRFIDReader();
MyReader.Connect(CAENRFIDPort.CAENRFID_RS232, "COM3");
CAENRFIDLogicalSource MySource = MyReader.GetSource("Source_0");
CAENRFIDTag[] MyTags = MySource.InventoryTag();
if (MyTags.Length > 0)
{
for (int i = 0; i < MyTags.Length; i++)
{
String s = BitConverter.ToString(MyTags[i].GetId());
Console.WriteLine(s);
}
}
Console.WriteLine("Press a key to end the program.");
Console.ReadKey();
MyReader.Disconnect();
}
}
}
The line MyReader.Connect(CAENRFIDPort.CAENRFID_RS232, "COM3"); is where I'm running into problems.
A little later in the manual, it states that the Connect method is to have two parameters:
ConType: The communication link to use for the connection.
Address: Depending on ConType parameter: IP address for TCP/IP communications ("xxx.xxx.xxx.xxx"), COM port for RS232 communications ("COMx"), an index for USB communications (not yet supported).
Bonus Question
The API in question seems to have been written on the assumption that it would be run on a Windows machine. (It's in C#.) The COM* format seems to be favoured - I'm happy to be corrected on this point - by Windows architectures, whereas Ubuntu seems to favour the ttyUSB* format. Assuming that I can funnel the data from my device from a ttyUSB* port to a COM* port, will the API actually be able to find said data? Or will it incorrectly follow the default Windows path?
Given the new information i suspect you can just give the ttyUSB as the parameter, mono will handle the connection correctly. However the same caution for the line endings below still applies. You might also consider making the parameter a command-line parameter thus making your code run on any platform by being able to supply the COM/USB through the command line parameters. I see no other issues using this code. Did you try it yet?
PS: i think your confusion is actually the statement usb id's are not supported yet, i suspect that is because the library relies on a (text-based) serial connection wich are fundamentally different from direct USB connections (wich drivers normally handle) that handle the connection in a more direct way. The ttyUSB ports on linux however DO represent the (UART) serial connections the same way as windows COM-ports, these are not direct USB connections.
Some handy info about the differences: https://rfc1149.net/blog/2013/03/05/what-is-the-difference-between-devttyusbx-and-devttyacmx/
Old answer
I am assuming you run this program on Mono?
Mono expects the path to the port, so COM* will not do. You could try creating a symlink named COM* to the ttyUSB*. Preferrably located in the environment directory. Once you get them linked the program should see no difference. However line endings in the data/program might be different than on windows. If the device expects CRLF and the program uses Environment.NewLine you might get unexpected behaviour too. It might just be easier if you have the permission/rights to edit the assembly with recompilation tools.

Bluetooth and C# PC -> Cellphone connection without paring

I'm trying to write simple app, which sends short text message to cellphones in bluetooth adapter range.
My first try is sending files: I can send file from PC to cellphone, but i must enter PIN on cellphone, and on PC.
I would rather to send text messages (something like push message) - is it possible to send it without paring devices?
If isn't possible to send push messages, maybe I can send simple file without requesting PIN ?
I use 32feet library.
Sample code (used to send files to selected device)
static int BTSendFile(string adres, string FileName)
{
Uri uri = new Uri("obex://" + adres + '/' + Path.GetFileName(FileName));
ObexWebRequest req = new ObexWebRequest(uri);
req.ReadFile(FileName);
ObexWebResponse rsp = (ObexWebResponse)req.GetResponse();
return (int)rsp.StatusCode;
}
A quick answer would be; NO, you will ALWAYS need some kind of pairing.
But if you take a look at the different kinds of pairing out there, you would see that BT 2.1 supports Secure Simple Pairing (SSP) with the Just Works-mode. This allows you to pair devices (almost) without any user interaction. From Wikipedia:
Just works: As implied by the name, this method just works. No user interaction is required; however, a device may prompt the user to confirm the pairing process. This method is typically used by headsets with very limited IO capabilities, and is more secure than the fixed PIN mechanism which is typically used for legacy pairing by this set of limited devices. This method provides no man in the middle protection.
However, since "This method is typically used by headsets with very limited IO capabilities", it would probably not apply to the cellphones you are talking about, but I thought you should know :)
According to the offical Bluetooth Message Access Profile, i.e. the specific Bluetooth profile that deals with accessing SMS/MMS systems on phones via a remote device:
'The MCE device shall use the services of the MSE device only after successfully creating a secure connection. This includes exchanging of security initialization messages, creation of link keys, and enabling encryption'
From: https://developer.bluetooth.org/TechnologyOverview/Pages/MAP.aspx
There is also a link to the full spec there if you are interested.
This certtainly suggests that secure pairing is required, which I'd assume to involve the passkey. My experience is that once a device has been paired a connection can be made without repeating the pairing as long as that pairing is remembered by the devices (i.e. I've paired a device once and not had to do it again). As to simpler, non-keyed pairing mentioned by khellang above, I've not seen anything about this - if it is purely for devices like headsets then the security requirements may be lower due to their not likely wanting write access to a device?

Accessing the Ubuntu terminal from Mono

Background
I'm writing an web application so I can control an Ubuntu Server from a web site.
One idea I had was to run the 'screen' application from mono and redirect my input and output from there.
Running 'screen' from mono:
ProcessStartInfo info = new ProcessStartInfo("screen", "-m");
info.UseShellExecute = false;
info.RedirectStandardOutput = true;
info.RedirectStandardInput = true;
var p = new Process();
p.StartInfo = info;
p.Start();
var output = p.StandardOutput;
var input = p.StandardInput;
but running 'screen' with the RedirectStandardInput gives out the error:
Must be connected to a terminal
I've tried many different arguments and none seems to work with 'Redirecting Standard Input'
Other ideas for controlling a server will be greatly appreciated
I think this is the typical question in which you're asking how to implement your solution to a problem, instead of asking how to solve your problem. I don't think you should do hacky things like making a web app that tunnels the user actions to the server via a terminal.
I think you can bypass all that and, without writing a single line of code, take advantage of what the platform (Gtk+ in this case) already provides you:
You could run gnome-terminal in the server with the Broadway GDK backend. This way the gnome-terminal app will not run in the server, but open a web server on the port you specify. Later, you can use any WebSockets-enabled browser to control it.
This is the easiest and less hacky solution compared to the other ones offered so far. If you still are excited about using Mono for web development you still can, and you could embed this access in an iFrame or something.
(PS: If you don't want to depend on GTK being installed in the server; you could just use WebSockets in your client part of the webpage to be able to send events from the server to the client, and the library SSHNET to send the user's input directly through the wire.)
screen will need a terminal of some sort. It's also gigantically overkill.
You may wish to investigate the pty program from the Advanced Programming in the Unix Environment book (pty/ in the sources) to provide a pseudo-terminal that you can drive programmatically. (You'd probably run the pty program as-provided and write your driver in Mono if you're so inclined.) (The pty program will make far more sense if studied in conjunction with the book.)
The benefit to using the pty program, or functionality similar to it, is that you'd properly handle programs such as passwd that open("/dev/tty") to prompt the user for a password. If you simply redirect standard IO streams via pipe() and dup2() system calls, you won't have a controlling terminal for the programs that need one. (This is still a lot of useful programs but not enough to be a remote administration tool.)
There may be a Mono interface to the pty(7) system; if so, it may be more natural to use it than to use the C API, but the C API is what does the actual work, so it may be easier to just write directly in the native language.
A different approach to solve the same problem is shellinabox. Also interesting is this page from the anyterm website that compares different products that implement this kind of functionality.
Using shellinabox is very simple:
# ./shellinaboxd -s /:LOGIN
(this is the example given on their website) will start a webserver (on in your case the Ubuntu server). When you point your browser to http://yourserver:4200 you'll see a login screen, just like you would see when opening a session with ssh/putty/telnet/... but in your browser.
You could provide the required remote access functionality to the server's shell by just including an iframe that points to that service in your application's webpage.

Simple cross-platform process to process communication in Mono?

I'm working on a Mono application that will run on Linux, Mac, and Windows, and need the ability for apps (on a single os) to send simple string messages to each other.
Specifically, I want a Single Instance Application. If a second instance is attempted to be started, it will instead send a message to the single instance already running.
DBus is out, as I don't want to have that be an additional requirement.
Socket communication seems to be hard, as windows seems to not allow permission to connect.
Memory Mapped Files seems not to be supported in Mono.
Named Pipes appears not to be supported in Mono.
IPC seems not to be supported on Mono.
So, is there a simple method to send string messages on a single machine to a server app that works on each os, without requiring permissions, or additional dependencies?
On my ubuntu (10.10 mono version: 2.6.7) I've tried using WCF for interprocess communication with BasicHttpBinding, NetTcpBinding and NetNamedPipeBinding. First 2 worked fine, for NetNamedPipeBinding I got an error:
Channel type IDuplexSessionChannel is
not supported
when calling ChannelFactory.CreateChannel() method.
I've also tried using Remoting (which is a legacy technology since WCF came out) with IpcChannel; example from this msdn page started and worked without problems on my machine.
I suppose you shouldn't have problems using WCF or Remoting on Windows either, not sure about Mac though, don't have any of those around to test. Let me know if you need any code examples.
hope this helps, regards
I wrote about this on the mono-dev mailing list. Several general-purpose inter-process messaging systems were considered, including DBus, System.Threading.Mutex class, WCF, Remoting, Named Pipes... The conclusions were basically mono doesn't support Mutex class (works for inter-thread, not for inter-process) and there's nothing platform agnostic available.
I have only been able to imagine three possible solutions. All have their drawbacks. Maybe there's a better solution available, or maybe just better solutions for specific purposes, or maybe there exist some cross-platform 3rd party libraries you could include in your app (I don't know.) But these are the best solutions I've been able to find so far:
Open or create a file in a known location, with exclusive lock. (FileShare.None). Each application tries to open the file, do its work, and close the file. If failing to open, Thread.Sleep(1) and try again. This is kind of ghetto, but it works cross-platform to provide inter-process mutex.
Sockets. First application listens on localhost, some high numbered port. Second application attempts to listen on that port, fails to open (because some other process already has it) so second process sends a message to the first process, which is already listening on that port.
If you have access to a transactional database, or message passing system (sqs, rabbitmq, etc) use it.
Of course, you could detect which platform you're on, and then use whatever works on that platform.
Solved my problem with two techniques: a named mutex (so that the app can be run on the same machine by different users), and a watcher on a message file. The file is opened and written to for communication. Here is a basic solution, written in IronPython 2.6:
(mutex, locked) = System.Threading.Mutex(True, "MyApp/%s" % System.Environment.UserName, None)
if locked:
watcher = System.IO.FileSystemWatcher()
watcher.Path = path_to_user_dir
watcher.Filter = "messages"
watcher.NotifyFilter = System.IO.NotifyFilters.LastWrite
watcher.Changed += handleMessages
watcher.EnableRaisingEvents = True
else:
messages = os.path.join(path_to_user_dir, "messages")
fp = file(messages, "a")
fp.write(command)
fp.close()
sys.exit(0)
For your simple reason for needing IPC, I'd look for another solution.
This code is confirmed to work on Linux and Windows. Should work on Mac as well:
public static IList Processes()
{
IList<Process> processes = new List<Process>();
foreach (System.Diagnostics.Process process in System.Diagnostics.Process.GetProcesses())
{
Process p = new Process();
p.Pid = process.Id;
p.Name = process.ProcessName;
processes.Add(p);
}
return processes;
}
Just iterate through the list and look for your own ProcessName.
To send a message to your application, just use MyProcess.StandardInput to write to the applications standard input. This only works assuming your application is a GUI application though.
If you have problems with that, then you could maybe use a specialized "lock" file. Using the FileSystemWatcher class you can check when it changes. This way the second instance could write a message in the file and then the first instance notice that it changes and can read in the contents of the file to get a message.

Can a WebServiceHost be changed to avoid the use of HttpListener?

I am looking for a way to use a WCF WebServiceHost without having to rely on the HttpListener class and it's associated permission problems (see this question for details).
I'm working on a application which communicates locally with another (third-party) application via their REST API.
At the moment we are using WCF as an embedded HTTP server. We create a WebServiceHost as follows:
String hostPath = "http://localhost:" + portNo;
WebServiceHost host = new WebServiceHost(typeof(IntegrationService), new Uri(hostPath));
// create a webhttpbinding for rest/pox and enable cookie support for session management
WebHttpBinding webHttpBinding = new WebHttpBinding();
webHttpBinding.AllowCookies = true;
ServiceEndpoint ep = host.AddServiceEndpoint(typeof(IIntegrationService), webHttpBinding, "");
host.Open()
ChannelFactory<IIntegrationService> cf = new ChannelFactory<IIntegrationService>(webHttpBinding, hostPath);
IIntegrationService channel = cf.CreateChannel();
Everything works nicely as long as our application is run as administrator. If we run our application on a machine without administrative privileges the host.Open() will throw an HttpListenerException with ErrorCode == 5 (ERROR_ACCESS_DENIED).
We can get around the problem by running httpcfg.exe from the command line but this is a one-click desktop application and that's not really as long term solution for us.
We could ditch WCF and write our own HTTP server but I'd like to avoid that if possible.
What's the easiest way to replace HttpListener with a standard TCP socket while still using all of the remaining HTTP scaffolding that WCF provides?
Your problem is not related to HttpListener.
Your problem is:
* You have a oneClick application with limited permissions that
* Tries to open a Server port.
This is a contradiction. An untrusted limited permission application should NOT OPEN A SERVER PORT. This is why this is not allowed per definition.
Have you tried opening a normal socket port? It should not work either.
In general, limited trust end user applications should not host a web service ;)
That said, I ahve been in a similar situation trying to use WCF in a driver communication scenario - thank heaven my application runs with full permission.
You can easily compose your own stack via CustomBinding, using the higher level protocol stuff "as is", and rolling your own version of HttpTransport that isn't backed by HttpListener or IIS. Do-able, sure, but it's a lot of work. Take the existing HttpTransport bits apart with Reflector- there are a LOT of moving parts in there. You could probably hack up a simple PoC over Socket in a day or two if you don't need anything fancy like HTTPS or chunking, but making it robust will be tricky. Here's a good wrapup of a bunch of resources (may be a bit dated now).
You could also look at ripping apart enough of Cassini to make it hostable in your app, and loading the WCF pipeline in there (via .svc files and the service activation handler)- it'd require writing very little new code that way, but still give you a fairly robust and tested webserver.

Categories