-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathProgram.cs
More file actions
690 lines (620 loc) · 27.3 KB
/
Program.cs
File metadata and controls
690 lines (620 loc) · 27.3 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
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
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using Mono.Options;
using System.Reflection;
using System.Text.RegularExpressions;
using System.IO;
using System.Threading.Tasks;
using System.Diagnostics.CodeAnalysis;
namespace NeoSmart.SecureStore.Client
{
static class Program
{
/// <summary>
/// The maximum number of levels to test when checking if a path is under VCS control.
/// </summary>
const int MAX_VCS_CHECK_DEPTH = 48;
static readonly Assembly Assembly = typeof(Program).GetTypeInfo().Assembly;
static string AssemblyVersion
{
get
{
var regex = new Regex("Version=(.*?),");
var fullVersion = regex.Match(Assembly.FullName!).Groups[1].Value;
while (fullVersion.EndsWith(".0") && fullVersion.Length > "1.0".Length)
{
fullVersion = fullVersion.Substring(0, fullVersion.Length - 2);
}
return fullVersion;
}
}
private static bool Parse(string value, out DecryptFormat format)
{
switch (value)
{
case "json":
format = DecryptFormat.Json;
return true;
case "text":
format = DecryptFormat.PlainText;
return true;
default:
format = DecryptFormat.None;
return false;
}
}
enum CliMode
{
None,
Help,
Version,
Create,
Get,
Set,
Delete,
}
enum VcsType
{
None,
Git,
}
/// <summary>
/// Checks the path and its parent directories to determine if it is under VCS control.
/// </summary>
/// <param name="path">The path to check if managed by VCS.</param>
/// <returns>The <see cref="VcsType"/> managing the <paramref name="path"/>, or <see cref="VcsType.None"/>.</returns>
private static VcsType GetVcsType(string path, int maxParents = MAX_VCS_CHECK_DEPTH)
{
var vcsPatterns = new[] { (Vcs: VcsType.Git, Path: ".git") };
var parent = Path.GetDirectoryName(Path.GetFullPath(path));
for (int i = 0; !string.IsNullOrEmpty(parent) && i < maxParents; ++i)
{
foreach (var vcs in vcsPatterns)
{
var vcsPath = Path.Join(parent, vcs.Path);
if (Directory.Exists(vcsPath))
{
return vcs.Vcs;
}
}
parent = Path.GetDirectoryName(parent);
}
return VcsType.None;
}
/// <summary>
/// Add's a VCS ignore rule for the path <paramref name="path"/> in the ignore file <paramref name="ignoreFile"/>
/// according to the conventions of the VCS <paramref name="vcs"/>.
/// </summary>
/// <param name="vcs"></param>
/// <param name="path"></param>
/// <returns></returns>
private async static Task<bool> AddIgnoreRuleAsync(VcsType vcs, string path, string ignoreFileDir)
{
var ignoreFile = vcs switch
{
VcsType.Git => Path.Combine(ignoreFileDir, ".gitignore"),
_ => throw new NotImplementedException("Support for this VCS is not yet implemented!"),
};
if (Path.GetDirectoryName(ignoreFile) != Path.GetDirectoryName(path))
{
throw new InvalidOperationException("Only ignore files in the same directory as the path to ignore are currently supported!");
}
if (!File.Exists(path))
{
throw new InvalidOperationException($"The file to ignore \"{path}\" is not a regular file!");
}
if (File.Exists(ignoreFile) && ((File.GetAttributes(ignoreFile) & (FileAttributes.Directory | FileAttributes.ReadOnly | FileAttributes.Device)) != 0))
{
throw new InvalidOperationException($"The ignore file \"{ignoreFile}\" exists and is not a regular file!");
}
var ignoreFileStatus = "existing";
var filename = Path.GetFileName(path);
var extension = Path.GetExtension(path);
if (!File.Exists(ignoreFile))
{
File.Create(ignoreFile).Dispose();
ignoreFileStatus = "newly-created";
}
// This is a valid exclude rule even if extension is empty
var wildcardExclude = $"*{extension}";
using (var reader = new StreamReader(File.Open(ignoreFile, FileMode.Open, FileAccess.Read, FileShare.Read)))
{
string? line;
while ((line = await reader.ReadLineAsync()) != null)
{
// Since we are excluding a file in the same directory, both /foo and foo will match
line = line.TrimStart('/').TrimEnd();
if (line == filename || line == wildcardExclude)
{
// The path is already excluded
return true;
}
}
}
using (var writer = new StreamWriter(File.Open(ignoreFile, FileMode.Append, FileAccess.Write, FileShare.None)))
{
await writer.WriteLineAsync("# SecureStore key file ignore rule:");
await writer.WriteLineAsync($"/{filename}");
}
await Console.Error.WriteLineAsync($"Excluding key file in {ignoreFileStatus} VCS ignore file {ignoreFile}");
return true;
}
static async Task Main(string[] mainArgs)
{
// Tweak the default VaultVersionPolicy to allow upgrades when the CLI is used to interface
// with the vault (by default, silent upgrades across major vault versions are prohibited to
// protect against schema downgrade attacks).
SecretsManager.VaultVersionPolicy = Versioning.VaultVersionPolicy.Upgrade;
var args = new List<string>(mainArgs);
bool help = false;
bool version = false;
string? path = null;
string? password = null;
string? keyfile = null;
string? keyExport = null;
string? secretName = null;
string? secretValue = null;
bool decryptAll = false;
DecryptFormat format = DecryptFormat.None;
var globalOptions = new OptionSet
{
{ "h|help|?", "Show this help message and exit", _ => help = true },
{ "v|version", "Print version information and exit", _ => version = true },
{ "s|store=", "Load secrets store from provided path", s => path = s },
{ "p|password:", "Prompt for decryption password", p => password = p ?? "" },
{ "k|keyfile=", "Load/save decryption key from/to path", k => keyfile = k },
{ "export-key=", "Export a copy of the key to path", k => keyExport = k },
};
var options = new Dictionary<string, OptionSet>();
options["create"] = new OptionSet
{
{ "h|help", "Show help for create command options", _ => help = true },
// password is : because automated systems may use the command line to specify passwords. This may change!
{ "p|password:", "Secure store with a key derived from a password", p => password = p ?? "" },
{ "k|keyfile=", "Path to load or save secure key from/to", k => keyfile = k },
{ "export-key=", "Export a copy of the key to path", k => keyExport = k },
};
options["delete"] = new OptionSet
{
{ "h|help", "Show help for delete command options", _ => help = true },
{ "s|store=", "Load secrets store from provided path", s => path = s },
// password is : because automated systems may use the command line to specify passwords. This may change!
{ "p|password:", "Decrypt store with key derived from password", p => password = p ?? "" },
{ "k|keyfile=", "Path to load secure key from", k => keyfile = k },
{ "export-key=", "Export a copy of the key to path", k => keyExport = k },
};
options["get"] = new OptionSet
{
{ "h|help", "Show help for decryption command options", _ => help = true },
{ "s|store=", "Load secrets store from provided path", s => path = s },
// password is : because automated systems may use the command line to specify passwords. This may change!
{ "p|password:", "Decrypt store with key derived from password", p => password = p ?? "" },
{ "k|keyfile=", "Path to load secure key from", k => keyfile = k },
{ "a|all", "Decrypt the entire contents of the store and print to stdout", _ => decryptAll = true },
{ "t|output-format=", "Specify the output format: json (default), text", t => { if (!Parse(t, out format)) throw new ExitCodeException(1, "Unsupported format specified!"); } },
{ "export-key=", "Export a copy of the key to path", k => keyExport = k },
};
options["set"] = new OptionSet
{
{ "h|help", "Show help for encryption command options", _ => help = true },
{ "s|store=", "Load secrets store from provided path", s => path = s },
// password is : because automated systems may use the command line to specify passwords. This may change!
{ "p|password:", "Decrypt store with key derived from password", p => password = p ?? "" },
{ "k|keyfile=", "Path to load secure key from", k => keyfile = k },
{ "export-key=", "Export a copy of the key to path", k => keyExport = k },
};
void printUsage(TextWriter output)
{
output.WriteLine($"ssclient [FLAGS] [create|set|get|delete] OPTIONS");
PrintOptions(output, null, globalOptions);
output.WriteLine();
foreach (var kv in options) {
PrintOptions(output, kv.Key, kv.Value);
}
}
if (args.Count == 0)
{
Console.Out.Write("Usage: ");
printUsage(Console.Out);
Environment.Exit(1);
}
// Only try to parse --help and --version
globalOptions.Parse(args);
void printVersion()
{
Console.Out.WriteLine($"ssclient {AssemblyVersion} - SecureStore secrets manager client");
Console.Out.WriteLine("Copyright NeoSmart Technologies 2017-2022 - https://github.com/neosmart/SecureStore/");
}
if (help)
{
printVersion();
Console.Out.WriteLine();
Console.Out.Write("Usage: ");
printUsage(Console.Out);
Environment.Exit(0);
}
if (version)
{
printVersion();
Environment.Exit(0);
}
int commandIndex = args.FindIndex(arg => options.ContainsKey(arg));
if (commandIndex < 0)
{
printUsage(Console.Error);
Environment.Exit(1);
}
string command = args[commandIndex].ToLower();
args.RemoveAt(commandIndex);
OptionSet parseOptions = options[command];
int exitCode = 0;
try
{
// Mono.Options is dumb and does not treat --password PASSWORD
// as an option:value tuple when password is defined as taking an optional value.
// It instead requires --password=PASSWORD or --password:PASSWORD or -pPASSWORD
var bareArguments = parseOptions.Parse(args);
var passwordMode = password == string.Empty; // instead of null
if (bareArguments.Count > 0 && passwordMode)
{
// Check if this was the standalone password
var possibles = new[] { "-p", "--password", "/p", "/password" };
for (int i = 0; i < args.Count - 1; ++i)
{
if (!possibles.Contains(args[i]))
{
continue;
}
// This was the password index
var bareIndex = bareArguments.FindIndex(arg => arg == args[i + 1]);
if (bareIndex >= 0)
{
password = bareArguments[bareIndex];
bareArguments.RemoveAt(bareIndex);
break;
}
}
}
// Consume remaining bare parameters before carrying out any actions so we can validate
// there are no unexpected bare parameters.
if (command == "create")
{
if (bareArguments.Count > 0 && string.IsNullOrEmpty(path))
{
path = bareArguments[0];
bareArguments.RemoveAt(0);
}
}
else if (command == "get" || command == "delete")
{
if (!decryptAll && bareArguments.Count != 1)
{
Console.Error.WriteLine("Expected the name of a single secret to look up or delete!");
throw new ExitCodeException(1);
}
else if (!decryptAll)
{
secretName = bareArguments[0];
bareArguments.RemoveAt(0);
}
}
else if (command == "set")
{
if (bareArguments.Count == 1 && bareArguments[0].Contains('='))
{
var parts = bareArguments[0].Split('=', 2);
secretName = parts[0];
secretValue = parts[1];
bareArguments.RemoveAt(0);
}
else if (bareArguments.Count == 2 && !bareArguments[0].Contains('='))
{
secretName = bareArguments[0];
secretValue = bareArguments[1];
bareArguments.RemoveRange(0, 2);
}
else
{
Console.Error.WriteLine("Expected a single \"key=value\" or \"key\" \"value\" to set!");
throw new ExitCodeException(1);
}
}
// Handle common parameters
// if (bareArguments.Count > 0)
// {
// Console.Error.Write($"BareArguments[0]: {bareArguments[0]}");
// Help(Console.Error, "Invalid arguments!", command, parseOptions);
// }
if (path is null)
{
// Help(Console.Error, "A path to the secrets store is required!", command, parseOptions);
// Default to secrets.json rather than error out
path = "secrets.json";
}
if (string.IsNullOrWhiteSpace(path))
{
Help(Console.Error, "A path to the secrets store is required!", command, parseOptions);
}
if (keyfile == null && !passwordMode)
{
// Changed: Default to password mode instead of erroring out
// Help(Console.Error, "Must specify either --password or --keyfile!", command, parseOptions);
password = string.Empty;
passwordMode = true;
}
if (passwordMode)
{
if (command == "create")
{
while (string.IsNullOrWhiteSpace(password))
{
Console.Write("New password: ");
var password1 = GetPassword();
Console.Write("Confirm password: ");
var password2 = GetPassword();
if (password1 == password2)
{
password = password1;
}
}
}
else
{
while (string.IsNullOrWhiteSpace(password))
{
Console.Write("Password: ");
password = GetPassword();
}
}
}
SecretsManager? sman = null;
// Handle parameters specific to certain commands
if (command == "create")
{
if (!passwordMode && string.IsNullOrWhiteSpace(keyfile))
{
// This block should no longer be reachable!
Console.Error.WriteLine("A newly created store must have one or both of --password and --keyfile specified");
Environment.Exit(1);
}
if (passwordMode && File.Exists(keyfile) && new FileInfo(keyfile).Length > 0)
{
Confirm($"Overwrite the existing contents of the key file at {keyfile} " +
"with a key derived from the provided password? [yes/no]: ");
}
sman = SecretsManager.CreateStore();
}
else
{
if (command == "get")
{
if (decryptAll && !string.IsNullOrWhiteSpace(secretName))
{
Help(Console.Error, "Either --all or KEY must be specified as an argument to decrypt (not both)!", command, parseOptions);
}
}
sman = SecretsManager.LoadStore(path);
}
using (sman)
{
if (passwordMode)
{
sman.LoadKeyFromPassword(password!);
try
{
sman.ValidateSentinel();
}
catch (TamperedCipherTextException)
{
throw new ExitCodeException(1, "Incorrect password!");
}
}
string? keyCreated = null;
if (command == "create")
{
if (File.Exists(path) && new FileInfo(path).Length > 0)
{
Confirm($"Overwrite existing store at {path}? [yes/no]: ");
}
if (!passwordMode)
{
ExitIfNullOrEmpty(keyfile, "A keyfile path is required if no password is provided");
if (File.Exists(keyfile) && new FileInfo(keyfile).Length > 0)
{
sman.LoadKeyFromFile(keyfile);
}
else
{
sman.GenerateKey();
sman.ExportKey(keyfile);
keyCreated = keyfile;
}
}
else if (!string.IsNullOrEmpty(keyfile))
{
sman.ExportKey(keyfile);
keyCreated = keyfile;
}
}
else if (!passwordMode && keyfile != null)
{
sman.LoadKeyFromFile(keyfile);
}
if (!passwordMode && keyfile is not null)
{
try
{
sman.ValidateSentinel();
}
catch (TamperedCipherTextException)
{
throw new ExitCodeException(1, "Incorrect key for store!");
}
}
// We store --export-key to its own variable so that it doesn't override our defaulting to password
// mode if no key file was specified. After we've decided on whether or not to use a password above,
// we can now coalesce the two values.
if (keyExport is not null && (keyfile is null || keyExport != keyfile))
{
sman.ExportKey(keyExport);
keyCreated = keyExport;
keyfile = keyExport;
}
if (keyCreated is not null)
{
var vcsType = GetVcsType(keyfile!);
if (vcsType != VcsType.None)
{
await AddIgnoreRuleAsync(vcsType, keyCreated, Path.GetDirectoryName(keyCreated)!);
}
}
var client = new Client(sman);
switch (command)
{
case "create":
client.Create();
break;
case "delete":
if (string.IsNullOrEmpty(secretName))
{
Help(Console.Error, "The name of the secret to delete is required", command, parseOptions);
}
client.Delete(secretName);
break;
case "set":
if (string.IsNullOrEmpty(secretName))
{
Help(Console.Error, "The name of the secret to set or update is required", command, parseOptions);
}
if (string.IsNullOrEmpty(secretValue))
{
Help(Console.Error, "The value of the secret to set or update is required", command, parseOptions);
}
client.Update(secretName, secretValue);
break;
case "get":
if (!decryptAll)
{
if (format != DecryptFormat.None)
{
Help(Console.Error, "--format can only be used in conjunction with --all!",
command, parseOptions);
}
if (string.IsNullOrEmpty(secretName))
{
Help(Console.Error, "The name of the secret to retrieve is required", command, parseOptions);
}
client.Decrypt(secretName);
}
else
{
client.DecryptAll(format);
}
break;
default:
throw new NotImplementedException($"Case {command} not handled!");
}
sman.SaveStore(path);
}
}
catch (OptionException ex)
{
Console.WriteLine(ex.Message);
exitCode = 1;
}
catch (ExitCodeException ex)
{
if (!string.IsNullOrWhiteSpace(ex.Message))
{
Console.WriteLine(ex.Message);
}
exitCode = ex.ExitCode;
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
exitCode = 1;
}
Environment.Exit(exitCode);
}
[DoesNotReturn]
static void Help(TextWriter output, string message, string? command = null, OptionSet? options = null)
{
output.WriteLine($"Error: {message}");
if (command != null && options != null)
{
output.WriteLine();
PrintOptions(output, command, options);
}
throw new ExitCodeException(1);
}
static void PrintOptions(TextWriter output, string? cmd, OptionSet options)
{
if (cmd != null)
{
output.WriteLine($"{cmd} options:");
}
foreach (var option in options)
{
var names = option.GetNames();
if (names.Length > 1)
{
output.WriteLine($"\t-{names[0]} --{names[1]}\t{option.Description}");
}
else
{
output.WriteLine($"\t--{names[0]}\t{option.Description}");
}
}
}
static void Confirm(string message)
{
while (true)
{
Console.Error.Write(message);
switch (Console.ReadLine()?.ToLower())
{
case "yes": return;
case "no": throw new ExitCodeException(1);
default: continue;
}
}
}
public static string GetPassword()
{
var password = new StringBuilder();
while (true)
{
var key = Console.ReadKey(true);
if (key.Key == ConsoleKey.Enter)
{
break;
}
else if (key.Key == ConsoleKey.Backspace)
{
if (password.Length > 0)
{
password.Remove(password.Length - 1, 1);
Console.Write("\b \b");
}
}
else
{
password.Append(key.KeyChar);
Console.Write("*");
}
}
Console.WriteLine();
return password.ToString();
}
public static void ExitIfNullOrEmpty([NotNull] this string? s, string message)
{
if (string.IsNullOrEmpty(s))
{
Help(Console.Error, message);
}
}
}
}