Skip to content

Commit

Permalink
Merge pull request #2 from sangyuxiaowu/dev
Browse files Browse the repository at this point in the history
优化DNS验证、SSL服务调试,增强IP查询支持并升级至.NET 8
  • Loading branch information
sangyuxiaowu authored Dec 8, 2023
2 parents daa415c + 36ac0da commit 55a4591
Show file tree
Hide file tree
Showing 7 changed files with 62 additions and 27 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ SSL证书申请,可以每天0点固定检查一次即可,将要过期时,
| --delay | (Default: 0) How many seconds delay? <br> 启动后延迟多少秒进行检查处理,默认为 0,防止开机启动过早导致出现一些问题 |
| --del | (Default: false) Is delete DDNS? <br>删除配置文件中设置的DDNS域名解析,默认为 false ,如果为 true,则尝试删除后退出 |
| --v6 | (Default: false) Is ipv6? <br>使用 IPv6 来解析,默认获取 IPv4 |
| --ip | (Default: ) If set will be used. Otherwise automatically obtained.<br>You can set 'ifconfig', It will check from 'https://ifconfig.me/ip' to get you Internet IP. <br>默认为空字符,如果传入了指定 IP ,则使用这个 IP 来解析。<br>可以传入 'ifconfig' 值,该值则表示通过网络获取网络出口 IP 来解析
| --ip | (Default: ) If set will be used. Otherwise automatically obtained.<br>You can set 'ifconfig', It will check from 'https://ipw.cn/' to get you Internet IP. <br>默认为空字符,如果传入了指定 IP ,则使用这个 IP 来解析。<br>可以传入 'ifconfig' 值,该值则表示通过网络获取网络出口 IP 来解析

> 如:使用本地的 IPv6 进行 DDNS 设置
Expand Down
4 changes: 2 additions & 2 deletions SangServerTool/Options.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,13 @@ public class AUTO_SSL
/// <summary>
/// DNS验证重试多少次?
/// </summary>
[Option("retry", Default = 2, HelpText = "How many retries? ")]
[Option("retry", Default = 8, HelpText = "How many retries? ")]
public int Retry { get; set; }

/// <summary>
/// DNS验证失败等待多少秒重试?
/// </summary>
[Option("delay", Default = 10, HelpText = "How many seconds to retry? ")]
[Option("delay", Default = 5, HelpText = "How many seconds to retry? ")]
public int Delay { get; set; }
}

Expand Down
2 changes: 1 addition & 1 deletion SangServerTool/Properties/launchSettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"profiles": {
"SangServerTool": {
"commandName": "Project",
"commandLineArgs": "ddns -c \"test.json\" --v6=1"
"commandLineArgs": "ssl -c \"test.json\" --retry 5"
}
}
}
10 changes: 5 additions & 5 deletions SangServerTool/SangServerTool.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<Authors>SangSQ(桑世强)</Authors>
Expand All @@ -12,11 +12,11 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Certes" Version="3.0.3" />
<PackageReference Include="Certes" Version="3.0.4" />
<PackageReference Include="CommandLineParser" Version="2.9.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="8.0.0" />
</ItemGroup>

</Project>
2 changes: 1 addition & 1 deletion SangServerTool/Tool/DDNS.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ public async static Task<int> Run(AUTO_DDNS opt,ILogger logger)
}

var nowip = opt.IP == "" ? Utils.CurrentIPAddress(opt.IPV6)
: opt.IP == "ifconfig" ? Utils.CurrentIPAddress() : opt.IP;
: opt.IP == "ifconfig" ? Utils.CurrentIPAddressByWeb(opt.IPV6) : opt.IP;

//检查IP是否合规
if (!System.Net.IPAddress.TryParse(nowip, out _))
Expand Down
65 changes: 50 additions & 15 deletions SangServerTool/Tool/SSL.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
using Certes.Acme;
using Microsoft.Extensions.Logging;
using System.Diagnostics;
using System.Net;
using System.Reflection;

namespace SangServerTool.Tool
{
Expand Down Expand Up @@ -43,10 +45,16 @@ public async static Task<int> Run(AUTO_SSL opt, ILogger logger)
return 0;
}

if(cer_csr is null || cer_info is null || cer_acme is null)
{
logger.LogError("配置文件格式错误");
return 1;
}

AcmeAccount acmeinfo;
try
{
acmeinfo = await getAcmeAccountAsync(cer_acme.email, cer_acme.account);
acmeinfo = await GetAcmeAccountAsync(cer_acme.email, cer_acme.account);
}
catch (Exception ex)
{
Expand All @@ -59,11 +67,25 @@ public async static Task<int> Run(AUTO_SSL opt, ILogger logger)
var orders = await orderListContext.Orders();
//https://acme-staging-v02.api.letsencrypt.org/acme/order/59498234/3028278734

if (orders.Any())
{
foreach (var order in orders)
{
// 打印订单
logger.LogInformation($"订单:{order.Location}");
}
logger.LogInformation("已存在订单");
return 1;
}

// 开始请求证书,获取DNS验证的配置信息
DnsTask DnsTask;
try
{
DnsTask = await getDnsAuthInfoAsync(acmeinfo.acme, cer_info.domains);
DnsTask = await GetDnsAuthInfoAsync(acmeinfo.acme, cer_info.domains);

logger.LogInformation($"订单:{DnsTask.order.Location}");
DnsTask.dnsChallenge.ToList().ForEach(x => logger.LogInformation($"验证:{x.Location}"));
}
catch (Exception ex)
{
Expand Down Expand Up @@ -92,17 +114,24 @@ public async static Task<int> Run(AUTO_SSL opt, ILogger logger)
logger.LogInformation("准备验证域名,请稍后 ...");
await Task.Delay(2000);

// 执行Validate
foreach (var challenge in DnsTask.dnsChallenge)
{
await challenge.Validate();
}

// 检查验证结果
int retry = 0;
int ok;
do
{
if (retry > 0) {
logger.LogInformation($"正在重试 {retry.ToString()}/{opt.Retry.ToString()}");
logger.LogInformation($"正在查询 {retry.ToString()}/{opt.Retry.ToString()}");
}
ok = 0;
foreach (var challenge in DnsTask.dnsChallenge)
{
var result = await challenge.Validate();
var result = await challenge.Resource();

ok += result.Status == Certes.Acme.Resource.ChallengeStatus.Valid ? 1 : 0;
}
Expand Down Expand Up @@ -179,34 +208,40 @@ public async static Task<int> Run(AUTO_SSL opt, ILogger logger)
/// <param name="acme">ACME账户对象</param>
/// <param name="domains">申请的域名信息,多个用空格隔开</param>
/// <returns></returns>
public static async Task<DnsTask> getDnsAuthInfoAsync(AcmeContext acme, string domains)
public static async Task<DnsTask> GetDnsAuthInfoAsync(AcmeContext acme, string domains)
{
string[] domain = domains.Split(' ');
var order = await acme.NewOrder(domain);
var authz = await order.Authorizations();
IChallengeContext[] dnsChallenges = new IChallengeContext[domain.Length];
string[] dnsTxts = new string[domain.Length];
int i = 0;
foreach (var z in authz)
var domainArray = domains.Split(' ');
var order = await acme.NewOrder(domainArray);
var authorizationContexts = await order.Authorizations();
var dnsChallenges = new IChallengeContext[domainArray.Length];
var dnsTxts = new string[domainArray.Length];

for (int i = 0; i < authorizationContexts.Count(); i++)
{
dnsChallenges[i] = await z.Dns();
var authorizationContext = authorizationContexts.ElementAt(i);
dnsChallenges[i] = await authorizationContext.Dns();
dnsTxts[i] = acme.AccountKey.DnsTxt(dnsChallenges[i].Token);
i++;
}

return new DnsTask(dnsChallenges, order, dnsTxts);
}



/// <summary>
/// 获取Acme登录后对象
/// </summary>
/// <param name="email">邮箱</param>
/// <param name="pemKeyFile">邮箱账户pem密钥文件地址</param>
/// <returns></returns>
public static async Task<AcmeAccount> getAcmeAccountAsync(string email, string pemKeyFile)
public static async Task<AcmeAccount> GetAcmeAccountAsync(string email, string pemKeyFile)
{
string pemKey = File.Exists(pemKeyFile) ? await File.ReadAllTextAsync(pemKeyFile) : "";
#if DEBUG
var acme = pemKey == "" ? new AcmeContext(WellKnownServers.LetsEncryptStagingV2) : new AcmeContext(WellKnownServers.LetsEncryptStagingV2, KeyFactory.FromPem(pemKey));
# else
var acme = pemKey == "" ? new AcmeContext(WellKnownServers.LetsEncryptV2) : new AcmeContext(WellKnownServers.LetsEncryptV2, KeyFactory.FromPem(pemKey));
#endif
var account = pemKey == "" ? await acme.NewAccount(email, true) : await acme.Account();

// 若没有账户,则保存一下账户的KEY
Expand Down
4 changes: 2 additions & 2 deletions SangServerTool/Utils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,12 @@ public static bool isCerWillExp(string certFilePath)
/// 获取电脑外网IP
/// </summary>
/// <returns></returns>
public static string CurrentIPAddress() {
public static string CurrentIPAddressByWeb(bool isV6 = false) {
using var client = new HttpClient();
string ip = "";
try
{
ip = client.GetStringAsync("https://ifconfig.me/ip").Result;
ip = client.GetStringAsync($"https://{(isV6 ? "6" : "4")}.ipw.cn/").Result;
}
catch {
return ip;
Expand Down

0 comments on commit 55a4591

Please sign in to comment.