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