-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAppConfig.cs
More file actions
243 lines (203 loc) · 9 KB
/
AppConfig.cs
File metadata and controls
243 lines (203 loc) · 9 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
using System.Diagnostics;
using System.Net;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
namespace NginxPanel
{
public static class AppConfig
{
#if DEBUG
private const string _basePath = "/mnt/d/Repositories/Visual Studio Projects/NginxPanel/config";
#else
private const string _basePath = "/etc/nginxpanel";
#endif
public const string AppConfigPath = _basePath + "/app.conf";
private static bool _runningInContainer = false;
public static int Port { get; set; } = 5000;
public static string PFXPath { get; set; } = Path.Combine(_basePath, "self-signed.pfx");
public static string PFXPassword { get; set; } = GeneratePFXPassword();
public static bool DisableAuthWarningOnStart { get; set; } = false;
// Basic auth related settings
public static string Username { get; set; } = string.Empty;
public static string Password { get; set; } = string.Empty;
// DUO related settings
public static bool DUOEnabled { get; set; } = false;
public static string DUOClientID { get; set; } = string.Empty;
public static string DUOSecretKey { get; set; } = string.Empty;
public static string DUOAPIHostname { get; set; } = string.Empty;
public static string DUOUsername { get; set; } = string.Empty;
public static bool UserRequired
{
get
{
return (!String.IsNullOrWhiteSpace(Username) && !String.IsNullOrWhiteSpace(Password));
}
}
public static bool IsRunningInContainer
{
get
{
return _runningInContainer;
}
}
public static bool DUORequired => (DUOAvailable && DUOEnabled);
public static bool DUOAvailable
{
get
{
return (!String.IsNullOrWhiteSpace(DUOClientID) &&
!String.IsNullOrWhiteSpace(DUOSecretKey) &&
!String.IsNullOrWhiteSpace(DUOAPIHostname) &&
(!String.IsNullOrWhiteSpace(DUOUsername) || !String.IsNullOrWhiteSpace(Username)));
}
}
public static void Init()
{
// Check if config already exists
if (File.Exists(AppConfigPath))
{
// Load config, then save to make sure config settings are current
ReadConfig();
SaveConfig();
}
else
{
// Create a new config file with defaults
SaveConfig();
}
// Determine container status
try
{
// Docker check
if (Environment.GetEnvironmentVariable("DOTNET_RUNNING_IN_CONTAINER") == "true")
_runningInContainer = true;
// LXC check
using (Process p = new Process())
{
p.StartInfo = new ProcessStartInfo()
{
FileName = "ps",
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true,
Arguments = "2"
};
p.Start();
string standardOut = p.StandardOutput.ReadToEnd().Trim();
p.WaitForExit();
if (!standardOut.Contains("2"))
_runningInContainer = true;
}
}
catch
{
// Ignore exceptions
}
}
public static void SaveConfig()
{
if (!Directory.Exists(_basePath))
Directory.CreateDirectory(_basePath);
StringBuilder config = new StringBuilder();
config.AppendLine($"Port='{Port}'");
config.AppendLine($"PFXPath='{PFXPath}'");
config.AppendLine($"PFXPassword='{PFXPassword}'");
config.AppendLine($"DisableAuthWarningOnStart='{DisableAuthWarningOnStart}'");
// Basic auth related settings
config.AppendLine($"Username='{Username}'");
config.AppendLine($"Password='{Password}'");
// DUO related settings
config.AppendLine($"DUOEnabled='{DUOEnabled}'");
config.AppendLine($"DUOClientID='{DUOClientID}'");
config.AppendLine($"DUOSecretKey='{DUOSecretKey}'");
config.AppendLine($"DUOAPIHostname='{DUOAPIHostname}'");
config.AppendLine($"DUOUsername='{DUOUsername}'");
// Output config file (overwrites)
File.WriteAllText(AppConfigPath, config.ToString());
// Make sure certificate exists, if not then generate a new self-signed one
if (!File.Exists(PFXPath))
GenerateSelfSignedCert();
}
public static void ReadConfig()
{
string[] lines = File.ReadAllLines(AppConfigPath);
string[] split;
foreach (string line in lines.Where((x) => x.Contains("=")))
{
// TODO Add collection on unrecognized lines (such as comments)
split = line.Split('=', 2);
split[1] = split[1].Trim().Trim('\'').Trim();
switch (split[0].ToLower())
{
case "port":
Port = int.Parse(split[1]); break;
case "pfxpath":
PFXPath = split[1]; break;
case "pfxpassword":
PFXPassword = split[1]; break;
case "disableauthwarningonstart":
DisableAuthWarningOnStart = (split[1] == "1" || split[1].ToLower() == "true" || split[1].ToLower() == "yes"); break;
case "username":
Username = split[1]; break;
case "password":
Password = split[1]; break;
case "duoenabled":
DUOEnabled = (split[1] == "1" || split[1].ToLower() == "true" || split[1].ToLower() == "yes"); break;
case "duoclientid":
DUOClientID = split[1]; break;
case "duosecretkey":
DUOSecretKey = split[1]; break;
case "duoapihostname":
DUOAPIHostname = split[1]; break;
case "duousername":
DUOUsername = split[1]; break;
}
}
// If PFX path is blank, generate a new self-signed one
// by updating and saving the default PFX path value
if (String.IsNullOrWhiteSpace(PFXPath))
{
PFXPath = Path.Combine(_basePath, "self-signed.pfx");
SaveConfig();
}
}
private static string GeneratePFXPassword()
{
const string valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
StringBuilder pass = new StringBuilder();
Random rnd = new Random();
for (int c = 0; c < 20; c++)
{
pass.Append(valid[rnd.Next(valid.Length)]);
Thread.Sleep(50);
}
return pass.ToString();
}
private static void GenerateSelfSignedCert()
{
FileInfo pfx = new FileInfo(PFXPath);
SubjectAlternativeNameBuilder sanBuilder = new SubjectAlternativeNameBuilder();
sanBuilder.AddIpAddress(IPAddress.Loopback);
sanBuilder.AddIpAddress(IPAddress.IPv6Loopback);
sanBuilder.AddDnsName("localhost");
sanBuilder.AddDnsName(Environment.MachineName);
X500DistinguishedName distinguishedName = new X500DistinguishedName($"CN=NginxPanel");
using (RSA rsa = RSA.Create(2048))
{
CertificateRequest request = new CertificateRequest(distinguishedName, rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
request.CertificateExtensions.Add(
new X509KeyUsageExtension(X509KeyUsageFlags.DataEncipherment | X509KeyUsageFlags.KeyEncipherment | X509KeyUsageFlags.DigitalSignature, false));
request.CertificateExtensions.Add(
new X509EnhancedKeyUsageExtension(
new OidCollection { new Oid("1.3.6.1.5.5.7.3.1") }, false));
request.CertificateExtensions.Add(sanBuilder.Build());
X509Certificate2 certificate = request.CreateSelfSigned(new DateTimeOffset(DateTime.UtcNow.AddDays(-1)), new DateTimeOffset(DateTime.UtcNow.AddDays(3650)));
byte[] certData = certificate.Export(X509ContentType.Pfx, PFXPassword);
if (!Directory.Exists(pfx.DirectoryName))
Directory.CreateDirectory(pfx.DirectoryName!);
File.WriteAllBytes(pfx.FullName, certData);
}
}
}
}