优化UI和系统选项设置和默认用户id

This commit is contained in:
snltty
2023-12-18 14:12:53 +08:00
parent 58eaeb7a8d
commit 9b816f231f
20 changed files with 306 additions and 279 deletions

View File

@@ -1,5 +1,6 @@
<template> <template>
<el-dialog class="options" title="阻止窗口" destroy-on-close v-model="state.show" center align-center width="94%"> <el-dialog class="options" title="阻止窗口" destroy-on-close v-model="state.show" center align-center width="94%">
<el-alert style="margin-bottom:.6rem" type="error" title="无法上网与窗口无关" :closable="false" show-icon />
<div class="rule-wrap flex"> <div class="rule-wrap flex">
<div class="items"> <div class="items">
<CheckBoxWrap ref="devices" :data="globalData.devices" :items="state.items" label="MachineName" title="选择设备"></CheckBoxWrap> <CheckBoxWrap ref="devices" :data="globalData.devices" :items="state.items" label="MachineName" title="选择设备"></CheckBoxWrap>
@@ -47,7 +48,16 @@ export default {
const state = reactive({ const state = reactive({
show: props.modelValue, show: props.modelValue,
items: computed(() => pluginState.value.activeWindow.devices), items: computed(() => {
const devices = pluginState.value.activeWindow.devices;
let ids = devices.reduce((arr, value) => {
arr.push(...value.DisallowRunIds);
return arr;
}, []);
state.currentPrivate = state.privateExes.filter(c => ids.indexOf(c.ID) >= 0);
state.currentPublic = state.publicExes.filter(c => ids.indexOf(c.ID) >= 0);
return devices;
}),
privateExes: computed(() => user.value ? user.value.Windows : []), privateExes: computed(() => user.value ? user.value.Windows : []),
publicExes: computed(() => usePublic ? publicUser.value.Windows : []), publicExes: computed(() => usePublic ? publicUser.value.Windows : []),
loading: false, loading: false,
@@ -62,14 +72,6 @@ export default {
} }
}); });
onMounted(() => {
if (state.items.length == 1) {
let item = state.items[0];
state.currentPrivate = state.privateExes.filter(c => item.DisallowRunIds.indexOf(c.ID) >= 0);
state.currentPublic = state.publicExes.filter(c => item.DisallowRunIds.indexOf(c.ID) >= 0);
}
});
const devices = ref(null); const devices = ref(null);
const privateExes = ref(null); const privateExes = ref(null);
const publicExes = ref(null); const publicExes = ref(null);

View File

@@ -1,5 +1,6 @@
<template> <template>
<el-dialog class="options" title="网络限制" destroy-on-close v-model="state.show" center align-center width="94%"> <el-dialog class="options" title="网络限制" destroy-on-close v-model="state.show" center align-center width="94%">
<el-alert style="margin-bottom:.6rem" type="error" title="打开不了软件与网络无关" :closable="false" show-icon />
<div class="rule-wrap flex"> <div class="rule-wrap flex">
<div class="items"> <div class="items">
<CheckBoxWrap ref="devices" :data="globalData.devices" :items="state.items" label="MachineName" title="选择设备"></CheckBoxWrap> <CheckBoxWrap ref="devices" :data="globalData.devices" :items="state.items" label="MachineName" title="选择设备"></CheckBoxWrap>
@@ -45,7 +46,16 @@ export default {
const state = reactive({ const state = reactive({
show: props.modelValue, show: props.modelValue,
items: computed(() => pluginState.value.hijack.devices), items: computed(() => {
const devices = pluginState.value.hijack.devices;
let ids = devices.reduce((arr, value) => {
arr.push(...value.RuleIds);
return arr;
}, []);
state.currentPrivate = state.privateRules.filter(c => ids.indexOf(c.ID) >= 0);
state.currentPublic = state.publicRules.filter(c => ids.indexOf(c.ID) >= 0);
return devices;
}),
privateRules: computed(() => user.value ? user.value.Rules : []), privateRules: computed(() => user.value ? user.value.Rules : []),
publicRules: computed(() => usePublic ? publicUser.value.Rules : []), publicRules: computed(() => usePublic ? publicUser.value.Rules : []),
loading: false, loading: false,
@@ -59,13 +69,6 @@ export default {
}, 300); }, 300);
} }
}); });
onMounted(() => {
if (state.items.length == 1) {
let item = state.items[0];
state.currentPrivate = state.privateRules.filter(c => item.RuleIds.indexOf(c.ID) >= 0);
state.currentPublic = state.publicRules.filter(c => item.RuleIds.indexOf(c.ID) >= 0);
}
});
const devices = ref(null); const devices = ref(null);
const privateRules = ref(null); const privateRules = ref(null);

View File

@@ -4,7 +4,7 @@
<el-icon> <el-icon>
<Tools /> <Tools />
</el-icon> </el-icon>
<span class="value">{{data.System.RegistrysCount}}</span> <span class="value">{{data.System.OptionCount}}</span>
</a> </a>
</div> </div>
</template> </template>

View File

@@ -23,20 +23,20 @@ export default {
const data = props.data; const data = props.data;
const pluginState = injectPluginState(); const pluginState = injectPluginState();
const usb = computed(() => { const usb = computed(() => {
if (data.System.RegistryValues && data.System.RegistryKeys.USBSTOR) { if (data.System.OptionValues && data.System.OptionKeys.USBSTOR) {
return data.System.RegistryValues[data.System.RegistryKeys.USBSTOR.Index] == '1'; return data.System.OptionValues[data.System.OptionKeys.USBSTOR.Index] == '1';
} }
return false; return false;
}); });
const setting = computed(() => { const setting = computed(() => {
if (data.System.RegistryValues && data.System.RegistryKeys.NoControlPanel) { if (data.System.OptionValues && data.System.OptionKeys.NoControlPanel) {
return data.System.RegistryValues[data.System.RegistryKeys.NoControlPanel.Index] == '1'; return data.System.OptionValues[data.System.OptionKeys.NoControlPanel.Index] == '1';
} }
return false; return false;
}); });
const shutdown = computed(() => { const shutdown = computed(() => {
if (data.System.RegistryValues && data.System.RegistryKeys.NoClose) { if (data.System.OptionValues && data.System.OptionKeys.NoClose) {
return data.System.RegistryValues[data.System.RegistryKeys.NoClose.Index] == '1'; return data.System.OptionValues[data.System.OptionKeys.NoClose.Index] == '1';
} }
return false; return false;
}); });

View File

@@ -74,7 +74,7 @@ export default {
const initOptions = () => { const initOptions = () => {
const devices = pluginState.value.system.devices.map(c => c.MachineName); const devices = pluginState.value.system.devices.map(c => c.MachineName);
const optionJson = globalData.value.allDevices.filter(c => devices.indexOf(c.MachineName) >= 0).reduce((json, value, index) => { const optionJson = globalData.value.allDevices.filter(c => devices.indexOf(c.MachineName) >= 0).reduce((json, value, index) => {
json = Object.assign(json, value.System.RegistryKeys); json = Object.assign(json, value.System.OptionKeys);
return json; return json;
}, {}); }, {});
const keys = Object.keys(optionJson); const keys = Object.keys(optionJson);
@@ -93,7 +93,7 @@ export default {
const device = globalData.value.allDevices.filter(c => c.MachineName == name)[0]; const device = globalData.value.allDevices.filter(c => c.MachineName == name)[0];
if (device) { if (device) {
const registrys = device.System.RegistryValues; const registrys = device.System.OptionValues;
const options = state.options; const options = state.options;
if (registrys && registrys.length == options.length) { if (registrys && registrys.length == options.length) {
for (let i = 0; i < registrys.length; i++) { for (let i = 0; i < registrys.length; i++) {

View File

@@ -2,9 +2,9 @@ export default {
field() { field() {
return { return {
System: { System: {
RegistryValues: [], OptionValues: [],
RegistryKeys: {}, OptionKeys: {},
RegistrysCount: 0, OptionCount: 0,
Cpu: 0, Cpu: 0,
Memory: 0, Memory: 0,
@@ -89,12 +89,12 @@ export default {
item.System.Drives = report.System.Drives || []; item.System.Drives = report.System.Drives || [];
} }
if (report.System.RegValues) { if (report.System.OptionValues) {
item.System.RegistryValues = report.System.RegValues.split('').map(c => +c); item.System.OptionValues = report.System.OptionValues.split('').map(c => +c);
item.System.RegistrysCount = item.System.RegistryValues.filter(c => c == '1').length; item.System.OptionCount = item.System.OptionValues.filter(c => c == '1').length;
} }
if (report.System.RegKeys) { if (report.System.OptionKeys) {
item.System.RegistryKeys = report.System.RegKeys; item.System.OptionKeys = report.System.OptionKeys;
} }
} }

View File

@@ -25,6 +25,8 @@ namespace cmonitor.client
WallpaperUrl = clientConfig.WallpaperUrl; WallpaperUrl = clientConfig.WallpaperUrl;
HijackConfig = clientConfig.HijackConfig; HijackConfig = clientConfig.HijackConfig;
WindowNames = clientConfig.WindowNames; WindowNames = clientConfig.WindowNames;
ScreenShareState = clientConfig.ScreenShareState;
UserSid = clientConfig.UserSid;
SaveTask(); SaveTask();
} }

View File

@@ -9,9 +9,14 @@ namespace cmonitor.client
private int networdkEnabledTimes = 0; private int networdkEnabledTimes = 0;
public Action<int> NetworkEnabledHandle { get; set; } public Action<int> NetworkEnabledHandle { get; set; }
public Action NetworkFirstEnabledHandle { get; set; }
public bool NetworkEnabled => Connected; public bool NetworkEnabled => Connected;
public void PushNetworkEnabled() public void PushNetworkEnabled()
{ {
if(networdkEnabledTimes == 0)
{
NetworkFirstEnabledHandle?.Invoke();
}
NetworkEnabledHandle?.Invoke(networdkEnabledTimes); NetworkEnabledHandle?.Invoke(networdkEnabledTimes);
networdkEnabledTimes++; networdkEnabledTimes++;
} }

View File

@@ -22,13 +22,10 @@ namespace cmonitor.client.reports.active
this.activeWindow = activeWindow; this.activeWindow = activeWindow;
if (config.IsCLient) if (config.IsCLient)
{ {
clientSignInState.NetworkEnabledHandle += (times) => clientSignInState.NetworkFirstEnabledHandle += () =>
{ {
if(times == 0) DisallowRun(clientConfig.WindowNames);
{ Loop();
DisallowRun(clientConfig.WindowNames);
Loop();
}
}; };
AppDomain.CurrentDomain.ProcessExit += (s, e) => DisallowRun(Array.Empty<string>()); AppDomain.CurrentDomain.ProcessExit += (s, e) => DisallowRun(Array.Empty<string>());

View File

@@ -31,13 +31,7 @@ namespace cmonitor.client.reports.hijack
hijackConfig.DeniedIPs = clientConfig.HijackConfig.DeniedIPs; hijackConfig.DeniedIPs = clientConfig.HijackConfig.DeniedIPs;
hijackConfig.AllowIPs = clientConfig.HijackConfig.AllowIPs; hijackConfig.AllowIPs = clientConfig.HijackConfig.AllowIPs;
clientSignInState.NetworkEnabledHandle += (times) => clientSignInState.NetworkFirstEnabledHandle += hijack.Start;
{
if (times == 0)
{
hijack.Start();
}
};
} }
catch (Exception ex) catch (Exception ex)
{ {

View File

@@ -21,13 +21,7 @@ namespace cmonitor.client.reports.llock
if (config.IsCLient) if (config.IsCLient)
{ {
clientSignInState.NetworkEnabledHandle += (times) => clientSignInState.NetworkFirstEnabledHandle +=()=> { LockScreen(clientConfig.LLock); };
{
if(times == 0)
{
LockScreen(clientConfig.LLock);
}
};
} }
} }

View File

@@ -1,10 +1,4 @@
using MemoryPack; using MemoryPack;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static cmonitor.client.reports.system.SystemOptionHelper;
namespace cmonitor.client.reports.system namespace cmonitor.client.reports.system
{ {
@@ -12,10 +6,9 @@ namespace cmonitor.client.reports.system
{ {
public ReportDriveInfo[] GetAllDrives(); public ReportDriveInfo[] GetAllDrives();
public Dictionary<string, SystemOptionKeyInfo> GetOptionKeys(); public Dictionary<string, SystemOptionKeyInfo> OptionKeys();
public string GetOptionValues(); public string OptionValues();
public bool OptionUpdate(SystemOptionUpdateInfo optionUpdateInfo); public void OptionUpdate(SystemOptionUpdateInfo optionUpdateInfo);
public void OptionRefresh();
public bool Password(PasswordInputInfo command); public bool Password(PasswordInputInfo command);

View File

@@ -17,24 +17,16 @@
return 0; return 0;
} }
public Dictionary<string, SystemOptionKeyInfo> GetOptionKeys() public Dictionary<string, SystemOptionKeyInfo> OptionKeys()
{ {
return new Dictionary<string, SystemOptionKeyInfo>(); return new Dictionary<string, SystemOptionKeyInfo>();
} }
public string OptionValues()
public string GetOptionValues()
{ {
return string.Empty; return string.Empty;
} }
public void OptionUpdate(SystemOptionUpdateInfo registryUpdateInfo)
public void OptionRefresh()
{ {
}
public bool OptionUpdate(SystemOptionUpdateInfo registryUpdateInfo)
{
return true;
} }
public bool Password(PasswordInputInfo command) public bool Password(PasswordInputInfo command)

View File

@@ -17,24 +17,16 @@
return 0; return 0;
} }
public Dictionary<string, SystemOptionKeyInfo> GetOptionKeys() public Dictionary<string, SystemOptionKeyInfo> OptionKeys()
{ {
return new Dictionary<string, SystemOptionKeyInfo>(); return new Dictionary<string, SystemOptionKeyInfo>();
} }
public string OptionValues()
public string GetOptionValues()
{ {
return string.Empty; return string.Empty;
} }
public void OptionUpdate(SystemOptionUpdateInfo registryUpdateInfo)
public void OptionRefresh()
{ {
}
public bool OptionUpdate(SystemOptionUpdateInfo registryUpdateInfo)
{
return true;
} }
public bool Password(PasswordInputInfo command) public bool Password(PasswordInputInfo command)

View File

@@ -1,4 +1,6 @@
using MemoryPack; using common.libs.winapis;
using MemoryPack;
using System.Diagnostics;
namespace cmonitor.client.reports.system namespace cmonitor.client.reports.system
{ {
@@ -21,7 +23,7 @@ namespace cmonitor.client.reports.system
if (config.IsCLient) if (config.IsCLient)
{ {
drives = system.GetAllDrives(); drives = system.GetAllDrives();
registryKeys = system.GetOptionKeys(); registryKeys = system.OptionKeys();
ReportTask(); ReportTask();
} }
} }
@@ -34,12 +36,12 @@ namespace cmonitor.client.reports.system
if (reportType == ReportType.Full) if (reportType == ReportType.Full)
{ {
systemReportInfo.Drives = drives; systemReportInfo.Drives = drives;
systemReportInfo.RegKeys = registryKeys; systemReportInfo.OptionKeys = registryKeys;
} }
else else
{ {
systemReportInfo.Drives = null; systemReportInfo.Drives = null;
systemReportInfo.RegKeys = null; systemReportInfo.OptionKeys = null;
} }
if (reportType == ReportType.Full || systemReportInfo.Cpu != lastCpu || systemReportInfo.Memory != lastMemory) if (reportType == ReportType.Full || systemReportInfo.Cpu != lastCpu || systemReportInfo.Memory != lastMemory)
@@ -51,15 +53,16 @@ namespace cmonitor.client.reports.system
return null; return null;
} }
public void OptionUpdate(SystemOptionUpdateInfo registryUpdateInfo)
{
system.OptionUpdate(registryUpdateInfo);
}
public bool Password(PasswordInputInfo info) public bool Password(PasswordInputInfo info)
{ {
return system.Password(info); return system.Password(info);
} }
public bool OptionUpdate(SystemOptionUpdateInfo registryUpdateInfo)
{
return system.OptionUpdate(registryUpdateInfo);
}
private void ReportTask() private void ReportTask()
{ {
@@ -71,12 +74,9 @@ namespace cmonitor.client.reports.system
{ {
systemReportInfo.Cpu = system.GetCpu(); systemReportInfo.Cpu = system.GetCpu();
systemReportInfo.Memory = system.GetMemory(); systemReportInfo.Memory = system.GetMemory();
systemReportInfo.RegValues = system.GetOptionValues(); systemReportInfo.OptionValues = system.OptionValues();
//systemReportInfo.Disk = WindowsDrive.GetDiskUsage(); //systemReportInfo.Disk = WindowsDrive.GetDiskUsage();
} }
system.OptionRefresh();
Thread.Sleep(1000); Thread.Sleep(1000);
} }
}, TaskCreationOptions.LongRunning); }, TaskCreationOptions.LongRunning);
@@ -91,12 +91,10 @@ namespace cmonitor.client.reports.system
public float Disk { get; set; } public float Disk { get; set; }
public ReportDriveInfo[] Drives { get; set; } public ReportDriveInfo[] Drives { get; set; }
public string RegValues { get; set; } public string OptionValues { get; set; }
public Dictionary<string, SystemOptionKeyInfo> RegKeys { get; set; } public Dictionary<string, SystemOptionKeyInfo> OptionKeys { get; set; }
} }
[MemoryPackable] [MemoryPackable]
public sealed partial class SystemOptionUpdateInfo public sealed partial class SystemOptionUpdateInfo
{ {

View File

@@ -1,25 +1,22 @@
using common.libs; using common.libs;
using common.libs.winapis; using common.libs.winapis;
using Microsoft.Win32; using Microsoft.Win32;
using System.Collections.Concurrent;
namespace cmonitor.client.reports.system namespace cmonitor.client.reports.system
{ {
public sealed class SystemWindows : ISystem public sealed class SystemWindows : ISystem
{ {
private readonly SystemOptionHelper registryOptionHelper; private readonly SystemOptionHelper registryOptionHelper;
private readonly ClientSignInState clientSignInState;
private ConcurrentQueue<Action> actions = new ConcurrentQueue<Action>();
public SystemWindows(ClientConfig clientConfig, Config config, ClientSignInState clientSignInState) public SystemWindows(ClientConfig clientConfig, Config config, ClientSignInState clientSignInState)
{ {
this.clientSignInState = clientSignInState;
if (config.IsCLient) if (config.IsCLient)
{ {
registryOptionHelper = new SystemOptionHelper(clientConfig); registryOptionHelper = new SystemOptionHelper(clientConfig);
clientSignInState.NetworkEnabledHandle += (times) => OptionsInit();
{
if (times == 0)
{
registryOptionHelper.Reuse();
OptionUpdate(new SystemOptionUpdateInfo { Keys = new string[] { "SoftwareSASGeneration" }, Value = false });
}
};
} }
} }
@@ -33,37 +30,55 @@ namespace cmonitor.client.reports.system
}).ToArray(); }).ToArray();
} }
public Dictionary<string, SystemOptionKeyInfo> GetOptionKeys() private void OptionsInit()
{
LoopTask();
actions.Enqueue(() =>
{
registryOptionHelper.Restore();
});
clientSignInState.NetworkFirstEnabledHandle += () =>
{
actions.Enqueue(() =>
{
registryOptionHelper.Reuse();
OptionUpdate(new SystemOptionUpdateInfo { Keys = new string[] { "SoftwareSASGeneration" }, Value = false });
});
};
}
public Dictionary<string, SystemOptionKeyInfo> OptionKeys()
{ {
return registryOptionHelper.GetKeys(); return registryOptionHelper.GetKeys();
} }
public string GetOptionValues() public string OptionValues()
{ {
return registryOptionHelper.GetValues(); return registryOptionHelper.GetValues();
} }
public bool OptionUpdate(SystemOptionUpdateInfo registryUpdateInfo) public void OptionUpdate(SystemOptionUpdateInfo registryUpdateInfo)
{ {
bool result = registryOptionHelper.UpdateValue(registryUpdateInfo.Keys, registryUpdateInfo.Value); actions.Enqueue(() =>
if (result)
{ {
Interlocked.Exchange(ref registryUpdated, 1); registryOptionHelper.UpdateValue(registryUpdateInfo.Keys, registryUpdateInfo.Value);
} });
return result;
} }
int registryUpdated = 0; private void LoopTask()
int registryUpdateFlag = 1;
public void OptionRefresh()
{ {
if (registryUpdated == 1 && registryUpdated == 1) Task.Factory.StartNew(() =>
{ {
Interlocked.CompareExchange(ref registryUpdated, 0, 1); while (true)
Interlocked.CompareExchange(ref registryUpdateFlag, 0, 1);
Task.Run(() =>
{ {
CommandHelper.Windows(string.Empty, new string[] { "gpupdate /force" }); if (registryOptionHelper.CanWrite && actions.Count > 0)
Interlocked.CompareExchange(ref registryUpdateFlag, 1, 0); {
}); while (actions.TryDequeue(out Action action))
} {
action();
}
registryOptionHelper.Refresh();
}
Thread.Sleep(30);
}
}, TaskCreationOptions.LongRunning);
} }
public bool Password(PasswordInputInfo command) public bool Password(PasswordInputInfo command)
@@ -71,6 +86,7 @@ namespace cmonitor.client.reports.system
return NetApi32.ChangePassword(null, Environment.UserName, command.OldPassword, command.NewPassword); return NetApi32.ChangePassword(null, Environment.UserName, command.OldPassword, command.NewPassword);
} }
CPUTime oldTime = new CPUTime(0, 0); CPUTime oldTime = new CPUTime(0, 0);
public double GetCpu() public double GetCpu()
{ {
@@ -92,72 +108,20 @@ namespace cmonitor.client.reports.system
private readonly ClientConfig clientConfig; private readonly ClientConfig clientConfig;
char[] values; char[] values;
public bool CanWrite => string.IsNullOrWhiteSpace(currentUserSid) == false;
public SystemOptionHelper(ClientConfig clientConfig) public SystemOptionHelper(ClientConfig clientConfig)
{ {
this.clientConfig = clientConfig; this.clientConfig = clientConfig;
values = string.Empty.PadLeft(Infos.Length, '0').ToCharArray(); values = string.Empty.PadLeft(Infos.Length, '0').ToCharArray();
GetSid(); GetSid();
BackUp();
AppDomain.CurrentDomain.ProcessExit += (sender, e) => Restore();
Console.CancelKeyPress += (sender, e) => Restore();
} }
bool backuped = false;
string backupPath = "HKEY_LOCAL_MACHINE\\SOFTWARE\\cmonitorBackup"; string backupPath = "HKEY_LOCAL_MACHINE\\SOFTWARE\\cmonitorBackup";
string backupKey = "cmonitorBackup"; string backupKey = "cmonitorBackup";
private void BackUp() public void Restore()
{ {
GetSid(); if (OperatingSystem.IsWindows() && GetSid())
if (string.IsNullOrWhiteSpace(currentUserSid))
{
return;
}
if (OperatingSystem.IsWindows())
{
try
{
Registry.SetValue(backupPath, "test", 1);
RegistryKey key = Registry.LocalMachine.OpenSubKey("Software");
key = key.OpenSubKey(backupKey, true);
backuped = key.GetValue("backuped", "0").ToString() == "1";
if (backuped)
{
return;
}
foreach (RegistryOptionInfo option in Infos)
{
foreach (RegistryOptionPathInfo path in option.Paths)
{
string pathStr = ReplaceRegistryPath(path.Path);
if (string.IsNullOrWhiteSpace(pathStr))
{
continue;
}
object value = Registry.GetValue(pathStr, path.Key, null);
if (value != null)
{
Registry.SetValue(backupPath, $"{option.Key}_{path.Key}", value);
}
}
}
Registry.SetValue(backupPath, "backuped", 1);
}
catch (Exception)
{
}
}
}
private void Restore()
{
if (backuped == false) return;
GetSid();
if (string.IsNullOrWhiteSpace(currentUserSid))
{
return;
}
if (OperatingSystem.IsWindows())
{ {
try try
{ {
@@ -172,39 +136,33 @@ namespace cmonitor.client.reports.system
{ {
continue; continue;
} }
//备份已经设置的
object setValue = Registry.GetValue(pathStr, path.Key, null); object setValue = Registry.GetValue(pathStr, path.Key, null);
if (setValue != null) if (setValue != null)
{ {
Registry.SetValue(backupPath, $"{option.Key}_{path.Key}_old", setValue); Registry.SetValue(backupPath, $"{option.Key}_{path.Key}_old", setValue);
} }
//删除设置
object value = Registry.GetValue(backupPath, $"{option.Key}_{path.Key}", null); string delPathStr = pathStr.Replace("HKEY_CURRENT_USER\\", "").Replace("HKEY_LOCAL_MACHINE\\", "");
if (value != null) try
{ {
Registry.SetValue(pathStr, path.Key, value); RegistryKey _key = Registry.LocalMachine.OpenSubKey(delPathStr);
_key?.DeleteValue(path.Key);
} }
else catch (Exception)
{
}
try
{
RegistryKey _key = Registry.CurrentUser.OpenSubKey(delPathStr);
_key?.DeleteValue(path.Key);
}
catch (Exception)
{ {
string delPathStr = pathStr.Replace("HKEY_CURRENT_USER\\", "").Replace("HKEY_LOCAL_MACHINE\\", "");
try
{
RegistryKey _key = Registry.LocalMachine.OpenSubKey(delPathStr);
_key?.DeleteValue(path.Key);
}
catch (Exception)
{
}
try
{
RegistryKey _key = Registry.CurrentUser.OpenSubKey(delPathStr);
_key?.DeleteValue(path.Key);
}
catch (Exception)
{
}
} }
} }
} }
Updated();
} }
catch (Exception) catch (Exception)
{ {
@@ -213,12 +171,7 @@ namespace cmonitor.client.reports.system
} }
public void Reuse() public void Reuse()
{ {
GetSid(); if (OperatingSystem.IsWindows() && GetSid())
if (string.IsNullOrWhiteSpace(currentUserSid))
{
return;
}
if (OperatingSystem.IsWindows())
{ {
try try
{ {
@@ -240,6 +193,7 @@ namespace cmonitor.client.reports.system
} }
} }
} }
Updated();
} }
catch (Exception) catch (Exception)
{ {
@@ -247,11 +201,41 @@ namespace cmonitor.client.reports.system
} }
} }
int registryUpdated = 0;
int registryUpdateFlag = 1;
private void Updated()
{
Interlocked.Exchange(ref registryUpdated, 1);
}
public void Refresh()
{
if (registryUpdated == 1 && registryUpdated == 1)
{
Interlocked.CompareExchange(ref registryUpdated, 0, 1);
Interlocked.CompareExchange(ref registryUpdateFlag, 0, 1);
Task.Run(() =>
{
CommandHelper.Windows(string.Empty, new string[] { "gpupdate /force" });
Interlocked.CompareExchange(ref registryUpdateFlag, 1, 0);
});
}
}
public Dictionary<string, SystemOptionKeyInfo> GetKeys()
{
Dictionary<string, SystemOptionKeyInfo> keys = new Dictionary<string, SystemOptionKeyInfo>();
for (int i = 0; i < Infos.Length; i++)
{
RegistryOptionInfo item = Infos[i];
keys[item.Key] = new SystemOptionKeyInfo { Desc = item.Desc, Index = (ushort)i };
}
return keys;
}
public string GetValues() public string GetValues()
{ {
GetSid(); if (OperatingSystem.IsWindows() && GetSid())
if (OperatingSystem.IsWindows())
{ {
for (int i = 0; i < Infos.Length; i++) for (int i = 0; i < Infos.Length; i++)
{ {
@@ -284,14 +268,13 @@ namespace cmonitor.client.reports.system
return result; return result;
} }
IEnumerable<RegistryOptionInfo> info = Infos.Where(c => keys.Contains(c.Key));
if (info.Any() == false)
{
return result;
}
if (OperatingSystem.IsWindows()) if (OperatingSystem.IsWindows())
{ {
IEnumerable<RegistryOptionInfo> info = Infos.Where(c => keys.Contains(c.Key));
if (info.Any() == false)
{
return result;
}
foreach (RegistryOptionInfo item in info) foreach (RegistryOptionInfo item in info)
{ {
foreach (RegistryOptionPathInfo pathItem in item.Paths) foreach (RegistryOptionPathInfo pathItem in item.Paths)
@@ -302,8 +285,8 @@ namespace cmonitor.client.reports.system
continue; continue;
} }
string setValue = value ? pathItem.DisallowValue : pathItem.AllowValue; string setValue = value ? pathItem.DisallowValue : pathItem.AllowValue;
string oldValue = Registry.GetValue(path, pathItem.Key, pathItem.AllowValue).ToString(); object oldValue = Registry.GetValue(path, pathItem.Key, null);
if (oldValue != setValue) if (oldValue == null || oldValue.ToString() != setValue)
{ {
Registry.SetValue(path, pathItem.Key, int.Parse(setValue), RegistryValueKind.DWord); Registry.SetValue(path, pathItem.Key, int.Parse(setValue), RegistryValueKind.DWord);
result |= true; result |= true;
@@ -312,8 +295,13 @@ namespace cmonitor.client.reports.system
} }
} }
if (result)
{
Updated();
}
return result; return result;
} }
private string ReplaceRegistryPath(string path) private string ReplaceRegistryPath(string path)
{ {
if (!string.IsNullOrWhiteSpace(currentUserSid)) if (!string.IsNullOrWhiteSpace(currentUserSid))
@@ -322,36 +310,32 @@ namespace cmonitor.client.reports.system
} }
return string.Empty; return string.Empty;
} }
private void GetSid() private bool GetSid()
{ {
if (string.IsNullOrWhiteSpace(currentUserSid)) if (string.IsNullOrWhiteSpace(currentUserSid) == false)
{ {
currentUserSid = clientConfig.UserSid; return true;
} }
if (string.IsNullOrWhiteSpace(currentUserSid))
currentUserSid = Win32Interop.GetCurrentUserSid();
clientConfig.UserSid = currentUserSid;
if (string.IsNullOrWhiteSpace(currentUserSid) == false)
{ {
currentUserSid = Win32Interop.GetCurrentUserSid(); return true;
clientConfig.UserSid = currentUserSid;
} }
if (string.IsNullOrWhiteSpace(currentUserSid))
currentUserSid = Win32Interop.GetDefaultUserSid();
clientConfig.UserSid = currentUserSid;
if (string.IsNullOrWhiteSpace(currentUserSid) == false)
{ {
currentUserSid = Win32Interop.GetDefaultUserSid(); return true;
clientConfig.UserSid = currentUserSid;
} }
return string.IsNullOrWhiteSpace(currentUserSid) == false;
} }
public Dictionary<string, SystemOptionKeyInfo> GetKeys()
{
Dictionary<string, SystemOptionKeyInfo> keys = new Dictionary<string, SystemOptionKeyInfo>();
for (int i = 0; i < Infos.Length; i++)
{
RegistryOptionInfo item = Infos[i];
keys[item.Key] = new SystemOptionKeyInfo { Desc = item.Desc, Index = (ushort)i };
}
return keys;
}
//Desc为空则不显示 //Desc为空则不显示
private RegistryOptionInfo[] Infos = new RegistryOptionInfo[] { private RegistryOptionInfo[] Infos = new RegistryOptionInfo[] {
new RegistryOptionInfo{ new RegistryOptionInfo{

View File

@@ -20,13 +20,7 @@ namespace cmonitor.client.reports.wallpaper
if (config.IsCLient) if (config.IsCLient)
{ {
clientSignInState.NetworkEnabledHandle += (times) => clientSignInState.NetworkFirstEnabledHandle += () => { Update(clientConfig.Wallpaper, clientConfig.WallpaperUrl); };
{
if(times == 0)
{
Update(clientConfig.Wallpaper, clientConfig.WallpaperUrl);
}
};
} }
} }

View File

@@ -1,4 +1,5 @@
using System; using System;
using System.Reflection.Metadata;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
namespace common.libs.winapis; namespace common.libs.winapis;
@@ -89,4 +90,13 @@ public static class Kernel32
dwLength = (uint)Marshal.SizeOf(typeof(MEMORYSTATUSEX)); dwLength = (uint)Marshal.SizeOf(typeof(MEMORYSTATUSEX));
} }
} }
[DllImport("kernel32.dll")]
public static extern bool SetHandleInformation(IntPtr hObject, int dwMask, int dwFlags);
// <20><><EFBFBD><EFBFBD><EFBFBD>̾<EFBFBD><CCBE><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ϊ<EFBFBD><CEAA><EFBFBD>ɱ<EFBFBD><C9B1><EFBFBD>ֹ
} }

View File

@@ -36,6 +36,68 @@ namespace common.libs.winapis
ref int resume_handle ref int resume_handle
); );
[DllImport("Netapi32.dll", CharSet = CharSet.Unicode)]
public static extern int NetUserGetInfo(
string servername,
string username,
int level,
out IntPtr bufptr
);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct USER_INFO_3
{
[MarshalAs(UnmanagedType.LPWStr)]
public string Name;
[MarshalAs(UnmanagedType.LPWStr)]
public string Password;
public int PasswordAge;
public int Privilege;
[MarshalAs(UnmanagedType.LPWStr)]
public string HomeDirectory;
[MarshalAs(UnmanagedType.LPWStr)]
public string Comment;
public int Flags;
[MarshalAs(UnmanagedType.LPWStr)]
public string ScriptPath;
public int AuthFlags;
[MarshalAs(UnmanagedType.LPWStr)]
public string FullName;
[MarshalAs(UnmanagedType.LPWStr)]
public string UserComment;
[MarshalAs(UnmanagedType.LPWStr)]
public string Parameters;
[MarshalAs(UnmanagedType.LPWStr)]
public string Workstations;
public int LastLogon;
public int LastLogoff;
public int AcctExpires;
public int MaxStorage;
public int UnitsPerWeek;
public IntPtr LogonHours;
public int BadPwdCount;
public int NumLogons;
[MarshalAs(UnmanagedType.LPWStr)]
public string LogonServer;
public int CountryCode;
public int CodePage;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct USER_INFO_0
{
public string usri0_name;
}
public const int NERR_Success = 0;
public const int ERROR_ACCESS_DENIED = 5;
public const int ERROR_INVALID_PARAMETER = 87;
public const int ERROR_NOT_ENOUGH_MEMORY = 8;
public const int ERROR_NO_SUCH_USER = 1317;
public const int ERROR_INVALID_LEVEL = 124;
public const int ERROR_MORE_DATA = 234;
[DllImport("Netapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)] [DllImport("Netapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern int NetApiBufferFree(IntPtr Buffer); public static extern int NetApiBufferFree(IntPtr Buffer);
} }

View File

@@ -4,11 +4,13 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.Linq; using System.Linq;
using System.Reflection.Metadata;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Runtime.Serialization; using System.Runtime.Serialization;
using System.Security.Principal; using System.Security.Principal;
using System.Text; using System.Text;
using static common.libs.winapis.ADVAPI32; using static common.libs.winapis.ADVAPI32;
using static common.libs.winapis.NetApi32;
using static common.libs.winapis.User32; using static common.libs.winapis.User32;
namespace common.libs.winapis namespace common.libs.winapis
@@ -330,10 +332,9 @@ namespace common.libs.winapis
return string.Empty; return string.Empty;
} }
List<string> registrySids = Registry.Users.GetSubKeyNames().ToList(); List<WindowUserInfo> users = new List<WindowUserInfo>();
List<string> sids = new List<string>();
int resumeHandle = 0; int resumeHandle = 0;
int result = NetApi32.NetUserEnum(null, 0, 2, out IntPtr bufPtr, -1, out int entriesRead, out int totalEntries, ref resumeHandle); int result = NetUserEnum(null, 0, 2, out IntPtr bufPtr, -1, out int entriesRead, out int totalEntries, ref resumeHandle);
if (result == 0) if (result == 0)
{ {
try try
@@ -342,35 +343,33 @@ namespace common.libs.winapis
{ {
USER_INFO_0 userInfo = (USER_INFO_0)Marshal.PtrToStructure(bufPtr + (Marshal.SizeOf(typeof(USER_INFO_0)) * i), typeof(USER_INFO_0)); USER_INFO_0 userInfo = (USER_INFO_0)Marshal.PtrToStructure(bufPtr + (Marshal.SizeOf(typeof(USER_INFO_0)) * i), typeof(USER_INFO_0));
int cbSid = 0; int cbSid = 0, cchReferencedDomainName = 0;
int cchReferencedDomainName = 0;
int peUse;
StringBuilder referencedDomainName = new StringBuilder(); StringBuilder referencedDomainName = new StringBuilder();
IntPtr pSid = IntPtr.Zero; IntPtr pSid = IntPtr.Zero;
bool bSuccess = LookupAccountName(null, userInfo.usri0_name, pSid, ref cbSid, referencedDomainName, ref cchReferencedDomainName, out int peUse);
bool bSuccess = LookupAccountName(null, userInfo.usri0_name, pSid, ref cbSid, referencedDomainName, ref cchReferencedDomainName, out peUse); if (bSuccess == false && cbSid > 0)
if (!bSuccess && cbSid > 0)
{ {
pSid = Marshal.AllocHGlobal(cbSid); pSid = Marshal.AllocHGlobal(cbSid);
referencedDomainName.EnsureCapacity(cchReferencedDomainName); referencedDomainName.EnsureCapacity(cchReferencedDomainName);
bSuccess = LookupAccountName(null, userInfo.usri0_name, pSid, ref cbSid, referencedDomainName, ref cchReferencedDomainName, out peUse); bSuccess = LookupAccountName(null, userInfo.usri0_name, pSid, ref cbSid, referencedDomainName, ref cchReferencedDomainName, out peUse);
} }
if (bSuccess == false || ConvertSidToStringSid(pSid, out string stringSid) == false) continue;
if (bSuccess)
{
if (ConvertSidToStringSid(pSid, out string stringSid))
{
if (registrySids.Contains(stringSid))
{
sids.Add(stringSid);
}
}
}
if (pSid != IntPtr.Zero) if (pSid != IntPtr.Zero)
{ {
Marshal.FreeHGlobal(pSid); Marshal.FreeHGlobal(pSid);
} }
if (NetUserGetInfo(null, userInfo.usri0_name, 3, out IntPtr bufptr) != NERR_Success)
{
continue;
}
USER_INFO_3 info = (USER_INFO_3)Marshal.PtrToStructure(bufptr, typeof(USER_INFO_3));
if (info.LastLogon > 0)
{
users.Add(new WindowUserInfo { LastLogon = info.LastLogon, Sid = stringSid });
}
NetApiBufferFree(bufptr);
} }
} }
catch (Exception) catch (Exception)
@@ -378,13 +377,13 @@ namespace common.libs.winapis
} }
finally finally
{ {
NetApi32.NetApiBufferFree(bufPtr); NetApiBufferFree(bufPtr);
} }
} }
if (sids.Count == 1) if (users.Count > 0)
{ {
return sids[0]; return users.OrderByDescending(c => c.LastLogon).FirstOrDefault().Sid;
} }
return string.Empty; return string.Empty;
} }
@@ -393,6 +392,13 @@ namespace common.libs.winapis
return currentUsername == "NT AUTHORITY\\SYSTEM"; return currentUsername == "NT AUTHORITY\\SYSTEM";
} }
public static void SetHandleBlockKill(IntPtr handle)
{
const int HANDLE_FLAG_PROTECT_FROM_CLOSE = 0x1;
Kernel32.SetHandleInformation(handle, HANDLE_FLAG_PROTECT_FROM_CLOSE, HANDLE_FLAG_PROTECT_FROM_CLOSE);
}
} }
@@ -416,10 +422,9 @@ namespace common.libs.winapis
public string Username { get; set; } = string.Empty; public string Username { get; set; } = string.Empty;
} }
public struct WindowUserInfo
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct USER_INFO_0
{ {
public string usri0_name; public int LastLogon;
public string Sid;
} }
} }