Let's say I have a website where
PHP 5.3 is installed
every output is htmlspecialchars()ed.
PDO and prepared statements are the only way to interact with the database
error_reporting() is off
every request is passed to index.php (front controller) and no direct file access is allowed except for index.php via .htaccess
every input is properly escaped (why should I? i use Prepared statements, how could an user input mess up with my code?)
there's no use of evil()
Is it considered safe? What other things could be fixed to improve security? How could you attack it? Hack it? PHP/Server side is possible to improve security?
Check this page : PHP Security Guide. Most attacks are documented. If after implementing these security checks, you're still hacked, there are high chances that the problem doesn't come from your PHP application.
By the way, as #Jacco stated, there is some wrong stuff on the article I linked to.
Use prepared statements instead of mysql_real_escape_string(), but you already did that.
About salting, follow this answer instead : https://stackoverflow.com/a/401684/851498
Finally, checking ['type'] (for file upload) is unsafe since a malicious user can change this value. Instead, see the suggested solution of this link : http://www.acunetix.com/websitesecurity/upload-forms-threat.htm
I remember when I started web developing, I read allot about sanitizing data, creating numerous mysql users with a subset of permissions for specific queries, etc.
It gets you in the mindset of treating security with code, not with the operating system.
What use is all of this if you connect to your console with telnet, or use ftp with authentication?
I guess I should cut to the point. I think modern open source technologies such as php mysql etc have build up allot of security features, which gave me a false sense of security.
The damage you can do through these technologies is negligible compared to hacking into console with a brute force attack. If I were you I would worry much more about geting a proper firewal and only allowing port 80 or the bare minimum of ports you need. If you enable console access I would only allow your desktop IP... etc.
and make sure if you ever send a password, that it is encrypted through ssl
There is no absolute security guarantee, you can add the following to the answers above:
If you allow file uploads, make sure you do mime checking;
Make sure the public cannot upload an unlimited amount of files to
overload and eventually kill your server;
If you own the server make sure there are no other weak gates to your site, you can spend millions making your site bulletproof to any type of attack, but if someone gains access to it through another website hosted on the same server, you're out of luck;
Use a vulnerability scanner like acunetix, skipfish;
If you own the server make sure you stay up to date with the versions of the software running on your server (PHP/Apache/MySQL). Subscribe to get updates from the vendors;
If the budget allows it, you could offer a bounty to someone to find a security hole in a DEV release of your code;
Use a product like the following: https://www.cloudflare.com/features-security
security is a major concern for any product and it can not be achieved by some finger count policies but they are important so everywhere in the code think the negative possibilities and work against them to prevent them.
other thing you have to do
store sensitive data in encrypted formate in db
clean XSS every user input data
It is important to note that "safe" is a context-based term. It highly depends on your needs, and there are companies out there (I'm looking at you Google) who will not even consider installing PHP at all.
If you are working at a big company, I would recommend hiring the services of professionals.I heard from a friend that this company does sec checkups for all the big companies, which seems likely since they are the people that distribute Kali Linux.
https://www.offensive-security.com/offensive-security-solutions/penetration-testing-services/
There can be multiple other issues as well, such as session problems, sensitive information enumeration, authorization and authentication issues, and lot more. Issues like business logic bypass can not be resolved by traditional secure coding guidelines. However, looking at PHP Security Cheat Sheet and OWASP PHP Security Project would be a great help to understand the big picture of security issues.
You can learn more about exploiting PHP security issues and related attack techniques by solving the PHP security challenges by RIPSTech (https://www.ripstech.com/php-security-calendar-2017/) or by reading their writeups of real-world vulnerabilities found in popular PHP apps (https://www.ripstech.com/security-vulnerability-database/)
Related
I know securing any website is a very tough and broad topic to be discussed upon but i want to relate this question to my specific website which i've been working on. It was coded in php by some other programmer around 2004 and i am responsible for it's management. My problem is it's being hacked time and again. I have noticed following things when it's been hacked.
.htaccess file has been modified
index.php and config.php files were modified
Admin password has been changed
Uploading files in server
changing file permission of files and folders
I have worked on the code, it has been properly escaped and i think there is no probability of sql injection. Since most of the problem is related to files and permission i have a doubt about the server security but due to the reason that it was coded around 2004 surely it will lack some security, so what other things do i need work upon in my code to prevent my site being hacked for above mentioned problems?
Thanks in advance.
Since files have been modified, this is unlikely due to SQL injection bugs.
Possibilities to get to the files:
Guess/steal your FTP password
Hack the server (you can't really do anything about that)
Insufficient isolation on the server, meaning other customers can change your files (you can't really do anything about that either)
Remote code execution bugs
Now since you say the website is from 2004, it could be that it uses eval for templating or include for things like site.php?section=foo and then include foo.php in the code somewhere which were both done frequently back in 2004. So I'd do a quick file search for eval and the regex include(.*\$.*) as well as require(.*\$.*). Those are prime suspects depending on how they were used.
Someone probably has direct access to the server, rather than to (a) script(s) in particular. This doesn't sound like a security issue having its origin in the codebase.
You might wanna consider moving the entire site to another provider if this has happened time and time again. Start over somewhere else, with fresh passwords, access control, etc.
OWASP top 10 is very good read. Some guesses of mine.
outdated OS which has vulnerabilities.
MySQL injection and maybe all password stored in plain-text which is very very bad. For authentication you should be using something like openID instead. Also when you have MySQL-injection you should pronto update code to use PDO(prepared statements) if possible.
read/write permissions not set properly or APACHE/PHP running at elevated level?
My advice to you is:
read up on information on OWASP. Then cleary look for flaws in your code. Every line could be source off problem. Maybe you should ditch old code, because very insecure?
reinstall your OS, because you could have a rootkit even?
Never use just shared hosting, use at least managed servers / keep the system up to date
Check your php.ini for security issues (that you can google)
Check your Apache/Nginx/... configs for overrides
Never communicate unencrypted with the server (use SFTP, SSH, ...)
Never trust external values (also from Cookies), always escape/cast those
Filter user input (remove line breaks, 0x00 characters, tags, ... where undesired)
Check all possibly existing user accounts for the server/database/...
Check if all services run as the correct user
Check file (write/execute) permissions in your web folders
Escape everything you show on the website, do not even trust your database data to be safe in any way
If you use 3rd party software, look out for security advisories
re-install the server, you might have been rooted
Use prepared statements
That's it;) This will enhance your security a lot, but experienced attackers are tough.
I'm currently building a website, using PHP, and looking into securing the website fully. Currently, and in the future, I don't plan on using SQL, or even user-submitted input anywhere on the website - the PHP pages are basically simply in place for ease in piecing together several different HTML fragments to create a full page, using requires.
What type of vulnerabilities, if any, should I be aware of to protect against?
There are no vulnerabilities in the situation you've outlined.
If you are using any query string variables to load pages, they may need to be secured. For example: article.php?page=php-page-security.
Otherwise just make sure that your server software is updated regularly to the latest versions, and access to the web server is properly secured. It sounds like your code is pretty basic and you aren't doing any processing in PHP, so you should be fine.
This is a huge topic that can't be answered in a single post. Some tips:
Secure physical access to your web server (your hosting provider should handle this)
Minimize remote access to the server. Setup a firewall, use proper passwords, regularly run updates
Secure your code (PHP and javascript). Make sure to "clean" any qstrings you might process and never use eval. Consider using a framework to simplify this step.
Keep server logs and review them regularly for mischief.
This is just a jumping point. A google search for "web application security" will turn up troves of information. Good luck!
Possible exploits are in the overall server security.
As you use PHP in that simple manner, there's a risk that you do not know it well enough and might overlook some hole: like user input option, or file access rights which would allow a bad guy to upload his php to the server.
PHP offers too much for a simple task of including files. More capabilities == more risk.
I'd use server-side includes for the sake of assembling several files into one web page, and just disable php — faster, more secure.
You should be sure that your software (e.g. webserver, operating system, PHP) is up-to-date, with the latest security patches and updates. You can also hide PHP (read the official guide or [search Google])(http://www.google.com/search?q=hiding+php)
By combining all the advice you get from the answers here, your application will be something more that perfectly safe.
As #Toast said, you had better block incoming traffic and only allow port 80 by using a firewall (Netfilter/iptables on Linux), except if you want to enable additional services, such as FTP.
And in case you want the data travelling between the server and the client to be safe, then HTTPS is the best solution.
If you're not basing the "piecing together" on any kind of user-provided data, and not including any user-provided data into the page, then you're about as vulnerable as a plain static .html file.
That means you're not doing:
include($_GET['pageName']); // hello total server compromise
or
echo "Hello, ", $_GET['username']; // hello cross-site-scripting!
and the like.
While installing an application onto a client's server, I would like to make sure that the client (or a future developer for them, etc) does not copy my application and place it on other domains/servers/local servers.
How can I verify that my application is running on the server I installed it on? I do not want any substantial lag in the script every time it runs, so I assume a 'handshake' method is not appropriate.
I was thinking the script could request a PHP page on my own server every time it runs. This could send my server their server info and domain name, which my script can check against a database of accepted clients. If the request is invalid, my server handles the work of emailing me the details so I can follow it up. This should not slow down the client's script as it isn't expecting a response, and will still operate on their 'invalid' server until I can investigate this and follow it up with them personally.
If this is the best method (or if there is better), what PHP call should I be making to request my server's script? file_get_contents, curl and similar seem to always retrieve the response, which I don't need.
UPDATE
Thank you all for your responses. I completely understand that PHP is open source and should be freely available to edit. I should have stated more clearly initially, but my intentions were for this verification method to assist me in finding anyone breaching my license agreement. The application is covered under a license, but I would also like to include this check so that I can monitor an initial misuse of my application.
Hence, somebody may still breach my license and it would most likely go unnoticed, but if I implement this script I have the advantage of any 'lazy robbers' who don't break apart my application and remove the verifier before ripping it.
Does this justify the use of such a script? If so, is cURL my best option?
Any checking code for verification is easily replaced with a return true;. Look at the faq at https://stackoverflow.com/tags/php/info :
Q. Can I protect my PHP code from theft? If so, how?
A. There is no effective technical solution to protect, encode or encrypt PHP source code. There are many products that offer some levels of protection, but all can be broken with time and effort. Your best option is not a technical solution, but a legal solution in the form of a license agreement.
You get a legal agreement and sue everyone.
SaaS is your friend. Host the application on your own secure servers, and charge a license fee for your customers to access it.
imo its worth checking out some joomla extensions that do this. There a few different implementations, some check the domain and validate it before executing, most are encrypted, along with a domain validation. I remember sakic's url sef extension used to do this. There are quite a few more commercial extensions that use the same thing. Apart from that I cant think of another way.Probably another good idea is to have a good license in place and a good lawyer....
Short answer: This can't be done.
Long answer: Whatever protection you put in your code, it can be removed with little difficulty by anyone with some experience in PHP. Even if the code is encoded with something like ionCube or Zend Guard, this too can be decoded with relative ease.
Your only option is to protect your intellectual property by actively pursuing copyright infringers. Even this is not foolproof, as our folks from RIAA and MPAA know very well. In this day and age, I'd say this is not a solvable problem.
You could integrate phone-home behavior into your software but you should probably consult a lawyer to discuss privacy issues about that and to work out privacy guidelines and terms of use for your clients' usage license.
One thing to be careful about is the data you send (and the way you send it, i.e. securely encrypted or not) to identify the client who is illegally using your product because it could potentially be used to compromise your client's infrastructure or for spying on your client.
Regarding your phone-home function, be warned that the client could just locate and remove it, so using a PHP obfuscator or compiler might provide some additional protection against this (though any sufficiently determined PHP developer could probably disable this). Note that your protection will only act as a deterrent aimed to make the cost of circumvention
approach or exceed the cost for legal use.
EDIT:
As poke wrote in the question comment, you could move parts of your code outside the software installed at your client's site to your servers but this may backfire when your servers are unreachable for some reason (e.g. for maintenance).
In the end, I think that customer satisfaction should be valued higher than protecting your software from the customer, i.e. try to avoid protections that are likely to make your customers angry.
You could encode it and hard code a license file that would allow it to only work on the domain it was intended for (e.g. use ioncube or zend to encode a file that checks if the HTTP HOST is the intended domain without doing a handshake). You could then make that file required in all other files (if everything was encoded).
I am creating a website that is using a perl script, PHP, a MySQL database, and HTML. My main concern is making sure there is not anyway someone can gain access to anything that give them access to my information. I mean is there anyway for someone to get my perl script and see my database information. I know about sql injection but I have no forms for information to be entered into. Is there anything I should keep in mind with this stuff.
is there anyway for someone to get my perl script and see my database information
This will only happen when the webserver doesn't parse/process the script and returns it as plaintext. Usually this parsing/processing only happens on specific file extensions like .pl for perl files and .php for PHP files. If you (or the hacker) renames it to .txt, the client will be able to obtain the entire script as plaintext. Nevertheless, if a hacker is able to rename it, it has access to the whole script anyway. This would then be done by a security hole in FTP or CMS.
Further, I've seen scripts which reads files (usually images or other static files) from (outside) the webapp context based on the path as a parameter. E.g. download.php?filename.ext If such a script doesn't do any sanity checks on the file path, a smart hacker may be able to obtain scripts as plaintext by download.php?%2Fserver%2Fhtdocs%2Fscript.php.
The breadth of this question is kind of overwhelming, but it's a great question and definitely important.
Much of the issues you are going to have with your server can be tied to server access itself, make sure you don't use any software you don't need. If you don't need a name server, turn off bind; same goes for ftp, even sendmail if you can. Use strong passwords and alternate ports if possible.
For PHP, see http://us3.php.net/manual/en/security.php and http://php-ids.org/; definitely use mysql_real_escape_string() and htmlentities().
For HTML/PHP/JS, see http://en.wikipedia.org/wiki/Cross-site_scripting
There is a lot to think about. I'd recommend trying to find a mentor to help you figure out what is important. I'm mentoring a guy right now and it helps him a lot even if I'm not perfect. SO can help, but a person you trust who can look at how you do things can make recommendations you just won't get here unless you post your entire code base.
Use placeholders for SQL, even PHP supports it.
Escape your output. Your templating system may help here.
Use cgi-bin directory. It really helps to protect accidental leaks. It is easy to make URLs without cgi-bin.
In Perl use taint mode, in PHP use hardened PHP.
Web application security is a big topic. However, you know about one of the biggest vulnerabilities out there, SQL Injection, so that's a good start.
A couple other big ones are Cross Site Scripting (XSS) and Cross Site Request Forgery (CSRF - "See-Surf")
XSS - http://en.wikipedia.org/wiki/Cross-site_scripting
CSRF - http://en.wikipedia.org/wiki/Csrf
As usual Wikipedia provides a good intro.
You may also want to look in to verifying request authenticity by using an HMAC
http://en.wikipedia.org/wiki/HMAC
Never ever trust any user input in any form.. Ever :)
The hard part is figuring out all the ways a user can supply input to your site..
I have a client who's wordpress sites have gotten hacked twice by iframe scammers. Each time they've injected iframe code into the content of the sites.
This last time, today, they simply changed the siteurl in wp_options to their iframe code. The result was obvious and appeared to simply botch the paths of the scripts that rely on
<?php bloginfo(); ?>
I can't determine if its a password compromise (on FTP or WordPress itself) or a SQL injection to alter siteurl. Since the only thing that was altered is siteurl, I'm thinking perhaps SQL Injection.
What are your thoughts? Any way to scan a site for potential SQL injection vulnerabilities?
The only active plugins on the site are contact form 7 and google xml sitemaps.
It is extremely unlikely that SQL Injection 0-day was used in this attack. Wordpress is one of the most insecure PHP projects I have ever audited, and it won a pwnie award for being so insecure. The "Wordpress hackers" are a complete joke, they rejected one of my vulnerability reports because they where unable to grasp the simple flaw, they didn't even bother running my exploit code. (The flaw was patched.)
Using FTP is an extremely bad idea. You are transmitting plain text passwords and source code over the open internet in CLEAR TEXT, you must be completely insane. Use SFTP!!!! I know there is a virus (can't remember the name...) that is spreading by sniffing network traffic looking for FTP passwords, then it logs in, and modifies .php and .html files it finds. Run an anti-virus on all machines with FTP access to the server, AVG will remove this virus.
I bet that wordpress or one of your plugins has never been updated. Vulnerabilities in plugins are a commonly used to break into web applications. Check all your version numbers of all installed libraries/web apps.
If you want to test your site for SQL Injection then turn display_errors=On in your php.ini and run the Sitewatch free service* or the open source Wapiti. After you patch any vulnerabilities, re run the scan to make sure your patches hold. Then run PhpSecInfo to lock down your php install. Make sure to remove all RED entries from the report.
*I am affiliated with this site/service.
Don't forget comments. I've had problems with users registering and then throwing code in the comments and in their profile. Check there.
I think it's trojan horse stealing FTP passwords from user's PC.
As for software to test your app against SQL injections, there are plenty of answers here on SO already
Have you tried any of the free SQL injection scanners? Nessus does it, but it's not free anymore, there are a few free ones available, sorry couldn't be any more help, have not looked at databases in ages and when I did it was only a cursory glance.
If the paper linked here is right, you should use NTOSpider to let it attack your site.