/
RevocationResponder.cs
386 lines (319 loc) · 12.7 KB
/
RevocationResponder.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
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Formats.Asn1;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
namespace System.Security.Cryptography.X509Certificates.Tests.Common
{
internal sealed class RevocationResponder : IDisposable
{
private static readonly bool s_traceEnabled =
Environment.GetEnvironmentVariable("TRACE_REVOCATION_RESPONSE") != null;
private readonly HttpListener _listener;
private readonly Dictionary<string, CertificateAuthority> _aiaPaths =
new Dictionary<string, CertificateAuthority>();
private readonly Dictionary<string, CertificateAuthority> _crlPaths
= new Dictionary<string, CertificateAuthority>();
private readonly List<(string, CertificateAuthority)> _ocspAuthorities =
new List<(string, CertificateAuthority)>();
public string UriPrefix { get; }
public bool RespondEmpty { get; set; }
public TimeSpan ResponseDelay { get; set; }
public DelayedActionsFlag DelayedActions { get; set; }
private RevocationResponder(HttpListener listener, string uriPrefix)
{
_listener = listener;
UriPrefix = uriPrefix;
}
public void Dispose()
{
_listener.Close();
}
internal void AddCertificateAuthority(CertificateAuthority authority)
{
if (authority.AiaHttpUri != null && authority.AiaHttpUri.StartsWith(UriPrefix))
{
_aiaPaths.Add(authority.AiaHttpUri.Substring(UriPrefix.Length - 1), authority);
}
if (authority.CdpUri != null && authority.CdpUri.StartsWith(UriPrefix))
{
_crlPaths.Add(authority.CdpUri.Substring(UriPrefix.Length - 1), authority);
}
if (authority.OcspUri != null && authority.OcspUri.StartsWith(UriPrefix))
{
_ocspAuthorities.Add((authority.OcspUri.Substring(UriPrefix.Length - 1), authority));
}
}
private void HandleRequests()
{
ThreadPool.QueueUserWorkItem(
state =>
{
while (state._listener.IsListening)
{
state.HandleRequest();
}
},
this,
true);
}
internal void HandleRequest()
{
HttpListenerContext context = null;
try
{
context = _listener.GetContext();
}
catch (Exception)
{
}
if (context != null)
{
HandleRequest(context);
}
}
internal async Task HandleRequestAsync()
{
HttpListenerContext context = null;
try
{
context = await _listener.GetContextAsync();
}
catch (Exception)
{
}
if (context != null)
{
HandleRequest(context);
}
}
internal void HandleRequest(HttpListenerContext context)
{
bool responded = false;
try
{
Trace($"{context.Request.HttpMethod} {context.Request.RawUrl} (HTTP {context.Request.ProtocolVersion})");
HandleRequest(context, ref responded);
}
catch (Exception e)
{
try
{
if (!responded && context != null)
{
context.Response.StatusCode = 500;
context.Response.StatusDescription = "Internal Server Error";
context.Response.Close();
Trace($"Sent 500 due to exception on {context.Request.HttpMethod} {context.Request.RawUrl}");
Trace(e.ToString());
}
}
catch (Exception)
{
}
return;
}
if (!responded)
{
Trace($"404 for {context.Request.HttpMethod} {context.Request.RawUrl}");
try
{
context.Response.StatusCode = 404;
context.Response.Close();
}
catch (Exception)
{
}
}
}
private void HandleRequest(HttpListenerContext context, ref bool responded)
{
CertificateAuthority authority;
string url = context.Request.RawUrl;
if (_aiaPaths.TryGetValue(url, out authority))
{
if (DelayedActions.HasFlag(DelayedActionsFlag.Aia))
{
Trace($"Delaying response by {ResponseDelay}.");
Thread.Sleep(ResponseDelay);
}
byte[] certData = RespondEmpty ? Array.Empty<byte>() : authority.GetCertData();
responded = true;
context.Response.StatusCode = 200;
context.Response.ContentType = "application/pkix-cert";
context.Response.Close(certData, willBlock: true);
Trace($"Responded with {certData.Length}-byte certificate from {authority.SubjectName}.");
return;
}
if (_crlPaths.TryGetValue(url, out authority))
{
if (DelayedActions.HasFlag(DelayedActionsFlag.Crl))
{
Trace($"Delaying response by {ResponseDelay}.");
Thread.Sleep(ResponseDelay);
}
byte[] crl = RespondEmpty ? Array.Empty<byte>() : authority.GetCrl();
responded = true;
context.Response.StatusCode = 200;
context.Response.ContentType = "application/pkix-crl";
context.Response.Close(crl, willBlock: true);
Trace($"Responded with {crl.Length}-byte CRL from {authority.SubjectName}.");
return;
}
string prefix;
foreach (var tuple in _ocspAuthorities)
{
(prefix, authority) = tuple;
if (url.StartsWith(prefix))
{
if (context.Request.HttpMethod == "GET")
{
ReadOnlyMemory<byte> certId;
ReadOnlyMemory<byte> nonce;
try
{
string base64 = HttpUtility.UrlDecode(url.Substring(prefix.Length + 1));
byte[] reqBytes = Convert.FromBase64String(base64);
DecodeOcspRequest(reqBytes, out certId, out nonce);
}
catch (Exception)
{
Trace($"OcspRequest Decode failed ({url})");
context.Response.StatusCode = 400;
context.Response.Close();
return;
}
byte[] ocspResponse = RespondEmpty ? Array.Empty<byte>() : authority.BuildOcspResponse(certId, nonce);
if (DelayedActions.HasFlag(DelayedActionsFlag.Ocsp))
{
Trace($"Delaying response by {ResponseDelay}.");
Thread.Sleep(ResponseDelay);
}
responded = true;
context.Response.StatusCode = 200;
context.Response.StatusDescription = "OK";
context.Response.ContentType = "application/ocsp-response";
context.Response.Close(ocspResponse, willBlock: true);
if (authority.HasOcspDelegation)
{
Trace($"OCSP Response: {ocspResponse.Length} bytes from {authority.SubjectName} delegated to {authority.OcspResponderSubjectName}");
}
else
{
Trace($"OCSP Response: {ocspResponse.Length} bytes from {authority.SubjectName}");
}
return;
}
}
}
}
internal static RevocationResponder CreateAndListen()
{
HttpListener listener = OpenListener(out string uriPrefix);
RevocationResponder responder = new RevocationResponder(listener, uriPrefix);
responder.HandleRequests();
return responder;
}
private static HttpListener OpenListener(out string uriPrefix)
{
while (true)
{
int port = RandomNumberGenerator.GetInt32(41000, 42000);
uriPrefix = $"http://127.0.0.1:{port}/";
HttpListener listener = new HttpListener();
listener.Prefixes.Add(uriPrefix);
listener.IgnoreWriteExceptions = true;
try
{
listener.Start();
Trace($"Listening at {uriPrefix}");
return listener;
}
catch
{
}
}
}
private static void DecodeOcspRequest(
byte[] requestBytes,
out ReadOnlyMemory<byte> certId,
out ReadOnlyMemory<byte> nonceExtension)
{
Asn1Tag context0 = new Asn1Tag(TagClass.ContextSpecific, 0);
Asn1Tag context1 = new Asn1Tag(TagClass.ContextSpecific, 1);
AsnReader reader = new AsnReader(requestBytes, AsnEncodingRules.DER);
AsnReader request = reader.ReadSequence();
reader.ThrowIfNotEmpty();
AsnReader tbsRequest = request.ReadSequence();
if (request.HasData)
{
// Optional signature
request.ReadEncodedValue();
request.ThrowIfNotEmpty();
}
// Only v1(0) is supported, and it shouldn't be written per DER.
// But Apple writes it anyways, so let's go ahead and be lenient.
if (tbsRequest.PeekTag().HasSameClassAndValue(context0))
{
AsnReader versionReader = tbsRequest.ReadSequence(context0);
if (!versionReader.TryReadInt32(out int version) || version != 0)
{
throw new CryptographicException("ASN1 corrupted data");
}
versionReader.ThrowIfNotEmpty();
}
if (tbsRequest.PeekTag().HasSameClassAndValue(context1))
{
tbsRequest.ReadEncodedValue();
}
AsnReader requestList = tbsRequest.ReadSequence();
AsnReader requestExtensions = null;
if (tbsRequest.HasData)
{
AsnReader requestExtensionsWrapper = tbsRequest.ReadSequence(new Asn1Tag(TagClass.ContextSpecific, 2));
requestExtensions = requestExtensionsWrapper.ReadSequence();
requestExtensionsWrapper.ThrowIfNotEmpty();
}
tbsRequest.ThrowIfNotEmpty();
AsnReader firstRequest = requestList.ReadSequence();
requestList.ThrowIfNotEmpty();
certId = firstRequest.ReadEncodedValue();
if (firstRequest.HasData)
{
firstRequest.ReadSequence(context0);
}
firstRequest.ThrowIfNotEmpty();
nonceExtension = default;
if (requestExtensions != null)
{
while (requestExtensions.HasData)
{
ReadOnlyMemory<byte> wholeExtension = requestExtensions.PeekEncodedValue();
AsnReader extension = requestExtensions.ReadSequence();
if (extension.ReadObjectIdentifier() == "1.3.6.1.5.5.7.48.1.2")
{
nonceExtension = wholeExtension;
}
}
}
}
private static void Trace(string trace)
{
if (s_traceEnabled)
{
Console.WriteLine(trace);
}
}
internal enum DelayedActionsFlag : byte
{
None = 0,
Ocsp = 0b1,
Crl = 0b10,
Aia = 0b100,
All = 0b11111111
}
}
}