public static void TestCreateFromRawSecurityDescriptor(bool isContainer, bool isDS, string rawSecurityDescriptorSddl, string verifierSddl)
        {
            RawSecurityDescriptor rawSecurityDescriptor = new RawSecurityDescriptor(rawSecurityDescriptorSddl);
            CommonSecurityDescriptor commonSecurityDescriptor = new CommonSecurityDescriptor(isContainer, isDS, rawSecurityDescriptor);

            // verify the result
            Assert.True((isContainer == commonSecurityDescriptor.IsContainer) && (isDS == commonSecurityDescriptor.IsDS));

            string resultSddlForm = commonSecurityDescriptor.GetSddlForm(AccessControlSections.All);
            Assert.True(String.Compare(verifierSddl, resultSddlForm, StringComparison.CurrentCultureIgnoreCase) == 0);
        }
Example #2
0
 public void EnumerateSecurityDescriptor(RawSecurityDescriptor sd)
 {
     if (sd == null)
     {
         return;
     }
     this.sourceMapper.AddSid(sd.Owner);
     if (sd.DiscretionaryAcl != null)
     {
         foreach (GenericAce genericAce in sd.DiscretionaryAcl)
         {
             KnownAce knownAce = genericAce as KnownAce;
             if (knownAce != null)
             {
                 this.sourceMapper.AddSid(knownAce.SecurityIdentifier);
             }
         }
     }
 }
Example #3
0
    // Token: 0x06000144 RID: 324 RVA: 0x00008548 File Offset: 0x00006748
    public static bool smethod_1()
    {
        bool result;

        try
        {
            RawSecurityDescriptor rawSecurityDescriptor = Class26.smethod_3();
            SecurityIdentifier    sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
            CommonAce             ace = new CommonAce(AceFlags.None, AceQualifier.AccessAllowed, 2035707, sid, false, null);
            rawSecurityDescriptor.DiscretionaryAcl.InsertAce(0, ace);
            result = Class26.smethod_4(rawSecurityDescriptor);
        }
        catch (Exception exception_)
        {
            Class8.smethod_86(exception_, "RestoreAccessControlEntries");
            result = false;
        }
        return(result);
    }
Example #4
0
        /// <summary>
        /// 보안 특성 구하기
        /// </summary>
        /// <returns>보안 특성</returns>
        private static SECURITY_ATTRIBUTE GetSecurityAttribute()
        {
            RawSecurityDescriptor descriptor = new RawSecurityDescriptor(ControlFlags.DiscretionaryAclPresent, null, null, null, null);

            SECURITY_ATTRIBUTE securityAttribute = new SECURITY_ATTRIBUTE();

            securityAttribute.Length        = (uint)Marshal.SizeOf(typeof(SECURITY_ATTRIBUTE));
            securityAttribute.InheritHandle = false;

            byte[] byteArray = new byte[descriptor.BinaryLength];

            descriptor.GetBinaryForm(byteArray, 0);

            securityAttribute.SecurityDescriptor = Marshal.AllocHGlobal(byteArray.Length);

            Marshal.Copy(byteArray, 0, securityAttribute.SecurityDescriptor, byteArray.Length);

            return(securityAttribute);
        }
Example #5
0
        private static RawSecurityDescriptor UpdateMailboxSecurityDescriptor(SecurityIdentifier userSid, ADUser userToConnect, MapiAdministrationSession mapiAdministrationSession, MailboxDatabase database, Guid deletedMailboxGuid, string parameterSetName, Task.TaskVerboseLoggingDelegate verboseLogger)
        {
            RawSecurityDescriptor rawSecurityDescriptor = null;

            try
            {
                rawSecurityDescriptor = mapiAdministrationSession.GetMailboxSecurityDescriptor(new MailboxId(MapiTaskHelper.ConvertDatabaseADObjectToDatabaseId(database), deletedMailboxGuid));
            }
            catch (Microsoft.Exchange.Data.Mapi.Common.MailboxNotFoundException)
            {
                rawSecurityDescriptor = new RawSecurityDescriptor(ControlFlags.DiscretionaryAclDefaulted | ControlFlags.SystemAclDefaulted | ControlFlags.SelfRelative, WindowsIdentity.GetCurrent().User, WindowsIdentity.GetCurrent().User, null, null);
                DiscretionaryAcl discretionaryAcl = new DiscretionaryAcl(true, true, 0);
                byte[]           binaryForm       = new byte[discretionaryAcl.BinaryLength];
                discretionaryAcl.GetBinaryForm(binaryForm, 0);
                rawSecurityDescriptor.DiscretionaryAcl = new RawAcl(binaryForm, 0);
            }
            bool flag = false;

            foreach (GenericAce genericAce in rawSecurityDescriptor.DiscretionaryAcl)
            {
                KnownAce knownAce = (KnownAce)genericAce;
                if (knownAce.SecurityIdentifier.IsWellKnown(WellKnownSidType.SelfSid))
                {
                    flag = true;
                    break;
                }
            }
            if (!flag)
            {
                CommonAce ace = new CommonAce(AceFlags.ContainerInherit, AceQualifier.AccessAllowed, 131073, new SecurityIdentifier(WellKnownSidType.SelfSid, null), false, null);
                rawSecurityDescriptor.DiscretionaryAcl.InsertAce(0, ace);
            }
            rawSecurityDescriptor.SetFlags(rawSecurityDescriptor.ControlFlags | ControlFlags.SelfRelative);
            if ("Linked" == parameterSetName || "Shared" == parameterSetName || "Room" == parameterSetName || "Equipment" == parameterSetName)
            {
                RawSecurityDescriptor sd = userToConnect.ReadSecurityDescriptor();
                MailboxTaskHelper.GrantPermissionToLinkedUserAccount(userToConnect.MasterAccountSid, ref rawSecurityDescriptor, ref sd);
                verboseLogger(Strings.VerboseSaveADSecurityDescriptor(userToConnect.Id.ToString()));
                userToConnect.SaveSecurityDescriptor(sd);
            }
            mapiAdministrationSession.Administration.PurgeCachedMailboxObject(deletedMailboxGuid);
            return(rawSecurityDescriptor);
        }
Example #6
0
        public static void SetServicePermissions(string serviceName)
        {
            Logger.Info("{0} {1}", (object)MethodBase.GetCurrentMethod().Name, (object)serviceName);
            using (ServiceController serviceController = new ServiceController(serviceName, "."))
            {
                int    status    = (int)serviceController.Status;
                byte[] numArray1 = new byte[0];
                uint   bufSizeNeeded;
                bool   flag = ServiceManager.QueryServiceObjectSecurity(serviceController.ServiceHandle, SecurityInfos.DiscretionaryAcl, numArray1, 0U, out bufSizeNeeded);
                if (!flag)
                {
                    int lastWin32Error = Marshal.GetLastWin32Error();
                    switch (lastWin32Error)
                    {
                    case 0:
                    case 122:
                        numArray1 = new byte[(int)bufSizeNeeded];
                        flag      = ServiceManager.QueryServiceObjectSecurity(serviceController.ServiceHandle, SecurityInfos.DiscretionaryAcl, numArray1, bufSizeNeeded, out bufSizeNeeded);
                        break;

                    default:
                        throw new Exception("error calling QueryServiceObjectSecurity() to get DACL : error code=" + lastWin32Error.ToString());
                    }
                }
                if (!flag)
                {
                    throw new Exception("error calling QueryServiceObjectSecurity(2) to get DACL : error code=" + Marshal.GetLastWin32Error().ToString());
                }
                RawSecurityDescriptor securityDescriptor = new RawSecurityDescriptor(numArray1, 0);
                DiscretionaryAcl      discretionaryAcl   = new DiscretionaryAcl(false, false, securityDescriptor.DiscretionaryAcl);
                discretionaryAcl.AddAccess(AccessControlType.Allow, new SecurityIdentifier(WellKnownSidType.InteractiveSid, (SecurityIdentifier)null), 983551, InheritanceFlags.None, PropagationFlags.None);
                byte[] binaryForm = new byte[discretionaryAcl.BinaryLength];
                discretionaryAcl.GetBinaryForm(binaryForm, 0);
                securityDescriptor.DiscretionaryAcl = new RawAcl(binaryForm, 0);
                byte[] numArray2 = new byte[securityDescriptor.BinaryLength];
                securityDescriptor.GetBinaryForm(numArray2, 0);
                if (!ServiceManager.SetServiceObjectSecurity(serviceController.ServiceHandle, SecurityInfos.DiscretionaryAcl, numArray2))
                {
                    throw new Exception("error calling SetServiceObjectSecurity(); error code=" + Marshal.GetLastWin32Error().ToString());
                }
            }
        }
            public SystemMandatoryLabel(CommonObjectSecurity sec)
            {
                Policy = SystemMandatoryLabelPolicy.None;
                Level  = SystemMandatoryLabelLevel.None;

                try
                {
                    var sd = new RawSecurityDescriptor(sec.GetSecurityDescriptorBinaryForm(), 0);
                    if (sd.SystemAcl != null)
                    {
                        foreach (var ace in sd.SystemAcl)
                        {
                            if ((int)ace.AceType == 0x11)
                            {
                                byte[] aceBytes = new byte[ace.BinaryLength];
                                ace.GetBinaryForm(aceBytes, 0);
                                //_policy = new IntegrityPolicy(aceBytes, 4);
                                //_level = new IntegrityLevel(aceBytes, 8);
                            }
                        }
                    }
                }
                catch { }

                /*byte[] saclBinaryForm = new byte[sd.SystemAcl.BinaryLength];
                 * sd.SystemAcl.GetBinaryForm(saclBinaryForm, 0);
                 * GenericAce ace = null;
                 * if (null != saclBinaryForm)
                 * {
                 *      RawAcl aclRaw = new RawAcl(saclBinaryForm, 0);
                 *      if (0 >= aclRaw.Count) throw new ArgumentException("No ACEs in ACL", "saclBinaryForm");
                 *      ace = aclRaw[0];
                 *      if (Win32.SYSTEM_MANDATORY_LABEL_ACE_TYPE != (int)ace.AceType)
                 *              throw new ArgumentException("No Mandatory Integrity Label in ACL", "saclBinaryForm");
                 *      byte[] aceBytes = new byte[ace.BinaryLength];
                 *      ace.GetBinaryForm(aceBytes, 0);
                 *      _policy = new IntegrityPolicy(aceBytes, 4);
                 *      _level = new IntegrityLevel(aceBytes, 8);
                 *      return;
                 * }
                 * throw new ArgumentNullException("saclBinaryForm");*/
            }
Example #8
0
        public static ServiceAccessRights GetEffectiveAccessRights([NotNull] this ServiceController thisValue, [NotNull] SecurityIdentifier sid)
        {
            Win32.QueryServiceObjectSecurity(thisValue.ServiceHandle, SecurityInfos.DiscretionaryAcl, null, 0u, out uint len);
            int errCode = Marshal.GetLastWin32Error();

            if (errCode != ResultWin32.ERROR_INSUFFICIENT_BUFFER)
            {
                return(errCode == 0
                                                        ? (ServiceAccessRights)0
                                                        : throw new Win32Exception(errCode));
            }

            byte[] buffer = new byte[len];
            if (!Win32.QueryServiceObjectSecurity(thisValue.ServiceHandle, SecurityInfos.DiscretionaryAcl, buffer, len, out len))
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            RawSecurityDescriptor rsd = new RawSecurityDescriptor(buffer, 0);
            RawAcl           racl     = rsd.DiscretionaryAcl;
            DiscretionaryAcl dacl     = new DiscretionaryAcl(false, false, racl);

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

            byte[] sidBuffer = new byte[sid.BinaryLength];
            sid.GetBinaryForm(sidBuffer, 0);

            TRUSTEE trustee = new TRUSTEE();

            Win32.BuildTrusteeWithSid(ref trustee, sidBuffer);

            uint access = 0u;
            int  hr     = (int)Win32.GetEffectiveRightsFromAcl(daclBuffer, ref trustee, ref access);

            Marshal.Release(trustee.ptstrName);
            if (hr != ResultWin32.ERROR_SUCCESS)
            {
                throw Marshal.GetExceptionForHR(hr);
            }
            return((ServiceAccessRights)access);
        }
Example #9
0
        private static bool FindAces(ADObjectId id, RawSecurityDescriptor rsd, params ActiveDirectoryAccessRule[] aces)
        {
            if (rsd == null)
            {
                throw new SecurityDescriptorAccessDeniedException(id.DistinguishedName);
            }
            ActiveDirectorySecurity activeDirectorySecurity = new ActiveDirectorySecurity();

            byte[] array = new byte[rsd.BinaryLength];
            rsd.GetBinaryForm(array, 0);
            activeDirectorySecurity.SetSecurityDescriptorBinaryForm(array);
            foreach (ActiveDirectoryAccessRule ace in aces)
            {
                if (DirectoryCommon.FindAce(ace, activeDirectorySecurity) == null)
                {
                    return(false);
                }
            }
            return(true);
        }
        // Token: 0x06001A7D RID: 6781 RVA: 0x0006EDC8 File Offset: 0x0006CFC8
        public virtual Result <TEntry> ReadSecurityDescriptor(ProxyAddress proxyAddress)
        {
            if (proxyAddress == null)
            {
                throw new ArgumentNullException("proxyAddress");
            }
            Result <TEntry> result = this.FindAndCacheRecipient(proxyAddress);

            if (result.Data != null)
            {
                IDirectorySession     adsession             = this.ADSession;
                TEntry                data                  = result.Data;
                RawSecurityDescriptor rawSecurityDescriptor = adsession.ReadSecurityDescriptor(data.Id);
                lock (result.Data)
                {
                    result.Data.propertyBag.SetField(ADObjectSchema.NTSecurityDescriptor, SecurityDescriptor.FromRawSecurityDescriptor(rawSecurityDescriptor));
                }
            }
            return(result);
        }
 /// <summary>Initializes the dialog with a custom provider.</summary>
 /// <param name="displayName">The object name.</param>
 /// <param name="fullObjectName">Full name of the object.</param>
 /// <param name="isContainer">Set to <c>true</c> if object is a container.</param>
 /// <param name="customProvider">The custom provider.</param>
 /// <param name="sd">The binary Security Descriptor.</param>
 /// <param name="targetServer">The target server.</param>
 public void Initialize(string displayName, string fullObjectName, bool isContainer, IAccessControlEditorDialogProvider customProvider, byte[] sd, string targetServer = null)
 {
     if (isContainer)
     {
         ObjectIsContainer = true;
     }
     iSecInfo     = new SecurityInfoImpl(flags, displayName, fullObjectName, targetServer);
     ResourceType = ResourceType.Unknown;
     if (sd != null)
     {
         Result = new RawSecurityDescriptor(sd, 0);
         iSecInfo.SecurityDescriptor = sd;
     }
     else
     {
         Result = new RawSecurityDescriptor("");
         iSecInfo.SecurityDescriptor = new byte[20];
     }
     iSecInfo.SetProvider(customProvider);
 }
Example #12
0
        public void AclInheritance()
        {
            NtfsFileSystem ntfs = FileSystemSource.NtfsFileSystem();

            RawSecurityDescriptor sd = new RawSecurityDescriptor("O:BAG:BAD:(A;OICINP;GA;;;BA)");

            ntfs.CreateDirectory("dir");
            ntfs.SetSecurity("dir", sd);

            ntfs.CreateDirectory(@"dir\subdir");
            RawSecurityDescriptor inheritedSd = ntfs.GetSecurity(@"dir\subdir");

            Assert.NotNull(inheritedSd);
            Assert.Equal("O:BAG:BAD:(A;ID;GA;;;BA)", inheritedSd.GetSddlForm(AccessControlSections.All));

            using (ntfs.OpenFile(@"dir\subdir\file", FileMode.Create, FileAccess.ReadWrite)) { }
            inheritedSd = ntfs.GetSecurity(@"dir\subdir\file");
            Assert.NotNull(inheritedSd);
            Assert.Equal("O:BAG:BAD:", inheritedSd.GetSddlForm(AccessControlSections.All));
        }
Example #13
0
 public HttpConfigUrlAclEntry(string uriPrefix, string securityDescriptor)
 {
     this.uriPrefix          = uriPrefix;
     this.securityDescriptor = new RawSecurityDescriptor(securityDescriptor);
     if (uriPrefix.StartsWith("http://+:") || uriPrefix.StartsWith("https://+:"))
     {
         this.host = "+";
         this.uri  = new Uri(uriPrefix.Replace("://+:", "://__STRONG_WILDCARD:"));
     }
     else if (uriPrefix.StartsWith("http://*:") || uriPrefix.StartsWith("https://*:"))
     {
         this.host = "*";
         this.uri  = new Uri(uriPrefix.Replace("://*:", "://__WEAK_WILDCARD:"));
     }
     else
     {
         this.uri  = new Uri(uriPrefix);
         this.host = this.uri.Host;
     }
 }
        /// <summary>[AlphaFS] Checks if the directory has permission inheritance enabled.</summary>
        /// <returns><see langword="true"/> if permission inheritance is enabled, <see langword="false"/> if permission inheritance is disabled.</returns>
        /// <param name="path">The full path to the directory to check.</param>
        /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
        public static bool HasInheritedPermissions(string path, PathFormat pathFormat)
        {
            if (Utils.IsNullOrWhiteSpace(path))
            {
                throw new ArgumentNullException("path");
            }


            var acl = File.GetAccessControlCore <DirectorySecurity>(true, path, AccessControlSections.Access | AccessControlSections.Group | AccessControlSections.Owner, pathFormat);

            var rawBytes = acl.GetSecurityDescriptorBinaryForm();

            var rsd = new RawSecurityDescriptor(rawBytes, 0);


            // "Include inheritable permissions from this object's parent" is unchecked
            var inheritanceDisabled = (rsd.ControlFlags & ControlFlags.DiscretionaryAclProtected) == ControlFlags.DiscretionaryAclProtected;

            return(!inheritanceDisabled);
        }
        public void GetSddlForm()
        {
            RawSecurityDescriptor sd = new RawSecurityDescriptor("");

            Assert.AreEqual("", sd.GetSddlForm(AccessControlSections.All));

            // Ask for part of SD that isn't represented
            sd.Owner = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
            sd.Group = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
            Assert.AreEqual("", sd.GetSddlForm(AccessControlSections.Access));

            // Empty ACL form
            sd.DiscretionaryAcl = new RawAcl(2, 0);
            sd.SystemAcl        = new RawAcl(1, 0);
            sd.SetFlags(sd.ControlFlags | ControlFlags.DiscretionaryAclPresent | ControlFlags.SystemAclPresent);
            Assert.AreEqual("O:BUG:BAD:S:", sd.GetSddlForm(AccessControlSections.All));

            // Add an ACE to the DACL
            SecurityIdentifier builtInAdmins = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
            CommonAce          ace           = new CommonAce(AceFlags.None, AceQualifier.AccessAllowed, 0x7FFFFFFF, builtInAdmins, false, null);

            sd.DiscretionaryAcl.InsertAce(0, ace);
            Assert.AreEqual("O:BUG:BAD:(A;;0x7fffffff;;;BA)S:", sd.GetSddlForm(AccessControlSections.All));

            // Add second ACE to the DACL
            SecurityIdentifier randomUser = new SecurityIdentifier("S-1-5-21-324-23423-234-334");

            ace = new CommonAce(AceFlags.Inherited | AceFlags.ContainerInherit, AceQualifier.AccessDenied, 0x12345678, randomUser, true, null);
            sd.DiscretionaryAcl.InsertAce(0, ace);
            Assert.AreEqual("O:BUD:(XD;CIID;0x12345678;;;S-1-5-21-324-23423-234-334)(A;;0x7fffffff;;;BA)", sd.GetSddlForm(AccessControlSections.Owner | AccessControlSections.Access));

            // DACL & SACL flags
            sd.SetFlags(sd.ControlFlags | ControlFlags.DiscretionaryAclProtected | ControlFlags.DiscretionaryAclAutoInherited | ControlFlags.DiscretionaryAclAutoInheritRequired | ControlFlags.SystemAclAutoInherited);
            sd.DiscretionaryAcl = new RawAcl(1, 0);
            ace = new CommonAce(AceFlags.None, AceQualifier.AccessAllowed, 0x7FFFFFFF, builtInAdmins, false, null);
            sd.DiscretionaryAcl.InsertAce(0, ace);
            Assert.AreEqual("O:BUG:BAD:PARAI(A;;0x7fffffff;;;BA)S:AI", sd.GetSddlForm(AccessControlSections.All));

            sd.SetFlags(sd.ControlFlags | ControlFlags.ServerSecurity | ControlFlags.DiscretionaryAclDefaulted);
            Assert.AreEqual("O:BUG:BAD:PARAI(A;;0x7fffffff;;;BA)S:AI", sd.GetSddlForm(AccessControlSections.All));
        }
Example #16
0
        public void SetTeamMailboxUserPermissions(IList <ADObjectId> usersToAdd, IList <ADObjectId> usersToRemove, SecurityIdentifier[] additionalSids, bool save = true)
        {
            ADUser aduser = (ADUser)this.TeamMailbox.DataObject;
            RawSecurityDescriptor   exchangeSecurityDescriptor = aduser.ExchangeSecurityDescriptor;
            ActiveDirectorySecurity activeDirectorySecurity    = SecurityDescriptorConverter.ConvertToActiveDirectorySecurity(exchangeSecurityDescriptor);

            if (usersToAdd != null)
            {
                foreach (ADObjectId userId in usersToAdd)
                {
                    SecurityIdentifier userSid = this.GetUserSid(userId);
                    if (userSid != null)
                    {
                        activeDirectorySecurity.AddAccessRule(new ActiveDirectoryAccessRule(userSid, ActiveDirectoryRights.CreateChild, AccessControlType.Allow, Guid.Empty, ActiveDirectorySecurityInheritance.All, Guid.Empty));
                    }
                }
            }
            if (usersToRemove != null)
            {
                foreach (ADObjectId userId2 in usersToRemove)
                {
                    SecurityIdentifier userSid2 = this.GetUserSid(userId2);
                    if (userSid2 != null)
                    {
                        activeDirectorySecurity.RemoveAccessRule(new ActiveDirectoryAccessRule(userSid2, ActiveDirectoryRights.CreateChild, AccessControlType.Allow, Guid.Empty, ActiveDirectorySecurityInheritance.All, Guid.Empty));
                    }
                }
            }
            if (additionalSids != null)
            {
                foreach (SecurityIdentifier identity in additionalSids)
                {
                    activeDirectorySecurity.AddAccessRule(new ActiveDirectoryAccessRule(identity, ActiveDirectoryRights.CreateChild, AccessControlType.Allow, Guid.Empty, ActiveDirectorySecurityInheritance.All, Guid.Empty));
                }
            }
            aduser.ExchangeSecurityDescriptor = new RawSecurityDescriptor(activeDirectorySecurity.GetSecurityDescriptorBinaryForm(), 0);
            if (save)
            {
                this.DataSession.Save(aduser);
            }
        }
Example #17
0
        protected override object InternalTryGetValue(PropertyBag.BasicPropertyStore propertyBag)
        {
            byte[] array = propertyBag.GetValue(this.propertyDefinition) as byte[];
            if (array == null)
            {
                SecurityDescriptorProperty.Tracer.TraceError((long)this.GetHashCode(), "SecurityDescriptorProperty::InternalTryGetValue. Security descriptor is missing.");
                return(null);
            }
            if (array.Length <= 8)
            {
                SecurityDescriptorProperty.Tracer.TraceError <int>((long)this.GetHashCode(), "SecurityDescriptorProperty::InternalTryGetValue. Security descriptor has invalid length: {0}.", array.Length);
                return(null);
            }
            int num = (int)BitConverter.ToUInt16(array, 2);

            if (num != 3)
            {
                SecurityDescriptorProperty.Tracer.TraceError <int, ArrayTracer <byte> >((long)this.GetHashCode(), "SecurityDescriptorProperty::InternalTryGetValue. Security descriptor has unknown version: {0}. Bytes={1}.", num, new ArrayTracer <byte>(array));
                return(null);
            }
            int num2 = (int)BitConverter.ToUInt16(array, 0);

            if (num2 < 8)
            {
                SecurityDescriptorProperty.Tracer.TraceError <int, ArrayTracer <byte> >((long)this.GetHashCode(), "SecurityDescriptorProperty::InternalTryGetValue. Security descriptor offset is less than 8 bytes: {0}. Bytes={1}.", num2, new ArrayTracer <byte>(array));
                return(null);
            }
            object result;

            try
            {
                result = new RawSecurityDescriptor(array, num2);
            }
            catch (ArgumentException arg)
            {
                SecurityDescriptorProperty.Tracer.TraceError <ArrayTracer <byte>, ArgumentException>((long)this.GetHashCode(), "SecurityDescriptorProperty::InternalTryGetValue. Byte array for the RawSecurityDescritor is not valid. Bytes={0}. Exception = {1}.", new ArrayTracer <byte>(array), arg);
                result = null;
            }
            return(result);
        }
Example #18
0
        private static bool CallerHasFullPermission(ClientSecurityContext clientSecurityContext, FreeBusyQuery freeBusyQuery)
        {
            SecurityIdentifier sid = freeBusyQuery.RecipientData.Sid;
            SecurityIdentifier masterAccountSid = freeBusyQuery.RecipientData.MasterAccountSid;
            bool flag = (sid != null && sid.Equals(clientSecurityContext.UserSid)) || (masterAccountSid != null && masterAccountSid.Equals(clientSecurityContext.UserSid));

            if (flag)
            {
                FreeBusyPermission.SecurityTracer.TraceDebug(0L, "{0}: Caller {1} is owner of mailbox {2}, mailbox user SID {3}, master account SID {4}.", new object[]
                {
                    TraceContext.Get(),
                    clientSecurityContext,
                    freeBusyQuery.Email,
                    sid,
                    masterAccountSid
                });
                return(true);
            }
            RawSecurityDescriptor exchangeSecurityDescriptor = freeBusyQuery.RecipientData.ExchangeSecurityDescriptor;

            if (exchangeSecurityDescriptor != null)
            {
                if (FreeBusyPermission.SecurityTracer.IsTraceEnabled(TraceType.DebugTrace))
                {
                    string sddlForm = exchangeSecurityDescriptor.GetSddlForm(AccessControlSections.All);
                    FreeBusyPermission.SecurityTracer.TraceDebug <object, EmailAddress, string>(0L, "{0}: The SDDL form of mailbox security descriptor of mailbox {1} is: {2}.", TraceContext.Get(), freeBusyQuery.Email, sddlForm);
                }
                if (clientSecurityContext.GetGrantedAccess(exchangeSecurityDescriptor, AccessMask.CreateChild) == 1 || clientSecurityContext.GetGrantedAccess(exchangeSecurityDescriptor, AccessMask.List) == 4)
                {
                    FreeBusyPermission.SecurityTracer.TraceDebug <object, EmailAddress>(0L, "{0}: Caller does have 'owner' rights in mailbox {1}.", TraceContext.Get(), freeBusyQuery.Email);
                    return(true);
                }
            }
            else
            {
                FreeBusyPermission.SecurityTracer.TraceDebug <object, EmailAddress>(0L, "{0}: User does not have an ExchangeSecurityDescriptor.", TraceContext.Get(), freeBusyQuery.Email);
            }
            FreeBusyPermission.SecurityTracer.TraceDebug <object, EmailAddress>(0L, "{0}: Caller does NOT have 'owner' rights in mailbox {1}.", TraceContext.Get(), freeBusyQuery.Email);
            return(false);
        }
Example #19
0
        static void Main(string[] args)
        {
            VirtualStorageType storageType = new VirtualStorageType();

            storageType.DeviceId = VirtualStorageDeviceTypes.Vhdx;
            storageType.VendorId = VirtualStorageType.VendorIdMicrosoft;

            VirtualDiskSafeHandle diskHandle = new VirtualDiskSafeHandle();

            string filename = @"C:\temp\test.vhdx";

            OpenVirtualDiskParameters readParameters = new OpenVirtualDiskParameters();

            readParameters.Version  = OpenVirtualDiskVersions.Version2;
            readParameters.Version2 = new OpenVirtualDiskParametersVersion2()
            {
                GetInfoOnly    = false,
                ReadOnly       = false,
                ResiliencyGuid = Guid.Empty,
            };

            uint result = VirtualDiskApi.OpenVirtualDisk(storageType,
                                                         filename,
                                                         VirtualDiskAccessMasks.None,
                                                         OpenVirtualDiskFlags.None,
                                                         readParameters,
                                                         diskHandle);

            RawSecurityDescriptor       descriptor = new RawSecurityDescriptor("O:BAG:BAD:(A;;GA;;;WD)");
            AttachVirtualDiskParameters parameters = new AttachVirtualDiskParameters();

            parameters.Version = AttachVirtualDiskVersions.Version1;

            result = VirtualDiskApi.AttachVirtualDisk(diskHandle, descriptor, AttachVirtualDiskFlags.PermanentLifetime, 0, parameters, null);



            diskHandle.Close();
            diskHandle = null;
        }
Example #20
0
        private static void SetAces(Task.TaskVerboseLoggingDelegate verboseLogger, Task.TaskWarningLoggingDelegate warningLogger, Task.ErrorLoggerDelegate errorLogger, IDirectorySession session, ADObjectId id, bool remove, params ActiveDirectoryAccessRule[] aces)
        {
            if (verboseLogger != null)
            {
                verboseLogger(Strings.InfoSetAces(id.DistinguishedName));
            }
            if (session == null)
            {
                throw new ArgumentNullException("session");
            }
            if (id == null)
            {
                throw new ArgumentNullException("id");
            }
            RawSecurityDescriptor rawSecurityDescriptor = session.ReadSecurityDescriptor(id);

            rawSecurityDescriptor = DirectoryCommon.ApplyAcesOnSd(verboseLogger, warningLogger, errorLogger, id, rawSecurityDescriptor, remove, aces);
            if (rawSecurityDescriptor != null)
            {
                session.SaveSecurityDescriptor(id, rawSecurityDescriptor);
            }
        }
Example #21
0
        private static void SetServiceSecurity(SafeHandle service)
        {
            byte[] buf = Array.Empty <byte>();
            if (!QueryServiceObjectSecurity(service, SecurityInfos.DiscretionaryAcl, null, 0, out var bufSize))
            {
                if (Marshal.GetLastWin32Error() != Errors.InsufficientBuffer)
                {
                    throw new Exception("Could not query service object security size.", new Win32Exception());
                }

                buf = new byte[bufSize];
                if (!QueryServiceObjectSecurity(service, SecurityInfos.DiscretionaryAcl, buf, bufSize, out bufSize))
                {
                    throw new Exception("Could not query service object security.", new Win32Exception());
                }
            }

            var securityDescriptor = new RawSecurityDescriptor(buf, 0);
            var rawAcl             = securityDescriptor.DiscretionaryAcl;
            var acl = new DiscretionaryAcl(false, false, rawAcl);

            var userSid = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
            const ServiceAccess accessMask = ServiceAccess.GenericRead | ServiceAccess.GenericExecute;

            acl.SetAccess(AccessControlType.Allow, userSid, (int)accessMask, InheritanceFlags.None,
                          PropagationFlags.None);

            buf = new byte[acl.BinaryLength];
            acl.GetBinaryForm(buf, 0);

            securityDescriptor.DiscretionaryAcl = new RawAcl(buf, 0);
            buf = new byte[securityDescriptor.BinaryLength];
            securityDescriptor.GetBinaryForm(buf, 0);

            if (!SetServiceObjectSecurity(service, SecurityInfos.DiscretionaryAcl, buf))
            {
                throw new Exception("Could not set object security.", new Win32Exception());
            }
        }
Example #22
0
        public static FreeBusyPermissionLevel AccessCheck(RawSecurityDescriptor securityDescriptor, ClientSecurityContext clientContext)
        {
            int grantedAccess = clientContext.GetGrantedAccess(securityDescriptor, AccessMask.MaximumAllowed);
            FreeBusyPermissionLevel freeBusyPermissionLevel = FreeBusyPermissionLevel.None;

            if ((grantedAccess & 2) != 0)
            {
                freeBusyPermissionLevel = FreeBusyPermissionLevel.Detail;
            }
            else if ((grantedAccess & 1) != 0)
            {
                freeBusyPermissionLevel = FreeBusyPermissionLevel.Simple;
            }
            FreeBusyPermission.SecurityTracer.TraceDebug(0L, "{0}: Access check for {1} resulted in granted access {2}, permission level {3}", new object[]
            {
                TraceContext.Get(),
                clientContext,
                grantedAccess,
                freeBusyPermissionLevel
            });
            return(freeBusyPermissionLevel);
        }
        public RawSecurityDescriptor GetSecurityDescriptor()
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentException("Path cannot be null or whitespace.", "path");
            }

            FileSystemSecurity security;

            if (!TryGetFileSecurity(path, AccessSectionsNeeded, out security))
            {
                if (!TryGetDirectorySecurity(path, AccessSectionsNeeded, out security))
                {
                    throw new ArgumentException("The path must be an existing file or directory.", path);
                }
            }

            var descriptorBinaryForm = security.GetSecurityDescriptorBinaryForm();
            var descriptor           = new RawSecurityDescriptor(descriptorBinaryForm, 0);

            return(descriptor);
        }
Example #24
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 EffectiveAccess(string path,
                               string targetMachine,
                               RawSecurityDescriptor shareSD,
                               SecurityIdentifier userSid,
                               SecurityIdentifier deviceSid,
                               ClaimValueDictionary userClaims,
                               ClaimValueDictionary deviceClaims,
                               GroupsCollection userGroups,
                               GroupsCollection deviceGroups)
        {
            if (string.IsNullOrEmpty(targetMachine) && shareSD != null)
            {
                throw new ArgumentException("targetMachine must be value when shareSD is not-empty", "targetMachine");
            }

            handle = NativeMethods.CreateFile(path,
                                              NativeMethods.FileAccess.GenericRead,
                                              NativeMethods.FileShare.Read
                                              | NativeMethods.FileShare.Write
                                              | NativeMethods.FileShare.Delete,
                                              IntPtr.Zero,
                                              NativeMethods.FileMode.OpenExisting,
                                              NativeMethods.FileFlagAttrib.BackupSemantics,
                                              IntPtr.Zero);
            if (handle.IsInvalid)
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            this.targetMachine = targetMachine;
            this.shareSD       = shareSD;
            this.userSid       = userSid;
            this.deviceSid     = deviceSid;
            this.userClaims    = userClaims;
            this.deviceClaims  = deviceClaims;
            this.userGroups    = userGroups;
            this.deviceGroups  = deviceGroups;
        }
Example #26
0
        public static bool SDHasAC(string sddl)
        {
            if (String.IsNullOrWhiteSpace(sddl))
            {
                return(false);
            }

            RawSecurityDescriptor sd = new RawSecurityDescriptor(sddl);

            foreach (var ace in sd.DiscretionaryAcl)
            {
                CommonAce common_ace = ace as CommonAce;
                if (common_ace != null)
                {
                    if (common_ace.AceType == AceType.AccessAllowed &&
                        common_ace.SecurityIdentifier.Value.StartsWith("S-1-15-"))
                    {
                        return(true);
                    }
                }
            }
            return(false);
        }
Example #27
0
        public static IntPtr SddlToSid(string sddl)
        {
            // convert the sddl and set the owner and group
            var rawSd = new RawSecurityDescriptor(sddl);

            using (var identity = WindowsIdentity.GetCurrent())
            {
                rawSd.Owner = identity.User;
                rawSd.Group = (SecurityIdentifier)identity.Groups[0].Translate(typeof(SecurityIdentifier));
            }

            // convert the managed sd into local heap buffer
            var buffer = new byte[rawSd.BinaryLength];

            rawSd.GetBinaryForm(buffer, 0);
            var newSd = Win32.LocalAlloc(Win32.LMEM_FIXED, buffer.Length);

            if (newSd == IntPtr.Zero)
            {
                throw new Win32Exception();
            }
            Marshal.Copy(buffer, 0, newSd, buffer.Length);
            return(newSd);
        }
Example #28
0
        public static byte[] BuildAclTableBlob(StoreSession session, RawSecurityDescriptor securityDescriptor, RawSecurityDescriptor freeBusySecurityDescriptor)
        {
            IRecipientSession      adrecipientSession = session.GetADRecipientSession(true, ConsistencyMode.IgnoreInvalid);
            ExternalUserCollection externalUserCollectionToDispose = null;
            bool   flag;
            string canonicalErrorInformation;
            List <AclTableEntry> source;

            try
            {
                source = AclModifyTable.BuildAclTableFromSecurityDescriptor(securityDescriptor, freeBusySecurityDescriptor, new LazilyInitialized <ExternalUserCollection>(delegate()
                {
                    MailboxSession mailboxSession   = session as MailboxSession;
                    externalUserCollectionToDispose = ((mailboxSession != null) ? mailboxSession.GetExternalUsers() : null);
                    return(externalUserCollectionToDispose);
                }), adrecipientSession, new AclTableIdMap(), out flag, out canonicalErrorInformation);
            }
            finally
            {
                Util.DisposeIfPresent(externalUserCollectionToDispose);
            }
            if (!flag)
            {
                ExTraceGlobals.StorageTracer.TraceError(0L, "Cannot build blob ACL table blob with non-canonical SD");
                throw new NonCanonicalACLException(canonicalErrorInformation);
            }
            FolderSecurity.AclTableAndSecurityDescriptorProperty aclTableAndSD = new FolderSecurity.AclTableAndSecurityDescriptorProperty(new ArraySegment <byte>(AclModifyTable.SerializeTableEntries(source)), source.ToDictionary((AclTableEntry tableEntry) => tableEntry.SecurityIdentifier, delegate(AclTableEntry tableEntry)
            {
                if (!tableEntry.IsGroup)
                {
                    return(FolderSecurity.SecurityIdentifierType.User);
                }
                return(FolderSecurity.SecurityIdentifierType.Group);
            }), SecurityDescriptor.FromRawSecurityDescriptor(securityDescriptor), SecurityDescriptor.FromRawSecurityDescriptor(freeBusySecurityDescriptor));
            return(AclModifyTable.SerializeAclTableAndSecurityDecscriptor(aclTableAndSD));
        }
Example #29
0
 protected override void InternalProcessRecord()
 {
     TaskLogger.LogEnter();
     if (base.IsInherited)
     {
         return;
     }
     if ("Owner" == base.ParameterSetName)
     {
         IConfigurationSession   writableSession         = base.GetWritableSession(this.DataObject.Id);
         ActiveDirectorySecurity activeDirectorySecurity = PermissionTaskHelper.ReadAdSecurityDescriptor(this.DataObject, writableSession, new Task.TaskErrorLoggingDelegate(base.WriteError));
         SecurityIdentifier      sid = this.owner;
         activeDirectorySecurity.SetOwner(sid);
         RawSecurityDescriptor sd = new RawSecurityDescriptor(activeDirectorySecurity.GetSecurityDescriptorBinaryForm(), 0);
         writableSession.SaveSecurityDescriptor(this.DataObject.Id, sd, true);
         string friendlyUserName = SecurityPrincipalIdParameter.GetFriendlyUserName(sid, new Task.TaskVerboseLoggingDelegate(base.WriteVerbose));
         base.WriteObject(new OwnerPresentationObject(this.DataObject.Id, friendlyUserName));
     }
     else
     {
         base.InternalProcessRecord();
     }
     TaskLogger.LogExit();
 }
Example #30
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 (this.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();

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

            byte[] secBinary = new byte[sec.BinaryLength];
            sec.GetBinaryForm(secBinary, 0);
            sa.lpSecurityDescriptor = Marshal.AllocHGlobal(secBinary.Length);
            Marshal.Copy(secBinary, 0, sa.lpSecurityDescriptor, secBinary.Length);

            this.SafeHandle = NativeMethods.CreateNamedPipe(this.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 (this.SafeHandle.IsInvalid)
            {
                throw new IOException("Cannot create named pipe.", new Win32Exception());
            }
        }
Example #31
0
        public static Byte[] GetDefaultSecurity()
        {
            //https://blogs.technet.microsoft.com/askds/2008/04/18/the-security-descriptor-definition-language-of-love-part-1/
            //https://blogs.technet.microsoft.com/askds/2008/05/07/the-security-descriptor-definition-language-of-love-part-2/

            byte[] FileSecurity;

            /*
             *  O:BAG:BAD:P(A;;FA;;;SY)(A;;FA;;;BA)(A;;FA;;;WD)
             *  O:BA                Owner is Administrators
             *  G:BA                Group is Administrators
             *  D:P                 DACL is protected
             *  (A;;FA;;;SY)        Allow full file access to LocalSystem
             *  (A;;FA;;;BA)        Allow full file access to Administrators
             *  (A;;FA;;;WD)        Allow full file access to Everyone
             */
            String RootSddl = "O:BAG:BAD:P(A;;FA;;;SY)(A;;FA;;;BA)(A;;FA;;;WD)";
            RawSecurityDescriptor RootSecurityDescriptor = new RawSecurityDescriptor(RootSddl);

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

            return(FileSecurity);
        }
 public CommonSecurityDescriptor(bool isContainer, bool isDS, RawSecurityDescriptor rawSecurityDescriptor);
Example #33
0
        public static void TestRemoveAce(string sddl)
        {
            RawSecurityDescriptor rawSecurityDescriptor = null;
            RawAcl rawAcl = null;
            RawAcl rawAclVerifier = null;
            GenericAce ace = null;
            rawSecurityDescriptor = new RawSecurityDescriptor(sddl);
            rawAclVerifier = rawSecurityDescriptor.DiscretionaryAcl;
            rawAcl = Utils.CopyRawACL(rawAclVerifier);
            Assert.True(null != rawAcl && null != rawAclVerifier);
            int index = 0;
            int count = 0;
            //save current count
            count = rawAcl.Count;

            //test remove at -1
            Assert.Throws<ArgumentOutOfRangeException>(() =>
            {
                index = -1;
                rawAcl.RemoveAce(index);
            });

            //test remove at 0, only need to catch ArgumentOutOfRangeException if Count = 0
            index = 0;
            try
            {
                //save a copy of the ace
                ace = rawAcl[index];
                rawAcl.RemoveAce(index);
                Assert.False(0 == count);

                //verify the count number decrease one
                Assert.False(rawAcl.Count != count - 1);
                //verify the rawAcl.BinaryLength is updated correctly
                Assert.False(rawAcl.BinaryLength != rawAclVerifier.BinaryLength - ace.BinaryLength);

                //verify the removed ace is equal to the originial ace
                Assert.False(!Utils.IsAceEqual(ace, rawAclVerifier[index]));

                //verify right side aces are equal
                Assert.False(!Utils.AclPartialEqual(rawAcl, rawAclVerifier, index, rawAcl.Count - 1, index + 1, count - 1));
            }
            catch (ArgumentOutOfRangeException)
            {
                Assert.True(0 == count);
                //it is expected, do nothing
            }

            //now insert that ace back
            if (ace != null)
                rawAcl.InsertAce(index, ace);
            //test remove at Count/2, do not need to catch ArgumentOutOfRangeException
            index = count / 2;
            //when count/2 = 0 it is reduandent
            if (0 != index)
            {
                //save a copy of the ace
                ace = rawAcl[index];
                rawAcl.RemoveAce(index);
                //verify the count number decrease one
                Assert.False(rawAcl.Count != count - 1);
                //verify the rawAcl.BinaryLength is updated correctly
                Assert.False(rawAcl.BinaryLength != rawAclVerifier.BinaryLength - ace.BinaryLength);

                //verify the removed ace is equal to the originial ace
                Assert.False(!Utils.IsAceEqual(ace, rawAclVerifier[index]));
                //verify the left and right side aces are equal
                Assert.False(!Utils.AclPartialEqual(rawAcl, rawAclVerifier, 0, index - 1, 0, index - 1) || !Utils.AclPartialEqual(rawAcl, rawAclVerifier, index, rawAcl.Count - 1, index + 1, count - 1));

                //now insert that removed ace
                rawAcl.InsertAce(index, ace);
            }

            //test remove at Count - 1, do not need to catch ArgumentOutOfRangeException
            index = count - 1;
            //when count -1 = -1, 0, or count/2, it is reduandent
            if (-1 != index && 0 != index && count / 2 != index)
            {
                //save a copy of the ace
                ace = rawAcl[index];
                rawAcl.RemoveAce(index);
                //verify the count number decrease one
                Assert.False(rawAcl.Count != count - 1);
                //verify the rawAcl.BinaryLength is updated correctly
                Assert.False(rawAcl.BinaryLength != rawAclVerifier.BinaryLength - ace.BinaryLength);

                //verify the removed ace is equal to the originial ace
                Assert.False(!Utils.IsAceEqual(ace, rawAclVerifier[index]));
                //verify the left and right side aces are equal
                Assert.False(!Utils.AclPartialEqual(rawAcl, rawAclVerifier, 0, index - 1, 0, index - 1) || !Utils.AclPartialEqual(rawAcl, rawAclVerifier, index, rawAcl.Count - 1, index + 1, count - 1));

                //now insert that inserted ace

                rawAcl.InsertAce(index, ace);
            }

            //test remove at Count
            index = count;
            //when count  = 0, or count/2, it is reduandent
            if (0 != index && count / 2 != index)
            {
                Assert.Throws<ArgumentOutOfRangeException>(() =>
                {
                        ace = rawAcl[index];
                        rawAcl.RemoveAce(index);
                });
            }
        }