forked from sta/websocket-sharp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
410 lines (329 loc) · 12.8 KB
/
Copy pathProgram.cs
File metadata and controls
410 lines (329 loc) · 12.8 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
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using WebSocketSharp;
namespace SecureAndProxyClient
{
internal static class Program
{
private const string SampleHeaderName = "X-Client-Example";
private const string SampleHeaderValue = "SecureAndProxyClient";
private static int Main (string[] args)
{
ClientOptions options;
if (!ClientOptions.TryParse (args, out options)) {
PrintUsage ();
return 1;
}
if (options.ShowHelp || options.ServerUri == null) {
PrintUsage ();
return 0;
}
using (var ws = new WebSocket (options.ServerUri.OriginalString)) {
// Request permessage-deflate. The server may decline it during the
// handshake; websocket-sharp then continues without compression.
ws.Compression = options.UseCompression
? CompressionMethod.Deflate
: CompressionMethod.None;
// Bounds TCP connect, proxy CONNECT, WebSocket handshake, and for wss://
// also the TLS handshake.
ws.ConnectionTimeout = options.ConnectionTimeout;
// Redirects are opt-in, bounded, and do not permit wss:// to ws://
// downgrade unless it is explicitly requested.
ws.EnableRedirection = options.FollowRedirects;
ws.MaxRedirections = options.MaxRedirections;
ws.AllowInsecureRedirection = options.AllowInsecureRedirection;
if (!String.IsNullOrEmpty (options.Origin))
ws.Origin = options.Origin;
// User headers are sent in the opening handshake.
ws.SetUserHeader (SampleHeaderName, SampleHeaderValue);
foreach (var header in options.UserHeaders)
ws.SetUserHeader (header.Key, header.Value);
if (!String.IsNullOrEmpty (options.ProxyUrl))
ws.SetProxy (options.ProxyUrl, options.ProxyUsername, options.ProxyPassword);
if (options.ServerUri.Scheme == "wss") {
// Safe default: accept only certificates that pass platform validation.
// The local/dev exception below is opt-in and limited to loopback/local
// hosts, so it does not weaken production WSS connections by default.
ws.SslConfiguration.ServerCertificateValidationCallback =
(sender, certificate, chain, sslPolicyErrors) =>
ValidateServerCertificate (
ws.Url,
options.AllowLocalDevCertificate,
options.TrustedCertificateThumbprint,
certificate,
sslPolicyErrors
);
}
ws.OnOpen += (sender, e) => Console.WriteLine ("Connected.");
ws.OnMessage +=
(sender, e) => Console.WriteLine ("Message: {0}", e.IsText ? e.Data : "<binary>");
ws.OnError += (sender, e) => Console.WriteLine ("Error: {0}", e.Message);
ws.OnClose +=
(sender, e) => Console.WriteLine ("Closed: {0} {1}", e.Code, e.Reason);
Console.WriteLine ("Connecting to {0}", options.ServerUri);
ws.Connect ();
if (ws.ReadyState == WebSocketState.Open) {
ws.Send ("Hello from SecureAndProxyClient.");
ws.Close ();
}
}
return 0;
}
private static bool ValidateServerCertificate (
Uri serverUri,
bool allowLocalDevCertificate,
string trustedCertificateThumbprint,
X509Certificate certificate,
SslPolicyErrors sslPolicyErrors
)
{
if (sslPolicyErrors == SslPolicyErrors.None)
return true;
if (certificate == null)
return false;
if (!String.IsNullOrEmpty (trustedCertificateThumbprint) &&
CertificateMatchesThumbprint (certificate, trustedCertificateThumbprint)) {
Console.WriteLine (
"Accepting certificate for {0} by explicit thumbprint pin.",
serverUri.Host
);
return true;
}
if (!allowLocalDevCertificate || !IsLocalDevelopmentHost (serverUri))
return false;
const SslPolicyErrors allowedLocalDevErrors =
SslPolicyErrors.RemoteCertificateChainErrors;
if ((sslPolicyErrors & ~allowedLocalDevErrors) != 0)
return false;
Console.WriteLine (
"Accepting local development certificate for {0}: {1}",
serverUri.Host,
sslPolicyErrors
);
return true;
}
private static bool CertificateMatchesThumbprint (
X509Certificate certificate,
string expectedThumbprint
)
{
var certificate2 = certificate as X509Certificate2
?? new X509Certificate2 (certificate);
var shouldDispose = !(certificate is X509Certificate2);
try {
return String.Equals (
NormalizeThumbprint (certificate2.Thumbprint),
NormalizeThumbprint (expectedThumbprint),
StringComparison.OrdinalIgnoreCase
);
}
finally {
if (shouldDispose)
certificate2.Dispose ();
}
}
private static string NormalizeThumbprint (string value)
{
if (String.IsNullOrEmpty (value))
return String.Empty;
var normalized = new StringBuilder (value.Length);
foreach (var ch in value) {
if (Uri.IsHexDigit (ch))
normalized.Append (ch);
}
return normalized.ToString ();
}
private static bool IsLocalDevelopmentHost (Uri uri)
{
if (uri == null)
return false;
if (uri.IsLoopback)
return true;
return String.Equals (uri.Host, "localhost", StringComparison.OrdinalIgnoreCase)
|| uri.Host.EndsWith (".localhost", StringComparison.OrdinalIgnoreCase);
}
private static void PrintUsage ()
{
Console.WriteLine ("SecureAndProxyClient");
Console.WriteLine ();
Console.WriteLine ("Usage:");
Console.WriteLine (" SecureAndProxyClient.exe <ws-or-wss-url> [options]");
Console.WriteLine ();
Console.WriteLine ("No connection is opened unless a URL is supplied.");
Console.WriteLine ();
Console.WriteLine ("Options:");
Console.WriteLine (" --origin <origin> Send an Origin header.");
Console.WriteLine (" --header <name=value> Send an additional user header.");
Console.WriteLine (" --proxy <http-url> Connect through an HTTP proxy.");
Console.WriteLine (" --proxy-user <username> Proxy authentication user.");
Console.WriteLine (" --proxy-password <password> Proxy authentication password.");
Console.WriteLine (" --timeout <seconds> Connection timeout. Default: 10.");
Console.WriteLine (" --follow-redirects Follow at most 5 redirects.");
Console.WriteLine (" --max-redirects <0..100> Override the redirect limit.");
Console.WriteLine (" --allow-insecure-redirect Permit wss:// to ws:// downgrade.");
Console.WriteLine (" --no-compression Do not request permessage-deflate.");
Console.WriteLine (" --allow-local-dev-cert For wss:// localhost/loopback only,");
Console.WriteLine (" allow certificate chain errors.");
Console.WriteLine (" --trusted-thumbprint <hex> Pin a specific server certificate.");
Console.WriteLine (" --help Print this usage.");
Console.WriteLine ();
Console.WriteLine ("Examples:");
Console.WriteLine (" SecureAndProxyClient.exe wss://localhost:5963/Echo --allow-local-dev-cert");
Console.WriteLine (" SecureAndProxyClient.exe wss://localhost:5963/Echo --trusted-thumbprint <sha1>");
Console.WriteLine (" SecureAndProxyClient.exe wss://example.com/Echo --proxy http://localhost:3128");
Console.WriteLine (" SecureAndProxyClient.exe ws://localhost:4649/Chat --origin http://localhost:4649 --header RequestForID=ID");
}
}
internal sealed class ClientOptions
{
public bool AllowLocalDevCertificate { get; private set; }
public bool AllowInsecureRedirection { get; private set; }
public TimeSpan ConnectionTimeout { get; private set; }
public bool FollowRedirects { get; private set; }
public int MaxRedirections { get; private set; }
public string Origin { get; private set; }
public string ProxyPassword { get; private set; }
public string ProxyUrl { get; private set; }
public string ProxyUsername { get; private set; }
public Uri ServerUri { get; private set; }
public bool ShowHelp { get; private set; }
public string TrustedCertificateThumbprint { get; private set; }
public bool UseCompression { get; private set; }
public List<KeyValuePair<string, string>> UserHeaders { get; private set; }
public static bool TryParse (string[] args, out ClientOptions options)
{
options = new ClientOptions {
ConnectionTimeout = TimeSpan.FromSeconds (10),
MaxRedirections = 5,
UseCompression = true,
UserHeaders = new List<KeyValuePair<string, string>> ()
};
if (args == null || args.Length == 0)
return true;
for (var i = 0; i < args.Length; i++) {
var arg = args[i];
if (arg == "--help" || arg == "-h") {
options.ShowHelp = true;
continue;
}
if (arg == "--allow-local-dev-cert") {
options.AllowLocalDevCertificate = true;
continue;
}
if (arg == "--allow-insecure-redirect") {
options.AllowInsecureRedirection = true;
options.FollowRedirects = true;
continue;
}
if (arg == "--follow-redirects") {
options.FollowRedirects = true;
continue;
}
if (arg == "--no-compression") {
options.UseCompression = false;
continue;
}
if (arg == "--max-redirects") {
string value;
int count;
if (!TryReadValue (args, ref i, out value)
|| !Int32.TryParse (value, out count)
|| count < 0
|| count > 100)
return false;
options.FollowRedirects = true;
options.MaxRedirections = count;
continue;
}
if (arg == "--origin") {
string value;
if (!TryReadValue (args, ref i, out value))
return false;
options.Origin = value;
continue;
}
if (arg == "--header") {
string value;
if (!TryReadValue (args, ref i, out value))
return false;
var separator = value.IndexOf ('=');
if (separator <= 0)
return false;
options.UserHeaders.Add (
new KeyValuePair<string, string> (
value.Substring (0, separator),
value.Substring (separator + 1)
)
);
continue;
}
if (arg == "--proxy") {
string value;
if (!TryReadValue (args, ref i, out value))
return false;
options.ProxyUrl = value;
continue;
}
if (arg == "--proxy-user") {
string value;
if (!TryReadValue (args, ref i, out value))
return false;
options.ProxyUsername = value;
continue;
}
if (arg == "--proxy-password") {
string value;
if (!TryReadValue (args, ref i, out value))
return false;
options.ProxyPassword = value;
continue;
}
if (arg == "--timeout") {
string value;
double seconds;
if (!TryReadValue (args, ref i, out value) ||
!Double.TryParse (
value,
NumberStyles.Float,
CultureInfo.InvariantCulture,
out seconds
) ||
seconds <= 0)
return false;
options.ConnectionTimeout = TimeSpan.FromSeconds (seconds);
continue;
}
if (arg == "--trusted-thumbprint") {
string value;
if (!TryReadValue (args, ref i, out value))
return false;
options.TrustedCertificateThumbprint = value;
continue;
}
if (arg.StartsWith ("-", StringComparison.Ordinal))
return false;
if (options.ServerUri != null)
return false;
Uri serverUri;
if (!Uri.TryCreate (arg, UriKind.Absolute, out serverUri))
return false;
if (serverUri.Scheme != "ws" && serverUri.Scheme != "wss")
return false;
options.ServerUri = serverUri;
}
return true;
}
private static bool TryReadValue (string[] args, ref int index, out string value)
{
value = null;
if (index + 1 >= args.Length)
return false;
value = args[++index];
return !String.IsNullOrEmpty (value);
}
}
}