Google Translate Vs CSP. Fight!
Recently we were asked to implement a Content Security Policy (CSP) onto an existing site. The process of retro fitting CSP goes something like this:
- Put in a restrictive policy
- Test the site and check for violation reports in the console
- Loosen policy to suit
- goto 2
This site, however, produced cryptic violation reports:
Content Security Policy: The page's settings blocked the loading of a resource at inline ("script-src"). srcdoc:1:1
Where is srcdoc and why is it loading a script? It turns out that srcdoc is an attribute of an
iframe, it allows you to load inline HTML into an iframe. A little deduction later reveals that this iframe was being injected dynamically by Google translate:
<iframe sandbox="allow-scripts" srcdoc="<body><script>[...]</script></body>" style="display: none;"></iframe>
There isn't much documentation out there about srcdoc and CSP but the pseudo-origin that is created by iframes with srcdoc inherits the same CSP as the root origin, hence the report. One option now is to add
unsafe-inline to the CSP and that will work but that also makes your CSP basically pointless. A better option is to add a hashes of the script tags. Doing this gives us a policy that looks like this:
img-src https://translate.googleapis.com https://translate.google.com https://www.google.com;
script-src 'sha256-NNiElek2Ktxo4OLn2zGTHHeUR6b91/P618EXWJXzl3s=' 'sha256-97l24HYIWEdSIQ8PoMHzpxiGCZuyBDXtN19RPKFsOgk=' https://translate.google.com https://translate.googleapis.com;
You can omit https://www.google.com from img-src as it is only being used to load a single pixel image, probably for tracking, and the feature still appears to work without it.
The hashes are as follows:
sha256-NNi...l3s=the frame srcdoc
void(0). This is used inline in the translate bar
Something to note is that hashes are an easy fix but like most easy fixes they are also fragile. If Google ever decides to change the script or if it's dynamic based on browser, language, OS etc it will get blocked again. We decided this risk was acceptable because the service is deprecated so is unlikely to receive any updates.
It's worth noting that the Google CSP validator shows both translate.google.com and translate.googleapis.com as possible CSP bypass vectors.