├── Dockerfile
├── LICENSE
├── README.md
├── checks
└── default.list
├── example_usage.png
├── gitgot-docker.sh
├── gitgot.py
├── logo.png
└── requirements.txt
/Dockerfile:
--------------------------------------------------------------------------------
1 | # Build and run with docker_run.sh
2 | # e.g., ./docker_run.sh -q example.com
3 | #
4 | # Thank you to Ilya Glotov (https://github.com/ilyaglow) for help with
5 | # this minimal alpine image
6 |
7 | FROM python:3-alpine
8 |
9 | ENV SSDEEP_VERSION="release-2.14.1" \
10 | BUILD_DEPS="build-base \
11 | automake \
12 | autoconf \
13 | libtool"
14 |
15 | ADD requirements.txt .
16 | RUN apk --update --no-cache add $BUILD_DEPS \
17 | git \
18 | libffi-dev \
19 | && git clone --depth=1 --branch=$SSDEEP_VERSION https://github.com/ssdeep-project/ssdeep.git \
20 | && cd ssdeep \
21 | && autoreconf -i \
22 | && ./configure \
23 | && make \
24 | && make install \
25 | && cd / \
26 | && rm -rf /ssdeep \
27 | \
28 | && pip3 install -r requirements.txt \
29 | \
30 | && apk del $BUILD_DEPS \
31 | \
32 | && adduser -D gitgot
33 |
34 | VOLUME ["/gitgot/logs", "/gitgot/states"]
35 |
36 | WORKDIR /gitgot
37 | USER gitgot
38 |
39 | ADD checks /gitgot/checks
40 | ADD gitgot.py .
41 | ENTRYPOINT ["python3", "gitgot.py"]
42 | CMD [ "-h" ]
43 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU LESSER 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 |
9 | This version of the GNU Lesser General Public License incorporates
10 | the terms and conditions of version 3 of the GNU General Public
11 | License, supplemented by the additional permissions listed below.
12 |
13 | 0. Additional Definitions.
14 |
15 | As used herein, "this License" refers to version 3 of the GNU Lesser
16 | General Public License, and the "GNU GPL" refers to version 3 of the GNU
17 | General Public License.
18 |
19 | "The Library" refers to a covered work governed by this License,
20 | other than an Application or a Combined Work as defined below.
21 |
22 | An "Application" is any work that makes use of an interface provided
23 | by the Library, but which is not otherwise based on the Library.
24 | Defining a subclass of a class defined by the Library is deemed a mode
25 | of using an interface provided by the Library.
26 |
27 | A "Combined Work" is a work produced by combining or linking an
28 | Application with the Library. The particular version of the Library
29 | with which the Combined Work was made is also called the "Linked
30 | Version".
31 |
32 | The "Minimal Corresponding Source" for a Combined Work means the
33 | Corresponding Source for the Combined Work, excluding any source code
34 | for portions of the Combined Work that, considered in isolation, are
35 | based on the Application, and not on the Linked Version.
36 |
37 | The "Corresponding Application Code" for a Combined Work means the
38 | object code and/or source code for the Application, including any data
39 | and utility programs needed for reproducing the Combined Work from the
40 | Application, but excluding the System Libraries of the Combined Work.
41 |
42 | 1. Exception to Section 3 of the GNU GPL.
43 |
44 | You may convey a covered work under sections 3 and 4 of this License
45 | without being bound by section 3 of the GNU GPL.
46 |
47 | 2. Conveying Modified Versions.
48 |
49 | If you modify a copy of the Library, and, in your modifications, a
50 | facility refers to a function or data to be supplied by an Application
51 | that uses the facility (other than as an argument passed when the
52 | facility is invoked), then you may convey a copy of the modified
53 | version:
54 |
55 | a) under this License, provided that you make a good faith effort to
56 | ensure that, in the event an Application does not supply the
57 | function or data, the facility still operates, and performs
58 | whatever part of its purpose remains meaningful, or
59 |
60 | b) under the GNU GPL, with none of the additional permissions of
61 | this License applicable to that copy.
62 |
63 | 3. Object Code Incorporating Material from Library Header Files.
64 |
65 | The object code form of an Application may incorporate material from
66 | a header file that is part of the Library. You may convey such object
67 | code under terms of your choice, provided that, if the incorporated
68 | material is not limited to numerical parameters, data structure
69 | layouts and accessors, or small macros, inline functions and templates
70 | (ten or fewer lines in length), you do both of the following:
71 |
72 | a) Give prominent notice with each copy of the object code that the
73 | Library is used in it and that the Library and its use are
74 | covered by this License.
75 |
76 | b) Accompany the object code with a copy of the GNU GPL and this license
77 | document.
78 |
79 | 4. Combined Works.
80 |
81 | You may convey a Combined Work under terms of your choice that,
82 | taken together, effectively do not restrict modification of the
83 | portions of the Library contained in the Combined Work and reverse
84 | engineering for debugging such modifications, if you also do each of
85 | the following:
86 |
87 | a) Give prominent notice with each copy of the Combined Work that
88 | the Library is used in it and that the Library and its use are
89 | covered by this License.
90 |
91 | b) Accompany the Combined Work with a copy of the GNU GPL and this license
92 | document.
93 |
94 | c) For a Combined Work that displays copyright notices during
95 | execution, include the copyright notice for the Library among
96 | these notices, as well as a reference directing the user to the
97 | copies of the GNU GPL and this license document.
98 |
99 | d) Do one of the following:
100 |
101 | 0) Convey the Minimal Corresponding Source under the terms of this
102 | License, and the Corresponding Application Code in a form
103 | suitable for, and under terms that permit, the user to
104 | recombine or relink the Application with a modified version of
105 | the Linked Version to produce a modified Combined Work, in the
106 | manner specified by section 6 of the GNU GPL for conveying
107 | Corresponding Source.
108 |
109 | 1) Use a suitable shared library mechanism for linking with the
110 | Library. A suitable mechanism is one that (a) uses at run time
111 | a copy of the Library already present on the user's computer
112 | system, and (b) will operate properly with a modified version
113 | of the Library that is interface-compatible with the Linked
114 | Version.
115 |
116 | e) Provide Installation Information, but only if you would otherwise
117 | be required to provide such information under section 6 of the
118 | GNU GPL, and only to the extent that such information is
119 | necessary to install and execute a modified version of the
120 | Combined Work produced by recombining or relinking the
121 | Application with a modified version of the Linked Version. (If
122 | you use option 4d0, the Installation Information must accompany
123 | the Minimal Corresponding Source and Corresponding Application
124 | Code. If you use option 4d1, you must provide the Installation
125 | Information in the manner specified by section 6 of the GNU GPL
126 | for conveying Corresponding Source.)
127 |
128 | 5. Combined Libraries.
129 |
130 | You may place library facilities that are a work based on the
131 | Library side by side in a single library together with other library
132 | facilities that are not Applications and are not covered by this
133 | License, and convey such a combined library under terms of your
134 | choice, if you do both of the following:
135 |
136 | a) Accompany the combined library with a copy of the same work based
137 | on the Library, uncombined with any other library facilities,
138 | conveyed under the terms of this License.
139 |
140 | b) Give prominent notice with the combined library that part of it
141 | is a work based on the Library, and explaining where to find the
142 | accompanying uncombined form of the same work.
143 |
144 | 6. Revised Versions of the GNU Lesser General Public License.
145 |
146 | The Free Software Foundation may publish revised and/or new versions
147 | of the GNU Lesser General Public License from time to time. Such new
148 | versions will be similar in spirit to the present version, but may
149 | differ in detail to address new problems or concerns.
150 |
151 | Each version is given a distinguishing version number. If the
152 | Library as you received it specifies that a certain numbered version
153 | of the GNU Lesser General Public License "or any later version"
154 | applies to it, you have the option of following the terms and
155 | conditions either of that published version or of any later version
156 | published by the Free Software Foundation. If the Library as you
157 | received it does not specify a version number of the GNU Lesser
158 | General Public License, you may choose any version of the GNU Lesser
159 | General Public License ever published by the Free Software Foundation.
160 |
161 | If the Library as you received it specifies that a proxy can decide
162 | whether future versions of the GNU Lesser General Public License shall
163 | apply, that proxy's public statement of acceptance of any version is
164 | permanent authorization for you to choose that version for the
165 | Library.
166 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | #
6 |
7 |
8 | 
9 | 
10 |
11 | ## Description
12 |
13 | GitGot is a semi-automated, feedback-driven tool to empower users to rapidly search through troves of public data on GitHub for sensitive secrets.
14 |
15 |
16 |
17 |
18 |
19 | ### How it Works
20 |
21 | During search sessions, users will provide feedback to GitGot about search results to ignore, and GitGot prunes the set of results. Users can blacklist files by filename, repository name, username, or a fuzzy match of the file contents.
22 |
23 | Blacklists generated from previous sessions can be saved and reused against similar queries (e.g.,
24 | `example.com` v.s. `subdomain.example.com` v.s. `Example Org`). Sessions can also be paused and resumed at any time.
25 |
26 | Read more about the semi-automated, human-in-the-loop design here: https://bishopfox.com/blog/semi-automated-vs-automated-security-tools.
27 |
28 | ## Install Instructions
29 |
30 | ### Manual Instructions
31 |
32 | [1] Install the `ssdeep` dependency for fuzzy hashing.
33 |
34 | Ubuntu/Debian (or equivalent for your distro):
35 | ```sh
36 | apt-get install python3-dev libfuzzy-dev ssdeep
37 | ```
38 |
39 | or, for Mac OSX:
40 | ```sh
41 | brew install ssdeep
42 | ```
43 | For Windows or *nix distributions without the `ssdeep` package, please see the [ssdeep installation instructions](https://ssdeep-project.github.io/ssdeep/index.html).
44 |
45 | [2] After installing `ssdeep`, install the Python dependencies using `pip`:
46 | ```
47 | pip3 install -r requirements.txt
48 | ```
49 |
50 | ### Docker Instructions
51 |
52 | Run `gitgot-docker.sh` to build the GitGot docker image (if it doesn't already exist) and execute the dockerized version of the GitGot tool.
53 |
54 | On invocation, `gitgot-docker.sh` will create and mount `logs` and `states` directories from the host's current working directory. If this `gitgot-docker.sh` is executed from the GitGot project directory it will update the docker container with changes to `gitgot.py` or `checks/`:
55 |
56 | ```sh
57 | ./gitgot-docker.sh -q example.com
58 | ```
59 |
60 | (See `gitgot-docker.sh` for specific docker commands)
61 | ## Usage
62 |
63 | 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 `gitgot.py` as shown below:
64 | ```sh
65 | ACCESS_TOKEN = ""
66 | ```
67 |
68 | (Alternatively, this token can be set as the `GITHUB_ACCESS_TOKEN` environment variable)
69 |
70 | After adding the token, you are ready to go:
71 | ```sh
72 | # Default RegEx list and logfile location (/logs/.log) are used when no others are specified.
73 |
74 | # Query for the string "example.com" using default GitHub search behavior (i.e., tokenization).
75 | # This will find com.example (e.g., Java) or example.com (Website)
76 | ./gitgot.py -q example.com
77 |
78 | # Query self-hosted GitHub instance
79 | ./gitgot.py -q example.com -u https://git.example.com
80 |
81 | # Query for the exact string "example.com". See Query Syntax in the next section for more details.
82 | ./gitgot.py -q '"example.com"'
83 |
84 | # Query through GitHub gists
85 | ./gitgot.py --gist -q CompanyName
86 |
87 | # Using GitHub advanced search syntax
88 | ./gitgot.py -q "org:github cats"
89 |
90 | # Custom RegEx List and custom log files location
91 | ./gitgot.py -q example.com -f checks/default.list -o example1.log
92 |
93 | # Recovery from existing session
94 | ./gitgot.py -q example.com -r example.com.state
95 |
96 | # Using an existing session (w/blacklists) for a new query
97 | ./gitgot.py -q "Example Org" -r example.com.state
98 | ```
99 | ### Query Syntax
100 |
101 | GitGot 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.
102 |
103 | ### UI Commands
104 | * **Ignore similar [c]ontent:** Blacklists a fuzzy hash of the file contents to ignore
105 | future results that are similar to the selected file
106 | * **Ignore [r]epo/[u]ser/[f]ilename:** Ignores future results by blacklisting selected strings
107 | * **Search [/(mykeyword)]:** Provides a custom regex expression with a capture group to searches on-the-fly (e.g., `/(secretToken)`)
108 | * **[a]dd to Log:** Add RegEx matches to log file, including all on-the-fly search results from search command
109 | * **Next[\], [b]ack:** Advances through search results, or returns to previous results
110 | * **[s]ave state:** Saves the blacklists and progress in the search results from the session
111 | * **[q]uit:** Quit
112 |
--------------------------------------------------------------------------------
/checks/default.list:
--------------------------------------------------------------------------------
1 | # RFC 1918 Checks (Approximation)
2 | (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})
3 |
4 | # Keywords
5 | (?i)(secret)
6 | (?i)(key)
7 | (?i)(token)
8 | (?i)(password)
9 | (?i)(jdbc)
10 |
11 |
12 | # Private Keys
13 | (?s)(-----BEGIN (RSA|DSA|PGP|EC|) PRIVATE KEY.*END (RSA|DSA|PGP|EC|) PRIVATE KEY( BLOCK)?-----)
14 |
15 | ### From Truffle Hog Regex lists: https://github.com/dxa4481/truffleHogRegexes/
16 |
17 | # Slack Token
18 | (xox[p|b|o|a]-[0-9]{12}-[0-9]{12}-[0-9]{12}-[a-z0-9]{32})
19 |
20 | # Amazon AWS Access Key ID
21 | (AKIA[0-9A-Z]{16})
22 |
23 | # Amazon MWS Auth Token
24 | (amzn\\.mws\\.[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})
25 |
26 | # Facebook Access Token
27 | (EAACEdEose0cBA[0-9A-Za-z]+)
28 |
29 | # Facebook OAuth
30 | ([f|F][a|A][c|C][e|E][b|B][o|O][o|O][k|K].*['|"][0-9a-f]{32}['|"])
31 |
32 | # GitHub
33 | ([g|G][i|I][t|T][h|H][u|U][b|B].*['|"][0-9a-zA-Z]{35,40}['|"])
34 |
35 | # Generic API Key
36 | ([a|A][p|P][i|I][_]?[k|K][e|E][y|Y].*['|"][0-9a-zA-Z]{32,45}['|"])
37 |
38 | # Generic Secret
39 | ([s|S][e|E][c|C][r|R][e|E][t|T].*['|"][0-9a-zA-Z]{32,45}['|"])
40 |
41 | # Google API Key
42 | (AIza[0-9A-Za-z\\-_]{35})
43 |
44 | #Google Cloud Platform API Key
45 | (AIza[0-9A-Za-z\\-_]{35})
46 |
47 | # Google Cloud Platform OAuth
48 | ([0-9]+-[0-9A-Za-z_]{32}\\.apps\\.googleusercontent\\.com)
49 |
50 | # Google Drive API Key
51 | (AIza[0-9A-Za-z\\-_]{35})
52 |
53 | # Google Drive OAuth
54 | ([0-9]+-[0-9A-Za-z_]{32}\\.apps\\.googleusercontent\\.com)
55 |
56 | # Google (GCP) Service-account
57 | ("type": "service_account".*)
58 |
59 | # Google Gmail API Key
60 | (AIza[0-9A-Za-z\\-_]{35})
61 |
62 | # Google Gmail OAuth
63 | ([0-9]+-[0-9A-Za-z_]{32}\\.apps\\.googleusercontent\\.com)
64 |
65 | # Google OAuth Access Token
66 | (ya29\\.[0-9A-Za-z\\-_]+)
67 |
68 | # Google YouTube API Key
69 | (AIza[0-9A-Za-z\\-_]{35})
70 |
71 | # Google YouTube OAuth
72 | ([0-9]+-[0-9A-Za-z_]{32}\\.apps\\.googleusercontent\\.com)
73 |
74 | # Heroku API Key
75 | ([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})
76 |
77 | # MailChimp API Key
78 | ([0-9a-f]{32}-us[0-9]{1,2})
79 |
80 | # Mailgun API Key
81 | (key-[0-9a-zA-Z]{32})
82 |
83 | # Password in URL
84 | ([a-zA-Z]{3,10}://[^/\\s:@]{3,20}:[^/\\s:@]{3,20}@.{1,100}["'\\s])
85 |
86 | # PayPal Braintree Access Token
87 | (access_token\\$production\\$[0-9a-z]{16}\\$[0-9a-f]{32})
88 |
89 | # Picatic API Key
90 | (sk_live_[0-9a-z]{32})
91 |
92 | # Slack Webhook
93 | (https://hooks.slack.com/services/T[a-zA-Z0-9_]{8}/B[a-zA-Z0-9_]{8}/[a-zA-Z0-9_]{24})
94 |
95 | # Stripe API Key
96 | (sk_live_[0-9a-zA-Z]{24})
97 |
98 | # Stripe Restricted API Key
99 | (rk_live_[0-9a-zA-Z]{24})
100 |
101 | # Square Access Token
102 | (sq0atp-[0-9A-Za-z\\-_]{22})
103 |
104 | # Square OAuth Secret
105 | (sq0csp-[0-9A-Za-z\\-_]{43})
106 |
107 | # Twilio API Key
108 | (SK[0-9a-fA-F]{32})
109 |
110 | # Twitter Access Token
111 | ([t|T][w|W][i|I][t|T][t|T][e|E][r|R].*[1-9][0-9]+-[0-9a-zA-Z]{40})
112 |
113 | # Twitter OAuth
114 | ([t|T][w|W][i|I][t|T][t|T][e|E][r|R].*['|"][0-9a-zA-Z]{35,44}['|"])
115 |
--------------------------------------------------------------------------------
/example_usage.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/BishopFox/GitGot/4ce0d88a36c285a7ceaca84104009a8e3b6f6e99/example_usage.png
--------------------------------------------------------------------------------
/gitgot-docker.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | if [[ -f "Dockerfile" && -f "gitgot.py" ]]; then
4 | if [ -z $(docker images -q gitgot) ]; then
5 | # Display output on fresh container build
6 | docker build -t gitgot .
7 | else
8 | # Silent rebuild if in project directory
9 | docker build -t gitgot . 2>&1 > /dev/null
10 | fi
11 | else
12 | echo "Not in project directory. Skipping container update/rebuild..."
13 | fi
14 |
15 | if [[ ! -d "logs" || ! -d "states" ]]; then
16 | mkdir logs states
17 | fi
18 |
19 | docker run --rm -it \
20 | -e GITHUB_ACCESS_TOKEN=$GITHUB_ACCESS_TOKEN \
21 | -v $PWD/logs:/gitgot/logs \
22 | -v $PWD/states:/gitgot/states \
23 | gitgot "$@"
24 |
--------------------------------------------------------------------------------
/gitgot.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 |
3 | import argparse
4 | import bs4
5 | import github
6 | import json
7 | import re
8 | import requests
9 | import sys
10 | import ssdeep
11 | import sre_constants
12 | import os
13 | import os.path
14 | import urllib.parse
15 |
16 |
17 | SIMILARITY_THRESHOLD = 65
18 | ACCESS_TOKEN = ""
19 | GITHUB_WHITESPACE = "\\.|,|:|;|/|\\\\|`|'|\"|=|\\*|!|\\?" \
20 | "|\\#|\\$|\\&|\\+|\\^|\\||\\~|<|>|\\(" \
21 | "|\\)|\\{|\\}|\\[|\\]| "
22 |
23 |
24 | class bcolors:
25 | """ Thank you Blender scripts :) """
26 | HEADER = '\033[95m'
27 | OKBLUE = '\033[94m'
28 | OKGREEN = '\033[92m'
29 | WARNING = '\033[93m'
30 | FAIL = '\033[91m'
31 | ENDC = '\033[0m'
32 | BOLD = '\033[1m'
33 | UNDERLINE = '\033[4m'
34 | CLEAR = '\x1b[2J'
35 |
36 |
37 | class State:
38 |
39 | def __init__(self,
40 | bad_users=[],
41 | bad_repos=[],
42 | bad_files=[],
43 | bad_signatures=[],
44 | checks=[],
45 | lastInitIndex=0,
46 | index=0,
47 | totalCount=0,
48 | query=None,
49 | logfile="",
50 | is_gist=False,
51 | line_numbers=False,
52 | ):
53 | self.bad_users = bad_users
54 | self.bad_repos = bad_repos
55 | self.bad_files = bad_files
56 | self.bad_signatures = bad_signatures
57 | self.checks = checks
58 | self.lastInitIndex = lastInitIndex
59 | self.index = index
60 | self.totalCount = totalCount
61 | self.query = query
62 | self.logfile = logfile
63 | self.is_gist = is_gist
64 | self.line_numbers = line_numbers
65 |
66 |
67 | def save_state(name, state):
68 | filename = state.logfile.replace("log", "state")
69 | if name == "ratelimited":
70 | filename += ".ratelimited"
71 | with open(filename, "w") as fd:
72 | json.dump(state.__dict__, fd)
73 | print("Saved as [{}]".format(filename))
74 |
75 |
76 | def regex_search(checks, repo, print_lines):
77 | output = ""
78 | lines = repo.decoded_content.splitlines()
79 |
80 | for i in range(len(lines)):
81 | line = lines[i]
82 | try:
83 | line = line.decode('utf-8')
84 | except AttributeError:
85 | pass
86 |
87 | for check in checks:
88 | try:
89 | (line, inst) = re.subn(
90 | check,
91 | bcolors.BOLD + bcolors.OKBLUE + r'\1' + bcolors.ENDC,
92 | line)
93 | if inst > 0:
94 | # Line number printing support
95 | line_str = ""
96 | if print_lines:
97 | line_str = bcolors.WARNING + str(i+1) + \
98 | ":" + bcolors.ENDC
99 |
100 | output += line_str + "\t" + line + "\n"
101 | print(line_str + "\t" + line)
102 |
103 | break
104 | except Exception as e:
105 | print(
106 | bcolors.FAIL + "ERROR: ", e, bcolors.ENDC,
107 | bcolors.WARNING, "\nCHECK: ", check, bcolors.ENDC,
108 | "\nLINE: ", line)
109 | print(bcolors.HEADER + "End of Matches" + bcolors.ENDC)
110 | return output
111 |
112 |
113 | def should_parse(repo, state, is_gist=False):
114 | owner_login = repo.owner.login if is_gist else repo.repository.owner.login
115 | if owner_login in state.bad_users:
116 | print(bcolors.FAIL + "Failed check: Ignore User" + bcolors.ENDC)
117 | return False
118 | if not is_gist and repo.repository.name in state.bad_repos:
119 | print(bcolors.FAIL + "Failed check: Ignore Repo" + bcolors.ENDC)
120 | return False
121 | if not is_gist and repo.name in state.bad_files:
122 | print(bcolors.FAIL + "Failed check: Ignore File" + bcolors.ENDC)
123 | return False
124 |
125 | # Fuzzy Hash Comparison
126 | try:
127 | candidate_sig = ssdeep.hash(repo.decoded_content)
128 | for sig in state.bad_signatures:
129 | similarity = ssdeep.compare(candidate_sig, sig)
130 | if similarity > SIMILARITY_THRESHOLD:
131 | print(
132 | bcolors.FAIL +
133 | "Failed check: Ignore Fuzzy Signature on Contents "
134 | "({}% Similarity)".format(similarity) +
135 | bcolors.ENDC)
136 | return False
137 | except github.GithubException as e:
138 | print(bcolors.FAIL + "API ERROR: {}".format(e) + bcolors.ENDC)
139 | return False
140 | return True
141 |
142 |
143 | def print_handler(contents):
144 | try:
145 | contents = contents.decode('utf-8')
146 | except AttributeError:
147 | pass
148 | finally:
149 | print(contents)
150 |
151 | print(contents)
152 |
153 |
154 | def input_handler(state, is_gist):
155 | prompt = bcolors.HEADER + \
156 | "(Result {}/{})".format(
157 | state.index +
158 | 1,
159 | state.totalCount if state.totalCount < 1000 else "1000+") + \
160 | "=== " + bcolors.ENDC + \
161 | "Ignore similar [c]ontents" + \
162 | bcolors.OKGREEN + "/[u]ser"
163 | prompt += "" if is_gist else \
164 | bcolors.OKBLUE + "/[r]epo" + \
165 | bcolors.WARNING + "/[f]ilename"
166 | prompt += bcolors.HEADER + \
167 | ", [p]rint contents, [s]ave state, [a]dd to log, " + \
168 | "search [/(findme)], [b]ack, [q]uit, next []===: " + \
169 | bcolors.ENDC
170 | return input(prompt)
171 |
172 |
173 | def pagination_hack(repositories, state):
174 | count = len(repositories.__dict__["_PaginatedListBase__elements"])
175 | if state.index >= count:
176 | n_elements = repositories.get_page(state.index//30)
177 | repositories.__dict__["_PaginatedListBase__elements"] += n_elements
178 | return repositories
179 |
180 |
181 | def regex_handler(choice, repo):
182 | if choice[1] != "(" or choice[-1] != ")":
183 | print(
184 | bcolors.FAIL +
185 | "Regex requires at least one group reference: "
186 | "e.g., (CaSeSensitive) or ((?i)insensitive)" +
187 | bcolors.ENDC)
188 | return ""
189 | else:
190 | print(bcolors.HEADER + "Searching: " + choice[1:] + bcolors.ENDC)
191 | return regex_search([choice[1:]], repo, False)
192 |
193 |
194 | def ui_loop(repo, log_buf, state, is_gist=False):
195 | choice = input_handler(state, is_gist)
196 |
197 | if choice == "c":
198 | state.bad_signatures.append(ssdeep.hash(repo.decoded_content))
199 | elif choice == "u":
200 | state.bad_users.append(repo.owner.login if is_gist
201 | else repo.repository.owner.login)
202 | elif choice == "r" and not is_gist:
203 | state.bad_repos.append(repo.repository.name)
204 | elif choice == "f" and not is_gist:
205 | state.bad_files.append(repo.name)
206 | elif choice == "p":
207 | print_handler(repo.decoded_content)
208 | ui_loop(repo, log_buf, state, is_gist)
209 | elif choice == "s":
210 | save_state(state.query, state)
211 | ui_loop(repo, log_buf, state, is_gist)
212 | elif choice == "a":
213 | with open(state.logfile, "a") as fd:
214 | fd.write(log_buf)
215 | elif choice.startswith("/"):
216 | log_buf += regex_handler(choice, repo)
217 | ui_loop(repo, log_buf, state, is_gist)
218 | elif choice == "b":
219 | if state.index - 1 < state.lastInitIndex:
220 | print(
221 | bcolors.FAIL +
222 | "Can't go backwards past restore point "
223 | "because of rate-limiting/API limitations" +
224 | bcolors.ENDC)
225 | ui_loop(repo, log_buf, state, is_gist)
226 | else:
227 | state.index -= 2
228 | elif choice == "q":
229 | sys.exit(0)
230 |
231 |
232 | def gist_fetch(query, page_idx, total_items=1000):
233 | gist_url = "https://gist.github.com/search?utf8=%E2%9C%93&q={}&p={}"
234 | query = urllib.parse.quote(query)
235 | gists = []
236 |
237 | try:
238 | resp = requests.get(gist_url.format(query, page_idx))
239 | soup = bs4.BeautifulSoup(resp.text, 'html.parser')
240 | total_items = min(total_items, int(
241 | [x.text.split()[0] for x in soup.find_all('h3')
242 | if "gist results" in x.text][0].replace(',', '')))
243 | gists = [x.get("href") for x in soup.findAll(
244 | "a", class_="link-overlay")]
245 | except IndexError:
246 | return {"data": None, "total_items": 0}
247 |
248 | return {"data": gists, "total_items": total_items}
249 |
250 |
251 | def gist_search(g, state):
252 | gists = []
253 | if state.index > 0:
254 | gists = [None] * (state.index//10) * 10
255 | else:
256 | gist_data = gist_fetch(state.query, 0)
257 | gists = gist_data["data"]
258 | state.totalCount = gist_data["total_items"]
259 |
260 | if state.totalCount == 0:
261 | print("No results found for query: {}".format(state.query))
262 | else:
263 | print(bcolors.CLEAR)
264 |
265 | i = state.index
266 | stepBack = False
267 | while i < state.totalCount:
268 | while True:
269 | state.index = i
270 |
271 | # Manual gist paginator
272 | if i >= len(gists):
273 | new_gists = gist_fetch(state.query, i // 10)["data"]
274 | if not new_gists:
275 | try:
276 | print(
277 | bcolors.FAIL +
278 | "RateLimitException: "
279 | "Please wait about 30 seconds before you "
280 | "try again, or exit (CTRL-C).\n " +
281 | bcolors.ENDC)
282 | save_state("ratelimited", state)
283 | input("Press enter to try again...")
284 | continue
285 | except KeyboardInterrupt:
286 | sys.exit(1)
287 | gists.extend(new_gists)
288 |
289 | gist = g.get_gist(gists[i].split("/")[-1])
290 | gist.decoded_content = "\n".join(
291 | [gist_file.content for _, gist_file in gist.files.items()])
292 |
293 | log_buf = "https://gist.github.com/" + \
294 | bcolors.OKGREEN + gist.owner.login + "/" + \
295 | bcolors.ENDC + \
296 | gist.id
297 | print(log_buf)
298 | log_buf = "\n" + log_buf + "\n"
299 |
300 | if should_parse(gist, state, is_gist=True) or stepBack:
301 | stepBack = False
302 | log_buf += regex_search(state.checks, gist, state.line_numbers)
303 | ui_loop(gist, log_buf, state, is_gist=True)
304 | if state.index < i:
305 | i = state.index
306 | stepBack = True
307 | print(bcolors.CLEAR)
308 | else:
309 | print("Skipping...")
310 | i += 1
311 | break
312 |
313 |
314 | def github_search(g, state):
315 | print("Collecting Github Search API data...")
316 | try:
317 | repositories = g.search_code(state.query)
318 |
319 | state.totalCount = repositories.totalCount
320 |
321 | # Hack to backfill PaginatedList with garbage to avoid ratelimiting on
322 | # restore, library fetches in 30 counts
323 | repositories.__dict__["_PaginatedListBase__elements"] = [
324 | None] * (state.index//30) * 30
325 | state.lastInitIndex = state.index
326 |
327 | print(bcolors.CLEAR)
328 |
329 | i = state.index
330 | stepBack = False
331 | while i < state.totalCount:
332 | while True:
333 | try:
334 | state.index = i
335 |
336 | # Manually fill Paginator to avoid ratelimiting on restore
337 | repositories = pagination_hack(repositories, state)
338 |
339 | repo = repositories[i]
340 |
341 |
342 | # Setting domain/scheme name for log output
343 | scheme = g._Github__requester._Requester__scheme
344 | domain = g._Github__requester._Requester__hostname
345 |
346 | if(domain == "api.github.com"):
347 | domain = "github.com"
348 |
349 | log_buf = scheme + "://" + \
350 | domain + "/" + \
351 | bcolors.OKGREEN + repo.repository.owner.login + "/" + \
352 | bcolors.OKBLUE + repo.repository.name + "/blob" + \
353 | bcolors.ENDC + \
354 | os.path.dirname(repo.html_url.split('blob')[1]) + \
355 | "/" + bcolors.WARNING + repo.name + bcolors.ENDC
356 | print(log_buf)
357 | log_buf = "\n" + log_buf + "\n"
358 |
359 | if should_parse(repo, state) or stepBack:
360 | stepBack = False
361 | log_buf += regex_search(state.checks, repo,
362 | state.line_numbers)
363 | ui_loop(repo, log_buf, state)
364 | if state.index < i:
365 | i = state.index
366 | stepBack = True
367 | print(bcolors.CLEAR)
368 | else:
369 | print("Skipping...")
370 | i += 1
371 | break
372 | except github.RateLimitExceededException:
373 | try:
374 | print(
375 | bcolors.FAIL +
376 | "RateLimitException: "
377 | "Please wait about 30 seconds before you "
378 | "try again, or exit (CTRL-C).\n " +
379 | bcolors.ENDC)
380 | save_state("ratelimited", state)
381 | input("Press enter to try again...")
382 | except KeyboardInterrupt:
383 | sys.exit(1)
384 | except github.RateLimitExceededException:
385 | print(
386 | bcolors.FAIL +
387 | "RateLimitException: "
388 | "Please wait about 30 seconds before you try again.\n" +
389 | bcolors.ENDC)
390 | save_state("ratelimited", state)
391 | sys.exit(-1)
392 |
393 |
394 | def regex_validator(args, state):
395 | with open(args.checks, "r") as fd:
396 | for line in fd.read().splitlines():
397 | if line.startswith("#") or len(line) == 0:
398 | continue
399 | try:
400 | re.subn(line, r'\1', "Expression test")
401 | except sre_constants.error as e:
402 | print(bcolors.FAIL + "Invalid Regular expression:\n\t" + line)
403 | if "group" in str(e):
404 | print(
405 | "Ensure expression contains"
406 | "a capture group for matches:\n\t" + str(e))
407 | sys.exit(-1)
408 | state.checks.append(line)
409 |
410 | split = []
411 | if not (state.query[0] == "\"" and state.query[-1] == "\""):
412 | split = re.split(GITHUB_WHITESPACE, state.query)
413 |
414 | for part in [state.query] + split:
415 | if part:
416 | escaped_query = re.escape(part) if split else \
417 | part.replace("\"", "")
418 | state.checks.append("(?i)(" + escaped_query + ")")
419 | return state
420 |
421 |
422 | def main():
423 | global ACCESS_TOKEN
424 |
425 | if sys.version_info < (3, 0):
426 | sys.stdout.write("Sorry, requires Python 3.x, not Python 2.x\n")
427 | sys.exit(1)
428 |
429 | parser = argparse.ArgumentParser(
430 | formatter_class=argparse.RawDescriptionHelpFormatter,
431 | description="./" + sys.argv[0] + " -q example.com\n" +
432 | "./" + sys.argv[0] + " -q example.com -f checks/default.list "
433 | "-o example1.log\n" +
434 | "./" + sys.argv[0] + " -q example.com -r example.com.state")
435 | parser.add_argument(
436 | "-q",
437 | "--query",
438 | help="Github Code Query",
439 | type=str,
440 | required=True)
441 | parser.add_argument(
442 | "--line-numbers",
443 | help="Print line numbers",
444 | action="store_true")
445 | parser.add_argument(
446 | "--gist",
447 | help="Search GitHub Gists instead",
448 | action="store_true",
449 | required=False)
450 | parser.add_argument(
451 | "-f",
452 | "--checks",
453 | help="List of RegEx checks (checks/default.list)",
454 | type=str,
455 | default=os.path.dirname(os.path.realpath(__file__)) + "/checks/default.list")
456 | parser.add_argument(
457 | "-o",
458 | "--output",
459 | help="Log name (default: .log)",
460 | type=str)
461 | parser.add_argument(
462 | "-r",
463 | "--recover",
464 | help="Name of recovery file",
465 | type=str)
466 | parser.add_argument(
467 | "-u",
468 | "--url",
469 | help="URL of self-hosted GitHub instance (e.g., https://git.example.com)",
470 | type=str)
471 | args = parser.parse_args()
472 |
473 | state = State()
474 | state.index = 0
475 |
476 | if ACCESS_TOKEN == "":
477 | ACCESS_TOKEN = os.environ.get("GITHUB_ACCESS_TOKEN", "")
478 |
479 | if not ACCESS_TOKEN:
480 | print("Github Access token not set")
481 | sys.exit(1)
482 |
483 | if args.recover:
484 | with open(args.recover, 'r') as fd:
485 | state = State(**json.load(fd))
486 |
487 | args.query = args.query.lstrip()
488 |
489 | # Reusing Blacklists on new query
490 | if state.query != args.query:
491 | state.query = args.query
492 | state.index = 0
493 |
494 | state.is_gist = state.is_gist or (args.gist and not state.is_gist)
495 | state.line_numbers = state.line_numbers or \
496 | (args.line_numbers and not state.line_numbers)
497 |
498 | if args.output:
499 | state.logfile = args.output
500 | else:
501 | state.logfile = "logs/" + \
502 | re.sub(r"[,.;@#?!&$/\\'\"]+\ *", "_", args.query)
503 | state.logfile += "_gist.log" if state.is_gist else ".log"
504 |
505 | # Create default directories if they don't exist
506 | try:
507 | os.mkdir("logs")
508 | os.mkdir("states")
509 | except FileExistsError:
510 | pass
511 |
512 | # Load/Validate RegEx Checks
513 | state = regex_validator(args, state)
514 |
515 | if args.url:
516 | g = github.Github(base_url=args.url + "/api/v3",
517 | login_or_token=ACCESS_TOKEN)
518 | else:
519 | g = github.Github(ACCESS_TOKEN)
520 |
521 |
522 | if state.is_gist:
523 | gist_search(g, state)
524 | else:
525 | github_search(g, state)
526 |
527 |
528 | if __name__ == "__main__":
529 | main()
530 |
--------------------------------------------------------------------------------
/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/BishopFox/GitGot/4ce0d88a36c285a7ceaca84104009a8e3b6f6e99/logo.png
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | beautifulsoup4
2 | PyGithub
3 | ssdeep
4 |
--------------------------------------------------------------------------------