Example #1
0
        public void GetBinaryFormOffset()
        {
            CommonSecurityDescriptor csd = new CommonSecurityDescriptor
                                               (false, false, ControlFlags.None, null, null, null, null);

            csd.GetBinaryForm(new byte[csd.BinaryLength], 1);
        }
Example #2
0
        public void GetBinaryFormNull()
        {
            CommonSecurityDescriptor csd = new CommonSecurityDescriptor
                                               (false, false, ControlFlags.None, null, null, null, null);

            csd.GetBinaryForm(null, 0);
        }
        internal static IpcPort Create(string portName, CommonSecurityDescriptor securityDescriptor, bool exclusive)
        {
            SECURITY_ATTRIBUTES security_attributes;

            if (Environment.OSVersion.Platform != PlatformID.Win32NT)
            {
                throw new NotSupportedException(CoreChannel.GetResourceString("Remoting_Ipc_Win9x"));
            }
            PipeHandle handle = null;
            string     lpName = @"\\.\pipe\" + portName;

            security_attributes = new SECURITY_ATTRIBUTES {
                nLength = Marshal.SizeOf(security_attributes)
            };
            byte[] binaryForm = null;
            if (securityDescriptor == null)
            {
                securityDescriptor = s_securityDescriptor;
            }
            binaryForm = new byte[securityDescriptor.BinaryLength];
            securityDescriptor.GetBinaryForm(binaryForm, 0);
            GCHandle handle2 = GCHandle.Alloc(binaryForm, GCHandleType.Pinned);

            security_attributes.lpSecurityDescriptor = Marshal.UnsafeAddrOfPinnedArrayElement(binaryForm, 0);
            handle = NativePipe.CreateNamedPipe(lpName, (uint)(0x40000003 | (exclusive ? 0x80000 : 0)), 0, 0xff, 0x2000, 0x2000, uint.MaxValue, security_attributes);
            handle2.Free();
            if (handle.Handle.ToInt32() == -1)
            {
                int errorCode = Marshal.GetLastWin32Error();
                throw new RemotingException(string.Format(CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_Ipc_CreateIpcFailed"), new object[] { GetMessage(errorCode) }));
            }
            return(new IpcPort(portName, handle));
        }
Example #4
0
        public void GetBinaryForm()
        {
            CommonSecurityDescriptor csd = new CommonSecurityDescriptor
                                               (false, false, ControlFlags.None, null, null, null, null);

            Assert.AreEqual(20, csd.BinaryLength);
            byte[] binaryForm = new byte[csd.BinaryLength];
            csd.GetBinaryForm(binaryForm, 0);

            Assert.AreEqual(ControlFlags.DiscretionaryAclPresent | ControlFlags.SelfRelative,
                            csd.ControlFlags);

            // The default 'Allow Everyone Full Access' serializes as NOT having a
            // DiscretionaryAcl, as the above demonstrates (byte 3 is 0 not 4).
            Assert.AreEqual(new byte[20] {
                1, 0, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
            }, binaryForm);

            // Changing SystemAcl protection does nothing special.
            csd.SetSystemAclProtection(true, true);
            Assert.AreEqual(20, csd.BinaryLength);

            // Modifying the DiscretionaryAcl (even effective no-ops like this) causes serialization.
            csd.SetDiscretionaryAclProtection(false, true);
            Assert.AreEqual(48, csd.BinaryLength);
        }
        private SafeFileHandle CreateNamedPipe(string pipeName)
        {
            CommonSecurityDescriptor sd = new CommonSecurityDescriptor(false, false, "D:(A;;GA;;;LS)(A;;GA;;;BA)(A;;GA;;;IU)");

            byte[] sdBytes = new byte[sd.BinaryLength];
            sd.GetBinaryForm(sdBytes, 0);
            GCHandle gcHandle = GCHandle.Alloc(sdBytes, GCHandleType.Pinned);

            Native.SECURITY_ATTRIBUTES securityAttributes = new Native.SECURITY_ATTRIBUTES();
            securityAttributes.nLength              = Marshal.SizeOf(securityAttributes);
            securityAttributes.bInheritHandle       = 0;
            securityAttributes.lpSecurityDescriptor = Marshal.UnsafeAddrOfPinnedArrayElement(sdBytes, 0);

            IntPtr handle = Native.CreateNamedPipe(
                pipeName,
                Native.PIPE_ACCESS_DUPLEX | Native.FILE_FLAG_OVERLAPPED | Native.FILE_FLAG_FIRST_PIPE_INSTANCE,
                Native.PIPE_TYPE_BYTE | Native.PIPE_READMODE_BYTE | Native.PIPE_WAIT,
                1,
                2048,
                2048,
                Native.NMPWAIT_USE_DEFAULT_WAIT,
                securityAttributes);

            gcHandle.Free();

            return(new SafeFileHandle(handle, true));
        }
        private static byte[] FromSecurityIdentifiersFull(List <SecurityIdentifier> allowedSids, int accessRights)
        {
            int capacity = (allowedSids == null) ? 3 : (2 + allowedSids.Count);
            DiscretionaryAcl discretionaryAcl = new DiscretionaryAcl(false, false, capacity);

            discretionaryAcl.AddAccess(AccessControlType.Deny, new SecurityIdentifier(WellKnownSidType.NetworkSid, null), 0x10000000, InheritanceFlags.None, PropagationFlags.None);
            int accessMask = GenerateClientAccessRights(accessRights);

            if (allowedSids == null)
            {
                discretionaryAcl.AddAccess(AccessControlType.Allow, new SecurityIdentifier(WellKnownSidType.WorldSid, null), accessMask, InheritanceFlags.None, PropagationFlags.None);
            }
            else
            {
                for (int i = 0; i < allowedSids.Count; i++)
                {
                    SecurityIdentifier sid = allowedSids[i];
                    discretionaryAcl.AddAccess(AccessControlType.Allow, sid, accessMask, InheritanceFlags.None, PropagationFlags.None);
                }
            }
            discretionaryAcl.AddAccess(AccessControlType.Allow, GetProcessLogonSid(), accessRights, InheritanceFlags.None, PropagationFlags.None);
            CommonSecurityDescriptor descriptor = new CommonSecurityDescriptor(false, false, ControlFlags.None, null, null, null, discretionaryAcl);

            byte[] binaryForm = new byte[descriptor.BinaryLength];
            descriptor.GetBinaryForm(binaryForm, 0);
            return(binaryForm);
        }
        /// <summary>
        /// Helper method to create a PowerShell transport named pipe via native API, along
        /// with a returned .Net NamedPipeServerStream object wrapping the named pipe.
        /// </summary>
        /// <param name="pipeName">Named pipe core name.</param>
        /// <param name="securityDesc"></param>
        /// <returns>NamedPipeServerStream</returns>
        internal static NamedPipeServerStream CreateNamedPipe(
            string pipeName,
            PipeSecurity pipeSecurity)

        {
            string fullPipeName = @"\\.\pipe\" + pipeName;
            CommonSecurityDescriptor securityDesc = new CommonSecurityDescriptor(false, false, pipeSecurity.GetSecurityDescriptorBinaryForm(), 0);

            // Create optional security attributes based on provided PipeSecurity.
            NamedPipeNative.SECURITY_ATTRIBUTES securityAttributes = null;
            GCHandle?securityDescHandle = null;

            if (securityDesc != null)
            {
                byte[] securityDescBuffer = new byte[securityDesc.BinaryLength];
                securityDesc.GetBinaryForm(securityDescBuffer, 0);

                securityDescHandle = GCHandle.Alloc(securityDescBuffer, GCHandleType.Pinned);
                securityAttributes = NamedPipeNative.GetSecurityAttributes(securityDescHandle.Value);
            }

            // Create named pipe.
            SafePipeHandle pipeHandle = NamedPipeNative.CreateNamedPipe(
                fullPipeName,
                NamedPipeNative.PIPE_ACCESS_DUPLEX | NamedPipeNative.FILE_FLAG_FIRST_PIPE_INSTANCE | NamedPipeNative.FILE_FLAG_OVERLAPPED,
                NamedPipeNative.PIPE_TYPE_BYTE | NamedPipeNative.PIPE_READMODE_BYTE,
                1,
                1024,
                1024,
                0,
                securityAttributes);

            int lastError = Marshal.GetLastWin32Error();

            if (securityDescHandle != null)
            {
                securityDescHandle.Value.Free();
            }

            if (pipeHandle.IsInvalid)
            {
                throw new InvalidOperationException();
            }
            // Create the .Net NamedPipeServerStream wrapper.
            try
            {
                return(new NamedPipeServerStream(
                           PipeDirection.InOut,
                           true,                // IsAsync
                           false,               // IsConnected
                           pipeHandle));
            }
            catch (Exception)
            {
                pipeHandle.Dispose();
                throw;
            }
        }
Example #8
0
        internal static NamedPipeServerStream CreateNamedServerPipe(
            string serverName,
            string namespaceName,
            string pipeName,
            PipeSecurity pipeSecurity)
        {
            string fullPipeName       = $@"\\{serverName}\{namespaceName}\{pipeName}";
            var    securityDescriptor = new CommonSecurityDescriptor(
                false,
                false,
                pipeSecurity.GetSecurityDescriptorBinaryForm(),
                0);

            byte[] securityDescriptorBuffer = new byte[securityDescriptor.BinaryLength];
            securityDescriptor.GetBinaryForm(securityDescriptorBuffer, 0);

            GCHandle?securityDescriptorHandle = GCHandle.Alloc(securityDescriptorBuffer, GCHandleType.Pinned);
            var      securityAttributes       = GetSecurityAttributes(securityDescriptorHandle.Value);

            if (Interop.Kernel32.WaitNamedPipe(fullPipeName, System.Threading.Timeout.Infinite))
            {
                if (Marshal.GetLastWin32Error() != Interop.Errors.ERROR_FILE_NOT_FOUND)
                {
                    throw new InvalidOperationException();
                }
            }

            SafePipeHandle pipeHandle = Interop.Kernel32.CreateNamedPipe(
                fullPipeName,
                Interop.Kernel32.PipeOptions.PIPE_ACCESS_DUPLEX | Interop.Kernel32.FileOperations.FILE_FLAG_OVERLAPPED,
                Interop.Kernel32.PipeOptions.PIPE_TYPE_BYTE | Interop.Kernel32.PipeOptions.PIPE_READMODE_BYTE,
                1,
                65536,
                65536,
                0,
                ref securityAttributes);

            securityDescriptorHandle.Value.Free();

            if (pipeHandle.IsInvalid)
            {
                throw new InvalidOperationException();
            }

            try
            {
                return(new NamedPipeServerStream(PipeDirection.InOut, true, true, pipeHandle));
            }
            catch (Exception)
            {
                pipeHandle.Dispose();
                throw;
            }
        }
        public override byte[] GetAllowAllNodeAcl(string repositoryName, Guid domainId, Guid rootMapId)
        {
            // Return an empty Windows node ACL.
            SecurityIdentifier       farmAccountSid     = SPFarm.Local.DefaultServiceAccount.SecurityIdentifier;
            CommonSecurityDescriptor securityDescriptor = new CommonSecurityDescriptor(false, false, ControlFlags.None, farmAccountSid, null, null, null);

            securityDescriptor.SetDiscretionaryAclProtection(true, false);

            byte[] itemAcl = new byte[securityDescriptor.BinaryLength];
            securityDescriptor.GetBinaryForm(itemAcl, 0);

            return(itemAcl);
        }
        public static void AdditionalTestCases()
        {
            // test case will be passing in binaryForm array that is null, length is invalid and offset is invalid
            CommonSecurityDescriptor commonSecurityDescriptor = null;
            string sddl = null;

            byte[] binaryForm = null;


            //Case 1, null byte array

            Assert.Throws <ArgumentNullException>(() =>
            {
                sddl = "O:LAG:SYD:AI(A;ID;FA;;;BA)(A;ID;FA;;;BG)(A;ID;FA;;;SY)";
                commonSecurityDescriptor = new CommonSecurityDescriptor(true, false, sddl);
                binaryForm = null;
                commonSecurityDescriptor.GetBinaryForm(binaryForm, 0);
            });


            //case 2, empty byte array

            Assert.Throws <ArgumentOutOfRangeException>(() =>
            {
                sddl = "O:LAG:SYD:AI(A;ID;FA;;;BA)(A;ID;FA;;;BG)(A;ID;FA;;;SY)";
                commonSecurityDescriptor = new CommonSecurityDescriptor(true, false, sddl);
                binaryForm = new byte[0];
                commonSecurityDescriptor.GetBinaryForm(binaryForm, 0);
            });

            //case 3, negative offset

            Assert.Throws <ArgumentOutOfRangeException>(() =>
            {
                sddl = "O:LAG:SYD:AI(A;ID;FA;;;BA)(A;ID;FA;;;BG)(A;ID;FA;;;SY)";
                commonSecurityDescriptor = new CommonSecurityDescriptor(true, false, sddl);
                binaryForm = new byte[100];
                commonSecurityDescriptor.GetBinaryForm(binaryForm, -1);
            });
            //case 4, binaryForm.Length - offset < BinaryLength

            Assert.Throws <ArgumentOutOfRangeException>(() =>
            {
                sddl = "O:LAG:SYD:AI(A;ID;FA;;;BA)(A;ID;FA;;;BG)(A;ID;FA;;;SY)";
                commonSecurityDescriptor = new CommonSecurityDescriptor(true, false, sddl);
                binaryForm = new byte[commonSecurityDescriptor.BinaryLength];
                commonSecurityDescriptor.GetBinaryForm(binaryForm, 8);
            });
        }
Example #11
0
        private void CheckAccess(WindowsIdentity clientIdentity, out bool IsAccessAllowed)
        {
            if (null == securityDescriptor)
            {
                throw Fx.AssertAndThrowFatal("Security Descriptor must not be NULL");
            }

            IsAccessAllowed = false;
            byte[] BinaryForm = new byte[securityDescriptor.BinaryLength];
            securityDescriptor.GetBinaryForm(BinaryForm, 0);
            SafeCloseHandle ImpersonationToken  = null;
            SafeCloseHandle clientIdentityToken = new SafeCloseHandle(clientIdentity.Token, false);

            try
            {
                if (SecurityUtils.IsPrimaryToken(clientIdentityToken))
                {
                    if (!SafeNativeMethods.DuplicateTokenEx(clientIdentityToken,
                                                            TokenAccessLevels.Query,
                                                            IntPtr.Zero,
                                                            SecurityImpersonationLevel.Identification,
                                                            TokenType.TokenImpersonation,
                                                            out ImpersonationToken))
                    {
                        int error = Marshal.GetLastWin32Error();
                        Utility.CloseInvalidOutSafeHandle(ImpersonationToken);
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error, SR.GetString(SR.DuplicateTokenExFailed, error)));
                    }
                }
                GENERIC_MAPPING GenericMapping     = new GENERIC_MAPPING();
                PRIVILEGE_SET   PrivilegeSet       = new PRIVILEGE_SET();
                uint            PrivilegeSetLength = (uint)Marshal.SizeOf(PrivilegeSet);
                uint            GrantedAccess      = 0;
                if (!SafeNativeMethods.AccessCheck(BinaryForm, (ImpersonationToken != null) ? ImpersonationToken : clientIdentityToken,
                                                   (int)ComRights.EXECUTE, GenericMapping, out PrivilegeSet,
                                                   ref PrivilegeSetLength, out GrantedAccess, out IsAccessAllowed))
                {
                    int error = Marshal.GetLastWin32Error();
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error, SR.GetString(SR.AccessCheckFailed, error)));
                }
            }
            finally
            {
                if (ImpersonationToken != null)
                {
                    ImpersonationToken.Dispose();
                }
            }
        }
Example #12
0
        public static void SetAclOnAlternateProperty(ADObject obj, GenericAce[] aces, PropertyDefinition sdProperty, SecurityIdentifier owner, SecurityIdentifier group)
        {
            DiscretionaryAcl discretionaryAcl = new DiscretionaryAcl(false, true, aces.Length);

            foreach (GenericAce genericAce in aces)
            {
                AccessControlType accessType;
                if (genericAce.AceType == AceType.AccessAllowed || genericAce.AceType == AceType.AccessAllowedObject)
                {
                    accessType = AccessControlType.Allow;
                }
                else
                {
                    if (genericAce.AceType != AceType.AccessDenied && genericAce.AceType != AceType.AccessDeniedObject)
                    {
                        throw new AceTypeHasUnsupportedValueException(genericAce.AceType.ToString());
                    }
                    accessType = AccessControlType.Deny;
                }
                if (genericAce is CommonAce)
                {
                    CommonAce commonAce = genericAce as CommonAce;
                    discretionaryAcl.AddAccess(accessType, commonAce.SecurityIdentifier, commonAce.AccessMask, commonAce.InheritanceFlags, commonAce.PropagationFlags);
                }
                else
                {
                    if (!(genericAce is ObjectAce))
                    {
                        throw new AceIsUnsupportedTypeException(genericAce.GetType().ToString());
                    }
                    ObjectAce objectAce = genericAce as ObjectAce;
                    discretionaryAcl.AddAccess(accessType, objectAce.SecurityIdentifier, objectAce.AccessMask, objectAce.InheritanceFlags, objectAce.PropagationFlags, objectAce.ObjectAceFlags, objectAce.ObjectAceType, objectAce.InheritedObjectAceType);
                }
            }
            CommonSecurityDescriptor commonSecurityDescriptor = new CommonSecurityDescriptor(false, true, ControlFlags.DiscretionaryAclPresent, owner, group, null, discretionaryAcl);

            byte[] binaryForm = new byte[commonSecurityDescriptor.BinaryLength];
            commonSecurityDescriptor.GetBinaryForm(binaryForm, 0);
            RawSecurityDescriptor rawSecurityDescriptor = new RawSecurityDescriptor(binaryForm, 0);

            obj.SetProperties(new PropertyDefinition[]
            {
                sdProperty
            }, new object[]
            {
                rawSecurityDescriptor
            });
        }
        public static void AdditionalTestCases()
        {
            // test case will be passing in binaryForm array that is null, length is invalid and offset is invalid
            CommonSecurityDescriptor commonSecurityDescriptor = null;
            string sddl = null;
            byte[] binaryForm = null;


            //Case 1, null byte array

            Assert.Throws<ArgumentNullException>(() =>
            {
                sddl = "O:LAG:SYD:AI(A;ID;FA;;;BA)(A;ID;FA;;;BG)(A;ID;FA;;;SY)";
                commonSecurityDescriptor = new CommonSecurityDescriptor(true, false, sddl);
                binaryForm = null;
                commonSecurityDescriptor.GetBinaryForm(binaryForm, 0);
            });


            //case 2, empty byte array

            Assert.Throws<ArgumentOutOfRangeException>(() =>
            {
                sddl = "O:LAG:SYD:AI(A;ID;FA;;;BA)(A;ID;FA;;;BG)(A;ID;FA;;;SY)";
                commonSecurityDescriptor = new CommonSecurityDescriptor(true, false, sddl);
                binaryForm = new byte[0];
                commonSecurityDescriptor.GetBinaryForm(binaryForm, 0);
            });

            //case 3, negative offset                 

            Assert.Throws<ArgumentOutOfRangeException>(() =>
            {
                sddl = "O:LAG:SYD:AI(A;ID;FA;;;BA)(A;ID;FA;;;BG)(A;ID;FA;;;SY)";
                commonSecurityDescriptor = new CommonSecurityDescriptor(true, false, sddl);
                binaryForm = new byte[100];
                commonSecurityDescriptor.GetBinaryForm(binaryForm, -1);
            });
            //case 4, binaryForm.Length - offset < BinaryLength

            Assert.Throws<ArgumentOutOfRangeException>(() =>
            {
                sddl = "O:LAG:SYD:AI(A;ID;FA;;;BA)(A;ID;FA;;;BG)(A;ID;FA;;;SY)";
                commonSecurityDescriptor = new CommonSecurityDescriptor(true, false, sddl);
                binaryForm = new byte[commonSecurityDescriptor.BinaryLength];
                commonSecurityDescriptor.GetBinaryForm(binaryForm, 8);
            });
        }
Example #14
0
        internal static IpcPort Create(String portName, CommonSecurityDescriptor securityDescriptor, bool exclusive)
        {
            if (Environment.OSVersion.Platform != PlatformID.Win32NT)
            {
                throw new NotSupportedException(CoreChannel.GetResourceString("Remoting_Ipc_Win9x"));
            }
            PipeHandle handle = null;
            // Add the prefix to the portName
            string pipeName          = prefix + portName;
            SECURITY_ATTRIBUTES attr = new SECURITY_ATTRIBUTES();

            attr.nLength = (int)Marshal.SizeOf(attr);
            byte[] sd = null;
            // If no securityDescriptor was set by the user use the default
            if (securityDescriptor == null)
            {
                securityDescriptor = s_securityDescriptor;
            }

            sd = new byte[securityDescriptor.BinaryLength];
            // Get the binary form of the descriptor
            securityDescriptor.GetBinaryForm(sd, 0);

            GCHandle pinningHandle = GCHandle.Alloc(sd, GCHandleType.Pinned);

            // get the address of the security descriptor
            attr.lpSecurityDescriptor = Marshal.UnsafeAddrOfPinnedArrayElement(sd, 0);

            // Create the named pipe with the appropriate name
            handle = NativePipe.CreateNamedPipe(pipeName,
                                                NativePipe.PIPE_ACCESS_DUPLEX | NativePipe.FILE_FLAG_OVERLAPPED
                                                | (exclusive ? NativePipe.FILE_FLAG_FIRST_PIPE_INSTANCE : 0x0), // Or exclusive flag
                                                NativePipe.PIPE_TYPE_BYTE | NativePipe.PIPE_READMODE_BYTE | NativePipe.PIPE_WAIT,
                                                NativePipe.PIPE_UNLIMITED_INSTANCES,
                                                8192,
                                                8192,
                                                NativePipe.NMPWAIT_WAIT_FOREVER,
                                                attr);

            pinningHandle.Free();
            if (handle.Handle.ToInt32() == NativePipe.INVALID_HANDLE_VALUE)
            {
                int error = Marshal.GetLastWin32Error();
                throw new RemotingException(String.Format(CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_Ipc_CreateIpcFailed"), GetMessage(error)));
            }

            return(new IpcPort(portName, handle));
        }
Example #15
0
        public void AefaRoundtrip()
        {
            CommonSecurityDescriptor csd;

            csd = new CommonSecurityDescriptor(false, false, ControlFlags.None, null, null, null, null);
            Assert.AreEqual(20, csd.BinaryLength);

            byte[] binaryForm1 = new byte[csd.BinaryLength];
            csd.GetBinaryForm(binaryForm1, 0);

            csd = new CommonSecurityDescriptor(false, false, new RawSecurityDescriptor(binaryForm1, 0));

            byte[] binaryForm2 = new byte[csd.BinaryLength];
            csd.GetBinaryForm(binaryForm2, 0);

            Assert.AreEqual(binaryForm1, binaryForm2);
        }
Example #16
0
        // Do not use this method unless you understand the consequnces of lack of synchronization
        static void EditKernelObjectSecurity(SafeCloseHandle kernelObject, List <SecurityIdentifier> accounts, SecurityIdentifier account, int right, bool add)
        {
            // take the SECURITY_DESCRIPTOR from the kernelObject
            int  lpnLengthNeeded;
            bool success = ListenerUnsafeNativeMethods.GetKernelObjectSecurity(kernelObject, ListenerUnsafeNativeMethods.DACL_SECURITY_INFORMATION, null, 0, out lpnLengthNeeded);

            if (!success)
            {
                int errorCode = Marshal.GetLastWin32Error();
                if (errorCode != ListenerUnsafeNativeMethods.ERROR_INSUFFICIENT_BUFFER)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(errorCode));
                }
            }
            byte[] pSecurityDescriptor = new byte[lpnLengthNeeded];
#pragma warning suppress 56523 // Microsoft, Win32Exception ctor calls Marshal.GetLastWin32Error()
            success = ListenerUnsafeNativeMethods.GetKernelObjectSecurity(kernelObject, ListenerUnsafeNativeMethods.DACL_SECURITY_INFORMATION, pSecurityDescriptor, pSecurityDescriptor.Length, out lpnLengthNeeded);
            if (!success)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception());
            }
            CommonSecurityDescriptor securityDescriptor = new CommonSecurityDescriptor(false, false, pSecurityDescriptor, 0);
            DiscretionaryAcl         dacl = securityDescriptor.DiscretionaryAcl;
            // add ACEs to the SECURITY_DESCRIPTOR of the kernelObject
            if (account != null)
            {
                EditDacl(dacl, account, right, add);
            }
            else if (accounts != null)
            {
                foreach (SecurityIdentifier accountInList in accounts)
                {
                    EditDacl(dacl, accountInList, right, add);
                }
            }
            lpnLengthNeeded     = securityDescriptor.BinaryLength;
            pSecurityDescriptor = new byte[lpnLengthNeeded];
            securityDescriptor.GetBinaryForm(pSecurityDescriptor, 0);
            // set the SECURITY_DESCRIPTOR on the kernelObject
#pragma warning suppress 56523 // Microsoft, Win32Exception ctor calls Marshal.GetLastWin32Error()
            success = ListenerUnsafeNativeMethods.SetKernelObjectSecurity(kernelObject, ListenerUnsafeNativeMethods.DACL_SECURITY_INFORMATION, pSecurityDescriptor);
            if (!success)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception());
            }
        }
        public void SamrSetSecurityObject_Owner_SECURITY_INFORMATION_Domain()
        {
            HRESULT hResult;

            ConnectAndOpenDomain(_samrProtocolAdapter.PDCNetbiosName, _samrProtocolAdapter.PrimaryDomainDnsName,
                                 out _serverHandle, out _domainHandle, (uint)(Common_ACCESS_MASK.WRITE_OWNER | Common_ACCESS_MASK.READ_CONTROL));

            CommonSecurityDescriptor commonsd = new CommonSecurityDescriptor(false, true, "O:BGG:BA");

            byte[] buffer = new byte[commonsd.BinaryLength];
            commonsd.GetBinaryForm(buffer, 0);
            _SAMPR_SR_SECURITY_DESCRIPTOR securityDescriptor = new _SAMPR_SR_SECURITY_DESCRIPTOR()
            {
                SecurityDescriptor = buffer,
                Length             = (uint)buffer.Length
            };

            Site.Log.Add(LogEntryKind.TestStep,
                         "SamrSetSecurityObject, SecurityInformation: OWNER_SECURITY_INFORMATION as Built-in Guests.");
            hResult = _samrProtocolAdapter.SamrSetSecurityObject(_domainHandle, SecurityInformation.OWNER_SECURITY_INFORMATION, securityDescriptor);
            Site.Assert.AreEqual(HRESULT.STATUS_SUCCESS, hResult, "If the database object referenced by ObjectHandle.Object is not a user object and the DACL_SECURITY_INFORMATION is not set in SecurityInformation, the server MUST silently ignore the request by aborting processing and returning 0.");

            Site.Log.Add(LogEntryKind.TestStep, "SamrQuerySecurityObject to check again, SecurityInformation: OWNER_SECURITY_INFORMATION.");
            _SAMPR_SR_SECURITY_DESCRIPTOR?sd;

            hResult = _samrProtocolAdapter.SamrQuerySecurityObject(_domainHandle, SecurityInformation.OWNER_SECURITY_INFORMATION, out sd);

            Site.Assert.AreEqual(HRESULT.STATUS_SUCCESS, hResult, "SamrQuerySecurityObject must return STATUS_SUCCESS.");
            Site.Assert.IsNotNull(securityDescriptor, "The SecurityDescriptor returned by SamrQuerySecurityObject is not null.");

            // Initializing SecurityDescriptor object using the obtained bytes of security descriptor.
            CommonSecurityDescriptor ObtainedSecurityDescriptor =
                new CommonSecurityDescriptor(false, true, sd.Value.SecurityDescriptor, 0);

            Site.Assert.AreEqual("O:BA", ObtainedSecurityDescriptor.GetSddlForm(AccessControlSections.Owner), "Owner should still be the Administrator.");

            _SECURITY_DESCRIPTOR secdes = DtypUtility.DecodeSecurityDescriptor(sd.Value.SecurityDescriptor);

            Site.Assert.IsNotNull(secdes.OwnerSid, "3.1.5.12.2 If this bit(OWNER_SECURITY_INFORMATION) is set, the client requests that the Owner member be returned.");
            Site.Assert.IsNull(secdes.GroupSid, "3.1.5.12.2 If this bit(GROUP_SECURITY_INFORMATION) is not set, the client requests that the Group member not be returned.");
            Site.Assert.IsNull(secdes.Dacl, "3.1.5.12.2 If this bit(DACL_SECURITY_INFORMATION) is not set, the client requests that the DACL not be returned.");
            Site.Assert.IsNull(secdes.Sacl, "3.1.5.12.2 If this bit(SACL_SECURITY_INFORMATION) is not set, the client requests that the SACL not be returned.");
            Site.Assert.AreEqual(AdministratorSid, DtypUtility.ToSddlString((_SID)secdes.OwnerSid), "3.1.5.12.2 The Owner and Group fields of the security descriptor MUST be the administrator's SID (S-1-5-32-544).");
        }
Example #18
0
        public void SamrSetSecurityObject_Server_Owner_NonDC()
        {
            HRESULT  hResult;
            IChecker PtfAssert = TestClassBase.BaseTestSite.Assert;

            Site.Log.Add(LogEntryKind.TestStep,
                         string.Format("SamrBind, Server:{0}, Domain:{1}, User:{2}, Password{3}.",
                                       _samrProtocolAdapter.domainMemberFqdn,
                                       _samrProtocolAdapter.domainMemberNetBIOSName,
                                       _samrProtocolAdapter.DMAdminName,
                                       _samrProtocolAdapter.DMAdminPassword));
            _samrProtocolAdapter.SamrBind(
                _samrProtocolAdapter.domainMemberFqdn,
                _samrProtocolAdapter.domainMemberNetBIOSName,
                _samrProtocolAdapter.DMAdminName,
                _samrProtocolAdapter.DMAdminPassword,
                false,
                false);
            Site.Log.Add(LogEntryKind.TestStep,
                         string.Format("SamrConnect5, Server:{0}, Desired Access: WRITE_OWNER.", _samrProtocolAdapter.domainMemberFqdn));
            hResult = (HRESULT)_samrProtocolAdapter.SamrConnect5(
                _samrProtocolAdapter.domainMemberFqdn,
                (uint)Common_ACCESS_MASK.WRITE_OWNER,
                out _serverHandle);
            PtfAssert.AreEqual(HRESULT.STATUS_SUCCESS, hResult, "SamrConnect5 must return STATUS_SUCCESS.");
            CommonSecurityDescriptor commonsd = new CommonSecurityDescriptor(false, true, "O:BAG:BA");

            byte[] buffer = new byte[commonsd.BinaryLength];
            commonsd.GetBinaryForm(buffer, 0);
            _SAMPR_SR_SECURITY_DESCRIPTOR sd = new _SAMPR_SR_SECURITY_DESCRIPTOR()
            {
                SecurityDescriptor = buffer,
                Length             = (uint)buffer.Length
            };

            Site.Log.Add(LogEntryKind.TestStep,
                         "SamrSetSecurityObject, SecurityInformation: OWNER_SECURITY_INFORMATION.");
            hResult = (HRESULT)SAMRProtocolAdapter.RpcAdapter.SamrSetSecurityObject(
                _serverHandle,
                SecurityInformation_Values.OWNER_SECURITY_INFORMATION,
                sd
                );
            PtfAssert.AreEqual(HRESULT.STATUS_SUCCESS, hResult, "SamrSetSecurityObject must return STATUS_SUCCESS.");
        }
        protected byte[] GetNodeAclWorker(string mapDatabaseName, string repositoryName, Guid domainId, Guid rootMapId, bool isCacheEnabled)
        {
            SecurityIdentifier       farmAccountSid     = SPFarm.Local.DefaultServiceAccount.SecurityIdentifier;
            CommonSecurityDescriptor securityDescriptor = new CommonSecurityDescriptor(false, false, ControlFlags.None, farmAccountSid, null, null, null);

            securityDescriptor.SetDiscretionaryAclProtection(true, false);

            // Deny access to all users.
            SecurityIdentifier everyoneSid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);

            securityDescriptor.DiscretionaryAcl.RemoveAccess(AccessControlType.Allow, everyoneSid, unchecked ((int)0xffffffffL), InheritanceFlags.None, PropagationFlags.None);

            // Grant access to specified users.
            securityDescriptor.DiscretionaryAcl.AddAccess(AccessControlType.Allow, farmAccountSid, unchecked ((int)0xffffffffL), InheritanceFlags.None, PropagationFlags.None);

            List <SpUserDetail> allowedUsers = GetAllowedUsers(mapDatabaseName, repositoryName, domainId, rootMapId);
            List <string>       addedSids    = new List <string>();

            foreach (SpUserDetail user in allowedUsers)
            {
                SecurityIdentifier userSid = null;
                if (!string.IsNullOrEmpty(user.Sid))
                {
                    userSid = new SecurityIdentifier(user.Sid);
                }
                else
                {
                    userSid = GetSidFromClaim(user.LoginName);
                }

                if (userSid != null && !addedSids.Contains(userSid.Value))
                {
                    securityDescriptor.DiscretionaryAcl.AddAccess(AccessControlType.Allow, userSid, unchecked ((int)0xffffffffL), InheritanceFlags.None, PropagationFlags.None);
                    addedSids.Add(userSid.Value);
                }
            }

            byte[] itemAcl = new byte[securityDescriptor.BinaryLength];
            securityDescriptor.GetBinaryForm(itemAcl, 0);

            return(itemAcl);
        }
Example #20
0
        private static byte[] GetRoleSecurityDescriptorData(SecurityIdentifier roleSid, int accessMask)
        {
            // Create a new ACL with one ACE.
            DiscretionaryAcl discretionaryAcl = new DiscretionaryAcl(false, false, 1);

            discretionaryAcl.AddAccess(AccessControlType.Allow, roleSid, accessMask,
                                       InheritanceFlags.None, PropagationFlags.None);

            // Create a new security descriptor.
            SecurityIdentifier        owner = new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null);
            SecurityIdentifier        group = new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null);
            GenericSecurityDescriptor securityDescriptor = new CommonSecurityDescriptor(
                false, false, ControlFlags.DiscretionaryAclPresent,
                owner, group, null, discretionaryAcl);

            // Marshal the security descriptor.
            byte[] securityDescriptorData = new byte[securityDescriptor.BinaryLength];
            securityDescriptor.GetBinaryForm(securityDescriptorData, 0);
            return(securityDescriptorData);
        }
        public static void TestGetBinaryForm(bool isContainer, bool isDS, string sddl, string verifierSddl, int offset)
        {
            CommonSecurityDescriptor commonSecurityDescriptor         = null;
            CommonSecurityDescriptor verifierCommonSecurityDescriptor = null;
            string resultSddl = null;

            commonSecurityDescriptor = new CommonSecurityDescriptor(isContainer, isDS, sddl);
            byte[] binaryForm = new byte[commonSecurityDescriptor.BinaryLength + offset];
            commonSecurityDescriptor.GetBinaryForm(binaryForm, offset);
            verifierCommonSecurityDescriptor = new CommonSecurityDescriptor(isContainer, isDS, binaryForm, offset);
            resultSddl = verifierCommonSecurityDescriptor.GetSddlForm(AccessControlSections.All);

            if (resultSddl == null || verifierSddl == null)
            {
                Assert.True(resultSddl == null && verifierSddl == null);
            }
            else
            {
                Assert.True(string.Compare(resultSddl, verifierSddl, StringComparison.CurrentCultureIgnoreCase) == 0);
            }
        }
Example #22
0
        private static NativeMethods.SECURITY_ATTRIBUTES CreateSecurityAttributes(WellKnownSidType sidType)
        {
            // Grant access to Network Service.
            SecurityIdentifier networkService = new SecurityIdentifier(sidType, null);
            DiscretionaryAcl   dacl           = new DiscretionaryAcl(false, false, 1);

            dacl.AddAccess(AccessControlType.Allow, networkService, -1, InheritanceFlags.None, PropagationFlags.None);
            CommonSecurityDescriptor csd = new CommonSecurityDescriptor(false, false, ControlFlags.DiscretionaryAclPresent | ControlFlags.OwnerDefaulted | ControlFlags.GroupDefaulted, null, null, null, dacl);

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

            IntPtr dest = Marshal.AllocHGlobal(buffer.Length);

            Marshal.Copy(buffer, 0, dest, buffer.Length);

            NativeMethods.SECURITY_ATTRIBUTES sa = new NativeMethods.SECURITY_ATTRIBUTES();
            sa.nLength = Marshal.SizeOf(sa);
            sa.lpSecurityDescriptor = dest;

            return(sa);
        }
Example #23
0
 public static void TakeOwnership(ADObjectId id, RawSecurityDescriptor sd, IConfigurationSession session)
 {
     if (id == null)
     {
         throw new ArgumentNullException("id");
     }
     if (session == null)
     {
         throw new ArgumentNullException("session");
     }
     if (sd == null)
     {
         using (WindowsIdentity current = WindowsIdentity.GetCurrent())
         {
             CommonSecurityDescriptor commonSecurityDescriptor = new CommonSecurityDescriptor(false, true, ControlFlags.DiscretionaryAclPresent, current.User, current.User, null, null);
             byte[] binaryForm = new byte[commonSecurityDescriptor.BinaryLength];
             commonSecurityDescriptor.GetBinaryForm(binaryForm, 0);
             sd = new RawSecurityDescriptor(binaryForm, 0);
         }
     }
     session.SaveSecurityDescriptor(id, sd, true);
 }
        public void SamrSetSecurityObject_INVALID_SECURITY_INFORMATION_Domain()
        {
            HRESULT hResult;

            ConnectAndOpenDomain(_samrProtocolAdapter.PDCNetbiosName, _samrProtocolAdapter.PrimaryDomainDnsName,
                                 out _serverHandle, out _domainHandle, (uint)Common_ACCESS_MASK.WRITE_OWNER);

            CommonSecurityDescriptor commonsd = new CommonSecurityDescriptor(false, true, "O:BAG:BA");

            byte[] buffer = new byte[commonsd.BinaryLength];
            commonsd.GetBinaryForm(buffer, 0);
            _SAMPR_SR_SECURITY_DESCRIPTOR securityDescriptor = new _SAMPR_SR_SECURITY_DESCRIPTOR()
            {
                SecurityDescriptor = buffer,
                Length             = (uint)buffer.Length
            };

            Site.Log.Add(LogEntryKind.TestStep,
                         "SamrSetSecurityObject, SecurityInformation: INVALID_SECURITY_INFORMATION.");
            hResult = _samrProtocolAdapter.SamrSetSecurityObject(_domainHandle, SecurityInformation.INVALID_SECURITY_INFORMATION, securityDescriptor);
            Site.Assert.AreEqual(Utilities.STATUS_INVALID_PARAMETER, (uint)hResult, "If none of the bits below are present, the server MUST return STATUS_INVALID_PARAMETER.");
        }
        public void SamrSetSecurityObject_DACL_SECURITY_INFORMATION_STATUS_ACCESS_DENIED_Domain()
        {
            HRESULT hResult;

            ConnectAndOpenDomain(_samrProtocolAdapter.PDCNetbiosName, _samrProtocolAdapter.PrimaryDomainDnsName,
                                 out _serverHandle, out _domainHandle, (uint)Common_ACCESS_MASK.WRITE_OWNER);

            CommonSecurityDescriptor commonsd = new CommonSecurityDescriptor(false, true, "O:BAG:BA");

            byte[] buffer = new byte[commonsd.BinaryLength];
            commonsd.GetBinaryForm(buffer, 0);
            _SAMPR_SR_SECURITY_DESCRIPTOR securityDescriptor = new _SAMPR_SR_SECURITY_DESCRIPTOR()
            {
                SecurityDescriptor = buffer,
                Length             = (uint)buffer.Length
            };

            Site.Log.Add(LogEntryKind.TestStep,
                         "SamrSetSecurityObject, SecurityInformation: DACL_SECURITY_INFORMATION with no WRITE_DAC access.");
            hResult = _samrProtocolAdapter.SamrSetSecurityObject(_domainHandle, SecurityInformation.DACL_SECURITY_INFORMATION, securityDescriptor);
            Site.Assert.AreEqual(HRESULT.STATUS_ACCESS_DENIED, hResult, "On error, the server MUST abort processing and return STATUS_ACCESS_DENIED.");
        }
        private static void EditKernelObjectSecurity(SafeCloseHandle kernelObject, List <SecurityIdentifier> accounts, SecurityIdentifier account, int right, bool add)
        {
            int num;

            if (!ListenerUnsafeNativeMethods.GetKernelObjectSecurity(kernelObject, 4, null, 0, out num))
            {
                int error = Marshal.GetLastWin32Error();
                if (error != 0x7a)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(error));
                }
            }
            byte[] pSecurityDescriptor = new byte[num];
            if (!ListenerUnsafeNativeMethods.GetKernelObjectSecurity(kernelObject, 4, pSecurityDescriptor, pSecurityDescriptor.Length, out num))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception());
            }
            CommonSecurityDescriptor descriptor       = new CommonSecurityDescriptor(false, false, pSecurityDescriptor, 0);
            DiscretionaryAcl         discretionaryAcl = descriptor.DiscretionaryAcl;

            if (account != null)
            {
                EditDacl(discretionaryAcl, account, right, add);
            }
            else if (accounts != null)
            {
                foreach (SecurityIdentifier identifier in accounts)
                {
                    EditDacl(discretionaryAcl, identifier, right, add);
                }
            }
            pSecurityDescriptor = new byte[descriptor.BinaryLength];
            descriptor.GetBinaryForm(pSecurityDescriptor, 0);
            if (!ListenerUnsafeNativeMethods.SetKernelObjectSecurity(kernelObject, 4, pSecurityDescriptor))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception());
            }
        }
Example #27
0
        protected void LockdownServiceAccess()
        {
            TaskLogger.Trace("Modifying service ACL to remove Network Logon ACE.", new object[0]);
            ServiceAccessFlags serviceAccessFlags = ServiceAccessFlags.ReadControl | ServiceAccessFlags.WriteDac;

            base.DoNativeServiceTask(this.Name, serviceAccessFlags, delegate(IntPtr service)
            {
                string name    = this.Name;
                IntPtr intPtr  = IntPtr.Zero;
                IntPtr intPtr2 = IntPtr.Zero;
                try
                {
                    int num = 65536;
                    intPtr  = Marshal.AllocHGlobal(num);
                    int num2;
                    if (!NativeMethods.QueryServiceObjectSecurity(service, SecurityInfos.DiscretionaryAcl, intPtr, num, out num2))
                    {
                        base.WriteError(TaskWin32Exception.FromErrorCodeAndVerbose(Marshal.GetLastWin32Error(), Strings.ErrorQueryServiceObjectSecurity(name)), ErrorCategory.InvalidOperation, null);
                    }
                    byte[] array = new byte[num2];
                    Marshal.Copy(intPtr, array, 0, num2);
                    RawSecurityDescriptor rawSecurityDescriptor       = new RawSecurityDescriptor(array, 0);
                    CommonSecurityDescriptor commonSecurityDescriptor = new CommonSecurityDescriptor(false, false, rawSecurityDescriptor);
                    CommonAce commonAce      = null;
                    SecurityIdentifier right = new SecurityIdentifier("S-1-5-11");
                    for (int i = 0; i < commonSecurityDescriptor.DiscretionaryAcl.Count; i++)
                    {
                        CommonAce commonAce2 = (CommonAce)commonSecurityDescriptor.DiscretionaryAcl[i];
                        if (commonAce2.SecurityIdentifier == right)
                        {
                            commonAce = commonAce2;
                            break;
                        }
                    }
                    if (commonAce == null)
                    {
                        TaskLogger.Trace("Service ACL was not modified as Network Logon SID is not found.", new object[0]);
                    }
                    else
                    {
                        commonSecurityDescriptor.DiscretionaryAcl.RemoveAccess(AccessControlType.Allow, commonAce.SecurityIdentifier, commonAce.AccessMask, commonAce.InheritanceFlags, commonAce.PropagationFlags);
                        int binaryLength = commonSecurityDescriptor.BinaryLength;
                        byte[] array2    = new byte[binaryLength];
                        commonSecurityDescriptor.GetBinaryForm(array2, 0);
                        intPtr2 = Marshal.AllocHGlobal(binaryLength);
                        Marshal.Copy(array2, 0, intPtr2, binaryLength);
                        if (!NativeMethods.SetServiceObjectSecurity(service, SecurityInfos.DiscretionaryAcl, intPtr2))
                        {
                            base.WriteError(TaskWin32Exception.FromErrorCodeAndVerbose(Marshal.GetLastWin32Error(), Strings.ErrorSetServiceObjectSecurity(name)), ErrorCategory.InvalidOperation, null);
                        }
                        TaskLogger.Trace("Service ACL modified - Network Logon ACE removed.", new object[0]);
                    }
                }
                finally
                {
                    if (IntPtr.Zero != intPtr)
                    {
                        Marshal.FreeHGlobal(intPtr);
                    }
                    if (IntPtr.Zero != intPtr2)
                    {
                        Marshal.FreeHGlobal(intPtr2);
                    }
                }
            });
        }
Example #28
0
        /// <summary>
        /// Helper method to create a PowerShell transport named pipe via native API, along
        /// with a returned .Net NamedPipeServerStream object wrapping the named pipe.
        /// </summary>
        /// <param name="serverName">Named pipe server name.</param>
        /// <param name="namespaceName">Named pipe namespace name.</param>
        /// <param name="coreName">Named pipe core name.</param>
        /// <param name="securityDesc"></param>
        /// <returns>NamedPipeServerStream</returns>
        private NamedPipeServerStream CreateNamedPipe(
            string serverName,
            string namespaceName,
            string coreName,
            CommonSecurityDescriptor securityDesc)
        {
            if (serverName == null)
            {
                throw new PSArgumentNullException("serverName");
            }
            if (namespaceName == null)
            {
                throw new PSArgumentNullException("namespaceName");
            }
            if (coreName == null)
            {
                throw new PSArgumentNullException("coreName");
            }

            string fullPipeName = @"\\" + serverName + @"\" + namespaceName + @"\" + coreName;

            // Create optional security attributes based on provided PipeSecurity.
            NamedPipeNative.SECURITY_ATTRIBUTES securityAttributes = null;
            GCHandle?securityDescHandle = null;

            if (securityDesc != null)
            {
                byte[] securityDescBuffer = new byte[securityDesc.BinaryLength];
                securityDesc.GetBinaryForm(securityDescBuffer, 0);
                securityDescHandle = GCHandle.Alloc(securityDescBuffer, GCHandleType.Pinned);
                securityAttributes = NamedPipeNative.GetSecurityAttributes(securityDescHandle.Value);
            }

            // Create named pipe.
            SafePipeHandle pipeHandle = NamedPipeNative.CreateNamedPipe(
                fullPipeName,
                NamedPipeNative.PIPE_ACCESS_DUPLEX | NamedPipeNative.FILE_FLAG_FIRST_PIPE_INSTANCE | NamedPipeNative.FILE_FLAG_OVERLAPPED,
                NamedPipeNative.PIPE_TYPE_MESSAGE | NamedPipeNative.PIPE_READMODE_MESSAGE,
                1,
                _namedPipeBufferSizeForRemoting,
                _namedPipeBufferSizeForRemoting,
                0,
                securityAttributes);

            int lastError = Marshal.GetLastWin32Error();

            if (securityDescHandle != null)
            {
                securityDescHandle.Value.Free();
            }

            if (pipeHandle.IsInvalid)
            {
                throw new PSInvalidOperationException(
                          StringUtil.Format(RemotingErrorIdStrings.CannotCreateNamedPipe, lastError));
            }

            // Create the .Net NamedPipeServerStream wrapper.
            try
            {
                return(new NamedPipeServerStream(
                           PipeDirection.InOut,
                           true,                // IsAsync
                           false,               // IsConnected
                           pipeHandle));
            }
            catch (Exception e)
            {
                CommandProcessorBase.CheckForSevereException(e);
                pipeHandle.Dispose();
                throw;
            }
        }
        internal override void AdjustRegKeyPermission()
        {
            const uint maxSecurityDescriptorSize = 40960;

            byte[] binarySecurityDescriptor;
            CommonSecurityDescriptor securityDescriptor = null;
            int  ret;
            uint dwSize = 256;

            do
            {
                binarySecurityDescriptor = new byte[dwSize];
                ret = SafeNativeMethods.ClusterRegGetKeySecurity(hKey, SecurityInfos.DiscretionaryAcl, binarySecurityDescriptor, ref dwSize);
                if (ret == SafeNativeMethods.ERROR_SUCCESS)
                {
                    break;
                }
                else if (ret == SafeNativeMethods.ERROR_INSUFFICIENT_BUFFER)
                {
                    dwSize *= 2;
                }
                else
                {
                    throw registryExceptionHelper.CreateRegistryWriteException(null);
                }
            } while (dwSize <= maxSecurityDescriptorSize);

            if (dwSize > maxSecurityDescriptorSize)
            {
                throw registryExceptionHelper.CreateRegistryWriteException(null);
            }

            try
            {
                securityDescriptor = new CommonSecurityDescriptor(false, false, binarySecurityDescriptor, 0);
                DiscretionaryAcl dacl = securityDescriptor.DiscretionaryAcl;
                if (dacl.Count == 1)
                {
                    CommonAce ace = dacl[0] as CommonAce;
                    if (ace != null && ace.AceType == AceType.AccessAllowed && ace.SecurityIdentifier.IsWellKnown(WellKnownSidType.WorldSid))
                    {
                        // This is the Allowed for everyone full access ACE that's automatically added by
                        // CommonSecurityDescriptor ctor; we should remove it
                        dacl.Purge(new SecurityIdentifier(WellKnownSidType.WorldSid, null));
                    }
                }

                // Add Read access for Authenticated Users account and Network Service account
                dacl.AddAccess(AccessControlType.Allow, new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null),
                               unchecked ((int)0x80000000), InheritanceFlags.None, PropagationFlags.None);
                dacl.AddAccess(AccessControlType.Allow, new SecurityIdentifier(WellKnownSidType.NetworkServiceSid, null),
                               unchecked ((int)0x80000000), InheritanceFlags.None, PropagationFlags.None);
            }
            #pragma warning suppress 56500
            catch (Exception e)
            {
                // MSDN does not have a spec of possible exceptions for the APIs used above.
                // To be safe, we should be a bit more generic in catching exceptions
                if (Utilities.IsCriticalException(e))
                {
                    throw;
                }
                throw registryExceptionHelper.CreateRegistryWriteException(e);
            }

            int    dsNewSecDescSize            = securityDescriptor.BinaryLength;
            byte[] newBinarySecurityDescriptor = new byte[dsNewSecDescSize];
            securityDescriptor.GetBinaryForm(newBinarySecurityDescriptor, 0);

            ret = SafeNativeMethods.ClusterRegSetKeySecurity(hKey, SecurityInfos.DiscretionaryAcl, newBinarySecurityDescriptor);
            if (ret != SafeNativeMethods.ERROR_SUCCESS)
            {
                throw registryExceptionHelper.CreateRegistryWriteException(null);
            }
        }
        /// <summary>
        /// Helper method to create a PowerShell transport named pipe via native API, along
        /// with a returned .Net NamedPipeServerStream object wrapping the named pipe.
        /// </summary>
        /// <param name="serverName">Named pipe server name.</param>
        /// <param name="namespaceName">Named pipe namespace name.</param>
        /// <param name="coreName">Named pipe core name.</param>
        /// <param name="securityDesc"></param>
        /// <returns>NamedPipeServerStream.</returns>
        private static NamedPipeServerStream CreateNamedPipe(
            string serverName,
            string namespaceName,
            string coreName,
            CommonSecurityDescriptor securityDesc)
        {
            if (serverName == null)
            {
                throw new PSArgumentNullException(nameof(serverName));
            }

            if (namespaceName == null)
            {
                throw new PSArgumentNullException(nameof(namespaceName));
            }

            if (coreName == null)
            {
                throw new PSArgumentNullException(nameof(coreName));
            }

#if !UNIX
            string fullPipeName = @"\\" + serverName + @"\" + namespaceName + @"\" + coreName;

            // Create optional security attributes based on provided PipeSecurity.
            NamedPipeNative.SECURITY_ATTRIBUTES securityAttributes = null;
            GCHandle?securityDescHandle = null;
            if (securityDesc != null)
            {
                byte[] securityDescBuffer = new byte[securityDesc.BinaryLength];
                securityDesc.GetBinaryForm(securityDescBuffer, 0);
                securityDescHandle = GCHandle.Alloc(securityDescBuffer, GCHandleType.Pinned);
                securityAttributes = NamedPipeNative.GetSecurityAttributes(securityDescHandle.Value);
            }

            // Create named pipe.
            SafePipeHandle pipeHandle = NamedPipeNative.CreateNamedPipe(
                fullPipeName,
                NamedPipeNative.PIPE_ACCESS_DUPLEX | NamedPipeNative.FILE_FLAG_FIRST_PIPE_INSTANCE | NamedPipeNative.FILE_FLAG_OVERLAPPED,
                NamedPipeNative.PIPE_TYPE_MESSAGE | NamedPipeNative.PIPE_READMODE_MESSAGE,
                1,
                _namedPipeBufferSizeForRemoting,
                _namedPipeBufferSizeForRemoting,
                0,
                securityAttributes);

            int lastError = Marshal.GetLastWin32Error();
            if (securityDescHandle != null)
            {
                securityDescHandle.Value.Free();
            }

            if (pipeHandle.IsInvalid)
            {
                throw new PSInvalidOperationException(
                          StringUtil.Format(RemotingErrorIdStrings.CannotCreateNamedPipe, lastError));
            }

            // Create the .Net NamedPipeServerStream wrapper.
            try
            {
                return(new NamedPipeServerStream(
                           PipeDirection.InOut,
                           true,                // IsAsync
                           false,               // IsConnected
                           pipeHandle));
            }
            catch (Exception)
            {
                pipeHandle.Dispose();
                throw;
            }
#else
            return(new NamedPipeServerStream(
                       pipeName: coreName,
                       direction: PipeDirection.InOut,
                       maxNumberOfServerInstances: 1,
                       transmissionMode: PipeTransmissionMode.Byte,
                       options: PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly,
                       inBufferSize: _namedPipeBufferSizeForRemoting,
                       outBufferSize: _namedPipeBufferSizeForRemoting));
#endif
        }
        public static void TestGetBinaryForm(bool isContainer, bool isDS, string sddl, string verifierSddl, int offset)
        {
            CommonSecurityDescriptor commonSecurityDescriptor = null;
            CommonSecurityDescriptor verifierCommonSecurityDescriptor = null;
            string resultSddl = null;
            commonSecurityDescriptor = new CommonSecurityDescriptor(isContainer, isDS, sddl);
            byte[] binaryForm = new byte[commonSecurityDescriptor.BinaryLength + offset];
            commonSecurityDescriptor.GetBinaryForm(binaryForm, offset);
            verifierCommonSecurityDescriptor = new CommonSecurityDescriptor(isContainer, isDS, binaryForm, offset);
            resultSddl = verifierCommonSecurityDescriptor.GetSddlForm(AccessControlSections.All);

            if (resultSddl == null || verifierSddl == null)
                Assert.True(resultSddl == null && verifierSddl == null);
            else
                Assert.True(String.Compare(resultSddl, verifierSddl, StringComparison.CurrentCultureIgnoreCase) == 0);
        }
Example #32
0
 public void CreatePublicFolderTree()
 {
     this.pfTree = new PublicFolderTree();
     try
     {
         QueryFilter filter;
         ADObjectId  adobjectId;
         if (Datacenter.GetExchangeSku() != Datacenter.ExchangeSku.ExchangeDatacenter)
         {
             filter = new ComparisonFilter(ComparisonOperator.Equal, ADObjectSchema.Name, PublicFolderTreeContainer.DefaultName);
             PublicFolderTreeContainer[] array = this.taskInstance.GlobalConfigSession.Find <PublicFolderTreeContainer>(null, QueryScope.SubTree, filter, null, 1);
             PublicFolderTreeContainer   publicFolderTreeContainer;
             if (array == null || array.Length == 0)
             {
                 filter = new ComparisonFilter(ComparisonOperator.Equal, ADObjectSchema.Name, AdministrativeGroup.DefaultName);
                 AdministrativeGroup[] array2 = this.taskInstance.GlobalConfigSession.Find <AdministrativeGroup>(null, QueryScope.SubTree, filter, null, 1);
                 if (array2 == null || array2.Length < 1)
                 {
                     throw new AdminGroupNotFoundException(AdministrativeGroup.DefaultName);
                 }
                 publicFolderTreeContainer = new PublicFolderTreeContainer();
                 publicFolderTreeContainer.SetId(array2[0].Id.GetChildId(PublicFolderTreeContainer.DefaultName));
                 this.taskInstance.DataSession.Save(publicFolderTreeContainer);
             }
             else
             {
                 publicFolderTreeContainer = array[0];
             }
             adobjectId = publicFolderTreeContainer.Id;
         }
         else
         {
             adobjectId = this.OrganizationId.ConfigurationUnit;
             this.pfTree.OrganizationId = this.OrganizationId;
         }
         this.pfTree.SetId(adobjectId.GetChildId("Public Folders"));
         this.taskInstance.WriteVerbose(Strings.VerboseCreatePublicFolderTree(this.pfTree.Id.ToString()));
         this.pfTree.PublicFolderTreeType = PublicFolderTreeType.Mapi;
         filter = new ComparisonFilter(ComparisonOperator.Equal, ExtendedRightSchema.DisplayName, "Create public folder");
         this.taskInstance.WriteVerbose(TaskVerboseStringHelper.GetFindDataObjectsVerboseString(this.taskInstance.GlobalConfigSession, typeof(ExtendedRight), filter, this.taskInstance.GlobalConfigSession.ConfigurationNamingContext, true));
         ExtendedRight[] array3 = this.taskInstance.GlobalConfigSession.Find <ExtendedRight>(this.taskInstance.GlobalConfigSession.ConfigurationNamingContext, QueryScope.SubTree, filter, null, 1);
         if (0 < array3.Length)
         {
             ObjectAce        objectAce        = new ObjectAce(AceFlags.None, AceQualifier.AccessAllowed, 256, new SecurityIdentifier("AU"), ObjectAceFlags.ObjectAceTypePresent, array3[0].RightsGuid, Guid.Empty, false, null);
             DiscretionaryAcl discretionaryAcl = new DiscretionaryAcl(false, true, 11);
             discretionaryAcl.AddAccess(AccessControlType.Allow, objectAce.SecurityIdentifier, objectAce.AccessMask, objectAce.InheritanceFlags, objectAce.PropagationFlags, objectAce.ObjectAceFlags, objectAce.ObjectAceType, objectAce.InheritedObjectAceType);
             using (WindowsIdentity current = WindowsIdentity.GetCurrent())
             {
                 SecurityIdentifier       user = current.User;
                 CommonSecurityDescriptor commonSecurityDescriptor = new CommonSecurityDescriptor(false, true, ControlFlags.DiscretionaryAclPresent, user, user, null, discretionaryAcl);
                 byte[] binaryForm = new byte[commonSecurityDescriptor.BinaryLength];
                 commonSecurityDescriptor.GetBinaryForm(binaryForm, 0);
                 this.pfTree.SetPublicFolderDefaultAdminAcl(new RawSecurityDescriptor(binaryForm, 0));
             }
         }
         this.taskInstance.WriteVerbose(TaskVerboseStringHelper.GetSourceVerboseString(this.TenantSession));
         this.taskInstance.WriteVerbose(TaskVerboseStringHelper.GetSaveObjectVerboseString(this.pfTree, this.TenantSession, typeof(PublicFolderTree)));
         this.TenantSession.Save(this.pfTree);
         if (Datacenter.GetExchangeSku() == Datacenter.ExchangeSku.ExchangeDatacenter)
         {
             this.SetOrganizationManagementACLs(this.pfTree);
         }
     }
     finally
     {
         this.taskInstance.WriteVerbose(TaskVerboseStringHelper.GetSourceVerboseString(this.TenantSession));
     }
 }