-
Notifications
You must be signed in to change notification settings - Fork 104
/
EthernetPacket.cs
357 lines (315 loc) · 13.1 KB
/
EthernetPacket.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
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
/*
This file is part of PacketDotNet.
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
using System;
using System.Collections.Generic;
using System.Net.NetworkInformation;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using PacketDotNet.Utils;
using PacketDotNet.Utils.Converters;
#if DEBUG
using log4net;
using System.Reflection;
#endif
namespace PacketDotNet
{
/// <summary>
/// See http://en.wikipedia.org/wiki/Ethernet#Ethernet_frame_types_and_the_EtherType_field
/// </summary>
public sealed class EthernetPacket : InternetLinkLayerPacket
{
#if DEBUG
private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
#else
// NOTE: No need to warn about lack of use, the compiler won't
// put any calls to 'log' here but we need 'log' to exist to compile
#pragma warning disable 0169, 0649
private static readonly ILogInactive Log;
#pragma warning restore 0169, 0649
#endif
/// <summary>
/// Construct a new ethernet packet from source and destination mac addresses
/// </summary>
public EthernetPacket
(
PhysicalAddress sourceHardwareAddress,
PhysicalAddress destinationHardwareAddress,
EthernetType ethernetType)
{
Log.Debug("");
// allocate memory for this packet
var length = EthernetFields.HeaderLength;
var headerBytes = new byte[length];
Header = new ByteArraySegment(headerBytes, 0, length);
// set the instance values
SourceHardwareAddress = sourceHardwareAddress;
DestinationHardwareAddress = destinationHardwareAddress;
Type = ethernetType;
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="byteArraySegment">
/// A <see cref="ByteArraySegment" />
/// </param>
public EthernetPacket(ByteArraySegment byteArraySegment)
{
Log.Debug("");
// slice off the header portion
// ReSharper disable once UseObjectOrCollectionInitializer
Header = new ByteArraySegment(byteArraySegment);
Header.Length = EthernetFields.HeaderLength;
// parse the encapsulated bytes
PayloadPacketOrData = new LazySlim<PacketOrByteArraySegment>(() => ParseNextSegment(Header, Type));
}
/// <summary>Fetch ascii escape sequence of the color associated with this packet type.</summary>
public override string Color => AnsiEscapeSequences.DarkGray;
/// <summary>MAC address of the host where the packet originated from.</summary>
public PhysicalAddress DestinationHardwareAddress
{
get
{
var hwAddress = new byte[EthernetFields.MacAddressLength];
var start = Header.Offset + EthernetFields.DestinationMacPosition;
Unsafe.WriteUnaligned(ref hwAddress[0], Unsafe.As<byte, int>(ref Header.Bytes[start]));
Unsafe.WriteUnaligned(ref hwAddress[4], Unsafe.As<byte, short>(ref Header.Bytes[start + 4]));
return new PhysicalAddress(hwAddress);
}
set
{
var hwAddress = value.GetAddressBytes();
if (hwAddress.Length != EthernetFields.MacAddressLength)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);
var start = Header.Offset + EthernetFields.DestinationMacPosition;
Unsafe.WriteUnaligned(ref Header.Bytes[start], Unsafe.As<byte, int>(ref hwAddress[0]));
Unsafe.WriteUnaligned(ref Header.Bytes[start + 4], Unsafe.As<byte, short>(ref hwAddress[4]));
}
}
/// <value>
/// Payload packet, overridden to set the 'Type' field based on
/// the type of packet being used here if the PayloadPacket is being set
/// </value>
public override Packet PayloadPacket
{
get => base.PayloadPacket;
set
{
base.PayloadPacket = value;
switch (value)
{
// set Type based on the type of the payload
case IPv4Packet _:
{
Type = EthernetType.IPv4;
break;
}
case IPv6Packet _:
{
Type = EthernetType.IPv6;
break;
}
case ArpPacket _:
{
Type = EthernetType.Arp;
break;
}
case LldpPacket _:
{
Type = EthernetType.Lldp;
break;
}
// NOTE: new types should be inserted here
case PppoePacket _:
{
Type = EthernetType.PppoeSessionStage;
break;
}
default:
{
Type = EthernetType.None;
break;
}
}
}
}
/// <summary>MAC address of the host where the packet originated from.</summary>
public PhysicalAddress SourceHardwareAddress
{
get
{
var hwAddress = new byte[EthernetFields.MacAddressLength];
var start = Header.Offset + EthernetFields.SourceMacPosition;
Unsafe.WriteUnaligned(ref hwAddress[0], Unsafe.As<byte, int>(ref Header.Bytes[start]));
Unsafe.WriteUnaligned(ref hwAddress[4], Unsafe.As<byte, short>(ref Header.Bytes[start + 4]));
return new PhysicalAddress(hwAddress);
}
set
{
var hwAddress = value.GetAddressBytes();
if (hwAddress.Length != EthernetFields.MacAddressLength)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);
var start = Header.Offset + EthernetFields.SourceMacPosition;
Unsafe.WriteUnaligned(ref Header.Bytes[start], Unsafe.As<byte, int>(ref hwAddress[0]));
Unsafe.WriteUnaligned(ref Header.Bytes[start + 4], Unsafe.As<byte, short>(ref hwAddress[4]));
}
}
/// <value>
/// Type of packet that this ethernet packet encapsulates.
/// </value>
public EthernetType Type
{
get => (EthernetType) EndianBitConverter.Big.ToInt16(Header.Bytes,
Header.Offset + EthernetFields.TypePosition);
set
{
var val = (short) value;
EndianBitConverter.Big.CopyBytes(val,
Header.Bytes,
Header.Offset + EthernetFields.TypePosition);
}
}
/// <summary>
/// Used by the EthernetPacket constructor. Located here because the LinuxSll constructor
/// also needs to perform the same operations as it contains an ethernet type
/// </summary>
/// <param name="header">
/// A <see cref="ByteArraySegment" />
/// </param>
/// <param name="type">
/// A <see cref="EthernetType" />
/// </param>
/// <returns>
/// A <see cref="PacketOrByteArraySegment" />
/// </returns>
internal static PacketOrByteArraySegment ParseNextSegment
(
ByteArraySegment header,
EthernetType type)
{
// slice off the payload
var payload = header.NextSegment();
Log.DebugFormat("payload {0}", payload);
var payloadPacketOrData = new PacketOrByteArraySegment();
// parse the encapsulated bytes
switch (type)
{
case EthernetType.IPv4:
{
payloadPacketOrData.Packet = new IPv4Packet(payload);
break;
}
case EthernetType.IPv6:
{
payloadPacketOrData.Packet = new IPv6Packet(payload);
break;
}
case EthernetType.Arp:
{
payloadPacketOrData.Packet = new ArpPacket(payload);
break;
}
case EthernetType.Lldp:
{
payloadPacketOrData.Packet = new LldpPacket(payload);
break;
}
case EthernetType.PppoeSessionStage:
{
payloadPacketOrData.Packet = new PppoePacket(payload);
break;
}
case EthernetType.WakeOnLan:
{
payloadPacketOrData.Packet = new WakeOnLanPacket(payload);
break;
}
case EthernetType.VLanTaggedFrame:
{
payloadPacketOrData.Packet = new Ieee8021QPacket(payload);
break;
}
default: // consider the sub-packet to be a byte array
{
payloadPacketOrData.ByteArraySegment = payload;
break;
}
}
return payloadPacketOrData;
}
/// <summary cref="Packet.ToString(StringOutputType)" />
public override string ToString(StringOutputType outputFormat)
{
var buffer = new StringBuilder();
var color = "";
var colorEscape = "";
if (outputFormat == StringOutputType.Colored || outputFormat == StringOutputType.VerboseColored)
{
color = Color;
colorEscape = AnsiEscapeSequences.Reset;
}
switch (outputFormat)
{
case StringOutputType.Normal:
case StringOutputType.Colored:
{
// build the output string
buffer.AppendFormat("{0}[EthernetPacket: SourceHardwareAddress={2}, DestinationHardwareAddress={3}, Type={4}]{1}",
color,
colorEscape,
HexPrinter.PrintMACAddress(SourceHardwareAddress),
HexPrinter.PrintMACAddress(DestinationHardwareAddress),
Type.ToString());
break;
}
case StringOutputType.Verbose:
case StringOutputType.VerboseColored:
{
// collect the properties and their value
var properties = new Dictionary<string, string>
{
{ "destination", HexPrinter.PrintMACAddress(DestinationHardwareAddress) },
{ "source", HexPrinter.PrintMACAddress(SourceHardwareAddress) },
{ "type", Type + " (0x" + Type.ToString("x") + ")" }
};
// calculate the padding needed to right-justify the property names
var padLength = RandomUtils.LongestStringLength(new List<string>(properties.Keys));
// build the output string
buffer.AppendLine("Eth: ******* Ethernet - \"Ethernet\" - offset=? length=" + TotalPacketLength);
buffer.AppendLine("Eth:");
foreach (var property in properties)
{
buffer.AppendLine("Eth: " + property.Key.PadLeft(padLength) + " = " + property.Value);
}
buffer.AppendLine("Eth:");
break;
}
}
// append the base output
buffer.Append(base.ToString(outputFormat));
return buffer.ToString();
}
/// <summary>
/// Generate a random EthernetPacket
/// TODO: could improve this routine to set a random payload as well
/// </summary>
/// <returns>
/// A <see cref="EthernetPacket" />
/// </returns>
public static EthernetPacket RandomPacket()
{
var rnd = new Random();
var srcPhysicalAddress = new byte[EthernetFields.MacAddressLength];
var dstPhysicalAddress = new byte[EthernetFields.MacAddressLength];
rnd.NextBytes(srcPhysicalAddress);
rnd.NextBytes(dstPhysicalAddress);
return new EthernetPacket(new PhysicalAddress(srcPhysicalAddress),
new PhysicalAddress(dstPhysicalAddress),
EthernetType.None);
}
}
}