Proper way to inject javascript code? - javascript

I would like to create a site with a similar functionality like translate.google.com or hypothes.is has: users can enter any address and the site opening with an additional menu. I gues this is done with some middleware-proxy solution and a javascript is injected in the response, but I'm not sure. Do you have any idea how to implement the same feature? How can it work with secured (https) sites?
Many Thanks

The entire site is fetched by the server, the source code is parsed, code injected and then sent back to the requesting client.
It works with SSL just fine, because it's two separate requests - the request that gets sent to the endpoint is not seen by the user.
The certificate is valid because it's being served under google's domain.
In order to actually implement something like this could potentially be quite complicated, because:
The HTML you are parsing won't necessarily conform to your expectations, or even be valid
The content you're forwarding to the client will likely reference resources with a relative URI. This means that you also need to intercept these requests and pull the resources (images, external css, js, etc) and serve them back to the client - and also rewrite the URLs.
It's very easy to break content by injecting arbitrary javascript. You need to be careful that your injected code is contained and won't interfere with any existing code on the site.
It's very common for an implementation such as this to have non-obvious security concerns, often resulting in XSS attacks being possible.

Related

Monitoring web requests made by a specific javascript src file

I'm looking for some help with the following:
I'm building a website that links external scripts (these scripts can be changed anytime by the script owner).
I want to route any web requests that's being sent by these scripts through my backend server as a proxy, so that I can parse the request and response to make sure they are not exfiltrating data from my website.
The idea here is to be able to leverage external scripts that cannot be trusted 100% with my data.
To enforce this, is it possible to intercept web requests made by <script>s from a different <script> that loaded early on?
If not, what is a better way?
If you cannot trust the scripts, this becomes more of a security question. You should get more information about web security in general.
An interesting example of such implementation is Tampermonkey and it's permission model (similar to what Android apps).
Depending on the use-case, you may want to manually approve each js file and enforce it via integrity checking:
https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity
At the end of the day, you cannot programmatically check the security of an external js file. You wither trust its author or you don't.

Detect Javascript Tampering in Ajax call

We have a Javascript file that we have developed for our clients to use. The Javascript snippet takes a screenshot of the website it is run on and then sends it back to our server via jQuery.post()
The nature of our industry means that we have to ensure there is no way that the file can be tampered with by the client.
So the challenge is that we need to make sure that the screenshot was generated by the javascript file hosted on our server, and not one that's been copied or potentially tampered with in any way.
I know that I can get the script location using:
var scripts = document.getElementsByTagName("script"),
src = scripts[scripts.length-1].src;
But this won't help if a client tampers with that part of the SRC.
What methods can I employ to make sure that:
1) The post was made from the javascript file hosted on our server
2) The javascript was not tampered with in any way.
Short answer:
You can't.
You can't.
Both stem from the fact that once you hand over something to the client side, it's out of your hands. Nothing will prevent the user from putting a proxy between you and their machine, a process that intercepts content or an extension that tampers content, headers, cookies, requests, responses etc.
You could, however, harden your app by preventing XSS (prevent injection of scripts via user input), using SSL (prevent tampering of the connection), applying CSP (only allow certain content on the page), add CSRF tokens (ensure the form is authorized by the server) and other practices to make it harder for tampered content to get through.
But again, this won't prevent a determined hacker to find an opening.

Prevent local PHP/HTML files preview from executing javascript on server

I have some HTML/PHP pages that include javascript calls.
Those calls points on JS/PHP methods included into a library (PIWIK) stored onto a distant server.
They are triggered using an http://www.domainname.com/ prefix to point the correct files.
I cannot modify the source code of the library.
When my own HTML/PHP pages are locally previewed within a browser, I mean using a c:\xxxx kind path, not a localhost://xxxx one, the distant script are called and do their process.
I don't want this to happen, only allowing those scripts to execute if they are called from a www.domainname.com page.
Can you help me to secure this ?
One can for sure directly bypass this security modifying the web pages on-the-fly with some browser add-on while browsing the real web site, but it's a little bit harder to achieve.
I've opened an issue onto the PIWIK issue tracker, but I would like to secure and protect my web site and the according statistics as soon as possible from this issue, waiting for a further Piwik update.
EDIT
The process I'd like to put in place would be :
Someone opens a page from anywhere than www.domainname.com
> this page calls a JS method on a distant server (or not, may be copied locally),
> this script calls a php script on the distant server
> the PHP script says "hey, from where damn do yo call me, go to hell !". Or the PHP script just do not execute....
I've tried to play with .htaccess for that, but as any JS script must be on a client, it blocks also the legitimate calls from www.domainname.com
Untested, but I think you can use php_sapi_name() or the PHP_SAPI constant to detect the interface PHP is using, and do logic accordingly.
Not wanting to sound cheeky, but your situation sounds rather scary and I would advise searching for some PHP configuration best practices regarding security ;)
Edit after the question has been amended twice:
Now the problem is more clear. But you will struggle to secure this if the JavaScript and PHP are not on the same server.
If they are not on the same server, you will be reliant on HTTP headers (like the Referer or Origin header) which are fakeable.
But PIWIK already tracks the referer ("Piwik uses first-party cookies to keep track some information (number of visits, original referrer, and unique visitor ID)" so you can discount hits from invalid referrers.
If that is not enough, the standard way of being sure that the request to a web service comes from a verified source is to use a standard Cross-Site Request Forgery prevention technique -- a CSRF "token", sometimes also called "crumb" or "nonce", and as this is analytics software I would be surprised if PIWIK does not do this already, if it is possible with their architecture. I would ask them.
Most web frameworks these days have CSRF token generators & API's you should be able to make use of, it's not hard to make your own, but if you cannot amend the JS you will have problems passing the token around. Again PIWIK JS API may have methods for passing session ID's & similar data around.
Original answer
This can be accomplished with a Content Security Policy to restrict the domains that scripts can be called from:
CSP defines the Content-Security-Policy HTTP header that allows you to create a whitelist of sources of trusted content, and instructs the browser to only execute or render resources from those sources.
Therefore, you can set the script policy to self to only allow scripts from your current domain (the filing system) to be executed. Any remote ones will not be allowed.
Normally this would only be available from a source where you get set HTTP headers, but as you are running from the local filing system this is not possible. However, you may be able to get around this with the http-equiv <meta> tag:
Authors who are unable to support signaling via HTTP headers can use tags with http-equiv="X-Content-Security-Policy" to define their policies. HTTP header-based policy will take precedence over tag-based policy if both are present.
Answer after question edit
Look into the Referer or Origin HTTP headers. Referer is available for most requests, however it is not sent from HTTPS resources in the browser and if the user has a proxy or privacy plugin installed it may block this header.
Origin is available for XHR requests only made cross domain, or even same domain for some browsers.
You will be able to check that these headers contain your domain where you will want the scripts to be called from. See here for how to do this with htaccess.
At the end of the day this doesn't make it secure, but as in your own words will make it a little bit harder to achieve.

XSS - Send data to the source server of a script?

I am writing a JavaScript application where I plan on host the code on a CDN. Now I plan to include this code to my clients' sites. However, I have a problem, I want to use AJAX to communicate between the client and the server. Now, from my understanding of XSS, this is not possible.
Ex:
User visits site.com, where a script tag's source is pointing to a file on cdn.somedomain.com
The script on cdn.somedomain.com fires an event.
This event will communicate with a PHP. I know it is possible for the script from cdn.somedomain.com to request documents on site.com. However, is it possible to send data back to a PHP file on cdn.somedomain.com?
Thanks for helping an entrepenuer! :D
The short is I think this is possible, but it depends on a couple of things. The same origin policy is a weird thing in that it won't allow cross domain reads, but will allow cross domain writes.
I think a way you could accomplish your goal is by making a GET request (minimally by creating an iframe, img, or whatever else that pulls a src) or possibly even using AJAX. If your goal is to only send data, then that should be fine. However, if you want to read this data back then I think that'll be a little less straight forward. I can't really answer that right now - especially without knowing more details about your system setup.
Sounds like a weird use of a cdn. Normally cdns serve static assets, so you wouldnt put a php file there. In fact the cdn wouldnt normally run dynamic server side code at all.
You can address the problem in several ways. Newer browsers support CORS and cross domain ajax. The cdn would then have to use the Access-control-* headers. You could also look at something like easyXDM, which works in older browsers.

Is there any reason NOT to use src="//domain.com/file.js", which is protocol dynamic?

In some of my E-Commerce applications I've started using src="//domain.com/file.js" in cases where I needed to reference externally hosted scripts that I wanted to include. In my E-Commerce applications not all pages actually use https as not every page has a form.
I'm wondering if there's really any disadvantage to always using this, as it's also a shortcut to http and you can always, always avoid the not-secure IE warning.
If your intent is to load the resources from the same protocol as the page is loaded with, then using it is a perfect way to accomplish it. However, you may need to load some resources from http even when your page is currently served under https (let's say the resouce is served only on http or you prefer to reduce load on your server by not making it encrypt every image on the page). In that case, you need to explicitly specify the protocol name.
#Mehrdad_Afshari Sourcing resources from HTTP can open up injection vulnerabilities from MITM attacks that HTTPS is specifically supposed to protect you from. Classic example is sourcing a script over HTTP, but there have been bugs in the past (see http://www.adambarth.com/papers/2009/barth-caballero-song.pdf) that could allow script injection through an IMG tag by a MITM. Scheme-relative links were specifically recommended in the ForceHTTPS work (https://crypto.stanford.edu/forcehttps/) because of concerns like this.

Categories

Resources