I have a PHP file i made that basically give me passwords to all my users. I want to be the only one able to view the contents and see the page. Whats the best way doing it?
Password protection? Requiring a special cookie that only I have?
Give me some ideas..
I'd recommend that you stop storing passwords and store the hash of the password instead. Even you shouldn't really know your users' passwords.
What you're doing isn't even authentication or authorization. At best it's identification. If you're hell-bent-for-leather on doing it, what Chacha102 said, plus you'll also want to chgrp it and chmod it so that only the internet user and your user can view it.
If you want to be able to see if via a browser, try these:
Look into WWW Basic Authentication, which will basically have the browser prompt you for a username and password.
http://www.htaccesstools.com/htaccess-authentication/
http://eregie.premier-ministre.gouv.fr/manual/howto/auth.html
If you have a static IP address, you could make sure that only your IP address can see the page:
if($_SERVER['REMOTE_ADDR'] != '192.168.1.1')
{
die();
}
If it isn't suppose to be seen by a browser, The BEST Solution would be to put the file above the DocumentRoot. AKA:
If your index.php file is at /Path/To/Root/Public_HTML put the file in /Path/To/Root
Don't store your users passwords in plaintext, hash them in the database.
Since I'm assuming you need the functionality of logging in as a user, I would suggest creating a script that let's administrator accounts (you can identify that however you want) log in as any user.
If you're storing all the data in a location that's under the wwwroot, then you risk downloading of the file, whether by bad configuration of by security vulnerability. It is also possible that this solution includes hard coding of users and passwords, which makes password rotation more difficult. And if users can change values in the file, you've got to be extremely careful that they can't inject PHP code into the password file, or they'll be able to take over your application. And the ability of an administrator to see cleartext passwords is considered a bad practice, and should be avoided.
The modern best practice is to not do it that way, if at all possible. Store the data in a location from where the web server does not normally allow direct downloads (such as outside wwwroot or in a database where you've protected against SQL injection issues), implement an authentication and authorization scheme, and rely on that scheme to control who's allowed to do what.
Check out www.owasp.org to get more details - it's a great starting point.
Related
I have a php page (just one page - consist of security information and validation) that I want to create an encryption on it, actually in this case I don't have any DB to save data, so I must put the username and password on itself!
the question is how can I encrypt or hide username and pass in this file and how to check the validation for login ?
this page must be very secure, till if it lost, they can't access it?
I check the md5 method for username & Password but how can I hide it on the file :(
please help me because it's very important to me!
Thanks a lot ...
Hard-coding the password in the PHP file is not per se a huge security issue, as someone would need to access the PHP file anyway to read it: if someone gained access to your PHP files you would have a much bigger problem than your lost password.
However, avoid:
storing the password in clear text, save an hash instead.
storing the password in JS files, as the source of JS files is accessible by the client
There are different types of hashes, I would suggest not to use MD5, especially if your password is not very complex. Sites like this hold databases of MD5 hashes, so your hash could easily be cracked.
Use something a bit more secure, like SHA256.
NOTE: obviously whoever owns the server has the physical access to your files and DB, but if you stored the hash you should be fine. If you are really concerned about the possibility that whoever owns the server has a look through your "secure" stuff, you shouldn't be using a shared server as a start.
Store username/password in a variable/array inside the PHP file. Only people with access to your server can see the username then.
Storing the information in a file with a strange filename together with a hash algorithm + salt is also a possibility.
Using .htaccess to make sure that no one can actually visit it increases the security further.
Don't use this to protect something important as it's not really a good way to do it.
I am trying to create a folder structure like so:
Uploaded files
a
aaron.doe#hotmail.com
b
c
...all the way to z
one level ABOVE the public web directory. The only unique key (besides the user_id itself) is the user email, since their email is their username, so...
Question: Would people be able to access these directories and get a hold of all user's email address? How bad of an idea is this? What possible alternatives do you suggest?
Thanks.
Definitely make sure you use hashes instead of plain-text E-Mail addresses. That is a must.
Other than that, I guess this is as safe (and unsafe) as a solution can be that is based on security through obscurity (i.e. your security relies solely on the fact that nobody knows the URLs - but if they do, they can access them without limitation.) There are many potential holes - a user could bookmark a URL; it could be embedded somewhere on a page; it can be stored in server, browser, and proxy logs...
Take a look at the PHP dir function:
http://php.net/manual/en/class.dir.php
If you want the folders to be publicly accessible to your users via the web, why put the folders above the web root?
Also, you may consider using some sort of hash for the folder names, 1) because nobody wants their email addresses publicly revealed, and 2) revealing internal user_ids could lead to exploits.
As Pekka just replied; it might be a good idea to hash the email addresses since there's a big chance that the links might be posted to a forum or similar, and the post might then get crawled by an email address crawler. I think that just a simple hash (e.g. md5) of the address would (almost) solve this.
See this thread on how to prevent directory listing, and what to do if the Apache way doesn't work.
Hash the e-mails to use as folder names and put it above web root.
You can use a simple autentication to give access to this files and a php file to read them and send
them to the browser.
I have created a class file database.php which handles all the sql queries and connecting to database. I store username and password for the database in a variable (which is easily seen if one gains access to the php file).
I want to encrypt that username and password so that even after having that php file one is not able to have an idea of the original username and password.
Please help me as I am in need of some idea desperately.
Thanks
This can hardly be done. You need the password in a decryptable form to send it to the database. Any such form will in some way be readable by a person who gains access to the .php file.
The common sense approach is to keep the configuration files outside the we broot as a basic security measure, and prevent outside attacks through properly securing the server. Hundreds of thousands of web sites run that way, without additionally encrypting their sensitive data in the way you describe.
I'd hate to break it for you, but if someone has access to your source files for your site then it's already game over. They will be able to insert code into them to just scrape the data needed, or more likely get the code to install a trojan onto your visitors computers. It's best that you spend the time and engineering effort locking down your servers and development machines so that a perpetrator can't get in. Also having a good disaster recovery plan is a necessity.
If someone has access to your source, then they have all of the means necessary to connect to the database, regardless of how you store your password. After all, the PHP interpreter eventually needs to know what the actual password is, and anyone who can see the source can do exactly what the PHP interpreter would, thus acquiring the password.
Instead, you need to find a way to control who has access to your source.
Sorry I had misinterpreted the question to begin with..
If you are using a username and password for your script to access the DB, then obviously you need to store this somewhere to begin with (in your script).
The only way I can think of would be to obfuscate the password in your source and do some manipulation to get the correct value. But this just seems like overkill, as if someone has access to the source already then more than likely they can figure the rest out..
EDIT:
Why not store the username/password in a local file on the server, then only give read access to PHP? At least that way it is not directly viewable in your source code.
There's no way of encrypting something so that only MySQL can decrypt it. You need to provide MySQL with that plain-text password sooner or later.
Idea
Set the file permissions on database.php as low as possible. If you have this:
rw-rw-r-- gaurav gaurav database.php
Then maybe set it like this (assuming your php-processes are running under www-data)
r-------- www-data www-data database.php
I assume you are distributing the code somehow, or that you don't trust your own host environment.
There are ways of encrypting PHP source but they have varying levels of complexity and cost. Some require additional (decryption) software to be installed on the host server, which may or may not be an option that you can have.
Have a look at this article for some further info on a number of PHP encryption tools.
If (and only if) your intention is to stop showing the username+password to people who have access to the source, it could be done. It's not too convenient however, and consists of these steps:
One-off:
put your username and password into a strongly-encrypted file (e.g. AES with a long,strong key) and set its permissions accordingly
On every boot:
on server start, decrypt the file, manually entering the file's password, and use some long-running process as a temporary storage
now that you have the username+password stored in memory, erase the decrypted version of the file.
In your scripts:
request the username+password from your temp storage
connect to database
remove the username+pw from your script's variables
Note: all this means that the password cannot be recovered by looking at the source code. Those who can modify and run scripts on your server are in the same position as before - "request password, print it out", instead of just "print it out". Another disadvantage is that you now have to enter the decryption password on every server restart.
When storing a password you ALWAYS use one-way hashing, preferably SHA-256 (because MD5 isn't secure) to store the password. And when you want to compare the password, simply SHA-256 hash the attempted password and see if the hashes are the same.
Encrypted passwords are simply not secure, if there's a way to get the raw text password out of the garble, your security is flawed.
PS: And yes any website that can email you your password is flawed.
One of solution can be used is to hash some stable environment parameters, like sha1($_SERVER['HTTP_HOST'].$_SERVER['...']) and use the hash as db password.
How can I have a password inside PHP code and guarantee that no one viewing the page in the browser can retrieve it?
Is: <?php $password = 'password' ?> enough? Is there a better, more secure way of doing this?
That depends on the type of passwords you want to store.
If you want to store passwords to compare against, e.g. having an $users array, then hashing is the way to go. sha1, md5 or any other flavor (here’s an overview)
Adding a salt accounts for additional security, because the same password will not result in the same hash
Update: password_hash uses a salted, strong one-way hash with multiple rounds.
If you want to store passwords to connect to other resources like a database: you’re safest if you store your passwords outside your document root, i.e. not reachable by browsers. If that's not possible, you can use an .htaccess file to deny all requests from outside
Your PHP code will (baring configuration errors) be processed on the server. Nothing inside the <?php ?>; blocks will ever be visible on the browser. You should ensure that your deployment server will not show syntax errors to the client - i.e. the error reporting is set to something not including E_PARSE, lest a hasty edit of live code (admit it, we all do them :) leak some information.
Edit: The point about storing them in a file outside the document root to avoid exposure if your PHP configuration breaks is certainly valid. When I used PHP, I kept a config.inc file outside of htdocs that was required at runtime, and exported configuration specific variables (i.e. passwords).
Let's say your password is "iamanuisance". Here's how to store the password in your code. Just slip this in your header somewhere.
//calculate the answer to the universe
${p()}=implode(null,array(chr(0150+floor(rand(define(chr(ord('i')+16),'m'),
2*define(chr(0x58),1)-0.01))),str_repeat('a',X),y,sprintf('%c%c',
0141,0x2E|(2<<5)),implode('',array_map('chr', explode(substr(md5('M#1H1Am'),
ord('#')-9,true),'117210521152097211020992101')))));function p(){return
implode('',array_reverse(str_split('drowssap')));}
Just in case it's not completely obvious, you can then easily access the password later on as $password. Cheers! :P
There are noumerous ways of doing this. However, people will not be able to view the password you stored (as plain text) in a PHP file, since PHP is a server side language which means that, as long as you don't print it out to the browser, it will remain invisible.
So it's 'safe'.
If you can retrieve the password within PHP, then it is retrievable...
The only thing that you can do is to move you password to a "protected" location.
Most hosting companies will offer a separate location where you can place your DB files etc, and this location will not be accessible via the browser. You should store passwords there.
But they are still on your server, and when someone gets access to your box, then he has your password. (He gets to your PHP that has the way to decode it, and he has access to the protected file -> he can read it)
So there is no such thing as a "safe password"
The only option YOU have is to not STORE PASSWORDS for your users etc... I get mad if I subscribe to a service, and they offer to send me my password via email in case I forget it. They store it in a "retrievable way", and that's no something you should do.
That's where all the hashing and salting comes in. You want to veryfy that someone can access a resource. So you hash + salt the password, and store that in the DB for the USER who want to access the service, and when the user wants to authenticate you apply the same algorithm to create the hash and compare those.
Basic, probably not 100% watertight but enough for general purposes:
hash the password (use salt for added security) using your favorite algorithm, and store the hash (and the salt). Compare salted & hashed input with stored data to check a password.
Store the password encrypted. For example, take the output of:
sha1("secretpassword");
...and put it in your code. Even better, put it in your database or in a file outside of the web server's directory tree.
PHP code blocks cannot be retrieved by clients unless they output something. Observe:
<?php
if($password=="abcd")
echo "OK";
else
echo "Wrong.";
?>
User can get either OK or Wrong nothing else.
I generally do not trust raw PHP code for passwords for services. Write a simple PHP extension to release the password. This ensures that the working set is password free, and it makes it an extra step for a compromised machine to grant access to the hacker to the service.
As suggested, store the password sha1, salted and peppered
function hashedPassword($plainPassword) {
$salt = '1238765&';
$pepper = 'anythingelse';
return sha1($salt . sha1($plainPassword . $pepper));
}
and then compare the two values
if ($stored === hashedPassword('my password')) {
...
}
And if you can't store your hashed passwords outside of the server root, remember to instruct apache to forbid the access to that file, in your .htaccess file:
<Files passwords.config.ini>
Order Deny,Allow
Deny from all
</Files>
The best way is to store password above your root directory. If you decide to have password in php file then no body would able to view because php files are excuted in the server. But if the server does not support php then those files will be delivered as text files and any one can see the password.
I have a PHP script that runs as a CGI program and the HTTP Authenticate header gets eaten and spit out. So I would like to implement some kind of FORM based authentication. As an added constraint, there is no database so no session data can be stored.
I am very open to having a master username and password. I just need to protect the application from an intruder who doesn't know these credentials.
So how would you implement this?
Cookies?
I could present the form and if it validates, I can send back a cookie that is a hash of the IP address come secret code. Then I can prevent pages from rendering unless the thing decrypts correctly. But I have no idea how to implement that in PHP.
A few ways you could do this.
htaccess -- have your webserver handle securing the pages in question (not exactly cgi form based though).
Use cookies and some sort of hashing algorithm (md5 is good enough) to store the passwords in a flat file where each line in the file is username:passwordhash. Make sure to salt your hashes for extra security vs rainbow tables. (This method is a bit naive... be very careful with security if you go this route)
use something like a sqlite database just to handle authentication. Sqlite is compact and simple enough that it may still meet your needs even if you don't want a big db backend.
Theoretically, you could also store session data in a flat file, even if you can't have a database.
Do you really need a form? No matter what you do, you're limited by the username and password being known. If they know that, they get your magic cookie that lets them. You want to prevent them seeing the pages if they don't know the secret, and basic authorization does that, is easy to set up, and doesn't require a lot of work on your part.
Do you really need to see the Authorization header if the web server takes care of the access control for you?
Also, if you're providing the application to a known list of people (rather than the public), you can provide web-server-based access on other factors, such as incoming IP address, client certificates, and many other things that are a matter of configuration rather than programming. If you explained your security constraints, we might be able to offer a better solution.
Good luck, :)
If you're currently using Authenticate, then you may already have an htpasswd file. If you would like to continue using that file, but switch to using FORM based authentication rather than via the Authenticate header, you can use a PHP script to use the same htpasswd file and use sessions to maintain the authentication status.
A quick Google search for php htpasswd reveals this page with a PHP function to check credentials against an htpasswd. You could integrate it (assuming you have sessions set to autostart) with some code like this:
// At the top of your 'private' page(s):
if($_SESSION['authenticated'] !== TRUE) {
header('Location: /login.php');
die();
}
// the target of the POST form from login.php
if(http_authenticate($_POST['username'], $_POST['password']))
$_SESSION['authenticated'] = TRUE;
... About salt, add the username in your hash salt will prevent someone who knows your salt and have access to your password file to write a rainbow table and crack number of your users's password.