xref: /aosp_15_r20/external/cronet/third_party/boringssl/src/pki/parser.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2015 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef BSSL_DER_PARSER_H_
6 #define BSSL_DER_PARSER_H_
7 
8 #include <stdint.h>
9 
10 #include <optional>
11 
12 #include <openssl/base.h>
13 #include <openssl/bytestring.h>
14 
15 #include "input.h"
16 
17 namespace bssl::der {
18 
19 class BitString;
20 struct GeneralizedTime;
21 
22 // Parses a DER-encoded ASN.1 structure. DER (distinguished encoding rules)
23 // encodes each data value with a tag, length, and value (TLV). The tag
24 // indicates the type of the ASN.1 value. Depending on the type of the value,
25 // it could contain arbitrary bytes, so the length of the value is encoded
26 // after the tag and before the value to indicate how many bytes of value
27 // follow. DER also defines how the values are encoded for particular types.
28 //
29 // This Parser places a few restrictions on the DER encoding it can parse. The
30 // largest restriction is that it only supports tags which have a tag number
31 // no greater than 30 - these are the tags that fit in a single octet. The
32 // second restriction is that the maximum length for a value that can be parsed
33 // is 4GB. Both of these restrictions should be fine for any reasonable input.
34 //
35 // The Parser class is mainly focused on parsing the TLV structure of DER
36 // encoding, and does not directly handle parsing primitive values (other
37 // functions in the bssl::der namespace are provided for this.) When a Parser
38 // is created, it is passed in a reference to the encoded data. Because the
39 // encoded data is not owned by the Parser, the data cannot change during the
40 // lifespan of the Parser. The Parser functions by keeping a pointer to the
41 // current TLV which starts at the beginning of the input and advancing through
42 // the input as each TLV is read. As such, a Parser instance is thread-unsafe.
43 //
44 // Most methods for using the Parser write the current tag and/or value to
45 // the output parameters provided and then advance the input to the next TLV.
46 // None of the methods explicitly expose the length because it is part of the
47 // value. All methods return a boolean indicating whether there was a parsing
48 // error with the current TLV.
49 //
50 // Some methods are provided in the Parser class as convenience to both read
51 // the current TLV from the input and also parse the DER encoded value,
52 // converting it to a corresponding C++ type. These methods simply combine
53 // ReadTag() with the appropriate ParseType() free function.
54 //
55 // The design of DER encoding allows for nested data structures with
56 // constructed values, where the value is a series of TLVs. The Parser class
57 // is not designed to traverse through a nested encoding from a single object,
58 // but it does facilitate parsing nested data structures through the
59 // convenience methods ReadSequence() and the more general ReadConstructed(),
60 // which provide the user with another Parser object to traverse the next
61 // level of TLVs.
62 //
63 // For a brief example of how to use the Parser, suppose we have the following
64 // ASN.1 type definition:
65 //
66 //   Foo ::= SEQUENCE {
67 //     bar OCTET STRING OPTIONAL,
68 //     quux OCTET STRING }
69 //
70 // If we have a DER-encoded Foo in an Input |encoded_value|, the
71 // following code shows an example of how to parse the quux field from the
72 // encoded data.
73 //
74 //   bool ReadQuux(Input encoded_value, Input* quux_out) {
75 //     Parser parser(encoded_value);
76 //     Parser foo_parser;
77 //     if (!parser.ReadSequence(&foo_parser))
78 //       return false;
79 //     if (!foo_parser->SkipOptionalTag(kOctetString))
80 //       return false;
81 //     if (!foo_parser->ReadTag(kOctetString, quux_out))
82 //       return false;
83 //     return true;
84 //   }
85 class OPENSSL_EXPORT Parser {
86  public:
87   // Default constructor; equivalent to calling Parser(Input()). This only
88   // exists so that a Parser can be stack allocated and passed in to
89   // ReadConstructed() and similar methods.
90   Parser();
91 
92   // Creates a parser to parse over the data represented by input. This class
93   // assumes that the underlying data will not change over the lifetime of
94   // the Parser object.
95   explicit Parser(Input input);
96 
97   Parser(const Parser &) = default;
98   Parser &operator=(const Parser &) = default;
99 
100   // Returns whether there is any more data left in the input to parse. This
101   // does not guarantee that the data is parseable.
102   bool HasMore();
103 
104   // Reads the current TLV from the input and advances. If the tag or length
105   // encoding for the current value is invalid, this method returns false and
106   // does not advance the input. Otherwise, it returns true, putting the
107   // read tag in |tag| and the value in |out|.
108   [[nodiscard]] bool ReadTagAndValue(CBS_ASN1_TAG *tag, Input *out);
109 
110   // Reads the current TLV from the input and advances. Unlike ReadTagAndValue
111   // where only the value is put in |out|, this puts the raw bytes from the
112   // tag, length, and value in |out|.
113   [[nodiscard]] bool ReadRawTLV(Input *out);
114 
115   // Basic methods for reading or skipping the current TLV, with an
116   // expectation of what the current tag should be. It should be possible
117   // to parse any structure with these 4 methods; convenience methods are also
118   // provided to make some cases easier.
119 
120   // If the current tag in the input is |tag|, it puts the corresponding value
121   // in |out| and advances the input to the next TLV. If the current tag is
122   // something else, then |out| is set to nullopt and the input is not
123   // advanced. Like ReadTagAndValue, it returns false if the encoding is
124   // invalid and does not advance the input.
125   [[nodiscard]] bool ReadOptionalTag(CBS_ASN1_TAG tag, std::optional<Input> *out);
126 
127   // If the current tag in the input is |tag|, it puts the corresponding value
128   // in |out|, sets |was_present| to true, and advances the input to the next
129   // TLV. If the current tag is something else, then |was_present| is set to
130   // false and the input is not advanced. Like ReadTagAndValue, it returns
131   // false if the encoding is invalid and does not advance the input.
132   // DEPRECATED: use the std::optional version above in new code.
133   // TODO(mattm): convert the existing callers and remove this override.
134   [[nodiscard]] bool ReadOptionalTag(CBS_ASN1_TAG tag, Input *out, bool *was_present);
135 
136   // Like ReadOptionalTag, but the value is discarded.
137   [[nodiscard]] bool SkipOptionalTag(CBS_ASN1_TAG tag, bool *was_present);
138 
139   // If the current tag matches |tag|, it puts the current value in |out|,
140   // advances the input, and returns true. Otherwise, it returns false.
141   [[nodiscard]] bool ReadTag(CBS_ASN1_TAG tag, Input *out);
142 
143   // Advances the input and returns true if the current tag matches |tag|;
144   // otherwise it returns false.
145   [[nodiscard]] bool SkipTag(CBS_ASN1_TAG tag);
146 
147   // Convenience methods to combine parsing the TLV with parsing the DER
148   // encoding for a specific type.
149 
150   // Reads the current TLV from the input, checks that the tag matches |tag|
151   // and is a constructed tag, and creates a new Parser from the value.
152   [[nodiscard]] bool ReadConstructed(CBS_ASN1_TAG tag, Parser *out);
153 
154   // A more specific form of ReadConstructed that expects the current tag
155   // to be 0x30 (SEQUENCE).
156   [[nodiscard]] bool ReadSequence(Parser *out);
157 
158   // Expects the current tag to be kInteger, and calls ParseUint8 on the
159   // current value. Note that DER-encoded integers are arbitrary precision,
160   // so this method will fail for valid input that represents an integer
161   // outside the range of an uint8_t.
162   //
163   // Note that on failure the Parser is left in an undefined state (the
164   // input may or may not have been advanced).
165   [[nodiscard]] bool ReadUint8(uint8_t *out);
166 
167   // Expects the current tag to be kInteger, and calls ParseUint64 on the
168   // current value. Note that DER-encoded integers are arbitrary precision,
169   // so this method will fail for valid input that represents an integer
170   // outside the range of an uint64_t.
171   //
172   // Note that on failure the Parser is left in an undefined state (the
173   // input may or may not have been advanced).
174   [[nodiscard]] bool ReadUint64(uint64_t *out);
175 
176   // Reads a BIT STRING. On success returns BitString. On failure, returns
177   // std::nullopt.
178   //
179   // Note that on failure the Parser is left in an undefined state (the
180   // input may or may not have been advanced).
181   [[nodiscard]] std::optional<BitString> ReadBitString();
182 
183   // Reads a GeneralizeTime. On success fills |out| and returns true.
184   //
185   // Note that on failure the Parser is left in an undefined state (the
186   // input may or may not have been advanced).
187   [[nodiscard]] bool ReadGeneralizedTime(GeneralizedTime *out);
188 
189   // Lower level methods. The previous methods couple reading data from the
190   // input with advancing the Parser's internal pointer to the next TLV; these
191   // lower level methods decouple those two steps into methods that read from
192   // the current TLV and a method that advances the internal pointer to the
193   // next TLV.
194 
195   // Reads the current TLV from the input, putting the tag in |tag| and the raw
196   // value in |out|, but does not advance the input. Returns true if the tag
197   // and length are successfully read and the output exists.
198   [[nodiscard]] bool PeekTagAndValue(CBS_ASN1_TAG *tag, Input *out);
199 
200   // Advances the input to the next TLV. This method only needs to be called
201   // after PeekTagAndValue; all other methods will advance the input if they
202   // read something.
203   bool Advance();
204 
205  private:
206   CBS cbs_;
207   size_t advance_len_ = 0;
208 };
209 
210 }  // namespace bssl::der
211 
212 #endif  // BSSL_DER_PARSER_H_
213