I am attempting to create a very simple web interface for changing some system settings on a network appliance. I am fairly new to PHP and becoming painfully aware of how easy it is to do things in hacky ways, so I am trying to write everything with the best practices in mind.

That said, what would the best practice be for editing files owned by root/some other admin account? Would it be to create a protected shell/perl/whatever script that gets executed by PHP? Using setuid was another option that came up, but that doesnt appear to have any way of restricting users.

I hope that wasn't too vague, let me know if you need any more details and I'll be glad to share.

Further Detail: Just to clarify - by edit system files I mean specifically ifcfg's and some proprietary licensing information. So for simplicity's sake, lets just say a simple web interface to change the ip/subnet/gateway/dns settings on a linux-based network appliance.

Comments

Restrict the webserver / router behind to 1 mac address, yours. Once the code is robust and analyzed by a security aware programmer, you can think of making a little bit more accessible.

Written by Wadih M.

Accepted Answer

A few things. Take a backup first. Write to a temporary file next. Then validate that file (re-read it to make sure it's syntatically valid, and means what you think it does). Only then, MOVE (mv or rename()) the file over the top of the original. That way, you can never get stuck in a position where another process tries to read while you're still writing, or a write failure causes a syntax error, etc...

Edit:

There are a few things that you can do for the escalated permissions.

One would be to write a script (shell) to validate the file and do the move. You can then setuid that file. So then, you write the temporary file using PHP, validate it in PHP (after all, you can never validate too much). Then call the script to move the temporary file into position (with the escalated privileges).

Another would be to add an account with permission to write to those files only (either via sudo or normally). Then, use PHP to su newuser -c "mv tmpfile finalfile". You'd have to bang out authentication, but it's better than running PHP as escilated...

The other option, would be to use the SSH extension to ssh back into the box (using a private key), upload the file and copy it to the final destination.

But either way you do it, if PHP is hacked, they have access to those files since PHP has a way to...

Written by ircmaxell
This page was build to provide you fast access to the question and the direct accepted answer.
The content is written by members of the stackoverflow.com community.
It is licensed under cc-wiki