-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSectigoClient.cs
More file actions
365 lines (316 loc) · 11.5 KB
/
Copy pathSectigoClient.cs
File metadata and controls
365 lines (316 loc) · 11.5 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
using Keyfactor.AnyGateway.Extensions;
using Keyfactor.Extensions.CAPlugin.Sectigo.API;
using Keyfactor.Extensions.CAPlugin.Sectigo.Models;
using Keyfactor.Logging;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Json;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Keyfactor.Extensions.CAPlugin.Sectigo.Client
{
public class SectigoClient
{
private static ILogger Logger => LogHandler.GetClassLogger<SectigoClient>();
private HttpClient RestClient { get; }
public SectigoClient(HttpClient client)
{
RestClient = client;
}
public async Task<Certificate> GetCertificate(int sslId)
{
var response = await RestClient.GetAsync($"api/ssl/v1/{sslId}");
return await ProcessResponse<Certificate>(response);
}
public async Task CertificateListProducer(BlockingCollection<Certificate> certs,
CancellationToken cancelToken, int pageSize = 25, string filter = "")
{
int batchCount;
int blockedCount;
int totalCount = 0;
List<Certificate> certificatePageToProcess;
try
{
//Paging loop will iterate though the certificates until all certificates have been returned
do
{
if (cancelToken.IsCancellationRequested)
{
certs.CompleteAdding();
break;
}
int certIndex = totalCount > 0 ? (totalCount - 1) : 0;
Logger.LogInformation($"Request Certificates at Position {certIndex} with Page Size {pageSize}");
certificatePageToProcess = await PageCertificates(certIndex, pageSize, filter);
Logger.LogDebug($"Found {certificatePageToProcess.Count} certificate to process");
//Processing Loop will add and retry adding to queue until all certificates have been processed for a page
batchCount = 0;
blockedCount = 0;
do
{
Certificate cert = certificatePageToProcess[batchCount];
Logger.LogDebug($"Processing: {cert}");
Certificate certDetails = null;
try
{
if (certDetails == null)
certDetails = await GetCertificate(cert.Id);
}
catch (Exception aEx)
{
Logger.LogError($"Error requesting certificate details. Skipping certificate. {aEx.Message}");
batchCount++;
continue;
}
if (certs.TryAdd(certDetails, 50, cancelToken))
{
batchCount++;
totalCount++;
}
else
{
Logger.LogTrace($"Adding {cert.Id} to queue was blocked. Retry");
blockedCount++;//TODO: If blocked count is excessive, should we skip?
}
certIndex++;
}
while (batchCount < certificatePageToProcess.Count);
Logger.LogInformation($"Added {batchCount} certificates to queue for processing.");
} while (certificatePageToProcess.Count == pageSize);//if the API returns less than we requested, we assume we have reached the end
}
catch (HttpRequestException hEx)
{
Logger.LogError($"Sync interrupted by HTTP Exception. {hEx.InnerException.Message}");
certs.CompleteAdding();//Stops the consuming enumerable and sync will continue until the queue is empty
}
catch (Exception ex)
{
//fail gracefully and stop syncing.
Logger.LogError($"Sync interrupted by General Exception. {ex.Message}");
certs.CompleteAdding();//Stops the consuming enumerable and sync will continue until the queue is empty
}
}
public async Task CertificateListProducer(BlockingCollection<Certificate> certs,
CancellationToken cancelToken, int pageSize = 25, Dictionary<string, string[]> filter = null)
{
if (filter != null && filter.Count > 0)
{
//each kvp key = type, value each filter
foreach (var s in filter)
{
foreach (var value in s.Value)
await CertificateListProducer(certs, cancelToken, pageSize, $"{s.Key}={value}");
}
}
else
{
// No filters
await CertificateListProducer(certs, cancelToken, pageSize, "");
}
certs.CompleteAdding();
}
public async Task<List<Certificate>> PageCertificates(int position = 0, int size = 25, string filter = "")
{
string filterQueryString = string.IsNullOrEmpty(filter) ? string.Empty : $"&{filter}";
Logger.LogTrace($"API Request: api/ssl/v1?position={position}&size={size}{filterQueryString}".TrimEnd());
var response = await RestClient.GetAsync($"api/ssl/v1?position={position}&size={size}{filterQueryString}".TrimEnd());
return await ProcessResponse<List<Certificate>>(response);
}
public async Task<bool> RevokeSslCertificateById(int sslId, int revcode, string revreason)
{
var data = new
{
reasonCode = revcode,
reason = revreason
};
var response = await RestClient.PostAsJsonAsync($"api/ssl/v1/revoke/{sslId}", data);
if (response.IsSuccessStatusCode)
{
return true;
}
var failedResp = ProcessResponse<RevocationResponse>(response).Result;
return failedResp.IsSuccess;//Should throw an exception with error message from API
}
public async Task<ListOrganizationsResponse> ListOrganizations()
{
var response = await RestClient.GetAsync("api/organization/v1");
if (response.IsSuccessStatusCode)
{
string responseContent = await response.Content.ReadAsStringAsync();
Logger.LogTrace($"Raw Response: {responseContent}");
}
var orgsResponse = await ProcessResponse<List<Organization>>(response);
return new ListOrganizationsResponse { Organizations = orgsResponse };
}
public async Task<OrganizationDetailsResponse> GetOrganizationDetails(int orgId)
{
var response = await RestClient.GetAsync($"api/organization/v1/{orgId}");
if (response.IsSuccessStatusCode)
{
string responseContent = await response.Content.ReadAsStringAsync();
Logger.LogTrace($"Raw Response: {responseContent}");
}
var orgDetailsResponse = await ProcessResponse<OrganizationDetailsResponse>(response);
return orgDetailsResponse;
}
public async Task<ListPersonsResponse> ListPersons(int orgId)
{
int pageSize = 25;
List<Person> responseList = new List<Person>();
List<Person> partialList = new List<Person>();
do
{
partialList = await PagePersons(orgId, responseList.Count - 1, pageSize);
responseList.AddRange(partialList);
}
while (partialList.Count == pageSize);
return new ListPersonsResponse() { Persons = responseList };
}
public async Task<ListCustomFieldsResponse> ListCustomFields()
{
var response = await RestClient.GetAsync("api/ssl/v1/customFields");
return new ListCustomFieldsResponse { CustomFields = await ProcessResponse<List<CustomField>>(response) };
}
public async Task<ListSslProfilesResponse> ListSslProfiles(int? orgId = null)
{
string urlSuffix = string.Empty;
if (orgId.HasValue)
{
urlSuffix = $"?organizationId={orgId}";
}
var response = await RestClient.GetAsync($"api/ssl/v1/types{urlSuffix}");
return new ListSslProfilesResponse { SslProfiles = await ProcessResponse<List<Profile>>(response) };
}
public async Task<List<Person>> PagePersons(int orgId, int position = 0, int size = 25)
{
var response = await RestClient.GetAsync($"api/person/v1?position={position}&size={size}&organizationId={orgId}");
return await ProcessResponse<List<Person>>(response);
}
public async Task<int> Enroll(EnrollRequest request)
{
try
{
var response = await RestClient.PostAsJsonAsync("api/ssl/v1/enroll", request);
var enrollResponse = await ProcessResponse<EnrollResponse>(response);
return enrollResponse.sslId;
}
catch (InvalidOperationException invalidOp)
{
throw new Exception($"Invalid Operation. {invalidOp.Message}|{invalidOp.StackTrace}", invalidOp);
}
catch (HttpRequestException httpEx)
{
throw new Exception($"HttpRequestException. {httpEx.Message}|{httpEx.StackTrace}", httpEx);
}
catch (Exception)
{
throw;
}
}
public async Task<int> Renew(int sslId)
{
try
{
var response = await RestClient.PostAsJsonAsync($"api/ssl/v1/renewById/{sslId}", "");
var renewResponse = await ProcessResponse<EnrollResponse>(response);
return renewResponse.sslId;
}
catch (InvalidOperationException invalidOp)
{
throw new Exception($"Invalid Operation. {invalidOp.Message}|{invalidOp.StackTrace}");
}
catch (HttpRequestException httpEx)
{
throw new Exception($"HttpRequestException. {httpEx.Message}|{httpEx.StackTrace}");
}
catch (Exception)
{
throw;
}
}
public async Task<X509Certificate2> PickupCertificate(int sslId, string subject)
{
var response = await RestClient.GetAsync($"api/ssl/v1/collect/{sslId}/x509CO");
if (response.IsSuccessStatusCode && response.Content.Headers.ContentLength > 0)
{
string pemChain = await response.Content.ReadAsStringAsync();
string[] splitChain = pemChain.Replace("\r\n", string.Empty).Split(new string[] { "-----" }, StringSplitOptions.RemoveEmptyEntries);
return new X509Certificate2(Convert.FromBase64String(splitChain[1]));
}
return null;
//return new X509Certificate2();
}
public async Task Reissue(ReissueRequest request, int sslId)
{
var response = await RestClient.PostAsJsonAsync($"api/ssl/v1/replace/{sslId}", request);
response.EnsureSuccessStatusCode();
}
#region Static Methods
private static async Task<T> ProcessResponse<T>(HttpResponseMessage response)
{
if (response.IsSuccessStatusCode)
{
string responseContent = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<T>(responseContent);
}
else
{
var error = JsonConvert.DeserializeObject<Error>(await response.Content.ReadAsStringAsync());
throw new Exception($"{error.Code} | {error.Description}");
}
}
public static SectigoClient InitializeClient(SectigoConfig config, ICertificateResolver certResolver)
{
Logger.MethodEntry(LogLevel.Debug);
HttpClientHandler clientHandler = new HttpClientHandler();
if (config.AuthenticationType.ToLower() == "certificate")
{
clientHandler.ClientCertificateOptions = ClientCertificateOption.Manual;
Logger.LogTrace($"Resolving certificate. Source: {config.Certificate.Source}");
X509Certificate2 authCert = null;
if (!string.IsNullOrEmpty(config.Certificate.ImportedCertificate))
{
authCert = new X509Certificate2(Convert.FromBase64String(config.Certificate.ImportedCertificate), config.Certificate.ImportedCertificatePassword);
}
else
{
authCert = certResolver.ResolveCertificate(config.Certificate);
}
if (authCert == null)
{
Logger.MethodExit(LogLevel.Debug);
throw new Exception("AuthType set to Certificate, but no certificate found!");
}
Logger.LogTrace($"Auth cert found. CERT DETAILS: \nSerial Number: {authCert.GetSerialNumberString()}\nHas PK: {authCert.HasPrivateKey.ToString()}\nSubject: {authCert.Subject}");
clientHandler.ClientCertificates.Add(authCert);
}
string apiEndpoint = config.ApiEndpoint;
if (!apiEndpoint.EndsWith("/"))
{
apiEndpoint += "/";
}
HttpClient restClient = new HttpClient(clientHandler)
{
BaseAddress = new Uri(apiEndpoint)
};
restClient.DefaultRequestHeaders.Add(Constants.CUSTOMER_URI_KEY, config.CustomerUri);
restClient.DefaultRequestHeaders.Add(Constants.CUSTOMER_LOGIN_KEY, config.Username);
//Determine
if (config.AuthenticationType.ToLower() == "password")
{
restClient.DefaultRequestHeaders.Add(Constants.CUSTOMER_PASSWORD_KEY, config.Password);
}
Logger.MethodExit(LogLevel.Debug);
return new SectigoClient(restClient);
}
#endregion
}
}