Just opened an HTM file with the following code, is it dangerous? - javascript

I received an email from an unknown person and opened an htm file in the attachment file. The following code executed :
<frameset onpageshow="document.location.replace(window.atob('aHR0cHM6Ly9tdXNrLmJ0Y2RvbmF0dmVyLnNpdGUvPzI0NDc1NTgg'));">
Did I just execute something that could harm my computer ?
Thank you,
Thomas

It may be dangerous to open email attachments received from untrusted sources, in general.
In your code, in particular, the following is happening:
window.atob API is called to decode aHR0cHM6Ly9tdXNrLmJ0Y2RvbmF0dmVyLnNpdGUvPzI0NDc1NTgg base64 encoded string. See https://developer.mozilla.org/en-US/docs/Web/API/atob for the API reference.
Using the free online base64 decoder (https://www.base64decode.org/ for example) you may translate aHR0cHM6Ly9tdXNrLmJ0Y2RvbmF0dmVyLnNpdGUvPzI0NDc1NTgg and get https://musk.btcdonatver.site/?2447558 .
On opening this page your browser may navigate to that URL, see document.location.replace API call
Now, it depends on what https://musk.btcdonatver.site/?2447558 is doing.
Please, do not open attachments from unknown people and untrusted sources. They may contain malicious contents, phishing and content that may do damage otherwise.

This sets the window location to
https://musk.btcdonatver.site/?2447558.
Looks like a scam but not sure. Possible wont do any harm unless you do something by visiting to that link.

Related

Is it possible to name file currently represented as buffer without having write/read?

I get data from the Postgres database as a "bytea" (this is how they are stored in the database), then using bytea-parser I turn it into a Node type "buffer" and I need to give this to the front-end as a file with the name, but currently it comes as an untitled file. Of course, I understand that I can write this file to disk and thus give it a name, but I would like to do without this operation (besides, I still have to read it - that a lot I/O). Is it possible? In other words, is it possible to have a file as a buffer and give it a name without having write/read I/O?
Yes, it's possible. You can set the content-disposition header. See this writeup on MDN for more explanation, but if you want the user to be prompted to save the file to their hard drive, you would probably use something like this:
Content-Disposition: attachment; filename="filename.jpg"
If you have any examples of responses (even if they use the disk for actual files) that work the way you want them in the browser, then you can look at exactly how that response is structured (use the Network tab in the Chrome debugger to see the actual http headers and content) and then you can emulate the appropriate headers and other parts of the response with your response.

How to attach blob file into HTML href="mailto:"

I have a file available through an URL (need authorization). I created a mailto: link and would like to attach this file in the mail. How can I do that ?
Something like "mailto:toto#gmail.fr&attachment=site.com/file.pdf"
mailto: doesn't support attachments, but there are various ways you could achieve a similar effect:
Link to the file in a message body
You mentioned that the link needs authorisation, you could generate temporary urls that last 30 minutes (or more/less) which allow for downloads (users can then attach the file themselves)
Send the email yourself
Your service could send an email to your user (or on behalf of your user) with the attachment using something like Amazon SES, or Mailchimp, etc...
Render your PDF into HTML
It seems you are planning on attaching PDF files. Depending on the complexity of the PDF files, you could attempt to convert the PDF into email-friendly HTML using one of many tools, such as pdf2htmlEX or Pandoc.
If you're hoping for an universal solution, you can't. The mailto protocol described in the RFC 2368 tells us :
The creator of a mailto URL cannot expect the resolver of a URL to
understand more than the "subject" and "body" headers.
Even though other headers might be used and understood by some mail clients, this isn't an universally compatible solution. Unless you tell your clients to open these links specifically with a specific mail client that you know supports more headers (like a hypothetical attachment header), you should consider this to not be doable.

make ASP.Net file upload secure

I'm creating an ASP.Net form with a fileupload control which will then email the details of the form and the file to another admin. I want to ensure this secure (for the server and the recipient). The attachment should be a CV so I will restrict it to typical text documents.
From what I can tell the best bet is to check that the file extension or MIME Type is of that kind and check it against the "magic numbers" to verify that the extension hasn't been changed. I'm not too concerned about how to go about doing that but want to know if that really is enough.
I'd also be happy to use a third party product that takes care of this and I've looked at a couple:
blueimp jQuery file upload
http://blueimp.github.io/jQuery-File-Upload/
and cutesoft ajaxuploader
http://ajaxuploader.com/Demo/
But blueimp one still seems to require custom server validation (i guess just being jQuery it just handles client-side validation) and the .net one checks the MIME-type matches the extension but I thought the MIME type followed the extension anyway.
So,
Do I need to worry about server security when the file is added as an attachment but not saved?
Is there a plugin or control that takes care of this well?
If I need to implement something for server validation myself is matching the MIME-type to the "magic numbers" good enough?
I'm sure nothing is 100% bulletproof but file upload is pretty common stuff and I assume most implementations are "safe enough" - but how!?
If it's relevant, here is my basic code so far
<p>Please attach your CV here</p>
<asp:FileUpload ID="fileUploader" runat="server" />
and on submit
MailMessage message = new MailMessage();
if (fileUploader.HasFile)
{
try
{
if (fileUploader.PostedFile.ContentType == "text")
{
// check magic numbers indicate same content type... if(){}
if (fileUploader.PostedFile.ContentLength < 102400)
{
string fileName = System.IO.Path.GetFileName(fileUploader.PostedFile.FileName);
message.Attachments.Add(new Attachment(fileUploader.PostedFile.InputStream, fileName));
}
else
{
// show a message saying the file is too large
}
}
else
{
// show a message saying the file is not a text based document
}
}
catch (Exception ex)
{
// display ex.Message;
}
}
A server can never be 100% secure, but we should do our best to minimize the risk on an incident. I should say at this point that I am not an expert, I am just a computer science student. So, here is an approach that I would follow in such a case. Please, comment any additional tip you can give.
Generally speaking, to have a secure form, all client inputs must be checked and validated. Any information that does not origin from our system is not trusted.
Inputs from the client in our case:
file's name
name
extension
file's content
Extension
We don't really care about the minetype, this is info for a web server. We care about the file extension, because this is the indicator for the OS on how to run/read/open a file. We have to support only specific file extensions (what ever your admin's pc can handle) there is no point supporting unknown file types.
Name (without the extension)
The name of the file is not always a valuable info. When I deal with file uploading I usually rename it (set it) to an id (a username, a time-stamp, hashes etc). If the name is important, always check/trim it, if you only expect letters or numbers delete all other chars (I avoid to leave "/", "\", "." because they can be used to inject paths).
So now we suppose that the generated file name is safe.
Content
When you support no structured files, you just can not validate the file's content. Thus, let an expert program do this for you... scan them with an antivirus. Call the antivirus from the console (carefully, use mechanics that avoid injections). Many antivirus can scan zips contents too (a malicious file, in a folder on your server is not a good idea). Always keep the scan program updated.
On the comments I suggested zipping the file, in order to avoid any automatic execution on the admin's machine and on the sever. The admin's machine's antivirus can then handle it before unzip.
Some more tips, don't give more information's to the client than he needs... don't let the client know where the files are saved, don't let the web-server access them for distribution if there no need to. Keep a log with weird actions (slashes in filenames, too big files, too long names, warning extensions like "sh" "exe" "bat") and report the admins with an email if anything weird happen (it is good to know if your protections work).
All these creates server work load (more system holes), so you may should count the number of files that are scanned/checked at the moment before accepting a new file upload request (that is where I would launch a DDoS attack).
With a quick google search Avast! For Linux - Command Line Guide, I do not promote Avast, I am just showing it as an existing example.
Lastly but not least, you are not paranoid, I manage a custom translation system that I coded... spams and hack attacks have occurred more than once.
Some more thoughts, JavaScript running on a web-page is only secure for the client's computer (thanks to the browser's security). We can use it to prevent invalid posts to the server but this does not ensures that such requests will not be done as JavaScript can be bypassed/edited.
So, all JavaScript solutions are only for a first validation (usually just to help the user correct mistakes) and to correctly set the form data.

How can I display javascript source file?

I have one server side js file. I need to take whole source from that file and show it. I have the url i.e. location of the js file in the server. when I hit the url in browser then I am getting response and I can see that source. But when I am trying this code, it is not working. no response, even can't see the alert msg(mean alert("1")), and just stop. please solve this problem.
$.get("http://localhost:8080/web/js/serviceFF.js", function(file) {
alert("1");
$("textarea").val(file);
});
The source file that you are running - is it also being viewed from http://localhost:8080 too? If it isn't, you may be running into XSS (cross-site script execution) browser protection.
So in other words, the code listed above should be on http://localhost:8080/testpage.html and you need to run it from there.
If it is on your local computer, like the browser showing file://home/user/Desktop/testpage.html - the browser may block it to prevent XSS exploits.
Also, same origin policy comes into play too. Please refer to the wiki table:
https://en.wikipedia.org/wiki/Same-origin_policy

can firefox extension modify DOM of HTML document then save as HTML?

I am creating a firefox extension that lets the operator perform various actions that modify the content of the HTML document. The operator does not edit HTML, they take other actions and my extension modifies the document by inserting elements, adding attributes, and so forth.
When the operator is finished, they need to be able to save the HTML document as a file (or have my extension send it to an internet destination, but this is not required since they can email the saved file).
I thought maybe the changes made by the javascript code in my extension would be reflected in the HTML document, but when I ask the firefox browser to "view source" after making modifications, it displays the original HTML text.
My questions are:
#1: What is the easiest way for the operator to save the HTML document with all the changes my extension has made?
#2: What is the easiest way for the javascript code in my extension to process the HTML document contents and write to an HTML file on the local disk?
#3: Is any valid HTML content incapable of accurate representation in the saved file?
#4: Is the TreeWalker part of the solution (see below)?
A couple observations from my research so far:
I've read about the TreeWalker object, which seems to provide a fairly painless way for an extension to walk through everything (?or almost everything?) in the HTML document. But does it expose everything so everything in the original (and my modifications) can be saved without losing anything of importance?
Does the TreeWalker walk through the HTML document in the "correct order" --- the order necessary for my extension to generate the original and/or modified HTML document?
Anything obscure or tricky about these problems?
Ok so I am assuming here you have access to page DOM. What you need to do it basically make changes to the dom and then get all the dom code and save it as a file. Here is how you can download the page's html code. This will create an a tag which the user needs to click for the file to download.
var a = document.createElement('a'), code = document.querySelectorAll('html')[0].innerHTML;
a.setAttribute('download', 'filename.html');
a.setAttribute('href', 'data:text/html,' + code);
Now you can insert this a tag anywhere in the DOM and the file will download when the user clicks it.
Note: This is sort of a hack, this injects entire html of the file in the a tag, it should in theory work in any up to date browser (except, surprise, IE). There are more stable and less hacky ways of doing it like storing it in a file system API file and then downloading that file instead.
Edit: The document.querySelectorAll line accesses the page DOM. For it to work the document must be accessible. You say you are modifying DOM so that should already be there. Make sure you are adding the code on the page and not your extension code. This code will be at the same place as your DOM modification code, not your extension pages that can't access the DOM.
And as for the a tag, it will be inserted in the page. I skipped the steps since I assumed you already know how to manipulate DOM and also because I don't know where you would like to add the link. And you can skip the user action of clicking the link too, but it's a hack and only works in modern browsers. You can insert the a tag somewhere in the original page where user won't see it and then call the a.click() function to simulate a click event on the link. But this is not a legit way and I personally only use it on my practice projects to call click event listeners.
I can only test this on chrome not on FF but try this code, this will not require you to even add the a link to DOM. You need to add this next to the DOM manipulation code. This will work if luck is on your side :)
var a = document.createElement('a'), code = document.querySelectorAll('html')[0].innerHTML;
a.setAttribute('download', 'filename.html');
a.setAttribute('href', 'data:text/html,' + code);
a.click();
There is no easy way to do this with the web API only, at least when you want a result that does not omit stuff like the doctype or comments. You could still write a serializer yourself that goes through document.childNodes and serialized according to the node type (Element.outerHTML, Comment.data and so on).
Luckily, you're writing a Firefox add-on, so you have access to a lot more (powerful) stuff.
While still not 100% perfect, the nsIDocumentEncoder implementations will produce pretty decent results, that should only differ in some whitespace and explicit charset declaration at most (everything else is a bug).
Here is an example on how one might use this component:
function serializeDocument(document) {
const {
classes: Cc,
interfaces: Ci,
utils: Cu
} = Components;
let encoder = Cc['#mozilla.org/layout/documentEncoder;1?type=text/html'].createInstance(Ci.nsIDocumentEncoder);
encoder.init(document, 'text/html', Ci.nsIDocumentEncoder.OutputLFLineBreak | Ci.nsIDocumentEncoder.OutputRaw);
encoder.setCharset("utf-8");
return encoder.encodeToString();
}
If you're writing an SDK add-on, stuff gets more complicated as the SDK abstracts some important stuff away. You'll need to go through the chrome module, and also figure out the active window and tab yourself. Something like Services.wm.getMostRecentWindow("navigator:browser").content.document (Services.jsm) should do the trick.
In XUL overlay add-ons, content.document should suffice to get the document of the currently active tab, and you have Components access already.
Still, you need to let the user choose a file destination, usually through nsIFilePicker and then actually write the file, by using something like a file stream or the fully async OS.File API.
Looks like I get to answer my own question, thanks to someone in mozilla #extdev IRC.
I got totally faked out by "view source". When I didn't see my modifications in the window displayed by "view source", I assumed the browser would not provide the information.
However, guess what? When I "file" ===>> "save page as...", then examine the page contents with a plain text editor... sure enough, that contained the modifications made by my firefox extension! Surprise!
A browser has no direct write access to the local filesystem. The only read access it has is when explicitly provide a file:// URL (see note 1 below)
In your case, we are explicitly talking about javascript - which can read and write cookies and local storage. It can also send stuff back to the server and retrieve it, e.g. using AJAX.
Stuff you put in local storage/cookies is effectively not accessible to other programs (such as email clients).
It is possible to create very long mailto: URLs (see note 2) but only handles inline content in the email and you're going to run into all sorts of encoding issues that you're not ready to deal with.
Hence I'd recommend pursuing storage serverside via AJAX - and look at local storage once you've got this sorted/working.
Note 1: this is not strictly true. a trusted, signed javascript has access to additional functions which may include direct file access.
Note 2: (the limit depends on the browser and the email client - Lotus Notes truncaets the content rather a lot)

Categories

Resources