Author: mikesamuel
Date: Mon Apr  6 11:27:36 2009
New Revision: 3406

Added:
   trunk/tests/com/google/caja/plugin/whitelisted_script.js
Modified:
   trunk/src/com/google/caja/lang/html/HtmlDefinitions.java
   trunk/src/com/google/caja/parser/html/DomParser.java
   trunk/src/com/google/caja/plugin/domita.js
   trunk/src/com/google/caja/plugin/html-sanitizer.js
   trunk/tests/com/google/caja/plugin/domita_test.html
   trunk/tests/com/google/caja/plugin/domita_test_untrusted.html

Log:
Issue 32092  http://codereview.appspot.com/32092
Allow dynamic script loading via proxy

Modifies domita to allow creation and manipulation of script elements.

Cajoled code can now create a script element, set its "src" attribute to
a URL passed through the url policy with the mime-type text/javascript, and
add that script to the DOM.  It cannot modify the textual content of a
script element.

Outstanding questions: do we need to prevent replay attacks and if so how?
If code can get a handle to a script element from the container, it
can clone it and add it to the DOM, possibly replaying script already
executed by the container.

Still TODO: http://code.google.com/p/google-caja/wiki/UrlPolicy

[email protected]


Modified: trunk/src/com/google/caja/lang/html/HtmlDefinitions.java
==============================================================================
--- trunk/src/com/google/caja/lang/html/HtmlDefinitions.java    (original)
+++ trunk/src/com/google/caja/lang/html/HtmlDefinitions.java Mon Apr 6 11:27:36 2009
@@ -76,6 +76,8 @@
      * HtmlSanitizer.java#isElementFoldable.
      */
     FOLDABLE(0x20),
+    SCRIPT(0x40),
+    STYLE(0x80),
     ;

     public final int bitMask;
@@ -114,7 +116,9 @@
         String key = e.getKey();
         Name elementName = Name.html(key.substring(0, key.indexOf(':')));
         if ("*".equals(elementName.getCanonicalForm())
-            || schema.isElementAllowed(elementName)) {
+            || schema.isElementAllowed(elementName)
+            // Whitelisted to allow dynamic script loading via proxy
+            || "script:src".equals(key)) {
           keys.add(StringLiteral.valueOf(unk, key));
values.add(new IntegerLiteral(unk, A_TYPE_MAP.get(e.getValue())));
         }
@@ -221,6 +225,11 @@
       }
       if (!schema.isElementAllowed(elementName)) {
         flags.add(EFlag.UNSAFE);
+        if (Name.html("script").equals(elementName)) {
+          flags.add(EFlag.SCRIPT);
+        } else if (Name.html("style").equals(elementName)) {
+          flags.add(EFlag.STYLE);
+        }
       }
       if (HtmlSchema.isElementFoldable(elementName)) {
         flags.add(EFlag.FOLDABLE);

Modified: trunk/src/com/google/caja/parser/html/DomParser.java
==============================================================================
--- trunk/src/com/google/caja/parser/html/DomParser.java        (original)
+++ trunk/src/com/google/caja/parser/html/DomParser.java Mon Apr 6 11:27:36 2009
@@ -229,7 +229,7 @@
               }
             } else {
               attribs = new ArrayList<DomTree.Attrib>();
-              end = parseTagAttributes(attribs);
+              end = parseTagAttributes(t.pos, attribs);
             }
             attribs = Collections.unmodifiableList(attribs);
             try {
@@ -259,7 +259,7 @@
    * token.
    */
   private Token<HtmlTokenType> parseTagAttributes(
-      List<? super DomTree.Attrib> children)
+      FilePosition start, List<? super DomTree.Attrib> children)
       throws ParseException {
     Token<HtmlTokenType> last;
     tokloop:
@@ -274,7 +274,7 @@
         break;
       default:
         throw new ParseException(new Message(
-            MessageType.MALFORMED_XHTML, last.pos,
+ MessageType.MALFORMED_XHTML, FilePosition.span(start, last.pos),
             MessagePart.Factory.valueOf(last.text)));
       }
     }

Modified: trunk/src/com/google/caja/plugin/domita.js
==============================================================================
--- trunk/src/com/google/caja/plugin/domita.js  (original)
+++ trunk/src/com/google/caja/plugin/domita.js  Mon Apr  6 11:27:36 2009
@@ -426,7 +426,10 @@
   }

   function mimeTypeForAttr(tagName, attribName) {
-    if (tagName === 'img' && attribName === 'src') { return 'image/*'; }
+    if (attribName === 'src') {
+      if (tagName === 'img') { return 'image/*'; }
+      if (tagName === 'script') { return 'text/javascript'; }
+    }
     return '*/*';
   }

@@ -730,7 +733,7 @@
                     html4.ATTRIBS.hasOwnProperty(attribKey))) {
               atype = html4.ATTRIBS[attribKey];
             } else {
-              return '';
+              return;
             }
             var value = attribs[i + 1];
             switch (atype) {
@@ -873,14 +876,6 @@
       switch (node.nodeType) {
         case 1:  // Element
           var tagName = node.tagName.toLowerCase();
-          if (!html4.ELEMENTS.hasOwnProperty(tagName)
-              || (html4.ELEMENTS[tagName] & html4.eflags.UNSAFE)) {
-            // If an unrecognized node, return a placeholder that
-            // doesn't prevent tree navigation, but that doesn't allow
-            // mutation or leak attribute information.
-            tamed = new TameOpaqueNode(node, editable);
-            break;
-          }
           switch (tagName) {
             case 'a':
               tamed = new TameAElement(node, editable);
@@ -898,6 +893,9 @@
             case 'img':
               tamed = new TameImageElement(node, editable);
               break;
+            case 'script':
+              tamed = new TameScriptElement(node, editable);
+              break;
             case 'td':
             case 'tr':
             case 'thead':
@@ -910,7 +908,16 @@
               tamed = new TameTableElement(node, editable);
               break;
             default:
-              tamed = new TameElement(node, editable);
+              if (!html4.ELEMENTS.hasOwnProperty(tagName)
+                  || (html4.ELEMENTS[tagName] & html4.eflags.UNSAFE)) {
+                // If an unrecognized or unsafe node, return a
+                // placeholder that doesn't prevent tree navigation,
+                // but that doesn't allow mutation or leak attribute
+                // information.
+                tamed = new TameOpaqueNode(node, editable);
+              } else {
+                tamed = new TameElement(node, editable, editable);
+              }
               break;
           }
           break;
@@ -1191,13 +1198,15 @@

     /**
      * A tame node that is backed by a real node.
+ * @param {boolean} childrenEditable true iff the child list is mutable.
      * @constructor
      */
-    function TameBackedNode(node, editable) {
+    function TameBackedNode(node, editable, childrenEditable) {
       if (!node) {
throw new Error('Creating tame node with undefined native delegate');
       }
       this.node___ = node;
+      this.childrenEditable___ = editable && childrenEditable;
       TameNode.call(this, editable);
     }
     classUtils.extend(TameBackedNode, TameNode);
@@ -1219,7 +1228,7 @@
     TameBackedNode.prototype.appendChild = function (child) {
// Child must be editable since appendChild can remove it from its parent.
       cajita.guard(tameNodeTrademark, child);
-      if (!this.editable___ || !child.editable___) {
+      if (!this.childrenEditable___ || !child.editable___) {
         throw new Error(NOT_EDITABLE);
       }
       this.node___.appendChild(child.node___);
@@ -1228,7 +1237,7 @@
       cajita.guard(tameNodeTrademark, toInsert);
       if (child === void 0) { child = null; }
       if (child !== null) { cajita.guard(tameNodeTrademark, child); }
-      if (!this.editable___ || !toInsert.editable___) {
+      if (!this.childrenEditable___ || !toInsert.editable___) {
         throw new Error(NOT_EDITABLE);
       }
       this.node___.insertBefore(
@@ -1236,7 +1245,7 @@
     };
     TameBackedNode.prototype.removeChild = function (child) {
       cajita.guard(tameNodeTrademark, child);
-      if (!this.editable___ || !child.editable___) {
+      if (!this.childrenEditable___ || !child.editable___) {
         throw new Error(NOT_EDITABLE);
       }
       this.node___.removeChild(child.node___);
@@ -1244,16 +1253,16 @@
     TameBackedNode.prototype.replaceChild = function (child, replacement) {
       cajita.guard(tameNodeTrademark, child);
       cajita.guard(tameNodeTrademark, replacement);
-      if (!this.editable___ || !replacement.editable___) {
+      if (!this.childrenEditable___ || !replacement.editable___) {
         throw new Error(NOT_EDITABLE);
       }
       this.node___.replaceChild(child.node___, replacement.node___);
     };
     TameBackedNode.prototype.getFirstChild = function () {
-      return tameNode(this.node___.firstChild, this.editable___);
+      return tameNode(this.node___.firstChild, this.childrenEditable___);
     };
     TameBackedNode.prototype.getLastChild = function () {
-      return tameNode(this.node___.lastChild, this.editable___);
+      return tameNode(this.node___.lastChild, this.childrenEditable___);
     };
     TameBackedNode.prototype.getNextSibling = function () {
// TODO(mikesamuel): replace with cursors so that subtrees are delegable
@@ -1275,14 +1284,15 @@
       return tameRelatedNode(this.node___.parentNode, this.editable___);
     };
     TameBackedNode.prototype.getElementsByTagName = function (tagName) {
- return tameGetElementsByTagName(this.node___, tagName, this.editable___);
+      return tameGetElementsByTagName(
+          this.node___, tagName, this.childrenEditable___);
     };
TameBackedNode.prototype.getElementsByClassName = function (className) {
       return tameGetElementsByClassName(
-          this.node___, className, this.editable___);
+          this.node___, className, this.childrenEditable___);
     };
     TameBackedNode.prototype.getChildNodes = function () {
-      return tameNodeList(this.node___.childNodes, this.editable___);
+ return tameNodeList(this.node___.childNodes, this.childrenEditable___);
     };
     TameBackedNode.prototype.getAttributes = function () {
       return tameNodeList(this.node___.attributes, this.editable___);
@@ -1623,7 +1633,7 @@


     function TameOpaqueNode(node, editable) {
-      TameBackedNode.call(this, node, editable);
+      TameBackedNode.call(this, node, editable, editable);
     }
     classUtils.extend(TameOpaqueNode, TameBackedNode);
     TameOpaqueNode.prototype.getNodeValue
@@ -1658,7 +1668,7 @@

     function TameAttrNode(node, editable) {
       assert(node.nodeType === 2);
-      TameBackedNode.call(this, node, editable);
+      TameBackedNode.call(this, node, editable, editable);
       classUtils.exportFields(
           this, ['name', 'nodeValue', 'value', 'specified']);
     }
@@ -1682,7 +1692,22 @@

     function TameTextNode(node, editable) {
       assert(node.nodeType === 3);
-      TameBackedNode.call(this, node, editable);
+
+ // The below should not be strictly necessary since childrenEditable for + // TameScriptElements is always false, but it protects against tameNode
+      // being called naively on a text node from container code.
+      var pn = node.parentNode;
+      if (editable && pn) {
+        if (1 === pn.nodeType
+            && (html4.ELEMENTS[pn.tagName.toLowerCase()]
+                & html4.eflags.UNSAFE)) {
+          // Do not allow mutation of text inside script elements.
+          // See the testScriptLoading testcase for examples of exploits.
+          editable = false;
+        }
+      }
+
+      TameBackedNode.call(this, node, editable, editable);
       classUtils.exportFields(this, ['nodeValue', 'data']);
     }
     classUtils.extend(TameTextNode, TameBackedNode);
@@ -1703,7 +1728,7 @@

     function TameCommentNode(node, editable) {
       assert(node.nodeType === 8);
-      TameBackedNode.call(this, node, editable);
+      TameBackedNode.call(this, node, editable, editable);
     }
     classUtils.extend(TameCommentNode, TameBackedNode);
     nodeClasses.CommentNode = TameCommentNode;
@@ -1767,9 +1792,9 @@
       throw new Error ("Not implemented.");
     };

-    function TameElement(node,editable) {
+    function TameElement(node, editable, childrenEditable) {
       assert(node.nodeType === 1);
-      TameBackedNode.call(this, node, editable);
+      TameBackedNode.call(this, node, editable, childrenEditable);
       classUtils.exportFields(
           this,
           ['className', 'id', 'innerHTML', 'tagName', 'style',
@@ -2046,8 +2071,8 @@
                     // which is why getters are not yet supported.
                     this.node___[attribName] = makeEventHandlerWrapper(
                         this.node___, listener);
-                    return listener;
                   }
+                  return listener;
                 });
            })(html4Attrib.match(attrNameRe)[1]);
         }
@@ -2055,7 +2080,7 @@
     })();

     function TameAElement(node, editable) {
-      TameElement.call(this, node, editable);
+      TameElement.call(this, node, editable, editable);
       classUtils.exportFields(this, ['href']);
     }
     classUtils.extend(TameAElement, TameElement);
@@ -2076,7 +2101,7 @@

     // http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-40002357
     function TameFormElement(node, editable) {
-      TameElement.call(this, node, editable);
+      TameElement.call(this, node, editable, editable);
       this.length = node.length;
       classUtils.exportFields(
           this,
@@ -2135,7 +2160,7 @@


     function TameInputElement(node, editable) {
-      TameElement.call(this, node, editable);
+      TameElement.call(this, node, editable, editable);
       classUtils.exportFields(
           this,
           ['form', 'value', 'defaultValue',
@@ -2337,7 +2362,7 @@


     function TameImageElement(node, editable) {
-      TameElement.call(this, node, editable);
+      TameElement.call(this, node, editable, editable);
       classUtils.exportFields(this, ['src', 'alt']);
     }
     classUtils.extend(TameImageElement, TameElement);
@@ -2346,25 +2371,45 @@
       return this.node___.src;
     };
     TameImageElement.prototype.setSrc = function (src) {
-      if (!this.editable___) { throw new Error(NOT_EDITABLE); }
       this.setAttribute('src', src);
       return src;
     };
     TameImageElement.prototype.getAlt = function () {
       return this.node___.alt;
     };
-    TameImageElement.prototype.setAlt = function (src) {
+    TameImageElement.prototype.setAlt = function (alt) {
       if (!this.editable___) { throw new Error(NOT_EDITABLE); }
-      this.node___.alt = src;
-      return src;
+      this.node___.alt = String(alt);
+      return alt;
     };
     ___.ctor(TameImageElement, TameElement, 'TameImageElement');
     ___.all2(___.grantTypedGeneric, TameImageElement.prototype,
              ['getSrc', 'setSrc', 'getAlt', 'setAlt']);

+    /**
+     * A script element wrapper that allows setting of a src that has been
+     * rewritten by a URL policy, but not modifying of textual content.
+     */
+    function TameScriptElement(node, editable) {
+      // Make the child list immutable so that text content can't be added
+      // or removed.
+      TameElement.call(this, node, editable, false);
+      classUtils.exportFields(this, ['src']);
+    }
+    classUtils.extend(TameScriptElement, TameElement);
+    nodeClasses.HTMLScriptElement = TameScriptElement;
+    TameScriptElement.prototype.getSrc = function () {
+      return this.node___.src;
+    };
+    TameScriptElement.prototype.setSrc = function (src) {
+      this.setAttribute('src', src);
+      return src;
+    };
+    ___.ctor(TameScriptElement, TameElement, 'TameScriptElement');
+

     function TameTableCompElement(node, editable) {
-      TameElement.call(this, node, editable);
+      TameElement.call(this, node, editable, editable);
       classUtils.exportFields(
           this,
           ['colSpan','cells','rowSpan','rows','rowIndex','align',
@@ -2759,11 +2804,11 @@
           // To avoid leaking information about the relative positioning of
// different roots, if neither contains the other, then we mask out
           // the preceeding/following bits.
-          // 0x18 is (CONTAINS | CONTAINED)
+          // 0x18 is (CONTAINS | CONTAINED).
           // 0x1f is all the bits documented at
- // http://www.w3.org/TR/DOM-Level-3-Core/core.html#DocumentPosition
-          //     except IMPLEMENTATION_SPECIFIC
-          // 0x01 is DISCONNECTED
+ // http://www.w3.org/TR/DOM-Level-3-Core/core.html#DocumentPosition
+          // except IMPLEMENTATION_SPECIFIC.
+          // 0x01 is DISCONNECTED.
           /*
           if (!(bitmask & 0x18)) {
// TODO: If they are not under the same virtual doc root, return
@@ -2784,7 +2829,8 @@
         ___.grantFunc(tameHtmlElement, 'compareDocumentPosition');
       }
       this.documentElement___ = tameHtmlElement;
- classUtils.exportFields(this, ['documentElement', 'body', 'title', 'domain']);
+      classUtils.exportFields(
+          this, ['documentElement', 'body', 'title', 'domain']);
     }
     classUtils.extend(TameHTMLDocument, TamePseudoNode);
     nodeClasses.HTMLDocument = TameHTMLDocument;
@@ -2840,7 +2886,8 @@
       return new TameCommentNode(this.doc___.createComment(" "), true);
     };
     TameHTMLDocument.prototype.createDocumentFragment = function () {
- return new TameBackedNode(this.doc___.createDocumentFragment(), this.editable___);
+      return new TameBackedNode(this.doc___.createDocumentFragment(),
+                                this.editable___);
     };
     TameHTMLDocument.prototype.createElement = function (tagName) {
       if (!this.editable___) { throw new Error(NOT_EDITABLE); }
@@ -2849,7 +2896,8 @@
         throw new Error(UNKNOWN_TAGNAME + "[" + tagName + "]");
       }
       var flags = html4.ELEMENTS[tagName];
-      if (flags & html4.eflags.UNSAFE) {
+      // Script exemption allows dynamic loading of proxied scripts.
+ if ((flags & html4.eflags.UNSAFE) && !(flags & html4.eflags.SCRIPT)) { cajita.log(UNSAFE_TAGNAME + "[" + tagName + "]: no action performed");
         return null;
       }

Modified: trunk/src/com/google/caja/plugin/html-sanitizer.js
==============================================================================
--- trunk/src/com/google/caja/plugin/html-sanitizer.js  (original)
+++ trunk/src/com/google/caja/plugin/html-sanitizer.js Mon Apr 6 11:27:36 2009
@@ -18,7 +18,7 @@
  *
  * <p>
  * The HTML sanitizer is built around a SAX parser and HTML element and
- * attributes schemas.
+ * attributes schemas.
  *
  * @author [email protected]
  * @requires html4
@@ -63,7 +63,7 @@
   var hexEscapeRe = /^#x([0-9A-Fa-f]+)$/;
   /**
    * Decodes an HTML entity.
-   *
+   *
    * {...@updoc
    * $ lookupEntity('lt')
    * # '<'

Modified: trunk/tests/com/google/caja/plugin/domita_test.html
==============================================================================
--- trunk/tests/com/google/caja/plugin/domita_test.html (original)
+++ trunk/tests/com/google/caja/plugin/domita_test.html Mon Apr 6 11:27:36 2009
@@ -29,12 +29,54 @@
     <script src="bridal.js" onerror="console.error(this.src)"></script>
<script src="html-emitter.js" onerror="console.error(this.src)"></script>
     <script src="domita.js" onerror="console.error(this.src)"></script>
+    <!-- Prime the browser cache by loading the whitelisted script
+      - synchronously so the test doesn't take so long. -->
+    <script src="whitelisted_script.js"
+     onerror="console.error(this.src)"></script>
+
+    <script src="../console.js"></script>

     <script type="text/javascript">
     function testDomita() {
       jsunitRun();
- assertTrue(document.title, / - all tests passed$/.test(document.title));
+      this.evaluateAsyncRequirements(function (pass) {
+        if (!pass) {
+          document.title = document.title.replace(
+              / - all tests passed$/, ' - async tests failed');
+        }
+        assertTrue(document.title,
+                   /(?: - all tests passed)?$/.test(document.title));
+      });
     }
+
+ // globalSideEffect() is not exposed to cajoled code, so if cajoled code
+    // can reach it, then it has escaped containment.
+ // checkGlobalSideEffect() is exposed to cajoled code and returns true iff
+    // globalSideEffect() has been called since the last call to
+    // checkGlobalSideEffect().
+    (function () {
+      var sideEffectHappened = false;
+      function globalSideEffect() { sideEffectHappened = true; }
+      function checkGlobalSideEffect() {
+        var result = sideEffectHappened;
+        sideEffectHappened = false;
+        return result;
+      }
+      this.globalSideEffect = globalSideEffect;
+      this.checkGlobalSideEffect = checkGlobalSideEffect;
+    })();
+
+    // Test that side effect catching works by trying it uncajoled.
+    jsunitRegister(
+        '_testSideEffectTestFramework',
+        function _testSideEffectTestFramework() {
+          assertFalse(checkGlobalSideEffect());
+          var s = document.createElement('SCRIPT');
+          s.innerHTML = 'globalSideEffect()';
+          document.body.appendChild(s);
+          assertTrue(checkGlobalSideEffect());
+          assertFalse(checkGlobalSideEffect());
+        });
     </script>
   </head>

@@ -68,7 +110,8 @@
       </div>

       <div class="testcontainer" id="test-opaque-nodes-xyz___"
-       ><!-- Comment -->a<script></script>b<object></object>c</div>
+ ><!-- Comment -->a<script id="howdy-script-xyz___">/* Howdy */</script
+       >b<object></object>c</div>
     </div>

     <script type="text/javascript">
@@ -157,7 +200,16 @@
           } else if (window.getComputedStyle) {
             return window.getComputedStyle(node, null)
                 .getPropertyValue(styleProp);
+          } else {
+            return null;
           }
+        }),
+        // Lets tests check that an outer hull breach -- access to
+        // an unexecuted script node -- does not allow a full breach.
+        makeUnattachedScriptNode: ___.frozenFunc(function () {
+          var s = document.createElement('script');
+ s.appendChild(document.createTextNode('/* intentionally blank */'));
+          return testImports.tameNode___(s, true);
         })
       });

@@ -170,6 +222,77 @@
         node.className = (node.className || '') + ' passed';
       }, 'pass');

+ testImports.checkGlobalSideEffect = ___.frozenFunc(checkGlobalSideEffect); + // An explicit channel between whitelisted_script.js and cajoled tests.
+      testImports.externalScript = { loaded: false };
+
+ // Define an asynchronous test mechanism so that we can test things like
+      // XHR, dynamic script loading, setTimeout, etc.
+      // This allows test code to requister conditions that must be true.
+      // The conditions can be run periodically until all are satisfied or
+      // the test times out.
+      // If a condition returns true once, it is never evaluated again.
+ // TODO(mikesamuel): rewrite XHR and setTimeout tests to use this scheme.
+      (function () {
+        var req = [];
+        var intervalId = null;
+        var TIMEOUT_MILLIS = 250;
+
+        /**
+         * Registers a requirement for later checking.
+         * @param {string} msg descriptive text used in error messages.
+ * @param {function () : boolean} predicate returns true to indicate
+         *     the requirement has been satisfied.
+         */
+        testImports.assertAsynchronousRequirement = ___.frozenFunc(
+            function (msg, predicate) {
+              req.push({ message: String(msg), predicate: predicate });
+            });
+        /**
+         * Start checking the asynchronous requirements.
+         * @param {function (boolean) : void} handler called with the value
+         *     {...@code true} when and if all requirements are satisfied.
+         *     Called with false if more than TIMEOUT_MILLIS time passes
+         *     and requirements still aren't satisfied.
+         */
+        this.evaluateAsyncRequirements = function (handler) {
+          if (intervalId !== null) { throw new Error('dupe handler'); }
+          if (req.length === 0) {
+            handler(true);
+          } else {
+            var timeoutTime = (new Date).getTime() + TIMEOUT_MILLIS;
+            intervalId = setInterval(function () {
+              for (var i = req.length; --i >= 0;) {
+                var msgAndPredicate = req[i];
+                try {
+                  if (true === ___.toFunc(msgAndPredicate.predicate)()) {
+                    // Requirement satisfied.
+                    req[i] = req[req.length - 1];
+                    --req.length;
+                  }
+                } catch (e) {
+                  console.error(
+                      'Asynchronous failure : ' + msgAndPredicate.message);
+                }
+              }
+ if (req.length === 0 || (new Date).getTime() >= timeoutTime) {
+                clearInterval(intervalId);
+                intervalId = null;
+
+                var failures = req.length !== 0;
+                if (failures) {
+                  for (var i = req.length; --i >= 0;) {
+                    console.error('async test timeout: ' + req[i].message);
+                  }
+                  req.length = 0;
+                }
+                handler(!failures);
+              }
+            }, 50);
+          }
+        };
+      })();
+
       var jsunitFns = [
           'assert', 'assertContains', 'assertEquals', 'assertEvaluatesToFalse',
           'assertEvaluatesToTrue', 'assertFalse', 'assertHTMLEquals',
@@ -192,7 +315,14 @@
            {
              rewrite:
                  function (uri, mimeType) {
-                   if (/\.\/xhrTest.*/.test(uri)) { return uri; }
+                   // TODO(mikesamuel): write this properly.
+                   // Whitelisting via regexp is not correct.
+                   var m = uri.match(
+                       /^([^?#]*\/)?unproxied_whitelisted_script\.js$/);
+ if (m) { return (m[1] || '') + 'whitelisted_script.js'; }
+                   if (/^(?:[^?#]*\/)?xhrTest[^\/?#]*$/.test(uri)) {
+                     return uri;
+                   }
                    if (!/^https?:\/\//i.test(uri)) { return null; }
return 'http://gadget-proxy/?url=' + encodeURIComponent(uri)
                        + '&mimeType=' + encodeURIComponent(mimeType);
@@ -210,8 +340,8 @@
           document, testDomContainer, false);

       testImports.htmlEmitter___ = new HtmlEmitter(testDomContainer);
-      if (valijaMaker) {
-        testImports.$v = valijaMaker.CALL___(testImports.outers);
+      if (valijaMaker) {
+        testImports.$v = valijaMaker.CALL___(testImports.outers);
       }
       window.toString = function () { return '[WINDOW]'; };
     })();</script>

Modified: trunk/tests/com/google/caja/plugin/domita_test_untrusted.html
==============================================================================
--- trunk/tests/com/google/caja/plugin/domita_test_untrusted.html       
(original)
+++ trunk/tests/com/google/caja/plugin/domita_test_untrusted.html Mon Apr 6 11:27:36 2009
@@ -104,7 +104,7 @@

 <div class="testcontainer" id="test-forms"></div>

-<div class="testcontainer" id="test-no-script"></div>
+<p class="testcontainer" id="test-script-loading"></p>

 <ol class="testcontainer" id="test-get-elements-by-tag-name">
   <li>One
@@ -910,25 +910,71 @@
   container.appendChild(div);
 }

-jsunitRegister('testCantLoadScript',
-               function testCantLoadScript() {
-  assertEquals(document.createElement('SCRIPT'), null);
-  assertEquals(document.createElement('script'), null);
-  assertEquals(document.createElement('scRipt'), null);
-
-  var node;
+jsunitRegister('testScriptLoading',
+               function testScriptLoading() {
+ // Test that we block ways scripts can be used to executed code in strings.
+  expectFailure(
+      function () {
+        var s = document.createElement('script');
+        s.appendChild(document.createTextNode('globalSideEffect()'));
+      }, 'script injection via appendChild');
+  assertFalse('gse1', checkGlobalSideEffect());
+  expectFailure(
+      function () {
+        var s = document.createElement('script');
+        s.innerHTML = 'globalSideEffect()';
+      }, 'script injection via innerHTML');
+  assertFalse('gse2', checkGlobalSideEffect());
+  expectFailure(
+      function () {
+        var s = directAccess.makeUnattachedScriptNode();
+        s.firstChild.nodeValue = 'globalSideEffect()';
+      }, 'script injection via nodeValue');
+  assertFalse('gse3', checkGlobalSideEffect());
+  expectFailure(
+      function () {
+        var os = document.getElementById('howdy-script');
+        var s = os.cloneNode(true);
+        s.firstChild.nodeValue = 'globalSideEffect()';
+      }, 'script injection via cloneNode');
+  assertFalse('gse4', checkGlobalSideEffect());
   assertFailsSafe(
       function () {
-        var i = 0;
-        node = document.createElement({
-          toString: function () { return (++i & 1) ? 'DIV' : 'SCRIPT'; }
-        });
+        var s = document.createElement('script');
+        s.innerText = 'globalSideEffect()';  // IE only, so failsafe.
+        document.body.appendChild(s);
       },
+      function () {});
+  assertFalse('gse5', checkGlobalSideEffect());
+  assertFailsSafe(
       function () {
-        assertEquals('DIV', node.tagName);
-      });
+        var s = document.createElement('script');
+        // IE only, so failsafe.
+        s.outerHTML = '<script>globalSideEffect()<\/script>';
+        document.body.appendChild(s);
+      },
+      function () {});
+  assertFalse('gse6', checkGlobalSideEffect());
+  assertFailsSafe(
+      function () {
+        var s = document.createElement('div');
+        // IE only, so failsafe.
+        s.outerHTML = '<script>globalSideEffect()<\/script>';
+        document.body.appendChild(s);
+      },
+      function () {});
+  assertFalse('gse7', checkGlobalSideEffect());
+
+ // Test that an external script can be loaded by setting the "src" attribute
+  // of a newly created script elements.
+  var s = document.createElement('script');
+  assertAsynchronousRequirement(
+      'whitelisted script never ran',
+      function () { return externalScript.loaded === true; });
+  s.src = 'unproxied_whitelisted_script.js';
+  document.getElementById('test-script-loading').appendChild(s);

-  pass('test-no-script');
+  pass('test-script-loading');
 });

 jsunitRegister('testGetElementsByTagName',
@@ -1206,7 +1252,7 @@
   assertEquals('SCRIPT', child.nodeName);
   assertEquals(null, child.nodeValue);
   expectFailure(function () { child.appendChild(noText); },
-                'opaque node was editable');
+                'script node was editable');

   child = child.nextSibling;
   assertEquals(3, child.nodeType);
@@ -1220,7 +1266,7 @@
   assertEquals('OBJECT', child.nodeName);
   assertEquals(null, child.nodeValue);
   expectFailure(function () { child.appendChild(noText); },
-                'opaque node was editable');
+                'object node was editable');

   child = child.nextSibling;
   assertEquals(3, child.nodeType);

Added: trunk/tests/com/google/caja/plugin/whitelisted_script.js
==============================================================================
--- (empty file)
+++ trunk/tests/com/google/caja/plugin/whitelisted_script.js Mon Apr 6 11:27:36 2009
@@ -0,0 +1,31 @@
+// Copyright (C) 2009 Google Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+/**
+ * @fileoverview
+ * Loaded by domita_test.html and associated tests to verify that dynamic script
+ * loading works.
+ */
+
+if (typeof ___ !== undefined) {
+  (function () {
+    var mh = ___.getNewModuleHandler();
+    if (mh) {
+      var imp = mh.getImports();
+      if (imp && imp.externalScript) {
+        imp.externalScript.loaded = true;
+      }
+    }
+  })();
+}

Reply via email to