├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── background.js ├── epr-manifest.json ├── icon.png ├── manifest.json ├── popup.html ├── reWorker.js └── spec └── epr.bs /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | ## How to contribute 2 | 3 | Open an issue or a pull request, its that easy! 4 | 5 | ## Contributor License Agreements 6 | 7 | We'd love to accept your pull requests! Before we can merge them, we have to jump a couple of legal hurdles. 8 | 9 | Please fill out either the individual or corporate Contributor License Agreement (CLA). 10 | 11 | * If you are an individual writing original source code and you're sure you own the intellectual property, then you'll need to sign an [individual CLA](https://developers.google.com/open-source/cla/individual). 12 | * If you work for a company that wants to allow you to contribute your work, then you'll need to sign a [corporate CLA](https://developers.google.com/open-source/cla/corporate). 13 | 14 | Follow either of the two links above to access the appropriate CLA and instructions for how to sign and return it. Once we receive it, we'll be able to accept your pull requests. 15 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2014 Google Inc. 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Entry Point Regulation Prototype Chrome Extension 2 | 3 | This prototype Chrome extension allows for the implementation of Entry Point Regulation (EPR) on a given web site. Sites with regulated entry points limit their exposure to reflected cross-site scripting vulnerabilities and cross-site request forgery. 4 | 5 | Disclaimer: This is not an official Google product. 6 | 7 | ## EPR Implementation for Web Sites 8 | 9 | To EPR-enable a site, three steps are required: 10 | 11 | 1) List out valid site entry points in a manifest file (/epr-manifest.json). Once installed in Chrome at the client, the EPR Chrome extension is responsible for enforcing the rules specified in a site's EPR manifest. Currently EPR manifests are specified for a given fully qualified domain name. (In the future, this may be extended to allow different paths on a domain to have individually maintained manifests.) 12 | 13 | 2) Serve the following HTTP response header from the domain: 14 | 15 | ``` 16 | X-EPR: 1 17 | ``` 18 | 19 | This header lets the EPR Chrome extension know to download and store the EPR manifest file. It's best if the X-EPR header is served via web server configuration rather than app-specific configuration, so that it will be served on all HTTP responses. 20 | 21 | 3) Install the EPR prototype Chrome extension on client browsers. 22 | 23 | 24 | ## Example EPR Manifest 25 | 26 | The background.js file contains a hardcoded example manifest, complete with comments. (See eprDataStatic.) The epr-manifest.json file contains the same manifest, just without comments. Edit epr-manifest.json as you'd like and host it at the root. 27 | 28 | Eg: [https://www.[Your EPR-enabled website].com/epr-manifest.json](https://www.[Your EPR-enabled website].com/epr-manifest.json) 29 | 30 | 31 | ## More Information 32 | 33 | EPR blog post: http://randomdross.blogspot.com/2014/08/entry-point-regulation-for-web-apps.html 34 | 35 | EPR Google Group: https://groups.google.com/forum/#!forum/epr-list 36 | 37 | See background.js for a list of TODOs for future improvements to the EPR Chrome extension. 38 | -------------------------------------------------------------------------------- /background.js: -------------------------------------------------------------------------------- 1 | // Copyright 2014 Google Inc. All rights reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | 16 | // Hardcoded EPR manifest (unused, currently) 17 | // Normally download epr-manifest.json instead 18 | var eprDataStatic = 19 | { 20 | "manifests": 21 | [ 22 | { 23 | "site": "https://[Your EPR-enabled website]", 24 | "maxAge": 31536000, 25 | "reportUrl": "https://[Report URL]", /* Currently ignored */ 26 | "defaultNavBehavior": "block", /* Currently ignored */ 27 | "defaultResBehavior": "block", /* Currently ignored */ 28 | "rules": 29 | [ 30 | /* 31 | This is the list of allowed entry points 32 | path: string for full path comparison (don't combine w/regex) 33 | regex: regex for full path comparison 34 | types: one of: navigation, stylesheet, script, image, xhr, other 35 | allowData: Does this entry point allow data passed via querystring, hash or POST? 36 | */ 37 | { "path": "/", "types": [ "navigation" ], "allowData": false }, 38 | { "regex": "^/\\d+$", "types": [ "navigation" ], "allowData": false }, 39 | { "path": "/image", "types": [ "image" ], "allowData": true }, 40 | { "regex": "^/(scoreboard|random|favorites|recentvisits|create)$", "types": [ "navigation" ], "allowData": false }, 41 | { "regex": "^/(recent|popular|metrics|template|search)$", "types": [ "navigation" ], "allowData": true }, 42 | ] 43 | } 44 | ] 45 | }; 46 | 47 | // "NO DATA" rule as described here: 48 | // http://lists.w3.org/Archives/Public/public-webappsec/2014Nov/0018.html 49 | var eprNoDataManifest = 50 | { 51 | "site": "", 52 | "maxAge": 90, 53 | "reportUrl": "", /* Currently ignored */ 54 | "defaultNavBehavior": "block", /* Currently ignored */ 55 | "defaultResBehavior": "allow", /* Currently ignored */ 56 | "rules": 57 | [ 58 | { "regex": ".*", "types": [ "image", "script", "stylesheet", "xhr", "other" ], "allowData": true }, 59 | { "regex": ".*", "types": [ "navigation" ], "allowData": false }, 60 | ] 61 | } 62 | 63 | // Wipe out example in eprDataStatic, defer to downloaded manifest 64 | // Comment this out to use the hardcoded manifest above 65 | eprDataStatic = { "manifests": [ ] }; 66 | 67 | var eprData = { "manifests": [ ] }; 68 | 69 | var refererTracking = { }; 70 | 71 | // Todo: 72 | // - Take some action in the event ReDoS is detected, beyond just informing the user 73 | // See comments below in checkRegex 74 | // - Advanced manifest features 75 | // - reportUrl 76 | // - defaultNavBehavior / defaultResBehavior 77 | // - Manifest expiration 78 | // - Make sure manifests are scheme-specific so it's not possible to serve a manifest for an HTTPS site via the HTTP version of that site 79 | // - Docs say: "Also synchronous XMLHttpRequests from your extension are hidden from blocking event handlers in order to prevent deadlocks." 80 | // - Determine if there is a problem w/this... XHR observed to go through, so this seems to be a no-op. 81 | // - Use bookmark API to monitor for added bookmarks and add them to bookmarkUrls 82 | // - Tie into logic for when browser cache is cleared so manifests are cleared as well 83 | // - Synchronous re-download and re-evaluation of manifests if a block operations happens on a cached manifest (see TODO in regulator()) 84 | 85 | // Other misc notes: 86 | // - Requests to pass unvalidated if origins... 87 | // ...match what's currently input to the Omnibox 88 | // - Ack, can't really do this... 89 | // - Better idea: allow all top-level blank-referer GET navigations that have no querystring or hash (path-based XSS is rare) 90 | // - Maybe we open this up to allow any referer? (or just any GET request w/o querystring or hash) Then we don't need the 91 | // allowData flag in the manifest to specify if querystring/hash/postdata is allowed. 92 | // - I'm leaning towards not doing this, but it's one one thing to consider. 93 | // ...are in the user's bookmarks 94 | // - Done 95 | // ...or are in the user's history, just because we can grovel that too, and these show up as suggestions in the omnibox 96 | // - ...or not. Seems unnecessary. There's some pretty odd stuff in my own omni-box drop-down 97 | // - Can key off of the transition type 98 | // ...anything else we can / should grovel through? 99 | // Use async methods to build up state to compare at the time of the webRequest 100 | 101 | var worker; 102 | var pathAnchor; 103 | var regexTestFinished; 104 | var regexTestDomain; 105 | var bookmarkUrls; 106 | 107 | // If the regex we died on last time doesn't complete in 5 seconds... 108 | function checkRegex() 109 | { 110 | if (!regexTestFinished) 111 | { 112 | worker.terminate(); 113 | 114 | // A little unclear if we should take action here or even advise any action. 115 | // Maybe just offer to report it to the web site? Is there any reasonable way to fix the user's configuration without unwanted side effects? 116 | alert("It looks like " + regexTestDomain + " may have served you a buggy Entry Point Regulation regex, and this caused your browser to be slow."); 117 | } 118 | } 119 | 120 | function bootWorker() 121 | { 122 | regexTestFinished = true; 123 | if (localStorage["ReDoS-flag"]) 124 | { 125 | worker = new Worker('reWorker.js'); 126 | 127 | regexTestDomain = localStorage["ReDoS-flag"]; 128 | 129 | regexTestFinished = false; 130 | worker.addEventListener('message', function(e) { 131 | if (e.data == true) regexTestFinished = true; 132 | }, false); 133 | 134 | // Test the regex with data, using a worker. If it takes >5 seconds, declare that a bogus regex has been detected and prompt the user. 135 | // Otherwise, don't prompt, leave things as-is. The user just happened to close the browser at a bad time. 136 | worker.postMessage({path: localStorage["ReDoS-path"], regex: localStorage["ReDoS-regex"]}); 137 | 138 | setTimeout(checkRegex, 5000); 139 | 140 | localStorage.removeItem("ReDoS-flag"); 141 | localStorage.removeItem("ReDoS-path"); 142 | localStorage.removeItem("ReDoS-regex"); 143 | } 144 | } 145 | 146 | // Get referer header 147 | function getReferer(headers) 148 | { 149 | var referer = null; 150 | 151 | for (var i = 0; i < headers.length; i++) { 152 | if (headers[i].name === 'Referer') { 153 | referer = headers[i].value; 154 | break; 155 | } 156 | } 157 | 158 | return referer; 159 | } 160 | 161 | // The core EPR functionality implemented prior to requests going out (onBeforeSendHeaders) 162 | function regulator(details) { 163 | var urlProtocol, urlHostname, urlPathname, urlSearch, urlHash; 164 | var retVal = false; 165 | var referer; 166 | var matchedStoredManifest; 167 | var bailOnRegulation; 168 | 169 | pathAnchor.href = details.url; 170 | urlProtocol = pathAnchor.protocol; 171 | urlHostname = pathAnchor.hostname; 172 | urlPathname = pathAnchor.pathname; 173 | urlSearch = pathAnchor.search; 174 | urlHash = pathAnchor.hash; 175 | 176 | bailOnRegulation = false; 177 | 178 | // Bail immediately if this is a manifest request 179 | if (details.method === "GET" && urlPathname === "/epr-manifest.json" && urlSearch.length == 0 && urlHash.length == 0) 180 | { 181 | return {cancel: false}; 182 | } 183 | 184 | // If there's a referer and it matches the domain then we can bail on regulation 185 | // ...though continue to download the manifest as necessary 186 | referer = getReferer(details.requestHeaders); 187 | 188 | if (referer) { 189 | // Keep track of the referer because it will be necessary in processing responses 190 | refererTracking[details.requestId] = referer; 191 | 192 | // If the referer scheme / domain matches the request, bail on regulation 193 | pathAnchor.href = referer; 194 | if ((pathAnchor.protocol == urlProtocol) && (pathAnchor.hostname == urlHostname)) { 195 | bailOnRegulation = true; 196 | } 197 | } 198 | else 199 | { 200 | bailOnRegulation = noRefererCheck(details, urlSearch, urlHash); 201 | } 202 | 203 | matchedStoredManifest = false; 204 | for (var i = 0; i < eprData.manifests.length; i++) 205 | { 206 | if (retVal) break; 207 | 208 | pathAnchor.href = eprData.manifests[i].site; 209 | if ((pathAnchor.protocol != urlProtocol) || (pathAnchor.hostname != urlHostname)) continue; 210 | 211 | matchedStoredManifest = true; 212 | 213 | if (bailOnRegulation) continue; 214 | 215 | // Check against the found manifest, unless it's a stub entry intended to just prevent further download attempts 216 | if (!eprData.manifests[i].sessionIgnore) 217 | { 218 | retVal = checkManifests(i, details.type, urlPathname, urlSearch, urlHash, details.method); 219 | } 220 | 221 | // TODO: If we block due to a manifest, do a sync re-download and re-evaluation of the manifest 222 | // The logic being that we'd block anyway, so performance is not a big deal. 223 | // But the driving factor is to allow fixes for broken manifests that would otherwise sit in the cache, 224 | // keeping the site broken for some visitors. 225 | // Maybe also provide an flag in the manifest to disable this behavior 226 | } 227 | 228 | return {cancel: retVal}; 229 | } 230 | 231 | // There is no referer... Should we bail on regulation? 232 | function noRefererCheck(details, urlSearch, urlHash) { 233 | // Could we have a no-querystring/hash top-level navigation? We want that to bypass regulation too as it's likely a URL typed 234 | // directly into the omnibox 235 | if ((details.method === "GET") && (details.type === "main_frame") && (details.frameId == 0) && (details.parentFrameId == -1) && 236 | (urlSearch.length == 0) && (urlHash.length == 0)) 237 | { 238 | // console.log(details.url + ": " + details.frameId + ": " + details.parentFrameId + ": " + details.tabId); 239 | 240 | // Bail on regulation 241 | return true; 242 | } 243 | 244 | // Also bail if it matches existing bookmark (+ no referer + HTTP GET + top-level nav) 245 | if ((details.method === "GET") && (details.type === "main_frame") && (details.frameId == 0) && (details.parentFrameId == -1) && 246 | (bookmarkUrls.indexOf(details.url) != -1)) 247 | { 248 | return true; 249 | } 250 | 251 | return false; 252 | } 253 | 254 | // Actually do the validation against the appropriate manifest 255 | function checkManifests(i, detailsType, urlPathname, urlSearch, urlHash, urlMethod) { 256 | var typeCheck, regexRule; 257 | var re, reMatches; 258 | var retVal = true; // Block 259 | 260 | for (var j = 0; j < eprData.manifests[i].rules.length; j++) 261 | { 262 | // Check the type of the reference 263 | // Do this first to avoid an unnecessary evaluation of the regular expression 264 | typeCheck = false; 265 | switch(detailsType) { 266 | case "main_frame": 267 | case "sub_frame": 268 | if (eprData.manifests[i].rules[j].types.indexOf("navigation") != -1) typeCheck = true; 269 | break; 270 | case "image": 271 | if (eprData.manifests[i].rules[j].types.indexOf("image") != -1) typeCheck = true; 272 | break; 273 | case "script": 274 | if (eprData.manifests[i].rules[j].types.indexOf("script") != -1) typeCheck = true; 275 | break; 276 | case "stylesheet": 277 | if (eprData.manifests[i].rules[j].types.indexOf("stylesheet") != -1) typeCheck = true; 278 | break; 279 | case "xmlhttprequest": 280 | if (eprData.manifests[i].rules[j].types.indexOf("xhr") != -1) typeCheck = true; 281 | break; 282 | case "object": 283 | case "other": 284 | if (eprData.manifests[i].rules[j].types.indexOf("other") != -1) typeCheck = true; 285 | break; 286 | } 287 | if (!typeCheck) continue; 288 | 289 | // Now also short-circuit if the rule says no data is allowed but there is data 290 | // If it's not a GET request, just assume it's a POST and thus has data 291 | if (!eprData.manifests[i].rules[j].allowData) 292 | { 293 | if ((urlSearch.length > 1) || (urlHash.length > 1) || (urlMethod != "GET")) continue; 294 | } 295 | 296 | if (typeof(eprData.manifests[i].rules[j].path) != "undefined" /* String */) 297 | { 298 | if (eprData.manifests[i].rules[j].path === urlPathname) 299 | { 300 | retVal = false; 301 | break; 302 | } 303 | } 304 | else if (typeof(eprData.manifests[i].rules[j].regex) != "undefined" /* Regex */) 305 | { 306 | regexRule = eprData.manifests[i].rules[j].regex; 307 | 308 | // Set a bit to flag ReDoS 309 | localStorage["ReDoS-regex"] = regexRule; 310 | localStorage["ReDoS-path"] = urlPathname; 311 | localStorage["ReDoS-flag"] = pathAnchor.protocol + "//" + pathAnchor.hostname; 312 | 313 | // Would have been nice to just store regex's as JS regex objects, but JSON doesn't handle that type 314 | re = new RegExp(regexRule); 315 | reMatches = urlPathname.match(re); 316 | 317 | localStorage.removeItem("ReDoS-flag"); 318 | localStorage.removeItem("ReDoS-path"); 319 | localStorage.removeItem("ReDoS-regex"); 320 | 321 | if (reMatches != null) 322 | { 323 | retVal = false; 324 | break; 325 | } 326 | } 327 | } 328 | 329 | return retVal; 330 | } 331 | 332 | // Bookmarked URLs are exempt from EPR 333 | function grovelBookmarks(results) { 334 | var i; 335 | 336 | for (i = 0; i < results.length; i++) 337 | { 338 | try { 339 | bookmarkUrls.push(results[i].url); 340 | } catch (e) { } 341 | try { 342 | grovelBookmarks(results[i].children); 343 | } catch (e) { } 344 | } 345 | } 346 | 347 | // Adaptation of http://www.html5rocks.com/en/tutorials/indexeddb/todo/ 348 | function configStorage() 349 | { 350 | EPRStorage.indexedDB.db = null; 351 | 352 | EPRStorage.indexedDB.open = function() { 353 | var version = 1; 354 | var request = indexedDB.open("manifests", version); 355 | 356 | request.onupgradeneeded = function(e) { 357 | var db = e.target.result; 358 | 359 | e.target.transaction.onerror = EPRStorage.indexedDB.onerror; 360 | 361 | if(db.objectStoreNames.contains("manifest")) { 362 | db.deleteObjectStore("manifest"); 363 | } 364 | 365 | var store = db.createObjectStore("manifest", 366 | {keyPath: "timeStamp"}); 367 | }; 368 | 369 | request.onsuccess = function(e) { 370 | EPRStorage.indexedDB.db = e.target.result; 371 | EPRStorage.indexedDB.getAllManifests(); 372 | }; 373 | 374 | request.onerror = EPRStorage.indexedDB.onerror; 375 | } 376 | 377 | EPRStorage.indexedDB.addManifest = function(manifestText) { 378 | var db = EPRStorage.indexedDB.db; 379 | var trans = db.transaction(["manifest"], "readwrite"); 380 | var store = trans.objectStore("manifest"); 381 | var request = store.put({ 382 | "text": manifestText, 383 | "timeStamp" : new Date().getTime() 384 | }); 385 | 386 | request.onsuccess = function(e) { 387 | // EPRStorage.indexedDB.getAllManifests(); 388 | }; 389 | 390 | request.onerror = function(e) { 391 | console.log(e.value); 392 | }; 393 | }; 394 | 395 | EPRStorage.indexedDB.getAllManifests = function() { 396 | var db = EPRStorage.indexedDB.db; 397 | var trans = db.transaction(["manifest"], "readwrite"); 398 | var store = trans.objectStore("manifest"); 399 | 400 | var keyRange = IDBKeyRange.lowerBound(0); 401 | var cursorRequest = store.openCursor(keyRange); 402 | 403 | cursorRequest.onsuccess = function(e) { 404 | var result = e.target.result; 405 | if (!!result == false) 406 | { 407 | // If indexedDB is blank, initialize it with the static manifest data 408 | // and write it back out to indexedDB 409 | if (eprData.manifests.length == 0) { 410 | eprData.manifests = eprDataStatic.manifests; 411 | for (var i = 0; i < eprData.manifests.length; i++) 412 | { 413 | EPRStorage.indexedDB.addManifest( JSON.stringify(eprData.manifests[i]) ); 414 | } 415 | } 416 | return; 417 | } 418 | 419 | eprData.manifests.push( JSON.parse(result.value.text) ); 420 | result.continue(); 421 | }; 422 | 423 | cursorRequest.onerror = EPRStorage.indexedDB.onerror; 424 | }; 425 | 426 | EPRStorage.indexedDB.deleteManifest = function(id) { 427 | var db = EPRStorage.indexedDB.db; 428 | var trans = db.transation(["manifest"], "readwrite"); 429 | var store = trans.objectStore("manifest"); 430 | 431 | var request = store.delete(id); 432 | 433 | request.onsuccess = function(e) { 434 | 435 | }; 436 | 437 | request.onerror = function(e) { 438 | console.log(e); 439 | }; 440 | }; 441 | 442 | // Uncomment to temporarily clear IndexedDB 443 | // indexedDB.deleteDatabase("manifests"); 444 | // This can also be done from the F12 debugger UI 445 | 446 | // Open the db and get all the manifests 447 | EPRStorage.indexedDB.open(); 448 | } 449 | 450 | function xhrError(evt) { 451 | // We hit this when a connection is reset, etc. 452 | } 453 | 454 | function xhrLoad(evt) { 455 | handleXHRResponse(evt.target); 456 | } 457 | 458 | function handleXHRResponse(xhr) 459 | { 460 | var contentType; 461 | var failedParse; 462 | var receivedManifest, receivedManifestPos; 463 | 464 | // Validate the response is of the right type and of a reasonable size 465 | contentType = xhr.getResponseHeader("Content-Type"); 466 | if ((xhr.status === 200) && contentType && (contentType.indexOf("application/json") == 0) 467 | && (xhr.responseText.length < 5242880)) 468 | { 469 | failedParse = false; 470 | try { 471 | receivedManifest = JSON.parse(xhr.responseText); 472 | } catch (e) { 473 | failedParse = true; 474 | } 475 | 476 | if (!failedParse) 477 | { 478 | // Don't let a manifest specify what site it's for, override the site 479 | receivedManifest.site = xhr._urlProtocol + "//" + xhr._urlHostname; 480 | 481 | receivedManifestPos = eprData.manifests.push(receivedManifest) - 1; 482 | 483 | // Need to re-serialize the manifest if only because we changed the site 484 | // Then persist it in indexedDB 485 | EPRStorage.indexedDB.addManifest(JSON.stringify(receivedManifest)); 486 | } 487 | } 488 | else 489 | { 490 | // Push a manifest entry that prevents more manifest fetch attempts for the duration of this browsing session, for this host 491 | // If the JSON fails to parse then we still won't get here, but no big deal 492 | eprData.manifests.push( { "site": xhr._urlProtocol + "//" + xhr._urlHostname, "sessionIgnore": true } ); 493 | } 494 | } 495 | 496 | // Operates on responses that come in to check for and handle X-EPR header 497 | function lateRegulator(details) { 498 | var urlProtocol, urlHostname, urlPathname, urlSearch, urlHash; 499 | var retVal = false; 500 | var matchedStoredManifest; 501 | var xhr; 502 | var receivedManifest, receivedManifestPos; 503 | var bailOnRegulation; 504 | var sawEPRHeader = false; 505 | 506 | pathAnchor.href = details.url; 507 | urlProtocol = pathAnchor.protocol; 508 | urlHostname = pathAnchor.hostname; 509 | urlPathname = pathAnchor.pathname; 510 | urlSearch = pathAnchor.search; 511 | urlHash = pathAnchor.hash; 512 | 513 | // Bail immediately if this is a manifest request 514 | if (details.method === "GET" && urlPathname === "/epr-manifest.json" && urlSearch.length == 0 && urlHash.length == 0) 515 | { 516 | return {}; 517 | } 518 | 519 | for (var j = 0; j < details.responseHeaders.length; j++) { 520 | // Don't let multiple x-epr headers function 521 | if (sawEPRHeader) break; 522 | 523 | if ((details.responseHeaders[j].name.toLowerCase() === 'x-epr')) { 524 | if ((details.responseHeaders[j].value.charAt(0) === '1')) { 525 | // Now we know X-EPR is on the response. Go download and evaluate the manifest as necessary. 526 | sawEPRHeader = true; 527 | 528 | if (refererTracking[details.requestId]) { 529 | // If the referer scheme / domain matches the request, bail on regulation 530 | pathAnchor.href = refererTracking[details.requestId]; 531 | if ((pathAnchor.protocol == urlProtocol) && (pathAnchor.hostname == urlHostname)) { 532 | bailOnRegulation = true; 533 | } 534 | } 535 | else 536 | { 537 | bailOnRegulation = noRefererCheck(details, urlSearch, urlHash); 538 | } 539 | 540 | // We do actually need to validate the manifest here, to cover the case where a request is initiated before 541 | // there was a manifest (no validation), but by the time we get the response there is already a manifest 542 | // (no manifest fetch). 543 | matchedStoredManifest = false; 544 | for (var i = 0; i < eprData.manifests.length; i++) 545 | { 546 | if (retVal) break; 547 | 548 | pathAnchor.href = eprData.manifests[i].site; 549 | if ((pathAnchor.protocol != urlProtocol) || (pathAnchor.hostname != urlHostname)) continue; 550 | 551 | matchedStoredManifest = true; 552 | 553 | if (bailOnRegulation) continue; 554 | 555 | if (!eprData.manifests[i].sessionIgnore) 556 | { 557 | retVal = checkManifests(i, details.type, urlPathname, urlSearch, urlHash, details.method); 558 | } 559 | } 560 | 561 | // We didn't match an existing manifest. Try to fetch one if necessary. 562 | if (!matchedStoredManifest) 563 | { 564 | // Fetch the manifest 565 | // XSS on navigation can happen immediately, doesn't require the user to first auth to the site as with XSRF 566 | // Previously we were doing async fetches when XSS wasn't a concern, but it turns out XHR can hang in the 567 | // case where a sync request for a URL is made when an async request for the same URL is pending. It's 568 | // also just a wierd situation when an async request goes out but then a secondary sync request went out 569 | // for the same URL. 570 | // Anyway, going 100% synchronous eliminates the problems, reduces code complexity, and is reasonable given 571 | // that a manifest fetch is a rare operation. 572 | // 1/8/2015: Plot twist: The synchronous approach is considered problematic. Even though it wouldn't be a 573 | // common case, blocking downloads in this way would not be great. Moving to the "NO DATA" approach 574 | // described here: http://lists.w3.org/Archives/Public/public-webappsec/2014Nov/0018.html 575 | // This moves us back to model where we now will always download manifests asynchronously. 576 | 577 | xhr = new XMLHttpRequest(); 578 | xhr.addEventListener("error", xhrError, false); 579 | xhr.addEventListener("load", xhrLoad, false); 580 | xhr._urlProtocol = urlProtocol; 581 | xhr._urlHostname = urlHostname; 582 | 583 | xhr.open("GET", urlProtocol + "//" + urlHostname + "/epr-manifest.json", true); 584 | 585 | console.log("Making async manifest req for: " + details.url); 586 | try { 587 | xhr.send(null); 588 | } catch (e) 589 | { 590 | console.log("xhr error on manifest req for " + details.url); 591 | } 592 | 593 | // Ugly deep copy 594 | receivedManifest = JSON.parse(JSON.stringify(eprNoDataManifest)); 595 | 596 | // Don't let a manifest specify what site it's for, override the site 597 | receivedManifest.site = urlProtocol + "//" + urlHostname; 598 | 599 | receivedManifestPos = eprData.manifests.push(receivedManifest) - 1; 600 | if (!bailOnRegulation) 601 | { 602 | retVal = checkManifests(receivedManifestPos, details.type, urlPathname, urlSearch, urlHash, details.method); 603 | } 604 | } 605 | } 606 | } 607 | } 608 | 609 | // It's possible that we downloaded an evaluated a manifest, and it tells us to block the request 610 | // But at this point we already made the request. All we can do is block the response from being shown 611 | // This prevents XSS but not XSRF. That's fine though because with XSRF, you'd need to go authenticate 612 | // to the site at some earlier point, and a manifest would have been fetched at that point, allowing 613 | // the request to have been blocked before it even went out (in onBeforeSendHeaders). 614 | if (retVal) { 615 | return { redirectUrl: "data:text/plain;charset=utf-8,%23" }; 616 | } 617 | else { 618 | return { }; 619 | } 620 | 621 | } 622 | 623 | function deleteReferer(details) { 624 | // Just delete the referer as it's no longer necessary to track 625 | try { 626 | delete refererTracking[details.requestId]; 627 | } catch (e) {}; 628 | } 629 | 630 | pathAnchor = document.createElement('a'); 631 | 632 | bootWorker(); 633 | 634 | var EPRStorage = {}; 635 | EPRStorage.indexedDB = {}; 636 | configStorage(); 637 | 638 | bookmarkUrls = new Array(); 639 | chrome.bookmarks.getTree(grovelBookmarks); 640 | 641 | chrome.webRequest.onBeforeSendHeaders.addListener(regulator, {urls: [""]}, ["blocking", "requestHeaders"]); 642 | chrome.webRequest.onHeadersReceived.addListener(lateRegulator, {urls: [""]}, ["blocking", "responseHeaders"]); 643 | chrome.webRequest.onCompleted.addListener(deleteReferer, {urls: [""]}); 644 | -------------------------------------------------------------------------------- /epr-manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "site": "https://[Your EPR-enabled website]", 3 | "maxAge": 31536000, 4 | "reportUrl": "https://[Report URL]", 5 | "defaultNavBehavior": "block", 6 | "defaultResBehavior": "block", 7 | "rules": 8 | [ 9 | { "path": "/", "types": [ "navigation" ], "allowData": false }, 10 | { "regex": "^/\\d+$", "types": [ "navigation" ], "allowData": false }, 11 | { "path": "/image", "types": [ "image" ], "allowData": true }, 12 | { "regex": "^/(scoreboard|random|favorites|recentvisits|create)$", "types": [ "navigation" ], "allowData": false }, 13 | { "regex": "^/(recent|popular|metrics|template|search)$", "types": [ "navigation" ], "allowData": true }, 14 | ] 15 | } 16 | 17 | -------------------------------------------------------------------------------- /icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/google/epr/8f05300a3989ccc7e74f1da2d179064f902429dd/icon.png -------------------------------------------------------------------------------- /manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "manifest_version": 2, 3 | 4 | "name": "Entry Point Regulator Prototype", 5 | "author": "David Ross", 6 | "description": "Prototype implementation of Entry Point Regulation (EPR)", 7 | "short_name": "EPR Prototype", 8 | "version": "0.54", 9 | 10 | "background": { 11 | "scripts": ["background.js"] 12 | }, 13 | 14 | "permissions": [ "webRequest", "webRequestBlocking", "bookmarks", "unlimitedStorage", "*://*/*" ], 15 | "browser_action": { 16 | "default_icon": "icon.png", 17 | "default_popup": "popup.html" 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /popup.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Entry Point Regulator Prototype 7 | 8 | 9 | -------------------------------------------------------------------------------- /reWorker.js: -------------------------------------------------------------------------------- 1 | // Copyright 2014 Google Inc. All rights reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | self.addEventListener('message', function(message) { 16 | var re; 17 | 18 | re = new RegExp(message.data.regex); 19 | message.data.path.match(re); 20 | 21 | self.postMessage(true); 22 | }, false); 23 | -------------------------------------------------------------------------------- /spec/epr.bs: -------------------------------------------------------------------------------- 1 |

Entry Point Regulation for Web Applications

2 | 3 | 13 | 14 |

15 | Introduction

16 | 17 | This section is not normative. 18 | 19 | EPR provides a browser-enforced mechanism for validating an entry point 20 | policy supplied with a web application. External references and navigations 21 | to non-entry points can then be restricted based on this policy. 22 | 23 | Entry point regulation may be considered an implementation of concepts 24 | introduced by Charlie Reis et al. in 25 | App Isolation: Get the Security of Multiple Browsers with Just One. 26 | 27 |

28 | Usage Examples

29 | 30 | This section is not normative. 31 | 32 | This section shows how developers can make use of the various features of 33 | this specification. 34 | 35 |

36 | Example manifest

37 | 38 | This section is not normative. 39 | 40 | The following shows a typical manifest. 41 | 42 | ...TBD... 43 | 44 |

45 | Using the EPR HTTP response header to link to a manifest

46 | 47 | This section is not normative. 48 | 49 | ...TBD... 50 | 51 |

52 | Manifest and its members

53 | 54 | EPR manifests are JSON-based and overlap syntactically with 55 | web application manifests. 56 | 57 | ...More on EPR manifests... 58 | 59 |

60 | site member 61 |

62 | 63 | The site member is the URL for which the manifest should apply. The steps for 64 | processing the site member are given by the following algorithm. The 65 | algorithm returns a URL. 66 | 67 | HasOwnProperty 68 | 69 | GetOwnProperty 70 | 71 | [The following is a simple adaptation from text in the manifest spec, at the 72 | moment.] 73 | 74 |
    75 |
  1. If HasOwnProperty(manifest, "site") returns false, then return undefined.
  2. 76 |
  3. Let value be the result of calling the GetOwnProperty internal method of the manifest with argument "site".
  4. 77 |
78 | 79 | ...etc... 80 | 81 |

82 | maxAge 83 |

84 | 85 | ...etc... 86 | 87 |

88 | EPR HTTP response header 89 |

90 | 91 | [More about the EPR header] 92 | 93 |

94 | Manifest Handling

95 | 96 |

97 | Pre-Request Processing

98 | 99 | [Steps taken by a UA prior to an HTTP request being sent out.] 100 | 101 |

102 | Post-Response Processing

103 | 104 | [Steps taken by a UA immediately after a HTTP response is received, but before 105 | rendering content from the response.] 106 | 107 |

108 | Security Considerations

109 | 110 | [Discuss regex DoS, for example.] 111 | 112 |

113 | Acknowledgments

114 | 115 | Thanks for feedback and contributions from 116 | ... 117 | --------------------------------------------------------------------------------