示例#1
0
        public static void StartEvent()
        {
            // The event does not exist, so create it.

            // Create an access control list (ACL) that denies the
            // current user the right to wait on or signal the
            // event, but allows the right to read and change
            // security information for the event.
            //
            bool   wasCreated;
            string user = GetUser();
            EventWaitHandleSecurity EventHandleSec = new EventWaitHandleSecurity();

            EventWaitHandleAccessRule rule = SetRule(user, EventWaitHandleRights.Synchronize | EventWaitHandleRights.Modify);

            EventHandleSec.AddAccessRule(rule);

            rule = SetRule(user, EventWaitHandleRights.ReadPermissions | EventWaitHandleRights.ChangePermissions);
            EventHandleSec.AddAccessRule(rule);

            EventHandle = new EventWaitHandle(true, EventResetMode.AutoReset, EventName, out wasCreated, EventHandleSec);

            if (wasCreated)
            {
                Console.Write("Created the named event.");
            }
            else
            {
                WriteError("Unable to create the event.");
                return;
            }
        }
示例#2
0
        /// <summary>
        /// Get the ready handle for the given scenario.
        /// </summary>
        /// <exception cref="CacheException"/>
        public static EventWaitHandle GetReadyWaitHandle(string scenario)
        {
            try
            {
                var eventName = GetReadyEventName(scenario);

#if !FEATURE_CORECLR
                var ret = new EventWaitHandle(false, EventResetMode.ManualReset, eventName, out bool created);

                var security = new EventWaitHandleSecurity();

                // Allow any client to wait on the event.
                security.AddAccessRule(EventWaitHandleAccessRules.PublicSynchronizeAccessRule());

                // Give full control to current user.
                security.AddAccessRule(EventWaitHandleAccessRules.CurrentUserFullControlRule());
                ret.SetAccessControl(security);
#else
                var ret = new EventWaitHandle(false, EventResetMode.ManualReset);
#endif

                return(ret);
            }
            catch (Exception e)
            {
                throw new CacheException(e.ToString(), e);
            }
        }
示例#3
0
            internal ManagedCommunicationBlock(string @namespace, string key, int bufferSize, int bufferId, IEnumerable <string> servicePrincpal)
            {
                Namespace = @namespace;
                Key       = key;

                EventWaitHandleSecurity  open        = null;
                MemoryMappedFileSecurity transparent = null;

                var service         = servicePrincpal.FirstOrDefault();
                var currentIdentity = WindowsIdentity.GetCurrent();

                if (service != null && currentIdentity != null)
                {
                    open = new EventWaitHandleSecurity();
                    open.AddAccessRule(new EventWaitHandleAccessRule(currentIdentity.Name, EventWaitHandleRights.FullControl, AccessControlType.Allow));
                    open.AddAccessRule(new EventWaitHandleAccessRule(service, EventWaitHandleRights.FullControl, AccessControlType.Allow));

                    transparent = new MemoryMappedFileSecurity();
                    transparent.AddAccessRule(new AccessRule <MemoryMappedFileRights>(currentIdentity.Name, MemoryMappedFileRights.FullControl, AccessControlType.Allow));
                    transparent.AddAccessRule(new AccessRule <MemoryMappedFileRights>(service, MemoryMappedFileRights.ReadWrite, AccessControlType.Allow));
                }

                _memoryMappedFile = MemoryMappedFile.CreateNew(
                    MakeName(@"\OpenCover_Profiler_Communication_MemoryMapFile_", bufferId),
                    bufferSize,
                    MemoryMappedFileAccess.ReadWrite,
                    MemoryMappedFileOptions.None,
                    transparent,
                    HandleInheritability.Inheritable);

                StreamAccessorComms = _memoryMappedFile.CreateViewStream(0, bufferSize, MemoryMappedFileAccess.ReadWrite);

                bool createdNew;

                ProfilerRequestsInformation = new EventWaitHandle(
                    false,
                    EventResetMode.ManualReset,
                    MakeName(@"\OpenCover_Profiler_Communication_SendData_Event_", bufferId),
                    out createdNew,
                    open);

                InformationReadyForProfiler = new EventWaitHandle(
                    false,
                    EventResetMode.ManualReset,
                    MakeName(@"\OpenCover_Profiler_Communication_ReceiveData_Event_", bufferId),
                    out createdNew,
                    open);

                InformationReadByProfiler = new EventWaitHandle(
                    false,
                    EventResetMode.ManualReset,
                    MakeName(@"\OpenCover_Profiler_Communication_ChunkData_Event_", bufferId),
                    out createdNew,
                    open);

                DataCommunication       = new byte[bufferSize];
                PinnedDataCommunication = GCHandle.Alloc(DataCommunication, GCHandleType.Pinned);
            }
示例#4
0
        private void SetEventSecurity()
        {
            EventWaitHandleSecurity security           = new EventWaitHandleSecurity();
            SecurityIdentifier      authenticatedUsers = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null);

            security.AddAccessRule(new EventWaitHandleAccessRule(authenticatedUsers, EventWaitHandleRights.Modify, AccessControlType.Allow));
            security.AddAccessRule(new EventWaitHandleAccessRule(authenticatedUsers, EventWaitHandleRights.ReadPermissions, AccessControlType.Allow));

            _loggersEvent.SetAccessControl(security);
        }
示例#5
0
        // This creates the named system event that "belongs to" the
        // logger (the logger has a handler for when the event is signaled).
        private void CreateLoggersEvent()
        {
            lock (_eventsLock)
            {
                string step = "creating named event";
                bool   createdNew;

                try
                {
                    // Set the security so any viewer can set/signal the event.

                    EventWaitHandleSecurity security           = new EventWaitHandleSecurity();
                    SecurityIdentifier      authenticatedUsers = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null);

                    //SecurityIdentifier curAccount = System.Security.Principal.WindowsIdentity.GetCurrent().User;
                    //security.AddAccessRule(new EventWaitHandleAccessRule(curAccount, EventWaitHandleRights.FullControl, AccessControlType.Allow));

                    security.AddAccessRule(new EventWaitHandleAccessRule(authenticatedUsers, EventWaitHandleRights.Modify, AccessControlType.Allow));
                    security.AddAccessRule(new EventWaitHandleAccessRule(authenticatedUsers, EventWaitHandleRights.ReadPermissions, AccessControlType.Allow));

                    string eventName = "Global\\TX-" + _fileGuidString;
                    //MetaLog?.Info("Creating logger's event ", eventName);
                    _loggersEvent = new EventWaitHandle(false, EventResetMode.AutoReset, eventName, out createdNew, security);

                    // If createdNew = false, it probably means something bad but I'm not sure it's always bad.
                    // For example, if the file was closed and reopened maybe we'll get the same event object again.

                    step = "registering callback";
                    //MetaLog?.Info("Calling RegisterWaitForSingleObject");
                    _loggersRegisteredWaitHandle = ThreadPool.RegisterWaitForSingleObject(_loggersEvent, LoggersEventHandler, null, -1, false);
                    //Debug.Print("Logger's named event is ready: {0}", eventName);
                }
                catch (Exception ex)
                {
                    string msg = "Exception at step '" + step + "': " + ex.Message;

                    while (ex.InnerException != null)
                    {
                        ex = ex.InnerException;

                        if (!string.IsNullOrEmpty(ex.Message))
                        {
                            msg += "\n" + ex.Message;
                        }
                    }

                    //MetaLog?.Info(msg);
                    Debug.Print(msg);
                    Logger.EventLogging.Log(msg, Logger.EventLogging.NonFatalExceptionInLogger);
                    Close();
                }
            }
        }
示例#6
0
        /// <summary>
        /// Creates a new SharedMemory instance.
        /// </summary>
        /// <param name="isOwnerProcess">Pass true only if this is the process which should own the shared memory.  E.g. the one which starts first and lives longer than all other related processes.  The owner process must prepare the shared memory before spawning other processes which will use the shared memory, and ideally keep the shared memory alive until other processes are closed.</param>
        /// <param name="uniqueId">An ID which is unique to this application.</param>
        private SharedMemoryStream(bool isOwnerProcess, string uniqueId)
        {
            this.isOwnerProcess = isOwnerProcess;
            string mmf_uniqueId  = "Global\\SHRD.SMS.MMF." + uniqueId;
            string ewh1_uniqueId = "Global\\SHRD.SMS.EWH1." + uniqueId;
            string ewh2_uniqueId = "Global\\SHRD.SMS.EWH2." + uniqueId;

            if (isOwnerProcess)
            {
                // Set up security objects
                SecurityIdentifier users       = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
                SecurityIdentifier localSystem = new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null);

                MemoryMappedFileSecurity mmf_security = new MemoryMappedFileSecurity();
                mmf_security.AddAccessRule(new AccessRule <MemoryMappedFileRights>(users, MemoryMappedFileRights.FullControl, AccessControlType.Allow));
                mmf_security.AddAccessRule(new AccessRule <MemoryMappedFileRights>(localSystem, MemoryMappedFileRights.FullControl, AccessControlType.Allow));

                var ewh_security = new EventWaitHandleSecurity();
                ewh_security.AddAccessRule(new EventWaitHandleAccessRule(users, EventWaitHandleRights.FullControl, AccessControlType.Allow));
                ewh_security.AddAccessRule(new EventWaitHandleAccessRule(localSystem, EventWaitHandleRights.FullControl, AccessControlType.Allow));

                // Set up Shared Memory
                _mmf         = MemoryMappedFile.CreateOrOpen(mmf_uniqueId, memoryMappedFileSize, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.DelayAllocatePages, mmf_security, HandleInheritability.Inheritable);
                viewAccessor = _mmf.CreateViewAccessor(0, memoryMappedFileSize);

                // Set up EventWaitHandles
                bool createdNew;
                if (!EventWaitHandle.TryOpenExisting(ewh1_uniqueId, out _ewh_read))
                {
                    _ewh_read = new EventWaitHandle(false, EventResetMode.ManualReset, ewh1_uniqueId, out createdNew, ewh_security);
                }
                _ewh_read.Set();
                if (!EventWaitHandle.TryOpenExisting(ewh2_uniqueId, out _ewh_write))
                {
                    _ewh_write = new EventWaitHandle(false, EventResetMode.ManualReset, ewh2_uniqueId, out createdNew, ewh_security);
                }
                _ewh_write.Set();
                myIncomingStreamStartsAt = metadataSize;
                myOutgoingStreamStartsAt = metadataSize + bufferSize;
            }
            else
            {
                // Set up Shared Memory
                _mmf         = MemoryMappedFile.OpenExisting(mmf_uniqueId, MemoryMappedFileRights.ReadWrite);
                viewAccessor = _mmf.CreateViewAccessor(0, memoryMappedFileSize);
                // This is the "slave process" so the read and write handles are reversed.
                _ewh_write = EventWaitHandle.OpenExisting(ewh1_uniqueId);
                _ewh_read  = EventWaitHandle.OpenExisting(ewh2_uniqueId);
                myOutgoingStreamStartsAt = metadataSize;
                myIncomingStreamStartsAt = metadataSize + bufferSize;
            }
        }
示例#7
0
            internal ManagedMemoryBlock(string @namespace, string key, int bufferSize, int bufferId, IEnumerable <string> servicePrincpal)
            {
                Namespace = @namespace;
                Key       = key;

                EventWaitHandleSecurity  open        = null;
                MemoryMappedFileSecurity transparent = null;

                var service         = servicePrincpal.FirstOrDefault();
                var currentIdentity = WindowsIdentity.GetCurrent();

                if (service != null && currentIdentity != null)
                {
                    open = new EventWaitHandleSecurity();
                    open.AddAccessRule(new EventWaitHandleAccessRule(currentIdentity.Name, EventWaitHandleRights.FullControl, AccessControlType.Allow));

                    // The event handles need more than just EventWaitHandleRights.Modify | EventWaitHandleRights.Synchronize to work
                    open.AddAccessRule(new EventWaitHandleAccessRule(service, EventWaitHandleRights.FullControl, AccessControlType.Allow));

                    transparent = new MemoryMappedFileSecurity();
                    transparent.AddAccessRule(new AccessRule <MemoryMappedFileRights>(currentIdentity.Name, MemoryMappedFileRights.FullControl, AccessControlType.Allow));
                    transparent.AddAccessRule(new AccessRule <MemoryMappedFileRights>(service, MemoryMappedFileRights.ReadWrite, AccessControlType.Allow));
                }

                bool createdNew;

                ProfilerHasResults = new EventWaitHandle(
                    false,
                    EventResetMode.ManualReset,
                    MakeName(@"\OpenCover_Profiler_Communication_SendResults_Event_", bufferId),
                    out createdNew,
                    open);

                ResultsHaveBeenReceived = new EventWaitHandle(
                    false,
                    EventResetMode.ManualReset,
                    MakeName(@"\OpenCover_Profiler_Communication_ReceiveResults_Event_", bufferId),
                    out createdNew,
                    open);

                _mmfResults = MemoryMappedFile.CreateNew(
                    MakeName(@"\OpenCover_Profiler_Results_MemoryMapFile_", bufferId),
                    bufferSize,
                    MemoryMappedFileAccess.ReadWrite,
                    MemoryMappedFileOptions.None,
                    transparent,
                    HandleInheritability.Inheritable);

                StreamAccessorResults = _mmfResults.CreateViewStream(0, bufferSize, MemoryMappedFileAccess.ReadWrite);
                StreamAccessorResults.Write(BitConverter.GetBytes(0), 0, 4);
                BufferSize = bufferSize;
            }
示例#8
0
        public static void CreateSyncEvent()
        {
            EventWaitHandleSecurity   eventSecurity = new EventWaitHandleSecurity();
            EventWaitHandleAccessRule rule          = new EventWaitHandleAccessRule("SYSTEM", EventWaitHandleRights.FullControl, AccessControlType.Allow);

            eventSecurity.AddAccessRule(rule);
            rule = new EventWaitHandleAccessRule("NETWORK SERVICE", EventWaitHandleRights.FullControl, AccessControlType.Allow);
            eventSecurity.AddAccessRule(rule);
            bool            createdNew;
            EventWaitHandle ew = new EventWaitHandle(true, EventResetMode.AutoReset, "Global\\ShopAide_MemSync_Event", out createdNew, eventSecurity);

            ew.Set();
        }
示例#9
0
    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.
        EventWaitHandleSecurity mSec = new EventWaitHandleSecurity();

        // Add a rule that grants the current user the
        // right to wait on or signal the event.
        EventWaitHandleAccessRule rule = new EventWaitHandleAccessRule(user,
                                                                       EventWaitHandleRights.Synchronize | EventWaitHandleRights.Modify,
                                                                       AccessControlType.Allow);

        mSec.AddAccessRule(rule);

        // Add a rule that denies the current user the
        // right to change permissions on the event.
        rule = new EventWaitHandleAccessRule(user,
                                             EventWaitHandleRights.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 event. This rule
        // is merged with the existing Allow rule.
        rule = new EventWaitHandleAccessRule(user,
                                             EventWaitHandleRights.ReadPermissions,
                                             AccessControlType.Allow);
        mSec.AddAccessRule(rule);

        ShowSecurity(mSec);

        // Create a rule that allows the current user to
        // take ownership of the event, and use that rule
        // to remove the existing Allow rule from the
        // EventWaitHandleSecurity object, showing that the user
        // and access type must match, while the rights are
        // ignored.
        Console.WriteLine("Use RemoveAccessRuleAll to remove the Allow rule.");
        rule = new EventWaitHandleAccessRule(user,
                                             EventWaitHandleRights.TakeOwnership,
                                             AccessControlType.Allow);
        mSec.RemoveAccessRuleAll(rule);

        ShowSecurity(mSec);
    }
        public CredentialsCacheLifetimeManager(int pid)
        {
            var security = new EventWaitHandleSecurity();

            //security.AddAccessRule(new EventWaitHandleAccessRule(
            //    new SecurityIdentifier(WellKnownSidType.InteractiveSid, null),
            //    EventWaitHandleRights.Synchronize | EventWaitHandleRights.Modify,
            //    AccessControlType.Allow));
            security.AddAccessRule(new EventWaitHandleAccessRule(
                                       new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null),
                                       EventWaitHandleRights.Synchronize | EventWaitHandleRights.Modify,
                                       AccessControlType.Allow));
            security.AddAccessRule(new EventWaitHandleAccessRule(
                                       new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null),
                                       EventWaitHandleRights.Synchronize | EventWaitHandleRights.Modify,
                                       AccessControlType.Allow));

            if (!EventWaitHandle.TryOpenExisting(
                    GLOBAL_WAIT_HANDLE_NAME,
                    EventWaitHandleRights.Synchronize | EventWaitHandleRights.Modify,
                    out var eventWaitHandle))
            {
                eventWaitHandle = new EventWaitHandle(false, EventResetMode.ManualReset, GLOBAL_WAIT_HANDLE_NAME, out var created, security);
            }

            if (!EventWaitHandle.TryOpenExisting(
                    GLOBAL_WAIT_HANDLE_NAME + pid.ToString(CultureInfo.InvariantCulture),
                    EventWaitHandleRights.Synchronize | EventWaitHandleRights.Modify,
                    out var eventWaitHandleSpecific))
            {
                eventWaitHandleSpecific = new EventWaitHandle(false, EventResetMode.ManualReset, GLOBAL_WAIT_HANDLE_NAME + pid.ToString(CultureInfo.InvariantCulture), out var created, security);
            }

            var credentialsResetThread = new Thread(() =>
            {
                if (WaitHandle.WaitAny(new WaitHandle[] { eventWaitHandle, eventWaitHandleSpecific }) >= 0)
                {
                    Logger.Instance.Log("Credentials Cache termination received", LogLevel.Info);
                    OnCacheClear?.Invoke();
                    eventWaitHandle.Close();
                    eventWaitHandle.Dispose();
                    eventWaitHandleSpecific.Close();
                    eventWaitHandleSpecific.Dispose();
                }
            });

            credentialsResetThread.IsBackground = true;
            credentialsResetThread.Start();
        }
示例#11
0
        protected override void ProcessRecord()
        {
            base.ProcessRecord();

            var secAttrs           = new EventWaitHandleSecurity();
            SecurityIdentifier sid = WindowsIdentity.GetCurrent().User;
            var rights             = EventWaitHandleRights.Synchronize;
            var aceType            = AccessControlType.Allow;
            var ace = new EventWaitHandleAccessRule(sid, rights, aceType);

            secAttrs.AddAccessRule(ace);
            bool createdNew;
            var  eventWaitHandle = new EventWaitHandle(false,
                                                       EventResetMode.ManualReset,
                                                       null,
                                                       out createdNew,
                                                       secAttrs);

            bool itWorked = NativeMethods.SetHandleInformation(eventWaitHandle.SafeWaitHandle,
                                                               HandleFlag.Inherit,
                                                               HandleFlag.Inherit);

            if (!itWorked)
            {
                throw new Win32Exception(); // uses last win32 error
            }
            SafeWriteObject(eventWaitHandle);
        } // end ProcessRecord()
示例#12
0
        private void ConfigureDropListener()
        {
            var sid        = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
            var accessRule = new EventWaitHandleAccessRule(sid, EventWaitHandleRights.Synchronize | EventWaitHandleRights.Modify, AccessControlType.Allow);

            var security = new EventWaitHandleSecurity();

            security.AddAccessRule(accessRule);

            bool newlyCreated = false;
            var  waitHandle   = new EventWaitHandle(false, EventResetMode.AutoReset, "ExtensionsForOneDrive_DataAvailableEvent", out newlyCreated, security);

            if (!newlyCreated)
            {
                throw new InvalidOperationException("Configuration Changed event already exists.");
            }

            _changeListenerTask = Task.Factory.StartNew(() =>
            {
                while (waitHandle.WaitOne())
                {
                    GetPublicLinkAndStore();
                }
            });
        }
示例#13
0
        /// <summary>
        /// Gets the cross process event wait handle.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <returns></returns>
        private EventWaitHandle GetCrossProcessEventWaitHandle(string name)
        {
            if (!name.StartsWith("Global\\"))
            {
                name = "Global\\" + name;
            }

            EventWaitHandle waitHandle;

            try
            {
                waitHandle = EventWaitHandle.OpenExisting(name, EventWaitHandleRights.Synchronize | EventWaitHandleRights.Modify);
            }
            catch (WaitHandleCannotBeOpenedException)
            {
                // Create a rule that allows any authenticated user to synchronise with us
                var users    = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null);
                var rule     = new EventWaitHandleAccessRule(users, EventWaitHandleRights.Synchronize | EventWaitHandleRights.Modify, AccessControlType.Allow);
                var security = new EventWaitHandleSecurity();
                security.AddAccessRule(rule);
                bool created;
                waitHandle = new EventWaitHandle(false, EventResetMode.AutoReset, name, out created, security);
            }

            return(waitHandle);
        }
        public AutoCaptureEngine(
            IEventAggregator events,
            [ImportMany] IEnumerable <IImageScanner> imageScanners)
        {
            this.events        = events;
            this.imageScanners = imageScanners;
            this.screenCapture = new ScreenCapture();
            var direct3DVersion = Direct3DVersion.Direct3D9SharedMem;

            CaptureMethod      = CaptureMethod.AutoDetect;
            this.captureConfig = new CaptureConfig()
            {
                Direct3DVersion = direct3DVersion
            };
            var security = new MutexSecurity();

            security.AddAccessRule(new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.Synchronize | MutexRights.Modify, AccessControlType.Allow));
            bool created;

            sharedMemMutexes = new[]
            {
                new Mutex(false, "Global\\DXHookD3D9Shared0", out created, security),
                new Mutex(false, "Global\\DXHookD3D9Shared1", out created, security)
            };
            var ewsecurity = new EventWaitHandleSecurity();

            ewsecurity.AddAccessRule(new EventWaitHandleAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), EventWaitHandleRights.FullControl, AccessControlType.Allow));
            captureDxWaitHandle = new EventWaitHandle(false, EventResetMode.ManualReset, "Global\\DXHookD3D9Capture", out created, ewsecurity);
            hookReadyWaitHandle = new EventWaitHandle(false, EventResetMode.ManualReset, "Global\\DXHookD3D9CaptureReady", out created, ewsecurity);
        }
示例#15
0
        /// <summary>
        /// Listen for a stop request.
        /// </summary>
        private void Listen()
        {
            String eventName = String.Format("STOP_COPS_MSGSERVER_{0}", Server.Name);

            sLogger.Info("Listening for event {0}.", eventName);

            var users = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
            var rule  = new EventWaitHandleAccessRule(users,
                                                      EventWaitHandleRights.Synchronize | EventWaitHandleRights.Modify,
                                                      AccessControlType.Allow);
            var security = new EventWaitHandleSecurity();

            security.AddAccessRule(rule);

            bool            createdNew = false;
            EventWaitHandle handle     = new EventWaitHandle(
                false, EventResetMode.AutoReset,
                eventName,
                out createdNew, security);

            handle.WaitOne();

            sLogger.Info("Received stop request !");
            Server.Stop();
        }
示例#16
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MemoryEventStore"/> class.
        /// </summary>
        public MemoryEventStore()
        {
            var waitHandleSecuritySettings = new EventWaitHandleSecurity();

            waitHandleSecuritySettings.AddAccessRule(
                new EventWaitHandleAccessRule(
                    new SecurityIdentifier(WellKnownSidType.WorldSid, null),
                    EventWaitHandleRights.FullControl,
                    AccessControlType.Allow));

            var waitHandleCreated = false;

            this.waitHandle = new EventWaitHandle(false, EventResetMode.AutoReset, "MemoryNotificationService2", out waitHandleCreated, waitHandleSecuritySettings);

            var mutexSecuritySettings = new MutexSecurity();

            mutexSecuritySettings.AddAccessRule(
                new MutexAccessRule(
                    new SecurityIdentifier(WellKnownSidType.WorldSid, null),
                    MutexRights.FullControl,
                    AccessControlType.Allow));

            var mutexCreated = false;

            this.mutex = new Mutex(false, @"Global\MemoryEventStore2Mutex", out mutexCreated, mutexSecuritySettings);
            this.file  = MemoryMappedFile.CreateOrOpen("MemoryEventStore2", 10 * 1024 * 1024 /* 10MB */);

            // TODO (Cameron): Fix.
            Serializer.RegisterConverters(new[] { new DateTimeConverter() });
        }
        public InterProcessLockedMemoryMappedFileStream(string mapName, long capacity)
        {
            _mapName = mapName;
            const int streamHeaderSize = 1024;

            _mmf = MemoryMappedFile.CreateOrOpen(mapName, capacity + streamHeaderSize, MemoryMappedFileAccess.ReadWrite,
                                                 MemoryMappedFileOptions.None,
                                                 null, HandleInheritability.Inheritable);


            _header = _mmf.CreateViewAccessor(0, streamHeaderSize);
            _mmfstr = _mmf.CreateViewStream(streamHeaderSize, capacity);

            var id = string.Format("Global\\PLMMFS-ObLock-{0}", mapName);

            var mutexAccessRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
            var mutexSecurity   = new MutexSecurity();

            mutexSecurity.AddAccessRule(mutexAccessRule);
            _objectMutex = new Mutex(false, id);
            _objectMutex.SetAccessControl(mutexSecurity);

            _writeSignal = new EventWaitHandle(false, EventResetMode.ManualReset,
                                               string.Format("Global\\PLMMFS-Written-{0}", mapName));
            var eventSecurity   = new EventWaitHandleSecurity();
            var eventAccessRule = new EventWaitHandleAccessRule(
                new SecurityIdentifier(WellKnownSidType.WorldSid, null),
                EventWaitHandleRights.FullControl,
                AccessControlType.Allow);

            eventSecurity.AddAccessRule(eventAccessRule);
            _writeSignal.SetAccessControl(eventSecurity);

            _capacity = capacity;
        }
示例#18
0
        static public EventWaitHandle CreateWaitHandle(string id, bool initState, EventResetMode resetMode, bool allowEveryone)
        {
            //EventResetMode.AutoReset: Set()後,不管有無進入WaitOne(),馬上被自動reset
            EventWaitHandle eventWaitHandle;
            bool            createNew;

            if (allowEveryone)
            {   //避免跨Process因權限不足產生WinIOError (Access to the path 'id' is denied.)
                // create a rule that allows anybody in the "Users" group to synchronise with us
                //var users = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);

                EventWaitHandleSecurity   evhSec        = new EventWaitHandleSecurity();
                EventWaitHandleRights     rights        = EventWaitHandleRights.FullControl;// EventWaitHandleRights.Synchronize | EventWaitHandleRights.Modify;
                EventWaitHandleAccessRule evhAccessRule = new EventWaitHandleAccessRule("Everyone", rights, AccessControlType.Allow);
                evhSec.AddAccessRule(evhAccessRule);
                eventWaitHandle = new EventWaitHandle(initState, resetMode, id, out createNew);
                //eventWaitHandle.SetAccessControl(evhSec);
            }
            else
            {
                eventWaitHandle = new EventWaitHandle(initState, resetMode, id, out createNew);
            }

            return(eventWaitHandle);
        }
示例#19
0
        private static EventWaitHandle CreateEvent(string fullName, Acl acl, bool isSet = false)
        {
            EventWaitHandle result = null;

            try
            {
#if !UWP
                var security = new EventWaitHandleSecurity();

                if (acl != null)
                {
                    foreach (var identity in acl)
                    {
                        security.AddAccessRule(new EventWaitHandleAccessRule(identity, EventWaitHandleRights.Modify | EventWaitHandleRights.Synchronize, AccessControlType.Allow));
                    }
                }

                result = new EventWaitHandle(isSet, EventResetMode.ManualReset, fullName, out bool _, security);
#else
                result = new EventWaitHandle(isSet, EventResetMode.ManualReset, fullName);
#endif
                return(result);
            }
            catch
            {
                PlatformSpecificDispose(result);

                throw;
            }
        }
        // Note: in order to be consistent with other messagings (e.g. TcpMessaging) value 0 for timeouts mean infinite time.
        public SharedMemoryReceiver(string memoryMappedFileName, bool useExistingMemoryMappedFile, TimeSpan openTimeout, int maxMessageSize, MemoryMappedFileSecurity memmoryMappedFileSecurity)
        {
            using (EneterTrace.Entering())
            {
                myOpenTimeout          = (openTimeout == TimeSpan.Zero) ? TimeSpan.FromMilliseconds(-1) : openTimeout;
                myMemoryMappedFileName = memoryMappedFileName;
                myMaxMessageSize       = maxMessageSize;

                // If true then the listener will not create the new memory shared file but will open existing one.
                // This is useful for security restrictions if the functionality is used in the windows service.
                myUseExistingMemoryMappedFile = useExistingMemoryMappedFile;

                myMemmoryMappedFileSecurity = memmoryMappedFileSecurity;

                // If the security shall be applied.
                if (myMemmoryMappedFileSecurity != null)
                {
                    // Create the security for the WaitHandle sync logic.
                    myEventWaitHandleSecurity = new EventWaitHandleSecurity();
                    myEventWaitHandleSecurity.SetSecurityDescriptorSddlForm("S:(ML;;NW;;;LW)");
                    SecurityIdentifier        aSid         = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
                    EventWaitHandleAccessRule anAccessRule = new EventWaitHandleAccessRule(aSid,
                                                                                           EventWaitHandleRights.Modify | EventWaitHandleRights.Synchronize,
                                                                                           AccessControlType.Allow);
                    myEventWaitHandleSecurity.AddAccessRule(anAccessRule);
                }
            }
        }
示例#21
0
        private static EventWaitHandleSecurity CreateDefaultWaitHandleSecurity()
        {
            EventWaitHandleSecurity eventWaitHandleSecurity = new EventWaitHandleSecurity();

            eventWaitHandleSecurity.AddAccessRule(new EventWaitHandleAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), EventWaitHandleRights.FullControl, AccessControlType.Allow));
            return(eventWaitHandleSecurity);
        }
示例#22
0
        private EventWaitHandle CreateEvent()
        {
            // based on http://stackoverflow.com/questions/2590334/creating-a-cross-process-eventwaithandle
            var security = new EventWaitHandleSecurity();

            // allow anyone to wait on and signal this lock
            security.AddAccessRule(
                new EventWaitHandleAccessRule(
                    new SecurityIdentifier(WellKnownSidType.WorldSid, domainSid: null),
                    EventWaitHandleRights.FullControl, // doesn't seem to work without this :-/
                    AccessControlType.Allow
                    )
                );

            bool ignored;
            var  @event = new EventWaitHandle(
                // if we create, start as unlocked
                initialState: true,
                // allow only one thread to hold the lock
                mode: EventResetMode.AutoReset,
                name: this.lockName,
                createdNew: out ignored,
                eventSecurity: security
                );

            return(@event);
        }
        /// <summary>Initializes the synchronization objects needed to deal with multiple instances of the same application.</summary>
        /// <param name="baseName">The base name of the synchronization objects.</param>
        /// <param name="identity">The identity to be associated to the synchronization objects.</param>
        void InitializeSynchronizationObjects(string baseName, IdentityReference identity)
        {
            string firstInstanceMutexName               = baseName + "_FirstInstance";
            string serviceInitializationMutexName       = baseName + "_ServiceInitialization";
            string serviceReadySemaphoreName            = baseName + "_ServiceReady";
            string signaledToFirstInstanceSemaphoreName = baseName + "_SignaledToFirstInstance";

            bool isNew;
            var  eventRule = new EventWaitHandleAccessRule(
                identity, EventWaitHandleRights.FullControl, AccessControlType.Allow);
            var eventSecurity = new EventWaitHandleSecurity();

            eventSecurity.AddAccessRule(eventRule);

            var mutexRule     = new MutexAccessRule(identity, MutexRights.FullControl, AccessControlType.Allow);
            var mutexSecurity = new MutexSecurity();

            mutexSecurity.AddAccessRule(mutexRule);

            firstInstanceMutex         = new Mutex(false, firstInstanceMutexName, out isNew, mutexSecurity);
            serviceInitializationMutex = new Mutex(false, serviceInitializationMutexName, out isNew, mutexSecurity);
            serviceReadySemaphore      = new EventWaitHandle(
                false, EventResetMode.ManualReset, serviceReadySemaphoreName, out isNew, eventSecurity);
            signaledToFirstInstanceSemaphore = new EventWaitHandle(
                false, EventResetMode.AutoReset, signaledToFirstInstanceSemaphoreName, out isNew, eventSecurity);
        }
示例#24
0
        private EventWaitHandle CreateSignal(string name)
        {
            EventWaitHandle result = null;

//			if (EventWaitHandle.TryOpenExisting(name, out result))
//			{
//				return result;
//			}
//			else
//			{
            // code from https://stackoverflow.com/questions/2590334/creating-a-cross-process-eventwaithandle
            // user https://stackoverflow.com/users/241462/dean-harding
            var users = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
            var rule  = new EventWaitHandleAccessRule(users, EventWaitHandleRights.Synchronize | EventWaitHandleRights.Modify,
                                                      AccessControlType.Allow);
            var security = new EventWaitHandleSecurity();

            security.AddAccessRule(rule);

            bool created;
            var  wh = new EventWaitHandle(false, EventResetMode.ManualReset, name, out created, security);

            return(wh);
//			}
        }
示例#25
0
        private EventWaitHandleSecurity CreateSecurity(EventWaitHandleRights eventRights)
        {
            EventWaitHandleSecurity security = null;

            // When "running as user", we have to grant the target user permissions to the objects (events and file mapping) explicitly
            if (!string.IsNullOrEmpty(_session.ExecutableProcessUserName))
            {
                security = new EventWaitHandleSecurity();
                IdentityReference si;
                try
                {
                    si = new NTAccount(_session.ExecutableProcessUserName);
                }
                catch (Exception e)
                {
                    throw _logger.WriteException(new SessionLocalException(_session, string.Format(CultureInfo.CurrentCulture, "Error resolving account {0}", _session.ExecutableProcessUserName), e));
                }

                EventWaitHandleAccessRule rule =
                    new EventWaitHandleAccessRule(
                        si, eventRights, AccessControlType.Allow);
                security.AddAccessRule(rule);
            }

            return(security);
        }
示例#26
0
        private static bool OnlyOneCopy()
        {
            bool isnew;

            s_setup_mutex = new Mutex(true, SETUP_MUTEX_NAME, out isnew);

            RestoreEvent = null;
            try
            {
#if RELEASE
                RestoreEvent = AutoResetEvent.OpenExisting(EVENT_NAME);
                RestoreEvent.Set();
                return(false);
            }
            catch (WaitHandleCannotBeOpenedException)
            {
#endif
                string user = Environment.UserDomainName + "\\" + Environment.UserName;
                EventWaitHandleSecurity evh_sec = new EventWaitHandleSecurity();

                EventWaitHandleAccessRule rule = new EventWaitHandleAccessRule(user,
                                                                               EventWaitHandleRights.Synchronize | EventWaitHandleRights.Modify,
                                                                               AccessControlType.Allow);
                evh_sec.AddAccessRule(rule);

                bool was_created;
                RestoreEvent = new EventWaitHandle(false, EventResetMode.AutoReset,
                                                   EVENT_NAME, out was_created, evh_sec);
            }
            catch (Exception)
            {
            }

            return(true);
        }
        /// <summary>
        /// Initializes the security for future events creation.
        /// </summary>
        private static void InitializeEventSecurity()
        {
            AuthorizedUsers = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
            AccessRule = new EventWaitHandleAccessRule(AuthorizedUsers, EventWaitHandleRights.FullControl, AccessControlType.Allow);
            Security = new EventWaitHandleSecurity();

            Security.AddAccessRule(AccessRule);
        }
示例#28
0
        private EventWaitHandleSecurity GetEventWaitHandleSecurity(WellKnownSidType sid, EventWaitHandleRights rights, AccessControlType accessControl)
        {
            EventWaitHandleSecurity   security   = new EventWaitHandleSecurity();
            SecurityIdentifier        identity   = new SecurityIdentifier(sid, null);
            EventWaitHandleAccessRule accessRule = new EventWaitHandleAccessRule(identity, rights, accessControl);

            security.AddAccessRule(accessRule);
            return(security);
        }
    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.
        EventWaitHandleSecurity mSec = new EventWaitHandleSecurity();

        // Add a rule that grants the current user the
        // right to wait on or signal the event and read the
        // permissions on the event.
        EventWaitHandleAccessRule rule = new EventWaitHandleAccessRule(user,
                                                                       EventWaitHandleRights.Synchronize | EventWaitHandleRights.Modify
                                                                       | EventWaitHandleRights.ReadPermissions,
                                                                       AccessControlType.Allow);

        mSec.AddAccessRule(rule);

        // Add a rule that denies the current user the
        // right to change permissions on the event.
        rule = new EventWaitHandleAccessRule(user,
                                             EventWaitHandleRights.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 event, and
        // take ownership of the event. 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 EventWaitHandleAccessRule(user,
                                             EventWaitHandleRights.TakeOwnership |
                                             EventWaitHandleRights.ReadPermissions,
                                             AccessControlType.Allow);
        mSec.RemoveAccessRule(rule);

        ShowSecurity(mSec);
    }
示例#30
0
        private EventWaitHandle ServiceEventFactory(string eventName)
        {
            var securityIdentifier = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
            var accessRule         = new EventWaitHandleAccessRule(securityIdentifier, EventWaitHandleRights.Synchronize, AccessControlType.Allow);
            var security           = new EventWaitHandleSecurity();

            security.AddAccessRule(accessRule);

            return(new EventWaitHandle(false, EventResetMode.AutoReset, eventName, out _, security));
        }
示例#31
0
文件: DbgView.cs 项目: xxy1991/cozy
    private void ListenerThread(object state)
    {
        EventWaitHandle bufferReadyEvent = null;
        EventWaitHandle dataReadyEvent = null;
        MemoryMappedFile memoryMappedFile = null;

        try
        {
            bool createdNew;
            var everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
            var eventSecurity = new EventWaitHandleSecurity();
            eventSecurity.AddAccessRule(new EventWaitHandleAccessRule(everyone, EventWaitHandleRights.Modify | EventWaitHandleRights.Synchronize, AccessControlType.Allow));

            bufferReadyEvent = new EventWaitHandle(false, EventResetMode.AutoReset, "DBWIN_BUFFER_READY", out createdNew, eventSecurity);
            if (!createdNew) throw new Exception("Some DbgView already running");

            dataReadyEvent = new EventWaitHandle(false, EventResetMode.AutoReset, "DBWIN_DATA_READY", out createdNew, eventSecurity);
            if (!createdNew) throw new Exception("Some DbgView already running");

            var memoryMapSecurity = new MemoryMappedFileSecurity();
            memoryMapSecurity.AddAccessRule(new AccessRule<MemoryMappedFileRights>(everyone, MemoryMappedFileRights.ReadWrite, AccessControlType.Allow));
            memoryMappedFile = MemoryMappedFile.CreateNew("DBWIN_BUFFER", 4096, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, memoryMapSecurity, System.IO.HandleInheritability.None);

            bufferReadyEvent.Set();
            this.writer.WriteLine("[DbgView] Started.");

            using (var accessor = memoryMappedFile.CreateViewAccessor())
            {
                byte[] buffer = new byte[4096];
                while (dataReadyEvent.WaitOne())
                {
                    accessor.ReadArray<byte>(0, buffer, 0, buffer.Length);
                    int processId = BitConverter.ToInt32(buffer, 0);
                    int terminator = Array.IndexOf<byte>(buffer, 0, 4);
                    string msg = Encoding.Default.GetString(buffer, 4, (terminator < 0 ? buffer.Length : terminator) - 4);
                    if (hashSet.Contains(processId))
                    {
                        if (msg == "CozyDebugOutput HideDebugPrint")
                        {
                            hashSet.Remove(processId);
                        }
                        writer.WriteLine("[{0:00000}] {1}", processId, msg);
                    }
                    else if (msg == "CozyDebugOutput ShowDebugPrint")
                    {
                        hashSet.Add(processId);
                        writer.WriteLine("[{0:00000}] {1}", processId, msg);
                    }
                    bufferReadyEvent.Set();
                }
            }
        }
        catch (ThreadInterruptedException)
        {
            this.writer.WriteLine("[DbgView] Stopped.");
        }
        catch (Exception e)
        {
            this.writer.WriteLine("[DbgView] Error: " + e.Message);
        }
        finally
        {
            foreach (var disposable in new IDisposable[] { bufferReadyEvent, dataReadyEvent, memoryMappedFile })
            {
                if (disposable != null) disposable.Dispose();
            }
        }
    }