What is the best way to send secure parameter in Ajax Request? - javascript

I send a ajax request with this function:
function myFunc(x)
{
$.ajax({
url: retrive.php,
type: 'POST',
data: 'data=' + x,
success: callback
});
}
I call the function with a integer parameter.for example:
myFunc(20);
myFunc(25);
can a hacker change the parameters of myFunc() ?
If he can, How to prevent change value?
What is the best way to send secure parameter?
** EDIT: **
My javascript codes have a variable called Score.
This variable is incremented by one:
if(condition)
{
Score++;
}
When the game is over, I send variable with Ajax.
And this variable with the game code is stored in the database.
if(game_over)
{
myFunc(20, Score); // game code, score
}
But this values can be changed by a user.(by console of chrome and firebug)
1. What is the solution?
2. What is the name of this type of attack? Is Xss?

Yes, a hacker sure can, and easily too. For example, by using Chrome Developer tools, one can inject or modify your script. As a motivating example, I routinely do this when I order a pizza to have it delivered a little faster ;)
So, you should not rely on JavaScript authentication. Instead, have your server verify or reject the parameters, or use some sort of challenge/accept system between the server and the JavaScript.
Here are some more ideas you can try: Ajax post request security

Can a hacker change the parameters of myFunc() ?
Yes he can.
If he can, How to prevent change value?
You can't prevent it but you can verify the parameters within server side code.
What is the best way to send secure parameter?
What you can do is you can use mcrypt_encrypt() function for encrypting your string or data and while receiving data you can use mcrypt-decrypt() function else you can use your other encoding ways of PHP
You can check PHP mcrypt - Complete encryption and decryption of data

It is the same as to send params via POST or GET over HTML form.
Its impossible secure it.
You can only use some encrypt method but it is not much secured because on server side you need decrypt it. And in final of this solution, its impossible to encrypt it at 100% secured.

Related

Set SESSION on php and remove it via JAVASCIPT [duplicate]

Is it possible to set PHP session variables using Javascript?
In JavaScript:
jQuery('#div_session_write').load('session_write.php?session_name=new_value');
In session_write.php file:
<?
session_start();
if (isset($_GET['session_name'])) {$_SESSION['session_name'] = $_GET['session_name'];}
?>
In HTML:
<div id='div_session_write'> </div>
The session is stored server-side so you cannot add values to it from JavaScript. All that you get client-side is the session cookie which contains an id. One possibility would be to send an AJAX request to a server-side script which would set the session variable. Example with jQuery's .post() method:
$.post('/setsessionvariable.php', { name: 'value' });
You should, of course, be cautious about exposing such script.
If you want to allow client-side manipulation of persistent data, then it's best to just use cookies. That's what cookies were designed for.
or by pure js, see also on StackOverflow :
JavaScript post request like a form submit
BUT WHY try to set $_session with js? any JS variable can be modified by a player with
some 3rd party tools (firebug), thus any player can mod the $_session[]! And PHP cant give js any secret codes (or even [rolling] encrypted) to return, it is all visible. Jquery or AJAX can't help, it's all js in the end.
This happens in online game design a lot. (Maybe a bit of Game Theory? forgive me, I have a masters and love to put theory to use :) ) Like in crimegameonline.com, I
initialize a minigame puzzle with PHP, saving the initial board in $_SESSION['foo'].
Then, I use php to [make html that] shows the initial puzzle start. Then, js takes over, watching buttons and modding element xy's as players make moves. I DONT want to play client-server (like WOW) and ask the server 'hey, my player want's to move to xy, what should I do?'. It's a lot of bandwidth, I don't want the server that involved.
And I can just send POSTs each time the player makes an error (or dies). The player can block outgoing POSTs (and alter local JS vars to make it forget the out count) or simply modify outgoing POST data. YES, people will do this, especially if real money is involved.
If the game is small, you could send post updates EACH move (button click), 1-way, with post vars of the last TWO moves. Then, the server sanity checks last and cats new in a $_SESSION['allMoves']. If the game is massive, you could just send a 'halfway' update of all preceeding moves, and see if it matches in the final update's list.
Then, after a js thinks we have a win, add or mod a button to change pages:
document.getElementById('but1').onclick=Function("leave()");
...
function leave() {
var line='crimegameonline-p9b.php';
top.location.href=line;
}
Then the new page's PHP looks at $_SESSION['init'] and plays thru each of the
$_SESSION['allMoves'] to see if it is really a winner. The server (PHP) must decide if it is really a winner, not the client (js).
You can't directly manipulate a session value from Javascript - they only exist on the server.
You could let your Javascript get and set values in the session by using AJAX calls though.
See also
Javascript and session variables
jQuery click event to change php session variable
One simple way to set session variable is by sending request to another PHP file. Here no need to use Jquery or any other library.
Consider I have index.php file where I am creating SESSION variable (say $_SESSION['v']=0) if SESSION is not created otherwise I will load other file.
Code is like this:
session_start();
if(!isset($_SESSION['v']))
{
$_SESSION['v']=0;
}
else
{
header("Location:connect.php");
}
Now in count.html I want to set this session variable to 1.
Content in count.html
function doneHandler(result) {
window.location="setSession.php";
}
In count.html javascript part, send a request to another PHP file (say setSession.php) where i can have access to session variable.
So in setSession.php will write
session_start();
$_SESSION['v']=1;
header('Location:index.php');
Not possible. Because JavaScript is client-side and session is server-side. To do anything related to a PHP session, you have to go to the server.
be careful when doing this, as it is a security risk. attackers could just repeatedly inject data into session variables, which is data stored on the server. this opens you to someone overloading your server with junk session data.
here's an example of code that you wouldn't want to do..
<input type="hidden" value="..." name="putIntoSession">
..
<?php
$_SESSION["somekey"] = $_POST["putIntoSession"]
?>
Now an attacker can just change the value of putIntoSession and submit the form a billion times. Boom!
If you take the approach of creating an AJAX service to do this, you'll want to make sure you enforce security to make sure repeated requests can't be made, that you're truncating the received value, and doing some basic data validation.
I solved this question using Ajax. What I do is make an ajax call to a PHP page where the value that passes will be saved in session.
The example that I am going to show you, what I do is that when you change the value of the number of items to show in a datatable, that value is saved in session.
$('#table-campus').on( 'length.dt', function ( e, settings, len ) {
$.ajax ({
data: {"numElems": len},
url: '../../Utiles/GuardarNumElems.php',
type: 'post'
});
});
And the GuardarNumElems.php is as following:
<?php
session_start();
if(isset ($_POST['numElems'] )){
$numElems = $_POST['numElems'];
$_SESSION['elems_table'] = $numElems;
}else{
$_SESSION['elems_table'] = 25;
}
?>

How can i make jQuery(javascript) ajax form data sent less human readable?

Someone using firebug or chrome console could intercept the submitted form data and then switch some of the values, eg.
Sender's ID . I was wondering if I can make data sent less human readable so the attacker won't want to deal with it.
I saw something like this:
$.ajax({
type: "POST",
url: 'http://www.example.com/widget_category.php',
data: "p=eyJUcmF6ZW5pUG9qYW0iOiIiLCJJREdydXBhIjoiMzA3IiwiSURQb2RHcnVwYSI6MzA3LCJQcm9kYXZhYyI6IiIsIk9rcnV6aSI6W10sIk9wc3RpbmUiOltdLCJDZW5hT2QiOi0xLCJDZW5hRG8iOi0xLCJTdGFuamFQcmVkbWV0YSI6W10sIk5hY2luaVBsYWNhbmphIjpbXSwiRmlsdGVyIjpbXX0=",
dataType:'html',
success: function(res){
$('#limwidget').empty().append(res);
}
});
Edit:
I see this question was accepted bad. I just want to point out that i am validating all data received on the server side and there should be no question about that, but I just wanted to hide the real sensitive data from database ( and maybe make them also timestamp signed in some manner and different from user to user).
I realize that maybe this problem should be considered on server-side(php), that all sensitive data should be swaped on server-side instead of client-side, so we can avoid security by obscurity.
Thanks for clarifying
One more edit:
I see now that output from atob function from the example given
eyJUcmF6ZW5pUG9qYW0iOiIiLCJJREdydXBhIjoiMzA3IiwiSURQb2RHcnVwYSI6MzA3LCJQcm9kYXZhYyI6IiIsIk9rcnV6aSI6W10sIk9wc3RpbmUiOltdLCJDZW5hT2QiOi0xLCJDZW5hRG8iOi0xLCJTdGFuamFQcmVkbWV0YSI6W10sIk5hY2luaVBsYWNhbmphIjpbXSwiRmlsdGVyIjpbXX0=
is
{"TrazeniPojam":"","IDGrupa":"307","IDPodGrupa":307,"Prodavac":"","Okruzi":[],"Opstine":[],"CenaOd":-1,"CenaDo":-1,"StanjaPredmeta":[],"NaciniPlacanja":[],"Filter":[]}
so I guess that it's useless to start hiding data on client-side.
You can encode your data to base64 with atob() and btoa(), and then decode it in the server. Be aware that doing this will only obfuscate your code, and won't make it 100% secure.
Here's some info about Base64 encoding for JavaScript.
https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding
You should forget about having sensitive logic on client side and expect to be safe, there is no way to do that.
Even in case you "ofuscate" the output, that evil user could put a breakpoint before the ofuscation and change values at will.
If you concern is that someone could change the SenderID then, assuming is valid for your scenario, you could validate on server side that SenderID posted is the same that initiated request.
They can change anything on the front end even with this change. Everything sent to the client can be read, including any encryption code you use. It is harder potentially but you are confusing obfuscation for security.
Obfuscation will not solve the problem.
You should make it your priority to get your server side code to validate and sanitise the data that comes from the front end.
http://en.wikipedia.org/wiki/Security_through_obscurity
Base64, the content will be a bit longer, but widely supported, there're also command line tools to decode it.
I think it's safest to just assume that all data from the client is evil and add code on your server to validate and authorize where appropriate. You could encode your data and then decode it on the server, but JavaScript encoding/encryption is less useful than you might want. The attacker could always just open the dev console in the browser, inspect your code, and run whichever encryption method you use on their new malicious data.

How to hide the data in source code from the user

As a side project to learn Web Development, I'm writing a web app in Javascript that allows my fellow classmates type in our Class ID # to a search field. If they enter the correct Class ID, they will automatically be redirected to our Google Groups page. The only problem I'm seeing is that since I'm running multiple Google Groups for different classes that I'm taking, I don't know how to hide the javascript code.
Example in Pseudocode:
If (input === 12345){
redirect to (LinkToClass1GoogleGroupsPage.com)}
Else If (input === 12344){
redirect to (LinkToClass2GoogleGroupsPage.com)}
The problem here is if they right-click and view source code, they will clearly see what inputs I'm looking for. I'm new to Web Development and I would like to know what's the best way to implement something like this.
You cannot hide JavaScript code. If you have a secret, keep it on the server.
Anything on client-side environment is readable unless it is encrypted - what doesn't works with JavaScript. You can use a server-side environment to deal with that without leaving JavaScript with node.js, look this post.
Use an ajax request(jQuery or pure) to a node.js service or any other server-side language of your choice and keep those actions out of user's sight. This is safer, right and maybe only way to do that.
You cannot literally hide the data in JavaScript, unless you use a server-side language to redirect.
What you can do however is obfuscate your code, there are tools to help you do this.
http://javascriptobfuscator.com/
"LinkToClass2GoogleGroupsPage.com"
Results in
var _0x2ec6= ["\x4C\x69\x6E\x6B\x54\x6F\x43\x6C\x61\x73\x73\x32\x47\x6F\x6F\x67\x6C\x65\x47\x72\x6F\x75\x70\x73\x50\x61\x67\x65\x2E\x63\x6F\x6D"];_0x2ec6[0];
Probably the most secure way for this to be done would be to have a Server Side function that can be called via Ajax to return the link.
What type of Server Side code you use depends on your preferences.
For example ASP.NET Web Service, PHP, ASPX Web Methods.
Below is example Ajax Request Code using jQuery :
var o = new Object();
o.ID = input;
var x = JSON.stringify(o);
$.ajax({
url: 'SOME URL', //Path to the Server Side function (i.e. Php / ASPX Web Method / Web Service)
type: 'GET',
dataType: 'JSON',
contentType: 'application/json;charset=utf-8;',
data: x,
success: function (data) {
//Method returned without issue
redirect to (data.d)
//data is a JSON object that contains a "d" property, if your function returns a string then d will be the value of the string.
},
error: function (ajaxrequest) {
//Ajax call received an error.
}
})
This cannpt be done yet. HTML5 might have DRM implementations in the future but this will also depend on browsers opting in for this feature (Mozilla are against it for example).
Disable right click and ctrl button thats all you can do! :D

Get data from URL, or possibly ajax?

I was wondering how I can get data from the server side that is being passed to my page via encrypted url using java script? Let say I have this in visual basic in my code behind,
lnkToAPage.NavigateUrl = RelativePagePaths.ThePage + "?"+ QueryStringModule.Encrypt("PageMode=" + pageMode ...
I need to extract a piece of that data, which I get from an object on the server, to do something with it on the client side using javascript. I understand I can get the data from the url like it says here
but the data in the url is encrypted so the data I get from there is useless, I can send it without the encryption but that exposes to much. So is there a way I can use ajax to retrieve that data or object, or maybe there's another way? Or is it not possible at all?
I am not aware of what encryption protocol you are using, but if you get an encrypted version of your attributes, you need to decrypt it using the same protocol with javascript.
On the web, it is common practice (and a good one) to encrypt the connection using HTTPS. it protects anyone from seeing the parameters as explained here.
This does not seem to be an ajax related problem (from what I understood of the question).

Is there any way to hide javascript functions from end user?

I want to user jquery ajax calls, for example;
function addnewteacher(){
$.ajax({
type: "POST",
url: "/actions/dboss/newteacher.php",
data: "uname=" + $("#newteacheruname").val() + "&upass=" + $("#newteacherupass").val() + "&name=" + document.getElementById("newteachername").value + "&surname=" + document.getElementById("newteachersurname").value + "&mobile=" + document.getElementById("newteachermobile").value + "&email=" + document.getElementById("newteacheremail").value,
success: function(html){
$("#response").html(html);
$("#response").dialog("open");
}
});
}
As you can see, i have to give away the data part to end user. But i want to encrypt it with a hidden function then decrypt it on server so probably no one can send and malicious code to server just because that code wont make any sense after decryption if not properly encrypted. But i have to hide the function from user or make the function work only for me?
Thanks for any help/idea
You cannot hide JavaScript code. It gets downloaded to the client and executed there. You can obfuscate it, push it way deep inside, whatever you want, but a determined user can still find it. Your security really needs to be on the server, where you have complete control, not on the client, where you have no control at all.
Make sure calls to /actions/dboss/newteacher.php are authorized and verify they are coming from valid sources on the server. Security through obscurity is not security.
No. You can obfuscate them by minifying the code and that sort of thing, but you should never ever assume that your javascript is unreadable.
You need to validate and sanitize any user-submitted data on the server end.
No, sorry that's not possible. Everything you put in javascript will eventually be visible to the user. No matter how hard you try to minify/obfuscate the code, suffice to install FireBug and the password will popout at user eyes like a balloon.
Everything JavaScript does can be done by a user. Even if you think noone will even understand you code, he doesn't have to. He can just execute it and see what it gives. JavaScript should only be used as a way to make the UI more convenient, not to secure anything. Basically, what you want to is not to write a password in the JavaScript and check it in here when the user types it but you want to send the password written to the server that either says "yes" or "no". If you check a form with JavaScript, you have to recheck it on the server-side because JavaScript could be disabled and so on. JavaScript on its own isn't secured (as client-side language of course).
You can use something like Google Closure to obfuscate the Javascript code, but I'd really look into why you need to hide this in the first place since they will be messing up their own data. As long as you don't rely on the data being valid for server side functionality (such as injecting the input directly into SQL) you should be ok.
You should be trying to hide keys, not the function that signs the content.
I've seen a number of JS systems that do something like this:
<script>// Runs first
(function () {
// Look for a key in the URL like 'http://mysite.com/my/path?my=params#;key=abcd...
var key = document.location.hash.match(/;key=([^;]+)/)[0];
// Make sure other code on the page can't retrieve the key.
// This is analagous to a program zeroing out its argv to prevent
// key retrieval via /proc.
document.location = "#"; // Does not cause reload.
// define signature algo and export to whatever scope is appropriate.
...
})();
</script>
Obviously, this only works with single-use keys.

Categories