Simplest way to "unpack" obfuscated javascript from within a Java program - java

Let's say that you have a web page that only contains obfuscated Javascript in the form of an eval(...) function within a script tag.
Dean Edwards' online unpacker (link) correctly unpacks this Javascript.
I would like to write a simple Java class that loads the initial web page (I use HttpClient), extracts the eval(...) function from the HTML, and unpacks it, in order to obtain the de-obfuscated Javascript.
I've tried with Rhino, here's my code :
int start = html.indexOf("<script>eval") + "<script>".length();
int end = html.indexOf("</script>");
javascript = html.substring(start, end);
evaled = eval(javascript);
NativeFunction fEvaled = (NativeFunction) evaled;
String encodedSource = fEvaled.getEncodedSource();
log.info("encodedSource: " + encodedSource);
and the "eval" java function called:
private Object eval(String javascript){
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("JavaScript");
Object eval = null;
try {
eval = engine.eval(javascript);
} catch (ScriptException e) {
// TODO Auto-generated catch block
log.error("Exception evaluating javascript " + javascript, e);
}
return eval;
}
But, that doesn't work, the code returned is far from being the correct code (returned by Edwards' unpacker). I've inspected the Rhino variables, found nothing useful.
Am I doing something wrong ?
I'm open to any suggestion, for example if there's a command-line tool that will work I can make a system call.
I'm on Ubuntu.
Thanks.

Related

How to call javascript from java code

I have no idea how to do this and found some examples of how to call it however creating the script in java code (what I don't want), in ASP.NET I would use this code ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "info only", "alert('" + message + "');", true); to call my script + pass parameters and would work fine as I wished. However I have no idea of how to do this in java. Thank you
Simply by googling I found this link which provides good examples on how to invoke a javascript file.
Here is a simple example to get you going:
import java.io.*;
import javax.script.*;
public class App
{
public static void main(String[] args)
{
String file = "javascript.js";
try
{
ScriptEngine engine =
new ScriptEngineManager().getEngineByName("javascript");
FileReader fr = new FileReader(file);
engine.eval(fr);
}
catch(IOException ioEx)
{
ioEx.printStackTrace();
}
catch(ScriptException scrEx)
{
scrEx.printStackTrace();
}
}
}
I saw that it wasn't possible to call my javascript via Servlet, however if I just pass my parameters using my resp/req objects and retrieve them in my JSP page and my JSP page call myt javascript method would work.
Anyway here is the code I used:
Check if my params arent empty and call my script
<c:if test="${not empty errors}">
<script>displayErrors(errors);</script>
</c:if>
The script I would like to call (sample):
<script>
var errors = ${errors};
if (errors.length) {
displayErrors(errors);
}
</script>
And I found this answer here (How to call function of JavaScript from servlet)
Big thanks for everybody

How to execute the Windows 'printto' verb using Java?

In the past I have used the 'printto' verb to print PDFs from with a .Net application. It looked something like this:
ProcessStartInfo psi = new ProcessStartInfo(file);
psi.Verb = "printto"; // print to given printer
psi.Arguments = "LPT1";
psi.CreateNoWindow = true;
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.ErrorDialog = true;
Process.Start(psi);
How can I do this from a Java application? Or is there an alternative approach? Note that the target platform will always be Windows.
Please try this.
public void print() {
//The desktop api can help calling native applications in windows
Desktop desktop = Desktop.getDesktop();
try {
desktop.print(new File("yourFile.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
Please Note : This is the easy fix. You can also use java's Print API to achieve the same thing

How to integrate googlemap api javascript from a webpage into java program?

from what I've read it seems to be possible to run some javascript within a java program, however I'm still struggling on fully grasping how. Would I be able to do enough to execute a googlemap api to be displayed in my java program?
The two examples of code that I have been looking at is this in java:
import javax.script.*;
public class script {
public static void main(String[] args) throws Exception {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
// JavaScript code in a String
String script = "function hello(name) { print('Hello, ' + name); }";
// evaluate script
engine.eval(script);
// javax.script.Invocable is an optional interface.
// Check whether your script engine implements or not!
// Note that the JavaScript engine implements Invocable interface.
Invocable inv = (Invocable) engine;
// invoke the global function named "hello"
inv.invokeFunction("hello", "Scripting!!" );
}
}
and this as an example found on the google doc site in javascript to produce this:
var center = new google.maps.LatLng(37.4419, -122.1419);
var options = {
'zoom': 13,
'center': center,
'mapTypeId': google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), options);
var markers = [];
for (var i = 0; i < 100; i++) {
var latLng = new google.maps.LatLng(data.photos[i].latitude,
data.photos[i].longitude);
var marker = new google.maps.Marker({'position': latLng});
markers.push(marker);
}
var markerCluster = new MarkerClusterer(map, markers);
If any of you can assist me in understanding how to integrate these two samples of code so that the map appears in a JPanel instead of "hello world", I think I could figure the rest of it out.
UPDATE: After reading through the terms of usage, I found out that I would be violating the terms, however; if I move the map onto our organizations public site, I should be able to load the result of that script into my Java programs JPanel which would give public access to the map and not be in violation. Am I correct? Is this possible to do? I don't have any experience with javascript.
I don't know much about integrating Google map script with or the integration policies.
But, you can execute JavaScript file from your java code.So i feel you can write your script code in a js file and execute it as follows :
import javax.script.*;
public class EvalFile {
public static void main(String[] args) throws Exception {
// create a script engine manager
ScriptEngineManager factory = new ScriptEngineManager();
// create JavaScript engine
ScriptEngine engine = factory.getEngineByName("JavaScript");
// evaluate JavaScript code from given file - specified by first argument
engine.eval(new java.io.FileReader(yourfile.js));
}
}
For more info please refer this link http://docs.oracle.com/javase/6/docs/technotes/guides/scripting/programmer_guide/index.html. I hope it may help you

Java-object to JSON

I am using Rhino to communicate between Java and JavaScript.
I call a JavaScript function via Rhino and this function takes an argument which must be a JSON-object. How do i parse Java-object to JSON and pass it to JavaScript in my case?
Java-code:
try {
engine.eval(fileReader);
Invocable invocableEngine = (Invocable) engine;
Object o = invocableEngine.invokeFunction("f", MyObject json);
System.out.println(o);
} catch (ScriptException ex) {
ex.printStackTrace();
} catch(Exception e){
e.printStackTrace();
}
JavaScript-Code:
function f(json){
var id = json.id;
return id;
}
I haven't used rhino, but for conversion of Java objects/collections to json I use the google library gson.
Back when I was using Rhino I just converted my Java-JSON-Object(org.json.JSONObject) to String and passed them as function parameter to a javascript function existing in the rhino scope.
String itemDatagram = jsonItemDatagram.toString;
String code = "inside.js.scope.aFunction(" + itemDatagram + ");";
The code String object would then have to be evaluated by Rhino. The String object automagically becomes a Javascript object inside the js scope(on the Rhino side). And since JSON is just a subset of javascript objects this should be what you want.

Running a Java program with a .dll from Adobe AIR's native process

I would like to be able to operate a scanner from my AIR application. Since there's no support for this natively, I'm trying to use the NativeProcess class to start a jar file that can run the scanner. The Java code is using the JTwain library to operate the scanner. The Java application runs fine by itself, and the AIR application can start and communicate with the Java application. The problem seems to be that any time I attempt to use a function from JTwain (which relies on the JTwain.dll), the application dies IF AIR STARTED IT.
I'm not sure if there's some limit about referencing dll files from the native process or what. I've included my code below
Java code-
while(true)
{
try {
System.out.println("Start");
text = in.readLine();
Source source = SourceManager.instance().getCurrentSource();
System.out.println("Java says: "+ text);
}
catch (IOException e)
{
System.err.println("Exception while reading the input. " + e);
}
catch (Exception e) {
System.out.println("Other exception occured: " + e.toString());
}
finally {
}
}
}
Air application-
import mx.events.FlexEvent;
private var nativeProcess:NativeProcess;
private var npInfo:NativeProcessStartupInfo;
private var processBuffer:ByteArray;
private var bLength:int = 0;
protected function windowedapplication1_applicationCompleteHandler(event:FlexEvent):void
{
var arg:Vector.<String> = new Vector.<String>;
arg.push("-jar");
arg.push(File.applicationDirectory.resolvePath("Hello2.jar").nativePath);
processBuffer = new ByteArray;
npInfo = new NativeProcessStartupInfo;
npInfo.executable = new File("C:/Program Files/Java/jre6/bin/javaw.exe");
npInfo.arguments = arg;
nativeProcess = new NativeProcess;
nativeProcess.addEventListener(ProgressEvent.STANDARD_OUTPUT_DATA, onStandardOutputData);
nativeProcess.start(npInfo);
}
private function onStandardOutputData(e:ProgressEvent):void
{
tArea.text += nativeProcess.standardOutput.readUTFBytes(nativeProcess.standardOutput.bytesAvailable);
}
protected function button1_clickHandler(event:MouseEvent):void
{
tArea.text += 'AIR app: '+tInput.text + '\n';
nativeProcess.standardInput.writeMultiByte(tInput.text + "\n", 'utf-8');
tInput.text = '';
}
protected function windowedapplication1_closeHandler(event:Event):void
{
nativeProcess.closeInput();
}
]]>
</fx:Script>
<s:Button label="Send" x="221" y="11" click="button1_clickHandler(event)"/>
<s:TextInput id="tInput" x="10" y="10" width="203"/>
<s:TextArea id="tArea" x="10" width="282" height="88" top="40"/>
I would love some explanation about why this is dying. I've done enough testing that I know absolutely that the line that kills it is the SourceManager.instance().getCurrentSource(). I would love any suggestions. Thanks.
When calling Java add this -Djava.library.path=location_of_dll to the command line
I have 0 experience with Air, but this reminded me of a Java issue I once spent some time figuring out. I don't have a suggestion on why the scanning doesn't work, but I think a stack trace would be your best friend right now.
I'm guessing you're relying on this line to capture and display it?
nativeProcess.standardOutput.readUTFBytes(nativeProcess.standardOutput.bytesAvailable);
However, you are writing IOExceptions to System.err - is there a nativeProcess.standardError you could read in Air? Alternatively, output everything to System.out.

Categories

Resources