RFC 8949: STD 94: Concise Binary Object Representation (CBOR)
- C. Bormann,
- P. Hoffman
Abstract
The Concise Binary Object Representation (CBOR) is a data format whose design goals include the possibility of extremely small code size, fairly small message size, and extensibility without the need for version negotiation. These design goals make it different from earlier binary serializations such as ASN.1 and MessagePack.¶
This document obsoletes RFC 7049, providing editorial improvements, new details, and errata fixes while keeping full compatibility with the interchange format of RFC 7049. It does not create a new version of the format.¶
Status of This Memo
This is an Internet Standards Track document.¶
This document is a product of the Internet Engineering Task Force (IETF). It represents the consensus of the IETF community. It has received public review and has been approved for publication by the Internet Engineering Steering Group (IESG). Further information on Internet Standards is available in Section 2 of RFC 7841.¶
Information about the current status of this document, any
errata, and how to provide feedback on it may be obtained at
https://
Copyright Notice
Copyright (c) 2020 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
(https://
1. Introduction
There are hundreds of standardized formats for binary representation of structured data (also known as binary serialization formats). Of those, some are for specific domains of information, while others are generalized for arbitrary data. In the IETF, probably the best-known formats in the latter category are ASN.1's BER and DER [ASN.1].¶
The format defined here follows some specific design goals that are not well met by current formats. The underlying data model is an extended version of the JSON data model [RFC8259]. It is important to note that this is not a proposal that the grammar in RFC 8259 be extended in general, since doing so would cause a significant backwards incompatibility with already deployed JSON documents. Instead, this document simply defines its own data model that starts from JSON.¶
Appendix E lists some existing binary formats and discusses how well they do or do not fit the design objectives of the Concise Binary Object Representation (CBOR).¶
This document obsoletes [RFC7049], providing editorial improvements, new details, and errata fixes while keeping full compatibility with the interchange format of RFC 7049. It does not create a new version of the format.¶
1.1. Objectives
The objectives of CBOR, roughly in decreasing order of importance, are:¶
1.2. Terminology
The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in BCP 14 [RFC2119] [RFC8174] when, and only when, they appear in all capitals, as shown here.¶
The term "byte" is used in its now-customary sense as a synonym for "octet". All multi-byte values are encoded in network byte order (that is, most significant byte first, also known as "big-endian").¶
This specification makes use of the following terminology:¶
- Data item:
- A single piece of CBOR data. The structure of a data item may contain zero, one, or more nested data items. The term is used both for the data item in representation format and for the abstract idea that can be derived from that by a decoder; the former can be addressed specifically by using the term "encoded data item".¶
- Decoder:
- A process that decodes a well-formed encoded CBOR data item and makes it available to an application. Formally speaking, a decoder contains a parser to break up the input using the syntax rules of CBOR, as well as a semantic processor to prepare the data in a form suitable to the application.¶
- Encoder:
- A process that generates the (well-formed) representation format of a CBOR data item from application information.¶
- Data Stream:
- A sequence of zero or more data items, not further assembled into a larger containing data item (see [RFC8742] for one application). The independent data items that make up a data stream are sometimes also referred to as "top-level data items".¶
- Well-formed:
- A data item that follows the syntactic structure of CBOR. A well-formed data item uses the initial bytes and the byte strings and/or data items that are implied by their values as defined in CBOR and does not include following extraneous data. CBOR decoders by definition only return contents from well-formed data items.¶
- Valid:
- A data item that is well-formed and also follows the semantic restrictions that apply to CBOR data items (Section 5.3).¶
- Expected:
-
Besides its normal English meaning, the term "expected" is used to
describe requirements beyond CBOR validity that an application has
on its input data. Well-formed (processable at all), valid (checked
by a validity
-checking generic decoder), and expected (checked by the application) form a hierarchy of layers of acceptability.¶ - Stream decoder:
- A process that decodes a data stream and makes each of the data items in the sequence available to an application as they are received.¶
Terms and concepts for floating-point values such as Infinity, NaN (not a number), negative zero, and subnormal are defined in [IEEE754].¶
Where bit arithmetic or data types are explained, this document uses the notation familiar from the programming language C [C], except that ".." denotes a range that includes both ends given, and superscript notation denotes exponentiation. For example, 2 to the power of 64 is notated: 264. In the plain-text version of this specification, superscript notation is not available and therefore is rendered by a surrogate notation. That notation is not optimized for this RFC; it is unfortunately ambiguous with C's exclusive-or (which is only used in the appendices, which in turn do not use exponentiation) and requires circumspection from the reader of the plain-text version.¶
Examples and pseudocode
assume that signed integers use two's complement representation and
that right shifts of signed integers perform sign extension; these
assumptions are also specified in Sections 6.8.1
Similar to the "0x" notation for hexadecimal numbers, numbers in binary notation are prefixed with "0b". Underscores can be added to a number solely for readability, so 0b00100001 (0x21) might be written 0b001_00001 to emphasize the desired interpretation of the bits in the byte; in this case, it is split into three bits and five bits. Encoded CBOR data items are sometimes given in the "0x" or "0b" notation; these values are first interpreted as numbers as in C and are then interpreted as byte strings in network byte order, including any leading zero bytes expressed in the notation.¶
Words may be italicized for emphasis; in the plain text
form of this specification, this is indicated by surrounding words
with underscore characters. Verbatim text (e.g., names from a
programming language) may be set in monospace type; in plain
text, this is approximated somewhat ambiguously by surrounding the
text in double quotes (which also retain their usual meaning).¶
2. CBOR Data Models
CBOR is explicit about its generic data model, which defines the set of all data items that can be represented in CBOR. Its basic generic data model is extensible by the registration of "simple values" and tags. Applications can then create a subset of the resulting extended generic data model to build their specific data models.¶
Within environments that can represent the data items in the generic
data model, generic CBOR encoders and decoders can be implemented
(which usually involves defining additional implementation data types
for those data items that do not already have a natural representation
in the environment). The ability to provide generic encoders and
decoders is an explicit design goal of CBOR; however, many applications
will provide their own application
In the basic (unextended) generic data model defined in Section 3, a data item is one of the following:¶
Note that integer and floating-point values are distinct in this model, even if they have the same numeric value.¶
Also note that serialization variants are not visible at the generic data model level. This deliberate absence of visibility includes the number of bytes of the encoded floating-point value. It also includes the choice of encoding for an "argument" (see Section 3) such as the encoding for an integer, the encoding for the length of a text or byte string, the encoding for the number of elements in an array or pairs in a map, or the encoding for a tag number.¶
2.1. Extended Generic Data Models
This basic generic data model has been extended in this document by the registration of a number of simple values and tag numbers, such as:¶
Additional elements of the extended generic data model can be (and have been) defined via the IANA registries created for CBOR. Even if such an extension is unknown to a generic encoder or decoder, data items using that extension can be passed to or from the application by representing them at the application interface within the basic generic data model, i.e., as generic simple values or generic tags.¶
In other words, the basic generic data model is stable as defined in this document, while the extended generic data model expands by the registration of new simple values or tag numbers, but never shrinks.¶
While there is a strong expectation that generic encoders and decoders
can represent false, true, and null (undefined is intentionally
omitted) in the form appropriate for their programming environment,
the implementation of the data model extensions created by tags is truly
optional and a matter of implementation quality.¶
2.2. Specific Data Models
The specific data model for a CBOR-based protocol usually takes a subset of the extended generic data model and assigns application semantics to the data items within this subset and its components. When documenting such specific data models and specifying the types of data items, it is preferable to identify the types by their generic data model names ("negative integer", "array") instead of referring to aspects of their CBOR representation ("major type 1", "major type 4").¶
Specific data models can also specify value equivalency (including
values of different types) for the purposes of map keys and encoder freedom. For
example, in the generic data model, a valid map MAY have both 0 and
0.0 as keys, and an encoder MUST NOT encode 0.0 as an integer
(major type 0, Section 3.1). However, if a specific data model
declares that floating-point and integer representations of integral
values are equivalent, using both map keys 0 and 0.0 in a single
map would be considered
duplicates, even while encoded as different major types, and so invalid; and an encoder could encode integral-valued
floats as integers or vice versa, perhaps to save encoded bytes.¶
3. Specification of the CBOR Encoding
A CBOR data item (Section 2) is encoded to or decoded from a byte string carrying a well-formed encoded data item as described in this section. The encoding is summarized in Table 7 in Appendix B, indexed by the initial byte. An encoder MUST produce only well-formed encoded data items. A decoder MUST NOT return a decoded data item when it encounters input that is not a well-formed encoded CBOR data item (this does not detract from the usefulness of diagnostic and recovery tools that might make available some information from a damaged encoded CBOR data item).¶
The initial byte of each encoded data item contains both information about the major type (the high-order 3 bits, described in Section 3.1) and additional information (the low-order 5 bits). With a few exceptions, the additional information's value describes how to load an unsigned integer "argument":¶
- Less than 24:
- The argument's value is the value of the additional information.¶
- 24, 25, 26, or 27:
- The argument's value is held in the following 1, 2, 4, or 8 bytes, respectively, in network byte order. For major type 7 and additional information value 25, 26, 27, these bytes are not used as an integer argument, but as a floating-point value (see Section 3.3).¶
- 28, 29, 30:
- These values are reserved for future additions to the CBOR format. In the present version of CBOR, the encoded item is not well-formed.¶
- 31:
-
No argument value is derived.
If the major type is 0, 1, or 6, the encoded item is not
well-formed. For major types 2 to 5, the item's length is
indefinite, and for major type 7, the byte does not constitute a data
item at all but terminates an indefinite
-length item; all are described in Section 3.2.¶
The initial byte and any additional bytes consumed to construct the argument are collectively referred to as the head of the data item.¶
The meaning of this argument depends on the major type. For example, in major type 0, the argument is the value of the data item itself (and in major type 1, the value of the data item is computed from the argument); in major type 2 and 3, it gives the length of the string data in bytes that follow; and in major types 4 and 5, it is used to determine the number of data items enclosed.¶
If the encoded sequence of bytes ends before the end of a data item, that item is not well-formed. If the encoded sequence of bytes still has bytes remaining after the outermost encoded item is decoded, that encoding is not a single well-formed CBOR item. Depending on the application, the decoder may either treat the encoding as not well-formed or just identify the start of the remaining bytes to the application.¶
A CBOR decoder implementation can be based on a jump table with all 256 defined values for the initial byte (Table 7). A decoder in a constrained implementation can instead use the structure of the initial byte and following bytes for more compact code (see Appendix C for a rough impression of how this could look).¶
3.1. Major Types
The following lists the major types and the additional information and other bytes associated with the type.¶
- Major type 0:
- An unsigned integer in the range 0..264-1 inclusive. The value of the encoded item is the argument itself. For example, the integer 10 is denoted as the one byte 0b000_01010 (major type 0, additional information 10). The integer 500 would be 0b000_11001 (major type 0, additional information 25) followed by the two bytes 0x01f4, which is 500 in decimal.¶
- Major type 1:
- A negative integer in the range -264..-1 inclusive. The value of the item is -1 minus the argument. For example, the integer -500 would be 0b001_11001 (major type 1, additional information 25) followed by the two bytes 0x01f3, which is 499 in decimal.¶
- Major type 2:
- A byte string. The number of bytes in the string is equal to the argument. For example, a byte string whose length is 5 would have an initial byte of 0b010_00101 (major type 2, additional information 5 for the length), followed by 5 bytes of binary content. A byte string whose length is 500 would have 3 initial bytes of 0b010_11001 (major type 2, additional information 25 to indicate a two-byte length) followed by the two bytes 0x01f4 for a length of 500, followed by 500 bytes of binary content.¶
- Major type 3:
- A text string (Section 2) encoded as UTF-8 [RFC3629]. The number of bytes in the string is equal to the argument. A string containing an invalid UTF-8 sequence is well-formed but invalid (Section 1.2). This type is provided for systems that need to interpret or display human-readable text, and allows the differentiation between unstructured bytes and text that has a specified repertoire (that of Unicode) and encoding (UTF-8). In contrast to formats such as JSON, the Unicode characters in this type are never escaped. Thus, a newline character (U+000A) is always represented in a string as the byte 0x0a, and never as the bytes 0x5c6e (the characters "\" and "n") nor as 0x5c7530303061 (the characters "\", "u", "0", "0", "0", and "a").¶
- Major type 4:
- An array of data items. In other formats, arrays are also called lists, sequences, or tuples (a "CBOR sequence" is something slightly different, though [RFC8742]). The argument is the number of data items in the array. Items in an array do not need to all be of the same type. For example, an array that contains 10 items of any type would have an initial byte of 0b100_01010 (major type 4, additional information 10 for the length) followed by the 10 remaining items.¶
- Major type 5:
- A map of pairs of data items. Maps are also called tables, dictionaries, hashes, or objects (in JSON). A map is comprised of pairs of data items, each pair consisting of a key that is immediately followed by a value. The argument is the number of pairs of data items in the map. For example, a map that contains 9 pairs would have an initial byte of 0b101_01001 (major type 5, additional information 9 for the number of pairs) followed by the 18 remaining items. The first item is the first key, the second item is the first value, the third item is the second key, and so on. Because items in a map come in pairs, their total number is always even: a map that contains an odd number of items (no value data present after the last key data item) is not well-formed. A map that has duplicate keys may be well-formed, but it is not valid, and thus it causes indeterminate decoding; see also Section 5.6.¶
- Major type 6:
- A tagged data item ("tag") whose tag number, an integer in the range 0..264-1 inclusive, is the argument and whose enclosed data item (tag content) is the single encoded data item that follows the head. See Section 3.4.¶
- Major type 7:
- Floating-point numbers and simple values, as well as the "break" stop code. See Section 3.3.¶
These eight major types lead to a simple table showing which of the 256 possible values for the initial byte of a data item are used (Table 7).¶
In major types 6 and 7, many of the possible values are reserved for future specification. See Section 9 for more information on these values.¶
Table 1 summarizes the major types defined by CBOR, ignoring Section 3.2 for now. The number N in this table stands for the argument.¶
3.2. Indefinite Lengths for Some Major Types
Four CBOR items (arrays, maps, byte strings, and text strings) can be encoded with an indefinite length using additional information value 31. This is useful if the encoding of the item needs to begin before the number of items inside the array or map, or the total length of the string, is known. (The ability to start sending a data item before all of it is known is often referred to as "streaming" within that data item.)¶
Indefinite
3.2.1. The "break" Stop Code
The "break" stop code is encoded with major type 7 and additional
information value 31 (0b111_11111). It is not itself a data item: it
is just a syntactic feature to close an indefinite
If the "break" stop code appears where a data item is expected,
other than directly inside an indefinite
3.2.2. Indefinite-Length Arrays and Maps
Indefinite
If the "break" stop code appears after a key in a map, in place of that key's value, the map is not well-formed.¶
There is no restriction against nesting indefinite
For example, assume an encoder wants to represent the abstract array
[1, [2, 3], [4, 5]]. The definite-length encoding would be
0x8301820203820
Indefinite
An example of an indefinite
3.2.3. Indefinite-Length Byte Strings and Text Strings
Indefinite
If any item between the indefinite
The design does not allow nesting
indefinite
If any definite-length text string inside an indefinite
For example, assume an encoded data item consisting of the bytes:¶
After decoding, this results in a single byte string with seven bytes:
0xaabbccddeeff9
3.2.4. Summary of Indefinite-Length Use of Major Types
Table 2 summarizes the major types defined by CBOR as
used for indefinite
3.3. Floating-Point Numbers and Values with No Content
Major type 7 is for two types of data: floating-point numbers and "simple values" that do not need any content. Each value of the 5-bit additional information in the initial byte has its own separate meaning, as defined in Table 3. Like the major types for integers, items of this major type do not carry content data; all the information is in the initial bytes (the head).¶
As with all other major types, the 5-bit value 24 signifies a single-byte extension: it is followed by an additional byte to represent the simple value. (To minimize confusion, only the values 32 to 255 are used.) This maintains the structure of the initial bytes: as for the other major types, the length of these always depends on the additional information in the first byte. Table 4 lists the numeric values assigned and available for simple values.¶
An encoder MUST NOT issue two-byte sequences that
start with 0xf8 (major type 7, additional information 24) and continue
with a byte less than 0x20 (32 decimal). Such sequences are not
well-formed. (This implies that an encoder cannot encode false, true,
null, or undefined in two-byte sequences and that only the one-byte
variants of these are well-formed; more generally speaking, each
simple value only has a single representation variant).¶
The 5-bit values of 25, 26, and 27 are for 16-bit, 32-bit, and 64-bit IEEE 754 binary floating-point values [IEEE754]. These floating-point values are encoded in the additional bytes of the appropriate size. (See Appendix D for some information about 16-bit floating-point numbers.)¶
4. Serialization Considerations
4.1. Preferred Serialization
For some values at the data model level, CBOR provides multiple serializations. For many applications, it is desirable that an encoder always chooses a preferred serialization (preferred encoding); however, the present specification does not put the burden of enforcing this preference on either the encoder or decoder.¶
Some constrained decoders may be limited in their ability to decode non-preferred serializations: for example, if only integers below 1_000_000_000 (one billion) are expected in an application, the decoder may leave out the code that would be needed to decode 64-bit arguments in integers. An encoder that always uses preferred serialization ("preferred encoder") interoperates with this decoder for the numbers that can occur in this application. Generally speaking, a preferred encoder is more universally interoperable (and also less wasteful) than one that, say, always uses 64-bit integers.¶
Similarly, a constrained encoder may be limited in the variety of
representation variants it supports such that it does not
emit preferred serializations ("variant encoder"). For instance, a constrained encoder could
be designed to
always use the 32-bit variant for an integer that it encodes even if a
short representation is available (assuming that there is no application need for integers that can only
be represented with the 64-bit variant).
A decoder that does not rely on
receiving only preferred serializations
The preferred serialization always uses the shortest form of representing the argument (Section 3); it also uses the shortest floating-point encoding that preserves the value being encoded.¶
The preferred serialization for a floating-point value is the shortest floating-point encoding that preserves its value, e.g., 0xf94580 for the number 5.5, and 0xfa45ad9c00 for the number 5555.5. For NaN values, a shorter encoding is preferred if zero-padding the shorter significand towards the right reconstitutes the original NaN value (for many applications, the single NaN encoding 0xf97e00 will suffice).¶
Definite-length encoding is preferred whenever the length is known at the time the serialization of the item starts.¶
4.2. Deterministically Encoded CBOR
Some protocols may want encoders to only emit CBOR in a particular deterministic format; those protocols might also have the decoders check that their input is in that deterministic format. Those protocols are free to define what they mean by a "deterministic format" and what encoders and decoders are expected to do. This section defines a set of restrictions that can serve as the base of such a deterministic format.¶
4.2.1. Core Deterministic Encoding Requirements
A CBOR encoding satisfies the "core deterministic encoding requirements" if it satisfies the following restrictions:¶
4.2.2. Additional Deterministic Encoding Considerations
CBOR tags present additional considerations for deterministic encoding. If a CBOR-based protocol were to provide the same semantics for the presence and absence of a specific tag (e.g., by allowing both tag 1 data items and raw numbers in a date/time position, treating the latter as if they were tagged), the deterministic format would not allow the presence of the tag, based on the "shortest form" principle. For example, a protocol might give encoders the choice of representing a URL as either a text string or, using Section 3.4.5.3, tag number 32 containing a text string. This protocol's deterministic encoding needs either to require that the tag is present or to require that it is absent, not allow either one.¶
In a protocol that does require tags in certain places to obtain specific semantics, the tag needs to appear in the deterministic format as well. Deterministic encoding considerations also apply to the content of tags.¶
If a protocol includes a field that can express integers with an absolute value of 264 or larger using tag numbers 2 or 3 (Section 3.4.3), the protocol's deterministic encoding needs to specify whether smaller integers are also expressed using these tags or using major types 0 and 1. Preferred serialization uses the latter choice, which is therefore recommended.¶
Protocols that include floating-point values, whether represented using basic floating-point values (Section 3.3) or using tags (or both), may need to define extra requirements on their deterministic encodings, such as:¶
4.2.3. Length-First Map Key Ordering
The core deterministic encoding requirements (Section 4.2.1) sort map keys in a different order from the one suggested by Section 3.9 of [RFC7049] (called "Canonical CBOR" there). Protocols that need to be compatible with the order specified in [RFC7049] can instead be specified in terms of this specification's "length-first core deterministic encoding requirements":¶
A CBOR encoding satisfies the "length-first core deterministic encoding requirements" if it satisfies the core deterministic encoding requirements except that the keys in every map MUST be sorted such that:¶
For example, under the length-first core deterministic encoding requirements, the following keys are sorted correctly:¶
5. Creating CBOR-Based Protocols
Data formats such as CBOR are often used in environments where there is no format negotiation. A specific design goal of CBOR is to not need any included or assumed schema: a decoder can take a CBOR item and decode it with no other knowledge.¶
Of course, in real-world implementations
CBOR-based protocols MUST specify how their decoders handle invalid and other unexpected data. CBOR-based protocols MAY specify that they treat arbitrary valid data as unexpected. Encoders for CBOR-based protocols MUST produce only valid items, that is, the protocol cannot be designed to make use of invalid items. An encoder can be capable of encoding as many or as few types of values as is required by the protocol in which it is used; a decoder can be capable of understanding as many or as few types of values as is required by the protocols in which it is used. This lack of restrictions allows CBOR to be used in extremely constrained environments.¶
The rest of this section discusses some considerations in creating CBOR-based
protocols. With few exceptions, it is advisory only and explicitly excludes any language
from BCP 14 [RFC2119] [RFC8174] other than words that could be interpreted as "MAY" in
the sense of BCP 14. The exceptions aim at facilitating
interoperabilit
5.1. CBOR in Streaming Applications
In a streaming application, a data stream may be composed of a sequence of CBOR data items concatenated back-to-back. In such an environment, the decoder immediately begins decoding a new data item if data is found after the end of a previous data item.¶
Not all of the bytes making up a data item may be immediately available to the decoder; some decoders will buffer additional data until a complete data item can be presented to the application. Other decoders can present partial information about a top-level data item to an application, such as the nested data items that could already be decoded, or even parts of a byte string that hasn't completely arrived yet. Such an application also MUST have a matching streaming security mechanism, where the desired protection is available for incremental data presented to the application.¶
Note that some applications and protocols will not want to use
indefinite
5.2. Generic Encoders and Decoders
A generic CBOR decoder can decode all well-formed encoded CBOR data items and present the data items to an application. See Appendix C. (The diagnostic notation, Section 8, may be used to present well-formed CBOR values to humans.)¶
Generic CBOR encoders provide an application interface that allows the application to specify any well-formed value to be encoded as a CBOR data item, including simple values and tags unknown to the encoder.¶
Even though CBOR attempts to minimize these cases, not all well-formed
CBOR data is valid: for example, the encoded text string 0x62c0ae
does not contain valid UTF-8 (because [RFC3629] requires always using the shortest
form) and so is not a valid CBOR item.
Also, specific tags may
make semantic constraints that may be violated, for instance, by a bignum tag
enclosing another tag or by an instance of tag number 0 containing a byte
string or containing a text string with contents that do not match the
date-time production of [RFC3339]. There is
no requirement that generic encoders and decoders make unnatural
choices for their application interface to enable the processing of
invalid data. Generic encoders and decoders are expected to forward
simple values and tags even if their specific codepoints are not
registered at the time the encoder/decoder is written
(Section 5.4).¶
5.3. Validity of Items
A well-formed but invalid CBOR data item (Section 1.2) presents a problem with interpreting the data encoded in it in the CBOR data model. A CBOR-based protocol could be specified in several layers, in which the lower layers don't process the semantics of some of the CBOR data they forward. These layers can't notice any validity errors in data they don't process and MUST forward that data as-is. The first layer that does process the semantics of an invalid CBOR item MUST pick one of two choices:¶
A CBOR-based protocol MUST specify which of these options its decoders take for each kind of invalid item they might encounter.¶
Such problems might occur at the basic validity level of CBOR or in the context of tags (tag validity).¶
5.3.1. Basic validity
Two kinds of validity errors can occur in the basic generic data model:¶
- Duplicate keys in a map:
- Generic decoders (Section 5.2) make data available to applications using the native CBOR data model. That data model includes maps (key-value mappings with unique keys), not multimaps (key-value mappings where multiple entries can have the same key). Thus, a generic decoder that gets a CBOR map item that has duplicate keys will decode to a map with only one instance of that key, or it might stop processing altogether. On the other hand, a "streaming decoder" may not even be able to notice. See Section 5.6 for more discussion of keys in maps.¶
- Invalid UTF-8 string:
- A decoder might or might not want to verify that the sequence of bytes in a UTF-8 string (major type 3) is actually valid UTF-8 and react appropriately.¶
5.3.2. Tag validity
Two additional kinds of validity errors are introduced by adding tags to the basic generic data model:¶
- Inadmissible type for tag content:
- Tag numbers (Section 3.4) specify what type of data item is supposed to be used as their tag content; for example, the tag numbers for unsigned or negative bignums are supposed to be put on byte strings. A decoder that decodes the tagged data item into a native representation (a native big integer in this example) is expected to check the type of the data item being tagged. Even decoders that don't have such native representations available in their environment may perform the check on those tags known to them and react appropriately.¶
- Inadmissible value for tag content:
- The type of data item may be admissible for a tag's content, but the specific value may not be; e.g., a value of "yesterday" is not acceptable for the content of tag 0, even though it properly is a text string. A decoder that normally ingests such tags into equivalent platform types might present this tag to the application in a similar way to how it would present a tag with an unknown tag number (Section 5.4).¶
5.4. Validity and Evolution
A decoder with validity checking will expend the effort to reliably detect data items with validity errors. For example, such a decoder needs to have an API that reports an error (and does not return data) for a CBOR data item that contains any of the validity errors listed in the previous subsection.¶
The set of tags defined in the "Concise Binary Object
Representation (CBOR) Tags" registry (Section 9.2), as well as the set of simple values defined in
the "Concise Binary Object Representation (CBOR) Simple Values"
registry (Section 9.1), can grow at
any time beyond the set understood by a generic decoder. A
validity
The latter approach, which is also appropriate for decoders that do not support validity checking, provides forward compatibility with newly registered tags and simple values without the requirement to update the encoder at the same time as the calling application. (For this, the decoder's API needs the ability to mark unknown items so that the calling application can handle them in a manner appropriate for the program.)¶
Since some of the processing needed for validity checking may have an appreciable cost (in particular with duplicate detection for maps), support of validity checking is not a requirement placed on all CBOR decoders.¶
Some encoders will rely on their applications to provide input data in
such a way that valid CBOR results from the encoder. A generic
encoder may also want to provide a validity
5.5. Numbers
CBOR-based protocols should take into account that different language environments pose different restrictions on the range and precision of numbers that are representable. For example, the basic JavaScript number system treats all numbers as floating-point values, which may result in the silent loss of precision in decoding integers with more than 53 significant bits. Another example is that, since CBOR keeps the sign bit for its integer representation in the major type, it has one bit more for signed numbers of a certain length (e.g., -264..264-1 for 1+8-byte integers) than the typical platform signed integer representation of the same length (-263..263-1 for 8-byte int64_t). A protocol that uses numbers should define its expectations on the handling of nontrivial numbers in decoders and receiving applications.¶
A CBOR-based protocol that includes floating-point numbers can
restrict which of the three formats
A CBOR-based protocol designed for compactness may want to exclude
specific integer encodings that are longer than necessary for the
application, such as to save the need to implement 64-bit integers.
There is an expectation that encoders will use the most compact
integer representation that can represent a given value. However, a
compact application that does not require deterministic encoding
should accept values that use a longer
CBOR-based protocols for constrained applications that provide a
choice between representing a specific number as an integer and
as a decimal fraction or bigfloat (such as when the exponent is small
and nonnegative) might express a quality
5.6. Specifying Keys for Maps
The encoding and decoding applications need to agree on what types of keys are going to be used in maps. In applications that need to interwork with JSON-based applications, conversion is simplified by limiting keys to text strings only; otherwise, there has to be a specified mapping from the other CBOR types to text strings, and this often leads to implementation errors. In applications where keys are numeric in nature, and numeric ordering of keys is important to the application, directly using the numbers for the keys is useful.¶
If multiple types of keys are to be used, consideration should be given to how these types would be represented in the specific programming environments that are to be used. For example, in JavaScript Maps [ECMA262], a key of integer 1 cannot be distinguished from a key of floating-point 1.0. This means that, if integer keys are used, the protocol needs to avoid the use of floating-point keys the values of which happen to be integer numbers in the same map.¶
Decoders that deliver data items nested within a CBOR data item immediately on decoding them ("streaming decoders") often do not keep the state that is necessary to ascertain uniqueness of a key in a map. Similarly, an encoder that can start encoding data items before the enclosing data item is completely available ("streaming encoder") may want to reduce its overhead significantly by relying on its data source to maintain uniqueness.¶
A CBOR-based protocol MUST define what to do when a receiving application sees multiple identical keys in a map. The resulting rule in the protocol MUST respect the CBOR data model: it cannot prescribe a specific handling of the entries with the identical keys, except that it might have a rule that having identical keys in a map indicates a malformed map and that the decoder has to stop with an error. When processing maps that exhibit entries with duplicate keys, a generic decoder might do one of the following:¶
Generic decoders need to document which of these three approaches they implement.¶
The CBOR data model for maps does not allow ascribing semantics to the order of the key/value pairs in the map representation. Thus, a CBOR-based protocol MUST NOT specify that changing the key/value pair order in a map changes the semantics, except to specify that some orders are disallowed, for example, where they would not meet the requirements of a deterministic encoding (Section 4.2). (Any secondary effects of map ordering such as on timing, cache usage, and other potential side channels are not considered part of the semantics but may be enough reason on their own for a protocol to require a deterministic encoding format.)¶
Applications for constrained devices should consider using small integers as keys if they have maps with a small number of frequently used keys; for instance, a set of 24 or fewer keys can be encoded in a single byte as unsigned integers, up to 48 if negative integers are also used. Less frequently occurring keys can then use integers with longer encodings.¶
5.6.1. Equivalence of Keys
The specific data model that applies to a CBOR data item is used to determine whether keys occurring in maps are duplicates or distinct.¶
At the generic data model level, numerically equivalent integer and floating-point values are distinct from each other, as they are from the various big numbers (Tags 2 to 5). Similarly, text strings are distinct from byte strings, even if composed of the same bytes. A tagged value is distinct from an untagged value or from a value tagged with a different tag number.¶
Within each of these groups, numeric values are distinct unless they are numerically equal (specifically, -0.0 is equal to 0.0); for the purpose of map key equivalence, NaN values are equivalent if they have the same significand after zero-extending both significands at the right to 64 bits.¶
Both byte strings and text strings are compared byte by byte, arrays are compared element by element, and are equal if they have the same number of bytes/elements and the same values at the same positions. Two maps are equal if they have the same set of pairs regardless of their order; pairs are equal if both the key and value are equal.¶
Tagged values are equal if both the tag number and the tag content are equal. (Note that a generic decoder that provides processing for a specific tag may not be able to distinguish some semantically equivalent values, e.g., if leading zeroes occur in the content of tag 2 or tag 3 (Section 3.4.3).) Simple values are equal if they simply have the same value. Nothing else is equal in the generic data model; a simple value 2 is not equivalent to an integer 2, and an array is never equivalent to a map.¶
As discussed in Section 2.2, specific data models can make values equivalent for the purpose of comparing map keys that are distinct in the generic data model. Note that this implies that a generic decoder may deliver a decoded map to an application that needs to be checked for duplicate map keys by that application (alternatively, the decoder may provide a programming interface to perform this service for the application). Specific data models are not able to distinguish values for map keys that are equal for this purpose at the generic data model level.¶
5.7. Undefined Values
In some CBOR-based protocols, the simple value (Section 3.3) of
undefined might be used by an encoder as a substitute for a data item
with an encoding problem, in order to allow the rest of the enclosing
data items to be encoded without harm.¶
6. Converting Data between CBOR and JSON
This section gives non-normative advice about converting between CBOR and JSON. Implementations of converters MAY use whichever advice here they want.¶
It is worth noting that a JSON text is a sequence of characters, not an encoded sequence of bytes, while a CBOR data item consists of bytes, not characters.¶
6.1. Converting from CBOR to JSON
Most of the types in CBOR have direct analogs in JSON. However, some do not, and someone implementing a CBOR-to-JSON converter has to consider what to do in those cases. The following non-normative advice deals with these by converting them to a single substitute value, such as a JSON null.¶
A CBOR-to-JSON converter may want to keep to the JSON profile I-JSON
[RFC7493], to maximize interoperabilit
6.2. Converting from JSON to CBOR
All JSON values, once decoded, directly map into one or more CBOR values. As with any kind of CBOR generation, decisions have to be made with respect to number representation. In a suggested conversion:¶
CBOR has been designed to generally provide a more compact encoding than JSON. One implementation strategy that might come to mind is to perform a JSON-to-CBOR encoding in place in a single buffer. This strategy would need to carefully consider a number of pathological cases, such as that some strings represented with no or very few escapes and longer (or much longer) than 255 bytes may expand when encoded as UTF-8 strings in CBOR. Similarly, a few of the binary floating-point representations might cause expansion from some short decimal representations (1.1, 1e9) in JSON. This may be hard to get right, and any ensuing vulnerabilities may be exploited by an attacker.¶
7. Future Evolution of CBOR
Successful protocols evolve over time. New ideas appear, implementation platforms improve, related protocols are developed and evolve, and new requirements from applications and protocols are added. Facilitating protocol evolution is therefore an important design consideration for any protocol development.¶
For protocols that will use CBOR, CBOR provides some useful mechanisms to facilitate their evolution. Best practices for this are well known, particularly from JSON format development of JSON-based protocols. Therefore, such best practices are outside the scope of this specification.¶
However, facilitating the evolution of CBOR itself is very well within its scope. CBOR is designed to both provide a stable basis for development of CBOR-based protocols and to be able to evolve. Since a successful protocol may live for decades, CBOR needs to be designed for decades of use and evolution. This section provides some guidance for the evolution of CBOR. It is necessarily more subjective than other parts of this document. It is also necessarily incomplete, lest it turn into a textbook on protocol development.¶
7.1. Extension Points
In a protocol design, opportunities for evolution are often included in the form of extension points. For example, there may be a codepoint space that is not fully allocated from the outset, and the protocol is designed to tolerate and embrace implementations that start using more codepoints than initially allocated.¶
Sizing the codepoint space may be difficult because the range required may be hard to predict. Protocol designs should attempt to make the codepoint space large enough so that it can slowly be filled over the intended lifetime of the protocol.¶
CBOR has three major extension points:¶
- the "simple" space (values in major type 7):
- Of the 24 efficient (and 224 slightly less efficient) values, only a small number have been allocated. Implementations receiving an unknown simple data item may easily be able to process it as such, given that the structure of the value is indeed simple. The IANA registry in Section 9.1 is the appropriate way to address the extensibility of this codepoint space.¶
- the "tag" space (values in major type 6):
- The total codepoint space is abundant; only a tiny part of it has been allocated. However, not all of these codepoints are equally efficient: the first 24 only consume a single ("1+0") byte, and half of them have already been allocated. The next 232 values only consume two ("1+1") bytes, with nearly a quarter already allocated. These subspaces need some curation to last for a few more decades. Implementations receiving an unknown tag number can choose to process just the enclosed tag content or, preferably, to process the tag as an unknown tag number wrapping the tag content. The IANA registry in Section 9.2 is the appropriate way to address the extensibility of this codepoint space.¶
- the "additional information" space:
- An implementation receiving an unknown additional information value has no way to continue decoding, so allocating codepoints in this space is a major step beyond just exercising an extension point. There are also very few codepoints left. See also Section 7.2.¶
7.2. Curating the Additional Information Space
The human mind is sometimes drawn to filling in little perceived gaps to make something neat. We expect the remaining gaps in the codepoint space for the additional information values to be an attractor for new ideas, just because they are there.¶
The present specification does not manage the additional information codepoint space by an IANA registry. Instead, allocations out of this space can only be done by updating this specification.¶
For an additional information value of n >= 24, the size of the additional data typically is 2n-24 bytes. Therefore, additional information values 28 and 29 should be viewed as candidates for 128-bit and 256-bit quantities, in case a need arises to add them to the protocol. Additional information value 30 is then the only additional information value available for general allocation, and there should be a very good reason for allocating it before assigning it through an update of the present specification.¶
8. Diagnostic Notation
CBOR is a binary interchange format. To facilitate documentation and debugging, and in particular to facilitate communication between entities cooperating in debugging, this section defines a simple human-readable diagnostic notation. All actual interchange always happens in the binary format.¶
Note that this truly is a diagnostic format; it is not meant to be parsed. Therefore, no formal definition (as in ABNF) is given in this document. (Implementers looking for a text-based format for representing CBOR data items in configuration files may also want to consider YAML [YAML].)¶
The diagnostic notation is loosely based on JSON as it is defined in RFC 8259, extending it where needed.¶
The notation borrows the JSON syntax for numbers (integer and
floating
0
or the equivalent relative time as the following:¶
1(1363896240)¶
Byte strings are notated in one of the base encodings, without padding, enclosed in single quotes, prefixed by >h< for base16, >b32< for base32, >h32< for base32hex, >b64< for base64 or base64url (the actual encodings do not overlap, so the string remains unambiguous). For example, the byte string 0x12345678 could be written h'12345678', b32'CI2FM6A', or b64'EjRWeA'.¶
Unassigned simple values are given as "simple()" with the appropriate integer in the parentheses. For example, "simple(42)" indicates major type 7, value 42.¶
A number of useful extensions to the diagnostic notation defined here are provided in Appendix G of [RFC8610], "Extended Diagnostic Notation" (EDN). Similarly, this notation could be extended in a separate document to provide documentation for NaN payloads, which are not covered in this document.¶
8.1. Encoding Indicators
Sometimes it is useful to indicate in the diagnostic notation which of
several alternative representations were actually used; for example, a
data item written >1.5< by a diagnostic decoder might have been
encoded as a half-, single-, or double
The convention for encoding indicators is that anything starting with
an underscore and all following characters that are alphanumeric or
underscore is an encoding indicator, and can be ignored by anyone not
interested in this information. For example, _ or _3.
Encoding indicators are always
optional.¶
A single underscore can be written after the opening brace of a map or
the opening bracket of an array to indicate that the data item was
represented in indefinite
An underscore followed by a decimal digit n indicates that the preceding item (or, for arrays and maps, the item starting with the preceding bracket or brace) was encoded with an additional information value of 24+n. For example, 1.5_1 is a half-precision floating-point number, while 1.5_3 is encoded as double precision. This encoding indicator is not shown in Appendix A. (Note that the encoding indicator "_" is thus an abbreviation of the full form "_7", which is not used.)¶
The detailed chunk structure of byte and text strings of indefinite
length can be
notated in the form (_ h'0123', h'4567') and (_ "foo", "bar").
However, for an indefinite
9. IANA Considerations
IANA has created two registries for new CBOR values. The registries are separate, that is, not under an umbrella registry, and follow the rules in [RFC8126]. IANA has also assigned a new media type, an associated CoAP Content-Format entry, and a structured syntax suffix.¶
9.1. CBOR Simple Values Registry
IANA has created the "Concise Binary Object Representation (CBOR)
Simple Values" registry at [IANA
New entries in the range 0 to 19 are assigned by Standards Action [RFC8126]. It is suggested that IANA allocate values starting with the number 16 in order to reserve the lower numbers for contiguous blocks (if any).¶
New entries in the range 32 to 255 are assigned by Specification Required.¶
9.3. Media Types Registry
The Internet media type [RFC6838] ("MIME type") for a single encoded CBOR data
item is "application
- Type name:
- application¶
- Subtype name:
- cbor¶
- Required parameters:
- n/a¶
- Optional parameters:
- n/a¶
- Encoding considerations:
- Binary¶
- Security considerations:
- See Section 10 of RFC 8949.¶
- Interoperability considerations:
- n/a¶
- Published specification:
- RFC 8949¶
- Applications that use this media type:
- Many¶
- Additional information:
-
- Person & email address to contact for further information:
- IETF CBOR Working Group (cbor@ietf.org) or IETF Applications and Real-Time Area (art@ietf.org)¶
- Intended usage:
- COMMON¶
- Restrictions on usage:
- none¶
- Author:
- IETF CBOR Working Group (cbor@ietf.org)¶
- Change controller:
- The IESG (iesg@ietf.org)¶
9.4. CoAP Content-Format Registry
The CoAP Content-Format for CBOR has been registered in the "CoAP
Content
9.5. Structured Syntax Suffix Registry
The structured syntax suffix [RFC6838] for media types based on a single
encoded CBOR data item is +cbor, which IANA has registered in the
"Structured Syntax Suffixes" registry [IANA
- Name:
- Concise Binary Object Representation (CBOR)¶
- +suffix:
- +cbor¶
- References:
- RFC 8949¶
- Encoding Considerations:
- CBOR is a binary format.¶
- Interoperability Considerations:
- n/a¶
- Fragment Identifier Considerations:
-
The syntax and semantics of fragment identifiers specified for +cbor SHOULD be as specified for "application
/cbor" . (At publication of RFC 8949, there is no fragment identification syntax defined for "application /cbor" .) ¶ The syntax and semantics for fragment identifiers for a specific "xxx/yyy+cbor" SHOULD be processed as follows:¶
- Security Considerations:
- See Section 10 of RFC 8949.¶
- Contact:
- IETF CBOR Working Group (cbor@ietf.org) or IETF Applications and Real-Time Area (art@ietf.org)¶
- Author/Change Controller:
- IETF¶
10. Security Considerations
A network-facing application can exhibit vulnerabilities in its
processing logic for incoming data. Complex parsers are well known as
a likely source of such vulnerabilities
Because CBOR decoders are often used as a first step in processing unvalidated input, they need to be fully prepared for all types of hostile input that may be designed to corrupt, overrun, or achieve control of the system decoding the CBOR data item. A CBOR decoder needs to assume that all input may be hostile even if it has been checked by a firewall, has come over a secure channel such as TLS, is encrypted or signed, or has come from some other source that is presumed trusted.¶
Section 4.1 gives examples of limitations in interoperabilit
As discussed throughout this document, there are many values that can be considered "equivalent" in some circumstances and "not equivalent" in others. As just one example, the numeric value for the number "one" might be expressed as an integer or a bignum. A system interpreting CBOR input might accept either form for the number "one", or might reject one (or both) forms. Such acceptance or rejection can have security implications in the program that is using the interpreted input.¶
Hostile input may be constructed to overrun buffers, to overflow or
underflow integer arithmetic, or to cause other decoding disruption. CBOR
data items might have lengths or sizes that are intentionally
extremely large or too short.
Resource exhaustion attacks might attempt to lure a decoder into
allocating very big data items (strings, arrays, maps, or even
arbitrary precision numbers) or exhaust the
stack depth by setting up deeply nested items. Decoders need to have
appropriate resource management to mitigate these attacks. (Items for
which very large sizes are given can also attempt to exploit integer
overflow vulnerabilities
A CBOR decoder, by definition, only accepts well-formed CBOR; this is the first step to its robustness. Input that is not well-formed CBOR causes no further processing from the point where the lack of well-formedness was detected. If possible, any data decoded up to this point should have no impact on the application using the CBOR decoder.¶
In addition to ascertaining well
The input check itself may consume resources. This is usually linear
in the size of the input, which means that an attacker has to spend
resources that are commensurate to the resources spent by the defender
on input validation.
However, an attacker might be able to craft inputs that will take longer for a
target decoder to process than for the attacker to produce.
Processing for arbitrary
CBOR encoders do not receive input directly from the network and are thus not directly attackable in the same way as CBOR decoders. However, CBOR encoders often have an API that takes input from another level in the implementation and can be attacked through that API. The design and implementation of that API should assume the behavior of its caller may be based on hostile input or on coding mistakes. It should check inputs for buffer overruns, overflow and underflow of integer arithmetic, and other such errors that are aimed to disrupt the encoder.¶
Protocols should be defined in
such a way that potential multiple interpretations are reliably
reduced to a single interpretation. For example, an attacker could make use of
invalid input such as duplicate keys in maps, or exploit different
precision in processing numbers to make one application base its
decisions on a different interpretation than the one that will be used
by a second application. To facilitate consistent interpretation,
encoder and decoder implementations should
provide a validity
Section 3.4.3 notes that using the non-preferred choice of a bignum representation instead of a basic integer for encoding a number is not intended to have application semantics, but it can have such semantics if an application receiving CBOR data is using a decoder in the basic generic data model. This disparity causes a security issue if the two sets of semantics differ. Thus, applications using CBOR need to specify the data model that they are using for each use of CBOR data.¶
It is common to convert CBOR data to other formats. In many cases, CBOR has more expressive types than other formats; this is particularly true for the common conversion to JSON. The loss of type information can cause security issues for the systems that are processing the less-expressive data.¶
Section 6.2 describes a possibly common usage scenario of converting between CBOR and JSON that could allow an attack if the attacker knows that the application is performing the conversion.¶
Security considerations for the use of base16 and base64 from [RFC4648], and the use of UTF-8 from [RFC3629], are relevant to CBOR as well.¶
11. References
11.1. Normative References
- [C]
-
International Organization for Standardization, "Information technology - Programming languages - C", Fourth Edition, ISO/IEC 9899:2018, , <https://
www >..iso .org /standard /74528 .html - [Cplusplus20]
-
International Organization for Standardization, "Programming languages - C++", Sixth Edition, ISO/IEC DIS 14882, ISO/IEC ISO/IEC JTC1 SC22 WG21 N 4860, , <https://
isocpp >..org /files /papers /N4860 .pdf - [IEEE754]
-
IEEE, "IEEE Standard for Floating-Point Arithmetic", IEEE Std 754-2019, DOI 10
.1109 , <https:///IEEESTD .2019 .8766229 ieeexplore >..ieee .org /document /8766229 - [RFC2045]
-
Freed, N. and N. Borenstein, "Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies", RFC 2045, DOI 10
.17487 , , <https:///RFC2045 www >..rfc -editor .org /info /rfc2045 - [RFC2119]
-
Bradner, S., "Key words for use in RFCs to Indicate Requirement Levels", BCP 14, RFC 2119, DOI 10
.17487 , , <https:///RFC2119 www >..rfc -editor .org /info /rfc2119 - [RFC3339]
-
Klyne, G. and C. Newman, "Date and Time on the Internet: Timestamps", RFC 3339, DOI 10
.17487 , , <https:///RFC3339 www >..rfc -editor .org /info /rfc3339 - [RFC3629]
-
Yergeau, F., "UTF-8, a transformation format of ISO 10646", STD 63, RFC 3629, DOI 10
.17487 , , <https:///RFC3629 www >..rfc -editor .org /info /rfc3629 - [RFC3986]
-
Berners-Lee, T., Fielding, R., and L. Masinter, "Uniform Resource Identifier (URI): Generic Syntax", STD 66, RFC 3986, DOI 10
.17487 , , <https:///RFC3986 www >..rfc -editor .org /info /rfc3986 - [RFC4287]
-
Nottingham, M., Ed. and R. Sayre, Ed., "The Atom Syndication Format", RFC 4287, DOI 10
.17487 , , <https:///RFC4287 www >..rfc -editor .org /info /rfc4287 - [RFC4648]
-
Josefsson, S., "The Base16, Base32, and Base64 Data Encodings", RFC 4648, DOI 10
.17487 , , <https:///RFC4648 www >..rfc -editor .org /info /rfc4648 - [RFC8126]
-
Cotton, M., Leiba, B., and T. Narten, "Guidelines for Writing an IANA Considerations Section in RFCs", BCP 26, RFC 8126, DOI 10
.17487 , , <https:///RFC8126 www >..rfc -editor .org /info /rfc8126 - [RFC8174]
-
Leiba, B., "Ambiguity of Uppercase vs Lowercase in RFC 2119 Key Words", BCP 14, RFC 8174, DOI 10
.17487 , , <https:///RFC8174 www >..rfc -editor .org /info /rfc8174 - [TIME_T]
-
The Open Group, "The Open Group Base Specifications", Section 4.16, 'Seconds Since the Epoch', Issue 7, 2018 Edition, IEEE Std 1003.1, , <https://
pubs >..opengroup .org /onlinepubs /9699919799 /basedefs /V1 _chap04 .html#tag _04 _16
11.2. Informative References
- [ASN.1]
-
International Telecommunicati
on , "Information Technology - ASN.1 encoding rules: Specification of Basic Encoding Rules (BER), Canonical Encoding Rules (CER) and Distinguished Encoding Rules (DER)", ITU-T Recommendation X.690, , <https://Union www >..itu .int /rec /T -REC -X .690 -201508 -I /en - [BSON]
-
Various, "BSON - Binary JSON", <http://
bsonspec >..org / -
Bormann, C., "Notable CBOR Tags", Work in Progress, Internet-Draft, draft
-bormann , , <https://-cbor -notable -tags -02 tools >..ietf .org /html /draft -bormann -cbor -notable -tags -02 - [ECMA262]
-
Ecma International, "ECMAScript 2020 Language Specification", Standard ECMA-262, 11th Edition, , <https://
www >..ecma -international .org /publications /standards /Ecma -262 .htm - [Err3764]
-
RFC Errata, Erratum ID 3764, RFC 7049, <https://
www >..rfc -editor .org /errata /eid3764 - [Err3770]
-
RFC Errata, Erratum ID 3770, RFC 7049, <https://
www >..rfc -editor .org /errata /eid3770 - [Err4294]
-
RFC Errata, Erratum ID 4294, RFC 7049, <https://
www >..rfc -editor .org /errata /eid4294 - [Err4409]
-
RFC Errata, Erratum ID 4409, RFC 7049, <https://
www >..rfc -editor .org /errata /eid4409 - [Err4963]
-
RFC Errata, Erratum ID 4963, RFC 7049, <https://
www >..rfc -editor .org /errata /eid4963 - [Err4964]
-
RFC Errata, Erratum ID 4964, RFC 7049, <https://
www >..rfc -editor .org /errata /eid4964 - [Err5434]
-
RFC Errata, Erratum ID 5434, RFC 7049, <https://
www >..rfc -editor .org /errata /eid5434 - [Err5763]
-
RFC Errata, Erratum ID 5763, RFC 7049, <https://
www >..rfc -editor .org /errata /eid5763 - [Err5917]
-
RFC Errata, Erratum ID 5917, RFC 7049, <https://
www >..rfc -editor .org /errata /eid5917 - [IANA
.cbor -simple -values] -
IANA, "Concise Binary Object Representation (CBOR) Simple Values", <https://
www >..iana .org /assignments /cbor -simple -values -
IANA, "Concise Binary Object Representation (CBOR) Tags", <https://
www >..iana .org /assignments /cbor -tags - [IANA
.core -parameters] -
IANA, "Constrained RESTful Environments (CoRE) Parameters", <https://
www >..iana .org /assignments /core -parameters - [IANA
.media -types] -
IANA, "Media Types", <https://
www >..iana .org /assignments /media -types - [IANA
.structured -suffix] -
IANA, "Structured Syntax Suffixes", <https://
www >..iana .org /assignments /media -type -structured -suffix - [MessagePack]
-
Furuhashi, S., "MessagePack", <https://
msgpack >..org / - [PCRE]
-
Hazel, P., "PCRE - Perl Compatible Regular Expressions", <https://
www >..pcre .org / - [RFC0713]
-
Haverty, J., "MSDTP-Message Services Data Transmission Protocol", RFC 713, DOI 10
.17487 , , <https:///RFC0713 www >..rfc -editor .org /info /rfc713 - [RFC6838]
-
Freed, N., Klensin, J., and T. Hansen, "Media Type Specifications and Registration Procedures", BCP 13, RFC 6838, DOI 10
.17487 , , <https:///RFC6838 www >..rfc -editor .org /info /rfc6838 - [RFC7049]
-
Bormann, C. and P. Hoffman, "Concise Binary Object Representation (CBOR)", RFC 7049, DOI 10
.17487 , , <https:///RFC7049 www >..rfc -editor .org /info /rfc7049 - [RFC7228]
-
Bormann, C., Ersue, M., and A. Keranen, "Terminology for Constrained
-Node , RFC 7228, DOI 10Networks" .17487 , , <https:///RFC7228 www >..rfc -editor .org /info /rfc7228 - [RFC7493]
-
Bray, T., Ed., "The I-JSON Message Format", RFC 7493, DOI 10
.17487 , , <https:///RFC7493 www >..rfc -editor .org /info /rfc7493 - [RFC7991]
-
Hoffman, P., "The "xml2rfc" Version 3 Vocabulary", RFC 7991, DOI 10
.17487 , , <https:///RFC7991 www >..rfc -editor .org /info /rfc7991 - [RFC8259]
-
Bray, T., Ed., "The JavaScript Object Notation (JSON) Data Interchange Format", STD 90, RFC 8259, DOI 10
.17487 , , <https:///RFC8259 www >..rfc -editor .org /info /rfc8259 - [RFC8610]
-
Birkholz, H., Vigano, C., and C. Bormann, "Concise Data Definition Language (CDDL): A Notational Convention to Express Concise Binary Object Representation (CBOR) and JSON Data Structures", RFC 8610, DOI 10
.17487 , , <https:///RFC8610 www >..rfc -editor .org /info /rfc8610 - [RFC8618]
-
Dickinson, J., Hague, J., Dickinson, S., Manderson, T., and J. Bond, "Compacted-DNS (C-DNS): A Format for DNS Packet Capture", RFC 8618, DOI 10
.17487 , , <https:///RFC8618 www >..rfc -editor .org /info /rfc8618 - [RFC8742]
-
Bormann, C., "Concise Binary Object Representation (CBOR) Sequences", RFC 8742, DOI 10
.17487 , , <https:///RFC8742 www >..rfc -editor .org /info /rfc8742 - [RFC8746]
-
Bormann, C., Ed., "Concise Binary Object Representation (CBOR) Tags for Typed Arrays", RFC 8746, DOI 10
.17487 , , <https:///RFC8746 www >..rfc -editor .org /info /rfc8746 - [SIPHASH_LNCS]
-
Aumasson, J. and D. Bernstein, "SipHash: A Fast Short-Input PRF", Progress in Cryptology - INDOCRYPT 2012, pp. 489-508, DOI 10
.1007 , , <https:///978 -3 -642 -34931 -7 _28 doi >..org /10 .1007 /978 -3 -642 -34931 -7 _28 - [SIPHASH_OPEN]
-
Aumasson, J. and D.J. Bernstein, "SipHash: a fast short-input PRF", <https://
www >..aumasson .jp /siphash /siphash .pdf - [YAML]
-
Ben-Kiki, O., Evans, C., and I.d. Net, "YAML Ain't Markup Language (YAML[TM]) Version 1.2", 3rd Edition, , <https://
www >..yaml .org /spec /1 .2 /spec .html
Appendix A. Examples of Encoded CBOR Data Items
The following table provides some CBOR-encoded values in hexadecimal
(right column), together with diagnostic notation for these values (left
column). Note that the string "\u00fc" is one form of diagnostic
notation for a UTF-8 string containing the single Unicode character U+00FC (LATIN SMALL LETTER U WITH DIAERESIS, "ü"). Similarly, "\u6c34" is a UTF-8 string in
diagnostic notation with a single character U+6C34 (CJK UNIFIED IDEOGRAPH-6C34, "水"),
often representing "water", and "\ud800\udd51" is a UTF-8 string
in diagnostic notation with a single character U+10151 (GREEK ACROPHONIC ATTIC FIFTY STATERS, "𐅑"). (Note that all these single
Appendix B. Jump Table for Initial Byte
For brevity, this jump table does not show initial bytes that are reserved for future extension. It also only shows a selection of the initial bytes that can be used for optional features. (All unsigned integers are in network byte order.)¶
Appendix C. Pseudocode
The well-formedness of a CBOR item can be checked by the pseudocode in Figure 1. The data is well-formed if and only if:¶
The pseudocode has the following prerequisites:¶
Note that well_formed returns the major type for well-formed
definite-length items, but 99 for an indefinitebreakable is set). This is used in
well to ascertain that indefinite
Note that the remaining complexity of a complete CBOR decoder is about presenting data that has been decoded to the application in an appropriate form.¶
Major types 0 and 1 are designed in such a way that they can be
encoded in C from a signed integer without actually doing an
if-then-else for positive
See Section 1.2 for some specific assumptions about the profile of the C language used in these pieces of code.¶
Appendix D. Half-Precision
As half-precision floating-point numbers were only added to IEEE 754 in 2008 [IEEE754], today's programming platforms often still only have limited support for them. It is very easy to include at least decoding support for them even without such support. An example of a small decoder for half-precision floating-point numbers in the C language is shown in Figure 3. A similar program for Python is in Figure 4; this code assumes that the 2-byte value has already been decoded as an (unsigned short) integer in network byte order (as would be done by the pseudocode in Appendix C).¶
Appendix E. Comparison of Other Binary Formats to CBOR's Design Objectives
The proposal for CBOR follows a history of binary formats that is as long as the history of computers themselves. Different formats have had different objectives. In most cases, the objectives of the format were never stated, although they can sometimes be implied by the context where the format was first used. Some formats were meant to be universally usable, although history has proven that no binary format meets the needs of all protocols and applications.¶
CBOR differs from many of these formats due to it starting with a set of objectives and attempting to meet just those. This section compares a few of the dozens of formats with CBOR's objectives in order to help the reader decide if they want to use CBOR or a different format for a particular protocol or application.¶
Note that the discussion here is not meant to be a criticism of any format: to the best of our knowledge, no format before CBOR was meant to cover CBOR's objectives in the priority we have assigned them. A brief recap of the objectives from Section 1.1 is:¶
A discussion of CBOR and other formats with respect to a different set of design objectives is provided in Section 5 and Appendix C of [RFC8618].¶
E.1. ASN.1 DER, BER, and PER
[ASN.1] has many serializations. In the IETF, DER and BER are the most common. The serialized output is not particularly compact for many items, and the code needed to decode numeric items can be complex on a constrained device.¶
Few (if any) IETF protocols have adopted one of the several variants of Packed Encoding Rules (PER). There could be many reasons for this, but one that is commonly stated is that PER makes use of the schema even for parsing the surface structure of the data item, requiring significant tool support. There are different versions of the ASN.1 schema language in use, which has also hampered adoption.¶
E.2. MessagePack
[MessagePack] is a concise, widely implemented counted binary serialization format, similar in many properties to CBOR, although somewhat less regular. While the data model can be used to represent JSON data, MessagePack has also been used in many remote procedure call (RPC) applications and for long-term storage of data.¶
MessagePack has been essentially stable since it was first published around 2011; it has not yet had a transition. The evolution of MessagePack is impeded by an imperative to maintain complete backwards compatibility with existing stored data, while only few bytecodes are still available for extension. Repeated requests over the years from the MessagePack user community to separate out binary and text strings in the encoding recently have led to an extension proposal that would leave MessagePack's "raw" data ambiguous between its usages for binary and text data. The extension mechanism for MessagePack remains unclear.¶
E.3. BSON
[BSON] is a data format that was developed for the storage of JSON-like maps (JSON objects) in the MongoDB database. Its major distinguishing feature is the capability for in-place update, which prevents a compact representation. BSON uses a counted representation except for map keys, which are null-byte terminated. While BSON can be used for the representation of JSON-like objects on the wire, its specification is dominated by the requirements of the database application and has become somewhat baroque. The status of how BSON extensions will be implemented remains unclear.¶
E.4. MSDTP: RFC 713
Message Services Data Transmission (MSDTP) is a very early example of a compact message format; it is described in [RFC0713], written in 1976. It is included here for its historical value, not because it was ever widely used.¶
E.5. Conciseness on the Wire
While CBOR's design objective of code compactness for encoders and
decoders is a higher priority than its objective of conciseness on the
wire, many people focus on the wire size. Table 8 shows some
encoding examples for the simple nested array [1, [2, 3]]; where some
form of indefinite
Appendix F. Well-Formedness Errors and Examples
There are three basic kinds of well-formedness errors that can occur in decoding a CBOR data item:¶
- Too much data:
- There are input bytes left that were not consumed. This is only an error if the application assumed that the input bytes would span exactly one data item. Where the application uses the self-delimiting nature of CBOR encoding to permit additional data after the data item, as is done in CBOR sequences [RFC8742], for example, the CBOR decoder can simply indicate which part of the input has not been consumed.¶
- Too little data:
- The input data available would need additional bytes added at their end for a complete CBOR data item. This may indicate the input is truncated; it is also a common error when trying to decode random data as CBOR. For some applications, however, this may not actually be an error, as the application may not be certain it has all the data yet and can obtain or wait for additional input bytes. Some of these applications may have an upper limit for how much additional data can appear; here the decoder may be able to indicate that the encoded CBOR data item cannot be completed within this limit.¶
- Syntax error:
- The input data are not consistent with the requirements of the CBOR encoding, and this cannot be remedied by adding (or removing) data at the end.¶
In Appendix C, errors of the first kind are addressed in the first
paragraph and bullet list (requiring "no bytes are left"), and errors of
the second kind are addressed in the second paragraph
F.1. Examples of CBOR Data Items That Are Not Well-Formed
This subsection shows a few examples for CBOR data items that are not well-formed. Each example is a sequence of bytes, each shown in hexadecimal; multiple examples in a list are separated by commas.¶
Examples for well-formedness error kind 1 (too much data) can easily be formed by adding data to a well-formed encoded CBOR data item.¶
Similarly, examples for well-formedness error kind 2 (too little data) can be formed by truncating a well-formed encoded CBOR data item. In test suites, it may be beneficial to specifically test with incomplete data items that would require large amounts of addition to be completed (for instance by starting the encoding of a string of a very large size).¶
A premature end of the input can occur in a head or within the enclosed data, which may be bare strings or enclosed data items that are either counted or should have been ended by a "break" stop code.¶
- End of input in a head:
- 18, 19, 1a, 1b, 19 01, 1a 01 02, 1b 01 02 03 04 05 06 07, 38, 58, 78, 98, 9a 01 ff 00, b8, d8, f8, f9 00, fa 00 00, fb 00 00 00¶
- Definite-length strings with short data:
- 41, 61, 5a ff ff ff ff 00, 5b ff ff ff ff ff ff ff ff 01 02 03, 7a ff ff ff ff 00, 7b 7f ff ff ff ff ff ff ff 01 02 03¶
- Definite-length maps and arrays not closed with enough items:
- 81, 81 81 81 81 81 81 81 81 81, 82 00, a1, a2 01 02, a1 00, a2 00 00 00¶
- Tag number not followed by tag content:
- c0¶
- Indefinite
-length strings not closed by a "break" stop code: - 5f 41 00, 7f 61 00¶
- Indefinite
-length maps and arrays not closed by a "break" stop code: - 9f, 9f 01 02, bf, bf 01 02 01 02, 81 9f, 9f 80 00, 9f 9f 9f 9f 9f ff ff ff ff, 9f 81 9f 81 9f 9f ff ff ff¶
A few examples for the five subkinds of well-formedness error kind 3 (syntax error) are shown below.¶
- Subkind 1:
-
- Reserved additional information values:
- 1c, 1d, 1e, 3c, 3d, 3e, 5c, 5d, 5e, 7c, 7d, 7e, 9c, 9d, 9e, bc, bd, be, dc, dd, de, fc, fd, fe,¶
- Subkind 2:
-
- Reserved two-byte encodings of simple values:
- f8 00, f8 01, f8 18, f8 1f¶
- Subkind 3:
- Subkind 4:
-
- Break occurring on its own outside of an indefinite
-length item: - ff¶
- Break occurring in a definite-length array or map or a tag:
- 81 ff, 82 00 ff, a1 ff, a1 ff 00, a1 00 ff, a2 00 00 ff, 9f 81 ff, 9f 82 9f 81 9f 9f ff ff ff ff¶
- Break in an indefinite
-length map that would lead to an odd number of items (break in a value position): - bf 00 ff, bf 00 00 00 ff¶
- Break occurring on its own outside of an indefinite
- Subkind 5:
-
- Major type 0, 1, 6 with additional information 31:
- 1f, 3f, df¶
Appendix G. Changes from RFC 7049
As discussed in the introduction, this document formally obsoletes RFC 7049 while keeping full compatibility with the interchange format from RFC 7049. This document provides editorial improvements, added detail, and fixed errata. This document does not create a new version of the format.¶
G.1. Errata Processing and Clerical Changes
The two verified errata on RFC 7049, [Err3764] and [Err3770], concerned two encoding examples in the text that have been corrected (Section 3.4.3: "29" -> "49", Section 5.5: "0b000_11101" -> "0b000_11001"). Also, RFC 7049 contained an example using the numeric value 24 for a simple value [Err5917], which is not well-formed; this example has been removed. Errata report 5763 [Err5763] pointed to an error in the wording of the definition of tags; this was resolved during a rewrite of Section 3.4. Errata report 5434 [Err5434] pointed out that the Universal Binary JSON (UBJSON) example in Appendix E no longer complied with the version of UBJSON current at the time of the errata report submission. It turned out that the UBJSON specification had completely changed since 2013; this example therefore was removed. Other errata reports [Err4409] [Err4963] [Err4964] complained that the map key sorting rules for canonical encoding were onerous; these led to a reconsideration of the canonical encoding suggestions and replacement by the deterministic encoding suggestions (described below). An editorial suggestion in errata report 4294 [Err4294] was also implemented (improved symmetry by adding "Second value" to a comment to the last example in Section 3.2.2).¶
Other clerical changes include:¶
G.2. Changes in IANA Considerations
The IANA considerations were generally updated (clerical changes, e.g., now pointing to the CBOR Working Group as the author of the specification). References to the respective IANA registries were added to the informative references.¶
In the "Concise Binary Object Representation (CBOR) Tags" registry [IANA.cbor-tags], tags in the space from 256 to 32767 (lower half of "1+2") are no longer assigned by First Come First Served; this range is now Specification Required.¶
G.3. Changes in Suggestions and Other Informational Components
While revising the document, beyond the addressing of the errata reports, the working group drew upon nearly seven years of experience with CBOR in a diverse set of applications. This led to a number of editorial changes, including adding tables for illustration, but also emphasizing some aspects and de-emphasizing others.¶
A significant addition is Section 2, which discusses the CBOR data model and its small variations involved in the processing of CBOR. The introduction of terms for those variations (basic generic, extended generic, specific) enables more concise language in other places of the document and also helps to clarify expectations of implementations and of the extensibility features of the format.¶
As a format derived from the JSON ecosystem, RFC 7049 was influenced by the JSON number system that was in turn inherited from JavaScript at the time. JSON does not provide distinct integers and floating-point values (and the latter are decimal in the format). CBOR provides binary representations of numbers, which do differ between integers and floating-point values. Experience from implementation and use suggested that the separation between these two number domains should be more clearly drawn in the document; language that suggested an integer could seamlessly stand in for a floating-point value was removed. Also, a suggestion (based on I-JSON [RFC7493]) was added for handling these types when converting JSON to CBOR, and the use of a specific rounding mechanism has been recommended.¶
For a single value in the data model, CBOR often provides multiple
encoding options. A new section (Section 4) introduces the term
"preferred serialization" (Section 4.1) and defines it for various
kinds of data items. On the basis of this terminology, the section
then discusses how a CBOR-based protocol can define "deterministic
encoding" (Section 4.2), which avoids terms
"canonical" and "canonicalizati
The terminology for well-formed and valid data was sharpened and more
stringently used, avoiding less well-defined alternative terms such as
"syntax error", "decoding error", and "strict mode" outside of examples.
Also, a third level of requirements that an
application has on its input data beyond CBOR-level validity is now explicitly called out.
Well-formed (processable at all), valid (checked by a
validity
The handling of non-well-formed simple values was clarified in text and pseudocode. Appendix F was added to discuss well-formedness errors and provide examples for them. The pseudocode was updated to be more portable, and some portability considerations were added.¶
The discussion of validity has been sharpened in two areas. Map validity (handling of duplicate keys) was clarified, and the domain of applicability of certain implementation choices explained. Also, while streamlining the terminology for tags, tag numbers, and tag content, discussion was added on tag validity, and the restrictions were clarified on tag content, in general and specifically for tag 1.¶
An implementation note (and note for future tag definitions) was added to Section 3.4 about defining tags with semantics that depend on serialization order.¶
Tag 35 is not defined by this document; the registration based on the definition in RFC 7049 remains in place.¶
Terminology was introduced in Section 3 for "argument" and "head", simplifying further discussion.¶
The security considerations (Section 10) were mostly rewritten and significantly expanded; in multiple other places, the document is now more explicit that a decoder cannot simply condone well-formedness errors.¶
Acknowledgements
CBOR was inspired by MessagePack. MessagePack was developed and promoted by Sadayuki Furuhashi ("frsyuki"). This reference to MessagePack is solely for attribution; CBOR is not intended as a version of, or replacement for, MessagePack, as it has different design goals and requirements.¶
The need for functionality beyond the original MessagePack
specification became obvious to many people at about the same time
around the year 2012. BinaryPack is a minor derivation of MessagePack
that was developed by Eric Zhang for the binaryjs project. A similar,
but different, extension was made by Tim Caswell for his msgpack-js
and msgpack
The encoding of the additional information in CBOR was inspired by the encoding of length information designed by Klaus Hartke for CoAP.¶
This document also incorporates suggestions made by many people, notably Dan Frost, James Manger, Jeffrey Yasskin, Joe Hildebrand, Keith Moore, Laurence Lundblade, Matthew Lepinski, Michael Richardson, Nico Williams, Peter Occil, Phillip Hallam-Baker, Ray Polk, Stuart Cheshire, Tim Bray, Tony Finch, Tony Hansen, and Yaron Sheffer. Benjamin Kaduk provided an extensive review during IESG processing. Éric Vyncke, Erik Kline, Robert Wilton, and Roman Danyliw provided further IESG comments, which included an IoT directorate review by Eve Schooler.¶