Encoding/Decoding Javascript in Nashorn - javascript

I use the technique described here:
http://scriptasylum.com/tutorials/encode-decode.html
In a nutshell, one has a javascript file that looks like this, where the actual javascript is encoded:
document.write( unescape( 'escaped string' ) ); dF('encoded javascript');
I now want to run that same .js module under Nashorn, but Nashorn does not have a document object. Therefore, I can not do document.write().
Note: It is well known that this technique is easily bypassed and people modest technical ability can still look at the actual code. My use case does not require strong security so that is not a concern. That said, Please consider answers on why one should not do this as off topic. Thanks.

Basically, that code breaks down into two parts:
Un-obfuscate the string via unescape.
Write the string out via document.write.
It sounds like you want to use the string directly for some reason.
You have at least two options:
You can provide a document object to the scripting engine with a write method that accepts a string. Then you can do with it what you like. (Or substitute document.write before evaluating the string with any function you want called.)
Remove the document.write( and the corresponding ) at the end and have the engine evaluate the string and hand it to you directly as the result of ScriptEngine#eval.
Either way, you'll end up with a string that you can then do something with.

Related

Scanf and Printf in JS

I'm studying to a Championship in Brazil. But I need help because I will do this in JS, but the problem is, they ask to answer with Scanf and Printf. How can I do this in JS? Thanks.
Ps: Its not document.write or something, need Scanf and Printf, if it dont exist in JS, please, let me some link and i will study how works syntax of Scanf and Printf.
First of all...
JavaScript is a general purpose programming language which can be executed in multiple different environments. Each one has it's own way of processing input and output operations.
As you didn't specify which competition is that, I'll assume you're talking about OBI, promoted by UNICAMP (the only one I know that accepts JS solutions and require standard I/O on them). If this is the case, a development environment called Saci is used to run and evaluate JavaScript submissions.
If you want to learn more about writing JS code for the Saci environment, you can search here.
Now, answering your question, two methods are used for standard I/O operations in this environment: scanf and printf. They work like C input/output methods with a few differences.
Writing with printf()
This method work exactly like its C equivalent. You'll see it in the following format:
printf(format, ...);
The first parameter is a string containing the text to be written to stdout. It can optionally contain embedded format tags that will be replaced by the values you specify in the next parameters.
Here's an example:
let x = 34;
printf("%d is an integer\n", x);
Reading with scanf()
This method will work like its C equivalent with two differences: each variable must be specified in quotes, and it'll only work with global variables. You'll find this method in the following format:
scanf(format, ...);
The first parameter is a string containing the format tags used to assign each value to its corresponding variable, which should be informed in the next parameters.
Here's an example:
let x, y;
scanf("%d%d", "x", "y");
console.log stuff supports the format specifiers a little, but not that useful.
If you are finding one for web browsers, you can use sprintf.js and prompt().
If you are finding one for Node.js:
Is there a sprintf equivalent for node.js
C scanf equivalent in nodejs

Go templating engine that also runs in the browser

I'm developing a web application with Go on the server, and the router will use PushState, so the server will also have to be able to render my templates. That means that I'll need a templating engine that works with Go and Javascript. The only one I've come across so far is Mustache, but it doesn't seem to be able to handle lowercase properties of structs, and there also doesn't seem to be a possibility to provide custom names like JSON:
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
So, is there a templating engine that is available in both Go and JavaScript, and that can handle lowercase struct properties?
As the comments above state, you can't expect any 3rd party library to be able to read lowercase properties on your struct, but it appears you are trying to use tags to represent alternative representations of your struct (as you can with the encoding/json library).
What you can do is use something like github.com/fatih/structs to convert your structs to maps and then range through to lowercase all of your keys (copying the values and removing the uppercase versions) and pass it into mustache.Render() as your context. If you want to use struct tags like the encoding/json library does, you'd have to use the reflect package and write a struct-to-map function that takes into account the tags on the struct (basic example given in the documentation here). There are some SO answers on how to write a struct-to-map function using reflection, which you can improve upon to add struct tag handling as you need.
To answer your question, I don't think this is something a current templating library does that also works with javascript, but it shouldn't be too hard to get working with mustache given the idea above.

javascript codes refacting using ruby

Suppose I have some javascript code like this:
function Person(){}
var pro=Person.prototype;
pro["setName"]=function(){}
pro["setAge"]=function(){}
....
Now,I will use the closure compiler to minify the source codes.
However,since Closure Compiler compilation never changes string literals,so I want to replace the myself.
So before compile the codes,I want to replace the string literals like this:
var a="setName",b="setAge";
function Person(){}
var pro=Person.prototype;
pro[a]=function(){}
pro[b]=function(){}
I want to use ruby to do this job,then I have two questions:
1)how to do the replacement?
I tried scan the files line by line,but how to find the string literals and do the replacement?
2)code conflict
Since I have to generate the variables like 'a,b',how to make sure that they are not conflict with my source codes? For example,I generate code like this:
var something="setName";
then how about if there is a varible or function named "something" defined in my source code?
If for some reason you are concerned about raw JS size instead of compressed JS (most people should only worry about compressed size). Perhaps you should consider enabling the "alias all strings" compiler options (available in the Closure Compiler's Java API)?
Instead of doing this you should consider using gzip to compress your files after closure minifies them.
gzip works by finding duplicated strings in the input data and replaces the second occurrence of the string with a pointer to the previous string. It will do this to all your input data, not just javascript string literals.
http://www.gzip.org/
I don't think your overall idea is correct, and I particularly think that doing 1) is too complicated to be able to answer within a single webpage. For 2), it is similarly difficult to do it from outside of the Javascript code, but you may be able to adjoin the original Javascript code with a couple of lines, referencing Here, run the Javascript, and get the list of variables.

JavaScript to evaluate simple math string like 5*1.2 (eval/white-list?)

I have an input onchange that converts numbers like 05008 to 5,008.00.
I am considering expanding on this, to allow simple calculations. For example, 45*5 would be converted automatically to 225.00.
I could use a character white-list ()+/*-0123456789., and then pass the result to eval, I think that these characters are safe to prevent any dangerous injections. That is assuming I use an appropriate try/catch, because a syntax error could be created.
Is this an OK white-list, and then pass it to eval?
Do recommend a revised white-list
Do you recommend a different approach (maybe there is already a function that does this)
I would prefer to keep it lightweight. That is why I like the eval/white-list approach. Very little code.
What do you recommend?
That whitelist looks safe to me, but it's not such a simple question. In some browsers, for example, an eval-string like this:
/.(.)/(34)
is equivalent to this:
new RegExp('.(.)').exec('34')
and therefore returns the array ['34','4']. Is that "safe"?
So while the approach can probably be made to work safely, it might be a very tricky proposition. If you do go forward with this idea, I think you should use a much more aggressive approach to validate your inputs. Your principle should be "this is a member of a well-defined set of strings that is known to be 'safe'" rather than "this is a member of an ill-defined set of strings that excludes all strings known to be 'unsafe'". Furthermore, to avoid any risk of operators peeking through that you hadn't considered (such as ++ or += or whatnot), I think you should insert a space in front of every non-digit-non-dot character; and to avoid any risk of parentheses triggering a function call, I think you should handle them yourself by repeatedly replacing (...) with a space plus the result of evaluating ... (after confirming that that result is a number) plus a space.
(By the way, how come = is in your whitelist? I just can't figure out what that's useful for!)
Given that extremely restrictive whitelist, I can't see any way of performing a malicious action beyond throwing an exception. The bracket trick won't work since it requires square brackets [].
Perhaps the safest option is to modify your page's default values parser to only accept numbers and throw out anything else. That way, potentially malicious code in a link will never make it to eval.
This only leaves the possibility of the user typing something malicious into a field, but why even bother worrying about that? The user already has access to a console (Dev Tools) they could use to execute arbitrary code.
An often overlooked issue with eval is that it causes problems for javascript minifiers.
Some minifiers like YUI take the safe route and stop renaming variables as soon as they see an eval statement. This means your javascript will work but your compressed file will be larger than it needs to be.
Other's like Google Closure Compiler will continue to rename variables but if you are not careful they can break your code. You should avoid passing strings with variable names in it to eval. so for example.
var input = "1+2*3";
var result = eval("input"); // unsafe
var result = eval(input); // safe

Writing a Parser for javascript code

I want to extract javasscript code and find out if there are any dynamic tag creations like document.createElement('script'); I have tried to do this with Regular expressions but using regular expressions restricts me to get only some formats so i thought of writing a javascript parser which extracts all the keywords, strings and functions from the javascript code.
In general there is no way to know if a given line of code will ever run, you would need to solve the halting problem.
If you restrict your analysis to just finding occurances of a function call you don't make much progress. Naive methods will still be easy to trick, if you just regex match for document.createElement, you would not be able to match something as simple as document["create" + "Element"]. In general you would need to not only parse the code but evaluate it as well to get around this. And to be sure that you can evaluate the code you would again need to solve the halting problem.
Maybe you should try using Burrito
Well the first rule is never use regex for big things like this, or DOM, or ... . You have to parse it by tokens. The good news is that you don't have to write your own. There are a few JS to JS parsers.
UglifyJS
narcissus
Esprima
ZeParser
They may be a bit hard to work with it. But well better to work with them. There are other projects that are uses these such as burrito or code surgeon. So you can have a look at the source code and see how they uses them.
But there is bad news too, which people can still outsmart other people, let alone the parsers and the code they write. At least you need to evaluate the code with some execution time variables and see if it tries to access the DOM or not.

Categories

Resources