-
Notifications
You must be signed in to change notification settings - Fork 17
/
SocketSniffer.cs
218 lines (186 loc) · 7.02 KB
/
SocketSniffer.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
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using Snifter.Filter;
using Snifter.Outputs;
namespace Snifter
{
public class SocketSniffer
{
private const int BUFFER_SIZE = 1024 * 64;
private const int MAX_RECEIVE = 100;
private bool isStopping;
private long packetsObserved;
private long packetsCaptured;
private Socket socket;
private readonly ConcurrentStack<SocketAsyncEventArgs> receivePool;
private readonly SemaphoreSlim maxReceiveEnforcer = new SemaphoreSlim(MAX_RECEIVE, MAX_RECEIVE);
private readonly BufferManager bufferManager;
private readonly BlockingCollection<TimestampedData> outputQueue;
private readonly Filters<IPPacket> filters;
private readonly IOutput output;
public long PacketsObserved => this.packetsObserved;
public long PacketsCaptured => this.packetsCaptured;
public SocketSniffer(NetworkInterfaceInfo nic, Filters<IPPacket> filters, IOutput output)
{
this.outputQueue = new BlockingCollection<TimestampedData>();
this.filters = filters;
this.output = output;
this.bufferManager = new BufferManager(BUFFER_SIZE, MAX_RECEIVE);
this.receivePool = new ConcurrentStack<SocketAsyncEventArgs>();
var endPoint = new IPEndPoint(nic.IPAddress, 0);
// Capturing at the IP level is not supported on Linux
// https://github.com/dotnet/corefx/issues/25115
// https://github.com/dotnet/corefx/issues/30197
var protocolType = SystemInformation.IsWindows
? ProtocolType.IP
: ProtocolType.Tcp;
// IPv4
this.socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, protocolType);
this.socket.Bind(endPoint);
this.socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, true);
// Enter promiscuous mode on Windows only
if (SystemInformation.IsWindows)
{
EnterPromiscuousMode();
}
}
private void EnterPromiscuousMode()
{
try
{
this.socket.IOControl(IOControlCode.ReceiveAll, BitConverter.GetBytes(1), new byte[4]);
}
catch (Exception ex)
{
Console.WriteLine("Unable to enter promiscuous mode: {0}", ex);
throw;
}
}
public void Start()
{
// Pre-allocate pool of SocketAsyncEventArgs for receive operations
for (var i = 0; i < MAX_RECEIVE; i++)
{
var socketEventArgs = new SocketAsyncEventArgs();
socketEventArgs.Completed += (e, args) => Receive(socketEventArgs);
// Allocate space from the single, shared buffer
this.bufferManager.AssignSegment(socketEventArgs);
this.receivePool.Push(socketEventArgs);
}
Task.Factory.StartNew(() =>
{
// GetConsumingEnumerable() will wait when queue is empty, until CompleteAdding() is called
foreach (var timestampedData in this.outputQueue.GetConsumingEnumerable())
{
Output(timestampedData);
}
});
Task.Factory.StartNew(StartReceiving);
}
public void Stop()
{
this.isStopping = true;
}
private void EnqueueOutput(TimestampedData timestampedData)
{
if (this.isStopping)
{
this.outputQueue.CompleteAdding();
return;
}
this.outputQueue.Add(timestampedData);
}
private void Output(TimestampedData timestampedData)
{
// Only parse the packet header if we need to filter
if (this.filters.PropertyFilters.Any())
{
var packet = new IPPacket(timestampedData.Data);
if (!this.filters.IsMatch(packet))
{
return;
}
}
this.output.Output(timestampedData);
Interlocked.Increment(ref this.packetsCaptured);
}
private void StartReceiving()
{
try
{
// Get SocketAsyncEventArgs from pool
this.maxReceiveEnforcer.Wait();
if (!this.receivePool.TryPop(out var socketEventArgs))
{
// Because we are controlling access to pooled SocketAsyncEventArgs, this
// *should* never happen...
throw new Exception("Connection pool exhausted");
}
// Returns true if the operation will complete asynchronously, or false if it completed
// synchronously
var willRaiseEvent = this.socket.ReceiveAsync(socketEventArgs);
if (!willRaiseEvent)
{
Receive(socketEventArgs);
}
}
catch (Exception ex)
{
// Exceptions while shutting down are expected
if (!this.isStopping)
{
Console.WriteLine(ex);
}
this.socket.Close();
this.socket = null;
}
}
private void Receive(SocketAsyncEventArgs e)
{
// Start a new receive operation straight away, without waiting
StartReceiving();
try
{
if (e.SocketError != SocketError.Success)
{
if (!this.isStopping)
{
Console.WriteLine("Socket error: {0}", e.SocketError);
}
return;
}
if (e.BytesTransferred <= 0)
{
return;
}
Interlocked.Increment(ref this.packetsObserved);
// Copy the bytes received into a new buffer
var buffer = new byte[e.BytesTransferred];
Buffer.BlockCopy(e.Buffer, e.Offset, buffer, 0, e.BytesTransferred);
EnqueueOutput(new TimestampedData(DateTime.UtcNow, buffer));
}
catch (SocketException ex)
{
Console.WriteLine("Socket error: {0}", ex);
}
catch (Exception ex)
{
Console.WriteLine("Error: {0}", ex);
}
finally
{
// Put the SocketAsyncEventArgs back into the pool
if (!this.isStopping && this.socket != null && this.socket.IsBound)
{
this.receivePool.Push(e);
this.maxReceiveEnforcer.Release();
}
}
}
}
}