asn1.go 21 KB

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