Skip to content

Instantly share code, notes, and snippets.

@eladshamir
Created April 11, 2020 21:50
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save eladshamir/97161caa718b95160fa3b603edcfbc2a to your computer and use it in GitHub Desktop.
Save eladshamir/97161caa718b95160fa3b603edcfbc2a to your computer and use it in GitHub Desktop.
This simple program tunnels UDP DNS packets to a TCP port
using System;
using System.Net.Sockets;
using System.Net;
namespace DnsTunnel
{
class Program
{
static void OpenTunnel(int listenerPort, string targetHost, int targetPort)
{
try
{
// Create a UdpClient for listening
UdpClient UDPServer = new UdpClient(listenerPort);
// Create a TcpClient to forward messages to the the team server
TcpClient forwarder = new TcpClient(targetHost, targetPort);
NetworkStream stream = forwarder.GetStream();
while (true)
{
IPEndPoint source = new IPEndPoint(IPAddress.Any, 0);
// Block until a message is received
Byte[] data = UDPServer.Receive(ref source);
// Send data to the team server
stream.Write(data, 0, data.Length);
// Read the response
byte[] response = new byte[16384];
int numBytesRead = stream.Read(response, 0, response.Length);
// Send the response
UDPServer.Send(response, numBytesRead, source);
}
}
catch (Exception e)
{
Console.Error.WriteLine(e.ToString());
}
}
static void Main(string[] args)
{
int UDPPort;
int TCPPort;
if (args.Length != 3 || !(int.TryParse(args[0], out UDPPort) && int.TryParse(args[2], out TCPPort)))
{
Console.Error.WriteLine("Syntax Error. Please provide the following positional arguments:\n[Local UDP Port] [Remote TCP Host] [Remote TCP Port]\nExample: 53 127.0.0.1 53530");
return;
}
OpenTunnel(UDPPort, args[1], TCPPort);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment