asn1.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824
  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. // ReadASN1Integer decodes an ASN.1 INTEGER into out and advances. If out does
  231. // not point to an integer, to a big.Int, or to a []byte it panics. Only
  232. // positive and zero values can be decoded into []byte, and they are returned as
  233. // big-endian binary values that share memory with s. Positive values will have
  234. // no leading zeroes, and zero will be returned as a single zero byte.
  235. // ReadASN1Integer reports whether the read was successful.
  236. func (s *String) ReadASN1Integer(out interface{}) bool {
  237. switch out := out.(type) {
  238. case *int, *int8, *int16, *int32, *int64:
  239. var i int64
  240. if !s.readASN1Int64(&i) || reflect.ValueOf(out).Elem().OverflowInt(i) {
  241. return false
  242. }
  243. reflect.ValueOf(out).Elem().SetInt(i)
  244. return true
  245. case *uint, *uint8, *uint16, *uint32, *uint64:
  246. var u uint64
  247. if !s.readASN1Uint64(&u) || reflect.ValueOf(out).Elem().OverflowUint(u) {
  248. return false
  249. }
  250. reflect.ValueOf(out).Elem().SetUint(u)
  251. return true
  252. case *big.Int:
  253. return s.readASN1BigInt(out)
  254. case *[]byte:
  255. return s.readASN1Bytes(out)
  256. default:
  257. panic("out does not point to an integer type")
  258. }
  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) readASN1Bytes(out *[]byte) 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. return false
  301. }
  302. for len(bytes) > 1 && bytes[0] == 0 {
  303. bytes = bytes[1:]
  304. }
  305. *out = bytes
  306. return true
  307. }
  308. func (s *String) readASN1Int64(out *int64) bool {
  309. var bytes String
  310. if !s.ReadASN1(&bytes, asn1.INTEGER) || !checkASN1Integer(bytes) || !asn1Signed(out, bytes) {
  311. return false
  312. }
  313. return true
  314. }
  315. func asn1Signed(out *int64, n []byte) bool {
  316. length := len(n)
  317. if length > 8 {
  318. return false
  319. }
  320. for i := 0; i < length; i++ {
  321. *out <<= 8
  322. *out |= int64(n[i])
  323. }
  324. // Shift up and down in order to sign extend the result.
  325. *out <<= 64 - uint8(length)*8
  326. *out >>= 64 - uint8(length)*8
  327. return true
  328. }
  329. func (s *String) readASN1Uint64(out *uint64) bool {
  330. var bytes String
  331. if !s.ReadASN1(&bytes, asn1.INTEGER) || !checkASN1Integer(bytes) || !asn1Unsigned(out, bytes) {
  332. return false
  333. }
  334. return true
  335. }
  336. func asn1Unsigned(out *uint64, n []byte) bool {
  337. length := len(n)
  338. if length > 9 || length == 9 && n[0] != 0 {
  339. // Too large for uint64.
  340. return false
  341. }
  342. if n[0]&0x80 != 0 {
  343. // Negative number.
  344. return false
  345. }
  346. for i := 0; i < length; i++ {
  347. *out <<= 8
  348. *out |= uint64(n[i])
  349. }
  350. return true
  351. }
  352. // ReadASN1Int64WithTag decodes an ASN.1 INTEGER with the given tag into out
  353. // and advances. It reports whether the read was successful and resulted in a
  354. // value that can be represented in an int64.
  355. func (s *String) ReadASN1Int64WithTag(out *int64, tag asn1.Tag) bool {
  356. var bytes String
  357. return s.ReadASN1(&bytes, tag) && checkASN1Integer(bytes) && asn1Signed(out, bytes)
  358. }
  359. // ReadASN1Enum decodes an ASN.1 ENUMERATION into out and advances. It reports
  360. // whether the read was successful.
  361. func (s *String) ReadASN1Enum(out *int) bool {
  362. var bytes String
  363. var i int64
  364. if !s.ReadASN1(&bytes, asn1.ENUM) || !checkASN1Integer(bytes) || !asn1Signed(&i, bytes) {
  365. return false
  366. }
  367. if int64(int(i)) != i {
  368. return false
  369. }
  370. *out = int(i)
  371. return true
  372. }
  373. func (s *String) readBase128Int(out *int) bool {
  374. ret := 0
  375. for i := 0; len(*s) > 0; i++ {
  376. if i == 5 {
  377. return false
  378. }
  379. // Avoid overflowing int on a 32-bit platform.
  380. // We don't want different behavior based on the architecture.
  381. if ret >= 1<<(31-7) {
  382. return false
  383. }
  384. ret <<= 7
  385. b := s.read(1)[0]
  386. // ITU-T X.690, section 8.19.2:
  387. // The subidentifier shall be encoded in the fewest possible octets,
  388. // that is, the leading octet of the subidentifier shall not have the value 0x80.
  389. if i == 0 && b == 0x80 {
  390. return false
  391. }
  392. ret |= int(b & 0x7f)
  393. if b&0x80 == 0 {
  394. *out = ret
  395. return true
  396. }
  397. }
  398. return false // truncated
  399. }
  400. // ReadASN1ObjectIdentifier decodes an ASN.1 OBJECT IDENTIFIER into out and
  401. // advances. It reports whether the read was successful.
  402. func (s *String) ReadASN1ObjectIdentifier(out *encoding_asn1.ObjectIdentifier) bool {
  403. var bytes String
  404. if !s.ReadASN1(&bytes, asn1.OBJECT_IDENTIFIER) || len(bytes) == 0 {
  405. return false
  406. }
  407. // In the worst case, we get two elements from the first byte (which is
  408. // encoded differently) and then every varint is a single byte long.
  409. components := make([]int, len(bytes)+1)
  410. // The first varint is 40*value1 + value2:
  411. // According to this packing, value1 can take the values 0, 1 and 2 only.
  412. // When value1 = 0 or value1 = 1, then value2 is <= 39. When value1 = 2,
  413. // then there are no restrictions on value2.
  414. var v int
  415. if !bytes.readBase128Int(&v) {
  416. return false
  417. }
  418. if v < 80 {
  419. components[0] = v / 40
  420. components[1] = v % 40
  421. } else {
  422. components[0] = 2
  423. components[1] = v - 80
  424. }
  425. i := 2
  426. for ; len(bytes) > 0; i++ {
  427. if !bytes.readBase128Int(&v) {
  428. return false
  429. }
  430. components[i] = v
  431. }
  432. *out = components[:i]
  433. return true
  434. }
  435. // ReadASN1GeneralizedTime decodes an ASN.1 GENERALIZEDTIME into out and
  436. // advances. It reports whether the read was successful.
  437. func (s *String) ReadASN1GeneralizedTime(out *time.Time) bool {
  438. var bytes String
  439. if !s.ReadASN1(&bytes, asn1.GeneralizedTime) {
  440. return false
  441. }
  442. t := string(bytes)
  443. res, err := time.Parse(generalizedTimeFormatStr, t)
  444. if err != nil {
  445. return false
  446. }
  447. if serialized := res.Format(generalizedTimeFormatStr); serialized != t {
  448. return false
  449. }
  450. *out = res
  451. return true
  452. }
  453. const defaultUTCTimeFormatStr = "060102150405Z0700"
  454. // ReadASN1UTCTime decodes an ASN.1 UTCTime into out and advances.
  455. // It reports whether the read was successful.
  456. func (s *String) ReadASN1UTCTime(out *time.Time) bool {
  457. var bytes String
  458. if !s.ReadASN1(&bytes, asn1.UTCTime) {
  459. return false
  460. }
  461. t := string(bytes)
  462. formatStr := defaultUTCTimeFormatStr
  463. var err error
  464. res, err := time.Parse(formatStr, t)
  465. if err != nil {
  466. // Fallback to minute precision if we can't parse second
  467. // precision. If we are following X.509 or X.690 we shouldn't
  468. // support this, but we do.
  469. formatStr = "0601021504Z0700"
  470. res, err = time.Parse(formatStr, t)
  471. }
  472. if err != nil {
  473. return false
  474. }
  475. if serialized := res.Format(formatStr); serialized != t {
  476. return false
  477. }
  478. if res.Year() >= 2050 {
  479. // UTCTime interprets the low order digits 50-99 as 1950-99.
  480. // This only applies to its use in the X.509 profile.
  481. // See https://tools.ietf.org/html/rfc5280#section-4.1.2.5.1
  482. res = res.AddDate(-100, 0, 0)
  483. }
  484. *out = res
  485. return true
  486. }
  487. // ReadASN1BitString decodes an ASN.1 BIT STRING into out and advances.
  488. // It reports whether the read was successful.
  489. func (s *String) ReadASN1BitString(out *encoding_asn1.BitString) bool {
  490. var bytes String
  491. if !s.ReadASN1(&bytes, asn1.BIT_STRING) || len(bytes) == 0 ||
  492. len(bytes)*8/8 != len(bytes) {
  493. return false
  494. }
  495. paddingBits := bytes[0]
  496. bytes = bytes[1:]
  497. if paddingBits > 7 ||
  498. len(bytes) == 0 && paddingBits != 0 ||
  499. len(bytes) > 0 && bytes[len(bytes)-1]&(1<<paddingBits-1) != 0 {
  500. return false
  501. }
  502. out.BitLength = len(bytes)*8 - int(paddingBits)
  503. out.Bytes = bytes
  504. return true
  505. }
  506. // ReadASN1BitStringAsBytes decodes an ASN.1 BIT STRING into out and advances. It is
  507. // an error if the BIT STRING is not a whole number of bytes. It reports
  508. // whether the read was successful.
  509. func (s *String) ReadASN1BitStringAsBytes(out *[]byte) bool {
  510. var bytes String
  511. if !s.ReadASN1(&bytes, asn1.BIT_STRING) || len(bytes) == 0 {
  512. return false
  513. }
  514. paddingBits := bytes[0]
  515. if paddingBits != 0 {
  516. return false
  517. }
  518. *out = bytes[1:]
  519. return true
  520. }
  521. // ReadASN1Bytes reads the contents of a DER-encoded ASN.1 element (not including
  522. // tag and length bytes) into out, and advances. The element must match the
  523. // given tag. It reports whether the read was successful.
  524. func (s *String) ReadASN1Bytes(out *[]byte, tag asn1.Tag) bool {
  525. return s.ReadASN1((*String)(out), tag)
  526. }
  527. // ReadASN1 reads the contents of a DER-encoded ASN.1 element (not including
  528. // tag and length bytes) into out, and advances. The element must match the
  529. // given tag. It reports whether the read was successful.
  530. //
  531. // Tags greater than 30 are not supported (i.e. low-tag-number format only).
  532. func (s *String) ReadASN1(out *String, tag asn1.Tag) bool {
  533. var t asn1.Tag
  534. if !s.ReadAnyASN1(out, &t) || t != tag {
  535. return false
  536. }
  537. return true
  538. }
  539. // ReadASN1Element reads the contents of a DER-encoded ASN.1 element (including
  540. // tag and length bytes) into out, and advances. The element must match the
  541. // given tag. 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) ReadASN1Element(out *String, tag asn1.Tag) bool {
  545. var t asn1.Tag
  546. if !s.ReadAnyASN1Element(out, &t) || t != tag {
  547. return false
  548. }
  549. return true
  550. }
  551. // ReadAnyASN1 reads the contents of a DER-encoded ASN.1 element (not including
  552. // tag and length bytes) into out, sets outTag to its tag, and advances.
  553. // It reports whether the read was successful.
  554. //
  555. // Tags greater than 30 are not supported (i.e. low-tag-number format only).
  556. func (s *String) ReadAnyASN1(out *String, outTag *asn1.Tag) bool {
  557. return s.readASN1(out, outTag, true /* skip header */)
  558. }
  559. // ReadAnyASN1Element reads the contents of a DER-encoded ASN.1 element
  560. // (including tag and length bytes) into out, sets outTag to is tag, and
  561. // advances. It reports whether the read was successful.
  562. //
  563. // Tags greater than 30 are not supported (i.e. low-tag-number format only).
  564. func (s *String) ReadAnyASN1Element(out *String, outTag *asn1.Tag) bool {
  565. return s.readASN1(out, outTag, false /* include header */)
  566. }
  567. // PeekASN1Tag reports whether the next ASN.1 value on the string starts with
  568. // the given tag.
  569. func (s String) PeekASN1Tag(tag asn1.Tag) bool {
  570. if len(s) == 0 {
  571. return false
  572. }
  573. return asn1.Tag(s[0]) == tag
  574. }
  575. // SkipASN1 reads and discards an ASN.1 element with the given tag. It
  576. // reports whether the operation was successful.
  577. func (s *String) SkipASN1(tag asn1.Tag) bool {
  578. var unused String
  579. return s.ReadASN1(&unused, tag)
  580. }
  581. // ReadOptionalASN1 attempts to read the contents of a DER-encoded ASN.1
  582. // element (not including tag and length bytes) tagged with the given tag into
  583. // out. It stores whether an element with the tag was found in outPresent,
  584. // unless outPresent is nil. It reports whether the read was successful.
  585. func (s *String) ReadOptionalASN1(out *String, outPresent *bool, tag asn1.Tag) bool {
  586. present := s.PeekASN1Tag(tag)
  587. if outPresent != nil {
  588. *outPresent = present
  589. }
  590. if present && !s.ReadASN1(out, tag) {
  591. return false
  592. }
  593. return true
  594. }
  595. // SkipOptionalASN1 advances s over an ASN.1 element with the given tag, or
  596. // else leaves s unchanged. It reports whether the operation was successful.
  597. func (s *String) SkipOptionalASN1(tag asn1.Tag) bool {
  598. if !s.PeekASN1Tag(tag) {
  599. return true
  600. }
  601. var unused String
  602. return s.ReadASN1(&unused, tag)
  603. }
  604. // ReadOptionalASN1Integer attempts to read an optional ASN.1 INTEGER explicitly
  605. // tagged with tag into out and advances. If no element with a matching tag is
  606. // present, it writes defaultValue into out instead. Otherwise, it behaves like
  607. // ReadASN1Integer.
  608. func (s *String) ReadOptionalASN1Integer(out interface{}, tag asn1.Tag, defaultValue interface{}) bool {
  609. var present bool
  610. var i String
  611. if !s.ReadOptionalASN1(&i, &present, tag) {
  612. return false
  613. }
  614. if !present {
  615. switch out.(type) {
  616. case *int, *int8, *int16, *int32, *int64,
  617. *uint, *uint8, *uint16, *uint32, *uint64, *[]byte:
  618. reflect.ValueOf(out).Elem().Set(reflect.ValueOf(defaultValue))
  619. case *big.Int:
  620. if defaultValue, ok := defaultValue.(*big.Int); ok {
  621. out.(*big.Int).Set(defaultValue)
  622. } else {
  623. panic("out points to big.Int, but defaultValue does not")
  624. }
  625. default:
  626. panic("invalid integer type")
  627. }
  628. return true
  629. }
  630. if !i.ReadASN1Integer(out) || !i.Empty() {
  631. return false
  632. }
  633. return true
  634. }
  635. // ReadOptionalASN1OctetString attempts to read an optional ASN.1 OCTET STRING
  636. // explicitly tagged with tag into out and advances. If no element with a
  637. // matching tag is present, it sets "out" to nil instead. It reports
  638. // whether the read was successful.
  639. func (s *String) ReadOptionalASN1OctetString(out *[]byte, outPresent *bool, tag asn1.Tag) bool {
  640. var present bool
  641. var child String
  642. if !s.ReadOptionalASN1(&child, &present, tag) {
  643. return false
  644. }
  645. if outPresent != nil {
  646. *outPresent = present
  647. }
  648. if present {
  649. var oct String
  650. if !child.ReadASN1(&oct, asn1.OCTET_STRING) || !child.Empty() {
  651. return false
  652. }
  653. *out = oct
  654. } else {
  655. *out = nil
  656. }
  657. return true
  658. }
  659. // ReadOptionalASN1Boolean sets *out to the value of the next ASN.1 BOOLEAN or,
  660. // if the next bytes are not an ASN.1 BOOLEAN, to the value of defaultValue.
  661. // It reports whether the operation was successful.
  662. func (s *String) ReadOptionalASN1Boolean(out *bool, defaultValue bool) bool {
  663. var present bool
  664. var child String
  665. if !s.ReadOptionalASN1(&child, &present, asn1.BOOLEAN) {
  666. return false
  667. }
  668. if !present {
  669. *out = defaultValue
  670. return true
  671. }
  672. return s.ReadASN1Boolean(out)
  673. }
  674. func (s *String) readASN1(out *String, outTag *asn1.Tag, skipHeader bool) bool {
  675. if len(*s) < 2 {
  676. return false
  677. }
  678. tag, lenByte := (*s)[0], (*s)[1]
  679. if tag&0x1f == 0x1f {
  680. // ITU-T X.690 section 8.1.2
  681. //
  682. // An identifier octet with a tag part of 0x1f indicates a high-tag-number
  683. // form identifier with two or more octets. We only support tags less than
  684. // 31 (i.e. low-tag-number form, single octet identifier).
  685. return false
  686. }
  687. if outTag != nil {
  688. *outTag = asn1.Tag(tag)
  689. }
  690. // ITU-T X.690 section 8.1.3
  691. //
  692. // Bit 8 of the first length byte indicates whether the length is short- or
  693. // long-form.
  694. var length, headerLen uint32 // length includes headerLen
  695. if lenByte&0x80 == 0 {
  696. // Short-form length (section 8.1.3.4), encoded in bits 1-7.
  697. length = uint32(lenByte) + 2
  698. headerLen = 2
  699. } else {
  700. // Long-form length (section 8.1.3.5). Bits 1-7 encode the number of octets
  701. // used to encode the length.
  702. lenLen := lenByte & 0x7f
  703. var len32 uint32
  704. if lenLen == 0 || lenLen > 4 || len(*s) < int(2+lenLen) {
  705. return false
  706. }
  707. lenBytes := String((*s)[2 : 2+lenLen])
  708. if !lenBytes.readUnsigned(&len32, int(lenLen)) {
  709. return false
  710. }
  711. // ITU-T X.690 section 10.1 (DER length forms) requires encoding the length
  712. // with the minimum number of octets.
  713. if len32 < 128 {
  714. // Length should have used short-form encoding.
  715. return false
  716. }
  717. if len32>>((lenLen-1)*8) == 0 {
  718. // Leading octet is 0. Length should have been at least one byte shorter.
  719. return false
  720. }
  721. headerLen = 2 + uint32(lenLen)
  722. if headerLen+len32 < len32 {
  723. // Overflow.
  724. return false
  725. }
  726. length = headerLen + len32
  727. }
  728. if int(length) < 0 || !s.ReadBytes((*[]byte)(out), int(length)) {
  729. return false
  730. }
  731. if skipHeader && !out.Skip(int(headerLen)) {
  732. panic("cryptobyte: internal error")
  733. }
  734. return true
  735. }