Exemplo n.º 1
0
 public static void CheckPrivilege(Privilege privilege)
 {
     if (GetCurrentManager() == null)
     {
         HttpContext.Current.Response.Redirect(Globals.GetAdminAbsolutePath("/accessDenied.aspx?privilege=" + privilege.ToString()));
     }
 }
Exemplo n.º 2
0
 public Member(bnet.protocol.Identity identity, Privilege privs, params Role[] roles)
 {
     this.Identity = identity;
     this.Privileges = privs;
     this.Roles = new List<Role>();
     AddRoles(roles);
 }
Exemplo n.º 3
0
 public static List<TestPrivilege> BuildPrivilegeFromDataBaseData(string idPerson)
 {
     List<TestPrivilege> priveleges = new List<TestPrivilege>();
     using (NpgsqlConnection connection = Global.GetSqlConnection())
     {
         string findPriviledge = "SELECT * FROM public.priviledge WHERE id_person = '" + idPerson + "'";
         NpgsqlCommand person = new NpgsqlCommand(findPriviledge, connection);
         using (NpgsqlDataReader contactReader = person.ExecuteReader())
         {
             while (contactReader.Read())
             {
                 //что делать с DateSpecified?
                 Privilege priv = new Privilege();
                 if (contactReader["date_start"] != DBNull.Value)
                     priv.StartDate = Convert.ToDateTime(contactReader["date_start"]);
                 if (contactReader["date_end"] != DBNull.Value)
                     priv.EndDate = Convert.ToDateTime(contactReader["date_end"]);
                 TestPrivilege privilege = new TestPrivilege(priv);
                 if (contactReader["id_priviledge_code"] != DBNull.Value)
                     privilege.privilegeType = TestCoding.BuildCodingFromDataBaseData(Convert.ToString(contactReader["id_priviledge_code"]));
                 priveleges.Add(privilege);
             }
         }
     }
     return (priveleges.Count != 0) ? priveleges : null;
 }
 public DbsyncTvPrivilegeType(Privilege pr)
 {
     this.priv = pr;
     this.Text = pr.Grantee;
     this.typeOfIcon = GrantIcon;
     this.Name = this.Text;
 }
Exemplo n.º 5
0
      /// <summary>Initializes a new instance of the <see cref="PrivilegeEnabler"/> class.
      /// This will enable the privileges specified (unless already enabled), and ensure that they are disabled again when
      /// the object is disposed. (Any privileges already enabled will not be disabled).
      /// </summary>
      /// <param name="privilege">The privilege to enable.</param>
      /// <param name="privileges">Additional privileges to enable.</param>
      public PrivilegeEnabler(Privilege privilege, params Privilege[] privileges)
      {
         _enabledPrivileges.Add(new InternalPrivilegeEnabler(privilege));

         if (privileges != null)
            foreach (Privilege priv in privileges)
               _enabledPrivileges.Add(new InternalPrivilegeEnabler(priv));
      }
Exemplo n.º 6
0
      public InternalPrivilegeEnabler(Privilege privilegeName)
      {
         if (privilegeName == null)
            throw new ArgumentNullException("privilegeName");

         _mPrivilege = privilegeName;
         AdjustPrivilege(true);
      }
Exemplo n.º 7
0
 public static string GetGrantPrivilegeQuery(string databaseName, string username, Privilege privilege)
 {
     return string.Format(
         GrantPrivilegeQueryFormat,
         privilege.ToString().ToUpper(),
         databaseName.FormatIdentifier(),
         username.FormatIdentifier()
     );
 }
Exemplo n.º 8
0
 public Member(bnet.protocol.Identity identity, Privilege privs)
 {
     this.Identity = identity;
     this.Privileges = privs;
     this.Roles = new List<Role>();
     this.Info = bnet.protocol.AccountInfo.CreateBuilder()
         .SetAccountStatus(bnet.protocol.AccountInfo.Types.AccountStatus.TRIAL)
         .SetCountryId(21843)
         .Build();
 }
Exemplo n.º 9
0
        public Resultat<Role> GetRoleByPrivilege(Privilege privilege)
        {
            return Resultat<Role>.SafeExecute<RoleService>(
                 result =>
                 {
                     int roleId = (int)privilege;

                     var role = context.Roles.Where(r => r.Id == roleId).First<Role>();
                     result.Valeur = role;
                 });
        }
Exemplo n.º 10
0
 public Member(bnet.protocol.Identity identity, Privilege privs, params Role[] roles)
 {
     this.Identity = identity;
     this.Privileges = privs;
     this.Roles = new List<Role>();
     AddRoles(roles);
     this.Info = bnet.protocol.AccountInfo.CreateBuilder()
         .SetAccountPaid(true)
         .SetCountryId(21843)
         .Build();
 }
Exemplo n.º 11
0
 public static void WriteOperationLog(Privilege privilege, string description)
 {
     OperationLogEntry entry2 = new OperationLogEntry();
     entry2.AddedTime = DateTime.Now;
     entry2.Privilege = privilege;
     entry2.Description = description;
     entry2.IpAddress = Globals.IPAddress;
     entry2.PageUrl = HiContext.Current.Context.Request.RawUrl;
     entry2.UserName = HiContext.Current.Context.User.Identity.Name;
     OperationLogEntry entry = entry2;
     StoreProvider.Instance().WriteOperationLogEntry(entry);
 }
Exemplo n.º 12
0
 public static void WriteOperationLog(Privilege privilege, string description)
 {
     OperationLogEntry entry = new OperationLogEntry {
         AddedTime = DateTime.Now,
         Privilege = privilege,
         Description = description,
         IpAddress = Globals.IPAddress,
         PageUrl = HttpContext.Current.Request.RawUrl,
         UserName = ManagerHelper.GetCurrentManager().UserName
     };
     new LogDao().WriteOperationLogEntry(entry);
 }
Exemplo n.º 13
0
        internal static PrivilegeAttributes GetPrivilegeAttributes(Privilege privilege, PrivilegeAndAttributesCollection privileges)
        {
            foreach (PrivilegeAndAttributes privilegeAndAttributes in privileges)
            {
                if (privilegeAndAttributes.Privilege == privilege)
                {
                    return privilegeAndAttributes.PrivilegeAttributes;
                }
            }

            GetLuid(privilege);

            return PrivilegeAttributes.Removed;
        }
        public AdjustPrivilegeResult EnablePrivilege(Privilege privilege)
        {
            lock (SharedPrivileges)
            {
                if (!SharedPrivileges.ContainsKey(privilege) &&
                    _accessTokenHandle.GetPrivilegeState(privilege) == PrivilegeState.Disabled &&
                    _accessTokenHandle.EnablePrivilege(privilege) == AdjustPrivilegeResult.PrivilegeModified)
                {
                    SharedPrivileges.Add(privilege, this);
                    return AdjustPrivilegeResult.PrivilegeModified;
                }

                return AdjustPrivilegeResult.None;
            }
        }
Exemplo n.º 15
0
        public static Privilege GetInstance()
        {
            if (_instance == null)
            {
                lock (_syncRoot)
                {
                    if (_instance == null)
                    {
                        _instance = new Privilege();
                    }
                }
            }

            return _instance;
        }
Exemplo n.º 16
0
 public static void CheckPrivilege(Privilege privilege)
 {
     IUser user = HiContext.Current.User;
     if (user.IsAnonymous || (user.UserRole != UserRole.SiteManager))
     {
         HttpContext.Current.Response.Redirect(Globals.GetAdminAbsolutePath("/accessDenied.aspx?privilege=" + privilege.ToString()));
     }
     else
     {
         SiteManager manager = user as SiteManager;
         if (!manager.IsAdministrator && !manager.HasPrivilege((int) privilege))
         {
             HttpContext.Current.Response.Redirect(Globals.GetAdminAbsolutePath("/accessDenied.aspx?privilege=" + privilege.ToString()));
         }
     }
 }
Exemplo n.º 17
0
        // Pour la direction
        public Resultat<Dictionary<int, string>> GetAllFormateur(Privilege role)
        {
            return Resultat<Dictionary<int, string>>.SafeExecute<PlanningService>(
                result =>
                {
                    int roleId = (int)role;
                    Dictionary<int, string> dicoFormateurs = new Dictionary<int, string>();

                    var formateurs = (from c in context.Utilisateurs.OfType<Employe>() where c.RoleId == roleId select c).ToList();

                    foreach (var c in formateurs)
                    {
                        dicoFormateurs.Add(c.Id, c.Nom);
                    }

                    result.Valeur = dicoFormateurs;
                });
        }
Exemplo n.º 18
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;
        }
Exemplo n.º 19
0
        public static Sentence parse(String sentenc)
        {


            Sentence sentence = null;

            String patterSelect = "SELECT\\s(\\*|\\w+(?:,*\\w+)*)\\sFROM\\s(\\w+)\\sWHERE\\s(\\w+)([<|=|>])('[^',]+'|-?\\d+\\.?\\d*);";
            String patternSelectAll = "SELECT\\s(\\*|\\w+(?:,*\\w+)*)\\sFROM\\s(\\w+);";
            String patterDelete = "DELETE\\sFROM\\s(\\w+)\\sWHERE\\s(\\w+)([<|=|>])('[^',]+'|-?\\d+\\.?\\d*);";
            String patternInsert = "INSERT\\sINTO\\s(\\w+)\\sVALUES\\s\\(((?:'[^',]+'|-?\\d+\\.?\\d*)(?:,(?:'[^',]+'|-?\\d+\\.?\\d*))*)\\);";
            String patternUpdate = "UPDATE\\s(\\w+)\\sSET\\s(\\w+=(?:'[^',]+'|-?\\d+\\.?\\d*)(?:,?\\w+=(?:'[^',]+'|-?\\d+\\.?\\d*))*)\\sWHERE\\s(\\w+)([<|=|>])('[^',]+'|-?\\d+\\.?\\d*);";
            String patternCreateTable = "CREATE\\sTABLE\\s(\\w+)\\s\\((\\w+\\s[TEXT|INT|DOUBLE]+(?:,?\\w+\\s[TEXT|INT|DOUBLE]+)*)\\);";
            String patterDropTable = "DROP\\sTABLE\\s(\\w+);";

            String patternCreateSecurityProfile = "CREATE\\sSECURITY\\sPROFILE\\s(\\w+);";
            String patternDropSecurityProfile = "DROP\\sSECURITY\\sPROFILE\\s(\\w+);";
            String patternGrantPrivilege = "GRANT\\s(DELETE|INSERT|SELECT|UPDATE)\\sON\\s(\\w+)\\sTO\\s(\\w+);";
            String patternRevokePrivilege = "REVOKE\\s(DELETE|INSERT|SELECT|UPDATE)\\sON\\s(\\w+)\\sTO\\s(\\w+);";
            String patternAddUser = "******";
            String patternDeleteUser = "******";


            // For the select
            if (Regex.IsMatch(sentenc, patterSelect))
            {
                Match match = Regex.Match(sentenc, patterSelect);

                List<String> list = new List<String>();

                // List of columns
                list = stringToList(match.Groups[1].Value, ',');

                // Table name
                String table = match.Groups[2].Value;

                // Where creation

                Operator op = stringToOperator(match.Groups[4].Value);

                Where where = new Where(match.Groups[3].Value, op, match.Groups[5].Value);

                // Select creation
                sentence = new Select(table, list, where);
            }

            // For the selectAll
            else if (Regex.IsMatch(sentenc, patternSelectAll))
            {
                Match match = Regex.Match(sentenc, patternSelectAll);

                List<String> list = new List<String>();

                // List of columns
                list = stringToList(match.Groups[1].Value, ',');

                // Table name
                String table = match.Groups[2].Value;

                sentence = new SelectAll(table, list);

            }

            // For the delete
            else if (Regex.IsMatch(sentenc, patterDelete))
            {
                Match match = Regex.Match(sentenc, patterDelete);
                String table = match.Groups[1].Value;

                Operator op = stringToOperator(match.Groups[3].Value);

                Where where = new Where(match.Groups[2].Value, op, match.Groups[4].Value);

                sentence = new Delete(table, where);
            }

            // For the insert
            else if (Regex.IsMatch(sentenc, patternInsert))
            {
                Match match = Regex.Match(sentenc, patternInsert);
                String table = match.Groups[1].Value;

                List<String> list = new List<String>();
                // List of columns
                list = stringToList(match.Groups[2].Value, ',');

                sentence = new Insert(table, list);
            }

            // For the update 
            else if (Regex.IsMatch(sentenc, patternUpdate))
            {
                Match match = Regex.Match(sentenc, patternUpdate);
                String table = match.Groups[1].Value;


                List<String> list = new List<String>();

                String valuees = match.Groups[2].Value;
                // List of columns
                var tuple = listToTwoList(stringToList(valuees, ','));

                List<string> colum = tuple.Item1;
                List<string> values = tuple.Item2;


                Operator op = stringToOperator(match.Groups[4].Value);

                Where where = new Where(match.Groups[3].Value, op, match.Groups[5].Value);

                sentence = new Update(table, colum, values, where);
            }

            //For the create table
            else if (Regex.IsMatch(sentenc, patternCreateTable))
            {

                Match match = Regex.Match(sentenc, patternCreateTable);
                String table = match.Groups[1].Value;

                List<String> list = new List<String>();
                // List of columns
                list = stringToList(match.Groups[2].Value, ',');

                sentence = new CreateTable(table, list);
            }

            // For the drop table
            else if (Regex.IsMatch(sentenc, patterDropTable))
            {
                Match match = Regex.Match(sentenc, patterDropTable);
                String table = match.Groups[1].Value;

                sentence = new DropTable(table);
            }


            // For the Create security profile
            else if (Regex.IsMatch(sentenc, patternCreateSecurityProfile))
            {

                Match match = Regex.Match(sentenc, patternCreateSecurityProfile);
                String secutiryProfile = match.Groups[1].Value;


                sentence = new CreateSecurityProfile(secutiryProfile);
            }

            // For the Drop security profile
            else if (Regex.IsMatch(sentenc, patternDropSecurityProfile))
            {

                Match match = Regex.Match(sentenc, patternDropSecurityProfile);
                String secutiryProfile = match.Groups[1].Value;

                sentence = new DropSecurityProfile(secutiryProfile);
            }

            // For grant privilege
            else if (Regex.IsMatch(sentenc, patternGrantPrivilege))
            {

                Match match = Regex.Match(sentenc, patternGrantPrivilege);

                string typeString = match.Groups[1].Value;
                Privilege type = stringToType(typeString);

                string table = match.Groups[2].Value;
                string securityProfile = match.Groups[3].Value;

                sentence = new GrantPrivilege(type, table, securityProfile);
            }

            // For revoke privilege
            else if (Regex.IsMatch(sentenc, patternRevokePrivilege))
            {

                Match match = Regex.Match(sentenc, patternRevokePrivilege);

                string typeString = match.Groups[1].Value;
                Privilege type = stringToType(typeString);

                string table = match.Groups[2].Value;
                string securityProfile = match.Groups[3].Value;

                sentence = new RevokePrivilege(type, table, securityProfile);
            }

            // For Add user
            else if (Regex.IsMatch(sentenc, patternAddUser))
            {

                Match match = Regex.Match(sentenc, patternAddUser);
                string name = match.Groups[1].Value;
                string pass = match.Groups[2].Value;
                string securityProfile = match.Groups[3].Value;

                sentence = new AddUser(name, pass, securityProfile);
            }

            // For delete user
            else if (Regex.IsMatch(sentenc, patternDeleteUser))
            {
                Match match = Regex.Match(sentenc, patternDeleteUser);
                string name = match.Groups[1].Value;

                sentence = new DeleteUser(name);
            }

            return sentence;
        }
Exemplo n.º 20
0
 public UserPrivSet()
 {
     set = new Set<Privilege>();
     highestPriv = Privilege.Regular;
 }
Exemplo n.º 21
0
        /// <summary>
        /// По заданному Referral'у строит Options для SeacrhMany.
        /// </summary>
        public Options GetRefferalReturnOptions_SearchMany(Referral referral, Privilege[] privileges, Coding mqReferralStatus)
        {
            Options opt = GetRefferalReturnOptions_SearchOne(referral, privileges, null, mqReferralStatus);

            if (referral.EventsInfo != null && referral.EventsInfo.Source != null)
            {
                opt.EventsInfo.Source = new EventSource
                {
                    PlannedDate = referral.EventsInfo.Source.PlannedDate
                };
            }

            OptionData.options = opt;
            return opt;
        }
Exemplo n.º 22
0
 public static PrivilegeAttributes GetPrivilegeAttributes(this AccessTokenHandle accessTokenHandle, Privilege privilege)
 {
     return(Privileges.GetPrivilegeAttributes(privilege, GetPrivileges(accessTokenHandle)));
 }
Exemplo n.º 23
0
        /// <summary>
        /// You must have the CREATE USER system privilege.
        /// When you create a user with the CREATE USER statement, the user's privilege domain is empty.
        /// To log on to Oracle Database, a user must have the CREATE SESSION system privilege.
        /// Therefore, after creating a user, you should grant the user at least the CREATE SESSION system privilege.
        /// Please refer to GRANT for more information.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnSave_Click(object sender, EventArgs e)
        {
            Privilege privilege = new Privilege
            {
                Name = CREATE_USER
            };
            Boolean hasPermision = this.privilegeBLL.HasSystemPrivilege(this.currentUser.UserName, privilege);

            if (hasPermision)
            {
                String Username  = txtUsername.Text;
                String Password  = txtPassword.Text;
                String Password2 = txtPassword2.Text;
                String IsAdmin;
                if (CbxIsAdmin.Checked)
                {
                    IsAdmin = "y";
                }
                else
                {
                    IsAdmin = "";
                }
                if (Username == "" || Password == "" || Password2 == "")
                {
                    MessageBox.Show("Username and password not empty!");
                }
                else
                {
                    Boolean flag = false;
                    foreach (USER_MANAGEMENT ExistUser in this.view.GetAll())
                    {
                        if (ExistUser.USERNAME == Username)
                        {
                            flag = true;
                            break;
                        }
                    }
                    if (flag == true)
                    {
                        MessageBox.Show("Username  is realy exist!");
                    }
                    else
                    {
                        String          HashPassword = PasswordUtils.Get(Password);
                        DateTime        now          = DateTime.Now;
                        USER_MANAGEMENT user         = new USER_MANAGEMENT
                        {
                            USERNAME     = Username,
                            PASSWORD     = HashPassword,
                            CREATE_TIME  = now,
                            ADMIN_OPTION = IsAdmin
                        };

                        this.view.Add(user);
                        this.OracleView.AddOracleUser(Username, Password);
                        UpdateQoutaDromform();
                        AddProfileFromForm();
                        AddRoleFromForm();
                        AddTableSpaceFromForm();
                        CheckLockAccountFromForm();
                        ClearText();
                        MessageBox.Show("User created!");
                        Hide();
                    }
                }
            }
            else
            {
                MessageBox.Show(String.Join(" ", "You don't have", CREATE_USER, "privilege!"));
            }
        }
Exemplo n.º 24
0
 public Privilege Delete(Privilege itemToDelete)
 {
     _context.Privileges.Remove(itemToDelete);
     _context.SaveChanges();
     return(itemToDelete);
 }
Exemplo n.º 25
0
 /// <returns>Wether the given user exists and has the given priv.</returns>
 public bool IsUser(IrcUser user, Privilege priv)
 {
     return(HasPriv(user, priv));
 }
Exemplo n.º 26
0
 public static void LookupPrivilegeValue(Privilege privilege, out Luid luid)
 {
     LookupPrivilegeValue(null, privilege, out luid);
 }
Exemplo n.º 27
0
 public Privilege Update(Privilege itemToUpdate)
 {
     _context.Entry(itemToUpdate).State = EntityState.Modified;
     _context.SaveChanges();
     return(itemToUpdate);
 }
Exemplo n.º 28
0
        public static string GetPrivilegeName(Privilege privilege)
        {
            switch (privilege)
            {
            case Privilege.AssignPrimaryToken:
                return("SeAssignPrimaryTokenPrivilege");

            case Privilege.Audit:
                return("SeAuditPrivilege");

            case Privilege.Backup:
                return("SeBackupPrivilege");

            case Privilege.ChangeNotify:
                return("SeChangeNotifyPrivilege");

            case Privilege.CreateGlobal:
                return("SeCreateGlobalPrivilege");

            case Privilege.CreatePagefile:
                return("SeCreatePagefilePrivilege");

            case Privilege.CreatePermanent:
                return("SeCreatePermanentPrivilege");

            case Privilege.CreateSymbolicLink:
                return("SeCreateSymbolicLinkPrivilege");

            case Privilege.CreateToken:
                return("SeCreateTokenPrivilege");

            case Privilege.Debug:
                return("SeDebugPrivilege");

            case Privilege.EnableDelegation:
                return("SeEnableDelegationPrivilege");

            case Privilege.Impersonate:
                return("SeImpersonatePrivilege");

            case Privilege.IncreaseBasePriority:
                return("SeIncreaseBasePriorityPrivilege");

            case Privilege.IncreaseQuota:
                return("SeIncreaseQuotaPrivilege");

            case Privilege.IncreaseWorkingSet:
                return("SeIncreaseWorkingSetPrivilege");

            case Privilege.LoadDriver:
                return("SeLoadDriverPrivilege");

            case Privilege.LockMemory:
                return("SeLockMemoryPrivilege");

            case Privilege.MachineAccount:
                return("SeMachineAccountPrivilege");

            case Privilege.ManageVolume:
                return("SeManageVolumePrivilege");

            case Privilege.ProfileSingleProcess:
                return("SeProfileSingleProcessPrivilege");

            case Privilege.Relabel:
                return("SeRelabelPrivilege");

            case Privilege.RemoteShutdown:
                return("SeRemoteShutdownPrivilege");

            case Privilege.Restore:
                return("SeRestorePrivilege");

            case Privilege.Security:
                return("SeSecurityPrivilege");

            case Privilege.Shutdown:
                return("SeShutdownPrivilege");

            case Privilege.SyncAgent:
                return("SeSyncAgentPrivilege");

            case Privilege.SystemEnvironment:
                return("SeSystemEnvironmentPrivilege");

            case Privilege.SystemProfile:
                return("SeSystemProfilePrivilege");

            case Privilege.Systemtime:
                return("SeSystemtimePrivilege");

            case Privilege.TakeOwnership:
                return("SeTakeOwnershipPrivilege");

            case Privilege.Tcb:
                return("SeTcbPrivilege");

            case Privilege.TimeZone:
                return("SeTimeZonePrivilege");

            case Privilege.TrustedCredManAccess:
                return("SeTrustedCredManAccessPrivilege");

            case Privilege.Undock:
                return("SeUndockPrivilege");

            case Privilege.UnsolicitedInput:
                return("SeUnsolicitedInputPrivilege");

            default:
                throw new ArgumentException("Unknown parameter privilege value");
            }
        }
Exemplo n.º 29
0
 internal PrivilegeAndAttributes(Privilege privilege, PrivilegeAttributes privilegeAttributes)
 {
     this.privilege           = privilege;
     this.privilegeAttributes = privilegeAttributes;
 }
 public string AddDashPrivilege([FromBody] Privilege info)
 {
     return(manager.AddDashPrivileges(info.UserID, new List <string>(new string[] { info.DashID })));
 }
Exemplo n.º 31
0
 public TokenPrivilege(Privilege privilege, PrivilegeAttribute attributes)
 {
     Privilege  = privilege;
     Attributes = attributes;
 } // end constructor
Exemplo n.º 32
0
 internal static AdjustPrivilegeResult RemovePrivilege(AccessTokenHandle accessTokenHandle, Privilege privilege)
 {
     return(AdjustPrivilege(accessTokenHandle, privilege, PrivilegeAttributes.Removed));
 }
    public bool AuthorizeCore(HttpContextBase httpContext, Privilege privilege)
    {
        ApplicationUser user = UserService.FindByName(httpContext.User.Identity.Name);

        return(UserService.UserHasPrivilege(user.Id, privilege.ToString()));
    }
Exemplo n.º 34
0
 public static PrivilegeState GetPrivilegeState(this AccessTokenHandle accessTokenHandle, Privilege privilege)
 {
     return(GetPrivilegeState(GetPrivilegeAttributes(accessTokenHandle, privilege)));
 }
Exemplo n.º 35
0
 public static AdjustPrivilegeResult EnablePrivilege(this AccessTokenHandle accessTokenHandle, Privilege privilege)
 {
     return(Privileges.EnablePrivilege(accessTokenHandle, privilege));
 }
Exemplo n.º 36
0
    public static DataTable GetMobileInfos(int year, int month, string searchString, string hospital, string product)
    {
        //DateTime d = DateTime.Now;
        //if (!string.IsNullOrEmpty(date))
        //    d = Convert.ToDateTime(date);
        DataSet   ds = FlowInfoSrv.GetMobileInfo(year, month);
        DataTable dt = null;

        if (ds != null)
        {
            dt = ds.Tables[0];
            DataTable resDt = dt.Clone();
            UserInfo  user  = (UserInfo)HttpContext.Current.Session["user"];
            if (!Privilege.checkPrivilege(user))
            {
                foreach (DataRow dr in dt.Rows)
                {
                    resDt.Rows.Add(dr.ItemArray);
                    string ProductCode  = dr["ProductCode"].ToString();
                    string HospitalCode = dr["HospitalCode"].ToString();
                    string Sales        = dr["Sales"].ToString();

                    ds = FlowInfoSrv.GetMobileSimilarInfo(ProductCode, HospitalCode, Sales, year, month);
                    if (ds != null)
                    {
                        foreach (DataRow tempDr in ds.Tables[0].Rows)
                        {
                            if (tempDr != null)
                            {
                                resDt.Rows.Add(tempDr.ItemArray);
                            }
                        }
                    }
                }
                dt = resDt;
            }

            if (string.IsNullOrEmpty(searchString) && string.IsNullOrEmpty(hospital) &&
                string.IsNullOrEmpty(product))   //搜索字符为空时,不搜索,直接返回
            {
                return(dt);
            }
            else if (string.IsNullOrEmpty(searchString) && string.IsNullOrEmpty(hospital))
            {
                dt = dt.Clone();
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    if (checkProductEqual(row, product))
                    {
                        dt.Rows.Add(row.ItemArray);
                        continue;
                    }
                }
            }
            else if (string.IsNullOrEmpty(searchString) && string.IsNullOrEmpty(product))
            {
                dt = dt.Clone();
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    if (checkHospitalEqual(row, hospital))
                    {
                        dt.Rows.Add(row.ItemArray);
                        continue;
                    }
                }
            }
            else if (string.IsNullOrEmpty(hospital) && string.IsNullOrEmpty(product))
            {
                dt = dt.Clone();
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    if (checkUserOrDepartmentEqual(row, searchString))
                    {
                        dt.Rows.Add(row.ItemArray);
                        continue;
                    }
                }
            }
            else if (string.IsNullOrEmpty(hospital))
            {
                dt = dt.Clone();
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    if (checkUserOrDepartmentEqual(row, searchString) && checkProductEqual(row, product))
                    {
                        dt.Rows.Add(row.ItemArray);
                        continue;
                    }
                }
            }
            else if (string.IsNullOrEmpty(product))
            {
                dt = dt.Clone();
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    if (checkUserOrDepartmentEqual(row, searchString) && checkHospitalEqual(row, hospital))
                    {
                        dt.Rows.Add(row.ItemArray);
                        continue;
                    }
                }
            }
            else if (string.IsNullOrEmpty(searchString))
            {
                dt = dt.Clone();
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    if (checkHospitalEqual(row, hospital) && checkProductEqual(row, product))
                    {
                        dt.Rows.Add(row.ItemArray);
                        continue;
                    }
                }
            }
            else
            {
                dt = dt.Clone();
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    if (checkHospitalEqual(row, hospital) && checkProductEqual(row, product) && checkUserOrDepartmentEqual(row, searchString))
                    {
                        dt.Rows.Add(row.ItemArray);
                        continue;
                    }
                }
            }


            //dt = dt.Clone();
            //foreach (DataRow row in ds.Tables[0].Rows)
            //{
            //    if ((PinYinHelper.IsEqual(row["Department"].ToString(), searchString)
            //        || row["Department"].ToString().Trim().Contains(searchString)
            //        || PinYinHelper.IsEqual(row["Sector"].ToString(), searchString)
            //        || row["Sector"].ToString().Trim().Contains(searchString)
            //        || PinYinHelper.IsEqual(row["Sales"].ToString(), searchString)
            //        || row["Sales"].ToString().Trim().Contains(searchString)
            //        || PinYinHelper.IsEqual(row["Supervisor"].ToString(), searchString)
            //        || row["Supervisor"].ToString().Trim().Contains(searchString)
            //        || PinYinHelper.IsEqual(row["Manager"].ToString(), searchString)
            //        || row["Manager"].ToString().Trim().Contains(searchString)
            //        || PinYinHelper.IsEqual(row["Director"].ToString(), searchString)
            //        || row["Director"].ToString().Trim().Contains(searchString))
            //        && (PinYinHelper.IsEqual(row["Hospital"].ToString(), hospital)
            //        || row["Hospital"].ToString().Trim().Contains(hospital))
            //        && (PinYinHelper.IsEqual(row["Product"].ToString(), product)
            //        || row["Product"].ToString().Trim().Contains(product)))
            //    {
            //        dt.Rows.Add(row.ItemArray);
            //        continue;
            //    }
            //}
        }
        return(dt);
    }
Exemplo n.º 37
0
 public static PrivilegeAttributes GetPrivilegeAttributes(this Process process, Privilege privilege)
 {
     return(Privileges.GetPrivilegeAttributes(privilege, GetPrivileges(process)));
 }
Exemplo n.º 38
0
 public Student(string name, string email, string password, Privilege myPrivilege) : base(name, email, password, myPrivilege)
 {
 }
Exemplo n.º 39
0
 internal void Remove(Privilege flag)
 {
     set.Remove(flag);
     if (privMap[flag] == highestPrivLvl)
     {
         FindHighest();
     }
 }
Exemplo n.º 40
0
    public List <Privilege> GetPrivilege(InitializeModule.EnumCampus Campus, string sCondition, bool isDeafaultIncluded)
    {
//' returns a list of Classes instances based on the
//' data in the Privilege
        Connection_StringCLS MyConnection_string = new Connection_StringCLS(Campus);
        string sSQL = GetSQL();

        if (!string.IsNullOrEmpty(sCondition))
        {
            sSQL += sCondition;
        }
        SqlConnection Conn = new SqlConnection(MyConnection_string.Conn_string.ToString());
        SqlCommand    Cmd  = new SqlCommand(sSQL, Conn);

        Conn.Open();
        SqlDataReader    reader  = Cmd.ExecuteReader(CommandBehavior.CloseConnection);
        List <Privilege> results = new List <Privilege>();

        try
        {
//Default Value
            Privilege myPrivilege = new Privilege();
            if (isDeafaultIncluded)
            {
//Change the code here
                myPrivilege.PrivilegeID     = 0;
                myPrivilege.PriviligeNameEn = "Select Privilege ...";
                results.Add(myPrivilege);
            }
            while (reader.Read())
            {
                myPrivilege = new Privilege();
                if (reader[LibraryMOD.GetFieldName(PrivilegeIDFN)].Equals(DBNull.Value))
                {
                    myPrivilege.PrivilegeID = 0;
                }
                else
                {
                    myPrivilege.PrivilegeID = int.Parse(reader[LibraryMOD.GetFieldName(PrivilegeIDFN)].ToString());
                }
                myPrivilege.PrivilegeNameAr = reader[LibraryMOD.GetFieldName(PrivilegeNameArFN)].ToString();
                myPrivilege.PriviligeNameEn = reader[LibraryMOD.GetFieldName(PriviligeNameEnFN)].ToString();
                if (reader[LibraryMOD.GetFieldName(DefaultEffectFN)].Equals(DBNull.Value))
                {
                    myPrivilege.DefaultEffect = 0;
                }
                else
                {
                    myPrivilege.DefaultEffect = int.Parse(reader[LibraryMOD.GetFieldName(DefaultEffectFN)].ToString());
                }
                results.Add(myPrivilege);
            }
        }
        catch (Exception ex)
        {
            LibraryMOD.ShowErrorMessage(ex);
        }
        finally
        {
            reader.Close();
            reader.Dispose();
            Conn.Close();
            Conn.Dispose();
        }
        return(results);
    }
Exemplo n.º 41
0
 internal void Add(Privilege flag)
 {
     set.Add(flag);
     _PrivLevel lvl;
     if (privMap.TryGetValue(highestPriv, out lvl) && privMap[flag] > lvl)
     {
         highestPriv = flag;
         highestPrivLvl = lvl;
     }
 }
Exemplo n.º 42
0
        /// <summary>
        /// Run the application.
        /// </summary>
        /// <param name="phpversion">The PHP version to switch to.</param>
        /// <param name="configJson">Path to phpswitch.json config file.</param>
        /// <param name="verbose">Verbose value will be true or false.</param>
        public void Run(string phpversion, FileInfo configJson, bool verbose)
        {
            if (Privilege.IsAdmin() == false)
            {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    try
                    {
                        Privilege.RelaunchAsAdmin(phpversion, configJson, verbose);
                    }
                    catch (Exception ex)
                    {
                        ConsoleStyle.ErrorMessage(ex.Message);
                        Environment.Exit(5);
                    }
                }
                else
                {
                    ConsoleStyle.ErrorMessage("Administrator privileges are required!");
                    Environment.Exit(403);
                }
            }

            // display program header.
            ConsoleStyle.ProgramHeader();

            this.MPHPSwitchConfig            = new PHPSwitchConfig();
            this.MPHPSwitchConfig.PhpVersion = phpversion;
            this.MPHPSwitchConfig.Verbose    = verbose;

            this.ConsoleStyle = new ConsoleStyle(this.MPHPSwitchConfig);

            // start to kill php processes.
            var processTask = new ProcessTask();

            processTask.killPHP();

            FileCopier FileCopierClass = new FileCopier(this.MPHPSwitchConfig);

            // validate required folders and files.
            FileCopierClass.ValidateRequired(configJson);

            // services tasks (stop services). -----------------
            Services ServicesClass = new Services(this.MPHPSwitchConfig);

            if (ServicesClass.IsServiceExists())
            {
                this.MPHPSwitchConfig.RunServiceTask = true;
                ServicesClass.StopServices();
            }
            else
            {
                this.ConsoleStyle.WriteVerbose("--The services are not specify." + Environment.NewLine);
                this.MPHPSwitchConfig.RunServiceTask = false;
            }
            // end services tasks (stop services). -------------

            // remove php-running files and copy from selected version.
            FileCopierClass.StartCopyFiles();

            // services tasks (start services). ----------------
            if (this.MPHPSwitchConfig.RunServiceTask == true)
            {
                ServicesClass.StartServices();
            }
            // end services tasks (start services). ------------

            // success message and exit.
            ConsoleStyle.SuccessExit();
        }
Exemplo n.º 43
0
 private void FindHighest()
 {
     highestPrivLvl = _PrivLevel.Regular;
     foreach (Privilege priv in set)
     {
         _PrivLevel lvl = privMap[priv];
         if (lvl > highestPrivLvl)
         {
             highestPrivLvl = lvl;
         }
     }
     highestPriv = (Privilege) Enum.Parse(typeof (Privilege), highestPrivLvl.ToString());
     //highestPriv = (Privilege)highestPrivLvl;
 }
Exemplo n.º 44
0
 /// <summary>
 /// Fires when a User deletes a Channel flag from another User.
 /// </summary>
 protected virtual void OnFlagDeleted(IrcUser user, IrcChannel chan, Privilege priv, IrcUser target)
 {
 }
Exemplo n.º 45
0
 public bool this[Privilege flag]
 {
     get { return HasAtLeast(flag); }
 }
Exemplo n.º 46
0
 internal void FlagDeletedNotify(IrcUser user, IrcChannel chan, Privilege priv, IrcUser target)
 {
     chan.FlagDeletedNotify(user, priv, target);
     OnFlagDeleted(user, chan, priv, target);
 }
Exemplo n.º 47
0
        /// <summary>
        /// По заданному Referral'у строит Options для SeacrhOne.
        /// 
        /// Может можно сделать лучше?(проверки на null)
        /// 
        /// </summary>
        public Options GetRefferalReturnOptions_SearchOne(Referral referral, Privilege[] privileges, string idMq, Coding mqReferralStatus)
        {
            Options opt = new Options();
            opt.IdMq = idMq;

            if (referral.ReferralInfo != null)
            {
                opt.ReferralInfo = new ReferralInfo
                {
                    ProfileMedService = referral.ReferralInfo.ProfileMedService,
                    ReferralType = referral.ReferralInfo.ReferralType,
                    MqReferralStatus = mqReferralStatus
                };
            }
            if (referral.Target != null)
            { opt.Target = new ReferralTarget { Lpu = referral.Target.Lpu }; }

            if (referral.Source != null)
            { opt.Source = new ReferralSource { Lpu = referral.Source.Lpu }; }

            if (referral.ReferralSurvey != null)
            {
                opt.Survey = new Survey
                {
                    SurveyType = referral.ReferralSurvey.SurveyType,
                    SurveyOrgan = referral.ReferralSurvey.SurveyOrgan
                };
            }

            if (referral.Patient != null)
            {
                opt.Patient.Person = new Person
                {
                    BirthDate = referral.Patient.Person.BirthDate,
                    IdPatientMis = referral.Patient.Person.IdPatientMis
                };

                if (referral.Patient.Person.HumanName != null)
                {
                    opt.Patient.Person.HumanName = new HumanName
                    {
                        FamilyName = referral.Patient.Person.HumanName.FamilyName,
                        GivenName = referral.Patient.Person.HumanName.GivenName,
                        MiddleName = referral.Patient.Person.HumanName.MiddleName
                    };
                }
            }

            if (privileges != null)
            { opt.Patient.Privileges = (Privilege[])privileges.Clone(); }

            if (referral.EventsInfo != null && referral.EventsInfo.Target != null)
            {
                opt.EventsInfo.Target = new EventTarget
                {
                    IsReferralReviwed = referral.EventsInfo.Target.IsReferralReviwed,
                    ReceptionAppointDate = referral.EventsInfo.Target.ReceptionAppointDate
                };
            }

            OptionData.options = opt;
            return opt;
        }
Exemplo n.º 48
0
        internal static WindowsIdentity KerberosCertificateLogon(X509Certificate2 certificate)
        {
            int status;
            SafeHGlobalHandle         pSourceName   = null;
            SafeHGlobalHandle         pPackageName  = null;
            SafeHGlobalHandle         pLogonInfo    = null;
            SafeLsaLogonProcessHandle logonHandle   = null;
            SafeLsaReturnBufferHandle profileHandle = null;
            SafeCloseHandle           tokenHandle   = null;

            try
            {
                pSourceName = SafeHGlobalHandle.AllocHGlobal(NativeMethods.LsaSourceName.Length + 1);
                Marshal.Copy(NativeMethods.LsaSourceName, 0, pSourceName.DangerousGetHandle(), NativeMethods.LsaSourceName.Length);
                UNICODE_INTPTR_STRING sourceName = new UNICODE_INTPTR_STRING(NativeMethods.LsaSourceName.Length, NativeMethods.LsaSourceName.Length + 1, pSourceName.DangerousGetHandle());

                Privilege privilege = null;

                RuntimeHelpers.PrepareConstrainedRegions();
                // Try to get an impersonation token.
                try
                {
                    // Try to enable the TCB privilege if possible
                    try
                    {
                        privilege = new Privilege(Privilege.SeTcbPrivilege);
                        privilege.Enable();
                    }
                    catch (PrivilegeNotHeldException ex)
                    {
                        DiagnosticUtility.TraceHandledException(ex, TraceEventType.Information);
                    }

                    IntPtr dummy = IntPtr.Zero;
                    status = NativeMethods.LsaRegisterLogonProcess(ref sourceName, out logonHandle, out dummy);
                    if (NativeMethods.ERROR_ACCESS_DENIED == NativeMethods.LsaNtStatusToWinError(status))
                    {
                        // We don't have the Tcb privilege. The best we can hope for is to get an Identification token.
                        status = NativeMethods.LsaConnectUntrusted(out logonHandle);
                    }
                    if (status < 0) // non-negative numbers indicate success
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(NativeMethods.LsaNtStatusToWinError(status)));
                    }
                }
                finally
                {
                    // if reverting privilege fails, fail fast!
                    int    revertResult = -1;
                    string message      = null;
                    try
                    {
                        revertResult = privilege.Revert();
                        if (revertResult != 0)
                        {
                            message = SR.GetString(SR.RevertingPrivilegeFailed, new Win32Exception(revertResult));
                        }
                    }
                    finally
                    {
                        if (revertResult != 0)
                        {
                            DiagnosticUtility.FailFast(message);
                        }
                    }
                }

                // package name ("Kerberos")
                pPackageName = SafeHGlobalHandle.AllocHGlobal(NativeMethods.LsaKerberosName.Length + 1);
                Marshal.Copy(NativeMethods.LsaKerberosName, 0, pPackageName.DangerousGetHandle(), NativeMethods.LsaKerberosName.Length);
                UNICODE_INTPTR_STRING packageName = new UNICODE_INTPTR_STRING(NativeMethods.LsaKerberosName.Length, NativeMethods.LsaKerberosName.Length + 1, pPackageName.DangerousGetHandle());

                uint packageId = 0;
                status = NativeMethods.LsaLookupAuthenticationPackage(logonHandle, ref packageName, out packageId);
                if (status < 0) // non-negative numbers indicate success
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(NativeMethods.LsaNtStatusToWinError(status)));
                }

                // source context
                TOKEN_SOURCE sourceContext = new TOKEN_SOURCE();
                if (!NativeMethods.AllocateLocallyUniqueId(out sourceContext.SourceIdentifier))
                {
                    int dwErrorCode = Marshal.GetLastWin32Error();
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(dwErrorCode));
                }

                // SourceContext
                sourceContext.Name    = new char[8];
                sourceContext.Name[0] = 'W'; sourceContext.Name[1] = 'C'; sourceContext.Name[2] = 'F';

                // LogonInfo
                byte[] certRawData   = certificate.RawData;
                int    logonInfoSize = KERB_CERTIFICATE_S4U_LOGON.Size + certRawData.Length;
                pLogonInfo = SafeHGlobalHandle.AllocHGlobal(logonInfoSize);
                unsafe
                {
                    KERB_CERTIFICATE_S4U_LOGON *pInfo = (KERB_CERTIFICATE_S4U_LOGON *)pLogonInfo.DangerousGetHandle().ToPointer();
                    pInfo->MessageType       = KERB_LOGON_SUBMIT_TYPE.KerbCertificateS4ULogon;
                    pInfo->Flags             = NativeMethods.KERB_CERTIFICATE_S4U_LOGON_FLAG_CHECK_LOGONHOURS;
                    pInfo->UserPrincipalName = new UNICODE_INTPTR_STRING(0, 0, IntPtr.Zero);
                    pInfo->DomainName        = new UNICODE_INTPTR_STRING(0, 0, IntPtr.Zero);
                    pInfo->CertificateLength = (uint)certRawData.Length;
                    pInfo->Certificate       = new IntPtr(pLogonInfo.DangerousGetHandle().ToInt64() + KERB_CERTIFICATE_S4U_LOGON.Size);
                    Marshal.Copy(certRawData, 0, pInfo->Certificate, certRawData.Length);
                }

                QUOTA_LIMITS quotas  = new QUOTA_LIMITS();
                LUID         logonId = new LUID();
                uint         profileBufferLength;
                int          subStatus = 0;

                // Call LsaLogonUser
                status = NativeMethods.LsaLogonUser(
                    logonHandle,
                    ref sourceName,
                    SecurityLogonType.Network,
                    packageId,
                    pLogonInfo.DangerousGetHandle(),
                    (uint)logonInfoSize,
                    IntPtr.Zero,
                    ref sourceContext,
                    out profileHandle,
                    out profileBufferLength,
                    out logonId,
                    out tokenHandle,
                    out quotas,
                    out subStatus
                    );

                // LsaLogon has restriction (eg. password expired).  SubStatus indicates the reason.
                if ((uint)status == NativeMethods.STATUS_ACCOUNT_RESTRICTION && subStatus < 0)
                {
                    status = subStatus;
                }
                if (status < 0) // non-negative numbers indicate success
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(NativeMethods.LsaNtStatusToWinError(status)));
                }
                if (subStatus < 0) // non-negative numbers indicate success
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(NativeMethods.LsaNtStatusToWinError(subStatus)));
                }

                return(new WindowsIdentity(tokenHandle.DangerousGetHandle(), SecurityUtils.AuthTypeCertMap));
            }
            finally
            {
                if (tokenHandle != null)
                {
                    tokenHandle.Close();
                }
                if (pLogonInfo != null)
                {
                    pLogonInfo.Close();
                }
                if (profileHandle != null)
                {
                    profileHandle.Close();
                }
                if (pSourceName != null)
                {
                    pSourceName.Close();
                }
                if (pPackageName != null)
                {
                    pPackageName.Close();
                }
                if (logonHandle != null)
                {
                    logonHandle.Close();
                }
            }
        }
Exemplo n.º 49
0
 //public enum AccountTypes
 //{
 //    Assets=1
 //}
 /// <summary>
 /// 
 /// </summary>
 /// <param name="privilege"></param>
 /// <param name="operation"></param>
 /// <param name="Policy"></param>
 /// <returns></returns>
 public static bool HasPrivilege(Privilege privilege, Operation operation, string Policy)
 {
     string bits = Convert.ToString(Convert.ToInt32(Policy[(int)privilege].ToString()), 2);
     bits += EmptyPolicy;
     return bits[(int)operation] == '1' ? true : false;
 }
Exemplo n.º 50
0
 private static AdjustPrivilegeResult AdjustPrivilege(
     AccessTokenHandle accessTokenHandle,
     Privilege privilege,
     PrivilegeAttributes privilegeAttributes)
 {
     return AdjustPrivilege(accessTokenHandle, GetLuid(privilege), privilegeAttributes);
 }
Exemplo n.º 51
0
 internal static AdjustPrivilegeResult EnablePrivilege(AccessTokenHandle accessTokenHandle, Privilege privilege)
 {
     return AdjustPrivilege(accessTokenHandle, privilege, PrivilegeAttributes.Enabled);
 }
        public DbSyncPrivilegeDiff(Privilege privAin, Privilege privBin)
        {
            this.privA = privAin;
            this.privB = privBin;

            privAtrListA = new List<ObjectAtribute>();
            privAtrListB = new List<ObjectAtribute>();

            if (privA == null || privB == null)
            {
                if (privA != null)
                {
                    this.privilegeName = privA.Grantee + " " + privA.Privilege_type;
                    privAtrListA.Add(new ObjectAtribute("Object name", privA.Table_name, true));
                    privAtrListA.Add(new ObjectAtribute("Grantee", privA.Grantee, true));
                    //privAtrListA.Add(new ObjectAtribute("Is Grantable", privA.Is_grantable.ToString(), true));
                    privAtrListA.Add(new ObjectAtribute("Privilege type", privA.Privilege_type, true));
                }
                else if (privB != null)
                {
                    this.privilegeName = privB.Grantee + " " + privB.Privilege_type;
                    privAtrListB.Add(new ObjectAtribute("Object name", privB.Table_name, true));
                    privAtrListB.Add(new ObjectAtribute("Grantee", privB.Grantee, true));
                    //privAtrListB.Add(new ObjectAtribute("Is Grantable", privB.Is_grantable.ToString(), true));
                    privAtrListB.Add(new ObjectAtribute("Privilege type", privB.Privilege_type, true));
                }
                else this.privilegeName = "UNDEFINED";

            }
            if (privA != null && privB != null)
            {
                this.privilegeName = privA.Grantee + " " + privA.Privilege_type;
                if (privA.Grantee != privB.Grantee) diffGrantee = true;
                //if (privA.Is_grantable != privB.Is_grantable) diffISGrantable = true;
                if (privA.Table_name != privB.Table_name) diffTableNAme = true;
                if (privA.Privilege_type != privB.Privilege_type) diffprivilegeType = true;
                if (diffGrantee || diffISGrantable || diffprivilegeType || diffTableNAme) different = true;
                else different = false;

                ObjectAtribute cObjectname = new ObjectAtribute("Object name ", privA.Table_name, false);
                privAtrListA.Add(cObjectname);
                privAtrListB.Add(cObjectname);

                if (diffGrantee)
                {
                    ObjectAtribute cGranteA = new ObjectAtribute("Grantee ", privA.Grantee, true);
                    privAtrListA.Add(cGranteA);
                    ObjectAtribute cGranteB = new ObjectAtribute("Grantee ", privB.Grantee, true);
                    privAtrListB.Add(cGranteB);
                }
                else
                {
                    ObjectAtribute cGrantee = new ObjectAtribute("Grantee ", privB.Grantee, false);
                    privAtrListA.Add(cGrantee);
                    privAtrListB.Add(cGrantee);
                }

                /*if (diffISGrantable)
                {
                    ObjectAtribute cIsGrantableA = new ObjectAtribute("Is Grantable ", privA.Is_grantable.ToString(), true);
                    privAtrListA.Add(cIsGrantableA);
                    ObjectAtribute cIsGrantableB = new ObjectAtribute("Is Grantable ", privB.Is_grantable.ToString(), true);
                    privAtrListB.Add(cIsGrantableB);
                }
                else
                {
                    ObjectAtribute cIsGrantable = new ObjectAtribute("Is Grantable ", privB.Is_grantable.ToString(), false);
                    privAtrListA.Add(cIsGrantable);
                    privAtrListB.Add(cIsGrantable);
                }
                */
                if (diffprivilegeType)
                {
                    ObjectAtribute cPrivilegeTypeA = new ObjectAtribute("Privilege type ", privA.Privilege_type, true);
                    privAtrListA.Add(cPrivilegeTypeA);
                    ObjectAtribute cPrivilegeTypeB = new ObjectAtribute("Privilege type ", privB.Privilege_type, true);
                    privAtrListB.Add(cPrivilegeTypeB);
                }
                else
                {
                    ObjectAtribute cPrivilegeType = new ObjectAtribute("Privilege type ", privB.Privilege_type, false);
                    privAtrListA.Add(cPrivilegeType);
                    privAtrListB.Add(cPrivilegeType);
                }

            }
            else different = true;
        }
Exemplo n.º 53
0
        internal static CryptoKeySecurity GetKeySetSecurityInfo(SafeProvHandle hProv, AccessControlSections accessControlSections)
        {
            SecurityInfos securityInfos = (SecurityInfos)0;
            Privilege     privilege     = null;

            if ((accessControlSections & AccessControlSections.Owner) != AccessControlSections.None)
            {
                securityInfos |= SecurityInfos.Owner;
            }
            if ((accessControlSections & AccessControlSections.Group) != AccessControlSections.None)
            {
                securityInfos |= SecurityInfos.Group;
            }
            if ((accessControlSections & AccessControlSections.Access) != AccessControlSections.None)
            {
                securityInfos |= SecurityInfos.DiscretionaryAcl;
            }
            byte[] array = null;
            RuntimeHelpers.PrepareConstrainedRegions();
            int num;

            try
            {
                if ((accessControlSections & AccessControlSections.Audit) != AccessControlSections.None)
                {
                    securityInfos |= SecurityInfos.SystemAcl;
                    privilege      = new Privilege("SeSecurityPrivilege");
                    privilege.Enable();
                }
                array = Utils._GetKeySetSecurityInfo(hProv, securityInfos, out num);
            }
            finally
            {
                if (privilege != null)
                {
                    privilege.Revert();
                }
            }
            if (num == 0 && (array == null || array.Length == 0))
            {
                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NoSecurityDescriptor"));
            }
            if (num == 8)
            {
                throw new OutOfMemoryException();
            }
            if (num == 5)
            {
                throw new UnauthorizedAccessException();
            }
            if (num == 1314)
            {
                throw new PrivilegeNotHeldException("SeSecurityPrivilege");
            }
            if (num != 0)
            {
                throw new CryptographicException(num);
            }
            CommonSecurityDescriptor securityDescriptor = new CommonSecurityDescriptor(false, false, new RawSecurityDescriptor(array, 0), true);

            return(new CryptoKeySecurity(securityDescriptor));
        }
Exemplo n.º 54
0
        /// <summary>
        /// Performs file system operation with translating exceptions to those expected by WebDAV engine.
        /// </summary>
        /// <param name="item">Item on which operation is performed.</param>
        /// <param name="func">The action to be performed.</param>
        /// <param name="privilege">Privilege which is needed to perform the operation.
        /// If <see cref="UnauthorizedAccessException"/> is thrown  this method will convert it to
        /// <see cref="NeedPrivilegesException"/> exception and specify this privilege in it.</param>
        /// <typeparam name="T">Type of operation's result.</typeparam>
        /// <returns>Result returned by <paramref name="func"/>.</returns>
        public async Task <T> FileOperationAsync <T>(IHierarchyItemAsync item, Func <Task <T> > actionAsync, Privilege privilege)
        {
            try
            {
                using (impersonate())
                {
                    return(await actionAsync());
                }
            }
            catch (UnauthorizedAccessException)
            {
                NeedPrivilegesException ex = new NeedPrivilegesException("Not enough privileges");
                ex.AddRequiredPrivilege(item.Path, privilege);
                throw ex;
            }
            catch (IOException ex)
            {
                int hr = Marshal.GetHRForException(ex);
                if (hr == ERROR_DISK_FULL)
                {
                    throw new InsufficientStorageException();
                }

                throw new DavException(ex.Message, DavStatus.CONFLICT);
            }
        }
Exemplo n.º 55
0
        private static Luid GetLuid(Privilege privilege)
        {
            if (LuidDictionary.ContainsKey(privilege))
            {
                return LuidDictionary[privilege];
            }

            Luid luid = new Luid();
            if (!NativeMethods.LookupPrivilegeValue(String.Empty, PrivilegeConstantsDictionary[privilege], ref luid))
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            LuidDictionary.Add(privilege, luid);
            return luid;
        }
Exemplo n.º 56
0
        internal static void SetKeySetSecurityInfo(SafeProvHandle hProv, CryptoKeySecurity cryptoKeySecurity, AccessControlSections accessControlSections)
        {
            SecurityInfos securityInfos = (SecurityInfos)0;
            Privilege     privilege     = null;

            if ((accessControlSections & AccessControlSections.Owner) != AccessControlSections.None && cryptoKeySecurity._securityDescriptor.Owner != null)
            {
                securityInfos |= SecurityInfos.Owner;
            }
            if ((accessControlSections & AccessControlSections.Group) != AccessControlSections.None && cryptoKeySecurity._securityDescriptor.Group != null)
            {
                securityInfos |= SecurityInfos.Group;
            }
            if ((accessControlSections & AccessControlSections.Audit) != AccessControlSections.None)
            {
                securityInfos |= SecurityInfos.SystemAcl;
            }
            if ((accessControlSections & AccessControlSections.Access) != AccessControlSections.None && cryptoKeySecurity._securityDescriptor.IsDiscretionaryAclPresent)
            {
                securityInfos |= SecurityInfos.DiscretionaryAcl;
            }
            if (securityInfos == (SecurityInfos)0)
            {
                return;
            }
            int num = 0;

            RuntimeHelpers.PrepareConstrainedRegions();
            try
            {
                if ((securityInfos & SecurityInfos.SystemAcl) != (SecurityInfos)0)
                {
                    privilege = new Privilege("SeSecurityPrivilege");
                    privilege.Enable();
                }
                byte[] securityDescriptorBinaryForm = cryptoKeySecurity.GetSecurityDescriptorBinaryForm();
                if (securityDescriptorBinaryForm != null && securityDescriptorBinaryForm.Length != 0)
                {
                    num = Utils.SetKeySetSecurityInfo(hProv, securityInfos, securityDescriptorBinaryForm);
                }
            }
            finally
            {
                if (privilege != null)
                {
                    privilege.Revert();
                }
            }
            if (num == 5 || num == 1307 || num == 1308)
            {
                throw new UnauthorizedAccessException();
            }
            if (num == 1314)
            {
                throw new PrivilegeNotHeldException("SeSecurityPrivilege");
            }
            if (num == 6)
            {
                throw new NotSupportedException(Environment.GetResourceString("AccessControl_InvalidHandle"));
            }
            if (num != 0)
            {
                throw new CryptographicException(num);
            }
        }
Exemplo n.º 57
0
 public PrivilegeSetting(Privilege privilege, PrivilegeAttributes attributes)
 {
     Privilege  = privilege;
     Attributes = attributes;
 }
Exemplo n.º 58
0
 public PrivilegeCheckAttribute(Privilege privilege)
 {
     this.privilege = privilege;
 }
Exemplo n.º 59
0
 public static PrivilegeState GetPrivilegeState(this Process process, Privilege privilege)
 {
     return(GetPrivilegeState(GetPrivilegeAttributes(process, privilege)));
 }
Exemplo n.º 60
0
 /// <returns>Wether the given user exists and has at least the given priv.</returns>
 public bool IsUserAtLeast(string nick, Privilege priv)
 {
     return(IsUserAtLeast(m_irc.GetUser(nick), priv));
 }