Restore SEBPatch

This commit is contained in:
2025-06-01 11:44:20 +02:00
commit 8c656e3137
1297 changed files with 142172 additions and 0 deletions

View File

@@ -0,0 +1,60 @@
/*
* Copyright (c) 2024 ETH Zürich, IT Services
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using SafeExamBrowser.Configuration.Contracts.Integrity;
using SafeExamBrowser.Core.Contracts.OperationModel;
using SafeExamBrowser.Core.Contracts.OperationModel.Events;
using SafeExamBrowser.I18n.Contracts;
using SafeExamBrowser.Logging.Contracts;
namespace SafeExamBrowser.Runtime.Operations
{
internal class ApplicationIntegrityOperation : IOperation
{
private readonly IIntegrityModule module;
private readonly ILogger logger;
public event ActionRequiredEventHandler ActionRequired { add { } remove { } }
public event StatusChangedEventHandler StatusChanged;
public ApplicationIntegrityOperation(IIntegrityModule module, ILogger logger)
{
this.module = module;
this.logger = logger;
}
public OperationResult Perform()
{
logger.Info($"Attempting to verify application integrity...");
StatusChanged?.Invoke(TextKey.OperationStatus_VerifyApplicationIntegrity);
if (module.TryVerifyCodeSignature(out var isValid))
{
if (isValid)
{
logger.Info("Application integrity successfully verified.");
}
else
{
logger.Warn("Application integrity is compromised!");
}
}
else
{
logger.Warn("Failed to verify application integrity!");
}
return OperationResult.Success;
}
public OperationResult Revert()
{
return OperationResult.Success;
}
}
}

View File

@@ -0,0 +1,270 @@
/*
* Copyright (c) 2024 ETH Zürich, IT Services
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using System;
using System.Text;
using System.Threading;
using SafeExamBrowser.Communication.Contracts;
using SafeExamBrowser.Communication.Contracts.Events;
using SafeExamBrowser.Communication.Contracts.Hosts;
using SafeExamBrowser.Communication.Contracts.Proxies;
using SafeExamBrowser.Core.Contracts.OperationModel;
using SafeExamBrowser.Core.Contracts.OperationModel.Events;
using SafeExamBrowser.I18n.Contracts;
using SafeExamBrowser.Logging.Contracts;
using SafeExamBrowser.WindowsApi.Contracts;
using SafeExamBrowser.WindowsApi.Contracts.Events;
namespace SafeExamBrowser.Runtime.Operations
{
internal class ClientOperation : SessionOperation
{
private readonly ILogger logger;
private readonly IProcessFactory processFactory;
private readonly IProxyFactory proxyFactory;
private readonly IRuntimeHost runtimeHost;
private readonly int timeout_ms;
private IProcess ClientProcess
{
get { return Context.ClientProcess; }
set { Context.ClientProcess = value; }
}
private IClientProxy ClientProxy
{
get { return Context.ClientProxy; }
set { Context.ClientProxy = value; }
}
public override event ActionRequiredEventHandler ActionRequired { add { } remove { } }
public override event StatusChangedEventHandler StatusChanged;
public ClientOperation(
ILogger logger,
IProcessFactory processFactory,
IProxyFactory proxyFactory,
IRuntimeHost runtimeHost,
SessionContext sessionContext,
int timeout_ms) : base(sessionContext)
{
this.logger = logger;
this.processFactory = processFactory;
this.proxyFactory = proxyFactory;
this.runtimeHost = runtimeHost;
this.timeout_ms = timeout_ms;
}
public override OperationResult Perform()
{
StatusChanged?.Invoke(TextKey.OperationStatus_StartClient);
var success = TryStartClient();
if (success)
{
logger.Info("Successfully started new client instance.");
}
else
{
logger.Error("Failed to start new client instance! Aborting procedure...");
}
return success ? OperationResult.Success : OperationResult.Failed;
}
public override OperationResult Repeat()
{
return Perform();
}
public override OperationResult Revert()
{
var success = true;
if (ClientProcess != null && !ClientProcess.HasTerminated)
{
StatusChanged?.Invoke(TextKey.OperationStatus_StopClient);
success = TryStopClient();
}
return success ? OperationResult.Success : OperationResult.Failed;
}
private bool TryStartClient()
{
var authenticationToken = Context.Next.ClientAuthenticationToken.ToString("D");
var executablePath = Context.Next.AppConfig.ClientExecutablePath;
var logFilePath = $"{'"' + Convert.ToBase64String(Encoding.UTF8.GetBytes(Context.Next.AppConfig.ClientLogFilePath)) + '"'}";
var logLevel = Context.Next.Settings.LogLevel.ToString();
var runtimeHostUri = Context.Next.AppConfig.RuntimeAddress;
var uiMode = Context.Next.Settings.UserInterface.Mode.ToString();
var clientReady = false;
var clientReadyEvent = new AutoResetEvent(false);
var clientReadyEventHandler = new CommunicationEventHandler(() => clientReadyEvent.Set());
var clientTerminated = false;
var clientTerminatedEventHandler = new ProcessTerminatedEventHandler(_ => { clientTerminated = true; clientReadyEvent.Set(); });
logger.Info("Starting new client process...");
runtimeHost.AllowConnection = true;
runtimeHost.AuthenticationToken = Context.Next.ClientAuthenticationToken;
runtimeHost.ClientReady += clientReadyEventHandler;
ClientProcess = processFactory.StartNew(executablePath, logFilePath, logLevel, runtimeHostUri, authenticationToken, uiMode);
ClientProcess.Terminated += clientTerminatedEventHandler;
logger.Info("Waiting for client to complete initialization...");
clientReady = clientReadyEvent.WaitOne();
runtimeHost.AllowConnection = false;
runtimeHost.AuthenticationToken = default(Guid?);
runtimeHost.ClientReady -= clientReadyEventHandler;
ClientProcess.Terminated -= clientTerminatedEventHandler;
if (clientReady && !clientTerminated)
{
return TryStartCommunication();
}
if (!clientReady)
{
logger.Error($"Failed to start client!");
}
if (clientTerminated)
{
logger.Error("Client instance terminated unexpectedly during initialization!");
}
return false;
}
private bool TryStartCommunication()
{
var success = false;
logger.Info("Client has been successfully started and initialized. Creating communication proxy for client host...");
ClientProxy = proxyFactory.CreateClientProxy(Context.Next.AppConfig.ClientAddress, Interlocutor.Runtime);
if (ClientProxy.Connect(Context.Next.ClientAuthenticationToken))
{
logger.Info("Connection with client has been established. Requesting authentication...");
var communication = ClientProxy.RequestAuthentication();
var response = communication.Value;
success = communication.Success && ClientProcess.Id == response?.ProcessId;
if (success)
{
logger.Info("Authentication of client has been successful, client is ready to operate.");
}
else
{
logger.Error("Failed to verify client integrity!");
}
}
else
{
logger.Error("Failed to connect to client!");
}
return success;
}
private bool TryStopClient()
{
var success = false;
var disconnected = false;
var disconnectedEvent = new AutoResetEvent(false);
var disconnectedEventHandler = new CommunicationEventHandler(() => disconnectedEvent.Set());
var terminated = false;
var terminatedEvent = new AutoResetEvent(false);
var terminatedEventHandler = new ProcessTerminatedEventHandler((_) => terminatedEvent.Set());
if (ClientProxy != null)
{
runtimeHost.ClientDisconnected += disconnectedEventHandler;
ClientProcess.Terminated += terminatedEventHandler;
logger.Info("Instructing client to initiate shutdown procedure.");
ClientProxy.InitiateShutdown();
logger.Info("Disconnecting from client communication host.");
ClientProxy.Disconnect();
logger.Info("Waiting for client to disconnect from runtime communication host...");
disconnected = disconnectedEvent.WaitOne(timeout_ms / 2);
if (!disconnected)
{
logger.Error($"Client failed to disconnect within {timeout_ms / 2 / 1000} seconds!");
}
logger.Info("Waiting for client process to terminate...");
terminated = terminatedEvent.WaitOne(timeout_ms / 2);
if (!terminated)
{
logger.Error($"Client failed to terminate within {timeout_ms / 2 / 1000} seconds!");
}
runtimeHost.ClientDisconnected -= disconnectedEventHandler;
ClientProcess.Terminated -= terminatedEventHandler;
}
if (disconnected && terminated)
{
logger.Info("Client has been successfully terminated.");
success = true;
}
else
{
logger.Warn("Attempting to kill client process since graceful termination failed!");
success = TryKillClient();
}
if (success)
{
ClientProcess = null;
ClientProxy = null;
}
return success;
}
private bool TryKillClient()
{
const int MAX_ATTEMPTS = 5;
for (var attempt = 1; attempt <= MAX_ATTEMPTS; attempt++)
{
logger.Info($"Attempt {attempt}/{MAX_ATTEMPTS} to kill client process with ID = {ClientProcess.Id}.");
if (ClientProcess.TryKill(500))
{
break;
}
}
if (ClientProcess.HasTerminated)
{
logger.Info("Client process has terminated.");
}
else
{
logger.Error($"Failed to kill client process within {MAX_ATTEMPTS} attempts!");
}
return ClientProcess.HasTerminated;
}
}
}

View File

@@ -0,0 +1,44 @@
/*
* Copyright (c) 2024 ETH Zürich, IT Services
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using SafeExamBrowser.Communication.Contracts.Hosts;
using SafeExamBrowser.Communication.Contracts.Proxies;
using SafeExamBrowser.Core.Contracts.OperationModel;
using SafeExamBrowser.Logging.Contracts;
using SafeExamBrowser.WindowsApi.Contracts;
namespace SafeExamBrowser.Runtime.Operations
{
internal class ClientTerminationOperation : ClientOperation
{
public ClientTerminationOperation(
ILogger logger,
IProcessFactory processFactory,
IProxyFactory proxyFactory,
IRuntimeHost runtimeHost,
SessionContext sessionContext,
int timeout_ms) : base(logger, processFactory, proxyFactory, runtimeHost, sessionContext, timeout_ms)
{
}
public override OperationResult Perform()
{
return OperationResult.Success;
}
public override OperationResult Repeat()
{
return base.Revert();
}
public override OperationResult Revert()
{
return OperationResult.Success;
}
}
}

View File

@@ -0,0 +1,91 @@
/*
* Copyright (c) 2024 ETH Zürich, IT Services
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using System;
using SafeExamBrowser.Communication.Contracts.Data;
using SafeExamBrowser.Configuration.Contracts;
using SafeExamBrowser.Configuration.Contracts.Cryptography;
using SafeExamBrowser.Core.Contracts.OperationModel.Events;
using SafeExamBrowser.Runtime.Operations.Events;
using SafeExamBrowser.Settings;
namespace SafeExamBrowser.Runtime.Operations
{
internal abstract class ConfigurationBaseOperation : SessionOperation
{
protected string[] commandLineArgs;
protected IConfigurationRepository configuration;
protected string AppDataFilePath => Context.Next.AppConfig.AppDataFilePath;
protected string ProgramDataFilePath => Context.Next.AppConfig.ProgramDataFilePath;
public ConfigurationBaseOperation(string[] commandLineArgs, IConfigurationRepository configuration, SessionContext context) : base(context)
{
this.commandLineArgs = commandLineArgs;
this.configuration = configuration;
}
protected abstract void InvokeActionRequired(ActionRequiredEventArgs args);
protected LoadStatus? TryLoadSettings(Uri uri, UriSource source, out PasswordParameters passwordParams, out AppSettings settings, string currentPassword = default)
{
passwordParams = new PasswordParameters { Password = string.Empty, IsHash = true };
var status = configuration.TryLoadSettings(uri, out settings, passwordParams);
if (status == LoadStatus.PasswordNeeded && currentPassword != default)
{
passwordParams.Password = currentPassword;
passwordParams.IsHash = true;
status = configuration.TryLoadSettings(uri, out settings, passwordParams);
}
for (var attempts = 0; attempts < 5 && status == LoadStatus.PasswordNeeded; attempts++)
{
var isLocalConfig = source == UriSource.AppData || source == UriSource.ProgramData;
var purpose = isLocalConfig ? PasswordRequestPurpose.LocalSettings : PasswordRequestPurpose.Settings;
var success = TryGetPassword(purpose, out var password);
if (success)
{
passwordParams.Password = password;
passwordParams.IsHash = false;
}
else
{
return null;
}
status = configuration.TryLoadSettings(uri, out settings, passwordParams);
}
return status;
}
protected bool TryGetPassword(PasswordRequestPurpose purpose, out string password)
{
var args = new PasswordRequiredEventArgs { Purpose = purpose };
InvokeActionRequired(args);
password = args.Password;
return args.Success;
}
protected enum UriSource
{
Undefined,
AppData,
CommandLine,
ProgramData,
Reconfiguration,
Server
}
}
}

View File

@@ -0,0 +1,452 @@
/*
* Copyright (c) 2024 ETH Zürich, IT Services
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using System;
using System.IO;
using SafeExamBrowser.Communication.Contracts.Data;
using SafeExamBrowser.Configuration.Contracts;
using SafeExamBrowser.Configuration.Contracts.Cryptography;
using SafeExamBrowser.Core.Contracts.OperationModel;
using SafeExamBrowser.Core.Contracts.OperationModel.Events;
using SafeExamBrowser.I18n.Contracts;
using SafeExamBrowser.Logging.Contracts;
using SafeExamBrowser.Runtime.Operations.Events;
using SafeExamBrowser.Settings;
using SafeExamBrowser.Settings.Security;
using SafeExamBrowser.SystemComponents.Contracts;
namespace SafeExamBrowser.Runtime.Operations
{
internal class ConfigurationOperation : ConfigurationBaseOperation
{
private readonly IFileSystem fileSystem;
private readonly IHashAlgorithm hashAlgorithm;
private readonly ILogger logger;
public override event ActionRequiredEventHandler ActionRequired;
public override event StatusChangedEventHandler StatusChanged;
public ConfigurationOperation(
string[] commandLineArgs,
IConfigurationRepository configuration,
IFileSystem fileSystem,
IHashAlgorithm hashAlgorithm,
ILogger logger,
SessionContext sessionContext) : base(commandLineArgs, configuration, sessionContext)
{
this.fileSystem = fileSystem;
this.hashAlgorithm = hashAlgorithm;
this.logger = logger;
}
public override OperationResult Perform()
{
logger.Info("Initializing application configuration...");
StatusChanged?.Invoke(TextKey.OperationStatus_InitializeConfiguration);
var result = OperationResult.Failed;
var isValidUri = TryInitializeSettingsUri(out var uri, out var source);
if (isValidUri)
{
result = LoadSettingsForStartup(uri, source);
}
else
{
result = LoadDefaultSettings();
}
LogOperationResult(result);
return result;
}
public override OperationResult Repeat()
{
logger.Info("Initializing new application configuration...");
StatusChanged?.Invoke(TextKey.OperationStatus_InitializeConfiguration);
var result = OperationResult.Failed;
var isValidUri = TryValidateSettingsUri(Context.ReconfigurationFilePath, out var uri);
if (isValidUri)
{
result = LoadSettingsForReconfiguration(uri);
}
else
{
logger.Warn($"The resource specified for reconfiguration does not exist or is not valid!");
}
LogOperationResult(result);
return result;
}
public override OperationResult Revert()
{
return OperationResult.Success;
}
protected override void InvokeActionRequired(ActionRequiredEventArgs args)
{
ActionRequired?.Invoke(args);
}
private OperationResult LoadDefaultSettings()
{
logger.Info("No valid configuration resource specified and no local client configuration found - loading default settings...");
Context.Next.Settings = configuration.LoadDefaultSettings();
return OperationResult.Success;
}
private OperationResult LoadSettingsForStartup(Uri uri, UriSource source)
{
var currentPassword = default(string);
var passwordParams = default(PasswordParameters);
var settings = default(AppSettings);
var status = default(LoadStatus?);
if (source == UriSource.CommandLine)
{
var hasAppDataFile = File.Exists(AppDataFilePath);
var hasProgramDataFile = File.Exists(ProgramDataFilePath);
if (hasProgramDataFile)
{
status = TryLoadSettings(new Uri(ProgramDataFilePath, UriKind.Absolute), UriSource.ProgramData, out _, out settings);
}
else if (hasAppDataFile)
{
status = TryLoadSettings(new Uri(AppDataFilePath, UriKind.Absolute), UriSource.AppData, out _, out settings);
}
if ((!hasProgramDataFile && !hasAppDataFile) || status == LoadStatus.Success)
{
currentPassword = settings?.Security.AdminPasswordHash;
status = TryLoadSettings(uri, source, out passwordParams, out settings, currentPassword);
}
}
else
{
status = TryLoadSettings(uri, source, out passwordParams, out settings);
}
if (status.HasValue)
{
return DetermineLoadResult(uri, source, settings, status.Value, passwordParams, currentPassword);
}
else
{
return OperationResult.Aborted;
}
}
private OperationResult LoadSettingsForReconfiguration(Uri uri)
{
var currentPassword = Context.Current.Settings.Security.AdminPasswordHash;
var source = UriSource.Reconfiguration;
var status = TryLoadSettings(uri, source, out var passwordParams, out var settings, currentPassword);
var result = OperationResult.Failed;
if (status.HasValue)
{
result = DetermineLoadResult(uri, source, settings, status.Value, passwordParams, currentPassword);
}
else
{
result = OperationResult.Aborted;
}
if (result == OperationResult.Success && Context.Current.IsBrowserResource)
{
HandleReconfigurationByBrowserResource();
}
fileSystem.Delete(uri.LocalPath);
logger.Info($"Deleted temporary configuration file '{uri}'.");
return result;
}
private OperationResult DetermineLoadResult(Uri uri, UriSource source, AppSettings settings, LoadStatus status, PasswordParameters passwordParams, string currentPassword = default)
{
var result = OperationResult.Failed;
if (status == LoadStatus.LoadWithBrowser || status == LoadStatus.Success)
{
var isNewConfiguration = source == UriSource.CommandLine || source == UriSource.Reconfiguration;
Context.Next.Settings = settings;
if (status == LoadStatus.LoadWithBrowser)
{
result = HandleBrowserResource(uri);
}
else if (isNewConfiguration && settings.ConfigurationMode == ConfigurationMode.ConfigureClient)
{
result = HandleClientConfiguration(uri, passwordParams, currentPassword);
}
else
{
result = OperationResult.Success;
}
HandleStartUrlQuery(uri, source);
}
else
{
ShowFailureMessage(status, uri);
}
return result;
}
private OperationResult HandleBrowserResource(Uri uri)
{
Context.Next.IsBrowserResource = true;
Context.Next.Settings.Applications.Blacklist.Clear();
Context.Next.Settings.Applications.Whitelist.Clear();
Context.Next.Settings.Display.AllowedDisplays = 10;
Context.Next.Settings.Display.IgnoreError = true;
Context.Next.Settings.Display.InternalDisplayOnly = false;
Context.Next.Settings.Browser.DeleteCacheOnShutdown = false;
Context.Next.Settings.Browser.DeleteCookiesOnShutdown = false;
Context.Next.Settings.Browser.StartUrl = uri.AbsoluteUri;
Context.Next.Settings.Security.AllowReconfiguration = true;
Context.Next.Settings.Security.VirtualMachinePolicy = VirtualMachinePolicy.Allow;
Context.Next.Settings.Service.IgnoreService = true;
logger.Info($"The configuration resource needs authentication or is a webpage, using '{uri}' as start URL for the browser.");
return OperationResult.Success;
}
private OperationResult HandleClientConfiguration(Uri uri, PasswordParameters passwordParams, string currentPassword = default)
{
var isFirstSession = Context.Current == null;
var success = TryConfigureClient(uri, passwordParams, currentPassword);
var result = OperationResult.Failed;
if (!success.HasValue || (success == true && isFirstSession && AbortAfterClientConfiguration()))
{
result = OperationResult.Aborted;
}
else if (success == true)
{
result = OperationResult.Success;
}
return result;
}
private void HandleReconfigurationByBrowserResource()
{
Context.Next.Settings.Browser.DeleteCookiesOnStartup = false;
logger.Info("Some browser settings were overridden in order to retain a potential LMS / web application session.");
}
private void HandleStartUrlQuery(Uri uri, UriSource source)
{
if (source == UriSource.Reconfiguration && Uri.TryCreate(Context.ReconfigurationUrl, UriKind.Absolute, out var reconfigurationUri))
{
uri = reconfigurationUri;
}
if (uri != default && uri.Query.LastIndexOf('?') > 0)
{
Context.Next.Settings.Browser.StartUrlQuery = uri.Query.Substring(uri.Query.LastIndexOf('?'));
}
}
private bool? TryConfigureClient(Uri uri, PasswordParameters passwordParams, string currentPassword = default)
{
var mustAuthenticate = IsRequiredToAuthenticateForClientConfiguration(passwordParams, currentPassword);
logger.Info("Starting client configuration...");
if (mustAuthenticate)
{
var authenticated = AuthenticateForClientConfiguration(currentPassword);
if (authenticated == true)
{
logger.Info("Authentication was successful.");
}
if (authenticated == false)
{
logger.Info("Authentication has failed!");
ActionRequired?.Invoke(new InvalidPasswordMessageArgs());
return false;
}
if (!authenticated.HasValue)
{
logger.Info("Authentication was aborted.");
return null;
}
}
else
{
logger.Info("Authentication is not required.");
}
var status = configuration.ConfigureClientWith(uri, passwordParams);
var success = status == SaveStatus.Success;
if (success)
{
logger.Info("Client configuration was successful.");
}
else
{
logger.Error($"Client configuration failed with status '{status}'!");
ActionRequired?.Invoke(new ClientConfigurationErrorMessageArgs());
}
return success;
}
private bool IsRequiredToAuthenticateForClientConfiguration(PasswordParameters passwordParams, string currentPassword = default)
{
var mustAuthenticate = currentPassword != default;
if (mustAuthenticate)
{
var nextPassword = Context.Next.Settings.Security.AdminPasswordHash;
var hasSettingsPassword = passwordParams.Password != null;
var sameAdminPassword = currentPassword.Equals(nextPassword, StringComparison.OrdinalIgnoreCase);
if (sameAdminPassword)
{
mustAuthenticate = false;
}
else if (hasSettingsPassword)
{
var settingsPassword = passwordParams.IsHash ? passwordParams.Password : hashAlgorithm.GenerateHashFor(passwordParams.Password);
var knowsAdminPassword = currentPassword.Equals(settingsPassword, StringComparison.OrdinalIgnoreCase);
mustAuthenticate = !knowsAdminPassword;
}
}
return mustAuthenticate;
}
private bool? AuthenticateForClientConfiguration(string currentPassword)
{
var authenticated = false;
for (var attempts = 0; attempts < 5 && !authenticated; attempts++)
{
var success = TryGetPassword(PasswordRequestPurpose.LocalAdministrator, out var password);
if (success)
{
authenticated = currentPassword.Equals(hashAlgorithm.GenerateHashFor(password), StringComparison.OrdinalIgnoreCase);
}
else
{
return null;
}
}
return authenticated;
}
private bool AbortAfterClientConfiguration()
{
var args = new ConfigurationCompletedEventArgs();
ActionRequired?.Invoke(args);
logger.Info($"The user chose to {(args.AbortStartup ? "abort" : "continue")} startup after successful client configuration.");
return args.AbortStartup;
}
private void ShowFailureMessage(LoadStatus status, Uri uri)
{
switch (status)
{
case LoadStatus.PasswordNeeded:
ActionRequired?.Invoke(new InvalidPasswordMessageArgs());
break;
case LoadStatus.InvalidData:
ActionRequired?.Invoke(new InvalidDataMessageArgs(uri.ToString()));
break;
case LoadStatus.NotSupported:
ActionRequired?.Invoke(new NotSupportedMessageArgs(uri.ToString()));
break;
case LoadStatus.UnexpectedError:
ActionRequired?.Invoke(new UnexpectedErrorMessageArgs(uri.ToString()));
break;
}
}
private bool TryInitializeSettingsUri(out Uri uri, out UriSource source)
{
var isValidUri = false;
uri = default;
source = default;
if (commandLineArgs?.Length > 1)
{
isValidUri = Uri.TryCreate(commandLineArgs[1], UriKind.Absolute, out uri);
source = UriSource.CommandLine;
logger.Info($"Found command-line argument for configuration resource: '{uri}', the URI is {(isValidUri ? "valid" : "invalid")}.");
}
if (!isValidUri && File.Exists(ProgramDataFilePath))
{
isValidUri = Uri.TryCreate(ProgramDataFilePath, UriKind.Absolute, out uri);
source = UriSource.ProgramData;
logger.Info($"Found configuration file in program data directory: '{uri}'.");
}
if (!isValidUri && File.Exists(AppDataFilePath))
{
isValidUri = Uri.TryCreate(AppDataFilePath, UriKind.Absolute, out uri);
source = UriSource.AppData;
logger.Info($"Found configuration file in app data directory: '{uri}'.");
}
return isValidUri;
}
private bool TryValidateSettingsUri(string path, out Uri uri)
{
var isValidUri = Uri.TryCreate(path, UriKind.Absolute, out uri);
isValidUri &= uri != null && uri.IsFile;
isValidUri &= File.Exists(path);
return isValidUri;
}
private void LogOperationResult(OperationResult result)
{
switch (result)
{
case OperationResult.Aborted:
logger.Info("The configuration was aborted by the user.");
break;
case OperationResult.Failed:
logger.Warn("The configuration has failed!");
break;
case OperationResult.Success:
logger.Info("The configuration was successful.");
break;
}
}
}
}

View File

@@ -0,0 +1,86 @@
/*
* Copyright (c) 2024 ETH Zürich, IT Services
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using SafeExamBrowser.Core.Contracts.OperationModel;
using SafeExamBrowser.Core.Contracts.OperationModel.Events;
using SafeExamBrowser.I18n.Contracts;
using SafeExamBrowser.Logging.Contracts;
using SafeExamBrowser.Runtime.Operations.Events;
using SafeExamBrowser.UserInterface.Contracts.MessageBox;
namespace SafeExamBrowser.Runtime.Operations
{
internal class DisclaimerOperation : SessionOperation
{
private readonly ILogger logger;
public override event ActionRequiredEventHandler ActionRequired;
public override event StatusChangedEventHandler StatusChanged;
public DisclaimerOperation(ILogger logger, SessionContext context) : base(context)
{
this.logger = logger;
}
public override OperationResult Perform()
{
var result = OperationResult.Success;
if (Context.Next.Settings.Proctoring.ScreenProctoring.Enabled)
{
result = ShowScreenProctoringDisclaimer();
}
return result;
}
public override OperationResult Repeat()
{
var result = OperationResult.Success;
if (Context.Next.Settings.Proctoring.ScreenProctoring.Enabled)
{
result = ShowScreenProctoringDisclaimer();
}
return result;
}
public override OperationResult Revert()
{
return OperationResult.Success;
}
private OperationResult ShowScreenProctoringDisclaimer()
{
var args = new MessageEventArgs
{
Action = MessageBoxAction.OkCancel,
Icon = MessageBoxIcon.Information,
Message = TextKey.MessageBox_ScreenProctoringDisclaimer,
Title = TextKey.MessageBox_ScreenProctoringDisclaimerTitle
};
StatusChanged?.Invoke(TextKey.OperationStatus_WaitDisclaimerConfirmation);
ActionRequired?.Invoke(args);
if (args.Result == MessageBoxResult.Ok)
{
logger.Info("The user confirmed the screen proctoring disclaimer.");
return OperationResult.Success;
}
else
{
logger.Warn("The user did not confirm the screen proctoring disclaimer! Aborting session initialization...");
return OperationResult.Aborted;
}
}
}
}

View File

@@ -0,0 +1,87 @@
/*
* Copyright (c) 2024 ETH Zürich, IT Services
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using System;
using SafeExamBrowser.Core.Contracts.OperationModel;
using SafeExamBrowser.Core.Contracts.OperationModel.Events;
using SafeExamBrowser.I18n.Contracts;
using SafeExamBrowser.Logging.Contracts;
using SafeExamBrowser.Monitoring.Contracts.Display;
using SafeExamBrowser.Runtime.Operations.Events;
using SafeExamBrowser.UserInterface.Contracts.MessageBox;
namespace SafeExamBrowser.Runtime.Operations
{
internal class DisplayMonitorOperation : SessionOperation
{
private readonly IDisplayMonitor displayMonitor;
private readonly ILogger logger;
private readonly IText text;
public override event ActionRequiredEventHandler ActionRequired;
public override event StatusChangedEventHandler StatusChanged;
public DisplayMonitorOperation(IDisplayMonitor displayMonitor, ILogger logger, SessionContext context, IText text) : base(context)
{
this.displayMonitor = displayMonitor;
this.logger = logger;
this.text = text;
}
public override OperationResult Perform()
{
return CheckDisplayConfiguration();
}
public override OperationResult Repeat()
{
return CheckDisplayConfiguration();
}
public override OperationResult Revert()
{
return OperationResult.Success;
}
private OperationResult CheckDisplayConfiguration()
{
logger.Info("Validating display configuration...");
StatusChanged?.Invoke(TextKey.OperationStatus_ValidateDisplayConfiguration);
var result = OperationResult.Failed;
var validation = displayMonitor.ValidateConfiguration(Context.Next.Settings.Display);
if (validation.IsAllowed)
{
logger.Info("Display configuration is allowed.");
result = OperationResult.Success;
}
else
{
var args = new MessageEventArgs
{
Action = MessageBoxAction.Ok,
Icon = MessageBoxIcon.Error,
Message = TextKey.MessageBox_DisplayConfigurationError,
Title = TextKey.MessageBox_DisplayConfigurationErrorTitle
};
logger.Error("Display configuration is not allowed!");
args.MessagePlaceholders.Add("%%_ALLOWED_COUNT_%%", Convert.ToString(Context.Next.Settings.Display.AllowedDisplays));
args.MessagePlaceholders.Add("%%_TYPE_%%", Context.Next.Settings.Display.InternalDisplayOnly ? text.Get(TextKey.MessageBox_DisplayConfigurationInternal) : text.Get(TextKey.MessageBox_DisplayConfigurationInternalOrExternal));
args.MessagePlaceholders.Add("%%_EXTERNAL_COUNT_%%", Convert.ToString(validation.ExternalDisplays));
args.MessagePlaceholders.Add("%%_INTERNAL_COUNT_%%", Convert.ToString(validation.InternalDisplays));
ActionRequired?.Invoke(args);
}
return result;
}
}
}

View File

@@ -0,0 +1,23 @@
/*
* Copyright (c) 2024 ETH Zürich, IT Services
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using SafeExamBrowser.I18n.Contracts;
using SafeExamBrowser.UserInterface.Contracts.MessageBox;
namespace SafeExamBrowser.Runtime.Operations.Events
{
internal class ClientConfigurationErrorMessageArgs : MessageEventArgs
{
internal ClientConfigurationErrorMessageArgs()
{
Icon = MessageBoxIcon.Error;
Message = TextKey.MessageBox_ClientConfigurationError;
Title = TextKey.MessageBox_ClientConfigurationErrorTitle;
}
}
}

View File

@@ -0,0 +1,17 @@
/*
* Copyright (c) 2024 ETH Zürich, IT Services
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using SafeExamBrowser.Core.Contracts.OperationModel.Events;
namespace SafeExamBrowser.Runtime.Operations.Events
{
internal class ConfigurationCompletedEventArgs : ActionRequiredEventArgs
{
public bool AbortStartup { get; set; }
}
}

View File

@@ -0,0 +1,26 @@
/*
* Copyright (c) 2024 ETH Zürich, IT Services
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using System.Collections.Generic;
using SafeExamBrowser.Core.Contracts.OperationModel.Events;
using SafeExamBrowser.Server.Contracts.Data;
namespace SafeExamBrowser.Runtime.Operations.Events
{
internal class ExamSelectionEventArgs : ActionRequiredEventArgs
{
internal IEnumerable<Exam> Exams { get; set; }
internal Exam SelectedExam { get; set; }
internal bool Success { get; set; }
internal ExamSelectionEventArgs(IEnumerable<Exam> exams)
{
Exams = exams;
}
}
}

View File

@@ -0,0 +1,24 @@
/*
* Copyright (c) 2024 ETH Zürich, IT Services
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using SafeExamBrowser.I18n.Contracts;
using SafeExamBrowser.UserInterface.Contracts.MessageBox;
namespace SafeExamBrowser.Runtime.Operations.Events
{
internal class InvalidDataMessageArgs : MessageEventArgs
{
internal InvalidDataMessageArgs(string uri)
{
Icon = MessageBoxIcon.Error;
Message = TextKey.MessageBox_InvalidConfigurationData;
MessagePlaceholders["%%URI%%"] = uri;
Title = TextKey.MessageBox_InvalidConfigurationDataTitle;
}
}
}

View File

@@ -0,0 +1,23 @@
/*
* Copyright (c) 2024 ETH Zürich, IT Services
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using SafeExamBrowser.I18n.Contracts;
using SafeExamBrowser.UserInterface.Contracts.MessageBox;
namespace SafeExamBrowser.Runtime.Operations.Events
{
internal class InvalidPasswordMessageArgs : MessageEventArgs
{
internal InvalidPasswordMessageArgs()
{
Icon = MessageBoxIcon.Error;
Message = TextKey.MessageBox_InvalidPasswordError;
Title = TextKey.MessageBox_InvalidPasswordErrorTitle;
}
}
}

View File

@@ -0,0 +1,33 @@
/*
* Copyright (c) 2024 ETH Zürich, IT Services
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using System.Collections.Generic;
using SafeExamBrowser.Core.Contracts.OperationModel.Events;
using SafeExamBrowser.I18n.Contracts;
using SafeExamBrowser.UserInterface.Contracts.MessageBox;
namespace SafeExamBrowser.Runtime.Operations.Events
{
internal class MessageEventArgs : ActionRequiredEventArgs
{
internal MessageBoxAction Action { get; set; }
internal MessageBoxIcon Icon { get; set; }
internal TextKey Message { get; set; }
internal MessageBoxResult Result { get; set; }
internal TextKey Title { get; set; }
internal Dictionary<string, string> MessagePlaceholders { get; private set; }
internal Dictionary<string, string> TitlePlaceholders { get; private set; }
public MessageEventArgs()
{
Action = MessageBoxAction.Ok;
MessagePlaceholders = new Dictionary<string, string>();
TitlePlaceholders = new Dictionary<string, string>();
}
}
}

View File

@@ -0,0 +1,24 @@
/*
* Copyright (c) 2024 ETH Zürich, IT Services
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using SafeExamBrowser.I18n.Contracts;
using SafeExamBrowser.UserInterface.Contracts.MessageBox;
namespace SafeExamBrowser.Runtime.Operations.Events
{
internal class NotSupportedMessageArgs : MessageEventArgs
{
internal NotSupportedMessageArgs(string uri)
{
Icon = MessageBoxIcon.Error;
Message = TextKey.MessageBox_NotSupportedConfigurationResource;
MessagePlaceholders["%%URI%%"] = uri;
Title = TextKey.MessageBox_NotSupportedConfigurationResourceTitle;
}
}
}

View File

@@ -0,0 +1,20 @@
/*
* Copyright (c) 2024 ETH Zürich, IT Services
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using SafeExamBrowser.Communication.Contracts.Data;
using SafeExamBrowser.Core.Contracts.OperationModel.Events;
namespace SafeExamBrowser.Runtime.Operations.Events
{
internal class PasswordRequiredEventArgs : ActionRequiredEventArgs
{
public string Password { get; set; }
public PasswordRequestPurpose Purpose { get; set; }
public bool Success { get; set; }
}
}

View File

@@ -0,0 +1,27 @@
/*
* Copyright (c) 2024 ETH Zürich, IT Services
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using SafeExamBrowser.Core.Contracts.OperationModel.Events;
namespace SafeExamBrowser.Runtime.Operations.Events
{
internal class ServerFailureEventArgs : ActionRequiredEventArgs
{
public bool Abort { get; set; }
public bool Fallback { get; set; }
public string Message { get; set; }
public bool Retry { get; set; }
public bool ShowFallback { get; }
public ServerFailureEventArgs(string message, bool showFallback)
{
Message = message;
ShowFallback = showFallback;
}
}
}

View File

@@ -0,0 +1,24 @@
/*
* Copyright (c) 2024 ETH Zürich, IT Services
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using SafeExamBrowser.I18n.Contracts;
using SafeExamBrowser.UserInterface.Contracts.MessageBox;
namespace SafeExamBrowser.Runtime.Operations.Events
{
internal class UnexpectedErrorMessageArgs : MessageEventArgs
{
internal UnexpectedErrorMessageArgs(string uri)
{
Icon = MessageBoxIcon.Error;
Message = TextKey.MessageBox_UnexpectedConfigurationError;
MessagePlaceholders["%%URI%%"] = uri;
Title = TextKey.MessageBox_UnexpectedConfigurationErrorTitle;
}
}
}

View File

@@ -0,0 +1,25 @@
/*
* Copyright (c) 2024 ETH Zürich, IT Services
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using SafeExamBrowser.I18n.Contracts;
using SafeExamBrowser.UserInterface.Contracts.MessageBox;
namespace SafeExamBrowser.Runtime.Operations.Events
{
internal class VersionRestrictionMessageArgs : MessageEventArgs
{
internal VersionRestrictionMessageArgs(string version, string requiredVersions)
{
Icon = MessageBoxIcon.Error;
Message = TextKey.MessageBox_VersionRestrictionError;
MessagePlaceholders["%%_VERSION_%%"] = version;
MessagePlaceholders["%%_REQUIRED_VERSIONS_%%"] = requiredVersions;
Title = TextKey.MessageBox_VersionRestrictionErrorTitle;
}
}
}

View File

@@ -0,0 +1,183 @@
/*
* Copyright (c) 2024 ETH Zürich, IT Services
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using SafeExamBrowser.Core.Contracts.OperationModel;
using SafeExamBrowser.Core.Contracts.OperationModel.Events;
using SafeExamBrowser.I18n.Contracts;
using SafeExamBrowser.Logging.Contracts;
using SafeExamBrowser.Settings.Security;
using SafeExamBrowser.WindowsApi.Contracts;
namespace SafeExamBrowser.Runtime.Operations
{
internal class KioskModeOperation : SessionOperation
{
private readonly IDesktopFactory desktopFactory;
private readonly IDesktopMonitor desktopMonitor;
private readonly IExplorerShell explorerShell;
private readonly ILogger logger;
private readonly IProcessFactory processFactory;
private KioskMode? activeMode;
private IDesktop customDesktop;
private IDesktop originalDesktop;
public override event ActionRequiredEventHandler ActionRequired { add { } remove { } }
public override event StatusChangedEventHandler StatusChanged;
public KioskModeOperation(
IDesktopFactory desktopFactory,
IDesktopMonitor desktopMonitor,
IExplorerShell explorerShell,
ILogger logger,
IProcessFactory processFactory,
SessionContext sessionContext) : base(sessionContext)
{
this.desktopFactory = desktopFactory;
this.desktopMonitor = desktopMonitor;
this.explorerShell = explorerShell;
this.logger = logger;
this.processFactory = processFactory;
}
public override OperationResult Perform()
{
logger.Info($"Initializing kiosk mode '{Context.Next.Settings.Security.KioskMode}'...");
/*
StatusChanged?.Invoke(TextKey.OperationStatus_InitializeKioskMode);
activeMode = Context.Next.Settings.Security.KioskMode;
switch (Context.Next.Settings.Security.KioskMode)
{
case KioskMode.CreateNewDesktop:
CreateCustomDesktop();
break;
case KioskMode.DisableExplorerShell:
TerminateExplorerShell();
break;
}
*/
return OperationResult.Success;
}
public override OperationResult Repeat()
{
var newMode = Context.Next.Settings.Security.KioskMode;
if (activeMode == newMode)
{
logger.Info($"New kiosk mode '{newMode}' is the same as the currently active mode, skipping re-initialization...");
}
else
{
logger.Info($"Switching from kiosk mode '{activeMode}' to '{newMode}'...");
StatusChanged?.Invoke(TextKey.OperationStatus_InitializeKioskMode);
switch (activeMode)
{
case KioskMode.CreateNewDesktop:
CloseCustomDesktop();
break;
case KioskMode.DisableExplorerShell:
RestartExplorerShell();
break;
}
activeMode = newMode;
switch (newMode)
{
case KioskMode.CreateNewDesktop:
CreateCustomDesktop();
break;
case KioskMode.DisableExplorerShell:
TerminateExplorerShell();
break;
}
}
return OperationResult.Success;
}
public override OperationResult Revert()
{
logger.Info($"Reverting kiosk mode '{activeMode}'...");
StatusChanged?.Invoke(TextKey.OperationStatus_RevertKioskMode);
switch (activeMode)
{
case KioskMode.CreateNewDesktop:
CloseCustomDesktop();
break;
case KioskMode.DisableExplorerShell:
RestartExplorerShell();
break;
}
return OperationResult.Success;
}
private void CreateCustomDesktop()
{
originalDesktop = desktopFactory.GetCurrent();
logger.Info($"Current desktop is {originalDesktop}.");
customDesktop = desktopFactory.CreateRandom();
logger.Info($"Created custom desktop {customDesktop}.");
customDesktop.Activate();
processFactory.StartupDesktop = customDesktop;
logger.Info("Successfully activated custom desktop.");
desktopMonitor.Start(customDesktop);
}
private void CloseCustomDesktop()
{
desktopMonitor.Stop();
if (originalDesktop != default)
{
originalDesktop.Activate();
processFactory.StartupDesktop = originalDesktop;
logger.Info($"Switched back to original desktop {originalDesktop}.");
}
else
{
logger.Warn($"No original desktop found to activate!");
}
if (customDesktop != default)
{
customDesktop.Close();
logger.Info($"Closed custom desktop {customDesktop}.");
}
else
{
logger.Warn($"No custom desktop found to close!");
}
}
private void TerminateExplorerShell()
{
StatusChanged?.Invoke(TextKey.OperationStatus_WaitExplorerTermination);
explorerShell.HideAllWindows();
explorerShell.Terminate();
}
private void RestartExplorerShell()
{
StatusChanged?.Invoke(TextKey.OperationStatus_WaitExplorerStartup);
explorerShell.Start();
explorerShell.RestoreAllWindows();
}
}
}

View File

@@ -0,0 +1,71 @@
/*
* Copyright (c) 2024 ETH Zürich, IT Services
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using SafeExamBrowser.Core.Contracts.OperationModel;
using SafeExamBrowser.Core.Contracts.OperationModel.Events;
using SafeExamBrowser.I18n.Contracts;
using SafeExamBrowser.Logging.Contracts;
using SafeExamBrowser.Monitoring.Contracts;
using SafeExamBrowser.Runtime.Operations.Events;
using SafeExamBrowser.UserInterface.Contracts.MessageBox;
namespace SafeExamBrowser.Runtime.Operations
{
internal class RemoteSessionOperation : SessionOperation
{
private readonly IRemoteSessionDetector detector;
private readonly ILogger logger;
public override event ActionRequiredEventHandler ActionRequired;
public override event StatusChangedEventHandler StatusChanged;
public RemoteSessionOperation(IRemoteSessionDetector detector, ILogger logger, SessionContext context) : base(context)
{
this.detector = detector;
this.logger = logger;
}
public override OperationResult Perform()
{
return ValidatePolicy();
}
public override OperationResult Repeat()
{
return ValidatePolicy();
}
public override OperationResult Revert()
{
return OperationResult.Success;
}
private OperationResult ValidatePolicy()
{
logger.Info($"Validating remote session policy...");
StatusChanged?.Invoke(TextKey.OperationStatus_ValidateRemoteSessionPolicy);
if (Context.Next.Settings.Service.DisableRemoteConnections && detector.IsRemoteSession())
{
var args = new MessageEventArgs
{
Icon = MessageBoxIcon.Error,
Message = TextKey.MessageBox_RemoteSessionNotAllowed,
Title = TextKey.MessageBox_RemoteSessionNotAllowedTitle
};
logger.Error("Detected remote session while SEB is not allowed to be run in a remote session! Aborting...");
ActionRequired?.Invoke(args);
return OperationResult.Aborted;
}
return OperationResult.Success;
}
}
}

View File

@@ -0,0 +1,292 @@
/*
* Copyright (c) 2024 ETH Zürich, IT Services
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using SafeExamBrowser.Configuration.Contracts;
using SafeExamBrowser.Core.Contracts.OperationModel;
using SafeExamBrowser.Core.Contracts.OperationModel.Events;
using SafeExamBrowser.I18n.Contracts;
using SafeExamBrowser.Logging.Contracts;
using SafeExamBrowser.Runtime.Operations.Events;
using SafeExamBrowser.Server.Contracts;
using SafeExamBrowser.Server.Contracts.Data;
using SafeExamBrowser.Settings;
using SafeExamBrowser.SystemComponents.Contracts;
using SafeExamBrowser.UserInterface.Contracts.MessageBox;
namespace SafeExamBrowser.Runtime.Operations
{
internal class ServerOperation : ConfigurationBaseOperation
{
private readonly IFileSystem fileSystem;
private readonly ILogger logger;
private readonly IServerProxy server;
public override event ActionRequiredEventHandler ActionRequired;
public override event StatusChangedEventHandler StatusChanged;
public ServerOperation(
string[] commandLineArgs,
IConfigurationRepository configuration,
IFileSystem fileSystem,
ILogger logger,
SessionContext context,
IServerProxy server) : base(commandLineArgs, configuration, context)
{
this.fileSystem = fileSystem;
this.logger = logger;
this.server = server;
}
public override OperationResult Perform()
{
var result = OperationResult.Success;
if (Context.Next.Settings.SessionMode == SessionMode.Server)
{
var browserExamKey = default(string);
var exam = default(Exam);
var exams = default(IEnumerable<Exam>);
var uri = default(Uri);
logger.Info("Initializing server...");
StatusChanged?.Invoke(TextKey.OperationStatus_InitializeServer);
server.Initialize(Context.Next.Settings.Server);
var (abort, fallback, success) = TryPerformWithFallback(() => server.Connect());
if (success)
{
(abort, fallback, success) = TryPerformWithFallback(() => server.GetAvailableExams(Context.Next.Settings.Server.ExamId), out exams);
}
if (success)
{
success = TrySelectExam(exams, out exam);
}
if (success)
{
(abort, fallback, success) = TryPerformWithFallback(() => server.GetConfigurationFor(exam), out uri);
}
if (success)
{
result = TryLoadServerSettings(exam, uri);
}
if (success && result == OperationResult.Success)
{
(abort, fallback, success) = TryPerformWithFallback(() => server.SendSelectedExam(exam), out browserExamKey);
}
if (browserExamKey != default)
{
Context.Next.Settings.Browser.CustomBrowserExamKey = browserExamKey;
}
if (abort)
{
result = OperationResult.Aborted;
logger.Info("The user aborted the server operation.");
}
if (fallback)
{
Context.Next.Settings.SessionMode = SessionMode.Normal;
result = OperationResult.Success;
logger.Info("The user chose to fallback and start a normal session.");
}
}
return result;
}
public override OperationResult Repeat()
{
var result = OperationResult.Success;
if (Context.Current.Settings.SessionMode == SessionMode.Server && Context.Next.Settings.SessionMode == SessionMode.Server)
{
result = AbortServerReconfiguration();
}
else if (Context.Current.Settings.SessionMode == SessionMode.Server)
{
result = Revert();
}
else if (Context.Next.Settings.SessionMode == SessionMode.Server)
{
result = Perform();
}
return result;
}
public override OperationResult Revert()
{
var result = OperationResult.Success;
if (Context.Current?.Settings.SessionMode == SessionMode.Server || Context.Next?.Settings.SessionMode == SessionMode.Server)
{
logger.Info("Finalizing server...");
StatusChanged?.Invoke(TextKey.OperationStatus_FinalizeServer);
var disconnect = server.Disconnect();
if (disconnect.Success)
{
result = OperationResult.Success;
}
else
{
result = OperationResult.Failed;
}
}
return result;
}
protected override void InvokeActionRequired(ActionRequiredEventArgs args)
{
ActionRequired?.Invoke(args);
}
private OperationResult TryLoadServerSettings(Exam exam, Uri uri)
{
var info = server.GetConnectionInfo();
var result = OperationResult.Failed;
var status = TryLoadSettings(uri, UriSource.Server, out _, out var settings);
fileSystem.Delete(uri.LocalPath);
if (status == LoadStatus.Success)
{
var browserSettings = Context.Next.Settings.Browser;
var serverSettings = Context.Next.Settings.Server;
Context.Next.AppConfig.ServerApi = info.Api;
Context.Next.AppConfig.ServerConnectionToken = info.ConnectionToken;
Context.Next.AppConfig.ServerExamId = exam.Id;
Context.Next.AppConfig.ServerOauth2Token = info.Oauth2Token;
Context.Next.Settings = settings;
Context.Next.Settings.Browser.StartUrl = exam.Url;
Context.Next.Settings.Browser.StartUrlQuery = browserSettings.StartUrlQuery;
Context.Next.Settings.Server = serverSettings;
Context.Next.Settings.SessionMode = SessionMode.Server;
result = OperationResult.Success;
}
return result;
}
private (bool abort, bool fallback, bool success) TryPerformWithFallback(Func<ServerResponse> request)
{
var abort = false;
var fallback = false;
var success = false;
while (!success)
{
var response = request();
success = response.Success;
if (!success && !Retry(response.Message, out abort, out fallback))
{
break;
}
}
return (abort, fallback, success);
}
private (bool abort, bool fallback, bool success) TryPerformWithFallback<T>(Func<ServerResponse<T>> request, out T value)
{
var abort = false;
var fallback = false;
var success = false;
value = default;
while (!success)
{
var response = request();
success = response.Success;
value = response.Value;
if (!success && !Retry(response.Message, out abort, out fallback))
{
break;
}
}
return (abort, fallback, success);
}
private bool Retry(string message, out bool abort, out bool fallback)
{
var args = new ServerFailureEventArgs(message, Context.Next.Settings.Server.PerformFallback);
ActionRequired?.Invoke(args);
abort = args.Abort;
fallback = args.Fallback;
if (args.Retry)
{
logger.Debug("The user chose to retry the current server request.");
}
return args.Retry;
}
private bool TrySelectExam(IEnumerable<Exam> exams, out Exam exam)
{
var success = true;
if (string.IsNullOrWhiteSpace(Context.Next.Settings.Server.ExamId))
{
var args = new ExamSelectionEventArgs(exams);
ActionRequired?.Invoke(args);
exam = args.SelectedExam;
success = args.Success;
}
else
{
exam = exams.First();
logger.Info("Automatically selected exam as defined in configuration.");
}
return success;
}
private OperationResult AbortServerReconfiguration()
{
var args = new MessageEventArgs
{
Action = MessageBoxAction.Ok,
Icon = MessageBoxIcon.Warning,
Message = TextKey.MessageBox_ServerReconfigurationWarning,
Title = TextKey.MessageBox_ServerReconfigurationWarningTitle
};
logger.Warn("Server reconfiguration is currently not supported, aborting...");
ActionRequired?.Invoke(args);
return OperationResult.Aborted;
}
}
}

View File

@@ -0,0 +1,293 @@
/*
* Copyright (c) 2024 ETH Zürich, IT Services
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using System;
using System.Security.AccessControl;
using System.Threading;
using SafeExamBrowser.Communication.Contracts.Hosts;
using SafeExamBrowser.Communication.Contracts.Proxies;
using SafeExamBrowser.Configuration.Contracts;
using SafeExamBrowser.Core.Contracts.OperationModel;
using SafeExamBrowser.Core.Contracts.OperationModel.Events;
using SafeExamBrowser.I18n.Contracts;
using SafeExamBrowser.Logging.Contracts;
using SafeExamBrowser.Runtime.Operations.Events;
using SafeExamBrowser.Settings.Service;
using SafeExamBrowser.SystemComponents.Contracts;
using SafeExamBrowser.UserInterface.Contracts.MessageBox;
namespace SafeExamBrowser.Runtime.Operations
{
internal class ServiceOperation : SessionOperation
{
private ILogger logger;
private IRuntimeHost runtimeHost;
private IServiceProxy service;
private string serviceEventName;
private Guid? sessionId;
private int timeout_ms;
private IUserInfo userInfo;
public override event ActionRequiredEventHandler ActionRequired;
public override event StatusChangedEventHandler StatusChanged;
public ServiceOperation(
ILogger logger,
IRuntimeHost runtimeHost,
IServiceProxy service,
SessionContext sessionContext,
int timeout_ms,
IUserInfo userInfo) : base(sessionContext)
{
this.logger = logger;
this.runtimeHost = runtimeHost;
this.service = service;
this.timeout_ms = timeout_ms;
this.userInfo = userInfo;
}
public override OperationResult Perform()
{
logger.Info($"Initializing service...");
StatusChanged?.Invoke(TextKey.OperationStatus_InitializeServiceSession);
var success = IgnoreService() || TryInitializeConnection();
if (success && service.IsConnected)
{
success = TryStartSession();
}
return success ? OperationResult.Success : OperationResult.Failed;
}
public override OperationResult Repeat()
{
logger.Info($"Initializing service...");
StatusChanged?.Invoke(TextKey.OperationStatus_InitializeServiceSession);
var success = true;
if (service.IsConnected)
{
if (sessionId.HasValue)
{
success = TryStopSession();
}
if (success && IgnoreService())
{
success = TryTerminateConnection();
}
}
else
{
success = IgnoreService() || TryInitializeConnection();
}
if (success && service.IsConnected)
{
success = TryStartSession();
}
return success ? OperationResult.Success : OperationResult.Failed;
}
public override OperationResult Revert()
{
logger.Info("Finalizing service...");
StatusChanged?.Invoke(TextKey.OperationStatus_FinalizeServiceSession);
var success = true;
if (service.IsConnected)
{
if (sessionId.HasValue)
{
success = TryStopSession(true);
}
success &= TryTerminateConnection();
}
return success ? OperationResult.Success : OperationResult.Failed;
}
private bool IgnoreService()
{
if (Context.Next.Settings.Service.IgnoreService)
{
logger.Info("The service will be ignored for the next session.");
return true;
}
return false;
}
private bool TryInitializeConnection()
{
var mandatory = Context.Next.Settings.Service.Policy == ServicePolicy.Mandatory;
var warn = Context.Next.Settings.Service.Policy == ServicePolicy.Warn;
var connected = service.Connect();
var success = connected || !mandatory;
if (success)
{
logger.Info($"The service is {(mandatory ? "mandatory" : "optional")} and {(connected ? "connected." : "not connected.")}");
if (!connected && warn)
{
ActionRequired?.Invoke(new MessageEventArgs
{
Icon = MessageBoxIcon.Warning,
Message = TextKey.MessageBox_ServiceUnavailableWarning,
Title = TextKey.MessageBox_ServiceUnavailableWarningTitle
});
}
}
else
{
logger.Error("The service is mandatory but no connection could be established!");
ActionRequired?.Invoke(new MessageEventArgs
{
Icon = MessageBoxIcon.Error,
Message = TextKey.MessageBox_ServiceUnavailableError,
Title = TextKey.MessageBox_ServiceUnavailableErrorTitle
});
}
return success;
}
private bool TryTerminateConnection()
{
var disconnected = service.Disconnect();
if (disconnected)
{
logger.Info("Successfully disconnected from service.");
}
else
{
logger.Error("Failed to disconnect from service!");
}
return disconnected;
}
private bool TryStartSession()
{
var configuration = new ServiceConfiguration
{
AppConfig = Context.Next.AppConfig,
SessionId = Context.Next.SessionId,
Settings = Context.Next.Settings,
UserName = userInfo.GetUserName(),
UserSid = userInfo.GetUserSid()
};
var started = false;
logger.Info("Starting new service session...");
var communication = service.StartSession(configuration);
if (communication.Success)
{
started = TryWaitForServiceEvent(Context.Next.AppConfig.ServiceEventName);
if (started)
{
sessionId = Context.Next.SessionId;
serviceEventName = Context.Next.AppConfig.ServiceEventName;
logger.Info("Successfully started new service session.");
}
else
{
logger.Error($"Failed to start new service session within {timeout_ms / 1000} seconds!");
}
}
else
{
logger.Error("Failed to communicate session start command to service!");
}
return started;
}
private bool TryStopSession(bool isFinalSession = false)
{
var success = false;
logger.Info("Stopping current service session...");
var communication = service.StopSession(sessionId.Value);
if (communication.Success)
{
success = TryWaitForServiceEvent(serviceEventName);
if (success)
{
sessionId = default(Guid?);
serviceEventName = default(string);
logger.Info("Successfully stopped service session.");
}
else
{
logger.Error($"Failed to stop service session within {timeout_ms / 1000} seconds!");
}
}
else
{
logger.Error("Failed to communicate session stop command to service!");
}
if (success && isFinalSession)
{
communication = service.RunSystemConfigurationUpdate();
success = communication.Success;
if (communication.Success)
{
logger.Info("Instructed service to perform system configuration update.");
}
else
{
logger.Error("Failed to communicate system configuration update command to service!");
}
}
return success;
}
private bool TryWaitForServiceEvent(string eventName)
{
var serviceEvent = default(EventWaitHandle);
var startTime = DateTime.Now;
do
{
if (EventWaitHandle.TryOpenExisting(eventName, EventWaitHandleRights.Synchronize, out serviceEvent))
{
break;
}
} while (startTime.AddMilliseconds(timeout_ms) > DateTime.Now);
if (serviceEvent != default(EventWaitHandle))
{
using (serviceEvent)
{
return serviceEvent.WaitOne(timeout_ms);
}
}
return false;
}
}
}

View File

@@ -0,0 +1,77 @@
/*
* Copyright (c) 2024 ETH Zürich, IT Services
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using SafeExamBrowser.Core.Contracts.OperationModel;
using SafeExamBrowser.Core.Contracts.OperationModel.Events;
using SafeExamBrowser.Logging.Contracts;
namespace SafeExamBrowser.Runtime.Operations
{
internal class SessionActivationOperation : SessionOperation
{
private ILogger logger;
public override event ActionRequiredEventHandler ActionRequired { add { } remove { } }
public override event StatusChangedEventHandler StatusChanged { add { } remove { } }
public SessionActivationOperation(ILogger logger, SessionContext sessionContext) : base(sessionContext)
{
this.logger = logger;
}
public override OperationResult Perform()
{
SwitchLogSeverity();
ActivateNewSession();
return OperationResult.Success;
}
public override OperationResult Repeat()
{
SwitchLogSeverity();
ActivateNewSession();
return OperationResult.Success;
}
public override OperationResult Revert()
{
return OperationResult.Success;
}
private void SwitchLogSeverity()
{
if (logger.LogLevel != Context.Next.Settings.LogLevel)
{
var current = logger.LogLevel.ToString().ToUpper();
var next = Context.Next.Settings.LogLevel.ToString().ToUpper();
logger.Info($"Switching from log severity '{current}' to '{next}' for new session.");
logger.LogLevel = Context.Next.Settings.LogLevel;
}
}
private void ActivateNewSession()
{
var isFirstSession = Context.Current == null;
if (isFirstSession)
{
logger.Info($"Successfully activated first session '{Context.Next.SessionId}'.");
}
else
{
logger.Info($"Successfully terminated old session '{Context.Current.SessionId}' and activated new session '{Context.Next.SessionId}'.");
}
Context.Current = Context.Next;
Context.Next = null;
}
}
}

View File

@@ -0,0 +1,83 @@
/*
* Copyright (c) 2024 ETH Zürich, IT Services
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using SafeExamBrowser.Communication.Contracts.Hosts;
using SafeExamBrowser.Configuration.Contracts;
using SafeExamBrowser.Core.Contracts.OperationModel;
using SafeExamBrowser.Core.Contracts.OperationModel.Events;
using SafeExamBrowser.I18n.Contracts;
using SafeExamBrowser.Logging.Contracts;
using SafeExamBrowser.SystemComponents.Contracts;
namespace SafeExamBrowser.Runtime.Operations
{
internal class SessionInitializationOperation : SessionOperation
{
private IConfigurationRepository configuration;
private IFileSystem fileSystem;
private ILogger logger;
private IRuntimeHost runtimeHost;
public override event ActionRequiredEventHandler ActionRequired { add { } remove { } }
public override event StatusChangedEventHandler StatusChanged;
public SessionInitializationOperation(
IConfigurationRepository configuration,
IFileSystem fileSystem,
ILogger logger,
IRuntimeHost runtimeHost,
SessionContext sessionContext) : base(sessionContext)
{
this.configuration = configuration;
this.fileSystem = fileSystem;
this.logger = logger;
this.runtimeHost = runtimeHost;
}
public override OperationResult Perform()
{
InitializeSessionConfiguration();
return OperationResult.Success;
}
public override OperationResult Repeat()
{
InitializeSessionConfiguration();
return OperationResult.Success;
}
public override OperationResult Revert()
{
FinalizeSessionConfiguration();
return OperationResult.Success;
}
private void InitializeSessionConfiguration()
{
logger.Info("Initializing new session configuration...");
StatusChanged?.Invoke(TextKey.OperationStatus_InitializeSession);
Context.Next = configuration.InitializeSessionConfiguration();
logger.Info($" -> Client-ID: {Context.Next.AppConfig.ClientId}");
logger.Info($" -> Runtime-ID: {Context.Next.AppConfig.RuntimeId}");
logger.Info($" -> Session-ID: {Context.Next.SessionId}");
fileSystem.CreateDirectory(Context.Next.AppConfig.TemporaryDirectory);
}
private void FinalizeSessionConfiguration()
{
Context.Current = null;
Context.Next = null;
}
}
}

View File

@@ -0,0 +1,136 @@
/*
* Copyright (c) 2024 ETH Zürich, IT Services
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using SafeExamBrowser.Core.Contracts.OperationModel;
using SafeExamBrowser.Core.Contracts.OperationModel.Events;
using SafeExamBrowser.I18n.Contracts;
using SafeExamBrowser.Logging.Contracts;
using SafeExamBrowser.Monitoring.Contracts.System;
namespace SafeExamBrowser.Runtime.Operations
{
internal class SessionIntegrityOperation : SessionOperation
{
private readonly ILogger logger;
private readonly ISystemSentinel sentinel;
public override event ActionRequiredEventHandler ActionRequired { add { } remove { } }
public override event StatusChangedEventHandler StatusChanged;
public SessionIntegrityOperation(ILogger logger, ISystemSentinel sentinel, SessionContext context) : base(context)
{
this.logger = logger;
this.sentinel = sentinel;
}
public override OperationResult Perform()
{
var success = true;
StatusChanged?.Invoke(TextKey.OperationStatus_VerifySessionIntegrity);
success &= InitializeStickyKeys();
success &= VerifyCursors();
success &= VerifyEaseOfAccess();
LogResult(success);
return success ? OperationResult.Success : OperationResult.Failed;
}
public override OperationResult Repeat()
{
var success = true;
StatusChanged?.Invoke(TextKey.OperationStatus_VerifySessionIntegrity);
success &= InitializeStickyKeys();
success &= VerifyCursors();
success &= VerifyEaseOfAccess();
LogResult(success);
return success ? OperationResult.Success : OperationResult.Failed;
}
public override OperationResult Revert()
{
FinalizeStickyKeys();
return OperationResult.Success;
}
private void FinalizeStickyKeys()
{
sentinel.RevertStickyKeys();
}
private bool InitializeStickyKeys()
{
var success = true;
sentinel.RevertStickyKeys();
if (!Context.Next.Settings.Security.AllowStickyKeys)
{
success = sentinel.DisableStickyKeys();
}
return success;
}
private void LogResult(bool success)
{
if (success)
{
logger.Info("Successfully ensured session integrity.");
}
else
{
logger.Error("Failed to ensure session integrity! Aborting session initialization...");
}
}
private bool VerifyCursors()
{
var success = true;
if (Context.Next.Settings.Security.VerifyCursorConfiguration)
{
success = sentinel.VerifyCursors();
}
else
{
logger.Debug("Verification of cursor configuration is disabled.");
}
return success;
}
private bool VerifyEaseOfAccess()
{
var success = sentinel.VerifyEaseOfAccess();
if (!success)
{
if (Context.Current?.Settings.Service.IgnoreService == false)
{
logger.Info($"Ease of access configuration is compromised but service was active in the current session.");
success = true;
}
else if (!Context.Next.Settings.Service.IgnoreService)
{
logger.Info($"Ease of access configuration is compromised but service will be active in the next session.");
success = true;
}
}
return success;
}
}
}

View File

@@ -0,0 +1,33 @@
/*
* Copyright (c) 2024 ETH Zürich, IT Services
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using SafeExamBrowser.Core.Contracts.OperationModel;
using SafeExamBrowser.Core.Contracts.OperationModel.Events;
namespace SafeExamBrowser.Runtime.Operations
{
/// <summary>
/// The base implementation to be used for all operations in the session operation sequence.
/// </summary>
internal abstract class SessionOperation : IRepeatableOperation
{
protected SessionContext Context { get; private set; }
public abstract event ActionRequiredEventHandler ActionRequired;
public abstract event StatusChangedEventHandler StatusChanged;
public SessionOperation(SessionContext context)
{
Context = context;
}
public abstract OperationResult Perform();
public abstract OperationResult Repeat();
public abstract OperationResult Revert();
}
}

View File

@@ -0,0 +1,164 @@
/*
* Copyright (c) 2024 ETH Zürich, IT Services
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SafeExamBrowser.Core.Contracts.OperationModel;
using SafeExamBrowser.Core.Contracts.OperationModel.Events;
using SafeExamBrowser.I18n.Contracts;
using SafeExamBrowser.Logging.Contracts;
using SafeExamBrowser.Runtime.Operations.Events;
using SafeExamBrowser.Settings.Security;
namespace SafeExamBrowser.Runtime.Operations
{
internal class VersionRestrictionOperation : SessionOperation
{
private readonly ILogger logger;
private readonly IText text;
private IList<VersionRestriction> Restrictions => Context.Next.Settings.Security.VersionRestrictions;
public override event ActionRequiredEventHandler ActionRequired;
public override event StatusChangedEventHandler StatusChanged;
public VersionRestrictionOperation(ILogger logger, SessionContext context, IText text) : base(context)
{
this.logger = logger;
this.text = text;
}
public override OperationResult Perform()
{
return ValidateRestrictions();
}
public override OperationResult Repeat()
{
return ValidateRestrictions();
}
public override OperationResult Revert()
{
return OperationResult.Success;
}
private OperationResult ValidateRestrictions()
{
var result = OperationResult.Success;
logger.Info("Validating version restrictions...");
StatusChanged?.Invoke(TextKey.OperationStatus_ValidateVersionRestrictions);
if (Restrictions.Any())
{
var requiredVersions = $"'{string.Join("', '", Restrictions)}'";
var version = Context.Next.AppConfig.ProgramInformationalVersion;
if (Restrictions.Any(r => IsFulfilled(r)))
{
logger.Info($"The installed SEB version '{version}' complies with the version restrictions: {requiredVersions}.");
}
else
{
result = OperationResult.Aborted;
logger.Error($"The installed SEB version '{version}' does not comply with the version restrictions: {requiredVersions}.");
ActionRequired?.Invoke(new VersionRestrictionMessageArgs(version, BuildRequiredVersions()));
}
}
else
{
logger.Info($"There are no version restrictions for the configuration.");
}
return result;
}
private bool IsFulfilled(VersionRestriction restriction)
{
var isFulfilled = true;
var (major, minor, patch, build, isAllianceEdition) = GetVersion();
if (restriction.IsMinimumRestriction)
{
isFulfilled &= restriction.Major <= major;
if (restriction.Major == major)
{
isFulfilled &= restriction.Minor <= minor;
if (restriction.Minor == minor)
{
isFulfilled &= !restriction.Patch.HasValue || restriction.Patch <= patch;
if (restriction.Patch == patch)
{
isFulfilled &= !restriction.Build.HasValue || restriction.Build <= build;
}
}
}
isFulfilled &= !restriction.RequiresAllianceEdition || isAllianceEdition;
}
else
{
isFulfilled &= restriction.Major == major;
isFulfilled &= restriction.Minor == minor;
isFulfilled &= !restriction.Patch.HasValue || restriction.Patch == patch;
isFulfilled &= !restriction.Build.HasValue || restriction.Build == build;
isFulfilled &= !restriction.RequiresAllianceEdition || isAllianceEdition;
}
return isFulfilled;
}
private (int major, int minor, int patch, int build, bool isAllianceEdition) GetVersion()
{
var parts = Context.Next.AppConfig.ProgramBuildVersion.Split('.');
var major = int.Parse(parts[0]);
var minor = int.Parse(parts[1]);
var patch = int.Parse(parts[2]);
var build = int.Parse(parts[3]);
var isAllianceEdition = Context.Next.AppConfig.ProgramInformationalVersion.Contains("Alliance Edition");
return (major, minor, patch, build, isAllianceEdition);
}
private string BuildRequiredVersions()
{
var info = new StringBuilder();
var minimumVersionText = text.Get(TextKey.MessageBox_VersionRestrictionMinimum);
info.AppendLine();
info.AppendLine();
foreach (var restriction in Restrictions)
{
var build = restriction.Build.HasValue ? $".{restriction.Build}" : "";
var patch = restriction.Patch.HasValue ? $".{restriction.Patch}" : "";
var allianceEdition = restriction.RequiresAllianceEdition ? " Alliance Edition" : "";
var version = $"{restriction.Major}.{restriction.Minor}{patch}{build}{allianceEdition}";
if (restriction.IsMinimumRestriction)
{
info.AppendLine(minimumVersionText.Replace("%%_VERSION_%%", version));
}
else
{
info.AppendLine($"SEB {version}");
}
}
info.AppendLine();
return info.ToString();
}
}
}

View File

@@ -0,0 +1,72 @@
/*
* Copyright (c) 2024 ETH Zürich, IT Services
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using SafeExamBrowser.Core.Contracts.OperationModel;
using SafeExamBrowser.Core.Contracts.OperationModel.Events;
using SafeExamBrowser.I18n.Contracts;
using SafeExamBrowser.Logging.Contracts;
using SafeExamBrowser.Monitoring.Contracts;
using SafeExamBrowser.Runtime.Operations.Events;
using SafeExamBrowser.Settings.Security;
using SafeExamBrowser.UserInterface.Contracts.MessageBox;
namespace SafeExamBrowser.Runtime.Operations
{
internal class VirtualMachineOperation : SessionOperation
{
private readonly IVirtualMachineDetector detector;
private readonly ILogger logger;
public override event ActionRequiredEventHandler ActionRequired;
public override event StatusChangedEventHandler StatusChanged;
public VirtualMachineOperation(IVirtualMachineDetector detector, ILogger logger, SessionContext context) : base(context)
{
this.detector = detector;
this.logger = logger;
}
public override OperationResult Perform()
{
return ValidatePolicy();
}
public override OperationResult Repeat()
{
return ValidatePolicy();
}
public override OperationResult Revert()
{
return OperationResult.Success;
}
private OperationResult ValidatePolicy()
{
logger.Info($"Validating virtual machine policy...");
StatusChanged?.Invoke(TextKey.OperationStatus_ValidateVirtualMachinePolicy);
if (Context.Next.Settings.Security.VirtualMachinePolicy == VirtualMachinePolicy.Deny && detector.IsVirtualMachine())
{
var args = new MessageEventArgs
{
Icon = MessageBoxIcon.Error,
Message = TextKey.MessageBox_VirtualMachineNotAllowed,
Title = TextKey.MessageBox_VirtualMachineNotAllowedTitle
};
logger.Error("Detected virtual machine while SEB is not allowed to be run in a virtual machine! Aborting...");
ActionRequired?.Invoke(args);
return OperationResult.Aborted;
}
return OperationResult.Success;
}
}
}