1
0
mirror of https://github.com/proxysu/ProxySU.git synced 2024-11-22 05:06:08 +03:00

add trojan-go project

This commit is contained in:
next-autumn 2021-05-08 11:45:46 +08:00
parent 5b547b87f9
commit c35d2d5434
13 changed files with 442 additions and 176 deletions

View File

@ -8,16 +8,8 @@ namespace ProxySU_Core.Models.Developers
{
int Port { get; set; }
int VLESS_gRPC_Port { get; set; }
int VLESS_KCP_Port { get; set; }
int VMESS_KCP_Port { get; set; }
int ShadowSocksPort { get; set; }
string Domain { get; set; }
List<XrayType> Types { get; set; }
List<int> FreePorts { get; }
}
}

View File

@ -305,26 +305,7 @@ namespace ProxySU_Core.Models.Developers
var portList = new List<int>();
portList.Add(80);
portList.Add(Parameters.Port);
if (Parameters.Types.Contains(XrayType.ShadowsocksAEAD))
{
portList.Add(Parameters.ShadowSocksPort);
}
if (Parameters.Types.Contains(XrayType.VMESS_KCP))
{
portList.Add(Parameters.VMESS_KCP_Port);
}
if (Parameters.Types.Contains(XrayType.VLESS_KCP))
{
portList.Add(Parameters.VLESS_KCP_Port);
}
if (Parameters.Types.Contains(XrayType.VLESS_gRPC))
{
portList.Add(Parameters.VLESS_gRPC_Port);
}
portList.AddRange(Parameters.FreePorts);
OpenPort(portList.ToArray());
}
@ -413,6 +394,9 @@ namespace ProxySU_Core.Models.Developers
RunCmd("systemctl enable caddy.service");
}
/// <summary>
/// 卸载 Caddy
/// </summary>
protected void UninstallCaddy()
{
RunCmd("rm -rf caddy_install.sh");
@ -491,9 +475,11 @@ namespace ProxySU_Core.Models.Developers
SetPortFree(80);
SetPortFree(443);
SetPortFree(Parameters.Port);
SetPortFree(Parameters.VLESS_gRPC_Port);
SetPortFree(Parameters.VLESS_KCP_Port);
SetPortFree(Parameters.ShadowSocksPort);
Parameters.FreePorts.ForEach(port =>
{
SetPortFree(port);
});
}
}
@ -562,6 +548,139 @@ namespace ProxySU_Core.Models.Developers
#endregion
#region BBR
private bool CheckKernelVersionBBR(string kernelVer)
{
string[] linuxKernelCompared = kernelVer.Split('.');
if (int.Parse(linuxKernelCompared[0]) > 4)
{
return true;
}
else if (int.Parse(linuxKernelCompared[0]) < 4)
{
return false;
}
else if (int.Parse(linuxKernelCompared[0]) == 4)
{
if (int.Parse(linuxKernelCompared[1]) >= 9)
{
return true;
}
else if (int.Parse(linuxKernelCompared[1]) < 9)
{
return false;
}
}
return false;
}
protected void EnableBBR()
{
var osVersion = RunCmd("uname -r");
var canInstallBBR = CheckKernelVersionBBR(osVersion.Split('-')[0]);
var bbrInfo = RunCmd("sysctl net.ipv4.tcp_congestion_control | grep bbr");
var installed = bbrInfo.Contains("bbr");
if (canInstallBBR && !installed)
{
RunCmd(@"bash -c 'echo ""net.core.default_qdisc=fq"" >> /etc/sysctl.conf'");
RunCmd(@"bash -c 'echo ""net.ipv4.tcp_congestion_control=bbr"" >> /etc/sysctl.conf'");
RunCmd(@"sysctl -p");
if (OnlyIpv6)
{
RemoveNat64();
}
WriteOutput("BBR启动成功");
}
if (!canInstallBBR)
{
WriteOutput("****** 系统不满足启用BBR条件启动失败。 ******");
}
}
#endregion
/// <summary>
/// 安装证书
/// </summary>
/// <param name="certPath"></param>
/// <param name="keyPath"></param>
protected void InstallCert(string dirPath, string certName, string keyName)
{
string certPath = Path.Combine(dirPath, certName);
string keyPath = Path.Combine(dirPath, keyName);
// 安装依赖
RunCmd(GetInstallCmd("socat"));
// 解决搬瓦工CentOS缺少问题
RunCmd(GetInstallCmd("automake autoconf libtool"));
// 安装Acme
var result = RunCmd($"curl https://get.acme.sh yes | sh");
if (result.Contains("Install success"))
{
WriteOutput("安装 acme.sh 成功");
}
else
{
WriteOutput("安装 acme.sh 失败,请联系开发者!");
throw new Exception("安装 acme.sh 失败,请联系开发者!");
}
RunCmd("cd ~/.acme.sh/");
RunCmd("alias acme.sh=~/.acme.sh/acme.sh");
// 申请证书
if (OnlyIpv6)
{
var cmd = $"/root/.acme.sh/acme.sh --force --debug --issue --standalone -d {Parameters.Domain} --listen-v6";
result = RunCmd(cmd);
}
else
{
var cmd = $"/root/.acme.sh/acme.sh --force --debug --issue --standalone -d {Parameters.Domain}";
result = RunCmd(cmd);
}
if (result.Contains("success"))
{
WriteOutput("申请证书成功");
}
else
{
WriteOutput("申请证书失败,如果申请次数过多请更换二级域名,或联系开发者!");
throw new Exception("申请证书失败,如果申请次数过多请更换二级域名,或联系开发者!");
}
// 安装证书
RunCmd($"mkdir -p {dirPath}");
RunCmd($"/root/.acme.sh/acme.sh --installcert -d {Parameters.Domain} --certpath {certPath} --keypath {keyPath} --capath {certPath}");
result = RunCmd($@"if [ ! -f ""{keyPath}"" ]; then echo ""0""; else echo ""1""; fi | head -n 1");
if (result.Contains("1"))
{
WriteOutput("安装证书成功");
}
else
{
WriteOutput("安装证书失败,请联系开发者!");
throw new Exception("安装证书失败,请联系开发者!");
}
RunCmd($"chmod 755 {dirPath}");
}
/// <summary>
/// 上传文件
/// </summary>
/// <param name="stream"></param>
/// <param name="path"></param>
protected void UploadFile(Stream stream, string path)
{
using (var sftp = new SftpClient(_sshClient.ConnectionInfo))

View File

@ -0,0 +1,62 @@
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProxySU_Core.Models.Developers
{
public class TrojanGoConfigBuilder
{
public static readonly int WebPort = 8088;
public static readonly string TrojanGoSettingPath = @"Templates\trojan-go\trojan-go.json";
public static readonly string CaddyFilePath = @"Templates\trojan-go\base.caddyfile";
public static string BuildTrojanGoConfig(TrojanGoSettings parameters)
{
var jsonStr = File.ReadAllText(TrojanGoSettingPath);
var settings = JToken.FromObject(JsonConvert.DeserializeObject(jsonStr));
settings["remote_port"] = WebPort;
settings["password"][0] = parameters.Password;
settings["ssl"]["sni"] = parameters.Domain;
return JsonConvert.SerializeObject(settings, Formatting.Indented, new JsonSerializerSettings()
{
NullValueHandling = NullValueHandling.Ignore
});
}
public static string BuildCaddyConfig(TrojanGoSettings parameters, bool useCustomWeb = false)
{
var caddyStr = File.ReadAllText(CaddyFilePath);
caddyStr.Replace("##domain##", parameters.Domain);
caddyStr.Replace("##port##", WebPort.ToString());
if (!useCustomWeb && !string.IsNullOrEmpty(parameters.MaskDomain))
{
var prefix = "http://";
if (parameters.MaskDomain.StartsWith("https://"))
{
prefix = "https://";
}
var domain = parameters.MaskDomain
.TrimStart("http://".ToCharArray())
.TrimStart("https://".ToCharArray());
caddyStr = caddyStr.Replace("##reverse_proxy##", $"reverse_proxy {prefix}{domain} {{ \n header_up Host {domain} \n }}");
}
else
{
caddyStr = caddyStr.Replace("##reverse_proxy##", "");
}
return caddyStr;
}
}
}

View File

@ -0,0 +1,134 @@
using Renci.SshNet;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace ProxySU_Core.Models.Developers
{
public class TrojanGoProject : Project<TrojanGoSettings>
{
public TrojanGoProject(SshClient sshClient, TrojanGoSettings parameters, Action<string> writeOutput) : base(sshClient, parameters, writeOutput)
{
}
public override void Install()
{
try
{
EnsureRootAuth();
if (FileExists("/usr/local/bin/xray"))
{
var btnResult = MessageBox.Show("已经安装Xray是否需要重装", "提示", MessageBoxButton.YesNo);
if (btnResult == MessageBoxResult.No)
{
MessageBox.Show("安装终止", "提示");
return;
}
}
WriteOutput("检测安装系统环境...");
EnsureSystemEnv();
WriteOutput("检测安装系统环境完成");
WriteOutput("配置服务器端口...");
ConfigurePort();
WriteOutput("端口配置完成");
WriteOutput("安装必要的系统工具...");
ConfigureSoftware();
WriteOutput("系统工具安装完成");
WriteOutput("检测IP6...");
ConfigureIPv6();
WriteOutput("检测IP6完成");
WriteOutput("配置防火墙...");
ConfigureFirewall();
WriteOutput("防火墙配置完成");
WriteOutput("同步系统和本地时间...");
SyncTimeDiff();
WriteOutput("时间同步完成");
WriteOutput("检测域名是否绑定本机IP...");
ValidateDomain();
WriteOutput("域名检测完成");
WriteOutput("安装Trojan-Go...");
InstallTrojanGo();
WriteOutput("Trojan-Go安装完成");
WriteOutput("安装Caddy...");
InstallCaddy();
WriteOutput("Caddy安装完成");
WriteOutput("启动BBR");
EnableBBR();
UploadCaddyFile();
WriteOutput("************");
WriteOutput("安装完成,尽情享用吧......");
WriteOutput("************");
}
catch (Exception ex)
{
var errorLog = "安装终止," + ex.Message;
WriteOutput(errorLog);
MessageBox.Show(errorLog);
}
}
private void InstallTrojanGo()
{
WriteOutput("安装Trojan-Go");
RunCmd(@"curl https://raw.githubusercontent.com/proxysu/shellscript/master/trojan-go.sh yes | bash");
var success = FileExists("/usr/local/etc/trojan-go");
if (success == false)
{
throw new Exception("trojan-go 安装失败,请联系开发者!");
}
RunCmd($"sed -i 's/User=nobody/User=root/g' /etc/systemd/system/xray.service");
RunCmd($"sed -i 's/CapabilityBoundingSet=/#CapabilityBoundingSet=/g' /etc/systemd/system/xray.service");
RunCmd($"sed -i 's/AmbientCapabilities=/#AmbientCapabilities=/g' /etc/systemd/system/xray.service");
RunCmd($"systemctl daemon-reload");
RunCmd("systemctl enable trojan-go");
RunCmd("systemctl start trojan-go");
WriteOutput("Trojan-Go 安装完成");
InstallCert(
dirPath: "/usr/local/etc/trojan-go",
certName: "trojan-go.crt",
keyName: "trojan-go.key");
if (FileExists("/usr/local/etc/trojan-go/config.json"))
{
RunCmd("mv /usr/local/etc/trojan-go/config.json config.json.old");
}
// 上传配置
var settings = TrojanGoConfigBuilder.BuildTrojanGoConfig(Parameters);
var stream = new MemoryStream(Encoding.UTF8.GetBytes(settings));
UploadFile(stream, "/usr/local/etc/trojan-go/config.json");
RunCmd("systemctl restart trojan-go");
}
private void UploadCaddyFile(bool useCustomWeb = false)
{
var config = TrojanGoConfigBuilder.BuildCaddyConfig(Parameters, useCustomWeb);
var stream = new MemoryStream(Encoding.UTF8.GetBytes(config));
if (FileExists("/etc/caddy/Caddyfile"))
{
RunCmd("mv /etc/caddy/Caddyfile /etc/caddy/Caddyfile.back");
}
UploadFile(stream, "/etc/caddy/Caddyfile");
RunCmd("systemctl restart caddy");
}
}
}

View File

@ -0,0 +1,29 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProxySU_Core.Models.Developers
{
public class TrojanGoSettings : IParameters
{
public int Port { get; set; }
public List<int> FreePorts
{
get
{
return new List<int>();
}
}
public string Domain { get; set; }
public List<XrayType> Types { get; set; }
public string Password { get; set; }
public string MaskDomain { get; set; }
}
}

View File

@ -8,11 +8,8 @@ using System.Text;
namespace ProxySU_Core.Models.Developers
{
public class ConfigBuilder
public class XrayConfigBuilder
{
public dynamic xrayConfig { get; set; }
public string CaddyConfig { get; set; }
private const string ServerLogDir = @"Templates\xray\server\00_log";
private const string ServerApiDir = @"Templates\xray\server\01_api";
private const string ServerDnsDir = @"Templates\xray\server\02_dns";

View File

@ -136,7 +136,7 @@ namespace ProxySU_Core.Models.Developers
EnsureRootAuth();
EnsureSystemEnv();
ConfigureFirewall();
var configJson = ConfigBuilder.BuildXrayConfig(Parameters);
var configJson = XrayConfigBuilder.BuildXrayConfig(Parameters);
var stream = new MemoryStream(Encoding.UTF8.GetBytes(configJson));
RunCmd("rm -rf /usr/local/etc/xray/config.json");
UploadFile(stream, "/usr/local/etc/xray/config.json");
@ -159,11 +159,15 @@ namespace ProxySU_Core.Models.Developers
/// <summary>
/// 安装证书
/// </summary>
public void InstallCert()
public void InstallCertToXray()
{
EnsureRootAuth();
EnsureSystemEnv();
this.InstallCertToXray();
InstallCert(
dirPath: "/usr/local/etc/xray/ssl",
certName: "xray_ssl.crt",
keyName: "xray_ssl.key");
RunCmd("systemctl restart xray");
WriteOutput("************ 安装证书完成 ************");
}
@ -243,66 +247,17 @@ namespace ProxySU_Core.Models.Developers
private void UploadCaddyFile(bool useCustomWeb = false)
{
var configJson = ConfigBuilder.BuildCaddyConfig(Parameters, useCustomWeb);
var configJson = XrayConfigBuilder.BuildCaddyConfig(Parameters, useCustomWeb);
var stream = new MemoryStream(Encoding.UTF8.GetBytes(configJson));
if (FileExists("/etc/caddy/Caddyfile"))
{
RunCmd("mv /etc/caddy/Caddyfile /etc/caddy/Caddyfile.back");
}
UploadFile(stream, "/etc/caddy/Caddyfile");
RunCmd("systemctl restart caddy");
}
private void EnableBBR()
{
var osVersion = RunCmd("uname -r");
var canInstallBBR = CheckKernelVersionBBR(osVersion.Split('-')[0]);
var bbrInfo = RunCmd("sysctl net.ipv4.tcp_congestion_control | grep bbr");
var installed = bbrInfo.Contains("bbr");
if (canInstallBBR && !installed)
{
RunCmd(@"bash -c 'echo ""net.core.default_qdisc=fq"" >> /etc/sysctl.conf'");
RunCmd(@"bash -c 'echo ""net.ipv4.tcp_congestion_control=bbr"" >> /etc/sysctl.conf'");
RunCmd(@"sysctl -p");
if (OnlyIpv6)
{
RemoveNat64();
}
WriteOutput("BBR启动成功");
}
if (!canInstallBBR)
{
WriteOutput("****** 系统不满足启用BBR条件启动失败。 ******");
}
}
private bool CheckKernelVersionBBR(string kernelVer)
{
string[] linuxKernelCompared = kernelVer.Split('.');
if (int.Parse(linuxKernelCompared[0]) > 4)
{
return true;
}
else if (int.Parse(linuxKernelCompared[0]) < 4)
{
return false;
}
else if (int.Parse(linuxKernelCompared[0]) == 4)
{
if (int.Parse(linuxKernelCompared[1]) >= 9)
{
return true;
}
else if (int.Parse(linuxKernelCompared[1]) < 9)
{
return false;
}
}
return false;
}
private void UninstallXray()
{
@ -340,82 +295,12 @@ namespace ProxySU_Core.Models.Developers
WriteOutput("TLS证书安装完成");
var configJson = ConfigBuilder.BuildXrayConfig(Parameters);
var configJson = XrayConfigBuilder.BuildXrayConfig(Parameters);
var stream = new MemoryStream(Encoding.UTF8.GetBytes(configJson));
RunCmd("rm -rf /usr/local/etc/xray/config.json");
UploadFile(stream, "/usr/local/etc/xray/config.json");
RunCmd("systemctl restart xray");
}
private void InstallCertToXray()
{
// 安装依赖
RunCmd(GetInstallCmd("socat"));
// 解决搬瓦工CentOS缺少问题
RunCmd(GetInstallCmd("automake autoconf libtool"));
// 安装Acme
var result = RunCmd($"curl https://raw.githubusercontent.com/acmesh-official/acme.sh/master/acme.sh | sh -s -- --install-online -m {GetRandomEmail()}");
if (result.Contains("Install success"))
{
WriteOutput("安装 acme.sh 成功");
}
else
{
WriteOutput("安装 acme.sh 失败,请联系开发者!");
throw new Exception("安装 acme.sh 失败,请联系开发者!");
}
RunCmd("cd ~/.acme.sh/");
RunCmd("alias acme.sh=~/.acme.sh/acme.sh");
// 申请证书
if (OnlyIpv6)
{
var cmd = $"/root/.acme.sh/acme.sh --force --debug --issue --standalone -d {Parameters.Domain} --listen-v6";
result = RunCmd(cmd);
}
else
{
var cmd = $"/root/.acme.sh/acme.sh --force --debug --issue --standalone -d {Parameters.Domain}";
result = RunCmd(cmd);
}
if (result.Contains("success"))
{
WriteOutput("申请证书成功");
}
else
{
WriteOutput("申请证书失败,如果申请次数过多请更换二级域名,或联系开发者!");
throw new Exception("申请证书失败,如果申请次数过多请更换二级域名,或联系开发者!");
}
// 安装证书到xray
RunCmd("mkdir -p /usr/local/etc/xray/ssl");
RunCmd($"/root/.acme.sh/acme.sh --installcert -d {Parameters.Domain} --certpath /usr/local/etc/xray/ssl/xray_ssl.crt --keypath /usr/local/etc/xray/ssl/xray_ssl.key --capath /usr/local/etc/xray/ssl/xray_ssl.crt");
result = RunCmd(@"if [ ! -f ""/usr/local/etc/xray/ssl/xray_ssl.key"" ]; then echo ""0""; else echo ""1""; fi | head -n 1");
if (result.Contains("1"))
{
WriteOutput("安装证书成功");
}
else
{
WriteOutput("安装证书失败,请联系开发者!");
throw new Exception("安装证书失败,请联系开发者!");
}
RunCmd(@"chmod 755 /usr/local/etc/xray/ssl");
}
private string GetRandomEmail()
{
Random r = new Random();
var num = r.Next(200000000, 900000000);
return $"{num}@qq.com";
}
private int GetRandomPort()
{
var random = new Random();

View File

@ -172,6 +172,19 @@ namespace ProxySU_Core.Models
/// </summary>
public List<XrayType> Types { get; set; }
public List<int> FreePorts
{
get
{
return new List<int>
{
VLESS_gRPC_Port,
VLESS_KCP_Port,
VMESS_KCP_Port,
ShadowSocksPort,
};
}
}
public string GetPath(XrayType type)
{

View File

@ -128,16 +128,19 @@
<Compile Include="Converters\LoginSecretTypeConverter.cs" />
<Compile Include="Converters\VisibleConverter.cs" />
<Compile Include="Models\AppSettings.cs" />
<Compile Include="Models\Developers\TrojanGoConfigBuilder.cs" />
<Compile Include="Models\Developers\TrojanGoProject.cs" />
<Compile Include="Models\Developers\TrojanGoSettings.cs" />
<Compile Include="Models\Host.cs" />
<Compile Include="Models\ShareLink.cs" />
<Compile Include="Models\XraySettings.cs" />
<Compile Include="Models\Developers\XraySettings.cs" />
<Compile Include="Models\XrayType.cs" />
<Compile Include="Tools\DateTimeUtils.cs" />
<Compile Include="Tools\Extensions.cs" />
<Compile Include="ViewModels\BaseCommand.cs" />
<Compile Include="ViewModels\BaseModel.cs" />
<Compile Include="ViewModels\BaseViewModel.cs" />
<Compile Include="Models\Developers\ConfigBuilder.cs" />
<Compile Include="Models\Developers\XrayConfigBuilder.cs" />
<Compile Include="Models\Developers\IParameters.cs" />
<Compile Include="Models\Developers\Project.cs" />
<Compile Include="Models\Developers\XrayProject.cs" />
@ -226,6 +229,12 @@
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
<None Include="Templates\trojan-go\base.caddyfile">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="Templates\trojan-go\trojan-go.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="Templates\xray\base.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>

View File

@ -0,0 +1,9 @@
:##port## {
root * /usr/share/caddy
file_server
##reverse_proxy##
}
##domain##:80 {
redir https://##domain##{uri}
}

View File

@ -0,0 +1,16 @@
{
"run_type": "server",
"local_addr": "0.0.0.0",
"local_port": 443,
"remote_addr": "127.0.0.1",
"remote_port": 80,
"password": [
""
],
"ssl": {
"cert": "/usr/local/etc/trojan-go/trojan-go.crt",
"key": "/usr/local/etc/trojan-go/trojan-go.key",
"sni": ""
}
}

View File

@ -37,9 +37,8 @@
<RowDefinition Height="auto" />
</Grid.RowDefinitions>
<TabControl Grid.Row="0" BorderThickness="0,1,0,0" BorderBrush="#DDD" Padding="10">
<TabItem metro:HeaderedControlHelper.HeaderFontSize="20" Header="xray-vless">
<TabItem metro:HeaderedControlHelper.HeaderFontSize="20" Padding="10,5,10,5" Header="Xray/V2ray">
<ScrollViewer Name="scroll"
BorderBrush="#ddd"
BorderThickness="2"
@ -58,6 +57,8 @@
</TabItem>
</TabControl>
<StackPanel Grid.Row="1" Grid.Column="0" VerticalAlignment="Center">
<Border BorderBrush="#DDD" BorderThickness="0,1,0,0" />
<Button Content="{DynamicResource Save}"

View File

@ -165,7 +165,7 @@ namespace ProxySU_Core
{
Task.Factory.StartNew(() =>
{
project.InstallCert();
project.InstallCertToXray();
});
}