├── assets ├── __init__.py ├── icon.png └── templates │ ├── custom.css │ ├── entity_template.html │ ├── base.html │ ├── finding_template.html │ └── bootstrap.min.js ├── core ├── __init__.py ├── buckets.py ├── utility.py ├── add_finding.py ├── category.py ├── config.py ├── insert_entity.py ├── fetch.py ├── display_results.py └── rules.py ├── categories ├── __init__.py ├── logs.py ├── service_accounts.py ├── roles.py ├── pubsub.py ├── addresses.py ├── service_account_IAM_policy.py ├── service_account_keys.py ├── instance_groups.py ├── buckets.py ├── compute_engine.py └── firewalls.py ├── requirements.txt ├── .gitignore ├── README.md ├── x_project.py ├── gscout.py └── LICENSE /assets/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /core/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /categories/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /assets/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nccgroup/G-Scout/HEAD/assets/icon.png -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | tinydb==3.6.0 2 | google_api_python_client==1.6.1 3 | jinja2==2.9.5 4 | ipaddress 5 | -------------------------------------------------------------------------------- /assets/templates/custom.css: -------------------------------------------------------------------------------- 1 | .list-group-item { 2 | position: relative; 3 | display: block; 4 | padding: 0px 15px; /* adjust here */ 5 | margin-bottom: -1px; 6 | border: 2px solid #ddd; 7 | line-height: 1em /* set to text height */ 8 | } 9 | .navbar{ 10 | min-height: 0 11 | } -------------------------------------------------------------------------------- /categories/logs.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | from oauth2client.file import Storage 4 | 5 | from core.utility import get_gcloud_creds 6 | 7 | storage = Storage('creds.data') 8 | from httplib2 import Http 9 | from tinydb import TinyDB 10 | 11 | db = TinyDB('entities.json') 12 | 13 | 14 | def list_log_services(): 15 | projectId = TinyDB('projects.json').table("Project").all() 16 | resp, content = get_gcloud_creds().authorize(Http()).request( 17 | "https://logging.googleapis.com/v1beta3/projects/" + projectId + "/logServices", "GET") 18 | return [service['name'] for service in json.loads(content)['logServices']] 19 | -------------------------------------------------------------------------------- /core/buckets.py: -------------------------------------------------------------------------------- 1 | from googleapiclient import discovery 2 | from oauth2client.file import Storage 3 | from tinydb import TinyDB 4 | 5 | db = TinyDB('projects.json') 6 | storage = Storage('creds.data') 7 | from core.utility import get_gcloud_creds 8 | 9 | service = discovery.build("storage", "v1", credentials=get_gcloud_creds()) 10 | 11 | 12 | def get_buckets(project): 13 | request = service.buckets().list(project=project['projectId']) 14 | response = request.execute() 15 | buckets = [] 16 | if (response.get('items')): 17 | for bucket in response['items']: 18 | if "logging" not in bucket: 19 | buckets.append(bucket) 20 | return buckets 21 | -------------------------------------------------------------------------------- /categories/service_accounts.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | from oauth2client.file import Storage 4 | 5 | def add_role(role): 6 | def transform(element): 7 | try: 8 | element['roles'].append(role) 9 | except KeyError: 10 | element['roles'] = [role] 11 | 12 | return transform 13 | 14 | 15 | def insert_sa_roles(projectId, db): 16 | for role in db.table('Role').all(): 17 | for sa in db.table('Service Account').all(): 18 | if "serviceAccount:" + str.split(str(sa['name']), '/')[-1] in role['members']: 19 | db.table("Service Account").update( 20 | add_role(role['role']), 21 | eids=[sa.eid]) -------------------------------------------------------------------------------- /core/utility.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import re 4 | import os 5 | 6 | from oauth2client.client import GoogleCredentials 7 | 8 | # GCP object IDs, names, etc., may contain characters which are not valid in directory names. 9 | # e.g. myproject:part2 10 | def object_id_to_directory_name(object_id): 11 | rex = re.compile(r"[^a-z0-9_\-\.()]", re.IGNORECASE) 12 | return rex.sub("_", object_id) 13 | 14 | def get_gcloud_creds(): 15 | base_script_directory = os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "..")) 16 | keyfile_path = os.path.join(base_script_directory, 'keyfile.json') 17 | if os.path.isfile(keyfile_path): 18 | os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = keyfile_path 19 | creds = GoogleCredentials.get_application_default() 20 | return creds 21 | -------------------------------------------------------------------------------- /core/add_finding.py: -------------------------------------------------------------------------------- 1 | from tinydb import Query 2 | 3 | 4 | def add_finding(db, entity_table, entity_id, rule_title): 5 | finding_table = db.table('Finding') 6 | rule_table = db.table('Rule') 7 | rule_id = "" 8 | try: 9 | rule_id_list = rule_table.search(Query().title == rule_title) 10 | if rule_id_list: 11 | if len(rule_id_list) > 0: 12 | rule_id_entry = rule_id_list[0] 13 | rule_id = rule_id_entry.eid 14 | else: 15 | print("Error: could not get rule ID for '%s' / '%s'" % (entity_id, rule_title)) 16 | except Exception as e: 17 | print("Error adding finding: %s" % (e)) 18 | 19 | finding_table.insert({ 20 | "entity": {"table": entity_table, "id": entity_id}, 21 | "rule": {"table": "rule", "id": rule_id} 22 | }) 23 | -------------------------------------------------------------------------------- /categories/roles.py: -------------------------------------------------------------------------------- 1 | import json 2 | from googleapiclient import discovery 3 | from core.utility import get_gcloud_creds 4 | 5 | service = discovery.build('cloudresourcemanager', 'v1', credentials=get_gcloud_creds()) 6 | 7 | def insert_roles(projectId, db): 8 | try: 9 | try: 10 | request = service.projects().getIamPolicy(resource=projectId, body={}) 11 | role_list = request.execute()['bindings'] 12 | except Exception as e: 13 | print("Error obtaining role list: %s" % (e)) 14 | if role_list: 15 | for role in role_list: 16 | try: 17 | db.table('Role').insert(role) 18 | except Exception as e: 19 | print("Error inserting role into database: %s" % (e)) 20 | except Exception as e: 21 | print("Error enumerating roles: %s" % (e)) -------------------------------------------------------------------------------- /categories/pubsub.py: -------------------------------------------------------------------------------- 1 | from googleapiclient import discovery 2 | from tinydb import TinyDB 3 | 4 | from core.utility import get_gcloud_creds 5 | 6 | from core.insert_entity import insert_entity 7 | 8 | db = TinyDB('entities.json') 9 | from oauth2client.file import Storage 10 | 11 | storage = Storage('creds.data') 12 | service = discovery.build('pubsub', 'v1', credentials=get_gcloud_creds()) 13 | request = service.projects().topics().list(project="projects/goat-sounds") 14 | request = service.projects().subscriptions().list(project="projects/goat-sounds") 15 | request = service.projects().subscriptions().getIamPolicy(resource="projects/goat-sounds/subscriptions/baaaa") 16 | insert_entity("pubsub", ["projects", "topics"], "Topics", "v1", {"project": "projects/" + projectId}, "topics") 17 | insert_entity("pubsub", "subscriptions", "Pub/Sub", "v1", {"project": "projects/" + projectId}, "subscriptions") 18 | -------------------------------------------------------------------------------- /categories/addresses.py: -------------------------------------------------------------------------------- 1 | from googleapiclient import discovery 2 | from oauth2client.client import GoogleCredentials 3 | from core.utility import get_gcloud_creds 4 | 5 | service = discovery.build('compute', 'v1', credentials=get_gcloud_creds()) 6 | 7 | def insert_addresses(projectId, db): 8 | project = projectId 9 | regions = ['us-central1','us-east1','us-east4','us-west1','us-west2'] 10 | #add more regions as desired 11 | 12 | for region in regions: 13 | try: 14 | request = service.addresses().list(project=project, region=region) 15 | while request is not None: 16 | response = request.execute() 17 | for address in response['items']: 18 | db.table("Address").insert(address) 19 | request = service.addresses().list_next(previous_request=request, previous_response=response) 20 | except KeyError: 21 | pass -------------------------------------------------------------------------------- /core/category.py: -------------------------------------------------------------------------------- 1 | class Category(object): 2 | def __init__(self, product, categories, table_name, version, list_args, items) 3 | 4 | def insert(self): 5 | project 6 | ":projectId},items=" 7 | items 8 | "): 9 | 10 | #creds = storage.get() 11 | creds = GoogleCredentials.get_application_default() 12 | service = discovery.build(product, version, credentials=creds) 13 | while categories: 14 | api_entity = getattr(service, categories.pop(0))() 15 | service = api_entity 16 | request = api_entity.list(**list_args) 17 | try: 18 | while request is not None: 19 | response = request.execute() 20 | for item in response[items]: 21 | db.table(table_name).insert(item) 22 | try: 23 | request = api_entity.list_next(previous_request=request, previous_response=response) 24 | except AttributeError: 25 | request = None 26 | except KeyError: 27 | pass 28 | -------------------------------------------------------------------------------- /core/config.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | 3 | import os.path 4 | from oauth2client import tools 5 | from oauth2client.client import GoogleCredentials 6 | from oauth2client.client import OAuth2WebServerFlow 7 | from oauth2client.file import Storage 8 | 9 | CLIENT_ID = '206629590950-6o7fig55aupliolgt6o10obpnagdf4pd.apps.googleusercontent.com' 10 | CLIENT_SECRET = 'qgRgh8NA4Y8Qlqn7r7ulrKXV' # not actually a secret 11 | flow = OAuth2WebServerFlow(client_id=CLIENT_ID, 12 | client_secret=CLIENT_SECRET, 13 | scope='https://www.googleapis.com/auth/cloud-platform') 14 | 15 | storage = Storage('../creds.data') 16 | parser = argparse.ArgumentParser(parents=[tools.argparser]) 17 | flags = parser.parse_args(args=[]) 18 | 19 | if os.path.isfile('keyfile.json'): 20 | os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = os.getcwd() + "/keyfile.json" 21 | creds = GoogleCredentials.get_application_default() 22 | else: 23 | creds = tools.run_flow(flow, storage, flags) 24 | 25 | storage.put(creds) 26 | -------------------------------------------------------------------------------- /assets/templates/entity_template.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | {% block content %} 3 |
4 | 27 | {% endblock %} -------------------------------------------------------------------------------- /assets/templates/base.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 27 | {% block content %} 28 | {% endblock %} -------------------------------------------------------------------------------- /assets/templates/finding_template.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | {% block content %} 3 |
4 | The following entities were found to be in violation of this rule: 5 | {{text}} 6 |
7 | 8 |
9 | 32 | {% endblock %} -------------------------------------------------------------------------------- /categories/service_account_IAM_policy.py: -------------------------------------------------------------------------------- 1 | from oauth2client.file import Storage 2 | 3 | storage = Storage('creds.data') 4 | from httplib2 import Http 5 | import json 6 | from core.utility import get_gcloud_creds 7 | 8 | headers = {"Content-Length": 0} 9 | 10 | 11 | def insert_sa_policies(projectId, db): 12 | service_accounts = db.table("Service Account").all() 13 | for account in service_accounts: 14 | resp, content = get_gcloud_creds().authorize(Http()).request( 15 | "https://iam.googleapis.com/v1/projects/" + projectId + "/serviceAccounts/" + account[ 16 | 'uniqueId'] + ":getIamPolicy", "POST", headers=headers) 17 | try: 18 | for policy in json.loads(content)['bindings']: 19 | db.table('Service Account').update( 20 | add_policy({ 21 | "permission": policy['role'], 22 | "scope": policy['members'] 23 | }), 24 | eids=[account.eid]) 25 | except KeyError: 26 | pass 27 | 28 | 29 | # Function to pass Tinydb for the update query 30 | def add_policy(policy): 31 | def transform(element): 32 | try: 33 | element['iam_policies'].append(policy) 34 | except KeyError: 35 | element['iam_policies'] = [policy] 36 | 37 | return transform 38 | -------------------------------------------------------------------------------- /categories/service_account_keys.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | import json 3 | 4 | from httplib2 import Http 5 | from core.utility import get_gcloud_creds 6 | from googleapiclient import discovery 7 | 8 | 9 | def insert_service_account_keys(projectId, db): 10 | service_accounts = db.table("Service Account").all() 11 | for sa in service_accounts: 12 | sa_keys = list_service_account_keys(sa, projectId) 13 | for sa_key in sa_keys['keys']: 14 | db.table('Service Account').update( 15 | add_key({ 16 | "keyAlgorithm": sa_key['keyAlgorithm'], 17 | "validBeforeTime": sa_key['validBeforeTime'], 18 | "validAfterTime": sa_key['validAfterTime'] 19 | }), 20 | eids=[sa.eid]) 21 | 22 | 23 | def list_service_account_keys(sa, projectId): 24 | service = discovery.build("iam", "v1", credentials=get_gcloud_creds()) 25 | request = service.projects().serviceAccounts().keys().list(name="projects/" + projectId + "/serviceAccounts/" + sa['email']) 26 | response = request.execute() 27 | return response 28 | 29 | 30 | # Function to pass Tinydb for the update query 31 | def add_key(key): 32 | def transform(element): 33 | try: 34 | element['keys'].append(key) 35 | except KeyError: 36 | element['keys'] = [key] 37 | 38 | return transform 39 | 40 | 41 | def key_is_old(key): 42 | creation_date = datetime.datetime.strptime(key['validAfterTime'][:10], "%Y-%m-%d") 43 | if creation_date < datetime.datetime.now() - datetime.timedelta(days=90): 44 | return True 45 | return False 46 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # G-Scout ignore list 2 | *.pyc 3 | *.json 4 | get-all-external-ips.py 5 | get-all-firewalls.py 6 | cross_project_findings.py 7 | creds.data 8 | log.txt 9 | Report Output/ 10 | 11 | # Byte-compiled / optimized / DLL files 12 | __pycache__/ 13 | *.py[cod] 14 | *$py.class 15 | 16 | # C extensions 17 | *.so 18 | 19 | # Misc 20 | *.DS_Store 21 | 22 | # Distribution / packaging 23 | .Python 24 | build/ 25 | develop-eggs/ 26 | dist/ 27 | downloads/ 28 | eggs/ 29 | .eggs/ 30 | lib/ 31 | lib64/ 32 | parts/ 33 | sdist/ 34 | var/ 35 | wheels/ 36 | *.egg-info/ 37 | .installed.cfg 38 | *.egg 39 | MANIFEST 40 | 41 | # PyInstaller 42 | # Usually these files are written by a python script from a template 43 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 44 | *.manifest 45 | *.spec 46 | 47 | # Installer logs 48 | pip-log.txt 49 | pip-delete-this-directory.txt 50 | 51 | # Unit test / coverage reports 52 | htmlcov/ 53 | .tox/ 54 | .coverage 55 | .coverage.* 56 | .cache 57 | nosetests.xml 58 | coverage.xml 59 | *.cover 60 | .hypothesis/ 61 | .pytest_cache/ 62 | 63 | # Translations 64 | *.mo 65 | *.pot 66 | 67 | # Django stuff: 68 | *.log 69 | local_settings.py 70 | db.sqlite3 71 | 72 | # Flask stuff: 73 | instance/ 74 | .webassets-cache 75 | 76 | # Scrapy stuff: 77 | .scrapy 78 | 79 | # Sphinx documentation 80 | docs/_build/ 81 | 82 | # PyBuilder 83 | target/ 84 | 85 | # Jupyter Notebook 86 | .ipynb_checkpoints 87 | 88 | # pyenv 89 | .python-version 90 | 91 | # celery beat schedule file 92 | celerybeat-schedule 93 | 94 | # SageMath parsed files 95 | *.sage.py 96 | 97 | # Environments 98 | .env 99 | .venv 100 | env/ 101 | venv/ 102 | ENV/ 103 | env.bak/ 104 | venv.bak/ 105 | 106 | # Spyder project settings 107 | .spyderproject 108 | .spyproject 109 | 110 | # Rope project settings 111 | .ropeproject 112 | 113 | # mkdocs documentation 114 | /site 115 | 116 | # mypy 117 | .mypy_cache/ 118 | -------------------------------------------------------------------------------- /categories/instance_groups.py: -------------------------------------------------------------------------------- 1 | from googleapiclient import discovery 2 | from tinydb import TinyDB 3 | 4 | from core.utility import get_gcloud_creds 5 | 6 | db = TinyDB('entities.json') 7 | group_table = db.table('Instance Groups') 8 | template_table = db.table('Instance Templates') 9 | credentials = GoogleCredentials.get_application_default() 10 | from oauth2client.file import Storage 11 | 12 | storage = Storage('creds.data') 13 | service = discovery.build('compute', 'v1', credentials=get_gcloud_creds()) 14 | instanceGroups = service.instances() 15 | instanceTemplates = service.instanceTemplates() 16 | zones = service.zones() 17 | 18 | 19 | def insert_templates(): 20 | projectId = TinyDB('projects.json').table("Project").all() 21 | request = instanceTemplates.list(project=projectId) 22 | try: 23 | while request is not None: 24 | response = request.execute() 25 | for instanceTemplate in response['items']: 26 | template_table.insert(instanceTemplate) 27 | request = instanceTemplates.list_next(previous_request=request, previous_response=response) 28 | except KeyError: 29 | pass 30 | 31 | 32 | def insert_instance_groups(): 33 | projectId = TinyDB('projects.json').table("Project").all() 34 | for zone in get_zones(): 35 | request = instanceGroups.list(project=projectId, zone=zone) 36 | try: 37 | while request is not None: 38 | response = request.execute() 39 | for instanceGroup in response['items']: 40 | group_table.insert(instanceGroup) 41 | request = instanceGroups.list_next(previous_request=request, previous_response=response) 42 | except KeyError: 43 | pass 44 | 45 | 46 | def get_zones(): 47 | projectId = TinyDB('projects.json').table("Project").all() 48 | results = [] 49 | request = zones.list(project=projectId) 50 | response = request.execute()['items'] 51 | for result in response: 52 | results.append(result['name']) 53 | return results 54 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # G-Scout 2 | 3 | G-Scout is a tool for auditing Google Cloud Platform configurations. By making API calls, applying security rules, and generating HTML files based on the output, G-Scout makes it easy to analyze the security of a GCP environment. 4 | 5 | There are two ways for the project owner to grant API permissions: 6 | 1. User Account: 7 | 1. Use an account with Viewer and Security Reviewer permissions on the project (may require the project to activate the Google Identity and Access Management API, which can be done in the console). 8 | 2. Approve the Oauth2 authentication request when prompted in your browser. 9 | 2. Service Account: 10 | 1. Go to the console service accounts page at https://console.cloud.google.com/iam-admin/serviceaccounts/project?project=[project] and create a service account. 11 | 2. Go to IAM management console at https://console.cloud.google.com/iam-admin/iam/project?project=[project] and add Security Reviewer and Viewer permissions to the service account created in step 1. 12 | 3. Generate a Service Account key from https://console.cloud.google.com/apis/credentials?project=[project]. 13 | 4. Place the JSON file (named keyfile.json) generated in step 3 into the application directory. 14 | 5. Set the environment variable `GOOGLE_APPLICATION_CREDENTIALS` to the path of the JSON file downloaded. Or use the SDK to run `gcloud auth application-default login`. 15 | 16 | To run the application: 17 | ```sh 18 | virtualenv -p python2 venv 19 | source venv/bin/activate 20 | pip install -r requirements.txt 21 | python gscout.py -h 22 | ``` 23 | 24 | The HTML report output will be in the "Report Output" folder. 25 | 26 | When specifying the project name you can also use a wildcard to run G-Scout on multiple projects, for example: `python gscout.py --project-name "dev-*"`. 27 | You can also run G-Scout on all projects in an organization like this: `python gscout.py --organization "organization id"`, where the id will be a number you can find next to the organization name in the GCP console. 28 | 29 | To create a custom rule, add it to the rules.py file. A Rule object takes a name, a category, and a filter function. The function will be passed a json object corresponding to the category. 30 | To see an example for each category (some of which are altered from the standard API response), see the entity_samples.json file. 31 | 32 | Running `python x_project.py` will create a file showing all results across all projects G-Scout has been run on for each finding specified. Change the items in the list of rule names in `x_project.py` to specify which rules to generate the files for. -------------------------------------------------------------------------------- /categories/buckets.py: -------------------------------------------------------------------------------- 1 | from googleapiclient import discovery 2 | from oauth2client.file import Storage 3 | 4 | from core.utility import get_gcloud_creds 5 | 6 | storage = Storage('creds.data') 7 | service = discovery.build('storage', 'v1', credentials=get_gcloud_creds()) 8 | 9 | 10 | def insert_acls(db): 11 | for bucket in db.table('Bucket').all(): 12 | request = service.bucketAccessControls().list(bucket=bucket['name']) 13 | try: 14 | response = request.execute() 15 | if 'items' in response.keys(): 16 | for acl in response['items']: 17 | acl_role = "" 18 | acl_entity = "" 19 | if 'role' in acl.keys(): 20 | acl_role = acl['role'] 21 | if 'entity' in acl.keys(): 22 | acl_entity = acl['entity'] 23 | db.table('Bucket').update( 24 | add_acl({"permission": acl_role, "scope": acl_entity}), eids=[bucket.eid]) 25 | except Exception as e: 26 | print("Error getting bucket ACLs for bucket '%s': %s" % (bucket, e)) 27 | 28 | 29 | def insert_defacls(db): 30 | for bucket in db.table('Bucket').all(): 31 | request = service.defaultObjectAccessControls().list(bucket=bucket['name']) 32 | try: 33 | response = request.execute() 34 | if 'items' in response.keys(): 35 | for defacl in response['items']: 36 | acl_role = "" 37 | acl_entity = "" 38 | if 'role' in defacl.keys(): 39 | acl_role = defacl['role'] 40 | if 'entity' in defacl.keys(): 41 | acl_entity = defacl['entity'] 42 | db.table('Bucket').update( 43 | add_defacl({"permission": acl_role, "scope": acl_entity}), eids=[bucket.eid]) 44 | except Exception as e: 45 | print("Error getting default ACLs for bucket '%s': %s" % (bucket, e)) 46 | 47 | 48 | # Function to pass Tinydb for the update query 49 | def add_acl(acl): 50 | def transform(element): 51 | if 'acls' in element.keys(): 52 | element['acls'].append(acl) 53 | else: 54 | element['acls'] = [acl] 55 | return transform 56 | 57 | 58 | def add_defacl(defacl): 59 | def transform(element): 60 | if 'defacls' in element.keys(): 61 | element['defacls'].append(defacl) 62 | else: 63 | element['defacls'] = [defacl] 64 | 65 | return transform 66 | -------------------------------------------------------------------------------- /x_project.py: -------------------------------------------------------------------------------- 1 | import json 2 | import os 3 | import logging 4 | from jinja2 import Environment, PackageLoader 5 | from tinydb import TinyDB, Query 6 | 7 | logging.basicConfig(filename="log.txt") 8 | env = Environment(loader=PackageLoader('assets', 'templates'), extensions=['jinja2.ext.do']) 9 | 10 | def pretty_print(dict): 11 | try: 12 | return json.dumps(dict, sort_keys=True, indent=4, separators=(',', ': ')) 13 | except: 14 | return dict 15 | 16 | env.filters['pretty_print'] = pretty_print 17 | 18 | def generate_cross_project_page(header, fields, dropdowns, findings, rule_title): 19 | template = env.get_template("finding_template.html") 20 | output_dir = "Report Output/cross-project/rules/" 21 | if not os.path.isdir(output_dir): 22 | try: 23 | os.makedirs(output_dir) 24 | except Exception as e: 25 | msg = "could not make output directory '%s'. The error encountered was: %s%s%sStack trace:%s%s" % (output_dir, e, os.linesep, os.linesep, os.linesep, traceback.format_exc()) 26 | print("Error: %s" % (msg)) 27 | logging.exception(msg) 28 | 29 | file = open("Report Output/cross-project/rules/" + rule_title + ".html", "w+") 30 | file.write(template.render( 31 | **{"records": findings, "dropdowns": dropdowns, "header": header, "fields": fields, 32 | "text": rule_title})) 33 | file.close() 34 | 35 | rules = ["Primitive Roles in Use","Bucket Logging Not Enabled"] #change to any list of rules 36 | def x_project_findings(rules): 37 | db = TinyDB("projects.json") 38 | project_list = [] 39 | for project in db.table("Project").all(): 40 | project_list.append(project['projectId']) 41 | 42 | for rule_title in rules: 43 | findings = [] 44 | entity = {} 45 | for projectId in project_list: 46 | project_db = TinyDB("project_dbs/" + projectId + ".json") 47 | res = project_db.table("Rule").get(Query().title == rule_title) 48 | for finding in project_db.table("Finding").all(): 49 | if finding['rule']['id'] == res.eid: 50 | entity = project_db.table(finding['entity']['table']).get(doc_id = finding['entity']['id']) 51 | entity['projectId'] = projectId 52 | findings.append(entity) 53 | generate_cross_project_page("", entity.keys(), {}, findings, rule_title) 54 | x_project_findings(rules) 55 | # This is just to get numbers of resources 56 | # for projectId in project_list: 57 | # project_db = TinyDB("project_dbs/" + projectId + ".json") 58 | # print(len(project_db.table("Bucket").all())) 59 | -------------------------------------------------------------------------------- /core/insert_entity.py: -------------------------------------------------------------------------------- 1 | from googleapiclient import discovery 2 | from tinydb import TinyDB, Query 3 | from core.utility import object_id_to_directory_name 4 | from core.utility import get_gcloud_creds 5 | 6 | 7 | def insert_entity(projectId, product, categories, table_name, version="v1", prefix="", items="items", suffix=""): 8 | db = TinyDB("project_dbs/" + object_id_to_directory_name(projectId) + ".json") 9 | service = discovery.build(product, version, credentials=get_gcloud_creds()) 10 | while categories: 11 | api_entity = getattr(service, categories.pop(0))() 12 | service = api_entity 13 | try: 14 | request = api_entity.list(project=prefix + projectId + suffix) 15 | except TypeError: 16 | try: 17 | request = api_entity.list(name=prefix + projectId + suffix) 18 | except TypeError: 19 | request = api_entity.list(parent=prefix + projectId + suffix) 20 | try: 21 | while request is not None: 22 | response = request.execute() 23 | for item in response[items]: 24 | db.table(table_name).insert(item) 25 | try: 26 | request = api_entity.list_next(previous_request=request, previous_response=response) 27 | except AttributeError: 28 | request = None 29 | except KeyError: 30 | pass 31 | 32 | #discovery.build('compute', 'v1', credentials=Storage('creds.data').get()).networks().get(project=projectId, network=network.get('name')).execute()["subnetworks"] 33 | 34 | def insert_subnet_entities(projectId, version="v1", prefix="", items="items"): 35 | product = "compute" 36 | categories = ["subnetworks"] 37 | table_name = "Subnet" 38 | db = TinyDB("project_dbs/" + object_id_to_directory_name(projectId) + ".json") 39 | service = discovery.build("compute", version, credentials=get_gcloud_creds()) 40 | region_list = [] 41 | request = service.regions().list(project=projectId) 42 | while request is not None: 43 | response = request.execute() 44 | if 'items' in response.keys(): 45 | for region in response['items']: 46 | #print("Debug: %s" % (region)) 47 | if 'description' in region.keys(): 48 | region_list.append(region['description']) 49 | else: 50 | print("Warning: no regions found for project '%s'" % (projectId)) 51 | request = service.regions().list_next(previous_request=request, previous_response=response) 52 | 53 | subnet_count = 0 54 | for region in region_list: 55 | request = service.subnetworks().list(project=projectId, region=region) 56 | while request is not None: 57 | response = request.execute() 58 | 59 | if 'items' in response.keys(): 60 | for subnetwork in response['items']: 61 | #print("Debug: %s" % (subnetwork)) 62 | db.table(table_name).insert(subnetwork) 63 | subnet_count = subnet_count + 1 64 | request = service.subnetworks().list_next(previous_request=request, previous_response=response) 65 | if subnet_count == 0: 66 | print("Warning: no subnets found for project '%s'" % (projectId)) 67 | -------------------------------------------------------------------------------- /categories/compute_engine.py: -------------------------------------------------------------------------------- 1 | from googleapiclient import discovery 2 | from oauth2client.file import Storage 3 | from tinydb import Query 4 | 5 | from core.utility import get_gcloud_creds 6 | 7 | storage = Storage('creds.data') 8 | service = discovery.build('compute', 'v1', credentials=get_gcloud_creds()) 9 | instances = service.instances() 10 | instanceGroups = service.instanceGroups() 11 | instanceTemplates = service.instanceTemplates() 12 | zones = service.zones() 13 | 14 | 15 | def insert_instances(projectId, db): 16 | out = [] 17 | request = service.instances().aggregatedList(project=projectId) 18 | while request is not None: 19 | response = request.execute() 20 | out.append(response) 21 | request = service.instances().aggregatedList_next(previous_request=request, previous_response=response) 22 | write_results(out, db) 23 | 24 | def write_results(out, db): 25 | for segment in out: 26 | for zone in segment['items'].keys(): 27 | if segment['items'][zone].get('instances'): 28 | for instance in segment['items'][zone].get('instances'): 29 | db.table('Compute Engine').insert(instance) 30 | 31 | def insert_instance_groups(projectId, db): 32 | request = instanceGroups.aggregatedList(project=projectId) 33 | try: 34 | while request is not None: 35 | response = request.execute() 36 | for region, group_list in response['items'].items(): 37 | if "warning" not in group_list: 38 | for group in group_list['instanceGroups']: 39 | db.table('Instance Group').insert(group) 40 | request = instanceGroups.list_next(previous_request=request, previous_response=response) 41 | except KeyError: 42 | pass 43 | 44 | 45 | def get_zones(projectId): 46 | results = [] 47 | request = zones.list(project=projectId) 48 | response = request.execute()['items'] 49 | for result in response: 50 | results.append(result['name']) 51 | return results 52 | 53 | 54 | # Function to pass Tinydb for the update query 55 | def add_member(member): 56 | def transform(element): 57 | try: 58 | element['members'].append(member) 59 | except KeyError: 60 | element['members'] = [member] 61 | 62 | return transform 63 | 64 | 65 | def add_member_instances(projectId, db): 66 | for instance in db.table('Compute Engine').all(): 67 | db.table('Network').update( 68 | add_member({ 69 | "kind": instance['kind'], 70 | "selfLink": instance['selfLink'], 71 | "tags": instance.get('tags', {}).get('items'), 72 | "name": instance['name'] 73 | }), 74 | eids=[db.table('Network').get( 75 | Query().selfLink == instance['networkInterfaces'][0]['network'] 76 | ).eid]) 77 | 78 | 79 | def add_member_instance_groups(projectId, db): 80 | for group in db.table('Instance Group').all(): 81 | db.table('Network').update( 82 | add_member({ 83 | "kind": group['kind'], 84 | "selfLink": group['selfLink'], 85 | "tags": group.get('tags', {}).get('items'), 86 | "name": group['name'] 87 | }), 88 | eids=[db.table('Network').get( 89 | Query().selfLink == group['network'] 90 | ).eid]) 91 | 92 | 93 | def add_member_instance_templates(projectId, db): 94 | for template in db.table('Instance Template').all(): 95 | db.table('Network').update( 96 | add_member({ 97 | "kind": template['kind'], 98 | "selfLink": template['selfLink'], 99 | "tags": template.get('tags', {}).get('items'), 100 | "name": template['name'] 101 | }), 102 | eids=[db.table('Network').get( 103 | Query().selfLink == template['properties']['networkInterfaces'][0]['network'] 104 | ).eid]) 105 | -------------------------------------------------------------------------------- /core/fetch.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import sys 3 | 4 | logging.basicConfig(filename="log.txt") 5 | from tinydb import TinyDB 6 | 7 | from core.utility import object_id_to_directory_name 8 | from core.utility import get_gcloud_creds 9 | 10 | def fetch(projectId): 11 | db = TinyDB("project_dbs/" + object_id_to_directory_name(projectId) + ".json") 12 | from rules import rules 13 | from display_results import display_results 14 | from insert_entity import insert_entity, insert_subnet_entities 15 | from categories.firewalls import add_affected_instances, add_network_rules 16 | from categories.roles import insert_roles 17 | import categories.compute_engine 18 | from categories.service_account_keys import insert_service_account_keys 19 | import categories.service_accounts 20 | import categories.service_account_IAM_policy 21 | import categories.buckets 22 | from categories.addresses import insert_addresses 23 | 24 | # initialize the entity database tables for the project, so that running G-Scout more than once against the same project doesn't result in duplicated data 25 | # I did this as an explicit list of tables so that if future versions store data that should persist between runs, those aren't deleted. 26 | entity_table_names = ["Address", "Bucket", "Cluster", "Compute Engine", "Finding", "Firewall", "Instance Template", "Network", "Pub/Sub", "Role", "Rule", "Service Account", "Snapshot", "SQL Instance", "Subnet", "Topics"] 27 | for tn in entity_table_names: 28 | db.purge_table(tn) 29 | 30 | try: 31 | insert_entity(projectId, "compute", ["networks"], "Network") 32 | except Exception as e: 33 | print("Failed to fetch networks.") 34 | logging.exception("networks") 35 | 36 | try: 37 | insert_subnet_entities(projectId) 38 | except Exception as e: 39 | print("Failed to fetch subnets: %s" % (e)) 40 | logging.exception("subnets: %s" % (e)) 41 | 42 | try: 43 | insert_entity(projectId, "compute", ["firewalls"], "Firewall") 44 | except Exception as e: 45 | print("Failed to fetch firewalls.") 46 | logging.exception("firewalls") 47 | 48 | try: 49 | insert_roles(projectId, db) 50 | except Exception as e: 51 | print("Failed to fetch roles.") 52 | logging.exception("roles") 53 | 54 | try: 55 | insert_entity(projectId, "iam", ["projects","serviceAccounts"], "Service Account", "v1", "projects/", "accounts") 56 | categories.service_accounts.insert_sa_roles(projectId, db) 57 | except Exception as e: 58 | print("Failed to fetch service accounts.") 59 | logging.exception("service accounts") 60 | 61 | try: 62 | insert_service_account_keys(projectId, db) 63 | except Exception as e: 64 | print("Failed to fetch service account keys.") 65 | logging.exception("service account keys") 66 | 67 | try: 68 | categories.service_account_IAM_policy.insert_sa_policies(projectId, db) 69 | except Exception as e: 70 | print("Failed to fetch service account IAM policies.") 71 | logging.exception("service account IAM policies") 72 | 73 | try: 74 | insert_entity(projectId, "storage", ["buckets"], "Bucket") 75 | except Exception as e: 76 | print("Failed to fetch buckets.") 77 | logging.exception("buckets") 78 | 79 | try: 80 | categories.buckets.insert_acls(db) 81 | categories.buckets.insert_defacls(db) 82 | except Exception as e: 83 | print("Failed to fetch bucket ACLS/Default ACLS: %s" % (e)) 84 | logging.exception("bucket ACLS/Default ACLS: %s" % (e)) 85 | 86 | try: 87 | categories.compute_engine.insert_instances(projectId, db) 88 | insert_entity(projectId, "compute", ["instanceTemplates"], "Instance Template") 89 | categories.compute_engine.insert_instance_groups(projectId, db) 90 | except Exception as e: 91 | print("Failed to fetch compute engine instances.") 92 | logging.exception("compute engine instances") 93 | try: 94 | categories.compute_engine.add_member_instances(projectId, db) 95 | except Exception as e: 96 | print("Failed add member instances to compute engine instances.") 97 | logging.exception("compute engine instances") 98 | try: 99 | add_network_rules(projectId, db) 100 | add_affected_instances(projectId, db) 101 | except Exception as e: 102 | print("Failed to display instances/rules with instances.") 103 | try: 104 | insert_addresses(projectId, db) 105 | except Exception as e: 106 | print("Failed to fetch IP addresses") 107 | print(e) 108 | try: 109 | insert_entity(projectId, "compute", ["snapshots"], "Snapshot") 110 | except Exception as e: 111 | print("Failed to fetch instance snapshots.") 112 | logging.exception("snapshots") 113 | 114 | try: 115 | insert_entity(projectId, "sqladmin", ["instances"], "SQL Instance", "v1beta4") 116 | except Exception as e: 117 | print("Failed to fetch SQL instances.") 118 | logging.exception("SQL instances") 119 | 120 | try: 121 | insert_entity(projectId, "pubsub", ["projects", "topics"], "Topics", "v1", "projects/", "topics") 122 | insert_entity(projectId, "pubsub", ["projects", "subscriptions"], "Pub/Sub", "v1", "projects/", "subscriptions") 123 | except Exception as e: 124 | print("Failed to fetch Pub/Sub topics/subscriptions.") 125 | logging.exception("pub/sub") 126 | try: 127 | insert_entity(projectId, "container", ['projects','locations','clusters'],"Cluster","v1beta1","projects/","clusters","/locations/-") 128 | except: 129 | print("Failed to fetch clusters") 130 | logging.exception("GKE") 131 | try: 132 | rules(projectId) 133 | except Exception as e: 134 | logging.exception(e) 135 | display_results(db, projectId) 136 | -------------------------------------------------------------------------------- /core/display_results.py: -------------------------------------------------------------------------------- 1 | import json 2 | import logging 3 | import os 4 | 5 | from jinja2 import Environment, PackageLoader 6 | from tinydb import Query 7 | 8 | from core.utility import object_id_to_directory_name 9 | 10 | logging.basicConfig(filename="log.txt") 11 | env = Environment(loader=PackageLoader('assets', 'templates'), extensions=['jinja2.ext.do']) 12 | 13 | 14 | def pretty_print(dict): 15 | try: 16 | return json.dumps(dict, sort_keys=True, indent=4, separators=(',', ': ')) 17 | except: 18 | return dict 19 | 20 | 21 | env.filters['pretty_print'] = pretty_print 22 | 23 | 24 | def display_results(db, projectId): 25 | def add_to_dropdown(category): 26 | rules = set([]) 27 | for rule in db.table("Rule").search(Query().category == category): 28 | if db.table('Finding').search(Query().rule.id == rule.eid): 29 | rules.add(rule['title']) 30 | return rules 31 | 32 | def generate_entities_page(category, header, fields, dropdowns): 33 | try: 34 | records = db.table(category).all() 35 | template = env.get_template("entity_template.html") 36 | entity_file_path = "Report Output/" + object_id_to_directory_name(projectId) + "/Information/" + category + "s.html" 37 | entity_dir_path = os.path.dirname(entity_file_path) 38 | if not os.path.isdir(entity_dir_path): 39 | os.makedirs(entity_dir_path) 40 | file = open(entity_file_path, "w+") 41 | file_content = None 42 | try: 43 | file_content = template.render(**{"records": records, "dropdowns": dropdowns, "header": header, "fields": fields}) 44 | except Exception as e: 45 | print("Error rendering output file '%s': %s" % (entity_file_path, e)) 46 | if file_content: 47 | file.write(file_content) 48 | file.close() 49 | except Exception as e: 50 | print("Error generating output file '%s': %s" % (entity_file_path, e)) 51 | 52 | def generate_findings_page(category, header, fields, dropdowns): 53 | try: 54 | for rule_title in dropdowns[category]: 55 | rule = db.table("Rule").get(Query().title == rule_title) 56 | findings = db.table("Finding").search(Query().rule.id == rule.eid) 57 | findings = [db.table(finding['entity']['table']).get(eid=finding['entity']['id']) for finding in 58 | findings] 59 | template = env.get_template("finding_template.html") 60 | finding_file_path = "Report Output/" + object_id_to_directory_name(projectId) + "/Findings/" + rule_title + ".html" 61 | finding_dir_path = os.path.dirname(finding_file_path) 62 | if not os.path.isdir(finding_dir_path): 63 | os.makedirs(finding_dir_path) 64 | file = open(finding_file_path, "w+") 65 | file_content = None 66 | try: 67 | file_content = template.render( 68 | **{"records": findings, "dropdowns": dropdowns, "header": header, "fields": fields, 69 | "text": rule['title']}) 70 | except Exception as e: 71 | print("Error rendering output file '%s': %s" % (entity_file_path, e)) 72 | if file_content: 73 | file.write(file_content) 74 | file.close() 75 | except KeyError as ke: 76 | pass 77 | except Exception as e: 78 | print("Error generating output file '%s': %s" % (entity_file_path, e)) 79 | 80 | # The following would place only categories with findings in the navbar 81 | # for finding in findings_table.all(): 82 | # categories.add(finding['entity']['table']) 83 | # for category in categories: 84 | # dropdowns[category] = add_to_dropdown(category) 85 | 86 | # The header is the name of the field that will be bolded 87 | def generate_pages(category, header, fields, dropdowns): 88 | try: 89 | generate_findings_page(category, header, fields, dropdowns) 90 | except Exception as e: 91 | logging.exception("findings page") 92 | try: 93 | generate_entities_page(category, header, fields, dropdowns) 94 | except Exception as e: 95 | logging.exception("entities page") 96 | 97 | # Navbar dropdowns 98 | dropdowns = {} 99 | categories = set([]) 100 | 101 | for rule in db.table("Rule").all(): 102 | categories.add(rule['category']) 103 | for category in categories: 104 | dropdowns[category] = add_to_dropdown(category) 105 | generate_pages("Bucket", "name", ["selfLink", "location", "storageClass", "acls", "defacls"], dropdowns) 106 | generate_pages("Firewall", "name", 107 | ["network", "sourceRanges", "sourceTags","direction", "destinationRanges", "allowed", "description", "targetTags", 108 | "affectedInstances"], dropdowns) 109 | generate_pages("Network", "selfLink", ["name", "description", "firewallRules", "members", "subnetworks"], dropdowns) 110 | generate_pages("Subnet", "selfLink", ["name", "region", "network", "ipCidrRange", "gatewayAddress", "enableFlowLogs", "privateIpGoogleAccess"], dropdowns) 111 | generate_pages("Role", "role", ["members"], dropdowns) 112 | generate_pages("Compute Engine", "name", ["selfLink", "machineType", "status", "startRestricted", "serviceAccounts", "networkInterfaces", "disks", "tags"], dropdowns) 113 | generate_pages("SQL Instance", "name", 114 | ["selfLink", "connectionName", "databaseVersion", "ipAddress", ["settings", "dataDiskSizeGb"], ["settings", "backupConfiguration"], 115 | ["settings", "ipConfiguration"], "serviceAccountEmailAddress", "gceZone" ], dropdowns) 116 | generate_pages("Service Account", "displayName", ["email", "name", "keys", "iam_policies", "uniqueId", "roles"], dropdowns) 117 | generate_pages("Address", "address", ["addressType","name","purpose","subnetwork"], dropdowns) 118 | generate_pages("Cluster", "name", ["nodeConfig", "addonsConfig","loggingService","privateClusterConfig","enablePrivateNodes","podSecurityPolicyConfig"], dropdowns) 119 | -------------------------------------------------------------------------------- /categories/firewalls.py: -------------------------------------------------------------------------------- 1 | from tinydb import Query 2 | 3 | 4 | def add_network_rules(projectId, db): 5 | for firewall in db.table('Firewall').all(): 6 | try: 7 | if not firewall.get('sourceRanges'): 8 | firewall['sourceRanges'] = firewall['sourceTags'] 9 | except KeyError: 10 | firewall['sourceRanges'] = "N/A" 11 | try: 12 | if not firewall.get('destinationRanges'): 13 | firewall['destinationRanges'] = firewall['destinationTags'] 14 | except KeyError: 15 | firewall['destinationRanges'] = "N/A" 16 | db.table('Network').update( 17 | add_rule({ 18 | "name": firewall['name'], 19 | "allowed": firewall.get('allowed'), 20 | "sourceRanges": firewall['sourceRanges'], 21 | "destinationRanges": firewall['destinationRanges'], 22 | "tags": firewall.get('targetTags') 23 | }), 24 | eids=[db.table('Network').get( 25 | Query().selfLink == firewall['network'] 26 | ).eid]) 27 | 28 | 29 | def add_affected_instances(projectId, db): 30 | for firewall in db.table('Firewall').all(): 31 | try: 32 | for instance in db.table('Network').get(Query().selfLink == firewall['network'])['members']: 33 | try: 34 | if not firewall.get('targetTags'): 35 | db.table('Firewall').update( 36 | add_instance({ 37 | "kind": instance['kind'], 38 | "selfLink": instance['selfLink'], 39 | # "tags":instance.get('tags'), 40 | "name": instance['name'] 41 | }), eids=[firewall.eid]) 42 | try: 43 | for tag in instance.get('tags'): 44 | if tag in firewall.get('targetTags'): 45 | db.table('Firewall').update( 46 | add_instance({ 47 | "kind": instance['kind'], 48 | "selfLink": instance['selfLink'], 49 | # "tags":instance.get('tags'), 50 | "name": instance['name'] 51 | }), eids=[firewall.eid]) 52 | except TypeError: 53 | continue 54 | except KeyError: 55 | continue 56 | except KeyError: 57 | continue 58 | 59 | 60 | # Function to pass Tinydb for the update query 61 | def add_instance(instance): 62 | def transform(element): 63 | try: 64 | element['affectedInstances'].append(instance) 65 | except KeyError: 66 | element['affectedInstances'] = [instance] 67 | 68 | return transform 69 | 70 | 71 | def add_rule(rule): 72 | def transform(element): 73 | try: 74 | element['firewallRules'].append(rule) 75 | except KeyError: 76 | element['firewallRules'] = [rule] 77 | 78 | return transform 79 | 80 | 81 | def port_in_range(port, ranges): 82 | for range in ranges: 83 | if "-" in range: 84 | range_split = str.split(str(range), "-") 85 | if int(range_split[0]) <= int(port) <= int(range_split[1]): 86 | return True 87 | elif int(port) == int(range): 88 | return True 89 | 90 | 91 | def test_allowed(rule, IPProtocol, ports): 92 | for allow in rule['allowed']: 93 | if not allow['IPProtocol'] == IPProtocol: 94 | continue 95 | for port in ports: 96 | if allow.get('ports') and port_in_range(port, allow['ports']): 97 | return True 98 | if not allow.get('ports'): 99 | return True 100 | 101 | #It's messy but it seems to work. Will tell you whether another firewall rule overrides the given one 102 | #Hopefully there will soon be an API endpoint to replace this. Not being used by default. 103 | from ipaddress import IPv4Network 104 | def overriden(firewall): 105 | priority = firewall['priority'] 106 | for comparison_rule in db.table("Firewall").all(): 107 | if comparison_rule['priority'] < priority \ 108 | or (comparison_rule['priority'] == priority and firewall.get("allowed")): 109 | allow_or_deny = "allowed" if firewall.get("allowed") else "denied" 110 | if allow_or_deny not in comparison_rule: 111 | if tags_encompassed(firewall, comparison_rule): 112 | if firewall['direction'] == comparison_rule['direction']: 113 | if allow_or_deny == "allowed": 114 | opposite = "denied" 115 | else: 116 | opposite = "allowed" 117 | if ports_fully_encompassed(firewall[allow_or_deny], comparison_rule[opposite]): 118 | higher_priority_cidr = comparison_rule.get("sourceRanges") or comparison_rule.get("destinationRanges") 119 | lower_priority_cidr = firewall.get("sourceRanges") or firewall.get("destinationRanges") 120 | if ips_fully_encompassed(lower_priority_cidr, higher_priority_cidr): 121 | #overriden by comparison_rule 122 | return True 123 | return False 124 | 125 | def ports_fully_encompassed(lower_priority_ports, higher_priority_ports): 126 | ledger = [] 127 | for lower in lower_priority_ports: 128 | for higher in higher_priority_ports: 129 | if lower['IPProtocol'] == higher['IPProtocol']: 130 | for lower_port in lower['ports']: 131 | encompassed = False 132 | for higher_port in higher['ports']: 133 | if range_fully_encompassed(lower_port, higher_port): 134 | encompassed = True 135 | ledger.append(encompassed) 136 | if False in ledger: 137 | return False 138 | else: 139 | return True 140 | 141 | def range_fully_encompassed(lower_range_or_num, higher_range_or_num): 142 | if "-" not in lower_range_or_num and "-" not in higher_range_or_num and lower_range_or_num != higher_range_or_num: 143 | return False 144 | if "-" in lower_range_or_num and "-" not in higher_range_or_num: 145 | return False 146 | if "-" in higher_range_or_num and "-" not in lower_range_or_num: 147 | ends = higher_range_or_num.split("-") 148 | if int(lower_range_or_num) < int(ends[0]) or int(lower_range_or_num) > int(ends[1]): 149 | return False 150 | if "-" in lower_range_or_num and "-" in higher_range_or_num: 151 | lower_ends = lower_range_or_num.split("-") 152 | higher_ends = higher_range_or_num.split("-") 153 | if int(lower_ends[0]) < int(higher_ends[0]) or int(lower_ends[1]) > int(higher_ends[1]): 154 | return False 155 | return True 156 | 157 | import ipaddress 158 | def ips_fully_encompassed(lower_priority_cidr, higher_priority_cidr): 159 | ledger = [] 160 | if lower_priority_cidr and not higher_priority_cidr: 161 | return False 162 | if higher_priority_cidr and not lower_priority_cidr: 163 | return False 164 | if not lower_priority_cidr and not higher_priority_cidr: 165 | return True 166 | for lower_cidr in lower_priority_cidr: 167 | encompassed = False 168 | for higher_cidr in higher_priority_cidr: 169 | if IPv4Network(lower_cidr).subnet_of(IPv4Network(higher_cidr)): 170 | encompassed = True 171 | ledger.append(encompassed) 172 | if False in ledger: 173 | return False 174 | else: 175 | return True 176 | 177 | def tags_encompassed(firewall, comparison_rule): 178 | if comparison_rule.get('targetTags') and not firewall.get('targetTags'): 179 | return False 180 | if not comparison_rule.get('targetTags') and firewall.get('targetTags'): 181 | return True 182 | if comparison_rule.get('targetTags') and firewall.get('targetTags'): 183 | if set(firewall['targetTags']).issubset(set(comparison_rule['targetTags'])): 184 | return True 185 | if comparison_rule.get('sourceTags') and not firewall.get('sourceTags'): 186 | return False 187 | if not comparison_rule.get('sourceTags') and firewall.get('sourceTags'): 188 | return True 189 | if comparison_rule.get('sourceTags') and firewall.get('sourceTags'): 190 | if set(firewall['sourceTags']).issubset(set(comparison_rule['sourceTags'])): 191 | return True 192 | return False -------------------------------------------------------------------------------- /gscout.py: -------------------------------------------------------------------------------- 1 | from googleapiclient import discovery 2 | from oauth2client.client import ApplicationDefaultCredentialsError 3 | from oauth2client.client import HttpAccessTokenRefreshError 4 | from oauth2client.file import Storage 5 | from tinydb import TinyDB 6 | import os 7 | from core.fetch import fetch 8 | from core.utility import object_id_to_directory_name 9 | import logging 10 | import urllib 11 | import argparse 12 | import shutil 13 | import sys 14 | import traceback 15 | 16 | storage = Storage('creds.data') 17 | 18 | from core.utility import get_gcloud_creds 19 | 20 | logging.basicConfig(filename="log.txt") 21 | logging.getLogger().setLevel(logging.ERROR) 22 | # Silence some errors 23 | logging.getLogger('googleapiclient.discovery_cache').setLevel(logging.ERROR) 24 | 25 | project_db_name = "projects.json" 26 | if os.path.isfile(project_db_name): 27 | try: 28 | os.remove(project_db_name) 29 | except Exception as e: 30 | msg = "could not remove the existing project database file '%s'. No further processing will take place. The error encountered was: %s" % (project_db_name, e) 31 | print("Error: %s" % (msg)) 32 | logging.error(msg) 33 | sys.exit(1) 34 | db = TinyDB(project_db_name) 35 | 36 | 37 | def list_projects(project_or_org, specifier): 38 | service = discovery.build('cloudresourcemanager', 'v1', credentials=get_gcloud_creds()) 39 | service2 = discovery.build('cloudresourcemanager', 'v2',credentials=get_gcloud_creds()) 40 | # the filter criteria need double-quotes around them in case they contain special characters, like colons 41 | # this was not documented ANYWHERE that I could find when I made this change 42 | # but if the double-quotes are not there, you'll get errors like the following: 43 | 44 | # googleapiclient.errors.HttpError: 46 | 47 | # HttpError 400 when requesting https://cloudresourcemanager.googleapis.com/v1/projects?filter=id%3Adatadog%3Aproject&alt=json 48 | # returned "field [query] has issue [Invalid filter query: resourceType="cloudresourcemanager.projects" AND (projectId = datadog:project)]" 49 | 50 | if project_or_org == "organization": 51 | child = service2.folders().list(parent='organizations/%s' % specifier) 52 | child_response = child.execute() 53 | request = service.projects().list(filter='parent.id:"%s"' % specifier) 54 | if 'folders' in child_response.keys() : 55 | for folder in child_response['folders'] : 56 | list_projects("folder-id", folder['name'].strip(u'folders/')) 57 | elif project_or_org == "project-name": 58 | request = service.projects().list(filter='name:"%s"' % specifier) 59 | elif project_or_org == "project-id": 60 | request = service.projects().list(filter='id:"%s"' % specifier) 61 | elif project_or_org=="folder-id": 62 | child = service2.folders().list(parent='folders/%s' % specifier) 63 | child_response = child.execute() 64 | request = service.projects().list(filter='parent.id:%s' % specifier) 65 | if 'folders' in child_response.keys() : 66 | for folder in child_response['folders'] : 67 | list_projects("folder-id", folder['name'].strip(u'folders/')) 68 | else: 69 | raise Exception('Organization or Project not specified.') 70 | add_projects(request, service) 71 | 72 | def add_projects(request, service): 73 | while request is not None: 74 | response = request.execute() 75 | if 'projects' in response.keys(): 76 | for project in response['projects']: 77 | if (project['lifecycleState'] != "DELETE_REQUESTED"): 78 | db.table('Project').insert(project) 79 | 80 | request = service.projects().list_next(previous_request=request, 81 | previous_response=response) 82 | 83 | 84 | def fetch_all(project, overwrite_existing): 85 | continue_fetching = True 86 | project_db_dir = "project_dbs" 87 | if not os.path.isdir(project_db_dir): 88 | try: 89 | os.makedirs(project_db_dir) 90 | except Exception as e: 91 | msg = "could not make project database directory '%s'. No further processing will take place. The error encountered was: %s" % (project_db_dir, e) 92 | print("Error: %s" % (msg)) 93 | logging.error(msg) 94 | continue_fetching = False 95 | if continue_fetching: 96 | project_output_dir = os.path.join("Report Output", object_id_to_directory_name(project['projectId'])) 97 | make_project_output_dir = True 98 | # Don't overwrite existing output unless the user has requested to do so 99 | if os.path.isdir(project_output_dir): 100 | if overwrite_existing: 101 | msg = "overwriting existing data and output for project '%s'" % (project['projectId']) 102 | print("Warning: %s" % (msg)) 103 | logging.warning(msg) 104 | # Delete any existing output files to avoid confusion 105 | try: 106 | shutil.rmtree(project_output_dir) 107 | except Exception as e: 108 | msg = "could not delete existing output directory '%s'. No further processing will take place. The error encountered was: %s" % (project_output_dir, e) 109 | print("Error: %s" % (msg)) 110 | logging.error(msg) 111 | continue_fetching = False 112 | else: 113 | msg = "there is an existing output directory for project '%s' ('%s'). Rerun with --overwrite to delete and recreate the content." % (project['projectId'], project_output_dir) 114 | print("Error: %s" % (msg)) 115 | logging.error(msg) 116 | make_project_output_dir = False 117 | continue_fetching = False 118 | if make_project_output_dir: 119 | try: 120 | os.makedirs(project_output_dir) 121 | except Exception as e: 122 | msg = "could not make project output directory '%s'. No further processing will take place. The error encountered was: %s" % (project_output_dir, e) 123 | print("Error: %s" % (msg)) 124 | logging.error(msg) 125 | continue_fetching = False 126 | if continue_fetching: 127 | # fetch(project['projectId']) 128 | try: 129 | fetch(project['projectId']) 130 | except Exception as e: 131 | msg = "could not fetch project '%s'. The error encountered was: %s%s%sStack trace:%s%s" % (project['projectId'], e, os.linesep, os.linesep, os.linesep, traceback.format_exc()) 132 | print("Error: %s" % (msg)) 133 | logging.exception(msg) 134 | 135 | def main(): 136 | # configure command line parameters 137 | parser = argparse.ArgumentParser(description='Google Cloud Platform Security Tool') 138 | parser.add_argument('--overwrite', action='store_true', help='Overwrite existing output for the same projects') 139 | group = parser.add_mutually_exclusive_group(required=True) 140 | group.add_argument('--project-name', '-p-name', help='Project name to scan') 141 | group.add_argument('--project-id', '-p-id', help='Project id to scan') 142 | group.add_argument('--organization', '-o', help='Organization id to scan') 143 | group.add_argument('--folder-id', '-f-id', help='Folder id to scan') 144 | args = parser.parse_args() 145 | 146 | output_dir = "Report Output" 147 | if not os.path.isdir(output_dir): 148 | try: 149 | os.makedirs(output_dir) 150 | except Exception as e: 151 | msg = "could not make output directory '%s'. The error encountered was: %s%s%sStack trace:%s%s" % (output_dir, e, os.linesep, os.linesep, os.linesep, traceback.format_exc()) 152 | print("Error: %s" % (msg)) 153 | logging.exception(msg) 154 | try: 155 | if args.project_name : 156 | list_projects(project_or_org='project-name', specifier=args.project_name) 157 | elif args.project_id : 158 | list_projects(project_or_org='project-id', specifier=args.project_id) 159 | elif args.folder_id : 160 | list_projects(project_or_org='folder-id', specifier=args.folder_id) 161 | else: 162 | list_projects(project_or_org='organization', specifier=args.organization) 163 | except (HttpAccessTokenRefreshError, ApplicationDefaultCredentialsError): 164 | from core import config 165 | list_projects(project_or_org='project' if args.project else 'organization', 166 | specifier=args.project if args.project else args.organization) 167 | 168 | for project in db.table("Project").all(): 169 | print("Scouting ", project['projectId']) 170 | fetch_all(project, args.overwrite) 171 | 172 | 173 | if __name__ == "__main__": 174 | main() -------------------------------------------------------------------------------- /core/rules.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | 3 | from googleapiclient import discovery 4 | from oauth2client.file import Storage 5 | 6 | from tinydb import TinyDB 7 | 8 | from core import add_finding 9 | from categories.firewalls import test_allowed 10 | from categories.service_account_keys import key_is_old 11 | 12 | from core.utility import object_id_to_directory_name 13 | from core.utility import get_gcloud_creds 14 | 15 | 16 | def rules(projectId): 17 | db = TinyDB("project_dbs/" + object_id_to_directory_name(projectId) + ".json") 18 | 19 | class Rule: 20 | def __init__(self, rule_title, category, filter_func): 21 | try: 22 | formatted_title = rule_title 23 | # formatted_title = "%s - %s" % (category, rule_title) 24 | # print("Inserting %s" % (formatted_title)) 25 | db.table('Rule').insert({"title": formatted_title, "category": category}) 26 | for entity in list(filter(filter_func, db.table(category).all())): 27 | add_finding.add_finding(db, category, entity.eid, rule_title) 28 | except Exception as e: 29 | print("Error inserting %s: %s" % (rule_title, e)) 30 | except KeyError: 31 | pass 32 | 33 | Rule("Unused Network", "Network", 34 | lambda network: not network.get('members')) 35 | 36 | Rule("VPC Flow Logs Disabled for Subnet", "Subnet", 37 | lambda subnet: not 'enableFlowLogs' in subnet.keys() or not subnet['enableFlowLogs']) 38 | 39 | # This isn't really a security finding, but there's not a good way to include it as informational without changing a bunch of other things 40 | Rule("VPC Flow Logs Enabled for Subnet", "Subnet", 41 | lambda subnet: 'enableFlowLogs' in subnet.keys() and subnet['enableFlowLogs']) 42 | 43 | Rule("Unrestriced Internal Traffic", "Network", 44 | lambda network: network.get('firewallRules') 45 | and [True for rule in network['firewallRules'] 46 | if "10.128.0.0/9" in rule['sourceRanges'] 47 | and [True for allow in rule['allowed'] 48 | if not allow.get('ports') or "0-65535" in allow['ports']]]) 49 | 50 | Rule("Primitive Roles in Use", "Role", 51 | lambda role: role['role'] in ["roles/owner", "roles/editor", "roles/viewer"]) 52 | 53 | 54 | try: 55 | Rule("Role Assigned Directly to User", "Role", 56 | lambda role: [True for member in role['members'] if ((len(member) > 4) and (member[:4] == "user"))]) 57 | except Exception as e: 58 | print("Error adding 'Role Assigned Directly to User' rule: %s" % (e)) 59 | 60 | Rule("Bucket Grants Access to allUsers", "Bucket", 61 | lambda bucket: 'acls' in bucket.keys() and [True for acl in bucket['acls'] if acl['scope'] == "allUsers"]) 62 | 63 | Rule("Bucket Grants Access to allAuthenticatedUsers", "Bucket", 64 | lambda bucket: 'acls' in bucket.keys() and [True for acl in bucket['acls'] if acl['scope'] == "allAuthenticatedUsers"]) 65 | 66 | try: 67 | Rule("User Assigned Bucket Permissions Directly", "Bucket", 68 | lambda bucket: 'acls' in bucket.keys() and [True for acl in bucket['acls'] if acl['scope'][:4] == "user"]) 69 | except Exception as e: 70 | print("Error adding 'User Assigned Bucket Permissions Directly' rule: %s" % (e)) 71 | 72 | Rule("Bucket Logging Not Enabled", "Bucket", lambda bucket: "logging" not in bucket) 73 | 74 | Rule("Bucket Versioning Not Enabled", "Bucket", 75 | lambda bucket: "versioning" not in bucket) 76 | 77 | Rule("Owner Role for allUsers in Bucket Default ACL", "Bucket", 78 | lambda bucket: bucket.get('defacls') and [True for defacl in bucket['defacls'] if 79 | defacl['scope'] == "allUsers" and defacl['permission'] == "OWNER"]) 80 | 81 | Rule("Read Role for allUsers in Bucket Default ACL", "Bucket", 82 | lambda bucket: bucket.get('defacls') and [True for defacl in bucket['defacls'] if 83 | defacl['scope'] == "allUsers" and defacl['permission'] == "READER"]) 84 | try: 85 | Rule("No Recent Compute Engine Backup Images", "Compute Engine", 86 | lambda instance: db.table('Snapshot').all() 87 | and [True for snapshot in db.table('Snapshot').all() 88 | if not [True for disk in instance['disks'] 89 | if snapshot['sourceDisk'] in disk.values()] 90 | and 'creationTimestamp' in snapshot.keys() and len(snapshot['creationTimestamp']) > 10 and datetime.datetime.strptime(snapshot['creationTimestamp'][:10], "%Y-%m-%d") 91 | < datetime.datetime.now() - datetime.timedelta(days=30)]) 92 | except Exception as e: 93 | print("Error creating 'No Recent Compute Engine Backup Images' rule: %s" % (e)) 94 | 95 | try: 96 | # Rule("Allows full access to all Cloud APIs", "Compute Engine", lambda instance: "https://www.googleapis.com/auth/cloud-platform" in instance['serviceAccounts'][0]['scopes']) 97 | # This is kind of a bad check, because it doesn't take into account the IAM policies which apply to the service accounts. 98 | # Access scopes are also a "legacy" method according to Google: https://cloud.google.com/compute/docs/access/service-accounts 99 | # Having it is arguably better than not having it, but it's misleading. 100 | # On the other hand, trying to take the IAM policies into account would also be a challenge. 101 | Rule("Service Account is Allowed Full Access to all Cloud APIs via Instance", "Compute Engine", lambda instance: 'serviceAccounts' in instance.keys() and [ True for service_account in instance['serviceAccounts'] if 'scopes' in service_account.keys() and "https://www.googleapis.com/auth/cloud-platform" in service_account['scopes'] ]) 102 | except Exception as e: 103 | print("Error adding rule 'Allows full access to all Cloud APIs': %s" % (e)) 104 | 105 | Rule("Compute Engine with Serial Port Enabled", "Compute Engine", lambda instance: instance.get("metadata").get("items") 106 | and [True for item in instance.get("metadata").get("items") if item['key']=="serial-port-enable" and item['value']=='true']) 107 | 108 | Rule("Cloud SQL Automatic Backup Disabled", "SQL Instance", 109 | # lambda instance: not instance.get('settings').get('backupConfiguration').get('enabled')) 110 | # Ignore this rule for replicas 111 | lambda instance: 'REPLICA' not in instance.get('instanceType') and not instance.get('settings').get('backupConfiguration').get('enabled')) 112 | 113 | Rule("Cloud SQL Binary Log Disabled", "SQL Instance", 114 | # Ignore this rule for replicas 115 | # PostgreSQL on GCP does not currently support binary logging 116 | lambda instance: 'POSTGRES' not in instance.get('databaseVersion') and 'REPLICA' not in instance.get('instanceType') and not instance.get('settings').get('backupConfiguration').get('binaryLogEnabled')) 117 | 118 | Rule("Cloud SQL Instance does not Require TLS Connections", "SQL Instance", 119 | lambda instance: not instance.get('settings').get('ipConfiguration').get('requireSsl')) 120 | 121 | Rule("Service Account with Unrotated Keys", "Service Account", 122 | lambda account: account.get('keys') 123 | and [True for key in account.get('keys') if key_is_old(key)]) 124 | 125 | Rule("Service Account with allUsers Permission", "Service Account", 126 | lambda account: account.get('iam_policies') 127 | and [True for policy in account.get('iam_policies') 128 | if "allUsers" in policy['scope']]) 129 | 130 | Rule("MongoDB Port Open to All", "Firewall", 131 | lambda firewall: firewall.get("sourceRanges") 132 | and "0.0.0.0/0" in firewall['sourceRanges'] 133 | and [True for rule in firewall['allowed'] if rule.get('ports') 134 | and "27017" in rule['ports']]) 135 | 136 | Rule("PostgreSQL Port Open to All", "Firewall", 137 | lambda firewall: firewall.get("sourceRanges") 138 | and "0.0.0.0/0" in firewall['sourceRanges'] 139 | and [True for rule in firewall['allowed'] if rule.get('ports') 140 | and "54322" in rule['ports']]) 141 | 142 | Rule("Oracle Port Open to All", "Firewall", 143 | lambda firewall: firewall.get("sourceRanges") 144 | and "0.0.0.0/0" in firewall['sourceRanges'] 145 | and [True for rule in firewall['allowed'] if rule.get('ports') 146 | and "1521" in rule['ports']]) 147 | 148 | # "MySQL" and "MS SQL" are not the same thing 149 | Rule("MySQL Port Open to All", "Firewall", 150 | lambda firewall: firewall.get("sourceRanges") 151 | and "0.0.0.0/0" in firewall['sourceRanges'] 152 | and test_allowed(firewall, "tcp", [3306])) 153 | 154 | Rule("Microsoft SQL Server Port Open to All", "Firewall", 155 | lambda firewall: firewall.get("sourceRanges") 156 | and "0.0.0.0/0" in firewall['sourceRanges'] 157 | and test_allowed(firewall, "tcp", [1433])) 158 | 159 | Rule("DNS Port Open to All", "Firewall", 160 | lambda firewall: firewall.get("sourceRanges") 161 | and "0.0.0.0/0" in firewall['sourceRanges'] 162 | and [True for rule in firewall['allowed'] if rule.get('ports') 163 | and "53" in rule['ports']]) 164 | 165 | Rule("FTP Port Open to All", "Firewall", 166 | lambda firewall: firewall.get("sourceRanges") 167 | and "0.0.0.0/0" in firewall['sourceRanges'] 168 | and [True for rule in firewall['allowed'] if rule.get('ports') 169 | and "21" in rule['ports']]) 170 | 171 | Rule("Telnet Port Open to All", "Firewall", 172 | lambda firewall: firewall.get("sourceRanges") 173 | and "0.0.0.0/0" in firewall['sourceRanges'] 174 | and [True for rule in firewall['allowed'] if rule.get('ports') 175 | and "23" in rule['ports']]) 176 | 177 | Rule("RDP Port Open to All", "Firewall", 178 | lambda firewall: firewall.get("sourceRanges") 179 | and "0.0.0.0/0" in firewall['sourceRanges'] 180 | and [True for rule in firewall['allowed'] if rule.get('ports') 181 | and "3389" in rule['ports']]) 182 | 183 | Rule("SSH Port Open to All", "Firewall", 184 | lambda firewall: firewall.get("sourceRanges") 185 | and "0.0.0.0/0" in firewall['sourceRanges'] 186 | and [True for rule in firewall['allowed'] if rule.get('ports') 187 | and "22" in rule['ports']]) 188 | 189 | Rule("All Ports Open to All", "Firewall", 190 | lambda firewall: firewall.get("sourceRanges") 191 | and "0.0.0.0/0" in firewall['sourceRanges'] 192 | and (not firewall.get('allowed')[0].get('ports') 193 | or [True for rule in firewall['allowed'] if rule.get('ports') 194 | and '0-65535' in rule.get('ports')])) 195 | 196 | Rule("Use of Port Ranges in Firewall Rule", "Firewall", 197 | lambda firewall: [allow for allow in firewall['allowed'] 198 | if allow.get('ports') and [port for port in allow['ports'] if "-" in port]]) 199 | 200 | Rule("Unused Firewall Rules", "Firewall", 201 | lambda firewall: not firewall.get('affectedInstances')) 202 | 203 | #GKE 204 | Rule("Legacy ABAC in Use", "Cluster", lambda cluster: cluster.get("legacyAbac")) 205 | Rule("Basic Authentication Enabled", "Cluster", lambda cluster: cluster.get("masterAuth").get("username")) 206 | Rule("Client Certificate Enabled", "Cluster", lambda cluster: cluster.get("masterAuth").get("clientCertificate")) 207 | Rule("No Network Policy", "Cluster", 208 | lambda cluster: cluster.get("addonsConfig").get("networkPolicyConfig").get("disabled")) 209 | #I don't know why this is here too, since node version is in node pools. (same with service account and imageType) 210 | # Rule("Node Version Outdated", "Cluster", lambda cluster: cluster.get('currentNodeVersion') != '') 211 | Rule("Not Using Private Cluster Master", "Cluster", lambda cluster: not cluster.get('privateClusterConfig')) 212 | Rule("Not Using Private Cluster Nodes", "Cluster", lambda cluster: not cluster.get('enablePrivateNodes')) 213 | Rule("Stackdriver Logging Disabled", "Cluster", lambda cluster: not cluster.get('loggingService') or (cluster.get("loggingService") == "none")) 214 | #Rule("Istio Not Enabled", "Cluster", lambda cluster: ) 215 | Rule("Dashboard Configured", "Cluster", lambda cluster: cluster.get("addonsConfig").get("kubernetesDashboard")) 216 | Rule("No Pod Security Policy", "Cluster", lambda cluster: not cluster.get("podSecurityPolicyConfig")) 217 | 218 | #Node Pools 219 | Rule("Auto Upgrade Disabled", "Cluster", lambda cluster: cluster.get("nodePools") and [True for nodePool in cluster.get("nodePools") if nodePool.get('management').get('autoUpgrade')]) 220 | Rule("Image Type not Container Optimized OS", "Cluster", 221 | lambda cluster: cluster.get("nodePools") and [True for nodePool in cluster.get("nodePools") if nodePool.get("config").get("imageType") != "COS"]) 222 | Rule("Node Uses Default Service Account", "Cluster", 223 | lambda cluster: cluster.get("nodePools") and [True for nodePool in cluster.get("nodePools") if "default" in nodePool.get("config").get("serviceAccount")]) 224 | Rule("Node Version Outdated", "Cluster", 225 | lambda cluster: cluster.get("nodePools") and [True for nodePool in cluster.get("nodePools") if nodePool.get("version") != "1.11.5-gke.5"]) 226 | -------------------------------------------------------------------------------- /assets/templates/bootstrap.min.js: -------------------------------------------------------------------------------- 1 | /*! 2 | * Bootstrap v3.3.7 (http://getbootstrap.com) 3 | * Copyright 2011-2016 Twitter, Inc. 4 | * Licensed under the MIT license 5 | */ 6 | if("undefined"==typeof jQuery)throw new Error("Bootstrap's JavaScript requires jQuery");+function(a){"use strict";var b=a.fn.jquery.split(" ")[0].split(".");if(b[0]<2&&b[1]<9||1==b[0]&&9==b[1]&&b[2]<1||b[0]>3)throw new Error("Bootstrap's JavaScript requires jQuery version 1.9.1 or higher, but lower than version 4")}(jQuery),+function(a){"use strict";function b(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var c in b)if(void 0!==a.style[c])return{end:b[c]};return!1}a.fn.emulateTransitionEnd=function(b){var c=!1,d=this;a(this).one("bsTransitionEnd",function(){c=!0});var e=function(){c||a(d).trigger(a.support.transition.end)};return setTimeout(e,b),this},a(function(){a.support.transition=b(),a.support.transition&&(a.event.special.bsTransitionEnd={bindType:a.support.transition.end,delegateType:a.support.transition.end,handle:function(b){if(a(b.target).is(this))return b.handleObj.handler.apply(this,arguments)}})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var c=a(this),e=c.data("bs.alert");e||c.data("bs.alert",e=new d(this)),"string"==typeof b&&e[b].call(c)})}var c='[data-dismiss="alert"]',d=function(b){a(b).on("click",c,this.close)};d.VERSION="3.3.7",d.TRANSITION_DURATION=150,d.prototype.close=function(b){function c(){g.detach().trigger("closed.bs.alert").remove()}var e=a(this),f=e.attr("data-target");f||(f=e.attr("href"),f=f&&f.replace(/.*(?=#[^\s]*$)/,""));var g=a("#"===f?[]:f);b&&b.preventDefault(),g.length||(g=e.closest(".alert")),g.trigger(b=a.Event("close.bs.alert")),b.isDefaultPrevented()||(g.removeClass("in"),a.support.transition&&g.hasClass("fade")?g.one("bsTransitionEnd",c).emulateTransitionEnd(d.TRANSITION_DURATION):c())};var e=a.fn.alert;a.fn.alert=b,a.fn.alert.Constructor=d,a.fn.alert.noConflict=function(){return a.fn.alert=e,this},a(document).on("click.bs.alert.data-api",c,d.prototype.close)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.button"),f="object"==typeof b&&b;e||d.data("bs.button",e=new c(this,f)),"toggle"==b?e.toggle():b&&e.setState(b)})}var c=function(b,d){this.$element=a(b),this.options=a.extend({},c.DEFAULTS,d),this.isLoading=!1};c.VERSION="3.3.7",c.DEFAULTS={loadingText:"loading..."},c.prototype.setState=function(b){var c="disabled",d=this.$element,e=d.is("input")?"val":"html",f=d.data();b+="Text",null==f.resetText&&d.data("resetText",d[e]()),setTimeout(a.proxy(function(){d[e](null==f[b]?this.options[b]:f[b]),"loadingText"==b?(this.isLoading=!0,d.addClass(c).attr(c,c).prop(c,!0)):this.isLoading&&(this.isLoading=!1,d.removeClass(c).removeAttr(c).prop(c,!1))},this),0)},c.prototype.toggle=function(){var a=!0,b=this.$element.closest('[data-toggle="buttons"]');if(b.length){var c=this.$element.find("input");"radio"==c.prop("type")?(c.prop("checked")&&(a=!1),b.find(".active").removeClass("active"),this.$element.addClass("active")):"checkbox"==c.prop("type")&&(c.prop("checked")!==this.$element.hasClass("active")&&(a=!1),this.$element.toggleClass("active")),c.prop("checked",this.$element.hasClass("active")),a&&c.trigger("change")}else this.$element.attr("aria-pressed",!this.$element.hasClass("active")),this.$element.toggleClass("active")};var d=a.fn.button;a.fn.button=b,a.fn.button.Constructor=c,a.fn.button.noConflict=function(){return a.fn.button=d,this},a(document).on("click.bs.button.data-api",'[data-toggle^="button"]',function(c){var d=a(c.target).closest(".btn");b.call(d,"toggle"),a(c.target).is('input[type="radio"], input[type="checkbox"]')||(c.preventDefault(),d.is("input,button")?d.trigger("focus"):d.find("input:visible,button:visible").first().trigger("focus"))}).on("focus.bs.button.data-api blur.bs.button.data-api",'[data-toggle^="button"]',function(b){a(b.target).closest(".btn").toggleClass("focus",/^focus(in)?$/.test(b.type))})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.carousel"),f=a.extend({},c.DEFAULTS,d.data(),"object"==typeof b&&b),g="string"==typeof b?b:f.slide;e||d.data("bs.carousel",e=new c(this,f)),"number"==typeof b?e.to(b):g?e[g]():f.interval&&e.pause().cycle()})}var c=function(b,c){this.$element=a(b),this.$indicators=this.$element.find(".carousel-indicators"),this.options=c,this.paused=null,this.sliding=null,this.interval=null,this.$active=null,this.$items=null,this.options.keyboard&&this.$element.on("keydown.bs.carousel",a.proxy(this.keydown,this)),"hover"==this.options.pause&&!("ontouchstart"in document.documentElement)&&this.$element.on("mouseenter.bs.carousel",a.proxy(this.pause,this)).on("mouseleave.bs.carousel",a.proxy(this.cycle,this))};c.VERSION="3.3.7",c.TRANSITION_DURATION=600,c.DEFAULTS={interval:5e3,pause:"hover",wrap:!0,keyboard:!0},c.prototype.keydown=function(a){if(!/input|textarea/i.test(a.target.tagName)){switch(a.which){case 37:this.prev();break;case 39:this.next();break;default:return}a.preventDefault()}},c.prototype.cycle=function(b){return b||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(a.proxy(this.next,this),this.options.interval)),this},c.prototype.getItemIndex=function(a){return this.$items=a.parent().children(".item"),this.$items.index(a||this.$active)},c.prototype.getItemForDirection=function(a,b){var c=this.getItemIndex(b),d="prev"==a&&0===c||"next"==a&&c==this.$items.length-1;if(d&&!this.options.wrap)return b;var e="prev"==a?-1:1,f=(c+e)%this.$items.length;return this.$items.eq(f)},c.prototype.to=function(a){var b=this,c=this.getItemIndex(this.$active=this.$element.find(".item.active"));if(!(a>this.$items.length-1||a<0))return this.sliding?this.$element.one("slid.bs.carousel",function(){b.to(a)}):c==a?this.pause().cycle():this.slide(a>c?"next":"prev",this.$items.eq(a))},c.prototype.pause=function(b){return b||(this.paused=!0),this.$element.find(".next, .prev").length&&a.support.transition&&(this.$element.trigger(a.support.transition.end),this.cycle(!0)),this.interval=clearInterval(this.interval),this},c.prototype.next=function(){if(!this.sliding)return this.slide("next")},c.prototype.prev=function(){if(!this.sliding)return this.slide("prev")},c.prototype.slide=function(b,d){var e=this.$element.find(".item.active"),f=d||this.getItemForDirection(b,e),g=this.interval,h="next"==b?"left":"right",i=this;if(f.hasClass("active"))return this.sliding=!1;var j=f[0],k=a.Event("slide.bs.carousel",{relatedTarget:j,direction:h});if(this.$element.trigger(k),!k.isDefaultPrevented()){if(this.sliding=!0,g&&this.pause(),this.$indicators.length){this.$indicators.find(".active").removeClass("active");var l=a(this.$indicators.children()[this.getItemIndex(f)]);l&&l.addClass("active")}var m=a.Event("slid.bs.carousel",{relatedTarget:j,direction:h});return a.support.transition&&this.$element.hasClass("slide")?(f.addClass(b),f[0].offsetWidth,e.addClass(h),f.addClass(h),e.one("bsTransitionEnd",function(){f.removeClass([b,h].join(" ")).addClass("active"),e.removeClass(["active",h].join(" ")),i.sliding=!1,setTimeout(function(){i.$element.trigger(m)},0)}).emulateTransitionEnd(c.TRANSITION_DURATION)):(e.removeClass("active"),f.addClass("active"),this.sliding=!1,this.$element.trigger(m)),g&&this.cycle(),this}};var d=a.fn.carousel;a.fn.carousel=b,a.fn.carousel.Constructor=c,a.fn.carousel.noConflict=function(){return a.fn.carousel=d,this};var e=function(c){var d,e=a(this),f=a(e.attr("data-target")||(d=e.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,""));if(f.hasClass("carousel")){var g=a.extend({},f.data(),e.data()),h=e.attr("data-slide-to");h&&(g.interval=!1),b.call(f,g),h&&f.data("bs.carousel").to(h),c.preventDefault()}};a(document).on("click.bs.carousel.data-api","[data-slide]",e).on("click.bs.carousel.data-api","[data-slide-to]",e),a(window).on("load",function(){a('[data-ride="carousel"]').each(function(){var c=a(this);b.call(c,c.data())})})}(jQuery),+function(a){"use strict";function b(b){var c,d=b.attr("data-target")||(c=b.attr("href"))&&c.replace(/.*(?=#[^\s]+$)/,"");return a(d)}function c(b){return this.each(function(){var c=a(this),e=c.data("bs.collapse"),f=a.extend({},d.DEFAULTS,c.data(),"object"==typeof b&&b);!e&&f.toggle&&/show|hide/.test(b)&&(f.toggle=!1),e||c.data("bs.collapse",e=new d(this,f)),"string"==typeof b&&e[b]()})}var d=function(b,c){this.$element=a(b),this.options=a.extend({},d.DEFAULTS,c),this.$trigger=a('[data-toggle="collapse"][href="#'+b.id+'"],[data-toggle="collapse"][data-target="#'+b.id+'"]'),this.transitioning=null,this.options.parent?this.$parent=this.getParent():this.addAriaAndCollapsedClass(this.$element,this.$trigger),this.options.toggle&&this.toggle()};d.VERSION="3.3.7",d.TRANSITION_DURATION=350,d.DEFAULTS={toggle:!0},d.prototype.dimension=function(){var a=this.$element.hasClass("width");return a?"width":"height"},d.prototype.show=function(){if(!this.transitioning&&!this.$element.hasClass("in")){var b,e=this.$parent&&this.$parent.children(".panel").children(".in, .collapsing");if(!(e&&e.length&&(b=e.data("bs.collapse"),b&&b.transitioning))){var f=a.Event("show.bs.collapse");if(this.$element.trigger(f),!f.isDefaultPrevented()){e&&e.length&&(c.call(e,"hide"),b||e.data("bs.collapse",null));var g=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[g](0).attr("aria-expanded",!0),this.$trigger.removeClass("collapsed").attr("aria-expanded",!0),this.transitioning=1;var h=function(){this.$element.removeClass("collapsing").addClass("collapse in")[g](""),this.transitioning=0,this.$element.trigger("shown.bs.collapse")};if(!a.support.transition)return h.call(this);var i=a.camelCase(["scroll",g].join("-"));this.$element.one("bsTransitionEnd",a.proxy(h,this)).emulateTransitionEnd(d.TRANSITION_DURATION)[g](this.$element[0][i])}}}},d.prototype.hide=function(){if(!this.transitioning&&this.$element.hasClass("in")){var b=a.Event("hide.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.dimension();this.$element[c](this.$element[c]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse in").attr("aria-expanded",!1),this.$trigger.addClass("collapsed").attr("aria-expanded",!1),this.transitioning=1;var e=function(){this.transitioning=0,this.$element.removeClass("collapsing").addClass("collapse").trigger("hidden.bs.collapse")};return a.support.transition?void this.$element[c](0).one("bsTransitionEnd",a.proxy(e,this)).emulateTransitionEnd(d.TRANSITION_DURATION):e.call(this)}}},d.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()},d.prototype.getParent=function(){return a(this.options.parent).find('[data-toggle="collapse"][data-parent="'+this.options.parent+'"]').each(a.proxy(function(c,d){var e=a(d);this.addAriaAndCollapsedClass(b(e),e)},this)).end()},d.prototype.addAriaAndCollapsedClass=function(a,b){var c=a.hasClass("in");a.attr("aria-expanded",c),b.toggleClass("collapsed",!c).attr("aria-expanded",c)};var e=a.fn.collapse;a.fn.collapse=c,a.fn.collapse.Constructor=d,a.fn.collapse.noConflict=function(){return a.fn.collapse=e,this},a(document).on("click.bs.collapse.data-api",'[data-toggle="collapse"]',function(d){var e=a(this);e.attr("data-target")||d.preventDefault();var f=b(e),g=f.data("bs.collapse"),h=g?"toggle":e.data();c.call(f,h)})}(jQuery),+function(a){"use strict";function b(b){var c=b.attr("data-target");c||(c=b.attr("href"),c=c&&/#[A-Za-z]/.test(c)&&c.replace(/.*(?=#[^\s]*$)/,""));var d=c&&a(c);return d&&d.length?d:b.parent()}function c(c){c&&3===c.which||(a(e).remove(),a(f).each(function(){var d=a(this),e=b(d),f={relatedTarget:this};e.hasClass("open")&&(c&&"click"==c.type&&/input|textarea/i.test(c.target.tagName)&&a.contains(e[0],c.target)||(e.trigger(c=a.Event("hide.bs.dropdown",f)),c.isDefaultPrevented()||(d.attr("aria-expanded","false"),e.removeClass("open").trigger(a.Event("hidden.bs.dropdown",f)))))}))}function d(b){return this.each(function(){var c=a(this),d=c.data("bs.dropdown");d||c.data("bs.dropdown",d=new g(this)),"string"==typeof b&&d[b].call(c)})}var e=".dropdown-backdrop",f='[data-toggle="dropdown"]',g=function(b){a(b).on("click.bs.dropdown",this.toggle)};g.VERSION="3.3.7",g.prototype.toggle=function(d){var e=a(this);if(!e.is(".disabled, :disabled")){var f=b(e),g=f.hasClass("open");if(c(),!g){"ontouchstart"in document.documentElement&&!f.closest(".navbar-nav").length&&a(document.createElement("div")).addClass("dropdown-backdrop").insertAfter(a(this)).on("click",c);var h={relatedTarget:this};if(f.trigger(d=a.Event("show.bs.dropdown",h)),d.isDefaultPrevented())return;e.trigger("focus").attr("aria-expanded","true"),f.toggleClass("open").trigger(a.Event("shown.bs.dropdown",h))}return!1}},g.prototype.keydown=function(c){if(/(38|40|27|32)/.test(c.which)&&!/input|textarea/i.test(c.target.tagName)){var d=a(this);if(c.preventDefault(),c.stopPropagation(),!d.is(".disabled, :disabled")){var e=b(d),g=e.hasClass("open");if(!g&&27!=c.which||g&&27==c.which)return 27==c.which&&e.find(f).trigger("focus"),d.trigger("click");var h=" li:not(.disabled):visible a",i=e.find(".dropdown-menu"+h);if(i.length){var j=i.index(c.target);38==c.which&&j>0&&j--,40==c.which&&jdocument.documentElement.clientHeight;this.$element.css({paddingLeft:!this.bodyIsOverflowing&&a?this.scrollbarWidth:"",paddingRight:this.bodyIsOverflowing&&!a?this.scrollbarWidth:""})},c.prototype.resetAdjustments=function(){this.$element.css({paddingLeft:"",paddingRight:""})},c.prototype.checkScrollbar=function(){var a=window.innerWidth;if(!a){var b=document.documentElement.getBoundingClientRect();a=b.right-Math.abs(b.left)}this.bodyIsOverflowing=document.body.clientWidth
',trigger:"hover focus",title:"",delay:0,html:!1,container:!1,viewport:{selector:"body",padding:0}},c.prototype.init=function(b,c,d){if(this.enabled=!0,this.type=b,this.$element=a(c),this.options=this.getOptions(d),this.$viewport=this.options.viewport&&a(a.isFunction(this.options.viewport)?this.options.viewport.call(this,this.$element):this.options.viewport.selector||this.options.viewport),this.inState={click:!1,hover:!1,focus:!1},this.$element[0]instanceof document.constructor&&!this.options.selector)throw new Error("`selector` option must be specified when initializing "+this.type+" on the window.document object!");for(var e=this.options.trigger.split(" "),f=e.length;f--;){var g=e[f];if("click"==g)this.$element.on("click."+this.type,this.options.selector,a.proxy(this.toggle,this));else if("manual"!=g){var h="hover"==g?"mouseenter":"focusin",i="hover"==g?"mouseleave":"focusout";this.$element.on(h+"."+this.type,this.options.selector,a.proxy(this.enter,this)),this.$element.on(i+"."+this.type,this.options.selector,a.proxy(this.leave,this))}}this.options.selector?this._options=a.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.getOptions=function(b){return b=a.extend({},this.getDefaults(),this.$element.data(),b),b.delay&&"number"==typeof b.delay&&(b.delay={show:b.delay,hide:b.delay}),b},c.prototype.getDelegateOptions=function(){var b={},c=this.getDefaults();return this._options&&a.each(this._options,function(a,d){c[a]!=d&&(b[a]=d)}),b},c.prototype.enter=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),b instanceof a.Event&&(c.inState["focusin"==b.type?"focus":"hover"]=!0),c.tip().hasClass("in")||"in"==c.hoverState?void(c.hoverState="in"):(clearTimeout(c.timeout),c.hoverState="in",c.options.delay&&c.options.delay.show?void(c.timeout=setTimeout(function(){"in"==c.hoverState&&c.show()},c.options.delay.show)):c.show())},c.prototype.isInStateTrue=function(){for(var a in this.inState)if(this.inState[a])return!0;return!1},c.prototype.leave=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);if(c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),b instanceof a.Event&&(c.inState["focusout"==b.type?"focus":"hover"]=!1),!c.isInStateTrue())return clearTimeout(c.timeout),c.hoverState="out",c.options.delay&&c.options.delay.hide?void(c.timeout=setTimeout(function(){"out"==c.hoverState&&c.hide()},c.options.delay.hide)):c.hide()},c.prototype.show=function(){var b=a.Event("show.bs."+this.type);if(this.hasContent()&&this.enabled){this.$element.trigger(b);var d=a.contains(this.$element[0].ownerDocument.documentElement,this.$element[0]);if(b.isDefaultPrevented()||!d)return;var e=this,f=this.tip(),g=this.getUID(this.type);this.setContent(),f.attr("id",g),this.$element.attr("aria-describedby",g),this.options.animation&&f.addClass("fade");var h="function"==typeof this.options.placement?this.options.placement.call(this,f[0],this.$element[0]):this.options.placement,i=/\s?auto?\s?/i,j=i.test(h);j&&(h=h.replace(i,"")||"top"),f.detach().css({top:0,left:0,display:"block"}).addClass(h).data("bs."+this.type,this),this.options.container?f.appendTo(this.options.container):f.insertAfter(this.$element),this.$element.trigger("inserted.bs."+this.type);var k=this.getPosition(),l=f[0].offsetWidth,m=f[0].offsetHeight;if(j){var n=h,o=this.getPosition(this.$viewport);h="bottom"==h&&k.bottom+m>o.bottom?"top":"top"==h&&k.top-mo.width?"left":"left"==h&&k.left-lg.top+g.height&&(e.top=g.top+g.height-i)}else{var j=b.left-f,k=b.left+f+c;jg.right&&(e.left=g.left+g.width-k)}return e},c.prototype.getTitle=function(){var a,b=this.$element,c=this.options;return a=b.attr("data-original-title")||("function"==typeof c.title?c.title.call(b[0]):c.title)},c.prototype.getUID=function(a){do a+=~~(1e6*Math.random());while(document.getElementById(a));return a},c.prototype.tip=function(){if(!this.$tip&&(this.$tip=a(this.options.template),1!=this.$tip.length))throw new Error(this.type+" `template` option must consist of exactly 1 top-level element!");return this.$tip},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},c.prototype.enable=function(){this.enabled=!0},c.prototype.disable=function(){this.enabled=!1},c.prototype.toggleEnabled=function(){this.enabled=!this.enabled},c.prototype.toggle=function(b){var c=this;b&&(c=a(b.currentTarget).data("bs."+this.type),c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c))),b?(c.inState.click=!c.inState.click,c.isInStateTrue()?c.enter(c):c.leave(c)):c.tip().hasClass("in")?c.leave(c):c.enter(c)},c.prototype.destroy=function(){var a=this;clearTimeout(this.timeout),this.hide(function(){a.$element.off("."+a.type).removeData("bs."+a.type),a.$tip&&a.$tip.detach(),a.$tip=null,a.$arrow=null,a.$viewport=null,a.$element=null})};var d=a.fn.tooltip;a.fn.tooltip=b,a.fn.tooltip.Constructor=c,a.fn.tooltip.noConflict=function(){return a.fn.tooltip=d,this}}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.popover"),f="object"==typeof b&&b;!e&&/destroy|hide/.test(b)||(e||d.data("bs.popover",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.init("popover",a,b)};if(!a.fn.tooltip)throw new Error("Popover requires tooltip.js");c.VERSION="3.3.7",c.DEFAULTS=a.extend({},a.fn.tooltip.Constructor.DEFAULTS,{placement:"right",trigger:"click",content:"",template:''}),c.prototype=a.extend({},a.fn.tooltip.Constructor.prototype),c.prototype.constructor=c,c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle(),c=this.getContent();a.find(".popover-title")[this.options.html?"html":"text"](b),a.find(".popover-content").children().detach().end()[this.options.html?"string"==typeof c?"html":"append":"text"](c),a.removeClass("fade top bottom left right in"),a.find(".popover-title").html()||a.find(".popover-title").hide()},c.prototype.hasContent=function(){return this.getTitle()||this.getContent()},c.prototype.getContent=function(){var a=this.$element,b=this.options;return a.attr("data-content")||("function"==typeof b.content?b.content.call(a[0]):b.content)},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")};var d=a.fn.popover;a.fn.popover=b,a.fn.popover.Constructor=c,a.fn.popover.noConflict=function(){return a.fn.popover=d,this}}(jQuery),+function(a){"use strict";function b(c,d){this.$body=a(document.body),this.$scrollElement=a(a(c).is(document.body)?window:c),this.options=a.extend({},b.DEFAULTS,d),this.selector=(this.options.target||"")+" .nav li > a",this.offsets=[],this.targets=[],this.activeTarget=null,this.scrollHeight=0,this.$scrollElement.on("scroll.bs.scrollspy",a.proxy(this.process,this)),this.refresh(),this.process()}function c(c){return this.each(function(){var d=a(this),e=d.data("bs.scrollspy"),f="object"==typeof c&&c;e||d.data("bs.scrollspy",e=new b(this,f)),"string"==typeof c&&e[c]()})}b.VERSION="3.3.7",b.DEFAULTS={offset:10},b.prototype.getScrollHeight=function(){return this.$scrollElement[0].scrollHeight||Math.max(this.$body[0].scrollHeight,document.documentElement.scrollHeight)},b.prototype.refresh=function(){var b=this,c="offset",d=0;this.offsets=[],this.targets=[],this.scrollHeight=this.getScrollHeight(),a.isWindow(this.$scrollElement[0])||(c="position",d=this.$scrollElement.scrollTop()),this.$body.find(this.selector).map(function(){var b=a(this),e=b.data("target")||b.attr("href"),f=/^#./.test(e)&&a(e);return f&&f.length&&f.is(":visible")&&[[f[c]().top+d,e]]||null}).sort(function(a,b){return a[0]-b[0]}).each(function(){b.offsets.push(this[0]),b.targets.push(this[1])})},b.prototype.process=function(){var a,b=this.$scrollElement.scrollTop()+this.options.offset,c=this.getScrollHeight(),d=this.options.offset+c-this.$scrollElement.height(),e=this.offsets,f=this.targets,g=this.activeTarget;if(this.scrollHeight!=c&&this.refresh(),b>=d)return g!=(a=f[f.length-1])&&this.activate(a);if(g&&b=e[a]&&(void 0===e[a+1]||b .dropdown-menu > .active").removeClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!1),b.addClass("active").find('[data-toggle="tab"]').attr("aria-expanded",!0),h?(b[0].offsetWidth,b.addClass("in")):b.removeClass("fade"),b.parent(".dropdown-menu").length&&b.closest("li.dropdown").addClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!0),e&&e()}var g=d.find("> .active"),h=e&&a.support.transition&&(g.length&&g.hasClass("fade")||!!d.find("> .fade").length);g.length&&h?g.one("bsTransitionEnd",f).emulateTransitionEnd(c.TRANSITION_DURATION):f(),g.removeClass("in")};var d=a.fn.tab;a.fn.tab=b,a.fn.tab.Constructor=c,a.fn.tab.noConflict=function(){return a.fn.tab=d,this};var e=function(c){c.preventDefault(),b.call(a(this),"show")};a(document).on("click.bs.tab.data-api",'[data-toggle="tab"]',e).on("click.bs.tab.data-api",'[data-toggle="pill"]',e)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.affix"),f="object"==typeof b&&b;e||d.data("bs.affix",e=new c(this,f)),"string"==typeof b&&e[b]()})}var c=function(b,d){this.options=a.extend({},c.DEFAULTS,d),this.$target=a(this.options.target).on("scroll.bs.affix.data-api",a.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",a.proxy(this.checkPositionWithEventLoop,this)),this.$element=a(b),this.affixed=null,this.unpin=null,this.pinnedOffset=null,this.checkPosition()};c.VERSION="3.3.7",c.RESET="affix affix-top affix-bottom",c.DEFAULTS={offset:0,target:window},c.prototype.getState=function(a,b,c,d){var e=this.$target.scrollTop(),f=this.$element.offset(),g=this.$target.height();if(null!=c&&"top"==this.affixed)return e=a-d&&"bottom"},c.prototype.getPinnedOffset=function(){if(this.pinnedOffset)return this.pinnedOffset;this.$element.removeClass(c.RESET).addClass("affix");var a=this.$target.scrollTop(),b=this.$element.offset();return this.pinnedOffset=b.top-a},c.prototype.checkPositionWithEventLoop=function(){setTimeout(a.proxy(this.checkPosition,this),1)},c.prototype.checkPosition=function(){if(this.$element.is(":visible")){var b=this.$element.height(),d=this.options.offset,e=d.top,f=d.bottom,g=Math.max(a(document).height(),a(document.body).height());"object"!=typeof d&&(f=e=d),"function"==typeof e&&(e=d.top(this.$element)),"function"==typeof f&&(f=d.bottom(this.$element));var h=this.getState(g,b,e,f);if(this.affixed!=h){null!=this.unpin&&this.$element.css("top","");var i="affix"+(h?"-"+h:""),j=a.Event(i+".bs.affix");if(this.$element.trigger(j),j.isDefaultPrevented())return;this.affixed=h,this.unpin="bottom"==h?this.getPinnedOffset():null,this.$element.removeClass(c.RESET).addClass(i).trigger(i.replace("affix","affixed")+".bs.affix")}"bottom"==h&&this.$element.offset({top:g-b-f})}};var d=a.fn.affix;a.fn.affix=b,a.fn.affix.Constructor=c,a.fn.affix.noConflict=function(){return a.fn.affix=d,this},a(window).on("load",function(){a('[data-spy="affix"]').each(function(){var c=a(this),d=c.data();d.offset=d.offset||{},null!=d.offsetBottom&&(d.offset.bottom=d.offsetBottom),null!=d.offsetTop&&(d.offset.top=d.offsetTop),b.call(c,d)})})}(jQuery); -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------