<?xml version="1.0" encoding="US-ASCII"?>
<!DOCTYPE rfc SYSTEM "rfc2629.dtd">
<?rfc toc="yes"?>
<?rfc tocdepth="3"?>
<?rfc tocindent="yes"?>
<?rfc symrefs="yes"?>
<?rfc sortrefs="yes"?>
<?rfc compact="yes"?>
<?rfc subcompact="no"?>

<rfc number="7635" category="std" submissionType="IETF" consensus="yes" 
   ipr="trust200902">
  <front>

    <title abbrev="STUN for Third-Party Authorization">Session Traversal
    Utilities for NAT (STUN) Extension for&nbsp;Third&nbhy;Party&nbsp;Authorization</title>

    <author fullname="Tirumaleswar Reddy" initials="T." surname="Reddy">
      <organization abbrev="Cisco">Cisco Systems, Inc.</organization>

      <address>
        <postal>
          <street>Cessna Business Park, Varthur Hobli</street>

          <street>Sarjapur Marathalli Outer Ring Road</street>

          <city>Bangalore</city>

          <region>Karnataka</region>

          <code>560103</code>

          <country>India</country>
        </postal>

        <email>tireddy@cisco.com</email>
      </address>
    </author>

    <author fullname="Prashanth Patil" initials="P." surname="Patil">
      <organization abbrev="Cisco">Cisco Systems, Inc.</organization>

      <address>
        <postal>
          <street></street>

          <street></street>

          <city>Bangalore</city>

          <country>India</country>
        </postal>

        <email>praspati@cisco.com</email>
      </address>
    </author>

    <author fullname="Ram Mohan Ravindranath" initials="R."
            surname="Ravindranath">
      <organization abbrev="Cisco">Cisco Systems, Inc.</organization>

      <address>
        <postal>
          <street>Cessna Business Park,</street>

          <street>Kadabeesanahalli Village, Varthur Hobli,</street>

          <street>Sarjapur-Marathahalli Outer Ring Road</street>

          <city>Bangalore</city>

          <region>Karnataka</region>

          <code>560103</code>

          <country>India</country>
        </postal>

        <email>rmohanr@cisco.com</email>
      </address>
    </author>

    <author fullname="Justin Uberti" initials="J." surname="Uberti">
      <organization>Google</organization>

      <address>
        <postal>
          <street>747 6th Ave S.</street>

          <city>Kirkland</city><region>WA</region>

          <code>98033</code>

          <country>United States</country>
        </postal>

        <email>justin@uberti.name</email>
      </address>
    </author>

    <date month="August" year="2015" />

    <workgroup>TRAM</workgroup>

    <abstract>
      <t>This document proposes the use of OAuth 2.0 to obtain and validate
      ephemeral tokens that can be used for Session Traversal Utilities for
      NAT (STUN) authentication. The usage of ephemeral tokens ensures that
      access to a STUN server can be controlled even if the tokens are
      compromised.</t>
    </abstract>
  </front>

  <middle>
    <section anchor="introduction" title="Introduction">
      <t>Session Traversal Utilities for NAT (STUN) <xref
      target="RFC5389"></xref> provides a mechanism to control access via
      'long-term' username/password credentials that are provided as part of
      the STUN protocol. It is expected that these credentials will be kept
      secret; if the credentials are discovered, the STUN server could be used
      by unauthorized users or applications. However, in web applications like
      WebRTC <xref target="WEBRTC"></xref> where JavaScript
      uses the browser functionality for making real-time audio and/or video
      calls, web conferencing, and direct data transfer, ensuring this secrecy
      is typically not possible.</t>

      <t>To address this problem and the ones described in <xref
      target="RFC7376"></xref>, this document proposes the use of third-party
      authorization using OAuth 2.0 <xref target="RFC6749"></xref> for STUN.
      Using OAuth 2.0, a client obtains an ephemeral token from an
      authorization server, e.g., a WebRTC server, and the token is presented to
      the STUN server instead of the traditional mechanism of presenting
      username/password credentials. The STUN server validates the
      authenticity of the token and provides required services. Third-party
      authorization using OAuth 2.0 for STUN explained in this specification
      can also be used with Traversal Using Relays around NAT (TURN) <xref
      target="RFC5766"></xref>.</t>
    </section>

    <section anchor="term" title="Terminology">
      <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"></xref>.</t>

      <t>This document uses the following abbreviations:</t>

      <t><list style="symbols">
          <t>WebRTC Server: A web server that supports WebRTC <xref
          target="WEBRTC"></xref>.</t>

          <t>Access Token: OAuth 2.0 access token.</t>

          <t>mac_key: The session key generated by the authorization server.
          This session key has a lifetime that corresponds to the lifetime of
          the access token, is generated by the authorization server, and is bound
          to the access token.</t>

          <t>kid: An ephemeral and unique key identifier. The kid also allows
          the resource server to select the appropriate keying material for
          decryption.</t>

          <t>AS: Authorization server.</t>

          <t>RS: Resource server.</t>
        </list></t>

      <t>Some sections in this specification show the WebRTC server as the
      authorization server and the client as the WebRTC client; however, WebRTC is
      intended to be used for illustrative purpose only.</t>
    </section>

    <section anchor="problem_stmt" title="Solution Overview">
      <t>The STUN client knows that it can use OAuth 2.0 with the target STUN
      server either through configuration or when it receives the new STUN
      attribute THIRD-PARTY-AUTHORIZATION in the error response with an error
      code of 401 (Unauthorized).</t>

      <t>This specification uses the token type 'Assertion' (a.k.a.
      self-contained token) described in <xref target="RFC6819"></xref> where
      all the information necessary to authenticate the validity of the token
      is contained within the token itself. This approach has the benefit of
      avoiding a protocol between the STUN server and the authorization server
      for token validation, thus reducing latency. The content of the token is
      opaque to the client. The client embeds the token within a STUN request
      sent to the STUN server. Once the STUN server has determined the token
      is valid, its services are offered for a determined period of time.
      The access token issued by the authorization server is explained in <xref
      target="token"></xref>. OAuth 2.0 in <xref target="RFC6749"></xref>
      defines four grant types. This specification uses the OAuth 2.0 grant
      type 'Implicit' as explained in Section 1.3.2 of <xref
      target="RFC6749"></xref> where the client is issued an access token
      directly. The string 'stun' is defined by this specification for use as
      the OAuth scope parameter (see Section 3.3 of <xref
      target="RFC6749"></xref>) for the OAuth token.</t>

      <t>The exact mechanism used by a client to obtain a token and other
      OAuth 2.0 parameters like token type, mac_key, token lifetime, and kid is
      outside the scope of this document. <xref target="Interaction"></xref>
      provides an example deployment scenario of interaction between the
      client and authorization server to obtain a token and other OAuth 2.0
      parameters.</t>

      <t><xref target="ex"></xref> illustrates the use of OAuth 2.0 to achieve
      third-party authorization for TURN.</t>

      <section anchor="ex" title="Usage with TURN">
        <t>TURN, an extension to the STUN protocol, is often used to improve
        the connectivity of peer-to-peer (P2P) applications. TURN ensures that a connection
        can be established even when one or both sides are incapable of a
        direct P2P connection. However, as a relay service, it imposes a
        non-trivial cost on the service provider. Therefore, access to a TURN
        service is almost always access controlled. In order to achieve third-party
        authorization, a resource owner, e.g., a WebRTC server, authorizes a
        TURN client to access resources on the TURN server.</t>

        <t>In this example, a resource owner, i.e., a WebRTC server, authorizes a
        TURN client to access resources on a TURN server.</t>

        <figure anchor="oauth_webrtc_terminology_map"
                title="OAuth Terminology Mapped to WebRTC Terminology">
          <artwork align="center"><![CDATA[
+----------------------+----------------------------+
|     OAuth 2.0        |            WebRTC          |
+======================+============================+
| Client               | WebRTC client              |
+----------------------+----------------------------+
| Resource owner       | WebRTC server              |
+----------------------+----------------------------+
| Authorization server | Authorization server       |
+----------------------+----------------------------+
| Resource server      | TURN server                |
+----------------------+----------------------------+
              ]]></artwork>
        </figure>

        <t></t>

        <t>Using the OAuth 2.0 authorization framework, a WebRTC client
        (third-party application) obtains limited access to a TURN server
        (resource server) on behalf of the WebRTC server (resource owner or
        authorization server). The WebRTC client requests access to resources
        controlled by the resource owner (WebRTC server) and hosted by the
        resource server (TURN server). The WebRTC client obtains the access token,
        lifetime, session key, and kid. The TURN client conveys the access
        token and other OAuth 2.0 parameters learned from the authorization
        server to the TURN server. The TURN server obtains the session key
        from the access token. The TURN server validates the token, computes
        the message integrity of the request, and takes appropriate action, i.e,
        permits the TURN client to create allocations. This is shown in an
        abstract way in <xref target="interactions"></xref>.</t>


        <figure anchor="interactions" title="Interactions">
          <artwork align="left"><![CDATA[                        +---------------+
                        |               +<******+
         +------------->| Authorization |       *
         |              | server        |       *    
         |   +----------|(WebRTC server)|       *  AS-RS,  
         |   |          |               |       *  AUTH keys    
(1)      |   |           +---------------+      *   (0)
Access   |   |  (2)                             *
Token    |   | Access Token                     *
request  |   |    +                             *
         |   | Session Key                      *
         |   |                                  *
         |   V                                  V
     +-------+---+                       +-+----=-----+
     |           |         (3)           |            |
     |           | TURN request + Access |            |
     | WebRTC    | Token                 | TURN       |
     | client    |---------------------->| server     |
     | (Alice)   | Allocate response (4) |            |
     |           |<----------------------|            |
     +-----------+                       +------------+
                                                  
User: Alice
****: Out-of-Band Long-Term Symmetric Key Establishment]]></artwork>
        </figure>

        <t></t>

        <t>In the below figure, the TURN client sends an Allocate request to
        the TURN server without credentials. Since the TURN server requires
        that all requests be authenticated using OAuth 2.0, the TURN server
        rejects the request with a 401 (Unauthorized) error code and the STUN
        attribute THIRD-PARTY-AUTHORIZATION. The WebRTC client obtains an access
        token from the WebRTC server, provides the access token to the TURN
        client, and it tries again, this time including the access token in the
        Allocate request. This time, the TURN server validates the token,
        accepts the Allocate request, and returns an Allocate success response
        containing (among other things) the relayed transport address
        assigned to the allocation.</t>

        <t><figure anchor="figure2" title="TURN Third-Party Authorization">
            <artwork><![CDATA[

+-------------------+                         +--------+  +---------+  
| .........  TURN   |                         |  TURN  |  |  WebRTC |
| .WebRTC .  client |                         |        |  |         | 
| .client .         |                         | server |  |  server |
| .........         |                         |        |  |         | 
+-------------------+                         +--------+  +---------+
  |       |           Allocate request                |         |
  |       |------------------------------------------>|         |
  |       |                                           |         |
  |       |         Allocate error response           |         |
  |       |         (401 Unauthorized)                |         |
  |       |<------------------------------------------|         |
  |       |         THIRD-PARTY-AUTHORIZATION         |         |  
  |       |                                           |         |                                      
  |       |                                           |         | 
  |       |      HTTP request for token               |         |
  |------------------------------------------------------------>|
  |       |      HTTP response with token parameters  |         |
  |<------------------------------------------------------------|
  |OAuth 2.0                                          |         |
   attributes                                         |         |
  |------>|                                           |         |
  |       |    Allocate request ACCESS-TOKEN          |         |
  |       |------------------------------------------>|         |
  |       |                                           |         |
  |       |         Allocate success response         |         |
  |       |<------------------------------------------|         |
  |       |             TURN messages                 |         |
  |       |      ////// integrity protected //////    |         |
  |       |      ////// integrity protected //////    |         |
  |       |      ////// integrity protected //////    |         |
       ]]></artwork>
          </figure></t>
      </section>
    </section>

    <section anchor="oauth" title="Obtaining a Token Using OAuth">
      <t>A STUN client needs to know the authentication capability of the STUN
      server before deciding to use third-party authorization. A STUN client
      initially makes a request without any authorization. If the STUN server
      supports third-party authorization, it will return an error message
      indicating that the client can authorize to the STUN server using an
      OAuth 2.0 access token. The STUN server includes an ERROR-CODE attribute
      with a value of 401 (Unauthorized), a nonce value in a NONCE attribute,
      and a SOFTWARE attribute that gives information about the STUN server's
      software. The STUN server also includes the additional STUN attribute
      THIRD-PARTY-AUTHORIZATION, which signals the STUN client that the STUN server
      supports third-party authorization.</t>

      <t>Note: An implementation may choose to contact the authorization
      server to obtain a token even before it makes a STUN request, if it
      knows the server details beforehand. For example, once a client has
      learned that a STUN server supports third-party authorization from a
      authorization server, the client can obtain the token before making
      subsequent STUN requests.</t>

      <section title="Key Establishment">
        <t>In this model, the STUN server would not authenticate the client
        itself but would rather verify whether the client knows the session
        key associated with a specific access token. An example of this approach
        can be found with the OAuth 2.0 Proof-of-Possession (PoP) Security
        Architecture <xref target="POP-ARCH"></xref>.
        The authorization server shares a long-term secret (K) with the STUN
        server. When the client requests an access token, the authorization
        server creates a fresh and unique session key (mac_key) and places it
        into the token encrypted with the long-term secret. Symmetric
        cryptography MUST be chosen to ensure that the size of the encrypted token
        is not large because usage of asymmetric cryptography will result in
        large encrypted tokens, which may not fit into a single STUN
        message.</t>

        <t>The STUN server and authorization server can establish a long-term symmetric
        key (K) and a certain authenticated encryption algorithm, using an out-of-band
        mechanism. The STUN and authorization servers MUST establish K
        over an authenticated secure channel. If authenticated encryption with
        AES-CBC and HMAC-SHA (defined in <xref
        target="ENCRYPT"></xref>) is used, then the AS-RS and AUTH
   keys will be derived from K. The AS-RS key is used for
        encrypting the self-contained token, and the message integrity of the
        encrypted token is calculated using the AUTH key. If the Authenticated
        Encryption with Associated Data (AEAD) algorithm defined in <xref
        target="RFC5116"></xref> is used, then there is no need to generate the
        AUTH key, and the AS-RS key will have the same value as K.</t>

        <t>The procedure for establishment of the long-term symmetric key is outside the
        scope of this specification, and this specification does not mandate
        support of any given mechanism. Sections <xref target="HTTP" format="counter"></xref> and <xref
        target="Manual" format="counter"></xref> show examples of mechanisms that can be
        used.</t>

        <section anchor="HTTP" title="HTTP Interactions">
          <t>The STUN and AS servers could choose to use Representational State Transfer (REST) API over HTTPS
          to establish a long-term symmetric key. HTTPS MUST be used for data
          confidentiality, and TLS based on a client certificate MUST be used for
          mutual authentication. To retrieve a new long-term symmetric key, the STUN
          server makes an HTTP GET request to the authorization server,
          specifying STUN as the service to allocate the long-term symmetric keys for
          and specifying the name of the STUN server. The response is returned
          with content-type 'application/json' and consists of a JavaScript
          Object Notation (JSON) <xref target="RFC7159"></xref> object
          containing the long-term symmetric key.</t>


          <t><figure>
              <artwork><![CDATA[Request
-------

service - specifies the desired service (TURN)
name    - STUN server name associated with the key

example: 
GET https://www.example.com/.well-known/stun-key?service=stun
&name=turn1@example.com


Response
--------

k   - long-term symmetric key
exp - identifies the time after which the key expires


example:
{
   "k" : 
"ESIzRFVmd4iZABEiM0RVZgKn6WjLaTC1FXAghRMVTzkBGNaaN496523WIISKerLi",
   "exp" : 1300819380,
   "kid" :"22BIjxU93h/IgwEb"
   "enc" : A256GCM
  }]]></artwork>
            </figure></t>

          <t>The authorization server must also signal kid to the STUN server,
          which will be used to select the appropriate keying material for
          decryption. The parameter 'k' is defined in Section 6.4.1 of <xref
          target="RFC7518"></xref>, 'enc' is defined
          in Section 4.1.2 of <xref
          target="RFC7516"></xref>, 'kid' is defined
          in Section 4.1.4 of <xref
          target="RFC7515"></xref>, and 'exp' is
          defined in Section 4.1.4 of <xref
          target="RFC7519"></xref>. A256GCM and other
          authenticated encryption algorithms are defined in Section 5.1 of
          <xref target="RFC7518"></xref>. A STUN
          server and authorization server implementation MUST support A256GCM
          as the authenticated encryption algorithm.</t>

          <t>If A256CBC-HS512 as defined in <xref
          target="RFC7518"></xref> is used, then the
          AS-RS and AUTH keys are derived from K using the mechanism explained
          in Section 5.2.2.1 of <xref
          target="RFC7518"></xref>. In this case, the
          AS-RS key length must be 256 bits and the AUTH key length must be 256 bits
          (Section 2.6 of <xref target="RFC4868"></xref>).</t>
        </section>

        <section anchor="Manual" title="Manual Provisioning">
          <t>The STUN and AS servers could be manually configured with a
          long-term symmetric key, an authenticated encryption algorithm, and kid.</t>

          <t>Note: The mechanism specified in this section requires
          configuration to change the long-term symmetric key and/or authenticated
          encryption algorithm. Hence, a STUN server and authorization server
          implementation SHOULD support REST as explained in <xref
          target="HTTP"></xref>.</t>
        </section>
      </section>
    </section>

    <section anchor="Request" title="Forming a Request">
      <t>When a STUN server responds that third-party authorization is
      required, a STUN client re-attempts the request, this time including
      access token and kid values in the ACCESS-TOKEN and USERNAME STUN
      attributes. The STUN client includes a MESSAGE-INTEGRITY attribute as
      the last attribute in the message over the contents of the STUN message.
      The HMAC for the MESSAGE-INTEGRITY attribute is computed as described in
      Section 15.4 of <xref target="RFC5389"></xref> where the mac_key is used
      as the input key for the HMAC computation. The STUN client and server
      will use the mac_key to compute the message integrity and do not perform
      MD5 hash on the credentials.</t>
    </section>

    <section anchor="attr" title="STUN Attributes">
      <t>The following new STUN attributes are introduced by this
      specification to accomplish third-party authorization.</t>

      <section anchor="attribute" title="THIRD-PARTY-AUTHORIZATION">
        <t>This attribute is used by the STUN server to inform the client that
        it supports third-party authorization. This attribute value contains
        the STUN server name. The authorization server may have tie ups with
        multiple STUN servers and vice versa, so the client MUST provide the
        STUN server name to the authorization server so that it can select the
        appropriate keying material to generate the self-contained token. If
        the authorization server does not have tie up with the STUN server,
        then it returns an error to the client. If the client does not support or
        is not capable of doing third-party authorization, then it defaults to
        first-party authentication. The THIRD&nbhy;PARTY&nbhy;AUTHORIZATION attribute is
        a comprehension-optional attribute (see Section 15 from <xref
        target="RFC5389"></xref>). If the client is able to comprehend
        THIRD-PARTY-AUTHORIZATION, it MUST ensure that third-party
        authorization takes precedence over first-party authentication
        (as explained in Section 10 of <xref target="RFC5389"></xref>).</t>
      </section>

      <section anchor="token" title="ACCESS-TOKEN">
        <t>The access token is issued by the authorization server. OAuth 2.0
        does not impose any limitation on the length of the access token but
        if path MTU is unknown, then STUN messages over IPv4 would need to be
        less than 548 bytes (Section 7.1 of <xref target="RFC5389"></xref>).
        The access token length needs to be restricted to fit within the
        maximum STUN message size. Note that the self-contained token is
        opaque to the client, and the client MUST NOT examine the token. The
        ACCESS-TOKEN attribute is a comprehension-required attribute (see
        Section 15 from <xref target="RFC5389"></xref>).</t>

        <t>The token is structured as follows:</t>

        <t><figure anchor="token1" title="Self-Contained Token Format">
            <artwork align="left"><![CDATA[      struct {
          uint16_t nonce_length; 
          opaque nonce[nonce_length];
          opaque {
              uint16_t key_length;
              opaque mac_key[key_length];
              uint64_t timestamp;
              uint32_t lifetime;
          } encrypted_block;            
      } token;
]]></artwork>
          </figure></t>

        <t>Note: uintN_t means an unsigned integer of exactly N bits.
        Single-byte entities containing uninterpreted data are of type 'opaque'.
        All values in the token are stored in network byte order.</t>

        <t>The fields are described below:</t>

        <t><list style="hanging">
            <t hangText="nonce_length:">Length of the nonce field. The length
            of nonce for AEAD
            algorithms is explained in <xref target="RFC5116"></xref>.</t>

            <t hangText="Nonce:">Nonce (N) formation is explained in Section
            3.2 of <xref target="RFC5116"></xref>.</t>

            <t hangText="key_length:">Length of the session key in octets. The key
            length of 160 bits MUST be supported (i.e., only the 160-bit key is
            used by HMAC-SHA-1 for message integrity of STUN messages). The key
            length facilitates the hash agility plan discussed in Section 16.3
            of <xref target="RFC5389"></xref>.</t>

            <t hangText="mac_key:">The session key generated by the
            authorization server.</t>

            <t hangText="timestamp:">64-bit unsigned integer field containing
            a timestamp. The value indicates the time since January 1, 1970,
            00:00 UTC, by using a fixed-point format. In this format, the
            integer number of seconds is contained in the first 48 bits of the
            field, and the remaining 16 bits indicate the number of 1/64000
            fractions of a second (Native format - Unix).</t>

            <t hangText="lifetime:">The lifetime of the access token, in
            seconds. For example, the value 3600 indicates one hour. The
            lifetime value MUST be greater than or equal to the 'expires_in'
            parameter defined in Section 4.2.2 of <xref
            target="RFC6749"></xref>, otherwise the resource server could revoke
            the token, but the client would assume that the token has not
            expired and would not refresh the token.</t>

            <t hangText="encrypted_block:">The encrypted_block (P) is
            encrypted and authenticated using the long-term symmetric key
            established between the STUN server and the authorization
            server.</t>
          </list></t>

        <t>The AEAD encryption operation has four inputs: K, N, A, and P, as
        defined in Section 2.1 of <xref target="RFC5116"></xref>, and there is
        a single output of ciphertext C or an indication that the requested
        encryption operation could not be performed.</t>

        <t>The associated data (A) MUST be the STUN server name. This ensures
        that the client does not use the same token to gain illegal access to
        other STUN servers provided by the same administrative domain, i.e.,
        when multiple STUN servers in a single administrative domain share the
        same long-term symmetric key with an authorization server.</t>

        <t>If authenticated encryption with AES-CBC and HMAC-SHA (explained in Section 2.1 of <xref
        target="ENCRYPT"></xref>) is used, then the
        encryption process is as illustrated below. The ciphertext consists of
        the string S, with the string T appended to it. Here, C and A denote
        ciphertext and the STUN server name, respectively. The octet string AL
        (Section 2.1 of <xref
        target="ENCRYPT"></xref>) is equal to the
        number of bits in A expressed as a 64-bit unsigned big-endian
        integer.<list style="symbols">
            <t>AUTH = initial authentication key length octets of K,</t>

            <t>AS-RS = final encryption key length octets of K,</t>

            <t>S = CBC-PKCS7-ENC(AS-RS, encrypted_block),<list style="symbols">
                <t>The Initialization Vector is set to zero because the
                encrypted_block in each access token will not be identical and
                hence will not result in generation of identical
                ciphertext.</t>
              </list></t>

            <t>mac = MAC(AUTH, A || S || AL),</t>

            <t>T = initial T_LEN octets of mac,</t>

            <t>C = S || T.</t>
          </list></t>

        <t>The entire token, i.e., the 'encrypted_block', is base64 encoded (see
        Section 4 of <xref target="RFC4648"></xref>), and the resulting access
        token is signaled to the client.</t>
      </section>
    </section>

    <section anchor="Response" title="STUN Server Behavior">
      <t>The STUN server, on receiving a request with the ACCESS-TOKEN attribute,
      performs checks listed in Section 10.2.2 of <xref
      target="RFC5389"></xref> in addition to the following steps to verify
      that the access token is valid:</t>

      <t><list style="symbols">
          <t>The STUN server selects the keying material based on kid signaled in
          the USERNAME attribute.</t>

          <t>The AEAD decryption operation has four inputs: K, N, A, and C, as
          defined in Section 2.2 of <xref target="RFC5116"></xref>. The AEAD
          decryption algorithm has only a single output, either a plaintext or
          a special symbol FAIL that indicates that the inputs are not
          authentic. If the authenticated decrypt operation returns FAIL, then the
          STUN server rejects the request with an error response 401
          (Unauthorized).</t>

          <t>If AES_CBC_HMAC_SHA2 is used, then the final T_LEN octets are
          stripped from C. It performs the verification of the token message
          integrity by calculating HMAC over the STUN server name, the
          encrypted portion in the self-contained token, and the AL using the AUTH
          key, and if the resulting value does not match the mac field in the
          self-contained token, then it rejects the request with an error
          response 401 (Unauthorized).</t>

          <t>The STUN server obtains the mac_key by retrieving the content of the
          access token (which requires decryption of the self-contained token
          using the AS-RS key).</t>

          <t>The STUN server verifies that no replay took place by performing
          the following check: <list style="symbols">

              <t>The access token is accepted if the timestamp field (TS) in
              the self-contained token is shortly before the reception time
              of the STUN request (RDnew).  The following formula is used:
 <figure>
                  <artwork><![CDATA[
         lifetime + Delta > abs(RDnew - TS)
]]></artwork>
                </figure>The RECOMMENDED value for the allowed Delta is 5
              seconds. If the timestamp is NOT within the boundaries, then the
              STUN server discards the request with error response 401
              (Unauthorized).</t>
            </list></t>

          <t>The STUN server uses the mac_key to compute the message integrity
          over the request, and if the resulting value does not match the
          contents of the MESSAGE-INTEGRITY attribute, then it rejects the
          request with an error response 401 (Unauthorized).</t>

          <t>If all the checks pass, the STUN server continues to process the
          request.</t>

          <t>Any response generated by the server MUST include the
          MESSAGE-INTEGRITY attribute, computed using the mac_key.</t>
        </list></t>

      <t>If a STUN server receives an ACCESS-TOKEN attribute unexpectedly
      (because it had not previously sent out a THIRD-PARTY-AUTHORIZATION), it
      will respond with an error code of 420 (Unknown Attribute) as specified
      in Section 7.3.1 of <xref target="RFC5389"></xref>.</t>
    </section>

    <section anchor="client" title="STUN Client Behavior">
      <t><list style="symbols">
          <t>The client looks for the MESSAGE-INTEGRITY attribute in the
          response. If MESSAGE-INTEGRITY is absent or the value computed for
          message integrity using mac_key does not match the contents of the
          MESSAGE-INTEGRITY attribute, then the response MUST be discarded.</t>

          <t>If the access token expires, then the client MUST obtain a new
          token from the authorization server and use it for new STUN
          requests.</t>
        </list></t>
    </section>

    <section anchor="TURN" title="TURN Client and Server Behavior">
      <t>Changes specific to TURN are listed below:</t>

      <t><list style="symbols">
          <t>The access token can be reused for multiple Allocate requests to
          the same TURN server. The TURN client MUST include the ACCESS-TOKEN
          attribute only in Allocate and Refresh requests. Since the access
          token is valid for a specific period of time, the TURN server can
          cache it so that it can check if the access token in a new
          allocation request matches one of the cached tokens and avoids the
          need to decrypt the token.</t>

          <t>The lifetime provided by the TURN server in the Allocate and
          Refresh responses MUST be less than or equal to the lifetime of the
          token. It is RECOMMENDED that the TURN server calculate the maximum
          allowed lifetime value using the formula:<figure>
              <artwork><![CDATA[     lifetime + Delta - abs(RDnew - TS)
]]></artwork>
            </figure>The RECOMMENDED value for the allowed Delta is 5
          seconds.</t>

          <t>If the access token expires, then the client MUST obtain a new
          token from the authorization server and use it for new allocations.
          The client MUST use the new token to refresh existing allocations.
          This way, the client has to maintain only one token per TURN server.</t>
        </list></t>
    </section>

    <section anchor="op" title="Operational Considerations">
      <t>The following operational considerations should be taken into
      account:</t>

      <t><list style="symbols">
          <t>Each authorization server should maintain the list of STUN
          servers for which it will grant tokens and the long-term secret
          shared with each of those STUN servers.</t>

          <t>If manual configuration (<xref target="Manual"></xref>) is used
          to establish long-term symmetric keys, the necessary information, which
          includes long-term secret (K) and the authenticated encryption algorithm,
          has to be configured on each authorization server and STUN server
          for each kid. The client obtains the session key and HMAC algorithm
          from the authorization server in company with the token.</t>

          <t>When a STUN client sends a request to get access to a particular
          STUN server (S), the authorization server must ensure that it selects
          the appropriate kid and access token depending on server S.</t>
        </list></t>
    </section>

    <section anchor="security" title="Security Considerations">
      <t>When OAuth 2.0 is used, the interaction between the client and the
      authorization server requires Transport Layer Security (TLS) with a
      ciphersuite offering confidentiality protection, and the guidance given
      in <xref target="RFC7525"></xref> must be followed to avoid attacks on
      TLS. The session key MUST NOT be transmitted in clear since this would
      completely destroy the security benefits of the proposed scheme. An
      attacker trying to replay the message with the ACCESS-TOKEN attribute can be
      mitigated by frequent changes of the nonce value as discussed in Section
      10.2 of <xref target="RFC5389"></xref>. The client may know some (but
      not all) of the token fields encrypted with an unknown secret key, and the
      token can be subjected to known-plaintext attacks, but AES is secure
      against this attack.</t>

      <t>An attacker may remove the THIRD-PARTY-AUTHORIZATION STUN attribute
      from the error message forcing the client to pick first-party
      authentication; this attack may be mitigated by opting for TLS
      <xref target="RFC5246"></xref> or Datagram
      Transport Layer Security (DTLS) <xref target="RFC6347"></xref> as a
      transport protocol for STUN, as
      defined in <xref target="RFC5389"></xref>and <xref
      target="RFC7350"></xref>.</t>

      <t>Threat mitigation discussed in Section 5 of <xref
      target="POP-ARCH"></xref> and security
      considerations in <xref target="RFC5389"></xref> are to be taken into
      account.</t>
    </section>

    <section anchor="iana" title="IANA Considerations">

      <t>This document defines the THIRD-PARTY-AUTHORIZATION STUN attribute,
      described in <xref target="attr"></xref>. IANA has allocated the
      comprehension-optional codepoint 0x802E for this attribute.</t>

      <t>This document defines the ACCESS-TOKEN STUN attribute, described in
      <xref target="attr"></xref>. IANA has allocated the
      comprehension-required codepoint 0x001B for this attribute.</t>

      <section title="Well-Known 'stun-key' URI">
        <t>This memo registers the 'stun-key' well-known URI in the Well-Known
        URIs registry as defined by <xref target="RFC5785"></xref>.</t>

        <t>URI suffix: stun-key</t>

        <t>Change controller: IETF</t>

        <t>Specification document(s): This RFC</t>

        <t>Related information: None</t>
      </section>
    </section>
  </middle>

  <back>
    <references title="Normative References">
      <?rfc include="reference.RFC.2119"?>

      <?rfc include="reference.RFC.5389"?>

      <?rfc include="reference.RFC.6749"?>

      <?rfc include="reference.RFC.4648"?>

      <?rfc include="reference.RFC.4868"?>

      <?rfc include="reference.RFC.5116"?>

<!--draft-ietf-jose-json-web-algorithms-40 now RFC 7518-->
      <?rfc include='reference.RFC.7518'?>

    </references>

    <references title="Informative References">

<!-- draft-ietf-rtcweb-overview-14, Active - I-D exists -->
<reference anchor='WEBRTC'>
<front>
<title>Overview: Real Time Protocols for Browser-based Applications</title>
<author initials='H' surname='Alvestrand' fullname='Harald Alvestrand'>
    <organization />
</author>
<date month='June' year='2015' />
</front>
<seriesInfo name='Work in Progress,' value='draft-ietf-rtcweb-overview-14' />
</reference>

<!-- ietf-oauth-pop-architecture, Active - I-D exists -->
     <reference anchor='POP-ARCH'>
<front>
<title>OAuth 2.0 Proof-of-Possession (PoP) Security Architecture</title>
<author initials='P' surname='Hunt' fullname='Phil Hunt'>
    <organization />
</author>
<author initials='J' surname='Richer' fullname='Justin Richer'>
    <organization />
</author>
<author initials='W' surname='Mills' fullname='William Mills'>
    <organization />
</author>
<author initials='P' surname='Mishra' fullname='Prateek Mishra'>
    <organization />
</author>
<author initials='H' surname='Tschofenig' fullname='Hannes Tschofenig'>
    <organization />
</author>
<date month='July' year='2015' />
</front>
<seriesInfo name='Work in Progress,' value='draft-ietf-oauth-pop-architecture-02' />
</reference>

<!-- draft-ietf-oauth-pop-key-distribution-01, Active - I-D exists -->
<reference anchor='POP-KEY-DIST'>
<front>
<title>OAuth 2.0 Proof-of-Possession: Authorization Server to Client Key Distribution</title>
<author initials='J' surname='Bradley' fullname='John Bradley'>
    <organization />
</author>
<author initials='P' surname='Hunt' fullname='Phil Hunt'>
    <organization />
</author>
<author initials='M' surname='Jones' fullname='Michael Jones'>
    <organization />
</author>
<author initials='H' surname='Tschofenig' fullname='Hannes Tschofenig'>
    <organization />
</author>
<date month='March' year='2015' />
</front>
<seriesInfo name='Work in Progress,' value='draft-ietf-oauth-pop-key-distribution-01' />
</reference>


<!-- I-D.ietf-tram-stunbis, Active - I-D exists -->
<reference anchor='STUN'>
<front>
<title>Session Traversal Utilities for NAT (STUN)</title>
<author initials='M' surname='Petit-Huguenin' fullname='Marc Petit-Huguenin'>
    <organization />
</author>
<author initials='G' surname='Salgueiro' fullname='Gonzalo Salgueiro'>
    <organization />
</author>
<author initials='J' surname='Rosenberg' fullname='Jonathan Rosenberg'>
    <organization />
</author>
<author initials='D' surname='Wing' fullname='Dan Wing'>
    <organization />
</author>
<author initials='R' surname='Mahy' fullname='Rohan Mahy'>
    <organization />
</author>
<author initials='P' surname='Matthews' fullname='Philip Matthews'>
    <organization />
</author>
<date month='March' year='2015' />
</front>
<seriesInfo name='Work in Progress,' value='draft-ietf-tram-stunbis-04' />
</reference>

<!-- I-D.ietf-jose-json-web-signature now RFC 7515 -->
      <?rfc include='reference.RFC.7515'?>

<!-- I-D.ietf-jose-json-web-encryption now RFC 7516 -->
      <?rfc include='reference.RFC.7516'?>

<!-- I-D.ietf-jose-json-web-token now RFC 7519 -->
      <?rfc include='reference.RFC.7519'?>

<!-- draft-mcgrew-aead-aes-cbc-hmac-sha2-05, Expired -->
<reference anchor='ENCRYPT'>
<front>
<title>Authenticated Encryption with AES-CBC and HMAC-SHA</title>
<author initials='D' surname='McGrew' fullname='David McGrew'>
    <organization />
</author>
<author initials='J' surname='Foley' fullname='John Foley'>
    <organization />
</author>
<author initials='K' surname='Paterson' fullname='Kenny Paterson'>
    <organization />
</author>
<date month='July' year='2014' />
</front>
<seriesInfo name='Work in Progress,' value='draft-mcgrew-aead-aes-cbc-hmac-sha2-05' />
</reference>

      
      <?rfc include="reference.RFC.5766"?>

      <?rfc include="reference.RFC.6819"?>

      <?rfc include="reference.RFC.7350"?>

      <?rfc include="reference.RFC.5246"?>

      <?rfc include="reference.RFC.6347"?>

      <?rfc include="reference.RFC.7376"?>

      <?rfc include="reference.RFC.7159"?>

      <?rfc include="reference.RFC.7525"?>

      <?rfc include="reference.RFC.5785"?>

    </references>

    <section anchor="sample" title="Sample Tickets">

<t><figure anchor="Ticket" title="Sample Tickets ">
          <artwork align="left"><![CDATA[Input data (same for all samples below):

   //STUN SERVER NAME
   server_name = "blackdow.carleon.gov";

   //Shared key between AS and RS

   long_term_key = \x48\x47\x6b\x6a\x33\x32\x4b\x4a\x47\x69\x75\x79
                   \x30\x39\x38\x73\x64\x66\x61\x71\x62\x4e\x6a\x4f
                   \x69\x61\x7a\x37\x31\x39\x32\x33

   //MAC key of the session (included in the token)
   mac_key = \x5a\x6b\x73\x6a\x70\x77\x65\x6f\x69\x78\x58\x6d\x76\x6e
             \x36\x37\x35\x33\x34\x6d;

   //length of the MAC key
   mac_key_length  =  20;

   //The timestamp field in the token
   token_timestamp = 92470300704768;

   //The lifetime of the token
   token_lifetime = 3600;

   //nonce for AEAD
   aead_nonce = \x68\x34\x6a\x33\x6b\x32\x6c\x32\x6e\x34\x62\x35;

   Samples:

   1) token encryption algorithm = AEAD_AES_256_GCM

      Encrypted token (64 bytes = 2 + 12 + 34 + 16) =

    \x00\x0c\x68\x34\x6a\x33\x6b\x32\x6c\x32\x6e\x34\x62
    \x35\x61\x7e\xf1\x34\xa3\xd5\xe4\x4e\x9a\x19\xcc\x7d
    \xc1\x04\xb0\xc0\x3d\x03\xb2\xa5\x51\xd8\xfd\xf5\xcd
    \x3b\x6d\xca\x6f\x10\xcf\xb7\x7e\x5b\x2d\xde\xc8\x4d
    \x29\x3a\x5c\x50\x49\x93\x59\xf0\xc2\xe2\x6f\x76

   2) token encryption algorithm = AEAD_AES_128_GCM

      Encrypted token (64 bytes = 2 + 12 + 34 + 16) =

   \x00\x0c\x68\x34\x6a\x33\x6b\x32\x6c\x32\x6e\x34\x62
   \x35\x7f\xb9\xe9\x9f\x08\x27\xbe\x3d\xf1\xe1\xbd\x65
   \x14\x93\xd3\x03\x1d\x36\xdf\x57\x07\x97\x84\xae\xe5
   \xea\xcb\x65\xfa\xd4\xf2\x7f\xab\x1a\x3f\x97\x97\x4b
   \x69\xf8\x51\xb2\x4b\xf5\xaf\x09\xed\xa3\x57\xe0


Note: 
[1] After EVP_EncryptFinal_ex encrypts the final data, 
    EVP_CIPHER_CTX_ctrl must be called to append 
    the authentication tag to the ciphertext.
    //EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, taglen, tag);

[2] EVP_CIPHER_CTX_ctrl must be invoked to set the 
    authentication tag before calling EVP_DecryptFinal.
    //EVP_CIPHER_CTX_ctrl (&ctx, EVP_CTRL_GCM_SET_TAG, taglen, tag);
    ]]></artwork>
        </figure></t>
    </section>

    <section anchor="Interaction"
             title="Interaction between the Client and Authorization Server">
      <t>The client makes an HTTP request to an authorization server to obtain a
      token that can be used to avail itself of STUN services. The STUN token
      is returned in JSON syntax <xref target="RFC7159"></xref>, along with
      other OAuth 2.0 parameters like token type, key, token lifetime, and kid
      as defined in <xref
      target="POP-KEY-DIST"></xref>.</t>

      <figure anchor="figure1" title="STUN Third-Party Authorization">
        <artwork><![CDATA[

+-------------------+                         +--------+  +---------+  
| .........  STUN   |                         |  STUN  |  |  WebRTC |
| .WebRTC .  client |                         |        |  |         | 
| .client .         |                         | server |  |  server |
| .........         |                         |        |  |         | 
+-------------------+                         +--------+  +---------+
  |       |           STUN request                    |         |
  |       |------------------------------------------>|         |
  |       |                                           |         |
  |       |         STUN error response               |         |
  |       |         (401 Unauthorized)                |         |
  |       |<------------------------------------------|         |
  |       |         THIRD-PARTY-AUTHORIZATION         |         |  
  |       |                                           |         |                                      
  |       |                                           |         | 
  |       |      HTTP request for token               |         |
  |------------------------------------------------------------>|
  |       |      HTTP response with token parameters  |         |
  |<------------------------------------------------------------|
  |OAuth 2.0                                          |         |
   attributes                                         |         |
  |------>|                                           |         |
  |       |    STUN request with ACCESS-TOKEN         |         |
  |       |------------------------------------------>|         |
  |       |                                           |         |
  |       |         STUN success response             |         |
  |       |<------------------------------------------|         |
  |       |             STUN messages                 |         |
  |       |      ////// integrity protected //////    |         |
  |       |      ////// integrity protected //////    |         |
  |       |      ////// integrity protected //////    |         |
       ]]></artwork>
      </figure>

      <t></t>

      <t><xref target="POP-KEY-DIST"></xref> describes
      the interaction between the client and the authorization server. For
      example, the client learns the STUN server name
      &ldquo;stun1@example.com&rdquo; from the THIRD-PARTY-AUTHORIZATION attribute
      value and makes the following HTTP request for the access token using
      TLS (with extra line breaks for display purposes only):</t>

      <t><figure anchor="Example1" title="Request">
          <artwork align="left"><![CDATA[     HTTP/1.1 
     Host: server.example.com
     Content-Type: application/x-www-form-urlencoded
     aud=stun1@example.com
     timestamp=1361471629
     grant_type=implicit
     token_type=pop
     alg=HMAC-SHA-256-128  
              ]]></artwork>
        </figure></t>

      <t><xref target="STUN"></xref> supports hash agility
      and accomplishes this agility by computing message integrity using both
      HMAC-SHA-1 and HMAC&nbhy;SHA&nbhy;256&nbhy;128. The client signals the algorithm
      supported by it to the authorization server in the 'alg' parameter
      defined in <xref target="POP-KEY-DIST"></xref>.
      The authorization server determines the length of the mac_key based on the
      HMAC algorithm conveyed by the client. If the client supports both
      HMAC-SHA-1 and HMAC-SHA-256-128, then it signals HMAC-SHA-256-128 to the
      authorization server, gets a 256-bit key from the authorization server, and
      calculates a 160-bit key for HMAC-SHA-1 using SHA1 and taking the 256-bit key
      as input.</t>

      <t>If the client is authorized, then the authorization server issues an
      access token. An example of a successful response:</t>

      <figure anchor="Example2" title="Response">
        <preamble></preamble>

        <artwork align="left"><![CDATA[
     HTTP/1.1 200 OK
     Content-Type: application/json
     Cache-Control: no-store

     {
       "access_token":
"U2FsdGVkX18qJK/kkWmRcnfHglrVTJSpS6yU32kmHmOrfGyI3m1gQj1jRPsr0uBb
HctuycAgsfRX7nJW2BdukGyKMXSiNGNnBzigkAofP6+Z3vkJ1Q5pWbfSRroOkWBn",
       "token_type":"pop",
       "expires_in":1800,
       "kid":"22BIjxU93h/IgwEb",
       "key":"v51N62OM65kyMvfTI08O"
       "alg":HMAC-SHA-256-128
     }
              ]]></artwork>
      </figure>
    </section>
 <section anchor="ack" title="Acknowledgements" numbered='no'>
      <t>The authors would like to thank Dan Wing, Pal Martinsen, Oleg Moskalenko,
      Charles Eckel, Spencer Dawkins, Hannes Tschofenig, Yaron Sheffer, Tom
      Taylor, Christer Holmberg, Pete Resnick, Kathleen Moriarty, Richard
      Barnes, Stephen Farrell, Alissa Cooper, and Rich Salz for comments and
      review. The authors would like to give special thanks to Brandon
      Williams for his help.</t>

      <t>Thanks to Oleg Moskalenko for providing token samples in <xref target="sample"/>.</t>
    </section>
  </back>
</rfc>
