3 # Restricts rsync to subdirectory declared in .ssh/authorized_keys. See
4 # the rrsync man page for details of how to make use of this script.
6 # NOTE: install python3 braceexpand to support brace expansion in the args!
8 # Originally a perl script by: Joe Smith <js-cgi@inwap.com> 30-Sep-2004
9 # Python version by: Wayne Davison <wayne@opencoder.net>
11 # You may configure these 2 values to your liking. See also the section of
12 # short & long options if you want to disable any options that rsync accepts.
13 RSYNC = '/usr/bin/rsync'
14 LOGFILE = 'rrsync.log' # NOTE: the file must exist for a line to be appended!
16 # The following options are mainly the options that a client rsync can send
17 # to the server, and usually just in the one option format that the stock
18 # rsync produces. However, there are some additional convenience options
19 # added as well, and thus a few options are present in both the short and
20 # long lists (such as --group, --owner, and --perms).
22 # NOTE when disabling: check for both a short & long version of the option!
24 ### START of options data produced by the cull-options script. ###
26 # To disable a short-named option, add its letter to this string:
29 # These are also disabled when the restricted dir is not "/":
30 short_disabled_subdir = 'KLk'
32 # These are all possible short options that we will accept (when not disabled above):
33 short_no_arg = 'ACDEHIJKLNORSUWXbcdgklmnopqrstuvxyz' # DO NOT REMOVE ANY
34 short_with_num = '@B' # DO NOT REMOVE ANY
36 # To disable a long-named option, change its value to a -1. The values mean:
37 # 0 = the option has no arg; 1 = the arg doesn't need any checking; 2 = only
38 # check the arg when receiving; and 3 = always check the arg.
51 'copy-unsafe-links': 0,
61 'delete-missing-args': 0,
75 'ignore-missing-args': 0,
102 'one-file-system': 0,
103 'only-write-batch': 1,
111 'remove-sent-files': 0,
112 'remove-source-files': 0,
131 ### END of options data produced by the cull-options script. ###
133 import os, sys, re, argparse, glob, socket, time, subprocess
134 from argparse import RawTextHelpFormatter
137 from braceexpand import braceexpand
139 braceexpand = lambda x: [ DE_BACKSLASH_RE.sub(r'\1', x) ]
141 HAS_DOT_DOT_RE = re.compile(r'(^|/)\.\.(/|$)')
142 LONG_OPT_RE = re.compile(r'^--([^=]+)(?:=(.*))?$')
143 DE_BACKSLASH_RE = re.compile(r'\\(.)')
146 if not os.path.isdir(args.dir):
147 die("Restricted directory does not exist!")
149 # The format of the environment variables set by sshd:
150 # SSH_ORIGINAL_COMMAND:
151 # rsync --server -vlogDtpre.iLsfxCIvu --etc . ARG # push
152 # rsync --server --sender -vlogDtpre.iLsfxCIvu --etc . ARGS # pull
153 # SSH_CONNECTION (client_ip client_port server_ip server_port):
154 # 192.168.1.100 64106 192.168.1.2 22
156 command = os.environ.get('SSH_ORIGINAL_COMMAND', None)
158 die("Not invoked via sshd")
159 command = command.split(' ', 2)
160 if command[0:1] != ['rsync']:
161 die("SSH_ORIGINAL_COMMAND does not run rsync")
162 if command[1:2] != ['--server']:
163 die("--server option is not the first arg")
164 command = '' if len(command) < 3 else command[2]
167 am_sender = command.startswith("--sender ") # Restrictive on purpose!
168 if args.ro and not am_sender:
169 die("sending to read-only server is not allowed")
170 if args.wo and am_sender:
171 die("reading from write-only server is not allowed")
173 if args.wo or not am_sender:
174 long_opts['sender'] = -1
176 for opt in long_opts:
177 if opt.startswith(('remove', 'delete')):
180 long_opts['log-file'] = -1
183 global short_disabled
184 short_disabled += short_disabled_subdir
186 short_no_arg_re = short_no_arg
187 short_with_num_re = short_with_num
189 for ltr in short_disabled:
190 short_no_arg_re = short_no_arg_re.replace(ltr, '')
191 short_with_num_re = short_with_num_re.replace(ltr, '')
192 short_disabled_re = re.compile(r'^-[%s]*([%s])' % (short_no_arg_re, short_disabled))
193 short_no_arg_re = re.compile(r'^-(?=.)[%s]*(e\d*\.\w*)?$' % short_no_arg_re)
194 short_with_num_re = re.compile(r'^-[%s]\d+$' % short_with_num_re)
196 log_fh = open(LOGFILE, 'a') if os.path.isfile(LOGFILE) else None
201 die('unable to chdir to restricted dir:', str(e))
203 rsync_opts = [ '--server' ]
205 saw_the_dot_arg = False
206 last_opt = check_type = None
208 for arg in re.findall(r'(?:[^\s\\]+|\\.[^\s\\]*)+', command):
210 rsync_opts.append(validated_arg(last_opt, arg, check_type))
212 elif saw_the_dot_arg:
213 # NOTE: an arg that starts with a '-' is safe due to our use of "--" in the cmd tuple.
215 b_e = braceexpand(arg) # Also removes backslashes
216 except: # Handle errors such as unbalanced braces by just de-backslashing the arg:
217 b_e = [ DE_BACKSLASH_RE.sub(r'\1', arg) ]
219 rsync_args += validated_arg('arg', xarg, wild=True)
220 else: # parsing the option args
222 saw_the_dot_arg = True
224 rsync_opts.append(arg)
225 if short_no_arg_re.match(arg) or short_with_num_re.match(arg):
228 m = LONG_OPT_RE.match(arg)
232 ct = long_opts.get(opt, None)
234 break # Generate generic failure due to unfinished arg parsing
239 if opt_arg is not None:
240 rsync_opts[-1] = opt + '=' + validated_arg(opt, opt_arg, ct)
247 m = short_disabled_re.match(arg)
250 opt = '-' + m.group(1)
253 die("option", opt, "has been disabled on this server.")
254 break # Generate a generic failure
256 if not saw_the_dot_arg:
257 die("invalid rsync-command syntax or options")
260 rsync_opts.append('--munge-links')
262 if args.no_overwrite:
263 rsync_opts.append('--ignore-existing')
268 cmd = (RSYNC, *rsync_opts, '--', '.', *rsync_args)
271 now = time.localtime()
272 host = os.environ.get('SSH_CONNECTION', 'unknown').split()[0] # Drop everything after the IP addr
273 if host.startswith('::ffff:'):
276 host = socket.gethostbyaddr(socket.inet_aton(host))
279 log_fh.write("%02d:%02d:%02d %-16s %s\n" % (now.tm_hour, now.tm_min, now.tm_sec, host, str(cmd)))
282 # NOTE: This assumes that the rsync protocol will not be maliciously hijacked.
284 os.execlp(RSYNC, *cmd)
285 die("execlp(", RSYNC, *cmd, ') failed')
286 child = subprocess.run(cmd)
287 if child.returncode != 0:
288 sys.exit(child.returncode)
291 def validated_arg(opt, arg, typ=3, wild=False):
292 if opt != 'arg': # arg values already have their backslashes removed.
293 arg = DE_BACKSLASH_RE.sub(r'\1', arg)
296 if arg.startswith('./'):
298 arg = arg.replace('//', '/')
300 if HAS_DOT_DOT_RE.search(arg):
301 die("do not use .. in", opt, "(anchor the path at the root of your restricted dir)")
302 if arg.startswith('/'):
314 if args.dir != '/' and arg != '.' and (typ == 3 or (typ == 2 and not am_sender)):
315 arg_has_trailing_slash = arg.endswith('/')
316 if arg_has_trailing_slash:
319 arg_has_trailing_slash_dot = arg.endswith('/.')
320 if arg_has_trailing_slash_dot:
322 real_arg = os.path.realpath(arg)
323 if arg != real_arg and not real_arg.startswith(args.dir_slash):
324 die('unsafe arg:', orig_arg, [arg, real_arg])
325 if arg_has_trailing_slash:
327 elif arg_has_trailing_slash_dot:
329 if opt == 'arg' and arg.startswith(args.dir_slash):
330 arg = arg[args.dir_slash_len:]
335 return ret if wild else ret[0]
338 def lock_or_die(dirname):
341 lock_handle = os.open(dirname, os.O_RDONLY)
343 fcntl.flock(lock_handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
345 die('Another instance of rrsync is already accessing this directory.')
349 print(sys.argv[0], 'error:', *msg, file=sys.stderr)
350 if sys.stdin.isatty():
351 arg_parser.print_help(sys.stderr)
355 # This class displays the --help to the user on argparse error IFF they're running it interactively.
356 class OurArgParser(argparse.ArgumentParser):
357 def error(self, msg):
361 if __name__ == '__main__':
362 our_desc = """Use "man rrsync" to learn how to restrict ssh users to using a restricted rsync command."""
363 arg_parser = OurArgParser(description=our_desc, add_help=False)
364 only_group = arg_parser.add_mutually_exclusive_group()
365 only_group.add_argument('-ro', action='store_true', help="Allow only reading from the DIR. Implies -no-del and -no-lock.")
366 only_group.add_argument('-wo', action='store_true', help="Allow only writing to the DIR.")
367 arg_parser.add_argument('-munge', action='store_true', help="Enable rsync's --munge-links on the server side.")
368 arg_parser.add_argument('-no-del', action='store_true', help="Disable rsync's --delete* and --remove* options.")
369 arg_parser.add_argument('-no-lock', action='store_true', help="Avoid the single-run (per-user) lock check.")
370 arg_parser.add_argument('-no-overwrite', action='store_true', help="Prevent overwriting existing files by enforcing --ignore-existing")
371 arg_parser.add_argument('-help', '-h', action='help', help="Output this help message and exit.")
372 arg_parser.add_argument('dir', metavar='DIR', help="The restricted directory to use.")
373 args = arg_parser.parse_args()
374 args.dir = os.path.realpath(args.dir)
375 args.dir_slash = args.dir + '/'
376 args.dir_slash_len = len(args.dir_slash)
379 elif not args.no_lock:
380 lock_or_die(args.dir)