I am currently using eval in JavaScript to convert JSON data returned from the server into an object.
eval ("myObject="+data);
I've been told that eval is 'evil' and can open up big security problems.
I'm wondering - is using eval to convert JSON data to an object the accepted practice? Or is there a better way?
The reason eval is considered a bad practice is that user can evaluate anything that is sent from the server. This means if you have comments forum and the user submits some JavaScript code for the comments and you eval on the client side then your website can easily be hijacked.
I like the JQuery-Json plug-in. You can check it out using the following link:
link text
Related
I'm pretty new to the Pickle Library and JS. I am writing code in JS to interact with a Python server; when I make a POST to the Python server, I am returned a pickled float. I want to convert the float into a JS-readable object.
The server returns something like pickle.dumps(3.14159,0). When I print this value in Python, I get b'F3.14159\n.' However, the library I'm working with, JPickle, cannot interpret the 'b' in the return (or at least, that's what I'm guessing...when I try to unpickle my response using console.log(jpickle.loads(response)), I get a "unhandled opcode" error). Separate from the POST request, jpickle.loads('F3.14159\n.') gives me 3.14159, but jpickle.loads(b'F3.14159\n.') fails to compile. I'm not sure how to change the response I get from the POST because it is unreadable in JS, so I'm unsure how to go about solving this problem.
I'm open to any solutions that don't involve changing the server-side code (I don't have control over it), including using another library. I've tried JsonPickle with no luck.
Use just JSON, no pickle library required; Python comes with the json module and browser JS can, out of the box, parse json into values.
Serialize your data via something like json.dump and use JSON.parse in the browser to deserialize it.
A little late, but the answers in attached might help:: the code allows Javascript on a browser to traverse and decode compressed pickled objects coming from Python via Ajax.
Is there an already published Javascript solution to traverse Python pickled objects without using Node.js
Make sure that the mime type is allowing you to pass binary numbers.
A common question is how to pass an object from Node.js/Express.js to the browser. It's possible to do that using JSON stringify, but if the object contains user-provided data, that can open the door to script-injection and possibly other attacks.
Is there a downside to the approach mentioned in this link using Base64?
https://stackoverflow.com/a/37920555/645715
Related links:
Passing an object to client in node/express + ejs?
How to pass a javascript object that contains strings with quotes from node.js to the browser?
Pass a NodeJS express object to AngularJS 1.6
Passing an object to client in node/express + ejs?
Using Base64 encoding does solve the immediate problem of passing back an injection attack, but it doesn't necessarily solve the issue of having a possible injection attack floating around out there. For example, this fiddle shows that it does prevent the immediate issue : https://jsfiddle.net/9prhkx74/
var test2 = JSON.parse(window.atob('PC9zY3JpcHQ+PHNjcmlwdD5hbGVydCgndGVzdDInKTwvc2NyaXB0PjxzY3JpcHQ+'));
This won't show an alert box, it'll just throw an error about invalid JSON. But if you change it to the literal string, it'll show the alert box (injection vulnerable)
var test2 = JSON.parse("</script><script>alert('test2')</script><script>")
Now if you are immediately parsing it to a JSON object, it'll blow up, and everything will be "safe". But if you assign it to a value because you are going to pass it around some more etc, you still have a potential issue out there.
Instead of putting a bandaid on the injection itself, I'd suggest fixing it in the first place and properly escaping data before passing it back to the client or processing it on the server side.
There are plenty of libraries that can help do this
https://www.npmjs.com/package/sanitize
https://www.npmjs.com/package/express-sanitizer
Here's a pretty good article that kind of highlights why it is important to sanitize and not just just patch over potentially malicious data : https://lockmedown.com/5-steps-handling-untrusted-node-js-data/
I have a large-ish amount of server-side data that I need to store in a mySQL table. [I'm a novice, working through the learning curve of javascript & php.]
I'm thinking it's best to stringify the javascript array into a JSON object and send that to a PHP page to save to the database. Once the data's in a PHP array, I know how* to get it into the database; I'm just not sure what's the best way to get it there.
I can't POST (like this example) since the maximum length of a POST string is 2048 characters, and I have maybe 10-20kb of data.
I'd rather not use AJAX or Node.js (like this example) for the sake of simplicity, and since this is a one-off (but both on my list to learn in the future!)
Or, would it be best to create a temp text file to the server with javascript, and then call a PHP page to load & process the data? (Although I can't find examples of how to do that without using POST.)
I understand the difference between server-side & client-side (thanks to this great explanation) but the size limit of POST seems to be my issue?
*Also I'm a little unsure as to when/how it's necessary to encode data (like with this deprecated mysql-real-escape-string example) for storage with {json/posting/DB tables/text}. In this case my data could contain 'single' & "double" quotes (but no foreign characters 国外 वर्ण), which [in my short experience] seem like the only times it will be an issue?
Thanks!
The problem is that Javascript is client side language while PHP is server side language. This means that PHP cannot interact with the user without some HTML, CSS or JavaScript and visa-versa, JavaScript can't interact with server side files without some PHP. Why is this? Since JavaScript is client side the user can edit it as they can see the code while with a PHP script it is all on the server and they are not able to see the code, only what it outputs/prints. So in short you cannot do what you are asking without POST or GET and it is not possible to do this without a server side script such as a PHP script (Python is also very useful if you are thinking of learning more about web backends).
There are numerous example of how to do this that you can find with a simple google search, here is a great example send data to MySQL with AJAX + jQuery + PHP
Hope I could clarify your question.
Good day.
I'm new to jQuery, and have a passing familiarity with javascript, having spent most of my time on the server side.
My interest is in posting in the browser a multipart/form-data form object consisting of one text field and one file. In response, the server returns a multipart/mixed response consisting of one part html or json, and one part application/octet-stream.
My goal is to learn how to extract with jQuery the html or json part and optionally display it in a target div (if html) or redirect to a URL in the json (if json), and save the octet-stream to disk. Preferably in that order.
Would someone be kind enough to comment on whether such multipart/mixed response parsing is possible with jQuery and some idea of how to do this.
Actually, while I much prefer jQuery, I'll learn something from answers framed in any popular javascript framework, and even unadorned javascript itself.
Thank you.
GREAT question. Judging by the existence of this plugin im assuming no:
I also found this link in a discussion of that plugin, which might be helpful to you:
http://about.digg.com/blog/duistream-and-mxhr
Have a look at the jQuery's API. If your AJAX call returns HTML you can use the .load function. If it returns JSON you can use the .getJSON function.
Quick Question. Eval in JavaScript is unsafe is it not? I have a JSON object as a string and I need to turn it into an actual object so I can obtain the data:
function PopulateSeriesFields(result)
{
data = eval('(' + result + ')');
var myFakeExample = data.exampleType
}
If it helps I am using the $.ajax method from jQuery.
Thanks
Well, safe or not, when you are using jQuery, you're better to use the $.getJSON() method, not $.ajax():
$.getJSON(url, function(data){
alert(data.exampleType);
});
eval() is usually considered safe for JSON parsing when you are only communicating with your own server and especially when you use a good JSON library on server side that guarantees that generated JSON will not contain anything nasty.
Even Douglas Crockford, the author of JSON, said that you shouldn't use eval() anywhere in your code, except for parsing JSON. See the corresponding section in his book JavaScript: The Good Parts
You should use JSON and write JSON.parse.
"Manual" parsing is too slow, so JSON.parse implementation from the library checks stuff and then ends up using eval, so it is still unsafe. But, if you are using a newer browser (IE8 or Firefox), the library code is not actually executed. Instead, native browser support kicks in, and then you are safe.
Read more here and here.
If you can't trust the source, then you're correct...eval is unsafe. It could be used to inject code into your pages.
Check out this link for a safer alternative:
JSON in Javascript
The page explains why eval is unsafe and provides a link to a JSON parser at the bottom of the page.
Unsafe? That depends on if you can trust the data.
If you can trust that the string will be JSON (and won't include, for example, functions) then it is safe.
That said - if you are using jQuery, why are you doing this manually? Use the dataType option to specify that it is JSON and let the library take care of it for you.
If you are using jQuery, as of version 1.4.1 you can use jQuery.parseJSON()
See this answer: Safe json parsing with jquery?
Using JavaScript’s eval is unsafe. Because JSON is just a subset of JavaScript but JavaScript’s eval allows any valid JavaScript.
Use a real JSON parser like the JSON parser from json.org instead.
The alternative to evaluating the code is to parse it manually. It's not as hard as it sounds but it's quite a lot heavier at runtime. You can read about it here.
The important part to note is evaluating JSON is not inherently insecure. As long as you trust the source not to balls things up. That includes making sure that things passed into the JSON encoder are properly escaped (to stop people 2 steps up the stream executing code on your users' machines).
you can try it like this
var object = new Function("return " + jsonString)()
Another great alternative is YUI:
http://yuilibrary.com/yui/docs/json/
So your code would be something like:
Y.JSON.parse('{"id": 15, "name": "something"}');