Reading windows registry Reg_SZ in javascript - javascript

first time posting here!:)
As title says I have a win reg fie (reg_sz) which contains "name" and "value"
this.reg = new Registry.Key(Registry.windef.HKEY.HKEY_CURRENT_USER, 'Path\Path\Path', Registry.windef.KEY_ACCESS.KEY_READ);
funct read(this.reg){
var value;
var pushes = [];
[
"food",
"veggy",
"etc",
"etc"].forEach(function(name) {
try {
value = key.getValue(name);
entries.push({name: name, value: value});
} catch (e) {
}
});
return pushes;
};
example: "food"="apple"
Which my code reads properly, however I came across a issue with special characters, example "ä"
"food"="äpple"
which my code reads as �pple.
My question is what kind of decoding/encoding should i use and what is with this win registry, what exactly are they using? Can it be raw JS preferably and if not what else? I tried using decodeURI/encodeURI but seems like its not the correct approach(dont know what encoding they are using and which decoding should I use)
TLDR: How can i type in "äpple" in win registry and when reading that file with JS get same "äpple" instead of "�pple"

It looks like you're using windows-registry-node. This is unfortunately a bug in that, #44. The reporter says:
If i return the raw buffer and use iconv to convert from "ISO-8859-1" to "UTF-8" i get the correct characters
Note that this is assuming the current code page of the system, though, and might not always be correct. (It might be possible to tell iconv to detect and use the current code page?)
The exact problem is in registry.js:
// READ VALUE
result = advApi.RegQueryValueExA(key.handle.deref(), valueName, null, pKeyType, value,
pKeyDataLength);
Here it uses RegQueryValueExA, which means fetch strings as the current Windows code page, as opposed to RegQueryValueExW which would use UTF-16. So value, which is a Node.JS Buffer, does not contain UTF-8. The code then calls Buffer.toString(), which assumes UTF-8 by default:
if (value.type === types.LPTSR) {
// TODO not sure why buffer's utf8 parsing leaves in the unicode null
// escape sequence. This is a work-around (at least on node 4.1)
value = value.toString().replace('\u0000', '');
}
So this is going to need a fix in windows-registry-node. The best fix is probably to set the code up for UTF-16, using the -W version of the function and value.toString('utf16le');

Related

Nodejs not recognizing string(Input in Japanese)

I am trying to take an input in Japanese language and pass the value as parameter to another function to retrieve data from the function but whenever I run node app.js it doesn't recognize the input. But in the browser it is working just fine.
So it is accessing data from json const innerArray = { Name : 'Test', Prefecture: '東京都' }
While accessing it:
let prefectureName = innerArray.Prefecture
console.log(prefectureName)
The output is ???
When I use the input in english it also works. Then I also tried to convert the japanese input into english. then again the same problem remains as it can not read the input.
Can anyone help me regarding this matter?
I suspect this is only a problem in your log console. Node.js uses UTF-16 internally, so Japanese characters are fully supported.
I'd suggest trying the following:
const fs = require("fs");
const innerArray = { Name : 'Test', Prefecture: '東京都' }
fs.writeFileSync("test.json", JSON.stringify(innerArray), "utf8");
console.log("innerArray:", innerArray);
Then open test.json in something like Notepad++, you should see the characters rendered correctly.
If I try this example in Visual Studio Code, the output is fine too since the console or output font has support for Japanese Characters.

Javascript crashes on special characters from query string

To use this value in my TypeScript I am getting it from my query string like this:
var UserName = #Request.QueryString["UserName"];
But I get a Unexpeted Identifier error on it because if in DevTool if I go to where it breaks that query string has a value like this:
var UserName = ANT -- ANT 37690 / THIRD PARTY
So is there a way to do some kind of sanitation on it so it wouldn't crash? I guess there are illegal characters in that value for JS?
The error has nothing to do with "special" characters, but with the fact that the right side of the assignment - unwrapped in quotes - contains what js engine views as unknown identifier[s].
One way to properly format data that becomes part of javascript code is to use JavaScriptSerializer class from System.Web.Script.Serialization namespace.
var UserName = #new System.Web.Script.Serialization.JavaScriptSerializer().Seria‌​lize(Request.Query‌​St‌​ring["UserName"]);
The shorter version of this for a string is:
var UserName = "#System.Web.HttpUtility.JavaScriptStringEncode(Request.Query‌​St‌​ring["UserName"])";
or overloaded version that wraps the result in double quotes:
var UserName = #System.Web.HttpUtility.JavaScriptStringEncode(Request.Query‌​St‌​ring["UserName"], true);
You need to include quotes for the value.
var UserName = "#(Request.QueryString["UserName"])";
Otherwise the name will come through verbatim in your code and cause the problems you are seeing.
There is no need to protect against an attack vector here as the user can alter the page as they see fit at any time with a user script, and the QueryString is entered by them and only seen as a result by them in this scenario.
If there was a need to scrub the user input, it should be done prior to it actually reaching the view on server side. However, if still concerned about scrubbing output into a view in this type of scenario in general, it would be prudent to include an encode from razor's library.
var sanitizedJsVariable = "#System.Web.HttpUtility.JavaScriptStringEncode(model.VariableFromServer)";

"%" is getting URI decoded while everyhting else not

I have a strange UI5 problem. I create a string from a control's binding context which looks like:
Entity('Element%3AInfo%2CID')
Just for info, it looks like this decoded: Entity('Element:Info,ID')
However, I get this String from the following method chain:
oItem.getBindingContext().getPath().substr(1)
So, the whole (pretty basic) "navigate to" block looks like this:
showElement : function (oItem) {
'use strict';
var bReplace = jQuery.device.is.phone ? false : true;
sap.ui.core.UIComponent.getRouterFor(this).navTo("element", {
from: "master",
element: oItem.getBindingContext().getPath().substr(1),
otherpattern: "something"
}, bReplace);
},
A console log in this block console.log(oItem.getBindingContext().getPath().substr(1)); provides the right string.
Console output of console.log(oItem.getBindingContext().getPath().substr(1)):
Entity('Element%3AInfo%2CID')
The problem is (be aware, this is getting curious) that my URL pattern "{element}" is filled with:
Entity('Element%253AInfo%252CID')
Decoded: Entity('Element%3AInfo%2CID')
As you probably already know, the pattern's "%" is encoded. I don't get why UI5 would do this.
You should also know these facts which I've tested:
decodeURIComponent(oItem.getBindingContext().getPath().substr(1)) leads to "Entity('Element:Info,ID')"
encodeURIComponent(oItem.getBindingContext().getPath().substr(1)) leads to "Entity('Element%25253AInfo%25252CID')"
oItem.getBindingContext().getPath().substr(1).replace("%3A", ":") leads to "Entity('Element:Info%252CID')"
Is this a bug? I mean the URI pattern is left untouched as long as it doesn't come to a "%". For some odd reason this special character is encoded while everything else doesn't matter.
Its not exactly like "%" is getting encoded and everything else is not encoded.
I also came across this issue. SAPUI5 does encoding once, and browser does it second time. Hence in the second iteration you will have only "%" to be encoded.
Initial string : Element:Info,ID
after first iteration of encoding(by UI5 framework) encodeURIComponent('Element:Info,ID') : We get Element%3AInfo%2CID
So for the second iteration, only % is left to be encoded Element%253AInfo%252CID hence we get this.
So if you are picking up the binding context from URL, you need to decode twice.
Else as you are doing once is fine.

readFileSync won't work with me. I tried to print the input after setting it to string but was weird

Im new to Node.js and I'm trying to learn alone. I have a simple task to do the following:
-read a file (supplied buy the first command line argument).
-print the number of lines in the file.
-I am using the readFileSync method.
The code is running but the output is weird. I tried printing every statement, and I think the problem is in the reading of the data. Can anyone please tell me where I'm wrong?
function numLines(){
var fs = require('fs');
var num = 0;
var contents = fs.readFileSync(process.argv[0]);
console.log(contents.toString());
return num;
}
disregard the return statement, please just focus on the readFileSync. While printing the contents, the text printed is full of weird characters, as if the reading is going wrong
var contents = fs.readFileSync(process.argv[0]);
process.argv[0] is not the first argument passed to your script, actually. It's the command node. The second item is the filename of the your script, which is passed to node, assuming you're calling it as node myscript.js somefile.txt. You need to get the third item: process.argv[2]
See https://nodejs.org/api/process.html#process_process_argv
Without an encoding, readFile and readFileSync give you back a raw buffer you have to interpret in the correct encoding yourself (rather than just calling toString on it). From the docs:
If no encoding is specified, then the raw buffer is returned.
So either specify the encoding of the file in the readFileSync call, or use a buffer methods to read it using a given encoding. The Buffer docs talk about the encodings supported by Node, such as utf8.
So for instance, if your file is in UTF-8, you'd use:
function numLines(){
var fs = require('fs');
var num = 0;
var contents = fs.readFileSync(process.argv[0], {encoding: 'utf8'});
console.log(contents.toString());
return num;
}
More: The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)

I need a Javascript literal syntax converter/deobfuscation tools

I have searched Google for a converter but I did not find anything. Is there any tools available or I must make one to decode my obfuscated JavaScript code ?
I presume there is such a tool but I'm not searching Google with the right keywords.
The code is 3 pages long, this is why I need a tools.
Here is an exemple of the code :
<script>([][(![]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]+(!![]+[])[+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[!+[]+!+[]]]()[(!![]+[])[!+[]+!+[]+!+[]]+(+(+[])+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+!+[]+[+[]]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]])(([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+
Thank you
This code is fascinating because it seems to use only nine characters ("[]()!+,;" and empty space U+0020) yet has some sophisticated functionality. It appears to use JavaScript's implicit type conversion to coerce arrays into various primitive types and their string representations and then use the characters from those strings to compose other strings which type out the names of functions which are then called.
Consider the following snippet which evaluates to the array filter function:
([][
(![]+[])[+[]] // => "f"
+ ([![]]+[][[]])[+!+[]+[+[]]] // => "i"
+ (![]+[])[!+[]+!+[]] // => "l"
+ (!![]+[])[+[]] // => "t"
+ (!![]+[])[!+[]+!+[]+!+[]] // => "e"
+ (!![]+[])[+!+[]] // => "r"
]) // => function filter() { /* native code */ }
Reconstructing the code as such is time consuming and error prone, so an automated solution is obviously desirable. However, the behavior of this code is so tightly bound to the JavaScript runtime that de-obsfucating it seems to require a JS interpreter to evaluate the code.
I haven't been able to find any tools that will work generally with this sort of encoding. It seems as though you'll have to study the code further and determine any patterns of usage (e.g. reliance on array methods) and figure out how to capture their usage (e.g. by wrapping high-level functions [such as Function.prototype.call]) to trace the code execution for you.
This question has already an accepted answer, but I will still post to clear some things up.
When this idea come up, some guy made a generator to encode JavaScript in this way. It is based on doing []["sort"]["call"]()["eval"](/* big blob of code here */). Therefore, you can decode the results of this encoder easily by removing the sort-call-eval part (i.e. the first 1628 bytes). In this case it produces:
if (document.cookie=="6ffe613e2919f074e477a0a80f95d6a1"){ alert("bravo"); }
else{ document.location="http://www.youtube.com/watch?v=oHg5SJYRHA0"; }
(Funny enough the creator of this code was not even able to compress it properly and save a kilobyte)
There is also an explanation of why this code doesn't work in newer browser anymore: They changed Array.prototype.sort so it does not return a reference to window. As far as I remember, this was the only way to get a reference to window, so this code is kind of broken now.

Categories

Resources