public static void Main() { // Create a string representing the current user. string user = Environment.UserDomainName + "\\" + Environment.UserName; // Create a security object that grants no access. SemaphoreSecurity mSec = new SemaphoreSecurity(); // Add a rule that grants the current user the // right to enter or release the semaphore and read the // permissions on the semaphore. SemaphoreAccessRule rule = new SemaphoreAccessRule(user, SemaphoreRights.Synchronize | SemaphoreRights.Modify | SemaphoreRights.ReadPermissions, AccessControlType.Allow); mSec.AddAccessRule(rule); // Add a rule that denies the current user the // right to change permissions on the semaphore. rule = new SemaphoreAccessRule(user, SemaphoreRights.ChangePermissions, AccessControlType.Deny); mSec.AddAccessRule(rule); // Display the rules in the security object. ShowSecurity(mSec); // Create a rule that grants the current user // the right to read permissions on the semaphore, and // take ownership of the semaphore. Use this rule to // remove the right to read permissions from the // Allow rule for the current user. The inclusion // of the right to take ownership has no effect. rule = new SemaphoreAccessRule(user, SemaphoreRights.TakeOwnership | SemaphoreRights.ReadPermissions, AccessControlType.Allow); mSec.RemoveAccessRule(rule); ShowSecurity(mSec); }
public static void Start() { var security = new SemaphoreSecurity(); security.AddAccessRule(new SemaphoreAccessRule("Everyone", SemaphoreRights.FullControl, AccessControlType.Allow)); _server = new CassiniDevServer(); _server.StartServer(@"..\..\..\FormUI", 54070, "/", "localhost"); RootUrl = _server.RootUrl; }
public static void Main() { // Create a string representing the current user. string user = Environment.UserDomainName + "\\" + Environment.UserName; // Create a security object that grants no access. SemaphoreSecurity mSec = new SemaphoreSecurity(); // Add a rule that grants the current user the // right to enter or release the semaphore and read the // permissions on the semaphore. SemaphoreAccessRule rule = new SemaphoreAccessRule(user, SemaphoreRights.Synchronize | SemaphoreRights.Modify | SemaphoreRights.ReadPermissions, AccessControlType.Allow); mSec.AddAccessRule(rule); // Add a rule that denies the current user the // right to change permissions on the semaphore. rule = new SemaphoreAccessRule(user, SemaphoreRights.ChangePermissions, AccessControlType.Deny); mSec.AddAccessRule(rule); // Display the rules in the security object. ShowSecurity(mSec); // Create a rule that grants the current user // the full control over the semaphore. Use the // ResetAccessRule method to replace both of // the existing rules with the new rule. rule = new SemaphoreAccessRule(user, SemaphoreRights.FullControl, AccessControlType.Allow); mSec.ResetAccessRule(rule); ShowSecurity(mSec); }
static Semaphore CreateGlobalSemaphoreAccessibleToEveryone(string name) { var semaphoreSecurity = new SemaphoreSecurity(); var everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null); var rule = new SemaphoreAccessRule(everyone, SemaphoreRights.FullControl, AccessControlType.Allow); semaphoreSecurity.AddAccessRule(rule); bool createdNew; var semaphore = new Semaphore(1, 1, name, out createdNew, semaphoreSecurity); return(semaphore); }
internal static bool IsNew(string semaphoreName) { bool isNewInstance; var semaphoreSecurity = new SemaphoreSecurity(); var securityIdentifier = new SecurityIdentifier(WellKnownSidType.WorldSid, null); var semaphoreAccessRule = new SemaphoreAccessRule(securityIdentifier, SemaphoreRights.FullControl, AccessControlType.Allow); semaphoreSecurity.AddAccessRule(semaphoreAccessRule); instanceSemaphore = new Semaphore(0, 1, $"Global\\{semaphoreName}", out isNewInstance, semaphoreSecurity); return(isNewInstance); }
public static void Main() { // Create a string representing the current user. string user = Environment.UserDomainName + "\\" + Environment.UserName; // Create a security object that grants no access. SemaphoreSecurity mSec = new SemaphoreSecurity(); // Add a rule that grants the current user the // right to enter or release the semaphore. SemaphoreAccessRule rule = new SemaphoreAccessRule(user, SemaphoreRights.Synchronize | SemaphoreRights.Modify, AccessControlType.Allow); mSec.AddAccessRule(rule); // Add a rule that denies the current user the // right to change permissions on the semaphore. rule = new SemaphoreAccessRule(user, SemaphoreRights.ChangePermissions, AccessControlType.Deny); mSec.AddAccessRule(rule); // Display the rules in the security object. ShowSecurity(mSec); // Add a rule that allows the current user the // right to read permissions on the semaphore. This rule // is merged with the existing Allow rule. rule = new SemaphoreAccessRule(user, SemaphoreRights.ReadPermissions, AccessControlType.Allow); mSec.AddAccessRule(rule); ShowSecurity(mSec); }
public AspNetTestHost(string physicalDirectory, string virtualDirectory, TimeSpan timeout, Type appDomainProxyType) { if (!typeof(AppDomainProxy).IsAssignableFrom(appDomainProxyType)) { throw new Exception(string.Format("Type: {0} should inherit from {1}", appDomainProxyType, typeof(AppDomainProxy))); } PhysicalDirectory = Path.GetFullPath(physicalDirectory); var security = new SemaphoreSecurity(); security.AddAccessRule(new SemaphoreAccessRule("Everyone", SemaphoreRights.FullControl, AccessControlType.Allow)); bool createdNew_notUsed; var semaphoreName = "Global\\MvcTestingAspNetTestHost" + PhysicalDirectory.GetHashCode(); _enforceSingleInstance = new Semaphore(1, 1, semaphoreName, out createdNew_notUsed, security); try { if (!_enforceSingleInstance.WaitOne(timeout)) { throw new Exception("Could not obtain semaphore: " + semaphoreName); } if (!Directory.Exists(PhysicalDirectory)) { throw new Exception("Could not find directory: " + PhysicalDirectory); } CopyTestBinaries(); _appDomainProxy = (AppDomainProxy)ApplicationHost.CreateApplicationHost(appDomainProxyType, virtualDirectory, PhysicalDirectory); _appDomainProxy.RunCodeInAppDomain(InitHost); } catch { DeleteTestBinaries(); using (_enforceSingleInstance) _enforceSingleInstance.Release(); throw; } }
public void ConnectByPid(Int32 pid) { var securityMemory = new MemoryMappedFileSecurity(); var securityMutex = new MutexSecurity(); var securitySemaphore = new SemaphoreSecurity(); var securityWaiter = new SemaphoreSecurity(); securityMemory.AddAccessRule(new AccessRule <MemoryMappedFileRights>(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MemoryMappedFileRights.FullControl, AccessControlType.Allow)); securityMutex.AddAccessRule(new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow)); securitySemaphore.AddAccessRule(new SemaphoreAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), SemaphoreRights.FullControl, AccessControlType.Allow)); securityWaiter.AddAccessRule(new SemaphoreAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), SemaphoreRights.FullControl, AccessControlType.Allow)); this.ipcMemory = MemoryMappedFile.CreateNew($"Global\\dr_analyzer_buffer_{pid}", 76012); this.ipcMemory.SetAccessControl(securityMemory); this.ipcMutex = new Mutex(false, $"Global\\dr_analyzer_mutex_{pid}", out bool createdMutex, securityMutex); this.ipcSentSemaphore = new Semaphore(0, 1, $"Global\\dr_analyzer_sent_semaphore_{pid}", out bool createdSentSemaphore, securitySemaphore); this.ipcReceivedSemaphore = new Semaphore(0, 1, $"Global\\dr_analyzer_received_semaphore_{pid}", out bool createdReceivedSemaphore, securitySemaphore); this.ipcWaiterSemaphore = new Semaphore(0, 1, $"Global\\dr_analyzer_waiter_semaphore_{pid}", out bool createdWaiter, securityWaiter); if (!(createdMutex && createdSentSemaphore && createdReceivedSemaphore && createdWaiter)) { this.FreeSharedObjects(); throw new Exception("One of sync object is already created"); } this.queueSem = new Semaphore(0, 1); this.queueMutex = new Mutex(false); this.isExit = false; this.receiverThread = new Thread(this.ReceiverThreadFunc); this.queueThread = new Thread(this.QueueThreadFunc); this.queueThread.Start(); this.receiverThread.Start(); Injector.InjectByPid(pid); this.Active = true; }
public void SetUp() { Console.WriteLine("Aquiring machine-wide lock ... "); try { var security = new SemaphoreSecurity(); security.AddAccessRule(new SemaphoreAccessRule("Everyone", SemaphoreRights.FullControl, AccessControlType.Allow)); bool createdNew_notUsed; var semaphoreName = "Global\\FormUITests"; lock (typeof(SetUpFixture)) { DisposeSemaphore(); _enforceSingleInstance = new Semaphore(1, 1, semaphoreName, out createdNew_notUsed, security); if (!_enforceSingleInstance.WaitOne(TimeSpan.FromSeconds(240))) { throw new Exception("Could not obtain semaphore: " + semaphoreName); } } Console.WriteLine("Aquired"); LocalRepository.VerifyRunning(); LocalCloudStore.VerifyRunning(); } catch { TearDown(); throw; } TestRegistry.TestHasFailed = false; }
public static Semaphore OpenGlobalSemaphore(string semName, int sInit, int sMax) { Semaphore semaphore = null; bool flag = false; bool flag2 = false; try { semaphore = Semaphore.OpenExisting(semName); } catch (WaitHandleCannotBeOpenedException) { flag = true; } catch (UnauthorizedAccessException) { flag2 = true; } if (flag) { //Environment.UserDomainName + "\\" + Environment.UserName; SecurityIdentifier identity = new SecurityIdentifier(WellKnownSidType.WorldSid, null); SemaphoreSecurity semaphoreSecurity = new SemaphoreSecurity(); semaphoreSecurity.AddAccessRule(new SemaphoreAccessRule(identity, SemaphoreRights.FullControl, AccessControlType.Allow)); bool flag3; semaphore = new Semaphore(sInit, sMax, semName, out flag3, semaphoreSecurity); if (!flag3) { return(null); } } else { if (flag2) { try { using (semaphore = Semaphore.OpenExisting(semName)) { //Environment.UserDomainName + "\\" + Environment.UserName; SecurityIdentifier identity2 = new SecurityIdentifier(WellKnownSidType.WorldSid, null); SemaphoreSecurity semaphoreSecurity2 = new SemaphoreSecurity(); semaphoreSecurity2.AddAccessRule(new SemaphoreAccessRule(identity2, SemaphoreRights.FullControl, AccessControlType.Allow)); semaphore.SetAccessControl(semaphoreSecurity2); semaphore = Semaphore.OpenExisting(semName); } } catch (UnauthorizedAccessException) { //if (semaphore != null) //{ // semaphore.Close(); // //semaphore.Dispose(); //} return(null); } return(semaphore); } } return(semaphore); }
internal ManagedMemoryBlock(string @namespace, string key, int bufferSize, int bufferId, IEnumerable <string> servicePrincpal) { Namespace = @namespace; Key = key; EventWaitHandleSecurity handleSecurity = null; MemoryMappedFileSecurity memSecurity = null; SemaphoreSecurity semaphoreSecurity = null; var serviceIdentity = servicePrincpal.FirstOrDefault(); var currentIdentity = WindowsIdentity.GetCurrent(); if (serviceIdentity != null && currentIdentity != null) { handleSecurity = new EventWaitHandleSecurity(); handleSecurity.AddAccessRule(new EventWaitHandleAccessRule(currentIdentity.Name, EventWaitHandleRights.FullControl, AccessControlType.Allow)); // The event handles need more than just EventWaitHandleRights.Modify | EventWaitHandleRights.Synchronize to work handleSecurity.AddAccessRule(new EventWaitHandleAccessRule(serviceIdentity, EventWaitHandleRights.FullControl, AccessControlType.Allow)); memSecurity = new MemoryMappedFileSecurity(); memSecurity.AddAccessRule(new AccessRule <MemoryMappedFileRights>(currentIdentity.Name, MemoryMappedFileRights.FullControl, AccessControlType.Allow)); memSecurity.AddAccessRule(new AccessRule <MemoryMappedFileRights>(serviceIdentity, MemoryMappedFileRights.ReadWrite, AccessControlType.Allow)); semaphoreSecurity = new SemaphoreSecurity(); semaphoreSecurity.AddAccessRule(new SemaphoreAccessRule(currentIdentity.Name, SemaphoreRights.FullControl, AccessControlType.Allow)); semaphoreSecurity.AddAccessRule(new SemaphoreAccessRule(serviceIdentity, SemaphoreRights.FullControl, AccessControlType.Allow)); } bool createdNew; ProfilerHasResults = new EventWaitHandle( false, EventResetMode.ManualReset, MakeName(@"\OpenCover_Profiler_Results_SendResults_Event_", bufferId), out createdNew, handleSecurity); ResultsHaveBeenReceived = new EventWaitHandle( false, EventResetMode.ManualReset, MakeName(@"\OpenCover_Profiler_Results_ReceiveResults_Event_", bufferId), out createdNew, handleSecurity); _semaphore = new Semaphore(0, 2, MakeName(@"\OpenCover_Profiler_Results_Semaphore_", bufferId), out createdNew, semaphoreSecurity); _mmfResults = MemoryMappedFile.CreateNew( MakeName(@"\OpenCover_Profiler_Results_MemoryMapFile_", bufferId), bufferSize, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, memSecurity, HandleInheritability.Inheritable); Buffer = new byte[bufferSize]; StreamAccessorResults = _mmfResults.CreateViewStream(0, bufferSize, MemoryMappedFileAccess.ReadWrite); StreamAccessorResults.Write(BitConverter.GetBytes(0), 0, 4); StreamAccessorResults.Flush(); BufferSize = bufferSize; }
internal ManagedCommunicationBlock(string @namespace, string key, int bufferSize, int bufferId, IEnumerable <string> servicePrincpal) { Namespace = @namespace; Key = key; EventWaitHandleSecurity eventSecurity = null; MemoryMappedFileSecurity memorySecurity = null; var serviceIdentity = servicePrincpal.FirstOrDefault(); var currentIdentity = WindowsIdentity.GetCurrent(); SemaphoreSecurity semaphoreSecurity = null; if (serviceIdentity != null && currentIdentity != null) { eventSecurity = new EventWaitHandleSecurity(); eventSecurity.AddAccessRule(new EventWaitHandleAccessRule(currentIdentity.Name, EventWaitHandleRights.FullControl, AccessControlType.Allow)); eventSecurity.AddAccessRule(new EventWaitHandleAccessRule(serviceIdentity, EventWaitHandleRights.FullControl, AccessControlType.Allow)); memorySecurity = new MemoryMappedFileSecurity(); memorySecurity.AddAccessRule(new AccessRule <MemoryMappedFileRights>(currentIdentity.Name, MemoryMappedFileRights.FullControl, AccessControlType.Allow)); memorySecurity.AddAccessRule(new AccessRule <MemoryMappedFileRights>(serviceIdentity, MemoryMappedFileRights.ReadWrite, AccessControlType.Allow)); semaphoreSecurity = new SemaphoreSecurity(); semaphoreSecurity.AddAccessRule(new SemaphoreAccessRule(currentIdentity.Name, SemaphoreRights.FullControl, AccessControlType.Allow)); semaphoreSecurity.AddAccessRule(new SemaphoreAccessRule(serviceIdentity, SemaphoreRights.FullControl, AccessControlType.Allow)); } bool createdNew; ProfilerRequestsInformation = new EventWaitHandle( false, EventResetMode.ManualReset, MakeName(@"\OpenCover_Profiler_Communication_SendData_Event_", bufferId), out createdNew, eventSecurity); InformationReadyForProfiler = new EventWaitHandle( false, EventResetMode.ManualReset, MakeName(@"\OpenCover_Profiler_Communication_ReceiveData_Event_", bufferId), out createdNew, eventSecurity); InformationReadByProfiler = new EventWaitHandle( false, EventResetMode.ManualReset, MakeName(@"\OpenCover_Profiler_Communication_ChunkData_Event_", bufferId), out createdNew, eventSecurity); _semaphore = new Semaphore(0, 2, MakeName(@"\OpenCover_Profiler_Communication_Semaphore_", bufferId), out createdNew, semaphoreSecurity); _memoryMappedFile = MemoryMappedFile.CreateNew( MakeName(@"\OpenCover_Profiler_Communication_MemoryMapFile_", bufferId), bufferSize, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, memorySecurity, HandleInheritability.Inheritable); StreamAccessorComms = _memoryMappedFile.CreateViewStream(0, bufferSize, MemoryMappedFileAccess.ReadWrite); DataCommunication = new byte[bufferSize]; PinnedDataCommunication = GCHandle.Alloc(DataCommunication, GCHandleType.Pinned); }
internal static void Main() { //<Snippet2> const string semaphoreName = "SemaphoreExample5"; Semaphore sem = null; bool doesNotExist = false; bool unauthorized = false; // Attempt to open the named semaphore. try { // Open the semaphore with (SemaphoreRights.Synchronize // | SemaphoreRights.Modify), to enter and release the // named semaphore. // sem = Semaphore.OpenExisting(semaphoreName); } catch (WaitHandleCannotBeOpenedException) { Console.WriteLine("Semaphore does not exist."); doesNotExist = true; } catch (UnauthorizedAccessException ex) { Console.WriteLine("Unauthorized access: {0}", ex.Message); unauthorized = true; } //</Snippet2> // There are three cases: (1) The semaphore does not exist. // (2) The semaphore exists, but the current user doesn't // have access. (3) The semaphore exists and the user has // access. // if (doesNotExist) { //<Snippet4> // The semaphore does not exist, so create it. // // The value of this variable is set by the semaphore // constructor. It is true if the named system semaphore was // created, and false if the named semaphore already existed. // bool semaphoreWasCreated; // Create an access control list (ACL) that denies the // current user the right to enter or release the // semaphore, but allows the right to read and change // security information for the semaphore. // string user = Environment.UserDomainName + "\\" + Environment.UserName; SemaphoreSecurity semSec = new SemaphoreSecurity(); SemaphoreAccessRule rule = new SemaphoreAccessRule( user, SemaphoreRights.Synchronize | SemaphoreRights.Modify, AccessControlType.Deny); semSec.AddAccessRule(rule); rule = new SemaphoreAccessRule( user, SemaphoreRights.ReadPermissions | SemaphoreRights.ChangePermissions, AccessControlType.Allow); semSec.AddAccessRule(rule); // Create a Semaphore object that represents the system // semaphore named by the constant 'semaphoreName', with // maximum count three, initial count three, and the // specified security access. The Boolean value that // indicates creation of the underlying system object is // placed in semaphoreWasCreated. // sem = new Semaphore(3, 3, semaphoreName, out semaphoreWasCreated, semSec); // If the named system semaphore was created, it can be // used by the current instance of this program, even // though the current user is denied access. The current // program enters the semaphore. Otherwise, exit the // program. // if (semaphoreWasCreated) { Console.WriteLine("Created the semaphore."); } else { Console.WriteLine("Unable to create the semaphore."); return; } //</Snippet4> } else if (unauthorized) { //<Snippet3> // Open the semaphore to read and change the access // control security. The access control security defined // above allows the current user to do this. // try { sem = Semaphore.OpenExisting( semaphoreName, SemaphoreRights.ReadPermissions | SemaphoreRights.ChangePermissions); // Get the current ACL. This requires // SemaphoreRights.ReadPermissions. SemaphoreSecurity semSec = sem.GetAccessControl(); string user = Environment.UserDomainName + "\\" + Environment.UserName; // First, the rule that denied the current user // the right to enter and release the semaphore must // be removed. SemaphoreAccessRule rule = new SemaphoreAccessRule( user, SemaphoreRights.Synchronize | SemaphoreRights.Modify, AccessControlType.Deny); semSec.RemoveAccessRule(rule); // Now grant the user the correct rights. // rule = new SemaphoreAccessRule(user, SemaphoreRights.Synchronize | SemaphoreRights.Modify, AccessControlType.Allow); semSec.AddAccessRule(rule); // Update the ACL. This requires // SemaphoreRights.ChangePermissions. sem.SetAccessControl(semSec); Console.WriteLine("Updated semaphore security."); // Open the semaphore with (SemaphoreRights.Synchronize // | SemaphoreRights.Modify), the rights required to // enter and release the semaphore. // sem = Semaphore.OpenExisting(semaphoreName); //</Snippet3> } catch (UnauthorizedAccessException ex) { Console.WriteLine("Unable to change permissions: {0}", ex.Message); return; } } // Enter the semaphore, and hold it until the program // exits. // try { sem.WaitOne(); Console.WriteLine("Entered the semaphore."); Console.WriteLine("Press the Enter key to exit."); Console.ReadLine(); sem.Release(); } catch (UnauthorizedAccessException ex) { Console.WriteLine("Unauthorized access: {0}", ex.Message); } }
public static Semaphore GetNamedSemaphore(string name, int maximumCount = 10, int initialCount = -1) { if (string.IsNullOrWhiteSpace(name)) { throw new ArgumentNullException("name", "Argument cannot be empty, null or white space."); } Semaphore namedSemaphore; bool semaphoreWasCreated; if (initialCount < 0) { initialCount = maximumCount; } // Create a semaphore name that is specific to an object (e.g., a path and file name). // Note that we use GetPasswordHash to create a short common name for the name parameter // that was passed into the function - this allows the parameter to be very long, e.g., // a file path, and still meet minimum semaphore name requirements. // Prefix semaphore name with "Global\" such that semaphore will apply to all active // application sessions in case terminal services is running. Note that this is necessary // even though .NET documentation does not state it - IL disassembly shows direct calls // to WinAPI OpenSemaphore and CreateSemaphore which clearly document this: // http://msdn.microsoft.com/en-us/library/windows/desktop/ms684326(v=vs.85).aspx string semaphoreName = "Global\\" + Cipher.GetPasswordHash(name.ToLower(), SemaphoreHash).Replace('\\', '-'); #if MONO // Mono Semaphore implementations do not include ability to change access rules namedSemaphore = new Semaphore(initialCount, maximumCount, semaphoreName, out semaphoreWasCreated); #else bool doesNotExist = false; // Attempt to open the named semaphore with minimum needed rights try { namedSemaphore = Semaphore.OpenExisting(semaphoreName, SemaphoreRights.Synchronize | SemaphoreRights.Modify); } catch (WaitHandleCannotBeOpenedException) { namedSemaphore = null; doesNotExist = true; } // If semaphore does not exist we attempt to create it if (doesNotExist) { try { SemaphoreSecurity security = new SemaphoreSecurity(); security.AddAccessRule(new SemaphoreAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), SemaphoreRights.Synchronize | SemaphoreRights.Modify, AccessControlType.Allow)); namedSemaphore = new Semaphore(initialCount, maximumCount, semaphoreName, out semaphoreWasCreated, security); } catch (UnauthorizedAccessException) { // Named semaphore exists now but current user doesn't have full control, attempt to open with minimum needed rights namedSemaphore = Semaphore.OpenExisting(semaphoreName, SemaphoreRights.Synchronize | SemaphoreRights.Modify); } } #endif return(namedSemaphore); }
public static Semaphore OpenGlobalSemaphore(string semName, int sInit, int sMax) { Semaphore semaphore = null; bool flag = false; bool flag2 = false; try { semaphore = Semaphore.OpenExisting(semName); } catch (WaitHandleCannotBeOpenedException) { InSnergyService.PostLog("Semaphore does not exist: " + semName); flag = true; } catch (UnauthorizedAccessException ex) { InSnergyService.PostLog("Unauthorized access: " + ex.Message + "===>" + semName); flag2 = true; } catch (Exception) { } if (flag) { Environment.UserDomainName + "\\" + Environment.UserName; SecurityIdentifier identity = new SecurityIdentifier(WellKnownSidType.WorldSid, null); SemaphoreSecurity semaphoreSecurity = new SemaphoreSecurity(); semaphoreSecurity.AddAccessRule(new SemaphoreAccessRule(identity, SemaphoreRights.FullControl, AccessControlType.Allow)); bool flag3; semaphore = new Semaphore(sInit, sMax, semName, ref flag3, semaphoreSecurity); if (!flag3) { InSnergyService.PostLog("Unable to create the semaphore: " + semName); return(null); } InSnergyService.PostLog("Created the semaphore: " + semName); } else { if (flag2) { try { semaphore = Semaphore.OpenExisting(semName); Environment.UserDomainName + "\\" + Environment.UserName; SecurityIdentifier identity2 = new SecurityIdentifier(WellKnownSidType.WorldSid, null); SemaphoreSecurity semaphoreSecurity2 = new SemaphoreSecurity(); semaphoreSecurity2.AddAccessRule(new SemaphoreAccessRule(identity2, SemaphoreRights.FullControl, AccessControlType.Allow)); semaphore.SetAccessControl(semaphoreSecurity2); InSnergyService.PostLog("Updated semaphore security: " + semName); semaphore = Semaphore.OpenExisting(semName); } catch (UnauthorizedAccessException ex2) { InSnergyService.PostLog("Unable to change permissions: " + ex2.Message + "===>" + semName); if (semaphore != null) { semaphore.Close(); semaphore.Dispose(); } return(null); } catch (Exception) { } return(semaphore); } } return(semaphore); }
public static void Main() { // Create a string representing the current user. string user = Environment.UserDomainName + "\\" + Environment.UserName; // Create a security object that grants no access. SemaphoreSecurity mSec = new SemaphoreSecurity(); // Add a rule that grants the current user the // right to enter or release the semaphore. SemaphoreAccessRule ruleA = new SemaphoreAccessRule(user, SemaphoreRights.Synchronize | SemaphoreRights.Modify, AccessControlType.Allow); mSec.AddAccessRule(ruleA); // Add a rule that denies the current user the // right to change permissions on the semaphore. SemaphoreAccessRule rule = new SemaphoreAccessRule(user, SemaphoreRights.ChangePermissions, AccessControlType.Deny); mSec.AddAccessRule(rule); // Display the rules in the security object. ShowSecurity(mSec); // Add a rule that allows the current user the // right to read permissions on the semaphore. This rule // is merged with the existing Allow rule. rule = new SemaphoreAccessRule(user, SemaphoreRights.ReadPermissions, AccessControlType.Allow); mSec.AddAccessRule(rule); ShowSecurity(mSec); // Attempt to remove the original rule (granting // the right to enter or release the semaphore) with // RemoveAccessRuleSpecific. The removal fails, // because the right to read the permissions on the // semaphore has been added to the rule, so that it no // longer matches the original rule. Console.WriteLine("Attempt to use RemoveAccessRuleSpecific on the original rule."); mSec.RemoveAccessRuleSpecific(ruleA); ShowSecurity(mSec); // Create a rule that grants the current user // the right to enter or release the semaphore, and // to read permissions. Use this rule to remove // the Allow rule for the current user. Console.WriteLine("Use RemoveAccessRuleSpecific with the correct rights."); rule = new SemaphoreAccessRule(user, SemaphoreRights.Synchronize | SemaphoreRights.Modify | SemaphoreRights.ReadPermissions, AccessControlType.Allow); mSec.RemoveAccessRuleSpecific(rule); ShowSecurity(mSec); }
/// <summary> /// Initializes this instance. /// </summary> /// <returns></returns> public static bool Initialize() { bool bResult = false; if (CurrentElement == null) { // lock lock (typeof(CompanyWebSiteSemaphore)) { if (CurrentElement == null) { int maxPortalsCount = License.PortalsCount; Semaphore semaphore = null; if (maxPortalsCount > 0) { // Step 1. Try open Semaphore try { semaphore = Semaphore.OpenExisting(Uid); } catch (WaitHandleCannotBeOpenedException) { // The named semaphore does not exist. SemaphoreSecurity security = new SemaphoreSecurity(); // OZ 2009-03-10/Fix: System.Security.Principal.IdentityNotMappedException //SemaphoreAccessRule accessRule = new SemaphoreAccessRule("Everyone", SemaphoreRights.TakeOwnership | SemaphoreRights.FullControl, AccessControlType.Allow); SecurityIdentifier everyoneSid = new SecurityIdentifier(WellKnownSidType.WorldSid, null); SemaphoreAccessRule accessRule = new SemaphoreAccessRule(everyoneSid, SemaphoreRights.TakeOwnership | SemaphoreRights.FullControl, AccessControlType.Allow); security.AddAccessRule(accessRule); bool createdNew; semaphore = new Semaphore(maxPortalsCount, maxPortalsCount, Uid, out createdNew, security); } // Wait one with timeout if (!semaphore.WaitOne(3000, false)) { throw new LicenseRestrictionException("License.PortalsCount"); } CurrentElement = new CompanyWebSiteSemaphore(semaphore); } else if (maxPortalsCount == -1) { // Unlimited CurrentElement = new CompanyWebSiteSemaphore(null); } else { throw new LicenseRestrictionException("Wrong License.PortalsCount = " + maxPortalsCount.ToString()); } bResult = true; } } } return(bResult); }