This repository has been archived by the owner on Jan 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5k
/
DummyTcpServer.cs
316 lines (271 loc) · 9.73 KB
/
DummyTcpServer.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Net.Sockets;
using System.Net.Test.Common;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Security.Tests
{
// Callback method that is called when the server receives data from a connected client.
// The callback method should return a byte array and the number of bytes to send from that array.
public delegate void DummyTcpServerReceiveCallback(byte[] bufferReceived, int bytesReceived, Stream stream);
// Provides a dummy TCP/IP server that accepts connections and supports SSL/TLS.
// It normally echoes data received but can be configured to write a byte array
// specified by a callback method.
public class DummyTcpServer : IDisposable
{
private VerboseTestLogging _log;
private TcpListener _listener;
private bool _useSsl;
private SslProtocols _sslProtocols = SslProtocols.Tls12 | SslProtocols.Tls11 | SslProtocols.Tls;
private EncryptionPolicy _sslEncryptionPolicy;
private IPEndPoint _remoteEndPoint;
private DummyTcpServerReceiveCallback _receiveCallback;
private void StartListener(IPEndPoint endPoint)
{
_listener = new TcpListener(endPoint);
_listener.Start(5);
_log.WriteLine("Server {0} listening", endPoint.Address.ToString());
_listener.AcceptTcpClientAsync().ContinueWith(t => OnAccept(t), TaskScheduler.Default);
}
public DummyTcpServer(IPEndPoint endPoint) : this(endPoint, null)
{
}
public DummyTcpServer(IPEndPoint endPoint, EncryptionPolicy? sslEncryptionPolicy)
{
_log = VerboseTestLogging.GetInstance();
if (sslEncryptionPolicy != null)
{
_remoteEndPoint = endPoint;
_useSsl = true;
_sslEncryptionPolicy = (EncryptionPolicy)sslEncryptionPolicy;
}
StartListener(endPoint);
}
public IPEndPoint RemoteEndPoint
{
get { return (IPEndPoint)_listener.LocalEndpoint; }
}
public SslProtocols SslProtocols
{
get { return _sslProtocols; }
set { _sslProtocols = value; }
}
protected DummyTcpServerReceiveCallback ReceiveCallback
{
get { return _receiveCallback; }
set { _receiveCallback = value; }
}
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
_listener.Stop();
}
}
protected virtual void OnClientAccepted(TcpClient client)
{
}
private void OnAuthenticate(Task result, ClientState state)
{
SslStream sslStream = (SslStream)state.Stream;
try
{
result.GetAwaiter().GetResult();
_log.WriteLine("Server authenticated to client with encryption cipher: {0} {1}-bit strength",
sslStream.CipherAlgorithm, sslStream.CipherStrength);
// Start listening for data from the client connection.
sslStream.BeginRead(state.ReceiveBuffer, 0, state.ReceiveBuffer.Length, OnReceive, state);
}
catch (AuthenticationException authEx)
{
_log.WriteLine(
"Server disconnecting from client during authentication. No shared SSL/TLS algorithm. ({0})",
authEx);
}
catch (Exception ex)
{
_log.WriteLine("Server disconnecting from client during authentication. Exception: {0}",
ex.Message);
}
finally
{
state.Dispose();
}
}
private void OnAccept(Task<TcpClient> result)
{
TcpClient client = null;
// Accept current connection
try
{
client = result.Result;
}
catch
{
}
// If we have a connection, then process it
if (client != null)
{
OnClientAccepted(client);
ClientState state;
// Start authentication for SSL?
if (_useSsl)
{
state = new ClientState(client, _sslEncryptionPolicy);
_log.WriteLine("Server: starting SSL authentication.");
SslStream sslStream = null;
X509Certificate2 certificate = TestConfiguration.GetServerCertificate();
try
{
sslStream = (SslStream)state.Stream;
_log.WriteLine("Server: attempting to open SslStream.");
sslStream.AuthenticateAsServerAsync(certificate, false, _sslProtocols, false).ContinueWith(t => OnAuthenticate(t, state), TaskScheduler.Default);
}
catch (Exception ex)
{
_log.WriteLine("Server: Exception: {0}", ex);
state.Dispose(); // close connection to client
}
}
else
{
state = new ClientState(client);
// Start listening for data from the client connection
try
{
state.Stream.BeginRead(state.ReceiveBuffer, 0, state.ReceiveBuffer.Length, OnReceive, state);
}
catch
{
}
}
}
// Listen for more client connections
try
{
_listener.AcceptTcpClientAsync().ContinueWith(t => OnAccept(t), TaskScheduler.Default);
}
catch
{
}
}
private void OnReceive(IAsyncResult result)
{
ClientState state = (ClientState)result.AsyncState;
try
{
int bytesReceived = state.Stream.EndRead(result);
if (bytesReceived == 0)
{
state.Dispose();
return;
}
if (_receiveCallback != null)
{
_receiveCallback(state.ReceiveBuffer, bytesReceived, state.Stream);
}
else
{
// Echo back what we received
state.Stream.Write(state.ReceiveBuffer, 0, bytesReceived);
}
// Read more from client (asynchronous)
state.Stream.BeginRead(state.ReceiveBuffer, 0, state.ReceiveBuffer.Length, OnReceive, state);
}
catch (IOException)
{
state.Dispose();
return;
}
catch (SocketException)
{
state.Dispose();
return;
}
catch (ObjectDisposedException)
{
state.Dispose();
return;
}
}
// The following method is invoked by the RemoteCertificateValidationDelegate.
public static bool AlwaysValidServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true; // allow everything
}
private class ClientState
{
private TcpClient _tcpClient;
private byte[] _receiveBuffer;
private bool _useSsl;
private SslStream _sslStream;
private bool _closed;
public ClientState(TcpClient client)
{
_tcpClient = client;
_receiveBuffer = new byte[1024];
_useSsl = false;
_closed = false;
}
public ClientState(TcpClient client, EncryptionPolicy sslEncryptionPolicy)
{
_tcpClient = client;
_receiveBuffer = new byte[1024];
_useSsl = true;
_sslStream = new SslStream(client.GetStream(), false, AlwaysValidServerCertificate, null, sslEncryptionPolicy);
_closed = false;
}
public void Dispose()
{
if (!_closed)
{
if (_useSsl)
{
_sslStream.Dispose();
}
_tcpClient.Dispose();
_closed = true;
}
}
public TcpClient TcpClient
{
get { return _tcpClient; }
}
public byte[] ReceiveBuffer
{
get { return _receiveBuffer; }
}
public bool UseSsl
{
get { return _useSsl; }
}
public bool Closed
{
get { return _closed; }
}
public Stream Stream
{
get
{
if (_useSsl)
{
return _sslStream;
}
else
{
return _tcpClient.GetStream();
}
}
}
}
}
}