-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFortigateStore.cs
More file actions
549 lines (468 loc) · 20.6 KB
/
Copy pathFortigateStore.cs
File metadata and controls
549 lines (468 loc) · 20.6 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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
// Copyright 2023 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 the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Keyfactor.Logging;
using Keyfactor.Extensions.Orchestrator.Fortigate.Api;
using System.Net.Http;
//using System.Net.Http.Json;
using System.Linq;
using System.Web;
using System.Text;
using System.Net.Http.Headers;
using Microsoft.Extensions.Logging;
using Org.BouncyCastle.Asn1.Ocsp;
namespace Keyfactor.Extensions.Orchestrator.Fortigate
{
public class FortigateStore
{
private ILogger logger { get; set; }
private string FortigateHost { get; set; }
private string VDOM { get; set; }
private static readonly string available_certificates = "/api/v2/monitor/system/available-certificates";
private static readonly string download_certificate = "/api/v2/monitor/system/certificate/download";
//private static readonly string certificate_api = "/api/v2/cmdb/certificate/local";
private static readonly string import_certificate_api = "/api/v2/monitor/vpn-certificate/local/import";
private static readonly string get_certificate_api = "/api/v2/cmdb/certificate/local/";
private static readonly string get_vdom_api = "/api/v2/cmdb/system/vdom/";
//api/v2/cmdb/vpn.certificate/local/test?vdom=root
private static readonly string delete_certificate_api = "/api/v2/cmdb/vpn.certificate/local/";
private static readonly string cert_usage_api = "/api/v2/monitor/system/object/usage";
private static readonly string https_usage_api = "/api/v2/cmdb/system/global";
private readonly HttpClientHandler handler = new HttpClientHandler()
{
ClientCertificateOptions = ClientCertificateOption.Manual,
ServerCertificateCustomValidationCallback = (httpRequestMessage, cert, certChain, policyErrors) => { return true; }
};
private readonly HttpClient client;
public FortigateStore(string fortigateHost, string accessToken, string vdom)
{
logger = LogHandler.GetClassLogger(this.GetType());
logger.MethodEntry(LogLevel.Debug);
client = new HttpClient(handler);
FortigateHost = fortigateHost;
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {accessToken}");
VDOM = string.IsNullOrEmpty(vdom) ? "root" : vdom;
ValidateVDOM();
logger.MethodExit(LogLevel.Debug);
}
public void Delete(string alias)
{
logger.MethodEntry(LogLevel.Debug);
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("vdom", VDOM);
try
{
DeleteResource(delete_certificate_api + alias, parameters);
}
catch (Exception ex)
{
logger.LogError(FortigateException.FlattenExceptionMessages(ex, $"Error deleting certificate {alias}: "));
throw;
}
finally
{
logger.MethodExit(LogLevel.Debug);
}
}
public void UpdateUsage(string alias, string path, string name, string attribute)
{
logger.MethodEntry(LogLevel.Debug);
var attributeValue = new Dictionary<String, String>();
attributeValue.Add("q_origin_key", alias);
var main = new Dictionary<String, Object>();
main.Add(attribute, attributeValue);
var endpoint = "/api/v2/cmdb/" + path + "/" + name;
var parameters = new Dictionary<String, String> { { "vdom", VDOM } };
try
{
PutAsJson(endpoint, main, parameters);
}
catch (Exception ex)
{
logger.LogError(FortigateException.FlattenExceptionMessages(ex, $"Error updating usage for {alias}: "));
throw;
}
finally
{
logger.MethodExit(LogLevel.Debug);
}
}
public Usage Usage(string alias, int qtype)
{
logger.MethodEntry(LogLevel.Debug);
var parameters = new Dictionary<String, String>();
parameters.Add("vdom", VDOM);
parameters.Add("mkey", alias);
parameters.Add("qtypes", $"[{qtype.ToString()}]");
try
{
var result = GetResource(cert_usage_api, parameters);
var response = JsonConvert.DeserializeObject<FortigateResponse<Usage>>(result);
return response.results;
}
catch (Exception ex)
{
logger.LogError(FortigateException.FlattenExceptionMessages(ex, $"Error checking usage for {alias}: "));
throw;
}
finally
{
logger.MethodExit(LogLevel.Debug);
}
}
public string HttpsServerUsage()
{
logger.MethodEntry(LogLevel.Debug);
try
{
var result = GetResource(https_usage_api, new Dictionary<String, String>());
return JsonConvert.DeserializeObject<FortigateResponse<HttpsUsage>>(result).results.AdminServerCert;
}
catch (Exception ex)
{
logger.LogError(FortigateException.FlattenExceptionMessages(ex, $"Error checking https bindings: "));
throw;
}
finally
{
logger.MethodExit(LogLevel.Debug);
}
}
public void UpdateHttpsServerUsage(string alias)
{
logger.MethodEntry(LogLevel.Debug);
HttpUsageRequest request = new HttpUsageRequest() { AdminServerCert = new OriginKey() { QOriginKey = alias } };
try
{
PutAsJson(https_usage_api, request, new Dictionary<string, string>());
}
catch (Exception ex)
{
logger.LogError(FortigateException.FlattenExceptionMessages(ex, $"Error updating https server binding: "));
throw;
}
finally
{
logger.MethodExit(LogLevel.Debug);
}
}
public void Insert(string alias, string cert, string privateKey, bool overwrite, string password = null)
{
logger.MethodEntry(LogLevel.Debug);
try
{
Certificate[] byAlias = List(alias);
if (overwrite)
{
var newAlias = CreateNewAlias(alias);
Certificate[] byNewAlias = List(newAlias);
Usage existingUsage = null;
//if there is an existing record
if (byAlias.Length > 0)
{
Certificate certItem = byAlias[0];
//check to see if it's in use
existingUsage = Usage(alias, certItem.q_type);
bool existingHttpsUsage = HttpsServerUsage() == alias;
//if it's currently in use
if ((existingUsage != null && existingUsage.currently_using != null && existingUsage.currently_using.Length > 0) || existingHttpsUsage)
{
//if newAlias exists, end with error
if (byNewAlias.Length > 0)
{
throw new Exception($"Error inserting certificate {alias}. New alias {newAlias} already exists, so certificate {alias} that is bound to one or more objects, cannot be replaced and rebound. Please remove {newAlias}, and try again.");
}
//create newAlias entry
logger.LogDebug("Inserting alias:" + newAlias);
Insert(newAlias, cert, privateKey, password);
if (existingUsage != null && existingUsage.currently_using != null && existingUsage.currently_using.Length > 0)
{
foreach (var existingUsing in existingUsage.currently_using)
{
logger.LogDebug($"Update binding for path/name/attribute {existingUsing.path}/{existingUsing.name}/{existingUsing.attribute} for new alias {newAlias}");
UpdateUsage(newAlias, existingUsing.path, existingUsing.name, existingUsing.attribute);
}
}
if (existingHttpsUsage)
{
UpdateHttpsServerUsage(newAlias);
}
logger.LogDebug("Deleting alias:" + alias);
Delete(alias);
}
else
{
logger.LogDebug("Deleting alias:" + alias);
Delete(alias);
logger.LogDebug("Inserting alias:" + alias);
Insert(alias, cert, privateKey, password);
}
}
else
{
logger.LogDebug("Inserting alias:" + alias);
Insert(alias, cert, privateKey, password);
}
}
else
{
if (byAlias.Length > 0)
throw new Exception($"Certificate {alias} already exists, but overwrite is set to false. Try rescheduling job with overwrite set to true if you wish to replace this certificate.");
//no overwrite so we just try to insert
logger.LogDebug("Inserting alias: " + alias);
Insert(alias, cert, privateKey, password);
}
}
catch (Exception ex)
{
logger.LogError(FortigateException.FlattenExceptionMessages(ex, $"Error inserting/replacing certificate {alias}: "));
throw;
}
finally
{
logger.MethodExit(LogLevel.Debug);
}
}
private void Insert(string alias, string cert, string privateKey, string password = null)
{
logger.MethodEntry(LogLevel.Debug);
var cert_resource = new cmdb_certificate_resource()
{
certname = alias,
key_file_content = privateKey,
file_content = cert,
scope = "vdom",
vdom = VDOM,
type = "regular"
};
try
{
PostAsJson(import_certificate_api, cert_resource);
}
catch (Exception ex)
{
logger.LogError(FortigateException.FlattenExceptionMessages(ex, $"Error inserting certificate {alias}: "));
throw;
}
finally
{
logger.MethodExit(LogLevel.Debug);
}
}
public Certificate[] List(string mkey)
{
logger.MethodEntry(LogLevel.Debug);
Certificate[] certificates = new List<Certificate>().ToArray();
try
{
string endpoint = available_certificates;
Dictionary<String, String> parameters = new Dictionary<string, string>();
if (!string.IsNullOrEmpty(mkey))
parameters.Add("mkey", mkey);
parameters.Add("vdom", VDOM);
var result = GetResource(endpoint, parameters);
certificates = JsonConvert.DeserializeObject<FortigateResponse<Certificate[]>>(result).results;
}
catch (Exception ex)
{
if (ex.GetType() != typeof(HttpRequestException) || ((HttpRequestException)ex).StatusCode != System.Net.HttpStatusCode.NotFound)
{
logger.LogError(FortigateException.FlattenExceptionMessages(ex, "Error retrieving certificate list: "));
throw;
}
}
finally
{
logger.MethodExit(LogLevel.Debug);
}
return certificates;
}
public string DownloadFileAsString(string mkey, string type, out bool isError)
{
logger.MethodEntry(LogLevel.Debug);
isError = false;
var parameters = new Dictionary<String, String>();
parameters.Add("mkey", mkey);
parameters.Add("type", type);
parameters.Add("vdom", VDOM);
string content = string.Empty;
try
{
var response = client.GetAsync(GetUrl(download_certificate, parameters)).GetAwaiter().GetResult();
content = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
if (!response.IsSuccessStatusCode)
throw new Exception($"Error retrieving certificate {mkey}: {content}");
}
catch (Exception ex)
{
logger.LogError(FortigateException.FlattenExceptionMessages(ex, $"Error retrieving downloading file {mkey}: "));
isError = true;
}
finally
{
logger.MethodExit(LogLevel.Debug);
}
return content;
}
public void ValidateVDOMScope(string alias)
{
logger.MethodEntry(LogLevel.Debug);
try
{
Certificate[] certs = List(alias);
if (certs.Length > 0 && certs[0].range.ToLower() == "global")
throw new Exception($"Certificate {alias} is scoped as global. Global certificates cannot be replaced or deleted by this integration.");
}
finally
{
logger.MethodExit(LogLevel.Debug);
}
}
private void ValidateVDOM()
{
logger.MethodEntry(LogLevel.Debug);
try
{
var response = client.GetAsync(GetUrl(get_vdom_api + VDOM, null)).GetAwaiter().GetResult();
if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
throw new FortigateException($"VDOM {VDOM} not found.");
if (!response.IsSuccessStatusCode)
throw new FortigateException($"Error retrieving VDOM {VDOM}. Status={response.StatusCode.ToString()}, Error={response.Content} {response.ReasonPhrase}");
}
finally
{
logger.MethodExit(LogLevel.Debug);
}
}
private String PostAsJson(string endpoint, cmdb_certificate_resource obj)
{
logger.MethodEntry(LogLevel.Debug);
var url = GetUrl(endpoint);
var stringContent = new StringContent(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json");
stringContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
try
{
HttpResponseMessage responseMessage = client.PostAsync(url, stringContent).GetAwaiter().GetResult();
var content = responseMessage.Content.ReadAsStringAsync().GetAwaiter().GetResult();
if (!responseMessage.IsSuccessStatusCode)
throw new Exception($"Error adding certificate {obj.certname}: {content}");
return responseMessage.StatusCode.ToString();
}
catch (HttpRequestException ex)
{
logger.LogError(FortigateException.FlattenExceptionMessages(ex, "Error performing POST: "));
throw;
}
finally
{
logger.MethodExit(LogLevel.Debug);
}
}
private void DeleteResource(string endpoint, Dictionary<String, String> additionalParams = null)
{
logger.MethodEntry(LogLevel.Debug);
try
{
HttpResponseMessage responseMessage = client.DeleteAsync(GetUrl(endpoint, additionalParams)).GetAwaiter().GetResult();
string content = responseMessage.Content.ReadAsStringAsync().GetAwaiter().GetResult();
if (!responseMessage.IsSuccessStatusCode)
throw new Exception($"Error removing certificate: {content}");
}
catch (HttpRequestException ex)
{
logger.LogError(FortigateException.FlattenExceptionMessages(ex, "Error performing DELETE: "));
throw;
}
finally
{
logger.MethodExit(LogLevel.Debug);
}
}
private void PutAsJson(string endpoint, Object obj, Dictionary<String, String> additionalParams = null)
{
logger.MethodEntry(LogLevel.Debug);
var stringContent = new StringContent(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json");
stringContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
try
{
HttpResponseMessage responseMessage = client.PutAsync(GetUrl(endpoint, additionalParams), stringContent).GetAwaiter().GetResult();
string content = responseMessage.Content.ReadAsStringAsync().GetAwaiter().GetResult();
if (!responseMessage.IsSuccessStatusCode)
throw new Exception(content);
}
catch (HttpRequestException ex)
{
logger.LogError(FortigateException.FlattenExceptionMessages(ex, "Error performing PUT: "));
throw;
}
finally
{
logger.MethodExit(LogLevel.Debug);
}
}
private String GetUrl(string endpoint, Dictionary<String, String> additionalParams = null)
{
logger.MethodEntry(LogLevel.Debug);
logger.MethodExit(LogLevel.Debug);
return AddQueryParams("https://" + FortigateHost + endpoint, additionalParams);
}
private String AddQueryParams(string endpoint, Dictionary<String, String> additionalParams = null)
{
logger.MethodEntry(LogLevel.Debug);
var parameters = new Dictionary<String, String>();
if (additionalParams != null)
{
foreach (var additionalParam in additionalParams)
{
parameters.Add(additionalParam.Key, additionalParam.Value);
}
}
var queryString = endpoint + "?" + string.Join("&", parameters.Select(kvp => $"{HttpUtility.UrlEncode(kvp.Key)}={HttpUtility.UrlEncode(kvp.Value)}"));
logger.MethodExit(LogLevel.Debug);
return queryString;
}
private string GetResource(string endpoint, Dictionary<String, String> additionalParams = null)
{
logger.MethodEntry(LogLevel.Debug);
try
{
return client.GetStringAsync(GetUrl(endpoint, additionalParams)).GetAwaiter().GetResult();
}
catch(HttpRequestException ex)
{
logger.LogError(FortigateException.FlattenExceptionMessages(ex, $"Error performing get resource: "));
throw;
}
finally
{
logger.MethodExit(LogLevel.Debug);
}
}
private string CreateNewAlias(string alias)
{
string suffix = $"--{DateTime.Now.Ticks.ToString("X8")}";
int suffixIdx = alias.IndexOf("--");
string newAlias = suffixIdx == -1 ? alias : alias.Substring(0, suffixIdx);
int aliasLengthOver = alias.Length + suffix.Length - 25;
if (aliasLengthOver > 0)
{
alias = alias.Substring(0, alias.Length - aliasLengthOver);
}
string rtnAlias = alias + suffix;
return rtnAlias;
}
}
}