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,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.ServiceModel;
using System.Timers;
using SafeExamBrowser.Communication.Contracts;
using SafeExamBrowser.Communication.Contracts.Data;
using SafeExamBrowser.Communication.Contracts.Events;
using SafeExamBrowser.Communication.Contracts.Proxies;
using SafeExamBrowser.Logging.Contracts;
namespace SafeExamBrowser.Communication.Proxies
{
/// <summary>
/// Base implementation of an <see cref="ICommunicationProxy"/>.
/// </summary>
public abstract class BaseProxy : ICommunicationProxy
{
private const int ONE_MINUTE = 60000;
private readonly object @lock = new object();
private string address;
private Interlocutor owner;
private IProxyObject proxy;
private IProxyObjectFactory factory;
private Guid? communicationToken;
private Timer timer;
protected ILogger Logger { get; }
public bool IsConnected => communicationToken.HasValue;
public event CommunicationEventHandler ConnectionLost;
public BaseProxy(string address, IProxyObjectFactory factory, ILogger logger, Interlocutor owner)
{
this.address = address;
this.factory = factory;
this.Logger = logger;
this.owner = owner;
}
public virtual bool Connect(Guid? token = null, bool autoPing = true)
{
try
{
Logger.Debug($"Trying to connect to endpoint '{address}'{(token.HasValue ? $" with authentication token '{token}'" : string.Empty)}...");
InitializeProxyObject();
var response = proxy.Connect(token);
var success = response.ConnectionEstablished;
communicationToken = response.CommunicationToken;
Logger.Debug($"Connection was {(success ? "established" : "refused")}.");
if (success && autoPing)
{
StartAutoPing();
}
return success;
}
catch (EndpointNotFoundException)
{
Logger.Warn($"Endpoint '{address}' could not be found!");
}
catch (Exception e)
{
Logger.Error($"Failed to connect to endpoint '{address}'!", e);
}
return false;
}
public virtual bool Disconnect()
{
try
{
if (!IsConnected)
{
Logger.Warn($"Cannot disconnect from endpoint '{address}' before being connected!");
return false;
}
StopAutoPing();
var message = new DisconnectionMessage
{
CommunicationToken = communicationToken.Value,
Interlocutor = owner
};
var response = proxy.Disconnect(message);
var success = response.ConnectionTerminated;
Logger.Debug($"{(success ? "Disconnected" : "Failed to disconnect")} from '{address}'.");
if (success)
{
communicationToken = null;
}
return success;
}
catch (Exception e)
{
Logger.Error($"Failed to disconnect from endpoint '{address}'!", e);
return false;
}
}
/// <summary>
/// Sends the given message, optionally returning a response. If no response is expected, <c>null</c> will be returned.
/// </summary>
/// <exception cref="ArgumentNullException">If the given message is <c>null</c>.</exception>
/// <exception cref="InvalidOperationException">If no connection has been established yet or the connection is corrupted.</exception>
protected virtual Response Send(Message message)
{
FailIfNull(message);
FailIfNotConnected();
message.CommunicationToken = communicationToken.Value;
Logger.Debug($"Sending message '{ToString(message)}'...");
var response = proxy.Send(message);
Logger.Debug($"Received response '{ToString(response)}' for message '{ToString(message)}'.");
return response;
}
/// <summary>
/// Sends the given purport as <see cref="SimpleMessage"/>.
/// </summary>
protected Response Send(SimpleMessagePurport purport)
{
return Send(new SimpleMessage(purport));
}
/// <summary>
/// Determines whether the given response is a <see cref="SimpleResponse"/> with purport <see cref="SimpleResponsePurport.Acknowledged"/>.
/// </summary>
protected bool IsAcknowledged(Response response)
{
return response is SimpleResponse simpleResponse && simpleResponse.Purport == SimpleResponsePurport.Acknowledged;
}
/// <summary>
/// Tests whether the connection to the host is alive by sending a ping message. If the transmission of the message fails or it is
/// not acknowledged, the <see cref="ConnectionLost"/> event is fired and the auto-ping timer stopped (if it was initialized).
/// </summary>
protected void TestConnection()
{
try
{
var response = Send(SimpleMessagePurport.Ping);
if (IsAcknowledged(response))
{
Logger.Info("Pinged host, connection is alive.");
}
else
{
Logger.Error($"Host did not acknowledge ping message! Received: {ToString(response)}.");
timer?.Stop();
ConnectionLost?.Invoke();
}
}
catch (Exception e)
{
Logger.Error("Failed to ping host!", e);
timer?.Stop();
ConnectionLost?.Invoke();
}
}
/// <summary>
/// Retrieves the string representation of the given <see cref="Message"/>, or indicates that a message is <c>null</c>.
/// </summary>
protected string ToString(Message message)
{
return message != null ? message.ToString() : "<null>";
}
/// <summary>
/// Retrieves the string representation of the given <see cref="Response"/>, or indicates that a response is <c>null</c>.
/// </summary>
protected string ToString(Response response)
{
return response != null ? response.ToString() : "<null>";
}
private void InitializeProxyObject()
{
proxy = factory.CreateObject(address);
proxy.Closed += BaseProxy_Closed;
proxy.Closing += BaseProxy_Closing;
proxy.Faulted += BaseProxy_Faulted;
proxy.Opened += BaseProxy_Opened;
proxy.Opening += BaseProxy_Opening;
}
private void BaseProxy_Closed(object sender, EventArgs e)
{
Logger.Debug("Communication channel has been closed.");
}
private void BaseProxy_Closing(object sender, EventArgs e)
{
Logger.Debug("Communication channel is closing...");
}
private void BaseProxy_Faulted(object sender, EventArgs e)
{
Logger.Warn("Communication channel has faulted!");
timer?.Stop();
ConnectionLost?.Invoke();
}
private void BaseProxy_Opened(object sender, EventArgs e)
{
Logger.Debug("Communication channel has been opened.");
}
private void BaseProxy_Opening(object sender, EventArgs e)
{
Logger.Debug("Communication channel is opening...");
}
private void FailIfNull(Message message)
{
if (message == null)
{
throw new ArgumentNullException(nameof(message));
}
}
private void FailIfNotConnected()
{
if (!IsConnected)
{
throw new InvalidOperationException($"Cannot send message before being connected to endpoint '{address}'!");
}
if (proxy == null || proxy.State != CommunicationState.Opened)
{
throw new InvalidOperationException($"Tried to send message, but channel was {GetChannelState()}!");
}
}
private string GetChannelState()
{
return proxy == null ? "null" : $"in state '{proxy.State}'";
}
private void StartAutoPing()
{
lock (@lock)
{
timer = new Timer(ONE_MINUTE) { AutoReset = true };
timer.Elapsed += Timer_Elapsed;
timer.Start();
}
}
private void StopAutoPing()
{
lock (@lock)
{
timer?.Stop();
}
}
private void Timer_Elapsed(object sender, ElapsedEventArgs args)
{
lock (@lock)
{
if (timer.Enabled)
{
TestConnection();
}
}
}
}
}

View File

@@ -0,0 +1,235 @@
/*
* 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 SafeExamBrowser.Communication.Contracts;
using SafeExamBrowser.Communication.Contracts.Data;
using SafeExamBrowser.Communication.Contracts.Proxies;
using SafeExamBrowser.Logging.Contracts;
namespace SafeExamBrowser.Communication.Proxies
{
/// <summary>
/// Default implementation of the <see cref="IClientProxy"/>, to be used for communication with the client application component.
/// </summary>
public class ClientProxy : BaseProxy, IClientProxy
{
public ClientProxy(string address, IProxyObjectFactory factory, ILogger logger, Interlocutor owner) : base(address, factory, logger, owner)
{
}
public CommunicationResult InformReconfigurationAborted()
{
try
{
var response = Send(new SimpleMessage(SimpleMessagePurport.ReconfigurationAborted));
var success = IsAcknowledged(response);
if (success)
{
Logger.Debug("Client acknowledged reconfiguration abortion.");
}
else
{
Logger.Error($"Client did not acknowledge reconfiguration abortion! Received: {ToString(response)}.");
}
return new CommunicationResult(success);
}
catch (Exception e)
{
Logger.Error($"Failed to perform '{nameof(InformReconfigurationAborted)}'", e);
return new CommunicationResult(false);
}
}
public CommunicationResult InformReconfigurationDenied(string filePath)
{
try
{
var response = Send(new ReconfigurationDeniedMessage(filePath));
var success = IsAcknowledged(response);
if (success)
{
Logger.Debug("Client acknowledged reconfiguration denial.");
}
else
{
Logger.Error($"Client did not acknowledge reconfiguration denial! Received: {ToString(response)}.");
}
return new CommunicationResult(success);
}
catch (Exception e)
{
Logger.Error($"Failed to perform '{nameof(InformReconfigurationDenied)}'", e);
return new CommunicationResult(false);
}
}
public CommunicationResult InitiateShutdown()
{
try
{
var response = Send(SimpleMessagePurport.Shutdown);
var success = IsAcknowledged(response);
if (success)
{
Logger.Debug("Client acknowledged shutdown request.");
}
else
{
Logger.Error($"Client did not acknowledge shutdown request! Received: {ToString(response)}.");
}
return new CommunicationResult(success);
}
catch (Exception e)
{
Logger.Error($"Failed to perform '{nameof(InitiateShutdown)}'", e);
return new CommunicationResult(false);
}
}
public CommunicationResult<AuthenticationResponse> RequestAuthentication()
{
try
{
var response = Send(SimpleMessagePurport.Authenticate);
var success = response is AuthenticationResponse;
if (success)
{
Logger.Debug("Received authentication response.");
}
else
{
Logger.Error($"Did not receive authentication response! Received: {ToString(response)}.");
}
return new CommunicationResult<AuthenticationResponse>(success, response as AuthenticationResponse);
}
catch (Exception e)
{
Logger.Error($"Failed to perform '{nameof(RequestAuthentication)}'", e);
return new CommunicationResult<AuthenticationResponse>(false, default(AuthenticationResponse));
}
}
public CommunicationResult RequestExamSelection(IEnumerable<(string id, string lms, string name, string url)> exams, Guid requestId)
{
try
{
var response = Send(new ExamSelectionRequestMessage(exams, requestId));
var success = IsAcknowledged(response);
if (success)
{
Logger.Debug("Client acknowledged server exam selection request.");
}
else
{
Logger.Error($"Client did not acknowledge server exam selection request! Received: {ToString(response)}.");
}
return new CommunicationResult(success);
}
catch (Exception e)
{
Logger.Error($"Failed to perform '{nameof(RequestExamSelection)}'", e);
return new CommunicationResult(false);
}
}
public CommunicationResult RequestPassword(PasswordRequestPurpose purpose, Guid requestId)
{
try
{
var response = Send(new PasswordRequestMessage(purpose, requestId));
var success = IsAcknowledged(response);
if (success)
{
Logger.Debug("Client acknowledged password request.");
}
else
{
Logger.Error($"Client did not acknowledge password request! Received: {ToString(response)}.");
}
return new CommunicationResult(success);
}
catch (Exception e)
{
Logger.Error($"Failed to perform '{nameof(RequestPassword)}'", e);
return new CommunicationResult(false);
}
}
public CommunicationResult RequestServerFailureAction(string message, bool showFallback, Guid requestId)
{
try
{
var response = Send(new ServerFailureActionRequestMessage(message, showFallback, requestId));
var success = IsAcknowledged(response);
if (success)
{
Logger.Debug("Client acknowledged server failure action request.");
}
else
{
Logger.Error($"Client did not acknowledge server failure action request! Received: {ToString(response)}.");
}
return new CommunicationResult(success);
}
catch (Exception e)
{
Logger.Error($"Failed to perform '{nameof(RequestServerFailureAction)}'", e);
return new CommunicationResult(false);
}
}
public CommunicationResult ShowMessage(string message, string title, int action, int icon, Guid requestId)
{
try
{
var response = Send(new MessageBoxRequestMessage(action, icon, message, requestId, title));
var success = IsAcknowledged(response);
if (success)
{
Logger.Debug("Client acknowledged message box request.");
}
else
{
Logger.Error($"Client did not acknowledge message box request! Received: {ToString(response)}.");
}
return new CommunicationResult(success);
}
catch (Exception e)
{
Logger.Error($"Failed to perform '{nameof(ShowMessage)}'", e);
return new CommunicationResult(false);
}
}
}
}

View File

@@ -0,0 +1,34 @@
/*
* 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;
using SafeExamBrowser.Communication.Contracts.Proxies;
using SafeExamBrowser.Logging.Contracts;
namespace SafeExamBrowser.Communication.Proxies
{
/// <summary>
/// Default implementation of the <see cref="IProxyFactory"/>, creating instances of the default proxy implementations.
/// </summary>
public class ProxyFactory : IProxyFactory
{
private IProxyObjectFactory factory;
private IModuleLogger logger;
public ProxyFactory(IProxyObjectFactory factory, IModuleLogger logger)
{
this.factory = factory;
this.logger = logger;
}
public IClientProxy CreateClientProxy(string address, Interlocutor owner)
{
return new ClientProxy(address, factory, logger.CloneFor(nameof(ClientProxy)), owner);
}
}
}

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 System.ServiceModel;
using SafeExamBrowser.Communication.Contracts.Proxies;
namespace SafeExamBrowser.Communication.Proxies
{
/// <summary>
/// Default implementation of the <see cref="IProxyObjectFactory"/> utilizing WCF (<see cref="ChannelFactory"/>).
/// </summary>
public class ProxyObjectFactory : IProxyObjectFactory
{
public IProxyObject CreateObject(string address)
{
var endpoint = new EndpointAddress(address);
var channel = ChannelFactory<IProxyObject>.CreateChannel(new NetNamedPipeBinding(NetNamedPipeSecurityMode.Transport), endpoint);
return channel;
}
}
}

View File

@@ -0,0 +1,234 @@
/*
* 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;
using SafeExamBrowser.Communication.Contracts.Data;
using SafeExamBrowser.Communication.Contracts.Proxies;
using SafeExamBrowser.Logging.Contracts;
namespace SafeExamBrowser.Communication.Proxies
{
/// <summary>
/// Default implementation of the <see cref="IRuntimeProxy"/>, to be used for communication with the runtime application component.
/// </summary>
public class RuntimeProxy : BaseProxy, IRuntimeProxy
{
public RuntimeProxy(string address, IProxyObjectFactory factory, ILogger logger, Interlocutor owner) : base(address, factory, logger, owner)
{
}
public CommunicationResult<ConfigurationResponse> GetConfiguration()
{
try
{
var response = Send(SimpleMessagePurport.ConfigurationNeeded);
var success = response is ConfigurationResponse;
if (success)
{
Logger.Debug("Received configuration response.");
}
else
{
Logger.Error($"Did not retrieve configuration response! Received: {ToString(response)}.");
}
return new CommunicationResult<ConfigurationResponse>(success, response as ConfigurationResponse);
}
catch (Exception e)
{
Logger.Error($"Failed to perform '{nameof(GetConfiguration)}'", e);
return new CommunicationResult<ConfigurationResponse>(false, default(ConfigurationResponse));
}
}
public CommunicationResult InformClientReady()
{
try
{
var response = Send(SimpleMessagePurport.ClientIsReady);
var success = IsAcknowledged(response);
if (success)
{
Logger.Debug("Runtime acknowledged that the client is ready.");
}
else
{
Logger.Error($"Runtime did not acknowledge that the client is ready! Response: {ToString(response)}.");
}
return new CommunicationResult(success);
}
catch (Exception e)
{
Logger.Error($"Failed to perform '{nameof(InformClientReady)}'", e);
return new CommunicationResult(false);
}
}
public CommunicationResult RequestReconfiguration(string filePath, string url)
{
try
{
var response = Send(new ReconfigurationMessage(filePath, url));
var success = IsAcknowledged(response);
if (success)
{
Logger.Debug("Runtime acknowledged reconfiguration request.");
}
else
{
Logger.Error($"Runtime did not acknowledge reconfiguration request! Response: {ToString(response)}.");
}
return new CommunicationResult(success);
}
catch (Exception e)
{
Logger.Error($"Failed to perform '{nameof(RequestReconfiguration)}'", e);
return new CommunicationResult(false);
}
}
public CommunicationResult RequestShutdown()
{
try
{
var response = Send(SimpleMessagePurport.RequestShutdown);
var success = IsAcknowledged(response);
if (success)
{
Logger.Debug("Runtime acknowledged shutdown request.");
}
else
{
Logger.Error($"Runtime did not acknowledge shutdown request! Response: {ToString(response)}.");
}
return new CommunicationResult(success);
}
catch (Exception e)
{
Logger.Error($"Failed to perform '{nameof(RequestShutdown)}'", e);
return new CommunicationResult(false);
}
}
public CommunicationResult SubmitExamSelectionResult(Guid requestId, bool success, string selectedExamId = null)
{
try
{
var response = Send(new ExamSelectionReplyMessage(requestId, success, selectedExamId));
var acknowledged = IsAcknowledged(response);
if (acknowledged)
{
Logger.Debug("Runtime acknowledged server exam selection transmission.");
}
else
{
Logger.Error($"Runtime did not acknowledge server exam selection transmission! Response: {ToString(response)}.");
}
return new CommunicationResult(acknowledged);
}
catch (Exception e)
{
Logger.Error($"Failed to perform '{nameof(SubmitExamSelectionResult)}'", e);
return new CommunicationResult(false);
}
}
public CommunicationResult SubmitMessageBoxResult(Guid requestId, int result)
{
try
{
var response = Send(new MessageBoxReplyMessage(requestId, result));
var acknowledged = IsAcknowledged(response);
if (acknowledged)
{
Logger.Debug("Runtime acknowledged message box result transmission.");
}
else
{
Logger.Error($"Runtime did not acknowledge message box result transmission! Response: {ToString(response)}.");
}
return new CommunicationResult(acknowledged);
}
catch (Exception e)
{
Logger.Error($"Failed to perform '{nameof(SubmitMessageBoxResult)}'", e);
return new CommunicationResult(false);
}
}
public CommunicationResult SubmitPassword(Guid requestId, bool success, string password = null)
{
try
{
var response = Send(new PasswordReplyMessage(requestId, success, password));
var acknowledged = IsAcknowledged(response);
if (acknowledged)
{
Logger.Debug("Runtime acknowledged password transmission.");
}
else
{
Logger.Error($"Runtime did not acknowledge password transmission! Response: {ToString(response)}.");
}
return new CommunicationResult(acknowledged);
}
catch (Exception e)
{
Logger.Error($"Failed to perform '{nameof(SubmitPassword)}'", e);
return new CommunicationResult(false);
}
}
public CommunicationResult SubmitServerFailureActionResult(Guid requestId, bool abort, bool fallback, bool retry)
{
try
{
var response = Send(new ServerFailureActionReplyMessage(abort, fallback, retry, requestId));
var acknowledged = IsAcknowledged(response);
if (acknowledged)
{
Logger.Debug("Runtime acknowledged server failure action transmission.");
}
else
{
Logger.Error($"Runtime did not acknowledge server failure action transmission! Response: {ToString(response)}.");
}
return new CommunicationResult(acknowledged);
}
catch (Exception e)
{
Logger.Error($"Failed to perform '{nameof(SubmitServerFailureActionResult)}'", e);
return new CommunicationResult(false);
}
}
}
}

View File

@@ -0,0 +1,105 @@
/*
* 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;
using SafeExamBrowser.Communication.Contracts.Data;
using SafeExamBrowser.Communication.Contracts.Proxies;
using SafeExamBrowser.Configuration.Contracts;
using SafeExamBrowser.Logging.Contracts;
namespace SafeExamBrowser.Communication.Proxies
{
/// <summary>
/// Default implementation of the <see cref="IServiceProxy"/>, to be used for communication with the service application component.
/// </summary>
public class ServiceProxy : BaseProxy, IServiceProxy
{
public ServiceProxy(string address, IProxyObjectFactory factory, ILogger logger, Interlocutor owner) : base(address, factory, logger, owner)
{
}
public CommunicationResult RunSystemConfigurationUpdate()
{
try
{
var response = Send(SimpleMessagePurport.UpdateSystemConfiguration);
var success = IsAcknowledged(response);
if (success)
{
Logger.Debug("Service acknowledged system configuration update.");
}
else
{
Logger.Error($"Service did not acknowledge system configuration update! Received: {ToString(response)}.");
}
return new CommunicationResult(success);
}
catch (Exception e)
{
Logger.Error($"Failed to perform '{nameof(RunSystemConfigurationUpdate)}'", e);
return new CommunicationResult(false);
}
}
public CommunicationResult StartSession(ServiceConfiguration configuration)
{
try
{
var response = Send(new SessionStartMessage(configuration));
var success = IsAcknowledged(response);
if (success)
{
Logger.Debug("Service acknowledged session start.");
}
else
{
Logger.Error($"Service did not acknowledge session start! Received: {ToString(response)}.");
}
return new CommunicationResult(success);
}
catch (Exception e)
{
Logger.Error($"Failed to perform '{nameof(StartSession)}'", e);
return new CommunicationResult(false);
}
}
public CommunicationResult StopSession(Guid sessionId)
{
try
{
var response = Send(new SessionStopMessage(sessionId));
var success = IsAcknowledged(response);
if (success)
{
Logger.Debug("Service acknowledged session stop.");
}
else
{
Logger.Error($"Service did not acknowledge session stop! Received: {ToString(response)}.");
}
return new CommunicationResult(success);
}
catch (Exception e)
{
Logger.Error($"Failed to perform '{nameof(StopSession)}'", e);
return new CommunicationResult(false);
}
}
}
}