An overview - XSLT: Extensible Stylesheet Language Transformations

An overview
===========

« Transforming XML with XSLT

The eXtensible Stylesheet Language/Transform is a very powerful language, and a complete discussion of it is well beyond the scope of this article, but a brief discussion of some basic concepts will be helpful in understanding the description of Netscape's capabilities that follows.

An XSLT stylesheet is an XML document.

Unlike CSS, which has its own specialized syntax, an XSLT stylesheet is an XML document, which must conform to all XML rules, including well-formedness. So the model for transformation is that one XML document is used to transform another XML document.

An XSLT stylesheet is marked as such by the inclusion of a standard XSLT heading.

The outermost element in an XSLT stylesheet must be the `<xsl:stylesheet>` element (an acceptable alternate is the `<xsl:transform>` element). This element will include at least one namespace declaration and the mandatory version attribute. Other namespaces and three optional attributes may also be included.

The mandatory namespace for XSLT is `"http://www.w3.org/1999/XSL/Transform"`.

Namespaces are the subject of a fair amount of confusion in XML. Despite the fact that very often namespaces appear to be URIs, they do not, in fact, refer to a resource located at that address. Instead they are a way of specifying a unique identifier for a known set of elements. The string `"http://www.w3.org/1999/XSL/Transform"` is a constant that designates the elements so marked as belonging to the set of tags designated by the W3C in the 1999 XSLT Recommendation. Another string that is occasionally seen in stylesheets, `"http://www.w3.org/TR/WD-xsl"`, indicates compliance with an earlier working draft (hence the WD) of the W3C document. This latter namespace is not compatible with the one that the W3C eventually adopted and is not supported by Netscape.

Because typing `"http://www.w3.org/1999/XSL/Transform"` repeatedly would be tedious and would render the markup difficult to read, there is a standard mechanism for assigning a shorthand name to the namespace in the stylesheet heading. Thus a full example of the opening stylesheet element might look like this.

`<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">`

The xmlns pseudo-attribute maps the shorthand name xsl onto the full namespace for use throughout the document that follows. Thus the stylesheet element above is prefixed with `xsl:`. Although xsl is the conventionally used shorthand name (called the prefix), it is not mandatory and it is quite possible to choose a different one. The examples in this article all assume the use of the xsl prefix.

All XSLT transformations are performed on trees, not documents.

The XSLT transformation engine, called the processor, does not work directly on documents. Before transformation can take place, the primary XML document(s) and the stylesheet document(s) must be run through a parser, which creates an abstract representation of the structure of the document in memory. This representation, called the tree, is what is actually manipulated by the processor. The tree is an abstract datatype, a conceptual model which can be implemented in various ways depending on the parser and the processor. :Netscape's uses a structure similar to the W3C DOM as its tree structure, but others are possible. The only requirements concern the disposition of objects in the tree, their properties, and their relationships.

The tree consists of a hierarchical framework of nodes. It can be made up of seven different types of nodes: the single root node, element nodes, text nodes, attribute nodes, comment nodes, processing instruction nodes, and namespace nodes.

At the top of the tree is the root node. The root node does not correspond to any individual part of the XML document: it represents the document as whole. Below the root node are its children, which can be elements, comments, processing instructions and so on. Some of those children may also have children. And this can continue for several levels. There are certain constraints on which type of nodes can occur where: for example, text nodes can have no children.

The result of the processor's action is also a tree. Netscape uses this tree to render the contents in the browser window.

XSLT is a high-level declarative language.

In essence, an XSLT stylesheet is a set of rules, called templates, which declare that any node that matches this specific pattern should be manipulated in this specific way and end up in this specific position in the result tree. The particulars of how this is to be accomplished are left up to the processor. Because the order of execution of the stylesheet cannot be guaranteed, XSLT does not support any functionality that produces side-effects. In this it is like Lisp or Scheme.

Locations on the tree are specified using XPath, another W3C Recommendation.

Transformations depend on the processor's being able to pinpoint individual nodes on the tree. To facilitate this, the W3C decided to use a separate language, XPath, which also has uses outside the XSLT context. As its name implies, XPath defines a "path" the processor must take through the tree to arrive at the desired node. This path consists of XPath-specific expressions to be evaluated, expressions which may include a number of conditions to be matched, a way of associating nodes, and/or an indication of directionality within the tree. A fuller description of the parts of XPath most commonly used in XSLT follows in the reference section.

Potential conflicts in template matching are resolved by using a set of cascading precedence rules.

In general, a more specific template rule takes precedence over a less specific one and, other things being equal, a template rule that appears later in the document takes precedence over one that appears earlier.

Stylesheets can be attached to an XML document via a processing instruction.

The simplest way to indicate which XSLT stylesheet should be used to process a particular XML document is to include a processing instruction in the XML document itself. For example, if the stylesheet is called inventory.xsl and resides in the same directory as the XML document, the processing instruction in the XML document would look like this:

`<?xml-stylesheet type="text/xml" href="inventory.xsl"?>`

This must be placed in the prolog section of the XML document.

To learn more about XSLT and XPath, see the For Further Reading section at the end of this article.


parent - XSLT: Extensible Stylesheet Language Transformations

parent
======

The parent axis indicates the single node that is the parent of the context node. It can be abbreviated as two periods (`..`).


child - XSLT: Extensible Stylesheet Language Transformations

child
=====

The child axis indicates the children of the context node. If an XPath expression does not specify an axis, the child axis is understood by default. Since only the root node or element nodes have children, any other use will select nothing.


ancestor - XSLT: Extensible Stylesheet Language Transformations

ancestor
========

The ancestor axis indicates all the ancestors of the context node beginning with the parent node and traveling through to the root node.


attribute - XSLT: Extensible Stylesheet Language Transformations

attribute
=========

The attribute axis indicates the attributes of the context node. Only elements have attributes. This axis can be abbreviated with the at sign (`@`).


following-sibling - XSLT: Extensible Stylesheet Language Transformations

following-sibling
=================

The following-sibling axis indicates all the nodes that have the same parent as the context node and appear after the context node in the source document.


self - XSLT: Extensible Stylesheet Language Transformations

self
====

The self axis indicates the context node itself. It can be abbreviated as a single period (`.`).


descendant-or-self - XSLT: Extensible Stylesheet Language Transformations

descendant-or-self
==================

The descendant-or-self axis indicates the context node and all of its descendants. Attribute and namespace nodes are **not** included - the parent of an attribute node is an element node, but attribute nodes are not the children of their parents.


preceding - XSLT: Extensible Stylesheet Language Transformations

preceding
=========

The preceding axis indicates all the nodes that precede the context node in the document except any ancestor, attribute, and namespace nodes.


preceding-sibling - XSLT: Extensible Stylesheet Language Transformations

preceding-sibling
=================

The preceding-sibling axis indicates all the nodes that have the same parent as the context node and appear before the context node in the source document.


following - XSLT: Extensible Stylesheet Language Transformations

following
=========

The following axis indicates all the nodes that appear after the context node, except any descendant, attribute, and namespace nodes.


ancestor-or-self - XSLT: Extensible Stylesheet Language Transformations

ancestor-or-self
================

The ancestor-or-self axis indicates the context node and all of its ancestors, including the root node.


descendant - XSLT: Extensible Stylesheet Language Transformations

descendant
==========

The descendant axis indicates all of the children of the context node, and all of their children, and so forth. Attribute and namespace nodes are **not** included - the parent of an attribute node is an element node, but attribute nodes are not the children of their parents.


namespace - XSLT: Extensible Stylesheet Language Transformations

namespace
=========

The namespace axis indicates all the nodes that are in scope for the context node. In this case, the context node must be an element node.


<xsl:decimal-format> - XSLT: Extensible Stylesheet Language Transformations

<xsl:decimal-format>
====================

The `<xsl:decimal-format>` element defines the characters and symbols that are to be used in converting numbers into strings using the `format-number( )` function.

### Syntax

```xml
<xsl:decimal-format
 name=NAME
 decimal-separator=CHARACTER
 grouping-separator=CHARACTER
 infinity=STRING
 minus-sign=CHARACTER
 NaN=STRING
 percent=CHARACTER
 per-mille=CHARACTER
 zero-digit=CHARACTER
 digit=CHARACTER
 pattern-separator=CHARACTER />
```

### Required Attributes

None.

### Optional Attributes

`name`

Specifies a name for this format.

`decimal-separator`

Specifies the decimal point character. The default is (`.`).

`grouping-separator`

Specifies the thousands separator character. The default is (`,`).

`infinity`

Specifies the string used to represent infinity. The default is the string "`Infinity`".

`minus-sign`

Specifies the minus sign character. The default is the hyphen (`-`).

`NaN`

Specifies the string used when the value is not a number. The default is the string "`NaN`".

`percent`

Specifies the percentage sign character. The default is (`%`).

`per-mille`

Specifies the per thousand character. The default is (`‰`).

`zero-digit`

Specifies the digit zero character. The default is (`0`).

`digit`

Specifies the character used in the format pattern to stand for a digit. The default is (`#`).

`pattern-separator`

Specifies the character separating positive and negative subpatterns in a format pattern. The default is the semicolon (`;`).

### Type

Top-level, must be the child of `<xsl:stylesheet>` or `<xsl:transform>`.

### Defined

XSLT, section 12.3.

### Gecko support

Supported as of 1.0 (Mozilla 1.0, Netscape 7.0).


<xsl:with-param> - XSLT: Extensible Stylesheet Language Transformations

<xsl:with-param>
================

The `<xsl:with-param>` element sets the value of a parameter to be passed into a template.

### Syntax

```xml
<xsl:with-param name=NAME select=EXPRESSION>
  TEMPLATE
</xsl:with-param>
```

### Required Attributes

`name`

Gives this parameter a name.

### Optional Attributes

`select`

Defines the value of the parameter through an XPath expression. If the element contains a template, this attribute is ignored.

### Type

Subinstruction, always appears within an `<xsl:apply-templates>` or an `<xsl:call-template>` element.

### Defined

XSLT 11.6

### Gecko support

Supported.


<xsl:choose> - XSLT: Extensible Stylesheet Language Transformations

<xsl:choose>
============

The `<xsl:choose>` element defines a choice among a number of alternatives. It behaves like a switch statement in procedural languages.

### Syntax

```xml
<xsl:choose>
  <xsl:when test="[whatever to test1]"></xsl:when>
  <xsl:when test="[whatever to test2]"></xsl:when>
  <xsl:otherwise></xsl:otherwise> [optional]
</xsl:choose>
```

### Required Attributes

None.

### Optional Attributes

None.

### Type

Instruction, appears with a template. It contains one or more `<xsl:when>` elements, and, optionally, a final `<xsl:otherwise>` element.

### Defined

XSLT, section 9.2.

### Gecko support

Supported.


<xsl:copy> - XSLT: Extensible Stylesheet Language Transformations

<xsl:copy>
==========

The `<xsl:copy>` element transfers a shallow copy (the node and any associated namespace node) of the current node to the output document. It does not copy any children or attributes of the current node.

### Syntax

```xml
<xsl:copy use-attribute-sets=LIST-OF-NAMES>
  TEMPLATE
</xsl:copy>
```

### Required Attributes

None.

### Optional Attributes

`use-attribute-sets`

Lists attribute sets that should be applied to the output node, if it is an element. Names of the sets should be separated with whitespace characters.

### Type

Instruction, appears within a template.

### Defined

XSLT, section 7.5.

### Gecko support

Supported.


<xsl:sort> - XSLT: Extensible Stylesheet Language Transformations

<xsl:sort>
==========

The `<xsl:sort>` element defines a sort key for nodes selected by `<xsl:apply-templates>` or `<xsl:for-each>` and determines the order in which they are processed.

### Syntax

```xml
<xsl:sort
 select=EXPRESSION
 order="ascending" | "descending"
 case-order="upper-first" | "lower-first"
 lang=XML:LANG-CODE
 data-type="text" | "number" />
```

### Required Attributes

None.

### Optional Attributes

`select`

Uses an XPath expression to specify the nodes to be sorted.

`order`

Specifies whether the nodes should be processed in "`ascending`" or "`descending`" order. The default is "`ascending`".

`case-order`

Indicates whether upper- or lowercase letters are to be ordered first. The allowable values are "`upper-first`" and "`lower-first`".

`lang`

Specifies which language is to be used by the sort.

`data-type`

Defines whether items are to be ordered alphabetically or numerically. The allowable values are "`text`" and "`number`" with "`text`" being the default.

### Type

Subinstruction, always appears as a child of <xsl:for-each>, where it must appear before the template proper or of <xsl:apply-templates>.

### Defined

XSLT, section10.

### Gecko support

Supported.


<xsl:transform> - XSLT: Extensible Stylesheet Language Transformations

<xsl:transform>
===============

The `<xsl:transform>` element is exactly equivalent to the `<xsl:stylesheet>` element.

### Gecko support

Supported.


<xsl:for-each> - XSLT: Extensible Stylesheet Language Transformations

<xsl:for-each>
==============

The `<xsl:for-each>` element selects a set of nodes and processes each of them in the same way. It is often used to iterate through a set of nodes or to change the current node. If one or more `<xsl:sort>` elements appear as the children of this element, sorting occurs before processing. Otherwise, nodes are processed in document order.

### Syntax

```xml
<xsl:for-each select=EXPRESSION>
  <xsl:sort> [optional]
  TEMPLATE
</xsl:for-each>
```

### Required Attributes

`select`

Uses an XPath expression to select nodes to be processed.

### Optional Attributes

None.

### Type

Instruction, appears within a template.

### Defined

XSLT, section 8.

### Gecko support

Supported.


<xsl:fallback> - XSLT: Extensible Stylesheet Language Transformations

<xsl:fallback>
==============

The `<xsl:fallback>` element specifies what template to use if a given extension (or, eventually, newer version) element is not supported.

### Syntax

```xml
<xsl:fallback>
  TEMPLATE
</xsl:fallback>
```

### Required Attributes

None.

### Optional Attributes

None.

### Type

Instruction, appears within a template.

### Defined

XSLT, section 15

### Gecko support

Not supported at this time.


<xsl:import> - XSLT: Extensible Stylesheet Language Transformations

<xsl:import>
============

The `<xsl:import>` element is a top-level element that serves to import the contents of one stylesheet into another stylesheet. Generally speaking, the contents of the imported stylesheet have a lower import precedence than that of the importing stylesheet. This is in contrast to `<xsl:include>` where the contents of the included stylesheet have exactly the same precedence as the contents of the including stylesheet.

### Syntax

```xml
<xsl:import href=URI />
```

### Required Attributes

`href`

Specifies the URI of the stylesheet to import.

### Optional Attributes

None.

### Type

Top-level, must appear before any other child of `<xsl:stylesheet>` or `<xsl:transform>` in the importing stylesheet.

### Defined

XSLT, section 2.6.2.

### Gecko support

Mostly supported with a few issues with top level variables and parameters as of Mozilla 1.0.


<xsl:variable> - XSLT: Extensible Stylesheet Language Transformations

<xsl:variable>
==============

The `<xsl:variable>` element declares a global or local variable in a stylesheet and gives it a value. Because XSLT permits no side-effects, once the value of the variable has been established, it remains the same until the variable goes out of scope

### Syntax

```xml
<xsl:variable name=NAME select=EXPRESSION >
  TEMPLATE
</xsl:variable>
```

### Required Attributes

`name`

Gives the variable a name.

### Optional Attributes

`select`

Defines the value of the variable through an XPath expression. If the element contains a template, this attribute is ignored.

### Type

Top-level or instruction. If it occurs as a top-level element, the variable is global in scope, and can be accessed throughout the document. If it occurs within a template, the variable is local in scope, accessible only within the template in which it appears.

### Defined

XSLT, section 11.

### Gecko support

Supported.


<xsl:when> - XSLT: Extensible Stylesheet Language Transformations

<xsl:when>
==========

The `<xsl:when>` element always appears within an `<xsl:choose>` element, acting like a case statement.

### Syntax

```xml
<xsl:when test=EXPRESSION>
  TEMPLATE
</xsl:when>
```

### Required Attributes

`test`

Specifies a boolean expression to be evaluated. If true, the contents of the element are processed; if false, they are ignored.

### Optional Attributes

None.

### Type

Subinstruction, always appears within an `<xsl:choose>` element.

### Defined

XSLT, section 9.2.

### Gecko support

Supported.


<xsl:stylesheet> - XSLT: Extensible Stylesheet Language Transformations

<xsl:stylesheet>
================

The `<xsl:stylesheet>` element (or the equivalent `<xsl:transform>` element) is the outermost element of a stylesheet.

### Namespace Declaration

A pseudo-attribute required to identify the document as an XSLT stylesheet. Typically this is `xmlns:xsl="http://www.w3.org/1999/XSL/Transform"`.

Syntax
------

```xml
<xsl:stylesheet
 version="NUMBER"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 id="NAME"
 extension-element-prefixes="LIST-OF-NAMES"
 exclude-result-prefixes="LIST-OF-NAMES">
    ENTIRE STYLESHEET
</xsl:stylesheet>
```

### Required Attributes

`version`

Specifies the version of XSLT required by this stylesheet.

### Optional Attributes

`exclude-result-prefixes`

Specifies any namespace used in this document that should not be sent to the output document. The list is whitespace separated.

`extension-element-prefixes`

Specifies a space-separated list of any namespace prefixes for extension elements in this document.

`default-collation`

Specifies the default collation used by all XPath expressions appearing in attributes or text value templates that have the element as an ancestor, unless overridden by another `default-collation` attribute on an inner element. It also determines the collation used by certain XSLT constructs (such as `<xsl:key>` and `<xsl:for-each-group>`) within its scope.

`default-mode`

Defines the default value for the `mode` attribute of all `<xsl:template>` and `<xsl:apply-templates>` elements within its scope.

`default-validation`

Defines the default value of the `validation` attribute of all relevant instructions appearing within its scope.

`expand-text`

Determines whether descendant text nodes of the element are treated as text value templates.

`id`

Specifies an `id` for this stylesheet. This is most often used when the stylesheet is embedded in another XML document.

`input-type-annotations`

Specifies whether type annotations are stripped from the element so the same results are produced whether the source documents have been validated against a schema or not.

`use-when`

Determines whether the element and all the nodes that have it as ancestor are excluded from the stylesheet.

`xpath-default-namespace`

Specifies the namespace that will be used if the element name is unprefixed or an unprefixed type name within an XPath expression.

### Type

Required outermost element of stylesheet.

Specifications
--------------

| Specification |
| --- |
| XSLT 3.0 # stylesheet-element |


<xsl:message> - XSLT: Extensible Stylesheet Language Transformations

<xsl:message>
=============

The `<xsl:message>` element outputs a message (to the JavaScript Console in NS) and optionally terminates execution of the stylesheet. It can be useful for debugging.

### Syntax

```xml
<xsl:message terminate="yes" | "no" >
  TEMPLATE
</xsl:message>
```

### Required Attributes

None.

### Optional Attributes

`terminate`

Set to "`yes`", indicates that execution should be terminated. The default value is "`no`", in which case the message is output and execution continues.

### Type

Instruction, appears within a template.

### Defined

XSLT, section 13.

### Gecko support

Supported.


<xsl:output> - XSLT: Extensible Stylesheet Language Transformations

<xsl:output>
============

The `<xsl:output>` element controls the characteristics of the output document. To function correctly in Netscape, this element, with the method attribute, must be used. As of 7.0, `method="text"` works as expected.

### Syntax

```xml
<xsl:output
 method="xml" | "html" | "text"
 version=STRING
 encoding=STRING
 omit-xml-declaration="yes" | "no"
 standalone="yes" | "no"
 doctype-public=STRING
 doctype-system=STRING
 cdata-section-elements=LIST-OF-NAMES
 indent="yes" | "no"
 media-type=STRING />
```

### Required Attributes

None.

### Optional Attributes

`method`

Specifies output format.

`version`

Specifies the value of the version attribute of the XML or HTML declaration in the output document. This attribute is only used when `method="html"` or `method="xml"`.

`encoding`

Specifies the value of the `encoding` attribute in the output document.

`omit-xml-declaration`

Indicates whether or not to include an XML declaration in the output. Acceptable values are "`yes`" or "`no`".

`standalone` (Not supported.)

If present, indicates that a standalone declaration should occur in the output document and gives its value. Acceptable values are "yes" or "no".

`doctype-public`

Specifies the value of the `PUBLIC` attribute of the `DOCTYPE` declaration in the output document.

`doctype-system`

Specifies the value of the `SYSTEM` attribute of the `DOCTYPE` declaration in the output document.

`cdata-section-elements`

Lists elements whose text contents should be written as `CDATA` sections. Elements should be whitespace separated.

`indent` (Not supported.)

Specifies if the output should be indented to indicate its hierarchic structure.

`media-type` (Not supported.)

Specifies the output document MIME type.

### Type

Top-level, must be the child `<xsl:stylesheet>` or `<xsl:transform>`.

### Defined

XSLT, section 16.

### Gecko support

Partial support. See comments above.


<xsl:namespace-alias> - XSLT: Extensible Stylesheet Language Transformations

<xsl:namespace-alias>
=====================

The `<xsl:namespace-alias>` element is a rarely used device that maps a namespace in the stylesheet to a different namespace in the output tree. The most common use for this element is in generating a stylesheet from another stylesheet. To prevent a normally `xsl:`-prefixed literal result element (which should be copied as-is to the result tree) from being misunderstood by the processor, it is assigned a temporary namespace which is appropriately re-converted back to the XSLT namespace in the output tree.

### Syntax

```xml
<xsl:namespace-alias stylesheet-prefix=NAME result-prefix=NAME />
```

### Required Attributes

`stylesheet-prefix`

Specifies the temporary namespace.

`result-prefix`

Specifies the desired namespace for the output tree.

### Optional Attributes

None.

### Type

Top-level, must be the child of `<xsl:stylesheet>` or `<xsl:transform>`.

### Defined

XSLT, section 7.1.1

### Gecko support

Not supported at this time.


<xsl:comment> - XSLT: Extensible Stylesheet Language Transformations

<xsl:comment>
=============

The `<xsl:comment>` element writes a comment to the output document. It must include only text.

### Syntax

```xml
<xsl:comment>
  TEMPLATE
</xsl:comment>
```

### Required Attributes

None.

### Optional Attributes

None.

### Type

Instruction, appears within a template.

### Defined

XSLT, section 7.4.

### Gecko support

Supported.


<xsl:if> - XSLT: Extensible Stylesheet Language Transformations

<xsl:if>
========

The `<xsl:if>` element contains a test attribute and a template. If the test evaluates to true, the template is processed. In this it is similar to an if statement in other languages. To achieve the functionality of an if-then-else statement, however, use the `<xsl:choose>` element with one `<xsl:when>` and one `<xsl:otherwise>` children.

### Syntax

```xml
<xsl:if test=EXPRESSION>
  TEMPLATE
</xsl:if>
```

### Required Attributes

`test`

Contains an XPath expression that can be evaluated (using the rules defined for `boolean( )` if necessary) to a Boolean value. If the value is true, the template is processed; if it is not, no action is taken.

### Optional Attributes

None.

### Type

Instruction, appears within a template.

### Defined

XSL section 9.1.

### Gecko support

Supported


<xsl:element> - XSLT: Extensible Stylesheet Language Transformations

<xsl:element>
=============

The `<xsl:element>` element creates an element in the output document.

### Syntax

```xml
<xsl:element name=NAME namespace=URI use-attribute-sets=LIST-OF-NAMES >
  TEMPLATE
</xsl:element>
```

### Required Attributes

`name`

Specifies the desired name of the output element. The name must be a valid QName.

### Optional Attributes

`namespace`

Specifies the namespace of the output element.

`use-attribute-sets`

A whitespace‐separated list of `attribute-set` element names to be applied to the `element` element's output element. Applied attributes can be overridden via nested `attribute` elements.

### Type

Instruction, appears within a template.

### Defined

XSLT, section 7.1.2.

### Gecko support

Supported.


<xsl:copy-of> - XSLT: Extensible Stylesheet Language Transformations

<xsl:copy-of>
=============

The `<xsl:copy-of>` element makes a deep copy (including descendant nodes) of whatever the select attribute specifies to the output document.

### Syntax

```xml
<xsl:copy-of select=EXPRESSION />
```

### Required Attributes

`select`

Uses an XPath expression that specifies what is to be copied.

### Optional Attributes

None.

### Type

Instruction, appears within a template.

### Defined

XSLT, section 11.3.

### Gecko support

Supported.


<xsl:template> - XSLT: Extensible Stylesheet Language Transformations

<xsl:template>
==============

The `<xsl:template>` element defines an output producing template. This element must have either the match attribute or the name attribute set.

### Syntax

```xml
<xsl:template
 match=PATTERN
 name=NAME
 mode=NAME
 priority=NUMBER>
  <xsl:param> [optional]
  TEMPLATE
</xsl:template>
```

### Required Attributes

None.

### Optional Attributes

`match`

Specifies a pattern that determines the elements for which this template should be used. It is a required attribute if there is no `name` attribute.

`name`

Specifies a name for this template, by which it can be invoked through the `<xsl:call-template>` element.

`mode`

Specifies a particular mode for this template, which can be matched by an attribute of the `<xsl:apply-templates>` element. This is useful for processing the same information in multiple ways.

`priority`

Specifies a numeric priority for this template. This can be any number other than `Infinity`. The processor uses this number when more than one template matches the same node.

### Type

Top-level, must be the child of `<xsl:stylesheet>` or `<xsl:transform>`.

### Defined

XSLT, section 5.3.

### Gecko support

Supported.


<xsl:otherwise> - XSLT: Extensible Stylesheet Language Transformations

<xsl:otherwise>
===============

The `<xsl:otherwise>` element is used to define the action that should be taken when none of the `<xsl:when>` conditions apply. It is similar to the `else` or `default` case in other programming languages.

### Syntax

```xml
<xsl:otherwise>
  TEMPLATE
</xsl:otherwise>
```

### Required Attributes

None.

### Optional Attributes

None.

### Type

Subinstruction, must appear as the last child of an `<xsl:choose>` element, within a template.

### Defined

XSLT, section 9.2

### Gecko support

Supported.


<xsl:apply-templates> - XSLT: Extensible Stylesheet Language Transformations

<xsl:apply-templates>
=====================

The `<xsl:apply-templates>` element selects a set of nodes in the input tree and instructs the processor to apply the proper templates to them.

### Syntax

```xml
<xsl:apply-templates select=EXPRESSION mode=NAME>
  <xsl:with-param> [optional]
  <xsl:sort> [optional]
</xsl:apply-templates>
```

### Required Attributes

None.

### Optional Attributes

`select`

Uses an XPath expression that specifies the nodes to be processed. An asterisk(`*`) selects the entire node-set. If this attribute is not set, all child nodes of the current node are selected.

`mode`

If there are multiple ways of processing defined for the same node, distinguishes among them.

### Type

Instruction, appears within a template.

### Defined

XSLT section 5.4.

### Gecko support

Supported.


<xsl:param> - XSLT: Extensible Stylesheet Language Transformations

<xsl:param>
===========

The `<xsl:param>` element establishes a parameter by name and, optionally, a default value for that parameter. When used as a top-level element, the parameter is global. When used inside an `<xsl:template>` element, the parameter is local to that template. In this case it must be the first child element of the template.

### Syntax

```xml
<xsl:param name=NAME select=EXPRESSION>
  TEMPLATE
</xsl:param>
```

### Required Attributes

`name`

Names the parameter. This must be a QName.

### Optional Attributes

`select`

Uses an XPath expression to provide a default value if none is specified.

### Type

Instruction, can appear as a top-level element or within a template.

### Defined

XSLT, section 11.

### Gecko support

Supported.


<xsl:number> - XSLT: Extensible Stylesheet Language Transformations

<xsl:number>
============

The `<xsl:number>` element counts things sequentially. It can also be used to quickly format a number.

### Syntax

```xml
<xsl:number
 count=EXPRESSION
 level="single" | "multiple" | "any"
 from=EXPRESSION
 value=EXPRESSION
 format=FORMAT-STRING
 lang=XML:LANG-CODE
 letter-value="alphabetic" | "traditional"
 grouping-separator=CHARACTER
 grouping-size=NUMBER />
```

### Required Attributes

None.

### Optional Attributes

`count`

Specifies what in the source tree should be numbered sequentially. It uses an XPath expression.

`level`

Defines how levels of the source tree should be considered in generating sequential numbers. It has three valid values: `single`, `multiple`, and `any`. The default value is `single`:

`single`

Numbers sibling nodes sequentially, as in the items in a list. The processor goes to the first node in the `ancestor-or-self` axis that matches the `count` attribute and then counts that node plus all its preceding siblings (stopping when it reaches a match to the `from` attribute, if there is one) that also match the `count` attribute. If no match is found, the sequence will be an empty list.

`multiple`

Numbers nodes as a composite sequence that reflects the hierarchic position of the node, e.g. 1.2.2.5. (The nested format can be specified with the `format` attribute, e.g. A.1.1). The processor looks at all `ancestors` of the current node and the current node itself, stopping when it reaches a match for the `from` attribute, if there is one. For each node in this list that matches the `count` attribute, the processor counts how many preceding matching siblings it has, and adds one for the node itself. If no match is found, the sequence will be an empty list.

`any` (Not supported at this time.)

Numbers all matching nodes, regardless of level, sequentially. The `ancestor`, `self`, and `preceding` axes are all considered. The processor starts at the current node and proceeds in reverse document order, stopping if it reaches a match to any `from` attribute. If no match to the `count` attribute is found, the sequence will be an empty list. This level is not supported at this time.

`from`

Specifies where the numbering should start or start over. The sequence begins with the first descendant of the node that matches the `from` attribute.

`value`

Applies a given format to a number. This is a quick way to format a user-supplied number (as opposed to a node sequence number) in any of the standard `<xsl:number>` formats.

`format`

Defines the format of the generated number:

`format="1"`

`1 2 3 . . .` (This is the only format supported at this time)

`format="01"`

`01 02 03 . . . 09 10 11 . . .`

`format="a"`

`a b c . . .y z aa ab . . .`

`format="A"`

`A B C . . . Y Z AA AB . . .`

`format="i"`

`i ii iii iv v . . .`

`format="I"`

`I II III IV V . . .`

`lang` (Not supported at this time.)

Specifies which language's alphabet should be used in letter-based numbering formats.

`letter-value`

Disambiguates between numbering sequences that use letters. Some languages have more than one numbering system that use letters. If both systems begin with the same token, ambiguity can arise. This attribute can have the value "`alphabetic`" or "`traditional`". The default is "`alphabetic`".

`grouping-separator`

Specifies what character should be used as the group (e.g. thousands) separator. The default is the comma (`,`).

`grouping-size`

Indicates the number of digits that make up a numeric group. The default value is "`3`".

### Type

Instruction, appears within a template.

### Defined

XSLT, section 7.7

### Gecko support

Partial support. See comments above.


<xsl:key> - XSLT: Extensible Stylesheet Language Transformations

<xsl:key>
=========

The `<xsl:key>` element declares a named key which can be used elsewhere in the stylesheet with the `key( )` function.

### Syntax

```xml
<xsl:key name=NAME match=EXPRESSION
 use=EXPRESSION />
```

### Required Attributes

`name`

Specifies a name for this key. Must be a QName.

`match`

Defines the nodes for which this key is applicable.

`use`

Specifies an XPath expression that will be used to determine the value of the key for each of the applicable nodes.

### Optional Attributes

None.

### Type

Top-level, must be the child of `<xsl:stylesheet>` or `<xsl:transform>`.

### Defined

XSLT, section 12.2.

### Gecko support

Supported.


<xsl:call-template> - XSLT: Extensible Stylesheet Language Transformations

<xsl:call-template>
===================

The `<xsl:call-template>` element invokes a named template.

### Syntax

```xml
<xsl:call-template name=NAME>
  <xsl:with-param> [optional]
</xsl:call-template>
```

### Required Attribute

`name`

Specifies the name of the template you wish to invoke.

### Optional Attributes

None.

### Type

Instruction, appears within a template.

### Defined

XSLT, section 6.

### Gecko support

Supported.


<xsl:text> - XSLT: Extensible Stylesheet Language Transformations

<xsl:text>
==========

The `<xsl:text>` element writes literal text to the output tree. It may contain `#PCDATA`, literal text, and entity references.

### Syntax

```xml
<xsl:text disable-output-escaping="yes" | "no">
  TEXT
</xsl:text>
```

### Required Attributes

None.

### Optional Attributes

`disable-output-escaping` (Netscape does not serialize the result of transformation - the "output" below - so this attribute is essentially irrelevant in context. To output html-entities, use numerical values instead, eg ` ` for ` `)

Specifies whether special characters are escaped when written to the output. The available values are "`yes`" or "`no`". If "`yes`" is set, for example, the character `>` is output as `>`, not as `>`.

### Type

Instruction, appears within a template.

### Defined

XSLT, section 7.2

### Gecko support

Supported as noted.


<xsl:value-of> - XSLT: Extensible Stylesheet Language Transformations

<xsl:value-of>
==============

The `<xsl:value-of>` element evaluates an XPath expression, converts it to a string, and writes that string to the result tree.

### Syntax

```xml
<xsl:value-of select=EXPRESSION disable-output-escaping="yes" | "no" />
```

### Required Attributes

`select`

Specifies the XPath expression to be evaluated and written to the output tree.

### Optional Attributes

`disable-output-escaping` (Netscape does not serialize the result of transformation - the "output" below - so this attribute is essentially irrelevant in context. To output html-entities, use numerical values instead, eg `&#160` for `&nbsp`)

Specifies whether special characters are escaped when written to the output. The available values are "`yes`" or "`no`". If "`yes`" is set, for example, the character > is output as `>`, not as "`&gt`".

### Type

Instruction, appears with a template.

### Defined

XSLT, section 7.6.1.

### Gecko support

Supported except as above.


<xsl:attribute> - XSLT: Extensible Stylesheet Language Transformations

<xsl:attribute>
===============

The `<xsl:attribute>` element creates an attribute in the output document, using any values that can be accessed from the stylesheet. The element must be defined before any other output document element inside the output document element for which it establishes attribute values. But it may be after or inside elements that won't be part of the output (like `<xsl:choose>` or `<xsl:apply-templates>` etc.).

### Syntax

```xml
<xsl:attribute name=NAME namespace=URI>
  TEMPLATE
</xsl:attribute>
```

### Required Attributes

`name`

Specifies the name of the attribute to be created in the output document. The name must be a valid QName.

### Optional Attributes

`namespace`

Defines the namespace URI for this attribute in the output document. You cannot set the related namespace prefix with this element.

### Type

Instruction, appears within a template or an `<xsl:attribute-set>` element.

### Defined

XSLT, section 7.1.3.

### Gecko support

Supported.


<xsl:include> - XSLT: Extensible Stylesheet Language Transformations

<xsl:include>
=============

The `<xsl:include>` element merges the contents of one stylesheet with another. Unlike the case of `<xsl:import>`, the contents of an included stylesheet have exactly the same precedence as the contents of the including stylesheet.

### Syntax

```xml
<xsl:include href=URI />
```

### Required Attributes

`href`

Specifies the URI of the stylesheet to include.

### Optional Attributes

None.

### Type

Top-level, may appear in any order as a child of `<xsl:stylesheet>` or `<xsl:transform>`.

### Defined

XSLT, section 2.6.1.

### Gecko support

Supported.


<xsl:strip-space> - XSLT: Extensible Stylesheet Language Transformations

<xsl:strip-space>
=================

The `<xsl:strip-space>` element defines the elements in the source document for which whitespace should be removed.

### Syntax

```xml
<xsl:strip-space elements=LIST-OF-ELEMENT-NAMES />
```

### Required Attributes

`elements`

Specifies a space-separated list of elements in the source whose whitespace-only text nodes should be removed.

### Optional Attributes

None.

### Type

Top-level, must be a child of `<xsl:stylesheet>` or `<xsl:transform>`.

### Defined

XSLT, section 3.4

### Gecko support

Supported.


<xsl:apply-imports> - XSLT: Extensible Stylesheet Language Transformations

<xsl:apply-imports>
===================

The `<xsl:apply-imports>` element is fairly arcane, used mostly in complex stylesheets. Import precedence requires that template rules in main stylesheets have higher precedence than template rules in imported stylesheets. Sometimes, however, it is useful to be able to force the processor to use a template rule from the (lower precedence) imported stylesheet rather than an equivalent rule in the main stylesheet.

### Syntax

```xml
<xsl:apply-imports/>
```

### Required Attributes

None.

### Optional Attributes

None.

### Type

Instruction, appears within a template.

### Defined

XSLT, section 5.6.

### Gecko support

Supported.


<xsl:processing-instruction> - XSLT: Extensible Stylesheet Language Transformations

<xsl:processing-instruction>
============================

The `<xsl:processing-instruction>` element writes a processing instruction to the output document.

### Syntax

`<xsl:processing-instruction name=NAME> TEMPLATE </xsl:processing-instruction>`

### Required Attributes

`name`

Specifies the name of this processing instruction.

### Optional Attributes

None.

### Type

Instruction, appears within a template.

### Defined

XSLT, section 7.3

### Gecko support

Supported.


<xsl:attribute-set> - XSLT: Extensible Stylesheet Language Transformations

<xsl:attribute-set>
===================

The `<xsl:attribute-set>` element creates a named set of attributes, which can then be applied as whole to the output document, in a manner similar to named styles in CSS.

### Syntax

```xml
<xsl:attribute-set name=NAME use-attribute-sets=LIST-OF-NAMES>
  <xsl:attribute>
</xsl:attribute-set>
```

### Required Attributes

`name`

Specifies the name of the attribute set. The name must be a valid QName.

### Optional Attributes

`use-attribute-sets`

Builds an attribute set from other attribute sets. The names of the contributing sets must be separated with whitespace characters and must not directly or indirectly embed themselves.

### Type

Top-level, must be the child of `<xsl:stylesheet>` or `<xsl:transform>`.

### Defined

XSLT, section 7.1.4.

### Gecko support

Supported.


<xsl:preserve-space> - XSLT: Extensible Stylesheet Language Transformations

<xsl:preserve-space>
====================

The `<xsl:preserve-space>` element defines the elements in the source document for which whitespace should be preserved. If there is more than one element, separate the names with a whitespace character. Preserving whitespace is the default setting, so this element only needs to be used to counteract an `<xsl:strip-space>` element.

### Syntax

```xml
<xsl:preserve-space elements=LIST-OF-ELEMENT-NAMES />
```

### Required Attributes

`elements`

Specifies the elements for which whitespace should be preserved.

### Optional Attributes

None.

### Type

Top-level, must be a child of `<xsl:stylesheet>` or `<xsl:transform>`.

### Defined

XSLT, section 3.4

### Gecko support

Supported.


Certificate Transparency - Security on the web

Certificate Transparency
========================

**Certificate Transparency** is an open framework designed to protect against and monitor for certificate mis-issuances. It's defined in RFC 9162. With certificate transparency, newly-issued certificates are 'logged' to publicly-run, often independent *CT logs* — which maintain an append-only, cryptographically-assured record of issued TLS certificates.

In this way, certificate authorities (CAs) can be subject to much greater public scrutiny and oversight. Potentially malicious certificates, such as those that violate the CA/B Forum *Baseline Requirements*, can be detected and revoked much more quickly. Browser vendors and root store maintainers are also empowered to make more informed decisions regarding problematic CAs that they may decide to distrust.

Background
----------

CT logs are built upon the foundation of the *Merkle tree* data structure. Nodes are labelled with the *cryptographic hashes* of their child nodes. Leaf nodes contain hashes of actual pieces of data. The label of the root node therefore depends on all other nodes in the tree.

In the context of certificate transparency, the data hashed by the leaf nodes are the certificates that have been issued by the various different CAs operating today. Certificate inclusion can be verified via an *audit proof* which can be generated and verified efficiently, in logarithmic O(log n) time.

Certificate transparency initially came about in 2013 against a backdrop of CA compromises (DigiNotar breach in 2011), questionable decisions (Trustwave subordinate root incident in 2012) and technical issuance issues (weak, 512-bit certificate issuance by Digicert Sdn Bhd of Malaysia).

Implementation
--------------

When certificates are submitted to a CT log, a *signed certificate timestamp* (SCT) is generated and returned. This serves as a proof that the certificate has been submitted and will be added to the log.

The specification states that compliant servers *must* provide a number of these SCTs to TLS clients when they connect. This can be accomplished via a number of different mechanisms:

* X.509v3 certificate extension which embeds signed certificate timestamps directly into the leaf certificate
* A TLS extension of type `signed_certificate_timestamp` sent during the handshake
* OCSP stapling (that is, the `status_request` TLS extension) and providing a `SignedCertificateTimestampList` with one or more SCTs

With the X.509 certificate extension, the included SCTs are decided by the issuing CA. Since June 2021, most actively used and valid publicly-trusted certificates contain transparency data embedded in this extension. This method should not require web servers to be modified.

With the latter methods, servers will need to be updated to send the required data. The advantage is that the server operator can customize the CT log sources providing the SCTs sent via the TLS extension/stapled OCSP response.

Browser Requirements
--------------------

Google Chrome requires CT log inclusion for all certificates issues with a notBefore date of after 30 April 2018. Users will be prevented from visiting sites using non-compliant TLS certificates. Chrome had previously required CT inclusion for *Extended Validation* (EV) and Symantec-issued certificates.

Apple requires a varying number of SCTs in order for Safari and other servers to trust server certificates.

Firefox does not currently check or require the use of CT logs for sites that users visit.


IFrame credentialless - Security on the web

IFrame credentialless
=====================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

**IFrame credentialless** provides a mechanism for developers to load third-party resources in `<iframe>`s using a new, ephemeral context. It doesn't have access to its regular origin's network, cookies, and storage data. It uses a new context local to the top-level document lifetime. In return, the `Cross-Origin-Embedder-Policy` (COEP) embedding rules can be lifted, so documents with COEP set can embed third-party documents that do not.

The problem
-----------

Various web API features can only be used on sites that opt in to cross-origin isolation — examples include `SharedArrayBuffer` and high-resolution timers. This is because of the risk of such features being exploited in Spectre attacks, where a victim's confidential information can be leaked via a side channel and captured by an attacker.

To opt in to cross-origin isolation, a resource must be served with a `Cross-Origin-Opener-Policy` with a value of `same-origin` (protects your origin from attackers) and `Cross-Origin-Embedder-Policy` with a value of `credentialless` or `require-corp` (protects victims from your origin). The latter prevents a document from loading any credentialled cross-origin resources that don't explicitly grant the document permission using `Cross-Origin-Resource-Policy` or Cross-Origin Resource Sharing.

The key issue limiting the adoption of cross-origin isolation is the fact that `Cross-Origin-Embedder-Policy` is applied recursively — any third-party content loaded into `<iframe>`s in a document with a `Cross-Origin-Embedder-Policy` set must also deploy `Cross-Origin-Embedder-Policy` for the embedding to succeed. This is a problem for developers embedding third-party content in their apps (such as ad-network content) as they generally have no control over it — their only choice up to now has been to wait for the third-party content providers to implement `Cross-Origin-Embedder-Policy`.

This problem can be solved by IFrame credentialless.

The solution — Iframe credentialless
------------------------------------

An `<iframe>` is made credentialless by applying the `credentialless` attribute to it, or setting the equivalent DOM property — `HTMLIFrameElement.credentialless` — to `true`.

```html
<iframe
 src="https://en.wikipedia.org/wiki/Spectre\_(security\_vulnerability)"
 title="Spectre vulnerability Wikipedia page"
 width="960"
 height="600"
 credentialless></iframe>
```

Or:

```html
<iframe width="960" height="600"> </iframe>
```

```js
const iframeElem = document.querySelector("iframe");

iframeElem.credentialless = true;
iframeElem.title = "Spectre vulnerability Wikipedia page";
iframeElem.src =
  "https://en.wikipedia.org/wiki/Spectre\_(security\_vulnerability)";
```

**Note:** The `window.credentialless` property can be queried by a document embedded in an `<iframe>` to test whether it is being run in a credentialless context. A value of `true` means the embedding `<iframe>` is credentialless.

This results in the documents inside the credentialless `<iframe>` being loaded using new, ephemeral contexts — those contexts don't have access to the data associated with their origins; for example cookies and localStorage. The credentialless storage is partitioned out separately with storage keys modified by a nonce ("number used once") value, set once per top-level document. So a cookie set in one credentialless `<iframe>` will be accessible only from other same-origin credentialless `<iframe>`s embedded below the same top-level document.

The nonce is shared for every credentialless iframe that is a descendant of the same top-level document, but it is different for each distinct top-level document the user navigates to, and no longer accessible once the user has navigated away. Credentialless IFrames do not share storage across different pages. Returning to the cookie mentioned above, reloading the document will load the credentialless `<iframe>`s in a different context, so none of the previously-set cookies will be available.

In addition:

* Pop-ups opened by credentialless iframes are opened with `rel="noopener"` set. This prevents OAuth pop-up flows from being used in credentialless iframes.
* Browser autofill or password manager functionality is unavailable in credentialless `<iframes>`.

The result of this is that documents loaded into credentialless `<iframes>` are effectively vanilla or "public" versions, not customized with any user's sensitive information. Since there is no sensitive information available to leak from these documents, they are of no use to would-be attackers, and so the Cross-Origin Embedder Policy requirement is dropped for those IFrames.

Recursive credentialless inside child IFrames
---------------------------------------------

If `credentialless` is set on an `<iframe>` that has child `<iframes>` embedded in the document loaded inside it, those child `<iframe>`s inherit the credentialless setting.

Live demo
---------

Use the https://anonymous-iframe.glitch.me/ demo to see IFrame credentialless in action.

Specifications
--------------

| Specification |
| --- |
| Iframe credentialless  |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Cross-Origin-Opener-Policy`
* `Cross-Origin-Embedder-Policy`
* `Cross-Origin-Resource-Policy`
* Cross-Origin Resource Sharing
* The `<iframe`> `credentialless` attribute
* `HTMLIFrameElement.credentialless`


Same-origin policy - Security on the web

Same-origin policy
==================

The **same-origin policy** is a critical security mechanism that restricts how a document or script loaded by one origin can interact with a resource from another origin.

It helps isolate potentially malicious documents, reducing possible attack vectors. For example, it prevents a malicious website on the Internet from running JS in a browser to read data from a third-party webmail service (which the user is signed into) or a company intranet (which is protected from direct access by the attacker by not having a public IP address) and relaying that data to the attacker.

Definition of an origin
-----------------------

Two URLs have the *same origin* if the protocol, port (if specified), and host are the same for both. You may see this referenced as the "scheme/host/port tuple", or just "tuple". (A "tuple" is a set of items that together comprise a whole — a generic form for double/triple/quadruple/quintuple/etc.)

The following table gives examples of origin comparisons with the URL `http://store.company.com/dir/page.html`:

| URL | Outcome | Reason |
| --- | --- | --- |
| `http://store.company.com/dir2/other.html` | Same origin | Only the path differs |
| `http://store.company.com/dir/inner/another.html` | Same origin | Only the path differs |
| `https://store.company.com/page.html` | Failure | Different protocol |
| `http://store.company.com:81/dir/page.html` | Failure | Different port (`http://` is port 80 by default) |
| `http://news.company.com/dir/page.html` | Failure | Different host |

### Inherited origins

Scripts executed from pages with an `about:blank` or `javascript:` URL inherit the origin of the document containing that URL, since these types of URLs do not contain information about an origin server.

For example, `about:blank` is often used as a URL of new, empty popup windows into which the parent script writes content (e.g. via the `Window.open()` mechanism). If this popup also contains JavaScript, that script would inherit the same origin as the script that created it.

`data:` URLs get a new, empty, security context.

### File origins

 Modern browsers usually treat the origin of files loaded using the `file:///` schema as *opaque origins*.
 What this means is that if a file includes other files from the same folder (say), they are not assumed to come from the same origin, and may trigger CORS errors.

Note that the URL specification states that the origin of files is implementation-dependent, and some browsers may treat files in the same directory or subdirectory as same-origin even though this has security implications.

Changing origin
---------------

**Warning:** The approach described here (using the `document.domain` setter) is deprecated because it undermines the security protections provided by the same origin policy, and complicates the origin model in browsers, leading to interoperability problems and security bugs.

A page may change its own origin, with some limitations. A script can set the value of `document.domain` to its current domain or a superdomain of its current domain. If set to a superdomain of the current domain, the shorter superdomain is used for same-origin checks.

For example, assume a script from the document at `http://store.company.com/dir/other.html` executes the following:

```js
document.domain = "company.com";
```

Afterward, the page can pass the same-origin check with `http://company.com/dir/page.html` (assuming `http://company.com/dir/page.html` sets its `document.domain` to "`company.com`" to indicate that it wishes to allow that - see `document.domain` for more). However, `company.com` could **not** set `document.domain` to `othercompany.com`, since that is not a superdomain of `company.com`.

The port number is checked separately by the browser. Any call to `document.domain`, including `document.domain = document.domain`, causes the port number to be overwritten with `null`. Therefore, one **cannot** make `company.com:8080` talk to `company.com` by only setting `document.domain = "company.com"` in the first. It has to be set in both so their port numbers are both `null`.

The mechanism has some limitations. For example, it will throw a "`SecurityError`" `DOMException` if the `document-domain` `Permissions-Policy` is enabled or the document is in a sandboxed `<iframe>`, and changing the origin in this way does not affect the origin checks used by many Web APIs (e.g. `localStorage`, `indexedDB`, `BroadcastChannel`, `SharedWorker`). A more exhaustive list of failure cases can be found in Document.domain > Failures.

**Note:** When using `document.domain` to allow a subdomain to access its parent, you need to set `document.domain` to the *same value* in both the parent domain and the subdomain. This is necessary even if doing so is setting the parent domain back to its original value. Failure to do this may result in permission errors.

Cross-origin network access
---------------------------

The same-origin policy controls interactions between two different origins, such as when you use `fetch()` or an `<img>` element. These interactions are typically placed into three categories:

* Cross-origin *writes* are typically allowed. Examples are links, redirects, and form submissions. Some HTTP requests require preflight.
* Cross-origin *embedding* is typically allowed. (Examples are listed below.)
* Cross-origin *reads* are typically disallowed, but read access is often leaked by embedding. For example, you can read the dimensions of an embedded image, the actions of an embedded script, or the availability of an embedded resource.

Here are some examples of resources which may be embedded cross-origin:

* JavaScript with `<script src="…"></script>`. Error details for syntax errors are only available for same-origin scripts.
* CSS applied with `<link rel="stylesheet" href="…">`. Due to the relaxed syntax rules of CSS, cross-origin CSS requires a correct `Content-Type` header. Browsers block stylesheet loads if it is a cross-origin load where the MIME type is incorrect and the resource does not start with a valid CSS construct.
* Images displayed by `<img>`.
* Media played by `<video>` and `<audio>`.
* External resources embedded with `<object>` and `<embed>`.
* Fonts applied with `@font-face`. Some browsers allow cross-origin fonts, others require same-origin.
* Anything embedded by `<iframe>`. Sites can use the `X-Frame-Options` header to prevent cross-origin framing.
### How to allow cross-origin access

Use CORS to allow cross-origin access. CORS is a part of HTTP that lets servers specify any other hosts from which a browser should permit loading of content.

### How to block cross-origin access

* To prevent cross-origin writes, check an unguessable token in the request — known as a Cross-Site Request Forgery (CSRF) token. You must prevent cross-origin reads of pages that require this token.
* To prevent cross-origin reads of a resource, ensure that it is not embeddable. It is often necessary to prevent embedding because embedding a resource always leaks some information about it.
* To prevent cross-origin embeds, ensure that your resource cannot be interpreted as one of the embeddable formats listed above. Browsers may not respect the `Content-Type` header. For example, if you point a `<script>` tag at an HTML document, the browser will try to parse the HTML as JavaScript. When your resource is not an entry point to your site, you can also use a CSRF token to prevent embedding.
Cross-origin script API access
------------------------------

JavaScript APIs like `iframe.contentWindow`, `window.parent`, `window.open`, and `window.opener` allow documents to directly reference each other. When two documents do not have the same origin, these references provide very limited access to `Window` and `Location` objects, as described in the next two sections.

To communicate between documents from different origins, use `window.postMessage`.

Specification: HTML Living Standard § Cross-origin objects.

### Window

The following cross-origin access to these `Window` properties is allowed:

| Methods |
| --- |
| `window.blur` |
| `window.close` |
| `window.focus` |
| `window.postMessage` |

| Attributes |  |
| --- | --- |
| `window.closed` | Read only. |
| `window.frames` | Read only. |
| `window.length` | Read only. |
| `window.location` | Read/Write. |
| `window.opener` | Read only. |
| `window.parent` | Read only. |
| `window.self` | Read only. |
| `window.top` | Read only. |
| `window.window` | Read only. |

Some browsers allow access to more properties than the above.

### Location

The following cross-origin access to `Location` properties is allowed:

| Methods |
| --- |
| `location.replace` |

| Attributes |  |
| --- | --- |
| `location.href` | Write-only. |

Some browsers allow access to more properties than the above.

Cross-origin data storage access
--------------------------------

Access to data stored in the browser such as Web Storage and IndexedDB are separated by origin. Each origin gets its own separate storage, and JavaScript in one origin cannot read from or write to the storage belonging to another origin.

Cookies use a separate definition of origins. A page can set a cookie for its own domain or any parent domain, as long as the parent domain is not a public suffix. Firefox and Chrome use the Public Suffix List to determine if a domain is a public suffix. When you set a cookie, you can limit its availability using the `Domain`, `Path`, `Secure`, and `HttpOnly` flags. When you read a cookie, you cannot see from where it was set. Even if you use only secure https connections, any cookie you see may have been set using an insecure connection.

See also
--------

* Same Origin Policy at W3C
* Same-origin policy at web.dev
* `Cross-Origin-Resource-Policy`
* `Cross-Origin-Embedder-Policy`


Insecure passwords - Security on the web

Insecure passwords
==================

Serving login forms over HTTP is especially dangerous because of the wide variety of attacks that can be used against them to extract a user's password. Network eavesdroppers could steal a user's password by sniffing the network, or by modifying the served page in transit.

The HTTPS protocol is designed to protect user data from eavesdropping (confidentiality) and from modification (integrity) on the network. Websites that handle user data should use HTTPS to protect their users from attackers. If a website uses HTTP instead of HTTPS, it is trivial to steal user information (such as their login credentials). This was famously demonstrated by Firesheep.

To fix this issue, install and configure a TLS certificate on your server. There are various vendors offering free and paid certificates. If you are using a cloud platform, it may have its own ways of enabling HTTPS.

Note on password reuse
----------------------

Sometimes websites require username and passwords but don't actually store data that is very sensitive. For example, a news site may save which news articles a user wants to go back to and read, but not save any other data about a user. Web developers of the news site may be less motivated to secure their site and their user credentials.

Unfortunately, password reuse is a big problem. Users use the same password across multiple sites (news websites, social networks, email providers, banks). Hence, even if access to the username and password to your site doesn't seem like a huge risk to you, it is a great risk to users who have used the same username and password to log in to their bank accounts. Attackers are getting smarter; they steal username/password pairs from one site and then try reusing them on more lucrative sites.

See also
--------

* No More Passwords over HTTP, Please! — detailed blog post with more information, and FAQ.


Referer header: Privacy and security concerns - Security on the web

Referer header: Privacy and security concerns
=============================================

There are privacy and security risks associated with the Referer HTTP header. This article describes them, and offers advice on mitigating those risks.

The referrer problem
--------------------

The `Referer` (sic) header contains the address of a request (for example, the address of the previous web page from which a link to the currently requested page was followed, or the address of a page loading an image or other resource). This has many fairly innocent uses, including analytics, logging, or optimized caching. However, there are more problematic uses such as tracking or stealing information, or even just side effects such as inadvertently leaking sensitive information.

For example, consider a "reset password" page with a social media link in a footer. If the link was followed, depending on how information was shared the social media site may receive the reset password URL and may still be able to use the shared information, potentially compromising a user's security.

By the same logic, an image from a third party site embedded in your page could result in sensitive information being leaked to the third party. Even if security is not compromised, the information may not be something the user wants shared.

How can we fix this?
--------------------

Much of this risk can be mitigated by sensible design of applications. A sensible application would remove such risks by making single-use password reset URLs, or combining them with a unique user token. The risk can also be reduced by transmitting sensitive data in more secure ways.

You should use `POST` rather than `GET` wherever possible, to avoid passing sensitive data to other locations via URLs.

You should always use HTTPS for your sites. This has many security advantages, including the fact that HTTPS sites will never transmit referrer information to non-HTTPS sites. This advice is less relevant now that most of the web is using HTTPS, but it is still a worthy consideration.

In addition, you should consider removing any third party content (e.g. social networking widgets embedded in `<iframe>`) from secure areas of your website, like password reset pages, payment forms, login areas, etc.

You can also mitigate such risks using:

* The `Referrer-Policy` header on your server to control what information is sent through the `Referer` header. For example, a directive of `no-referrer` would omit the Referer header entirely.
* The `referrerpolicy` attribute on HTML elements that are in danger of leaking such information (such as `<img>` and `<a>`). This can for example be set to `no-referrer` to stop the `Referer` header being sent altogether.
* The `rel` attribute set to `noreferrer` on HTML elements that are in danger of leaking such information (such as `<img>` and `<a>`).
* A `<meta>` element with a name of `referrer` and the content set to `no-referrer` to disable the Referer header for the whole document. See Referrer-Policy Integration with HTML.
* The Exit page technique.

Security-conscious server-side frameworks tend to have built in mitigations for such problems, for example:

* Security in Django (especially see Cross site request forgery (CSRF) protection).
* helmetjs referrer-policy — middleware for setting Referrer-Policy in Node.js/Express apps (see also helmetjs for more security provisions).
Policy and requirements
-----------------------

It would make sense to write a set of security and privacy requirements for your project team(s) that specify usage of such features to mitigate the associated risks. You should enlist the help of a web security expert to write these requirements, and consider both user needs and welfare, as well as other issues like policy and regulation enforced by legislation such as the EU General Data Protection Regulation (GDPR).

See also
--------

* Mozilla security team guidelines on Referrer-Policy


Weak signature algorithms - Security on the web

Weak signature algorithms
=========================

The strength of the hash algorithm used in signing a digital certificate is a critical element of the security of the certificate. This article provides some information about signature algorithms known to be weak, so you can avoid them when appropriate.

Weaknesses in hash algorithms can lead to situations in which attackers can create or obtain fraudulent certificates. As new attacks are found and improvements in available technology make attacks more feasible, the use of older algorithms is discouraged and support for them is eventually removed.

SHA-1
-----

SHA-1 certificates will no longer be treated as secure by major browser manufacturers beginning in 2017. Certificates employing more secure hash algorithms (such as SHA-256 or SHA-512) should be used instead.

MD5
---

Support for MD5 based signatures was removed in early 2012.

See also
--------

* Mozilla Security Blog post on the deprecation of SHA-1


Firefox security guidelines - Security on the web

Firefox security guidelines
===========================

Purpose
-------

This document outlines a set of security guidelines that will generally apply to all client applications, such as Firefox and Thunderbird.

Secure Coding Principles
------------------------

Ensure that the application follows the OWASP Secure Coding Principles:

1. Minimize attack surface area
2. Establish secure defaults
3. Principle of Least privilege
4. Principle of Defense in depth
5. Fail securely
6. Don't trust services
7. Keep security simple
8. Fix security issues correctly
Input Validation
----------------

1. Does the application accept user input?
    1. Verify a sampling of input locations to ensure that reasonable maximums are in place when accepting user data
    2. Verify a sampling of input locations to ensure that the application allows only a defined set of acceptable characters
    3. Ensure that allowlisting is used instead of denylisting
2. Does the application accept user input that is displayed in any way?
    1. Verify a sampling of input and output locations to ensure user supplied content is properly encoded in the response
Chrome JS - Dangerous Functions
-------------------------------

Are any of the following functions used?

If so ensure they are safe and that no better alternatives are available.

| Name | Risk Level | Problem | Solution |
| --- | --- | --- | --- |
| eval | Very High | Invokes JavaScript parser - dangerous if used with untrusted input | Avoid eval if at all possible. |
| setTimeout(string, time) | Very High | Acts like eval | Use setTimeout(function, time, param1, param2, …) |

C++ - Dangerous Functions
-------------------------

Are any of the following functions used?

If so ensure they are safe and that no better alternatives are available.

| Name | Risk Level | Problem | Solution |
| --- | --- | --- | --- |
| gets | Very High | No bounds checking | Do not use gets. Use fgets instead. |
| strcpy | Very High | No bounds checking | strcpy is safe only if the source string is a constant and the destination is large enough to hold it. Otherwise, use strncpy. |
| sprintf | Very High | No bounds checking, format string attacks | sprintf is very hard to use safely. Use snprintf instead. |
| scanf, sscanf | High | Possibly no bounds checking, format string attacks | Make sure all %-directives match the corresponding argument types. Do not use '%s' directives with no bounds checking. Use '%xs' where x is the buffer size of the corresponding argument. Do not use untrusted, un-validated data in the format string. |
| strcat | High | No bounds checking | If input sizes are not well-known and fixed, use strncat instead. |
| printf, fprintf, snprintf, vfprintf, vsprintf, syslog | High | format string attacks | Do not use untrusted, un-validated data in the format string. If the format string can be influenced by Web content or user input, validate it for the proper number and type of %-directives before calling these functions. Make sure destination size arguments are correct. |
| strncpy, fgets, strncat | Low | May not null-terminate | Always explicitly null-terminate the destination buffer. Make sure the size argument is correct. Be sure to leave room in the destination buffer to add the null character! |

URLs
----

1. Does the application make use of untrusted data to construct URLs?
    * Ensure any such data is adequately sanitized and encoded prior to use.
    * Ensure any data obtained from these URLs is checked before use or storage.
2. Does the application follow redirects?
    * Ensure security checks are performed on redirects as well as the original request URI.
Security Controls
-----------------

1. Does the application implement suitable permission checks?
    * Ensure the correct APIs are used where available (e.g. shouldLoad, etc.)
    * Ensure the application fails securely.
Remote System Access
--------------------

1. Does the application access any remote systems?

* Ensure that TLS is used unless there's a *very* good reason not to.
* Ensure that no user information is transmitted without the user's consent.
Information Storage
-------------------

1. File storage
    1. Ensure the application checks that any files created are under allowed paths
    2. Are filenames generated from untrusted data?
        * Ensure the data is suitably encoded
    3. Check files are of an acceptable type
    4. Check files cannot exceed reasonable size limits
2. Database storage
    1. Ensure any untrusted information sent to the database is adequately sanitized
    2. Where possible, make use of type safe parameterization to prevent injection attacks
3. Sensitive information
    1. Ensure any security sensitive or personal information is adequately protected (see Encryption section)
    2. Particular care must be taken around credentials (passwords, etc.) - If you're working with information of this type and you're unsure of what to do, it's always worth asking
4. Logging
    1. Don't forget the above rules apply to logs as well as your usual application data
Encryption
----------

1. Does the application use any form of encryption?
2. Are the algorithms used recognized standards?
Denial of Service
-----------------

1. Ensure the application protects against exhaustion of:
    1. System memory
    2. Storage
Security Warnings
-----------------

1. Does the application present the user with any security warnings?
2. Are they clearly understandable and appropriate?
3. Can untrusted data change the meaning of messages to the user?
    * Can user input change the meaning of messages?
    * Can user input force system messages off the visible screen?
    * Can user input include special characters that can change the meaning of messages (e.g. Unicode right-to-left override U+202E)
4. Can an attacker use the timing of dialogs to fool the user into clicking on something they didn't intend to?
Information Disclosure
----------------------

1. Does the application disclose information that could compromise the user?
2. Does the application disclose any information that it does not need to?
3. Does the application disclose anything that may surprise or upset the user?
Front End
---------

1. Are safe mechanisms used to create XUL and HTML UI elements?
    * e.g. use createTextNode instead of innerHTML or similar
2. Does the application create its own docshells (tabs, iframes)?
    * Ensure you are explicit about the type of these, e.g. iframe.setAttribute("type", "content")
References
----------

* Web Security Verification
* Mozilla Security Review and Best Practices
* Security tips for Mozilla and extension developers
* OWASP Secure Coding Practices - Quick Reference Guide


Securing your site - Security on the web

Securing your site
==================

There are a number of things you can do to help secure your site. This article offers an assortment of suggestions, as well as links to other articles providing more useful information.

**Note:** This article is a work in progress, and is neither complete nor does following its suggestions guarantee your site will be fully secure.

User information security
-------------------------

How to turn off form autocompletion

Form fields support autocompletion in Gecko; that is, their values can be remembered and automatically brought back the next time the user visits your site. For certain types of data, you may wish to disable this feature.

Privacy and the :visited selector

This article discusses changes made to the `getComputedStyle()` method that eliminates the ability for malicious sites to figure out the user's browsing history.

Hash passwords using a secure algorithm (OWASP)

Storing passwords in plain text can lead to attackers knowing and leaking the exact password of your site's users, potentially putting the users at risk. The same issues can arise if you use an old or insecure algorithm for hashing (such as md5). You should use a password-specific hashing algorithm (such as Argon2, PBKDF2, scrypt or bcrypt) instead of message digest algorithms (such as md5 and sha). This article showcases best practices to use when storing passwords.

Content security
----------------

Properly configuring server MIME types

There are several ways incorrect MIME types can cause potential security problems with your site. This article explains some of those and shows how to configure your server to serve files with the correct MIME types.

HTTP Strict Transport Security

The `Strict-Transport-Security:` HTTP header lets a website specify that it may only be accessed using HTTPS.

HTTP access control

The Cross-Origin Resource Sharing standard provides a way to specify what content may be loaded from other domains. You can use this to prevent your site from being used improperly; in addition, you can use it to establish resources that other sites are expressly permitted to use.

Content Security Policy

An added layer of security that helps to detect and mitigate certain types of attacks, including Cross Site Scripting (XSS) and data injection attacks. These attacks are used for everything from data theft to site defacement or distribution of malware. Code is executed by the victims and lets the attackers bypass access controls and impersonate users.

The X-Frame-Options response header

The `X-Frame-Options:` HTTP response header can be used to indicate whether a browser should be allowed to render a page in a `<frame>`. Sites can use this to avoid clickjacking attacks, by ensuring that their content is not embedded into other sites.

Access control by configuring a website

It is the best way to secure your site. You can ignore specific IPs, restrict access to certain areas of website, protect different files, protect against image hotlinking, and a lot more. For example, .htaccess file is used for websites hosted on Apache HTTP Server.

See also
--------

* Open Web Application Security Project (OWASP)
* Mozilla Web Security Cheat Sheet
* Cross-site scripting on OWASP


Types of attacks - Security on the web

Types of attacks
================

This article describes various types of security attacks and techniques to mitigate them.

Click-jacking
-------------

Clickjacking is the practice of tricking a user into clicking on a link, button, etc. that is other than what the user thinks it is. This can be used, for example, to steal login credentials or to get the user's unwitting permission to install a piece of malware. (Click-jacking is sometimes called "user interface redressing", though this is a misuse of the term "redress".)

Cross-site scripting (XSS)
--------------------------

Cross-site scripting (XSS) is a security exploit which allows an attacker to inject into a website malicious client-side code. This code is executed by the victims and lets the attackers bypass access controls and impersonate users. According to the Open Web Application Security Project, XSS was the seventh most common Web app vulnerability in 2017.

These attacks succeed if the Web app does not employ enough validation or encoding. The user's browser cannot detect the malicious script is untrustworthy, and so gives it access to any cookies, session tokens, or other sensitive site-specific information, or lets the malicious script rewrite the HTML content.

Cross-site scripting attacks usually occur when 1) data enters a Web app through an untrusted source (most often a Web request) or 2) dynamic content is sent to a Web user without being validated for malicious content.

The malicious content often includes JavaScript, but sometimes HTML, Flash, or any other code the browser can execute. The variety of attacks based on XSS is almost limitless, but they commonly include transmitting private data like cookies or other session information to the attacker, redirecting the victim to a webpage controlled by the attacker, or performing other malicious operations on the user's machine under the guise of the vulnerable site.

XSS attacks can be put into three categories: stored (also called persistent), reflected (also called non-persistent), or DOM-based.

Stored XSS Attacks

The injected script is stored permanently on the target servers. The victim then retrieves this malicious script from the server when the browser sends a request for data.

Reflected XSS Attacks

When a user is tricked into clicking a malicious link, submitting a specially crafted form, or browsing to a malicious site, the injected code travels to the vulnerable website. The Web server reflects the injected script back to the user's browser, such as in an error message, search result, or any other response that includes data sent to the server as part of the request. The browser executes the code because it assumes the response is from a "trusted" server which the user has already interacted with.

DOM-based XSS Attacks

The payload is executed as a result of modifying the DOM environment (in the victim's browser) used by the original client-side script. That is, the page itself does not change, but the client side code contained in the page runs in an unexpected manner because of the malicious modifications to the DOM environment.

Cross-site request forgery (CSRF)
---------------------------------

CSRF (sometimes also called XSRF) is a related class of attack. The attacker causes the user's browser to perform a request to the website's backend without the user's consent or knowledge. An attacker can use an XSS payload to launch a CSRF attack.

Wikipedia mentions a good example for CSRF. In this situation, someone includes an image that isn't really an image (for example in an unfiltered chat or forum), instead it really is a request to your bank's server to withdraw money:

```html
<img
 src="https://bank.example.com/withdraw?account=bob&amount=1000000&for=mallory" />
```

Now, if you are logged into your bank account and your cookies are still valid (and there is no other validation), you will transfer money as soon as you load the HTML that contains this image. For endpoints that require a POST request, it's possible to programmatically trigger a <form> submit (perhaps in an invisible <iframe>) when the page is loaded:

```html
<form action="https://bank.example.com/withdraw" method="POST">
  <input type="hidden" name="account" value="bob" />
  <input type="hidden" name="amount" value="1000000" />
  <input type="hidden" name="for" value="mallory" />
</form>
<script>
 window.addEventListener("DOMContentLoaded", () => {
 document.querySelector("form").submit();
 });
</script>
```

There are a few techniques that should be used to prevent this from happening:

* GET endpoints should be idempotent—actions that enact a change and do not retrieve data should require sending a POST (or other HTTP method) request. POST endpoints should not interchangeably accept GET requests with parameters in the query string.
* A session-unique CSRF token should be provided by the server to the browser. This token can then be included whenever a form is posted by the browser (in a hidden input field in the `<form>` element). For all non-GET requests that have the potential to perform an action, the server compares the sent token against its stored value for the session. If there is a mismatch, the request is aborted.
* This method of protection relies on an attacker being unable to predict the user's assigned CSRF token. The token should be regenerated on sign-in.
* Cookies that are used for sensitive actions (such as session cookies) should have a short lifetime with the SameSite attribute set to Strict or Lax. (See SameSite cookies above). In supporting browsers, this will have the effect of ensuring that the session cookie is not sent along with cross-site requests and so the request is effectively unauthenticated to the application server.
* Both CSRF tokens and SameSite cookies should be deployed. This ensures all browsers are protected and provides protection where SameSite cookies cannot help (such as attacks originating from a separate subdomain).

For more prevention tips, see the OWASP CSRF prevention cheat sheet.

Man-in-the-middle (MitM)
------------------------

A third party intercepts traffic between a web server and a client (browser), and impersonates the web server in order to capture data (such as login credentials or credit card information). The traffic is passed through, possibly with alterations. Open Wi-Fi networks are typical means of executing this attack.

Session hijacking
-----------------

Session hijacking consists of gaining access to and misusing a user's authenticated session. This may happen by stealing a cookie for an existing session, or by fooling the user (or their browser) into setting a cookie with a predetermined session ID.

Exfiltration avenues can be limited by deploying a strict Content-Security-Policy.

### Session fixation

A third party is able to determine a user's session identifier (i.e., by reading it or setting it), and therefore interact with the server as that user. Stealing cookies is one way to do this.

Recall that a subdomain such as application.example.com can set a cookie to be sent with requests to example.com or other subdomains by setting the `Domain` attribute:

```http
Set-Cookie: CSRF=e8b667; Secure; Domain=example.com
```

 If a vulnerable application is available on a subdomain, this mechanism can be abused in a session fixation attack. When the user visits a page on the parent domain (or another subdomain), the application may trust the existing value sent in the user's cookie. This could allow an attacker to bypass CSRF protection or hijack a session after the user logs in.
 Alternatively, if the parent domain does not use HTTP Strict-Transport-Security with `includeSubdomains` set, a user subject to an active MitM (perhaps connected to an open Wi-Fi network) could be served a response with a Set-Cookie header from a non-existent subdomain. The end result would be much the same, with the browser storing the illegitimate cookie and sending it to all other pages under example.com.

Session fixation should primarily be mitigated by regenerating session cookie values when the user authenticates (even if a cookie already exists) and by tying any CSRF token to the user.

### Session side-jacking

### Browser hijacking malware


Subresource Integrity - Security on the web

Subresource Integrity
=====================

**Subresource Integrity** (SRI) is a security feature that enables browsers to verify that resources they fetch (for example, from a CDN) are delivered without unexpected manipulation. It works by allowing you to provide a cryptographic hash that a fetched resource must match.

**Note:** For subresource-integrity verification of a resource served from an origin other than the document in which it's embedded, browsers additionally check the resource using Cross-Origin Resource Sharing (CORS), to ensure the origin serving the resource allows it to be shared with the requesting origin.

How Subresource Integrity helps
-------------------------------

Using Content Delivery Networks (CDNs) to host files such as scripts and stylesheets that are shared among multiple sites can improve site performance and conserve bandwidth. However, using CDNs also comes with a risk, in that if an attacker gains control of a CDN, the attacker can inject arbitrary malicious content into files on the CDN (or replace the files completely) and thus can also potentially attack all sites that fetch files from that CDN.

Subresource Integrity enables you to mitigate some risks of attacks such as this, by ensuring that the files your web application or web document fetches (from a CDN or anywhere) have been delivered without a third-party having injected any additional content into those files — and without any other changes of any kind at all having been made to those files.

Using Subresource Integrity
---------------------------

You use the Subresource Integrity feature by specifying a base64-encoded cryptographic hash of a resource (file) you're telling the browser to fetch, in the value of the `integrity` attribute of a `<script>` element or a `<link>` element with `rel="stylesheet"`, `rel="preload"`, or `rel="modulepreload"`.

An `integrity` value begins with at least one string, with each string including a prefix indicating a particular hash algorithm (currently the allowed prefixes are `sha256`, `sha384`, and `sha512`), followed by a dash, and ending with the actual base64-encoded hash.

**Note:** An **integrity** value may contain multiple hashes separated by whitespace. A resource will be loaded if it matches one of those hashes.

Example `integrity` string with base64-encoded sha384 hash:
```

sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC
```

So `oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC` is the "hash" part, and the prefix `sha384` indicates that it's a sha384 hash.

**Note:** An `integrity` value's "hash" part is, strictly speaking, a ***cryptographic* *digest*** formed by applying a particular hash function to some input (for example, a script or stylesheet file). But it's common to use the shorthand "hash" to mean *cryptographic* *digest*, so that's what's used in this article.

### Tools for generating SRI hashes

#### SRI Hash Generator

The SRI Hash Generator is an online tool you can use to generate SRI hashes.

#### Using OpenSSL

You can generate SRI hashes from the command-line using **OpenSSL** with a command invocation such as:

```bash
cat FILENAME.js | openssl dgst -sha384 -binary | openssl base64 -A
```

In a Windows environment, you can create a tool for generating SRI hashes with the following code:

```batch
@echo off
set bits=384
openssl dgst -sha%bits% -binary %1% | openssl base64 -A > tmp
set /p a= < tmp
del tmp
echo sha%bits%-%a%
pause
```

To use that code:

1. Save that code in a file named `sri-hash.bat` in the Windows SendTo folder in your environment (for example, `C:\Users\USER\AppData\Roaming\Microsoft\Windows\SendTo`).
2. Right-click a file in the File Explorer, select **Send to…**, and then select `sri-hash`. You will see the integrity value in a command box.
3. Select the integrity value and right-click to copy it to the Clipboard.
4. Press any key to dismiss the command box.

**Note:** If OpenSSL is not installed on your system, visit the OpenSSL project website for information about downloading and installing it. The OpenSSL project does not itself host binary distributions of OpenSSL, but does maintain an informal list of third-party distributions: https://wiki.openssl.org/index.php/Binaries.

#### Using shasum

You can generate SRI hashes using **shasum** with a command invocation such as:

```bash
shasum -b -a 384 FILENAME.js | awk '{ print $1 }' | xxd -r -p | base64
```

* The pipe-through `xxd` step takes the hexadecimal output from `shasum` and converts it to binary.
* The pipe-through `awk` step is necessary because `shasum` will pass the hashed filename in its output to `xxd`. That can have disastrous consequences if the filename happens to have valid hex characters in it — because `xxd` will also decode that and pass it to `base64`.
### Cross-Origin Resource Sharing and Subresource Integrity

For subresource-integrity verification of a resource served from an origin other than the document in which it's embedded, browsers additionally check the resource using Cross-Origin Resource Sharing (CORS), to ensure the origin serving the resource allows it to be shared with the requesting origin. Therefore, the resource must be served with an `Access-Control-Allow-Origin` header that allows the resource to be shared with the requesting origin; for example:

```http
Access-Control-Allow-Origin: \*
```

Examples
--------

In the following examples, assume that `oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC` is already known to be the expected SHA-384 hash (digest) of a particular script `example-framework.js`, and there's a copy of the script hosted at `https://example.com/example-framework.js`.

### Subresource Integrity with the <script> element

You can use the following `<script>` element to tell a browser that before executing the `https://example.com/example-framework.js` script, the browser must first compare the script to the expected hash, and verify that there's a match.

```html
<script
 src="https://example.com/example-framework.js"
 integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC"
 crossorigin="anonymous"></script>
```

**Note:** For more details on the purpose of the `crossorigin` attribute, see CORS settings attributes.

How browsers handle Subresource Integrity
-----------------------------------------

Browsers handle SRI by doing the following:

1. When a browser encounters a `<script>` or `<link>` element with an `integrity` attribute, before executing the script or before applying any stylesheet specified by the `<link>` element, the browser must first compare the script or stylesheet to the expected hash given in the `integrity` value.
 For subresource-integrity verification of a resource served from an origin other than the document in which it's embedded, browsers additionally check the resource using Cross-Origin Resource Sharing (CORS), to ensure the origin serving the resource allows it to be shared with the requesting origin.
2. If the script or stylesheet doesn't match its associated `integrity` value, the browser must refuse to execute the script or apply the stylesheet, and must instead return a network error indicating that fetching of that script or stylesheet failed.
Specifications
--------------

| Specification |
| --- |
| HTML Standard # attr-link-integrity |
| Subresource Integrity # the-integrity-attribute |
| HTML Standard # attr-script-integrity |

Browser compatibility
---------------------

### html.elements.link.integrity

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

### html.elements.script.integrity

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Content Security Policy
* The `Content-Security-Policy` HTTP header.
* A CDN that can not XSS you: Using Subresource Integrity
* Subresource Integrity test from W3C
* SRI Hash Generator