asn1.go 16 KB

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