Esempio n. 1
0
    def get_grants_for_object(self, qualified_obj_name, obj_type_str,
                              global_privs=False):
        """ Retrieves the list of grants that the current user has that that
         have effect over a given object.

        qualified_obj_name[in]   String with the qualified name of the object.
        obj_type_str[in]         String with the type of the object that we are
                                 working with, must be one of 'ROUTINE',
                                 'TABLE' or 'DATABASE'.
        global_privs[in]         If True, the wildcard'%' host privileges are
                                 also taken into account


        This method takes the MySQL privilege hierarchy into account, e.g,
        if the qualified object is a table, it returns all the grant
        statements for this user regarding that table, as well as the grant
        statements for this user regarding the db where the table is at and
        finally any global grants that the user might have.

        Returns a list of strings with the grant statements.
        """

        grant_stm_lst = self.get_grants(global_privs)
        obj_name_regexp = re.compile(REGEXP_QUALIFIED_OBJ_NAME)
        m_obj = obj_name_regexp.match(qualified_obj_name)
        grants = []
        if not m_obj:
            raise UtilError("Cannot parse the specified qualified name "
                            "'{0}'".format(qualified_obj_name))
        else:
            db_name, obj_name = m_obj.groups()
            # Quote database and object name if necessary
            if not is_quoted_with_backticks(db_name):
                db_name = quote_with_backticks(db_name)
            if obj_name and obj_name != '*':
                if not is_quoted_with_backticks(obj_name):
                    obj_name = quote_with_backticks(obj_name)

            # For each grant statement look for the ones that apply to this
            # user and object
            for grant_stm in grant_stm_lst:
                grant_tpl = self._parse_grant_statement(grant_stm[0])
                if grant_tpl:
                    # Check if any of the privileges applies to this object
                    # and if it does then check if it inherited from this
                    # statement
                    if filter_grants(grant_tpl.privileges, obj_type_str):
                        # Add global grants
                        if grant_tpl.db == '*':
                            grants.append(grant_stm[0])
                            continue
                        # Add database level grants
                        if grant_tpl.db == db_name and grant_tpl.object == '*':
                            grants.append(grant_stm[0])
                            continue
                        # If it is an object, add existing object level grants
                        # as well.
                        if obj_name:
                            if (grant_tpl.db == db_name and
                                    grant_tpl.object == obj_name):
                                grants.append(grant_stm[0])

        return grants
Esempio n. 2
0
def check_grants(server_cnx_val, options, dict_of_objects):
    """Show list of privileges over a set of objects

    This function creates a GrantShow object which shows the list of
    users with (the optionally specified list of ) privileges over the
    specified set of objects.

    server_cnx_val[in]      Dictionary with the connection values to the
                            server.
    options[in]             Dictionary of options (verbosity, privileges,
                            show_mode).
    list_of_objects[in]     Dictionary of objects (set of databases, tables
                            and procedures) by database to check.

    """

    # Create server connection:
    server = connect_servers(server_cnx_val, None, options)[0]

    # Check user permissions to consult the grant information.
    _check_privileges(server)

    # Validate the dict of objects against our server.
    valid_dict_of_objects = validate_obj_type_dict(server, dict_of_objects)

    # Get optional list of required privileges
    req_privs = set(options['privileges']) if options['privileges'] else None

    # If we specify some privileges that are not valid for all the objects
    # print warning message stating that some will be ignored.
    if req_privs:
        for obj_type in valid_dict_of_objects:
            # get list of privileges that applies to the object type
            filtered_req_privs = filter_grants(req_privs, obj_type)
            # if the size of the set is different that means that some of the
            # privileges cannot be applied to this object type, print warning
            if len(filtered_req_privs) != len(req_privs):
                if obj_type.upper() == DATABASE_TYPE:
                    obj_lst = [obj_tpl[0] for obj_tpl in
                               valid_dict_of_objects[obj_type]]
                else:
                    obj_lst = [".".join(obj_tpl) for obj_tpl in
                               valid_dict_of_objects[obj_type]]
                obj_lst_str = join_and_build_str(obj_lst)
                missing_privs = sorted(req_privs - filtered_req_privs)
                priv_str = join_and_build_str(missing_privs)
                verb = "do" if len(missing_privs) > 1 else "does"
                print("# WARNING: {0} {1} not apply to {2}s "
                      "and will be ignored for: {3}.".format(
                          priv_str, verb, obj_type.lower(), obj_lst_str))

    # get the grantee information dictionary
    grantee_info_dict = get_grantees(server, valid_dict_of_objects,
                                     req_privileges=req_privs)

    # Print the information
    obj_type_lst = [DATABASE_TYPE, TABLE_TYPE, ROUTINE_TYPE]
    for obj_type in obj_type_lst:
        if obj_type in grantee_info_dict:
            # Sort by object name
            for obj_name in sorted(grantee_info_dict[obj_type]):
                print("\n# {0} {1}:".format(obj_type, obj_name))
                if options['show_mode'] == 'users':
                    # Sort by grantee name
                    output_str = ", ".join(
                        sorted(grantee_info_dict[obj_type][obj_name].keys()))
                    print("# - {0}".format(output_str))
                elif options['show_mode'] == 'user_grants':
                    # Sort by grantee name
                    for grantee, priv_set in sorted(
                            grantee_info_dict[obj_type][obj_name].iteritems()):
                        # print privileges sorted by name
                        print("# - {0} : {1}".format(
                            grantee, ", ".join(sorted(priv_set))))
                else:  # raw mode
                    # Sort by grantee name
                    for grantee in sorted(
                            grantee_info_dict[obj_type][obj_name].keys()):
                        user = User(server, grantee)
                        grant_stms = sorted(
                            user.get_grants_for_object(obj_name, obj_type))
                        if grant_stms:
                            print("# - For {0}".format(grantee))
                        for grant_stm in grant_stms:
                            print("{0}".format(grant_stm))