public void CheckDefaultMessage() { RegistryOperations ro = new RegistryOperations(); Assert.True(ro.DeleteMessage()); Assert.Equal(ro.HelloMessageDefault, ro.GetMessage()); }
public void NewTemporaryRegistryValueTest_RegistryKey_Success() { var testSubKeyPath = "FiveChecks.Tests"; Registry.CurrentUser.DeleteSubKey(testSubKeyPath, false); using (Registry.CurrentUser.CreateSubKey(testSubKeyPath)){} Some <string> valueName = "SomeValueName"; var actual = TemporaryRegistryValue.NewTemporaryRegistryValue(Registry.CurrentUser, testSubKeyPath, valueName, RegistryValueKind.DWord, 0); var val = actual.Match( value => { Assert.IsTrue(actual.IsSuccess, "Expected success"); Assert.IsTrue(RegistryOperations.RegistryValueExists(Registry.CurrentUser, testSubKeyPath, valueName), "Temporary value does not exist."); value.Dispose(); Assert.IsFalse(RegistryOperations.RegistryValueExists(Registry.CurrentUser, testSubKeyPath, valueName.Value), "Temporary value was not deleted."); return(Option <object> .None); }, exception => { Assert.IsFalse(true, exception.Message); return(Option <object> .None); }); //Cleanup Registry.CurrentUser.DeleteSubKey(testSubKeyPath, false); }
/// <summary> /// List children of a directory and retrieve their /// <see cref="Org.Apache.Hadoop.Registry.Client.Types.RegistryPathStatus"/> /// values. /// <p> /// This is not an atomic operation; A child may be deleted /// during the iteration through the child entries. If this happens, /// the <code>PathNotFoundException</code> is caught and that child /// entry ommitted. /// </summary> /// <param name="path">path</param> /// <returns> /// a possibly empty map of child entries listed by /// their short name. /// </returns> /// <exception cref="Org.Apache.Hadoop.FS.PathNotFoundException">path is not in the registry. /// </exception> /// <exception cref="Org.Apache.Hadoop.Registry.Client.Exceptions.InvalidPathnameException /// ">the path is invalid.</exception> /// <exception cref="System.IO.IOException">Any other IO Exception</exception> public static IDictionary <string, RegistryPathStatus> StatChildren(RegistryOperations registryOperations, string path) { IList <string> childNames = registryOperations.List(path); IDictionary <string, RegistryPathStatus> results = new Dictionary <string, RegistryPathStatus >(); foreach (string childName in childNames) { string child = RegistryPathUtils.Join(path, childName); try { RegistryPathStatus stat = registryOperations.Stat(child); results[childName] = stat; } catch (PathNotFoundException pnfe) { if (Log.IsDebugEnabled()) { Log.Debug("stat failed on {}: moved? {}", child, pnfe, pnfe); } } } // and continue return(results); }
private static FeatureCommandsCollection CreateCommandsImpl(IEnumerable <IISFeature> features, CommandOptions commandOptions) { var commands = new FeatureCommandsCollection(); try { bool internetInformationServerIsPresent = RegistryOperations.CheckMachineKey(@"SOFTWARE\Microsoft\InetStp"); if (!internetInformationServerIsPresent) { // IIS not installed > :-( Begin installation commands.Add(FeatureCommand.Create("IIS-DefaultDocument", "All")); } commands.InternetInformationServerIsPresent = internetInformationServerIsPresent; // IIS installed // > Enable All Features > Install foreach (IISFeature feature in features) { commands.Add(FeatureCommand.Create(feature, options: commandOptions)); } return(commands); } catch { return(commands); } }
public static double GetExpiryWarningDays() { var passwordExpiryWarningDays = RegistryOperations.GetRegistryValue(Registry.LocalMachine, @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon", "PasswordExpiryWarning", 0d); return(passwordExpiryWarningDays.Match(o => Convert.ToDouble(o, CultureInfo.InvariantCulture), () => 0d)); }
/// <summary>List service records directly under a path</summary> /// <param name="registryOperations">registry operations instance</param> /// <param name="path">path to list</param> /// <returns> /// a mapping of the service records that were resolved, indexed /// by their full path /// </returns> /// <exception cref="System.IO.IOException"/> public static IDictionary <string, ServiceRecord> ListServiceRecords(RegistryOperations registryOperations, string path) { IDictionary <string, RegistryPathStatus> children = StatChildren(registryOperations , path); return(ExtractServiceRecords(registryOperations, path, children.Values)); }
public static PendingFileRenameOperation[] GetPendingFileRenameOperations() { var registryKeyPath = @"SYSTEM\CurrentControlSet\Control\Session Manager"; var registryValueName = "PendingFileRenameOperations"; var pendingFileRenameOperationsStringArray = RegistryOperations.GetMultiStringRegistryValue(Registry.LocalMachine, registryKeyPath, registryValueName); return(pendingFileRenameOperationsStringArray.ToPendingFileRenameOperations().ToArray()); }
public RegistryCli(RegistryOperations reg, Configuration conf, TextWriter sysout, TextWriter syserr) : base(conf) { Preconditions.CheckArgument(reg != null, "Null registry"); registry = reg; this.sysout = sysout; this.syserr = syserr; }
public void ReadMessage() { RegistryOperations ro = new RegistryOperations(); Assert.True(ro.DeleteMessage()); Assert.True(ro.SetMessage("hello")); Assert.Equal("hello", ro.GetMessage()); Assert.True(ro.DeleteMessage()); }
public virtual void TestZookeeperCanWriteUnderSystem() { RMRegistryOperationsService rmRegistryOperations = StartRMRegistryOperations(); RegistryOperations operations = rmRegistryOperations; operations.Mknode(PathSystemServices + "hdfs", false); ZKPathDumper pathDumper = rmRegistryOperations.DumpPath(true); Log.Info(pathDumper.ToString()); }
public virtual void SetupRegistry() { registry = new RMRegistryOperationsService("yarnRegistry"); operations = registry; registry.Init(CreateRegistryConfiguration()); registry.Start(); operations.Delete("/", true); registry.CreateRootRegistryPaths(); AddToTeardown(registry); }
public RegistryCli(TextWriter sysout, TextWriter syserr) { Configuration conf = new Configuration(); base.SetConf(conf); registry = RegistryOperationsFactory.CreateInstance(conf); registry.Start(); this.sysout = sysout; this.syserr = syserr; }
public virtual void TestAnonReadAccess() { RMRegistryOperationsService rmRegistryOperations = StartRMRegistryOperations(); Describe(Log, "testAnonReadAccess"); RegistryOperations operations = RegistryOperationsFactory.CreateAnonymousInstance (zkClientConf); AddToTeardown(operations); operations.Start(); NUnit.Framework.Assert.IsFalse("RegistrySecurity.isClientSASLEnabled()==true", RegistrySecurity .IsClientSASLEnabled()); operations.List(PathSystemServices); }
public virtual void TestAnonNoWriteAccess() { RMRegistryOperationsService rmRegistryOperations = StartRMRegistryOperations(); Describe(Log, "testAnonNoWriteAccess"); RegistryOperations operations = RegistryOperationsFactory.CreateAnonymousInstance (zkClientConf); AddToTeardown(operations); operations.Start(); string servicePath = PathSystemServices + "hdfs"; ExpectMkNodeFailure(operations, servicePath); }
public virtual void TestAnonNoWriteAccessOffRoot() { RMRegistryOperationsService rmRegistryOperations = StartRMRegistryOperations(); Describe(Log, "testAnonNoWriteAccessOffRoot"); RegistryOperations operations = RegistryOperationsFactory.CreateAnonymousInstance (zkClientConf); AddToTeardown(operations); operations.Start(); NUnit.Framework.Assert.IsFalse("mknode(/)", operations.Mknode("/", false)); ExpectMkNodeFailure(operations, "/sub"); ExpectDeleteFailure(operations, PathSystemServices, true); }
public virtual void TestUserZookeeperHomePathAccess() { RMRegistryOperationsService rmRegistryOperations = StartRMRegistryOperations(); string home = rmRegistryOperations.InitUserRegistry(Zookeeper); Describe(Log, "Creating ZK client"); RegistryOperations operations = zookeeperUGI.DoAs(new _PrivilegedExceptionAction_232 (this)); operations.List(home); string path = home + "/subpath"; operations.Mknode(path, false); operations.Delete(path, true); }
public virtual void TestAlicePathRestrictedAnonAccess() { RMRegistryOperationsService rmRegistryOperations = StartRMRegistryOperations(); string aliceHome = rmRegistryOperations.InitUserRegistry(Alice); Describe(Log, "Creating anonymous accessor"); RegistryOperations anonOperations = RegistryOperationsFactory.CreateAnonymousInstance (zkClientConf); AddToTeardown(anonOperations); anonOperations.Start(); anonOperations.List(aliceHome); ExpectMkNodeFailure(anonOperations, aliceHome + "/anon"); ExpectDeleteFailure(anonOperations, aliceHome, true); }
// expected // expected /// <summary>Expect a delete operation to fail</summary> /// <param name="operations">operations instance</param> /// <param name="path">path</param> /// <param name="recursive"/> /// <exception cref="System.IO.IOException">An IO failure other than those permitted</exception> public virtual void ExpectDeleteFailure(RegistryOperations operations, string path , bool recursive) { try { operations.Delete(path, recursive); NUnit.Framework.Assert.Fail("should have failed to delete the node " + path); } catch (PathPermissionException) { } catch (NoPathPermissionsException) { } }
/// <summary>Expect a mknode operation to fail</summary> /// <param name="operations">operations instance</param> /// <param name="path">path</param> /// <exception cref="System.IO.IOException">An IO failure other than those permitted</exception> public virtual void ExpectMkNodeFailure(RegistryOperations operations, string path ) { try { operations.Mknode(path, false); NUnit.Framework.Assert.Fail("should have failed to create a node under " + path); } catch (PathPermissionException) { } catch (NoPathPermissionsException) { } }
private static async Task <Result <PendingRebootInfo> > GetCbsRebootPending() { var rebootPendingRegistryKeyPath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending"; Logging.DefaultLogger.Debug($@"Checking if Component Based Servicing has a pending reboot (Check if key exists: '{rebootPendingRegistryKeyPath}')."); var rebootIsPending = RegistryOperations.RegistryKeyExists(Registry.LocalMachine, rebootPendingRegistryKeyPath); var rebootSource = rebootIsPending ? new List <RebootSource> { RebootSource.Cbs } : new List <RebootSource>(); var pendingRebootInfo = new PendingRebootInfo { RebootIsPending = rebootIsPending, Sources = rebootSource }; Logging.DefaultLogger.Info($@"Component Based Servicing (CBS) pending reboot check result: {pendingRebootInfo.ObjectToString()}"); return(await Task.FromResult(new Result <PendingRebootInfo>(pendingRebootInfo)).ConfigureAwait(false)); }
public virtual void TestDigestAccess() { RMRegistryOperationsService registryAdmin = StartRMRegistryOperations(); string id = "username"; string pass = "******"; registryAdmin.AddWriteAccessor(id, pass); IList <ACL> clientAcls = registryAdmin.GetClientAcls(); Log.Info("Client ACLS=\n{}", RegistrySecurity.AclsToString(clientAcls)); string @base = "/digested"; registryAdmin.Mknode(@base, false); IList <ACL> baseACLs = registryAdmin.ZkGetACLS(@base); string aclset = RegistrySecurity.AclsToString(baseACLs); Log.Info("Base ACLs=\n{}", aclset); ACL found = null; foreach (ACL acl in baseACLs) { if (ZookeeperConfigOptions.SchemeDigest.Equals(acl.GetId().GetScheme())) { found = acl; break; } } NUnit.Framework.Assert.IsNotNull("Did not find digest entry in ACLs " + aclset, found ); zkClientConf.Set(KeyRegistryUserAccounts, "sasl:[email protected], sasl:other" ); RegistryOperations operations = RegistryOperationsFactory.CreateAuthenticatedInstance (zkClientConf, id, pass); AddToTeardown(operations); operations.Start(); RegistryOperationsClient operationsClient = (RegistryOperationsClient)operations; IList <ACL> digestClientACLs = operationsClient.GetClientAcls(); Log.Info("digest client ACLs=\n{}", RegistrySecurity.AclsToString(digestClientACLs )); operations.Stat(@base); operations.Mknode(@base + "/subdir", false); ZKPathDumper pathDumper = registryAdmin.DumpPath(true); Log.Info(pathDumper.ToString()); }
/// <summary> /// Remove the StateFlags0200 value for each defined volume cache registry key /// </summary> /// <returns></returns> public static Result <Unit> ResetCleanupManagerStateFlags() { Logging.DefaultLogger.Info("Resetting volume cache state flags after running CleanMrg.exe"); return (VolumeCachesKeyPaths .Select(subKeyPath => RegistryOperations.DeleteRegistryValue(Registry.LocalMachine, subKeyPath, StateFlagsValueName)) .ToArray() .ToResult() .Match(units => { Logging.DefaultLogger.Info("Successfully reset volume cache state flags."); return new Result <Unit>(Unit.Default); }, exception => { Logging.DefaultLogger.Error($"Failed resetting volume cache state flags. {exception.ToExceptionMessage()}"); return new Result <Unit>(new Exception($"Failed to execute function {nameof(ResetCleanupManagerStateFlags)}", exception)); })); }
/// <summary> /// Resolves a mapped network drive into valid <b>UNC</b> path. /// </summary> /// <param name="path"></param> /// <returns> /// <b>UNC</b> path. /// </returns> public static string UncPathResolver(string path) { if (string.IsNullOrEmpty(path)) { throw new ArgumentNullException(nameof(path)); } if (Environment.OSVersion.Platform == PlatformID.MacOSX || Environment.OSVersion.Platform == PlatformID.Unix) { return(path); } if (IsNetworkDrive(path)) { return($"{RegistryOperations.GetCurrentUserKeyValue<string>($@"Network\\{path.ToUpperInvariant()[0]}", "RemotePath")}{path.Remove(0, 2)}"); } return(path); }
/// <summary> /// Extract all service records under a list of stat operations...this /// skips entries that are too short or simply not matching /// </summary> /// <param name="operations">operation support for fetches</param> /// <param name="parentpath">path of the parent of all the entries</param> /// <param name="stats">Collection of stat results</param> /// <returns>a possibly empty map of fullpath:record.</returns> /// <exception cref="System.IO.IOException">for any IO Operation that wasn't ignored. /// </exception> public static IDictionary <string, ServiceRecord> ExtractServiceRecords(RegistryOperations operations, string parentpath, ICollection <RegistryPathStatus> stats) { IDictionary <string, ServiceRecord> results = new Dictionary <string, ServiceRecord >(stats.Count); foreach (RegistryPathStatus stat in stats) { if (stat.size > ServiceRecord.RecordType.Length) { // maybe has data string path = RegistryPathUtils.Join(parentpath, stat.path); try { ServiceRecord serviceRecord = operations.Resolve(path); results[path] = serviceRecord; } catch (EOFException) { if (Log.IsDebugEnabled()) { Log.Debug("data too short for {}", path); } } catch (InvalidRecordException) { if (Log.IsDebugEnabled()) { Log.Debug("Invalid record at {}", path); } } catch (NoRecordException) { if (Log.IsDebugEnabled()) { Log.Debug("No record at {}", path); } } } } return(results); }
/// <summary> /// Performs the execution of the command. /// </summary> public override void ExecuteCmdlet() { if (!ShouldProcess("Creates the group policy and service connection point required to have domain joined devices automatically enroll into MDM.")) { return; } if (string.IsNullOrEmpty(Domain) || string.IsNullOrEmpty(TenantId)) { if (MgmtSession.Instance.Context == null) { throw new PSInvalidOperationException(Resources.RunConnectSecMgmtAccount); } } string tenantId = string.IsNullOrEmpty(TenantId) ? MgmtSession.Instance.Context.Account.Tenant : TenantId; string aadDomain = string.IsNullOrEmpty(Domain) ? GetDomainValue(tenantId).ConfigureAwait(false).GetAwaiter().GetResult() : Domain; WriteDebug($"Using {aadDomain} for the domain value and {tenantId} for the tenant identifier value"); using (DirectoryEntry rootDSE = new DirectoryEntry("LDAP://RootDSE")) { DirectoryEntry deDRC; DirectoryEntry deSCP; int size = Marshal.SizeOf(typeof(int)); string azureADId = $"azureADId:{tenantId}"; string azureADName = $"azureADName:{aadDomain}"; string configCN = rootDSE.Properties["configurationNamingContext"][0].ToString(); string servicesCN = $"CN=Services,{configCN}"; string drcCN = $"CN=Device Registration Configuration,{servicesCN}"; string scpCN = $"CN=62a0ff2e-97b9-4513-943f-0d221bd30080,{drcCN}"; if (DirectoryEntry.Exists($"LDAP://{drcCN}")) { WriteDebug($"Device registration configuration container already exists at LDAP://{drcCN}"); deDRC = new DirectoryEntry($"LDAP://{drcCN}"); } else { WriteDebug($"Creating the device registration configuration container in LDAP://{servicesCN}"); DirectoryEntry entry = new DirectoryEntry($"LDAP://{servicesCN}"); deDRC = entry.Children.Add("CN=Device Registration Configuration", "container"); deDRC.CommitChanges(); } if (DirectoryEntry.Exists($"LDAP://{scpCN}")) { deSCP = new DirectoryEntry($"LDAP://{scpCN}"); WriteDebug($"Service connection point LDAP://{scpCN} already exists, so clearing the keywords property"); deSCP.Properties["keywords"].Clear(); WriteDebug($"Updating the keywords propoerty on the service connection point LDAP://{scpCN}"); deSCP.Properties["keywords"].Add(azureADName); deSCP.Properties["keywords"].Add(azureADId); deSCP.CommitChanges(); } else { WriteDebug($"The service connection point LDAP://{scpCN} does not exists, so it will be created"); deSCP = deDRC.Children.Add("CN=62a0ff2e-97b9-4513-943f-0d221bd30080", "serviceConnectionPoint"); deSCP.Properties["keywords"].Add(azureADName); deSCP.Properties["keywords"].Add(azureADId); deSCP.CommitChanges(); } IGroupPolicyObject2 groupPolicyObject = new GroupPolicyObject() as IGroupPolicyObject2; IntPtr sectionKeyHandle; string domainName = $"LDAP://{rootDSE.Properties["defaultNamingContext"].Value}"; WriteDebug($"Creating {GroupPolicyDisplayName} group policy"); groupPolicyObject.New(domainName, GroupPolicyDisplayName, 0x1); sectionKeyHandle = groupPolicyObject.GetRegistryKey(0x2); RegistryOperations.RegistryCreateKey( sectionKeyHandle, @"Software\Policies\Microsoft\Windows\CurrentVersion\MDM", 0, null, 0, RegSAM.Write, null, out IntPtr key, out RegResult desposition); SetRegistryDWordValue(key, "AutoEnrollMDM", 1); SetRegistryDWordValue(key, "UseAADCredentialType", 1); groupPolicyObject.Save(true, true, new Guid("7909AD9E-09EE-4247-BAB9-7029D5F0A278"), new Guid("D02B1F72-3407-48AE-BA88-E8213C6761F1")); groupPolicyObject.Save(true, true, new Guid("35378EAC-683F-11D2-A89A-00C04FBBCFA2"), new Guid("D02B1F72-3407-48AE-BA88-E8213C6761F1")); RegistryOperations.RegistryCloseKey(ref key); RegistryOperations.RegistryCloseKey(ref sectionKeyHandle); WriteObject($"Domain has been prepared and the {GroupPolicyDisplayName} group policy has been created. You will need to link the group policy for the settings to apply."); } }
private void SetRegistryDWordValue(IntPtr key, string valueName, int value) { byte[] data = { (byte)value, (byte)(value >> 8), (byte)(value >> 16), (byte)(value >> 24) }; RegistryOperations.RegistrySetValue(key, valueName, IntPtr.Zero, RegistryValueKind.DWord, data, 4); }
/// <summary> /// Extract all service records under a list of stat operations...this /// non-atomic action skips entries that are too short or simply not matching. /// </summary> /// <remarks> /// Extract all service records under a list of stat operations...this /// non-atomic action skips entries that are too short or simply not matching. /// <p> /// </remarks> /// <param name="operations">operation support for fetches</param> /// <param name="parentpath">path of the parent of all the entries</param> /// <returns>a possibly empty map of fullpath:record.</returns> /// <exception cref="System.IO.IOException">for any IO Operation that wasn't ignored. /// </exception> public static IDictionary <string, ServiceRecord> ExtractServiceRecords(RegistryOperations operations, string parentpath) { return(ExtractServiceRecords(operations, parentpath, StatChildren(operations, parentpath ).Values)); }
/// <summary> /// Extract all service records under a list of stat operations...this /// non-atomic action skips entries that are too short or simply not matching. /// </summary> /// <remarks> /// Extract all service records under a list of stat operations...this /// non-atomic action skips entries that are too short or simply not matching. /// <p> /// </remarks> /// <param name="operations">operation support for fetches</param> /// <param name="parentpath">path of the parent of all the entries</param> /// <returns>a possibly empty map of fullpath:record.</returns> /// <exception cref="System.IO.IOException">for any IO Operation that wasn't ignored. /// </exception> public static IDictionary <string, ServiceRecord> ExtractServiceRecords(RegistryOperations operations, string parentpath, IDictionary <string, RegistryPathStatus> stats) { return(ExtractServiceRecords(operations, parentpath, stats.Values)); }
private void btnUnregFolder_Click(object sender, EventArgs e) { lblStatus.Text = RegistryOperations.DeleteHandlerInRegistry(false); CheckFolderHandler(); }
/// <summary> /// Checks if the given path is a network drive. /// </summary> /// <param name="path">The path to check.</param> /// <returns> /// <b>true</b> if is a network drive; otherwise <b>false</b>. /// </returns> public static bool IsNetworkDrive(string path) => !string.IsNullOrEmpty(path) && RegistryOperations.CheckCurrentUserKey($@"Network\\{path.ToUpperInvariant()[0]}");