Skip to content

Commit

Permalink
Add WebServer Support
Browse files Browse the repository at this point in the history
  • Loading branch information
mantikafasi committed Jun 12, 2023
1 parent 53d03d2 commit 0fd0077
Show file tree
Hide file tree
Showing 12 changed files with 153 additions and 28 deletions.
3 changes: 3 additions & 0 deletions Common/Config.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,8 @@ public class Config

[DataMember(Name = "startLocked")] public bool StartLocked { get; set; }
[DataMember(Name = "enableBlur")] public bool BlurBackground { get; set; }
[DataMember(Name="enableWebServer")] public bool EnableWebServer { get; set;}
[DataMember (Name="webServerPassword")] public string WebServerPassword { get; set; }
[DataMember (Name="debug")] public bool Debug { get; set; } // this is only used to disable keyhook for testing
}
}
18 changes: 15 additions & 3 deletions MLock/App.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Security.Principal;
using System.Windows;
using System.Windows.Forms;
using Common;
using MessageBox = System.Windows.MessageBox;

namespace MLock
{
Expand All @@ -14,6 +17,14 @@ public partial class App

public App()
{
var isAdmin = new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator);
if (!isAdmin)
{
MessageBox.Show("Please run MLock as administrator", "Admin Privileges Required", MessageBoxButton.OK,
MessageBoxImage.Warning);
Environment.Exit(0);
}

if (!ParseConfig()) Environment.Exit(0);

InitializeComponent();
Expand Down Expand Up @@ -54,7 +65,7 @@ public bool ParseConfig()
{
if (!File.Exists(MLOCK_DIR + "\\publicKey.xml"))
{
System.Windows.MessageBox.Show(
MessageBox.Show(
"Public Key for USB Locking not found, please run the USB key generator and config installer first");
return false;
}
Expand All @@ -65,11 +76,12 @@ public bool ParseConfig()
if (Config.INSTANCE.EnablePasswordUnlocking &&
(Config.INSTANCE.Password == null || Config.INSTANCE.Password.Trim() == ""))
{
System.Windows.MessageBox.Show("Password not set, please run the config installer first");
MessageBox.Show("Password not set, please run the config installer first");
return false;
}

if (!Config.INSTANCE.EnablePasswordUnlocking && !Config.INSTANCE.EnableUSBUnlocking)
if (!Config.INSTANCE.EnablePasswordUnlocking && !Config.INSTANCE.EnableUSBUnlocking &&
!Config.INSTANCE.EnableWebServer)
{
MessageBox.Show("No unlocking methods enabled, please run the config installer first");
return false;
Expand Down
18 changes: 11 additions & 7 deletions MLock/LockWindow.xaml.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;
using Common;
using MLock.Modules;

namespace MLock
{
Expand Down Expand Up @@ -43,11 +45,10 @@ public MainWindow()

Events.LockApp += () =>
{
var screenshot = Utils.Screenshot();


Dispatcher.Invoke(() =>
{
var screenshot = Utils.Screenshot();

var bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(
screenshot.GetHbitmap(),
IntPtr.Zero,
Expand All @@ -62,17 +63,19 @@ public MainWindow()
Events.UnlockApp += () => { SetBlur(true); };
}


Native.SetKHookConfig(config);

if (Config.INSTANCE.StartLocked) Events.Lock();
if (Config.INSTANCE.StartLocked && !Config.INSTANCE.EnableUSBUnlocking) // CheckUSBs method automaticly locks if no USBs are found
Events.Lock();

if (Config.INSTANCE.EnableUSBUnlocking)
{
USB.Initialize();

USB.CheckUSBs();
}

if (Config.INSTANCE.EnableWebServer)
Task.Run(() => new WebServer().Initialize());
}

private void SetPasswordText(string text)
Expand Down Expand Up @@ -132,7 +135,8 @@ public void OnLock()
return;
}

Native.InstallKHook();
if (!Config.INSTANCE.Debug)
Native.InstallKHook();
Visibility = Visibility.Visible;
});
}
Expand Down
4 changes: 3 additions & 1 deletion MLock/MLock.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,8 @@
<SubType>Designer</SubType>
</ApplicationDefinition>
<Compile Include="Events.cs" />
<Compile Include="USB.cs" />
<Compile Include="Modules\USB.cs" />
<Compile Include="Modules\WebServer.cs" />
<Compile Include="Utils.cs" />
<Page Include="LockWindow.xaml">
<Generator>MSBuild:Compile</Generator>
Expand Down Expand Up @@ -123,5 +124,6 @@
<Name>Common</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
File renamed without changes.
60 changes: 60 additions & 0 deletions MLock/Modules/WebServer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using Common;

namespace MLock.Modules
{
internal class WebServer
{
private CancellationTokenSource cts;
private HttpListener listener;

public async Task Initialize()
{
listener = new HttpListener();
listener.Prefixes.Add("http://+:4444/");

listener.Start();

while (listener.IsListening)
{
var context = await listener.GetContextAsync();
ProcessRequest(context);
}

listener.Stop();
}

private void ProcessRequest(HttpListenerContext context)
{
var password = context.Request.QueryString.Get("password");
if (password == null || password != Config.INSTANCE.WebServerPassword)
{
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
context.Response.Close();
return;
}

switch (context.Request.Url.AbsolutePath)
{
case "/lock":
Events.Lock();
break;
case "/unlock":
Events.Unlock();
break;
}

context.Response.StatusCode = (int)HttpStatusCode.OK;

context.Response.Close();
}

private void StopServer(object sender, RoutedEventArgs e) // I am guessing server gets closed automatically when the program closes
{
cts?.Cancel();
}
}
}
6 changes: 4 additions & 2 deletions MLock/Utils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,10 @@ public static Bitmap Screenshot()
var captureRectangle = Screen.PrimaryScreen.Bounds;

var captureBitmap = new Bitmap(captureRectangle.Width, captureRectangle.Height);
var captureGraphics = Graphics.FromImage(captureBitmap);
captureGraphics.CopyFromScreen(captureRectangle.Left, captureRectangle.Top, 0, 0, captureRectangle.Size);
using (var graphics = Graphics.FromImage(captureBitmap))
{
graphics.CopyFromScreen(captureRectangle.Left, captureRectangle.Top, 0, 0, captureRectangle.Size);
}

return captureBitmap;
}
Expand Down
16 changes: 15 additions & 1 deletion MLockConfigurator/App.xaml.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,23 @@
namespace MLockUSBKeyGenerator
using System.Windows;
using System;

namespace MLockUSBKeyGenerator
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App
{
public App()
{
if (!Utils.IsAdmin())
{
MessageBox.Show("Configurator requires administrative privileges to properly save the config file. Please run the program as an administrator.", "Admin Privileges Required", MessageBoxButton.OK, MessageBoxImage.Warning);
Environment.Exit(0);
return;
}

InitializeComponent();
}
}
}
15 changes: 14 additions & 1 deletion MLockConfigurator/ConfiguratorWindow.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="MLock Config Generator" Height="400" Width="525">
Title="MLock Config Generator" Height="500" Width="525">
<StackPanel>
<CheckBox x:Name="StartLockedCheckBox" Content="Start Locked" Margin="10"
IsChecked="{Binding StartLocked, Mode=TwoWay}" />
Expand All @@ -22,6 +22,19 @@
IsEnabled="{Binding EnablePasswordUnlocking}" />
</Grid>

<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>

<CheckBox x:Name="WebServerCheckBox" Content="Enable WebServer" Margin="10" Grid.Column="0"
IsChecked="{Binding EnableWebServer, Mode=TwoWay}" />
<TextBox x:Name="WebServerTextBox" Margin="10" Grid.Row="9" Grid.Column="1" Width="Auto"
Text="{Binding WebServerPassword}"
IsEnabled="{Binding EnablePasswordUnlocking}" />
</Grid>

<CheckBox x:Name="USBUnlockingCheckBox" Content="USB Unlocking" Margin="10"
IsChecked="{Binding EnableUSBUnlocking, Mode=TwoWay}" />

Expand Down
17 changes: 16 additions & 1 deletion MLockConfigurator/ConfiguratorWindow.xaml.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.IO;
using System.Security.AccessControl;
using System.Windows;
using Common;
using Microsoft.Win32;
Expand Down Expand Up @@ -106,6 +107,14 @@ public void InstallConfigButton_Click(object sender, RoutedEventArgs e)

if (config.EnableUSBUnlocking && config.privateKey != null)
File.WriteAllText(MLOCK_DIR + "\\publicKey.xml", RSAUtils.GetPublicKey(config.privateKey));

// Make Config file only readable by admins
FileSecurity fileSecurity = File.GetAccessControl(MLOCK_DIR);
fileSecurity.SetAccessRuleProtection(true, false);
FileSystemAccessRule rule = new FileSystemAccessRule("Administrators", FileSystemRights.FullControl, AccessControlType.Allow);
fileSecurity.AddAccessRule(rule);
File.SetAccessControl(MLOCK_DIR, fileSecurity);

MessageBox.Show("Config installed successfully");
}
}
Expand Down Expand Up @@ -142,7 +151,13 @@ public bool ValidateConfig()
return false;
}

if (!config.EnablePasswordUnlocking && !config.EnableUSBUnlocking)
if (Config.INSTANCE.EnableWebServer && Config.INSTANCE.WebServerPassword.Trim() == "")
{
MessageBox.Show("WebServer password not set");
return false;
}

if (!config.EnablePasswordUnlocking && !config.EnableUSBUnlocking && !config.EnableWebServer)
{
MessageBox.Show("No unlocking methods enabled, select one first");
return false;
Expand Down
14 changes: 5 additions & 9 deletions MLockConfigurator/Utils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,17 +39,13 @@ public static bool IsTaskInstalled()
return TaskService.Instance.RootFolder.Tasks.Any(task => task.Name == "MLockTask");
}

public static void InstallTask()
public static bool IsAdmin()
{
var isAdmin = new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator);

if (!isAdmin)
{
MessageBox.Show("To Install task, please run Configurator as admin");
// Instead of this I can make it start a CMD process as admin and copy file but better do in code i think
return;
}
return new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator);
}

public static void InstallTask()
{
var td = TaskService.Instance.NewTask();
td.RegistrationInfo.Description = "Starts MLock";
td.Principal.RunLevel = TaskRunLevel.Highest;
Expand Down
10 changes: 7 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,14 @@ https://github.com/mantikafasi/MLock/assets/67705577/7440eb07-5159-47ea-a202-524

Incase you get locked out, from different account with admin permissions you can delete config.json inside C:/Users/YourUser/AppData/Roaming/MLock

## Notes
- Currently passwords are stored as plaintext in config.json, so any user with admin permissions can see your password.
- WebServer doesnt use https, so if someone is sniffing your network they can see your password.

## TODO
- [ ] Add more unlock methods (Like from mobile app)
- [ ] Design a better UI (current one is terrible)
- [ ] Add option to configurator to run program at startup
- [x] Add more unlock methods (Like from mobile app)
- [x] Design a better UI (current one is terrible)
- [x] Add option to configurator to run program at startup
- [ ] Add github actions to create releases automatically
- [ ] Maybe add option to remove sound when locked
- [ ] Log Failures to file

0 comments on commit 0fd0077

Please sign in to comment.