Linux users and groups for a LAMP server - php

What is the best practice for setting up a LAMP server in terms of linux users and groups? If there are multiple sites hosted on the same server, is it best to have a single user that owns all site source files (and uploads) that is in the same group as apache - or to have a different user for each site (so that each site has its own crontab)? Or something else entirely?
For some reason, this question never seems to be addressed in PHP/MySQL/Linux books that I've encountered.

On our platform each site's htdocs etc has it's own user. This means if one site is compromised, the others should be fine.

If this is a small number of large sites, you may find that splitting your server into multiple VMs using something like Xen is a better option than simply segregating by user. This will improve the isolation of your sites, and make it easier to move a site to its own hardware if, in future, one starts to become much heavier on resource usage than the others.

I assume you don't want to go crazy and get WHM for cPanel and may want to do this inexpesnively.
I think its a best practice to have each user access their space from their own username and group - especially if unrelated users may be using the webserver.
If you have over 10 domains and users and want to keep accounts segregated to their own space, I would consider using Webmin with VirtualMin installed on the server. This easily handles these type of issues, within a nice, free install. Otherwise, you'll have to purchase a commercial product or handle everything manually - a real pain, but it can be done (not recommended for a commercial venture).
Also, Xen and VMS might be overkill, but also not as easy to manage as Webmin/VirtualMin for 10-100+ accounts.

The best choice is create VirtualHost for each domain using Apache with suPHP module. By this way, each site will be owned by an user and run with that user's permission. Webroot of each site should be put under user's homedir to prevent local attack.
If you use the same user for every websites, that means user from websiteA can access read/write to files of websiteB.

I did some kind of small level hosting over several years and my answer is "It depends".
First of all there is a difference between Apache Module (mod_php). CGI and FastCGI.
A good list with all the pros and cons could be found here:
Apache php modes
When it comes to security all of the modes have pros and cons.
Since we only hosted a relatively small amount of Domains with moderate traffic I decided to stay with mod_php and used vhost configuration.
I also used different FTP users for each vhost root dir (of course).
Configuring vhosts (one per customer) allows you to switch off domains the easy way without digging your way through a ridiculously big httpd.conf and producing errors on the way.

Related

Any PHP framework to use SECURELY on shared hosting?

Are there PHP frameworks that would allow me to generate an application and then use it SECURELY on a shared hosting, as far as a shared hosting security can be achieved? By this I mean, for example, not requiring any app/tmp directory with 777 access.
Not Symfony -> http://trac.symfony-project.org/wiki/SharedHostingNotSecure
Not CakePHP -> http://book.cakephp.org/view/911/Permissions
CodeIgniter -> "If you're a developer who lives in the real world of shared hosting accounts and clients with deadlines..." - looks promising, maybe this one? But I couldn't find anything specific to shared hosting file permissions in the documentation
Maybe ZendFramework? (I am not sure if it is the same category as PHP framework, looks like)
Any existing possible frameworks to use SECURELY on shared hosting??
Having to declare directories with 777 permissions is only a problem on cheapo and entry-level shared hosting systems. It's common to see the safe_mode hack and openbasedir restrictions in that area, which only prevent access via PHP but not other CGI interpreters.
Contemporary server setups use suexec/suphp, where every PHP scripts runs under the current accounts permissions. Therefore you don't need any world-write directories and most PHP application should be secure against cross-account tampering at least. The framework itself doesn't make a difference here.
You're looking at the right problem from the wrong point of view.
Having a directory with the rights 777 is not unsecure per se.
Having a 777'ed directory on a shared hosting is unsecure, because the http daemon is run for all clients under the same system account.
It is an intrinsic "feature" of shared hosting, that's why it's the cheapest. Yep, it's not cheap for nothing, it's cheap at the price of security.
If security is that important to you, buy a VPS. Nowadays VPSes are cheap enough.
I suggest Zend Framework. Doesn't require any file permissions as far as I know. Just needs some proper configuration. And yes, it is a PHP Framework. My entire library is under root owner, with read permissions for everyone and it works fine. Never needed to chmod anything. When it comes to libraries you can always define your own tmp path if it's needed by the class.
Most successful attacks happen because the user/admin sticks with the defaults; which are well-known. See Windows attacks. It's unbelievable how many "administrators" keep not only default URLs, default directory structures but also User IDs and passwords. On my website I see repeatedly some log in attempts at /wp-login.php with ID:PW as admin:admin. I don't even know if these are some defaults and my website is not even WP but it seems to be and I think those hackers will get lucky every once in a while.
Security I believe is always about raising the bar, make it more difficult. There is never a 100% guarantee of security. I think you can choose whatever framework or application but it is your job to make it more difficult by changing the defaults.
I can only speak for ZF and you can do some freaky configuration nobody will ever guess; unless your application has occasional errors and you show your error messages with full information.

Best methods to clean up a hacked site with no clean version available?

I have been asked to fix a hacked site that was built using osCommerce on a production server.
The site has always existed on the remote host. There is no offline clean version. Let's forget how stupid this is for a moment and deal with what it is.
It has been hacked multiple times and another person fixed it by removing the web shell files/upload scripts.
It is continually hacked often.
What can I do?
Because you cannot trust anything on the web host (it might have had a rootkit installed), the safest approach is to rebuild a new web server from scratch; don't forget to update all the external-facing software before bringing it online. Do all the updating on the happy side of a draconian firewall.
When you rebuild the system, be sure to pay special attention to proper configuration. If the web content is owned by a different Unix user than the web server's userid and the permissions on the files are set to forbid writing, then the web server cannot modify the program files.
Configure your web server's Unix user account so it has write access to only its log files and database sockets, if they are in the filesystem. A hacked web server could still serve hacked pages to clients, but a restart would 'undo' the 'live hack'. Of course, your database contents could be sent to the Yakuza or corrupted by people who think your data should include pictures of unicorns. The Principle of Least Privilege will be a good guideline -- what, exactly, does your web server need to access in order to do its job? Grant only that.
Also consider deploying a mandatory access control system such as AppArmor, SELinux, TOMOYO, or SMACK. Any of these systems, properly configured, can control the scope of what can be damaged or leaked when a system is hacked. (I've worked on AppArmor for ten years, and I'm confident most system administrators can learn how to deploy a workable security policy on their systems in a day or two of study. No tool is applicable to all situations, so be sure to read about all of your choices.)
The second time around, be sure to keep your configuration managed through tools such as as puppet, chef, or at the very least in a revision control system.
Update
Something else, a little unrelated to coming back online, but potentially educational all the same: save the hard drive from the compromised system, so you can mount it and inspect its contents from another system. Maybe there's something that can be learned by doing forensics on the compromised data: you might find that the compromise happened months earlier and had been stealing passwords or ssh keys. You might find a rootkit or further exploit tools. You might find information to show the source of the attack -- perhaps the admin of that site doesn't yet realize they've been hacked.
Be careful when inspecting hacked data -- that .jpg you don't recognize might very well be the exploit that cracked the system in the first place, and viewing it on a 'known good' system might crack it, too. Do the work with a hard drive you can format when you're done. (Virtualized or with a mandatory access control system might be sufficient to confine "passive" data-based hacks, but there's nothing quite like throwaway systems for peace of mind.)
Obtain a fresh copy of the osCommerce version the site was built with, and do a diff between the new fresh osCommerce and the hacked site. Also check for files which exist on the server but not in the osCommerce package.
By manually comparing the differences, you can track down all possible places the hack may have created or modified scripts.
I know this is a little late in the day to be offering this solution but the official fix from osCommerce developement is here:
http://library.oscommerce.com/confluence/display/OSCOM23/(A)+(SEC)+Administration+Tool+Log-In+Update
Once those code changes are applied then most of the actual work is in cleaning up the website. The admin login bypass exploit will be the cause that has allowed attackers to upload files via the file manager (usually) into directories that are writable, often the images directory.
There are other files that are often writable too which can have malicious code appended in them. cookie_usage.php and includes/languages/english/cookie_usage.php are the usual files that are affected, however on some server configurations, all site files can be susceptible.
Even though the official osCommerce fix is linked to above, I would also suggest to make this change as well: In the page above, scroll down till you see the link that says "Update PHP_SELF Value". Make those changes as well.
This will correct the way $PHP_SELF reports and prevent attackers from using malformed URLs in attempts to bypass the admin login.
I also suggest that you add htaccess basic authentication login to the admin directory.
Also check out an addon I authored called osC_Sec which is an all in one security fix, which while works on most php backed websystems, it is specifically designed to deal to the issues that exist in the older versions of osCommerce.
http://addons.oscommerce.com/info/8283

Building a 'multi-site' application

I'm planning an application that allow users to create a specific type of website. I wanted to link account names to 'account.myapp.com'. Going to 'account.myapp.com' will serve up a website. I haven't a clue on how to map this. I'll be using Code Igniter as my development tool.
I would like to give users the ability to add a registered domain name for their website, rather than use the standard sub domain. Any tips/methods on this?
Also, what are some pitfalls and problems I should be looking for when developing something with this design? My biggest concern is backing myself in a corner with bad database design, and creating a nightmare of an app to maintain or update.
Thanks for your time!
Your plan for having a single app that serves all the sites is going to be quite an undertaking and a lot of work. That is not to say it isn't possible (plenty of enterprise CMS's, including Sharepoint, allow you to run 'virtual sites' etc. from a single install).
You are going to need to undertake a lot of planning and design, specifically on the security front, to make sure the individual sites operate in isolation. I assume that each site will have its own account(s) - you are going to have to do a lot of work to make sure users can't accidentally (or malicously) start editing another site.
And you are right to consider maintanence - if you have all the sites running under a single application, and therefore a single database, that database is going to get big and messy, very quickly. It also then becomes a single point of failure.
A better plan would be to develop a self-contained solution (for a single website) - this can then run from it's own directory, with it's own database with it's own set of accounts. It would be significantly smaller (in terms of both code and database) and therefore probably perform a lot better. Day-to-Day maintanence would be easier (restore a website from backup), but software updates (to add a new feature) would be a bit trickier, though as it's PHP it's just file uploads and SQL patches, therefore you can automate this with ease.
In terms of domains: if you went with the invidual app (one per website) approach, you can use Apache's Dynamic Virtual Hosts feature, which effectively maps a URL to the filesystem, (so website.mydomain.com could be translated to automatically be severed from /home/vhosts/com/mydomain/website): thus deploying a new website would be a matter of simply copying the files into the correct directory, creating the database, and updating a config file, all of which could be automated with ease.
If users want to use their own URL's then they have to firstly update their DNS to point to your server and secondly you would need to configure an Apache vhost for that domain, which would probably involve a restart of apache and thus affect all other users.
This is very easy to do in codeigniter and can be complete done using routes.php, and a pre-controller hook.
THAT BEING SAID... Don't do this. It's generally not a good idea. Even 37Signals, who made this sort of account management famous is recanting, and moving towards centralized accounts. Check http://37signals.com/accounts
If I'm understanding your question correctly, you need to setup wildcard DNS, and use Apache mod_rewrite to internally redirect (example) myaccount.myapp.com to myapp.com/?account=myaccount. You app logic can take it from there.
I just Googled, "wildcard dns mod_rewrite account" (without quotes) and found some examples with instructions, such as:
http://www.reconn.us/content/view/46/67/
This is a valid and desirable way to structure certain web apps IMO. I'm not aware of serious drawbacks.
I don't really know of a great (automated/scalable) way to allow the users to specify their own individual domain names but you might be able to do it if you had them modify their domain's DNS to point to your web server, then added a ServerAlias directive to your "myapp" Apache configuration. You're still left with the problem of your myapp runtime instance understanding that requests coming through a customer's domain are specific to a customer account. So (example) customeraccount.com really equates to myapp.com/?account=customeraccount. Some more mod_rewrite rules could probably take care of this, but it's not automated (perhaps it could be though with an include file or such).
Sorry, you said you were using CodeIgniter ... substitute in then myapp.com/account/myaccount where I wrote myapp.com/?account=myaccount.
First, you have to setup your Apache (or whatever webserver you're using) to give every subdomain the same DNS settings (wildcard match). Then, you have to use CodeIgniter's routing features to parse the subdomain from the request URL, set that as param (or whatever that's called in CodeIgniter) and have some fun with it in your controller.
About pitfalls and problems: that depends on what you want to do. ;)

UNIX wrapper in PHP

For a simple web application, I'd like to be able to take advantage of several UNIX features that are stable, have a long history, and are well proven in production, rather than having to write my own code. Take users, for example. Rather than having an entire user, group, permission infrastructure in my webapp, I'd like to be able to simply piggyback on top of the equivalent features of UNIX.
Is there a PHP library that will allow me to register users, log them in, manage permissions, etc. ?
It's really not a good idea to fumble around with the user and permission settings of the actual system that is hosting your site. If you want to protect individual directories of your site, you're better off using .htaccess files. If OTOH you're working with virtual URLs, you'll have a hard time mapping the UNIX directory permissions to them anyway.
Based on your comment to deceze's answer, are you looking for something like PHP's filesystem functions?
Then, there is system and its related functions, which gives access to Unix commands, but I'd recommend other ways of doing things if possible.
Edit: In response to the comments about needing user and group functionality:
Firstly, in case your plan is to let web users have access to the whole file system (or even just their regular log in directories), I just want to advise against that - lots of security concerns (eg. if someone else gets into a user's account, they could delete everything to which they have access).
The little experience I have with handling users in PHP was in some beginner level training. In that class, we had our users in an SQL database and used sessions. We didn't use SSL, but I'd advise some sort of crypto when passing passwords around.
If you're using Apache, it can handle the authentication for you. Other server software can probably do the same, but Apache is all I've ever worked with. I can't address whether Apache can handle sessions itself and don't have the time to research it right now.
If php or your webserver is running with root rights it should be no problem to use this functions.
For security reasons I would strongly recommend to reimplement these things or using any existing php library instead!!
It seems there are standard functions for interfacing with Kerberos or Radius in php.
These both have a long history and are well proven in production, while being separate from the system users.

Virus code injected in PHP Files

I own a website running on LAMP - Linux, Apache, mySQL and PHP. In the past 2-3 weeks the PHP and jQuery files on my website have become infected from malware from a site called gumblar.cn
I can't understand how does this malware get into my PHP files and how do I prevent it from happening again and again.
Any ideas?
UPDATE:
Looks like it is a cpanel exploit
Your site is cracked, so the crackers simply replace your files.
You should always upgrade your Linux OS, Apache, MySQL, PHP, and the web PHP programs whenever a security alert is announced.
Linux servers running open services without upgrading them regularly are the most vulnerable boxes on internet.
No one here can provide a conclusive solution based on the information you provided, so all we can suggest is that you follow good security practices and standards and correct any weak points immediately.
Make sure your software is up-to-date. It's very possible to gain access to local files through exploits in PHP programs, so keep any third-party applications you're running on their latest versions (especially very widespread programs like Wordpress and phpBB), and do whatever you can to ensure that your server is running the correct versions of its services (PHP, Apache, etc.).
Use strong passwords. A strong password is a long, random list of characters. It should have nothing to do with your life, it should have no readily available acronyms or mnemonics, it should not resemble a dictionary word, and it should contain a healthy interspersing of different characters; numbers, letters of different cases, and symbols. It should also be reasonably long, ideally more than 26 characters. This should help keep people from bruteforcing your credentials for enough time for competent sysadmins to take action against the attackers.
Work with the administrators at your hosting provider to understand what happened in this particular case and do things to correct it. They may not have noticed anything unusual; for instance, if you have an easy password, or if this attack was perpetrated by a trusted individual, or if you have an unpatched exploit in a custom PHP application, there would be nothing to indicate an improper use.
Shared hosts also have many people with access to the same local machine, so things like file permissions and patching of locally-accessible exploits both within your application and generally is very important. Make sure your host has good policies on this and make sure that none of your software unequivocally trusts local connections or users.
The nature of the attack (an import of malware from a site that appears to do this kind of thing en masse) suggests that you were running an exploitable application or that your username/password combination was not sufficiently strong, but the administrators at your provider are really the only ones able to supply accurate details on how this happened. Good luck. :)
Chances are, there is an application on your server with a known vulnerability that has been attacked, and something has modified files on your web site or installed a new file.
When searching for information on gumblar.cn, it looks like they use a trojan called JS-Redirector-H. Not sure if this is what is involved here.
Fixing this may involve restoring your web site from backup, if you have no way of knowing what has been modified. If you have source control or a recent version, you may be able to do a whole-site diff. But you will also need to fix the security vulnerability that allowed this to happen in the first place.
Chances are it's some insecure app, or an app you installed some time ago but have not updated recently. A few people who have complained about this mentioned that they use Gallery (ie PHP Gallery). Though I'm not sure if that's connected.
If you are not the server administrator, talk to the server admin. They may be able to help, and it would be wise to let them know about this.
Google Advisory:
http://safebrowsing.clients.google.com/safebrowsing/diagnostic?client=Firefox&hl=en-US&site=http://gumblar.cn (linking doesn't work)
First, contact your hosting company and report this. If this is server-wide, they need to know about it.
The most common cause of infections like this is vulnerable popular PHP software (such as PHPBB, Mamboserver and other popular systems). If you're running any 3rd party PHP code, make sure you have the latest version.
If you've determined that this only affects your site, restore from a backup. If you don't have any backups, try re-installing everything (you can probably migrate the database) you have (to the latest version) and go through your own PHP code (if any).
PHP Programs are actually simple text files that run on the server by the PHP interpreter. if your application is infected, then I think there are tow posiibilities:
1.they have used some security hole in YOUR application to inject some code into your server, so now they have changed some of your PHP files, or some of your database information.
if this is the case, you better double check every single place where you are fetching information from the user (text inputs, file uploads, cookie values, ...), make sure everything is well filtered. this is very common security practice to filter anything that comes from the user. you also better make sure that the data that is currently saved in your database (or file system) is clean. I suggest using Zend_Filter component of the Zend Framework to filter user input. there are many full featured filter libraries out there.
2.they could have run some program on your server, that is affecting your PHP source files. so somehow they have accomplished running some program/script your server, that is changing your application.
if this is the case, I suggest your check all your server processes and make sure you know every process that is running. although I think this is less possible.
Ok, this is NOT a programming question and SO is not the place for this because if we would tolerate such questions here we would soon be a first aid / support site for ppl with bad shared hosting accounts.
I only didn't vote for closing because I feel bad turning a few ppl down who are probably feeling really bad about a problem they don't have the knowledge to fix.
First of all: google for gumblar.cn, there is a growing number of potentialy helpful posts accumulating as we speak.
If you're a real beginner and you feel you don't get any of the things in the answers here then just do the following:
Get a new host
Google for information about all your software until you know, if the software is safe. If it's not, don't use it, until the developers have fixed the problem. An example of a not secure software is 'Galery'.
Install all your software (the secure ones only) FRESH INSTALL!!
Copy over static files (like images) to the new server. Do NOT copy over any dynamic files, like php scripts, as they could be infected.
Don't upload any of your own PHP scripts until you've checked them for security vulnerabilities. If you don't know how to do this, don't upload anything before you've learned about these things.
I have been affected by this virus/malware and currently cleaning up. I hope this will be helpful:
1) You most likely have a TROJAN on your PC. To verify this simply run (Start > Run... or Windows key + R) and type "cmd" or "regedit". If either of those doesnt open its window as expected, you have the Js:Redirector trojan. You can also verify that the anti virus programs aVast and Malware Bytes can not connect to updates for some reason (sneaky trojan that is). Plus, you'll notice that the Security program of the Control Panel was disabled, you wouldn't have seen a notification in the tray icons to tell you that the virus protection was disabled.
2) This is a very recent exploit, apparently of vulnerabilities inflash or pdf plugins, thus you are not safe even if you didn't use Internet Explorer!
As for me, I believe because I hate programs slowing down my PC, I have my Windows Updates on "manual", and I didn't have resident protection (scanning of all web connections, etc), and I was probably infected by visiting another hacked site which was not blacklisted yet. Also I was over confident in non-IE browsers! I sometimes ignore the blacklist warning as I am curious about what the scripts do etc, and forgot once again just how BAD Windows really is. Conclusion: leave Windows Updates on automatic, have minimal resident protection (aVast Web Shield + Network Shield).
3) Because this is a trojan that sends back your FTP password, it doesn't matter how good your password was!
4) Try to lceanup your PC with Malware or aVast, it will find a file ending with ".ctv"
You MUST have a virus database dated 14 May or more recent. If you can't update (as explained above), then follow these instructions (you'll need to extrapolate but basically you have a file, the name may vary, which is pointed in the registry, and use HiJackThis to remove it, once you rebout without this file excuted, all is fine)
5) Of course update your passwords, BUT make sure the trojan is removed first!
6) For an exact list of all pages modified try to get a FTP log and you'll find the IP of the script/hacker and all touched files.
7) If you have a complete local copy of the "production" environment, then the safest is to delete ALL the site on the server, and re-upload all files.
8) During the clean up process DONT visit your infected site, or you will re-install the trojan! If you have the latest aVast Home Edition and the "Web Shield" protection it will give you a warning and block the page from being executed by your browser.
like Francis mentioned, try to get your hosting company to make sure their software is up to date.
On your side, change your ftp password to something completely obscure as soon as possible. I've seen this happen to people before. What these 'hackers' do is a brute force on your ftp account, download a couple of files, modify them slightly, and then re-upload the infected copies. If you have access to the ftp log files you'll probably see a connection to your account from an IP other than yours. You may be able to submit this to your hosting company and ask them to black-list that IP from accessing their servers.
That website (gumblar.cn that you mentioned) is being tested for malware. You can monitor results here: http://www.siteadvisor.com/sites/gumblar.cn/postid?p=1659540
I had something like this happen to me at an old hosting provider. Somehow, someone, was able to infect Apache in some way so that a special header was injected into all my PHP files which caused the browser to try to download and run in the browser. While they got it fixed, the quick solution was to take down all my PHP files, and change my index file a plain HTML file. Whether or not this stops the problem for you depends on how the server is infected. The best thing and probably most responsible thing you can do is to protect your visitors by taking down site, and if possible (if text files aren't infected), display a message stating that if they visited recently they may have been infected.
Needless to say, I switched hosting providers quick soon after my site was infected. My hosting provider was pretty bad in a lot of other ways, but this was pretty much the final straw.

Categories