-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCliApp.cs
More file actions
454 lines (404 loc) · 17.8 KB
/
CliApp.cs
File metadata and controls
454 lines (404 loc) · 17.8 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
using System.Text.Json;
using PostQuantum.FileFormat.Armor;
using PostQuantum.FileFormat.File;
using PostQuantum.FileFormat.Fingerprint;
using PostQuantum.FileFormat.Keys;
namespace PostQuantum.FileFormat.Cli;
public static class CliApp
{
public static async Task<int> RunAsync(string[] args, TextWriter stdout, TextWriter stderr)
{
if (args.Length == 0 || IsHelp(args[0]))
{
PrintHelp(stdout);
return ExitCodes.Success;
}
try
{
return args[0] switch
{
"keygen" => await RunKeygenAsync(args[1..], stdout, stderr).ConfigureAwait(false),
"encrypt" => await RunEncryptAsync(args[1..], stdout, stderr).ConfigureAwait(false),
"decrypt" => await RunDecryptAsync(args[1..], stdout, stderr).ConfigureAwait(false),
"inspect" => await RunInspectAsync(args[1..], stdout, stderr).ConfigureAwait(false),
"fingerprint" => await RunFingerprintAsync(args[1..], stdout, stderr).ConfigureAwait(false),
_ => FailUsage(stderr, $"Unknown command '{args[0]}'.")
};
}
catch (IOException ex)
{
await stderr.WriteLineAsync($"I/O error: {ex.Message}").ConfigureAwait(false);
return ExitCodes.IoError;
}
catch (UnauthorizedAccessException ex)
{
await stderr.WriteLineAsync($"Permission error: {ex.Message}").ConfigureAwait(false);
return ExitCodes.IoError;
}
catch (JsonException ex)
{
await stderr.WriteLineAsync($"Invalid key file JSON: {ex.Message}").ConfigureAwait(false);
return ExitCodes.KeyError;
}
catch (FormatException ex)
{
await stderr.WriteLineAsync($"Invalid key format: {ex.Message}").ConfigureAwait(false);
return ExitCodes.KeyError;
}
catch (KeyFormatException ex)
{
await stderr.WriteLineAsync($"Invalid key material: {ex.Message}").ConfigureAwait(false);
return ExitCodes.KeyError;
}
catch (Exception ex)
{
await stderr.WriteLineAsync($"Internal error: {ex.Message}").ConfigureAwait(false);
return ExitCodes.InternalError;
}
}
private static async Task<int> RunKeygenAsync(string[] args, TextWriter stdout, TextWriter stderr)
{
if (!TryParseOptions(args, out var options, out var error))
{
return FailUsage(stderr, error);
}
if (!TryGetSingle(options, "type", out var keyType) ||
!TryGetSingle(options, "public-out", out var publicOut) ||
!TryGetSingle(options, "private-out", out var privateOut))
{
return FailUsage(stderr, "keygen requires --type, --public-out, and --private-out.");
}
Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(publicOut)) ?? ".");
Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(privateOut)) ?? ".");
if (string.Equals(keyType, "encrypt", StringComparison.OrdinalIgnoreCase))
{
using var identity = PqfIdentity.Generate();
await KeyFileStore.WriteEncryptionIdentityAsync(identity, publicOut, privateOut).ConfigureAwait(false);
await stdout.WriteLineAsync($"Generated encryption identity: {privateOut}").ConfigureAwait(false);
await stdout.WriteLineAsync($"Generated encryption public key: {publicOut}").ConfigureAwait(false);
return ExitCodes.Success;
}
if (string.Equals(keyType, "sign", StringComparison.OrdinalIgnoreCase))
{
using var identity = PqfSigningIdentity.Generate();
await KeyFileStore.WriteSigningIdentityAsync(identity, publicOut, privateOut).ConfigureAwait(false);
await stdout.WriteLineAsync($"Generated signing identity: {privateOut}").ConfigureAwait(false);
await stdout.WriteLineAsync($"Generated signing public key: {publicOut}").ConfigureAwait(false);
return ExitCodes.Success;
}
return FailUsage(stderr, "--type must be either 'encrypt' or 'sign'.");
}
private static async Task<int> RunEncryptAsync(string[] args, TextWriter stdout, TextWriter stderr)
{
if (!TryParseOptions(args, out var options, out var error))
{
return FailUsage(stderr, error);
}
if (!TryGetSingle(options, "in", out var inputPath) || !TryGetSingle(options, "out", out var outputPath))
{
return FailUsage(stderr, "encrypt requires --in and --out.");
}
if (!options.TryGetValue("recipient", out var recipientPaths) || recipientPaths.Count == 0)
{
return FailUsage(stderr, "encrypt requires at least one --recipient file.");
}
var recipients = new List<PqfPublicKey>(recipientPaths.Count);
foreach (var recipientPath in recipientPaths)
{
recipients.Add(await KeyFileStore.ReadRecipientPublicKeyAsync(recipientPath).ConfigureAwait(false));
}
PqfSigningIdentity? signer = null;
if (TryGetSingle(options, "signing-key", out var signingKeyPath))
{
signer = await KeyFileStore.ReadSigningIdentityAsync(signingKeyPath).ConfigureAwait(false);
}
var chunkSize = 65536;
if (TryGetSingle(options, "chunk-size", out var chunkSizeRaw) && !int.TryParse(chunkSizeRaw, out chunkSize))
{
signer?.Dispose();
return FailUsage(stderr, "--chunk-size must be an integer.");
}
await using var input = System.IO.File.OpenRead(inputPath);
await using var output = System.IO.File.Create(outputPath);
try
{
await PqfFile.EncryptAsync(input, output, recipients, signer, chunkSize).ConfigureAwait(false);
}
finally
{
signer?.Dispose();
}
await stdout.WriteLineAsync($"Encrypted {inputPath} -> {outputPath}").ConfigureAwait(false);
return ExitCodes.Success;
}
private static async Task<int> RunDecryptAsync(string[] args, TextWriter stdout, TextWriter stderr)
{
if (!TryParseOptions(args, out var options, out var error))
{
return FailUsage(stderr, error);
}
if (!TryGetSingle(options, "in", out var inputPath) ||
!TryGetSingle(options, "out", out var outputPath) ||
!TryGetSingle(options, "identity", out var identityPath))
{
return FailUsage(stderr, "decrypt requires --in, --out, and --identity.");
}
var mode = "authenticated";
if (TryGetSingle(options, "mode", out var explicitMode))
{
mode = explicitMode;
}
using var identity = await KeyFileStore.ReadEncryptionIdentityAsync(identityPath).ConfigureAwait(false);
await using var input = System.IO.File.OpenRead(inputPath);
// Atomic-write pattern: decrypt to a sibling .partial file, rename it to
// the final output path only on success, delete it on any failure. This
// prevents a verification refusal from leaving partially-decrypted
// plaintext at the user-visible --out path. Without this, a downstream
// script that gates on file existence (rather than CLI exit code) could
// consume rejected bytes.
var partialPath = outputPath + ".partial";
if (System.IO.File.Exists(partialPath))
{
System.IO.File.Delete(partialPath);
}
var partialOptions = new FileStreamOptions
{
Mode = FileMode.CreateNew,
Access = FileAccess.Write,
Share = FileShare.None,
};
if (!OperatingSystem.IsWindows())
{
// Decrypted plaintext should not be world-readable on a multi-user
// host even briefly during the .partial -> final rename window.
partialOptions.UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite;
}
var success = false;
long? streamingEmittedBytes = null;
try
{
await using (var output = new FileStream(partialPath, partialOptions))
{
if (string.Equals(mode, "authenticated", StringComparison.OrdinalIgnoreCase))
{
try
{
await PqfDecryptor.DecryptAsync(input, output, identity).ConfigureAwait(false);
success = true;
}
catch (PqfFileException ex)
{
await stderr.WriteLineAsync($"Decryption refused ({ex.Reason}): {ex.Message}").ConfigureAwait(false);
return ExitCodes.Refused;
}
}
else if (string.Equals(mode, "streaming", StringComparison.OrdinalIgnoreCase))
{
var result = await PqfDecryptor.DecryptStreamingAsync(input, output, identity).ConfigureAwait(false);
if (!result.Success)
{
var postHoc = result.PostHocAuthenticationFailed ? " post-hoc-auth=true" : string.Empty;
await stderr.WriteLineAsync($"Decryption refused ({result.FailureReason}) emitted={result.PlaintextBytesEmitted}{postHoc}").ConfigureAwait(false);
await stderr.WriteLineAsync($"Discarded {result.PlaintextBytesEmitted} bytes; output not written to {outputPath}.").ConfigureAwait(false);
return ExitCodes.Refused;
}
streamingEmittedBytes = result.PlaintextBytesEmitted;
success = true;
}
else
{
return FailUsage(stderr, "--mode must be either 'authenticated' or 'streaming'.");
}
}
// FileStream is now disposed; promote the .partial file to the final
// output path. Both modes share this path so the success contract is
// identical: nothing appears at outputPath until verification passed.
if (System.IO.File.Exists(outputPath))
{
System.IO.File.Delete(outputPath);
}
System.IO.File.Move(partialPath, outputPath);
if (streamingEmittedBytes is { } emitted)
{
await stdout.WriteLineAsync($"Decrypted {inputPath} -> {outputPath} ({emitted} bytes)").ConfigureAwait(false);
}
else
{
await stdout.WriteLineAsync($"Decrypted {inputPath} -> {outputPath}").ConfigureAwait(false);
}
return ExitCodes.Success;
}
finally
{
if (!success)
{
try
{
if (System.IO.File.Exists(partialPath))
{
System.IO.File.Delete(partialPath);
}
}
catch
{
// Best-effort cleanup. The non-zero exit code is the
// authoritative signal; a leftover .partial file is annoying
// but does not violate fail-closed (it has the .partial
// suffix and is not at the user-visible --out path).
}
}
}
}
private static async Task<int> RunInspectAsync(string[] args, TextWriter stdout, TextWriter stderr)
{
if (!TryParseOptions(args, out var options, out var error))
{
return FailUsage(stderr, error);
}
if (!TryGetSingle(options, "in", out var inputPath))
{
return FailUsage(stderr, "inspect requires --in.");
}
var emitJson = options.ContainsKey("json");
var bytes = await System.IO.File.ReadAllBytesAsync(inputPath).ConfigureAwait(false);
try
{
var reader = PqfFileReader.OpenForValidation(bytes);
var payload = new
{
chunkSize = reader.Header.ChunkSize,
createdUtc = reader.Header.CreatedUtc,
fileId = Convert.ToHexString(reader.Header.FileId).ToLowerInvariant(),
recipients = reader.Header.Recipients.Count,
signed = reader.Header.Signer is not null,
chunkCount = reader.TotalChunkCount,
plaintextBytes = reader.ReportedPlaintextBytes,
};
if (emitJson)
{
await stdout.WriteLineAsync(JsonSerializer.Serialize(payload, new JsonSerializerOptions
{
WriteIndented = true,
})).ConfigureAwait(false);
}
else
{
await stdout.WriteLineAsync($"chunk_size: {payload.chunkSize}").ConfigureAwait(false);
await stdout.WriteLineAsync($"created_utc: {payload.createdUtc:O}").ConfigureAwait(false);
await stdout.WriteLineAsync($"file_id: {payload.fileId}").ConfigureAwait(false);
await stdout.WriteLineAsync($"recipients: {payload.recipients}").ConfigureAwait(false);
await stdout.WriteLineAsync($"signed: {payload.signed}").ConfigureAwait(false);
await stdout.WriteLineAsync($"chunk_count: {payload.chunkCount}").ConfigureAwait(false);
await stdout.WriteLineAsync($"plaintext_bytes: {payload.plaintextBytes}").ConfigureAwait(false);
}
return ExitCodes.Success;
}
catch (PqfFileException ex)
{
await stderr.WriteLineAsync($"Inspect refused ({ex.Reason}): {ex.Message}").ConfigureAwait(false);
return ExitCodes.Refused;
}
}
private static async Task<int> RunFingerprintAsync(string[] args, TextWriter stdout, TextWriter stderr)
{
if (!TryParseOptions(args, out var options, out var error))
{
return FailUsage(stderr, error);
}
if (!TryGetSingle(options, "public-key", out var keyPath))
{
return FailUsage(stderr, "fingerprint requires --public-key.");
}
var pem = await System.IO.File.ReadAllTextAsync(keyPath).ConfigureAwait(false);
try
{
var key = PemArmor.DearmorPublicKey(pem);
var fp = PqfFingerprint.Compute(key);
await stdout.WriteLineAsync($"{PqfFingerprint.ToPrefixedHex(fp)} (enc, short={PqfFingerprint.ToShortHex(fp)})").ConfigureAwait(false);
return ExitCodes.Success;
}
catch (FormatException)
{
var key = PemArmor.DearmorSigningPublicKey(pem);
var fp = PqfFingerprint.Compute(key);
await stdout.WriteLineAsync($"{PqfFingerprint.ToPrefixedHex(fp)} (sig, short={PqfFingerprint.ToShortHex(fp)})").ConfigureAwait(false);
return ExitCodes.Success;
}
}
private static bool IsHelp(string arg)
{
return string.Equals(arg, "-h", StringComparison.OrdinalIgnoreCase) ||
string.Equals(arg, "--help", StringComparison.OrdinalIgnoreCase) ||
string.Equals(arg, "help", StringComparison.OrdinalIgnoreCase);
}
private static int FailUsage(TextWriter stderr, string message)
{
stderr.WriteLine($"Usage error: {message}");
return ExitCodes.Usage;
}
private static bool TryParseOptions(
IReadOnlyList<string> args,
out Dictionary<string, List<string>> options,
out string error)
{
options = new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase);
error = string.Empty;
for (var i = 0; i < args.Count; i++)
{
var token = args[i];
if (!token.StartsWith("--", StringComparison.Ordinal))
{
error = $"Unexpected argument '{token}'. Use --name value options.";
return false;
}
var name = token[2..];
if (string.IsNullOrWhiteSpace(name))
{
error = "Encountered empty option name.";
return false;
}
if (!options.TryGetValue(name, out var values))
{
values = new List<string>();
options[name] = values;
}
if (i + 1 >= args.Count || args[i + 1].StartsWith("--", StringComparison.Ordinal))
{
values.Add("true");
continue;
}
values.Add(args[++i]);
}
return true;
}
private static bool TryGetSingle(Dictionary<string, List<string>> options, string name, out string value)
{
value = string.Empty;
if (!options.TryGetValue(name, out var values) || values.Count == 0)
{
return false;
}
value = values[^1];
return true;
}
private static void PrintHelp(TextWriter stdout)
{
stdout.WriteLine("pqf - PostQuantum.FileFormat CLI");
stdout.WriteLine();
stdout.WriteLine("Commands:");
stdout.WriteLine(" keygen --type encrypt|sign --public-out <path> --private-out <path>");
stdout.WriteLine(" encrypt --in <path> --out <path> --recipient <pub.pem> [--recipient <pub.pem>] [--signing-key <signing.key.json>] [--chunk-size <n>]");
stdout.WriteLine(" decrypt --in <path> --out <path> --identity <identity.key.json> [--mode authenticated|streaming]");
stdout.WriteLine(" inspect --in <path> [--json]");
stdout.WriteLine(" fingerprint --public-key <pub.pem>");
}
public static class ExitCodes
{
public const int Success = 0;
public const int Usage = 2;
public const int IoError = 3;
public const int KeyError = 4;
public const int Refused = 5;
public const int InternalError = 10;
}
}