Get connected Port - c#

I want to build a program that will run on my Raspberry Pi and starts processes when I connect to it. I want to run a specific processes if there is a connection on a specific port.
So I need to get the port somebody is trying to connect to.
For example:
If I open localhost:4444 in my browser I want to get 4444 as a string or an int.
It doesn’t need to be C#. Would be great, but it can also be in other languages.
Is this possible and how can I achieve that?

Listening for an incoming packet on any port number, rather than on a specific port number, is an unnatural act on Linux (the rPi's OS) and on most operating systems.
You could probably, with a lot of work, figure out how to do it with the tcpdump command line utility and/or its underlying libpcap runtime library. This subsystem intercepts network messages at the driver level and reports them. You could write a hunk of code that notices an incoming connection request and launches a server (written in your language of choice) to listen on that port.
But, the server would not be launched in time to handle the request detected by tcpdump or libpcap. Instead, the OS on the rPi would reject it immediately with the ECONNREFUSED OS error. You would have to rely on the client software retrying the connection after the rPi had a chance to launch the server. But client software like web browsers don't automatically retry those refused connections.
You might be able to make this work, but it will always be a brittle solution and a miserable hack. You will be better off rethinking this system design. You should run servers (listeners) on any ports you think your clients will use.
I must mention the security hazards of the approach you propose. A cybercreep could crash your machine simply by running nmap on it if you started servers upon receiving messages on random ports.

Related

C# TCP Server-Socket Security with PLC

I used this MS link to put together a TCP server in C# on a PC. I'm holding the port open and waiting for connections to be established by various PLC clients. The PLCs are in moving autonomous bots, so they move in and out of Wi-Fi range. I'm using this setup to acquire running variables (battery %, etc.) from the bots and display them in a UI for the system administrator to monitor.
I setup the router with port forwarding so that the data arrives on the server PC from the various clients. I'm using Siemens S7-1200 PLCs and I don't believe that they support high end security features like PCs.
So my question is this, if the admin PC is running a Windows service that constantly monitors the open port then is there a security risk? And if there are risks, can you please explain and support with links or resources to help me patch these holes (in C#)?
It seems safe to me because if the PC is off, the port is closed. If the PC is on, the port is open but is bound to the application monitoring it. If the port receives something that it does not deem valid it just dumps that data. I am not incredibly knowledgeable on software and PC security, but this is slightly different because it is a single PC interfacing with less capable hardware.
Having a port open exposes you to anyone connecting to that port and providing bad information, exposing a vulnerability on your message parsing and socket handling implementation (buffer overflow or script injection), or just swamping your application with traffic. The last one is almost impossible to protect against, someone can always DOS you at some level.
None of these are unexpected risks, but you need to be aware of them and ensure that you properly scrub incoming traffic to reject malformed requests and somehow authenticate and drop connections that aren't from the bots you expect.
If you do make an authentication step, you'll want to encrypt the channel before authentication using something like SSL or SSH. Otherwise, someone else could watch your traffic, observe the authentication transaction, and then just copy it.
Best of luck! Security is a deep rabbit hole, but a very valuable skill!

C# Check a port for incomming traffic

I have a server that i use to run game servers on for my friends and me, and some of the servers are "attack-able" (monsters can destroy our base) so i want the server to be shut down when not in use. Then i was wondering if there was a way to detect if there was an incoming signal (trying to connect to the server) on the given port, so the server can be turned on?
Raw question:
Is there a way to detect, if someone is trying to send a message (or connect) through a specific port in c# (or another language better suited for this action)?
Yes, you have to create a server to listen on that port. The problem you will face is that the server you create to detect incoming connections will need to be shut down so the game server can be turned on. They can't listen on the same port unless they're coded to work together and that likely isn't going to be the case with your game server.
If you want to see if there is any connections in use you can try to list all current TCP connections (assuming server using TCP) and find if there is any alive connection to specific port.
Resmon does this in his "Network" tab, so there must be a way to access it programmatically.
Here is answer describing how to get active TCP connections.
How can I get all the the active TCP connections using .NET Framework (no unmanaged PE import!)?
You probably should monitor server with some intervals because player might lose and reestablish connection, so sample it every 10 seconds or so and if there is no connection for more than few samples - shut down the server.

C# and ActiveSync communication / open and read files

I have a device connected to a host computer through cradle usb. Now, I'm just wondering if I could use C# sockets to communicate with the device (ie device sending data, host computer processing it then replying back to the device). How can I accomplish this? by that, what ip address etc etc.. do I have to change so that it would connect cause I have the sockets working on wireless. If not, then is there a way to connect to the device, open and read a file (a text document to be more specific) from the device to my host application.. any ideas?
Thanks! :)
Depending on your target device, when you connect via ActiveSync it likely makes a local RNDIS network connection between teh two devices. You can resolve "ppp_peer" as the partner's network name instead of trying to use a hard-coded IP address (IIRC the IP is different on XP than on Vista).
Be aware that it's not a full connection. TCP packets gets passed through, but things like ICMP do not.
Of course, this just gives you a socket connection, just like if you were to connect between two PCs. It's not going to allow you to do file system operations unless you have an app on the other side listening for commands. If you want that type of thing, Microsoft provides the Remote API (RAPI) interface (wrapped in managed code here)for a lot of basic commands, and it can be extended (with C) to do anything you'd like.

Receiving an ICMP packet in the context of a service on 2008

When we send a packet from a udp port we receive an exception if the network returns an ICMP host unreachable. The exception doesn't tell us anything useful (like the contents of the ICMP packet).
No problem, we'll just listen for ICMP and that will give us the info we need, while ignoring the exception on the UDP port. So, open a raw socket, listen for ICMP packets and go from there.
Works fine in development (Win XP) but in production on server 2008 it appears the security context the exe is running in must have admin rights to be able to open a raw socket. This is useless for a service. If I understand what Microsoft are saying then the only way we can do what we want is run our service under an account with admin rights. Feels a bit like sledgehammer for a peanut not to mention a potential security hole that goes with having a network facing service running under an admin account.
I really hope I am wrong here but I can't seem to find anything that contradicts the above.
Anyone got any comments / hints or sympathy?
Rather than listening for ICMP responses to your failed UDP sends, why not send a brand spanking new ICMP echo request?
When you get the exception, you could PInvoke the IcmpSendEcho() function (from Win32 IP Helper API) to generate a new ICMP echo request yourself. The key bit is that the function returns a buffer with the echo reply in it, including status codes e.g. IP_DEST_HOST_UNREACHABLE.
I don't think you need any special privileges to do this, so it should be easier than listening for ICMP replies with raw sockets.
You will need three functions: IcmpCreateFile(), IcmpSendEcho() and IcmpCloseHandle() - PInvoke.net has the necessary interop details:
http://www.pinvoke.net/default.aspx/icmp/IcmpCreateFile.html
http://www.pinvoke.net/default.aspx/icmp/IcmpSendEcho.html
http://www.pinvoke.net/default.aspx/icmp/IcmpCloseHandle.html
Had exactly the same issue myself Listen for ICMP packets in C#. Actually looks like your issue is windows permissions so that post won't help.
One area I was planning on delving into a bit further is to check whether there is anymore information in the SocketException generated by the UdpListener. It just seems unreasonable that as Windows is using the ICMP packet to generate the exception it wouldn't be recording the information in that packet somewhere.
Like you I have not been able to get very far with getting the ICMP info out of the exception information at the .Net level but I want to see if there is anything further that can be obtained with the Win32 API such as GetLastError or some other calls specifically for WinSock32.
From the MSDN website:
To use a socket of type SOCK_RAW
requires administrative privileges.
Users running Winsock applications
that use raw sockets must be a member
of the Administrators group on the
local computer, otherwise raw socket
calls will fail with an error code of
WSAEACCES. On Windows Vista and later,
access for raw sockets is enforced at
socket creation. In earlier versions
of Windows, access for raw sockets is
enforced during other socket
operations.
To get around this problem in my project , I've created a Windows service that serves as a network proxy for our UI application. The Windows serves runs under the local admin account in order to get around the limitations. The application connects to the service using WCF, telling it what kind of socket to open and what filter(s) to apply. The data is then sent back via callback using Protocol Buffers for encoding (at least that's the plan - the callback part is still in progress).

Checking IP Port State Remotely

I found an article on getting active tcp/udp connections on a machine.
http://www.codeproject.com/KB/IP/iphlpapi.aspx
My issue however is I need to be able to determine active connections remotely - to see if a particular port is running or listening without tampering with the machine.
Is this possible?
Doesn't seem like it natively, otherwise it could pose a security issue. The alternative would be to query a remoting service which could then make the necessary calls on the local machine.
Any thoughts?
Nmap is what you are looking for.
There is no way to know which ports are open without the remote computer knowing it. But you can determine the information without the program running on the port knowing it (i.e. without interfering with the program).
Use SYN scanning:
To establish a connection, TCP uses a three-way handshake. This can be exploited to find out if a port is open or not without the program knowing.
The handshake works as follows:
The client performs an active open by sending a SYN to the server.
The server replies with a SYN-ACK.
Normally, the client sends an ACK back to the server. But this step is skipped.
SYN scan is the most popular form of
TCP scanning. Rather than use the
operating system's network functions,
the port scanner generates raw IP
packets itself, and monitors for
responses. This scan type is also
known as "half-open scanning", because
it never actually opens a full TCP
connection. The port scanner generates
a SYN packet. If the target port is
open, it will respond with a SYN-ACK
packet. The scanner host responds with
a RST packet, closing the connection
before the handshake is completed.
The use of raw networking has several
advantages, giving the scanner full
control of the packets sent and the
timeout for responses, and allowing
detailed reporting of the responses.
There is debate over which scan is
less intrusive on the target host. SYN
scan has the advantage that the
individual services never actually
receive a connection while some
services can be crashed with a connect
scan. However, the RST during the
handshake can cause problems for some
network stacks, particularly simple
devices like printers. There are no
conclusive arguments either way.
Source Wikipedia
As is mentioned below, I think nmap can do SYN scanning.
Using sockets for TCP port scanning:
One way to determine which ports are open is to open a socket to that port. Or to a different port which finds out the information for you like you mentioned.
For example from command prompt or a terminal:
telnet google.com 80
UDP Port scanning:
if a UDP packet is sent to a port that is not open, the system will respond with an ICMP port unreachable message. You can use this method to determine if a port is open or close. But the receiving program will know.
neouser99 (et al) has suggested NMAP. NMAP is very good if all you're trying to do is to detect ports that are open on the remote machine.
But from the sounds of your question you're actually trying to determine what ports are both open and connected on your remote machine. If you're after a general monitoring solution, including the connected ports, then you could install an snmp server on your remote machine. There are two MIBs that let you check for port status which are TCP-MIB::tcpConnectionTable and UDP-MIB::udpEndpointTable.
The daemon (server) supplied in net-snmp has most likely got support for these mibs.

Categories

Resources