82

I have this command to backup a remote machine. The problem is that I need root rights to read and copy all files. I have no root user enabled for security reasons and use sudo the Ubuntu way. Would I need some cool piping or something to do this?

rsync -chavzP --stats [email protected]:/ /media/backupdisk/myserverbackup/
2
  • 3
    Just use the root account in the first place. sudo, especially combined with NOPASSWD as recommended in the comments, doesn't really improve the security of your machine. Commented Sep 24, 2013 at 12:01
  • ssh for root is disabled for security. Commented Apr 20, 2021 at 10:59

8 Answers 8

112

I would recommend that you just use the root account in the first place. If you set it up like this:

  • Configure your sshd_config on the target machine to PermitRootLogin without-password.
  • Use ssh-keygen on the machine that pulls the backup to create an SSH private key (only if you don't already have an SSH key). Do not set a passphrase. Google a tutorial if you need details for this, there should be plenty.
  • Append the contents of /root/.ssh/id_rsa.pub of the backup machine to the /root/.ssh/authorized_keys of your target machine.
  • Now your backup machine has root access to your target machine, without having to use password authentication.

then the resulting setup should be pretty safe.


sudo, especially combined with NOPASSWD as recommended in the comments, has no security benefits over just using the root account. For example this suggestion:

add the following to your /etc/sudoers file: rsyncuser ALL= NOPASSWD:/usr/bin/rsync

essentially gives rsyncuser root permissions anyway. You ask:

@MartinvonWittich Easy to gain a full root shell because rsync executed with sudo? Walk [m]e [through] that please.

Well, simple. With the recommended configuration, rsyncuser may now run rsync as root without even being asked for a password. rsync is a very powerful tool to manipulate files, so now rsyncuser has a very powerful tool to manipulate files with root permissions. Finding a way to exploit this took me just a few minutes (tested on Ubuntu 13.04, requires dash, bash didn't work):

martin@martin ~ % sudo rsync --perms --chmod u+s /bin/dash /bin/rootdash
martin@martin ~ % rootdash
# whoami
root
# touch /etc/evil
# tail -n1 /etc/shadow
dnsmasq:*:15942:0:99999:7:::

As you can see, I have created myself a root shell; whoami identifies my account as root, I can create files in /etc, and I can read from /etc/shadow. My exploit was to set the setuid bit on the dash binary; it causes Linux to always run that binary with the permissions of the owner, in this case root.

Having a real root is not [recommended] for good reasons. – redanimalwar 15 hours ago

No, clumsily working around the root account in situations where it is absolutely appropriate to use it is not for good reasons. This is just another form of cargo cult programming - you don't really understand the concept behind sudo vs root, you just blindly apply the belief "root is bad, sudo is good" because you've read that somewhere.

On the one hand, there are situations where sudo is definitely the right tool for the job. For example, when you're interactively working on a graphical Linux desktop, let's say Ubuntu, then having to use sudo is fine in those rare cases where you sometimes need root access. Ubuntu intentionally has a disabled root account and forces you to use sudo by default to prevent users from just always using the root account to log in. When the user just wants to use e.g. the web browser, then logging in as root would be a dangerous thing, and therefore not having a root account by default prevents stupid people from doing this.

On the other hand, there are situations like yours, where an automated script requires root permissions to something, for example to make a backup. Now using sudo to work around the root account is not only pointless, it's also dangerous: at first glance rsyncuser looks like an ordinary unprivileged account. But as I've already explained, it would be very easy for an attacker to gain full root access if he had already gained rsyncuser access. So essentially, you now have an additional root account that doesn't look like a root account at all, which is not a good thing.

14
  • 2
    Nice explanation. Would another reason for using sudo over root be in the situation where multiple people have sysadmin roles on a server? This way each can use their own SSH keys instead of sharing the SSH key of root? Commented Jan 22, 2014 at 21:33
  • 2
    @NathanS.Watson-Haigh you could just as easy put all SSH keys into /root/.ssh/authorized_keys, or even create multiple root accounts with different homes so each user can have his own shell, home and .ssh/authorized_keys :) Commented Jan 23, 2014 at 11:17
  • 2
    You can restrict ssh keys to only allowing certain commands, too. Definitely a good idea, since if you're automating something, you will probably be making these ssh keys without any passphrase, or at least so they're accessible all the time a machine is running. (meaning that root on that machine grants access to root on other machines.) Commented Mar 7, 2015 at 15:10
  • 3
    Martin's concerns regarding using sudo root are valid, but it seems they could be mitigated by specifying the exact rsync parameters in the sudoers file. According to the sudoers(5) man page on Ubuntu: "If a Cmnd has associated command line arguments, then the arguments in the Cmnd must match exactly those given by the user on the command line (or match the wildcards if there are any)." If the sudoers file specifies the exact rsync command with the exact options (including source and destination), then it seems it should be safe.
    – user155566
    Commented Feb 8, 2016 at 18:41
  • 5
    One consideration not brought up earlier: sshd generally does not log which authorized key was used to connect to an account, so if you connect as bob then sudo, you get a better audit trail than if you connect in to root directly with bob's key.
    – Coderer
    Commented Jun 15, 2016 at 12:44
83

Make use of the --rsync-path option to make the remote rsync command run with sudo privileges. Your command should then be e.g.:

rsync -chavzP --rsync-path="sudo rsync" --stats [email protected]:/ .

If sudo prompts you for a password, you have to avoid that either by using a NOPASSWD privilege with the remote user account (pointless for root, may make sense in other use cases), or if you don't want to do that:

  • Make sure that the option tty_tickets is disabled for the user you are using, by running e.g. sudo visudo -f /etc/sudoers.d/local-rsync and entering:

    Defaults:your.username.for.rsync !tty_tickets
    
  • Make sure that the option requiretty is disabled for the user you are using - it could be off by default. The method is the same as above.

  • Seed the sudo password on the remote machine, by running e.g. ssh -t [email protected] sudo

13
  • 2
    @scai the password that is asked for is most likely the sudo password, not the ssh password
    – umläute
    Commented Sep 24, 2013 at 8:15
  • 2
    @redanimalwar allows your user to sudo /usr/bin/rsync without asking for a passphrase; check man sudoers for how to do this; you might want to create an extra backup user for this.
    – umläute
    Commented Sep 24, 2013 at 8:17
  • 6
    To allow sudo /usr/bin/rsync to run without requiring as password add the following to your /etc/sudoers file: rsyncuser ALL= NOPASSWD:/usr/bin/rsync This will allow the user rsyncuser (as mentioned above it would be best to create a dedicated backup user) with the username you want.
    – M_dk
    Commented Sep 24, 2013 at 9:38
  • 5
    @M_dk now rsync essentially always has root permissions; it's probably very easy to gain a full root shell in that account. I think it's better to just use the real root account in the first place. Commented Sep 24, 2013 at 12:00
  • 1
    The answer in no way speaking of echo "password" | something I actually never used this and agree with the security problems coming with letting sudoless execution of rsync (also not suggested here) is bad. What the tty_tickets does I have actually no idea, seems needed and a security issue. This would work securely without tweaking anything by just running sodo on ssh and then executing the command right? But since I asked that question for scriping purposes, I totally agree that key based ssh without pw is the secure and right was to do. I accepted Martins answer instead. Commented Mar 7, 2015 at 16:47
17

One simple way to do this is to use the graphical ssh-askpass program with sudo, this gets around the fact that sudo is not connected to the terminal and allows you to enter the password safely:

rsync -chavzPe 'ssh -X' --stats \
  --rsync-path='SUDO_ASKPASS=/usr/lib/ssh/x11-ssh-askpass sudo -A rsync' \
  [email protected]:/ .

Of course the ssh-askpass program must be installed in the given location and you must be running an X session on the machine you are working on. There are a few variations on the ssh-askpass program which should also work (Gnome/KDE versions). Also a graphical sudo replacement program like gksu or kdesudo should also work.

4
  • rsync --rsh='ssh -X' --rsync-path='gksudo -- rsync' user@host:/ . doesn't work. rsync error: syntax or usage error (code 1) at main.c(1634) [server=3.1.1]. Oh, ubuntu does ship gnome-ssh-askpass, but it's /usr/bin/ssh-askpass, instead of /usr/lib/ssh/x11.... So that worked :) Commented Mar 7, 2015 at 15:05
  • 1
    This is one of the better solutions as it doesn't need any reconfiguration on the other end -- just needs the askpass installed and X forwarding enabled, both of which should be fairly common. Commented Aug 4, 2015 at 10:55
  • 1
    Works like a charm after installing ssh-askpass. I just had to look up the meaning of -chavzPe, would be great to spell these out as long options.
    – krlmlr
    Commented Oct 14, 2016 at 16:19
  • I tried this, but the prompt is opening on the remote machine and is not being forwarded to the local machine. X11Forwarding is working ask expected, which I verified by running xeyes using SSH.
    – Joyce Babu
    Commented Jan 19, 2019 at 14:51
7

If your user has already sudo privileges which are protected with a password I would keep them as-is and only add a stanza to use rsync without a password:

%admin ALL=(ALL) ALL
%admin ALL= NOPASSWD:/usr/bin/rsync 
1
  • This answer is technically correct (which is the best kind of correct), in that it does not directly use the root account. However i can set myself as root in 10 seconds if you give me unrestricted rsync access like in this answer.
    – Walter
    Commented May 8 at 14:13
6

I ran into this problem today and solved it without the need for modifying configuration files or granting root-level permissions to user accounts. My particular set-up was that user A on machine foo had to copy all of the user directories from foo to machine bar in a backup directory that user A owned. (User A has sudo privileges on foo.)

The command I used is below. It was invoked by user A in the /home directory on foo.

sudo rsync -avu -e "ssh -i /home/A/.ssh/id_rsa -l A"  * B:/home/backup

This runs rsync as sudo so that all user directories on foo can be accessed but it tells rsync to use ssh to access machine bar using user A's credentials. My needs were slightly different than the question above but this allowed me to quickly get a backup of all the user directories on a particular machine I manage without mucking with the system's configuration.

3
  • 2
    This is brilliant. I forgot about the -i option to ssh. You can use --rsync-path="sudo /usr/bin/rsync" if you have sudo on machine bar. This then does reading as root@foo and writing as root@bar, but transferring via A@foo -> B@bar. Thanks!
    – ctbrown
    Commented Jan 21, 2016 at 18:09
  • It will not preserve owner (e.g. root), am I right?
    – Andris
    Commented May 13, 2019 at 12:51
  • This was the answer that solved it for me after two days of trying various options. I could ssh into my server without a password but rsync continually asked for one. The important part is --rsh='ssh -i path/to/id_rsa' which tells rsync to use the ssh key when logging in ( --rsh is the long form of -e ). The full command is sudo rsync [options] --rsh='ssh -i path/to/id_rsa' /local/path [email protected]:/remote/path. Commented Jun 16, 2023 at 18:48
4

Running rsync as daemon on the target machine allows you to do what you want.

3
  • 2
    I upvoted this answer, but it would be better w/ some explanation of how to get the rsynch daemon running, and how you use it w/ root access. Commented Feb 9, 2015 at 16:29
  • rsync as daemon wouldn't match this case, because rsync will drop root permissions even when started as root then not all files could be transferred.
    – teissler
    Commented Apr 22, 2016 at 7:57
  • @teissler Please explain which root permissions are "dropped"? As far as I know, you only need to set uid = root and gid = root in the module config to use a specific rsyncd user (which are all separate from usual linux users) to copy all files, even those with root permissions. Finally it's much safer than all other described methods in the other answers as no root SSH access is needed and you can force ready-only.
    – mgutt
    Commented Jul 28, 2022 at 10:28
1

My solution is to use --rsync-path="sudo rsync" but it ask for password, workaround:

rsync -chavzP --stats --rsync-path="echo <SUDOPASS> | sudo -Sv && sudo rsync"  [email protected]:/ .
1
  • 3
    It usually isn't a good idea to put passwords into a command line one-liner; they become visible in the process tree, for example. I sometimes replace the actual password in this type of statement with $( cat my_password.txt ) which is slightly better, but it is usually preferred to configure the permissions on either end, and/or use SSH keys, in such a way that passwords aren't required on the CLI
    – JDS
    Commented May 2, 2018 at 15:13
-1

Re-vitalizing this old thread, as still valid.... To restrict root access across server using pre-shared keys I recommend:

A) Restrict ssh-in for root in sshd

Put this into /etc/sshd/sshd_config on the client at the end (may also be in authorized keys):

Match User root
    AllowUsers root@<(dirvish) servers from which access to root is granted>
    X11Forwarding no
    AllowTcpForwarding no
    PermitTTY no

B) Force command (I did this in authorized keys, may also be in sshd_config)

command="/root/.ssh/allowed_commands.sh 2> /root/.ssh/allowed_commands_`/bin/date +\%Y-\%m-\%d_\%H-\%M-\%S`_stderr.log" ssh-rsa ..... (here goes the key) ......

C) Wrapper script /root/.ssh/allowed_commands.sh Rights: 700 This is based on https://serverfault.com/questions/749474/ssh-authorized-keys-command-option-multiple-commands

#!/bin/bash
#
# You can have only one forced command in ~/.ssh/authorized_keys. Use this
# wrapper to allow several commands.

MY_PATH=`pwd`/.ssh
BASENAME=`basename $0`
STDOUT_LOG_FILE=${MY_PATH}/${BASENAME%.sh}_`/bin/date +\%Y-\%m-\%d_\%H-\%M-\%S`_stdout.log
find ${MY_PATH}/${BASENAME%.sh}*.log -ctime +4 | tee ${MY_PATH}/${BASENAME%.sh}_deleted_`/bin/date +\%Y-\%m-\%d_\%H-\%M-\%S`.log | xargs rm -f
# skip stdout? "rsync" commands have huge output and will flood FS....
# List here those which not to log stdout
COMMANDS_TO_SKIP_STDOUT=(rsync cat)

date >&2
echo I am instructed to run >&2
echo $SSH_ORIGINAL_COMMAND >&2
# skip stdout of the comand?
SKIP_STDOUT=0
for i in ${COMMANDS_TO_SKIP_STDOUT[@]}; do
 FOUND_SKIP_CMMAND=`expr "$SSH_ORIGINAL_COMMAND" : $i`
 if (( ${FOUND_SKIP_CMMAND} > 0 )) ; then 
  SKIP_STDOUT=1
 fi
done

case "$SSH_ORIGINAL_COMMAND" in
 "rsync --server --sender -vlkHogDtpre.iLsfxC --numeric-ids . <path 1>"     | \
 "rsync --server --sender -vlkHogDtpre.iLsfxC --numeric-ids . <path 2>/"    | \
 "rsync --server --sender -vlkHogDtpre.iLsfxC --numeric-ids . <path 3>/"    | \
 "cat /etc/hosts"                            | \
 "ls -alt /etc")
 # last entries for testing
 if (( ${SKIP_STDOUT} > 0 )) ; then 
      $SSH_ORIGINAL_COMMAND 
      RET_CODE=$?
  else
      $SSH_ORIGINAL_COMMAND | tee ${STDOUT_LOG_FILE}
      RET_CODE=$?
  fi
  echo "command executed" >&2
  echo "return code: " $RET_CODE >&2
  echo "output on stdout (this is the output to stderr)" >&2
  ;;
 *)
  echo "Access denied" | tee ${STDOUT_LOG_FILE}
  echo "Not in the list of allowed commands! Access denied" >&2
  echo "command not executed" >&2
  exit 1
  ;;
esac

So there is always a log (written to stderr and stored in /root/.ssh) at least from the latest run in which you can see what the command was.

If you want to set up a new command, just run it and check the stderr log.

stdout is also logged and as well passed back to the calling process, but is omitted for some commands (E.g. rsyncs would flood your filesystem) Logs are deleted in order not to eat storage.

(All set up in my systems and working perfect)

Still a lot of degrees of freedom, but I think this explains the idea :-)

Any Comments?

Bestest

Thilo

1
  • This question is over 7 years old and already has an accepted answer
    – Creek
    Commented May 6, 2021 at 22:09

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .