Repository: spotify/gcp-audit Branch: master Commit: 2d17578e8845 Files: 21 Total size: 37.9 KB Directory structure: gitextract_bn9_4qd9/ ├── .gitignore ├── CONTRIBUTORS ├── LICENSE ├── MANIFEST.in ├── NOTICE ├── README.md ├── gcp_audit/ │ ├── __init__.py │ ├── gcp_audit.py │ ├── rules/ │ │ ├── bucket_objects/ │ │ │ └── world-writable-default-permissions.json │ │ ├── buckets/ │ │ │ └── world-writable-buckets.json │ │ ├── cloudsql/ │ │ │ └── allips.json │ │ └── firewalls/ │ │ ├── allips-multiports-list.json │ │ ├── allips-multiports-range.json │ │ ├── allips-multiports-range.yaml │ │ ├── allips-mysql.json │ │ └── allips-notags.json │ └── util/ │ ├── __init__.py │ ├── filter.py │ └── gcp.py ├── requirements.txt └── setup.py ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ *.pyc venv/ test_configs/* results.json dist *.egg-info .DS_Store ================================================ FILE: CONTRIBUTORS ================================================ Patrik Nordlen Fredrik Gustafsson Jeff Gibat Gianluca Brindisi ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] 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. ================================================ FILE: MANIFEST.in ================================================ recursive-include gcp_audit/rules * include README.md include LICENSE include NOTICE include CONTRIBUTORS ================================================ FILE: NOTICE ================================================ GCP Audit Copyright (c) 2016-2017 Spotify AB ================================================ FILE: README.md ================================================ # gcp-audit **This code purely exists for posterity, it is no longer developed or maintained. Please look to [Forseti Security](https://forsetisecurity.org/) for your GCP auditing needs. The PyPi package gcp-audit is not the same thing.** --- A tool for auditing security properties of GCP projects. Inspired by [Scout2]. `gcp-audit` takes a set of projects and audits them for common issues as defined by its ruleset. Issues can include, but are certainly not limited to, storage buckets with read/write permissions for anyone and compute engine instances with services exposed to the Internet. The results are written to a report containing information about issues that were found along with information about which objects these issues were found in so that it's possible to address the problems. [Scout2]: `gcp-audit` is currently in alpha status. We are actively improving it and Spotify's production environment is our current test suite. ## Installation Run `pip install git+https://github.com/spotify/gcp-audit.git`. ## Usage ```bash usage: gcp-audit.py [-h] [-c CHECKS] [-k KEYFILE] [-o OUTPUT] [-p PROJECTS] A tool for auditing security properties of GCP projects. optional arguments: -h, --help show this help message and exit -c CHECKS, --checks CHECKS comma separated list of types of checks to run -k KEYFILE, --keyfile KEYFILE keyfile to use for GCP credentials -o OUTPUT, --output OUTPUT file to output results to -p PROJECTS, --projects PROJECTS comma separated list of GCP projects to audit ``` ## Prerequisites Make sure you have virtualenv (on OSX: `brew install virtualenv`) then run ```bash virtualenv env env/bin/pip install gcp-audit GOOGLE_APPLICATION_CREDENTIALS=YourCredentials-abc123.json env/bin/python gcp-audit ``` Alternatively you can specify your credentials using the `-k` switch. Make sure your credentials have the `Organization viewer` role. Supported Python versions: 2.7+ ## Development To contribute and develop, clone the project inside a virtualenv and install all the dependencies with `pip install -r requirements.txt`. ## Rules Rules are put in a [subdirectory] under `rules/`. The subdirectories are based on the check category. Currently checks for the following categories exist: - `bucket_objects` - objects within buckets (as opposed to the buckets themselves) - `buckets` - buckets. :) - `firewalls` - GCP firewall settings - `cloudsql` - CloudSQL instances The rule language is fairly simplistic and can be done using YAML (which will be translated to JSON internally) or raw JSON. Each rule can specify the following: - `name` - the name of the rule that will be shown in reports etc. - `filters` - a list of filters that the engine should use to match the rule to the object that is being evaluated. This section needs a set of subproperties defined, see below. - `matchtype` - specifies how the engine should match filter properties. Valid values are "regex", "exact", "partial" and "count". See the "Match types" section below for more details. - `filter` - a template of properties and values that will be matched against the object. The structure of the filter needs to mimic the structure of the object. - `listcondition` (OPTIONAL) - what boolean operator to apply if a rule specifies lists with values. Can be "and" or "or". "and" means all list entries must match. "or" means at least one list entry must match. - `filtercondition` (OPTIONAL) - what boolean operator to apply between multiple filters. Can be "and" or "or". "and" means all filters must match. "or" means at least one list entry must match. Default is "and". Rules will match against output received from the API's Google exposes for each service supported by gcp-audit. The official documentation on the API's can be found [here] but to make writing rules easier, sample objects for each category are provided in the `docs/samples` directory. As an example of what a rule can look like, this rule will find CloudSQL instances that are exposed to `0.0.0.0/0`: [subdirectory]: https://github.com/spotify/gcp-audit/tree/master/gcp_audit/rules [here]: https://developers.google.com/api-client-library/python/apis/ ```json { "name": "Traffic allowed from all IP's to CloudSQL instance", "filters": [{ "matchtype": "exact", "filter": { "settings":{ "ipConfiguration":{ "authorizedNetworks":[{ "value":"0.0.0.0/0" }] } } } }] } ``` And here's the same rule in YAML format: ``` name: Traffic allowed from all IP's to CloudSQL instance filters: - matchtype: exact filter: settings: ipConfiguration: authorizedNetworks: - value: 0.0.0.0/0 ``` The engine will apply the filters defined in the template to the object and check whether the properties match exactly and the values match according to the defined `matchtype` for each filter. ### Match types Each filter must define a match type that will be used for evaluating filter values against object values. Each filter can define only one match type, so for rules that need to evaluate something based on multiple match types, separate filters need to be created. Examples below are all matching this mock object: ```json {"someproperty":"some text"} ``` #### exact Match filter values to the corresponding object values exactly. Example: ```json { "name":"Example regex rule", "filters":[{ "matchtype":"exact", "filter":{ "someproperty":"some text" } }] } ``` #### partial Match filter values to the corresponding object values by checking if the filter values are a subset of the object values. No wildcards needed, or supported - wildcards will be treated as regular characters so should only be used if you actually *want* to match a literal `*`. Example: ```json { "name":"Example partial rule", "filters":[{ "matchtype":"partial", "filter":{ "someproperty":"me tex" } }] } ``` #### regex Match filter values to the corresponding object values based on regular expressions. Example: ```json { "name":"Example regex rule", "filters":[{ "matchtype":"regex", "filter":{ "someproperty":"^.+?so?e\s+text\s*" } }] } ``` #### numeric Perform a numeric comparison between the filter value and the object value. The syntax is `"field":" "` where `op` is one of `eq`, `lt`, `le`, `gt` or `ge`. Example: ```json { "name":"Example numeric rule", "filters":[{ "matchtype":"numeric", "filter":{ "someproperty":"lt 100" } }] } ``` #### count This match type doesn't actually look at the data in the fields themselves but rather counts how many occurrences are found of the field that is to be matched. Syntax is identical to the one used for the `numeric` match type, see previous section. Example: ```json { "name":"Example count rule", "filters":[{ "matchtype":"count", "filter":{ "someproperty":"ge 1" } }] } ``` ### Caveats When writing rules, it's important to remember that the filter template needs to match the object EXACTLY. If a value exists within a list in the object, the template needs to reflect that too. So for the following object: ```json {"name":"someobject","properties":[{"someproperty":"somevalue"}]} ``` The following template will NOT match, because the subsection under "properties" is not specified as a list: ```json {"properties":{"someproperty":"somevalue"}} ``` But this one matches: ```json {"properties":[{"someproperty":"somevalue"}]} ``` Handling both these templates so they both match in an unambiguous way is on the todo list. ## Code of Conduct This project adheres to the [Open Code of Conduct][code-of-conduct]. By participating, you are expected to honor this code. [code-of-conduct]: https://github.com/spotify/code-of-conduct/blob/master/code-of-conduct.md ================================================ FILE: gcp_audit/__init__.py ================================================ ================================================ FILE: gcp_audit/gcp_audit.py ================================================ #!/usr/bin/env python # Copyright (c) 2016-2017 Spotify AB. # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. import atexit import datetime import googleapiclient import json import os import signal import sys import util.gcp as gcp import yaml from argparse import ArgumentParser from termcolor import colored from util.filter import filterjson env_credentials = '' checks = { 'buckets': { 'func': gcp.get_acls_for_buckets, 'descfield': 'bucket' }, 'bucket_objects': { 'func': gcp.get_default_acls, 'descfield': 'entity' }, 'cloudsql': { 'func': gcp.get_cloudsql_instances, 'descfield': 'name' }, 'firewalls': { 'func': gcp.get_firewalls, 'descfield': 'name' } } def loadrules(ruletype): rules = [] path = os.path.join(os.path.dirname(__file__), "rules/%s" % ruletype) for file in os.listdir(path): with open("%s/%s" % (path, file)) as rulefile: if file.endswith(".json"): rule = json.load(rulefile) elif file.endswith(".yaml"): rule = yaml.safe_load(rulefile) else: raise "Unknown rule format" rules.append(rule) return rules def apply_rules(ruletype, gcpobjects, descfield, outfile, project): rules = loadrules(ruletype) for obj in gcpobjects: for rule in rules: if 'filtercondition' in rule: res = apply_rule_filters(obj, rule['filters'], rule['filtercondition']) else: res = apply_rule_filters(obj, rule['filters']) if res: print colored('MATCH:', 'red'), \ "object '%s' matches rule '%s'" \ % (obj[descfield], rule['name']) with open(outfile, 'a') as f: f.write(datetime.datetime.now().ctime() + ": Project: " + project + " | Object: " + obj[descfield] + " | Matches rule: " + rule['name'] + "\n" + json.dumps(obj) + "\n\n") def apply_rule_filters(obj, filters, filtercondition='and'): res = True for f in filters: if 'listcondition' in f: res = filterjson(obj, f['filter'], f['matchtype'], f['listcondition']) else: res = filterjson(obj, f['filter'], f['matchtype']) if ((filtercondition == 'or' and res) or (filtercondition == 'and' and not res)): break return res def handle_signal(signal, frame): print "SIGINT received. Exiting." sys.exit(0) def parse_options(): def comma_split(str): return str.split(',') parser = ArgumentParser(description='A tool for auditing security \ properties of GCP projects.', epilog='gcp-audit needs a valid key for an account \ with audit capabilities for the projects \ in scope in order to work. This needs \ to be set either via the \ GOOGLE_APPLICATION_CREDENTIALS \ environment variable, \ or via the -k parameter.') parser.add_argument('-c', '--checks', help='comma separated list of types of checks to run') parser.add_argument('-k', '--keyfile', help="keyfile to use for GCP credentials") parser.add_argument('-o', '--output', help='file to output results to', default='results.json') parser.add_argument('-p', '--projects', help='comma separated list of GCP projects to audit', type=comma_split) options = parser.parse_args() return options def restore_env_credentials(): if env_credentials: os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = env_credentials else: os.unsetenv('GOOGLE_APPLICATION_CREDENTIALS') def main(): global checks global env_credentials options = parse_options() signal.signal(signal.SIGINT, handle_signal) if options.checks: checks = dict((k, v) for k, v in checks.iteritems() if k in options.checks.split(',')) if options.keyfile: if 'GOOGLE_APPLICATION_CREDENTIALS' in os.environ: env_credentials = os.environ['GOOGLE_APPLICATION_CREDENTIALS'] atexit.register(restore_env_credentials) os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = options.keyfile if options.projects: projects = options.projects else: projects = gcp.get_all_projects() for project in projects: print colored('Project:', 'blue'), project for name, check in checks.iteritems(): try: res = check['func'](project) apply_rules(name, res, check['descfield'], options.output, project) except googleapiclient.errors.HttpError: print colored('ERROR:', 'red'), "Permission denied?" print colored('DONE', 'green'), \ ' - results (if any) have been written to %s' % options.output if __name__ == "__main__": main() ================================================ FILE: gcp_audit/rules/bucket_objects/world-writable-default-permissions.json ================================================ { "name": "World writable default object permissions", "filters": [ { "matchtype": "regex", "filter": { "entity": "allUsers", "role": "OWNER|EDITOR" } } ] } ================================================ FILE: gcp_audit/rules/buckets/world-writable-buckets.json ================================================ { "name": "World writable bucket", "filters": [ { "matchtype": "regex", "filter": { "entity": "allUsers", "role": "OWNER|EDITOR" } } ] } ================================================ FILE: gcp_audit/rules/cloudsql/allips.json ================================================ { "name": "Traffic allowed from all IP's to CloudSQL instance", "filters": [ { "matchtype": "exact", "filter": { "settings": { "ipConfiguration": { "authorizedNetworks": [ { "value": "0.0.0.0/0" } ] } } } } ] } ================================================ FILE: gcp_audit/rules/firewalls/allips-multiports-list.json ================================================ { "name": "Traffic allowed from all IP's to multiple ports (list variant)", "filters": [ { "matchtype": "regex", "filter": { "sourceRanges": "0.0.0.0/0", "allowed": [ { "IPProtocol": "tcp|udp" } ] } }, { "matchtype": "count", "filter": { "allowed": [ { "ports": "gt 1" } ] } } ] } ================================================ FILE: gcp_audit/rules/firewalls/allips-multiports-range.json ================================================ { "name": "Traffic allowed from all IP's to multiple ports (range variant)", "filters": [ { "matchtype": "regex", "filter": { "sourceRanges": [ "0.0.0.0/0" ], "allowed": [ { "IPProtocol": "tcp|udp", "ports": "\\d+-\\d+" } ] } } ] } ================================================ FILE: gcp_audit/rules/firewalls/allips-multiports-range.yaml ================================================ name: Traffic allowed from all IP's to multiple ports (YAML range variant) filters: - matchtype: regex filter: sourceRanges: - 0.0.0.0/0 allowed: - IPProtocol: tcp|udp ports: \d+-\d+ ================================================ FILE: gcp_audit/rules/firewalls/allips-mysql.json ================================================ { "name": "Traffic allowed from all IP's to MySQL port", "filters": [ { "matchtype": "exact", "filter": { "sourceRanges": "0.0.0.0/0", "allowed": [ { "IPProtocol": "tcp", "ports": "3306" } ] } } ] } ================================================ FILE: gcp_audit/rules/firewalls/allips-notags.json ================================================ { "type": "firewall", "name": "Traffic allowed from all IP's with no target tags set", "filters": [ { "matchtype": "regex", "filter": { "sourceRanges": "0.0.0.0/0", "allowed": [ { "IPProtocol": "tcp|udp", "ports": ".+" } ] } }, { "matchtype": "count", "filter": { "targetTags": "eq 0" } } ] } ================================================ FILE: gcp_audit/util/__init__.py ================================================ ================================================ FILE: gcp_audit/util/filter.py ================================================ #!/usr/bin/env python # Copyright (c) 2016-2017 Spotify AB. # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. import re import operator def filterjson(event, filter, matchtype, listcondition="or"): match = True if isinstance(filter, dict): for k, v in filter.iteritems(): if k in event: if isinstance(v, dict): match = filterjson(event[k], v, matchtype, listcondition) elif isinstance(v, list) and isinstance(event[k], list): match = filterjson(event[k], v, matchtype, listcondition) else: # Match filter string against object array if isinstance(event[k], list): for e in event[k]: match = filterjson(e, v, matchtype) if match: break # Match filter string against object string, int, bool else: match = matchstr(event[k], v, matchtype) else: # For count checks, handle a missing key # as if the key were an empty list if matchtype == "count": match = matchstr([], v, matchtype) else: match = False if not match: break elif isinstance(filter, list) and isinstance(event, list): for f in filter: for e in event: match = filterjson(e, f, matchtype, listcondition) if ((listcondition == 'or' and match) or (listcondition == 'and' and not match)): break elif isinstance(filter, list): for v in filter: match = filterjson(event, v, matchtype, listcondition) if ((listcondition == 'or' and match) or (listcondition == 'and' and not match)): break elif isinstance(filter, basestring): match = matchstr(event, filter, matchtype) else: raise "ERROR, unknown object encountered" return match def matchstr(estr, fstr, matchtype): if matchtype == 'count' or matchtype == 'numeric': ops = {"lt": operator.lt, "gt": operator.gt, "eq": operator.eq} op, val = fstr.split() val = int(val) if matchtype == 'exact': match = (fstr == estr) elif matchtype == 'partial': match = estr.find(fstr) elif matchtype == 'regex': match = (re.search(fstr, estr) is not None) elif matchtype == 'numeric': match = isinstance(estr, (int, long) and ops[op](estr, val)) elif matchtype == 'count': # All other objects than lists are single objects if isinstance(estr, list): objlen = len(estr) else: objlen = 1 match = ops[op](objlen, val) else: raise "ERROR: unknown mode" return match ================================================ FILE: gcp_audit/util/gcp.py ================================================ #!/usr/bin/env python # Copyright (c) 2016-2017 Spotify AB. # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. from googleapiclient import discovery from oauth2client.client import GoogleCredentials def create_service(service, version='v1'): credentials = GoogleCredentials.get_application_default() service = discovery.build(service, version, credentials=credentials) return service def get_firewalls(project): service = create_service('compute') req = service.firewalls().list(project=project) try: res = req.execute()['items'] except: res = [] return res def get_buckets(project): service = create_service('storage') req = service.buckets().list(project=project) try: res = req.execute()['items'] except: res = [] return res def get_default_acls(project): res = [] for bucket in get_buckets(project): res.extend(get_default_access_controls(project, bucket["name"])) return res def get_default_access_controls(project, bucket): service = create_service('storage') req = service.defaultObjectAccessControls().list(bucket=bucket) try: res = req.execute()['items'] except: res = [] return res def get_acls_for_bucket(project, bucket): service = create_service('storage') req = service.bucketAccessControls().list(bucket=bucket) try: res = req.execute()['items'] except: res = [] return res def get_acls_for_buckets(project): res = [] for bucket in get_buckets(project): res += get_acls_for_bucket(project, bucket['name']) return res def get_cloudsql_instances(project): service = create_service(service='sqladmin', version='v1beta4') req = service.instances().list(project=project) try: res = req.execute()['items'] except: res = [] return res def get_projects_for_organization(organization_id): projects = [] page_token = None while True: resp = create_service('cloudresourcemanager', 'v1beta1').projects() \ .list(filter='parent.id:%s' % organization_id, pageSize=250, pageToken=page_token).execute() projects += [x['projectId'] for x in resp['projects']] page_token = resp.get('nextPageToken', None) if not page_token: break return projects def get_all_organizations(): """Get all organizations that the credentials have access to.""" resp = create_service('cloudresourcemanager', 'v1beta1') \ .organizations().list().execute() return [x['organizationId'] for x in resp['organizations']] def get_all_projects(): """Get all organizations that the credentials have access to.""" projects = [] for org in get_all_organizations(): projects += get_projects_for_organization(org) return projects ================================================ FILE: requirements.txt ================================================ setuptools==18.5 google_api_python_client==1.6.1 termcolor==1.1.0 PyYAML==3.12 ================================================ FILE: setup.py ================================================ #!/usr/bin/env python # Copyright (c) 2016-2017 Spotify AB. # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. from codecs import open from os import path from setuptools import setup, find_packages here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='gcp-audit', version='1.0.0', description='A tool for auditing security properties of GCP projects.', long_description=long_description, url='https://github.com/spotify/gcp-audit', author='Spotify Security', author_email='security@spotify.com', license='License :: OSI Approved :: Apache Software License', classifiers=[ 'Development Status :: 3 - Alpha', 'Topic :: Security', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', ], keywords='security gcp google-cloud-platform', packages=find_packages(), install_requires=['termcolor', 'google-api-python-client', 'PyYAML'], include_package_data=True, entry_points={ 'console_scripts': [ 'gcp-audit=gcp_audit.gcp_audit:main' ], }, )