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
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
|
using Autofac;
using PKISharp.WACS.Configuration;
using PKISharp.WACS.DomainObjects;
using PKISharp.WACS.Extensions;
using PKISharp.WACS.Plugins.TargetPlugins;
using PKISharp.WACS.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace PKISharp.WACS
{
internal class RenewalManager
{
private readonly IInputService _input;
private readonly ILogService _log;
private readonly IRenewalStore _renewalStore;
private readonly IArgumentsService _arguments;
private readonly MainArguments _args;
private readonly IContainer _container;
private readonly IAutofacBuilder _scopeBuilder;
private readonly ExceptionHandler _exceptionHandler;
private readonly RenewalExecutor _renewalExecutor;
private readonly ISettingsService _settings;
public RenewalManager(
IArgumentsService arguments, MainArguments args,
IRenewalStore renewalStore, IContainer container,
IInputService input, ILogService log,
ISettingsService settings,
IAutofacBuilder autofacBuilder, ExceptionHandler exceptionHandler,
RenewalExecutor renewalExecutor)
{
_renewalStore = renewalStore;
_args = args;
_input = input;
_log = log;
_settings = settings;
_arguments = arguments;
_container = container;
_scopeBuilder = autofacBuilder;
_exceptionHandler = exceptionHandler;
_renewalExecutor = renewalExecutor;
}
/// <summary>
/// Renewal management mode
/// </summary>
/// <returns></returns>
internal async Task ManageRenewals()
{
IEnumerable<Renewal> originalSelection = _renewalStore.Renewals.OrderBy(x => x.LastFriendlyName);
var selectedRenewals = originalSelection;
var quit = false;
var displayAll = false;
do
{
var all = selectedRenewals.Count() == originalSelection.Count();
var none = selectedRenewals.Count() == 0;
var totalLabel = originalSelection.Count() != 1 ? "renewals" : "renewal";
var renewalSelectedLabel = selectedRenewals.Count() != 1 ? "renewals" : "renewal";
var selectionLabel =
all ? selectedRenewals.Count() == 1 ? "the renewal" : "*all* renewals" :
none ? "no renewals" :
$"{selectedRenewals.Count()} of {originalSelection.Count()} {totalLabel}";
_input.CreateSpace();
_input.Show(null,
"Welcome to the renewal manager. Actions selected in the menu below will " +
"be applied to the following list of renewals. You may filter the list to target " +
"your action at a more specific set of renewals, or sort it to make it easier to " +
"find what you're looking for.");
var displayRenewals = selectedRenewals;
var displayLimited = !displayAll && selectedRenewals.Count() >= _settings.UI.PageSize;
var displayHidden = 0;
var displayHiddenLabel = "";
if (displayLimited)
{
displayRenewals = displayRenewals.Take(_settings.UI.PageSize - 1);
displayHidden = selectedRenewals.Count() - displayRenewals.Count();
displayHiddenLabel = displayHidden != 1 ? "renewals" : "renewal";
}
var choices = displayRenewals.Select(x => Choice.Create<Renewal?>(x,
description: x.ToString(_input),
color: x.History.LastOrDefault()?.Success ?? false ?
x.IsDue() ?
ConsoleColor.DarkYellow :
ConsoleColor.Green :
ConsoleColor.Red)).ToList();
if (displayLimited)
{
choices.Add(Choice.Create<Renewal?>(null,
command: "More",
description: $"{displayHidden} additional {displayHiddenLabel} selected but currently not displayed"));
}
await _input.WritePagedList(choices);
displayAll = false;
var options = new List<Choice<Func<Task>>>();
if (displayLimited)
{
options.Add(
Choice.Create<Func<Task>>(
() => { displayAll = true; return Task.CompletedTask; },
"List all selected renewals", "A"));
}
if (selectedRenewals.Count() > 1)
{
options.Add(
Choice.Create<Func<Task>>(
async () => selectedRenewals = await FilterRenewalsMenu(selectedRenewals),
all ? "Apply filter" : "Apply additional filter", "F",
@disabled: (selectedRenewals.Count() < 2, "Not enough renewals to filter.")));
options.Add(
Choice.Create<Func<Task>>(
async () => selectedRenewals = await SortRenewalsMenu(selectedRenewals),
"Sort renewals", "S",
@disabled: (selectedRenewals.Count() < 2, "Not enough renewals to sort.")));
}
if (!all)
{
options.Add(
Choice.Create<Func<Task>>(
() => { selectedRenewals = originalSelection; return Task.CompletedTask; },
"Reset sorting and filtering", "X",
@disabled: (all, "No filters have been applied yet.")));
}
options.Add(
Choice.Create<Func<Task>>(
async () => {
foreach (var renewal in selectedRenewals) {
var index = selectedRenewals.ToList().IndexOf(renewal) + 1;
_log.Information("Details for renewal {n}/{m}", index, selectedRenewals.Count());
await ShowRenewal(renewal);
var cont = false;
if (index != selectedRenewals.Count())
{
cont = await _input.Wait("Press <Enter> to continue or <Esc> to abort");
if (!cont)
{
break;
}
}
else
{
await _input.Wait();
}
}
},
$"Show details for {selectionLabel}", "D",
@disabled: (none, "No renewals selected.")));
options.Add(
Choice.Create<Func<Task>>(
async () => {
WarnAboutRenewalArguments();
foreach (var renewal in selectedRenewals)
{
var runLevel = RunLevel.Interactive | RunLevel.ForceRenew;
if (_args.Force)
{
runLevel |= RunLevel.IgnoreCache;
}
await ProcessRenewal(renewal, runLevel);
}
},
$"Run {selectionLabel}", "R",
@disabled: (none, "No renewals selected.")));
options.Add(
Choice.Create<Func<Task>>(
async () => selectedRenewals = await Analyze(selectedRenewals),
$"Analyze duplicates for {selectionLabel}", "U",
@disabled: (none, "No renewals selected.")));
options.Add(
Choice.Create<Func<Task>>(
async () => {
var confirm = await _input.PromptYesNo($"Are you sure you want to cancel {selectedRenewals.Count()} currently selected {renewalSelectedLabel}?", false);
if (confirm)
{
foreach (var renewal in selectedRenewals)
{
_renewalStore.Cancel(renewal);
};
originalSelection = _renewalStore.Renewals.OrderBy(x => x.LastFriendlyName);
selectedRenewals = originalSelection;
}
},
$"Cancel {selectionLabel}", "C",
@disabled: (none, "No renewals selected.")));
options.Add(
Choice.Create<Func<Task>>(
async () => {
var confirm = await _input.PromptYesNo($"Are you sure you want to revoke the most recently issued certificate for {selectedRenewals.Count()} currently selected {renewalSelectedLabel}? This should only be done in case of a (suspected) security breach. Cancel the {renewalSelectedLabel} if you simply don't need the certificates anymore.", false);
if (confirm)
{
await RevokeCertificates(selectedRenewals);
}
},
$"Revoke certificate(s) for {selectionLabel}", "V",
@disabled: (none, "No renewals selected.")));
options.Add(
Choice.Create<Func<Task>>(
() => { quit = true; return Task.CompletedTask; },
"Back", "Q",
@default: originalSelection.Count() == 0));
if (selectedRenewals.Count() > 1)
{
_input.CreateSpace();
_input.Show(null, $"Currently selected {selectedRenewals.Count()} of {originalSelection.Count()} {totalLabel}");
}
var chosen = await _input.ChooseFromMenu(
"Choose an action or type numbers to select renewals",
options,
(string unexpected) =>
Choice.Create<Func<Task>>(
async () => selectedRenewals = await FilterRenewalsById(selectedRenewals, unexpected)));
await chosen.Invoke();
}
while (!quit);
}
/// <summary>
/// Check if there are multiple renewals installing to the same site
/// or requesting certificates for the same domains
/// </summary>
/// <param name="selectedRenewals"></param>
/// <returns></returns>
private async Task<IEnumerable<Renewal>> Analyze(IEnumerable<Renewal> selectedRenewals)
{
var foundHosts = new Dictionary<string, List<Renewal>>();
var foundSites = new Dictionary<long, List<Renewal>>();
foreach (var renewal in selectedRenewals)
{
using var targetScope = _scopeBuilder.Target(_container, renewal, RunLevel.Unattended);
var target = targetScope.Resolve<Target>();
foreach (var targetPart in target.Parts)
{
if (targetPart.SiteId != null)
{
var siteId = targetPart.SiteId.Value;
if (!foundSites.ContainsKey(siteId))
{
foundSites.Add(siteId, new List<Renewal>());
}
foundSites[siteId].Add(renewal);
}
foreach (var host in targetPart.GetHosts(true))
{
if (!foundHosts.ContainsKey(host))
{
foundHosts.Add(host, new List<Renewal>());
}
foundHosts[host].Add(renewal);
}
}
}
// List results
var options = new List<Choice<List<Renewal>>>();
foreach (var site in foundSites)
{
if (site.Value.Count() > 1)
{
options.Add(
Choice.Create(
site.Value,
$"Select {site.Value.Count()} renewals covering IIS site {site.Key}"));
}
}
foreach (var host in foundHosts)
{
if (host.Value.Count() > 1)
{
options.Add(
Choice.Create(
host.Value,
$"Select {host.Value.Count()} renewals covering host {host.Key}"));
}
}
_input.CreateSpace();
if (options.Count == 0)
{
_input.Show(null, "Analysis didn't find any overlap between renewals.");
return selectedRenewals;
}
else
{
options.Add(
Choice.Create(
selectedRenewals.ToList(),
$"Back"));
_input.Show(null, "Analysis found some overlap between renewals. You can select the overlapping renewals from the menu.");
return await _input.ChooseFromMenu("Please choose from the menu", options);
}
}
/// <summary>
/// Offer user different ways to sort the renewals
/// </summary>
/// <param name="current"></param>
/// <returns></returns>
private async Task<IEnumerable<Renewal>> SortRenewalsMenu(IEnumerable<Renewal> current)
{
var options = new List<Choice<Func<IEnumerable<Renewal>>>>
{
Choice.Create<Func<IEnumerable<Renewal>>>(
() => current.OrderBy(x => x.LastFriendlyName),
"Sort by friendly name",
@default: true),
Choice.Create<Func<IEnumerable<Renewal>>>(
() => current.OrderByDescending(x => x.LastFriendlyName),
"Sort by friendly name (descending)"),
Choice.Create<Func<IEnumerable<Renewal>>>(
() => current.OrderBy(x => x.GetDueDate()),
"Sort by due date"),
Choice.Create<Func<IEnumerable<Renewal>>>(
() => current.OrderByDescending(x => x.GetDueDate()),
"Sort by due date (descending)")
};
var chosen = await _input.ChooseFromMenu("How would you like to sort the renewals list?", options);
return chosen.Invoke();
}
/// <summary>
/// Offer user different ways to filter the renewals
/// </summary>
/// <param name="current"></param>
/// <returns></returns>
private async Task<IEnumerable<Renewal>> FilterRenewalsMenu(IEnumerable<Renewal> current)
{
var options = new List<Choice<Func<Task<IEnumerable<Renewal>>>>>
{
Choice.Create<Func<Task<IEnumerable<Renewal>>>>(
() => FilterRenewalsByFriendlyName(current),
"Filter by friendly name"),
Choice.Create<Func<Task<IEnumerable<Renewal>>>>(
() => Task.FromResult(current.Where(x => x.IsDue())),
"Keep only due renewals"),
Choice.Create<Func<Task<IEnumerable<Renewal>>>>(
() => Task.FromResult(current.Where(x => !x.IsDue())),
"Remove due renewals"),
Choice.Create<Func<Task<IEnumerable<Renewal>>>>(
() => Task.FromResult(current.Where(x => !x.History.Last().Success)),
"Keep only renewals with errors"),
Choice.Create<Func<Task<IEnumerable<Renewal>>>>(
() => Task.FromResult(current.Where(x => x.History.Last().Success)),
"Remove renewals with errors"),
Choice.Create<Func<Task<IEnumerable<Renewal>>>>(
() => Task.FromResult(current),
"Cancel")
};
var chosen = await _input.ChooseFromMenu("How would you like to filter?", options);
return await chosen.Invoke();
}
private async Task<IEnumerable<Renewal>> FilterRenewalsById(IEnumerable<Renewal> current, string input)
{
var parts = input.ParseCsv();
if (parts == null)
{
return current;
}
var ret = new List<Renewal>();
foreach (var part in parts)
{
if (int.TryParse(part, out var index))
{
if (index > 0 && index <= current.Count())
{
ret.Add(current.ElementAt(index - 1));
}
else
{
_log.Warning("Input out of range: {part}", part);
}
}
else
{
_log.Warning("Invalid input: {part}", part);
}
}
return ret;
}
/// <summary>
/// Filter specific renewals by friendly name
/// </summary>
/// <param name="current"></param>
/// <returns></returns>
private async Task<IEnumerable<Renewal>> FilterRenewalsByFriendlyName(IEnumerable<Renewal> current)
{
_input.CreateSpace();
_input.Show(null, "Please input friendly name to filter renewals by. " + IISArgumentsProvider.PatternExamples);
var rawInput = await _input.RequestString("Friendly name");
var ret = new List<Renewal>();
var regex = new Regex(rawInput.PatternToRegex(), RegexOptions.IgnoreCase);
foreach (var r in current)
{
if (regex.Match(r.LastFriendlyName).Success)
{
ret.Add(r);
}
}
return ret;
}
/// <summary>
/// Filters for unattended mode
/// </summary>
/// <param name="command"></param>
/// <returns></returns>
private async Task<IEnumerable<Renewal>> FilterRenewalsByCommandLine(string command)
{
if (_arguments.HasFilter())
{
var targets = _renewalStore.FindByArguments(
_arguments.MainArguments.Id,
_arguments.MainArguments.FriendlyName);
if (targets.Count() == 0)
{
_log.Error("No renewals matched.");
}
return targets;
}
else
{
_log.Error($"Specify which renewal to {command} using the parameter --id or --friendlyname.");
}
return new List<Renewal>();
}
/// <summary>
/// Loop through the store renewals and run those which are
/// due to be run
/// </summary>
internal async Task CheckRenewals(RunLevel runLevel)
{
IEnumerable<Renewal> renewals;
if (_arguments.HasFilter())
{
renewals = _renewalStore.FindByArguments(_args.Id, _args.FriendlyName);
if (renewals.Count() == 0)
{
_log.Error("No renewals found that match the filter parameters --id and/or --friendlyname.");
}
}
else
{
_log.Verbose("Checking renewals");
renewals = _renewalStore.Renewals;
if (renewals.Count() == 0)
{
_log.Warning("No scheduled renewals found.");
}
}
if (renewals.Count() > 0)
{
WarnAboutRenewalArguments();
foreach (var renewal in renewals)
{
try
{
var success = await ProcessRenewal(renewal, runLevel);
if (!success)
{
// Make sure the ExitCode is set
_exceptionHandler.HandleException();
}
}
catch (Exception ex)
{
_exceptionHandler.HandleException(ex, "Unhandled error processing renewal");
continue;
}
}
}
}
/// <summary>
/// Process a single renewal
/// </summary>
/// <param name="renewal"></param>
internal async Task<bool> ProcessRenewal(Renewal renewal, RunLevel runLevel)
{
var notification = _container.Resolve<NotificationService>();
try
{
var result = await _renewalExecutor.HandleRenewal(renewal, runLevel);
if (!result.Abort)
{
_renewalStore.Save(renewal, result);
if (result.Success)
{
await notification.NotifySuccess(renewal, _log.Lines);
return true;
}
else
{
await notification.NotifyFailure(runLevel, renewal, result.ErrorMessages, _log.Lines);
}
}
else
{
return true;
}
}
catch (Exception ex)
{
_exceptionHandler.HandleException(ex);
await notification.NotifyFailure(runLevel, renewal, new List<string> { ex.Message }, _log.Lines);
}
return false;
}
/// <summary>
/// Show a warning when the user appears to be trying to
/// use command line arguments in combination with a renew
/// command.
/// </summary>
internal void WarnAboutRenewalArguments()
{
if (_arguments.Active)
{
_log.Warning("You have specified command line options for plugins. " +
"Note that these only affect new certificates, but NOT existing renewals. " +
"To change settings, re-create (overwrite) the renewal.");
}
}
/// <summary>
/// Show certificate details
/// </summary>
private async Task ShowRenewal(Renewal renewal)
{
try
{
_input.CreateSpace();
_input.Show("Id", renewal.Id);
_input.Show("File", $"{renewal.Id}.renewal.json");
_input.Show("FriendlyName", string.IsNullOrEmpty(renewal.FriendlyName) ? $"[Auto] {renewal.LastFriendlyName}" : renewal.FriendlyName);
_input.Show(".pfx password", renewal.PfxPassword?.Value);
_input.Show("Renewal due", renewal.GetDueDate()?.ToString() ?? "now");
_input.Show("Renewed", $"{renewal.History.Where(x => x.Success).Count()} times");
renewal.TargetPluginOptions.Show(_input);
renewal.ValidationPluginOptions.Show(_input);
if (renewal.OrderPluginOptions != null)
{
renewal.OrderPluginOptions.Show(_input);
}
if (renewal.CsrPluginOptions != null)
{
renewal.CsrPluginOptions.Show(_input);
}
foreach (var ipo in renewal.StorePluginOptions)
{
ipo.Show(_input);
}
foreach (var ipo in renewal.InstallationPluginOptions)
{
ipo.Show(_input);
}
var historyLimit = 10;
if (renewal.History.Count <= historyLimit)
{
_input.Show("History");
}
else
{
_input.Show($"History (most recent {historyLimit} of {renewal.History.Count} entries)");
}
await _input.WritePagedList(
renewal.History.
AsEnumerable().
Reverse().
Take(historyLimit).
Reverse().
Select(x => Choice.Create(x)));
}
catch (Exception ex)
{
_log.Error(ex, "Unable to list details for target");
}
}
#region Unattended
/// <summary>
/// For command line --list
/// </summary>
/// <returns></returns>
internal async Task ShowRenewalsUnattended()
{
await _input.WritePagedList(
_renewalStore.Renewals.Select(x => Choice.Create<Renewal?>(x,
description: x.ToString(_input),
color: x.History.Last().Success ?
x.IsDue() ?
ConsoleColor.DarkYellow :
ConsoleColor.Green :
ConsoleColor.Red)));
}
/// <summary>
/// Cancel certificate from the command line
/// </summary>
/// <returns></returns>
internal async Task CancelRenewalsUnattended()
{
var targets = await FilterRenewalsByCommandLine("cancel");
foreach (var t in targets)
{
_renewalStore.Cancel(t);
}
}
/// <summary>
/// Revoke certifcate from the command line
/// </summary>
/// <returns></returns>
internal async Task RevokeCertificatesUnattended()
{
_log.Warning($"Certificates should only be revoked in case of a (suspected) security breach. Cancel the renewal if you simply don't need the certificate anymore.");
var renewals = await FilterRenewalsByCommandLine("revoke");
await RevokeCertificates(renewals);
}
/// <summary>
/// Shared code for command line and renewal manager
/// </summary>
/// <param name="renewals"></param>
/// <returns></returns>
internal async Task RevokeCertificates(IEnumerable<Renewal> renewals)
{
foreach (var renewal in renewals)
{
using var scope = _scopeBuilder.Execution(_container, renewal, RunLevel.Unattended);
var cs = scope.Resolve<ICertificateService>();
try
{
await cs.RevokeCertificate(renewal);
renewal.History.Add(new RenewResult("Certificate(s) revoked"));
}
catch (Exception ex)
{
_exceptionHandler.HandleException(ex);
}
}
}
#endregion
}
}
|