| 1 |
# -*- coding: utf-8 -*- |
| 2 |
|
| 3 |
# This code is part of Ansible, but is an independent component. |
| 4 |
# This particular file snippet, and this file snippet only, is BSD licensed. |
| 5 |
# Modules you write using this snippet, which is embedded dynamically by Ansible |
| 6 |
# still belong to the author of the module, and may assign their own license |
| 7 |
# to the complete work. |
| 8 |
# |
| 9 |
# Copyright (c), Michael DeHaan <[email protected]>, 2012-2013 |
| 10 |
# All rights reserved. |
| 11 |
# |
| 12 |
# Redistribution and use in source and binary forms, with or without modification, |
| 13 |
# are permitted provided that the following conditions are met: |
| 14 |
# |
| 15 |
# * Redistributions of source code must retain the above copyright |
| 16 |
# notice, this list of conditions and the following disclaimer. |
| 17 |
# * Redistributions in binary form must reproduce the above copyright notice, |
| 18 |
# this list of conditions and the following disclaimer in the documentation |
| 19 |
# and/or other materials provided with the distribution. |
| 20 |
# |
| 21 |
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND |
| 22 |
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED |
| 23 |
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. |
| 24 |
# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
| 25 |
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, |
| 26 |
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS |
| 27 |
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
| 28 |
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE |
| 29 |
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| 30 |
|
| 31 |
from functools import cmp_to_key |
| 32 |
|
| 33 |
from ansible.module_utils.common.text.converters import to_text |
| 34 |
|
| 35 |
|
| 36 |
def _canonify_root_arn(arn): |
| 37 |
# There are multiple ways to specifiy delegation of access to an account |
| 38 |
# https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html#principal-accounts |
| 39 |
if arn.startswith("arn:aws:iam::") and arn.endswith(":root"): |
| 40 |
arn = arn.split(":")[4] |
| 41 |
return arn |
| 42 |
|
| 43 |
|
| 44 |
def _canonify_policy_dict_item(item, key): |
| 45 |
""" |
| 46 |
Converts special cases where there are multiple ways to write the same thing into a single form |
| 47 |
""" |
| 48 |
# There are multiple ways to specify anonymous principals |
| 49 |
# https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html#principal-anonymous |
| 50 |
if key in ["NotPrincipal", "Principal"]: |
| 51 |
if item == "*": |
| 52 |
return {"AWS": "*"} |
| 53 |
return item |
| 54 |
|
| 55 |
|
| 56 |
def _tuplify_list(element): |
| 57 |
if isinstance(element, list): |
| 58 |
return tuple(element) |
| 59 |
return element |
| 60 |
|
| 61 |
|
| 62 |
def _hashable_policy(policy, policy_list): |
| 63 |
""" |
| 64 |
Takes a policy and returns a list, the contents of which are all hashable and sorted. |
| 65 |
Example input policy: |
| 66 |
{'Version': '2012-10-17', |
| 67 |
'Statement': [{'Action': 's3:PutObjectAcl', |
| 68 |
'Sid': 'AddCannedAcl2', |
| 69 |
'Resource': 'arn:aws:s3:::test_policy/*', |
| 70 |
'Effect': 'Allow', |
| 71 |
'Principal': {'AWS': ['arn:aws:iam::XXXXXXXXXXXX:user/username1', 'arn:aws:iam::XXXXXXXXXXXX:user/username2']} |
| 72 |
}]} |
| 73 |
Returned value: |
| 74 |
[('Statement', ((('Action', ('s3:PutObjectAcl',)), |
| 75 |
('Effect', ('Allow',)), |
| 76 |
('Principal', ('AWS', (('arn:aws:iam::XXXXXXXXXXXX:user/username1',), ('arn:aws:iam::XXXXXXXXXXXX:user/username2',)))), |
| 77 |
('Resource', ('arn:aws:s3:::test_policy/*',)), ('Sid', ('AddCannedAcl2',)))), |
| 78 |
('Version', ('2012-10-17',)))] |
| 79 |
|
| 80 |
""" |
| 81 |
# Amazon will automatically convert bool and int to strings for us |
| 82 |
if isinstance(policy, bool): |
| 83 |
return tuple([str(policy).lower()]) |
| 84 |
elif isinstance(policy, int): |
| 85 |
return tuple([str(policy)]) |
| 86 |
|
| 87 |
if isinstance(policy, list): |
| 88 |
for each in policy: |
| 89 |
hashed_policy = _hashable_policy(each, []) |
| 90 |
tupleified = _tuplify_list(hashed_policy) |
| 91 |
policy_list.append(tupleified) |
| 92 |
elif isinstance(policy, str) or isinstance(policy, bytes): |
| 93 |
policy = to_text(policy) |
| 94 |
# convert root account ARNs to just account IDs |
| 95 |
policy = _canonify_root_arn(policy) |
| 96 |
return [policy] |
| 97 |
elif isinstance(policy, dict): |
| 98 |
# Sort the keys to ensure a consistent order for later comparison |
| 99 |
sorted_keys = list(policy.keys()) |
| 100 |
sorted_keys.sort() |
| 101 |
for key in sorted_keys: |
| 102 |
# Converts special cases to a consistent form |
| 103 |
element = _canonify_policy_dict_item(policy[key], key) |
| 104 |
hashed_policy = _hashable_policy(element, []) |
| 105 |
tupleified = _tuplify_list(hashed_policy) |
| 106 |
policy_list.append((key, tupleified)) |
| 107 |
# ensure we aren't returning deeply nested structures of length 1 |
| 108 |
if len(policy_list) == 1 and isinstance(policy_list[0], tuple): |
| 109 |
policy_list = policy_list[0] |
| 110 |
if isinstance(policy_list, list): |
| 111 |
policy_list.sort(key=cmp_to_key(_py3cmp)) |
| 112 |
return policy_list |
| 113 |
|
| 114 |
|
| 115 |
def _py3cmp(a, b): |
| 116 |
"""Python 2 can sort lists of mixed types. Strings < tuples. Without this function this fails on Python 3.""" |
| 117 |
try: |
| 118 |
if a > b: |
| 119 |
return 1 |
| 120 |
elif a < b: |
| 121 |
return -1 |
| 122 |
else: |
| 123 |
return 0 |
| 124 |
except TypeError as e: |
| 125 |
# check to see if they're tuple-string |
| 126 |
# always say strings are less than tuples (to maintain compatibility with python2) |
| 127 |
str_ind = to_text(e).find("str") |
| 128 |
tup_ind = to_text(e).find("tuple") |
| 129 |
if -1 not in (str_ind, tup_ind): |
| 130 |
if str_ind < tup_ind: |
| 131 |
return -1 |
| 132 |
elif tup_ind < str_ind: |
| 133 |
return 1 |
| 134 |
raise |
| 135 |
|
| 136 |
|
| 137 |
def compare_policies(current_policy, new_policy, default_version="2008-10-17"): |
| 138 |
"""Compares the existing policy and the updated policy |
| 139 |
Returns True if there is a difference between policies. |
| 140 |
""" |
| 141 |
# https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_version.html |
| 142 |
if default_version: |
| 143 |
if isinstance(current_policy, dict): |
| 144 |
current_policy = current_policy.copy() |
| 145 |
current_policy.setdefault("Version", default_version) |
| 146 |
if isinstance(new_policy, dict): |
| 147 |
new_policy = new_policy.copy() |
| 148 |
new_policy.setdefault("Version", default_version) |
| 149 |
|
| 150 |
return set(_hashable_policy(new_policy, [])) != set(_hashable_policy(current_policy, [])) |