Exemplo n.º 1
0
    def get_rendered_policy(self, db_session, minimize=None):
        """
        Get the JSON rendered policy

        :param db_session: SQLAlchemy database session
        :param minimize: Reduce the character count of policies without creating overlap with other action names
        :rtype: dict
        """
        statements = []
        # Only set the actions to lowercase if minimize is provided
        all_actions = get_all_actions(db_session, lowercase=True)

        # render the policy
        for sid in self.sids:
            actions = self.sids[sid]["actions"]
            if len(actions) == 0:
                continue
            if minimize is not None and isinstance(minimize, int):
                actions = minimize_statement_actions(actions,
                                                     all_actions,
                                                     minchars=minimize)
            statements.append({
                "Sid": sid,
                "Effect": "Allow",
                "Action": actions,
                "Resource": self.sids[sid]["arn"],
            })
        policy = {"Version": POLICY_LANGUAGE_VERSION, "Statement": statements}
        return policy
Exemplo n.º 2
0
    def get_rendered_policy(self, minimize=None):
        """
        Get the JSON rendered policy

        :param minimize: Reduce the character count of policies without creating overlap with other action names
        :rtype: dict
        """
        statements = []
        # Only set the actions to lowercase if minimize is provided
        all_actions = get_all_actions(lowercase=True)

        # render the policy
        for sid in self.sids:
            actions = self.sids[sid]["actions"]
            if len(actions) == 0:
                logger.debug(f"No actions for sid {sid}")
                continue
            if minimize is not None and isinstance(minimize, int):
                logger.debug("Minimizing statements...")
                actions = minimize_statement_actions(actions,
                                                     all_actions,
                                                     minchars=minimize)
            logger.debug(f"Adding statement with SID {sid}")
            logger.debug(f"{sid} SID has the actions: {actions}")
            logger.debug(
                f"{sid} SID has the resources: {self.sids[sid]['arn']}")

            statements.append({
                "Sid": sid,
                "Effect": "Allow",
                "Action": actions,
                "Resource": self.sids[sid]["arn"],
            })
        policy = {"Version": POLICY_LANGUAGE_VERSION, "Statement": statements}
        return policy
Exemplo n.º 3
0
def print_policy(arn_dict_with_actions_and_resources,
                 db_session,
                 minimize=None):
    """
    Prints the least privilege policy
    """
    statement = []
    all_actions = get_all_actions(db_session)

    for sid in arn_dict_with_actions_and_resources:
        actions = arn_dict_with_actions_and_resources[sid]['actions']
        if minimize is not None and isinstance(minimize, int):
            actions = minimize_statement_actions(actions,
                                                 all_actions,
                                                 minchars=minimize)
        statement.append({
            "Sid":
            arn_dict_with_actions_and_resources[sid]['name'],
            "Effect":
            "Allow",
            "Action":
            actions,
            "Resource":
            arn_dict_with_actions_and_resources[sid]['arns']
        })

    policy = {"Version": POLICY_LANGUAGE_VERSION, "Statement": statement}
    return policy
Exemplo n.º 4
0
 def test_minimize_statement_actions(self):
     actions_to_minimize = [
         "kms:creategrant", "kms:createcustomkeystore",
         "ec2:authorizesecuritygroupegress",
         "ec2:authorizesecuritygroupingress"
     ]
     desired_result = ['ec2:authorizes*', 'kms:createc*', 'kms:createg*']
     all_actions = get_all_actions(db_session)
     minchars = None
     self.maxDiff = None
     # minimized_actions_list = minimize_statement_actions(desired_actions, all_actions, minchars)
     self.assertListEqual(
         sorted(
             minimize_statement_actions(actions_to_minimize, all_actions,
                                        minchars)), sorted(desired_result))
Exemplo n.º 5
0
    def get_rendered_policy(self, minimize=None):
        """
        Get the JSON rendered policy

        Arguments:
            minimize: Reduce the character count of policies without creating overlap with other action names
        Returns:
            Dictionary: The IAM Policy JSON
        """
        statements = []
        # Only set the actions to lowercase if minimize is provided
        all_actions = get_all_actions(lowercase=True)

        # render the policy
        for sid in self.sids:
            temp_actions = self.sids[sid]["actions"]
            if len(temp_actions) == 0:
                logger.debug(f"No actions for sid {sid}")
                continue
            actions = []
            if self.exclude_actions:
                for temp_action in temp_actions:
                    if temp_action.lower() in self.exclude_actions:
                        logger.debug(f"\tExcluded action: {temp_action}")
                    else:
                        if temp_action not in actions:
                            actions.append(temp_action)
            else:
                actions = temp_actions
            # temp_actions.clear()
            if minimize is not None and isinstance(minimize, int):
                logger.debug("Minimizing statements...")
                actions = minimize_statement_actions(actions,
                                                     all_actions,
                                                     minchars=minimize)
            logger.debug(f"Adding statement with SID {sid}")
            logger.debug(f"{sid} SID has the actions: {actions}")
            logger.debug(
                f"{sid} SID has the resources: {self.sids[sid]['arn']}")

            statements.append({
                "Sid": sid,
                "Effect": "Allow",
                "Action": actions,
                "Resource": self.sids[sid]["arn"],
            })
        policy = {"Version": POLICY_LANGUAGE_VERSION, "Statement": statements}
        return policy
Exemplo n.º 6
0
 def test_minimize_statement_actions(self):
     actions_to_minimize = [
         "kms:CreateGrant",
         "kms:CreateCustomKeyStore",
         "ec2:AuthorizeSecurityGroupEgress",
         "ec2:AuthorizeSecurityGroupIngress",
     ]
     desired_result = ["ec2:authorizes*", "kms:createc*", "kms:createg*"]
     all_actions = get_all_actions(lowercase=True)
     minchars = None
     self.maxDiff = None
     # minimized_actions_list = minimize_statement_actions(desired_actions, all_actions, minchars)
     self.assertListEqual(
         sorted(
             minimize_statement_actions(actions_to_minimize, all_actions,
                                        minchars)),
         sorted(desired_result),
     )
Exemplo n.º 7
0
 def test_minimize_statement_actions_funky_case(self):
     actions_to_minimize = [
         "kms:creategrant",
         "kms:createcustomkeystore",
         "ec2:authorizesecuritygroupegress",
         "ec2:authorizesecuritygroupingress",
     ]
     desired_result = ["ec2:authorizes*", "kms:createc*", "kms:createg*"]
     all_actions = get_all_actions(lowercase=True)
     minchars = None
     self.maxDiff = None
     # minimized_actions_list = minimize_statement_actions(desired_actions, all_actions, minchars)
     self.assertListEqual(
         sorted(
             minimize_statement_actions(actions_to_minimize, all_actions,
                                        minchars)),
         sorted(desired_result),
     )
Exemplo n.º 8
0
    def get_rendered_policy(self, minimize=None):
        """
        Get the JSON rendered policy

        Arguments:
            minimize: Reduce the character count of policies without creating overlap with other action names
        Returns:
            Dictionary: The IAM Policy JSON
        """
        statements = []
        # Only set the actions to lowercase if minimize is provided
        all_actions = get_all_actions(lowercase=True)

        # render the policy
        sids_to_be_changed = []
        for sid in self.sids:
            temp_actions = self.sids[sid]["actions"]
            if len(temp_actions) == 0:
                logger.debug(f"No actions for sid {sid}")
                continue
            actions = []
            if self.exclude_actions:
                for temp_action in temp_actions:
                    if temp_action.lower() in self.exclude_actions:
                        logger.debug(f"\tExcluded action: {temp_action}")
                    else:
                        if temp_action not in actions:
                            actions.append(temp_action)
            else:
                actions = temp_actions
            # temp_actions.clear()
            match_found = False
            if minimize is not None and isinstance(minimize, int):
                logger.debug("Minimizing statements...")
                actions = minimize_statement_actions(actions,
                                                     all_actions,
                                                     minchars=minimize)
                # searching in the existing statements
                # further minimizing the the output
                for stmt in statements:
                    if stmt["Resource"] == self.sids[sid]["arn"]:
                        stmt["Action"].extend(actions)
                        match_found = True
                        sids_to_be_changed.append(stmt["Sid"])
                        break
            logger.debug(f"Adding statement with SID {sid}")
            logger.debug(f"{sid} SID has the actions: {actions}")
            logger.debug(
                f"{sid} SID has the resources: {self.sids[sid]['arn']}")

            if not match_found:
                statements.append({
                    "Sid": sid,
                    "Effect": "Allow",
                    "Action": actions,
                    "Resource": self.sids[sid]["arn"],
                })

        if sids_to_be_changed:
            for stmt in statements:
                if stmt['Sid'] in sids_to_be_changed:
                    arn_details = parse_arn(stmt['Resource'][0])
                    resource_path = arn_details.get("resource_path")
                    resource_sid_segment = strip_special_characters(
                        f"{arn_details['resource']}{resource_path}")
                    stmt['Sid'] = create_policy_sid_namespace(
                        arn_details['service'], "Mult", resource_sid_segment)

        policy = {"Version": POLICY_LANGUAGE_VERSION, "Statement": statements}
        return policy