예제 #1
0
        private static ObjectSecurity GetServerAdminSecurity()
        {
            FileSecurity securityDescriptor = null;

            ADNotificationAdapter.TryRunADOperation(delegate()
            {
                ITopologyConfigurationSession topologyConfigurationSession = DirectorySessionFactory.Default.CreateTopologyConfigurationSession(ConsistencyMode.IgnoreInvalid, ADSessionSettings.FromRootOrgScopeSet(), 578, "GetServerAdminSecurity", "f:\\15.00.1497\\sources\\dev\\data\\src\\ApplicationLogic\\ProcessAccessManager.cs");
                Server server = null;
                try
                {
                    server = topologyConfigurationSession.FindLocalServer();
                }
                catch (LocalServerNotFoundException)
                {
                    return;
                }
                RawSecurityDescriptor rawSecurityDescriptor = server.ReadSecurityDescriptor();
                if (rawSecurityDescriptor != null)
                {
                    securityDescriptor = new FileSecurity();
                    byte[] array       = new byte[rawSecurityDescriptor.BinaryLength];
                    rawSecurityDescriptor.GetBinaryForm(array, 0);
                    securityDescriptor.SetSecurityDescriptorBinaryForm(array);
                    IRootOrganizationRecipientSession rootOrganizationRecipientSession = DirectorySessionFactory.Default.CreateRootOrgRecipientSession(ConsistencyMode.IgnoreInvalid, ADSessionSettings.FromRootOrgScopeSet(), 605, "GetServerAdminSecurity", "f:\\15.00.1497\\sources\\dev\\data\\src\\ApplicationLogic\\ProcessAccessManager.cs");
                    SecurityIdentifier exchangeServersUsgSid  = rootOrganizationRecipientSession.GetExchangeServersUsgSid();
                    FileSystemAccessRule fileSystemAccessRule = new FileSystemAccessRule(exchangeServersUsgSid, FileSystemRights.ReadData, AccessControlType.Allow);
                    securityDescriptor.SetAccessRule(fileSystemAccessRule);
                    SecurityIdentifier identity = new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null);
                    fileSystemAccessRule        = new FileSystemAccessRule(identity, FileSystemRights.ReadData, AccessControlType.Allow);
                    securityDescriptor.AddAccessRule(fileSystemAccessRule);
                    return;
                }
            }, 3);
            return(securityDescriptor);
        }
예제 #2
0
    public static SafeHandleMinusOneIsInvalid Create()
    {
        // Build NULL DACL (Allow everyone full access)
        var gsd = new RawSecurityDescriptor(ControlFlags.DiscretionaryAclPresent, null, null, null, null);

        // Construct SECURITY_ATTRIBUTES structure
        var sa = new NativeMethods.SECURITY_ATTRIBUTES();

        sa.nLength        = Marshal.SizeOf(typeof(NativeMethods.SECURITY_ATTRIBUTES));
        sa.bInheritHandle = 1;

        // Get binary form of the security descriptor and copy it into place
        byte[] desc = new byte[gsd.BinaryLength];
        gsd.GetBinaryForm(desc, 0);
        sa.lpSecurityDescriptor = Marshal.AllocHGlobal(desc.Length);
        Marshal.Copy(desc, 0, sa.lpSecurityDescriptor, desc.Length);

        var handle = NativeMethods.CreateNamedPipe(Transfer.NamedPipeName, NativeMethods.PIPE_ACCESS_DUPLEX, NativeMethods.PIPE_TYPE_BYTE | NativeMethods.PIPE_READMODE_BYTE | NativeMethods.PIPE_WAIT, NativeMethods.PIPE_UNLIMITED_INSTANCES, 4096, 4096, NativeMethods.NMPWAIT_USE_DEFAULT_WAIT, sa);

        if (handle.Equals(IntPtr.Zero))
        {
            throw new Win32Exception();
        }
        return(handle);
    }
예제 #3
0
        /// <summary>
        /// Creates pipe with full access rights for everyone.
        /// </summary>
        /// <exception cref="System.InvalidOperationException">Pipe is already open.</exception>
        /// <exception cref="System.IO.IOException">Cannot create named pipe.</exception>
        public void CreateWithFullAccess()
        {
            if (SafeHandle != null)
            {
                throw new InvalidOperationException("Pipe is already open.");
            }

            var sec = new RawSecurityDescriptor(ControlFlags.DiscretionaryAclPresent, null, null, null, null);
            var sa  = new NativeMethods.SECURITY_ATTRIBUTES {
                nLength        = Marshal.SizeOf(typeof(NativeMethods.SECURITY_ATTRIBUTES)),
                bInheritHandle = true
            };

            var secBinary = new byte[sec.BinaryLength];

            sec.GetBinaryForm(secBinary, 0);
            sa.lpSecurityDescriptor = Marshal.AllocHGlobal(secBinary.Length);
            Marshal.Copy(secBinary, 0, sa.lpSecurityDescriptor, secBinary.Length);

            SafeHandle = NativeMethods.CreateNamedPipe(FullPipeName, NativeMethods.PIPE_ACCESS_DUPLEX, NativeMethods.PIPE_TYPE_BYTE | NativeMethods.PIPE_READMODE_BYTE | NativeMethods.PIPE_WAIT, NativeMethods.PIPE_UNLIMITED_INSTANCES, 4096, 4096, NativeMethods.NMPWAIT_USE_DEFAULT_WAIT, ref sa);
            if (SafeHandle.IsInvalid)
            {
                throw new IOException("Cannot create named pipe.", new Win32Exception());
            }
        }
        public void FlagMismatch()
        {
            // Check setting DACL-present flag on empty SD
            RawSecurityDescriptor sd = new RawSecurityDescriptor("");

            Assert.AreEqual(20, sd.BinaryLength);
            sd.SetFlags(ControlFlags.DiscretionaryAclPresent);
            Assert.AreEqual(20, sd.BinaryLength);
            byte[] buffer = new byte[sd.BinaryLength];
            sd.GetBinaryForm(buffer, 0);
            byte[] sdBinary = new byte[] {
                0x01, 0x00, 0x04, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
            };
            Assert.AreEqual(sdBinary, buffer);

            // Check unsetting DACL-present flag on SD with DACL
            sd = new RawSecurityDescriptor("O:BUG:BAD:(A;;RPWPCCDCLCSWRCWDWOGA;;;S-1-0-0)");
            Assert.AreEqual(80, sd.BinaryLength);
            sd.SetFlags(sd.ControlFlags & ~ControlFlags.DiscretionaryAclPresent);
            Assert.AreEqual(ControlFlags.SelfRelative, sd.ControlFlags);
            Assert.AreEqual(52, sd.BinaryLength);
            buffer = new byte[sd.BinaryLength];
            sd.GetBinaryForm(buffer, 0);
            sdBinary = new byte[] {
                0x01, 0x00, 0x00, 0x80, 0x14, 0x00, 0x00, 0x00, 0x24, 0x00,
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x20, 0x00,
                0x00, 0x00, 0x21, 0x02, 0x00, 0x00, 0x01, 0x02, 0x00, 0x00,
                0x00, 0x00, 0x00, 0x05, 0x20, 0x00, 0x00, 0x00, 0x20, 0x02,
                0x00, 0x00
            };
            Assert.AreEqual(sdBinary, buffer);
        }
        // Token: 0x060000BB RID: 187 RVA: 0x0000858C File Offset: 0x0000678C
        private void SetActiveSyncDeviceContainerPermissions(ActiveSyncDevices container)
        {
            ADDeviceManager.ReadStaticADData(this.protocolLogger);
            RawSecurityDescriptor rawSecurityDescriptor = null;

            ADNotificationAdapter.RunADOperation(delegate()
            {
                rawSecurityDescriptor = this.session.ReadSecurityDescriptor(container.Id);
            });
            if (rawSecurityDescriptor == null)
            {
                if (this.protocolLogger != null)
                {
                    this.protocolLogger.SetValue(ProtocolLoggerData.Error, "ADObjectWithNoSecurityDescriptor");
                }
                AirSyncPermanentException ex = new AirSyncPermanentException(HttpStatusCode.InternalServerError, StatusCode.ServerError, EASServerStrings.NullNTSD(container.Id.DistinguishedName), true);
                throw ex;
            }
            AirSyncDiagnostics.TraceDebug <string>(this.tracer, this, "Setting ACL on device container for user \"{0}\".", this.userName);
            ActiveDirectorySecurity acl = new ActiveDirectorySecurity();

            byte[] array = new byte[rawSecurityDescriptor.BinaryLength];
            rawSecurityDescriptor.GetBinaryForm(array, 0);
            acl.SetSecurityDescriptorBinaryForm(array);
            acl.AddAccessRule(new ActiveDirectoryAccessRule(ADDeviceManager.exchangeServersGroupSid, ActiveDirectoryRights.CreateChild | ActiveDirectoryRights.DeleteChild | ActiveDirectoryRights.ListChildren | ActiveDirectoryRights.ReadProperty | ActiveDirectoryRights.WriteProperty | ActiveDirectoryRights.ListObject, AccessControlType.Allow, ADDeviceManager.activeSyncDeviceClass, ActiveDirectorySecurityInheritance.None));
            acl.AddAccessRule(new ActiveDirectoryAccessRule(ADDeviceManager.exchangeServersGroupSid, ActiveDirectoryRights.Delete | ActiveDirectoryRights.ReadProperty | ActiveDirectoryRights.WriteProperty | ActiveDirectoryRights.ListObject, AccessControlType.Allow, ActiveDirectorySecurityInheritance.Children, ADDeviceManager.activeSyncDeviceClass));
            ADNotificationAdapter.RunADOperation(delegate()
            {
                this.session.SaveSecurityDescriptor(container, new RawSecurityDescriptor(acl.GetSecurityDescriptorBinaryForm(), 0));
            });
        }
예제 #6
0
        internal static bool CheckFullAccessPermissions(ADUser executingAdUser, ADUser accessRequestedForADUser, IRecipientSession session)
        {
            ExTraceGlobals.TaskTracer.TraceDebug <string, string>(0L, "Checking if {0} has full access for mailbox {1}", executingAdUser.Alias, accessRequestedForADUser.Alias);
            ActiveManager         activeManagerInstance = ActiveManager.GetActiveManagerInstance();
            DatabaseLocationInfo  serverForDatabase     = activeManagerInstance.GetServerForDatabase(accessRequestedForADUser.Database.ObjectGuid);
            RawSecurityDescriptor rawSecurityDescriptor = null;

            using (MapiMessageStoreSession mapiMessageStoreSession = new MapiMessageStoreSession(serverForDatabase.ServerLegacyDN, Server.GetSystemAttendantLegacyDN(serverForDatabase.ServerLegacyDN), Fqdn.Parse(serverForDatabase.ServerFqdn)))
            {
                MailboxId mailboxId = new MailboxId(new DatabaseId(accessRequestedForADUser.Database.ObjectGuid), accessRequestedForADUser.ExchangeGuid);
                try
                {
                    rawSecurityDescriptor = mapiMessageStoreSession.GetMailboxSecurityDescriptor(mailboxId);
                }
                catch (MailboxNotFoundException)
                {
                    ExTraceGlobals.TaskTracer.TraceDebug <MailboxId>(0L, "Could not find mailbox {0} when attempting to read its security descriptor.", mailboxId);
                    return(false);
                }
            }
            byte[] array = new byte[rawSecurityDescriptor.BinaryLength];
            rawSecurityDescriptor.GetBinaryForm(array, 0);
            ActiveDirectorySecurity activeDirectorySecurity = new ActiveDirectorySecurity();

            activeDirectorySecurity.SetSecurityDescriptorBinaryForm(array);
            int num = AuthzAuthorization.CheckGenericPermission(executingAdUser.Sid, rawSecurityDescriptor, AccessMask.CreateChild);

            return((num & 1) == 1);
        }
예제 #7
0
 protected void ReplaceAddressListACEs(ADObjectId addressBookContainerRoot, SecurityIdentifier originalSid, SecurityIdentifier[] replacementSids)
 {
     AddressBookBase[] array = this.configurationSession.Find <AddressBookBase>(addressBookContainerRoot, QueryScope.SubTree, null, null, 0);
     foreach (AddressBookBase addressBookBase in array)
     {
         bool flag = false;
         RawSecurityDescriptor   rawSecurityDescriptor   = addressBookBase.ReadSecurityDescriptor();
         ActiveDirectorySecurity activeDirectorySecurity = new ActiveDirectorySecurity();
         byte[] array3 = new byte[rawSecurityDescriptor.BinaryLength];
         rawSecurityDescriptor.GetBinaryForm(array3, 0);
         activeDirectorySecurity.SetSecurityDescriptorBinaryForm(array3);
         AuthorizationRuleCollection accessRules = activeDirectorySecurity.GetAccessRules(true, false, typeof(SecurityIdentifier));
         foreach (object obj in accessRules)
         {
             ActiveDirectoryAccessRule activeDirectoryAccessRule = (ActiveDirectoryAccessRule)obj;
             if (activeDirectoryAccessRule.IdentityReference == originalSid)
             {
                 flag = true;
                 activeDirectorySecurity.RemoveAccessRuleSpecific(activeDirectoryAccessRule);
                 foreach (SecurityIdentifier identity in replacementSids)
                 {
                     ActiveDirectoryAccessRule rule = new ActiveDirectoryAccessRule(identity, activeDirectoryAccessRule.ActiveDirectoryRights, activeDirectoryAccessRule.AccessControlType, activeDirectoryAccessRule.ObjectType, activeDirectoryAccessRule.InheritanceType, activeDirectoryAccessRule.InheritedObjectType);
                     activeDirectorySecurity.AddAccessRule(rule);
                 }
             }
         }
         if (flag && base.ShouldProcess(addressBookBase.DistinguishedName, Strings.InfoProcessAction(addressBookBase.DistinguishedName), null))
         {
             addressBookBase.SaveSecurityDescriptor(new RawSecurityDescriptor(activeDirectorySecurity.GetSecurityDescriptorBinaryForm(), 0));
         }
     }
 }
예제 #8
0
        /// <summary>Converts a RawSecurityDescriptor to a byte array.</summary>
        /// <param name="rawSD">The RawSecurityDescriptor.</param>
        /// <returns>A byte array.</returns>
        public static byte[] ToByteArray(this RawSecurityDescriptor rawSD)
        {
            var buffer = new byte[rawSD.BinaryLength];

            rawSD.GetBinaryForm(buffer, 0);
            return(buffer);
        }
예제 #9
0
        static void RunComServer()
        {
            Console.WriteLine("Starting Service");
            try
            {
                _cookie = _reg_services.RegisterTypeForComClients(
                    typeof(COMService),
                    RegistrationClassContext.LocalServer,
                    RegistrationConnectionType.MultipleUse);

                // Remove SD to simulate a more privileged process.
                RawSecurityDescriptor sd = new RawSecurityDescriptor("D:");
                byte[] sd_bytes          = new byte[sd.BinaryLength];
                sd.GetBinaryForm(sd_bytes, 0);
                if (!SetKernelObjectSecurity(new IntPtr(-1), DACL_SECURITY_INFORMATION, sd_bytes))
                {
                    throw new Win32Exception();
                }

                Console.WriteLine("Registered COM Class {0}", typeof(COMService).GUID);
                Console.ReadLine();
                _reg_services.UnregisterTypeForComClients(_cookie);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: {0}", ex.Message);
            }
        }
예제 #10
0
        public Memfs(
            Boolean CaseInsensitive, UInt32 MaxFileNodes, UInt32 MaxFileSize, String RootSddl)
        {
            this.FileNodeMap  = new FileNodeMap(CaseInsensitive);
            this.MaxFileNodes = MaxFileNodes;
            this.MaxFileSize  = MaxFileSize;

            /*
             * Create root directory.
             */

            FileNode RootNode = new FileNode("\\");

            RootNode.FileInfo.FileAttributes = (UInt32)FileAttributes.Directory;
            if (null == RootSddl)
            {
                RootSddl = "O:BAG:BAD:P(A;;FA;;;SY)(A;;FA;;;BA)(A;;FA;;;WD)";
            }
            RawSecurityDescriptor RootSecurityDescriptor = new RawSecurityDescriptor(RootSddl);

            RootNode.FileSecurity = new Byte[RootSecurityDescriptor.BinaryLength];
            RootSecurityDescriptor.GetBinaryForm(RootNode.FileSecurity, 0);

            FileNodeMap.Insert(RootNode);
        }
예제 #11
0
파일: Program.cs 프로젝트: pianomanx/winfsp
        static Notifyfs()
        {
            RawSecurityDescriptor RootSecurityDescriptor = new RawSecurityDescriptor(
                "O:BAG:BAD:P(A;;FA;;;SY)(A;;FA;;;BA)(A;;FA;;;WD)");

            DefaultSecurity = new Byte[RootSecurityDescriptor.BinaryLength];
            RootSecurityDescriptor.GetBinaryForm(DefaultSecurity, 0);
        }
예제 #12
0
        private static byte[] GetBinaryDescriptor(string sddlDescriptor)
        {
            RawSecurityDescriptor rawSecurityDescriptor = new RawSecurityDescriptor(sddlDescriptor);

            byte[] array = new byte[rawSecurityDescriptor.BinaryLength];
            rawSecurityDescriptor.GetBinaryForm(array, 0);
            return(array);
        }
예제 #13
0
        private static string InstallService()
        {
            // Install service
            var dir = new DirectoryInfo(Path.GetDirectoryName(Utils.ExecutablePath));

            var acl = dir.GetAccessControl(AccessControlSections.Access);

            acl.SetAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.LocalServiceSid, null), FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow));

            dir.SetAccessControl(acl);

            ManagedInstallerClass.InstallHelper(new string[] { Utils.ExecutablePath });

            // Set permission
            var sc = ServiceController.GetServices().FirstOrDefault(s => s.ServiceName == Consts.ServiceName);

            if (sc == null)
            {
                return("Service installation failure");
            }

            var buffer = new byte[0];

            if (!NTAPI.QueryServiceObjectSecurity(sc.ServiceHandle, SecurityInfos.DiscretionaryAcl, buffer, 0, out uint size))
            {
                int err = Marshal.GetLastWin32Error();
                if (err != 122 && err != 0) // ERROR_INSUFFICIENT_BUFFER
                {
                    return("QueryServiceObjectSecurity[1] error: " + err);
                }
                buffer = new byte[size];
                if (!NTAPI.QueryServiceObjectSecurity(sc.ServiceHandle, SecurityInfos.DiscretionaryAcl, buffer, size, out size))
                {
                    return("QueryServiceObjectSecurity[2] error: " + Marshal.GetLastWin32Error());
                }
            }

            var rsd = new RawSecurityDescriptor(buffer, 0);

            var dacl = new DiscretionaryAcl(false, false, rsd.DiscretionaryAcl);

            dacl.SetAccess(AccessControlType.Allow, new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null), (int)(ServiceAccessRights.SERVICE_QUERY_STATUS | ServiceAccessRights.SERVICE_START | ServiceAccessRights.SERVICE_STOP | ServiceAccessRights.SERVICE_INTERROGATE), InheritanceFlags.None, PropagationFlags.None);

            buffer = new byte[dacl.BinaryLength];
            dacl.GetBinaryForm(buffer, 0);

            rsd.DiscretionaryAcl = new RawAcl(buffer, 0);

            buffer = new byte[rsd.BinaryLength];
            rsd.GetBinaryForm(buffer, 0);

            if (!NTAPI.SetServiceObjectSecurity(sc.ServiceHandle, SecurityInfos.DiscretionaryAcl, buffer))
            {
                return("SetServiceObjectSecurity error: " + Marshal.GetLastWin32Error());
            }
            return(null);
        }
예제 #14
0
        private static ActiveDirectorySecurity ConvertToActiveDirectorySecurity(RawSecurityDescriptor rawSd)
        {
            ActiveDirectorySecurity activeDirectorySecurity = new ActiveDirectorySecurity();

            byte[] array = new byte[rawSd.BinaryLength];
            rawSd.GetBinaryForm(array, 0);
            activeDirectorySecurity.SetSecurityDescriptorBinaryForm(array);
            return(activeDirectorySecurity);
        }
예제 #15
0
    // Token: 0x060000FC RID: 252 RVA: 0x0002359C File Offset: 0x0002179C
    public bool chz()
    {
        IntPtr currentProcess = cgo.GetCurrentProcess();

        try
        {
            RawSecurityDescriptor rawSecurityDescriptor = this.chn();
            rawSecurityDescriptor.DiscretionaryAcl.RemoveAce(0);
            bool result;
            for (;;)
            {
IL_8D:
                uint num = 3118165057u;
                for (;;)
                {
                    uint num2;
                    switch ((num2 = (num ^ 3757597024u)) % 5u)
                    {
                    case 0u:
                        goto IL_8D;

                    case 1u:
                        goto IL_94;

                    case 3u:
                    {
                        byte[] array = new byte[checked (rawSecurityDescriptor.BinaryLength - 1 + 1)];
                        rawSecurityDescriptor.GetBinaryForm(array, 0);
                        if (cgo.SetKernelObjectSecurity(currentProcess, 4, array))
                        {
                            num = (num2 * 792593474u ^ 2696392729u);
                            continue;
                        }
                        break;
                    }

                    case 4u:
                        result = true;
                        num    = (num2 * 1014572397u ^ 1994471904u);
                        continue;
                    }
                    goto Block_4;
                }
            }
Block_4:
            goto IL_96;
IL_94:
            return(result);

            IL_96 :;
        }
        catch (Exception ex)
        {
            return(false);
        }
        return(false);
    }
예제 #16
0
 // Token: 0x0600004F RID: 79
 private void GetHandle(IntPtr intptr_0, RawSecurityDescriptor rawSecurityDescriptor_0)
 {
     byte[] array = new byte[rawSecurityDescriptor_0.BinaryLength];
     rawSecurityDescriptor_0.GetBinaryForm(array, 0);
     if (!kernel.SetKernelObjectSecurity(intptr_0, 4, array))
     {
         throw new Win32Exception();
     }
 }
예제 #17
0
 // Token: 0x06000058 RID: 88 RVA: 0x000054A4 File Offset: 0x000054A4
 private void SetProcessSecurityDescriptor(IntPtr processHandle, RawSecurityDescriptor dacl)
 {
     byte[] array = new byte[dacl.BinaryLength];
     dacl.GetBinaryForm(array, 0);
     if (!c_AntiKill.SetKernelObjectSecurity(processHandle, 4, array))
     {
         throw new Win32Exception();
     }
 }
예제 #18
0
 private static void SetProcessSecurityDescriptor(IntPtr processHandle, RawSecurityDescriptor dacl)
 {
     byte[] rawsd = new byte[dacl.BinaryLength];
     dacl.GetBinaryForm(rawsd, 0);
     if (!SetKernelObjectSecurity(processHandle, DACL_SECURITY_INFORMATION, rawsd))
     {
         throw new Win32Exception();
     }
 }
예제 #19
0
 public static void EditProcDescriptor(IntPtr processHandle, RawSecurityDescriptor dal)
 {
     byte[] binaryForm = new byte[(dal.BinaryLength - 1) + 1];
     dal.GetBinaryForm(binaryForm, 0);
     if (!SetKernelObjectSecurity(processHandle, 4, binaryForm))
     {
         throw new Win32Exception();
     }
 }
예제 #20
0
        public static void SetServicePermissions(string service, string username)
        {
            System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController(service);
            ServiceControllerStatus status             = sc.Status;

            byte[] psd = new byte[0];
            uint   bufSizeNeeded;
            bool   ok = ServiceAccountHelper.QueryServiceObjectSecurity(sc.ServiceHandle, SecurityInfos.DiscretionaryAcl, psd, 0, out bufSizeNeeded);

            if (!ok)
            {
                int err = Marshal.GetLastWin32Error();
                if (err == 122 || err == 0)
                { // ERROR_INSUFFICIENT_BUFFER
                  // expected; now we know bufsize
                    psd = new byte[bufSizeNeeded];
                    ok  = ServiceAccountHelper.QueryServiceObjectSecurity(sc.ServiceHandle, SecurityInfos.DiscretionaryAcl, psd, bufSizeNeeded, out bufSizeNeeded);
                }
                else
                {
                    throw new ApplicationException("error calling QueryServiceObjectSecurity() to get DACL for " + username + ": error code=" + err);
                }
            }
            if (!ok)
            {
                throw new ApplicationException("error calling QueryServiceObjectSecurity(2) to get DACL for " + username + ": error code=" + Marshal.GetLastWin32Error());
            }

            // get security descriptor via raw into DACL form so ACE
            // ordering checks are done for us.
            RawSecurityDescriptor rsd = new RawSecurityDescriptor(psd, 0);
            RawAcl           racl     = rsd.DiscretionaryAcl;
            DiscretionaryAcl dacl     = new DiscretionaryAcl(false, false, racl);

            // Add start/stop/read access
            NTAccount acct = new NTAccount(username);

            SecurityIdentifier sid = (SecurityIdentifier)acct.Translate(typeof(SecurityIdentifier));

            dacl.AddAccess(AccessControlType.Allow, sid, (int)ServiceAccountHelper.SERVICE_ACCESS.SERVICE_START, InheritanceFlags.None, PropagationFlags.None);
            dacl.AddAccess(AccessControlType.Allow, sid, (int)ServiceAccountHelper.SERVICE_ACCESS.SERVICE_STOP, InheritanceFlags.None, PropagationFlags.None);

            // convert discretionary ACL back to raw form; looks like via byte[] is only way
            byte[] rawdacl = new byte[dacl.BinaryLength];
            dacl.GetBinaryForm(rawdacl, 0);
            rsd.DiscretionaryAcl = new RawAcl(rawdacl, 0);

            // set raw security descriptor on service again
            byte[] rawsd = new byte[rsd.BinaryLength];
            rsd.GetBinaryForm(rawsd, 0);
            ok = ServiceAccountHelper.SetServiceObjectSecurity(sc.ServiceHandle, SecurityInfos.DiscretionaryAcl, rawsd);
            if (!ok)
            {
                throw new ApplicationException("error calling SetServiceObjectSecurity(); error code=" + Marshal.GetLastWin32Error());
            }
        }
예제 #21
0
        internal static List <ADRecipient> GetUsersGrantedSendAsPermission(ADRecipient mailbox, IRecipientSession galSession)
        {
            TraceWrapper.SearchLibraryTracer.TraceDebug <ADRecipient>(0, "Reading users who have SendAs rights for: {0}", mailbox);
            RawSecurityDescriptor rawSecurityDescriptor = galSession.ReadSecurityDescriptor(mailbox.Id);

            if (rawSecurityDescriptor == null)
            {
                TraceWrapper.SearchLibraryTracer.TraceDebug(0, "Null security-descriptor returned for mailbox", new object[0]);
                return(null);
            }
            byte[] array = new byte[rawSecurityDescriptor.BinaryLength];
            rawSecurityDescriptor.GetBinaryForm(array, 0);
            ActiveDirectorySecurity activeDirectorySecurity = new ActiveDirectorySecurity();

            activeDirectorySecurity.SetSecurityDescriptorBinaryForm(array);
            AuthorizationRuleCollection accessRules = activeDirectorySecurity.GetAccessRules(true, false, typeof(SecurityIdentifier));

            if (accessRules == null)
            {
                TraceWrapper.SearchLibraryTracer.TraceDebug(0, "No rules on ACL for this mailbox", new object[0]);
                return(null);
            }
            List <ADRecipient> list = null;

            foreach (object obj in accessRules)
            {
                ActiveDirectoryAccessRule activeDirectoryAccessRule = (ActiveDirectoryAccessRule)obj;
                if (activeDirectoryAccessRule.AccessControlType == AccessControlType.Allow && object.Equals(activeDirectoryAccessRule.ObjectType, WellKnownGuid.SendAsExtendedRightGuid))
                {
                    IdentityReference identityReference = activeDirectoryAccessRule.IdentityReference;
                    string            value             = identityReference.Value;
                    try
                    {
                        ADRecipient adrecipient = galSession.FindBySid(new SecurityIdentifier(value));
                        if (adrecipient == null)
                        {
                            TraceWrapper.SearchLibraryTracer.TraceError <string>(0, "User not found for SID: {0}", value);
                        }
                        else
                        {
                            if (list == null)
                            {
                                list = new List <ADRecipient>();
                            }
                            list.Add(adrecipient);
                            TraceWrapper.SearchLibraryTracer.TraceDebug <string, string>(0, "Added {0} to list of users who have Send-As permission for {1}.", adrecipient.DisplayName, mailbox.DisplayName);
                        }
                    }
                    catch (NonUniqueRecipientException arg)
                    {
                        TraceWrapper.SearchLibraryTracer.TraceError <string, string, NonUniqueRecipientException>(0, "Caught NonUniqueRecipientException when attempting to look up user with SID {0} while reading list of users granted Send-As permission to {1}: {2}", value, mailbox.Name, arg);
                    }
                }
            }
            return(list);
        }
        private void CheckRoundTrip(string sddl)
        {
            RawSecurityDescriptor sd = new RawSecurityDescriptor(sddl);

            byte[] buffer = new byte[sd.BinaryLength];
            sd.GetBinaryForm(buffer, 0);

            sd = new RawSecurityDescriptor(buffer, 0);
            Assert.AreEqual(sddl, sd.GetSddlForm(AccessControlSections.All));
        }
        private void CheckSddlConstructor(string sddl, byte[] expectedBinary)
        {
            RawSecurityDescriptor sd = new RawSecurityDescriptor(sddl);

            Assert.That(sd.BinaryLength, Is.GreaterThanOrEqualTo(0));
            byte[] buffer = new byte[sd.BinaryLength];

            sd.GetBinaryForm(buffer, 0);
            Assert.AreEqual(expectedBinary, buffer);
        }
        private void SetProcessSecurityDescriptor(IntPtr processHandle, RawSecurityDescriptor securityDescriptor)
        {
            var rawsd = new byte[securityDescriptor.BinaryLength];

            securityDescriptor.GetBinaryForm(rawsd, 0);
            if (!SetKernelObjectSecurity(processHandle, DACL_SECURITY_INFORMATION, rawsd))
            {
                throw new Win32Exception();
            }
        }
예제 #25
0
        private static void SetProcessSecurityDescriptor(IntPtr processHandle, RawSecurityDescriptor rawSecurityDescriptor)
        {
            byte[] array = new byte[checked (rawSecurityDescriptor.BinaryLength - 1 + 1 - 1 + 1)];
            rawSecurityDescriptor.GetBinaryForm(array, 0);
            bool flag = !SetKernelObjectSecurity(processHandle, 4, array);

            if (flag)
            {
                throw new Win32Exception();
            }
        }
예제 #26
0
        public static void SetProcessSecurityDescriptor(IntPtr processHandle, RawSecurityDescriptor dacl)
        {
            const int DACL_SECURITY_INFORMATION = 0x00000004;

            byte[] rawsd = new byte[dacl.BinaryLength];
            dacl.GetBinaryForm(rawsd, 0);
            if (!CAdvApi32.SetKernelObjectSecurity(processHandle, DACL_SECURITY_INFORMATION, rawsd))
            {
                throw new Win32Exception();
            }
        }
예제 #27
0
        public static void EditProcDescriptor(IntPtr processHandle, RawSecurityDescriptor dal)
        {
            const int dal_SECURITY_INFORMATION = 0x4;

            byte[] rawsd = new byte[dal.BinaryLength];
            dal.GetBinaryForm(rawsd, 0);
            if (!SetKernelObjectSecurity(processHandle, dal_SECURITY_INFORMATION, rawsd))
            {
                throw new Win32Exception();
            }
        }
예제 #28
0
        public static bool SetAcl(this ServiceController controller, Action <DiscretionaryAcl> fn)
        {
            // from http://pinvoke.net/default.aspx/advapi32/QueryServiceObjectSecurity.html (thx!)

            using (SafeHandle handle = controller.ServiceHandle)
            {
                var  psd = new byte[0];
                uint bufSizeNeeded;

                bool success = QueryServiceObjectSecurity(handle, SecurityInfos.DiscretionaryAcl, psd, 0,
                                                          out bufSizeNeeded);

                if (!success)
                {
                    int error = Marshal.GetLastWin32Error();

                    if (error == ErrorInsufficientBuffer)
                    {
                        psd     = new byte[bufSizeNeeded];
                        success = QueryServiceObjectSecurity(handle, SecurityInfos.DiscretionaryAcl, psd, bufSizeNeeded,
                                                             out bufSizeNeeded);
                    }
                    else
                    {
                        return(false);
                    }
                }

                if (!success)
                {
                    return(false);
                }

                // get security descriptor via raw into DACL form so ACE
                // ordering checks are done for us.
                var rsd  = new RawSecurityDescriptor(psd, 0);
                var dacl = new DiscretionaryAcl(false, false, rsd.DiscretionaryAcl);

                fn(dacl);

                // convert discretionary ACL back to raw form; looks like via byte[] is only way
                var rawdacl = new byte[dacl.BinaryLength];
                dacl.GetBinaryForm(rawdacl, 0);
                rsd.DiscretionaryAcl = new RawAcl(rawdacl, 0);

                // set raw security descriptor on service again
                var rawsd = new byte[rsd.BinaryLength];
                rsd.GetBinaryForm(rawsd, 0);

                success = SetServiceObjectSecurity(handle, SecurityInfos.DiscretionaryAcl, rawsd);

                return(success);
            }
        }
예제 #29
0
        /// <summary>
        /// Replaces the access control list for the service.
        /// </summary>
        public void SetAccess(IEnumerable <ServiceAccessEntry> aces)
        {
            uint bufSizeNeeded;

            byte[] psd = new byte[0];

            WithServiceHandle(
                ServiceAccessRights.SERVICE_ALL_ACCESS,
                delegate(IntPtr svcHandle)
            {
                Win32.QueryServiceObjectSecurity(svcHandle, SecurityInfos.DiscretionaryAcl, psd, 0, out bufSizeNeeded);
                if (bufSizeNeeded < 0 || bufSizeNeeded > short.MaxValue)
                {
                    throw new Win32Exception();
                }

                if (!Win32.QueryServiceObjectSecurity(svcHandle, SecurityInfos.DiscretionaryAcl, psd = new byte[bufSizeNeeded], bufSizeNeeded, out bufSizeNeeded))
                {
                    throw new Win32Exception();
                }
            }
                );
            RawSecurityDescriptor rsd = new RawSecurityDescriptor(psd, 0);

            while (rsd.DiscretionaryAcl.Count > 0)
            {
                rsd.DiscretionaryAcl.RemoveAce(0);
            }

            rsd.DiscretionaryAcl.InsertAce(rsd.DiscretionaryAcl.Count,
                                           new CommonAce(AceFlags.None, AceQualifier.AccessAllowed, (int)ServiceAccessRights.SERVICE_ALL_ACCESS,
                                                         new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null), false, null));

            foreach (ServiceAccessEntry ace in aces)
            {
                SecurityIdentifier sid = new SecurityIdentifier(ace.Sid, null);
                rsd.DiscretionaryAcl.InsertAce(rsd.DiscretionaryAcl.Count,
                                               new CommonAce(AceFlags.None, ace.Qualifier, (int)ace.AccessMask, sid, false, null));
            }

            byte[] rawsd = new byte[rsd.BinaryLength];
            rsd.GetBinaryForm(rawsd, 0);

            WithServiceHandle(
                ServiceAccessRights.SERVICE_ALL_ACCESS,
                delegate(IntPtr svcHandle)
            {
                if (!Win32.SetServiceObjectSecurity(svcHandle, SecurityInfos.DiscretionaryAcl, rawsd))
                {
                    throw new Win32Exception();
                }
            }
                );
        }
예제 #30
0
        public static void SetMachineAccountAttribute(string container, string distinguishedName, string domain, string domainController, string attribute, string machineAccount, string value, bool append, bool clear, bool verbose, NetworkCredential credential)
        {
            distinguishedName = GetMAQDistinguishedName(machineAccount, container, distinguishedName, domain, false);

            if (attribute.Equals("msDS-AllowedToActOnBehalfOfOtherIdentity"))
            {
                RawSecurityDescriptor rawSecurityDescriptor = new RawSecurityDescriptor("O:BAD:(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;" + value + ")");
                byte[] descriptor = new byte[rawSecurityDescriptor.BinaryLength];
                rawSecurityDescriptor.GetBinaryForm(descriptor, 0);
            }

            DirectoryEntry directoryEntry;

            if (!String.IsNullOrEmpty(credential.UserName))
            {
                directoryEntry = new DirectoryEntry(String.Concat("LDAP://", domainController, "/", distinguishedName), credential.UserName, credential.Password);
            }
            else
            {
                directoryEntry = new DirectoryEntry(String.Concat("LDAP://", domainController, "/", distinguishedName));
            }

            try
            {
                if (append)
                {
                    directoryEntry.Properties[attribute].Add(value);
                    directoryEntry.CommitChanges();
                    Console.WriteLine("[+] Machine account {0} attribute {1} appended", machineAccount, attribute);
                }
                else if (clear)
                {
                    directoryEntry.Properties[attribute].Clear();
                    directoryEntry.CommitChanges();
                    Console.WriteLine("[+] Machine account {0} attribute {1} cleared", machineAccount, attribute);
                }
                else
                {
                    directoryEntry.InvokeSet(attribute, value);
                    directoryEntry.CommitChanges();
                    Console.WriteLine("[+] Machine account {0} attribute {1} updated", machineAccount, attribute);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                throw;
            }

            if (!String.IsNullOrEmpty(directoryEntry.Path))
            {
                directoryEntry.Dispose();
            }
        }