Website Security Without Breaking the Bank?
An anonymous reader writes "I do my own Web design and have a few websites — MySQL, PHP, CSS, HTML, that kind of thing. It's simple, amateur stuff, but I would love to have some reasonable ways to assess their security myself and patch the big holes, or possibly enlist someone to do 'white hat' work to assist me. I have absolutely no idea how to proceed. I don't want to get mired in a never-ending paranoia-fueled race to patch holes before the hackers find them, but on the other hand, I don't want my websites to look like Swiss cheese. Right now, I wouldn't know what kind of cheese they look like: Swiss, Havarti, or hard as Parmesan. How can I take reasonable steps to protect these websites myself? What books has the community found useful? What groups (if any) can offer me inexpensive white-hat hacking that won't end up costing me a first-born child? Or am I better off just waiting until a problem arises and then fixing it?"
What's the URL? ;)
Use the Internet for the last time.
Buy a pony.
You still need to do homework. I realized a while ago that I not only lack a good understanding of potential weaknesses in my sites, but I also lack the knowledge needed to actually do the forensic log analysis if I was to actually get exploited. Along the lines of the original post, what good introductory tools are there that relate to forensic log analysis?
"Proximity to wonder has blunted our perception and appreciation of it" --Tim Hartnell in 'Exploring ARTIFICIAL INTELLI
http://www.owasp.org/index.php/Main_Page
You can write insecure websites using pretty much any tools, but if you're using MySQL and PHP, especially if you're using other peoples code in your app, you're probably going to end up with a security nightmare, regardless of how hard you try.
It's possible to write secure code in PHP, but almost nobody does, and most of the PHP code that you can acquire easily is painfully insecure. A never ending race to patch a never ending series of holes means you've already failed at security. Depending on "white-hat hacking", ditto.
Other than that... security is something integrated process, starting with the architectural design, the implementation and the processes around it, documentation and maintenance. It's not something you can just add on the side.
Books? No idea, but looks for stuff that talks about the entire lifecycle, and that comes from real world experience.
Oh, and learn some real crypto, so you can avoid both the snake oil and the irrational paranoia.
Not only will it have a look at what you've got, but it's a good kick-off point to understand some of the pitfalls.
The Open Web Application Security Project (OWASP) has a Top 10 list, which lists the most serious web application vulnerabilities, discusses how to protect against them, and provides links to more information (http://www.owasp.org/index.php/Category:OWASP_Top_Ten_Project). This might be a good start.
I learned a decent amount from Essential PHP Security*. It doesn't cover everything, but should cover most of the crazy-stupid errors that crop up in a lot of novice php/mysql stuff. Not that the information isn't out there in plenty of places (just like every other topic humanity has ever thought up), but for twenty bucks it's nice to have a hard copy of the essentials in one place.
*Yes, that's a referral link to amazon. But I'd recommend it either way for people getting started with securing their basic LAMP sites.
How are sites slashdotted when nobody reads TFAs?
http://127.0.0.1/
Enjoy.
Insert
It doesn't matter what you do after the fact to secure your web sites, if your scripting is full of holes, trying to plug them up after the fact isn't going to work. For example, you mention MySQL so I gather your code accesses one or more databases? If so do you know what a SQL injection bug is and have you reviewed your code for them? Nothing you do at the point of deployment is going to help fix a SQL injection bug.
I'm afraid that if you're using MySQL and PHP you've moved from the realm of the very basic to something more advanced. You're no longer just talking about slapping static content on the web. People spend years learning how to do these things really well. You should find yourself a good book and get started. Start with a Google. It costs nothing. If you have friends who do web development with similar tools talk to them and see if they'll help point you in the right direction.
Here are some things to get you started. Note that these are language independent things you should do no matter what dev tools you use. You might want to look at something more targetted for PHP as well.
https://www.securecoding.cert.org/confluence/display/seccode/Top+10+Secure+Coding+Practices
Here's the main site.
https://www.securecoding.cert.org/confluence/display/seccode/CERT+Secure+Coding+Standards
The other way to go would be to make your web files more static. However getting rid of everything dynamic may not be a reasonable option in 2009.
These posts express my own personal views, not those of my employer
Here's a good read with a checklist of things to do to secure your website from page 80
http://www.ipa.go.jp/security/vuln/documents/website_security_en.pdf
It's quite easy to understand and if you follow all the recommendations your website should be more secure than average.
I recommend mod_security and mod_evasive. A reverse proxy would help as well. The DoD and NSA have configuration guides that provide tips on securing Apache (as well as IIS).
Either you spend the time to teach yourself about security.
Or you pay someone to do it for you.
Parmesean actually crumbles really easily. I don't think any type of cheese is really tough enough to protect your server lol. Maybe gouda cuz that's some tough, thick stuff but other than that, I'd suggest dousing a wall in gasoline and lighting it up. That would of course be a firewall lol.
Google's Super Secret Search Algorithm: SELECT @search_results FROM internet WHERE @search_results = 'good'
Keep you MySQL only accessible via localhost, put a good password on it's root account, and make separate users for each database with access restricted to each one. I know it's important. Other than that, if you close ports you don't need , keep your software up to date, and write your own PHP I really don't think you have much too worry about.
but you asked about our applications, not your server setup. So my answer presumes that you are in a hosted environment and are trusting to your host to handle that end.
In that case, the biggest exploits that you are probably easily vulnerable to are SQL injection and JavaScript injection. I highly recommend that you research those two things, they will go a long way toward securing your website.
The Kaspersky anti-virus website fell victim to SQL injection just yesterday... but it is an easy thing to prevent with a little knowledge and diligence.
should help some
It's possible to write secure code in PHP, but almost nobody does, and most of the PHP code that you can acquire easily is painfully insecure.
Writing secure code with PHP is no more harder than with Perl/Java/Ruby... same rules apply. I would even say nowadays it's extremely easy - use PDO with prepared queries, and you've pretty much eliminated SQL injections. Don't reinvent the wheel - for example Zend Framework is pretty cabable and done most of the work for you which you'd probably end up doing.
In a nutshell:
Validate your goddamned data. Use prepared queries to prevent SQL injections. And so on. The language used itself has very, very little to do with security in the end.
This video is a couple years old, but an interesting overview (Mike Andrews presenting at Google) http://www.youtube.com/watch?v=ZgW2B2gKZVw I'm sure OWASP has some decent info for you as well: http://www.owasp.org/index.php/Main_Page Good luck :)
I farted
- very very imho -
backups don't help your users who might be attacked by your compromised sites but the ability to wipe the bad and restart is great. requires multiple levels of backups, daily, weekly, monthly, all separate.
You can't restart immediately, presumably you'll get nailed by the same exploit when you recover, but at least you'll know there's a specific problem - finding something specific is nearly always easier than finding something general.
also, control your URLs. controlling what can be passed to your site controls a hell of a lot of security problems.
lastly - make sure your logs are good and safe and verbose. if you pay attention to making the logs right, when you have a problem, you can find someone to review the logs and find the issue. if you don't have the logs, well. you're more screwed.
Do those three things and some common sense when coding and you'll be better off than most. Security is always where you draw the line, personally I like it a bit ahead of the curve but no where near perfect.
closed minded is as closed minded does
There are some good automated security scanners out there. For instance: Nesses/Nikto, WebScarab with proxmon, portswigger, and you can even go as far as using 3rd party companies such as HackerSafe.com or SecurityMetrics.com. Even though this doesn't give you a 100% fail-safe security scenario (*cough* nothing does and probably never will), it at least helps decrease the chances of common and even some more uncommon attacks such as SQL injections, overflows, man-in-the-middle attacks, etc.
You also obviously have to write secure code and keep all of your software up to date (especially open source software). This is not only true for PHP, but for all programming languages.
You should also try using BSD since you have a LAMP system.
Some other good sources of information:
http://www.webappsec.org/
http://www.owasp.org/
Hope this helps...
I'd do the following. Put your code in Subversion or some other version control system. Find someone (maybe in your environment, maybe on Elance) who does this sort of stuff for a living.
Pay him to check out the code of your sites and your databases. Let him save his changes in your version control system, then go look for yourself to see what he changed. Reserve an extra hour of face or phone time with the guy to walk through all changes.
8 of 13 people found this answer helpful. Did you?
There are some good automated security scanners out there. For instance: Nesses/Nikto, WebScarab with proxmon, portswigger, and you can even go as far as using 3rd party companies such as HackerSafe.com or SecurityMetrics.com. Even though this doesn't give you a 100% fail-safe security scenario (*cough* nothing does and probably never will), it at least helps decrease the chances of common and even some more uncommon attacks such as SQL injections, overflows, man-in-the-middle attacks, etc. You also obviously have to write secure code and keep all of your software up to date (especially open source software). This is not only true for PHP, but for all programming languages. You should also try using BSD since you have a LAMP system. Some other good sources of information: http://www.webappsec.org/ http://www.owasp.org/ Hope this helps...
If you can prevent SQL injection attacks, you're already one step ahead of the "experts" at Kaspersky :o)
Change all of your database access code to use parameterised queries (which in your case means MySQLi) and you've eliminated one of the major points of attack.
First and foremost, check and sanitize EVERY input passed via a $_POST or $_GET (and to be safe, check cookie inputs too).
Make SURE that none of them are in a format or contain data that you don't expect.
It is easier said than done, and it sucks major ass to do, but it's really the only way to be sure of what you are doing.
I just spent most of the last week tracking down an XSS exploit for a client, and it was a mother to find where to filter the input AND what to look for. SOME inputs needed SOME HTML tags to pass through, others required binary data, and still others needed integers.
My advice on new code is to check your inputs like crazy before assigning any submitted data to a variable. Then check the variables themselves.
Watch for hex encodings of HTML characters, and then watch for it again.
Then, after all that work, hope it works, then drink heavily.
...and outsource the whole thing to some host. There are very cheap deals with great bandwidth and speed that take only little time. I used to put CMS myself onto root servers... then VPS and it was too much work and nobody cared.
Security, massive capabilities and you can install free modules like chat rooms, blogs, calendars. You can also up/download files and display picture/video galleries.
If you want to sell stuff, it works as E-commerce too.
There is so much and it is so versatile, I have not run across anything I can't do yet.
Kaspersky
How is PHP/MySQL so insecure? I write asp.net for a living (I'd rather write in python or C, but such is life), and I find it hard to imagine where these pages are so vulnerable. Is PHP vulnerable to buffer overflows the way old C code is? Does MySQL not support parameterized queries? If that's not the case, then what kind of attacks are people using to hack these sites?
I just got back from a PHP security class, here's a quick overview of what was covered:
- register_globals = off
- Use the Suhosin PHP hardening patch.
- Always filter all of your input for injection attempts. Write a validation class to handle this.
- Use prepared SQL statements, or stored procedures to help avoid sql injections
There are some pretty good articles out there that cover most of these points and more, just google for "PHP security". Take the time to read the articles, they're worth it.
It's really sad that more people don't pay attention to PHP security. The class I took was, as far as I know, the only commercial PHP security class offered in the US this year, and there were only 4 students in attendance.
This should be relevant to my interests. I too want the URL.
SQL injection: Use prepared statements. Always. Period. Do not EVER interpolate or concatenate user input into a query. SQL injection was pretty much solved years ago and it's an embarrassment that sites still fall prey to it. With PHP, this requires mysqli.
Javascript injection/XSS: Find a template language that escapes BY DEFAULT and only prints raw HTML if you explicitly ask for it. You're on your own there; I'm not familiar enough with the PHP ecosystem to name one.
The usual PHP advice is "well, just wrap your input in these three functions every time you use it." That's just begging to forget it a few times, which leads to a few holes you are unlikely to notice. Security should be a default; it should not require constant extra work on your end.
If you cover those two and make sure you keep all your software patched, you will already be well ahead of the curve.
exactly right.
Honestly, if the OP is in the situation where he is trying to find and patch holes, it would probably be a better idea to do a little homework and start the project over again and use good security techniques when writing.
It is not that hard, really. You just have to remember never to trust user input. That means that you filter all of it, you don't rely on cookies for access control, and you don't trust the variables that the browser sent you (such as $_SESSION['http_referer']).
As far as filtering is concerned, remember that php has a lot of filters at your disposal (just remember to strip new lines out of email addresses yourself, the filter misses that one). Another word of warning: if you are echoing user input out onto a page, it is much easier to use bb syntax than allow html tags through strip tags: the danger is that an attacker can get javascript attributes the filter and it is better just to avoid it.
weirdest thing I ever saw: scientology advertising on slashdot.
Ensure your users pick good passwords, by preventing them from entering passwords described here (e.g. their firstname, "password", "qwerty", etc).
Slartibartfast:"Is that your robot?"
Marvin:"No, I'm mine."
Anyone else hungry after reading this article?
Agreed with everything you said. You could write your own classes to turn PHP into acting strongly typed, then sanitize your data after it's been type checked, but that might be beyond the scope of this project. Save yourself some hassle and read this too: http://devzone.zend.com/node/view/id/168 It will help validating those inputs.
I'm not suggesting this is rock-solid security. It's a few easy steps that keeps most of the knuckleheads at bay.
Seth
$5 / month hosted VPS on linux = awesome!
You can write insecure websites using pretty much any tools, but if you're using MySQL and PHP, especially if you're using other peoples code in your app, you're probably going to end up with a security nightmare, regardless of how hard you try.
Taken to the extreme you could prepare you own active page servlet using FORTRAN and obfuscate the binaries, randomize query url generation, and run everything on your server through a microkernel operating system where you change all of the system calls and commands to things only you know.
Then operate your website entirely anonymously with tenneling through tor between your actual webserver and the server putting up your domain.
http://www.aaronrogier.net
I have an idea! Let's rename this site to cluelessitadminswhocannotfigureoutshitontheirown.com
Real IT admins do not publicly ask for help, they use the infinite power of the intertubes and find the answers on their own.
Lesson #2 will cover the many reasons why you should not include your real first/last name in your username, for example kdawson. Stay tuned for an exciting preview!
Especially since you seem to want to patch holes when you find them instead of designing your code with security in mind. If you do not learn about security and secure programming, you will run into problems again and again. Even the "best" outside help will not be able to completely overhaul your insecure system if you regard security as something to be "patched in" instead of something to be designed for.
If you are going to wait for your sites to be compromised to figure out if anything went wrong (and let's face it, if you did not pay attention to security until now, it will), you better be sure not to be handling any sensitive information (such as ANY personal information of other people, email addresses, payment records, etc.), have very good backups, and have a way to spot whether you have been compromised (contrary to popular opinion, "hackers" don't usually/always deface your website or send you threatening emails or the like; ask yourself whether you would know that somebody is abusing your servers if that did not happen ... But that would also require security-aware programming).
You can write insecure websites using pretty much any tools, but if you're using MySQL and PHP, especially if you're using other peoples code in your app, you're probably going to end up with a security nightmare, regardless of how hard you try.
That's the problem.
Most of the pros on here can write good-quality, secure code, in PHP, RoR, whatever.
It's the external libraries which are the gap. For example, look at phplist, which is used in many places. Now, every installation of it needs to be upgraded. Now. Right now.
Unless you're a 100% fulltime sysadmin, you haven't got the time to be reading the security lists hourly and upgrading phplist etc when required.
The OP is really asking: how do I make sure phplist and the other hundred Ruby gems or PHP add-ins are up-to-date and safe? And keep them that way?
http://blog.grcm.net/
http://xkcd.com/327/
Apart from speeding the recovery in case of a breaking/defacement it will also assist you if your hosting service goes bust, stops serving or you find someone else who's better / cheaper / has more facilities.
I'm not saying you shouldn't apply sensible security precautions, but don't treat them as if they'll make your sites impregnable. The ability to quickly restore a site means you don't have to go around checking each link on every page to see if it's been messed with.
politicians are like babies' nappies: they should both be changed regularly and for the same reasons
http://www.addedbytes.com/php/writing-secure-php/ is a useful four-part guide to the basics of writing secure PHP. I found it to be a very helpful read.
Just a few things that pop into mind... (a) I second one of the above posters - try to move more content into the "static" section. This should be just a basic design principle of the site. For example: is there content that doesn't refresh more often than each 5 minutes? If so, don't let a PHP page pull it out of MySQL; instead, write a stand-alone PHP or Perl script that accesses the database and pre-cooks an HTML page. I'm often surprised how many sites build dynamic content using a CMS (or ~like) approach while this is totally unnecessary and bad for performance too. (b) On the database access layer: of course stored procedures and prepared SQL statements. (c) In general, when e.g. validating user input, or remote IP addresses, or just about anything: Use whitelists, never blacklists - meaning: have a set of allowed inputs which are accepted, and all else is denied (instead of the other way 'round). Test extensively for e.g. Javascript injection in input fields. (d) On PHP coding: Try to abstract all operations into layers / classes. It will save you tons of headaches later. Never "take a shortcut" in coding, by which I mean that you do the quick 'n' dirty thing because "this code will only be used on this page" or "this code will be here just for testing". Quick 'n' dirty code tends to boomerang back to you. (e) During coding, prepare your regression tests, which are preferably automatically run every time you update the site. Regression tests can e.g. include a fancy PHP class and call its methods, and compare the outcome with what the test expects. Always have regression tests for the "good" outcome (no errors) AND for the error conditions that your class should be able to handle. Here too, never take the quick 'n' dirty approach by postponing the writing of tests until you have more time. (f) Whichever technology you choose, follow the forums or mailing lists about that technology. There will be security-related posts or questions that may apply to your site. (g) Strip data that you don't need. For example: Maybe your site stores your visitor's IP addresses so you can cave trolls. Good practice, but the address will probably be only valid for a week or so. Ergo.. delete IP addresses that are older than a week. In the unfortunate case of a database disclosure there will be simply less exposed data. In a similar vein, try not to store plain text data at all. If your site stores something like the answer to a secret question ("what is your pet's name"), then store a hashed value of the answer instead of the plaintext version. Again, in the case of exposure, there will be less data. (h) Take a look at frameworks that protect from e.g. cross site request forgery. If you don't find anything useful, consider coding your own protection against CSRF (by having a hidden form field in each form with a random value, and by having the same value in the user's session. Upon submission of the form, the two values must match. (i) Other than the above I'm sure that there is a ton of good advice.. It's a bit of a lengthy post but I hope that it provides you with a few valid pointers.
The banks are already broken. Too late.
== Jez ==
Do you miss Firefox? Try Pale Moon.
Seconded. Doing MySQL/PHP websites is indeed easy, but doing them secure is where the real challenge is. Without any knowledge of common flaws, your current architecture is probably already unpatchable and would require a rewrite to secure. I may be overly pessimistic but there are so many ways to botch it when you don't know much that it would a miracle that you don't rely on a flawed feature.
The Wise adapts himself to the world. The Fool adapts the world to himself. Therefore, all progress depends on the Fool.
I know Java has a lot of different security frameworks like JSecurity or AcegiSecurity, but I'm not so sure about PHP.
Buy everyone on /. a pony
I could do with the extra protein.
Finally had enough. Come see us over at https://soylentnews.org/
http://cwe.mitre.org/top25/
Use a secure php config file - see http://www.securityfocus.com/infocus/1706
Briefly:
1) There is an unfortunate yet statistically significant correlation between 'choosing PHP/MySQL' and 'having no clue what you're doing', for historical reasons; basically, loads of "start your own web site today in ten easy steps!!" tutorials are geared toward PHP/MySQL. Horror stories ensue.
2) MySQL per se is not insecure, it's just a pain to keep running well under non-trivial load. (Thankfully most Web sites only see trivial load.) But that's a problem for the sysadmins, not the developers.
3) PHP is, I'm afraid, something of a mess (the core developers are, I am told, notorious for their habit to mimic features from other languages without understanding fully what they entail), which results in an effect where the path of least resistance from 'nothing' to 'job done' goes through stark lack of architecture and horrible shortcuts that routinely lead to gaping holes.
The latter point, I think, is the real problem with PHP. I vehemently question the notion that languages are 'just a tool', as you will commonly hear: they're also teachers, insofar as they reward certain behaviors and discourage others. If it's more work to use certain practices and the end results looks the same outwardly (if your language has a tendency to sweep issues under the carpet, for instance), then guess what habits you'll end up learning.
Now, it is, of course, possible to write good, secure code in PHP -- see what the guys over at the Symfony project are doing for instance. (Many PHP frameworks -- hell, many frameworks of many languages -- are crap of the sort that commonly follows from cargo cults, but this one is actually pretty good.) It's just more work than in languages where the use of good practices is the path of least resistance.
Get your defense budget in balance with the threats. I guess this depends on the kind of content you post to the web. But then again we live in a world where social and bank info is apparently still up for grabs. Why put your money in security if someone else is giving the same info away?
I have read most messages in this thread so far and the only thing I find is vague recommendations but nothing solid.
What we could all benefit from is:
- Specific book titles.
- Specific websites.
- Specific training (go on, if you are providing such training people want to hear from you).
The amount of vaguery posted so far tells me that people with a clue about security may not frequent this site or that simply there is no material out there.
I may have a business plan there somewhere ...
IANAL but write like a drunk one.
one good and strong way is to wrap your apps with client certificates. if you can reasonably trust your users (to not throw 0day exploits at your site with a client certificate) it's a great way to keep the bots, worms, etc off your code. this gives you a bit more flexibility on time line for upgrading your software down the road at a cheaper cost and more quality testing of said upgrades.
Note, however, client certificates are somewhat foreign to 95% of the internet population. whatever cert. management system you use, would have to be mostly transparent to your users.
Some of these have been said, but IMO (and to reiterate):
- Offsite backups = good idea
- If you write your own apps, ensure that you have sufficient validation of ANY code that does or can accept/output user supplied data; don't just limit yourself to forms.
- If you use third party apps, ensure that you keep on top of vendor updates -- this includes OS level patches that could pose a risk to your environment.
- Run a host-based firewall (eg. iptables) on top of any hardware devices you or your provider might have. Only open up what you need; to whom you need, for any given service. If you're overly paranoid, filter outbound traffic also.
- Limit what information you make available about your system/environment to the outside world (ie. no phpinfo() pages, apache set to ServerTokens Prod, etc.)
- Use common sense when administering your environment. (eg. don't use system accounts called 'test' with the password 'P@ssw0rd' when you have SSH/FTP open to the world)
- Encryption is your friend; at rest, or in transport.
- Read as much as you can.
Most web server attacks are going to be because of a flaw in the site code, not the system code.
Use a framework and you can avoid a lot of the problems with ease.
There is an initial learning curve but it will increase your productivity 10-fold and handle a LOT of the boring stuff transparently.
I recommend Symfony.
Learn what each of those are, and then study 3 major applications or frameworks to see how they go about preventing them.
For instance, Drupal, Wordpress, Joomla, CakePHP, CodeIgniter, or the Zend Framework.
I'd say you're own your own in regards to privilege escalation and logic errors with your own code.
Static analysis tools are quite nice to point out the problems that are present in your existing code. I've used Fortify for Java code and was quite pleased with that. Just remember to be wary of false negatives. You need to review the code manually as well, but automated tools help you get started quickly.
If you're on a budget (either time or money), use a framework that handles most of the problems for you. Why reinvent the wheel?
For PHP, there's CodeIgniter, Cake, and some others in the MVC area, and probably some outside. Google is your friend.
Why a framework? Because stuff like escaping your data before handing it to the database (to prevent SQL injection attacks), or sanitizing your input (to prevent XSS and other attacks) and so on are fairly simple things to do, you just have to remember to do them every time, everywhere. That's when you want a function to handle it, or a framework to shove all the stuff off to.
Assorted stuff I do sometimes: Lemuria.org
Even taking the posts that get voted up is dodgy, as people tend to vote up things they agree with rather than replies which are correct, or relevant, or useful. You'd probably be far better taking this questionj to a specialist website / security forum, than posting on a general site like /.
Oh, and if you do go to a specialist site, be specific about exactly what software, versions, platforms etc. you are using, if you want targeted answers.
politicians are like babies' nappies: they should both be changed regularly and for the same reasons
There is no quick fix for computer security.
It takes time to learn about security issues.
It takes time to practice solving each issue.
It takes practice to fight against poorly written code and poorly managed servers.
It takes diligence to ensure your partners and employees don't screw you too. Multi-authenticated processes are probably the best check where no single person has access to the servers, code, database or data.
It takes something I don't have to convince users, accountants and CEOs that they need to take this effort seriously. A reputation burned can never be regained, just ask Monster.com.
Anyone who claims a firewall solves it is wrong.
Anyone who claims server code solves it is wrong.
True security is inconvenient. The trade off is usability.
A starting point: http://www.isc2.org/
You can start here:
https://buildsecurityin.us-cert.gov/daisy/bsi/articles/knowledge/principles/358-BSI.html
And for specifically for web apps:
https://buildsecurityin.us-cert.gov/daisy/bsi/articles/best-practices/assembly/639-BSI.html
Then you frighten yourself by playing with the toys here:
http://insecure.org/
Another useful read (albeit not focused on PHP per-se) is David Wheelers Secure Programming (http://www.dwheeler.com/secure-programs/)
I have a simple guide when I write code, it's not flawless but it covers a lot of bases - every time I load a variable that has anything to do with generated content (i.e. from a user) I sanitise it - I don't report errors, I just strip out invalid characters (as a rule). It's not the best way to do it, but combined with a good site design it helps a lot.
Me failed English...
FreeBSD over Linux. If my comments seem odd, this may explain...
You should probably check out some of the open source static analysis tools:
http://en.wikipedia.org/wiki/List_of_tools_for_static_code_analysis
I wrote one that deals mostly with web applications:
http://www.yasca.org/
You should also get your hands on Acunetix Free Edition, which scans for XSS:
http://www.acunetix.com/cross-site-scripting/scanner.htm
Also grab yourself a copy of Software Security by Gary McGraw and Secure Programming with Static Analyis by Brian Chess and Jacob West.
Finally, if you want to outsource an assessment on the cheap (really), send me an e-mail.
Wer mit Ungeheuern kämpft, mag zusehn, dass er nicht dabei zum Ungeheuer wird. --Nietzsche
In a nutshell: Validate your goddamned data. Use prepared queries to prevent SQL injections. And so on. The language used itself has very, very little to do with security in the end.
Stored procedures are also good ways to avoid injection attacks...
We don't believe in radical loony monotheistic religions from the middle east -- we're Christians.
For example the PCI DSS is a security standard for payment card industries. Their documents go into detail on the specific vulnerabilities that needs to be addressed to be certified. For example they mention specific flaws (say cross-site scripting), and also measures to protect data if an attack succeeds.
This document lists specific flaws that are known to be a problem, and had better be comprehensive since these are the standards banks are measured against. "Comprehensive" is perhaps a gross understatement, but it will give you an idea of the aspects to watch out for.
"the PCI DSS is a security standard for payment card industries. Their documents go into detail on the specific vulnerabilities that needs to be addressed to be certified. For example they mention specific flaws (say cross-site scripting), and also measures to protect data if an attack succeeds"
.. install a firewall, don't use default passwords, encrypt the transmission data, assign a unique ID to each user, restrict physical access to cardholder data, track all access to network resources and ..
.. :)
All the PCI standard does is set down a number of criteria to be PCI certified. In the real world this provides no defense against getting hacked, as Heartland Payment Systems learned to their regret.
"This document lists specific flaws that are known to be a problem, and had better be comprehensive since these are the standards banks are measured against. "Comprehensive" is perhaps a gross understatement, but it will give you an idea of the aspects to watch out for"
If you need this PCI standard to tell you how to secure your network, then perhaps you shouldn't be in the security industry. Lets see what the 'document' has to teach us that we don't already know:
WOW, I would never have thought of that. But how does one go about getting PCI certified, well there is self assessment or an 'on-site data security assessment' by a suitable qualified security assessor (QSA). How do you get QSA qualified, by filling in a bunch of forms
Do a barrel roll.
If you can read this, it means that I bothered to log in.
The problem is that MOST sites that get 0wn3d are running phpbb or other very common and popular packages. They are getting better but they are still the most hacked because it's easy to identify what your site is using and then go and find the exploits for that site.
the SAFEST is typically custom code. and go NUTS on everything that comes from a user treating it like it's a bomb every time. It causes the kiddie to take a LOT of time to crack you, they typically move along for easier fields quite quickly. Back in the early 2000's I used to taunt the "crackers" and "kiddies" if you tried banging on my telnet or ssh door, you were actually banging on my taunt the L0ser door. It would insult the hell out of them and make them think their bot got in because it would give a successful login every time and then taunt the hell out of them and "logoff" I had a single little turd in chicago banging on me for a month until he got his buddies involved and they DDOS attacked my box with all of them trying to attack 120 bored kiddies can bring down a T1 fast, it lasted for 3 days. Funny part was 4 of them was doing it from home and when I personally called their parents all the attacks stopped. (They were on Comcast cable modems and I worked for Comcast at the time so I got the customer contact info quite easily.)
You more than likely do not have the resources I did, so dont provoke them. Taunting the lions is fun, but they now have an army of robots.
Step 1 look through you logs DAILY. 99.999782% of all website admins do not do this. Sorry but you cant spot strange things without going through logs. get a parser that makes it easier, but do it.
Step 2 learn to write secure php code and then write your sites scripts custom. Got a mailer for a contact us page? HARD CODE the to: address and get ready for the never ending fight to filter out spam.
Step 3 Backups.. never TRUST a backup you make from the site, your only real backup is the files you created and uploaded.
Step 4 review everything monthly go over stuff, look for broken or strange, go over all of it.. Look there's a wierd file in your ftp area.. how did that get there?
If you are running phpbb or drupal or other "popular" scripts you needto update them weekly. phpbb has patches all the time and MOST dont get applied by sites that get cracked.
Do not look at laser with remaining good eye.
Run the web facing site from a ROM and have it communicate with the backend through SSL. Have all activity written to log files on a write-only archive running on a second system. Run intrusion detection software on a third system. At worst you only have to deal with in-memory hacks, and you can use the archive and intrusion detection system to detect any attempted breaches.
There are a number of web app security sites that will teach you how to test your website for security vulnerabilities. Even providing sample inputs for trying XSS and SQL-Injection attacks on your own site. Try these for starters:
http://www.owasp.org/
http://ha.ckers.org/xss.html
1. Filter input
2. Don't run other people's software
3. Use placeholders in SQL
4. Make backups often so you can restore your site quickly.
If you don't have money or time these will protect you in the 95% range and even if you do get a drive by from a Romanian dude, he will most likely go away after he has done his damage, but the main thing is to get your site back up asap. I know this isn't a popular opinion, but it is how most businesses really handle this stuff without spending a fortune. Remember most web hacks have nothing to do with the site your your info etc, most are about adding to bot nets, setting up IRC forwarders etc.
I am assuming basic stuff like that you watch your bandwidth and know what services you are running on your machine, if you don't do that then there isn't even any point in the rest.
Or rather, the input your user gives you.
Let's leave aside non-web vulnerabilities for now - of course you'll want to use SFTP and SSH instead of unsecured FTP or Telnet to connect to your server, and HTTPS for your web admin panel, but these are outside the scope of the actual website - they're for your host to deal with.
When you write any kind of dynamic website, user input is the threat. Your website communicates via text with other layers such as the database (SQL) or the users' browser (HTML). Your two biggest risks are SQL injection (where user input breaks out of SQL quotes) and Cross Site Scripting/Request Forgery (where one user's input is executed as Javascript in another user's browser).
Another threat is performing actions (such as deleting/editing content) via GET requests, which will allow search spiders or content prefetchers to wreak havoc.
Smoked cheddar.
Any of the great LAMP books should have sections devoted to security. Each of the components has a part to play. The obvious vectors are PHP and MySQL so pay particular attention to those. If that's not enough, get a book for each... I'm certain there are "Security for MySQL" , etc.
They should all be available used on amazon for $10- $15 each... if $100 is out of your budget, then you'll need to start googling and doc diving.
A fool throws a stone into a well and a thousand sages can not remove it.
See subject.
This is a good place to plug the old manta: As simple as possible (but no simpler). In my case that translates to an awk script that takes the
markup and outputs static html. Easy editing, easy link checking, easy indexing, and no cgi, built-in scripting, databases, or whatever needed.
Colouring with css is fine AFAIK, but the moment you introduce javascript, frames, or other ``advanced'' features, you open the door for unholy trickery with them. Not saying this isn't the case with only static html, but I daresay the opportunity to take advantage is smaller.
Not saying static is the only way to go, but certainly less complexity means less risk of vulnerability.
...dropping PHP.
He said MySQL, so no stored procedures unless he's running > v5. I don't know what the penetration is for MySQL 5 in the hosting market.
With PHP and most PHP-based Web sites stored procedures are overkill. Use ADOdb or PDO and you'll get similar protection with less hassle.
Potato chips are a by-yourself food.
+1 to the above. Like anything else, you pay for someone else's expertise, or you learn yourself.
The best and most through guide to web testing and security out there is to the Web Application Hackers Handbook, but the OWASP Testing Guide is a good intro and a free download you can start working with today.
PDF version
Main page
The best way to learn is by doing, and OWASP WebGoat is a good interactive learning environment. It's also quite easy to try out using the OWASP Live cd, which has many of the testing tools like burp, paros, etc and also webgoat ready to run.
There's also a fairly decent "white box" source code scanner for PHP called pixy. You may wish to check that out also.
If you want to pay someone, that's what I do for a living, and I know a decent number of others in the field if you want recommendations.
Blessed are the pessimists, for they have made backups.
SethJohnson brings up two excellent points:
a) back up regularly. If you back up nightly then the most you can lose is a days worth of data. If you sync the backup directory (mysqldump cron job) to your local machine (I use lftp) then it's quicker than having to contact your hosting support. I disagree with H310iSe, just daily backups are fine.
b) don't install anything you don't have to. Disable all plug-ins you aren't using. If using somebody else's code Google it to see what problems other people are having with it. And don't use PHPNuke or derivatives.
I don't see why cerberusss's comment didn't get modded up:
c) put your source code in Subversion, and if in doubt get somebody else to go through and harden it. Not only will this protect you but by looking through the changes you will learn how to do it yourself.
My suggestion:
d) develop a script that downloads the package dependencies you need (eg mysql, apache), or at least document well so that the code doesn't depend on something you've installed and forgotten about (eg ImageMagick).
I'm not too bothered if somebody hacks my site, or even gets root access. One click reimages my VPS with a fresh install of the operating system (3 mins), (d) means in under 5 minutes my OS is ready to go, (c) means I can instantly checkout my code (< 1 minute), and (a) means I can restore my database (< 1 minute).
Of course you will want to tar up all the log files before reformatting and so you can find out what went wrong, but at least for your customers there can only be a maximum down time of 15 minutes or so. Personally I have a second synced server so all I have to do is repoint the DNS, but for amateur sites you don't even need to do that. For most web sites 10-15 minutes down time each year or two isn't a great disaster.
Phillip.
Property for sale in Nice, France
Your choice -- Zend, Drupal, whatever. Active frameworks are constantly being reviewed and patched for security holes. Building your sites on top of a framework will insure that those issues are taken care of for your sites as well.
This in response to a question that could be summarized as "Where can I learn more about security or find someone to teach me at a decent rate?"
William of Ockham had no beard. The most likely explanation is that it was chewed off by squirrels every morning.
Writing secure code with PHP is no more harder than with Perl/Java/Ruby... same rules apply.
Bugs happen. Perl has a taint mode specifically for this - to keep you from accidentally processing unsanitised user-provided data.
Does PHP? For that matter, do Java or Ruby? If not, I'd argue that writing secure code IS "more harder" in those languages.
Validate your input, use parameters in your SQL, and escape your output. Use sessions to display user specific data instead of URL parameters. Use SSL for displaying and passing sensitive data like username/passwords. This will solve 90% of all security holes, and you probably don't need to go any farther unless your site or database contains something sensitive like SSNs or credit card numbers.
The list of things you need to protect against is actually pretty short, provided that your list is high-level and general enough. ;-)
Look at this. Most of that boils down to instances of trusting inputs, which is always a bad idea when the internet is involved.
Then audit your code and look for the mistakes. It is impossible to achieve your goal without doing this. Anyone whose todo list doesn't include this step, should be ignored.
I recommend against hiring a white-hat. If you are going to continue to develop, then you need to learn to write defensive code yourself, and auditing your existing code will really help you.
As copyright owner of this comment, I authorize everyone to defeat any technological measure which limits access to it.
I personally suggest Hacking Exposed: Web Applications This is an excellent book that got me into testing web security. OWASP is terrific for tools and best practices (I suggest WebScarab. If you read the aforementioned book, you will be well on your way to understanding web security! As for someone to test your site I wouldn't trust anyone to do it that wouldn't cost you an arm and a leg; however, there are some good network scanners out there (Nikito for one). You can also find many useful tools at sectools.org. NOTE: don't merely trust the output of these tools! They are useful for finding the obvious stuff, but seasoned hackers/security experts will routinely find holes that these miss! Good luck!
Writing secure code with PHP is harder than other web scripting languages, because there are bunch of built in-functions that have un-expected behavior gotchas that can be exploited. Any time you use a built-in, you need to read the documentation thoroughly, because they more often than not do something totally weird that you would not expect in a corner case. Plus, you need to be an expert at setting php.ini settings to avoid server-wide security holes.
Eat 500 Oreo cookies.
FORTRAN: The RealUltimatePower?
Seriously, though, if you're really, really intent on obfuscating the code, why not C-Intercal through CGI? Link!
Sure, there are some minor performance hits, but it's hard to get more obfuscated.
Comment removed based on user account deletion
Only if they're used correctly.
A code like $query = "CALL mystoredprocedure($data)"; is just as vulnerable to injection attacks as other queries.
While the stored procedure might be safe the code executing the SQL is not. One could easily input " somedata); SELECT * from something;-- "
Someone posted this link in another discussion and it's pretty good: http://www.dotnetjunkies.com/WebLog/chris.taylor/archive/2004/10/13/28370.aspx
One method I use when securing SQL is to run scripts in a least privileged mode, ie. the script db user can not drop tables etc..
If you're interested in the actual hacking (err ... cracking) side of things ... Web Application Hacker's Handbook came highly recommended by my SANS instructor.
http://www.bestwebbuys.com/The_Web_Application_Hacker's_Handbook-ISBN_9780470170779.html?isrc=b-search
Que Deus te de em dobro o que me desejas
[May God give you double that which you wish for me]
This is a good idea. While ponies will not help to secure code, they make everyone feel better. Additionally, log in users over a secure connection and never email passwords. Wait, er, /.
How about Nessus?
As an experienced PHP / MySQL dev, here are the biggest things to keep in mind:
PHP htmlspecialchars() on any input submitted by the user before echoing out for display purposes. This prevents the user from embedding script (XSS).
PHP mysql_real_escape_string() before injecting user submitted data into the DB.
PHP verify MIME type of any uploaded files, don't rely only on the extension!!!
Don't EVER use PHP extract(). There are ways to use it correctly, but for a beginner, avoid it like the plague.
Make sure ini_set('register_globals', 'false'); is in your config file, or that its disabled by default in your servers php.ini.
That should keep you pretty well safeguarded. If you're interesting in talking more (as I'm security advocate helping fledling developers make their sites more secure) go ahead and send me an e-mail (skoneberg@gmail.com).
Thanks.
Love it...Learn it.
Brag about how awesome your site security is. Somebody's bound to take you up on the offer.
0) Use a version control system
1) Validate input, escape output
2) Turn off unused services
3) Regular, automatic backups to another location
Ok, the OWASP list is more comprehensive, but these four things are fundamental to preventing, and recovering from, security breaches.
Step 1 look through you logs DAILY.
Just to expand on this:
The first thing I usually check for are error codes. Filtering for 404 errors will help isolate IP addresses that try commonly known scripts with holes.
nbvnbv
http://sqlmap.sourceforge.net/
Hey if its 'simple amateur stuff' why are you asking for help? Do it yourself.
Or just use Joomla! /sarcasm
Hahahaha
I was recently asked by a new friend to review a site they had paid a company $90k to produce.
It was clear that despite the claims of the developers that they were *experts* that had produced over a 1,000 websites they knew exactly nothing about security.
The site itself was trivial in nature, members could fill out a profile and share it with others. It shouldn't have been much more then a weekend project to build WITH security.
Ok so there is two scary parts to this story. First, I had a look at their portfolio and found a bunch of other sites using much of the same code and practices for sign ups and payments. I am currently trying to figure out the correct way to notify these people that they may have a problem.
The other scary thing is, how come I never get clients will to drop $90k on me for such simple work!
You can allow access to the entire docroot, but limit ranges of IPs from posting data to specific directories or even specific files that handle form input. Rather than drop the connection, the htacccess directive can redirect the browser request to a special page that says, "Hey, I'm glad you're trying to set up a dental appointment from overseas. Please call this phone number to speak with our scheduler." Here is the section of my
Some of them are stateside addresses (Washington state) that were sources of malicious behavior. They can cruise my website reading content, etc. But as soon as they try to post a comment, they get a 'This site is undergoing maintenance' message.
Specific to your concern, try using the ban lists this site generates. If you pick China, Brazil, and Russia, you'll shut off most of the unwanted noise that is directed at your site with very little risk of blocking your target visitors.
Seth
$5 / month hosted VPS on linux = awesome!
The answer depends on the nature of the websites you built, how critical they are to their owners, and the sensitivity of the data contained in them. In other words, if you built a few blog sites or simple DB-driven PHP inventory sites, you're not likely to invite any potent hackers for there is no payoff. However, if you are protecting critical data (PII), or the sites are mission-critical, you will need to invest resources to properly defend them. I imagine you live someplace in the middle, so Google for the top ten web security threats and start at the top.
In short, read something, dude. The only difference between a developer and a white hat is knowledge. Get some.
Using a tool called dotdefender we prevent sql injection attacks on our website. Its an automatic tool that can be configured as well.
You can try for free there monitoring version at http://www.applicure.com
There is a passive mode and active mode.
The Monitor is for free while the protection mode you need to download a license free for 30 day.
It works for us - It will work for you.
Tom