• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

randombit / botan / 28768347627

05 Jul 2026 06:04PM UTC coverage: 89.35% (+0.008%) from 89.342%
28768347627

push

github

web-flow
Merge pull request #5710 from randombit/jack/asn1-hardening

ASN.1 hardenings and improved decoder strictness

112337 of 125727 relevant lines covered (89.35%)

11029908.92 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

89.71
/src/tests/test_asn1.cpp
1
/*
2
* (C) 2017 Jack Lloyd
3
*
4
* Botan is released under the Simplified BSD License (see license.txt)
5
*/
6

7
#include "tests.h"
8

9
#if defined(BOTAN_HAS_ASN1)
10
   #include <botan/asn1_obj.h>
11
   #include <botan/asn1_print.h>
12
   #include <botan/asn1_time.h>
13
   #include <botan/ber_dec.h>
14
   #include <botan/bigint.h>
15
   #include <botan/data_src.h>
16
   #include <botan/der_enc.h>
17
   #include <botan/hex.h>
18
   #include <botan/pss_params.h>
19
   #include <botan/internal/fmt.h>
20
   #include <botan/internal/parsing.h>
21
#endif
22

23
namespace Botan_Tests {
24

25
namespace {
26

27
#if defined(BOTAN_HAS_ASN1)
28

29
class ASN1_Test_Sequence final : public Botan::ASN1_Object {
2✔
30
   public:
31
      explicit ASN1_Test_Sequence(size_t value = 0) : m_value(value) {}
2✔
32

33
      void encode_into(Botan::DER_Encoder& der) const override { der.start_sequence().encode(m_value).end_cons(); }
1✔
34

35
      void decode_from(Botan::BER_Decoder& ber) override { ber.start_sequence().decode(m_value).end_cons(); }
1✔
36

37
      size_t value() const { return m_value; }
1✔
38

39
   private:
40
      size_t m_value;
41
};
42

43
Test::Result test_ber_stack_recursion() {
1✔
44
   Test::Result result("BER stack recursion");
1✔
45

46
   // OSS-Fuzz #813 GitHub #989
47

48
   try {
1✔
49
      const std::vector<uint8_t> in(10000000, 0);
1✔
50
      Botan::DataSource_Memory input(in.data(), in.size());
1✔
51
      Botan::BER_Decoder dec(input);
1✔
52

53
      while(dec.more_items()) {
1✔
54
         Botan::BER_Object obj;
1✔
55
         dec.get_next(obj);
1✔
56
      }
1✔
57
   } catch(Botan::Decoding_Error&) {}
3✔
58

59
   result.test_success("No crash");
1✔
60

61
   return result;
1✔
62
}
×
63

64
Test::Result test_ber_eoc_decoding_limits() {
1✔
65
   Test::Result result("BER nested indefinite length");
1✔
66

67
   // OSS-Fuzz #4353
68

69
   const Botan::ASN1_Pretty_Printer printer;
1✔
70

71
   size_t max_eoc_allowed = 0;
1✔
72

73
   for(size_t len = 1; len < 1024; ++len) {
17✔
74
      std::vector<uint8_t> buf(4 * len);
17✔
75

76
      /*
77
      This constructs a len deep sequence of SEQUENCES each with
78
      an indefinite length
79
      */
80
      for(size_t i = 0; i != 2 * len; i += 2) {
170✔
81
         buf[i] = 0x30;
153✔
82
         buf[i + 1] = 0x80;
153✔
83
      }
84
      // remainder of values left as zeros (EOC markers)
85

86
      try {
17✔
87
         printer.print(buf);
17✔
88
      } catch(Botan::BER_Decoding_Error&) {
1✔
89
         max_eoc_allowed = len - 1;
1✔
90
         break;
1✔
91
      }
1✔
92
   }
17✔
93

94
   result.test_sz_eq("EOC limited to prevent stack exhaustion", max_eoc_allowed, 16);
1✔
95

96
   return result;
1✔
97
}
1✔
98

99
Test::Result test_ber_standalone_eoc_limits() {
1✔
100
   Test::Result result("BER standalone EOC handling");
1✔
101

102
   // Empty SEQUENCE (30 00) followed by a standalone EOC marker (00 00) that
103
   // does not terminate any indefinite-length encoding.
104
   const std::vector<uint8_t> wire = {0x30, 0x00, 0x00, 0x00};
1✔
105

106
   auto count_objects = [](const std::vector<uint8_t>& in, Botan::BER_Decoder::Limits limits) {
6✔
107
      Botan::BER_Decoder dec(in, limits);
5✔
108
      size_t objects = 0;
5✔
109
      while(dec.more_items()) {
8✔
110
         if(dec.get_next_object().is_set()) {
7✔
111
            objects += 1;
2✔
112
         }
113
      }
114
      return objects;
1✔
115
   };
5✔
116

117
   // A standalone EOC marker is rejected by default
118
   result.test_throws<Botan::Decoding_Error>("standalone EOC rejected by default",
1✔
119
                                             [&]() { count_objects(wire, Botan::BER_Decoder::Limits::BER()); });
2✔
120

121
   // ... but tolerated when the decoder is configured to allow it
122
   try {
1✔
123
      const size_t objects = count_objects(wire, Botan::BER_Decoder::Limits::BER().with_standalone_eoc_allowed());
1✔
124
      result.test_sz_eq("standalone EOC skipped when allowed", objects, 1);
1✔
125
   } catch(const std::exception& e) {
×
126
      result.test_failure(Botan::fmt("standalone EOC unexpectedly rejected: {}", e.what()));
×
127
   }
×
128

129
   // A constructed encoding of the EOC tag (20 00) is not an EOC marker at
130
   // all; it is rejected in every mode, including with the leniency flag
131
   const std::vector<uint8_t> cons_eoc = {0x20, 0x00};
1✔
132

133
   for(auto limits : {Botan::BER_Decoder::Limits::DER(),
1✔
134
                      Botan::BER_Decoder::Limits::BER(),
1✔
135
                      Botan::BER_Decoder::Limits::BER().with_standalone_eoc_allowed()}) {
4✔
136
      result.test_throws<Botan::Decoding_Error>("constructed EOC tag rejected",
3✔
137
                                                [&]() { count_objects(cons_eoc, limits); });
9✔
138
   }
139

140
   return result;
1✔
141
}
1✔
142

143
Test::Result test_ber_max_object_size() {
1✔
144
   Test::Result result("BER maximum object size");
1✔
145

146
   // OCTET STRING with 5 content bytes
147
   const std::vector<uint8_t> obj = {0x04, 0x05, 0x01, 0x02, 0x03, 0x04, 0x05};
1✔
148

149
   auto decode = [&](const char* what, Botan::BER_Decoder::Limits limits, bool expect_ok) {
5✔
150
      try {
4✔
151
         Botan::BER_Decoder(obj, limits).get_next_object();
4✔
152
         result.test_bool_eq(what, true, expect_ok);
3✔
153
      } catch(const Botan::Decoding_Error&) {
1✔
154
         result.test_bool_eq(what, false, expect_ok);
1✔
155
      }
1✔
156
   };
4✔
157

158
   using Limits = Botan::BER_Decoder::Limits;
1✔
159

160
   decode("accepted under the default limit", Limits::BER(), true);
1✔
161
   decode("accepted at exactly the limit", Limits::BER().with_max_object_size(5), true);
1✔
162
   decode("rejected one byte over the limit", Limits::BER().with_max_object_size(4), false);
1✔
163
   decode("accepted when the limit is disabled", Limits::BER().with_max_object_size(std::nullopt), true);
1✔
164

165
   return result;
1✔
166
}
1✔
167

168
Test::Result test_ber_constructed_string_rejected() {
1✔
169
   Test::Result result("BER constructed OCTET/BIT STRING rejected");
1✔
170

171
   using Botan::ASN1_Class;
1✔
172
   using Botan::ASN1_Type;
1✔
173

174
   // Constructed OCTET STRING (24) wrapping two OCTET STRING fragments
175
   const std::vector<uint8_t> cons_octet = {0x24, 0x06, 0x04, 0x02, 0xAA, 0xBB, 0x04, 0x00};
1✔
176
   // Constructed BIT STRING (23) wrapping one BIT STRING fragment
177
   const std::vector<uint8_t> cons_bits = {0x23, 0x04, 0x03, 0x02, 0x00, 0xAA};
1✔
178

179
   // Reachable when the caller's expected class matches the constructed object;
180
   // rejected in both BER and DER
181
   for(auto limits : {Botan::BER_Decoder::Limits::BER(), Botan::BER_Decoder::Limits::DER()}) {
3✔
182
      result.test_throws<Botan::Decoding_Error>("constructed OCTET STRING rejected", [&]() {
2✔
183
         std::vector<uint8_t> out;
2✔
184
         Botan::BER_Decoder(cons_octet, limits)
4✔
185
            .decode(out, ASN1_Type::OctetString, ASN1_Type::OctetString, ASN1_Class::Constructed);
2✔
186
      });
2✔
187

188
      result.test_throws<Botan::Decoding_Error>("constructed BIT STRING rejected", [&]() {
2✔
189
         std::vector<uint8_t> out;
2✔
190
         Botan::BER_Decoder(cons_bits, limits)
4✔
191
            .decode(out, ASN1_Type::BitString, ASN1_Type::BitString, ASN1_Class::Constructed);
2✔
192
      });
2✔
193

194
      result.test_throws<Botan::Decoding_Error>("constructed BIT STRING rejected via decode_bitstring", [&]() {
2✔
195
         Botan::ASN1_BitString bs;
2✔
196
         Botan::BER_Decoder(cons_bits, limits).decode_bitstring(bs, ASN1_Type::BitString, ASN1_Class::Constructed);
4✔
197
      });
×
198
   }
199

200
   return result;
1✔
201
}
1✔
202

203
Test::Result test_asn1_utf8_ascii_parsing() {
1✔
204
   Test::Result result("ASN.1 ASCII parsing");
1✔
205

206
   try {
1✔
207
      // \x13 - ASN1 tag for 'printable string'
208
      // \x06 - 6 characters of payload
209
      // ...  - UTF-8 encoded (ASCII chars only) word 'Moscow'
210
      const std::string moscow = "\x13\x06\x4D\x6F\x73\x63\x6F\x77";
1✔
211
      const std::string moscow_plain = "Moscow";
1✔
212
      Botan::DataSource_Memory input(moscow);
1✔
213
      Botan::BER_Decoder dec(input);
1✔
214

215
      Botan::ASN1_String str;
1✔
216
      str.decode_from(dec);
1✔
217

218
      result.test_str_eq("value()", str.value(), moscow_plain);
1✔
219
   } catch(const Botan::Decoding_Error& ex) {
2✔
220
      result.test_failure(ex.what());
×
221
   }
×
222

223
   return result;
1✔
224
}
×
225

226
Test::Result test_asn1_utf8_parsing() {
1✔
227
   Test::Result result("ASN.1 UTF-8 parsing");
1✔
228

229
   try {
1✔
230
      // \x0C - ASN1 tag for 'UTF8 string'
231
      // \x0C - 12 characters of payload
232
      // ...  - UTF-8 encoded russian word for Moscow in cyrillic script
233
      const std::string moscow = "\x0C\x0C\xD0\x9C\xD0\xBE\xD1\x81\xD0\xBA\xD0\xB2\xD0\xB0";
1✔
234
      const std::string moscow_plain = "\xD0\x9C\xD0\xBE\xD1\x81\xD0\xBA\xD0\xB2\xD0\xB0";
1✔
235
      Botan::DataSource_Memory input(moscow);
1✔
236
      Botan::BER_Decoder dec(input);
1✔
237

238
      Botan::ASN1_String str;
1✔
239
      str.decode_from(dec);
1✔
240

241
      result.test_str_eq("value()", str.value(), moscow_plain);
1✔
242
   } catch(const Botan::Decoding_Error& ex) {
2✔
243
      result.test_failure(ex.what());
×
244
   }
×
245

246
   return result;
1✔
247
}
×
248

249
Test::Result test_asn1_ucs2_parsing() {
1✔
250
   Test::Result result("ASN.1 BMP string (UCS-2) parsing");
1✔
251

252
   try {
1✔
253
      // \x1E     - ASN1 tag for 'BMP (UCS-2) string'
254
      // \x0C     - 12 characters of payload
255
      // ...      - UCS-2 encoding for Moscow in cyrillic script
256
      const std::string moscow = "\x1E\x0C\x04\x1C\x04\x3E\x04\x41\x04\x3A\x04\x32\x04\x30";
1✔
257
      const std::string moscow_plain = "\xD0\x9C\xD0\xBE\xD1\x81\xD0\xBA\xD0\xB2\xD0\xB0";
1✔
258

259
      Botan::DataSource_Memory input(moscow);
1✔
260
      Botan::BER_Decoder dec(input);
1✔
261

262
      Botan::ASN1_String str;
1✔
263
      str.decode_from(dec);
1✔
264

265
      result.test_str_eq("value()", str.value(), moscow_plain);
1✔
266
   } catch(const Botan::Decoding_Error& ex) {
2✔
267
      result.test_failure(ex.what());
×
268
   }
×
269

270
   return result;
1✔
271
}
×
272

273
Test::Result test_asn1_ucs4_parsing() {
1✔
274
   Test::Result result("ASN.1 universal string (UCS-4) parsing");
1✔
275

276
   try {
1✔
277
      // \x1C - ASN1 tag for 'universal string'
278
      // \x18 - 24 characters of payload
279
      // ...  - UCS-4 encoding for Moscow in cyrillic script
280
      const uint8_t moscow[] =
1✔
281
         "\x1C\x18\x00\x00\x04\x1C\x00\x00\x04\x3E\x00\x00\x04\x41\x00\x00\x04\x3A\x00\x00\x04\x32\x00\x00\x04\x30";
282
      const std::string moscow_plain = "\xD0\x9C\xD0\xBE\xD1\x81\xD0\xBA\xD0\xB2\xD0\xB0";
1✔
283
      Botan::DataSource_Memory input(moscow, sizeof(moscow));
1✔
284
      Botan::BER_Decoder dec(input);
1✔
285

286
      Botan::ASN1_String str;
1✔
287
      str.decode_from(dec);
1✔
288

289
      result.test_str_eq("value()", str.value(), moscow_plain);
1✔
290
   } catch(const Botan::Decoding_Error& ex) {
2✔
291
      result.test_failure(ex.what());
×
292
   }
×
293

294
   return result;
1✔
295
}
×
296

297
Test::Result test_asn1_ucs_invalid_codepoint_rejection() {
1✔
298
   Test::Result result("ASN.1 UCS-2/UCS-4 invalid codepoint rejection");
1✔
299

300
   auto expect_decode_throws = [&](const char* what, const std::vector<uint8_t>& wire) {
7✔
301
      result.test_throws(what, [&]() {
6✔
302
         Botan::DataSource_Memory input(wire.data(), wire.size());
6✔
303
         Botan::BER_Decoder dec(input);
6✔
304
         Botan::ASN1_String str;
6✔
305
         str.decode_from(dec);
6✔
306
      });
6✔
307
   };
6✔
308

309
   auto expect_decode_ok = [&](const char* what, const std::vector<uint8_t>& wire) {
2✔
310
      try {
1✔
311
         Botan::DataSource_Memory input(wire.data(), wire.size());
1✔
312
         Botan::BER_Decoder dec(input);
1✔
313
         Botan::ASN1_String str;
1✔
314
         str.decode_from(dec);
1✔
315
         result.test_success(what);
1✔
316
      } catch(const std::exception& ex) {
2✔
317
         result.test_failure(Botan::fmt("{}: unexpected throw: {}", what, ex.what()));
×
318
      }
×
319
   };
1✔
320

321
   // UniversalString (tag 0x1C) with codepoint 0x00110000 - one past Unicode max
322
   expect_decode_throws("UniversalString rejects codepoint > 0x10FFFF", {0x1C, 0x04, 0x00, 0x11, 0x00, 0x00});
1✔
323

324
   // UniversalString with codepoint 0xFFFFFFFF (clearly out of range)
325
   expect_decode_throws("UniversalString rejects codepoint 0xFFFFFFFF", {0x1C, 0x04, 0xFF, 0xFF, 0xFF, 0xFF});
1✔
326

327
   // UniversalString with high surrogate 0xD800
328
   expect_decode_throws("UniversalString rejects surrogate codepoint", {0x1C, 0x04, 0x00, 0x00, 0xD8, 0x00});
1✔
329

330
   // UniversalString boundary case: 0x10FFFF is the highest valid codepoint
331
   expect_decode_ok("UniversalString accepts codepoint 0x10FFFF", {0x1C, 0x04, 0x00, 0x10, 0xFF, 0xFF});
1✔
332

333
   // BmpString (tag 0x1E) with high surrogate
334
   expect_decode_throws("BmpString rejects surrogate codepoint", {0x1E, 0x02, 0xD8, 0x00});
1✔
335

336
   // BmpString with odd length is malformed
337
   expect_decode_throws("BmpString rejects odd-length payload", {0x1E, 0x03, 0x00, 0x41, 0x00});
1✔
338

339
   // UniversalString with non-multiple-of-4 length is malformed
340
   expect_decode_throws("UniversalString rejects non-multiple-of-4 payload",
1✔
341
                        {0x1C, 0x05, 0x00, 0x00, 0x00, 0x41, 0x00});
342

343
   return result;
1✔
344
}
×
345

346
Test::Result test_asn1_ascii_encoding() {
1✔
347
   Test::Result result("ASN.1 ASCII encoding");
1✔
348

349
   try {
1✔
350
      // UTF-8 encoded (ASCII chars only) word 'Moscow'
351
      const std::string moscow = "Moscow";
1✔
352
      const Botan::ASN1_String str(moscow);
1✔
353

354
      Botan::DER_Encoder enc;
1✔
355

356
      str.encode_into(enc);
1✔
357
      auto encodingResult = enc.get_contents();
1✔
358

359
      // \x13 - ASN1 tag for 'printable string'
360
      // \x06 - 6 characters of payload
361
      result.test_bin_eq("encoding result", encodingResult, "13064D6F73636F77");
1✔
362

363
      result.test_success("No crash");
1✔
364
   } catch(const std::exception& ex) {
2✔
365
      result.test_failure(ex.what());
×
366
   }
×
367

368
   return result;
1✔
369
}
×
370

371
Test::Result test_asn1_utf8_encoding() {
1✔
372
   Test::Result result("ASN.1 UTF-8 encoding");
1✔
373

374
   try {
1✔
375
      // UTF-8 encoded russian word for Moscow in cyrillic script
376
      const std::string moscow = "\xD0\x9C\xD0\xBE\xD1\x81\xD0\xBA\xD0\xB2\xD0\xB0";
1✔
377
      const Botan::ASN1_String str(moscow);
1✔
378

379
      Botan::DER_Encoder enc;
1✔
380

381
      str.encode_into(enc);
1✔
382
      auto encodingResult = enc.get_contents();
1✔
383

384
      // \x0C - ASN1 tag for 'UTF8 string'
385
      // \x0C - 12 characters of payload
386
      result.test_bin_eq("encoding result", encodingResult, "0C0CD09CD0BED181D0BAD0B2D0B0");
1✔
387

388
      result.test_success("No crash");
1✔
389
   } catch(const std::exception& ex) {
2✔
390
      result.test_failure(ex.what());
×
391
   }
×
392

393
   return result;
1✔
394
}
×
395

396
Test::Result test_asn1_tag_underlying_type() {
1✔
397
   Test::Result result("ASN.1 class and type underlying type");
1✔
398

399
   if constexpr(std::is_same_v<std::underlying_type_t<Botan::ASN1_Class>, std::underlying_type_t<Botan::ASN1_Type>>) {
1✔
400
      if constexpr(!std::is_same_v<std::underlying_type_t<Botan::ASN1_Class>,
1✔
401
                                   std::invoke_result_t<decltype(&Botan::BER_Object::tagging), Botan::BER_Object>>) {
402
         result.test_failure(
403
            "Return type of BER_Object::tagging() is different than the underlying type of ASN1_Class");
404
      } else {
405
         result.test_success("Same types");
1✔
406
      }
407
   } else {
408
      result.test_failure("ASN1_Class and ASN1_Type have different underlying types");
409
   }
410

411
   return result;
1✔
412
}
×
413

414
Test::Result test_asn1_high_tag_number() {
1✔
415
   Test::Result result("ASN.1 high tag number encode/decode");
1✔
416

417
   // The encoder emits high-tag-number encodings for the full uint32_t range,
418
   // so the decoder must round trip the same range.
419
   const std::vector<uint8_t> content = {0x01, 0x02, 0x03};
1✔
420

421
   const uint32_t tags[] = {31, 0x7FFFFFFF, 0x80000000, 0xFFFFFFFE, 0xFFFFFFFF};
1✔
422

423
   for(const uint32_t tag : tags) {
6✔
424
      Botan::DER_Encoder enc;
5✔
425
      // NOLINTNEXTLINE(clang-analyzer-optin.core.EnumCastOutOfRange)
426
      enc.add_object(static_cast<Botan::ASN1_Type>(tag), Botan::ASN1_Class::ContextSpecific, content);
5✔
427
      const auto der = enc.get_contents_unlocked();
5✔
428

429
      try {
5✔
430
         const Botan::BER_Object obj = Botan::BER_Decoder(der).get_next_object();
5✔
431
         result.test_sz_eq("decoded tag matches encoded tag", static_cast<uint32_t>(obj.type()), tag);
5✔
432
      } catch(const std::exception& e) {
5✔
433
         result.test_failure(Botan::fmt("tag {} unexpectedly rejected: {}", tag, e.what()));
×
434
      }
×
435
   }
5✔
436

437
   // A tag value that does not fit in uint32_t (here 2^32, encoded as
438
   // 1F 90 80 80 80 00) must be rejected rather than silently truncated.
439
   const std::vector<uint8_t> overflow_tag = {0x1F, 0x90, 0x80, 0x80, 0x80, 0x00};
1✔
440
   result.test_throws<Botan::Decoding_Error>("over-uint32 tag rejected",
1✔
441
                                             [&]() { Botan::BER_Decoder(overflow_tag).get_next_object(); });
2✔
442

443
   return result;
1✔
444
}
1✔
445

446
Test::Result test_asn1_negative_int_encoding() {
1✔
447
   Test::Result result("DER encode/decode of negative integers");
1✔
448

449
   BigInt n(32);
1✔
450

451
   for(size_t i = 0; i != 2048; ++i) {
2,049✔
452
      n--;
2,048✔
453

454
      const auto enc = Botan::DER_Encoder().encode(n).get_contents_unlocked();
2,048✔
455

456
      BigInt n_dec;
2,048✔
457
      Botan::BER_Decoder(enc, Botan::BER_Decoder::Limits::DER()).decode(n_dec);
4,096✔
458

459
      result.test_bn_eq("DER encoding round trips negative integers", n_dec, n);
2,048✔
460
   }
2,048✔
461

462
   return result;
1✔
463
}
1✔
464

465
Test::Result test_der_set_ordering() {
1✔
466
   Test::Result result("DER SET ordering validation");
1✔
467

468
   using Limits = Botan::BER_Decoder::Limits;
1✔
469

470
   // SET { INTEGER 1, INTEGER 2 } - canonically sorted
471
   const std::vector<uint8_t> sorted_set = {0x31, 0x06, 0x02, 0x01, 0x01, 0x02, 0x01, 0x02};
1✔
472
   // SET { INTEGER 2, INTEGER 1 } - elements out of order
473
   const std::vector<uint8_t> unsorted_set = {0x31, 0x06, 0x02, 0x01, 0x02, 0x02, 0x01, 0x01};
1✔
474

475
   auto decode_set = [](const std::vector<uint8_t>& wire, Limits limits) {
5✔
476
      Botan::BER_Decoder dec(wire, limits);
4✔
477
      Botan::BER_Decoder set = dec.start_set();
4✔
478
      while(set.more_items()) {
9✔
479
         Botan::BigInt v;
6✔
480
         set.decode(v);
6✔
481
      }
6✔
482
      set.end_cons();
3✔
483
   };
4✔
484

485
   // A sorted SET is accepted in both modes
486
   try {
1✔
487
      decode_set(sorted_set, Limits::DER());
1✔
488
      decode_set(sorted_set, Limits::BER());
1✔
489
      result.test_success("sorted SET accepted");
1✔
490
   } catch(const std::exception& e) {
×
491
      result.test_failure(Botan::fmt("sorted SET unexpectedly rejected: {}", e.what()));
×
492
   }
×
493

494
   // An unsorted SET is rejected in DER mode ...
495
   result.test_throws<Botan::Decoding_Error>("unsorted SET rejected in DER mode",
1✔
496
                                             [&]() { decode_set(unsorted_set, Limits::DER()); });
2✔
497

498
   // ... but accepted in BER mode (canonical ordering is a DER requirement)
499
   try {
1✔
500
      decode_set(unsorted_set, Limits::BER());
1✔
501
      result.test_success("unsorted SET accepted in BER mode");
1✔
502
   } catch(const std::exception& e) {
×
503
      result.test_failure(Botan::fmt("unsorted SET unexpectedly rejected in BER mode: {}", e.what()));
×
504
   }
×
505

506
   return result;
1✔
507
}
1✔
508

509
Test::Result test_der_constructed_tag_17_not_sorted() {
1✔
510
   Test::Result result("DER constructed [17] is not SET-sorted");
1✔
511

512
   // Two INTEGERs in descending order. A universal SET would lex-sort and put
513
   // 0x01 before 0x02; a non-universal constructed [17] must preserve order.
514
   const std::vector<uint8_t> first = {0x02, 0x01, 0x02};   // INTEGER 2
1✔
515
   const std::vector<uint8_t> second = {0x02, 0x01, 0x01};  // INTEGER 1
1✔
516

517
   auto encode_with = [&](auto starter) {
5✔
518
      Botan::DER_Encoder enc;
4✔
519
      starter(enc).raw_bytes(first).raw_bytes(second).end_cons();
4✔
520
      return enc.get_contents_unlocked();
8✔
521
   };
5✔
522

523
   // Reference: a universal SET of the same children gets sorted
524
   const auto set_enc = encode_with([](Botan::DER_Encoder& e) -> Botan::DER_Encoder& { return e.start_set(); });
2✔
525
   const std::vector<uint8_t> set_expected = {0x31, 0x06, 0x02, 0x01, 0x01, 0x02, 0x01, 0x02};
1✔
526
   result.test_bin_eq("universal SET is lex-sorted", set_enc, set_expected);
1✔
527

528
   // start_context_specific(17): tag byte = ContextSpecific | Constructed | 17 = 0xB1
529
   const auto ctx_enc =
1✔
530
      encode_with([](Botan::DER_Encoder& e) -> Botan::DER_Encoder& { return e.start_context_specific(17); });
2✔
531
   const std::vector<uint8_t> ctx_expected = {0xB1, 0x06, 0x02, 0x01, 0x02, 0x02, 0x01, 0x01};
1✔
532
   result.test_bin_eq("context-specific [17] preserves order", ctx_enc, ctx_expected);
1✔
533

534
   // start_explicit_context_specific(17): same tag byte 0xB1
535
   const auto explicit_ctx_enc =
1✔
536
      encode_with([](Botan::DER_Encoder& e) -> Botan::DER_Encoder& { return e.start_explicit_context_specific(17); });
2✔
537
   result.test_bin_eq("explicit context-specific [17] preserves order", explicit_ctx_enc, ctx_expected);
1✔
538

539
   // start_explicit(17): used to throw Internal_Error; must now produce [17] in order
540
   const auto explicit_enc =
1✔
541
      encode_with([](Botan::DER_Encoder& e) -> Botan::DER_Encoder& { return e.start_explicit(17); });
2✔
542
   result.test_bin_eq("start_explicit(17) preserves order", explicit_enc, ctx_expected);
1✔
543

544
   return result;
1✔
545
}
1✔
546

547
Test::Result test_der_implicit_tagging_helpers() {
1✔
548
   Test::Result result("DER implicit tagging helpers");
1✔
549

550
   const std::vector<uint8_t> first = {0x02, 0x01, 0x02};   // INTEGER 2
1✔
551
   const std::vector<uint8_t> second = {0x02, 0x01, 0x01};  // INTEGER 1
1✔
552

553
   Botan::DER_Encoder set_enc;
1✔
554
   set_enc.start_set(23).raw_bytes(first).raw_bytes(second).end_cons();
1✔
555
   const auto implicit_set = set_enc.get_contents_unlocked();
1✔
556
   result.test_bin_eq("implicit SET is still sorted", implicit_set, "B706020101020102");
1✔
557

558
   const ASN1_Test_Sequence seq(42);
1✔
559
   const auto implicit_seq = Botan::DER_Encoder().encode_implicit(seq, Botan::ASN1_Type(3)).get_contents_unlocked();
1✔
560
   result.test_bin_eq("implicit constructed object keeps constructed bit", implicit_seq, "A30302012A");
1✔
561

562
   ASN1_Test_Sequence decoded;
1✔
563
   Botan::BER_Decoder(implicit_seq, Botan::BER_Decoder::Limits::DER())
2✔
564
      .decode_implicit(decoded,
1✔
565
                       Botan::ASN1_Type(3),
566
                       Botan::ASN1_Class::ContextSpecific | Botan::ASN1_Class::Constructed,
567
                       Botan::ASN1_Type::Sequence,
568
                       Botan::ASN1_Class::Constructed)
569
      .verify_end();
1✔
570
   result.test_sz_eq("implicit constructed object decodes", decoded.value(), 42);
1✔
571

572
   const std::vector<uint8_t> one_bit = {0x80};
1✔
573
   const auto implicit_bitstring =
1✔
574
      Botan::DER_Encoder()
1✔
575
         .encode_bitstring(one_bit, 7, Botan::ASN1_Type(1), Botan::ASN1_Class::ContextSpecific)
2✔
576
         .get_contents_unlocked();
1✔
577
   result.test_bin_eq("implicit BIT STRING keeps unused bit count", implicit_bitstring, "81020780");
1✔
578

579
   const std::vector<uint8_t> bad_padding = {0x81};
1✔
580
   result.test_throws<Botan::Invalid_Argument>("BIT STRING unused bits must be zero",
1✔
581
                                               [&] { Botan::DER_Encoder().encode_bitstring(bad_padding, 7); });
2✔
582

583
   return result;
1✔
584
}
1✔
585

586
Test::Result test_asn1_bitstring_helpers() {
1✔
587
   Test::Result result("ASN.1 BIT STRING helpers");
1✔
588

589
   const std::vector<uint8_t> raw_der = {0x03, 0x03, 0x03, 0xA8, 0x00};
1✔
590
   Botan::ASN1_BitString raw_bits;
1✔
591
   Botan::BER_Decoder(raw_der, Botan::BER_Decoder::Limits::DER()).decode_bitstring(raw_bits).verify_end();
1✔
592

593
   result.test_sz_eq("raw bytes", raw_bits.bytes().size(), 2);
1✔
594
   result.test_sz_eq("raw unused bits", raw_bits.unused_bits(), 3);
1✔
595
   result.test_sz_eq("raw bit length", raw_bits.bit_length(), 13);
1✔
596
   result.test_is_true("raw bit 0", raw_bits.bit_at(0));
1✔
597
   result.test_is_false("raw bit 1", raw_bits.bit_at(1));
1✔
598
   result.test_is_true("raw bit 2", raw_bits.bit_at(2));
1✔
599

600
   const auto raw_reencoded = Botan::DER_Encoder().encode_bitstring(raw_bits).get_contents_unlocked();
1✔
601
   result.test_bin_eq("raw BIT STRING re-encodes", raw_reencoded, raw_der);
1✔
602

603
   const std::vector<uint8_t> octet_aligned_der = {0x03, 0x02, 0x00, 0xAA};
1✔
604
   std::vector<uint8_t> octets;
1✔
605
   Botan::BER_Decoder(octet_aligned_der, Botan::BER_Decoder::Limits::DER())
2✔
606
      .decode_octet_aligned_bitstring(octets)
1✔
607
      .verify_end();
1✔
608
   const std::vector<uint8_t> expected_octets = {0xAA};
1✔
609
   result.test_bin_eq("octet-aligned BIT STRING decodes as bytes", octets, expected_octets);
1✔
610

611
   const std::vector<uint8_t> non_octet_aligned_der = {0x03, 0x02, 0x01, 0x80};
1✔
612
   result.test_throws<Botan::Decoding_Error>("octet-aligned BIT STRING rejects unused bits", [&] {
1✔
613
      std::vector<uint8_t> rejected;
1✔
614
      Botan::BER_Decoder(non_octet_aligned_der, Botan::BER_Decoder::Limits::DER())
3✔
615
         .decode_octet_aligned_bitstring(rejected)
1✔
616
         .verify_end();
×
617
   });
1✔
618

619
   const uint64_t named = (uint64_t(1) << 15) | (uint64_t(1) << 7);
1✔
620
   const auto named_der = Botan::DER_Encoder().encode_named_bitstring(named, 16).get_contents_unlocked();
1✔
621
   const std::vector<uint8_t> expected_named_der = {0x03, 0x03, 0x07, 0x80, 0x80};
1✔
622
   result.test_bin_eq("named BIT STRING uses DER minimum length", named_der, expected_named_der);
1✔
623

624
   uint64_t decoded_named = 0;
1✔
625
   Botan::BER_Decoder(named_der, Botan::BER_Decoder::Limits::DER())
2✔
626
      .decode_named_bitstring(decoded_named, 16)
1✔
627
      .verify_end();
1✔
628
   result.test_u64_eq("named BIT STRING round-trips", decoded_named, named);
1✔
629

630
   const auto width9_der = Botan::DER_Encoder().encode_named_bitstring(1, 9).get_contents_unlocked();
1✔
631
   const std::vector<uint8_t> expected_width9_der = {0x03, 0x03, 0x07, 0x00, 0x80};
1✔
632
   result.test_bin_eq("named BIT STRING handles non-byte width", width9_der, expected_width9_der);
1✔
633

634
   const std::vector<uint8_t> non_minimal_named_der = {0x03, 0x02, 0x00, 0x80};
1✔
635
   result.test_throws<Botan::BER_Decoding_Error>("DER named BIT STRING rejects trailing zero bits", [&] {
1✔
636
      uint64_t rejected = 0;
1✔
637
      Botan::BER_Decoder(non_minimal_named_der, Botan::BER_Decoder::Limits::DER())
2✔
638
         .decode_named_bitstring(rejected, 16)
1✔
639
         .verify_end();
×
640
   });
×
641

642
   uint64_t non_minimal_named = 0;
1✔
643
   Botan::BER_Decoder(non_minimal_named_der, Botan::BER_Decoder::Limits::BER())
2✔
644
      .decode_named_bitstring(non_minimal_named, 16)
1✔
645
      .verify_end();
1✔
646
   result.test_u64_eq("BER named BIT STRING accepts trailing zero bits", non_minimal_named, uint64_t(1) << 15);
1✔
647

648
   return result;
1✔
649
}
1✔
650

651
Test::Result test_ber_indefinite_length_trailing_data() {
1✔
652
   Test::Result result("BER indefinite length trailing data");
1✔
653

654
   // Case 1: verify_end after consuming indef SEQUENCE
655
   try {
1✔
656
      const std::vector<uint8_t> enc = {0x30, 0x80, 0x02, 0x01, 0x42, 0x00, 0x00};
1✔
657
      Botan::BER_Decoder dec(enc);
1✔
658
      Botan::BigInt x;
1✔
659
      dec.start_sequence().decode(x).end_cons();
1✔
660
      dec.verify_end();
1✔
661
      result.test_bn_eq("verify_end decoded x", x, Botan::BigInt(0x42));
1✔
662
   } catch(Botan::Exception& e) {
1✔
663
      result.test_failure("verify_end after indef SEQUENCE", e.what());
×
664
   }
×
665

666
   // Case 2: two back-to-back indef SEQUENCES at top level
667
   try {
1✔
668
      const std::vector<uint8_t> enc = {
1✔
669
         0x30, 0x80, 0x02, 0x01, 0x42, 0x00, 0x00, 0x30, 0x80, 0x02, 0x01, 0x43, 0x00, 0x00};
1✔
670
      Botan::BER_Decoder dec(enc);
1✔
671
      Botan::BigInt x;
1✔
672
      Botan::BigInt y;
1✔
673
      dec.start_sequence().decode(x).end_cons();
1✔
674
      dec.start_sequence().decode(y).end_cons();
1✔
675
      dec.verify_end();
1✔
676
      result.test_bn_eq("back-to-back x", x, Botan::BigInt(0x42));
1✔
677
      result.test_bn_eq("back-to-back y", y, Botan::BigInt(0x43));
1✔
678
   } catch(Botan::Exception& e) {
1✔
679
      result.test_failure("two back-to-back indef SEQUENCES", e.what());
×
680
   }
×
681

682
   // Case 3: nested indef SEQUENCES
683
   try {
1✔
684
      const std::vector<uint8_t> enc = {0x30, 0x80, 0x30, 0x80, 0x02, 0x01, 0x42, 0x00, 0x00, 0x00, 0x00};
1✔
685
      Botan::BER_Decoder dec(enc);
1✔
686
      Botan::BigInt x;
1✔
687
      auto outer = dec.start_sequence();
1✔
688
      outer.start_sequence().decode(x).end_cons();
1✔
689
      outer.end_cons();
1✔
690
      dec.verify_end();
1✔
691
      result.test_bn_eq("nested x", x, Botan::BigInt(0x42));
1✔
692
   } catch(Botan::Exception& e) {
1✔
693
      result.test_failure("nested indef SEQUENCE", e.what());
×
694
   }
×
695

696
   // Case 4: while(more_items()) loop over an indef SEQUENCE
697
   try {
1✔
698
      const std::vector<uint8_t> enc = {0x30, 0x80, 0x02, 0x01, 0x42, 0x02, 0x01, 0x43, 0x00, 0x00};
1✔
699
      Botan::BER_Decoder dec(enc);
1✔
700
      auto seq = dec.start_sequence();
1✔
701
      std::vector<Botan::BigInt> xs;
1✔
702
      while(seq.more_items()) {
3✔
703
         Botan::BigInt x;
2✔
704
         seq.decode(x);
2✔
705
         xs.push_back(x);
2✔
706
      }
2✔
707
      seq.end_cons();
1✔
708
      dec.verify_end();
1✔
709
      result.test_sz_eq("more_items count", xs.size(), 2);
1✔
710
      if(xs.size() == 2) {
1✔
711
         result.test_bn_eq("more_items xs[0]", xs[0], Botan::BigInt(0x42));
1✔
712
         result.test_bn_eq("more_items xs[1]", xs[1], Botan::BigInt(0x43));
1✔
713
      }
714
   } catch(Botan::Exception& e) {
1✔
715
      result.test_failure("more_items loop over indef SEQUENCE", e.what());
×
716
   }
×
717

718
   return result;
1✔
719
}
×
720

721
Test::Result test_ber_find_eoc() {
1✔
722
   Test::Result result("BER indefinite length EOC matching");
1✔
723

724
   const size_t num_siblings = 4096;
1✔
725

726
   std::vector<uint8_t> ber;
1✔
727
   ber.push_back(0x30);  // outer SEQUENCE | CONSTRUCTED
1✔
728
   ber.push_back(0x80);  // indefinite length
1✔
729
   for(size_t i = 0; i != num_siblings; ++i) {
4,097✔
730
      ber.push_back(0x30);  // inner SEQUENCE | CONSTRUCTED
4,096✔
731
      ber.push_back(0x80);  // indefinite length
4,096✔
732
      ber.push_back(0x00);  // EOC tag
4,096✔
733
      ber.push_back(0x00);  // EOC length
4,096✔
734
   }
735
   ber.push_back(0x00);  // outer EOC tag
1✔
736
   ber.push_back(0x00);  // outer EOC length
1✔
737

738
   try {
1✔
739
      Botan::BER_Decoder dec(ber);
1✔
740
      const Botan::BER_Object obj = dec.get_next_object();
1✔
741

742
      result.test_sz_eq("object body includes children", obj.length(), num_siblings * 4);
1✔
743
   } catch(Botan::Exception& e) {
1✔
744
      result.test_failure("decode failed", e.what());
×
745
   }
×
746

747
   return result;
1✔
748
}
1✔
749

750
Test::Result test_asn1_string_zero_length_roundtrip() {
1✔
751
   Test::Result result("ASN.1 String zero-length round-trip");
1✔
752

753
   auto roundtrip = [&](const char* what, const std::vector<uint8_t>& wire) {
4✔
754
      try {
3✔
755
         Botan::DataSource_Memory input(wire.data(), wire.size());
3✔
756
         Botan::BER_Decoder dec(input);
3✔
757
         Botan::ASN1_String str;
3✔
758
         str.decode_from(dec);
3✔
759

760
         Botan::DER_Encoder enc;
3✔
761
         str.encode_into(enc);
3✔
762
         const auto out = enc.get_contents();
3✔
763
         result.test_bin_eq(what, std::span{out}, std::span{wire});
3✔
764
      } catch(const std::exception& ex) {
9✔
765
         result.test_failure(Botan::fmt("{}: unexpected throw: {}", what, ex.what()));
×
766
      }
×
767
   };
3✔
768

769
   roundtrip("BmpString 1E 00", {0x1E, 0x00});
1✔
770
   roundtrip("UniversalString 1C 00", {0x1C, 0x00});
1✔
771
   roundtrip("TeletexString 14 00", {0x14, 0x00});
1✔
772

773
   return result;
1✔
774
}
×
775

776
Test::Result test_pss_params_rejects_trailing_data_in_mgf1_params() {
1✔
777
   Test::Result result("PSS-Params rejects trailing data in MGF1 parameters");
1✔
778

779
   const Botan::AlgorithmIdentifier sha256_alg_id("SHA-256", Botan::AlgorithmIdentifier::USE_NULL_PARAM);
1✔
780
   const auto sha256_der = sha256_alg_id.BER_encode();
1✔
781

782
   auto encode_pss_params = [&](const std::vector<uint8_t>& mgf_params) {
3✔
783
      const Botan::AlgorithmIdentifier mgf("MGF1", mgf_params);
2✔
784
      Botan::DER_Encoder enc;
2✔
785
      enc.start_sequence()
2✔
786
         .start_context_specific(0)
2✔
787
         .encode(sha256_alg_id)
2✔
788
         .end_cons()
2✔
789
         .start_context_specific(1)
2✔
790
         .encode(mgf)
2✔
791
         .end_cons()
2✔
792
         .start_context_specific(2)
2✔
793
         .encode(static_cast<size_t>(32))
2✔
794
         .end_cons()
2✔
795
         .end_cons();
2✔
796
      return enc.get_contents();
2✔
797
   };
4✔
798

799
   try {
1✔
800
      const auto clean_der = encode_pss_params(sha256_der);
1✔
801
      const Botan::PSS_Params clean(clean_der);
1✔
802
      result.test_success("control: clean PSS-Params decodes");
1✔
803
   } catch(const std::exception& e) {
2✔
804
      result.test_failure(Botan::fmt("clean PSS-Params unexpected throw: {}", e.what()));
×
805
   }
×
806

807
   std::vector<uint8_t> mgf_params_with_junk = sha256_der;
1✔
808
   const std::vector<uint8_t> trailing_junk{0x02, 0x01, 0x00};
1✔
809
   mgf_params_with_junk.insert(mgf_params_with_junk.end(), trailing_junk.begin(), trailing_junk.end());
1✔
810
   const auto bad_der = encode_pss_params(mgf_params_with_junk);
1✔
811

812
   result.test_throws<Botan::Decoding_Error>("PSS-Params rejects trailing data in MGF1 parameters",
1✔
813
                                             [&]() { const Botan::PSS_Params bad(bad_der); });
2✔
814

815
   return result;
1✔
816
}
2✔
817

818
Test::Result test_alg_id_parameter_validation() {
1✔
819
   Test::Result result("AlgorithmIdentifier parameter validation");
1✔
820

821
   auto decode_alg_id = [](std::string_view hex) {
10✔
822
      const auto wire = Botan::hex_decode(hex);
9✔
823
      Botan::AlgorithmIdentifier alg_id;
9✔
824
      Botan::BER_Decoder(wire).decode(alg_id).verify_end();
13✔
825
   };
9✔
826

827
   auto verify_params_accepted = [&](const std::string& label, std::string_view hex) {
6✔
828
      try {
5✔
829
         decode_alg_id(hex);
5✔
830
         result.test_success(Botan::fmt("{} parameters accepted", label));
10✔
831
      } catch(const std::exception& e) {
×
832
         result.test_failure(Botan::fmt("{} parameters unexpectedly rejected: {}", label, e.what()));
×
833
      }
×
834
   };
5✔
835

836
   auto verify_params_rejected = [&](const std::string& label, std::string_view hex) {
5✔
837
      result.test_throws<Botan::Decoding_Error>(Botan::fmt("{} parameters rejected", label),
8✔
838
                                                [&]() { decode_alg_id(hex); });
8✔
839
   };
4✔
840

841
   // The wire is SEQUENCE { OID 2.5.4.3, <parameters> } in each case
842

843
   verify_params_accepted("absent", "30050603550403");
1✔
844
   verify_params_accepted("NULL", "300706035504030500");
1✔
845
   verify_params_accepted("SEQUENCE", "300706035504033000");
1✔
846
   verify_params_accepted("OID", "300A06035504030603550403");
1✔
847
   verify_params_accepted("OCTET STRING", "300906035504030402AABB");
1✔
848

849
   verify_params_rejected("two values (NULL, NULL)", "3009060355040305000500");
1✔
850
   verify_params_rejected("trailing data after NULL", "300A06035504030500020100");
1✔
851
   verify_params_rejected("truncated SEQUENCE", "300706035504033005");
1✔
852
   verify_params_rejected("single INTEGER", "30080603550403020100");
1✔
853

854
   return result;
1✔
855
}
×
856

857
Test::Result test_der_default_value_encoding() {
1✔
858
   Test::Result result("DER DEFAULT value rejection");
1✔
859

860
   using Limits = Botan::BER_Decoder::Limits;
1✔
861

862
   // SEQUENCE { version INTEGER DEFAULT 0 } in three forms
863
   const std::vector<uint8_t> present_default = {0x30, 0x03, 0x02, 0x01, 0x00};     // present, == default
1✔
864
   const std::vector<uint8_t> omitted = {0x30, 0x00};                               // absent
1✔
865
   const std::vector<uint8_t> present_nondefault = {0x30, 0x03, 0x02, 0x01, 0x05};  // present, != default
1✔
866

867
   auto decode_version = [](const std::vector<uint8_t>& wire, Limits limits) {
7✔
868
      Botan::BER_Decoder dec(wire, limits);
6✔
869
      size_t version = 99;
6✔
870
      dec.start_sequence()
6✔
871
         .decode_default(version, Botan::ASN1_Type::Integer, Botan::ASN1_Class::Universal, size_t(0))
11✔
872
         .end_cons();
5✔
873
      return version;
5✔
874
   };
6✔
875

876
   // By default an explicitly-encoded default value is accepted
877
   try {
1✔
878
      result.test_sz_eq("present default accepted (lax)", decode_version(present_default, Limits::DER()), 0);
1✔
879
      result.test_sz_eq("omitted uses default (lax)", decode_version(omitted, Limits::DER()), 0);
1✔
880
      result.test_sz_eq("present non-default decoded", decode_version(present_nondefault, Limits::DER()), 5);
1✔
881
   } catch(const std::exception& e) {
×
882
      result.test_failure(Botan::fmt("unexpected rejection: {}", e.what()));
×
883
   }
×
884

885
   // With the flag set, a present default-valued component is rejected ...
886
   result.test_throws<Botan::Decoding_Error>("present default rejected (strict)", [&]() {
1✔
887
      decode_version(present_default, Limits::DER().with_default_value_encoding_rejected());
1✔
888
   });
×
889

890
   // ... but omitted and non-default forms are still accepted
891
   try {
1✔
892
      const auto strict = Limits::DER().with_default_value_encoding_rejected();
1✔
893
      result.test_sz_eq("omitted uses default (strict)", decode_version(omitted, strict), 0);
1✔
894
      result.test_sz_eq("present non-default accepted (strict)", decode_version(present_nondefault, strict), 5);
1✔
895
   } catch(const std::exception& e) {
×
896
      result.test_failure(Botan::fmt("unexpected strict rejection: {}", e.what()));
×
897
   }
×
898

899
   return result;
1✔
900
}
1✔
901

902
class ASN1_Tests final : public Test {
1✔
903
   public:
904
      std::vector<Test::Result> run() override {
1✔
905
         std::vector<Test::Result> results;
1✔
906

907
         results.push_back(test_ber_stack_recursion());
2✔
908
         results.push_back(test_ber_eoc_decoding_limits());
2✔
909
         results.push_back(test_ber_standalone_eoc_limits());
2✔
910
         results.push_back(test_ber_max_object_size());
2✔
911
         results.push_back(test_ber_constructed_string_rejected());
2✔
912
         results.push_back(test_ber_indefinite_length_trailing_data());
2✔
913
         results.push_back(test_ber_find_eoc());
2✔
914
         results.push_back(test_asn1_utf8_ascii_parsing());
2✔
915
         results.push_back(test_asn1_utf8_parsing());
2✔
916
         results.push_back(test_asn1_ucs2_parsing());
2✔
917
         results.push_back(test_asn1_ucs4_parsing());
2✔
918
         results.push_back(test_asn1_ucs_invalid_codepoint_rejection());
2✔
919
         results.push_back(test_asn1_ascii_encoding());
2✔
920
         results.push_back(test_asn1_utf8_encoding());
2✔
921
         results.push_back(test_asn1_tag_underlying_type());
2✔
922
         results.push_back(test_asn1_high_tag_number());
2✔
923
         results.push_back(test_asn1_negative_int_encoding());
2✔
924
         results.push_back(test_der_set_ordering());
2✔
925
         results.push_back(test_der_constructed_tag_17_not_sorted());
2✔
926
         results.push_back(test_der_implicit_tagging_helpers());
2✔
927
         results.push_back(test_asn1_bitstring_helpers());
2✔
928
         results.push_back(test_asn1_string_zero_length_roundtrip());
2✔
929
         results.push_back(test_pss_params_rejects_trailing_data_in_mgf1_params());
2✔
930
         results.push_back(test_alg_id_parameter_validation());
2✔
931
         results.push_back(test_der_default_value_encoding());
2✔
932

933
         return results;
1✔
934
      }
×
935
};
936

937
BOTAN_REGISTER_TEST("asn1", "asn1_encoding", ASN1_Tests);
938

939
class ASN1_Time_Parsing_Tests final : public Text_Based_Test {
×
940
   public:
941
      ASN1_Time_Parsing_Tests() : Text_Based_Test("asn1_time.vec", "Tspec") {}
2✔
942

943
      Test::Result run_one_test(const std::string& tag_str, const VarMap& vars) override {
26✔
944
         Test::Result result("ASN.1 date parsing");
26✔
945

946
         const std::string tspec = vars.get_req_str("Tspec");
26✔
947

948
         if(tag_str != "UTC" && tag_str != "UTC.invalid" && tag_str != "Generalized" &&
26✔
949
            tag_str != "Generalized.invalid") {
13✔
950
            throw Test_Error("Invalid tag value in ASN1 date parsing test");
×
951
         }
952

953
         const bool out_of_range = [&]() -> bool {
78✔
954
            if(tspec.size() == 15) {
26✔
955
               const size_t year = Botan::to_u32bit(std::string_view(tspec).substr(0, 4));
24✔
956
               if(year >= 2262) {
24✔
957
                  return true;
958
               }
959
               if(year >= 2038 && sizeof(time_t) == 4) {
960
                  return true;
961
               }
962
            }
963

964
            return false;
965
         }();
26✔
966

967
         const Botan::ASN1_Type tag = (tag_str == "UTC" || tag_str == "UTC.invalid")
25✔
968
                                         ? Botan::ASN1_Type::UtcTime
26✔
969
                                         : Botan::ASN1_Type::GeneralizedTime;
26✔
970

971
         const bool valid = tag_str.find(".invalid") == std::string::npos;
26✔
972

973
         if(valid) {
26✔
974
            const Botan::ASN1_Time time(tspec, tag);
12✔
975
            result.test_success("Accepted valid time");
12✔
976

977
            try {
12✔
978
               const auto std_timepoint = time.to_std_timepoint();
12✔
979
               result.test_success("Was able to convert time to std timepoint");
10✔
980

981
               const auto from_std_timepoint = Botan::ASN1_Time::from_time_point(std_timepoint);
10✔
982
               result.test_is_true("ASN1_Time from std timepoint matches input", from_std_timepoint == time);
10✔
983
            } catch(std::exception& e) {
12✔
984
               if(out_of_range) {
2✔
985
                  result.test_str_contains("Exception message", e.what(), "time is outside the representable range");
2✔
986
               } else {
987
                  result.test_failure("Was not able to convert time to std timepoint", e.what());
×
988
               }
989
            }
2✔
990
         } else {
12✔
991
            result.test_throws("Invalid time rejected", [=]() { const Botan::ASN1_Time time(tspec, tag); });
70✔
992
         }
993

994
         return result;
26✔
995
      }
26✔
996
};
997

998
BOTAN_REGISTER_TEST("asn1", "asn1_time", ASN1_Time_Parsing_Tests);
999

1000
class ASN1_String_Validation_Tests final : public Text_Based_Test {
×
1001
   public:
1002
      ASN1_String_Validation_Tests() :
1✔
1003
            Text_Based_Test("asn1_string_validation.vec",
1004
                            "Input,ValidNumeric,ValidPrintable,ValidIa5,ValidVisible,ValidUtf8") {}
2✔
1005

1006
      Test::Result run_one_test(const std::string& /*header*/, const VarMap& vars) override {
7✔
1007
         Test::Result result("ASN.1 string validation");
7✔
1008

1009
         const auto input = vars.get_req_str("Input");
7✔
1010
         const bool valid_numeric = vars.get_req_bool("ValidNumeric");
7✔
1011
         const bool valid_printable = vars.get_req_bool("ValidPrintable");
7✔
1012
         const bool valid_ia5 = vars.get_req_bool("ValidIa5");
7✔
1013
         const bool valid_visible = vars.get_req_bool("ValidVisible");
7✔
1014
         const bool valid_utf8 = vars.get_req_bool("ValidUtf8");
7✔
1015

1016
         test_string_type(result, input, "NumericString", Botan::ASN1_Type::NumericString, valid_numeric);
7✔
1017
         test_string_type(result, input, "PrintableString", Botan::ASN1_Type::PrintableString, valid_printable);
7✔
1018
         test_string_type(result, input, "Ia5String", Botan::ASN1_Type::Ia5String, valid_ia5);
7✔
1019
         test_string_type(result, input, "VisibleString", Botan::ASN1_Type::VisibleString, valid_visible);
7✔
1020
         test_string_type(result, input, "Utf8String", Botan::ASN1_Type::Utf8String, valid_utf8);
7✔
1021

1022
         if(valid_utf8) {
7✔
1023
            try {
7✔
1024
               const Botan::ASN1_String str(input);
7✔
1025
               const auto expected_tag =
14✔
1026
                  valid_printable ? Botan::ASN1_Type::PrintableString : Botan::ASN1_Type::Utf8String;
7✔
1027
               result.test_u32_eq("String tagging categorization",
7✔
1028
                                  static_cast<uint32_t>(str.tagging()),
7✔
1029
                                  static_cast<uint32_t>(expected_tag));
1030
            } catch(const std::exception& ex) {
7✔
1031
               result.test_failure(Botan::fmt("default constructor unexpectedly rejected '{}': {}", input, ex.what()));
×
1032
            }
×
1033
         }
1034

1035
         return result;
7✔
1036
      }
7✔
1037

1038
   private:
1039
      void test_string_type(Test::Result& result,
35✔
1040
                            std::string_view input,
1041
                            std::string_view type,
1042
                            Botan::ASN1_Type tag,
1043
                            bool expected_valid) {
1044
         if(expected_valid) {
35✔
1045
            try {
24✔
1046
               const Botan::ASN1_String str(input, tag);
24✔
1047
               result.test_str_eq(Botan::fmt("{} constructor value", type), str.value(), input);
24✔
1048

1049
               const auto enc = raw_encode_string(input, tag);
24✔
1050
               Botan::BER_Decoder dec(enc);
24✔
1051
               Botan::ASN1_String decoded;
24✔
1052
               decoded.decode_from(dec);
24✔
1053
               result.test_str_eq(Botan::fmt("{} decode value", type), decoded.value(), input);
48✔
1054
            } catch(const std::exception& e) {
48✔
1055
               result.test_failure(Botan::fmt("{} unexpectedly rejected '{}': {}", type, input, e.what()));
×
1056
            }
×
1057
         } else {
1058
            result.test_throws(Botan::fmt("{} constructor rejects", type),
22✔
1059
                               [&]() { const Botan::ASN1_String str(input, tag); });
22✔
1060

1061
            result.test_throws(Botan::fmt("{} decode rejects", type), [&]() {
22✔
1062
               const auto enc = raw_encode_string(input, tag);
11✔
1063
               Botan::BER_Decoder dec(enc);
11✔
1064
               Botan::ASN1_String decoded;
11✔
1065
               decoded.decode_from(dec);
11✔
1066
            });
22✔
1067
         }
1068
      }
35✔
1069

1070
      static std::vector<uint8_t> raw_encode_string(std::string_view input, Botan::ASN1_Type tag) {
35✔
1071
         std::vector<uint8_t> encoding;
35✔
1072
         Botan::DER_Encoder der(encoding);
35✔
1073
         der.add_object(tag, Botan::ASN1_Class::Universal, input);
35✔
1074
         return encoding;
35✔
1075
      }
35✔
1076
};
1077

1078
BOTAN_REGISTER_TEST("asn1", "asn1_string_validation", ASN1_String_Validation_Tests);
1079

1080
class ASN1_Printer_Tests final : public Test {
1✔
1081
   public:
1082
      std::vector<Test::Result> run() override {
1✔
1083
         Test::Result result("ASN1_Pretty_Printer");
1✔
1084

1085
         const Botan::ASN1_Pretty_Printer printer;
1✔
1086

1087
         const size_t num_tests = 8;
1✔
1088

1089
         for(size_t i = 1; i <= num_tests; ++i) {
9✔
1090
            const std::string i_str = std::to_string(i);
8✔
1091
            const std::vector<uint8_t> input_data = Test::read_binary_data_file("asn1_print/input" + i_str + ".der");
24✔
1092
            const std::string expected_output = Test::read_data_file("asn1_print/output" + i_str + ".txt");
24✔
1093

1094
            try {
8✔
1095
               const std::string output = printer.print(input_data);
8✔
1096
               result.test_str_eq("Test " + i_str, output, expected_output);
16✔
1097
            } catch(Botan::Exception& e) {
8✔
1098
               result.test_failure(Botan::fmt("Printing test {} failed with an exception: '{}'", i, e.what()));
×
1099
            }
×
1100
         }
8✔
1101

1102
         return {result};
2✔
1103
      }
10✔
1104
};
1105

1106
BOTAN_REGISTER_TEST("asn1", "asn1_printer", ASN1_Printer_Tests);
1107

1108
class ASN1_Decoding_Tests final : public Text_Based_Test {
×
1109
   public:
1110
      ASN1_Decoding_Tests() : Text_Based_Test("asn1_decoding.vec", "Input,ResultBER", "ResultDER") {}
2✔
1111

1112
      Test::Result run_one_test(const std::string& /*header*/, const VarMap& vars) override {
58✔
1113
         const auto input = vars.get_req_bin("Input");
58✔
1114
         const std::string expected_ber = vars.get_req_str("ResultBER");
58✔
1115
         const std::string expected_der = vars.get_opt_str("ResultDER", expected_ber);
58✔
1116

1117
         Test::Result result("ASN1 decoding");
58✔
1118

1119
         decoding_test(result, input, expected_ber, false);
58✔
1120
         decoding_test(result, input, expected_der, true);
58✔
1121

1122
         return result;
116✔
1123
      }
58✔
1124

1125
   private:
1126
      static void decoding_test(Test::Result& result,
116✔
1127
                                std::span<const uint8_t> input,
1128
                                std::string_view expected,
1129
                                bool require_der) {
1130
         const Botan::ASN1_Pretty_Printer printer(4096, 2048, true, 0, 60, 64, require_der);
116✔
1131
         const std::string mode = require_der ? "DER" : "BER";
174✔
1132
         std::ostringstream sink;
116✔
1133

1134
         try {
116✔
1135
            printer.print_to_stream(sink, input.data(), input.size());
116✔
1136

1137
            if(expected == "OK") {
51✔
1138
               result.test_success();
51✔
1139
            } else {
1140
               result.test_failure(Botan::fmt("Accepted invalid {} input, expected error {}", mode, expected));
×
1141
            }
1142
         } catch(const std::exception& e) {
65✔
1143
            if(expected == "OK") {
65✔
1144
               result.test_failure(Botan::fmt("Rejected valid {} input with {}", mode, e.what()));
×
1145
            } else {
1146
               // BER_Decoding_Error prepends "BER: " to the message
1147
               std::string msg = e.what();
65✔
1148
               if(msg.starts_with("BER: ")) {
65✔
1149
                  msg = msg.substr(5);
45✔
1150
               }
1151
               result.test_str_eq("error message", msg, expected);
65✔
1152
            }
65✔
1153
         }
65✔
1154
      }
161✔
1155
};
1156

1157
BOTAN_REGISTER_TEST("asn1", "asn1_decoding", ASN1_Decoding_Tests);
1158

1159
#endif
1160

1161
}  // namespace
1162

1163
}  // namespace Botan_Tests
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc