Botan 3.11.0
Crypto and TLS for C&
ber_dec.cpp
Go to the documentation of this file.
1/*
2* BER Decoder
3* (C) 1999-2008,2015,2017,2018 Jack Lloyd
4*
5* Botan is released under the Simplified BSD License (see license.txt)
6*/
7
8#include <botan/ber_dec.h>
9
10#include <botan/bigint.h>
11#include <botan/data_src.h>
12#include <botan/internal/int_utils.h>
13#include <botan/internal/loadstor.h>
14#include <memory>
15
16namespace Botan {
17
18namespace {
19
20/*
21* This value is somewhat arbitrary. OpenSSL allows up to 128 nested
22* indefinite length sequences. If you increase this, also increase the
23* limit in the test in test_asn1.cpp
24*/
25const size_t ALLOWED_EOC_NESTINGS = 16;
26
27/*
28* BER decode an ASN.1 type tag
29*/
30size_t decode_tag(DataSource* ber, ASN1_Type& type_tag, ASN1_Class& class_tag) {
31 auto b = ber->read_byte();
32
33 if(!b) {
34 type_tag = ASN1_Type::NoObject;
35 class_tag = ASN1_Class::NoObject;
36 return 0;
37 }
38
39 if((*b & 0x1F) != 0x1F) {
40 type_tag = ASN1_Type(*b & 0x1F);
41 class_tag = ASN1_Class(*b & 0xE0);
42 return 1;
43 }
44
45 size_t tag_bytes = 1;
46 class_tag = ASN1_Class(*b & 0xE0);
47
48 size_t tag_buf = 0;
49 while(true) {
50 b = ber->read_byte();
51 if(!b) {
52 throw BER_Decoding_Error("Long-form tag truncated");
53 }
54 if((tag_buf >> 24) != 0) {
55 throw BER_Decoding_Error("Long-form tag overflowed 32 bits");
56 }
57 // This is required even by BER (see X.690 section 8.1.2.4.2 sentence c)
58 if(tag_bytes == 0 && b == 0x80) {
59 throw BER_Decoding_Error("Long form tag with leading zero");
60 }
61 ++tag_bytes;
62 tag_buf = (tag_buf << 7) | (*b & 0x7F);
63 if((*b & 0x80) == 0) {
64 break;
65 }
66 }
67 type_tag = ASN1_Type(tag_buf);
68 return tag_bytes;
69}
70
71/*
72* Find the EOC marker
73*/
74size_t find_eoc(DataSource* src, size_t allow_indef);
75
76/*
77* BER decode an ASN.1 length field
78*/
79size_t decode_length(DataSource* ber, size_t& field_size, size_t allow_indef) {
80 uint8_t b = 0;
81 if(ber->read_byte(b) == 0) {
82 throw BER_Decoding_Error("Length field not found");
83 }
84 field_size = 1;
85 if((b & 0x80) == 0) {
86 return b;
87 }
88
89 field_size += (b & 0x7F);
90 if(field_size > 5) {
91 throw BER_Decoding_Error("Length field is too large");
92 }
93
94 if(field_size == 1) {
95 if(allow_indef == 0) {
96 throw BER_Decoding_Error("Nested EOC markers too deep, rejecting to avoid stack exhaustion");
97 } else {
98 return find_eoc(ber, allow_indef - 1);
99 }
100 }
101
102 size_t length = 0;
103
104 for(size_t i = 0; i != field_size - 1; ++i) {
105 if(get_byte<0>(length) != 0) {
106 throw BER_Decoding_Error("Field length overflow");
107 }
108 if(ber->read_byte(b) == 0) {
109 throw BER_Decoding_Error("Corrupted length field");
110 }
111 length = (length << 8) | b;
112 }
113 return length;
114}
115
116/*
117* Find the EOC marker
118*/
119size_t find_eoc(DataSource* ber, size_t allow_indef) {
122
123 while(true) {
124 const size_t got = ber->peek(buffer.data(), buffer.size(), data.size());
125 if(got == 0) {
126 break;
127 }
128
129 data += std::make_pair(buffer.data(), got);
130 }
131
132 DataSource_Memory source(data);
133 data.clear();
134
135 size_t length = 0;
136 while(true) {
139 const size_t tag_size = decode_tag(&source, type_tag, class_tag);
140 if(type_tag == ASN1_Type::NoObject) {
141 break;
142 }
143
144 size_t length_size = 0;
145 const size_t item_size = decode_length(&source, length_size, allow_indef);
146 source.discard_next(item_size);
147
148 if(auto new_len = checked_add(length, item_size, tag_size, length_size)) {
149 length = new_len.value();
150 } else {
151 throw Decoding_Error("Integer overflow while decoding DER");
152 }
153
154 if(type_tag == ASN1_Type::Eoc && class_tag == ASN1_Class::Universal) {
155 break;
156 }
157 }
158 return length;
159}
160
161class DataSource_BERObject final : public DataSource {
162 public:
163 size_t read(uint8_t out[], size_t length) override {
164 BOTAN_ASSERT_NOMSG(m_offset <= m_obj.length());
165 const size_t got = std::min<size_t>(m_obj.length() - m_offset, length);
166 copy_mem(out, m_obj.bits() + m_offset, got);
167 m_offset += got;
168 return got;
169 }
170
171 size_t peek(uint8_t out[], size_t length, size_t peek_offset) const override {
172 BOTAN_ASSERT_NOMSG(m_offset <= m_obj.length());
173 const size_t bytes_left = m_obj.length() - m_offset;
174
175 if(peek_offset >= bytes_left) {
176 return 0;
177 }
178
179 const size_t got = std::min(bytes_left - peek_offset, length);
180 copy_mem(out, m_obj.bits() + m_offset + peek_offset, got);
181 return got;
182 }
183
184 bool check_available(size_t n) override {
185 BOTAN_ASSERT_NOMSG(m_offset <= m_obj.length());
186 return (n <= (m_obj.length() - m_offset));
187 }
188
189 bool end_of_data() const override { return get_bytes_read() == m_obj.length(); }
190
191 size_t get_bytes_read() const override { return m_offset; }
192
193 explicit DataSource_BERObject(BER_Object&& obj) : m_obj(std::move(obj)) {}
194
195 private:
196 BER_Object m_obj;
197 size_t m_offset = 0;
198};
199
200} // namespace
201
202BER_Decoder::~BER_Decoder() = default;
203
204/*
205* Check if more objects are there
206*/
208 if(m_source->end_of_data() && !m_pushed.is_set()) {
209 return false;
210 }
211 return true;
212}
213
214/*
215* Verify that no bytes remain in the source
216*/
218 return verify_end("BER_Decoder::verify_end called, but data remains");
219}
220
221/*
222* Verify that no bytes remain in the source
223*/
224BER_Decoder& BER_Decoder::verify_end(std::string_view err) {
225 if(!m_source->end_of_data() || m_pushed.is_set()) {
226 throw Decoding_Error(err);
227 }
228 return (*this);
229}
230
231/*
232* Discard all the bytes remaining in the source
233*/
235 uint8_t buf = 0;
236 while(m_source->read_byte(buf) != 0) {}
237 return (*this);
238}
239
240std::optional<uint8_t> BER_Decoder::read_next_byte() {
241 BOTAN_ASSERT_NOMSG(m_source != nullptr);
242 uint8_t b = 0;
243 if(m_source->read_byte(b) != 0) {
244 return b;
245 } else {
246 return {};
247 }
248}
249
251 if(!m_pushed.is_set()) {
252 m_pushed = get_next_object();
253 }
254
255 return m_pushed;
256}
257
258/*
259* Return the BER encoding of the next object
260*/
262 BER_Object next;
263
264 if(m_pushed.is_set()) {
265 std::swap(next, m_pushed);
266 return next;
267 }
268
269 for(;;) {
272 decode_tag(m_source, type_tag, class_tag);
273 next.set_tagging(type_tag, class_tag);
274 if(next.is_set() == false) { // no more objects
275 return next;
276 }
277
278 size_t field_size = 0;
279 const size_t length = decode_length(m_source, field_size, ALLOWED_EOC_NESTINGS);
280 if(!m_source->check_available(length)) {
281 throw BER_Decoding_Error("Value truncated");
282 }
283
284 uint8_t* out = next.mutable_bits(length);
285 if(m_source->read(out, length) != length) {
286 throw BER_Decoding_Error("Value truncated");
287 }
288
289 if(next.tagging() == static_cast<uint32_t>(ASN1_Type::Eoc)) {
290 continue;
291 } else {
292 break;
293 }
294 }
295
296 return next;
297}
298
299BER_Object BER_Decoder::get_next_value(size_t sizeofT, ASN1_Type type_tag, ASN1_Class class_tag) {
300 const BER_Object obj = get_next_object();
301 obj.assert_is_a(type_tag, class_tag);
302
303 if(obj.length() != sizeofT) {
304 throw BER_Decoding_Error("Size mismatch. Object value size is " + std::to_string(obj.length()) +
305 "; Output type size is " + std::to_string(sizeofT));
306 }
307
308 return obj;
309}
310
311/*
312* Push a object back into the stream
313*/
315 if(m_pushed.is_set()) {
316 throw Invalid_State("BER_Decoder: Only one push back is allowed");
317 }
318 m_pushed = obj;
319}
320
322 if(m_pushed.is_set()) {
323 throw Invalid_State("BER_Decoder: Only one push back is allowed");
324 }
325 m_pushed = std::move(obj);
326}
327
330 obj.assert_is_a(type_tag, class_tag | ASN1_Class::Constructed);
331 return BER_Decoder(std::move(obj), this);
332}
333
334/*
335* Finish decoding a CONSTRUCTED type
336*/
338 if(m_parent == nullptr) {
339 throw Invalid_State("BER_Decoder::end_cons called with null parent");
340 }
341 if(!m_source->end_of_data()) {
342 throw Decoding_Error("BER_Decoder::end_cons called with data left");
343 }
344 return (*m_parent);
345}
346
347BER_Decoder::BER_Decoder(BER_Object&& obj, BER_Decoder* parent) : m_parent(parent) {
348 m_data_src = std::make_unique<DataSource_BERObject>(std::move(obj));
349 m_source = m_data_src.get();
350}
351
352/*
353* BER_Decoder Constructor
354*/
355BER_Decoder::BER_Decoder(DataSource& src) : m_source(&src) {}
356
357/*
358* BER_Decoder Constructor
359 */
360BER_Decoder::BER_Decoder(const uint8_t data[], size_t length) {
361 m_data_src = std::make_unique<DataSource_Memory>(data, length);
362 m_source = m_data_src.get();
363}
364
365/*
366* BER_Decoder Constructor
367*/
369 m_data_src = std::make_unique<DataSource_Memory>(data);
370 m_source = m_data_src.get();
371}
372
373/*
374* BER_Decoder Constructor
375*/
376BER_Decoder::BER_Decoder(const std::vector<uint8_t>& data) {
377 m_data_src = std::make_unique<DataSource_Memory>(data.data(), data.size());
378 m_source = m_data_src.get();
379}
380
381/*
382* BER_Decoder Copy Constructor
383*/
384BER_Decoder::BER_Decoder(const BER_Decoder& other) : m_parent(other.m_parent), m_source(other.m_source) {
385 // take ownership of other's data source
386 std::swap(m_data_src, other.m_data_src);
387}
388
389BER_Decoder::BER_Decoder(BER_Decoder&& other) noexcept = default;
390
391BER_Decoder& BER_Decoder::operator=(BER_Decoder&&) noexcept = default;
392
393/*
394* Request for an object to decode itself
395*/
397 obj.decode_from(*this);
398 return (*this);
399}
400
401/*
402* Decode a BER encoded NULL
403*/
405 const BER_Object obj = get_next_object();
407 if(obj.length() > 0) {
408 throw BER_Decoding_Error("NULL object had nonzero size");
409 }
410 return (*this);
411}
412
416 out = BigInt::from_bytes(out_vec);
417 return (*this);
418}
419
420/*
421* Decode a BER encoded BOOLEAN
422*/
423BER_Decoder& BER_Decoder::decode(bool& out, ASN1_Type type_tag, ASN1_Class class_tag) {
424 const BER_Object obj = get_next_object();
425 obj.assert_is_a(type_tag, class_tag);
426
427 if(obj.length() != 1) {
428 throw BER_Decoding_Error("BER boolean value had invalid size");
429 }
430
431 const uint8_t val = obj.bits()[0];
432
433 // TODO if decoding DER we should reject non-canonical booleans
434 out = (val != 0) ? true : false;
435
436 return (*this);
437}
438
439/*
440* Decode a small BER encoded INTEGER
441*/
442BER_Decoder& BER_Decoder::decode(size_t& out, ASN1_Type type_tag, ASN1_Class class_tag) {
443 BigInt integer;
444 decode(integer, type_tag, class_tag);
445
446 if(integer.is_negative()) {
447 throw BER_Decoding_Error("Decoded small integer value was negative");
448 }
449
450 if(integer.bits() > 32) {
451 throw BER_Decoding_Error("Decoded integer value larger than expected");
452 }
453
454 out = 0;
455 for(size_t i = 0; i != 4; ++i) {
456 out = (out << 8) | integer.byte_at(3 - i);
457 }
458
459 return (*this);
460}
461
462/*
463* Decode a small BER encoded INTEGER
464*/
465uint64_t BER_Decoder::decode_constrained_integer(ASN1_Type type_tag, ASN1_Class class_tag, size_t T_bytes) {
466 if(T_bytes > 8) {
467 throw BER_Decoding_Error("Can't decode small integer over 8 bytes");
468 }
469
470 BigInt integer;
471 decode(integer, type_tag, class_tag);
472
473 if(integer.bits() > 8 * T_bytes) {
474 throw BER_Decoding_Error("Decoded integer value larger than expected");
475 }
476
477 uint64_t out = 0;
478 for(size_t i = 0; i != 8; ++i) {
479 out = (out << 8) | integer.byte_at(7 - i);
480 }
481
482 return out;
483}
484
485/*
486* Decode a BER encoded INTEGER
487*/
489 const BER_Object obj = get_next_object();
490 obj.assert_is_a(type_tag, class_tag);
491
492 if(obj.length() == 0) {
493 out.clear();
494 } else {
495 const uint8_t first = obj.bits()[0];
496 const bool negative = (first & 0x80) == 0x80;
497
498 if(negative) {
499 secure_vector<uint8_t> vec(obj.bits(), obj.bits() + obj.length());
500 for(size_t i = obj.length(); i > 0; --i) {
501 const bool gt0 = (vec[i - 1] > 0);
502 vec[i - 1] -= 1;
503 if(gt0) {
504 break;
505 }
506 }
507 for(size_t i = 0; i != obj.length(); ++i) {
508 vec[i] = ~vec[i];
509 }
510 out._assign_from_bytes(vec);
511 out.flip_sign();
512 } else {
513 out._assign_from_bytes(obj.data());
514 }
515 }
516
517 return (*this);
518}
519
520namespace {
521
522template <typename Alloc>
523void asn1_decode_binary_string(std::vector<uint8_t, Alloc>& buffer,
524 const BER_Object& obj,
525 ASN1_Type real_type,
526 ASN1_Type type_tag,
527 ASN1_Class class_tag) {
528 obj.assert_is_a(type_tag, class_tag);
529
530 if(real_type == ASN1_Type::OctetString) {
531 buffer.assign(obj.bits(), obj.bits() + obj.length());
532 } else {
533 if(obj.length() == 0) {
534 throw BER_Decoding_Error("Invalid BIT STRING");
535 }
536 if(obj.bits()[0] >= 8) {
537 throw BER_Decoding_Error("Bad number of unused bits in BIT STRING");
538 }
539
540 buffer.resize(obj.length() - 1);
541
542 if(obj.length() > 1) {
543 copy_mem(buffer.data(), obj.bits() + 1, obj.length() - 1);
544 }
545 }
546}
547
548} // namespace
549
550/*
551* BER decode a BIT STRING or OCTET STRING
552*/
554 ASN1_Type real_type,
555 ASN1_Type type_tag,
556 ASN1_Class class_tag) {
557 if(real_type != ASN1_Type::OctetString && real_type != ASN1_Type::BitString) {
558 throw BER_Bad_Tag("Bad tag for {BIT,OCTET} STRING", static_cast<uint32_t>(real_type));
559 }
560
561 asn1_decode_binary_string(buffer, get_next_object(), real_type, type_tag, class_tag);
562 return (*this);
563}
564
565BER_Decoder& BER_Decoder::decode(std::vector<uint8_t>& buffer,
566 ASN1_Type real_type,
567 ASN1_Type type_tag,
568 ASN1_Class class_tag) {
569 if(real_type != ASN1_Type::OctetString && real_type != ASN1_Type::BitString) {
570 throw BER_Bad_Tag("Bad tag for {BIT,OCTET} STRING", static_cast<uint32_t>(real_type));
571 }
572
573 asn1_decode_binary_string(buffer, get_next_object(), real_type, type_tag, class_tag);
574 return (*this);
575}
576
577} // namespace Botan
#define BOTAN_ASSERT_NOMSG(expr)
Definition assert.h:75
BER_Decoder(const uint8_t buf[], size_t len)
Definition ber_dec.cpp:360
const BER_Object & peek_next_object()
Definition ber_dec.cpp:250
void push_back(const BER_Object &obj)
Definition ber_dec.cpp:314
BER_Object get_next_object()
Definition ber_dec.cpp:261
BER_Decoder & get_next_value(T &out, ASN1_Type type_tag, ASN1_Class class_tag=ASN1_Class::ContextSpecific)
Definition ber_dec.h:157
BER_Decoder & decode(bool &out)
Definition ber_dec.h:188
uint64_t decode_constrained_integer(ASN1_Type type_tag, ASN1_Class class_tag, size_t T_bytes)
Definition ber_dec.cpp:465
bool more_items() const
Definition ber_dec.cpp:207
BER_Decoder & verify_end()
Definition ber_dec.cpp:217
BER_Decoder & end_cons()
Definition ber_dec.cpp:337
BER_Decoder start_cons(ASN1_Type type_tag, ASN1_Class class_tag)
Definition ber_dec.cpp:328
BER_Decoder & discard_remaining()
Definition ber_dec.cpp:234
BER_Decoder & decode_octet_string_bigint(BigInt &b)
Definition ber_dec.cpp:413
BER_Decoder & decode_null()
Definition ber_dec.cpp:404
BER_Decoder & operator=(const BER_Decoder &)=delete
size_t length() const
Definition asn1_obj.h:152
const uint8_t * bits() const
Definition asn1_obj.h:150
void assert_is_a(ASN1_Type type_tag, ASN1_Class class_tag, std::string_view descr="object") const
Definition asn1_obj.cpp:34
uint32_t tagging() const
Definition asn1_obj.h:140
bool is_set() const
Definition asn1_obj.h:138
std::span< const uint8_t > data() const
Definition asn1_obj.h:154
void flip_sign()
Definition bigint.h:602
static BigInt from_bytes(std::span< const uint8_t > bytes)
Definition bigint.cpp:83
size_t bits() const
Definition bigint.cpp:307
uint8_t byte_at(size_t n) const
Definition bigint.cpp:118
void clear()
Definition bigint.h:415
void _assign_from_bytes(std::span< const uint8_t > bytes)
Definition bigint.h:963
bool is_negative() const
Definition bigint.h:575
size_t read_byte(uint8_t &out)
Definition data_src.cpp:27
constexpr uint8_t get_byte(T input)
Definition loadstor.h:79
constexpr std::optional< T > checked_add(T a, T b)
Definition int_utils.h:19
constexpr void copy_mem(T *out, const T *in, size_t n)
Definition mem_ops.h:144
ASN1_Class
Definition asn1_obj.h:28
ASN1_Type
Definition asn1_obj.h:43
std::vector< T, secure_allocator< T > > secure_vector
Definition secmem.h:68
constexpr size_t DefaultBufferSize
Definition types.h:137