/
Program.cs
112 lines (104 loc) · 3.89 KB
/
Program.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
using System;
using System.Collections;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
namespace CertificateAuthBug
{
internal static class Program
{
private const string CertificatePath = "certificate.pfx";
private const string Password = "qwerty";
private const string ServerUrl = "https://localhost:8443";
private static void Main(string[] args)
{
// AppContext.SetSwitch("System.Net.Http.UseSocketsHttpHandler", true);
var certificate = new X509Certificate2(CertificatePath, Password);
using var handler1 = new HttpClientHandler
{
ClientCertificates = { certificate },
// Disabling domain name check
ServerCertificateCustomValidationCallback = (a, b, c, d) => true
};
var client1 = new HttpClient(handler1)
{
Timeout = TimeSpan.FromSeconds(10)
};
using var handler2 = new HttpClientHandler
{
ClientCertificates = { certificate },
// Disabling domain name check
ServerCertificateCustomValidationCallback = (a, b, c, d) => true
};
var client2 = new HttpClient(handler2)
{
Timeout = TimeSpan.FromSeconds(10)
};
for (var i = 0; i < 5; i++)
{
var requestNum = i;
try
{
MakeRequest(() =>
{
switch (requestNum)
{
case 0:
return client2;
case 1:
return client2;
case 2:
if (args.Any())
{
ClearSslCache();
}
return client1;
case 3:
return client1;
case 4:
return client2;
default:
return client2;
}
});
}
catch (Exception e)
{
Console.Error.WriteLine(e);
}
Thread.Sleep(1000);
}
Console.Out.Flush();
}
// Using synchronous version for better external debug experience
private static void MakeRequest(Func<HttpClient> clientFactory)
{
var cli = clientFactory();
var response = cli.SendAsync(new HttpRequestMessage(HttpMethod.Get, ServerUrl)
{
Version = new Version(1, 1)
}).Result;
if (!response.IsSuccessStatusCode)
{
Console.Error.WriteLine($"Received error status code: {response.StatusCode}");
return;
}
var responseString = response.Content.ReadAsStringAsync().Result.TrimEnd('\n');
Console.WriteLine($"Received response: {responseString}");
}
private static void ClearSslCache()
{
var assembly = AppDomain.CurrentDomain.GetAssemblies()
.First(x => x.FullName?.Contains("System.Net.Security") == true);
var cacheType = assembly.GetTypes().First(x => x.Name == "SslSessionsCache");
var field = cacheType.GetField("s_cachedCreds", BindingFlags.NonPublic | BindingFlags.Static);
if (field != null)
{
var dic = (IDictionary?) field.GetValue(null);
dic?.Clear();
}
}
}
}