How to encrypt this file with PHP? - php

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.

Related

Why is database password stored in plain text in wp-config.php in WordPress, security issue?

I wonder why the database password and login data is stored in plain text in the wp-config.php file. Isn't this a security issue and is it good practice to solve it?
I am not a pro concerning security but what I have learned is, that a first security step would be to store the password not as plain text. Second, use another file to store the password in. And I know that up to date security uses hashing including salting the password.
Or are there any other security measures installed I do not know of?
If your users can read your wp-config.php you've already lost from a security perspective.
Let's say the database credentials weren't stored in plain text and were, say, stored as an encrypted string that would be decrypted by Wordpress itself. If the potential attacker can read the wp-config.php they can probably read the decryption key as well as there's no reason to suspect that that would be stored any more securely.
When people talk about how up to date security mechanisms use hashing and salting that is only relevant to when you are the effective server. Hashing is a one way process of taking a password and converting it into something that is impossible to reverse back into the password. If you're a client rather than a server, there's no way to get around the fact that you need to have a way of getting the plain text password.
When we say to always properly hash user passwords, this means when you store them in the database. When you connect to the database, you need to provide the password (not the hash), so the password is stored in this file.
Because it's a PHP file, if a user attempts to open this file via we server, it wouldn't work because they are just PHP constants. They are not printed to the screen.
You can figure the security by making the database server only accept connections from your server (often localhost) only. Some server setups set the database credentials in environment variables. This doesn't make things anymore secure, but it keeps your wp-config file clean

Should I store passwords using php serialize instead of using database?

I'm editing web pages directly using ajax, and php with simple html dom. I dont see the point of using a database when I can do without. However, my hands go cold with fright when I think of storing admin password for the app on the webserver using serialize even though it is above htdocs, it is encrypted and I am using an anti brute force script.
I dont want to use a database just for one password but is it secure enough?
I look forward to your thoughts...
A file with the correct chmod permissions is just as secure as a database storage in this instance.
Think about it: the mysql database is actually stored in binary files on your server's filesystem. If a malicious user gains access to your server they have the same access to the binary database files as any other file, including your serialized and encrypted data in a text file.
As long as this text file isn't in a directory that's publicly accessible via the web server it's no less secure. Of course, if someone gets root access you're pretty much foobar'd either way.
What you should never do is store clear text passwords. md5() is (just) okay. sha1() has now emerged as a better option for encrypting this type of data.
Database doesn't let you have your password more secure than in file system, because in case your server gets hacked, your database password gets hacked too, which means that the admin password will be revealed in any case
If this login is and will be for you only, it's quite easier to store your password in your code/ in a file. But you have to encrypt your password to prevent hackerkiddies from reading this file and login. Please don't forget right chmods on the file ;)
As long as you aren't storing the plain-text password in the file, I don't see a problem with keeping a password hash in the actual php file.
Example using SHA1:
if(sha1($_POST['password']) == "8cb2237d0679ca88db6464eac60da96345513964") {
//success
} else {
//failure
}
you should store your "Hash" somewhere secure ( the key you're generating a password with) . it doesnt matter where you store that password if someone can get to the "hash / key", they can get to your passwords. the nice thing about a database is that it's most likely going to be easier to traverse your directory structure and find a file than it is to connect to your database, discover your table structure, then discover the values stored in a field in the database..

how do I encrypt and then decrypt the text of username and password used in database class file

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 to safely store a password inside PHP code?

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.

How would you implement FORM based authentication without a backing database?

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.

Categories