Exemple #1
0
    def add_by_arn_and_access_level(self,
                                    arn_list,
                                    access_level,
                                    conditions_block=None):
        """
        This adds the user-supplied ARN(s), service prefixes, access levels, and condition keys (if applicable) given
        by the user. It derives the list of IAM actions based on the user's requested ARNs and access levels.

        Arguments:
            arn_list: Just a list of resource ARNs.
            access_level: "Read", "List", "Tagging", "Write", or "Permissions management"
            conditions_block: Optionally, a condition block with one or more conditions
        """
        for arn in arn_list:
            service_prefix = get_service_from_arn(arn)
            service_action_data = get_action_data(service_prefix, "*")
            for service_prefix in service_action_data:
                for row in service_action_data[service_prefix]:
                    if (does_arn_match(arn, row["resource_arn_format"])
                            and row["access_level"] == access_level):
                        raw_arn_format = row["resource_arn_format"]
                        resource_type_name = get_resource_type_name_with_raw_arn(
                            raw_arn_format)
                        sid_namespace = create_policy_sid_namespace(
                            service_prefix, access_level, resource_type_name)
                        actions = get_actions_with_arn_type_and_access_level(
                            service_prefix, resource_type_name, access_level)
                        # Make supplied actions lowercase
                        # supplied_actions = [x.lower() for x in actions]
                        supplied_actions = actions.copy()
                        dependent_actions = get_dependent_actions(
                            supplied_actions)
                        # List comprehension to get all dependent actions that are not in the supplied actions.
                        dependent_actions = [
                            x for x in dependent_actions
                            if x not in supplied_actions
                        ]
                        if len(dependent_actions) > 0:
                            for dep_action in dependent_actions:
                                self.add_action_without_resource_constraint(
                                    dep_action)
                                # self.add_action_without_resource_constraint(
                                #     str.lower(dep_action)
                                # )

                        temp_sid_dict = {
                            "arn": [arn],
                            "service": service_prefix,
                            "access_level": access_level,
                            "arn_format": raw_arn_format,
                            "actions": actions,
                            "conditions": [],  # TODO: Add conditions
                        }
                        if sid_namespace in self.sids.keys():
                            # If the ARN already exists there, skip it.
                            if arn not in self.sids[sid_namespace]["arn"]:
                                self.sids[sid_namespace]["arn"].append(arn)
                        # If it did not exist before at all, create it.
                        else:
                            self.sids[sid_namespace] = temp_sid_dict
    def test_get_actions_with_arn_type_and_access_level_case_5(self):
        """querying.actions.get_actions_with_arn_type_and_access_level with arn type"""

        output = get_actions_with_arn_type_and_access_level(
            "all", "object", "List")

        self.assertTrue(len(output) == 2)
Exemple #3
0
 def test_get_actions_with_arn_type_and_access_level_case_4(self):
     """querying.actions.get_actions_with_arn_type_and_access_level with arn type"""
     desired_output = [
         'secretsmanager:ListSecrets'
     ]
     output = get_actions_with_arn_type_and_access_level(
         "secretsmanager", "*", "List"
     )
     self.assertListEqual(desired_output, output)
 def test_get_actions_with_arn_type_and_access_level_case_3(self):
     """querying.actions.get_actions_with_arn_type_and_access_level with arn type"""
     desired_output = ['s3:PutAccountPublicAccessBlock']
     output = get_actions_with_arn_type_and_access_level(
         # "ram", "resource-share", "Write"
         "s3",
         "*",
         "Permissions management")
     self.assertListEqual(desired_output, output)
 def test_get_actions_with_arn_type_and_access_level_case_2(self):
     """querying.actions.get_actions_with_arn_type_and_access_level with arn type"""
     desired_output = [
         'ssm:DeleteParameter', 'ssm:DeleteParameters',
         'ssm:LabelParameterVersion', 'ssm:PutParameter'
     ]
     output = get_actions_with_arn_type_and_access_level(
         "ssm", "parameter", "Write")
     self.assertListEqual(desired_output, output)
 def test_get_actions_with_arn_type_and_access_level_case_1(self):
     """querying.actions.get_actions_with_arn_type_and_access_level"""
     desired_output = [
         's3:DeleteBucketPolicy', 's3:PutBucketAcl', 's3:PutBucketPolicy',
         's3:PutBucketPublicAccessBlock'
     ]
     output = get_actions_with_arn_type_and_access_level(
         # "ram", "resource-share", "Write"
         "s3",
         "bucket",
         "Permissions management")
     self.maxDiff = None
     self.assertListEqual(desired_output, output)
Exemple #7
0
 def test_get_actions_with_arn_type_and_access_level(self):
     """test_get_actions_with_arn_type_and_access_level: Tests a function that gets a list of
     actions in a service under different access levels, specific to an ARN format."""
     desired_output = [
         'ram:associateresourceshare', 'ram:createresourceshare',
         'ram:deleteresourceshare', 'ram:disassociateresourceshare',
         'ram:updateresourceshare'
     ]
     output = get_actions_with_arn_type_and_access_level(
         db_session, "ram", "resource-share", "Permissions management")
     print(output)
     self.maxDiff = None
     self.assertListEqual(desired_output, output)
Exemple #8
0
 def test_get_actions_with_arn_type_and_access_level(self):
     """querying.actions.get_actions_with_arn_type_and_access_level"""
     desired_output = [
         "ram:AssociateResourceShare",
         # 'ram:createresourceshare',
         "ram:DeleteResourceShare",
         "ram:DisassociateResourceShare",
         "ram:UpdateResourceShare",
     ]
     output = get_actions_with_arn_type_and_access_level(
         db_session, "ram", "resource-share", "Permissions management")
     print(output)
     self.maxDiff = None
     self.assertListEqual(desired_output, output)
Exemple #9
0
def query_action_table(name,
                       service,
                       access_level,
                       condition,
                       resource_type,
                       fmt="json"):
    """Query the Action Table from the Policy Sentry database.
    Use this one when leveraging Policy Sentry as a library."""
    if os.path.exists(LOCAL_DATASTORE_FILE_PATH):
        logger.info(
            f"Using the Local IAM definition: {LOCAL_DATASTORE_FILE_PATH}. To leverage the bundled definition instead, remove the folder $HOME/.policy_sentry/"
        )
    else:
        # Otherwise, leverage the datastore inside the python package
        logger.debug("Leveraging the bundled IAM Definition.")
    # Actions on all services
    if service == "all":
        all_services = get_all_service_prefixes()
        if access_level:
            level = transform_access_level_text(access_level)
            print(f"{access_level} actions across ALL services:\n")
            output = []
            for serv in all_services:
                result = get_actions_with_access_level(serv, level)
                output.extend(result)
            print(yaml.dump(output)) if fmt == "yaml" else [
                print(result) for result in output
            ]
        # Get a list of all services in the database
        else:
            print("All services in the database:\n")
            output = all_services
            print(yaml.dump(output)) if fmt == "yaml" else [
                print(item) for item in output
            ]
    elif name is None and access_level and not resource_type:
        print(
            f"All IAM actions under the {service} service that have the access level {access_level}:"
        )
        level = transform_access_level_text(access_level)
        output = get_actions_with_access_level(service, level)
        print(yaml.dump(output)) if fmt == "yaml" else [
            print(json.dumps(output, indent=4))
        ]
    elif name is None and access_level and resource_type:
        print(
            f"{service} {access_level.upper()} actions that have the resource type {resource_type.upper()}:"
        )
        access_level = transform_access_level_text(access_level)
        output = get_actions_with_arn_type_and_access_level(
            service, resource_type, access_level)
        print(yaml.dump(output)) if fmt == "yaml" else [
            print(json.dumps(output, indent=4))
        ]
    # Get a list of all IAM actions under the service that support the specified condition key.
    elif condition:
        print(
            f"IAM actions under {service} service that support the {condition} condition only:"
        )
        output = get_actions_matching_condition_key(service, condition)
        print(yaml.dump(output)) if fmt == "yaml" else [
            print(json.dumps(output, indent=4))
        ]
    # Get a list of IAM Actions under the service that only support resources = "*"
    # (i.e., you cannot restrict it according to ARN)
    elif resource_type:
        print(
            f"IAM actions under {service} service that have the resource type {resource_type}:"
        )
        output = get_actions_matching_arn_type(service, resource_type)
        print(yaml.dump(output)) if fmt == "yaml" else [
            print(json.dumps(output, indent=4))
        ]
    elif name and access_level is None:
        output = get_action_data(service, name)
        print(yaml.dump(output)) if fmt == "yaml" else [
            print(json.dumps(output, indent=4))
        ]
    else:
        # Get a list of all IAM Actions available to the service
        output = get_actions_for_service(service)
        print(f"ALL {service} actions:")
        print(yaml.dump(output)) if fmt == "yaml" else [
            print(item) for item in output
        ]
    return output
#!/usr/bin/env python
from policy_sentry.shared.database import connect_db
from policy_sentry.querying.actions import get_actions_with_arn_type_and_access_level
import json

if __name__ == '__main__':
    db_session = connect_db('bundled')
    output = get_actions_with_arn_type_and_access_level(
        db_session, "ram", "resource-share", "Permissions management")
    print(json.dumps(output, indent=4))
"""
Output:

[
    'ram:associateresourceshare',
    'ram:createresourceshare',
    'ram:deleteresourceshare',
    'ram:disassociateresourceshare',
    'ram:updateresourceshare'
]
"""