asn1.go 19 KB

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