///////////////////////////////////////////////////// // // // DoCollect() // // // ///////////////////////////////////////////////////// //Description: Collects all files identified in the scan // as malicious and stuffs them into a // password-protected, encrypted ZIP file. // // NOTE: depends on DoSignatureScan() // // //Returns: true if successful ////////////////////////////////////////////////////// private unsafe bool DoCollect() { AgentScanLog.AppendLine(""); AgentScanLog.AppendLine("*********************************************"); AgentScanLog.AppendLine(" COLLECT "); AgentScanLog.AppendLine("*********************************************"); AgentScanLog.AppendLine(""); AgentScanLog.AppendLine("COLLECT: Collecting evidence files..."); //collect the following files to wrap up in archive file: // 1. all identified malware files // 2. infection log (Infection_Log.txt) which we create // 3. usb device list file (USB_Devices.txt) which we create // 4. .net installation log (if exists) // //--------------------------------- // BUILD ZIP NAME //--------------------------------- ZipFileName = Collect.BuildZipName(TotalFindingsCount); ZipFile zip = new ZipFile(ZipFileName); if (AgentSettings.ContainsKey("Reporting_Archive_Password")) { IntPtr pptr = IntPtr.Zero; //do this secure string thing if password specified char[] str = AgentSettings["Reporting_Archive_Password"].ToCharArray(); fixed (char* pChars = str) { ZipPassword = new SecureString(pChars, str.Length); } //decrypt our password in memory pptr = Marshal.SecureStringToBSTR(ZipPassword); zip.Password = Marshal.PtrToStringBSTR(pptr); //zero the password memory Marshal.ZeroFreeBSTR(pptr); } zip.TempFileFolder = "."; ArrayList CollectList = new ArrayList(); int count = 0; AgentScanLog.AppendLine("COLLECT: Searching file signature matches for files..."); //loop through file signatures foreach (CwXML.FileSignatureMatch fileMatch in AgentSignatureMatches.FileSignatureMatches) if (Collect.AddToZip(zip, fileMatch.FullPath)) count++; AgentScanLog.AppendLine("COLLECT: Added " + count + " files."); count = 0; AgentScanLog.AppendLine("COLLECT: Searching registry signature matches for files..."); //loop through registry signatures foreach (CwXML.RegistrySignatureMatch registryMatch in AgentSignatureMatches.RegistrySignatureMatches) if (registryMatch.IsFileOnDisk) if (Collect.AddToZip(zip, registryMatch.RegistryValueData)) count++; AgentScanLog.AppendLine("COLLECT: Added " + count + " files."); AgentScanLog.AppendLine("COLLECT: Generating infection summary report..."); //--------------------------------- // ADD INFECTION LOG //--------------------------------- //2. infection log (Infection_Log.txt) which we create StreamWriter infectionlog = new StreamWriter("InfectionLog.txt"); StringBuilder InfectionSummaryReport = new StringBuilder(); //print infection summary for each signature type RegistryHelper RegHelper = new RegistryHelper(); FileHelper FileHelper = new FileHelper(); MemoryHelper MemHelper = new MemoryHelper(); RegHelper.PrintRegistryFindings(AgentSignatureMatches.RegistrySignatureMatches, ref InfectionSummaryReport); FileHelper.PrintFileFindings(AgentSignatureMatches.FileSignatureMatches, ref InfectionSummaryReport); MemHelper.PrintMemoryFindings(AgentSignatureMatches.MemorySignatureMatches, ref InfectionSummaryReport); infectionlog.WriteLine(InfectionSummaryReport.ToString()); infectionlog.Close(); zip.AddFile("InfectionLog.txt"); AgentScanLog.AppendLine("COLLECT: Enumerating USB Devices..."); //--------------------------------- // ADD USB DEVICES LOG //--------------------------------- //3. usb device list file (USB_Devices.txt) which we create StreamWriter usblogfile = new StreamWriter("USB_Devices.txt"); StringBuilder UsbDevicesReport = new StringBuilder(); Collect.EnumerateUSBDevices(ref UsbDevicesReport); usblogfile.WriteLine(UsbDevicesReport.ToString()); usblogfile.Close(); zip.AddFile("USB_Devices.txt"); //--------------------------------- // ADD .NET LOG //--------------------------------- //4. .net installation log (if exists) try { FileInfo dotnetfxLogfile = new FileInfo("dotnetfx_install_log.txt"); if (dotnetfxLogfile.Exists) zip.AddFile("dotnetfx_install_log.txt"); } catch { } //no biggie.. AgentScanLog.AppendLine("COLLECT: All evidence collected."); AgentScanLog.AppendLine("COLLECT: Saving zip to disk..."); zip.Save(); zip.Dispose(); //at this point zip is closed and written to disk return true; }
public override bool CheckSetting() { return(!( RegistryHelper.IntEquals(EdgeKey, "BackgroundModeEnabled", DesiredValue) )); }
public static void AutoDetectSystemPaths(Settings settings) { if (string.IsNullOrEmpty(settings.FF7Exe) || !File.Exists(settings.FF7Exe)) { Logger.Info("FF7 Exe path is empty or ff7.exe is missing. Auto detecting paths ..."); string registry_path = @"HKEY_LOCAL_MACHINE\SOFTWARE\Square Soft, Inc.\Final Fantasy VII"; string ff7 = null; FF7Version foundVersion = FF7Version.Unknown; try { // first try to detect 1998 game or a "converted" game from the old 7H game converter ff7 = (string)Registry.GetValue(registry_path, "AppPath", null); foundVersion = !string.IsNullOrWhiteSpace(ff7) ? FF7Version.Original98 : FF7Version.Unknown; if (!Directory.Exists(ff7)) { Logger.Warn($"Deleting invalid 'AppPath' registry key since path does not exist: {ff7}"); RegistryHelper.DeleteValueFromKey(registry_path, "AppPath"); // delete old paths set RegistryHelper.DeleteValueFromKey(registry_path, "DataPath"); // delete old paths set RegistryHelper.DeleteValueFromKey(registry_path, "MoviePath"); // delete old paths set foundVersion = FF7Version.Unknown; // set back to Unknown to check other registry keys } if (foundVersion == FF7Version.Unknown) { // next check Steam registry keys and then Re-Release registry keys for installation path ff7 = GameConverter.GetInstallLocation(FF7Version.Steam); foundVersion = !string.IsNullOrWhiteSpace(ff7) ? FF7Version.Steam : FF7Version.Unknown; if (foundVersion == FF7Version.Unknown) { ff7 = GameConverter.GetInstallLocation(FF7Version.ReRelease); foundVersion = !string.IsNullOrWhiteSpace(ff7) ? FF7Version.ReRelease : FF7Version.Unknown; } } string versionStr = foundVersion == FF7Version.Original98 ? $"{foundVersion.ToString()} (or Game Converted)" : foundVersion.ToString(); Logger.Info($"FF7Version Detected: {versionStr} with installation path: {ff7}"); if (!Directory.Exists(ff7)) { Logger.Warn("Found installation path does not exist. Ignoring..."); return; } } catch { // could fail if game not installed } if (foundVersion != FF7Version.Unknown) { settings.SetPathsFromInstallationPath(ff7); // copy ff7.exe to install path if not found since Steam & Re-Release installation does not provide a ff7.exe if (!File.Exists(settings.FF7Exe) && Path.GetFileName(settings.FF7Exe).Equals("ff7.exe", StringComparison.InvariantCultureIgnoreCase)) { Logger.Info($"Copying ff7.exe from {Sys.PathToPatchedExeFolder} to {settings.FF7Exe}"); try { File.Copy(Path.Combine(Sys.PathToPatchedExeFolder, "ff7.exe"), settings.FF7Exe, true); Logger.Info($"\tcopied succesfully."); } catch (Exception ex) { Logger.Error(ex); } } } else { Logger.Warn("Auto detect paths failed - could not get ff7.exe path from Windows Registry."); } } }
private static void CheckRegANSI() { try { if (RegistryHelper.GetRegValue("HKCU", "CONSOLE", "VirtualTerminalLevel") == "" && RegistryHelper.GetRegValue("HKCU", "CONSOLE", "VirtualTerminalLevel") == "") { System.Console.WriteLine(@"ANSI color bit for Windows is not set. If you are execcuting this from a Windows terminal inside the host you should run 'REG ADD HKCU\Console /v VirtualTerminalLevel /t REG_DWORD /d 1' and then start a new CMD"); } } catch (Exception ex) { Beaprint.GrayPrint("Error while checking ansi color registry: " + ex); } }
public string SetDefaultProjectPath(string path) { return(RegistryHelper.SetDefaultProjectPath(path)); }
public static ImmutableArray <OneDriveFolder> LoadOneDriveFolders() { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) == false) { throw new PlatformNotSupportedException(); } const string DisplayNameKey = "DisplayName"; const string UserFolderKey = "UserFolder"; const string AccountsKey = "Accounts"; const string EmailKey = "UserEmail"; var folders = new List <OneDriveFolder>(); using var oneDriveKey = RegistryHelper.GetRegistryKey(RegistryHelper.KeyCurrentUserOneDrive, RegistryHive.CurrentUser); if (oneDriveKey.IsNotNull()) { // Get Accounts using var accountKey = oneDriveKey.GetSubKey(AccountsKey); if (accountKey.IsNotNull() && accountKey.SubKeyCount > 0) { for (var subKeyCount = 0; subKeyCount < accountKey.GetSubKeyNames().Length; subKeyCount++) { using var key = accountKey.OpenSubKey(accountKey.GetSubKeyNames()[subKeyCount]); var folder = new OneDriveFolder(); var directoryValue = key.GetValue <string>(UserFolderKey); if (directoryValue.HasValue()) { folder.DirectoryInfo = new DirectoryInfo(directoryValue); var emailValue = key.GetValue <string>(EmailKey); if (emailValue.IsNotNull()) { folder.UserEmail = emailValue; } // Figure out account type var name = key.GetValue <string>(DisplayNameKey); if (name.HasValue()) { folder.AccountType = OneDriveAccountType.Business; folder.AccountName = name; } else { folder.AccountName = (string)key.GetValue(string.Empty); } if (folder.AccountName.HasValue() && folder.DirectoryInfo.IsNotNull()) { folders.Add(folder); } } } } } return(folders.ToImmutableArray()); }
public override bool CheckSetting() { return(!( RegistryHelper.IntEquals(AppKey, "ToastEnabled", DesiredValue) )); }
public override bool CheckSetting() { return(!( RegistryHelper.IntEquals(HEIPKey, "ImplicitFeedback", DesiredValue) )); }
/// <summary> /// Figures out if the server is in azure and if so gets the azure instance name /// </summary> private void GetAzureInfo() { #if NETFULL if (registryAccessFailure) { return; } try { string rootKey = @"SOFTWARE\Microsoft\Windows Azure\Deployments"; using (var root = RegistryHelper.GetRegistryKey(rootKey)) { if (root != null) { var versions = root.GetSubKeyNames(); string versionKeyPath = rootKey + "\\" + versions.First(); using (var versionKey = RegistryHelper.GetRegistryKey(versionKeyPath)) { var deployments = versionKey.GetSubKeyNames(); if (deployments.Any()) { string deploymentID = deployments.First(); Guid g; bool validDeploymentID = Guid.TryParse(deploymentID, out g); if (!validDeploymentID) { return; } string deploymentKeyPath = versionKeyPath + "\\" + deploymentID; using (var deploymentKey = RegistryHelper.GetRegistryKey(deploymentKeyPath)) { var roles = deploymentKey.GetSubKeyNames(); if (roles.Any()) { this.AppName = roles.First(); string roleKeyPath = deploymentKeyPath + "\\" + this.AppName; using (var roleKey = RegistryHelper.GetRegistryKey(roleKeyPath)) { var instances = roleKey.GetSubKeyNames(); this.AzureInstanceName = instances.First(); } } } } } } } } catch (System.Security.SecurityException ex) { registryAccessFailure = true; } catch (Exception ex) { StackifyLib.Utils.StackifyAPILogger.Log("Error seeing if the app is an azure cloud service\r\n" + ex.ToString(), true); } #endif }
public override bool CheckSetting() { return(!( RegistryHelper.IntEquals(EdgeKey, "DoNotUpdateToEdgeWithChromium", DesiredValue) )); }
private static Dictionary <string, List <string> > GetIEHistFav() { int lastDays = 90; Dictionary <string, List <string> > results = new Dictionary <string, List <string> >() { { "history", new List <string>() }, { "favorites", new List <string>() }, }; DateTime startTime = System.DateTime.Now.AddDays(-lastDays); try { if (MyUtils.IsHighIntegrity()) { string[] SIDs = Registry.Users.GetSubKeyNames(); foreach (string SID in SIDs) { if (SID.StartsWith("S-1-5") && !SID.EndsWith("_Classes")) { Dictionary <string, object> settings = RegistryHelper.GetRegValues("HKU", string.Format("{0}\\SOFTWARE\\Microsoft\\Internet Explorer\\TypedURLs", SID)); if ((settings != null) && (settings.Count > 1)) { foreach (KeyValuePair <string, object> kvp in settings) { byte[] timeBytes = RegistryHelper.GetRegValueBytes("HKU", string.Format("{0}\\SOFTWARE\\Microsoft\\Internet Explorer\\TypedURLsTime", SID), kvp.Key.ToString().Trim()); if (timeBytes != null) { long timeLong = (long)(BitConverter.ToInt64(timeBytes, 0)); DateTime urlTime = DateTime.FromFileTime(timeLong); if (urlTime > startTime) { results["history"].Add(kvp.Value.ToString().Trim()); } } } } } } string userFolder = string.Format("{0}\\Users\\", Environment.GetEnvironmentVariable("SystemDrive")); var dirs = Directory.EnumerateDirectories(userFolder); foreach (var dir in dirs) { string[] parts = dir.Split('\\'); string userName = parts[parts.Length - 1]; if (!(dir.EndsWith("Public") || dir.EndsWith("Default") || dir.EndsWith("Default User") || dir.EndsWith("All Users"))) { string userIEBookmarkPath = string.Format("{0}\\Favorites\\", dir); if (Directory.Exists(userIEBookmarkPath)) { string[] bookmarkPaths = Directory.EnumerateFiles(userIEBookmarkPath, "*.url", SearchOption.AllDirectories).ToArray(); if (bookmarkPaths.Length != 0) { foreach (string bookmarkPath in bookmarkPaths) { using (StreamReader rdr = new StreamReader(bookmarkPath)) { string line; string url = ""; while ((line = rdr.ReadLine()) != null) { if (line.StartsWith("URL=", StringComparison.InvariantCultureIgnoreCase)) { if (line.Length > 4) { url = line.Substring(4); } break; } } results["history"].Add(url.ToString().Trim()); } } } } } } } else { Dictionary <string, object> settings = RegistryHelper.GetRegValues("HKCU", "SOFTWARE\\Microsoft\\Internet Explorer\\TypedURLs"); if ((settings != null) && (settings.Count != 0)) { foreach (KeyValuePair <string, object> kvp in settings) { byte[] timeBytes = RegistryHelper.GetRegValueBytes("HKCU", "SOFTWARE\\Microsoft\\Internet Explorer\\TypedURLsTime", kvp.Key.ToString().Trim()); if (timeBytes != null) { long timeLong = (long)(BitConverter.ToInt64(timeBytes, 0)); DateTime urlTime = DateTime.FromFileTime(timeLong); if (urlTime > startTime) { results["history"].Add(kvp.Value.ToString().Trim()); } } } } string userIEBookmarkPath = string.Format("{0}\\Favorites\\", System.Environment.GetEnvironmentVariable("USERPROFILE")); string[] bookmarkPaths = Directory.EnumerateFiles(userIEBookmarkPath, "*.url", SearchOption.AllDirectories).ToArray(); foreach (string bookmarkPath in bookmarkPaths) { using (StreamReader rdr = new StreamReader(bookmarkPath)) { string line; string url = ""; while ((line = rdr.ReadLine()) != null) { if (line.StartsWith("URL=", StringComparison.InvariantCultureIgnoreCase)) { if (line.Length > 4) { url = line.Substring(4); } break; } } results["favorites"].Add(url.ToString().Trim()); } } } } catch (Exception ex) { Beaprint.GrayPrint(string.Format(" [X] Exception: {0}", ex)); } return(results); }
protected override async Task GetItems(bool getNextPage) { Items = await RegistryHelper.GetApplicationListAsync(Items, getNextPage); }
private void InternalRedetectNetwork() { Logger.Log("RedetectNetwork called"); OnRedetectNetworkStatusChanged(NetworkChangeStatus.Detecting); bool error = false; try { semaphore.WaitOne(); bool atLeastOneFound = false; bool stopAfterFirstMatch = SettingsManager.Instance.GetApplicationSetting(SettingsManager.App_StopAfterFirstNetworkMatch, SettingsManager.Default_StopAfterFirstNetworkMatch); var allActiveInterfaces = NetworkInterface.GetAllNetworkInterfaces().Where(p => p.OperationalStatus == System.Net.NetworkInformation.OperationalStatus.Up); foreach (var nc in SettingsManager.Instance.GetNetworkConfigurations(true)) { if (nc.IsUnknownNetwork) { continue; } #region Network foreach (NetworkInterface ni in allActiveInterfaces) { if (nc.IsNetworkInterfaceDependend && nc.NetworkInterfaceId != ni.Id) { continue; } bool found = false; switch (nc.Method) { case NetworkConfigurationMethod.DNSSuffix: if (ni.GetIPProperties().DnsSuffix.ToUpper().Contains(nc.Query.ToUpper())) { ActivateNetworkConfiguration(nc); found = true; atLeastOneFound = true; } break; case NetworkConfigurationMethod.Gateway: foreach (GatewayIPAddressInformation gi in ni.GetIPProperties().GatewayAddresses) { if (gi.Address.ToString().ToUpper().Contains(nc.Query.ToUpper())) { ActivateNetworkConfiguration(nc); found = true; atLeastOneFound = true; break; } } break; case NetworkConfigurationMethod.GatewayMAC: foreach (GatewayIPAddressInformation gi in ni.GetIPProperties().GatewayAddresses) { var mac = ARPRequest.GetMacAddress(gi.Address); if (mac.ToUpper().Contains(nc.Query.ToUpper())) { ActivateNetworkConfiguration(nc); found = true; atLeastOneFound = true; break; } } break; case NetworkConfigurationMethod.WLANSSID: string wlanSSID = WlanManager.GetCurrentSSID(); if (wlanSSID.ToUpper().Contains(nc.Query.ToUpper())) { ActivateNetworkConfiguration(nc); found = true; atLeastOneFound = true; } break; case NetworkConfigurationMethod.WLANAvailable: if (WlanManager.IsSSIDAvailable(nc.Query)) { ActivateNetworkConfiguration(nc); found = true; atLeastOneFound = true; } break; case NetworkConfigurationMethod.IP: string hostName = Dns.GetHostName(); IPHostEntry ipEntry = Dns.GetHostEntry(hostName); foreach (var item in ipEntry.AddressList) { if (item.ToString().ToUpper().Contains(nc.Query.ToUpper())) { ActivateNetworkConfiguration(nc); found = true; atLeastOneFound = true; break; } } break; case NetworkConfigurationMethod.ServerAvailable: try { var repl = new Ping().Send(nc.Query, 5000); if (repl.Status == IPStatus.Success) { ActivateNetworkConfiguration(nc); found = true; atLeastOneFound = true; } } catch (PingException) { } break; default: break; } if (found) { break; } } #endregion #region DockingState // no network matched, try docking state if (!atLeastOneFound) { if (nc.Method != NetworkConfigurationMethod.DockingStationState) { continue; } var val = RegistryHelper.GetValue(@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\IDConfigDB\CurrentDockInfo", "DockingState"); if (val != null) { //0 = Workstation or Server, 1 = Undocked Laptop, 2 = Docked Laptop var dockState = val.ToString(); if (nc.Query == "1" && dockState == "2") { ActivateNetworkConfiguration(nc); atLeastOneFound = true; } } } #endregion #region Location // no network matched, try location if (!atLeastOneFound) { if (nc.Method != NetworkConfigurationMethod.Location) { continue; } if (locationManager == null) { continue; } var queryArray = nc.Query.Split(','); var currentLocation = locationManager.GetCurrentLocation(); if (currentLocation == null) { continue; } int allQueries = queryArray.Length; int queriesFound = 0; foreach (var query in queryArray) { foreach (var locPart in currentLocation) { if (locPart.Trim().ToUpper().Contains(query.Trim().ToUpper())) { queriesFound++; break; } } } if (allQueries == queriesFound) { ActivateNetworkConfiguration(nc); atLeastOneFound = true; } } #endregion if (atLeastOneFound && stopAfterFirstMatch) { break; } } // nothing found, activate "Unknown Network" if (!atLeastOneFound) { var unknown = SettingsManager.Instance.GetNetworkConfiguration(SwitcherActionBase.DeactivateNetworkId); ActivateNetworkConfiguration(unknown); } } catch (Exception ex) { Logger.Log(ex.Message, ex); error = true; } finally { semaphore.Release(); Logger.Log("RedetectNetwork completed"); if (error) { OnRedetectNetworkStatusChanged(NetworkChangeStatus.Error); } else { OnRedetectNetworkStatusChanged(NetworkChangeStatus.Completed); } } }
private static void WriteSuccessTemplate(EngineState s, CodeType codeType, string rawCode, RegistryKey hKey, RegistryValueKind compKind, string keyPath, string valueName, object comp, CompatOption opts = null, ErrorCheck check = ErrorCheck.Success) { if (opts == null) { EngineTests.Eval(s, rawCode, codeType, check); } else { EngineTests.Eval(s, rawCode, codeType, check, opts); } if (check == ErrorCheck.Success || check == ErrorCheck.Warning || check == ErrorCheck.Overwrite) { using (RegistryKey subKey = hKey.OpenSubKey(keyPath, false)) { Assert.IsNotNull(subKey); RegistryValueKind kind = subKey.GetValueKind(valueName); Assert.IsTrue(kind == compKind); object valueData; if (kind == RegistryValueKind.Unknown) { valueData = RegistryHelper.RegGetValue(hKey, keyPath, valueName, RegistryValueKind.Unknown); } else { valueData = subKey.GetValue(valueName, null, RegistryValueOptions.DoNotExpandEnvironmentNames); } Assert.IsNotNull(valueData); switch (kind) { case RegistryValueKind.Unknown: { // RegWriteEx byte[] destBin = (byte[])valueData; byte[] compBin = (byte[])comp; Assert.IsTrue(destBin.SequenceEqual(compBin)); } break; case RegistryValueKind.None: break; case RegistryValueKind.String: case RegistryValueKind.ExpandString: { string destStr = (string)valueData; string compStr = (string)comp; Assert.IsTrue(destStr.Equals(compStr, StringComparison.Ordinal)); } break; case RegistryValueKind.MultiString: { string[] destStrs = (string[])valueData; string[] compStrs = (string[])comp; Assert.IsTrue(destStrs.Length == compStrs.Length); for (int i = 0; i < destStrs.Length; i++) { Assert.IsTrue(destStrs[i].Equals(compStrs[i], StringComparison.Ordinal)); } } break; case RegistryValueKind.Binary: { byte[] destBin = (byte[])valueData; byte[] compBin = (byte[])comp; Assert.IsTrue(destBin.SequenceEqual(compBin)); } break; case RegistryValueKind.DWord: { uint destInt = (uint)(int)valueData; uint compInt = (uint)comp; Assert.IsTrue(destInt == compInt); } break; case RegistryValueKind.QWord: { ulong destInt = (ulong)(long)valueData; ulong compInt = (ulong)comp; Assert.IsTrue(destInt == compInt); } break; default: Assert.Fail(); break; } } } }
///////////////////////////////////////////////////// // // // DoSignatureScan() // // // ///////////////////////////////////////////////////// //Description: Scans memory, disk and registry for // given signatures. Stores results in // class global results object. // //Returns: true if successful ////////////////////////////////////////////////////// private unsafe bool DoSignatureScan() { AgentScanLog.AppendLine(""); AgentScanLog.AppendLine("*********************************************"); AgentScanLog.AppendLine(" SIGNATURE SCAN "); AgentScanLog.AppendLine("*********************************************"); AgentScanLog.AppendLine(""); // //============================================= // SCAN FOR REGISTRY SIGNATURES //============================================= // RegistryHelper RegistryScanner = new RegistryHelper(); //mount NTUSER.DAT files (so every user's SID is mounted in HKEY_USERS) RegistryScanner.LoadNtUserDatFiles(false); if (AgentRegistrySignatures.Length > 0) { AgentScanLog.AppendLine("SCAN: Scanning registry for infections..."); //optionally scan HKCR for potentially malicious GUIDs //nb: if any found, auto added to malware_info.GUIDs container if (AgentSettings.ContainsKey("Option_Scan_GUIDs")) if (AgentSettings["Option_Scan_GUIDs"] == "True") RegistryScanner.ScanForMaliciousGUIDs(); //create a static GUID in our AgentRegistryGuidSignatures for every dynamic GUID RegistryScanner.LoadDynamicGUIDs(ref AgentRegistryGuidSignatures); // //perform actual scan // //initialization here is irrelevant; it will be allocated in the function RegistryScanner.ScanForRegistrySignatures(AgentRegistrySignatures, AgentRegistryGuidSignatures, ref AgentSignatureMatches.RegistrySignatureMatches); //append scan log AgentScanLog.AppendLine(RegistryScanner.RegistryHelperLog.ToString()); AgentScanLog.AppendLine("SCAN: Registry scan complete."); } // //============================================= // SCAN FOR FILE SIGNATURES //============================================= // FileHelper FileScanner = new FileHelper(); if (AgentFileSignatures.Length > 0) { AgentScanLog.AppendLine("SCAN: Scanning all attached disks for file signatures..."); //perform scan FileScanner.ScanForFileSignatures(AgentFileSignatures, ref AgentSignatureMatches.FileSignatureMatches); //append the file scan log AgentScanLog.AppendLine(FileScanner.FileHelperLog.ToString()); AgentScanLog.AppendLine("SCAN: Disk scans complete."); } // //============================================= // SCAN FOR MEMORY SIGNATURES //============================================= // MemoryHelper MemoryScanner = new MemoryHelper(); if (AgentMemorySignatures.Length > 0) { AgentScanLog.AppendLine("SCAN: Scanning active processes for memory signatures..."); //setup a few scan parameters based on agent settings // //search cmd line parameters? bool SearchCmdLine = false; if (AgentSettings.ContainsKey("MemorySignatures_SearchCmdLine")) if (AgentSettings["MemorySignatures_SearchCmdLine"] == "True") SearchCmdLine = true; //search heap space? bool SearchHeap = false; if (AgentSettings.ContainsKey("MemorySignatures_SearchHeapSpace")) if (AgentSettings["MemorySignatures_SearchHeapSpace"] == "True") SearchHeap = true; //search loaded module list (dlls)? bool SearchLoadedModuleList = false; if (AgentSettings.ContainsKey("MemorySignatures_SearchLoadedModules")) if (AgentSettings["MemorySignatures_SearchLoadedModules"] == "True") SearchLoadedModuleList = true; //search registry findings in process? bool SearchForRegistryFindings = false; if (AgentSettings.ContainsKey("MemorySignatures_UseRegistryFindings")) if (AgentSettings["MemorySignatures_UseRegistryFindings"] == "True") SearchForRegistryFindings = true; //perform scan MemoryScanner.ScanForMemorySignatures(AgentSignatureMatches.RegistrySignatureMatches, AgentMemorySignatures, ref AgentSignatureMatches.MemorySignatureMatches, SearchCmdLine, SearchHeap, SearchLoadedModuleList, SearchForRegistryFindings); //append the memory scanner log AgentScanLog.AppendLine(MemoryScanner.MemoryHelperLog.ToString()); AgentScanLog.AppendLine("SCAN: Process scan complete."); } //calculate total # of findings TotalFindingsCount = 0; if (AgentSignatureMatches.RegistrySignatureMatches != null) TotalFindingsCount += AgentSignatureMatches.RegistrySignatureMatches.Length; if (AgentSignatureMatches.FileSignatureMatches != null) TotalFindingsCount += AgentSignatureMatches.FileSignatureMatches.Length; if (AgentSignatureMatches.MemorySignatureMatches != null) TotalFindingsCount += AgentSignatureMatches.MemorySignatureMatches.Length; //unload NTUSER.DAT files RegistryScanner.LoadNtUserDatFiles(true); /* StreamWriter sw = new StreamWriter("AgentScanLog.txt"); sw.WriteLine(AgentScanLog.ToString()); sw.Close();*/ return true; }
public override bool CheckSetting() { return(!( RegistryHelper.IntEquals(SharingKey, "DODownloadMode", DesiredValue) )); }
public void RegCopy() { EngineState s = EngineTests.CreateEngineState(); string singleSrcSet = Path.Combine(RegCopyPath, "Src"); string multiSrcSet1 = Path.Combine(RegCopyPath, "Set*"); string multiSrcSet2 = Path.Combine(RegCopyPath, "Set?0"); string destSet = Path.Combine(RegCopyPath, "Dest"); // Success SingleTemplate($@"RegCopy,HKCU,{singleSrcSet},HKCU,{destSet}", Registry.CurrentUser, singleSrcSet, destSet); WildcardTemplate($@"RegCopy,HKCU,{multiSrcSet1},HKCU,{destSet},WILDCARD", Registry.CurrentUser, RegCopyPath, new string[] { "Set10", "Set20", "Set31" }, destSet, new string[] { "Set10", "Set20", "Set31" }); WildcardTemplate($@"RegCopy,HKCU,{multiSrcSet2},HKCU,{destSet},WILDCARD", Registry.CurrentUser, RegCopyPath, new string[] { "Set10", "Set20", "Set31" }, destSet, new string[] { "Set10", "Set20" }); // Error SingleTemplate($@"RegCopy,HKCU,{singleSrcSet},HKCU,{destSet},WILDCARD", Registry.CurrentUser, singleSrcSet, destSet, ErrorCheck.RuntimeError); WildcardTemplate($@"RegCopy,HKCU,{multiSrcSet1},HKCU,{destSet}", Registry.CurrentUser, RegCopyPath, new string[] { "Set10", "Set20", "Set31" }, destSet, new string[] { "Set10", "Set20", "Set31" }, ErrorCheck.RuntimeError); WildcardTemplate($@"RegCopy,HKCU,{multiSrcSet2},HKCU,{destSet}", Registry.CurrentUser, RegCopyPath, new string[] { "Set10", "Set20", "Set31" }, destSet, new string[] { "Set10", "Set20" }, ErrorCheck.RuntimeError); #region CreateRegValues, CheckRegValues void CreateRegValues(RegistryKey hKey, string subKeyPath) { using (RegistryKey key = hKey.CreateSubKey(subKeyPath, true)) { Assert.IsNotNull(key); key.SetValue("None", new byte[0], RegistryValueKind.None); key.SetValue("Binary", new byte[] { 0x01, 0x02, 0x03 }, RegistryValueKind.Binary); key.SetValue("Integer", 1225, RegistryValueKind.DWord); key.SetValue("String", "English", RegistryValueKind.String); // .Net Framework's RegistryKey.SetValue do not allow arbitrary type, so call Win32 API directly. RegistryHelper.RegSetValue(hKey, subKeyPath, "Strange10", new byte[0], 0x100000); RegistryHelper.RegSetValue(hKey, subKeyPath, "Strange20", new byte[] { 0x01, 0x02, 0x03 }, 0x200000); using (RegistryKey subKey = key.CreateSubKey("SubKey", true)) { Assert.IsNotNull(subKey); subKey.SetValue("Unicode", "한국어", RegistryValueKind.ExpandString); subKey.SetValue("WinDir", "%WinDir%", RegistryValueKind.ExpandString); } } } void CheckRegValues(RegistryKey hKey, string subKeyPath) { using (RegistryKey key = hKey.OpenSubKey(subKeyPath, false)) { Assert.IsNotNull(key); byte[] bin = key.GetValue("None") as byte[]; Assert.IsNotNull(bin); Assert.AreEqual(0, bin.Length); bin = key.GetValue("Binary") as byte[]; Assert.IsNotNull(bin); Assert.IsTrue(bin.SequenceEqual(new byte[] { 0x01, 0x02, 0x03 })); int dword = (int)key.GetValue("Integer"); Assert.AreEqual(dword, 1225); string str = key.GetValue("String") as string; Assert.IsNotNull(str); Assert.IsTrue(str.Equals("English", StringComparison.Ordinal)); // .Net Framework's RegistryKey.GetValue cannot handle arbitrary type. Call Win32 API directly. bin = RegistryHelper.RegGetValue(hKey, subKeyPath, "Strange10", RegistryValueKind.Unknown) as byte[]; Assert.IsNotNull(bin); Assert.AreEqual(0, bin.Length); // .Net Framework's RegistryKey.GetValue cannot handle arbitrary type. Call Win32 API directly. bin = RegistryHelper.RegGetValue(hKey, subKeyPath, "Strange20", RegistryValueKind.Unknown) as byte[]; Assert.IsNotNull(bin); Assert.IsTrue(bin.SequenceEqual(new byte[] { 0x01, 0x02, 0x03 })); using (RegistryKey subKey = key.OpenSubKey("SubKey", false)) { Assert.IsNotNull(subKey); str = subKey.GetValue("Unicode") as string; Assert.IsNotNull(str); Assert.IsTrue(str.Equals("한국어", StringComparison.Ordinal)); str = subKey.GetValue("WinDir", null, RegistryValueOptions.DoNotExpandEnvironmentNames) as string; Assert.IsNotNull(str); Assert.IsTrue(str.Equals("%WinDir%", StringComparison.Ordinal)); } } } #endregion #region Template void SingleTemplate(string rawCode, RegistryKey hKey, string srcKeyPath, string destKeyPath, ErrorCheck check = ErrorCheck.Success) { // RegCopy,<SrcKey>,<SrcKeyPath>,<DestKey>,<DestKeyPath>,[WILDCARD] Registry.CurrentUser.DeleteSubKeyTree(RegCopyPath, false); try { CreateRegValues(hKey, srcKeyPath); EngineTests.Eval(s, rawCode, CodeType.RegCopy, check); if (check == ErrorCheck.Success || check == ErrorCheck.Warning) { CheckRegValues(hKey, destKeyPath); } } finally { Registry.CurrentUser.DeleteSubKeyTree(RegCopyPath, false); } } void WildcardTemplate(string rawCode, RegistryKey hKey, string srcKeyPath, string[] srcTargets, string destKeyPath, string[] destTargets, ErrorCheck check = ErrorCheck.Success) { // RegCopy,<SrcKey>,<SrcKeyPath>,<DestKey>,<DestKeyPath>,[WILDCARD] Registry.CurrentUser.DeleteSubKeyTree(RegCopyPath, false); try { foreach (string target in srcTargets) { string t = Path.Combine(srcKeyPath, target); CreateRegValues(hKey, t); } EngineTests.Eval(s, rawCode, CodeType.RegCopy, check); if (check == ErrorCheck.Success || check == ErrorCheck.Warning) { foreach (string target in destTargets) { string t = Path.Combine(destKeyPath, target); CheckRegValues(hKey, t); } } } finally { Registry.CurrentUser.DeleteSubKeyTree(RegCopyPath, false); } } #endregion }
/// <summary> /// Register file associations /// </summary> /// <param name="extensions">Extension string, ex: *.png;*.svg;</param> public static void SetRegistryAssociations(string extensions) { DeleteRegistryAssociations(extensions); RegistryHelper reg = new RegistryHelper(); reg.ShowError = true; reg.BaseRegistryKey = Registry.LocalMachine; // Register the application to Registry reg.SubKey = @"SOFTWARE\RegisteredApplications"; if (!reg.Write("ImageGlass", @"SOFTWARE\PhapSoftware\ImageGlass\Capabilities")) { return; } // Register Capabilities info reg.SubKey = @"SOFTWARE\PhapSoftware\ImageGlass\Capabilities"; if (!reg.Write("ApplicationName", "ImageGlass")) { return; } if (!reg.Write("ApplicationIcon", $"\"{Path.Combine(GlobalSetting.StartUpDir, "ImageGlass.exe")}\", 0")) { return; } if (!reg.Write("ApplicationDescription", "A lightweight, versatile image viewer")) { return; } // Register File Associations var extList = extensions.Split("*;".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); foreach (var ext in extList) { var keyname = "ImageGlass.AssocFile" + ext.ToUpper(); reg.SubKey = @"SOFTWARE\PhapSoftware\ImageGlass\Capabilities\FileAssociations"; if (!reg.Write(ext, keyname)) { return; } // Config the File Associations - Icon var iconPath = Path.Combine(GlobalSetting.StartUpDir, @"Ext-Icons\" + ext.ToUpper().Substring(1) + ".ico"); if (!File.Exists(iconPath)) { iconPath = Path.Combine(GlobalSetting.StartUpDir, "ImageGlass.exe"); } reg.SubKey = @"SOFTWARE\Classes\" + keyname + @"\DefaultIcon"; if (!reg.Write("", $"\"{iconPath}\", 0")) { return; } // Config the File Associations - Friendly App Name reg.SubKey = @"SOFTWARE\Classes\" + keyname + @"\shell\open"; if (!reg.Write("FriendlyAppName", "ImageGlass")) { return; } // Config the File Associations - Command reg.SubKey = @"SOFTWARE\Classes\" + keyname + @"\shell\open\command"; if (!reg.Write("", $"\"{Path.Combine(GlobalSetting.StartUpDir, "ImageGlass.exe")}\" \"%1\"")) { return; } } }
public override bool CheckSetting() { return(!( RegistryHelper.IntEquals(CortanaKey, "AllowCortana", DesiredValue) )); }
public bool IsServiceInstalled() { return(RegistryHelper.CheckInstalled(RegistryDisplayName)); }
public IIoTPlatformTestContext() { Configuration = GetConfiguration(); RegistryHelper = new RegistryHelper(this); OutputHelper = null; }
////////////////////////////////////// /////// Get Autorun Registry //////// ////////////////////////////////////// /// Find Autorun registry where you have write or equivalent access private static IEnumerable <Dictionary <string, string> > GetRegistryAutoRuns(Dictionary <string, string> NtAccountNames) { List <Dictionary <string, string> > results = new List <Dictionary <string, string> >(); try { //Add the keyvalues inside autorunLocationsKeys to autorunLocations foreach (List <string> autorunLocationKey in autorunLocationsKeys) { List <string> subkeys = RegistryHelper.GetRegSubkeys(autorunLocationKey[0], autorunLocationKey[1]).ToList(); foreach (string keyname in subkeys) { string clsid_name = keyname; Match clsid = Regex.Match(keyname, @"^\W*(\{[\w\-]+\})\W*"); if (clsid.Groups.Count > 1) //Sometime the CLSID is bad writting and this kind of fix common mistakes { clsid_name = clsid.Groups[1].ToString(); } autorunLocations.Add(autorunLocationKey.Count > 2 ? new List <string> { autorunLocationKey[0], autorunLocationKey[1] + "\\" + clsid_name, autorunLocationKey[2] } : new List <string> { autorunLocationKey[0], autorunLocationKey[1] + "\\" + clsid_name }); } } //Read registry and get values foreach (List <string> autorunLocation in autorunLocations) { Dictionary <string, object> settings = RegistryHelper.GetRegValues(autorunLocation[0], autorunLocation[1]); if ((settings != null) && (settings.Count != 0)) { foreach (KeyValuePair <string, object> kvp in settings) { RegistryKey key = null; if ("HKLM" == autorunLocation[0]) { key = Registry.LocalMachine.OpenSubKey(autorunLocation[1]); } else { key = Registry.CurrentUser.OpenSubKey(autorunLocation[1]); } if (autorunLocation.Count > 2 && kvp.Key != autorunLocation[2]) { continue; //If only interested on 1 key of the registry and it's that one, continue } string orig_filepath = Environment.ExpandEnvironmentVariables(string.Format("{0}", kvp.Value)); string filepath = orig_filepath; if (MyUtils.GetExecutableFromPath(Environment.ExpandEnvironmentVariables(string.Format("{0}", kvp.Value))).Length > 0) { filepath = MyUtils.GetExecutableFromPath(filepath); } string filepath_cleaned = filepath.Replace("'", "").Replace("\"", ""); string folder = Path.GetDirectoryName(filepath_cleaned); try { //If the path doesn't exist, pass if (File.GetAttributes(filepath_cleaned).HasFlag(FileAttributes.Directory)) { //If the path is already a folder, change the values of the params orig_filepath = ""; folder = filepath_cleaned; } } catch { } results.Add(new Dictionary <string, string>() { { "Reg", autorunLocation[0] + "\\" + autorunLocation[1] }, { "RegKey", kvp.Key }, { "Folder", folder }, { "File", orig_filepath }, { "RegPermissions", string.Join(", ", PermissionsHelper.GetMyPermissionsR(key, Checks.Checks.CurrentUserSiDs)) }, { "interestingFolderRights", string.Join(", ", PermissionsHelper.GetPermissionsFolder(folder, Checks.Checks.CurrentUserSiDs)) }, { "interestingFileRights", orig_filepath.Length > 1 ? string.Join(", ", PermissionsHelper.GetPermissionsFile(orig_filepath, Checks.Checks.CurrentUserSiDs)) : "" }, { "isUnquotedSpaced", MyUtils.CheckQuoteAndSpace(filepath).ToString() } }); } } } //Check the autoruns that depends on CLSIDs foreach (List <string> autorunLocation in autorunLocationsKeysCLSIDs) { List <string> CLSIDs = RegistryHelper.GetRegSubkeys(autorunLocation[0], autorunLocation[1]).ToList(); foreach (string clsid in CLSIDs) { string reg = autorunLocation[1] + "\\" + clsid; RegistryKey key = null; if ("HKLM" == autorunLocation[0]) { key = Registry.LocalMachine.OpenSubKey(reg); } else { key = Registry.CurrentUser.OpenSubKey(reg); } string orig_filepath = MyUtils.GetCLSIDBinPath(clsid); if (string.IsNullOrEmpty(orig_filepath)) { continue; } orig_filepath = Environment.ExpandEnvironmentVariables(orig_filepath).Replace("'", "").Replace("\"", ""); string folder = Path.GetDirectoryName(orig_filepath); results.Add(new Dictionary <string, string>() { { "Reg", autorunLocation[0] + "\\" + reg }, { "RegKey", "" }, { "Folder", folder }, { "File", orig_filepath }, { "RegPermissions", string.Join(", ", PermissionsHelper.GetMyPermissionsR(key, Checks.Checks.CurrentUserSiDs)) }, { "interestingFolderRights", string.Join(", ", PermissionsHelper.GetPermissionsFolder(folder, Checks.Checks.CurrentUserSiDs)) }, { "interestingFileRights", orig_filepath.Length > 1 ? string.Join(", ", PermissionsHelper.GetPermissionsFile(orig_filepath, Checks.Checks.CurrentUserSiDs)) : "" }, { "isUnquotedSpaced", MyUtils.CheckQuoteAndSpace(orig_filepath).ToString() } }); } } } catch (Exception ex) { Beaprint.PrintException(ex.Message); } return(results); }
/// <summary> /// Executes the task /// </summary> /// <returns></returns> public override bool Execute() { var configuration = Microsoft.Practices.RecipeFramework.GuidancePackage.ReadConfiguration(Path.GetFileName(this.ConfigurationFile.ItemSpec)); var cacheFiles = new List <string>(); var addItemsProjectFactories = new List <Guid>(); foreach (var vsTemplate in this.Templates) { var templateMetadata = new TemplateMetaData( Path.Combine(this.OutputPath, vsTemplate.ItemSpec), new CommandID(new Guid(configuration.Guid), this.Templates.ToList().IndexOf(vsTemplate) + 1), configuration.Name, RegistryHelper.GetCurrentVsRegistryKey(false)); templateMetadata.Register(true); if (templateMetadata.Kind == Common.TemplateKind.ProjectItem && !addItemsProjectFactories.Contains(templateMetadata.ProjectFactory)) { addItemsProjectFactories.Add(templateMetadata.ProjectFactory); } cacheFiles.AddRange(Directory.EnumerateFiles(templateMetadata.CacheBaseBath)); } var registryTemplate = new GuidancePackageRegistryTemplate(); registryTemplate.GuidancePackage = configuration; registryTemplate.SatelliteDllFile = Path.GetFileName(this.SatelliteDllFile); registryTemplate.VsTemplates = this.Templates; registryTemplate.AddItemsProjectFactories = addItemsProjectFactories; registryTemplate.OutputPath = Path.GetFullPath(this.OutputPath); var content = registryTemplate.TransformText(); this.CacheFiles = cacheFiles.Distinct().Select(file => { var item = new TaskItem(file); item.SetMetadata("VSIXSubPath", Path.GetDirectoryName(file).Remove(0, this.OutputPath.Length)); // Fix the output path in the .vsz file if (".vsz".Equals(Path.GetExtension(item.ItemSpec), StringComparison.InvariantCultureIgnoreCase)) { var vsz = File.ReadAllText(file).Replace("Param=\"" + this.OutputPath, "Param=\""); File.Delete(file); File.WriteAllText(file, vsz); } return(item); } ).ToArray(); if (File.Exists(this.OutputFile)) { File.Delete(this.OutputFile); } File.WriteAllText(this.OutputFile, content); return(true); }
protected override async void OnNavigatedTo(NavigationEventArgs eventArgs) { base.OnNavigatedTo(eventArgs); // Add item jumping handler App.mainWindow.Content.CharacterReceived += Content_CharacterReceived; navigationArguments = (NavigationArguments)eventArgs.Parameter; ParentShellPageInstance = navigationArguments.AssociatedTabInstance; IsItemSelected = false; FolderSettings.LayoutModeChangeRequested += FolderSettings_LayoutModeChangeRequested; ParentShellPageInstance.FilesystemViewModel.IsFolderEmptyTextDisplayed = false; FolderSettings.SetLayoutInformation(); if (!navigationArguments.IsSearchResultPage) { ParentShellPageInstance.NavigationToolbar.CanRefresh = true; string previousDir = ParentShellPageInstance.FilesystemViewModel.WorkingDirectory; await ParentShellPageInstance.FilesystemViewModel.SetWorkingDirectoryAsync(navigationArguments.NavPathParam); // pathRoot will be empty on recycle bin path var workingDir = ParentShellPageInstance.FilesystemViewModel.WorkingDirectory; string pathRoot = Path.GetPathRoot(workingDir); if (string.IsNullOrEmpty(pathRoot) || workingDir == pathRoot || workingDir.StartsWith(AppSettings.RecycleBinPath)) // Can't go up from recycle bin { ParentShellPageInstance.NavigationToolbar.CanNavigateToParent = false; } else { ParentShellPageInstance.NavigationToolbar.CanNavigateToParent = true; } ParentShellPageInstance.InstanceViewModel.IsPageTypeRecycleBin = workingDir.StartsWith(App.AppSettings.RecycleBinPath); ParentShellPageInstance.InstanceViewModel.IsPageTypeMtpDevice = workingDir.StartsWith("\\\\?\\"); ParentShellPageInstance.InstanceViewModel.IsPageTypeSearchResults = false; ParentShellPageInstance.NavigationToolbar.PathControlDisplayText = navigationArguments.NavPathParam; if (!navigationArguments.IsLayoutSwitch) { ParentShellPageInstance.FilesystemViewModel.RefreshItems(previousDir); } else { ParentShellPageInstance.NavigationToolbar.CanGoForward = false; } } else { ParentShellPageInstance.NavigationToolbar.CanRefresh = false; ParentShellPageInstance.NavigationToolbar.CanGoForward = false; ParentShellPageInstance.NavigationToolbar.CanGoBack = true; // Impose no artificial restrictions on back navigation. Even in a search results page. ParentShellPageInstance.NavigationToolbar.CanNavigateToParent = false; ParentShellPageInstance.InstanceViewModel.IsPageTypeRecycleBin = false; ParentShellPageInstance.InstanceViewModel.IsPageTypeMtpDevice = false; ParentShellPageInstance.InstanceViewModel.IsPageTypeSearchResults = true; if (!navigationArguments.IsLayoutSwitch) { await ParentShellPageInstance.FilesystemViewModel.AddSearchResultsToCollection(navigationArguments.SearchResults, navigationArguments.SearchPathParam); } } ParentShellPageInstance.InstanceViewModel.IsPageTypeNotHome = true; // show controls that were hidden on the home page FolderSettings.IsLayoutModeChanging = false; cachedNewContextMenuEntries = await RegistryHelper.GetNewContextMenuEntries(); FocusFileList(); // Set focus on layout specific file list control }
protected override async void OnNavigatedTo(NavigationEventArgs eventArgs) { base.OnNavigatedTo(eventArgs); // Add item jumping handler Window.Current.CoreWindow.CharacterReceived += Page_CharacterReceived; var parameters = (NavigationArguments)eventArgs.Parameter; isSearchResultPage = parameters.IsSearchResultPage; ParentShellPageInstance = parameters.AssociatedTabInstance; IsItemSelected = false; FolderSettings.LayoutModeChangeRequested += FolderSettings_LayoutModeChangeRequested; ParentShellPageInstance.FilesystemViewModel.IsFolderEmptyTextDisplayed = false; if (!isSearchResultPage) { ParentShellPageInstance.NavigationToolbar.CanRefresh = true; ParentShellPageInstance.NavigationToolbar.CanCopyPathInPage = true; string previousDir = ParentShellPageInstance.FilesystemViewModel.WorkingDirectory; await ParentShellPageInstance.FilesystemViewModel.SetWorkingDirectoryAsync(parameters.NavPathParam); // pathRoot will be empty on recycle bin path var workingDir = ParentShellPageInstance.FilesystemViewModel.WorkingDirectory; string pathRoot = Path.GetPathRoot(workingDir); if (string.IsNullOrEmpty(pathRoot) || workingDir == pathRoot) { ParentShellPageInstance.NavigationToolbar.CanNavigateToParent = false; } else { ParentShellPageInstance.NavigationToolbar.CanNavigateToParent = true; } ParentShellPageInstance.InstanceViewModel.IsPageTypeRecycleBin = workingDir.StartsWith(App.AppSettings.RecycleBinPath); ParentShellPageInstance.InstanceViewModel.IsPageTypeMtpDevice = workingDir.StartsWith("\\\\?\\"); MainPage.MultitaskingControl?.UpdateSelectedTab(new DirectoryInfo(workingDir).Name, workingDir, false); ParentShellPageInstance.FilesystemViewModel.RefreshItems(previousDir); ParentShellPageInstance.NavigationToolbar.PathControlDisplayText = parameters.NavPathParam; ParentShellPageInstance.InstanceViewModel.IsPageTypeSearchResults = false; } else { ParentShellPageInstance.NavigationToolbar.CanRefresh = false; ParentShellPageInstance.NavigationToolbar.CanCopyPathInPage = false; ParentShellPageInstance.NavigationToolbar.CanNavigateToParent = false; ParentShellPageInstance.InstanceViewModel.IsPageTypeRecycleBin = false; ParentShellPageInstance.InstanceViewModel.IsPageTypeMtpDevice = false; ParentShellPageInstance.InstanceViewModel.IsPageTypeSearchResults = true; MainPage.MultitaskingControl?.UpdateSelectedTab(null, null, true); ParentShellPageInstance.FilesystemViewModel.AddSearchResultsToCollection(parameters.SearchResults, parameters.SearchPathParam); } ParentShellPageInstance.InstanceViewModel.IsPageTypeNotHome = true; // show controls that were hidden on the home page ParentShellPageInstance.Clipboard_ContentChanged(null, null); FolderSettings.IsLayoutModeChanging = false; cachedNewContextMenuEntries = await RegistryHelper.GetNewContextMenuEntries(); FocusFileList(); // Set focus on layout specific file list control }
void PrintWSLDistributions() { Beaprint.MainPrint("Looking for Linux shells/distributions - wsl.exe, bash.exe"); List <string> linuxShells = InterestingFiles.InterestingFiles.GetLinuxShells(); string hive = "HKCU"; string basePath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Lxss"; const string linpeas = "linpeas.sh"; if (linuxShells.Any()) { foreach (string path in linuxShells) { Beaprint.BadPrint(" " + path); } Beaprint.BadPrint(""); try { var wslKeys = RegistryHelper.GetRegSubkeys(hive, basePath); if (wslKeys.Any()) { const string distribution = "Distribution"; const string rootDirectory = "Root directory"; const string runWith = "Run command"; var colors = new Dictionary <string, string>(); new List <string> { linpeas, distribution, rootDirectory, runWith }.ForEach(str => colors.Add(str, Beaprint.ansi_color_bad)); Beaprint.BadPrint(" Found installed WSL distribution(s) - listed below"); Beaprint.AnsiPrint($" Run {linpeas} in your WSL distribution(s) home folder(s).\n", colors); foreach (var wslKey in wslKeys) { try { string distributionSubKey = $"{basePath}\\{wslKey}"; string distributionRootDirectory = $"{RegistryHelper.GetRegValue(hive, distributionSubKey, "BasePath")}\\rootfs"; string distributionName = RegistryHelper.GetRegValue(hive, distributionSubKey, "DistributionName"); Beaprint.AnsiPrint($" {distribution}: \"{distributionName}\"\n" + $" {rootDirectory}: \"{distributionRootDirectory}\"\n" + $" {runWith}: wsl.exe --distribution \"{distributionName}\"", colors); Beaprint.PrintLineSeparator(); } catch (Exception) { } } // try to run linpeas.sh in the default distribution Beaprint.ColorPrint($" Running {linpeas} in the default distribution\n" + $" Using linpeas.sh URL: {Checks.LinpeasUrl}", Beaprint.LBLUE); if (Checks.IsLinpeas) { try { WSL.RunLinpeas(Checks.LinpeasUrl); } catch (Exception ex) { Beaprint.PrintException($" Unable to run linpeas.sh: {ex.Message}"); } } else { Beaprint.ColorPrint(" [!] Check skipped, if you want to run it, please specify '-linpeas=[url]' argument", Beaprint.YELLOW); } } else { Beaprint.GoodPrint(" WSL - no installed Linux distributions found."); } } catch (Exception) { } } }
public override bool CheckSetting() { return(!( RegistryHelper.StringEquals(AppKey, "Value", DesiredValue) )); }
public override bool CheckSetting() { return(!( RegistryHelper.IntEquals(DiagnosticKey, "TailoredExperiencesWithDiagnosticDataEnabled", DesiredValue) )); }
public override bool CheckSetting() { return(!( RegistryHelper.IntEquals(GameBarKey, "AllowGameDVR", DesiredValue) )); }
private void CheckRegistryWritebacks(RegistryHelper reg, CmdApp app, OpenTarget target) { this.CheckWritebacks(reg, null, app, target); }
///////////////////////////////////////////////////// // // // DoMitigate() // // // ///////////////////////////////////////////////////// //Description: Performs various mitigation tasks, such // as usb device disabling. // // NOTE: depends on DoSignatureScan() // //Returns: true if successful ////////////////////////////////////////////////////// private unsafe bool DoMitigate() { AgentScanLog.AppendLine(""); AgentScanLog.AppendLine("*********************************************"); AgentScanLog.AppendLine(" MITIGATE/CLEAN "); AgentScanLog.AppendLine("*********************************************"); AgentScanLog.AppendLine(""); //remove file references we found in registry from disk? bool removeReferences = false; if (AgentSettings.ContainsKey("Option_Delete_MalwareFoundInRegistry")) if (AgentSettings["Option_Delete_MalwareFoundInRegistry"] == "True") removeReferences = true; //instantiate our helper classes RegistryHelper RegHelper = new RegistryHelper(); FileHelper FileHelper = new FileHelper(); MemoryHelper MemHelper = new MemoryHelper(); if (AgentSignatureMatches.RegistrySignatureMatches != null) if (AgentSignatureMatches.RegistrySignatureMatches.Length > 0) RegHelper.CleanRegistryFindings(ref AgentSignatureMatches.RegistrySignatureMatches, removeReferences); if (AgentSignatureMatches.FileSignatureMatches != null) if (AgentSignatureMatches.FileSignatureMatches.Length > 0) FileHelper.CleanFileFindings(ref AgentSignatureMatches.FileSignatureMatches); if (AgentSignatureMatches.MemorySignatureMatches != null) if (AgentSignatureMatches.MemorySignatureMatches.Length > 0) MemHelper.CleanMemoryFindings(ref AgentSignatureMatches.MemorySignatureMatches); //============================================= // Disable/Disassociate autorun //============================================= if (AgentSettings["Option_Disable_Autorun"] == "True") Mitigate.DisableAndDisassociateAutorun(); //============================================= // Disable USB //============================================= if (AgentSettings["Option_Disable_USB"] == "True") Mitigate.DisableUseOfUSBDevices(); AgentScanLog.AppendLine("MITIGATE: Cleanup process complete."); AgentScanLog.AppendLine("MITIGATE: Closing log file..."); AgentScanLog.AppendLine("FINALIZE: Codeword exiting on " + DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss")); return true; }
private void CheckWritebacks(RegistryHelper reg, ShortcutHelper shortcut, CmdApp app, OpenTarget target) { // either registry or shortcut are null if ((reg == null && shortcut == null) || (reg != null && shortcut != null)) { throw new NotSupportedException("Must leave either registry or shortcut null. And must supply one of the two."); } bool isRegMode = reg != null; // true is reg mode, false is shortcut mode string modeName = isRegMode ? "registry" : "shortcut"; AutoHelpers.LogInvariant("Beginning {0} writeback tests for {1}", modeName, target.ToString()); using (PropertiesDialog props = new PropertiesDialog(app)) { // STEP 1: VERIFY EVERYTHING SAVES IN AN ON/MAX STATE AutoHelpers.LogInvariant("Open dialog and check boxes."); props.Open(target); using (Tabs tabs = new Tabs(props)) { // Set V2 on. tabs.SetGlobalState(Tabs.GlobalState.ConsoleV2); AutoHelpers.LogInvariant("Toggling elements on all tabs."); foreach (TabBase tab in tabs.AllTabs) { tab.NavigateToTab(); foreach (CheckBoxMeta obj in tab.GetCheckboxesForVerification()) { obj.Check(); } foreach (SliderMeta obj in tab.GetSlidersForVerification()) { // adjust slider to the maximum obj.SetToMaximum(); } } AutoHelpers.LogInvariant("Hit OK to save."); props.Close(PropertiesDialog.CloseAction.OK); AutoHelpers.LogInvariant("Verify values changed as appropriate."); CheckWritebacksVerifyValues(isRegMode, reg, shortcut, target, tabs, SliderMeta.ExpectedPosition.Maximum, false, Tabs.GlobalState.ConsoleV2); } // STEP 2: VERIFY EVERYTHING SAVES IN AN OFF/MIN STATE AutoHelpers.LogInvariant("Open dialog and uncheck boxes."); props.Open(target); using (Tabs tabs = new Tabs(props)) { AutoHelpers.LogInvariant("Toggling elements on all tabs."); foreach (TabBase tab in tabs.AllTabs) { tab.NavigateToTab(); foreach (SliderMeta slider in tab.GetSlidersForVerification()) { // adjust slider to the minimum slider.SetToMinimum(); } foreach (CheckBoxMeta obj in tab.GetCheckboxesForVerification()) { obj.Uncheck(); } } tabs.SetGlobalState(Tabs.GlobalState.ConsoleV1); AutoHelpers.LogInvariant("Hit OK to save."); props.Close(PropertiesDialog.CloseAction.OK); AutoHelpers.LogInvariant("Verify values changed as appropriate."); CheckWritebacksVerifyValues(isRegMode, reg, shortcut, target, tabs, SliderMeta.ExpectedPosition.Minimum, true, Tabs.GlobalState.ConsoleV1); } // STEP 3: VERIFY CANCEL DOES NOT SAVE AutoHelpers.LogInvariant("Open dialog and check boxes."); props.Open(target); using (Tabs tabs = new Tabs(props)) { tabs.SetGlobalState(Tabs.GlobalState.ConsoleV2); AutoHelpers.LogInvariant("Toggling elements on all tabs."); foreach (TabBase tab in tabs.AllTabs) { tab.NavigateToTab(); foreach (CheckBoxMeta obj in tab.GetCheckboxesForVerification()) { obj.Check(); } foreach (SliderMeta obj in tab.GetSlidersForVerification()) { // adjust slider to the maximum obj.SetToMaximum(); } } AutoHelpers.LogInvariant("Hit cancel to not save."); props.Close(PropertiesDialog.CloseAction.Cancel); AutoHelpers.LogInvariant("Verify values did not change."); CheckWritebacksVerifyValues(isRegMode, reg, shortcut, target, tabs, SliderMeta.ExpectedPosition.Minimum, true, Tabs.GlobalState.ConsoleV1); } } }
/// <summary> /// Process the specified log entries and create a hash table of the resources touched /// </summary> /// <param name="log">a log entry</param> /// <returns>a two element array of hashtables; [0] contains the file resources, [1] contains the registry resources</returns> protected static Hashtable[] ProcessLog(String[][] log) { Hashtable[] retTable = new Hashtable[2]; RegistryHelper registryHelper = new RegistryHelper (); FileHelper fileHelper = new FileHelper (); for (int i = 0; i < log.Length; i++) { // TODO: handle exceptions registryHelper.AddEntry (log[i]); fileHelper.AddEntry (log[i]); } retTable[0] = fileHelper.GetEntryTable (); retTable[1] = registryHelper.GetEntryTable (); return retTable; }
public static List <Dictionary <string, string> > GetNonstandardServicesFromReg() { List <Dictionary <string, string> > results = new List <Dictionary <string, string> >(); try { foreach (string key in RegistryHelper.GetRegSubkeys("HKLM", @"SYSTEM\CurrentControlSet\Services")) { Dictionary <string, object> key_values = RegistryHelper.GetRegValues("HKLM", @"SYSTEM\CurrentControlSet\Services\" + key); if (key_values.ContainsKey("DisplayName") && key_values.ContainsKey("ImagePath")) { string companyName = ""; string isDotNet = ""; string pathName = Environment.ExpandEnvironmentVariables(string.Format("{0}", key_values["ImagePath"]).Replace("\\SystemRoot\\", "%SystemRoot%\\")); string binaryPath = MyUtils.ReconstructExecPath(pathName); if (binaryPath != "") { try { FileVersionInfo myFileVersionInfo = FileVersionInfo.GetVersionInfo(binaryPath); companyName = myFileVersionInfo.CompanyName; isDotNet = MyUtils.CheckIfDotNet(binaryPath) ? "isDotNet" : ""; } catch (Exception) { // Not enough privileges } } string displayName = string.Format("{0}", key_values["DisplayName"]); string imagePath = string.Format("{0}", key_values["ImagePath"]); string description = key_values.ContainsKey("Description") ? string.Format("{0}", key_values["Description"]) : ""; string startMode = ""; if (key_values.ContainsKey("Start")) { switch (key_values["Start"].ToString()) { case "0": startMode = "Boot"; break; case "1": startMode = "System"; break; case "2": startMode = "Autoload"; break; case "3": startMode = "System"; break; case "4": startMode = "Manual"; break; case "5": startMode = "Disabled"; break; } } if (string.IsNullOrEmpty(companyName) || (!Regex.IsMatch(companyName, @"^Microsoft.*", RegexOptions.IgnoreCase))) { Dictionary <string, string> toadd = new Dictionary <string, string> { ["Name"] = displayName, ["DisplayName"] = displayName, ["CompanyName"] = companyName, ["State"] = "", ["StartMode"] = startMode, ["PathName"] = pathName, ["FilteredPath"] = binaryPath, ["isDotNet"] = isDotNet, ["Description"] = description }; results.Add(toadd); } } } } catch (Exception ex) { Beaprint.PrintException(ex.Message); } return(results); }