-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRequestManager.cs
More file actions
454 lines (403 loc) · 18.1 KB
/
Copy pathRequestManager.cs
File metadata and controls
454 lines (403 loc) · 18.1 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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
// Copyright 2025 Keyfactor
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain a
// copy of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless
// required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
// OR CONDITIONS OF ANY KIND, either express or implied. See the License for
// thespecific language governing permissions and limitations under the
// License.
using System;
using System.Collections.Generic;
using System.IO;
using Keyfactor.HydrantId.Client.Models;
using Keyfactor.HydrantId.Client.Models.Enums;
using Keyfactor.HydrantId.Interfaces;
using Keyfactor.HydrantId.Exceptions;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Pkcs;
using Microsoft.Extensions.Logging;
using Keyfactor.Logging;
using LogHandler = Keyfactor.Logging.LogHandler;
using Keyfactor.AnyGateway.Extensions;
using Keyfactor.PKI.Enums.EJBCA;
using System.Linq;
namespace Keyfactor.HydrantId
{
public class RequestManager
{
private static readonly ILogger Log = LogHandler.GetClassLogger<RequestManager>();
public int GetMapReturnStatus(RevocationStatusEnum hydrantIdStatus)
{
try
{
Log.MethodEntry();
int returnStatus;
Log.LogTrace("GetMapReturnStatus: hydrantIdStatus={Status}", hydrantIdStatus);
switch (hydrantIdStatus)
{
case RevocationStatusEnum.Valid:
returnStatus = (int)EndEntityStatus.GENERATED;
break;
case RevocationStatusEnum.Pending:
returnStatus = (int)EndEntityStatus.INPROCESS;
break;
case RevocationStatusEnum.Revoked:
returnStatus = (int)EndEntityStatus.REVOKED;
break;
case RevocationStatusEnum.Failed:
returnStatus = (int)EndEntityStatus.FAILED;
break;
default:
Log.LogWarning("GetMapReturnStatus: unrecognized status '{Status}', defaulting to FAILED", hydrantIdStatus);
returnStatus = (int)EndEntityStatus.FAILED;
break;
}
Log.LogTrace("GetMapReturnStatus: {HydrantStatus} -> {MappedStatus}", hydrantIdStatus, returnStatus);
Log.MethodExit();
return returnStatus;
}
catch (Exception e)
{
Log.LogError(e, "Error occurred in RequestManager.GetMapReturnStatus: {Message}", e.Message);
throw;
}
}
public RevocationReasons GetMapRevokeReasons(uint keyfactorRevokeReason)
{
try
{
Log.MethodEntry();
Log.LogTrace("GetMapRevokeReasons: keyfactorRevokeReason={Reason}", keyfactorRevokeReason);
RevocationReasons returnStatus;
switch (keyfactorRevokeReason)
{
case 0:
returnStatus = RevocationReasons.Unspecified;
break;
case 1:
returnStatus = RevocationReasons.KeyCompromise;
break;
case 3:
returnStatus = RevocationReasons.AffiliationChanged;
break;
case 4:
returnStatus = RevocationReasons.Superseded;
break;
case 5:
returnStatus = RevocationReasons.CessationOfOperation;
break;
default:
Log.LogError("GetMapRevokeReasons: unsupported revoke reason {Reason}", keyfactorRevokeReason);
throw new RevokeReasonNotSupportedException($"Revoke reason {keyfactorRevokeReason} is not supported. Supported values: 0 (Unspecified), 1 (KeyCompromise), 3 (AffiliationChanged), 4 (Superseded), 5 (CessationOfOperation).");
Log.LogTrace("GetMapRevokeReasons: {Input} -> {Mapped}", keyfactorRevokeReason, returnStatus);
Log.MethodExit();
return returnStatus;
}
catch (RevokeReasonNotSupportedException)
{
throw;
}
catch (Exception e)
{
Log.LogError(e, "Error occurred in RequestManager.GetMapRevokeReasons: {Message}", e.Message);
throw;
}
}
public RevokeCertificateReason GetRevokeRequest(RevocationReasons reason)
{
try
{
Log.MethodEntry();
Log.LogTrace("GetRevokeRequest: reason={Reason}", reason);
return new RevokeCertificateReason
{
Reason = reason
};
}
catch (Exception e)
{
Log.LogError(e, "Error occurred in RequestManager.GetRevokeRequest: {Message}", e.Message);
throw;
}
}
public CertificatesPayload GetCertificatesListRequest(int offset, int limit)
{
try
{
Log.MethodEntry();
Log.LogTrace("GetCertificatesListRequest: offset={Offset}, limit={Limit}", offset, limit);
return new CertificatesPayload
{
Limit = limit,
Offset = offset,
Status = 0,
Expired = true
};
}
catch (Exception e)
{
Log.LogError(e, "Error occurred in RequestManager.GetCertificatesListRequest: {Message}", e.Message);
throw;
}
}
public CertRequestBody GetEnrollmentRequest(Guid? policyId, EnrollmentProductInfo productInfo, string csr, Dictionary<string, string[]> san)
{
Log.MethodEntry();
Log.LogTrace("GetEnrollmentRequest: policyId={PolicyId}, productID='{ProductId}', csr length={CsrLen}",
policyId?.ToString() ?? "(null)", productInfo?.ProductID ?? "(null)", csr?.Length ?? 0);
if (productInfo == null)
throw new ArgumentNullException(nameof(productInfo), "productInfo cannot be null.");
if (productInfo.ProductParameters == null)
throw new ArgumentNullException(nameof(productInfo), "productInfo.ProductParameters cannot be null.");
if (string.IsNullOrEmpty(csr))
throw new ArgumentNullException(nameof(csr), "CSR cannot be null or empty.");
if (!productInfo.ProductParameters.ContainsKey("ValidityPeriod"))
throw new ArgumentException("ValidityPeriod is required in ProductParameters.", nameof(productInfo));
if (!productInfo.ProductParameters.ContainsKey("ValidityUnits"))
throw new ArgumentException("ValidityUnits is required in ProductParameters.", nameof(productInfo));
var request = new CertRequestBody
{
Policy = policyId,
Csr = csr,
DnComponents = GetDnComponentsRequest(csr),
Validity = GetValidity(productInfo.ProductParameters["ValidityPeriod"], Convert.ToInt16(productInfo.ProductParameters["ValidityUnits"]))
};
if (san != null && san.Count > 0)
{
request.SubjectAltNames = GetSansRequest(san);
}
Log.MethodExit();
return request;
}
public RenewalRequest GetRenewalRequest(string csr, bool reuseCsr)
{
try
{
Log.MethodEntry();
Log.LogTrace("GetRenewalRequest: csr length={CsrLen}, reuseCsr={ReuseCsr}", csr?.Length ?? 0, reuseCsr);
if (string.IsNullOrEmpty(csr) && !reuseCsr)
throw new ArgumentNullException(nameof(csr), "CSR cannot be null or empty when reuseCsr is false.");
return new RenewalRequest
{
Csr = csr,
ReuseCsr = reuseCsr
};
}
catch (Exception e)
{
Log.LogError(e, "Error occurred in RequestManager.GetRenewalRequest: {Message}", e.Message);
throw;
}
}
private CertRequestBodyValidity GetValidity(string period, int units)
{
try
{
Log.MethodEntry();
Log.LogTrace("GetValidity: period='{Period}', units={Units}", period ?? "(null)", units);
if (string.IsNullOrEmpty(period))
throw new ArgumentNullException(nameof(period), "Validity period cannot be null or empty.");
CertRequestBodyValidity validity = new CertRequestBodyValidity();
switch (period)
{
case "Years":
validity.Years = units;
break;
case "Months":
validity.Months = units;
break;
case "Days":
validity.Days = units;
break;
default:
Log.LogWarning("GetValidity: unrecognized period '{Period}', no validity set", period);
break;
}
return validity;
}
catch (Exception e)
{
Log.LogError(e, "Error occurred in RequestManager.GetValidity: {Message}", e.Message);
throw;
}
}
public CertRequestBodySubjectAltNames GetSansRequest(Dictionary<string, string[]> sans)
{
try
{
Log.MethodEntry();
Log.LogTrace("GetSansRequest: sans is {Null}, count={Count}",
sans == null ? "NULL" : "present", sans?.Count ?? 0);
if (sans == null)
return new CertRequestBodySubjectAltNames();
var san = new CertRequestBodySubjectAltNames();
if (sans.TryGetValue("dnsname", out var dnsNames))
{
san.Dnsname = dnsNames?.ToList() ?? new List<string>();
Log.LogTrace("GetSansRequest: dnsname count={Count}", san.Dnsname.Count);
}
if (sans.TryGetValue("ipaddress", out var ipAddresses))
{
san.Ipaddress = ipAddresses?.ToList() ?? new List<string>();
Log.LogTrace("GetSansRequest: ipaddress count={Count}", san.Ipaddress.Count);
}
if (sans.TryGetValue("rfc822name", out var rfcNames))
{
san.Rfc822Name = rfcNames?.ToList() ?? new List<string>();
Log.LogTrace("GetSansRequest: rfc822name count={Count}", san.Rfc822Name.Count);
}
if (sans.TryGetValue("upn", out var upns))
{
san.Upn = upns?.ToList() ?? new List<string>();
Log.LogTrace("GetSansRequest: upn count={Count}", san.Upn.Count);
}
return san;
}
catch (Exception e)
{
Log.LogError(e, "Error occurred in RequestManager.GetSansRequest: {Message}", e.Message);
throw;
}
}
public EnrollmentResult GetEnrollmentResult(ICertificate enrollmentResult, AnyCAPluginCertificate cert)
{
try
{
Log.MethodEntry();
Log.LogTrace("GetEnrollmentResult: enrollmentResult is {Null}, cert is {CertNull}",
enrollmentResult == null ? "NULL" : "present",
cert == null ? "NULL" : "present");
if (enrollmentResult == null)
{
Log.LogError("GetEnrollmentResult: enrollmentResult is null.");
return new EnrollmentResult
{
Status = (int)EndEntityStatus.FAILED,
StatusMessage = "Enrollment failed: could not get the certificate from the request tracking id."
};
}
if (!enrollmentResult.Id.HasValue)
{
Log.LogError("GetEnrollmentResult: enrollmentResult.Id has no value.");
return new EnrollmentResult
{
Status = (int)EndEntityStatus.FAILED,
StatusMessage = "Enrollment failed: certificate response has no ID."
};
}
if (cert == null || string.IsNullOrEmpty(cert.Certificate))
{
Log.LogWarning("GetEnrollmentResult: cert is null or has empty Certificate for ID={Id}", enrollmentResult.Id);
return new EnrollmentResult
{
Status = (int)EndEntityStatus.FAILED,
StatusMessage = "Enrollment failed: could not retrieve certificate content."
};
}
Log.LogTrace("GetEnrollmentResult: success - ID={Id}, certificate length={Len}",
enrollmentResult.Id, cert.Certificate?.Length ?? 0);
return new EnrollmentResult
{
Status = (int)EndEntityStatus.GENERATED,
CARequestID = enrollmentResult.Id.ToString(),
Certificate = cert.Certificate,
StatusMessage = "Order Successfully Created"
};
}
catch (Exception e)
{
Log.LogError(e, "Error occurred in RequestManager.GetEnrollmentResult: {Message}", e.Message);
throw;
}
}
public static Func<string, string> Pemify = ss =>
ss.Length <= 64 ? ss : ss.Substring(0, 64) + "\n" + Pemify(ss.Substring(64));
public CertRequestBodyDnComponents GetDnComponentsRequest(string csr)
{
try
{
Log.MethodEntry();
Log.LogTrace("GetDnComponentsRequest: csr length={CsrLen}", csr?.Length ?? 0);
if (string.IsNullOrEmpty(csr))
throw new ArgumentNullException(nameof(csr), "CSR cannot be null or empty.");
var c = String.Empty;
var o = String.Empty;
var cn = string.Empty;
var l = string.Empty;
var st = string.Empty;
var ou = string.Empty;
var cert = csr;
Log.LogTrace("GetDnComponentsRequest: parsing CSR");
var reader = new PemReader(new StringReader(cert));
var pemObject = reader.ReadObject();
if (pemObject == null)
{
Log.LogWarning("GetDnComponentsRequest: PemReader returned null object");
return new CertRequestBodyDnComponents { Cn = cn, Ou = new List<string> { ou }, O = o, L = l, St = st, C = c };
}
if (pemObject is Pkcs10CertificationRequest req)
{
var info = req.GetCertificationRequestInfo();
Log.LogTrace("GetDnComponentsRequest: subject='{Subject}'", info?.Subject?.ToString() ?? "(null)");
if (info?.Subject != null)
{
var array1 = info.Subject.ToString().Split(',');
foreach (var x in array1)
{
if (string.IsNullOrWhiteSpace(x))
continue;
var itemArray = x.Split('=');
if (itemArray.Length < 2)
{
Log.LogTrace("GetDnComponentsRequest: skipping malformed DN component '{Component}'", x);
continue;
}
switch (itemArray[0].Trim().ToUpper())
{
case "C":
c = itemArray[1].Trim();
break;
case "O":
o = itemArray[1].Trim();
break;
case "CN":
cn = itemArray[1].Trim();
break;
case "OU":
ou = itemArray[1].Trim();
break;
case "ST":
st = itemArray[1].Trim();
break;
case "L":
l = itemArray[1].Trim();
break;
}
}
}
}
else
{
Log.LogWarning("GetDnComponentsRequest: PEM object is not a PKCS10 request, type={Type}", pemObject.GetType().Name);
}
Log.LogTrace("GetDnComponentsRequest: CN='{Cn}', O='{O}', OU='{Ou}', C='{C}', ST='{St}', L='{L}'",
cn, o, ou, c, st, l);
return new CertRequestBodyDnComponents
{
Cn = cn,
Ou = new List<string> { ou },
O = o,
L = l,
St = st,
C = c
};
}
catch (Exception e)
{
Log.LogError(e, "Error occurred in RequestManager.GetDnComponentsRequest: {Message}", e.Message);
throw;
}
}
}
}