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
|
using PKISharp.WACS.Clients.IIS;
using PKISharp.WACS.Extensions;
using PKISharp.WACS.Plugins.Base.Factories;
using PKISharp.WACS.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace PKISharp.WACS.Plugins.TargetPlugins
{
internal class IISOptionsFactory : TargetPluginOptionsFactory<IIS, IISOptions>
{
private readonly IISHelper _iisHelper;
private readonly ILogService _log;
private readonly IArgumentsService _arguments;
public IISOptionsFactory(
ILogService log,
IISHelper iisHelper,
IArgumentsService arguments,
IUserRoleService userRoleService)
{
_iisHelper = iisHelper;
_log = log;
_arguments = arguments;
Disabled = IIS.Disabled(userRoleService);
}
public override int Order => 2;
/// <summary>
/// Match with the legacy target plugin names
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public override bool Match(string name)
{
switch (name.ToLowerInvariant())
{
case "iisbinding":
case "iissite":
case "iissites":
return true;
default:
return base.Match(name);
}
}
/// <summary>
/// Get settings in interactive mode
/// </summary>
/// <param name="input"></param>
/// <param name="runLevel"></param>
/// <returns></returns>
public override async Task<IISOptions?> Aquire(IInputService input, RunLevel runLevel)
{
var allSites = _iisHelper.GetSites(true).Where(x => x.Hosts.Any()).ToList();
if (!allSites.Any())
{
_log.Error($"No sites with host bindings have been configured in IIS. " +
$"Add one in the IIS Manager or choose the plugin '{ManualOptions.DescriptionText}' " +
$"instead.");
return null;
}
var visibleSites = allSites.Where(x => !_arguments.MainArguments.HideHttps || x.Https == false).ToList();
if (!visibleSites.Any())
{
_log.Error("No sites with host bindings remain after applying the --{hidehttps} filter. " +
"It looks like all your websites are already configured for https!", "hidehttps");
return null;
}
// Remove sites with only wildcard bindings because they cannot be validated in simple mode
if (!runLevel.HasFlag(RunLevel.Advanced))
{
visibleSites = visibleSites.Where(x => x.Hosts.Any(h => !h.StartsWith("*"))).ToList();
if (!visibleSites.Any())
{
_log.Error("No sites with host bindings remain after discarding wildcard domains. To " +
"create certificates including wildcards, please use the 'Full options' mode, as " +
"this requires DNS validation.");
return null;
}
}
// Repeat the process until the user is happy with their settings
do
{
var allBindings = _iisHelper.GetBindings();
var visibleBindings = allBindings.Where(x => !_arguments.MainArguments.HideHttps || x.Https == false).ToList();
var ret = await TryAquireSettings(input, allBindings, visibleBindings, allSites, visibleSites, runLevel);
if (ret != null)
{
var filtered = _iisHelper.FilterBindings(allBindings, ret);
await ListBindings(input, filtered, ret.CommonName);
if (await input.PromptYesNo("Continue with this selection?", true))
{
return ret;
}
}
if (!await input.PromptYesNo("Restart?", true))
{
return null;
}
}
while (true);
}
/// <summary>
/// Single round of aquiring settings
/// </summary>
/// <param name="input"></param>
/// <param name="allBindings"></param>
/// <param name="visibleBindings"></param>
/// <param name="allSites"></param>
/// <param name="visibleSites"></param>
/// <param name="runLevel"></param>
/// <returns></returns>
private async Task<IISOptions?> TryAquireSettings(
IInputService input,
List<IISHelper.IISBindingOption> allBindings,
List<IISHelper.IISBindingOption> visibleBindings,
List<IISHelper.IISSiteOption> allSites,
List<IISHelper.IISSiteOption> visibleSites,
RunLevel runLevel)
{
input.CreateSpace();
input.Show(null, "Please select which website(s) should be scanned for host names. " +
"You may input one or more site identifiers (comma separated) to filter by those sites, " +
"or alternatively leave the input empty to scan *all* websites.");
var options = new IISOptions();
await input.WritePagedList(
visibleSites.Select(x => Choice.Create(
item: x,
description: $"{x.Name} ({x.Hosts.Count()} binding{(x.Hosts.Count() == 1 ? "" : "s")})",
command: x.Id.ToString(),
color: x.Https ? ConsoleColor.DarkGray : (ConsoleColor?)null)));
var raw = await input.RequestString("Site identifier(s) or <Enter> to choose all");
if (!ParseSiteOptions(raw, allSites, options))
{
return null;
}
var filtered = _iisHelper.FilterBindings(visibleBindings, options);
await ListBindings(input, filtered);
input.CreateSpace();
input.Show(null,
"Listed above are the bindings found on the selected site(s). By default all of " +
"them will be included, but you may either pick specific ones by typing the host names " +
"or identifiers (comma seperated) or filter them using one of the options from the " +
"menu.");
var askExclude = true;
var filters = new List<Choice<Func<Task>>>
{
Choice.Create<Func<Task>>(() => {
return InputPattern(input, options);
}, "Pick bindings based on a search pattern", command: "P"),
Choice.Create<Func<Task>>(() => {
askExclude = false;
return Task.CompletedTask;
}, "Pick *all* bindings", @default: true, command: "A")
};
if (runLevel.HasFlag(RunLevel.Advanced))
{
filters.Insert(1, Choice.Create<Func<Task>>(() => {
askExclude = true;
return InputRegex(input, options);
}, "Pick bindings based on a regular expression", command: "R"));
}
var chosen = await input.ChooseFromMenu(
"Binding identifiers(s) or menu option",
filters,
(unknown) =>
{
return Choice.Create<Func<Task>>(() =>
{
askExclude = false;
return ProcessInputHosts(
unknown, allBindings, filtered, options,
() => options.IncludeHosts, x => options.IncludeHosts = x);
});
});
await chosen.Invoke();
filtered = _iisHelper.FilterBindings(allBindings, options);
// Exclude specific bindings
if (askExclude && filtered.Count > 1 && runLevel.HasFlag(RunLevel.Advanced))
{
await ListBindings(input, filtered);
input.CreateSpace();
input.Show(null, "The listed bindings match your current filter settings. " +
"If you wish to exclude one or more of them from the certificate, please " +
"input those bindings now. Press <Enter> to include all listed bindings.");
await InputHosts("Exclude bindings",
input, allBindings, filtered, options,
() => options.ExcludeHosts, x => options.ExcludeHosts = x);
if (options.ExcludeHosts != null)
{
filtered = _iisHelper.FilterBindings(allBindings, options);
}
}
// Now the common name
if (filtered.Select(x => x.HostUnicode).Distinct().Count() > 1)
{
await InputCommonName(input, filtered, options);
}
return options;
}
/// <summary>
/// Allows users to input both the full host name, or the number that
/// it's referred to by in the displayed list
/// </summary>
/// <param name="label"></param>
/// <param name="input"></param>
/// <param name="allBindings"></param>
/// <param name="filtered"></param>
/// <param name="options"></param>
/// <param name="get"></param>
/// <param name="set"></param>
/// <returns></returns>
async Task InputHosts(
string label,
IInputService input,
List<IISHelper.IISBindingOption> allBindings,
List<IISHelper.IISBindingOption> filtered,
IISOptions options,
Func<List<string>?> get,
Action<List<string>> set)
{
string? raw;
do
{
raw = await input.RequestString(label);
}
while (!await ProcessInputHosts(raw, allBindings, filtered, options, get, set));
}
/// <summary>
/// Allows users to input both the full host name, or the number that
/// it's referred to by in the displayed list
/// </summary>
/// <param name="label"></param>
/// <param name="input"></param>
/// <param name="allBindings"></param>
/// <param name="filtered"></param>
/// <param name="options"></param>
/// <param name="get"></param>
/// <param name="set"></param>
/// <returns></returns>
async Task<bool> ProcessInputHosts(
string raw,
List<IISHelper.IISBindingOption> allBindings,
List<IISHelper.IISBindingOption> filtered,
IISOptions options,
Func<List<string>?> get,
Action<List<string>> set)
{
var sorted = SortBindings(filtered).ToList();
if (!string.IsNullOrEmpty(raw))
{
// Magically replace binding identifiers by their proper host names
raw = string.Join(",", raw.ParseCsv().Select(x =>
{
if (int.TryParse(x, out var id))
{
if (id > 0 && id <= sorted.Count())
{
return sorted[id - 1].HostUnicode;
}
}
return x;
}));
}
return ParseHostOptions(raw, allBindings, options, get, set);
}
async Task InputCommonName(IInputService input, List<IISHelper.IISBindingOption> filtered, IISOptions options)
{
var sorted = SortBindings(filtered).ToList();
var common = await input.ChooseRequired(
"Please pick the main host, which will be presented as the subject of the certificate",
sorted,
(x) => Choice.Create(x,
description: x.HostUnicode,
@default: sorted.IndexOf(x) == 0));
ParseCommonName(common.HostUnicode, filtered.Select(x => x.HostUnicode), options);
}
/// <summary>
/// Interactive input of a search pattern
/// </summary>
/// <param name="input"></param>
/// <param name="options"></param>
/// <returns></returns>
async Task InputPattern(IInputService input, IISOptions options)
{
input.CreateSpace();
input.Show(null, IISArgumentsProvider.PatternExamples);
string raw;
do
{
raw = await input.RequestString("Pattern");
}
while (!ParsePattern(raw, options));
}
async Task InputRegex(IInputService input, IISOptions options)
{
string raw;
do
{
raw = await input.RequestString("Regex");
}
while (!ParseRegex(raw, options));
}
private bool ParsePattern(string? pattern, IISOptions ret)
{
if (string.IsNullOrWhiteSpace(pattern))
{
_log.Error("Invalid input");
return false;
}
try
{
var regexString = pattern.PatternToRegex();
var actualRegex = new Regex(regexString);
ret.IncludePattern = pattern;
return true;
}
catch (Exception ex)
{
_log.Error(ex, "Unable to convert pattern to regex");
return false;
}
}
private bool ParseRegex(string? regex, IISOptions options)
{
if (string.IsNullOrWhiteSpace(regex))
{
_log.Error("Invalid input");
return false;
}
try
{
var actualRegex = new Regex(regex);
options.IncludeRegex = actualRegex;
return true;
}
catch (Exception ex)
{
_log.Error(ex, "Unable to convert pattern to regex");
return false;
}
}
/// <summary>
/// We need to use consistent sorting in both listing the bindings and parsing
/// user input for includes, excludes and common name picking
/// </summary>
/// <param name="bindings"></param>
/// <returns></returns>
private IEnumerable<IISHelper.IISBindingOption> SortBindings(IEnumerable<IISHelper.IISBindingOption> bindings) => bindings.OrderBy(x => x.HostUnicode).ThenBy(x => x.SiteId);
/// <summary>
/// List bindings for the user to pick from
/// </summary>
/// <param name="input"></param>
/// <param name="bindings"></param>
/// <param name="highlight"></param>
/// <returns></returns>
private async Task ListBindings(IInputService input, List<IISHelper.IISBindingOption> bindings, string? highlight = null)
{
var sortedBindings = SortBindings(bindings);
await input.WritePagedList(
sortedBindings.Select(x => Choice.Create(
item: x,
color: BindingColor(x, highlight))));
}
private ConsoleColor? BindingColor(IISHelper.IISBindingOption binding, string? highlight = null)
{
if (binding.HostUnicode == highlight)
{
return ConsoleColor.Green;
}
else if (binding.Https)
{
return ConsoleColor.DarkGray;
}
else
{
return default;
}
}
public override async Task<IISOptions?> Default()
{
var options = new IISOptions();
var args = _arguments.GetArguments<IISArguments>();
if (args == null)
{
return null;
}
if (string.IsNullOrWhiteSpace(args.Host) &&
string.IsNullOrWhiteSpace(args.Pattern) &&
string.IsNullOrWhiteSpace(args.Regex) &&
string.IsNullOrWhiteSpace(args.SiteId))
{
// Logically this would be a no-filter run: all
// bindings for all websites. Because the impact
// of that can be so high, we want the user to
// be explicit about it.
_log.Error("You have not specified any filters. If you are sure that you want " +
"to create a certificate for *all* bindings on the server, please specific " +
"--siteid s");
return null;
}
var allSites = _iisHelper.GetSites(false);
if (!ParseSiteOptions(args.SiteId, allSites, options))
{
return null;
}
var allBindings = _iisHelper.GetBindings();
if (!ParseHostOptions(args.Host, allBindings, options, () => options.IncludeHosts, x => options.IncludeHosts = x))
{
return null;
}
// Pattern
if (args.Pattern != null)
{
if (options.IncludeHosts != null)
{
_log.Error("Parameters --host and --host-pattern cannot be combined");
return null;
}
if (!ParsePattern(args.Pattern, options))
{
return null;
}
}
// Regex
if (args.Regex != null)
{
if (options.IncludeHosts != null)
{
_log.Error("Parameters --host and --host-regex cannot be combined");
return null;
}
if (options.IncludePattern != null)
{
_log.Error("Parameters --host-pattern and --host-regex cannot be combined");
return null;
}
if (!ParseRegex(args.Regex, options))
{
return null;
}
}
// Excludes
var filtered = _iisHelper.FilterBindings(allBindings, options);
if (options.IncludeHosts == null && !string.IsNullOrEmpty(args.ExcludeBindings))
{
if (!ParseHostOptions(args.ExcludeBindings, filtered, options, () => options.ExcludeHosts, x => options.ExcludeHosts = x))
{
return null;
}
filtered = _iisHelper.FilterBindings(allBindings, options);
}
// Common name
if (args.CommonName != null)
{
if (!ParseCommonName(args.CommonName, filtered.Select(x => x.HostUnicode), options))
{
return null;
}
}
return options;
}
/// <summary>
/// Host filtering options in unattended mode
/// </summary>
/// <param name="args"></param>
/// <param name="bindings"></param>
/// <param name="options"></param>
private bool ParseHostOptions(
string? input,
List<IISHelper.IISBindingOption> allBindings,
IISOptions options,
Func<List<string>?> get,
Action<List<string>> set)
{
var specifiedHosts = input.ParseCsv();
if (specifiedHosts != null)
{
var filteredBindings = _iisHelper.FilterBindings(allBindings, options);
foreach (var specifiedHost in specifiedHosts)
{
var filteredBinding = filteredBindings.FirstOrDefault(x => x.HostUnicode == specifiedHost || x.HostPunycode == specifiedHost);
var binding = allBindings.FirstOrDefault(x => x.HostUnicode == specifiedHost || x.HostPunycode == specifiedHost);
if (filteredBinding != null)
{
var list = get();
if (list == null)
{
list = new List<string>();
set(list);
}
list.Add(filteredBinding.HostUnicode);
}
else if (binding != null)
{
_log.Error("Binding {specifiedHost} is excluded by another filter", specifiedHost);
return false;
}
else
{
_log.Error("Binding {specifiedHost} not found", specifiedHost);
return false;
}
}
}
return true;
}
/// <summary>
/// Advanced options in unattended mode
/// </summary>
/// <param name="args"></param>
/// <param name="chosen"></param>
/// <param name="ret"></param>
/// <returns></returns>
private bool ParseCommonName(string commonName, IEnumerable<string> chosen, IISOptions ret)
{
if (string.IsNullOrWhiteSpace(commonName))
{
return false;
}
commonName = commonName.ToLower().Trim().ConvertPunycode();
if (chosen.Contains(commonName))
{
ret.CommonName = commonName;
return true;
}
else
{
_log.Error("Common name {commonName} not found or excluded", commonName);
return false;
}
}
/// <summary>
/// SiteId filter in unattended mode
/// </summary>
/// <param name="args"></param>
/// <param name="options"></param>
/// <returns></returns>
private bool ParseSiteOptions(string? input, List<IISHelper.IISSiteOption> sites, IISOptions options)
{
if (string.IsNullOrEmpty(input))
{
return true;
}
if (string.Equals(input, "s", StringComparison.InvariantCultureIgnoreCase))
{
return true;
}
var identifiers = input.ParseCsv();
if (identifiers == null)
{
throw new InvalidOperationException("No identifiers found");
}
var ret = new List<long>();
foreach (var identifierString in identifiers)
{
if (long.TryParse(identifierString, out var id))
{
var site = sites.Where(t => t.Id == id).FirstOrDefault();
if (site != null)
{
ret.Add(site.Id);
}
else
{
_log.Error("Site identifier '{id}' not found", id);
return false;
}
}
else
{
_log.Error("Invalid site identifier '{identifierString}', should be a number", identifierString);
return false;
}
}
options.IncludeSiteIds = ret;
return true;
}
}
}
|