asn1.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737
  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. // ReadASN1Boolean decodes an ASN.1 INTEGER and converts it to a boolean
  196. // representation into out and advances. It reports whether the read
  197. // was successful.
  198. func (s *String) ReadASN1Boolean(out *bool) bool {
  199. var bytes String
  200. if !s.ReadASN1(&bytes, asn1.INTEGER) || len(bytes) != 1 {
  201. return false
  202. }
  203. switch bytes[0] {
  204. case 0:
  205. *out = false
  206. case 0xff:
  207. *out = true
  208. default:
  209. return false
  210. }
  211. return true
  212. }
  213. var bigIntType = reflect.TypeOf((*big.Int)(nil)).Elem()
  214. // ReadASN1Integer decodes an ASN.1 INTEGER into out and advances. If out does
  215. // not point to an integer or to a big.Int, it panics. It reports whether the
  216. // read was successful.
  217. func (s *String) ReadASN1Integer(out interface{}) bool {
  218. if reflect.TypeOf(out).Kind() != reflect.Ptr {
  219. panic("out is not a pointer")
  220. }
  221. switch reflect.ValueOf(out).Elem().Kind() {
  222. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  223. var i int64
  224. if !s.readASN1Int64(&i) || reflect.ValueOf(out).Elem().OverflowInt(i) {
  225. return false
  226. }
  227. reflect.ValueOf(out).Elem().SetInt(i)
  228. return true
  229. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  230. var u uint64
  231. if !s.readASN1Uint64(&u) || reflect.ValueOf(out).Elem().OverflowUint(u) {
  232. return false
  233. }
  234. reflect.ValueOf(out).Elem().SetUint(u)
  235. return true
  236. case reflect.Struct:
  237. if reflect.TypeOf(out).Elem() == bigIntType {
  238. return s.readASN1BigInt(out.(*big.Int))
  239. }
  240. }
  241. panic("out does not point to an integer type")
  242. }
  243. func checkASN1Integer(bytes []byte) bool {
  244. if len(bytes) == 0 {
  245. // An INTEGER is encoded with at least one octet.
  246. return false
  247. }
  248. if len(bytes) == 1 {
  249. return true
  250. }
  251. if bytes[0] == 0 && bytes[1]&0x80 == 0 || bytes[0] == 0xff && bytes[1]&0x80 == 0x80 {
  252. // Value is not minimally encoded.
  253. return false
  254. }
  255. return true
  256. }
  257. var bigOne = big.NewInt(1)
  258. func (s *String) readASN1BigInt(out *big.Int) bool {
  259. var bytes String
  260. if !s.ReadASN1(&bytes, asn1.INTEGER) || !checkASN1Integer(bytes) {
  261. return false
  262. }
  263. if bytes[0]&0x80 == 0x80 {
  264. // Negative number.
  265. neg := make([]byte, len(bytes))
  266. for i, b := range bytes {
  267. neg[i] = ^b
  268. }
  269. out.SetBytes(neg)
  270. out.Add(out, bigOne)
  271. out.Neg(out)
  272. } else {
  273. out.SetBytes(bytes)
  274. }
  275. return true
  276. }
  277. func (s *String) readASN1Int64(out *int64) bool {
  278. var bytes String
  279. if !s.ReadASN1(&bytes, asn1.INTEGER) || !checkASN1Integer(bytes) || !asn1Signed(out, bytes) {
  280. return false
  281. }
  282. return true
  283. }
  284. func asn1Signed(out *int64, n []byte) bool {
  285. length := len(n)
  286. if length > 8 {
  287. return false
  288. }
  289. for i := 0; i < length; i++ {
  290. *out <<= 8
  291. *out |= int64(n[i])
  292. }
  293. // Shift up and down in order to sign extend the result.
  294. *out <<= 64 - uint8(length)*8
  295. *out >>= 64 - uint8(length)*8
  296. return true
  297. }
  298. func (s *String) readASN1Uint64(out *uint64) bool {
  299. var bytes String
  300. if !s.ReadASN1(&bytes, asn1.INTEGER) || !checkASN1Integer(bytes) || !asn1Unsigned(out, bytes) {
  301. return false
  302. }
  303. return true
  304. }
  305. func asn1Unsigned(out *uint64, n []byte) bool {
  306. length := len(n)
  307. if length > 9 || length == 9 && n[0] != 0 {
  308. // Too large for uint64.
  309. return false
  310. }
  311. if n[0]&0x80 != 0 {
  312. // Negative number.
  313. return false
  314. }
  315. for i := 0; i < length; i++ {
  316. *out <<= 8
  317. *out |= uint64(n[i])
  318. }
  319. return true
  320. }
  321. // ReadASN1Enum decodes an ASN.1 ENUMERATION into out and advances. It reports
  322. // whether the read was successful.
  323. func (s *String) ReadASN1Enum(out *int) bool {
  324. var bytes String
  325. var i int64
  326. if !s.ReadASN1(&bytes, asn1.ENUM) || !checkASN1Integer(bytes) || !asn1Signed(&i, bytes) {
  327. return false
  328. }
  329. if int64(int(i)) != i {
  330. return false
  331. }
  332. *out = int(i)
  333. return true
  334. }
  335. func (s *String) readBase128Int(out *int) bool {
  336. ret := 0
  337. for i := 0; len(*s) > 0; i++ {
  338. if i == 4 {
  339. return false
  340. }
  341. ret <<= 7
  342. b := s.read(1)[0]
  343. ret |= int(b & 0x7f)
  344. if b&0x80 == 0 {
  345. *out = ret
  346. return true
  347. }
  348. }
  349. return false // truncated
  350. }
  351. // ReadASN1ObjectIdentifier decodes an ASN.1 OBJECT IDENTIFIER into out and
  352. // advances. It reports whether the read was successful.
  353. func (s *String) ReadASN1ObjectIdentifier(out *encoding_asn1.ObjectIdentifier) bool {
  354. var bytes String
  355. if !s.ReadASN1(&bytes, asn1.OBJECT_IDENTIFIER) || len(bytes) == 0 {
  356. return false
  357. }
  358. // In the worst case, we get two elements from the first byte (which is
  359. // encoded differently) and then every varint is a single byte long.
  360. components := make([]int, len(bytes)+1)
  361. // The first varint is 40*value1 + value2:
  362. // According to this packing, value1 can take the values 0, 1 and 2 only.
  363. // When value1 = 0 or value1 = 1, then value2 is <= 39. When value1 = 2,
  364. // then there are no restrictions on value2.
  365. var v int
  366. if !bytes.readBase128Int(&v) {
  367. return false
  368. }
  369. if v < 80 {
  370. components[0] = v / 40
  371. components[1] = v % 40
  372. } else {
  373. components[0] = 2
  374. components[1] = v - 80
  375. }
  376. i := 2
  377. for ; len(bytes) > 0; i++ {
  378. if !bytes.readBase128Int(&v) {
  379. return false
  380. }
  381. components[i] = v
  382. }
  383. *out = components[:i]
  384. return true
  385. }
  386. // ReadASN1GeneralizedTime decodes an ASN.1 GENERALIZEDTIME into out and
  387. // advances. It reports whether the read was successful.
  388. func (s *String) ReadASN1GeneralizedTime(out *time.Time) bool {
  389. var bytes String
  390. if !s.ReadASN1(&bytes, asn1.GeneralizedTime) {
  391. return false
  392. }
  393. t := string(bytes)
  394. res, err := time.Parse(generalizedTimeFormatStr, t)
  395. if err != nil {
  396. return false
  397. }
  398. if serialized := res.Format(generalizedTimeFormatStr); serialized != t {
  399. return false
  400. }
  401. *out = res
  402. return true
  403. }
  404. // ReadASN1BitString decodes an ASN.1 BIT STRING into out and advances.
  405. // It reports whether the read was successful.
  406. func (s *String) ReadASN1BitString(out *encoding_asn1.BitString) bool {
  407. var bytes String
  408. if !s.ReadASN1(&bytes, asn1.BIT_STRING) || len(bytes) == 0 {
  409. return false
  410. }
  411. paddingBits := uint8(bytes[0])
  412. bytes = bytes[1:]
  413. if paddingBits > 7 ||
  414. len(bytes) == 0 && paddingBits != 0 ||
  415. len(bytes) > 0 && bytes[len(bytes)-1]&(1<<paddingBits-1) != 0 {
  416. return false
  417. }
  418. out.BitLength = len(bytes)*8 - int(paddingBits)
  419. out.Bytes = bytes
  420. return true
  421. }
  422. // ReadASN1BitString decodes an ASN.1 BIT STRING into out and advances. It is
  423. // an error if the BIT STRING is not a whole number of bytes. It reports
  424. // whether the read was successful.
  425. func (s *String) ReadASN1BitStringAsBytes(out *[]byte) bool {
  426. var bytes String
  427. if !s.ReadASN1(&bytes, asn1.BIT_STRING) || len(bytes) == 0 {
  428. return false
  429. }
  430. paddingBits := uint8(bytes[0])
  431. if paddingBits != 0 {
  432. return false
  433. }
  434. *out = bytes[1:]
  435. return true
  436. }
  437. // ReadASN1Bytes reads the contents of a DER-encoded ASN.1 element (not including
  438. // tag and length bytes) into out, and advances. The element must match the
  439. // given tag. It reports whether the read was successful.
  440. func (s *String) ReadASN1Bytes(out *[]byte, tag asn1.Tag) bool {
  441. return s.ReadASN1((*String)(out), tag)
  442. }
  443. // ReadASN1 reads the contents of a DER-encoded ASN.1 element (not including
  444. // tag and length bytes) into out, and advances. The element must match the
  445. // given tag. It reports whether the read was successful.
  446. //
  447. // Tags greater than 30 are not supported (i.e. low-tag-number format only).
  448. func (s *String) ReadASN1(out *String, tag asn1.Tag) bool {
  449. var t asn1.Tag
  450. if !s.ReadAnyASN1(out, &t) || t != tag {
  451. return false
  452. }
  453. return true
  454. }
  455. // ReadASN1Element reads the contents of a DER-encoded ASN.1 element (including
  456. // tag and length bytes) into out, and advances. The element must match the
  457. // given tag. It reports whether the read was successful.
  458. //
  459. // Tags greater than 30 are not supported (i.e. low-tag-number format only).
  460. func (s *String) ReadASN1Element(out *String, tag asn1.Tag) bool {
  461. var t asn1.Tag
  462. if !s.ReadAnyASN1Element(out, &t) || t != tag {
  463. return false
  464. }
  465. return true
  466. }
  467. // ReadAnyASN1 reads the contents of a DER-encoded ASN.1 element (not including
  468. // tag and length bytes) into out, sets outTag to its tag, and advances.
  469. // It reports whether the read was successful.
  470. //
  471. // Tags greater than 30 are not supported (i.e. low-tag-number format only).
  472. func (s *String) ReadAnyASN1(out *String, outTag *asn1.Tag) bool {
  473. return s.readASN1(out, outTag, true /* skip header */)
  474. }
  475. // ReadAnyASN1Element reads the contents of a DER-encoded ASN.1 element
  476. // (including tag and length bytes) into out, sets outTag to is tag, and
  477. // advances. It reports whether the read was successful.
  478. //
  479. // Tags greater than 30 are not supported (i.e. low-tag-number format only).
  480. func (s *String) ReadAnyASN1Element(out *String, outTag *asn1.Tag) bool {
  481. return s.readASN1(out, outTag, false /* include header */)
  482. }
  483. // PeekASN1Tag reports whether the next ASN.1 value on the string starts with
  484. // the given tag.
  485. func (s String) PeekASN1Tag(tag asn1.Tag) bool {
  486. if len(s) == 0 {
  487. return false
  488. }
  489. return asn1.Tag(s[0]) == tag
  490. }
  491. // SkipASN1 reads and discards an ASN.1 element with the given tag. It
  492. // reports whether the operation was successful.
  493. func (s *String) SkipASN1(tag asn1.Tag) bool {
  494. var unused String
  495. return s.ReadASN1(&unused, tag)
  496. }
  497. // ReadOptionalASN1 attempts to read the contents of a DER-encoded ASN.1
  498. // element (not including tag and length bytes) tagged with the given tag into
  499. // out. It stores whether an element with the tag was found in outPresent,
  500. // unless outPresent is nil. It reports whether the read was successful.
  501. func (s *String) ReadOptionalASN1(out *String, outPresent *bool, tag asn1.Tag) bool {
  502. present := s.PeekASN1Tag(tag)
  503. if outPresent != nil {
  504. *outPresent = present
  505. }
  506. if present && !s.ReadASN1(out, tag) {
  507. return false
  508. }
  509. return true
  510. }
  511. // SkipOptionalASN1 advances s over an ASN.1 element with the given tag, or
  512. // else leaves s unchanged. It reports whether the operation was successful.
  513. func (s *String) SkipOptionalASN1(tag asn1.Tag) bool {
  514. if !s.PeekASN1Tag(tag) {
  515. return true
  516. }
  517. var unused String
  518. return s.ReadASN1(&unused, tag)
  519. }
  520. // ReadOptionalASN1Integer attempts to read an optional ASN.1 INTEGER
  521. // explicitly tagged with tag into out and advances. If no element with a
  522. // matching tag is present, it writes defaultValue into out instead. If out
  523. // does not point to an integer or to a big.Int, it panics. It reports
  524. // whether the read was successful.
  525. func (s *String) ReadOptionalASN1Integer(out interface{}, tag asn1.Tag, defaultValue interface{}) bool {
  526. if reflect.TypeOf(out).Kind() != reflect.Ptr {
  527. panic("out is not a pointer")
  528. }
  529. var present bool
  530. var i String
  531. if !s.ReadOptionalASN1(&i, &present, tag) {
  532. return false
  533. }
  534. if !present {
  535. switch reflect.ValueOf(out).Elem().Kind() {
  536. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
  537. reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  538. reflect.ValueOf(out).Elem().Set(reflect.ValueOf(defaultValue))
  539. case reflect.Struct:
  540. if reflect.TypeOf(out).Elem() != bigIntType {
  541. panic("invalid integer type")
  542. }
  543. if reflect.TypeOf(defaultValue).Kind() != reflect.Ptr ||
  544. reflect.TypeOf(defaultValue).Elem() != bigIntType {
  545. panic("out points to big.Int, but defaultValue does not")
  546. }
  547. out.(*big.Int).Set(defaultValue.(*big.Int))
  548. default:
  549. panic("invalid integer type")
  550. }
  551. return true
  552. }
  553. if !i.ReadASN1Integer(out) || !i.Empty() {
  554. return false
  555. }
  556. return true
  557. }
  558. // ReadOptionalASN1OctetString attempts to read an optional ASN.1 OCTET STRING
  559. // explicitly tagged with tag into out and advances. If no element with a
  560. // matching tag is present, it writes defaultValue into out instead. It reports
  561. // whether the read was successful.
  562. func (s *String) ReadOptionalASN1OctetString(out *[]byte, outPresent *bool, tag asn1.Tag) bool {
  563. var present bool
  564. var child String
  565. if !s.ReadOptionalASN1(&child, &present, tag) {
  566. return false
  567. }
  568. if outPresent != nil {
  569. *outPresent = present
  570. }
  571. if present {
  572. var oct String
  573. if !child.ReadASN1(&oct, asn1.OCTET_STRING) || !child.Empty() {
  574. return false
  575. }
  576. *out = oct
  577. } else {
  578. *out = nil
  579. }
  580. return true
  581. }
  582. // ReadOptionalASN1Boolean sets *out to the value of the next ASN.1 BOOLEAN or,
  583. // if the next bytes are not an ASN.1 BOOLEAN, to the value of defaultValue.
  584. // It reports whether the operation was successful.
  585. func (s *String) ReadOptionalASN1Boolean(out *bool, defaultValue bool) bool {
  586. var present bool
  587. var child String
  588. if !s.ReadOptionalASN1(&child, &present, asn1.BOOLEAN) {
  589. return false
  590. }
  591. if !present {
  592. *out = defaultValue
  593. return true
  594. }
  595. return s.ReadASN1Boolean(out)
  596. }
  597. func (s *String) readASN1(out *String, outTag *asn1.Tag, skipHeader bool) bool {
  598. if len(*s) < 2 {
  599. return false
  600. }
  601. tag, lenByte := (*s)[0], (*s)[1]
  602. if tag&0x1f == 0x1f {
  603. // ITU-T X.690 section 8.1.2
  604. //
  605. // An identifier octet with a tag part of 0x1f indicates a high-tag-number
  606. // form identifier with two or more octets. We only support tags less than
  607. // 31 (i.e. low-tag-number form, single octet identifier).
  608. return false
  609. }
  610. if outTag != nil {
  611. *outTag = asn1.Tag(tag)
  612. }
  613. // ITU-T X.690 section 8.1.3
  614. //
  615. // Bit 8 of the first length byte indicates whether the length is short- or
  616. // long-form.
  617. var length, headerLen uint32 // length includes headerLen
  618. if lenByte&0x80 == 0 {
  619. // Short-form length (section 8.1.3.4), encoded in bits 1-7.
  620. length = uint32(lenByte) + 2
  621. headerLen = 2
  622. } else {
  623. // Long-form length (section 8.1.3.5). Bits 1-7 encode the number of octets
  624. // used to encode the length.
  625. lenLen := lenByte & 0x7f
  626. var len32 uint32
  627. if lenLen == 0 || lenLen > 4 || len(*s) < int(2+lenLen) {
  628. return false
  629. }
  630. lenBytes := String((*s)[2 : 2+lenLen])
  631. if !lenBytes.readUnsigned(&len32, int(lenLen)) {
  632. return false
  633. }
  634. // ITU-T X.690 section 10.1 (DER length forms) requires encoding the length
  635. // with the minimum number of octets.
  636. if len32 < 128 {
  637. // Length should have used short-form encoding.
  638. return false
  639. }
  640. if len32>>((lenLen-1)*8) == 0 {
  641. // Leading octet is 0. Length should have been at least one byte shorter.
  642. return false
  643. }
  644. headerLen = 2 + uint32(lenLen)
  645. if headerLen+len32 < len32 {
  646. // Overflow.
  647. return false
  648. }
  649. length = headerLen + len32
  650. }
  651. if uint32(int(length)) != length || !s.ReadBytes((*[]byte)(out), int(length)) {
  652. return false
  653. }
  654. if skipHeader && !out.Skip(int(headerLen)) {
  655. panic("cryptobyte: internal error")
  656. }
  657. return true
  658. }