61

I love the idea of accessing servers via keys, so that I don't have to type in my password every time I ssh into a box, I even lock my user's (not root) password (passwd -l username) so it's impossible to log in without a key.

But all of this breaks if I'm required to enter password for sudo commands. So I'm tempted to set up passwordless sudo to make things in line with passwordless login.

However, I keep having a gut feeling that it may backfire at me in some unexpected way, it just seems somehow insecure. Are there any caveats with such set up? Would you recommend/not recommend doing this for a user account on a server?

Clarifications

  1. I'm talking about the use of sudo in an interactive user session here, not for services or administrative scripts
  2. I'm talking about using a cloud server (so I have no physical local access to a machine and can only log in remotely)
  3. I know that sudo has a timeout during which I don't have to re-enter my password. But my concert isn't really about wasting the extra time to physically type in a password. My idea though was to not have to deal with a password at all, because I assume that:
    • If I have to memorize it at all, it's very likely too short to be secure or reused
    • If I generate a long and unique password for my remote account, I'll have to store it somewhere (a local password manager program or a cloud service) and fetch it every time I want to use sudo. I hoped I could avoid that.

So with this question I wanted to better understand the risks, caveats and tradeoffs of one possible configuration over the others.

Follow up 1

All answers say that passwordless sudo is insecure as it allows "easy" escalation of privileges if my personal user account gets compromised. I understand that. But on the other hand, if I use a password, we incur all the classic risks with passwords (too short or common string, repeated across different services, etc.). But I guess that if I disable password authentication in /etc/ssh/sshd_config so that you still have to have a key to log in, I can use a simpler password just for sudo that's easier to type in? Is that a valid strategy?

Follow up 2

If I also have a key to log in as root via ssh, if somebody gets access to my computer and steal my keys (they're still protected by OS' keyring password though!), they might as well get a direct access to the root account, bypassing the sudo path. What should be the policy for accessing the root account then?

Dmitry Pashkevich
  • 693
  • 1
  • 5
  • 11
  • 2
    Would not recommend it at all, because there are often ways to get a shell as user (since all services are subject to security breach, but they usually run as user to avoid full access to the system), but having a password to login as root prevents unauthorized people to get root access. If there is none, thinks that anyone who get access to your user account by any way has a full access to the server. Setting a password might not be much, but it helps. – piernov Mar 09 '14 at 21:50
  • Please see my follow-up questions – Dmitry Pashkevich Mar 10 '14 at 09:46
  • 1
    sudo should never be passwordless. root should be disabled from remote login via SSH, ssh port shouldn't be default (to ditch the dumb-bots), and any account needing sudo should either be limited to only the bare minimum sudo powers for whatever they need (restart a service only, etc), and also have very strong passwords. – SnakeDoc Mar 10 '14 at 19:10
  • @SnakeDoc Thanks, that's a kind of reply I was expecting. Care to write a detailed answer? I'm happy to learn! – Dmitry Pashkevich Mar 10 '14 at 19:18
  • @SnakeDoc - how do you propose that you'd enable programmatic access to sudo commands if "sudo should never be passwordless". – EEAA Mar 10 '14 at 19:39
  • 2
    @EEAA it's actually quite easy in linux. The only accounts that should be allowed to be passwordless in sudo, would be system accounts that one cannot log into and therefore cannot elevate to that account and use those permissions against you. Set a bogus shell for the account in `/etc/passwd` such as nologin, set no password, and then set passwordless in visudo. If you do this, you should also make certain the visudo setting is for only what that system account absolutely needs, ie lock it down to the only commands it should ever run. – SnakeDoc Mar 10 '14 at 20:12
  • @SnakeDoc Fair enough. That's different than your statement that "sudo should never be passwordless", though. – EEAA Mar 10 '14 at 20:14
  • @EEAA i was in interactive-user mindset... didn't realize we were talking about *all* accounts originally. – SnakeDoc Mar 10 '14 at 20:18
  • @EEAA, SnakeDoc I actually meant interactive-user case (as I clarified later) but supplementary information is useful too! – Dmitry Pashkevich Mar 10 '14 at 20:32
  • @DmitryPashkevich Yup, understood. I always try and provide a survey of all the relevant information on a topic. – EEAA Mar 10 '14 at 20:33
  • Amazon obviously think it's OK because they do it. But you can obviously change it after your AMI has been started. AMI's are only as secure as the key file and the server name by default. But once you launch your ami you can customize it how you like. – hookenz Mar 10 '14 at 23:35
  • cloud = "my butt" ;) – d-_-b Mar 12 '14 at 09:08

9 Answers9

47

I love the idea of accessing servers via keys, so that I don't have to type in my password every time I ssh into a box, I even lock my user's (not root) password (passwd -l username) so it's impossible to log in without a key...Would you recommend/not recommend doing this for a user account on a server?

You're going about disabling password-based logins the wrong way. Instead of locking a user's account, set PasswordAuthentication no in your /etc/ssh/sshd_config.

With that set, password authentication is disabled for ssh, but you can still use a password for sudo.

The only time I recommend setting NOPASSWD in sudo is for service accounts, where processes need to be able to run commands via sudo programmatically. In those circumstances, make sure that you explicitly whitelist only the specific commands that account needs to run. For interactive accounts, you should always leave passwords enabled.

Responses to your follow-up questions:

But I guess that if I disable password authentication in /etc/ssh/sshd_config so that you still have to have a key to log in, I can use a simpler password just for sudo that's easier to type in? Is that a valid strategy?

Yes, that's correct. I still recommend using relatively strong local account passwords, but not ridiculously-strong. ~8 characters, randomly generated is sufficient.

If I also have a key to log in as root via ssh, if somebody gets access to my computer and steal my keys (they're still protected by OS' keyring password though!), they might as well get a direct access to the root account, bypassing the sudo path.

Root access via ssh should be disabled. Period. Set PermitRootLogin no in your sshd_config.

What should be the policy for accessing the root account then?

You should always have a means of obtaining out-of-band access to the console of your server. Several VPS vendors do provide this, as do vendors of dedicated hardware. If your provider doesn't grant real console access (say, EC2 for instance), you can typically still restore access using a process like what I outline in this answer.

EEAA
  • 108,414
  • 18
  • 172
  • 242
  • 2
    +1 *should* leave passwords... – Chris S Mar 10 '14 at 03:11
  • 6
    +1 the sudo password isn't _really_ there for secutiry (as far as I can see) but more as an idiot check. Not having there could cause untold havok. – Boris the Spider Mar 10 '14 at 08:21
  • Thanks for clarifying on `PasswordAuthentication`! This does mean, however, that this policy would be enforced for ALL accounts in the system, right? That way I might lock myself out of the box (including `root` account!) if I lose my keys... what should I do about that? Also, please see the updates to my question – Dmitry Pashkevich Mar 10 '14 at 09:49
  • @EEAA forgot to mention that for "service accounts" you had better set up a whitelist of commands that the service-user can execute without a password. You don't want that service user to be able to `rm -rf /*` when the user was configured just to be able to bounce Apache periodically without user intervention. – Christopher Schultz Mar 10 '14 at 13:50
  • @ChristopherSchultz Great point. I've amended my answer. – EEAA Mar 10 '14 at 14:25
  • @DmitryPashkevich - I've updated my answer. – EEAA Mar 10 '14 at 14:25
  • 1
    if you loose your key, you are done, unless you have a backdoor in, but then so does an attacker. the only way to fix a lost key if done properly, would be to sit at the actual terminal yourself, physically. If you need the kind of protection ssh keys provide, you should be aware of the pitfalls, and simply... just don't loose your keys. – SnakeDoc Mar 10 '14 at 19:58
  • @BoristheSpider - "sudo not there for security but more as an idiot proof check"?? nonsense. Sudo is designed to increase privileges to users who require it and are allowed to do so according to rules defined in the sudoers file. Obviously, if you're an ordinary user you should not be allowed root user privileges granted by sudo. That's why the password is there. – hookenz Mar 10 '14 at 23:27
  • @Matt, that's my point - _increase privileges to users who require it and are allowed to do so according to rules defined in the sudoers file_. If you are not allowed to `sudo` then you should not be granted the privilege to in the sudoers file. The password is not, in my experience, used as a security feature - or at least not as a major component of a security protocol. – Boris the Spider Mar 10 '14 at 23:29
  • Oh I get you. Sorry I misunderstood your point. Well the password is still useful if you happen to leave your console open. Which you should not be doing. Or if your account got somehow hacked into, the user would still stuck at your lowered privilege. Gaining root still would require a password. – hookenz Mar 10 '14 at 23:32
  • 1
    A comment towards your last paragraph, and regarding loosing access in general for any VPS... some VPS providers will actually help you out if you get locked out. I"ve had one boot my VM into Single User mode and do some things for me when I locked myself out (it happens... bad firewall rule lol). Depending on your host, they may charge you for the service; they are, after all, dedicating special attention to you. Also, some will do backup/snapshots for a small price or sometimes for free, which can be worth it if you are about to commit a large, possibly disruptive change. – SnakeDoc Mar 11 '14 at 14:56
  • @snakedoc - yep, absolutely. Good providers will often help out. Given the choice, though, when selecting a vendor, I recommend always choosing one that grants its customers the tools to gain console access on their own, without needing to go through support channels. – EEAA Mar 11 '14 at 15:28
  • 1
    @DmitryPashkevich - regarding `PasswordAuthentication` affecting all users, you can always use `Match` sections in sshd_config to turn it back on for certain users or groups. – Matt Thomason Mar 12 '14 at 02:16
  • @nyuszika7h I'm not sure what any of that has to go with disabling root ssh. Anyway, this is why you password protect private keys. Even if I handed you my unencrypted private key, you still wouldn't be able to get access to my servers via linode' serial console. To do that, you would still need username and password. And yes, I absolutely do have different keys for each device. Are you happy now? – EEAA Mar 18 '15 at 12:40
  • @nyuszika7h Logging in as root is *always* a bad idea, period. Security concerns or not. Security is only one reason to do this. The other reason is that by logging in as root, you get lazy, and do not force yourself to really think through what you're doing. You also lose the auditing aspect you gain by using sudo. I'm not going to sit here and argue with you any more. In this instance, it is overwhelmingly clear what the right course of action is. – EEAA Mar 18 '15 at 12:49
  • @nyuszika7h Except that there is. You can get on Linode's console with my key, but then you still need to use user/pass to authenticate to the server before gaining access to the OS. Serial consoles know nothing about key authentication. Anyway, have a great day! – EEAA Mar 18 '15 at 13:02
  • 1
    @nyuszika7h When logging directly into Root you lose the audit trail, something that EEAA has tried to point out. Yes you can assume you are the only person with the root password or ssh keys, but what if that's not true (someone stole or cracked them)? When in a corporate environment and there's likely several admins, if you allow direct root login, who last logged in? Who's credentials were stolen/compromised? When you force regular user login, then sudo, you know who to go when something stupid was done under root, or who's credentials to revoke if they were leaked. – SnakeDoc Mar 18 '15 at 14:45
  • 1
    @nyuszika7h Just stop. What you are describing *is* just plain bad practice. The "locked out admin" can almost always fire up their IPMI or remote console and login directly as root -- no need to get the provider involved. But that doesn't make the case for allowing direct root access over ssh remotely. If you take this poor practice and implement it on your own personal VPS, fine. When you get into corporate IT; this mindset will get your and your servers into trouble. – SnakeDoc Mar 20 '15 at 14:40
  • I'm sorry, I should calm down. You're right. Although I still think allowing root login over SSH with a single well-protected SSH key isn't exactly a glaring security hole (if it were, that would mean SSH keys are broken), now I see that there's almost never a reason to allow it. If you're locked out, you probably would have to use the serial console anyway, whether you can access it directly (which they can in most cases) or have to go through someone (like with my VPS hosted by my friend—and he's not incompetent, it works great) doesn't make a difference in this case. – nyuszika7h Mar 20 '15 at 18:59
  • @nyuszika7h I'm glad you finally came around to understand that we're not all crazies here. :) In the future, you may consider taking more seriously the advice of those who are in charge of large fleets of servers, versus your own experience, not managing your own single VPS. – EEAA Mar 20 '15 at 19:03
  • Do you still stand by this advice, now that ansible is so popular? As you know, ansible typically logs into a remote server/vps and then uses passwordless sudo in order to run its automation. Do you believe that is "ok", or would you advise against it? I have a [related question here](https://serverfault.com/questions/980031/is-it-insecure-to-have-an-ansible-user-with-passwordless-sudo), if you don't mind :) – lonix Aug 20 '19 at 19:04
13

I generally restrict use of NOPASSWORD to commands that are run by an automated process. It is preferable to have a service account for these commands, and restrict the use of sudo to the required commands.

Allowing NOPASSWORD for general commands, allows anyone who gets access to your userid to run any commands. This could result from a compromise of your credentials, but could be as simple as someone sitting at your desk when you step away for a second.

I find I don't have to enter my password that often. Once you enter your password, you can run several commands if you don't wait too long between them. The timeout is configurable.

BillThor
  • 27,354
  • 3
  • 35
  • 69
13

You can have the best of both worlds: SSH authentication for both login and for sudo. If you integrate the pam_ssh_agent_auth module you can use SSH keys to authenticate without giving a password when you sudo.

I've been using this in production for more than five years.

To configure it, install the PAM module, and then add a line to /etc/pam.d/sudo or your system's equivalent:

auth    sufficient     pam_ssh_agent_auth.so file=~/.ssh/authorized_keys

If you do this, be sure to protect your keys on your computer with a passphrase. That way, someone would have to break into your computer and steal the keys to get in. They could do that by pulling them from memory while they were unlocked if they have access to your account, by cracking your passphrase, or stealing your passphrase through a keylogger or shoulder surfing it while you type it in (look behind you!).

You can use the same SSH key as you do to login, or you could set up a separate key that you only add to your agent when you sudo. So if you want to be extra careful, you could maintain a separate authorized_keys file that has a separate SSH key that you only add to your agent when you need to sudo:

auth    sufficient     pam_ssh_agent_auth.so file=~/.ssh/authorized_keys_sudo
  • Wow, that sounds great! So do I generate a separate key for executing `sudo` commands or I use the same one that was used for SSH authentication? – Dmitry Pashkevich Mar 12 '14 at 13:54
  • 1
    This is amazing. I would upvote you multiple times if I could. – nyuszika7h Mar 20 '15 at 19:03
  • You can use the same key as you use for normal SSH authentication, or for added security, you can temporarily add a key you use for sudo-ing to your SSH authentication agent. This would require that you specify a different file than `~/.ssh/authorized_keys`, you could manage another file, `~/.ssh/authorized_keys_sudo` for example, or `/etc/ssh/authorized_keys_sudo`. – obscurerichard Dec 16 '16 at 21:49
  • 1
    I've been using this for years but now I'm not sure it adds any more security. The only way to login as me is with an SSH key anyway so how does requiring the same SSH key to sudo add any more security? – Hamish Moffatt Sep 10 '21 at 10:52
8

I would only use this in two circumstances:

  • When it is absolutely required for an automated script that is running as a specific user
  • For specific admin tasks (read only admin tasks, not those that take action to alter the system) and then only for specific users of course

By default most sudo configurations will not ask you again for a while in the same session (if you open a new shell that doesn't have any effect). You can control this behaviour to an extent with the timestamp_timeout setting.

Password-less sudo is not nearly as dangerous as passphrase-less ssh keys, as a remote attacker needs your credentials to get in in the first place, but if they have got in by somehow compromising your private key (or if they are physically local to you and you've left yourself logged in and unlocked while away from the machine) then the password request is a valuable extra defence between them and privileged access.

Regarding follow-up 2:

If I also have a key to log in as root via ssh

This is best avoided too, for exactly the reason you describe. If a remote connection must have privileged access have it login via a service account and give that just enough control to do its job via sudo. This is more faf to configure of course so many don't bother (which works in your favour if you do, as there is plenty of lower hanging fruit than you for attackers to spend there time on!), so it comes down to the age old compromise between security and convenience (pro tip: pick security!).

David Spillett
  • 22,534
  • 42
  • 66
  • Thanks for addressing my follow-up #2. I'm still confused though: I do try to avoid logging in as `root` directly but I do need SOME way to access the account, right? So how do I do it then? With a password, not ssh key? But aren't keys better than passwords? – Dmitry Pashkevich Mar 10 '14 at 10:05
  • You can always login locally as root, but it is recommended that direct logins to root from remote hosts (via ssh or similar) be completely disabled. If you have an account that can become root via sudo (with password of course) then you never lose all access to the account. – David Spillett Mar 10 '14 at 10:07
6

Since you asked, here's my general advice on how to address the sudo issue.

Sudo was not designed to provide more security (although it can in some regard)... but rather provide a good audit trail of who's doing what on your system with what privileges.

A properly setup Sudo will not use the ALL=(ALL) ALL setting, but rather something more limited to whatever it is specifically that the user needs. For example, if you need a user to be able to login and restart a stuck service, they probably do not need the ability to install new software or shutdown your server, change firewall rules, etc.

It's sometimes common for people to use sudo to elevate themselves to the root account, ie. sudo su -. Once they do that, you stop seeing who's doing what from the root account (root can be logged into multiple times concurrently). So sometimes people want to disable the sudo su - command as well. But, for practical reasons, if you do need a fully root-privileged account for administration, at the very least having someone issue the sudo su - command would log who elevated to root and when.

How I secure my boxes:

Change the SSH port to something other than the default. This is to avoid the dumb-bots that look for port numbers then pound away until they get in (or not).

Disallow Root login over SSH using the AllowRootLogin no setting in your sshd_config. This prevents someone from brute forcing into your root account. It's just generally good practice to never allow someone to directly log in to the root/administrator account for audit reasons as well as security. If you allow root login directly, you don't know who logged in, who they got the password from, etc. But, if someone logs into Jimmy's account, then elevates their permissions to root, you have a better idea where to start your audit search (and who's account to reset).

Only allow users to SSH that require it Use the AllowUsers setting and explicity specify which accounts needs SSH access. This will, by default, block all other accounts from SSH.

Edit Sudoers via visudo and only allow the commands the user needs. There are a lot of in depth guides on how to do this, so I won't detail here. Here's a starter: http://ubuntuforums.org/showthread.php?t=1132821

The gist of this is to prevent a compromised account from jeopardizing your machine. ie. if Sally's account gets broken into, and Sally can only use sudo to restart the web server, well the attacker might have fun restarting your web server in a loop, but at least they can't rm -rf /your/webserver/directory or open all your firewall ports, etc.

Setup good firewall rules that only allow the ports that are necessary for your box to operate. Generally you want to drop everything and only allow explicitly what you need. There's plenty of decent iptables and other firewall starts online, here's one I use (it's a basic starter):

# Generated by iptables-save v1.4.7 on Mon Mar  3 17:55:02 2014
*filter
:INPUT DROP [4528:192078]
:FORWARD DROP [0:0]
:OUTPUT ACCEPT [39845:27914520]
-A INPUT -i lo -j ACCEPT
-A INPUT -p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -m state --state NEW -j DROP
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p tcp -m tcp --dport 4254 -m state --state NEW -j ACCEPT
-A INPUT -p tcp -m tcp --dport 8080 -m state --state NEW -j ACCEPT
-A INPUT -p tcp -m tcp --dport 8443 -m state --state NEW -j ACCEPT
-A INPUT -p icmp -m icmp --icmp-type 8 -j ACCEPT
-A INPUT -p icmp -m icmp --icmp-type 11 -j ACCEPT
-A OUTPUT -o lo -j ACCEPT
COMMIT
# Completed on Mon Mar  3 17:55:02 2014

Also a strong password is key. Even if you use SSH keys for your remote access, you should still require a password for Sudo use. This is a case where sudo could provide some more security. If someone were to steal your ssh keys, they would still be prevented from doing anything significant on your box if they have to still brute force your account password to use sudo. Passwords should not be a word, but rather a Pass Phrase. Think of a sentence, and use that. This generally will get you something more than 8 characters long, providing plenty of entropy, but also is easier to remember than some random password. Of course, good password practices say to use a machine-generated random password as to fool cracking tools like John the Ripper, which will rip right through most passphrases and passwords. No, changing E with 3 does not work, John gets those permutations as well.

SnakeDoc
  • 560
  • 6
  • 23
  • Thanks for a comprehensive answer! I definitely need to use all of these advices to secure my boxes. I'll still accept EEAA's answer though as it's a little more specific to what I was asking. – Dmitry Pashkevich Mar 10 '14 at 21:12
  • 1
    @DmitryPashkevich that's OK, EEAA has a good and fitting answer. You asked me to detail my comment above, so I did. No worries :) – SnakeDoc Mar 10 '14 at 21:14
  • As for `sudo su -` and variations, `sudoreplay` could come in handy. – nyuszika7h Mar 20 '15 at 19:06
3

In some cases it's necessary to do this. e.g. some hypervisor API's need passwordless login and passwordless sudo. But you can still restrict that without breaking.

For what you're trying to achieve. I'd say, get used to typing in a password. Security is more convenient that convenience here. Besides, if you really need root access you can use sudo and it'll cache the credentials for a little while so that if you run several sudo commands in a row it'll only prompt for the password the first time. So it's not such a big inconvenience as you suppose.

Also if you're typing in a lot of root privileged commands and don't want to put sudo on the front of them all the time you can either su or sudo -s to get a root shell. You'll enter your password once and then that's it.

Dmitry Pashkevich
  • 693
  • 1
  • 5
  • 11
hookenz
  • 14,132
  • 22
  • 86
  • 142
2

I've been bitten by passwordless sudo once. It was a shell script, some installer which called sudo on my behalf as opposed to, you know, just requiring sudo or erroring out.

Imaging typing 'make' and the script doing the 'sudo make install' part for you, without setting or displaying the base path, and the script being so braindead in the first place that you're not sure they know about /usr/local and so you start checking /usr for modifications...

I vowed never to use NOPASSWD again and also changed that timeout setting to 0.

aib
  • 121
  • 3
2

The other answers here are great, and touch on most of the important points. One thing which I haven't seen mentioned is the fact that any sort of authentication you do when logged in yourself can be captured by a remote attacker who has already established a foothold in your account. They can modify your shell login files or PATH to install a keylogger so that everything you type, including your sudo password, is sent to them. They could add a hacked sudo binary to your PATH to collect your password. They can hijack the ssh agent connection back to your connecting machine to defeat pam_ssh_agent_auth and become root themselves as soon as you connect. So in terms of absolute security, I don't see a difference between using a password for sudo and not. It does, of course, make it a more complicated attackj, and they only get root once you have used sudo once, rather than immediately.

In summary, I believe the only way to absolutely prevent a compromised user account from becoming root if you have sudo access is to remove sudo access from yourself, or never use it. If you disagree, let me know, as I would love to be wrong!

Ian Hinder
  • 121
  • 2
1

While not strictly answering your question, another option may be to set a longer timestamp_timeout so you don't need to type in your password so often. This will prevent just anyone gaining admin privileges, but reducing your annoyance.

From the sudoers man page:

timestamp_timeout

Number of minutes that can elapse before sudo will ask for a passwd again. The timeout may include a fractional component if minute granularity is insufficient, for example 2.5. The default is 5. Set this to 0 to always prompt for a password. If set to a value less than 0 the user’s time stamp will never expire. This can be used to allow users to create or delete their own time stamps via "sudo -v" and "sudo -k" respectively.

This blog post shows some examples using visudo to set the timeout in minutes, such as:

Defaults timestamp_timeout=60

Maybe this is a happy middle-ground between security and ease-of-use?

daveharris
  • 11
  • 2
  • Thanks for the input! My original question was about not having to ever use (and remember) a password at all since you can use keys to ssh into the machine, not about how often I'm required to enter it. Other people made it clear that that's a bad idea though. – Dmitry Pashkevich Sep 05 '14 at 15:19