// ------------------------------------------------------------------ // Cree le node racine dans le RegistryTree. // Retourne Null si la racine est un WrongNode (sans enfants) // ------------------------------------------------------------------ private RegistryItem CreateRootNode(string rootpath) { if (rootpath == string.Empty) { // Vérification : HKLM RegistryItem WrongNode = new RegistryItem("HKLM is not allowed. Try a smaller subtree.", "node"); RegistryTree.Add(WrongNode); return(null); } else if (rootpath.Equals("SECURITY")) { // Vérification : HKLM\SECURITY RegistryItem WrongNode = new RegistryItem("SECURITY subtree is not accessible (reserved access).", "node"); RegistryTree.Add(WrongNode); return(null); } else { // Les vérifications sont OK: On crée le node Racine RegistryItem RacineNode = new RegistryItem(rootpath, "node"); RegistryTree.Add(RacineNode); this.AddToNodeTable(RacineNode, RacineNode.Name); // On memorise le Level de ce Node base.RacineNodeLevel = rootpath.Split('\\').Length; return(RacineNode); } }
public static void Load(object data, RegistryTree tree, string keyName) { RegistryKey rootKey = registryTrees[(int)tree].OpenSubKey(keyName); if (rootKey != null) { Load(data, rootKey); rootKey.Close(); } }
public void GivenMsBuildVersionTwelveIsAvailable() { RegistryTree tree = new RegistryTree(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild") { new RegistryDirectory("12.0"), new RegistryDirectory("ToolsVersions") { new RegistryDirectory("12.0") { new RegistryText("MSBuildToolsPath", @"C:\Program Files (x86)\MSBuild\12.0\bin\amd64\") } } }; this.core.Registry.Register(tree); }
// ------------------------------------------------------------------ // Cree les Nodes SubKeys et les Values du Node donné // C'est un peut redondant de donner le node et le path, mais ça évite de le recalculer à chaque fois. // ------------------------------------------------------------------ private void CreateChildNodes(RegistryItem ParentNode, string ParentPath) { RegistryKey rk; if (ParentNode == null) { return; } try { rk = Registry.LocalMachine.OpenSubKey(ParentPath); } catch (Exception ex) { RegistryItem WrongNode = new RegistryItem("This registry cannot be read (" + ex.Message + ").", "node"); RegistryTree.Add(WrongNode); return; } if (rk == null) { RegistryItem WrongNode = new RegistryItem("This registry was found null (" + ParentPath + ").", "node"); RegistryTree.Add(WrongNode); return; } string[] SubKeysArray = rk.GetSubKeyNames(); string[] ValuesArray = rk.GetValueNames(); // Traitement des Subkeys: on les ajoute dans l'arborescence foreach (string SubKeyName in SubKeysArray) { // on cree un nouveau node pour chaque SubKey string nodePath = ParentPath + @"\" + SubKeyName; RegistryItem NewNode = base.CreateRegistryNode(nodePath); // On met le node dans le dictionnaire base.AddToNodeTable(NewNode, SubKeyName); // On le rattache à son parent base.AttachToParentNode(NewNode, ParentNode); // On traite ses enfants (recursivité) this.CreateChildNodes(NewNode, nodePath); } // Traitement des Values: on les ajoute dans l'arborescence foreach (string ValueName in ValuesArray) { // On recupère toutes les infos sur cette value string ValueKind = string.Empty; string Value = string.Empty; try { ValueKind = rk.GetValueKind(ValueName).ToString(); } catch (NullReferenceException) { ValueKind = string.Empty; } try { Value = rk.GetValue(ValueName).ToString(); } catch (NullReferenceException) { Value = string.Empty; } // On cree une Key RegistryItem newKey = this.CreateRegistryKeyFromHive(ValueName, ValueKind, Value); // On la rattache à son parent base.AttachToParentNode(newKey, ParentNode); } }
public static void Save(object data, RegistryTree tree, string keyName) { Save(data, registryTrees[(int)tree], keyName); }
/// <summary> /// Tests loading of a workshare signed action with no unmanaged dependencies. /// This test relies on an example action precompiled and committed to source control as /// test data : this AbortOnExecute action can be found in the PESAction solution. /// </summary> // [Test] public void LoadSignedActionFromLocation() { ActionDetails ad = new ActionDetails("Abort", Workshare.TestUtils.TestFileUtils.MakeRootPathAbsolute(@"\projects\Hygiene\src\PolicyEngine.Tests\TestFiles\SignedPartyAction"), "Workshare.Policy.Actions.AbortOnExecuteAction.dll", "Workshare\\ProtectEnterprise\\Actions", "Workshare.Policy.Actions.AbortOnExecuteAction", "f2099407-96c1-4e5d-8b6a-ed5163b41fd4"); System.IO.File.Move(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ad.AssemblyName), Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ad.AssemblyName + ".tmp")); try { #region setup RegistryTree rt = new RegistryTree(ad.HKLMRegLocation, ad.AssemblyName, ad.Path); //now comes the ugly bit of the setup //rules and object file below retrieved from a policy created with PolicyDesigner and copy/pasted from the //policy explorer string rulesXML = System.IO.File.ReadAllText(Workshare.TestUtils.TestFileUtils.MakeRootPathAbsolute(@"\projects\Hygiene\src\PolicyEngine.Tests\TestFiles\SignedPartyAction\rules.xml")); string objectsXML = System.IO.File.ReadAllText(Workshare.TestUtils.TestFileUtils.MakeRootPathAbsolute(@"\projects\Hygiene\src\PolicyEngine.Tests\TestFiles\SignedPartyAction\objects.xml")); GeneralPolicyProcessor gpp = new GeneralPolicyProcessor(); //start following parameters have no bearing on this test case but need to be filled in for the gpp to run gpp.FileType = "*.email"; gpp.CurrentUser = "******"; gpp.CurrentRunAtMode = RunAt.Client; gpp.RecipientList = new string[] { "*****@*****.**" }; //end irrelevant parameters gpp.Initialise(RunAt.Client, rulesXML, objectsXML); #endregion string assemblyName, className; //execute //parameters must match what is setup in the object and rules file CachedAction action = gpp.LoadActionObject(ad.ObjectRef, ad.Name, out assemblyName, out className); //verify Assert.IsNotNull(action, "No {0} action found", ad.Name); VerifyObjectLocation(action.Action, ad); } finally { System.IO.File.Move(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ad.AssemblyName + ".tmp"), Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ad.AssemblyName)); } }
/// <summary> /// Tests loading of a 3rd party unsigned action with a dependency on an unmanaged dll. /// Verifies that all the action ifaces are loaded from the correct location and that the unmanaged dll /// is loaded from the correct location. /// </summary> // [Test] public void LoadUnsignedActionFromLocation() { if (Marshal.SizeOf(typeof(IntPtr)) == 8) throw new IgnoreException("can't run this test easily on 64 bit without recompiling the action and adding its references and a whole bunch of related stuff"); #region setup ActionDetails ad = new ActionDetails("3rd Party", Workshare.TestUtils.TestFileUtils.MakeRootPathAbsolute(@"\projects\Hygiene\src\PolicyEngine.Tests\TestFiles\UnsignedAction"), "Typical3rdPartyAction.dll", "Workshare\\ProtectEnterprise\\Actions", "Typical3rdPartyAction", "f2c04c19-54fb-48f6-af3d-82c9404deaf2"); string managedDll = "unmanageddll.dll"; string managedDllLocation = Path.Combine(Path.GetDirectoryName(ad.Path), managedDll); string targetDllLocation = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, managedDll); //attempt to copy the managed dll to the basedirectory of current appdomain so its in 2 locations System.IO.File.Copy(managedDllLocation,targetDllLocation, true); //add temp file to the deletion list m_TempFiles.Add(targetDllLocation); RegistryTree rt = new RegistryTree(ad.HKLMRegLocation, ad.AssemblyName, ad.Path); string rulesXML = System.IO.File.ReadAllText(Workshare.TestUtils.TestFileUtils.MakeRootPathAbsolute(@"\projects\Hygiene\src\PolicyEngine.Tests\TestFiles\SignedPartyAction\rules.xml")); string objectsXML = System.IO.File.ReadAllText(Workshare.TestUtils.TestFileUtils.MakeRootPathAbsolute(@"\projects\Hygiene\src\PolicyEngine.Tests\TestFiles\SignedPartyAction\objects.xml")); GeneralPolicyProcessor gpp = new GeneralPolicyProcessor(); //start following parameters have no bearing on this test case but need to be filled in for the gpp to run gpp.FileType = "*.email"; gpp.CurrentUser = "******"; gpp.CurrentRunAtMode = RunAt.Client; gpp.RecipientList = new string[] { "*****@*****.**" }; //end irrelevant parameters gpp.Initialise(RunAt.Client, rulesXML, objectsXML); Chilkat.Cert cert = new Chilkat.Cert(); #endregion string assemblyName, className; CachedAction action = gpp.LoadActionObject(ad.ObjectRef, ad.Name, out assemblyName, out className); Assert.IsNotNull(action, "No {0} action found", ad.Name); VerifyObjectLocation(action.Action, ad); //verify location of unmanaged dll - cause unmanaged dll is latebound we need to invoke to make sure it gets loaded first ActionPropertySet adata = action.Action.PropertySet; ActionData testData = new ActionData(); testData.FileName = Workshare.TestUtils.TestFileUtils.MakeRootPathAbsolute(@"\projects\Hygiene\src\PolicyEngine.Tests\TestFiles\TestfileActionLoad.txt"); testData.Properties.Add("DisplayName", Path.GetFileName(testData.FileName)); action.Action.Execute(testData, adata); // testdll.dll should be loaded now bool found = false; foreach (ProcessModule pm in Process.GetCurrentProcess().Modules) { if (pm.ModuleName.Equals(managedDll, StringComparison.InvariantCultureIgnoreCase)) { found = true; Assert.IsTrue(string.Equals(managedDllLocation, pm.FileName, StringComparison.InvariantCultureIgnoreCase), "{0} loaded from incorrect location, expected {1}, actual {2}", managedDll, managedDllLocation, pm.FileName); } } Assert.IsTrue(found, "unmanaged dll {0} not found in current process' modules", managedDll); }
// ------------------------------------------------------------------ // Parse le fichier REG // Enregistre l'arborescence dans un RegistryTree // Enregistre la liste des Nodes dans un Dictionnaire // ------------------------------------------------------------------ public void ParseFile(string fileName) { // On commence par vider la collection et le dictionnaire InitParser(); AverageLabelLength = 0; ModalLabelLength = 0; Array.Clear(TableStats, 0, TableStats.Length); // Vérification if (!fileName.EndsWith(".reg")) { RegistryItem WrongNode = new RegistryItem("Not a REG file", "node"); RegistryTree.Add(WrongNode); return; } // On lit le fichier et on met tout dans une très longue string. // fileName = "E:\\source\\repos\\RegFineViewer\\_example1.reg"; StreamReader streamFile = new StreamReader(File.Open(fileName, FileMode.OpenOrCreate)); string fichier = streamFile.ReadToEnd(); streamFile.Close(); // On decoupe le fichier en un tableau de lignes string[] lignes = fichier.Split('\r', '\n'); // Vérification if (lignes.Length > 50000) { RegistryItem WrongNode = new RegistryItem("The file contains too many lines (max 10.000).", "node"); RegistryTree.Add(WrongNode); return; } // On crée un Node Racine RegistryItem currentNode = new RegistryItem("root", "node"); RegistryTree.Add(currentNode); bool firstNode = true; // On parcourt le tableau des lignes du fichier for (int i = 0; i < lignes.Length; i++) { string ligne = lignes[i]; // On ignore la ligne d'entete if (ligne.StartsWith("Windows Registry Editor")) { } // On ignore les lignes vides else if (ligne.Equals("")) { } // Lignes de type [path\to\node] else if (ligne.StartsWith("[") && ligne.EndsWith("]")) { string nodePath = ligne.Trim('[', ']'); string parentPath = GetParentPath(nodePath); // ---------------------------------------------------------------------- // S'il s'agit du premier node // ---------------------------------------------------------------------- // Le node racine du treeView est le parent du premier node du fichier REG if (firstNode) { if (parentPath != "") { // Pour ce node racine, son nom est le chemin complet du parent currentNode.Name = parentPath; } else { // sauf si le nom du parent est vide... currentNode.Name = nodePath; } // On met le node Racine dans le dictionnaire AddToNodeTable(currentNode, currentNode.Name); // On memorise le Level de ce Node RacineNodeLevel = nodePath.Split('\\').Length - 1; firstNode = false; } // on cree un nouveau node currentNode = CreateRegistryNode(nodePath); // On le rattache à son parent AttachToParentNode(currentNode, parentPath); // on comptabilise sa longueur dans les statistiques TableStats[currentNode.Name.Length] += 1; } // Lignes du type: "ErrorLogSizeInKb" = dword:000186A0 // Lignes du type: "Application" = "" else if (ligne.StartsWith("\"")) { // Si on n'a pas de node courant, on passe. Ca ne devrait pas arriver. if (currentNode != null) { // On cree une Key RegistryItem newKey = CreateRegistryKeyFromFileLine(ligne); // On la rattache au Node courant currentNode.AddSubItem(newKey); } } // Autres cas else { } } }