diff --git a/Dockerfile b/Dockerfile
new file mode 100644
index 0000000..13cd31d
--- /dev/null
+++ b/Dockerfile
@@ -0,0 +1,42 @@
+# Build and run with docker_run.sh
+# e.g., ./docker_run.sh -q example.com
+#
+# Thank you to Ilya Glotov (https://github.com/andripwn) for help with
+# this minimal alpine image
+
+FROM python:3-alpine
+
+ENV SSDEEP_VERSION="release-2.14.1" \
+ BUILD_DEPS="build-base \
+ automake \
+ autoconf \
+ libtool"
+
+ADD requirements.txt .
+RUN apk --update --no-cache add $BUILD_DEPS \
+ git \
+ libffi-dev \
+ && git clone --depth=1 --branch=$SSDEEP_VERSION https://github.com/ssdeep-project/ssdeep.git \
+ && cd ssdeep \
+ && autoreconf -i \
+ && ./configure \
+ && make \
+ && make install \
+ && cd / \
+ && rm -rf /ssdeep \
+ \
+ && pip3 install -r requirements.txt \
+ \
+ && apk del $BUILD_DEPS \
+ \
+ && adduser -D pwngit
+
+VOLUME ["/pwngit/logs", "/pwngit/states"]
+
+WORKDIR /pwngit
+USER pwngit
+
+ADD checks /pwngit/checks
+ADD pwngit.py .
+ENTRYPOINT ["python3", "pwngit.py"]
+CMD [ "-h" ]
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..65c5ca8
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,165 @@
+ GNU LESSER GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+
+ This version of the GNU Lesser General Public License incorporates
+the terms and conditions of version 3 of the GNU General Public
+License, supplemented by the additional permissions listed below.
+
+ 0. Additional Definitions.
+
+ As used herein, "this License" refers to version 3 of the GNU Lesser
+General Public License, and the "GNU GPL" refers to version 3 of the GNU
+General Public License.
+
+ "The Library" refers to a covered work governed by this License,
+other than an Application or a Combined Work as defined below.
+
+ An "Application" is any work that makes use of an interface provided
+by the Library, but which is not otherwise based on the Library.
+Defining a subclass of a class defined by the Library is deemed a mode
+of using an interface provided by the Library.
+
+ A "Combined Work" is a work produced by combining or linking an
+Application with the Library. The particular version of the Library
+with which the Combined Work was made is also called the "Linked
+Version".
+
+ The "Minimal Corresponding Source" for a Combined Work means the
+Corresponding Source for the Combined Work, excluding any source code
+for portions of the Combined Work that, considered in isolation, are
+based on the Application, and not on the Linked Version.
+
+ The "Corresponding Application Code" for a Combined Work means the
+object code and/or source code for the Application, including any data
+and utility programs needed for reproducing the Combined Work from the
+Application, but excluding the System Libraries of the Combined Work.
+
+ 1. Exception to Section 3 of the GNU GPL.
+
+ You may convey a covered work under sections 3 and 4 of this License
+without being bound by section 3 of the GNU GPL.
+
+ 2. Conveying Modified Versions.
+
+ If you modify a copy of the Library, and, in your modifications, a
+facility refers to a function or data to be supplied by an Application
+that uses the facility (other than as an argument passed when the
+facility is invoked), then you may convey a copy of the modified
+version:
+
+ a) under this License, provided that you make a good faith effort to
+ ensure that, in the event an Application does not supply the
+ function or data, the facility still operates, and performs
+ whatever part of its purpose remains meaningful, or
+
+ b) under the GNU GPL, with none of the additional permissions of
+ this License applicable to that copy.
+
+ 3. Object Code Incorporating Material from Library Header Files.
+
+ The object code form of an Application may incorporate material from
+a header file that is part of the Library. You may convey such object
+code under terms of your choice, provided that, if the incorporated
+material is not limited to numerical parameters, data structure
+layouts and accessors, or small macros, inline functions and templates
+(ten or fewer lines in length), you do both of the following:
+
+ a) Give prominent notice with each copy of the object code that the
+ Library is used in it and that the Library and its use are
+ covered by this License.
+
+ b) Accompany the object code with a copy of the GNU GPL and this license
+ document.
+
+ 4. Combined Works.
+
+ You may convey a Combined Work under terms of your choice that,
+taken together, effectively do not restrict modification of the
+portions of the Library contained in the Combined Work and reverse
+engineering for debugging such modifications, if you also do each of
+the following:
+
+ a) Give prominent notice with each copy of the Combined Work that
+ the Library is used in it and that the Library and its use are
+ covered by this License.
+
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
+ document.
+
+ c) For a Combined Work that displays copyright notices during
+ execution, include the copyright notice for the Library among
+ these notices, as well as a reference directing the user to the
+ copies of the GNU GPL and this license document.
+
+ d) Do one of the following:
+
+ 0) Convey the Minimal Corresponding Source under the terms of this
+ License, and the Corresponding Application Code in a form
+ suitable for, and under terms that permit, the user to
+ recombine or relink the Application with a modified version of
+ the Linked Version to produce a modified Combined Work, in the
+ manner specified by section 6 of the GNU GPL for conveying
+ Corresponding Source.
+
+ 1) Use a suitable shared library mechanism for linking with the
+ Library. A suitable mechanism is one that (a) uses at run time
+ a copy of the Library already present on the user's computer
+ system, and (b) will operate properly with a modified version
+ of the Library that is interface-compatible with the Linked
+ Version.
+
+ e) Provide Installation Information, but only if you would otherwise
+ be required to provide such information under section 6 of the
+ GNU GPL, and only to the extent that such information is
+ necessary to install and execute a modified version of the
+ Combined Work produced by recombining or relinking the
+ Application with a modified version of the Linked Version. (If
+ you use option 4d0, the Installation Information must accompany
+ the Minimal Corresponding Source and Corresponding Application
+ Code. If you use option 4d1, you must provide the Installation
+ Information in the manner specified by section 6 of the GNU GPL
+ for conveying Corresponding Source.)
+
+ 5. Combined Libraries.
+
+ You may place library facilities that are a work based on the
+Library side by side in a single library together with other library
+facilities that are not Applications and are not covered by this
+License, and convey such a combined library under terms of your
+choice, if you do both of the following:
+
+ a) Accompany the combined library with a copy of the same work based
+ on the Library, uncombined with any other library facilities,
+ conveyed under the terms of this License.
+
+ b) Give prominent notice with the combined library that part of it
+ is a work based on the Library, and explaining where to find the
+ accompanying uncombined form of the same work.
+
+ 6. Revised Versions of the GNU Lesser General Public License.
+
+ The Free Software Foundation may publish revised and/or new versions
+of the GNU Lesser General Public License from time to time. Such new
+versions will be similar in spirit to the present version, but may
+differ in detail to address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Library as you received it specifies that a certain numbered version
+of the GNU Lesser General Public License "or any later version"
+applies to it, you have the option of following the terms and
+conditions either of that published version or of any later version
+published by the Free Software Foundation. If the Library as you
+received it does not specify a version number of the GNU Lesser
+General Public License, you may choose any version of the GNU Lesser
+General Public License ever published by the Free Software Foundation.
+
+ If the Library as you received it specifies that a proxy can decide
+whether future versions of the GNU Lesser General Public License shall
+apply, that proxy's public statement of acceptance of any version is
+permanent authorization for you to choose that version for the
+Library.
diff --git a/README.md b/README.md
index 2516229..c6717a0 100644
--- a/README.md
+++ b/README.md
@@ -1,2 +1,109 @@
-# PwnGIT
+
+
+
+
+#
+
+
+![License](https://img.shields.io/badge/license-LGPLv3%2B-lightgrey.svg)
+![Python version](https://img.shields.io/badge/python-3.x-blue.svg)
+
+## Description
+
PwnGIT is a semi-automated, feedback-driven tool to empower users to rapidly search through troves of public data on GitHub for sensitive secrets.
+
+
+
+
+
+### How it Works
+
+During search sessions, users will provide feedback to PwnGIT about search results to ignore, and PwnGIT prunes the set of results. Users can blacklist files by filename, repository name, username, or a fuzzy match of the file contents.
+
+Blacklists generated from previous sessions can be saved and reused against similar queries (e.g.,
+`example.com` v.s. `subdomain.example.com` v.s. `Example Org`). Sessions can also be paused and resumed at any time.
+
+## Install Instructions
+
+### Manual Instructions
+
+[1] Install the `ssdeep` dependency for fuzzy hashing.
+
+Ubuntu/Debian (or equivalent for your distro):
+```sh
+apt-get install libfuzzy-dev ssdeep
+```
+
+or, for Mac OSX:
+```sh
+brew install ssdeep
+```
+For Windows or *nix distributions without the `ssdeep` package, please see the [ssdeep installation instructions](https://ssdeep-project.github.io/ssdeep/index.html).
+
+[2] After installing `ssdeep`, install the Python dependencies using `pip`:
+```
+pip3 install -r requirements.txt
+```
+
+### Docker Instructions
+
+Run `pwngit-docker.sh` to build the PwnGIT docker image (if it doesn't already exist) and execute the dockerized version of the PwnGIT tool.
+
+On invocation, `pwngit-docker.sh` will create and mount `logs` and `states` directories from the host's current working directory. If this `pwngit-docker.sh` is executed from the PwnGIT project directory it will update the docker container with changes to `pwngit.py` or `checks/`:
+
+```sh
+./pwngit-docker.sh -q example.com
+```
+
+(See `pwngit-docker.sh` for specific docker commands)
+## Usage
+
+GitHub requires a token for rate-limiting purposes. Create a [GitHub API token](https://github.com/settings/tokens) with **no permissions/no scope**. This will be equivalent to public GitHub access, but it will allow access to use the GitHub Search API. Set this token at the top of `pwngit.py` as shown below:
+```sh
+ACCESS_TOKEN = ""
+```
+
+(Alternatively, this token can be set as the `GITHUB_ACCESS_TOKEN` environment variable)
+
+After adding the token, you are ready to go:
+```sh
+# Default RegEx list and logfile location (/logs/.log) are used when no others are specified.
+
+# Query for the string "example.com" using default GitHub search behavior (i.e., tokenization).
+# This will find com.example (e.g., Java) or example.com (Website)
+./pwngit.py -q example.com
+
+# Query self-hosted GitHub instance
+./pwngit.py -q example.com -u https://git.example.com
+
+# Query for the exact string "example.com". See Query Syntax in the next section for more details.
+./pwngit.py -q '"example.com"'
+
+# Query through GitHub gists
+./pwngit.py --gist -q CompanyName
+
+# Using GitHub advanced search syntax
+./pwngit.py -q "org:github cats"
+
+# Custom RegEx List and custom log files location
+./pwngit.py -q example.com -f checks/default.list -o example1.log
+
+# Recovery from existing session
+./pwngit.py -q example.com -r example.com.state
+
+# Using an existing session (w/blacklists) for a new query
+./pwngit.py -q "Example Org" -r example.com.state
+```
+### Query Syntax
+
+PwnGIT queries are fed directly into the GitHub code search API, so check out [GitHub's documentation](https://help.github.com/en/articles/searching-code) for more advanced query syntax.
+
+### UI Commands
+* **Ignore similar [c]ontent:** Blacklists a fuzzy hash of the file contents to ignore
+future results that are similar to the selected file
+* **Ignore [r]epo/[u]ser/[f]ilename:** Ignores future results by blacklisting selected strings
+* **Search [/(mykeyword)]:** Provides a custom regex expression with a capture group to searches on-the-fly (e.g., `/(secretToken)`)
+* **[a]dd to Log:** Add RegEx matches to log file, including all on-the-fly search results from search command
+* **Next[\], [b]ack:** Advances through search results, or returns to previous results
+* **[s]ave state:** Saves the blacklists and progress in the search results from the session
+* **[q]uit:** Quit
diff --git a/checks/default.list b/checks/default.list
new file mode 100644
index 0000000..7cd9259
--- /dev/null
+++ b/checks/default.list
@@ -0,0 +1,114 @@
+# RFC 1918 Checks (Approximation)
+(127\.([0-9]{1,3}\.){2}[0-9]{1,3}|10\.([0-9]{1,3}\.){2}[0-9]{1,3}|172\.[123][0-9]\.[0-9]{1,3}\.[0-9]{1,3}|192\.168\.[0-9]{1,3}\.[0-9]{1,3})
+
+# Keywords
+(?i)(secret)
+(?i)(key)
+(?i)(token)
+(?i)(password)
+(?i)(jdbc)
+
+
+# Private Keys
+(?s)(-----BEGIN (RSA|DSA|PGP|EC|) PRIVATE KEY.*END (RSA|DSA|PGP|EC|) PRIVATE KEY( BLOCK)?-----)
+
+### From Truffle Hog Regex lists: https://github.com/dxa4481/truffleHogRegexes/
+
+# Slack Token
+(xox[p|b|o|a]-[0-9]{12}-[0-9]{12}-[0-9]{12}-[a-z0-9]{32})
+
+# Amazon AWS Access Key ID
+(AKIA[0-9A-Z]{16})
+
+# Amazon MWS Auth Token
+(amzn\\.mws\\.[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})
+
+# Facebook Access Token
+(EAACEdEose0cBA[0-9A-Za-z]+)
+
+# Facebook OAuth
+([f|F][a|A][c|C][e|E][b|B][o|O][o|O][k|K].*['|"][0-9a-f]{32}['|"])
+
+# GitHub
+([g|G][i|I][t|T][h|H][u|U][b|B].*['|"][0-9a-zA-Z]{35,40}['|"])
+
+# Generic API Key
+([a|A][p|P][i|I][_]?[k|K][e|E][y|Y].*['|"][0-9a-zA-Z]{32,45}['|"])
+
+# Generic Secret
+([s|S][e|E][c|C][r|R][e|E][t|T].*['|"][0-9a-zA-Z]{32,45}['|"])
+
+# Google API Key
+(AIza[0-9A-Za-z\\-_]{35})
+
+#Google Cloud Platform API Key
+(AIza[0-9A-Za-z\\-_]{35})
+
+# Google Cloud Platform OAuth
+([0-9]+-[0-9A-Za-z_]{32}\\.apps\\.googleusercontent\\.com)
+
+# Google Drive API Key
+(AIza[0-9A-Za-z\\-_]{35})
+
+# Google Drive OAuth
+([0-9]+-[0-9A-Za-z_]{32}\\.apps\\.googleusercontent\\.com)
+
+# Google (GCP) Service-account
+("type": "service_account".*)
+
+# Google Gmail API Key
+(AIza[0-9A-Za-z\\-_]{35})
+
+# Google Gmail OAuth
+([0-9]+-[0-9A-Za-z_]{32}\\.apps\\.googleusercontent\\.com)
+
+# Google OAuth Access Token
+(ya29\\.[0-9A-Za-z\\-_]+)
+
+# Google YouTube API Key
+(AIza[0-9A-Za-z\\-_]{35})
+
+# Google YouTube OAuth
+([0-9]+-[0-9A-Za-z_]{32}\\.apps\\.googleusercontent\\.com)
+
+# Heroku API Key
+([h|H][e|E][r|R][o|O][k|K][u|U].*[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12})
+
+# MailChimp API Key
+([0-9a-f]{32}-us[0-9]{1,2})
+
+# Mailgun API Key
+(key-[0-9a-zA-Z]{32})
+
+# Password in URL
+([a-zA-Z]{3,10}://[^/\\s:@]{3,20}:[^/\\s:@]{3,20}@.{1,100}["'\\s])
+
+# PayPal Braintree Access Token
+(access_token\\$production\\$[0-9a-z]{16}\\$[0-9a-f]{32})
+
+# Picatic API Key
+(sk_live_[0-9a-z]{32})
+
+# Slack Webhook
+(https://hooks.slack.com/services/T[a-zA-Z0-9_]{8}/B[a-zA-Z0-9_]{8}/[a-zA-Z0-9_]{24})
+
+# Stripe API Key
+(sk_live_[0-9a-zA-Z]{24})
+
+# Stripe Restricted API Key
+(rk_live_[0-9a-zA-Z]{24})
+
+# Square Access Token
+(sq0atp-[0-9A-Za-z\\-_]{22})
+
+# Square OAuth Secret
+(sq0csp-[0-9A-Za-z\\-_]{43})
+
+# Twilio API Key
+(SK[0-9a-fA-F]{32})
+
+# Twitter Access Token
+([t|T][w|W][i|I][t|T][t|T][e|E][r|R].*[1-9][0-9]+-[0-9a-zA-Z]{40})
+
+# Twitter OAuth
+([t|T][w|W][i|I][t|T][t|T][e|E][r|R].*['|"][0-9a-zA-Z]{35,44}['|"])
diff --git a/example_usage.png b/example_usage.png
new file mode 100644
index 0000000..f3722be
Binary files /dev/null and b/example_usage.png differ
diff --git a/logo.png b/logo.png
new file mode 100644
index 0000000..a82fe14
Binary files /dev/null and b/logo.png differ
diff --git a/pwngit-docker.sh b/pwngit-docker.sh
new file mode 100644
index 0000000..0e2bfbd
--- /dev/null
+++ b/pwngit-docker.sh
@@ -0,0 +1,23 @@
+#!/bin/bash
+
+if [[ -f "Dockerfile" && -f "pwngit.py" ]]; then
+ if [ -z $(docker images -q pwngit) ]; then
+ # Display output on fresh container build
+ docker build -t pwngit .
+ else
+ # Silent rebuild if in project directory
+ docker build -t pwngit . 2>&1 > /dev/null
+ fi
+else
+ echo "Not in project directory. Skipping container update/rebuild..."
+fi
+
+if [[ ! -d "logs" || ! -d "states" ]]; then
+ mkdir logs states
+fi
+
+docker run --rm -it \
+ -e GITHUB_ACCESS_TOKEN=$GITHUB_ACCESS_TOKEN \
+ -v $PWD/logs:/pwngit/logs \
+ -v $PWD/states:/pwngit/states \
+ pwngit "$@"
diff --git a/pwngit.py b/pwngit.py
new file mode 100644
index 0000000..4b31df1
--- /dev/null
+++ b/pwngit.py
@@ -0,0 +1,519 @@
+#!/usr/bin/env python3
+
+import argparse
+import bs4
+import github
+import json
+import re
+import requests
+import sys
+import ssdeep
+import sre_constants
+import os
+import os.path
+import urllib.parse
+
+
+SIMILARITY_THRESHOLD = 65
+ACCESS_TOKEN = "a669551e651f0ae69688a446a29acd9f756f9583"
+GITHUB_WHITESPACE = "\\.|,|:|;|/|\\\\|`|'|\"|=|\\*|!|\\?" \
+ "|\\#|\\$|\\&|\\+|\\^|\\||\\~|<|>|\\(" \
+ "|\\)|\\{|\\}|\\[|\\]| "
+
+
+class bcolors:
+ """ Thank you Blender scripts :) """
+ HEADER = '\033[95m'
+ OKBLUE = '\033[94m'
+ OKGREEN = '\033[92m'
+ WARNING = '\033[93m'
+ FAIL = '\033[91m'
+ ENDC = '\033[0m'
+ BOLD = '\033[1m'
+ UNDERLINE = '\033[4m'
+ CLEAR = '\x1b[2J'
+
+
+class State:
+
+ def __init__(self,
+ bad_users=[],
+ bad_repos=[],
+ bad_files=[],
+ bad_signatures=[],
+ checks=[],
+ lastInitIndex=0,
+ index=0,
+ totalCount=0,
+ query=None,
+ logfile="",
+ is_gist=False,
+ ):
+ self.bad_users = bad_users
+ self.bad_repos = bad_repos
+ self.bad_files = bad_files
+ self.bad_signatures = bad_signatures
+ self.checks = checks
+ self.lastInitIndex = lastInitIndex
+ self.index = index
+ self.totalCount = totalCount
+ self.query = query
+ self.logfile = logfile
+ self.is_gist = is_gist
+
+
+def save_state(name, state):
+ filename = state.logfile.replace("log", "state")
+ if name == "ratelimited":
+ filename += ".ratelimited"
+ with open(filename, "w") as fd:
+ json.dump(state.__dict__, fd)
+ print("Saved as [{}]".format(filename))
+
+
+def regex_search(checks, repo):
+ output = ""
+ for line in repo.decoded_content.splitlines():
+ for check in checks:
+ try:
+ line = line.decode('utf-8')
+ except AttributeError:
+ pass
+
+ try:
+ (line, inst) = re.subn(
+ check,
+ bcolors.BOLD + bcolors.OKBLUE + r'\1' + bcolors.ENDC,
+ line)
+ if inst > 0:
+ output += "\t" + line + "\n"
+ print("\t", line)
+ break
+ except Exception as e:
+ print(
+ bcolors.FAIL + "ERROR: ", e, bcolors.ENDC,
+ bcolors.WARNING, "\nCHECK: ", check, bcolors.ENDC,
+ "\nLINE: ", line)
+ print(bcolors.HEADER + "End of Matches" + bcolors.ENDC)
+ return output
+
+
+def should_parse(repo, state, is_gist=False):
+ owner_login = repo.owner.login if is_gist else repo.repository.owner.login
+ if owner_login in state.bad_users:
+ print(bcolors.FAIL + "Failed check: Ignore User" + bcolors.ENDC)
+ return False
+ if not is_gist and repo.repository.name in state.bad_repos:
+ print(bcolors.FAIL + "Failed check: Ignore Repo" + bcolors.ENDC)
+ return False
+ if not is_gist and repo.name in state.bad_files:
+ print(bcolors.FAIL + "Failed check: Ignore File" + bcolors.ENDC)
+ return False
+
+ # Fuzzy Hash Comparison
+ try:
+ if not is_gist:
+ # Temporary fix for PyGithub until fixed upstream (PyGithub#1178)
+ repo._url.value = repo._url.value.replace(
+ repo._path.value,
+ urllib.parse.quote(repo._path.value))
+
+ candidate_sig = ssdeep.hash(repo.decoded_content)
+ for sig in state.bad_signatures:
+ similarity = ssdeep.compare(candidate_sig, sig)
+ if similarity > SIMILARITY_THRESHOLD:
+ print(
+ bcolors.FAIL +
+ "Failed check: Ignore Fuzzy Signature on Contents "
+ "({}% Similarity)".format(similarity) +
+ bcolors.ENDC)
+ return False
+ except github.UnknownObjectException:
+ print(
+ bcolors.FAIL +
+ "API Error: File no longer exists on github.com" +
+ bcolors.ENDC)
+ return False
+ return True
+
+
+def print_handler(contents):
+ try:
+ contents = contents.decode('utf-8')
+ except AttributeError:
+ pass
+ finally:
+ print(contents)
+
+ print(contents)
+
+
+def input_handler(state, is_gist):
+ prompt = bcolors.HEADER + \
+ "(Result {}/{})".format(
+ state.index +
+ 1,
+ state.totalCount if state.totalCount < 1000 else "1000+") + \
+ "=== " + bcolors.ENDC + \
+ "Ignore similar [c]ontents" + \
+ bcolors.OKGREEN + "/[u]ser"
+ prompt += "" if is_gist else \
+ bcolors.OKBLUE + "/[r]epo" + \
+ bcolors.WARNING + "/[f]ilename"
+ prompt += bcolors.HEADER + \
+ ", [p]rint contents, [s]ave state, [a]dd to log, " + \
+ "search [/(findme)], [b]ack, [q]uit, next []===: " + \
+ bcolors.ENDC
+ return input(prompt)
+
+
+def pagination_hack(repositories, state):
+ count = len(repositories.__dict__["_PaginatedListBase__elements"])
+ if state.index >= count:
+ n_elements = repositories.get_page(state.index//30)
+ repositories.__dict__["_PaginatedListBase__elements"] += n_elements
+ return repositories
+
+
+def regex_handler(choice, repo):
+ if choice[1] != "(" or choice[-1] != ")":
+ print(
+ bcolors.FAIL +
+ "Regex requires at least one group reference: "
+ "e.g., (CaSeSensitive) or ((?i)insensitive)" +
+ bcolors.ENDC)
+ return ""
+ else:
+ print(bcolors.HEADER + "Searching: " + choice[1:] + bcolors.ENDC)
+ return regex_search([choice[1:]], repo)
+
+
+def ui_loop(repo, log_buf, state, is_gist=False):
+ choice = input_handler(state, is_gist)
+
+ if choice == "c":
+ state.bad_signatures.append(ssdeep.hash(repo.decoded_content))
+ elif choice == "u":
+ state.bad_users.append(repo.owner.login if is_gist
+ else repo.repository.owner.login)
+ elif choice == "r" and not is_gist:
+ state.bad_repos.append(repo.repository.name)
+ elif choice == "f" and not is_gist:
+ state.bad_files.append(repo.name)
+ elif choice == "p":
+ print_handler(repo.decoded_content)
+ ui_loop(repo, log_buf, state, is_gist)
+ elif choice == "s":
+ save_state(state.query, state)
+ ui_loop(repo, log_buf, state, is_gist)
+ elif choice == "a":
+ with open(state.logfile, "a") as fd:
+ fd.write(log_buf)
+ elif choice.startswith("/"):
+ log_buf += regex_handler(choice, repo)
+ ui_loop(repo, log_buf, state, is_gist)
+ elif choice == "b":
+ if state.index - 1 < state.lastInitIndex:
+ print(
+ bcolors.FAIL +
+ "Can't go backwards past restore point "
+ "because of rate-limiting/API limitations" +
+ bcolors.ENDC)
+ ui_loop(repo, log_buf, state, is_gist)
+ else:
+ state.index -= 2
+ elif choice == "q":
+ sys.exit(0)
+
+
+def gist_fetch(query, page_idx, total_items=1000):
+ gist_url = "https://gist.github.com/search?utf8=%E2%9C%93&q={}&p={}"
+ query = urllib.parse.quote(query)
+ gists = []
+
+ try:
+ resp = requests.get(gist_url.format(query, page_idx))
+ soup = bs4.BeautifulSoup(resp.text, 'html.parser')
+ total_items = min(total_items, int(
+ [x.text.split()[0] for x in soup.find_all('h3')
+ if "gist results" in x.text][0].replace(',', '')))
+ gists = [x.get("href") for x in soup.findAll(
+ "a", class_="link-overlay")]
+ except IndexError:
+ return {"data": None, "total_items": 0}
+
+ return {"data": gists, "total_items": total_items}
+
+
+def gist_search(g, state):
+ gists = []
+ if state.index > 0:
+ gists = [None] * (state.index//10) * 10
+ else:
+ gist_data = gist_fetch(state.query, 0)
+ gists = gist_data["data"]
+ state.totalCount = gist_data["total_items"]
+
+ if state.totalCount == 0:
+ print("No results found for query: {}".format(state.query))
+ else:
+ print(bcolors.CLEAR)
+
+ i = state.index
+ stepBack = False
+ while i < state.totalCount:
+ while True:
+ state.index = i
+
+ # Manual gist paginator
+ if i >= len(gists):
+ new_gists = gist_fetch(state.query, i // 10)["data"]
+ if not new_gists:
+ try:
+ print(
+ bcolors.FAIL +
+ "RateLimitException: "
+ "Please wait about 30 seconds before you "
+ "try again, or exit (CTRL-C).\n " +
+ bcolors.ENDC)
+ save_state("ratelimited", state)
+ input("Press enter to try again...")
+ continue
+ except KeyboardInterrupt:
+ sys.exit(1)
+ gists.extend(new_gists)
+
+ gist = g.get_gist(gists[i].split("/")[-1])
+ gist.decoded_content = "\n".join(
+ [gist_file.content for _, gist_file in gist.files.items()])
+
+ log_buf = "https://gist.github.com/" + \
+ bcolors.OKGREEN + gist.owner.login + "/" + \
+ bcolors.ENDC + \
+ gist.id
+ print(log_buf)
+ log_buf = "\n" + log_buf + "\n"
+
+ if should_parse(gist, state, is_gist=True) or stepBack:
+ stepBack = False
+ log_buf += regex_search(state.checks, gist)
+ ui_loop(gist, log_buf, state, is_gist=True)
+ if state.index < i:
+ i = state.index
+ stepBack = True
+ print(bcolors.CLEAR)
+ else:
+ print("Skipping...")
+ i += 1
+ break
+
+
+def github_search(g, state):
+ print("Collecting Github Search API data...")
+ try:
+ repositories = g.search_code(state.query)
+
+ state.totalCount = repositories.totalCount
+
+ # Hack to backfill PaginatedList with garbage to avoid ratelimiting on
+ # restore, library fetches in 30 counts
+ repositories.__dict__["_PaginatedListBase__elements"] = [
+ None] * (state.index//30) * 30
+ state.lastInitIndex = state.index
+
+ print(bcolors.CLEAR)
+
+ i = state.index
+ stepBack = False
+ while i < state.totalCount:
+ while True:
+ try:
+ state.index = i
+
+ # Manually fill Paginator to avoid ratelimiting on restore
+ repositories = pagination_hack(repositories, state)
+
+ repo = repositories[i]
+
+
+ # Setting domain/scheme name for log output
+ scheme = g._Github__requester._Requester__scheme
+ domain = g._Github__requester._Requester__hostname
+
+ if(domain == "api.github.com"):
+ domain = "github.com"
+
+ log_buf = scheme + "://" + \
+ domain + "/" + \
+ bcolors.OKGREEN + repo.repository.owner.login + "/" + \
+ bcolors.OKBLUE + repo.repository.name + "/blob" + \
+ bcolors.ENDC + \
+ os.path.dirname(repo.html_url.split('blob')[1]) + \
+ "/" + bcolors.WARNING + repo.name + bcolors.ENDC
+ print(log_buf)
+ log_buf = "\n" + log_buf + "\n"
+
+ if should_parse(repo, state) or stepBack:
+ stepBack = False
+ log_buf += regex_search(state.checks, repo)
+ ui_loop(repo, log_buf, state)
+ if state.index < i:
+ i = state.index
+ stepBack = True
+ print(bcolors.CLEAR)
+ else:
+ print("Skipping...")
+ i += 1
+ break
+ except github.RateLimitExceededException:
+ try:
+ print(
+ bcolors.FAIL +
+ "RateLimitException: "
+ "Please wait about 30 seconds before you "
+ "try again, or exit (CTRL-C).\n " +
+ bcolors.ENDC)
+ save_state("ratelimited", state)
+ input("Press enter to try again...")
+ except KeyboardInterrupt:
+ sys.exit(1)
+ except github.RateLimitExceededException:
+ print(
+ bcolors.FAIL +
+ "RateLimitException: "
+ "Please wait about 30 seconds before you try again.\n" +
+ bcolors.ENDC)
+ save_state("ratelimited", state)
+ sys.exit(-1)
+
+
+def regex_validator(args, state):
+ with open(args.checks, "r") as fd:
+ for line in fd.read().splitlines():
+ if line.startswith("#") or len(line) == 0:
+ continue
+ try:
+ re.subn(line, r'\1', "Expression test")
+ except sre_constants.error as e:
+ print(bcolors.FAIL + "Invalid Regular expression:\n\t" + line)
+ if "group" in str(e):
+ print(
+ "Ensure expression contains"
+ "a capture group for matches:\n\t" + str(e))
+ sys.exit(-1)
+ state.checks.append(line)
+
+ split = []
+ if not (state.query[0] == "\"" and state.query[-1] == "\""):
+ split = re.split(GITHUB_WHITESPACE, state.query)
+
+ for part in [state.query] + split:
+ if part:
+ escaped_query = re.escape(part) if split else \
+ part.replace("\"", "")
+ state.checks.append("(?i)(" + escaped_query + ")")
+ return state
+
+
+def main():
+ global ACCESS_TOKEN
+
+ if sys.version_info < (3, 0):
+ sys.stdout.write("Sorry, requires Python 3.x, not Python 2.x\n")
+ sys.exit(1)
+
+ parser = argparse.ArgumentParser(
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ description="./" + sys.argv[0] + " -q example.com\n" +
+ "./" + sys.argv[0] + " -q example.com -f checks/default.list "
+ "-o example1.log\n" +
+ "./" + sys.argv[0] + " -q example.com -r example.com.state")
+ parser.add_argument(
+ "-q",
+ "--query",
+ help="Github Code Query",
+ type=str,
+ required=True)
+ parser.add_argument(
+ "--gist",
+ help="Search GitHub Gists instead",
+ action='store_true',
+ required=False)
+ parser.add_argument(
+ "-f",
+ "--checks",
+ help="List of RegEx checks (checks/default.list)",
+ type=str,
+ default=os.path.dirname(os.path.realpath(__file__)) + "/checks/default.list")
+ parser.add_argument(
+ "-o",
+ "--output",
+ help="Log name (default: .log)",
+ type=str)
+ parser.add_argument(
+ "-r",
+ "--recover",
+ help="Name of recovery file",
+ type=str)
+ parser.add_argument(
+ "-u",
+ "--url",
+ help="URL of self-hosted GitHub instance (e.g., https://git.example.com)",
+ type=str)
+ args = parser.parse_args()
+
+ state = State()
+ state.index = 0
+
+ if ACCESS_TOKEN == "":
+ ACCESS_TOKEN = os.environ.get("GITHUB_ACCESS_TOKEN", "")
+
+ if not ACCESS_TOKEN:
+ print("Github Access token not set")
+ sys.exit(1)
+
+ if args.recover:
+ with open(args.recover, 'r') as fd:
+ state = State(**json.load(fd))
+
+ args.query = args.query.lstrip()
+
+ # Reusing Blacklists on new query
+ if state.query != args.query:
+ state.query = args.query
+ state.index = 0
+
+ state.is_gist = state.is_gist or (args.gist and not state.is_gist)
+
+ if args.output:
+ state.logfile = args.output
+ else:
+ state.logfile = "logs/" + \
+ re.sub(r"[,.;@#?!&$/\\'\"]+\ *", "_", args.query)
+ state.logfile += "_gist.log" if state.is_gist else ".log"
+
+ # Create default directories if they don't exist
+ try:
+ os.mkdir("logs")
+ os.mkdir("states")
+ except FileExistsError:
+ pass
+
+ # Load/Validate RegEx Checks
+ state = regex_validator(args, state)
+
+ if args.url:
+ g = github.Github(base_url=args.url + "/api/v3",
+ login_or_token=ACCESS_TOKEN)
+ else:
+ g = github.Github(ACCESS_TOKEN)
+
+
+ if state.is_gist:
+ gist_search(g, state)
+ else:
+ github_search(g, state)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/requirements.txt b/requirements.txt
new file mode 100644
index 0000000..371e581
--- /dev/null
+++ b/requirements.txt
@@ -0,0 +1,3 @@
+beautifulsoup4
+PyGithub
+ssdeep