This repository has been archived by the owner on Aug 26, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 13
/
netstat.cs
325 lines (276 loc) · 14.2 KB
/
netstat.cs
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
// Source: https://docs.microsoft.com/en-us/dotnet/api/system.environment.getcommandlineargs?view=net-5.0
// Source: https://social.msdn.microsoft.com/Forums/vstudio/en-US/9c28a7b0-9ee1-425e-8aa0-afeac329a983/list-of-installed-devices-and-drivers-using-cnet?forum=csharpgeneral
// Source: https://docs.microsoft.com/en-us/dotnet/api/system.management.managementobjectsearcher.scope?view=dotnet-plat-ext-6.0#system-management-managementobjectsearcher-scope
// To Compile:
// C:\Windows\Microsoft.NET\Framework\v3.5\csc.exe /t:exe /out:netstat.exe netstat.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Management;
namespace Netstat
{
public class Program
{
private static void WriteOutput(string outputFilepath, List<string> output)
{
if (outputFilepath != "")
{
Console.WriteLine("[*] Writing output to: {0}", outputFilepath);
System.IO.File.WriteAllLines(outputFilepath, output.ToArray());
}
else
{
foreach (string line in output)
{
Console.WriteLine(line);
}
}
}
private static void PrintUsage()
{
Console.WriteLine(@"Lists listening TCP and UDP ports, and active TCP connection (equivalent to 'netstat -ano'); optionally writes output to a file
USAGE:
netstat.exe [/S <system> [/U [domain\]username /P password]] [/O <output_filepath>] [TCP | UDP]
Examples:
netstat.exe
netstat.exe tcp
netstat.exe -S DC01.MGMT.LOCAL
netstat.exe -S DC01.MGMT.LOCAL -U MGMT\Administrator -P password");
}
public static void Main()
{
try
{
string outputFilepath = "";
string system = ".";
string username = "";
string password = "";
string protocol = "";
// Parse arguments
string[] args = Environment.GetCommandLineArgs();
for (int i = 1; i < args.Length; i++)
{
string arg = args[i];
switch (arg.ToUpper())
{
case "-O":
case "/O":
i++;
try
{
outputFilepath = args[i];
if (File.Exists(outputFilepath))
{
throw new ArgumentException("Output file already exists");
}
}
catch (IndexOutOfRangeException)
{
throw new ArgumentException("No output file specified");
}
break;
case "-S":
case "/S":
i++;
try
{
system = args[i];
}
catch (IndexOutOfRangeException)
{
throw new ArgumentException("No system specified");
}
break;
case "-U":
case "/U":
i++;
try
{
username = args[i];
}
catch (IndexOutOfRangeException)
{
throw new ArgumentException("No username specified");
}
break;
case "-P":
case "/P":
i++;
try
{
password = args[i];
}
catch (IndexOutOfRangeException)
{
throw new ArgumentException("No password specified");
}
break;
case "/?":
PrintUsage();
return;
default:
protocol = args[i].ToUpper();
if (!(protocol.Equals("TCP") || protocol.Equals("UDP")))
{
throw new ArgumentException("Invalid protocol specified");
}
break;
}
}
ConnectionOptions conn_opts = new ConnectionOptions();
// Apply username and password if specified
if (username.Length > 0 && password.Length > 0)
{
conn_opts.Username = username;
conn_opts.Password = password;
}
else if (username.Length > 0 || password.Length > 0)
{
// Throw an exception if username or password were specified, but not both
throw new ArgumentException("Please specify username and password");
}
// Keep track of the max length of each entry in order to dynamically space the columns
int localAddrMaxSize = 13; // Length of "Local Address"
int remoteAddrMaxSize = 15; // Length of "Foreign Address"
int stateMaxSize = 5; // Length of "State"
int colPadding = 4;
Dictionary<string, string> entry;
List<Dictionary<string, string>> entries = new List<Dictionary<string, string>>();
// Lookup table for TCP connection states
Dictionary<string, string> tcpStates = new Dictionary<string, string>();
tcpStates.Add("1", "Closed");
tcpStates.Add("2", "LISTENING");
tcpStates.Add("3", "SYN_SENT");
tcpStates.Add("4", "SYN_RECEIVED");
tcpStates.Add("5", "ESTABLISHED");
tcpStates.Add("6", "FIN_WAIT1");
tcpStates.Add("7", "FIN_WAIT2");
tcpStates.Add("8", "CLOSE_WAIT");
tcpStates.Add("9", "CLOSING");
tcpStates.Add("10", "LAST_ACK");
tcpStates.Add("11", "TIME_WAIT");
tcpStates.Add("12", "DELETE_TCB");
tcpStates.Add("100", "BOUND");
ManagementPath path = new ManagementPath() { NamespacePath = @"root\standardcimv2", Server = system };
ManagementScope scope = new ManagementScope(path, conn_opts);
SelectQuery query;
// Display TCP if it's specified or no protocol was specified
if (protocol.Equals("TCP") || protocol.Equals(""))
{
// Query for TCP ports and connections; return specified attributes
query = new SelectQuery("MSFT_NetTCPConnection", null, new string[] { "LocalAddress", "LocalPort", "RemoteAddress", "RemotePort", "State", "OwningProcess" });
using (var searcher = new ManagementObjectSearcher(scope, query))
{
foreach (ManagementObject obj in searcher.Get())
{
if (obj != null)
{
entry = new Dictionary<string, string>();
entry.Add("protocol", "TCP");
// Use a lookup to convert the state code into a human-readable string
entry.Add("state", tcpStates[obj.GetPropertyValue("State").ToString()]);
entry.Add("pid", obj.GetPropertyValue("OwningProcess").ToString());
if (obj.GetPropertyValue("LocalAddress").ToString().Contains(":"))
{
// IPv6 address
entry.Add("local_address", "[" + obj.GetPropertyValue("LocalAddress").ToString() + "]:" + obj.GetPropertyValue("LocalPort").ToString());
entry.Add("remote_address", "[" + obj.GetPropertyValue("RemoteAddress").ToString() + "]:" + obj.GetPropertyValue("RemotePort").ToString());
}
else
{
// IPv4 address
entry.Add("local_address", obj.GetPropertyValue("LocalAddress").ToString() + ":" + obj.GetPropertyValue("LocalPort").ToString());
entry.Add("remote_address", obj.GetPropertyValue("RemoteAddress").ToString() + ":" + obj.GetPropertyValue("RemotePort").ToString());
}
entries.Add(entry);
// Calculate the max length of each column (for dynamic spacing)
if (entry["local_address"].Length > localAddrMaxSize)
{
localAddrMaxSize = entry["local_address"].Length;
}
if (entry["remote_address"].Length > remoteAddrMaxSize)
{
remoteAddrMaxSize = entry["remote_address"].Length;
}
if (entry["state"].Length > stateMaxSize)
{
stateMaxSize = entry["state"].Length;
}
}
}
}
}
// Display UDP if it's specified or no protocol was specified
if (protocol.Equals("UDP") || protocol.Equals(""))
{
// Query for UDP ports; return specified attributes
query = new SelectQuery("MSFT_NetUDPEndpoint", null, new string[] { "LocalAddress", "LocalPort", "OwningProcess" });
using (var searcher = new ManagementObjectSearcher(scope, query))
{
foreach (ManagementObject obj in searcher.Get())
{
if (obj != null)
{
entry = new Dictionary<string, string>();
entry.Add("protocol", "UDP");
entry.Add("state", "");
entry.Add("remote_address", "*:*");
entry.Add("pid", obj.GetPropertyValue("OwningProcess").ToString());
if (obj.GetPropertyValue("LocalAddress").ToString().Contains(":"))
{
// IPv6 address
entry.Add("local_address", "[" + obj.GetPropertyValue("LocalAddress").ToString() + "]:" + obj.GetPropertyValue("LocalPort").ToString());
}
else
{
// IPv4 address
entry.Add("local_address", obj.GetPropertyValue("LocalAddress").ToString() + ":" + obj.GetPropertyValue("LocalPort").ToString());
}
entries.Add(entry);
// Calculate the max length of the local address column (remote address and state and not populated)
if (entry["local_address"].Length > localAddrMaxSize)
{
localAddrMaxSize = entry["local_address"].Length;
}
}
}
}
}
// Add extra padding to separate the columns
localAddrMaxSize += colPadding;
remoteAddrMaxSize += colPadding;
stateMaxSize += colPadding;
List<string> output = new List<string>();
string line;
// Convert dictionary of network entries to a string with each column dynamically padded
foreach (Dictionary<string, string> row in entries)
{
line = " " + row["protocol"] + " ";
line += row["local_address"].PadRight(localAddrMaxSize);
line += row["remote_address"].PadRight(remoteAddrMaxSize);
line += row["state"].PadRight(stateMaxSize);
line += row["pid"];
output.Add(line);
}
// Sort the output to make it look cleaner
output.Sort();
// Prepend table header after sorting
line = "\nActive Connections\n\n Proto ";
line += "Local Address".PadRight(localAddrMaxSize);
line += "Foreign Address".PadRight(remoteAddrMaxSize);
line += "State".PadRight(stateMaxSize);
line += "PID";
output.Insert(0, line);
WriteOutput(outputFilepath, output);
}
catch (Exception e)
{
Console.Error.WriteLine("[-] ERROR: {0}", e.Message.Trim());
}
finally
{
Console.WriteLine("\nDONE");
}
}
}
}