-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPacketCrafter.cs
More file actions
414 lines (330 loc) · 13.2 KB
/
Copy pathPacketCrafter.cs
File metadata and controls
414 lines (330 loc) · 13.2 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
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Runtime.InteropServices;
namespace SharpKit;
public enum EtherType : ushort
{
IPv4 = 0x0800,
IPv6 = 0x86DD,
ARP = 0x0806,
VLAN = 0x8100
}
public enum ArpOperation : ushort
{
Request = 1,
Reply = 2
}
public enum IpProtocol : byte
{
ICMP = 1,
TCP = 6,
UDP = 17
}
public enum DnsType : ushort
{
A = 1,
NS = 2,
CNAME = 5,
SOA = 6,
PTR = 12,
MX = 15,
AAAA = 28,
TXT = 16,
ANY = 255
}
public enum DnsClass : ushort
{
IN = 1,
ANY = 255
}
[Flags]
public enum TcpFlags : byte
{
FIN = 0x01,
SYN = 0x02,
RST = 0x04,
PSH = 0x08,
ACK = 0x10,
URG = 0x20
}
public static class PacketCrafter
{
public static byte[] BuildArpRequest(PhysicalAddress senderMac, IPAddress senderIp, IPAddress targetIp)
{
var packet = new byte[42];
var target = new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
var src = senderMac.GetAddressBytes();
var senderIpBytes = senderIp.GetAddressBytes();
var targetIpBytes = targetIp.GetAddressBytes();
Buffer.BlockCopy(target, 0, packet, 0, 6);
Buffer.BlockCopy(src, 0, packet, 6, 6);
packet[12] = (byte)((ushort)EtherType.ARP >> 8);
packet[13] = (byte)((ushort)EtherType.ARP & 0xFF);
packet[14] = 0x00; packet[15] = 0x01;
packet[16] = 0x08; packet[17] = 0x00;
packet[18] = 0x06;
packet[19] = 0x04;
var op = (ushort)ArpOperation.Request;
packet[20] = (byte)(op >> 8);
packet[21] = (byte)(op & 0xFF);
Buffer.BlockCopy(src, 0, packet, 22, 6);
Buffer.BlockCopy(senderIpBytes, 0, packet, 28, 4);
Buffer.BlockCopy(new byte[6], 0, packet, 32, 6);
Buffer.BlockCopy(targetIpBytes, 0, packet, 38, 4);
return packet;
}
public static byte[] BuildArpReply(PhysicalAddress senderMac, IPAddress senderIp, PhysicalAddress targetMac, IPAddress targetIp)
{
var packet = new byte[42];
var srcBytes = senderMac.GetAddressBytes();
var dstBytes = targetMac.GetAddressBytes();
var senderIpBytes = senderIp.GetAddressBytes();
var targetIpBytes = targetIp.GetAddressBytes();
Buffer.BlockCopy(dstBytes, 0, packet, 0, 6);
Buffer.BlockCopy(srcBytes, 0, packet, 6, 6);
packet[12] = (byte)((ushort)EtherType.ARP >> 8);
packet[13] = (byte)((ushort)EtherType.ARP & 0xFF);
packet[14] = 0x00; packet[15] = 0x01;
packet[16] = 0x08; packet[17] = 0x00;
packet[18] = 0x06;
packet[19] = 0x04;
var op = (ushort)ArpOperation.Reply;
packet[20] = (byte)(op >> 8);
packet[21] = (byte)(op & 0xFF);
Buffer.BlockCopy(srcBytes, 0, packet, 22, 6);
Buffer.BlockCopy(senderIpBytes, 0, packet, 28, 4);
Buffer.BlockCopy(dstBytes, 0, packet, 32, 6);
Buffer.BlockCopy(targetIpBytes, 0, packet, 38, 4);
return packet;
}
public static byte[] BuildDnsQuery(string hostname, DnsType queryType = DnsType.A, ushort transactionId = 0)
{
if (transactionId == 0)
transactionId = (ushort)Random.Shared.Next(1, 65535);
var ms = new MemoryStream();
ms.WriteByte((byte)(transactionId >> 8));
ms.WriteByte((byte)(transactionId & 0xFF));
ms.WriteByte(0x01); ms.WriteByte(0x00);
ms.WriteByte(0x00); ms.WriteByte(0x01);
ms.WriteByte(0x00); ms.WriteByte(0x00);
ms.WriteByte(0x00); ms.WriteByte(0x00);
ms.WriteByte(0x00); ms.WriteByte(0x00);
foreach (var label in hostname.Split('.'))
{
ms.WriteByte((byte)label.Length);
foreach (var c in label)
ms.WriteByte((byte)c);
}
ms.WriteByte(0x00);
var qt = (ushort)queryType;
ms.WriteByte((byte)(qt >> 8));
ms.WriteByte((byte)(qt & 0xFF));
var qc = (ushort)DnsClass.IN;
ms.WriteByte((byte)(qc >> 8));
ms.WriteByte((byte)(qc & 0xFF));
return ms.ToArray();
}
public static byte[] BuildDnsResponse(byte[] query, IPAddress[] answers)
{
if (query.Length < 12) throw new ArgumentException("Invalid DNS query");
var ms = new MemoryStream();
ms.Write(query, 0, query.Length);
ms.GetBuffer()[2] = 0x81;
ms.GetBuffer()[3] = 0x80;
var answerCount = (ushort)answers.Length;
ms.GetBuffer()[6] = (byte)(answerCount >> 8);
ms.GetBuffer()[7] = (byte)(answerCount & 0xFF);
foreach (var ip in answers)
{
ms.WriteByte(0xC0); ms.WriteByte(0x0C);
ms.WriteByte(0x00); ms.WriteByte((byte)DnsType.A);
ms.WriteByte(0x00); ms.WriteByte((byte)DnsClass.IN);
ms.WriteByte(0x00); ms.WriteByte(0x00);
ms.WriteByte(0x00); ms.WriteByte(0x3C);
ms.WriteByte(0x00); ms.WriteByte(0x04);
var ipBytes = ip.GetAddressBytes();
ms.Write(ipBytes, 0, 4);
}
return ms.ToArray();
}
public static byte[] BuildTcpSyn(IPAddress srcIp, IPAddress dstIp, ushort srcPort, ushort dstPort, uint sequenceNumber = 0)
{
if (sequenceNumber == 0)
sequenceNumber = (uint)Random.Shared.Next();
var ipHeader = BuildIpHeader(srcIp, dstIp, IpProtocol.TCP, 40);
var tcpHeader = BuildTcpHeader(srcPort, dstPort, sequenceNumber, 0, TcpFlags.SYN, 65535, 0, Array.Empty<byte>());
var pseudoHeader = BuildPseudoHeader(srcIp, dstIp, IpProtocol.TCP, (ushort)tcpHeader.Length);
var tcpChecksum = CalculateChecksum(Combine(pseudoHeader, tcpHeader));
tcpHeader[16] = (byte)(tcpChecksum >> 8);
tcpHeader[17] = (byte)(tcpChecksum & 0xFF);
return Combine(ipHeader, tcpHeader);
}
public static byte[] BuildTcpSynAck(IPAddress srcIp, IPAddress dstIp, ushort srcPort, ushort dstPort, uint seqNumber, uint ackNumber)
{
var ipHeader = BuildIpHeader(srcIp, dstIp, IpProtocol.TCP, 40);
var tcpHeader = BuildTcpHeader(srcPort, dstPort, seqNumber, ackNumber, TcpFlags.SYN | TcpFlags.ACK, 65535, 0, Array.Empty<byte>());
var pseudoHeader = BuildPseudoHeader(srcIp, dstIp, IpProtocol.TCP, (ushort)tcpHeader.Length);
var checksum = CalculateChecksum(Combine(pseudoHeader, tcpHeader));
tcpHeader[16] = (byte)(checksum >> 8);
tcpHeader[17] = (byte)(checksum & 0xFF);
return Combine(ipHeader, tcpHeader);
}
public static byte[] BuildTcpRst(IPAddress srcIp, IPAddress dstIp, ushort srcPort, ushort dstPort, uint seqNumber)
{
var ipHeader = BuildIpHeader(srcIp, dstIp, IpProtocol.TCP, 40);
var tcpHeader = BuildTcpHeader(srcPort, dstPort, seqNumber, 0, TcpFlags.RST, 0, 0, Array.Empty<byte>());
var pseudoHeader = BuildPseudoHeader(srcIp, dstIp, IpProtocol.TCP, (ushort)tcpHeader.Length);
var checksum = CalculateChecksum(Combine(pseudoHeader, tcpHeader));
tcpHeader[16] = (byte)(checksum >> 8);
tcpHeader[17] = (byte)(checksum & 0xFF);
return Combine(ipHeader, tcpHeader);
}
public static byte[] BuildUdpPacket(IPAddress srcIp, IPAddress dstIp, ushort srcPort, ushort dstPort, byte[] payload)
{
var udpLength = (ushort)(8 + payload.Length);
var ipHeader = BuildIpHeader(srcIp, dstIp, IpProtocol.UDP, (ushort)(20 + udpLength));
var udpHeader = new byte[8 + payload.Length];
udpHeader[0] = (byte)(srcPort >> 8);
udpHeader[1] = (byte)(srcPort & 0xFF);
udpHeader[2] = (byte)(dstPort >> 8);
udpHeader[3] = (byte)(dstPort & 0xFF);
udpHeader[4] = (byte)(udpLength >> 8);
udpHeader[5] = (byte)(udpLength & 0xFF);
Buffer.BlockCopy(payload, 0, udpHeader, 8, payload.Length);
var pseudoHeader = BuildPseudoHeader(srcIp, dstIp, IpProtocol.UDP, udpLength);
var checksum = CalculateChecksum(Combine(pseudoHeader, udpHeader));
udpHeader[6] = (byte)(checksum >> 8);
udpHeader[7] = (byte)(checksum & 0xFF);
return Combine(ipHeader, udpHeader);
}
public static async Task<List<ushort>> TcpSynScanAsync(IPAddress target, IEnumerable<ushort> ports, IPAddress sourceIp, TimeSpan timeout, CancellationToken ct = default)
{
var open = new List<ushort>();
foreach (var port in ports)
{
ct.ThrowIfCancellationRequested();
using var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
socket.Blocking = false;
try
{
await socket.ConnectAsync(new IPEndPoint(target, port), ct).ConfigureAwait(false);
open.Add(port);
}
catch (SocketException ex) when (ex.SocketErrorCode == SocketError.ConnectionRefused)
{
}
catch (SocketException)
{
using var cts = new CancellationTokenSource(timeout);
try
{
await socket.ConnectAsync(new IPEndPoint(target, port), cts.Token).ConfigureAwait(false);
open.Add(port);
}
catch { }
}
}
return open;
}
public static async Task<bool> SendDnsQueryAsync(string hostname, IPAddress dnsServer, int port = 53, DnsType queryType = DnsType.A, CancellationToken ct = default)
{
var query = BuildDnsQuery(hostname, queryType);
using var udpClient = new UdpClient();
await udpClient.SendAsync(query, query.Length, new IPEndPoint(dnsServer, port)).ConfigureAwait(false);
udpClient.Client.ReceiveTimeout = 3000;
try
{
var result = await udpClient.ReceiveAsync(ct).ConfigureAwait(false);
return result.Buffer.Length > 0 && (result.Buffer[2] & 0x80) != 0;
}
catch
{
return false;
}
}
private static byte[] BuildIpHeader(IPAddress srcIp, IPAddress dstIp, IpProtocol protocol, ushort totalLength)
{
var header = new byte[20];
header[0] = 0x45;
header[1] = 0x00;
header[2] = (byte)(totalLength >> 8);
header[3] = (byte)(totalLength & 0xFF);
var id = (ushort)Random.Shared.Next(1, 65535);
header[4] = (byte)(id >> 8);
header[5] = (byte)(id & 0xFF);
header[6] = 0x40; header[7] = 0x00;
header[8] = 64;
header[9] = (byte)protocol;
header[10] = 0x00; header[11] = 0x00;
var srcBytes = srcIp.GetAddressBytes();
var dstBytes = dstIp.GetAddressBytes();
Buffer.BlockCopy(srcBytes, 0, header, 12, 4);
Buffer.BlockCopy(dstBytes, 0, header, 16, 4);
var checksum = CalculateChecksum(header);
header[10] = (byte)(checksum >> 8);
header[11] = (byte)(checksum & 0xFF);
return header;
}
private static byte[] BuildTcpHeader(ushort srcPort, ushort dstPort, uint seqNum, uint ackNum, TcpFlags flags, ushort windowSize, ushort urgentPointer, byte[] options)
{
var headerLen = 20 + options.Length;
var dataOffset = (byte)((headerLen / 4) << 4);
var header = new byte[headerLen];
header[0] = (byte)(srcPort >> 8);
header[1] = (byte)(srcPort & 0xFF);
header[2] = (byte)(dstPort >> 8);
header[3] = (byte)(dstPort & 0xFF);
header[4] = (byte)(seqNum >> 24);
header[5] = (byte)(seqNum >> 16);
header[6] = (byte)(seqNum >> 8);
header[7] = (byte)(seqNum & 0xFF);
header[8] = (byte)(ackNum >> 24);
header[9] = (byte)(ackNum >> 16);
header[10] = (byte)(ackNum >> 8);
header[11] = (byte)(ackNum & 0xFF);
header[12] = dataOffset;
header[13] = (byte)flags;
header[14] = (byte)(windowSize >> 8);
header[15] = (byte)(windowSize & 0xFF);
header[16] = 0x00; header[17] = 0x00;
header[18] = (byte)(urgentPointer >> 8);
header[19] = (byte)(urgentPointer & 0xFF);
if (options.Length > 0)
Buffer.BlockCopy(options, 0, header, 20, options.Length);
return header;
}
private static byte[] BuildPseudoHeader(IPAddress srcIp, IPAddress dstIp, IpProtocol protocol, ushort length)
{
var pseudo = new byte[12];
Buffer.BlockCopy(srcIp.GetAddressBytes(), 0, pseudo, 0, 4);
Buffer.BlockCopy(dstIp.GetAddressBytes(), 0, pseudo, 4, 4);
pseudo[8] = 0x00;
pseudo[9] = (byte)protocol;
pseudo[10] = (byte)(length >> 8);
pseudo[11] = (byte)(length & 0xFF);
return pseudo;
}
private static ushort CalculateChecksum(byte[] data)
{
uint sum = 0;
int i = 0;
while (i < data.Length - 1)
{
sum += (uint)((data[i] << 8) | data[i + 1]);
i += 2;
}
if (i < data.Length)
sum += (uint)(data[i] << 8);
while ((sum >> 16) != 0)
sum = (sum & 0xFFFF) + (sum >> 16);
return (ushort)~sum;
}
private static byte[] Combine(byte[] a, byte[] b)
{
var result = new byte[a.Length + b.Length];
Buffer.BlockCopy(a, 0, result, 0, a.Length);
Buffer.BlockCopy(b, 0, result, a.Length, b.Length);
return result;
}
}