<?xml version="1.0" encoding="US-ASCII"?>
<!DOCTYPE rfc SYSTEM "rfc2629.dtd" [
<!ENTITY RFC2119 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.2119.xml">
<!ENTITY RFC4648 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.4648.xml">
<!ENTITY RFC1951 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.1951.xml">
<!ENTITY RFC4086 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.4086.xml">
<!ENTITY RFC2104 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.2104.xml">
<!ENTITY RFC5652 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.5652.xml">
<!ENTITY RFC5246 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.5246.xml">
<!ENTITY RFC3740 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.3740.xml">
<!ENTITY RFC4301 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.4301.xml">
<!ENTITY RFC6265 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.6265.xml">
<!ENTITY RFC6194 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.6194.xml">
<!ENTITY RFC5056 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.5056.xml">
<!ENTITY RFC2616 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.2616.xml">
]>
<?xml-stylesheet type='text/xsl' href='rfc2629.xslt' ?>
<?rfc strict="yes" ?>
<?rfc toc="yes"?>
<?rfc tocdepth="4"?>
<?rfc symrefs="yes"?>
<?rfc sortrefs="yes" ?>
<?rfc compact="yes" ?>
<?rfc subcompact="no" ?>
<rfc category="info" docName="draft-secure-cookie-session-protocol-09"
     ipr="trust200902">
  <front>
    <title abbrev="">SCS: Secure Cookie Sessions for HTTP</title>

    <author fullname="Stefano Barbato" initials="S." surname="Barbato">
      <organization>KoanLogic</organization>

      <address>
        <postal>
          <street>Via Marmolada, 4</street>

          <city>Vitorchiano (VT)</city>

          <region></region>

          <code>01030</code>

          <country>Italy</country>
        </postal>

        <email>tat@koanlogic.com</email>
      </address>
    </author>

    <author fullname="Steven Dorigotti" initials="S." surname="Dorigotti">
      <organization>KoanLogic</organization>

      <address>
        <postal>
          <street>Via Maso della Pieve 25/C</street>

          <city>Bolzano</city>

          <region></region>

          <code>39100</code>

          <country>Italy</country>
        </postal>

        <email>stewy@koanlogic.com</email>
      </address>
    </author>

    <author fullname="Thomas Fossati" initials="T." role="editor"
            surname="Fossati">
      <organization>KoanLogic</organization>

      <address>
        <postal>
          <street>Via di Sabbiuno 11/5</street>

          <city>Bologna</city>

          <region></region>

          <code>40136</code>

          <country>Italy</country>
        </postal>

        <phone>+39 051 644 82 68</phone>

        <email>tho@koanlogic.com</email>
      </address>
    </author>

    <date year="2012" />

    <!-- Meta-data Declarations -->

    <area>General</area>

    <workgroup>Internet Engineering Task Force</workgroup>

    <keyword>HTTP Secure Cookies</keyword>

    <abstract>
      <t>This memo defines a generic URI and HTTP header friendly envelope for
      carrying symmetrically encrypted, authenticated, and origin-timestamped
      tokens.  It also describes one possible usage of such tokens via a simple
      protocol based on HTTP cookies.</t>

      <t>SCS use cases cover a wide spectrum of applications, ranging from
      distribution of authorized content via HTTP (e.g. with out-of-band signed
      URIs), to securing browser sessions with diskless embedded devices (e.g.
      SOHO routers), or web servers with high availability or load
      balancing requirements that may want to delegate the handling of the
      application state to clients instead of using shared storage or
      forced peering.</t>
    </abstract>
  </front>

  <middle>
    <section anchor="sec_intro" title="Introduction">
      <t>This memo defines a generic URI and HTTP header friendly envelope for
      carrying symmetrically encrypted, authenticated, and origin-timestamped
      tokens.</t>

      <t>It is generic in that it does not force any specific format upon the
      authenticated information - which makes SCS tokens flexible, easy, and
      secure to use in many different scenarios.</t>

      <t>It is URI and HTTP header friendly, as it has been explicitly designed
      to be compatible with both the ABNF "token" syntax <xref target="RFC2616"
      /> (the one used for e.g. Set-Cookie and Cookie headers), and the path or
      query syntax of HTTP URIs.</t>

      <t>This memo also describes one possible usage of such tokens via a
      simple protocol based on HTTP cookies that allows to establish "client
      mode" sessions.  This is not their sole possible usage, and while no
      other operational patterns are outlined here, it is expected that SCS
      tokens may be easily employed as a building block for other kind of HTTP
      based applications that need to carry in-band secured information.</t>

      <t>When SCS tokens are used to implement client mode cookie sessions, the
      SCS implementer must fully understand the security implications entailed
      by the act of delegating the whole application state to the client
      (browser).  In this regard, some hopefully useful security considerations
      have been collected in <xref target="sec_impact_of_scs_cookie_model" />.
      Please note that they may not cover all possible scenarios though, and
      must therefore be weighed carefully against the specific application
      threat model.</t>

<!--
      <t>By having a non-tamperable proof of authorship attached, each SCS
      cookie can always be validated by the originator, making it possible for
      a server to handle clients' session state without the need to store 
      it locally.  In fact, an SCS enabled server could completely delegate the 
      application state storage to the client (e.g. a web browser) and use it, 
      in all respects, as a remote storage device.  
      The result of the cryptographic transformations applied to state data can
      be used to ensure that its information authenticity and confidentiality 
      attributes are the same as if they were stored privately on 
      server-side.</t>

      <t>The no-storage requirement, which is the key design constraint of
      SCS, makes it an ideal candidate in the following settings: <list
          style="letters">
          <t>devices with little or no storage - typically embedded devices
          which provide functionality such as software updates, configuration,
          device monitoring, etc. via an HTTP interface;</t>

          <t>web applications with high availability or load balancing 
          requirements, which may delegate handling of the application state 
          to clients instead of using shared storage or forced peering, to 
          enhance overall parallelism.</t>
        </list></t>
     
      <t>It is worth noting that a peculiar difference between SCS, when used 
      in strict no-storage mode, and usual "server-side" cookie sessions arises
      as soon as we carefully consider the roles of the playing entities. 
      In the "server-side" model, the server acts a triple role as the 
      "generator", the "owner", and the "verifier" of cookie credentials.
      Instead, a server implementing SCS in no-storage mode, acts the 
      "generator" and "verifier" roles only - the "owner" being inapplicable 
      for obvious reasons.</t>

      <t>In all respects, the Server grants the custody of the generated
      cookie to the Client, whose trust model needs to be taken into
      consideration when designing applications that use SCS this way.  
      The consequences of such discrepancy (e.g. deliberate deletion of a 
      cookie, explicit privilege revocation, etc.) will be analyzed in 
      <xref target="sec_impact_of_scs_cookie_model"></xref>.</t>
-->
      <t>An SCS server may be implemented within a web application by means of
      a user library that exposes the core SCS functionality and leaves explicit
      control over SCS tokens to the programmer, or transparently, for example
      by hiding a "diskless session" facility behind a generic session API
      abstraction.  SCS implementers are free to choose the model that best
      suits their needs.</t>
    </section>

    <section title="Requirements Language">
      <t>The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT",
      "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this
      document are to be interpreted as described in 
      <xref target="RFC2119" />.</t>
    </section>

    <section anchor="sec_scs_protocol" title="SCS Protocol">
      <t>The SCS protocol defines: <list style="symbols">
          <t>the SCS cookie structure and encoding (<xref
          target="sec_pdu_description"></xref>);</t>

          <t>the cryptographic transformations involved in SCS cookie creation 
          and verification (<xref target="sec_crypto_transform"></xref>);</t>

          <t>the HTTP-based PDU exchange that uses the Set-Cookie and Cookie
          HTTP headers (<xref target="sec_pdu_exchange"></xref>);</t>

          <t>the underlying key management model (<xref
          target="sec_key_management"></xref>).</t>
        </list></t>

      <t>Note that the PDU is transmitted to the client as an opaque data
      block, hence no interpretation nor validation is necessary.
      The single requirement for client-side support of SCS is cookie
      activation on the user agent.  The origin server is the sole actor
      involved in the PDU manipulation process, which greatly simplifies the
      crypto operations - especially key management, which is usually a pesky
      task.</t>

      <t>In the following sections we assume S to be one or more
      interchangeable HTTP server entities (e.g. a server pool in a
      load-balanced or high-availability environment) and C to be the client 
      with a cookie-enabled browser, or any user agent with equivalent 
      capabilities.</t>

      <section anchor="sec_pdu_description" title="SCS Cookie Description">
        <t>S and C exchange a cookie (<xref target="sec_pdu_exchange" />),
        whose cookie-value consists of a sequence of adjacent non-empty values,
        each of which is the 'URL and Filename safe' Base-64 encoding <xref
        target="RFC4648" /> of a specific SCS field.</t>
        <t>(Hereafter the encoded and raw versions of each SCS field are
        distinguished based on the presence, or lack thereof, of the 'e'
        prefix in their name, e.g. eATIME and ATIME.)</t>
        <t>Each SCS field is separated by its left and/or right sibling by means 
        of the %x7c ASCII character (i.e. '|'), as follows:
        <figure anchor="abnf">
            <artwork align="left"><![CDATA[
scs-cookie        = scs-cookie-name "=" scs-cookie-value
scs-cookie-name   = token
scs-cookie-value  = eDATA "|" eATIME "|" eTID "|" eIV "|" eAUTHTAG
eDATA             = 1*base64url-character
eATIME            = 1*base64url-character
eTID              = 1*base64url-character
eIV               = 1*base64url-character
eAUTHTAG          = 1*base64url-character
            ]]></artwork>
        </figure>
        </t>

        <t>Confidentiality is limited to the application state information
        (i.e. the DATA field), while integrity and authentication apply to
        the entire cookie-value.</t>

        <t>The following subsections describe the syntax and semantics of
        each SCS cookie field.</t>

        <section anchor="sec_scs_atime" title="ATIME">
        <!-- hex or decimal ? -->
          <t>Absolute timestamp relating to the last read or write operation 
          performed on session DATA, encoded as a HEX string holding the number
          of seconds since the UNIX epoch (i.e. since 00:00:00, Jan 1
          1970.)</t>

          <t>This value is updated with each client contact and is used to
          identify expired sessions.  If the delta between the received ATIME 
          value and the current time on S is larger than a predefined
          "session_max_age" (which is chosen by S as an application-level
          parameter), a session is considered to be no longer valid, and
          is therefore rejected.</t>

          <t>Such expiration error may be used to force user logout from an SCS
          cookie based session, or hooked in the web application logic to
          display an HTML form requiring re-validation of user credentials.</t>
        </section>

        <!-- end of ATIME -->

        <section anchor="sec_scs_data" title="DATA">
          <t>Block of encrypted and optionally compressed data, possibly
          containing the current session state.  Note that no restriction is 
          imposed on the clear text structure: the protocol is completely agnostic 
          as to inner data layout.</t>
          <t>Generally speaking, the plain text is the "normal" cookie that
          would have been exchanged by S and C if SCS had not been used.</t>


<!-- TODO data split across many SCS cookies TODO

          <t>If the total size of the SCS cookie, including name, value
          and attributes, exceeds 4096 bytes (see Section 6.1. of <xref
          target="RFC6265"></xref>), it is sliced into n
          SCS_DATA{n} cookies, each 4KB in size, so that the concatenation of
          their values ordered by cookie name (1, 2, ..., N) yields the
          original SCS_DATA.</t>

          <t>It is suggested <xref target="RFC6265"></xref>
          that browsers accept at least 50 cookies per domain, which could
          lead to a theoretical limit of 184 KB as the maximum allowed state
          data block.</t>

          <t>Anyway, in order to minimize both network bandwidth and client
          cookie store consumption, applications should try to upper bound
          state data to some sensible value. Also, an SCS implementation MAY
          decide to limit the accepted state data to any value greater than
          or equal to 4KB.</t>
-->
        </section>

        <!-- end of DATA -->

        <section anchor="sec_scs_tid" title="TID">
          <t>This identifier is equivalent to a SPI in a Data Security SA <xref
          target="RFC3740"></xref>) and consists of an ASCII string that 
          uniquely identifies the transform set (keys and algorithms) used to 
          generate this SCS cookie.</t>

          <t>SCS assumes that a key-agreement/distribution mechanism exists
          for environments in which S consists of multiple servers, which 
          provides a unique external identifier for each transform set shared 
          amongst pool members.</t>

          <t>Such mechanism may safely downgrade to a periodic key-refresh if
          there is only one server in the pool and the key is generated in
          place - i.e. it is not handled by an external source.</t>

          <t>However, when many servers act concurrently upon the same pool, a
          more sophisticated protocol, whose specification is out of the scope
          of the present document, must be devised (ideally one that is able to
          handle key agreement for dynamic peer groups in a secure and efficient
          way, e.g. <xref target="CLIQUES" />, <xref target="Steiner" />).</t>
        </section>

        <!-- end of TID -->

        <section anchor="sec_scs_iv" title="IV">
          <t>Initialization Vector used for the encryption algorithm (see <xref
          target="sec_crypto_transform"></xref>).</t>

          <t>In order to avoid providing correlation information to a possible
          attacker with access to a sample of SCS cookies created using the
          same TID, the IV MUST be created randomly for each SCS cookie.</t>
        </section>

        <!-- end of IV -->

        <section anchor="sec_scs_authtag" title="AUTHTAG">
          <t>Authentication tag based on the plain string concatenation of the base64url encoded DATA, ATIME, TID and IV fields, framed by the "|" separator (see also the definition of the Box() function in <xref target="sec_crypto_transform" />):
          <figure>
            <artwork align="left"><![CDATA[
AUTHTAG = HMAC(base64url(DATA)  "|"
               base64url(ATIME) "|"
               base64url(TID)   "|"
               base64url(IV))
            ]]></artwork>
         </figure>
         Note that, from a cryptographic point of view, the "|" character
         provides explicit authentication of the length of each supplied field,
         which results in a robust countermeasure against splicing attacks.
         </t>
        </section>

        <!-- end of SCS_AUTHTAG -->
      </section>

      <!-- end PDU description -->

      <section anchor="sec_crypto_transform" title="Crypto Transform">
        <t>SCS could potentially use any combination of primitives capable of
        performing authenticated encryption. In practice an encrypt-then-mac
        approach <xref target="Kohno"></xref> with CBC-mode encryption and
        <xref target="RFC2104">HMAC</xref> authentication was chosen.</t>

        <t>The two algorithms MUST be associated with two independent
        keys.</t>

        <t>The following conventions will be used in the algorithm description
        (<xref target="sec_outbound_transform"></xref> and <xref
        target="sec_inbound_transform"></xref>): <list style="symbols">
            <t>Enc/Dec(): block encryption/decryption functions (<xref
            target="sec_cipher_set"></xref>);</t>

            <t>HMAC(): authentication function (<xref
            target="sec_cipher_set"></xref>);</t>

            <t>Comp/Uncomp(): compression/decompression functions (<xref
            target="sec_compression"></xref>);</t>

            <t>e/d(): cookie value encoding/decoding functions (<xref
            target="sec_cookie_encoding"></xref>);</t>

            <t>RAND(): random number generator <xref target="RFC4086"></xref>;</t>

            <t>Box(): string boxing function. It takes an arbitrary
            number of base64url encoded strings and returns the string obtained
            by concatenating each of the inputs in the exact order in which they
            are listed, separated by the "|" char.  For example:
            <list style="empty">
              <t>Box("akxI", "MTM", "Hadvo") = "akxI|MTM|Hadvo".</t>
            </list></t>
          </list></t>

        <section title="Choice and Role of the Framing Symbol">
            <t>Note that that the adoption of "|" as the framing symbol
            in the Box() function is arbitrary: any char allowed by the cookie-value
            ABNF in <xref target="RFC6265" /> is safe to be used as long it has
            empty intersection with the base64url alphabet.</t>

            <t>It is also worth noting that the role of the framing symbol, which provides
            an implicit length indicator for each of the atoms, is key to the correctness
            and security of SCS.</t>

            <t>This is especially relevant when the authentication tag is computed 
            (see <xref target="sec_scs_authtag"/>).  More specifically, the
            explicit inclusion of the framing symbol within the HMAC input seals
            the integrity of the blob as a whole together with each of its
            composing atoms in their exact position.</t>

            <t>This feature makes the protocol robust against attacks aimed at disrupting
            the security of SCS PDUs by freely moving boundaries between adjacent atoms.</t>
        </section>

        <section anchor="sec_cipher_set" title="Cipher Set">
          <t>Implementors MUST support at least the following algorithms:
          <list style="symbols">
              <t>AES-CBC-128 for encryption <xref target="NIST-AES" />;</t>

              <t>HMAC-SHA1 with a 128 bit key for authenticity and
              integrity,</t>
            </list> which appear to be sufficiently secure in a broad range of
          use cases <xref target="Bellare"></xref>, <xref target="RFC6194" />,
          are widely available, and can be implemented in a few kilobytes of memory,
          providing an extremely valuable feature for constrained devices.</t>

          <t>One should consider using larger cryptographic key lengths (192
          or 256 bit) according to the actual security and overall system
          performance requirements.</t>

        <!-- TODO add reasoning about algo != AES-CBC / HMAC -->

        </section>

        <!-- end Cipher Set -->

        <section anchor="sec_compression" title="Compression">
          <t>Compression, which may be useful or even necessary when handling
          large quantities of data, is not compulsory (in such case
          Comp/Uncomp are replaced by an identity matrix). If this function is
          enabled, <xref target="RFC1951">DEFLATE</xref> format MUST be
          supported.</t>

          <t>Some advice to SCS users: compression should not be enabled when
          handling relatively short and entropic state such as pseudo random 
          session identifiers.  Instead, large and quite regular state blobs 
          could get a significant boost when compressed.</t>
        </section>

        <!-- end Compression -->

        <section anchor="sec_cookie_encoding" title="Cookie Encoding">
          <t>SCS cookie values MUST be encoded using the URL and filename safe
          alphabet (i.e. base64url) defined in section 5 of <xref
          target="RFC4648">Base-64</xref>.  This encoding is very wide-spread,
          falls smoothly into the encoding rules defined in Section 4.1.1 of
          <xref target="RFC6265"></xref>, and can be safely used to supply
          SCS based authorization tokens within a URI (e.g. in a query string
          or straight into a path segment).</t>
        </section>

        <!-- end Cookie Encoding -->

        <section anchor="sec_outbound_transform" title="Outbound Transform">
          <t>The output data transformation as seen by the server (the only
          actor which explicitly manipulates SCS cookies) is illustrated by the
          pseudo-code in <xref target="fig_outbound_transform"></xref>.</t>

          <figure anchor="fig_outbound_transform">
            <artwork align="center"><![CDATA[
1.  IV := RAND()
2.  ATIME := NOW
3.  DATA := Enc(Comp(plain-text-cookie-value), IV)
4.  AUTHTAG := HMAC(Box(e(DATA), e(ATIME), e(TID), e(IV)))
                ]]></artwork>
          </figure>

          <t>A new Initialization Vector is randomly picked (step 1.).
          As previously mentioned (<xref target="sec_scs_iv" />) this step is
          necessary to avoid providing correlation information to an
          attacker.</t>

          <t>A new ATIME value is taken as the current timestamp according to
          the server clock (step 2.).</t>

          <t>Since the only user of the ATIME field is the server, it is
          unnecessary for it to be synchronized with the client - though
          it needs to use a fairly stable clock.  However, if multiple servers 
          are active in a load-balancing configuration, clocks SHOULD be 
          synchronized to avoid errors in the calculation of session expiry.</t>

          <t>The plain text cookie value is then compressed (if needed) and
          encrypted by using the key-set identified by TID (step 3.).</t>

          <t>If the length of (compressed) state is not a multiple of the
          block size, its value MUST be filled with as many padding bytes of
          equal value as the pad length - as defined by the scheme given in
          Section 6.3 of <xref target="RFC5652"></xref>.</t>

          <t>Then the authentication tag, which encompasses each SCS field
          (along with lengths, and relative positions) is computed by HMAC'ing
          the "|"-separated concatenation of their base64url representations using
          the key-set identified by TID (step 4.).</t>

          <t>Finally the SCS cookie-value is created as follows:
          <list style="empty">
              <t>scs-cookie-value = Box(e(DATA), e(ATIME), e(TID), e(IV), e(tag))</t>
          </list></t>
        </section>

        <!-- end Outbound Transform -->

        <section anchor="sec_inbound_transform" title="Inbound Transform">
          <t>The inbound transformation is described in <xref
          target="fig_inbound_transform"></xref>.  Each of the 'e'-prefixed
          names shown has to be interpreted as the base64url encoded value of
          the corresponding SCS field.</t>

          <figure anchor="fig_inbound_transform">
            <artwork align="center"><![CDATA[
0.  If (split_fields(scs-cookie-value) == ok)
1.      tid' := d(eTID)
2.      If (tid' is available)
3.          tag' := d(eAUTHTAG)
4.          tag := HMAC(Box(eDATA, eATIME, eTID, eIV))
5.          If (tag = tag')
6.              atime' := d(eATIME)
7.              If (NOW - atime' <= session_max_age)
8.                  iv' := d(eIV)
                    data' := d(eDATA)
9.                  state := Uncomp(Dec(data', iv'))
10.             Else discard PDU
11.         Else discard PDU
12.     Else discard PDU
13. Else discard PDU
                ]]></artwork>
          </figure>

          <t>First of all, the inbound scs-cookie-value is broken into its
          component fields which MUST be exactly 5, and each at least of the
          minimum length specified in <xref target="abnf" /> (step 0.).
          In case any of these preliminary checks fails, the PDU is discarded 
          (step 13.); else TID is decoded to allow key-set lookup (step 1.).</t>

          <t>If the cryptographic credentials (encryption and authentication
          algorithms and keys identified by TID) are unavailable (step 12.),
          the inbound SCS cookie is discarded since its value has no chance to
          be interpreted correctly.
          This may happen for several reasons: e.g., if a device without 
          storage has been reset and loses the credentials stored in RAM, if 
          a server pool node desynchronizes, or in case of a key compromise 
          that forces the invalidation of all current TID's, etc.</t>

          <t>When a valid key-set is found (step 2.), the AUTHTAG field is
          decoded (step 3.) and the (still) encoded DATA, ATIME, TID and IV 
          fields are supplied to the primitive that computes the authentication
          tag (step 4.).</t>

          <t>If the tag computed using the local key-set matches the one carried
          by the supplied SCS cookie, we can be confident that the cookie
          carries authentic material; otherwise the SCS cookie is discarded
          (step 11.).</t>

          <t>Then the age of the SCS cookie (as deduced by ATIME field value
          and current time provided by the server clock) is decoded and 
          compared to the maximum time-to-live defined by the session_max_age 
          parameter.</t>

          <t>If the "age" check passes, the DATA and IV fields are finally
          decoded (step 8.), so that the original plain text data can be
          extracted from the encrypted and optionally compressed blob (step
          9.).</t>

          <t>Note that steps 5. and 7. allow any altered packets or expired
          sessions to be discarded, hence avoiding unnecessary state decryption
          and decompression.</t>

        </section>

        <!-- end Inbound Transform -->
      </section>

      <!-- end Crypto Transform -->

      <section anchor="sec_pdu_exchange" title="PDU Exchange">
        <t>SCS can be modeled in the same manner as a typical
        store-and-forward protocol, in which the endpoints are S, consisting
        of one or more HTTP servers, and the client C, an intermediate node
        used to "temporarily" store the data to be successively forwarded to
        S.</t>

        <t>In brief, S and C exchange an immutable cookie data block (<xref
        target="sec_pdu_description"></xref>): the state is stored on the
        client at the first hop and then restored on the server at the second,
        as in <xref target="fig_pdu_exchange"></xref>.</t>

        <figure anchor="fig_pdu_exchange">
          <artwork align="center"><![CDATA[
1.  dump-state:
    S --> C
        Set-Cookie: ANY_COOKIE_NAME=KrdPagFes_5ma-ZUluMsww|MTM0...
           Expires=...; Path=...; Domain=...;

2.  restore-state:
    C --> S
        Cookie: ANY_COOKIE_NAME=KrdPagFes_5ma-ZUluMsww|MTM0...
          ]]></artwork>
        </figure>

        <section anchor="cookie_attributes" title="Cookie Attributes">
          <t>In the following sub paragraphs a series of recommendations is
          provided in order to maximize SCS PDU fitness in the generic cookie
          ecosystem.</t>

          <section anchor="sec_expires" title="Expires">
            <t>If an SCS cookie includes an Expires attribute, then the attribute
            MUST be set to a value consistent with session_max_age.</t>

            <t>For maximum compatibility with existing user agents the
            timestamp value MUST be encoded in rfc1123-date format which
            requires a 4-digit year.</t>
          </section>

          <section anchor="sec_max_age" title="Max-Age">
            <t>Since not all UAs support this attribute, it MUST NOT be
            present in any SCS cookie.</t>
          </section>

          <section anchor="sec_domain" title="Domain">
            <t>SCS cookies MUST include a Domain attribute compatible with
            application usage.</t>

            <t>A trailing '.' MUST NOT be present in order to minimize the
            possibility of a user agent ignoring the attribute value.</t>
          </section>

          <section anchor="sec_secure" title="Secure">
            <t>This attribute MUST always be asserted when SCS sessions are
            carried over a TLS channel.</t>
          </section>

          <section anchor="sec_httponly" title="HttpOnly">
            <t>This attribute SHOULD always be asserted.</t>
          </section>

        </section>
        <!-- end Cookie Attributes -->
      </section>

      <!-- end PDU Exchange -->
    </section>

    <!-- end Protocol -->

    <section anchor="sec_key_management"
             title="Key Management and Session State">
      <t>This specification provides some common recommendations and practices
      relevant to cryptographic key management.</t>

      <t>In the following, the term 'key' references both encryption and HMAC
      keys. <list style="symbols">
          <t>The key SHOULD be generated securely following the randomness
          recommendations in <xref target="RFC4086"></xref>;</t>

          <t>the key SHOULD only be used to generate and verify SCS PDUs;</t>

          <t>the key SHOULD be replaced regularly as well as any time the
          format of SCS PDUs or cryptographic algorithms changes.</t>
        </list></t>

      <t>Furthermore, to preserve the validity of active HTTP sessions upon
      renewal of cryptographic credentials (whenever the value of TID changes),
      an SCS server MUST be capable of managing at least two transforms 
      contemporarily: the currently instantiated one, and its predecessor.</t>

      <t>Each transform set SHOULD be associated with an attribute pair:
      "refresh" and "expiry", which is used to identify the exposure limits
      (in terms of time or quantity of encrypted and/or authenticated bytes,
      etc) of related cryptographic material.</t>

      <t>In particular, the "refresh" attribute specifies the time limit for
      substitution of transform set T with new material T'. From that moment
      onwards, and for an amount of time determined by "expiry", all new
      sessions will be created using T', while the active T-protected ones go
      through a translation phase in which: <list style="symbols">
          <t>the inbound transformation authenticates and
          decrypts/decompresses using T (identified by TID);</t>

          <t>the outbound transformation encrypts/compresses and authenticates
          using T'.</t>
        </list></t>

      <figure anchor="fig_keylifetime">
        <artwork align="center"><![CDATA[
T' {not valid yet} |---------------------|----------------
                   |  translation stage  |
T  ----------------|---------------------| {no longer valid}
                 refresh         refresh + expiry
        ]]></artwork>
      </figure>

      <t>As shown in <xref target="fig_keylifetime"></xref>, the duration of the
      HTTP session MUST fit within the lifetime of a given transform set (i.e.
      from creation time until "refresh" + "expiry").</t>

      <t>In practice, this should not be an obstacle because the longevity of
      the two entities (HTTP session and SCS transform set) should differ by
      one or two orders of magnitude.</t>

      <t>An SCS server may take this into account by determining the duration
      of a session adaptively according to the expected deletion time of the
      active T, or by setting the "expiry" value to at least the maximum
      lifetime allowed by an HTTP session.</t>

      <t>Since there is only one refresh attribute also in situations with
      more than one key (e.g. one for encryption and one for authentication)
      within the same T, the smallest value is chosen.</t>

      <t>It is critical for the correctness of the protocol that, in case
      multiple equivalent SCS servers are used in a pool, all of them share
      the same view of time (see also <xref target="sec_outbound_transform" />)
      and keying material.</t>
      
      <t>As far as the latter is concerned, SCS does not mandate the use of any
      specific key sharing mechanism, and will keep working correctly as long
      as the said mechanism is able to provide a single, coherent, view of the keys
      shared by pool members - while conforming to the recommendations given
      in this section.</t>
    </section>

    <section anchor="scs_inflation" title="Cookie Size Considerations">

      <t>In general, SCS cookies are bigger than their plain text counterparts.
      This is due to the following reasons: 
      <list style="symbols">
        <t>inflation of the Base-64 encoding of state data (approx. 
        1.4 times the original size, including the encryption padding);</t> 
        <t>the fixed size increment (approx. 80/90 bytes) caused by SCS fields and 
        framing overhead.</t>
      </list></t>
      <t>While the former is a price the user must always pay proportionally
      to the original data size, the latter is a fixed quantum, which can be 
      huge on small amounts of data, but is quickly absorbed as soon as data 
      becomes big enough.</t>

      <t>The following table compares byte lengths of SCS cookies (with a four
      byte TID) and corresponding plain text cookies in a worst case scenario,
      i.e. when no compression is in use (or applicable).
      <figure>
        <artwork align="center"><![CDATA[
  plain |  SCS
 -------+-------
    11  |  128
   102  |  256
   285  |  512
   651  | 1024
  1382  | 2048
  2842  | 4096
        ]]></artwork>
      </figure>
      The largest uncompressed cookie value that can be safely supplied to SCS 
      is about 2.8KB.
      </t>

    </section>

    <section anchor="sec_ack" title="Acknowledgements">
      <t>We would like to thank Jim Schaad, David Wagner, Lorenzo Cavallaro,
      Willy Tarreau, Tobias Gondrom, John Michener, Sean Turner, Barry Leiba,
      Robert Sparks, Stephen Farrell, Stewart Bryant, and Nevil Brownlee for
      their valuable feedback on this document.</t>
    </section>

    <section anchor="sec_iana" title="IANA Considerations">
      <t>This memo includes no request to IANA.</t>
    </section>

    <section anchor="sec_security_considerations"
             title="Security Considerations">
      <section anchor="sec_security_of_the_crypto_protocol"
               title="Security of the Cryptographic Protocol">
        <t>From a cryptographic architecture perspective, the described
        mechanism can be easily traced to an "encode then encrypt then MAC"
        scheme (Encode-then-EtM) as described in <xref
        target="Kohno"></xref>.</t>

        <t>Given a "provably-secure" encryption scheme and MAC (as for the
        algorithms mandated in <xref target="sec_cipher_set"></xref>),
        Kohno et al. <xref target="Kohno"></xref> demonstrate that their
        composition results in a secure authenticated encryption scheme.</t>
      </section>

      <section anchor="sec_impact_of_scs_cookie_model"
               title="Impact of the SCS Cookie Model">
        <t>The fact that the server does not own the cookie it produces, gives
        rise to a series of consequences that must be clearly understood when
        one envisages the use of SCS as a cookie provider and validator for
        his/her application.</t>

        <t>In the following paragraphs, a set of different attack scenarios
        (together with corresponding countermeasures where applicable) are
        identified and analyzed.</t>

        <section anchor="sec_old_cookie_replay" title="Old cookie replay">
          <t>SCS doesn't address replay of old cookie values.</t>

          <t>In fact, there is nothing that guarantees an SCS application
          about the client having returned the most recent version of the
          cookie.</t>

          <t>As with "server-side" sessions, if an attacker gains possession
          of a given user's cookies - via simple passive interception or
          another technique - he/she will always be able to restore the state
          of an intercepted session by representing the captured data to the
          server.</t>

          <t>The ATIME value along with the session_max_age configuration
          parameter allow SCS to mitigate the chances of an attack (by forcing
          a time window outside of which a given cookie is no longer valid),
          but cannot exclude it completely.</t>

          <t>A countermeasure against the "passive interception and replay"
          scenario can be applied at transport/network level using the
          anti-replay services provided by e.g., <xref
          target="RFC5246">SSL/TLS</xref> or <xref
          target="RFC4301">IPsec</xref>.</t>

          <t>A native solution is not in scope with the security properties
          inherent to an SCS cookie.  Hence, application wishing to be replay-resistant
          must put in place some ad hoc mechanism to prevent clients (both rogue and
          legitimate) from (a) being able to replay old cookies as valid credentials
          and/or (b) getting any advantage by replaying them.</t>

          <t>In the following, some typical use cases are illustrated: <list
              style="symbols">
              <t>Session inactivity timeout scenario (implicit invalidation):
              use the session_max_age parameter if a global setting is viable,
              else place an explicit TTL in the cookie (e.g.
              validity_period="start_time, duration") that can be verified by
              the application each time the Client presents the SCS
              cookie.</t>

              <t>Session voidance scenario (explicit invalidation): put a
              randomly chosen string into each SCS cookie (cid="$(random())")
              and keep a list of valid session cid's against which the SCS
              cookie presented by the client can be checked. When a cookie
              needs to be invalidated, delete the corresponding cid from the
              list. The described method has the drawback that, in case a
              non-permanent storage is used to archive valid cid's, a
              reboot/restart would invalidate all sessions (It can't be used
              when |S| &gt; 1).</t>

              <t>One-shot transaction scenario (ephemeral): this is a
              variation on the previous theme when sessions are consumed
              within a single request/response. Put a nonce="$(random())"
              within the state information and keep a list of not-yet-consumed
              nonces in RAM. Once the client presents its cookie credential,
              the embodied nonce is deleted from the list and will be
              therefore discarded whenever replayed.</t>

              <t>TLS binding scenario: the Server application must run on TLS,
              be able to extract information related to the current TLS session, and
              store it in the DATA field of the SCS cookie itself <xref target="RFC5056" />.
              The establishment of this secure channel binding prevents any third party 
              from reusing the SCS cookie, and drops its value altogether after the TLS session
              is terminated - regardless of the lifetime of the cookie.  This approach
              suffers a scalability problem in that it requires each SCS session to be
              handled by the same client-server pair.  However, it provides
              a robust model and an affordable compromise when security of the session
              is exceptionally valuable (e.g. a user interacting with his/her online
              banking site).</t>

            </list></t>

          <t>It is worth noting that in all but the latter scenario, if an attacker is able 
          to use the cookie before the legitimate Client gets a chance to, then the
          impersonation attack will always succeed.</t>

        </section>

        <section anchor="sec_cookie_deletion" title="Cookie Deletion">
          <t>A direct, and important, consequence of the missing owner role in
          SCS is that a client could intentionally delete its cookie and
          return nothing.</t>

          <t>The application protocol has to be designed so there is no
          incentive to do so, for instance: <list style="symbols">
              <t>it is safe for the cookie to represent some kind of positive
              capability - the possession of which increases the client's
              powers;</t>

              <t>it is not safe to use the cookie to represent negative
              capabilities - where possession reduces the client's powers - or
              for revocation.</t>
            </list></t>

          <t>Note that this behavior is not equivalent to cookie removal in
          the "server-side" cookie model, because in case of missing cookie
          backup by other parties (e.g. the application using SCS), the Client
          could simply make it disappear once and for all.</t>
        </section>

        <section anchor="sec_cookie_sharing_or_theft"
                 title="Cookie Sharing or Theft">
          <t>Just like with plain cookies, SCS doesn't prevent sharing (both 
          voluntary and illegitimate) of cookies between multiple clients.</t>

          <t>In the context of voluntary cookie sharing, using HTTPS only as a separate
          secure transport provider is useless: in fact, Client certificates are just as
          shareable as cookies.  Instead, using some form of secure channel binding (as
          illustrated in <xref target="sec_old_cookie_replay" />) may cancel this risk.</t>
          
          <t>The risk of theft could be mitigated by securing the wire (e.g.
                  via HTTPS, IPsec, VPN, ...), thus reducing the opportunity of
          cookie stealing to a successful attack on the protocol endpoints.</t>

          <t>In order to reduce the attack window on stolen cookies, an
          application may choose to generate cookies whose lifetime is upper
          bounded by the browsing session lifetime (i.e. by not attaching an
          Expires attribute to them.)</t>
        </section>

        <section anchor="session_fixation"
                 title="Session Fixation">

          <t>Session fixation vulnerabilities <xref target="Kolsec" />
          are not addressed by SCS.</t>

          <t>A more sophisticated protocol involving active participation of
          the UA in the SCS cookie manipulation process would be needed: e.g.
          some form of challange-response exchange initiated by the Server in
          the HTTP response and replied to by the UA in the next chained HTTP
          request.</t>

          <t>Unfortunately the present specification which is based on 
          <xref target="RFC6265" /> sees the UA as a completely passive 
          actor, whose role is to blindly paste the cookie value set 
          by the Server.</t>

          <t>Nevertheless, the SCS cookies wrapping mechanism may be used 
          in the future as a building block for a more robust HTTP state 
          management protocol.</t>

        </section>

      </section>

      <section anchor="sec_advantages"
               title="Advantages of SCS over Server-side Sessions">

        <t>Note that all the above-mentioned vulnerabilities also apply to
        plain cookies, making SCS at least as secure, but there are a few 
        good reasons to consider its security level enhanced.</t>

        <t>First of all, the confidentiality and authentication features 
        provided by SCS protect the cookie-value which is normally plain text
        and tamperable.</t>

        <t>Furthermore, neither of the common vulnerabilities of server-side 
        sessions (SID prediction and SID brute forcing) can be exploited when 
        using SCS, unless the attacker possesses encryption and HMAC keys 
        (both current ones and those relating to the previous set of 
        credentials).</t>

        <t>More in general, no slicing nor altering operations can be done over
        an SCS PDU without controlling the cryptographic key-set.</t>

      </section>
    </section>
  </middle>

  <back>
    <references title="Normative References">
      &RFC2119;
      &RFC2616;
      &RFC4648;
      &RFC1951;
      &RFC4086;
      &RFC2104;
      &RFC5652;
      &RFC6265;
      &RFC6194;

      <reference anchor="NIST-AES">
        <front>
          <title>Advanced Encryption Standard (AES)</title>
          <author />
          <date month="November" year="2001" />
        </front>
        <seriesInfo name="NIST," value="FIPS PUB 197" />
      </reference>

    </references>

    <references title="Informative References">
      &RFC5246;
      &RFC3740;
      &RFC4301;
      &RFC5056;

      <reference anchor="Bellare">
        <front>
          <title>New Proofs for NMAC and HMAC: Security Without
          Collision-Resistance</title>

          <author initials="M.B." surname="Bellare"></author>

          <date year="2006" />
        </front>
      </reference>

      <reference anchor="Kohno">
        <front>
          <title>Building Secure Cryptographic Transforms, or How to Encrypt
          and MAC</title>

          <author initials="T.K." surname="Kohno"></author>

          <author initials="A.P." surname="Palacio"></author>

          <author initials="J.B." surname="Black"></author>

          <date year="2003" />
        </front>
      </reference>

      <reference anchor="Kolsec">
        <front>
          <title>Session Fixation Vulnerability in Web-based
          Applications</title>

          <author initials="M.K." surname="Kolsec"></author>

          <date year="2002" />
        </front>
      </reference>

      <reference anchor="Steiner">
        <front>
          <title>Diffie-Hellman Key Distribution Extended to Group Communication</title>
          <author initials="M." surname="Steiner"></author>
          <author initials="G." surname="Tsudik"></author>
          <author initials="M." surname="Waidner"></author>
          <date year="1996" />
        </front>
      </reference>

      <reference anchor="CLIQUES">
        <front>
          <title>Cliques: A New Approach to Group Key Agreement</title>
          <author initials="M." surname="Steiner"></author>
          <author initials="G." surname="Tsudik"></author>
          <author initials="M." surname="Waidner"></author>
          <date year="1996" />
        </front>
      </reference>
    </references>

    <section anchor="examples" title="Examples">
      <t>The examples in this section have been created using the 'scs' test 
      tool bundled with LibSCS, a free and opensource reference implementation 
      of the SCS protocol that can be found at 
      <eref target="http://github.com/koanlogic/libscs"></eref>.</t>

      <section anchor="no_compression" title="No Compression">

        <t>The following parameters:
        <list style="symbols">
          <t>Plain text cookie: "a state string"</t>
          <t>AES-CBC-128 key: "123456789abcdef"</t>
          <t>HMAC-SHA1 key: "12345678901234567890"</t>
          <t>TID: "tid"</t>
          <t>ATIME: 1347265955</t>
          <t>IV: \xb4\xbd\xe5\x24\xf7\xf6\x9d\x44\x85\x30\xde\x9d\xb5\x55\xc9\x4f</t>
        </list></t>

        <t>produce the following tokens:
        <list style="symbols">
          <t>DATA: DqfW4SFqcjBXqSTvF2qnRA</t>
          <t>ATIME: MTM0NzI2NTk1NQ</t>
          <t>TID: OHU7M1cqdDQt</t>
          <t>IV: tL3lJPf2nUSFMN6dtVXJTw</t>
          <t>AUTHTAG: AznYHKga9mLL8ioi3If_1iy2KSA</t>
        </list></t>
      </section>

      <section anchor="compression" title="Use Compression">
        <t>The same parameters as above, except ATIME and IV:
        <list style="symbols">
          <t>Plain text cookie: "a state string"</t>
          <t>AES-CBC-128 key: "123456789abcdef"</t>
          <t>HMAC-SHA1 key: "12345678901234567890"</t>
          <t>TID: "tid"</t>
          <t>ATIME: 1347281709</t>
          <t>IV: \x1d\xa7\x6f\xa0\xff\x11\xd7\x95\xe3\x4b\xfb\xa9\xff\x65\xf9\xc7</t>
        </list></t>
        <t>produce the following tokens:
        <list style="symbols">
          <t>DATA: PbE-ypmQ43M8LzKZ6fMwFg-COrLP2l-Bvgs</t>
          <t>ATIME: MTM0NzI4MTcwOQ</t>
          <t>TID: akxIKmhbMTE8</t>
          <t>IV: HadvoP8R15XjS_up_2X5xw</t>
          <t>AUTHTAG: A6qevPr-ugHQChlr_EiKYWPvpB0</t>
        </list></t>
        <t>In both cases, the resulting SCS cookie is obtained via ordered 
        concatenation of the produced tokens, as described in 
        <xref target="sec_pdu_description" />.</t>
      </section>
    </section>

  </back>
</rfc>
