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