CoRE Working Group                                           G. Selander
Internet-Draft                                               J. Mattsson
Intended status: Standards Track                            F. Palombini
Expires: June 22, September 14, 2017                                  Ericsson AB
                                                                L. Seitz
                                                        SICS Swedish ICT
                                                       December 19, 2016
                                                          March 13, 2017

                    Object Security of CoAP (OSCOAP)
                   draft-ietf-core-object-security-01
                   draft-ietf-core-object-security-02

Abstract

   This memo document defines Object Security of CoAP (OSCOAP), a method for
   application layer protection of message exchanges with the Constrained Application Protocol
   (CoAP), using the CBOR Object Signing and Encryption (COSE) format. (COSE).  OSCOAP
   provides end-to-end encryption, integrity and replay protection to
   CoAP payload, options, and header fields, as well as a secure binding between CoAP request message
   binding.  OSCOAP is designed for constrained nodes and response messages. networks and
   can be used across intermediaries and over any layer.  The use of
   OSCOAP is signaled with the CoAP option Object-Security, also defined
   in this memo. document.

Status of This Memo

   This Internet-Draft is submitted in full conformance with the
   provisions of BCP 78 and BCP 79.

   Internet-Drafts are working documents of the Internet Engineering
   Task Force (IETF).  Note that other groups may also distribute
   working documents as Internet-Drafts.  The list of current Internet-
   Drafts is at http://datatracker.ietf.org/drafts/current/.

   Internet-Drafts are draft documents valid for a maximum of six months
   and may be updated, replaced, or obsoleted by other documents at any
   time.  It is inappropriate to use Internet-Drafts as reference
   material or to cite them other than as "work in progress."

   This Internet-Draft will expire on June 22, September 14, 2017.

Copyright Notice

   Copyright (c) 2016 2017 IETF Trust and the persons identified as the
   document authors.  All rights reserved.

   This document is subject to BCP 78 and the IETF Trust's Legal
   Provisions Relating to IETF Documents
   (http://trustee.ietf.org/license-info) in effect on the date of
   publication of this document.  Please review these documents
   carefully, as they describe your rights and restrictions with respect
   to this document.  Code Components extracted from this document must
   include Simplified BSD License text as described in Section 4.e of
   the Trust Legal Provisions and are provided without warranty as
   described in the Simplified BSD License.

Table of Contents

   1.  Introduction  . . . . . . . . . . . . . . . . . . . . . . . .   3
     1.1.  Terminology . . . . . . . . . . . . . . . . . . . . . . .   4
   2.  The Object-Security Option  . . . . . . . . . . . . . . . . .   5
   3.  The Security Context  . . . . . . . . . . . . . . . . . . . .   6
     3.1.  Security Context Definition . . . . . . . . . . . . . . .   6
     3.2.  Derivation of Security Context Parameters . . . . . . . .   8
       3.2.1.  Derivation of Sender Key/IV, Recipient Key/IV
     3.3.  Requirements on the Security Context Parameters . . . .  10
       3.2.2.  Context Identifier .  10
   4.  Protected CoAP Message Fields . . . . . . . . . . . . . . . .  11
       3.2.3.  Sender ID and Recipient ID
     4.1.  CoAP Payload  . . . . . . . . . . . . .  11
       3.2.4.  Sequence Numbers and Replay Window . . . . . . . . .  11
   4.  Protected
     4.2.  CoAP Message Fields Header . . . . . . . . . . . . . . . .  11
     4.1. . . . . . . .  12
     4.3.  CoAP Payload Options  . . . . . . . . . . . . . . . . . . . . . .  12
     4.2.  CoAP Header .
   5.  The COSE Object . . . . . . . . . . . . . . . . . . . . . .  12
     4.3.  CoAP Options .  17
     5.1.  Plaintext . . . . . . . . . . . . . . . . . . . . .  13
       4.3.1.  Class E Options . . .  18
     5.2.  Additional Authenticated Data . . . . . . . . . . . . . .  19
   6.  Sequence Numbers, Replay, Message Binding, and Freshness  . .  15
       4.3.2.  Class A Options  20
     6.1.  AEAD Nonce Uniqueness . . . . . . . . . . . . . . . . . .  20
     6.2.  Replay Protection .  17
   5.  The COSE Object . . . . . . . . . . . . . . . . . . .  20
     6.3.  Sequence Number and Replay Window State . . . .  17
     5.1.  Plaintext . . . . .  20
     6.4.  Freshness . . . . . . . . . . . . . . . . . . .  19
     5.2.  Additional Authenticated Data . . . . .  21
     6.5.  Delay and Mismatch Attacks  . . . . . . . . .  19
   6.  Protecting CoAP Messages . . . . . .  21
   7.  Processing  . . . . . . . . . . . .  21
     6.1.  Replay and Freshness Protection . . . . . . . . . . . . .  21
     6.2.  22
     7.1.  Protecting the Request  . . . . . . . . . . . . . . . . .  22
     6.3.
     7.2.  Verifying the Request . . . . . . . . . . . . . . . . . .  23
     6.4.  22
     7.3.  Protecting the Response . . . . . . . . . . . . . . . . .  24
     6.5.  23
     7.4.  Verifying the Response  . . . . . . . . . . . . . . . . .  25
   7.  Security Considerations  23
   8.  Web Linking . . . . . . . . . . . . . . . . . . .  26
   8.  Privacy . . . . . .  24
   9.  Security Considerations . . . . . . . . . . . . . . . . . . .  28
   9.  IANA  25
   10. Privacy Considerations  . . . . . . . . . . . . . . . . . . .  27
   11. IANA Considerations . .  28
     9.1.  CoAP Option Numbers Registry . . . . . . . . . . . . . .  28
     9.2.  COSE Header Parameters . . . . .  27
     11.1.  CoAP Option Numbers Registry . . . . . . . . . . . . .  29
     9.3. .  27
     11.2.  Media Type Registrations . . . . . . . . . . . . . . . .  29
     9.4.  27
     11.3.  CoAP Content Format Registration . . . . . . . . . . . .  30
   10.  28
   12. Acknowledgments . . . . . . . . . . . . . . . . . . . . . . .  31
   11.  29
   13. References  . . . . . . . . . . . . . . . . . . . . . . . . .  31
     11.1.  29
     13.1.  Normative References . . . . . . . . . . . . . . . . . .  31
     11.2.  29
     13.2.  Informative References . . . . . . . . . . . . . . . . .  32  30
   Appendix A.  Overhead  OSCOAP Compression . . . . . . . . . . . . . . . . . . . . . .  33
     A.1.  Length of the Object-Security Option  . . . . . . . . . .  33
     A.2.  Size of the COSE Object . . . . . . . . . . . . . . . . .  33
     A.3.  Message Expansion .  31
     A.1.  Examples  . . . . . . . . . . . . . . . . . . .  34
     A.4.  Example . . . . .  32

   Appendix B.  Test Vectors . . . . . . . . . . . . . . . . . . . .  35  33
   Appendix B. C.  Examples . . . . . . . . . . . . . . . . . . . . . .  36
     B.1.  33
     C.1.  Secure Access to Sensor . . . . . . . . . . . . . . . . .  36
     B.2.  33
     C.2.  Secure Subscribe to Sensor  . . . . . . . . . . . . . . .  38  34
   Appendix C. D.  Object Security of Content (OSCON) . . . . . . . . .  39
     C.1.  36
     D.1.  Overhead OSCON  . . . . . . . . . . . . . . . . . . . . .  40
     C.2.  37
     D.2.  MAC Only  . . . . . . . . . . . . . . . . . . . . . . . .  41
     C.3.  38
     D.3.  Signature Only  . . . . . . . . . . . . . . . . . . . . .  42
     C.4.  38
     D.4.  Authenticated Encryption with Additional Data (AEAD)  . .  43
     C.5.  39
     D.5.  Symmetric Encryption with Asymmetric Signature (SEAS) . .  43  40
   Authors' Addresses  . . . . . . . . . . . . . . . . . . . . . . .  44  40

1.  Introduction

   The Constrained Application Protocol (CoAP) [RFC7252] is a web application
   protocol, designed for constrained nodes and networks [RFC7228].
   CoAP specifies the use of proxies for scalability and efficiency.  At
   the same time CoAP [RFC7252] references DTLS [RFC6347] for security.
   Proxy operations on CoAP messages require DTLS to be terminated at
   the proxy.  The proxy therefore not only has access to the data
   required for performing the intended proxy functionality, but is also
   able to eavesdrop on, or manipulate any part of the CoAP payload and
   metadata, in transit between client and server.  The proxy can also
   inject, delete, or reorder packages without being protected or
   detected by DTLS.

   This memo document defines Object Security of CoAP (OSCOAP), a data object
   based security protocol, protecting CoAP message exchanges end-to-
   end, across intermediary nodes.  An analysis of end-to-end security
   for CoAP messages through intermediary nodes is performed in
   [I-D.hartke-core-e2e-security-reqs], this specification addresses the
   forwarding case.

   The solution  In addition to the core features defined in
   [RFC7252], OSCOAP supports Observe [RFC7641] and Blockwise [RFC7959].

   OSCOAP is designed for constrained nodes and networks and provides an
   in-layer security protocol for CoAP which does not depend on
   underlying layers and is therefore favorable for
   providing security for "CoAP over foo", e.g. layers.  OSCOAP can be used anywhere that CoAP messages passing
   over both can be
   used, including unreliable and transport [RFC7228], reliable transport
   [I-D.ietf-core-coap-tcp-tls], CoAP over IEEE 802.15.4 IE and non-IP transport
   [I-D.bormann-6lo-coap-802-15-ie].  OSCOAP may also be used to protect
   group communication for CoAP [I-D.tiloca-core-multicast-oscoap].  The
   use of OSCOAP does not affect the URI scheme and OSCOAP can therefore
   be used with any URI scheme defined for CoAP.  The application
   decides the conditions for which OSCOAP is required.

   OSCOAP builds on CBOR Object Signing and Encryption (COSE)
   [I-D.ietf-cose-msg], providing end-to-end encryption, integrity, and
   replay protection. protection, and secure message binding.  The use of OSCOAP is
   signaled with the CoAP option Object-Security, also defined in this memo. Section 2.
   OSCOAP provides protection of CoAP payload, certain options, and
   header fields.  The solution transforms an unprotected CoAP message
   into a protected CoAP message in the following way: the unprotected
   CoAP message is protected by including payload (if present), certain
   options, and header fields in a COSE object.  The message fields that
   have been encrypted are removed from the message whereas the Object-Security Object-
   Security option and the COSE object are added.  We call the result the "protected" CoAP
   message.  Thus OSCOAP is a security protocol based on the exchange of
   protected CoAP messages (see added, see Figure 1). 1.

          Client                                           Server
             |  request:                                     |
             |    GET example.com                            |
             |    [Header, Token, Options:{...,              |
             |     Object-Security:COSE object}]             |
             +---------------------------------------------->|
             |  response:                                    |
             |    2.05 (Content)                             |
             |    [Header, Token, Options:{...,              |
             |     Object-Security:-}, Payload:COSE object]  |
             |<----------------------------------------------+
             |                                               |

                        Figure 1: Sketch of OSCOAP

   OSCOAP provides protection may be used in extremely constrained settings, where CoAP over
   DTLS may be prohibitive e.g. due to large code size.  Alternatively,
   OSCOAP can be combined with DTLS, thereby enabling end-to-end
   security of e.g.  CoAP payload, certain options, and
   header fields, as well as a secure binding between CoAP request payload and
   response messages.  OSCOAP provides replay protection, but like DTLS,
   OSCOAP only provides relative freshness in the sense that the
   sequence numbers allows a recipient to determine the relative order
   of messages.  For applications having stronger demands on freshness
   (e.g. control of actuators), OSCOAP needs to be augmented with
   mechanisms providing absolute freshness
   [I-D.mattsson-core-coap-actuators].

   OSCOAP may be used in extremely constrained settings, where DTLS
   cannot be supported.  Alternatively, OSCOAP can be combined with
   DTLS, thereby enabling end-to-end security of CoAP payload, options, in combination with hop-by-hop hop-
   by-hop protection of the entire CoAP message, during transport
   between end-point and intermediary node.  Examples of the use of
   OSCOAP are given in Appendix B. C.

   The message protection provided by OSCOAP can alternatively be
   applied only to the payload of individual messages.  We call this
   object security of content (OSCON) and it is defined in Appendix C. D.

1.1.  Terminology

   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 [RFC2119].  These
   words may also appear in this document in lowercase, absent their
   normative meanings.

   Readers are expected to be familiar with the terms and concepts
   described in [RFC7252] and [RFC7641].  Readers are also expected to
   be familiar with [RFC7049] CoAP [RFC7252], Observe [RFC7641], Blockwise [RFC7959],
   COSE [I-D.ietf-cose-msg], CBOR [RFC7049], CDDL

   [I-D.greevenbosch-appsawg-cbor-cddl], and understand
   [I-D.greevenbosch-appsawg-cbor-cddl].  Terminology for constrained
   environments, such as "constrained device", "constrained-node
   network", is defined in environments
   [RFC7228].

2.  The Object-Security Option

   The Object-Security option (see Figure 2) indicates that OSCOAP is
   used to protect the CoAP message exchange.  The protection is achieved by means of a
   COSE object included in the protected CoAP message, as detailed in
   Section 5.

   The Object-Security
   option is critical, safe to forward, part of the cache key, and not repeatable.
   repeatable, and opaque.

        +-----+---+---+---+---+-----------------+--------+--------+
        | No. | C | U | N | R | Name            | Format | Length |
        +-----+---+---+---+---+-----------------+--------+--------|
        | TBD | x |   |   |   | Object-Security | opaque | 0-     |
        +-----+---+---+---+---+-----------------+--------+--------+
             C=Critical, U=Unsafe, N=NoCacheKey, R=Repeatable

                   Figure 2 illustrates 2: The Object-Security Option

   A successful response to a request with the structure of Object-Security option
   SHALL contain the Object-Security option.  A CoAP proxy endpoint SHOULD NOT
   cache a response to a request with an Object-
   Security Object-Security option, since
   the response is only applicable to the original client's request.
   The Object-Security option is included in the cache key for backward
   compatibility with proxies not recognizing the Object-Security
   option.  The effect of this is that messages with the Object-Security option
   will never generate cache hits.  To
   further prevent caching, a  For Max-Age option with value zero SHOULD be
   added to processing, see
   Section 4.3.1.1.

   The protection is achieved by means of a COSE object (see Section 5)
   included in the protected CoAP responses.

        +-----+---+---+---+---+-----------------+--------+--------+
        | No. | C | U | N | R | Name            | Format | Length |
        +-----+---+---+---+---+-----------------+--------+--------|
        | TBD | x |   |   |   | Object-Security | opaque | 0-     |
        +-----+---+---+---+---+-----------------+--------+--------+
             C=Critical, U=Unsafe, N=NoCacheKey, R=Repeatable

                   Figure 2: The Object-Security Option message.  The length placement of the Object-Security option COSE
   object depends on whether the
   unprotected message method/response code allows payload, on the set of options that are
   included in the unprotected message, the length of the integrity tag,
   and the length of the information identifying the security context. payload
   (see [RFC7252]):

   o  If the unprotected message method/response code allows payload, then the compressed
      COSE object is the payload of the protected message (see Section 6.2 and
      Section 6.4), message, and the
      Object-Security option has length zero.  An endpoint receiving a
      CoAP message with payload, that also contains a non-empty Object-Security Object-
      Security option SHALL treat it as malformed and reject it.

   o  If the unprotected message method/response code does not allow payload, then the
      compressed COSE object is the value of the Object-Security option
      and the length of the Object-Security option is equal to the size
      of the compressed COSE object.  An endpoint receiving a CoAP
      message without payload, that also contains an empty Object-Security Object-
      Security option SHALL treat it as malformed and reject it.

   Note that according to [RFC7252], new Methods and Response Codes
   should specify

   The size of the COSE object depends on whether the method/response
   code allows payload, if the payload message is optional, required a request or not allowed
   (Section 12.1.2) in response, on the message, and
   set of options that are included in case this is not defined the
   sender must not include a payload (Section 5.5).  Thus, in this case, unprotected message, the COSE object MUST be AEAD
   algorithm, the value length of the Object-Security option.

   More details about information identifying the message overhead caused by security
   context, and the Object-Security
   option are given in Appendix A. length of the sequence number.

3.  The Security Context

   OSCOAP uses COSE with an Authenticated Encryption with Additional
   Data (AEAD) algorithm. algorithm between a CoAP client and a CoAP server.  An
   implementation supporting this specification MAY only implement the
   client part or MAY only the server part.

   The specification requires that client and server establish a
   security context to apply to the COSE objects protecting the CoAP
   messages.  In this section we define the security context, and also
   specify how to derive the initial security contexts in client and
   server based on common shared secret and a key derivation function
   (KDF).

3.1.  Security Context Definition

   The security context is the set of information elements necessary to
   carry out the cryptographic operations in OSCOAP.  Each security
   context is identified by a Context Identifier.  A Context Identifier
   that is no longer in use can be reassigned to a new security context.  For each endpoint,
   the security context is composed by of a "Common Context", a "Sender Context"
   Context", and a "Recipient Context".

   The endpoints protect messages to send using the Sender Context and
   verify messages received using the Recipient Context, both contexts
   being derived from the Common Context and other data.  Each  Clients need
   to be able to retrieve the correct security context to use.

   An endpoint
   has a unique uses its Sender ID used (SID) to derive its Sender Context, this identifier is
   called "Sender ID".  The Recipient Context is derived with
   and the other
   endpoint's endpoint uses the same ID, which is now called "Recipient ID".  The Recipient ID is
   thus the ID of the endpoint from which a CoAP message is received.
   (RID), to derive its Recipient Context.  In communication between two
   endpoints, the Sender Context of one endpoint matches the Recipient
   Context of the other endpoint, and vice versa.  Thus the two security
   contexts identified by the same
   Context Identifiers IDs in the two endpoints are not the
   same, but they are partly mirrored.  Retrieval and use of the
   security context are shown in Figure 3."

                  .-Cid = Cid1-.           .-Cid = Cid1-. 3.

                  .------------.           .------------.
                  |  Common,   |           |  Common,   |
                  |  Sender,   |           |  Recipient,|
                  |  Recipient |           |  Sender    |
                  '------------'           '------------'
                      Client                   Server
                         |                       |
   Retrieve context for  | request:              |
    target resource      | [Token = Token1,      |
   Protect request with  |  Cid  kid = Cid1, SID, ...]      |
     Sender Context      +---------------------->| Retrieve context with
                         |                       |  Cid  RID = Cid1 SID
                         |                       | Verify request with
                         |                       |  Recipient Context
                         | response:             | Protect response with
                         | [Token = Token1, ...] |  Sender Context
   Retrieve context with |<----------------------+
    Token = Token1       |                       |
   Verify request with   |                       |
    Recipient Context    |                       |

            Figure 3: Retrieval and use of the Security Context

   The Common Context contains the following parameters:

   o  Context Identifier (Cid).  Variable length byte string that
      identifies the security context.  Its value is immutable once the
      security context is established.

   o  Algorithm (Alg).  Value that identifies the COSE AEAD algorithm to
      use for encryption.  Its value is immutable once the security
      context is established.

   o  Base Key (master_secret).  Master Secret.  Variable length, uniformly random byte string
      containing the key used to derive traffic keys and IVs.  Its value
      is immutable once the security context is established.

   o  Master Salt (OPTIONAL).  Variable length byte string containing
      the salt used to derive traffic keys and IVs.  Its value is
      immutable once the security context is established.

   The Sender Context contains the following parameters:

   o  Sender ID.  Variable length byte string identifying the endpoint
      itself. Sender
      Context.  Its value is immutable once the security context is
      established.

   o  Sender Key. Byte string containing the symmetric key to protect
      messages to send.  Derived from Common Context and Sender ID.
      Length is determined by Algorithm.  Its value is immutable once
      the security context is established.

   o  Sender IV.  Byte string containing the fixed context IV
      [I-D.ietf-cose-msg]) to protect messages to
      send.  Derived from Common Context and Sender ID.  Length is
      determined by Algorithm.  Its value is immutable once the security
      context is established.

   o  Sender  Sequence Number.  Non-negative integer enumerating the COSE
      objects that the endpoint sends using the context. used to protect requests
      and observe responses to send.  Used as partial IV
      [I-D.ietf-cose-msg] to generate unique nonces for the AEAD.
      Maximum value is determined by Algorithm.

   The Recipient Context contains the following parameters:

   o  Recipient ID.  Variable length byte string identifying the
      endpoint messages are received from.
      Recipient Context.  Its value is immutable once the security
      context is established.

   o  Recipient Key. Byte string containing the symmetric key to verify
      messages received.  Derived from Common Context and Recipient ID.
      Length is determined by the Algorithm.  Its value is immutable
      once the security context is established.

   o  Recipient IV.  Byte string containing the context IV to verify messages
      received.  Derived from Common Context and Recipient ID.  Length
      is determined by Algorithm.  Its value is immutable once the
      security context is established.

   o  Recipient  Replay Window.  The replay protection window for
      messages to verify requests and observe
      responses received.

   The 3-tuple (Cid,

   An endpoint may free up memory by not storing the Sender ID, Partial IV) is called Transaction
   Identifier (Tid), Key, Sender
   IV, Recipient Key, and SHALL be unique for each Base Key. The Tid is
   used as a unique challenge in Recipient IV, deriving them from the COSE object of Common
   Context when needed.  Alternatively, an endpoint may free up memory
   by not storing the protected CoAP
   request. Master Secret and Master Salt after the other
   parameters have been derived.

   The Tid is part of endpoints MAY interchange the Additional Authenticated Data (AAD,
   see Section 5) of client and server roles while
   maintaining the protected CoAP response message, which is how
   responses are bound to requests.

3.2.  Derivation of Security Context Parameters

   This section describes how to derive the initial parameters in the
   security context, given a small set of input parameters.  We also
   give indications on how applications should select the input
   parameters.

   The following input parameters SHALL be pre-established:

   o  Context Identifier (Cid)
   o  Base Key (master_secret)

   o  AEAD Algorithm (Alg)

      *  Default is AES-CCM-64-64-128 (value 12)

   The following input parameters MAY be pre-established:

   o  Sender ID

      *  Defaults are 0x00 for the endpoint intially being client, and
         0x01 for the endpoint initially being server

   o  Recipient ID

      *  Defaults are 0x01 for the endpoint intially being client, and
         0x00 for the endpoint initially being server

   o  Key Derivation Function (KDF)

      *  Default is HKDF SHA-256

   o  Replay Window Size

      *  Default is 64

   The endpoints MAY interchange the CoAP client and server roles while
   maintaining the same security context.  When this happens, the former
   server still protects the message same security context.  When this happens, the former
   server still protects messages to send using the its Sender Context, and
   verifies the message messages received using its Recipient Context.  The same is
   also true for the former client.  The endpoints MUST NOT change the
   Sender/Recipient ID.  In other words, changing the roles does not
   change the set of keys to be used.

3.2.  Derivation of Security Context Parameters

   The input parameters are included unchanged in the security context.
   From the context are derived from a small set
   of input parameters, the parameters.  The following input parameters are derived: SHALL be pre-
   established:

   o  Master Secret

   o  Sender Key, Sender IV, Sender Sequence Number ID

   o  Recipient Key, Recipient IV, Recipient Sequence Number ID

   The following input parameters MAY be pre-established.  In case any
   of these parameters is not pre-established, the default value
   indicated below is used:

   o  AEAD Algorithm (Alg)

      *  Default is AES-CCM-64-64-128 (value 12)

   o  Master Salt

      *  Default is the empty string

   o  Key Derivation Function (KDF)

      *  Default is HKDF SHA-256

   o  Replay Window Type and Size

      *  Default is DTLS-type replay protection with a window size of 32

   How the input parameters are pre-established, is application
   specific.  The EDHOC protocol [I-D.selander-ace-cose-ecdhe] enables
   the establishment of input parameters with the property of forward
   secrecy,
   secrecy and negotiation of KDF and AEAD, it thus provides all
   necessary pre-requisite steps for using OSCOAP as defined here.

3.2.1.  Derivation of Sender Key/IV, Recipient Key/IV

   Given the input parameters, the client and server can derive all the
   other parameters in the security context.  The derivation procedure
   described here MUST NOT be executed more than once using the same
   master_secret and Cid. The same master_secret SHOULD NOT be used with
   more than one Cid.

   The KDF MUST be one of the HKDF [RFC5869] algorithms defined in COSE.
   The KDF
   HKDF SHA-256 is mandatory to implement.  The security context
   parameters Sender Key/IV, Key/IV and Recipient Key/IV SHALL be derived from
   the input parameters using the HKDF, and which consists of the
   composition of the HKDF-Extract and HKDF-
   Expand HKDF-Expand steps ({{RFC5869}): ([RFC5869]):

      output parameter = HKDF(master_secret, salt, HKDF(salt, IKM, info, output_length), L)

   where:

   o  master_secret  salt is the Master Salt as defined above

   o  salt  IKM is a string of zeros of the length of the hash function
      output in octets Master Secret is defined above
   o  info is a serialized CBOR array consisting of:

      info = [
          cid : bstr,
          id : bstr,
          alg : int,
          out_type
          type : tstr,
          out_len
          L : uint int
      ]

      -

      * id is the Sender ID or Recipient ID

      - out_type

      * type is "Key" or "IV"

      - out_len

   o  L is the key/IV size of the AEAD algorithm

   o  output_length is the size of the AEAD key/IV in bytes encoded as
      an 8-bit unsigned integer octets without
      leading zeroes.

   For example, if the algorithm AES-CCM-64-64-128 (see Section 10.2 in
   [I-D.ietf-cose-msg]) is used, output_length for the keys value for L is 128 bits 16 for keys and output_length 7
   for the IVs is 56 bits. IVs.

3.2.2.  Context Identifier

   As mentioned, Cid is pre-established.  How this  Initial Sequence Numbers and Replay Window

   The Sequence Number is done initialized to 0.  The supported types of
   replay protection and replay window length is application specific, but it is RECOMMENDED that specific
   and depends on the application uses
   64-bits long pseudo-random Cids, lower layers.  Default is DTLS-type replay
   protection with a window size of 32 initiated as described in order to have globally unique
   Section 4.1.2.6 of [RFC6347].

3.3.  Requirements on the Security Context Identifiers.  Cid SHOULD Parameters

   As collisions may lead to the loss of both confidentiality and
   integrity, Sender ID SHALL be unique in the sets set of all security
   contexts used by all the endpoints.  If it is not the case,
   it is the role of the application to specify how to handle
   collisions.

   If using the application has total control of both clients and servers,
   shorter unique Cids MAY same Master Secret.  Normally (e.g. when using
   EDHOC) Sender IDs can be used. very short.  Note that Cids Sender IDs of
   different lengths can be used by different clients and that e.g. a Cid with the same Master Secret.  E.g. the
   SID with value 0x00 is different from the Cid SID with the value 0x0000.

   In the same phase during which the Cid is established in the
   endpoint, the application informs the endpoint what resources can be
   accessed using the corresponding security contexts.  Resources that
   are accessed with OSCOAP are called "protected" resources.  The set
   of resources that can be accessed using a certain security context is
   decided by the application (resource, host, etc.).  The client SHALL
   save the association resource-Cid, in order to be able to retrieve
   the correct security context to access a protected resource.  The
   server SHALL save the association resource-Cid, in order to determine
   whether a particular resource may be accessed using a certain Cid.

3.2.3.  Sender ID and Recipient ID

   The
   If Sender ID and Recipient ID SHALL uniqueness cannot be unique in the set of all
   endpoints using the same security context.  Collisions may lead to
   the loss of both confidentiality and integrity.  If guaranteed, random Sender IDs MUST
   be used.  Random Sender IDs are
   used, they MUST be long enough so that the
   probability of collisions is negligible.

3.2.4.  Sequence Numbers and Replay Window

   The Sender Sequence Number is initialized to 0.  The

   To enable retrieval of the right Recipient Replay
   Window is initiated as described Context, the Recipient ID
   SHOULD be unique in Section 4.1.2.6 the sets of [RFC6347]. all Recipient Contexts used by an
   endpoint.

   The same Master Salt MAY be used with several Master Secrets.

4.  Protected CoAP Message Fields

   OSCOAP transforms an unprotected CoAP message into a protected CoAP
   message, and vice versa.  This section defines how the unprotected CoAP message
   fields are protected.  OSCOAP protects as much of the unprotected
   CoAP message as possible, while still allowing forward proxy
   operations [I-D.hartke-core-e2e-security-reqs].  Message fields may
   either be

   o  Class E: encrypted and integrity protected,

   o  Class I: integrity protected only, or

   o  Class U: unprotected.

   This section also outlines how the message fields are processed and transferred, a
   detailed description of the processing is provided in Section 6. 7.
   Message fields of the unprotected CoAP message are either transferred
   in the header/options part of the protected CoAP message, or in the
   plaintext of the COSE object.  Depending on which, the location of
   the message field in the protected CoAP message is called "outer" "inner" or
   "inner":
   "outer":

   o  Inner message field = field: message field included in the plaintext of
      the COSE object of the protected CoAP message (see Section 5.1)

   o  Outer message field = field: message field included in the header or
      options part of the protected CoAP message

   The inner message fields are by definition encrypted and integrity
   protected by the COSE object. object (Class E).  The outer message fields are sent in plain text
   not encrypted and thus visible to an intermediary, but may be
   integrity protected by including the message field values in the AAD
   of the COSE object (see Section 5.2).  I.e. outer message fields may
   be Class I or Class U.

   Note that, even though the message formats are slightly different,
   OSCOAP complies with CoAP over unreliable transport [RFC7252] as well
   as CoAP over reliable transport [I-D.ietf-core-coap-tcp-tls].

4.1.  CoAP Payload

   The CoAP Payload SHALL be encrypted and integrity protected, protected (Class
   E), and thus is an inner message field.

   The sending endpoint writes the payload of the unprotected CoAP
   message into the plaintext of the COSE object (see Section 6.2 and
   Section 6.4). object.

   The receiving endpoint verifies and decrypts the COSE object, and
   recreates the payload of the unprotected CoAP message (see
   Section 6.3 and Section 6.5). message.

4.2.  CoAP Header

   Many CoAP header fields are required to be read and changed during a
   normal message exchange or when traversing a proxy and thus cannot be
   protected between the endpoints, e.g.  CoAP message layer fields such
   as Message ID.

   The CoAP header field Code MUST be sent in plaintext to support
   RESTful processing, but MUST be integrity protected to prevent an
   intermediary from changing, e.g. from GET to DELETE. DELETE (Class I).  The
   CoAP version number SHALL MUST be integrity protected to prevent potential
   future version-based attacks. attacks (Class I).  Note that while the version
   number is not sent in each CoAP message over reliable transport
   [I-D.ietf-core-coap-tcp-tls], its value is known to client and
   server.

   Other CoAP header fields SHALL neither be integrity protected nor
   encrypted.
   encrypted (Class U).  The CoAP header fields are thus outer message
   fields.

   The sending endpoint SHALL copy the header fields from the
   unprotected CoAP message to the protected CoAP message.  The
   receiving endpoint SHALL copy the header fields from the protected
   CoAP message to the unprotected CoAP message.  Both sender and
   receiver inserts insert the CoAP version number and header field Code in the
   AAD of the COSE object (see section Section 5.2).

4.3.  CoAP Options

   As with the message fields described in the previous sections, CoAP

   Most options may be are encrypted and integrity protected, integrity protected
   only, or neither encrypted nor integrity protected.

   Most options are encrypted and integrity protected (see Figure 4), (Class E), and
   thus inner message fields.  But to allow certain proxy operations,
   some options have outer values and require special
   processing.  Indeed, certain values, i.e. are present in the protected
   CoAP message.  Certain options may or must have both an inner value and a
   potentially different outer value, where the inner value is intended
   for the destination endpoint and the outer value is intended for the
   proxy.

     +----+---+---+---+---+----------------+--------+--------+---+---+

   A summary of how options are protected and processed is shown in
   Figure 4.  Options within each class are protected and processed in a
   similar way, but certain options which require special processing as
   described in the subsections and indicated by a * in Figure 4.

                   +----+----------------+---+---+---+
                   | No.| C | U | N | R | Name           | Format | Length | E | A |
     +----+---+---+---+---+----------------+--------+--------+---+---+
     |  1 | x I | U |
                   +----+----------------+---+---+---+
                   | x  1 | If-Match       | opaque | 0-8    | x |   |   |  3 | x | x | -
                   |  3 | Uri-Host       | string | 1-255   |   | x |
                   |  4 |   |   |   | x | ETag           | opaque | 1-8    | x |   |   |  5 | x |   |
                   |  5 | If-None-Match  | empty  | 0      | x |   |   |  6 |   | x | -
                   |  6 | Observe        | uint   | 0-3   | * |   |
                   |  7 | x | x | - |   | Uri-Port       | uint   | 0-2   |   | x |
                   |  8 |   |   |   | x | Location-Path  | string | 0-255  | x |   |   | 11 | x | x | -
                   | x 11 | Uri-Path       | string | 0-255  | x |   |   | 12 |   |   |
                   | 12 | Content-Format | uint   | 0-2    | x |   |   | 14 |   | x | -
                   | 14 | Max-Age        | uint   | 0-4    | * |   |   | 15 | x | x | -
                   | x 15 | Uri-Query      | string | 0-255  | x |   |   | 17 | x |   |
                   | 17 | Accept         | uint   | 0-2    | x |   |   | 20 |   |   |
                   | x 20 | Location-Query | string | 0-255  | x |   |   | 23 | x | x | -
                   | - 23 | Block2         | uint   | 0-3    | * |   |   | 27 | x | x | -
                   | - 27 | Block1         | uint   | 0-3    | * |   |   | 28 |   |   | x
                   | 28 | Size2          | unit   | 0-4    | * |   |   | 35 | x | x | -
                   | 35 | Proxy-Uri      | string | 1-1034   |   | * |
                   | 39 | x | x | - |   | Proxy-Scheme   | string | 1-255   |   | x |
                   | 60 |   |   | x |   | Size1          | uint   | 0-4    | * |   |
     +----+---+---+---+---+----------------+--------+--------+---+---+
           C=Critical, U=Unsafe, N=NoCacheKey, R=Repeatable,   |
                   +----+----------------+---+---+---+

        E=Encrypt and Integrity Protect, A=Integrity Protect, I=Integrity Protect only,
        U=Unprotected, *=Special

                   Figure 4: Protection of CoAP Options

   A summary of how options are protected and processed is shown in
   Figure 4.  The CoAP options are partitioned into two classes:

   o  E - options which are encrypted and integrity protected, and

   o  A - options which are only integrity protected.

   Options within each class are protected and processed in a similar
   way, but certain options which require special processing as
   described in the subsections and indicated by a '*' in Figure 4.

   Unless specified otherwise, CoAP options not listed in Figure 4 SHALL
   be encrypted and integrity protected and processed as class E
   options.

   Specifications of new CoAP options SHOULD specify define how they are
   processed with OSCOAP.  New COAP options SHOULD be of class E and
   SHOULD NOT have outer options unless a forwarding proxy needs to read
   an
   that option value.  If a certain option is both inner and outer, the
   two values SHOULD NOT be the same, unless a proxy is required by
   specification to be able to read the end-to-end value.

4.3.1.  Class E Options

   For options in class E (see Figure 4) the option value in the
   unprotected CoAP message, if present, SHALL be encrypted and
   integrity protected between the endpoints, and thus is not visible to
   or possible to change by intermediary nodes. endpoints.  Hence the actions
   resulting from the use of such options is analogous to communicating
   in a protected manner with the endpoint.  For example, a client using
   an ETag option will not be served by a proxy.

   The sending endpoint SHALL write the class E option from the
   unprotected CoAP message into the plaintext of the COSE object (see
   Section 6.2 and Section 6.4). object.

   Except for the special options described in the subsections, the
   sending endpoint SHALL NOT use the outer options of class E.
   However, note that an intermediary may, legimitimately legitimately or not, add,
   change or remove the value of an outer option.

   Execept

   Except for the Block options Section 4.3.1.3, 4.3.1.2, the receiving endpoint
   SHALL discard any outer options of class E from the protected CoAP
   message and SHALL replace it in the unprotected CoAP messages with
   the value from the COSE object when
   present (see Section 6.3 and Section 6.5). present.

4.3.1.1.  Max-Age

   An inner Max-Age option option, like other class E options, is used as
   defined in [RFC7252] taking into account that it is not accessible to
   proxies.

   Since OSCOAP binds CoAP responses to requests, a cached response
   would not be possible to use for any other request.  Therefore, there
   SHOULD be  To avoid
   unnecessary caching, a server MAY add an outer Max-Age option with
   value zero to prevent caching
   of protected CoAP responses (see Section 5.6.1 of
   [RFC7252]).

   The outer Max-Age option SHALL NOT be encrypted and SHALL NOT be is not integrity protected.

4.3.1.2.  Observe  The Observe option as used here targets the requirements on
   forwarding of [I-D.hartke-core-e2e-security-reqs] (Section 2.2.1.2).

   An inner Observe option Block Options

   Blockwise [RFC7959] is used between endpoints.  In order for a
   proxy to support forwarding of notifications, there SHALL be an outer
   Observe option.  To simplify the processing in the server, optional feature.  An implementation MAY
   comply with [RFC7252] and the outer Object-Security option SHOULD have the same value as the inner Observe option. without
   implementing [RFC7959].

   The
   outer Observe option Block options (Block1, Block2, Size1 and Size2) MAY have different values than the inner, but
   the order of the different values is SHALL be the same as for the either
   only inner Observe option.

   The outer Observe option SHALL neither be encrypted nor integrity
   protected.

4.3.1.3.  The Block Options

   The Block options (Block1, Block2, Size1 and Size2) MAY be either
   only inner options, only options, only outer options or both inner and outer
   options.  The inner and outer options are processed independently.

   The inner block options are used for endpoint-to-endpoint secure
   fragmentation of payload into blocks and protection of information
   about the fragmentation (block number, block size, last block, etc.).
   Additionally, a proxy may arbitrarily do fragmentation operations on block).  In
   this case, the protected CoAP message, adding outer block options that are not
   intended to be verified client fragments the CoAP message as defined in
   [RFC7959] before the message is processed by any endpoint or proxy. OSCOAP.  The CoAP server
   first processes the OSCOAP message before processing blockwise as
   defined in [RFC7959].

   There SHALL be a security policy defining a maximum unfragmented
   message size for inner Block options such that messages exceeding
   this size SHALL be fragmented by the sending endpoint.

   In addition to the processing defined for the inner Block options
   inherent to class E options, the AEAD Tag from each block SHALL be
   included in the calculation of the Tag for the next block (see
   Section 5.2), so that each

   Additionally, a proxy may arbitrarily do block in the order being sent can be
   verified as it arrives.

   The protected fragmentation on any
   CoAP message may be fragmented by the sending endpoint
   or proxy message, in particular an OSCOAP message, as defined in [RFC7959], in which case the
   [RFC7959] and thereby add outer Block options are being used. to a block and send on
   the next hop.  The outer Block block options SHALL are thus neither be encrypted nor
   integrity protected.

   An endpoint receiving a message with an outer Block option SHALL
   first process this option according to [RFC7959], until all blocks of
   the protected CoAP message has been received, or the cumulated
   message size of the exceeds the maximum unfragmented message size.
   In the latter case the message SHALL be discarded.  In the former
   case, the processing of the protected CoAP message continues as
   defined in this document (see Section 6.3 and Section 6.5). document.

   If the unprotected CoAP message in turn contains Block options, the
   receiving endpoint processes this according to {{RFC7959}. [RFC7959].

   TODO: Update processing to support multiple concurrently proceeding
   requests

4.3.2.  Class A Options I Options

   Except for the special options described in this class are used to support forward proxy operations.
   Class A the subsections, for
   options in Class I (see Figure 4) the option value SHALL only be
   integrity protected between the endpoints.  Options in Class I have
   outer values and SHALL NOT be
   encrypted.  In order for values.  Unless otherwise specified, the destination sending endpoint to verify SHALL
   encode the Uri,
   class A options SHALL be integrity protected.

   Uri-Host, Uri-Port, Proxy-Scheme and Proxy-Uri are class A options.
   When Uri-Host, Uri-Port, Proxy-Scheme options are present, Proxy-Uri
   is not used [RFC7252].  Proxy-Uri is processed like the other class A Class I options after a pre-processing step (see Section 4.3.2.1.

   Except for Proxi-Uri, the sending endpoint SHALL copy the class A
   option from the unprotected CoAP message to in the protected CoAP
   message.  The class A message as described
   in Section 4.3.4.

   Class I options are inserted included in the AAD of the COSE
   object (see unencrypted-Uri Section external_aad (Section 5.2).

4.3.2.1.  Proxy-Uri

   Proxy-Uri, when present,  Observe

   Observe [RFC7641] is split by OSCOAP into class A options an optional feature.  An implementation MAY
   support [RFC7252] and
   privacy sensitive class E options, which are processed accordingly.
   When Proxy-Uri is the Object-Security option without supporting
   [RFC7641].  The Observe option as used here targets the requirements
   on forwarding of [I-D.hartke-core-e2e-security-reqs]
   (Section 2.2.1.2).

   In order for a proxy to support forwarding of Observe, there MUST be
   an outer Observe option in the unprotected CoAP message, Uri-* are not
   present [RFC7252]. message.

   o  The sending endpoint SHALL first decompose the Proxy-Uri value Observe Registration (see Section 1.2 of [RFC7641]) of the
      unprotected CoAP message into the unencrypted-Uri (Section 5.2) and
   Uri-Path/Query options according to section 6.4 of [RFC7252].

   Uri-Path and Uri-Query are class E options and request SHALL be protected and
   processed as if obtained from encoded in the unprotected protected CoAP message, see
      request as described in Section 4.3.1. 4.3.4.

   o  The value Observe Notification (see Section 1.2 of the Proxy-Uri option [RFC7641]) of the protected
      unprotected CoAP message response SHALL be replaced with unencrypted-Uri encoded in the protected CoAP
      response as described in Section 4.3.4.

   To secure the Observe Registration and the order of the
   Notifications, Observe SHALL be integrity protected and processed as a class A option, see Section 4.3.2.

5. described in
   this section:

   o  The COSE Object

   This section defines how to use the COSE format [I-D.ietf-cose-msg]
   to wrap and protect data Observe option in the unprotected CoAP message.  OSCOAP
   uses the COSE_Encrypt0 structure with an Authenticated Encryption
   with Additional Data (AEAD) algorithm.

   The AEAD algorithm AES-CCM-64-64-128 defined in Section 10.2 of
   [I-D.ietf-cose-msg] is mandatory to implement.  For AES-CCM-64-64-128
   the length of Sender Key and Recipient Key request SHALL be 128 bits,
      included in the
   length external_aad of nonce, Sender IV, and Recipient IV SHALL be 7 bytes, and the maximum Sequence Number request (see Section 5.2).

   o  The Observe option SHALL be 2^56-1.  The nonce is
   constructed as described included in Section 3.1 the external_aad of [I-D.ietf-cose-msg], i.e.
   by padding the Partial IV (Sequence Number) with zeroes and XORing it
      response (see Section 5.2), with the context IV (Sender IV or Recipient IV).

   Since OSCOAP only makes use of a single COSE structure, there is no
   need value set to explicitly specify the structure, and OSCOAP uses the
   untagged version 3 least
      significant bytes of the COSE_Encrypt0 structure (Section 2. Sequence Number of
   [I-D.ietf-cose-msg]).  If the COSE object has a different structure, response

4.3.3.  Class U Options

   Options in Class U have outer values and are used to support forward
   proxy operations.  Unless otherwise specified, the recipient MUST reject sending endpoint
   SHALL encode the message, treating it Class U options in the protected CoAP message as malformed.

   OSCOAP introduces a new COSE Header Parameter,
   described in Section 4.3.4.

4.3.3.1.  Uri-Host, Uri-Port, and Proxy-Scheme

   The sending endpoint SHALL copy Uri-Host, Uri-Port, and Proxy-Scheme
   from the Sender Identifier:

   sid:  This parameter is used unprotected CoAP message to identify the sender of the protected CoAP message.
      Applications MUST NOT assume that 'sid' values
   When Uri-Host, Uri-Port, Proxy-Scheme options are unique.  This present, Proxy-Uri
   is not a security critical field.  For this reason, it can be
      placed in the unprotected headers bucket.

    +------+-------+------------+----------------+-------------------+
    | name | label | value type | value registry | description       |
    +------+-------+------------+----------------+-------------------+
    | sid  |  TBD  |    bstr    |                | Sender Identifier |
    +------+-------+------------+----------------+-------------------+

                 Table 1: Additional COSE Header Parameter

   We denote by Plaintext the data that used [RFC7252].

4.3.3.2.  Proxy-Uri

   Proxy-Uri, when present, is encrypted and integrity
   protected, and split by Additional Authenticated Data (AAD) the data that OSCOAP into class U options and
   privacy sensitive class E options, which are processed accordingly.
   When Proxy-Uri is integrity protected only, used in the COSE object.

   The fields of COSE_Encrypt0 structure unprotected CoAP message, Uri-* are defined as follows (see
   example in Appendix C.4).

   o  The "Headers" field is formed by:

      * not
   present [RFC7252].

   The "protected" field, which sending endpoint SHALL include:

         +  The "Partial IV" parameter.  The value is set to first decompose the Sender
            Sequence Number.  The Partial IV is a byte string (type:
            bstr), and SHOULD be Proxy-Uri value of minimum length needed to encode the
            sequence number.

         +  The "kid" parameter.  The value is set to
   unprotected CoAP message into the Context
            Identifier (see Section 3).  This parameter is optional Proxy-Scheme, Uri-Host, Uri-Port,
   Uri-Path and Uri-Query options (if present) according to section 6.4
   of [RFC7252].

   Uri-Path and Uri-Query are class E options and MUST be protected and
   processed as if obtained from the message is a unprotected CoAP response.

         +  Optionally, the parameter called "sid", defined below. message, see
   Section 4.3.1.

   The value is set to the Sender ID (see Section 3).  Note that
            since this parameter is sent in clear, privacy issues SHOULD
            be considered by of the application defining Proxy-Uri option of the Sender ID.

      *  The "unprotected" field, which SHALL protected CoAP message MUST
   be empty.

   o  The "ciphertext" field is computed from the Plaintext (see
      Section 5.1) replaced with Proxy-Scheme, Uri-Host and the Additional Authenticated Data (AAD) (see
      Section 5.2) Uri-Port options (if
   present) composed according to section 6.5 of [RFC7252] and encoded MUST be
   processed as a byte string (type: bstr), following class U option, see Section 5.2 4.3.3.

   An example of [I-D.ietf-cose-msg].

5.1.  Plaintext

   The Plaintext how Proxy-Uri is formatted as a processed is given below.

   An unprotected CoAP message without Header (see
   Figure 5) consisting of: contains:

   o  all CoAP Options present  Proxy-Uri = "coap://example.com/resource?q=1"

   During OSCOAP processing, Proxy-Uri is split into:

   o  Proxy-Scheme = "coap"

   o  Uri-Host = "example.com"

   o  Uri-Port = "5863"

   o  Uri-Path = "resource"

   o  Uri-Query = "q=1"

   Uri-Path and Uri-Query follow the processing defined in
   Section 4.3.1.  Proxy-Uri is added to the unprotected OSCOAP protected message which are
      encrypted (see Section 4),
   with value:

   o  Proxy-Uri = "coap://example.com"

4.3.4.  Outer Options in the order as given by the Option
      number (each Option Protected CoAP Message

   All options with Option Header outer values present in the protected CoAP message,
   including the Object-Security option, SHALL be encoded as described
   in Section 3.1 of [RFC7252], where the delta is the difference to previous the
   previously included encrypted option); outer option.

5.  The COSE Object

   This section defines how to use COSE [I-D.ietf-cose-msg] to wrap and

   o
   protect data in the unprotected CoAP Payload, if present, message.  OSCOAP uses the
   untagged COSE_Encrypt0 structure with an Authenticated Encryption
   with Additional Data (AEAD) algorithm.  The key lengths, IV lengths,
   and maximum sequence number are algorithm dependent.

   The AEAD algorithm AES-CCM-64-64-128 defined in that case prefixed by Section 10.2 of
   [I-D.ietf-cose-msg] is mandatory to implement.  For AES-CCM-64-64-128
   the
      one-byte Payload Marker (0xFF).

      0                   1                   2                   3
      0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 length of Sender Key and Recipient Key is 128 bits, the length of
   nonce, Sender IV, and Recipient IV is 7 8 9 0 1
     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
     |    Options to Encrypt (if any) ...                            ~
     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
     |1 1 1 1 1 1 1 1|    Payload (if any) ...                       ~
     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
      (only if there bytes, and the maximum
   Sequence Number is payload)

                            Figure 5: Plaintext

5.2.  Additional Authenticated Data 2^55 - 1.

   The Additional Authenticated Data ("Enc_structure") nonce is constructed as described is in Section 5.3 3.1 of [I-D.ietf-cose-msg] includes:

   o  the "context" parameter, which has value "Encrypted"

   o  the "protected" parameter, which includes
   [I-D.ietf-cose-msg], i.e. by padding the "protected" part of partial IV (Sequence Number
   in network byte order) with zeroes and XORing it with the "Headers" field;

   o context IV
   (Sender IV or Recipient IV).  The first bit in the "external_aad" is a serialized CBOR array Figure 6 where Sender IV or
   Recipient IV SHALL be flipped in responses.

   We denote by Plaintext the
      exact content data that is different in requests (external_aad_req) encrypted and
      repsonses (external_aad_resp).  It contains:

      *  ver: uint, contains integrity
   protected, and by Additional Authenticated Data (AAD) the CoAP version number, as data that
   is integrity protected only.

   The COSE Object SHALL be a COSE_Encrypt0 object with fields defined in
         Section 3 of [RFC7252]
   as follows

   o  The "protected" field includes:

      *  code: uint, contains  The "Partial IV" parameter.  The value is set to the CoAP Code Sequence
         Number.  The Partial IV SHALL be of minimum length needed to
         encode the unprotected CoAP
         message, as defined sequence number.  This parameter SHALL be present in Section 3
         requests, and MAY be present in responses.  In case of [RFC7252].

      *  alg: int, contains the Algorithm from Observe
         (Section 4.3.2.1}) the security context used
         for Partial IV SHALL be present in the exchange (see Section 3.1);
         response.

      *  unencrypted-uri: tstr with tag URI, contains the part of the
         URI which  The "kid" parameter.  The value is not encrypted, set to the Sender ID (see
         Section 3).  This parameter SHALL be present in requests and
         SHALL NOT be present in responses.

   o  The "unprotected" field is composed of empty.

   o  The "ciphertext" field is computed from the request
         scheme (Proxy-Scheme if present), Uri-Host Plaintext (see
      Section 5.1) and Uri-Port (if
         present) options according to the method Additional Authenticated Data (AAD) (see
      Section 5.2) following Section 5.2 of [I-D.ietf-cose-msg].

   The encryption process is described in Section 6.5 5.3 of [RFC7252], if the message
   [I-D.ietf-cose-msg].

5.1.  Plaintext

   The Plaintext is formatted as a CoAP request;

      *  cid : bstr, contains the cid for the request (which is same as
         the cid for the response).

      *  id : bstr, is the identifier for the endpoint sending the
         request and verifying the response; which means that for the
         endpoint sending the response, the id has value Recipient ID,
         while for the endpoint receiving the response, id has the value
         Sender ID.

      *  seq : bstr, is the value of the "Partial IV" message without Header (see
   Figure 5) consisting of:

   o  all Class E options Section 4.3.1 present in the COSE object
         of the request unprotected CoAP
      message (see Section 5).

      *  tag-previous-block: bstr, contains the AEAD Tag 4).  The options are encoded as described in
      Section 3.1 of [RFC7252], where the message
         containing delta is the previous block in difference to the sequence, as enumerated by
         Block1 in
      previously included Class E option; and

   o  the case Payload of a request unprotected CoAP message, if present, and Block2 in the that
      case of a
         response, if prefixed by the message is fragmented using one-byte Payload Marker (0xFF).

      0                   1                   2                   3
      0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
     |    Options to Encrypt (if any) ...
     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
     |1 1 1 1 1 1 1 1|    Payload (if any) ...
     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
      (only if there
        is payload)

                            Figure 5: Plaintext

5.2.  Additional Authenticated Data

   The external_aad SHALL be a block option
         [RFC7959]. CBOR array as defined below:

   external_aad = external_aad_req / external_aad_resp

            external_aad_req = [
      ver : uint,
      code : uint,
               alg : int,
               unencrypted-uri : uri,
               ? tag-previous-block : bstr
            ]

            external_aad_resp = [
               ver : uint,
               code
      options : uint, bstr,
      alg : int,
               cid
      request_kid : bstr,
               id : bstr,
               seq : bstr,
               ? tag-previous-block
      request_seq : bstr
   ]

                   Figure 6: External AAD (external_aad)

   The encryption process is described

   where:

   o  ver: contains the CoAP version number, as defined in Section 5.3 3 of
   [I-D.ietf-cose-msg].

6.  Protecting
      [RFC7252].

   o  code: contains is the CoAP Messages

6.1.  Replay and Freshness Protection

   In order to protect from replay Code of messages and verify freshness, a the unprotected CoAP endpoint SHALL maintain a Sender Sequence Number and a Recipient
   Replay Window message,
      as defined in Section 3 of [RFC7252].

   o  options: contains the security context.  An endpoint uses the Sender
   Sequence Number to protect messages to send and Class I options Section 4.3.2 present in the Recipient Replay
   Window to verify received messages,
      unprotected CoAP message encoded as described in Section 3.

   A receiving endpoint SHALL verify that 3.1 of
      [RFC7252], where the Sequence Number (Partial
   IV) received in delta is the COSE object has not been received before in difference to the previously
      included class I option

   o  alg: contains the Algorithm from the security context identified by the Cid. The size of used for the Replay
      exchange (see Section 3.1).

   o  request_kid: contains the value of the 'kid' in the COSE object of
      the request (see Section 5).

   o  request_seq: contains the value of the 'Partial IV' in the COSE
      object of the request (see Section 5).

6.  Sequence Numbers, Replay, Message Binding, and Freshness

6.1.  AEAD Nonce Uniqueness

   An AEAD nonce MUST NOT be used more than once per AEAD key.  In order
   to assure unique nonces, each Sender Context contains a Sequence
   Number used to protect requests, and - in case of Observe -
   responses.  The maximum sequence number is algorithm dependent and
   SHALL be 2^(min(nonce length in bits, 56) - 1) - 1.  If the Sequence
   Number exceeds the maximum sequence number, the endpoint MUST NOT
   process any more messages with the given Sender Context.  The
   endpoint SHOULD acquire a new security context (and consequently
   inform the other endpoint) before this happens.  The latter is out of
   scope of this document.

6.2.  Replay Protection

   In order to protect from replay of messages, each Recipient Context
   contains a Replay Window used to verify request, and - in case of
   Observe - responses.  A receiving endpoint SHALL verify that a
   Sequence Number (Partial IV) received in the COSE object has not been
   received before in the Recipient Context.  The size and type of the
   Replay Window depends on the use case and lower protocol layers.  In
   case of reliable and ordered transport, transport from endpoint to endpoint, the
   recipient MAY just store the last received sequence number and
   require that newly received Sequence Numbers equals the last received Recipient
   Sequence Number + 1.

6.3.  Sequence Number and Replay Window State

6.3.1.  The receiving endpoint SHALL reject messages Basic Case

   To prevent reuse of the Nonce/Sequence Number with the same key, or
   from accepting replayed messages, a node needs to handle the
   situation of suddenly losing sequence number
   greater than the maximum value and replay window state
   in RAM, e.g. as a result of the Partial IV.  This maximum value
   is algorithm specific, for example for AES-CCM-64-64-128 a reboot.

   After boot, a node MAY reject to use existing security contexts from
   before it booted and MAY establish a new security context with each
   party it communicates, e.g. using EDHOC
   [I-D.selander-ace-cose-ecdhe].  However, establishing a fresh
   security context may have a non-negligible cost in terms of e.g.
   power consumption.

   If a stored security context is
   2^56-1.

   OSCOAP responses are verified to match be used after reboot, then the
   node MUST NOT reuse a prior request, by including previous Sequence Number and MUST NOT accept
   previously accepted messages.  The node MAY perform the unique transaction identifier (Tid as defined in Section 3) of following
   procedure:

   o  Before sending a message, the request client stores in persistent memory a
      sequence number associated to the Additional Authenticated Data of stored security context higher
      than any sequence number which has been or are being sent using
      this security context.  After boot, the response
   message.  In case client does not use any
      lower sequence number in a request than what was persistently
      stored with that security context.

      *  Storing to persistent memory can be costly.  Instead of CoAP observe, storing
         a sequence number for each notification MUST be verified
   using request, the Tid client may store Seq +
         K to persistent memory every K requests, where Seq is the
         current sequence number and K > 1.  This is a trade-off between
         the number of storage operations and efficient use of sequence
         numbers.

   o  After boot, before accepting a message from a stored security
      context, the observe registration, server synchronizes the replay window so that no old
      messages are being accepted.  The server uses the Tid of Repeat option
      [I-D.mattsson-core-coap-actuators] for synchronizing the
   registration needs to be cached by replay
      window: For each stored security context, the observer until first time after
      boot the observation
   ends.

   If a CoAP server receives an OSCOAP request, it generates a request pseudo-
      random nonce and responds with the Object-Security option,
   then the server SHALL include the Tid of the request in the AAD of Repeat option set to the response, nonce
      as described in Section 6.4. [I-D.mattsson-core-coap-actuators].  If the CoAP client server
      receives a response with repeated OSCOAP request containing the Object-Security
   option, then Repeat option
      and the client SHALL same nonce, and if the server can verify the integrity request, then
      the sequence number obtained in the repeated message is set as the
      lower limit of the response,
   using replay window.

6.4.  Freshness

   For responses without Observe, OSCOAP provides absolute freshness.
   For requests, and responses with Observe, OSCOAP provides relative
   freshness in the Tid sense that the sequence numbers allows a recipient
   to determine the relative order of its own associated messages.  For applications having
   stronger demands on freshness (e.g. control of actuators), OSCOAP
   needs to be augmented with mechanisms providing absolute freshness
   [I-D.mattsson-core-coap-actuators].

6.5.  Delay and Mismatch Attacks

   In order to prevent response delay and mismatch attacks
   [I-D.mattsson-core-coap-actuators] from on-path attackers and
   compromised proxies, OSCOAP binds responses to the request in by
   including the AAD, as described request's ID (Sender ID or Recipient ID) and sequence
   number in Section 6.5.

6.2. the AAD of the response.  The server therefore needs to
   store the request's ID (Sender ID or Recipient ID) and sequence
   number until all responses have been sent.

7.  Processing

7.1.  Protecting the Request

   Given an unprotected CoAP request, including header, options and
   payload, the client SHALL perform the following
   steps to create a protected CoAP request using a security context request:

   1.  Retrieve the Sender Context associated with the target resource (see Section 3.2.2).

   When using Uri-Host or Proxy-Uri in the construction of the request,
   the <host> value MUST be a reg-name ([RFC3986]), and not an IP-
   literal or IPv4address, for canonicalization of the destination
   address.

   1.  Compute resource.

   2.  Compose the COSE object Additional Authenticated Data, as specified described in
       Section 5

       * 5.

   3.  Compose the AEAD nonce is created by XORing the Sender context IV (context (Sender IV) with
       the Sender partial IV (Sequence Number in network byte order).
       Increment the Sequence Number (partial IV).

       *  If by one.

   4.  Encrypt the block option is used, COSE object using the AAD includes Sender Key. Compress the AEAD Tag
          from COSE
       Object as specified in Appendix A.

   5.  Format the previous block sent (from the second block and
          following) protected CoAP message according to Section 5.2.  This means that the endpoint MUST
          store 4.  The
       Object-Security option is added, see Section 4.3.4.

   6.  Store the Tag of each last-sent block association Token - Security Context.  The client SHALL
       be able to compute find the
          following.

       *  Note that Recipient Context from the 'sid' field Token in the
       response.

7.2.  Verifying the Request

   A server receiving a request containing the Sender Object-Security option
   SHALL perform the following steps:

   1.  Process outer Block options according to [RFC7959], until all
       blocks of the request have been received, see Section 4.3.1.2.

   2.  Retrieve the Recipient Context associated with the Recipient ID is included
       in the 'kid' parameter of the COSE object (Section 5) if object.

   3.  Verify the application needs it.

   2.  Format Sequence Number in the protected CoAP message 'Partial IV' parameter, as an ordinary CoAP message,
       described in Section 6.

   4.  Compose the Additional Authenticated Data, as described in
       Section 5.

   5.  Compose the AEAD nonce by XORing the context IV (Recipient IV)
       with the following Header, Options, and Payload, based on padded 'Partial IV' parameter, received in the
       unprotected CoAP message: COSE
       Object.

   6.  Decrypt the COSE object using the Recipient Key.

       *  The CoAP header is  If decryption fails, the same as server MUST stop processing the unprotected CoAP
          request and SHOULD send an 4.01 error message.

       *  If present, decryption succeeds, update the CoAP option Proxy-Uri is decomposed Recipient Replay Window, as
          described in Section 4.3.2.1.

       *  The CoAP 6.

   7.  Add decrypted options which are of class or payload to the unprotected request,
       overwriting any outer E (Section 4) are removed. options (see Section 4).  The Object-Security Object-
       Security option is added.

       *  If the message type of the removed.

   8.  The unprotected CoAP message does not
          allow Payload, then the value of the Object-Security option request is processed according to [RFC7252]

7.3.  Protecting the COSE object.  If the message type of the Response

   Given an unprotected CoAP
          message allows Payload, then the Object-Security option is
          empty and response, the Payload of server SHALL perform the following
   steps to create a protected CoAP message is response:

   1.  Retrieve the
          COSE object.

   3.  Store Sender Context in the association Token - Cid. The Client SHALL be able Security Context used to
       find
       verify the request.

   2.  Compose the Additional Authenticated Data, as described in
       Section 5.

   3.  Compose the AEAD nonce

       *  If Observe is not used, compose the AEAD nonce by XORing the correct security
          context used to protect IV (Recipient IV with the request and
       verify first bit flipped) with the response
          padded Partial IV parameter from the request.

       *  If Observe is used, compose the AEAD nonce by XORing the
          context IV (Recipient IV with use of the Token of first bit flipped) with the message
       exchange.

   4.
          partial IV (Sequence Number in network byte order).  Increment
          the Sender Sequence Number by one.  If the Sender
       Sequence Number exceeds the maximum number for the AEAD
       algorithm,

   4.  Encrypt the client MUST NOT process any more requests with COSE object using the
       given security context.  The client SHOULD acquire a new security
       context (and consequently inform Sender Key. Compress the server about it) before this
       happens.  The latter is out of scope of this memo.

6.3.  Verifying COSE
       Object as specified in Appendix A.

   5.  Format the Request

   A CoAP server receiving an unprotected protected CoAP request message according to access a
   protected resource (as defined Section 3.2.2) SHALL reject 4.  The
       Object-Security option is added, see Section 4.3.4.

7.4.  Verifying the
   message with error code 4.01 (Unauthorized). Response

   A CoAP server client receiving a message response containing the Object-Security option and a
   SHALL perform the following steps:

   1.  Process outer Block option SHALL first process this option options according to [RFC7959], until all
       blocks of the protected CoAP message has have been received, see
       Section 4.3.1.3.

   A CoAP server receiving a message containing the Object-Security
   option SHALL perform the following steps, using the security context
   identified by 4.3.1.2.

   2.  Retrieve the Recipient Context Identifier in the "kid" parameter in associated with the
   received COSE object:

   1.  Verify Token.

   3.  If Observe is used, verify the Sequence Number in the Partial IV parameter, 'Partial
       IV' parameter as described in Section 6.1.  If it cannot be verified that the
       Sequence Number has not been received before, the server MUST
       stop processing the request.

   2.  Recreate 6.

   4.  Compose the Additional Authenticated Data, as described in
       Section 5.

   5.  Compose the AEAD nonce

       *  If the block option Observe is not used, the AAD includes compose the AEAD Tag
          from the previous block received (from nonce by XORing the second block and
          following) Section 5.2.  This means that
          context IV (Recipient IV with the endpoint MUST
          store first bit flipped) with the Tag of each last-received block to compute
          padded Partial IV parameter from the
          following. request.

       *  Note that the server's <host> value MUST be a reg-name
          ([RFC3986]), and not an IP-literal or IPv4address.

   3.  Compose  If Observe is used, compose the AEAD nonce by XORing the Recipient
          context IV (context IV) (Recipient IV with the first bit flipped) with the
          padded Partial IV parameter, received in parameter from the response.

   6.  Decrypt the COSE
       Object.

   4.  Retrieve object using the Recipient Key.

   5.  Verify and decrypt the message.

       *  If the verification decryption fails, the
       server client MUST stop processing the request.

   6.
          response and SHOULD send an 4.01 error message.

       *  If the message verifies, decryption succeeds and Observe is used, update the
          Recipient Replay Window, as described in Section 6.1. 6.

   7.  Restore the unprotected request by adding any  Add decrypted options or payload from to the plaintext.  Any unprotected response
       overwriting any outer E options (Section 4)
       are overwritten. (see Section 4).  The Object-Security Object-
       Security option is removed.

6.4.  Protecting

       *  If Observe is used, replace the Response

   A server receiving a valid request with a protected CoAP message
   (i.e. containing an Object-Security option) SHALL respond Observe value with a
   protected CoAP message.

   Given an unprotected CoAP response, including header, options, and
   payload, the server SHALL perform 3 least
          significant bytes in the following steps to create a
   protected CoAP response, using the security context identified by the
   Context Identifier of the received request:

   1.  Compute the COSE object as specified in Section Section 5

       * sequence number.

   8.  The AEAD nonce unprotected CoAP response is created processed according to [RFC7252]

8.  Web Linking

   The use of OSCOAP MAY be indicated by XORing the Sender IV (context IV)
          and the padded Sender Sequence Number.

       *  If the block option [RFC7959] is used, the AAD includes the
          AEAD Tag from the previous block sent (from the second block
          and following) Section 5.2. a target attribute "osc" in a
   web link [RFC5988] to a CoAP resource.  This means attribute is a hint
   indicating that the endpoint MUST
          store the Tag destination of each last-sent block that link is to compute the
          following. be accessed using
   OSCOAP.  Note that this applies even for random access of
          blocks, i.e. when blocks are is simply a hint, it does not requested in include any
   security context material or any other information required to run
   OSCOAP.

   A value MUST NOT be given for the order of
          their relative number (NUM).

   2.  Format "osc" attribute; any present value
   MUST be ignored by parsers.  The "osc" attribute MUST NOT appear more
   than once in a given link-value; occurrences after the protected CoAP message as an ordinary CoAP message, first MUST be
   ignored by parsers.

9.  Security Considerations

   In scenarios with intermediary nodes such as proxies or brokers,
   transport layer security such as DTLS only protects data hop-by-hop.
   As a consequence the following Header, Options, intermediary nodes can read and Payload based on the
       unprotected CoAP message:

       * modify
   information.  The CoAP header trust model where all intermediate nodes are
   considered trustworthy is the same problematic, not only from a privacy
   perspective, but also from a security perspective, as the unprotected CoAP message.

       *  The CoAP options which are of class E
   intermediaries are removed, except any
          special option (labelled '*') that is present which has its
          outer value (Section 4).  The Object-Security option is added.

       *  If the message type of free to delete resources on sensors and falsify
   commands to actuators (such as "unlock door", "start fire alarm",
   "raise bridge").  Even in the unprotected CoAP message does not
          allow Payload, then rare cases, where all the value owners of the Object-Security option is
          the COSE object.  If the message type of
   intermediary nodes are fully trusted, attacks and data breaches make
   such an architecture brittle.

   DTLS protects hop-by-hop the unprotected entire CoAP
          message allows Payload, then the Object-Security option is
          empty message, including header,
   options, and payload.  OSCOAP protects end-to-end the Payload of payload, and
   all information in the protected CoAP message options and header, that is the
          COSE object.

   3.  Increment the Sender Sequence Number by one.  If the Sender
       Sequence Number exceeds the maximum number not required for the AEAD
       algorithm, the server MUST NOT process any more responses with
       the given security context.  The server SHOULD acquire a new
   forwarding (see Section 4).  DTLS and OSCOAP can be combined, thereby
   enabling end-to-end security context (and consequently inform the client about it)
       before this happens.  The latter is out of scope CoAP payload, in combination with
   hop-by-hop protection of this memo.

   Note the differences entire CoAP message, during transport
   between generating a end-point and intermediary node.

   The CoAP message layer, however, cannot be protected request, end-to-end
   through intermediary devices since the parameters Type and Message
   ID, as well as Token and Token Length may be changed by a
   protected response, proxy.
   Moreover, messages that are not possible to verify should for example whether "kid" is present
   security reasons not always be acknowledged but in some cases be
   silently dropped.  This would not comply with CoAP message layer, but
   does not have an impact on the
   header, or whether Destination URI or Tid application layer security solution,
   since message layer is present in the AAD, excluded from that.

   The use of
   the COSE object.

6.5.  Verifying the Response

   A to protect CoAP client receiving a message containing the Object-Security
   option SHALL perform the following steps, using messages as specified in this
   document requires an established security context.  The method to
   establish the security context
   identified described in Section 3.2 is based on a
   common shared secret material in client and server, which may be
   obtained e.g. by using EDHOC [I-D.selander-ace-cose-ecdhe] or the Token ACE
   framework [I-D.ietf-ace-oauth-authz].  An OSCOAP profile of ACE is
   described in [I-D.seitz-ace-oscoap-profile].

   The formula 2^(min(nonce length in bits, 56) - 1) - 1 (Section 6.1)
   guarantees unique nonces during the received response:

   1.  If required use the message contain an outer Block option algorithm,
   considering the client SHALL
       process this option according to [RFC7959], until all blocks same partial IV and flipped first bit of
       the protected CoAP message has been received, see
       Section 4.3.1.3.

   2.  Verify the Sequence Number in the Partial IV parameter as
       described
   (Section 5) is used in Section 6.1.  If it cannot be verified that the
       Sequence Number has not been received before, the client MUST
       stop processing the response.

   3.  Recreate request and response (which is the Additional Authenticated Data as described reason for
   -1 in
       Section 5.

       *  If the block option exponent).  The compression algorithm (Appendix A) assumes
   that the partial IV is 56 bits or less (which is used, the AAD includes reason for
   min(,) in the exponent).

   The mandatory-to-implement AEAD Tag
          from the previous block received (from the second block algorithm AES-CCM-64-64-128 is
   selected for broad applicability in terms of message size (2^64
   blocks) and
          following) Section 5.2.  This means that the endpoint MUST
          store the Tag maximum number of each last-received block to compute the
          following.

   4.  Compose messages (2^56).  Compatibility with
   CCM* is achieved by using the algorithm AES-CCM-16-64-128
   [I-D.ietf-cose-msg].

   Most AEAD algorithms require a unique nonce by XORing the Recipient IV (context IV)
       with for each message, for
   which the Partial IV parameter, received sequence numbers in the COSE Object.

   5.  Retrieve the Recipient Key.

   6.  Verify and decrypt the message.  If the verification fails, the
       client MUST stop processing the response.

   7.  If the message verifies, update the Recipient Replay Window, as
       described in Section 6.1.

   8.  Restore field "Partial IV" is
   used.  If the unprotected response by adding recipient accepts any decrypted options
       or payload from sequence number larger than the plaintext.  Any class E options (Section 4)
       are overwritten.  The Object-Security option
   one previously received, then the problem of sequence number
   synchronization is removed.

7.  Security Considerations

   In scenarios with intermediary nodes such as proxies or brokers, avoided.  With reliable transport layer security such as DTLS it may be
   defined that only protects data hop-by-hop.
   As a consequence the intermediary nodes can read messages with sequence number which are equal to
   previous sequence number + 1 are accepted.  The alternatives to
   sequence numbers have their issues: very constrained devices may not
   be able to support accurate time, or to generate and modify
   information. store large
   numbers of random nonces.  The trust model where all intermediate nodes are
   considered trustworthy requirement to change key at counter
   wrap is problematic, not only from a privacy
   perspective, complication, but it also from a security perspective, as the
   intermediaries are free to delete resources on sensors and falsify
   commands to actuators (such as "unlock door", "start fire alarm",
   "raise bridge").  Even in the rare cases, where all forces the owners user of this
   specification to think about implementing key renewal.

   The inner block options enable the
   intermediary nodes are fully trusted, attacks and data breaches make sender to split large messages
   into protected blocks such an architecture brittle.

   DTLS protects hop-by-hop the entire CoAP message, including header,
   options, and payload.  OSCOAP protects end-to-end that the payload, and
   all information in receiving node can verify blocks
   before having received the complete message.  The outer block options and header, that is not required
   allow for
   forwarding (see Section 4).  DTLS and OSCOAP arbitrary proxy fragmentation operations that cannot be
   verified by the endpoints, but can by policy be combined, thereby
   enabling end-to-end security of CoAP payload, restricted in combination with
   hop-by-hop protection of size
   since the entire CoAP message, during transport
   between end-point and intermediary node.

   The CoAP encrypted options allow for secure fragmentation of very
   large messages.  A maximum message layer, however, cannot be protected end-to-end
   through intermediary devices since size (above which the parameters Type and Message
   ID, as well as Token sending
   endpoint fragments the message and Token Length the receiving endpoint discards
   the message, if complying to the policy) may be changed by a proxy.
   Moreover, messages that are not possible obtained as part of
   normal resource discovery.

   Applications need to verify should for
   security reasons not always be acknowledged but in some cases use a padding scheme if the content of a message
   can be
   silently dropped.  This would not comply with CoAP message layer, but
   does not have an impact on the application layer security solution,
   since message layer is excluded determined solely from that.

   The use the length of COSE to protect CoAP messages as specified in this
   document requires an established security context.  The method to
   establish the security context described in Section 3.2 is based on a
   common shared secret material and key derivation function in client
   and server.  EDHOC [I-D.selander-ace-cose-ecdhe] describes payload.  As an
   augmented Diffie-Hellman key exchange to produce forward secret
   keying material
   example, the strings "YES" and agree on crypto algorithms necessary for OSCOAP,
   authenticated with pre-established credentials.  These pre-
   established credentials may, in turn, "NO" even if encrypted can be provisioned using a trusted
   third party such
   distinguished from each other as described in there is no padding supplied by the OAuth-based ACE framework
   [I-D.ietf-ace-oauth-authz].
   current set of encryption algorithms.  Some information can be
   determined even from looking at boundary conditions.  An OSCOAP profile example of ACE is described in
   [I-D.seitz-ace-oscoap-profile].

   The mandatory-to-implement AEAD algorithm AES-CCM-64-64-128 is
   selected for broad applicability in terms
   this would be returning an integer between 0 and 100 where lengths of message size (2^64
   blocks)
   1, 2 and maximum no. messages (2^56-1).  Compatibility 3 will provide information about where in the range things
   are.  Three different methods to deal with CCM*
   is achieved by using this are: 1) ensure that
   all messages are the algorithm AES-CCM-16-64-128
   [I-D.ietf-cose-msg].

   Most AEAD algorithms require same length.  For example using 0 and 1 instead
   of 'yes' and 'no'.  2) Use a unique nonce for each message, for character which the sequence numbers in the COSE message field "Partial IV" is
   used.  If not part of the recipient accepts any sequence number larger than
   responses to pad to a fixed length.  For example, pad with a space to
   three characters.  3) Use the
   one previously received, then PKCS #7 style padding scheme where m
   bytes are appended each having the problem value of sequence number
   synchronization is avoided.  With reliable transport it may be
   defined m.  For example,
   appending a 0 to "YES" and two 1's to "NO".  This style of padding
   means that only messages with sequence number which are equal all values need to
   previous sequence number + 1 be padded.

10.  Privacy Considerations

   Privacy threats executed through intermediate nodes are accepted.  The alternatives to
   sequence numbers considerably
   reduced by means of OSCOAP.  End-to-end integrity protection and
   encryption of CoAP payload and all options that are not used for
   forwarding, provide mitigation against attacks on sensor and actuator
   communication, which may have their issues: very constrained devices a direct impact on the personal sphere.

   The unprotected options (Figure 4) may not
   be able to support accurate time, or to generate reveal privacy sensitive
   information.  In particular Uri-Host SHOULD NOT contain privacy
   sensitive information.

   CoAP headers sent in plaintext allow for example matching of CON and store large
   numbers
   ACK (CoAP Message Identifier), matching of random nonces.  The requirement request and responses
   (Token) and traffic analysis.

11.  IANA Considerations

   Note to change key at counter
   wrap is a complication, but it also forces RFC Editor: Please replace all occurrences of "[[this
   document]]" with the user RFC number of this
   specification to think about implementing key renewal. specification.

11.1.  CoAP Option Numbers Registry

   The encrypted block options enable the sender to split large messages
   into protected blocks such that the receiving node can verify blocks
   before having received the complete message.  In order to protect
   from attacks replacing blocks from a different message with the same
   block number between same endpoints and same resource at roughly the
   same time, the AEAD Tag from the message containing one block is
   included in the external_aad of the message containing the next
   block.

   The unencrypted block options allow for arbitrary proxy fragmentation
   operations that cannot be verified by the endpoints, but can by
   policy be restricted in size since the encrypted options allow for
   secure fragmentation of very large messages.  A maximum message size
   (above which the sending endpoint fragments the message and the
   receiving endpoint discards the message, if complying to the policy)
   may be obtained as part of normal resource discovery.

   Applications need to use a padding scheme if the content of a message
   can be determined solely from the length of the payload.  As an
   example, the strings "YES" and "NO" even if encrypted can be
   distinguished from each other as there is no padding supplied by the
   current set of encryption algorithms.  Some information can be
   determined even from looking at boundary conditions.  An example of
   this would be returning an integer between 0 and 100 where lengths of
   1, 2 and 3 will provide information about where in the range things
   are.  Three different methods to deal with this are: 1) ensure that
   all messages are the same length.  For example using 0 and 1 instead
   of 'yes' and 'no'.  2) Use a character which is not part of the
   responses to pad to a fixed length.  For example, pad with a space to
   three characters.  3) Use the PKCS #7 style padding scheme where m
   bytes are appended each having the value of m.  For example,
   appending a 0 to "YES" and two 1's to "NO".  This style of padding
   means that all values need to be padded.

8.  Privacy Considerations

   Privacy threats executed through intermediate nodes are considerably
   reduced by means of OSCOAP.  End-to-end integrity protection and
   encryption of CoAP payload and all options that are not used for
   forwarding, provide mitigation against attacks on sensor and actuator
   communication, which may have a direct impact on the personal sphere.

   CoAP headers sent in plaintext allow for example matching of CON and
   ACK (CoAP Message Identifier), matching of request and responses
   (Token) and traffic analysis.

9.  IANA Considerations

   Note to RFC Editor: Please replace all occurrences of "[[this
   document]]" with the RFC number of this specification.

9.1.  CoAP Option Numbers Registry

   The Object-Security option is added to the CoAP Option Numbers
   registry:

             +--------+-----------------+-------------------+
             | Number | Name            | Reference         |
             +--------+-----------------+-------------------+
             |  TBD   | Object-Security | [[this document]] |
             +--------+-----------------+-------------------+

9.2.  COSE Header Parameters Registry

   The "sid" parameter is added to the COSE Header Parameter Registry:

    +------+-------+------------+----------------+-------------------+
    | name | label | value type | value registry | description       |
    +------+-------+------------+----------------+-------------------+
    |  sid |  TBD  |    bstr    |                | Sender Identifier |
    +------+-------+------------+----------------+-------------------+

9.3.  Media Type Registrations

   The "application/oscon" media type is added to the Media Types
   registry:

       Type name: application

       Subtype name: oscon

       Required parameters: N/A

       Optional parameters: N/A

       Encoding considerations: binary

       Security considerations: See Appendix C of [[this document]].

       Interoperability considerations: N/A

       Published specification: [[this document]]

       Applications that use this media type: To be identified

       Fragment identifier considerations: N/A

       Additional information:

       * Magic number(s): N/A

       * File extension(s): N/A

       * Macintosh file type code(s): N/A

       Person & email address to contact for further information:
       iesg@ietf.org

       Intended usage: COMMON

       Restrictions on usage: N/A

       Author: Goeran Selander, goran.selander@ericsson.com

       Change Controller: IESG

       Provisional registration? No

9.4.  CoAP Content Format Registration

   The "application/oscon" content format is added to the CoAP Content
   Format registry:

         +-------------------+----------+----+-------------------+
         | Media type        | Encoding | ID | Reference         |
         +-------------------+----------+----+-------------------+
         | application/oscon | -        | 70 | [[this document]] |
         +-------------------+----------+----+-------------------+

10.  Acknowledgments

   The following individuals provided input to this document: Carsten
   Bormann, Joakim Brorsson, Martin Gunnarsson, Klaus Hartke, Jim
   Schaad, Marco Tiloca, and Malisa Vucinic.

   Ludwig Seitz and Goeran Selander worked on this document as part of
   the CelticPlus project CyberWI, with funding from Vinnova.

11.  References

11.1.  Normative References

   [I-D.ietf-cose-msg]
              Schaad, J., "CBOR Object Signing and Encryption (COSE)",
              draft-ietf-cose-msg-24 (work in progress), November 2016.

   [RFC2119]  Bradner, S., "Key words for use in RFCs to Indicate
              Requirement Levels", BCP 14, RFC 2119,
              DOI 10.17487/RFC2119, March 1997,
              <http://www.rfc-editor.org/info/rfc2119>.

   [RFC6347]  Rescorla, E. and N. Modadugu, "Datagram Transport Layer
              Security Version 1.2", RFC 6347, DOI 10.17487/RFC6347,
              January 2012, <http://www.rfc-editor.org/info/rfc6347>.

   [RFC7252]  Shelby, Z., Hartke, K., and C. Bormann, "The Constrained
              Application Protocol (CoAP)", RFC 7252,
              DOI 10.17487/RFC7252, June 2014,
              <http://www.rfc-editor.org/info/rfc7252>.

   [RFC7641]  Hartke, K., "Observing Resources in the Constrained
              Application Protocol (CoAP)", RFC 7641,
              DOI 10.17487/RFC7641, September 2015,
              <http://www.rfc-editor.org/info/rfc7641>.

   [RFC7959]  Bormann, C. and Z. Shelby, Ed., "Block-Wise Transfers in
              the Constrained Application Protocol (CoAP)", RFC 7959,
              DOI 10.17487/RFC7959, August 2016,
              <http://www.rfc-editor.org/info/rfc7959>.

   [RFC3986]  Berners-Lee, T., Fielding, R., and L. Masinter, "Uniform
              Resource Identifier (URI): Generic Syntax", STD 66,
              RFC 3986, DOI 10.17487/RFC3986, January 2005,
              <http://www.rfc-editor.org/info/rfc3986>.

   [RFC7049]  Bormann, C. and P. Hoffman, "Concise Binary Object
              Representation (CBOR)", RFC 7049, DOI 10.17487/RFC7049,
              October 2013, <http://www.rfc-editor.org/info/rfc7049>.

11.2.  Informative References

   [I-D.selander-ace-cose-ecdhe]
              Selander, G., Mattsson, J., and F. Palombini, "Ephemeral
              Diffie-Hellman Over COSE (EDHOC)", draft-selander-ace-
              cose-ecdhe-04 (work in progress), October 2016.

   [I-D.hartke-core-e2e-security-reqs]
              Selander, G., Palombini, F., and K. Hartke, "Requirements
              for CoAP End-To-End Security", draft-hartke-core-e2e-
              security-reqs-01 (work in progress), July 2016.

   [I-D.mattsson-core-coap-actuators]
              Mattsson, J., Fornehed, J., Selander, G., and F.
              Palombini, "Controlling Actuators with CoAP", draft-
              mattsson-core-coap-actuators-02 (work in progress),
              November 2016.

   [I-D.bormann-6lo-coap-802-15-ie]
              Bormann, C., "Constrained Application Protocol (CoAP) over
              IEEE 802.15.4 Information Element for IETF", draft-
              bormann-6lo-coap-802-15-ie-00 (work in progress), April
              2016.

   [I-D.ietf-ace-oauth-authz]
              Seitz, L., Selander, G., Wahlstroem, E., Erdtman, S., and
              H. Tschofenig, "Authentication and Authorization for
              Constrained Environments (ACE)", draft-ietf-ace-oauth-
              authz-04 (work in progress), October 2016.

   [I-D.seitz-ace-oscoap-profile]
              Seitz, L. and F. Palombini, "OSCOAP profile of ACE",
              draft-seitz-ace-oscoap-profile-01 (work in progress),
              October 2016.

   [I-D.ietf-core-coap-tcp-tls]
              Bormann, C., Lemay, S., Tschofenig, H., Hartke, K.,
              Silverajan, B., and B. Raymor, "CoAP (Constrained
              Application Protocol) over TCP, TLS, and WebSockets",
              draft-ietf-core-coap-tcp-tls-05 (work in progress),
              October 2016.

   [I-D.greevenbosch-appsawg-cbor-cddl]
              Vigano, C. and H. Birkholz, "CBOR data definition language
              (CDDL): a notational convention to express CBOR data
              structures", draft-greevenbosch-appsawg-cbor-cddl-09 (work
              in progress), September 2016.

   [RFC5869]  Krawczyk, H. and P. Eronen, "HMAC-based Extract-and-Expand
              Key Derivation Function (HKDF)", RFC 5869,
              DOI 10.17487/RFC5869, May 2010,
              <http://www.rfc-editor.org/info/rfc5869>.

   [RFC7228]  Bormann, C., Ersue, M., and A. Keranen, "Terminology for
              Constrained-Node Networks", RFC 7228,
              DOI 10.17487/RFC7228, May 2014,
              <http://www.rfc-editor.org/info/rfc7228>.

Appendix A.  Overhead

   OSCOAP transforms an unprotected CoAP message to a protected CoAP
   message, and the protected CoAP message Object-Security option is larger than added to the
   unprotected CoAP message.  This appendix illustrates the message
   expansion.

A.1.  Length of the Object-Security Option Numbers
   registry:

             +--------+-----------------+-------------------+
             | Number | Name            | Reference         |
             +--------+-----------------+-------------------+
             |  TBD   | Object-Security | [[this document]] |
             +--------+-----------------+-------------------+

11.2.  Media Type Registrations

   The protected CoAP message contains the COSE object.  The COSE object
   is included in the payload if the message "application/oscon" media type of the unprotected
   CoAP message allows payload or else in the Object-Security option.
   In the former case the Object-Security option is empty.  So the
   length of the Object-Security option is either zero or added to the size Media Types
   registry:

       Type name: application

       Subtype name: oscon

       Required parameters: N/A

       Optional parameters: N/A

       Encoding considerations: binary

       Security considerations: See Appendix C of
   the COSE object, depending this document.

       Interoperability considerations: N/A

       Published specification: [[this document]] (this document)

       Applications that use this media type: To be identified

       Fragment identifier considerations: N/A

       Additional information:

       * Magic number(s): N/A

       * File extension(s): N/A

       * Macintosh file type code(s): N/A

       Person & email address to contact for further information:
          Goeran Selander <goran.selander@ericsson.com>

       Intended usage: COMMON

       Restrictions on whether the usage: N/A

       Author: Goeran Selander, goran.selander@ericsson.com

11.3.  CoAP message allows payload
   or not.

   Length of Object-Security option = { 0, size of COSE Object }

A.2.  Size of the COSE Object Content Format Registration

   The size of the COSE object is the sum of the sizes of

   o  the Header parameters,
   o  the Cipher Text (excluding the Tag),

   o  the Tag, and

   o  data incurred by the COSE "application/oscon" content format itself (including CBOR encoding).

   Let's analyze is added to the contributions one at a time:

   o CoAP Content
   Format registry:

         +-------------------+----------+----+-------------------+
         | Media type        | Encoding | ID | Reference         |
         +-------------------+----------+----+-------------------+
         | application/oscon | -        | 70 | [[this document]] |
         +-------------------+----------+----+-------------------+

12.  Acknowledgments

   The header parameters of the COSE object are the Context
      Identifier (Cid) following individuals provided input to this document: Christian
   Amsuess, Carsten Bormann, Joakim Brorsson, Martin Gunnarsson, Klaus
   Hartke, Jim Schaad, Marco Tiloca, and the Sequence Number (Seq) (also Malisa Vu&#269;ini&#263;.

   Ludwig Seitz and Goeran Selander worked on this document as part of
   the
      Transaction Identifier (Tid)) if the message is a request, CelticPlus project CyberWI, with funding from Vinnova.

13.  References

13.1.  Normative References

   [I-D.ietf-cose-msg]
              Schaad, J., "CBOR Object Signing and Seq
      only if the message is a response (see Section 5).

      *  The size of Cid is recommended to be 64 bits, but may be
         shorter, as discussed Encryption (COSE)",
              draft-ietf-cose-msg-24 (work in Section 3.2.2

      *  The size of Seq is variable, progress), November 2016.

   [RFC2119]  Bradner, S., "Key words for use in RFCs to Indicate
              Requirement Levels", BCP 14, RFC 2119,
              DOI 10.17487/RFC2119, March 1997,
              <http://www.rfc-editor.org/info/rfc2119>.

   [RFC5869]  Krawczyk, H. and P. Eronen, "HMAC-based Extract-and-Expand
              Key Derivation Function (HKDF)", RFC 5869,
              DOI 10.17487/RFC5869, May 2010,
              <http://www.rfc-editor.org/info/rfc5869>.

   [RFC5988]  Nottingham, M., "Web Linking", RFC 5988,
              DOI 10.17487/RFC5988, October 2010,
              <http://www.rfc-editor.org/info/rfc5988>.

   [RFC6347]  Rescorla, E. and increases with the number of
         messages exchanged.

      *  As the AEAD nonce is generated from the padded Sequence Number N. Modadugu, "Datagram Transport Layer
              Security Version 1.2", RFC 6347, DOI 10.17487/RFC6347,
              January 2012, <http://www.rfc-editor.org/info/rfc6347>.

   [RFC7049]  Bormann, C. and a previously agreed upon context IV it is not required to
         send the whole nonce P. Hoffman, "Concise Binary Object
              Representation (CBOR)", RFC 7049, DOI 10.17487/RFC7049,
              October 2013, <http://www.rfc-editor.org/info/rfc7049>.

   [RFC7252]  Shelby, Z., Hartke, K., and C. Bormann, "The Constrained
              Application Protocol (CoAP)", RFC 7252,
              DOI 10.17487/RFC7252, June 2014,
              <http://www.rfc-editor.org/info/rfc7252>.

   [RFC7641]  Hartke, K., "Observing Resources in the message.

   o  The Cipher Text, excluding the Tag, is the encryption of the
      payload Constrained
              Application Protocol (CoAP)", RFC 7641,
              DOI 10.17487/RFC7641, September 2015,
              <http://www.rfc-editor.org/info/rfc7641>.

   [RFC7959]  Bormann, C. and the encrypted options Section 4, which are present Z. Shelby, Ed., "Block-Wise Transfers in
              the unprotected CoAP message.

   o  The size of the Tag depends on the Algorithm.  For example, Constrained Application Protocol (CoAP)", RFC 7959,
              DOI 10.17487/RFC7959, August 2016,
              <http://www.rfc-editor.org/info/rfc7959>.

13.2.  Informative References

   [I-D.bormann-6lo-coap-802-15-ie]
              Bormann, C., "Constrained Application Protocol (CoAP) over
              IEEE 802.15.4 Information Element for
      the algorithm AES-CCM-64-64-128, the Tag is 8 bytes.

   o  The overhead from the COSE format itself depends on the sizes of
      the previous fields, IETF", draft-
              bormann-6lo-coap-802-15-ie-00 (work in progress), April
              2016.

   [I-D.greevenbosch-appsawg-cbor-cddl]
              Vigano, C. and is of the order of 10 bytes.

A.3.  Message Expansion

   The message expansion is not the size of the COSE object.  The
   ciphertext H. Birkholz, "CBOR data definition language
              (CDDL): a notational convention to express CBOR data
              structures", draft-greevenbosch-appsawg-cbor-cddl-09 (work
              in the COSE object is encrypted payload progress), September 2016.

   [I-D.hartke-core-e2e-security-reqs]
              Selander, G., Palombini, F., and options of the
   unprotected CoAP message - the plaintext of which is removed from the
   protected K. Hartke, "Requirements
              for CoAP message.  Since the size of the ciphertext is the same
   as the corresponding plaintext, there is no message expansion due to
   encryption; payload End-To-End Security", draft-hartke-core-e2e-
              security-reqs-02 (work in progress), January 2017.

   [I-D.ietf-ace-oauth-authz]
              Seitz, L., Selander, G., Wahlstroem, E., Erdtman, S., and options are just represented
              H. Tschofenig, "Authentication and Authorization for
              Constrained Environments (ACE)", draft-ietf-ace-oauth-
              authz-05 (work in a different
   way progress), February 2017.

   [I-D.ietf-core-coap-tcp-tls]
              Bormann, C., Lemay, S., Tschofenig, H., Hartke, K.,
              Silverajan, B., and B. Raymor, "CoAP (Constrained
              Application Protocol) over TCP, TLS, and WebSockets",
              draft-ietf-core-coap-tcp-tls-07 (work in the protected CoAP message:

   o  The encrypted payload is progress), March
              2017.

   [I-D.mattsson-core-coap-actuators]
              Mattsson, J., Fornehed, J., Selander, G., and F.
              Palombini, "Controlling Actuators with CoAP", draft-
              mattsson-core-coap-actuators-02 (work in the payload progress),
              November 2016.

   [I-D.seitz-ace-oscoap-profile]
              Seitz, L. and F. Palombini, "OSCOAP profile of the protected CoAP
      message

   o  The encrypted options are ACE",
              draft-seitz-ace-oscoap-profile-01 (work in the Object-Security option or within
      the payload.

   Therefore the OSCOAP message expansion is due to Cid (if present),
   Seq, Tag, progress),
              October 2016.

   [I-D.selander-ace-cose-ecdhe]
              Selander, G., Mattsson, J., and F. Palombini, "Ephemeral
              Diffie-Hellman Over COSE overhead:

            Message Overhead = Cid + Seq + Tag + COSE Overhead

                    Figure 7: OSCOAP message expansion

A.4.  Example

   This section gives an example of message expansion (EDHOC)", draft-selander-ace-
              cose-ecdhe-04 (work in a request with
   OSCOAP.

   In this example we assume an 8-byte Cid.

   o  Cid: 0xa1534e3c9cecad84

   In the example the sequence number is 225, requiring 1 byte to
   encode.  (The size of Seq could be larger depending on how many
   messages that has been sent as is discussed progress), October 2016.

   [I-D.tiloca-core-multicast-oscoap]
              Tiloca, M., Selander, G., and F. Palombini, "Secure group
              communication for CoAP", draft-tiloca-core-multicast-
              oscoap-00 (work in progress), October 2016.

   [RFC7228]  Bormann, C., Ersue, M., and A. Keranen, "Terminology for
              Constrained-Node Networks", RFC 7228,
              DOI 10.17487/RFC7228, May 2014,
              <http://www.rfc-editor.org/info/rfc7228>.

Appendix A.2.)

   o  Seq: 225

   The example is based on AES-CCM-64-64-128.

   o  Tag is 8 bytes A.  OSCOAP Compression

   The COSE object is represented in Figure 8 using CBOR's diagnostic
   notation.

      [
        h'a20448a1534e3c9cecad840641e2', / protected:
                                            {04:h'a1534e3c9cecad84',
                                             06:h'e2'} /
        {},                              / unprotected: - /
        Ciph + Tag                       / ciphertext + 8 byte
                                            authentication tag /
      ]

                  Figure 8: Example of Concise Binary Object Representation (CBOR) combines very small
   message expansion

   Note that the encrypted CoAP options sizes with extensibility.  CBOR Object Signing and payload are omitted since we
   target the Encryption
   (COSE) uses CBOR to achieve smaller message expansion (see Appendix A.3).  Therefore the size
   of the sizes than JOSE.  COSE Cipher Text equals the size of the Tag, which is 8 bytes.

   The COSE object encodes
   however constructed to support a total size large number of 26 bytes, which different stateless
   use cases, and is the not fully optimized for use as a stateful security
   protocol, leading to a larger than necessary message expansion in expansion.  In
   this example. section we define a simple stateless compression mechanism for
   OSCOAP, which significantly reduces the per-packet overhead.

   The COSE overhead in this example
   is 26 - (8 + 1 + 8) = 9 bytes, according to value of the formula in Figure 7.

   Note that in this example two bytes Object-Security option SHALL in general be encoded
   as:

   [
     Partial IV,
     ? kid,
     ciphertext
   ]

   Furthermore, the COSE overhead are used to
   encode the type and length of Cid for the ciphertext is redundant and
   10 bits in the length of Seq.

   Figure 9 summarizes these results.

          +---------+---------+---------+----------+------------+
          |   Cid   |   Seq   |   Tag   | COSE OH  | Message OH |
          +---------+---------+---------+----------+------------+
          | 8 bytes | 1 byte  | 8 bytes |  9 bytes |  22 bytes  |
          +---------+---------+---------+----------+------------+

    Figure 9: Message overhead first two bytes are static.  The type and length for a 8-byte Cid, 1-byte Seq
   the ciphertext SHALL be excluded, and 8-byte
                                   Tag. the first sixteen bits in the
   above COSE array SHALL be encoded as a single byte:

   10000abc 01000def -> 00abcdef

   The exception is Responses without Observe that SHALL be encoded as:

   ciphertext

A.1.  Examples

A.1.1.  Example Request

   COSE Object Before Compression (24 bytes)
   83 a2 04 41 25 06 41 05 a0 4e ae a0 15 56 67 92
   4d ff 8a 24 e4 cb 35 b9

   [
   {
     4:h'25',
     6:h'05'
   },
   {},
   h'aea0155667924dff8a24e4cb35b9'
   ]

   After Compression (18 bytes)
   19 05 41 25 ae a0 15 56 67 92 4d ff 8a 24 e4 cb
   35 b9

A.1.2.  Example Response

   COSE Object Before Compression (18 bytes)
   83 a0 a0 4e ae a0 15 56 67 92 4d ff 8a 24 e4 cb
   35 b9

   [
   {},
   {},
   h'aea0155667924dff8a24e4cb35b9'
   ]

   After Compression (14 bytes)
   ae a0 15 56 67 92 4d ff 8a 24 e4 cb 35 b9

A.1.3.  Example Response (with Observe)
   COSE Object Before Compression (21 bytes)
   83 a1 06 41 07 a0 4e ae a0 15 56 67 92 4d ff 8a
   24 e4 cb 35 b9

   [
   {
     6:h'07'
   },
   {},
   h'aea0155667924dff8a24e4cb35b9'
   ]

   After Compression (16 bytes)
   11 07 ae a0 15 56 67 92 4d ff 8a 24 e4 cb 35 b9

Appendix B.  Test Vectors

   TODO: This section needs to be updated.

Appendix C.  Examples

   This section gives examples of OSCOAP.  The message exchanges are
   made, based on the assumption that there is a security context
   established between client and server.  For simplicity, these
   examples only indicate the content of the messages without going into
   detail of the COSE message format.

B.1.

C.1.  Secure Access to Sensor

   Here is an

   This example targeting targets the scenario in the Section 2.2.1. -
   Forwarding 3.1 of [I-D.hartke-core-e2e-security-reqs].  The example
   [I-D.hartke-core-e2e-security-reqs] and illustrates a client
   requesting the alarm status from a server.  In
   the request, CoAP option Uri-Path is encrypted and integrity
   protected, and the CoAP header fields Code and Version are integrity
   protected (see Section 4).  In the response, the CoAP Payload is
   encrypted and integrity protected, and the CoAP header fields Code
   and Version are integrity protected.

      Client  Proxy  Server
         |      |      |
         +----->|      |            Code: 0.01 (GET)
         | GET  |      |           Token: 0x8c
         |      |      | Object-Security: [cid:5fdc, [kid:5f, seq:42,
         |      |      |                   {Uri-Path:"alarm_status"},
         |      |      |                   <Tag>]                   {Uri-Path:"alarm_status"}]
         |      |      |         Payload: -
         |      |      |
         |      +----->|            Code: 0.01 (GET)
         |      | GET  |           Token: 0x7b
         |      |      | Object-Security: [cid:5fdc, [kid:5f, seq:42,
         |      |      |                   {Uri-Path:"alarm_status"},
         |      |      |                   <Tag>]                   {Uri-Path:"alarm_status"}]
         |      |      |         Payload: -
         |      |      |
         |      |<-----+            Code: 2.05 (Content)
         |      | 2.05 |           Token: 0x7b
         |      |      |         Max-Age: 0
         |      |      | Object-Security: -
         |      |      |         Payload: [seq:56, {"OFF"}, <Tag>] [{"OFF"}]
         |      |      |
         |<-----+      |            Code: 2.05 (Content)
         | 2.05 |      |           Token: 0x8c
         |      |      |         Max-Age: 0
         |      |      | Object-Security: -
         |      |      |         Payload: [seq:56, {"OFF"}, <Tag>] [{"OFF"}]
         |      |      |

   Figure 10: Indication of CoAP GET protected with OSCOAP.  The 6: Secure Access to Sensor.  Square brackets [ ... ] indicate
      a COSE object.  The  Curly brackets { ... } indicate encrypted data.

   Since the unprotected request message method (GET) has no doesn't allow payload, the Object-Security
   option carries the COSE object as its value.  Since the unprotected response message code
   (Content) has payload ("OFF"), allows payload, the COSE object (indicated with [ ... ]) is carried as the CoAP
   payload.

   The COSE header of the request contains a Context Identifier
   (cid:5fdc), an identifier (5f),
   indicating which security context was used to protect the message and
   a Sequence Number (seq:42). sequence number (42).  The option Uri-Path (alarm_status) ("alarm_status") and
   payload ("OFF") are formatted
   as indicated in Section 5, and encrypted in the COSE Cipher Text
   (indicated with { ... }).

   The server verifies that the Sequence Number has not been received
   before (see Section 6.1). ("OFF") are encrypted.

   The client server verifies that the Sequence
   Number sequence number has not been received before and
   before.  The client verifies that the response message is
   generated as a response bound to the sent request message (see
   Section 6.1).

B.2.
   request.

C.2.  Secure Subscribe to Sensor

   Here is an

   This example targeting targets the scenario in the Forwarding with
   observe case Section 3.2 of [I-D.hartke-core-e2e-security-reqs].  The example
   [I-D.hartke-core-e2e-security-reqs] and illustrates a client
   requesting subscription to a blood sugar measurement resource (GET
   /glucose), and first receiving the value 220 mg/dl, mg/dl and then a second reading with
   value 180 mg/dl.  The CoAP
   options Observe, Uri-Path, Content-Format, and Payload are encrypted
   and integrity protected, and the CoAP header field Code is integrity
   protected (see Section 4).

 Client  Proxy  Server
    |      |      |
    +----->|      |            Code: 0.01 (GET)
    | GET  |      |           Token: 0x83
    |      |      |         Observe: 0
    |      |      | Object-Security: [cid:ca, seq:15b7, {Observe:0, [kid:ca, seq:15,
    |      |      |                   Uri-Path:"glucose"}, <Tag>]                   {Uri-Path:"glucose"}]
    |      |      |         Payload: -
    |      |      |
    |      +----->|            Code: 0.01 (GET)
    |      | GET  |           Token: 0xbe
    |      |      |         Observe: 0
    |      |      | Object-Security: [cid:ca, seq:15b7, {Observe:0, [kid:ca, seq:15,
    |      |      |                   Uri-Path:"glucose"}, <Tag>]                   {Uri-Path:"glucose"}]
    |      |      |         Payload: -
    |      |      |
    |      |<-----+            Code: 2.05 (Content)
    |      | 2.05 |           Token: 0xbe
    |      |      |         Max-Age: 0
      |      |      |         Observe: 1 000032
    |      |      | Object-Security: -
    |      |      |         Payload: [seq:32c2, {Observe:1,
      |      |      |                   Content-Format:0, "220"}, <Tag>] [seq:32, {Content-Format:0, "220"}]
    |      |      |
    |<-----+      |            Code: 2.05 (Content)
    | 2.05 |      |           Token: 0x83
    |      |      |         Max-Age: 0
      |      |      |         Observe: 1 000032
    |      |      | Object-Security: -
    |      |      |         Payload: [seq:32c2, {Observe:1,
      |      |      |                   Content-Format:0, "220"}, <Tag>] [seq:32, {Content-Format:0, "220"}]
   ...    ...    ...
    |      |      |
    |      |<-----+            Code: 2.05 (Content)
    |      | 2.05 |           Token: 0xbe
    |      |      |         Max-Age: 0
      |      |      |         Observe: 2 000036
    |      |      | Object-Security: -
    |      |      |         Payload: [seq:32c6, {Observe:2,
      |      |      |                   Content-Format:0, "180"}, <Tag>] [seq:36, {Content-Format:0, "180"}]
    |      |      |
    |<-----+      |            Code: 2.05 (Content)
    | 2.05 |      |           Token: 0x83
    |      |      |         Max-Age: 0
      |      |      |         Observe: 2 000036
    |      |      | Object-Security: -
    |      |      |         Payload: [seq:32c6, {Observe:2,
      |      |      |                   Content-Format:0, "180"}, <Tag>] [seq:36, {Content-Format:0, "180"}]
    |      |      |

      Figure 11: Indication of CoAP GET protected with OSCOAP.  The 7: Secure Subscribe to Sensor.  Square brackets [ ... ] indicates
    indicate a COSE object.  The bracket  Curly brackets { ... }
                         indicates indicate encrypted
                                   data.

   Since the unprotected request message method (GET) allows no doesn't allow payload, the Object-Security
   option carries the COSE object (indicated with [ ... ]) is carried in the Object-
   Security option as its value.  Since the unprotected response message code
   (Content) has allows payload, the Object-Security option is empty, and the COSE object is carried as the CoAP
   payload.

   The COSE header of the request contains a Context Identifier
   (cid:ca), an identifier (ca),
   indicating which the security context was used to protect the message and a
   Sequence Number (seq:15b7). (15).  The COSE header of the responses contains
   sequence numbers (32 and 36).  The options Observe, Content-Format (0) and the
   payload ("220" and "180"), are formatted as
   indicated in Section 5, encrypted.  The Observe option is
   integrity protected.  The shown Observe values (000032 and encrypted in 000036)
   are the COSE ciphertext
   (indicated with { ... }). ones that the client will see after OSCOAP processing.

   The server verifies that the Sequence Number sequence number has not been received
   before (see Section 6.1).
   before.  The client verifies that the Sequence
   Number sequence number has not been
   received before and that the response message is
   generated as a response responses are bound to the subscribe request.

Appendix C. D.  Object Security of Content (OSCON)

   TODO: This section needs to be updated.

   OSCOAP protects message exchanges end-to-end between a certain client
   and a certain server, targeting the security requirements for forward
   proxy of [I-D.hartke-core-e2e-security-reqs].  In contrast, many use
   cases require one and the same message to be protected for, and
   verified by, multiple endpoints, see caching proxy section of
   [I-D.hartke-core-e2e-security-reqs].  Those security requirements can
   be addressed by protecting essentially the payload/content of
   individual messages using the COSE format ([I-D.ietf-cose-msg]),
   rather than the entire request/response message exchange.  This is
   referred to as Object Security of Content (OSCON).

   OSCON transforms an unprotected CoAP message into a protected CoAP
   message in the following way: the payload of the unprotected CoAP
   message is wrapped by a COSE object, which replaces the payload of
   the unprotected CoAP message.  We call the result the "protected"
   CoAP message.

   The unprotected payload shall be the plaintext/payload of the COSE
   object.  The 'protected' field of the COSE object 'Headers' shall
   include the context identifier, both for requests and responses.  If
   the unprotected CoAP message includes a Content-Format option, then
   the COSE object shall include a protected 'content type' field, whose
   value is set to the unprotected message Content-Format value.  The
   Content-Format option of the protected CoAP message shall be replaced
   with "application/oscon" (Section 9) 11)
   The COSE object shall be protected (encrypted) and verified
   (decrypted) as described in ([I-D.ietf-cose-msg]).

   Most AEAD algorithms require a unique nonce for each message.
   Sequence numbers for partial IV as specified for OSCOAP may be used
   for replay protection as described in Section 6.1. 6.  The use of time
   stamps in the COSE header parameter 'operation time'
   [I-D.ietf-cose-msg] for freshness may be used.

   OSCON shall not be used in cases where CoAP header fields (such as
   Code or Version) or CoAP options need to be integrity protected or
   encrypted.  OSCON shall not be used in cases which require a secure
   binding between request and response.

   The scenarios in Sections 3.3 - 3.5 of
   [I-D.hartke-core-e2e-security-reqs] assume multiple recipients for a
   particular content.  In this case the use of symmetric keys does not
   provide data origin authentication.  Therefore the COSE object should
   in general be protected with a digital signature.

C.1.

D.1.  Overhead OSCON

   In general there are four different kinds of modes that need to be
   supported: message authentication code, digital signature,
   authenticated encryption, and symmetric encryption + digital
   signature.  The use of digital signature is necessary for
   applications with many legitimate recipients of a given message, and
   where data origin authentication is required.

   To distinguish between these different cases, the tagged structures
   of COSE are used (see Section 2 of [I-D.ietf-cose-msg]).

   The sizes of COSE messages for selected algorithms are detailed in
   this section.

   The size of the header is shown separately from the size of the MAC/
   signature.  A 4-byte Context Identifier and a 1-byte Sequence Number
   are used throughout all examples, with these values:

   o  Cid: 0xa1534e3c

   o  Seq: 0xa3

   For each scheme, we indicate the fixed length of these two parameters
   ("Cid+Seq" column) and of the Tag ("MAC"/"SIG"/"TAG").  The "Message
   OH" column shows the total expansions of the CoAP message size, while
   the "COSE OH" column is calculated from the previous columns
   following the formula in Figure 7. columns.

   Overhead incurring from CBOR encoding is also included in the COSE
   overhead count.

   To make it easier to read, COSE objects are represented using CBOR's
   diagnostic notation rather than a binary dump.

C.2.

D.2.  MAC Only

   This example is based on HMAC-SHA256, with truncation to 8 bytes
   (HMAC 256/64).

   Since the key is implicitly known by the recipient, the
   COSE_Mac0_Tagged structure is used (Section 6.2 of
   [I-D.ietf-cose-msg]).

   The object in COSE encoding gives:

            996(                         # COSE_Mac0_Tagged
              [
                h'a20444a1534e3c0641a3', # protected:
                                           {04:h'a1534e3c',
                                            06:h'a3'}
                {},                      # unprotected
                h'',                     # payload
                MAC                      # truncated 8-byte MAC
              ]
            )

   This COSE object encodes to a total size of 26 bytes.

   Figure 12 8 summarizes these results.

          +------------------+-----+-----+---------+------------+
          |     Structure    | Tid | MAC | COSE OH | Message OH |
          +------------------+-----+-----+---------+------------+
          | COSE_Mac0_Tagged | 5 B | 8 B |   13 B  |    26 B    |
          +------------------+-----+-----+---------+------------+

       Figure 12: 8: Message overhead for a 5-byte Tid using HMAC 256/64

C.3.

D.3.  Signature Only

   This example is based on ECDSA, with a signature of 64 bytes.

   Since only one signature is used, the COSE_Sign1_Tagged structure is
   used (Section 4.2 of [I-D.ietf-cose-msg]).

   The object in COSE encoding gives:

             997(                         # COSE_Sign1_Tagged
               [
                 h'a20444a1534e3c0641a3', # protected:
                                            {04:h'a1534e3c',
                                             06:h'a3'}
                 {},                      # unprotected
                 h'',                     # payload
                 SIG                      # 64-byte signature
               ]
             )

   This COSE object encodes to a total size of 83 bytes.

   Figure 13 9 summarizes these results.

         +-------------------+-----+------+---------+------------+
         |     Structure     | Tid |  SIG | COSE OH | Message OH |
         +-------------------+-----+------+---------+------------+
         | COSE_Sign1_Tagged | 5 B | 64 B |   14 B  |  83 bytes  |
         +-------------------+-----+------+---------+------------+

      Figure 13: 9: Message overhead for a 5-byte Tid using 64 byte ECDSA
                                signature.

C.4.

D.4.  Authenticated Encryption with Additional Data (AEAD)

   This example is based on AES-CCM with the Tag truncated to 8 bytes.

   Since the key is implicitly known by the recipient, the
   COSE_Encrypt0_Tagged structure is used (Section 5.2 of
   [I-D.ietf-cose-msg]).

   The object in COSE encoding gives:

     993(                         # COSE_Encrypt0_Tagged
       [
         h'a20444a1534e3c0641a3', # protected:
                                    {04:h'a1534e3c',
                                     06:h'a3'}
         {},                      # unprotected
         TAG                      # ciphertext + truncated 8-byte TAG
       ]
     )

   This COSE object encodes to a total size of 25 bytes.

   Figure 14 10 summarizes these results.

        +----------------------+-----+-----+---------+------------+
        |       Structure      | Tid | TAG | COSE OH | Message OH |
        +----------------------+-----+-----+---------+------------+
        | COSE_Encrypt0_Tagged | 5 B | 8 B |   12 B  |  25 bytes  |
        +----------------------+-----+-----+---------+------------+

     Figure 14: 10: Message overhead for a 5-byte Tid using AES_128_CCM_8.

C.5.

D.5.  Symmetric Encryption with Asymmetric Signature (SEAS)

   This example is based on AES-CCM and ECDSA with 64 bytes signature.
   The same assumption on the security context as in Appendix C.4. D.4.  COSE
   defines the field 'counter signature w/o headers' that is used here
   to sign a COSE_Encrypt0_Tagged message (see Section 3 of
   [I-D.ietf-cose-msg]).

   The object in COSE encoding gives:

     993(                         # COSE_Encrypt0_Tagged
       [
         h'a20444a1534e3c0641a3', # protected:
                                    {04:h'a1534e3c',
                                     06:h'a3'}
         {9:SIG},                 # unprotected:
                                     09: 64 bytes signature
         TAG                      # ciphertext + truncated 8-byte TAG
       ]
     )

   This COSE object encodes to a total size of 92 bytes.

   Figure 15 11 summarizes these results.

    +----------------------+-----+-----+------+---------+------------+
    |       Structure      | Tid | TAG | SIG  | COSE OH | Message OH |
    +----------------------+-----+-----+------+---------+------------+
    | COSE_Encrypt0_Tagged | 5 B | 8 B | 64 B |   15 B  |    92 B    |
    +----------------------+-----+-----+------+---------+------------+

        Figure 15: 11: Message overhead for a 5-byte Tid using AES-CCM
                         countersigned with ECDSA.

Authors' Addresses

   Goeran Selander
   Ericsson AB
   Farogatan 6
   Kista  SE-16480 Stockholm
   Sweden

   Email: goran.selander@ericsson.com
   John Mattsson
   Ericsson AB
   Farogatan 6
   Kista  SE-16480 Stockholm
   Sweden

   Email: john.mattsson@ericsson.com

   Francesca Palombini
   Ericsson AB
   Farogatan 6
   Kista  SE-16480 Stockholm
   Sweden

   Email: francesca.palombini@ericsson.com

   Ludwig Seitz
   SICS Swedish ICT
   Scheelevagen 17
   Lund  22370
   Sweden

   Email: ludwig@sics.se