Repository navigation
Expand file tree
/
Copy pathRemoteShell.cs
More file actions
109 lines (98 loc) · 3.81 KB
/
Copy pathRemoteShell.cs
File metadata and controls
109 lines (98 loc) · 3.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace BlinkkShell
{
internal sealed class RemoteShell
{
private readonly int _port;
private readonly string _authPassword;
private readonly CancellationTokenSource _shutdown = new();
private TcpListener? _listener;
public RemoteShell(int port, string authPassword)
{
_port = port;
_authPassword = authPassword;
}
public async Task StartAsync()
{
_listener = new TcpListener(IPAddress.Any, _port);
_listener.Start();
Console.WriteLine($"Listening on all network interfaces, port {_port}.");
while (!_shutdown.IsCancellationRequested)
{
TcpClient client;
try
{
client = await _listener.AcceptTcpClientAsync(_shutdown.Token);
}
catch (OperationCanceledException) when (_shutdown.IsCancellationRequested)
{
break;
}
catch (SocketException) when (_shutdown.IsCancellationRequested)
{
break;
}
catch (ObjectDisposedException) when (_shutdown.IsCancellationRequested)
{
break;
}
_ = HandleClientAsync(client);
}
}
private async Task HandleClientAsync(TcpClient client)
{
string clientIp = ((IPEndPoint?)client.Client.RemoteEndPoint)?.Address.ToString() ?? "Unknown";
Console.WriteLine($"[+] Client connected | IP: {clientIp}");
try
{
using (client)
using (NetworkStream stream = client.GetStream())
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
using (StreamWriter writer = new StreamWriter(stream, new UTF8Encoding(false)) { AutoFlush = true })
{
try
{
string? authLine = await reader.ReadLineAsync();
if (authLine == null || !string.Equals(authLine.Trim(), _authPassword, StringComparison.Ordinal))
{
await writer.WriteLineAsync("AUTH_FAILED");
return;
}
await writer.WriteLineAsync("AUTH_SUCCESS");
string? inputLine;
while ((inputLine = await reader.ReadLineAsync()) != null)
{
inputLine = inputLine.Trim();
if (string.Equals(inputLine, "exit", StringComparison.OrdinalIgnoreCase))
{
await writer.WriteLineAsync("Closing connection...");
break;
}
string response = ShellHandles.ProcessCommand(inputLine);
await writer.WriteLineAsync(response);
await writer.WriteLineAsync("<END_OF_RESPONSE>");
}
}
catch (IOException)
{
}
catch (SocketException)
{
}
}
}
finally
{
Console.WriteLine($"[-] Client disconnected | IP: {clientIp}");
}
}
public void Stop()
{
_shutdown.Cancel();
_listener?.Stop();
}
}
}