Analyzing Policies

The following are examples of how to leverage some of the functions available from Policy Sentry. The functions selected are likely to be of most interest to other developers.

These ones relate to the analysis features.

Analyzing by access level

Determine if a policy has any actions with a given access level. This is particularly useful when determining who has ‘Permissions management’ level access.

analysis.analyze_by_access_level

#!/usr/bin/env python
from policy_sentry.shared.database import connect_db
from policy_sentry.analysis.analyze import analyze_by_access_level
import json

if __name__ == '__main__':
    db_session = connect_db('bundled')
    permissions_management_policy = {
        "Version": "2012-10-17",
        "Statement": [
            {
                "Effect": "Allow",
                "Action": [
                    # These ones are Permissions management
                    "ecr:SetRepositoryPolicy",
                    "secretsmanager:DeleteResourcePolicy",
                    "iam:UpdateAccessKey",
                    # These ones are not permissions management
                    "ecr:GetRepositoryPolicy",
                    "ecr:DescribeRepositories",
                    "ecr:ListImages",
                    "ecr:DescribeImages",
                ],
                "Resource": "*"
            }
        ]
    }
    permissions_management_actions = analyze_by_access_level(db_session, permissions_management_policy, "permissions-management")
    print(json.dumps(permissions_management_actions, indent=4))

"""
Output:

[
    'ecr:setrepositorypolicy',
    'iam:updateaccesskey',
    'secretsmanager:deleteresourcepolicy'
]
"""

Expanding actions from a policy file

#!/usr/bin/env python
from policy_sentry.shared.database import connect_db
from policy_sentry.util.policy_files import get_actions_from_policy
from policy_sentry.analysis.analyze import determine_actions_to_expand
import json

POLICY_JSON_TO_EXPAND = {
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "cloud9:*",
      ],
      "Resource": "*"
    }
  ]
}


if __name__ == '__main__':
    db_session = connect_db('bundled')
    requested_actions = get_actions_from_policy(POLICY_JSON_TO_EXPAND)
    expanded_actions = determine_actions_to_expand(db_session, requested_actions)
    print(json.dumps(expanded_actions, indent=4))


"""
Output:

[
    "cloud9:createenvironmentec2",
    "cloud9:createenvironmentmembership",
    "cloud9:deleteenvironment",
    "cloud9:deleteenvironmentmembership",
    "cloud9:describeenvironmentmemberships",
    "cloud9:describeenvironments",
    "cloud9:describeenvironmentstatus",
    "cloud9:getusersettings",
    "cloud9:listenvironments",
    "cloud9:updateenvironment",
    "cloud9:updateenvironmentmembership",
    "cloud9:updateusersettings"
]
"""