1// Copyright 2017 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5package cryptobyte
6
7import (
8	encoding_asn1 "encoding/asn1"
9	"fmt"
10	"math/big"
11	"reflect"
12	"time"
13
14	"golang.org/x/crypto/cryptobyte/asn1"
15)
16
17// This file contains ASN.1-related methods for String and Builder.
18
19// Builder
20
21// AddASN1Int64 appends a DER-encoded ASN.1 INTEGER.
22func (b *Builder) AddASN1Int64(v int64) {
23	b.addASN1Signed(asn1.INTEGER, v)
24}
25
26// AddASN1Int64WithTag appends a DER-encoded ASN.1 INTEGER with the
27// given tag.
28func (b *Builder) AddASN1Int64WithTag(v int64, tag asn1.Tag) {
29	b.addASN1Signed(tag, v)
30}
31
32// AddASN1Enum appends a DER-encoded ASN.1 ENUMERATION.
33func (b *Builder) AddASN1Enum(v int64) {
34	b.addASN1Signed(asn1.ENUM, v)
35}
36
37func (b *Builder) addASN1Signed(tag asn1.Tag, v int64) {
38	b.AddASN1(tag, func(c *Builder) {
39		length := 1
40		for i := v; i >= 0x80 || i < -0x80; i >>= 8 {
41			length++
42		}
43
44		for ; length > 0; length-- {
45			i := v >> uint((length-1)*8) & 0xff
46			c.AddUint8(uint8(i))
47		}
48	})
49}
50
51// AddASN1Uint64 appends a DER-encoded ASN.1 INTEGER.
52func (b *Builder) AddASN1Uint64(v uint64) {
53	b.AddASN1(asn1.INTEGER, func(c *Builder) {
54		length := 1
55		for i := v; i >= 0x80; i >>= 8 {
56			length++
57		}
58
59		for ; length > 0; length-- {
60			i := v >> uint((length-1)*8) & 0xff
61			c.AddUint8(uint8(i))
62		}
63	})
64}
65
66// AddASN1BigInt appends a DER-encoded ASN.1 INTEGER.
67func (b *Builder) AddASN1BigInt(n *big.Int) {
68	if b.err != nil {
69		return
70	}
71
72	b.AddASN1(asn1.INTEGER, func(c *Builder) {
73		if n.Sign() < 0 {
74			// A negative number has to be converted to two's-complement form. So we
75			// invert and subtract 1. If the most-significant-bit isn't set then
76			// we'll need to pad the beginning with 0xff in order to keep the number
77			// negative.
78			nMinus1 := new(big.Int).Neg(n)
79			nMinus1.Sub(nMinus1, bigOne)
80			bytes := nMinus1.Bytes()
81			for i := range bytes {
82				bytes[i] ^= 0xff
83			}
84			if len(bytes) == 0 || bytes[0]&0x80 == 0 {
85				c.add(0xff)
86			}
87			c.add(bytes...)
88		} else if n.Sign() == 0 {
89			c.add(0)
90		} else {
91			bytes := n.Bytes()
92			if bytes[0]&0x80 != 0 {
93				c.add(0)
94			}
95			c.add(bytes...)
96		}
97	})
98}
99
100// AddASN1OctetString appends a DER-encoded ASN.1 OCTET STRING.
101func (b *Builder) AddASN1OctetString(bytes []byte) {
102	b.AddASN1(asn1.OCTET_STRING, func(c *Builder) {
103		c.AddBytes(bytes)
104	})
105}
106
107const generalizedTimeFormatStr = "20060102150405Z0700"
108
109// AddASN1GeneralizedTime appends a DER-encoded ASN.1 GENERALIZEDTIME.
110func (b *Builder) AddASN1GeneralizedTime(t time.Time) {
111	if t.Year() < 0 || t.Year() > 9999 {
112		b.err = fmt.Errorf("cryptobyte: cannot represent %v as a GeneralizedTime", t)
113		return
114	}
115	b.AddASN1(asn1.GeneralizedTime, func(c *Builder) {
116		c.AddBytes([]byte(t.Format(generalizedTimeFormatStr)))
117	})
118}
119
120// AddASN1UTCTime appends a DER-encoded ASN.1 UTCTime.
121func (b *Builder) AddASN1UTCTime(t time.Time) {
122	b.AddASN1(asn1.UTCTime, func(c *Builder) {
123		// As utilized by the X.509 profile, UTCTime can only
124		// represent the years 1950 through 2049.
125		if t.Year() < 1950 || t.Year() >= 2050 {
126			b.err = fmt.Errorf("cryptobyte: cannot represent %v as a UTCTime", t)
127			return
128		}
129		c.AddBytes([]byte(t.Format(defaultUTCTimeFormatStr)))
130	})
131}
132
133// AddASN1BitString appends a DER-encoded ASN.1 BIT STRING. This does not
134// support BIT STRINGs that are not a whole number of bytes.
135func (b *Builder) AddASN1BitString(data []byte) {
136	b.AddASN1(asn1.BIT_STRING, func(b *Builder) {
137		b.AddUint8(0)
138		b.AddBytes(data)
139	})
140}
141
142func (b *Builder) addBase128Int(n int64) {
143	var length int
144	if n == 0 {
145		length = 1
146	} else {
147		for i := n; i > 0; i >>= 7 {
148			length++
149		}
150	}
151
152	for i := length - 1; i >= 0; i-- {
153		o := byte(n >> uint(i*7))
154		o &= 0x7f
155		if i != 0 {
156			o |= 0x80
157		}
158
159		b.add(o)
160	}
161}
162
163func isValidOID(oid encoding_asn1.ObjectIdentifier) bool {
164	if len(oid) < 2 {
165		return false
166	}
167
168	if oid[0] > 2 || (oid[0] <= 1 && oid[1] >= 40) {
169		return false
170	}
171
172	for _, v := range oid {
173		if v < 0 {
174			return false
175		}
176	}
177
178	return true
179}
180
181func (b *Builder) AddASN1ObjectIdentifier(oid encoding_asn1.ObjectIdentifier) {
182	b.AddASN1(asn1.OBJECT_IDENTIFIER, func(b *Builder) {
183		if !isValidOID(oid) {
184			b.err = fmt.Errorf("cryptobyte: invalid OID: %v", oid)
185			return
186		}
187
188		b.addBase128Int(int64(oid[0])*40 + int64(oid[1]))
189		for _, v := range oid[2:] {
190			b.addBase128Int(int64(v))
191		}
192	})
193}
194
195func (b *Builder) AddASN1Boolean(v bool) {
196	b.AddASN1(asn1.BOOLEAN, func(b *Builder) {
197		if v {
198			b.AddUint8(0xff)
199		} else {
200			b.AddUint8(0)
201		}
202	})
203}
204
205func (b *Builder) AddASN1NULL() {
206	b.add(uint8(asn1.NULL), 0)
207}
208
209// MarshalASN1 calls encoding_asn1.Marshal on its input and appends the result if
210// successful or records an error if one occurred.
211func (b *Builder) MarshalASN1(v interface{}) {
212	// NOTE(martinkr): This is somewhat of a hack to allow propagation of
213	// encoding_asn1.Marshal errors into Builder.err. N.B. if you call MarshalASN1 with a
214	// value embedded into a struct, its tag information is lost.
215	if b.err != nil {
216		return
217	}
218	bytes, err := encoding_asn1.Marshal(v)
219	if err != nil {
220		b.err = err
221		return
222	}
223	b.AddBytes(bytes)
224}
225
226// AddASN1 appends an ASN.1 object. The object is prefixed with the given tag.
227// Tags greater than 30 are not supported and result in an error (i.e.
228// low-tag-number form only). The child builder passed to the
229// BuilderContinuation can be used to build the content of the ASN.1 object.
230func (b *Builder) AddASN1(tag asn1.Tag, f BuilderContinuation) {
231	if b.err != nil {
232		return
233	}
234	// Identifiers with the low five bits set indicate high-tag-number format
235	// (two or more octets), which we don't support.
236	if tag&0x1f == 0x1f {
237		b.err = fmt.Errorf("cryptobyte: high-tag number identifier octects not supported: 0x%x", tag)
238		return
239	}
240	b.AddUint8(uint8(tag))
241	b.addLengthPrefixed(1, true, f)
242}
243
244// String
245
246// ReadASN1Boolean decodes an ASN.1 BOOLEAN and converts it to a boolean
247// representation into out and advances. It reports whether the read
248// was successful.
249func (s *String) ReadASN1Boolean(out *bool) bool {
250	var bytes String
251	if !s.ReadASN1(&bytes, asn1.BOOLEAN) || len(bytes) != 1 {
252		return false
253	}
254
255	switch bytes[0] {
256	case 0:
257		*out = false
258	case 0xff:
259		*out = true
260	default:
261		return false
262	}
263
264	return true
265}
266
267var bigIntType = reflect.TypeOf((*big.Int)(nil)).Elem()
268
269// ReadASN1Integer decodes an ASN.1 INTEGER into out and advances. If out does
270// not point to an integer or to a big.Int, it panics. It reports whether the
271// read was successful.
272func (s *String) ReadASN1Integer(out interface{}) bool {
273	if reflect.TypeOf(out).Kind() != reflect.Ptr {
274		panic("out is not a pointer")
275	}
276	switch reflect.ValueOf(out).Elem().Kind() {
277	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
278		var i int64
279		if !s.readASN1Int64(&i) || reflect.ValueOf(out).Elem().OverflowInt(i) {
280			return false
281		}
282		reflect.ValueOf(out).Elem().SetInt(i)
283		return true
284	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
285		var u uint64
286		if !s.readASN1Uint64(&u) || reflect.ValueOf(out).Elem().OverflowUint(u) {
287			return false
288		}
289		reflect.ValueOf(out).Elem().SetUint(u)
290		return true
291	case reflect.Struct:
292		if reflect.TypeOf(out).Elem() == bigIntType {
293			return s.readASN1BigInt(out.(*big.Int))
294		}
295	}
296	panic("out does not point to an integer type")
297}
298
299func checkASN1Integer(bytes []byte) bool {
300	if len(bytes) == 0 {
301		// An INTEGER is encoded with at least one octet.
302		return false
303	}
304	if len(bytes) == 1 {
305		return true
306	}
307	if bytes[0] == 0 && bytes[1]&0x80 == 0 || bytes[0] == 0xff && bytes[1]&0x80 == 0x80 {
308		// Value is not minimally encoded.
309		return false
310	}
311	return true
312}
313
314var bigOne = big.NewInt(1)
315
316func (s *String) readASN1BigInt(out *big.Int) bool {
317	var bytes String
318	if !s.ReadASN1(&bytes, asn1.INTEGER) || !checkASN1Integer(bytes) {
319		return false
320	}
321	if bytes[0]&0x80 == 0x80 {
322		// Negative number.
323		neg := make([]byte, len(bytes))
324		for i, b := range bytes {
325			neg[i] = ^b
326		}
327		out.SetBytes(neg)
328		out.Add(out, bigOne)
329		out.Neg(out)
330	} else {
331		out.SetBytes(bytes)
332	}
333	return true
334}
335
336func (s *String) readASN1Int64(out *int64) bool {
337	var bytes String
338	if !s.ReadASN1(&bytes, asn1.INTEGER) || !checkASN1Integer(bytes) || !asn1Signed(out, bytes) {
339		return false
340	}
341	return true
342}
343
344func asn1Signed(out *int64, n []byte) bool {
345	length := len(n)
346	if length > 8 {
347		return false
348	}
349	for i := 0; i < length; i++ {
350		*out <<= 8
351		*out |= int64(n[i])
352	}
353	// Shift up and down in order to sign extend the result.
354	*out <<= 64 - uint8(length)*8
355	*out >>= 64 - uint8(length)*8
356	return true
357}
358
359func (s *String) readASN1Uint64(out *uint64) bool {
360	var bytes String
361	if !s.ReadASN1(&bytes, asn1.INTEGER) || !checkASN1Integer(bytes) || !asn1Unsigned(out, bytes) {
362		return false
363	}
364	return true
365}
366
367func asn1Unsigned(out *uint64, n []byte) bool {
368	length := len(n)
369	if length > 9 || length == 9 && n[0] != 0 {
370		// Too large for uint64.
371		return false
372	}
373	if n[0]&0x80 != 0 {
374		// Negative number.
375		return false
376	}
377	for i := 0; i < length; i++ {
378		*out <<= 8
379		*out |= uint64(n[i])
380	}
381	return true
382}
383
384// ReadASN1Int64WithTag decodes an ASN.1 INTEGER with the given tag into out
385// and advances. It reports whether the read was successful and resulted in a
386// value that can be represented in an int64.
387func (s *String) ReadASN1Int64WithTag(out *int64, tag asn1.Tag) bool {
388	var bytes String
389	return s.ReadASN1(&bytes, tag) && checkASN1Integer(bytes) && asn1Signed(out, bytes)
390}
391
392// ReadASN1Enum decodes an ASN.1 ENUMERATION into out and advances. It reports
393// whether the read was successful.
394func (s *String) ReadASN1Enum(out *int) bool {
395	var bytes String
396	var i int64
397	if !s.ReadASN1(&bytes, asn1.ENUM) || !checkASN1Integer(bytes) || !asn1Signed(&i, bytes) {
398		return false
399	}
400	if int64(int(i)) != i {
401		return false
402	}
403	*out = int(i)
404	return true
405}
406
407func (s *String) readBase128Int(out *int) bool {
408	ret := 0
409	for i := 0; len(*s) > 0; i++ {
410		if i == 4 {
411			return false
412		}
413		ret <<= 7
414		b := s.read(1)[0]
415		ret |= int(b & 0x7f)
416		if b&0x80 == 0 {
417			*out = ret
418			return true
419		}
420	}
421	return false // truncated
422}
423
424// ReadASN1ObjectIdentifier decodes an ASN.1 OBJECT IDENTIFIER into out and
425// advances. It reports whether the read was successful.
426func (s *String) ReadASN1ObjectIdentifier(out *encoding_asn1.ObjectIdentifier) bool {
427	var bytes String
428	if !s.ReadASN1(&bytes, asn1.OBJECT_IDENTIFIER) || len(bytes) == 0 {
429		return false
430	}
431
432	// In the worst case, we get two elements from the first byte (which is
433	// encoded differently) and then every varint is a single byte long.
434	components := make([]int, len(bytes)+1)
435
436	// The first varint is 40*value1 + value2:
437	// According to this packing, value1 can take the values 0, 1 and 2 only.
438	// When value1 = 0 or value1 = 1, then value2 is <= 39. When value1 = 2,
439	// then there are no restrictions on value2.
440	var v int
441	if !bytes.readBase128Int(&v) {
442		return false
443	}
444	if v < 80 {
445		components[0] = v / 40
446		components[1] = v % 40
447	} else {
448		components[0] = 2
449		components[1] = v - 80
450	}
451
452	i := 2
453	for ; len(bytes) > 0; i++ {
454		if !bytes.readBase128Int(&v) {
455			return false
456		}
457		components[i] = v
458	}
459	*out = components[:i]
460	return true
461}
462
463// ReadASN1GeneralizedTime decodes an ASN.1 GENERALIZEDTIME into out and
464// advances. It reports whether the read was successful.
465func (s *String) ReadASN1GeneralizedTime(out *time.Time) bool {
466	var bytes String
467	if !s.ReadASN1(&bytes, asn1.GeneralizedTime) {
468		return false
469	}
470	t := string(bytes)
471	res, err := time.Parse(generalizedTimeFormatStr, t)
472	if err != nil {
473		return false
474	}
475	if serialized := res.Format(generalizedTimeFormatStr); serialized != t {
476		return false
477	}
478	*out = res
479	return true
480}
481
482const defaultUTCTimeFormatStr = "060102150405Z0700"
483
484// ReadASN1UTCTime decodes an ASN.1 UTCTime into out and advances.
485// It reports whether the read was successful.
486func (s *String) ReadASN1UTCTime(out *time.Time) bool {
487	var bytes String
488	if !s.ReadASN1(&bytes, asn1.UTCTime) {
489		return false
490	}
491	t := string(bytes)
492
493	formatStr := defaultUTCTimeFormatStr
494	var err error
495	res, err := time.Parse(formatStr, t)
496	if err != nil {
497		// Fallback to minute precision if we can't parse second
498		// precision. If we are following X.509 or X.690 we shouldn't
499		// support this, but we do.
500		formatStr = "0601021504Z0700"
501		res, err = time.Parse(formatStr, t)
502	}
503	if err != nil {
504		return false
505	}
506
507	if serialized := res.Format(formatStr); serialized != t {
508		return false
509	}
510
511	if res.Year() >= 2050 {
512		// UTCTime interprets the low order digits 50-99 as 1950-99.
513		// This only applies to its use in the X.509 profile.
514		// See https://tools.ietf.org/html/rfc5280#section-4.1.2.5.1
515		res = res.AddDate(-100, 0, 0)
516	}
517	*out = res
518	return true
519}
520
521// ReadASN1BitString decodes an ASN.1 BIT STRING into out and advances.
522// It reports whether the read was successful.
523func (s *String) ReadASN1BitString(out *encoding_asn1.BitString) bool {
524	var bytes String
525	if !s.ReadASN1(&bytes, asn1.BIT_STRING) || len(bytes) == 0 ||
526		len(bytes)*8/8 != len(bytes) {
527		return false
528	}
529
530	paddingBits := uint8(bytes[0])
531	bytes = bytes[1:]
532	if paddingBits > 7 ||
533		len(bytes) == 0 && paddingBits != 0 ||
534		len(bytes) > 0 && bytes[len(bytes)-1]&(1<<paddingBits-1) != 0 {
535		return false
536	}
537
538	out.BitLength = len(bytes)*8 - int(paddingBits)
539	out.Bytes = bytes
540	return true
541}
542
543// ReadASN1BitString decodes an ASN.1 BIT STRING into out and advances. It is
544// an error if the BIT STRING is not a whole number of bytes. It reports
545// whether the read was successful.
546func (s *String) ReadASN1BitStringAsBytes(out *[]byte) bool {
547	var bytes String
548	if !s.ReadASN1(&bytes, asn1.BIT_STRING) || len(bytes) == 0 {
549		return false
550	}
551
552	paddingBits := uint8(bytes[0])
553	if paddingBits != 0 {
554		return false
555	}
556	*out = bytes[1:]
557	return true
558}
559
560// ReadASN1Bytes reads the contents of a DER-encoded ASN.1 element (not including
561// tag and length bytes) into out, and advances. The element must match the
562// given tag. It reports whether the read was successful.
563func (s *String) ReadASN1Bytes(out *[]byte, tag asn1.Tag) bool {
564	return s.ReadASN1((*String)(out), tag)
565}
566
567// ReadASN1 reads the contents of a DER-encoded ASN.1 element (not including
568// tag and length bytes) into out, and advances. The element must match the
569// given tag. It reports whether the read was successful.
570//
571// Tags greater than 30 are not supported (i.e. low-tag-number format only).
572func (s *String) ReadASN1(out *String, tag asn1.Tag) bool {
573	var t asn1.Tag
574	if !s.ReadAnyASN1(out, &t) || t != tag {
575		return false
576	}
577	return true
578}
579
580// ReadASN1Element reads the contents of a DER-encoded ASN.1 element (including
581// tag and length bytes) into out, and advances. The element must match the
582// given tag. It reports whether the read was successful.
583//
584// Tags greater than 30 are not supported (i.e. low-tag-number format only).
585func (s *String) ReadASN1Element(out *String, tag asn1.Tag) bool {
586	var t asn1.Tag
587	if !s.ReadAnyASN1Element(out, &t) || t != tag {
588		return false
589	}
590	return true
591}
592
593// ReadAnyASN1 reads the contents of a DER-encoded ASN.1 element (not including
594// tag and length bytes) into out, sets outTag to its tag, and advances.
595// It reports whether the read was successful.
596//
597// Tags greater than 30 are not supported (i.e. low-tag-number format only).
598func (s *String) ReadAnyASN1(out *String, outTag *asn1.Tag) bool {
599	return s.readASN1(out, outTag, true /* skip header */)
600}
601
602// ReadAnyASN1Element reads the contents of a DER-encoded ASN.1 element
603// (including tag and length bytes) into out, sets outTag to is tag, and
604// advances. It reports whether the read was successful.
605//
606// Tags greater than 30 are not supported (i.e. low-tag-number format only).
607func (s *String) ReadAnyASN1Element(out *String, outTag *asn1.Tag) bool {
608	return s.readASN1(out, outTag, false /* include header */)
609}
610
611// PeekASN1Tag reports whether the next ASN.1 value on the string starts with
612// the given tag.
613func (s String) PeekASN1Tag(tag asn1.Tag) bool {
614	if len(s) == 0 {
615		return false
616	}
617	return asn1.Tag(s[0]) == tag
618}
619
620// SkipASN1 reads and discards an ASN.1 element with the given tag. It
621// reports whether the operation was successful.
622func (s *String) SkipASN1(tag asn1.Tag) bool {
623	var unused String
624	return s.ReadASN1(&unused, tag)
625}
626
627// ReadOptionalASN1 attempts to read the contents of a DER-encoded ASN.1
628// element (not including tag and length bytes) tagged with the given tag into
629// out. It stores whether an element with the tag was found in outPresent,
630// unless outPresent is nil. It reports whether the read was successful.
631func (s *String) ReadOptionalASN1(out *String, outPresent *bool, tag asn1.Tag) bool {
632	present := s.PeekASN1Tag(tag)
633	if outPresent != nil {
634		*outPresent = present
635	}
636	if present && !s.ReadASN1(out, tag) {
637		return false
638	}
639	return true
640}
641
642// SkipOptionalASN1 advances s over an ASN.1 element with the given tag, or
643// else leaves s unchanged. It reports whether the operation was successful.
644func (s *String) SkipOptionalASN1(tag asn1.Tag) bool {
645	if !s.PeekASN1Tag(tag) {
646		return true
647	}
648	var unused String
649	return s.ReadASN1(&unused, tag)
650}
651
652// ReadOptionalASN1Integer attempts to read an optional ASN.1 INTEGER
653// explicitly tagged with tag into out and advances. If no element with a
654// matching tag is present, it writes defaultValue into out instead. If out
655// does not point to an integer or to a big.Int, it panics. It reports
656// whether the read was successful.
657func (s *String) ReadOptionalASN1Integer(out interface{}, tag asn1.Tag, defaultValue interface{}) bool {
658	if reflect.TypeOf(out).Kind() != reflect.Ptr {
659		panic("out is not a pointer")
660	}
661	var present bool
662	var i String
663	if !s.ReadOptionalASN1(&i, &present, tag) {
664		return false
665	}
666	if !present {
667		switch reflect.ValueOf(out).Elem().Kind() {
668		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
669			reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
670			reflect.ValueOf(out).Elem().Set(reflect.ValueOf(defaultValue))
671		case reflect.Struct:
672			if reflect.TypeOf(out).Elem() != bigIntType {
673				panic("invalid integer type")
674			}
675			if reflect.TypeOf(defaultValue).Kind() != reflect.Ptr ||
676				reflect.TypeOf(defaultValue).Elem() != bigIntType {
677				panic("out points to big.Int, but defaultValue does not")
678			}
679			out.(*big.Int).Set(defaultValue.(*big.Int))
680		default:
681			panic("invalid integer type")
682		}
683		return true
684	}
685	if !i.ReadASN1Integer(out) || !i.Empty() {
686		return false
687	}
688	return true
689}
690
691// ReadOptionalASN1OctetString attempts to read an optional ASN.1 OCTET STRING
692// explicitly tagged with tag into out and advances. If no element with a
693// matching tag is present, it sets "out" to nil instead. It reports
694// whether the read was successful.
695func (s *String) ReadOptionalASN1OctetString(out *[]byte, outPresent *bool, tag asn1.Tag) bool {
696	var present bool
697	var child String
698	if !s.ReadOptionalASN1(&child, &present, tag) {
699		return false
700	}
701	if outPresent != nil {
702		*outPresent = present
703	}
704	if present {
705		var oct String
706		if !child.ReadASN1(&oct, asn1.OCTET_STRING) || !child.Empty() {
707			return false
708		}
709		*out = oct
710	} else {
711		*out = nil
712	}
713	return true
714}
715
716// ReadOptionalASN1Boolean sets *out to the value of the next ASN.1 BOOLEAN or,
717// if the next bytes are not an ASN.1 BOOLEAN, to the value of defaultValue.
718// It reports whether the operation was successful.
719func (s *String) ReadOptionalASN1Boolean(out *bool, defaultValue bool) bool {
720	var present bool
721	var child String
722	if !s.ReadOptionalASN1(&child, &present, asn1.BOOLEAN) {
723		return false
724	}
725
726	if !present {
727		*out = defaultValue
728		return true
729	}
730
731	return s.ReadASN1Boolean(out)
732}
733
734func (s *String) readASN1(out *String, outTag *asn1.Tag, skipHeader bool) bool {
735	if len(*s) < 2 {
736		return false
737	}
738	tag, lenByte := (*s)[0], (*s)[1]
739
740	if tag&0x1f == 0x1f {
741		// ITU-T X.690 section 8.1.2
742		//
743		// An identifier octet with a tag part of 0x1f indicates a high-tag-number
744		// form identifier with two or more octets. We only support tags less than
745		// 31 (i.e. low-tag-number form, single octet identifier).
746		return false
747	}
748
749	if outTag != nil {
750		*outTag = asn1.Tag(tag)
751	}
752
753	// ITU-T X.690 section 8.1.3
754	//
755	// Bit 8 of the first length byte indicates whether the length is short- or
756	// long-form.
757	var length, headerLen uint32 // length includes headerLen
758	if lenByte&0x80 == 0 {
759		// Short-form length (section 8.1.3.4), encoded in bits 1-7.
760		length = uint32(lenByte) + 2
761		headerLen = 2
762	} else {
763		// Long-form length (section 8.1.3.5). Bits 1-7 encode the number of octets
764		// used to encode the length.
765		lenLen := lenByte & 0x7f
766		var len32 uint32
767
768		if lenLen == 0 || lenLen > 4 || len(*s) < int(2+lenLen) {
769			return false
770		}
771
772		lenBytes := String((*s)[2 : 2+lenLen])
773		if !lenBytes.readUnsigned(&len32, int(lenLen)) {
774			return false
775		}
776
777		// ITU-T X.690 section 10.1 (DER length forms) requires encoding the length
778		// with the minimum number of octets.
779		if len32 < 128 {
780			// Length should have used short-form encoding.
781			return false
782		}
783		if len32>>((lenLen-1)*8) == 0 {
784			// Leading octet is 0. Length should have been at least one byte shorter.
785			return false
786		}
787
788		headerLen = 2 + uint32(lenLen)
789		if headerLen+len32 < len32 {
790			// Overflow.
791			return false
792		}
793		length = headerLen + len32
794	}
795
796	if int(length) < 0 || !s.ReadBytes((*[]byte)(out), int(length)) {
797		return false
798	}
799	if skipHeader && !out.Skip(int(headerLen)) {
800		panic("cryptobyte: internal error")
801	}
802
803	return true
804}
805