cloud-foundation-fabric/blueprints/cloud-operations/iam-delegated-role-grants/audit.py

78 lines
2.4 KiB
Python
Raw Permalink Normal View History

# Copyright 2023 Google LLC
2021-09-21 06:02:23 -07:00
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
2021-09-21 05:52:18 -07:00
import click
from googleapiclient.errors import Error
from googleapiclient import discovery
from oauth2client.client import GoogleCredentials
credentials = GoogleCredentials.get_application_default()
iam_service = discovery.build("iam", "v1", credentials=credentials)
SENSITIVE_PERMISSIONS = {
"resourcemanager.projects.setIamPolicy",
"resourcemanager.folders.setIamPolicy",
"resourcemanager.organizations.setIamPolicy",
}
def get_role_permissions(role):
2022-01-01 06:52:31 -08:00
if role.startswith("roles/"):
endpoint = iam_service.roles()
elif role.startswith("projects/"):
endpoint = iam_service.projects().roles()
elif role.startswith("organizations/"):
endpoint = iam_service.organizations().roles()
else:
raise Exception(f"Invalid role {role}")
2021-09-21 05:52:18 -07:00
2022-01-01 06:52:31 -08:00
response = endpoint.get(name=role).execute()
permissions = response.get("includedPermissions")
return permissions
2021-09-21 05:52:18 -07:00
@click.command()
@click.argument("file", type=click.File("r"))
def main(file):
2022-01-01 06:52:31 -08:00
"""Verify that the set of GCP roles in FILE does not include the
permission setIamPolicy at project, folder or organization level
2021-09-21 05:52:18 -07:00
2022-01-01 06:52:31 -08:00
This program authenticates against GCP using default application
credentials to query project and organization level roles.
2021-09-21 05:52:18 -07:00
2022-01-01 06:52:31 -08:00
"""
clean_roles = [x.rstrip(" \n") for x in file]
roles = (x for x in clean_roles if x)
2021-09-21 05:52:18 -07:00
2022-01-01 06:52:31 -08:00
allok = True
for role in roles:
try:
permissions = set(get_role_permissions(role))
except Error as e:
print(f"WARNING: can't read {role}: {e}")
allok = False
else:
matched_sensitive_permissions = SENSITIVE_PERMISSIONS & permissions
if matched_sensitive_permissions:
print(f"WARNING: {role} contains {matched_sensitive_permissions}")
allok = False
else:
print(f"{role} ok")
2021-09-21 05:52:18 -07:00
2022-01-01 06:52:31 -08:00
exit(0 if allok else 1)
2021-09-21 05:52:18 -07:00
if __name__ == "__main__":
2022-01-01 06:52:31 -08:00
main()