Skip to content

Instantly share code, notes, and snippets.

@kubicek
Created March 30, 2009 11:32
Show Gist options
  • Save kubicek/87751 to your computer and use it in GitHub Desktop.
Save kubicek/87751 to your computer and use it in GitHub Desktop.
import sys, os, optparse, re
def die(msg):
print >>sys.stderr, '%s: %s' % (sys.argv[0], msg)
sys.exit(1)
def getParser():
parser = optparse.OptionParser(
usage='%prog [OPTIONS] DIR',
description='Allow restricted git operations under DIR',
)
parser.add_option('--read-only',
help='disable write operations',
action='store_true',
default=False,
)
return parser
ALLOW_RE = re.compile("^(?P<command>git-(?:receive|upload)-pack) '[a-zA-Z][a-zA-Z0-9@._-]*(/[a-zA-Z][a-zA-Z0-9@._-]*)*'$")
COMMANDS_READONLY = [
'git-upload-pack',
]
COMMANDS_WRITE = [
'git-receive-pack',
]
def main(args):
os.umask(0022)
parser = getParser()
(options, args) = parser.parse_args()
try:
(path,) = args
except ValueError:
parser.error('Missing argument DIR.')
os.chdir('repos')
cmd = os.environ.get('SSH_ORIGINAL_COMMAND', None)
if cmd is None:
die("Need SSH_ORIGINAL_COMMAND in environment.")
if '\n' in cmd:
die("Command may not contain newlines.")
match = ALLOW_RE.match(cmd)
if match is None:
die("Command to run looks dangerous")
match = re.compile("^(?P<command>git-(?:receive|upload)-pack) '"+path+"/[a-zA-Z][a-zA-Z0-9@._-]*(/[a-zA-Z][a-zA-Z0-9@._-]*)*'$").match(cmd)
if path == 'kubicek' and match is None:
match = re.compile("^(?P<command>git-(?:receive|upload)-pack) 'xnet/[a-zA-Z][a-zA-Z0-9@._-]*(/[a-zA-Z][a-zA-Z0-9@._-]*)*'$").match(cmd)
if match is None:
die("User is not authorized to access this repository")
allowed = list(COMMANDS_READONLY)
if not options.read_only:
allowed.extend(COMMANDS_WRITE)
if match.group('command') not in allowed:
die("Command not allowed")
os.execve('/usr/local/bin/git-shell', ['git-shell', '-c', cmd], {})
die("Cannot execute git-shell.")
if __name__ == '__main__':
main(args=sys.argv[1:])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment