Exemplo n.º 1
0
            private static byte[] GetBytes(System.Security.Principal.SecurityIdentifier si)
            {
                var b = new byte[si.BinaryLength];

                si.GetBinaryForm(b, 0);
                return(b);
            }
 public void SecurityIdentifierExtensions_GetBinaryForm_Test1()
 {
     SecurityIdentifier sid = new SecurityIdentifier("S-1-5-21-3180365339-800773672-3767752645-500");
     byte[] binary = sid.GetBinaryForm();
     SecurityIdentifier sid2 = new SecurityIdentifier(binary, 0);
     Assert.AreEqual(sid, sid2);
 }
Exemplo n.º 3
0
		private void CheckStringCtor (string strValue, byte[] expectedBinary)
		{
			SecurityIdentifier sid = new SecurityIdentifier (strValue);
			byte[] buffer = new byte[sid.BinaryLength];
			sid.GetBinaryForm (buffer, 0);
			
			Assert.AreEqual (expectedBinary.Length, buffer.Length, "SID length mismatch");
			Assert.AreEqual (expectedBinary, buffer, "SIDs different in binary form");
		}
Exemplo n.º 4
0
		public static bool ConvertStringSidToSid (string StringSid, out IntPtr ptrSid)
		{
			unsafe {
				var ident = new SecurityIdentifier (StringSid);
				byte[] pSID = new byte[ident.BinaryLength];
				ident.GetBinaryForm (pSID, 0);
				ptrSid = GCHandle.ToIntPtr (GCHandle.Alloc (pSID));
			}
			return true;
		}
Exemplo n.º 5
0
 // use this for binding string...
 internal static string SecurityIdentifierToLdapHexBindingString(SecurityIdentifier sid)
 {
     byte[] sidB = new byte[sid.BinaryLength];
     sid.GetBinaryForm(sidB, 0);
     StringBuilder stringizedBinarySid = new StringBuilder();
     foreach (byte b in sidB)
     {
         stringizedBinarySid.Append(b.ToString("x2", CultureInfo.InvariantCulture));
     }
     return stringizedBinarySid.ToString();
 }
 //work around way to create a new userProxyFull object
 public static void CreateProxy(string server, string path, string name, SecurityIdentifier sid)
 {
     var sidInBytes = new byte[sid.BinaryLength];
     sid.GetBinaryForm(sidInBytes, 0);
     var ouDE = new DirectoryEntry(string.Format("LDAP://{0}/{1}", server, path));
     var proxyDE = ouDE.Children.Add(String.Format("CN={0}", name), "userProxyFull");
     proxyDE.Properties["objectSid"].Clear();
     proxyDE.Properties["objectSid"].Value = sidInBytes;
     proxyDE.Properties["userPrincipalName"].Value = name;
     proxyDE.CommitChanges();
 }
 //work around way to create a new userProxyFull object
 public static UserProxyFullPrincipal CreateProxy(PrincipalContext context, string name, SecurityIdentifier sid)
 {
     var sidInBytes = new byte[sid.BinaryLength];
     sid.GetBinaryForm(sidInBytes, 0);
     var ouDE = new DirectoryEntry(string.Format("LDAP://{0}/{1}", context.ConnectedServer, context.Container));
     var proxyDE = ouDE.Children.Add(String.Format("CN={0}", name), "userProxyFull");
     proxyDE.Properties["objectSid"].Clear();
     proxyDE.Properties["objectSid"].Value = sidInBytes;
     proxyDE.Properties["userPrincipalName"].Value = name;
     proxyDE.CommitChanges();
     return FindByIdentity(context, name);
 }
Exemplo n.º 8
0
        private static object[] CommonAce_CreateTestData(int intFlags, int intQualifier, int accessMask, string stringsid, bool isCallback, int opaqueLength, int offset)
        {
            AceFlags flags = (AceFlags)intFlags;
            AceQualifier qualifier = (AceQualifier)intQualifier;
            SecurityIdentifier sid = new SecurityIdentifier(stringsid);
            byte[] opaque = new byte[opaqueLength];

            CommonAce ace = new CommonAce(flags, qualifier, accessMask, sid, isCallback, opaque);
            Assert.Equal(flags, ace.AceFlags);
            Assert.Equal(accessMask, ace.AccessMask);
            Assert.Equal(sid, ace.SecurityIdentifier);
            Assert.Equal(opaque, ace.GetOpaque());
            Assert.Equal(qualifier, ace.AceQualifier);
            Assert.Equal(isCallback, ace.IsCallback);

            byte[] binaryForm = new byte[ace.BinaryLength + offset];
            switch (qualifier)
            {
                case AceQualifier.AccessAllowed:
                    binaryForm[offset + 0] = isCallback ? (byte)AceType.AccessAllowedCallback : (byte)AceType.AccessAllowed;
                    break;
                case AceQualifier.AccessDenied:
                    binaryForm[offset + 0] = isCallback ? (byte)AceType.AccessDeniedCallback : (byte)AceType.AccessDenied;
                    break;
                case AceQualifier.SystemAudit:
                    binaryForm[offset + 0] = isCallback ? (byte)AceType.SystemAuditCallback : (byte)AceType.SystemAudit;
                    break;
                case AceQualifier.SystemAlarm:
                    binaryForm[offset + 0] = isCallback ? (byte)AceType.SystemAlarmCallback : (byte)AceType.SystemAlarm;
                    break;
                default:
                    return null;
            }
            binaryForm[offset + 1] = (byte)flags;
            binaryForm[offset + 2] = (byte)(ace.BinaryLength >> 0);
            binaryForm[offset + 3] = (byte)(ace.BinaryLength >> 8);

            int baseOffset = offset + 4;
            int offsetLocal = 0;

            binaryForm[baseOffset + 0] = (byte)(accessMask >> 0);
            binaryForm[baseOffset + 1] = (byte)(accessMask >> 8);
            binaryForm[baseOffset + 2] = (byte)(accessMask >> 16);
            binaryForm[baseOffset + 3] = (byte)(accessMask >> 24);
            offsetLocal += 4;

            sid.GetBinaryForm(binaryForm, baseOffset + offsetLocal);
            offsetLocal += sid.BinaryLength;
            opaque.CopyTo(binaryForm, baseOffset + offsetLocal);

            return new object[] { ace, binaryForm, offset };
        }
Exemplo n.º 9
0
 public static string EncodeSidToString(string sid)
 {
     try
     {
         var realsid = new System.Security.Principal.SecurityIdentifier(sid);
         var bytesid = new byte[realsid.BinaryLength];
         realsid.GetBinaryForm(bytesid, 0);
         return("\\" + BitConverter.ToString(bytesid).Replace("-", "\\"));
     }
     catch (ArgumentException)
     {
         Trace.WriteLine("Unable to encode " + sid);
         throw;
     }
 }
Exemplo n.º 10
0
 //creates Everyone,Full, inherit security descriptor
 private ManagementObject SecurityDescriptor()
 {
     SecurityIdentifier sec = new SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null);
     byte[] sidArray = new byte[sec.BinaryLength];
     sec.GetBinaryForm(sidArray, 0);
     ManagementObject Trustee = new ManagementClass(new ManagementPath("Win32_Trustee"), null);
     Trustee["Domain"] = "NT Authority";
     Trustee["Name"] = "Everyone";
     Trustee["SID"] = sidArray;
     ManagementObject ACE = new ManagementClass(new ManagementPath("Win32_Ace"), null);
     ACE["AccessMask"] = 2032127; // 0x1f01ff Full Access
     ACE["AceFlags"] = 3;    //Non-container and container child objects to inherit ace
     ACE["AceType"] = 0;     //defines access allowed (1 would be defining access denied
     ACE["Trustee"] = Trustee;
     ManagementObject SecDesc = new ManagementClass(new ManagementPath("Win32_SecurityDescriptor"), null);
     SecDesc["ControlFlags"] = 4;        //SE_DACL_present
     SecDesc["DACL"] = new object[] { ACE };
     return SecDesc;
 }
Exemplo n.º 11
0
        public static bool CreateUncShare(string shareName, string localPath)
        {
            ManagementScope scope = new System.Management.ManagementScope(@"root\CIMV2");
              scope.Connect();

              using (ManagementClass managementClass = new ManagementClass(scope, new ManagementPath("Win32_Share"), (ObjectGetOptions) null))
              {
            SecurityIdentifier securityIdentifier = new SecurityIdentifier(WellKnownSidType.WorldSid, (SecurityIdentifier) null);
            byte[] binaryForm = new byte[securityIdentifier.BinaryLength];
            securityIdentifier.GetBinaryForm(binaryForm, 0);

            using (ManagementObject wmiTrustee = new ManagementClass(scope, new ManagementPath("Win32_Trustee"), (ObjectGetOptions) null).CreateInstance())
            {
              wmiTrustee["SID"] = (object) binaryForm;
              using (ManagementObject wmiACE = new ManagementClass(scope, new ManagementPath("Win32_ACE"), (ObjectGetOptions) null).CreateInstance())
              {
            wmiACE["AccessMask"] = 131241; //READ_CONTROL | FILE_READ | FILE_TRAVERSE | FILE_READ_EA | FILE_LIST_DIRECTORY
            wmiACE["AceFlags"] = 3;        //OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE
            wmiACE["AceType"] = 0; //ACCESS_ALLOWED
            wmiACE["Trustee"] = wmiTrustee;
            using (ManagementObject wmiSecurityDescriptor = new ManagementClass(scope, new ManagementPath("Win32_SecurityDescriptor"), (ObjectGetOptions) null).CreateInstance())
            {
              wmiSecurityDescriptor["ControlFlags"] = 4;
              wmiSecurityDescriptor["DACL"] = new ManagementObject[] { wmiACE };
              using (ManagementBaseObject inParamsCreate = managementClass.GetMethodParameters("Create"))
              {
                inParamsCreate["Access"] = wmiSecurityDescriptor;
                inParamsCreate["Path"] = localPath;
                inParamsCreate["Name"] = shareName;
                inParamsCreate["Type"] = 0;
                inParamsCreate["Description"] = "TVServerXBMC share";
                using (ManagementBaseObject outParams = managementClass.InvokeMethod("Create", inParamsCreate, (InvokeMethodOptions) null))
                  return ((int) (uint) outParams["returnValue"] == 0);
              }
            }
              }
            }
              }
        }
Exemplo n.º 12
0
        //
        // Wrapper around advapi32.IsWellKnownSid
        //


        internal static bool IsWellKnownSid(
            SecurityIdentifier sid,
            WellKnownSidType type
            )
        {
            byte[] BinaryForm = new byte[sid.BinaryLength];
            sid.GetBinaryForm(BinaryForm, 0);

            if (FALSE == Interop.mincore.IsWellKnownSid(BinaryForm, (int)type))
            {
                return false;
            }
            else
            {
                return true;
            }
        }
Exemplo n.º 13
0
        //
        // Wrapper around avdapi32.GetWindowsAccountDomainSid
        //
        internal static int GetWindowsAccountDomainSid(
            SecurityIdentifier sid,
            out SecurityIdentifier resultSid
            )
        {
            //
            // Passing an array as big as it can ever be is a small price to pay for
            // not having to P/Invoke twice (once to get the buffer, once to get the data)
            //

            byte[] BinaryForm = new Byte[sid.BinaryLength];
            sid.GetBinaryForm(BinaryForm, 0);
            uint sidLength = (uint)SecurityIdentifier.MaxBinaryLength;
            byte[] resultSidBinary = new byte[sidLength];

            if (FALSE != Interop.mincore.GetWindowsAccountDomainSid(BinaryForm, resultSidBinary, ref sidLength))
            {
                resultSid = new SecurityIdentifier(resultSidBinary, 0);

                return Interop.mincore.Errors.ERROR_SUCCESS;
            }
            else
            {
                resultSid = null;

                return Marshal.GetLastWin32Error();
            }
        }
Exemplo n.º 14
0
        //
        // Wrapper around advapi32.EqualDomainSid
        //


        internal static bool IsEqualDomainSid(SecurityIdentifier sid1, SecurityIdentifier sid2)
        {
            if (sid1 == null || sid2 == null)
            {
                return false;
            }
            else
            {
                bool result;

                byte[] BinaryForm1 = new Byte[sid1.BinaryLength];
                sid1.GetBinaryForm(BinaryForm1, 0);

                byte[] BinaryForm2 = new Byte[sid2.BinaryLength];
                sid2.GetBinaryForm(BinaryForm2, 0);

                return (Interop.mincore.IsEqualDomainSid(BinaryForm1, BinaryForm2, out result) == FALSE ? false : result);
            }
        }
        internal unsafe bool TemplateT_SID(
            ref EventDescriptor eventDescriptor,
            SecurityIdentifier Prop_SID
            )
        {
            int argumentCount = 1;
            bool status = true;

            if (IsEnabled(eventDescriptor.Level, eventDescriptor.Keywords))
            {
                byte* userData = stackalloc byte[sizeof(EventData) * argumentCount];
                EventData* userDataPtr = (EventData*)userData;

                byte [] Prop_SIDBin = new byte[Prop_SID.BinaryLength];
                Prop_SID.GetBinaryForm(Prop_SIDBin, 0);
                userDataPtr[0].Size = (uint)(Prop_SID.BinaryLength);

                fixed (byte* a0 = Prop_SIDBin)
                {
                    userDataPtr[0].DataPointer = (ulong)a0;
                    status = WriteEvent(ref eventDescriptor, argumentCount, (IntPtr)(userData));
                }
            }

            return status;
        }
Exemplo n.º 16
0
        private static object[] ObjectAce_CreateTestData(int intFlags, int intQualifier, int accessMask, string stringsid, int intObjectAceFlags, string stringType, string stringInheritedType, bool isCallback, int opaqueLength, int offset)
        {
            AceFlags aceFlags = (AceFlags)intFlags;
            AceQualifier qualifier = (AceQualifier)intQualifier;
            SecurityIdentifier sid = new SecurityIdentifier(stringsid);
            ObjectAceFlags flags = (ObjectAceFlags)intObjectAceFlags;
            Guid type = new Guid(stringType);
            Guid inheritedType = new Guid(stringInheritedType);
            byte[] opaque = new byte[opaqueLength];

            ObjectAce ace = new ObjectAce(aceFlags, qualifier, accessMask, sid, flags, type, inheritedType, isCallback, opaque);
            VerifyObjectAce(ace, aceFlags, qualifier, accessMask, sid, flags, type, inheritedType, isCallback, opaque);

            byte[] binaryForm = new byte[ace.BinaryLength + offset];
            switch (qualifier)
            {
                case AceQualifier.AccessAllowed:
                    binaryForm[offset + 0] = isCallback ? (byte)AceType.AccessAllowedCallbackObject : (byte)AceType.AccessAllowedObject;
                    break;
                case AceQualifier.AccessDenied:
                    binaryForm[offset + 0] = isCallback ? (byte)AceType.AccessDeniedCallbackObject : (byte)AceType.AccessDeniedObject;
                    break;
                case AceQualifier.SystemAudit:
                    binaryForm[offset + 0] = isCallback ? (byte)AceType.SystemAuditCallbackObject : (byte)AceType.SystemAuditObject;
                    break;
                case AceQualifier.SystemAlarm:
                    binaryForm[offset + 0] = isCallback ? (byte)AceType.SystemAlarmCallbackObject : (byte)AceType.SystemAlarmObject;
                    break;
                default:
                    return null;
            }
            binaryForm[offset + 1] = (byte)aceFlags;
            binaryForm[offset + 2] = (byte)(ace.BinaryLength >> 0);
            binaryForm[offset + 3] = (byte)(ace.BinaryLength >> 8);

            int baseOffset = offset + 4;
            int offsetLocal = 0;

            binaryForm[baseOffset + 0] = (byte)(accessMask >> 0);
            binaryForm[baseOffset + 1] = (byte)(accessMask >> 8);
            binaryForm[baseOffset + 2] = (byte)(accessMask >> 16);
            binaryForm[baseOffset + 3] = (byte)(accessMask >> 24);
            offsetLocal += 4;

            binaryForm[baseOffset + offsetLocal + 0] = (byte)(((uint)flags) >> 0);
            binaryForm[baseOffset + offsetLocal + 1] = (byte)(((uint)flags) >> 8);
            binaryForm[baseOffset + offsetLocal + 2] = (byte)(((uint)flags) >> 16);
            binaryForm[baseOffset + offsetLocal + 3] = (byte)(((uint)flags) >> 24);

            offsetLocal += 4;

            if ((flags & ObjectAceFlags.ObjectAceTypePresent) != 0)
            {
                type.ToByteArray().CopyTo(binaryForm, baseOffset + offsetLocal);
                offsetLocal += 16;
            }

            if ((flags & ObjectAceFlags.InheritedObjectAceTypePresent) != 0)
            {
                inheritedType.ToByteArray().CopyTo(binaryForm, baseOffset + offsetLocal);
                offsetLocal += 16;
            }

            sid.GetBinaryForm(binaryForm, baseOffset + offsetLocal);
            offsetLocal += sid.BinaryLength;
            opaque.CopyTo(binaryForm, baseOffset + offsetLocal);

            return new object[] { ace, binaryForm, offset };
        }
 internal static bool IsWellKnownSid(SecurityIdentifier sid, WellKnownSidType type)
 {
     if (!WellKnownSidApisSupported)
     {
         throw new PlatformNotSupportedException(Environment.GetResourceString("PlatformNotSupported_RequiresW2kSP3"));
     }
     byte[] binaryForm = new byte[sid.BinaryLength];
     sid.GetBinaryForm(binaryForm, 0);
     if (Win32Native.IsWellKnownSid(binaryForm, (int) type) == 0)
     {
         return false;
     }
     return true;
 }
Exemplo n.º 18
0
        public ActiveDirectoryMembershipUser(string providerName,
                              string              name,
                              object             providerUserKey,
                              string              email,
                              string              passwordQuestion,
                              string              comment,
                              bool                isApproved,
                              bool                isLockedOut,
                              DateTime            creationDate,
                              DateTime            lastLoginDate,
                              DateTime            lastActivityDate,
                              DateTime            lastPasswordChangedDate,
                              DateTime            lastLockoutDate) 
            :base(providerName, 
                        name, 
                        null, 
                        email, 
                        passwordQuestion, 
                        comment, 
                        isApproved, 
                        isLockedOut,
                        creationDate, 
                        lastLoginDate, 
                        lastActivityDate,
                        lastPasswordChangedDate,
                        lastLockoutDate)  
        {
            if ((providerUserKey != null) && !(providerUserKey is SecurityIdentifier))
                throw new ArgumentException( SR.GetString(SR.ADMembership_InvalidProviderUserKey) , "providerUserKey" );

            sid = (SecurityIdentifier) providerUserKey;
            if (sid != null) 
            {
                // 
                // store the sid in binary form for serialization
                //
                sidBinaryForm = new byte[sid.BinaryLength];
                sid.GetBinaryForm(sidBinaryForm, 0);
            }
        }
 internal static int GetWindowsAccountDomainSid(SecurityIdentifier sid, out SecurityIdentifier resultSid)
 {
     if (!WellKnownSidApisSupported)
     {
         throw new PlatformNotSupportedException(Environment.GetResourceString("PlatformNotSupported_RequiresW2kSP3"));
     }
     byte[] binaryForm = new byte[sid.BinaryLength];
     sid.GetBinaryForm(binaryForm, 0);
     uint maxBinaryLength = (uint) SecurityIdentifier.MaxBinaryLength;
     byte[] buffer2 = new byte[maxBinaryLength];
     if (Win32Native.GetWindowsAccountDomainSid(binaryForm, buffer2, ref maxBinaryLength) != 0)
     {
         resultSid = new SecurityIdentifier(buffer2, 0);
         return 0;
     }
     resultSid = null;
     return Marshal.GetLastWin32Error();
 }
Exemplo n.º 20
0
        public static bool CreateUncShare(string shareName, string localPath)
        {
            ManagementScope scope = new System.Management.ManagementScope(@"root\CIMV2");
            scope.Connect();

            using (ManagementClass wmiShare = new ManagementClass(scope, new ManagementPath("Win32_Share"), null))
            {
                SecurityIdentifier worldSid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
                byte[] worldSidBytes = new byte[worldSid.BinaryLength];
                worldSid.GetBinaryForm(worldSidBytes, 0);

                using (ManagementObject wmiTrustee =
                    new ManagementClass(scope, new ManagementPath("Win32_Trustee"), null).CreateInstance())
                {
                    wmiTrustee["SID"] = worldSidBytes;

                    using (ManagementObject wmiAce =
                        new ManagementClass(scope, new ManagementPath("Win32_ACE"), null).CreateInstance())
                    {
                        wmiAce["AccessMask"] = 0x0200A9; // 0x1F01FF;
                        wmiAce["AceFlags"] = 3;
                        wmiAce["AceType"] = 0;
                        wmiAce["Trustee"] = wmiTrustee;

                        using (ManagementObject secDescriptor =
                            new ManagementClass(scope, new ManagementPath("Win32_SecurityDescriptor"), null).CreateInstance())
                        {
                            secDescriptor["ControlFlags"] = 4;
                            secDescriptor["DACL"] = new ManagementObject[] { wmiAce };

                            using (ManagementBaseObject inParams = wmiShare.GetMethodParameters("Create"))
                            {
                                inParams["Access"] = secDescriptor;
                                inParams["Path"] = localPath;
                                inParams["Name"] = shareName;
                                inParams["Type"] = 0;
                                inParams["Description"] = "ARGUS TV Recordings";

                                using (ManagementBaseObject outParams = wmiShare.InvokeMethod("Create", inParams, null))
                                {
                                    return ((uint)outParams["ReturnValue"] == 0);
                                }
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 21
0
		public void ConstructorBinary ()
		{
			byte[] inForm = new byte[] {
				0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x4E, 0x01,
				0x00, 0x00, 0xEA, 0x00, 0x00, 0x00 };
			SecurityIdentifier sid = new SecurityIdentifier (inForm, 0);
			
			byte[] outForm = new byte[inForm.Length];
			sid.GetBinaryForm (outForm, 0);
			Assert.AreEqual (inForm, outForm);
		}
Exemplo n.º 22
0
		public unsafe void IntPtrRoundtrip ()
		{
			SecurityIdentifier sidIn, sidOut;
			byte[] binaryFormIn, binaryFormOut;

			sidIn = new SecurityIdentifier ("WD");
			binaryFormIn = new byte[sidIn.BinaryLength];
			sidIn.GetBinaryForm (binaryFormIn, 0);

			fixed (byte* pointerForm = binaryFormIn)
				sidOut = new SecurityIdentifier ((IntPtr)pointerForm);
			binaryFormOut = new byte[sidOut.BinaryLength];
			sidOut.GetBinaryForm (binaryFormOut, 0);

			Assert.AreEqual (sidIn, sidOut);
			Assert.AreEqual (binaryFormIn, binaryFormOut);
		}
Exemplo n.º 23
0
        [System.Security.SecurityCritical]  // auto-generated
        internal static int GetWindowsAccountDomainSid(
            SecurityIdentifier sid, 
            out SecurityIdentifier resultSid
            ) 
        { 

            // 
            // Check if the api is supported
            //
            if (!WellKnownSidApisSupported) {
                throw new PlatformNotSupportedException( Environment.GetResourceString( "PlatformNotSupported_RequiresW2kSP3" )); 
            }
 
            // 
            // Passing an array as big as it can ever be is a small price to pay for
            // not having to P/Invoke twice (once to get the buffer, once to get the data) 
            //

            byte[] BinaryForm = new Byte[sid.BinaryLength];
            sid.GetBinaryForm( BinaryForm, 0 ); 
            uint sidLength = ( uint )SecurityIdentifier.MaxBinaryLength;
            byte[] resultSidBinary = new byte[ sidLength ]; 
 
            if ( FALSE != Win32Native.GetWindowsAccountDomainSid( BinaryForm, resultSidBinary, ref sidLength ))
            { 
                resultSid = new SecurityIdentifier( resultSidBinary, 0 );

                return Win32Native.ERROR_SUCCESS;
            } 
            else
            { 
                resultSid = null; 

                return Marshal.GetLastWin32Error(); 
            }
        }
Exemplo n.º 24
0
		internal static string SecurityIdentifierToLdapHexBindingString(SecurityIdentifier sid)
		{
			byte[] numArray = new byte[sid.BinaryLength];
			sid.GetBinaryForm(numArray, 0);
			StringBuilder stringBuilder = new StringBuilder();
			byte[] numArray1 = numArray;
			for (int i = 0; i < (int)numArray1.Length; i++)
			{
				byte num = numArray1[i];
				stringBuilder.Append(num.ToString("x2", CultureInfo.InvariantCulture));
			}
			return stringBuilder.ToString();
		}
Exemplo n.º 25
0
        internal static int SetSecurityInfo(
					ResourceType type,
					string name,
					SafeHandle handle,
					SecurityInfos securityInformation,
					SecurityIdentifier owner,
					SecurityIdentifier group,
					GenericAcl sacl,
					GenericAcl dacl)
        {
            int errorCode;
            int Length;
            byte[] OwnerBinary = null, GroupBinary = null, SaclBinary = null, DaclBinary = null;
            Privilege securityPrivilege = null;

            //
            // Demand unmanaged code permission
            // The integrator layer is free to assert this permission
            // and, in turn, demand another permission of its caller
            //

            new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();

            if (owner != null)
            {
                Length = owner.BinaryLength;
                OwnerBinary = new byte[Length];
                owner.GetBinaryForm(OwnerBinary, 0);
            }

            if (@group != null)
            {
                Length = @group.BinaryLength;
                GroupBinary = new byte[Length];
                @group.GetBinaryForm(GroupBinary, 0);
            }

            if (dacl != null)
            {
                Length = dacl.BinaryLength;
                DaclBinary = new byte[Length];
                dacl.GetBinaryForm(DaclBinary, 0);
            }

            if (sacl != null)
            {
                Length = sacl.BinaryLength;
                SaclBinary = new byte[Length];
                sacl.GetBinaryForm(SaclBinary, 0);
            }

            if ((securityInformation & SecurityInfos.SystemAcl) != 0)
            {
                //
                // Enable security privilege if trying to set a SACL.
                // Note: even setting it by handle needs this privilege enabled!
                //

                securityPrivilege = new Privilege(Privilege.Security);
            }

            // Ensure that the finally block will execute
            RuntimeHelpers.PrepareConstrainedRegions();

            try
            {
                if (securityPrivilege != null)
                {
                    try
                    {
                        securityPrivilege.Enable();
                    }
                    catch (PrivilegeNotHeldException)
                    {
                        // we will ignore this exception and press on just in case this is a remote resource
                    }
                }

                if (name != null)
                {
                    errorCode = (int)NativeMethods.SetSecurityInfoByName(name, (uint)type, (uint)securityInformation, OwnerBinary, GroupBinary, DaclBinary, SaclBinary);
                }
                else if (handle != null)
                {
                    if (handle.IsInvalid)
                    {
                        throw new ArgumentException("Invalid safe handle");
                    }
                    else
                    {
                        errorCode = (int)NativeMethods.SetSecurityInfoByHandle(handle, (uint)type, (uint)securityInformation, OwnerBinary, GroupBinary, DaclBinary, SaclBinary);
                    }
                }
                else
                {
                    // both are null, shouldn't happen
                    throw new InvalidProgramException();
                }

                if (errorCode == NativeMethods.ERROR_NOT_ALL_ASSIGNED ||
                    errorCode == NativeMethods.ERROR_PRIVILEGE_NOT_HELD)
                {
                    throw new PrivilegeNotHeldException(Privilege.Security);
                }
                else if (errorCode == NativeMethods.ERROR_ACCESS_DENIED ||
                    errorCode == NativeMethods.ERROR_CANT_OPEN_ANONYMOUS)
                {
                    throw new UnauthorizedAccessException();
                }
                else if (errorCode != NativeMethods.ERROR_SUCCESS)
                {
                    goto Error;
                }
            }
            catch
            {
                // protection against exception filter-based luring attacks
                if (securityPrivilege != null)
                {
                    securityPrivilege.Revert();
                }
                throw;
            }
            finally
            {
                if (securityPrivilege != null)
                {
                    securityPrivilege.Revert();
                }
            }

            return 0;

            Error:

            if (errorCode == NativeMethods.ERROR_NOT_ENOUGH_MEMORY)
            {
                throw new OutOfMemoryException();
            }

            return errorCode;
        }
 internal static bool IsEqualDomainSid(SecurityIdentifier sid1, SecurityIdentifier sid2)
 {
     bool flag;
     if (!WellKnownSidApisSupported)
     {
         throw new PlatformNotSupportedException(Environment.GetResourceString("PlatformNotSupported_RequiresW2kSP3"));
     }
     if ((sid1 == null) || (sid2 == null))
     {
         return false;
     }
     byte[] binaryForm = new byte[sid1.BinaryLength];
     sid1.GetBinaryForm(binaryForm, 0);
     byte[] buffer2 = new byte[sid2.BinaryLength];
     sid2.GetBinaryForm(buffer2, 0);
     return ((Win32Native.IsEqualDomainSid(binaryForm, buffer2, out flag) != 0) && flag);
 }
Exemplo n.º 27
0
        [System.Security.SecurityCritical]  // auto-generated
        internal static bool IsEqualDomainSid( SecurityIdentifier sid1, SecurityIdentifier sid2 ) 
        {
            //
            // Check if the api is supported
            // 
            if (!WellKnownSidApisSupported) {
                throw new PlatformNotSupportedException( Environment.GetResourceString( "PlatformNotSupported_RequiresW2kSP3" )); 
            } 

            if ( sid1 == null || sid2 == null ) 
            {
                return false;
            }
            else 
            {
                bool result; 
 
                byte[] BinaryForm1 = new Byte[sid1.BinaryLength];
                sid1.GetBinaryForm( BinaryForm1, 0 ); 

                byte[] BinaryForm2 = new Byte[sid2.BinaryLength];
                sid2.GetBinaryForm( BinaryForm2, 0 );
 
                return ( Win32Native.IsEqualDomainSid( BinaryForm1, BinaryForm2, out result ) == FALSE ? false : result );
            } 
        } 
 public void SecurityIdentifierExtensions_GetBinaryForm_Test3()
 {
     SecurityIdentifier sid1 = new SecurityIdentifier("S-1-5-21-3180365339-800773672-3767752645-1234");
     SecurityIdentifier sid2 = sid1.GetBinaryForm(false).ToSecurityIdentifier(false);
     Assert.AreEqual(sid1, sid2);
 }
Exemplo n.º 29
0
        [System.Security.SecurityCritical]  // auto-generated
        internal static bool IsWellKnownSid( 
            SecurityIdentifier sid,
            WellKnownSidType type
            )
        { 
            //
            // Check if the api is supported 
            // 
            if (!WellKnownSidApisSupported) {
                throw new PlatformNotSupportedException( Environment.GetResourceString( "PlatformNotSupported_RequiresW2kSP3" )); 
            }

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

            if ( FALSE == Win32Native.IsWellKnownSid( BinaryForm, ( int )type )) 
            { 
                return false;
            } 
            else
            {
                return true;
            } 
        }
 static void SerializeSid(SecurityIdentifier sid, SctClaimDictionary dictionary, XmlDictionaryWriter writer)
 {
     byte[] sidBytes = new byte[sid.BinaryLength];
     sid.GetBinaryForm(sidBytes, 0);
     writer.WriteBase64(sidBytes, 0, sidBytes.Length);
 }
Exemplo n.º 31
0
        //
        // Wrapper around advapi32.SetNamedSecurityInfoW and advapi32.SetSecurityInfo
        //

        internal static int SetSecurityInfo(
            ResourceType type,
            string name,
            SafeHandle handle,
            SecurityInfos securityInformation,
            SecurityIdentifier owner,
            SecurityIdentifier group,
            GenericAcl sacl,
            GenericAcl dacl)
        {
            int errorCode;
            int Length;
            byte[] OwnerBinary = null, GroupBinary = null, SaclBinary = null, DaclBinary = null;
            Privilege securityPrivilege = null;

            if (owner != null)
            {
                Length = owner.BinaryLength;
                OwnerBinary = new byte[Length];
                owner.GetBinaryForm(OwnerBinary, 0);
            }

            if (group != null)
            {
                Length = group.BinaryLength;
                GroupBinary = new byte[Length];
                group.GetBinaryForm(GroupBinary, 0);
            }

            if (dacl != null)
            {
                Length = dacl.BinaryLength;
                DaclBinary = new byte[Length];
                dacl.GetBinaryForm(DaclBinary, 0);
            }

            if (sacl != null)
            {
                Length = sacl.BinaryLength;
                SaclBinary = new byte[Length];
                sacl.GetBinaryForm(SaclBinary, 0);
            }

            if ((securityInformation & SecurityInfos.SystemAcl) != 0)
            {
                //
                // Enable security privilege if trying to set a SACL. 
                // Note: even setting it by handle needs this privilege enabled!
                //

                securityPrivilege = new Privilege(Privilege.Security);
            }

            try
            {
                if (securityPrivilege != null)
                {
                    try
                    {
                        securityPrivilege.Enable();
                    }
                    catch (PrivilegeNotHeldException)
                    {
                        // we will ignore this exception and press on just in case this is a remote resource
                    }
                }

                if (name != null)
                {
                    errorCode = (int)Interop.mincore.SetSecurityInfoByName(name, (uint)type, (uint)securityInformation, OwnerBinary, GroupBinary, DaclBinary, SaclBinary);
                }
                else if (handle != null)
                {
                    if (handle.IsInvalid)
                    {
                        throw new ArgumentException(
                            SR.Argument_InvalidSafeHandle,
nameof(handle));
                    }
                    else
                    {
                        errorCode = (int)Interop.mincore.SetSecurityInfoByHandle(handle, (uint)type, (uint)securityInformation, OwnerBinary, GroupBinary, DaclBinary, SaclBinary);
                    }
                }
                else
                {
                    // both are null, shouldn't happen
                    Contract.Assert(false, "Internal error: both name and handle are null");
                    throw new ArgumentException();
                }

                if (errorCode == Interop.mincore.Errors.ERROR_NOT_ALL_ASSIGNED ||
                    errorCode == Interop.mincore.Errors.ERROR_PRIVILEGE_NOT_HELD)
                {
                    throw new PrivilegeNotHeldException(Privilege.Security);
                }
                else if (errorCode == Interop.mincore.Errors.ERROR_ACCESS_DENIED ||
                    errorCode == Interop.mincore.Errors.ERROR_CANT_OPEN_ANONYMOUS)
                {
                    throw new UnauthorizedAccessException();
                }
                else if (errorCode != Interop.mincore.Errors.ERROR_SUCCESS)
                {
                    goto Error;
                }
            }
            catch
            {
                // protection against exception filter-based luring attacks
                if (securityPrivilege != null)
                {
                    securityPrivilege.Revert();
                }
                throw;
            }
            finally
            {
                if (securityPrivilege != null)
                {
                    securityPrivilege.Revert();
                }
            }

            return 0;

        Error:

            if (errorCode == Interop.mincore.Errors.ERROR_NOT_ENOUGH_MEMORY)
            {
                throw new OutOfMemoryException();
            }

            return errorCode;
        }
 static void WriteSidAttribute(SecurityIdentifier sid, SctClaimDictionary dictionary, XmlDictionaryWriter writer)
 {
     byte[] sidBytes = new byte[sid.BinaryLength];
     sid.GetBinaryForm(sidBytes, 0);
     writer.WriteAttributeString(dictionary.Sid, dictionary.EmptyString, Convert.ToBase64String(sidBytes));
 }