Ajax inside wordpress security - javascript

Before I get to the question, let me explain how we have things set up.
We have a proxy.php file, in which class Proxy is defined with functions that call upon a rest for creating/editing/getting Wordpress posts, fields etc.
Then, we have a proxyhandler.php, in which Proxy class is initialized and serves as a handle between proxy.php and a javascript file.
In javascript file we have an ajax call to proxyhandler.php in which we send our secret and other data.
Now, the problem arises here:
We define the secret through wp_localize_script, by using md5 custom string + timestamp. We send the encripted string and timestamp through ajax to proxy handler, where we use the previous (hardcoded inside proxyhandler) string and timestamp to generate a md5 string again, and check the one sent against the one generated. If they are the same, we continue by doing whatever was requested, if they dont fit, we just return that the secret didn't match.
Now, the real issue comes here - by using wp_localize_script, the variable for the secret is global and as such, anyone can utilize it via dev tools and can send any ajax request to proxyhandler that they want.
What would be the proper procedure to make it more secure? We've thought of doing this:
Instead of using wp_localize_script, we put the script inside a php file, we define the secret using a php variable and then simply echo the secret file into ajax. Would this be viable, or are there any other ways?

Instead of sending an encrypted string in global scope, then check against it, you should use nonce in your AJAX request:
var data = {
action: 'your_action',
whatever_data: who_know,
_ajax_nonce: <?= wp_create_nonce('your_ajax_nonce') ?>
};
Then, use check_ajax_refer() to verify that nonce:
function your_callback_function()
{
// Make sure to verify nonce
check_ajax_refer('your_ajax_nonce');
// If logged in user, make sure to check capabilities.
if ( current_user_can($capability) ) {
// Process data.
} else {
// Do something else.
}
...
}
Depend on the AJAX METHOD, you can use $_METHOD['whatever_data'] to retrieve who_know data without needing to use wp_localize_script().
Also remember that we can allow only logged in users process AJAX data:
// For logged in users
add_action('wp_ajax_your_action', 'your_callback_function');
// Remove for none logged in users
// add_action('wp_ajax_nopriv_your_action', 'your_callback_function');
The final thing is to make sure NONCE_KEY and NONCE_SALT in your wp-config.php are secure.

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.

Call model function from JavaScript in Laravel

I'm actually running into little problems with my current project. Following case:
I've got a model called "Posting" with relations:
public function subscribers(){
return $this->belongsToMany('User');
}
In my view-file there is a table containing all Postings and also a checkbox for subscribing/unsubscribing with the matching value to the posting-id:
<input class="click" type="checkbox" name="mobileos" value="{{{$posting->id}}}"
#if($posting->subscribers->find(Auth::User()->id))
checked="checked"
#endif
>
Now the thing I want to archive:
A JavaScript is going to watch if the checkbox is checked or not. According to that, the current user subscribes/unsubscribes to the posting. Something like:
$('.click').on('click',function() {
// $posting->find(---$(this).prop('checked')---)->subscribers()->attach(---Auth::user()->id---);
// $posting->find(---$(this).prop('checked')---)->subscribers()->detach(---Auth::user()->id---);
});
Is there any possibility to archieve that or any other ways? I couldn't get my head around this so far.
Cheers,
Chris
If you want to use Ajax to achieve this, you will need a REST endpoint in Laravel for the subscriptions, e.g.:
http://localhost/subscribe/{{userid}}
When this Endpoint is called, the database can be updated. The function could also return a JSON showing, if the saving database in the database successful.
Use this endpoint to make an Ajax Call on click:
var user = {
id: 0 // retrieve the correct ID from wherever it is stored
}
$('.click').on('click',function() {
$.GET('http://localhost/subscribe/' + user.id,
function () { // this is the success callback, that is called, if the Ajax GET did not return any errors
alert('You are subsribed')
});
});
Ideally you won't be using the GET method, but instead use POST and send the user ID as data. Also you would need to retrieve the user ID from session or wherever it is stored.
Take care that as you are using Ajax it can easily be manipulated from the client side. So on the server you should check, if the user ID that was sent is the same as in the Session. Maybe you don't need to send the user id at all, but that depends on how your backend is built.

fetch data from a url in javascript [duplicate]

This question already has answers here:
Ways to circumvent the same-origin policy
(8 answers)
Closed 9 years ago.
I am trying to fetch a data file from a URL given by the user, but I don't know how to do. Actually, I can get data from my server successfully. Here is my code:
$("button#btn-demo").click(function() {
$.get('/file', {
'filename' : 'vase.rti',
},
function(json) {
var data = window.atob(json);
// load HSH raw file
floatPixels = loadHSH(data);
render();
});
});
It can fetch the binary data from my server, parse the file and render it into an image. But now I want it work without any server, which means users can give a URL and javascript can get the file and render it. I know it's about the cross-site request. Can you tell me about it and how to realize it?
Thanks in advance!
assuming your URL is the address of a valid XML document this example will go grab it. if the URL is on a different domain than the one that's holding your scripts you will need to use a server side scripting language to got out and grab the resource (XML doc at URL value) and return it your domain. in PHP it would be ...
<?php echo file_get_contents( $_GET['u'] );
where $_GET['u'] is a URL value from your USER. let's call our PHP script proxy.php. now our JavaScript will call our proxy.php and concatenate the URL value to the end which will allow us to pass the URL value to the PHP script.
addy = $("#idOfInputFieldhere").val();
$.ajax({
url: 'proxy.php?u='+addy, /* we pass the user input url value here */
dataType:'xml',
async:false,
success:function(data){
console.log(data); /* returns the data in the XML to the browser console */
}
});
you'll need to use the js debugger console in chrome to view data. at this point you'd want to pull out data in a loop and use find() http://api.jquery.com/?s=find%28%29
I'm not very familiar with jQuery, but as I know, due to the same origin policy, the browser won't let any JavaScript code to make an AJAX request to a domain other than its own. So in order to retrieve some data (specially JSON formatted), you can add a <script> element to your page dynamically and set its src property to the address of the data provider. Something like this:
<script src='otherdomain.com/give_me_data.json'/>
This only works if you need to access some static data (like the url above) or you have access to the server side code. Because in this scenario, the server side code should return an string like:
callbackFunction({data1: 'value1', data2: 'value2', ...});
As the browser fetches the item specified in src property, tries to run it (because it know it's a script). So if the server sends a function call as a response, the function would be called immediately after all data has been fetched.
You can implement the server side in such a way that it accepts the name of the callback function as a parameter, loads requested data and generates an appropriate output that consists of a function call with loaded data as a json parameter.

Pass client side value to server side

I need to use a javascript variable value in server side.
Example:
JavaScript
var result = false;
CS Code
if(result)
{
Console.Write("Welcome..")
}
else
{
Console.Write("plz try again..")
}
Note
I don't want to post a hidden field.
With each request, any server side code will run and then any client side code will run. You can't switch between them at will.
Your options are:
Provide all the data to the client in the first place, then use JS to decide which of them to keep/delete/show/hide/etc
Use Ajax to make a second request to the server with the data you get from JS, return content, and then do something with that content in the JS callback function.
Make a second request to the server and load a complete new page.
Remember to build on things that work.
best way to do this use hidden fields...

Make an ajax request to get some data, then redirect to a new page, passing the returned data

I want to redirect after a successful ajax request (which I know how to do) but I want to pass along the returned data which will be used to load an iframe on the page I just redirected to.
What's the best way to pass such data along and use it to open and populate an iframe in the page I just redirected to?
EDIT:
I am passing a GET variable but am having to use the following to access it for use in my iframe src attribute:
function $_GET(q,s) {
s = (s) ? s : window.location.search;
var re = new RegExp('&'+q+'=([^&]*)','i');
return (s=s.replace(/^\?/,'&').match(re)) ? s=s[1] : s='';
}
var d = $_GET('thedata');
I assume there isn't really a more straightforward way to access the GET vars?
If it's not too much data, you could pass it as a get parameter in the redirect:
document.location = "/otherpage?somevar=" + urlescape(var)
Remember that urls are limited to 1024 chars, and that special chars must be escaped.
If it is beyond that limit your best move is to use server side sessions. You will use a database on the server to store the necessary information and pass a unique identifier in the url, or as a cookie on the users computer. When the new page loads, it can then pull the information out of the database using the identifier. Sessions are supported in virtually every web framework out of the box.
Another alternative may be to place the data as a hidden attribute in a form which uses the post method (to get around the 1024 char limit), and simulating a submission of the form in javascript to accomplish the redirect, including the data.

Categories