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