-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathProgram.cs
More file actions
424 lines (365 loc) · 13.7 KB
/
Program.cs
File metadata and controls
424 lines (365 loc) · 13.7 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
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
using Remotely.Server.Extensions;
using Bitbound.SimpleMessenger;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.Server.Circuits;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.FileProviders;
using Remotely.Server.Auth;
using Remotely.Server.Components.Account;
using Remotely.Server.Data;
using Remotely.Server.Hubs;
using Remotely.Server.Models;
using Remotely.Server.Options;
using Remotely.Server.Services;
using Remotely.Server.Services.Stores;
using Remotely.Shared.Entities;
using Remotely.Shared.Services;
using Serilog;
using System.Net;
using RatePolicyNames = Remotely.Server.RateLimiting.PolicyNames;
using Remotely.Server.Filters;
var builder = WebApplication.CreateBuilder(args);
var configuration = builder.Configuration;
var services = builder.Services;
configuration.AddEnvironmentVariables("Remotely_");
services.Configure<ApplicationOptions>(
configuration.GetSection(ApplicationOptions.SectionKey));
var appOptions = configuration
.GetSection(ApplicationOptions.SectionKey)
.Get<ApplicationOptions>();
services
.AddRazorComponents()
.AddInteractiveServerComponents();
services.AddRazorPages();
services.AddCascadingAuthenticationState();
services.AddScoped<IdentityUserAccessor>();
services.AddScoped<IdentityRedirectManager>();
services.AddScoped<AuthenticationStateProvider, IdentityRevalidatingAuthenticationStateProvider>();
var dbProvider = appOptions?.DbProvider?.ToLower();
switch (dbProvider)
{
case "sqlite":
services.AddDbContext<AppDb, SqliteDbContext>(
contextLifetime: ServiceLifetime.Transient,
optionsLifetime: ServiceLifetime.Transient);
break;
case "sqlserver":
services.AddDbContext<AppDb, SqlServerDbContext>(
contextLifetime: ServiceLifetime.Transient,
optionsLifetime: ServiceLifetime.Transient);
break;
case "postgresql":
services.AddDbContext<AppDb, PostgreSqlDbContext>(
contextLifetime: ServiceLifetime.Transient,
optionsLifetime: ServiceLifetime.Transient);
break;
default:
throw new InvalidOperationException(
$"Invalid DBProvider: {dbProvider}. Ensure a valid value " +
$"is set in appsettings.json or environment variables.");
}
using AppDb appDb = dbProvider switch
{
"sqlite" => new SqliteDbContext(builder.Configuration, builder.Environment),
"sqlserver" => new SqlServerDbContext(builder.Configuration, builder.Environment),
"postgresql" => new PostgreSqlDbContext(builder.Configuration, builder.Environment),
_ => throw new InvalidOperationException($"Invalid DBProvider: {dbProvider}")
};
await appDb.Database.MigrateAsync();
var settings = await appDb.GetAppSettings();
ConfigureSerilog(builder, settings);
builder.Logging.AddConfiguration(builder.Configuration.GetSection("Logging"));
if (OperatingSystem.IsWindows() && settings.EnableWindowsEventLog)
{
builder.Logging.AddEventLog();
}
builder.Services.AddAuthentication(options =>
{
options.DefaultScheme = IdentityConstants.ApplicationScheme;
options.DefaultSignInScheme = IdentityConstants.ExternalScheme;
})
.AddIdentityCookies();
services.AddIdentityCore<RemotelyUser>(options =>
{
options.Stores.MaxLengthForKeys = 128;
options.Password.RequireNonAlphanumeric = false;
})
.AddEntityFrameworkStores<AppDb>()
.AddSignInManager()
.AddDefaultTokenProviders();
services.AddScoped<IAuthorizationHandler, TwoFactorRequiredHandler>();
services.AddScoped<IAuthorizationHandler, OrganizationAdminRequirementHandler>();
services.AddScoped<IAuthorizationHandler, ServerAdminRequirementHandler>();
services.AddSingleton<IEmailSender<RemotelyUser>, IdentityNoOpEmailSender>();
services.AddAuthorization(options =>
{
options.AddPolicy(PolicyNames.TwoFactorRequired, builder =>
{
builder.Requirements.Add(new TwoFactorRequiredRequirement());
});
options.AddPolicy(PolicyNames.OrganizationAdminRequired, builder =>
{
builder.Requirements.Add(new OrganizationAdminRequirement());
});
options.AddPolicy(PolicyNames.ServerAdminRequired, builder =>
{
builder.Requirements.Add(new ServerAdminRequirement());
});
});
services.AddDatabaseDeveloperPageExceptionFilter();
if (settings.UseHttpLogging)
{
services.AddHttpLogging(options =>
{
options.RequestHeaders.Add("X-Forwarded-For");
options.RequestHeaders.Add("X-Forwarded-Proto");
options.RequestHeaders.Add("X-Forwarded-Host");
options.RequestHeaders.Add("X-Original-For");
options.RequestHeaders.Add("X-Original-Proto");
options.RequestHeaders.Add("X-Original-Host");
options.RequestHeaders.Add("Host");
});
}
services.AddCors(options =>
{
if (settings.TrustedCorsOrigins is { Count: > 0 } trustedOrigins)
{
options.AddPolicy("TrustedOriginPolicy", builder => builder
.WithOrigins(trustedOrigins.ToArray())
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
);
}
});
services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders = ForwardedHeaders.All;
options.ForwardLimit = null;
// Default Docker host. We want to allow forwarded headers from this address.
if (IPAddress.TryParse(appOptions?.DockerGatewayIp, out var dockerGatewayIp))
{
options.KnownProxies.Add(dockerGatewayIp);
}
if (settings.KnownProxies is { Count: > 0 } knownProxies)
{
foreach (var proxy in knownProxies)
{
if (IPAddress.TryParse(proxy, out var ip))
{
options.KnownProxies.Add(ip);
}
// Allow for CIDR in Known Proxies
else
{
// Try to parse the CIDR address
try
{
var network = Microsoft.AspNetCore.HttpOverrides.IPNetwork.Parse(proxy);
options.KnownNetworks.Add(network); // Add the network to KnownNetworks
}
catch (FormatException)
{
// Handle invalid CIDR format gracefully
// Log or throw an exception as needed
Console.WriteLine($"Invalid CIDR format: {proxy}");
}
}
}
}
});
services.AddSignalR(options =>
{
options.EnableDetailedErrors = builder.Environment.IsDevelopment();
options.MaximumReceiveMessageSize = 100_000;
})
.AddJsonProtocol(options =>
{
options.PayloadSerializerOptions.PropertyNameCaseInsensitive = true;
})
.AddMessagePackProtocol();
services.AddRateLimiter(options =>
{
options.AddConcurrencyLimiter(RatePolicyNames.AgentUpdateDownloads, clOptions =>
{
clOptions.QueueLimit = int.MaxValue;
clOptions.PermitLimit =
settings.MaxConcurrentUpdates <= 0 ?
10 :
settings.MaxConcurrentUpdates;
});
});
services.AddHttpClient();
services.AddLogging();
services.AddScoped<IEmailSender, EmailSender>();
if (builder.Environment.IsDevelopment())
{
services.AddScoped<IEmailSenderEx, EmailSenderFake>();
}
else
{
services.AddScoped<IEmailSender<RemotelyUser>, EmailSenderEx>();
services.AddScoped<IEmailSenderEx, EmailSenderEx>();
}
services.AddSingleton<IAppDbFactory, AppDbFactory>();
services.AddTransient<IDataService, DataService>();
services.AddScoped<ApiAuthorizationFilter>();
services.AddScoped<LocalOnlyFilter>();
services.AddScoped<ExpiringTokenFilter>();
services.AddHostedService<DataCleanupService>();
services.AddHostedService<ScriptScheduler>();
services.AddSingleton<IUpgradeService, UpgradeService>();
services.AddScoped<IToastService, ToastService>();
services.AddScoped<IModalService, ModalService>();
services.AddScoped<IJsInterop, JsInterop>();
services.AddScoped<ICircuitConnection, CircuitConnection>();
services.AddScoped<ILoaderService, LoaderService>();
services.AddScoped(x => (CircuitHandler)x.GetRequiredService<ICircuitConnection>());
services.AddSingleton<ICircuitManager, CircuitManager>();
services.AddScoped<IAuthService, AuthService>();
services.AddScoped<ISelectedCardsStore, SelectedCardsStore>();
services.AddScoped<IExpiringTokenService, ExpiringTokenService>();
services.AddScoped<IScriptScheduleDispatcher, ScriptScheduleDispatcher>();
services.AddSingleton<IOtpProvider, OtpProvider>();
services.AddSingleton<IEmbeddedServerDataProvider, EmbeddedServerDataProvider>();
services.AddSingleton<ILogsManager, LogsManager>();
services.AddScoped<IThemeProvider, ThemeProvider>();
services.AddScoped<IChatSessionStore, ChatSessionStore>();
services.AddScoped<ITerminalStore, TerminalStore>();
services.AddScoped<ViewerAuthorizationFilter>();
services.AddSingleton(WeakReferenceMessenger.Default);
services.AddSingleton<ISessionRecordingSink, SessionRecordingSink>();
services.AddSingleton<IDesktopStreamCache, DesktopStreamCache>();
services.AddSingleton<IRemoteControlSessionCache, RemoteControlSessionCache>();
services.AddSingleton<ISystemTime, SystemTime>();
services.AddSingleton<IAgentHubSessionCache, AgentHubSessionCache>();
services.AddHostedService<RemoteControlSessionCleaner>();
services.AddHostedService<RemoteControlSessionReconnector>();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
app.UseForwardedHeaders();
app.UseRateLimiter();
if (settings.UseHttpLogging)
{
app.UseHttpLogging();
}
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseMigrationsEndPoint();
}
else
{
app.UseExceptionHandler("/Error");
if (settings.UseHsts)
{
app.UseHsts();
}
if (settings.RedirectToHttps)
{
app.UseHttpsRedirection();
}
}
app.UseSwagger();
app.UseSwaggerUI();
ConfigureStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseCors("TrustedOriginPolicy");
app.UseAntiforgery();
app.MapRazorPages();
app.MapHub<DesktopHub>("/hubs/desktop");
app.MapHub<ViewerHub>("/hubs/viewer");
app.MapHub<AgentHub>("/hubs/service");
app.MapControllers();
app.MapRazorComponents<App>()
.AddInteractiveServerRenderMode();
app.MapAdditionalIdentityEndpoints();
using (var scope = app.Services.CreateScope())
{
var dataService = scope.ServiceProvider.GetRequiredService<IDataService>();
await dataService.SetAllDevicesNotOnline();
await dataService.CleanupOldRecords();
}
await app.RunAsync();
void ConfigureStaticFiles()
{
var provider = new FileExtensionContentTypeProvider();
// Add new mappings
provider.Mappings[".ps1"] = "application/octet-stream";
provider.Mappings[".exe"] = "application/octet-stream";
provider.Mappings[".dll"] = "application/octet-stream";
provider.Mappings[".appimage"] = "application/octet-stream";
provider.Mappings[".zip"] = "application/octet-stream";
provider.Mappings[".config"] = "application/octet-stream";
app.UseStaticFiles();
var contentPath = Path.Combine(app.Environment.WebRootPath, "Content");
if (Directory.Exists(contentPath))
{
app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(Path.Combine(app.Environment.WebRootPath, "Content")),
ServeUnknownFileTypes = true,
RequestPath = new PathString("/Content"),
ContentTypeProvider = provider,
DefaultContentType = "application/octet-stream"
});
}
// Needed for Let's Encrypt.
if (Directory.Exists(Path.Combine(app.Environment.ContentRootPath, ".well-known")))
{
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(Path.Combine(app.Environment.ContentRootPath, @".well-known")),
RequestPath = new PathString("/.well-known"),
ServeUnknownFileTypes = true
});
}
}
void ConfigureSerilog(WebApplicationBuilder webAppBuilder, SettingsModel settings)
{
try
{
var dataRetentionDays = settings.DataRetentionInDays;
if (dataRetentionDays <= 0)
{
dataRetentionDays = 7;
}
var logPath = LogsManager.DefaultLogsDirectory;
void ApplySharedLoggerConfig(LoggerConfiguration loggerConfiguration)
{
loggerConfiguration
.Enrich.FromLogContext()
.Enrich.WithThreadId()
.WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} {Properties}{NewLine}{Exception}")
.WriteTo.File($"{logPath}/Remotely_Server.log",
rollingInterval: RollingInterval.Day,
retainedFileTimeLimit: TimeSpan.FromDays(dataRetentionDays),
outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj} {Properties}{NewLine}{Exception}",
shared: true);
}
// https://github.com/serilog/serilog-aspnetcore#two-stage-initialization
var loggerConfig = new LoggerConfiguration();
ApplySharedLoggerConfig(loggerConfig);
Log.Logger = loggerConfig.CreateBootstrapLogger();
builder.Host.UseSerilog((context, services, configuration) =>
{
configuration
.ReadFrom.Configuration(context.Configuration)
.ReadFrom.Services(services);
ApplySharedLoggerConfig(configuration);
});
}
catch (Exception ex)
{
Console.WriteLine($"Failed to configure Serilog file logging. Error: {ex.Message}");
}
}