Restore SEBPatch
This commit is contained in:
34
SafeExamBrowser.Browser/Handlers/ContextMenuHandler.cs
Normal file
34
SafeExamBrowser.Browser/Handlers/ContextMenuHandler.cs
Normal 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 CefSharp;
|
||||
|
||||
namespace SafeExamBrowser.Browser.Handlers
|
||||
{
|
||||
internal class ContextMenuHandler : IContextMenuHandler
|
||||
{
|
||||
public void OnBeforeContextMenu(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, IMenuModel model)
|
||||
{
|
||||
model.Clear();
|
||||
}
|
||||
|
||||
public bool OnContextMenuCommand(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, CefMenuCommand commandId, CefEventFlags eventFlags)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public void OnContextMenuDismissed(IWebBrowser browserControl, IBrowser browser, IFrame frame)
|
||||
{
|
||||
}
|
||||
|
||||
public bool RunContextMenu(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, IMenuModel model, IRunContextMenuCallback callback)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
51
SafeExamBrowser.Browser/Handlers/DialogHandler.cs
Normal file
51
SafeExamBrowser.Browser/Handlers/DialogHandler.cs
Normal file
@@ -0,0 +1,51 @@
|
||||
/*
|
||||
* 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.Threading.Tasks;
|
||||
using CefSharp;
|
||||
using SafeExamBrowser.Browser.Events;
|
||||
using SafeExamBrowser.Browser.Wrapper;
|
||||
|
||||
namespace SafeExamBrowser.Browser.Handlers
|
||||
{
|
||||
internal class DialogHandler : IDialogHandler
|
||||
{
|
||||
internal event DialogRequestedEventHandler DialogRequested;
|
||||
|
||||
public bool OnFileDialog(IWebBrowser webBrowser, IBrowser browser, CefFileDialogMode mode, string title, string defaultFilePath, List<string> acceptFilters, IFileDialogCallback callback)
|
||||
{
|
||||
var args = new DialogRequestedEventArgs
|
||||
{
|
||||
Element = mode.ToElement(),
|
||||
InitialPath = defaultFilePath,
|
||||
Operation = mode.ToOperation(),
|
||||
Title = title
|
||||
};
|
||||
|
||||
Task.Run(() =>
|
||||
{
|
||||
DialogRequested?.Invoke(args);
|
||||
|
||||
using (callback)
|
||||
{
|
||||
if (args.Success)
|
||||
{
|
||||
callback.Continue(new List<string> { args.FullPath });
|
||||
}
|
||||
else
|
||||
{
|
||||
callback.Cancel();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
73
SafeExamBrowser.Browser/Handlers/DisplayHandler.cs
Normal file
73
SafeExamBrowser.Browser/Handlers/DisplayHandler.cs
Normal file
@@ -0,0 +1,73 @@
|
||||
/*
|
||||
* 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 CefSharp;
|
||||
using CefSharp.Enums;
|
||||
using CefSharp.Structs;
|
||||
using SafeExamBrowser.Browser.Events;
|
||||
|
||||
namespace SafeExamBrowser.Browser.Handlers
|
||||
{
|
||||
internal class DisplayHandler : IDisplayHandler
|
||||
{
|
||||
public event FaviconChangedEventHandler FaviconChanged;
|
||||
public event ProgressChangedEventHandler ProgressChanged;
|
||||
|
||||
public void OnAddressChanged(IWebBrowser chromiumWebBrowser, AddressChangedEventArgs addressChangedArgs)
|
||||
{
|
||||
}
|
||||
|
||||
public bool OnAutoResize(IWebBrowser chromiumWebBrowser, IBrowser browser, Size newSize)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public bool OnConsoleMessage(IWebBrowser chromiumWebBrowser, ConsoleMessageEventArgs consoleMessageArgs)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public bool OnCursorChange(IWebBrowser chromiumWebBrowser, IBrowser browser, IntPtr cursor, CursorType type, CursorInfo customCursorInfo)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public void OnFaviconUrlChange(IWebBrowser chromiumWebBrowser, IBrowser browser, IList<string> urls)
|
||||
{
|
||||
if (urls.Any())
|
||||
{
|
||||
FaviconChanged?.Invoke(urls.First());
|
||||
}
|
||||
}
|
||||
|
||||
public void OnFullscreenModeChange(IWebBrowser chromiumWebBrowser, IBrowser browser, bool fullscreen)
|
||||
{
|
||||
}
|
||||
|
||||
public void OnLoadingProgressChange(IWebBrowser chromiumWebBrowser, IBrowser browser, double progress)
|
||||
{
|
||||
ProgressChanged?.Invoke(progress);
|
||||
}
|
||||
|
||||
public void OnStatusMessage(IWebBrowser chromiumWebBrowser, StatusMessageEventArgs statusMessageArgs)
|
||||
{
|
||||
}
|
||||
|
||||
public void OnTitleChanged(IWebBrowser chromiumWebBrowser, TitleChangedEventArgs titleChangedArgs)
|
||||
{
|
||||
}
|
||||
|
||||
public bool OnTooltipChanged(IWebBrowser chromiumWebBrowser, ref string text)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
210
SafeExamBrowser.Browser/Handlers/DownloadHandler.cs
Normal file
210
SafeExamBrowser.Browser/Handlers/DownloadHandler.cs
Normal file
@@ -0,0 +1,210 @@
|
||||
/*
|
||||
* 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.Concurrent;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using CefSharp;
|
||||
using SafeExamBrowser.Browser.Contracts.Events;
|
||||
using SafeExamBrowser.Browser.Events;
|
||||
using SafeExamBrowser.Configuration.Contracts;
|
||||
using SafeExamBrowser.Logging.Contracts;
|
||||
using SafeExamBrowser.Settings.Browser;
|
||||
using SafeExamBrowser.UserInterface.Contracts.Browser.Data;
|
||||
using Syroot.Windows.IO;
|
||||
using BrowserSettings = SafeExamBrowser.Settings.Browser.BrowserSettings;
|
||||
|
||||
namespace SafeExamBrowser.Browser.Handlers
|
||||
{
|
||||
internal class DownloadHandler : IDownloadHandler
|
||||
{
|
||||
private readonly AppConfig appConfig;
|
||||
private readonly ConcurrentDictionary<int, DownloadFinishedCallback> callbacks;
|
||||
private readonly ConcurrentDictionary<int, Guid> downloads;
|
||||
private readonly ILogger logger;
|
||||
private readonly BrowserSettings settings;
|
||||
private readonly WindowSettings windowSettings;
|
||||
|
||||
internal event DownloadRequestedEventHandler ConfigurationDownloadRequested;
|
||||
internal event DownloadAbortedEventHandler DownloadAborted;
|
||||
internal event DownloadUpdatedEventHandler DownloadUpdated;
|
||||
|
||||
internal DownloadHandler(AppConfig appConfig, ILogger logger, BrowserSettings settings, WindowSettings windowSettings)
|
||||
{
|
||||
this.appConfig = appConfig;
|
||||
this.callbacks = new ConcurrentDictionary<int, DownloadFinishedCallback>();
|
||||
this.downloads = new ConcurrentDictionary<int, Guid>();
|
||||
this.logger = logger;
|
||||
this.settings = settings;
|
||||
this.windowSettings = windowSettings;
|
||||
}
|
||||
|
||||
public bool CanDownload(IWebBrowser chromiumWebBrowser, IBrowser browser, string url, string requestMethod)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public void OnBeforeDownload(IWebBrowser webBrowser, IBrowser browser, DownloadItem downloadItem, IBeforeDownloadCallback callback)
|
||||
{
|
||||
var fileExtension = Path.GetExtension(downloadItem.SuggestedFileName);
|
||||
var isConfigurationFile = false;
|
||||
var url = downloadItem.Url;
|
||||
var urlExtension = default(string);
|
||||
|
||||
if (downloadItem.Url.StartsWith("data:"))
|
||||
{
|
||||
url = downloadItem.Url.Length <= 100 ? downloadItem.Url : downloadItem.Url.Substring(0, 100) + "...";
|
||||
}
|
||||
|
||||
if (Uri.TryCreate(downloadItem.Url, UriKind.RelativeOrAbsolute, out var uri))
|
||||
{
|
||||
urlExtension = Path.GetExtension(uri.AbsolutePath);
|
||||
}
|
||||
|
||||
isConfigurationFile |= string.Equals(appConfig.ConfigurationFileExtension, fileExtension, StringComparison.OrdinalIgnoreCase);
|
||||
isConfigurationFile |= string.Equals(appConfig.ConfigurationFileExtension, urlExtension, StringComparison.OrdinalIgnoreCase);
|
||||
isConfigurationFile |= string.Equals(appConfig.ConfigurationFileMimeType, downloadItem.MimeType, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
logger.Debug($"Detected download request{(windowSettings.UrlPolicy.CanLog() ? $" for '{url}'" : "")}.");
|
||||
|
||||
if (isConfigurationFile)
|
||||
{
|
||||
Task.Run(() => RequestConfigurationFileDownload(downloadItem, callback));
|
||||
}
|
||||
else if (settings.AllowDownloads)
|
||||
{
|
||||
Task.Run(() => HandleFileDownload(downloadItem, callback));
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.Info($"Aborted download request{(windowSettings.UrlPolicy.CanLog() ? $" for '{url}'" : "")}, as downloading is not allowed.");
|
||||
Task.Run(() => DownloadAborted?.Invoke());
|
||||
}
|
||||
}
|
||||
|
||||
public void OnDownloadUpdated(IWebBrowser webBrowser, IBrowser browser, DownloadItem downloadItem, IDownloadItemCallback callback)
|
||||
{
|
||||
var hasId = downloads.TryGetValue(downloadItem.Id, out var id);
|
||||
|
||||
if (hasId)
|
||||
{
|
||||
var state = new DownloadItemState(id)
|
||||
{
|
||||
Completion = downloadItem.PercentComplete / 100.0,
|
||||
FullPath = downloadItem.FullPath,
|
||||
IsCancelled = downloadItem.IsCancelled,
|
||||
IsComplete = downloadItem.IsComplete,
|
||||
Url = downloadItem.Url
|
||||
};
|
||||
|
||||
Task.Run(() => DownloadUpdated?.Invoke(state));
|
||||
}
|
||||
|
||||
if (downloadItem.IsComplete || downloadItem.IsCancelled)
|
||||
{
|
||||
logger.Debug($"Download of '{downloadItem.FullPath}' {(downloadItem.IsComplete ? "is complete" : "was cancelled")}.");
|
||||
|
||||
if (callbacks.TryRemove(downloadItem.Id, out var finished) && finished != null)
|
||||
{
|
||||
Task.Run(() => finished.Invoke(downloadItem.IsComplete, downloadItem.Url, downloadItem.FullPath));
|
||||
}
|
||||
|
||||
if (hasId)
|
||||
{
|
||||
downloads.TryRemove(downloadItem.Id, out _);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void HandleFileDownload(DownloadItem downloadItem, IBeforeDownloadCallback callback)
|
||||
{
|
||||
var filePath = default(string);
|
||||
var showDialog = settings.AllowCustomDownAndUploadLocation;
|
||||
|
||||
logger.Debug($"Handling download of file '{downloadItem.SuggestedFileName}'.");
|
||||
|
||||
if (!string.IsNullOrEmpty(settings.DownAndUploadDirectory))
|
||||
{
|
||||
filePath = Path.Combine(Environment.ExpandEnvironmentVariables(settings.DownAndUploadDirectory), downloadItem.SuggestedFileName);
|
||||
}
|
||||
else
|
||||
{
|
||||
filePath = Path.Combine(KnownFolders.Downloads.ExpandedPath, downloadItem.SuggestedFileName);
|
||||
}
|
||||
|
||||
if (File.Exists(filePath))
|
||||
{
|
||||
filePath = AppendIndexSuffixTo(filePath);
|
||||
}
|
||||
|
||||
if (showDialog)
|
||||
{
|
||||
logger.Debug($"Allowing user to select custom download location, with '{filePath}' as suggestion.");
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.Debug($"Automatically downloading file as '{filePath}'.");
|
||||
}
|
||||
|
||||
downloads[downloadItem.Id] = Guid.NewGuid();
|
||||
|
||||
using (callback)
|
||||
{
|
||||
callback.Continue(filePath, showDialog);
|
||||
}
|
||||
}
|
||||
|
||||
private string AppendIndexSuffixTo(string filePath)
|
||||
{
|
||||
var directory = Path.GetDirectoryName(filePath);
|
||||
var extension = Path.GetExtension(filePath);
|
||||
var name = Path.GetFileNameWithoutExtension(filePath);
|
||||
var path = default(string);
|
||||
|
||||
for (var suffix = 1; suffix < int.MaxValue; suffix++)
|
||||
{
|
||||
path = Path.Combine(directory, $"{name}({suffix}){extension}");
|
||||
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return path;
|
||||
}
|
||||
|
||||
private void RequestConfigurationFileDownload(DownloadItem downloadItem, IBeforeDownloadCallback callback)
|
||||
{
|
||||
var args = new DownloadEventArgs { Url = downloadItem.Url };
|
||||
|
||||
logger.Debug($"Handling download of configuration file '{downloadItem.SuggestedFileName}'.");
|
||||
ConfigurationDownloadRequested?.Invoke(downloadItem.SuggestedFileName, args);
|
||||
|
||||
if (args.AllowDownload)
|
||||
{
|
||||
if (args.Callback != null)
|
||||
{
|
||||
callbacks[downloadItem.Id] = args.Callback;
|
||||
}
|
||||
|
||||
logger.Debug($"Starting download of configuration file '{downloadItem.SuggestedFileName}'...");
|
||||
|
||||
using (callback)
|
||||
{
|
||||
callback.Continue(args.DownloadPath, false);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.Debug($"Download of configuration file '{downloadItem.SuggestedFileName}' was cancelled.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
93
SafeExamBrowser.Browser/Handlers/KeyboardHandler.cs
Normal file
93
SafeExamBrowser.Browser/Handlers/KeyboardHandler.cs
Normal file
@@ -0,0 +1,93 @@
|
||||
/*
|
||||
* 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.Windows.Forms;
|
||||
using CefSharp;
|
||||
using SafeExamBrowser.Browser.Contracts.Events;
|
||||
using SafeExamBrowser.UserInterface.Contracts;
|
||||
|
||||
namespace SafeExamBrowser.Browser.Handlers
|
||||
{
|
||||
internal class KeyboardHandler : IKeyboardHandler
|
||||
{
|
||||
internal event ActionRequestedEventHandler FindRequested;
|
||||
internal event ActionRequestedEventHandler HomeNavigationRequested;
|
||||
internal event ActionRequestedEventHandler ReloadRequested;
|
||||
internal event ActionRequestedEventHandler ZoomInRequested;
|
||||
internal event ActionRequestedEventHandler ZoomOutRequested;
|
||||
internal event ActionRequestedEventHandler ZoomResetRequested;
|
||||
internal event ActionRequestedEventHandler FocusAddressBarRequested;
|
||||
internal event TabPressedEventHandler TabPressed;
|
||||
|
||||
private int? currentKeyDown = null;
|
||||
|
||||
public bool OnKeyEvent(IWebBrowser browserControl, IBrowser browser, KeyType type, int keyCode, int nativeKeyCode, CefEventFlags modifiers, bool isSystemKey)
|
||||
{
|
||||
var ctrl = modifiers.HasFlag(CefEventFlags.ControlDown);
|
||||
var shift = modifiers.HasFlag(CefEventFlags.ShiftDown);
|
||||
|
||||
if (type == KeyType.KeyUp)
|
||||
{
|
||||
if (ctrl && keyCode == (int) Keys.F)
|
||||
{
|
||||
FindRequested?.Invoke();
|
||||
}
|
||||
|
||||
if (keyCode == (int) Keys.Home)
|
||||
{
|
||||
HomeNavigationRequested?.Invoke();
|
||||
}
|
||||
|
||||
if (ctrl && keyCode == (int) Keys.L)
|
||||
{
|
||||
FocusAddressBarRequested?.Invoke();
|
||||
}
|
||||
|
||||
if ((ctrl && keyCode == (int) Keys.Add) || (ctrl && keyCode == (int) Keys.Oemplus) || (ctrl && shift && keyCode == (int) Keys.D1))
|
||||
{
|
||||
ZoomInRequested?.Invoke();
|
||||
}
|
||||
|
||||
if (ctrl && (keyCode == (int) Keys.Subtract || keyCode == (int) Keys.OemMinus))
|
||||
{
|
||||
ZoomOutRequested?.Invoke();
|
||||
}
|
||||
|
||||
if (ctrl && (keyCode == (int) Keys.D0 || keyCode == (int) Keys.NumPad0))
|
||||
{
|
||||
ZoomResetRequested?.Invoke();
|
||||
}
|
||||
|
||||
if (keyCode == (int) Keys.Tab && keyCode == currentKeyDown)
|
||||
{
|
||||
TabPressed?.Invoke(shift);
|
||||
}
|
||||
}
|
||||
|
||||
currentKeyDown = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
public bool OnPreKeyEvent(IWebBrowser browserControl, IBrowser browser, KeyType type, int keyCode, int nativeKeyCode, CefEventFlags modifiers, bool isSystemKey, ref bool isKeyboardShortcut)
|
||||
{
|
||||
if (type == KeyType.KeyUp && keyCode == (int) Keys.F5)
|
||||
{
|
||||
ReloadRequested?.Invoke();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
if (type == KeyType.RawKeyDown || type == KeyType.KeyDown)
|
||||
{
|
||||
currentKeyDown = keyCode;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
@@ -0,0 +1,80 @@
|
||||
/*
|
||||
* 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 CefSharp;
|
||||
using SafeExamBrowser.Browser.Content;
|
||||
using SafeExamBrowser.Configuration.Contracts;
|
||||
using SafeExamBrowser.Configuration.Contracts.Cryptography;
|
||||
using SafeExamBrowser.I18n.Contracts;
|
||||
using BrowserSettings = SafeExamBrowser.Settings.Browser.BrowserSettings;
|
||||
|
||||
namespace SafeExamBrowser.Browser.Handlers
|
||||
{
|
||||
internal class RenderProcessMessageHandler : IRenderProcessMessageHandler
|
||||
{
|
||||
private readonly AppConfig appConfig;
|
||||
private readonly Clipboard clipboard;
|
||||
private readonly ContentLoader contentLoader;
|
||||
private readonly IKeyGenerator keyGenerator;
|
||||
private readonly BrowserSettings settings;
|
||||
private readonly IText text;
|
||||
|
||||
internal RenderProcessMessageHandler(AppConfig appConfig, Clipboard clipboard, IKeyGenerator keyGenerator, BrowserSettings settings, IText text)
|
||||
{
|
||||
this.appConfig = appConfig;
|
||||
this.clipboard = clipboard;
|
||||
this.contentLoader = new ContentLoader(text);
|
||||
this.keyGenerator = keyGenerator;
|
||||
this.settings = settings;
|
||||
this.text = text;
|
||||
}
|
||||
|
||||
public void OnContextCreated(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame)
|
||||
{
|
||||
var browserExamKey = keyGenerator.CalculateBrowserExamKeyHash(settings.ConfigurationKey, settings.BrowserExamKeySalt, frame.Url);
|
||||
var configurationKey = keyGenerator.CalculateConfigurationKeyHash(settings.ConfigurationKey, frame.Url);
|
||||
var api = contentLoader.LoadApi(browserExamKey, configurationKey, appConfig.ProgramBuildVersion);
|
||||
var clipboardScript = contentLoader.LoadClipboard();
|
||||
var pageZoomScript = contentLoader.LoadPageZoom();
|
||||
|
||||
frame.ExecuteJavaScriptAsync(api);
|
||||
|
||||
if (!settings.AllowPageZoom)
|
||||
{
|
||||
frame.ExecuteJavaScriptAsync(pageZoomScript);
|
||||
}
|
||||
|
||||
if (!settings.AllowPrint)
|
||||
{
|
||||
frame.ExecuteJavaScriptAsync($"window.print = function() {{ alert('{text.Get(TextKey.Browser_PrintNotAllowed)}') }}");
|
||||
}
|
||||
|
||||
if (settings.UseIsolatedClipboard)
|
||||
{
|
||||
frame.ExecuteJavaScriptAsync(clipboardScript);
|
||||
|
||||
if (clipboard.Content != default)
|
||||
{
|
||||
frame.ExecuteJavaScriptAsync($"SafeExamBrowser.clipboard.update('', '{clipboard.Content}');");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void OnContextReleased(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame)
|
||||
{
|
||||
}
|
||||
|
||||
public void OnFocusedNodeChanged(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IDomNode node)
|
||||
{
|
||||
}
|
||||
|
||||
public void OnUncaughtException(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, JavascriptException exception)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
220
SafeExamBrowser.Browser/Handlers/RequestHandler.cs
Normal file
220
SafeExamBrowser.Browser/Handlers/RequestHandler.cs
Normal file
@@ -0,0 +1,220 @@
|
||||
/*
|
||||
* 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 System.Net;
|
||||
using System.Text.RegularExpressions;
|
||||
using CefSharp;
|
||||
using SafeExamBrowser.Browser.Contracts.Filters;
|
||||
using SafeExamBrowser.Browser.Events;
|
||||
using SafeExamBrowser.Configuration.Contracts;
|
||||
using SafeExamBrowser.Logging.Contracts;
|
||||
using SafeExamBrowser.Settings.Browser;
|
||||
using SafeExamBrowser.Settings.Browser.Filter;
|
||||
using BrowserSettings = SafeExamBrowser.Settings.Browser.BrowserSettings;
|
||||
using Request = SafeExamBrowser.Browser.Contracts.Filters.Request;
|
||||
|
||||
namespace SafeExamBrowser.Browser.Handlers
|
||||
{
|
||||
internal class RequestHandler : CefSharp.Handler.RequestHandler
|
||||
{
|
||||
private readonly AppConfig appConfig;
|
||||
private readonly IRequestFilter filter;
|
||||
private readonly ILogger logger;
|
||||
private readonly ResourceHandler resourceHandler;
|
||||
private readonly WindowSettings windowSettings;
|
||||
private readonly BrowserSettings settings;
|
||||
|
||||
private string quitUrlPattern;
|
||||
|
||||
internal event UrlEventHandler QuitUrlVisited;
|
||||
internal event UrlEventHandler RequestBlocked;
|
||||
|
||||
internal RequestHandler(
|
||||
AppConfig appConfig,
|
||||
IRequestFilter filter,
|
||||
ILogger logger,
|
||||
ResourceHandler resourceHandler,
|
||||
BrowserSettings settings,
|
||||
WindowSettings windowSettings)
|
||||
{
|
||||
this.appConfig = appConfig;
|
||||
this.filter = filter;
|
||||
this.logger = logger;
|
||||
this.resourceHandler = resourceHandler;
|
||||
this.settings = settings;
|
||||
this.windowSettings = windowSettings;
|
||||
}
|
||||
|
||||
protected override bool GetAuthCredentials(IWebBrowser webBrowser, IBrowser browser, string originUrl, bool isProxy, string host, int port, string realm, string scheme, IAuthCallback callback)
|
||||
{
|
||||
if (isProxy)
|
||||
{
|
||||
foreach (var proxy in settings.Proxy.Proxies)
|
||||
{
|
||||
if (proxy.RequiresAuthentication && host?.Equals(proxy.Host, StringComparison.OrdinalIgnoreCase) == true && port == proxy.Port)
|
||||
{
|
||||
callback.Continue(proxy.Username, proxy.Password);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return base.GetAuthCredentials(webBrowser, browser, originUrl, isProxy, host, port, realm, scheme, callback);
|
||||
}
|
||||
|
||||
protected override IResourceRequestHandler GetResourceRequestHandler(IWebBrowser webBrowser, IBrowser browser, IFrame frame, IRequest request, bool isNavigation, bool isDownload, string requestInitiator, ref bool disableDefaultHandling)
|
||||
{
|
||||
return resourceHandler;
|
||||
}
|
||||
|
||||
protected override bool OnBeforeBrowse(IWebBrowser webBrowser, IBrowser browser, IFrame frame, IRequest request, bool userGesture, bool isRedirect)
|
||||
{
|
||||
if (IsQuitUrl(request))
|
||||
{
|
||||
QuitUrlVisited?.Invoke(request.Url);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
if (Block(request))
|
||||
{
|
||||
if (request.ResourceType == ResourceType.MainFrame)
|
||||
{
|
||||
RequestBlocked?.Invoke(request.Url);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
if (IsConfigurationFile(request, out var downloadUrl))
|
||||
{
|
||||
browser.GetHost().StartDownload(downloadUrl);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return base.OnBeforeBrowse(webBrowser, browser, frame, request, userGesture, isRedirect);
|
||||
}
|
||||
|
||||
protected override bool OnOpenUrlFromTab(IWebBrowser webBrowser, IBrowser browser, IFrame frame, string targetUrl, WindowOpenDisposition targetDisposition, bool userGesture)
|
||||
{
|
||||
switch (targetDisposition)
|
||||
{
|
||||
case WindowOpenDisposition.NewBackgroundTab:
|
||||
case WindowOpenDisposition.NewPopup:
|
||||
case WindowOpenDisposition.NewWindow:
|
||||
case WindowOpenDisposition.SaveToDisk:
|
||||
return true;
|
||||
default:
|
||||
return base.OnOpenUrlFromTab(webBrowser, browser, frame, targetUrl, targetDisposition, userGesture);
|
||||
}
|
||||
}
|
||||
|
||||
private bool IsConfigurationFile(IRequest request, out string downloadUrl)
|
||||
{
|
||||
var isValidUri = Uri.TryCreate(request.Url, UriKind.RelativeOrAbsolute, out var uri);
|
||||
var hasFileExtension = string.Equals(appConfig.ConfigurationFileExtension, Path.GetExtension(uri.AbsolutePath), StringComparison.OrdinalIgnoreCase);
|
||||
var isDataUri = request.Url.Contains(appConfig.ConfigurationFileMimeType);
|
||||
var isConfigurationFile = isValidUri && (hasFileExtension || isDataUri);
|
||||
|
||||
downloadUrl = request.Url;
|
||||
|
||||
if (isConfigurationFile)
|
||||
{
|
||||
if (isDataUri)
|
||||
{
|
||||
if (uri.Scheme == appConfig.SebUriScheme)
|
||||
{
|
||||
downloadUrl = request.Url.Replace($"{appConfig.SebUriScheme}{Uri.SchemeDelimiter}", "data:");
|
||||
}
|
||||
else if (uri.Scheme == appConfig.SebUriSchemeSecure)
|
||||
{
|
||||
downloadUrl = request.Url.Replace($"{appConfig.SebUriSchemeSecure}{Uri.SchemeDelimiter}", "data:");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (uri.Scheme == appConfig.SebUriScheme)
|
||||
{
|
||||
downloadUrl = new UriBuilder(uri) { Scheme = Uri.UriSchemeHttp }.Uri.AbsoluteUri;
|
||||
}
|
||||
else if (uri.Scheme == appConfig.SebUriSchemeSecure)
|
||||
{
|
||||
downloadUrl = new UriBuilder(uri) { Scheme = Uri.UriSchemeHttps }.Uri.AbsoluteUri;
|
||||
}
|
||||
}
|
||||
|
||||
logger.Debug($"Detected configuration file {(windowSettings.UrlPolicy.CanLog() ? $"'{uri}'" : "")}.");
|
||||
}
|
||||
|
||||
return isConfigurationFile;
|
||||
}
|
||||
|
||||
private bool IsQuitUrl(IRequest request)
|
||||
{
|
||||
var isQuitUrl = false;
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(settings.QuitUrl))
|
||||
{
|
||||
if (quitUrlPattern == default)
|
||||
{
|
||||
quitUrlPattern = $"^{Regex.Escape(settings.QuitUrl.TrimEnd('/'))}/?$";
|
||||
}
|
||||
|
||||
isQuitUrl = Regex.IsMatch(request.Url, quitUrlPattern, RegexOptions.IgnoreCase);
|
||||
|
||||
if (isQuitUrl)
|
||||
{
|
||||
logger.Debug($"Detected quit URL{(windowSettings.UrlPolicy.CanLog() ? $"'{request.Url}'" : "")}.");
|
||||
}
|
||||
}
|
||||
|
||||
return isQuitUrl;
|
||||
}
|
||||
|
||||
private bool Block(IRequest request)
|
||||
{
|
||||
var block = false;
|
||||
var url = WebUtility.UrlDecode(request.Url);
|
||||
var isValidUrl = Uri.TryCreate(url, UriKind.Absolute, out _);
|
||||
|
||||
if (settings.Filter.ProcessMainRequests && request.ResourceType == ResourceType.MainFrame && isValidUrl)
|
||||
{
|
||||
var result = filter.Process(new Request { Url = url });
|
||||
|
||||
// We apparently can't filter chrome extension requests, as this prevents the rendering of PDFs.
|
||||
if (result == FilterResult.Block && !url.StartsWith("chrome-extension://"))
|
||||
{
|
||||
block = true;
|
||||
logger.Info($"Blocked main request{(windowSettings.UrlPolicy.CanLog() ? $" for '{url}'" : "")} ({request.ResourceType}, {request.TransitionType}).");
|
||||
}
|
||||
}
|
||||
|
||||
if (settings.Filter.ProcessContentRequests && request.ResourceType != ResourceType.MainFrame && isValidUrl)
|
||||
{
|
||||
var result = filter.Process(new Request { Url = url });
|
||||
|
||||
if (result == FilterResult.Block)
|
||||
{
|
||||
block = true;
|
||||
logger.Info($"Blocked content request{(windowSettings.UrlPolicy.CanLog() ? $" for '{url}'" : "")} ({request.ResourceType}, {request.TransitionType}).");
|
||||
}
|
||||
}
|
||||
|
||||
if (!isValidUrl)
|
||||
{
|
||||
logger.Warn($"Filter could not process request{(windowSettings.UrlPolicy.CanLog() ? $" for '{url}'" : "")} ({request.ResourceType}, {request.TransitionType})!");
|
||||
}
|
||||
|
||||
return block;
|
||||
}
|
||||
}
|
||||
}
|
451
SafeExamBrowser.Browser/Handlers/ResourceHandler.cs
Normal file
451
SafeExamBrowser.Browser/Handlers/ResourceHandler.cs
Normal file
@@ -0,0 +1,451 @@
|
||||
/*
|
||||
* 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.Specialized;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Mime;
|
||||
using System.Threading.Tasks;
|
||||
using CefSharp;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using SafeExamBrowser.Browser.Content;
|
||||
using SafeExamBrowser.Browser.Contracts.Events;
|
||||
using SafeExamBrowser.Browser.Contracts.Filters;
|
||||
using SafeExamBrowser.Configuration.Contracts;
|
||||
using SafeExamBrowser.Configuration.Contracts.Cryptography;
|
||||
using SafeExamBrowser.I18n.Contracts;
|
||||
using SafeExamBrowser.Logging.Contracts;
|
||||
using SafeExamBrowser.Settings;
|
||||
using SafeExamBrowser.Settings.Browser;
|
||||
using SafeExamBrowser.Settings.Browser.Filter;
|
||||
using BrowserSettings = SafeExamBrowser.Settings.Browser.BrowserSettings;
|
||||
using Request = SafeExamBrowser.Browser.Contracts.Filters.Request;
|
||||
|
||||
namespace SafeExamBrowser.Browser.Handlers
|
||||
{
|
||||
internal class ResourceHandler : CefSharp.Handler.ResourceRequestHandler
|
||||
{
|
||||
private readonly AppConfig appConfig;
|
||||
private readonly ContentLoader contentLoader;
|
||||
private readonly IRequestFilter filter;
|
||||
private readonly IKeyGenerator keyGenerator;
|
||||
private readonly ILogger logger;
|
||||
private readonly SessionMode sessionMode;
|
||||
private readonly BrowserSettings settings;
|
||||
private readonly WindowSettings windowSettings;
|
||||
|
||||
private IResourceHandler contentHandler;
|
||||
private IResourceHandler pageHandler;
|
||||
private string userIdentifier;
|
||||
|
||||
internal event UserIdentifierDetectedEventHandler UserIdentifierDetected;
|
||||
|
||||
internal ResourceHandler(
|
||||
AppConfig appConfig,
|
||||
IRequestFilter filter,
|
||||
IKeyGenerator keyGenerator,
|
||||
ILogger logger,
|
||||
SessionMode sessionMode,
|
||||
BrowserSettings settings,
|
||||
WindowSettings windowSettings,
|
||||
IText text)
|
||||
{
|
||||
this.appConfig = appConfig;
|
||||
this.filter = filter;
|
||||
this.contentLoader = new ContentLoader(text);
|
||||
this.keyGenerator = keyGenerator;
|
||||
this.logger = logger;
|
||||
this.sessionMode = sessionMode;
|
||||
this.settings = settings;
|
||||
this.windowSettings = windowSettings;
|
||||
}
|
||||
|
||||
protected override IResourceHandler GetResourceHandler(IWebBrowser webBrowser, IBrowser browser, IFrame frame, IRequest request)
|
||||
{
|
||||
if (Block(request))
|
||||
{
|
||||
return ResourceHandlerFor(request.ResourceType);
|
||||
}
|
||||
|
||||
return base.GetResourceHandler(webBrowser, browser, frame, request);
|
||||
}
|
||||
|
||||
protected override CefReturnValue OnBeforeResourceLoad(IWebBrowser webBrowser, IBrowser browser, IFrame frame, IRequest request, IRequestCallback callback)
|
||||
{
|
||||
if (IsMailtoUrl(request.Url))
|
||||
{
|
||||
return CefReturnValue.Cancel;
|
||||
}
|
||||
|
||||
AppendCustomHeaders(webBrowser, request);
|
||||
ReplaceSebScheme(request);
|
||||
|
||||
return base.OnBeforeResourceLoad(webBrowser, browser, frame, request, callback);
|
||||
}
|
||||
|
||||
protected override bool OnProtocolExecution(IWebBrowser webBrowser, IBrowser browser, IFrame frame, IRequest request)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
protected override void OnResourceRedirect(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, IResponse response, ref string newUrl)
|
||||
{
|
||||
if (sessionMode == SessionMode.Server)
|
||||
{
|
||||
SearchUserIdentifier(request, response);
|
||||
}
|
||||
|
||||
base.OnResourceRedirect(chromiumWebBrowser, browser, frame, request, response, ref newUrl);
|
||||
}
|
||||
|
||||
protected override bool OnResourceResponse(IWebBrowser webBrowser, IBrowser browser, IFrame frame, IRequest request, IResponse response)
|
||||
{
|
||||
if (RedirectToDisablePdfReaderToolbar(request, response, out var url))
|
||||
{
|
||||
frame?.LoadUrl(url);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
if (sessionMode == SessionMode.Server)
|
||||
{
|
||||
SearchUserIdentifier(request, response);
|
||||
}
|
||||
|
||||
return base.OnResourceResponse(webBrowser, browser, frame, request, response);
|
||||
}
|
||||
|
||||
private void AppendCustomHeaders(IWebBrowser webBrowser, IRequest request)
|
||||
{
|
||||
Uri.TryCreate(webBrowser.Address, UriKind.Absolute, out var pageUrl);
|
||||
Uri.TryCreate(request.Url, UriKind.Absolute, out var requestUrl);
|
||||
|
||||
if (request.ResourceType == ResourceType.MainFrame || pageUrl?.Host?.Equals(requestUrl?.Host) == true)
|
||||
{
|
||||
var headers = new NameValueCollection(request.Headers);
|
||||
|
||||
if (settings.SendConfigurationKey)
|
||||
{
|
||||
headers["X-SafeExamBrowser-ConfigKeyHash"] = keyGenerator.CalculateConfigurationKeyHash(settings.ConfigurationKey, request.Url);
|
||||
}
|
||||
|
||||
if (settings.SendBrowserExamKey)
|
||||
{
|
||||
headers["X-SafeExamBrowser-RequestHash"] = keyGenerator.CalculateBrowserExamKeyHash(settings.ConfigurationKey, settings.BrowserExamKeySalt, request.Url);
|
||||
}
|
||||
|
||||
request.Headers = headers;
|
||||
}
|
||||
}
|
||||
|
||||
private bool Block(IRequest request)
|
||||
{
|
||||
var block = false;
|
||||
var url = WebUtility.UrlDecode(request.Url);
|
||||
var isValidUri = Uri.TryCreate(url, UriKind.Absolute, out _);
|
||||
|
||||
if (settings.Filter.ProcessContentRequests && isValidUri)
|
||||
{
|
||||
var result = filter.Process(new Request { Url = url });
|
||||
|
||||
if (result == FilterResult.Block)
|
||||
{
|
||||
block = true;
|
||||
logger.Info($"Blocked content request{(windowSettings.UrlPolicy.CanLog() ? $" for '{url}'" : "")} ({request.ResourceType}, {request.TransitionType}).");
|
||||
}
|
||||
}
|
||||
else if (!isValidUri)
|
||||
{
|
||||
logger.Warn($"Filter could not process request{(windowSettings.UrlPolicy.CanLog() ? $" for '{url}'" : "")} ({request.ResourceType}, {request.TransitionType})!");
|
||||
}
|
||||
|
||||
return block;
|
||||
}
|
||||
|
||||
private bool IsMailtoUrl(string url)
|
||||
{
|
||||
return url.StartsWith(Uri.UriSchemeMailto);
|
||||
}
|
||||
|
||||
private bool RedirectToDisablePdfReaderToolbar(IRequest request, IResponse response, out string url)
|
||||
{
|
||||
const string DISABLE_PDF_READER_TOOLBAR = "#toolbar=0";
|
||||
|
||||
var isPdf = response.Headers["Content-Type"] == MediaTypeNames.Application.Pdf;
|
||||
var isMainFrame = request.ResourceType == ResourceType.MainFrame;
|
||||
var hasFragment = request.Url.Contains(DISABLE_PDF_READER_TOOLBAR);
|
||||
var redirect = settings.AllowPdfReader && !settings.AllowPdfReaderToolbar && isPdf && isMainFrame && !hasFragment;
|
||||
|
||||
url = request.Url + DISABLE_PDF_READER_TOOLBAR;
|
||||
|
||||
if (redirect)
|
||||
{
|
||||
logger.Info($"Redirecting{(windowSettings.UrlPolicy.CanLog() ? $" to '{url}'" : "")} to disable PDF reader toolbar.");
|
||||
}
|
||||
|
||||
return redirect;
|
||||
}
|
||||
|
||||
private void ReplaceSebScheme(IRequest request)
|
||||
{
|
||||
if (Uri.IsWellFormedUriString(request.Url, UriKind.RelativeOrAbsolute))
|
||||
{
|
||||
var uri = new Uri(request.Url);
|
||||
|
||||
if (uri.Scheme == appConfig.SebUriScheme)
|
||||
{
|
||||
request.Url = new UriBuilder(uri) { Scheme = Uri.UriSchemeHttp }.Uri.AbsoluteUri;
|
||||
}
|
||||
else if (uri.Scheme == appConfig.SebUriSchemeSecure)
|
||||
{
|
||||
request.Url = new UriBuilder(uri) { Scheme = Uri.UriSchemeHttps }.Uri.AbsoluteUri;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private IResourceHandler ResourceHandlerFor(ResourceType resourceType)
|
||||
{
|
||||
if (contentHandler == default(IResourceHandler))
|
||||
{
|
||||
contentHandler = CefSharp.ResourceHandler.FromString(contentLoader.LoadBlockedContent());
|
||||
}
|
||||
|
||||
if (pageHandler == default(IResourceHandler))
|
||||
{
|
||||
pageHandler = CefSharp.ResourceHandler.FromString(contentLoader.LoadBlockedPage());
|
||||
}
|
||||
|
||||
switch (resourceType)
|
||||
{
|
||||
case ResourceType.MainFrame:
|
||||
case ResourceType.SubFrame:
|
||||
return pageHandler;
|
||||
default:
|
||||
return contentHandler;
|
||||
}
|
||||
}
|
||||
|
||||
private void SearchUserIdentifier(IRequest request, IResponse response)
|
||||
{
|
||||
var success = TrySearchGenericUserIdentifier(response);
|
||||
|
||||
if (!success)
|
||||
{
|
||||
success = TrySearchEdxUserIdentifier(response);
|
||||
}
|
||||
|
||||
if (!success)
|
||||
{
|
||||
TrySearchMoodleUserIdentifier(request, response);
|
||||
}
|
||||
}
|
||||
|
||||
private bool TrySearchGenericUserIdentifier(IResponse response)
|
||||
{
|
||||
var ids = response.Headers.GetValues("X-LMS-USER-ID");
|
||||
var success = false;
|
||||
|
||||
if (ids != default(string[]))
|
||||
{
|
||||
var userId = ids.FirstOrDefault();
|
||||
|
||||
if (userId != default && userIdentifier != userId)
|
||||
{
|
||||
userIdentifier = userId;
|
||||
Task.Run(() => UserIdentifierDetected?.Invoke(userIdentifier));
|
||||
logger.Info("Generic LMS user identifier detected.");
|
||||
success = true;
|
||||
}
|
||||
}
|
||||
|
||||
return success;
|
||||
}
|
||||
|
||||
private bool TrySearchEdxUserIdentifier(IResponse response)
|
||||
{
|
||||
var cookies = response.Headers.GetValues("Set-Cookie");
|
||||
var success = false;
|
||||
|
||||
if (cookies != default(string[]))
|
||||
{
|
||||
try
|
||||
{
|
||||
var userInfo = cookies.FirstOrDefault(c => c.Contains("edx-user-info"));
|
||||
|
||||
if (userInfo != default)
|
||||
{
|
||||
var start = userInfo.IndexOf("=") + 1;
|
||||
var end = userInfo.IndexOf("; expires");
|
||||
var cookie = userInfo.Substring(start, end - start);
|
||||
var sanitized = cookie.Replace("\\\"", "\"").Replace("\\054", ",").Trim('"');
|
||||
var json = JsonConvert.DeserializeObject(sanitized) as JObject;
|
||||
var userName = json["username"].Value<string>();
|
||||
|
||||
if (userIdentifier != userName)
|
||||
{
|
||||
userIdentifier = userName;
|
||||
Task.Run(() => UserIdentifierDetected?.Invoke(userIdentifier));
|
||||
logger.Info("EdX user identifier detected.");
|
||||
success = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
logger.Error("Failed to parse edX user identifier!", e);
|
||||
}
|
||||
}
|
||||
|
||||
return success;
|
||||
}
|
||||
|
||||
private bool TrySearchMoodleUserIdentifier(IRequest request, IResponse response)
|
||||
{
|
||||
var success = TrySearchMoodleUserIdentifierByLocation(response);
|
||||
|
||||
if (!success)
|
||||
{
|
||||
success = TrySearchMoodleUserIdentifierByRequest(MoodleRequestType.Plugin, request, response);
|
||||
}
|
||||
|
||||
if (!success)
|
||||
{
|
||||
success = TrySearchMoodleUserIdentifierByRequest(MoodleRequestType.Theme, request, response);
|
||||
}
|
||||
|
||||
return success;
|
||||
}
|
||||
|
||||
private bool TrySearchMoodleUserIdentifierByLocation(IResponse response)
|
||||
{
|
||||
var locations = response.Headers.GetValues("Location");
|
||||
|
||||
if (locations != default(string[]))
|
||||
{
|
||||
try
|
||||
{
|
||||
var location = locations.FirstOrDefault(l => l.Contains("/login/index.php?testsession"));
|
||||
|
||||
if (location != default)
|
||||
{
|
||||
var userId = location.Substring(location.IndexOf("=") + 1);
|
||||
|
||||
if (userIdentifier != userId)
|
||||
{
|
||||
userIdentifier = userId;
|
||||
Task.Run(() => UserIdentifierDetected?.Invoke(userIdentifier));
|
||||
logger.Info("Moodle user identifier detected by location.");
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
logger.Error("Failed to parse Moodle user identifier by location!", e);
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private bool TrySearchMoodleUserIdentifierByRequest(MoodleRequestType type, IRequest request, IResponse response)
|
||||
{
|
||||
var cookies = response.Headers.GetValues("Set-Cookie");
|
||||
var success = false;
|
||||
|
||||
if (cookies != default(string[]))
|
||||
{
|
||||
var session = cookies.FirstOrDefault(c => c.Contains("MoodleSession"));
|
||||
|
||||
if (session != default)
|
||||
{
|
||||
var userId = ExecuteMoodleUserIdentifierRequest(request.Url, session, type);
|
||||
|
||||
if (int.TryParse(userId, out var id) && id > 0 && userIdentifier != userId)
|
||||
{
|
||||
userIdentifier = userId;
|
||||
Task.Run(() => UserIdentifierDetected?.Invoke(userIdentifier));
|
||||
logger.Info($"Moodle user identifier detected by request ({type}).");
|
||||
success = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return success;
|
||||
}
|
||||
|
||||
private string ExecuteMoodleUserIdentifierRequest(string requestUrl, string session, MoodleRequestType type)
|
||||
{
|
||||
var userId = default(string);
|
||||
|
||||
try
|
||||
{
|
||||
Task.Run(async () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
var endpointUrl = default(string);
|
||||
var start = session.IndexOf("=") + 1;
|
||||
var end = session.IndexOf(";");
|
||||
var name = session.Substring(0, start - 1);
|
||||
var value = session.Substring(start, end - start);
|
||||
var uri = new Uri(requestUrl);
|
||||
|
||||
if (type == MoodleRequestType.Plugin)
|
||||
{
|
||||
endpointUrl = $"{uri.Scheme}{Uri.SchemeDelimiter}{uri.Host}/mod/quiz/accessrule/sebserver/classes/external/user.php";
|
||||
}
|
||||
else
|
||||
{
|
||||
endpointUrl = $"{uri.Scheme}{Uri.SchemeDelimiter}{uri.Host}/theme/boost_ethz/sebuser.php";
|
||||
}
|
||||
|
||||
var message = new HttpRequestMessage(HttpMethod.Get, endpointUrl);
|
||||
|
||||
using (var handler = new HttpClientHandler { UseCookies = false })
|
||||
using (var client = new HttpClient(handler))
|
||||
{
|
||||
message.Headers.Add("Cookie", $"{name}={value}");
|
||||
|
||||
var result = await client.SendAsync(message);
|
||||
|
||||
if (result.IsSuccessStatusCode)
|
||||
{
|
||||
userId = await result.Content.ReadAsStringAsync();
|
||||
}
|
||||
else if (result.StatusCode != HttpStatusCode.NotFound)
|
||||
{
|
||||
logger.Error($"Failed to retrieve Moodle user identifier by request ({type})! Response: {(int) result.StatusCode} {result.ReasonPhrase}");
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
logger.Error($"Failed to parse Moodle user identifier by request ({type})!", e);
|
||||
}
|
||||
}).GetAwaiter().GetResult();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
logger.Error($"Failed to execute Moodle user identifier request ({type})!", e);
|
||||
}
|
||||
|
||||
return userId;
|
||||
}
|
||||
|
||||
private enum MoodleRequestType
|
||||
{
|
||||
Plugin,
|
||||
Theme
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user