Landon Kuhn
Landon Kuhn

Reputation: 78441

Using netcat (nc) as an HTTP proxy server and monitor

Is it possible to use the Unix netcat (nc) program to create a TCP proxy server and monitor? I would like all TCP traffic to be passed across the pipe, as well as sent to stdout for monitoring. Note this will be used for monitoring HTTP traffic between a hardware device and an HTTP server.

Upvotes: 21

Views: 30851

Answers (5)

Antoine Martin
Antoine Martin

Reputation: 1257

Just had the need yesterday. You can find the answer here (french) : http://www.linux-france.org/~mdecore/linux/doc/memo2/node168.html

mknod backpipe p
nc -l -p 80 < backpipe | tee -a in | nc localhost 8080 | tee -a out.html > backpipe

This listens on port 80 and redirect on port 8080. Incoming traffic will be present in the in file, outgoing traffic in the out.html file.The named pipe is needed for the connection to be bi-directional.

Upvotes: 22

symcbean
symcbean

Reputation: 48367

It'd be tricky to set up so it worked properly. A better solution would be to use a proper proxy (e.g. squid) or just sniff the traffic (wireshark, pastmon).

Upvotes: 0

Tom Anderson
Tom Anderson

Reputation: 47213

Yeah, should be possible.

When i [asked about writing a web server in bash1 on a newsgroup, i ended up with two decent ideas. One was to use xinetd as the actual server, and have it run a shell script for each connection; in your case, the script could then use tee and nc to forward and log the connection (with some file descriptor trickery to get a tee on each stream, i think). The other was to use socat, which effectively lets you write a fully operational server, with listening sockets and handler subprocesses, in bash; again, you would want tee and netcat to do the logging and proxying.

If you want a proper proxy server, than as @Spacedman says, you'd need to interpret the request line, but that's easy enough - read the first line, apply cut -d ' ' -f 2 to get the URL, some sed or shell string operators to pull out the domain and port, and continue. If you know upfront that all traffic is going to one endpoint, though, then you can hardwire it.

Upvotes: 0

Spacedman
Spacedman

Reputation: 94222

Not netcat on its own, since it would have to interpret the HTTP request and pass it on. For example, an HTTP request through a proxy starts with:

GET http://www.example.org/ HTTP/1.1

which your proxy then has to go, 'okay, I gotta connect to example.org and GET /'.

Now this could maybe be done by piping the nc output into a script which parses the HTTP req and then calls 'wget' to get the page, then slurp that back through netcat... oh heck, why?

Apache, or squid can probably do the job.

Upvotes: 2

J&#233; Queue
J&#233; Queue

Reputation: 10637

Sure, you can use it or a faucet|hose pair, but why do that when you can have a minimal Apache instance do the exact same thing and provide a more feature-full set of analysis?

Upvotes: 0

Related Questions