- Notifications
You must be signed in to change notification settings - Fork 73
/
Copy pathProgram.cs
815 lines (707 loc) · 36.9 KB
/
Program.cs
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
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
usingSystem;
usingSystem.Collections.Generic;
usingSystem.IO;
usingSystem.Linq;
usingSystem.Net.Http;
usingSystem.Security.Cryptography;
usingSystem.Security.Cryptography.X509Certificates;
usingSystem.Text;
usingSystem.Threading;
usingSystem.Threading.Tasks;
usingACMESharp.Authorizations;
usingACMESharp.Crypto.JOSE;
usingACMESharp.Protocol;
usingACMESharp.Protocol.Resources;
usingExamples.Common;
usingExamples.Common.PKI;
usingMcMaster.Extensions.CommandLineUtils;
usingNewtonsoft.Json;
usingPKISharp.SimplePKI;
namespaceACMECLI
{
[Command]
classProgram
{
[Option(ShortName="",Description="Directory to store stateful information; defaults to current")]
publicstringState{get;}=".";
[Option(ShortName="",Description="Name of a predefined ACME CA base endpoint (specify invalid value to see list)")]
[AllowedValues(
Constants.LetsEncryptName,
Constants.LetsEncryptStagingName,
IgnoreCase=true
)]
publicstringCaName{get;}=Constants.LetsEncryptName;
[Option(ShortName="",Description="Full URL of an ACME CA endpoint; this option overrides "+nameof(CaName))]
publicstringCaUrl{get;}
[Option(ShortName="",Description="Flag indicates to refresh the current cached ACME Directory of service endpoints for the target CA")]
publicboolRefreshDir{get;}
[Option(CommandOptionType.MultipleValue,
ShortName="",Description="One or more emails to be registered as account contact info (can be repeated)")]
publicIEnumerable<string>Email{get;}
[Option(ShortName="",Description="Flag indicates that you agree to CA's terms of service")]
publicboolAcceptTos{get;}
[Option(CommandOptionType.MultipleValue,
ShortName="",Description="One or more DNS names to include in the cert; the first is primary subject name, subsequent are subject alternative names (can be repeated)")]
publicIEnumerable<string>Dns{get;}
[Option(CommandOptionType.MultipleValue,
ShortName="",Description="One or more DNS name servers to be used to resolve host entries, such as during testing (can be repeated)")]
publicIEnumerable<string>NameServer{get;}
[Option(ShortName="",Description="Flag indicates to refresh the state of pending ACME Order")]
publicboolRefreshOrder{get;}
[Option(ShortName="",Description="Indicates that only one specific Challenge type should be handled")]
[AllowedValues(
Constants.Dns01ChallengeType,
Constants.Http01ChallengeType,
IgnoreCase=true
)]
publicstringChallengeType{get;}
[Option(ShortName="",Description="Flag indicates to refresh the state of the Challenges of the pending ACME Order")]
publicboolRefreshChallenges{get;}
[Option(ShortName="",Description="Flag indicates to check if the Challenges have been handled correctly")]
publicboolTestChallenges{get;}
[Option(ShortName="",Description="Flag indicates to wait until Challenge tests are successfully validated, optionally override the default timeout of 300 (seconds)")]
public(boolenabled,int?timeout)WaitForTest{get;}
[Option(ShortName="",Description="Flag indicates to submit Answers to pending Challenges")]
publicboolAnswerChallenges{get;}
[Option(ShortName="",Description="Flag indicates to wait until Authorizations become Valid, optionally override the default timeout of 300 (seconds)")]
public(boolenabled,int?timeout)WaitForAuthz{get;}
[Option(ShortName="",Description="Flag indicates to finalize the pending ACME Order")]
publicboolFinalize{get;}
[Option(ShortName="",Description="Indicates the encryption algorithm of certificate keys, defaults to RSA")]
[AllowedValues(
Constants.RsaKeyType,
Constants.EcKeyType,
IgnoreCase=true
)]
publicstringKeyAlgor{get;}=Constants.RsaKeyType;
[Option(ShortName="",Description="Indicates the encryption algorithm key size, defaults to 2048 (RSA) or 256 (EC)")]
publicint?KeySize{get;}
[Option(ShortName="",Description="Flag indicates to regenerate a certificate key pair and CSR")]
publicboolRegenerateCsr{get;}
[Option(ShortName="",Description="Flag indicates to refresh the local cache of an issued certificate")]
publicboolRefreshCert{get;}
[Option(ShortName="",Description="Flag indicates to wait until Certificate is available, optionally override the default timeout of 300 (seconds)")]
public(boolenabled,int?timeout)WaitForCert{get;}
// Not enough support in .NET Core/Standard out of the box for this yet
// [Option(ShortName = "", Description = "Save the certificate private key (PEM) to the named file path (currently only supports RSA)")]
// public string ExportKey { get; }
[Option(ShortName="",Description="Save the certificate chain (PEM) to the named file path")]
publicstringExportCert{get;}
[Option(ShortName="",Description="Save the certificate chain as PFX (PKCS12) to the named file path")]
publicstringExportPfx{get;}
[Option(ShortName="",Description="Includes the private key to the PFX (PKCS12) and secures with specified password (use ' ' for no password)")]
publicstringExportPfxPassword{get;}
privatestring_statePath;
privateHttpClient_http;
privateAcmeProtocolClient_acme;
privateDateTime?_testWaitUntil;
staticasyncTaskMain(string[]args)=>
awaitCommandLineApplication.ExecuteAsync<Program>(args);
publicasyncTaskOnExecute()
{
_statePath=Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(),State));
Console.WriteLine("################################################################################");
Console.WriteLine("## ACCOUNT");
Console.WriteLine("################################################################################");
Console.WriteLine();
if(!Directory.Exists(_statePath))
{
Console.WriteLine($"Creating State Persistence Path [{_statePath}]");
Directory.CreateDirectory(_statePath);
Console.WriteLine();
}
varurl=CaUrl;
if(string.IsNullOrEmpty(url))
Constants.NameUrlMap.TryGetValue(CaName,outurl);
if(string.IsNullOrEmpty(url))
thrownewException("Unresolved ACME CA URL; either name or URL argument must be specified");
ServiceDirectoryacmeDir=default;
if(LoadStateInto(refacmeDir,failThrow:false,
Constants.AcmeDirectoryFile))
{
Console.WriteLine("Loaded existing Service Directory");
Console.WriteLine();
}
if(NameServer!=null)
{
DnsUtil.DnsServers=NameServer.ToArray();
}
AccountDetailsaccount=default;
if(LoadStateInto(refaccount,failThrow:false,
Constants.AcmeAccountDetailsFile))
{
Console.WriteLine($"Loaded Account Details for KID:");
Console.WriteLine($" Account KID....: {account.Kid}");
Console.WriteLine();
}
IJwsToolaccountSigner=default;
ExamplesAccountKeyaccountKey=default;
stringaccountKeyHash=default;
if(LoadStateInto(refaccountKey,failThrow:false,
Constants.AcmeAccountKeyFile))
{
accountSigner=accountKey.GenerateTool();
accountKeyHash=ComputeHash(accountSigner.Export());
Console.WriteLine($"Loaded EXISTING Account Key:");
Console.WriteLine($" Key Type...........: {accountKey.KeyType}");
Console.WriteLine($" Key Export Hash....: {accountKeyHash}");
Console.WriteLine();
}
_http=newHttpClient{BaseAddress=newUri(url),};
_acme=newAcmeProtocolClient(_http,acmeDir,account,accountSigner,usePostAsGet:true);
if(acmeDir==null||RefreshDir)
{
Console.WriteLine("Refreshing Service Directory");
acmeDir=await_acme.GetDirectoryAsync();
_acme.Directory=acmeDir;
SaveStateFrom(acmeDir,Constants.AcmeDirectoryFile);
Console.WriteLine();
}
await_acme.GetNonceAsync();
if(account==null||accountSigner==null)
{
Console.WriteLine("Generating/Registering NEW Account Key");
if(!AcceptTos)
{
Console.WriteLine("You must agree (using CLI flag) to terms of service to create an account:");
Console.WriteLine(" "+_acme.Directory.Meta.TermsOfService);
return;
}
if((Email?.Count()??0)==0)
thrownewException("At least one email must be specified as a contact for new account");
account=await_acme.CreateAccountAsync(Email.Select(x =>"mailto:"+x),AcceptTos);
accountSigner=_acme.Signer;
accountKey=newExamplesAccountKey
{
KeyType=accountSigner.JwsAlg,
KeyExport=accountSigner.Export(),
};
SaveStateFrom(account,Constants.AcmeAccountDetailsFile);
SaveStateFrom(accountKey,Constants.AcmeAccountKeyFile);
_acme.Account=account;
}
// Dump out Account Details
varcontacts=account.Payload.Contact;
varcontactsJoined=contacts==null?string.Empty:string.Join(",",contacts);
Console.WriteLine($"Account Details:");
Console.WriteLine($" Id..........: {account?.Payload?.Id}");
Console.WriteLine($" Kid.........: {account?.Kid}");
Console.WriteLine($" Status......: {account?.Payload?.Status}");
Console.WriteLine($" Contacts....: {contactsJoined}");
// Dump out Account Key
accountKeyHash=ComputeHash(accountSigner.Export());
Console.WriteLine($"Account Key:");
Console.WriteLine($" JWS Algorithm......: {_acme.Signer.JwsAlg}");
Console.WriteLine($" Impl Class Type....: {_acme.Signer.GetType().Name}");
Console.WriteLine($" Key Export Hash....: {accountKeyHash}");
Console.WriteLine();
if(Dns?.Count()==0)
// No DNS names means we can only handle the
// Account and no request to create an Order
return;
Console.WriteLine("################################################################################");
Console.WriteLine("## ORDER");
Console.WriteLine("################################################################################");
Console.WriteLine();
vardnsNames=Dns.Distinct();
varcertName=string.Join(",",dnsNames.Distinct()).Replace("%","").ToLower();
varcertNameHash=ComputeHash(certName);
varorderId=certNameHash;
OrderDetailsorder=default;
LoadStateInto(reforder,failThrow:false,
Constants.AcmeOrderDetailsFileFmt,orderId);
if(order==null)
{
Console.WriteLine("Creating NEW Order");
order=await_acme.CreateOrderAsync(dnsNames);
SaveStateFrom(order,Constants.AcmeOrderDetailsFileFmt,orderId);
}
if(RefreshOrder)
{
Console.WriteLine("Refreshing EXISTING Order");
order=await_acme.GetOrderDetailsAsync(order.OrderUrl,existing:order);
SaveStateFrom(order,Constants.AcmeOrderDetailsFileFmt,orderId);
}
// Dump out Order Details
Console.WriteLine($"Order Details:");
Console.WriteLine($" Order URL......: {order.OrderUrl}");
Console.WriteLine($" Expires........: {order.Payload.Expires}");
Console.WriteLine($" Status.........: {order.Payload.Status}");
Console.WriteLine($@" Identifiers....: {string.Join(",",
order.Payload.Identifiers.Select(x =>$"{x.Type}:{x.Value}"))}");
Console.WriteLine();
if(WaitForTest.enabled)
_testWaitUntil=DateTime.Now.AddSeconds(
WaitForTest.timeout.GetValueOrDefault(300));
if(order.Payload.Status==Constants.InvalidStatus)
thrownewException("Order is already marked as INVALID");
if(order.Payload.Status==Constants.PendingStatus)
{
varauthzStatusCounts=newDictionary<string,int>
{
[Constants.ValidStatus]=0,
[Constants.InvalidStatus]=0,
[Constants.ValidStatus]=0,
["unknown"]=0,
};
voidAddStatusCount(stringstatus,intadd)
{
if(!authzStatusCounts.ContainsKey(status))
status="unknown";
authzStatusCounts[status]+=add;
}
Console.WriteLine("== Authorizations ==============================================================");
Console.WriteLine();
foreach(varauthzUrlinorder.Payload.Authorizations)
{
varauthzId=ComputeHash(authzUrl);
Authorizationauthz=default;
LoadStateInto(refauthz,failThrow:false,
Constants.AcmeOrderAuthzDetailsFileFmt,orderId,authzId);
if(authz==null||RefreshOrder)
{
Console.WriteLine("Getting Authorization Details...");
authz=await_acme.GetAuthorizationDetailsAsync(authzUrl);
SaveStateFrom(authz,Constants.AcmeOrderAuthzDetailsFileFmt,orderId,authzId);
}
Console.WriteLine($"Identifier: [{authz.Identifier.Value}]");
Console.WriteLine($" Status.............: {authz.Status}");
Console.WriteLine($" Expires............: {authz.Expires}");
Console.WriteLine($" Is Wildcard........: {authz.Wildcard}");
Console.WriteLine($" Challenge Count....: {authz.Challenges.Length}");
Console.WriteLine();
AddStatusCount(authz.Status,1);
Console.WriteLine("-- Challenges ------------------------------------------------------------------");
intchlngCount=0;
foreach(varchlnginauthz.Challenges)
{
if(ChallengeType!=null
&&!ChallengeType.Equals(chlng.Type,StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine($" Skipping [{chlng.Type}]");
continue;
}
AuthorizationauthzUpdated=null;
ChallengechlngUpdated=null;
if(RefreshChallenges)
{
Console.WriteLine(" Refreshing Challenge...");
chlngUpdated=await_acme.GetChallengeDetailsAsync(chlng.Url);
}
varcd=AuthorizationDecoder.DecodeChallengeValidation(authz,chlng.Type,accountSigner);
switch(chlng.Type)
{
caseDns01ChallengeValidationDetails.Dns01ChallengeType:
awaitProcessDns01(accountSigner,authz,chlngUpdated??chlng,cd);
break;
caseHttp01ChallengeValidationDetails.Http01ChallengeType:
awaitProcessHttp01(accountSigner,authz,chlngUpdated??chlng,cd);
break;
default:
Console.WriteLine($" Challenge of Type: {cd.ChallengeType}");
Console.WriteLine($" This Challenge type is unknown, but here are the details:");
Console.WriteLine(JsonConvert.SerializeObject(cd));
break;
}
if(AnswerChallenges)
{
Console.WriteLine(" Answering Challenge...");
chlngUpdated=await_acme.AnswerChallengeAsync(chlng.Url);
authzUpdated=await_acme.GetAuthorizationDetailsAsync(authzUrl);
}
if(chlngUpdated!=null)
{
SaveStateFrom(chlngUpdated,Constants.AcmeOrderAuthzChlngDetailsFileFmt,
orderId,authzId,chlngUpdated.Type);
}
if(authzUpdated!=null)
{
if(authzUpdated.Status!=authz.Status)
{
AddStatusCount(authz.Status,-1);
AddStatusCount(authzUpdated.Status,1);
}
authz=authzUpdated;
SaveStateFrom(authz,Constants.AcmeOrderAuthzDetailsFileFmt,orderId,authzId);
authzUpdated=null;
}
++chlngCount;
}
if(chlngCount==0)
thrownewException($"No matching Challenges found for Type [{ChallengeType}]");
}
if(Finalize)
{
if(authzStatusCounts[Constants.ValidStatus]<
order.Payload.Authorizations.Length)
{
intvalidStatusCount=0;
if(WaitForAuthz.enabled)
{
Console.WriteLine("Waiting for Authorizations to be Validated...");
varwaitUntil=DateTime.Now.AddSeconds(
WaitForAuthz.timeout.GetValueOrDefault(300));
foreach(varauthzUrlinorder.Payload.Authorizations)
{
varauthz=await_acme.GetAuthorizationDetailsAsync(authzUrl);
Console.WriteLine($" Identifier: {authz.Identifier.Type}:{authz.Identifier.Value}:");
while(authz.Status!=Constants.ValidStatus
&&DateTime.Now<waitUntil)
{
Thread.Sleep(1*1000);
authz=await_acme.GetAuthorizationDetailsAsync(authzUrl);
}
Console.WriteLine($" Status: {authz.Status}");
if(authz.Status==Constants.ValidStatus)
++validStatusCount;
}
Console.WriteLine();
}
if(validStatusCount<order.Payload.Authorizations.Length)
thrownewException("Cannot finalize Order until all Authorizations are valid");
}
PkiKeyPairkeyPair=null;
PkiCertificateSigningRequestcsr=null;
stringcertKeys=null;
byte[]certCsr=null;
if(LoadStateInto(refcertKeys,failThrow:false,
Constants.AcmeOrderCertKeyFmt,orderId))
Console.WriteLine("Loaded existing Certificate key pair");
if(LoadStateInto(refcertCsr,failThrow:false,
Constants.AcmeOrderCertCsrFmt,orderId))
Console.WriteLine("Loaded existing CSR");
if(certKeys==null||certCsr==null||RegenerateCsr)
{
Console.WriteLine("Generating Certificate key pair and CSR...");
switch(KeyAlgor)
{
caseConstants.RsaKeyType:
keyPair=PkiKeyPair.GenerateRsaKeyPair(KeySize??Constants.DefaultAlgorKeySizeMap[KeyAlgor]);
break;
caseConstants.EcKeyType:
keyPair=PkiKeyPair.GenerateEcdsaKeyPair(KeySize??Constants.DefaultAlgorKeySizeMap[KeyAlgor]);
break;
default:
thrownewException($"Unknown key algorithm type [{KeyAlgor}]");
}
csr=GenerateCsr(Dns,keyPair);
certKeys=Save(keyPair);
certCsr=csr.ExportSigningRequest(PkiEncodingFormat.Der);
SaveStateFrom(certKeys,Constants.AcmeOrderCertKeyFmt,orderId);
SaveStateFrom(certCsr,Constants.AcmeOrderCertCsrFmt,orderId);
}
Console.WriteLine("Finalizing Order...");
order=await_acme.FinalizeOrderAsync(order.Payload.Finalize,certCsr);
SaveStateFrom(order,Constants.AcmeOrderDetailsFileFmt,orderId);
}
else
{
// Since we haven't been asked to Finalize and we were most recently
// still in PENDING state, we should end at this point to give it time
return;
}
}
if(order.Payload.Status==Constants.ValidStatus)
{
Console.WriteLine("Order is VALID");
if(string.IsNullOrEmpty(order.Payload.Certificate))
{
if(WaitForCert.enabled)
{
Console.WriteLine("Waiting for Certificate to become available");
varwaitUntil=DateTime.Now.AddSeconds(
WaitForCert.timeout.GetValueOrDefault(300));
while(DateTime.Now<waitUntil)
{
Console.WriteLine(" Waiting...");
Thread.Sleep(10*1000);
order=await_acme.GetOrderDetailsAsync(order.OrderUrl,existing:order);
if(RefreshOrder)
{
// If refresh was indicated, persist the latest state
SaveStateFrom(order,Constants.AcmeOrderDetailsFileFmt,orderId);
}
if(!string.IsNullOrEmpty(order.Payload.Certificate))
break;
}
}
else
{
thrownewException("Certificate URL on Order is missing, did you refresh or wait long enough?");
}
}
if(RefreshCert||!StateExists(Constants.AcmeOrderCertFmt,orderId))
{
Console.WriteLine("Fetching Certificate...");
varcertResp=await_acme.GetAsync(order.Payload.Certificate);
certResp.EnsureSuccessStatusCode();
using(varras=awaitcertResp.Content.ReadAsStreamAsync())
{
SaveRaw(ras,Constants.AcmeOrderCertFmt,orderId);
}
}
else
{
Console.WriteLine("Certificate already cached");
}
if(ExportCert!=null)
{
Console.WriteLine("Exporting Certificate Copy...");
using(varrs=LoadRaw<Stream>(true,Constants.AcmeOrderCertFmt,orderId))
using(varws=newFileStream(ExportCert,FileMode.Create))
{
awaitrs.CopyToAsync(ws);
}
}
if(ExportPfx!=null)
{
Console.WriteLine("Exporting Certificate as PFX (PKCS12)...");
PkiKeyprivateKey=null;
varpfxPassword=ExportPfxPassword;
if(pfxPassword!=null)
{
Console.WriteLine("...including private key in export");
stringcertKeys=default;
LoadStateInto(refcertKeys,failThrow:true,
Constants.AcmeOrderCertKeyFmt,orderId);
varkeyPair=Load(certKeys);
privateKey=keyPair.PrivateKey;
if(pfxPassword==" ")
{
Console.WriteLine("...WITH NO PASSWORD");
pfxPassword=null;
}
else
{
Console.WriteLine("...securing with password");
}
}
using(varcert=newX509Certificate2(LoadRaw<byte[]>(true,Constants.AcmeOrderCertFmt,orderId)))
{
varpkiCert=PkiCertificate.From(cert);
varpfx=pkiCert.Export(PkiArchiveFormat.Pkcs12,
privateKey:privateKey,
password:pfxPassword?.ToCharArray());
awaitFile.WriteAllBytesAsync(ExportPfx,pfx);
}
}
}
else
{
thrownewException($"Order is in unexpected state [{order.Payload.Status}];"
+$" expected [{Constants.PendingStatus}]");
}
}
privateasyncTaskProcessDns01(IJwsToolaccountSigner,Authorizationauthz,
Challengechlng,IChallengeValidationDetailscd)
{
vardnsCd=(Dns01ChallengeValidationDetails)cd;
vardnsCdValue=dnsCd.DnsRecordValue;
Console.WriteLine($" Challenge of Type: [{dnsCd.ChallengeType}]");
Console.WriteLine($" To handle this Challenge, create a DNS record with these details:");
Console.WriteLine($" DNS Record Name.....: {dnsCd.DnsRecordName}");
Console.WriteLine($" DNS Record Type.....: {dnsCd.DnsRecordType}");
Console.WriteLine($" DNS Record Value....: {dnsCdValue}");
Console.WriteLine();
if(chlng.Status!=Constants.PendingStatus)
{
Console.WriteLine($" Challenge No Longer Pending [{chlng.Status}]");
}
elseif(TestChallenges)
{
Console.WriteLine(" Testing for handling of DNS Challenge");
while(true)
{
stringerr=null;
varlookup=awaitDnsUtil.LookupRecordAsync(dnsCd.DnsRecordType,dnsCd.DnsRecordName);
vardnsValues=lookup?.Select(x =>x.Trim('"'));
if(dnsValues==null)
{
err="Could not resolve *any* DNS entries for Challenge record name";
}
elseif(!dnsValues.Contains(dnsCdValue))
{
vardnsValuesFlattened=string.Join(",",dnsValues);
err=$"DNS entry does not match expected value for Challenge record name ({dnsCdValue} not in {dnsValuesFlattened})";
}
else
{
Console.WriteLine(" Found response:");
foreach(vardvindnsValues)
Console.WriteLine($" {dv}");
Console.WriteLine(" SUCCESS! Found expected DNS entry for Challenge record name");
// We're done
break;
}
if(DateTime.Now<_testWaitUntil.GetValueOrDefault(DateTime.MinValue))
{
Console.WriteLine(" Last Test: "+err);
Console.WriteLine(" Waiting...");
Thread.Sleep(30*1000);
continue;
}
thrownewException(err);
}
}
Console.WriteLine();
}
privateasyncTaskProcessHttp01(IJwsToolaccountSigner,Authorizationauthz,
Challengechlng,IChallengeValidationDetailscd)
{
varhttpCd=(Http01ChallengeValidationDetails)cd;
Console.WriteLine($" Challenge of Type: [{httpCd.ChallengeType}]");
Console.WriteLine($" To handle this Challenge, create a file that will respond to an HTTP request with these details:");
Console.WriteLine($" HTTP Full URL.................: {httpCd.HttpResourceUrl}");
Console.WriteLine($" HTTP Resource Path............: {httpCd.HttpResourcePath}");
Console.WriteLine($" HTTP Resource Value...........: {httpCd.HttpResourceValue}");
Console.WriteLine($" HTTP Resource Content-Type....: {httpCd.HttpResourceContentType}");
if(chlng.Status!=Constants.PendingStatus)
{
Console.WriteLine($" Challenge No Longer Pending [{chlng.Status}]");
}
elseif(TestChallenges)
{
Console.WriteLine(" Testing for handling of HTTP Challenge");
while(true)
{
stringerr=null;
varhttpValue=awaitHttpUtil.GetStringAsync(httpCd.HttpResourceUrl);
if(string.IsNullOrEmpty(httpValue))
{
err="Missing or empty HTTP response for Challenge URL";
}
elseif(httpValue!=httpCd.HttpResourceValue)
{
err="HTTP response content does not match expected value for Challenge URL";
}
else
{
Console.WriteLine(" Found response:");
Console.WriteLine($" {httpValue}");
Console.WriteLine(" SUCCESS! Found expected HTTP response content for Challenge URL");
// We're done
break;
}
if(DateTime.Now<_testWaitUntil.GetValueOrDefault(DateTime.MinValue))
{
Console.WriteLine(" Last Test: "+err);
Console.WriteLine(" Waiting...");
Thread.Sleep(30*1000);
continue;
}
thrownewException(err);
}
}
Console.WriteLine();
}
privateboolStateExists(stringnameFormat,paramsobject[]nameArgs)
{
varname=string.Format(nameFormat,nameArgs);
varfullPath=Path.Combine(_statePath,name);
returnFile.Exists(fullPath);
}
privateboolSaveStateFrom<T>(Tvalue,stringnameFormat,paramsobject[]nameArgs)
{
varname=string.Format(nameFormat,nameArgs);
varfullPath=Path.Combine(_statePath,name);
varfullDir=Path.GetDirectoryName(fullPath);
if(!Directory.Exists(fullDir))
Directory.CreateDirectory(fullDir);
varser=JsonConvert.SerializeObject(value,Formatting.Indented);
File.WriteAllText(fullPath,ser);
returntrue;
}
privateboolSaveRaw<T>(Tvalue,stringnameFormat,paramsobject[]nameArgs)
{
varname=string.Format(nameFormat,nameArgs);
varfullPath=Path.Combine(_statePath,name);
varfullDir=Path.GetDirectoryName(fullPath);
if(!Directory.Exists(fullDir))
Directory.CreateDirectory(fullDir);
switch(value)
{
casestrings:
File.WriteAllText(fullPath,s);
break;
casebyte[]b:
File.WriteAllBytes(fullPath,b);
break;
caseStreamm:
using(varfs=newFileStream(fullPath,FileMode.Create))
m.CopyTo(fs);
break;
default:
thrownewArgumentException("Unsupported value type; must be one of: string, byte[], Stream",
nameof(value));
}
returntrue;
}
privateboolLoadStateInto<T>(refTvalue,stringnameFormat,paramsobject[]nameArgs)=>
LoadStateInto<T>(refvalue,true,nameFormat,nameArgs);
privateboolLoadStateInto<T>(refTvalue,boolfailThrow,stringnameFormat,paramsobject[]nameArgs)
{
varname=string.Format(nameFormat,nameArgs);
varfullPath=Path.Combine(_statePath,name);
if(!File.Exists(fullPath))
if(failThrow)
thrownewException($"Failed to read object from non-existent path [{fullPath}]");
else
returnfalse;
varser=File.ReadAllText(fullPath);
value=JsonConvert.DeserializeObject<T>(ser);
returntrue;
}
privateTLoadRaw<T>(boolfailThrow,stringnameFormat,paramsobject[]nameArgs)
{
varname=string.Format(nameFormat,nameArgs);
varfullPath=Path.Combine(_statePath,name);
if(!File.Exists(fullPath))
if(failThrow)
thrownewException($"Failed to read object from non-existent path [{fullPath}]");
else
returndefault;
if(typeof(T)==typeof(string))
return(T)(object)File.ReadAllText(fullPath);
elseif(typeof(T)==typeof(byte[]))
return(T)(object)File.ReadAllBytes(fullPath);
elseif(typeof(T)==typeof(Stream)||typeof(T)==typeof(FileStream))
return(T)(object)newFileStream(fullPath,FileMode.Open);
else
thrownewArgumentException("Unsupported return type; must be one of: string, byte[], Stream",
nameof(T));
}
privatestringComputeHash(stringvalue)
{
using(varsha=SHA256.Create())
{
varhash=sha.ComputeHash(Encoding.UTF8.GetBytes(value));
returnBitConverter.ToString(hash).Replace("-","");
}
}
privatestringSave(PkiKeyPairkeyPair)
{
using(varms=newMemoryStream())
{
keyPair.Save(ms);
returnConvert.ToBase64String(ms.ToArray());
}
}
privatePkiKeyPairLoad(stringb64)
{
using(varms=newMemoryStream(Convert.FromBase64String(b64)))
{
returnPkiKeyPair.Load(ms);
}
}
privatePkiCertificateSigningRequestGenerateCsr(IEnumerable<string>dnsNames,
PkiKeyPairkeyPair)
{
varfirstDns=dnsNames.First();
varcsr=newPkiCertificateSigningRequest($"CN={firstDns}",keyPair,
PkiHashAlgorithm.Sha256);
csr.CertificateExtensions.Add(
PkiCertificateExtension.CreateDnsSubjectAlternativeNames(dnsNames));
returncsr;
}
}
}