Disclaimer: there are surely many, far better ways to do this — feel free to add them in the comments. This was just a quick and dirty script I came up with yesterday, after a co-worker wondered if there was an easy way to do this on all the servers we administer.
The situation: you administer 1000 or more servers, you and your team are the only users who are supposed to be able to sudo to root (unlike simply running certain specific commands, which is typically OK), but sometimes you have to grant temporary access to a particular user or group of users who, for instance, are doing the initial application installations, but who are supposed to lose that access when the server enters production.
The problem: it’s easy to forget about those, and so the temporary access becomes permanent (yes, there are other ways around that, such as using a specific syntax for those accesses that includes a comment that you then use a script, called by the “at” daemon, to remove later, but bear with me for now). Wouldn’t it be useful to be able to look at a group of some, or even all, of the servers you administer, and find those unwanted, forgotten sudo accesses?
Here’s a bash script:
- as I said, this is something I came up with in a short time; I’m sure there are far better ways to do it. Feel free to suggest some. 🙂
- the script makes an exception for a “sysadmins” group that is allowed to sudo to root at will. Change or remove that part as needed.
- the point, of course, is to run this script on a lot of servers — possibly the whole list of servers you maintain –, and then check the exit codes (anything other than 0 means someone can sudo to root) and/or output (anything other than the string “Everything OK!” means… you get the idea.) If your company already uses a system to run scripts on a group of machines, use it; if not, there are always pssh, or a “for” loop in bash (e.g. create a file “find-sudoers.sh” with the script, and then do the following:
for i in `cat servers.txt`; do ssh root@$i < find-sudoers.sh ; done
- the method just above, however, requires ssh servers allowing direct root access by ssh, which isn’t a good idea at all. Assuming you don’t have such access, but have a user who can sudo to root without being asked for a password, you can do this:
for i in `cat servers.txt`; do cat find-sudoers.sh | ssh user@$i "cat - | sudo /bin/bash"; done
- if you do have to enter a password when sudoing to root, and creating an excepted user is not an option, then you have a problem. There are ways around it, but right now nothing comes to mind that is either simple enough or doesn’t add a new security problem (again, feel free to comment). But, if you’re a sysadmin at a sizable company, I’m sure you already have some way to run scripts as root on a large number of servers. (If not, my condolences…)