asn1.go 21 KB

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