Skip to content

Commit

Permalink
feat: Windows 下,自动添加防火墙入站规则
Browse files Browse the repository at this point in the history
  • Loading branch information
SALTWOOD committed Mar 9, 2024
1 parent cd74932 commit 0a6eb13
Show file tree
Hide file tree
Showing 5 changed files with 63 additions and 16 deletions.
1 change: 1 addition & 0 deletions CSharp-OpenBMCLAPI/CSharp-OpenBMCLAPI.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="SaltWood.TeraIO" Version="1.0.4" />
<PackageReference Include="SocketIOClient" Version="3.1.1" />
<PackageReference Include="WindowsFirewallHelper" Version="2.2.0.86" />
<PackageReference Include="ZstdSharp.Port" Version="0.7.5" />
</ItemGroup>

Expand Down
2 changes: 1 addition & 1 deletion CSharp-OpenBMCLAPI/Modules/Cluster.cs
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ private void InitializeHttpsServer(HttpServerAppBase server)
{
server.UriPrefixes = new()
{
$"http://*:4000/"
$"http://*:{SharedData.Config.PORT}/"
};
server.Started += (current, e) => SharedData.Logger.LogInfo($"HTTP 服务实例 \"<{server} {server.GetHashCode()}>\" 已启动");
server.Stopped += (current, e) => SharedData.Logger.LogInfo($"HTTP 服务实例 \"<{server} {server.GetHashCode()}>\" 已停止");
Expand Down
17 changes: 2 additions & 15 deletions CSharp-OpenBMCLAPI/Modules/Config.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,23 +14,10 @@ public class Config
public string clusterVersion;
// 用户访问时使用的 IP 或域名
[JsonProperty("host")]
public string HOST
{
get
{
if (string.IsNullOrEmpty(this._host))
{
//HttpClient client = new HttpClient();
//this._host = client.GetAsync("https://4.ipw.cn/").Result.Content.ReadAsStringAsync().Result;
this._host = $"";
}
return this._host;
}
set => this._host = value;
}
public string HOST { get; set; }
// 对外服务端口
[JsonProperty("port")]
public int PORT { get; set; }
public ushort PORT { get; set; }
// 是否使用自定义域名
public bool byoc;
// 指示是否执行快速上线,若为 true 则每次都不执行
Expand Down
49 changes: 49 additions & 0 deletions CSharp-OpenBMCLAPI/Modules/Utils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
using System.Security.Cryptography;
using System.Security.Principal;
using System.Text;
using WindowsFirewallHelper;
using static System.Net.Mime.MediaTypeNames;

namespace CSharpOpenBMCLAPI.Modules
{
Expand Down Expand Up @@ -73,5 +75,52 @@ public static bool RunAsAdministrator()
return false;
}
}

public static string ExceptionToDetail(Exception ex)
{
return $"""
{ex.GetType().FullName}: {ex.Message}
{ex.StackTrace}
""";
}

public static void CreatePortRule(string newPortRuleName, ushort portNumber, FirewallAction firewallAction, FirewallDirection firewallDirection)
{
//搜索规则
var rule = FirewallManager.Instance.Rules.Where(r =>
r.Direction == firewallDirection &&
r.Name.Equals(newPortRuleName)
).FirstOrDefault();

if (rule == null) // 指定的规则不存在
{
try
{
rule = FirewallManager.Instance.CreatePortRule(
FirewallProfiles.Domain | FirewallProfiles.Private | FirewallProfiles.Public, // 生效的配置文件
newPortRuleName,
firewallAction, // 运作:允许或阻止
portNumber,
FirewallProtocol.TCP //协议

);

rule.Direction = firewallDirection; //方向

FirewallManager.Instance.Rules.Add(rule);

SharedData.Logger.LogInfo($"添加防火墙规则成功:<IFirewallRule {rule.Name} {string.Join(',', rule.LocalPorts)} => {string.Join(',', rule.RemotePorts)} {rule.Protocol} {rule.Action}>");
}
catch (Exception ex)
{
SharedData.Logger.LogWarn($"添加防火墙规则失败:{ExceptionToDetail(ex)}");
}
}
else
{
// FirewallManager.Instance.Rules.Remove(rule);
SharedData.Logger.LogInfo($"防火墙规则已存在:<IFirewallRule {rule.Name} {string.Join(',', rule.LocalPorts)} => {string.Join(',', rule.RemotePorts)} {rule.Protocol} {rule.Action}>");
}
}
}
}
10 changes: 10 additions & 0 deletions CSharp-OpenBMCLAPI/Program.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using CSharpOpenBMCLAPI.Modules;
using Newtonsoft.Json;
using System.Reflection;
using System.Runtime.InteropServices;
using TeraIO.Runnable;

namespace CSharpOpenBMCLAPI
Expand Down Expand Up @@ -86,6 +87,15 @@ protected async Task<int> AsyncRun()
}
}

if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Utils.CreatePortRule("CSharp-OpenBMCLAPI",
SharedData.Config.PORT,
WindowsFirewallHelper.FirewallAction.Allow,
WindowsFirewallHelper.FirewallDirection.Inbound
);
}

// 从 .env.json 读取密钥然后 FetchToken
ClusterInfo info = JsonConvert.DeserializeObject<ClusterInfo>(await File.ReadAllTextAsync(".env.json"));
SharedData.ClusterInfo = info;
Expand Down

0 comments on commit 0a6eb13

Please sign in to comment.