public static string verifyNTuser(string userName)
        {
            DirectoryEntry dEntry = new DirectoryEntry("LDAP://ds.kycourts.net/CN=Users,DC=ds,DC=kycourts,DC=net");

            DirectorySearcher dSearch = new DirectorySearcher(dEntry);
            dSearch.PageSize = 6000;
            dSearch.Filter = "cn="+userName;
            dSearch.PropertiesToLoad.Add("cn");
            dSearch.PropertiesToLoad.Add("mail");
            dSearch.PropertiesToLoad.Add("objectSid");
            dSearch.CacheResults = true;
            if (dSearch.FindAll().Count > 0)
            {
                foreach (SearchResult sResultSet in dSearch.FindAll())
                {
                    SecurityIdentifier sid = new SecurityIdentifier((byte[])sResultSet.Properties["objectSid"][0], 0);
                    string[] namesid = sid.ToString().Split('-');
                    dEntry.Close();
                    return sResultSet.Properties["cn"][0].ToString() + ";" + sResultSet.Properties["mail"][0].ToString() + ";" +
                        namesid[namesid.Length - 1].ToString();

                }

            }
            else
            {
                dEntry.Close();
                return "false";
            }

            return "false";
        }
        public static string GetSingleStringPropertyCollectionValue(ResultPropertyCollection props, string name)
        {
            try
            {
                if (!props.Contains(name))
                {
                    return string.Empty;
                }
                ResultPropertyValueCollection pvc = props[name];
                if (pvc == null || pvc.Count == 0)
                {
                    return string.Empty;
                }
                if (string.Compare(name, Constants.Properties.AdProperties.ObjectSID) == 0)
                {
                    byte[] sidInBytes = (byte[])pvc[0];
                    SecurityIdentifier sid = new SecurityIdentifier(sidInBytes, 0);
                    return Convert.ToString(sid);
                }
                else
                {
                    return Convert.ToString(pvc[0]);

                }
            }
            catch (Exception ex)
            {
                throw new ApplicationException(string.Format("Failed to retrieve property '{0}' from ResultPropertyCollection.", name), ex);
            }
        }
        public static ActiveDirectoryRole CreateFromSecurityIdentifier(SecurityIdentifier sid)
        {
            if (sid == null)
                throw new ArgumentNullException("sid");

            ActiveDirectoryRole role = new ActiveDirectoryRole(GetRootEntry(), new DirectoryRootQuery("objectSID", sid.ToString(), DirectoryQueryOperation.Equal));
            role.Operations.Add(s_directoryGroupQuery);
            ValidateRole(role);
            return role;
        }
Example #4
0
		internal static bool AreSidsInSameDomain(SecurityIdentifier sid1, SecurityIdentifier sid2)
		{
			if (!sid1.IsAccountSid() || !sid2.IsAccountSid())
			{
				return false;
			}
			else
			{
				return sid1.AccountDomainSid.Equals(sid2.AccountDomainSid);
			}
		}
Example #5
0
        public static string CreateAdGroup(string name, string adPath)
        {
            string grpSid = String.Empty;

            using (WindowsImpersonationContextFacade impersonationContext
              = new WindowsImpersonationContextFacade(
                  nc))
            {
                //DirectoryEntry directoryEntry = new DirectoryEntry(DomainPath);
                //DirectoryEntry ou = directoryEntry.Children.Find(adPath);
                //DirectoryEntry group = ou.Children.Add($"CN={name}", "group");
                //group.Properties["samAccountName"].Value = name;
                //group.CommitChanges();

                bool groupIsExist = false;
                DirectoryEntry directoryEntry = new DirectoryEntry(DomainPath);

                using (directoryEntry)
                {
                    //Если пользователь существует
                    DirectorySearcher search = new DirectorySearcher(directoryEntry);
                    search.Filter = String.Format("(&(objectClass=user)(sAMAccountName={0}))", name);
                    SearchResult resultGroup = search.FindOne();
                    groupIsExist = resultGroup != null && resultGroup.Properties.Contains("sAMAccountName");

                    if (!groupIsExist)
                    {

                        DirectoryEntry ou = directoryEntry.Children.Find(adPath);
                        DirectoryEntry group = ou.Children.Add($"CN={name}", "group");
                        group.Properties["samAccountName"].Value = name;
                        group.CommitChanges();
                        SecurityIdentifier sid = new SecurityIdentifier((byte[])group.Properties["objectsid"][0],
                            0);
                        grpSid = sid.Value;
                    }
                    else
                    {
                        SecurityIdentifier sid = new SecurityIdentifier((byte[])resultGroup.Properties["objectsid"][0],
                            0);
                        grpSid = sid.Value;
                    }
                }
            }

            return grpSid;
        }
        public static string FindGroup(SecurityIdentifier searchSid)
        {
            using(var ad = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer"))
            {
                ad.Children.SchemaFilter.Add("group");
                foreach(DirectoryEntry dChildEntry in ad.Children)
                {
                    var bytes = (byte[])dChildEntry.Properties["objectSid"].Value;
                    var sid = new SecurityIdentifier(bytes, 0).ToString();

                    if(sid == searchSid.ToString())
                    {
                        return dChildEntry.Name;
                    }
                }
            }
            throw new Exception("Cannot find group");
        }
Example #7
0
 public static void Configure(NameValueCollection sections)
 {
     LdapFilter = sections["LdapFilter"];
     FolderCreatePath= sections["FolderCreatePath"];
     SearchBase = sections["SearchBase"];
     switch (sections["SearchScope"])
     {
         case "Base":
             SearchScope = SearchScope.Base;
             break;
         case "OneLevel":
             SearchScope = SearchScope.OneLevel;
             break;
         case "Subtree":
             SearchScope = SearchScope.Subtree;
             break;
         default:
             throw new ArgumentOutOfRangeException();
     }
     DirectoryEntry= new DirectoryEntry(SearchBase);
     DomainSid= WindowsIdentity.GetCurrent().User.AccountDomainSid;
 }
Example #8
0
        public static string GetSingleStringPropertyCollectionValue(ResultPropertyCollection props, string name)
        {
            if (!props.Contains(name))
            {
                return string.Empty;
            }
            ResultPropertyValueCollection pvc = props[name];
            if (pvc == null || pvc.Count == 0)
            {
                return string.Empty;
            }
            if (string.Compare(name, Constants.Properties.AdProperties.ObjectSID) == 0)
            {
                byte[] sidInBytes = (byte[])pvc[0];
                SecurityIdentifier sid = new SecurityIdentifier(sidInBytes, 0);
                return Convert.ToString(sid);
            }
            else
            {
                return pvc[0] as string;

            }
        }
 public CompoundAce(AceFlags flags, int accessMask, CompoundAceType compoundAceType, SecurityIdentifier sid);
Example #10
0
 public void Purge(SecurityIdentifier sid)
 {
     RequireCanonicity();
     RemoveAces <KnownAce> (ace => ace.SecurityIdentifier == sid);
 }
 public void PurgeAccessControl(SecurityIdentifier sid);
Example #12
0
        /// <summary>
        /// Get the List of HotFixes installed on the Local Machine.
        /// </summary>
        protected override void BeginProcessing()
        {
            foreach (string computer in ComputerName)
            {
                bool              foundRecord = false;
                StringBuilder     QueryString = new StringBuilder();
                ConnectionOptions conOptions  = ComputerWMIHelper.GetConnectionOptions(AuthenticationLevel.Packet, ImpersonationLevel.Impersonate, this.Credential);
                ManagementScope   scope       = new ManagementScope(ComputerWMIHelper.GetScopeString(computer, ComputerWMIHelper.WMI_Path_CIM), conOptions);
                scope.Connect();
                if (Id != null)
                {
                    QueryString.Append("Select * from Win32_QuickFixEngineering where (");
                    for (int i = 0; i <= Id.Length - 1; i++)
                    {
                        QueryString.Append("HotFixID= '");
                        QueryString.Append(Id[i].ToString().Replace("'", "\\'"));
                        QueryString.Append("'");
                        if (i < Id.Length - 1)
                        {
                            QueryString.Append(" Or ");
                        }
                    }
                    QueryString.Append(")");
                }
                else
                {
                    QueryString.Append("Select * from Win32_QuickFixEngineering");
                    foundRecord = true;
                }
                _searchProcess = new ManagementObjectSearcher(scope, new ObjectQuery(QueryString.ToString()));
                foreach (ManagementObject obj in _searchProcess.Get())
                {
                    if (Description != null)
                    {
                        if (!FilterMatch(obj))
                        {
                            continue;
                        }
                    }
                    else
                    {
                        _inputContainsWildcard = true;
                    }

                    // try to translate the SID to a more friendly username
                    // just stick with the SID if anything goes wrong
                    string installed = (string)obj["InstalledBy"];
                    if (!String.IsNullOrEmpty(installed))
                    {
                        try
                        {
                            SecurityIdentifier secObj = new SecurityIdentifier(installed);
                            obj["InstalledBy"] = secObj.Translate(typeof(NTAccount));;
                        }
                        catch (IdentityNotMappedException) // thrown by SecurityIdentifier.Translate
                        {
                        }
                        catch (SystemException e) // thrown by SecurityIdentifier.constr
                        {
                            CommandsCommon.CheckForSevereException(this, e);
                        }
                        //catch (ArgumentException) // thrown (indirectly) by SecurityIdentifier.constr (on XP only?)
                        //{ catch not needed - this is already caught as SystemException
                        //}
                        //catch (PlatformNotSupportedException) // thrown (indirectly) by SecurityIdentifier.Translate (on Win95 only?)
                        //{ catch not needed - this is already caught as SystemException
                        //}
                        //catch (UnauthorizedAccessException) // thrown (indirectly) by SecurityIdentifier.Translate
                        //{ catch not needed - this is already caught as SystemException
                        //}
                    }

                    WriteObject(obj);
                    foundRecord = true;
                }
                if (!foundRecord && !_inputContainsWildcard)
                {
                    Exception Ex = new ArgumentException(StringUtil.Format(HotFixResources.NoEntriesFound, computer));
                    WriteError(new ErrorRecord(Ex, "GetHotFixNoEntriesFound", ErrorCategory.ObjectNotFound, null));
                }
                if (_searchProcess != null)
                {
                    this.Dispose();
                }
            }
        }//end of BeginProcessing method
Example #13
0
 private CommonSecurityDescriptor(bool isContainer, bool isDS, ControlFlags flags, SecurityIdentifier owner, SecurityIdentifier group, RawAcl systemAcl, RawAcl discretionaryAcl)
     : this(isContainer, isDS, flags, owner, group, systemAcl == null ? null : new SystemAcl(isContainer, isDS, systemAcl), discretionaryAcl == null ? null : new DiscretionaryAcl(isContainer, isDS, discretionaryAcl))
 {
 }
 public ObjectAce(AceFlags aceFlags, AceQualifier qualifier, int accessMask, SecurityIdentifier sid, ObjectAceFlags flags, Guid type, Guid inheritedType, bool isCallback, byte[] opaque);
 public void RemoveAuditSpecific(SecurityIdentifier sid, ObjectAuditRule rule);
Example #16
0
        public void ComparesAgainstStringIgnoringCase()
        {
            var a = new Symbol(SecurityIdentifier.GenerateForex("a", Market.FXCM), "a");

            Assert.AreEqual(0, a.CompareTo("A"));
        }
Example #17
0
        static void Main(string[] args)
        {
            //IPrincipal principal = Thread.CurrentPrincipal;
            //WindowsIdentity id = (WindowsIdentity)principal.Identity;
            //IdentityReferenceCollection clGroups = id.Groups;

            IdentityReferenceCollection clGroups = WindowsIdentity.GetCurrent().Groups;
            string groupName = "";

            foreach (IdentityReference group in clGroups)
            {
                SecurityIdentifier sid = (SecurityIdentifier)group.Translate(typeof(SecurityIdentifier));
                var name = sid.Translate(typeof(NTAccount));
                groupName = Formatter.ParseName(name.ToString());    /// return name of the Windows group
                if (groupName == "admini" || groupName == "radnik" || groupName == "korisnik")
                {
                    break;
                }
            }

            NetTcpBinding binding = new NetTcpBinding();

            //if (!found)
            //{
            //    Console.WriteLine("Klijent nije ni u jednoj od grupa.");
            //    Console.ReadLine();
            //}
            //else
            //{
            string address = "net.tcp://localhost:9999/Operacije";
            int    opcija, opcijaRadnik, opcijaKorisnik, opcijaDM;
            string korisnickoIme, sifra, korisnickoIme1, sifra1 = String.Empty;

            using (KlijentServis proxy = new KlijentServis(binding, new EndpointAddress(new Uri(address))))
            {
                do
                {
                    Console.WriteLine("Prijavite se kao: ");
                    Console.WriteLine("1. Admin");
                    Console.WriteLine("2. Radnik");
                    Console.WriteLine("3. Korisnik");
                    Console.WriteLine("4. Exit");

                    opcija = Convert.ToInt32(Console.ReadLine());

                    switch (opcija)
                    {
                    case 1:
                        Console.Write("Unesite vase korisnicko ime: ");
                        korisnickoIme = Console.ReadLine();
                        Console.Write("Unesite vasu sifru: ");
                        sifra = Console.ReadLine();

                        using (StreamReader sr = new StreamReader(File.Open("C:\\Users\\NanaPC\\Downloads\\EBankaBlok2-master\\EBanka\\Admin.txt", FileMode.Open)))
                        {
                            korisnickoIme1 = sr.ReadLine();
                            sifra1         = sr.ReadLine();
                        }

                        if (korisnickoIme == korisnickoIme1 && sifra == sifra1)
                        {
                            Console.WriteLine("Uspesno logovanje!");
                            do
                            {
                                Console.WriteLine("Izaberite opciju: ");
                                Console.WriteLine("1. Dodajte radnika");
                                Console.WriteLine("2. Promeni radnikove podatke");
                                Console.WriteLine("3. Izbrisi radnika");
                                Console.WriteLine("4. Promeni iznos provizije");
                                Console.WriteLine("5. Exit");

                                opcijaRadnik = Convert.ToInt32(Console.ReadLine());

                                switch (opcijaRadnik)
                                {
                                case 1:
                                    break;

                                case 2:
                                    break;

                                case 3:
                                    break;

                                case 4:
                                    break;

                                case 5:
                                    break;
                                }
                            } while (opcijaRadnik != 5);
                        }
                        else
                        {
                            Console.WriteLine("Neuspesno logovanje!");
                        }
                        break;

                    case 2:
                        Console.WriteLine("Unesite vase korisnicko ime: ");
                        korisnickoIme = Console.ReadLine();
                        Console.WriteLine("Unesite vasu sifru: ");
                        sifra = Console.ReadLine();
                        //CheckPassword i ResetPassword
                        do
                        {
                            Console.WriteLine("Izaberite opciju: ");
                            Console.WriteLine("1. Dodajte korisnika");
                            Console.WriteLine("2. Promeni korisnikove podatke");
                            Console.WriteLine("3. Izbrisi korisnika");
                            Console.WriteLine("4. Dodajte transakciju za korisnika");
                            Console.WriteLine("5. Izmenite korisnikove transakciju");
                            Console.WriteLine("6. Izbrisite korisnikove transakcije");
                            Console.WriteLine("7. Dozvoljeni minusi");
                            Console.WriteLine("8. Exit");

                            opcijaKorisnik = Convert.ToInt32(Console.ReadLine());

                            switch (opcijaKorisnik)
                            {
                            case 1:
                                break;

                            case 2:
                                break;

                            case 3:
                                break;

                            case 4:
                                break;

                            case 5:
                                break;

                            case 6:
                                break;

                            case 7:
                                break;

                            case 8:
                                break;
                            }
                        } while (opcijaKorisnik != 8);
                        break;

                    case 3:
                        Console.WriteLine("Unesite vase korisnicko ime: ");
                        korisnickoIme = Console.ReadLine();
                        Console.WriteLine("Unesite vasu sifru: ");
                        sifra = Console.ReadLine();
                        do
                        {
                            Console.WriteLine("1. Zahtev za dozvoljeni minus");
                            Console.WriteLine("2. Exit");

                            opcijaDM = Convert.ToInt32(Console.ReadLine());

                            switch (opcijaDM)
                            {
                            case 1:
                                break;

                            case 2:
                                break;
                            }
                        } while (opcijaDM != 2);
                        break;

                    case 4:
                        break;
                    }
                } while (opcija != 4);
            }
            //}
            Console.ReadLine();
        }
Example #18
0
        public void CompareToItselfReturnsZero()
        {
            var sym = new Symbol(SecurityIdentifier.GenerateForex("sym", Market.FXCM), "sym");

            Assert.AreEqual(0, sym.CompareTo(sym));
        }
Example #19
0
        public void ComparesAgainstStringWithoutException()
        {
            var a = new Symbol(SecurityIdentifier.GenerateForex("a", Market.FXCM), "a");

            Assert.AreEqual(0, a.CompareTo("a"));
        }
        public void EnumerateAccount(SecurityIdentifier DomainSid, int MaximumNumber = int.MaxValue)
        {
            NativeMethods.UNICODE_STRING        us  = new NativeMethods.UNICODE_STRING();
            NativeMethods.LSA_OBJECT_ATTRIBUTES loa = new NativeMethods.LSA_OBJECT_ATTRIBUTES();
            us.Initialize(Server);
            IntPtr PolicyHandle = IntPtr.Zero;
            int    ret          = NativeMethods.LsaOpenPolicy(ref us, ref loa, 0x00000800, out PolicyHandle);

            if (ret != 0)
            {
                Trace.WriteLine("LsaOpenPolicy 0x" + ret.ToString("x"));
            }
            try
            {
                uint currentRid     = 500;
                int  iteration      = 0;
                int  returnCode     = 0;
                int  UserEnumerated = 0;
                // allows 10*1000 sid non resolved
                int retrycount = 0;
                while ((returnCode == 0 || returnCode == 0x00000107 || (retrycount < 10 && returnCode == -1073741709)) && UserEnumerated < MaximumNumber)
                {
                    Trace.WriteLine("LsaLookupSids iteration " + iteration++);
                    List <GCHandle> HandleToFree = new List <GCHandle>();
                    IntPtr          Names = IntPtr.Zero, ReferencedDomains = IntPtr.Zero;
                    try
                    {
                        SecurityIdentifier[] SidEnumBuffer = new SecurityIdentifier[1000];
                        IntPtr[]             SidHandles    = new IntPtr[SidEnumBuffer.Length];
                        for (int i = 0; i < SidEnumBuffer.Length; i++)
                        {
                            SidEnumBuffer[i] = NullSessionTester.BuildSIDFromDomainSidAndRid(DomainSid, currentRid++);
                            byte[] sid = new byte[SidEnumBuffer[i].BinaryLength];
                            SidEnumBuffer[i].GetBinaryForm(sid, 0);
                            GCHandle handlesid = GCHandle.Alloc(sid, GCHandleType.Pinned);
                            HandleToFree.Add(handlesid);
                            SidHandles[i] = handlesid.AddrOfPinnedObject();
                        }
                        GCHandle sidHandle = GCHandle.Alloc(SidHandles, GCHandleType.Pinned);
                        HandleToFree.Add(sidHandle);

                        returnCode = NativeMethods.LsaLookupSids(PolicyHandle, SidEnumBuffer.Length, sidHandle.AddrOfPinnedObject(), out ReferencedDomains, out Names);
                        if (returnCode == 0 || returnCode == 0x00000107)
                        {
                            retrycount = 0;
                            NativeMethods.LSA_TRANSLATED_NAME[]      lsaNames   = new NativeMethods.LSA_TRANSLATED_NAME[SidEnumBuffer.Length];
                            NativeMethods.LSA_REFERENCED_DOMAIN_LIST domainList = (NativeMethods.LSA_REFERENCED_DOMAIN_LIST)Marshal.PtrToStructure(ReferencedDomains, typeof(NativeMethods.LSA_REFERENCED_DOMAIN_LIST));
                            for (int i = 0; i < SidEnumBuffer.Length; i++)
                            {
                                lsaNames[i] = (NativeMethods.LSA_TRANSLATED_NAME)Marshal.PtrToStructure(
                                    new IntPtr(Names.ToInt64() + i * Marshal.SizeOf(typeof(NativeMethods.LSA_TRANSLATED_NAME)))
                                    , typeof(NativeMethods.LSA_TRANSLATED_NAME));
                                if (lsaNames[i].Use > 0 && lsaNames[i].Use != NativeMethods.SID_NAME_USE.SidTypeUnknown)
                                {
                                    string account = lsaNames[i].Name.ToString();
                                    if (!String.IsNullOrEmpty(account))
                                    {
                                        NativeMethods.LSA_TRUST_INFORMATION trustInfo = (NativeMethods.LSA_TRUST_INFORMATION)Marshal.PtrToStructure
                                                                                            (new IntPtr(domainList.Domains.ToInt64() + lsaNames[i].DomainIndex * Marshal.SizeOf(typeof(NativeMethods.LSA_TRUST_INFORMATION))), typeof(NativeMethods.LSA_TRUST_INFORMATION));
                                        EnumerateCallback(SidEnumBuffer[i], new NTAccount(trustInfo.Name.ToString(), account));
                                    }
                                }
                            }
                        }
                        else
                        {
                            retrycount++;
                            Trace.WriteLine("LsaLookupSids " + returnCode);
                        }
                    }
                    finally
                    {
                        if (ReferencedDomains != IntPtr.Zero)
                        {
                            NativeMethods.LsaFreeMemory(ReferencedDomains);
                        }
                        if (Names != IntPtr.Zero)
                        {
                            NativeMethods.LsaFreeMemory(Names);
                        }
                        foreach (GCHandle handle in HandleToFree)
                        {
                            handle.Free();
                        }
                    }
                }
            }
            finally
            {
                NativeMethods.LsaClose(PolicyHandle);
            }
        }
        internal static int SetSecurityInfo(ResourceType type, string name, SafeHandle handle, SecurityInfos securityInformation, SecurityIdentifier owner, SecurityIdentifier group, GenericAcl sacl, GenericAcl dacl)
        {
            byte[]    binaryForm = null;
            byte[]    buffer2    = null;
            byte[]    buffer3    = null;
            byte[]    buffer4    = null;
            Privilege privilege  = null;

            new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
            if (owner != null)
            {
                binaryForm = new byte[owner.BinaryLength];
                owner.GetBinaryForm(binaryForm, 0);
            }
            if (group != null)
            {
                buffer2 = new byte[group.BinaryLength];
                group.GetBinaryForm(buffer2, 0);
            }
            if (dacl != null)
            {
                buffer4 = new byte[dacl.BinaryLength];
                dacl.GetBinaryForm(buffer4, 0);
            }
            if (sacl != null)
            {
                buffer3 = new byte[sacl.BinaryLength];
                sacl.GetBinaryForm(buffer3, 0);
            }
            if ((securityInformation & SecurityInfos.SystemAcl) != 0)
            {
                privilege = new Privilege("SeSecurityPrivilege");
            }
            RuntimeHelpers.PrepareConstrainedRegions();
            try
            {
                int num;
                if (privilege != null)
                {
                    try
                    {
                        privilege.Enable();
                    }
                    catch (PrivilegeNotHeldException)
                    {
                    }
                }
                if (name != null)
                {
                    num = (int)Win32Native.SetSecurityInfoByName(name, (uint)type, (uint)securityInformation, binaryForm, buffer2, buffer4, buffer3);
                }
                else
                {
                    if (handle == null)
                    {
                        throw new InvalidProgramException();
                    }
                    if (handle.IsInvalid)
                    {
                        throw new ArgumentException(Environment.GetResourceString("Argument_InvalidSafeHandle"), "handle");
                    }
                    num = (int)Win32Native.SetSecurityInfoByHandle(handle, (uint)type, (uint)securityInformation, binaryForm, buffer2, buffer4, buffer3);
                }
                if ((num == 0x514) || (num == 0x522))
                {
                    throw new PrivilegeNotHeldException("SeSecurityPrivilege");
                }
                if ((num == 5) || (num == 0x543))
                {
                    throw new UnauthorizedAccessException();
                }
                if (num != 0)
                {
                    if (num == 8)
                    {
                        throw new OutOfMemoryException();
                    }
                    return(num);
                }
            }
            catch
            {
                if (privilege != null)
                {
                    privilege.Revert();
                }
                throw;
            }
            finally
            {
                if (privilege != null)
                {
                    privilege.Revert();
                }
            }
            return(0);
        }
Example #22
0
        internal void RemoveAceSpecific(AceQualifier aceQualifier,
                                        SecurityIdentifier sid,
                                        int accessMask,
                                        InheritanceFlags inheritanceFlags,
                                        PropagationFlags propagationFlags,
                                        AuditFlags auditFlags,
                                        ObjectAceFlags objectFlags,
                                        Guid objectType,
                                        Guid inheritedObjectType)
        {
            if (!IsDS)
            {
                throw new InvalidOperationException("For this overload, IsDS must be true.");
            }

            if (ObjectAceFlags.None == objectFlags)
            {
                RemoveAceSpecific(aceQualifier, sid, accessMask, inheritanceFlags, propagationFlags, auditFlags);
                return;
            }

            RequireCanonicity();
            RemoveAces <ObjectAce> (ace =>
            {
                if (ace.AccessMask != accessMask)
                {
                    return(false);
                }
                if (ace.AceQualifier != aceQualifier)
                {
                    return(false);
                }
                if (ace.SecurityIdentifier != sid)
                {
                    return(false);
                }
                if (ace.InheritanceFlags != inheritanceFlags)
                {
                    return(false);
                }
                if (InheritanceFlags.None != inheritanceFlags)
                {
                    if (ace.PropagationFlags != propagationFlags)
                    {
                        return(false);
                    }
                }
                if (ace.AuditFlags != auditFlags)
                {
                    return(false);
                }
                if (ace.ObjectAceFlags != objectFlags)
                {
                    return(false);
                }
                if (0 != (objectFlags & ObjectAceFlags.ObjectAceTypePresent))
                {
                    if (ace.ObjectAceType != objectType)
                    {
                        return(false);
                    }
                }
                if (0 != (objectFlags & ObjectAceFlags.InheritedObjectAceTypePresent))
                {
                    if (ace.InheritedObjectAceType != objectType)
                    {
                        return(false);
                    }
                }
                return(true);
            });
            CleanAndRetestCanonicity();
        }
 public void RemoveAccessSpecific(AccessControlType accessType, SecurityIdentifier sid, ObjectAccessRule rule);
Example #24
0
 public WindowsSidIdentity(SecurityIdentifier sid)
 {
     SecurityIdentifier = sid ?? throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("sid");
     AuthenticationType = string.Empty;
 }
 public void SetAccess(AccessControlType accessType, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, ObjectAceFlags objectFlags, Guid objectType, Guid inheritedObjectType);
Example #26
0
 public WindowsSidIdentity(SecurityIdentifier sid, string name, string authenticationType)
 {
     SecurityIdentifier = sid ?? throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(sid));
     _name = name ?? throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(name));
     AuthenticationType = authenticationType ?? throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(authenticationType));
 }
 public bool RemoveAudit(SecurityIdentifier sid, ObjectAuditRule rule);
        // Workaround: create the pipe via API call
        // we have to do it this way, since NamedPipeServerStream() for netstd still lacks a few CTORs
        // and _stream.SetAccessControl(pipesec); only keeps throwing ACCESS_DENIED errors at us
        // References:
        // - https://github.com/dotnet/corefx/issues/30170 (closed, continued in 31190)
        // - https://github.com/dotnet/corefx/issues/31190 System.IO.Pipes.AccessControl package does not work
        // - https://github.com/dotnet/corefx/issues/24040 NamedPipeServerStream: Provide support for WRITE_DAC
        // - https://github.com/dotnet/corefx/issues/34400 Have a mechanism for lower privileged user to connect to a privileged user's pipe
        private SafePipeHandle CreatePipeNative(string name, int inbuf, int outbuf)
        {
            if (Environment.OSVersion.Platform != PlatformID.Win32NT)
            {
                return(null); // Windows only
            }
            var pinningHandle = new GCHandle();

            try
            {
                // owner gets full access, everyone else read/write
                var pipesec = new PipeSecurity();
                using (var currentIdentity = WindowsIdentity.GetCurrent())
                {
                    var sidOwner = currentIdentity.Owner;
                    var sidWorld = new SecurityIdentifier(WellKnownSidType.WorldSid, null);

                    pipesec.SetOwner(sidOwner);
                    pipesec.AddAccessRule(new PipeAccessRule(sidOwner, PipeAccessRights.FullControl, AccessControlType.Allow));
                    pipesec.AddAccessRule(new PipeAccessRule(sidWorld, PipeAccessRights.ReadWrite, AccessControlType.Allow));
                }

                // create a security descriptor and assign it to the security attribs
                var    secAttrs = new SECURITY_ATTRIBUTES();
                byte[] sdBytes  = pipesec.GetSecurityDescriptorBinaryForm();
                pinningHandle = GCHandle.Alloc(sdBytes, GCHandleType.Pinned);
                unsafe
                {
                    fixed(byte *pSD = sdBytes)
                    {
                        secAttrs.lpSecurityDescriptor = (IntPtr)pSD;
                    }
                }

                // a bunch of constants we will need shortly
                const int PIPE_ACCESS_DUPLEX       = 0x00000003;
                const int FILE_FLAG_OVERLAPPED     = 0x40000000;
                const int WRITE_DAC                = 0x00040000;
                const int PIPE_TYPE_BYTE           = 0x00000000;
                const int PIPE_READMODE_BYTE       = 0x00000000;
                const int PIPE_UNLIMITED_INSTANCES = 255;

                // create the pipe via API call
                var rawHandle = CreateNamedPipe(
                    @"\\.\pipe\" + name,
                    PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED | WRITE_DAC,
                    PIPE_TYPE_BYTE | PIPE_READMODE_BYTE,
                    PIPE_UNLIMITED_INSTANCES, (uint)inbuf, (uint)outbuf,
                    5 * 1000,
                    secAttrs
                    );

                // make a SafePipeHandle() from it
                var handle = new SafePipeHandle(rawHandle, true);
                if (handle.IsInvalid)
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                // return it (to be packaged)
                return(handle);
            }
            finally
            {
                if (pinningHandle.IsAllocated)
                {
                    pinningHandle.Free();
                }
            }
        }
 public void SetAudit(AuditFlags auditFlags, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, ObjectAceFlags objectFlags, Guid objectType, Guid inheritedObjectType);
Example #30
0
        public void GenerateEquityProperlyResolvesFirstDate()
        {
            var spy = SecurityIdentifier.GenerateEquity("SPY", Market.USA);

            Assert.AreEqual(new DateTime(1998, 01, 02), spy.Date);
        }
Example #31
0
        //
        // Creates a security descriptor explicitly
        //

        public CommonSecurityDescriptor(bool isContainer, bool isDS, ControlFlags flags, SecurityIdentifier owner, SecurityIdentifier group, SystemAcl systemAcl, DiscretionaryAcl discretionaryAcl)
        {
            CreateFromParts(isContainer, isDS, flags, owner, group, systemAcl, discretionaryAcl);
        }
Example #32
0
 public void RoundTripEmptyParse()
 {
     Assert.AreEqual(SecurityIdentifier.Empty, SecurityIdentifier.Parse(SecurityIdentifier.Empty.ToString()));
 }
Example #33
0
        public static bool CheckWriteAccessEnabled(string path, string sid)
        {
            // get file or directory security object
            FileSystemSecurity security = GetFileSystemSecurity(path);
            if (security == null)
                return false;

            if (sid == null)
                return false;

            AuthorizationRuleCollection rules = security.GetAccessRules(true, true, typeof(SecurityIdentifier));
            SecurityIdentifier identity = new SecurityIdentifier(sid);
            foreach (FileSystemAccessRule rule in rules)
            {
                if (rule.IdentityReference == identity
                    && rule.AccessControlType == AccessControlType.Allow
                    && (rule.FileSystemRights & FileSystemRights.Write) == FileSystemRights.Write)
                    return true;
            }
            return false;
        }
Example #34
0
        ////////////////////////////////////////////////////////////////////////////////////////// Instance
        //////////////////////////////////////////////////////////////////////////////// Public

        #region 연결 대기하기 - WaitForConnection()

        /// <summary>
        /// 연결 대기하기
        /// </summary>
        /// <returns>자식 파이프</returns>
        public NamedPipe WaitForConnection()
        {
            if (string.IsNullOrEmpty(this.pipeName) == true || this.exitEventHandle == null)
            {
                Trace.WriteLine("파이프 서비스 종료");

                return(null);
            }

            NamedPipe clientPipe = new NamedPipe();

            clientPipe.pipeName      = this.pipeName;
            clientPipe.pipeDirection = this.pipeDirection;

            SECURITY_ATTRIBUTE securityAttribute = GetSecurityAttribute();

            clientPipe.pipeHandle = CreateNamedPipe
                                    (
                clientPipe.pipeName,
                (uint)(this.pipeDirection | PipeDirection.FILE_FLAG_OVERLAPPED),
                PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT,
                255,
                BUFFER_SIZE,
                BUFFER_SIZE,
                0,
                ref securityAttribute
                                    );

            Marshal.FreeHGlobal(securityAttribute.SecurityDescriptor);

            if (clientPipe.pipeHandle.IsInvalid)
            {
                Trace.WriteLine("무효한 파이프 연결");

                clientPipe.Dispose();

                return(null);
            }

            NativeOverlapped nativeOverlapped = new NativeOverlapped();

            SecurityIdentifier securityIdentifier = new SecurityIdentifier(WellKnownSidType.WorldSid, null);

            EventWaitHandleSecurity eventHandleSecurity = new EventWaitHandleSecurity();

            bool created;

            eventHandleSecurity.AddAccessRule(new EventWaitHandleAccessRule(securityIdentifier, EventWaitHandleRights.FullControl, AccessControlType.Allow));
            eventHandleSecurity.AddAccessRule(new EventWaitHandleAccessRule(securityIdentifier, EventWaitHandleRights.ChangePermissions, AccessControlType.Deny));

            using (EventWaitHandle eventHandle = new EventWaitHandle(false, EventResetMode.ManualReset, null, out created, eventHandleSecurity))
            {
                nativeOverlapped.EventHandle = eventHandle.SafeWaitHandle.DangerousGetHandle();

                ConnectNamedPipe(clientPipe.pipeHandle, ref nativeOverlapped);

                int lastError = Marshal.GetLastWin32Error();

                if (lastError == 997)
                {
                    int completeCode = 0;

                    IntPtr[] waitHandleArray = new IntPtr[]
                    {
                        eventHandle.SafeWaitHandle.DangerousGetHandle(),
                        this.exitEventHandle.SafeWaitHandle.DangerousGetHandle()
                    };

                    completeCode = WaitForMultipleObjects(waitHandleArray.Length, waitHandleArray, false, -1);

                    if (completeCode == 0)
                    {
                    }
                    else if (completeCode == 1)
                    {
                        Trace.WriteLine("파이프 서비스 종료 (리소스 해제)");

                        clientPipe.Dispose();

                        return(null);
                    }
                }
                else if (lastError != 535)
                {
                    Trace.WriteLine("파이프 연결 에러 : " + lastError);

                    clientPipe.Dispose();

                    return(null);
                }
                else
                {
                    Debug.WriteLine("연결되었습니다.");
                }
            }

            clientPipe.needToDisconnect = true;

            FileAccess fileAccess = GetFileAccess(clientPipe.pipeDirection);

            clientPipe.pipeStream = new FileStream(clientPipe.pipeHandle, fileAccess, (int)BUFFER_SIZE, true);

            if (clientPipe.pipeStream == null)
            {
                Trace.WriteLine("파이프 파일 스트림이 null 입니다.");

                clientPipe.Dispose();

                return(null);
            }

            return(clientPipe);
        }
 internal SecurityIdentifier GetSpnSid()
 {
     if (!this.hasSpnSidBeenComputed)
     {
         lock (this.thisLock)
         {
             if (!this.hasSpnSidBeenComputed)
             {
                 string spn = null;
                 try
                 {
                     if (ClaimTypes.Dns.Equals(base.IdentityClaim.ClaimType))
                     {
                         spn = "host/" + ((string) base.IdentityClaim.Resource);
                     }
                     else
                     {
                         spn = (string) base.IdentityClaim.Resource;
                     }
                     if (spn != null)
                     {
                         spn = spn.Replace("*", @"\*").Replace("(", @"\(").Replace(")", @"\)");
                     }
                     using (DirectorySearcher searcher = new DirectorySearcher(GetDirectoryEntry()))
                     {
                         searcher.CacheResults = true;
                         searcher.ClientTimeout = SpnLookupTime;
                         searcher.Filter = "(&(objectCategory=Computer)(objectClass=computer)(servicePrincipalName=" + spn + "))";
                         searcher.PropertiesToLoad.Add("objectSid");
                         SearchResult result = searcher.FindOne();
                         if (result != null)
                         {
                             byte[] binaryForm = (byte[]) result.Properties["objectSid"][0];
                             this.spnSid = new SecurityIdentifier(binaryForm, 0);
                         }
                         else
                         {
                             SecurityTraceRecordHelper.TraceSpnToSidMappingFailure(spn, null);
                         }
                     }
                 }
                 catch (Exception exception)
                 {
                     if (Fx.IsFatal(exception))
                     {
                         throw;
                     }
                     if ((exception is NullReferenceException) || (exception is SEHException))
                     {
                         throw;
                     }
                     SecurityTraceRecordHelper.TraceSpnToSidMappingFailure(spn, exception);
                 }
                 finally
                 {
                     this.hasSpnSidBeenComputed = true;
                 }
             }
         }
     }
     return this.spnSid;
 }
 public void Purge(SecurityIdentifier sid);
Example #37
0
 public override int GetHashCode()
 {
     return(SecurityIdentifier.GetHashCode());
 }
Example #38
0
        public void ReturnsCorrectMarketWhenNotFound()
        {
            var sid = new SecurityIdentifier("some symbol", 0357960000000009901);

            Assert.AreEqual("99", sid.Market);
        }
Example #39
0
        public static void GrantNtfsPermissionsBySid(string path, string sid,
            NTFSPermission permissions, bool inheritParentPermissions,
            bool preserveOriginalPermissions)
        {
            // get file or directory security object
            FileSystemSecurity security = GetFileSystemSecurity(path);
            if (security == null)
                return;

            FileSystemRights rights = FileSystemRights.Read;
            if (permissions == NTFSPermission.FullControl)
                rights = FileSystemRights.FullControl;
            else if (permissions == NTFSPermission.Modify)
                rights = FileSystemRights.Modify;
            else if (permissions == NTFSPermission.Write)
                rights = FileSystemRights.Write;
            else if (permissions == NTFSPermission.Read && security is DirectorySecurity)
                rights = FileSystemRights.ReadAndExecute;
            else if (permissions == NTFSPermission.Read && security is FileSecurity)
                rights = FileSystemRights.Read;

            SecurityIdentifier identity = new SecurityIdentifier(sid);

            if (!preserveOriginalPermissions)
                security = CreateFileSystemSecurity(path);
            else
                security.RemoveAccessRuleAll(new FileSystemAccessRule(identity,
                    FileSystemRights.Read, AccessControlType.Allow));

            if (!inheritParentPermissions)
                security.SetAccessRuleProtection(true, inheritParentPermissions);
            else
                security.SetAccessRuleProtection(false, true);

            InheritanceFlags flags = security is FileSecurity ? InheritanceFlags.None
                : InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;

            // change DACL
            FileSystemAccessRule rule = new FileSystemAccessRule(
                identity, rights,
                flags,
                PropagationFlags.None,
                AccessControlType.Allow);

            // add/modify rule
            security.AddAccessRule(rule);

            // set security object
            SetFileSystemSecurity(path, security);
        }
        /// <summary>
        /// Create an order from a simple JObject
        /// </summary>
        /// <param name="jObject"></param>
        /// <returns>Order Object</returns>
        public static Order CreateOrderFromJObject(JObject jObject)
        {
            // create order instance based on order type field
            var orderType = (OrderType)jObject["Type"].Value <int>();
            var order     = CreateOrder(orderType, jObject);

            // populate common order properties
            order.Id = jObject["Id"].Value <int>();

            var jsonStatus = jObject["Status"];
            var jsonTime   = jObject["Time"];

            if (jsonStatus.Type == JTokenType.Integer)
            {
                order.Status = (OrderStatus)jsonStatus.Value <int>();
            }
            else if (jsonStatus.Type == JTokenType.Null)
            {
                order.Status = OrderStatus.Canceled;
            }
            else
            {
                // The `Status` tag can sometimes appear as a string of the enum value in the LiveResultPacket.
                order.Status = (OrderStatus)Enum.Parse(typeof(OrderStatus), jsonStatus.Value <string>(), true);
            }
            if (jsonTime != null && jsonTime.Type != JTokenType.Null)
            {
                order.Time = jsonTime.Value <DateTime>();
            }
            else
            {
                // `Time` can potentially be null in some LiveResultPacket instances, but
                // `CreatedTime` will always be there if `Time` is absent.
                order.Time = jObject["CreatedTime"].Value <DateTime>();
            }

            var orderSubmissionData = jObject["OrderSubmissionData"];

            if (orderSubmissionData != null && orderSubmissionData.Type != JTokenType.Null)
            {
                var bidPrice  = orderSubmissionData["BidPrice"].Value <decimal>();
                var askPrice  = orderSubmissionData["AskPrice"].Value <decimal>();
                var lastPrice = orderSubmissionData["LastPrice"].Value <decimal>();
                order.OrderSubmissionData = new OrderSubmissionData(bidPrice, askPrice, lastPrice);
            }

            var lastFillTime   = jObject["LastFillTime"];
            var lastUpdateTime = jObject["LastUpdateTime"];
            var canceledTime   = jObject["CanceledTime"];

            if (canceledTime != null && canceledTime.Type != JTokenType.Null)
            {
                order.CanceledTime = canceledTime.Value <DateTime>();
            }
            if (lastFillTime != null && lastFillTime.Type != JTokenType.Null)
            {
                order.LastFillTime = lastFillTime.Value <DateTime>();
            }
            if (lastUpdateTime != null && lastUpdateTime.Type != JTokenType.Null)
            {
                order.LastUpdateTime = lastUpdateTime.Value <DateTime>();
            }
            var tag = jObject["Tag"];

            if (tag != null && tag.Type != JTokenType.Null)
            {
                order.Tag = tag.Value <string>();
            }
            else
            {
                order.Tag = "";
            }

            order.Quantity = jObject["Quantity"].Value <decimal>();
            var orderPrice = jObject["Price"];

            if (orderPrice != null && orderPrice.Type != JTokenType.Null)
            {
                order.Price = orderPrice.Value <decimal>();
            }
            else
            {
                order.Price = default(decimal);
            }

            var priceCurrency = jObject["PriceCurrency"];

            if (priceCurrency != null && priceCurrency.Type != JTokenType.Null)
            {
                order.PriceCurrency = priceCurrency.Value <string>();
            }
            var securityType = (SecurityType)jObject["SecurityType"].Value <int>();

            order.BrokerId     = jObject["BrokerId"].Select(x => x.Value <string>()).ToList();
            order.ContingentId = jObject["ContingentId"].Value <int>();

            var timeInForce = jObject["Properties"]?["TimeInForce"] ?? jObject["TimeInForce"] ?? jObject["Duration"];

            order.Properties.TimeInForce = timeInForce != null
                ? CreateTimeInForce(timeInForce, jObject)
                : TimeInForce.GoodTilCanceled;

            string market = null;

            //does data have market?
            var suppliedMarket = jObject.SelectTokens("Symbol.ID.Market");

            if (suppliedMarket.Any())
            {
                market = suppliedMarket.Single().Value <string>();
            }

            if (jObject.SelectTokens("Symbol.ID").Any())
            {
                var sid    = SecurityIdentifier.Parse(jObject.SelectTokens("Symbol.ID").Single().Value <string>());
                var ticker = jObject.SelectTokens("Symbol.Value").Single().Value <string>();
                order.Symbol = new Symbol(sid, ticker);
            }
            else if (jObject.SelectTokens("Symbol.Value").Any())
            {
                // provide for backwards compatibility
                var ticker = jObject.SelectTokens("Symbol.Value").Single().Value <string>();

                if (market == null && !SymbolPropertiesDatabase.FromDataFolder().TryGetMarket(ticker, securityType, out market))
                {
                    market = DefaultBrokerageModel.DefaultMarketMap[securityType];
                }
                order.Symbol = Symbol.Create(ticker, securityType, market);
            }
            else
            {
                var tickerstring = jObject["Symbol"].Value <string>();

                if (market == null && !SymbolPropertiesDatabase.FromDataFolder().TryGetMarket(tickerstring, securityType, out market))
                {
                    market = DefaultBrokerageModel.DefaultMarketMap[securityType];
                }
                order.Symbol = Symbol.Create(tickerstring, securityType, market);
            }

            return(order);
        }
 public CommonAce(AceFlags flags, AceQualifier qualifier, int accessMask, SecurityIdentifier sid, bool isCallback, byte[] opaque);
Example #42
0
        public static string GetNameFromSID(SecurityIdentifier sid)
        {
            NTAccount ntAccount = (NTAccount)sid.Translate(typeof(NTAccount));

            return(ntAccount.ToString());
        }
 public CommonSecurityDescriptor(bool isContainer, bool isDS, ControlFlags flags, SecurityIdentifier owner, SecurityIdentifier group, SystemAcl systemAcl, DiscretionaryAcl discretionaryAcl);
Example #44
0
 public void PurgeAccessControl(SecurityIdentifier sid)
 {
     throw new NotImplementedException();
 }
 public void PurgeAudit(SecurityIdentifier sid);
Example #46
0
 public void PurgeAudit(SecurityIdentifier sid)
 {
     throw new NotImplementedException();
 }
 public bool RemoveAccess(AccessControlType accessType, SecurityIdentifier sid, ObjectAccessRule rule);
Example #48
0
        //
        // Modifies the SACL
        //
        private bool ModifyAudit(AccessControlModification modification, ObjectAuditRule rule, out bool modified)
        {
            bool result = true;

            if (_securityDescriptor.SystemAcl == null)
            {
                if (modification == AccessControlModification.Remove || modification == AccessControlModification.RemoveAll || modification == AccessControlModification.RemoveSpecific)
                {
                    modified = false;
                    return(result);
                }

                //_securityDescriptor.SystemAcl = new SystemAcl(IsContainer, IsDS, GenericAcl.AclRevisionDS, 1);
                //_securityDescriptor.AddControlFlags(ControlFlags.SystemAclPresent);
                _securityDescriptor.AddSystemAcl(GenericAcl.AclRevisionDS, 1);
            }
            else if ((modification == AccessControlModification.Add || modification == AccessControlModification.Set || modification == AccessControlModification.Reset) &&
                     (rule.ObjectFlags != ObjectAceFlags.None))
            {
                //
                // This will result in an object ace being added to the sacl, so the sacl revision must be AclRevisionDS
                //
                if (_securityDescriptor.SystemAcl.Revision < GenericAcl.AclRevisionDS)
                {
                    //
                    // we need to create a new sacl with the same aces as the existing one but the revision should be AclRevisionDS
                    //
                    byte[] binaryForm = new byte[_securityDescriptor.SystemAcl.BinaryLength];
                    _securityDescriptor.SystemAcl.GetBinaryForm(binaryForm, 0);
                    binaryForm[0] = GenericAcl.AclRevisionDS; // revision is the first byte of the binary form

                    _securityDescriptor.SystemAcl = new SystemAcl(IsContainer, IsDS, new RawAcl(binaryForm, 0));
                }
            }

            SecurityIdentifier sid = rule.IdentityReference.Translate(typeof(SecurityIdentifier)) as SecurityIdentifier;

            switch (modification)
            {
            case AccessControlModification.Add:
                //_securityDescriptor.SystemAcl.AddAudit(rule.AuditFlags, sid, rule.AccessMask, rule.InheritanceFlags, rule.PropagationFlags, rule.ObjectFlags, rule.ObjectType, rule.InheritedObjectType);
                _securityDescriptor.SystemAcl.AddAudit(sid, rule);
                break;

            case AccessControlModification.Set:
                //_securityDescriptor.SystemAcl.SetAudit(rule.AuditFlags, sid, rule.AccessMask, rule.InheritanceFlags, rule.PropagationFlags, rule.ObjectFlags, rule.ObjectType, rule.InheritedObjectType);
                _securityDescriptor.SystemAcl.SetAudit(sid, rule);
                break;

            case AccessControlModification.Reset:
                _securityDescriptor.SystemAcl.RemoveAudit(AuditFlags.Failure | AuditFlags.Success, sid, -1, InheritanceFlags.ContainerInherit, 0, ObjectAceFlags.None, Guid.Empty, Guid.Empty);
                //_securityDescriptor.SystemAcl.SetAudit(rule.AuditFlags, sid, rule.AccessMask, rule.InheritanceFlags, rule.PropagationFlags, rule.ObjectFlags, rule.ObjectType, rule.InheritedObjectType);
                _securityDescriptor.SystemAcl.SetAudit(sid, rule);
                break;

            case AccessControlModification.Remove:
                //result = _securityDescriptor.SystemAcl.RemoveAudit(rule.AuditFlags, sid, rule.AccessMask, rule.InheritanceFlags, rule.PropagationFlags, rule.ObjectFlags, rule.ObjectType, rule.InheritedObjectType);
                result = _securityDescriptor.SystemAcl.RemoveAudit(sid, rule);
                break;

            case AccessControlModification.RemoveAll:
                result = _securityDescriptor.SystemAcl.RemoveAudit(AuditFlags.Failure | AuditFlags.Success, sid, -1, InheritanceFlags.ContainerInherit, 0, ObjectAceFlags.None, Guid.Empty, Guid.Empty);
                if (result == false)
                {
                    Debug.Assert(false, "Invalid operation");
                    throw new Exception();
                }

                break;

            case AccessControlModification.RemoveSpecific:
                //_securityDescriptor.SystemAcl.RemoveAuditSpecific(rule.AuditFlags, sid, rule.AccessMask, rule.InheritanceFlags, rule.PropagationFlags, rule.ObjectFlags, rule.ObjectType, rule.InheritedObjectType);
                _securityDescriptor.SystemAcl.RemoveAuditSpecific(sid, rule);
                break;

            default:
                throw new ArgumentOutOfRangeException(
                          nameof(modification),
                          SR.ArgumentOutOfRange_Enum);
            }

            modified            = result;
            AuditRulesModified |= modified;
            return(result);
        }
 public void SetAccess(AccessControlType accessType, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags);
Example #50
0
        private void CheckQualifiedWellKnownSid(WellKnownSidType type, SecurityIdentifier domain, string sddl)
        {
            SecurityIdentifier sid = new SecurityIdentifier(type, domain);

            Assert.AreEqual(sddl, sid.Value, "Bad SID for type: " + type);
        }
 public void SetAccess(AccessControlType accessType, SecurityIdentifier sid, ObjectAccessRule rule);
Example #52
0
 public ConditionalAceSecurityIdentifierToken(SecurityIdentifier sid) : base(ConditionalAceTokenByteCode.Sid)
 {
     this.SecurityIdentifier = sid;
 }
 public RawSecurityDescriptor(ControlFlags flags, SecurityIdentifier owner, SecurityIdentifier group, RawAcl systemAcl, RawAcl discretionaryAcl);
        public static TerminalSessionInfo GetSessionInfo(string ServerName, int SessionId)
        {
            IntPtr server = IntPtr.Zero;
            IntPtr buffer = IntPtr.Zero;
            int    bytesReturned;
            TerminalSessionInfo data   = new TerminalSessionInfo();
            bool   _IsCurrentSessionId = false;
            bool   _IsConsoleSession   = false;
            bool   _IsUserSession      = false;
            int    currentSessionID    = 0;
            string _NTAccount          = String.Empty;

            if (ServerName == "localhost" || ServerName == String.Empty)
            {
                ServerName = Environment.MachineName;
            }
            if (ProcessIdToSessionId(GetCurrentProcessId(), ref currentSessionID) == false)
            {
                currentSessionID = -1;
            }

            // Get all members of the local administrators group
            bool          _IsLocalAdminCheckSuccess = false;
            List <string> localAdminGroupSidsList   = new List <string>();

            try
            {
                DirectoryEntry localMachine        = new DirectoryEntry("WinNT://" + ServerName + ",Computer");
                string         localAdminGroupName = new SecurityIdentifier("S-1-5-32-544").Translate(typeof(NTAccount)).Value.Split('\\')[1];
                DirectoryEntry admGroup            = localMachine.Children.Find(localAdminGroupName, "group");
                object         members             = admGroup.Invoke("members", null);
                string         validSidPattern     = @"^S-\d-\d+-(\d+-){1,14}\d+$";
                foreach (object groupMember in (IEnumerable)members)
                {
                    DirectoryEntry member = new DirectoryEntry(groupMember);
                    if (member.Name != String.Empty)
                    {
                        if (Regex.IsMatch(member.Name, validSidPattern))
                        {
                            localAdminGroupSidsList.Add(member.Name);
                        }
                        else
                        {
                            localAdminGroupSidsList.Add((new NTAccount(member.Name)).Translate(typeof(SecurityIdentifier)).Value);
                        }
                    }
                }
                _IsLocalAdminCheckSuccess = true;
            }
            catch { }

            try
            {
                server = OpenServer(ServerName);

                if (WTSQuerySessionInformation(server, SessionId, WTS_INFO_CLASS.ClientBuildNumber, out buffer, out bytesReturned) == false)
                {
                    return(data);
                }
                int lData = Marshal.ReadInt32(buffer);
                data.ClientBuildNumber = lData;

                if (WTSQuerySessionInformation(server, SessionId, WTS_INFO_CLASS.ClientDirectory, out buffer, out bytesReturned) == false)
                {
                    return(data);
                }
                string strData = Marshal.PtrToStringAnsi(buffer);
                data.ClientDirectory = strData;

                if (WTSQuerySessionInformation(server, SessionId, WTS_INFO_CLASS.ClientName, out buffer, out bytesReturned) == false)
                {
                    return(data);
                }
                strData         = Marshal.PtrToStringAnsi(buffer);
                data.ClientName = strData;

                if (WTSQuerySessionInformation(server, SessionId, WTS_INFO_CLASS.ClientProtocolType, out buffer, out bytesReturned) == false)
                {
                    return(data);
                }
                Int16 intData = Marshal.ReadInt16(buffer);
                if (intData == 2)
                {
                    strData           = "RDP";
                    data.IsRdpSession = true;
                }
                else
                {
                    strData           = "";
                    data.IsRdpSession = false;
                }
                data.ClientProtocolType = strData;

                if (WTSQuerySessionInformation(server, SessionId, WTS_INFO_CLASS.ConnectState, out buffer, out bytesReturned) == false)
                {
                    return(data);
                }
                lData             = Marshal.ReadInt32(buffer);
                data.ConnectState = ((WTS_CONNECTSTATE_CLASS)lData).ToString();

                if (WTSQuerySessionInformation(server, SessionId, WTS_INFO_CLASS.SessionId, out buffer, out bytesReturned) == false)
                {
                    return(data);
                }
                lData          = Marshal.ReadInt32(buffer);
                data.SessionId = lData;

                if (WTSQuerySessionInformation(server, SessionId, WTS_INFO_CLASS.DomainName, out buffer, out bytesReturned) == false)
                {
                    return(data);
                }
                strData         = Marshal.PtrToStringAnsi(buffer).ToUpper();
                data.DomainName = strData;
                if (strData != String.Empty)
                {
                    _NTAccount = strData;
                }

                if (WTSQuerySessionInformation(server, SessionId, WTS_INFO_CLASS.UserName, out buffer, out bytesReturned) == false)
                {
                    return(data);
                }
                strData       = Marshal.PtrToStringAnsi(buffer);
                data.UserName = strData;
                if (strData != String.Empty)
                {
                    data.NTAccount = _NTAccount + "\\" + strData;
                    string _Sid = (new NTAccount(_NTAccount + "\\" + strData)).Translate(typeof(SecurityIdentifier)).Value;
                    data.SID = _Sid;
                    if (_IsLocalAdminCheckSuccess == true)
                    {
                        foreach (string localAdminGroupSid in localAdminGroupSidsList)
                        {
                            if (localAdminGroupSid == _Sid)
                            {
                                data.IsLocalAdmin = true;
                                break;
                            }
                            else
                            {
                                data.IsLocalAdmin = false;
                            }
                        }
                    }
                }

                if (WTSQuerySessionInformation(server, SessionId, WTS_INFO_CLASS.SessionName, out buffer, out bytesReturned) == false)
                {
                    return(data);
                }
                strData          = Marshal.PtrToStringAnsi(buffer);
                data.SessionName = strData;
                if (strData != "Services" && strData != "RDP-Tcp" && data.UserName != String.Empty)
                {
                    _IsUserSession = true;
                }
                data.IsUserSession = _IsUserSession;
                if (strData == "Console")
                {
                    _IsConsoleSession = true;
                }
                data.IsConsoleSession = _IsConsoleSession;

                WINSTATIONINFORMATIONW wsInfo = GetWinStationInformation(server, SessionId);
                DateTime?_loginTime           = FileTimeToDateTime(wsInfo.LoginTime);
                DateTime?_lastInputTime       = FileTimeToDateTime(wsInfo.LastInputTime);
                DateTime?_disconnectTime      = FileTimeToDateTime(wsInfo.DisconnectTime);
                DateTime?_currentTime         = FileTimeToDateTime(wsInfo.CurrentTime);
                TimeSpan?_idleTime            = (_currentTime != null && _lastInputTime != null) ? _currentTime.Value - _lastInputTime.Value : TimeSpan.Zero;
                data.LogonTime      = _loginTime;
                data.IdleTime       = _idleTime;
                data.DisconnectTime = _disconnectTime;

                if (currentSessionID == SessionId)
                {
                    _IsCurrentSessionId = true;
                }
                data.IsCurrentSession = _IsCurrentSessionId;
            }
            finally
            {
                WTSFreeMemory(buffer);
                buffer = IntPtr.Zero;
                CloseServer(server);
            }
            return(data);
        }
 public void RemoveAuditSpecific(AuditFlags auditFlags, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags);
Example #56
0
        //
        // Creates a security descriptor explicitly
        //

        public RawSecurityDescriptor(ControlFlags flags, SecurityIdentifier owner, SecurityIdentifier group, RawAcl systemAcl, RawAcl discretionaryAcl)
            : base()
        {
            CreateFromParts(flags, owner, group, systemAcl, discretionaryAcl);
        }
 public void SetAudit(AuditFlags auditFlags, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags);
Example #58
0
        //
        // Creates a security descriptor from its binary representation
        // Important: the representation must be in self-relative format
        //

        public RawSecurityDescriptor(byte[] binaryForm, int offset)
            : base()
        {
            //
            // The array passed in must be valid
            //

            if (binaryForm == null)
            {
                throw new ArgumentNullException("binaryForm");
            }

            if (offset < 0)
            {
                //
                // Offset must not be negative
                //

                throw new ArgumentOutOfRangeException("offset",
                                                      Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
            }

            //
            // At least make sure the header is in place
            //

            if (binaryForm.Length - offset < HeaderLength)
            {
                throw new ArgumentOutOfRangeException(
                          "binaryForm",
                          Environment.GetResourceString("ArgumentOutOfRange_ArrayTooSmall"));
            }

            //
            // We only understand revision-1 security descriptors
            //

            if (binaryForm[offset + 0] != Revision)
            {
                throw new ArgumentOutOfRangeException("binaryForm",
                                                      Environment.GetResourceString("AccessControl_InvalidSecurityDescriptorRevision"));
            }
            Contract.EndContractBlock();


            ControlFlags       flags;
            SecurityIdentifier owner, group;
            RawAcl             sacl, dacl;
            byte rmControl;

            //
            // Extract the ResourceManagerControl field
            //

            rmControl = binaryForm[offset + 1];

            //
            // Extract the control flags
            //

            flags = ( ControlFlags )((binaryForm[offset + 2] << 0) + (binaryForm[offset + 3] << 8));

            //
            // Make sure that the input is in self-relative format
            //

            if ((flags & ControlFlags.SelfRelative) == 0)
            {
                throw new ArgumentException(
                          Environment.GetResourceString("AccessControl_InvalidSecurityDescriptorSelfRelativeForm"),
                          "binaryForm");
            }

            //
            // Extract the owner SID
            //

            int ownerOffset = UnmarshalInt(binaryForm, offset + OwnerFoundAt);

            if (ownerOffset != 0)
            {
                owner = new SecurityIdentifier(binaryForm, offset + ownerOffset);
            }
            else
            {
                owner = null;
            }

            //
            // Extract the group SID
            //

            int groupOffset = UnmarshalInt(binaryForm, offset + GroupFoundAt);

            if (groupOffset != 0)
            {
                group = new SecurityIdentifier(binaryForm, offset + groupOffset);
            }
            else
            {
                group = null;
            }

            //
            // Extract the SACL
            //

            int saclOffset = UnmarshalInt(binaryForm, offset + SaclFoundAt);

            if (((flags & ControlFlags.SystemAclPresent) != 0) &&
                saclOffset != 0)
            {
                sacl = new RawAcl(binaryForm, offset + saclOffset);
            }
            else
            {
                sacl = null;
            }

            //
            // Extract the DACL
            //

            int daclOffset = UnmarshalInt(binaryForm, offset + DaclFoundAt);

            if (((flags & ControlFlags.DiscretionaryAclPresent) != 0) &&
                daclOffset != 0)
            {
                dacl = new RawAcl(binaryForm, offset + daclOffset);
            }
            else
            {
                dacl = null;
            }

            //
            // Create the resulting security descriptor
            //

            CreateFromParts(flags, owner, group, sacl, dacl);

            //
            // In the offchance that the flags indicate that the rmControl
            // field is meaningful, remember what was there.
            //

            if ((flags & ControlFlags.RMControlValid) != 0)
            {
                ResourceManagerControl = rmControl;
            }
        }
 public void SetAudit(SecurityIdentifier sid, ObjectAuditRule rule);
Example #60
0
        private void CreateFromParts(bool isContainer, bool isDS, ControlFlags flags, SecurityIdentifier owner, SecurityIdentifier group, SystemAcl systemAcl, DiscretionaryAcl discretionaryAcl)
        {
            if (systemAcl != null &&
                systemAcl.IsContainer != isContainer)
            {
                throw new ArgumentException(
                          Environment.GetResourceString(isContainer ?
                                                        "AccessControl_MustSpecifyContainerAcl" :
                                                        "AccessControl_MustSpecifyLeafObjectAcl"),
                          "systemAcl");
            }

            if (discretionaryAcl != null &&
                discretionaryAcl.IsContainer != isContainer)
            {
                throw new ArgumentException(
                          Environment.GetResourceString(isContainer ?
                                                        "AccessControl_MustSpecifyContainerAcl" :
                                                        "AccessControl_MustSpecifyLeafObjectAcl"),
                          "discretionaryAcl");
            }

            _isContainer = isContainer;

            if (systemAcl != null &&
                systemAcl.IsDS != isDS)
            {
                throw new ArgumentException(
                          Environment.GetResourceString(isDS ?
                                                        "AccessControl_MustSpecifyDirectoryObjectAcl" :
                                                        "AccessControl_MustSpecifyNonDirectoryObjectAcl"),
                          "systemAcl");
            }

            if (discretionaryAcl != null &&
                discretionaryAcl.IsDS != isDS)
            {
                throw new ArgumentException(
                          Environment.GetResourceString(isDS ?
                                                        "AccessControl_MustSpecifyDirectoryObjectAcl" :
                                                        "AccessControl_MustSpecifyNonDirectoryObjectAcl"),
                          "discretionaryAcl");
            }

            _isDS = isDS;

            _sacl = systemAcl;

            //
            // Replace null DACL with an allow-all for everyone DACL
            //

            if (discretionaryAcl == null)
            {
                //
                // to conform to native behavior, we will add allow everyone ace for DACL
                //

                discretionaryAcl = DiscretionaryAcl.CreateAllowEveryoneFullAccess(_isDS, _isContainer);
            }

            _dacl = discretionaryAcl;

            //
            // DACL is never null. So always set the flag bit on
            //

            ControlFlags actualFlags = flags | ControlFlags.DiscretionaryAclPresent;

            //
            // Keep SACL and the flag bit in sync.
            //

            if (systemAcl == null)
            {
                unchecked { actualFlags &= ~(ControlFlags.SystemAclPresent); }
            }
            else
            {
                actualFlags |= (ControlFlags.SystemAclPresent);
            }

            _rawSd = new RawSecurityDescriptor(actualFlags, owner, group, systemAcl == null ? null : systemAcl.RawAcl, discretionaryAcl.RawAcl);
        }